Riot ID 자동 갱신 (Riot 클라이언트에 붙으면 바로 · 10분마다 이름 서비스로 연결 계정의 지금 Riot ID 확인, puuid 는 그대로 두고 표시 이름만) · 경기 탭 데스매치 숨김 · 모드(GET /api/matches/modes) · 날짜(after) 필터 (예전 앱은 사이트가 거름) · 범인찾기 목록 데스매치 숨김 · 녹음 없거나 끊긴 경기도 범인찾기 (eligibility.notes, AI 자료에 안내 줄) · Riot 경기 기록 마지막 확인 시각(historyAt) 안내 · 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-21 07:14:07 +09:00
parent 8782df2111
commit 5e756f9eb8
21 changed files with 413 additions and 40 deletions

View File

@@ -6,6 +6,7 @@ import type { Culprit } from '../culprit.js';
import { normalizePhrase, type Store, type UserRow } from '../db/db.js';
import type { Dictionary } from '../dict/dictionary.js';
import type { GameManager } from '../games/manager.js';
import { HIDDEN_MODE } from '../games/modes.js';
import type { Settings } from '../settings.js';
import { safeJson, type Timeline, type TimelineQuery } from '../timeline.js';
import type { Bus } from '../util/events.js';
@@ -321,12 +322,18 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
.listMatches({
game: q.game || undefined,
before: q.before ? Number(q.before) : undefined,
after: q.after ? Number(q.after) : 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,
// 모드 필터 (v1.11.0, 모드 이름 "경쟁전" 등) · 데스매치는 늘 뺀다
onlyModes: q.mode ? d.games.modeKeys((name) => name === q.mode) : undefined,
skipModes: d.games.modeKeys((name) => name === HIDDEN_MODE),
})
.map((m) => d.games.summary(m));
});
// 모드 필터 목록 (v1.11.0): 모드 이름별 경기 수
app.get<{ Querystring: Record<string, string> }>('/api/matches/modes', async (req) => d.games.modeList(req.query.game || undefined));
app.get<{ Params: { id: string } }>('/api/matches/:id', async (req, reply): Promise<MatchDetail | void> => {
const m = store.getMatch(req.params.id);

View File

@@ -14,6 +14,7 @@ import type {
import { rateLol, rateValorant } from '@gvr/shared';
import type { EventRow, MatchRow, Store, UtteranceRow } from './db/db.js';
import type { GameManager } from './games/manager.js';
import { HIDDEN_MODE } from './games/modes.js';
import { safeJson, type Timeline } from './timeline.js';
/**
@@ -23,6 +24,7 @@ import { safeJson, type Timeline } from './timeline.js';
/** 녹음 공백 허용치: 경기 처음 · 끝 · 중간에 이보다 긴 빈 곳이 있으면 "기록 부족" */
export const COVERAGE_GAP_MS = 60000;
const NO_RECORDING = '녹음 기록이 없습니다';
/** 대화가 이보다 많으면 짧은 잡담부터 줄여서 보낸다 (경기당 비용 상한, 계획서 7장) */
export const MAX_UTTERANCES = 2500;
@@ -57,17 +59,22 @@ export class Culprit {
const players: any[] = det.players || [];
const gotResult = !det.live && players.length >= 2 && (m.game !== 'valorant' || (det.roundsDetail || []).length > 0);
if (!gotResult) reasons.push('경기 결과를 받지 못했습니다');
const start = realStart(m);
const end = m.ended_at;
const gap = this.coverageGap(start, end);
if (gap) reasons.push(gap);
// 녹음이 없거나 끊긴 경기도 분석한다 (v1.11.0, 앱을 켜지 않고 한 경기): 플레이 기록 · 채팅과 녹음된 대화만 쓴다
const notes = this.recordingNotes(m);
const pending = (
this.store.db.prepare(`SELECT count(*) n FROM utterances WHERE match_id=? AND status='pending' AND audio_deleted=0`).get(m.id) as { n: number }
).n;
if (reasons.length) return { state: 'blocked', reasons };
if (pending) return { state: 'pending', reasons: [`음성 변환 중 (${pending}문장 남음)`] };
if (this.current(m.id)) return { state: 'done', reasons: [] };
return { state: 'ready', reasons: [] };
if (pending) return { state: 'pending', reasons: [`음성 변환 중 (${pending}문장 남음)`], notes };
if (this.current(m.id)) return { state: 'done', reasons: [], notes };
return { state: 'ready', reasons: [], notes };
}
/** 녹음이 경기를 다 덮지 못하면 알림 문장 (분석은 그대로 한다) */
private recordingNotes(m: MatchRow): string[] {
const gap = m.ended_at ? this.coverageGap(realStart(m), m.ended_at) : null;
if (!gap) return [];
return [gap === NO_RECORDING ? '녹음 없음: 플레이 기록 · 채팅으로만 분석합니다' : `${gap}: 녹음된 대화만 씁니다`];
}
/** 녹음(봇이 음성채널에 있던 구간)이 경기를 덮는지. 빈 곳이 1분 넘으면 이유 문장, 아니면 null */
@@ -75,7 +82,7 @@ export class Culprit {
const sess = this.store.db
.prepare('SELECT started_at, ended_at FROM sessions WHERE started_at < ? AND (ended_at IS NULL OR ended_at > ?) ORDER BY started_at')
.all(end, start) as { started_at: number; ended_at: number | null }[];
if (!sess.length) return '녹음 기록이 없습니다';
if (!sess.length) return NO_RECORDING;
let cursor = start;
let worst: { at: number; ms: number } | null = null;
for (const s of sess) {
@@ -93,7 +100,9 @@ export class Culprit {
// ---------------------------------------------------------------- 목록 · 상세
list(opts: { game?: string; limit?: number }): CulpritMatchItem[] {
const rows = this.store.listMatches({ game: opts.game, limit: Math.min(opts.limit ?? 50, 200) }).filter((m) => m.status !== 'live');
const rows = this.store
.listMatches({ game: opts.game, limit: Math.min(opts.limit ?? 50, 200), skipModes: this.games.modeKeys((name) => name === HIDDEN_MODE) })
.filter((m) => m.status !== 'live');
return rows.map((m) => {
const cur = this.current(m.id);
const elig = this.eligibility(m);
@@ -219,6 +228,9 @@ export class Culprit {
out.push(`# 경기 리그 오브 레전드 ${sum.mode} · ${sum.map.name} · 킬 ${score} (${resultKo}) · ${minutes}분`);
}
if (basic) out.push('# 이 경기는 기본 기록만 있다 (피해량 · 첫킬 · 시야 같은 추가 지표 없음)');
const gap = m.ended_at ? this.coverageGap(realStart(m), m.ended_at) : null;
if (gap === NO_RECORDING) out.push('# 이 경기는 음성 녹음이 없다. 모두 음성X 로 보고 플레이 기록과 채팅으로만 평가한다');
else if (gap) out.push(`# ${gap}. 녹음이 빠진 구간의 대화는 없다`);
if (totalUtts > utts.length) out.push(`# 대화가 많아 ${totalUtts}문장 중 짧은 말을 빼고 ${utts.length}문장만 보냄`);
// 참가자

View File

@@ -38,6 +38,12 @@ export interface UtteranceRow {
attempts: number;
created_at: number;
}
/** 경기 모드를 가르는 칸 조합 (모드 이름은 games/modes.ts matchModeKo) */
export interface ModeKey {
game: string;
queue: string | null;
mode: string | null;
}
export interface MatchRow {
id: string;
game: 'valorant' | 'lol';
@@ -431,9 +437,35 @@ export class Store {
/**
* has: timeline = 타임라인에 나오는 경기 (앱이 잡은 경기 · 기록에서 가져왔어도 대화가 붙은 경기), voice = 목소리가 녹음된 경기
*/
listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[]; has?: 'timeline' | 'voice' }): MatchRow[] {
/**
* onlyModes = 이 (게임, 큐, 모드) 조합만 · skipModes = 이 조합은 빼고 (경기 탭 모드 필터 · 데스매치 숨기기, v1.11.0).
* after = 이 시각 이후에 시작한 경기만 (날짜 필터)
*/
listMatches(opts: {
game?: string;
before?: number;
after?: number;
limit?: number;
ids?: string[];
has?: 'timeline' | 'voice';
onlyModes?: ModeKey[];
skipModes?: ModeKey[];
}): MatchRow[] {
const where: string[] = [];
const args: any[] = [];
const modeCond = (keys: ModeKey[]) => {
args.push(...keys.flatMap((k) => [k.game, k.queue, k.mode]));
return `(${keys.map(() => '(game=? AND queue IS ? AND mode IS ?)').join(' OR ')})`;
};
if (opts.onlyModes) {
if (!opts.onlyModes.length) return [];
where.push(modeCond(opts.onlyModes));
}
if (opts.skipModes?.length) where.push(`NOT ${modeCond(opts.skipModes)}`);
if (opts.after) {
where.push('started_at>=?');
args.push(opts.after);
}
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})`);
@@ -454,6 +486,10 @@ export class Store {
.prepare(`SELECT * FROM matches ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY started_at DESC LIMIT ?`)
.all(...args, opts.limit ?? 50) as MatchRow[];
}
/** 경기 행의 (게임, 큐, 모드) 조합과 경기 수 */
matchModeRows(): (ModeKey & { n: number })[] {
return this.db.prepare('SELECT game, queue, mode, count(*) n FROM matches GROUP BY game, queue, mode').all() as (ModeKey & { n: number })[];
}
/** ts 시점에 진행 중이던 경기 */
matchAt(ts: number): MatchRow | undefined {
return this.db

View File

@@ -83,6 +83,14 @@ export class HistorySync {
return this.cancelled || !this.src.idle();
}
/** 마지막으로 끝까지 확인한 때 (사이트 경기 탭 안내, v1.11.0). 아직 없으면 null */
lastDoneAt(): number | null {
return Number(this.store.meta(this.lastKey())) || null;
}
private lastKey(): string {
return `history_last:${this.src.game}`;
}
private skipKey(): string {
return `history_skip:${this.src.game}`;
}
@@ -144,6 +152,7 @@ export class HistorySync {
if (this.cancelled) return added;
// 끝(또는 max)까지 다 받았다: 다음부터는 새 경기만 본다
this.store.setMeta(fullKey, '1');
this.store.setMeta(this.lastKey(), String(Date.now()));
if (this.store.meta(pendingKey)) this.store.setMeta(pendingKey, '');
if (added) log.info(`${this.src.game} 경기 기록: ${added}개 저장`);
return added;

View File

@@ -167,6 +167,7 @@ export class LolAdapter implements GameAdapter {
players: snap?.players ?? null,
error: this.lastErr || null,
history: this.history.progress(),
historyAt: this.history.lastDoneAt(),
updatedAt: Date.now(),
};
}

View File

@@ -1,5 +1,5 @@
import type { LiveGame, MatchSummary } from '@gvr/shared';
import type { EventRow, MatchRow, Store } from '../db/db.js';
import type { EventRow, MatchRow, ModeKey, Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { SttPipeline } from '../stt/pipeline.js';
import type { WorkerClient } from '../stt/worker.js';
@@ -11,7 +11,7 @@ import type { GameAssets } from './assets.js';
import { LolAdapter } from './lol.js';
import type { AdapterHost, GameAdapter, MatchStart } from './types.js';
import { ValorantAdapter } from './valorant.js';
import { lolModeKo, valModeKo } from './modes.js';
import { HIDDEN_MODE, matchModeKo } from './modes.js';
const log = logger('games');
@@ -199,6 +199,41 @@ export class GameManager implements AdapterHost {
}
}
renameAccounts(names: { puuid: string; riotId: string }[]): number {
let n = 0;
for (const x of names) {
if (!/^[^#]{1,32}#[^#]{1,8}$/.test(x.riotId)) continue;
const old = this.store.listAccounts().find((a) => a.puuid === x.puuid && a.riot_id !== x.riotId);
if (!old) continue;
n += this.store.db.prepare('UPDATE game_accounts SET riot_id=? WHERE puuid=? AND riot_id<>?').run(x.riotId, x.puuid, x.riotId).changes;
log.info(`Riot ID 바뀜: ${old.riot_id} → ${x.riotId}`);
}
if (n) this.bus.live({ type: 'users.updated', data: [] });
return n;
}
/** 모드 이름이 맞는 (게임, 큐, 모드) 조합 (경기 목록 모드 필터 · 데스매치 숨기기) */
modeKeys(pick: (name: string, game: string) => boolean): ModeKey[] {
return this.store
.matchModeRows()
.filter((r) => pick(matchModeKo(r), r.game))
.map(({ game, queue, mode }) => ({ game, queue, mode }));
}
/** 경기 탭 모드 필터 목록: 모드 이름별 경기 수, 많은 것부터. 데스매치는 경기 목록에 나오지 않아 뺀다 */
modeList(game?: string): { game: string; mode: string; count: number }[] {
const by = new Map<string, { game: string; mode: string; count: number }>();
for (const r of this.store.matchModeRows()) {
const mode = matchModeKo(r);
if (mode === HIDDEN_MODE || (game && r.game !== game)) continue;
const k = `${r.game}\n${mode}`;
const cur = by.get(k) ?? { game: r.game, mode, count: 0 };
cur.count += r.n;
by.set(k, cur);
}
return [...by.values()].sort((a, b) => b.count - a.count || a.mode.localeCompare(b.mode));
}
summary(m: MatchRow): MatchSummary {
const result = safeJson<{ win: boolean | null; score: { ally: number; enemy: number } | null }>(m.result, { win: null, score: null });
const map = m.game === 'valorant' ? this.assets.valMap(m.map) : null;
@@ -214,7 +249,7 @@ export class GameManager implements AdapterHost {
m.game === 'valorant'
? { id: m.map ?? '', name: map?.name ?? m.map ?? '?', image: map?.image ?? null }
: { id: m.map ?? 'Map11', name: '소환사의 협곡', image: this.assets.lolMapImage() },
mode: modeKo(m),
mode: matchModeKo(m),
win: result.win,
score: result.score,
status: m.status as MatchSummary['status'],
@@ -229,8 +264,3 @@ export class GameManager implements AdapterHost {
if (m) this.bus.live({ type: 'match.updated', data: this.summary(m) });
}
}
function modeKo(m: MatchRow): string {
const q = m.queue || m.mode || '';
return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드');
}

View File

@@ -32,3 +32,12 @@ export function lolModeKo(queue: string | number | null | undefined): string | n
export function valNoRounds(queue: string | null | undefined): boolean {
return ['deathmatch', 'hurm', 'ggteam', 'snowball'].includes((queue || '').toLowerCase());
}
/** 경기 목록 · 범인찾기 목록에 보이지 않는 모드 (연습용 데스매치, v1.11.0) */
export const HIDDEN_MODE = '데스매치';
/** 경기 행의 모드 이름 (경기 목록 · 모드 필터) */
export function matchModeKo(m: { game: string; queue: string | null; mode: string | null }): string {
const q = m.queue || m.mode || '';
return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드');
}

View File

@@ -35,6 +35,8 @@ export interface AdapterHost {
selfAccount(puuid: string, riotId: string): void;
/** 경기 참가자 Riot ID 로 디스코드 유저 연결 갱신 */
resolvePlayers(players: { puuid: string; riotId: string }[]): void;
/** Riot 이름 서비스가 알려 준 지금 Riot ID 로 연결된 계정 이름을 바꾼다 (닉네임 · 태그를 바꾼 사람). 바꾼 수 */
renameAccounts(names: { puuid: string; riotId: string }[]): number;
}
export interface GameAdapter {

View File

@@ -77,6 +77,8 @@ export class ValorantAdapter implements GameAdapter {
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
private polling = false;
private lastErr = '';
/** 연결된 계정 Riot ID 를 마지막으로 확인한 때 (닉네임 · 태그 바꾼 사람) */
private namesAt = 0;
/** 내 경기 기록 (앱이 꺼져 있을 때 한 경기도 경기 목록에) */
readonly history: HistorySync;
@@ -185,6 +187,7 @@ export class ValorantAdapter implements GameAdapter {
players: m?.players || null,
error: this.lastErr || null,
history: this.history.progress(),
historyAt: this.history.lastDoneAt(),
updatedAt: Date.now(),
};
}
@@ -255,7 +258,10 @@ 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.history.maybeRun(Number(process.env.GVR_HISTORY_EVERY_MS) || 30 * 60000);
await this.refreshNames(a);
}
} else {
this.presence = null;
// 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다
@@ -423,6 +429,25 @@ export class ValorantAdapter implements GameAdapter {
}
}
/**
* 디스코드 유저에 연결된 Riot 계정의 지금 Riot ID 를 이름 서비스로 확인한다 (Riot 클라이언트에 붙은 뒤 바로, 그 뒤 10분마다).
* 닉네임이나 태그를 바꾼 사람은 연결은 그대로(puuid) 두고 표시되는 Riot ID 만 새 이름으로 바꾼다.
* 아직 경기에서 만나지 못한 계정(riotid: 자리표시)은 puuid 를 몰라 물을 수 없다.
*/
private async refreshNames(a: Auth): Promise<void> {
if (Date.now() - this.namesAt < (Number(process.env.GVR_NAMES_EVERY_MS) || 10 * 60000)) return;
this.namesAt = Date.now();
const puuids = [...new Set(this.host.store.listAccounts().map((x) => x.puuid))].filter((p) => p && !p.startsWith('riotid:') && !p.includes('#'));
if (!puuids.length) return;
try {
const r = await request(`${this.pd(a)}/name-service/v2/players`, { method: 'PUT', headers: this.pvpHeaders(a), body: puuids, timeoutMs: 8000 });
if (r.status !== 200 || !Array.isArray(r.data)) return void log.debug(`Riot ID 확인 실패 (${r.status})`);
this.host.renameAccounts(r.data.filter((n: any) => n?.Subject && n.GameName && n.TagLine).map((n: any) => ({ puuid: n.Subject, riotId: `${n.GameName}#${n.TagLine}` })));
} catch (e) {
log.debug('Riot ID 확인 실패', e);
}
}
/**
* 경기 상세에 선수 이름이 비어 오면(Riot 이 이름을 가림) 이름 서비스로 채운다. 내 이름은 로컬 채팅 세션 값으로.
* v1.3.5 는 빈 이름을 그대로 써서 "주인 계정 자동 연결: #" 이 남았다.

View File

@@ -49,8 +49,9 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const m = ctx.store.getMatch(id)!;
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [] });
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [], notes: [] });
const input = ctx.culprit.buildInput(m);
assert.ok(!input.text.includes('녹음'), '녹음이 경기를 다 덮으면 녹음 안내 줄 없음');
const lines = input.text.split('\n');
assert.match(lines[0], /^# 경기 발로란트 .* 13:9 \(우리 팀 승리\) · 22라운드/);
// 우리 팀이 P1~P5, 하늘은 음성O, 디스코드 계정이 없는 상대는 음성X
@@ -88,16 +89,30 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
assert.ok(u2Index > lines.findIndex((l) => l.startsWith('[u1] ')));
});
test('범인찾기: 녹음이 늦게 시작 · 음성 변환 중 · 녹음 제외', () => {
test('범인찾기: 녹음이 늦게 시작 · 녹음 없음 · 음성 변환 중 · 녹음 제외', () => {
// 녹음이 끊긴 경기도 분석한다 (v1.11.0): 녹음된 대화만 쓰고 AI 에 알린다
const late = setup();
const a = seedValorant(late, { sessionStartOffsetMs: 17 * MIN });
const e = late.culprit.eligibility(late.store.getMatch(a.id)!);
assert.equal(e.state, 'blocked');
assert.deepEqual(e.reasons, ['녹음이 경기 시작 12분 뒤에 시작됐습니다']);
assert.deepEqual(e, { state: 'ready', reasons: [], notes: ['녹음이 경기 시작 12분 뒤에 시작됐습니다: 녹음된 대화만 씁니다'] });
assert.ok(late.culprit.buildInput(late.store.getMatch(a.id)!).text.includes('\n# 녹음이 경기 시작 12분 뒤에 시작됐습니다. 녹음이 빠진 구간의 대화는 없다\n'));
// 앱을 켜지 않고 한 경기 (녹음 · 대화 없음): 플레이 기록 · 채팅으로만
const none = setup();
const n = seedValorant(none);
none.store.db.prepare('DELETE FROM utterances').run();
none.store.db.prepare('DELETE FROM sessions').run();
const nm = none.store.getMatch(n.id)!;
assert.deepEqual(none.culprit.eligibility(nm), { state: 'ready', reasons: [], notes: ['녹음 없음: 플레이 기록 · 채팅으로만 분석합니다'] });
const ni = none.culprit.buildInput(nm);
assert.ok(ni.text.includes('\n# 이 경기는 음성 녹음이 없다. 모두 음성X 로 보고 플레이 기록과 채팅으로만 평가한다\n'));
assert.ok(ni.players.every((p) => !p.voice));
assert.equal(ni.stats.utterances, 0);
assert.ok(ni.stats.events > 0 && ni.stats.rounds > 0);
const pend = setup();
const b = seedValorant(pend, { pending: true });
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'] });
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'], notes: [] });
// 녹음 제외한 사람의 대화는 보내지 않는다
const ex = setup();

View File

@@ -27,6 +27,7 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
process.env.GVR_LOL_LIVE_URL = mock.base;
process.env.GVR_POLL_MS = '150';
process.env.GVR_DETAIL_RETRY_MS = '100';
process.env.GVR_NAMES_EVERY_MS = '200';
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');
@@ -89,6 +90,16 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
assert.deepEqual(sum.score, { ally: 2, enemy: 1 });
assert.equal(sum.win, true);
// ---- Riot ID 를 바꾼 사람: 연결(puuid)은 그대로, 표시되는 Riot ID 만 새 이름으로
store.upsertUser({ id: 'friend', name: '민수', avatar: null });
store.setAccounts('friend', [{ puuid: 'riotid:아직모름#KR1', riotId: '아직모름#KR1' }]);
const before = live.filter((e) => e.type === 'users.updated').length;
mock.st.names = { 'self-puuid-0001': ['새하늘', 'KR2'] };
await until(() => store.listAccounts().some((a) => a.puuid === 'self-puuid-0001' && a.riot_id === '새하늘#KR2'), 5000, 'rename');
assert.equal(store.userIdForPuuid('self-puuid-0001'), 'owner');
assert.ok(live.filter((e) => e.type === 'users.updated').length > before, '사이트에 유저 목록 다시 보냄');
assert.ok(store.listAccounts().some((a) => a.user_id === 'friend' && a.riot_id === '아직모름#KR1'), 'puuid 모르는 계정은 그대로');
// ---- 롤
mock.st.lolPhase = 'ChampSelect';
await until(() => (gm as any).adapters[1].pendingChat.length === 1, 5000, 'champ select chat');

View File

@@ -73,6 +73,8 @@ test('경기 기록: 발로란트 · 롤 기록을 가져와 history 경기로
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'));
// 사이트 경기 탭 안내: 마지막으로 끝까지 확인한 때
await until(() => gm.live().every((g) => typeof g.historyAt === 'number'), 5000, 'historyAt');
// 필터
const ids = (has?: 'timeline' | 'voice') => store.listMatches({ limit: 100, has }).map((m) => m.id).sort();
@@ -203,6 +205,7 @@ test('경기 기록: 진행 상황은 지금 게임 상태(games.state)로 나
// 롤만 가져오는 중
let lolRunning = true;
const fake = (game: 'valorant' | 'lol') => ({
lastDoneAt: () => null,
progress: () => (game === 'lol' && lolRunning ? { phase: 'fetch', first: true, scanned: 40, done: 10, total: 40, startedAt: Date.now() - 20000, etaMs: 60000 } : null),
cancel: () => {
if (game !== 'lol' || !lolRunning) return { cancelled: false, resumeAt: null };
@@ -329,3 +332,56 @@ test('경기 기록: 끝까지 훑은 계정에서 새 경기를 받다가 취
store.close();
}
});
test('경기 목록: 데스매치는 빼고, 모드 · 날짜로 거른다 · 모드 목록 (v1.11.0)', async () => {
const dir = tmp();
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 { Culprit } = await import('../src/core/culprit.ts');
const { Bus } = await import('../src/core/util/events.ts');
const { buildApi } = await import('../src/core/api/server.ts');
const { defaultSettings } = await import('../src/core/settings.ts');
const store = new Store(path.join(dir, 'db.sqlite'));
const bus = new Bus();
const s = defaultSettings();
const tl = new Timeline(store);
const gm = new GameManager(store, new GameAssets(path.join(dir, 'cache')), Object.assign(new EventEmitter(), { request: async () => ({}) }) as any, { setGameActive: async () => undefined } as any, tl, bus, () => s, () => null);
const DAY = 86400000;
const T = Date.UTC(2026, 10, 20, 12);
const add = (id: string, game: 'valorant' | 'lol', queue: string | null, at: number, mode: string | null = queue) =>
store.upsertMatch({ id, game, started_at: at, ended_at: at + 1800000, queue, mode, status: 'complete', source: 'history' });
add('val-comp1', 'valorant', 'competitive', T);
add('val-dm', 'valorant', 'deathmatch', T - 1000);
add('val-unr', 'valorant', 'unrated', T - DAY);
add('val-comp2', 'valorant', 'competitive', T - 3 * DAY);
add('val-prem', 'valorant', 'premier', T - 4 * DAY);
add('val-dm-live', 'valorant', '', T - 5 * DAY, 'deathmatch'); // 큐가 비고 모드 칸에만 있는 데스매치
add('lol-1', 'lol', '420', T - 2 * DAY, 'CLASSIC');
const app = await buildApi({ store, timeline: tl, games: gm, dict: {} as any, culprit: new Culprit(store, tl, gm), bus, settings: () => s, trainingDir: () => dir, overviewExtra: () => ({ guild: null, recording: {} as any }), version: 'test' });
const ids = async (qs: string) => (await app.inject({ url: `/api/matches${qs}` })).json().map((m: any) => m.id);
try {
assert.deepEqual(await ids(''), ['val-comp1', 'val-unr', 'lol-1', 'val-comp2', 'val-prem'], '데스매치는 목록에 없다');
assert.deepEqual(await ids('?mode=' + encodeURIComponent('경쟁전')), ['val-comp1', 'val-comp2']);
assert.deepEqual(await ids('?mode=' + encodeURIComponent('데스매치')), [], '데스매치는 모드로 골라도 나오지 않는다');
assert.deepEqual(await ids('?mode=' + encodeURIComponent('없는모드')), []);
// 날짜: after 이상 · before 미만 (사이트는 고른 날의 0시 · 다음 날 0시를 보낸다)
assert.deepEqual(await ids(`?after=${T - 3 * DAY}&before=${T}`), ['val-unr', 'lol-1', 'val-comp2']);
assert.deepEqual(await ids(`?game=valorant&mode=${encodeURIComponent('경쟁전')}&after=${T - DAY}`), ['val-comp1']);
const modes = (await app.inject({ url: '/api/matches/modes' })).json();
assert.deepEqual(modes, [
{ game: 'valorant', mode: '경쟁전', count: 2 },
{ game: 'lol', mode: '솔로 랭크', count: 1 },
{ game: 'valorant', mode: '일반전', count: 1 },
{ game: 'valorant', mode: '프리미어', count: 1 },
]);
assert.deepEqual((await app.inject({ url: '/api/matches/modes?game=lol' })).json(), [{ game: 'lol', mode: '솔로 랭크', count: 1 }]);
// 범인찾기 목록에도 데스매치는 없다
const cu = (await app.inject({ url: '/api/culprit/matches' })).json().map((x: any) => x.match.id);
assert.ok(cu.includes('val-comp1') && !cu.includes('val-dm') && !cu.includes('val-dm-live'));
} finally {
await app.close();
store.close();
}
});

View File

@@ -22,6 +22,8 @@ export interface MockState {
valHistory: { MatchID: string; GameStartTime: number }[];
/** 롤 경기 기록 (LCU, 새것부터) */
lolHistoryList: { gameId: number; gameCreation: number }[];
/** 이름 서비스: puuid → [이름, 태그] (Riot ID 를 바꾼 사람 흉내) */
names: Record<string, [string, string]>;
/** 요청 기록 (경로) */
hits: string[];
}
@@ -46,6 +48,7 @@ export async function startMockRiot(dir: string) {
lolStart: 0,
valHistory: [],
lolHistoryList: [],
names: {},
hits: [],
};
const password = 'pw-test';
@@ -95,6 +98,10 @@ export async function startMockRiot(dir: string) {
return auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}];
},
],
[
/^\/name-service\/v2\/players$/,
(_m, auth) => (auth.startsWith('Bearer ') ? [200, Object.entries(st.names).map(([Subject, [GameName, TagLine]]) => ({ Subject, GameName, TagLine }))] : [401, {}]),
],
// ---- LoL Live Client Data
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
// ---- LCU