v1.3.6: 목소리 깨짐(RTP 기준 쉼 채우기) · 알 수 없음 · 잡음 숨기기/삭제 · 사이트 로그 · 지금 게임 · TTS 속도 · 시작 창

- 녹음기: 패킷 도착 간격 대신 RTP 타임스탬프로 자리를 정한다. 게임 중 몰려 온 패킷 사이에 무음이 끼어 목소리가 깨졌다. 예전 녹음은 한 번 고친 뒤 다시 변환
- users.updated 를 빈 목록으로 보내 사이트에서 말한 사람이 '알 수 없음'이 되던 것
- 잡음은 숨기고 ogg 삭제, 로그에 잡음으로 남김. 짧은 목소리도 Whisper 로, 반복 고리는 줄여서 보여 줌
- 사이트: 재생 음량, 발화 우클릭(자세한 정보 · ogg 다운로드), 사이트 로그(/logs, 게임 PC 꺼져도), 지금 게임 상태
- 앱: 지금 게임 상태, 녹음 안내 말 속도 0.1~2.0, 포터블 · 앱 시작 창
- 발로란트 데스매치 가짜 라운드 · 에이스, 빈 선수 이름

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-16 05:01:14 +09:00
parent 2ffb18263c
commit fa6126e17f
66 changed files with 2265 additions and 128 deletions

View File

@@ -252,7 +252,7 @@ export function registerAppAuth(
return s && r ? { userId: s.userId, role: r } : null;
};
return { completeLogin, verifyToken };
return { completeLogin, verifyToken, roleOf };
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

View File

@@ -12,15 +12,24 @@ import type { KnowledgeAuto } from './culprit-prompt.js';
import { avatarUrl, DiscordApi } from './discord.js';
import { RateLimiter } from './rate-limit.js';
import { RelayHub } from './relay.js';
import { SiteLog } from './site-log.js';
import { ServerStore, type Session } from './store.js';
const SID = 'gvr_sid';
const RECHECK_MS = 10 * 60000;
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto } = {}) {
export async function buildServer(
cfg: Config,
opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; logEcho?: boolean } = {},
) {
// 사이트 로그: 날짜별 파일(data/logs/site-날짜.log)로 남기고 관리자가 사이트에서 본다. 게임 PC 가 꺼져 있어도 볼 수 있다
const siteLog = new SiteLog(path.join(cfg.dataDir, 'logs'), { echo: opts.logEcho ?? true });
const app = Fastify({
// 요청 기록은 아래 onResponse 에서 한 줄로 남긴다 (pino 기본 요청 로그는 두 줄 + 상태 확인 폴링으로 너무 많음)
disableRequestLogging: true,
logger: {
stream: siteLog,
level: process.env.LOG_LEVEL || 'info',
// 로그에 비밀값을 남기지 않는다: 로그인 주소의 code · state, 앱 로그인 요청 아이디, 기록 검색어(쿼리)는 지운다
serializers: { req: (req) => ({ method: req.method, url: safeLogUrl(req.url), remoteAddress: req.ip }) },
@@ -31,12 +40,13 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
});
const store = new ServerStore(cfg.dataDir);
const hub = new RelayHub(store);
hub.log = app.log.child({ area: 'relay' });
const discord = new DiscordApi(cfg);
await app.register(cookie, { secret: cfg.sessionSecret });
const secure = cfg.publicUrl.startsWith('https://');
let broker: BotBroker | null = null;
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log, opts.botRecheckMs);
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log.child({ area: 'bot' }), opts.botRecheckMs);
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
// CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게)
@@ -98,9 +108,54 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
reply.code(401).send({ error: 'unauthorized' });
return null;
}
(req as any).gvrUser = s.user.id;
return s;
};
// ------------------------------------------------------------------ 사이트 로그
// 요청 한 줄 기록: 기록 API · 로그인 · 앱 요청은 모두, 화면 파일은 실패만. 자주 부르는 상태 확인 · 음성 파일은 실패만 남긴다
app.addHook('onResponse', async (req, reply) => {
const url = safeLogUrl(req.url);
const st = reply.statusCode;
const p = url.split('?')[0];
const api = /^\/(api|auth|app|admin|device|site)\//.test(p);
if (st < 400 && (!api || p === '/api/status' || p.startsWith('/api/audio/') || p.startsWith('/site/logs') || p === '/site/client-log')) return;
const o = { area: 'http', status: st, ms: Math.round(reply.elapsedTime), ...((req as any).gvrUser ? { user: (req as any).gvrUser } : {}) };
if (st >= 500 && st !== 503) req.log.error(o, `${req.method} ${url}`);
else if (st >= 400 && st !== 401) req.log.warn(o, `${req.method} ${url}`);
else req.log.info(o, `${req.method} ${url}`);
});
const canViewLogs = (userId: string) => cfg.owners.includes(userId) || ['admin', 'superadmin'].includes(appAuth.roleOf(userId) ?? '');
app.get('/site/logs', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
if (!canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '사이트 로그는 관리자만 볼 수 있습니다' });
return { days: siteLog.days(), now: Date.now() };
});
app.get<{ Params: { date: string }; Querystring: { download?: string } }>('/site/logs/:date', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
if (!canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '사이트 로그는 관리자만 볼 수 있습니다' });
const text = siteLog.read(req.params.date);
if (text === null) return reply.code(404).send({ error: 'not_found' });
reply.header('cache-control', 'no-store').type('text/plain; charset=utf-8');
if (req.query.download) reply.header('content-disposition', `attachment; filename="gvr-site-${req.params.date}.log"`);
return text;
});
// 브라우저 오류(화면 오류 · 처리 안 된 오류 · 요청 실패)를 사이트 로그에 남긴다. 로그인한 사람만, 1분에 30개까지
const clientLogLimit = new RateLimiter(30, 60000);
app.post<{ Body: { level?: string; message?: string; detail?: string; page?: string } }>('/site/client-log', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
if (!clientLogLimit.hit(s.user.id)) return reply.code(429).send({ error: 'rate_limited' });
const b = req.body ?? {};
const cut = (v: unknown, n: number) => String(v ?? '').slice(0, n);
const o = { area: 'web', user: s.user.id, page: cut(b.page, 200), ...(b.detail ? { detail: cut(b.detail, 2000) } : {}), ua: cut(req.headers['user-agent'], 160) };
if (b.level === 'error') req.log.error(o, cut(b.message, 500));
else req.log.warn(o, cut(b.message, 500));
return reply.code(204).send();
});
// ------------------------------------------------------------------ 로그인
app.get('/auth/discord', async (req, reply) => {
const state = crypto.randomBytes(16).toString('base64url');
@@ -148,7 +203,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
app.get('/auth/me', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
return { user: s.user, isOwner: cfg.owners.includes(s.user.id) };
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id) };
});
// ------------------------------------------------------------------ 상태 · 관리
@@ -177,7 +232,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
});
// ------------------------------------------------------------------ 범인찾기 (Claude API 는 이 서버만 부른다)
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log, call: opts.culpritCall, knowledge: opts.culpritKnowledge });
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log.child({ area: 'culprit' }), call: opts.culpritCall, knowledge: opts.culpritKnowledge });
// ------------------------------------------------------------------ 기록 API 중계
const relay = async (req: FastifyRequest, reply: FastifyReply) => {
@@ -226,7 +281,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
if (fs.existsSync(cfg.webDir)) {
await app.register(fastifyStatic, { root: cfg.webDir, wildcard: false, index: ['index.html'] });
app.setNotFoundHandler((req, reply) => {
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/app/') && !req.url.startsWith('/game-assets/'))
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/app/') && !req.url.startsWith('/site/') && !req.url.startsWith('/game-assets/'))
return reply.type('text/html').send(fs.readFileSync(path.join(cfg.webDir, 'index.html')));
return reply.code(404).send({ error: 'not_found' });
});
@@ -284,9 +339,10 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
});
app.addHook('onClose', async () => {
store.flush();
siteLog.close();
});
return { app, store, hub, broker, culprit };
return { app, store, hub, broker, culprit, siteLog };
}
/** 로그에 남길 주소: /auth/* 는 쿼리를 지우고 앱 로그인 요청 아이디를 가린다, 다른 주소도 쿼리 값은 지운다 */

View File

