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:
EJClaw
2026-10-15 01:32:51 +09:00
parent 2745af8f61
commit 9abda88046
84 changed files with 13399 additions and 21 deletions

109
site/web/mock/audio.mjs Normal file
View File

@@ -0,0 +1,109 @@
// 목 음성: 단어 타이밍(words s/e)에 맞춰 음절마다 모음 비슷한 소리를 합성한 16bit WAV.
// 실제 앱은 Ogg Opus 를 주지만 브라우저 입장에서는 둘 다 <audio> 로 재생된다.
const SR = 22050;
const VOWELS = [
[800, 1200], [500, 1900], [300, 2300], [500, 900], [350, 800], [650, 1600],
];
const PITCH = { '310482915522101248': 118, '310482915522101249': 104, '310482915522101250': 205, '310482915522101251': 140 };
function hash(str) {
let h = 2166136261;
for (let i = 0; i < str.length; i++) h = Math.imul(h ^ str.charCodeAt(i), 16777619);
return h >>> 0;
}
/** @param {any} utt UtteranceItem */
export function synthWav(utt) {
const dur = utt.audio.durationMs / 1000;
const n = Math.ceil(dur * SR);
const out = new Float32Array(n);
// 원래 음량: 게인이 클수록(조용한 사람) 작게 녹음된 것
const amp = 0.45 * Math.pow(10, -utt.audio.gainDb / 20);
const f0base = PITCH[utt.userId] ?? 130;
let seed = hash(utt.id);
const rand = () => {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
};
if (utt.noise || !utt.words.length) {
// 잡음 / 처리 중: 짧은 숨소리·키보드 같은 잡음 덩어리
const bursts = utt.noise ? 5 : 0;
if (!bursts) {
// 처리 중 발화도 소리는 있다 (텍스트만 없음) → 음절 몇 개
const syl = Math.max(3, Math.round(dur * 4));
return encode(voice(out, [{ s: 0.1, e: dur - 0.1, syl }], f0base, amp, rand));
}
for (let b = 0; b < bursts; b++) {
const st = Math.floor(rand() * n * 0.8);
const len = Math.floor(SR * (0.04 + rand() * 0.12));
let lp = 0;
for (let i = 0; i < len && st + i < n; i++) {
lp += (rand() * 2 - 1 - lp) * 0.3;
const env = Math.sin((Math.PI * i) / len);
out[st + i] += lp * env * amp * 0.9;
}
}
return encode(out);
}
const segs = utt.words.map((w) => ({ s: w.s, e: w.e, syl: Math.max(1, [...w.w].length) }));
return encode(voice(out, segs, f0base, amp, rand));
}
function voice(out, segs, f0base, amp, rand) {
let phase = 0;
for (const seg of segs) {
const s0 = Math.floor(seg.s * SR);
const s1 = Math.min(out.length, Math.floor(seg.e * SR));
const total = s1 - s0;
if (total <= 0) continue;
const sylLen = total / seg.syl;
for (let k = 0; k < seg.syl; k++) {
const [F1, F2] = VOWELS[Math.floor(rand() * VOWELS.length)];
const a = s0 + Math.floor(k * sylLen);
const b = s0 + Math.floor((k + 1) * sylLen);
const pitchStart = f0base * (0.95 + rand() * 0.15);
const pitchEnd = pitchStart * (0.9 + rand() * 0.15);
const loud = 0.7 + rand() * 0.3;
for (let i = a; i < b; i++) {
const x = (i - a) / (b - a);
const f0 = pitchStart + (pitchEnd - pitchStart) * x;
phase += (2 * Math.PI * f0) / SR;
// 음절 엔벌로프: 빠른 어택, 부드러운 릴리즈
const env = Math.min(1, x / 0.12) * Math.min(1, (1 - x) / 0.3) * loud;
let v = 0;
for (let h = 1; h * f0 < 3800; h++) {
const f = h * f0;
const r1 = 1 / (1 + ((f - F1) / 140) ** 2);
const r2 = 0.6 / (1 + ((f - F2) / 200) ** 2);
v += (r1 + r2 + 0.02) * Math.sin(h * phase) / Math.sqrt(h);
}
out[i] += v * env * amp * 0.55;
}
}
}
return out;
}
function encode(samples) {
const n = samples.length;
const buf = Buffer.alloc(44 + n * 2);
buf.write('RIFF', 0);
buf.writeUInt32LE(36 + n * 2, 4);
buf.write('WAVE', 8);
buf.write('fmt ', 12);
buf.writeUInt32LE(16, 16);
buf.writeUInt16LE(1, 20);
buf.writeUInt16LE(1, 22);
buf.writeUInt32LE(SR, 24);
buf.writeUInt32LE(SR * 2, 28);
buf.writeUInt16LE(2, 32);
buf.writeUInt16LE(16, 34);
buf.write('data', 36);
buf.writeUInt32LE(n * 2, 40);
for (let i = 0; i < n; i++) {
const v = Math.max(-1, Math.min(1, samples[i]));
buf.writeInt16LE(Math.round(v * 32767), 44 + i * 2);
}
return buf;
}

531
site/web/mock/data.mjs Normal file
View File

