fix: logins now refresh on plugins load

feat: Added tar archive support
fix: Downloaded games and emulator execute permission now updated
fix: Fixed rclone for linux
fix: on screen keyaboard only now shows up when using a gamepad or touch
This commit is contained in:
Simeon Radivoev 2026-04-21 23:21:50 +03:00
parent 6aacec2c0d
commit 7bd0ebdcca
Signed by: simeonradivoev
GPG key ID: C16C2132A7660C8E
39 changed files with 523 additions and 275 deletions

View file

@ -4,7 +4,7 @@ A Cross-Platform open source Retro gaming frontend designed for handheld and con
Focused on building a simple user experience and intuitive UI as a curated community driven experience.
> [!WARNING]
> This app is actively in development, it doesn't have most of its major features implemented yet.
> This app is actively in development, it is contantly chaning and improving.
> It will have an opinionated design and will be used as an experiment in discovering a good UX.
## Features
@ -13,6 +13,8 @@ Focused on building a simple user experience and intuitive UI as a curated commu
- **[ROMM](https://github.com/rommapp/romm)** - download, sync and update roms and platforms.
- **[Emulator JS](https://github.com/EmulatorJS/EmulatorJS)** - play your games with emulator js right within the app. Uses RetroArch cores.
- **[RClone](https://github.com/rclone/rclone)** - sync saves between devices or cloud.
- **[UMU](https://github.com/Open-Wine-Components/umu-launcher)** - UMU Launcher for playing windows games on linux without needing steam. (Only used for store games for now)
### Store
@ -32,6 +34,7 @@ Focused on building a simple user experience and intuitive UI as a curated commu
- **Automatic Emulator Discovery** - Using the configs of the excellent ES-DE to discover installed emulators and launch games.
- Easy fallback configuration with built in file browser.
- **Responsive Layout** - Optimized mainly for the steam deck with responsive layout support and dynamic switching of inputs.
- **Cloud/Device Save Sync** - For supported games and emulators.
## Screenshots

View file

@ -22,7 +22,7 @@ CREATE TABLE `__new_games` (
FOREIGN KEY (`platform_id`) REFERENCES `platforms`(`id`) ON UPDATE cascade ON DELETE no action
);
--> statement-breakpoint
INSERT INTO `__new_games`("id", "source_id", "source", "igdb_id", "name", "ra_id", "path_fs", "main_glob", "last_played", "created_at", "metadata", "slug", "platform_id", "cover", "type", "summary", "version", "version_source", "version_system") SELECT "id", "source_id", "source", "igdb_id", "name", "ra_id", "path_fs", "main_glob", "last_played", "created_at", "metadata", "slug", "platform_id", "cover", "type", "summary", "version", "version_source", "version_system" FROM `games`;--> statement-breakpoint
INSERT INTO `__new_games`("id", "source_id", "source", "igdb_id", "name", "ra_id", "path_fs", "main_glob", "last_played", "created_at", "metadata", "slug", "platform_id", "cover", "type", "summary", "version", "version_source", "version_system") SELECT "id", "source_id", "source", "igdb_id", "name", "ra_id", "path_fs", NULL, "last_played", "created_at", "metadata", "slug", "platform_id", "cover", "type", "summary", NULL, NULL, NULL FROM `games`;--> statement-breakpoint
DROP TABLE `games`;--> statement-breakpoint
ALTER TABLE `__new_games` RENAME TO `games`;--> statement-breakpoint
PRAGMA foreign_keys=ON;--> statement-breakpoint

View file

@ -72,6 +72,7 @@ export async function load ()
console.log("Config Path Located At: ", config.path);
console.log("Custom Emulator Paths Located At: ", customEmulators.path);
console.log("App Directory is ", process.env.APPDIR);
console.log("Cache Path is ", cachePath);
cachePath = path.join(os.tmpdir(), 'gameflow', 'cache.sqlite');
fileCookieStore = new FileCookieStore(path.join(path.dirname(config.path), 'cookies.json'));

View file

@ -46,8 +46,36 @@ export default new Elysia()
return status(res.status, res.statusText);
})
.get('/login/twitch', async () =>
.get('/login/twitch', checkLoginAndRefreshTwitch)
.post('/login/romm/qr', async () =>
{
if (taskQueue.hasActiveOfType(LoginJob))
{
return status("Conflict", "Login Already Active");
}
return taskQueue.enqueue(LoginJob.id, new LoginJob());
})
.get('/user/romm', async () =>
{
const data = await getCurrentUserApiUsersMeGet();
if (data.error) return status("Internal Server Error", data.response.statusText);
return data.data as UserSchema;
})
.post('/login/romm', async ({ body }) => tryLoginAndSave(body), { body: z.object({ host: z.url(), username: z.string(), password: z.string() }) })
.get('/login/romm', checkLoginAndRefreshRomm,
{ response: z.object({ hasLogin: z.boolean() }) })
.post('/logout/romm', async () =>
{
await secrets.delete({ service: 'gameflow', name: 'romm_access_token' });
await secrets.delete({ service: 'gameflow', name: 'romm_refresh_token' });
await secrets.delete({ service: 'gameflow', name: 'romm_expires_in' });
return status(200);
}, { response: z.any() });
export async function checkLoginAndRefreshTwitch ()
{
const access_token = await secrets.get({ service: 'gamflow_twitch', name: 'access_token' });
if (!access_token)
{
@ -106,25 +134,10 @@ export default new Elysia()
}
return status(400, res.statusText);
})
.post('/login/romm/qr', async () =>
{
if (taskQueue.hasActiveOfType(LoginJob))
{
return status("Conflict", "Login Already Active");
}
}
return taskQueue.enqueue(LoginJob.id, new LoginJob());
})
.get('/user/romm', async () =>
{
const data = await getCurrentUserApiUsersMeGet();
if (data.error) return status("Internal Server Error", data.response.statusText);
return data.data as UserSchema;
})
.post('/login/romm', async ({ body }) => tryLoginAndSave(body), { body: z.object({ host: z.url(), username: z.string(), password: z.string() }) })
.get('/login/romm', async () =>
{
export async function checkLoginAndRefreshRomm ()
{
const access_token = await secrets.get({ service: 'gameflow', name: 'romm_access_token' });
if (!access_token)
{
@ -163,17 +176,7 @@ export default new Elysia()
}
return status(refreshResponse.response.status, refreshResponse.response.statusText) as any;
},
{ response: z.object({ hasLogin: z.boolean() }) })
.post('/logout/romm', async () =>
{
await secrets.delete({ service: 'gameflow', name: 'romm_access_token' });
await secrets.delete({ service: 'gameflow', name: 'romm_refresh_token' });
await secrets.delete({ service: 'gameflow', name: 'romm_expires_in' });
return status(200);
}, { response: z.any() });
}
export async function tryLoginAndSave ({ host, username, password }: { host: string, username: string, password: string; })
{

View file

@ -2,6 +2,7 @@ import { eq } from "drizzle-orm";
import { cache } from "./app";
import cacheSchema from "@schema/cache";
import { GithubReleaseSchema } from "@/shared/constants";
import PQueue from "p-queue";
export const CACHE_KEYS = {
ROM_PLATFORMS: 'rom-platforms',
@ -9,6 +10,8 @@ export const CACHE_KEYS = {
STORE_GAME_MANIFEST: 'store-game-manifest'
} as const;
export const githubRequestQueue = new PQueue({ intervalCap: 10, interval: 1000 * 60 * 10, strict: true });
export async function getOrCached<T> (key: string, getter: () => Promise<T>, options?: { expireMs?: number; }): Promise<T>
{
const cached = await cache.query.item_cache.findFirst({ where: eq(cacheSchema.item_cache.key, key) });
@ -37,10 +40,10 @@ export async function getOrCached<T> (key: string, getter: () => Promise<T>, opt
export async function getOrCachedGithubRelease (path: string)
{
return getOrCached(`github-release-${path}`, async () =>
return getOrCached(`github-release-${path}`, async () => githubRequestQueue.add(async () =>
{
const response = await fetch(`https://api.github.com/repos/${path}/releases/latest`, { method: "GET" });
if (!response.ok) throw new Error(response.statusText);
return GithubReleaseSchema.parseAsync(await response.json());
});
}), { expireMs: 1000 * 60 * 60 });
}

View file

@ -124,6 +124,12 @@ export class GameHooks
platformSlug?: string;
};
}]>(["ctx"]);
postInstall = new AsyncSeriesHook<[ctx: {
source: string,
id: string;
files: string[];
info: DownloadInfo;
}]>(['ctx']);
fetchCollections = new AsyncSeriesHook<[ctx: { collections: FrontEndCollection[]; }]>(['ctx']);
fetchCollection = new AsyncSeriesBailHook<[ctx: { source: string, id: string; }], FrontEndCollection | undefined>(['ctx']);

View file

@ -11,6 +11,7 @@ import { ensureDir, move } from "fs-extra";
import { simulateProgress } from "@/bun/utils";
import { path7za } from "7zip-bin";
import { getEmulatorDownload, getEmulatorPath } from "../store/services/emulatorsService";
import { $ } from "bun";
type EmulatorDownloadStates = "download" | "extract";
@ -61,7 +62,7 @@ export class EmulatorDownloadJob implements IJob<z.infer<typeof EmulatorDownload
const destinationPaths = await downloader.start();
if (destinationPaths)
{
const isArchive = destinationPaths[0].endsWith('.7z') || destinationPaths[0].endsWith('.zip');
const isArchive = destinationPaths[0].endsWith('.7z') || destinationPaths[0].endsWith('.zip') || destinationPaths[0].endsWith('.tar');
const isAppImage = destinationPaths[0].endsWith(".AppImage");
if (!isArchive && !isAppImage)
@ -74,6 +75,14 @@ export class EmulatorDownloadJob implements IJob<z.infer<typeof EmulatorDownload
if (destinationPaths[0])
{
let destinationPath = destinationPaths[0];
if (destinationPath.endsWith('.tar'))
{
context.setProgress(0, "extract");
await ensureDir(emulatorsFolder);
await $`tar -xf ${destinationPath} -C ${emulatorsFolder}`;
await fs.rm(destinationPath, { recursive: true });
} else
{
await new Promise((resolve, reject) =>
{
const seven = Seven.extractFull(destinationPath, emulatorsFolder, { $bin: process.env.ZIP7_PATH ?? path7za, $progress: true, noRootDuplication: true });
@ -82,6 +91,7 @@ export class EmulatorDownloadJob implements IJob<z.infer<typeof EmulatorDownload
seven.on('end', () => resolve(true));
});
await fs.rm(destinationPath, { recursive: true });
}
// check if 1 root folder we need to get rid of
const contents = await fs.readdir(emulatorsFolder);
@ -106,15 +116,18 @@ export class EmulatorDownloadJob implements IJob<z.infer<typeof EmulatorDownload
}
}
await Bun.write(`${emulatorsFolder}.json`, JSON.stringify(info, null, 3));
const execs: EmulatorSourceEntryType[] = [];
await plugins.hooks.emulators.findEmulatorSource.promise({ emulator: this.emulator, sources: execs });
await plugins.hooks.emulators.emulatorPostInstall.promise({
emulator: this.emulator,
emulatorPackage: this.emulatorPackage,
path: emulatorsFolder,
path: execs.find(e => e.type === 'store')?.binPath ?? emulatorsFolder,
info,
update: this.isUpdate
});
await Bun.write(`${emulatorsFolder}.json`, JSON.stringify(info, null, 3));
}
}

