M0: 기술 검증 - 구조 설계, STT 워커, 앱 코어, 게임 PC 진단

- docs/dev/ARCHITECTURE.md: 코어-워커-사이트 인터페이스 계약
- worker/: faster-whisper 한국어 STT, 음량 정규화, 4단계 잡음 판정, 사전 교정, GPU 감지·모델/CUDA 다운로드, 롤 채팅 OCR·r3dlog, 파인튜닝 파이프라인 (39 tests)
- app/src/core: 디스코드 DAVE 음성 녹음(Ogg Opus), STT 대기열, 발로란트/롤 로컬 API 어댑터, 타임라인·기록 API, 사이트 중계, 7일 음성 삭제, 진단
- tools/gen-dictionary.mjs: 공식 게임 데이터 기반 기본 단어사전 (1993단어)
- M0 결과: DAVE 연결 1.06s Ready, CPU tiny STT 3.6s→0.31s, 가짜 Riot 서버 통합 테스트 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 01:17:48 +09:00
parent 4596989ba7
commit 7c9146cd2d
95 changed files with 18435 additions and 0 deletions

248
app/src/core/api/server.ts Normal file
View File

@@ -0,0 +1,248 @@
import Fastify, { type FastifyInstance } from 'fastify';
import fs from 'node:fs';
import path from 'node:path';
import type { MatchDetail, MatchPlayer, Overview, User, UserProfile, Word } from '@gvr/shared';
import type { Store, UserRow } from '../db/db.js';
import type { Dictionary } from '../dict/dictionary.js';
import type { GameManager } from '../games/manager.js';
import type { Settings } from '../settings.js';
import { safeJson, type Timeline, type TimelineQuery } from '../timeline.js';
import type { Bus } from '../util/events.js';
export interface ApiDeps {
store: Store;
timeline: Timeline;
games: GameManager;
dict: Dictionary;
bus: Bus;
settings: () => Settings;
trainingDir: () => string;
overviewExtra: () => { guild: Overview['guild']; recording: Overview['recording'] };
version: string;
}
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
export function toUser(u: UserRow, accounts: { user_id: string; puuid: string; riot_id: string }[]): User {
return {
id: u.id,
name: u.name,
color: u.color,
avatar: u.avatar,
excluded: !!u.excluded,
riot: accounts.filter((a) => a.user_id === u.id).map((a) => ({ puuid: a.puuid, riotId: a.riot_id })),
};
}
/** 사이트에서 쓰는 기록 API (docs/dev/ARCHITECTURE.md 4장). 사이트 서버가 그대로 중계한다. */
export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
const app = Fastify({ logger: false, bodyLimit: 1024 * 1024 });
const { store, timeline } = d;
const users = (): User[] => {
const acc = store.listAccounts();
return store.listUsers().map((u) => toUser(u, acc));
};
app.get('/api/overview', async (): Promise<Overview> => {
const extra = d.overviewExtra();
const gs = d.games.status();
return {
guild: extra.guild,
recording: extra.recording,
users: users(),
games: { valorant: { connected: gs.valorant.connected, inMatch: gs.valorant.inMatch }, lol: { connected: gs.lol.connected, inMatch: gs.lol.inMatch } },
counts: store.counts(),
version: d.version,
};
});
app.get('/api/users', async () => users());
app.get<{ Params: { id: string } }>('/api/users/:id', async (req, reply): Promise<UserProfile | void> => {
const u = store.getUser(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found' });
const st = store.db
.prepare('SELECT count(*) n, coalesce(sum(ended_at-started_at),0) ms FROM utterances WHERE user_id=? AND (noise=0 OR corrected=1)')
.get(u.id) as { n: number; ms: number };
const texts = store.db
.prepare('SELECT text FROM utterances WHERE user_id=? AND text IS NOT NULL AND (noise=0 OR corrected=1) ORDER BY started_at DESC LIMIT 3000')
.all(u.id) as { text: string }[];
const freq = new Map<string, number>();
for (const t of texts)
for (const raw of t.text.split(/\s+/)) {
const w = raw.replace(/[.,!?~…"'()\[\]]/g, '');
if ([...w].length < 2 || STOP.has(w)) continue;
freq.set(w, (freq.get(w) || 0) + 1);
}
const topWords = [...freq.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, 30)
.map(([w, n]) => ({ w, n }));
const puuids = store
.listAccounts()
.filter((a) => a.user_id === u.id)
.map((a) => a.puuid)
.filter(Boolean);
const matchIds = new Set<string>(
(store.db.prepare('SELECT DISTINCT match_id FROM utterances WHERE user_id=? AND match_id IS NOT NULL').all(u.id) as { match_id: string }[]).map((r) => r.match_id),
);
if (puuids.length) {
const ph = puuids.map(() => '?').join(',');
for (const r of store.db.prepare(`SELECT DISTINCT match_id FROM game_events WHERE actor_puuid IN (${ph}) OR target_puuid IN (${ph})`).all(...puuids, ...puuids) as { match_id: string }[])
matchIds.add(r.match_id);
}
const matches = store.listMatches({ ids: [...matchIds], limit: 50 }).map((m) => d.games.summary(m));
return { user: toUser(u, store.listAccounts()), stats: { talkMs: st.ms, count: st.n, topWords }, matches };
});
app.get<{ Querystring: Record<string, string> }>('/api/timeline', async (req) => {
const q = req.query;
const tq: TimelineQuery = {
users: q.users ? q.users.split(',').filter(Boolean) : undefined,
game: q.game === 'valorant' || q.game === 'lol' || q.game === 'none' ? q.game : undefined,
match: q.match || undefined,
from: q.from ? Number(q.from) : undefined,
to: q.to ? Number(q.to) : undefined,
q: q.q || undefined,
types: q.types ? q.types.split(',').filter(Boolean) : undefined,
hideNoise: q.hideNoise === '1' || q.hideNoise === 'true',
cursor: q.cursor || undefined,
limit: q.limit ? Number(q.limit) : undefined,
order: q.order === 'asc' ? 'asc' : 'desc',
};
return timeline.query(tq);
});
app.get<{ Params: { id: string } }>('/api/audio/:id', async (req, reply) => {
const u = store.getUtterance(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found' });
if (!u.audio_path || u.audio_deleted || !fs.existsSync(u.audio_path)) return reply.code(410).send({ error: 'audio_deleted' });
const size = fs.statSync(u.audio_path).size;
const range = req.headers.range;
reply.header('content-type', 'audio/ogg').header('accept-ranges', 'bytes').header('cache-control', 'private, max-age=86400');
const m = range ? /bytes=(\d*)-(\d*)/.exec(range) : null;
if (m) {
const start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2]));
const end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1;
if (start >= size) return reply.code(416).header('content-range', `bytes */${size}`).send();
const buf = Buffer.alloc(end - start + 1);
const fd = fs.openSync(u.audio_path, 'r');
fs.readSync(fd, buf, 0, buf.length, start);
fs.closeSync(fd);
return reply.code(206).header('content-range', `bytes ${start}-${end}/${size}`).send(buf);
}
return reply.send(fs.readFileSync(u.audio_path));
});
app.get<{ Querystring: Record<string, string> }>('/api/matches', async (req) => {
const q = req.query;
return store
.listMatches({ game: q.game || undefined, before: q.before ? Number(q.before) : undefined, limit: q.limit ? Math.min(Number(q.limit), 200) : 50 })
.map((m) => d.games.summary(m));
});
app.get<{ Params: { id: string } }>('/api/matches/:id', async (req, reply): Promise<MatchDetail | void> => {
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
const det = safeJson<any>(m.detail, {});
const sum = d.games.summary(m);
const accounts = store.listAccounts();
const userOf = (puuid: string) => accounts.find((a) => a.puuid === puuid)?.user_id;
const players: MatchPlayer[] = (det.players || []).map((p: any) => ({
puuid: p.puuid,
name: p.name ?? '?',
tag: p.tag,
team: p.team,
ally: p.ally ?? (det.self ? p.team === (det.players || []).find((x: any) => x.puuid === det.self)?.team : false),
character: p.character ?? { id: '', name: '?', icon: null },
kills: p.kills ?? 0,
deaths: p.deaths ?? 0,
assists: p.assists ?? 0,
score: p.score,
cs: p.cs,
gold: p.gold,
level: p.level,
items: p.items,
rank: p.rank ?? null,
userId: p.puuid ? userOf(p.puuid) : undefined,
}));
const evRows = store.events(m.id);
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? ORDER BY started_at').all(m.id) as any[];
const vmap = m.game === 'valorant' ? d.games.assets.valMap(m.map) : null;
return {
...sum,
players,
rounds: m.game === 'valorant' ? det.roundsDetail ?? roundsFromTable(store, m.id, m.clock_offset) : undefined,
goldDiff: m.game === 'lol' ? det.goldDiff ?? [] : undefined,
events: evRows.map((e) => timeline.eventItem(e)),
utterances: utts.map((u) => timeline.utteranceItem(u)),
mapTransform:
m.game === 'valorant'
? vmap
? { valorant: { xMultiplier: vmap.xMultiplier, yMultiplier: vmap.yMultiplier, xScalarToAdd: vmap.xScalarToAdd, yScalarToAdd: vmap.yScalarToAdd } }
: null
: { lol: { minX: -120, minY: -120, maxX: 14870, maxY: 14980 } },
};
});
app.patch<{ Params: { id: string }; Body: { text?: string } }>('/api/utterances/:id', async (req, reply) => {
const u = store.getUtterance(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found' });
const text = String(req.body?.text ?? '').trim().slice(0, 1000);
if (!text) return reply.code(400).send({ error: 'empty_text' });
const old = u.text ?? u.raw_text ?? '';
const words = realignWords(safeJson<Word[]>(u.words, []), text, (u.ended_at - u.started_at) / 1000);
store.correctUtterance(u.id, text, words);
const s = d.settings();
if (s.dictionary.applySiteCorrections && old) d.dict.learn(old, text);
// 학습 데이터: 고친 문장 + 음성 조각 (자동 삭제 제외, A3). 녹음 제외 유저는 넣지 않는다.
const user = store.getUser(u.user_id);
if (u.audio_path && !u.audio_deleted && fs.existsSync(u.audio_path) && !user?.excluded) {
const dir = d.trainingDir();
fs.mkdirSync(dir, { recursive: true });
const dest = path.join(dir, `${u.id}.ogg`);
if (!fs.existsSync(dest)) fs.copyFileSync(u.audio_path, dest);
store.addTrainingSample({ id: u.id, utterance_id: u.id, text, audio_path: dest });
}
const item = timeline.utteranceItem(store.getUtterance(u.id)!);
d.bus.live({ type: 'utterance.updated', data: item });
return item;
});
app.get('/api/dictionary', async () => ({
labels: d.dict.labels,
entries: store.listDict().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 })),
}));
return app;
}
function roundsFromTable(store: Store, matchId: string, offset: number) {
return store.rounds(matchId).map((r) => ({
num: r.num,
startedAt: r.started_at + offset,
endedAt: r.ended_at + offset,
win: !!r.win,
result: r.result ?? '',
score: { ally: r.ally_score ?? 0, enemy: r.enemy_score ?? 0 },
economy: safeJson(r.economy, {}),
}));
}
/** 고친 문장에 단어 시각을 다시 붙인다. 단어 수가 같으면 기존 시각, 다르면 길이 비례 배분 */
export function realignWords(old: Word[], text: string, durationS: number): Word[] {
const toks = text.split(/\s+/).filter(Boolean);
if (old.length === toks.length) return toks.map((w, i) => ({ ...old[i], w }));
const start = old.length ? old[0].s : 0;
const end = old.length ? old[old.length - 1].e : durationS;
const total = toks.reduce((n, t) => n + [...t].length, 0) || 1;
let t = start;
return toks.map((w) => {
const len = ((end - start) * [...w].length) / total;
const out = { w, s: round2(t), e: round2(t + len) };
t += len;
return out;
});
}
const round2 = (x: number) => Math.round(x * 100) / 100;

44
app/src/core/cli.ts Normal file
View File

@@ -0,0 +1,44 @@
// 헤드리스 실행 (리눅스 개발·테스트용). Electron 없이 코어만 돈다.
// GVR_DATA_DIR=... GVR_BOT_TOKEN=... npm run core
// npm run core -- --diagnose (M0 진단만 돌리고 종료)
import path from 'node:path';
import { runDiagnostics } from './diagnostics.js';
import { WorkerClient } from './stt/worker.js';
import { startCore } from './index.js';
async function main() {
const root = path.resolve(__dirname, '..', '..');
const dataDir = process.env.GVR_DATA_DIR || path.join(root, '.gvr-data');
const py = process.env.GVR_WORKER_PYTHON || path.join(root, '..', 'worker', '.venv', 'bin', 'python');
const worker = { cmd: py, args: ['-m', 'gvr_worker'], cwd: path.join(root, '..', 'worker') };
if (process.argv.includes('--diagnose')) {
const w = new WorkerClient({ ...worker, env: { GVR_DATA_DIR: dataDir, GVR_MODELS_DIR: process.env.GVR_MODELS_DIR || path.join(dataDir, 'models') } });
w.start();
await new Promise((r) => w.once('ready', r));
const items = await runDiagnostics({
worker: w,
resourcesDir: path.join(root, 'resources'),
logsDir: path.join(dataDir, 'logs'),
model: process.env.GVR_DIAG_MODEL || 'large-v3-turbo',
device: process.env.GVR_DIAG_DEVICE || 'cuda',
computeType: process.env.GVR_DIAG_COMPUTE || 'float16',
onItem: (it) => console.log(`${it.ok === null ? '·' : it.ok ? '✔' : '✘'} ${it.label}: ${it.detail}`),
});
await w.stop();
process.exit(items.some((i) => i.ok === false) ? 1 : 0);
}
const core = await startCore({
dataDir,
resourcesDir: path.join(root, 'resources'),
worker,
version: process.env.npm_package_version || '1.0.0',
apiPort: Number(process.env.GVR_API_PORT || 0),
});
const shutdown = async () => {
await core.stop();
process.exit(0);
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
}
void main();

399
app/src/core/db/db.ts Normal file
View File

@@ -0,0 +1,399 @@
import Database from 'better-sqlite3';
import fs from 'node:fs';
import path from 'node:path';
import { SCHEMA_SQL } from './schema.js';
import { colorFor } from '../util/ids.js';
export interface UserRow {
id: string;
name: string;
color: string;
avatar: string | null;
excluded: number;
gain_lufs: number | null;
gain_n: number;
updated_at: number;
}
export interface UtteranceRow {
rowid?: number;
id: string;
session_id: string | null;
user_id: string;
started_at: number;
ended_at: number;
audio_path: string | null;
audio_deleted: number;
text: string | null;
raw_text: string | null;
words: string;
noise: number;
noise_reason: string | null;
confidence: number | null;
lufs: number | null;
gain_db: number;
model: string | null;
status: string;
match_id: string | null;
corrected: number;
attempts: number;
created_at: number;
}
export interface MatchRow {
id: string;
game: 'valorant' | 'lol';
started_at: number;
ended_at: number | null;
map: string | null;
mode: string | null;
queue: string | null;
result: string | null;
detail: string | null;
status: string;
clock_offset: number;
}
export interface RoundRow {
match_id: string;
num: number;
started_at: number;
combat_at: number;
ended_at: number;
win: number | null;
result: string | null;
ally_score: number | null;
enemy_score: number | null;
economy: string | null;
}
export interface EventRow {
id: string;
match_id: string;
game: 'valorant' | 'lol';
type: string;
ts: number;
game_time_ms: number | null;
round: number | null;
actor_puuid: string | null;
target_puuid: string | null;
data: string;
}
export interface DictRow {
id: number;
word: string;
pack: string;
kind: 'hotword' | 'correction';
from_text: string;
source: 'builtin' | 'user' | 'site';
enabled: number;
hits: number;
created_at: number;
}
export class Store {
readonly db: Database.Database;
constructor(file: string) {
fs.mkdirSync(path.dirname(file), { recursive: true });
this.db = new Database(file);
this.db.exec(SCHEMA_SQL);
}
close(): void {
this.db.close();
}
// ---------------------------------------------------------------- users
upsertUser(u: { id: string; name: string; avatar: string | null }): UserRow {
const now = Date.now();
this.db
.prepare(
`INSERT INTO users(id,name,color,avatar,updated_at) VALUES(?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET name=excluded.name, avatar=excluded.avatar, updated_at=excluded.updated_at`,
)
.run(u.id, u.name, colorFor(u.id), u.avatar, now);
return this.getUser(u.id)!;
}
getUser(id: string): UserRow | undefined {
return this.db.prepare('SELECT * FROM users WHERE id=?').get(id) as UserRow | undefined;
}
listUsers(): UserRow[] {
return this.db.prepare('SELECT * FROM users ORDER BY name').all() as UserRow[];
}
setExcluded(id: string, excluded: boolean): void {
this.db.prepare('UPDATE users SET excluded=?, updated_at=? WHERE id=?').run(excluded ? 1 : 0, Date.now(), id);
}
/** 유저 평소 음량 누적 평균 (최근값에 가중치) */
updateGainProfile(id: string, lufs: number): void {
const u = this.getUser(id);
if (!u) return;
const n = Math.min(u.gain_n, 49);
const next = u.gain_lufs === null ? lufs : (u.gain_lufs * n + lufs) / (n + 1);
this.db.prepare('UPDATE users SET gain_lufs=?, gain_n=? WHERE id=?').run(next, u.gain_n + 1, id);
}
listAccounts(): { user_id: string; puuid: string; riot_id: string }[] {
return this.db.prepare('SELECT * FROM game_accounts').all() as any[];
}
setAccounts(userId: string, accounts: { puuid: string; riotId: string }[]): void {
const tx = this.db.transaction(() => {
this.db.prepare('DELETE FROM game_accounts WHERE user_id=?').run(userId);
for (const a of accounts)
this.db.prepare('INSERT OR REPLACE INTO game_accounts(user_id,puuid,riot_id) VALUES(?,?,?)').run(userId, a.puuid, a.riotId);
});
tx();
}
userIdForPuuid(puuid: string): string | undefined {
const r = this.db.prepare('SELECT user_id FROM game_accounts WHERE puuid=?').get(puuid) as any;
return r?.user_id;
}
// ---------------------------------------------------------------- sessions
startSession(id: string, guildId: string, channelId: string, channelName: string | null, at: number): void {
this.db
.prepare('INSERT INTO sessions(id,guild_id,channel_id,channel_name,started_at) VALUES(?,?,?,?,?)')
.run(id, guildId, channelId, channelName, at);
}
endSession(id: string, at: number): void {
this.db.prepare('UPDATE sessions SET ended_at=? WHERE id=?').run(at, id);
}
// ---------------------------------------------------------------- utterances
insertUtterance(u: Pick<UtteranceRow, 'id' | 'session_id' | 'user_id' | 'started_at' | 'ended_at' | 'audio_path' | 'match_id'>): UtteranceRow {
this.db
.prepare(
`INSERT INTO utterances(id,session_id,user_id,started_at,ended_at,audio_path,match_id,created_at)
VALUES(@id,@session_id,@user_id,@started_at,@ended_at,@audio_path,@match_id,@created_at)`,
)
.run({ ...u, created_at: Date.now() });
return this.getUtterance(u.id)!;
}
getUtterance(id: string): UtteranceRow | undefined {
return this.db.prepare('SELECT rowid,* FROM utterances WHERE id=?').get(id) as UtteranceRow | undefined;
}
updateUtteranceResult(
id: string,
r: {
text: string | null;
raw_text: string | null;
words: unknown[];
noise: boolean;
noise_reason: string | null;
confidence: number | null;
lufs: number | null;
gain_db: number;
model: string;
status: 'realtime' | 'precise';
},
): void {
// 사용자가 이미 고친 문장은 재변환 결과로 덮어쓰지 않는다
this.db
.prepare(
`UPDATE utterances SET
text = CASE WHEN corrected=1 THEN text ELSE @text END,
raw_text=@raw_text,
words = CASE WHEN corrected=1 THEN words ELSE @words END,
noise=@noise, noise_reason=@noise_reason, confidence=@confidence, lufs=@lufs, gain_db=@gain_db,
model=@model, status=@status
WHERE id=@id`,
)
.run({ ...r, id, words: JSON.stringify(r.words), noise: r.noise ? 1 : 0 });
}
markUtteranceFailed(id: string): void {
this.db.prepare(`UPDATE utterances SET status='failed', attempts=attempts+1 WHERE id=?`).run(id);
}
bumpAttempt(id: string): number {
this.db.prepare('UPDATE utterances SET attempts=attempts+1 WHERE id=?').run(id);
return (this.db.prepare('SELECT attempts FROM utterances WHERE id=?').get(id) as any)?.attempts ?? 0;
}
pendingUtterances(): UtteranceRow[] {
return this.db
.prepare(`SELECT rowid,* FROM utterances WHERE status='pending' AND audio_deleted=0 ORDER BY started_at`)
.all() as UtteranceRow[];
}
/** 경기 후 정밀 재변환 대상 */
realtimeUtterancesInRange(from: number, to: number): UtteranceRow[] {
return this.db
.prepare(
`SELECT rowid,* FROM utterances WHERE status IN ('realtime','pending') AND audio_deleted=0 AND corrected=0
AND started_at>=? AND started_at<=? ORDER BY started_at`,
)
.all(from, to) as UtteranceRow[];
}
correctUtterance(id: string, text: string, words: unknown[]): void {
this.db.prepare('UPDATE utterances SET text=?, words=?, corrected=1, noise=0 WHERE id=?').run(text, JSON.stringify(words), id);
}
assignMatch(matchId: string, from: number, to: number): number {
return this.db
.prepare('UPDATE utterances SET match_id=? WHERE started_at>=? AND started_at<=? AND (match_id IS NULL OR match_id=?)')
.run(matchId, from, to, matchId).changes;
}
/** 보관 기간 지난 음성 파일 목록 */
expiredAudio(before: number): { id: string; audio_path: string }[] {
return this.db
.prepare('SELECT id, audio_path FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND started_at<?')
.all(before) as any[];
}
markAudioDeleted(id: string): void {
this.db.prepare('UPDATE utterances SET audio_deleted=1 WHERE id=?').run(id);
}
// ---------------------------------------------------------------- matches
upsertMatch(m: Partial<MatchRow> & { id: string; game: 'valorant' | 'lol'; started_at: number }): MatchRow {
const cur = this.getMatch(m.id);
const row: MatchRow = {
ended_at: null,
map: null,
mode: null,
queue: null,
result: null,
detail: null,
status: 'live',
clock_offset: 0,
...(cur || {}),
...stripUndef(m),
} as MatchRow;
this.db
.prepare(
`INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset)
VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset)
ON CONFLICT(id) DO UPDATE SET started_at=@started_at, ended_at=@ended_at, map=@map, mode=@mode, queue=@queue,
result=@result, detail=@detail, status=@status, clock_offset=@clock_offset`,
)
.run(row);
return this.getMatch(m.id)!;
}
getMatch(id: string): MatchRow | undefined {
return this.db.prepare('SELECT * FROM matches WHERE id=?').get(id) as MatchRow | undefined;
}
listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[] }): MatchRow[] {
const where: string[] = [];
const args: any[] = [];
if (opts.game) {
where.push('game=?');
args.push(opts.game);
}
if (opts.before) {
where.push('started_at<?');
args.push(opts.before);
}
if (opts.ids) {
if (!opts.ids.length) return [];
where.push(`id IN (${opts.ids.map(() => '?').join(',')})`);
args.push(...opts.ids);
}
return this.db
.prepare(`SELECT * FROM matches ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY started_at DESC LIMIT ?`)
.all(...args, opts.limit ?? 50) as MatchRow[];
}
/** ts 시점에 진행 중이던 경기 */
matchAt(ts: number): MatchRow | undefined {
return this.db
.prepare('SELECT * FROM matches WHERE started_at<=? AND (ended_at IS NULL OR ended_at>=?) ORDER BY started_at DESC LIMIT 1')
.get(ts, ts) as MatchRow | undefined;
}
replaceRounds(matchId: string, rounds: RoundRow[]): void {
const tx = this.db.transaction(() => {
this.db.prepare('DELETE FROM rounds WHERE match_id=?').run(matchId);
const st = this.db.prepare(
`INSERT INTO rounds(match_id,num,started_at,combat_at,ended_at,win,result,ally_score,enemy_score,economy)
VALUES(@match_id,@num,@started_at,@combat_at,@ended_at,@win,@result,@ally_score,@enemy_score,@economy)`,
);
for (const r of rounds) st.run(r);
});
tx();
}
rounds(matchId: string): RoundRow[] {
return this.db.prepare('SELECT * FROM rounds WHERE match_id=? ORDER BY num').all(matchId) as RoundRow[];
}
roundsForMatches(ids: string[]): Map<string, RoundRow[]> {
const out = new Map<string, RoundRow[]>();
if (!ids.length) return out;
const rows = this.db
.prepare(`SELECT * FROM rounds WHERE match_id IN (${ids.map(() => '?').join(',')}) ORDER BY num`)
.all(...ids) as RoundRow[];
for (const r of rows) {
if (!out.has(r.match_id)) out.set(r.match_id, []);
out.get(r.match_id)!.push(r);
}
return out;
}
// ---------------------------------------------------------------- events
insertEvent(e: EventRow): boolean {
return (
this.db
.prepare(
`INSERT OR IGNORE INTO game_events(id,match_id,game,type,ts,game_time_ms,round,actor_puuid,target_puuid,data)
VALUES(@id,@match_id,@game,@type,@ts,@game_time_ms,@round,@actor_puuid,@target_puuid,@data)`,
)
.run(e).changes > 0
);
}
replaceEvents(matchId: string, types: string[], events: EventRow[]): void {
const tx = this.db.transaction(() => {
this.db
.prepare(`DELETE FROM game_events WHERE match_id=? AND type IN (${types.map(() => '?').join(',')})`)
.run(matchId, ...types);
for (const e of events) this.insertEvent(e);
});
tx();
}
events(matchId: string): EventRow[] {
return this.db.prepare('SELECT * FROM game_events WHERE match_id=? ORDER BY ts').all(matchId) as EventRow[];
}
// ---------------------------------------------------------------- dictionary
addDict(d: Omit<DictRow, 'id' | 'created_at' | 'hits' | 'enabled'> & { enabled?: number }): void {
this.db
.prepare(
`INSERT INTO dictionary(word,pack,kind,from_text,source,enabled,created_at) VALUES(?,?,?,?,?,?,?)
ON CONFLICT(kind,word,from_text) DO UPDATE SET pack=excluded.pack, enabled=excluded.enabled`,
)
.run(d.word, d.pack, d.kind, d.from_text ?? '', d.source, d.enabled ?? 1, Date.now());
}
listDict(): DictRow[] {
return this.db.prepare('SELECT * FROM dictionary ORDER BY pack, word').all() as DictRow[];
}
deleteDict(id: number): void {
this.db.prepare('DELETE FROM dictionary WHERE id=?').run(id);
}
setDictEnabled(id: number, enabled: boolean): void {
this.db.prepare('UPDATE dictionary SET enabled=? WHERE id=?').run(enabled ? 1 : 0, id);
}
hitDict(words: string[]): void {
const st = this.db.prepare(`UPDATE dictionary SET hits=hits+1 WHERE kind='hotword' AND word=?`);
for (const w of words) st.run(w);
}
// ---------------------------------------------------------------- training
addTrainingSample(s: { id: string; utterance_id: string; text: string; audio_path: string }): void {
this.db
.prepare(
`INSERT INTO training_samples(id,utterance_id,text,audio_path,created_at) VALUES(?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET text=excluded.text`,
)
.run(s.id, s.utterance_id, s.text, s.audio_path, Date.now());
}
trainingSamples(): { id: string; utterance_id: string; text: string; audio_path: string; used: number; created_at: number }[] {
return this.db.prepare('SELECT * FROM training_samples ORDER BY created_at').all() as any[];
}
clearTraining(): void {
this.db.prepare('DELETE FROM training_samples').run();
}
// ---------------------------------------------------------------- stats
counts(): { utterances: number; matches: number } {
const u = (this.db.prepare('SELECT count(*) n FROM utterances').get() as any).n;
const m = (this.db.prepare('SELECT count(*) n FROM matches').get() as any).n;
return { utterances: u, matches: m };
}
meta(key: string): string | undefined {
return (this.db.prepare('SELECT value FROM meta WHERE key=?').get(key) as any)?.value;
}
setMeta(key: string, value: string): void {
this.db.prepare('INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key, value);
}
}
function stripUndef<T extends object>(o: T): Partial<T> {
const out: any = {};
for (const [k, v] of Object.entries(o)) if (v !== undefined) out[k] = v;
return out;
}

