From 5e756f9eb8573f93521cc26d4ad819cb2dd06eff Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sat, 21 Nov 2026 07:14:07 +0900 Subject: [PATCH] =?UTF-8?q?Riot=20ID=20=EC=9E=90=EB=8F=99=20=EA=B0=B1?= =?UTF-8?q?=EC=8B=A0=20(Riot=20=ED=81=B4=EB=9D=BC=EC=9D=B4=EC=96=B8?= =?UTF-8?q?=ED=8A=B8=EC=97=90=20=EB=B6=99=EC=9C=BC=EB=A9=B4=20=EB=B0=94?= =?UTF-8?q?=EB=A1=9C=20=C2=B7=2010=EB=B6=84=EB=A7=88=EB=8B=A4=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84=20=EC=84=9C=EB=B9=84=EC=8A=A4=EB=A1=9C=20=EC=97=B0?= =?UTF-8?q?=EA=B2=B0=20=EA=B3=84=EC=A0=95=EC=9D=98=20=EC=A7=80=EA=B8=88=20?= =?UTF-8?q?Riot=20ID=20=ED=99=95=EC=9D=B8,=20puuid=20=EB=8A=94=20=EA=B7=B8?= =?UTF-8?q?=EB=8C=80=EB=A1=9C=20=EB=91=90=EA=B3=A0=20=ED=91=9C=EC=8B=9C=20?= =?UTF-8?q?=EC=9D=B4=EB=A6=84=EB=A7=8C)=20=C2=B7=20=EA=B2=BD=EA=B8=B0=20?= =?UTF-8?q?=ED=83=AD=20=EB=8D=B0=EC=8A=A4=EB=A7=A4=EC=B9=98=20=EC=88=A8?= =?UTF-8?q?=EA=B9=80=20=C2=B7=20=EB=AA=A8=EB=93=9C(GET=20/api/matches/mode?= =?UTF-8?q?s)=20=C2=B7=20=EB=82=A0=EC=A7=9C(after)=20=ED=95=84=ED=84=B0=20?= =?UTF-8?q?(=EC=98=88=EC=A0=84=20=EC=95=B1=EC=9D=80=20=EC=82=AC=EC=9D=B4?= =?UTF-8?q?=ED=8A=B8=EA=B0=80=20=EA=B1=B0=EB=A6=84)=20=C2=B7=20=EB=B2=94?= =?UTF-8?q?=EC=9D=B8=EC=B0=BE=EA=B8=B0=20=EB=AA=A9=EB=A1=9D=20=EB=8D=B0?= =?UTF-8?q?=EC=8A=A4=EB=A7=A4=EC=B9=98=20=EC=88=A8=EA=B9=80=20=C2=B7=20?= =?UTF-8?q?=EB=85=B9=EC=9D=8C=20=EC=97=86=EA=B1=B0=EB=82=98=20=EB=81=8A?= =?UTF-8?q?=EA=B8=B4=20=EA=B2=BD=EA=B8=B0=EB=8F=84=20=EB=B2=94=EC=9D=B8?= =?UTF-8?q?=EC=B0=BE=EA=B8=B0=20(eligibility.notes,=20AI=20=EC=9E=90?= =?UTF-8?q?=EB=A3=8C=EC=97=90=20=EC=95=88=EB=82=B4=20=EC=A4=84)=20=C2=B7?= =?UTF-8?q?=20Riot=20=EA=B2=BD=EA=B8=B0=20=EA=B8=B0=EB=A1=9D=20=EB=A7=88?= =?UTF-8?q?=EC=A7=80=EB=A7=89=20=ED=99=95=EC=9D=B8=20=EC=8B=9C=EA=B0=81(hi?= =?UTF-8?q?storyAt)=20=EC=95=88=EB=82=B4=20=C2=B7=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/core/api/server.ts | 7 ++ app/src/core/culprit.ts | 30 +++++--- app/src/core/db/db.ts | 38 +++++++++- app/src/core/games/history.ts | 9 +++ app/src/core/games/lol.ts | 1 + app/src/core/games/manager.ts | 46 ++++++++++-- app/src/core/games/modes.ts | 9 +++ app/src/core/games/types.ts | 2 + app/src/core/games/valorant.ts | 27 ++++++- app/test/culprit.test.ts | 25 +++++-- app/test/games.test.ts | 11 +++ app/test/history.test.ts | 56 ++++++++++++++ app/test/mock/riot.ts | 7 ++ packages/shared/src/protocol.ts | 4 + site/web/mock/data.mjs | 2 +- site/web/mock/server.mjs | 23 +++++- site/web/src/components/HistoryImport.tsx | 29 ++++++++ site/web/src/lib/api.ts | 6 +- site/web/src/pages/CulpritPage.tsx | 8 +- site/web/src/pages/UserPages.tsx | 90 +++++++++++++++++++++-- site/web/src/styles.css | 23 ++++++ 21 files changed, 413 insertions(+), 40 deletions(-) diff --git a/app/src/core/api/server.ts b/app/src/core/api/server.ts index 023acf1..bccfecc 100644 --- a/app/src/core/api/server.ts +++ b/app/src/core/api/server.ts @@ -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 { .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 }>('/api/matches/modes', async (req) => d.games.modeList(req.query.game || undefined)); app.get<{ Params: { id: string } }>('/api/matches/:id', async (req, reply): Promise => { const m = store.getMatch(req.params.id); diff --git a/app/src/core/culprit.ts b/app/src/core/culprit.ts index 68fc8cf..463e907 100644 --- a/app/src/core/culprit.ts +++ b/app/src/core/culprit.ts @@ -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}문장만 보냄`); // 참가자 diff --git a/app/src/core/db/db.ts b/app/src/core/db/db.ts index a12f053..6476f28 100644 --- a/app/src/core/db/db.ts +++ b/app/src/core/db/db.ts @@ -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 diff --git a/app/src/core/games/history.ts b/app/src/core/games/history.ts index 8e1d4b4..a6809fc 100644 --- a/app/src/core/games/history.ts +++ b/app/src/core/games/history.ts @@ -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; diff --git a/app/src/core/games/lol.ts b/app/src/core/games/lol.ts index 94b3ff8..0052efc 100644 --- a/app/src/core/games/lol.ts +++ b/app/src/core/games/lol.ts @@ -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(), }; } diff --git a/app/src/core/games/manager.ts b/app/src/core/games/manager.ts index 13e4bd4..1832bd9 100644 --- a/app/src/core/games/manager.ts +++ b/app/src/core/games/manager.ts @@ -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(); + 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 ?? '리그 오브 레전드'); -} diff --git a/app/src/core/games/modes.ts b/app/src/core/games/modes.ts index a353d04..86b4ee9 100644 --- a/app/src/core/games/modes.ts +++ b/app/src/core/games/modes.ts @@ -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 ?? '리그 오브 레전드'); +} diff --git a/app/src/core/games/types.ts b/app/src/core/games/types.ts index e4bb06a..2ad8f4b 100644 --- a/app/src/core/games/types.ts +++ b/app/src/core/games/types.ts @@ -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 { diff --git a/app/src/core/games/valorant.ts b/app/src/core/games/valorant.ts index 2a3496a..7524050 100644 --- a/app/src/core/games/valorant.ts +++ b/app/src/core/games/valorant.ts @@ -77,6 +77,8 @@ export class ValorantAdapter implements GameAdapter { private detailQueue = new Map(); 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 { + 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 는 빈 이름을 그대로 써서 "주인 계정 자동 연결: #" 이 남았다. diff --git a/app/test/culprit.test.ts b/app/test/culprit.test.ts index 736cdea..a2e5e52 100644 --- a/app/test/culprit.test.ts +++ b/app/test/culprit.test.ts @@ -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(); diff --git a/app/test/games.test.ts b/app/test/games.test.ts index cdd571f..faecaef 100644 --- a/app/test/games.test.ts +++ b/app/test/games.test.ts @@ -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'); diff --git a/app/test/history.test.ts b/app/test/history.test.ts index b81d4c7..c540f3a 100644 --- a/app/test/history.test.ts +++ b/app/test/history.test.ts @@ -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(); + } +}); diff --git a/app/test/mock/riot.ts b/app/test/mock/riot.ts index 1049d96..1e9fc3c 100644 --- a/app/test/mock/riot.ts +++ b/app/test/mock/riot.ts @@ -22,6 +22,8 @@ export interface MockState { valHistory: { MatchID: string; GameStartTime: number }[]; /** 롤 경기 기록 (LCU, 새것부터) */ lolHistoryList: { gameId: number; gameCreation: number }[]; + /** 이름 서비스: puuid → [이름, 태그] (Riot ID 를 바꾼 사람 흉내) */ + names: Record; /** 요청 기록 (경로) */ 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 diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index efb0588..7bfd24b 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -281,6 +281,8 @@ export interface LiveGame { error: string | null; /** Riot 경기 기록 가져오는 중이면 진행 상황 (v1.9.1~, 예전 앱은 없음) */ history?: HistoryProgress | null; + /** Riot 경기 기록을 마지막으로 끝까지 확인한 때 (v1.11.0~, 아직 한 번도 못 했으면 null) */ + historyAt?: number | null; updatedAt: number; } @@ -356,6 +358,8 @@ export interface UserProfile { export interface CulpritEligibility { state: 'ready' | 'done' | 'pending' | 'blocked'; reasons: string[]; + /** 분석은 되지만 알려 둘 것 (녹음 없음 · 녹음이 끊김, v1.11.0 앱부터) */ + notes?: string[]; } export interface CulpritPlayer { /** P1~P10 (우리 팀 먼저) */ diff --git a/site/web/mock/data.mjs b/site/web/mock/data.mjs index dd37855..ab9bd66 100644 --- a/site/web/mock/data.mjs +++ b/site/web/mock/data.mjs @@ -595,7 +595,7 @@ if (process.env.GVR_MOCK_REPLAY) genReplayDemo(process.env.GVR_MOCK_REPLAY); startedAt: start, endedAt: start + 38 * MIN, map: { ...base.map, name: MAPS[i % MAPS.length] }, - mode: i % 4 === 0 ? '일반전' : '경쟁전', + mode: i % 7 === 3 ? '데스매치' : i % 4 === 0 ? '일반전' : '경쟁전', win, score: win ? { ally, enemy } : { ally: enemy, enemy: ally }, status: 'complete', diff --git a/site/web/mock/server.mjs b/site/web/mock/server.mjs index e22eb65..ce0e465 100644 --- a/site/web/mock/server.mjs +++ b/site/web/mock/server.mjs @@ -52,8 +52,8 @@ const histProgress = () => { return { phase: 'fetch', first: true, scanned: 200, done, total: h.total, startedAt: h.startedAt, etaMs: done ? (h.total - done) * 1500 : null }; }; const liveGames = () => [ - { game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, startedAt: Date.now() - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, updatedAt: Date.now() }, - { game: 'lol', enabled: true, connected: !!state.hist, phase: state.hist ? '로비' : '롤 클라이언트 꺼짐', inMatch: false, matchId: null, mode: null, map: null, mapImage: null, startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: null, players: null, error: null, history: histProgress(), updatedAt: Date.now() }, + { game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, startedAt: Date.now() - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, historyAt: Date.now() - 12 * 60000, updatedAt: Date.now() }, + { game: 'lol', enabled: true, connected: !!state.hist, phase: state.hist ? '로비' : '롤 클라이언트 꺼짐', inMatch: false, matchId: null, mode: null, map: null, mapImage: null, startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: null, players: null, error: null, history: histProgress(), historyAt: null, updatedAt: Date.now() }, ]; const json = (res, status, body, headers = {}) => { @@ -358,9 +358,26 @@ async function handle(req, res) { const limit = Number(q.get('limit') ?? 20); const has = q.get('has'); const keep = (x) => (has === 'voice' ? x.utterances.length > 0 : has === 'timeline' ? x.source !== 'history' || x.utterances.length > 0 : true); - const list = db.matches.filter((x) => (!game || x.game === game) && x.startedAt < before && keep(x)).sort((a, b) => b.startedAt - a.startedAt).slice(0, limit).map(summary); + // 모드 · 날짜 필터, 데스매치는 늘 뺀다 (v1.11.0 앱과 같게) + const mode = q.get('mode'); + const after = q.get('after') ? Number(q.get('after')) : 0; + const list = db.matches + .filter((x) => (!game || x.game === game) && x.startedAt < before && x.startedAt >= after && keep(x) && x.mode !== '데스매치' && (!mode || x.mode === mode)) + .sort((a, b) => b.startedAt - a.startedAt) + .slice(0, limit) + .map(summary); return json(res, 200, list); } + if (p === '/api/matches/modes') { + const game = q.get('game'); + const by = new Map(); + for (const x of db.matches) { + if (x.mode === '데스매치' || (game && x.game !== game)) continue; + const k = `${x.game}\n${x.mode}`; + by.set(k, { game: x.game, mode: x.mode, count: (by.get(k)?.count ?? 0) + 1 }); + } + return json(res, 200, [...by.values()].sort((a, b) => b.count - a.count)); + } if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) { const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1])); if (!mt) return json(res, 404, { error: 'not_found' }); diff --git a/site/web/src/components/HistoryImport.tsx b/site/web/src/components/HistoryImport.tsx index 4c1baef..fb3deec 100644 --- a/site/web/src/components/HistoryImport.tsx +++ b/site/web/src/components/HistoryImport.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from 'react'; import { GAME_NAME, historyStatus, resumeText, type GameType } from '@gvr/shared'; import { api } from '../lib/api'; +import { fmtWhen } from '../lib/format'; import { useData } from '../store/app'; /** @@ -69,3 +70,31 @@ export function HistoryImport({ onDone }: { onDone: () => void }) { ); } + +/** + * Riot 경기 기록을 언제 확인했는지 (v1.11.0 앱부터, 경기 탭). 앱이 꺼져 있던 때 한 경기는 이 PC 에서 Riot 클라이언트에 + * 로그인해 있어야 가져올 수 있어서, 아직 못 가져왔으면 그 방법을 알려 준다. 가져오는 중이면 위 진행 바가 대신 보인다. + */ +export function HistoryHint() { + const { overview } = useData(); + const rows = (overview?.live ?? []).filter((g) => g.enabled && !g.history && g.historyAt !== undefined); + if (!rows.length) return null; + return ( +
+ {rows.map((g) => { + const client = g.game === 'valorant' ? 'Riot 클라이언트' : '롤 클라이언트'; + const text = + g.historyAt != null + ? `Riot 경기 기록 ${fmtWhen(g.historyAt)} 확인${g.connected ? ' · 30분마다 새 경기를 가져옵니다' : ` · ${client}를 켜면 그사이 한 경기를 가져옵니다`}` + : g.connected + ? '앱이 꺼져 있던 때 한 경기를 곧 가져옵니다' + : `앱이 꺼져 있던 때 한 경기는 아직 못 가져왔습니다. 이 PC 에서 ${client}에 로그인해 두면 자동으로 가져옵니다`; + return ( +
+ {GAME_NAME[g.game]} {text} +
+ ); + })} +
+ ); +} diff --git a/site/web/src/lib/api.ts b/site/web/src/lib/api.ts index 885ae2d..21f3222 100644 --- a/site/web/src/lib/api.ts +++ b/site/web/src/lib/api.ts @@ -166,7 +166,11 @@ export const api = { })}`, ), // has: timeline = 타임라인에 나오는 경기, voice = 목소리가 녹음된 경기 (v1.9.0 앱부터, 예전 앱은 무시하고 다 보냄) - matches: (o: { game?: GameType; limit?: number; before?: number; has?: MatchHas } = {}) => request(`/api/matches${qs(o)}`), + // mode · after (v1.11.0 앱부터): 모드 이름("경쟁전") · 이 시각 이후 시작한 경기. 데스매치는 앱이 늘 뺀다 (예전 앱은 사이트가 거름) + matches: (o: { game?: GameType; limit?: number; before?: number; after?: number; has?: MatchHas; mode?: string } = {}) => + request(`/api/matches${qs(o)}`), + /** 경기 탭 모드 필터 목록 (v1.11.0 앱부터, 예전 앱은 404) */ + matchModes: (game?: GameType) => request<{ game: GameType; mode: string; count: number }[]>(`/api/matches/modes${qs({ game })}`), match: (id: string) => request(`/api/matches/${encodeURIComponent(id)}`), /** 발로란트 리플레이(.vrf)에서 뽑은 재생 데이터. 없으면 404 replay_not_found, 게임 PC 가 변환 중이면 202 { status: 'converting' } */ // fresh: 새로고침 때는 브라우저 캐시를 거치지 않는다 (방금 내려받은 리플레이가 보이게) diff --git a/site/web/src/pages/CulpritPage.tsx b/site/web/src/pages/CulpritPage.tsx index 43db941..5190132 100644 --- a/site/web/src/pages/CulpritPage.tsx +++ b/site/web/src/pages/CulpritPage.tsx @@ -188,7 +188,7 @@ function MatchRow({ x, on, running, onClick }: { x: CulpritMatchItem; on: boolea {m.mode} · {fmtWhen(m.startedAt)} {m.endedAt ? ` · ${fmtDuration(m.endedAt - m.startedAt)}` : ''} - {x.eligibility.reasons[0] ? ` · ${x.eligibility.reasons[0]}` : ''} + {x.eligibility.reasons[0] ? ` · ${x.eligibility.reasons[0]}` : x.eligibility.notes?.[0] ? ` · ${x.eligibility.notes[0].split(':')[0]}` : ''} {score} @@ -236,7 +236,8 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM [true, m.game === 'valorant' ? '킬 · 스파이크 · 라운드 결과 이벤트' : '킬 · 오브젝트 이벤트', `${s.events}개`], [e.state !== 'pending' || !e.reasons[0]?.startsWith('음성 변환'), '음성 대화 (텍스트 변환 완료)', `${s.utterances}문장`], [true, '인게임 채팅 (팀 · 전체)', `${s.chats}개`], - [!e.reasons.some((r) => r.startsWith('녹음')), '녹음이 경기 시작부터 끝까지 이어짐', ''], + // 녹음이 없거나 끊겨도 분석은 된다 (v1.11.0 앱): 빠진 것만 ✕ 로 보이고 아래 안내를 단다 + [!e.reasons.some((r) => r.startsWith('녹음')) && !e.notes?.length, '녹음이 경기 시작부터 끝까지 이어짐', e.notes?.length ? '없어도 분석 가능' : ''], ]; return ( <> @@ -261,7 +262,7 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM

