diff --git a/app/src/core/api/server.ts b/app/src/core/api/server.ts index d5c25f3..df8ebed 100644 --- a/app/src/core/api/server.ts +++ b/app/src/core/api/server.ts @@ -310,7 +310,13 @@ export async function buildApi(d: ApiDeps): Promise { app.get<{ Querystring: Record }>('/api/matches', async (req) => { const q = req.query; return store - .listMatches({ game: q.game || undefined, before: q.before ? Number(q.before) : undefined, limit: q.limit ? Math.min(Number(q.limit), 200) : 50 }) + .listMatches({ + game: q.game || undefined, + before: q.before ? Number(q.before) : undefined, + limit: q.limit ? Math.min(Number(q.limit), 200) : 50, + // 사이트 경기 탭 필터 (v1.9.0): timeline = 타임라인에 나오는 경기, voice = 목소리가 녹음된 경기 + has: q.has === 'timeline' || q.has === 'voice' ? q.has : undefined, + }) .map((m) => d.games.summary(m)); }); diff --git a/app/src/core/bundles.ts b/app/src/core/bundles.ts index 72dc6ea..e9a72b2 100644 --- a/app/src/core/bundles.ts +++ b/app/src/core/bundles.ts @@ -75,6 +75,8 @@ export class Bundles { const out: Group[] = []; for (const m of matches) { const list = byMatch.get(m.id) ?? []; + // Riot 경기 기록에서 가져오기만 한 경기(녹음 없음)는 기록 묶음으로 보이지 않는다 + if (m.source === 'history' && !list.length) continue; 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}` : ''; @@ -314,8 +316,8 @@ export class Bundles { 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); + .prepare('INSERT OR IGNORE INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset,source) 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, m.source === 'history' ? 'history' : 'live'); res.added.matches += r.changes; } for (const r of data.rounds ?? []) diff --git a/app/src/core/db/db.ts b/app/src/core/db/db.ts index 7e6a3d2..a12f053 100644 --- a/app/src/core/db/db.ts +++ b/app/src/core/db/db.ts @@ -50,6 +50,8 @@ export interface MatchRow { detail: string | null; status: string; clock_offset: number; + /** live: 앱이 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 */ + source: 'live' | 'history'; } export interface RoundRow { match_id: string; @@ -128,6 +130,9 @@ export class Store { /** 예전 DB 를 지금 스키마로 맞춘다 (스키마를 바꿀 때마다 여기에 단계 추가) */ private migrate(): void { + // v1.9.0: 경기 출처 (Riot 경기 기록에서 가져온 경기) + const mcols = this.db.prepare(`PRAGMA table_info(matches)`).all() as { name: string }[]; + if (!mcols.some((c) => c.name === 'source')) this.db.exec(`ALTER TABLE matches ADD COLUMN source TEXT NOT NULL DEFAULT 'live'`); // v1.0 개발 중: dictionary UNIQUE 에 pack 추가 (같은 단어가 여러 묶음에 들어갈 수 있게) const idx = this.db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='dictionary'`).get() as { sql: string } | undefined; if (idx && !/UNIQUE\s*\(kind,\s*word,\s*from_text,\s*pack\)/.test(idx.sql)) { @@ -406,13 +411,14 @@ export class Store { detail: null, status: 'live', clock_offset: 0, + source: 'live', ...(cur || {}), ...stripUndef(m), } as MatchRow; this.db .prepare( - `INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset) - VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset) + `INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset,source) + VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset,@source) ON CONFLICT(id) DO UPDATE SET started_at=@started_at, ended_at=@ended_at, map=@map, mode=@mode, queue=@queue, result=@result, detail=@detail, status=@status, clock_offset=@clock_offset`, ) @@ -422,9 +428,15 @@ export class Store { getMatch(id: string): MatchRow | undefined { return this.db.prepare('SELECT * FROM matches WHERE id=?').get(id) as MatchRow | undefined; } - listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[] }): MatchRow[] { + /** + * has: timeline = 타임라인에 나오는 경기 (앱이 잡은 경기 · 기록에서 가져왔어도 대화가 붙은 경기), voice = 목소리가 녹음된 경기 + */ + listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[]; has?: 'timeline' | 'voice' }): MatchRow[] { const where: string[] = []; const args: any[] = []; + const voice = `EXISTS (SELECT 1 FROM utterances u WHERE u.match_id = matches.id AND (u.noise = 0 OR u.corrected = 1))`; + if (opts.has === 'voice') where.push(voice); + else if (opts.has === 'timeline') where.push(`(source = 'live' OR ${voice})`); if (opts.game) { where.push('game=?'); args.push(opts.game); diff --git a/app/src/core/db/schema.sql b/app/src/core/db/schema.sql index 383dea2..f149fc5 100644 --- a/app/src/core/db/schema.sql +++ b/app/src/core/db/schema.sql @@ -82,7 +82,9 @@ CREATE TABLE IF NOT EXISTS matches ( result TEXT, detail TEXT, status TEXT NOT NULL DEFAULT 'live', - clock_offset INTEGER NOT NULL DEFAULT 0 + clock_offset INTEGER NOT NULL DEFAULT 0, + -- live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0) + source TEXT NOT NULL DEFAULT 'live' ); CREATE INDEX IF NOT EXISTS matches_started ON matches(started_at); diff --git a/app/src/core/games/history.ts b/app/src/core/games/history.ts new file mode 100644 index 0000000..2f6db77 --- /dev/null +++ b/app/src/core/games/history.ts @@ -0,0 +1,106 @@ +import type { Store } from '../db/db.js'; +import { logger } from '../util/log.js'; + +const log = logger('history'); + +/** 게임별 Riot 경기 기록 읽기 */ +export interface HistorySource { + readonly game: 'valorant' | 'lol'; + /** 지금 가져와도 되는가 (게임 중 · 요원 선택 중이면 false) */ + idle(): boolean; + /** 이 PC 에 로그인한 계정 (계정이 바뀌면 처음부터 다시 훑는다) */ + account(): string | null; + /** start 번째부터 n 개 (새것부터). 경기 행 ID 로 돌려준다. 'retry' = 지금은 못 읽음 */ + page(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'>; + /** 경기 하나를 받아 저장. gone = 기록이 없음(다시 묻지 않음), retry = 나중에 */ + fetch(id: string): Promise<'ok' | 'gone' | 'retry'>; +} + +export interface HistoryOptions { + pageSize: number; + /** 최대 몇 경기 전까지 훑을지 */ + max: number; + /** 경기 상세 요청 사이 간격 (Riot 요청 한도) */ + gapMs: number; +} + +/** + * 내 Riot 경기 기록 → 경기 목록 (v1.9.0). 앱이 꺼져 있을 때 한 경기도 사이트 경기 탭에 보이게 한다. + * 처음에는 끝까지 훑고, 그다음부터는 이미 아는 경기만 나오는 쪽까지만 본다. 게임이 시작되면 바로 멈춘다. + */ +export class HistorySync { + private running = false; + private lastAt = 0; + + constructor( + private store: Store, + private src: HistorySource, + private opts: HistoryOptions, + ) {} + + /** 주기 확인: 앞 실행에서 everyMs 가 지났고 게임 중이 아니면 백그라운드로 돌린다 */ + maybeRun(everyMs: number, firstDelayMs = 60000): void { + const now = Date.now(); + if (!this.lastAt) this.lastAt = now - everyMs + Math.min(firstDelayMs, everyMs); + if (this.running || now - this.lastAt < everyMs || !this.src.idle()) return; + this.lastAt = now; + void this.run().catch((e) => log.warn(`${this.src.game} 경기 기록 가져오기 실패`, e)); + } + + private skipKey(): string { + return `history_skip:${this.src.game}`; + } + private skipped(): Set { + try { + return new Set(JSON.parse(this.store.meta(this.skipKey()) || '[]')); + } catch { + return new Set(); + } + } + + /** 한 번 훑기. 새로 저장한 경기 수 */ + async run(): Promise { + if (this.running) return 0; + const acct = this.src.account(); + if (!acct) return 0; + this.running = true; + try { + const fullKey = `history_full:${this.src.game}:${acct}`; + const full = !!this.store.meta(fullKey); + const skip = this.skipped(); + const todo: string[] = []; + for (let start = 0; start < this.opts.max; start += this.opts.pageSize) { + if (!this.src.idle()) return 0; + const p = await this.src.page(start, this.opts.pageSize); + if (p === 'retry') return 0; + const fresh = p.ids.filter((id) => !skip.has(id) && !this.store.getMatch(id) && !todo.includes(id)); + todo.push(...fresh); + if (!p.ids.length || p.ids.length < this.opts.pageSize || (p.total !== null && start + this.opts.pageSize >= p.total)) break; + // 한 번 끝까지 훑은 뒤에는 아는 경기만 나오는 쪽에서 멈춘다 + if (full && !fresh.length) break; + } + if (todo.length) log.info(`${this.src.game} 경기 기록: 새 경기 ${todo.length}개 가져오는 중`); + let added = 0; + for (const id of todo) { + if (!this.src.idle()) { + log.info(`${this.src.game} 경기 기록: 게임이 시작돼 멈춤 (${added}/${todo.length})`); + return added; + } + const r = await this.src.fetch(id).catch(() => 'retry' as const); + if (r === 'retry') return added; + if (r === 'ok') added++; + else { + skip.add(id); + this.store.setMeta(this.skipKey(), JSON.stringify([...skip].slice(-2000))); + } + await new Promise((res) => setTimeout(res, this.opts.gapMs)); + } + // 끝(또는 max)까지 다 받았다: 다음부터는 새 경기만 본다 + this.store.setMeta(fullKey, '1'); + if (added) log.info(`${this.src.game} 경기 기록: ${added}개 저장`); + return added; + } finally { + this.running = false; + } + } +} diff --git a/app/src/core/games/lol.ts b/app/src/core/games/lol.ts index 0baafae..706f0c2 100644 --- a/app/src/core/games/lol.ts +++ b/app/src/core/games/lol.ts @@ -5,6 +5,7 @@ import { logger } from '../util/log.js'; import { lolObjectIcon } from './assets.js'; import { basicAuth, findLcu, request } from './riot.js'; import type { AdapterHost, GameAdapter } from './types.js'; +import { HistorySync } from './history.js'; const log = logger('lol'); @@ -71,8 +72,42 @@ export class LolAdapter implements GameAdapter { /** 게임 클라이언트 API 마지막 값 (지금 게임 상태 표시용) */ private snap: { at: number; gameTime: number; mode: string | null; champ: string | null; champIcon: string | null; kda: string | null; extra: string | null; teamKills: { ally: number; enemy: number } | null; players: number } | null = null; private selfRiotId: string | null = null; + private selfPuuid: string | null = null; + /** 내 경기 기록 (LCU, 앱이 꺼져 있을 때 한 경기도 경기 목록에) */ + readonly history: HistorySync; - constructor(private host: AdapterHost) {} + constructor(private host: AdapterHost) { + this.history = new HistorySync( + host.store, + { + game: 'lol', + idle: () => !!this.lcu && !(this.live && !this.live.ended) && !['ChampSelect', 'GameStart', 'InProgress', 'Reconnect'].includes(this.phase ?? ''), + account: () => this.selfPuuid, + page: (start, n) => this.historyPage(start, n), + fetch: (id) => this.historyFetch(id), + }, + { pageSize: 20, max: Number(process.env.GVR_HISTORY_MAX) || 200, gapMs: Number(process.env.GVR_HISTORY_GAP_MS) || 500 }, + ); + } + + private async historyPage(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'> { + const r = await this.lcuGet(`/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=${start}&endIndex=${start + n}`); + const games = r?.games?.games; + if (!Array.isArray(games)) return 'retry'; + return { ids: games.filter((g: any) => g?.gameId).map((g: any) => `lol-${g.gameId}`), total: null }; + } + + private async historyFetch(id: string): Promise<'ok' | 'gone' | 'retry'> { + if (!this.lcu) return 'retry'; + const gameId = id.replace(/^lol-/, ''); + const game = await this.lcuGet(`/lol-match-history/v1/games/${gameId}`); + if (!this.lcu) return 'retry'; + if (!game?.participants || !game.gameCreation) return 'gone'; + const timeline = await this.lcuGet(`/lol-match-history/v1/game-timelines/${gameId}`); + this.host.historyMatch({ id, game: 'lol', startedAt: game.gameCreation, map: game.mapId ? `Map${game.mapId}` : 'Map11', mode: game.gameMode ?? null, queue: game.queueId ? String(game.queueId) : null }); + this.applyHistory(id, game, timeline, game.gameCreation); + return 'ok'; + } start(): void { if (this.timer) return; @@ -446,6 +481,7 @@ export class LolAdapter implements GameAdapter { log.info('롤 클라이언트(LCU) 연결'); const me = await this.lcuGet('/lol-summoner/v1/current-summoner'); if (me?.puuid) this.host.selfAccount(me.puuid, `${me.gameName}#${me.tagLine}`); + this.selfPuuid = me?.puuid ?? null; if (me?.gameName) this.selfRiotId = `${me.gameName}#${me.tagLine ?? ''}`; } } @@ -463,6 +499,7 @@ export class LolAdapter implements GameAdapter { this.queueName = q ? (lolModeKo(q.id) ?? q.description ?? null) : null; } if (phase === 'ChampSelect' || phase === 'InProgress' || phase === 'PreEndOfGame' || phase === 'EndOfGame') await this.pollLcuChat(phase); + this.history.maybeRun(Number(process.env.GVR_HISTORY_EVERY_MS) || 30 * 60000); } private async pollLcuChat(phase: string): Promise { diff --git a/app/src/core/games/manager.ts b/app/src/core/games/manager.ts index a0a5e7d..5168062 100644 --- a/app/src/core/games/manager.ts +++ b/app/src/core/games/manager.ts @@ -104,6 +104,22 @@ export class GameManager implements AdapterHost { this.emitMatch(m.id); } + /** Riot 경기 기록에서 가져온 경기 (상세는 바로 이어서 matchUpdated 로 채운다). 녹음 · STT 와는 상관없다 */ + historyMatch(m: MatchStart): void { + if (this.store.getMatch(m.id)) return; + this.store.upsertMatch({ + id: m.id, + game: m.game, + started_at: m.startedAt, + map: m.map ?? null, + mode: m.mode ?? null, + queue: m.queue ?? null, + detail: m.detail ? JSON.stringify(m.detail) : null, + status: 'pending_detail', + source: 'history', + }); + } + matchUpdated(id: string, patch: Partial, opts?: { complete?: boolean }): void { const cur = this.store.getMatch(id); if (!cur) return; @@ -183,6 +199,8 @@ export class GameManager implements AdapterHost { score: result.score, status: m.status as MatchSummary['status'], participants, + source: m.source === 'history' ? 'history' : 'live', + voice: !!this.store.db.prepare('SELECT 1 FROM utterances WHERE match_id=? AND (noise=0 OR corrected=1) LIMIT 1').get(m.id), }; } diff --git a/app/src/core/games/types.ts b/app/src/core/games/types.ts index ecc1faa..ca6b3f6 100644 --- a/app/src/core/games/types.ts +++ b/app/src/core/games/types.ts @@ -21,6 +21,8 @@ export interface AdapterHost { worker: WorkerClient; settings(): Settings; matchStarted(m: MatchStart): void; + /** Riot 경기 기록에서 가져온 경기 행 만들기 (이미 있으면 그대로) */ + historyMatch(m: MatchStart): void; /** 경기 정보 갱신 (상세가 채워졌을 때 등) */ matchUpdated(id: string, patch: Partial, opts?: { complete?: boolean }): void; matchEnded(id: string, endedAt: number): void; diff --git a/app/src/core/games/valorant.ts b/app/src/core/games/valorant.ts index 2d8bf2e..e57fd2b 100644 --- a/app/src/core/games/valorant.ts +++ b/app/src/core/games/valorant.ts @@ -5,6 +5,7 @@ import { logger } from '../util/log.js'; import type { GameAssets } from './assets.js'; import { basicAuth, readLockfile, request, riotClientLockfilePath, type Lockfile } from './riot.js'; import type { AdapterHost, GameAdapter } from './types.js'; +import { HistorySync } from './history.js'; const log = logger('valorant'); @@ -76,8 +77,51 @@ export class ValorantAdapter implements GameAdapter { private detailQueue = new Map(); private polling = false; private lastErr = ''; + /** 내 경기 기록 (앱이 꺼져 있을 때 한 경기도 경기 목록에) */ + readonly history: HistorySync; - constructor(private host: AdapterHost) {} + constructor(private host: AdapterHost) { + this.history = new HistorySync( + host.store, + { + game: 'valorant', + idle: () => { + const st = this.presence?.state; + return !!this.auth && !this.match && st !== 'INGAME' && st !== 'PREGAME'; + }, + account: () => this.auth?.puuid ?? null, + page: (start, n) => this.historyPage(start, n), + fetch: (id) => this.historyFetch(id), + }, + { pageSize: 20, max: Number(process.env.GVR_HISTORY_MAX) || 500, gapMs: Number(process.env.GVR_HISTORY_GAP_MS) || 1500 }, + ); + } + + private async historyPage(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'> { + const a = this.auth; + if (!a) return 'retry'; + const r = await request(`${this.pd(a)}/match-history/v1/history/${a.puuid}?startIndex=${start}&endIndex=${start + n}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 }); + if (r.status !== 200 || !Array.isArray(r.data?.History)) { + log.debug(`경기 기록 목록 실패 (${r.status})`); + return 'retry'; + } + return { ids: r.data.History.map((h: any) => `val-${h.MatchID}`), total: typeof r.data.Total === 'number' ? r.data.Total : null }; + } + + private async historyFetch(id: string): Promise<'ok' | 'gone' | 'retry'> { + const a = this.auth; + if (!a) return 'retry'; + const r = await request(`${this.pd(a)}/match-details/v1/matches/${id.replace(/^val-/, '')}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 }); + if (r.status === 404 || r.status === 400) return 'gone'; + if (r.status !== 200 || !r.data?.matchInfo) return 'retry'; + const md = r.data; + const S: number = md.matchInfo.gameStartMillis; + if (!S) return 'gone'; + this.host.historyMatch({ id, game: 'valorant', startedAt: S, map: md.matchInfo.mapId ?? null, mode: md.matchInfo.queueID ?? null, queue: md.matchInfo.queueID ?? null }); + await this.fillNames(a, md); + this.applyDetails(id, md, a.puuid, S); + return 'ok'; + } start(): void { if (this.timer) return; @@ -210,6 +254,7 @@ export class ValorantAdapter implements GameAdapter { if (a) { await this.pollPresence(a); if (this.match) await this.pollChat(a); + else this.history.maybeRun(Number(process.env.GVR_HISTORY_EVERY_MS) || 30 * 60000); } else { this.presence = null; // 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다 diff --git a/app/src/core/timeline.ts b/app/src/core/timeline.ts index 728a20f..3d45fc2 100644 --- a/app/src/core/timeline.ts +++ b/app/src/core/timeline.ts @@ -173,9 +173,15 @@ export class Timeline { if (q.match) { where.push('e.match_id = ?'); args.push(q.match); - } else if (q.game) { - where.push('e.game = ?'); - args.push(q.game); + } else { + if (q.game) { + where.push('e.game = ?'); + args.push(q.game); + } + // Riot 경기 기록에서 가져오기만 한 경기(앱이 녹음하지 않은 경기)의 킬 · 라운드는 타임라인에 넣지 않는다 (경기 화면에서는 보인다) + where.push( + `(e.match_id IS NULL OR e.match_id NOT IN (SELECT m.id FROM matches m WHERE m.source = 'history' AND NOT EXISTS (SELECT 1 FROM utterances x WHERE x.match_id = m.id)))`, + ); } if (q.users?.length) { // 선택하지 않은 (디스코드에 연결된) 유저가 주인공인 이벤트만 뺀다. 라운드·오브젝트·상대 킬처럼 유저가 없는 이벤트는 남긴다. diff --git a/app/test/games.test.ts b/app/test/games.test.ts index 225ad94..cdd571f 100644 --- a/app/test/games.test.ts +++ b/app/test/games.test.ts @@ -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 = { diff --git a/app/test/history.test.ts b/app/test/history.test.ts new file mode 100644 index 0000000..9dcac5e --- /dev/null +++ b/app/test/history.test.ts @@ -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]; + } +}); diff --git a/app/test/mock/riot.ts b/app/test/mock/riot.ts index e6cf70d..1049d96 100644 --- a/app/test/mock/riot.ts +++ b/app/test/mock/riot.ts @@ -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; diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index 6743b4f..e053693 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -165,6 +165,10 @@ export interface MatchSummary { score: { ally: number; enemy: number } | null; status: 'live' | 'pending_detail' | 'complete'; participants: string[]; + /** live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0 앱부터, 없으면 live) */ + source?: 'live' | 'history'; + /** 목소리가 녹음된 경기 (잡음 제외, v1.9.0 앱부터) */ + voice?: boolean; } export interface MatchPlayer {