경기 기록 가져오기 진행 바 · 취소: Riot 경기 기록을 가져오는 동안 사이트 경기 탭 · 앱 게임 연동 탭에 목록 확인 중(얼마나 걸릴지 모름) → 받은 경기 / 받을 경기 · % · 남은 시간 진행 바와 취소 버튼 (취소하면 받은 경기는 남고 다음 주기에 남은 것부터 이어서) · 진행 상황은 games.state 의 history 로 보냄 · POST /api/games/history/cancel · 끝나면 경기 목록 새로 · 목록 불러오는 중 표시 · schema.ts 사본 다시 맞춤
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -120,6 +120,14 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
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);
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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초마다 확인) */
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -110,6 +110,8 @@ export interface GvrApi {
|
||||
users(): Promise<User[]>;
|
||||
setRiotIds(userId: string, riotIds: string[]): Promise<void>;
|
||||
setExcluded(userId: string, excluded: boolean): Promise<void>;
|
||||
/** Riot 경기 기록 가져오기 취소 (v1.9.1). game 이 없으면 둘 다. resumeAt = 다시 이어서 하는 시각 */
|
||||
cancelHistory(game?: 'valorant' | 'lol'): Promise<{ cancelled: ('valorant' | 'lol')[]; resumeAt: number | null }>;
|
||||
dictionary(): Promise<{ labels: Record<string, string>; 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<void>;
|
||||
addCorrection(from: string, to: string): Promise<void>;
|
||||
|
||||
@@ -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: [] });
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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 (
|
||||
<Section title="Riot 경기 기록" sub="사이트 경기 탭에 지난 경기 채우기">
|
||||
{rows.map((g) => {
|
||||
const st = historyStatus(g.history!);
|
||||
return (
|
||||
<div key={g.game} className="hist-row">
|
||||
<div className="hist-top">
|
||||
<Spinner />
|
||||
<b>{GAME_NAME[g.game]}</b>
|
||||
<span>{st.title}</span>
|
||||
<span className="muted">{st.detail}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<Btn small ghost busy={act.busy} onClick={() => cancel(g.game)}>
|
||||
취소
|
||||
</Btn>
|
||||
</div>
|
||||
<div className={`pbar${st.pct == null ? ' indet' : ''}`}>
|
||||
<i style={{ width: st.pct == null ? undefined : `${st.pct}%` }} />
|
||||
</div>
|
||||
{g.history!.first && <div className="hint">처음 한 번은 지난 경기를 끝까지 가져와서 오래 걸립니다. 게임을 켜면 바로 멈추고, 다음부터는 새 경기만 가져옵니다.</div>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<Err>{act.error}</Err>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
const RIOT_RE = /^[^#]{1,16}#[^#\s]{2,5}$/;
|
||||
|
||||
function RiotRow({ u }: { u: User }) {
|
||||
@@ -178,6 +216,7 @@ export function GamesTab() {
|
||||
return (
|
||||
<Page title="게임 연동">
|
||||
<GameCards />
|
||||
<HistoryImport />
|
||||
<LiveGames />
|
||||
<Section title="리그 오브 레전드 세부 설정" className={g.lol ? '' : 'disabled'}>
|
||||
<div className="muted" style={{ marginBottom: 8 }}>
|
||||
|
||||
Reference in New Issue
Block a user