WIP v1.3.7: 기록 묶음(경기 · 경기 전후 대화) 관리 · zip 내보내기/받아오기

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-16 05:21:32 +09:00
parent 98b8342678
commit c397bacf8c
23 changed files with 1376 additions and 17 deletions

View File

@@ -9,6 +9,7 @@ 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';
import { BundleError, type Bundles } from '../bundles.js';
export interface ApiDeps {
store: Store;
@@ -21,6 +22,8 @@ export interface ApiDeps {
trainingDir: () => string;
overviewExtra: () => { guild: Overview['guild']; recording: Overview['recording'] };
version: string;
/** 기록 묶음 (없으면 /api/bundles 없음) */
bundles?: Bundles;
}
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
@@ -154,6 +157,52 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
};
});
// ---- 기록 묶음: 경기별 · 경기 전후 대화별로 보기 · 지우기 · zip 내보내기 · zip 받아오기 (v1.3.7)
// zip 은 사이트 서버가 조각으로 나눠 보낸다. 300MB 까지
app.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body));
const bundleErr = (reply: any, e: unknown) => {
if (e instanceof BundleError) return reply.code(e.code === 'not_found' ? 404 : 400).send({ error: e.code, message: e.message });
throw e;
};
app.get('/api/bundles', async (_req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
return { bundles: d.bundles.list() };
});
app.post<{ Body: { ids?: string[] } }>('/api/bundles/delete', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
try {
const ids = Array.isArray(req.body?.ids) ? req.body.ids.map(String) : [];
const r = d.bundles.delete(ids);
timeline.invalidate();
d.bus.live({ type: 'records.changed', data: { reason: 'deleted', ids } });
return r;
} catch (e) {
return bundleErr(reply, e);
}
});
app.get<{ Querystring: { ids?: string } }>('/api/bundles/export', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
try {
const { zip, fileName } = d.bundles.export(String(req.query.ids ?? '').split(',').filter(Boolean));
return reply.header('content-type', 'application/zip').header('content-disposition', `attachment; filename="${fileName}"`).header('cache-control', 'no-store').send(zip);
} catch (e) {
return bundleErr(reply, e);
}
});
app.post('/api/bundles/import', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
if (!Buffer.isBuffer(req.body)) return reply.code(400).send({ error: 'invalid_bundle', message: '받아오기 실패: zip 파일을 보내 주세요' });
try {
const r = d.bundles.import(req.body);
timeline.invalidate();
d.bus.live({ type: 'records.changed', data: { reason: 'imported' } });
d.bus.live({ type: 'users.updated', data: [] });
return r;
} catch (e) {
return bundleErr(reply, e);
}
});
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' });

425
app/src/core/bundles.ts Normal file
View File

