- 기록 묶음 API · zip 형식(gvr-bundle v1) · 받아오기 검사(꼭 필요한 내용이 없으면 실패, 아무것도 넣지 않음) - 사이트 기록 탭, 큰 zip 조각 중계 - 관리자 확인 %인코딩 우회, 큰 전송 중 연결 끊김, 진행 중 경기 지우기, 예전 녹음 고치기 덮어쓰기, 타임라인 끼워 넣기, 숫자 반복 줄이기, TTS 반쪽 파일 등 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
197 lines
9.4 KiB
TypeScript
197 lines
9.4 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 { 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, 5, '잡음 발화는 내보내지 않는다');
|
|
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, 5);
|
|
// 받아온 녹음은 보관 기간을 받아온 날부터 센다 (녹음 날짜가 오래돼도 바로 지우지 않음)
|
|
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('기록 묶음: 진행 중인 경기는 지우지 않는다', () => {
|
|
const { store, b } = seed(tmp());
|
|
store.db.prepare(`UPDATE matches SET status='live' WHERE id='val-1'`).run();
|
|
const m = b.list().find((x) => x.kind === 'match')!;
|
|
assert.equal(m.live, true);
|
|
assert.throws(() => b.delete([m.id]), (e: any) => e instanceof BundleError && e.code === 'busy');
|
|
assert.ok(store.getMatch('val-1'));
|
|
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();
|
|
});
|