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

@ -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,67 +46,7 @@ export default new Elysia()
return status(res.status, res.statusText);
})
.get('/login/twitch', async () =>
{
const access_token = await secrets.get({ service: 'gamflow_twitch', name: 'access_token' });
if (!access_token)
{
return status('Not Found', "Not Logged In");
}
const res = await fetch('https://id.twitch.tv/oauth2/validate', { headers: { Authorization: `OAuth ${access_token}` } });
if (res.ok)
{
return await res.json() as { login: string, expires_in: number; client_id: string, user_id: string; };
}
if (!process.env.TWITCH_CLIENT_ID)
{
return status("Not Found", "Twitch Client ID not set");
}
const refresh_token = await secrets.get({ service: 'gamflow_twitch', name: "refresh_token" });
if (!refresh_token)
{
return status("Not Found", "Refresh Token Not Found");
}
// refresh token
const refreshResponse = await fetch('https://id.twitch.tv/oauth2/token', {
method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({
client_id: process.env.TWITCH_CLIENT_ID,
access_token,
grant_type: "refresh_token",
refresh_token
})
});
if (refreshResponse.ok)
{
const data: {
access_token: string,
refresh_token: string,
token_type: string;
expires_in: number;
} = await refreshResponse.json();
await secrets.set({ service: 'gamflow_twitch', name: 'access_token', value: data.access_token });
await secrets.set({ service: 'gamflow_twitch', name: 'refresh_token', value: data.refresh_token });
await secrets.set({ service: 'gamflow_twitch', name: 'expires_in', value: new Date(new Date().getTime() + data.expires_in).toString() });
await plugins.hooks.auth.loginComplete.promise({ service: 'twitch' });
events.emit('notification', { message: "Twitch Refresh Successful", type: 'success' });
const res = await fetch('https://id.twitch.tv/oauth2/validate', { headers: { Authorization: `OAuth ${data.access_token}` } });
if (res.ok)
{
return await res.json() as { login: string, expires_in: number; client_id: string, user_id: string; };
}
}
return status(400, res.statusText);
})
.get('/login/twitch', checkLoginAndRefreshTwitch)
.post('/login/romm/qr', async () =>
{
if (taskQueue.hasActiveOfType(LoginJob))
@ -123,47 +63,7 @@ export default new Elysia()
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 () =>
{
const access_token = await secrets.get({ service: 'gameflow', name: 'romm_access_token' });
if (!access_token)
{
return { hasLogin: false };
}
const expires_in = await secrets.get({ service: 'gameflow', name: "romm_expires_in" });
if (expires_in)
{
const date = new Date(expires_in);
if (date > new Date())
{
return { hasLogin: true };
}
}
const refresh_token = await secrets.get({ service: 'gameflow', name: "romm_refresh_token" });
if (!refresh_token)
{
return { hasLogin: false };
}
const refreshResponse = await tokenApiTokenPost({ body: { grant_type: "refresh_token", refresh_token: refresh_token } });
if (refreshResponse.response.ok && refreshResponse.data)
{
await secrets.set({ service: 'gameflow', name: 'romm_access_token', value: refreshResponse.data.access_token });
if (refreshResponse.data.refresh_token)
await secrets.set({ service: 'gameflow', name: 'romm_refresh_token', value: refreshResponse.data.refresh_token });
await secrets.set({ service: 'gameflow', name: 'romm_expires_in', value: new Date(new Date().getTime() + refreshResponse.data.expires * 1000).toString() });
await plugins.hooks.auth.loginComplete.promise({ service: 'romm' });
events.emit('notification', { message: "Romm Refresh Successful", type: 'success' });
return { hasLogin: true };
}
return status(refreshResponse.response.status, refreshResponse.response.statusText) as any;
},
.get('/login/romm', checkLoginAndRefreshRomm,
{ response: z.object({ hasLogin: z.boolean() }) })
.post('/logout/romm', async () =>
{
@ -174,6 +74,109 @@ export default new Elysia()
}, { response: z.any() });
export async function checkLoginAndRefreshTwitch ()
{
const access_token = await secrets.get({ service: 'gamflow_twitch', name: 'access_token' });
if (!access_token)
{
return status('Not Found', "Not Logged In");
}
const res = await fetch('https://id.twitch.tv/oauth2/validate', { headers: { Authorization: `OAuth ${access_token}` } });
if (res.ok)
{
return await res.json() as { login: string, expires_in: number; client_id: string, user_id: string; };
}
if (!process.env.TWITCH_CLIENT_ID)
{
return status("Not Found", "Twitch Client ID not set");
}
const refresh_token = await secrets.get({ service: 'gamflow_twitch', name: "refresh_token" });
if (!refresh_token)
{
return status("Not Found", "Refresh Token Not Found");
}
// refresh token
const refreshResponse = await fetch('https://id.twitch.tv/oauth2/token', {
method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({
client_id: process.env.TWITCH_CLIENT_ID,
access_token,
grant_type: "refresh_token",
refresh_token
})
});
if (refreshResponse.ok)
{
const data: {
access_token: string,
refresh_token: string,
token_type: string;
expires_in: number;
} = await refreshResponse.json();
await secrets.set({ service: 'gamflow_twitch', name: 'access_token', value: data.access_token });
await secrets.set({ service: 'gamflow_twitch', name: 'refresh_token', value: data.refresh_token });
await secrets.set({ service: 'gamflow_twitch', name: 'expires_in', value: new Date(new Date().getTime() + data.expires_in).toString() });
await plugins.hooks.auth.loginComplete.promise({ service: 'twitch' });
events.emit('notification', { message: "Twitch Refresh Successful", type: 'success' });
const res = await fetch('https://id.twitch.tv/oauth2/validate', { headers: { Authorization: `OAuth ${data.access_token}` } });
if (res.ok)
{
return await res.json() as { login: string, expires_in: number; client_id: string, user_id: string; };
}
}
return status(400, res.statusText);
}
export async function checkLoginAndRefreshRomm ()
{
const access_token = await secrets.get({ service: 'gameflow', name: 'romm_access_token' });
if (!access_token)
{
return { hasLogin: false };
}
const expires_in = await secrets.get({ service: 'gameflow', name: "romm_expires_in" });
if (expires_in)
{
const date = new Date(expires_in);
if (date > new Date())
{
return { hasLogin: true };
}
}
const refresh_token = await secrets.get({ service: 'gameflow', name: "romm_refresh_token" });
if (!refresh_token)
{
return { hasLogin: false };
}
const refreshResponse = await tokenApiTokenPost({ body: { grant_type: "refresh_token", refresh_token: refresh_token } });
if (refreshResponse.response.ok && refreshResponse.data)
{
await secrets.set({ service: 'gameflow', name: 'romm_access_token', value: refreshResponse.data.access_token });
if (refreshResponse.data.refresh_token)
await secrets.set({ service: 'gameflow', name: 'romm_refresh_token', value: refreshResponse.data.refresh_token });
await secrets.set({ service: 'gameflow', name: 'romm_expires_in', value: new Date(new Date().getTime() + refreshResponse.data.expires * 1000).toString() });
await plugins.hooks.auth.loginComplete.promise({ service: 'romm' });
events.emit('notification', { message: "Romm Refresh Successful", type: 'success' });
return { hasLogin: true };
}
return status(refreshResponse.response.status, refreshResponse.response.statusText) as 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,14 +75,23 @@ export class EmulatorDownloadJob implements IJob<z.infer<typeof EmulatorDownload
if (destinationPaths[0])
{
let destinationPath = destinationPaths[0];
await new Promise((resolve, reject) =>
if (destinationPath.endsWith('.tar'))
{
const seven = Seven.extractFull(destinationPath, emulatorsFolder, { $bin: process.env.ZIP7_PATH ?? path7za, $progress: true, noRootDuplication: true });
seven.on('progress', p => context.setProgress(p.percent, "extract"));
seven.on('error', e => reject(e));
seven.on('end', () => resolve(true));
});
await fs.rm(destinationPath, { recursive: true });
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 });
seven.on('progress', p => context.setProgress(p.percent, "extract"));
seven.on('error', e => reject(e));
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,15 +42,24 @@ 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 plugins.hooks.games.postPlay.promise(
{
source,
id,
command: this.validCommand,
changedSaveFiles: Array.from(this.changedSaveFiles.values()),
validChangedSaveFiles: {},
gameInfo
}).catch(e => console.error(e));
await new Promise(async (resolve) =>
{
await plugins.hooks.games.postPlay.promise(
{
source,
id,
command: this.validCommand,
changedSaveFiles: Array.from(this.changedSaveFiles.values()),
validChangedSaveFiles: {},
gameInfo
}).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,31 +127,58 @@ export class LaunchGameJob implements IJob<z.infer<typeof LaunchGameJob.dataSche
{
await this.prePlay(context.setProgress.bind(context), { platformSlug: gameInfo?.platformSlug }).catch(e => reject(e));
// ES-DE commands require shell execution. Some emulators fail otherwise.
const spawnGame = spawn(this.validCommand.command, {
shell: this.validCommand.shell ?? true,
cwd: this.validCommand.startDir,
signal: context.abortSignal,
env: {
...process.env,
...this.validCommand.env
},
});
context.setProgress(0, "playing");
spawnGame.stdout.on('data', data => console.log(data));
spawnGame.on('close', (code) =>
if (Array.isArray(this.validCommand.command))
{
resolve(code);
});
spawnGame.on('error', e =>
{
console.error(e);
resolve(1);
});
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,
cwd: this.validCommand.startDir,
signal: context.abortSignal,
env: {
...process.env,
...this.validCommand.env
},
});
context.setProgress(0, "playing");
spawnGame.stdout.on('data', data => console.log(data));
spawnGame.on('close', (code) =>
{
resolve(code);
});
spawnGame.on('error', e =>
{
console.error(e);
resolve(1);
});
game = spawnGame;
}
game = spawnGame;
}
else if (this.validCommand.metadata.emulatorBin)
{
@ -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";
@ -318,4 +318,47 @@ 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,18 +15,22 @@ 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 ()
{
const latest = await fetch('https://api.github.com/repos/simeonradivoev/gameflow-deck/releases/latest');
if (latest.ok)
return getOrCached('check-for-update', async () => githubRequestQueue.add(async () =>
{
const data = await latest.json();
const hasUpdate = semver.order(data.tag_name, packageDef.version);
return hasUpdate;
}
const latest = await fetch('https://api.github.com/repos/simeonradivoev/gameflow-deck/releases/latest');
if (latest.ok)
{
const data = await latest.json();
const hasUpdate = semver.order(data.tag_name, packageDef.version);
return hasUpdate;
}
return 0;
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>;