View file

@ -59,6 +59,7 @@ export class InstallJob implements IJob<never, InstallJobStates>
if (!info) throw new Error(`Could not find downloader for source ${this.source}`);
const files = await checkFiles(info.files, !!info.extract_path);
const finalFiles: string[] = [];
if (this.config?.dryRun !== true)
{
@ -84,6 +85,7 @@ export class InstallJob implements IJob<never, InstallJobStates>
{
return;
}
if (info.extract_path && downloadedFiles)
{
let progress = 0;
@ -139,6 +141,7 @@ export class InstallJob implements IJob<never, InstallJobStates>
if (filePath.endsWith('.zip'))
{
cx.setProgress(0, "extract");
console.error(e);
console.warn("Could not extract", filePath, "with 7zip trying zip extractor");
await ensureDir(extractPath);
const zip = new StreamZip.async({ file: filePath });
@ -175,6 +178,12 @@ export class InstallJob implements IJob<never, InstallJobStates>
await move(tmpGameFolder, extractPath, { overwrite: true });
}
}
finalFiles.push(extractPath);
} else
{
finalFiles.push(...downloadedFiles);
}
}
@ -323,6 +332,7 @@ export class InstallJob implements IJob<never, InstallJobStates>
await simulateProgress(p => cx.setProgress(p, "download"), cx.abortSignal);
}
await plugins.hooks.games.postInstall.promise({ source: this.source, id: this.gameId, files: finalFiles, info });
events.emit('notification', { message: `${info.name}: Installed`, type: 'success', duration: 8000 });
}

View file