138
app/src/core/db/schema.sql Normal file
View File

@@ -0,0 +1,138 @@
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
color TEXT NOT NULL,
avatar TEXT,
excluded INTEGER NOT NULL DEFAULT 0,
gain_lufs REAL,
gain_n INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS game_accounts (
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
puuid TEXT NOT NULL,
riot_id TEXT NOT NULL,
PRIMARY KEY (user_id, puuid)
);
CREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
channel_name TEXT,
started_at INTEGER NOT NULL,
ended_at INTEGER
);
CREATE TABLE IF NOT EXISTS utterances (
id TEXT PRIMARY KEY,
session_id TEXT,
user_id TEXT NOT NULL,
started_at INTEGER NOT NULL,
ended_at INTEGER NOT NULL,
audio_path TEXT,
audio_deleted INTEGER NOT NULL DEFAULT 0,
text TEXT,
raw_text TEXT,
words TEXT NOT NULL DEFAULT '[]',
noise INTEGER NOT NULL DEFAULT 0,
noise_reason TEXT,
confidence REAL,
lufs REAL,
gain_db REAL NOT NULL DEFAULT 0,
model TEXT,
status TEXT NOT NULL DEFAULT 'pending',
match_id TEXT,
corrected INTEGER NOT NULL DEFAULT 0,
attempts INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);
CREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);
CREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);
CREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);
CREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');
CREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN
INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));
END;
CREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN
INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));
END;
CREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN
INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));
INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));
END;
CREATE TABLE IF NOT EXISTS matches (
id TEXT PRIMARY KEY,
game TEXT NOT NULL,
started_at INTEGER NOT NULL,
ended_at INTEGER,
map TEXT,
mode TEXT,
queue TEXT,
result TEXT,
detail TEXT,
status TEXT NOT NULL DEFAULT 'live',
clock_offset INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);
CREATE TABLE IF NOT EXISTS rounds (
match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,
num INTEGER NOT NULL,
started_at INTEGER NOT NULL,
combat_at INTEGER NOT NULL,
ended_at INTEGER NOT NULL,
win INTEGER,
result TEXT,
ally_score INTEGER,
enemy_score INTEGER,
economy TEXT,
PRIMARY KEY (match_id, num)
);
CREATE TABLE IF NOT EXISTS game_events (
id TEXT PRIMARY KEY,
match_id TEXT NOT NULL,
game TEXT NOT NULL,
type TEXT NOT NULL,
ts INTEGER NOT NULL,
game_time_ms INTEGER,
round INTEGER,
actor_puuid TEXT,
target_puuid TEXT,
data TEXT NOT NULL DEFAULT '{}'
);
CREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);
CREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);
CREATE TABLE IF NOT EXISTS dictionary (
id INTEGER PRIMARY KEY AUTOINCREMENT,
word TEXT NOT NULL,
pack TEXT NOT NULL,
kind TEXT NOT NULL,
from_text TEXT NOT NULL DEFAULT '',
source TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
hits INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
UNIQUE (kind, word, from_text)
);
CREATE TABLE IF NOT EXISTS training_samples (
id TEXT PRIMARY KEY,
utterance_id TEXT,
text TEXT NOT NULL,
audio_path TEXT NOT NULL,
used INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);

View File

@@ -0,0 +1,2 @@
// 자동 생성: schema.sql 사본 (npm run build 가 다시 만든다)
export const SCHEMA_SQL = "PRAGMA journal_mode = WAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);\n\nCREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n color TEXT NOT NULL,\n avatar TEXT,\n excluded INTEGER NOT NULL DEFAULT 0,\n gain_lufs REAL,\n gain_n INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS game_accounts (\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n puuid TEXT NOT NULL,\n riot_id TEXT NOT NULL,\n PRIMARY KEY (user_id, puuid)\n);\nCREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);\n\nCREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n guild_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n channel_name TEXT,\n started_at INTEGER NOT NULL,\n ended_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS utterances (\n id TEXT PRIMARY KEY,\n session_id TEXT,\n user_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n audio_path TEXT,\n audio_deleted INTEGER NOT NULL DEFAULT 0,\n text TEXT,\n raw_text TEXT,\n words TEXT NOT NULL DEFAULT '[]',\n noise INTEGER NOT NULL DEFAULT 0,\n noise_reason TEXT,\n confidence REAL,\n lufs REAL,\n gain_db REAL NOT NULL DEFAULT 0,\n model TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n match_id TEXT,\n corrected INTEGER NOT NULL DEFAULT 0,\n attempts INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);\nCREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');\nCREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\n\nCREATE TABLE IF NOT EXISTS matches (\n id TEXT PRIMARY KEY,\n game TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER,\n map TEXT,\n mode TEXT,\n queue TEXT,\n result TEXT,\n detail TEXT,\n status TEXT NOT NULL DEFAULT 'live',\n clock_offset INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);\n\nCREATE TABLE IF NOT EXISTS rounds (\n match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,\n num INTEGER NOT NULL,\n started_at INTEGER NOT NULL,\n combat_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n win INTEGER,\n result TEXT,\n ally_score INTEGER,\n enemy_score INTEGER,\n economy TEXT,\n PRIMARY KEY (match_id, num)\n);\n\nCREATE TABLE IF NOT EXISTS game_events (\n id TEXT PRIMARY KEY,\n match_id TEXT NOT NULL,\n game TEXT NOT NULL,\n type TEXT NOT NULL,\n ts INTEGER NOT NULL,\n game_time_ms INTEGER,\n round INTEGER,\n actor_puuid TEXT,\n target_puuid TEXT,\n data TEXT NOT NULL DEFAULT '{}'\n);\nCREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);\nCREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);\n\nCREATE TABLE IF NOT EXISTS dictionary (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n word TEXT NOT NULL,\n pack TEXT NOT NULL,\n kind TEXT NOT NULL,\n from_text TEXT NOT NULL DEFAULT '',\n source TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n UNIQUE (kind, word, from_text)\n);\n\nCREATE TABLE IF NOT EXISTS training_samples (\n id TEXT PRIMARY KEY,\n utterance_id TEXT,\n text TEXT NOT NULL,\n audio_path TEXT NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n";

157
app/src/core/diagnostics.ts Normal file
View File

@@ -0,0 +1,157 @@
import fs from 'node:fs';
import path from 'node:path';
import { basicAuth, findLcu, readLockfile, request, riotClientLockfilePath } from './games/riot.js';
import { decodePresence } from './games/valorant.js';
import type { WorkerClient } from './stt/worker.js';
export interface DiagItem {
id: string;
label: string;
ok: boolean | null; // null = 확인 불가(게임 꺼짐 등)
detail: string;
data?: unknown;
}
/**
* M0 기술 검증을 게임 PC 에서 그대로 돌리는 진단. 설정 창 "진단" 탭과 `--diagnose` 에서 쓴다.
* 결과 JSON 은 GVR-Data/logs/diagnostics-<시각>.json 에 남는다.
*/
export async function runDiagnostics(opts: {
worker: WorkerClient;
resourcesDir: string;
logsDir: string;
model: string;
device: string;
computeType: string;
lolLogsDir?: string | null;
onItem?: (it: DiagItem) => void;
}): Promise<DiagItem[]> {
const out: DiagItem[] = [];
const add = (it: DiagItem) => {
out.push(it);
opts.onItem?.(it);
};
// 1. GPU
try {
const g = await opts.worker.request('gpu_info', {}, 30000);
const gpu = g.gpus?.[0];
add({
id: 'gpu',
label: 'NVIDIA GPU',
ok: !!gpu,
detail: gpu ? `${gpu.name} · VRAM ${(gpu.vram_total_mb / 1024).toFixed(1)}GB · 드라이버 ${gpu.driver} (CUDA ${gpu.cuda_driver ?? '?'})` : 'NVIDIA GPU 를 찾지 못했습니다',
data: g,
});
} catch (e: any) {
add({ id: 'gpu', label: 'NVIDIA GPU', ok: false, detail: e.message });
}
// 2. STT 속도·VRAM
try {
const models = await opts.worker.request('models', {}, 30000);
const m = (models.models || []).find((x: any) => x.name === opts.model);
if (!m?.installed) add({ id: 'stt', label: `STT 속도 (${opts.model})`, ok: null, detail: '모델이 아직 없습니다. STT 모델 탭에서 내려받은 뒤 다시 실행하세요.' });
else {
const t0 = Date.now();
const ld = await opts.worker.request('load', { slot: 'precise', model: opts.model, device: opts.device, compute_type: opts.computeType }, 15 * 60000);
const loadMs = Date.now() - t0;
const sample = path.join(opts.resourcesDir, 'diag', 'speech_ko.ogg');
const runs: number[] = [];
let text = '';
for (let i = 0; i < 3; i++) {
const r = await opts.worker.request('transcribe', { slot: 'precise', path: sample, hotwords: '레이즈 로테 B 사이트', corrections: [], dictionary: [], target_lufs: -18, noise_sensitivity: 0.5, denoise: false, profile_lufs: null }, 120000);
runs.push(r.elapsed_ms);
text = r.text ?? '';
}
const g = await opts.worker.request('gpu_info', {}, 30000).catch(() => null);
await opts.worker.request('unload', { slot: 'precise' }, 60000).catch(() => undefined);
const dur = 3.6;
const best = Math.min(...runs);
add({
id: 'stt',
label: `STT 속도 (${opts.model})`,
ok: best < dur * 1000,
detail: `적재 ${(loadMs / 1000).toFixed(1)}초 · ${dur}초 음성 변환 ${best}ms (실시간의 ${(dur * 1000 / best).toFixed(1)}배) · VRAM 사용 ${g?.gpus?.[0]?.vram_used_mb ?? '?'}MB · "${text}"${ld?.fallback ? ' · GPU 없음 → CPU' : ''}`,
data: { loadMs, runs, text, gpu: g },
});
}
} catch (e: any) {
add({ id: 'stt', label: `STT 속도 (${opts.model})`, ok: false, detail: e.message });
}
// 3. 발로란트 (Riot Client 로컬 API)
const lf = readLockfile(riotClientLockfilePath());
if (!lf) add({ id: 'valorant', label: '발로란트 로컬 API', ok: null, detail: 'Riot 클라이언트가 실행 중이 아닙니다 (발로란트를 켜고 다시 실행)' });
else {
try {
const h = { authorization: basicAuth(lf.password) };
const ent = await request(`https://127.0.0.1:${lf.port}/entitlements/v1/token`, { headers: h, local: true });
const pres = await request(`https://127.0.0.1:${lf.port}/chat/v4/presences`, { headers: h, local: true });
const mine = (pres.data?.presences || []).find((p: any) => p.puuid === ent.data?.subject && p.product === 'valorant');
const p = mine?.private ? decodePresence(mine.private) : null;
add({
id: 'valorant',
label: '발로란트 로컬 API',
ok: ent.status === 200,
detail: ent.status === 200 ? `로그인 확인 · 상태 ${p?.state ?? '발로란트 꺼짐'}${p?.map ? ` · 맵 ${p.map}` : ''}` : `인증 실패 (${ent.status})`,
data: { presence: p },
});
} catch (e: any) {
add({ id: 'valorant', label: '발로란트 로컬 API', ok: false, detail: e.message });
}
}
// 4. 롤 게임 클라이언트 API · LCU
try {
const r = await request('https://127.0.0.1:2999/liveclientdata/gamestats', { local: true, timeoutMs: 1500 });
add({ id: 'lol-live', label: '롤 게임 클라이언트 API (2999)', ok: r.status === 200, detail: r.status === 200 ? `게임 중 · 게임 시간 ${Math.round(r.data.gameTime)}초` : `응답 ${r.status}` });
} catch {
add({ id: 'lol-live', label: '롤 게임 클라이언트 API (2999)', ok: null, detail: '게임 중이 아닙니다 (롤 게임에 들어가서 실행하면 확인됩니다)' });
}
const lcu = await findLcu().catch(() => null);
if (!lcu) add({ id: 'lcu', label: '롤 클라이언트 (LCU)', ok: null, detail: '롤 클라이언트가 실행 중이 아닙니다' });
else {
const h = { authorization: basicAuth(lcu.password) };
const base = `https://127.0.0.1:${lcu.port}`;
const me = await request(`${base}/lol-summoner/v1/current-summoner`, { headers: h, local: true }).catch(() => null);
// 최근 경기 하나로 타임라인(킬 위치·골드) 조회가 되는지
const hist = await request(`${base}/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=0&endIndex=1`, { headers: h, local: true }).catch(() => null);
const gid = hist?.data?.games?.games?.[0]?.gameId;
const tl = gid ? await request(`${base}/lol-match-history/v1/game-timelines/${gid}`, { headers: h, local: true }).catch(() => null) : null;
add({
id: 'lcu',
label: '롤 클라이언트 (LCU) · 타임라인',
ok: me?.status === 200,
detail: `${me?.data?.gameName ? `로그인: ${me.data.gameName}#${me.data.tagLine}` : '로그인 정보 없음'} · 최근 경기 타임라인 ${tl?.status === 200 && tl.data?.frames ? `조회 가능 (프레임 ${tl.data.frames.length})` : gid ? '조회 불가 → 킬 위치·골드 그래프에 공식 API 키 필요' : '최근 경기 없음'}`,
data: { installDir: lcu.installDir, timeline: tl?.status ?? null },
});
}
// 5. 채팅 OCR (한국어 OCR 설치 여부 + 정확도)
try {
const r = await opts.worker.request('ocr_image', { path: path.join(opts.resourcesDir, 'diag', 'lol-chat-sample.png'), lang: 'ko' }, 60000);
const lines: string[] = (r.lines || []).map((l: any) => l.text ?? l);
const expect = ['드래곤 가자', 'gg', '바텀 갱 간다'];
const hit = expect.filter((e) => lines.some((l) => l.replace(/\s/g, '').includes(e.replace(/\s/g, '')))).length;
add({ id: 'ocr', label: '채팅 OCR (한국어)', ok: hit >= 2, detail: `예시 3줄 중 ${hit}줄 인식: ${lines.join(' / ')}`, data: r });
} catch (e: any) {
add({ id: 'ocr', label: '채팅 OCR (한국어)', ok: false, detail: e.message });
}
// 6. r3dlog 채팅
const logs = opts.lolLogsDir || (lcu?.installDir ? path.join(lcu.installDir, 'Logs', 'GameLogs') : null);
if (!logs || !fs.existsSync(logs)) add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: null, detail: '로그 폴더를 찾지 못했습니다 (롤을 한 판 한 뒤 확인)' });
else {
try {
const r = await opts.worker.request('r3dlog_check', { logs_dir: logs }, 30000);
add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: r.found_chat, detail: r.found_chat ? `채팅이 남아 있음 → OCR 대신 사용 (${r.file})` : '로그에 채팅이 없음 → 화면 OCR 사용', data: r });
} catch (e: any) {
add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: false, detail: e.message });
}
}
fs.mkdirSync(opts.logsDir, { recursive: true });
fs.writeFileSync(path.join(opts.logsDir, `diagnostics-${new Date().toISOString().replace(/[:.]/g, '-')}.json`), JSON.stringify(out, null, 2));
return out;
}

View File

