M2: 사이트 서버 · 사이트 v1 - gvr.tkrmagid.kr 배포
- site/server: Discord OAuth2 + 봇 토큰 멤버 확인, 세션, 1회용 등록 코드·기기 키 인증, 게임 PC WebSocket 중계(JSON·음성 바이너리), 15초 무응답 잠금, 게임 이미지 캐시, 관리 CLI - site/web: 타임라인·따라 읽기 재생(단어 강조·이어듣기·현장 모드·재생 게인)·필터·검색·실시간·교정, 발로란트/롤 경기 상세, 잠금 화면(관리자 등록 코드), 모바일, 효과음 - deploy/site: Dockerfile·compose·deploy.sh·make-env.sh (.5, 포트 2972) - 앱 코어: 사이트 필터 묶음(킬·라운드)과 유저 필터 규칙 맞춤, hello 에 서버 ID Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
299
site/web/mock/server.mjs
Normal file
299
site/web/mock/server.mjs
Normal file
@@ -0,0 +1,299 @@
|
||||
// 겜녹이 사이트 목 서버 (개발용). 사이트 서버(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 /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 };
|
||||
|
||||
const state = {
|
||||
device: { registered: true, online: process.env.MOCK_OFFLINE !== '1', name: '승한의 게임 PC', lastSeen: Date.now(), version: '1.0.0' },
|
||||
live: process.env.MOCK_LIVE !== '0',
|
||||
liveInterval: Number(process.env.MOCK_LIVE_INTERVAL ?? 15000),
|
||||
};
|
||||
|
||||
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 hideNoise = q.get('hideNoise') === '1';
|
||||
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 (hideNoise && 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 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 });
|
||||
|
||||
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;
|
||||
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' });
|
||||
|
||||
// 게임 이미지 (목: docs/report/mock/assets)
|
||||
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 === '/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 });
|
||||
}
|
||||
|
||||
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 } },
|
||||
counts: { utterances: db.utterances.length, matches: db.matches.length },
|
||||
version: '1.0.0',
|
||||
});
|
||||
}
|
||||
if (p === '/api/users') return json(res, 200, db.users);
|
||||
let m;
|
||||
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 list = db.matches.filter((x) => (!game || x.game === game) && x.startedAt < before).sort((a, b) => b.startedAt - a.startedAt).slice(0, limit).map(summary);
|
||||
return json(res, 200, list);
|
||||
}
|
||||
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
|
||||
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
||||
return mt ? json(res, 200, mt) : json(res, 404, { error: 'not_found' });
|
||||
}
|
||||
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\/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);
|
||||
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);
|
||||
});
|
||||
return server;
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) startMock();
|
||||
Reference in New Issue
Block a user