From adc1c66f47ff44907f6cc3fa288d002cf720dd90 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sat, 17 Oct 2026 14:55:38 +0900 Subject: [PATCH] =?UTF-8?q?v1.5.0:=20=EA=B2=8C=EC=9E=84=20PC=20=EC=95=B1?= =?UTF-8?q?=EC=9D=B4=20=EB=B0=9C=EB=A1=9C=EB=9E=80=ED=8A=B8=20=EB=A6=AC?= =?UTF-8?q?=ED=94=8C=EB=A0=88=EC=9D=B4(.vrf)=EB=A5=BC=20=EC=B0=BE=EC=95=84?= =?UTF-8?q?=20=EB=B3=80=ED=99=98=ED=95=B4=20=EC=82=AC=EC=9D=B4=ED=8A=B8=20?= =?UTF-8?q?3D=20=EC=9E=AC=EC=83=9D=EA=B8=B0=EB=A1=9C=20=EB=B3=B4=EB=83=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 앱: %LOCALAPPDATA%\VALORANT\Saved 아래 <경기 ID>.vrf 를 찾아 gvr-replay.exe 로 변환, GVR-Data/replays/<경기 ID>.json.gz 로 보관 (원본 · 앱 버전이 같으면 다시 변환하지 않음) - GET /api/matches/:id/replay: gzip JSON, 처음 변환이 15초를 넘으면 202 converting, 실패 422 replay_failed(이유), 변환기 없음 500. GET /api/replays: 찾은 리플레이 목록 - 변환은 한 번에 하나, 낮은 우선순위. 실패한 파일은 다시 내려받을 때까지 다시 하지 않음 - 중계: content-encoding 이 있는 응답은 바이너리 조각으로 (gzip 이 깨지지 않게) - 사이트: 변환 중(202)이면 3초마다 다시 묻고 '변환하는 중' 표시, 변환 실패 안내 - 빌드: win-ci 가 .NET 10 SDK 로 gvr-replay.exe(단일 파일)를 만들어 resources/replay 에 넣고, 시험 리플레이로 변환기 · 포터블 앱 안 변환까지 확인 (smoke GVR_SMOKE_VRF) Co-Authored-By: Claude Opus 5.5 --- app/package-lock.json | 4 +- app/package.json | 9 +- app/src/core/api/server.ts | 28 ++++ app/src/core/cli.ts | 1 + app/src/core/index.ts | 7 +- app/src/core/relay/client.ts | 5 +- app/src/core/replays.ts | 203 ++++++++++++++++++++++++ app/src/main/main.ts | 19 ++- app/src/main/paths.ts | 7 + app/test/replays.test.ts | 184 +++++++++++++++++++++ site/web/src/components/ReplayPanel.tsx | 33 +++- site/web/src/lib/api.ts | 4 +- tools/win-ci/gvr.ps1 | 43 +++++ 13 files changed, 530 insertions(+), 17 deletions(-) create mode 100644 app/src/core/replays.ts create mode 100644 app/test/replays.test.ts diff --git a/app/package-lock.json b/app/package-lock.json index 1023131..1e40d3a 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -1,12 +1,12 @@ { "name": "gvr-app", - "version": "1.4.3", + "version": "1.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gvr-app", - "version": "1.4.3", + "version": "1.5.0", "license": "UNLICENSED", "dependencies": { "@discordjs/voice": "^0.19.2", diff --git a/app/package.json b/app/package.json index b9fc543..eea9575 100644 --- a/app/package.json +++ b/app/package.json @@ -1,7 +1,7 @@ { "name": "gvr-app", "productName": "겜녹이", - "version": "1.4.3", + "version": "1.5.0", "description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록", "private": true, "main": "dist/main.cjs", @@ -76,6 +76,13 @@ "from": "../worker/dist/gvr-worker", "to": "worker" }, + { + "from": "../tools/replay-extract/out/win", + "to": "replay", + "filter": [ + "gvr-replay.exe" + ] + }, { "from": "../assets/app", "to": "brand", diff --git a/app/src/core/api/server.ts b/app/src/core/api/server.ts index 932541e..3a34749 100644 --- a/app/src/core/api/server.ts +++ b/app/src/core/api/server.ts @@ -10,6 +10,7 @@ import type { Settings } from '../settings.js'; import { safeJson, type Timeline, type TimelineQuery } from '../timeline.js'; import type { Bus } from '../util/events.js'; import { BundleError, type Bundles } from '../bundles.js'; +import type { Replays } from '../replays.js'; import { logger } from '../util/log.js'; const log = logger('api'); @@ -37,6 +38,8 @@ export interface ApiDeps { version: string; /** 기록 묶음 (없으면 /api/bundles 없음) */ bundles?: Bundles; + /** 발로란트 리플레이 (없으면 /api/replays 없음) */ + replays?: Replays; } const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']); @@ -321,6 +324,31 @@ export async function buildApi(d: ApiDeps): Promise { }; }); + // 3D 리플레이 (v1.5.0): 이 PC 에 내려받은 발로란트 리플레이(.vrf)를 변환해 보낸다 (gzip JSON). + // 처음 열 때 변환하느라 15초 넘게 걸리면 202 converting → 사이트가 몇 초 뒤 다시 묻는다 + app.get<{ Params: { id: string } }>('/api/matches/:id/replay', async (req, reply) => { + const m = store.getMatch(req.params.id); + if (!m) return reply.code(404).send({ error: 'not_found' }); + if (m.game !== 'valorant' || !d.replays) return reply.code(404).send({ error: 'replay_not_found' }); + const r = await d.replays.get(m.id.replace(/^val-/, '')); + if (r.state === 'ready') + return reply.header('content-type', 'application/json; charset=utf-8').header('content-encoding', 'gzip').header('cache-control', 'private, max-age=3600').send(fs.readFileSync(r.file)); + if (r.state === 'converting') return reply.code(202).send({ status: 'converting' }); + if (r.state === 'missing') return reply.code(404).send({ error: 'replay_not_found' }); + if (r.state === 'no_tool') return reply.code(500).send({ error: 'replay_tool_missing', message: '리플레이 변환기가 없습니다 (앱을 다시 설치해 주세요)' }); + return reply.code(422).send({ error: 'replay_failed', message: r.error }); + }); + + // 이 PC 에서 찾은 리플레이 목록 (경기 기록이 있는지 · 변환했는지) + app.get('/api/replays', async (_req, reply) => { + if (!d.replays) return reply.code(404).send({ error: 'not_found' }); + const rp = d.replays; + return rp.list().map((r) => { + const match = store.getMatch(`val-${r.matchId}`) ?? null; + return { matchId: r.matchId, file: path.basename(r.file), size: r.size, mtime: r.mtimeMs, match: match ? match.id : null, converted: !!rp.cached(r) }; + }); + }); + app.patch<{ Params: { id: string }; Body: { text?: string } }>('/api/utterances/:id', async (req, reply) => { const u = store.getUtterance(req.params.id); if (!u) return reply.code(404).send({ error: 'not_found' }); diff --git a/app/src/core/cli.ts b/app/src/core/cli.ts index f35d75e..13aa1b0 100644 --- a/app/src/core/cli.ts +++ b/app/src/core/cli.ts @@ -33,6 +33,7 @@ async function main() { worker, version: process.env.npm_package_version || '1.0.0', apiPort: Number(process.env.GVR_API_PORT || 0), + replayTool: process.env.GVR_REPLAY_TOOL || path.join(root, '..', 'tools', 'replay-extract', 'out', 'linux', 'gvr-replay'), }); const shutdown = async () => { await core.stop(); diff --git a/app/src/core/index.ts b/app/src/core/index.ts index 0b8fe68..ad98724 100644 --- a/app/src/core/index.ts +++ b/app/src/core/index.ts @@ -14,6 +14,7 @@ import { Announcer } from './discord/tts.js'; import { GameAssets } from './games/assets.js'; import { GameManager } from './games/manager.js'; import { RelayClient } from './relay/client.js'; +import { defaultReplayDirs, Replays } from './replays.js'; import { Retention } from './retention.js'; import { SettingsStore, resolvePaths, type SecretCodec } from './settings.js'; import { SttPipeline } from './stt/pipeline.js'; @@ -37,6 +38,8 @@ export interface CoreOptions { apiPort?: number; /** 겜녹이 봇 중계에서 로그인 만료 · 등록 해제를 알려 왔을 때 (Electron: 바로 다시 확인해서 잠근다) */ onBotUnauthorized?: () => void; + /** 발로란트 리플레이 변환기 (gvr-replay.exe). 없으면 3D 리플레이를 보내지 않는다 */ + replayTool?: string | null; } export type Core = Awaited>; @@ -91,6 +94,7 @@ export async function startCore(opts: CoreOptions) { }); const culprit = new Culprit(store, timeline, games); + const replays = new Replays({ dirs: defaultReplayDirs, tool: opts.replayTool ?? null, cacheDir: () => path.join(opts.dataDir, 'replays'), version: opts.version }); const api: FastifyInstance = await buildApi({ store, timeline, @@ -101,6 +105,7 @@ export async function startCore(opts: CoreOptions) { settings: S, trainingDir: () => paths().training, version: opts.version, + replays, bundles: new Bundles(store, games, () => paths().audio, opts.version, (ids) => ids.forEach((id) => audioNames.refresh(id))), overviewExtra: () => ({ guild: bot.state.guild, @@ -189,5 +194,5 @@ export async function startCore(opts: CoreOptions) { store.close(); }; - return { settings, store, bus, timeline, dict, worker, stt, assets, games, audioNames, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir }; + return { settings, store, bus, timeline, dict, worker, stt, assets, games, audioNames, recorder, bot, api, relay, retention, replays, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir }; } diff --git a/app/src/core/relay/client.ts b/app/src/core/relay/client.ts index cbeb8a6..fdcbba4 100644 --- a/app/src/core/relay/client.ts +++ b/app/src/core/relay/client.ts @@ -161,12 +161,13 @@ export class RelayClient { if (req.user) headers['x-gvr-user'] = encodeURIComponent(JSON.stringify(req.user)); const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: bin ?? req.body ?? undefined }); const outHeaders: Record = {}; - for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length', 'content-disposition']) { + for (const k of ['content-type', 'content-encoding', 'content-range', 'accept-ranges', 'cache-control', 'content-length', 'content-disposition']) { const v = res.headers[k]; if (v !== undefined) outHeaders[k] = String(v); } const ct = outHeaders['content-type'] || ''; - if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream') || ct.startsWith('application/zip')) { + // 압축한 본문(리플레이 gzip JSON)도 글자로 바꾸면 깨지므로 바이너리로 보낸다 + if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream') || ct.startsWith('application/zip') || outHeaders['content-encoding']) { this.send({ t: 'res_head', id: req.id, status: res.statusCode, headers: outHeaders }); const idBuf = Buffer.from(req.id, 'utf8'); const head = Buffer.alloc(4); diff --git a/app/src/core/replays.ts b/app/src/core/replays.ts new file mode 100644 index 0000000..86195d2 --- /dev/null +++ b/app/src/core/replays.ts @@ -0,0 +1,203 @@ +import { execFile } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { logger } from './util/log.js'; + +const log = logger('replay'); + +/** 발로란트 경기 ID (리플레이 파일 이름이 `<경기 ID>.vrf`) */ +const MATCH_ID = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i; +/** 리플레이를 찾지 않는 하위 폴더 (Saved 아래 로그 · 오류 덤프 · 설정 · 브라우저 캐시) */ +const SKIP_DIRS = new Set(['logs', 'crashes', 'config', 'webcache', 'webcache_4430', 'cefcache']); + +export interface ReplayFileInfo { + matchId: string; + file: string; + size: number; + mtimeMs: number; +} + +export type ReplayState = + | { state: 'ready'; file: string } + | { state: 'converting' } + | { state: 'missing' } + | { state: 'no_tool' } + | { state: 'failed'; error: string }; + +export interface ReplaysOptions { + /** 리플레이(.vrf)를 찾을 폴더들 */ + dirs: () => string[]; + /** 변환기 (gvr-replay.exe). 없으면 변환하지 않는다 */ + tool: string | null; + /** 변환 결과 보관 폴더 (<경기 ID>.json.gz) */ + cacheDir: () => string; + /** 변환기가 바뀌면(앱 업데이트) 다시 변환한다 */ + version: string; + /** 변환 시간 제한 (기본 3분) */ + timeoutMs?: number; + /** 사이트 요청이 변환을 기다리는 시간 (기본 15초, 사이트 서버는 20초 뒤 시간 초과) */ + waitMs?: number; +} + +/** 발로란트가 리플레이를 내려받는 곳: %LOCALAPPDATA%\VALORANT\Saved (보통 Demos\<경기 ID>.vrf). GVR_REPLAY_DIRS 로 바꿀 수 있다 */ +export function defaultReplayDirs(): string[] { + const env = process.env.GVR_REPLAY_DIRS; + if (env) return env.split(path.delimiter).filter(Boolean); + const local = process.env.LOCALAPPDATA; + return local ? [path.join(local, 'VALORANT', 'Saved')] : []; +} + +/** + * 발로란트 리플레이(.vrf) 찾기 · 변환 (docs/dev/replay-3d.md). + * 사이트에서 경기의 3D 리플레이를 열면 그때 이 PC 에서 `.vrf` 를 찾아 gvr-replay 로 변환하고 gzip 으로 보관해 둔다. + * 변환은 한 번에 하나, 낮은 우선순위로 (게임 중일 수 있다). 실패하면 같은 파일 · 같은 앱 버전으로는 다시 하지 않는다. + */ +export class Replays { + private scanCache: { at: number; list: ReplayFileInfo[] } | null = null; + private running = new Map>(); + private failed = new Map(); + private queue: Promise = Promise.resolve(); + + constructor(private o: ReplaysOptions) {} + + /** 찾은 리플레이 (새것부터). 10초 동안은 다시 훑지 않는다 */ + list(): ReplayFileInfo[] { + if (this.scanCache && Date.now() - this.scanCache.at < 10000) return this.scanCache.list; + const byId = new Map(); + const walk = (dir: string, depth: number) => { + let ents: fs.Dirent[]; + try { + ents = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const e of ents) { + const p = path.join(dir, e.name); + if (e.isDirectory()) { + if (depth > 0 && !SKIP_DIRS.has(e.name.toLowerCase())) walk(p, depth - 1); + continue; + } + if (!(e.isFile() || e.isSymbolicLink()) || !e.name.toLowerCase().endsWith('.vrf')) continue; + const m = MATCH_ID.exec(e.name); + if (!m) continue; + try { + const st = fs.statSync(p); + const info = { matchId: m[1].toLowerCase(), file: p, size: st.size, mtimeMs: Math.floor(st.mtimeMs) }; + const prev = byId.get(info.matchId); + if (!prev || prev.mtimeMs < info.mtimeMs) byId.set(info.matchId, info); + } catch { + /* 그 사이 지워짐 */ + } + } + }; + for (const d of this.o.dirs()) walk(d, 3); + const list = [...byId.values()].sort((a, b) => b.mtimeMs - a.mtimeMs); + this.scanCache = { at: Date.now(), list }; + return list; + } + + find(matchId: string): ReplayFileInfo | null { + const id = matchId.toLowerCase(); + return this.list().find((r) => r.matchId === id) ?? null; + } + + /** 변환 결과 파일 (원본 · 변환기가 그대로일 때만) */ + cached(r: ReplayFileInfo): string | null { + const out = this.outFile(r.matchId); + try { + if (fs.readFileSync(out + '.src', 'utf8') === this.stamp(r) && fs.existsSync(out)) return out; + } catch { + /* 아직 없음 */ + } + return null; + } + + /** 경기 리플레이 상태. 변환이 필요하면 시작하고 waitMs 까지 기다린다 (그때까지 안 끝나면 converting) */ + async get(matchId: string, waitMs = this.o.waitMs ?? 15000): Promise { + this.scanCache = null; // 사이트에서 열 때는 방금 내려받은 파일도 보이게 + const r = this.find(matchId); + if (!r) return { state: 'missing' }; + const done = this.cached(r); + if (done) return { state: 'ready', file: done }; + const key = this.stamp(r); + const err = this.failed.get(key); + if (err) return { state: 'failed', error: err }; + if (!this.o.tool || !fs.existsSync(this.o.tool)) return { state: 'no_tool' }; + let job = this.running.get(r.matchId); + if (!job) { + job = this.enqueue(r).finally(() => this.running.delete(r.matchId)); + this.running.set(r.matchId, job); + } + if (waitMs > 0) await Promise.race([job, new Promise((res) => setTimeout(res, waitMs).unref?.())]); + if (this.running.has(r.matchId)) return { state: 'converting' }; + const out = this.cached(r); + if (out) return { state: 'ready', file: out }; + return { state: 'failed', error: this.failed.get(key) ?? '변환 결과 없음' }; + } + + private outFile(matchId: string): string { + return path.join(this.o.cacheDir(), `${matchId}.json.gz`); + } + + private stamp(r: ReplayFileInfo): string { + return `${r.size}:${r.mtimeMs}:${this.o.version}`; + } + + private enqueue(r: ReplayFileInfo): Promise { + const run = this.queue.then(() => this.convert(r)); + this.queue = run.catch(() => undefined); + return run; + } + + private async convert(r: ReplayFileInfo): Promise { + const dir = this.o.cacheDir(); + fs.mkdirSync(dir, { recursive: true }); + const out = this.outFile(r.matchId); + const tmpJson = path.join(dir, `${r.matchId}.json.tmp-${process.pid}`); + const t0 = Date.now(); + log.info(`리플레이 변환 시작 ${r.matchId} (${(r.size / 1048576).toFixed(1)}MB)`); + try { + const summary = await this.run([r.file, tmpJson]); + if (!summary?.ok) throw new Error(summary?.error || '변환기가 결과를 알리지 않음'); + const gz = zlib.gzipSync(fs.readFileSync(tmpJson), { level: 6 }); + fs.writeFileSync(out + '.tmp', gz); + fs.renameSync(out + '.tmp', out); + fs.writeFileSync(out + '.src', this.stamp(r)); + log.info( + `리플레이 변환 완료 ${r.matchId}: ${summary.map ?? '?'} · 선수 ${summary.players} · 라운드 ${summary.rounds} · 킬 ${summary.kills} · ${((Date.now() - t0) / 1000).toFixed(1)}초 · ${(gz.length / 1048576).toFixed(1)}MB`, + ); + } catch (e: any) { + const msg = String(e?.message ?? e).slice(0, 300); + this.failed.set(this.stamp(r), msg); + log.warn(`리플레이 변환 실패 ${r.matchId}: ${msg}`); + } finally { + fs.rmSync(tmpJson, { force: true }); + } + } + + /** 변환기 실행. 마지막 줄 JSON 요약을 돌려준다 */ + private run(args: string[]): Promise { + return new Promise((resolve, reject) => { + const child = execFile(this.o.tool!, args, { timeout: this.o.timeoutMs ?? 180000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => { + const last = String(stdout).trim().split(/\r?\n/).pop() ?? ''; + let summary: any = null; + try { + summary = JSON.parse(last); + } catch { + /* JSON 아님 */ + } + if (summary) return resolve(summary); + if (err) return reject(new Error((err as any).killed ? '변환 시간 초과' : String(stderr).trim().split(/\r?\n/).pop() || err.message)); + reject(new Error('변환기 출력 없음')); + }); + // 게임 중일 수 있으니 낮은 우선순위로 + try { + if (child.pid) os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL); + } catch { + /* 권한 없음 */ + } + }); + } +} diff --git a/app/src/main/main.ts b/app/src/main/main.ts index 107a8e7..247f34a 100644 --- a/app/src/main/main.ts +++ b/app/src/main/main.ts @@ -11,7 +11,7 @@ import { hardenTlsEnv, secureFetch } from '../core/util/secure-http.js'; import { Finetuner } from './finetune.js'; import type { AuthView } from './api-types.js'; import { buildState, registerIpc } from './ipc.js'; -import { brandDir, rendererDir, resolveDataDir, resourcesDir, workerCommand } from './paths.js'; +import { brandDir, rendererDir, replayToolPath, resolveDataDir, resourcesDir, workerCommand } from './paths.js'; // 인증서 검증을 끄는 환경변수(NODE_TLS_REJECT_UNAUTHORIZED=0)는 무시한다. fuses 로 막지 못하는 변수라 가장 먼저 지운다 hardenTlsEnv(); @@ -217,7 +217,7 @@ async function smoke(): Promise { const a = await new AppAuth(st, { version: app.getVersion(), openUrl: () => undefined }).check(); out.auth = a.status; out.builtinBot = st.hasBuiltinBot; - const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: st }); + const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: st, replayTool: replayToolPath() }); out.codec = c.settings.codecName; out.botMode = c.settings.get().discord.botMode; const ready = await new Promise((res) => { @@ -244,7 +244,18 @@ async function smoke(): Promise { out.dict = c.store.listDict().length; out.renderer = fs.existsSync(path.join(rendererDir(), 'index.html')); out.tray = fs.existsSync(path.join(brandDir(), 'tray.png')); - code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray && out.siteTls === true ? 0 : 1; + // 3D 리플레이 변환기 (v1.5.0): 배포본 안에 있어야 한다. GVR_SMOKE_VRF 가 있으면 실제로 변환해 본다 + out.replayTool = fs.existsSync(replayToolPath()); + if (process.env.GVR_SMOKE_VRF) { + const vrf = process.env.GVR_SMOKE_VRF; + const id = path.basename(vrf).replace(/\.vrf$/i, ''); + process.env.GVR_REPLAY_DIRS = path.dirname(vrf); + const t0 = Date.now(); + const r = await c.replays.get(id, 170000); + out.replayConvert = r.state === 'ready' ? { ok: true, ms: Date.now() - t0, gz: fs.statSync(r.file).size } : r; + } + const replayOk = out.replayTool === true && (!process.env.GVR_SMOKE_VRF || (out.replayConvert as any)?.ok === true); + code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray && out.siteTls === true && replayOk ? 0 : 1; await c.stop(); } catch (e: any) { out.error = e.stack || e.message; @@ -293,7 +304,7 @@ function startApp(): Promise { starting ??= (async () => { try { // 겜녹이 봇 중계가 로그인 만료 · 등록 해제를 알려 오면 10분을 기다리지 않고 바로 확인해서 잠근다 - const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check() }); + const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check(), replayTool: replayToolPath() }); core = c; void syncNames(); ft = new Finetuner(c, pushState); diff --git a/app/src/main/paths.ts b/app/src/main/paths.ts index fff1e62..d68d9be 100644 --- a/app/src/main/paths.ts +++ b/app/src/main/paths.ts @@ -55,3 +55,10 @@ export function workerCommand(): { cmd: string; args: string[]; cwd?: string } { export function finetuneScriptsDir(): string { return app.isPackaged ? path.join(process.resourcesPath, 'worker', '_internal', 'gvr_worker', 'finetune') : path.join(appRoot, '..', 'worker', 'gvr_worker', 'finetune'); } + +/** 발로란트 리플레이 변환기 (tools/replay-extract, 배포본은 resources/replay/gvr-replay.exe) */ +export function replayToolPath(): string { + if (process.env.GVR_REPLAY_TOOL) return process.env.GVR_REPLAY_TOOL; + if (app.isPackaged) return path.join(process.resourcesPath, 'replay', process.platform === 'win32' ? 'gvr-replay.exe' : 'gvr-replay'); + return path.join(appRoot, '..', 'tools', 'replay-extract', 'out', process.platform === 'win32' ? 'win/gvr-replay.exe' : 'linux/gvr-replay'); +} diff --git a/app/test/replays.test.ts b/app/test/replays.test.ts new file mode 100644 index 0000000..bcda767 --- /dev/null +++ b/app/test/replays.test.ts @@ -0,0 +1,184 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import WebSocket from 'ws'; +import { Store } from '../src/core/db/db.ts'; +import { buildApi } from '../src/core/api/server.ts'; +import { Timeline } from '../src/core/timeline.ts'; +import { Bus } from '../src/core/util/events.ts'; +import { Replays } from '../src/core/replays.ts'; +import { RelayClient } from '../src/core/relay/client.ts'; + +const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-replay-')); +const ID = '4145f041-7d83-4785-ac4b-b532154f14a4'; +const ID2 = '0e1f2a3b-0000-4000-8000-000000000002'; + +/** 가짜 변환기: 호출 횟수를 세고, 모드 파일에 따라 성공 · 실패 · 느림 */ +function fakeTool(dir: string): { tool: string; calls: () => number; mode: (m: 'ok' | 'fail' | 'slow') => void } { + const tool = path.join(dir, 'gvr-replay'); + const count = path.join(dir, 'calls'); + const modeFile = path.join(dir, 'mode'); + fs.writeFileSync(modeFile, 'ok'); + fs.writeFileSync( + tool, + `#!/bin/sh +echo x >> "${count}" +mode=$(cat "${modeFile}") +if [ "$mode" = fail ]; then echo '{"ok":false,"error":"InvalidDataException: bad chunk"}'; exit 1; fi +if [ "$mode" = slow ]; then sleep 2; fi +printf '{"format":"gvr-replay","v":1,"matchId":"%s","players":[]}' "$(basename "$1" .vrf)" > "$2" +echo '{"ok":true,"map":"/Game/Maps/Infinity/Infinity","players":10,"rounds":20,"kills":146}' +`, + { mode: 0o755 }, + ); + return { tool, calls: () => (fs.existsSync(count) ? fs.readFileSync(count, 'utf8').split('\n').filter(Boolean).length : 0), mode: (m) => fs.writeFileSync(modeFile, m) }; +} + +function setup(waitMs = 15000) { + const dir = tmp(); + const saved = path.join(dir, 'VALORANT', 'Saved'); + const demos = path.join(saved, 'Demos'); + fs.mkdirSync(demos, { recursive: true }); + const t = fakeTool(dir); + const replays = new Replays({ dirs: () => [saved], tool: t.tool, cacheDir: () => path.join(dir, 'GVR-Data', 'replays'), version: '1.5.0', waitMs }); + const store = new Store(path.join(dir, 'db.sqlite')); + store.upsertMatch({ id: `val-${ID}`, game: 'valorant', started_at: Date.now() - 3600000 }); + store.upsertMatch({ id: `val-${ID2}`, game: 'valorant', started_at: Date.now() - 7200000 }); + store.upsertMatch({ id: 'lol-KR_1', game: 'lol', started_at: Date.now() - 7200000 }); + return { dir, saved, demos, replays, store, ...t }; +} + +const api = (s: ReturnType) => + buildApi({ + store: s.store, + timeline: new Timeline(s.store), + games: {} as any, + dict: {} as any, + culprit: {} as any, + bus: new Bus(), + settings: () => ({}) as any, + trainingDir: () => path.join(s.dir, 'training'), + overviewExtra: () => ({ guild: null, recording: {} as any }), + version: 'test', + replays: s.replays, + }); + +test('리플레이 찾기: Saved 아래 <경기 ID>.vrf (하위 폴더 포함), 로그 폴더 · 이름이 다른 파일은 무시', () => { + const s = setup(); + fs.writeFileSync(path.join(s.demos, `${ID.toUpperCase()}.vrf`), 'a'); + fs.mkdirSync(path.join(s.demos, 'old'), { recursive: true }); + fs.writeFileSync(path.join(s.demos, 'old', `${ID2}.vrf`), 'b'); + fs.writeFileSync(path.join(s.demos, 'notes.vrf'), 'c'); + fs.mkdirSync(path.join(s.saved, 'Logs'), { recursive: true }); + fs.writeFileSync(path.join(s.saved, 'Logs', '11111111-1111-4111-8111-111111111111.vrf'), 'd'); + const ids = s.replays.list().map((r) => r.matchId); + assert.deepEqual(ids.sort(), [ID, ID2].sort()); + assert.equal(s.replays.find(ID.toUpperCase())?.matchId, ID); +}); + +test('3D 리플레이 API: 처음 열면 변환해서 gzip JSON, 다음부터는 보관본 (변환 한 번)', async () => { + const s = setup(); + const app = await api(s); + const miss = await app.inject({ url: `/api/matches/val-${ID}/replay` }); + assert.equal(miss.statusCode, 404); + assert.equal(miss.json().error, 'replay_not_found'); + fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf'); + const r = await app.inject({ url: `/api/matches/val-${ID}/replay` }); + assert.equal(r.statusCode, 200); + assert.equal(r.headers['content-encoding'], 'gzip'); + assert.match(String(r.headers['content-type']), /application\/json/); + const body = JSON.parse(zlib.gunzipSync(r.rawPayload).toString('utf8')); + assert.equal(body.format, 'gvr-replay'); + assert.equal(body.matchId, ID); + const again = await app.inject({ url: `/api/matches/val-${ID}/replay` }); + assert.equal(again.statusCode, 200); + assert.equal(s.calls(), 1, '두 번째는 변환하지 않는다'); + // 목록: 경기 기록과 변환 여부 + const list = (await app.inject({ url: '/api/replays' })).json(); + assert.deepEqual(list.map((x: any) => [x.matchId, x.match, x.converted]), [[ID, `val-${ID}`, true]]); + // 롤 경기 · 없는 경기 + assert.equal((await app.inject({ url: '/api/matches/lol-KR_1/replay' })).json().error, 'replay_not_found'); + assert.equal((await app.inject({ url: '/api/matches/val-nope/replay' })).statusCode, 404); +}); + +test('변환 실패는 422 로 이유를 알리고, 같은 파일은 다시 변환하지 않는다 (파일이 바뀌면 다시)', async () => { + const s = setup(); + const app = await api(s); + const vrf = path.join(s.demos, `${ID}.vrf`); + fs.writeFileSync(vrf, 'broken'); + s.mode('fail'); + const r = await app.inject({ url: `/api/matches/val-${ID}/replay` }); + assert.equal(r.statusCode, 422); + assert.equal(r.json().error, 'replay_failed'); + assert.match(r.json().message, /bad chunk/); + await app.inject({ url: `/api/matches/val-${ID}/replay` }); + assert.equal(s.calls(), 1); + // 다시 내려받음 (크기 · 시각이 바뀜) → 다시 변환 + s.mode('ok'); + fs.writeFileSync(vrf, 'fixed replay'); + fs.utimesSync(vrf, new Date(), new Date(Date.now() + 5000)); + const ok = await app.inject({ url: `/api/matches/val-${ID}/replay` }); + assert.equal(ok.statusCode, 200); + assert.equal(s.calls(), 2); +}); + +test('변환이 기다리는 시간보다 길면 202 converting, 끝나면 200 (같은 파일을 두 번 변환하지 않음)', async () => { + const s = setup(300); + const app = await api(s); + fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf'); + s.mode('slow'); + const r1 = await app.inject({ url: `/api/matches/val-${ID}/replay` }); + assert.equal(r1.statusCode, 202); + assert.equal(r1.json().status, 'converting'); + const r2 = await app.inject({ url: `/api/matches/val-${ID}/replay` }); + assert.equal(r2.statusCode, 202); + let last = r2; + for (let i = 0; i < 20 && last.statusCode === 202; i++) { + await new Promise((res) => setTimeout(res, 300)); + last = await app.inject({ url: `/api/matches/val-${ID}/replay` }); + } + assert.equal(last.statusCode, 200); + assert.equal(s.calls(), 1); +}); + +test('변환기가 없으면 500 replay_tool_missing', async () => { + const s = setup(); + const replays = new Replays({ dirs: () => [s.saved], tool: path.join(s.dir, 'none.exe'), cacheDir: () => path.join(s.dir, 'c'), version: '1' }); + fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf'); + assert.deepEqual(await replays.get(ID), { state: 'no_tool' }); +}); + +test('중계: gzip 리플레이는 바이너리 조각 + content-encoding 으로 사이트 서버에 간다', async () => { + const s = setup(); + const app = await api(s); + fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf'); + const relay = new RelayClient(app, new Bus(), () => ({ serverUrl: 'https://x', deviceId: null, deviceKey: null, name: 'pc', version: 't', guildId: null })); + const sent: any[] = []; + (relay as any).ws = { readyState: WebSocket.OPEN, bufferedAmount: 0, send: (m: any) => sent.push(m) }; + await (relay as any).handle({ t: 'req', id: 'r1', method: 'GET', path: `/api/matches/val-${ID}/replay`, headers: {}, user: { id: 'u', name: 'u', avatar: null }, body: null }); + const head = JSON.parse(sent[0]); + assert.equal(head.t, 'res_head'); + assert.equal(head.status, 200); + assert.equal(head.headers['content-encoding'], 'gzip'); + const chunks = sent.slice(1, -1).map((b: Buffer) => b.subarray(4 + b.readUInt32BE(0))); + assert.equal(JSON.parse(sent.at(-1)).t, 'res_end'); + assert.equal(JSON.parse(zlib.gunzipSync(Buffer.concat(chunks)).toString()).matchId, ID); +}); + +test('실제 변환기 (tools/replay-extract 리눅스 빌드 + 13.08 리플레이가 있을 때만)', { skip: !fs.existsSync(path.join(os.homedir(), 'work/vrf/match.vrf')) || !fs.existsSync(path.resolve(import.meta.dirname, '../../tools/replay-extract/out/linux/gvr-replay')) }, async () => { + if (!process.env.DOTNET_ROOT && fs.existsSync(path.join(os.homedir(), '.dotnet'))) process.env.DOTNET_ROOT = path.join(os.homedir(), '.dotnet'); + const dir = tmp(); + const demos = path.join(dir, 'Demos'); + fs.mkdirSync(demos); + fs.symlinkSync(path.join(os.homedir(), 'work/vrf/match.vrf'), path.join(demos, `${ID}.vrf`)); + const replays = new Replays({ dirs: () => [dir], tool: path.resolve(import.meta.dirname, '../../tools/replay-extract/out/linux/gvr-replay'), cacheDir: () => path.join(dir, 'c'), version: '1' }); + const r = await replays.get(ID, 120000); + assert.equal(r.state, 'ready'); + const j = JSON.parse(zlib.gunzipSync(fs.readFileSync((r as any).file)).toString()); + assert.equal(j.matchId, ID); + assert.equal(j.players.length, 10); + assert.ok(j.kills.length > 100); +}); diff --git a/site/web/src/components/ReplayPanel.tsx b/site/web/src/components/ReplayPanel.tsx index a5c7c8f..e0d0ddb 100644 --- a/site/web/src/components/ReplayPanel.tsx +++ b/site/web/src/components/ReplayPanel.tsx @@ -12,22 +12,43 @@ export function ReplayPanel({ m }: { m: MatchDetail }) { const [open, setOpen] = useState(false); const [replay, setReplay] = useState(null); const [err, setErr] = useState(null); + const [converting, setConverting] = useState(false); useEffect(() => { if (!open || replay) return; let alive = true; + let timer: ReturnType | undefined; setErr(null); - api - .replay(m.id) - .then((r) => alive && setReplay(r)) - .catch((e) => alive && setErr(e)); + // 처음 열면 게임 PC 가 리플레이를 변환한다 (보통 10초 안팎). 변환 중(202)이면 3초 뒤 다시 묻는다 (5분까지) + const ask = (tries: number) => + api + .replay(m.id) + .then((r) => { + if (!alive) return; + if ('status' in r && r.status === 'converting') { + setConverting(true); + if (tries >= 100) setErr(new Error('게임 PC 가 리플레이 변환을 끝내지 못했습니다')); + else timer = setTimeout(() => ask(tries + 1), 3000); + return; + } + setConverting(false); + setReplay(r as ReplayFile); + }) + .catch((e) => { + if (!alive) return; + setConverting(false); + setErr(e); + }); + void ask(0); return () => { alive = false; + if (timer) clearTimeout(timer); }; }, [open, m.id, replay]); 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'; return ( ) : appTooOld ? (
지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.
+ ) : failed ? ( +
게임 PC 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다 (게임 PC 앱 로그에 이유가 남습니다).
) : err ? (
리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}
) : !replay || !sync ? ( - + ) : ( }> diff --git a/site/web/src/lib/api.ts b/site/web/src/lib/api.ts index 232906a..e52f177 100644 --- a/site/web/src/lib/api.ts +++ b/site/web/src/lib/api.ts @@ -136,8 +136,8 @@ export const api = { ), matches: (o: { game?: GameType; limit?: number; before?: number } = {}) => request(`/api/matches${qs(o)}`), match: (id: string) => request(`/api/matches/${encodeURIComponent(id)}`), - /** 발로란트 리플레이(.vrf)에서 뽑은 재생 데이터. 없으면 404 replay_not_found */ - replay: (id: string) => request(`/api/matches/${encodeURIComponent(id)}/replay`), + /** 발로란트 리플레이(.vrf)에서 뽑은 재생 데이터. 없으면 404 replay_not_found, 게임 PC 가 변환 중이면 202 { status: 'converting' } */ + replay: (id: string) => request(`/api/matches/${encodeURIComponent(id)}/replay`), culpritMatches: (o: { game?: GameType; limit?: number } = {}) => request(`/api/culprit/matches${qs(o)}`), culpritMatch: (id: string) => request(`/api/culprit/matches/${encodeURIComponent(id)}`), culpritBudget: () => request('/api/culprit/budget'), diff --git a/tools/win-ci/gvr.ps1 b/tools/win-ci/gvr.ps1 index 930712c..3e611a2 100644 --- a/tools/win-ci/gvr.ps1 +++ b/tools/win-ci/gvr.ps1 @@ -120,6 +120,46 @@ try { } if ($Phase -eq 'full') { + # 3D 리플레이 변환기 (v1.5.0~): .NET SDK 10 (없으면 받음) → ValorantReplayParser 고정 커밋 → win-x64 단일 exe + $r['replay_build'] = Step 'replay_build' { + $dn = 'C:\win-ci\dotnet' + if (-not (Test-Path (Join-Path $dn 'dotnet.exe'))) { + $inst = Get-File 'https://dot.net/v1/dotnet-install.ps1' 'dotnet-install.ps1' + & powershell -NoProfile -ExecutionPolicy Bypass -File $inst -Channel 10.0 -InstallDir $dn + } + $env:DOTNET_ROOT = $dn + $env:DOTNET_CLI_TELEMETRY_OPTOUT = '1' + $env:DOTNET_NOLOGO = '1' + & (Join-Path $dn 'dotnet.exe') --version + $tx = Join-Path $Repo 'tools\replay-extract' + $vd = Join-Path $tx 'vendor\ValorantReplayParser' + $pc = (Select-String -Path (Join-Path $tx 'fetch-parser.sh') -Pattern 'PARSER_COMMIT:-([0-9a-f]{40})').Matches[0].Groups[1].Value + if (-not (Test-Path (Join-Path $vd '.git'))) { & git clone -q https://github.com/michel-giehl/ValorantReplayParser $vd } + & git -C $vd fetch -q origin + & git -C $vd checkout -q --force $pc + # global.json 의 SDK 패치 버전 고정을 푼다 (fetch-parser.sh 와 같게) + $gj = Join-Path $vd 'global.json' + $j = Get-Content $gj -Raw | ConvertFrom-Json + $j.sdk | Add-Member -NotePropertyName rollForward -NotePropertyValue 'latestFeature' -Force + $j | ConvertTo-Json -Depth 5 | Set-Content $gj -Encoding UTF8 + "parser @ $(& git -C $vd rev-parse --short HEAD)" + Push-Location $tx + & (Join-Path $dn 'dotnet.exe') publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:EnableCompressionInSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=none -o out\win + $c = $LASTEXITCODE + Pop-Location + if ($c -ne 0) { throw "dotnet publish exit $c" } + $exe = Join-Path $tx 'out\win\gvr-replay.exe' + if (-not (Test-Path $exe)) { throw 'gvr-replay.exe 없음' } + "gvr-replay.exe $([math]::Round((Get-Item $exe).Length / 1MB, 1)) MB" + # 실제 13.08 리플레이 변환 (호스트가 serve/ 에 둔 시험 파일, 없으면 건너뜀) + $vrf = Join-Path $OutDir '4145f041-7d83-4785-ac4b-b532154f14a4.vrf' + try { Invoke-WebRequest -Uri 'http://10.0.2.2:8099/gvr-test.vrf' -OutFile $vrf -UseBasicParsing -TimeoutSec 600 } catch { Remove-Item $vrf -Force -ErrorAction SilentlyContinue; "시험 리플레이 없음: $($_.Exception.Message)" } + if (Test-Path $vrf) { + $out = & $exe $vrf (Join-Path $OutDir 'replay.json') + $out + if ($LASTEXITCODE -ne 0) { throw "gvr-replay exit $LASTEXITCODE" } + } + } $r['app_build'] = Step 'app_build' { Push-Location (Join-Path $Repo 'app') & npm.cmd ci --no-audit --no-fund @@ -134,6 +174,9 @@ try { $exe = Get-ChildItem app\release\win-unpacked\GameVoiceRecorder.exe $data = Join-Path $OutDir 'smoke-data' Remove-Item $data -Recurse -Force -ErrorAction SilentlyContinue + # 시험 리플레이가 있으면 앱 안의 변환기로 실제 변환까지 확인한다 + $vrf = Join-Path $OutDir '4145f041-7d83-4785-ac4b-b532154f14a4.vrf' + if (Test-Path $vrf) { $env:GVR_SMOKE_VRF = $vrf } else { Remove-Item Env:GVR_SMOKE_VRF -ErrorAction SilentlyContinue } $p = Start-Process $exe.FullName -ArgumentList '--smoke', "--data-dir=$data" -PassThru -Wait Get-Content (Join-Path $data 'smoke.json') -ErrorAction SilentlyContinue if ($p.ExitCode -ne 0) { throw "app smoke exit $($p.ExitCode)" }