feat(saves): add local save selection and editing
This commit is contained in:
1 parent
2b1da24263
commit
073a907617
18 files changed
+634
-4
No files matched your search
@@ -13,6 +13,7 @@ import { createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentC
|
||||
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
|
||||
import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
|
||||
import { resourcePaths } from '../services/resources/resource-paths.ts';
|
||||
import { createSave, getSaveDetails, getSaveList, saveWriteInProgress, selectSave, setSaveCurrencies } from '../services/saves/manage-saves.ts';
|
||||
import { broadcast, handle } from './register.ts';
|
||||
|
||||
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
|
||||
@@ -96,16 +97,23 @@ export function registerIpcHandlers(): void {
|
||||
|
||||
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
|
||||
handle('copies:maintain', async (request) => {
|
||||
if (saveWriteInProgress()) throw new AppError('maintenance_busy');
|
||||
const updated = await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress));
|
||||
broadcast('event:copies-changed', updated);
|
||||
return updated;
|
||||
});
|
||||
handle('copies:cancelMaintenance', () => cancelMaintenance());
|
||||
|
||||
handle('saves:list', ({ copyId }) => getSaveList(copyId));
|
||||
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
|
||||
handle('saves:setCurrent', ({ copyId, userId }) => selectSave(copyId, userId));
|
||||
handle('saves:create', (request) => createSave(request));
|
||||
handle('saves:editCurrencies', ({ copyId, userId, values }) => setSaveCurrencies(copyId, userId, values));
|
||||
|
||||
handle('launch:getState', () => getLaunchState());
|
||||
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
|
||||
handle('launch:start', () => {
|
||||
if (maintenanceInProgress()) throw new AppError('maintenance_busy');
|
||||
if (maintenanceInProgress() || saveWriteInProgress()) throw new AppError('maintenance_busy');
|
||||
return startLaunch((state) => broadcast('event:launch-state', state));
|
||||
});
|
||||
handle('launch:stop', async () => { await stopLaunch(); });
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { join } from 'node:path';
|
||||
import { utilityProcess } from 'electron';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { CurrencyEdits, SaveDetails, SaveList, SaveRegistration } from '@shared/schemas/saves.ts';
|
||||
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
|
||||
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
|
||||
import { listCopies, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
||||
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { forwardProcessOutput } from '../launch/process-output.ts';
|
||||
|
||||
let writing = false;
|
||||
|
||||
export function saveWriteInProgress(): boolean {
|
||||
return writing;
|
||||
}
|
||||
|
||||
async function requireCopy(id: string): Promise<InstallRecord> {
|
||||
const copy = (await listCopies()).copies.find((record) => record.id === id);
|
||||
if (!copy) throw new AppError('copy_not_found');
|
||||
return copy;
|
||||
}
|
||||
|
||||
function location(copy: InstallRecord) {
|
||||
return { gameFolder: copy.copyPath, dataFolder: copy.dataPath };
|
||||
}
|
||||
|
||||
export async function getSaveList(copyId: string): Promise<SaveList> {
|
||||
const copy = await requireCopy(copyId);
|
||||
const saves = await run({ operation: 'list', ...location(copy) }) as SaveList['saves'];
|
||||
const current = saves.find(({ userId }) => userId === copy.currentSaveId)?.userId ?? saves[0]?.userId ?? null;
|
||||
return { saves, current };
|
||||
}
|
||||
|
||||
export async function getSaveDetails(copyId: string, userId: string): Promise<SaveDetails> {
|
||||
const copy = await requireCopy(copyId);
|
||||
return await run({ operation: 'details', ...location(copy), userId }) as SaveDetails;
|
||||
}
|
||||
|
||||
export async function selectSave(copyId: string, userId: string): Promise<SaveList> {
|
||||
await getSaveDetails(copyId, userId);
|
||||
await updateCopyRecord(copyId, (record) => ({ ...record, currentSaveId: userId }));
|
||||
return getSaveList(copyId);
|
||||
}
|
||||
|
||||
export async function createSave({ copyId, login, password, nick }: SaveRegistration): Promise<SaveList> {
|
||||
return write(async () => {
|
||||
const copy = await requireCopy(copyId);
|
||||
const { userId } = await run({ operation: 'create', ...location(copy), login, password, nick }) as { userId: string };
|
||||
await updateCopyRecord(copyId, (record) => ({ ...record, currentSaveId: userId }));
|
||||
return getSaveList(copyId);
|
||||
});
|
||||
}
|
||||
|
||||
export async function setSaveCurrencies(copyId: string, userId: string, values: CurrencyEdits): Promise<SaveDetails> {
|
||||
return write(async () => {
|
||||
const copy = await requireCopy(copyId);
|
||||
await run({ operation: 'edit', ...location(copy), userId, values });
|
||||
return getSaveDetails(copyId, userId);
|
||||
});
|
||||
}
|
||||
|
||||
async function write<T>(operation: () => Promise<T>): Promise<T> {
|
||||
if (writing || launchInProgress() || maintenanceInProgress()) throw new AppError('save_read_only');
|
||||
writing = true;
|
||||
try {
|
||||
if (await gameProcessRunning(AbortSignal.timeout(4000)) || await labServerRunning()) {
|
||||
throw new AppError('save_read_only');
|
||||
}
|
||||
return await operation();
|
||||
} finally {
|
||||
writing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function labServerRunning(): Promise<boolean> {
|
||||
const lab = await readInstalledLab().catch(() => null);
|
||||
if (!lab) return false;
|
||||
try {
|
||||
const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(600) });
|
||||
return response.ok && (await response.json() as { app?: string }).app === 'wto-server';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function run(task: SaveTask): Promise<SaveResult> {
|
||||
const child = utilityProcess.fork(join(import.meta.dirname, 'save-worker.js'), [], { serviceName: 'WTOffline save management', stdio: 'pipe' });
|
||||
forwardProcessOutput(child.stdout, 'saves', 'info');
|
||||
forwardProcessOutput(child.stderr, 'saves', 'error');
|
||||
try {
|
||||
return await new Promise<SaveResult>((resolve, reject) => {
|
||||
child.once('exit', () => reject(new AppError('save_operation_failed')));
|
||||
child.once('message', (reply: SaveReply) => {
|
||||
if (reply.ok) resolve(reply.result);
|
||||
else reject(new AppError(reply.error));
|
||||
});
|
||||
child.postMessage(task);
|
||||
});
|
||||
} finally {
|
||||
child.removeAllListeners('exit');
|
||||
child.kill();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { AppErrorCode } from '@shared/errors.ts';
|
||||
import type { CurrencyEdits, SaveDetails, SaveList } from '@shared/schemas/saves.ts';
|
||||
|
||||
interface Location {
|
||||
readonly gameFolder: string;
|
||||
readonly dataFolder: string;
|
||||
}
|
||||
|
||||
export type SaveTask = Location & (
|
||||
| { readonly operation: 'list' }
|
||||
| { readonly operation: 'details'; readonly userId: string }
|
||||
| { readonly operation: 'edit'; readonly userId: string; readonly values: CurrencyEdits }
|
||||
| { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string }
|
||||
);
|
||||
export type SaveResult = SaveList['saves'] | SaveDetails | { userId: string } | null;
|
||||
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { MessageEvent } from 'electron';
|
||||
import { AccountStore, editSaveCurrencies, listSaveSummaries, readSaveDetails } from '@wto/server';
|
||||
import type { SaveTask, SaveReply } from './save-protocol.ts';
|
||||
|
||||
function execute(task: SaveTask): SaveReply {
|
||||
switch (task.operation) {
|
||||
case 'list':
|
||||
return { ok: true, result: listSaveSummaries(task.dataFolder) };
|
||||
case 'details': {
|
||||
const result = readSaveDetails(task.dataFolder, task.userId);
|
||||
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
|
||||
}
|
||||
case 'edit':
|
||||
return editSaveCurrencies(task, task.userId, task.values)
|
||||
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
|
||||
case 'create': {
|
||||
const result = new AccountStore(task.dataFolder).register(task.login, task.password, task.nick);
|
||||
switch (result.kind) {
|
||||
case 'registered': return { ok: true, result: { userId: result.account.userId } };
|
||||
case 'invalid-login': return { ok: false, error: 'save_login_invalid' };
|
||||
case 'invalid-password': return { ok: false, error: 'save_password_invalid' };
|
||||
case 'invalid-nick': return { ok: false, error: 'save_nick_invalid' };
|
||||
case 'already-registered': return { ok: false, error: 'save_login_exists' };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
process.parentPort.once('message', (event: MessageEvent) => {
|
||||
let reply: SaveReply;
|
||||
try {
|
||||
reply = execute(event.data as SaveTask);
|
||||
} catch (error) {
|
||||
console.error('[saves] the save operation failed:', error);
|
||||
reply = { ok: false, error: 'save_operation_failed' };
|
||||
}
|
||||
process.parentPort.postMessage(reply);
|
||||
});
|
||||
Reference in new issue
Block a user