분석에 쓰는 기록 - {e.state === 'ready' || e.state === 'done' ? '모두 있음' : STATE_LABEL[e.state]} + {e.state === 'ready' || e.state === 'done' ? (e.notes?.length ? '분석 가능' : '모두 있음') : STATE_LABEL[e.state]}

{checks.map(([ok, label, val]) => (
@@ -272,6 +273,7 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM ))} {!s.extraStats &&
이 경기는 피해량 · 시야 같은 추가 지표가 없어 기본 기록으로 분석합니다.
} {e.reasons.length > 0 &&
{e.reasons.join(' · ')}
} + {!!e.notes?.length &&
{e.notes.join(' · ')}
}
음성 파일은 7일 뒤 지워져도 괜찮습니다. 분석은 텍스트로 합니다.
diff --git a/site/web/src/pages/UserPages.tsx b/site/web/src/pages/UserPages.tsx index 5519633..8285914 100644 --- a/site/web/src/pages/UserPages.tsx +++ b/site/web/src/pages/UserPages.tsx @@ -3,11 +3,11 @@ import { Link, useNavigate, useParams } from 'react-router'; import type { GameType, MatchSummary, User, UserProfile } from '@gvr/shared'; import { api, type MatchHas } from '../lib/api'; import { useStatus } from '../store/app'; -import { fmtDuration, fmtDay } from '../lib/format'; +import { dateInputToMs, dateInputValue, fmtDuration, fmtDay } from '../lib/format'; import { sfx } from '../lib/sfx'; import { Avatar, ErrorBox, Spinner } from '../components/common'; import { MatchItem } from './Sidebar'; -import { HistoryImport } from '../components/HistoryImport'; +import { HistoryHint, HistoryImport } from '../components/HistoryImport'; function useLoad(fn: () => Promise, deps: unknown[]) { const { epoch } = useStatus(); @@ -60,11 +60,41 @@ const HAS_CHIPS: { has: MatchHas | null; label: string; title: string }[] = [ { has: 'voice', label: '목소리 녹음된 경기', title: '디스코드 대화가 녹음된 경기' }, ]; +/** 경기 목록에 보이지 않는 모드 (예전 앱은 다 보내서 여기서도 거른다) */ +const HIDDEN_MODE = '데스매치'; + export function MatchesPage() { - const [game, setGame] = useState(null); + const [game, setGameRaw] = useState(null); const [has, setHas] = useState(null); + const [mode, setMode] = useState(null); + // 날짜 (한국 시각): from = 시작 날 0시, to = 끝 날 23:59:59.999 + const [from, setFrom] = useState(undefined); + const [to, setTo] = useState(undefined); + // 게임을 바꾸면 그 게임에 없을 수 있는 모드는 풀어 준다 + const setGame = (g: GameType | null) => { + setGameRaw(g); + setMode(null); + }; const nav = useNavigate(); - const { data, err, retry } = useLoad(() => api.matches({ limit: PAGE, game: game ?? undefined, has: has ?? undefined }), [game, has]); + const query = { limit: PAGE, game: game ?? undefined, has: has ?? undefined, mode: mode ?? undefined, after: from, before: to === undefined ? undefined : to + 1 }; + const { data, err, retry } = useLoad(() => api.matches(query), [game, has, mode, from, to]); + // 모드 목록: 예전 앱(404)은 불러온 경기에서 만든다 + const [modeList, setModeList] = useState<{ mode: string; count: number | null }[] | null>(null); + useEffect(() => { + let alive = true; + api + .matchModes(game ?? undefined) + .then((r) => { + if (!alive) return; + const by = new Map(); + for (const x of r) by.set(x.mode, (by.get(x.mode) ?? 0) + x.count); + setModeList([...by].map(([m, count]) => ({ mode: m, count }))); + }) + .catch(() => alive && setModeList(null)); + return () => { + alive = false; + }; + }, [game, data]); // 더 보기: 지난 쪽 경기들 (필터가 바뀌면 처음부터) const [more, setMore] = useState<{ list: MatchSummary[]; done: boolean; busy: boolean; err: unknown }>({ list: [], done: false, busy: false, err: null }); useEffect(() => setMore({ list: [], done: false, busy: false, err: null }), [data]); @@ -74,22 +104,30 @@ export function MatchesPage() { for (const m of [...(data ?? []), ...more.list]) { if (seen.has(m.id)) continue; seen.add(m.id); - // 예전 앱은 has 를 모르고 다 보낸다: 목소리 필터는 여기서도 거른다 + // 예전 앱은 has · 모드 · 날짜를 모르고 다 보낸다: 여기서도 거른다 if (has === 'voice' && !hasVoice(m)) continue; + if (m.mode === HIDDEN_MODE || (mode && m.mode !== mode)) continue; + if ((from !== undefined && m.startedAt < from) || (to !== undefined && m.startedAt > to)) continue; out.push(m); } return out; - }, [data, more.list, has]); + }, [data, more.list, has, mode, from, to]); + const modes = useMemo(() => { + if (modeList) return modeList; + const seen = [...new Set([...(data ?? []), ...more.list].filter((m) => !game || m.game === game).map((m) => m.mode))]; + return seen.filter((m) => m !== HIDDEN_MODE).map((m) => ({ mode: m, count: null })); + }, [modeList, data, more.list, game]); const canMore = !!data && data.length >= PAGE && !more.done; const loadMore = () => { const last = more.list[more.list.length - 1] ?? data?.[data.length - 1]; if (!last || more.busy) return; setMore((s) => ({ ...s, busy: true, err: null })); api - .matches({ limit: PAGE, game: game ?? undefined, has: has ?? undefined, before: last.startedAt }) + .matches({ ...query, before: last.startedAt }) .then((r) => setMore((s) => ({ list: [...s.list, ...r], done: r.length < PAGE, busy: false, err: null }))) .catch((e) => setMore((s) => ({ ...s, busy: false, err: e }))); }; + const filtered = !!mode || from !== undefined || to !== undefined; const groups = useMemo(() => { const g = new Map(); for (const m of all) { @@ -121,12 +159,48 @@ export function MatchesPage() { ))} +
+ +
+ setFrom(dateInputToMs(e.target.value))} aria-label="시작 날짜" /> + ~ + setTo(dateInputToMs(e.target.value, true))} aria-label="끝 날짜" /> +
+ {filtered && ( + + )} +
+ {err != null && } {!data && !err && } {data && all.length === 0 && (
- {has === 'voice' ? '목소리가 녹음된 경기가 없습니다.' : has === 'timeline' ? '타임라인이 있는 경기가 없습니다.' : '경기 기록이 없습니다.'} + {filtered + ? '고른 모드 · 날짜에 맞는 경기가 없습니다.' + : has === 'voice' + ? '목소리가 녹음된 경기가 없습니다.' + : has === 'timeline' + ? '타임라인이 있는 경기가 없습니다.' + : '경기 기록이 없습니다.'}
)} {groups.map(([day, ms]) => ( diff --git a/site/web/src/styles.css b/site/web/src/styles.css index 0a6fc3a..ce3b0f8 100644 --- a/site/web/src/styles.css +++ b/site/web/src/styles.css @@ -2740,6 +2740,29 @@ button.match:hover { .match-has { margin: 4px 0 2px; } +.match-filters { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 10px; + margin: 8px 0 2px; +} +.mf-sel { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 7px; + padding: 6px 8px; + font-size: 12.5px; + color: #c6d1dc; +} +.mf-dates input { + flex: none; + width: 140px; +} +.hist-hint { + margin: 8px 0 2px; + line-height: 1.6; +} .m-tags { display: flex; gap: 4px;