@@ -0,0 +1,177 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Store, DictRow } from '../db/db.js';
import { logger } from '../util/log.js';
const log = logger('dict');
export type DictContext = 'valorant' | 'lol' | 'none';
/** 상황별로 우선 쓰는 묶음 (앞쪽이 우선) */
const CONTEXT_PACKS: Record<DictContext, string[]> = {
valorant: ['site', 'user', 'valorant', 'valorant_callouts', 'game', 'slang20s', 'daily'],
lol: ['site', 'user', 'lol', 'lol_skills', 'game', 'slang20s', 'daily'],
none: ['site', 'user', 'daily', 'university', 'slang20s', 'game', 'valorant', 'lol'],
};
/** Whisper 프롬프트 길이 제한 때문에 핫워드는 이 정도까지만 */
const MAX_HOTWORDS = 60;
export interface PackFile {
meta: { generatedAt: string };
packs: Record<string, { label: string; words: string[] }>;
}
export class Dictionary {
private cache: { rows: DictRow[]; at: number } | null = null;
labels: Record<string, string> = { site: '사이트 교정', user: '사용자 단어' };
constructor(
private store: Store,
private resourcesDir: string,
private enabledPacks: () => Record<string, boolean>,
) {}
/** 기본 사전을 DB 에 넣는다. 파일이 바뀌었을 때만. */
seed(): void {
const packFile = path.join(this.resourcesDir, 'dictionary', 'packs.json');
const corrFile = path.join(this.resourcesDir, 'dictionary', 'corrections.json');
let data: PackFile;
try {
data = JSON.parse(fs.readFileSync(packFile, 'utf8'));
} catch (e) {
log.warn(`기본 사전 파일 없음: ${packFile}`);
return;
}
for (const [k, p] of Object.entries(data.packs)) this.labels[k] = p.label;
const version = data.meta.generatedAt;
if (this.store.meta('dict_version') === version) return;
const corrections: { from: string; to: string }[] = fs.existsSync(corrFile) ? JSON.parse(fs.readFileSync(corrFile, 'utf8')) : [];
const tx = this.store.db.transaction(() => {
this.store.db.prepare(`DELETE FROM dictionary WHERE source='builtin'`).run();
for (const [pack, p] of Object.entries(data.packs))
for (const w of p.words) this.store.addDict({ word: w, pack, kind: 'hotword', from_text: '', source: 'builtin' });
for (const c of corrections)
this.store.addDict({ word: c.to, pack: 'corrections', kind: 'correction', from_text: c.from, source: 'builtin' });
});
tx();
this.store.setMeta('dict_version', version);
this.cache = null;
log.info(`기본 사전 적재: ${Object.values(data.packs).reduce((n, p) => n + p.words.length, 0)}단어, 교정 ${corrections.length}개`);
}
invalidate(): void {
this.cache = null;
}
private rows(): DictRow[] {
if (!this.cache || Date.now() - this.cache.at > 60000) this.cache = { rows: this.store.listDict(), at: Date.now() };
return this.cache.rows;
}
private packOn(pack: string): boolean {
if (pack === 'site' || pack === 'user' || pack === 'corrections') return true;
const en = this.enabledPacks();
// 하위 묶음은 상위 묶음 설정을 따른다 (valorant_callouts → valorant)
const parent = pack.split('_')[0];
return en[pack] ?? en[parent] ?? true;
}
/** extra: 지금 경기에 나온 요원·챔피언·선수 이름 (가장 먼저 넣는다) */
hotwords(ctx: DictContext, extra: string[] = []): string {
const order = CONTEXT_PACKS[ctx];
const rows = this.rows().filter((r) => r.kind === 'hotword' && r.enabled && this.packOn(r.pack) && order.includes(r.pack));
// 묶음 순서 → 많이 나온 단어 → 사전 파일 순서(중요한 고유명사가 앞에 있음)
rows.sort((a, b) => order.indexOf(a.pack) - order.indexOf(b.pack) || b.hits - a.hits || a.id - b.id);
const out: string[] = [];
const seen = new Set<string>();
for (const w of extra) {
const t = w.trim();
if (!t || seen.has(t)) continue;
seen.add(t);
out.push(t);
}
for (const r of rows) {
if (seen.has(r.word)) continue;
seen.add(r.word);
out.push(r.word);
if (out.length >= MAX_HOTWORDS) break;
}
return out.join(' ');
}
corrections(): { from: string; to: string }[] {
return this.rows()
.filter((r) => r.kind === 'correction' && r.enabled && r.from_text)
.map((r) => ({ from: r.from_text, to: r.word }));
}
/** 자모 유사도 교정 후보 (상황 묶음의 단어, 2글자 이상) */
candidates(ctx: DictContext): string[] {
const order = CONTEXT_PACKS[ctx];
const set = new Set<string>();
for (const r of this.rows())
if (r.kind === 'hotword' && r.enabled && this.packOn(r.pack) && order.includes(r.pack) && r.word.length >= 2) set.add(r.word);
return [...set];
}
/**
* 사이트에서 고친 문장을 사전에 반영한다. 단어 단위로 맞춰 보고 바뀐 단어를 교정 규칙으로,
* 고친 쪽 단어를 핫워드로 넣는다. 반환: 추가된 규칙 수
*/
learn(raw: string, corrected: string): number {
const pairs = diffWords(raw, corrected);
let n = 0;
for (const [from, to] of pairs) {
if (!from || !to || from === to || from.length > 20 || to.length > 20) continue;
this.store.addDict({ word: to, pack: 'site', kind: 'correction', from_text: from, source: 'site' });
this.store.addDict({ word: to.replace(/\s+/g, ''), pack: 'site', kind: 'hotword', from_text: '', source: 'site' });
n++;
}
if (n) this.invalidate();
return n;
}
}
/**
* 두 문장을 단어 단위로 정렬(LCS)해서 바뀐 구간 쌍을 돌려준다.
* 예: "레이저 궁 빠졌어" → "레이즈 궁 빠졌어" ⇒ [["레이저","레이즈"]]
*/
export function diffWords(a: string, b: string): [string, string][] {
const x = a.trim().split(/\s+/).filter(Boolean);
const y = b.trim().split(/\s+/).filter(Boolean);
const n = x.length;
const m = y.length;
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) dp[i][j] = x[i] === y[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
const out: [string, string][] = [];
let i = 0;
let j = 0;
let bufA: string[] = [];
let bufB: string[] = [];
const flush = () => {
if (bufA.length && bufB.length) {
if (bufA.length === bufB.length && bufA.length > 1) {
// 단어 수가 같으면 한 단어씩 짝짓되, 한 글자짜리("비")는 문맥 없이 규칙이 되면 위험하니 다음 단어와 묶는다
let i = 0;
while (i < bufA.length) {
let j = i + 1;
while (j < bufA.length && [...bufA.slice(i, j).join('')].length < 2) j++;
out.push([bufA.slice(i, j).join(' '), bufB.slice(i, j).join(' ')]);
i = j;
}
} else out.push([bufA.join(' '), bufB.join(' ')]);
}
bufA = [];
bufB = [];
};
while (i < n || j < m) {
if (i < n && j < m && x[i] === y[j]) {
flush();
i++;
j++;
} else if (j < m && (i >= n || dp[i][j + 1] >= dp[i + 1][j])) bufB.push(y[j++]);
else bufA.push(x[i++]);
}
flush();
return out;
}

318
app/src/core/discord/bot.ts Normal file
View File

@@ -0,0 +1,318 @@
import {
AudioPlayerStatus,
createAudioPlayer,
createAudioResource,
entersState,
joinVoiceChannel,
NoSubscriberBehavior,
StreamType,
VoiceConnectionStatus,
type AudioPlayer,
type VoiceConnection,
} from '@discordjs/voice';
import {
ChannelType,
Client,
Events,
GatewayIntentBits,
MessageFlags,
type ChatInputCommandInteraction,
type Guild,
type GuildMember,
type VoiceBasedChannel,
type VoiceState,
} from 'discord.js';
import fs from 'node:fs';
import type { Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { Bus } from '../util/events.js';
import { newId } from '../util/ids.js';
import { logger } from '../util/log.js';
import type { Recorder } from './recorder.js';
import type { Announcer } from './tts.js';
const log = logger('bot');
export const COMMANDS = [
{ name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' },
{ name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' },
{ name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' },
{ name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' },
];
export interface BotState {
status: 'off' | 'connecting' | 'ready' | 'error';
error: string | null;
user: { id: string; name: string; avatar: string | null } | null;
guild: { id: string; name: string; icon: string | null } | null;
guilds: { id: string; name: string }[];
recording: { active: boolean; channel: string | null; channelId: string | null; since: number | null; participants: string[]; reason: 'follow' | 'command' | null };
}
/**
* 디스코드 봇: 나를 따라 음성채널에 들어가거나(/녹음시작) 명령으로 참여하고, TTS 로 녹음 사실을 알린다 (Q7, Q8).
* 채팅 메시지는 보내지 않는다. 명령 응답은 본인에게만 보인다.
*/
export class Bot {
client: Client | null = null;
private connection: VoiceConnection | null = null;
private player: AudioPlayer | null = null;
private sessionId: string | null = null;
private emptyTimer: NodeJS.Timeout | null = null;
state: BotState = {
status: 'off',
error: null,
user: null,
guild: null,
guilds: [],
recording: { active: false, channel: null, channelId: null, since: null, participants: [], reason: null },
};
constructor(
private store: Store,
private recorder: Recorder,
private announcer: Announcer,
private bus: Bus,
private settings: () => Settings,
private onGuild?: (guildId: string) => void,
) {}
async start(token: string): Promise<void> {
await this.stop();
this.state.status = 'connecting';
this.state.error = null;
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers],
});
this.client = client;
client.on(Events.ClientReady, () => void this.onReady());
client.on(Events.VoiceStateUpdate, (o, n) => void this.onVoiceState(o, n).catch((e) => log.error('voiceState 처리 오류', e)));
client.on(Events.InteractionCreate, (i) => {
if (i.isChatInputCommand()) void this.onCommand(i).catch((e) => log.error('명령 처리 오류', e));
});
client.on(Events.Error, (e) => log.error('discord 오류', e));
client.on(Events.GuildCreate, () => this.refreshGuilds());
try {
await client.login(token);
} catch (e: any) {
this.state.status = 'error';
this.state.error = e?.message?.includes('TOKEN_INVALID') || e?.code === 'TokenInvalid' ? '봇 토큰이 올바르지 않습니다' : e.message;
this.client = null;
throw e;
}
}
async stop(): Promise<void> {
this.leave('stop');
if (this.client) {
await this.client.destroy();
this.client = null;
}
this.state.status = 'off';
}
private refreshGuilds(): void {
if (!this.client) return;
this.state.guilds = [...this.client.guilds.cache.values()].map((g) => ({ id: g.id, name: g.name }));
}
guild(): Guild | null {
if (!this.client) return null;
const id = this.settings().discord.guildId;
return (id && this.client.guilds.cache.get(id)) || this.client.guilds.cache.first() || null;
}
private async onReady(): Promise<void> {
const c = this.client!;
this.state.status = 'ready';
this.state.user = { id: c.user!.id, name: c.user!.username, avatar: c.user!.displayAvatarURL({ size: 128 }) };
this.refreshGuilds();
const g = this.guild();
log.info(`봇 로그인: ${c.user!.tag}, 서버 ${this.state.guilds.map((x) => x.name).join(', ')}`);
if (!g) return;
this.state.guild = { id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) };
this.onGuild?.(g.id);
if (this.settings().discord.commandsEnabled) {
try {
await g.commands.set(COMMANDS);
log.info('슬래시 명령 등록 완료');
} catch (e) {
log.warn('슬래시 명령 등록 실패', e);
}
}
// 이미 따라갈 유저가 음성채널에 있으면 바로 들어간다
const follow = this.settings().discord.followUserId;
if (follow && this.settings().discord.followEnabled) {
const m = await g.members.fetch(follow).catch(() => null);
if (m?.voice.channel) await this.join(m.voice.channel, 'follow');
}
}
private async onVoiceState(o: VoiceState, n: VoiceState): Promise<void> {
const g = this.guild();
if (!g || n.guild.id !== g.id) return;
const s = this.settings().discord;
const uid = n.id;
if (uid === this.client?.user?.id) {
// 누군가 봇을 끊었으면 세션 종료
if (o.channelId && !n.channelId) this.leave('kicked');
return;
}
// 따라가기
if (s.followEnabled && s.followUserId === uid && o.channelId !== n.channelId) {
if (n.channel) await this.join(n.channel, 'follow');
else if (this.state.recording.reason === 'follow') this.leave('follow-left');
}
const myCh = this.state.recording.channelId;
if (!myCh) return;
// 새 사람이 들어오면 안내를 다시 튼다
if (n.channelId === myCh && o.channelId !== myCh && n.member && !n.member.user.bot) {
this.touchUser(n.member);
this.updateParticipants();
if (s.ttsEnabled && s.ttsOnNewMember) void this.announce();
}
if (o.channelId === myCh && n.channelId !== myCh) this.updateParticipants();
}
private touchUser(m: GuildMember): void {
this.store.upsertUser({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }) });
}
private updateParticipants(): void {
const ch = this.currentChannel();
const humans = ch ? [...ch.members.values()].filter((m) => !m.user.bot) : [];
this.state.recording.participants = humans.map((m) => m.id);
this.emitState();
// 사람이 아무도 없으면 30초 뒤 나간다
if (this.emptyTimer) clearTimeout(this.emptyTimer);
this.emptyTimer = null;
if (ch && humans.length === 0) this.emptyTimer = setTimeout(() => this.leave('empty'), 30000);
}
private currentChannel(): VoiceBasedChannel | null {
const id = this.state.recording.channelId;
if (!id || !this.client) return null;
const ch = this.client.channels.cache.get(id);
return ch && (ch.type === ChannelType.GuildVoice || ch.type === ChannelType.GuildStageVoice) ? (ch as VoiceBasedChannel) : null;
}
async join(channel: VoiceBasedChannel, reason: 'follow' | 'command'): Promise<void> {
if (this.state.recording.channelId === channel.id && this.connection) return;
if (this.connection) this.leave('move');
log.info(`음성채널 참여: ${channel.name} (${reason})`);
const conn = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false,
daveEncryption: true,
});
this.connection = conn;
conn.on('error', (e) => log.error('음성 연결 오류', e));
conn.on(VoiceConnectionStatus.Disconnected, async () => {
try {
await Promise.race([
entersState(conn, VoiceConnectionStatus.Signalling, 5000),
entersState(conn, VoiceConnectionStatus.Connecting, 5000),
]);
} catch {
if (this.connection === conn) this.leave('disconnected');
}
});
try {
await entersState(conn, VoiceConnectionStatus.Ready, 20000);
} catch (e) {
log.error('음성채널 연결 실패', e);
conn.destroy();
if (this.connection === conn) this.connection = null;
throw new Error('음성채널 연결 실패');
}
const now = Date.now();
this.sessionId = newId(now);
this.store.startSession(this.sessionId, channel.guild.id, channel.id, channel.name, now);
for (const m of channel.members.values()) if (!m.user.bot) this.touchUser(m);
this.bus.live({ type: 'users.updated', data: [] });
this.state.recording = { active: true, channel: channel.name, channelId: channel.id, since: now, participants: [], reason };
this.recorder.attach(conn, this.sessionId);
this.player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause } });
conn.subscribe(this.player);
this.updateParticipants();
if (this.settings().discord.ttsEnabled) void this.announce();
}
leave(why: string): void {
if (this.emptyTimer) clearTimeout(this.emptyTimer);
this.emptyTimer = null;
this.recorder.detach();
if (this.connection) {
log.info(`음성채널 나감 (${why})`);
try {
this.connection.destroy();
} catch {
/* 이미 끊김 */
}
}
this.connection = null;
this.player?.stop(true);
this.player = null;
if (this.sessionId) this.store.endSession(this.sessionId, Date.now());
this.sessionId = null;
if (this.state.recording.active) {
this.state.recording = { active: false, channel: null, channelId: null, since: null, participants: [], reason: null };
this.emitState();
}
}
async announce(): Promise<void> {
if (!this.player) return;
const s = this.settings().discord;
try {
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice);
if (!this.player) return;
const res = createAudioResource(fs.createReadStream(file), { inputType: StreamType.WebmOpus });
this.player.play(res);
await entersState(this.player, AudioPlayerStatus.Playing, 5000).catch(() => undefined);
} catch (e) {
log.warn('안내 음성 재생 실패', e);
}
}
private emitState(): void {
const r = this.state.recording;
this.bus.live({ type: 'recording.state', data: { active: r.active, channel: r.channel, since: r.since, participants: r.participants } });
}
private async onCommand(i: ChatInputCommandInteraction): Promise<void> {
const reply = (content: string) => i.reply({ content, flags: MessageFlags.Ephemeral });
const member = i.member as GuildMember | null;
switch (i.commandName) {
case '녹음시작': {
const ch = member?.voice?.channel;
if (!ch) return void (await reply('먼저 음성채널에 들어가 주세요.'));
await i.deferReply({ flags: MessageFlags.Ephemeral });
try {
await this.join(ch, 'command');
await i.editReply(`🎙️ ${ch.name} 채널 녹음을 시작했습니다.`);
} catch (e: any) {
await i.editReply(`음성채널에 들어가지 못했습니다: ${e.message}`);
}
return;
}
case '녹음종료':
if (!this.connection) return void (await reply('지금은 녹음 중이 아닙니다.'));
this.leave('command');
return void (await reply('⏹️ 녹음을 끝냈습니다.'));
case '녹음제외':
if (member) this.touchUser(member);
this.store.setExcluded(i.user.id, true);
this.bus.live({ type: 'users.updated', data: [] });
return void (await reply('🔇 이제부터 내 목소리는 녹음하지 않습니다. 다시 참여하려면 /녹음참여 를 입력하세요.'));
case '녹음참여':
if (member) this.touchUser(member);
this.store.setExcluded(i.user.id, false);
this.bus.live({ type: 'users.updated', data: [] });
return void (await reply('🎙️ 다시 녹음에 참여합니다.'));
}
}
}

129
app/src/core/discord/ogg.ts Normal file
View File

@@ -0,0 +1,129 @@
import fs from 'node:fs';
// Ogg Opus 파일 쓰기 (RFC 7845). 디스코드에서 받은 Opus 패킷을 다시 인코딩하지 않고 그대로 담는다.
const CRC_TABLE = (() => {
const t = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let r = i << 24;
for (let j = 0; j < 8; j++) r = r & 0x80000000 ? (r << 1) ^ 0x04c11db7 : r << 1;
t[i] = r >>> 0;
}
return t;
})();
function crc32(buf: Buffer): number {
let crc = 0;
for (let i = 0; i < buf.length; i++) crc = ((crc << 8) ^ CRC_TABLE[((crc >>> 24) & 0xff) ^ buf[i]]) >>> 0;
return crc >>> 0;
}
/** Opus 패킷 TOC 로 48kHz 기준 샘플 수 계산 */
export function opusSamples(packet: Buffer): number {
if (!packet.length) return 0;
const toc = packet[0];
const config = toc >> 3;
let frame: number;
if (config < 12) frame = [480, 960, 1920, 2880][config & 3];
else if (config < 16) frame = [480, 960][config & 1];
else frame = [120, 240, 480, 960][config & 3];
const c = toc & 3;
const count = c === 0 ? 1 : c === 3 ? (packet[1] ?? 0) & 0x3f : 2;
return frame * count;
}
/** 20ms 무음 Opus 프레임 (디스코드가 말이 끝날 때 보내는 것과 같은 값) */
export const SILENCE_FRAME = Buffer.from([0xf8, 0xff, 0xfe]);
export class OggOpusWriter {
private fd: number;
private serial = (Math.random() * 0xffffffff) >>> 0;
private seq = 0;
private granule = 0n;
private packets: Buffer[] = [];
private closed = false;
/** 담긴 오디오 길이 (48kHz 샘플) */
samples = 0;
bytes = 0;
constructor(
readonly path: string,
channels = 2,
) {
this.fd = fs.openSync(path, 'w');
const head = Buffer.alloc(19);
head.write('OpusHead', 0, 'ascii');
head[8] = 1;
head[9] = channels;
head.writeUInt16LE(0, 10); // pre-skip
head.writeUInt32LE(48000, 12);
head.writeInt16LE(0, 16);
head[18] = 0;
this.writePage([head], 0n, 0x02);
const vendor = Buffer.from('gvr', 'ascii');
const tags = Buffer.alloc(8 + 4 + vendor.length + 4);
tags.write('OpusTags', 0, 'ascii');
tags.writeUInt32LE(vendor.length, 8);
vendor.copy(tags, 12);
tags.writeUInt32LE(0, 12 + vendor.length);
this.writePage([tags], 0n, 0);
}
write(packet: Buffer): void {
if (this.closed) return;
this.packets.push(packet);
this.samples += opusSamples(packet);
if (this.packets.length >= 50) this.flush(false);
}
private flush(last: boolean): void {
if (!this.packets.length && !last) return;
this.granule = BigInt(this.samples);
this.writePage(this.packets, this.granule, last ? 0x04 : 0);
this.packets = [];
}
private writePage(packets: Buffer[], granule: bigint, flags: number): void {
const lacing: number[] = [];
for (const p of packets) {
let n = p.length;
while (n >= 255) {
lacing.push(255);
n -= 255;
}
lacing.push(n);
}
if (lacing.length > 255) {
// 한 페이지 최대 255 세그먼트. 넘으면 나눠 쓴다 (50패킷이면 생기지 않음)
const half = Math.ceil(packets.length / 2);
this.writePage(packets.slice(0, half), granule, flags & 0x02);
this.writePage(packets.slice(half), granule, flags & 0x04);
return;
}
const header = Buffer.alloc(27 + lacing.length);
header.write('OggS', 0, 'ascii');
header[4] = 0;
header[5] = flags;
header.writeBigInt64LE(granule, 6);
header.writeUInt32LE(this.serial, 14);
header.writeUInt32LE(this.seq++, 18);
header.writeUInt32LE(0, 22);
header[26] = lacing.length;
for (let i = 0; i < lacing.length; i++) header[27 + i] = lacing[i];
const page = Buffer.concat([header, ...packets]);
page.writeUInt32LE(crc32(page), 22);
fs.writeSync(this.fd, page);
this.bytes += page.length;
}
close(): void {
if (this.closed) return;
this.flush(true);
this.closed = true;
fs.closeSync(this.fd);
}
get durationMs(): number {
return Math.round(this.samples / 48);
}
}

View File

