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 는 빈 이름을 그대로 써서 "주인 계정 자동 연결: #" 이 남았다.