@@ -0,0 +1,531 @@
// 목 데이터 생성기. 서버 시작 시각(NOW) 기준으로 오늘 저녁 세션을 만든다.
// 롤 1판(19:40 무렵) → 발로란트 바인드(패) → 발로란트 어센트(13:9 승) → 경기 후 잡담.
// 이미지 URL 은 실제 사이트 서버 캐시 경로 형식(/game-assets/...)을 흉내 낸 /game-assets/mock/...
export const A = (p) => `/game-assets/mock/${p}`;
function mulberry32(a) {
return function () {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const rnd = mulberry32(20261015);
const pick = (arr) => arr[Math.floor(rnd() * arr.length)];
const range = (a, b) => a + rnd() * (b - a);
const irange = (a, b) => Math.floor(range(a, b + 1));
export function fmtClock(ms) {
const neg = ms < 0;
let s = Math.floor(Math.abs(ms) / 1000);
const h = Math.floor(s / 3600);
s -= h * 3600;
const m = Math.floor(s / 60);
s -= m * 60;
const body = h > 0 ? `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}` : `${m}:${String(s).padStart(2, '0')}`;
return neg ? `-${body}` : body;
}
export function fmtReal(ts) {
return new Intl.DateTimeFormat('ko-KR', { timeZone: 'Asia/Seoul', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(ts);
}
// ── 유저 ──────────────────────────────────────────────
export const USERS = [
{ id: '310482915522101248', name: '승한', color: '#3987e5', avatar: null, excluded: false, riot: [{ puuid: 'p-sh', riotId: '승한#KR1' }] },
{ id: '310482915522101249', name: '민수', color: '#e5743f', avatar: null, excluded: false, riot: [{ puuid: 'p-ms', riotId: '민수#0707' }] },
{ id: '310482915522101250', name: '지우', color: '#1fb383', avatar: null, excluded: false, riot: [{ puuid: 'p-jw', riotId: '지우#KR2' }] },
{ id: '310482915522101251', name: '현우', color: '#9085e9', avatar: null, excluded: false, riot: [{ puuid: 'p-hw', riotId: '현우#HW1' }] },
{ id: '310482915522101252', name: '도윤', color: '#c98500', avatar: null, excluded: true, riot: [] },
];
const [SH, MS, JW, HW] = USERS;
const SPEAKERS = [SH, MS, JW, HW];
// 유저별 평소 음량 → 재생 게인. 지우는 마이크가 작아서 +13dB
export const USER_GAIN = { [SH.id]: 4.1, [MS.id]: -1.5, [JW.id]: 13.2, [HW.id]: 6.8 };
// ── 문장 풀 ───────────────────────────────────────────
const VAL_LINES = [
'B 쪽 조용한데 로테 도는 거 같아', '미드 하나 있어 체력 낮아', '스파이크 내가 들게', '에코 라운드야 아끼자', '풀바이 가자',
'나 오퍼 사줄 사람', '나 셰리프만 살게', '레이즈 궁 빠졌어', '제트 대시 썼어', '연막 깔아줘', '플래시 간다 셋 둘 하나',
'시간 끌어 수비 오고 있어', '해체 해 내가 커버할게', 'B 롱 하나 죽였어', '킬조이 터렛 있어 조심', '드론 날린다',
'정찰 화살 쏠게 A 사이트', '뒤에 하나 남았어', '나 죽었어 미안', '와 에이스 각이었는데', '다음 라운드 B로 가자',
'체력 30이야 뒤로 빠질게', '궁 찼다 이번 판 쓴다', '세이지 벽 칠게', '부활 해줄게 잠깐만', '오멘 텔레포트 탄다',
'적 셋이 A로 온다', '포지션 바꿔 너무 뻔해', '고마워 덕분에 살았다', '잘했다 이거 이겼어', '마켓 쪽 발소리 들려',
'헤븐에 하나 있어', '스파이크 떨궜어 주워줘', '나 이번엔 미드 볼게',
];
const LOL_LINES = [
'탑 갱 간다 점멸 없어', '미드 미아 미아', '와드 박아줘 강가에', '바론 치자 지금 다 죽었어', '정글 동선 봤어 위쪽이야',
'나 귀환할게 템 사고 올게', '포탑 다이브 하지 마', '유충 먹으러 가자', '쓰레쉬 랜턴 줘', '점멸 빠졌다 상대 미드',
'궁 쿨 30초 남았어', '봇 듀오 둘 다 체력 낮아', '르블랑 사라졌어 조심해', '세주아니 궁 맞으면 끝이야', '억제기 밀고 빠지자',
'용 영혼 각이다', '가렌 스플릿 가줘', '이즈 뒤에서 딜 넣어', '한 명만 잡고 빠지자', '킬 따줘서 고마워', '전령 먹고 미드 박자',
];
const REAL_LINES = [
'오늘 몇 판 할 거야', '잠깐 물 좀 떠올게', '롤 한 판 더 할까 발로 갈까', '아까 그 한타 진짜 미쳤다',
'다음 판은 내가 감시자 할게', '배고프다 치킨 시킬까', '마이크 소리 너무 작아', '아 렉 걸렸어 잠깐만', '녹음 잘 되고 있지?',
'내일도 이 시간에 모여', '랭크 점수 얼마나 올랐어', '새 요원 써볼까', '오늘 컨디션 좋다', '디코 잠깐 나갔다 올게',
];
const CHAT_VAL = ['스파이크 설치함 B로 돌지마', 'ㄱㄱ', '에코', '오퍼 드랍 부탁', 'A 3명', 'gg', '나이스'];
const CHAT_LOL = ['용 치자 바론 말고', '미드 미아', '점멸 없음 바텀', '귀환 ㄱ', '바론 ㄱㄱ', 'ㅈㅅ'];
// ── 공통 생성 ─────────────────────────────────────────
const utterances = [];
const events = [];
const matches = [];
let seq = 1;
const nid = (p) => `${p}${String(seq++).padStart(5, '0')}`;
function makeWords(text, durSec) {
const toks = text.split(/\s+/).filter(Boolean);
const chars = toks.reduce((n, t) => n + t.length, 0) || 1;
const lead = 0.12;
const usable = Math.max(0.3, durSec - lead - 0.15);
let t = lead;
return toks.map((w) => {
const len = (usable * w.length) / chars;
const s = +t.toFixed(2);
const e = +(t + len * 0.86).toFixed(2);
t += len;
return { w, s, e, p: +range(0.62, 0.99).toFixed(2) };
});
}
/** 발화 하나 생성. game 컨텍스트와 time 라벨을 받는다. */
function addUtt({ user, ts, text, game = null, time, noise = false, status = 'precise', audio = true }) {
const syll = text ? text.replace(/\s/g, '').length : 4;
const durMs = Math.round((noise ? range(0.6, 1.4) : syll * range(0.17, 0.22) + 0.5) * 1000);
const id = nid('ut_');
const gainDb = +(USER_GAIN[user.id] + range(-0.8, 0.8)).toFixed(1);
const it = {
kind: 'utterance',
id,
ts,
endTs: ts + durMs,
userId: user.id,
text: noise || status === 'pending' ? null : text,
words: noise || status === 'pending' ? [] : makeWords(text, durMs / 1000),
noise,
status,
corrected: false,
confidence: noise || status === 'pending' ? null : +range(0.74, 0.97).toFixed(2),
model: status === 'pending' ? null : status === 'precise' ? 'large-v3' : 'large-v3-turbo',
audio: audio ? { url: `/api/audio/${id}`, durationMs: durMs, gainDb } : null,
game,
time,
_pendingText: status === 'pending' ? text : undefined,
};
utterances.push(it);
return it;
}
const realLabel = (ts) => ({ primary: fmtReal(ts), real: ts });
// ── 발로란트 ─────────────────────────────────────────
const AG = {
jett: { id: 'add6443a-41bd-e414-f6ad-e58d267f4e95', name: '제트', icon: A('val/a-jett.png') },
sova: { id: '320b2a48-4d9b-a075-30f1-1f93a9b638fa', name: '소바', icon: A('val/a-sova.png') },
sage: { id: '569fdd95-4d10-43ab-ca70-79becc718b46', name: '세이지', icon: A('val/a-sage.png') },
omen: { id: '8e253930-4c05-31dd-1b6c-968525494517', name: '오멘', icon: A('val/a-omen.png') },
killjoy: { id: '1e58de9c-4950-5125-93e9-a0aee9f98746', name: '킬조이', icon: A('val/a-killjoy.png') },
raze: { id: 'f94c3b30-42be-e959-889c-5aa313dba261', name: '레이즈', icon: A('val/a-raze.png') },
reyna: { id: 'a3bfb853-43b2-7238-a4f1-ad90e9e46bcc', name: '레이나', icon: A('val/a-reyna.png') },
};
const WP = {
vandal: { id: '9c82e19d-4575-0200-1a81-3eacf00cf872', name: '밴달', icon: A('val/w-vandal-kill.png') },
phantom: { id: 'ee8e8d15-496b-07ac-e5f6-8fae5d4c7b1a', name: '팬텀', icon: A('val/w-phantom-kill.png') },
operator: { id: 'a03b24d3-4319-996d-0f8c-94bbfba1dfc7', name: '오퍼레이터', icon: A('val/w-operator-kill.png') },
sheriff: { id: 'e336c6b8-418d-9340-d77f-7a9e4cfe0702', name: '셰리프', icon: A('val/w-sheriff-kill.png') },
};
// 어센트 미니맵 위 플레이 가능한 지점(이미지 비율 u,v) → 게임 좌표 역변환
const ASCENT_T = { xMultiplier: 7e-5, yMultiplier: -7e-5, xScalarToAdd: 0.813895, yScalarToAdd: 0.573242 };
const ASCENT_SPOTS = [
[320, 150], [300, 190], [400, 140], [410, 300], [480, 130], [500, 250], [330, 290], [200, 350], [500, 500], [540, 520],
[420, 500], [300, 480], [310, 570], [180, 640], [160, 450], [100, 450], [280, 800], [240, 770], [300, 700], [420, 750],
[560, 740], [800, 580], [900, 580], [790, 420], [600, 270], [690, 400], [560, 450],
];
function valLoc(T, spot) {
const u = (spot[0] + range(-14, 14)) / 1024;
const v = (spot[1] + range(-14, 14)) / 1024;
return { x: Math.round((v - T.yScalarToAdd) / T.yMultiplier), y: Math.round((u - T.xScalarToAdd) / T.xMultiplier) };
}
const ROUND_RESULT = ['Elimination', 'Bomb detonated', 'Bomb defused', 'Round timer expired'];
function genValorant({ id, mapName, mapId, image, T, start, results, mode = '경쟁전', linesPerRound = [3, 5], scripted = {} }) {
const ally = [
{ puuid: 'p-sh', name: '승한', tag: 'KR1', team: 'Blue', ally: true, character: AG.jett, userId: SH.id },
{ puuid: 'p-ms', name: '민수', tag: '0707', team: 'Blue', ally: true, character: AG.sova, userId: MS.id },
{ puuid: 'p-jw', name: '지우', tag: 'KR2', team: 'Blue', ally: true, character: AG.sage, userId: JW.id },
{ puuid: 'p-hw', name: '현우', tag: 'HW1', team: 'Blue', ally: true, character: AG.omen, userId: HW.id },
{ puuid: 'p-r1', name: 'Duck', tag: 'KR3', team: 'Blue', ally: true, character: AG.killjoy },
];
const enemy = [
{ puuid: 'e-1', name: 'Lumi', tag: 'KR1', team: 'Red', ally: false, character: AG.raze },
{ puuid: 'e-2', name: 'Nox', tag: '0420', team: 'Red', ally: false, character: AG.killjoy },
{ puuid: 'e-3', name: 'Haru', tag: 'KR2', team: 'Red', ally: false, character: AG.reyna },
{ puuid: 'e-4', name: 'Mint', tag: '7777', team: 'Red', ally: false, character: AG.omen },
{ puuid: 'e-5', name: 'Kiwi', tag: 'KR9', team: 'Red', ally: false, character: AG.sova },
];
const players = [...ally, ...enemy].map((p) => ({ ...p, kills: 0, deaths: 0, assists: 0, score: 0, rank: null }));
const byPuuid = Object.fromEntries(players.map((p) => [p.puuid, p]));
const ref = (p) => ({ puuid: p.puuid, name: `${p.name}#${p.tag}`, team: p.team, character: p.character, userId: p.userId });
const refUserName = (p) => (p.userId ? p.name : `${p.name}#${p.tag}`);
const ROUND_LEN = 112000;
const BUY = 30000;
const rounds = [];
const mEvents = [];
const mUtts = [];
let score = { ally: 0, enemy: 0 };
const label = (ts, rStart, num) => {
const inRound = ts - rStart;
const primary = inRound < BUY ? `R${num} · 구매` : `R${num} · ${fmtClock(inRound - BUY)}`;
return { primary, secondary: fmtClock(ts - start), real: ts };
};
const ecoPattern = [4, 12, 9, 20, 8, 22, 25, 14, 6, 21, 24, 26, 15, 4, 11, 22, 18, 24, 12, 23, 25, 26];
mEvents.push({ kind: 'event', id: nid('ev_'), ts: start, game: 'valorant', matchId: id, type: 'match_start', data: { map: mapName, mode }, time: { primary: 'R1 · 구매', secondary: '0:00', real: start } });
results.split('').forEach((rc, i) => {
const num = i + 1;
const win = rc === 'W';
const rStart = start + i * ROUND_LEN;
const combatLen = irange(55, 80) * 1000;
const rEnd = rStart + BUY + combatLen;
// 경제
const teamCred = ecoPattern[i % ecoPattern.length] * 1000 + irange(0, 900);
const economy = {};
for (const p of ally) {
const total = Math.round(teamCred / 5 + range(-500, 500));
const spent = Math.max(0, Math.min(total, Math.round(total * range(0.55, 0.95))));
economy[p.puuid] = { spent, remaining: total - spent, weapon: spent > 3500 ? (p.character === AG.jett && spent > 4500 ? '오퍼레이터' : '밴달') : spent > 1500 ? '셰리프' : '클래식' };
}
// 킬
const nKills = irange(5, 9);
const allyDead = new Set();
const enemyDead = new Set();
const kills = [];
for (let k = 0; k < nKills; k++) {
const allyKills = win ? rnd() < 0.62 : rnd() < 0.4;
const killers = (allyKills ? ally : enemy).filter((p) => !(allyKills ? allyDead : enemyDead).has(p.puuid));
const victims = (allyKills ? enemy : ally).filter((p) => !(allyKills ? enemyDead : allyDead).has(p.puuid));
if (!killers.length || !victims.length) break;
const killer = pick(killers);
const victim = pick(victims);
(allyKills ? enemyDead : allyDead).add(victim.puuid);
kills.push({ killer, victim, allyKills });
}
let t = rStart + BUY + irange(8, 20) * 1000;
const step = (combatLen - 15000) / Math.max(1, kills.length);
for (const k of kills) {
t += Math.round(step * range(0.5, 1.3));
if (t > rEnd - 2000) t = rEnd - 2000 - irange(0, 3000);
const killer = byPuuid[k.killer.puuid];
const victim = byPuuid[k.victim.puuid];
killer.kills++;
victim.deaths++;
killer.score += irange(150, 260);
const mates = (k.allyKills ? ally : enemy).filter((p) => p !== k.killer);
const assists = rnd() < 0.5 ? [pick(mates)] : [];
assists.forEach((a) => {
byPuuid[a.puuid].assists++;
byPuuid[a.puuid].score += 50;
});
const weapon = killer.character === AG.jett && rnd() < 0.4 ? WP.operator : pick([WP.vandal, WP.vandal, WP.phantom, WP.sheriff]);
mEvents.push({
kind: 'event', id: nid('ev_'), ts: t, game: 'valorant', matchId: id, type: 'kill', round: num,
data: { killer: ref(killer), victim: ref(victim), assists: assists.map(ref), weapon, headshot: rnd() < 0.35, location: valLoc(T, pick(ASCENT_SPOTS)), ally: k.allyKills },
time: label(t, rStart, num), userId: killer.userId ?? victim.userId,
});
}
// 스파이크
if (rnd() < 0.55) {
const ts = rStart + BUY + Math.round(combatLen * range(0.35, 0.6));
const planter = pick(win ? ally : enemy);
mEvents.push({ kind: 'event', id: nid('ev_'), ts, game: 'valorant', matchId: id, type: 'spike', round: num, data: { action: 'plant', site: pick(['A', 'B']), player: ref(planter), location: valLoc(T, pick([[320, 150], [280, 800]])) }, time: label(ts, rStart, num), userId: planter.userId });
}
// 발화
const nLines = scripted[num] ? 0 : irange(linesPerRound[0], linesPerRound[1]);
for (let l = 0; l < nLines; l++) {
const ts = rStart + irange(4, Math.floor((BUY + combatLen) / 1000) - 3) * 1000 + irange(0, 900);
const user = pick(SPEAKERS);
const noise = rnd() < 0.08;
mUtts.push(addUtt({ user, ts, text: pick(VAL_LINES), noise, game: { type: 'valorant', matchId: id, round: num }, time: label(ts, rStart, num) }));
}
for (const s of scripted[num] ?? []) {
const ts = rStart + BUY + s.at * 1000;
if (s.chat) {
mEvents.push({ kind: 'event', id: nid('ev_'), ts, game: 'valorant', matchId: id, type: 'chat', round: num, data: { sender: { name: s.user.name, puuid: s.user.riot[0]?.puuid, userId: s.user.id }, channel: 'team', text: s.chat, source: 'log' }, time: label(ts, rStart, num), userId: s.user.id });
} else {
mUtts.push(addUtt({ user: s.user, ts, text: s.text ?? '', noise: !!s.noise, game: { type: 'valorant', matchId: id, round: num }, time: label(ts, rStart, num) }));
}
}
if (!scripted[num] && rnd() < 0.3) {
const ts = rStart + irange(5, 25) * 1000;
const u = pick(SPEAKERS);
mEvents.push({ kind: 'event', id: nid('ev_'), ts, game: 'valorant', matchId: id, type: 'chat', round: num, data: { sender: { name: u.name, puuid: u.riot[0]?.puuid, userId: u.id }, channel: pick(['team', 'team', 'all', 'party']), text: pick(CHAT_VAL), source: 'log' }, time: label(ts, rStart, num), userId: u.id });
}
if (win) score = { ...score, ally: score.ally + 1 };
else score = { ...score, enemy: score.enemy + 1 };
const result = enemyDead.size === 5 || allyDead.size === 5 ? 'Elimination' : pick(ROUND_RESULT.slice(1));
mEvents.push({ kind: 'event', id: nid('ev_'), ts: rEnd, game: 'valorant', matchId: id, type: 'round_end', round: num, data: { round: num, win, result, score: { ...score } }, time: label(rEnd, rStart, num) });
rounds.push({ num, startedAt: rStart, endedAt: rEnd, win, result, score: { ...score }, economy });
});
const endedAt = rounds[rounds.length - 1].endedAt + 8000;
mEvents.push({ kind: 'event', id: nid('ev_'), ts: endedAt, game: 'valorant', matchId: id, type: 'match_end', data: { win: score.ally > score.enemy, score }, time: { primary: fmtClock(endedAt - start), real: endedAt } });
for (const e of mEvents) delete e.round;
events.push(...mEvents);
const summary = {
id, game: 'valorant', startedAt: start, endedAt, map: { id: mapId, name: mapName, image }, mode,
win: score.ally > score.enemy, score, status: 'complete', participants: [SH.id, MS.id, JW.id, HW.id],
};
matches.push({ ...summary, players, rounds, events: mEvents, utterances: mUtts, mapTransform: { valorant: T } });
}
// ── 롤 ───────────────────────────────────────────────
const CH = {
Ahri: { id: 'Ahri', name: '아리', icon: A('lol/c-Ahri.png') },
LeeSin: { id: 'LeeSin', name: '리 신', icon: A('lol/c-LeeSin.png') },
Garen: { id: 'Garen', name: '가렌', icon: A('lol/c-Garen.png') },
Ezreal: { id: 'Ezreal', name: '이즈리얼', icon: A('lol/c-Ezreal.png') },
Thresh: { id: 'Thresh', name: '쓰레쉬', icon: A('lol/c-Thresh.png') },
Leblanc: { id: 'Leblanc', name: '르블랑', icon: A('lol/c-Leblanc.png') },
Sejuani: { id: 'Sejuani', name: '세주아니', icon: A('lol/c-Sejuani.png') },
Darius: { id: 'Darius', name: '다리우스', icon: null },
Caitlyn: { id: 'Caitlyn', name: '케이틀린', icon: null },
Lulu: { id: 'Lulu', name: '룰루', icon: null },
};
const OBJ_ICON = {
dragon_infernal: A('lol/o-dragon_infernal.png'), dragon_ocean: A('lol/o-dragon_ocean.png'), dragon_mountain: A('lol/o-dragon_mountain.png'),
baron: A('lol/o-baron.png'), grub: A('lol/o-grub.png'), tower: A('lol/o-tower.png'),
};
const LOL_T = { minX: -120, minY: -120, maxX: 14870, maxY: 14980 };
function genLol({ id, start }) {
const DUR = (32 * 60 + 14) * 1000;
const endedAt = start + DUR;
const ally = [
{ puuid: 'p-sh', name: '승한', tag: 'KR1', team: '100', ally: true, character: CH.Ahri, userId: SH.id, lane: 'mid' },
{ puuid: 'p-ms', name: '민수', tag: '0707', team: '100', ally: true, character: CH.LeeSin, userId: MS.id, lane: 'jg' },
{ puuid: 'p-hw', name: '현우', tag: 'HW1', team: '100', ally: true, character: CH.Garen, userId: HW.id, lane: 'top' },
{ puuid: 'p-ez', name: 'Ezreal', tag: 'KR7', team: '100', ally: true, character: CH.Ezreal, lane: 'bot' },
{ puuid: 'p-jw', name: '지우', tag: 'KR2', team: '100', ally: true, character: CH.Thresh, userId: JW.id, lane: 'sup' },
];
const enemy = [
{ puuid: 'l-1', name: 'Velvet', tag: 'KR1', team: '200', ally: false, character: CH.Leblanc },
{ puuid: 'l-2', name: 'IceQ', tag: 'KR5', team: '200', ally: false, character: CH.Sejuani },
{ puuid: 'l-3', name: 'Axe', tag: 'NOX', team: '200', ally: false, character: CH.Darius },
{ puuid: 'l-4', name: 'Piltie', tag: 'KR3', team: '200', ally: false, character: CH.Caitlyn },
{ puuid: 'l-5', name: 'Pix', tag: 'KR8', team: '200', ally: false, character: CH.Lulu },
];
const players = [...ally, ...enemy].map(({ lane, ...p }) => ({ ...p, kills: 0, deaths: 0, assists: 0, cs: 0, gold: 0, level: 1, items: [], rank: null }));
const byPuuid = Object.fromEntries(players.map((p) => [p.puuid, p]));
const ref = (p) => ({ puuid: p.puuid, name: p.userId ? p.name : p.character.name, team: p.team, character: p.character, userId: p.userId });
const label = (ts) => ({ primary: fmtClock(ts - start), real: ts });
const mEvents = [];
const mUtts = [];
const at = (mm, ss) => start + (mm * 60 + ss) * 1000;
mEvents.push({ kind: 'event', id: nid('ev_'), ts: start, game: 'lol', matchId: id, type: 'match_start', data: { map: '소환사의 협곡', mode: '개인/2인 랭크' }, time: label(start) });
// 골드 차이 (분 단위)
const curve = [0, -100, 200, -300, -500, -150, 300, 500, 250, 900, 1200, 1500, 2100, 1900, 2600, 3200, 2800, 3500, 4100, 3900, 4600, 5200, 4800, 5600, 6100, 5800, 6900, 7400, 7100, 7800, 8000, 8100, 8200];
const goldDiff = curve.map((d, m) => ({ t: m * 60000, diff: d + (m ? irange(-150, 150) : 0) }));
goldDiff[goldDiff.length - 1] = { t: DUR, diff: 8200 };
// 오브젝트
const objs = [
{ t: at(5, 55), object: 'grub', icon: OBJ_ICON.grub, ally: true, loc: { x: 4950, y: 10400 }, killer: 'p-ms' },
{ t: at(6, 10), object: 'dragon', subtype: 'infernal', icon: OBJ_ICON.dragon_infernal, ally: true, loc: { x: 9866, y: 4414 }, killer: 'p-ms' },
{ t: at(10, 40), object: 'tower', subtype: 'outer_bot', icon: OBJ_ICON.tower, ally: false, loc: { x: 13866, y: 4505 } },
{ t: at(12, 30), object: 'dragon', subtype: 'ocean', icon: OBJ_ICON.dragon_ocean, ally: true, loc: { x: 9866, y: 4414 }, killer: 'p-ms' },
{ t: at(14, 2), object: 'tower', subtype: 'outer_top', icon: OBJ_ICON.tower, ally: true, loc: { x: 4318, y: 13875 } },
{ t: at(17, 20), object: 'tower', subtype: 'outer_mid', icon: OBJ_ICON.tower, ally: true, loc: { x: 8955, y: 8510 } },
{ t: at(21, 38), object: 'dragon', subtype: 'ocean', icon: OBJ_ICON.dragon_ocean, ally: true, loc: { x: 9866, y: 4414 }, killer: 'p-ms' },
{ t: at(22, 5), object: 'tower', subtype: 'outer_mid', icon: OBJ_ICON.tower, ally: true, loc: { x: 9767, y: 10113 } },
{ t: at(24, 50), object: 'tower', subtype: 'inner_bot', icon: OBJ_ICON.tower, ally: false, loc: { x: 8955, y: 1600 } },
{ t: at(26, 40), object: 'baron', icon: OBJ_ICON.baron, ally: true, loc: { x: 4942, y: 10395 }, killer: 'p-ms' },
{ t: at(28, 12), object: 'dragon', subtype: 'mountain', icon: OBJ_ICON.dragon_mountain, ally: true, loc: { x: 9866, y: 4414 }, killer: 'p-ms' },
{ t: at(29, 30), object: 'inhibitor', subtype: 'mid', icon: OBJ_ICON.tower, ally: true, loc: { x: 11598, y: 11667 } },
{ t: at(31, 50), object: 'tower', subtype: 'nexus', icon: OBJ_ICON.tower, ally: true, loc: { x: 13052, y: 12612 } },
];
for (const o of objs) {
const killer = o.killer ? byPuuid[o.killer] : null;
mEvents.push({
kind: 'event', id: nid('ev_'), ts: o.t, game: 'lol', matchId: id, type: 'object',
data: { object: o.object, subtype: o.subtype, team: o.ally ? '100' : '200', killer: killer ? ref(killer) : null, ally: o.ally, icon: o.icon, location: o.loc },
time: label(o.t), userId: killer?.userId,
});
}
// 킬 45개 (우리 27 : 18)
const killTimes = [];
for (let i = 0; i < 45; i++) killTimes.push(irange(150, DUR / 1000 - 60));
killTimes.sort((a, b) => a - b);
// 21:14 한타 장면 고정
const scriptedKills = [
{ s: 21 * 60 + 16, killer: 'p-sh', victim: 'l-1', assists: ['p-ms', 'p-jw'], loc: { x: 9300, y: 4300 } },
{ s: 21 * 60 + 19, killer: 'p-ms', victim: 'l-2', assists: ['p-jw'], loc: { x: 10100, y: 4900 }, multi: 2 },
];
let allyLeft = 25;
let enemyLeft = 18;
killTimes.forEach((s, i) => {
if (s > 20 * 60 + 50 && s < 21 * 60 + 40) s += 60;
const allyKills = allyLeft && (rnd() < allyLeft / (allyLeft + enemyLeft) || !enemyLeft);
if (allyKills) allyLeft--;
else if (enemyLeft) enemyLeft--;
else return;
const killer = pick(allyKills ? ally : enemy);
const victim = pick(allyKills ? enemy : ally);
const mates = (allyKills ? ally : enemy).filter((p) => p !== killer);
const asg = mates.filter(() => rnd() < 0.35);
scriptedKills.push({ s, killer: killer.puuid, victim: victim.puuid, assists: asg.map((a) => a.puuid), loc: { x: irange(1200, 13600), y: irange(1200, 13600) }, i });
});
for (const k of scriptedKills) {
const ts = start + k.s * 1000;
const killer = byPuuid[k.killer];
const victim = byPuuid[k.victim];
killer.kills++;
victim.deaths++;
k.assists.forEach((a) => byPuuid[a].assists++);
mEvents.push({
kind: 'event', id: nid('ev_'), ts, game: 'lol', matchId: id, type: 'kill',
data: { killer: ref(killer), victim: ref(victim), assists: k.assists.map((a) => ref(byPuuid[a])), weapon: null, location: k.loc, ally: killer.ally },
time: label(ts), userId: killer.userId ?? victim.userId,
});
if (k.multi) {
mEvents.push({ kind: 'event', id: nid('ev_'), ts: ts + 10, game: 'lol', matchId: id, type: 'multikill', data: { player: ref(killer), count: k.multi, ally: killer.ally }, time: label(ts), userId: killer.userId });
}
}
// 스탯 마무리
const csBase = { 'p-sh': 188, 'p-ms': 132, 'p-hw': 170, 'p-ez': 201, 'p-jw': 31, 'l-1': 176, 'l-2': 120, 'l-3': 160, 'l-4': 214, 'l-5': 28 };
const goldBase = { 'p-sh': 13900, 'p-ms': 12100, 'p-hw': 11800, 'p-ez': 13400, 'p-jw': 8700, 'l-1': 11200, 'l-2': 9600, 'l-3': 10100, 'l-4': 11900, 'l-5': 7300 };
const ITEMS = [
[3157, '존야의 모래시계'], [6655, '루덴의 동반자'], [3089, '라바돈의 죽음모자'], [3071, '칠흑의 양날 도끼'], [6631, '선체파괴자'],
[3190, '강철의 솔라리 펜던트'], [3047, '판금 장화'], [3111, '헤르메스의 발걸음'], [3020, '마법사의 신발'], [3508, '정수 약탈자'],
];
for (const p of players) {
p.cs = csBase[p.puuid];
p.gold = goldBase[p.puuid];
p.level = irange(14, 18);
p.items = Array.from({ length: irange(4, 6) }, () => pick(ITEMS)).map(([iid, name]) => ({ id: iid, name, icon: null }));
}
// 발화
const scriptedUtt = [
{ m: 20, s: 41, user: MS, text: '드래곤 30초 남았어 바텀 웨이브 밀고 와' },
{ m: 21, s: 14, user: SH, text: '지금 이니시 걸어 내가 매혹 맞췄어' },
{ m: 21, s: 24, user: JW, text: '한타 이겼다 용 먹자 용' },
{ m: 21, s: 50, user: HW, text: '', noise: true },
];
for (const u of scriptedUtt) {
const ts = at(u.m, u.s);
mUtts.push(addUtt({ user: u.user, ts, text: u.text, noise: !!u.noise, game: { type: 'lol', matchId: id }, time: label(ts) }));
}
for (let i = 0; i < 64; i++) {
let s = irange(30, DUR / 1000 - 20);
if (s > 20 * 60 + 30 && s < 22 * 60 + 10) s += 120;
const ts = start + s * 1000 + irange(0, 900);
mUtts.push(addUtt({ user: pick(SPEAKERS), ts, text: pick(LOL_LINES), noise: rnd() < 0.07, game: { type: 'lol', matchId: id }, time: label(ts) }));
}
// 채팅 (OCR / LCU)
const chats = [{ ts: at(21, 31), user: MS, text: '용 치자 바론 말고', source: 'ocr', ch: CH.LeeSin }];
for (let i = 0; i < 7; i++) chats.push({ ts: start + irange(60, DUR / 1000 - 30) * 1000, user: pick(SPEAKERS), text: pick(CHAT_LOL), source: pick(['ocr', 'lcu']) });
for (const c of chats) {
const p = players.find((pp) => pp.userId === c.user.id);
mEvents.push({ kind: 'event', id: nid('ev_'), ts: c.ts, game: 'lol', matchId: id, type: 'chat', data: { sender: { name: c.user.name, puuid: p?.puuid, userId: c.user.id, character: p?.character }, channel: 'team', text: c.text, source: c.source }, time: label(c.ts), userId: c.user.id });
}
mEvents.push({ kind: 'event', id: nid('ev_'), ts: endedAt, game: 'lol', matchId: id, type: 'match_end', data: { win: true, score: { ally: 27, enemy: 18 } }, time: label(endedAt) });
events.push(...mEvents);
const ak = players.filter((p) => p.ally).reduce((n, p) => n + p.kills, 0);
const ek = players.filter((p) => !p.ally).reduce((n, p) => n + p.kills, 0);
const summary = {
id, game: 'lol', startedAt: start, endedAt, map: { id: '11', name: '소환사의 협곡', image: A('lol/map11.png') }, mode: '개인/2인 랭크',
win: true, score: { ally: ak, enemy: ek }, status: 'complete', participants: [SH.id, MS.id, JW.id, HW.id],
};
matches.push({ ...summary, players, goldDiff, events: mEvents, utterances: mUtts, mapTransform: { lol: LOL_T } });
}
// ── 일정 ─────────────────────────────────────────────
export const NOW = Date.now();
const MIN = 60000;
const lolStart = NOW - 140 * MIN;
const bindStart = NOW - 99 * MIN;
const ascentStart = NOW - 50 * MIN;
// 8일 전 세션: 음성 삭제됨
for (let i = 0; i < 6; i++) {
const ts = NOW - 8 * 24 * 60 * MIN + i * 47000;
addUtt({ user: pick(SPEAKERS), ts, text: pick(REAL_LINES), time: realLabel(ts), audio: false });
}
// 롤 전
for (let i = 0; i < 5; i++) {
const ts = lolStart - (6 - i) * 52000 - irange(0, 9000);
addUtt({ user: pick(SPEAKERS), ts, text: i === 4 ? '롤 한 판 하고 발로 가자' : pick(REAL_LINES), time: realLabel(ts) });
}
genLol({ id: 'lol-KR_7712093344', start: lolStart });
// 롤 → 바인드 사이
for (let i = 0; i < 4; i++) {
const ts = lolStart + 33 * MIN + i * 60000 + irange(0, 20000);
addUtt({ user: pick(SPEAKERS), ts, text: pick(REAL_LINES), time: realLabel(ts) });
}
genValorant({ id: 'val-5d1c0a7e-bind', mapName: '바인드', mapId: '2c9d57ec-4431-9c5e-2939-8f9ef6dd5cba', image: null, T: { xMultiplier: 5.9e-5, yMultiplier: -5.9e-5, xScalarToAdd: 0.576941, yScalarToAdd: 0.967566 }, start: bindStart, results: 'LWLLWLWWLLWLWLLWWLLWWLL', linesPerRound: [1, 2] });
// 바인드 → 어센트
const preAscent = [
[SH, '아 바인드 아쉽다 한 판 더 하자'],
[JW, '이번엔 내가 세이지 할게'],
[MS, '큐 돌리자 이번 판은 어센트 나왔으면 좋겠다'],
];
preAscent.forEach(([u, text], i) => {
const ts = ascentStart - (4 - i) * 50000;
addUtt({ user: u, ts, text, time: realLabel(ts) });
});
genValorant({
id: 'val-9f2e7b10-ascent', mapName: '어센트', mapId: '7eaecc1b-4337-bbf6-6ab9-04b8f06b3319', image: A('val/map-ascent.png'), T: ASCENT_T, start: ascentStart,
results: 'WWLWLWWLLWWLWLWLWLWLWW',
scripted: {
7: [
{ at: 31, user: SH, text: 'A 메인 둘 봤어 하나 체력 낮아' },
{ at: 38, user: JW, text: '내가 스모크 깔게 들어가 들어가' },
{ at: 41, user: MS, text: '나이스 원탭!' },
{ at: 44, user: MS, noise: true },
{ at: 51, user: MS, chat: '스파이크 설치함 B로 돌지마' },
{ at: 62, user: SH, text: '레이즈 하나 남았어 메인 쪽에서 와 시간 끌어' },
{ at: 69, user: MS, text: '아 미안 셰리프 맞았다' },
],
},
});
// 경기 후 잡담 (최근 것은 STT 처리 중)
const post = [
[SH, '13 대 9 깔끔하다 오늘 폼 좋네', 'precise'],
[HW, '오멘 궁 타이밍 좋았지?', 'realtime'],
[MS, '나 마지막 라운드 셰리프 원탭 봤어?', 'realtime'],
[JW, '잠깐 쉬었다가 롤 한 판 더 하자', 'pending'],
[SH, '나 물 좀 마시고 올게', 'pending'],
];
const lastMatch = matches[matches.length - 1];
post.forEach(([u, text, status], i) => {
const ts = lastMatch.endedAt + 40000 + i * 70000;
addUtt({ user: u, ts, text, status, time: realLabel(ts) });
});
// ── 내보내기 ─────────────────────────────────────────
export const db = {
users: USERS,
utterances,
events,
matches,
sortAll() {
utterances.sort((a, b) => a.ts - b.ts);
events.sort((a, b) => a.ts - b.ts);
for (const m of matches) {
m.utterances.sort((a, b) => a.ts - b.ts);
m.events.sort((a, b) => a.ts - b.ts);
}
},
nextId: (p) => nid(p),
makeWords,
addLiveUtterance(user, text) {
const ts = Date.now();
return addUtt({ user, ts, text, status: 'pending', time: realLabel(ts) });
},
REAL_LINES,
SPEAKERS,
};
db.sortAll();

18
site/web/mock/run.mjs Normal file
View File

@@ -0,0 +1,18 @@
// npm run dev → 목 서버(18787) + vite dev(5173)
// npm run preview → 목 서버(18787) + vite preview(4173, dist/)
import { createServer, preview } from 'vite';
import { startMock } from './server.mjs';
const mode = process.argv[2] ?? 'dev';
const mock = startMock();
const server = mode === 'preview' ? await preview() : await createServer();
if (mode !== 'preview') await server.listen();
server.printUrls();
const stop = async () => {
mock.close();
await server.close?.();
process.exit(0);
};
process.on('SIGINT', stop);
process.on('SIGTERM', stop);

299
site/web/mock/server.mjs Normal file
View 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();