@@ -0,0 +1,151 @@
import fs from 'node:fs';
import path from 'node:path';
import { EndBehaviorType, type VoiceConnection } from '@discordjs/voice';
import type { Store } from '../db/db.js';
import type { SttPipeline } from '../stt/pipeline.js';
import type { Timeline } from '../timeline.js';
import type { Bus } from '../util/events.js';
import { newId } from '../util/ids.js';
import { logger } from '../util/log.js';
import { OggOpusWriter, SILENCE_FRAME } from './ogg.js';
const log = logger('rec');
export interface RecorderOptions {
audioDir: () => string;
silenceMs: () => number;
maxUtteranceSec: () => number;
/** 이 유저를 녹음하지 않는다 (/녹음제외, 봇) */
skip: (userId: string) => boolean;
/** ts 시점 진행 중인 경기 ID */
matchAt: (ts: number) => string | null;
}
/** 발화 하나 = 파일 하나. 말이 0.8초 끊기면 끝, 최대 30초 (보고서 4장 1~3단계) */
class Utterance {
writer: OggOpusWriter;
id: string;
startedAt: number;
lastArrival: number;
constructor(dir: string, now: number) {
this.id = newId(now);
this.startedAt = now;
this.lastArrival = now;
const day = localDay(now);
const d = path.join(dir, day);
fs.mkdirSync(d, { recursive: true });
this.writer = new OggOpusWriter(path.join(d, `${this.id}.ogg`));
}
}
function localDay(ts: number): string {
const d = new Date(ts);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
export class Recorder {
private active = new Map<string, Utterance>();
private connection: VoiceConnection | null = null;
private sessionId: string | null = null;
private onSpeak = (userId: string) => this.subscribe(userId);
constructor(
private store: Store,
private stt: SttPipeline,
private timeline: Timeline,
private bus: Bus,
private opts: RecorderOptions,
) {}
attach(connection: VoiceConnection, sessionId: string): void {
this.detach();
this.connection = connection;
this.sessionId = sessionId;
connection.receiver.speaking.on('start', this.onSpeak);
}
detach(): void {
if (this.connection) {
this.connection.receiver.speaking.off('start', this.onSpeak);
for (const s of this.connection.receiver.subscriptions.values()) s.destroy();
}
for (const userId of [...this.active.keys()]) this.finish(userId);
this.connection = null;
this.sessionId = null;
}
private subscribe(userId: string): void {
const conn = this.connection;
if (!conn || conn.receiver.subscriptions.has(userId)) return;
if (this.opts.skip(userId)) return;
const stream = conn.receiver.subscribe(userId, {
end: { behavior: EndBehaviorType.AfterSilence, duration: this.opts.silenceMs() },
});
stream.on('data', (packet: Buffer) => this.onPacket(userId, packet));
stream.once('end', () => this.finish(userId));
stream.once('close', () => this.finish(userId));
stream.on('error', (e) => log.warn(`수신 오류 (${userId})`, e));
}
private onPacket(userId: string, packet: Buffer): void {
// 녹음 도중 /녹음제외 하면 바로 버린다
if (this.opts.skip(userId)) {
const cur = this.active.get(userId);
if (cur) this.discard(userId, cur);
return;
}
const now = Date.now();
let u = this.active.get(userId);
if (!u) {
u = new Utterance(this.opts.audioDir(), now - 20);
this.active.set(userId, u);
} else {
// 말 사이 짧은 쉼은 디스코드가 패킷을 안 보낸다. 무음 프레임으로 채워 실제 시간과 맞춘다.
const gap = now - u.lastArrival;
const missing = Math.round(gap / 20) - 1;
if (missing > 0 && missing * 20 < this.opts.silenceMs() + 200) for (let i = 0; i < missing; i++) u.writer.write(SILENCE_FRAME);
}
u.lastArrival = now;
u.writer.write(packet);
if (u.writer.samples >= this.opts.maxUtteranceSec() * 48000) {
this.finish(userId);
}
}
private discard(userId: string, u: Utterance): void {
this.active.delete(userId);
u.writer.close();
fs.rmSync(u.writer.path, { force: true });
}
private finish(userId: string): void {
const u = this.active.get(userId);
if (!u) return;
this.active.delete(userId);
u.writer.close();
const dur = u.writer.durationMs;
// 0.25초보다 짧으면 버린다 (키 클릭, 끊긴 패킷)
if (dur < 250) {
fs.rmSync(u.writer.path, { force: true });
return;
}
const endedAt = u.startedAt + dur;
const matchId = this.opts.matchAt(u.startedAt);
const row = this.store.insertUtterance({
id: u.id,
session_id: this.sessionId,
user_id: userId,
started_at: u.startedAt,
ended_at: endedAt,
audio_path: u.writer.path,
match_id: matchId,
});
this.bus.live({ type: 'utterance.created', data: this.timeline.utteranceItem(row) });
this.stt.enqueue(row.id, 'realtime');
log.debug(`발화 저장 ${userId} ${dur}ms ${u.writer.bytes}B`);
}
get speaking(): string[] {
return [...this.active.keys()];
}
}

View File

@@ -0,0 +1,64 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { MsEdgeTTS, OUTPUT_FORMAT } from 'msedge-tts';
import { DEFAULT_TTS_TEXT } from '../settings.js';
import { logger } from '../util/log.js';
const log = logger('tts');
/**
* 녹음 안내 음성. 미리 합성해서 캐시하고, 문구를 바꾸면 다시 합성한다 (보고서 7-3).
* 합성은 Microsoft Edge 온라인 TTS(무료). 인터넷이 안 되면 기본 문구 음성(앱에 포함)을 쓴다.
*/
export class Announcer {
constructor(
private cacheDir: string,
private resourcesDir: string,
) {}
private bundled(): string {
return path.join(this.resourcesDir, 'tts', 'announce-default.webm');
}
cachedPath(text: string, voice: string): string {
const h = crypto.createHash('sha1').update(`${voice}\n${text}`).digest('hex').slice(0, 16);
return path.join(this.cacheDir, `announce-${h}.webm`);
}
/** 안내 음성 파일 경로 (WebM Opus). 없으면 합성. */
async ensure(text: string, voice: string): Promise<string> {
const p = this.cachedPath(text, voice);
if (fs.existsSync(p) && fs.statSync(p).size > 1000) return p;
if (text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled();
try {
await synthesize(text, voice, p);
log.info(`안내 음성 합성: ${path.basename(p)}`);
return p;
} catch (e) {
log.warn('안내 음성 합성 실패, 기본 음성 사용', e);
return this.bundled();
}
}
}
export async function synthesize(text: string, voice: string, outFile: string): Promise<void> {
fs.mkdirSync(path.dirname(outFile), { recursive: true });
const tts = new MsEdgeTTS();
const tmpDir = fs.mkdtempSync(path.join(path.dirname(outFile), '.tts-'));
try {
await tts.setMetadata(voice, OUTPUT_FORMAT.WEBM_24KHZ_16BIT_MONO_OPUS);
const r = await Promise.race([
tts.toFile(tmpDir, text),
new Promise<never>((_, rej) => setTimeout(() => rej(new Error('TTS 시간 초과')), 20000)),
]);
fs.renameSync(r.audioFilePath, outFile);
} finally {
try {
tts.close();
} catch {
/* 무시 */
}
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}

View File

@@ -0,0 +1,180 @@
import fs from 'node:fs';
import path from 'node:path';
import { logger } from '../util/log.js';
import { request } from './riot.js';
const log = logger('assets');
/**
* 게임 이미지·이름 목록 (보고서 7-7). 원본 URL 을 사이트 서버의 캐시 경로(/game-assets/...)로 바꿔서 준다.
* - 발로란트: valorant-api.com (ko-KR 이름, 미니맵 좌표 변환값)
* - 롤: Riot Data Dragon (ko_KR), 오브젝트 아이콘은 Community Dragon
*/
export function assetUrl(url: string | null | undefined): string | null {
if (!url) return null;
return url
.replace('https://media.valorant-api.com/', '/game-assets/valmedia/')
.replace('https://ddragon.leagueoflegends.com/', '/game-assets/ddragon/')
.replace('https://raw.communitydragon.org/', '/game-assets/cdragon/');
}
export const LOL_OBJECT_ICON: Record<string, string> = {
baron: 'baron.png',
herald: 'riftherald.png',
grub: 'grub.png',
tower: 'tower.png',
inhibitor: 'inhibitor.png',
atakhan: 'atakhan.png',
dragon: 'dragon.png',
dragon_fire: 'dragon_infernal.png',
dragon_earth: 'dragon_mountain.png',
dragon_water: 'dragon_ocean.png',
dragon_air: 'dragon_cloud.png',
dragon_hextech: 'dragon_hextech.png',
dragon_chemtech: 'dragon_chemtech.png',
dragon_elder: 'dragon_elder.png',
};
export function lolObjectIcon(key: string): string {
return `/game-assets/cdragon/latest/game/assets/ux/minimap/icons/${LOL_OBJECT_ICON[key] || 'dragon.png'}`;
}
interface ValCatalog {
at: number;
agents: Record<string, { name: string; icon: string; abilities: Record<string, { name: string; icon: string | null }> }>;
maps: Record<string, { uuid: string; name: string; image: string | null; xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }>;
weapons: Record<string, { name: string; icon: string | null }>;
tiers: Record<number, string>;
modes: Record<string, string>;
clientVersion: string | null;
}
interface LolCatalog {
at: number;
version: string;
champions: Record<string, { id: string; key: string; name: string; icon: string }>;
items: Record<string, { name: string; icon: string; gold: number }>;
}
const DAY = 24 * 3600 * 1000;
export class GameAssets {
val: ValCatalog | null = null;
lol: LolCatalog | null = null;
constructor(private cacheDir: string) {
fs.mkdirSync(cacheDir, { recursive: true });
this.val = this.readCache('valorant.json');
this.lol = this.readCache('lol.json');
}
private readCache<T>(name: string): T | null {
try {
return JSON.parse(fs.readFileSync(path.join(this.cacheDir, name), 'utf8'));
} catch {
return null;
}
}
private writeCache(name: string, v: unknown): void {
fs.writeFileSync(path.join(this.cacheDir, name), JSON.stringify(v));
}
async refresh(force = false): Promise<void> {
await Promise.all([this.refreshVal(force).catch((e) => log.warn('발로란트 목록 갱신 실패', e)), this.refreshLol(force).catch((e) => log.warn('롤 목록 갱신 실패', e))]);
}
async refreshVal(force = false): Promise<void> {
if (!force && this.val && Date.now() - this.val.at < DAY) return;
const get = async (p: string) => (await request(`https://valorant-api.com/v1/${p}`, { timeoutMs: 20000 })).data?.data;
const [agents, maps, weapons, tiers, modes, version] = await Promise.all([
get('agents?language=ko-KR&isPlayableCharacter=true'),
get('maps?language=ko-KR'),
get('weapons?language=ko-KR'),
get('competitivetiers?language=ko-KR'),
get('gamemodes?language=ko-KR'),
get('version'),
]);
const cat: ValCatalog = { at: Date.now(), agents: {}, maps: {}, weapons: {}, tiers: {}, modes: {}, clientVersion: version?.riotClientVersion ?? null };
for (const a of agents || []) {
const abilities: ValCatalog['agents'][string]['abilities'] = {};
for (const ab of a.abilities || []) abilities[ab.slot] = { name: ab.displayName, icon: assetUrl(ab.displayIcon) };
cat.agents[a.uuid.toLowerCase()] = { name: a.displayName, icon: assetUrl(a.displayIcon)!, abilities };
}
for (const m of maps || [])
cat.maps[m.mapUrl] = {
uuid: m.uuid,
name: m.displayName,
image: assetUrl(m.displayIcon),
xMultiplier: m.xMultiplier,
yMultiplier: m.yMultiplier,
xScalarToAdd: m.xScalarToAdd,
yScalarToAdd: m.yScalarToAdd,
};
for (const w of weapons || []) cat.weapons[w.uuid.toLowerCase()] = { name: w.displayName, icon: assetUrl(w.killStreamIcon || w.displayIcon) };
const lastTiers = (tiers || [])[tiers?.length - 1];
for (const t of lastTiers?.tiers || []) cat.tiers[t.tier] = t.tierName;
for (const gm of modes || []) if (gm.assetPath) cat.modes[gm.assetPath] = gm.displayName;
this.val = cat;
this.writeCache('valorant.json', cat);
log.info(`발로란트 목록 갱신: 요원 ${Object.keys(cat.agents).length}, 맵 ${Object.keys(cat.maps).length}`);
}
async refreshLol(force = false): Promise<void> {
if (!force && this.lol && Date.now() - this.lol.at < DAY) return;
const versions = (await request('https://ddragon.leagueoflegends.com/api/versions.json', { timeoutMs: 20000 })).data;
const v = versions[0];
const base = `https://ddragon.leagueoflegends.com/cdn/${v}`;
const champs = (await request(`${base}/data/ko_KR/champion.json`, { timeoutMs: 30000 })).data.data;
const items = (await request(`${base}/data/ko_KR/item.json`, { timeoutMs: 30000 })).data.data;
const cat: LolCatalog = { at: Date.now(), version: v, champions: {}, items: {} };
for (const c of Object.values<any>(champs)) {
const entry = { id: c.id, key: c.key, name: c.name, icon: assetUrl(`${base}/img/champion/${c.image.full}`)! };
cat.champions[c.id.toLowerCase()] = entry;
cat.champions[`key:${c.key}`] = entry;
cat.champions[`name:${c.name}`] = entry;
}
for (const [id, it] of Object.entries<any>(items)) cat.items[id] = { name: it.name, icon: assetUrl(`${base}/img/item/${id}.png`)!, gold: it.gold?.total ?? 0 };
this.lol = cat;
this.writeCache('lol.json', cat);
log.info(`롤 목록 갱신: ${v}, 챔피언 ${Object.keys(champs).length}`);
}
// ---- 발로란트 조회
agent(id: string | null | undefined) {
const a = id ? this.val?.agents[id.toLowerCase()] : undefined;
return { id: id || '', name: a?.name ?? '?', icon: a?.icon ?? null };
}
valMap(mapUrl: string | null | undefined) {
return mapUrl ? this.val?.maps[mapUrl] : undefined;
}
/** 킬 무기·스킬 이름 */
damageItem(agentId: string | null, type: string, item: string): { id: string; name: string; icon: string | null } | null {
if (type === 'Weapon' && item) {
const w = this.val?.weapons[item.toLowerCase()];
return { id: item.toLowerCase(), name: w?.name ?? '무기', icon: w?.icon ?? null };
}
if (type === 'Ability' && agentId) {
const ab = this.val?.agents[agentId.toLowerCase()]?.abilities[item];
return { id: item, name: ab?.name ?? '스킬', icon: ab?.icon ?? null };
}
if (type === 'Bomb') return { id: 'spike', name: '스파이크', icon: null };
if (type === 'Melee') return { id: 'melee', name: '근접 무기', icon: null };
return item || type ? { id: item || type, name: type === 'Fall' ? '낙사' : item || type, icon: null } : null;
}
// ---- 롤 조회
champion(raw: string | null | undefined, localized?: string) {
const cat = this.lol;
let c: LolCatalog['champions'][string] | undefined;
if (raw && cat) {
const m = /game_character_displayname_(\w+)/.exec(raw);
c = cat.champions[(m ? m[1] : raw).toLowerCase()] || cat.champions[`key:${raw}`];
}
if (!c && localized && cat) c = cat.champions[`name:${localized}`];
return { id: c?.id ?? raw ?? '', name: c?.name ?? localized ?? raw ?? '?', icon: c?.icon ?? null };
}
item(id: number) {
const it = this.lol?.items[String(id)];
return { id, name: it?.name ?? String(id), icon: it?.icon ?? null, gold: it?.gold ?? 0 };
}
lolMapImage(): string {
return assetUrl(`https://ddragon.leagueoflegends.com/cdn/${this.lol?.version ?? '16.20.1'}/img/map/map11.png`)!;
}
}

616
app/src/core/games/lol.ts Normal file
View File

@@ -0,0 +1,616 @@
import type { ChatData, KillData, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared';
import type { EventRow } from '../db/db.js';
import { logger } from '../util/log.js';
import { lolObjectIcon } from './assets.js';
import { basicAuth, findLcu, request } from './riot.js';
import type { AdapterHost, GameAdapter } from './types.js';
const log = logger('lol');
const LIVE = () => process.env.GVR_LOL_LIVE_URL || 'https://127.0.0.1:2999';
interface LiveMatch {
id: string;
gameId: number | null;
startedAt: number;
selfName: string | null;
selfTeam: string | null;
players: any[];
seenEvents: Set<number>;
failures: number;
goldDiff: { t: number; diff: number }[];
lastGoldAt: number;
lastSnapshotAt: number;
ended: boolean;
}
const DRAGON: Record<string, string> = {
Fire: 'dragon_fire',
Earth: 'dragon_earth',
Water: 'dragon_water',
Air: 'dragon_air',
Hextech: 'dragon_hextech',
Chemtech: 'dragon_chemtech',
Elder: 'dragon_elder',
};
const DRAGON_KO: Record<string, string> = {
Fire: '화염의 용',
Earth: '대지의 용',
Water: '바다의 용',
Air: '바람의 용',
Hextech: '마법공학 용',
Chemtech: '화학공학 용',
Elder: '장로 드래곤',
};
/**
* 리그 오브 레전드 어댑터 (보고서 6-5).
* - 게임 클라이언트 API(127.0.0.1:2999): 게임 시간, 10명 KDA·CS·아이템, 킬·오브젝트 이벤트
* - 롤 클라이언트(LCU): 경기 ID·결과·경기 기록(타임라인), 챔피언 선택·게임 후 채팅
* - 게임 중 채팅: 화면 OCR (STT 워커) 또는 로그 파일(남아 있을 때)
*/
export class LolAdapter implements GameAdapter {
readonly game = 'lol' as const;
private timer: NodeJS.Timeout | null = null;
private lcuTimer: NodeJS.Timeout | null = null;
private live: LiveMatch | null = null;
private lcu: { port: number; password: string; installDir: string | null } | null = null;
private lcuCheckedAt = 0;
private polling = false;
private seenChat = new Set<string>();
private pendingChat: EventRow[] = [];
private detailQueue = new Map<string, { gameId: number; tries: number; endedAt: number; startedAt: number }>();
private summonerNames = new Map<string, string>();
private ocrSeen = new Set<string>();
private lastMatchId: string | null = null;
private lastErr = '';
constructor(private host: AdapterHost) {
host.worker.on('event', (ev: any) => {
if (ev.event === 'ocr_line') this.onOcrLine(ev);
});
}
start(): void {
if (this.timer) return;
this.timer = setInterval(() => void this.tick(), Number(process.env.GVR_POLL_MS) || 2000);
this.lcuTimer = setInterval(() => void this.lcuTick(), (Number(process.env.GVR_POLL_MS) || 2000) * 2.5);
}
stop(): void {
if (this.timer) clearInterval(this.timer);
if (this.lcuTimer) clearInterval(this.lcuTimer);
this.timer = this.lcuTimer = null;
if (this.live) void this.host.worker.request('ocr_stop', {}, 5000).catch(() => undefined);
}
status() {
return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined };
}
private async lcuGet<T = any>(path: string): Promise<T | null> {
if (!this.lcu) return null;
try {
const r = await request<T>(`https://127.0.0.1:${this.lcu.port}${path}`, { headers: { authorization: basicAuth(this.lcu.password) }, local: true });
return r.status === 200 ? r.data : null;
} catch {
this.lcu = null;
return null;
}
}
// ------------------------------------------------------------------ 게임 클라이언트 API
private async tick(): Promise<void> {
if (this.polling || !this.host.settings().games.lol) return;
this.polling = true;
try {
let data: any = null;
try {
const r = await request(`${LIVE()}/liveclientdata/allgamedata`, { local: true, timeoutMs: 1500 });
if (r.status === 200 && r.data?.gameData) data = r.data;
} catch {
/* 게임 중이 아님 */
}
if (data) await this.onLive(data);
else if (this.live && !this.live.ended && ++this.live.failures >= 3) this.endMatch(null);
await this.pollDetails();
this.lastErr = '';
} catch (e: any) {
this.lastErr = e.message;
log.debug('롤 폴링 오류', e);
} finally {
this.polling = false;
}
}
private async onLive(d: any): Promise<void> {
const gameTime = Number(d.gameData.gameTime) || 0;
if (gameTime <= 0) return; // 로딩 화면
const now = Date.now();
if (!this.live || this.live.ended) {
if (this.live?.ended) return; // 결과 화면에서도 API 가 잠깐 살아 있다
let gameId: number | null = null;
const sess = await this.lcuGet<any>('/lol-gameflow/v1/session');
gameId = sess?.gameData?.gameId ?? null;
const id = `lol-${gameId ?? now}`;
const selfName = d.activePlayer?.riotId || d.activePlayer?.summonerName || null;
const me = (d.allPlayers || []).find((p: any) => p.riotId === selfName || p.summonerName === selfName);
this.live = {
id,
gameId,
startedAt: now - gameTime * 1000,
selfName,
selfTeam: me?.team ?? null,
players: d.allPlayers || [],
seenEvents: new Set(),
failures: 0,
goldDiff: [],
lastGoldAt: 0,
lastSnapshotAt: 0,
ended: false,
};
this.lastMatchId = id;
this.ocrSeen.clear();
this.host.matchStarted({
id,
game: 'lol',
startedAt: this.live.startedAt,
map: d.gameData.mapName || 'Map11',
mode: d.gameData.gameMode || null,
queue: sess?.gameData?.queue?.description ?? null,
detail: { live: true, players: this.snapshotPlayers(d.allPlayers || []) },
});
// 버퍼해 둔 챔피언 선택 채팅을 이 경기에 붙인다
for (const e of this.pendingChat) this.host.event({ ...e, match_id: id, id: `${id}:${e.id}` });
this.pendingChat = [];
void this.startOcr();
log.info(`롤 경기 시작 감지 ${id}`);
}
const m = this.live;
m.failures = 0;
m.players = d.allPlayers || m.players;
// 게임 시간과 PC 시계로 시작 시각을 계속 다듬는다 (가장 이른 값 = 지연이 가장 적은 값)
m.startedAt = Math.min(m.startedAt, now - gameTime * 1000);
for (const ev of d.events?.Events || []) {
if (m.seenEvents.has(ev.EventID)) continue;
m.seenEvents.add(ev.EventID);
const row = this.liveEvent(m, ev);
if (row) this.host.event(row);
if (ev.EventName === 'GameEnd') this.endMatch(ev.Result === 'Win');
}
if (now - m.lastGoldAt >= 30000) {
m.lastGoldAt = now;
m.goldDiff.push({ t: Math.round(gameTime * 1000), diff: this.itemGoldDiff(m) });
}
if (now - m.lastSnapshotAt >= 10000) {
m.lastSnapshotAt = now;
this.host.matchUpdated(m.id, {
detail: JSON.stringify({ live: true, players: this.snapshotPlayers(m.players), goldDiff: m.goldDiff, goldEstimated: true }),
});
}
}
private findPlayer(m: LiveMatch, name: string | undefined): any {
if (!name) return null;
return m.players.find((p) => p.riotIdGameName === name || p.riotId === name || p.summonerName === name || p.riotId?.split('#')[0] === name) ?? null;
}
private ref(m: LiveMatch, name: string | undefined): PlayerRef | null {
if (!name) return null;
const p = this.findPlayer(m, name);
if (!p) return { name: prettyUnit(name) };
return { name: p.riotIdGameName || p.summonerName || name, team: p.team, character: this.host.assets.champion(p.rawChampionName, p.championName) };
}
private liveEvent(m: LiveMatch, ev: any): EventRow | null {
const t = Math.round((ev.EventTime || 0) * 1000);
const base = { match_id: m.id, game: 'lol' as const, ts: m.startedAt + t, game_time_ms: t, round: null, actor_puuid: null, target_puuid: null };
const id = `${m.id}:live:${ev.EventID}`;
const allyOf = (team: string | undefined) => (team && m.selfTeam ? team === m.selfTeam : undefined);
switch (ev.EventName) {
case 'ChampionKill': {
const killer = this.ref(m, ev.KillerName);
const data: KillData = {
killer,
victim: this.ref(m, ev.VictimName)!,
assists: (ev.Assisters || []).map((a: string) => this.ref(m, a)!).filter(Boolean),
weapon: null,
ally: allyOf(killer?.team),
};
return { ...base, id, type: 'kill', data: JSON.stringify(data) };
}
case 'DragonKill':
case 'BaronKill':
case 'HeraldKill':
case 'HordeKill':
case 'AtakhanKill': {
const killer = this.ref(m, ev.KillerName);
const object: ObjectData['object'] =
ev.EventName === 'DragonKill' ? 'dragon' : ev.EventName === 'BaronKill' ? 'baron' : ev.EventName === 'HeraldKill' ? 'herald' : ev.EventName === 'HordeKill' ? 'grub' : 'atakhan';
const key = object === 'dragon' ? DRAGON[ev.DragonType] || 'dragon' : object;
const data: ObjectData & { icon: string; label: string; stolen?: boolean } = {
object,
subtype: ev.DragonType,
team: killer?.team,
killer,
ally: allyOf(killer?.team),
icon: lolObjectIcon(key),
label: object === 'dragon' ? DRAGON_KO[ev.DragonType] || '드래곤' : { baron: '내셔 남작', herald: '협곡의 전령', grub: '공허 유충', atakhan: '아타칸' }[object as string] || object,
stolen: ev.Stolen === 'True' || ev.Stolen === true,
};
return { ...base, id, type: 'object', data: JSON.stringify(data) };
}
case 'TurretKilled':
case 'InhibKilled': {
const name: string = ev.TurretKilled || ev.InhibKilled || '';
// T1 = 블루(ORDER) 건물 → 레드가 부숨
const destroyedBy = /_T1_/.test(name) ? 'CHAOS' : /_T2_/.test(name) ? 'ORDER' : undefined;
const object = ev.EventName === 'TurretKilled' ? 'tower' : 'inhibitor';
const data = {
object,
team: destroyedBy,
killer: this.ref(m, ev.KillerName),
ally: allyOf(destroyedBy),
icon: lolObjectIcon(object),
label: object === 'tower' ? '포탑 파괴' : '억제기 파괴',
};
return { ...base, id, type: 'object', data: JSON.stringify(data) };
}
case 'Multikill': {
const p = this.ref(m, ev.KillerName);
return { ...base, id, type: 'multikill', data: JSON.stringify({ player: p, count: ev.KillStreak, ally: allyOf(p?.team) }) };
}
case 'Ace': {
const p = this.ref(m, ev.Acer);
return { ...base, id, type: 'ace', data: JSON.stringify({ player: p, team: ev.AcingTeam, ally: allyOf(ev.AcingTeam) }) };
}
case 'GameEnd':
return { ...base, id, type: 'match_end', data: JSON.stringify({ win: ev.Result === 'Win' }) };
default:
return null;
}
}
/** 경기 중 골드 차이 추정: 아이템 가격 합 (경기 후 타임라인 값으로 교체) */
private itemGoldDiff(m: LiveMatch): number {
let ally = 0;
let enemy = 0;
for (const p of m.players) {
const g = (p.items || []).reduce((s: number, it: any) => s + this.host.assets.item(it.itemID).gold * (it.count || 1), 0);
if (p.team === m.selfTeam) ally += g;
else enemy += g;
}
return ally - enemy;
}
private snapshotPlayers(players: any[]): MatchPlayer[] {
const selfTeam = this.live?.selfTeam;
return players.map((p) => ({
puuid: p.puuid || p.riotId || p.summonerName,
name: p.riotIdGameName || p.summonerName,
tag: p.riotIdTagLine,
team: p.team,
ally: p.team === selfTeam,
character: this.host.assets.champion(p.rawChampionName, p.championName),
kills: p.scores?.kills ?? 0,
deaths: p.scores?.deaths ?? 0,
assists: p.scores?.assists ?? 0,
cs: p.scores?.creepScore ?? 0,
level: p.level,
items: (p.items || []).map((it: any) => {
const x = this.host.assets.item(it.itemID);
return { id: it.itemID, name: it.displayName || x.name, icon: x.icon };
}),
}));
}
private endMatch(win: boolean | null): void {
const m = this.live;
if (!m || m.ended) return;
m.ended = true;
const now = Date.now();
void this.host.worker.request('ocr_stop', {}, 5000).catch(() => undefined);
this.host.matchEnded(m.id, now);
this.host.matchUpdated(m.id, {
result: JSON.stringify({ win, score: null }),
detail: JSON.stringify({ live: false, players: this.snapshotPlayers(m.players), goldDiff: m.goldDiff, goldEstimated: true }),
});
if (m.gameId) this.detailQueue.set(m.id, { gameId: m.gameId, tries: 0, endedAt: now, startedAt: m.startedAt });
else this.host.matchUpdated(m.id, { status: 'complete' }, { complete: true });
void this.readLogChat(m);
log.info(`롤 경기 종료 ${m.id}`);
// 결과 화면에서 API 가 살아 있는 동안 다시 시작으로 잡지 않도록 잠시 유지
setTimeout(() => {
if (this.live === m) this.live = null;
}, 60000).unref();
}
// ------------------------------------------------------------------ 채팅 OCR · 로그
private async startOcr(): Promise<void> {
const s = this.host.settings().games;
if (!s.lolChatOcr || process.platform !== 'win32') return;
try {
await this.host.worker.request('ocr_start', { window_title: 'League of Legends (TM) Client', region: s.lolOcrRegion, fps: 3, lang: 'ko' }, 15000);
log.info('롤 채팅 OCR 시작');
} catch (e: any) {
this.lastErr = `채팅 OCR: ${e.message}`;
log.warn('채팅 OCR 시작 실패', e);
}
}
private chatRow(m: LiveMatch, key: string, gameTimeS: number | null, ts: number, p: any, source: ChatData['source']): EventRow {
const sender = this.findPlayer(m, p.sender);
const ts2 = gameTimeS !== null ? m.startedAt + gameTimeS * 1000 : ts;
const data: ChatData = {
sender: {
name: p.sender || '?',
team: sender?.team,
character: sender ? this.host.assets.champion(sender.rawChampionName, sender.championName) : p.champion ? this.host.assets.champion(null, p.champion) : undefined,
},
channel: p.channel || 'all',
text: p.message || '',
source,
};
return {
id: `${m.id}:chat:${source}:${key}`,
match_id: m.id,
game: 'lol',
type: 'chat',
ts: ts2,
game_time_ms: ts2 - m.startedAt,
round: null,
actor_puuid: null,
target_puuid: null,
data: JSON.stringify(data),
};
}
private onOcrLine(ev: any): void {
const m = this.live;
if (!m || m.ended || !ev.parsed?.message) return;
const p = ev.parsed;
const key = `${p.game_time ?? ''}|${p.sender ?? ''}|${p.message}`;
if (this.ocrSeen.has(key)) return;
this.ocrSeen.add(key);
const gts = typeof p.game_time_s === 'number' ? p.game_time_s : null;
this.host.event(this.chatRow(m, hash(key), gts, ev.ts || Date.now(), p, 'ocr'));
}
/** 로그 파일에 채팅이 남아 있으면 OCR 보다 정확하므로 그걸로 바꾼다 */
private async readLogChat(m: LiveMatch): Promise<void> {
const dir = this.host.settings().games.lolLogsDir || (this.lcu?.installDir ? `${this.lcu.installDir}\\Logs\\GameLogs` : null);
if (!dir) return;
try {
const r = await this.host.worker.request('r3dlog_read', { logs_dir: dir, since_ms: m.startedAt - 600000 }, 30000);
const lines = r?.lines || [];
if (!lines.length) return;
const rows = lines.map((p: any, i: number) =>
this.chatRow(m, `${i}-${hash(`${p.game_time_s}|${p.sender}|${p.message}`)}`, typeof p.game_time_s === 'number' ? p.game_time_s : null, m.startedAt, p, 'log'),
);
this.host.replaceEvents(m.id, ['chat'], rows);
log.info(`로그 파일 채팅 ${rows.length}줄로 교체`);
} catch (e) {
log.debug('로그 파일 채팅 없음', e);
}
}
// ------------------------------------------------------------------ LCU
private async lcuTick(): Promise<void> {
if (!this.host.settings().games.lol) return;
if (!this.lcu && Date.now() - this.lcuCheckedAt > (Number(process.env.GVR_POLL_MS) ? 0 : 15000)) {
this.lcuCheckedAt = Date.now();
this.lcu = await findLcu().catch(() => null);
if (this.lcu) {
log.info('롤 클라이언트(LCU) 연결');
const me = await this.lcuGet<any>('/lol-summoner/v1/current-summoner');
if (me?.puuid) this.host.selfAccount(me.puuid, `${me.gameName}#${me.tagLine}`);
}
}
if (!this.lcu) return;
const phase = await this.lcuGet<string>('/lol-gameflow/v1/gameflow-phase');
if (phase === 'ChampSelect' || phase === 'InProgress' || phase === 'PreEndOfGame' || phase === 'EndOfGame') await this.pollLcuChat(phase);
}
private async pollLcuChat(phase: string): Promise<void> {
const convs = (await this.lcuGet<any[]>('/lol-chat/v1/conversations')) || [];
for (const c of convs) {
if (c.type !== 'championSelect' && c.type !== 'postGame') continue;
const msgs = (await this.lcuGet<any[]>(`/lol-chat/v1/conversations/${encodeURIComponent(c.id)}/messages`)) || [];
for (const msg of msgs) {
const key = `${c.id}:${msg.id}`;
if (this.seenChat.has(key) || msg.type === 'system') continue;
this.seenChat.add(key);
const ts = Date.parse(msg.timestamp) || Date.now();
const name = await this.summonerName(msg.fromSummonerId, msg.fromId);
const data: ChatData = { sender: { name }, channel: c.type === 'postGame' ? 'all' : 'team', text: msg.body || '', source: 'lcu' };
const row: EventRow = {
id: `lcu:${hash(key)}`,
match_id: '',
game: 'lol',
type: 'chat',
ts,
game_time_ms: null,
round: null,
actor_puuid: null,
target_puuid: null,
data: JSON.stringify(data),
};
const target = c.type === 'postGame' ? this.lastMatchId : this.live && !this.live.ended ? this.live.id : null;
if (target) this.host.event({ ...row, match_id: target, id: `${target}:${row.id}` });
else if (c.type === 'championSelect') this.pendingChat.push(row);
}
}
if (phase !== 'ChampSelect' && phase !== 'InProgress' && this.pendingChat.length && !this.live) this.pendingChat = [];
}
private async summonerName(summonerId: number | undefined, pid: string | undefined): Promise<string> {
const k = String(summonerId ?? pid ?? '');
if (this.summonerNames.has(k)) return this.summonerNames.get(k)!;
let name = '?';
if (summonerId) {
const s = await this.lcuGet<any>(`/lol-summoner/v1/summoners/${summonerId}`);
name = s?.gameName || s?.displayName || name;
}
this.summonerNames.set(k, name);
return name;
}
private async pollDetails(): Promise<void> {
if (!this.detailQueue.size || !this.lcu) return;
for (const [id, q] of this.detailQueue) {
if (Date.now() - q.endedAt < q.tries * (Number(process.env.GVR_DETAIL_RETRY_MS) || 20000)) continue;
q.tries++;
const game = await this.lcuGet<any>(`/lol-match-history/v1/games/${q.gameId}`);
if (!game?.participants) {
if (q.tries >= 15) {
this.detailQueue.delete(id);
this.host.matchUpdated(id, { status: 'complete' }, { complete: true });
}
continue;
}
const timeline = await this.lcuGet<any>(`/lol-match-history/v1/game-timelines/${q.gameId}`);
this.detailQueue.delete(id);
this.applyHistory(id, game, timeline, q.startedAt);
}
}
applyHistory(id: string, game: any, timeline: any, startedAt: number): void {
const res = processLolHistory(game, timeline, this.host, id, startedAt);
if (res.events.length) this.host.replaceEvents(id, ['kill', 'object'], res.events);
this.host.resolvePlayers(res.players.filter((p) => p.puuid && p.tag).map((p) => ({ puuid: p.puuid, riotId: `${p.name}#${p.tag}` })));
this.host.matchUpdated(
id,
{
ended_at: startedAt + (game.gameDuration ?? 0) * 1000,
result: JSON.stringify(res.result),
detail: JSON.stringify({ live: false, players: res.players, goldDiff: res.goldDiff, goldEstimated: !res.goldDiff.length, self: res.self }),
queue: game.queueId ? String(game.queueId) : null,
status: 'complete',
},
{ complete: true },
);
log.info(`롤 경기 기록 적용 ${id}: 타임라인 ${timeline?.frames ? '있음' : '없음'}`);
}
}
/** LCU 경기 기록 + 타임라인 → 선수·이벤트(킬 위치 포함)·골드 그래프. 순수 함수 */
export function processLolHistory(game: any, timeline: any, host: Pick<AdapterHost, 'assets' | 'store'>, id: string, startedAt: number) {
const ident: Record<number, any> = {};
for (const pi of game.participantIdentities || []) ident[pi.participantId] = pi.player || {};
const selfPuuid = host.store.meta('riot_self_puuid');
const selfPart = (game.participants || []).find((p: any) => ident[p.participantId]?.puuid === selfPuuid);
const selfTeam = selfPart?.teamId ?? 100;
const teamName = (t: number) => (t === 100 ? 'ORDER' : 'CHAOS');
const champ = (cid: number) => host.assets.champion(String(cid));
const byPid: Record<number, any> = {};
for (const p of game.participants || []) byPid[p.participantId] = p;
const ref = (pid: number | undefined): PlayerRef | null => {
if (!pid || !byPid[pid]) return pid === 0 ? { name: '미니언·포탑' } : null;
const p = byPid[pid];
const who = ident[pid] || {};
return { puuid: who.puuid, name: who.gameName || who.summonerName || '?', team: teamName(p.teamId), character: champ(p.championId) };
};
const players: MatchPlayer[] = (game.participants || []).map((p: any) => {
const who = ident[p.participantId] || {};
const st = p.stats || {};
return {
puuid: who.puuid || '',
name: who.gameName || who.summonerName || '?',
tag: who.tagLine,
team: teamName(p.teamId),
ally: p.teamId === selfTeam,
character: champ(p.championId),
kills: st.kills ?? 0,
deaths: st.deaths ?? 0,
assists: st.assists ?? 0,
cs: (st.totalMinionsKilled ?? 0) + (st.neutralMinionsKilled ?? 0),
gold: st.goldEarned ?? 0,
level: st.champLevel,
items: [st.item0, st.item1, st.item2, st.item3, st.item4, st.item5, st.item6]
.filter((x: number) => x)
.map((x: number) => {
const it = host.assets.item(x);
return { id: x, name: it.name, icon: it.icon };
}),
};
});
const events: EventRow[] = [];
const goldDiff: { t: number; diff: number }[] = [];
for (const f of timeline?.frames || []) {
let ally = 0;
let enemy = 0;
for (const [pid, pf] of Object.entries<any>(f.participantFrames || {})) {
const team = byPid[Number(pid)]?.teamId;
if (team === selfTeam) ally += pf.totalGold ?? 0;
else enemy += pf.totalGold ?? 0;
}
goldDiff.push({ t: f.timestamp, diff: ally - enemy });
for (const e of f.events || []) {
const t = e.timestamp ?? 0;
const base = { match_id: id, game: 'lol' as const, ts: startedAt + t, game_time_ms: t, round: null, target_puuid: null };
if (e.type === 'CHAMPION_KILL') {
const killer = ref(e.killerId);
const data: KillData = {
killer,
victim: ref(e.victimId)!,
assists: (e.assistingParticipantIds || []).map((x: number) => ref(x)!).filter(Boolean),
weapon: null,
location: e.position ?? null,
ally: byPid[e.killerId]?.teamId === selfTeam,
};
events.push({ ...base, id: `${id}:kill:${t}:${e.victimId}`, type: 'kill', actor_puuid: killer?.puuid ?? null, target_puuid: data.victim?.puuid ?? null, data: JSON.stringify(data) });
} else if (e.type === 'ELITE_MONSTER_KILL') {
const mt = String(e.monsterType || '');
const object = mt === 'DRAGON' ? 'dragon' : mt === 'BARON_NASHOR' ? 'baron' : mt === 'RIFTHERALD' ? 'herald' : mt === 'HORDE' ? 'grub' : mt === 'ATAKHAN' ? 'atakhan' : 'dragon';
const sub = String(e.monsterSubType || '');
const dk = sub.includes('FIRE') ? 'Fire' : sub.includes('EARTH') ? 'Earth' : sub.includes('WATER') ? 'Water' : sub.includes('AIR') ? 'Air' : sub.includes('HEXTECH') ? 'Hextech' : sub.includes('CHEMTECH') ? 'Chemtech' : sub.includes('ELDER') ? 'Elder' : '';
const killer = ref(e.killerId);
const data = {
object,
subtype: dk || undefined,
team: killer?.team,
killer,
ally: byPid[e.killerId]?.teamId === selfTeam,
location: e.position ?? null,
icon: lolObjectIcon(object === 'dragon' ? DRAGON[dk] || 'dragon' : object),
label: object === 'dragon' ? DRAGON_KO[dk] || '드래곤' : { baron: '내셔 남작', herald: '협곡의 전령', grub: '공허 유충', atakhan: '아타칸' }[object] || object,
};
events.push({ ...base, id: `${id}:obj:${t}:${object}`, type: 'object', actor_puuid: killer?.puuid ?? null, data: JSON.stringify(data) });
} else if (e.type === 'BUILDING_KILL') {
const object = e.buildingType === 'INHIBITOR_BUILDING' ? 'inhibitor' : 'tower';
const destroyedBy = e.teamId === 100 ? 'CHAOS' : 'ORDER';
const data = {
object,
team: destroyedBy,
killer: ref(e.killerId),
ally: (e.teamId === 100 ? 200 : 100) === selfTeam,
location: e.position ?? null,
icon: lolObjectIcon(object),
label: object === 'tower' ? '포탑 파괴' : '억제기 파괴',
};
events.push({ ...base, id: `${id}:bld:${t}:${e.position?.x}:${e.position?.y}`, type: 'object', actor_puuid: null, data: JSON.stringify(data) });
}
}
}
const myTeam = (game.teams || []).find((t: any) => t.teamId === selfTeam);
const allyKills = players.filter((p) => p.ally).reduce((s, p) => s + p.kills, 0);
const enemyKills = players.filter((p) => !p.ally).reduce((s, p) => s + p.kills, 0);
return {
players,
events,
goldDiff,
self: selfPuuid,
result: { win: myTeam ? myTeam.win === 'Win' : (selfPart?.stats?.win ?? null), score: { ally: allyKills, enemy: enemyKills } },
};
}
function prettyUnit(name: string): string {
if (/^Turret_/.test(name)) return '포탑';
if (/Minion/.test(name)) return '미니언';
if (/^SRU_/.test(name)) return '몬스터';
return name;
}
function hash(s: string): string {
let h = 2166136261;
for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619) >>> 0;
return h.toString(36);
}

View File

@@ -0,0 +1,179 @@
import type { MatchSummary } from '@gvr/shared';
import type { EventRow, MatchRow, Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { SttPipeline } from '../stt/pipeline.js';
import type { WorkerClient } from '../stt/worker.js';
import type { Timeline } from '../timeline.js';
import { safeJson } from '../timeline.js';
import type { Bus } from '../util/events.js';
import { logger } from '../util/log.js';
import type { GameAssets } from './assets.js';
import { LolAdapter } from './lol.js';
import type { AdapterHost, GameAdapter, MatchStart } from './types.js';
import { ValorantAdapter } from './valorant.js';
const log = logger('games');
/** 게임 어댑터들을 묶고, 경기 시작·종료를 녹음/STT/타임라인에 반영한다 */
export class GameManager implements AdapterHost {
adapters: GameAdapter[];
constructor(
readonly store: Store,
readonly assets: GameAssets,
readonly worker: WorkerClient,
private stt: SttPipeline,
private timeline: Timeline,
private bus: Bus,
private getSettings: () => Settings,
private ownerUserId: () => string | null,
) {
this.adapters = [new ValorantAdapter(this), new LolAdapter(this)];
}
settings(): Settings {
return this.getSettings();
}
start(): void {
void this.assets.refresh();
for (const a of this.adapters) a.start();
// 앱이 꺼졌다 켜졌을 때 'live' 로 남은 경기는 끝난 것으로 정리
for (const m of this.store.listMatches({ limit: 20 }))
if (m.status === 'live') this.store.upsertMatch({ id: m.id, game: m.game, started_at: m.started_at, status: 'complete', ended_at: m.ended_at ?? Date.now() });
}
stop(): void {
for (const a of this.adapters) a.stop();
}
status() {
const out: Record<string, { connected: boolean; inMatch: boolean; detail?: string }> = {};
for (const a of this.adapters) out[a.game] = a.status();
return out as { valorant: { connected: boolean; inMatch: boolean }; lol: { connected: boolean; inMatch: boolean } };
}
/** 지금 진행 중인 경기 (녹음 시 발화에 붙인다) */
liveMatchAt(ts: number): string | null {
const m = this.store.matchAt(ts);
return m && (m.status === 'live' || !m.ended_at || ts <= m.ended_at) ? m.id : null;
}
matchStarted(m: MatchStart): void {
this.store.upsertMatch({
id: m.id,
game: m.game,
started_at: m.startedAt,
map: m.map ?? null,
mode: m.mode ?? null,
queue: m.queue ?? null,
detail: m.detail ? JSON.stringify(m.detail) : null,
status: 'live',
});
this.timeline.invalidate(m.id);
void this.stt.onMatchStart();
this.emitMatch(m.id);
}
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void {
const cur = this.store.getMatch(id);
if (!cur) return;
this.store.upsertMatch({ ...patch, id, game: cur.game, started_at: patch.started_at ?? cur.started_at });
this.timeline.invalidate(id);
if (opts?.complete) {
const m = this.store.getMatch(id)!;
// 정확한 경기 시간으로 발화를 다시 붙인다
const n = this.store.assignMatch(id, m.started_at + m.clock_offset - 2000, (m.ended_at ?? Date.now()) + 1000);
log.info(`경기 ${id}: 발화 ${n}개 연결`);
this.bus.live({ type: 'users.updated', data: [] });
}
this.emitMatch(id);
}
matchEnded(id: string, endedAt: number): void {
const cur = this.store.getMatch(id);
if (!cur) return;
this.store.upsertMatch({ id, game: cur.game, started_at: cur.started_at, ended_at: endedAt, status: 'pending_detail' });
this.store.assignMatch(id, cur.started_at, endedAt);
this.timeline.invalidate(id);
void this.stt.onMatchEnd(cur.started_at, endedAt);
this.emitMatch(id);
}
event(e: EventRow): void {
if (this.store.insertEvent(e)) this.bus.live({ type: 'event.created', data: this.timeline.eventItem(e) });
}
replaceEvents(matchId: string, types: string[], events: EventRow[]): void {
this.store.replaceEvents(matchId, types, events);
this.timeline.invalidate(matchId);
}
selfAccount(puuid: string, riotId: string): void {
const owner = this.ownerUserId();
this.store.setMeta('riot_self_puuid', puuid);
if (!owner || !this.store.getUser(owner)) return;
const have = this.store.listAccounts().some((a) => a.user_id === owner && a.puuid === puuid);
if (have) return;
this.store.db.prepare('INSERT OR REPLACE INTO game_accounts(user_id,puuid,riot_id) VALUES(?,?,?)').run(owner, puuid, riotId);
this.store.db.prepare(`DELETE FROM game_accounts WHERE user_id=? AND puuid=''`).run(owner);
log.info(`주인 계정 자동 연결: ${riotId}`);
}
/** 설정에서 Riot ID 로만 연결해 둔 유저(puuid '' 자리표시)를 실제 puuid 로 바꾼다 */
resolvePlayers(players: { puuid: string; riotId: string }[]): void {
const pending = this.store.listAccounts().filter((a) => !a.puuid || a.puuid.startsWith('riotid:'));
for (const a of pending) {
const p = players.find((x) => x.riotId.toLowerCase() === a.riot_id.toLowerCase());
if (!p) continue;
this.store.db.prepare('UPDATE game_accounts SET puuid=? WHERE user_id=? AND puuid=?').run(p.puuid, a.user_id, a.puuid);
log.info(`Riot ID 연결: ${a.riot_id}`);
}
}
summary(m: MatchRow): MatchSummary {
const result = safeJson<{ win: boolean | null; score: { ally: number; enemy: number } | null }>(m.result, { win: null, score: null });
const map = m.game === 'valorant' ? this.assets.valMap(m.map) : null;
const participants = (
this.store.db.prepare('SELECT DISTINCT user_id FROM utterances WHERE match_id=?').all(m.id) as { user_id: string }[]
).map((r) => r.user_id);
return {
id: m.id,
game: m.game,
startedAt: m.started_at + m.clock_offset,
endedAt: m.ended_at,
map:
m.game === 'valorant'
? { id: m.map ?? '', name: map?.name ?? m.map ?? '?', image: map?.image ?? null }
: { id: m.map ?? 'Map11', name: '소환사의 협곡', image: this.assets.lolMapImage() },
mode: modeKo(m),
win: result.win,
score: result.score,
status: m.status as MatchSummary['status'],
participants,
};
}
emitMatch(id: string): void {
const m = this.store.getMatch(id);
if (m) this.bus.live({ type: 'match.updated', data: this.summary(m) });
}
}
function modeKo(m: MatchRow): string {
const q = (m.queue || m.mode || '').toLowerCase();
if (m.game === 'valorant') {
const map: Record<string, string> = {
competitive: '경쟁전',
unrated: '일반전',
swiftplay: '신속플레이',
spikerush: '스파이크 돌격',
deathmatch: '데스매치',
hurm: '팀 데스매치',
premier: '프리미어',
custom: '사용자 지정',
ggteam: '에스컬레이션',
};
return map[q] || m.mode || '발로란트';
}
const lq: Record<string, string> = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', classic: '소환사의 협곡', aram: '칼바람 나락' };
return lq[q] || m.mode || '리그 오브 레전드';
}

114
app/src/core/games/riot.ts Normal file
View File

@@ -0,0 +1,114 @@
import { execFile } from 'node:child_process';
import fs from 'node:fs';
import http from 'node:http';
import https from 'node:https';
import os from 'node:os';
import path from 'node:path';
/** Riot 로컬 API 는 자체 서명 인증서라 검증을 끈 에이전트로만 부른다 (127.0.0.1 전용) */
const localAgent = new https.Agent({ rejectUnauthorized: false, keepAlive: true });
export interface HttpResult<T = any> {
status: number;
data: T;
}
export function request<T = any>(
url: string,
opts: { method?: string; headers?: Record<string, string>; body?: unknown; timeoutMs?: number; local?: boolean } = {},
): Promise<HttpResult<T>> {
return new Promise((resolve, reject) => {
const u = new URL(url);
const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
const lib: any = u.protocol === 'http:' ? http : https;
const req = lib.request(
u,
{
method: opts.method || 'GET',
headers: { accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}), ...opts.headers },
agent: u.protocol === 'https:' && (opts.local ?? isLocal(u)) ? localAgent : undefined,
timeout: opts.timeoutMs ?? 5000,
},
(res: any) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => {
const txt = Buffer.concat(chunks).toString('utf8');
let data: any = txt;
try {
data = txt ? JSON.parse(txt) : null;
} catch {
/* 텍스트 그대로 */
}
resolve({ status: res.statusCode || 0, data });
});
},
);
req.on('timeout', () => req.destroy(new Error('timeout')));
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
function isLocal(u: URL): boolean {
return u.hostname === '127.0.0.1' || u.hostname === 'localhost';
}
export interface Lockfile {
name: string;
pid: number;
port: number;
password: string;
protocol: string;
}
export function parseLockfile(txt: string): Lockfile | null {
const p = txt.trim().split(':');
if (p.length < 5) return null;
return { name: p[0], pid: Number(p[1]), port: Number(p[2]), password: p[3], protocol: p[4] };
}
export function readLockfile(file: string): Lockfile | null {
try {
return parseLockfile(fs.readFileSync(file, 'utf8'));
} catch {
return null;
}
}
export function basicAuth(password: string): string {
return 'Basic ' + Buffer.from(`riot:${password}`).toString('base64');
}
/** Riot Client lockfile (발로란트 로컬 API) */
export function riotClientLockfilePath(): string {
if (process.env.GVR_RIOT_LOCKFILE) return process.env.GVR_RIOT_LOCKFILE;
const base = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
return path.join(base, 'Riot Games', 'Riot Client', 'Config', 'lockfile');
}
/** 롤 클라이언트(LCU) 접속 정보. lockfile 기본 위치 → 실행 중인 LeagueClientUx 명령줄 순서로 찾는다. */
export async function findLcu(): Promise<{ port: number; password: string; installDir: string | null } | null> {
if (process.env.GVR_LCU_LOCKFILE) {
const lf = readLockfile(process.env.GVR_LCU_LOCKFILE);
return lf ? { port: lf.port, password: lf.password, installDir: path.dirname(process.env.GVR_LCU_LOCKFILE) } : null;
}
if (process.platform !== 'win32') return null;
for (const dir of ['C:\\Riot Games\\League of Legends', 'D:\\Riot Games\\League of Legends']) {
const lf = readLockfile(path.join(dir, 'lockfile'));
if (lf) return { port: lf.port, password: lf.password, installDir: dir };
}
const cmd = await new Promise<string>((resolve) => {
execFile(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-Command', "(Get-CimInstance Win32_Process -Filter \"name='LeagueClientUx.exe'\").CommandLine"],
{ windowsHide: true, timeout: 8000 },
(err, stdout) => resolve(err ? '' : String(stdout)),
);
});
const port = /--app-port=(\d+)/.exec(cmd)?.[1];
const pw = /--remoting-auth-token=([\w-]+)/.exec(cmd)?.[1];
const dir = /--install-directory=([^"]+?)"?\s--/.exec(cmd)?.[1] ?? null;
return port && pw ? { port: Number(port), password: pw, installDir: dir } : null;
}

View File

@@ -0,0 +1,41 @@
import type { EventRow, MatchRow, Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { WorkerClient } from '../stt/worker.js';
import type { GameAssets } from './assets.js';
export interface MatchStart {
id: string;
game: 'valorant' | 'lol';
startedAt: number;
map?: string | null;
mode?: string | null;
queue?: string | null;
detail?: unknown;
}
/** 게임 어댑터가 코어에 알리는 통로. 다른 게임도 같은 규격으로 붙인다 (F-15). */
export interface AdapterHost {
store: Store;
assets: GameAssets;
worker: WorkerClient;
settings(): Settings;
matchStarted(m: MatchStart): void;
/** 경기 정보 갱신 (상세가 채워졌을 때 등) */
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void;
matchEnded(id: string, endedAt: number): void;
/** 실시간 이벤트 1건 (중복 ID 는 무시) */
event(e: EventRow): void;
/** 경기 후 상세로 이벤트를 통째로 교체 */
replaceEvents(matchId: string, types: string[], events: EventRow[]): void;
/** 이 PC 의 Riot 계정 (주인 디스코드 유저와 자동 연결) */
selfAccount(puuid: string, riotId: string): void;
/** 경기 참가자 Riot ID 로 디스코드 유저 연결 갱신 */
resolvePlayers(players: { puuid: string; riotId: string }[]): void;
}
export interface GameAdapter {
readonly game: 'valorant' | 'lol';
start(): void;
stop(): void;
status(): { connected: boolean; inMatch: boolean; detail?: string };
}

View File

@@ -0,0 +1,553 @@
import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound } from '@gvr/shared';
import type { EventRow, RoundRow } from '../db/db.js';
import { logger } from '../util/log.js';
import type { GameAssets } from './assets.js';
import { basicAuth, readLockfile, request, riotClientLockfilePath, type Lockfile } from './riot.js';
import type { AdapterHost, GameAdapter } from './types.js';
const log = logger('valorant');
const CLIENT_PLATFORM = Buffer.from(
JSON.stringify({ platformType: 'PC', platformOS: 'Windows', platformOSVersion: '10.0.19042.1.256.64bit', platformChipset: 'Unknown' }),
).toString('base64');
/** 구매 단계 길이 (경쟁·일반 30초). 라운드 시작 = 전투 시작 - 구매 단계 */
const BUY_MS = 30000;
interface Presence {
state: 'MENUS' | 'PREGAME' | 'INGAME' | string;
map: string | null;
queue: string | null;
ally: number | null;
enemy: number | null;
provisioning: string | null;
}
export function decodePresence(b64: string): Presence | null {
try {
const p = JSON.parse(Buffer.from(b64, 'base64').toString('utf8'));
const mp = p.matchPresenceData || {};
const pp = p.partyPresenceData || {};
return {
state: mp.sessionLoopState || p.sessionLoopState || 'MENUS',
map: mp.matchMap || p.matchMap || null,
queue: mp.queueId || p.queueId || null,
ally: num(pp.partyOwnerMatchScoreAllyTeam ?? p.partyOwnerMatchScoreAllyTeam),
enemy: num(pp.partyOwnerMatchScoreEnemyTeam ?? p.partyOwnerMatchScoreEnemyTeam),
provisioning: mp.provisioningFlow || p.provisioningFlow || null,
};
} catch {
return null;
}
}
const num = (v: any) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
interface Auth {
lock: Lockfile;
accessToken: string;
entitlement: string;
puuid: string;
region: string;
shard: string;
clientVersion: string | null;
}
/**
* 발로란트 어댑터: Riot 클라이언트 로컬 API (Q1 B).
* - 상태(presence)로 경기 시작·종료와 실시간 점수 감지
* - 경기 중 채팅(팀/전체/파티)은 로컬 채팅 API
* - 경기가 끝나면 경기 상세(킬·라운드·경제)를 받아 시간축에 맞춘다
* 읽기 전용, 게임 메모리 접근 없음.
*/
export class ValorantAdapter implements GameAdapter {
readonly game = 'valorant' as const;
private timer: NodeJS.Timeout | null = null;
private auth: Auth | null = null;
private authAt = 0;
private presence: Presence | null = null;
private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number } | null = null;
private seenChat = new Set<string>();
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
private polling = false;
private lastErr = '';
constructor(private host: AdapterHost) {}
start(): void {
if (this.timer) return;
this.timer = setInterval(() => void this.tick(), Number(process.env.GVR_POLL_MS) || 3000);
void this.tick();
}
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
status() {
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
}
private async local<T = any>(path: string): Promise<T | null> {
const lock = this.auth?.lock ?? readLockfile(riotClientLockfilePath());
if (!lock) return null;
const r = await request<T>(`https://127.0.0.1:${lock.port}${path}`, { headers: { authorization: basicAuth(lock.password) }, local: true });
return r.status === 200 ? r.data : null;
}
private async ensureAuth(): Promise<Auth | null> {
const lock = readLockfile(riotClientLockfilePath());
if (!lock) {
this.auth = null;
return null;
}
if (this.auth && this.auth.lock.port === lock.port && Date.now() - this.authAt < 10 * 60000) return this.auth;
const base = `https://127.0.0.1:${lock.port}`;
const h = { authorization: basicAuth(lock.password) };
const ent = await request(`${base}/entitlements/v1/token`, { headers: h, local: true });
if (ent.status !== 200 || !ent.data?.accessToken) {
this.auth = null;
return null;
}
let region = process.env.GVR_VAL_REGION || 'kr';
let shard = process.env.GVR_VAL_SHARD || 'kr';
let clientVersion: string | null = null;
const sess = await request(`${base}/product-session/v1/external-sessions`, { headers: h, local: true }).catch(() => null);
for (const s of Object.values<any>(sess?.data || {})) {
if (s?.productId !== 'valorant') continue;
clientVersion = s.version || null;
for (const a of s.launchConfiguration?.arguments || []) {
const d = /^-ares-deployment=(\w+)/.exec(a);
if (d) region = d[1];
const c = /^-config-endpoint=https:\/\/shared\.(\w+)\.a\.pvp\.net/.exec(a);
if (c) shard = c[1];
}
}
this.auth = { lock, accessToken: ent.data.accessToken, entitlement: ent.data.token, puuid: ent.data.subject, region, shard, clientVersion };
this.authAt = Date.now();
log.info(`Riot 클라이언트 연결 (region=${region}, shard=${shard})`);
return this.auth;
}
private pvpHeaders(a: Auth): Record<string, string> {
return {
authorization: `Bearer ${a.accessToken}`,
'x-riot-entitlements-jwt': a.entitlement,
'x-riot-clientplatform': CLIENT_PLATFORM,
'x-riot-clientversion': a.clientVersion || this.host.assets.val?.clientVersion || '',
};
}
private glz(a: Auth): string {
return process.env.GVR_VAL_GLZ || `https://glz-${a.region}-1.${a.shard}.a.pvp.net`;
}
private pd(a: Auth): string {
return process.env.GVR_VAL_PD || `https://pd.${a.shard}.a.pvp.net`;
}
private async tick(): Promise<void> {
if (this.polling || !this.host.settings().games.valorant) return;
this.polling = true;
try {
const a = await this.ensureAuth();
if (a) {
await this.pollPresence(a);
if (this.match) await this.pollChat(a);
} else if (this.match) {
// 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다
this.endMatch();
}
await this.pollDetails();
this.lastErr = '';
} catch (e: any) {
this.lastErr = e.message;
log.debug('발로란트 폴링 오류', e);
} finally {
this.polling = false;
}
}
private async pollPresence(a: Auth): Promise<void> {
const pres = await this.local<any>('/chat/v4/presences');
const mine = (pres?.presences || []).find((p: any) => p.puuid === a.puuid && p.product === 'valorant');
const p = mine?.private ? decodePresence(mine.private) : null;
const prev = this.presence;
this.presence = p;
if (!p) return;
if (p.state === 'INGAME' && !this.match) await this.beginMatch(a, p);
else if (p.state !== 'INGAME' && this.match && prev?.state === 'INGAME') this.endMatch();
else if (this.match && p.ally !== null && p.enemy !== null) {
const m = this.match;
const total = p.ally + p.enemy;
if (total > m.ally + m.enemy) {
// 실시간 라운드 결과 (경기 후 상세로 교체됨)
const win = p.ally > m.ally;
m.ally = p.ally;
m.enemy = p.enemy;
const data: RoundEndData = { round: total, win, result: win ? '승리' : '패배', score: { ally: p.ally, enemy: p.enemy } };
this.host.event({
id: `${m.id}:live-round:${total}`,
match_id: m.id,
game: 'valorant',
type: 'round_end',
ts: Date.now(),
game_time_ms: Date.now() - m.startedAt,
round: total,
actor_puuid: null,
target_puuid: null,
data: JSON.stringify(data),
});
this.host.matchUpdated(m.id, { result: JSON.stringify({ win: null, score: { ally: p.ally, enemy: p.enemy } }) });
}
}
}
private async beginMatch(a: Auth, p: Presence): Promise<void> {
let matchId: string | null = null;
let detail: any = null;
try {
const r = await request(`${this.glz(a)}/core-game/v1/players/${a.puuid}`, { headers: this.pvpHeaders(a), timeoutMs: 8000 });
matchId = r.data?.MatchID ?? null;
if (matchId) {
const m = await request(`${this.glz(a)}/core-game/v1/matches/${matchId}`, { headers: this.pvpHeaders(a), timeoutMs: 8000 });
if (m.status === 200) detail = m.data;
}
} catch (e) {
log.warn('core-game 조회 실패', e);
}
const now = Date.now();
const id = `val-${matchId ?? now}`;
const mapUrl = detail?.MapID || p.map;
const players = (detail?.Players || []).map((pl: any) => ({
puuid: pl.Subject,
team: pl.TeamID,
character: this.host.assets.agent(pl.CharacterID),
}));
this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0 };
this.seenChat.clear();
this.host.matchStarted({
id,
game: 'valorant',
startedAt: now,
map: mapUrl,
mode: p.provisioning === 'CustomGame' ? 'custom' : p.queue,
queue: p.queue,
detail: { live: true, self: a.puuid, players },
});
log.info(`경기 시작 감지 ${id} (${this.host.assets.valMap(mapUrl)?.name ?? mapUrl})`);
}
private endMatch(): void {
const m = this.match;
if (!m) return;
this.match = null;
const now = Date.now();
this.host.matchEnded(m.id, now);
if (m.matchId) this.detailQueue.set(m.id, { tries: 0, endedAt: now, startedLocal: m.startedAt });
log.info(`경기 종료 감지 ${m.id}`);
}
private async pollChat(a: Auth): Promise<void> {
const m = this.match!;
const r = await this.local<any>('/chat/v6/messages');
for (const msg of r?.messages || []) {
const key = msg.mid || msg.id;
if (!key || this.seenChat.has(key)) continue;
const ts = Number(msg.time) || Date.now();
if (ts < m.startedAt - 120000) {
this.seenChat.add(key);
continue;
}
const cid: string = msg.cid || '';
const channel: ChatData['channel'] | null = cid.includes('-all@')
? 'all'
: cid.includes('ares-coregame') || cid.includes('ares-pregame')
? 'team'
: cid.includes('ares-parties')
? 'party'
: null;
this.seenChat.add(key);
if (!channel) continue;
const data: ChatData = {
sender: { puuid: msg.puuid, name: msg.game_name ? `${msg.game_name}` : msg.name || '?' },
channel,
text: String(msg.body ?? ''),
source: 'api',
};
this.host.event({
id: `${m.id}:chat:${key}`,
match_id: m.id,
game: 'valorant',
type: 'chat',
ts,
game_time_ms: ts - m.startedAt,
round: null,
actor_puuid: msg.puuid || null,
target_puuid: null,
data: JSON.stringify(data),
});
}
}
/** 경기 상세는 끝나고 수 분 안에 조회된다. 30초마다 최대 20번 시도 */
private async pollDetails(): Promise<void> {
if (!this.detailQueue.size) return;
const a = this.auth;
if (!a) return;
for (const [id, q] of this.detailQueue) {
if (Date.now() - q.endedAt < q.tries * (Number(process.env.GVR_DETAIL_RETRY_MS) || 30000)) continue;
q.tries++;
const matchId = id.replace(/^val-/, '');
try {
const r = await request(`${this.pd(a)}/match-details/v1/matches/${matchId}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
if (r.status === 200 && r.data?.matchInfo) {
this.detailQueue.delete(id);
this.applyDetails(id, r.data, a.puuid, q.startedLocal);
continue;
}
log.debug(`경기 상세 아직 없음 ${id} (${r.status})`);
} catch (e) {
log.debug('경기 상세 조회 실패', e);
}
if (q.tries >= 20) {
this.detailQueue.delete(id);
this.host.matchUpdated(id, { status: 'complete' }, { complete: true });
}
}
}
applyDetails(id: string, md: any, selfPuuid: string, startedLocal: number): void {
const res = processMatchDetails(md, selfPuuid, this.host.assets, id, startedLocal);
this.host.store.replaceRounds(id, res.rounds);
this.host.replaceEvents(id, ['kill', 'round_end', 'spike', 'multikill', 'ace'], res.events);
this.host.resolvePlayers(res.players.map((p) => ({ puuid: p.puuid, riotId: `${p.name}#${p.tag}` })));
const self = res.players.find((p) => p.puuid === selfPuuid);
if (self) this.host.selfAccount(self.puuid, `${self.name}#${self.tag}`);
this.host.matchUpdated(
id,
{
started_at: res.startedAt,
ended_at: res.endedAt + res.clockOffset,
clock_offset: res.clockOffset,
map: md.matchInfo.mapId,
mode: res.mode,
queue: md.matchInfo.queueID ?? null,
result: JSON.stringify(res.result),
detail: JSON.stringify({ self: selfPuuid, players: res.players, roundsDetail: res.roundsDetail }),
status: 'complete',
},
{ complete: true },
);
log.info(`경기 상세 적용 ${id}: 라운드 ${res.rounds.length}, 킬 ${res.events.filter((e) => e.type === 'kill').length}`);
}
}
/** match-details → 라운드·이벤트·선수. 순수 함수 (테스트 대상) */
export function processMatchDetails(md: any, selfPuuid: string, assets: GameAssets, id: string, startedLocal: number) {
const info = md.matchInfo;
const S: number = info.gameStartMillis;
const length: number = info.gameLengthMillis ?? 0;
// PC 시계와 서버 시계 차이: 10초 넘게 차이 나면 보정 (경기 로딩 시간 때문에 작은 차이는 무시)
const diff = startedLocal - S;
const clockOffset = Math.abs(diff) > 10000 && Math.abs(diff) < 6 * 3600000 ? diff - 5000 : 0;
const players: Record<string, any> = {};
for (const p of md.players || []) players[p.subject] = p;
const selfTeam = players[selfPuuid]?.teamId ?? 'Blue';
const ref = (puuid: string | null | undefined): PlayerRef | null => {
if (!puuid) return null;
const p = players[puuid];
if (!p) return { puuid, name: '?' };
return { puuid, name: p.gameName, team: p.teamId, character: assets.agent(p.characterId) };
};
const rr: any[] = md.roundResults || [];
const n = rr.length;
// 라운드 전투 시작 시각(게임 시간) = 킬 gameTime - roundTime
const combat: (number | null)[] = rr.map((r) => {
let best: number | null = null;
for (const ps of r.playerStats || [])
for (const k of ps.kills || []) {
const c = k.gameTime - k.roundTime;
if (best === null || c < best) best = c;
}
return best;
});
const avg = n ? length / n : 100000;
for (let i = 0; i < n; i++) {
if (combat[i] !== null) continue;
const prev = i > 0 ? combat[i - 1] : null;
let next: number | null = null;
for (let j = i + 1; j < n; j++) if (combat[j] !== null) {
next = combat[j]! - (j - i) * avg;
break;
}
combat[i] = prev !== null ? prev + avg : next !== null ? next : BUY_MS + i * avg;
}
const rounds: RoundRow[] = [];
const roundsDetail: MatchRound[] = [];
const events: EventRow[] = [];
let ally = 0;
let enemy = 0;
for (let i = 0; i < n; i++) {
const r = rr[i];
const num = (r.roundNum ?? i) + 1;
const c = combat[i]!;
const start = Math.max(0, c - BUY_MS);
const end = i + 1 < n ? Math.max(c, combat[i + 1]! - BUY_MS) : Math.max(c, length);
const win = r.winningTeam === selfTeam;
if (win) ally++;
else enemy++;
const economy: Record<string, { spent: number; remaining: number; weapon?: string }> = {};
for (const ps of r.playerStats || []) {
if (ps.economy)
economy[ps.subject] = {
spent: ps.economy.spent ?? 0,
remaining: ps.economy.remaining ?? 0,
weapon: ps.economy.weapon ? assets.damageItem(null, 'Weapon', ps.economy.weapon)?.name : undefined,
};
}
rounds.push({
match_id: id,
num,
started_at: S + start,
combat_at: S + c,
ended_at: S + end,
win: win ? 1 : 0,
result: r.roundResult ?? null,
ally_score: ally,
enemy_score: enemy,
economy: JSON.stringify(economy),
});
roundsDetail.push({ num, startedAt: S + start + clockOffset, endedAt: S + end + clockOffset, win, result: roundResultKo(r.roundResult), score: { ally, enemy }, economy });
// 킬
const killsBy: Record<string, number> = {};
const kills = (r.playerStats || []).flatMap((ps: any) => ps.kills || []).sort((x: any, y: any) => x.gameTime - y.gameTime);
for (const k of kills) {
const killer = ref(k.killer);
const victim = ref(k.victim)!;
killsBy[k.killer] = (killsBy[k.killer] || 0) + 1;
const fd = k.finishingDamage || {};
const data: KillData = {
killer,
victim,
assists: (k.assistants || []).map((x: string) => ref(x)!).filter(Boolean),
weapon: assets.damageItem(players[k.killer]?.characterId ?? null, fd.damageType, fd.damageItem),
location: k.victimLocation ? { x: k.victimLocation.x, y: k.victimLocation.y } : null,
ally: players[k.killer]?.teamId === selfTeam,
};
events.push({
id: `${id}:kill:${num}:${k.gameTime}:${k.victim}`,
match_id: id,
game: 'valorant',
type: 'kill',
ts: S + k.gameTime + clockOffset,
game_time_ms: k.gameTime,
round: num,
actor_puuid: k.killer ?? null,
target_puuid: k.victim ?? null,
data: JSON.stringify(data),
});
}
for (const [puuid, cnt] of Object.entries(killsBy)) {
if (cnt >= 4) {
const last = kills.filter((k: any) => k.killer === puuid).pop();
events.push({
id: `${id}:${cnt >= 5 ? 'ace' : 'multikill'}:${num}:${puuid}`,
match_id: id,
game: 'valorant',
type: cnt >= 5 ? 'ace' : 'multikill',
ts: S + last.gameTime + clockOffset + 1,
game_time_ms: last.gameTime,
round: num,
actor_puuid: puuid,
target_puuid: null,
data: JSON.stringify({ player: ref(puuid), count: cnt, ally: players[puuid]?.teamId === selfTeam }),
});
}
}
if (r.plantRoundTime) {
events.push({
id: `${id}:spike:plant:${num}`,
match_id: id,
game: 'valorant',
type: 'spike',
ts: S + c + r.plantRoundTime + clockOffset,
game_time_ms: c + r.plantRoundTime,
round: num,
actor_puuid: r.bombPlanter ?? null,
target_puuid: null,
data: JSON.stringify({ action: 'plant', site: r.plantSite ?? null, player: ref(r.bombPlanter), location: r.plantLocation ?? null }),
});
}
if (r.defuseRoundTime) {
events.push({
id: `${id}:spike:defuse:${num}`,
match_id: id,
game: 'valorant',
type: 'spike',
ts: S + c + r.defuseRoundTime + clockOffset,
game_time_ms: c + r.defuseRoundTime,
round: num,
actor_puuid: r.bombDefuser ?? null,
target_puuid: null,
data: JSON.stringify({ action: 'defuse', player: ref(r.bombDefuser), location: r.defuseLocation ?? null }),
});
}
const rd: RoundEndData = { round: num, win, result: roundResultKo(r.roundResult), score: { ally, enemy } };
events.push({
id: `${id}:round_end:${num}`,
match_id: id,
game: 'valorant',
type: 'round_end',
ts: S + end + clockOffset - 1,
game_time_ms: end,
round: num,
actor_puuid: null,
target_puuid: null,
data: JSON.stringify(rd),
});
}
const mp: MatchPlayer[] = (md.players || []).map((p: any) => ({
puuid: p.subject,
name: p.gameName,
tag: p.tagLine,
team: p.teamId,
ally: p.teamId === selfTeam,
character: assets.agent(p.characterId),
kills: p.stats?.kills ?? 0,
deaths: p.stats?.deaths ?? 0,
assists: p.stats?.assists ?? 0,
score: p.stats?.roundsPlayed ? Math.round((p.stats.score ?? 0) / p.stats.roundsPlayed) : (p.stats?.score ?? 0),
rank: assets.val?.tiers[p.competitiveTier] ?? null,
}));
const selfTeamInfo = (md.teams || []).find((t: any) => t.teamId === selfTeam);
const enemyTeamInfo = (md.teams || []).find((t: any) => t.teamId !== selfTeam);
return {
startedAt: S,
endedAt: S + length,
clockOffset,
rounds,
roundsDetail,
events,
players: mp,
mode: assets.val?.modes[info.gameMode] ?? info.queueID ?? null,
result: {
win: selfTeamInfo ? !!selfTeamInfo.won : null,
score: { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy },
},
};
}
export function roundResultKo(r: string | undefined): string {
switch (r) {
case 'Eliminated':
return '전멸';
case 'Bomb detonated':
return '스파이크 폭발';
case 'Bomb defused':
return '스파이크 해체';
case 'Round timer expired':
return '시간 초과';
case 'Surrendered':
return '항복';
default:
return r || '';
}
}

136
app/src/core/index.ts Normal file
View File

@@ -0,0 +1,136 @@
import fs from 'node:fs';
import path from 'node:path';
import type { FastifyInstance } from 'fastify';
import { buildApi } from './api/server.js';
import { Store } from './db/db.js';
import { Dictionary } from './dict/dictionary.js';
import { Bot } from './discord/bot.js';
import { Recorder } from './discord/recorder.js';
import { Announcer } from './discord/tts.js';
import { GameAssets } from './games/assets.js';
import { GameManager } from './games/manager.js';
import { RelayClient } from './relay/client.js';
import { Retention } from './retention.js';
import { SettingsStore, resolvePaths, type SecretCodec } from './settings.js';
import { SttPipeline } from './stt/pipeline.js';
import { WorkerClient, type WorkerCommand } from './stt/worker.js';
import { Timeline } from './timeline.js';
import { Bus } from './util/events.js';
import { initLogFile, logger } from './util/log.js';
const log = logger('core');
export interface CoreOptions {
dataDir: string;
resourcesDir: string;
worker: WorkerCommand;
version: string;
codec?: SecretCodec;
/** 로컬 API 를 127.0.0.1 포트로도 연다 (설정 창·디버그용). 0 이면 열지 않음 */
apiPort?: number;
}
export type Core = Awaited<ReturnType<typeof startCore>>;
/** 코어 조립 (Electron 메인 프로세스와 헤드리스 CLI 가 같이 쓴다) */
export async function startCore(opts: CoreOptions) {
fs.mkdirSync(opts.dataDir, { recursive: true });
const settings = new SettingsStore(opts.dataDir, opts.codec);
const S = () => settings.get();
const paths = () => resolvePaths(opts.dataDir, S());
initLogFile(paths().logs);
log.info(`겜녹이 ${opts.version} 시작, 데이터 폴더 ${opts.dataDir}`);
const store = new Store(paths().db);
const bus = new Bus();
bus.setMaxListeners(50);
const timeline = new Timeline(store);
const dict = new Dictionary(store, opts.resourcesDir, () => S().dictionary.packs);
dict.seed();
const worker = new WorkerClient({
...opts.worker,
env: { ...(opts.worker.env || {}), GVR_DATA_DIR: opts.dataDir, GVR_MODELS_DIR: paths().models },
});
const stt = new SttPipeline(worker, store, dict, timeline, bus, S);
const assets = new GameAssets(path.join(opts.dataDir, 'cache'));
const games = new GameManager(store, assets, worker, stt, timeline, bus, S, () => S().discord.followUserId);
const recorder: Recorder = new Recorder(store, stt, timeline, bus, {
audioDir: () => paths().audio,
silenceMs: () => S().audio.silenceMs,
maxUtteranceSec: () => S().audio.maxUtteranceSec,
skip: (uid): boolean => {
const u = store.getUser(uid);
if (u?.excluded) return true;
return !!bot.client?.users.cache.get(uid)?.bot;
},
matchAt: (ts) => games.liveMatchAt(ts),
});
const announcer = new Announcer(paths().tts, opts.resourcesDir);
const bot: Bot = new Bot(store, recorder, announcer, bus, S, (gid) => {
if (!S().discord.guildId) settings.update({ discord: { guildId: gid } });
});
const api: FastifyInstance = await buildApi({
store,
timeline,
games,
dict,
bus,
settings: S,
trainingDir: () => paths().training,
version: opts.version,
overviewExtra: () => ({
guild: bot.state.guild,
recording: {
active: bot.state.recording.active,
channel: bot.state.recording.channel,
since: bot.state.recording.since,
participants: bot.state.recording.participants,
},
}),
});
const relay = new RelayClient(api, bus, () => ({
serverUrl: S().site.serverUrl,
deviceId: S().site.deviceId,
deviceKey: settings.getSecret('deviceKey') ?? null,
name: S().site.deviceName,
version: opts.version,
}));
const retention = new Retention(store, () => S().storage.retentionDays, () => paths().audio);
worker.start();
stt.resumePending();
games.start();
retention.start();
relay.start();
if (opts.apiPort) await api.listen({ host: '127.0.0.1', port: opts.apiPort });
const startBot = async () => {
const token = settings.getSecret('botToken');
if (!token) {
log.warn('봇 토큰이 없습니다. 설정에서 입력해 주세요.');
return;
}
try {
await bot.start(token);
} catch (e: any) {
log.error(`봇 로그인 실패: ${e.message}`);
}
};
await startBot();
const stop = async () => {
log.info('종료 중');
relay.stop();
retention.stop();
games.stop();
await bot.stop();
await worker.stop();
await api.close();
store.close();
};
return { settings, store, bus, timeline, dict, worker, stt, assets, games, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version };
}

View File

@@ -0,0 +1,160 @@
import type { FastifyInstance } from 'fastify';
import WebSocket from 'ws';
import type { LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
import type { Bus } from '../util/events.js';
import { logger } from '../util/log.js';
const log = logger('relay');
export interface RelayStatus {
state: 'off' | 'connecting' | 'online' | 'error';
error: string | null;
since: number | null;
serverUrl: string | null;
}
/**
* 사이트 서버로 나가는 WebSocket 하나를 유지한다 (포트 개방 불필요, 보고서 3장).
* 서버가 넘겨 준 /api 요청을 로컬 API(Fastify inject)로 처리해 돌려주고, 실시간 이벤트를 올린다.
*/
export class RelayClient {
private ws: WebSocket | null = null;
private pingTimer: NodeJS.Timeout | null = null;
private retryTimer: NodeJS.Timeout | null = null;
private retries = 0;
private stopped = true;
private lastPong = 0;
status: RelayStatus = { state: 'off', error: null, since: null, serverUrl: null };
constructor(
private api: FastifyInstance,
private bus: Bus,
private cfg: () => { serverUrl: string; deviceId: string | null; deviceKey: string | null; name: string; version: string },
) {
bus.on('live', (ev: LiveEvent) => this.send({ t: 'event', event: ev }));
}
start(): void {
this.stopped = false;
this.connect();
}
stop(): void {
this.stopped = true;
if (this.retryTimer) clearTimeout(this.retryTimer);
this.retryTimer = null;
this.cleanup();
this.ws?.close();
this.ws = null;
this.status = { state: 'off', error: null, since: null, serverUrl: null };
}
restart(): void {
this.stop();
this.start();
}
private connect(): void {
const c = this.cfg();
if (!c.deviceId || !c.deviceKey) {
this.status = { state: 'off', error: '사이트 서버에 등록되지 않았습니다', since: null, serverUrl: c.serverUrl };
return;
}
const url = c.serverUrl.replace(/^http/, 'ws').replace(/\/$/, '') + '/device/ws';
this.status = { ...this.status, state: 'connecting', serverUrl: c.serverUrl };
const ws = new WebSocket(url, { headers: { authorization: `Device ${c.deviceId}.${c.deviceKey}` }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024 });
this.ws = ws;
ws.on('open', () => {
this.retries = 0;
this.lastPong = Date.now();
this.status = { state: 'online', error: null, since: Date.now(), serverUrl: c.serverUrl };
log.info(`사이트 서버 연결됨: ${c.serverUrl}`);
this.send({ t: 'hello', name: c.name, version: c.version });
this.pingTimer = setInterval(() => {
if (Date.now() - this.lastPong > 20000) {
log.warn('사이트 서버 응답 없음, 다시 연결');
ws.terminate();
return;
}
this.send({ t: 'ping', ts: Date.now() });
}, 5000);
});
ws.on('message', (data, isBinary) => {
if (isBinary) return;
let msg: RelayToDevice;
try {
msg = JSON.parse(String(data));
} catch {
return;
}
if (msg.t === 'pong') this.lastPong = Date.now();
else if (msg.t === 'req') void this.handle(msg);
});
ws.on('unexpected-response', (_req, res) => {
this.status.error = res.statusCode === 401 ? '기기 인증 실패 (다시 등록해 주세요)' : `서버 응답 ${res.statusCode}`;
});
ws.on('error', (e) => {
this.status.error = this.status.error || e.message;
});
ws.on('close', () => {
this.cleanup();
if (this.ws === ws) this.ws = null;
if (this.stopped) return;
this.status = { ...this.status, state: 'error', since: null };
const delay = Math.min(30000, 1000 * 2 ** Math.min(this.retries++, 5));
this.retryTimer = setTimeout(() => this.connect(), delay);
});
}
private cleanup(): void {
if (this.pingTimer) clearInterval(this.pingTimer);
this.pingTimer = null;
}
private send(m: RelayFromDevice): void {
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(m));
}
private async handle(req: Extract<RelayToDevice, { t: 'req' }>): Promise<void> {
if (!req.path.startsWith('/api/')) {
this.send({ t: 'res', id: req.id, status: 403, headers: { 'content-type': 'application/json' }, body: '{"error":"forbidden"}' });
return;
}
try {
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = req.headers[k];
if (req.user) headers['x-gvr-user'] = encodeURIComponent(JSON.stringify(req.user));
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: req.body ?? undefined });
const outHeaders: Record<string, string> = {};
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length']) {
const v = res.headers[k];
if (v !== undefined) outHeaders[k] = String(v);
}
const ct = outHeaders['content-type'] || '';
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream')) {
this.send({ t: 'res_head', id: req.id, status: res.statusCode, headers: outHeaders });
const idBuf = Buffer.from(req.id, 'utf8');
const head = Buffer.alloc(4);
head.writeUInt32BE(idBuf.length, 0);
this.ws?.send(Buffer.concat([head, idBuf, res.rawPayload]), { binary: true });
this.send({ t: 'res_end', id: req.id });
} else {
this.send({ t: 'res', id: req.id, status: res.statusCode, headers: outHeaders, body: res.payload });
}
} catch (e: any) {
this.send({ t: 'res', id: req.id, status: 500, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ error: 'internal', message: e.message }) });
}
}
}
/** 1회용 등록 코드로 이 PC 를 사이트 서버에 등록한다 */
export async function registerDevice(serverUrl: string, code: string, name: string): Promise<{ deviceId: string; deviceKey: string }> {
const r = await fetch(serverUrl.replace(/\/$/, '') + '/device/register', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ code: code.trim(), name }),
});
const data: any = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(data.message || (r.status === 400 || r.status === 404 ? '등록 코드가 올바르지 않거나 만료되었습니다' : `서버 오류 ${r.status}`));
return { deviceId: data.deviceId, deviceKey: data.deviceKey };
}

