Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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)
|
- 설계·계획: [`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/`)
|
- 범인찾기 · 리플레이 동기화 계획서 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)
|
- **제작 완료 보고서 (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.8.2](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.8.2) (`GameVoiceRecorder-1.8.2-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.8.2-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~)
|
## 로그인 · 관리자 (v1.2.0~)
|
||||||
|
|
||||||
|
|||||||
4
app/package-lock.json
generated
4
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "gvr-app",
|
"name": "gvr-app",
|
||||||
"version": "1.8.2",
|
"version": "1.9.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "gvr-app",
|
"name": "gvr-app",
|
||||||
"version": "1.8.2",
|
"version": "1.9.0",
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@discordjs/voice": "^0.19.2",
|
"@discordjs/voice": "^0.19.2",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "gvr-app",
|
"name": "gvr-app",
|
||||||
"productName": "겜녹이",
|
"productName": "겜녹이",
|
||||||
"version": "1.8.2",
|
"version": "1.9.0",
|
||||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||||
"private": true,
|
"private": true,
|
||||||
"main": "dist/main.cjs",
|
"main": "dist/main.cjs",
|
||||||
|
|||||||
@@ -310,7 +310,13 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
|||||||
app.get<{ Querystring: Record<string, string> }>('/api/matches', async (req) => {
|
app.get<{ Querystring: Record<string, string> }>('/api/matches', async (req) => {
|
||||||
const q = req.query;
|
const q = req.query;
|
||||||
return store
|
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));
|
.map((m) => d.games.summary(m));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -75,6 +75,8 @@ export class Bundles {
|
|||||||
const out: Group[] = [];
|
const out: Group[] = [];
|
||||||
for (const m of matches) {
|
for (const m of matches) {
|
||||||
const list = byMatch.get(m.id) ?? [];
|
const list = byMatch.get(m.id) ?? [];
|
||||||
|
// Riot 경기 기록에서 가져오기만 한 경기(녹음 없음)는 기록 묶음으로 보이지 않는다
|
||||||
|
if (m.source === 'history' && !list.length) continue;
|
||||||
const sum = this.games.summary(m);
|
const sum = this.games.summary(m);
|
||||||
const label = `${m.game === 'valorant' ? '발로란트' : '롤'} · ${sum.mode} · ${sum.map.name}`;
|
const label = `${m.game === 'valorant' ? '발로란트' : '롤'} · ${sum.mode} · ${sum.map.name}`;
|
||||||
const score = sum.score ? ` ${sum.score.ally}:${sum.score.enemy}` : '';
|
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);
|
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 ?? []) {
|
for (const m of data.matches ?? []) {
|
||||||
const r = db
|
const r = db
|
||||||
.prepare('INSERT OR IGNORE INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset) VALUES(?,?,?,?,?,?,?,?,?,?,?)')
|
.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);
|
.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;
|
res.added.matches += r.changes;
|
||||||
}
|
}
|
||||||
for (const r of data.rounds ?? [])
|
for (const r of data.rounds ?? [])
|
||||||
|
|||||||
@@ -50,6 +50,8 @@ export interface MatchRow {
|
|||||||
detail: string | null;
|
detail: string | null;
|
||||||
status: string;
|
status: string;
|
||||||
clock_offset: number;
|
clock_offset: number;
|
||||||
|
/** live: 앱이 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 */
|
||||||
|
source: 'live' | 'history';
|
||||||
}
|
}
|
||||||
export interface RoundRow {
|
export interface RoundRow {
|
||||||
match_id: string;
|
match_id: string;
|
||||||
@@ -128,6 +130,9 @@ export class Store {
|
|||||||
|
|
||||||
/** 예전 DB 를 지금 스키마로 맞춘다 (스키마를 바꿀 때마다 여기에 단계 추가) */
|
/** 예전 DB 를 지금 스키마로 맞춘다 (스키마를 바꿀 때마다 여기에 단계 추가) */
|
||||||
private migrate(): void {
|
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 추가 (같은 단어가 여러 묶음에 들어갈 수 있게)
|
// 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;
|
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)) {
|
if (idx && !/UNIQUE\s*\(kind,\s*word,\s*from_text,\s*pack\)/.test(idx.sql)) {
|
||||||
@@ -406,13 +411,14 @@ export class Store {
|
|||||||
detail: null,
|
detail: null,
|
||||||
status: 'live',
|
status: 'live',
|
||||||
clock_offset: 0,
|
clock_offset: 0,
|
||||||
|
source: 'live',
|
||||||
...(cur || {}),
|
...(cur || {}),
|
||||||
...stripUndef(m),
|
...stripUndef(m),
|
||||||
} as MatchRow;
|
} as MatchRow;
|
||||||
this.db
|
this.db
|
||||||
.prepare(
|
.prepare(
|
||||||
`INSERT INTO matches(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)
|
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,
|
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`,
|
result=@result, detail=@detail, status=@status, clock_offset=@clock_offset`,
|
||||||
)
|
)
|
||||||
@@ -422,9 +428,15 @@ export class Store {
|
|||||||
getMatch(id: string): MatchRow | undefined {
|
getMatch(id: string): MatchRow | undefined {
|
||||||
return this.db.prepare('SELECT * FROM matches WHERE id=?').get(id) as 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 where: string[] = [];
|
||||||
const args: any[] = [];
|
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) {
|
if (opts.game) {
|
||||||
where.push('game=?');
|
where.push('game=?');
|
||||||
args.push(opts.game);
|
args.push(opts.game);
|
||||||
|
|||||||
@@ -82,7 +82,9 @@ CREATE TABLE IF NOT EXISTS matches (
|
|||||||
result TEXT,
|
result TEXT,
|
||||||
detail TEXT,
|
detail TEXT,
|
||||||
status TEXT NOT NULL DEFAULT 'live',
|
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);
|
CREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);
|
||||||
|
|
||||||
|
|||||||
106
app/src/core/games/history.ts
Normal file
106
app/src/core/games/history.ts
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private store: Store,
|
||||||
|
private src: HistorySource,
|
||||||
|
private opts: HistoryOptions,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** 주기 확인: 앞 실행에서 everyMs 가 지났고 게임 중이 아니면 백그라운드로 돌린다 */
|
||||||
|
maybeRun(everyMs: number, firstDelayMs = 60000): void {
|
||||||
|
const now = Date.now();
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
try {
|
||||||
|
const fullKey = `history_full:${this.src.game}:${acct}`;
|
||||||
|
const full = !!this.store.meta(fullKey);
|
||||||
|
const skip = this.skipped();
|
||||||
|
const todo: string[] = [];
|
||||||
|
for (let start = 0; start < this.opts.max; start += this.opts.pageSize) {
|
||||||
|
if (!this.src.idle()) return 0;
|
||||||
|
const p = await this.src.page(start, this.opts.pageSize);
|
||||||
|
if (p === 'retry') return 0;
|
||||||
|
const fresh = p.ids.filter((id) => !skip.has(id) && !this.store.getMatch(id) && !todo.includes(id));
|
||||||
|
todo.push(...fresh);
|
||||||
|
if (!p.ids.length || p.ids.length < this.opts.pageSize || (p.total !== null && start + this.opts.pageSize >= p.total)) break;
|
||||||
|
// 한 번 끝까지 훑은 뒤에는 아는 경기만 나오는 쪽에서 멈춘다
|
||||||
|
if (full && !fresh.length) break;
|
||||||
|
}
|
||||||
|
if (todo.length) log.info(`${this.src.game} 경기 기록: 새 경기 ${todo.length}개 가져오는 중`);
|
||||||
|
let added = 0;
|
||||||
|
for (const id of todo) {
|
||||||
|
if (!this.src.idle()) {
|
||||||
|
log.info(`${this.src.game} 경기 기록: 게임이 시작돼 멈춤 (${added}/${todo.length})`);
|
||||||
|
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)));
|
||||||
|
}
|
||||||
|
await new Promise((res) => setTimeout(res, this.opts.gapMs));
|
||||||
|
}
|
||||||
|
// 끝(또는 max)까지 다 받았다: 다음부터는 새 경기만 본다
|
||||||
|
this.store.setMeta(fullKey, '1');
|
||||||
|
if (added) log.info(`${this.src.game} 경기 기록: ${added}개 저장`);
|
||||||
|
return added;
|
||||||
|
} finally {
|
||||||
|
this.running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { logger } from '../util/log.js';
|
|||||||
import { lolObjectIcon } from './assets.js';
|
import { lolObjectIcon } from './assets.js';
|
||||||
import { basicAuth, findLcu, request } from './riot.js';
|
import { basicAuth, findLcu, request } from './riot.js';
|
||||||
import type { AdapterHost, GameAdapter } from './types.js';
|
import type { AdapterHost, GameAdapter } from './types.js';
|
||||||
|
import { HistorySync } from './history.js';
|
||||||
|
|
||||||
const log = logger('lol');
|
const log = logger('lol');
|
||||||
|
|
||||||
@@ -71,8 +72,42 @@ export class LolAdapter implements GameAdapter {
|
|||||||
/** 게임 클라이언트 API 마지막 값 (지금 게임 상태 표시용) */
|
/** 게임 클라이언트 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 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 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 {
|
start(): void {
|
||||||
if (this.timer) return;
|
if (this.timer) return;
|
||||||
@@ -87,6 +122,10 @@ export class LolAdapter implements GameAdapter {
|
|||||||
status() {
|
status() {
|
||||||
return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined };
|
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 {
|
liveGame(): LiveGame {
|
||||||
const enabled = this.host.settings().games.lol;
|
const enabled = this.host.settings().games.lol;
|
||||||
@@ -442,6 +481,7 @@ export class LolAdapter implements GameAdapter {
|
|||||||
log.info('롤 클라이언트(LCU) 연결');
|
log.info('롤 클라이언트(LCU) 연결');
|
||||||
const me = await this.lcuGet<any>('/lol-summoner/v1/current-summoner');
|
const me = await this.lcuGet<any>('/lol-summoner/v1/current-summoner');
|
||||||
if (me?.puuid) this.host.selfAccount(me.puuid, `${me.gameName}#${me.tagLine}`);
|
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 ?? ''}`;
|
if (me?.gameName) this.selfRiotId = `${me.gameName}#${me.tagLine ?? ''}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -459,6 +499,7 @@ export class LolAdapter implements GameAdapter {
|
|||||||
this.queueName = q ? (lolModeKo(q.id) ?? q.description ?? null) : null;
|
this.queueName = q ? (lolModeKo(q.id) ?? q.description ?? null) : null;
|
||||||
}
|
}
|
||||||
if (phase === 'ChampSelect' || phase === 'InProgress' || phase === 'PreEndOfGame' || phase === 'EndOfGame') await this.pollLcuChat(phase);
|
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> {
|
private async pollLcuChat(phase: string): Promise<void> {
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ export class GameManager implements AdapterHost {
|
|||||||
private watchLive(): void {
|
private watchLive(): void {
|
||||||
if (this.liveTimer) return;
|
if (this.liveTimer) return;
|
||||||
this.liveTimer = setInterval(() => {
|
this.liveTimer = setInterval(() => {
|
||||||
|
void this.stt.setGameActive(this.adapters.some((a) => this.settings().games[a.game] && a.gameRunning()));
|
||||||
const live = this.live();
|
const live = this.live();
|
||||||
const key = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest));
|
const key = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest));
|
||||||
if (key === this.lastLive) return;
|
if (key === this.lastLive) return;
|
||||||
@@ -103,6 +104,22 @@ export class GameManager implements AdapterHost {
|
|||||||
this.emitMatch(m.id);
|
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 {
|
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void {
|
||||||
const cur = this.store.getMatch(id);
|
const cur = this.store.getMatch(id);
|
||||||
if (!cur) return;
|
if (!cur) return;
|
||||||
@@ -182,6 +199,8 @@ export class GameManager implements AdapterHost {
|
|||||||
score: result.score,
|
score: result.score,
|
||||||
status: m.status as MatchSummary['status'],
|
status: m.status as MatchSummary['status'],
|
||||||
participants,
|
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),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ export interface AdapterHost {
|
|||||||
worker: WorkerClient;
|
worker: WorkerClient;
|
||||||
settings(): Settings;
|
settings(): Settings;
|
||||||
matchStarted(m: MatchStart): void;
|
matchStarted(m: MatchStart): void;
|
||||||
|
/** Riot 경기 기록에서 가져온 경기 행 만들기 (이미 있으면 그대로) */
|
||||||
|
historyMatch(m: MatchStart): void;
|
||||||
/** 경기 정보 갱신 (상세가 채워졌을 때 등) */
|
/** 경기 정보 갱신 (상세가 채워졌을 때 등) */
|
||||||
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void;
|
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void;
|
||||||
matchEnded(id: string, endedAt: number): void;
|
matchEnded(id: string, endedAt: number): void;
|
||||||
@@ -39,6 +41,8 @@ export interface GameAdapter {
|
|||||||
start(): void;
|
start(): void;
|
||||||
stop(): void;
|
stop(): void;
|
||||||
status(): { connected: boolean; inMatch: boolean; detail?: string };
|
status(): { connected: boolean; inMatch: boolean; detail?: string };
|
||||||
|
/** 게임이 켜져 있어 GPU 를 쓰고 있는가 (발로란트: 게임 실행 중 · 롤: 경기 중) */
|
||||||
|
gameRunning(): boolean;
|
||||||
/** 지금 게임 상태 (자세히) */
|
/** 지금 게임 상태 (자세히) */
|
||||||
liveGame(): LiveGame;
|
liveGame(): LiveGame;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { logger } from '../util/log.js';
|
|||||||
import type { GameAssets } from './assets.js';
|
import type { GameAssets } from './assets.js';
|
||||||
import { basicAuth, readLockfile, request, riotClientLockfilePath, type Lockfile } from './riot.js';
|
import { basicAuth, readLockfile, request, riotClientLockfilePath, type Lockfile } from './riot.js';
|
||||||
import type { AdapterHost, GameAdapter } from './types.js';
|
import type { AdapterHost, GameAdapter } from './types.js';
|
||||||
|
import { HistorySync } from './history.js';
|
||||||
|
|
||||||
const log = logger('valorant');
|
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 detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
|
||||||
private polling = false;
|
private polling = false;
|
||||||
private lastErr = '';
|
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 {
|
start(): void {
|
||||||
if (this.timer) return;
|
if (this.timer) return;
|
||||||
@@ -91,6 +135,10 @@ export class ValorantAdapter implements GameAdapter {
|
|||||||
status() {
|
status() {
|
||||||
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
|
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
|
||||||
}
|
}
|
||||||
|
/** 발로란트는 메뉴에서도 게임 화면을 그린다: 게임이 켜져 있으면(내 발로란트 상태가 있으면) 켜짐 */
|
||||||
|
gameRunning(): boolean {
|
||||||
|
return !!this.match || (!!this.auth && !!this.presence);
|
||||||
|
}
|
||||||
|
|
||||||
liveGame(): LiveGame {
|
liveGame(): LiveGame {
|
||||||
const p = this.presence;
|
const p = this.presence;
|
||||||
@@ -206,9 +254,11 @@ export class ValorantAdapter implements GameAdapter {
|
|||||||
if (a) {
|
if (a) {
|
||||||
await this.pollPresence(a);
|
await this.pollPresence(a);
|
||||||
if (this.match) await this.pollChat(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();
|
await this.pollDetails();
|
||||||
this.lastErr = '';
|
this.lastErr = '';
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ export interface Settings {
|
|||||||
modelsDir: string | null;
|
modelsDir: string | null;
|
||||||
reprocessAfterMatch: boolean;
|
reprocessAfterMatch: boolean;
|
||||||
gameVramReserveMb: number;
|
gameVramReserveMb: number;
|
||||||
|
/** 게임이 켜져 있는 동안 GPU 를 아낀다: 실시간 모델만 가볍게(빔 1) · 쉬어 가며, 정밀 모델 변환은 게임을 끈 뒤로 (v1.9.0) */
|
||||||
|
gameSaver: boolean;
|
||||||
};
|
};
|
||||||
audio: {
|
audio: {
|
||||||
targetLufs: number;
|
targetLufs: number;
|
||||||
@@ -111,6 +113,7 @@ export function defaultSettings(): Settings {
|
|||||||
modelsDir: null,
|
modelsDir: null,
|
||||||
reprocessAfterMatch: true,
|
reprocessAfterMatch: true,
|
||||||
gameVramReserveMb: 3072,
|
gameVramReserveMb: 3072,
|
||||||
|
gameSaver: true,
|
||||||
},
|
},
|
||||||
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
|
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
|
||||||
dictionary: {
|
dictionary: {
|
||||||
|
|||||||
@@ -100,6 +100,12 @@ export class SttPipeline {
|
|||||||
return c ? Number(c) : null;
|
return c ? Number(c) : null;
|
||||||
}
|
}
|
||||||
private inMatch = false;
|
private inMatch = false;
|
||||||
|
/** 게임(발로란트 · 롤 경기)이 켜져 있다 (GameManager 가 2초마다 알려 줌) */
|
||||||
|
private gameActive = false;
|
||||||
|
/** 게임 중 GPU 아끼기: 켜져 있고 게임 중일 때 */
|
||||||
|
private saving(): boolean {
|
||||||
|
return this.gameActive && this.settings().stt.gameSaver !== false;
|
||||||
|
}
|
||||||
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
|
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
|
||||||
private bothFit = true;
|
private bothFit = true;
|
||||||
status: SttStatus = {
|
status: SttStatus = {
|
||||||
@@ -143,10 +149,46 @@ export class SttPipeline {
|
|||||||
this.bothFit = false;
|
this.bothFit = false;
|
||||||
}
|
}
|
||||||
await this.load('realtime', s.realtimeModel);
|
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();
|
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>> {
|
private async installed(): Promise<Set<string>> {
|
||||||
try {
|
try {
|
||||||
const r = await this.worker.request('models', {}, 30000);
|
const r = await this.worker.request('models', {}, 30000);
|
||||||
@@ -223,6 +265,13 @@ export class SttPipeline {
|
|||||||
this.inMatch = false;
|
this.inMatch = false;
|
||||||
const s = this.settings().stt;
|
const s = this.settings().stt;
|
||||||
if (!s.reprocessAfterMatch || s.preciseModel === s.realtimeModel) return;
|
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') await this.load('precise', s.preciseModel);
|
||||||
if (this.status.slots.precise.state !== 'loaded') return;
|
if (this.status.slots.precise.state !== 'loaded') return;
|
||||||
const rows = this.store.realtimeUtterancesInRange(from, to);
|
const rows = this.store.realtimeUtterancesInRange(from, to);
|
||||||
@@ -232,6 +281,11 @@ export class SttPipeline {
|
|||||||
|
|
||||||
private pickSlot(job: Job): Slot | null {
|
private pickSlot(job: Job): Slot | null {
|
||||||
const { realtime, precise } = this.status.slots;
|
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 (job.slot === 'precise') return precise.state === 'loaded' ? 'precise' : null;
|
||||||
// 경기 밖이고 정밀 모델이 올라와 있으면 처음부터 정밀 모델로
|
// 경기 밖이고 정밀 모델이 올라와 있으면 처음부터 정밀 모델로
|
||||||
if (!this.inMatch && precise.state === 'loaded' && this.queue.length < 20) return 'precise';
|
if (!this.inMatch && precise.state === 'loaded' && this.queue.length < 20) return 'precise';
|
||||||
@@ -255,6 +309,7 @@ export class SttPipeline {
|
|||||||
this.busy = true;
|
this.busy = true;
|
||||||
this.processing = job.id;
|
this.processing = job.id;
|
||||||
this.status.processing = job.id;
|
this.status.processing = job.id;
|
||||||
|
const t0 = Date.now();
|
||||||
this.run(job, this.pickSlot(job)!)
|
this.run(job, this.pickSlot(job)!)
|
||||||
.catch((e) => log.error('STT 작업 오류', e))
|
.catch((e) => log.error('STT 작업 오류', e))
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
@@ -267,7 +322,9 @@ export class SttPipeline {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.warn('변환 뒤 처리 실패', 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,
|
target_lufs: s.audio.targetLufs,
|
||||||
noise_sensitivity: s.audio.noiseSensitivity,
|
noise_sensitivity: s.audio.noiseSensitivity,
|
||||||
denoise: s.audio.denoise,
|
denoise: s.audio.denoise,
|
||||||
|
// 게임 중에는 빔 1 (빔 3 보다 가볍다. 경기 뒤 정밀 모델이 다시 변환한다)
|
||||||
|
...(this.saving() && slot === 'realtime' ? { beam_size: 1 } : {}),
|
||||||
},
|
},
|
||||||
5 * 60000,
|
5 * 60000,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -173,9 +173,15 @@ export class Timeline {
|
|||||||
if (q.match) {
|
if (q.match) {
|
||||||
where.push('e.match_id = ?');
|
where.push('e.match_id = ?');
|
||||||
args.push(q.match);
|
args.push(q.match);
|
||||||
} else if (q.game) {
|
} else {
|
||||||
where.push('e.game = ?');
|
if (q.game) {
|
||||||
args.push(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) {
|
if (q.users?.length) {
|
||||||
// 선택하지 않은 (디스코드에 연결된) 유저가 주인공인 이벤트만 뺀다. 라운드·오브젝트·상대 킬처럼 유저가 없는 이벤트는 남긴다.
|
// 선택하지 않은 (디스코드에 연결된) 유저가 주인공인 이벤트만 뺀다. 라운드·오브젝트·상대 킬처럼 유저가 없는 이벤트는 남긴다.
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ const opt = (name: string) => argv.find((a) => a.startsWith(`--${name}=`))?.spli
|
|||||||
const SMOKE = flag('smoke');
|
const SMOKE = flag('smoke');
|
||||||
|
|
||||||
app.setAppUserModelId('kr.tkrmagid.gvr');
|
app.setAppUserModelId('kr.tkrmagid.gvr');
|
||||||
|
// 설정 창은 글자 · 버튼뿐이라 GPU 로 그릴 필요가 없다. 게임 · 브라우저와 GPU 를 나눠 쓰지 않게 끈다 (v1.9.0)
|
||||||
|
app.disableHardwareAcceleration();
|
||||||
if (!SMOKE && !app.requestSingleInstanceLock()) {
|
if (!SMOKE && !app.requestSingleInstanceLock()) {
|
||||||
app.quit();
|
app.quit();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ function defaults(): Settings {
|
|||||||
modelsDir: null,
|
modelsDir: null,
|
||||||
reprocessAfterMatch: true,
|
reprocessAfterMatch: true,
|
||||||
gameVramReserveMb: 3072,
|
gameVramReserveMb: 3072,
|
||||||
|
gameSaver: true,
|
||||||
},
|
},
|
||||||
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
|
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
|
||||||
dictionary: {
|
dictionary: {
|
||||||
|
|||||||
@@ -184,6 +184,12 @@ export function SttTab() {
|
|||||||
<div className="warn-text small">⚠ RTX 50 시리즈(Blackwell)에서 int8 계열은 cuBLAS 오류 사례가 있습니다. 문제가 생기면 float16으로 돌려 주세요.</div>
|
<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="경기가 끝나면 정밀 모델로 다시 변환" 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="두 게임 중 큰 값 · 실측 후 조정">
|
<Line label="게임용 VRAM 예약" hint="두 게임 중 큰 값 · 실측 후 조정">
|
||||||
<NumInput value={s.gameVramReserveMb} min={0} max={24576} step={256} width={90} suffix="MB" onCommit={(n) => save({ stt: { gameVramReserveMb: n } })} />
|
<NumInput value={s.gameVramReserveMb} min={0} max={24576} step={256} width={90} suffix="MB" onCommit={(n) => save({ stt: { gameVramReserveMb: n } })} />
|
||||||
</Line>
|
</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 tl = new Timeline(store);
|
||||||
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
|
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
|
||||||
const sttCalls: string[] = [];
|
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'));
|
const assets = new GameAssets(path.join(dir, 'cache'));
|
||||||
(assets as any).refresh = async () => undefined; // 네트워크 없이
|
(assets as any).refresh = async () => undefined; // 네트워크 없이
|
||||||
assets.lol = {
|
assets.lol = {
|
||||||
|
|||||||
115
app/test/history.test.ts
Normal file
115
app/test/history.test.ts
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
// 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];
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -18,6 +18,12 @@ export interface MockState {
|
|||||||
lolGameId: number;
|
lolGameId: number;
|
||||||
lolHistoryReady: boolean;
|
lolHistoryReady: boolean;
|
||||||
lolStart: number;
|
lolStart: number;
|
||||||
|
/** 발로란트 경기 기록 (새것부터): MatchID → 경기 시작 시각 */
|
||||||
|
valHistory: { MatchID: string; GameStartTime: number }[];
|
||||||
|
/** 롤 경기 기록 (LCU, 새것부터) */
|
||||||
|
lolHistoryList: { gameId: number; gameCreation: number }[];
|
||||||
|
/** 요청 기록 (경로) */
|
||||||
|
hits: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function startMockRiot(dir: string) {
|
export async function startMockRiot(dir: string) {
|
||||||
@@ -38,6 +44,9 @@ export async function startMockRiot(dir: string) {
|
|||||||
lolGameId: 7001,
|
lolGameId: 7001,
|
||||||
lolHistoryReady: false,
|
lolHistoryReady: false,
|
||||||
lolStart: 0,
|
lolStart: 0,
|
||||||
|
valHistory: [],
|
||||||
|
lolHistoryList: [],
|
||||||
|
hits: [],
|
||||||
};
|
};
|
||||||
const password = 'pw-test';
|
const password = 'pw-test';
|
||||||
const presence = () => {
|
const presence = () => {
|
||||||
@@ -52,7 +61,7 @@ export async function startMockRiot(dir: string) {
|
|||||||
};
|
};
|
||||||
return Buffer.from(JSON.stringify(priv)).toString('base64');
|
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
|
// ---- Riot Client local
|
||||||
[/^\/entitlements\/v1\/token$/, () => [200, { accessToken: 'acc-token', token: 'ent-token', subject: SELF, issuer: 'x' }]],
|
[/^\/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' }] }],
|
() => [200, { MatchID: st.valMatchId, MapID: ASCENT, Players: [{ Subject: SELF, TeamID: 'Blue', CharacterID: 'add6443a-41bd-e414-f6ad-e58d267f4e95' }] }],
|
||||||
],
|
],
|
||||||
// ---- pd
|
// ---- 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
|
// ---- LoL Live Client Data
|
||||||
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
|
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
|
||||||
// ---- LCU
|
// ---- 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$/, () => [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-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-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, {}])],
|
[/^\/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) => {
|
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) {
|
for (const [re, fn] of routes) {
|
||||||
const m = url.pathname.match(re);
|
const m = url.pathname.match(re);
|
||||||
if (!m) continue;
|
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.writeHead(code, { 'content-type': 'application/json' });
|
||||||
res.end(JSON.stringify(body));
|
res.end(JSON.stringify(body));
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -287,6 +287,15 @@ VOICE E2E PASS
|
|||||||
- 화면: 목 서버 + 헤드리스 크롬(playwright-core)으로 내 정보(이름 저장 · 머리글 반영 · 색 · 녹음 제외 · 되돌리기) · 관리 페이지(새 버전 링크 · 이름 바꾸기 · 앱 유저 등록) · 모바일 390px 확인, 콘솔 오류 0
|
- 화면: 목 서버 + 헤드리스 크롬(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 에 새 버전 안내)
|
- 배포: 사이트 서버 다시 배포 (`/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.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)
|
## v1.8.1 — 변환기: 무기 상태의 주인을 그 시각 주인으로 (2026-10-18)
|
||||||
|
|
||||||
- 고침: 무기 상태(재장전 · 사격 등)의 주인을 장비의 마지막 주인으로 정해, 무기를 넘겨받으면 넘기기 전 상태까지 새 주인 것이 되던 문제 → 인벤토리 기록 시간표에서 상태가 생긴 시각의 주인 (`EquipOwners`)
|
- 고침: 무기 상태(재장전 · 사격 등)의 주인을 장비의 마지막 주인으로 정해, 무기를 넘겨받으면 넘기기 전 상태까지 새 주인 것이 되던 문제 → 인벤토리 기록 시간표에서 상태가 생긴 시각의 주인 (`EquipOwners`)
|
||||||
|
|||||||
@@ -165,6 +165,10 @@ export interface MatchSummary {
|
|||||||
score: { ally: number; enemy: number } | null;
|
score: { ally: number; enemy: number } | null;
|
||||||
status: 'live' | 'pending_detail' | 'complete';
|
status: 'live' | 'pending_detail' | 'complete';
|
||||||
participants: string[];
|
participants: string[];
|
||||||
|
/** live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0 앱부터, 없으면 live) */
|
||||||
|
source?: 'live' | 'history';
|
||||||
|
/** 목소리가 녹음된 경기 (잡음 제외, v1.9.0 앱부터) */
|
||||||
|
voice?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MatchPlayer {
|
export interface MatchPlayer {
|
||||||
|
|||||||
@@ -580,6 +580,34 @@ function genReplayDemo(file) {
|
|||||||
}
|
}
|
||||||
if (process.env.GVR_MOCK_REPLAY) genReplayDemo(process.env.GVR_MOCK_REPLAY);
|
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 = {
|
export const db = {
|
||||||
users: USERS,
|
users: USERS,
|
||||||
|
|||||||
@@ -115,7 +115,10 @@ function timeline(q) {
|
|||||||
return { items: page, next: items.length > limit ? enc(page[page.length - 1]) : null };
|
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) {
|
function userProfile(id) {
|
||||||
const user = db.users.find((u) => u.id === id);
|
const user = db.users.find((u) => u.id === id);
|
||||||
@@ -335,7 +338,9 @@ async function handle(req, res) {
|
|||||||
const game = q.get('game');
|
const game = q.get('game');
|
||||||
const before = q.get('before') ? Number(q.get('before')) : Infinity;
|
const before = q.get('before') ? Number(q.get('before')) : Infinity;
|
||||||
const limit = Number(q.get('limit') ?? 20);
|
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);
|
return json(res, 200, list);
|
||||||
}
|
}
|
||||||
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
|
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
|
||||||
@@ -347,7 +352,8 @@ async function handle(req, res) {
|
|||||||
if ((m = p.match(/^\/api\/matches\/([^/]+)\/replay$/))) {
|
if ((m = p.match(/^\/api\/matches\/([^/]+)\/replay$/))) {
|
||||||
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
||||||
if (!mt) return json(res, 404, { error: 'not_found' });
|
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' });
|
res.writeHead(200, { 'content-type': 'application/json' });
|
||||||
return fs.createReadStream(mt.replayPath).pipe(res);
|
return fs.createReadStream(mt.replayPath).pipe(res);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
|||||||
const [replay, setReplay] = useState<ReplayFile | null>(null);
|
const [replay, setReplay] = useState<ReplayFile | null>(null);
|
||||||
const [err, setErr] = useState<unknown>(null);
|
const [err, setErr] = useState<unknown>(null);
|
||||||
const [converting, setConverting] = useState(false);
|
const [converting, setConverting] = useState(false);
|
||||||
|
// 새로고침을 누를 때마다 1씩 올려 리플레이를 다시 묻는다
|
||||||
|
const [reload, setReload] = useState(0);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open || replay) return;
|
if (!open || replay) return;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
@@ -22,7 +24,7 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
|||||||
// 처음 열면 게임 PC 가 리플레이를 변환한다 (보통 10초 안팎). 변환 중(202)이면 3초 뒤 다시 묻는다 (5분까지)
|
// 처음 열면 게임 PC 가 리플레이를 변환한다 (보통 10초 안팎). 변환 중(202)이면 3초 뒤 다시 묻는다 (5분까지)
|
||||||
const ask = (tries: number) =>
|
const ask = (tries: number) =>
|
||||||
api
|
api
|
||||||
.replay(m.id)
|
.replay(m.id, reload > 0)
|
||||||
.then((r) => {
|
.then((r) => {
|
||||||
if (!alive) return;
|
if (!alive) return;
|
||||||
if ('status' in r && r.status === 'converting') {
|
if ('status' in r && r.status === 'converting') {
|
||||||
@@ -46,12 +48,17 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
|||||||
alive = false;
|
alive = false;
|
||||||
if (timer) clearTimeout(timer);
|
if (timer) clearTimeout(timer);
|
||||||
};
|
};
|
||||||
}, [open, m.id, replay]);
|
}, [open, m.id, replay, reload]);
|
||||||
const sync = useMemo(() => (replay ? computeSync(m, replay) : null), [m, replay]);
|
const sync = useMemo(() => (replay ? computeSync(m, replay) : null), [m, replay]);
|
||||||
// replay_not_found: 앱이 리플레이를 못 찾음. 다른 404: 이 앱 버전에는 리플레이 기능이 아직 없음
|
// replay_not_found: 앱이 리플레이를 못 찾음. 다른 404: 이 앱 버전에는 리플레이 기능이 아직 없음
|
||||||
const missing = err instanceof ApiError && err.status === 404 && err.code === 'replay_not_found';
|
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 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 failed = err instanceof ApiError && err.status === 422 && err.code === 'replay_failed';
|
||||||
|
const refresh = (
|
||||||
|
<button className="mini-btn" onClick={() => setReload((n) => n + 1)}>
|
||||||
|
새로고침
|
||||||
|
</button>
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<Panel
|
<Panel
|
||||||
className={`replay-panel${open ? ' open' : ''}`}
|
className={`replay-panel${open ? ' open' : ''}`}
|
||||||
@@ -67,15 +74,31 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
|||||||
발로란트에서 이 경기 리플레이를 내려받으면 선수 10명의 움직임을 3D로 보면서 그때 나눈 대화를 같이 들을 수 있습니다.
|
발로란트에서 이 경기 리플레이를 내려받으면 선수 10명의 움직임을 3D로 보면서 그때 나눈 대화를 같이 들을 수 있습니다.
|
||||||
</div>
|
</div>
|
||||||
) : missing ? (
|
) : missing ? (
|
||||||
<div className="dim small">
|
<div className="replay-msg">
|
||||||
이 경기 리플레이가 아직 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받으면 게임 PC 앱이 찾아서 변환합니다 (몇 초 걸림).
|
<div>
|
||||||
|
<b>리플레이 파일 없음</b>
|
||||||
|
<div className="dim small">
|
||||||
|
게임 PC 에 이 경기의 리플레이 파일이 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받은 뒤 새로고침을 누르면 게임 PC 앱이 찾아서
|
||||||
|
변환합니다 (몇 초 걸림).
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{refresh}
|
||||||
</div>
|
</div>
|
||||||
) : appTooOld ? (
|
) : appTooOld ? (
|
||||||
<div className="dim small">지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.</div>
|
<div className="replay-msg">
|
||||||
|
<div className="dim small">지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.</div>
|
||||||
|
{refresh}
|
||||||
|
</div>
|
||||||
) : failed ? (
|
) : 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 ? (
|
) : 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 ? (
|
) : !replay || !sync ? (
|
||||||
<Spinner label={converting ? '게임 PC 가 리플레이를 변환하는 중 (처음 한 번, 10초 안팎)' : '리플레이 불러오는 중'} />
|
<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> {
|
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||||
let res: Response;
|
let res: Response;
|
||||||
try {
|
try {
|
||||||
@@ -162,10 +165,13 @@ export const api = {
|
|||||||
hideNoise: 1,
|
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)}`),
|
match: (id: string) => request<MatchDetail>(`/api/matches/${encodeURIComponent(id)}`),
|
||||||
/** 발로란트 리플레이(.vrf)에서 뽑은 재생 데이터. 없으면 404 replay_not_found, 게임 PC 가 변환 중이면 202 { status: 'converting' } */
|
/** 발로란트 리플레이(.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)}`),
|
culpritMatches: (o: { game?: GameType; limit?: number } = {}) => request<CulpritMatchItem[]>(`/api/culprit/matches${qs(o)}`),
|
||||||
culpritMatch: (id: string) => request<CulpritMatchInfo>(`/api/culprit/matches/${encodeURIComponent(id)}`),
|
culpritMatch: (id: string) => request<CulpritMatchInfo>(`/api/culprit/matches/${encodeURIComponent(id)}`),
|
||||||
culpritBudget: () => request<CulpritBudget>('/api/culprit/budget'),
|
culpritBudget: () => request<CulpritBudget>('/api/culprit/budget'),
|
||||||
|
|||||||
@@ -15,7 +15,9 @@ export function toggleUser(f: Filters, users: User[], id: string): string[] {
|
|||||||
return all.every((x) => nextSet.includes(x)) ? [] : nextSet;
|
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 dur = m.endedAt ? Math.round((m.endedAt - m.startedAt) / 60000) : null;
|
||||||
const res = m.win == null ? '' : m.win ? '승' : '패';
|
const res = m.win == null ? '' : m.win ? '승' : '패';
|
||||||
const Tag = onClick ? 'button' : 'div';
|
const Tag = onClick ? 'button' : 'div';
|
||||||
@@ -32,6 +34,19 @@ export function MatchItem({ m, on, onClick }: { m: MatchSummary; on?: boolean; o
|
|||||||
{dur != null ? ` · ${dur}분` : ''}
|
{dur != null ? ` · ${dur}분` : ''}
|
||||||
{m.status === 'live' && <span className="live-dot"> · 진행 중</span>}
|
{m.status === 'live' && <span className="live-dot"> · 진행 중</span>}
|
||||||
</div>
|
</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>
|
</div>
|
||||||
{res && <span className={`badge ${m.win ? 'b-win' : 'b-loss'}`}>{res}</span>}
|
{res && <span className={`badge ${m.win ? 'b-win' : 'b-loss'}`}>{res}</span>}
|
||||||
</Tag>
|
</Tag>
|
||||||
|
|||||||
@@ -257,7 +257,7 @@ export function TimelinePage() {
|
|||||||
// 사이드바 경기 목록 · 선택한 경기 상세
|
// 사이드바 경기 목록 · 선택한 경기 상세
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
api
|
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)
|
.then(setMatches)
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}, [f.game, epoch]);
|
}, [f.game, epoch]);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
import { Link, useNavigate, useParams } from 'react-router';
|
import { Link, useNavigate, useParams } from 'react-router';
|
||||||
import type { GameType, MatchSummary, User, UserProfile } from '@gvr/shared';
|
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 { useStatus } from '../store/app';
|
||||||
import { fmtDuration, fmtDay } from '../lib/format';
|
import { fmtDuration, fmtDay } from '../lib/format';
|
||||||
import { sfx } from '../lib/sfx';
|
import { sfx } from '../lib/sfx';
|
||||||
@@ -50,18 +50,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() {
|
export function MatchesPage() {
|
||||||
const [game, setGame] = useState<GameType | null>(null);
|
const [game, setGame] = useState<GameType | null>(null);
|
||||||
|
const [has, setHas] = useState<MatchHas | null>(null);
|
||||||
const nav = useNavigate();
|
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 groups = useMemo(() => {
|
||||||
const g = new Map<string, MatchSummary[]>();
|
const g = new Map<string, MatchSummary[]>();
|
||||||
for (const m of data ?? []) {
|
for (const m of all) {
|
||||||
const d = fmtDay(m.startedAt);
|
const d = fmtDay(m.startedAt);
|
||||||
g.set(d, [...(g.get(d) ?? []), m]);
|
g.set(d, [...(g.get(d) ?? []), m]);
|
||||||
}
|
}
|
||||||
return [...g];
|
return [...g];
|
||||||
}, [data]);
|
}, [all]);
|
||||||
return (
|
return (
|
||||||
<main className="page-pad">
|
<main className="page-pad">
|
||||||
<div className="page-h-row">
|
<div className="page-h-row">
|
||||||
@@ -78,19 +113,38 @@ export function MatchesPage() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</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>
|
||||||
{err != null && <ErrorBox error={err} onRetry={retry} />}
|
{err != null && <ErrorBox error={err} onRetry={retry} />}
|
||||||
{!data && !err && <Spinner />}
|
{!data && !err && <Spinner />}
|
||||||
{data && data.length === 0 && <div className="empty">경기 기록이 없습니다.</div>}
|
{data && all.length === 0 && (
|
||||||
|
<div className="empty">
|
||||||
|
{has === 'voice' ? '목소리가 녹음된 경기가 없습니다.' : has === 'timeline' ? '타임라인이 있는 경기가 없습니다.' : '경기 기록이 없습니다.'}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{groups.map(([day, ms]) => (
|
{groups.map(([day, ms]) => (
|
||||||
<section key={day} className="match-day">
|
<section key={day} className="match-day">
|
||||||
<h4>{day}</h4>
|
<h4>{day}</h4>
|
||||||
<div className="match-cards">
|
<div className="match-cards">
|
||||||
{ms.map((m) => (
|
{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>
|
</div>
|
||||||
</section>
|
</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>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2737,6 +2737,33 @@ button.match:hover {
|
|||||||
letter-spacing: 1px;
|
letter-spacing: 1px;
|
||||||
margin: 20px 0 8px;
|
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 {
|
.match-cards {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||||
@@ -3936,6 +3963,21 @@ button.match:hover {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* ── 3D 리플레이 (components/ReplayViewer.tsx) ── */
|
/* ── 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 {
|
.replay-panel {
|
||||||
flex: none;
|
flex: none;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -152,6 +152,10 @@ class SttEngine:
|
|||||||
if noise.judge_vad(speech_ratio, speech_s, sensitivity):
|
if noise.judge_vad(speech_ratio, speech_s, sensitivity):
|
||||||
return done("vad")
|
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 = req.get("hotwords") or None
|
||||||
hotwords = hotwords if isinstance(hotwords, str) and hotwords.strip() else None
|
hotwords = hotwords if isinstance(hotwords, str) and hotwords.strip() else None
|
||||||
|
|
||||||
@@ -161,7 +165,7 @@ class SttEngine:
|
|||||||
prep.audio,
|
prep.audio,
|
||||||
language="ko",
|
language="ko",
|
||||||
task="transcribe",
|
task="transcribe",
|
||||||
beam_size=BEAM.get(slot, 5),
|
beam_size=beam,
|
||||||
word_timestamps=True,
|
word_timestamps=True,
|
||||||
vad_filter=True,
|
vad_filter=True,
|
||||||
vad_parameters={"min_silence_duration_ms": VAD_MIN_SILENCE_MS},
|
vad_parameters={"min_silence_duration_ms": VAD_MIN_SILENCE_MS},
|
||||||
|
|||||||
Reference in New Issue
Block a user