내 Riot 경기 기록 가져오기: 발로란트 match-history · 롤 LCU 기록을 게임 중이 아닐 때 30분마다 훑어 앱이 잡지 못한 경기를 source=history 로 저장 (처음은 끝까지, 다음부터 새 경기만, 상세 없는 경기는 건너뜀) · /api/matches has=timeline|voice 필터 · 경기 요약 source · voice · 녹음 없는 기록 경기의 킬 · 라운드는 타임라인 · 기록 관리에서 뺌
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -40,7 +40,7 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
|
||||
const tl = new Timeline(store);
|
||||
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
|
||||
const sttCalls: string[] = [];
|
||||
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end') };
|
||||
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end'), setGameActive: async () => undefined };
|
||||
const assets = new GameAssets(path.join(dir, 'cache'));
|
||||
(assets as any).refresh = async () => undefined; // 네트워크 없이
|
||||
assets.lol = {
|
||||
|
||||
115
app/test/history.test.ts
Normal file
115
app/test/history.test.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
// v1.9.0: 내 Riot 경기 기록 가져오기 (앱이 꺼져 있을 때 한 경기도 사이트 경기 탭에)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { startMockRiot } from './mock/riot.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-hist-'));
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
async function until(fn: () => boolean, ms = 10000, label = 'condition') {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - t > ms) throw new Error(`timeout: ${label}`);
|
||||
await sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
test('경기 기록: 발로란트 · 롤 기록을 가져와 history 경기로 저장, 필터 · 타임라인 · 다시 훑기', async () => {
|
||||
const dir = tmp();
|
||||
const mock = await startMockRiot(path.join(dir, 'mock'));
|
||||
Object.assign(process.env, {
|
||||
GVR_RIOT_LOCKFILE: mock.lockfile,
|
||||
GVR_LCU_LOCKFILE: mock.lockfile,
|
||||
GVR_VAL_GLZ: mock.base,
|
||||
GVR_VAL_PD: mock.base,
|
||||
GVR_LOL_LIVE_URL: mock.base,
|
||||
GVR_POLL_MS: '150',
|
||||
GVR_HISTORY_EVERY_MS: '400',
|
||||
GVR_HISTORY_GAP_MS: '5',
|
||||
});
|
||||
const { Store } = await import('../src/core/db/db.ts');
|
||||
const { Timeline } = await import('../src/core/timeline.ts');
|
||||
const { GameAssets } = await import('../src/core/games/assets.ts');
|
||||
const { GameManager } = await import('../src/core/games/manager.ts');
|
||||
const { Bus } = await import('../src/core/util/events.ts');
|
||||
const { defaultSettings } = await import('../src/core/settings.ts');
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
const tl = new Timeline(store);
|
||||
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
|
||||
const stt: any = { onMatchStart: async () => undefined, onMatchEnd: async () => undefined, setGameActive: async () => undefined };
|
||||
const assets = new GameAssets(path.join(dir, 'cache'));
|
||||
(assets as any).refresh = async () => undefined;
|
||||
const s = defaultSettings();
|
||||
store.upsertUser({ id: 'owner', name: '하늘', avatar: null });
|
||||
const H = Date.now() - 30 * 86400000;
|
||||
// 발로란트 23경기 (두 쪽): 하나는 앱이 이미 잡은 경기, 하나는 상세가 없는 경기
|
||||
mock.st.valHistory = Array.from({ length: 23 }, (_, i) => ({ MatchID: i === 5 ? 'gone-5' : `h-${i}`, GameStartTime: H - i * 3600000 }));
|
||||
store.upsertMatch({ id: 'val-h-0', game: 'valorant', started_at: H, status: 'complete' });
|
||||
// 앱이 녹음하던 때 잡지 못한 경기: 그 시간 발화가 경기에 붙는다
|
||||
store.insertUtterance({ id: 'u1', session_id: null, user_id: 'owner', started_at: H - 3600000 + 60000, ended_at: H - 3600000 + 62000, audio_path: null, match_id: null });
|
||||
mock.st.lolHistoryList = [
|
||||
{ gameId: 9001, gameCreation: H - 100000 },
|
||||
{ gameId: 9002, gameCreation: H - 200000 },
|
||||
];
|
||||
const gm = new GameManager(store, assets, worker, stt, tl, bus(), () => s, () => 'owner');
|
||||
function bus() {
|
||||
return new Bus();
|
||||
}
|
||||
gm.start();
|
||||
try {
|
||||
await until(() => !!store.getMatch('val-h-22') && store.getMatch('val-h-22')!.status === 'complete', 15000, 'val history');
|
||||
await until(() => !!store.getMatch('lol-9002') && store.getMatch('lol-9002')!.status === 'complete', 15000, 'lol history');
|
||||
const vals = store.listMatches({ game: 'valorant', limit: 100 });
|
||||
assert.equal(vals.length, 22, '23경기 중 상세 없는 1경기 빼고');
|
||||
assert.equal(store.getMatch('val-h-0')!.source, 'live', '앱이 잡은 경기는 그대로');
|
||||
const h1 = store.getMatch('val-h-1')!;
|
||||
assert.equal(h1.source, 'history');
|
||||
assert.equal(h1.started_at, H - 3600000);
|
||||
assert.ok(store.events('val-h-1').some((e) => e.type === 'kill'), '킬 기록도 (경기 화면용)');
|
||||
assert.equal(store.getUtterance('u1')!.match_id, 'val-h-1', '그 시간 발화가 붙는다');
|
||||
assert.equal(store.getMatch('lol-9001')!.source, 'history');
|
||||
assert.ok(!store.getMatch('val-gone-5'));
|
||||
assert.ok(JSON.parse(store.meta('history_skip:valorant')!).includes('val-gone-5'));
|
||||
|
||||
// 필터
|
||||
const ids = (has?: 'timeline' | 'voice') => store.listMatches({ limit: 100, has }).map((m) => m.id).sort();
|
||||
assert.equal(ids().length, 24);
|
||||
assert.deepEqual(ids('timeline'), ['val-h-0', 'val-h-1'], '타임라인: 앱이 잡은 경기 + 대화가 붙은 기록 경기');
|
||||
store.updateUtteranceResult('u1', { text: '가자', raw_text: '가자', words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'm', status: 'precise' });
|
||||
assert.deepEqual(ids('voice'), ['val-h-1']);
|
||||
const sum = gm.summary(store.getMatch('val-h-2')!);
|
||||
assert.equal(sum.source, 'history');
|
||||
assert.equal(sum.voice, false);
|
||||
assert.equal(gm.summary(store.getMatch('val-h-1')!).voice, true);
|
||||
|
||||
// 타임라인: 녹음 없는 기록 경기의 이벤트는 빼고, 그 경기를 고르면 보인다
|
||||
const page = tl.query({ limit: 500 });
|
||||
const evMatches = new Set(page.items.filter((it: any) => it.kind === 'event').map((it: any) => it.matchId));
|
||||
assert.ok(!evMatches.has('val-h-2') && !evMatches.has('lol-9001'));
|
||||
assert.ok(evMatches.has('val-h-1'), '대화가 붙은 기록 경기는 타임라인에');
|
||||
assert.ok(tl.query({ match: 'val-h-2', limit: 50 }).items.length > 0);
|
||||
|
||||
// 다시 훑기: 한 번 끝까지 본 뒤에는 첫 쪽만 (새 경기 1개)
|
||||
const before = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length;
|
||||
mock.st.valHistory.unshift({ MatchID: 'h-new', GameStartTime: Date.now() - 3600000 });
|
||||
await until(() => store.getMatch('val-h-new')?.status === 'complete', 10000, 'new match');
|
||||
await sleep(100);
|
||||
const pages = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length - before;
|
||||
assert.ok(pages >= 1 && pages <= 3, `다시 훑을 때는 첫 쪽만 (${pages})`);
|
||||
|
||||
// 경기 중에는 가져오지 않는다
|
||||
mock.st.valState = 'INGAME';
|
||||
await until(() => gm.status().valorant.inMatch, 5000, 'in match');
|
||||
const n = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length;
|
||||
await sleep(1200);
|
||||
assert.equal(mock.st.hits.filter((h) => h.startsWith('/match-history/')).length, n);
|
||||
} finally {
|
||||
gm.stop();
|
||||
await mock.close();
|
||||
store.close();
|
||||
for (const k of ['GVR_HISTORY_EVERY_MS', 'GVR_HISTORY_GAP_MS']) delete process.env[k];
|
||||
}
|
||||
});
|
||||
@@ -18,6 +18,12 @@ export interface MockState {
|
||||
lolGameId: number;
|
||||
lolHistoryReady: boolean;
|
||||
lolStart: number;
|
||||
/** 발로란트 경기 기록 (새것부터): MatchID → 경기 시작 시각 */
|
||||
valHistory: { MatchID: string; GameStartTime: number }[];
|
||||
/** 롤 경기 기록 (LCU, 새것부터) */
|
||||
lolHistoryList: { gameId: number; gameCreation: number }[];
|
||||
/** 요청 기록 (경로) */
|
||||
hits: string[];
|
||||
}
|
||||
|
||||
export async function startMockRiot(dir: string) {
|
||||
@@ -38,6 +44,9 @@ export async function startMockRiot(dir: string) {
|
||||
lolGameId: 7001,
|
||||
lolHistoryReady: false,
|
||||
lolStart: 0,
|
||||
valHistory: [],
|
||||
lolHistoryList: [],
|
||||
hits: [],
|
||||
};
|
||||
const password = 'pw-test';
|
||||
const presence = () => {
|
||||
@@ -52,7 +61,7 @@ export async function startMockRiot(dir: string) {
|
||||
};
|
||||
return Buffer.from(JSON.stringify(priv)).toString('base64');
|
||||
};
|
||||
const routes: [RegExp, (m: RegExpMatchArray, auth: string) => [number, any]][] = [
|
||||
const routes: [RegExp, (m: RegExpMatchArray, auth: string, url: URL) => [number, any]][] = [
|
||||
// ---- Riot Client local
|
||||
[/^\/entitlements\/v1\/token$/, () => [200, { accessToken: 'acc-token', token: 'ent-token', subject: SELF, issuer: 'x' }]],
|
||||
[
|
||||
@@ -69,7 +78,23 @@ export async function startMockRiot(dir: string) {
|
||||
() => [200, { MatchID: st.valMatchId, MapID: ASCENT, Players: [{ Subject: SELF, TeamID: 'Blue', CharacterID: 'add6443a-41bd-e414-f6ad-e58d267f4e95' }] }],
|
||||
],
|
||||
// ---- pd
|
||||
[/^\/match-details\/v1\/matches\/(.+)$/, (_m, auth) => (auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}])],
|
||||
[
|
||||
/^\/match-history\/v1\/history\/(.+)$/,
|
||||
(_m, auth, url) => {
|
||||
if (!auth.startsWith('Bearer ')) return [401, {}];
|
||||
const s = Number(url.searchParams.get('startIndex') ?? 0);
|
||||
const e = Number(url.searchParams.get('endIndex') ?? 20);
|
||||
return [200, { Subject: SELF, BeginIndex: s, EndIndex: e, Total: st.valHistory.length, History: st.valHistory.slice(s, e).map((h) => ({ ...h, QueueID: 'competitive' })) }];
|
||||
},
|
||||
],
|
||||
[
|
||||
/^\/match-details\/v1\/matches\/(.+)$/,
|
||||
(m, auth) => {
|
||||
const h = st.valHistory.find((x) => x.MatchID === m[1]);
|
||||
if (h) return m[1].startsWith('gone') ? [404, {}] : [200, { ...makeValDetails(h.GameStartTime), matchInfo: { ...makeValDetails(h.GameStartTime).matchInfo, matchId: h.MatchID } }];
|
||||
return auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}];
|
||||
},
|
||||
],
|
||||
// ---- LoL Live Client Data
|
||||
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
|
||||
// ---- LCU
|
||||
@@ -79,7 +104,23 @@ export async function startMockRiot(dir: string) {
|
||||
[/^\/lol-chat\/v1\/conversations$/, () => [200, st.lolPhase === 'ChampSelect' ? [{ id: 'cs1@champ-select.kr', type: 'championSelect' }] : []]],
|
||||
[/^\/lol-chat\/v1\/conversations\/(.+)\/messages$/, () => [200, [{ id: 'msg1', body: '정글 갱 갈게요', fromSummonerId: 11, timestamp: new Date(Date.now() - 5000).toISOString(), type: 'groupchat' }]]],
|
||||
[/^\/lol-summoner\/v1\/summoners\/(\d+)$/, () => [200, { gameName: '민수' }]],
|
||||
[/^\/lol-match-history\/v1\/games\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolHistory()] : [404, {}])],
|
||||
[
|
||||
/^\/lol-match-history\/v1\/products\/lol\/current-summoner\/matches$/,
|
||||
(_m, _a, url) => {
|
||||
const s = Number(url.searchParams.get('begIndex') ?? 0);
|
||||
const e = Number(url.searchParams.get('endIndex') ?? 20);
|
||||
const games = st.lolHistoryList.slice(s, e);
|
||||
return [200, { games: { gameCount: games.length, gameIndexBegin: s, gameIndexEnd: e, games } }];
|
||||
},
|
||||
],
|
||||
[
|
||||
/^\/lol-match-history\/v1\/games\/(\d+)$/,
|
||||
(m) => {
|
||||
const h = st.lolHistoryList.find((x) => String(x.gameId) === m[1]);
|
||||
if (h) return [200, { ...lolHistory(), gameId: h.gameId, gameCreation: h.gameCreation }];
|
||||
return st.lolHistoryReady ? [200, lolHistory()] : [404, {}];
|
||||
},
|
||||
],
|
||||
[/^\/lol-match-history\/v1\/game-timelines\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolTimeline()] : [404, {}])],
|
||||
];
|
||||
const server = https.createServer({ key: fs.readFileSync(key), cert: fs.readFileSync(cert) }, (req, res) => {
|
||||
@@ -87,7 +128,8 @@ export async function startMockRiot(dir: string) {
|
||||
for (const [re, fn] of routes) {
|
||||
const m = url.pathname.match(re);
|
||||
if (!m) continue;
|
||||
const [code, body] = fn(m, String(req.headers.authorization || ''));
|
||||
st.hits.push(url.pathname);
|
||||
const [code, body] = fn(m, String(req.headers.authorization || ''), url);
|
||||
res.writeHead(code, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify(body));
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user