89
app/src/core/retention.ts Normal file
View File

@@ -0,0 +1,89 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Store } from './db/db.js';
import { logger } from './util/log.js';
const log = logger('retention');
/**
* 음성 7일 자동 삭제 (Q9, A2): 음성 파일만 지우고 텍스트·경기 기록은 남긴다.
* 학습 데이터(training/)는 대상이 아니다 (A3). 시작할 때와 매일 새벽 4시에 돈다.
*/
export class Retention {
private timer: NodeJS.Timeout | null = null;
constructor(
private store: Store,
private days: () => number,
private audioDir: () => string,
) {}
start(): void {
this.run();
this.schedule();
}
stop(): void {
if (this.timer) clearTimeout(this.timer);
this.timer = null;
}
private schedule(): void {
const now = new Date();
const next = new Date(now);
next.setHours(4, 0, 0, 0);
if (next <= now) next.setDate(next.getDate() + 1);
this.timer = setTimeout(() => {
this.run();
this.schedule();
}, next.getTime() - now.getTime());
}
run(now = Date.now()): { deleted: number; freedBytes: number } {
const before = now - this.days() * 24 * 3600 * 1000;
let deleted = 0;
let freed = 0;
for (const r of this.store.expiredAudio(before)) {
try {
freed += fs.statSync(r.audio_path).size;
fs.rmSync(r.audio_path, { force: true });
} catch {
/* 이미 없음 */
}
this.store.markAudioDeleted(r.id);
deleted++;
}
// 빈 날짜 폴더 정리
try {
for (const d of fs.readdirSync(this.audioDir())) {
const p = path.join(this.audioDir(), d);
if (fs.statSync(p).isDirectory() && fs.readdirSync(p).length === 0) fs.rmdirSync(p);
}
} catch {
/* 폴더 없음 */
}
if (deleted) log.info(`보관 기간 지난 음성 ${deleted}개 삭제 (${(freed / 1048576).toFixed(1)}MB)`);
return { deleted, freedBytes: freed };
}
}
export function dirSize(dir: string): number {
let total = 0;
const walk = (d: string) => {
let ents: fs.Dirent[] = [];
try {
ents = fs.readdirSync(d, { withFileTypes: true });
} catch {
return;
}
for (const e of ents) {
const p = path.join(d, e.name);
if (e.isDirectory()) walk(p);
else
try {
total += fs.statSync(p).size;
} catch {
/* 무시 */
}
}
};
walk(dir);
return total;
}