@@ -0,0 +1,425 @@
import fs from 'node:fs';
import path from 'node:path';
import type { BundleImportResult, BundleInfo, GameType } from '@gvr/shared';
import { fmtReal } from '@gvr/shared';
import type { MatchRow, Store, UtteranceRow } from './db/db.js';
import type { GameManager } from './games/manager.js';
import { logger } from './util/log.js';
import { readZip, writeZip, ZipError, type ZipEntry } from './util/zip.js';
const log = logger('bundles');
/** 기록 묶음 zip 형식 (manifest.json · data.json · audio/<발화ID>.ogg · 대화.txt) */
export const BUNDLE_FORMAT = 'gvr-bundle';
export const BUNDLE_VERSION = 1;
/** 경기와 대화를 같은 판으로 볼 최대 간격 */
const NEAR_MS = 30 * 60000;
/** 세션 없는 대화를 나누는 쉼 */
const TALK_GAP_MS = 30 * 60000;
const SAFE_ID = /^[\w.-]{1,80}$/;
export class BundleError extends Error {
constructor(
message: string,
readonly code = 'invalid_bundle',
) {
super(message);
}
}
interface Group {
info: BundleInfo;
/** 이 묶음의 발화 (잡음 포함: 지울 때 함께 지운다) */
ids: string[];
match: MatchRow | null;
}
type Row = Pick<UtteranceRow, 'id' | 'session_id' | 'user_id' | 'started_at' | 'ended_at' | 'match_id' | 'audio_path' | 'audio_deleted' | 'noise' | 'corrected'>;
/**
* 기록 묶음 (v1.3.7): 경기 하나 = 묶음 하나, 경기 밖 대화는 녹음 세션 안에서 경기 사이마다 한 묶음.
* 다음 경기가 30분 안에 시작하면 "경기 전 대화", 지난 경기가 30분 안에 끝났으면 "경기 후 대화", 아니면 "게임 밖 대화".
* 묶음 단위로 지우기 · zip 내보내기 · zip 받아오기를 한다.
*/
export class Bundles {
constructor(
private store: Store,
private games: GameManager,
private audioDir: () => string,
private version: string,
) {}
private groups(): Group[] {
const db = this.store.db;
const rows = db
.prepare('SELECT id, session_id, user_id, started_at, ended_at, match_id, audio_path, audio_deleted, noise, corrected FROM utterances ORDER BY started_at, id')
.all() as Row[];
const matches = this.store.listMatches({ limit: 100000 });
const mStart = (m: MatchRow) => m.started_at + m.clock_offset;
const mEnd = (m: MatchRow) => m.ended_at ?? mStart(m);
const evCount = new Map((db.prepare('SELECT match_id, count(*) n FROM game_events GROUP BY match_id').all() as { match_id: string; n: number }[]).map((r) => [r.match_id, r.n]));
const byMatch = new Map<string, Row[]>();
const talk: Row[] = [];
const known = new Set(matches.map((m) => m.id));
for (const r of rows) {
if (r.match_id && known.has(r.match_id)) {
const list = byMatch.get(r.match_id) ?? [];
list.push(r);
byMatch.set(r.match_id, list);
} else talk.push(r);
}
const out: Group[] = [];
for (const m of matches) {
const list = byMatch.get(m.id) ?? [];
const sum = this.games.summary(m);
const label = `${m.game === 'valorant' ? '발로란트' : '롤'} · ${sum.mode} · ${sum.map.name}`;
const score = sum.score ? ` ${sum.score.ally}:${sum.score.enemy}` : '';
const result = sum.win === true ? '승리' : sum.win === false ? '패배' : null;
out.push({
info: this.info(`match-${m.id}`, 'match', label, [result, score.trim()].filter(Boolean).join(' ') || null, m.game, m.id, Math.min(mStart(m), ...list.map((r) => r.started_at)), Math.max(mEnd(m), ...list.map((r) => r.ended_at)), list, evCount.get(m.id) ?? 0),
ids: list.map((r) => r.id),
match: m,
});
}
// 경기 밖 대화: 세션이 바뀌거나, 사이에 경기가 시작했거나, 30분 넘게 쉬면 새 묶음
const starts = matches.map(mStart).sort((a, b) => a - b);
const runs: Row[][] = [];
for (const r of talk) {
const cur = runs[runs.length - 1];
const prev = cur?.[cur.length - 1];
const split =
!prev ||
(prev.session_id ?? '') !== (r.session_id ?? '') ||
r.started_at - prev.ended_at > TALK_GAP_MS ||
starts.some((s) => s > prev.started_at && s <= r.started_at);
if (split) runs.push([r]);
else cur.push(r);
}
for (const run of runs) {
const from = run[0].started_at;
const to = Math.max(...run.map((r) => r.ended_at));
const next = matches.filter((m) => mStart(m) >= to - 1000 && mStart(m) - to <= NEAR_MS).sort((a, b) => mStart(a) - mStart(b))[0];
const prev = matches.filter((m) => mEnd(m) <= from + 1000 && from - mEnd(m) <= NEAR_MS).sort((a, b) => mEnd(b) - mEnd(a))[0];
const name = (m: MatchRow) => {
const s = this.games.summary(m);
return `${m.game === 'valorant' ? '발로란트' : '롤'} ${s.map.name}`;
};
const [label, sub] = next ? ['경기 전 대화', `다음 경기: ${name(next)}`] : prev ? ['경기 후 대화', `지난 경기: ${name(prev)}`] : ['게임 밖 대화', null];
const info = this.info(`talk-${run[0].id}`, 'talk', label, sub, null, null, from, to, run, 0);
if (!info.utterances) continue; // 잡음만 남은 묶음은 보이지 않는다
out.push({ info, ids: run.map((r) => r.id), match: null });
}
return out.sort((a, b) => b.info.from - a.info.from);
}
private info(id: string, kind: BundleInfo['kind'], label: string, sub: string | null, game: GameType | null, matchId: string | null, from: number, to: number, rows: Row[], events: number): BundleInfo {
const shown = rows.filter((r) => !r.noise || r.corrected);
let audio = 0;
let bytes = 0;
for (const r of shown) {
if (!r.audio_path || r.audio_deleted) continue;
try {
bytes += fs.statSync(r.audio_path).size;
audio++;
} catch {
/* 파일 없음 */
}
}
return {
id,
kind,
label,
sub,
game,
matchId,
from: isFinite(from) ? from : 0,
to: isFinite(to) ? to : from,
utterances: shown.length,
audio,
audioBytes: bytes,
events,
talkMs: shown.reduce((n, r) => n + (r.ended_at - r.started_at), 0),
users: [...new Set(shown.map((r) => r.user_id))],
};
}
list(): BundleInfo[] {
return this.groups().map((g) => g.info);
}
private pick(ids: string[]): Group[] {
if (!ids.length) throw new BundleError('고른 묶음이 없습니다', 'bad_request');
const all = new Map(this.groups().map((g) => [g.info.id, g]));
const out: Group[] = [];
for (const id of ids) {
const g = all.get(id);
if (!g) throw new BundleError(`묶음을 찾을 수 없습니다: ${id} (목록을 새로 고쳐 주세요)`, 'not_found');
out.push(g);
}
return out;
}
// ------------------------------------------------------------------ 지우기
delete(ids: string[]): { bundles: number; utterances: number; files: number } {
const groups = this.pick(ids);
const db = this.store.db;
const uttIds = groups.flatMap((g) => g.ids);
const matchIds = groups.flatMap((g) => (g.match ? [g.match.id] : []));
const files: string[] = [];
const culprit = !!db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='culprit_analyses'`).get();
db.transaction(() => {
for (const id of uttIds) {
const u = this.store.getUtterance(id);
if (u?.audio_path) files.push(u.audio_path);
for (const t of db.prepare('SELECT audio_path FROM training_samples WHERE utterance_id=?').all(id) as { audio_path: string }[]) files.push(t.audio_path);
db.prepare('DELETE FROM training_samples WHERE utterance_id=?').run(id);
db.prepare('DELETE FROM utterance_imports WHERE id=?').run(id);
db.prepare('DELETE FROM utterances WHERE id=?').run(id);
}
for (const m of matchIds) {
db.prepare('DELETE FROM game_events WHERE match_id=?').run(m);
db.prepare('DELETE FROM rounds WHERE match_id=?').run(m);
if (culprit) db.prepare('DELETE FROM culprit_analyses WHERE match_id=?').run(m);
db.prepare('DELETE FROM matches WHERE id=?').run(m);
}
})();
let removed = 0;
for (const f of files) {
try {
if (fs.existsSync(f)) {
fs.rmSync(f, { force: true });
removed++;
}
} catch (e) {
log.warn(`파일 삭제 실패 ${f}`, e);
}
}
log.info(`기록 묶음 ${groups.length}개 삭제: ${groups.map((g) => g.info.label).join(', ')} (발화 ${uttIds.length}개, 파일 ${removed}개)`);
return { bundles: groups.length, utterances: uttIds.length, files: removed };
}
// ------------------------------------------------------------------ 내보내기
export(ids: string[]): { zip: Buffer; fileName: string } {
const groups = this.pick(ids);
const db = this.store.db;
const uttIds = new Set(groups.flatMap((g) => g.ids));
const utts = [...uttIds].map((id) => this.store.getUtterance(id)!).filter(Boolean);
const matches = groups.flatMap((g) => (g.match ? [g.match] : []));
const userIds = new Set(utts.map((u) => u.user_id));
const users = this.store.listUsers().filter((u) => userIds.has(u.id));
const accounts = this.store.listAccounts().filter((a) => userIds.has(a.user_id));
const sessIds = [...new Set(utts.map((u) => u.session_id).filter((s): s is string => !!s))];
const sessions = sessIds.map((s) => db.prepare('SELECT * FROM sessions WHERE id=?').get(s)).filter(Boolean);
const culprit = !!db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='culprit_analyses'`).get();
const entries: ZipEntry[] = [];
const outUtts = utts.map((u) => {
const { audio_path, ...rest } = u as UtteranceRow & { rowid?: number };
delete (rest as any).rowid;
let audio: string | null = null;
if (audio_path && !u.audio_deleted && fs.existsSync(audio_path)) {
audio = `audio/${u.id}.ogg`;
entries.push({ name: audio, data: fs.readFileSync(audio_path) });
}
return { ...rest, audio };
});
const data = {
users: users.map((u) => ({ id: u.id, name: u.name, color: u.color, avatar: u.avatar, excluded: u.excluded })),
accounts,
sessions,
matches,
rounds: matches.flatMap((m) => this.store.rounds(m.id)),
events: matches.flatMap((m) => this.store.events(m.id)),
culprit: culprit ? matches.flatMap((m) => db.prepare('SELECT * FROM culprit_analyses WHERE match_id=?').all(m.id)) : [],
utterances: outUtts,
};
const manifest = {
format: BUNDLE_FORMAT,
version: BUNDLE_VERSION,
app: this.version,
exportedAt: Date.now(),
bundles: groups.map((g) => g.info),
counts: { utterances: outUtts.length, audio: outUtts.filter((u) => u.audio).length, matches: matches.length, events: data.events.length },
};
const name = (id: string) => users.find((u) => u.id === id)?.name ?? id;
const transcript = groups
.map((g) => {
const head = `■ ${g.info.label}${g.info.sub ? ` (${g.info.sub})` : ''} · ${fmtReal(g.info.from)} ~ ${fmtReal(g.info.to)}`;
const lines = outUtts
.filter((u) => g.ids.includes(u.id) && (!u.noise || u.corrected) && u.text)
.sort((a, b) => a.started_at - b.started_at)
.map((u) => `[${fmtReal(u.started_at)}] ${name(u.user_id)}: ${u.text}`);
return [head, ...lines].join('\r\n');
})
.join('\r\n\r\n');
entries.unshift(
{ name: 'manifest.json', data: Buffer.from(JSON.stringify(manifest, null, 2)) },
{ name: 'data.json', data: Buffer.from(JSON.stringify(data)) },
{ name: '대화.txt', data: Buffer.from('' + transcript + '\r\n', 'utf8') },
{
name: '읽어 주세요.txt',
data: Buffer.from(
'겜녹이 기록 묶음입니다.\r\n사이트(gvr.tkrmagid.kr) → 기록 관리 → "받아오기"로 이 zip 을 그대로 넣으면 기록이 다시 추가됩니다.\r\nmanifest.json · data.json · audio 폴더를 지우거나 고치면 받아오기가 실패합니다.\r\n',
'utf8',
),
},
);
const first = groups.map((g) => g.info.from).sort((a, b) => a - b)[0] ?? Date.now();
const d = new Date(first);
const stamp = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}`;
const kind = groups.length > 1 ? `${groups.length}bundles` : groups[0].info.kind === 'match' ? (groups[0].info.game ?? 'match') : 'talk';
log.info(`기록 묶음 ${groups.length}개 내보내기 (발화 ${outUtts.length}개, 음성 ${manifest.counts.audio}개)`);
return { zip: writeZip(entries), fileName: `gvr-${kind}-${stamp}.zip` };
}
// ------------------------------------------------------------------ 받아오기
import(buf: Buffer): BundleImportResult {
let files: Map<string, Buffer>;
try {
files = readZip(buf);
} catch (e) {
throw new BundleError(`받아오기 실패: ${e instanceof ZipError ? e.message : 'zip 파일을 읽지 못했습니다'}`);
}
const { manifest, data } = validate(files, this.store);
const db = this.store.db;
const now = Date.now();
const res: BundleImportResult = { bundles: manifest.bundles.map((b: any) => String(b.label ?? b.id)), added: { utterances: 0, audio: 0, matches: 0, events: 0, users: 0 }, skipped: 0 };
const written: string[] = [];
try {
db.transaction(() => {
for (const u of data.users) {
if (this.store.getUser(u.id)) continue;
db.prepare('INSERT INTO users(id,name,color,avatar,excluded,updated_at) VALUES(?,?,?,?,?,?)').run(u.id, String(u.name ?? u.id), String(u.color ?? '#8696a6'), u.avatar ?? null, u.excluded ? 1 : 0, now);
res.added.users++;
}
for (const a of data.accounts ?? []) if (a?.user_id && a?.puuid && this.store.getUser(a.user_id)) db.prepare('INSERT OR IGNORE INTO game_accounts(user_id,puuid,riot_id) VALUES(?,?,?)').run(a.user_id, a.puuid, String(a.riot_id ?? ''));
for (const s of data.sessions ?? [])
if (s?.id) db.prepare('INSERT OR IGNORE INTO sessions(id,guild_id,channel_id,channel_name,started_at,ended_at) VALUES(?,?,?,?,?,?)').run(s.id, String(s.guild_id ?? ''), String(s.channel_id ?? ''), s.channel_name ?? null, Number(s.started_at) || 0, s.ended_at ?? null);
for (const m of data.matches ?? []) {
const r = db
.prepare('INSERT OR IGNORE INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset) VALUES(?,?,?,?,?,?,?,?,?,?,?)')
.run(m.id, m.game, m.started_at, m.ended_at ?? null, m.map ?? null, m.mode ?? null, m.queue ?? null, m.result ?? null, m.detail ?? null, m.status === 'live' ? 'complete' : (m.status ?? 'complete'), Number(m.clock_offset) || 0);
res.added.matches += r.changes;
}
for (const r of data.rounds ?? [])
db.prepare('INSERT OR IGNORE INTO rounds(match_id,num,started_at,combat_at,ended_at,win,result,ally_score,enemy_score,economy) VALUES(?,?,?,?,?,?,?,?,?,?)').run(
r.match_id, r.num, r.started_at, r.combat_at, r.ended_at, r.win ?? null, r.result ?? null, r.ally_score ?? null, r.enemy_score ?? null, r.economy ?? null,
);
for (const e of data.events ?? []) {
const r = db
.prepare('INSERT OR IGNORE INTO game_events(id,match_id,game,type,ts,game_time_ms,round,actor_puuid,target_puuid,data) VALUES(?,?,?,?,?,?,?,?,?,?)')
.run(e.id, e.match_id, e.game, e.type, e.ts, e.game_time_ms ?? null, e.round ?? null, e.actor_puuid ?? null, e.target_puuid ?? null, typeof e.data === 'string' ? e.data : JSON.stringify(e.data ?? {}));
res.added.events += r.changes;
}
const hasCulprit = !!db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='culprit_analyses'`).get();
if (hasCulprit)
for (const c of data.culprit ?? [])
if (c?.id && c?.match_id)
db.prepare('INSERT OR IGNORE INTO culprit_analyses(id,match_id,created_at,created_by,model,current,result,meta) VALUES(?,?,?,?,?,?,?,?)').run(
c.id, c.match_id, c.created_at, c.created_by, c.model, c.current ?? 1, c.result, c.meta ?? '{}',
);
for (const u of data.utterances) {
if (this.store.getUtterance(u.id)) {
res.skipped++;
continue;
}
let audioPath: string | null = null;
if (u.audio) {
const d = new Date(u.started_at);
const day = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
const dir = path.join(this.audioDir(), day);
fs.mkdirSync(dir, { recursive: true });
audioPath = path.join(dir, `${u.id}.ogg`);
if (!fs.existsSync(audioPath)) {
fs.writeFileSync(audioPath, files.get(u.audio)!);
written.push(audioPath);
}
res.added.audio++;
}
db.prepare(
`INSERT INTO utterances(id,session_id,user_id,started_at,ended_at,audio_path,audio_deleted,text,raw_text,words,noise,noise_reason,confidence,lufs,gain_db,model,status,match_id,corrected,attempts,created_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
).run(
u.id, u.session_id ?? null, u.user_id, u.started_at, u.ended_at, audioPath, audioPath ? 0 : 1, u.text ?? null, u.raw_text ?? null,
typeof u.words === 'string' ? u.words : JSON.stringify(u.words ?? []), u.noise ? 1 : 0, u.noise_reason ?? null, u.confidence ?? null, u.lufs ?? null,
Number(u.gain_db) || 0, u.model ?? null, u.status === 'pending' && !audioPath ? 'failed' : (u.status ?? 'precise'), u.match_id ?? null, u.corrected ? 1 : 0, 0, now,
);
db.prepare('INSERT OR REPLACE INTO utterance_imports(id, imported_at) VALUES(?,?)').run(u.id, now);
res.added.utterances++;
}
})();
} catch (e) {
// DB 에 못 넣었으면 쓴 음성 파일도 지운다
for (const f of written) fs.rmSync(f, { force: true });
throw e instanceof BundleError ? e : new BundleError(`받아오기 실패: 기록을 저장하지 못했습니다 (${(e as Error).message})`, 'import_failed');
}
log.info(`기록 묶음 받아오기: ${res.bundles.join(', ')} (발화 ${res.added.utterances}개 추가, 음성 ${res.added.audio}개, 이미 있음 ${res.skipped}개)`);
return res;
}
}
const num = (v: unknown) => typeof v === 'number' && isFinite(v);
/** 받아오기 검사: 꼭 필요한 내용이 하나라도 없으면 BundleError (무엇이 빠졌는지 알려 준다) */
export function validate(files: Map<string, Buffer>, store?: Store): { manifest: any; data: any } {
const fail = (why: string): never => {
throw new BundleError(`받아오기 실패: ${why}`);
};
const json = (name: string): any => {
const b = files.get(name);
if (!b) fail(`${name} 이 없습니다 (겜녹이에서 내보낸 기록 zip 이 아닙니다)`);
try {
return JSON.parse(b!.toString('utf8').replace(/^/, ''));
} catch {
return fail(`${name} 을 읽을 수 없습니다 (내용이 깨졌습니다)`);
}
};
const manifest = json('manifest.json');
if (manifest?.format !== BUNDLE_FORMAT) fail('겜녹이 기록 묶음 형식이 아닙니다 (manifest.json 의 format)');
if (!num(manifest.version) || manifest.version > BUNDLE_VERSION) fail(`이 앱이 모르는 묶음 형식 버전입니다 (${manifest.version}). 앱을 업데이트해 주세요`);
if (!Array.isArray(manifest.bundles) || !manifest.bundles.length) fail('묶음 정보(manifest.json 의 bundles)가 없습니다');
const data = json('data.json');
if (!Array.isArray(data?.utterances)) fail('발화 목록(data.json 의 utterances)이 없습니다');
if (!Array.isArray(data.users)) fail('유저 목록(data.json 의 users)이 없습니다');
for (const k of ['matches', 'rounds', 'events', 'sessions', 'accounts', 'culprit']) if (data[k] !== undefined && !Array.isArray(data[k])) fail(`data.json 의 ${k} 가 목록이 아닙니다`);
const userIds = new Set<string>();
for (const u of data.users) {
if (typeof u?.id !== 'string' || !u.id) fail('이름 없는 유저가 있습니다 (data.json 의 users)');
userIds.add(u.id);
}
const matchIds = new Set<string>();
for (const m of data.matches ?? []) {
if (typeof m?.id !== 'string' || !SAFE_ID.test(m.id)) fail('경기 ID 가 잘못되었습니다');
if (m.game !== 'valorant' && m.game !== 'lol') fail(`경기 ${m.id} 의 게임 종류가 없습니다`);
if (!num(m.started_at)) fail(`경기 ${m.id} 의 시작 시각이 없습니다`);
matchIds.add(m.id);
}
for (const b of manifest.bundles) {
if (b?.kind !== 'match' && b?.kind !== 'talk') fail('묶음 종류(match/talk)가 잘못되었습니다');
if (b.kind === 'match' && !matchIds.has(b.matchId)) fail(`경기 묶음 "${b.label ?? b.id}" 의 경기 기록이 data.json 에 없습니다`);
}
for (const e of data.events ?? []) {
if (typeof e?.id !== 'string' || typeof e?.type !== 'string' || !num(e?.ts)) fail('경기 이벤트에 꼭 필요한 값(id · type · ts)이 없습니다');
if (!matchIds.has(e.match_id)) fail(`이벤트 ${e.id} 의 경기(${e.match_id})가 data.json 에 없습니다`);
}
for (const r of data.rounds ?? []) if (!matchIds.has(r?.match_id) || !num(r?.num) || !num(r?.started_at) || !num(r?.combat_at) || !num(r?.ended_at)) fail('라운드 기록에 꼭 필요한 값이 없습니다');
const seen = new Set<string>();
for (const u of data.utterances) {
if (typeof u?.id !== 'string' || !SAFE_ID.test(u.id)) fail('발화 ID 가 잘못되었습니다');
if (seen.has(u.id)) fail(`발화 ${u.id} 가 두 번 들어 있습니다`);
seen.add(u.id);
if (typeof u.user_id !== 'string' || !u.user_id) fail(`발화 ${u.id} 에 말한 사람이 없습니다`);
if (!userIds.has(u.user_id) && !store?.getUser(u.user_id)) fail(`발화 ${u.id} 의 말한 사람(${u.user_id})이 유저 목록에 없습니다`);
if (!num(u.started_at) || !num(u.ended_at) || u.ended_at < u.started_at) fail(`발화 ${u.id} 의 시각이 잘못되었습니다`);
if (u.match_id && !matchIds.has(u.match_id) && !store?.getMatch(u.match_id)) fail(`발화 ${u.id} 의 경기(${u.match_id})가 없습니다`);
if (u.audio) {
if (u.audio !== `audio/${u.id}.ogg`) fail(`발화 ${u.id} 의 음성 파일 이름이 잘못되었습니다`);
const a = files.get(u.audio);
if (!a) fail(`음성 파일 ${u.audio} 가 zip 안에 없습니다`);
if (a!.length < 4 || a!.toString('ascii', 0, 4) !== 'OggS') fail(`음성 파일 ${u.audio} 가 ogg 가 아닙니다`);
}
}
if (!data.utterances.length && !matchIds.size) fail('넣을 발화 · 경기가 하나도 없습니다');
const c = manifest.counts;
if (c && num(c.utterances) && c.utterances !== data.utterances.length) fail(`발화 수가 맞지 않습니다 (manifest ${c.utterances}개, data ${data.utterances.length}개). zip 이 잘렸거나 고쳐졌습니다`);
return { manifest, data };
}

View File

@@ -319,8 +319,11 @@ export class Store {
/** 보관 기간 지난 음성 파일 목록 */
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[];
.prepare(
`SELECT id, audio_path FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND started_at<?
AND NOT EXISTS (SELECT 1 FROM utterance_imports i WHERE i.id=utterances.id AND i.imported_at>=?)`,
)
.all(before, before) as any[];
}
/** 잡음으로 끝난 발화 중 아직 음성 파일이 남은 것 (v1.3.5 이하에서 녹음한 것) */
noiseWithAudio(): UtteranceRow[] {

View File

@@ -136,3 +136,9 @@ CREATE TABLE IF NOT EXISTS training_samples (
used INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
-- 받아오기(zip)로 넣은 발화: 보관 기간은 녹음 날짜가 아니라 받아온 날부터 센다
CREATE TABLE IF NOT EXISTS utterance_imports (
id TEXT PRIMARY KEY,
imported_at INTEGER NOT NULL
);

View File

@@ -1,2 +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, pack)\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";
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, pack)\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\n-- 받아오기(zip)로 넣은 발화: 보관 기간은 녹음 날짜가 아니라 받아온 날부터 센다\nCREATE TABLE IF NOT EXISTS utterance_imports (\n id TEXT PRIMARY KEY,\n imported_at INTEGER NOT NULL\n);\n";

View File

@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import type { FastifyInstance } from 'fastify';
import { buildApi, toUser } from './api/server.js';
import { Bundles } from './bundles.js';
import { Culprit } from './culprit.js';
import { Store } from './db/db.js';
import { Dictionary } from './dict/dictionary.js';
@@ -97,6 +98,7 @@ export async function startCore(opts: CoreOptions) {
settings: S,
trainingDir: () => paths().training,
version: opts.version,
bundles: new Bundles(store, games, () => paths().audio, opts.version),
overviewExtra: () => ({
guild: bot.state.guild,
recording: {

View File

@@ -6,6 +6,9 @@ import { logger } from '../util/log.js';
import { secureFetch, TLS_TRUST } from '../util/secure-http.js';
import { secureServerUrl, wsUrl } from '../util/secure-url.js';
/** 바이너리 한 조각 (서버 · 앱 모두 메시지 크기 제한보다 작게) */
const RELAY_CHUNK = 1024 * 1024;
const log = logger('relay');
export interface RelayStatus {
@@ -89,7 +92,7 @@ export class RelayClient {
}, 5000);
});
ws.on('message', (data, isBinary) => {
if (isBinary) return;
if (isBinary) return this.onBinary(data as Buffer);
let msg: RelayToDevice;
try {
msg = JSON.parse(String(data));
@@ -124,7 +127,22 @@ export class RelayClient {
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(m));
}
/** 사이트 서버가 보낸 요청 본문 조각 (zip 받아오기): [id 길이 4바이트][id][조각] */
private bodyChunks = new Map<string, { chunks: Buffer[]; at: number }>();
private onBinary(buf: Buffer): void {
if (buf.length < 4) return;
const n = buf.readUInt32BE(0);
const id = buf.subarray(4, 4 + n).toString('utf8');
const cur = this.bodyChunks.get(id) ?? { chunks: [], at: Date.now() };
cur.chunks.push(Buffer.from(buf.subarray(4 + n)));
this.bodyChunks.set(id, cur);
// 끝내 요청이 오지 않은 조각은 10분 뒤 버린다
for (const [k, v] of this.bodyChunks) if (Date.now() - v.at > 10 * 60000) this.bodyChunks.delete(k);
}
private async handle(req: Extract<RelayToDevice, { t: 'req' }>): Promise<void> {
const bin = req.bin ? Buffer.concat(this.bodyChunks.get(req.id)?.chunks ?? []) : null;
this.bodyChunks.delete(req.id);
if (!req.path.startsWith('/api/')) {
this.send({ t: 'res', id: req.id, status: 403, headers: { 'content-type': 'application/json' }, body: '{"error":"forbidden"}' });
return;
@@ -133,19 +151,21 @@ export class RelayClient {
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept', 'x-gvr-internal']) 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 res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: bin ?? req.body ?? undefined });
const outHeaders: Record<string, string> = {};
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length']) {
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length', 'content-disposition']) {
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')) {
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream') || ct.startsWith('application/zip')) {
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 });
// 사이트 서버는 한 메시지에 16MB 까지만 받는다. 1MB 씩 나눠 보낸다 (zip 내보내기)
const raw = res.rawPayload;
for (let i = 0; i < raw.length || i === 0; i += RELAY_CHUNK) this.ws?.send(Buffer.concat([head, idBuf, raw.subarray(i, i + RELAY_CHUNK)]), { 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 });

135
app/src/core/util/zip.ts Normal file
View File

@@ -0,0 +1,135 @@
import zlib from 'node:zlib';
// 작은 ZIP 읽기 · 쓰기 (기록 묶음 내보내기 · 받아오기). 의존성 없이 쓰려고 직접 만든다.
// - 쓰기: 압축 안 함(store). ogg 는 이미 압축되어 있어 deflate 해도 거의 줄지 않는다
// - 읽기: store · deflate 둘 다 (다른 프로그램으로 다시 압축한 zip 도 받는다). ZIP64 · 암호는 안 받음
const CRC_TABLE = (() => {
const t = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
t[n] = c >>> 0;
}
return t;
})();
export function crc32(buf: Buffer): number {
let c = 0xffffffff;
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function dosTime(d: Date): { time: number; date: number } {
return {
time: (d.getHours() << 11) | (d.getMinutes() << 5) | Math.floor(d.getSeconds() / 2),
date: ((Math.max(1980, d.getFullYear()) - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate(),
};
}
export interface ZipEntry {
name: string;
data: Buffer;
}
/** 파일 목록 → zip (store) */
export function writeZip(entries: ZipEntry[], when = new Date()): Buffer {
const { time, date } = dosTime(when);
const parts: Buffer[] = [];
const central: Buffer[] = [];
let offset = 0;
for (const e of entries) {
const name = Buffer.from(e.name, 'utf8');
const crc = crc32(e.data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x0800, 6); // UTF-8 이름
local.writeUInt16LE(0, 8); // store
local.writeUInt16LE(time, 10);
local.writeUInt16LE(date, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(e.data.length, 18);
local.writeUInt32LE(e.data.length, 22);
local.writeUInt16LE(name.length, 26);
local.writeUInt16LE(0, 28);
parts.push(local, name, e.data);
const cen = Buffer.alloc(46);
cen.writeUInt32LE(0x02014b50, 0);
cen.writeUInt16LE(20, 4);
cen.writeUInt16LE(20, 6);
cen.writeUInt16LE(0x0800, 8);
cen.writeUInt16LE(0, 10);
cen.writeUInt16LE(time, 12);
cen.writeUInt16LE(date, 14);
cen.writeUInt32LE(crc, 16);
cen.writeUInt32LE(e.data.length, 20);
cen.writeUInt32LE(e.data.length, 24);
cen.writeUInt16LE(name.length, 28);
cen.writeUInt32LE(offset, 42);
central.push(cen, name);
offset += 30 + name.length + e.data.length;
}
const cenBuf = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(entries.length, 8);
end.writeUInt16LE(entries.length, 10);
end.writeUInt32LE(cenBuf.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...parts, cenBuf, end]);
}
export class ZipError extends Error {}
/** zip → 파일 이름별 내용. 폴더 항목은 뺀다. 깨진 파일이면 ZipError */
export function readZip(buf: Buffer, maxTotal = 2 * 1024 * 1024 * 1024): Map<string, Buffer> {
// 끝 레코드 찾기 (주석이 있을 수 있어 뒤에서부터)
let eocd = -1;
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) {
if (buf.readUInt32LE(i) === 0x06054b50) {
eocd = i;
break;
}
}
if (eocd < 0) throw new ZipError('zip 파일이 아닙니다');
const count = buf.readUInt16LE(eocd + 10);
let p = buf.readUInt32LE(eocd + 16);
const out = new Map<string, Buffer>();
let total = 0;
for (let i = 0; i < count; i++) {
if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) throw new ZipError('zip 목록이 깨졌습니다');
const flags = buf.readUInt16LE(p + 8);
const method = buf.readUInt16LE(p + 10);
const crc = buf.readUInt32LE(p + 16);
const csize = buf.readUInt32LE(p + 20);
const size = buf.readUInt32LE(p + 24);
const nlen = buf.readUInt16LE(p + 28);
const xlen = buf.readUInt16LE(p + 30);
const clen = buf.readUInt16LE(p + 32);
const loc = buf.readUInt32LE(p + 42);
const name = buf.toString(flags & 0x0800 ? 'utf8' : 'latin1', p + 46, p + 46 + nlen).replace(/\\/g, '/');
p += 46 + nlen + xlen + clen;
if (name.endsWith('/')) continue;
if (flags & 1) throw new ZipError(`암호가 걸린 파일은 받을 수 없습니다: ${name}`);
if (csize === 0xffffffff || size === 0xffffffff) throw new ZipError('너무 큰 zip(ZIP64)은 받을 수 없습니다');
if (loc + 30 > buf.length || buf.readUInt32LE(loc) !== 0x04034b50) throw new ZipError(`zip 안 파일이 깨졌습니다: ${name}`);
const start = loc + 30 + buf.readUInt16LE(loc + 26) + buf.readUInt16LE(loc + 28);
const raw = buf.subarray(start, start + csize);
if (raw.length !== csize) throw new ZipError(`zip 안 파일이 잘렸습니다: ${name}`);
total += size;
if (total > maxTotal) throw new ZipError('zip 내용이 너무 큽니다');
let data: Buffer;
if (method === 0) data = Buffer.from(raw);
else if (method === 8) {
try {
data = zlib.inflateRawSync(raw, { maxOutputLength: size + 1024 });
} catch {
throw new ZipError(`zip 안 파일을 풀지 못했습니다: ${name}`);
}
} else throw new ZipError(`지원하지 않는 압축 방식(${method})입니다: ${name}`);
if (data.length !== size || crc32(data) !== crc) throw new ZipError(`zip 안 파일이 손상되었습니다: ${name}`);
out.set(name, data);
}
return out;
}

186
app/test/bundles.test.ts Normal file
View File

@@ -0,0 +1,186 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { Store } from '../src/core/db/db.ts';
import { Bundles, BundleError } from '../src/core/bundles.ts';
import { readZip, writeZip } from '../src/core/util/zip.ts';
import { Retention } from '../src/core/retention.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-bundle-'));
const MIN = 60000;
// 20일 전 새벽 3시 (보관 기간 7일보다 오래된 녹음)
const T0 = (() => {
const d = new Date(Date.now() - 20 * 86400000);
d.setHours(3, 0, 0, 0);
return d.getTime();
})();
const OGG = (n: number) => Buffer.concat([Buffer.from('OggS'), Buffer.alloc(200, n)]);
const games: any = {
summary: (m: any) => ({ mode: '경쟁전', map: { name: '어센트' }, score: { ally: 13, enemy: 9 }, win: true, startedAt: m.started_at }),
};
function seed(dir: string) {
const store = new Store(path.join(dir, 'db.sqlite'));
const audio = path.join(dir, 'audio');
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
store.db.prepare('INSERT INTO sessions(id,guild_id,channel_id,channel_name,started_at,ended_at) VALUES(?,?,?,?,?,?)').run('s1', 'g', 'c', '음성', T0, T0 + 60 * MIN);
const utt = (id: string, user: string, at: number, opts: { match?: string; noise?: boolean; session?: string | null } = {}) => {
const f = path.join(audio, 'day', `${id}.ogg`);
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(f, OGG(at % 250));
store.insertUtterance({ id, session_id: opts.session === undefined ? 's1' : opts.session, user_id: user, started_at: at, ended_at: at + 1500, audio_path: f, match_id: opts.match ?? null });
store.updateUtteranceResult(id, { text: opts.noise ? null : `말 ${id}`, raw_text: null, words: [], noise: !!opts.noise, noise_reason: opts.noise ? 'vad' : null, confidence: 0.9, lufs: -20, gain_db: 2, model: 'm', status: 'precise' });
};
// 경기 전 대화 (경기 10분 전부터) → 경기 (10~40분) → 경기 후 대화 (42분) → 다른 날 게임 밖 대화
utt('pre1', 'u1', T0);
utt('pre2', 'u2', T0 + 2 * MIN);
utt('preNoise', 'u1', T0 + 3 * MIN, { noise: true });
store.upsertMatch({ id: 'val-1', game: 'valorant', started_at: T0 + 10 * MIN, ended_at: T0 + 40 * MIN, map: 'Ascent', mode: '경쟁전', queue: 'competitive', status: 'complete' });
store.insertEvent({ id: 'val-1:kill:1', match_id: 'val-1', game: 'valorant', type: 'kill', ts: T0 + 12 * MIN, game_time_ms: 120000, round: 1, actor_puuid: null, target_puuid: null, data: '{}' });
store.replaceRounds('val-1', [{ match_id: 'val-1', num: 1, started_at: T0 + 10 * MIN, combat_at: T0 + 10.5 * MIN, ended_at: T0 + 12 * MIN, win: 1, result: 'Elim', ally_score: 1, enemy_score: 0, economy: '{}' }]);
utt('in1', 'u1', T0 + 15 * MIN, { match: 'val-1' });
utt('in2', 'u2', T0 + 16 * MIN, { match: 'val-1' });
utt('post1', 'u2', T0 + 42 * MIN);
utt('other1', 'u1', T0 + 24 * 60 * MIN, { session: null });
return { store, audio, b: new Bundles(store, games, () => audio, 'test') };
}
test('기록 묶음: 경기 · 경기 전 대화 · 경기 후 대화 · 게임 밖 대화로 나눈다', () => {
const { store, b } = seed(tmp());
const list = b.list();
assert.deepEqual(
list.map((x) => [x.kind, x.label, x.utterances]),
[
['talk', '게임 밖 대화', 1],
['talk', '경기 후 대화', 1],
['match', '발로란트 · 경쟁전 · 어센트', 2],
['talk', '경기 전 대화', 2],
],
);
const pre = list.find((x) => x.label === '경기 전 대화')!;
assert.equal(pre.sub, '다음 경기: 발로란트 어센트');
assert.equal(pre.audio, 2, '잡음은 세지 않는다');
const m = list.find((x) => x.kind === 'match')!;
assert.equal(m.events, 1);
assert.deepEqual(m.users.sort(), ['u1', 'u2']);
store.close();
});
test('기록 묶음: zip 내보내기 → 지우기 → 받아오기로 그대로 되돌린다', () => {
const dir = tmp();
const { store, audio, b } = seed(dir);
const ids = b.list().filter((x) => x.label !== '게임 밖 대화').map((x) => x.id);
const { zip, fileName } = b.export(ids);
assert.match(fileName, /^gvr-3bundles-\d{8}-0300\.zip$/);
const zf = path.join(dir, fileName);
fs.writeFileSync(zf, zip);
execFileSync('unzip', ['-tq', zf]); // 다른 프로그램으로도 열린다
const files = readZip(zip);
assert.ok(files.has('manifest.json') && files.has('data.json') && files.has('대화.txt') && files.has('audio/in1.ogg'));
assert.match(files.get('대화.txt')!.toString('utf8'), /하늘: 말 in1/);
// 지우기: 발화 · 파일 · 경기 · 이벤트 · 라운드
const r = b.delete(ids);
assert.equal(r.bundles, 3);
assert.equal(r.utterances, 6, '잡음 발화도 함께 지운다');
assert.equal(store.getUtterance('in1'), undefined);
assert.equal(store.getMatch('val-1'), undefined);
assert.equal(store.events('val-1').length, 0);
assert.equal(store.rounds('val-1').length, 0);
assert.ok(!fs.existsSync(path.join(audio, 'day', 'in1.ogg')));
assert.equal(b.list().length, 1);
// 받아오기
const imp = b.import(zip);
assert.equal(imp.added.utterances, 6);
assert.equal(imp.added.matches, 1);
assert.equal(imp.added.events, 1);
assert.equal(imp.skipped, 0);
assert.equal(b.list().length, 4);
assert.equal(store.getUtterance('in1')!.text, '말 in1');
assert.ok(fs.existsSync(store.getUtterance('in1')!.audio_path!));
assert.equal(store.rounds('val-1').length, 1);
// 같은 zip 을 또 받으면 건너뛴다
assert.equal(b.import(zip).skipped, 6);
// 받아온 녹음은 보관 기간을 받아온 날부터 센다 (녹음 날짜가 오래돼도 바로 지우지 않음)
const ret = new Retention(store, () => 7, () => audio).run(Date.now());
assert.equal(ret.deleted, 1, '받아오지 않은 다른 날 발화만 지운다');
assert.equal(store.getUtterance('in1')!.audio_deleted, 0);
store.close();
});
test('기록 묶음: 다른 프로그램으로 다시 압축한(deflate) zip 도 받는다', () => {
const dir = tmp();
const { store, b } = seed(dir);
const id = b.list().find((x) => x.kind === 'match')!.id;
const { zip } = b.export([id]);
const x = path.join(dir, 'x');
fs.mkdirSync(x);
fs.writeFileSync(path.join(dir, 'a.zip'), zip);
execFileSync('unzip', ['-q', path.join(dir, 'a.zip'), '-d', x]);
execFileSync('zip', ['-q', '-r', '-9', path.join(dir, 'b.zip'), '.'], { cwd: x });
b.delete([id]);
const r = b.import(fs.readFileSync(path.join(dir, 'b.zip')));
assert.equal(r.added.utterances, 2);
store.close();
});
test('기록 묶음 받아오기: 꼭 필요한 내용이 없으면 실패', () => {
const { store, b } = seed(tmp());
const { zip } = b.export([b.list().find((x) => x.kind === 'match')!.id]);
const files = readZip(zip);
const make = (patch: (m: Map<string, Buffer>) => void) => {
const m = new Map(files);
patch(m);
return writeZip([...m].map(([name, data]) => ({ name, data })));
};
const data = () => JSON.parse(files.get('data.json')!.toString());
const cases: [string, Buffer, RegExp][] = [
['zip 아님', Buffer.from('hello'), /zip 파일이 아닙니다/],
['manifest 없음', make((m) => m.delete('manifest.json')), /manifest\.json 이 없습니다/],
['data 없음', make((m) => m.delete('data.json')), /data\.json 이 없습니다/],
['음성 없음', make((m) => m.delete('audio/in1.ogg')), /audio\/in1\.ogg 가 zip 안에 없습니다/],
['ogg 아님', make((m) => m.set('audio/in1.ogg', Buffer.from('not ogg'))), /ogg 가 아닙니다/],
['다른 형식', make((m) => m.set('manifest.json', Buffer.from(JSON.stringify({ format: 'other' })))), /형식이 아닙니다/],
[
'말한 사람 없음',
make((m) => {
const d = data();
d.users = [];
d.utterances[0].user_id = 'nobody';
m.set('data.json', Buffer.from(JSON.stringify(d)));
}),
/말한 사람\(nobody\)이 유저 목록에 없습니다/,
],
[
'경기 기록 없음',
make((m) => {
const d = data();
d.matches = [];
m.set('data.json', Buffer.from(JSON.stringify(d)));
}),
/경기 기록이 data\.json 에 없습니다/,
],
[
'발화 수 다름',
make((m) => {
const d = data();
d.utterances.pop();
m.set('data.json', Buffer.from(JSON.stringify(d)));
}),
/발화 수가 맞지 않습니다/,
],
];
const before = store.db.prepare('SELECT count(*) n FROM utterances').get() as { n: number };
for (const [name, buf, re] of cases) {
assert.throws(
() => b.import(buf),
(e: any) => e instanceof BundleError && re.test(e.message) && e.message.startsWith('받아오기 실패'),
name,
);
}
assert.deepEqual(store.db.prepare('SELECT count(*) n FROM utterances').get(), before, '실패하면 아무것도 넣지 않는다');
store.close();
});

View File

@@ -89,6 +89,23 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
assert.ok(fs.existsSync(core.store.trainingSamples()[0].audio_path));
const search = (await core.api.inject({ method: 'GET', url: '/api/timeline?q=' + encodeURIComponent('궁 빠졌어') })).json();
assert.deepEqual(search.items.map((i: any) => i.id), ['speech']);
// 기록 묶음 API: 목록 → zip → 지우기 → 받아오기
const bl = (await core.api.inject({ method: 'GET', url: '/api/bundles' })).json().bundles;
assert.equal(bl.length, 1);
assert.equal(bl[0].label, '게임 밖 대화');
const ex = await core.api.inject({ method: 'GET', url: `/api/bundles/export?ids=${bl[0].id}` });
assert.equal(ex.headers['content-type'], 'application/zip');
assert.match(String(ex.headers['content-disposition']), /attachment; filename="gvr-talk-\d{8}-\d{4}\.zip"/);
const del = (await core.api.inject({ method: 'POST', url: '/api/bundles/delete', payload: { ids: [bl[0].id] } })).json();
assert.equal(del.utterances, 3);
assert.equal((await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.length, 0);
const bad = await core.api.inject({ method: 'POST', url: '/api/bundles/import', headers: { 'content-type': 'application/zip' }, payload: Buffer.from('PK nope') });
assert.equal(bad.statusCode, 400);
assert.match(bad.json().message, /^받아오기 실패/);
const imp = (await core.api.inject({ method: 'POST', url: '/api/bundles/import', headers: { 'content-type': 'application/zip' }, payload: ex.rawPayload })).json();
assert.equal(imp.added.utterances, 3);
assert.equal((await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.length, 2);
assert.ok(live.some((e) => e.type === 'records.changed'));
} finally {
await core.stop();
}

View File

@@ -278,6 +278,37 @@ export interface LiveGame {
updatedAt: number;
}
/** 기록 묶음 (사이트 기록 관리, v1.3.7~): 경기 하나 또는 경기 밖 대화 한 덩어리 */
export interface BundleInfo {
/** match-<경기ID> 또는 talk-<첫 발화ID> */
id: string;
kind: 'match' | 'talk';
/** "발로란트 · 경쟁전 · 어센트" · "경기 전 대화" · "경기 후 대화" · "게임 밖 대화" */
label: string;
/** 경기: "승리 13:9", 대화: "다음 경기: 발로란트 어센트" */
sub: string | null;
game: GameType | null;
matchId: string | null;
from: number;
to: number;
/** 보이는 발화 수 (잡음 뺌) */
utterances: number;
/** 음성 파일이 남은 발화 수 */
audio: number;
audioBytes: number;
/** 경기 이벤트 수 (킬 · 라운드 …) */
events: number;
talkMs: number;
users: string[];
}
export interface BundleImportResult {
bundles: string[];
added: { utterances: number; audio: number; matches: number; events: number; users: number };
/** 이미 있어서 건너뛴 발화 */
skipped: number;
}
export interface Overview {
guild: { id: string; name: string; icon: string | null } | null;
recording: { active: boolean; channel: string | null; since: number | null; participants: string[] };
@@ -393,7 +424,8 @@ export type LiveEvent =
| { type: 'match.updated'; data: MatchSummary }
| { type: 'recording.state'; data: Overview['recording'] }
| { type: 'users.updated'; data: User[] }
| { type: 'games.state'; data: LiveGame[] };
| { type: 'games.state'; data: LiveGame[] }
| { type: 'records.changed'; data: { reason: 'deleted' | 'imported'; ids?: string[] } };
export interface DeviceStatus {
registered: boolean;
@@ -415,6 +447,8 @@ export type RelayToDevice =
headers: Record<string, string>;
user: { id: string; name: string; avatar: string | null } | null;
body: string | null;
/** 본문이 바이너리(zip 등)면 true. 본문은 이 메시지 앞에 같은 id 의 바이너리 조각으로 먼저 온다 (v1.3.7~) */
bin?: boolean;
}
| { t: 'cancel'; id: string }
| { t: 'pong'; ts: number }

View File

@@ -243,11 +243,16 @@ export async function buildServer(
const origin = String(req.headers.origin || '');
if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' });
}
// 기록 묶음 지우기 · 받아오기는 관리자만 (보기 · zip 내려받기는 서버 멤버 누구나)
const p = req.url.split('?')[0];
const bundles = p.startsWith('/api/bundles');
if (bundles && req.method !== 'GET' && !canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '기록 지우기 · 받아오기는 관리자만 할 수 있습니다' });
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = String(req.headers[k]);
const body = req.body === undefined || req.body === null ? null : typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
const body = req.body === undefined || req.body === null ? null : Buffer.isBuffer(req.body) || typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
try {
const r = await hub.request(req.method, req.url, headers, s.user, body);
// zip 만들기 · 받아오기는 오래 걸릴 수 있다
const r = await hub.request(req.method, req.url, headers, s.user, body, bundles ? 180000 : 20000);
for (const [k, v] of Object.entries(r.headers)) if (k !== 'content-length') reply.header(k, v);
return reply.code(r.status).send(r.body);
} catch (e: any) {
@@ -255,6 +260,8 @@ export async function buildServer(
return reply.code(504).send({ error: 'timeout' });
}
};
// zip 받아오기 본문 (300MB 까지)
app.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body));
app.route({ method: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'], url: '/api/*', handler: relay });
// ------------------------------------------------------------------ 게임 이미지 캐시 (보고서 7-7)

View File

@@ -188,7 +188,7 @@ export class RelayHub {
}
/** 브라우저 요청 하나를 게임 PC 로 넘긴다 */
request(method: string, path: string, headers: Record<string, string>, user: { id: string; name: string; avatar: string | null }, body: string | null, timeoutMs = 20000): Promise<RelayResponse> {
request(method: string, path: string, headers: Record<string, string>, user: { id: string; name: string; avatar: string | null }, body: string | Buffer | null, timeoutMs = 20000): Promise<RelayResponse> {
const dev = this.device;
if (!dev || !this.status().online) return Promise.reject(new Error('device_offline'));
const id = crypto.randomBytes(8).toString('hex');
@@ -200,6 +200,17 @@ export class RelayHub {
}
}, timeoutMs);
this.pending.set(id, { resolve, reject, timer, chunks: [] });
if (Buffer.isBuffer(body)) {
// 바이너리 본문(zip 받아오기): 1MB 조각으로 먼저 보내고 요청을 보낸다 (앱은 한 메시지 8MB 까지)
const idBuf = Buffer.from(id, 'utf8');
const head = Buffer.alloc(4);
head.writeUInt32BE(idBuf.length, 0);
const CH = 1024 * 1024;
for (let i = 0; i < body.length; i += CH) dev.ws.send(Buffer.concat([head, idBuf, body.subarray(i, i + CH)]), { binary: true });
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body: null, bin: true };
dev.ws.send(JSON.stringify(msg));
return;
}
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body };
dev.ws.send(JSON.stringify(msg));
});

View File

@@ -99,6 +99,12 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
local.get('/api/timeline', async (req) => ({ items: [], next: null, user: req.headers['x-gvr-user'] }));
local.get('/api/audio/:id', async (_req, reply) => reply.header('content-type', 'audio/ogg').send(Buffer.from('OggS' + 'x'.repeat(5000))));
local.patch('/api/utterances/:id', async (req) => ({ ok: true, body: req.body }));
// 큰 zip (20MB: 한 메시지 한도 16MB 넘음) 내보내기 · 받아오기
const big = Buffer.alloc(20 * 1024 * 1024);
for (let i = 0; i < big.length; i += 4096) big[i] = (i / 4096) & 0xff;
local.get('/api/bundles/export', async (_req, reply) => reply.header('content-type', 'application/zip').header('content-disposition', 'attachment; filename="gvr-test.zip"').send(big));
local.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body));
local.post('/api/bundles/import', async (req) => ({ size: (req.body as Buffer).length, same: (req.body as Buffer).equals(big) }));
const bus = new Bus();
const rc = new RelayClient(local as any, bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: '1.0.0', guildId: '222' }));
rc.start();
@@ -121,6 +127,16 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
const au = await fetch(base + '/api/audio/abc', { headers: { cookie: sid } });
assert.equal(au.headers.get('content-type'), 'audio/ogg');
assert.equal((await au.arrayBuffer()).byteLength, 5004);
// 큰 zip 내보내기: 조각으로 나눠 와서 그대로 붙는다 (content-disposition 도 전달)
const ex = await fetch(base + '/api/bundles/export?ids=match-1', { headers: { cookie: sid } });
assert.equal(ex.headers.get('content-disposition'), 'attachment; filename="gvr-test.zip"');
assert.ok(Buffer.from(await ex.arrayBuffer()).equals(big));
// 받아오기는 관리자만
assert.equal((await fetch(base + '/api/bundles/import', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/zip', origin: cfg.publicUrl }, body: big })).status, 403);
store.upsertAppUser({ id: 'member1', name: '하늘', avatar: null, role: 'admin', addedBy: 'test' });
const im = (await (await fetch(base + '/api/bundles/import', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/zip', origin: cfg.publicUrl }, body: big })).json()) as any;
assert.deepEqual(im, { size: big.length, same: true });
store.setAppUserRole('member1', 'user');
// 쓰기 요청: 다른 사이트 Origin 은 거절
assert.equal((await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: 'https://evil.example' }, body: '{"text":"x"}' })).status, 403);
const pr = (await (await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: cfg.publicUrl }, body: '{"text":"고침"}' })).json()) as any;

View File

@@ -264,6 +264,32 @@ async function handle(req, res) {
broadcast({ type: 'utterance.updated', data: it });
return json(res, 200, it);
}
if (p === '/api/bundles') {
const out = [];
for (const mt of db.matches) {
const us = db.utterances.filter((u) => u.game?.matchId === mt.id);
out.push({ id: `match-${mt.id}`, kind: 'match', label: `${mt.game === 'valorant' ? '발로란트' : '롤'} · ${mt.mode} · ${mt.map.name}`, sub: mt.score ? `${mt.win ? '승리' : '패배'} ${mt.score.ally}:${mt.score.enemy}` : null, game: mt.game, matchId: mt.id, from: mt.startedAt, to: mt.endedAt ?? mt.startedAt, utterances: us.length, audio: us.filter((u) => u.audio).length, audioBytes: us.length * 41230, events: mt.events.length, talkMs: us.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(us.map((u) => u.userId))] });
}
const talk = db.utterances.filter((u) => !u.game && !u.noise).sort((a, b) => a.ts - b.ts);
const runs = [];
for (const u of talk) {
const cur = runs[runs.length - 1];
if (!cur || u.ts - cur[cur.length - 1].endTs > 30 * 60000 || db.matches.some((mt) => mt.startedAt > cur[cur.length - 1].ts && mt.startedAt <= u.ts)) runs.push([u]);
else cur.push(u);
}
for (const r of runs) {
const from = r[0].ts, to = r[r.length - 1].endTs;
const next = db.matches.find((mt) => mt.startedAt >= to && mt.startedAt - to < 30 * 60000);
const prev = db.matches.find((mt) => (mt.endedAt ?? 0) <= from && from - (mt.endedAt ?? 0) < 30 * 60000);
out.push({ id: `talk-${r[0].id}`, kind: 'talk', label: next ? '경기 전 대화' : prev ? '경기 후 대화' : '게임 밖 대화', sub: next ? `다음 경기: ${next.map.name}` : prev ? `지난 경기: ${prev.map.name}` : null, game: null, matchId: null, from, to, utterances: r.length, audio: r.filter((u) => u.audio).length, audioBytes: r.length * 41230, events: 0, talkMs: r.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(r.map((u) => u.userId))] });
}
return json(res, 200, { bundles: out.sort((a, b) => b.from - a.from) });
}
if (p === '/api/bundles/delete' && req.method === 'POST') return json(res, 200, { bundles: 1, utterances: 12, files: 12 });
if (p === '/api/bundles/import' && req.method === 'POST') {
req.resume();
return json(res, 400, { error: 'invalid_bundle', message: '받아오기 실패: manifest.json 이 없습니다 (겜녹이에서 내보낸 기록 zip 이 아닙니다)' });
}
if ((m = p.match(/^\/api\/utterances\/([^/]+)\/info$/))) {
const u = db.utterances.find((x) => x.id === m[1]);
if (!u) return json(res, 404, { error: 'not_found' });

View File

@@ -17,6 +17,7 @@ import { MatchPage } from './pages/MatchPage';
import { CulpritPage } from './pages/CulpritPage';
import { MatchesPage, UserPage, UsersPage } from './pages/UserPages';
import { LogsPage } from './pages/LogsPage';
import { RecordsPage } from './pages/RecordsPage';
import { installErrorReporting } from './lib/report';
import { useLocation } from 'react-router';
@@ -67,6 +68,7 @@ function Shell() {
<Routes>
<Route path="/" element={<TimelinePage />} />
<Route path="/matches" element={<MatchesPage />} />
<Route path="/records" element={<RecordsPage />} />
<Route path="/matches/:id" element={<MatchPage />} />
<Route path="/users" element={<UsersPage />} />
<Route path="/users/:id" element={<UserPage />} />

View File

@@ -174,6 +174,7 @@ export function Header() {
const nav = [
['/', '타임라인'],
['/matches', '경기'],
['/records', '기록'],
['/users', '유저'],
['/dictionary', '단어사전'],
['/culprit', '🔍 범인찾기'],

View File

@@ -12,6 +12,8 @@ import type {
UtteranceItem,
UtteranceInfo,
GameType,
BundleInfo,
BundleImportResult,
} from '@gvr/shared';
import { reportClient } from './report';
@@ -159,6 +161,23 @@ export const api = {
if (res.status === 503 && b.error === 'device_offline') emit('device_offline');
return { ok: false, status: res.status, error: b.error ?? 'error', message: b.message ?? '분석을 시작하지 못했습니다' };
},
/** 기록 묶음 (v1.3.7~ 앱) */
bundles: () => request<{ bundles: BundleInfo[] }>('/api/bundles').then((r) => r.bundles),
deleteBundles: (ids: string[]) => request<{ bundles: number; utterances: number; files: number }>('/api/bundles/delete', { method: 'POST', body: JSON.stringify({ ids }) }),
bundleExportUrl: (ids: string[]) => `/api/bundles/export?ids=${ids.map(encodeURIComponent).join(',')}`,
/** zip 받아오기. 실패하면 서버가 준 이유("받아오기 실패: …")를 담은 Error */
importBundle: async (file: Blob): Promise<BundleImportResult> => {
let res: Response;
try {
res = await fetch('/api/bundles/import', { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/zip', accept: 'application/json' }, body: file });
} catch {
throw new Error('받아오기 실패: 네트워크 오류');
}
const b = await res.json().catch(() => ({}));
if (res.ok) return b as BundleImportResult;
if (res.status === 503) emit('device_offline');
throw new Error(b.message ?? (res.status === 413 ? '받아오기 실패: zip 이 너무 큽니다 (300MB 까지)' : `받아오기 실패 (${res.status} ${b.error ?? ''})`));
},
utteranceInfo: (id: string) => request<UtteranceInfo>(`/api/utterances/${encodeURIComponent(id)}/info`),
correct: (id: string, text: string) =>
request<UtteranceItem>(`/api/utterances/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ text }) }),