@ -5,9 +5,9 @@ import { db, events, plugins } from "../app";
import * as appSchema from "@schema/app";
import { eq } from "drizzle-orm";
import { spawn } from 'node:child_process';
import { watch } from "node:fs";
import fs from "node:fs/promises";
import { updateLocalLastPlayed } from "../games/services/statusService";
import { getErrorMessage } from "@/bun/utils";
export class LaunchGameJob implements IJob<z.infer<typeof LaunchGameJob.dataSchema>, string>
{
@ -42,6 +42,8 @@ export class LaunchGameJob implements IJob<z.infer<typeof LaunchGameJob.dataSche
const source = this.gameSource ?? this.gameId.source;
const id = this.gameSourceId ?? this.gameId.id;
await new Promise(async (resolve) =>
{
await plugins.hooks.games.postPlay.promise(
{
source,
@ -50,7 +52,14 @@ export class LaunchGameJob implements IJob<z.infer<typeof LaunchGameJob.dataSche
changedSaveFiles: Array.from(this.changedSaveFiles.values()),
validChangedSaveFiles: {},
gameInfo
}).catch(e => console.error(e));
}).catch(e =>
{
console.error(e);
events.emit('notification', { message: getErrorMessage(e), type: 'error' });
}).then(() => resolve(false));
const timeoutHandler = () => resolve(false);
setTimeout(timeoutHandler, 5000);
});
}
prePlay (setProgress: (progress: number, state: string) => void, gameInfo: { platformSlug?: string; })
@ -118,6 +127,31 @@ export class LaunchGameJob implements IJob<z.infer<typeof LaunchGameJob.dataSche
{
await this.prePlay(context.setProgress.bind(context), { platformSlug: gameInfo?.platformSlug }).catch(e => reject(e));
if (Array.isArray(this.validCommand.command))
{
const bunGame = Bun.spawn(this.validCommand.command, {
cwd: this.validCommand.startDir,
signal: context.abortSignal,
env: {
...process.env,
...this.validCommand.env
}
});
context.setProgress(0, "playing");
bunGame.exited.then(e =>
{
resolve(true);
}).catch(e =>
{
console.error(e);
reject(e);
});
game = bunGame;
} else
{
// ES-DE commands require shell execution. Some emulators fail otherwise.
const spawnGame = spawn(this.validCommand.command, {
shell: this.validCommand.shell ?? true,
@ -144,6 +178,8 @@ export class LaunchGameJob implements IJob<z.infer<typeof LaunchGameJob.dataSche
game = spawnGame;
}
}
else if (this.validCommand.metadata.emulatorBin)
{
this.saveSlots = commandArgs.savesPath ?? {};
@ -151,7 +187,6 @@ export class LaunchGameJob implements IJob<z.infer<typeof LaunchGameJob.dataSche
await this.prePlay(context.setProgress.bind(context), { platformSlug: gameInfo?.platformSlug });
// We have full control over launching integrated emulators better to use bun spawn
await fs.chmod(this.validCommand.metadata.emulatorBin, 0o755);
const bunGame = Bun.spawn([this.validCommand.metadata.emulatorBin, ...commandArgs.args], {
cwd: this.validCommand.startDir,
signal: context.abortSignal,
@ -212,7 +247,7 @@ export class LaunchGameJob implements IJob<z.infer<typeof LaunchGameJob.dataSche
} catch (e)
{
context.abort(e);
reject(e);
resolve(e);
}
});

View file

@ -175,7 +175,7 @@ export default class IgdbIntegration implements PluginType
const emulator = await emulatorsDb.query.emulators.findFirst({ where: eq(emulatorSchema.emulators.name, emulatorName) });
if (!emulator)
{
throw new Error(`Could not find emulator ${emulatorName}`);
return [];
}
return this.findExecs(emulatorName, emulator);
}

View file

@ -5,6 +5,7 @@
"description": "ES-DE Launch Configurations. Used as fallback",
"main": "./es-de.ts",
"icon": "https://impro.usercontent.one/appid/oneComWsb/domain/es-de.org/media/es-de.org/onewebmedia/ES-DE_logo.png",
"canDisable": false,
"category": "launchers",
"keywords": [
"integration",

View file

@ -22,7 +22,9 @@ const SettingsSchema = z.object({
verboseLog: z.boolean()
.default(false)
.describe("Show detailed log of operation for debugging")
.meta({ $comment: JSON.stringify({ category: "debug" }) })
.meta({ $comment: JSON.stringify({ category: "debug" }) }),
importSaves: z.boolean().default(true).describe("Import Saves From the Destination. This will override local saves"),
exportSaves: z.boolean().default(true).describe("Export saves to remove. This will sync current saves with remote")
});
type SettingsType = z.infer<typeof SettingsSchema>;
@ -75,8 +77,8 @@ export default class RcloneIntegration implements PluginType<SettingsType>
await ensureDir(toolsPath);
const binaryMap: Record<string, string> = {
win32: '**/rclone.exe',
linux: '**/rclone',
darwin: '**/rclone'
linux: 'rclone-*/rclone',
darwin: 'rclone-*/rclone'
};
const existingRclones = await Array.fromAsync(fs.glob(binaryMap[process.platform], { cwd: toolsPath }));
if (existingRclones[0])
@ -102,7 +104,7 @@ export default class RcloneIntegration implements PluginType<SettingsType>
await ensureDir(toolsPath);
await pipeline(Readable.fromWeb(rcCloseZip.body as any), unzip.Extract({ path: toolsPath }));
const dests = await Array.fromAsync(fs.glob('**/rclone.exe', { cwd: toolsPath }));
const dests = await Array.fromAsync(fs.glob(binaryMap[process.platform], { cwd: toolsPath }));
if (dests[0])
{
this.rclonePath = path.join(toolsPath, dests[0]);
@ -218,7 +220,7 @@ export default class RcloneIntegration implements PluginType<SettingsType>
ctx.hooks.games.prePlay.tapPromise({ name: desc.name, stage: 10 }, async ({ source, id, setProgress, saveFolderSlots }) =>
{
if (source !== 'store' || !this.rclonePath || !saveFolderSlots) return;
if (source !== 'store' || !this.rclonePath || !saveFolderSlots || !ctx.config.get('importSaves')) return;
for await (const [slot, { cwd }] of Object.entries(saveFolderSlots))
{
@ -250,8 +252,7 @@ export default class RcloneIntegration implements PluginType<SettingsType>
UseJSONLog: true,
LogLevel: "DEBUG",
HumanReadable: true,
Progress: true,
DryRun: true
Progress: true
}
});
console.log(data);
@ -261,7 +262,7 @@ export default class RcloneIntegration implements PluginType<SettingsType>
ctx.hooks.games.postPlay.tapPromise({ name: desc.name, stage: 10 }, async ({ source, id, validChangedSaveFiles }) =>
{
if (source !== 'store' || !this.rclonePath) return;
if (source !== 'store' || !this.rclonePath || !ctx.config.get('exportSaves')) return;
console.log("Save Files", Object.values(validChangedSaveFiles).flatMap(c => Array.isArray(c.subPath) ? c.subPath : [c.subPath]).join(","));
await Promise.all(Object.entries(validChangedSaveFiles).map(async ([slot, change]) =>

View file

@ -3,6 +3,7 @@ import desc from './package.json';
import secrets from "@/bun/api/secrets";
import PQueue from 'p-queue';
import * as igdb from '@phalcode/ts-igdb-client';
import { checkLoginAndRefreshTwitch } from "@/bun/api/auth";
export default class IgdbIntegration implements PluginType
{
@ -39,6 +40,8 @@ export default class IgdbIntegration implements PluginType
async load (ctx: PluginLoadingContextType)
{
await checkLoginAndRefreshTwitch();
ctx.hooks.games.gameLookup.tapPromise(desc.name, async ({ source, id }) =>
{
if (!process.env.TWITCH_CLIENT_ID) return;

View file

@ -13,6 +13,7 @@ import { getAuthToken } from "@/clients/romm/core/auth.gen";
import { client } from "@/clients/romm/client.gen";
import { validateGameSource } from "@/bun/api/games/services/statusService";
import z from "zod";
import { checkLoginAndRefreshRomm } from "@/bun/api/auth";
const SettingsSchema = z.object({
savesSync: z.boolean().default(false).describe("Experimental save sync support")
@ -143,6 +144,8 @@ export default class RommIntegration implements PluginType<SettingsType>
async load (ctx: PluginLoadingContextType<SettingsType>)
{
this.isSteamDeck = isSteamDeckGameMode();
ctx.setProgress(0, "Logging Into Romm");
await checkLoginAndRefreshRomm();
await this.updateClient();
ctx.hooks.games.fetchGames.tapPromise(desc.name, async ({ query, games }) =>
@ -150,7 +153,6 @@ export default class RommIntegration implements PluginType<SettingsType>
if (!await this.checkRemote()) return;
if (((!query.platform_source || query.platform_source === 'romm') || !!query.collection_id) && (!query.source || query.source === 'romm'))
{
const rommGames = await getRomsApiRomsGet({
query: {
platform_ids: query.platform_id ? [query.platform_id] : undefined,

View file

@ -4,7 +4,7 @@ import os from 'node:os';
import path from "node:path";
import * as appSchema from '@schema/app';
import * as emulatorSchema from '@schema/emulators';
import { db, emulatorsDb, plugins } from "@/bun/api/app";
import { config, db, emulatorsDb, plugins } from "@/bun/api/app";
import { and, eq } from "drizzle-orm";
import { getOrCached } from "@/bun/api/cache";
import { Glob } from "bun";
@ -319,3 +319,46 @@ export async function getExistingStoreEmulatorDownload (emulator: EmulatorPackag
// this should only happen if download info is missing maybe manually deleted or wasn't saved.
return undefined;
}
export async function buildLaunchCommand (ctx: { gamePath: string; systemSlug: string; mainGlob?: string | null; }): Promise<CommandEntry | undefined>
{
if (ctx.systemSlug !== 'win' && ctx.systemSlug !== 'linux' && ctx.systemSlug !== 'mac') return;
const downloadPath = config.get('downloadPath');
const gamePathAbsolute = path.join(downloadPath, ctx.gamePath);
if (!(await fs.exists(gamePathAbsolute))) return;
const gamePathStat = await fs.stat(gamePathAbsolute);
if (gamePathStat.isDirectory())
{
let mainGlob = ctx.mainGlob;
if (!mainGlob && ctx.systemSlug === 'win') mainGlob = '**/*.exe';
if (!mainGlob) return;
const fileGlob = new Glob(mainGlob);
for await (const file of fileGlob.scan({ cwd: path.join(downloadPath, ctx.gamePath) }))
{
return {
startDir: path.join(downloadPath, ctx.gamePath, path.dirname(file)),
command: [`./${path.basename(file)}`],
id: `store-${process.platform}`,
shell: false,
valid: true,
metadata: {
romPath: path.join(downloadPath, ctx.gamePath, file)
}
};
}
} else
{
return {
startDir: path.join(downloadPath, path.dirname(ctx.gamePath)),
command: [`./${path.basename(ctx.gamePath)}`],
id: `store-${process.platform}`,
valid: true,
shell: false,
metadata: {
romPath: path.join(downloadPath, ctx.gamePath),
}
};
}
}

View file

@ -10,11 +10,24 @@ import { config, emulatorsDb, taskQueue } from "@/bun/api/app";
import fs from "node:fs/promises";
import { getSourceGameDetailed } from "@/bun/api/games/services/utils";
import UpdateStoreJob from "@/bun/api/jobs/update-store";
import { getEmulatorDownload } from "@/bun/api/store/services/emulatorsService";
import { buildFilters, buildSaves, convertStoreEmulatorToFrontend, convertStoreToFrontend, convertStoreToFrontendDetailed, getExistingStoreEmulatorDownload, getShuffledStoreGames, getStoreGame, getValidDownloads } from "./services";
import { getEmulatorDownload, getEmulatorPath } from "@/bun/api/store/services/emulatorsService";
import { buildFilters, buildLaunchCommand, buildSaves, convertStoreEmulatorToFrontend, convertStoreToFrontend, convertStoreToFrontendDetailed, getExistingStoreEmulatorDownload, getShuffledStoreGames, getStoreGame, getValidDownloads } from "./services";
import { path7za } from "7zip-bin";
export default class RommIntegration implements PluginType
{
eventsNames = [{ id: 'updateStore', title: "Update Store", description: "Update the Store Manifest", action: "Update" }];
async onEvent (e: string)
{
switch (e)
{
case 'updateStore':
await taskQueue.enqueue(UpdateStoreJob.id, new UpdateStoreJob());
return { reload: true };
}
}
async setup (ctx: PluginLoadingContextType)
{
console.log("Store Directory is ", getStoreFolder());
@ -126,52 +139,52 @@ export default class RommIntegration implements PluginType
saves?.forEach(([key, val]) => validChangedSaveFiles[key] = val);
});
ctx.hooks.emulators.findEmulatorSource.tapPromise(desc.name, async ({ emulator, sources }) =>
{
const emulatorPackage = await getStoreEmulatorPackage(emulator);
if (!emulatorPackage) return undefined;
const storeDownloadInfo = await getExistingStoreEmulatorDownload(emulatorPackage);
if (!storeDownloadInfo) return;
const emulatorPath = getEmulatorPath(emulator);
if (!await fs.exists(emulatorPath)) return;
const validDownload = emulatorPackage.downloads?.[`${process.platform}:${process.arch}`].find(d => d.type === storeDownloadInfo?.type);
if (!validDownload || !validDownload.bin) return;
const glob = new Glob(validDownload.bin);
const files = await Array.fromAsync(glob.scan({ cwd: emulatorPath }));
if (files.length > 0)
{
sources.push({ binPath: path.join(emulatorPath, files[0]), exists: true, rootPath: emulatorPath, type: 'store' });
}
});
ctx.hooks.emulators.emulatorPostInstall.tapPromise({ name: desc.name, emulator: 'UMU' }, async ({ path: emulatorPath }) =>
{
const pathStat = await fs.stat(emulatorPath);
if (pathStat.isFile())
{
await fs.chmod(emulatorPath, 0o755);
}
});
ctx.hooks.games.postInstall.tapPromise(desc.name, async ({ source, id, files, info }) =>
{
if (source !== 'store') return;
if (files.length === 1)
{
const command = await buildLaunchCommand({ gamePath: files[0], systemSlug: info.system_slug, mainGlob: info.main_glob });
if (command && command.metadata.romPath)
{
await fs.chmod(command.metadata.romPath, 0o755);
}
}
});
ctx.hooks.games.buildLaunchCommands.tapPromise({ name: desc.name, before: 'com.simeonradivoev.gameflow.es' }, async ({ gamePath, source, sourceId, systemSlug, mainGlob }) =>
{
if (source !== 'store' || !gamePath) return;
const downloadPath = config.get('downloadPath');
const gamePathAbsolute = path.join(downloadPath, gamePath);
if (!(await fs.exists(gamePathAbsolute))) return;
const gamePathStat = await fs.stat(gamePathAbsolute);
if (gamePathStat.isDirectory())
{
if (!mainGlob && systemSlug !== 'win') return;
const fileGlob = new Glob(mainGlob ?? '**/*.exe');
for await (const file of fileGlob.scan({ cwd: path.join(downloadPath, gamePath) }))
{
return [{
startDir: path.join(downloadPath, gamePath, dirname(file)),
command: `./${basename(file)}`,
id: `store-${process.platform}`,
shell: false,
valid: true,
env: {
XDG_DATA_HOME: path.join(config.get('downloadPath'), 'save', source, sourceId ?? '')
},
metadata: {
romPath: path.join(downloadPath, gamePath, file)
}
}];
}
} else
{
return [{
startDir: path.join(downloadPath, dirname(gamePath)),
command: `./${basename(gamePath)}`,
env: {
XDG_DATA_HOME: path.join(config.get('downloadPath'), 'save', source, sourceId ?? '')
},
id: `store-${process.platform}`,
valid: true,
shell: false,
metadata: {
romPath: path.join(downloadPath, gamePath)
}
}];
}
const command = await buildLaunchCommand({ gamePath, systemSlug, mainGlob });
if (!command) return;
return [command];
});
ctx.hooks.games.fetchFilters.tapPromise(desc.name, async ({ filters, source }) =>

View file

@ -19,7 +19,7 @@ export default new Elysia({ prefix: '/plugins' })
canDisable: p.description.canDisable ?? true,
icon: p.description.icon,
category: p.description.category,
hasSettings: !!p.config
hasSettings: !!p.config || !!p.plugin.eventsNames
};
return plugin;
});

View file

@ -1,6 +1,6 @@
import { EmulatorPackageSchema, EmulatorPackageType, GithubManifestSchema, StoreGameSchema } from "@/shared/constants";
import { CACHE_KEYS, getOrCached } from "../../cache";
import { and, eq } from "drizzle-orm";
import { and, eq, or } from "drizzle-orm";
import { config, emulatorsDb } from '../../app';
import path from "node:path";
import fs from 'node:fs/promises';
@ -46,10 +46,10 @@ export async function buildStoreFrontendEmulatorSystems (emulator: EmulatorPacka
const systems = await Promise.all(emulator.systems.map(async system =>
{
const rommSystem = await emulatorsDb.query.systemMappings.findFirst({
where: and(eq(emulatorSchema.systemMappings.source, 'romm'), eq(emulatorSchema.systemMappings.system, system))
where: or(and(eq(emulatorSchema.systemMappings.source, 'romm'), eq(emulatorSchema.systemMappings.system, system)), and(eq(emulatorSchema.systemMappings.source, 'romm'), eq(emulatorSchema.systemMappings.sourceSlug, system)))
});
const esSystem = await emulatorsDb.query.systems.findFirst({ where: eq(emulatorSchema.emulators.name, system), columns: { fullname: true } });
const esSystem = await emulatorsDb.query.systems.findFirst({ where: or(eq(emulatorSchema.emulators.name, system), eq(emulatorSchema.emulators.name, rommSystem?.system ?? '')), columns: { fullname: true } });
let icon: string = `/api/romm/image/romm/assets/platforms/${rommSystem?.sourceSlug ?? system}.svg`;

View file

@ -12,7 +12,7 @@ import { CACHE_KEYS, getOrCached } from "../cache";
import { getStoreFolder } from "./services/gamesService";
import { EmulatorDownloadJob } from "../jobs/emulator-download-job";
import { BiosDownloadJob } from "../jobs/bios-download-job";
import { findEmulatorPluginIntegration } from "./services/emulatorsService";
import { findEmulatorPluginIntegration, getEmulatorPath } from "./services/emulatorsService";
export const store = new Elysia({ prefix: '/api/store' })
.get('/emulators', async ({ query }) =>
@ -148,13 +148,22 @@ export const store = new Elysia({ prefix: '/api/store' })
})
.delete('/emulator/:id', async ({ params: { id } }) =>
{
const storeEmulatorFolder = path.join(config.get('downloadPath'), 'emulators', id);
const storeEmulatorFolder = getEmulatorPath(id);
const existingPackagePath = `${storeEmulatorFolder}.json`;
let hadDelete = false;
if (await fs.exists(existingPackagePath))
{
await fs.rm(existingPackagePath);
hadDelete = true;
}
if (await fs.exists(storeEmulatorFolder))
{
fs.rm(storeEmulatorFolder, { recursive: true });
return status("OK");
hadDelete = true;
}
return status("Not Found");
return hadDelete ? status("OK") : status("Not Found");
})
.post('/download/bios/:id', async ({ params: { id } }) =>
{

View file

@ -15,9 +15,12 @@ import { getStoreFolder } from "./store/services/gamesService";
import ReloadPluginsJob from "./jobs/reload-plugins-job";
import { semver } from "bun";
import packageDef from '~/package.json';
import { getOrCached, githubRequestQueue } from "./cache";
async function checkUpdate ()
{
return getOrCached('check-for-update', async () => githubRequestQueue.add(async () =>
{
const latest = await fetch('https://api.github.com/repos/simeonradivoev/gameflow-deck/releases/latest');
if (latest.ok)
{
@ -27,6 +30,7 @@ async function checkUpdate ()
}
return 0;
}), { expireMs: 1000 * 60 * 60 });
}
export const system = new Elysia({ prefix: '/api/system' })

View file

@ -36,7 +36,10 @@ export const PluginSchema = z.object({
description: z.string().optional(),
action: z.string()
}).array().optional(),
onEvent: z.function().input([z.string()]).output(z.any()).optional()
onEvent: z.function().input([z.string()]).output(z.object({
openTab: z.string().optional(),
reload: z.boolean().optional()
}).or(z.record(z.string(), z.any()))).optional()
});
export type PluginType<T extends Record<string, any> = Record<string, any>> = Omit<z.infer<typeof PluginSchema>, "load" | 'settingsMigrations'> & {
@ -55,6 +58,6 @@ export const ActiveGameSchema = z.object({
source: z.string().optional(),
sourceId: z.string().optional(),
name: z.string(),
command: z.object({ command: z.string(), startDir: z.string().optional() })
command: z.object({ command: z.string().or(z.string().array()), startDir: z.string().optional() })
});
export type ActiveGameType = z.infer<typeof ActiveGameSchema>;

View file

@ -63,7 +63,7 @@ export function CardList (data: {
onSelectGame?: (id: string) => void;
focus?: string;
className?: string;
finalElement?: JSX.Element;
finalElement?: JSX.Element | JSX.Element[];
saveChildFocus?: 'session' | 'local';
} & FocusParams)
{

View file

@ -1,7 +1,7 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { ContextList, DialogEntry } from "./ContextDialog";
import { systemApi } from "../scripts/clientApi";
import { useContext, useRef, useState } from "react";
import { FocusEventHandler, useContext, useRef, useState } from "react";
import path from "pathe";
import { Check, File, Folder, FolderInput, FolderOutput, FolderPlus, HardDrive, Usb, X } from "lucide-react";
import { FocusContext, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
@ -15,6 +15,7 @@ import toast from "react-hot-toast";
import { FilePickerContext } from "../scripts/contexts";
import useActiveControl from "../scripts/gamepads";
import { createFolderMutation, drivesQuery, filesQuery } from "@queries/system";
import { showKeyboardHandler } from "../scripts/utils";
function List (data: {
id: string,
@ -87,15 +88,16 @@ function List (data: {
function NewFolderInput (data: { id: string, name: string | undefined, setName: (name: string) => void; className?: string; })
{
const inputRef = useRef<HTMLInputElement>(null);
const { control } = useActiveControl();
const { ref, focused, focusSelf } = useFocusable({
focusKey: data.id,
onEnterPress: () => inputRef.current?.focus(),
onBlur: () => inputRef.current?.blur(),
});
const handleFocus = () =>
const handleFocus: FocusEventHandler<HTMLInputElement> = (e) =>
{
focusSelf();
systemApi.api.system.show_keyboard.post();
showKeyboardHandler(control as any, e.target);
};
return <div className={data.className} ref={ref}>
<input ref={inputRef}

View file

@ -17,7 +17,8 @@ export interface GameListParams extends FocusParams
onGameSelect?: (id: FrontEndId, source: string | null, sourceId: string | null) => void;
focus?: string;
className?: string;
finalElement?: JSX.Element;
finalElement?: JSX.Element | JSX.Element[];
emptyElement?: JSX.Element | JSX.Element[];
saveChildFocus?: "session" | "local";
}
@ -52,6 +53,25 @@ export function GameList (data: GameListParams)
navigator({ to: '/game/$source/$id', params: { id: String(g.source_id ?? g.id.id), source: g.source ?? g.id.source } });
};
const finalElement: JSX.Element[] = [];
if (!games.isFetching && !!games.data && games.data.games.length <= 0)
{
if (Array.isArray(data.emptyElement))
{
finalElement.push(...data.emptyElement);
} else if (data.emptyElement)
{
finalElement.push(data.emptyElement);
}
}
if (Array.isArray(data.finalElement))
{
finalElement.push(...data.finalElement);
} else if (data.finalElement)
{
finalElement.push(data.finalElement);
}
return (
<>
<CardList
@ -60,7 +80,7 @@ export function GameList (data: GameListParams)
grid={data.grid}
className={data.className}
onFocus={data.onFocus}
finalElement={data.finalElement}
finalElement={finalElement}
saveChildFocus={data.saveChildFocus}
focus={data.focus}
games={games.data?.games

View file

@ -153,7 +153,7 @@ function WiFiStatus ()
return systemContext && systemContext.wifiConnections.length > 0 ? <div>
{systemContext.wifiConnections.map(w =>
{
const className = "w-6 h-6";
const className = "w-10 h-10";
let icon = <Wifi className={className} />;
if (w.signalLevel >= -60)
icon = <Wifi className={className} />;
@ -164,7 +164,7 @@ function WiFiStatus ()
else if (w.signalLevel >= -90)
icon = <WifiZero className={className} />;
return <div className="tooltip" data-tip={w.signalLevel}>
return <div className="tooltip tooltip-bottom" data-tip={w.signalLevel}>
{icon}
</div>;
})}

View file

@ -1,10 +1,13 @@
import { FocusContext, useFocusable } from "@noriginmedia/norigin-spatial-navigation";
import { Ref, RefObject, useEffect, useRef, useState } from "react";
import { FocusEventHandler, Ref, RefObject, useEffect, useRef, useState } from "react";
import { GamePadButtonCode, useShortcuts } from "../scripts/shortcuts";
import { oneShot } from "../scripts/audio/audio";
import { Search } from "lucide-react";
import { RoundButton } from "./RoundButton";
import { useEventListener } from "usehooks-ts";
import { systemApi } from "../scripts/clientApi";
import { showKeyboardHandler } from "../scripts/utils";
import useActiveControl from "../scripts/gamepads";
function SearchInput (data: {
id: string;
@ -16,6 +19,7 @@ function SearchInput (data: {
onSubmit: (search: string | undefined) => void;
} & FocusParams)
{
const { control } = useActiveControl();
const { ref, focusKey } = useFocusable({
onBlur: () => inputRef.current?.blur(),
onFocus: (l, p, d) =>
@ -59,6 +63,8 @@ function SearchInput (data: {
data.onSubmit?.(undefined);
}, inputRef as any);
const handlInputFocus: FocusEventHandler<HTMLInputElement> = e => showKeyboardHandler(control as any, e.target);
return <label ref={ref} onFocus={data.onInputFocus} className='input rounded-full input-lg w-full max-w-xs has-focus:bg-base-300 ring-primary focused:ring-7 has-focus:ring-7 has-focus:ring-base-content'>
<Search />
<input
@ -68,6 +74,7 @@ function SearchInput (data: {
setLocalSearch(data.search);
}}
autoFocus={data.compact}
onFocus={handlInputFocus}
ref={inputRef}
value={localSearch ?? ""}
onChange={v => setLocalSearch(v.target.value)}

View file

@ -2,7 +2,7 @@ import { setFocus, useFocusable } from "@noriginmedia/norigin-spatial-navigation
import { FOCUS_KEYS } from "../scripts/types";
import { useIntersectionObserver } from "usehooks-ts";
export default function LoadMoreButton (data: { isFetching: boolean; lastId?: FrontEndId; } & FocusParams & InteractParams)
export default function LoadMoreButton (data: { isFetching: boolean; hidden?: boolean, lastId?: FrontEndId; } & FocusParams & InteractParams)
{
const handleAction = (event?: Event) =>
{
@ -12,7 +12,7 @@ export default function LoadMoreButton (data: { isFetching: boolean; lastId?: Fr
};
const { ref, focusKey, focused } = useFocusable({
focusable: !data.isFetching,
focusable: !data.isFetching && data.hidden !== true,
focusKey: 'load-more-btn',
onFocus: (_l, _p, details) => data.onFocus?.(focusKey, ref.current, details),
onEnterPress: handleAction
@ -34,5 +34,5 @@ export default function LoadMoreButton (data: { isFetching: boolean; lastId?: Fr
{
ref.current = r;
intersct(r);
}} className='flex bg-base-100 game-card focusable focusable-accent focusable-hover text-2xl justify-center items-center cursor-pointer' onClick={e => handleAction(e.nativeEvent)} id='load-more-btn'>{data.isFetching ? <span className="loading loading-spinner loading-xl"></span> : "Load More"}</div>;
}} className='flex data-[hidden=true]:invisible bg-base-100 game-card focusable focusable-accent focusable-hover text-2xl justify-center items-center cursor-pointer' data-hidden={data.hidden} onClick={e => handleAction(e.nativeEvent)} id='load-more-btn'>{data.isFetching ? <span className="loading loading-spinner loading-xl"></span> : "Load More"}</div>;
}

View file

@ -6,6 +6,8 @@ import { systemApi } from "../../scripts/clientApi";
import { CheckIcon, X } from "lucide-react";
import { oneShot } from "@/mainview/scripts/audio/audio";
import { GamePadButtonCode, Shortcut, useShortcuts } from "@/mainview/scripts/shortcuts";
import { showKeyboardHandler } from "@/mainview/scripts/utils";
import useActiveControl from "@/mainview/scripts/gamepads";
export function OptionInput (data: {
name: string;
@ -35,6 +37,7 @@ export function OptionInput (data: {
}
oneShot('click');
};
const { control } = useActiveControl();
const [inputFocused, setInputFocused] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const { ref, focusKey } = useFocusable({
@ -99,20 +102,11 @@ export function OptionInput (data: {
return shortcuts;
}, [inputFocused, data.type]);
const handleInputFocus = () =>
const handleInputFocus: FocusEventHandler<HTMLInputElement> = (e) =>
{
option.focus();
setInputFocused(true);
if (inputRef.current)
{
var rect = inputRef.current?.getBoundingClientRect();
systemApi.api.system.show_keyboard.post({
XPosition: rect.x,
YPosition: rect.y,
Width: rect.width,
Height: rect.height
});
}
showKeyboardHandler(control as any, e.target);
};
const handleInputBlur = (e: any) =>

View file

@ -10,6 +10,9 @@ import
OctagonAlert,
Maximize,
Store,
LayoutGrid,
PlusCircle,
Plus,
} from "lucide-react";
import
{
@ -39,7 +42,7 @@ import { GamePadButtonCode, useShortcutContext, useShortcuts } from "../scripts/
import z from "zod";
import CollectionList from "../components/CollectionList";
import { zodValidator } from '@tanstack/zod-adapter';
import { mobileCheck, useDragScroll } from "../scripts/utils";
import { mobileCheck, scrollIntoNearestParent, scrollIntoViewHandler, useDragScroll } from "../scripts/utils";
import { AnimatedBackgroundContext } from "../scripts/contexts";
import Carousel from "../components/Carousel";
import { closeMutation } from "@queries/system";
@ -48,6 +51,7 @@ import { oneShot } from "../scripts/audio/audio";
import { FloatingShortcuts } from "../components/Shortcuts";
import SelectMenu from "../components/SelectMenu";
import HeaderSearchField from "../components/HeaderSearchField";
import CardElement from "../components/CardElement";
export const Route = createFileRoute("/")({
component: ConsoleHomeUI,
@ -91,6 +95,35 @@ function HomeListError (data: { focused: boolean; })
</div></div>;
}
function Preview (data: { index: number; children?: any; })
{
const isMobile = mobileCheck();
return <div
className="flex p-6 bg-base-100 justify-center items-center aspect-3/4"
style={{
background: `linear-gradient(
color-mix(in srgb, var(--color-base-content) 60%, transparent),
color-mix(in srgb, var(--color-base-300) 60%, transparent)
), url(https://picsum.photos/id/${10 + data.index}/100/100.webp?blur=10) center / cover`,
backgroundBlendMode: isMobile ? undefined : "screen",
boxShadow: isMobile ? undefined : 'inset 0 0 32px rgba(0,0,0,0.6)'
}}
>
{data.children}
</div>;
}
function GetStoreGamesCard ()
{
const router = useRouter();
const handleNavigate = () =>
{
router.navigate({ to: '/store/tab/games' });
};
return <CardElement onFocus={scrollIntoViewHandler({ behavior: "smooth", inline: "center" })} badges={[<Search className="size-8" />]} onAction={handleNavigate} title="Gameflow Store" subtitle="Get Free Games" preview={<Preview index={43} ><Store className="not-mobile:drop-shadow-md in-focus:animate-rotate size-32" /></Preview>} focusKey='store-games-btn' index={0} id="store-games-btn" />;
}
function ShowAllGamesCard ()
{
const router = useRouter();
@ -98,8 +131,7 @@ function ShowAllGamesCard ()
{
router.navigate({ to: '/games' });
};
const { ref } = useFocusable({ focusKey: 'all-games-btn', onEnterPress: handleNavigate });
return <div ref={ref} onClick={handleNavigate} className="flex focusable focusable-primary justify-center items-center bg-base-300/80 rounded-3xl font-semibold w-(--game-card-width) h-(--game-card-height) focusable-hover cursor-pointer">All Games</div>;
return <CardElement onFocus={scrollIntoViewHandler({ behavior: "smooth", inline: "center" })} onAction={handleNavigate} title="All Games" preview={<Preview index={17} ><LayoutGrid className="not-mobile:drop-shadow-md in-focus:animate-rotate size-32" /></Preview>} focusKey='all-games-btn' index={0} id="all-games-btn" />;
}
function HomeList (data: {
@ -165,7 +197,8 @@ function HomeList (data: {
id="games-list"
setBackground={bg.setBackground}
filters={{ limit: 12, orderBy: 'activity' }}
finalElement={<ShowAllGamesCard />}
finalElement={[<GetStoreGamesCard />, <ShowAllGamesCard />]}
emptyElement={[]}
/>
<AutoFocus parentKey={focusKey} focus={focusSelf} delay={10} />
</>;

View file

@ -10,7 +10,8 @@ import { useRef } from 'react';
export const Route = createFileRoute('/launcher/$source/$id')({
component: RouteComponent,
staticData: {
enterSound: 'launch'
enterSound: 'launch',
missNavSound: false
},
});

View file

@ -24,7 +24,7 @@ import { useJobStatus } from "@/mainview/scripts/utils";
import { useInterval } from "usehooks-ts";
import { TwitchIcon } from "@/mainview/scripts/brandIcons";
import { twitchLoginMutation, twitchLoginVerificationQuery, twitchLogoutMutation } from "@queries/settings";
import { rommGetOptionsQuery, rommLoggedInQuery, rommHostnameQuery, rommLoginMutation, rommLogoutMutation, rommQrLoginMutation, rommUsernameQuery, rommUserQuery } from "@queries/romm";
import { rommGetOptionsQuery, rommLoggedInQuery, rommHostnameQuery, rommLoginMutation, rommLogoutMutation, rommQrLoginMutation, rommUsernameQuery, rommUserQuery, invalidateLogin } from "@queries/romm";
import { systemApi } from "@/mainview/scripts/clientApi";
export const Route = createFileRoute("/settings/accounts")({
@ -59,10 +59,7 @@ function TwitchLogin ()
{
const loginStatus = useQuery(twitchLoginVerificationQuery);
const loginMutation = useMutation({
...twitchLoginMutation,
onSuccess: () => loginStatus.refetch()
});
const loginMutation = useMutation(twitchLoginMutation);
const logoutMutation = useMutation({ ...twitchLogoutMutation, onSuccess: () => loginStatus.refetch() });
@ -100,8 +97,8 @@ function LoginControls (data: {})
...rommLogoutMutation,
onSuccess: async (d, v, r, c) =>
{
user.refetch();
await c.client.invalidateQueries({ queryKey: ["romm", "auth"] });
await user.refetch();
await invalidateLogin(c.client);
await router.navigate({ replace: true });
}
});

View file

@ -42,7 +42,7 @@ function PluginAction (data: { id: string, title: string | undefined, descriptio
<div>{data.title ?? data.id}</div>
<div className='text-sm text-base-content/40 text-wrap'>{data.description}</div>
</div>}>
<Button id={`${data.id}-btn`} onAction={e => action.mutate()} >{data.action}</Button>
<Button id={`${data.id}-btn`} onAction={e => action.mutate()} >{action.isPending && <span className="loading loading-spinner loading-lg"></span>}{data.action}</Button>
</OptionSpace>;
}

View file

@ -71,6 +71,7 @@ function RouteComponent ()
</div>
<div className="pl-12">
<CardList grid finalElement={<LoadMoreButton
hidden
lastId={data?.pages.at(-1)?.data.at(-1)?.id}
onFocus={handleFocus}
isFetching={isFetchingNextPage || isFetching}

View file

@ -80,11 +80,11 @@ function Main (data: { games?: FrontEndGameTypeDetailed[]; })
<div className='flex sm:portrait:flex-wrap sm:portrait:grow gap-4 max-h-full justify-center'>
<div className='relative rounded-3xl max-w-xs h-48 overflow-hidden shadow-lg'>
<div className='flex absolute bottom-4 left-4 size-8 bg-base-content text-base-100 rounded-full items-center justify-center shadow-lg '><HardDrive /></div>
{!!data.games && <img className='object-cover w-full h-full ' src={`${RPC_URL(__HOST__)}${data.games[selectedGame].path_covers[0]}`} />}
{!!data.games && <img className='object-cover w-full h-full' src={`${RPC_URL(__HOST__)}${data.games[selectedGame].path_covers[0]}`} />}
</div>
<div className='flex flex-col gap-2 py-3 max-w-md'>
<h1 className='font-semibold text-3xl text-shadow-md'>{game.name}</h1>
<p className='overflow-hidden text-wrap text-ellipsis text-base-content/60 text-shadow-md'>{game.summary}</p>
<p className='overflow-hidden text-wrap text-ellipsis wrap-anywhere max-h-24 text-base-content/60 text-shadow-md'>{game.summary}</p>
</div>
</div>
</div>

View file

@ -1,6 +1,6 @@
import { DefaultRommStaleTime, GameListFilterType, RommLoginDataSchema } from "@/shared/constants";
import { rommApi, settingsApi } from "../clientApi";
import { InvalidateQueryFilters, mutationOptions, QueryFilters, queryOptions, useMutation } from "@tanstack/react-query";
import { InvalidateQueryFilters, mutationOptions, QueryClient, QueryFilters, queryOptions, useMutation } from "@tanstack/react-query";
import z from "zod";
import { statsApiStatsGetOptions } from "@/clients/romm/@tanstack/react-query.gen";
@ -23,6 +23,20 @@ export const gameQuery = (source: string, id: string) => queryOptions({
},
});
export const rommLogoutMutation = mutationOptions({ mutationKey: ["romm", "auth", "logout"], mutationFn: () => rommApi.api.romm.logout.romm.post() });
export const invalidateLogin = (client: QueryClient) =>
{
return client.invalidateQueries({
predicate (query)
{
return query.queryKey.includes('auth')
|| query.queryKey.includes('games')
|| query.queryKey.includes('game')
|| query.queryKey.includes('platform')
|| query.queryKey.includes('platforms')
|| query.queryKey.includes('collections');
},
});
};
export const rommQrLoginMutation = mutationOptions({
mutationKey: ['login', 'qr', 'cancel'],
mutationFn: async () =>
@ -30,7 +44,11 @@ export const rommQrLoginMutation = mutationOptions({
const { data, error } = await rommApi.api.romm.login.romm.qr.post();
if (error) throw error;
return data;
}
},
onSuccess: (d, v, r, c) =>
{
invalidateLogin(c.client);
},
});
export const rommLoginMutation = mutationOptions({
mutationKey: ["romm", "login"],
@ -41,7 +59,7 @@ export const rommLoginMutation = mutationOptions({
},
onSuccess: (d, v, r, c) =>
{
c.client.invalidateQueries({ queryKey: ['romm', 'auth'] });
invalidateLogin(c.client);
},
onError: (e) =>
{

View file

@ -2,6 +2,7 @@ import { mutationOptions, queryOptions } from "@tanstack/react-query";
import { getErrorMessage } from "react-error-boundary";
import toast from "react-hot-toast";
import { rommApi, settingsApi } from "../clientApi";
import { invalidateLogin } from "./romm";
export const changeDownloadsMutation = mutationOptions({
mutationKey: ["setting", "downloads"],
@ -29,21 +30,25 @@ export const autoEmulatorsQuery = queryOptions({
}
});
export const twitchLogoutMutation = mutationOptions({
mutationKey: ['twitch', 'logout'],
mutationKey: ['twitch', 'auth', 'logout'],
mutationFn: () =>
{
return rommApi.api.romm.logout.twitch.post();
}
});
export const twitchLoginMutation = mutationOptions({
mutationKey: ['twitch', 'login'],
mutationKey: ['twitch', 'auth', 'login'],
mutationFn: (openInBrowser: boolean) =>
{
return rommApi.api.romm.login.twitch.post({ openInBrowser });
}
},
onSuccess (data, variables, onMutateResult, context)
{
invalidateLogin(context.client);
},
});
export const twitchLoginVerificationQuery = queryOptions({
queryKey: ['twitch', 'login', 'status'],
queryKey: ['twitch', 'login', 'status', 'auth'],
retry (failureCount, error)
{
if ((error as any).status === 404)

View file

@ -1,7 +1,7 @@
import { LocalSettingsSchema, LocalSettingsType } from "@/shared/constants";
import { DependencyList, RefObject, useEffect, useRef, useState } from "react";
import { DependencyList, FocusEventHandler, RefObject, useEffect, useRef, useState } from "react";
import { useLocalStorage } from "usehooks-ts";
import { jobsApi } from "./clientApi";
import { jobsApi, systemApi } from "./clientApi";
import { JobsAPIType } from "@/bun/api/rpc";
import { AnyRouter, useRouter } from "@tanstack/react-router";
import { soundMap } from "./audio/audioConstants";
@ -369,3 +369,17 @@ export function useOnNavigateBack (callback: (state: { sound?: keyof typeof soun
return unsub;
}, [router]);
}
export function showKeyboardHandler (activeControl: string, node?: HTMLInputElement)
{
if (node && node.type !== 'checkbox' && (activeControl === 'gamepad' || activeControl === 'touch'))
{
var rect = node.getBoundingClientRect();
systemApi.api.system.show_keyboard.post({
XPosition: rect.x,
YPosition: rect.y,
Width: rect.width,
Height: rect.height
});
}
};

View file

@ -145,15 +145,18 @@ export const EmulatorPackageSchema = z.object({
z.object({
type: z.literal(['github', 'gitlab']),
pattern: z.string(),
path: z.string()
path: z.string(),
bin: z.string().optional()
}),
z.object({
type: z.literal('direct'),
url: z.url(),
bin: z.string().optional()
}),
z.object({
type: z.literal('scoop'),
url: z.url(),
bin: z.string().optional()
})
]))).optional(),
systems: z.array(z.string()),

View file

@ -119,7 +119,7 @@ declare interface CommandEntry
/** The front end label for the command. Mainly gotten from ES-DE list */
label?: string;
/** Compiled command to be executed */
command: string;
command: string | string[];
/** Environment variables */
env?: Record<string, string>,
/** The path the spawned process will start at */