217
app/src/core/settings.ts Normal file
View File

@@ -0,0 +1,217 @@
import fs from 'node:fs';
import path from 'node:path';
export interface Settings {
version: 1;
firstRunDone: boolean;
discord: {
guildId: string | null;
/** 따라갈 유저 (보통 게임 PC 주인) */
followUserId: string | null;
followEnabled: boolean;
commandsEnabled: boolean;
ttsEnabled: boolean;
ttsText: string;
ttsOnNewMember: boolean;
ttsVoice: string;
};
games: {
valorant: boolean;
lol: boolean;
lolChatOcr: boolean;
lolOcrRegion: { x: number; y: number; w: number; h: number };
lolLogsDir: string | null;
};
stt: {
realtimeModel: string;
preciseModel: string;
device: 'cuda' | 'cpu';
computeType: string;
modelsDir: string | null;
reprocessAfterMatch: boolean;
gameVramReserveMb: number;
};
audio: {
targetLufs: number;
denoise: boolean;
noiseSensitivity: number;
silenceMs: number;
maxUtteranceSec: number;
};
dictionary: {
packs: Record<string, boolean>;
applySiteCorrections: boolean;
};
storage: {
audioDir: string | null;
retentionDays: number;
};
site: {
serverUrl: string;
deviceId: string | null;
deviceName: string;
};
general: {
autoStart: boolean;
sfx: boolean;
};
finetune: {
schedule: 'off' | 'nightly';
activeModel: string | null;
previousModel: string | null;
};
}
export interface Secrets {
botToken?: string;
deviceKey?: string;
riotApiKey?: string;
}
export const DEFAULT_TTS_TEXT =
'겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.';
export function defaultSettings(): Settings {
return {
version: 1,
firstRunDone: false,
discord: {
guildId: null,
followUserId: null,
followEnabled: true,
commandsEnabled: true,
ttsEnabled: true,
ttsText: DEFAULT_TTS_TEXT,
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
},
games: {
valorant: true,
lol: true,
lolChatOcr: true,
lolOcrRegion: { x: 0.0, y: 0.6, w: 0.3, h: 0.27 },
lolLogsDir: null,
},
stt: {
realtimeModel: 'large-v3-turbo',
preciseModel: 'large-v3',
device: 'cuda',
computeType: 'float16',
modelsDir: null,
reprocessAfterMatch: true,
gameVramReserveMb: 3072,
},
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
dictionary: {
packs: { valorant: true, valorant_callouts: true, lol: true, lol_skills: true, game: true, daily: true, university: true, slang20s: true },
applySiteCorrections: true,
},
storage: { audioDir: null, retentionDays: 7 },
site: { serverUrl: 'https://gvr.tkrmagid.kr', deviceId: null, deviceName: 'GAME-PC' },
general: { autoStart: false, sfx: true },
finetune: { schedule: 'off', activeModel: null, previousModel: null },
};
}
function deepMerge<T>(base: T, over: any): T {
if (over === undefined || over === null || typeof base !== 'object' || base === null || Array.isArray(base)) {
return (over ?? base) as T;
}
const out: any = { ...base };
for (const k of Object.keys(over)) {
const b = (base as any)[k];
out[k] = b && typeof b === 'object' && !Array.isArray(b) ? deepMerge(b, over[k]) : over[k];
}
return out;
}
/** 비밀값 암호화 방식. Electron 에서는 safeStorage(DPAPI), 헤드리스는 평문(0600). */
export interface SecretCodec {
name: string;
encrypt(plain: string): Buffer;
decrypt(data: Buffer): string;
}
export const plainCodec: SecretCodec = {
name: 'plain',
encrypt: (s) => Buffer.from(s, 'utf8'),
decrypt: (b) => b.toString('utf8'),
};
export class SettingsStore {
private file: string;
private secretFile: string;
private cur: Settings;
private secrets: Secrets;
private listeners = new Set<(s: Settings) => void>();
constructor(
private dataDir: string,
private codec: SecretCodec = plainCodec,
) {
this.file = path.join(dataDir, 'settings.json');
this.secretFile = path.join(dataDir, 'secrets.bin');
this.cur = defaultSettings();
try {
this.cur = deepMerge(defaultSettings(), JSON.parse(fs.readFileSync(this.file, 'utf8')));
} catch {
/* 첫 실행 */
}
this.secrets = {};
try {
this.secrets = JSON.parse(this.codec.decrypt(fs.readFileSync(this.secretFile)));
} catch {
/* 없음 */
}
// 개발/헤드리스: 환경변수로 비밀값 주입
if (process.env.GVR_BOT_TOKEN) this.secrets.botToken = process.env.GVR_BOT_TOKEN;
}
get(): Settings {
return this.cur;
}
update(patch: any): Settings {
this.cur = deepMerge(this.cur, patch);
this.save();
for (const l of this.listeners) l(this.cur);
return this.cur;
}
onChange(fn: (s: Settings) => void): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
save(): void {
fs.mkdirSync(this.dataDir, { recursive: true });
const tmp = this.file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(this.cur, null, 2));
fs.renameSync(tmp, this.file);
}
getSecret<K extends keyof Secrets>(k: K): Secrets[K] {
return this.secrets[k];
}
hasSecret(k: keyof Secrets): boolean {
return !!this.secrets[k];
}
setSecret<K extends keyof Secrets>(k: K, v: Secrets[K] | null): void {
if (v === null || v === undefined || v === '') delete this.secrets[k];
else this.secrets[k] = v;
fs.mkdirSync(this.dataDir, { recursive: true });
fs.writeFileSync(this.secretFile, this.codec.encrypt(JSON.stringify(this.secrets)), { mode: 0o600 });
for (const l of this.listeners) l(this.cur);
}
get codecName(): string {
return this.codec.name;
}
}
export function resolvePaths(dataDir: string, s: Settings) {
return {
dataDir,
db: path.join(dataDir, 'gvr.sqlite'),
audio: s.storage.audioDir || path.join(dataDir, 'audio'),
training: path.join(dataDir, 'training'),
models: s.stt.modelsDir || path.join(dataDir, 'models'),
tts: path.join(dataDir, 'tts'),
logs: path.join(dataDir, 'logs'),
};
}
export type Paths = ReturnType<typeof resolvePaths>;