View File

@@ -15,6 +15,11 @@ export function fmtWhen(ts: number): string {
return `${md} ${hm}`;
}
/** 날짜만: "오늘" · "어제" · "10월 7일" (fmtWhen 에서 시각을 뺀 것) */
export function fmtDay(ts: number): string {
return fmtWhen(ts).replace(/\s\d{2}:\d{2}$/, '');
}
export function fmtHM(ts: number): string {
return new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, hour: '2-digit', minute: '2-digit', hour12: false }).format(ts);
}
@@ -54,7 +59,7 @@ export function fmtSec(sec: number): string {
}
export function realTip(ts: number) {
return `현실 시간 ${fmtWhen(ts).split(' ')[0]} ${fmtReal(ts)}`;
return `현실 시간 ${fmtDay(ts)} ${fmtReal(ts)}`;
}
/** "YYYY-MM-DD" (KST) ↔ ms */

View File

@@ -0,0 +1,263 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
import type { BundleInfo, BundleImportResult } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { fmtDuration, fmtHM, fmtWhen, fmtDay } from '../lib/format';
import { sfx } from '../lib/sfx';
import { useAuth, useData, useLive, useStatus } from '../store/app';
import { Avatar, ErrorBox, Spinner } from '../components/common';
import { IDownload } from '../components/Icons';
/**
* 기록 관리 (v1.3.7): 경기 하나 · 경기 전 대화 · 경기 후 대화 · 게임 밖 대화를 묶음으로 보고,
* 묶음 단위로 기록 보기 · zip 내려받기 · 지우기(관리자) · zip 받아오기(관리자)를 한다.
*/
const fmtMB = (b: number) => (b >= 1024 * 1024 ? `${(b / 1024 / 1024).toFixed(1)}MB` : `${Math.max(1, Math.round(b / 1024))}KB`);
const MAX_ZIP = 300 * 1024 * 1024;
export function RecordsPage() {
const { epoch } = useStatus();
const { auth } = useAuth();
const admin = auth.status === 'ok' && !!auth.me.canViewLogs;
const nav = useNavigate();
const [list, setList] = useState<BundleInfo[] | null>(null);
const [err, setErr] = useState<unknown>(null);
const [old, setOld] = useState(false);
const [sel, setSel] = useState<Set<string>>(new Set());
const [confirm, setConfirm] = useState<BundleInfo[] | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [kind, setKind] = useState<'all' | 'match' | 'talk'>('all');
const file = useRef<HTMLInputElement>(null);
const load = useCallback(() => {
setErr(null);
api
.bundles()
.then((b) => {
setList(b);
setSel((s) => new Set([...s].filter((id) => b.some((x) => x.id === id))));
})
.catch((e) => {
if (e instanceof ApiError && e.status === 404) setOld(true);
else setErr(e);
});
}, []);
useEffect(load, [load, epoch]);
useLive((e) => {
if (e.type === 'records.changed') load();
});
const shown = useMemo(() => (list ?? []).filter((b) => kind === 'all' || b.kind === kind), [list, kind]);
const days = useMemo(() => {
const g = new Map<string, BundleInfo[]>();
for (const b of shown) {
const d = fmtDay(b.from);
g.set(d, [...(g.get(d) ?? []), b]);
}
return [...g];
}, [shown]);
const picked = (list ?? []).filter((b) => sel.has(b.id));
const toggle = (id: string) => setSel((s) => (s.has(id) ? new Set([...s].filter((x) => x !== id)) : new Set([...s, id])));
const download = (ids: string[]) => {
sfx('click');
const a = document.createElement('a');
a.href = api.bundleExportUrl(ids);
a.download = '';
document.body.appendChild(a);
a.click();
a.remove();
setMsg({ ok: true, text: `zip 을 만드는 중입니다. 묶음이 크면 내려받기가 시작될 때까지 조금 걸립니다.` });
};
const doDelete = async (bs: BundleInfo[]) => {
setBusy('delete');
try {
const r = await api.deleteBundles(bs.map((b) => b.id));
setMsg({ ok: true, text: `묶음 ${r.bundles}개를 지웠습니다 (발화 ${r.utterances}개, 음성 파일 ${r.files}개)` });
setSel(new Set());
setConfirm(null);
load();
} catch (e) {
setMsg({ ok: false, text: e instanceof ApiError && e.status === 403 ? '지우기는 관리자만 할 수 있습니다' : '지우지 못했습니다' });
} finally {
setBusy(null);
}
};
const doImport = async (f: File) => {
if (f.size > MAX_ZIP) return setMsg({ ok: false, text: '받아오기 실패: zip 이 너무 큽니다 (300MB 까지)' });
setBusy('import');
setMsg(null);
try {
const r: BundleImportResult = await api.importBundle(f);
setMsg({
ok: true,
text: `받아오기 완료: ${r.bundles.join(', ')} · 발화 ${r.added.utterances}개 추가 (음성 ${r.added.audio}개${r.added.matches ? `, 경기 ${r.added.matches}개` : ''})${r.skipped ? ` · 이미 있는 발화 ${r.skipped}개는 건너뜀` : ''}`,
});
load();
} catch (e) {
setMsg({ ok: false, text: (e as Error).message });
} finally {
setBusy(null);
if (file.current) file.current.value = '';
}
};
const view = (b: BundleInfo) => {
sfx('click');
if (b.kind === 'match' && b.matchId) nav(`/?match=${encodeURIComponent(b.matchId)}`);
else nav(`/?game=none&from=${b.from}&to=${b.to}&order=asc`);
};
if (old)
return (
<main className="page-pad">
<h2 className="page-h h">기록 관리</h2>
<div className="empty">게임 PC 의 겜녹이가 예전 버전입니다. v1.3.7 이상으로 업데이트하면 경기별로 묶어 보고 지우기 · zip 내려받기 · 받아오기를 할 수 있습니다.</div>
</main>
);
return (
<main className="page-pad records">
<div className="page-h-row">
<h2 className="page-h h">기록 관리</h2>
<div className="chips-wrap">
{(
[
['all', '전체'],
['match', '경기'],
['talk', '경기 밖 대화'],
] as const
).map(([k, l]) => (
<button key={k} className={`chip${kind === k ? ' on' : ''}`} onClick={() => setKind(k)}>
{l}
</button>
))}
</div>
<div className="rec-actions">
{admin && (
<>
<input ref={file} type="file" accept=".zip,application/zip" hidden onChange={(e) => e.target.files?.[0] && void doImport(e.target.files[0])} />
<button className="chip" disabled={busy === 'import'} onClick={() => file.current?.click()} title="내려받아 둔 기록 zip 을 다시 넣습니다">
⬆ {busy === 'import' ? '받아오는 중…' : '받아오기 (zip)'}
</button>
</>
)}
</div>
</div>
<p className="rec-help dim">
경기 하나가 묶음 하나입니다. 경기 밖 대화는 다음 경기 30분 전 안이면 "경기 전 대화", 지난 경기 30분 안이면 "경기 후 대화"로 묶습니다. 묶음을 골라 한 번에 zip 으로 내려받거나{admin ? ' 지울 수 있고, 받아 둔 zip 은 "받아오기"로 다시 넣을 수 있습니다' : ' 할 수 있습니다 (지우기 · 받아오기는 관리자만)'}.
</p>
{msg && <div className={`rec-msg ${msg.ok ? 'ok' : 'bad'}`}>{msg.text}</div>}
{picked.length > 0 && (
<div className="rec-selbar">
<b>{picked.length}개 선택</b>
<span className="dim">
발화 {picked.reduce((n, b) => n + b.utterances, 0)}개 · 음성 {fmtMB(picked.reduce((n, b) => n + b.audioBytes, 0))}
</span>
<button className="chip on" onClick={() => download(picked.map((b) => b.id))}>
<IDownload width={14} height={14} /> 한 번에 zip
</button>
{admin && (
<button className="chip danger" onClick={() => setConfirm(picked)}>
🗑 한 번에 지우기
</button>
)}
<button className="link-btn" onClick={() => setSel(new Set())}>
선택 해제
</button>
</div>
)}
{err != null && <ErrorBox error={err} onRetry={load} />}
{!list && !err && <Spinner />}
{list && !shown.length && <div className="empty">기록이 없습니다.</div>}
{days.map(([day, bs]) => (
<section key={day} className="rec-day">
<h4>
<label>
<input
type="checkbox"
checked={bs.every((b) => sel.has(b.id))}
onChange={(e) => setSel((s) => (e.target.checked ? new Set([...s, ...bs.map((b) => b.id)]) : new Set([...s].filter((id) => !bs.some((b) => b.id === id)))))}
/>{' '}
{day}
</label>
</h4>
{bs.map((b) => (
<BundleRow key={b.id} b={b} on={sel.has(b.id)} admin={admin} onToggle={() => toggle(b.id)} onView={() => view(b)} onZip={() => download([b.id])} onDelete={() => setConfirm([b])} />
))}
</section>
))}
{confirm && (
<div className="ctx-dim" onPointerDown={() => busy !== 'delete' && setConfirm(null)}>
<div className="ctx-dialog" role="alertdialog" aria-label="기록 지우기" onPointerDown={(e) => e.stopPropagation()}>
<div className="ctx-head">
<b>기록 {confirm.length}묶음을 지울까요?</b>
</div>
<ul className="rec-del-list">
{confirm.map((b) => (
<li key={b.id}>
{b.label} · {fmtWhen(b.from)} · 발화 {b.utterances}개
</li>
))}
</ul>
<p className="dim small">발화 · 음성 파일 · 경기 기록(킬 · 라운드 · 범인 분석)이 게임 PC 에서 지워지고 되돌릴 수 없습니다. 먼저 zip 으로 받아 두면 "받아오기"로 다시 넣을 수 있습니다.</p>
<div className="ctx-foot">
<button className="chip" onClick={() => download(confirm.map((b) => b.id))}>
<IDownload width={14} height={14} /> 먼저 zip 받기
</button>
<button className="chip danger" disabled={busy === 'delete'} onClick={() => void doDelete(confirm)}>
{busy === 'delete' ? '지우는 중…' : '🗑 지우기'}
</button>
<button className="chip" onClick={() => setConfirm(null)}>
취소
</button>
</div>
</div>
</div>
)}
</main>
);
}
function BundleRow({ b, on, admin, onToggle, onView, onZip, onDelete }: { b: BundleInfo; on: boolean; admin: boolean; onToggle: () => void; onView: () => void; onZip: () => void; onDelete: () => void }) {
const { userById } = useData();
const icon = b.kind === 'match' ? (b.game === 'lol' ? '🏆' : '🎯') : '💬';
return (
<div className={`rec-row k-${b.kind}${b.game ? ` g-${b.game}` : ''}${on ? ' sel' : ''}`}>
<input type="checkbox" checked={on} onChange={onToggle} aria-label={`${b.label} 선택`} />
<span className="rec-ic">{icon}</span>
<div className="rec-main" onClick={onView} role="button" title="기록 보기">
<div className="rec-title">
<b>{b.label}</b>
{b.sub && <span className="dim">· {b.sub}</span>}
</div>
<div className="rec-meta dim">
<span className="mono">
{fmtHM(b.from)} ~ {fmtHM(b.to)}
</span>{' '}
({fmtDuration(Math.max(0, b.to - b.from))}) · 발화 {b.utterances}개 · 말한 시간 {fmtDuration(b.talkMs)} · 음성 {b.audio}개 {b.audioBytes ? `(${fmtMB(b.audioBytes)})` : ''}
{b.kind === 'match' ? ` · 경기 이벤트 ${b.events}개` : ''}
</div>
</div>
<div className="rec-avs">
{b.users.slice(0, 6).map((id) => (
<Avatar key={id} user={userById(id)} size={24} />
))}
</div>
<div className="rec-btns">
<button className="chip" onClick={onView}>
기록 보기
</button>
<button className="chip" onClick={onZip} title="이 묶음을 zip 으로 내려받기 (음성 ogg · 대화.txt 포함)">
<IDownload width={14} height={14} /> zip
</button>
{admin && (
<button className="chip danger" onClick={onDelete} title="이 묶음 지우기">
🗑
</button>
)}
</div>
</div>
);
}

