Files
game_voice_recorder/app/test/core.test.ts
EJClaw 79d6bb2aad v1.4.2: 녹음 중에 들어온 사람이 사이트에서 "알 수 없음"으로 뜨던 문제
- 앱: 녹음 중 새로 들어온 사람을 저장한 뒤 users.updated 를 보낸다
- 사이트: 실시간 발화 · 녹음 상태에 모르는 유저 아이디가 오면 유저 목록을 한 번 다시 받는다 (예전 앱 대비)
- 목 서버: /mock/latejoin 로 재현

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 22:41:48 +09:00

334 lines
17 KiB
TypeScript

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 { Timeline, timeLabel } from '../src/core/timeline.ts';
import { diffWords, Dictionary } from '../src/core/dict/dictionary.ts';
import { realignWords } from '../src/core/api/server.ts';
import { processMatchDetails } from '../src/core/games/valorant.ts';
import { GameAssets } from '../src/core/games/assets.ts';
import { OggOpusWriter, opusSamples, removeInsertedSilence, SILENCE_FRAME } from '../src/core/discord/ogg.ts';
import { Utterance, tagRtp, tapRtp } from '../src/core/discord/recorder.ts';
import { Retention } from '../src/core/retention.ts';
import { makeValDetails, SELF } from './fixtures/make-val-details.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-test-'));
test('Ogg Opus writer: ffmpeg 가 읽을 수 있고 길이가 맞다', () => {
const dir = tmp();
const src = path.join(dir, 'src.ogg');
// 2초 톤을 Opus 로 만든 뒤 패킷을 꺼내 다시 쓴다
execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2', '-ac', '2', '-ar', '48000', '-c:a', 'libopus', '-frame_duration', '20', src]);
const packets = readOggPackets(fs.readFileSync(src)).slice(2); // OpusHead, OpusTags 제외
const out = path.join(dir, 'out.ogg');
const w = new OggOpusWriter(out);
for (const p of packets) w.write(p);
for (let i = 0; i < 25; i++) w.write(SILENCE_FRAME); // 0.5초 무음 채우기
w.close();
assert.equal(opusSamples(SILENCE_FRAME), 960);
const dur = Number(execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', out]).toString());
assert.ok(Math.abs(dur - 2.5) < 0.05, `duration ${dur}`);
// 끝까지 디코드되는지
execFileSync('ffmpeg', ['-v', 'error', '-i', out, '-f', 'null', '-']);
});
test('녹음기: 패킷이 몰려 와도 말 중간에 무음을 넣지 않는다 (RTP 타임스탬프 기준)', () => {
// 게임 중 실제 수신 모양: 20ms 간격으로 만든 패킷이 40~60ms 마다 2~3개씩 한꺼번에 도착 (v1.3.5 사용자 파일 "##.##.##")
const dir = tmp();
const voice = Array.from({ length: 100 }, (_, i) => Buffer.from([0x78, i & 0xff, 0x01]));
const u = new Utterance(dir, 1_000_000);
let now = 1_000_020;
let seq = 65530; // 순번이 한 바퀴 도는 경우도 함께
let ts = 4294967296 - 960 * 10; // 타임스탬프도 한 바퀴 돔
let filled = 0;
for (let i = 0; i < voice.length; i++) {
if (i === 60) {
// 진짜 쉼 0.4초: 패킷 20개 자리가 비었다
seq = (seq + 20) & 0xffff;
ts = (ts + 960 * 20) >>> 0;
now += 400;
}
if (i % 3 === 0) now += 60; // 3개씩 몰려 도착
filled += Math.max(0, u.place(tagRtp(voice[i], { seq, ts }), now, 1000));
seq = (seq + 1) & 0xffff;
ts = (ts + 960) >>> 0;
}
// 중복 패킷은 버린다
assert.equal(u.place(tagRtp(Buffer.from([0x78, 0, 0]), { seq: (seq - 1) & 0xffff, ts: (ts - 960) >>> 0 }), now, 1000), -1);
assert.equal(filled, 20, '진짜 쉼만 채운다');
assert.equal(u.writer.samples, (100 + 20) * 960);
u.writer.close();
});
test('예전 녹음 고치기: 말 중간에 끼운 무음만 빼고 말 끝 무음은 남긴다', () => {
const f = path.join(tmp(), 'old.ogg');
const w = new OggOpusWriter(f);
const v = (i: number) => Buffer.from([0x78, i, 1]);
// "##.##.##" + 진짜 쉼(10) + "##" + 말 끝 무음 5
const seq = [v(1), v(2), SILENCE_FRAME, v(3), v(4), SILENCE_FRAME, v(5), v(6), ...Array(10).fill(SILENCE_FRAME), v(7), v(8), ...Array(5).fill(SILENCE_FRAME)];
for (const p of seq) w.write(p);
w.close();
assert.equal(removeInsertedSilence(f), 2);
const after = readOggPackets(fs.readFileSync(f)).slice(2);
assert.equal(after.length, seq.length - 2);
assert.equal(removeInsertedSilence(f), 0, '두 번 고치지 않는다');
execFileSync('ffmpeg', ['-v', 'error', '-i', f, '-f', 'null', '-']);
});
test('녹음기: RTP 시각이 없을 때도 몰려 온 패킷 사이에 무음을 넣지 않는다', () => {
const u = new Utterance(tmp(), 1_000_000);
let now = 1_000_020;
let filled = 0;
for (let i = 0; i < 60; i++) {
if (i % 3 === 0) now += 60;
filled += u.place(Buffer.from([0x78, i, 1]), now, 1000);
}
assert.equal(filled, 0);
now += 500; // 0.5초 쉼 뒤 말
filled += u.place(Buffer.from([0x78, 9, 1]), now, 1000);
assert.ok(filled >= 18 && filled <= 25, `filled ${filled}`);
u.writer.close();
});
test('녹음기: 디스코드 수신기의 RTP 헤더를 패킷에 붙인다', () => {
const rtp = Buffer.alloc(16);
rtp[0] = 0x80;
rtp.writeUInt16BE(1234, 2);
rtp.writeUInt32BE(99999, 4);
const opus = Buffer.from([0x78, 1, 2]);
const receiver = { parsePacket: (_b: Buffer) => opus };
assert.equal(tapRtp(receiver), true);
assert.equal(tapRtp(receiver), true); // 두 번 감싸지 않음
const out = receiver.parsePacket(rtp);
const u = new Utterance(tmp(), 0);
u.place(out, 20, 1000);
assert.equal(u.rtpBase, 99999);
assert.equal(u.lastSeq, 1234);
u.writer.close();
});
function readOggPackets(buf: Buffer): Buffer[] {
const out: Buffer[] = [];
let pos = 0;
let cur: Buffer[] = [];
while (pos < buf.length) {
const nseg = buf[pos + 26];
const lacing = buf.subarray(pos + 27, pos + 27 + nseg);
let p = pos + 27 + nseg;
for (const l of lacing) {
cur.push(buf.subarray(p, p + l));
p += l;
if (l < 255) {
out.push(Buffer.concat(cur));
cur = [];
}
}
pos = p;
}
return out;
}
test('단어 diff: 고친 단어 쌍 추출', () => {
assert.deepEqual(diffWords('레이저 궁 빠졌어 비 싸이트 로태 하자', '레이즈 궁 빠졌어 B 사이트 로테 하자'), [
['레이저', '레이즈'],
['비 싸이트', 'B 사이트'],
['로태', '로테'],
]);
assert.deepEqual(diffWords('같은 문장', '같은 문장'), []);
});
test('단어 시각 재배치', () => {
const old = [
{ w: '레이저', s: 0.1, e: 0.5 },
{ w: '궁', s: 0.6, e: 0.8 },
];
assert.deepEqual(realignWords(old, '레이즈 궁', 1).map((w) => [w.w, w.s]), [
['레이즈', 0.1],
['궁', 0.6],
]);
const re = realignWords(old, '레이즈 궁 빠졌어', 1);
assert.equal(re.length, 3);
assert.equal(re[0].s, 0.1);
assert.ok(Math.abs(re[2].e - 0.8) < 0.02);
});
test('사전: 기본 사전 적재, 상황별 핫워드, 사이트 교정 학습', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const dict = new Dictionary(store, path.join(import.meta.dirname, '..', 'resources'), () => ({ valorant: true, lol: true, daily: true }));
dict.seed();
const hv = dict.hotwords('valorant').split(' ');
assert.ok(hv.length > 20 && hv.length <= 40);
assert.ok(hv.includes('레이즈') || hv.includes('제트'), hv.slice(0, 10).join(','));
assert.ok(dict.corrections().some((c) => c.from === '레이저' && c.to === '레이즈'));
assert.equal(dict.learn('나 오퍼래잇 삼', '나 오퍼레이터 삼'), 1);
assert.ok(dict.corrections().some((c) => c.from === '오퍼래잇' && c.to === '오퍼레이터'));
assert.ok(dict.hotwords('valorant').split(' ')[0] === '오퍼레이터', '사이트 교정 단어가 가장 먼저');
// 다시 seed 해도 사이트 교정은 남는다
dict.seed();
assert.ok(dict.corrections().some((c) => c.from === '오퍼래잇'));
store.close();
});
test('발로란트 경기 상세 → 라운드·킬·시간 표시', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const assets = new GameAssets(path.join(dir, 'cache'));
const S = Date.UTC(2026, 9, 15, 12, 0, 0);
const res = processMatchDetails(makeValDetails(S), SELF, assets, 'val-m-0001', S + 3000);
assert.equal(res.clockOffset, 0);
assert.equal(res.rounds.length, 3);
// R1 전투 시작 = 60000-25000 = 35000
assert.equal(res.rounds[0].combat_at, S + 35000);
assert.equal(res.rounds[0].started_at, S + 5000);
// R3 전투 시작 = 330000-20000 = 310000, R2 는 보간
assert.equal(res.rounds[2].combat_at, S + 310000);
assert.ok(res.rounds[1].combat_at > res.rounds[0].combat_at && res.rounds[1].combat_at < res.rounds[2].combat_at);
assert.deepEqual(res.result, { win: true, score: { ally: 2, enemy: 1 } });
const kills = res.events.filter((e) => e.type === 'kill');
assert.equal(kills.length, 4);
assert.ok(res.events.some((e) => e.type === 'spike' && JSON.parse(e.data).action === 'defuse'));
store.upsertMatch({ id: 'val-m-0001', game: 'valorant', started_at: S, ended_at: S + 420000, status: 'complete' });
store.replaceRounds('val-m-0001', res.rounds);
const ctx = { match: store.getMatch('val-m-0001')!, rounds: store.rounds('val-m-0001') };
// R1 전투 42초 후
assert.deepEqual(timeLabel(S + 35000 + 42000, ctx).primary, 'R1 · 0:42');
assert.equal(timeLabel(S + 35000 + 42000, ctx).secondary, '1:17');
// 구매 단계
assert.equal(timeLabel(S + 10000, ctx).primary, 'R1 · 구매');
// 경기 밖: 현실 시각
assert.match(timeLabel(S + 3600000, ctx).primary, /^\d\d:\d\d:\d\d$/);
store.close();
});
test('타임라인 조회: 필터·검색·커서', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const tl = new Timeline(store);
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
const t0 = Date.UTC(2026, 9, 15, 12, 0, 0);
const texts = ['스모크 깔게 미드로 와', '레이즈 궁 빠졌어', '오퍼 사줘', '배고프다 치킨 먹자', 'B 사이트 로테 하자'];
texts.forEach((t, i) => {
store.insertUtterance({ id: `x${i}`, session_id: null, user_id: i % 2 ? 'u2' : 'u1', started_at: t0 + i * 1000, ended_at: t0 + i * 1000 + 800, audio_path: null, match_id: null });
store.updateUtteranceResult(`x${i}`, { text: t, raw_text: t, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 2, model: 'tiny', status: 'realtime' });
});
store.insertUtterance({ id: 'n1', session_id: null, user_id: 'u1', started_at: t0 + 9000, ended_at: t0 + 9500, audio_path: null, match_id: null });
store.updateUtteranceResult('n1', { text: null, raw_text: '시청해 주셔서 감사합니다', words: [], noise: true, noise_reason: 'hallucination', confidence: 0.2, lufs: -40, gain_db: 20, model: 'tiny', status: 'realtime' });
let page = tl.query({ limit: 3 });
assert.equal(page.items.length, 3);
assert.equal(page.items[0].id, 'x4', '잡음은 보이지 않는다');
const page2 = tl.query({ limit: 3, cursor: page.next! });
assert.deepEqual(page2.items.map((i) => i.id), ['x1', 'x0']);
assert.equal(tl.query({}).items.length, 5);
assert.deepEqual(tl.query({ q: '레이즈 궁' }).items.map((i) => i.id), ['x1']);
assert.deepEqual(tl.query({ q: '오퍼' }).items.map((i) => i.id), ['x2']);
assert.equal(tl.query({ users: ['u2'] }).items.length, 2);
page = tl.query({ order: 'asc', limit: 2 });
assert.deepEqual(page.items.map((i) => i.id), ['x0', 'x1']);
// 교정하면 검색 색인도 바뀐다
store.correctUtterance('x3', '배고프다 피자 먹자', []);
assert.deepEqual(tl.query({ q: '피자' }).items.map((i) => i.id), ['x3']);
assert.equal(tl.query({ q: '치킨' }).items.length, 0);
store.close();
});
test('7일 지난 음성만 삭제, 텍스트는 남음', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const audio = path.join(dir, 'audio', '2026-10-01');
fs.mkdirSync(audio, { recursive: true });
const now = Date.now();
for (const [id, age] of [
['old', 8],
['new', 2],
] as const) {
const f = path.join(audio, `${id}.ogg`);
fs.writeFileSync(f, 'x'.repeat(100));
store.insertUtterance({ id, session_id: null, user_id: 'u', started_at: now - age * 86400000, ended_at: now - age * 86400000 + 500, audio_path: f, match_id: null });
store.updateUtteranceResult(id, { text: id, raw_text: id, words: [], noise: false, noise_reason: null, confidence: 1, lufs: -18, gain_db: 0, model: 'm', status: 'precise' });
}
const r = new Retention(store, () => 7, () => path.join(dir, 'audio')).run(now);
assert.equal(r.deleted, 1);
assert.ok(!fs.existsSync(path.join(audio, 'old.ogg')));
assert.ok(fs.existsSync(path.join(audio, 'new.ogg')));
assert.equal(store.getUtterance('old')!.text, 'old');
assert.equal(store.getUtterance('old')!.audio_deleted, 1);
store.close();
});
test('표시 이름: 정한 이름으로 유저 이름 · 지난 범인 분석의 이름을 바꾸고, 새로 들어온 이름에도 쓴다', () => {
const store = new Store(path.join(tmp(), 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '실명이', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
store.db.exec(`CREATE TABLE culprit_analyses (id TEXT PRIMARY KEY, match_id TEXT NOT NULL, created_at INTEGER NOT NULL, created_by TEXT NOT NULL, model TEXT NOT NULL, current INTEGER NOT NULL DEFAULT 1, result TEXT NOT NULL, meta TEXT NOT NULL DEFAULT '{}')`);
store.db
.prepare('INSERT INTO culprit_analyses(id,match_id,created_at,created_by,model,result) VALUES(?,?,?,?,?,?)')
.run('a1', 'm1', 1, JSON.stringify({ id: 'u1', name: '실명이 다른표기' }), 'x', JSON.stringify({ result: { summary: '실명이가 캐리' }, players: [{ name: '실명이' }, { name: '민수' }] }));
store.setDisplayNames({ u1: '별명' });
assert.equal(store.getUser('u1')?.name, '별명');
assert.equal(store.getUser('u2')?.name, '민수');
const r = store.db.prepare('SELECT created_by, result FROM culprit_analyses').get() as any;
assert.equal(JSON.parse(r.created_by).name, '별명');
assert.ok(!r.result.includes('실명이') && r.result.includes('별명가 캐리'), r.result);
// 디스코드에서 예전 이름이 다시 와도 표시 이름으로 저장, 다시 열어도 유지
store.upsertUser({ id: 'u1', name: '실명이', avatar: null });
assert.equal(store.getUser('u1')?.name, '별명');
const file = store.db.name;
store.close();
const again = new Store(file);
again.upsertUser({ id: 'u1', name: '실명이', avatar: null });
assert.equal(again.getUser('u1')?.name, '별명');
again.close();
});
test('users.updated: 보내는 쪽이 빈 목록을 줘도 실제 유저 목록이 나간다 ("알 수 없음" 버그)', async () => {
const { Bus } = await import('../src/core/util/events.ts');
const bus = new Bus();
bus.usersProvider = () => [{ id: '1', name: '하늘', color: '#fff', avatar: null, excluded: false, riot: [] }];
const got: any[] = [];
bus.on('live', (e) => got.push(e));
bus.live({ type: 'users.updated', data: [] });
assert.equal(got[0].data.length, 1);
assert.equal(got[0].data[0].name, '하늘');
});
test('녹음 중에 들어온 사람: 유저로 저장하고 users.updated 를 보낸다 (중간 참여자 "알 수 없음" 버그)', async () => {
const { Bus } = await import('../src/core/util/events.ts');
const { Bot } = await import('../src/core/discord/bot.ts');
const store = new Store(path.join(tmp(), 'db.sqlite'));
const bus = new Bus();
bus.usersProvider = () => store.listUsers().map((u) => ({ id: u.id, name: u.name, color: u.color, avatar: u.avatar, excluded: false, riot: [] }));
const got: any[] = [];
bus.on('live', (e) => got.push(e));
const settings = () => ({ discord: { followEnabled: false, followUserId: null, ttsEnabled: false, ttsOnNewMember: false } }) as any;
const bot = new Bot(store, {} as any, {} as any, bus, settings);
const late = { id: '42', name: '늦게온사람', avatar: null, bot: false };
bot.gateway = { channelMembers: () => [late] } as any;
bot.state.guild = { id: 'g', name: 'g', icon: null };
bot.state.recording = { active: true, channel: '음성', channelId: 'vc', since: 1, participants: [], reason: 'command' };
await (bot as any).onVoiceState({ guildId: 'g', member: late, oldChannelId: null, newChannelId: 'vc', channel: { id: 'vc', name: '음성' } });
assert.equal(store.getUser('42')?.name, '늦게온사람');
const upd = got.filter((e) => e.type === 'users.updated');
assert.equal(upd.length, 1);
assert.ok(upd[0].data.some((u: any) => u.id === '42' && u.name === '늦게온사람'));
assert.deepEqual(bot.state.recording.participants, ['42']);
store.close();
});
test('녹음 안내 말 속도: 0.1~2.0 으로 자르고 속도마다 따로 캐시한다', async () => {
const { Announcer, clampRate } = await import('../src/core/discord/tts.ts');
assert.equal(clampRate(0.05), 0.1);
assert.equal(clampRate(3), 2);
assert.equal(clampRate('x'), 1);
const a = new Announcer(tmp(), tmp());
const one = a.cachedPath('안내', 'v', 1);
assert.equal(one, a.cachedPath('안내', 'v'), '1.0배는 예전 캐시 그대로');
assert.notEqual(a.cachedPath('안내', 'v', 1.5), one);
assert.ok(a.cachedPath('안내', 'v', 0.3).endsWith('.ogg'), '0.5배보다 느리면 워커가 만든 Ogg');
assert.ok(a.cachedPath('안내', 'v', 0.5).endsWith('.webm'));
});