View File

@@ -0,0 +1,282 @@
import fs from 'node:fs';
import type { Store, UtteranceRow } from '../db/db.js';
import type { Dictionary, DictContext } from '../dict/dictionary.js';
import type { Settings } from '../settings.js';
import type { Timeline } from '../timeline.js';
import type { Bus } from '../util/events.js';
import { logger } from '../util/log.js';
import { WorkerClient, WorkerError, type TranscribeResult } from './worker.js';
const log = logger('stt');
type Slot = 'realtime' | 'precise';
interface Job {
id: string;
slot: Slot;
/** 낮을수록 먼저 */
prio: number;
}
export interface SttStatus {
worker: 'starting' | 'ready' | 'down';
slots: Record<Slot, { model: string | null; state: 'empty' | 'loading' | 'loaded' | 'missing' | 'error'; error?: string }>;
queue: number;
processing: string | null;
device: string | null;
lastError: string | null;
}
/**
* 녹음과 STT 를 분리하는 대기열 (N-05). 발화는 DB 에 'pending' 으로 먼저 저장되고, 여기서 하나씩 변환한다.
* 프로그램을 다시 켜면 pending 을 다시 넣는다.
* 경기 중에는 실시간 모델, 경기가 끝나면 같은 구간을 정밀 모델로 다시 변환한다 (Q4).
*/
export class SttPipeline {
private queue: Job[] = [];
private queued = new Set<string>();
private busy = false;
private processing: string | null = null;
private inMatch = false;
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
private bothFit = true;
status: SttStatus = {
worker: 'starting',
slots: { realtime: { model: null, state: 'empty' }, precise: { model: null, state: 'empty' } },
queue: 0,
processing: null,
device: null,
lastError: null,
};
constructor(
private worker: WorkerClient,
private store: Store,
private dict: Dictionary,
private timeline: Timeline,
private bus: Bus,
private settings: () => Settings,
) {
worker.on('ready', (r) => {
this.status.worker = 'ready';
this.status.device = r?.device ?? null;
void this.prepareModels();
});
worker.on('exit', () => {
this.status.worker = 'down';
this.status.slots.realtime.state = 'empty';
this.status.slots.precise.state = 'empty';
});
}
/** 설치된 모델을 슬롯에 올린다. 없으면 'missing' 으로 두고 발화는 pending 으로 쌓인다. */
async prepareModels(): Promise<void> {
const s = this.settings().stt;
try {
const gi = await this.worker.request('gpu_info', {}, 30000);
const g = gi?.gpus?.[0];
if (g) this.bothFit = g.vram_total_mb - s.gameVramReserveMb >= 9000;
else this.bothFit = false;
} catch {
this.bothFit = false;
}
await this.load('realtime', s.realtimeModel);
if (this.bothFit && !this.inMatch) await this.load('precise', s.preciseModel);
this.pump();
}
private async installed(): Promise<Set<string>> {
try {
const r = await this.worker.request('models', {}, 30000);
return new Set((r.models || []).filter((m: any) => m.installed).map((m: any) => m.name));
} catch {
return new Set();
}
}
async load(slot: Slot, model: string): Promise<boolean> {
const s = this.settings().stt;
const st = this.status.slots[slot];
if (st.model === model && st.state === 'loaded') return true;
const inst = await this.installed();
// 파인튜닝한 모델 이름이나 경로도 그대로 넘긴다 (워커가 해석)
if (!inst.has(model) && !model.includes('/') && !model.includes('\\') && !model.includes('-ft-')) {
st.model = model;
st.state = 'missing';
return false;
}
st.model = model;
st.state = 'loading';
try {
await this.worker.request('load', { slot, model, device: s.device, compute_type: s.computeType }, 15 * 60000);
st.state = 'loaded';
st.error = undefined;
log.info(`${slot} 모델 적재: ${model}`);
return true;
} catch (e: any) {
st.state = 'error';
st.error = e.message;
this.status.lastError = e.message;
log.error(`${slot} 모델 적재 실패: ${model}`, e);
return false;
}
}
async unload(slot: Slot): Promise<void> {
try {
await this.worker.request('unload', { slot }, 60000);
} catch {
/* 무시 */
}
this.status.slots[slot].state = 'empty';
}
/** 시작 시 미처리분 복구 */
resumePending(): void {
const rows = this.store.pendingUtterances();
if (rows.length) log.info(`미처리 발화 ${rows.length}개 다시 대기열에 넣음`);
for (const r of rows) this.enqueue(r.id, 'realtime', 5);
}
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10): void {
const key = `${slot}:${id}`;
if (this.queued.has(key)) return;
this.queued.add(key);
this.queue.push({ id, slot, prio });
this.queue.sort((a, b) => a.prio - b.prio);
this.status.queue = this.queue.length;
this.pump();
}
async onMatchStart(): Promise<void> {
this.inMatch = true;
// VRAM 이 빠듯하면 경기 중에는 정밀 모델을 내린다 (게임 프레임 보호)
if (!this.bothFit && this.status.slots.precise.state === 'loaded') await this.unload('precise');
}
async onMatchEnd(from: number, to: number): Promise<void> {
this.inMatch = false;
const s = this.settings().stt;
if (!s.reprocessAfterMatch || s.preciseModel === s.realtimeModel) return;
if (this.status.slots.precise.state !== 'loaded') await this.load('precise', s.preciseModel);
if (this.status.slots.precise.state !== 'loaded') return;
const rows = this.store.realtimeUtterancesInRange(from, to);
log.info(`경기 종료: ${rows.length}개 발화를 정밀 모델로 다시 변환`);
for (const r of rows) this.enqueue(r.id, 'precise', 10);
}
private pickSlot(job: Job): Slot | null {
const { realtime, precise } = this.status.slots;
if (job.slot === 'precise') return precise.state === 'loaded' ? 'precise' : null;
// 경기 밖이고 정밀 모델이 올라와 있으면 처음부터 정밀 모델로
if (!this.inMatch && precise.state === 'loaded' && this.queue.length < 20) return 'precise';
if (realtime.state === 'loaded') return 'realtime';
if (precise.state === 'loaded') return 'precise';
return null;
}
private pump(): void {
if (this.busy || !this.worker.ready) return;
const idx = this.queue.findIndex((j) => this.pickSlot(j) !== null);
if (idx < 0) return;
const job = this.queue.splice(idx, 1)[0];
this.queued.delete(`${job.slot}:${job.id}`);
this.status.queue = this.queue.length;
this.busy = true;
this.processing = job.id;
this.status.processing = job.id;
this.run(job, this.pickSlot(job)!)
.catch((e) => log.error('STT 작업 오류', e))
.finally(() => {
this.busy = false;
this.processing = null;
this.status.processing = null;
setImmediate(() => this.pump());
});
}
/** 이 경기에 나온 요원·챔피언·선수 이름 → 핫워드 맨 앞 */
private matchWords(u: UtteranceRow): string[] {
if (!u.match_id) return [];
const m = this.store.getMatch(u.match_id);
if (!m?.detail) return [];
try {
const det = JSON.parse(m.detail);
const out: string[] = [];
for (const p of det.players || []) {
if (p.character?.name && p.character.name !== '?') out.push(p.character.name);
}
for (const p of det.players || []) if (p.name && p.name !== '?') out.push(p.name);
return out;
} catch {
return [];
}
}
private dictContext(u: UtteranceRow): DictContext {
if (!u.match_id) return 'none';
return (this.store.getMatch(u.match_id)?.game as DictContext) || 'none';
}
private async run(job: Job, slot: Slot): Promise<void> {
const u = this.store.getUtterance(job.id);
if (!u || !u.audio_path || u.audio_deleted) return;
if (!fs.existsSync(u.audio_path)) {
this.store.markUtteranceFailed(u.id);
return;
}
if (job.slot === 'precise' && (u.corrected || u.status === 'precise')) return;
const s = this.settings();
const ctx = this.dictContext(u);
const user = this.store.getUser(u.user_id);
let r: TranscribeResult;
try {
r = await this.worker.request<TranscribeResult>(
'transcribe',
{
slot,
path: u.audio_path,
hotwords: this.dict.hotwords(ctx, this.matchWords(u)),
initial_prompt: null,
corrections: this.dict.corrections(),
dictionary: this.dict.candidates(ctx),
profile_lufs: user?.gain_lufs ?? null,
target_lufs: s.audio.targetLufs,
noise_sensitivity: s.audio.noiseSensitivity,
denoise: s.audio.denoise,
},
5 * 60000,
);
} catch (e: any) {
const attempts = this.store.bumpAttempt(u.id);
this.status.lastError = e.message;
log.warn(`STT 실패 (${u.id}, ${attempts}회): ${e.message}`);
if (e instanceof WorkerError && (e.code === 'worker_exit' || e.code === 'worker_down') && attempts < 3) {
this.enqueue(u.id, job.slot, job.prio + 1);
} else if (attempts >= 3) {
this.store.markUtteranceFailed(u.id);
this.emit(u.id);
} else this.enqueue(u.id, job.slot, job.prio + 2);
return;
}
this.store.updateUtteranceResult(u.id, {
text: r.text,
raw_text: r.raw_text,
words: r.words,
noise: r.noise,
noise_reason: r.noise_reason,
confidence: r.confidence,
lufs: r.lufs,
gain_db: r.gain_db,
model: r.model,
status: slot,
});
if (!r.noise && r.lufs !== null && r.duration_s >= 1) this.store.updateGainProfile(u.user_id, r.lufs);
if (r.text) this.store.hitDict(r.words.map((w) => w.w));
this.emit(u.id);
}
private emit(id: string): void {
const row = this.store.getUtterance(id);
if (row) this.bus.live({ type: 'utterance.updated', data: this.timeline.utteranceItem(row) });
}
}

