Files
game_voice_recorder/app/src/main/ipc.ts
EJClaw fa6126e17f v1.3.6: 목소리 깨짐(RTP 기준 쉼 채우기) · 알 수 없음 · 잡음 숨기기/삭제 · 사이트 로그 · 지금 게임 · TTS 속도 · 시작 창
- 녹음기: 패킷 도착 간격 대신 RTP 타임스탬프로 자리를 정한다. 게임 중 몰려 온 패킷 사이에 무음이 끼어 목소리가 깨졌다. 예전 녹음은 한 번 고친 뒤 다시 변환
- users.updated 를 빈 목록으로 보내 사이트에서 말한 사람이 '알 수 없음'이 되던 것
- 잡음은 숨기고 ogg 삭제, 로그에 잡음으로 남김. 짧은 목소리도 Whisper 로, 반복 고리는 줄여서 보여 줌
- 사이트: 재생 음량, 발화 우클릭(자세한 정보 · ogg 다운로드), 사이트 로그(/logs, 게임 PC 꺼져도), 지금 게임 상태
- 앱: 지금 게임 상태, 녹음 안내 말 속도 0.1~2.0, 포터블 · 앱 시작 창
- 발로란트 데스매치 가짜 라운드 · 에이스, 빈 선수 이름

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:01:14 +09:00

