From 63d0e43196e28621e9e28cc6a685d33a5c06f413 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Wed, 4 Nov 2026 09:54:09 +0900 Subject: [PATCH] =?UTF-8?q?=EA=B2=BD=EA=B8=B0=20=EA=B8=B0=EB=A1=9D=20?= =?UTF-8?q?=EA=B0=80=EC=A0=B8=EC=98=A4=EA=B8=B0=20=EC=A7=84=ED=96=89=20?= =?UTF-8?q?=EB=B0=94=20=C2=B7=20=EC=B7=A8=EC=86=8C:=20Riot=20=EA=B2=BD?= =?UTF-8?q?=EA=B8=B0=20=EA=B8=B0=EB=A1=9D=EC=9D=84=20=EA=B0=80=EC=A0=B8?= =?UTF-8?q?=EC=98=A4=EB=8A=94=20=EB=8F=99=EC=95=88=20=EC=82=AC=EC=9D=B4?= =?UTF-8?q?=ED=8A=B8=20=EA=B2=BD=EA=B8=B0=20=ED=83=AD=20=C2=B7=20=EC=95=B1?= =?UTF-8?q?=20=EA=B2=8C=EC=9E=84=20=EC=97=B0=EB=8F=99=20=ED=83=AD=EC=97=90?= =?UTF-8?q?=20=EB=AA=A9=EB=A1=9D=20=ED=99=95=EC=9D=B8=20=EC=A4=91(?= =?UTF-8?q?=EC=96=BC=EB=A7=88=EB=82=98=20=EA=B1=B8=EB=A6=B4=EC=A7=80=20?= =?UTF-8?q?=EB=AA=A8=EB=A6=84)=20=E2=86=92=20=EB=B0=9B=EC=9D=80=20?= =?UTF-8?q?=EA=B2=BD=EA=B8=B0=20/=20=EB=B0=9B=EC=9D=84=20=EA=B2=BD?= =?UTF-8?q?=EA=B8=B0=20=C2=B7=20%=20=C2=B7=20=EB=82=A8=EC=9D=80=20?= =?UTF-8?q?=EC=8B=9C=EA=B0=84=20=EC=A7=84=ED=96=89=20=EB=B0=94=EC=99=80=20?= =?UTF-8?q?=EC=B7=A8=EC=86=8C=20=EB=B2=84=ED=8A=BC=20(=EC=B7=A8=EC=86=8C?= =?UTF-8?q?=ED=95=98=EB=A9=B4=20=EB=B0=9B=EC=9D=80=20=EA=B2=BD=EA=B8=B0?= =?UTF-8?q?=EB=8A=94=20=EB=82=A8=EA=B3=A0=20=EB=8B=A4=EC=9D=8C=20=EC=A3=BC?= =?UTF-8?q?=EA=B8=B0=EC=97=90=20=EB=82=A8=EC=9D=80=20=EA=B2=83=EB=B6=80?= =?UTF-8?q?=ED=84=B0=20=EC=9D=B4=EC=96=B4=EC=84=9C)=20=C2=B7=20=EC=A7=84?= =?UTF-8?q?=ED=96=89=20=EC=83=81=ED=99=A9=EC=9D=80=20games.state=20?= =?UTF-8?q?=EC=9D=98=20history=20=EB=A1=9C=20=EB=B3=B4=EB=83=84=20=C2=B7?= =?UTF-8?q?=20POST=20/api/games/history/cancel=20=C2=B7=20=EB=81=9D?= =?UTF-8?q?=EB=82=98=EB=A9=B4=20=EA=B2=BD=EA=B8=B0=20=EB=AA=A9=EB=A1=9D=20?= =?UTF-8?q?=EC=83=88=EB=A1=9C=20=C2=B7=20=EB=AA=A9=EB=A1=9D=20=EB=B6=88?= =?UTF-8?q?=EB=9F=AC=EC=98=A4=EB=8A=94=20=EC=A4=91=20=ED=91=9C=EC=8B=9C=20?= =?UTF-8?q?=C2=B7=20schema.ts=20=EC=82=AC=EB=B3=B8=20=EB=8B=A4=EC=8B=9C=20?= =?UTF-8?q?=EB=A7=9E=EC=B6=A4?= 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 | 8 ++ app/src/core/db/schema.ts | 2 +- app/src/core/games/history.ts | 52 ++++++++- app/src/core/games/lol.ts | 1 + app/src/core/games/manager.ts | 20 ++++ app/src/core/games/types.ts | 3 + app/src/core/games/valorant.ts | 1 + app/src/main/api-types.ts | 2 + app/src/main/ipc.ts | 1 + app/src/main/preload.ts | 2 +- app/src/renderer/mock-gvr.ts | 15 ++- app/src/renderer/styles.css | 4 + app/src/renderer/tabs/GamesTab.tsx | 41 ++++++- app/test/history.test.ts | 136 ++++++++++++++++++++++ packages/shared/src/live-game.ts | 24 +++- packages/shared/src/protocol.ts | 19 +++ site/web/mock/server.mjs | 33 +++++- site/web/src/components/HistoryImport.tsx | 71 +++++++++++ site/web/src/lib/api.ts | 3 + site/web/src/pages/UserPages.tsx | 4 +- site/web/src/styles.css | 80 +++++++++++++ 21 files changed, 507 insertions(+), 15 deletions(-) create mode 100644 site/web/src/components/HistoryImport.tsx diff --git a/app/src/core/api/server.ts b/app/src/core/api/server.ts index df8ebed..023acf1 100644 --- a/app/src/core/api/server.ts +++ b/app/src/core/api/server.ts @@ -120,6 +120,14 @@ export async function buildApi(d: ApiDeps): Promise { return { user: toUser(u, store.listAccounts()), stats: { talkMs: st.ms, count: st.n, topWords }, matches }; }); + // Riot 경기 기록 가져오기 취소 (v1.9.1, 사이트 경기 탭 진행 바). 받은 경기는 그대로 두고 다음 주기(30분 뒤)에 이어서 한다 + app.post<{ Body: { game?: string } }>('/api/games/history/cancel', async (req) => { + const g = req.body?.game; + const r = d.games.cancelHistory(g === 'valorant' || g === 'lol' ? g : undefined); + if (r.cancelled.length) log.info(`경기 기록 가져오기 취소 (${r.cancelled.join(', ')}) · ${req.headers['x-gvr-user'] ? '사이트' : '이 PC'}`); + return { ok: true, ...r }; + }); + // 유저 설정 (v1.6.0, 사이트 "내 정보" · 관리 화면): 색 · 녹음 제외 · 라이엇 ID. 본인 또는 관리자만 app.patch<{ Params: { id: string }; Body: { color?: string; excluded?: boolean; riotIds?: string[] } }>('/api/users/:id', async (req, reply) => { const u = store.getUser(req.params.id); diff --git a/app/src/core/db/schema.ts b/app/src/core/db/schema.ts index 658e3bd..abf9755 100644 --- a/app/src/core/db/schema.ts +++ b/app/src/core/db/schema.ts @@ -1,2 +1,2 @@ // 자동 생성: schema.sql 사본 (npm run build 가 다시 만든다) -export const SCHEMA_SQL = "PRAGMA journal_mode = WAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);\n\nCREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n color TEXT NOT NULL,\n avatar TEXT,\n excluded INTEGER NOT NULL DEFAULT 0,\n gain_lufs REAL,\n gain_n INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS game_accounts (\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n puuid TEXT NOT NULL,\n riot_id TEXT NOT NULL,\n PRIMARY KEY (user_id, puuid)\n);\nCREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);\n\nCREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n guild_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n channel_name TEXT,\n started_at INTEGER NOT NULL,\n ended_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS utterances (\n id TEXT PRIMARY KEY,\n session_id TEXT,\n user_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n audio_path TEXT,\n audio_deleted INTEGER NOT NULL DEFAULT 0,\n text TEXT,\n raw_text TEXT,\n words TEXT NOT NULL DEFAULT '[]',\n noise INTEGER NOT NULL DEFAULT 0,\n noise_reason TEXT,\n confidence REAL,\n lufs REAL,\n gain_db REAL NOT NULL DEFAULT 0,\n model TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n match_id TEXT,\n corrected INTEGER NOT NULL DEFAULT 0,\n attempts INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);\nCREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');\nCREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\n\nCREATE TABLE IF NOT EXISTS matches (\n id TEXT PRIMARY KEY,\n game TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER,\n map TEXT,\n mode TEXT,\n queue TEXT,\n result TEXT,\n detail TEXT,\n status TEXT NOT NULL DEFAULT 'live',\n clock_offset INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);\n\nCREATE TABLE IF NOT EXISTS rounds (\n match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,\n num INTEGER NOT NULL,\n started_at INTEGER NOT NULL,\n combat_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n win INTEGER,\n result TEXT,\n ally_score INTEGER,\n enemy_score INTEGER,\n economy TEXT,\n PRIMARY KEY (match_id, num)\n);\n\nCREATE TABLE IF NOT EXISTS game_events (\n id TEXT PRIMARY KEY,\n match_id TEXT NOT NULL,\n game TEXT NOT NULL,\n type TEXT NOT NULL,\n ts INTEGER NOT NULL,\n game_time_ms INTEGER,\n round INTEGER,\n actor_puuid TEXT,\n target_puuid TEXT,\n data TEXT NOT NULL DEFAULT '{}'\n);\nCREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);\nCREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);\n\nCREATE TABLE IF NOT EXISTS dictionary (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n word TEXT NOT NULL,\n pack TEXT NOT NULL,\n kind TEXT NOT NULL,\n from_text TEXT NOT NULL DEFAULT '',\n source TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n UNIQUE (kind, word, from_text, pack)\n);\n\nCREATE TABLE IF NOT EXISTS training_samples (\n id TEXT PRIMARY KEY,\n utterance_id TEXT,\n text TEXT NOT NULL,\n audio_path TEXT NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\n-- 받아오기(zip)로 넣은 발화: 보관 기간은 녹음 날짜가 아니라 받아온 날부터 센다\nCREATE TABLE IF NOT EXISTS utterance_imports (\n id TEXT PRIMARY KEY,\n imported_at INTEGER NOT NULL\n);\n\n-- 사이트에서 \"잡음이라 삭제\"한 문장 (v1.4.0). 같은 문장(띄어쓰기 · 문장부호 무시, 긴 문장은 글자 한두 개 바뀐 것까지)이 다시 인식되면 잡음으로 본다\nCREATE TABLE IF NOT EXISTS noise_phrases (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n phrase TEXT NOT NULL UNIQUE,\n sample TEXT NOT NULL,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n"; +export const SCHEMA_SQL = "PRAGMA journal_mode = WAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);\n\nCREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n color TEXT NOT NULL,\n avatar TEXT,\n excluded INTEGER NOT NULL DEFAULT 0,\n gain_lufs REAL,\n gain_n INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS game_accounts (\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n puuid TEXT NOT NULL,\n riot_id TEXT NOT NULL,\n PRIMARY KEY (user_id, puuid)\n);\nCREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);\n\nCREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n guild_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n channel_name TEXT,\n started_at INTEGER NOT NULL,\n ended_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS utterances (\n id TEXT PRIMARY KEY,\n session_id TEXT,\n user_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n audio_path TEXT,\n audio_deleted INTEGER NOT NULL DEFAULT 0,\n text TEXT,\n raw_text TEXT,\n words TEXT NOT NULL DEFAULT '[]',\n noise INTEGER NOT NULL DEFAULT 0,\n noise_reason TEXT,\n confidence REAL,\n lufs REAL,\n gain_db REAL NOT NULL DEFAULT 0,\n model TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n match_id TEXT,\n corrected INTEGER NOT NULL DEFAULT 0,\n attempts INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);\nCREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');\nCREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\n\nCREATE TABLE IF NOT EXISTS matches (\n id TEXT PRIMARY KEY,\n game TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER,\n map TEXT,\n mode TEXT,\n queue TEXT,\n result TEXT,\n detail TEXT,\n status TEXT NOT NULL DEFAULT 'live',\n clock_offset INTEGER NOT NULL DEFAULT 0,\n -- live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0)\n source TEXT NOT NULL DEFAULT 'live'\n);\nCREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);\n\nCREATE TABLE IF NOT EXISTS rounds (\n match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,\n num INTEGER NOT NULL,\n started_at INTEGER NOT NULL,\n combat_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n win INTEGER,\n result TEXT,\n ally_score INTEGER,\n enemy_score INTEGER,\n economy TEXT,\n PRIMARY KEY (match_id, num)\n);\n\nCREATE TABLE IF NOT EXISTS game_events (\n id TEXT PRIMARY KEY,\n match_id TEXT NOT NULL,\n game TEXT NOT NULL,\n type TEXT NOT NULL,\n ts INTEGER NOT NULL,\n game_time_ms INTEGER,\n round INTEGER,\n actor_puuid TEXT,\n target_puuid TEXT,\n data TEXT NOT NULL DEFAULT '{}'\n);\nCREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);\nCREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);\n\nCREATE TABLE IF NOT EXISTS dictionary (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n word TEXT NOT NULL,\n pack TEXT NOT NULL,\n kind TEXT NOT NULL,\n from_text TEXT NOT NULL DEFAULT '',\n source TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n UNIQUE (kind, word, from_text, pack)\n);\n\nCREATE TABLE IF NOT EXISTS training_samples (\n id TEXT PRIMARY KEY,\n utterance_id TEXT,\n text TEXT NOT NULL,\n audio_path TEXT NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\n-- 받아오기(zip)로 넣은 발화: 보관 기간은 녹음 날짜가 아니라 받아온 날부터 센다\nCREATE TABLE IF NOT EXISTS utterance_imports (\n id TEXT PRIMARY KEY,\n imported_at INTEGER NOT NULL\n);\n\n-- 사이트에서 \"잡음이라 삭제\"한 문장 (v1.4.0). 같은 문장(띄어쓰기 · 문장부호 무시, 긴 문장은 글자 한두 개 바뀐 것까지)이 다시 인식되면 잡음으로 본다\nCREATE TABLE IF NOT EXISTS noise_phrases (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n phrase TEXT NOT NULL UNIQUE,\n sample TEXT NOT NULL,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n"; diff --git a/app/src/core/games/history.ts b/app/src/core/games/history.ts index 2f6db77..06e469d 100644 --- a/app/src/core/games/history.ts +++ b/app/src/core/games/history.ts @@ -1,3 +1,4 @@ +import type { HistoryProgress } from '@gvr/shared'; import type { Store } from '../db/db.js'; import { logger } from '../util/log.js'; @@ -31,6 +32,11 @@ export interface HistoryOptions { export class HistorySync { private running = false; private lastAt = 0; + private everyMs = 0; + /** 지금 가져오는 중이면 진행 상황 (사이트 · 앱 화면 진행 바, v1.9.1) */ + private prog: HistoryProgress | null = null; + /** 사용자가 취소함: 이번 실행만 멈추고 다음 주기에 이어서 한다 */ + private cancelled = false; constructor( private store: Store, @@ -41,12 +47,40 @@ export class HistorySync { /** 주기 확인: 앞 실행에서 everyMs 가 지났고 게임 중이 아니면 백그라운드로 돌린다 */ maybeRun(everyMs: number, firstDelayMs = 60000): void { const now = Date.now(); + this.everyMs = everyMs; 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)); } + /** 진행 상황 (가져오는 중이 아니면 null). 남은 시간은 지금까지 한 경기에 걸린 평균으로 잰다 */ + progress(): HistoryProgress | null { + const p = this.prog; + if (!p) return null; + let etaMs: number | null = null; + if (p.phase === 'fetch' && p.done > 0 && this.fetchStartedAt) { + const per = (Date.now() - this.fetchStartedAt) / p.done; + etaMs = Math.round(per * (p.total - p.done)); + } + return { ...p, etaMs }; + } + private fetchStartedAt = 0; + + /** 지금 가져오기 취소. 받은 경기는 그대로 두고, 다음 주기(everyMs 뒤)에 남은 것부터 이어서 한다 */ + cancel(): { cancelled: boolean; resumeAt: number | null } { + if (!this.running || this.cancelled) return { cancelled: false, resumeAt: null }; + this.cancelled = true; + this.prog = null; + log.info(`${this.src.game} 경기 기록 가져오기: 사용자가 취소함`); + return { cancelled: true, resumeAt: this.everyMs ? this.lastAt + this.everyMs : null }; + } + + /** 멈춰야 하나 (게임 시작 · 취소) */ + private halted(): boolean { + return this.cancelled || !this.src.idle(); + } + private skipKey(): string { return `history_skip:${this.src.game}`; } @@ -64,26 +98,31 @@ export class HistorySync { const acct = this.src.account(); if (!acct) return 0; this.running = true; + this.cancelled = false; try { const fullKey = `history_full:${this.src.game}:${acct}`; const full = !!this.store.meta(fullKey); const skip = this.skipped(); const todo: string[] = []; + this.prog = { phase: 'scan', first: !full, scanned: 0, done: 0, total: 0, startedAt: Date.now(), etaMs: null }; for (let start = 0; start < this.opts.max; start += this.opts.pageSize) { - if (!this.src.idle()) return 0; + if (this.halted()) return 0; const p = await this.src.page(start, this.opts.pageSize); - if (p === 'retry') return 0; + if (p === 'retry' || this.cancelled) return 0; const fresh = p.ids.filter((id) => !skip.has(id) && !this.store.getMatch(id) && !todo.includes(id)); todo.push(...fresh); + this.prog = { ...this.prog, scanned: this.prog.scanned + p.ids.length, total: todo.length }; 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})`); + this.fetchStartedAt = Date.now(); + if (this.prog) this.prog = { ...this.prog, phase: 'fetch', done: 0, total: todo.length }; + for (const [i, id] of todo.entries()) { + if (this.halted()) { + log.info(`${this.src.game} 경기 기록: ${this.cancelled ? '취소해서' : '게임이 시작돼'} 멈춤 (${added}/${todo.length})`); return added; } const r = await this.src.fetch(id).catch(() => 'retry' as const); @@ -93,14 +132,17 @@ export class HistorySync { skip.add(id); this.store.setMeta(this.skipKey(), JSON.stringify([...skip].slice(-2000))); } + if (this.prog) this.prog = { ...this.prog, done: i + 1 }; await new Promise((res) => setTimeout(res, this.opts.gapMs)); } + if (this.cancelled) return added; // 끝(또는 max)까지 다 받았다: 다음부터는 새 경기만 본다 this.store.setMeta(fullKey, '1'); if (added) log.info(`${this.src.game} 경기 기록: ${added}개 저장`); return added; } finally { this.running = false; + this.prog = null; } } } diff --git a/app/src/core/games/lol.ts b/app/src/core/games/lol.ts index 706f0c2..94b3ff8 100644 --- a/app/src/core/games/lol.ts +++ b/app/src/core/games/lol.ts @@ -166,6 +166,7 @@ export class LolAdapter implements GameAdapter { self: this.lcu || inMatch ? { name: this.selfRiotId, character: snap?.champ ?? null, characterImage: snap?.champIcon ?? null, kda: snap?.kda ?? null, extra: snap?.extra ?? null } : null, players: snap?.players ?? null, error: this.lastErr || null, + history: this.history.progress(), updatedAt: Date.now(), }; } diff --git a/app/src/core/games/manager.ts b/app/src/core/games/manager.ts index 5168062..13e4bd4 100644 --- a/app/src/core/games/manager.ts +++ b/app/src/core/games/manager.ts @@ -67,6 +67,26 @@ export class GameManager implements AdapterHost { return this.adapters.map((a) => a.liveGame()); } + /** Riot 경기 기록 가져오기 취소 (사이트 경기 탭 · 앱 게임 연동 탭의 취소 버튼, v1.9.1). game 이 없으면 둘 다 */ + cancelHistory(game?: 'valorant' | 'lol'): { cancelled: ('valorant' | 'lol')[]; resumeAt: number | null } { + const cancelled: ('valorant' | 'lol')[] = []; + let resumeAt: number | null = null; + for (const a of this.adapters) { + if (game && a.game !== game) continue; + const r = a.history.cancel(); + if (!r.cancelled) continue; + cancelled.push(a.game); + if (r.resumeAt && (!resumeAt || r.resumeAt < resumeAt)) resumeAt = r.resumeAt; + } + // 화면에서 진행 바가 바로 사라지게 + if (cancelled.length) { + const live = this.live(); + this.lastLive = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest)); + this.bus.live({ type: 'games.state', data: live }); + } + return { cancelled, resumeAt }; + } + private liveTimer: NodeJS.Timeout | null = null; private lastLive = ''; /** 게임 상태가 바뀌면 사이트로 알린다 (2초마다 확인) */ diff --git a/app/src/core/games/types.ts b/app/src/core/games/types.ts index ca6b3f6..e4bb06a 100644 --- a/app/src/core/games/types.ts +++ b/app/src/core/games/types.ts @@ -3,6 +3,7 @@ import type { EventRow, MatchRow, Store } from '../db/db.js'; import type { Settings } from '../settings.js'; import type { WorkerClient } from '../stt/worker.js'; import type { GameAssets } from './assets.js'; +import type { HistorySync } from './history.js'; export interface MatchStart { id: string; @@ -45,4 +46,6 @@ export interface GameAdapter { gameRunning(): boolean; /** 지금 게임 상태 (자세히) */ liveGame(): LiveGame; + /** Riot 경기 기록 가져오기 */ + readonly history: HistorySync; } diff --git a/app/src/core/games/valorant.ts b/app/src/core/games/valorant.ts index e57fd2b..2a3496a 100644 --- a/app/src/core/games/valorant.ts +++ b/app/src/core/games/valorant.ts @@ -184,6 +184,7 @@ export class ValorantAdapter implements GameAdapter { self: this.auth ? { name: this.selfName, character: m?.selfAgent ?? null, characterImage: null, kda: null, extra: null } : null, players: m?.players || null, error: this.lastErr || null, + history: this.history.progress(), updatedAt: Date.now(), }; } diff --git a/app/src/main/api-types.ts b/app/src/main/api-types.ts index 89e9f01..b7755a4 100644 --- a/app/src/main/api-types.ts +++ b/app/src/main/api-types.ts @@ -110,6 +110,8 @@ export interface GvrApi { users(): Promise; setRiotIds(userId: string, riotIds: string[]): Promise; setExcluded(userId: string, excluded: boolean): Promise; + /** Riot 경기 기록 가져오기 취소 (v1.9.1). game 이 없으면 둘 다. resumeAt = 다시 이어서 하는 시각 */ + cancelHistory(game?: 'valorant' | 'lol'): Promise<{ cancelled: ('valorant' | 'lol')[]; resumeAt: number | null }>; dictionary(): Promise<{ labels: Record; packs: { key: string; label: string; count: number }[]; entries: { id: number; word: string; from: string | null; kind: 'hotword' | 'correction'; pack: string; source: string; enabled: boolean; hits: number }[] }>; addWord(word: string): Promise; addCorrection(from: string, to: string): Promise; diff --git a/app/src/main/ipc.ts b/app/src/main/ipc.ts index 61ae8c4..5fa799c 100644 --- a/app/src/main/ipc.ts +++ b/app/src/main/ipc.ts @@ -244,6 +244,7 @@ export function registerIpc(ctx: IpcContext) { core.store.setRiotIds(userId, riotIds, true); core.bus.live({ type: 'users.updated', data: [] }); }, + cancelHistory: (game?: 'valorant' | 'lol') => core.games.cancelHistory(game), setExcluded: (userId: string, excluded: boolean) => { core.store.setExcluded(userId, excluded); core.bus.live({ type: 'users.updated', data: [] }); diff --git a/app/src/main/preload.ts b/app/src/main/preload.ts index 86dfef8..afb930f 100644 --- a/app/src/main/preload.ts +++ b/app/src/main/preload.ts @@ -4,7 +4,7 @@ import { contextBridge, ipcRenderer } from 'electron'; const METHODS = [ 'getState', 'updateSettings', 'setSecret', 'testBotToken', 'restartBot', 'guildMembers', 'previewTts', 'gpuInfo', 'models', 'download', 'deleteModel', 'applyModels', 'chooseFolder', 'registerDevice', 'unregisterDevice', 'runDiagnostics', 'storageUsage', - 'runRetention', 'users', 'setRiotIds', 'setExcluded', 'dictionary', 'addWord', 'addCorrection', 'deleteDict', 'setDictEnabled', + 'runRetention', 'users', 'setRiotIds', 'setExcluded', 'cancelHistory', 'dictionary', 'addWord', 'addCorrection', 'deleteDict', 'setDictEnabled', 'finetuneStatus', 'finetuneInstall', 'finetuneStart', 'finetuneStop', 'finetuneRollback', 'clearTrainingData', 'openExternal', 'openPath', 'setAutoStart', 'finishWizard', 'recentLogs', 'quit', 'authState', 'authLogin', 'authCancel', 'authLogout', 'authRecheck', 'adminUsers', 'adminAddUser', 'adminSetRole', 'adminRemoveUser', 'adminDisplayNames', 'adminSetDisplayName', diff --git a/app/src/renderer/mock-gvr.ts b/app/src/renderer/mock-gvr.ts index 56b4328..a986624 100644 --- a/app/src/renderer/mock-gvr.ts +++ b/app/src/renderer/mock-gvr.ts @@ -168,7 +168,8 @@ export function createMockGvr(): GvrApi { }, { game: 'lol', enabled: true, connected: true, phase: '로비', inMatch: false, matchId: null, mode: '솔로 랭크', map: null, mapImage: null, - startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: null, characterImage: null, kda: null, extra: null }, players: null, error: null, updatedAt: now, + startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: null, characterImage: null, kda: null, extra: null }, players: null, error: null, + history: q.has('nohistory') ? null : { phase: 'fetch', first: true, scanned: 140, done: 37, total: 120, startedAt: now - 40000, etaMs: 90000 }, updatedAt: now, }, ], counts: { utterances: 1824, matches: 37 }, @@ -519,6 +520,18 @@ export function createMockGvr(): GvrApi { const u = users.find((x) => x.id === userId); if (u) u.riot = riotIds.map((r, i) => ({ puuid: `${userId}-${i}`, riotId: r })); }, + async cancelHistory(game) { + await sleep(150); + const cancelled: ('valorant' | 'lol')[] = []; + for (const g of state.liveGames ?? []) { + if (g.history && (!game || g.game === game)) { + g.history = null; + cancelled.push(g.game); + } + } + emit(); + return { cancelled, resumeAt: cancelled.length ? Date.now() + 30 * 60000 : null }; + }, async setExcluded(userId, excluded) { const u = users.find((x) => x.id === userId); if (u) u.excluded = excluded; diff --git a/app/src/renderer/styles.css b/app/src/renderer/styles.css index 4ede4ac..9ccd5d3 100644 --- a/app/src/renderer/styles.css +++ b/app/src/renderer/styles.css @@ -149,6 +149,10 @@ input[type='number'].input { flex: none; padding: 7px 8px; } .pbar i { display: block; height: 100%; background: linear-gradient(90deg, var(--accent), #ff7a85); border-radius: 5px; transition: width 0.25s; } .pbar.done i { background: linear-gradient(90deg, #1fb383, var(--good)); } .pbar.error i { background: #6b2a33; } +.pbar.indet i { width: 35%; animation: pbar-indet 1.4s ease-in-out infinite; } +@keyframes pbar-indet { 0% { transform: translateX(-100%); } 100% { transform: translateX(290%); } } +.hist-row + .hist-row { margin-top: 12px; } +.hist-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } .prog { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; } .prog-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; font-size: 13px; } .dl-list { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; } diff --git a/app/src/renderer/tabs/GamesTab.tsx b/app/src/renderer/tabs/GamesTab.tsx index 581c3b3..5cdd39f 100644 --- a/app/src/renderer/tabs/GamesTab.tsx +++ b/app/src/renderer/tabs/GamesTab.tsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { GAME_NAME, liveGameRows, type LiveGame, type User } from '@gvr/shared'; +import { GAME_NAME, historyStatus, liveGameRows, resumeText, type LiveGame, type User } from '@gvr/shared'; import { gvr, useAction, useApp, useLoad } from '../store'; import { Avatar, Btn, Dot, Err, FolderRow, Page, Section, Spinner, Toggle } from '../ui'; @@ -84,6 +84,44 @@ function LiveGames() { ); } +/** Riot 경기 기록 가져오기 진행 바 · 취소 (v1.9.1). 게임 중이 아닐 때 30분마다 돈다 */ +function HistoryImport() { + const { state, toast } = useApp(); + const act = useAction(); + const rows = (state.liveGames ?? []).filter((g) => g.history); + if (!rows.length) return null; + const cancel = async (game: LiveGame['game']) => { + const r = await act.run(() => gvr.cancelHistory(game)); + if (r?.cancelled.length) toast(`${GAME_NAME[game]} 경기 기록 가져오기를 멈췄습니다. 받은 경기는 남고, ${resumeText(r.resumeAt)} 남은 것부터 이어서 가져옵니다`); + }; + return ( +
+ {rows.map((g) => { + const st = historyStatus(g.history!); + return ( +
+
+ + {GAME_NAME[g.game]} + {st.title} + {st.detail} + + cancel(g.game)}> + 취소 + +
+
+ +
+ {g.history!.first &&
처음 한 번은 지난 경기를 끝까지 가져와서 오래 걸립니다. 게임을 켜면 바로 멈추고, 다음부터는 새 경기만 가져옵니다.
} +
+ ); + })} + {act.error} +
+ ); +} + const RIOT_RE = /^[^#]{1,16}#[^#\s]{2,5}$/; function RiotRow({ u }: { u: User }) { @@ -178,6 +216,7 @@ export function GamesTab() { return ( +
diff --git a/app/test/history.test.ts b/app/test/history.test.ts index 9dcac5e..68d14ac 100644 --- a/app/test/history.test.ts +++ b/app/test/history.test.ts @@ -113,3 +113,139 @@ test('경기 기록: 발로란트 · 롤 기록을 가져와 history 경기로 for (const k of ['GVR_HISTORY_EVERY_MS', 'GVR_HISTORY_GAP_MS']) delete process.env[k]; } }); + +test('경기 기록: 진행 상황 (목록 확인 → 경기 받기 · 남은 시간) · 취소하면 멈추고 다음에 이어서', async () => { + const dir = tmp(); + const { Store } = await import('../src/core/db/db.ts'); + const { HistorySync } = await import('../src/core/games/history.ts'); + const store = new Store(path.join(dir, 'db.sqlite')); + const all = Array.from({ length: 30 }, (_, i) => `val-p-${i}`); + let gate: (() => void) | null = null; + const fetched: string[] = []; + const src = { + game: 'valorant' as const, + idle: () => true, + account: () => 'me', + page: async (start: number, n: number) => { + // 첫 쪽은 화면에서 목록 확인 중을 볼 수 있게 잠깐 멈춘다 + if (start === 0) await new Promise((r) => (gate = r)); + return { ids: all.slice(start, start + n), total: all.length }; + }, + fetch: async (id: string) => { + await sleep(15); + store.upsertMatch({ id, game: 'valorant', started_at: Date.now(), status: 'complete' }); + fetched.push(id); + return 'ok' as const; + }, + }; + const h = new HistorySync(store, src, { pageSize: 10, max: 500, gapMs: 5 }); + try { + assert.equal(h.progress(), null, '가져오는 중이 아니면 없음'); + assert.deepEqual(h.cancel(), { cancelled: false, resumeAt: null }, '돌지 않을 때 취소는 아무 일 없음'); + h.maybeRun(60000, 0); + await until(() => !!gate, 2000, 'scan start'); + const s0 = h.progress()!; + assert.equal(s0.phase, 'scan'); + assert.equal(s0.first, true, '처음 끝까지 훑는 중'); + assert.equal(s0.etaMs, null); + gate!(); + await until(() => h.progress()?.phase === 'fetch' && h.progress()!.done >= 5, 5000, 'fetching'); + const p = h.progress()!; + assert.equal(p.total, 30); + assert.equal(p.scanned, 30); + assert.ok(p.etaMs !== null && p.etaMs > 0 && p.etaMs < 10000, `남은 시간 (${p.etaMs})`); + + // 취소: 진행 상황은 바로 사라지고, 루프는 다음 경기 전에 멈춘다 + const c = h.cancel(); + assert.equal(c.cancelled, true); + assert.ok(c.resumeAt && c.resumeAt > Date.now() + 50000, '다음 주기에 이어서'); + assert.equal(h.progress(), null); + const n = fetched.length; + await sleep(150); + assert.ok(fetched.length <= n + 1, `취소 뒤 더 받지 않음 (${n} → ${fetched.length})`); + assert.ok(fetched.length < 30); + assert.ok(!store.meta('history_full:valorant:me'), '끝까지 받지 않았으니 다음에도 끝까지 훑는다'); + + // 다음 실행: 받은 경기는 건너뛰고 남은 것만 + gate = null; + const run = h.run(); + await until(() => !!gate, 2000, 'scan 2'); + gate!(); + const before = fetched.length; + await run; + assert.equal(fetched.length, 30, '남은 것부터 끝까지'); + assert.equal(new Set(fetched).size, 30, '같은 경기를 두 번 받지 않음'); + assert.ok(fetched.length - before === 30 - before); + assert.equal(store.meta('history_full:valorant:me'), '1'); + assert.equal(h.progress(), null, '끝나면 진행 상황 없음'); + } finally { + store.close(); + } +}); + +test('경기 기록: 진행 상황은 지금 게임 상태(games.state)로 나가고, 사이트에서 POST /api/games/history/cancel 로 취소', 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 { 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 { historyStatus, fmtEta } = await import('@gvr/shared'); + const store = new Store(path.join(dir, 'db.sqlite')); + const bus = new Bus(); + const sent: any[] = []; + bus.on('live', (e) => sent.push(e)); + const s = defaultSettings(); + const stt: any = { setGameActive: async () => undefined }; + const gm = new GameManager(store, new GameAssets(path.join(dir, 'cache')), Object.assign(new EventEmitter(), { request: async () => ({}) }) as any, stt, new Timeline(store), bus, () => s, () => null); + // 롤만 가져오는 중 + let lolRunning = true; + const fake = (game: 'valorant' | 'lol') => ({ + 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 }; + lolRunning = false; + return { cancelled: true, resumeAt: Date.now() + 30 * 60000 }; + }, + }); + for (const a of gm.adapters) (a as any).history = fake(a.game); + const app = await buildApi({ + store, + timeline: new Timeline(store), + games: gm, + dict: {} as any, + culprit: {} as any, + bus, + settings: () => s, + trainingDir: () => dir, + overviewExtra: () => ({ guild: null, recording: {} as any }), + version: 'test', + }); + try { + const lol = gm.live().find((g) => g.game === 'lol')!; + assert.equal(lol.history?.done, 10); + assert.equal(gm.live().find((g) => g.game === 'valorant')!.history, null); + assert.deepEqual(historyStatus(lol.history!), { title: '경기 기록 가져오는 중', detail: '10 / 40경기 (25%) · 약 1분 남음', pct: 25 }); + assert.equal(historyStatus({ ...lol.history!, phase: 'scan', total: 3 }).pct, null, '목록 확인 중에는 얼마나 걸릴지 모름'); + assert.equal(fmtEta(null), '남은 시간 계산 중'); + assert.equal(fmtEta(25000), '30초 남음'); + assert.equal(fmtEta(2 * 3600000 + 5 * 60000), '약 2시간 5분 남음'); + + const member = { 'x-gvr-user': encodeURIComponent(JSON.stringify({ id: 'm1', name: 'm1', avatar: null })), 'x-gvr-role': 'member' }; + const r = await app.inject({ method: 'POST', url: '/api/games/history/cancel', headers: member, payload: { game: 'lol' } }); + assert.equal(r.statusCode, 200); + const b = r.json(); + assert.deepEqual(b.cancelled, ['lol'], '서버 멤버 누구나 취소 (다음 주기에 이어서 하니 지워지는 것 없음)'); + assert.ok(b.resumeAt > Date.now()); + const st = sent.filter((e) => e.type === 'games.state').at(-1); + assert.ok(st, '취소하면 바로 게임 상태를 보낸다'); + assert.equal(st.data.find((g: any) => g.game === 'lol').history, null); + const again = await app.inject({ method: 'POST', url: '/api/games/history/cancel', payload: {} }); + assert.deepEqual(again.json().cancelled, [], '이미 멈췄으면 아무 일 없음'); + } finally { + await app.close(); + store.close(); + } +}); diff --git a/packages/shared/src/live-game.ts b/packages/shared/src/live-game.ts index 50aef40..5963117 100644 --- a/packages/shared/src/live-game.ts +++ b/packages/shared/src/live-game.ts @@ -1,4 +1,4 @@ -import type { LiveGame } from './protocol.js'; +import type { HistoryProgress, LiveGame } from './protocol.js'; import { fmtClock } from './time.js'; export const GAME_NAME: Record = { valorant: '발로란트', lol: '리그 오브 레전드' }; @@ -33,3 +33,25 @@ export function liveGameRows(g: LiveGame, now = Date.now()): [string, string][] if (g.error) rows.push(['오류', g.error]); return rows; } + +/** 남은 시간 글자: "약 3분 남음" · "40초 남음" · "남은 시간 계산 중" */ +export function fmtEta(ms: number | null): string { + if (ms == null) return '남은 시간 계산 중'; + if (ms < 60000) return `${Math.max(1, Math.ceil(ms / 10000) * 10)}초 남음`; + const min = Math.ceil(ms / 60000); + return min < 60 ? `약 ${min}분 남음` : `약 ${Math.floor(min / 60)}시간 ${min % 60}분 남음`; +} + +/** 경기 기록 가져오기 진행 바 글자 (v1.9.1, 사이트 경기 탭 · 앱 게임 연동 탭). pct = null 이면 얼마나 걸릴지 아직 모름 */ +export function historyStatus(p: HistoryProgress): { title: string; detail: string; pct: number | null } { + if (p.phase === 'scan') + return { title: '경기 기록 목록 확인 중', detail: `${p.scanned}경기 확인${p.total ? ` · 새 경기 ${p.total}개` : ''}`, pct: null }; + const pct = p.total ? Math.min(100, Math.round((p.done / p.total) * 100)) : 100; + return { title: '경기 기록 가져오는 중', detail: `${p.done} / ${p.total}경기 (${pct}%) · ${fmtEta(p.etaMs)}`, pct }; +} + +/** 취소한 가져오기를 다시 하는 때: "약 30분 뒤" (모르면 "다음 확인 때") */ +export function resumeText(resumeAt: number | null, now = Date.now()): string { + if (!resumeAt) return '다음 확인 때'; + return `약 ${Math.max(1, Math.ceil((resumeAt - now) / 60000))}분 뒤`; +} diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index e053693..efb0588 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -279,9 +279,28 @@ export interface LiveGame { players: number | null; /** 마지막 오류 (연결 실패 등) */ error: string | null; + /** Riot 경기 기록 가져오는 중이면 진행 상황 (v1.9.1~, 예전 앱은 없음) */ + history?: HistoryProgress | null; updatedAt: number; } +/** Riot 경기 기록 가져오기 진행 상황 (v1.9.1~). 사이트 경기 탭 · 앱 게임 연동 탭에 진행 바로 보여 준다 */ +export interface HistoryProgress { + /** scan = 경기 목록 훑는 중 (몇 경기를 받을지 아직 모름), fetch = 경기 하나씩 받는 중 */ + phase: 'scan' | 'fetch'; + /** 처음 끝까지 훑는 중 (오래 걸림) */ + first: boolean; + /** 경기 목록에서 확인한 경기 수 (scan) */ + scanned: number; + /** 받은 경기 수 / 받을 경기 수 (fetch) */ + done: number; + total: number; + /** 시작 시각 (PC 시계) */ + startedAt: number; + /** 남은 시간 예상 (ms). scan 중이거나 아직 모르면 null */ + etaMs: number | null; +} + /** 기록 묶음 (사이트 기록 관리, v1.3.7~): 경기 하나 또는 경기 밖 대화 한 덩어리 */ export interface BundleInfo { /** match-<경기ID> 또는 talk-<첫 발화ID> */ diff --git a/site/web/mock/server.mjs b/site/web/mock/server.mjs index e0633a3..9a76de7 100644 --- a/site/web/mock/server.mjs +++ b/site/web/mock/server.mjs @@ -39,7 +39,22 @@ const state = { device: { registered: true, online: process.env.MOCK_OFFLINE !== '1', name: '하늘의 게임 PC', lastSeen: Date.now(), version: '1.0.0' }, live: process.env.MOCK_LIVE !== '0', liveInterval: Number(process.env.MOCK_LIVE_INTERVAL ?? 15000), + // 롤 경기 기록 가져오기 흉내 (v1.9.1 진행 바): 1.5초에 한 경기, MOCK_HISTORY=0 이면 끔 + hist: process.env.MOCK_HISTORY === '0' ? null : { startedAt: Date.now(), total: Number(process.env.MOCK_HISTORY_TOTAL ?? 120) }, }; +const histProgress = () => { + const h = state.hist; + if (!h) return null; + const el = Date.now() - h.startedAt; + if (el < 4000) return { phase: 'scan', first: true, scanned: Math.floor(el / 400) * 20, done: 0, total: Math.floor(el / 400) * 12, startedAt: h.startedAt, etaMs: null }; + const done = Math.min(h.total, Math.floor((el - 4000) / 1500)); + if (done >= h.total) return (state.hist = null); + 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() }, +]; const json = (res, status, body, headers = {}) => { const s = JSON.stringify(body, (k, v) => (k.startsWith('_') ? undefined : v)); @@ -303,10 +318,7 @@ async function handle(req, res) { recording: { active: true, channel: '발로 음성방', since: NOW - 150 * 60000, participants: db.SPEAKERS.map((u) => u.id) }, users: db.users, games: { valorant: { connected: true, inMatch: false }, lol: { connected: false, inMatch: false } }, - live: [ - { 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: false, phase: '롤 클라이언트 꺼짐', 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, updatedAt: Date.now() }, - ], + live: liveGames(), counts: { utterances: db.utterances.length, matches: db.matches.length }, version: '1.0.0', }); @@ -422,6 +434,12 @@ async function handle(req, res) { } return json(res, 200, { bundles: out.sort((a, b) => b.from - a.from) }); } + if (p === '/api/games/history/cancel' && req.method === 'POST') { + const was = !!histProgress(); + state.hist = null; + broadcast({ type: 'games.state', data: liveGames() }); + return json(res, 200, { ok: true, cancelled: was ? ['lol'] : [], resumeAt: was ? Date.now() + 30 * 60000 : null }); + } if (p === '/api/bundles/delete' && req.method === 'POST') return json(res, 200, { bundles: 1, utterances: 12, files: 12 }); if (p === '/api/bundles/export' && req.method === 'POST') { req.resume(); @@ -491,10 +509,17 @@ export function startMock({ port = Number(process.env.MOCK_PORT ?? 18787) } = {} if (state.live && wss.clients.size) emitLive(); }, state.liveInterval); const hb = setInterval(() => deviceOk() && pushStatus(), 20000); + // 경기 기록 가져오기 진행 (앱은 2초마다 바뀌면 보낸다) + const histTimer = setInterval(() => { + if (!wss.clients.size) return; + const had = !!state.hist; + if (had) broadcast({ type: 'games.state', data: liveGames() }); + }, 2000); server.listen(port, '127.0.0.1', () => console.log(`[mock] http://127.0.0.1:${port} (데이터: 발화 ${db.utterances.length} · 이벤트 ${db.events.length} · 경기 ${db.matches.length} · 기준 ${fmtClock(0)})`)); server.on('close', () => { clearInterval(timer); clearInterval(hb); + clearInterval(histTimer); }); return server; } diff --git a/site/web/src/components/HistoryImport.tsx b/site/web/src/components/HistoryImport.tsx new file mode 100644 index 0000000..4c1baef --- /dev/null +++ b/site/web/src/components/HistoryImport.tsx @@ -0,0 +1,71 @@ +import { useEffect, useRef, useState } from 'react'; +import { GAME_NAME, historyStatus, resumeText, type GameType } from '@gvr/shared'; +import { api } from '../lib/api'; +import { useData } from '../store/app'; + +/** + * Riot 경기 기록 가져오기 진행 바 (v1.9.1, 경기 탭 위). 게임 PC 앱이 게임 중이 아닐 때 30분마다 지난 경기를 받아 온다. + * 받을 경기 수 · 남은 시간을 보여 주고 취소할 수 있다. 끝나면 onDone 으로 경기 목록을 다시 받게 한다. + */ +export function HistoryImport({ onDone }: { onDone: () => void }) { + const { overview } = useData(); + const rows = (overview?.live ?? []).filter((g) => g.history); + const [busy, setBusy] = useState(null); + const [msg, setMsg] = useState<{ text: string; bad?: boolean } | null>(null); + // 가져오기가 끝나거나 멈추면 경기 목록을 새로 + const active = rows.map((g) => g.game).join(','); + const prev = useRef(active); + useEffect(() => { + const now = active.split(','); + if (prev.current.split(',').some((g) => g && !now.includes(g))) onDone(); + prev.current = active; + }, [active, onDone]); + const cancel = (game: GameType) => { + setBusy(game); + setMsg(null); + api + .cancelHistory(game) + .then((r) => { + if (r.cancelled.length) setMsg({ text: `${GAME_NAME[game]} 경기 기록 가져오기를 멈췄습니다. 받은 경기는 그대로 있고, ${resumeText(r.resumeAt)} 남은 것부터 이어서 가져옵니다.` }); + }) + .catch((e) => setMsg({ text: `취소하지 못했습니다: ${e instanceof Error ? e.message : String(e)}`, bad: true })) + .finally(() => setBusy(null)); + }; + if (!rows.length && !msg) return null; + return ( +
+ {rows.map((g) => { + const st = historyStatus(g.history!); + return ( +
+
+ + {GAME_NAME[g.game]} + {st.title} + {st.detail} + + +
+ + + +
+ {g.history!.first ? '처음 한 번은 지난 경기를 끝까지 가져와서 오래 걸립니다. ' : ''} + 게임을 켜면 바로 멈추고, 끝나면 이 목록에 자동으로 나타납니다. +
+
+ ); + })} + {msg && ( +
+ {msg.text} + +
+ )} +
+ ); +} diff --git a/site/web/src/lib/api.ts b/site/web/src/lib/api.ts index 53fce64..885ae2d 100644 --- a/site/web/src/lib/api.ts +++ b/site/web/src/lib/api.ts @@ -232,6 +232,9 @@ export const api = { /** 발화 지우기 (v1.4.0). noise = 잡음이라 삭제 (같은 문장을 다음부터 잡음으로) */ deleteUtterance: (id: string, noise: boolean) => request<{ ok: true; learned: string | null }>(`/api/utterances/${encodeURIComponent(id)}/delete`, { method: 'POST', body: JSON.stringify({ noise }) }), + /** Riot 경기 기록 가져오기 취소 (v1.9.1). 받은 경기는 남고 resumeAt 에 이어서 한다 */ + cancelHistory: (game?: GameType) => + request<{ ok: true; cancelled: GameType[]; resumeAt: number | null }>('/api/games/history/cancel', { method: 'POST', body: JSON.stringify({ game }) }), noisePhrases: () => request<{ phrases: NoisePhrase[] }>('/api/noise-phrases'), deleteNoisePhrase: (id: number) => request<{ ok: true }>(`/api/noise-phrases/${id}`, { method: 'DELETE' }), }; diff --git a/site/web/src/pages/UserPages.tsx b/site/web/src/pages/UserPages.tsx index 2933c5f..5519633 100644 --- a/site/web/src/pages/UserPages.tsx +++ b/site/web/src/pages/UserPages.tsx @@ -7,6 +7,7 @@ import { 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'; function useLoad(fn: () => Promise, deps: unknown[]) { const { epoch } = useStatus(); @@ -120,8 +121,9 @@ export function MatchesPage() { ))}
+ {err != null && } - {!data && !err && } + {!data && !err && } {data && all.length === 0 && (
{has === 'voice' ? '목소리가 녹음된 경기가 없습니다.' : has === 'timeline' ? '타임라인이 있는 경기가 없습니다.' : '경기 기록이 없습니다.'} diff --git a/site/web/src/styles.css b/site/web/src/styles.css index 3af28a9..105e9aa 100644 --- a/site/web/src/styles.css +++ b/site/web/src/styles.css @@ -4528,3 +4528,83 @@ button.match:hover { max-height: calc(100vh - var(--header-h) - 16px); } } + +/* Riot 경기 기록 가져오기 진행 바 (v1.9.1, 경기 탭) */ +.hist-import { + display: flex; + flex-direction: column; + gap: 8px; + margin: 10px 0 4px; +} +.hist-card { + border: 1px solid var(--line); + border-left: 3px solid var(--accent); + border-radius: 10px; + background: var(--panel); + padding: 10px 14px; + display: flex; + flex-direction: column; + gap: 7px; +} +.hist-card.lol { + border-left-color: var(--lol); +} +.hist-top { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + font-size: 13.5px; +} +.hist-gap { + flex: 1; +} +.hist-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--mint); + animation: hist-pulse 1.2s ease-in-out infinite; +} +@keyframes hist-pulse { + 50% { + opacity: 0.3; + } +} +.hist-card .btn, +.hist-msg .btn { + padding: 5px 12px; + font-size: 12.5px; +} +.hist-bar i { + background: var(--mint); +} +.hist-card.lol .hist-bar i { + background: var(--lol); +} +.hist-bar.indet i { + width: 35%; + animation: hist-indet 1.4s ease-in-out infinite; +} +@keyframes hist-indet { + 0% { + transform: translateX(-100%); + } + 100% { + transform: translateX(290%); + } +} +.hist-msg { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + font-size: 13px; + padding: 8px 14px; + border-radius: 10px; + background: var(--panel2); + color: var(--muted); +} +.hist-msg.bad { + color: var(--accent); +}