169
app/src/core/stt/worker.ts Normal file
View File

@@ -0,0 +1,169 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { EventEmitter } from 'node:events';
import readline from 'node:readline';
import os from 'node:os';
import { logger } from '../util/log.js';
const log = logger('worker');
export interface WorkerCommand {
/** 실행 파일 (gvr-worker.exe 또는 python) */
cmd: string;
args: string[];
cwd?: string;
env?: Record<string, string>;
}
export interface TranscribeResult {
text: string | null;
raw_text: string | null;
words: { w: string; s: number; e: number; p?: number }[];
noise: boolean;
noise_reason: string | null;
confidence: number | null;
lufs: number | null;
gain_db: number;
speech_ratio: number;
duration_s: number;
model: string;
elapsed_ms: number;
}
type Pending = { resolve: (v: any) => void; reject: (e: Error) => void; op: string; onEvent?: (ev: any) => void };
export class WorkerError extends Error {
constructor(
public code: string,
message: string,
) {
super(message);
}
}
/**
* STT 워커 프로세스 (JSON Lines). 죽으면 자동으로 다시 띄우고, 진행 중이던 요청은 실패로 돌려준다.
* docs/dev/ARCHITECTURE.md 1장.
*/
export class WorkerClient extends EventEmitter {
private proc: ChildProcess | null = null;
private seq = 0;
private pending = new Map<string, Pending>();
private stopping = false;
private restarts = 0;
ready = false;
lastError: string | null = null;
constructor(private command: WorkerCommand) {
super();
}
start(): void {
this.stopping = false;
this.spawn();
}
private spawn(): void {
const { cmd, args, cwd, env } = this.command;
log.info(`워커 시작: ${cmd} ${args.join(' ')}`);
const p = spawn(cmd, args, {
cwd,
env: { ...process.env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8', ...env },
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
this.proc = p;
// 게임 프레임을 덜 건드리도록 낮은 우선순위
try {
if (p.pid) os.setPriority(p.pid, 10);
} catch {
/* 권한 없음 무시 */
}
readline.createInterface({ input: p.stdout! }).on('line', (line) => this.onLine(line));
readline.createInterface({ input: p.stderr! }).on('line', (line) => {
if (line.trim()) log.debug(line);
if (/Traceback|Error/.test(line)) this.lastError = line.slice(0, 500);
});
p.on('error', (e) => {
this.lastError = e.message;
log.error('워커 실행 실패', e);
});
p.on('exit', (code, sig) => {
this.ready = false;
this.proc = null;
for (const [, pend] of this.pending) pend.reject(new WorkerError('worker_exit', `워커 종료 (code=${code} sig=${sig})`));
this.pending.clear();
this.emit('exit', code);
if (this.stopping) return;
this.restarts++;
const delay = Math.min(30000, 1000 * 2 ** Math.min(this.restarts, 5));
log.warn(`워커가 종료됨 (code=${code}). ${delay / 1000}초 뒤 다시 시작`);
setTimeout(() => !this.stopping && this.spawn(), delay);
});
this.request('hello', {}, 30000)
.then((r) => {
this.ready = true;
this.restarts = 0;
log.info(`워커 준비됨 ${JSON.stringify(r)}`);
this.emit('ready', r);
})
.catch((e) => log.error('워커 hello 실패', e));
}
private onLine(line: string): void {
let msg: any;
try {
msg = JSON.parse(line);
} catch {
log.debug(`워커 stdout(비프로토콜): ${line}`);
return;
}
if (msg.event) {
if (msg.id && this.pending.has(msg.id)) this.pending.get(msg.id)!.onEvent?.(msg);
this.emit('event', msg);
return;
}
const pend = this.pending.get(msg.id);
if (!pend) return;
this.pending.delete(msg.id);
if (msg.ok) pend.resolve(msg.result);
else pend.reject(new WorkerError(msg.error?.code || 'error', msg.error?.message || '워커 오류'));
}
request<T = any>(op: string, params: Record<string, unknown>, timeoutMs = 600000, onEvent?: (ev: any) => void): Promise<T> {
if (!this.proc || !this.proc.stdin) return Promise.reject(new WorkerError('worker_down', 'STT 워커가 실행 중이 아닙니다'));
const id = String(++this.seq);
return new Promise<T>((resolve, reject) => {
const timer =
timeoutMs > 0
? setTimeout(() => {
if (this.pending.delete(id)) reject(new WorkerError('timeout', `${op} 시간 초과`));
}, timeoutMs)
: null;
this.pending.set(id, {
op,
onEvent,
resolve: (v) => {
if (timer) clearTimeout(timer);
resolve(v);
},
reject: (e) => {
if (timer) clearTimeout(timer);
reject(e);
},
});
this.proc!.stdin!.write(JSON.stringify({ id, op, ...params }) + '\n');
});
}
async stop(): Promise<void> {
this.stopping = true;
if (!this.proc) return;
const p = this.proc;
try {
await Promise.race([this.request('shutdown', {}, 5000), new Promise((r) => setTimeout(r, 5000))]);
} catch {
/* 무시 */
}
if (p.exitCode === null) p.kill();
}
}

243
app/src/core/timeline.ts Normal file
View File

@@ -0,0 +1,243 @@
import type { EventItem, TimeLabel, TimelineItem, TimelinePage, UtteranceItem, GameType } from '@gvr/shared';
import { fmtClock, fmtReal } from '@gvr/shared';
import type { EventRow, MatchRow, RoundRow, Store, UtteranceRow } from './db/db.js';
export interface MatchCtx {
match: MatchRow;
rounds: RoundRow[];
}
/** 시간 표시 규칙 (보고서 6-3, Q5): 발로란트 "R7 · 0:42" + 경기 경과, 롤 게임 시간, 경기 밖 현실 시각 */
export function timeLabel(ts: number, ctx: MatchCtx | null): TimeLabel {
if (!ctx) return { primary: fmtReal(ts), real: ts };
const { match, rounds } = ctx;
const gameTs = ts - match.clock_offset;
const elapsed = gameTs - match.started_at;
// 경기 전(챔피언 선택 채팅 등)·경기 후는 현실 시각
if (elapsed < -1000 || (match.ended_at && ts > match.ended_at + 1000)) return { primary: fmtReal(ts), real: ts };
if (match.game === 'lol') return { primary: fmtClock(Math.max(0, elapsed)), real: ts };
// 발로란트
const r = rounds.find((x) => gameTs >= x.started_at && gameTs <= x.ended_at) ?? rounds.find((x) => gameTs < x.started_at && x.num === 1);
if (r) {
if (gameTs < r.combat_at) return { primary: `R${r.num} · 구매`, secondary: fmtClock(Math.max(0, elapsed)), real: ts };
return { primary: `R${r.num} · ${fmtClock(gameTs - r.combat_at)}`, secondary: fmtClock(Math.max(0, elapsed)), real: ts };
}
return { primary: fmtClock(Math.max(0, elapsed)), secondary: '경기 중', real: ts };
}
export function roundAt(ts: number, ctx: MatchCtx | null): number | undefined {
if (!ctx || ctx.match.game !== 'valorant') return undefined;
const gameTs = ts - ctx.match.clock_offset;
return ctx.rounds.find((x) => gameTs >= x.started_at && gameTs <= x.ended_at)?.num;
}
export class Timeline {
constructor(private store: Store) {}
private ctxCache = new Map<string, { at: number; ctx: MatchCtx }>();
ctx(matchId: string | null | undefined): MatchCtx | null {
if (!matchId) return null;
const c = this.ctxCache.get(matchId);
if (c && Date.now() - c.at < 5000) return c.ctx;
const match = this.store.getMatch(matchId);
if (!match) return null;
const ctx = { match, rounds: this.store.rounds(matchId) };
this.ctxCache.set(matchId, { at: Date.now(), ctx });
return ctx;
}
invalidate(matchId?: string): void {
if (matchId) this.ctxCache.delete(matchId);
else this.ctxCache.clear();
}
utteranceItem(u: UtteranceRow): UtteranceItem {
const ctx = this.ctx(u.match_id);
return {
kind: 'utterance',
id: u.id,
ts: u.started_at,
endTs: u.ended_at,
userId: u.user_id,
text: u.noise && !u.corrected ? null : u.text,
words: u.noise && !u.corrected ? [] : safeJson(u.words, []),
noise: !!u.noise && !u.corrected,
status: u.status as UtteranceItem['status'],
corrected: !!u.corrected,
confidence: u.confidence,
model: u.model,
audio:
u.audio_path && !u.audio_deleted
? { url: `/api/audio/${u.id}`, durationMs: u.ended_at - u.started_at, gainDb: u.gain_db ?? 0 }
: null,
game: ctx ? { type: ctx.match.game as GameType, matchId: ctx.match.id, round: roundAt(u.started_at, ctx) } : null,
time: timeLabel(u.started_at, ctx),
};
}
eventItem(e: EventRow): EventItem {
const ctx = this.ctx(e.match_id);
const data = safeJson(e.data, {});
const userId = e.actor_puuid ? this.store.userIdForPuuid(e.actor_puuid) : undefined;
return {
kind: 'event',
id: e.id,
ts: e.ts,
game: e.game,
matchId: e.match_id,
type: e.type as EventItem['type'],
data,
time: timeLabel(e.ts, ctx),
...(userId ? { userId } : {}),
};
}
query(q: TimelineQuery): TimelinePage {
const limit = Math.min(Math.max(q.limit ?? 100, 1), 500);
const desc = q.order !== 'asc';
const cur = q.cursor ? parseCursor(q.cursor) : null;
const types = q.types && q.types.length ? new Set(q.types) : null;
const wantUtt = !types || types.has('utterance');
const eventTypes = types
? [...types].flatMap((t) => (t === 'round' ? ['round_end'] : t === 'match' ? ['match_start', 'match_end'] : t === 'utterance' ? [] : [t]))
: null;
const wantEvents = (!types || (eventTypes && eventTypes.length > 0)) && q.game !== 'none';
const cmp = desc ? '<' : '>';
const ord = desc ? 'DESC' : 'ASC';
let utts: UtteranceRow[] = [];
if (wantUtt) {
const where: string[] = [];
const args: any[] = [];
if (cur) {
where.push(`(u.started_at ${cmp} ? OR (u.started_at = ? AND u.id ${cmp} ?))`);
args.push(cur.ts, cur.ts, cur.id);
}
if (q.users?.length) {
where.push(`u.user_id IN (${q.users.map(() => '?').join(',')})`);
args.push(...q.users);
}
if (q.match) {
where.push('u.match_id = ?');
args.push(q.match);
} else if (q.game === 'none') where.push('u.match_id IS NULL');
else if (q.game) {
where.push('u.match_id IN (SELECT id FROM matches WHERE game = ?)');
args.push(q.game);
}
if (q.from) {
where.push('u.started_at >= ?');
args.push(q.from);
}
if (q.to) {
where.push('u.started_at <= ?');
args.push(q.to);
}
if (q.hideNoise) where.push('(u.noise = 0 OR u.corrected = 1)');
if (q.q) {
const kw = q.q.trim();
if ([...kw].length >= 3) {
where.push('u.rowid IN (SELECT rowid FROM utterances_fts WHERE utterances_fts MATCH ?)');
args.push(`"${kw.replace(/"/g, '""')}"`);
} else {
where.push('u.text LIKE ?');
args.push(`%${kw.replace(/[%_]/g, '')}%`);
}
}
utts = this.store.db
.prepare(
`SELECT u.rowid, u.* FROM utterances u ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
ORDER BY u.started_at ${ord}, u.id ${ord} LIMIT ?`,
)
.all(...args, limit + 1) as UtteranceRow[];
}
let evs: EventRow[] = [];
if (wantEvents) {
const where: string[] = [];
const args: any[] = [];
if (cur) {
where.push(`(e.ts ${cmp} ? OR (e.ts = ? AND e.id ${cmp} ?))`);
args.push(cur.ts, cur.ts, cur.id);
}
if (eventTypes) {
where.push(`e.type IN (${eventTypes.map(() => '?').join(',')})`);
args.push(...eventTypes);
}
if (q.match) {
where.push('e.match_id = ?');
args.push(q.match);
} else if (q.game) {
where.push('e.game = ?');
args.push(q.game);
}
if (q.users?.length) {
const puuids = this.store
.listAccounts()
.filter((a) => q.users!.includes(a.user_id))
.map((a) => a.puuid);
if (!puuids.length) where.push('0');
else {
const ph = puuids.map(() => '?').join(',');
where.push(`(e.actor_puuid IN (${ph}) OR e.target_puuid IN (${ph}))`);
args.push(...puuids, ...puuids);
}
}
if (q.from) {
where.push('e.ts >= ?');
args.push(q.from);
}
if (q.to) {
where.push('e.ts <= ?');
args.push(q.to);
}
if (q.q) {
where.push(`e.type = 'chat' AND e.data LIKE ?`);
args.push(`%${q.q.trim().replace(/[%_]/g, '')}%`);
}
evs = this.store.db
.prepare(`SELECT e.* FROM game_events e ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY e.ts ${ord}, e.id ${ord} LIMIT ?`)
.all(...args, limit + 1) as EventRow[];
}
const merged: { ts: number; id: string; item: () => TimelineItem }[] = [
...utts.map((u) => ({ ts: u.started_at, id: u.id, item: () => this.utteranceItem(u) })),
...evs.map((e) => ({ ts: e.ts, id: e.id, item: () => this.eventItem(e) })),
];
merged.sort((a, b) => (desc ? b.ts - a.ts || (b.id < a.id ? -1 : 1) : a.ts - b.ts || (a.id < b.id ? -1 : 1)));
const page = merged.slice(0, limit);
const hasMore = merged.length > limit;
const last = page[page.length - 1];
return { items: page.map((p) => p.item()), next: hasMore && last ? `${last.ts}:${last.id}` : null };
}
}
export interface TimelineQuery {
users?: string[];
game?: 'valorant' | 'lol' | 'none';
match?: string;
from?: number;
to?: number;
q?: string;
types?: string[];
hideNoise?: boolean;
cursor?: string;
limit?: number;
order?: 'asc' | 'desc';
}
function parseCursor(c: string): { ts: number; id: string } | null {
const i = c.indexOf(':');
if (i < 0) return null;
const ts = Number(c.slice(0, i));
return Number.isFinite(ts) ? { ts, id: c.slice(i + 1) } : null;
}
export function safeJson<T>(s: string | null | undefined, d: T): T {
if (!s) return d;
try {
return JSON.parse(s) as T;
} catch {
return d;
}
}

View File

@@ -0,0 +1,9 @@
import { EventEmitter } from 'node:events';
import type { LiveEvent } from '@gvr/shared';
/** 코어 내부 이벤트 버스. 'live' 는 사이트로 그대로 나가는 이벤트. */
export class Bus extends EventEmitter {
live(ev: LiveEvent): void {
this.emit('live', ev);
}
}

13
app/src/core/util/ids.ts Normal file
View File

@@ -0,0 +1,13 @@
import crypto from 'node:crypto';
/** 시간순 정렬되는 짧은 ID (ms 타임스탬프 base36 + 랜덤) */
export function newId(ts = Date.now()): string {
return ts.toString(36).padStart(9, '0') + crypto.randomBytes(5).toString('hex');
}
const PALETTE = ['#ff4655', '#14c1b7', '#c8aa6e', '#7aa2ff', '#f5a623', '#b48cff', '#5fd068', '#ff7ab6', '#4fd1ff', '#ffd45c'];
export function colorFor(id: string): string {
let h = 0;
for (const c of id) h = (h * 31 + c.charCodeAt(0)) >>> 0;
return PALETTE[h % PALETTE.length];
}

49
app/src/core/util/log.ts Normal file
View File

@@ -0,0 +1,49 @@
import fs from 'node:fs';
import path from 'node:path';
type Level = 'debug' | 'info' | 'warn' | 'error';
const order: Record<Level, number> = { debug: 10, info: 20, warn: 30, error: 40 };
let minLevel: Level = (process.env.GVR_LOG_LEVEL as Level) || 'info';
let stream: fs.WriteStream | null = null;
const listeners = new Set<(line: string) => void>();
export function initLogFile(dir: string): void {
fs.mkdirSync(dir, { recursive: true });
const day = new Date().toISOString().slice(0, 10);
stream = fs.createWriteStream(path.join(dir, `gvr-${day}.log`), { flags: 'a' });
}
export function setLogLevel(l: Level): void {
minLevel = l;
}
export function onLog(fn: (line: string) => void): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
function write(level: Level, scope: string, msg: string, extra?: unknown): void {
if (order[level] < order[minLevel]) return;
let line = `${new Date().toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}`;
if (extra !== undefined) {
if (extra instanceof Error) line += ` ${extra.stack || extra.message}`;
else {
try {
line += ' ' + JSON.stringify(extra);
} catch {
line += ' ' + String(extra);
}
}
}
(level === 'error' || level === 'warn' ? process.stderr : process.stdout).write(line + '\n');
stream?.write(line + '\n');
for (const l of listeners) l(line);
}
export function logger(scope: string) {
return {
debug: (m: string, e?: unknown) => write('debug', scope, m, e),
info: (m: string, e?: unknown) => write('info', scope, m, e),
warn: (m: string, e?: unknown) => write('warn', scope, m, e),
error: (m: string, e?: unknown) => write('error', scope, m, e),
};
}
export type Logger = ReturnType<typeof logger>;