373 lines
16 KiB
TypeScript

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 type { AppAuth, AuthState } from '../core/auth.js';
import { runDiagnostics } from '../core/diagnostics.js';
import { clampRate, isOgg, render } 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 { secureServerUrl } from '../core/util/secure-url.js';
import { ADMIN_ONLY_ACTIONS, ADMIN_ONLY_MESSAGE, adminOnlyPaths, isAdminRole } from '../core/roles.js';
import type { AppState, AuthView, 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; auth: AuthState }): AppState {
const s = core.settings.get();
return {
account: { user: opts.auth.user, role: opts.auth.role, offline: opts.auth.offline },
version: core.version,
dataDir: opts.dataDir,
portable: opts.portable,
settings: s,
builtinBot: core.settings.hasBuiltinBot,
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'],
liveGames: core.games.live(),
counts: core.store.counts(),
excludedUsers: core.store
.listUsers()
.filter((u) => u.excluded)
.map((u) => ({ id: u.id, name: u.name })),
autoStart: app.getLoginItemSettings().openAtLogin,
};
}
export interface IpcContext {
dataDir: string;
portable: boolean;
win: () => BrowserWindow | null;
finishWizard: () => void;
quit: () => void;
auth: AppAuth;
/** 로그인해서 코어가 떠 있으면 코어 · 파인튜너 */
current: () => { core: Core; ft: Finetuner } | null;
authView: () => AuthView;
/** 로그인 화면에서 다시 확인 (서버 연결 실패 후 재시도) */
recheck: () => Promise<void>;
}
/** 설정 창의 window.gvr 요청 처리 (api-types.ts GvrApi). 로그인 · 관리자 요청은 코어 없이도 받는다 */
export function registerIpc(ctx: IpcContext) {
const send = (ch: string, payload: unknown) => ctx.win()?.webContents.send(ch, payload);
const progress = (p: DownloadProgress) => send('gvr:progress', p);
const role = () => (ctx.auth.ok ? ctx.auth.state.role : null);
// 로그인해야 쓰는 요청은 지금 떠 있는 코어로 보낸다 (로그아웃 후 다시 로그인하면 코어가 새로 뜬다)
const live = () => {
const c = ctx.auth.ok ? ctx.current() : null;
if (!c) throw new Error('로그인이 필요합니다');
return c;
};
const core = new Proxy({} as Core, { get: (_t, k) => (live().core as any)[k] });
const ft = new Proxy({} as Finetuner, {
get: (_t, k) => {
const f = live().ft as any;
return typeof f[k] === 'function' ? f[k].bind(f) : f[k];
},
});
const h: Handlers = {
getState: () => buildState(core, { ...ctx, auth: ctx.auth.state }),
updateSettings: (patch) => {
if (!isAdminRole(role()) && adminOnlyPaths(patch).length) throw new Error(ADMIN_ONLY_MESSAGE);
// 사이트 서버 주소는 https 만 (로그인 토큰 · 기기 키 · 기록이 오간다)
if (patch?.site?.serverUrl !== undefined) patch = { ...patch, site: { ...patch.site, serverUrl: secureServerUrl(patch.site.serverUrl) } };
return core.settings.update(patch);
},
setSecret: (key, value) => {
if (key !== 'botToken' && key !== 'riotApiKey') throw new Error('바꿀 수 없는 값입니다');
if (key === 'botToken' && !isAdminRole(role())) throw new Error(ADMIN_ONLY_MESSAGE);
return core.settings.setSecret(key, value);
},
testBotToken: async (token?: string) => {
const t = token || core.settings.activeBotToken();
// 겜녹이 봇은 토큰이 이 PC 에 없다: 사이트 서버 중계로 붙어 보고 결과를 알려 준다
if (!t && core.settings.get().discord.botMode === 'builtin') {
const b = core.bot;
if (b.state.status !== 'ready' || b.gateway?.kind !== 'remote') {
await b.stop();
await core.startBot();
}
if (b.state.status !== 'ready' || !b.state.user) return { ok: false, error: b.state.error ?? '사이트 서버의 겜녹이 봇에 연결하지 못했습니다' };
return { ok: true, bot: b.state.user, guilds: b.state.guilds };
}
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 [ms, admins] = await Promise.all([core.bot.members(), ctx.auth.adminIds().catch(() => [] as string[])]);
const meId = ctx.auth.state.user?.id ?? null;
const rank = (m: { me: boolean; admin: boolean }) => (m.me ? 0 : m.admin ? 1 : 2);
return ms
.map((m) => ({ id: m.id, name: core.store.displayNames()[m.id] ?? m.name, avatar: m.avatar, bot: m.bot, me: m.id === meId, admin: admins.includes(m.id) }))
.sort((a, b) => rank(a) - rank(b) || a.name.localeCompare(b.name, 'ko'));
},
previewTts: async (text: string, voice: string, rate = 1) => {
try {
const r = clampRate(rate);
const f = path.join(core.paths().tts, `preview-${Date.now()}.${r < 0.5 ? 'ogg' : 'webm'}`);
await render(text, voice, r, f, (src, dst, tempo) => core.worker.request('tempo', { src, dst, tempo }, 120000));
const data = fs.readFileSync(f);
fs.rmSync(f, { force: true });
return { ok: true, dataUrl: `data:audio/${isOgg(f) ? 'ogg' : '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<string, number>();
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(),
};
const authHandlers: Handlers = {
authState: () => ctx.authView(),
authLogin: () => ctx.auth.login().then(() => ctx.authView()),
authCancel: () => ctx.auth.cancelLogin(),
authLogout: () => ctx.auth.logout(),
authRecheck: () => ctx.recheck().then(() => ctx.authView()),
adminUsers: () => ctx.auth.adminUsers(),
adminAddUser: (id: string, r: 'admin' | 'user') => ctx.auth.adminAddUser(id, r),
adminSetRole: (id: string, r: 'admin' | 'user') => ctx.auth.adminSetRole(id, r),
adminRemoveUser: (id: string) => ctx.auth.adminRemoveUser(id),
adminDisplayNames: () => ctx.auth.displayNames(),
adminSetDisplayName: async (id: string, name: string) => {
if (role() !== 'superadmin') throw new Error('표시 이름은 최고 관리자만 바꿀 수 있습니다');
const r = await ctx.auth.adminSetDisplayName(id, name);
ctx.current()?.core.store.setDisplayNames(r.names);
return r.names;
},
openExternal: h.openExternal,
quit: h.quit,
};
for (const [name, fn] of Object.entries(authHandlers)) ipcMain.handle(`gvr:${name}`, async (_e, ...args) => fn!(...args));
for (const [name, fn] of Object.entries(h)) {
if (name in authHandlers) continue;
ipcMain.handle(`gvr:${name}`, async (_e, ...args) => {
live();
if (ADMIN_ONLY_ACTIONS.has(name) && !isAdminRole(role())) throw new Error('관리자만 쓸 수 있는 기능입니다');
return fn!(...args);
});
}
}