View File

@@ -2,7 +2,7 @@ import type { MatchDetail, MatchSummary, User } from '@gvr/shared';
import type { Filters } from '../lib/filters';
import { Avatar, CharIcon } from '../components/common';
import { sfx } from '../lib/sfx';
import { dateInputToMs, dateInputValue, fmtHM, fmtWhen } from '../lib/format';
import { dateInputToMs, dateInputValue, fmtHM, fmtDay } from '../lib/format';
import { TYPE_GROUPS } from '../lib/game';
type Update = (p: Partial<Filters>) => void;
@@ -45,7 +45,7 @@ export function Sidebar({ f, update, users, matches, detail }: { f: Filters; upd
sfx('click');
fn();
};
const today = matches.length ? fmtWhen(matches[0].startedAt).split(' ')[0] : '';
const today = matches.length ? fmtDay(matches[0].startedAt) : '';
return (
<aside className="side">
<div>

View File

@@ -3,7 +3,7 @@ import { Link, useNavigate, useParams } from 'react-router';
import type { GameType, MatchSummary, User, UserProfile } from '@gvr/shared';
import { api } from '../lib/api';
import { useStatus } from '../store/app';
import { fmtDuration, fmtWhen } from '../lib/format';
import { fmtDuration, fmtDay } from '../lib/format';
import { sfx } from '../lib/sfx';
import { Avatar, ErrorBox, Spinner } from '../components/common';
import { MatchItem } from './Sidebar';
@@ -57,7 +57,7 @@ export function MatchesPage() {
const groups = useMemo(() => {
const g = new Map<string, MatchSummary[]>();
for (const m of data ?? []) {
const d = fmtWhen(m.startedAt).split(' ')[0];
const d = fmtDay(m.startedAt);
g.set(d, [...(g.get(d) ?? []), m]);
}
return [...g];

View File

@@ -3743,3 +3743,135 @@ button.match:hover {
background: var(--accent);
box-shadow: 0 0 6px rgba(255, 70, 85, 0.6);
}
/* ── 기록 관리 (/records) ── */
.records .page-h-row {
flex-wrap: wrap;
}
.rec-actions {
margin-left: auto;
display: flex;
gap: 8px;
}
.rec-help {
font-size: 13px;
margin: 4px 0 14px;
line-height: 1.6;
}
.rec-msg {
padding: 9px 14px;
border-radius: 8px;
font-size: 13px;
margin-bottom: 12px;
}
.rec-msg.ok {
background: rgba(69, 211, 154, 0.1);
border: 1px solid rgba(69, 211, 154, 0.35);
color: #9ff0cc;
}
.rec-msg.bad {
background: #2a1418;
border: 1px solid #5a2630;
color: #ffb3bb;
}
.rec-selbar {
position: sticky;
top: 0;
z-index: 5;
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
padding: 10px 14px;
margin-bottom: 12px;
background: #13202c;
border: 1px solid #2c3f52;
border-radius: 10px;
font-size: 13px;
}
.chip.danger {
border-color: rgba(255, 70, 85, 0.5);
color: #ff9aa3;
}
.chip.danger:hover:not(:disabled) {
background: rgba(255, 70, 85, 0.15);
}
.rec-day h4 {
font-size: 12.5px;
color: var(--muted);
margin: 18px 0 8px;
}
.rec-day h4 label {
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
}
.rec-row {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 14px;
border: 1px solid #1c2a37;
border-left: 3px solid #3a4d60;
border-radius: 10px;
background: #0f1923;
margin-bottom: 8px;
}
.rec-row.k-match.g-valorant {
border-left-color: var(--accent);
}
.rec-row.k-match.g-lol {
border-left-color: var(--lol);
}
.rec-row.k-talk {
border-left-color: var(--mint);
}
.rec-row.sel {
background: #14222f;
border-color: #2c3f52;
}
.rec-ic {
font-size: 18px;
width: 24px;
text-align: center;
}
.rec-main {
flex: 1;
min-width: 0;
cursor: pointer;
}
.rec-title {
display: flex;
gap: 6px;
align-items: baseline;
font-size: 14px;
flex-wrap: wrap;
}
.rec-meta {
font-size: 12px;
margin-top: 3px;
}
.rec-avs {
display: flex;
gap: 2px;
}
.rec-btns {
display: flex;
gap: 6px;
}
.rec-del-list {
font-size: 13px;
margin: 6px 0 10px;
padding-left: 18px;
max-height: 240px;
overflow: auto;
}
@media (max-width: 720px) {
.rec-row {
flex-wrap: wrap;
}
.rec-avs {
display: none;
}
}