- 따라갈 사람: 봇이 서버를 지켜보기 전 멤버 요청을 사이트 서버가 forbidden 으로 거절하고 앱이 오류를 숨겨 빈 목록이 됐다 → 가입한 서버면 지켜보기 전에도 응답(source.members 가 멤버 확인), 앱은 오류 · 다시 불러오기 표시 → 내 계정 → 관리자(GET /app/admins) → 이름순, 녹음할 서버를 바꾸면 봇을 다시 붙여 새 서버를 지켜봄 - 롤 채팅 OCR 제거: 앱 설정 · 마법사 · 진단 · lol.ts · 워커 ocr.py/ocr_* op · pywinrt/mss/Pillow · win-ci ocr_lang 롤은 게임 중 전체/팀 채팅 API 가 없어 LCU(챔피언 선택 · 게임 후) + r3dlog(남아 있을 때, LCU 채팅을 지우지 않고 추가) - 표시 이름: 서버 store.displayNames (세션 · 앱 유저 · 접속 기록 이름까지 바꿈), GET /app/names, PUT /app/admin/names, cli name. 앱은 받아서 users · 지난 범인 분석 이름을 바꾸고 이후 디스코드 이름 대신 저장. 관리자 탭에 편집 UI - 저장소 시연 · 테스트 데이터 · 화면 캡처 · 계획서 PDF 의 실제 이름을 가짜 이름으로 교체 - 테스트: 앱 41 · 서버 16 · 워커 39 통과 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
300 lines
14 KiB
JavaScript
300 lines
14 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 /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();
|