Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
320cc9babe | ||
|
|
b645d7575d | ||
|
|
63d0e43196 | ||
|
|
2a9a6496d8 | ||
|
|
b1568db8ca | ||
|
|
11db2e5104 | ||
|
|
f9fbf4c6c0 | ||
|
|
9e1875b237 | ||
|
|
d0371fa0ac | ||
|
|
cfe5075f76 |
@@ -8,7 +8,7 @@
|
||||
- 설계·계획: [`docs/gemnoki-project-plan.pdf`](docs/gemnoki-project-plan.pdf), 개발 구조·인터페이스: [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
|
||||
- 범인찾기 · 리플레이 동기화 계획서 v1.2 (결정 반영): [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf) · 원본 · 비용 계산 · 프롬프트 초안: `docs/report/culprit/` (실제로 쓰는 프롬프트는 `site/server/prompt/`)
|
||||
- **제작 완료 보고서 (M0~M8)**: [`docs/gemnoki-final-report.pdf`](docs/gemnoki-final-report.pdf) · 단계별 테스트 기록: [`docs/dev/test-results.md`](docs/dev/test-results.md)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.8.1](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.8.1) (`GameVoiceRecorder-1.8.1-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.8.1-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.9.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.9.0) (`GameVoiceRecorder-1.9.0-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.9.0-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
|
||||
## 로그인 · 관리자 (v1.2.0~)
|
||||
|
||||
|
||||
4
app/package-lock.json
generated
4
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"version": "1.8.2",
|
||||
"version": "1.9.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gvr-app",
|
||||
"version": "1.8.2",
|
||||
"version": "1.9.1",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@discordjs/voice": "^0.19.2",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"productName": "겜녹이",
|
||||
"version": "1.8.2",
|
||||
"version": "1.9.1",
|
||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||
"private": true,
|
||||
"main": "dist/main.cjs",
|
||||
|
||||
@@ -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);
|
||||
@@ -310,7 +318,13 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
app.get<{ Querystring: Record<string, string> }>('/api/matches', async (req) => {
|
||||
const q = req.query;
|
||||
return store
|
||||
.listMatches({ game: q.game || undefined, before: q.before ? Number(q.before) : undefined, limit: q.limit ? Math.min(Number(q.limit), 200) : 50 })
|
||||
.listMatches({
|
||||
game: q.game || undefined,
|
||||
before: q.before ? Number(q.before) : 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,
|
||||
})
|
||||
.map((m) => d.games.summary(m));
|
||||
});
|
||||
|
||||
|
||||
@@ -75,6 +75,8 @@ export class Bundles {
|
||||
const out: Group[] = [];
|
||||
for (const m of matches) {
|
||||
const list = byMatch.get(m.id) ?? [];
|
||||
// Riot 경기 기록에서 가져오기만 한 경기(녹음 없음)는 기록 묶음으로 보이지 않는다
|
||||
if (m.source === 'history' && !list.length) continue;
|
||||
const sum = this.games.summary(m);
|
||||
const label = `${m.game === 'valorant' ? '발로란트' : '롤'} · ${sum.mode} · ${sum.map.name}`;
|
||||
const score = sum.score ? ` ${sum.score.ally}:${sum.score.enemy}` : '';
|
||||
@@ -314,8 +316,8 @@ export class Bundles {
|
||||
if (s?.id) db.prepare('INSERT OR IGNORE INTO sessions(id,guild_id,channel_id,channel_name,started_at,ended_at) VALUES(?,?,?,?,?,?)').run(s.id, String(s.guild_id ?? ''), String(s.channel_id ?? ''), s.channel_name ?? null, Number(s.started_at) || 0, s.ended_at ?? null);
|
||||
for (const m of data.matches ?? []) {
|
||||
const r = db
|
||||
.prepare('INSERT OR IGNORE INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset) VALUES(?,?,?,?,?,?,?,?,?,?,?)')
|
||||
.run(m.id, m.game, m.started_at, m.ended_at ?? null, m.map ?? null, m.mode ?? null, m.queue ?? null, m.result ?? null, m.detail ?? null, m.status === 'live' ? 'complete' : (m.status ?? 'complete'), Number(m.clock_offset) || 0);
|
||||
.prepare('INSERT OR IGNORE INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset,source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)')
|
||||
.run(m.id, m.game, m.started_at, m.ended_at ?? null, m.map ?? null, m.mode ?? null, m.queue ?? null, m.result ?? null, m.detail ?? null, m.status === 'live' ? 'complete' : (m.status ?? 'complete'), Number(m.clock_offset) || 0, m.source === 'history' ? 'history' : 'live');
|
||||
res.added.matches += r.changes;
|
||||
}
|
||||
for (const r of data.rounds ?? [])
|
||||
|
||||
@@ -50,6 +50,8 @@ export interface MatchRow {
|
||||
detail: string | null;
|
||||
status: string;
|
||||
clock_offset: number;
|
||||
/** live: 앱이 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 */
|
||||
source: 'live' | 'history';
|
||||
}
|
||||
export interface RoundRow {
|
||||
match_id: string;
|
||||
@@ -128,6 +130,9 @@ export class Store {
|
||||
|
||||
/** 예전 DB 를 지금 스키마로 맞춘다 (스키마를 바꿀 때마다 여기에 단계 추가) */
|
||||
private migrate(): void {
|
||||
// v1.9.0: 경기 출처 (Riot 경기 기록에서 가져온 경기)
|
||||
const mcols = this.db.prepare(`PRAGMA table_info(matches)`).all() as { name: string }[];
|
||||
if (!mcols.some((c) => c.name === 'source')) this.db.exec(`ALTER TABLE matches ADD COLUMN source TEXT NOT NULL DEFAULT 'live'`);
|
||||
// v1.0 개발 중: dictionary UNIQUE 에 pack 추가 (같은 단어가 여러 묶음에 들어갈 수 있게)
|
||||
const idx = this.db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='dictionary'`).get() as { sql: string } | undefined;
|
||||
if (idx && !/UNIQUE\s*\(kind,\s*word,\s*from_text,\s*pack\)/.test(idx.sql)) {
|
||||
@@ -406,13 +411,14 @@ export class Store {
|
||||
detail: null,
|
||||
status: 'live',
|
||||
clock_offset: 0,
|
||||
source: 'live',
|
||||
...(cur || {}),
|
||||
...stripUndef(m),
|
||||
} as MatchRow;
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset)
|
||||
VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset)
|
||||
`INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset,source)
|
||||
VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset,@source)
|
||||
ON CONFLICT(id) DO UPDATE SET started_at=@started_at, ended_at=@ended_at, map=@map, mode=@mode, queue=@queue,
|
||||
result=@result, detail=@detail, status=@status, clock_offset=@clock_offset`,
|
||||
)
|
||||
@@ -422,9 +428,15 @@ export class Store {
|
||||
getMatch(id: string): MatchRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM matches WHERE id=?').get(id) as MatchRow | undefined;
|
||||
}
|
||||
listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[] }): MatchRow[] {
|
||||
/**
|
||||
* has: timeline = 타임라인에 나오는 경기 (앱이 잡은 경기 · 기록에서 가져왔어도 대화가 붙은 경기), voice = 목소리가 녹음된 경기
|
||||
*/
|
||||
listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[]; has?: 'timeline' | 'voice' }): MatchRow[] {
|
||||
const where: string[] = [];
|
||||
const args: any[] = [];
|
||||
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})`);
|
||||
if (opts.game) {
|
||||
where.push('game=?');
|
||||
args.push(opts.game);
|
||||
|
||||
@@ -82,7 +82,9 @@ CREATE TABLE IF NOT EXISTS matches (
|
||||
result TEXT,
|
||||
detail TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'live',
|
||||
clock_offset INTEGER NOT NULL DEFAULT 0
|
||||
clock_offset INTEGER NOT NULL DEFAULT 0,
|
||||
-- live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0)
|
||||
source TEXT NOT NULL DEFAULT 'live'
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
155
app/src/core/games/history.ts
Normal file
155
app/src/core/games/history.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import type { HistoryProgress } from '@gvr/shared';
|
||||
import type { Store } from '../db/db.js';
|
||||
import { logger } from '../util/log.js';
|
||||
|
||||
const log = logger('history');
|
||||
|
||||
/** 게임별 Riot 경기 기록 읽기 */
|
||||
export interface HistorySource {
|
||||
readonly game: 'valorant' | 'lol';
|
||||
/** 지금 가져와도 되는가 (게임 중 · 요원 선택 중이면 false) */
|
||||
idle(): boolean;
|
||||
/** 이 PC 에 로그인한 계정 (계정이 바뀌면 처음부터 다시 훑는다) */
|
||||
account(): string | null;
|
||||
/** start 번째부터 n 개 (새것부터). 경기 행 ID 로 돌려준다. 'retry' = 지금은 못 읽음 */
|
||||
page(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'>;
|
||||
/** 경기 하나를 받아 저장. gone = 기록이 없음(다시 묻지 않음), retry = 나중에 */
|
||||
fetch(id: string): Promise<'ok' | 'gone' | 'retry'>;
|
||||
}
|
||||
|
||||
export interface HistoryOptions {
|
||||
pageSize: number;
|
||||
/** 최대 몇 경기 전까지 훑을지 */
|
||||
max: number;
|
||||
/** 경기 상세 요청 사이 간격 (Riot 요청 한도) */
|
||||
gapMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 내 Riot 경기 기록 → 경기 목록 (v1.9.0). 앱이 꺼져 있을 때 한 경기도 사이트 경기 탭에 보이게 한다.
|
||||
* 처음에는 끝까지 훑고, 그다음부터는 이미 아는 경기만 나오는 쪽까지만 본다. 게임이 시작되면 바로 멈춘다.
|
||||
*/
|
||||
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,
|
||||
private src: HistorySource,
|
||||
private opts: HistoryOptions,
|
||||
) {}
|
||||
|
||||
/** 주기 확인: 앞 실행에서 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;
|
||||
// 다음 실행은 취소한 때부터 한 주기 뒤 (오래 돈 실행을 취소해도 바로 다시 시작하지 않게)
|
||||
this.lastAt = Date.now();
|
||||
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}`;
|
||||
}
|
||||
private skipped(): Set<string> {
|
||||
try {
|
||||
return new Set(JSON.parse(this.store.meta(this.skipKey()) || '[]'));
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
/** 한 번 훑기. 새로 저장한 경기 수 */
|
||||
async run(): Promise<number> {
|
||||
if (this.running) return 0;
|
||||
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 pendingKey = `history_pending:${this.src.game}:${acct}`;
|
||||
const full = !!this.store.meta(fullKey);
|
||||
const pending = !!this.store.meta(pendingKey);
|
||||
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.halted()) return 0;
|
||||
const p = await this.src.page(start, this.opts.pageSize);
|
||||
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 && !pending && !fresh.length) break;
|
||||
}
|
||||
if (todo.length) log.info(`${this.src.game} 경기 기록: 새 경기 ${todo.length}개 가져오는 중`);
|
||||
let added = 0;
|
||||
this.fetchStartedAt = Date.now();
|
||||
if (this.prog) this.prog = { ...this.prog, phase: 'fetch', done: 0, total: todo.length };
|
||||
if (todo.length && !pending) this.store.setMeta(pendingKey, '1');
|
||||
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);
|
||||
if (r === 'retry') return added;
|
||||
if (r === 'ok') added++;
|
||||
else {
|
||||
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 (this.store.meta(pendingKey)) this.store.setMeta(pendingKey, '');
|
||||
if (added) log.info(`${this.src.game} 경기 기록: ${added}개 저장`);
|
||||
return added;
|
||||
} finally {
|
||||
this.running = false;
|
||||
this.prog = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { logger } from '../util/log.js';
|
||||
import { lolObjectIcon } from './assets.js';
|
||||
import { basicAuth, findLcu, request } from './riot.js';
|
||||
import type { AdapterHost, GameAdapter } from './types.js';
|
||||
import { HistorySync } from './history.js';
|
||||
|
||||
const log = logger('lol');
|
||||
|
||||
@@ -71,8 +72,42 @@ export class LolAdapter implements GameAdapter {
|
||||
/** 게임 클라이언트 API 마지막 값 (지금 게임 상태 표시용) */
|
||||
private snap: { at: number; gameTime: number; mode: string | null; champ: string | null; champIcon: string | null; kda: string | null; extra: string | null; teamKills: { ally: number; enemy: number } | null; players: number } | null = null;
|
||||
private selfRiotId: string | null = null;
|
||||
private selfPuuid: string | null = null;
|
||||
/** 내 경기 기록 (LCU, 앱이 꺼져 있을 때 한 경기도 경기 목록에) */
|
||||
readonly history: HistorySync;
|
||||
|
||||
constructor(private host: AdapterHost) {}
|
||||
constructor(private host: AdapterHost) {
|
||||
this.history = new HistorySync(
|
||||
host.store,
|
||||
{
|
||||
game: 'lol',
|
||||
idle: () => !!this.lcu && !(this.live && !this.live.ended) && !['ChampSelect', 'GameStart', 'InProgress', 'Reconnect'].includes(this.phase ?? ''),
|
||||
account: () => this.selfPuuid,
|
||||
page: (start, n) => this.historyPage(start, n),
|
||||
fetch: (id) => this.historyFetch(id),
|
||||
},
|
||||
{ pageSize: 20, max: Number(process.env.GVR_HISTORY_MAX) || 200, gapMs: Number(process.env.GVR_HISTORY_GAP_MS) || 500 },
|
||||
);
|
||||
}
|
||||
|
||||
private async historyPage(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'> {
|
||||
const r = await this.lcuGet<any>(`/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=${start}&endIndex=${start + n}`);
|
||||
const games = r?.games?.games;
|
||||
if (!Array.isArray(games)) return 'retry';
|
||||
return { ids: games.filter((g: any) => g?.gameId).map((g: any) => `lol-${g.gameId}`), total: null };
|
||||
}
|
||||
|
||||
private async historyFetch(id: string): Promise<'ok' | 'gone' | 'retry'> {
|
||||
if (!this.lcu) return 'retry';
|
||||
const gameId = id.replace(/^lol-/, '');
|
||||
const game = await this.lcuGet<any>(`/lol-match-history/v1/games/${gameId}`);
|
||||
if (!this.lcu) return 'retry';
|
||||
if (!game?.participants || !game.gameCreation) return 'gone';
|
||||
const timeline = await this.lcuGet<any>(`/lol-match-history/v1/game-timelines/${gameId}`);
|
||||
this.host.historyMatch({ id, game: 'lol', startedAt: game.gameCreation, map: game.mapId ? `Map${game.mapId}` : 'Map11', mode: game.gameMode ?? null, queue: game.queueId ? String(game.queueId) : null });
|
||||
this.applyHistory(id, game, timeline, game.gameCreation);
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.timer) return;
|
||||
@@ -87,6 +122,10 @@ export class LolAdapter implements GameAdapter {
|
||||
status() {
|
||||
return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined };
|
||||
}
|
||||
/** 롤은 경기 중에만 (클라이언트 화면은 가볍다) */
|
||||
gameRunning(): boolean {
|
||||
return !!this.live && !this.live.ended;
|
||||
}
|
||||
|
||||
liveGame(): LiveGame {
|
||||
const enabled = this.host.settings().games.lol;
|
||||
@@ -127,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(),
|
||||
};
|
||||
}
|
||||
@@ -442,6 +482,7 @@ export class LolAdapter implements GameAdapter {
|
||||
log.info('롤 클라이언트(LCU) 연결');
|
||||
const me = await this.lcuGet<any>('/lol-summoner/v1/current-summoner');
|
||||
if (me?.puuid) this.host.selfAccount(me.puuid, `${me.gameName}#${me.tagLine}`);
|
||||
this.selfPuuid = me?.puuid ?? null;
|
||||
if (me?.gameName) this.selfRiotId = `${me.gameName}#${me.tagLine ?? ''}`;
|
||||
}
|
||||
}
|
||||
@@ -459,6 +500,7 @@ export class LolAdapter implements GameAdapter {
|
||||
this.queueName = q ? (lolModeKo(q.id) ?? q.description ?? null) : null;
|
||||
}
|
||||
if (phase === 'ChampSelect' || phase === 'InProgress' || phase === 'PreEndOfGame' || phase === 'EndOfGame') await this.pollLcuChat(phase);
|
||||
this.history.maybeRun(Number(process.env.GVR_HISTORY_EVERY_MS) || 30 * 60000);
|
||||
}
|
||||
|
||||
private async pollLcuChat(phase: string): Promise<void> {
|
||||
|
||||
@@ -67,12 +67,33 @@ 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초마다 확인) */
|
||||
private watchLive(): void {
|
||||
if (this.liveTimer) return;
|
||||
this.liveTimer = setInterval(() => {
|
||||
void this.stt.setGameActive(this.adapters.some((a) => this.settings().games[a.game] && a.gameRunning()));
|
||||
const live = this.live();
|
||||
const key = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest));
|
||||
if (key === this.lastLive) return;
|
||||
@@ -103,6 +124,22 @@ export class GameManager implements AdapterHost {
|
||||
this.emitMatch(m.id);
|
||||
}
|
||||
|
||||
/** Riot 경기 기록에서 가져온 경기 (상세는 바로 이어서 matchUpdated 로 채운다). 녹음 · STT 와는 상관없다 */
|
||||
historyMatch(m: MatchStart): void {
|
||||
if (this.store.getMatch(m.id)) return;
|
||||
this.store.upsertMatch({
|
||||
id: m.id,
|
||||
game: m.game,
|
||||
started_at: m.startedAt,
|
||||
map: m.map ?? null,
|
||||
mode: m.mode ?? null,
|
||||
queue: m.queue ?? null,
|
||||
detail: m.detail ? JSON.stringify(m.detail) : null,
|
||||
status: 'pending_detail',
|
||||
source: 'history',
|
||||
});
|
||||
}
|
||||
|
||||
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void {
|
||||
const cur = this.store.getMatch(id);
|
||||
if (!cur) return;
|
||||
@@ -182,6 +219,8 @@ export class GameManager implements AdapterHost {
|
||||
score: result.score,
|
||||
status: m.status as MatchSummary['status'],
|
||||
participants,
|
||||
source: m.source === 'history' ? 'history' : 'live',
|
||||
voice: !!this.store.db.prepare('SELECT 1 FROM utterances WHERE match_id=? AND (noise=0 OR corrected=1) LIMIT 1').get(m.id),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -21,6 +22,8 @@ export interface AdapterHost {
|
||||
worker: WorkerClient;
|
||||
settings(): Settings;
|
||||
matchStarted(m: MatchStart): void;
|
||||
/** Riot 경기 기록에서 가져온 경기 행 만들기 (이미 있으면 그대로) */
|
||||
historyMatch(m: MatchStart): void;
|
||||
/** 경기 정보 갱신 (상세가 채워졌을 때 등) */
|
||||
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void;
|
||||
matchEnded(id: string, endedAt: number): void;
|
||||
@@ -39,6 +42,10 @@ export interface GameAdapter {
|
||||
start(): void;
|
||||
stop(): void;
|
||||
status(): { connected: boolean; inMatch: boolean; detail?: string };
|
||||
/** 게임이 켜져 있어 GPU 를 쓰고 있는가 (발로란트: 게임 실행 중 · 롤: 경기 중) */
|
||||
gameRunning(): boolean;
|
||||
/** 지금 게임 상태 (자세히) */
|
||||
liveGame(): LiveGame;
|
||||
/** Riot 경기 기록 가져오기 */
|
||||
readonly history: HistorySync;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { logger } from '../util/log.js';
|
||||
import type { GameAssets } from './assets.js';
|
||||
import { basicAuth, readLockfile, request, riotClientLockfilePath, type Lockfile } from './riot.js';
|
||||
import type { AdapterHost, GameAdapter } from './types.js';
|
||||
import { HistorySync } from './history.js';
|
||||
|
||||
const log = logger('valorant');
|
||||
|
||||
@@ -76,8 +77,51 @@ export class ValorantAdapter implements GameAdapter {
|
||||
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
|
||||
private polling = false;
|
||||
private lastErr = '';
|
||||
/** 내 경기 기록 (앱이 꺼져 있을 때 한 경기도 경기 목록에) */
|
||||
readonly history: HistorySync;
|
||||
|
||||
constructor(private host: AdapterHost) {}
|
||||
constructor(private host: AdapterHost) {
|
||||
this.history = new HistorySync(
|
||||
host.store,
|
||||
{
|
||||
game: 'valorant',
|
||||
idle: () => {
|
||||
const st = this.presence?.state;
|
||||
return !!this.auth && !this.match && st !== 'INGAME' && st !== 'PREGAME';
|
||||
},
|
||||
account: () => this.auth?.puuid ?? null,
|
||||
page: (start, n) => this.historyPage(start, n),
|
||||
fetch: (id) => this.historyFetch(id),
|
||||
},
|
||||
{ pageSize: 20, max: Number(process.env.GVR_HISTORY_MAX) || 500, gapMs: Number(process.env.GVR_HISTORY_GAP_MS) || 1500 },
|
||||
);
|
||||
}
|
||||
|
||||
private async historyPage(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'> {
|
||||
const a = this.auth;
|
||||
if (!a) return 'retry';
|
||||
const r = await request(`${this.pd(a)}/match-history/v1/history/${a.puuid}?startIndex=${start}&endIndex=${start + n}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
|
||||
if (r.status !== 200 || !Array.isArray(r.data?.History)) {
|
||||
log.debug(`경기 기록 목록 실패 (${r.status})`);
|
||||
return 'retry';
|
||||
}
|
||||
return { ids: r.data.History.map((h: any) => `val-${h.MatchID}`), total: typeof r.data.Total === 'number' ? r.data.Total : null };
|
||||
}
|
||||
|
||||
private async historyFetch(id: string): Promise<'ok' | 'gone' | 'retry'> {
|
||||
const a = this.auth;
|
||||
if (!a) return 'retry';
|
||||
const r = await request(`${this.pd(a)}/match-details/v1/matches/${id.replace(/^val-/, '')}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
|
||||
if (r.status === 404 || r.status === 400) return 'gone';
|
||||
if (r.status !== 200 || !r.data?.matchInfo) return 'retry';
|
||||
const md = r.data;
|
||||
const S: number = md.matchInfo.gameStartMillis;
|
||||
if (!S) return 'gone';
|
||||
this.host.historyMatch({ id, game: 'valorant', startedAt: S, map: md.matchInfo.mapId ?? null, mode: md.matchInfo.queueID ?? null, queue: md.matchInfo.queueID ?? null });
|
||||
await this.fillNames(a, md);
|
||||
this.applyDetails(id, md, a.puuid, S);
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.timer) return;
|
||||
@@ -91,6 +135,10 @@ export class ValorantAdapter implements GameAdapter {
|
||||
status() {
|
||||
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
|
||||
}
|
||||
/** 발로란트는 메뉴에서도 게임 화면을 그린다: 게임이 켜져 있으면(내 발로란트 상태가 있으면) 켜짐 */
|
||||
gameRunning(): boolean {
|
||||
return !!this.match || (!!this.auth && !!this.presence);
|
||||
}
|
||||
|
||||
liveGame(): LiveGame {
|
||||
const p = this.presence;
|
||||
@@ -136,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(),
|
||||
};
|
||||
}
|
||||
@@ -206,9 +255,11 @@ export class ValorantAdapter implements GameAdapter {
|
||||
if (a) {
|
||||
await this.pollPresence(a);
|
||||
if (this.match) await this.pollChat(a);
|
||||
} else if (this.match) {
|
||||
else this.history.maybeRun(Number(process.env.GVR_HISTORY_EVERY_MS) || 30 * 60000);
|
||||
} else {
|
||||
this.presence = null;
|
||||
// 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다
|
||||
this.endMatch();
|
||||
if (this.match) this.endMatch();
|
||||
}
|
||||
await this.pollDetails();
|
||||
this.lastErr = '';
|
||||
|
||||
@@ -33,6 +33,8 @@ export interface Settings {
|
||||
modelsDir: string | null;
|
||||
reprocessAfterMatch: boolean;
|
||||
gameVramReserveMb: number;
|
||||
/** 게임이 켜져 있는 동안 GPU 를 아낀다: 실시간 모델만 가볍게(빔 1) · 쉬어 가며, 정밀 모델 변환은 게임을 끈 뒤로 (v1.9.0) */
|
||||
gameSaver: boolean;
|
||||
};
|
||||
audio: {
|
||||
targetLufs: number;
|
||||
@@ -111,6 +113,7 @@ export function defaultSettings(): Settings {
|
||||
modelsDir: null,
|
||||
reprocessAfterMatch: true,
|
||||
gameVramReserveMb: 3072,
|
||||
gameSaver: true,
|
||||
},
|
||||
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
|
||||
dictionary: {
|
||||
|
||||
@@ -100,6 +100,12 @@ export class SttPipeline {
|
||||
return c ? Number(c) : null;
|
||||
}
|
||||
private inMatch = false;
|
||||
/** 게임(발로란트 · 롤 경기)이 켜져 있다 (GameManager 가 2초마다 알려 줌) */
|
||||
private gameActive = false;
|
||||
/** 게임 중 GPU 아끼기: 켜져 있고 게임 중일 때 */
|
||||
private saving(): boolean {
|
||||
return this.gameActive && this.settings().stt.gameSaver !== false;
|
||||
}
|
||||
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
|
||||
private bothFit = true;
|
||||
status: SttStatus = {
|
||||
@@ -143,10 +149,46 @@ export class SttPipeline {
|
||||
this.bothFit = false;
|
||||
}
|
||||
await this.load('realtime', s.realtimeModel);
|
||||
if (this.bothFit && !this.inMatch) await this.load('precise', s.preciseModel);
|
||||
if (this.bothFit && !this.inMatch && !this.saving()) await this.load('precise', s.preciseModel);
|
||||
this.pump();
|
||||
}
|
||||
|
||||
/**
|
||||
* 게임이 켜지고 꺼질 때 (v1.9.0). 게임 중 GPU 아끼기가 켜져 있으면
|
||||
* 켜질 때 정밀 모델을 내리고(정밀 변환은 대기열에서 기다림), 꺼지면 다시 올려 밀린 정밀 변환을 한다.
|
||||
*/
|
||||
async setGameActive(on: boolean): Promise<void> {
|
||||
if (this.gameActive === on) return;
|
||||
this.gameActive = on;
|
||||
const s = this.settings().stt;
|
||||
if (on) {
|
||||
if (s.gameSaver === false) return;
|
||||
log.info('게임 켜짐: GPU 아끼기 (실시간 모델만 가볍게, 정밀 변환은 게임을 끈 뒤)');
|
||||
if (this.status.slots.precise.state === 'loaded') await this.unload('precise');
|
||||
return;
|
||||
}
|
||||
if (s.gameSaver !== false || this.queue.some((j) => j.slot === 'precise')) log.info('게임 꺼짐: 밀린 정밀 변환 시작');
|
||||
if (this.status.worker !== 'ready') return; // 워커가 켜지면 prepareModels 가 이어서 한다
|
||||
const wantPrecise = this.queue.some((j) => j.slot === 'precise') || this.bothFit;
|
||||
if (wantPrecise) await this.load('precise', s.preciseModel);
|
||||
if (this.gameActive) return; // 올리는 동안 게임이 다시 켜짐
|
||||
// 정밀 모델이 없으면(설치 안 됨 · 실패) 기다리던 정밀 변환은 버린다 (실시간 결과가 그대로 남음)
|
||||
if (this.status.slots.precise.state !== 'loaded') this.dropPrecise();
|
||||
else if (!this.bothFit && !this.queue.some((j) => j.slot === 'precise')) await this.unload('precise');
|
||||
this.pump();
|
||||
}
|
||||
|
||||
private dropPrecise(): void {
|
||||
const before = this.queue.length;
|
||||
this.queue = this.queue.filter((j) => {
|
||||
if (j.slot !== 'precise') return true;
|
||||
this.queued.delete(`precise:${j.id}`);
|
||||
return false;
|
||||
});
|
||||
this.status.queue = this.queue.length;
|
||||
if (before !== this.queue.length) log.info(`정밀 모델이 없어 정밀 변환 ${before - this.queue.length}개를 건너뜀`);
|
||||
}
|
||||
|
||||
private async installed(): Promise<Set<string>> {
|
||||
try {
|
||||
const r = await this.worker.request('models', {}, 30000);
|
||||
@@ -223,6 +265,13 @@ export class SttPipeline {
|
||||
this.inMatch = false;
|
||||
const s = this.settings().stt;
|
||||
if (!s.reprocessAfterMatch || s.preciseModel === s.realtimeModel) return;
|
||||
if (this.saving()) {
|
||||
// 게임(발로란트 메뉴 등)이 아직 켜져 있으면 정밀 변환은 대기열에서 게임이 꺼질 때까지 기다린다
|
||||
const rows = this.store.realtimeUtterancesInRange(from, to);
|
||||
log.info(`경기 종료: ${rows.length}개 발화의 정밀 변환은 게임을 끈 뒤에`);
|
||||
for (const r of rows) this.enqueue(r.id, 'precise', 10);
|
||||
return;
|
||||
}
|
||||
if (this.status.slots.precise.state !== 'loaded') await this.load('precise', s.preciseModel);
|
||||
if (this.status.slots.precise.state !== 'loaded') return;
|
||||
const rows = this.store.realtimeUtterancesInRange(from, to);
|
||||
@@ -232,6 +281,11 @@ export class SttPipeline {
|
||||
|
||||
private pickSlot(job: Job): Slot | null {
|
||||
const { realtime, precise } = this.status.slots;
|
||||
if (this.saving()) {
|
||||
// 게임 중: 정밀 변환은 기다리고, 새 발화는 실시간 모델로만
|
||||
if (job.slot === 'precise') return null;
|
||||
return realtime.state === 'loaded' ? 'realtime' : null;
|
||||
}
|
||||
if (job.slot === 'precise') return precise.state === 'loaded' ? 'precise' : null;
|
||||
// 경기 밖이고 정밀 모델이 올라와 있으면 처음부터 정밀 모델로
|
||||
if (!this.inMatch && precise.state === 'loaded' && this.queue.length < 20) return 'precise';
|
||||
@@ -255,6 +309,7 @@ export class SttPipeline {
|
||||
this.busy = true;
|
||||
this.processing = job.id;
|
||||
this.status.processing = job.id;
|
||||
const t0 = Date.now();
|
||||
this.run(job, this.pickSlot(job)!)
|
||||
.catch((e) => log.error('STT 작업 오류', e))
|
||||
.finally(() => {
|
||||
@@ -267,7 +322,9 @@ export class SttPipeline {
|
||||
} catch (e) {
|
||||
log.warn('변환 뒤 처리 실패', e);
|
||||
}
|
||||
setImmediate(() => this.pump());
|
||||
// 게임 중에는 변환한 만큼(최대 3초) 쉬고 다음 발화로: 여러 명이 연달아 말해도 GPU 를 계속 붙잡지 않는다
|
||||
if (this.saving()) setTimeout(() => this.pump(), Math.min(Date.now() - t0, 3000));
|
||||
else setImmediate(() => this.pump());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -324,6 +381,8 @@ export class SttPipeline {
|
||||
target_lufs: s.audio.targetLufs,
|
||||
noise_sensitivity: s.audio.noiseSensitivity,
|
||||
denoise: s.audio.denoise,
|
||||
// 게임 중에는 빔 1 (빔 3 보다 가볍다. 경기 뒤 정밀 모델이 다시 변환한다)
|
||||
...(this.saving() && slot === 'realtime' ? { beam_size: 1 } : {}),
|
||||
},
|
||||
5 * 60000,
|
||||
);
|
||||
|
||||
@@ -173,9 +173,15 @@ export class Timeline {
|
||||
if (q.match) {
|
||||
where.push('e.match_id = ?');
|
||||
args.push(q.match);
|
||||
} else if (q.game) {
|
||||
where.push('e.game = ?');
|
||||
args.push(q.game);
|
||||
} else {
|
||||
if (q.game) {
|
||||
where.push('e.game = ?');
|
||||
args.push(q.game);
|
||||
}
|
||||
// Riot 경기 기록에서 가져오기만 한 경기(앱이 녹음하지 않은 경기)의 킬 · 라운드는 타임라인에 넣지 않는다 (경기 화면에서는 보인다)
|
||||
where.push(
|
||||
`(e.match_id IS NULL OR e.match_id NOT IN (SELECT m.id FROM matches m WHERE m.source = 'history' AND NOT EXISTS (SELECT 1 FROM utterances x WHERE x.match_id = m.id)))`,
|
||||
);
|
||||
}
|
||||
if (q.users?.length) {
|
||||
// 선택하지 않은 (디스코드에 연결된) 유저가 주인공인 이벤트만 뺀다. 라운드·오브젝트·상대 킬처럼 유저가 없는 이벤트는 남긴다.
|
||||
|
||||
@@ -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: [] });
|
||||
|
||||
@@ -23,6 +23,8 @@ const opt = (name: string) => argv.find((a) => a.startsWith(`--${name}=`))?.spli
|
||||
const SMOKE = flag('smoke');
|
||||
|
||||
app.setAppUserModelId('kr.tkrmagid.gvr');
|
||||
// 설정 창은 글자 · 버튼뿐이라 GPU 로 그릴 필요가 없다. 게임 · 브라우저와 GPU 를 나눠 쓰지 않게 끈다 (v1.9.0)
|
||||
app.disableHardwareAcceleration();
|
||||
if (!SMOKE && !app.requestSingleInstanceLock()) {
|
||||
app.quit();
|
||||
process.exit(0);
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -35,6 +35,7 @@ function defaults(): Settings {
|
||||
modelsDir: null,
|
||||
reprocessAfterMatch: true,
|
||||
gameVramReserveMb: 3072,
|
||||
gameSaver: true,
|
||||
},
|
||||
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
|
||||
dictionary: {
|
||||
@@ -167,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 },
|
||||
@@ -518,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 }}>
|
||||
|
||||
@@ -184,6 +184,12 @@ export function SttTab() {
|
||||
<div className="warn-text small">⚠ RTX 50 시리즈(Blackwell)에서 int8 계열은 cuBLAS 오류 사례가 있습니다. 문제가 생기면 float16으로 돌려 주세요.</div>
|
||||
)}
|
||||
<ToggleLine label="경기가 끝나면 정밀 모델로 다시 변환" on={s.reprocessAfterMatch} onChange={(v) => save({ stt: { reprocessAfterMatch: v } })} />
|
||||
<ToggleLine
|
||||
label="게임 중 GPU 아끼기"
|
||||
hint="게임이 켜져 있으면 실시간 모델만 가볍게 쉬어 가며 돌리고, 정밀 모델 변환은 게임을 끈 뒤에 합니다"
|
||||
on={s.gameSaver}
|
||||
onChange={(v) => save({ stt: { gameSaver: v } })}
|
||||
/>
|
||||
<Line label="게임용 VRAM 예약" hint="두 게임 중 큰 값 · 실측 후 조정">
|
||||
<NumInput value={s.gameVramReserveMb} min={0} max={24576} step={256} width={90} suffix="MB" onCommit={(n) => save({ stt: { gameVramReserveMb: n } })} />
|
||||
</Line>
|
||||
|
||||
103
app/test/game-saver.test.ts
Normal file
103
app/test/game-saver.test.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
// v1.9.0: 게임 중 GPU 아끼기 (발로란트 + 브라우저 + 겜녹이를 같이 켜면 GPU 가 100% 가까이 차던 것)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Store } from '../src/core/db/db.ts';
|
||||
import { Timeline } from '../src/core/timeline.ts';
|
||||
import { Bus } from '../src/core/util/events.ts';
|
||||
import { SttPipeline } from '../src/core/stt/pipeline.ts';
|
||||
|
||||
function setup(gameSaver = true) {
|
||||
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-saver-'));
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
||||
const t0 = Date.now() - 600000;
|
||||
store.upsertMatch({ id: 'm1', game: 'valorant', started_at: t0, status: 'live' });
|
||||
const mk = (id: string, at = Date.now()) => {
|
||||
const f = path.join(dir, 'audio', `${id}.ogg`);
|
||||
fs.mkdirSync(path.dirname(f), { recursive: true });
|
||||
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
||||
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: at, ended_at: at + 1000, audio_path: f, match_id: 'm1' });
|
||||
};
|
||||
const reqs: any[] = [];
|
||||
const ops: string[] = [];
|
||||
const worker: any = Object.assign(new EventEmitter(), {
|
||||
ready: true,
|
||||
request: async (op: string, req: any) => {
|
||||
if (op === 'gpu_info') return { gpus: [{ vram_total_mb: 16303 }] }; // 두 모델을 같이 올릴 수 있는 카드
|
||||
if (op === 'models') return { models: [{ name: 'rt', installed: true }, { name: 'pr', installed: true }] };
|
||||
if (op === 'load' || op === 'unload') {
|
||||
ops.push(`${op}:${req.slot}`);
|
||||
return {};
|
||||
}
|
||||
reqs.push(req);
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
return { text: '말', raw_text: '말', words: [], noise: false, noise_reason: null, confidence: 0.5, lufs: -30, gain_db: 0, speech_ratio: 1, duration_s: 1, model: req.slot, elapsed_ms: 40 };
|
||||
},
|
||||
});
|
||||
const settings: any = () => ({
|
||||
stt: { realtimeModel: 'rt', preciseModel: 'pr', device: 'cuda', computeType: 'float16', gameVramReserveMb: 3072, reprocessAfterMatch: true, gameSaver },
|
||||
audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false },
|
||||
});
|
||||
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
|
||||
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
|
||||
stt.status.worker = 'ready';
|
||||
const wait = async (fn: () => boolean, ms = 5000) => {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - t > ms) throw new Error('timeout');
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
};
|
||||
return { store, stt, mk, reqs, ops, wait, t0 };
|
||||
}
|
||||
|
||||
test('게임 중: 정밀 모델을 내리고, 새 발화는 실시간 모델 · 빔 1 로만, 발화 사이에 쉰다', async () => {
|
||||
const s = setup();
|
||||
await s.stt.prepareModels();
|
||||
assert.equal(s.stt.status.slots.precise.state, 'loaded', '게임 밖에서는 두 모델 모두');
|
||||
await s.stt.setGameActive(true);
|
||||
assert.equal(s.stt.status.slots.precise.state, 'empty', '게임이 켜지면 정밀 모델을 내린다');
|
||||
s.mk('a1');
|
||||
s.mk('a2');
|
||||
s.stt.enqueue('a1', 'realtime');
|
||||
s.stt.enqueue('a2', 'realtime');
|
||||
const t = Date.now();
|
||||
await s.wait(() => s.reqs.length === 2 && !s.stt.status.processing);
|
||||
assert.ok(Date.now() - t >= 75, '두 번째 발화 전에 앞 변환만큼 쉰다');
|
||||
assert.deepEqual(s.reqs.map((r) => [r.slot, r.beam_size]), [['realtime', 1], ['realtime', 1]]);
|
||||
});
|
||||
|
||||
test('경기가 끝나도 게임(메뉴)이 켜져 있으면 정밀 변환은 기다리고, 게임을 끄면 정밀 모델을 올려 한다', async () => {
|
||||
const s = setup();
|
||||
await s.stt.prepareModels();
|
||||
await s.stt.setGameActive(true);
|
||||
await s.stt.onMatchStart();
|
||||
s.mk('b1', s.t0 + 1000);
|
||||
s.stt.enqueue('b1', 'realtime');
|
||||
await s.wait(() => s.store.getUtterance('b1')!.status === 'realtime');
|
||||
await s.stt.onMatchEnd(s.t0, Date.now());
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
assert.equal(s.reqs.length, 1, '게임이 켜져 있는 동안 정밀 변환 안 함');
|
||||
assert.equal(s.stt.status.queue, 1);
|
||||
assert.equal(s.stt.status.slots.precise.state, 'empty');
|
||||
await s.stt.setGameActive(false);
|
||||
await s.wait(() => s.store.getUtterance('b1')!.status === 'precise');
|
||||
assert.equal(s.reqs[1].slot, 'precise');
|
||||
assert.equal(s.reqs[1].beam_size, undefined, '게임 밖에서는 기본 빔');
|
||||
});
|
||||
|
||||
test('게임 중 GPU 아끼기를 끄면 예전처럼 (정밀 모델 유지 · 기본 빔)', async () => {
|
||||
const s = setup(false);
|
||||
await s.stt.prepareModels();
|
||||
await s.stt.setGameActive(true);
|
||||
assert.equal(s.stt.status.slots.precise.state, 'loaded');
|
||||
await s.stt.onMatchStart();
|
||||
s.mk('c1');
|
||||
s.stt.enqueue('c1', 'realtime');
|
||||
await s.wait(() => s.reqs.length === 1);
|
||||
assert.equal(s.reqs[0].beam_size, undefined);
|
||||
});
|
||||
@@ -40,7 +40,7 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
|
||||
const tl = new Timeline(store);
|
||||
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
|
||||
const sttCalls: string[] = [];
|
||||
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end') };
|
||||
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end'), setGameActive: async () => undefined };
|
||||
const assets = new GameAssets(path.join(dir, 'cache'));
|
||||
(assets as any).refresh = async () => undefined; // 네트워크 없이
|
||||
assets.lol = {
|
||||
|
||||
331
app/test/history.test.ts
Normal file
331
app/test/history.test.ts
Normal file
@@ -0,0 +1,331 @@
|
||||
// v1.9.0: 내 Riot 경기 기록 가져오기 (앱이 꺼져 있을 때 한 경기도 사이트 경기 탭에)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { startMockRiot } from './mock/riot.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-hist-'));
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
async function until(fn: () => boolean, ms = 10000, label = 'condition') {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - t > ms) throw new Error(`timeout: ${label}`);
|
||||
await sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
test('경기 기록: 발로란트 · 롤 기록을 가져와 history 경기로 저장, 필터 · 타임라인 · 다시 훑기', async () => {
|
||||
const dir = tmp();
|
||||
const mock = await startMockRiot(path.join(dir, 'mock'));
|
||||
Object.assign(process.env, {
|
||||
GVR_RIOT_LOCKFILE: mock.lockfile,
|
||||
GVR_LCU_LOCKFILE: mock.lockfile,
|
||||
GVR_VAL_GLZ: mock.base,
|
||||
GVR_VAL_PD: mock.base,
|
||||
GVR_LOL_LIVE_URL: mock.base,
|
||||
GVR_POLL_MS: '150',
|
||||
GVR_HISTORY_EVERY_MS: '400',
|
||||
GVR_HISTORY_GAP_MS: '5',
|
||||
});
|
||||
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 { defaultSettings } = await import('../src/core/settings.ts');
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
const tl = new Timeline(store);
|
||||
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
|
||||
const stt: any = { onMatchStart: async () => undefined, onMatchEnd: async () => undefined, setGameActive: async () => undefined };
|
||||
const assets = new GameAssets(path.join(dir, 'cache'));
|
||||
(assets as any).refresh = async () => undefined;
|
||||
const s = defaultSettings();
|
||||
store.upsertUser({ id: 'owner', name: '하늘', avatar: null });
|
||||
const H = Date.now() - 30 * 86400000;
|
||||
// 발로란트 23경기 (두 쪽): 하나는 앱이 이미 잡은 경기, 하나는 상세가 없는 경기
|
||||
mock.st.valHistory = Array.from({ length: 23 }, (_, i) => ({ MatchID: i === 5 ? 'gone-5' : `h-${i}`, GameStartTime: H - i * 3600000 }));
|
||||
store.upsertMatch({ id: 'val-h-0', game: 'valorant', started_at: H, status: 'complete' });
|
||||
// 앱이 녹음하던 때 잡지 못한 경기: 그 시간 발화가 경기에 붙는다
|
||||
store.insertUtterance({ id: 'u1', session_id: null, user_id: 'owner', started_at: H - 3600000 + 60000, ended_at: H - 3600000 + 62000, audio_path: null, match_id: null });
|
||||
mock.st.lolHistoryList = [
|
||||
{ gameId: 9001, gameCreation: H - 100000 },
|
||||
{ gameId: 9002, gameCreation: H - 200000 },
|
||||
];
|
||||
const gm = new GameManager(store, assets, worker, stt, tl, bus(), () => s, () => 'owner');
|
||||
function bus() {
|
||||
return new Bus();
|
||||
}
|
||||
gm.start();
|
||||
try {
|
||||
await until(() => !!store.getMatch('val-h-22') && store.getMatch('val-h-22')!.status === 'complete', 15000, 'val history');
|
||||
await until(() => !!store.getMatch('lol-9002') && store.getMatch('lol-9002')!.status === 'complete', 15000, 'lol history');
|
||||
const vals = store.listMatches({ game: 'valorant', limit: 100 });
|
||||
assert.equal(vals.length, 22, '23경기 중 상세 없는 1경기 빼고');
|
||||
assert.equal(store.getMatch('val-h-0')!.source, 'live', '앱이 잡은 경기는 그대로');
|
||||
const h1 = store.getMatch('val-h-1')!;
|
||||
assert.equal(h1.source, 'history');
|
||||
assert.equal(h1.started_at, H - 3600000);
|
||||
assert.ok(store.events('val-h-1').some((e) => e.type === 'kill'), '킬 기록도 (경기 화면용)');
|
||||
assert.equal(store.getUtterance('u1')!.match_id, 'val-h-1', '그 시간 발화가 붙는다');
|
||||
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'));
|
||||
|
||||
// 필터
|
||||
const ids = (has?: 'timeline' | 'voice') => store.listMatches({ limit: 100, has }).map((m) => m.id).sort();
|
||||
assert.equal(ids().length, 24);
|
||||
assert.deepEqual(ids('timeline'), ['val-h-0', 'val-h-1'], '타임라인: 앱이 잡은 경기 + 대화가 붙은 기록 경기');
|
||||
store.updateUtteranceResult('u1', { text: '가자', raw_text: '가자', words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'm', status: 'precise' });
|
||||
assert.deepEqual(ids('voice'), ['val-h-1']);
|
||||
const sum = gm.summary(store.getMatch('val-h-2')!);
|
||||
assert.equal(sum.source, 'history');
|
||||
assert.equal(sum.voice, false);
|
||||
assert.equal(gm.summary(store.getMatch('val-h-1')!).voice, true);
|
||||
|
||||
// 타임라인: 녹음 없는 기록 경기의 이벤트는 빼고, 그 경기를 고르면 보인다
|
||||
const page = tl.query({ limit: 500 });
|
||||
const evMatches = new Set(page.items.filter((it: any) => it.kind === 'event').map((it: any) => it.matchId));
|
||||
assert.ok(!evMatches.has('val-h-2') && !evMatches.has('lol-9001'));
|
||||
assert.ok(evMatches.has('val-h-1'), '대화가 붙은 기록 경기는 타임라인에');
|
||||
assert.ok(tl.query({ match: 'val-h-2', limit: 50 }).items.length > 0);
|
||||
|
||||
// 다시 훑기: 한 번 끝까지 본 뒤에는 첫 쪽만 (새 경기 1개)
|
||||
const before = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length;
|
||||
mock.st.valHistory.unshift({ MatchID: 'h-new', GameStartTime: Date.now() - 3600000 });
|
||||
await until(() => store.getMatch('val-h-new')?.status === 'complete', 10000, 'new match');
|
||||
await sleep(100);
|
||||
const pages = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length - before;
|
||||
assert.ok(pages >= 1 && pages <= 3, `다시 훑을 때는 첫 쪽만 (${pages})`);
|
||||
|
||||
// 경기 중에는 가져오지 않는다
|
||||
mock.st.valState = 'INGAME';
|
||||
await until(() => gm.status().valorant.inMatch, 5000, 'in match');
|
||||
const n = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length;
|
||||
await sleep(1200);
|
||||
assert.equal(mock.st.hits.filter((h) => h.startsWith('/match-history/')).length, n);
|
||||
} finally {
|
||||
gm.stop();
|
||||
await mock.close();
|
||||
store.close();
|
||||
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<void>((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();
|
||||
}
|
||||
});
|
||||
|
||||
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'));
|
||||
// 예전 경기 20개는 이미 받았고 끝까지 훑은 계정
|
||||
const old = Array.from({ length: 20 }, (_, i) => `val-old-${i}`);
|
||||
for (const id of old) store.upsertMatch({ id, game: 'valorant', started_at: 1, status: 'complete' });
|
||||
store.setMeta('history_full:valorant:me', '1');
|
||||
// 새 경기 30개 (새것부터 = 목록 앞쪽)
|
||||
const fresh = Array.from({ length: 30 }, (_, i) => `val-new-${i}`);
|
||||
const all = [...fresh, ...old];
|
||||
const fetched: string[] = [];
|
||||
let pages = 0;
|
||||
let h!: InstanceType<typeof HistorySync>;
|
||||
const src = {
|
||||
game: 'valorant' as const,
|
||||
idle: () => true,
|
||||
account: () => 'me',
|
||||
page: async (start: number, n: number) => {
|
||||
pages++;
|
||||
return { ids: all.slice(start, start + n), total: all.length };
|
||||
},
|
||||
fetch: async (id: string) => {
|
||||
await sleep(5);
|
||||
store.upsertMatch({ id, game: 'valorant', started_at: 2, status: 'complete' });
|
||||
fetched.push(id);
|
||||
// 첫 쪽 10경기를 받은 뒤 취소
|
||||
if (fetched.length === 10) h.cancel();
|
||||
return 'ok' as const;
|
||||
},
|
||||
};
|
||||
h = new HistorySync(store, src, { pageSize: 10, max: 500, gapMs: 1 });
|
||||
try {
|
||||
assert.equal(await h.run(), 10);
|
||||
assert.equal(fetched.length, 10);
|
||||
assert.equal(store.meta('history_pending:valorant:me'), '1', '받다가 멈춤');
|
||||
|
||||
// 다음 실행: 첫 쪽은 다 아는 경기지만 멈추지 않고 끝까지 훑어 남은 20경기를 받는다
|
||||
assert.equal(await h.run(), 20, '남은 경기 모두');
|
||||
assert.deepEqual([...fetched].sort(), [...fresh].sort());
|
||||
assert.ok(!store.meta('history_pending:valorant:me'), '다 받았으면 표시를 지운다');
|
||||
|
||||
// 그다음부터는 다시 첫 쪽만
|
||||
pages = 0;
|
||||
assert.equal(await h.run(), 0);
|
||||
assert.equal(pages, 1, '아는 경기만 나오는 첫 쪽에서 멈춤');
|
||||
|
||||
// 취소한 때부터 한 주기 뒤에 이어서: 오래(주기보다 길게) 돈 실행을 취소해도 바로 다시 시작하지 않는다
|
||||
const every = 60000;
|
||||
fetched.length = 0;
|
||||
all.unshift(...Array.from({ length: 15 }, (_, i) => `val-more-${i}`));
|
||||
let gate!: () => void;
|
||||
const slowFetch = src.fetch;
|
||||
src.fetch = async (id: string) => {
|
||||
await new Promise<void>((r) => (gate = r));
|
||||
return slowFetch(id);
|
||||
};
|
||||
// 위에서 취소한 때부터 한 주기가 지나지 않았으니 maybeRun 은 아직 돌지 않는다
|
||||
h.maybeRun(every, 0);
|
||||
assert.equal((h as any).running, false, '취소 뒤 한 주기 안에는 다시 시작하지 않음');
|
||||
(h as any).lastAt = 0;
|
||||
h.maybeRun(every, 0);
|
||||
await until(() => h.progress()?.phase === 'fetch', 2000, 'fetch start');
|
||||
(h as any).lastAt -= 2 * every; // 두 주기 넘게 돈 것처럼
|
||||
const c = h.cancel();
|
||||
assert.equal(c.cancelled, true);
|
||||
assert.ok(c.resumeAt! >= Date.now() + every - 1000, `취소한 때부터 한 주기 뒤 (${c.resumeAt! - Date.now()}ms)`);
|
||||
gate();
|
||||
await until(() => !(h as any).running, 2000, 'stopped');
|
||||
pages = 0;
|
||||
h.maybeRun(every, 0);
|
||||
await sleep(50);
|
||||
assert.equal(pages, 0, '다음 확인에서 바로 다시 시작하지 않음');
|
||||
assert.equal(h.progress(), null);
|
||||
} finally {
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
@@ -18,6 +18,12 @@ export interface MockState {
|
||||
lolGameId: number;
|
||||
lolHistoryReady: boolean;
|
||||
lolStart: number;
|
||||
/** 발로란트 경기 기록 (새것부터): MatchID → 경기 시작 시각 */
|
||||
valHistory: { MatchID: string; GameStartTime: number }[];
|
||||
/** 롤 경기 기록 (LCU, 새것부터) */
|
||||
lolHistoryList: { gameId: number; gameCreation: number }[];
|
||||
/** 요청 기록 (경로) */
|
||||
hits: string[];
|
||||
}
|
||||
|
||||
export async function startMockRiot(dir: string) {
|
||||
@@ -38,6 +44,9 @@ export async function startMockRiot(dir: string) {
|
||||
lolGameId: 7001,
|
||||
lolHistoryReady: false,
|
||||
lolStart: 0,
|
||||
valHistory: [],
|
||||
lolHistoryList: [],
|
||||
hits: [],
|
||||
};
|
||||
const password = 'pw-test';
|
||||
const presence = () => {
|
||||
@@ -52,7 +61,7 @@ export async function startMockRiot(dir: string) {
|
||||
};
|
||||
return Buffer.from(JSON.stringify(priv)).toString('base64');
|
||||
};
|
||||
const routes: [RegExp, (m: RegExpMatchArray, auth: string) => [number, any]][] = [
|
||||
const routes: [RegExp, (m: RegExpMatchArray, auth: string, url: URL) => [number, any]][] = [
|
||||
// ---- Riot Client local
|
||||
[/^\/entitlements\/v1\/token$/, () => [200, { accessToken: 'acc-token', token: 'ent-token', subject: SELF, issuer: 'x' }]],
|
||||
[
|
||||
@@ -69,7 +78,23 @@ export async function startMockRiot(dir: string) {
|
||||
() => [200, { MatchID: st.valMatchId, MapID: ASCENT, Players: [{ Subject: SELF, TeamID: 'Blue', CharacterID: 'add6443a-41bd-e414-f6ad-e58d267f4e95' }] }],
|
||||
],
|
||||
// ---- pd
|
||||
[/^\/match-details\/v1\/matches\/(.+)$/, (_m, auth) => (auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}])],
|
||||
[
|
||||
/^\/match-history\/v1\/history\/(.+)$/,
|
||||
(_m, auth, url) => {
|
||||
if (!auth.startsWith('Bearer ')) return [401, {}];
|
||||
const s = Number(url.searchParams.get('startIndex') ?? 0);
|
||||
const e = Number(url.searchParams.get('endIndex') ?? 20);
|
||||
return [200, { Subject: SELF, BeginIndex: s, EndIndex: e, Total: st.valHistory.length, History: st.valHistory.slice(s, e).map((h) => ({ ...h, QueueID: 'competitive' })) }];
|
||||
},
|
||||
],
|
||||
[
|
||||
/^\/match-details\/v1\/matches\/(.+)$/,
|
||||
(m, auth) => {
|
||||
const h = st.valHistory.find((x) => x.MatchID === m[1]);
|
||||
if (h) return m[1].startsWith('gone') ? [404, {}] : [200, { ...makeValDetails(h.GameStartTime), matchInfo: { ...makeValDetails(h.GameStartTime).matchInfo, matchId: h.MatchID } }];
|
||||
return auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}];
|
||||
},
|
||||
],
|
||||
// ---- LoL Live Client Data
|
||||
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
|
||||
// ---- LCU
|
||||
@@ -79,7 +104,23 @@ export async function startMockRiot(dir: string) {
|
||||
[/^\/lol-chat\/v1\/conversations$/, () => [200, st.lolPhase === 'ChampSelect' ? [{ id: 'cs1@champ-select.kr', type: 'championSelect' }] : []]],
|
||||
[/^\/lol-chat\/v1\/conversations\/(.+)\/messages$/, () => [200, [{ id: 'msg1', body: '정글 갱 갈게요', fromSummonerId: 11, timestamp: new Date(Date.now() - 5000).toISOString(), type: 'groupchat' }]]],
|
||||
[/^\/lol-summoner\/v1\/summoners\/(\d+)$/, () => [200, { gameName: '민수' }]],
|
||||
[/^\/lol-match-history\/v1\/games\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolHistory()] : [404, {}])],
|
||||
[
|
||||
/^\/lol-match-history\/v1\/products\/lol\/current-summoner\/matches$/,
|
||||
(_m, _a, url) => {
|
||||
const s = Number(url.searchParams.get('begIndex') ?? 0);
|
||||
const e = Number(url.searchParams.get('endIndex') ?? 20);
|
||||
const games = st.lolHistoryList.slice(s, e);
|
||||
return [200, { games: { gameCount: games.length, gameIndexBegin: s, gameIndexEnd: e, games } }];
|
||||
},
|
||||
],
|
||||
[
|
||||
/^\/lol-match-history\/v1\/games\/(\d+)$/,
|
||||
(m) => {
|
||||
const h = st.lolHistoryList.find((x) => String(x.gameId) === m[1]);
|
||||
if (h) return [200, { ...lolHistory(), gameId: h.gameId, gameCreation: h.gameCreation }];
|
||||
return st.lolHistoryReady ? [200, lolHistory()] : [404, {}];
|
||||
},
|
||||
],
|
||||
[/^\/lol-match-history\/v1\/game-timelines\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolTimeline()] : [404, {}])],
|
||||
];
|
||||
const server = https.createServer({ key: fs.readFileSync(key), cert: fs.readFileSync(cert) }, (req, res) => {
|
||||
@@ -87,7 +128,8 @@ export async function startMockRiot(dir: string) {
|
||||
for (const [re, fn] of routes) {
|
||||
const m = url.pathname.match(re);
|
||||
if (!m) continue;
|
||||
const [code, body] = fn(m, String(req.headers.authorization || ''));
|
||||
st.hits.push(url.pathname);
|
||||
const [code, body] = fn(m, String(req.headers.authorization || ''), url);
|
||||
res.writeHead(code, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify(body));
|
||||
return;
|
||||
|
||||
@@ -287,6 +287,21 @@ VOICE E2E PASS
|
||||
- 화면: 목 서버 + 헤드리스 크롬(playwright-core)으로 내 정보(이름 저장 · 머리글 반영 · 색 · 녹음 제외 · 되돌리기) · 관리 페이지(새 버전 링크 · 이름 바꾸기 · 앱 유저 등록) · 모바일 390px 확인, 콘솔 오류 0
|
||||
- 배포: 사이트 서버 다시 배포 (`/site/admin/overview` · `/site/profile/name` 로그인 없이 401, 컨테이너에서 Gitea 최신 릴리스 조회 확인), Windows CI (b9431c1, full) 8개 모두 PASS · 앱 버전 1.6.0 → Gitea 릴리스 v1.6.0 (v1.5.0 · v1.4.3 에 새 버전 안내)
|
||||
|
||||
## v1.9.0 — 내 Riot 경기 기록 · 경기 탭 필터 · 게임 중 GPU 아끼기 · 리플레이 파일 없음 (2026-11-04)
|
||||
|
||||
- 앱: 게임 중이 아닐 때 30분마다 발로란트 match-history · 롤 LCU 기록을 훑어 앱이 잡지 못한 경기를 `source=history` 로 저장 (f9fbf4c) · 게임 중 GPU 아끼기 (발로란트 실행 중 · 롤 경기 중 정밀 모델 내림, 실시간 빔 1 · 발화 사이 쉼, 설정 토글 기본 켜짐, 앱 창 하드웨어 가속 끔, 9e1875b)
|
||||
- 사이트: 경기 탭 필터 (전체 / 타임라인 있는 경기 / 목소리 녹음된 경기) · 지난 경기 더 보기 (11db2e5), 3D 리플레이 '리플레이 파일 없음' · 새로고침 버튼 (d0371fa). 사이트는 앱보다 먼저 배포
|
||||
- 배포: Windows CI (b1568db, full) 8개 모두 PASS (변환기 회귀 검사 · 실제 리플레이 crosshairs 10, 앱 smoke 버전 1.9.0 · 실제 변환 11.0초 · gzip 1.60MB) · 앱 버전 1.9.0 → Gitea 릴리스 v1.9.0 (portable.exe 206,687,273 B · win-x64.zip 302,928,085 B, 올린 파일 sha256 일치) (v1.8.2 · v1.8.1 · v1.8.0 에 새 버전 안내)
|
||||
|
||||
## v1.8.2 — 3D 리플레이 선수 조준점 · 내 조준점 설정 (2026-10-29)
|
||||
|
||||
- 변환기: `BombPlayerState` 에 복제된 선수 조준점 프로필을 두 번째 읽기로 뽑아 `players[].crosshair` (`src/Crosshair.cs`). 어비스 13.08 리플레이 10명 모두, 프로필 이름 "1 4 2 0" = 불투명도 1 · 길이 4 · 두께 2 · 간격 0 으로 값 해독 확인. 두 번째 읽기 +0.4초 (리눅스 6.2초)
|
||||
- 회귀 검사 `--self-test`: 조준점 필드 자리(13.08 번호 · 2칸 밀린 패치 · 이름 어긋남) · 기본색 · 사용자 지정 색 추가, 통과
|
||||
- 사이트: 1인칭 "조준점" 버튼 · 설정 창 (선수 조준점 / 모든 선수에 내 조준점, 직접 고치기 · 발로란트 조준점 코드 가져오기 · 선수 조준점 복사). 조준점 코드 읽기 · 시각별 조준점 고르기를 esbuild 로 묶어 node 로 확인
|
||||
- 테스트: 앱 테스트 통과, 화면 타입 검사 · 빌드 통과
|
||||
- 화면: 목 서버 + 헤드리스 크롬으로 새 변환 결과 열어 하늘(1 4 2 0 흰 십자) · 상대5(빨강 굵은 십자 + 점) 선수 조준점, 코드 가져오기(초록 · 외곽선 · 점) · 모든 선수에 내 조준점 저장 확인, 콘솔 오류 0
|
||||
- 배포: 사이트 서버 다시 배포 (화면 번들에 '모든 선수에 내 조준점' 확인), Windows CI (96fb417, full) 8개 모두 PASS (변환기 실제 리플레이 crosshairs 10, 앱 smoke 실제 변환 16.3초 · gzip 1.60MB) · 앱 버전 1.8.2 → Gitea 릴리스 v1.8.2 (v1.8.1 · v1.8.0 · v1.7.0 에 새 버전 안내)
|
||||
|
||||
## v1.8.1 — 변환기: 무기 상태의 주인을 그 시각 주인으로 (2026-10-18)
|
||||
|
||||
- 고침: 무기 상태(재장전 · 사격 등)의 주인을 장비의 마지막 주인으로 정해, 무기를 넘겨받으면 넘기기 전 상태까지 새 주인 것이 되던 문제 → 인벤토리 기록 시간표에서 상태가 생긴 시각의 주인 (`EquipOwners`)
|
||||
|
||||
@@ -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<LiveGame['game'], string> = { 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))}분 뒤`;
|
||||
}
|
||||
|
||||
@@ -165,6 +165,10 @@ export interface MatchSummary {
|
||||
score: { ally: number; enemy: number } | null;
|
||||
status: 'live' | 'pending_detail' | 'complete';
|
||||
participants: string[];
|
||||
/** live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0 앱부터, 없으면 live) */
|
||||
source?: 'live' | 'history';
|
||||
/** 목소리가 녹음된 경기 (잡음 제외, v1.9.0 앱부터) */
|
||||
voice?: boolean;
|
||||
}
|
||||
|
||||
export interface MatchPlayer {
|
||||
@@ -275,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> */
|
||||
|
||||
@@ -580,6 +580,34 @@ function genReplayDemo(file) {
|
||||
}
|
||||
if (process.env.GVR_MOCK_REPLAY) genReplayDemo(process.env.GVR_MOCK_REPLAY);
|
||||
|
||||
// Riot 경기 기록에서 가져온 경기 (v1.9.0, 겜녹이가 꺼져 있을 때 한 경기): 녹음 · 타임라인 없음
|
||||
{
|
||||
const base = matches.find((m) => m.game === 'valorant');
|
||||
const MAPS = ['어센트', '바인드', '헤이븐', '로터스', '선셋'];
|
||||
for (let i = 0; i < 70; i++) {
|
||||
const start = NOW - (1 + i * 0.37) * 24 * 60 * MIN;
|
||||
const ally = 13;
|
||||
const enemy = (i * 5) % 12;
|
||||
const win = i % 3 !== 0;
|
||||
matches.push({
|
||||
...base,
|
||||
id: `val-hist-${i}`,
|
||||
startedAt: start,
|
||||
endedAt: start + 38 * MIN,
|
||||
map: { ...base.map, name: MAPS[i % MAPS.length] },
|
||||
mode: i % 4 === 0 ? '일반전' : '경쟁전',
|
||||
win,
|
||||
score: win ? { ally, enemy } : { ally: enemy, enemy: ally },
|
||||
status: 'complete',
|
||||
participants: [],
|
||||
source: 'history',
|
||||
utterances: [],
|
||||
events: [],
|
||||
replayPath: undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── 내보내기 ─────────────────────────────────────────
|
||||
export const db = {
|
||||
users: USERS,
|
||||
|
||||
@@ -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));
|
||||
@@ -115,7 +130,10 @@ function timeline(q) {
|
||||
return { items: page, next: items.length > limit ? enc(page[page.length - 1]) : null };
|
||||
}
|
||||
|
||||
const summary = (m) => ({ id: m.id, game: m.game, startedAt: m.startedAt, endedAt: m.endedAt, map: m.map, mode: m.mode, win: m.win, score: m.score, status: m.status, participants: m.participants });
|
||||
const summary = (m) => ({
|
||||
id: m.id, game: m.game, startedAt: m.startedAt, endedAt: m.endedAt, map: m.map, mode: m.mode, win: m.win, score: m.score, status: m.status, participants: m.participants,
|
||||
source: m.source ?? 'live', voice: m.utterances.length > 0,
|
||||
});
|
||||
|
||||
function userProfile(id) {
|
||||
const user = db.users.find((u) => u.id === id);
|
||||
@@ -300,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',
|
||||
});
|
||||
@@ -335,7 +350,9 @@ async function handle(req, res) {
|
||||
const game = q.get('game');
|
||||
const before = q.get('before') ? Number(q.get('before')) : Infinity;
|
||||
const limit = Number(q.get('limit') ?? 20);
|
||||
const list = db.matches.filter((x) => (!game || x.game === game) && x.startedAt < before).sort((a, b) => b.startedAt - a.startedAt).slice(0, limit).map(summary);
|
||||
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);
|
||||
return json(res, 200, list);
|
||||
}
|
||||
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
|
||||
@@ -347,7 +364,8 @@ async function handle(req, res) {
|
||||
if ((m = p.match(/^\/api\/matches\/([^/]+)\/replay$/))) {
|
||||
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
||||
if (!mt) return json(res, 404, { error: 'not_found' });
|
||||
if (!mt.replayPath) return json(res, 404, { error: 'replay_not_found' });
|
||||
// 파일을 지웠다가 다시 두면 "리플레이 없음 → 내려받고 새로고침" 을 흉내 낼 수 있다
|
||||
if (!mt.replayPath || !fs.existsSync(mt.replayPath)) return json(res, 404, { error: 'replay_not_found' });
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
return fs.createReadStream(mt.replayPath).pipe(res);
|
||||
}
|
||||
@@ -416,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();
|
||||
@@ -485,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;
|
||||
}
|
||||
|
||||
71
site/web/src/components/HistoryImport.tsx
Normal file
71
site/web/src/components/HistoryImport.tsx
Normal file
@@ -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<GameType | null>(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 (
|
||||
<div className="hist-import">
|
||||
{rows.map((g) => {
|
||||
const st = historyStatus(g.history!);
|
||||
return (
|
||||
<div key={g.game} className={`hist-card ${g.game}`} role="status">
|
||||
<div className="hist-top">
|
||||
<span className="hist-dot" />
|
||||
<b>{GAME_NAME[g.game]}</b>
|
||||
<span>{st.title}</span>
|
||||
<span className="dim small">{st.detail}</span>
|
||||
<span className="hist-gap" />
|
||||
<button className="btn small" disabled={busy === g.game} onClick={() => cancel(g.game)}>
|
||||
{busy === g.game ? '멈추는 중…' : '취소'}
|
||||
</button>
|
||||
</div>
|
||||
<span className={`bar hist-bar${st.pct == null ? ' indet' : ''}`}>
|
||||
<i style={st.pct == null ? undefined : { width: `${st.pct}%` }} />
|
||||
</span>
|
||||
<div className="dim small">
|
||||
{g.history!.first ? '처음 한 번은 지난 경기를 끝까지 가져와서 오래 걸립니다. ' : ''}
|
||||
게임을 켜면 바로 멈추고, 끝나면 이 목록에 자동으로 나타납니다.
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{msg && (
|
||||
<div className={`hist-msg${msg.bad ? ' bad' : ''}`}>
|
||||
{msg.text}
|
||||
<button className="btn small" onClick={() => setMsg(null)}>
|
||||
닫기
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,8 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
const [replay, setReplay] = useState<ReplayFile | null>(null);
|
||||
const [err, setErr] = useState<unknown>(null);
|
||||
const [converting, setConverting] = useState(false);
|
||||
// 새로고침을 누를 때마다 1씩 올려 리플레이를 다시 묻는다
|
||||
const [reload, setReload] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!open || replay) return;
|
||||
let alive = true;
|
||||
@@ -22,7 +24,7 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
// 처음 열면 게임 PC 가 리플레이를 변환한다 (보통 10초 안팎). 변환 중(202)이면 3초 뒤 다시 묻는다 (5분까지)
|
||||
const ask = (tries: number) =>
|
||||
api
|
||||
.replay(m.id)
|
||||
.replay(m.id, reload > 0)
|
||||
.then((r) => {
|
||||
if (!alive) return;
|
||||
if ('status' in r && r.status === 'converting') {
|
||||
@@ -46,12 +48,17 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
alive = false;
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
}, [open, m.id, replay]);
|
||||
}, [open, m.id, replay, reload]);
|
||||
const sync = useMemo(() => (replay ? computeSync(m, replay) : null), [m, replay]);
|
||||
// replay_not_found: 앱이 리플레이를 못 찾음. 다른 404: 이 앱 버전에는 리플레이 기능이 아직 없음
|
||||
const missing = err instanceof ApiError && err.status === 404 && err.code === 'replay_not_found';
|
||||
const appTooOld = err instanceof ApiError && err.status === 404 && err.code === 'Not Found'; // Fastify 기본 404 (경로 없음)
|
||||
const failed = err instanceof ApiError && err.status === 422 && err.code === 'replay_failed';
|
||||
const refresh = (
|
||||
<button className="mini-btn" onClick={() => setReload((n) => n + 1)}>
|
||||
새로고침
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<Panel
|
||||
className={`replay-panel${open ? ' open' : ''}`}
|
||||
@@ -67,15 +74,31 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
발로란트에서 이 경기 리플레이를 내려받으면 선수 10명의 움직임을 3D로 보면서 그때 나눈 대화를 같이 들을 수 있습니다.
|
||||
</div>
|
||||
) : missing ? (
|
||||
<div className="dim small">
|
||||
이 경기 리플레이가 아직 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받으면 게임 PC 앱이 찾아서 변환합니다 (몇 초 걸림).
|
||||
<div className="replay-msg">
|
||||
<div>
|
||||
<b>리플레이 파일 없음</b>
|
||||
<div className="dim small">
|
||||
게임 PC 에 이 경기의 리플레이 파일이 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받은 뒤 새로고침을 누르면 게임 PC 앱이 찾아서
|
||||
변환합니다 (몇 초 걸림).
|
||||
</div>
|
||||
</div>
|
||||
{refresh}
|
||||
</div>
|
||||
) : appTooOld ? (
|
||||
<div className="dim small">지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.</div>
|
||||
<div className="replay-msg">
|
||||
<div className="dim small">지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.</div>
|
||||
{refresh}
|
||||
</div>
|
||||
) : failed ? (
|
||||
<div className="dim small">게임 PC 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다. ({(err as ApiError).detail ?? '이유 모름'})</div>
|
||||
<div className="replay-msg">
|
||||
<div className="dim small">게임 PC 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다. ({(err as ApiError).detail ?? '이유 모름'})</div>
|
||||
{refresh}
|
||||
</div>
|
||||
) : err ? (
|
||||
<div className="dim small">리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}</div>
|
||||
<div className="replay-msg">
|
||||
<div className="dim small">리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}</div>
|
||||
{refresh}
|
||||
</div>
|
||||
) : !replay || !sync ? (
|
||||
<Spinner label={converting ? '게임 PC 가 리플레이를 변환하는 중 (처음 한 번, 10초 안팎)' : '리플레이 불러오는 중'} />
|
||||
) : (
|
||||
|
||||
@@ -42,6 +42,9 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** 경기 탭 필터 */
|
||||
export type MatchHas = 'timeline' | 'voice';
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
@@ -162,10 +165,13 @@ export const api = {
|
||||
hideNoise: 1,
|
||||
})}`,
|
||||
),
|
||||
matches: (o: { game?: GameType; limit?: number; before?: number } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
|
||||
// has: timeline = 타임라인에 나오는 경기, voice = 목소리가 녹음된 경기 (v1.9.0 앱부터, 예전 앱은 무시하고 다 보냄)
|
||||
matches: (o: { game?: GameType; limit?: number; before?: number; has?: MatchHas } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
|
||||
match: (id: string) => request<MatchDetail>(`/api/matches/${encodeURIComponent(id)}`),
|
||||
/** 발로란트 리플레이(.vrf)에서 뽑은 재생 데이터. 없으면 404 replay_not_found, 게임 PC 가 변환 중이면 202 { status: 'converting' } */
|
||||
replay: (id: string) => request<ReplayFile | { status: 'converting' }>(`/api/matches/${encodeURIComponent(id)}/replay`),
|
||||
// fresh: 새로고침 때는 브라우저 캐시를 거치지 않는다 (방금 내려받은 리플레이가 보이게)
|
||||
replay: (id: string, fresh = false) =>
|
||||
request<ReplayFile | { status: 'converting' }>(`/api/matches/${encodeURIComponent(id)}/replay`, fresh ? { cache: 'no-cache' } : {}),
|
||||
culpritMatches: (o: { game?: GameType; limit?: number } = {}) => request<CulpritMatchItem[]>(`/api/culprit/matches${qs(o)}`),
|
||||
culpritMatch: (id: string) => request<CulpritMatchInfo>(`/api/culprit/matches/${encodeURIComponent(id)}`),
|
||||
culpritBudget: () => request<CulpritBudget>('/api/culprit/budget'),
|
||||
@@ -226,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' }),
|
||||
};
|
||||
|
||||
@@ -15,7 +15,9 @@ export function toggleUser(f: Filters, users: User[], id: string): string[] {
|
||||
return all.every((x) => nextSet.includes(x)) ? [] : nextSet;
|
||||
}
|
||||
|
||||
export function MatchItem({ m, on, onClick }: { m: MatchSummary; on?: boolean; onClick?: () => void }) {
|
||||
/** tags: 경기 탭에서 녹음 · 기록만 표시 */
|
||||
export function MatchItem({ m, on, onClick, tags }: { m: MatchSummary; on?: boolean; onClick?: () => void; tags?: boolean }) {
|
||||
const voice = m.voice ?? m.participants.length > 0;
|
||||
const dur = m.endedAt ? Math.round((m.endedAt - m.startedAt) / 60000) : null;
|
||||
const res = m.win == null ? '' : m.win ? '승' : '패';
|
||||
const Tag = onClick ? 'button' : 'div';
|
||||
@@ -32,6 +34,19 @@ export function MatchItem({ m, on, onClick }: { m: MatchSummary; on?: boolean; o
|
||||
{dur != null ? ` · ${dur}분` : ''}
|
||||
{m.status === 'live' && <span className="live-dot"> · 진행 중</span>}
|
||||
</div>
|
||||
{tags && (voice || m.source === 'history') && (
|
||||
<div className="m-tags">
|
||||
{voice ? (
|
||||
<span className="m-tag voice" title="디스코드 대화가 녹음된 경기">
|
||||
🎙 녹음
|
||||
</span>
|
||||
) : (
|
||||
<span className="m-tag hist" title="겜녹이가 꺼져 있을 때 한 경기 (Riot 경기 기록에서 가져옴)">
|
||||
경기 기록만
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{res && <span className={`badge ${m.win ? 'b-win' : 'b-loss'}`}>{res}</span>}
|
||||
</Tag>
|
||||
|
||||
@@ -257,7 +257,7 @@ export function TimelinePage() {
|
||||
// 사이드바 경기 목록 · 선택한 경기 상세
|
||||
useEffect(() => {
|
||||
api
|
||||
.matches({ limit: 15, game: f.game === 'valorant' || f.game === 'lol' ? f.game : undefined })
|
||||
.matches({ limit: 15, game: f.game === 'valorant' || f.game === 'lol' ? f.game : undefined, has: 'timeline' })
|
||||
.then(setMatches)
|
||||
.catch(() => {});
|
||||
}, [f.game, epoch]);
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import type { GameType, MatchSummary, User, UserProfile } from '@gvr/shared';
|
||||
import { api } from '../lib/api';
|
||||
import { api, type MatchHas } from '../lib/api';
|
||||
import { useStatus } from '../store/app';
|
||||
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<T>(fn: () => Promise<T>, deps: unknown[]) {
|
||||
const { epoch } = useStatus();
|
||||
@@ -50,18 +51,53 @@ export function UsersPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const PAGE = 50;
|
||||
/** 목소리가 녹음된 경기 (예전 앱은 voice 가 없어 말한 사람으로 본다) */
|
||||
const hasVoice = (m: MatchSummary) => m.voice ?? m.participants.length > 0;
|
||||
const HAS_CHIPS: { has: MatchHas | null; label: string; title: string }[] = [
|
||||
{ has: null, label: '전체 경기', title: '내가 플레이한 경기 전부 (앱이 꺼져 있을 때 한 경기는 Riot 경기 기록에서 가져옴)' },
|
||||
{ has: 'timeline', label: '타임라인 있는 경기', title: '겜녹이가 켜져 있을 때 한 경기 (타임라인에서 대화 · 킬을 같이 볼 수 있음)' },
|
||||
{ has: 'voice', label: '목소리 녹음된 경기', title: '디스코드 대화가 녹음된 경기' },
|
||||
];
|
||||
|
||||
export function MatchesPage() {
|
||||
const [game, setGame] = useState<GameType | null>(null);
|
||||
const [has, setHas] = useState<MatchHas | null>(null);
|
||||
const nav = useNavigate();
|
||||
const { data, err, retry } = useLoad<MatchSummary[]>(() => api.matches({ limit: 50, game: game ?? undefined }), [game]);
|
||||
const { data, err, retry } = useLoad<MatchSummary[]>(() => api.matches({ limit: PAGE, game: game ?? undefined, has: has ?? undefined }), [game, has]);
|
||||
// 더 보기: 지난 쪽 경기들 (필터가 바뀌면 처음부터)
|
||||
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]);
|
||||
const all = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
const out: MatchSummary[] = [];
|
||||
for (const m of [...(data ?? []), ...more.list]) {
|
||||
if (seen.has(m.id)) continue;
|
||||
seen.add(m.id);
|
||||
// 예전 앱은 has 를 모르고 다 보낸다: 목소리 필터는 여기서도 거른다
|
||||
if (has === 'voice' && !hasVoice(m)) continue;
|
||||
out.push(m);
|
||||
}
|
||||
return out;
|
||||
}, [data, more.list, has]);
|
||||
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 })
|
||||
.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 groups = useMemo(() => {
|
||||
const g = new Map<string, MatchSummary[]>();
|
||||
for (const m of data ?? []) {
|
||||
for (const m of all) {
|
||||
const d = fmtDay(m.startedAt);
|
||||
g.set(d, [...(g.get(d) ?? []), m]);
|
||||
}
|
||||
return [...g];
|
||||
}, [data]);
|
||||
}, [all]);
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<div className="page-h-row">
|
||||
@@ -78,19 +114,39 @@ export function MatchesPage() {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="chips-wrap match-has">
|
||||
{HAS_CHIPS.map((c) => (
|
||||
<button key={c.label} className={`chip${has === c.has ? ' on-mint' : ''}`} title={c.title} onClick={() => setHas(c.has)}>
|
||||
{c.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<HistoryImport onDone={retry} />
|
||||
{err != null && <ErrorBox error={err} onRetry={retry} />}
|
||||
{!data && !err && <Spinner />}
|
||||
{data && data.length === 0 && <div className="empty">경기 기록이 없습니다.</div>}
|
||||
{!data && !err && <Spinner label="경기 목록 불러오는 중" />}
|
||||
{data && all.length === 0 && (
|
||||
<div className="empty">
|
||||
{has === 'voice' ? '목소리가 녹음된 경기가 없습니다.' : has === 'timeline' ? '타임라인이 있는 경기가 없습니다.' : '경기 기록이 없습니다.'}
|
||||
</div>
|
||||
)}
|
||||
{groups.map(([day, ms]) => (
|
||||
<section key={day} className="match-day">
|
||||
<h4>{day}</h4>
|
||||
<div className="match-cards">
|
||||
{ms.map((m) => (
|
||||
<MatchItem key={m.id} m={m} onClick={() => nav(`/matches/${encodeURIComponent(m.id)}`)} />
|
||||
<MatchItem key={m.id} m={m} tags onClick={() => nav(`/matches/${encodeURIComponent(m.id)}`)} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
{more.err != null && <ErrorBox error={more.err} onRetry={loadMore} />}
|
||||
{canMore && (
|
||||
<div className="more-row">
|
||||
<button className="btn" onClick={loadMore} disabled={more.busy}>
|
||||
{more.busy ? '불러오는 중…' : '지난 경기 더 보기'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2737,6 +2737,33 @@ button.match:hover {
|
||||
letter-spacing: 1px;
|
||||
margin: 20px 0 8px;
|
||||
}
|
||||
.match-has {
|
||||
margin: 4px 0 2px;
|
||||
}
|
||||
.m-tags {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin-top: 3px;
|
||||
}
|
||||
.m-tag {
|
||||
font-size: 11px;
|
||||
padding: 0 6px;
|
||||
border-radius: 4px;
|
||||
line-height: 17px;
|
||||
}
|
||||
.m-tag.voice {
|
||||
background: #0f2e2c;
|
||||
color: #7fe9e1;
|
||||
}
|
||||
.m-tag.hist {
|
||||
background: #1a2633;
|
||||
color: var(--muted);
|
||||
}
|
||||
.more-row {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin: 18px 0 8px;
|
||||
}
|
||||
.match-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
@@ -3936,6 +3963,21 @@ button.match:hover {
|
||||
}
|
||||
|
||||
/* ── 3D 리플레이 (components/ReplayViewer.tsx) ── */
|
||||
.replay-msg {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.replay-msg b {
|
||||
display: block;
|
||||
margin-bottom: 2px;
|
||||
color: #e6edf3;
|
||||
font-size: 13px;
|
||||
}
|
||||
.replay-msg .mini-btn {
|
||||
flex: none;
|
||||
}
|
||||
.replay-panel {
|
||||
flex: none;
|
||||
}
|
||||
@@ -4486,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);
|
||||
}
|
||||
|
||||
@@ -152,6 +152,10 @@ class SttEngine:
|
||||
if noise.judge_vad(speech_ratio, speech_s, sensitivity):
|
||||
return done("vad")
|
||||
|
||||
# 앱이 게임 중에는 빔 1(가장 가벼움)을 보낸다. 없으면 슬롯 기본값
|
||||
beam = req.get("beam_size")
|
||||
beam = int(beam) if isinstance(beam, (int, float)) and 1 <= int(beam) <= 10 else BEAM.get(slot, 5)
|
||||
|
||||
hotwords = req.get("hotwords") or None
|
||||
hotwords = hotwords if isinstance(hotwords, str) and hotwords.strip() else None
|
||||
|
||||
@@ -161,7 +165,7 @@ class SttEngine:
|
||||
prep.audio,
|
||||
language="ko",
|
||||
task="transcribe",
|
||||
beam_size=BEAM.get(slot, 5),
|
||||
beam_size=beam,
|
||||
word_timestamps=True,
|
||||
vad_filter=True,
|
||||
vad_parameters={"min_silence_duration_ms": VAD_MIN_SILENCE_MS},
|
||||
|
||||
Reference in New Issue
Block a user