import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron'; import fs from 'node:fs'; import path from 'node:path'; import { toUser } from '../core/api/server.js'; import { runDiagnostics } from '../core/diagnostics.js'; import { synthesize } from '../core/discord/tts.js'; import type { Core } from '../core/index.js'; import { registerDevice } from '../core/relay/client.js'; import { dirSize } from '../core/retention.js'; import type { AppState, DownloadProgress, GvrApi } from './api-types.js'; import type { Finetuner } from './finetune.js'; type Handlers = { [K in keyof GvrApi]?: (...args: any[]) => any }; export function buildState(core: Core, opts: { dataDir: string; portable: boolean }): AppState { const s = core.settings.get(); return { version: core.version, dataDir: opts.dataDir, portable: opts.portable, settings: s, secrets: { botToken: core.settings.hasSecret('botToken'), riotApiKey: core.settings.hasSecret('riotApiKey'), deviceKey: core.settings.hasSecret('deviceKey') }, secretCodec: core.settings.codecName, bot: core.bot.state, worker: { ready: core.worker.ready, lastError: core.worker.lastError }, stt: core.stt.status, relay: core.relay.status, games: core.games.status() as AppState['games'], counts: core.store.counts(), excludedUsers: core.store .listUsers() .filter((u) => u.excluded) .map((u) => ({ id: u.id, name: u.name })), autoStart: app.getLoginItemSettings().openAtLogin, }; } /** 설정 창의 window.gvr 요청 처리 (api-types.ts GvrApi) */ export function registerIpc(core: Core, ft: Finetuner, ctx: { dataDir: string; portable: boolean; win: () => BrowserWindow | null; finishWizard: () => void; quit: () => void }) { const send = (ch: string, payload: unknown) => ctx.win()?.webContents.send(ch, payload); const progress = (p: DownloadProgress) => send('gvr:progress', p); const h: Handlers = { getState: () => buildState(core, ctx), updateSettings: (patch) => core.settings.update(patch), setSecret: (key, value) => core.settings.setSecret(key, value), testBotToken: async (token?: string) => { const t = token || core.settings.getSecret('botToken'); if (!t) return { ok: false, error: '봇 토큰을 입력해 주세요' }; const get = (p: string) => fetch(`https://discord.com/api/v10${p}`, { headers: { authorization: `Bot ${t}` } }); try { const me = await get('/users/@me'); if (me.status === 401) return { ok: false, error: '봇 토큰이 올바르지 않습니다' }; if (!me.ok) return { ok: false, error: `디스코드 응답 ${me.status}` }; const u: any = await me.json(); const gs: any[] = await (await get('/users/@me/guilds')).json(); return { ok: true, bot: { id: u.id, name: u.username, avatar: u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png` : null }, guilds: gs.map((g) => ({ id: g.id, name: g.name })), }; } catch (e: any) { return { ok: false, error: `연결 실패: ${e.message}` }; } }, restartBot: async () => { await core.bot.stop(); await core.startBot(); return core.bot.state.status === 'ready' || core.bot.state.status === 'connecting' ? { ok: true } : { ok: false, error: core.bot.state.error ?? '봇을 시작하지 못했습니다' }; }, guildMembers: async () => { const g = core.bot.guild(); if (!g) return []; const ms = await g.members.fetch().catch(() => g.members.cache); return [...ms.values()].map((m) => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 64 }), bot: m.user.bot })).sort((a, b) => a.name.localeCompare(b.name, 'ko')); }, previewTts: async (text: string, voice: string) => { try { const f = path.join(core.paths().tts, `preview-${Date.now()}.webm`); await synthesize(text, voice, f); const data = fs.readFileSync(f); fs.rmSync(f, { force: true }); return { ok: true, dataUrl: `data:audio/webm;base64,${data.toString('base64')}` }; } catch (e: any) { return { ok: false, error: `음성 합성 실패: ${e.message}` }; } }, gpuInfo: () => core.worker.request('gpu_info', {}, 30000).catch(() => null), models: () => core.worker.request('models', {}, 30000).catch(() => null), download: async (target: 'model' | 'cuda_runtime', name?: string) => { const key = target === 'model' ? `model:${name}` : 'cuda_runtime'; progress({ key, done_mb: 0, total_mb: 0, state: 'running' }); try { await core.worker.request('download', { target, name }, 0, (ev) => { if (ev.event === 'progress') progress({ key, done_mb: ev.done_mb, total_mb: ev.total_mb, speed_mbps: ev.speed_mbps, eta_s: ev.eta_s, stage: ev.stage, state: 'running' }); }); progress({ key, done_mb: 1, total_mb: 1, state: 'done' }); if (target === 'cuda_runtime') { // 받은 DLL 은 워커를 다시 띄워야 적용된다 await core.worker.stop(); core.worker.start(); } else await core.stt.prepareModels(); return { ok: true }; } catch (e: any) { progress({ key, done_mb: 0, total_mb: 0, state: 'error', error: e.message }); return { ok: false, error: e.message }; } }, deleteModel: async (name: string) => { if (!/^[\w.\-]+$/.test(name)) return { ok: false, error: '잘못된 모델 이름' }; for (const slot of ['realtime', 'precise'] as const) if (core.stt.status.slots[slot].model === name) await core.stt.unload(slot); fs.rmSync(path.join(core.paths().models, name), { recursive: true, force: true }); return { ok: true }; }, applyModels: async () => { await core.stt.unload('realtime'); await core.stt.unload('precise'); core.stt.status.slots.realtime.model = null; core.stt.status.slots.precise.model = null; await core.stt.prepareModels(); }, chooseFolder: async (title: string, defaultPath?: string) => { const w = ctx.win(); const r = w ? await dialog.showOpenDialog(w, { title, defaultPath, properties: ['openDirectory', 'createDirectory'] }) : await dialog.showOpenDialog({ title, defaultPath, properties: ['openDirectory', 'createDirectory'] }); return r.canceled ? null : r.filePaths[0]; }, registerDevice: async (code: string) => { const s = core.settings.get(); try { const r = await registerDevice(s.site.serverUrl, code, s.site.deviceName); core.settings.update({ site: { deviceId: r.deviceId } }); core.settings.setSecret('deviceKey', r.deviceKey); core.relay.restart(); return { ok: true }; } catch (e: any) { return { ok: false, error: e.message }; } }, unregisterDevice: () => { core.settings.update({ site: { deviceId: null } }); core.settings.setSecret('deviceKey', null); core.relay.restart(); }, runDiagnostics: async () => { const s = core.settings.get(); return runDiagnostics({ worker: core.worker, resourcesDir: core.resourcesDir, logsDir: core.paths().logs, model: s.stt.realtimeModel, device: s.stt.device, computeType: s.stt.computeType, lolLogsDir: s.games.lolLogsDir, onItem: (it) => send('gvr:diag', it), }); }, storageUsage: async () => { const p = core.paths(); let free: number | null = null; try { const st = fs.statfsSync(p.dataDir); free = st.bavail * st.bsize; } catch { /* 지원 안 함 */ } return { audioBytes: dirSize(p.audio), trainingBytes: dirSize(p.training), dbBytes: ['', '-wal', '-shm'].reduce((n, x) => n + (fs.existsSync(p.db + x) ? fs.statSync(p.db + x).size : 0), 0), modelsBytes: dirSize(p.models), freeBytes: free, }; }, runRetention: () => core.retention.run(), users: () => { const acc = core.store.listAccounts(); return core.store.listUsers().map((u) => toUser(u, acc)); }, setRiotIds: (userId: string, riotIds: string[]) => { const cur = core.store.listAccounts().filter((a) => a.user_id === userId); const next = riotIds .map((r) => r.trim()) .filter((r) => /^.+#.+$/.test(r)) .map((r) => cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r }); core.store.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id }))); }, setExcluded: (userId: string, excluded: boolean) => { core.store.setExcluded(userId, excluded); core.bus.live({ type: 'users.updated', data: [] }); }, dictionary: () => { const rows = core.store.listDict(); const counts = new Map(); for (const r of rows) if (r.kind === 'hotword' && r.source === 'builtin') counts.set(r.pack, (counts.get(r.pack) || 0) + 1); return { labels: core.dict.labels, packs: [...counts.entries()].map(([key, count]) => ({ key, label: core.dict.labels[key] ?? key, count })), entries: rows .filter((r) => r.source !== 'builtin' || r.kind === 'correction') .map((r) => ({ id: r.id, word: r.word, from: r.from_text || null, kind: r.kind, pack: r.pack, source: r.source, enabled: !!r.enabled, hits: r.hits })), }; }, addWord: (word: string) => { const w = word.trim(); if (w) core.store.addDict({ word: w, pack: 'user', kind: 'hotword', from_text: '', source: 'user' }); core.dict.invalidate(); }, addCorrection: (from: string, to: string) => { if (from.trim() && to.trim()) core.store.addDict({ word: to.trim(), pack: 'user', kind: 'correction', from_text: from.trim(), source: 'user' }); core.dict.invalidate(); }, deleteDict: (id: number) => { core.store.deleteDict(id); core.dict.invalidate(); }, setDictEnabled: (id: number, enabled: boolean) => { core.store.setDictEnabled(id, enabled); core.dict.invalidate(); }, finetuneStatus: () => ft.refresh(), finetuneInstall: async () => { try { await ft.install(); return { ok: true }; } catch (e: any) { return { ok: false, error: e.message }; } }, finetuneStart: async () => { try { void ft.start().catch(() => undefined); await new Promise((r) => setTimeout(r, 300)); return ft.status.running ? { ok: true } : { ok: false, error: ft.status.log[ft.status.log.length - 1] ?? '시작하지 못했습니다' }; } catch (e: any) { return { ok: false, error: e.message }; } }, finetuneStop: () => ft.stop(), finetuneRollback: async () => { try { await ft.rollback(); return { ok: true }; } catch (e: any) { return { ok: false, error: e.message }; } }, clearTrainingData: () => { for (const s of core.store.trainingSamples()) fs.rmSync(s.audio_path, { force: true }); core.store.clearTraining(); }, openExternal: (url: string) => { if (/^https?:\/\//.test(url)) return shell.openExternal(url); }, openPath: (p: string) => shell.openPath(p), setAutoStart: (on: boolean) => { app.setLoginItemSettings({ openAtLogin: on, path: process.env.PORTABLE_EXECUTABLE_FILE || process.execPath, args: ['--hidden'] }); core.settings.update({ general: { autoStart: on } }); }, finishWizard: () => { core.settings.update({ firstRunDone: true }); ctx.finishWizard(); }, recentLogs: () => { try { const dir = core.paths().logs; const f = fs.readdirSync(dir).filter((x) => x.startsWith('gvr-')).sort().pop(); if (!f) return []; return fs.readFileSync(path.join(dir, f), 'utf8').trimEnd().split('\n').slice(-300); } catch { return []; } }, quit: () => ctx.quit(), }; for (const [name, fn] of Object.entries(h)) { ipcMain.handle(`gvr:${name}`, async (_e, ...args) => fn!(...args)); } }