556 lines
31 KiB
JavaScript
556 lines
31 KiB
JavaScript
// 겜녹이 사이트 목 서버 (개발용). 사이트 서버(7장) + 앱 API(4장) + 브라우저 WS(/ws)를 흉내 낸다.
|
|
// 의존성: node 내장 http + ws(devDependency).
|
|
//
|
|
// 제어용 엔드포인트 (목 전용):
|
|
// GET /mock/device?online=0|1 게임 PC 오프라인/온라인 전환 (생략하면 토글)
|
|
// GET /mock/device?registered=0|1 등록 안 된 상태 흉내
|
|
// GET /mock/live?on=0|1 주기적 가짜 실시간 발화 켜기/끄기
|
|
// GET /mock/emit 가짜 실시간 발화 하나 즉시 만들기
|
|
// GET /mock/latejoin 녹음 중에 새 사람이 들어와 말함 (v1.4.1 이하 앱처럼 users.updated 없이 발화만 보냄). ?again=1 이면 마지막에 들어온 사람이 또 말함
|
|
// GET /mock/users-fail?n=1 다음 n 번 /api/users 를 500 으로 실패
|
|
// GET /auth/discord?as=notmember 길드 멤버가 아닌 계정으로 로그인 흉내 (403 not_member)
|
|
import http from 'node:http';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { WebSocketServer } from 'ws';
|
|
import { db, NOW, fmtClock } from './data.mjs';
|
|
import { synthWav } from './audio.mjs';
|
|
|
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
const ASSET_DIR = path.resolve(here, '../../../docs/report/mock/assets');
|
|
const ME = { id: '310482915522101248', name: '하늘', avatar: null };
|
|
|
|
let m0;
|
|
/** 표시 이름: 목에서는 유저 목록 이름도 같이 바꾼다 (실제로는 게임 PC 앱이 받아서 바꿈) */
|
|
function setName(id, n) {
|
|
const u = db.users.find((x) => x.id === id);
|
|
if (u) u._orig ??= u.name;
|
|
if (n) state.names[id] = n;
|
|
else delete state.names[id];
|
|
if (u) u.name = n || u._orig;
|
|
broadcast({ type: 'users.updated', data: db.users });
|
|
}
|
|
const state = {
|
|
names: {},
|
|
regs: [
|
|
{ id: ME.id, name: ME.name, avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: Date.now() - 3600000, lastVersion: '1.5.0' },
|
|
],
|
|
device: { registered: true, online: process.env.MOCK_OFFLINE !== '1', name: '하늘의 게임 PC', lastSeen: Date.now(), version: '1.0.0' },
|
|
live: process.env.MOCK_LIVE !== '0',
|
|
liveInterval: Number(process.env.MOCK_LIVE_INTERVAL ?? 15000),
|
|
// 롤 경기 기록 가져오기 흉내 (v1.9.1 진행 바): 1.5초에 한 경기, MOCK_HISTORY=0 이면 끔
|
|
hist: process.env.MOCK_HISTORY === '0' ? null : { startedAt: Date.now(), total: Number(process.env.MOCK_HISTORY_TOTAL ?? 120) },
|
|
};
|
|
const histProgress = () => {
|
|
const h = state.hist;
|
|
if (!h) return null;
|
|
const el = Date.now() - h.startedAt;
|
|
if (el < 4000) return { phase: 'scan', first: true, scanned: Math.floor(el / 400) * 20, done: 0, total: Math.floor(el / 400) * 12, startedAt: h.startedAt, etaMs: null };
|
|
const done = Math.min(h.total, Math.floor((el - 4000) / 1500));
|
|
if (done >= h.total) return (state.hist = null);
|
|
return { phase: 'fetch', first: true, scanned: 200, done, total: h.total, startedAt: h.startedAt, etaMs: done ? (h.total - done) * 1500 : null };
|
|
};
|
|
const liveGames = () => [
|
|
{ game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, startedAt: Date.now() - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, historyAt: Date.now() - 12 * 60000, updatedAt: Date.now() },
|
|
{ game: 'lol', enabled: true, connected: !!state.hist, phase: state.hist ? '로비' : '롤 클라이언트 꺼짐', inMatch: false, matchId: null, mode: null, map: null, mapImage: null, startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: null, players: null, error: null, history: histProgress(), historyAt: null, updatedAt: Date.now() },
|
|
];
|
|
|
|
const json = (res, status, body, headers = {}) => {
|
|
const s = JSON.stringify(body, (k, v) => (k.startsWith('_') ? undefined : v));
|
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...headers });
|
|
res.end(s);
|
|
};
|
|
const parseCookies = (req) =>
|
|
Object.fromEntries((req.headers.cookie ?? '').split(';').map((c) => c.trim().split('=')).filter((p) => p[0]).map(([k, ...v]) => [k, decodeURIComponent(v.join('='))]));
|
|
const session = (req) => parseCookies(req).gvr_session ?? null;
|
|
const readBody = (req) =>
|
|
new Promise((resolve) => {
|
|
let b = '';
|
|
req.on('data', (c) => (b += c));
|
|
req.on('end', () => resolve(b));
|
|
});
|
|
|
|
const deviceStatus = () => ({ ...state.device, lastSeen: state.device.online ? Date.now() : state.device.lastSeen });
|
|
const deviceOk = () => state.device.registered && state.device.online;
|
|
|
|
// ── 타임라인 필터 ─────────────────────────────────────
|
|
const TYPE_GROUP = { kill: 'kill', multikill: 'kill', ace: 'kill', chat: 'chat', object: 'object', round_end: 'round', match_start: 'round', match_end: 'round', spike: 'round' };
|
|
function filterItems(q) {
|
|
const users = q.get('users') ? new Set(q.get('users').split(',')) : null;
|
|
const game = q.get('game');
|
|
const match = q.get('match');
|
|
const from = q.get('from') ? Number(q.get('from')) : null;
|
|
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 all = [...db.utterances, ...db.events];
|
|
return all.filter((it) => {
|
|
if (from != null && it.ts < from) return false;
|
|
if (to != null && it.ts > to) return false;
|
|
const g = it.kind === 'utterance' ? it.game?.type ?? null : it.game;
|
|
const mid = it.kind === 'utterance' ? it.game?.matchId ?? null : it.matchId;
|
|
if (game === 'none' && g) return false;
|
|
if (game && game !== 'none' && g !== game) return false;
|
|
if (match && mid !== match) return false;
|
|
if (types) {
|
|
const grp = it.kind === 'utterance' ? 'utterance' : TYPE_GROUP[it.type];
|
|
if (!types.has(grp)) return false;
|
|
}
|
|
if (it.kind === 'utterance') {
|
|
if (users && !users.has(it.userId)) 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;
|
|
if (kw && !(it.type === 'chat' && String(it.data.text).toLowerCase().includes(kw))) return false;
|
|
}
|
|
return true;
|
|
});
|
|
}
|
|
const cmp = (a, b) => a.ts - b.ts || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
const enc = (it) => Buffer.from(JSON.stringify([it.ts, it.id])).toString('base64url');
|
|
const dec = (c) => {
|
|
try {
|
|
const [ts, id] = JSON.parse(Buffer.from(c, 'base64url').toString());
|
|
return { ts, id };
|
|
} catch {
|
|
return null;
|
|
}
|
|
};
|
|
|
|
function timeline(q) {
|
|
const order = q.get('order') === 'asc' ? 'asc' : 'desc';
|
|
const limit = Math.min(200, Math.max(1, Number(q.get('limit') ?? 100)));
|
|
let items = filterItems(q).sort(cmp);
|
|
if (order === 'desc') items.reverse();
|
|
const cur = q.get('cursor') ? dec(q.get('cursor')) : null;
|
|
if (cur) items = items.filter((it) => (order === 'desc' ? cmp(it, cur) < 0 : cmp(it, cur) > 0));
|
|
const page = items.slice(0, limit);
|
|
return { items: page, next: items.length > limit ? enc(page[page.length - 1]) : null };
|
|
}
|
|
|
|
const hasReplay = (m) => !!m.replayPath && fs.existsSync(m.replayPath);
|
|
const summary = (m) => ({
|
|
id: m.id, game: m.game, startedAt: m.startedAt, endedAt: m.endedAt, map: m.map, mode: m.mode, win: m.win, score: m.score, status: m.status, participants: m.participants,
|
|
source: m.source ?? 'live', voice: m.utterances.length > 0,
|
|
...(m.game === 'valorant' ? { replay: hasReplay(m) } : {}),
|
|
});
|
|
|
|
function userProfile(id) {
|
|
const user = db.users.find((u) => u.id === id);
|
|
if (!user) return null;
|
|
const mine = db.utterances.filter((u) => u.userId === id && !u.noise && u.text);
|
|
const counts = new Map();
|
|
for (const u of mine) for (const w of u.words) if (w.w.length >= 2) counts.set(w.w, (counts.get(w.w) ?? 0) + 1);
|
|
const topWords = [...counts].sort((a, b) => b[1] - a[1]).slice(0, 30).map(([w, n]) => ({ w, n }));
|
|
return {
|
|
user,
|
|
stats: { talkMs: mine.reduce((n, u) => n + (u.endTs - u.ts), 0), count: mine.length, topWords },
|
|
matches: db.matches.filter((m) => m.players.some((p) => p.userId === id)).sort((a, b) => b.startedAt - a.startedAt).map(summary),
|
|
};
|
|
}
|
|
|
|
// ── WS ───────────────────────────────────────────────
|
|
let wss;
|
|
// "잡음이라 삭제"로 배운 문장 (v1.4.0)
|
|
const noisePhrases = [{ id: 1, text: '시청해 주셔서 감사합니다 자막 제공', hits: 3, createdAt: Date.now() - 86400000 }];
|
|
let noiseSeq = 1;
|
|
const broadcast = (msg) => {
|
|
const s = JSON.stringify(msg, (k, v) => (k.startsWith('_') ? undefined : v));
|
|
wss?.clients.forEach((c) => c.readyState === 1 && c.send(s));
|
|
};
|
|
const pushStatus = () => broadcast({ type: 'status', data: { device: deviceStatus() } });
|
|
|
|
function emitLive() {
|
|
if (!deviceOk()) return;
|
|
const user = db.SPEAKERS[Math.floor(Math.random() * db.SPEAKERS.length)];
|
|
const text = db.REAL_LINES[Math.floor(Math.random() * db.REAL_LINES.length)];
|
|
const it = db.addLiveUtterance(user, text);
|
|
broadcast({ type: 'utterance.created', data: it });
|
|
setTimeout(() => {
|
|
it.text = text;
|
|
it.words = db.makeWords(text, (it.endTs - it.ts) / 1000);
|
|
it.status = 'realtime';
|
|
it.model = 'large-v3-turbo';
|
|
it.confidence = 0.88;
|
|
broadcast({ type: 'utterance.updated', data: it });
|
|
}, 2600);
|
|
return it;
|
|
}
|
|
|
|
// ── HTTP ─────────────────────────────────────────────
|
|
const MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml' };
|
|
const audioCache = new Map();
|
|
|
|
async function handle(req, res) {
|
|
const url = new URL(req.url, 'http://x');
|
|
const p = url.pathname;
|
|
const q = url.searchParams;
|
|
|
|
// 목 제어
|
|
if (p === '/mock/device') {
|
|
if (q.has('registered')) state.device.registered = q.get('registered') === '1';
|
|
if (q.has('online')) state.device.online = q.get('online') === '1';
|
|
else if (!q.has('registered')) state.device.online = !state.device.online;
|
|
if (!state.device.online) state.device.lastSeen = Date.now() - 12 * 60000;
|
|
pushStatus();
|
|
return json(res, 200, { device: deviceStatus() });
|
|
}
|
|
if (p === '/mock/live') {
|
|
state.live = q.get('on') !== '0';
|
|
return json(res, 200, { live: state.live });
|
|
}
|
|
if (p === '/mock/emit') return json(res, 200, emitLive() ?? { error: 'device_offline' });
|
|
if (p === '/mock/users-fail') {
|
|
state.usersFail = Number(q.get('n') ?? 1);
|
|
return json(res, 200, { usersFail: state.usersFail });
|
|
}
|
|
if (p === '/mock/latejoin') {
|
|
const n = db.users.length;
|
|
const u = q.get('again') === '1' ? db.users[n - 1] : { id: `41000000000000${String(n).padStart(4, '0')}`, name: `늦게온사람${n}`, color: '#d4537e', avatar: null, excluded: false, riot: [] };
|
|
if (q.get('again') !== '1') db.users.push(u);
|
|
const it = db.addLiveUtterance(u, '나 지금 들어왔어');
|
|
broadcast({ type: 'utterance.created', data: it });
|
|
return json(res, 200, { user: u, utterance: it.id });
|
|
}
|
|
|
|
// 맵 3D (GVR_MOCK_MAPS3D=<사이트 서버 data/maps3d 와 같은 구조의 폴더>: index.json + <dir>/<code>.glb.gz)
|
|
if (p === '/site/maps3d' || p.startsWith('/site/maps3d/')) {
|
|
const root = process.env.GVR_MOCK_MAPS3D;
|
|
if (!root) return p === '/site/maps3d' ? json(res, 200, { version: null, dir: null, maps: {} }) : json(res, 404, { error: 'not_found' });
|
|
if (p === '/site/maps3d') return json(res, 200, JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8')));
|
|
// 무기 스킨: <폴더>/skins/index.json (없으면 빈 목록), 요청은 받기만 한다 (뽑는 쪽이 없다)
|
|
if (p === '/site/maps3d/skins') {
|
|
const f = path.join(root, 'skins', 'index.json');
|
|
return json(res, 200, fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : { skins: {}, looks: {} });
|
|
}
|
|
if (p === '/site/maps3d/skins/want') return json(res, 200, { queued: 0 });
|
|
const [dir, file] = p.slice('/site/maps3d/'.length).split('/').map(decodeURIComponent);
|
|
const f = path.join(root, dir ?? '', (file ?? '') + '.gz');
|
|
const type = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' }[path.extname(file ?? '').toLowerCase()];
|
|
if (!/^[\w.-]+$/.test(dir ?? '') || !/^[\w.-]+$/.test(file ?? '') || !type || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' });
|
|
res.writeHead(200, { 'content-type': type, 'content-encoding': 'gzip', 'content-length': fs.statSync(f).size });
|
|
return fs.createReadStream(f).pipe(res);
|
|
}
|
|
|
|
// 게임 이미지 (목: docs/report/mock/assets)
|
|
// 3D 리플레이 데모 바닥 미니맵 (GVR_MOCK_REPLAY_MAP_FILE, 데이터 생성은 data.mjs genReplayDemo)
|
|
if (p === '/game-assets/mock/replay-map.png' && process.env.GVR_MOCK_REPLAY_MAP_FILE) {
|
|
res.writeHead(200, { 'content-type': 'image/png' });
|
|
return fs.createReadStream(process.env.GVR_MOCK_REPLAY_MAP_FILE).pipe(res);
|
|
}
|
|
if (p.startsWith('/game-assets/mock/')) {
|
|
const f = path.resolve(ASSET_DIR, decodeURIComponent(p.slice('/game-assets/mock/'.length)));
|
|
if (!f.startsWith(ASSET_DIR) || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' });
|
|
res.writeHead(200, { 'content-type': MIME[path.extname(f)] ?? 'application/octet-stream', 'cache-control': 'public, max-age=86400' });
|
|
return fs.createReadStream(f).pipe(res);
|
|
}
|
|
|
|
// 인증
|
|
if (p === '/auth/discord') {
|
|
const v = q.get('as') === 'notmember' ? 'nm' : 'ok';
|
|
res.writeHead(302, { location: '/', 'set-cookie': `gvr_session=${v}; Path=/; HttpOnly; SameSite=Lax` });
|
|
return res.end();
|
|
}
|
|
if (p === '/auth/logout' && req.method === 'POST') {
|
|
res.writeHead(204, { 'set-cookie': 'gvr_session=; Path=/; Max-Age=0' });
|
|
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, name: state.names[ME.id] ?? ME.name }, isOwner: true, canViewLogs: true, role: 'superadmin' });
|
|
}
|
|
// 내 정보 · 관리 화면 (v1.6.0)
|
|
if (p === '/site/profile') return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null, role: 'superadmin' });
|
|
if (p === '/site/profile/name' && req.method === 'PUT') {
|
|
const b = JSON.parse((await readBody(req)) || '{}');
|
|
const n = String(b.name ?? '').trim();
|
|
if (n && Object.entries(state.names).some(([id, x]) => id !== ME.id && x === n)) return json(res, 400, { error: 'bad_name', message: '다른 사람이 이미 쓰는 이름입니다' });
|
|
setName(ME.id, n);
|
|
return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null });
|
|
}
|
|
if (p === '/site/admin/overview') return json(res, 200, { device: { ...deviceStatus(), guildId: '1200000000000000000' }, latest: { version: '1.6.0', url: 'https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.6.0', publishedAt: null }, role: 'superadmin', serverVersion: '1.0.0' });
|
|
if (p === '/site/admin/users' && req.method === 'GET') return json(res, 200, { users: state.regs, names: state.names });
|
|
if (p === '/site/admin/names' && req.method === 'PUT') {
|
|
const b = JSON.parse((await readBody(req)) || '{}');
|
|
setName(String(b.id), String(b.name ?? '').trim());
|
|
return json(res, 200, { names: state.names });
|
|
}
|
|
if (p === '/site/admin/users' && req.method === 'POST') {
|
|
const b = JSON.parse((await readBody(req)) || '{}');
|
|
const u = db.users.find((x) => x.id === b.id);
|
|
state.regs.push({ id: b.id, name: u?.name ?? b.id, avatar: null, role: b.role, fixed: false, addedBy: ME.id, addedAt: Date.now(), lastSeenAt: null, lastVersion: null });
|
|
return json(res, 200, { users: state.regs });
|
|
}
|
|
if ((m0 = p.match(/^\/site\/admin\/users\/(\d+)$/))) {
|
|
const b = req.method === 'PATCH' ? JSON.parse((await readBody(req)) || '{}') : {};
|
|
if (req.method === 'PATCH') state.regs = state.regs.map((r) => (r.id === m0[1] ? { ...r, role: b.role } : r));
|
|
if (req.method === 'DELETE') state.regs = state.regs.filter((r) => r.id !== m0[1]);
|
|
return json(res, 200, { users: state.regs });
|
|
}
|
|
|
|
if (p.startsWith('/api/')) {
|
|
if (!sess) return json(res, 401, { error: 'unauthorized' });
|
|
if (sess === 'nm') return json(res, 403, { error: 'not_member' });
|
|
if (p === '/api/status') return json(res, 200, { device: deviceStatus(), server: { version: '1.0.0' } });
|
|
if (!deviceOk()) return json(res, 503, { error: 'device_offline' });
|
|
await new Promise((r) => setTimeout(r, 60 + Math.random() * 120)); // 중계 지연 흉내
|
|
|
|
if (p === '/api/overview') {
|
|
return json(res, 200, {
|
|
guild: { id: '1200000000000000000', name: 'M&L', icon: null },
|
|
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: liveGames(),
|
|
counts: { utterances: db.utterances.length, matches: db.matches.length },
|
|
version: '1.0.0',
|
|
});
|
|
}
|
|
if (p === '/api/users') {
|
|
if (state.usersFail > 0) {
|
|
state.usersFail--;
|
|
return json(res, 500, { error: 'mock_fail' });
|
|
}
|
|
return json(res, 200, db.users);
|
|
}
|
|
let m;
|
|
if ((m = p.match(/^\/api\/users\/([^/]+)$/)) && req.method === 'PATCH') {
|
|
const u = db.users.find((x) => x.id === decodeURIComponent(m[1]));
|
|
if (!u) return json(res, 404, { error: 'not_found', message: '이 PC 기록에 없는 유저입니다' });
|
|
const b = JSON.parse((await readBody(req)) || '{}');
|
|
if (b.color) u.color = b.color;
|
|
if (b.excluded !== undefined) u.excluded = !!b.excluded;
|
|
if (b.riotIds) u.riot = b.riotIds.map((r) => ({ puuid: `riotid:${r}`, riotId: r }));
|
|
broadcast({ type: 'users.updated', data: db.users });
|
|
return json(res, 200, { user: u, taken: [] });
|
|
}
|
|
if ((m = p.match(/^\/api\/users\/([^/]+)$/))) {
|
|
const prof = userProfile(decodeURIComponent(m[1]));
|
|
return prof ? json(res, 200, prof) : json(res, 404, { error: 'not_found' });
|
|
}
|
|
if (p === '/api/timeline') return json(res, 200, timeline(q));
|
|
if (p === '/api/matches') {
|
|
const game = q.get('game');
|
|
const before = q.get('before') ? Number(q.get('before')) : Infinity;
|
|
const limit = Number(q.get('limit') ?? 20);
|
|
const has = q.get('has');
|
|
const keep = (x) => (has === 'voice' ? x.utterances.length > 0 : has === 'timeline' ? x.source !== 'history' || x.utterances.length > 0 : true);
|
|
// 모드 · 날짜 필터, 데스매치는 늘 뺀다 (v1.11.0 앱과 같게)
|
|
const mode = q.get('mode');
|
|
const after = q.get('after') ? Number(q.get('after')) : 0;
|
|
// 리플레이 필터 (v1.12.0 앱과 같게): 발로란트 경기만
|
|
const replay = q.get('replay');
|
|
const keepReplay = (x) => (replay === 'yes' || replay === 'no' ? x.game === 'valorant' && hasReplay(x) === (replay === 'yes') : true);
|
|
const list = db.matches
|
|
.filter((x) => (!game || x.game === game) && x.startedAt < before && x.startedAt >= after && keep(x) && keepReplay(x) && x.mode !== '데스매치' && (!mode || x.mode === mode))
|
|
.sort((a, b) => b.startedAt - a.startedAt)
|
|
.slice(0, limit)
|
|
.map(summary);
|
|
return json(res, 200, list);
|
|
}
|
|
if (p === '/api/matches/modes') {
|
|
const game = q.get('game');
|
|
const by = new Map();
|
|
for (const x of db.matches) {
|
|
if (x.mode === '데스매치' || (game && x.game !== game)) continue;
|
|
const k = `${x.game}\n${x.mode}`;
|
|
by.set(k, { game: x.game, mode: x.mode, count: (by.get(k)?.count ?? 0) + 1 });
|
|
}
|
|
return json(res, 200, [...by.values()].sort((a, b) => b.count - a.count));
|
|
}
|
|
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
|
|
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
|
if (!mt) return json(res, 404, { error: 'not_found' });
|
|
const { replayPath, ...rest } = mt;
|
|
return json(res, 200, rest);
|
|
}
|
|
if ((m = p.match(/^\/api\/matches\/([^/]+)\/replay$/))) {
|
|
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
|
if (!mt) return json(res, 404, { error: 'not_found' });
|
|
// 파일을 지웠다가 다시 두면 "리플레이 없음 → 내려받고 새로고침" 을 흉내 낼 수 있다
|
|
if (!mt.replayPath || !fs.existsSync(mt.replayPath)) return json(res, 404, { error: 'replay_not_found' });
|
|
res.writeHead(200, { 'content-type': 'application/json' });
|
|
return fs.createReadStream(mt.replayPath).pipe(res);
|
|
}
|
|
if ((m = p.match(/^\/api\/utterances\/([^/]+)$/)) && req.method === 'PATCH') {
|
|
const it = db.utterances.find((u) => u.id === decodeURIComponent(m[1]));
|
|
if (!it) return json(res, 404, { error: 'not_found' });
|
|
const body = JSON.parse((await readBody(req)) || '{}');
|
|
const text = String(body.text ?? '').trim();
|
|
if (!text) return json(res, 400, { error: 'empty_text' });
|
|
it.text = text;
|
|
it.words = db.makeWords(text, (it.endTs - it.ts) / 1000);
|
|
it.corrected = true;
|
|
it.noise = false;
|
|
if (it.status === 'pending') it.status = 'realtime';
|
|
audioCache.delete(it.id);
|
|
broadcast({ type: 'utterance.updated', data: it });
|
|
return json(res, 200, it);
|
|
}
|
|
if ((m = p.match(/^\/api\/utterances\/([^/]+)\/delete$/)) && req.method === 'POST') {
|
|
const i = db.utterances.findIndex((u) => u.id === decodeURIComponent(m[1]));
|
|
if (i < 0) return json(res, 404, { error: 'not_found' });
|
|
const body = JSON.parse((await readBody(req)) || '{}');
|
|
const [it] = db.utterances.splice(i, 1);
|
|
let learned = null;
|
|
if (body.noise && it.text) {
|
|
learned = it.text;
|
|
noisePhrases.unshift({ id: ++noiseSeq, text: it.text, hits: 0, createdAt: Date.now() });
|
|
}
|
|
broadcast({ type: 'utterance.deleted', data: { id: it.id, noise: !!body.noise } });
|
|
return json(res, 200, { ok: true, learned });
|
|
}
|
|
if (p === '/api/dictionary')
|
|
return json(res, 200, {
|
|
labels: { valorant: '발로란트', lol: '롤' },
|
|
entries: [
|
|
{ id: 1, word: '로테', from: null, kind: 'hotword', pack: 'site', source: 'site', enabled: true, hits: 12 },
|
|
{ id: 2, word: '레이즈', from: '레이저', kind: 'correction', pack: 'site', source: 'site', enabled: true, hits: 0 },
|
|
],
|
|
packs: [{ key: 'valorant', label: '발로란트', count: 420 }],
|
|
});
|
|
if (p === '/api/noise-phrases') return json(res, 200, { phrases: noisePhrases });
|
|
if ((m = p.match(/^\/api\/noise-phrases\/(\d+)$/)) && req.method === 'DELETE') {
|
|
const i = noisePhrases.findIndex((x) => x.id === Number(m[1]));
|
|
if (i < 0) return json(res, 404, { error: 'not_found' });
|
|
noisePhrases.splice(i, 1);
|
|
return json(res, 200, { ok: true });
|
|
}
|
|
if (p === '/api/bundles') {
|
|
const out = [];
|
|
for (const mt of db.matches) {
|
|
const us = db.utterances.filter((u) => u.game?.matchId === mt.id);
|
|
out.push({ id: `match-${mt.id}`, kind: 'match', label: `${mt.game === 'valorant' ? '발로란트' : '롤'} · ${mt.mode} · ${mt.map.name}`, sub: mt.score ? `${mt.win ? '승리' : '패배'} ${mt.score.ally}:${mt.score.enemy}` : null, game: mt.game, matchId: mt.id, from: mt.startedAt, to: mt.endedAt ?? mt.startedAt, utterances: us.length, audio: us.filter((u) => u.audio).length, audioBytes: us.length * 41230, events: mt.events.length, talkMs: us.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(us.map((u) => u.userId))], live: false });
|
|
}
|
|
const talk = db.utterances.filter((u) => !u.game && !u.noise).sort((a, b) => a.ts - b.ts);
|
|
const runs = [];
|
|
for (const u of talk) {
|
|
const cur = runs[runs.length - 1];
|
|
if (!cur || u.ts - cur[cur.length - 1].endTs > 30 * 60000 || db.matches.some((mt) => mt.startedAt > cur[cur.length - 1].ts && mt.startedAt <= u.ts)) runs.push([u]);
|
|
else cur.push(u);
|
|
}
|
|
for (const r of runs) {
|
|
const from = r[0].ts, to = r[r.length - 1].endTs;
|
|
const next = db.matches.find((mt) => mt.startedAt >= to && mt.startedAt - to < 30 * 60000);
|
|
const prev = db.matches.find((mt) => (mt.endedAt ?? 0) <= from && from - (mt.endedAt ?? 0) < 30 * 60000);
|
|
out.push({ id: `talk-${r[0].id}`, kind: 'talk', label: next ? '경기 전 대화' : prev ? '경기 후 대화' : '게임 밖 대화', sub: next ? `다음 경기: ${next.map.name}` : prev ? `지난 경기: ${prev.map.name}` : null, game: null, matchId: null, from, to, utterances: r.length, audio: r.filter((u) => u.audio).length, audioBytes: r.length * 41230, events: 0, talkMs: r.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(r.map((u) => u.userId))], live: false });
|
|
}
|
|
return json(res, 200, { bundles: out.sort((a, b) => b.from - a.from) });
|
|
}
|
|
if (p === '/api/games/history/cancel' && req.method === 'POST') {
|
|
const was = !!histProgress();
|
|
state.hist = null;
|
|
broadcast({ type: 'games.state', data: liveGames() });
|
|
return json(res, 200, { ok: true, cancelled: was ? ['lol'] : [], resumeAt: was ? Date.now() + 30 * 60000 : null });
|
|
}
|
|
if (p === '/api/bundles/delete' && req.method === 'POST') return json(res, 200, { bundles: 1, utterances: 12, files: 12 });
|
|
if (p === '/api/bundles/export' && req.method === 'POST') {
|
|
req.resume();
|
|
res.writeHead(200, { 'content-type': 'application/zip', 'content-disposition': 'attachment; filename="gvr-valorant-20261016-0430.zip"' });
|
|
return res.end(Buffer.from('PK\x05\x06' + '\0'.repeat(18)));
|
|
}
|
|
if (p === '/api/bundles/import' && req.method === 'POST') {
|
|
req.resume();
|
|
return json(res, 400, { error: 'invalid_bundle', message: '받아오기 실패: manifest.json 이 없습니다 (겜녹이에서 내보낸 기록 zip 이 아닙니다)' });
|
|
}
|
|
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' });
|
|
if (!it.audio) return json(res, 410, { error: 'audio_deleted' });
|
|
let buf = audioCache.get(it.id);
|
|
if (!buf) {
|
|
buf = synthWav(it);
|
|
if (audioCache.size > 300) audioCache.clear();
|
|
audioCache.set(it.id, buf);
|
|
}
|
|
const range = req.headers.range?.match(/bytes=(\d*)-(\d*)/);
|
|
if (range) {
|
|
const start = range[1] ? Number(range[1]) : 0;
|
|
const end = range[2] ? Math.min(Number(range[2]), buf.length - 1) : buf.length - 1;
|
|
res.writeHead(206, { 'content-type': 'audio/wav', 'accept-ranges': 'bytes', 'content-range': `bytes ${start}-${end}/${buf.length}`, 'content-length': end - start + 1 });
|
|
return res.end(buf.subarray(start, end + 1));
|
|
}
|
|
res.writeHead(200, { 'content-type': 'audio/wav', 'accept-ranges': 'bytes', 'content-length': buf.length });
|
|
return res.end(buf);
|
|
}
|
|
return json(res, 404, { error: 'not_found' });
|
|
}
|
|
return json(res, 404, { error: 'not_found', path: p });
|
|
}
|
|
|
|
export function startMock({ port = Number(process.env.MOCK_PORT ?? 18787) } = {}) {
|
|
const server = http.createServer((req, res) => {
|
|
handle(req, res).catch((e) => {
|
|
console.error(e);
|
|
json(res, 500, { error: 'mock_error', message: String(e) });
|
|
});
|
|
});
|
|
wss = new WebSocketServer({ noServer: true });
|
|
server.on('upgrade', (req, sock, head) => {
|
|
const url = new URL(req.url, 'http://x');
|
|
const sess = session(req);
|
|
if (url.pathname !== '/ws' || sess !== 'ok') {
|
|
sock.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
|
return sock.destroy();
|
|
}
|
|
wss.handleUpgrade(req, sock, head, (ws) => {
|
|
ws.send(JSON.stringify({ type: 'status', data: { device: deviceStatus() } }));
|
|
});
|
|
});
|
|
const timer = setInterval(() => {
|
|
if (state.live && wss.clients.size) emitLive();
|
|
}, state.liveInterval);
|
|
const hb = setInterval(() => deviceOk() && pushStatus(), 20000);
|
|
// 경기 기록 가져오기 진행 (앱은 2초마다 바뀌면 보낸다)
|
|
const histTimer = setInterval(() => {
|
|
if (!wss.clients.size) return;
|
|
const had = !!state.hist;
|
|
if (had) broadcast({ type: 'games.state', data: liveGames() });
|
|
}, 2000);
|
|
server.listen(port, '127.0.0.1', () => console.log(`[mock] http://127.0.0.1:${port} (데이터: 발화 ${db.utterances.length} · 이벤트 ${db.events.length} · 경기 ${db.matches.length} · 기준 ${fmtClock(0)})`));
|
|
server.on('close', () => {
|
|
clearInterval(timer);
|
|
clearInterval(hb);
|
|
clearInterval(histTimer);
|
|
});
|
|
return server;
|
|
}
|
|
|
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) startMock();
|