@@ -7,7 +7,7 @@ const cfg = loadConfig();
let log: { info: (o: any, m?: string) => void; error: (o: any, m?: string) => void } = { info: () => undefined, error: (o, m) => console.error(m, o) };
const botSource = process.env.BOT_GATEWAY === '0' ? undefined : new DiscordSource({ info: (o, m) => log.info(o, m), error: (o, m) => log.error(o, m) });
const { app } = await buildServer(cfg, { botSource });
log = app.log;
log = app.log.child({ area: 'discord' });
await app.listen({ host: cfg.host, port: cfg.port });
if (botSource) {
// 디스코드에 못 붙어도 사이트는 계속 돈다 (discord.js 가 알아서 다시 연결)

View File

@@ -4,6 +4,9 @@ import { WebSocket, WebSocketServer } from 'ws';
import type { BrowserMessage, DeviceStatus, LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
import type { ServerStore } from './store.js';
type Log = { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void };
const NOLOG: Log = { info: () => undefined, warn: () => undefined };
const OFFLINE_AFTER_MS = 15000;
interface Pending {
@@ -33,6 +36,9 @@ export class RelayHub {
private watchdog: NodeJS.Timeout;
private lastStatus = '';
/** 사이트 로그 (app.ts 가 [relay] 영역 로거를 넣는다) */
log: Log = NOLOG;
constructor(private store: ServerStore) {
this.watchdog = setInterval(() => this.checkAlive(), 2000);
}
@@ -74,6 +80,7 @@ export class RelayHub {
private checkAlive(): void {
if (this.device && Date.now() - this.device.lastMsg > OFFLINE_AFTER_MS) {
this.log.warn({ name: this.device.name, silentMs: Date.now() - this.device.lastMsg }, '게임 PC 응답 없음 (15초) → 연결 끊음');
this.device.ws.terminate();
this.dropDevice(this.device.ws);
}
@@ -92,11 +99,13 @@ export class RelayHub {
attachDevice(ws: WebSocket, id: string): void {
if (this.device) {
// 같은 기기가 다시 연결 (네트워크 재연결) → 이전 연결을 끊는다
this.log.info({ name: this.device.name }, '게임 PC 가 다시 연결해서 이전 연결을 닫음');
this.device.ws.close(4000, 'replaced');
this.dropDevice(this.device.ws);
}
const dev = this.store.device();
this.device = { ws, id, name: dev?.name ?? 'GAME-PC', version: null, lastMsg: Date.now() };
this.log.info({ name: this.device.name }, '게임 PC 연결');
this.store.touchDevice(id, { lastSeen: Date.now() });
ws.send(JSON.stringify({ t: 'welcome', deviceId: id } satisfies RelayToDevice));
ws.on('message', (data, isBinary) => {
@@ -111,13 +120,14 @@ export class RelayHub {
}
this.onDeviceMessage(m);
});
ws.on('close', () => this.dropDevice(ws));
ws.on('error', () => this.dropDevice(ws));
ws.on('close', (code, reason) => this.dropDevice(ws, `닫힘 ${code}${reason?.length ? ' ' + String(reason) : ''}`));
ws.on('error', (e) => this.dropDevice(ws, `오류 ${e.message}`));
this.broadcastStatus(true);
}
private dropDevice(ws: WebSocket): void {
private dropDevice(ws: WebSocket, why = '응답 없음'): void {
if (!this.device || this.device.ws !== ws) return;
this.log.warn({ name: this.device.name, why, pending: this.pending.size }, '게임 PC 연결 끊김 (사이트 잠김)');
this.store.touchDevice(this.device.id, { lastSeen: this.device.lastMsg });
this.device = null;
for (const [id, p] of this.pending) {
@@ -134,6 +144,7 @@ export class RelayHub {
case 'hello':
dev.name = m.name;
dev.version = m.version;
this.log.info({ name: m.name, version: m.version, guild: m.guildId ?? null }, '게임 PC 정보');
this.store.touchDevice(dev.id, { name: m.name, version: m.version, guildId: m.guildId ?? null, lastSeen: Date.now() });
this.broadcastStatus(true);
break;
@@ -183,7 +194,10 @@ export class RelayHub {
const id = crypto.randomBytes(8).toString('hex');
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (this.pending.delete(id)) reject(new Error('timeout'));
if (this.pending.delete(id)) {
this.log.warn({ method, path: path.split('?')[0], ms: timeoutMs }, '게임 PC 가 기록 요청에 답하지 않음 (시간 초과)');
reject(new Error('timeout'));
}
}, timeoutMs);
this.pending.set(id, { resolve, reject, timer, chunks: [] });
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body };

109
site/server/src/site-log.ts Normal file
View File

@@ -0,0 +1,109 @@
import fs from 'node:fs';
import path from 'node:path';
/**
* 사이트 서버 로그 (v1.3.6~). exe 로그(gvr-날짜.log)와 같은 모양의 글 로그를 날짜별 파일로 남긴다.
* 게임 PC 와 연결이 끊겨도 사이트에서 볼 수 있다 (관리자만, /site/logs).
*
* Fastify(pino)가 한 줄씩 쓰는 JSON 을 받아 "시각 수준 [영역] 내용 {추가 값}" 으로 바꾼다. 표준 출력(docker logs)에도 그대로 낸다.
*/
const LEVELS: Record<number, string> = { 10: 'TRACE', 20: 'DEBUG', 30: 'INFO ', 40: 'WARN ', 50: 'ERROR', 60: 'FATAL' };
const SKIP_KEYS = new Set(['level', 'time', 'pid', 'hostname', 'msg', 'area', 'reqId', 'err', 'v']);
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
export interface SiteLogOptions {
keepDays?: number;
/** 표준 출력에도 쓰기 (테스트에서는 끈다) */
echo?: boolean;
}
export class SiteLog {
private day = '';
private fd: number | null = null;
private keepDays: number;
private echo: boolean;
constructor(
readonly dir: string,
opts: SiteLogOptions = {},
) {
this.keepDays = opts.keepDays ?? 14;
this.echo = opts.echo ?? true;
fs.mkdirSync(dir, { recursive: true });
}
/** pino destination: JSON 한 줄(또는 여러 줄) */
write(chunk: string): void {
if (this.echo) process.stdout.write(chunk);
for (const line of String(chunk).split('\n')) {
if (!line.trim()) continue;
let o: Record<string, any>;
try {
o = JSON.parse(line);
} catch {
o = { level: 30, time: Date.now(), msg: line };
}
this.append(format(o), typeof o.time === 'number' ? o.time : Date.now());
}
}
private append(text: string, ts: number): void {
const day = new Date(ts).toISOString().slice(0, 10);
try {
if (day !== this.day || this.fd === null) {
if (this.fd !== null) fs.closeSync(this.fd);
this.day = day;
this.fd = fs.openSync(this.file(day), 'a');
this.cleanup();
}
fs.writeSync(this.fd, text + '\n');
} catch {
/* 디스크 문제로 로그를 못 써도 서버는 계속 돈다 */
}
}
file(day: string): string {
return path.join(this.dir, `site-${day}.log`);
}
/** 남아 있는 로그 날짜 (최신 먼저) */
days(): { date: string; size: number }[] {
return fs
.readdirSync(this.dir)
.map((f) => /^site-(\d{4}-\d{2}-\d{2})\.log$/.exec(f)?.[1])
.filter((d): d is string => !!d)
.sort()
.reverse()
.map((date) => ({ date, size: fs.statSync(this.file(date)).size }));
}
/** 그날 로그 원문. 없으면 null */
read(day: string): string | null {
if (!DATE_RE.test(day)) return null;
const f = this.file(day);
return fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : null;
}
private cleanup(): void {
const cut = new Date(Date.now() - this.keepDays * 86400000).toISOString().slice(0, 10);
for (const { date } of this.days()) if (date < cut) fs.rmSync(this.file(date), { force: true });
}
close(): void {
if (this.fd !== null) fs.closeSync(this.fd);
this.fd = null;
}
}
/** exe 로그와 같은 모양: 2026-10-15T17:15:59.289Z INFO [relay] 게임 PC 연결 {"name":"TKRMAGID-PC"} */
export function format(o: Record<string, any>): string {
const time = new Date(typeof o.time === 'number' ? o.time : Date.now()).toISOString();
const lv = LEVELS[o.level] ?? 'INFO ';
const area = o.area || 'server';
const extra: Record<string, unknown> = {};
for (const [k, v] of Object.entries(o)) if (!SKIP_KEYS.has(k) && v !== undefined) extra[k] = v;
let s = `${time} ${lv} [${area}] ${o.msg ?? ''}`;
if (Object.keys(extra).length) s += ' ' + JSON.stringify(extra);
if (o.err) s += `\n ${String(o.err.stack || `${o.err.type ?? 'Error'}: ${o.err.message}`).replace(/\n/g, '\n ')}`;
return s;
}

View File

@@ -50,7 +50,7 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
discordApi: dc.url,
assetUpstream: {},
};
const { app, store } = await buildServer(cfg);
const { app, store } = await buildServer(cfg, { logEcho: false });
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
try {
@@ -134,6 +134,20 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
rc.stop();
await wait(() => bmsgs.some((m) => m.type === 'status' && m.data.device.registered && !m.data.device.online));
assert.equal((await fetch(base + '/api/timeline', { headers: { cookie: sid } })).status, 503);
// 사이트 로그: 게임 PC 가 끊겨도 관리자는 볼 수 있다. 일반 유저는 못 본다
assert.equal((await fetch(base + '/site/logs', { headers: { cookie: sid } })).status, 403);
assert.equal(((await (await fetch(base + '/auth/me', { headers: { cookie: sid } })).json()) as any).canViewLogs, false);
assert.equal((await fetch(base + '/site/client-log', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/json' }, body: JSON.stringify({ level: 'error', message: '화면 오류 테스트', page: '/' }) })).status, 204);
store.upsertAppUser({ id: 'member1', name: '하늘', avatar: null, role: 'admin', addedBy: 'test' });
assert.equal(((await (await fetch(base + '/auth/me', { headers: { cookie: sid } })).json()) as any).canViewLogs, true);
const days = ((await (await fetch(base + '/site/logs', { headers: { cookie: sid } })).json()) as any).days;
assert.equal(days.length, 1);
const logText = await (await fetch(`${base}/site/logs/${days[0].date}`, { headers: { cookie: sid } })).text();
for (const want of ['[relay] 게임 PC 연결', '[relay] 게임 PC 정보', '[relay] 게임 PC 연결 끊김', 'GET /api/timeline?limit=***', '"status":503', '[web] 화면 오류 테스트']) assert.ok(logText.includes(want), `로그에 "${want}" 없음\n${logText}`);
assert.ok(!/GET \/api\/status \{"status":200/.test(logText), '성공한 상태 확인 폴링은 남기지 않는다');
const dl = await fetch(`${base}/site/logs/${days[0].date}?download=1`, { headers: { cookie: sid } });
assert.match(dl.headers.get('content-disposition') ?? '', /gvr-site-\d{4}-\d{2}-\d{2}\.log/);
assert.equal((await fetch(`${base}/site/logs/..%2F..%2Fetc`, { headers: { cookie: sid } })).status, 404);
// 서버 멤버가 아니면 로그인 거절
members.clear();
const s2 = await fetch(base + '/auth/discord', { redirect: 'manual' });

View File

@@ -53,7 +53,6 @@ function filterItems(q) {
const to = q.get('to') ? Number(q.get('to')) : null;
const kw = (q.get('q') ?? '').trim().toLowerCase();
const types = q.get('types') ? new Set(q.get('types').split(',')) : null;
const hideNoise = q.get('hideNoise') === '1';
const all = [...db.utterances, ...db.events];
return all.filter((it) => {
if (from != null && it.ts < from) return false;
@@ -69,7 +68,7 @@ function filterItems(q) {
}
if (it.kind === 'utterance') {
if (users && !users.has(it.userId)) return false;
if (hideNoise && it.noise) return false;
if (it.noise) return false;
if (kw && !(it.text ?? '').toLowerCase().includes(kw)) return false;
} else {
if (users && it.userId && !users.has(it.userId)) return false;
@@ -184,10 +183,31 @@ async function handle(req, res) {
return res.end();
}
const sess = session(req);
if (p === '/site/logs') return json(res, 200, { days: [{ date: '2026-10-16', size: 18234 }, { date: '2026-10-15', size: 40211 }], now: Date.now() });
if (p.startsWith('/site/logs/')) {
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
return res.end(
[
'2026-10-16T03:55:46.679Z INFO [relay] 게임 PC 연결 {"name":"TKRMAGID-PC"}',
'2026-10-16T03:55:46.690Z INFO [relay] 게임 PC 정보 {"name":"TKRMAGID-PC","version":"1.3.6","guild":"789051930965835810"}',
'2026-10-16T03:55:47.353Z INFO [bot] 겜녹이 봇 중계 연결 {"user":"293719842274541579","conn":"a1"}',
'2026-10-16T03:56:59.564Z INFO [http] GET /api/timeline?limit=*** {"status":200,"ms":38,"user":"293719842274541579"}',
'2026-10-16T04:01:10.710Z WARN [http] GET /api/matches/val-1 {"status":404,"ms":12,"user":"293719842274541579"}',
'2026-10-16T04:12:58.961Z ERROR [web] 화면 오류: Cannot read properties of undefined (reading \'name\') {"user":"293719842274541579","page":"/matches/val-1"}',
" TypeError: Cannot read properties of undefined (reading 'name')",
' at MatchPage (index-abc.js:1:2345)',
'2026-10-16T04:13:41.000Z WARN [relay] 게임 PC 연결 끊김 (사이트 잠김) {"name":"TKRMAGID-PC","why":"닫힘 1006","pending":0}',
].join('\n') + '\n',
);
}
if (p === '/site/client-log') {
res.writeHead(204);
return res.end();
}
if (p === '/auth/me') {
if (!sess) return json(res, 401, { error: 'unauthorized' });
if (sess === 'nm') return json(res, 403, { error: 'not_member' });
return json(res, 200, { user: ME, isOwner: true });
return json(res, 200, { user: ME, isOwner: true, canViewLogs: true });
}
if (p.startsWith('/api/')) {
@@ -203,6 +223,10 @@ async function handle(req, res) {
recording: { active: true, channel: '발로 음성방', since: NOW - 150 * 60000, participants: db.SPEAKERS.map((u) => u.id) },
users: db.users,
games: { valorant: { connected: true, inMatch: false }, lol: { connected: false, inMatch: false } },
live: [
{ game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, startedAt: Date.now() - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, updatedAt: Date.now() },
{ game: 'lol', enabled: true, connected: false, phase: '롤 클라이언트 꺼짐', inMatch: false, matchId: null, mode: null, map: null, mapImage: null, startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: null, players: null, error: null, updatedAt: Date.now() },
],
counts: { utterances: db.utterances.length, matches: db.matches.length },
version: '1.0.0',
});
@@ -240,6 +264,17 @@ async function handle(req, res) {
broadcast({ type: 'utterance.updated', data: it });
return json(res, 200, it);
}
if ((m = p.match(/^\/api\/utterances\/([^/]+)\/info$/))) {
const u = db.utterances.find((x) => x.id === m[1]);
if (!u) return json(res, 404, { error: 'not_found' });
const path = `C:\\Users\\gamer\\Desktop\\GameVoiceRecorder\\GVR-Data\\audio\\2026-10-16\\${u.id}.ogg`;
return json(res, 200, {
id: u.id, userId: u.userId, fileName: `${u.id}.ogg`, path, folder: path.slice(0, path.lastIndexOf('\\')),
sizeBytes: u.audio ? 41230 : null, deleted: u.audio ? null : 'retention', startedAt: u.ts, endedAt: u.endTs, durationMs: u.endTs - u.ts,
sessionId: 'sess1', channel: '음성', matchId: u.game?.matchId ?? null, status: u.status, model: u.model, confidence: u.confidence,
lufs: -36.4, gainDb: u.audio?.gainDb ?? null, rawText: u.text, text: u.text, corrected: u.corrected, noise: u.noise, noiseReason: null, attempts: 0, createdAt: u.endTs + 400,
});
}
if ((m = p.match(/^\/api\/audio\/([^/]+)$/))) {
const it = db.utterances.find((u) => u.id === decodeURIComponent(m[1]));
if (!it) return json(res, 404, { error: 'not_found' });

View File

@@ -10,11 +10,15 @@ import { Header } from './components/Header';
import { LockOverlay } from './components/LockOverlay';
import { LoginPage } from './components/LoginPage';
import { PlayerBar } from './components/PlayerBar';
import { UttMenuHost } from './components/UttMenu';
import { Spinner } from './components/common';
import { TimelinePage } from './pages/TimelinePage';
import { MatchPage } from './pages/MatchPage';
import { CulpritPage } from './pages/CulpritPage';
import { MatchesPage, UserPage, UsersPage } from './pages/UserPages';
import { LogsPage } from './pages/LogsPage';
import { installErrorReporting } from './lib/report';
import { useLocation } from 'react-router';
/** Space 재생/일시정지 · ←/→ 이전/다음 발화 · / 검색 */
function useShortcuts() {
@@ -74,6 +78,7 @@ function Shell() {
</div>
<PlayerBar />
</div>
<UttMenuHost />
<LockOverlay />
</div>
);
@@ -81,6 +86,10 @@ function Shell() {
function Gate() {
const { auth } = useAuth();
const loc = useLocation();
useEffect(() => {
if (auth.status === 'ok') installErrorReporting();
}, [auth.status]);
if (auth.status === 'loading')
return (
<div className="boot">
@@ -94,6 +103,8 @@ function Gate() {
return <LoginPage notMember={q === 'not_member'} error={q === 'error' || q === 'invalid' ? '로그인 중 문제가 생겼습니다. 다시 시도해 주세요.' : undefined} />;
}
if (auth.status === 'not_member') return <LoginPage notMember />;
// 사이트 로그: 게임 PC 연결(잠금)과 상관없이 연다
if (loc.pathname === '/logs') return <LogsPage />;
return (
<StatusProvider>
<DataProvider>

View File

@@ -7,9 +7,12 @@ import { sfx, SFX_LABEL } from '../lib/sfx';
import { resumeAudio } from '../lib/audio';
import { Avatar, Brand } from './common';
import { IGear, ILogout, ISearch } from './Icons';
import { GAME_NAME, liveGameLine, liveGameRows } from '@gvr/shared';
function SettingsPopover({ onClose }: { onClose: () => void }) {
const s = useSettings();
const { auth } = useAuth();
const canViewLogs = auth.status === 'ok' && !!auth.me.canViewLogs;
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const down = (e: PointerEvent) => {
@@ -80,11 +83,36 @@ function SettingsPopover({ onClose }: { onClose: () => void }) {
<input type="checkbox" checked={s.reduceMotion} onChange={(e) => settings.set({ reduceMotion: e.target.checked })} />
<span>모션 줄이기</span>
</label>
{canViewLogs && (
<>
<h5>문제 해결</h5>
<a className="row" href="/logs">
📄 사이트 로그 보기 · 내려받기
</a>
</>
)}
<div className="pop-foot">단축키: Space 재생 · ←/→ 이전·다음 발화 · / 검색 · Esc 닫기</div>
</motion.div>
);
}
/** 지금 게임: 경기 중이면 "발로란트 · 경쟁전 · 어센트 · R15 8:6", 아니면 연결된 게임 상태 */
function GamePill() {
const { overview } = useData();
const live = (overview?.live ?? []).filter((g) => g.enabled && g.connected);
const g = live.find((x) => x.inMatch) ?? live[0];
if (!g) return null;
const tip = liveGameRows(g)
.map(([k, v]) => `${k}: ${v}`)
.join('\n');
return (
<div className={`game-pill ${g.game}${g.inMatch ? ' in' : ''}`} title={tip}>
<span className="gp-name">{GAME_NAME[g.game]}</span>
<span className="gp-txt">{liveGameLine(g)}</span>
</div>
);
}
export function SearchBox() {
const [params, setParams] = useSearchParams();
const loc = useLocation();
@@ -170,6 +198,7 @@ export function Header() {
<span className="rec-short">녹음 중</span>
</div>
)}
{!locked && <GamePill />}
{device && (
<div className={`conn ${locked ? 'off' : conn === 'open' ? 'on' : 'warn'}`} title={conn === 'open' ? '실시간 연결됨' : '실시간 연결 재시도 중'}>
<span className="dot" />

View File

@@ -65,6 +65,17 @@ export const IVolume = (p: SVGProps<SVGSVGElement>) => (
<path d="M19 5a10 10 0 0 1 0 14" />
</svg>
);
export const IMute = (p: SVGProps<SVGSVGElement>) => (
<svg {...base(p)}>
<path d="M11 5 6 9H2v6h4l5 4V5z" />
<path d="m23 9-6 6M17 9l6 6" />
</svg>
);
export const IDownload = (p: SVGProps<SVGSVGElement>) => (
<svg {...base(p)}>
<path d="M12 3v12M7 10l5 5 5-5M4 21h16" />
</svg>
);
export const IUsers = (p: SVGProps<SVGSVGElement>) => (
<svg {...base(p)}>
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />

View File

@@ -123,6 +123,11 @@ export function LockOverlay() {
>
↻ {checking ? '확인 중…' : '지금 다시 확인'}
</button>
{auth.status === 'ok' && auth.me.canViewLogs && (
<a className="btn" href="/logs">
📄 사이트 로그 보기
</a>
)}
<button className="btn" onClick={logout}>
로그아웃
</button>

View File

@@ -6,7 +6,8 @@ import { useData } from '../store/app';
import { sfx } from '../lib/sfx';
import { fmtClock, fmtSec } from '../lib/format';
import { Avatar } from './common';
import { IClose, ILoop, INext, IPause, IPlay, IPrev, IVolume } from './Icons';
import { IClose, ILoop, IMute, INext, IPause, IPlay, IPrev, IVolume } from './Icons';
import { clampVolume } from '../lib/audio';
const RATES = [1, 1.25, 1.5, 2];
@@ -51,6 +52,32 @@ function SceneLanes({ scene }: { scene: SceneInfo }) {
);
}
/** 녹음 재생 음량 0~200% (아이콘을 누르면 음소거 / 되돌리기) */
function VolumeControl() {
const cfg = useSettings();
const v = clampVolume(cfg.playVolume);
const last = useRef(v || 1);
if (v > 0) last.current = v;
return (
<div className="pb-vol" title={`재생 음량 ${Math.round(v * 100)}%`}>
<button className={`icon-btn${v === 0 ? ' muted-on' : ''}`} onClick={() => settings.set({ playVolume: v === 0 ? last.current : 0 })} aria-label={v === 0 ? '소리 켜기' : '음소거'}>
{v === 0 ? <IMute width={16} height={16} /> : <IVolume width={16} height={16} />}
</button>
<input
type="range"
min={0}
max={200}
step={5}
value={Math.round(v * 100)}
onChange={(e) => settings.set({ playVolume: Number(e.target.value) / 100 })}
aria-label="재생 음량"
style={{ ['--p' as string]: `${(v / 2) * 100}%` }}
/>
<span className="mono pb-vol-n">{Math.round(v * 100)}%</span>
</div>
);
}
export function PlayerBar() {
const s = usePlayer((x) => x);
const cfg = useSettings();
@@ -145,6 +172,7 @@ export function PlayerBar() {
<button className="chip mono" onClick={click(() => settings.set({ rate: RATES[(RATES.indexOf(cfg.rate) + 1) % RATES.length] }))} title="재생 속도">
{cfg.rate}x
</button>
<VolumeControl />
<button
className={`chip${cfg.normalize ? ' on-mint' : ''}`}
onClick={click(() => settings.set({ normalize: !cfg.normalize }))}

View File

@@ -0,0 +1,218 @@
import { useEffect, useState, useSyncExternalStore, type ReactNode } from 'react';
import type { UtteranceInfo, UtteranceItem } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { fmtWhen } from '../lib/format';
import { player } from '../store/player';
import { useData } from '../store/app';
import { IClose, IDownload, IPlay } from './Icons';
/** 발화 우클릭 메뉴 · 자세한 정보 창 (앱에 하나만 띄운다) */
type MenuState = { item: UtteranceItem; x: number; y: number } | null;
let menu: MenuState = null;
let infoFor: UtteranceItem | null = null;
const subs = new Set<() => void>();
const notify = () => subs.forEach((f) => f());
const subscribe = (f: () => void) => {
subs.add(f);
return () => {
subs.delete(f);
};
};
export function openUttMenu(item: UtteranceItem, x: number, y: number): void {
menu = { item, x, y };
notify();
}
function closeMenu(): void {
menu = null;
notify();
}
function openInfo(item: UtteranceItem): void {
menu = null;
infoFor = item;
notify();
}
function closeInfo(): void {
infoFor = null;
notify();
}
/** 녹음 원본(.ogg)을 내려받는다. 게임 PC → 사이트 서버 중계로 받은 파일을 그대로 저장 */
export async function downloadAudio(item: UtteranceItem, fileName?: string | null): Promise<void> {
const res = await fetch(`/api/audio/${encodeURIComponent(item.id)}`, { credentials: 'include' });
if (!res.ok) throw new Error(res.status === 410 ? '음성 파일이 삭제되었습니다' : `받지 못했습니다 (${res.status})`);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName || `${item.id}.ogg`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10000);
}
const copy = (text: string) => navigator.clipboard?.writeText(text).catch(() => undefined);
export function UttMenuHost() {
const m = useSyncExternalStore(subscribe, () => menu);
const info = useSyncExternalStore(subscribe, () => infoFor);
const [err, setErr] = useState<string | null>(null);
useEffect(() => {
if (!m) return;
const close = () => closeMenu();
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeMenu();
window.addEventListener('pointerdown', close);
window.addEventListener('scroll', close, true);
window.addEventListener('resize', close);
window.addEventListener('keydown', onKey);
return () => {
window.removeEventListener('pointerdown', close);
window.removeEventListener('scroll', close, true);
window.removeEventListener('resize', close);
window.removeEventListener('keydown', onKey);
};
}, [m]);
useEffect(() => {
if (!err) return;
const t = setTimeout(() => setErr(null), 4000);
return () => clearTimeout(t);
}, [err]);
const act = (fn: () => unknown) => (e: React.PointerEvent | React.MouseEvent) => {
e.stopPropagation();
closeMenu();
fn();
};
return (
<>
{m && (
<div
className="ctx-menu"
role="menu"
style={{ left: Math.min(m.x, window.innerWidth - 230), top: Math.min(m.y, window.innerHeight - 190) }}
onPointerDown={(e) => e.stopPropagation()}
onContextMenu={(e) => e.preventDefault()}
>
<button role="menuitem" disabled={!m.item.audio} onClick={act(() => void player.play(m.item))}>
<IPlay width={14} height={14} /> 재생
</button>
<button role="menuitem" onClick={act(() => openInfo(m.item))}>
<span className="ctx-ic">ℹ</span> 자세한 정보
</button>
<button role="menuitem" disabled={!m.item.audio} onClick={act(() => downloadAudio(m.item).catch((e) => setErr(e.message)))}>
<IDownload width={14} height={14} /> 음성 다운로드 (.ogg)
</button>
<button role="menuitem" disabled={!m.item.text} onClick={act(() => copy(m.item.text ?? ''))}>
<span className="ctx-ic">⧉</span> 내용 복사
</button>
</div>
)}
{info && <InfoDialog item={info} onError={setErr} />}
{err && <div className="ctx-toast">{err}</div>}
</>
);
}
const STATUS: Record<string, string> = { pending: '변환 대기', realtime: '실시간 모델', precise: '정밀 모델', failed: '인식 실패' };
const DELETED: Record<string, string> = { retention: '보관 기간이 지나 삭제됨', noise: '잡음이라 삭제됨', missing: '파일을 찾을 수 없음' };
function fmtBytes(n: number): string {
return n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(2)} MB` : `${(n / 1024).toFixed(1)} KB`;
}
function InfoDialog({ item, onError }: { item: UtteranceItem; onError: (m: string) => void }) {
const { userById } = useData();
const [info, setInfo] = useState<UtteranceInfo | null>(null);
const [failed, setFailed] = useState<string | null>(null);
const [copied, setCopied] = useState<string | null>(null);
useEffect(() => {
let alive = true;
api
.utteranceInfo(item.id)
.then((r) => alive && setInfo(r))
.catch((e) => {
if (!alive) return;
// v1.3.5 이하 앱에는 이 기능이 없다
setFailed(e instanceof ApiError && e.status === 404 ? '게임 PC 의 겜녹이가 예전 버전입니다. v1.3.6 이상으로 업데이트하면 볼 수 있습니다.' : '정보를 받지 못했습니다.');
});
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeInfo();
window.addEventListener('keydown', onKey);
return () => {
alive = false;
window.removeEventListener('keydown', onKey);
};
}, [item.id]);
const doCopy = (label: string, v: string) => {
void copy(v);
setCopied(label);
setTimeout(() => setCopied(null), 1500);
};
const user = userById(item.userId);
const rows: [string, ReactNode][] = info
? [
['말한 사람', user?.name ?? info.userId],
['원본 파일', <span className="mono">{info.fileName ?? '-'}</span>],
[
'경로 (게임 PC)',
info.path ? (
<span className="mono path">
{info.path}{' '}
<button className="link-btn" onClick={() => doCopy('path', info.path!)}>
{copied === 'path' ? '복사됨' : '복사'}
</button>
</span>
) : (
'-'
),
],
['파일 상태', info.deleted ? DELETED[info.deleted] : info.sizeBytes != null ? `있음 · ${fmtBytes(info.sizeBytes)}` : '-'],
['녹음 시각', `${fmtWhen(info.startedAt)} · ${(info.durationMs / 1000).toFixed(1)}초`],
['음성채널', info.channel ?? '-'],
['경기', info.matchId ?? '경기 밖'],
['인식', `${STATUS[info.status] ?? info.status}${info.model ? ` · ${info.model}` : ''}${info.confidence != null ? ` · 신뢰도 ${Math.round(info.confidence * 100)}%` : ''}`],
['원래 인식 결과', info.rawText ?? '-'],
...(info.corrected ? ([['교정', '사람이 고친 글']] as [string, ReactNode][]) : []),
['음량', `${info.lufs != null ? `${info.lufs.toFixed(1)} LUFS` : '-'} · 재생 보정 ${info.gainDb != null ? `${info.gainDb > 0 ? '+' : ''}${info.gainDb.toFixed(1)} dB` : '-'}`],
['발화 ID', <span className="mono">{info.id}</span>],
]
: [];
return (
<div className="ctx-dim" onPointerDown={closeInfo}>
<div className="ctx-dialog" role="dialog" aria-label="발화 자세한 정보" onPointerDown={(e) => e.stopPropagation()}>
<div className="ctx-head">
<b>발화 자세한 정보</b>
<button className="icon-btn" onClick={closeInfo} aria-label="닫기">
<IClose width={16} height={16} />
</button>
</div>
{failed && <p className="dim">{failed}</p>}
{!info && !failed && <p className="dim">불러오는 중…</p>}
{info && (
<dl className="ctx-rows">
{rows.map(([k, v]) => (
<div key={k}>
<dt>{k}</dt>
<dd>{v}</dd>
</div>
))}
</dl>
)}
<div className="ctx-foot">
<button className="chip on" disabled={!item.audio || !!info?.deleted} onClick={() => downloadAudio(item, info?.fileName).catch((e) => onError(e.message))}>
<IDownload width={14} height={14} /> 원본 ogg 다운로드
</button>
<button className="chip" onClick={closeInfo}>
닫기
</button>
</div>
</div>
</div>
);
}

View File

@@ -7,6 +7,7 @@ import { sfx } from '../lib/sfx';
import { realTip } from '../lib/format';
import { Avatar, TimeCell } from './common';
import { IEdit } from './Icons';
import { openUttMenu } from './UttMenu';
const STATUS: Record<UtteranceItem['status'], [string, string]> = {
realtime: ['실시간', 'st-rt'],
@@ -152,6 +153,12 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
if (active && player.state.mode === 'single') player.toggle();
else void player.play(item);
};
// 우클릭: 재생 · 자세한 정보(원본 ogg 이름 · 경로) · 다운로드
const menu = (e: MouseEvent) => {
if (editing) return;
e.preventDefault();
openUttMenu(item, e.clientX, e.clientY);
};
const edit = (e: MouseEvent) => {
e.stopPropagation();
sfx('click');
@@ -178,7 +185,7 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
if (variant === 'compact') {
return (
<div className={`l utt${active ? ' cur' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} data-id={item.id}>
<div className={`l utt${active ? ' cur' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} onContextMenu={menu} data-id={item.id}>
<span className="t mono" data-tip={realTip(item.ts)}>
{timeText ?? item.time.primary}
</span>
@@ -199,7 +206,7 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
}
return (
<div className={`it utt${active ? ' playing' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} data-id={item.id}>
<div className={`it utt${active ? ' playing' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} onContextMenu={menu} data-id={item.id}>
<TimeCell time={item.time} real={!item.game} />
<Avatar user={user} size={30} />
<div className="body">

View File

@@ -10,9 +10,12 @@ import type {
UserProfile,
User,
UtteranceItem,
UtteranceInfo,
GameType,
} from '@gvr/shared';
import { reportClient } from './report';
/** 전역 신호: 401 → 로그인 화면, 503 device_offline → 잠금 화면 */
type Signal = 'unauthorized' | 'not_member' | 'device_offline';
const listeners = new Set<(s: Signal) => void>();
@@ -55,12 +58,16 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
if (res.status === 401) emit('unauthorized');
else if (res.status === 403 && code === 'not_member') emit('not_member');
else if (res.status === 503 && code === 'device_offline') emit('device_offline');
// 게임 PC 쪽 오류 · 시간 초과는 사이트 로그에도 남긴다 (게임 PC 꺼짐은 서버가 이미 남김)
else if (res.status >= 500) reportClient('error', `요청 실패 ${res.status} ${code}: ${init.method ?? 'GET'} ${path.split('?')[0]}`);
throw new ApiError(res.status, code);
}
export interface Me {
user: { id: string; name: string; avatar: string | null };
isOwner: boolean;
/** 사이트 로그를 볼 수 있는지 (관리자 · 최고 관리자, v1.3.6~) */
canViewLogs?: boolean;
}
export interface StatusResponse {
device: DeviceStatus;
@@ -75,7 +82,6 @@ export interface TimelineQuery {
to?: number;
q?: string;
types?: string[];
hideNoise?: boolean;
cursor?: string | null;
limit?: number;
order?: 'asc' | 'desc';
@@ -117,7 +123,6 @@ export const api = {
to: q.to,
q: q.q,
types: q.types?.length ? q.types.join(',') : undefined,
hideNoise: q.hideNoise ? 1 : undefined,
cursor: q.cursor,
limit: q.limit ?? 100,
order: q.order,
@@ -152,6 +157,7 @@ export const api = {
if (res.status === 503 && b.error === 'device_offline') emit('device_offline');
return { ok: false, status: res.status, error: b.error ?? 'error', message: b.message ?? '분석을 시작하지 못했습니다' };
},
utteranceInfo: (id: string) => request<UtteranceInfo>(`/api/utterances/${encodeURIComponent(id)}/info`),
correct: (id: string, text: string) =>
request<UtteranceItem>(`/api/utterances/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ text }) }),
};

View File

@@ -1,3 +1,5 @@
import { settings } from '../store/settings';
/** 공용 AudioContext 와 출력 체인 (플레이어 + 효과음) */
let ctx: AudioContext | null = null;
let playerBus: GainNode | null = null;
@@ -14,6 +16,11 @@ export function audioCtx(): AudioContext {
limiter.attack.value = 0.002;
limiter.release.value = 0.12;
playerBus = ctx.createGain();
// 녹음 재생 음량 (플레이어 막대의 음량 조절). 리미터 앞에서 바꿔 크게 키워도 찢어지지 않는다
playerBus.gain.value = clampVolume(settings.get().playVolume);
settings.subscribe(() => {
if (playerBus) playerBus.gain.value = clampVolume(settings.get().playVolume);
});
playerBus.connect(limiter).connect(ctx.destination);
sfxBus = ctx.createGain();
sfxBus.connect(ctx.destination);
@@ -35,4 +42,6 @@ export function sfxOutput(): GainNode {
return sfxBus!;
}
export const clampVolume = (v: unknown) => (typeof v === 'number' && isFinite(v) ? Math.min(2, Math.max(0, v)) : 1);
export const dbToGain = (db: number) => Math.pow(10, db / 20);

View File

@@ -11,7 +11,6 @@ export interface Filters {
to: number | undefined;
q: string;
types: TypeGroup[];
hideNoise: boolean;
order: 'asc' | 'desc' | null;
}
@@ -28,7 +27,6 @@ export function parseFilters(p: URLSearchParams): Filters {
to: num(p.get('to')),
q: p.get('q') ?? '',
types: (p.get('types')?.split(',').filter(Boolean) ?? []) as TypeGroup[],
hideNoise: p.get('hideNoise') === '1',
order: order === 'asc' || order === 'desc' ? order : null,
};
}
@@ -42,7 +40,6 @@ export function writeFilters(f: Filters): URLSearchParams {
if (f.to != null) p.set('to', String(f.to));
if (f.q) p.set('q', f.q);
if (f.types.length) p.set('types', f.types.join(','));
if (f.hideNoise) p.set('hideNoise', '1');
if (f.order) p.set('order', f.order);
return p;
}
@@ -59,7 +56,6 @@ export function toQuery(f: Filters): TimelineQuery {
to: f.to,
q: f.q || undefined,
types: f.types,
hideNoise: f.hideNoise,
order: effectiveOrder(f),
};
}
@@ -76,7 +72,7 @@ export function matchesFilter(it: TimelineItem, f: Filters): boolean {
const kw = f.q.trim().toLowerCase();
if (it.kind === 'utterance') {
if (f.users.length && !f.users.includes(it.userId)) return false;
if (f.hideNoise && it.noise) return false;
if (it.noise) return false; // 잡음은 보여 주지 않는다
if (kw && !(it.text ?? '').toLowerCase().includes(kw)) return false;
} else {
if (f.users.length && it.userId && !f.users.includes(it.userId)) return false;

View File

@@ -0,0 +1,29 @@
/** 브라우저 오류를 사이트 로그([web])에 남긴다. 같은 내용은 30초에 한 번만 */
const recent = new Map<string, number>();
export function reportClient(level: 'warn' | 'error', message: string, detail?: string): void {
const key = `${level}:${message}`;
const now = Date.now();
if ((recent.get(key) ?? 0) > now - 30000) return;
recent.set(key, now);
if (recent.size > 200) recent.clear();
void fetch('/site/client-log', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ level, message: message.slice(0, 500), detail: detail?.slice(0, 2000), page: location.pathname + location.search }),
keepalive: true,
}).catch(() => undefined);
}
let installed = false;
export function installErrorReporting(): void {
if (installed) return;
installed = true;
window.addEventListener('error', (e) => reportClient('error', `화면 오류: ${e.message}`, e.error?.stack ?? `${e.filename}:${e.lineno}:${e.colno}`));
window.addEventListener('unhandledrejection', (e) => {
const r = e.reason;
if (r?.name === 'AbortError') return;
reportClient('error', `처리 안 된 오류: ${r?.message ?? String(r)}`, r?.stack);
});
}

View File

@@ -0,0 +1,121 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useAuth } from '../store/app';
import { Brand } from '../components/common';
/**
* 사이트 로그 (관리자만). 게임 PC 와 연결이 끊겨 사이트가 잠겨 있어도 볼 수 있게 잠금 화면 밖에서 그린다.
* exe 로그(게임 PC 의 GVR-Data\logs\gvr-날짜.log)와 이 로그를 같이 보내면 대부분의 문제를 찾을 수 있다.
*/
type Level = 'all' | 'warn' | 'error';
const LEVEL_RE: Record<Level, RegExp> = { all: /./, warn: /^\S+ (WARN|ERROR|FATAL)/, error: /^\S+ (ERROR|FATAL)/ };
export function LogsPage() {
const { auth } = useAuth();
const [days, setDays] = useState<{ date: string; size: number }[] | null>(null);
const [date, setDate] = useState<string | null>(null);
const [text, setText] = useState('');
const [err, setErr] = useState<string | null>(null);
const [level, setLevel] = useState<Level>('all');
const [q, setQ] = useState('');
const [live, setLive] = useState(true);
useEffect(() => {
fetch('/site/logs', { credentials: 'include' })
.then(async (r) => {
if (r.status === 403) throw new Error('사이트 로그는 관리자만 볼 수 있습니다.');
if (!r.ok) throw new Error(`로그 목록을 받지 못했습니다 (${r.status})`);
const b = (await r.json()) as { days: { date: string; size: number }[] };
setDays(b.days);
setDate((d) => d ?? b.days[0]?.date ?? null);
})
.catch((e) => setErr(e.message));
}, []);
const load = useCallback(async () => {
if (!date) return;
const r = await fetch(`/site/logs/${date}`, { credentials: 'include', cache: 'no-store' });
if (r.ok) setText(await r.text());
}, [date]);
useEffect(() => {
void load();
// 오늘 로그는 5초마다 새로 받는다
if (!live || date !== days?.[0]?.date) return;
const t = window.setInterval(() => void load(), 5000);
return () => window.clearInterval(t);
}, [load, live, date, days]);
// 줄 단위로 나누되, 오류 스택(들여쓴 줄)은 위 줄에 붙인다
const entries = useMemo(() => {
const out: string[] = [];
for (const line of text.split('\n')) {
if (!line) continue;
if (line.startsWith(' ') && out.length) out[out.length - 1] += '\n' + line;
else out.push(line);
}
return out;
}, [text]);
const shown = useMemo(() => {
const kw = q.trim().toLowerCase();
return entries.filter((e) => LEVEL_RE[level].test(e) && (!kw || e.toLowerCase().includes(kw))).reverse();
}, [entries, level, q]);
const name = auth.status === 'ok' ? auth.me.user.name : '';
return (
<div className="logs-page">
<header className="logs-head">
<a href="/" className="logs-back">
<Brand />
</a>
<h1>사이트 로그</h1>
<span className="dim">{name}</span>
</header>
<p className="logs-help">
사이트 서버(gvr.tkrmagid.kr)가 남긴 기록입니다. 게임 PC 프로그램과 연결이 끊겨도 볼 수 있습니다. 문제를 알릴 때는 이 로그와 게임 PC 의 exe 로그(
<span className="mono">GVR-Data\logs\gvr-날짜.log</span>)를 같이 보내 주세요. 시각은 UTC(한국 시각 -9시간)입니다.
</p>
{err && <div className="logs-err">{err}</div>}
{days && (
<div className="logs-bar">
<select value={date ?? ''} onChange={(e) => setDate(e.target.value)} aria-label="날짜">
{days.map((d) => (
<option key={d.date} value={d.date}>
{d.date} ({(d.size / 1024).toFixed(0)} KB)
</option>
))}
</select>
<div className="logs-seg">
{(['all', 'warn', 'error'] as Level[]).map((l) => (
<button key={l} className={`chip${level === l ? ' on' : ''}`} onClick={() => setLevel(l)}>
{l === 'all' ? '전체' : l === 'warn' ? '경고 이상' : '오류만'}
</button>
))}
</div>
<input className="logs-q" value={q} onChange={(e) => setQ(e.target.value)} placeholder="찾기 (예: 게임 PC, 503, 범인찾기)" />
{date === days[0]?.date && (
<label className="logs-live">
<input type="checkbox" checked={live} onChange={(e) => setLive(e.target.checked)} /> 자동 새로 고침
</label>
)}
{date && (
<a className="chip on" href={`/site/logs/${date}?download=1`} download>
⬇ 내려받기 (gvr-site-{date}.log)
</a>
)}
</div>
)}
{days && !days.length && <p className="dim">아직 로그가 없습니다.</p>}
<div className="logs-list mono" role="log">
{shown.map((e, i) => {
const lv = /^\S+ (\w+)/.exec(e)?.[1] ?? 'INFO';
return (
<pre key={i} className={`lg lg-${lv.toLowerCase()}`}>
{e}
</pre>
);
})}
{days && date && !shown.length && <p className="dim">조건에 맞는 줄이 없습니다.</p>}
</div>
</div>
);
}

View File

@@ -105,12 +105,7 @@ export function Sidebar({ f, update, users, matches, detail }: { f: Filters; upd
</div>
</div>
<div className="side-foot">
<label className="switch">
<input type="checkbox" checked={f.hideNoise} onChange={(e) => update({ hideNoise: e.target.checked })} />
<span className="sw" />
잡음 숨기기
</label>
<button className="link-btn" onClick={tap(() => update({ users: [], game: null, match: null, from: undefined, to: undefined, q: '', types: [], hideNoise: false, order: null }))}>
<button className="link-btn" onClick={tap(() => update({ users: [], game: null, match: null, from: undefined, to: undefined, q: '', types: [], order: null }))}>
필터 초기화
</button>
</div>
@@ -151,9 +146,6 @@ export function MobileFilters({ f, update, users, matches }: { f: Filters; updat
{t.icon} {t.label}
</button>
))}
<button className={`chip${f.hideNoise ? ' on' : ''}`} onClick={() => update({ hideNoise: !f.hideNoise })}>
잡음 숨기기
</button>
</div>
);
}

View File

@@ -13,6 +13,7 @@ import { Avatar, ErrorBox, Spinner } from '../components/common';
import { IWaves } from '../components/Icons';
import { MobileFilters, Sidebar } from './Sidebar';
import { TalkBars } from '../components/TalkBars';
import { GAME_NAME, liveGameRows } from '@gvr/shared';
function NowPlayingCard() {
const item = usePlayer((s) => (s.mode === 'single' ? s.item : null));
@@ -143,6 +144,7 @@ function RightPanel({ items, detail }: { items: TimelineItem[]; detail: MatchDet
)}
</div>
)}
{!detail && <LiveGamesCard />}
<div className="card">
<h5>{detail ? '이 경기 발화량' : '지금 목록의 발화량'}</h5>
<TalkBars utts={utts} />
@@ -151,6 +153,37 @@ function RightPanel({ items, detail }: { items: TimelineItem[]; detail: MatchDet
);
}
/** 게임 PC 에 지금 연결된 게임 · 진행 중인 경기 */
function LiveGamesCard() {
const { overview } = useData();
const live = (overview?.live ?? []).filter((g) => g.enabled);
if (!overview?.live) return null;
return (
<div className="card live-card">
<h5>게임 상태</h5>
{!live.length && <div className="dim small">게임 연동이 꺼져 있습니다.</div>}
{live.map((g) => (
<div key={g.game} className={`live-g ${g.game}${g.inMatch ? ' in' : ''}`}>
<div className="live-g-top">
<span className={`ldot${g.inMatch ? ' on' : g.connected ? ' mid' : ''}`} />
<b>{GAME_NAME[g.game]}</b>
<span className="dim small">{g.phase}</span>
</div>
{(g.connected || g.inMatch) &&
liveGameRows(g)
.slice(1)
.map(([k, v]) => (
<div className="kv" key={k}>
<span className="muted">{k}</span>
<span>{v}</span>
</div>
))}
</div>
))}
</div>
);
}
export function TimelinePage() {
const [params, setParams] = useSearchParams();
const f = useMemo(() => parseFilters(params), [params]);
@@ -277,7 +310,16 @@ export function TimelinePage() {
else if (it.type === 'kill') sfx('kill');
else if (it.type === 'round_end') sfx('round');
} else if (e.type === 'utterance.updated') {
setItems((prev) => prev.map((p) => (p.id === e.data.id ? e.data : p)));
const it = e.data;
// 잡음으로 판정되면 목록에서 뺀다. 경기 뒤 정밀 변환에서 말이 나오면 다시 넣는다
if (!matchesFilter(it, f)) setItems((prev) => prev.filter((p) => p.id !== it.id));
else
setItems((prev) => {
if (prev.some((p) => p.id === it.id)) return prev.map((p) => (p.id === it.id ? it : p));
const i = prev.findIndex((p) => (order === 'desc' ? p.ts < it.ts : p.ts > it.ts));
if (i < 0) return order === 'asc' && next ? prev : [...prev, it];
return [...prev.slice(0, i), it, ...prev.slice(i)];
});
}
});

View File

@@ -140,8 +140,17 @@ export function DataProvider({ children }: { children: ReactNode }) {
};
}, [epoch, locked]);
useLive((e) => {
if (e.type === 'users.updated') setOverview((o) => (o ? { ...o, users: e.data } : o));
if (e.type === 'users.updated') {
// v1.3.5 이하 앱은 빈 목록을 보낸다: 그대로 쓰면 모든 발화가 "알 수 없음"이 되니 다시 받아 온다
if (e.data.length) setOverview((o) => (o ? { ...o, users: e.data } : o));
else
api
.users()
.then((users) => setOverview((o) => (o ? { ...o, users } : o)))
.catch(() => {});
}
if (e.type === 'recording.state') setOverview((o) => (o ? { ...o, recording: e.data } : o));
if (e.type === 'games.state') setOverview((o) => (o ? { ...o, live: e.data } : o));
});
const users = overview?.users ?? [];
const map = useMemo(() => new Map(users.map((u) => [u.id, u])), [users]);

View File

@@ -8,6 +8,8 @@ export interface Settings {
rate: number;
continuous: boolean;
normalize: boolean;
/** 녹음 재생 음량 0..2 (1 = 원래 크기) */
playVolume: number;
}
const KEY = 'gvr.settings.v1';
@@ -18,6 +20,7 @@ const DEFAULTS: Settings = {
rate: 1,
continuous: true,
normalize: true,
playVolume: 1,
};
function load(): Settings {

View File

@@ -3430,3 +3430,316 @@ button.match:hover {
.cu-row { grid-template-columns: 34px 1fr auto; }
.cu-row .cu-st { grid-column: 2 / -1; justify-self: start; }
}
/* ── 재생 음량 (플레이어 막대) ── */
.pb-vol {
display: flex;
align-items: center;
gap: 6px;
flex: none;
}
.pb-vol .icon-btn {
color: var(--muted);
}
.pb-vol .icon-btn.muted-on {
color: var(--accent);
}
.pb-vol input[type='range'] {
-webkit-appearance: none;
appearance: none;
width: 90px;
height: 4px;
border-radius: 2px;
background: linear-gradient(90deg, var(--mint, #14c1b7) var(--p, 50%), #2a3a4a var(--p, 50%));
cursor: pointer;
}
.pb-vol input[type='range']::-webkit-slider-thumb {
-webkit-appearance: none;
width: 12px;
height: 12px;
border-radius: 50%;
background: #fff;
}
.pb-vol input[type='range']::-moz-range-thumb {
width: 12px;
height: 12px;
border: 0;
border-radius: 50%;
background: #fff;
}
.pb-vol-n {
font-size: 11.5px;
width: 36px;
color: var(--muted);
}
@media (max-width: 720px) {
.pb-vol input[type='range'],
.pb-vol-n {
display: none;
}
}
/* ── 발화 우클릭 메뉴 · 자세한 정보 ── */
.ctx-menu {
position: fixed;
z-index: 80;
min-width: 210px;
background: #0f1923;
border: 1px solid #2c3f52;
border-radius: 10px;
padding: 5px;
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.55);
}
.ctx-menu button {
display: flex;
align-items: center;
gap: 9px;
width: 100%;
padding: 8px 10px;
border-radius: 7px;
font-size: 13px;
color: var(--text, #e6edf3);
text-align: left;
}
.ctx-menu button:hover:not(:disabled) {
background: #1b2a38;
}
.ctx-menu button:disabled {
opacity: 0.4;
cursor: default;
}
.ctx-ic {
width: 14px;
text-align: center;
font-size: 13px;
}
.ctx-dim {
position: fixed;
inset: 0;
z-index: 90;
background: rgba(3, 8, 12, 0.6);
display: flex;
align-items: center;
justify-content: center;
padding: 16px;
}
.ctx-dialog {
width: min(620px, 100%);
max-height: 90vh;
overflow: auto;
background: #0f1923;
border: 1px solid #2c3f52;
border-radius: 14px;
padding: 16px 18px;
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.6);
}
.ctx-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.ctx-rows {
margin: 0;
font-size: 13px;
}
.ctx-rows > div {
display: grid;
grid-template-columns: 120px 1fr;
gap: 10px;
padding: 6px 0;
border-bottom: 1px solid #1c2a37;
}
.ctx-rows dt {
color: var(--muted);
}
.ctx-rows dd {
margin: 0;
word-break: break-all;
}
.ctx-rows .path {
font-size: 12px;
}
.ctx-foot {
display: flex;
gap: 8px;
justify-content: flex-end;
margin-top: 14px;
}
.ctx-toast {
position: fixed;
left: 50%;
bottom: calc(var(--player-h) + 16px);
transform: translateX(-50%);
z-index: 95;
background: #2a1418;
border: 1px solid #5a2630;
color: #ffb3bb;
padding: 8px 14px;
border-radius: 8px;
font-size: 13px;
}
/* ── 사이트 로그 (/logs) ── */
.logs-page {
min-height: 100vh;
padding: 18px 26px 40px;
max-width: 1500px;
margin: 0 auto;
}
.logs-head {
display: flex;
align-items: center;
gap: 16px;
margin-bottom: 8px;
}
.logs-head h1 {
font-size: 18px;
margin: 0;
}
.logs-back {
display: flex;
}
.logs-help {
color: var(--muted);
font-size: 13px;
line-height: 1.6;
margin: 0 0 14px;
}
.logs-err {
background: #2a1418;
border: 1px solid #5a2630;
color: #ffb3bb;
padding: 10px 14px;
border-radius: 8px;
margin-bottom: 14px;
}
.logs-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
margin-bottom: 12px;
}
.logs-bar select,
.logs-q {
background: #0f1923;
border: 1px solid #2c3f52;
color: inherit;
border-radius: 8px;
padding: 7px 10px;
font-size: 13px;
}
.logs-q {
flex: 1;
min-width: 200px;
}
.logs-seg {
display: flex;
gap: 6px;
}
.logs-live {
font-size: 13px;
color: var(--muted);
display: flex;
align-items: center;
gap: 5px;
}
.logs-list {
background: #0a121a;
border: 1px solid #1c2a37;
border-radius: 10px;
padding: 8px 0;
font-size: 12.5px;
}
.logs-list pre {
margin: 0;
padding: 3px 14px;
white-space: pre-wrap;
word-break: break-all;
font: inherit;
}
.logs-list pre:hover {
background: #111d28;
}
.lg-warn {
color: #ffd27a;
}
.lg-error,
.lg-fatal {
color: #ff8a95;
}
.lg-info {
color: #c9d4de;
}
/* ── 지금 게임 (헤더 · 타임라인 오른쪽) ── */
.game-pill {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
border-radius: 999px;
padding: 5px 10px;
white-space: nowrap;
border: 1px solid #2c3f52;
color: #b9c6d2;
max-width: 260px;
min-width: 0;
flex-shrink: 1;
overflow: hidden;
}
.me-nm {
white-space: nowrap;
}
.game-pill .gp-name {
font-weight: 700;
}
.game-pill .gp-txt {
overflow: hidden;
text-overflow: ellipsis;
}
.game-pill.valorant.in {
border-color: rgba(255, 70, 85, 0.6);
color: #ffd0d4;
}
.game-pill.lol.in {
border-color: rgba(200, 170, 110, 0.6);
color: #f0e2c0;
}
@media (max-width: 1500px) {
.game-pill .gp-txt {
display: none;
}
}
.live-g + .live-g {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid #1c2a37;
}
.live-g-top {
display: flex;
align-items: center;
gap: 7px;
font-size: 13px;
}
.live-g-top .dim {
margin-left: auto;
}
.ldot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #4d5d6c;
}
.ldot.mid {
background: #e3b341;
}
.ldot.on {
background: #45d39a;
box-shadow: 0 0 6px rgba(69, 211, 154, 0.6);
}
.live-g.valorant.in .ldot.on {
background: var(--accent);
box-shadow: 0 0 6px rgba(255, 70, 85, 0.6);
}

View File

@@ -10,6 +10,7 @@ const proxy = {
'/auth': { target: backend, changeOrigin: false },
'/game-assets': { target: backend, changeOrigin: false },
'/mock': { target: backend, changeOrigin: false },
'/site': { target: backend, changeOrigin: false },
'/ws': { target: backend.replace(/^http/, 'ws'), ws: true },
};