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>
@@ -13,7 +13,7 @@
|
||||
|---|---|---|
|
||||
| M0 기술 검증 | DAVE 음성 연결, faster-whisper STT·음량·잡음·사전, 게임 로컬 API 처리, 게임 PC 진단 기능 | ✅ 완료 ([결과](docs/dev/M0-verification.md)) |
|
||||
| M1 녹음 + STT 기본 | 따라가기·명령 참여, TTS 안내, 유저별 녹음, 대기열 STT, /녹음제외·참여 | ✅ 완료 ([실음성 테스트](docs/dev/test-results.md)) |
|
||||
| M2 사이트 서버 · 사이트 v1 | 디스코드 로그인, 연결 확인·잠금, 타임라인·따라 읽기·필터·검색·실시간 | ⏳ |
|
||||
| M2 사이트 서버 · 사이트 v1 | 디스코드 로그인, 연결 확인·잠금, 타임라인·따라 읽기·필터·검색·실시간 | ✅ 완료 · https://gvr.tkrmagid.kr 배포 |
|
||||
| M3 발로란트 연동 | 경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과 시간, 경기 상세 | ⏳ |
|
||||
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ⏳ |
|
||||
| M5 exe · 설정 · 모델 | 포터블 exe, 첫 실행 마법사, GPU 감지·모델 다운로드, 암호화 저장, 7일 삭제 | ⏳ |
|
||||
@@ -42,6 +42,11 @@ assets/ 앱·사이트 아이콘·배너
|
||||
cd worker && uv venv --python 3.11 .venv && uv pip install --python .venv/bin/python -r requirements-dev.txt
|
||||
.venv/bin/python -m pytest -q
|
||||
|
||||
# 사이트 (가짜 데이터로 화면 개발: http://127.0.0.1:5173)
|
||||
cd site/web && npm install && npm run dev
|
||||
cd site/server && npm install && npm test
|
||||
deploy/site/deploy.sh # .5 배포 (deploy/README.md)
|
||||
|
||||
# 앱 코어 (헤드리스)
|
||||
cd app && npm install && npm test
|
||||
npm run core -- --diagnose # 게임 PC 진단 (GPU·STT 속도·Riot API·OCR)
|
||||
|
||||
24
app/scripts/site-e2e.mts
Normal file
@@ -0,0 +1,24 @@
|
||||
// M2 실서버 확인: 등록 코드로 이 코어를 https://gvr.tkrmagid.kr 에 등록하고 연결·중계가 되는지 본다.
|
||||
// node --import tsx scripts/site-e2e.mts <등록코드>
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { registerDevice } from '../src/core/relay/client.ts';
|
||||
|
||||
const code = process.argv[2];
|
||||
const root = path.resolve(import.meta.dirname, '..', '..');
|
||||
const work = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-site-e2e-'));
|
||||
const reg = await registerDevice('https://gvr.tkrmagid.kr', code, 'DEV-TEST');
|
||||
console.log('등록 완료 deviceId', reg.deviceId);
|
||||
fs.writeFileSync(path.join(work, 'settings.json'), JSON.stringify({ site: { deviceId: reg.deviceId, deviceName: 'DEV-TEST' }, games: { valorant: false, lol: false } }));
|
||||
const { startCore } = await import('../src/core/index.ts');
|
||||
const core = await startCore({ dataDir: work, resourcesDir: path.join(root, 'app', 'resources'), worker: { cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') }, version: 'site-e2e' });
|
||||
core.settings.setSecret('deviceKey', reg.deviceKey);
|
||||
core.relay.restart();
|
||||
const t = Date.now();
|
||||
while (core.relay.status.state !== 'online' && Date.now() - t < 15000) await new Promise((r) => setTimeout(r, 200));
|
||||
console.log('relay', core.relay.status.state, core.relay.status.error ?? '');
|
||||
const online = core.relay.status.state === 'online';
|
||||
await new Promise((r) => setTimeout(r, 7000)); // ping 한 번 이상
|
||||
await core.stop();
|
||||
process.exit(online ? 0 : 1);
|
||||
@@ -98,6 +98,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
deviceKey: settings.getSecret('deviceKey') ?? null,
|
||||
name: S().site.deviceName,
|
||||
version: opts.version,
|
||||
guildId: S().discord.guildId,
|
||||
}));
|
||||
const retention = new Retention(store, () => S().storage.retentionDays, () => paths().audio);
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ export class RelayClient {
|
||||
constructor(
|
||||
private api: FastifyInstance,
|
||||
private bus: Bus,
|
||||
private cfg: () => { serverUrl: string; deviceId: string | null; deviceKey: string | null; name: string; version: string },
|
||||
private cfg: () => { serverUrl: string; deviceId: string | null; deviceKey: string | null; name: string; version: string; guildId: string | null },
|
||||
) {
|
||||
bus.on('live', (ev: LiveEvent) => this.send({ t: 'event', event: ev }));
|
||||
}
|
||||
@@ -69,7 +69,7 @@ export class RelayClient {
|
||||
this.lastPong = Date.now();
|
||||
this.status = { state: 'online', error: null, since: Date.now(), serverUrl: c.serverUrl };
|
||||
log.info(`사이트 서버 연결됨: ${c.serverUrl}`);
|
||||
this.send({ t: 'hello', name: c.name, version: c.version });
|
||||
this.send({ t: 'hello', name: c.name, version: c.version, guildId: c.guildId });
|
||||
this.pingTimer = setInterval(() => {
|
||||
if (Date.now() - this.lastPong > 20000) {
|
||||
log.warn('사이트 서버 응답 없음, 다시 연결');
|
||||
|
||||
@@ -98,9 +98,14 @@ export class Timeline {
|
||||
const cur = q.cursor ? parseCursor(q.cursor) : null;
|
||||
const types = q.types && q.types.length ? new Set(q.types) : null;
|
||||
const wantUtt = !types || types.has('utterance');
|
||||
const eventTypes = types
|
||||
? [...types].flatMap((t) => (t === 'round' ? ['round_end'] : t === 'match' ? ['match_start', 'match_end'] : t === 'utterance' ? [] : [t]))
|
||||
: null;
|
||||
// 사이트 필터 묶음: 킬 = 킬·멀티킬·에이스, 라운드 = 라운드 종료·경기 시작/종료·스파이크
|
||||
const GROUPS: Record<string, string[]> = {
|
||||
kill: ['kill', 'multikill', 'ace'],
|
||||
round: ['round_end', 'match_start', 'match_end', 'spike'],
|
||||
match: ['match_start', 'match_end'],
|
||||
utterance: [],
|
||||
};
|
||||
const eventTypes = types ? [...new Set([...types].flatMap((t) => GROUPS[t] ?? [t]))] : null;
|
||||
const wantEvents = (!types || (eventTypes && eventTypes.length > 0)) && q.game !== 'none';
|
||||
const cmp = desc ? '<' : '>';
|
||||
const ord = desc ? 'DESC' : 'ASC';
|
||||
@@ -172,15 +177,14 @@ export class Timeline {
|
||||
args.push(q.game);
|
||||
}
|
||||
if (q.users?.length) {
|
||||
const puuids = this.store
|
||||
// 선택하지 않은 (디스코드에 연결된) 유저가 주인공인 이벤트만 뺀다. 라운드·오브젝트·상대 킬처럼 유저가 없는 이벤트는 남긴다.
|
||||
const others = this.store
|
||||
.listAccounts()
|
||||
.filter((a) => q.users!.includes(a.user_id))
|
||||
.filter((a) => a.puuid && !q.users!.includes(a.user_id))
|
||||
.map((a) => a.puuid);
|
||||
if (!puuids.length) where.push('0');
|
||||
else {
|
||||
const ph = puuids.map(() => '?').join(',');
|
||||
where.push(`(e.actor_puuid IN (${ph}) OR e.target_puuid IN (${ph}))`);
|
||||
args.push(...puuids, ...puuids);
|
||||
if (others.length) {
|
||||
where.push(`(e.actor_puuid IS NULL OR e.actor_puuid NOT IN (${others.map(() => '?').join(',')}))`);
|
||||
args.push(...others);
|
||||
}
|
||||
}
|
||||
if (q.from) {
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
# Deploy (site server)
|
||||
# Deploy (사이트 서버)
|
||||
|
||||
- Host: .5 Docker (`root@192.168.10.5:/root/other/game-voice-recorder`), container `gvr-web`, port **2972**.
|
||||
- Domain: `gvr.tkrmagid.kr` → NPMplus on 192.168.10.3 (proxy host id 13, websocket upgrade on) → `192.168.10.5:2972`.
|
||||
- DNS: A record `gvr` → 211.213.11.141 must be added at hosting.co.kr (user). Then run `./cert.sh` (LE cert + force SSL).
|
||||
- `placeholder/` is a static "준비 중" page until the real site server replaces it (same port, same compose project name).
|
||||
Update: `scp -r placeholder/* root@192.168.10.5:/root/other/game-voice-recorder/ && ssh root@192.168.10.5 'cd /root/other/game-voice-recorder && docker compose up -d'`
|
||||
- Secrets (Discord bot token / OAuth client secret) live in `~/.config/ejclaw/secrets.json` under `discord.com/bot/game-voice-recorder`; inject via `.env` on the host, never commit.
|
||||
- 위치: .5 Docker `root@192.168.10.5:/root/other/game-voice-recorder` (compose 프로젝트 `game-voice-recorder`, 컨테이너 `gvr-web`), 포트 **2972 → 8080**
|
||||
- 도메인: `gvr.tkrmagid.kr` → NPMplus(192.168.10.3, proxy host 13, WebSocket 허용) → `192.168.10.5:2972`. Let's Encrypt 인증서는 NPMplus 가 자동 갱신 (`cert.sh`)
|
||||
- 배포: 저장소 루트에서 `deploy/site/deploy.sh` (소스를 tar 로 보내 `.5` 에서 이미지 빌드 → 재시작 → healthz 확인)
|
||||
- 비밀값: `.5` 의 `.env` 에만 있다. 처음 한 번 `deploy/site/make-env.sh` (secrets.json 에서 읽어 원격에 바로 씀)
|
||||
- `DISCORD_CLIENT_ID/SECRET` (OAuth 로그인), `DISCORD_BOT_TOKEN` (서버 멤버 확인), `SESSION_SECRET`
|
||||
- `ALLOWED_GUILD_IDS=457514742940958731` (M&L), `OWNER_DISCORD_IDS=293719842274541579` (등록 코드를 만들 수 있는 관리자)
|
||||
- 관리 명령 (컨테이너 안):
|
||||
- `docker exec gvr-web node dist/cli.js code [분]` — 게임 PC 1회용 등록 코드 (사이트에서 관리자도 만들 수 있음)
|
||||
- `docker exec gvr-web node dist/cli.js device` — 등록된 게임 PC
|
||||
- `docker exec gvr-web node dist/cli.js unregister && docker restart gvr-web` — 등록 해제
|
||||
- 서버 데이터(`data/`): `server.json`(기기 키 해시·세션), `codes.json`(등록 코드), `asset-cache/`(게임 이미지). 기록 내용은 저장하지 않는다.
|
||||
- `placeholder/` 는 M2 이전 "준비 중" 페이지 (기록용으로 남김)
|
||||
|
||||
24
deploy/site/Dockerfile
Normal file
@@ -0,0 +1,24 @@
|
||||
# 겜녹이 사이트 서버 (디스코드 로그인 · 게임 PC 중계 · 사이트 화면 · 게임 이미지 캐시)
|
||||
# 빌드 컨텍스트 = 저장소 루트 구조 (packages/shared, site/web, site/server)
|
||||
FROM node:22-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY packages/shared packages/shared
|
||||
COPY site/web/package.json site/web/package-lock.json site/web/
|
||||
RUN cd site/web && npm ci --no-audit --no-fund
|
||||
COPY site/server/package.json site/server/package-lock.json site/server/
|
||||
RUN cd site/server && npm ci --no-audit --no-fund
|
||||
COPY site/web site/web
|
||||
COPY site/server site/server
|
||||
RUN cd site/web && npm run build && cd ../server && npm run build
|
||||
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production WEB_DIR=/app/web DATA_DIR=/data PORT=8080
|
||||
COPY site/server/package.json site/server/package-lock.json ./
|
||||
RUN npm ci --omit=dev --no-audit --no-fund && npm cache clean --force
|
||||
COPY --from=build /src/site/server/dist ./dist
|
||||
COPY --from=build /src/site/web/dist ./web
|
||||
VOLUME /data
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=30s --timeout=5s CMD wget -qO- http://127.0.0.1:8080/healthz || exit 1
|
||||
CMD ["node", "dist/main.js"]
|
||||
18
deploy/site/deploy.sh
Executable file
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# 사이트 서버를 .5 에 배포한다. 저장소 루트에서: deploy/site/deploy.sh
|
||||
# 비밀값(.env)은 .5 에만 있다. 처음이면 deploy/site/make-env.sh 로 만든다.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
HOST=root@192.168.10.5
|
||||
DIR=/root/other/game-voice-recorder
|
||||
ssh -o BatchMode=yes $HOST "mkdir -p $DIR/src $DIR/data"
|
||||
# .5 에는 rsync 가 없어서 tar 로 보낸다 (src 는 매번 새로)
|
||||
tar czf - --exclude node_modules --exclude dist --exclude screenshots --exclude 'site/server/data' \
|
||||
packages site deploy/site | ssh $HOST "rm -rf $DIR/src && mkdir -p $DIR/src && tar xzf - -C $DIR/src"
|
||||
scp -q deploy/site/docker-compose.yml "$HOST:$DIR/docker-compose.yml"
|
||||
ssh $HOST "cd $DIR && test -f .env || { echo '.env 없음 (make-env.sh 먼저)'; exit 1; } && docker compose up -d --build 2>&1 | tail -5 && sleep 3 && docker compose ps"
|
||||
for i in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if curl -fsS https://gvr.tkrmagid.kr/healthz >/dev/null 2>&1; then echo "https://gvr.tkrmagid.kr 정상"; exit 0; fi
|
||||
sleep 3
|
||||
done
|
||||
echo "healthz 응답 없음"; exit 1
|
||||
15
deploy/site/docker-compose.yml
Normal file
@@ -0,0 +1,15 @@
|
||||
# .5:/root/other/game-voice-recorder (NPMplus 가 gvr.tkrmagid.kr → 192.168.10.5:2972 로 넘긴다, WebSocket 허용)
|
||||
name: game-voice-recorder
|
||||
services:
|
||||
web:
|
||||
build:
|
||||
context: ./src
|
||||
dockerfile: deploy/site/Dockerfile
|
||||
image: gvr-site:latest
|
||||
container_name: gvr-web
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
ports:
|
||||
- "2972:8080"
|
||||
volumes:
|
||||
- ./data:/data
|
||||
17
deploy/site/make-env.sh
Executable file
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
# .5 에 사이트 서버 .env 를 만든다 (secrets.json 에서 읽어 바로 원격에 씀, 로컬에 남기지 않음)
|
||||
set -euo pipefail
|
||||
HOST=root@192.168.10.5
|
||||
DIR=/root/other/game-voice-recorder
|
||||
python3 - <<'PY' | ssh -o BatchMode=yes $HOST "mkdir -p $DIR && umask 077 && cat > $DIR/.env"
|
||||
import json, secrets
|
||||
c = json.load(open('/home/claude/.config/ejclaw/secrets.json'))['credentials']['discord.com/bot/game-voice-recorder']
|
||||
print(f"PUBLIC_URL=https://gvr.tkrmagid.kr")
|
||||
print(f"DISCORD_CLIENT_ID={c['client_id']}")
|
||||
print(f"DISCORD_CLIENT_SECRET={c['client_secret']}")
|
||||
print(f"DISCORD_BOT_TOKEN={c['token']}")
|
||||
print(f"SESSION_SECRET={secrets.token_urlsafe(48)}")
|
||||
print("ALLOWED_GUILD_IDS=457514742940958731")
|
||||
print("OWNER_DISCORD_IDS=293719842274541579")
|
||||
PY
|
||||
echo ".env 작성 완료"
|
||||
BIN
docs/dev/live-login.png
Normal file
|
After Width: | Height: | Size: 374 KiB |
@@ -26,3 +26,10 @@ VOICE E2E PASS
|
||||
|
||||
- `cd app && npm test` — 9개 통과 (Ogg 쓰기, 사전·diff, 경기 상세·시간 표시, 타임라인 조회, 7일 삭제, STT E2E, 가짜 Riot 서버 통합)
|
||||
- `cd worker && .venv/bin/python -m pytest -q` — 39개 통과
|
||||
|
||||
## M2 사이트 서버 · 사이트 v1 (2026-10-15)
|
||||
|
||||
- `cd site/server && npm test` — 통합 테스트 통과: OAuth(state 쿠키) → 서버 멤버 확인 → 세션 → 기기 등록(1회용 코드, 잘못된 키 거절) → 실제 앱 `RelayClient` 연결 → JSON·음성(바이너리) 중계 → 다른 Origin 쓰기 거절 → 실시간 이벤트 → 연결 끊김 시 잠금(503) → 멤버 아니면 로그인 거절
|
||||
- `cd site/web && npm run typecheck && npm run build` — 오류 0. 가짜 서버로 18개 동작(무한 스크롤, 필터 URL, 검색, 재생·단어 강조, 이어듣기, 단축키, 교정, 잠금/해제, 경기 상세) 헤드리스 확인
|
||||
- 실서버: https://gvr.tkrmagid.kr 배포. 등록 코드로 개발 서버의 코어를 등록 → `wss://gvr.tkrmagid.kr/device/ws` 로 연결·ping 확인 (`app/scripts/site-e2e.mts`) 후 테스트 기기는 등록 해제
|
||||
- 화면: `site/web/screenshots/` (가짜 데이터), `docs/dev/live-login.png` (실서버 로그인 화면)
|
||||
|
||||
@@ -218,7 +218,7 @@ export type RelayToDevice =
|
||||
| { t: 'welcome'; deviceId: string };
|
||||
|
||||
export type RelayFromDevice =
|
||||
| { t: 'hello'; name: string; version: string }
|
||||
| { t: 'hello'; name: string; version: string; guildId?: string | null }
|
||||
| { t: 'ping'; ts: number }
|
||||
| { t: 'res'; id: string; status: number; headers: Record<string, string>; body: string | null }
|
||||
| { t: 'res_head'; id: string; status: number; headers: Record<string, string> }
|
||||
|
||||
3
site/server/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
dist/
|
||||
data/
|
||||
2019
site/server/package-lock.json
generated
Normal file
27
site/server/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "gvr-site-server",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "겜녹이 사이트 서버: 디스코드 로그인, 게임 PC 연결 확인·중계, 게임 이미지 캐시",
|
||||
"scripts": {
|
||||
"build": "esbuild src/main.ts src/cli.ts --bundle --platform=node --format=esm --target=node22 --outdir=dist --packages=external --alias:@gvr/shared=../../packages/shared/src/index.ts",
|
||||
"start": "node dist/main.js",
|
||||
"dev": "node --import tsx src/main.ts",
|
||||
"typecheck": "tsc --noEmit -p .",
|
||||
"test": "node --import tsx --test test/*.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/static": "^8.2.0",
|
||||
"fastify": "^5.6.1",
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.18.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"esbuild": "^0.25.10",
|
||||
"tsx": "^4.20.6",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
225
site/server/src/app.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
import cookie from '@fastify/cookie';
|
||||
import fastifyStatic from '@fastify/static';
|
||||
import Fastify, { type FastifyReply, type FastifyRequest } from 'fastify';
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Config } from './config.js';
|
||||
import { avatarUrl, DiscordApi } from './discord.js';
|
||||
import { RelayHub } from './relay.js';
|
||||
import { ServerStore, type Session } from './store.js';
|
||||
|
||||
const SID = 'gvr_sid';
|
||||
const RECHECK_MS = 10 * 60000;
|
||||
|
||||
export async function buildServer(cfg: Config) {
|
||||
const app = Fastify({ logger: { level: process.env.LOG_LEVEL || 'info' }, trustProxy: true, bodyLimit: 1024 * 1024 });
|
||||
const store = new ServerStore(cfg.dataDir);
|
||||
const hub = new RelayHub(store);
|
||||
const discord = new DiscordApi(cfg);
|
||||
await app.register(cookie, { secret: cfg.sessionSecret });
|
||||
const secure = cfg.publicUrl.startsWith('https://');
|
||||
|
||||
const allowedGuilds = (): string[] => {
|
||||
const g = new Set(cfg.allowedGuilds);
|
||||
const dg = store.device()?.guildId;
|
||||
if (dg) g.add(dg);
|
||||
return [...g];
|
||||
};
|
||||
|
||||
/** 세션 확인. 10분마다 서버 멤버인지 다시 확인 (서버에서 나가면 바로 막힘) */
|
||||
async function getSession(req: FastifyRequest): Promise<Session | null> {
|
||||
const raw = req.cookies[SID];
|
||||
if (!raw) return null;
|
||||
const un = req.unsignCookie(raw);
|
||||
if (!un.valid || !un.value) return null;
|
||||
const s = store.session(un.value);
|
||||
if (!s) return null;
|
||||
if (Date.now() - s.checkedAt > RECHECK_MS && !cfg.owners.includes(s.user.id)) {
|
||||
try {
|
||||
let ok = false;
|
||||
for (const g of allowedGuilds()) if (await discord.memberOf(g, s.user.id)) ok = true;
|
||||
if (!ok) {
|
||||
store.deleteSession(s.id);
|
||||
return null;
|
||||
}
|
||||
store.touchSession(s.id);
|
||||
} catch {
|
||||
/* 디스코드 API 장애면 기존 세션 유지 */
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
const requireSession = async (req: FastifyRequest, reply: FastifyReply): Promise<Session | null> => {
|
||||
const s = await getSession(req);
|
||||
if (!s) {
|
||||
reply.code(401).send({ error: 'unauthorized' });
|
||||
return null;
|
||||
}
|
||||
return s;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ 로그인
|
||||
app.get('/auth/discord', async (req, reply) => {
|
||||
const state = crypto.randomBytes(16).toString('base64url');
|
||||
reply.setCookie('gvr_state', state, { path: '/auth', httpOnly: true, secure, sameSite: 'lax', maxAge: 600, signed: true });
|
||||
return reply.redirect(discord.authorizeUrl(state));
|
||||
});
|
||||
|
||||
app.get<{ Querystring: { code?: string; state?: string; error?: string } }>('/auth/discord/callback', async (req, reply) => {
|
||||
const st = req.cookies.gvr_state ? req.unsignCookie(req.cookies.gvr_state) : null;
|
||||
reply.clearCookie('gvr_state', { path: '/auth' });
|
||||
if (req.query.error) return reply.redirect('/?login=cancelled');
|
||||
if (!req.query.code || !st?.valid || st.value !== req.query.state) return reply.redirect('/?login=invalid');
|
||||
try {
|
||||
const tok = await discord.exchange(req.query.code);
|
||||
const u = await discord.me(tok.access_token);
|
||||
let member: { nick: string | null } | null = null;
|
||||
for (const g of allowedGuilds()) {
|
||||
member = await discord.memberOf(g, u.id);
|
||||
if (member) break;
|
||||
}
|
||||
if (!member && !cfg.owners.includes(u.id)) {
|
||||
req.log.info({ user: u.id }, '서버 멤버가 아니라 로그인 거절');
|
||||
return reply.redirect('/?login=not_member');
|
||||
}
|
||||
const s = store.createSession({ id: u.id, name: member?.nick || u.global_name || u.username, avatar: avatarUrl(u) });
|
||||
reply.setCookie(SID, s.id, { path: '/', httpOnly: true, secure, sameSite: 'lax', maxAge: 30 * 24 * 3600, signed: true });
|
||||
return reply.redirect('/');
|
||||
} catch (e) {
|
||||
req.log.error(e, 'OAuth 실패');
|
||||
return reply.redirect('/?login=error');
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/auth/logout', async (req, reply) => {
|
||||
const raw = req.cookies[SID];
|
||||
const un = raw ? req.unsignCookie(raw) : null;
|
||||
if (un?.valid && un.value) store.deleteSession(un.value);
|
||||
reply.clearCookie(SID, { path: '/' });
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
app.get('/auth/me', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
return { user: s.user, isOwner: cfg.owners.includes(s.user.id) };
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 상태 · 관리
|
||||
app.get('/api/status', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
return { device: hub.status(), server: { version: cfg.version } };
|
||||
});
|
||||
|
||||
app.post('/admin/registration-code', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
if (!cfg.owners.includes(s.user.id)) return reply.code(403).send({ error: 'forbidden' });
|
||||
return store.createCode(s.user.id);
|
||||
});
|
||||
|
||||
app.post<{ Body: { code?: string; name?: string } }>('/device/register', async (req, reply) => {
|
||||
const r = store.redeem(String(req.body?.code ?? ''), String(req.body?.name ?? 'GAME-PC'));
|
||||
if (!r) return reply.code(400).send({ error: 'invalid_code', message: '등록 코드가 올바르지 않거나 만료되었습니다' });
|
||||
req.log.info('게임 PC 등록');
|
||||
return r;
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 기록 API 중계
|
||||
const relay = async (req: FastifyRequest, reply: FastifyReply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
// 쓰기 요청은 같은 사이트에서 온 것만 (CSRF)
|
||||
if (req.method !== 'GET') {
|
||||
const origin = String(req.headers.origin || '');
|
||||
if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' });
|
||||
}
|
||||
const headers: Record<string, string> = {};
|
||||
for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = String(req.headers[k]);
|
||||
const body = req.body === undefined || req.body === null ? null : typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
|
||||
try {
|
||||
const r = await hub.request(req.method, req.url, headers, s.user, body);
|
||||
for (const [k, v] of Object.entries(r.headers)) if (k !== 'content-length') reply.header(k, v);
|
||||
return reply.code(r.status).send(r.body);
|
||||
} catch (e: any) {
|
||||
if (e.message === 'device_offline') return reply.code(503).send({ error: 'device_offline' });
|
||||
return reply.code(504).send({ error: 'timeout' });
|
||||
}
|
||||
};
|
||||
app.route({ method: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'], url: '/api/*', handler: relay });
|
||||
|
||||
// ------------------------------------------------------------------ 게임 이미지 캐시 (보고서 7-7)
|
||||
const cacheDir = path.join(cfg.dataDir, 'asset-cache');
|
||||
app.get<{ Params: { src: string; '*': string } }>('/game-assets/:src/*', async (req, reply) => {
|
||||
const base = cfg.assetUpstream[req.params.src];
|
||||
const rel = req.params['*'];
|
||||
if (!base || !/^[\w\-./]+\.(png|jpg|jpeg|webp)$/i.test(rel) || rel.includes('..')) return reply.code(404).send();
|
||||
const file = path.join(cacheDir, req.params.src, rel);
|
||||
const type = rel.endsWith('.png') ? 'image/png' : rel.endsWith('.webp') ? 'image/webp' : 'image/jpeg';
|
||||
reply.header('cache-control', 'public, max-age=604800').type(type);
|
||||
if (fs.existsSync(file)) return reply.send(fs.createReadStream(file));
|
||||
const r = await fetch(base + rel).catch(() => null);
|
||||
if (!r || !r.ok) return reply.code(r?.status === 404 ? 404 : 502).send();
|
||||
const buf = Buffer.from(await r.arrayBuffer());
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, buf);
|
||||
return reply.send(buf);
|
||||
});
|
||||
|
||||
app.get('/healthz', async () => 'ok\n');
|
||||
|
||||
// ------------------------------------------------------------------ 사이트 화면
|
||||
if (fs.existsSync(cfg.webDir)) {
|
||||
await app.register(fastifyStatic, { root: cfg.webDir, wildcard: false, index: ['index.html'] });
|
||||
app.setNotFoundHandler((req, reply) => {
|
||||
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/game-assets/'))
|
||||
return reply.type('text/html').send(fs.readFileSync(path.join(cfg.webDir, 'index.html')));
|
||||
return reply.code(404).send({ error: 'not_found' });
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ WebSocket
|
||||
app.server.on('upgrade', async (req, socket, head) => {
|
||||
const url = new URL(req.url || '/', 'http://x');
|
||||
if (url.pathname === '/device/ws') {
|
||||
const d = hub.authenticateDevice(req);
|
||||
if (!d) {
|
||||
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
||||
return socket.destroy();
|
||||
}
|
||||
hub.deviceWss.handleUpgrade(req, socket, head, (ws) => hub.attachDevice(ws, d.id));
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/ws') {
|
||||
const fakeReq: any = { cookies: parseCookies(String(req.headers.cookie || '')), unsignCookie: (v: string) => app.unsignCookie(v), log: app.log };
|
||||
const s = await getSession(fakeReq);
|
||||
if (!s) {
|
||||
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
||||
return socket.destroy();
|
||||
}
|
||||
hub.browserWss.handleUpgrade(req, socket, head, (ws) => hub.attachBrowser(ws));
|
||||
return;
|
||||
}
|
||||
socket.destroy();
|
||||
});
|
||||
|
||||
app.addHook('onClose', async () => {
|
||||
hub.close();
|
||||
store.flush();
|
||||
});
|
||||
|
||||
return { app, store, hub };
|
||||
}
|
||||
|
||||
function parseCookies(h: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of h.split(';')) {
|
||||
const i = part.indexOf('=');
|
||||
if (i < 0) continue;
|
||||
out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
26
site/server/src/cli.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
// 관리 명령 (컨테이너 안에서): node dist/cli.js code → 게임 PC 1회용 등록 코드 (10분)
|
||||
import { loadConfig } from './config.js';
|
||||
import { ServerStore } from './store.js';
|
||||
|
||||
const cmd = process.argv[2];
|
||||
const dataDir = process.env.DATA_DIR || loadConfigSafe()?.dataDir || 'data';
|
||||
const store = new ServerStore(dataDir);
|
||||
if (cmd === 'code') {
|
||||
const c = store.createCode('cli', Number(process.argv[3] || 10) * 60000);
|
||||
console.log(`등록 코드: ${c.code} (만료 ${new Date(c.expiresAt).toLocaleString('ko-KR', { timeZone: 'Asia/Seoul' })})`);
|
||||
} else if (cmd === 'device') {
|
||||
console.log(JSON.stringify(store.device(), (k, v) => (k === 'keyHash' ? undefined : v), 2));
|
||||
} else if (cmd === 'unregister') {
|
||||
console.log(`등록 해제: ${store.removeDevices()}대 (서버를 다시 시작하면 연결도 끊긴다)`);
|
||||
} else {
|
||||
console.log('사용법: node dist/cli.js code [분] | device | unregister');
|
||||
}
|
||||
store.flush();
|
||||
|
||||
function loadConfigSafe() {
|
||||
try {
|
||||
return loadConfig();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
48
site/server/src/config.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import path from 'node:path';
|
||||
|
||||
export interface Config {
|
||||
port: number;
|
||||
host: string;
|
||||
publicUrl: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
botToken: string;
|
||||
/** 로그인 허용 디스코드 서버 (기본: M&L). 게임 PC 가 알려 준 서버도 함께 허용 */
|
||||
allowedGuilds: string[];
|
||||
owners: string[];
|
||||
sessionSecret: string;
|
||||
dataDir: string;
|
||||
webDir: string;
|
||||
version: string;
|
||||
/** 테스트용: 디스코드 API 주소 바꾸기 */
|
||||
discordApi: string;
|
||||
assetUpstream: Record<string, string>;
|
||||
}
|
||||
|
||||
export function loadConfig(env = process.env): Config {
|
||||
const need = (k: string) => {
|
||||
const v = env[k];
|
||||
if (!v) throw new Error(`환경변수 ${k} 가 필요합니다`);
|
||||
return v;
|
||||
};
|
||||
return {
|
||||
port: Number(env.PORT || 8080),
|
||||
host: env.HOST || '0.0.0.0',
|
||||
publicUrl: (env.PUBLIC_URL || 'https://gvr.tkrmagid.kr').replace(/\/$/, ''),
|
||||
clientId: need('DISCORD_CLIENT_ID'),
|
||||
clientSecret: need('DISCORD_CLIENT_SECRET'),
|
||||
botToken: need('DISCORD_BOT_TOKEN'),
|
||||
allowedGuilds: (env.ALLOWED_GUILD_IDS || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
owners: (env.OWNER_DISCORD_IDS || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
sessionSecret: need('SESSION_SECRET'),
|
||||
dataDir: env.DATA_DIR || path.resolve('data'),
|
||||
webDir: env.WEB_DIR || path.resolve('../web/dist'),
|
||||
version: env.GVR_VERSION || '1.0.0',
|
||||
discordApi: env.DISCORD_API || 'https://discord.com/api/v10',
|
||||
assetUpstream: {
|
||||
valmedia: 'https://media.valorant-api.com/',
|
||||
ddragon: 'https://ddragon.leagueoflegends.com/',
|
||||
cdragon: 'https://raw.communitydragon.org/',
|
||||
},
|
||||
};
|
||||
}
|
||||
59
site/server/src/discord.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import type { Config } from './config.js';
|
||||
|
||||
export interface DiscordUser {
|
||||
id: string;
|
||||
username: string;
|
||||
global_name: string | null;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
export class DiscordApi {
|
||||
constructor(private cfg: Config) {}
|
||||
|
||||
authorizeUrl(state: string): string {
|
||||
const p = new URLSearchParams({
|
||||
client_id: this.cfg.clientId,
|
||||
response_type: 'code',
|
||||
redirect_uri: `${this.cfg.publicUrl}/auth/discord/callback`,
|
||||
scope: 'identify guilds',
|
||||
state,
|
||||
prompt: 'none',
|
||||
});
|
||||
return `https://discord.com/oauth2/authorize?${p}`;
|
||||
}
|
||||
|
||||
async exchange(code: string): Promise<{ access_token: string }> {
|
||||
const r = await fetch(`${this.cfg.discordApi}/oauth2/token`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
client_id: this.cfg.clientId,
|
||||
client_secret: this.cfg.clientSecret,
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
redirect_uri: `${this.cfg.publicUrl}/auth/discord/callback`,
|
||||
}),
|
||||
});
|
||||
if (!r.ok) throw new Error(`token ${r.status} ${await r.text()}`);
|
||||
return (await r.json()) as { access_token: string };
|
||||
}
|
||||
|
||||
async me(accessToken: string): Promise<DiscordUser> {
|
||||
const r = await fetch(`${this.cfg.discordApi}/users/@me`, { headers: { authorization: `Bearer ${accessToken}` } });
|
||||
if (!r.ok) throw new Error(`users/@me ${r.status}`);
|
||||
return (await r.json()) as DiscordUser;
|
||||
}
|
||||
|
||||
/** 봇 토큰으로 서버 멤버인지 확인 (OAuth guilds 목록보다 확실하고, 나중에 다시 확인할 때 사용자 토큰이 필요 없다) */
|
||||
async memberOf(guildId: string, userId: string): Promise<{ nick: string | null; avatar: string | null } | null> {
|
||||
const r = await fetch(`${this.cfg.discordApi}/guilds/${guildId}/members/${userId}`, { headers: { authorization: `Bot ${this.cfg.botToken}` } });
|
||||
if (r.status === 404) return null;
|
||||
if (!r.ok) throw new Error(`member ${r.status}`);
|
||||
const m: any = await r.json();
|
||||
return { nick: m.nick ?? null, avatar: m.avatar ?? null };
|
||||
}
|
||||
}
|
||||
|
||||
export function avatarUrl(u: DiscordUser): string | null {
|
||||
return u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png?size=128` : null;
|
||||
}
|
||||
12
site/server/src/main.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { buildServer } from './app.js';
|
||||
import { loadConfig } from './config.js';
|
||||
|
||||
const cfg = loadConfig();
|
||||
const { app } = await buildServer(cfg);
|
||||
await app.listen({ host: cfg.host, port: cfg.port });
|
||||
const stop = async () => {
|
||||
await app.close();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', stop);
|
||||
process.on('SIGINT', stop);
|
||||
205
site/server/src/relay.ts
Normal file
@@ -0,0 +1,205 @@
|
||||
import crypto from 'node:crypto';
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import { WebSocket, WebSocketServer } from 'ws';
|
||||
import type { BrowserMessage, DeviceStatus, LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
|
||||
import type { ServerStore } from './store.js';
|
||||
|
||||
const OFFLINE_AFTER_MS = 15000;
|
||||
|
||||
interface Pending {
|
||||
resolve: (r: RelayResponse) => void;
|
||||
reject: (e: Error) => void;
|
||||
timer: NodeJS.Timeout;
|
||||
head?: { status: number; headers: Record<string, string> };
|
||||
chunks: Buffer[];
|
||||
}
|
||||
export interface RelayResponse {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body: Buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* 게임 PC 연결 하나와 브라우저 연결 여러 개를 잇는다.
|
||||
* - 게임 PC 가 먼저 연결 (기기 키 인증), 5초마다 ping. 15초 동안 소식이 없으면 오프라인 → 모든 브라우저에 잠금 상태 전송 (Q2)
|
||||
* - 브라우저의 /api 요청을 게임 PC 로 넘기고 응답을 돌려준다
|
||||
*/
|
||||
export class RelayHub {
|
||||
private device: { ws: WebSocket; id: string; name: string; version: string | null; lastMsg: number } | null = null;
|
||||
private browsers = new Set<WebSocket>();
|
||||
private pending = new Map<string, Pending>();
|
||||
readonly deviceWss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024 });
|
||||
readonly browserWss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 });
|
||||
private watchdog: NodeJS.Timeout;
|
||||
private lastStatus = '';
|
||||
|
||||
constructor(private store: ServerStore) {
|
||||
this.watchdog = setInterval(() => this.checkAlive(), 2000);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
clearInterval(this.watchdog);
|
||||
this.device?.ws.terminate();
|
||||
for (const b of this.browsers) b.terminate();
|
||||
}
|
||||
|
||||
status(): DeviceStatus {
|
||||
const d = this.store.device();
|
||||
return {
|
||||
registered: !!d,
|
||||
online: !!this.device && Date.now() - this.device.lastMsg < OFFLINE_AFTER_MS,
|
||||
name: d?.name ?? null,
|
||||
lastSeen: this.device ? this.device.lastMsg : (d?.lastSeen ?? null),
|
||||
version: this.device?.version ?? d?.version ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
private broadcastStatus(force = false): void {
|
||||
const st = this.status();
|
||||
const key = `${st.registered}|${st.online}|${st.name}`;
|
||||
if (!force && key === this.lastStatus) return;
|
||||
this.lastStatus = key;
|
||||
this.broadcast({ type: 'status', data: { device: st } });
|
||||
}
|
||||
|
||||
private broadcast(m: BrowserMessage): void {
|
||||
const txt = JSON.stringify(m);
|
||||
for (const b of this.browsers) if (b.readyState === WebSocket.OPEN) b.send(txt);
|
||||
}
|
||||
|
||||
private checkAlive(): void {
|
||||
if (this.device && Date.now() - this.device.lastMsg > OFFLINE_AFTER_MS) {
|
||||
this.device.ws.terminate();
|
||||
this.dropDevice(this.device.ws);
|
||||
}
|
||||
this.broadcastStatus();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 게임 PC
|
||||
authenticateDevice(req: IncomingMessage): { id: string } | null {
|
||||
const h = String(req.headers.authorization || '');
|
||||
const m = /^Device ([0-9a-f]+)\.([\w-]+)$/.exec(h);
|
||||
if (!m) return null;
|
||||
const d = this.store.verifyDevice(m[1], m[2]);
|
||||
return d ? { id: d.id } : null;
|
||||
}
|
||||
|
||||
attachDevice(ws: WebSocket, id: string): void {
|
||||
if (this.device) {
|
||||
// 같은 기기가 다시 연결 (네트워크 재연결) → 이전 연결을 끊는다
|
||||
this.device.ws.close(4000, 'replaced');
|
||||
this.dropDevice(this.device.ws);
|
||||
}
|
||||
const dev = this.store.device();
|
||||
this.device = { ws, id, name: dev?.name ?? 'GAME-PC', version: null, lastMsg: Date.now() };
|
||||
this.store.touchDevice(id, { lastSeen: Date.now() });
|
||||
ws.send(JSON.stringify({ t: 'welcome', deviceId: id } satisfies RelayToDevice));
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (!this.device || this.device.ws !== ws) return;
|
||||
this.device.lastMsg = Date.now();
|
||||
if (isBinary) return this.onBinary(data as Buffer);
|
||||
let m: RelayFromDevice;
|
||||
try {
|
||||
m = JSON.parse(String(data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
this.onDeviceMessage(m);
|
||||
});
|
||||
ws.on('close', () => this.dropDevice(ws));
|
||||
ws.on('error', () => this.dropDevice(ws));
|
||||
this.broadcastStatus(true);
|
||||
}
|
||||
|
||||
private dropDevice(ws: WebSocket): void {
|
||||
if (!this.device || this.device.ws !== ws) return;
|
||||
this.store.touchDevice(this.device.id, { lastSeen: this.device.lastMsg });
|
||||
this.device = null;
|
||||
for (const [id, p] of this.pending) {
|
||||
clearTimeout(p.timer);
|
||||
p.reject(new Error('device_offline'));
|
||||
this.pending.delete(id);
|
||||
}
|
||||
this.broadcastStatus(true);
|
||||
}
|
||||
|
||||
private onDeviceMessage(m: RelayFromDevice): void {
|
||||
const dev = this.device!;
|
||||
switch (m.t) {
|
||||
case 'hello':
|
||||
dev.name = m.name;
|
||||
dev.version = m.version;
|
||||
this.store.touchDevice(dev.id, { name: m.name, version: m.version, guildId: m.guildId ?? null, lastSeen: Date.now() });
|
||||
this.broadcastStatus(true);
|
||||
break;
|
||||
case 'ping':
|
||||
dev.ws.send(JSON.stringify({ t: 'pong', ts: m.ts } satisfies RelayToDevice));
|
||||
this.store.touchDevice(dev.id, { lastSeen: Date.now() });
|
||||
break;
|
||||
case 'res': {
|
||||
const p = this.pending.get(m.id);
|
||||
if (!p) return;
|
||||
this.pending.delete(m.id);
|
||||
clearTimeout(p.timer);
|
||||
p.resolve({ status: m.status, headers: m.headers, body: Buffer.from(m.body ?? '', 'utf8') });
|
||||
break;
|
||||
}
|
||||
case 'res_head': {
|
||||
const p = this.pending.get(m.id);
|
||||
if (p) p.head = { status: m.status, headers: m.headers };
|
||||
break;
|
||||
}
|
||||
case 'res_end': {
|
||||
const p = this.pending.get(m.id);
|
||||
if (!p || !p.head) return;
|
||||
this.pending.delete(m.id);
|
||||
clearTimeout(p.timer);
|
||||
p.resolve({ status: p.head.status, headers: p.head.headers, body: Buffer.concat(p.chunks) });
|
||||
break;
|
||||
}
|
||||
case 'event':
|
||||
this.broadcast(m.event as LiveEvent);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private onBinary(buf: Buffer): void {
|
||||
if (buf.length < 4) return;
|
||||
const n = buf.readUInt32BE(0);
|
||||
const id = buf.subarray(4, 4 + n).toString('utf8');
|
||||
const p = this.pending.get(id);
|
||||
if (p) p.chunks.push(buf.subarray(4 + n));
|
||||
}
|
||||
|
||||
/** 브라우저 요청 하나를 게임 PC 로 넘긴다 */
|
||||
request(method: string, path: string, headers: Record<string, string>, user: { id: string; name: string; avatar: string | null }, body: string | null, timeoutMs = 20000): Promise<RelayResponse> {
|
||||
const dev = this.device;
|
||||
if (!dev || !this.status().online) return Promise.reject(new Error('device_offline'));
|
||||
const id = crypto.randomBytes(8).toString('hex');
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
if (this.pending.delete(id)) reject(new Error('timeout'));
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, { resolve, reject, timer, chunks: [] });
|
||||
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body };
|
||||
dev.ws.send(JSON.stringify(msg));
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 브라우저
|
||||
attachBrowser(ws: WebSocket): void {
|
||||
this.browsers.add(ws);
|
||||
ws.send(JSON.stringify({ type: 'status', data: { device: this.status() } } satisfies BrowserMessage));
|
||||
const ping = setInterval(() => ws.readyState === WebSocket.OPEN && ws.ping(), 25000);
|
||||
ws.on('close', () => {
|
||||
clearInterval(ping);
|
||||
this.browsers.delete(ws);
|
||||
});
|
||||
ws.on('message', () => undefined);
|
||||
}
|
||||
|
||||
/** 로그아웃·세션 만료 시 해당 브라우저 연결 끊기용 */
|
||||
get browserCount(): number {
|
||||
return this.browsers.size;
|
||||
}
|
||||
}
|
||||
152
site/server/src/store.ts
Normal file
@@ -0,0 +1,152 @@
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
export interface Device {
|
||||
id: string;
|
||||
keyHash: string;
|
||||
name: string;
|
||||
createdAt: number;
|
||||
lastSeen: number | null;
|
||||
version: string | null;
|
||||
guildId: string | null;
|
||||
}
|
||||
export interface Session {
|
||||
id: string;
|
||||
user: { id: string; name: string; avatar: string | null };
|
||||
createdAt: number;
|
||||
checkedAt: number;
|
||||
expiresAt: number;
|
||||
}
|
||||
interface Data {
|
||||
devices: Device[];
|
||||
codes: { code: string; expiresAt: number; createdBy: string }[];
|
||||
sessions: Session[];
|
||||
}
|
||||
// codes 는 server.json 에 두지 않는다 (codes.json)
|
||||
|
||||
const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
|
||||
|
||||
/**
|
||||
* 사이트 서버가 저장하는 것은 이것뿐이다: 등록된 게임 PC(기기 키 해시), 1회용 등록 코드, 로그인 세션.
|
||||
* 기록 내용은 저장하지 않는다 (보고서 3장).
|
||||
*/
|
||||
export class ServerStore {
|
||||
private file: string;
|
||||
private codesFile: string;
|
||||
private d: Data;
|
||||
private saveTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(dir: string) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
this.file = path.join(dir, 'server.json');
|
||||
this.codesFile = path.join(dir, 'codes.json');
|
||||
try {
|
||||
this.d = JSON.parse(fs.readFileSync(this.file, 'utf8'));
|
||||
} catch {
|
||||
this.d = { devices: [], codes: [], sessions: [] };
|
||||
}
|
||||
this.d.devices ||= [];
|
||||
this.d.sessions ||= [];
|
||||
}
|
||||
|
||||
private save(now = false): void {
|
||||
const write = () => {
|
||||
this.saveTimer = null;
|
||||
const tmp = this.file + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(this.d), { mode: 0o600 });
|
||||
fs.renameSync(tmp, this.file);
|
||||
};
|
||||
if (now) return write();
|
||||
if (!this.saveTimer) this.saveTimer = setTimeout(write, 500);
|
||||
}
|
||||
flush(): void {
|
||||
if (this.saveTimer) {
|
||||
clearTimeout(this.saveTimer);
|
||||
this.save(true);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 등록 코드: 관리 CLI(다른 프로세스)도 만들 수 있게 codes.json 을 매번 디스크에서 읽고 쓴다
|
||||
private readCodes(): Data['codes'] {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(this.codesFile, 'utf8')).filter((c: any) => c.expiresAt > Date.now());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
private writeCodes(codes: Data['codes']): void {
|
||||
const tmp = this.codesFile + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(codes), { mode: 0o600 });
|
||||
fs.renameSync(tmp, this.codesFile);
|
||||
}
|
||||
createCode(createdBy: string, ttlMs = 10 * 60000): { code: string; expiresAt: number } {
|
||||
const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
let code = '';
|
||||
for (const b of crypto.randomBytes(8)) code += alphabet[b % alphabet.length];
|
||||
code = `${code.slice(0, 4)}-${code.slice(4)}`;
|
||||
const expiresAt = Date.now() + ttlMs;
|
||||
this.writeCodes([...this.readCodes(), { code, expiresAt, createdBy }]);
|
||||
return { code, expiresAt };
|
||||
}
|
||||
/** 코드 확인 후 기기 등록. 한 게임 PC 만 쓰므로 새로 등록하면 이전 기기는 지운다. */
|
||||
redeem(code: string, name: string): { deviceId: string; deviceKey: string } | null {
|
||||
const norm = code.trim().toUpperCase();
|
||||
const codes = this.readCodes();
|
||||
const c = codes.find((x) => x.code === norm);
|
||||
if (!c) return null;
|
||||
this.writeCodes(codes.filter((x) => x !== c));
|
||||
const deviceId = crypto.randomBytes(8).toString('hex');
|
||||
const deviceKey = crypto.randomBytes(32).toString('base64url');
|
||||
this.d.devices = [{ id: deviceId, keyHash: sha256(deviceKey), name: name.slice(0, 40) || 'GAME-PC', createdAt: Date.now(), lastSeen: null, version: null, guildId: null }];
|
||||
this.save(true);
|
||||
return { deviceId, deviceKey };
|
||||
}
|
||||
verifyDevice(id: string, key: string): Device | null {
|
||||
const d = this.d.devices.find((x) => x.id === id);
|
||||
if (!d) return null;
|
||||
const a = Buffer.from(d.keyHash, 'hex');
|
||||
const b = Buffer.from(sha256(key), 'hex');
|
||||
return a.length === b.length && crypto.timingSafeEqual(a, b) ? d : null;
|
||||
}
|
||||
removeDevices(): number {
|
||||
const n = this.d.devices.length;
|
||||
this.d.devices = [];
|
||||
this.save(true);
|
||||
return n;
|
||||
}
|
||||
device(): Device | null {
|
||||
return this.d.devices[0] ?? null;
|
||||
}
|
||||
touchDevice(id: string, patch: Partial<Pick<Device, 'lastSeen' | 'version' | 'guildId' | 'name'>>): void {
|
||||
const d = this.d.devices.find((x) => x.id === id);
|
||||
if (!d) return;
|
||||
Object.assign(d, patch);
|
||||
this.save();
|
||||
}
|
||||
|
||||
// ---- 세션
|
||||
createSession(user: Session['user'], ttlMs = 30 * 24 * 3600 * 1000): Session {
|
||||
const s: Session = { id: crypto.randomBytes(24).toString('base64url'), user, createdAt: Date.now(), checkedAt: Date.now(), expiresAt: Date.now() + ttlMs };
|
||||
this.d.sessions = this.d.sessions.filter((x) => x.expiresAt > Date.now());
|
||||
this.d.sessions.push(s);
|
||||
this.save();
|
||||
return s;
|
||||
}
|
||||
session(id: string | undefined): Session | null {
|
||||
if (!id) return null;
|
||||
const s = this.d.sessions.find((x) => x.id === id);
|
||||
return s && s.expiresAt > Date.now() ? s : null;
|
||||
}
|
||||
touchSession(id: string): void {
|
||||
const s = this.d.sessions.find((x) => x.id === id);
|
||||
if (s) {
|
||||
s.checkedAt = Date.now();
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
deleteSession(id: string): void {
|
||||
this.d.sessions = this.d.sessions.filter((x) => x.id !== id);
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
148
site/server/test/relay.test.ts
Normal file
@@ -0,0 +1,148 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import WebSocket from 'ws';
|
||||
import { buildServer } from '../src/app.ts';
|
||||
import type { Config } from '../src/config.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-site-'));
|
||||
|
||||
/** 가짜 디스코드 API: OAuth 토큰 교환, users/@me, 길드 멤버 */
|
||||
async function fakeDiscord(members: Set<string>) {
|
||||
const srv = http.createServer((req, res) => {
|
||||
const u = new URL(req.url!, 'http://x');
|
||||
res.setHeader('content-type', 'application/json');
|
||||
if (u.pathname === '/oauth2/token') return res.end(JSON.stringify({ access_token: 'at-' + 'member1' }));
|
||||
if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'seunghan', global_name: '승한', avatar: null }));
|
||||
const m = /\/guilds\/(\d+)\/members\/(\w+)/.exec(u.pathname);
|
||||
if (m) {
|
||||
if (members.has(m[2])) return res.end(JSON.stringify({ nick: '승한', avatar: null }));
|
||||
res.statusCode = 404;
|
||||
return res.end('{}');
|
||||
}
|
||||
res.statusCode = 404;
|
||||
res.end('{}');
|
||||
});
|
||||
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
|
||||
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
|
||||
}
|
||||
|
||||
test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음성) → 실시간 이벤트 → 연결 끊김 잠금', async () => {
|
||||
const members = new Set(['member1']);
|
||||
const dc = await fakeDiscord(members);
|
||||
const cfg: Config = {
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
publicUrl: 'http://127.0.0.1',
|
||||
clientId: 'cid',
|
||||
clientSecret: 'secret',
|
||||
botToken: 'bot',
|
||||
allowedGuilds: ['111'],
|
||||
owners: ['owner1'],
|
||||
sessionSecret: 'x'.repeat(32),
|
||||
dataDir: tmp(),
|
||||
webDir: '/nonexistent',
|
||||
version: 'test',
|
||||
discordApi: dc.url,
|
||||
assetUpstream: {},
|
||||
};
|
||||
const { app, store } = await buildServer(cfg);
|
||||
await app.listen({ host: '127.0.0.1', port: 0 });
|
||||
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
|
||||
try {
|
||||
// 로그인 안 하면 401
|
||||
assert.equal((await fetch(base + '/api/status')).status, 401);
|
||||
// OAuth: state 쿠키 → callback
|
||||
const start = await fetch(base + '/auth/discord', { redirect: 'manual' });
|
||||
assert.equal(start.status, 302);
|
||||
const loc = new URL(start.headers.get('location')!);
|
||||
assert.equal(loc.searchParams.get('scope'), 'identify guilds');
|
||||
const stateCookie = start.headers.getSetCookie()[0].split(';')[0];
|
||||
const cb = await fetch(`${base}/auth/discord/callback?code=abc&state=${loc.searchParams.get('state')}`, { headers: { cookie: stateCookie }, redirect: 'manual' });
|
||||
assert.equal(cb.headers.get('location'), '/');
|
||||
const sid = cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0];
|
||||
const me = (await (await fetch(base + '/auth/me', { headers: { cookie: sid } })).json()) as any;
|
||||
assert.equal(me.user.name, '승한');
|
||||
// 기기 없음 → 상태 registered:false, /api 는 503
|
||||
let st = (await (await fetch(base + '/api/status', { headers: { cookie: sid } })).json()) as any;
|
||||
assert.equal(st.device.registered, false);
|
||||
assert.equal((await fetch(base + '/api/timeline', { headers: { cookie: sid } })).status, 503);
|
||||
// 등록 코드 → 기기 등록
|
||||
const code = store.createCode('test');
|
||||
assert.equal((await fetch(base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: 'WRONG', name: 'x' }) })).status, 400);
|
||||
const reg = (await (await fetch(base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: code.code, name: 'GAME-PC' }) })).json()) as any;
|
||||
assert.ok(reg.deviceKey);
|
||||
// 코드는 1회용
|
||||
assert.equal((await fetch(base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: code.code, name: 'x' }) })).status, 400);
|
||||
// 잘못된 키는 거절
|
||||
await assert.rejects(
|
||||
new Promise((res, rej) => {
|
||||
const w = new WebSocket(base.replace('http', 'ws') + '/device/ws', { headers: { authorization: `Device ${reg.deviceId}.wrong` } });
|
||||
w.on('open', res);
|
||||
w.on('error', rej);
|
||||
}),
|
||||
);
|
||||
// 브라우저 WS
|
||||
const bws = new WebSocket(base.replace('http', 'ws') + '/ws', { headers: { cookie: sid } });
|
||||
const bmsgs: any[] = [];
|
||||
bws.on('message', (d) => bmsgs.push(JSON.parse(String(d))));
|
||||
await new Promise((r) => bws.on('open', r));
|
||||
// 앱 코어 쪽 (실제 RelayClient + Fastify inject)
|
||||
const { RelayClient } = await import('../../../app/src/core/relay/client.ts');
|
||||
const { Bus } = await import('../../../app/src/core/util/events.ts');
|
||||
const Fastify = (await import('fastify')).default;
|
||||
const local = Fastify();
|
||||
local.get('/api/timeline', async (req) => ({ items: [], next: null, user: req.headers['x-gvr-user'] }));
|
||||
local.get('/api/audio/:id', async (_req, reply) => reply.header('content-type', 'audio/ogg').send(Buffer.from('OggS' + 'x'.repeat(5000))));
|
||||
local.patch('/api/utterances/:id', async (req) => ({ ok: true, body: req.body }));
|
||||
const bus = new Bus();
|
||||
const rc = new RelayClient(local as any, bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: '1.0.0', guildId: '222' }));
|
||||
rc.start();
|
||||
const wait = async (fn: () => boolean, ms = 5000) => {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - t > ms) throw new Error('timeout');
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
};
|
||||
await wait(() => rc.status.state === 'online');
|
||||
await wait(() => bmsgs.some((m) => m.type === 'status' && m.data.device.online));
|
||||
st = (await (await fetch(base + '/api/status', { headers: { cookie: sid } })).json()) as any;
|
||||
assert.equal(st.device.online, true);
|
||||
// JSON 중계
|
||||
const tl = (await (await fetch(base + '/api/timeline?limit=5', { headers: { cookie: sid } })).json()) as any;
|
||||
assert.deepEqual(tl.items, []);
|
||||
assert.equal(JSON.parse(decodeURIComponent(tl.user)).id, 'member1');
|
||||
// 음성(바이너리) 중계
|
||||
const au = await fetch(base + '/api/audio/abc', { headers: { cookie: sid } });
|
||||
assert.equal(au.headers.get('content-type'), 'audio/ogg');
|
||||
assert.equal((await au.arrayBuffer()).byteLength, 5004);
|
||||
// 쓰기 요청: 다른 사이트 Origin 은 거절
|
||||
assert.equal((await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: 'https://evil.example' }, body: '{"text":"x"}' })).status, 403);
|
||||
const pr = (await (await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: cfg.publicUrl }, body: '{"text":"고침"}' })).json()) as any;
|
||||
assert.equal(pr.body.text, '고침');
|
||||
// 실시간 이벤트 → 브라우저
|
||||
bus.live({ type: 'recording.state', data: { active: true, channel: '음성', since: 1, participants: [] } });
|
||||
await wait(() => bmsgs.some((m) => m.type === 'recording.state'));
|
||||
// 기기가 알려 준 서버(222) 멤버도 로그인 허용
|
||||
assert.equal(store.device()!.guildId, '222');
|
||||
// 연결 끊김 → 잠금
|
||||
rc.stop();
|
||||
await wait(() => bmsgs.some((m) => m.type === 'status' && m.data.device.registered && !m.data.device.online));
|
||||
assert.equal((await fetch(base + '/api/timeline', { headers: { cookie: sid } })).status, 503);
|
||||
// 서버 멤버가 아니면 로그인 거절
|
||||
members.clear();
|
||||
const s2 = await fetch(base + '/auth/discord', { redirect: 'manual' });
|
||||
const l2 = new URL(s2.headers.get('location')!);
|
||||
const cb2 = await fetch(`${base}/auth/discord/callback?code=abc&state=${l2.searchParams.get('state')}`, { headers: { cookie: s2.headers.getSetCookie()[0].split(';')[0] }, redirect: 'manual' });
|
||||
assert.equal(cb2.headers.get('location'), '/?login=not_member');
|
||||
bws.close();
|
||||
await local.close();
|
||||
} finally {
|
||||
await app.close();
|
||||
dc.close();
|
||||
}
|
||||
});
|
||||
17
site/server/tsconfig.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"types": ["node"],
|
||||
"lib": ["ES2023"],
|
||||
"baseUrl": ".",
|
||||
"paths": { "@gvr/shared": ["../../packages/shared/src/index.ts"] }
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts", "../../packages/shared/src/**/*.ts"]
|
||||
}
|
||||
3
site/web/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
dist
|
||||
*.log
|
||||
19
site/web/index.html
Normal file
@@ -0,0 +1,19 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#0b141c" />
|
||||
<title>겜녹이 · Game Voice Recorder</title>
|
||||
<meta name="description" content="겜녹이 — 디스코드 음성 녹음 · 발로란트 / 리그 오브 레전드 경기 기록" />
|
||||
<meta property="og:title" content="겜녹이 · Game Voice Recorder" />
|
||||
<meta property="og:image" content="/og-image.png" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="any" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
109
site/web/mock/audio.mjs
Normal 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
@@ -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
@@ -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
@@ -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();
|
||||
1850
site/web/package-lock.json
generated
Normal file
30
site/web/package.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "@gvr/web",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node mock/run.mjs dev",
|
||||
"dev:vite": "vite",
|
||||
"mock": "node mock/server.mjs",
|
||||
"build": "vite build",
|
||||
"preview": "node mock/run.mjs preview",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"framer-motion": "^12.43.0",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router": "^7.18.4",
|
||||
"wavesurfer.js": "^7.12.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.20.5",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.3.7",
|
||||
"ws": "^8.22.0"
|
||||
}
|
||||
}
|
||||
BIN
site/web/public/apple-touch-icon.png
Normal file
|
After Width: | Height: | Size: 29 KiB |
BIN
site/web/public/banner.png
Normal file
|
After Width: | Height: | Size: 463 KiB |
BIN
site/web/public/banner.webp
Normal file
|
After Width: | Height: | Size: 37 KiB |
BIN
site/web/public/favicon.ico
Normal file
|
After Width: | Height: | Size: 8.1 KiB |
43
site/web/public/favicon.svg
Normal file
@@ -0,0 +1,43 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
|
||||
<defs>
|
||||
<radialGradient id="bg" cx="50%" cy="45%" r="65%">
|
||||
<stop offset="0" stop-color="#1d3346"/><stop offset="1" stop-color="#0b141c"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="gold" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#f0d9a0"/><stop offset="1" stop-color="#a8854a"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="mic" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#ff6b78"/><stop offset="1" stop-color="#d92f40"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<clipPath id="rr"><rect width="1024" height="1024" rx="200"/></clipPath><g clip-path="url(#rr)"><rect width="1024" height="1024" fill="url(#bg)"/>
|
||||
<!-- crosshair ring with 4 gaps -->
|
||||
<g fill="none" stroke="url(#gold)" stroke-width="22" stroke-linecap="round">
|
||||
<circle cx="512" cy="512" r="370" stroke-dasharray="500.9 80.3" stroke-dashoffset="-40.15" transform="rotate(0 512 512)"/>
|
||||
</g>
|
||||
<!-- crosshair ticks -->
|
||||
<g stroke="#f0e6d2" stroke-width="22" stroke-linecap="round">
|
||||
<line x1="512" y1="110" x2="512" y2="200"/>
|
||||
<line x1="512" y1="824" x2="512" y2="914"/>
|
||||
<line x1="110" y1="512" x2="200" y2="512"/>
|
||||
<line x1="824" y1="512" x2="914" y2="512"/>
|
||||
</g>
|
||||
<!-- sound waves -->
|
||||
<g fill="none" stroke="#14c1b7" stroke-width="26" stroke-linecap="round">
|
||||
<path d="M290 360 A200 200 0 0 0 290 620"/>
|
||||
<path d="M734 360 A200 200 0 0 1 734 620"/>
|
||||
</g>
|
||||
<!-- microphone -->
|
||||
<rect x="417" y="250" width="190" height="320" rx="95" fill="url(#mic)"/>
|
||||
<g stroke="#ffffff" stroke-opacity=".35" stroke-width="12" stroke-linecap="round">
|
||||
<line x1="462" y1="340" x2="562" y2="340"/>
|
||||
<line x1="462" y1="390" x2="562" y2="390"/>
|
||||
<line x1="462" y1="440" x2="562" y2="440"/>
|
||||
</g>
|
||||
<path d="M362 470 A150 150 0 0 0 662 470" fill="none" stroke="#f0e6d2" stroke-width="26" stroke-linecap="round"/>
|
||||
<line x1="512" y1="620" x2="512" y2="700" stroke="#f0e6d2" stroke-width="26" stroke-linecap="round"/>
|
||||
<line x1="432" y1="712" x2="592" y2="712" stroke="#f0e6d2" stroke-width="26" stroke-linecap="round"/>
|
||||
<!-- REC dot -->
|
||||
<circle cx="668" cy="270" r="48" fill="#ff4655" stroke="#0b141c" stroke-width="18"/>
|
||||
<circle cx="668" cy="270" r="18" fill="#ffffff" opacity=".9"/>
|
||||
</g></svg>
|
||||
|
After Width: | Height: | Size: 2.3 KiB |
BIN
site/web/public/icon-192.png
Normal file
|
After Width: | Height: | Size: 36 KiB |
BIN
site/web/public/icon-512.png
Normal file
|
After Width: | Height: | Size: 154 KiB |
BIN
site/web/public/og-image.png
Normal file
|
After Width: | Height: | Size: 405 KiB |
BIN
site/web/screenshots/locked.png
Normal file
|
After Width: | Height: | Size: 267 KiB |
BIN
site/web/screenshots/login-not-member.png
Normal file
|
After Width: | Height: | Size: 146 KiB |
BIN
site/web/screenshots/login.png
Normal file
|
After Width: | Height: | Size: 146 KiB |
BIN
site/web/screenshots/match-lol.png
Normal file
|
After Width: | Height: | Size: 116 KiB |
BIN
site/web/screenshots/match-valorant-scene.png
Normal file
|
After Width: | Height: | Size: 109 KiB |
BIN
site/web/screenshots/match-valorant.png
Normal file
|
After Width: | Height: | Size: 114 KiB |
BIN
site/web/screenshots/mobile.png
Normal file
|
After Width: | Height: | Size: 76 KiB |
BIN
site/web/screenshots/settings.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
site/web/screenshots/timeline-live.png
Normal file
|
After Width: | Height: | Size: 66 KiB |
BIN
site/web/screenshots/timeline-playing.png
Normal file
|
After Width: | Height: | Size: 80 KiB |
BIN
site/web/screenshots/timeline.png
Normal file
|
After Width: | Height: | Size: 67 KiB |
BIN
site/web/screenshots/user.png
Normal file
|
After Width: | Height: | Size: 59 KiB |
113
site/web/src/App.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Navigate, Route, Routes } from 'react-router';
|
||||
import { MotionConfig } from 'framer-motion';
|
||||
import { AuthProvider, DataProvider, StatusProvider, useAuth, useStatus } from './store/app';
|
||||
import { useReducedMotion } from './store/settings';
|
||||
import { player } from './store/player';
|
||||
import { resumeAudio } from './lib/audio';
|
||||
import { Header } from './components/Header';
|
||||
import { LockOverlay } from './components/LockOverlay';
|
||||
import { LoginPage } from './components/LoginPage';
|
||||
import { PlayerBar } from './components/PlayerBar';
|
||||
import { Spinner } from './components/common';
|
||||
import { TimelinePage } from './pages/TimelinePage';
|
||||
import { MatchPage } from './pages/MatchPage';
|
||||
import { MatchesPage, UserPage, UsersPage } from './pages/UserPages';
|
||||
|
||||
/** Space 재생/일시정지 · ←/→ 이전/다음 발화 · / 검색 */
|
||||
function useShortcuts() {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
const t = e.target as HTMLElement;
|
||||
const typing = t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName);
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
if (e.key === '/' && !typing) {
|
||||
e.preventDefault();
|
||||
document.getElementById('gvr-search')?.focus();
|
||||
return;
|
||||
}
|
||||
if (typing) return;
|
||||
if (e.key === ' ' || e.code === 'Space') {
|
||||
if (t.tagName === 'BUTTON' || t.tagName === 'A') t.blur();
|
||||
e.preventDefault();
|
||||
player.toggle();
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
e.preventDefault();
|
||||
player.next();
|
||||
} else if (e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
player.prev();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
// 첫 사용자 제스처에서 AudioContext 를 깨워 효과음이 바로 나게
|
||||
const wake = () => resumeAudio();
|
||||
window.addEventListener('pointerdown', wake, { once: true });
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('pointerdown', wake);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const { locked, epoch } = useStatus();
|
||||
useShortcuts();
|
||||
return (
|
||||
<div className={`shell${locked ? ' is-locked' : ''}`}>
|
||||
<div className="app" aria-hidden={locked || undefined}>
|
||||
<Header />
|
||||
<div className="content" key={epoch}>
|
||||
<Routes>
|
||||
<Route path="/" element={<TimelinePage />} />
|
||||
<Route path="/matches" element={<MatchesPage />} />
|
||||
<Route path="/matches/:id" element={<MatchPage />} />
|
||||
<Route path="/users" element={<UsersPage />} />
|
||||
<Route path="/users/:id" element={<UserPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</div>
|
||||
<PlayerBar />
|
||||
</div>
|
||||
<LockOverlay />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Gate() {
|
||||
const { auth } = useAuth();
|
||||
if (auth.status === 'loading')
|
||||
return (
|
||||
<div className="boot">
|
||||
<img src="/icon-192.png" alt="" />
|
||||
<Spinner label="겜녹이 여는 중" />
|
||||
</div>
|
||||
);
|
||||
if (auth.status === 'anon') {
|
||||
// 서버가 OAuth 결과를 ?login=... 으로 알려 준다
|
||||
const q = new URLSearchParams(window.location.search).get('login');
|
||||
return <LoginPage notMember={q === 'not_member'} error={q === 'error' || q === 'invalid' ? '로그인 중 문제가 생겼습니다. 다시 시도해 주세요.' : undefined} />;
|
||||
}
|
||||
if (auth.status === 'not_member') return <LoginPage notMember />;
|
||||
return (
|
||||
<StatusProvider>
|
||||
<DataProvider>
|
||||
<Shell />
|
||||
</DataProvider>
|
||||
</StatusProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const reduce = useReducedMotion();
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle('reduce-motion', reduce);
|
||||
}, [reduce]);
|
||||
return (
|
||||
<MotionConfig reducedMotion={reduce ? 'always' : 'never'}>
|
||||
<AuthProvider>
|
||||
<Gate />
|
||||
</AuthProvider>
|
||||
</MotionConfig>
|
||||
);
|
||||
}
|
||||
184
site/web/src/components/EventRow.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
import { memo } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { ChatData, EventItem, KillData, ObjectData, PlayerRef, RoundEndData } from '@gvr/shared';
|
||||
import { CharIcon, PName, TimeCell } from './common';
|
||||
import { CHANNEL_KO, MULTI_KO, OBJECT_GLYPH, objectName, roundResultKo } from '../lib/game';
|
||||
import { useReducedMotion } from '../store/settings';
|
||||
import { realTip } from '../lib/format';
|
||||
|
||||
export function KillLine({ d, game, iconSize = 22 }: { d: KillData; game: 'valorant' | 'lol'; iconSize?: number }) {
|
||||
return (
|
||||
<>
|
||||
{d.killer ? (
|
||||
<>
|
||||
<CharIcon c={d.killer.character} size={iconSize} />
|
||||
<PName p={d.killer} />
|
||||
</>
|
||||
) : (
|
||||
<span className="dim">{game === 'lol' ? '처형' : '낙사'}</span>
|
||||
)}
|
||||
{d.weapon?.icon ? <img className="wk" src={d.weapon.icon} alt={d.weapon.name} title={d.weapon.name} /> : d.weapon ? <span className="dim wname">{d.weapon.name}</span> : null}
|
||||
<span className="arrow">▶</span>
|
||||
<CharIcon c={d.victim.character} size={iconSize} />
|
||||
<PName p={d.victim} />
|
||||
{d.headshot && <span className="dim">헤드샷</span>}
|
||||
{d.assists?.length > 0 && game === 'lol' && (
|
||||
<span className="dim">
|
||||
· 어시{' '}
|
||||
{d.assists.map((a: PlayerRef, i: number) => (
|
||||
<span key={i}>
|
||||
{i > 0 && ', '}
|
||||
<PName p={a} strong={false} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function isAllyDeath(e: EventItem) {
|
||||
const d = e.data as KillData;
|
||||
return e.type === 'kill' && (d.ally === false || (d.ally == null && !!d.victim?.userId));
|
||||
}
|
||||
|
||||
/** 이벤트 내용 (킬 · 채팅 · 오브젝트 · 스파이크 · 멀티킬) */
|
||||
export function EventBody({ e, iconSize = 22 }: { e: EventItem; iconSize?: number }) {
|
||||
switch (e.type) {
|
||||
case 'kill':
|
||||
return (
|
||||
<div className={`ev ${isAllyDeath(e) ? 'death' : 'kill'}`}>
|
||||
<KillLine d={e.data as KillData} game={e.game} iconSize={iconSize} />
|
||||
</div>
|
||||
);
|
||||
case 'multikill':
|
||||
case 'ace': {
|
||||
const d = e.data as { player?: PlayerRef; count?: number };
|
||||
return (
|
||||
<div className="ev kill multi">
|
||||
<CharIcon c={d.player?.character} size={iconSize} />
|
||||
<PName p={d.player} />
|
||||
<span className="kbadge">{e.type === 'ace' ? '에이스' : MULTI_KO[d.count ?? 2] ?? `${d.count}킬`}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
case 'chat': {
|
||||
const d = e.data as ChatData;
|
||||
return (
|
||||
<div className={`ev chat ${e.game}`}>
|
||||
<span aria-hidden>💬</span>
|
||||
<span className={`ctag ch-${d.channel}`}>{CHANNEL_KO[d.channel] ?? d.channel}</span>
|
||||
<PName p={d.sender} />
|
||||
{d.sender.character && <span className="dim">({d.sender.character.name})</span>}
|
||||
<span className="ctext">{d.text}</span>
|
||||
{d.source === 'ocr' && (
|
||||
<span className="ocr" title="게임 화면에서 글자 인식(OCR)으로 읽은 채팅">
|
||||
OCR
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
case 'object': {
|
||||
const d = e.data as ObjectData & { icon?: string | null };
|
||||
const name = objectName(d.object, d.subtype);
|
||||
const destroyed = d.object === 'tower' || d.object === 'inhibitor';
|
||||
return (
|
||||
<div className={`ev obj${d.ally === false ? ' enemy' : ''}`}>
|
||||
{d.icon ? <img className="oi" src={d.icon} alt="" /> : <span aria-hidden>{OBJECT_GLYPH[d.object] ?? '◆'}</span>}
|
||||
{destroyed ? (
|
||||
<span>
|
||||
{d.ally === false ? '우리' : '상대'} <b className="gold">{name}</b> 파괴
|
||||
</span>
|
||||
) : (
|
||||
<span>
|
||||
{d.ally === false ? '상대 팀' : '우리 팀'} <b className="gold">{name}</b> 처치
|
||||
</span>
|
||||
)}
|
||||
{d.killer && (
|
||||
<span className="dim">
|
||||
· <PName p={d.killer} strong={false} />
|
||||
{d.object === 'dragon' || d.object === 'baron' ? ' 강타' : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
case 'spike': {
|
||||
const d = e.data as { action?: string; site?: string; player?: PlayerRef };
|
||||
const act = d.action === 'defuse' ? '해체' : d.action === 'detonate' ? '폭발' : '설치';
|
||||
return (
|
||||
<div className="ev spike">
|
||||
<span className="spike-ic">◆</span> 스파이크 {act}
|
||||
{d.site && <span className="dim">· {d.site} 사이트</span>}
|
||||
{d.player && (
|
||||
<span className="dim">
|
||||
· <PName p={d.player} strong={false} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
default:
|
||||
return <div className="ev">{e.type}</div>;
|
||||
}
|
||||
}
|
||||
|
||||
export const SEPARATOR_TYPES = new Set(['round_end', 'match_start', 'match_end']);
|
||||
|
||||
/** 라운드 종료 · 경기 시작/종료 구분선 (와이프 연출) */
|
||||
export const SeparatorRow = memo(function SeparatorRow({ e }: { e: EventItem }) {
|
||||
const reduce = useReducedMotion();
|
||||
let pill = '';
|
||||
let text = '';
|
||||
let score = '';
|
||||
let cls = '';
|
||||
if (e.type === 'round_end') {
|
||||
const d = e.data as RoundEndData & { winner?: string };
|
||||
const win = d.win ?? d.winner === 'ally';
|
||||
pill = `R${d.round}`;
|
||||
text = `${win ? '승리' : '패배'} · ${roundResultKo(d.result)}`;
|
||||
score = `${d.score.ally} : ${d.score.enemy}`;
|
||||
cls = win ? 'win' : 'loss';
|
||||
} else if (e.type === 'match_start') {
|
||||
const d = e.data as { map?: string; mode?: string };
|
||||
pill = '경기 시작';
|
||||
text = [d.map, d.mode].filter(Boolean).join(' · ');
|
||||
cls = 'start';
|
||||
} else {
|
||||
const d = e.data as { win?: boolean; score?: { ally: number; enemy: number } };
|
||||
pill = '경기 종료';
|
||||
text = d.win == null ? '' : d.win ? '승리' : '패배';
|
||||
score = d.score ? `${d.score.ally} : ${d.score.enemy}` : '';
|
||||
cls = d.win ? 'win' : 'loss';
|
||||
}
|
||||
return (
|
||||
<div className={`sep ${cls} g-${e.game}`} data-tip={realTip(e.ts)}>
|
||||
<span className="pill">{pill}</span>
|
||||
<span className="sep-text">{text}</span>
|
||||
{score && <span className="score mono">{score}</span>}
|
||||
<span className="sep-time mono">{e.time.primary}</span>
|
||||
<span className="sep-line">
|
||||
<motion.i
|
||||
initial={reduce ? false : { scaleX: 0 }}
|
||||
whileInView={{ scaleX: 1 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.7, ease: [0.2, 0.7, 0.2, 1] }}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export const EventRow = memo(function EventRow({ e }: { e: EventItem }) {
|
||||
if (SEPARATOR_TYPES.has(e.type)) return <SeparatorRow e={e} />;
|
||||
return (
|
||||
<div className={`it evrow t-${e.type}`} data-id={e.id}>
|
||||
<TimeCell time={e.time} />
|
||||
<span className="av-spacer" />
|
||||
<div className="body">
|
||||
<EventBody e={e} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
193
site/web/src/components/Header.tsx
Normal file
@@ -0,0 +1,193 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { NavLink, useLocation, useNavigate, useSearchParams } from 'react-router';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { useAuth, useData, useStatus } from '../store/app';
|
||||
import { settings, useSettings, type SfxKind } from '../store/settings';
|
||||
import { sfx, SFX_LABEL } from '../lib/sfx';
|
||||
import { resumeAudio } from '../lib/audio';
|
||||
import { Avatar, Brand } from './common';
|
||||
import { IGear, ILogout, ISearch } from './Icons';
|
||||
|
||||
function SettingsPopover({ onClose }: { onClose: () => void }) {
|
||||
const s = useSettings();
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const down = (e: PointerEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node) && !(e.target as HTMLElement).closest('.gear-btn')) onClose();
|
||||
};
|
||||
const key = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
|
||||
document.addEventListener('pointerdown', down);
|
||||
document.addEventListener('keydown', key);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', down);
|
||||
document.removeEventListener('keydown', key);
|
||||
};
|
||||
}, [onClose]);
|
||||
return (
|
||||
<motion.div
|
||||
ref={ref}
|
||||
className="popover"
|
||||
initial={{ opacity: 0, y: -6, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -6, scale: 0.98 }}
|
||||
transition={{ duration: 0.16 }}
|
||||
role="dialog"
|
||||
aria-label="설정"
|
||||
>
|
||||
<h5>효과음</h5>
|
||||
<label className="row">
|
||||
<span>전체 볼륨</span>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={s.volume}
|
||||
onChange={(e) => settings.set({ volume: Number(e.target.value) })}
|
||||
onPointerUp={() => {
|
||||
resumeAudio();
|
||||
sfx('click');
|
||||
}}
|
||||
/>
|
||||
<span className="mono val">{Math.round(s.volume * 100)}</span>
|
||||
</label>
|
||||
{(Object.keys(SFX_LABEL) as SfxKind[]).map((k) => (
|
||||
<label className="row check" key={k}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={s.sfx[k]}
|
||||
onChange={(e) => {
|
||||
settings.set({ sfx: { ...s.sfx, [k]: e.target.checked } });
|
||||
resumeAudio();
|
||||
if (e.target.checked) window.setTimeout(() => sfx(k), 30);
|
||||
}}
|
||||
/>
|
||||
<span>{SFX_LABEL[k]}</span>
|
||||
<button
|
||||
className="mini-btn"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
resumeAudio();
|
||||
window.setTimeout(() => sfx(k), 30);
|
||||
}}
|
||||
>
|
||||
미리 듣기
|
||||
</button>
|
||||
</label>
|
||||
))}
|
||||
<h5>화면</h5>
|
||||
<label className="row check">
|
||||
<input type="checkbox" checked={s.reduceMotion} onChange={(e) => settings.set({ reduceMotion: e.target.checked })} />
|
||||
<span>모션 줄이기</span>
|
||||
</label>
|
||||
<div className="pop-foot">단축키: Space 재생 · ←/→ 이전·다음 발화 · / 검색 · Esc 닫기</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SearchBox() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const loc = useLocation();
|
||||
const nav = useNavigate();
|
||||
const onTimeline = loc.pathname === '/';
|
||||
const urlQ = onTimeline ? params.get('q') ?? '' : '';
|
||||
const [v, setV] = useState(urlQ);
|
||||
useEffect(() => setV(urlQ), [urlQ]);
|
||||
const timer = useRef<number | null>(null);
|
||||
const commit = (q: string) => {
|
||||
if (!onTimeline) {
|
||||
nav(q ? `/?q=${encodeURIComponent(q)}` : '/');
|
||||
return;
|
||||
}
|
||||
const p = new URLSearchParams(params);
|
||||
if (q) p.set('q', q);
|
||||
else p.delete('q');
|
||||
setParams(p, { replace: true });
|
||||
};
|
||||
return (
|
||||
<form
|
||||
className="search"
|
||||
role="search"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (timer.current) window.clearTimeout(timer.current);
|
||||
commit(v.trim());
|
||||
}}
|
||||
>
|
||||
<ISearch width={16} height={16} />
|
||||
<input
|
||||
id="gvr-search"
|
||||
value={v}
|
||||
placeholder="대화 내용 검색 (예: 스파이크)"
|
||||
onChange={(e) => {
|
||||
const q = e.target.value;
|
||||
setV(q);
|
||||
if (!onTimeline) return;
|
||||
if (timer.current) window.clearTimeout(timer.current);
|
||||
timer.current = window.setTimeout(() => commit(q.trim()), 350);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') (e.target as HTMLInputElement).blur();
|
||||
}}
|
||||
aria-label="대화 내용 검색"
|
||||
/>
|
||||
<kbd>/</kbd>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function Header() {
|
||||
const { auth, logout } = useAuth();
|
||||
const { overview } = useData();
|
||||
const { device, locked, conn } = useStatus();
|
||||
const [open, setOpen] = useState(false);
|
||||
const me = auth.status === 'ok' ? auth.me.user : null;
|
||||
const rec = overview?.recording;
|
||||
const nav = [
|
||||
['/', '타임라인'],
|
||||
['/matches', '경기'],
|
||||
['/users', '유저'],
|
||||
] as const;
|
||||
return (
|
||||
<header className="topbar">
|
||||
<NavLink to="/" className="brand-link" aria-label="겜녹이 홈">
|
||||
<Brand />
|
||||
</NavLink>
|
||||
<nav className="nav">
|
||||
{nav.map(([to, label]) => (
|
||||
<NavLink key={to} to={to} end={to === '/'} className={({ isActive }) => `chip${isActive ? ' on' : ''}`} onClick={() => sfx('click')}>
|
||||
{label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
<SearchBox />
|
||||
<div className="hdr-right">
|
||||
{rec?.active && !locked && (
|
||||
<div className="rec" title={rec.since ? `녹음 시작 ${new Date(rec.since).toLocaleTimeString('ko-KR', { hour12: false })}` : undefined}>
|
||||
<i /> <span className="rec-txt">녹음 중{rec.channel ? ` · #${rec.channel}` : ''} · {rec.participants.length}명</span>
|
||||
<span className="rec-short">녹음 중</span>
|
||||
</div>
|
||||
)}
|
||||
{device && (
|
||||
<div className={`conn ${locked ? 'off' : conn === 'open' ? 'on' : 'warn'}`} title={conn === 'open' ? '실시간 연결됨' : '실시간 연결 재시도 중'}>
|
||||
<span className="dot" />
|
||||
<span className="conn-txt">{locked ? '게임 PC 연결 해제됨' : conn === 'open' ? '게임 PC 연결됨' : '실시간 재연결 중'}</span>
|
||||
</div>
|
||||
)}
|
||||
<button className="icon-btn gear-btn" onClick={() => setOpen((o) => !o)} aria-label="설정" title="효과음 · 모션 설정">
|
||||
<IGear />
|
||||
</button>
|
||||
<AnimatePresence>{open && <SettingsPopover onClose={() => setOpen(false)} />}</AnimatePresence>
|
||||
{me && (
|
||||
<div className="me">
|
||||
<Avatar name={me.name} src={me.avatar} color="#5865f2" size={26} />
|
||||
<span className="me-nm">{me.name}</span>
|
||||
<button className="icon-btn" onClick={logout} title="로그아웃" aria-label="로그아웃">
|
||||
<ILogout width={16} height={16} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
98
site/web/src/components/Icons.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import type { SVGProps } from 'react';
|
||||
|
||||
const base = (p: SVGProps<SVGSVGElement>) => ({ width: 18, height: 18, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round' as const, strokeLinejoin: 'round' as const, 'aria-hidden': true, ...p });
|
||||
|
||||
export const IPlay = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)} fill="currentColor" stroke="none">
|
||||
<path d="M7 4.5v15a1 1 0 0 0 1.5.86l12-7.5a1 1 0 0 0 0-1.72l-12-7.5A1 1 0 0 0 7 4.5z" />
|
||||
</svg>
|
||||
);
|
||||
export const IPause = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)} fill="currentColor" stroke="none">
|
||||
<rect x="5.5" y="4" width="4.5" height="16" rx="1.2" />
|
||||
<rect x="14" y="4" width="4.5" height="16" rx="1.2" />
|
||||
</svg>
|
||||
);
|
||||
export const IPrev = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)} fill="currentColor" stroke="none">
|
||||
<rect x="4" y="5" width="2.6" height="14" rx="1" />
|
||||
<path d="M20 5.6v12.8a.9.9 0 0 1-1.38.76L8.8 12.76a.9.9 0 0 1 0-1.52l9.82-6.4A.9.9 0 0 1 20 5.6z" />
|
||||
</svg>
|
||||
);
|
||||
export const INext = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)} fill="currentColor" stroke="none">
|
||||
<rect x="17.4" y="5" width="2.6" height="14" rx="1" />
|
||||
<path d="M4 5.6v12.8a.9.9 0 0 0 1.38.76l9.82-6.4a.9.9 0 0 0 0-1.52L5.38 4.84A.9.9 0 0 0 4 5.6z" />
|
||||
</svg>
|
||||
);
|
||||
export const IEdit = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M12 20h9" />
|
||||
<path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z" />
|
||||
</svg>
|
||||
);
|
||||
export const ISearch = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<circle cx="11" cy="11" r="7" />
|
||||
<path d="m20 20-3.5-3.5" />
|
||||
</svg>
|
||||
);
|
||||
export const IGear = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
|
||||
</svg>
|
||||
);
|
||||
export const ILogout = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
|
||||
<path d="m16 17 5-5-5-5" />
|
||||
<path d="M21 12H9" />
|
||||
</svg>
|
||||
);
|
||||
export const ILoop = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="m17 2 4 4-4 4" />
|
||||
<path d="M3 11v-1a4 4 0 0 1 4-4h14" />
|
||||
<path d="m7 22-4-4 4-4" />
|
||||
<path d="M21 13v1a4 4 0 0 1-4 4H3" />
|
||||
</svg>
|
||||
);
|
||||
export const IVolume = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M11 5 6 9H2v6h4l5 4V5z" />
|
||||
<path d="M15.5 8.5a5 5 0 0 1 0 7" />
|
||||
<path d="M19 5a10 10 0 0 1 0 14" />
|
||||
</svg>
|
||||
);
|
||||
export const IUsers = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="9" cy="7" r="4" />
|
||||
<path d="M23 21v-2a4 4 0 0 0-3-3.87" />
|
||||
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
|
||||
</svg>
|
||||
);
|
||||
export const IClose = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M18 6 6 18M6 6l12 12" />
|
||||
</svg>
|
||||
);
|
||||
export const IWaves = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M2 12h2M6 8v8M10 5v14M14 8v8M18 10v4M22 12h0" />
|
||||
</svg>
|
||||
);
|
||||
export const IDiscord = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg width={22} height={22} viewBox="0 0 24 24" fill="currentColor" aria-hidden {...p}>
|
||||
<path d="M20.3 4.4A19.6 19.6 0 0 0 15.4 3l-.6 1.3a18 18 0 0 0-5.6 0L8.6 3a19.6 19.6 0 0 0-4.9 1.5C.6 9.1-.3 13.6.1 18a19.8 19.8 0 0 0 6 3l1.3-2a12.8 12.8 0 0 1-2-1l.5-.4a14 14 0 0 0 12.2 0l.5.4-2 1 1.3 2a19.7 19.7 0 0 0 6-3c.5-5.1-.8-9.6-3.6-13.6zM8 15.3c-1.2 0-2.2-1.1-2.2-2.4S6.8 10.5 8 10.5s2.2 1.1 2.2 2.4-1 2.4-2.2 2.4zm8 0c-1.2 0-2.2-1.1-2.2-2.4s1-2.4 2.2-2.4 2.2 1.1 2.2 2.4-1 2.4-2.2 2.4z" />
|
||||
</svg>
|
||||
);
|
||||
export const IPlug = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg width={34} height={34} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" aria-hidden {...p}>
|
||||
<path d="M9 2v5M15 2v5" />
|
||||
<path d="M6 7h12v4a6 6 0 0 1-12 0V7z" />
|
||||
<path d="M12 17v5" />
|
||||
<path d="m3 3 18 18" stroke="#ff4655" />
|
||||
</svg>
|
||||
);
|
||||
135
site/web/src/components/LockOverlay.tsx
Normal file
@@ -0,0 +1,135 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { useAuth, useStatus } from '../store/app';
|
||||
import { fmtAgo, fmtWhen } from '../lib/format';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { api } from '../lib/api';
|
||||
import { IPlug } from './Icons';
|
||||
|
||||
/** 게임 PC 연결 해제 잠금. 다시 연결되면 열리는 전환과 함께 자동으로 사라진다. */
|
||||
export function LockOverlay() {
|
||||
const { device, serverOk, locked, recheck } = useStatus();
|
||||
const { logout, auth } = useAuth();
|
||||
const isOwner = auth.status === 'ok' && auth.me.isOwner;
|
||||
const [code, setCode] = useState<{ code: string; expiresAt: number } | null>(null);
|
||||
const [codeErr, setCodeErr] = useState<string | null>(null);
|
||||
const [, force] = useState(0);
|
||||
const [checking, setChecking] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!locked) return;
|
||||
const t = window.setInterval(() => force((n) => n + 1), 15000);
|
||||
return () => window.clearInterval(t);
|
||||
}, [locked]);
|
||||
|
||||
const notRegistered = device && !device.registered;
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{locked && device && (
|
||||
<motion.div
|
||||
key="lock"
|
||||
className="lock"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0, transition: { duration: 0.6, delay: 0.25 } }}
|
||||
role="alertdialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="lock-title"
|
||||
>
|
||||
<div className="lock-veil" />
|
||||
<motion.div
|
||||
className="lock-box"
|
||||
initial={{ opacity: 0, y: 24, scale: 0.97 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1, transition: { duration: 0.35 } }}
|
||||
exit={{ opacity: 0, scale: 1.08, y: -10, filter: 'blur(6px)', transition: { duration: 0.5, ease: [0.4, 0, 0.2, 1] } }}
|
||||
>
|
||||
<div className="lock-ic">
|
||||
<IPlug />
|
||||
</div>
|
||||
<div className="t h" id="lock-title">
|
||||
{notRegistered ? '등록된 게임 PC가 없습니다' : '게임 PC 프로그램과 연결이 끊어졌습니다'}
|
||||
</div>
|
||||
<div className="d">
|
||||
기록은 게임 PC에만 저장되어 있어서, 프로그램이 켜져 있을 때만 볼 수 있어요.
|
||||
<br />
|
||||
{notRegistered ? '게임 PC에서 겜녹이 프로그램을 등록하면 자동으로 열립니다.' : '프로그램이 다시 연결되면 자동으로 열립니다.'}
|
||||
</div>
|
||||
<div className="st">
|
||||
<div>
|
||||
<span className="muted">사이트 서버</span>
|
||||
{serverOk === false ? <span className="c-r">● 응답 없음</span> : <span className="c-g">● 정상</span>}
|
||||
</div>
|
||||
<div>
|
||||
<span className="muted">등록된 게임 PC</span>
|
||||
<span>
|
||||
{device.name ?? '없음'} {device.version && <span className="dim">(v{device.version})</span>}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="muted">프로그램 상태</span>
|
||||
<span className="c-r">
|
||||
● {notRegistered ? '등록 안 됨' : '연결 해제됨'}
|
||||
{device.lastSeen ? ` · 마지막 응답 ${fmtWhen(device.lastSeen)} (${fmtAgo(device.lastSeen)})` : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="muted">다시 확인</span>
|
||||
<span className="c-y">
|
||||
5초마다 자동 확인 중
|
||||
<span className="dots">
|
||||
<i />
|
||||
<i />
|
||||
<i />
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{isOwner && (
|
||||
<div className="lock-reg">
|
||||
{code ? (
|
||||
<div>
|
||||
게임 PC 겜녹이 설정 → <b>저장 · 사이트</b> 탭에 이 코드를 입력하세요
|
||||
<div className="lock-code">{code.code}</div>
|
||||
<span className="dim">{fmtWhen(code.expiresAt)}까지 유효 · 한 번만 쓸 수 있음</span>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
className="btn"
|
||||
onClick={async () => {
|
||||
sfx('click');
|
||||
setCodeErr(null);
|
||||
try {
|
||||
setCode(await api.registrationCode());
|
||||
} catch {
|
||||
setCodeErr('코드를 만들지 못했습니다');
|
||||
}
|
||||
}}
|
||||
>
|
||||
🔑 {notRegistered ? '게임 PC 등록 코드 만들기' : '게임 PC 다시 등록 (새 코드)'}
|
||||
</button>
|
||||
)}
|
||||
{codeErr && <div className="c-r">{codeErr}</div>}
|
||||
</div>
|
||||
)}
|
||||
<div className="lock-btns">
|
||||
<button
|
||||
className="btn"
|
||||
disabled={checking}
|
||||
onClick={async () => {
|
||||
sfx('click');
|
||||
setChecking(true);
|
||||
await recheck();
|
||||
window.setTimeout(() => setChecking(false), 600);
|
||||
}}
|
||||
>
|
||||
↻ {checking ? '확인 중…' : '지금 다시 확인'}
|
||||
</button>
|
||||
<button className="btn" onClick={logout}>
|
||||
로그아웃
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
79
site/web/src/components/LoginPage.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import { motion } from 'framer-motion';
|
||||
import { IDiscord } from './Icons';
|
||||
|
||||
/** 블러 처리된 가짜 화면 (로그인 뒤 배경) */
|
||||
function FakeBackdrop() {
|
||||
return (
|
||||
<div className="login-bg" aria-hidden>
|
||||
<div className="fb-top" />
|
||||
<div className="fb-main">
|
||||
<div className="fb-side">
|
||||
{Array.from({ length: 5 }, (_, i) => (
|
||||
<i key={i} style={{ background: ['#3987e5', '#e5743f', '#1fb383', '#9085e9', '#c98500'][i] }} />
|
||||
))}
|
||||
</div>
|
||||
<div className="fb-list">
|
||||
{Array.from({ length: 9 }, (_, i) => (
|
||||
<div key={i} className={i === 3 ? 'hot' : ''}>
|
||||
<b />
|
||||
<span style={{ width: `${40 + ((i * 37) % 45)}%` }} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="fb-right">
|
||||
<div />
|
||||
<div />
|
||||
</div>
|
||||
</div>
|
||||
<div className="fb-foot" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginPage({ notMember = false, error }: { notMember?: boolean; error?: string }) {
|
||||
return (
|
||||
<div className="login">
|
||||
<FakeBackdrop />
|
||||
<div className="login-veil" />
|
||||
<motion.div className="login-box" initial={{ opacity: 0, y: 18 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.45, ease: [0.2, 0.8, 0.2, 1] }}>
|
||||
<picture>
|
||||
<source srcSet="/banner.webp" type="image/webp" />
|
||||
<img className="ban" src="/banner.png" alt="겜녹이 Game Voice Recorder" />
|
||||
</picture>
|
||||
<div className="in">
|
||||
{notMember ? (
|
||||
<>
|
||||
<div className="t h">들어올 수 없는 계정입니다</div>
|
||||
<div className="nm-warn">M&L 서버 멤버만 들어올 수 있습니다</div>
|
||||
<div className="d">겜녹이 봇이 있는 디스코드 서버(M&L)에 참여한 계정으로 다시 로그인해 주세요.</div>
|
||||
<a className="dc" href="/auth/discord">
|
||||
<IDiscord />
|
||||
다른 계정으로 로그인
|
||||
</a>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="t h">디스코드 계정으로 로그인</div>
|
||||
{error && <div className="nm-warn">{error}</div>}
|
||||
<div className="d">
|
||||
겜녹이 봇이 있는 디스코드 서버(M&L)의 멤버만 들어올 수 있어요.
|
||||
<br />
|
||||
로그인하면 녹음된 대화와 경기 기록을 볼 수 있습니다.
|
||||
</div>
|
||||
<a className="dc" href="/auth/discord">
|
||||
<IDiscord />
|
||||
Discord로 로그인
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
<div className="st">
|
||||
<span>
|
||||
<span className="c-g">●</span> 사이트 서버 정상
|
||||
</span>
|
||||
<span>🔒 HTTPS · gvr.tkrmagid.kr</span>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
162
site/web/src/components/PlayerBar.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import { useEffect, useMemo, useRef, type MouseEvent } from 'react';
|
||||
import WaveSurfer from 'wavesurfer.js';
|
||||
import { player, usePlayer, type SceneInfo } from '../store/player';
|
||||
import { settings, useSettings } from '../store/settings';
|
||||
import { useData } from '../store/app';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { fmtClock, fmtSec } from '../lib/format';
|
||||
import { Avatar } from './common';
|
||||
import { IClose, ILoop, INext, IPause, IPlay, IPrev, IVolume } from './Icons';
|
||||
|
||||
const RATES = [1, 1.25, 1.5, 2];
|
||||
|
||||
function SceneLanes({ scene }: { scene: SceneInfo }) {
|
||||
const { userById } = useData();
|
||||
const ts = usePlayer((s) => s.sceneTs);
|
||||
const lanes = useMemo(() => [...new Set(scene.items.map((i) => i.userId))], [scene]);
|
||||
const span = Math.max(1, scene.end - scene.start);
|
||||
const seek = (e: MouseEvent<HTMLDivElement>) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
player.seekScene(((e.clientX - r.left) / r.width) * span);
|
||||
};
|
||||
const pos = ts == null ? 0 : Math.min(1, Math.max(0, (ts - scene.start) / span));
|
||||
return (
|
||||
<div className="lanes" onClick={seek} title="눌러서 이동">
|
||||
{lanes.map((uid) => {
|
||||
const u = userById(uid);
|
||||
return (
|
||||
<div className="lane" key={uid}>
|
||||
<span className="lane-nm" style={{ color: u?.color }}>
|
||||
{u?.name ?? '?'}
|
||||
</span>
|
||||
<div className="lane-track">
|
||||
{scene.items
|
||||
.filter((i) => i.userId === uid)
|
||||
.map((i) => {
|
||||
const on = ts != null && ts >= i.ts && ts <= i.endTs;
|
||||
return (
|
||||
<i
|
||||
key={i.id}
|
||||
className={on ? 'on' : ''}
|
||||
style={{ left: `${((i.ts - scene.start) / span) * 100}%`, width: `${Math.max(0.4, ((i.endTs - i.ts) / span) * 100)}%`, background: u?.color ?? '#5b6b7b' }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="lane-cursor" style={{ left: `calc(64px + (100% - 64px) * ${pos})` }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlayerBar() {
|
||||
const s = usePlayer((x) => x);
|
||||
const cfg = useSettings();
|
||||
const { userById } = useData();
|
||||
const waveRef = useRef<HTMLDivElement>(null);
|
||||
const wsRef = useRef<WaveSurfer | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!waveRef.current) return;
|
||||
const mobile = window.matchMedia('(max-width: 720px)').matches;
|
||||
const ws = WaveSurfer.create({
|
||||
container: waveRef.current,
|
||||
media: player.el,
|
||||
height: mobile ? 30 : 52,
|
||||
waveColor: '#33495e',
|
||||
progressColor: '#ff4655',
|
||||
cursorColor: '#ffffff',
|
||||
cursorWidth: 2,
|
||||
barWidth: 3,
|
||||
barGap: 3,
|
||||
barRadius: 2,
|
||||
normalize: true,
|
||||
interact: true,
|
||||
dragToSeek: true,
|
||||
});
|
||||
wsRef.current = ws;
|
||||
player.attachWave(ws);
|
||||
return () => {
|
||||
player.attachWave(null);
|
||||
ws.destroy();
|
||||
wsRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const lol = s.item?.game?.type === 'lol';
|
||||
useEffect(() => {
|
||||
wsRef.current?.setOptions({ progressColor: lol ? '#c8aa6e' : '#ff4655' });
|
||||
}, [lol]);
|
||||
|
||||
const user = userById(s.item?.userId);
|
||||
const idle = s.mode === 'idle';
|
||||
const scene = s.mode === 'scene' ? s.scene : null;
|
||||
const click = (fn: () => void) => () => {
|
||||
sfx('click');
|
||||
fn();
|
||||
};
|
||||
|
||||
return (
|
||||
<footer className={`playerbar${lol ? ' lol' : ''}${idle ? ' idle' : ''}`} aria-label="플레이어">
|
||||
<button className="pb-skip" onClick={() => player.prev()} title="이전 발화 (←)" aria-label="이전 발화">
|
||||
<IPrev width={20} height={20} />
|
||||
</button>
|
||||
<button className="ctrl" onClick={() => player.toggle()} title="재생/일시정지 (Space)" aria-label={s.playing ? '일시정지' : '재생'}>
|
||||
{s.playing ? <IPause width={20} height={20} /> : <IPlay width={20} height={20} style={{ marginLeft: 3 }} />}
|
||||
</button>
|
||||
<button className="pb-skip" onClick={() => player.next()} title="다음 발화 (→)" aria-label="다음 발화">
|
||||
<INext width={20} height={20} />
|
||||
</button>
|
||||
<span className="mono muted pb-time">
|
||||
{scene ? `${fmtClock(s.time * 1000)} / ${fmtClock(s.duration * 1000)}` : `${fmtSec(s.time)} / ${fmtSec(s.duration)}`}
|
||||
</span>
|
||||
<div className="pb-now">
|
||||
{scene ? (
|
||||
<>
|
||||
<span className="scene-tag">현장 모드</span>
|
||||
<span className="pb-now-txt">
|
||||
<b>{scene.label}</b>
|
||||
<small>{scene.items.length}개 발화 겹쳐 듣기</small>
|
||||
</span>
|
||||
</>
|
||||
) : s.item ? (
|
||||
<>
|
||||
<Avatar user={user} size={30} />
|
||||
<span className="pb-now-txt">
|
||||
<b style={{ color: user?.color }}>{user?.name ?? '알 수 없음'}</b>
|
||||
<small className="mono">{s.item.time.primary}</small>
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="pb-hint">발화를 누르면 여기서 재생됩니다 · Space · ←/→</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="wave-box">
|
||||
<div ref={waveRef} className="wave" style={{ display: scene || s.message || idle ? 'none' : undefined }} />
|
||||
{scene && <SceneLanes scene={scene} />}
|
||||
{!scene && s.message && <div className="pb-msg">🗑 {s.message}</div>}
|
||||
{idle && !s.message && <div className="wave-empty" />}
|
||||
</div>
|
||||
<button className={`chip${cfg.continuous ? ' on' : ''}`} onClick={click(() => settings.set({ continuous: !cfg.continuous }))} title="끝나면 다음 발화로 자동으로 넘어갑니다">
|
||||
<ILoop width={14} height={14} /> 이어듣기
|
||||
</button>
|
||||
<button className="chip mono" onClick={click(() => settings.set({ rate: RATES[(RATES.indexOf(cfg.rate) + 1) % RATES.length] }))} title="재생 속도">
|
||||
{cfg.rate}x
|
||||
</button>
|
||||
<button
|
||||
className={`chip${cfg.normalize ? ' on-mint' : ''}`}
|
||||
onClick={click(() => settings.set({ normalize: !cfg.normalize }))}
|
||||
title={s.item?.audio ? `보정 게인 ${s.item.audio.gainDb > 0 ? '+' : ''}${s.item.audio.gainDb.toFixed(1)} dB` : '사람마다 다른 마이크 음량을 재생할 때 맞춥니다'}
|
||||
>
|
||||
<IVolume width={14} height={14} /> 보정 음량
|
||||
</button>
|
||||
{!idle && (
|
||||
<button className="icon-btn pb-close" onClick={click(() => player.stop())} title="닫기" aria-label="플레이어 닫기">
|
||||
<IClose width={16} height={16} />
|
||||
</button>
|
||||
)}
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
33
site/web/src/components/TalkBars.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useMemo } from 'react';
|
||||
import type { UtteranceItem } from '@gvr/shared';
|
||||
import { useData } from '../store/app';
|
||||
import { fmtDuration } from '../lib/format';
|
||||
|
||||
export function TalkBars({ utts }: { utts: UtteranceItem[] }) {
|
||||
const { userById } = useData();
|
||||
const rows = useMemo(() => {
|
||||
const m = new Map<string, number>();
|
||||
for (const u of utts) if (!u.noise) m.set(u.userId, (m.get(u.userId) ?? 0) + (u.endTs - u.ts));
|
||||
return [...m].sort((a, b) => b[1] - a[1]);
|
||||
}, [utts]);
|
||||
const max = rows[0]?.[1] ?? 1;
|
||||
if (!rows.length) return <div className="dim small">아직 발화가 없습니다</div>;
|
||||
return (
|
||||
<div className="talkbars">
|
||||
{rows.map(([uid, ms]) => {
|
||||
const u = userById(uid);
|
||||
return (
|
||||
<div key={uid} className="tb-row" data-tip={`${u?.name ?? '?'} · ${fmtDuration(ms)}`}>
|
||||
<div className="kv">
|
||||
<span>{u?.name ?? '알 수 없음'}</span>
|
||||
<span className="mono">{fmtDuration(ms)}</span>
|
||||
</div>
|
||||
<div className="bar">
|
||||
<i style={{ width: `${(ms / max) * 100}%`, background: u?.color ?? '#5b6b7b' }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
64
site/web/src/components/TimelineRows.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import { Fragment } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { MatchSummary, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { UtteranceRow } from './UtteranceRow';
|
||||
import { EventRow } from './EventRow';
|
||||
import { itemMatch } from '../lib/game';
|
||||
import { fmtWhen } from '../lib/format';
|
||||
import { useReducedMotion } from '../store/settings';
|
||||
|
||||
/** 경기가 바뀌는 지점에 넣는 맥락 구분선 */
|
||||
function ContextDivider({ m, matchId }: { m?: MatchSummary; matchId: string | null }) {
|
||||
if (!matchId)
|
||||
return (
|
||||
<div className="div ctx">
|
||||
<span>경기 밖 · 현실 시간</span>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className={`div ctx g-${m?.game ?? 'valorant'}`}>
|
||||
<span className="pill">{m?.game === 'lol' ? 'LoL' : 'VALORANT'}</span>
|
||||
<span>{m ? `${m.map.name} · ${m.mode} · ${fmtWhen(m.startedAt)} 시작` : '경기'}</span>
|
||||
{m?.score && <span className="score mono">{`${m.score.ally} : ${m.score.enemy}`}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TimelineRows({
|
||||
items,
|
||||
matches,
|
||||
newIds,
|
||||
onUpdate,
|
||||
}: {
|
||||
items: TimelineItem[];
|
||||
matches: Map<string, MatchSummary>;
|
||||
newIds: Set<string>;
|
||||
onUpdate: (it: UtteranceItem) => void;
|
||||
}) {
|
||||
const reduce = useReducedMotion();
|
||||
let prevMatch: string | null | undefined = undefined;
|
||||
return (
|
||||
<>
|
||||
{items.map((it) => {
|
||||
const mid = itemMatch(it);
|
||||
const divider = mid !== prevMatch ? <ContextDivider m={mid ? matches.get(mid) : undefined} matchId={mid} /> : null;
|
||||
prevMatch = mid;
|
||||
const row = it.kind === 'utterance' ? <UtteranceRow item={it} onUpdate={onUpdate} /> : <EventRow e={it} />;
|
||||
const isNew = newIds.has(it.id);
|
||||
return (
|
||||
<Fragment key={it.id}>
|
||||
{divider}
|
||||
<motion.div
|
||||
className={`row-wrap${isNew ? ' is-new' : ''}`}
|
||||
initial={isNew && !reduce ? { opacity: 0, x: -24, height: 0 } : false}
|
||||
animate={{ opacity: 1, x: 0, height: 'auto' }}
|
||||
transition={{ duration: 0.45, ease: [0.2, 0.8, 0.2, 1] }}
|
||||
>
|
||||
{row}
|
||||
</motion.div>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
222
site/web/src/components/UtteranceRow.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
import { memo, useEffect, useRef, useState, type MouseEvent } from 'react';
|
||||
import type { UtteranceItem, Word } from '@gvr/shared';
|
||||
import { player, useIsActive, useLocalTime, usePlayer } from '../store/player';
|
||||
import { useData } from '../store/app';
|
||||
import { api } from '../lib/api';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { realTip } from '../lib/format';
|
||||
import { Avatar, TimeCell } from './common';
|
||||
import { IEdit } from './Icons';
|
||||
|
||||
const STATUS: Record<UtteranceItem['status'], [string, string]> = {
|
||||
realtime: ['실시간', 'st-rt'],
|
||||
precise: ['정밀', 'st-pr'],
|
||||
pending: ['처리 중', 'st-pd'],
|
||||
failed: ['인식 실패', 'st-fail'],
|
||||
};
|
||||
|
||||
export function MiniWave({ n = 5, live = false }: { n?: number; live?: boolean }) {
|
||||
const hs = [6, 12, 5, 9, 4, 11, 7, 13, 5, 8, 10, 6, 12, 4, 9, 7];
|
||||
return (
|
||||
<span className={`mini-wave${live ? ' live' : ''}`} aria-hidden>
|
||||
{Array.from({ length: n }, (_, i) => (
|
||||
<i key={i} style={{ height: hs[i % hs.length], animationDelay: `${(i * 0.09).toFixed(2)}s` }} />
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function wordClick(e: MouseEvent, item: UtteranceItem, w: Word) {
|
||||
e.stopPropagation();
|
||||
player.seekTo(item, w.s);
|
||||
}
|
||||
|
||||
/** 재생 중인 발화: 재생 위치에 따라 단어 강조 (이 컴포넌트만 매 프레임 갱신) */
|
||||
function ActiveWords({ item }: { item: UtteranceItem }) {
|
||||
const t = useLocalTime(item.ts);
|
||||
return (
|
||||
<>
|
||||
{item.words.map((w, i) => {
|
||||
const cls = t < 0 ? '' : t >= w.e ? 'done' : t >= w.s ? 'now' : 'todo';
|
||||
return (
|
||||
<span key={i}>
|
||||
<span className={`w ${cls}`} onClick={(e) => wordClick(e, item, w)}>
|
||||
{w.w}
|
||||
</span>{' '}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Text({ item, active }: { item: UtteranceItem; active: boolean }) {
|
||||
if (item.noise)
|
||||
return (
|
||||
<span className="noise">
|
||||
[잡음] <MiniWave />
|
||||
</span>
|
||||
);
|
||||
if (item.status === 'pending' && !item.text)
|
||||
return (
|
||||
<span className="pending">
|
||||
<MiniWave n={16} live /> <span className="dim">음성 인식 중…</span>
|
||||
</span>
|
||||
);
|
||||
if (!item.text) return <span className="dim">{item.status === 'failed' ? '(인식하지 못함)' : '(내용 없음)'}</span>;
|
||||
if (!item.words.length) return <>{item.text}</>;
|
||||
if (active) return <ActiveWords item={item} />;
|
||||
return (
|
||||
<>
|
||||
{item.words.map((w, i) => (
|
||||
<span key={i}>
|
||||
<span className="w" onClick={(e) => wordClick(e, item, w)}>
|
||||
{w.w}
|
||||
</span>{' '}
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Editor({ item, onDone }: { item: UtteranceItem; onDone: (it?: UtteranceItem) => void }) {
|
||||
const [text, setText] = useState(item.text ?? '');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const ref = useRef<HTMLInputElement>(null);
|
||||
useEffect(() => {
|
||||
ref.current?.focus();
|
||||
ref.current?.select();
|
||||
}, []);
|
||||
const save = async () => {
|
||||
const v = text.trim();
|
||||
if (!v || v === item.text) return onDone();
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
try {
|
||||
const it = await api.correct(item.id, v);
|
||||
sfx('click');
|
||||
onDone(it);
|
||||
} catch {
|
||||
setErr('저장하지 못했습니다');
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="editor" onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
ref={ref}
|
||||
value={text}
|
||||
disabled={busy}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void save();
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
onDone();
|
||||
}
|
||||
}}
|
||||
aria-label="발화 텍스트 교정"
|
||||
/>
|
||||
<button className="btn primary sm" disabled={busy} onClick={() => void save()}>
|
||||
저장
|
||||
</button>
|
||||
<button className="btn sm" disabled={busy} onClick={() => onDone()}>
|
||||
취소
|
||||
</button>
|
||||
{err && <span className="err">{err}</span>}
|
||||
<div className="hint">고친 문장은 교정 사전과 학습 데이터에 반영됩니다 · Enter 저장 · Esc 취소</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface Props {
|
||||
item: UtteranceItem;
|
||||
variant?: 'full' | 'compact';
|
||||
/** compact 에서 시간 칸에 쓸 라벨 (예: 라운드 시간만) */
|
||||
timeText?: string;
|
||||
sub?: string;
|
||||
onUpdate?: (it: UtteranceItem) => void;
|
||||
}
|
||||
|
||||
export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full', timeText, sub, onUpdate }: Props) {
|
||||
const { userById } = useData();
|
||||
const user = userById(item.userId);
|
||||
const active = useIsActive(item);
|
||||
const playing = usePlayer((s) => active && s.playing);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [st, stCls] = STATUS[item.status];
|
||||
|
||||
const click = () => {
|
||||
if (editing) return;
|
||||
if (active && player.state.mode === 'single') player.toggle();
|
||||
else void player.play(item);
|
||||
};
|
||||
const edit = (e: MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
sfx('click');
|
||||
setEditing(true);
|
||||
};
|
||||
const done = (it?: UtteranceItem) => {
|
||||
setEditing(false);
|
||||
if (it) onUpdate?.(it);
|
||||
};
|
||||
|
||||
const badges = (
|
||||
<>
|
||||
{(item.status !== 'precise' || variant === 'full') && <span className={`sbadge ${stCls}`}>{st}</span>}
|
||||
{item.corrected && <span className="sbadge st-fix">교정됨</span>}
|
||||
{!item.audio && <span className="sbadge st-del" title="음성 보관 기간(7일)이 지나 삭제됨">음성 삭제됨</span>}
|
||||
{active && <span className="playing-tag">{playing ? '▶ 재생 중' : '❚❚ 일시정지'}</span>}
|
||||
</>
|
||||
);
|
||||
const editBtn = !item.noise && item.status !== 'pending' && onUpdate && (
|
||||
<button className="icon-btn edit-btn" title="텍스트 교정" aria-label="텍스트 교정" onClick={edit}>
|
||||
<IEdit width={15} height={15} />
|
||||
</button>
|
||||
);
|
||||
|
||||
if (variant === 'compact') {
|
||||
return (
|
||||
<div className={`l utt${active ? ' cur' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} data-id={item.id}>
|
||||
<span className="t mono" data-tip={realTip(item.ts)}>
|
||||
{timeText ?? item.time.primary}
|
||||
</span>
|
||||
<div className="lb">
|
||||
<b style={{ color: user?.color }}>{user?.name ?? '알 수 없음'}</b>
|
||||
{sub && <span className="dim sub"> · {sub}</span>} {badges}
|
||||
{editing ? (
|
||||
<Editor item={item} onDone={done} />
|
||||
) : (
|
||||
<div className="txt">
|
||||
<Text item={item} active={active} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!editing && editBtn}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`it utt${active ? ' playing' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} data-id={item.id}>
|
||||
<TimeCell time={item.time} real={!item.game} />
|
||||
<Avatar user={user} size={30} />
|
||||
<div className="body">
|
||||
<div className="who">
|
||||
<span style={{ color: user?.color ?? '#8696a6' }}>{user?.name ?? '알 수 없음'}</span>
|
||||
{sub && <span className="dim sub">· {sub}</span>}
|
||||
{badges}
|
||||
</div>
|
||||
{editing ? (
|
||||
<Editor item={item} onDone={done} />
|
||||
) : (
|
||||
<div className="txt">
|
||||
<Text item={item} active={active} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!editing && editBtn}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
105
site/web/src/components/common.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import type { PlayerRef, TimeLabel, User } from '@gvr/shared';
|
||||
import { useData } from '../store/app';
|
||||
import { realTip } from '../lib/format';
|
||||
|
||||
export function Brand({ compact = false }: { compact?: boolean }) {
|
||||
return (
|
||||
<div className={`brand${compact ? ' compact' : ''}`}>
|
||||
<img src="/icon-192.png" alt="" />
|
||||
<div>
|
||||
<div className="nm">겜녹이</div>
|
||||
{!compact && <div className="en">GAME VOICE RECORDER</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Avatar({ user, size = 28, name, color, src }: { user?: User | null; size?: number; name?: string; color?: string; src?: string | null }) {
|
||||
const nm = user?.name ?? name ?? '?';
|
||||
const bg = user?.color ?? color ?? '#3a4654';
|
||||
const img = user?.avatar ?? src;
|
||||
const style: CSSProperties = { width: size, height: size, fontSize: Math.round(size * 0.42), background: bg };
|
||||
return (
|
||||
<span className="av" style={style} title={nm}>
|
||||
{img ? <img src={img} alt="" /> : nm.slice(0, 1)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** 요원 · 챔피언 아이콘. icon 이 null 이면 이름 첫 글자 */
|
||||
export function CharIcon({ c, size = 24, className = '' }: { c?: { name: string; icon: string | null } | null; size?: number; className?: string }) {
|
||||
if (!c) return null;
|
||||
const style: CSSProperties = { width: size, height: size };
|
||||
return c.icon ? (
|
||||
<img className={`ag ${className}`} src={c.icon} alt={c.name} title={c.name} style={style} loading="lazy" />
|
||||
) : (
|
||||
<span className={`ag ag-fallback ${className}`} style={{ ...style, fontSize: Math.round(size * 0.45) }} title={c.name}>
|
||||
{c.name.slice(0, 1)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** 플레이어 이름: 디스코드 유저와 연결돼 있으면 유저 색 */
|
||||
export function PName({ p, strong = true }: { p: PlayerRef | null | undefined; strong?: boolean }) {
|
||||
const { userById } = useData();
|
||||
if (!p) return <span className="dim">?</span>;
|
||||
const u = userById(p.userId);
|
||||
const Tag = strong ? 'b' : 'span';
|
||||
return <Tag style={u ? { color: u.color } : undefined}>{u?.name ?? p.name}</Tag>;
|
||||
}
|
||||
|
||||
export function UserName({ id, fallback = '알 수 없음' }: { id: string | undefined; fallback?: string }) {
|
||||
const { userById } = useData();
|
||||
const u = userById(id);
|
||||
return <b style={{ color: u?.color ?? '#8696a6' }}>{u?.name ?? fallback}</b>;
|
||||
}
|
||||
|
||||
/** 시간 칸: 주 표시 + 보조 표시, 마우스를 올리면 현실 시간 */
|
||||
export function TimeCell({ time, real = false, className = '' }: { time: TimeLabel; real?: boolean; className?: string }) {
|
||||
return (
|
||||
<div className={`time mono ${real ? 'real' : ''} ${className}`} data-tip={realTip(time.real)}>
|
||||
{time.primary}
|
||||
<small>{time.secondary ?? (real ? '현실 시간' : '')}</small>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Panel({ title, right, children, className = '' }: { title: ReactNode; right?: ReactNode; children: ReactNode; className?: string }) {
|
||||
return (
|
||||
<section className={`panel ${className}`}>
|
||||
<h4>
|
||||
<span>{title}</span>
|
||||
{right && <span className="ph-right">{right}</span>}
|
||||
</h4>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function Spinner({ label = '불러오는 중' }: { label?: string }) {
|
||||
return (
|
||||
<div className="spinner" role="status">
|
||||
<i />
|
||||
<i />
|
||||
<i />
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBox({ error, onRetry }: { error: unknown; onRetry?: () => void }) {
|
||||
const code = (error as { code?: string; status?: number })?.code;
|
||||
const status = (error as { status?: number })?.status;
|
||||
const msg = code === 'device_offline' ? '게임 PC와 연결이 끊어져 있습니다' : status === 404 ? '찾을 수 없습니다' : code === 'network' ? '네트워크 오류' : '불러오지 못했습니다';
|
||||
return (
|
||||
<div className="errbox">
|
||||
<span>{msg}</span>
|
||||
{onRetry && (
|
||||
<button className="btn" onClick={onRetry}>
|
||||
다시 시도
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
123
site/web/src/lib/api.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
import type {
|
||||
DeviceStatus,
|
||||
MatchDetail,
|
||||
MatchSummary,
|
||||
Overview,
|
||||
TimelinePage,
|
||||
UserProfile,
|
||||
User,
|
||||
UtteranceItem,
|
||||
GameType,
|
||||
} from '@gvr/shared';
|
||||
|
||||
/** 전역 신호: 401 → 로그인 화면, 503 device_offline → 잠금 화면 */
|
||||
type Signal = 'unauthorized' | 'not_member' | 'device_offline';
|
||||
const listeners = new Set<(s: Signal) => void>();
|
||||
export function onApiSignal(fn: (s: Signal) => void): () => void {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
}
|
||||
const emit = (s: Signal) => listeners.forEach((fn) => fn(s));
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public code: string,
|
||||
) {
|
||||
super(`${status} ${code}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(path, {
|
||||
credentials: 'include',
|
||||
...init,
|
||||
headers: { accept: 'application/json', ...(init.body ? { 'content-type': 'application/json' } : {}), ...init.headers },
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, 'network');
|
||||
}
|
||||
if (res.ok) {
|
||||
if (res.status === 204) return undefined as T;
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
let code = 'error';
|
||||
try {
|
||||
code = ((await res.json()) as { error?: string }).error ?? code;
|
||||
} catch {
|
||||
/* 본문 없음 */
|
||||
}
|
||||
if (res.status === 401) emit('unauthorized');
|
||||
else if (res.status === 403 && code === 'not_member') emit('not_member');
|
||||
else if (res.status === 503 && code === 'device_offline') emit('device_offline');
|
||||
throw new ApiError(res.status, code);
|
||||
}
|
||||
|
||||
export interface Me {
|
||||
user: { id: string; name: string; avatar: string | null };
|
||||
isOwner: boolean;
|
||||
}
|
||||
export interface StatusResponse {
|
||||
device: DeviceStatus;
|
||||
server: { version: string };
|
||||
}
|
||||
|
||||
export interface TimelineQuery {
|
||||
users?: string[];
|
||||
game?: GameType | 'none';
|
||||
match?: string;
|
||||
from?: number;
|
||||
to?: number;
|
||||
q?: string;
|
||||
types?: string[];
|
||||
hideNoise?: boolean;
|
||||
cursor?: string | null;
|
||||
limit?: number;
|
||||
order?: 'asc' | 'desc';
|
||||
}
|
||||
|
||||
function qs(o: Record<string, string | number | undefined | null>): string {
|
||||
const p = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(o)) if (v !== undefined && v !== null && v !== '') p.set(k, String(v));
|
||||
const s = p.toString();
|
||||
return s ? `?${s}` : '';
|
||||
}
|
||||
|
||||
export const api = {
|
||||
/** /auth/me 는 401/403 을 신호로 돌리지 않고 호출자가 직접 처리한다 */
|
||||
async me(): Promise<{ ok: true; me: Me } | { ok: false; reason: 'anon' | 'not_member' }> {
|
||||
const res = await fetch('/auth/me', { credentials: 'include', headers: { accept: 'application/json' } });
|
||||
if (res.ok) return { ok: true, me: (await res.json()) as Me };
|
||||
if (res.status === 403) return { ok: false, reason: 'not_member' };
|
||||
return { ok: false, reason: 'anon' };
|
||||
},
|
||||
logout: () => fetch('/auth/logout', { method: 'POST', credentials: 'include' }),
|
||||
/** 관리자(OWNER_DISCORD_IDS) 전용: 게임 PC 1회용 등록 코드 (10분) */
|
||||
registrationCode: () => request<{ code: string; expiresAt: number }>('/admin/registration-code', { method: 'POST' }),
|
||||
status: () => request<StatusResponse>('/api/status'),
|
||||
overview: () => request<Overview>('/api/overview'),
|
||||
users: () => request<User[]>('/api/users'),
|
||||
user: (id: string) => request<UserProfile>(`/api/users/${encodeURIComponent(id)}`),
|
||||
timeline: (q: TimelineQuery) =>
|
||||
request<TimelinePage>(
|
||||
`/api/timeline${qs({
|
||||
users: q.users?.length ? q.users.join(',') : undefined,
|
||||
game: q.game,
|
||||
match: q.match,
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
q: q.q,
|
||||
types: q.types?.length ? q.types.join(',') : undefined,
|
||||
hideNoise: q.hideNoise ? 1 : undefined,
|
||||
cursor: q.cursor,
|
||||
limit: q.limit ?? 100,
|
||||
order: q.order,
|
||||
})}`,
|
||||
),
|
||||
matches: (o: { game?: GameType; limit?: number; before?: number } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
|
||||
match: (id: string) => request<MatchDetail>(`/api/matches/${encodeURIComponent(id)}`),
|
||||
correct: (id: string, text: string) =>
|
||||
request<UtteranceItem>(`/api/utterances/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ text }) }),
|
||||
};
|
||||
38
site/web/src/lib/audio.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
/** 공용 AudioContext 와 출력 체인 (플레이어 + 효과음) */
|
||||
let ctx: AudioContext | null = null;
|
||||
let playerBus: GainNode | null = null;
|
||||
let sfxBus: GainNode | null = null;
|
||||
|
||||
export function audioCtx(): AudioContext {
|
||||
if (!ctx) {
|
||||
ctx = new AudioContext({ latencyHint: 'interactive' });
|
||||
// 플레이어: 발화별 게인(+최대 20dB) 뒤에 리미터를 둬서 클리핑을 막는다
|
||||
const limiter = ctx.createDynamicsCompressor();
|
||||
limiter.threshold.value = -3;
|
||||
limiter.knee.value = 2;
|
||||
limiter.ratio.value = 20;
|
||||
limiter.attack.value = 0.002;
|
||||
limiter.release.value = 0.12;
|
||||
playerBus = ctx.createGain();
|
||||
playerBus.connect(limiter).connect(ctx.destination);
|
||||
sfxBus = ctx.createGain();
|
||||
sfxBus.connect(ctx.destination);
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function resumeAudio() {
|
||||
const c = audioCtx();
|
||||
if (c.state === 'suspended') void c.resume();
|
||||
}
|
||||
|
||||
export function playerOutput(): GainNode {
|
||||
audioCtx();
|
||||
return playerBus!;
|
||||
}
|
||||
export function sfxOutput(): GainNode {
|
||||
audioCtx();
|
||||
return sfxBus!;
|
||||
}
|
||||
|
||||
export const dbToGain = (db: number) => Math.pow(10, db / 20);
|
||||
86
site/web/src/lib/filters.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import type { GameType, TimelineItem } from '@gvr/shared';
|
||||
import type { TimelineQuery } from './api';
|
||||
import { itemGame, itemMatch, typeGroup, type TypeGroup } from './game';
|
||||
|
||||
/** URL 쿼리에 남기는 타임라인 필터 (공유 가능한 링크) */
|
||||
export interface Filters {
|
||||
users: string[];
|
||||
game: GameType | 'none' | null;
|
||||
match: string | null;
|
||||
from: number | undefined;
|
||||
to: number | undefined;
|
||||
q: string;
|
||||
types: TypeGroup[];
|
||||
hideNoise: boolean;
|
||||
order: 'asc' | 'desc' | null;
|
||||
}
|
||||
|
||||
const num = (v: string | null) => (v && !isNaN(Number(v)) ? Number(v) : undefined);
|
||||
|
||||
export function parseFilters(p: URLSearchParams): Filters {
|
||||
const game = p.get('game');
|
||||
const order = p.get('order');
|
||||
return {
|
||||
users: p.get('users')?.split(',').filter(Boolean) ?? [],
|
||||
game: game === 'valorant' || game === 'lol' || game === 'none' ? game : null,
|
||||
match: p.get('match') || null,
|
||||
from: num(p.get('from')),
|
||||
to: num(p.get('to')),
|
||||
q: p.get('q') ?? '',
|
||||
types: (p.get('types')?.split(',').filter(Boolean) ?? []) as TypeGroup[],
|
||||
hideNoise: p.get('hideNoise') === '1',
|
||||
order: order === 'asc' || order === 'desc' ? order : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function writeFilters(f: Filters): URLSearchParams {
|
||||
const p = new URLSearchParams();
|
||||
if (f.users.length) p.set('users', f.users.join(','));
|
||||
if (f.game) p.set('game', f.game);
|
||||
if (f.match) p.set('match', f.match);
|
||||
if (f.from != null) p.set('from', String(f.from));
|
||||
if (f.to != null) p.set('to', String(f.to));
|
||||
if (f.q) p.set('q', f.q);
|
||||
if (f.types.length) p.set('types', f.types.join(','));
|
||||
if (f.hideNoise) p.set('hideNoise', '1');
|
||||
if (f.order) p.set('order', f.order);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** 경기 필터가 있으면 경기 기록처럼 시간순(asc), 아니면 최신순(desc) */
|
||||
export const effectiveOrder = (f: Filters): 'asc' | 'desc' => f.order ?? (f.match ? 'asc' : 'desc');
|
||||
|
||||
export function toQuery(f: Filters): TimelineQuery {
|
||||
return {
|
||||
users: f.users,
|
||||
game: f.game ?? undefined,
|
||||
match: f.match ?? undefined,
|
||||
from: f.from,
|
||||
to: f.to,
|
||||
q: f.q || undefined,
|
||||
types: f.types,
|
||||
hideNoise: f.hideNoise,
|
||||
order: effectiveOrder(f),
|
||||
};
|
||||
}
|
||||
|
||||
/** 실시간으로 들어온 항목이 지금 필터에 맞는지 (서버 필터와 같은 규칙) */
|
||||
export function matchesFilter(it: TimelineItem, f: Filters): boolean {
|
||||
if (f.from != null && it.ts < f.from) return false;
|
||||
if (f.to != null && it.ts > f.to) return false;
|
||||
const g = itemGame(it);
|
||||
if (f.game === 'none' && g) return false;
|
||||
if (f.game && f.game !== 'none' && g !== f.game) return false;
|
||||
if (f.match && itemMatch(it) !== f.match) return false;
|
||||
if (f.types.length && !f.types.includes(typeGroup(it))) return false;
|
||||
const kw = f.q.trim().toLowerCase();
|
||||
if (it.kind === 'utterance') {
|
||||
if (f.users.length && !f.users.includes(it.userId)) return false;
|
||||
if (f.hideNoise && it.noise) return false;
|
||||
if (kw && !(it.text ?? '').toLowerCase().includes(kw)) return false;
|
||||
} else {
|
||||
if (f.users.length && it.userId && !f.users.includes(it.userId)) return false;
|
||||
if (kw && !(it.type === 'chat' && String(it.data?.text ?? '').toLowerCase().includes(kw))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
71
site/web/src/lib/format.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { fmtReal } from '@gvr/shared';
|
||||
|
||||
export { fmtClock, fmtReal } from '@gvr/shared';
|
||||
|
||||
const TZ = 'Asia/Seoul';
|
||||
const dayKey = (ts: number) => new Intl.DateTimeFormat('en-CA', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' }).format(ts);
|
||||
|
||||
/** "오늘 23:41" / "어제 21:10" / "10월 7일 21:10" */
|
||||
export function fmtWhen(ts: number): string {
|
||||
const hm = new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, hour: '2-digit', minute: '2-digit', hour12: false }).format(ts);
|
||||
const k = dayKey(ts);
|
||||
if (k === dayKey(Date.now())) return `오늘 ${hm}`;
|
||||
if (k === dayKey(Date.now() - 86400000)) return `어제 ${hm}`;
|
||||
const md = new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, month: 'long', day: 'numeric' }).format(ts);
|
||||
return `${md} ${hm}`;
|
||||
}
|
||||
|
||||
export function fmtHM(ts: number): string {
|
||||
return new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, hour: '2-digit', minute: '2-digit', hour12: false }).format(ts);
|
||||
}
|
||||
|
||||
export function fmtDate(ts: number): string {
|
||||
return new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' }).format(ts).replace(/\.\s?/g, '-').replace(/-$/, '');
|
||||
}
|
||||
|
||||
/** "12분 전" */
|
||||
export function fmtAgo(ts: number, now = Date.now()): string {
|
||||
const s = Math.max(0, Math.round((now - ts) / 1000));
|
||||
if (s < 60) return '방금';
|
||||
const m = Math.round(s / 60);
|
||||
if (m < 60) return `${m}분 전`;
|
||||
const h = Math.round(m / 60);
|
||||
if (h < 24) return `${h}시간 전`;
|
||||
return `${Math.round(h / 24)}일 전`;
|
||||
}
|
||||
|
||||
/** 492000 → "8분 12초" */
|
||||
export function fmtDuration(ms: number): string {
|
||||
const s = Math.round(ms / 1000);
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
const ss = s % 60;
|
||||
if (h) return `${h}시간 ${String(m).padStart(2, '0')}분`;
|
||||
if (m) return `${m}분 ${String(ss).padStart(2, '0')}초`;
|
||||
return `${ss}초`;
|
||||
}
|
||||
|
||||
/** 초 → "0:01.4" */
|
||||
export function fmtSec(sec: number): string {
|
||||
if (!isFinite(sec) || sec < 0) sec = 0;
|
||||
const m = Math.floor(sec / 60);
|
||||
const s = sec - m * 60;
|
||||
return `${m}:${s.toFixed(1).padStart(4, '0')}`;
|
||||
}
|
||||
|
||||
export function realTip(ts: number) {
|
||||
return `현실 시간 ${fmtWhen(ts).split(' ')[0]} ${fmtReal(ts)}`;
|
||||
}
|
||||
|
||||
/** "YYYY-MM-DD" (KST) ↔ ms */
|
||||
export function dateInputValue(ms: number | undefined): string {
|
||||
if (ms == null) return '';
|
||||
return dayKey(ms);
|
||||
}
|
||||
export function dateInputToMs(v: string, end = false): number | undefined {
|
||||
if (!v) return undefined;
|
||||
const t = Date.parse(`${v}T${end ? '23:59:59.999' : '00:00:00'}+09:00`);
|
||||
return isNaN(t) ? undefined : t;
|
||||
}
|
||||
|
||||
export const k = (n: number) => (Math.abs(n) >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
|
||||
97
site/web/src/lib/game.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import type { EventItem, MatchDetail, TimelineItem } from '@gvr/shared';
|
||||
|
||||
export const ROUND_RESULT_KO: Record<string, string> = {
|
||||
Elimination: '섬멸',
|
||||
'Bomb detonated': '스파이크 폭발',
|
||||
'Bomb defused': '스파이크 해체',
|
||||
'Round timer expired': '시간 초과',
|
||||
Surrendered: '항복',
|
||||
};
|
||||
export const roundResultKo = (r: string | undefined) => (r ? ROUND_RESULT_KO[r] ?? r : '');
|
||||
|
||||
export const OBJECT_KO: Record<string, string> = {
|
||||
dragon: '드래곤',
|
||||
baron: '내셔 남작',
|
||||
herald: '협곡의 전령',
|
||||
grub: '공허 유충',
|
||||
tower: '포탑',
|
||||
inhibitor: '억제기',
|
||||
atakhan: '아타칸',
|
||||
};
|
||||
export const DRAGON_KO: Record<string, string> = {
|
||||
infernal: '화염',
|
||||
ocean: '바다',
|
||||
mountain: '대지',
|
||||
cloud: '바람',
|
||||
hextech: '마법공학',
|
||||
chemtech: '화학공학',
|
||||
elder: '장로',
|
||||
};
|
||||
export function objectName(object: string, subtype?: string) {
|
||||
if (object === 'dragon' && subtype && DRAGON_KO[subtype]) return `${DRAGON_KO[subtype]} 드래곤`;
|
||||
return OBJECT_KO[object] ?? object;
|
||||
}
|
||||
export const OBJECT_GLYPH: Record<string, string> = {
|
||||
dragon: '🐉',
|
||||
baron: '👾',
|
||||
herald: '🦀',
|
||||
grub: '🪲',
|
||||
tower: '🗼',
|
||||
inhibitor: '💠',
|
||||
atakhan: '😈',
|
||||
};
|
||||
|
||||
export const CHANNEL_KO: Record<string, string> = { team: '팀', all: '전체', party: '파티', system: '시스템' };
|
||||
export const MULTI_KO = ['', '', '더블 킬', '트리플 킬', '쿼드라 킬', '펜타 킬'];
|
||||
|
||||
/** 발로란트 게임 좌표 → 미니맵 비율 (valorant-api.com 맵 변환값) */
|
||||
export function valorantUV(t: { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }, p: { x: number; y: number }) {
|
||||
return { u: p.y * t.xMultiplier + t.xScalarToAdd, v: p.x * t.yMultiplier + t.yScalarToAdd };
|
||||
}
|
||||
/** 롤 게임 좌표 → 지도 비율 (y축 뒤집기) */
|
||||
export function lolUV(t: { minX: number; minY: number; maxX: number; maxY: number }, p: { x: number; y: number }) {
|
||||
return { u: (p.x - t.minX) / (t.maxX - t.minX), v: 1 - (p.y - t.minY) / (t.maxY - t.minY) };
|
||||
}
|
||||
export function toUV(m: MatchDetail, p: { x: number; y: number } | null | undefined): { u: number; v: number } | null {
|
||||
if (!p || !m.mapTransform) return null;
|
||||
if ('valorant' in m.mapTransform) return valorantUV(m.mapTransform.valorant, p);
|
||||
if ('lol' in m.mapTransform) return lolUV(m.mapTransform.lol, p);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 롤 오브젝트 기본 위치 (이벤트에 좌표가 없을 때) */
|
||||
export const LOL_OBJECT_POS: Record<string, { x: number; y: number }> = {
|
||||
dragon: { x: 9866, y: 4414 },
|
||||
baron: { x: 4942, y: 10395 },
|
||||
herald: { x: 4942, y: 10395 },
|
||||
grub: { x: 4942, y: 10395 },
|
||||
atakhan: { x: 7400, y: 7400 },
|
||||
};
|
||||
|
||||
/** 이벤트 종류 필터 그룹 (URL types 값) */
|
||||
export type TypeGroup = 'utterance' | 'kill' | 'chat' | 'object' | 'round';
|
||||
export const TYPE_GROUPS: { id: TypeGroup; label: string; icon: string }[] = [
|
||||
{ id: 'utterance', label: '발화', icon: '🎙' },
|
||||
{ id: 'kill', label: '킬·데스', icon: '⚔' },
|
||||
{ id: 'chat', label: '채팅', icon: '💬' },
|
||||
{ id: 'object', label: '오브젝트', icon: '🐉' },
|
||||
{ id: 'round', label: '라운드', icon: '🏆' },
|
||||
];
|
||||
export function typeGroup(it: TimelineItem): TypeGroup {
|
||||
if (it.kind === 'utterance') return 'utterance';
|
||||
switch ((it as EventItem).type) {
|
||||
case 'kill':
|
||||
case 'multikill':
|
||||
case 'ace':
|
||||
return 'kill';
|
||||
case 'chat':
|
||||
return 'chat';
|
||||
case 'object':
|
||||
return 'object';
|
||||
default:
|
||||
return 'round';
|
||||
}
|
||||
}
|
||||
|
||||
export const itemGame = (it: TimelineItem) => (it.kind === 'utterance' ? it.game?.type ?? null : it.game);
|
||||
export const itemMatch = (it: TimelineItem) => (it.kind === 'utterance' ? it.game?.matchId ?? null : it.matchId);
|
||||
108
site/web/src/lib/live.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import type { BrowserMessage } from '@gvr/shared';
|
||||
|
||||
/**
|
||||
* 브라우저 WS `/ws` 클라이언트. 끊기면 지수 백오프(1s → 15s, 지터)로 다시 붙는다.
|
||||
* 메시지는 구독자에게 그대로 전달한다 ({type:'status'} + 5장 이벤트).
|
||||
*/
|
||||
export type LiveConn = 'connecting' | 'open' | 'closed';
|
||||
|
||||
type MsgFn = (m: BrowserMessage) => void;
|
||||
type ConnFn = (c: LiveConn) => void;
|
||||
|
||||
class LiveSocket {
|
||||
private ws: WebSocket | null = null;
|
||||
private attempt = 0;
|
||||
private timer: number | null = null;
|
||||
private stopped = true;
|
||||
private msgFns = new Set<MsgFn>();
|
||||
private connFns = new Set<ConnFn>();
|
||||
conn: LiveConn = 'closed';
|
||||
|
||||
start() {
|
||||
if (!this.stopped) return;
|
||||
this.stopped = false;
|
||||
this.connect();
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.stopped = true;
|
||||
if (this.timer) window.clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.ws?.close();
|
||||
this.ws = null;
|
||||
this.setConn('closed');
|
||||
}
|
||||
|
||||
/** 즉시 재연결 시도 (잠금 화면의 "지금 다시 확인") */
|
||||
kick() {
|
||||
if (this.stopped || this.conn === 'open') return;
|
||||
if (this.timer) window.clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.attempt = 0;
|
||||
this.connect();
|
||||
}
|
||||
|
||||
onMessage(fn: MsgFn) {
|
||||
this.msgFns.add(fn);
|
||||
return () => {
|
||||
this.msgFns.delete(fn);
|
||||
};
|
||||
}
|
||||
onConn(fn: ConnFn) {
|
||||
this.connFns.add(fn);
|
||||
return () => {
|
||||
this.connFns.delete(fn);
|
||||
};
|
||||
}
|
||||
|
||||
private setConn(c: LiveConn) {
|
||||
this.conn = c;
|
||||
this.connFns.forEach((fn) => fn(c));
|
||||
}
|
||||
|
||||
private connect() {
|
||||
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
let ws: WebSocket;
|
||||
try {
|
||||
ws = new WebSocket(`${proto}://${location.host}/ws`);
|
||||
} catch {
|
||||
this.schedule();
|
||||
return;
|
||||
}
|
||||
this.ws = ws;
|
||||
this.setConn('connecting');
|
||||
ws.onopen = () => {
|
||||
this.attempt = 0;
|
||||
this.setConn('open');
|
||||
};
|
||||
ws.onmessage = (e) => {
|
||||
let m: BrowserMessage;
|
||||
try {
|
||||
m = JSON.parse(String(e.data)) as BrowserMessage;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
this.msgFns.forEach((fn) => fn(m));
|
||||
};
|
||||
ws.onclose = () => {
|
||||
if (this.ws !== ws) return;
|
||||
this.ws = null;
|
||||
this.setConn('closed');
|
||||
this.schedule();
|
||||
};
|
||||
ws.onerror = () => ws.close();
|
||||
}
|
||||
|
||||
private schedule() {
|
||||
if (this.stopped) return;
|
||||
const base = Math.min(15000, 1000 * 2 ** this.attempt);
|
||||
this.attempt++;
|
||||
const delay = base * (0.75 + Math.random() * 0.5);
|
||||
this.timer = window.setTimeout(() => {
|
||||
this.timer = null;
|
||||
this.connect();
|
||||
}, delay);
|
||||
}
|
||||
}
|
||||
|
||||
export const live = new LiveSocket();
|
||||
118
site/web/src/lib/sfx.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { audioCtx, sfxOutput } from './audio';
|
||||
import { settings, type SfxKind } from '../store/settings';
|
||||
|
||||
/**
|
||||
* 효과음은 전부 Web Audio 로 즉석 합성한다 (음원 파일 · 라이선스 없음).
|
||||
* 사용자 제스처 전에는 AudioContext 가 잠겨 있으므로 조용히 건너뛴다.
|
||||
*/
|
||||
let noiseBuf: AudioBuffer | null = null;
|
||||
function noise(ctx: AudioContext) {
|
||||
if (!noiseBuf) {
|
||||
noiseBuf = ctx.createBuffer(1, ctx.sampleRate * 0.6, ctx.sampleRate);
|
||||
const d = noiseBuf.getChannelData(0);
|
||||
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
|
||||
}
|
||||
const s = ctx.createBufferSource();
|
||||
s.buffer = noiseBuf;
|
||||
return s;
|
||||
}
|
||||
|
||||
function env(ctx: AudioContext, peak: number, attack: number, decay: number, at: number) {
|
||||
const g = ctx.createGain();
|
||||
g.gain.setValueAtTime(0.0001, at);
|
||||
g.gain.exponentialRampToValueAtTime(peak, at + attack);
|
||||
g.gain.exponentialRampToValueAtTime(0.0001, at + attack + decay);
|
||||
return g;
|
||||
}
|
||||
|
||||
function tone(ctx: AudioContext, out: AudioNode, type: OscillatorType, f0: number, f1: number, at: number, dur: number, peak: number) {
|
||||
const o = ctx.createOscillator();
|
||||
o.type = type;
|
||||
o.frequency.setValueAtTime(f0, at);
|
||||
o.frequency.exponentialRampToValueAtTime(f1, at + dur);
|
||||
const g = env(ctx, peak, 0.004, dur, at);
|
||||
o.connect(g).connect(out);
|
||||
o.start(at);
|
||||
o.stop(at + dur + 0.05);
|
||||
}
|
||||
|
||||
const SYNTH: Record<SfxKind, (ctx: AudioContext, out: AudioNode, t: number) => void> = {
|
||||
// 짧은 틱
|
||||
click(ctx, out, t) {
|
||||
tone(ctx, out, 'sine', 2100, 1500, t, 0.03, 0.18);
|
||||
const n = noise(ctx);
|
||||
const hp = ctx.createBiquadFilter();
|
||||
hp.type = 'highpass';
|
||||
hp.frequency.value = 4000;
|
||||
n.connect(hp).connect(env(ctx, 0.08, 0.001, 0.015, t)).connect(out);
|
||||
n.start(t);
|
||||
n.stop(t + 0.03);
|
||||
},
|
||||
// 재생 시작: 위로 올라가는 두 음
|
||||
play(ctx, out, t) {
|
||||
tone(ctx, out, 'triangle', 660, 680, t, 0.08, 0.22);
|
||||
tone(ctx, out, 'triangle', 990, 1000, t + 0.065, 0.12, 0.2);
|
||||
},
|
||||
// 킬: 짧은 사각파 블립 + 하강
|
||||
kill(ctx, out, t) {
|
||||
const bp = ctx.createBiquadFilter();
|
||||
bp.type = 'bandpass';
|
||||
bp.frequency.value = 1400;
|
||||
bp.Q.value = 1.2;
|
||||
bp.connect(out);
|
||||
tone(ctx, bp, 'square', 1250, 520, t, 0.09, 0.3);
|
||||
tone(ctx, out, 'sine', 180, 90, t, 0.12, 0.25);
|
||||
},
|
||||
// 라운드 전환: 대역 통과 잡음 스윕 (휙)
|
||||
round(ctx, out, t) {
|
||||
const n = noise(ctx);
|
||||
const bp = ctx.createBiquadFilter();
|
||||
bp.type = 'bandpass';
|
||||
bp.Q.value = 2.5;
|
||||
bp.frequency.setValueAtTime(300, t);
|
||||
bp.frequency.exponentialRampToValueAtTime(3800, t + 0.32);
|
||||
const g = ctx.createGain();
|
||||
g.gain.setValueAtTime(0.0001, t);
|
||||
g.gain.exponentialRampToValueAtTime(0.5, t + 0.16);
|
||||
g.gain.exponentialRampToValueAtTime(0.0001, t + 0.42);
|
||||
n.connect(bp).connect(g).connect(out);
|
||||
n.start(t);
|
||||
n.stop(t + 0.45);
|
||||
},
|
||||
// 새 발화 알림: 맑은 두 음 종소리
|
||||
chime(ctx, out, t) {
|
||||
for (const [f, d, p] of [
|
||||
[1046.5, 0.7, 0.16],
|
||||
[1568, 0.55, 0.1],
|
||||
[2093, 0.3, 0.04],
|
||||
] as const) {
|
||||
tone(ctx, out, 'sine', f, f * 0.998, t, d, p);
|
||||
}
|
||||
tone(ctx, out, 'sine', 1318.5, 1318, t + 0.09, 0.6, 0.12);
|
||||
},
|
||||
};
|
||||
|
||||
let last: Partial<Record<SfxKind, number>> = {};
|
||||
export function sfx(kind: SfxKind) {
|
||||
const s = settings.get();
|
||||
if (!s.sfx[kind] || s.volume <= 0) return;
|
||||
const ctx = audioCtx();
|
||||
if (ctx.state !== 'running') return;
|
||||
const now = ctx.currentTime;
|
||||
// 같은 효과음이 몰려도 귀가 아프지 않게 60ms 안 중복은 생략
|
||||
if ((last[kind] ?? -1) > now - 0.06) return;
|
||||
last = { ...last, [kind]: now };
|
||||
const out = ctx.createGain();
|
||||
out.gain.value = s.volume * 0.7;
|
||||
out.connect(sfxOutput());
|
||||
SYNTH[kind](ctx, out, now + 0.005);
|
||||
window.setTimeout(() => out.disconnect(), 1500);
|
||||
}
|
||||
|
||||
export const SFX_LABEL: Record<SfxKind, string> = {
|
||||
click: '버튼 클릭 틱',
|
||||
play: '재생 시작',
|
||||
kill: '킬 이벤트',
|
||||
round: '라운드 전환',
|
||||
chime: '새 발화 알림',
|
||||
};
|
||||
13
site/web/src/main.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { App } from './App';
|
||||
import './styles.css';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
);
|
||||
371
site/web/src/pages/LolMatch.tsx
Normal file
@@ -0,0 +1,371 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { EventItem, KillData, MatchDetail, MatchPlayer, ObjectData, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { player, usePlayer } from '../store/player';
|
||||
import { useData } from '../store/app';
|
||||
import { useReducedMotion } from '../store/settings';
|
||||
import { LOL_OBJECT_POS, OBJECT_GLYPH, objectName, toUV } from '../lib/game';
|
||||
import { fmtClock, k, realTip } from '../lib/format';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { CharIcon, Panel } from '../components/common';
|
||||
import { UtteranceRow } from '../components/UtteranceRow';
|
||||
import { EventBody, SeparatorRow } from '../components/EventRow';
|
||||
import { TalkBars } from '../components/TalkBars';
|
||||
import { IWaves } from '../components/Icons';
|
||||
import { matchMeta } from './MatchPage';
|
||||
|
||||
const WIN = 60000; // 지도에 보이는 구간: 선택 시각 ±60초
|
||||
type ObjEvent = EventItem & { data: ObjectData & { icon?: string | null; location?: { x: number; y: number } } };
|
||||
|
||||
function ObjIcon({ e, size = 18 }: { e: ObjEvent; size?: number }) {
|
||||
return e.data.icon ? (
|
||||
<img className="oi" src={e.data.icon} alt={objectName(e.data.object, e.data.subtype)} style={{ width: size, height: size }} />
|
||||
) : (
|
||||
<span style={{ fontSize: size * 0.8 }}>{OBJECT_GLYPH[e.data.object] ?? '◆'}</span>
|
||||
);
|
||||
}
|
||||
|
||||
function GoldGraph({ m, center, onPick }: { m: MatchDetail; center: number; onPick: (t: number) => void }) {
|
||||
const W = 470;
|
||||
const H = 80;
|
||||
const gd = m.goldDiff ?? [];
|
||||
const dur = (m.endedAt ?? m.startedAt + (gd[gd.length - 1]?.t ?? 1)) - m.startedAt;
|
||||
const maxAbs = Math.max(1000, ...gd.map((g) => Math.abs(g.diff)));
|
||||
const mid = 34;
|
||||
const x = (t: number) => (t / dur) * W;
|
||||
const y = (d: number) => mid - (d / maxAbs) * 30;
|
||||
const line = gd.map((g, i) => `${i ? 'L' : 'M'}${x(g.t).toFixed(1)} ${y(g.diff).toFixed(1)}`).join(' ');
|
||||
const area = gd.length ? `${line} L${x(gd[gd.length - 1].t).toFixed(1)} ${mid} L0 ${mid} Z` : '';
|
||||
const objs = m.events.filter((e): e is ObjEvent => e.type === 'object' && e.data.object !== 'tower' && e.data.object !== 'inhibitor');
|
||||
const towers = m.events.filter((e): e is ObjEvent => e.type === 'object' && (e.data.object === 'tower' || e.data.object === 'inhibitor'));
|
||||
const ts = usePlayer((s) => s.sceneTs);
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const play = ts != null && ts >= m.startedAt && ts <= m.startedAt + dur ? ts - m.startedAt : null;
|
||||
const at = (clientX: number, el: Element) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return Math.max(0, Math.min(dur, ((clientX - r.left) / r.width) * dur));
|
||||
};
|
||||
const nearest = (t: number) => gd.reduce((b, g) => (Math.abs(g.t - t) < Math.abs(b.t - t) ? g : b), gd[0]);
|
||||
const final = gd[gd.length - 1]?.diff ?? 0;
|
||||
const hv = hover != null && gd.length ? nearest(hover) : null;
|
||||
return (
|
||||
<div className="goldgraph">
|
||||
<div className="gold-h">
|
||||
<span>골드 차이 (우리 팀 − 상대)</span>
|
||||
<span className="gold-final">
|
||||
최종 {final >= 0 ? '+' : ''}
|
||||
{k(final)}
|
||||
</span>
|
||||
</div>
|
||||
<svg
|
||||
viewBox={`0 0 ${W} ${H}`}
|
||||
width="100%"
|
||||
height={H}
|
||||
preserveAspectRatio="none"
|
||||
onMouseMove={(e) => setHover(at(e.clientX, e.currentTarget))}
|
||||
onMouseLeave={() => setHover(null)}
|
||||
onClick={(e) => onPick(at(e.clientX, e.currentTarget))}
|
||||
role="img"
|
||||
aria-label="골드 차이 그래프"
|
||||
>
|
||||
<line x1="0" y1={mid} x2={W} y2={mid} stroke="#2a3542" />
|
||||
<path d={area} fill="rgba(200,170,110,.12)" />
|
||||
<path d={line} fill="none" stroke="#c8aa6e" strokeWidth="2" vectorEffect="non-scaling-stroke" />
|
||||
<rect x={x(center - WIN)} y="0" width={x(2 * WIN)} height={H - 18} fill="rgba(10,200,185,.07)" />
|
||||
{objs.map((e) => (
|
||||
<image key={e.id} href={e.data.icon ?? undefined} x={x(e.ts - m.startedAt) - 8} y={H - 17} width="16" height="16" preserveAspectRatio="xMidYMid meet" />
|
||||
))}
|
||||
{towers.map((e) => (
|
||||
<rect key={e.id} x={x(e.ts - m.startedAt) - 1.5} y={H - 12} width="3" height="8" rx="1.5" fill={e.data.ally === false ? '#ff4655' : '#0ac8b9'} />
|
||||
))}
|
||||
{play != null && <line x1={x(play)} y1="0" x2={x(play)} y2={H - 18} stroke="#ff4655" strokeDasharray="3 3" vectorEffect="non-scaling-stroke" />}
|
||||
{hv && (
|
||||
<>
|
||||
<line x1={x(hv.t)} y1="0" x2={x(hv.t)} y2={H - 18} stroke="#f0e6d2" strokeOpacity=".5" vectorEffect="non-scaling-stroke" />
|
||||
<circle cx={x(hv.t)} cy={y(hv.diff)} r="3.5" fill="#c8aa6e" stroke="#010a13" strokeWidth="2" />
|
||||
</>
|
||||
)}
|
||||
</svg>
|
||||
{hv && (
|
||||
<div className="gold-tip" style={{ left: `${(x(hv.t) / W) * 100}%` }}>
|
||||
<span className="mono">{fmtClock(hv.t)}</span> · {hv.diff >= 0 ? '우리 팀 +' : '상대 +'}
|
||||
{k(Math.abs(hv.diff))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LolMap({ m, center }: { m: MatchDetail; center: number }) {
|
||||
const ts = usePlayer((s) => s.sceneTs);
|
||||
const reduce = useReducedMotion();
|
||||
const t0 = m.startedAt + center - WIN;
|
||||
const t1 = m.startedAt + center + WIN;
|
||||
const evs = m.events.filter((e) => e.ts >= t0 && e.ts <= t1);
|
||||
const kills = evs.filter((e) => e.type === 'kill');
|
||||
const objs = evs.filter((e): e is ObjEvent => e.type === 'object');
|
||||
const pts = kills.map((e) => toUV(m, (e.data as KillData).location)).filter((p): p is { u: number; v: number } => !!p);
|
||||
let ring: { u: number; v: number; r: number } | null = null;
|
||||
if (pts.length >= 3) {
|
||||
const cu = pts.reduce((s, p) => s + p.u, 0) / pts.length;
|
||||
const cv = pts.reduce((s, p) => s + p.v, 0) / pts.length;
|
||||
const r = Math.max(...pts.map((p) => Math.hypot(p.u - cu, p.v - cv)));
|
||||
if (r < 0.2) ring = { u: cu, v: cv, r: r + 0.04 };
|
||||
}
|
||||
return (
|
||||
<div className="map-sq lol-map">
|
||||
{m.map.image && <img src={m.map.image} alt="소환사의 협곡" />}
|
||||
{ring && <div className="mk ring" style={{ left: `${ring.u * 100}%`, top: `${ring.v * 100}%`, width: `${ring.r * 200}%`, height: `${ring.r * 200}%` }} />}
|
||||
{objs.map((e) => {
|
||||
const uv = toUV(m, e.data.location ?? LOL_OBJECT_POS[e.data.object]);
|
||||
if (!uv) return null;
|
||||
const hot = ts != null && ts - e.ts >= 0 && ts - e.ts < 5000;
|
||||
return (
|
||||
<div key={e.id} className={`mk o${hot ? ' hot' : ''}`} style={{ left: `${uv.u * 100}%`, top: `${uv.v * 100}%` }} data-tip={`${e.time.primary} ${objectName(e.data.object, e.data.subtype)}`}>
|
||||
<ObjIcon e={e} size={26} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{kills.map((e) => {
|
||||
const d = e.data as KillData;
|
||||
const uv = toUV(m, d.location);
|
||||
if (!uv) return null;
|
||||
const allyKill = d.ally ?? !!d.killer?.userId;
|
||||
const recent = ts != null && ts - e.ts >= 0 && ts - e.ts < 4000;
|
||||
const future = ts != null && ts >= t0 && ts <= t1 && e.ts > ts;
|
||||
return (
|
||||
<div
|
||||
key={e.id}
|
||||
className={`mk kill ${allyKill ? 'ally' : 'enemy'}${recent ? ' recent' : ''}${future ? ' future' : ''}`}
|
||||
style={{ left: `${uv.u * 100}%`, top: `${uv.v * 100}%` }}
|
||||
data-tip={`${e.time.primary} ${d.killer?.name ?? '?'} → ${d.victim.name}`}
|
||||
>
|
||||
{recent && d.killer && (
|
||||
<motion.span className={`mk-p ${allyKill ? '' : 'en'}`} initial={reduce ? false : { scale: 0.3, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}>
|
||||
<CharIcon c={d.killer.character} size={26} />
|
||||
</motion.span>
|
||||
)}
|
||||
<span className="x">✕</span>
|
||||
{recent && !reduce && <span className="ping" />}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ObjSummary({ m }: { m: MatchDetail }) {
|
||||
const objs = m.events.filter((e): e is ObjEvent => e.type === 'object');
|
||||
const dragons = objs.filter((e) => e.data.object === 'dragon' && e.data.ally !== false);
|
||||
const barons = objs.filter((e) => e.data.object === 'baron' && e.data.ally !== false);
|
||||
const grubs = objs.filter((e) => e.data.object === 'grub' && e.data.ally !== false);
|
||||
const towersUs = objs.filter((e) => (e.data.object === 'tower' || e.data.object === 'inhibitor') && e.data.ally !== false).length;
|
||||
const towersThem = objs.filter((e) => (e.data.object === 'tower' || e.data.object === 'inhibitor') && e.data.ally === false).length;
|
||||
return (
|
||||
<div className="obj-sum">
|
||||
{dragons.length > 0 && (
|
||||
<span>
|
||||
{dragons.map((d) => (
|
||||
<ObjIcon key={d.id} e={d} />
|
||||
))}{' '}
|
||||
드래곤 {dragons.length}
|
||||
</span>
|
||||
)}
|
||||
{barons.map((b) => (
|
||||
<span key={b.id}>
|
||||
<ObjIcon e={b} /> 바론 {b.time.primary}
|
||||
</span>
|
||||
))}
|
||||
<span>
|
||||
{objs.find((o) => o.data.object === 'tower') && <ObjIcon e={objs.find((o) => o.data.object === 'tower')!} />} 포탑 {towersUs} : {towersThem}
|
||||
</span>
|
||||
{grubs.length > 0 && (
|
||||
<span>
|
||||
<ObjIcon e={grubs[0]} /> 공허 유충 {grubs.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LolScoreboard({ players }: { players: MatchPlayer[] }) {
|
||||
const { userById } = useData();
|
||||
return (
|
||||
<table className="score-tbl lol">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>소환사</th>
|
||||
<th>K/D/A</th>
|
||||
<th>CS</th>
|
||||
<th>골드</th>
|
||||
</tr>
|
||||
</thead>
|
||||
{[true, false].map((ally) => (
|
||||
<tbody key={String(ally)} className={ally ? 'ally' : 'enemy'}>
|
||||
<tr className="team-row">
|
||||
<td colSpan={4}>{ally ? '우리 팀' : '상대 팀'}</td>
|
||||
</tr>
|
||||
{players
|
||||
.filter((p) => p.ally === ally)
|
||||
.map((p) => {
|
||||
const u = userById(p.userId);
|
||||
return (
|
||||
<tr key={p.puuid} className={u ? 'linked' : ''}>
|
||||
<td>
|
||||
<div className="lp">
|
||||
<CharIcon c={p.character} size={28} className="ch" />
|
||||
<div>
|
||||
{u ? <b style={{ color: u.color }}>{u.name}</b> : <span>{p.tag ? `${p.name}#${p.tag}` : p.name}</span>}
|
||||
<div className="items">
|
||||
{(p.items ?? []).slice(0, 6).map((it, i) =>
|
||||
it.icon ? <img key={i} src={it.icon} alt={it.name} title={it.name} /> : <i key={i} title={it.name} />,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="mono">
|
||||
{p.kills}/{p.deaths}/{p.assists}
|
||||
</td>
|
||||
<td className="mono">{p.cs ?? '—'}</td>
|
||||
<td className="mono">{p.gold != null ? k(p.gold) : '—'}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
))}
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
function LolRow({ it, m, onPick }: { it: TimelineItem; m: MatchDetail; onPick: (t: number) => void }) {
|
||||
const active = usePlayer((s) => it.kind === 'event' && s.sceneTs != null && s.sceneTs - it.ts >= 0 && s.sceneTs - it.ts < 3000);
|
||||
if (it.kind === 'utterance') {
|
||||
const char = m.players.find((p) => p.userId === it.userId)?.character.name;
|
||||
return <UtteranceRow item={it} variant="compact" sub={char} />;
|
||||
}
|
||||
if (it.type === 'match_start' || it.type === 'match_end') return <SeparatorRow e={it} />;
|
||||
return (
|
||||
<div className={`l evl${active ? ' flash' : ''}${it.type === 'object' ? ' glow' : ''}`} onClick={() => onPick(it.ts - m.startedAt)} data-tip={realTip(it.ts)}>
|
||||
<span className="t mono">{it.time.primary}</span>
|
||||
<EventBody e={it} iconSize={24} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 킬이 가장 몰린 구간 (기본 선택 시각) */
|
||||
function densest(m: MatchDetail) {
|
||||
const ks = m.events.filter((e) => e.type === 'kill').map((e) => e.ts - m.startedAt);
|
||||
let best = ks[0] ?? 0;
|
||||
let bestN = 0;
|
||||
for (const t of ks) {
|
||||
const n = ks.filter((x) => Math.abs(x - t) <= WIN).length;
|
||||
if (n > bestN) {
|
||||
bestN = n;
|
||||
best = t;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function LolMatch({ m }: { m: MatchDetail }) {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const meta = matchMeta(m);
|
||||
const def = useMemo(() => densest(m), [m]);
|
||||
const picked = params.get('t') != null ? Number(params.get('t')) * 1000 : def;
|
||||
// 재생 중이면 지도 구간이 재생 위치를 따라간다 (5초 단위)
|
||||
const follow = usePlayer((s) => (s.sceneTs != null && s.sceneTs >= m.startedAt && s.sceneTs <= (m.endedAt ?? Infinity) ? Math.round((s.sceneTs - m.startedAt) / 5000) * 5000 : null));
|
||||
const center = follow ?? picked;
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const items = useMemo(() => [...m.utterances, ...m.events].sort((a, b) => a.ts - b.ts), [m]);
|
||||
const pick = (t: number) => {
|
||||
sfx('click');
|
||||
const p = new URLSearchParams(params);
|
||||
p.set('t', String(Math.round(t / 1000)));
|
||||
setParams(p, { replace: true });
|
||||
};
|
||||
const curId = usePlayer((s) => (s.mode === 'single' ? s.item?.id ?? null : null));
|
||||
useEffect(() => {
|
||||
if (curId) listRef.current?.querySelector(`[data-id="${curId}"]`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||
}, [curId]);
|
||||
// 처음 열 때 선택 구간으로 스크롤
|
||||
useEffect(() => {
|
||||
const target = items.find((i) => i.ts >= m.startedAt + picked - 15000);
|
||||
if (target) listRef.current?.querySelector(`[data-id="${target.id}"]`)?.scrollIntoView({ block: 'start' });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [m.id]);
|
||||
|
||||
const scene = () =>
|
||||
player.startScene({
|
||||
start: m.startedAt + center - WIN,
|
||||
end: m.startedAt + center + WIN,
|
||||
label: `소환사의 협곡 · ${fmtClock(center - WIN)} ~ ${fmtClock(center + WIN)}`,
|
||||
items: m.utterances,
|
||||
});
|
||||
|
||||
return (
|
||||
<main className="match lol theme-lol">
|
||||
<div className="mtop">
|
||||
<div>
|
||||
<div className="eyebrow">MATCH DETAIL · LEAGUE OF LEGENDS</div>
|
||||
<div className="mtitle h">
|
||||
{m.map.name}{' '}
|
||||
{m.score && (
|
||||
<span className="score">
|
||||
<span className="a">{m.score.ally}</span> <span className="dim colon">:</span> <span className="b">{m.score.enemy}</span>
|
||||
</span>
|
||||
)}
|
||||
{m.win != null && <span className={`res-badge ${m.win ? 'win' : 'loss'}`}>{m.win ? '승리' : '패배'}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="meta">
|
||||
{m.mode} · {meta.when} 시작 · {meta.dur}
|
||||
<br />
|
||||
대화 {m.utterances.length}개 · 킬 {meta.kills} · 오브젝트 {meta.objs} · 우리 팀 5명 중 {meta.voiced}명 음성 기록
|
||||
</div>
|
||||
<GoldGraph m={m} center={center} onPick={pick} />
|
||||
</div>
|
||||
<div className="mgrid">
|
||||
<Panel
|
||||
className="map-panel"
|
||||
title={`킬 · 오브젝트 위치 (${fmtClock(Math.max(0, center - WIN))} ~ ${fmtClock(center + WIN)})`}
|
||||
right={
|
||||
<button className="mini-btn" onClick={scene} title="이 구간의 발화를 실제 순서대로 겹쳐 재생">
|
||||
<IWaves width={12} height={12} /> 현장 모드
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<div className="map-area lol-map-area">
|
||||
<LolMap m={m} center={center} />
|
||||
</div>
|
||||
<ObjSummary m={m} />
|
||||
<div className="map-legend">
|
||||
<div>
|
||||
<span className="lg-ring" /> 우리 팀 <span className="lg-ring en" /> 상대 팀 <b className="accent">✕</b> 우리 팀 데스 <b className="hex">✕</b> 상대 데스
|
||||
</div>
|
||||
<div className="dim">위치는 경기 후 타임라인 좌표를 지도 위에 옮긴 것입니다. 그래프나 목록을 누르면 구간이 바뀝니다.</div>
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel className="feed-panel" title="대화 · 킬 · 오브젝트 (게임 시간)" right="현실 시간은 마우스를 올리면 표시">
|
||||
<div className="feed scroll" ref={listRef}>
|
||||
{items.map((it) => (
|
||||
<div key={it.id} data-id={it.id}>
|
||||
<LolRow it={it} m={m} onPick={pick} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel className="sb-panel" title="스코어보드" right="경기 종료 기준">
|
||||
<div className="scroll">
|
||||
<LolScoreboard players={m.players} />
|
||||
<h4 className="sub-h">
|
||||
<span>이 경기 발화량</span>
|
||||
</h4>
|
||||
<TalkBars utts={m.utterances as UtteranceItem[]} />
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
61
site/web/src/pages/MatchPage.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router';
|
||||
import type { MatchDetail } from '@gvr/shared';
|
||||
import { api } from '../lib/api';
|
||||
import { useStatus } from '../store/app';
|
||||
import { player } from '../store/player';
|
||||
import { ErrorBox, Spinner } from '../components/common';
|
||||
import { ValorantMatch } from './ValorantMatch';
|
||||
import { LolMatch } from './LolMatch';
|
||||
import { fmtDuration, fmtWhen } from '../lib/format';
|
||||
|
||||
export function matchMeta(m: MatchDetail) {
|
||||
const kills = m.events.filter((e) => e.type === 'kill').length;
|
||||
const chats = m.events.filter((e) => e.type === 'chat').length;
|
||||
const objs = m.events.filter((e) => e.type === 'object').length;
|
||||
const voiced = new Set(m.utterances.map((u) => u.userId)).size;
|
||||
return { kills, chats, objs, voiced, when: fmtWhen(m.startedAt), dur: m.endedAt ? fmtDuration(m.endedAt - m.startedAt) : '진행 중' };
|
||||
}
|
||||
|
||||
export function MatchPage() {
|
||||
const { id = '' } = useParams();
|
||||
const { epoch } = useStatus();
|
||||
const [m, setM] = useState<MatchDetail | null>(null);
|
||||
const [err, setErr] = useState<unknown>(null);
|
||||
const [n, setN] = useState(0);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setErr(null);
|
||||
api
|
||||
.match(id)
|
||||
.then((d) => alive && setM(d))
|
||||
.catch((e) => alive && setErr(e));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [id, epoch, n]);
|
||||
useEffect(() => {
|
||||
if (m) player.setQueue([...m.utterances, ...m.events]);
|
||||
}, [m]);
|
||||
if (err)
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<ErrorBox error={err} onRetry={() => setN((x) => x + 1)} />
|
||||
</main>
|
||||
);
|
||||
if (!m || m.id !== id)
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<Spinner label="경기 기록 불러오는 중" />
|
||||
</main>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<div className="crumbs">
|
||||
<Link to="/matches">← 경기 목록</Link>
|
||||
<Link to={`/?match=${encodeURIComponent(m.id)}`}>타임라인에서 보기</Link>
|
||||
</div>
|
||||
{m.game === 'lol' ? <LolMatch m={m} /> : <ValorantMatch m={m} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
159
site/web/src/pages/Sidebar.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
import type { MatchDetail, MatchSummary, User } from '@gvr/shared';
|
||||
import type { Filters } from '../lib/filters';
|
||||
import { Avatar, CharIcon } from '../components/common';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { dateInputToMs, dateInputValue, fmtHM, fmtWhen } from '../lib/format';
|
||||
import { TYPE_GROUPS } from '../lib/game';
|
||||
|
||||
type Update = (p: Partial<Filters>) => void;
|
||||
|
||||
export function toggleUser(f: Filters, users: User[], id: string): string[] {
|
||||
const all = users.filter((u) => !u.excluded).map((u) => u.id);
|
||||
const cur = f.users.length ? f.users : all;
|
||||
const nextSet = cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id];
|
||||
if (!nextSet.length) return [id];
|
||||
return all.every((x) => nextSet.includes(x)) ? [] : nextSet;
|
||||
}
|
||||
|
||||
export function MatchItem({ m, on, onClick }: { m: MatchSummary; on?: boolean; onClick?: () => void }) {
|
||||
const dur = m.endedAt ? Math.round((m.endedAt - m.startedAt) / 60000) : null;
|
||||
const res = m.win == null ? '' : m.win ? '승' : '패';
|
||||
const Tag = onClick ? 'button' : 'div';
|
||||
return (
|
||||
<Tag className={`match g-${m.game}${on ? ' on' : ''}${m.win === false ? ' loss' : ''}`} onClick={onClick}>
|
||||
<span className="res" />
|
||||
<div className="mi">
|
||||
<div>
|
||||
<b>{m.map.name}</b> {m.score && <span className="mono">{`${m.score.ally} : ${m.score.enemy}`}</span>}
|
||||
</div>
|
||||
<div className="t">
|
||||
{m.game === 'lol' ? '롤 · ' : ''}
|
||||
{m.mode} · {fmtHM(m.startedAt)}
|
||||
{dur != null ? ` · ${dur}분` : ''}
|
||||
{m.status === 'live' && <span className="live-dot"> · 진행 중</span>}
|
||||
</div>
|
||||
</div>
|
||||
{res && <span className={`badge ${m.win ? 'b-win' : 'b-loss'}`}>{res}</span>}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar({ f, update, users, matches, detail }: { f: Filters; update: Update; users: User[]; matches: MatchSummary[]; detail: MatchDetail | null }) {
|
||||
const isOn = (id: string) => (f.users.length ? f.users.includes(id) : true);
|
||||
const charOf = (uid: string) => detail?.players.find((p) => p.userId === uid)?.character;
|
||||
const tap = (fn: () => void) => () => {
|
||||
sfx('click');
|
||||
fn();
|
||||
};
|
||||
const today = matches.length ? fmtWhen(matches[0].startedAt).split(' ')[0] : '';
|
||||
return (
|
||||
<aside className="side">
|
||||
<div>
|
||||
<h4>유저</h4>
|
||||
{users.map((u) => {
|
||||
const on = !u.excluded && isOn(u.id);
|
||||
const c = charOf(u.id);
|
||||
return (
|
||||
<button
|
||||
key={u.id}
|
||||
className={`urow${on ? ' sel' : ''}${u.excluded ? ' excluded' : ''}`}
|
||||
onClick={u.excluded ? undefined : tap(() => update({ users: toggleUser(f, users, u.id) }))}
|
||||
disabled={u.excluded}
|
||||
aria-pressed={on}
|
||||
title={u.excluded ? '/녹음제외 를 사용한 유저입니다' : undefined}
|
||||
>
|
||||
<span className={`chk${on ? ' on' : ''}`} />
|
||||
<Avatar user={u} />
|
||||
{c && <CharIcon c={c} size={22} className="side-ag" />}
|
||||
<span className={`n${on ? '' : ' muted'}`}>{u.name}</span>
|
||||
{u.excluded ? <span className="badge b-excl">녹음 제외</span> : <span className="c">{c?.name ?? ''}</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div>
|
||||
<h4>게임</h4>
|
||||
<div className="chips-wrap">
|
||||
<button className={`chip val${f.game === 'valorant' ? ' on' : ''}`} onClick={tap(() => update({ game: f.game === 'valorant' ? null : 'valorant', match: null }))}>
|
||||
발로란트
|
||||
</button>
|
||||
<button className={`chip lol${f.game === 'lol' ? ' on' : ''}`} onClick={tap(() => update({ game: f.game === 'lol' ? null : 'lol', match: null }))}>
|
||||
롤
|
||||
</button>
|
||||
<button className={`chip${f.game === 'none' ? ' on' : ''}`} onClick={tap(() => update({ game: f.game === 'none' ? null : 'none', match: null }))}>
|
||||
게임 외 대화
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="side-matches">
|
||||
<h4>
|
||||
경기 <span className="dim">{today && `· ${today}`}</span>
|
||||
</h4>
|
||||
<div className="mlist">
|
||||
{matches.length === 0 && <div className="dim small">경기 기록 없음</div>}
|
||||
{matches.map((m) => (
|
||||
<MatchItem key={m.id} m={m} on={f.match === m.id} onClick={tap(() => update({ match: f.match === m.id ? null : m.id, order: null }))} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h4>날짜</h4>
|
||||
<div className="dates">
|
||||
<input type="date" value={dateInputValue(f.from)} max={dateInputValue(f.to)} onChange={(e) => update({ from: dateInputToMs(e.target.value) })} aria-label="시작 날짜" />
|
||||
<span className="dim">~</span>
|
||||
<input type="date" value={dateInputValue(f.to)} min={dateInputValue(f.from)} onChange={(e) => update({ to: dateInputToMs(e.target.value, true) })} aria-label="끝 날짜" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="side-foot">
|
||||
<label className="switch">
|
||||
<input type="checkbox" checked={f.hideNoise} onChange={(e) => update({ hideNoise: e.target.checked })} />
|
||||
<span className="sw" />
|
||||
잡음 숨기기
|
||||
</label>
|
||||
<button className="link-btn" onClick={tap(() => update({ users: [], game: null, match: null, from: undefined, to: undefined, q: '', types: [], hideNoise: false, order: null }))}>
|
||||
필터 초기화
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
/** 휴대폰: 필터를 가로 칩 줄로 접는다 */
|
||||
export function MobileFilters({ f, update, users, matches }: { f: Filters; update: Update; users: User[]; matches: MatchSummary[] }) {
|
||||
const cur = matches.find((m) => m.id === f.match);
|
||||
const typeOn = (id: string) => f.types.includes(id as never);
|
||||
return (
|
||||
<div className="m-chips">
|
||||
<label className={`chip sel-chip${f.match ? ' on' : ''}`}>
|
||||
{cur ? `${cur.map.name} ${cur.score ? `${cur.score.ally}:${cur.score.enemy}` : ''}` : '모든 경기'}
|
||||
<select value={f.match ?? ''} onChange={(e) => update({ match: e.target.value || null, order: null })} aria-label="경기 선택">
|
||||
<option value="">모든 경기</option>
|
||||
{matches.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.map.name} {m.score ? `${m.score.ally}:${m.score.enemy}` : ''} · {fmtHM(m.startedAt)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{users
|
||||
.filter((u) => !u.excluded)
|
||||
.map((u) => {
|
||||
const on = f.users.includes(u.id);
|
||||
return (
|
||||
<button key={u.id} className={`chip${on ? ' on-user' : ''}`} style={on ? { borderColor: u.color, color: '#fff', background: `${u.color}33` } : undefined} onClick={() => update({ users: on ? f.users.filter((x) => x !== u.id) : [...f.users, u.id] })}>
|
||||
<span className="udot" style={{ background: u.color }} />
|
||||
{u.name}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{TYPE_GROUPS.map((t) => (
|
||||
<button key={t.id} className={`chip${typeOn(t.id) ? ' on' : ''}`} onClick={() => update({ types: typeOn(t.id) ? f.types.filter((x) => x !== t.id) : [...f.types, t.id] })}>
|
||||
{t.icon} {t.label}
|
||||
</button>
|
||||
))}
|
||||
<button className={`chip${f.hideNoise ? ' on' : ''}`} onClick={() => update({ hideNoise: !f.hideNoise })}>
|
||||
잡음 숨기기
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
353
site/web/src/pages/TimelinePage.tsx
Normal file
@@ -0,0 +1,353 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import type { MatchDetail, MatchSummary, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { api } from '../lib/api';
|
||||
import { effectiveOrder, matchesFilter, parseFilters, toQuery, writeFilters, type Filters } from '../lib/filters';
|
||||
import { TYPE_GROUPS, type TypeGroup } from '../lib/game';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { fmtReal, fmtWhen } from '../lib/format';
|
||||
import { useAuth, useData, useLive, useStatus } from '../store/app';
|
||||
import { player, usePlayer } from '../store/player';
|
||||
import { TimelineRows } from '../components/TimelineRows';
|
||||
import { Avatar, ErrorBox, Spinner } from '../components/common';
|
||||
import { IWaves } from '../components/Icons';
|
||||
import { MobileFilters, Sidebar } from './Sidebar';
|
||||
import { TalkBars } from '../components/TalkBars';
|
||||
|
||||
function NowPlayingCard() {
|
||||
const item = usePlayer((s) => (s.mode === 'single' ? s.item : null));
|
||||
const scene = usePlayer((s) => (s.mode === 'scene' ? s.scene : null));
|
||||
const { userById } = useData();
|
||||
if (scene)
|
||||
return (
|
||||
<div className="card">
|
||||
<h5>현장 모드</h5>
|
||||
<div className="np-scene">
|
||||
<b>{scene.label}</b>
|
||||
<div className="dim small">
|
||||
{fmtReal(scene.start)} ~ {fmtReal(scene.end)} · 발화 {scene.items.length}개를 실제 순서대로 겹쳐 재생
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
if (!item)
|
||||
return (
|
||||
<div className="card">
|
||||
<h5>재생 중인 발화</h5>
|
||||
<div className="dim small">발화를 누르면 음량 보정 · 인식 정보가 여기에 보입니다.</div>
|
||||
</div>
|
||||
);
|
||||
const u = userById(item.userId);
|
||||
const conf = item.confidence ?? 0;
|
||||
return (
|
||||
<div className="card">
|
||||
<h5>재생 중인 발화</h5>
|
||||
<div className="np-head">
|
||||
<Avatar user={u} size={40} />
|
||||
<div>
|
||||
<b>{u?.name ?? '알 수 없음'}</b>
|
||||
<div className="dim small">
|
||||
{item.time.primary} · {fmtReal(item.ts)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">재생 보정 게인</span>
|
||||
<span className="mono" style={{ color: 'var(--mint)' }}>
|
||||
{item.audio ? `${item.audio.gainDb > 0 ? '+' : ''}${item.audio.gainDb.toFixed(1)} dB` : '—'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">길이</span>
|
||||
<span className="mono">{((item.endTs - item.ts) / 1000).toFixed(1)}초</span>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">인식 모델</span>
|
||||
<span className="mono">{item.model ?? '처리 중'}</span>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">인식 신뢰도</span>
|
||||
<span className="mono">{item.confidence != null ? `${Math.round(conf * 100)}%` : '—'}</span>
|
||||
</div>
|
||||
<div className="bar">
|
||||
<i style={{ width: `${conf * 100}%`, background: 'var(--mint)' }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RightPanel({ items, detail }: { items: TimelineItem[]; detail: MatchDetail | null }) {
|
||||
const { auth } = useAuth();
|
||||
const { overview, userById } = useData();
|
||||
const meId = auth.status === 'ok' ? auth.me.user.id : null;
|
||||
const mine = detail?.players.find((p) => p.userId === meId);
|
||||
const utts = useMemo(() => (detail ? detail.utterances : items.filter((i): i is UtteranceItem => i.kind === 'utterance')), [detail, items]);
|
||||
const rounds = detail?.rounds?.length ?? 0;
|
||||
const rec = overview?.recording;
|
||||
return (
|
||||
<div className="right">
|
||||
<NowPlayingCard />
|
||||
{detail && mine && (
|
||||
<div className="card">
|
||||
<h5>
|
||||
이 경기 · {userById(meId)?.name ?? mine.name}
|
||||
</h5>
|
||||
<div className="stat4">
|
||||
<div>
|
||||
<b className="h">{mine.kills}</b>
|
||||
<span>킬</span>
|
||||
</div>
|
||||
<div>
|
||||
<b className="h">{mine.deaths}</b>
|
||||
<span>데스</span>
|
||||
</div>
|
||||
<div>
|
||||
<b className="h">{mine.assists}</b>
|
||||
<span>어시</span>
|
||||
</div>
|
||||
{detail.game === 'valorant' ? (
|
||||
<div>
|
||||
<b className="h accent">{rounds && mine.score != null ? Math.round(mine.score / rounds) : '—'}</b>
|
||||
<span>ACS</span>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<b className="h gold">{mine.cs ?? '—'}</b>
|
||||
<span>CS</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!detail && rec && (
|
||||
<div className="card">
|
||||
<h5>녹음 상태</h5>
|
||||
{rec.active ? (
|
||||
<>
|
||||
<div className="kv">
|
||||
<span className="muted">채널</span>
|
||||
<span>#{rec.channel}</span>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">시작</span>
|
||||
<span className="mono">{rec.since ? fmtWhen(rec.since) : '—'}</span>
|
||||
</div>
|
||||
<div className="avs">
|
||||
{rec.participants.map((id) => (
|
||||
<Avatar key={id} user={userById(id)} size={30} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="dim small">지금은 녹음하고 있지 않습니다.</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="card">
|
||||
<h5>{detail ? '이 경기 발화량' : '지금 목록의 발화량'}</h5>
|
||||
<TalkBars utts={utts} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TimelinePage() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const f = useMemo(() => parseFilters(params), [params]);
|
||||
const order = effectiveOrder(f);
|
||||
const key = writeFilters(f).toString();
|
||||
const { epoch } = useStatus();
|
||||
const { users } = useData();
|
||||
const [items, setItems] = useState<TimelineItem[]>([]);
|
||||
const [next, setNext] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
const [newIds, setNewIds] = useState<Set<string>>(() => new Set());
|
||||
const [matches, setMatches] = useState<MatchSummary[]>([]);
|
||||
const [detail, setDetail] = useState<MatchDetail | null>(null);
|
||||
const req = useRef(0);
|
||||
const [reload, setReload] = useState(0);
|
||||
const itemsRef = useRef(items);
|
||||
itemsRef.current = items;
|
||||
const scrollRef = useRef<HTMLElement>(null);
|
||||
const sentinel = useRef<HTMLDivElement>(null);
|
||||
|
||||
const update = useCallback((p: Partial<Filters>) => setParams(writeFilters({ ...parseFilters(params), ...p })), [params, setParams]);
|
||||
|
||||
// 첫 페이지
|
||||
useEffect(() => {
|
||||
const my = ++req.current;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setItems([]);
|
||||
setNext(null);
|
||||
scrollRef.current?.scrollTo({ top: 0 });
|
||||
api
|
||||
.timeline({ ...toQuery(f), limit: 100 })
|
||||
.then((p) => {
|
||||
if (my !== req.current) return;
|
||||
setItems(p.items);
|
||||
setNext(p.next);
|
||||
})
|
||||
.catch((e) => my === req.current && setError(e))
|
||||
.finally(() => my === req.current && setLoading(false));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [key, epoch, reload]);
|
||||
|
||||
const loadMore = useCallback(() => {
|
||||
if (!next || loading) return;
|
||||
const my = req.current;
|
||||
setLoading(true);
|
||||
api
|
||||
.timeline({ ...toQuery(f), cursor: next, limit: 100 })
|
||||
.then((p) => {
|
||||
if (my !== req.current) return;
|
||||
setItems((prev) => {
|
||||
const seen = new Set(prev.map((i) => i.id));
|
||||
return [...prev, ...p.items.filter((i) => !seen.has(i.id))];
|
||||
});
|
||||
setNext(p.next);
|
||||
})
|
||||
.catch((e) => my === req.current && setError(e))
|
||||
.finally(() => my === req.current && setLoading(false));
|
||||
}, [next, loading, f]);
|
||||
|
||||
// 무한 스크롤
|
||||
useEffect(() => {
|
||||
const el = sentinel.current;
|
||||
if (!el || !next) return;
|
||||
const io = new IntersectionObserver((es) => es.some((e) => e.isIntersecting) && loadMore(), { root: scrollRef.current, rootMargin: '600px' });
|
||||
io.observe(el);
|
||||
return () => io.disconnect();
|
||||
}, [loadMore, next]);
|
||||
|
||||
// 사이드바 경기 목록 · 선택한 경기 상세
|
||||
useEffect(() => {
|
||||
api
|
||||
.matches({ limit: 15, game: f.game === 'valorant' || f.game === 'lol' ? f.game : undefined })
|
||||
.then(setMatches)
|
||||
.catch(() => {});
|
||||
}, [f.game, epoch]);
|
||||
useEffect(() => {
|
||||
setDetail(null);
|
||||
if (!f.match) return;
|
||||
let alive = true;
|
||||
api
|
||||
.match(f.match)
|
||||
.then((d) => alive && setDetail(d))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [f.match, epoch]);
|
||||
|
||||
useEffect(() => player.setQueue(items), [items]);
|
||||
|
||||
// 이어듣기로 넘어간 발화를 화면에 보이게
|
||||
const curId = usePlayer((s) => (s.mode === 'single' ? s.item?.id ?? null : null));
|
||||
useEffect(() => {
|
||||
if (!curId) return;
|
||||
const el = scrollRef.current?.querySelector(`[data-id="${curId}"]`);
|
||||
el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||
}, [curId]);
|
||||
|
||||
const markNew = (id: string) => {
|
||||
setNewIds((s) => new Set(s).add(id));
|
||||
window.setTimeout(
|
||||
() =>
|
||||
setNewIds((s) => {
|
||||
const n = new Set(s);
|
||||
n.delete(id);
|
||||
return n;
|
||||
}),
|
||||
2500,
|
||||
);
|
||||
};
|
||||
|
||||
useLive((e) => {
|
||||
if (e.type === 'utterance.created' || e.type === 'event.created') {
|
||||
const it = e.data;
|
||||
if (!matchesFilter(it, f)) return;
|
||||
const prev = itemsRef.current;
|
||||
if (prev.some((p) => p.id === it.id)) return;
|
||||
if (order === 'asc' && next) return; // 시간순: 끝까지 불러온 뒤에만 아래에 붙인다
|
||||
setItems((cur) => (cur.some((p) => p.id === it.id) ? cur : order === 'desc' ? [it, ...cur] : [...cur, it]));
|
||||
markNew(it.id);
|
||||
if (it.kind === 'utterance') sfx('chime');
|
||||
else if (it.type === 'kill') sfx('kill');
|
||||
else if (it.type === 'round_end') sfx('round');
|
||||
} else if (e.type === 'utterance.updated') {
|
||||
setItems((prev) => prev.map((p) => (p.id === e.data.id ? e.data : p)));
|
||||
}
|
||||
});
|
||||
|
||||
const onUpdate = useCallback((it: UtteranceItem) => setItems((prev) => prev.map((p) => (p.id === it.id ? it : p))), []);
|
||||
const matchMap = useMemo(() => new Map(matches.map((m) => [m.id, m])), [matches]);
|
||||
if (detail && !matchMap.has(detail.id)) matchMap.set(detail.id, detail);
|
||||
|
||||
const toggleType = (t: TypeGroup) => {
|
||||
sfx('click');
|
||||
update({ types: f.types.includes(t) ? f.types.filter((x) => x !== t) : [...f.types, t] });
|
||||
};
|
||||
|
||||
const startScene = () => {
|
||||
const utts = items.filter((i): i is UtteranceItem => i.kind === 'utterance' && !!i.audio).sort((a, b) => a.ts - b.ts);
|
||||
if (!utts.length) return;
|
||||
const sel = player.state.item;
|
||||
const startTs = sel && utts.some((u) => u.id === sel.id) ? sel.ts : utts[0].ts;
|
||||
const end = Math.max(...utts.map((u) => u.endTs));
|
||||
const m = f.match ? matchMap.get(f.match) : undefined;
|
||||
player.startScene({ start: startTs - 500, end: end + 300, label: `${m?.map.name ?? '경기'} · ${fmtReal(startTs)}부터`, items: utts });
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="tl-main">
|
||||
<Sidebar f={f} update={update} users={users} matches={matches} detail={detail} />
|
||||
<section className="tl" ref={scrollRef}>
|
||||
<MobileFilters f={f} update={update} users={users} matches={matches} />
|
||||
<div className="filters">
|
||||
<button className={`chip${f.types.length === 0 ? ' on' : ''}`} onClick={() => update({ types: [] })}>
|
||||
전체
|
||||
</button>
|
||||
{TYPE_GROUPS.map((t) => (
|
||||
<button key={t.id} className={`chip${f.types.includes(t.id) ? ' on' : ''}`} onClick={() => toggleType(t.id)}>
|
||||
<span aria-hidden>{t.icon}</span> {t.label}
|
||||
</button>
|
||||
))}
|
||||
<span className="grow" />
|
||||
{f.match && (
|
||||
<button className="chip scene-btn" onClick={startScene} title="불러온 발화를 실제 시각 순서대로 겹쳐서 재생합니다">
|
||||
<IWaves width={14} height={14} /> 현장 모드
|
||||
</button>
|
||||
)}
|
||||
<button className="chip" onClick={() => update({ order: order === 'desc' ? 'asc' : 'desc' })} title="정렬 순서">
|
||||
{order === 'desc' ? '최신순 ↓' : '시간순 ↑'}
|
||||
</button>
|
||||
</div>
|
||||
{(f.q || f.from || f.to) && (
|
||||
<div className="active-filters">
|
||||
{f.q && (
|
||||
<button className="chip on-soft" onClick={() => update({ q: '' })}>
|
||||
“{f.q}” 검색 ✕
|
||||
</button>
|
||||
)}
|
||||
{(f.from || f.to) && (
|
||||
<button className="chip on-soft" onClick={() => update({ from: undefined, to: undefined })}>
|
||||
기간 지정 ✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="rows">
|
||||
<TimelineRows items={items} matches={matchMap} newIds={newIds} onUpdate={onUpdate} />
|
||||
</div>
|
||||
{error != null && <ErrorBox error={error} onRetry={() => setReload((n) => n + 1)} />}
|
||||
{!loading && !error && items.length === 0 && <div className="empty">조건에 맞는 기록이 없습니다.</div>}
|
||||
{loading && <Spinner />}
|
||||
{!loading && !next && items.length > 0 && <div className="list-end">{order === 'desc' ? '가장 오래된 기록입니다' : '마지막 기록입니다'}</div>}
|
||||
<div ref={sentinel} className="sentinel" />
|
||||
</section>
|
||||
<RightPanel items={items} detail={detail} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
200
site/web/src/pages/UserPages.tsx
Normal file
@@ -0,0 +1,200 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import type { GameType, MatchSummary, User, UserProfile } from '@gvr/shared';
|
||||
import { api } from '../lib/api';
|
||||
import { useStatus } from '../store/app';
|
||||
import { fmtDuration, fmtWhen } from '../lib/format';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { Avatar, ErrorBox, Spinner } from '../components/common';
|
||||
import { MatchItem } from './Sidebar';
|
||||
|
||||
function useLoad<T>(fn: () => Promise<T>, deps: unknown[]) {
|
||||
const { epoch } = useStatus();
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [err, setErr] = useState<unknown>(null);
|
||||
const [n, setN] = useState(0);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setErr(null);
|
||||
fn()
|
||||
.then((d) => alive && setData(d))
|
||||
.catch((e) => alive && setErr(e));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [...deps, epoch, n]);
|
||||
return { data, err, retry: () => setN((x) => x + 1) };
|
||||
}
|
||||
|
||||
export function UsersPage() {
|
||||
const { data, err, retry } = useLoad<User[]>(() => api.users(), []);
|
||||
if (err) return <main className="page-pad"><ErrorBox error={err} onRetry={retry} /></main>;
|
||||
if (!data) return <main className="page-pad"><Spinner /></main>;
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<h2 className="page-h h">유저</h2>
|
||||
<div className="user-grid">
|
||||
{data.map((u) => (
|
||||
<Link key={u.id} to={`/users/${u.id}`} className="user-card" style={{ borderTopColor: u.color }} onClick={() => sfx('click')}>
|
||||
<Avatar user={u} size={52} />
|
||||
<div>
|
||||
<b style={{ color: u.color }}>{u.name}</b>
|
||||
<div className="dim small">{u.riot.map((r) => r.riotId).join(' · ') || 'Riot 계정 연결 안 됨'}</div>
|
||||
</div>
|
||||
{u.excluded && <span className="badge b-excl">녹음 제외</span>}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function MatchesPage() {
|
||||
const [game, setGame] = useState<GameType | null>(null);
|
||||
const nav = useNavigate();
|
||||
const { data, err, retry } = useLoad<MatchSummary[]>(() => api.matches({ limit: 50, game: game ?? undefined }), [game]);
|
||||
const groups = useMemo(() => {
|
||||
const g = new Map<string, MatchSummary[]>();
|
||||
for (const m of data ?? []) {
|
||||
const d = fmtWhen(m.startedAt).split(' ')[0];
|
||||
g.set(d, [...(g.get(d) ?? []), m]);
|
||||
}
|
||||
return [...g];
|
||||
}, [data]);
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<div className="page-h-row">
|
||||
<h2 className="page-h h">경기</h2>
|
||||
<div className="chips-wrap">
|
||||
<button className={`chip${!game ? ' on' : ''}`} onClick={() => setGame(null)}>
|
||||
전체
|
||||
</button>
|
||||
<button className={`chip val${game === 'valorant' ? ' on' : ''}`} onClick={() => setGame('valorant')}>
|
||||
발로란트
|
||||
</button>
|
||||
<button className={`chip lol${game === 'lol' ? ' on' : ''}`} onClick={() => setGame('lol')}>
|
||||
롤
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{err != null && <ErrorBox error={err} onRetry={retry} />}
|
||||
{!data && !err && <Spinner />}
|
||||
{data && data.length === 0 && <div className="empty">경기 기록이 없습니다.</div>}
|
||||
{groups.map(([day, ms]) => (
|
||||
<section key={day} className="match-day">
|
||||
<h4>{day}</h4>
|
||||
<div className="match-cards">
|
||||
{ms.map((m) => (
|
||||
<MatchItem key={m.id} m={m} onClick={() => nav(`/matches/${encodeURIComponent(m.id)}`)} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function WordCloud({ words, color }: { words: { w: string; n: number }[]; color: string }) {
|
||||
const max = words[0]?.n ?? 1;
|
||||
const shuffled = useMemo(() => [...words].sort((a, b) => (a.w < b.w ? -1 : 1)), [words]);
|
||||
return (
|
||||
<div className="cloud">
|
||||
{shuffled.map((x) => {
|
||||
const r = x.n / max;
|
||||
return (
|
||||
<Link key={x.w} to={`/?q=${encodeURIComponent(x.w)}`} style={{ fontSize: 13 + r * 22, opacity: 0.45 + r * 0.55, color: r > 0.6 ? color : undefined }} data-tip={`${x.n}번 · 눌러서 검색`}>
|
||||
{x.w}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function UserPage() {
|
||||
const { id = '' } = useParams();
|
||||
const { data, err, retry } = useLoad<UserProfile>(() => api.user(id), [id]);
|
||||
if (err) return <main className="page-pad"><ErrorBox error={err} onRetry={retry} /></main>;
|
||||
if (!data || data.user.id !== id) return <main className="page-pad"><Spinner /></main>;
|
||||
const { user, stats, matches } = data;
|
||||
const top = stats.topWords.slice(0, 10);
|
||||
const max = top[0]?.n ?? 1;
|
||||
const wins = matches.filter((m) => m.win).length;
|
||||
return (
|
||||
<main className="page-pad user-page">
|
||||
<div className="user-hero" style={{ ['--uc' as string]: user.color }}>
|
||||
<Avatar user={user} size={76} />
|
||||
<div>
|
||||
<h2 className="h" style={{ color: user.color }}>
|
||||
{user.name} {user.excluded && <span className="badge b-excl">녹음 제외</span>}
|
||||
</h2>
|
||||
<div className="riot">
|
||||
{user.riot.length ? user.riot.map((r) => <span key={r.puuid} className="chip">🎮 {r.riotId}</span>) : <span className="dim">연결된 Riot 계정 없음</span>}
|
||||
</div>
|
||||
</div>
|
||||
<Link className="btn" to={`/?users=${user.id}`}>
|
||||
이 유저 대화만 보기 →
|
||||
</Link>
|
||||
</div>
|
||||
<div className="tiles">
|
||||
<div className="tile">
|
||||
<span>말한 시간</span>
|
||||
<b className="h">{fmtDuration(stats.talkMs)}</b>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<span>발화 수</span>
|
||||
<b className="h">{stats.count.toLocaleString()}개</b>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<span>평균 발화 길이</span>
|
||||
<b className="h">{stats.count ? (stats.talkMs / stats.count / 1000).toFixed(1) : 0}초</b>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<span>함께한 경기</span>
|
||||
<b className="h">
|
||||
{matches.length}판 <small className="dim">{matches.length ? `${wins}승 ${matches.length - wins}패` : ''}</small>
|
||||
</b>
|
||||
</div>
|
||||
</div>
|
||||
<div className="user-grid2">
|
||||
<section className="panel">
|
||||
<h4>
|
||||
<span>자주 쓰는 단어</span>
|
||||
</h4>
|
||||
{top.length === 0 ? (
|
||||
<div className="dim small">아직 기록이 없습니다</div>
|
||||
) : (
|
||||
<>
|
||||
<WordCloud words={stats.topWords} color={user.color} />
|
||||
<div className="wordbars">
|
||||
{top.map((w) => (
|
||||
<div key={w.w} className="wb" data-tip={`${w.w} · ${w.n}번`}>
|
||||
<span className="wb-w">{w.w}</span>
|
||||
<span className="bar">
|
||||
<i style={{ width: `${(w.n / max) * 100}%`, background: user.color }} />
|
||||
</span>
|
||||
<span className="mono dim">{w.n}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
<section className="panel">
|
||||
<h4>
|
||||
<span>연결된 Riot 계정 경기</span>
|
||||
</h4>
|
||||
<div className="mlist">
|
||||
{matches.length === 0 && <div className="dim small">경기 기록 없음</div>}
|
||||
{matches.map((m) => (
|
||||
<Link key={m.id} to={`/matches/${encodeURIComponent(m.id)}`} className="mlink">
|
||||
<MatchItem m={m} />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
355
site/web/src/pages/ValorantMatch.tsx
Normal file
@@ -0,0 +1,355 @@
|
||||
import { useEffect, useMemo, useRef, type MouseEvent } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { ChatData, EventItem, KillData, MatchDetail, MatchPlayer, MatchRound, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { player, usePlayer } from '../store/player';
|
||||
import { useAuth, useData } from '../store/app';
|
||||
import { useReducedMotion } from '../store/settings';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { toUV, roundResultKo, CHANNEL_KO } from '../lib/game';
|
||||
import { fmtClock, realTip } from '../lib/format';
|
||||
import { CharIcon, PName, Panel } from '../components/common';
|
||||
import { UtteranceRow } from '../components/UtteranceRow';
|
||||
import { KillLine, SeparatorRow } from '../components/EventRow';
|
||||
import { IPlay, IWaves } from '../components/Icons';
|
||||
import { matchMeta } from './MatchPage';
|
||||
|
||||
const BUY_MS = 30000;
|
||||
/** "R7 · 0:38" → "0:38" */
|
||||
const short = (p: string) => p.replace(/^R\d+\s*·\s*/, '');
|
||||
|
||||
function RoundStrip({ rounds, sel, onSelect }: { rounds: MatchRound[]; sel: number; onSelect: (n: number) => void }) {
|
||||
return (
|
||||
<div className="rounds" role="tablist" aria-label="라운드">
|
||||
{rounds.map((r) => (
|
||||
<button
|
||||
key={r.num}
|
||||
role="tab"
|
||||
aria-selected={r.num === sel}
|
||||
className={`rb ${r.win ? 'win' : 'loss'}${r.num === sel ? ' sel' : ''}${r.num === 13 ? ' half' : ''}`}
|
||||
onClick={() => onSelect(r.num)}
|
||||
data-tip={`R${r.num} ${r.win ? '승리' : '패배'} · ${roundResultKo(r.result)} · ${r.score.ally}:${r.score.enemy}`}
|
||||
>
|
||||
{r.num}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ValMap({ m, round, events }: { m: MatchDetail; round: MatchRound; events: EventItem[] }) {
|
||||
const ts = usePlayer((s) => s.sceneTs);
|
||||
const reduce = useReducedMotion();
|
||||
const inRound = ts != null && ts >= round.startedAt && ts <= round.endedAt + 2000;
|
||||
const kills = events.filter((e) => e.type === 'kill');
|
||||
const spikes = events.filter((e) => e.type === 'spike');
|
||||
const span = round.endedAt - round.startedAt;
|
||||
const progress = inRound ? Math.min(1, (ts! - round.startedAt) / span) : 0;
|
||||
const seek = (e: MouseEvent<HTMLDivElement>) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
const off = ((e.clientX - r.left) / r.width) * span;
|
||||
player.startScene({ start: round.startedAt, end: round.endedAt, label: `ROUND ${round.num} 현장 모드`, items: m.utterances });
|
||||
player.seekScene(off);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<div className="map-area">
|
||||
{m.map.image ? (
|
||||
<div className="map-sq">
|
||||
<img src={m.map.image} alt={`${m.map.name} 미니맵`} />
|
||||
{spikes.map((e) => {
|
||||
const uv = toUV(m, e.data.location);
|
||||
return uv ? (
|
||||
<div key={e.id} className="mk spike" style={{ left: `${uv.u * 100}%`, top: `${uv.v * 100}%` }} data-tip={`${short(e.time.primary)} 스파이크 설치`}>
|
||||
설치
|
||||
</div>
|
||||
) : null;
|
||||
})}
|
||||
{kills.map((e) => {
|
||||
const d = e.data as KillData;
|
||||
const uv = toUV(m, d.location);
|
||||
if (!uv) return null;
|
||||
const past = !inRound || e.ts <= ts!;
|
||||
const recent = inRound && ts! - e.ts >= 0 && ts! - e.ts < 3500;
|
||||
const ally = d.ally ?? !!d.killer?.userId;
|
||||
return (
|
||||
<div
|
||||
key={e.id}
|
||||
className={`mk kill ${ally ? 'ally' : 'enemy'}${past ? '' : ' future'}${recent ? ' recent' : ''}`}
|
||||
style={{ left: `${uv.u * 100}%`, top: `${uv.v * 100}%` }}
|
||||
data-tip={`${short(e.time.primary)} ${d.killer?.name ?? '?'} → ${d.victim.name}${d.weapon ? ` (${d.weapon.name})` : ''}`}
|
||||
>
|
||||
{recent && (
|
||||
<motion.span className="mk-pop" initial={reduce ? false : { scale: 0.3, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}>
|
||||
<CharIcon c={d.victim.character} size={30} />
|
||||
</motion.span>
|
||||
)}
|
||||
<span className="x">✕</span>
|
||||
{recent && !reduce && <span className="ping" />}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="map-missing">미니맵 이미지 없음</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="timebar">
|
||||
<span className="mono muted">{inRound ? fmtClock(Math.max(0, ts! - round.startedAt - BUY_MS)) : '0:00'}</span>
|
||||
<div className="tb" onClick={seek} title="눌러서 이 시점부터 현장 모드로 듣기">
|
||||
<i style={{ width: `${progress * 100}%` }} />
|
||||
<span className="buy" style={{ width: `${(BUY_MS / span) * 100}%` }} />
|
||||
{kills.map((e) => (
|
||||
<b key={e.id} className={(e.data as KillData).ally ? 'ally' : ''} style={{ left: `${((e.ts - round.startedAt) / span) * 100}%` }} />
|
||||
))}
|
||||
</div>
|
||||
<span className="mono muted">{fmtClock(span - BUY_MS)}</span>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function FeedRow({ it, meId }: { it: TimelineItem; meId: string | null }) {
|
||||
const active = usePlayer((s) => s.sceneTs != null && it.kind === 'event' && s.sceneTs - it.ts >= 0 && s.sceneTs - it.ts < 2500);
|
||||
if (it.kind === 'utterance') return <UtteranceRow item={it} variant="compact" timeText={short(it.time.primary)} />;
|
||||
const e = it;
|
||||
if (e.type === 'round_end') return <SeparatorRow e={e} />;
|
||||
if (e.type === 'kill') {
|
||||
const d = e.data as KillData;
|
||||
return (
|
||||
<div className={`k${d.killer?.userId && d.killer.userId === meId ? ' me' : ''}${d.ally === false ? ' death' : ''}${active ? ' flash' : ''}`} data-tip={realTip(e.ts)}>
|
||||
<span className="t mono">{short(e.time.primary)}</span>
|
||||
<KillLine d={d} game="valorant" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (e.type === 'chat') {
|
||||
const d = e.data as ChatData;
|
||||
return (
|
||||
<div className="l chat-l" data-tip={realTip(e.ts)}>
|
||||
<span className="t mono">{short(e.time.primary)}</span>
|
||||
<div className="lb">
|
||||
<span className="ctag ch-team">💬 {CHANNEL_KO[d.channel] ?? d.channel}</span> <PName p={d.sender} /> {d.text}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (e.type === 'spike')
|
||||
return (
|
||||
<div className="l spike-l">
|
||||
<span className="t mono">{short(e.time.primary)}</span>
|
||||
<div className="lb">
|
||||
<span className="spike-ic">◆</span> 스파이크 설치 {e.data.site ? `· ${e.data.site} 사이트` : ''}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
function Scoreboard({ players, rounds }: { players: MatchPlayer[]; rounds: number }) {
|
||||
const { userById } = useData();
|
||||
const acs = (p: MatchPlayer) => (rounds && p.score != null ? Math.round(p.score / rounds) : null);
|
||||
const top = Math.max(...players.map((p) => acs(p) ?? 0));
|
||||
const team = (ally: boolean) => players.filter((p) => p.ally === ally).sort((a, b) => (acs(b) ?? 0) - (acs(a) ?? 0));
|
||||
return (
|
||||
<table className="score-tbl">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>플레이어</th>
|
||||
<th>K</th>
|
||||
<th>D</th>
|
||||
<th>A</th>
|
||||
<th>ACS</th>
|
||||
</tr>
|
||||
</thead>
|
||||
{[true, false].map((ally) => (
|
||||
<tbody key={String(ally)} className={ally ? 'ally' : 'enemy'}>
|
||||
<tr className="team-row">
|
||||
<td colSpan={5}>{ally ? '우리 팀' : '상대 팀'}</td>
|
||||
</tr>
|
||||
{team(ally).map((p) => {
|
||||
const u = userById(p.userId);
|
||||
return (
|
||||
<tr key={p.puuid} className={u ? 'linked' : ''} style={u ? { background: `${u.color}14` } : undefined}>
|
||||
<td>
|
||||
<CharIcon c={p.character} size={22} />{' '}
|
||||
{u ? <b style={{ color: u.color }}>{u.name}</b> : <span>{p.tag ? `${p.name}#${p.tag}` : p.name}</span>} <span className="dim">{p.character.name}</span>
|
||||
</td>
|
||||
<td>{p.kills}</td>
|
||||
<td>{p.deaths}</td>
|
||||
<td>{p.assists}</td>
|
||||
<td className={acs(p) === top ? 'accent' : ''}>{acs(p) ?? '—'}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
))}
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
function Economy({ m, sel, onSelect }: { m: MatchDetail; sel: number; onSelect: (n: number) => void }) {
|
||||
const allyIds = new Set(m.players.filter((p) => p.ally).map((p) => p.puuid));
|
||||
const data = (m.rounds ?? []).map((r) => {
|
||||
let total = 0;
|
||||
let spent = 0;
|
||||
for (const [id, e] of Object.entries(r.economy ?? {})) {
|
||||
if (!allyIds.has(id)) continue;
|
||||
total += e.spent + e.remaining;
|
||||
spent += e.spent;
|
||||
}
|
||||
return { r, total, spent };
|
||||
});
|
||||
const max = Math.max(1, ...data.map((d) => d.total));
|
||||
if (!data.some((d) => d.total)) return <div className="dim small">경제 기록 없음</div>;
|
||||
return (
|
||||
<>
|
||||
<div className="eco" role="list">
|
||||
{data.map(({ r, total, spent }) => (
|
||||
<button
|
||||
key={r.num}
|
||||
role="listitem"
|
||||
className={`eco-bar${r.num === sel ? ' sel' : ''}`}
|
||||
onClick={() => onSelect(r.num)}
|
||||
data-tip={`R${r.num} · 팀 크레딧 ${total.toLocaleString()} · 사용 ${spent.toLocaleString()}`}
|
||||
>
|
||||
<i style={{ height: `${(total / max) * 100}%` }}>
|
||||
<em style={{ height: `${total ? (spent / total) * 100 : 0}%` }} />
|
||||
</i>
|
||||
<span className={r.win ? 'w' : 'l'} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="eco-legend dim">
|
||||
막대 높이 = 라운드 시작 시 팀 보유 크레딧 · 진한 부분 = 사용 · 아래 점 = <span className="mint">승</span>/패
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ValorantMatch({ m }: { m: MatchDetail }) {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const { auth } = useAuth();
|
||||
const meId = auth.status === 'ok' ? auth.me.user.id : null;
|
||||
const rounds = m.rounds ?? [];
|
||||
const selNum = Number(params.get('round')) || rounds[0]?.num || 1;
|
||||
const round = rounds.find((r) => r.num === selNum) ?? rounds[0];
|
||||
const meta = matchMeta(m);
|
||||
const feedRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const select = (n: number) => {
|
||||
if (n === selNum) return;
|
||||
sfx('round');
|
||||
const p = new URLSearchParams(params);
|
||||
p.set('round', String(n));
|
||||
setParams(p, { replace: true });
|
||||
};
|
||||
|
||||
// 재생이 다음 라운드로 넘어가면 라운드 선택도 따라간다
|
||||
const playRound = usePlayer((s) => {
|
||||
if (s.sceneTs == null || s.sceneTs < m.startedAt || (m.endedAt && s.sceneTs > m.endedAt)) return null;
|
||||
return rounds.find((r) => s.sceneTs! >= r.startedAt && s.sceneTs! <= r.endedAt + 4000)?.num ?? null;
|
||||
});
|
||||
useEffect(() => {
|
||||
if (playRound && playRound !== selNum) select(playRound);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [playRound]);
|
||||
|
||||
const roundItems = useMemo(() => {
|
||||
if (!round) return [];
|
||||
const inR = (t: number) => t >= round.startedAt && t <= round.endedAt + 1000;
|
||||
return [...m.utterances.filter((u) => inR(u.ts)), ...m.events.filter((e) => inR(e.ts) && e.type !== 'match_end' && e.type !== 'match_start')].sort((a, b) => a.ts - b.ts);
|
||||
}, [m, round]);
|
||||
const roundEvents = roundItems.filter((i): i is EventItem => i.kind === 'event');
|
||||
const roundUtts = roundItems.filter((i): i is UtteranceItem => i.kind === 'utterance');
|
||||
|
||||
const curId = usePlayer((s) => (s.mode === 'single' ? s.item?.id ?? null : null));
|
||||
useEffect(() => {
|
||||
if (curId) feedRef.current?.querySelector(`[data-id="${curId}"]`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||
}, [curId]);
|
||||
|
||||
if (!round) return <main className="page-pad">라운드 기록이 없습니다.</main>;
|
||||
|
||||
const playRoundAll = () => {
|
||||
const first = roundUtts.find((u) => u.audio);
|
||||
if (first) void player.play(first);
|
||||
};
|
||||
const scene = () => player.startScene({ start: round.startedAt, end: round.endedAt, label: `${m.map.name} · ROUND ${round.num}`, items: m.utterances });
|
||||
|
||||
return (
|
||||
<main className="match val">
|
||||
<div className="mtop">
|
||||
{m.map.image && <img className="map-thumb" src={m.map.image} alt="" />}
|
||||
<div>
|
||||
<div className="eyebrow">MATCH DETAIL · VALORANT</div>
|
||||
<div className="mtitle h">
|
||||
{m.map.name}{' '}
|
||||
{m.score && (
|
||||
<span className="score">
|
||||
<span className="a">{m.score.ally}</span> <span className="dim colon">:</span> <span className="b">{m.score.enemy}</span>
|
||||
</span>
|
||||
)}
|
||||
{m.win != null && <span className={`res-badge ${m.win ? 'win' : 'loss'}`}>{m.win ? '승리' : '패배'}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="meta">
|
||||
{m.mode} · {meta.when} 시작 · {meta.dur}
|
||||
<br />
|
||||
대화 {m.utterances.length}개 · 킬 이벤트 {meta.kills}개 · 채팅 {meta.chats}개
|
||||
</div>
|
||||
<RoundStrip rounds={rounds} sel={round.num} onSelect={select} />
|
||||
</div>
|
||||
<div className="mgrid">
|
||||
<Panel
|
||||
className="map-panel"
|
||||
title={`ROUND ${round.num} · 킬 위치 (재생 시점 연동)`}
|
||||
right={`${m.map.name} 미니맵 · 게임 좌표 변환`}
|
||||
>
|
||||
<ValMap m={m} round={round} events={roundEvents} />
|
||||
<div className="map-legend dim">
|
||||
<b className="mint">✕</b> 우리 팀이 처치 <b className="accent">✕</b> 상대 팀이 처치 <span className="spike-ic">◆</span> 스파이크
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel
|
||||
className="feed-panel"
|
||||
title={`ROUND ${round.num} · 대화 + 킬피드`}
|
||||
right={
|
||||
<span className="ph-btns">
|
||||
<button className="mini-btn" onClick={playRoundAll}>
|
||||
<IPlay width={11} height={11} /> 라운드 이어듣기
|
||||
</button>
|
||||
<button className="mini-btn" onClick={scene} title="겹친 발화를 실제 순서대로 섞어서 재생">
|
||||
<IWaves width={12} height={12} /> 현장 모드
|
||||
</button>
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="feed scroll" ref={feedRef}>
|
||||
<div className="round-head">
|
||||
<span className={`pill ${round.win ? 'win' : 'loss'}`}>R{round.num}</span>
|
||||
<span>{round.win ? '승리' : '패배'} · {roundResultKo(round.result)}</span>
|
||||
<span className="mono score">
|
||||
{round.score.ally} : {round.score.enemy}
|
||||
</span>
|
||||
</div>
|
||||
{roundItems.length === 0 && <div className="dim small">이 라운드에는 기록이 없습니다</div>}
|
||||
{roundItems.map((it) => (
|
||||
<div key={it.id} data-id={it.id}>
|
||||
<FeedRow it={it} meId={meId} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel className="sb-panel" title="스코어보드">
|
||||
<div className="scroll">
|
||||
<Scoreboard players={m.players} rounds={rounds.length} />
|
||||
<h4 className="sub-h">
|
||||
<span>라운드별 우리 팀 크레딧</span>
|
||||
</h4>
|
||||
<Economy m={m} sel={round.num} onSelect={select} />
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
151
site/web/src/store/app.tsx
Normal file
@@ -0,0 +1,151 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import type { DeviceStatus, LiveEvent, Overview, User } from '@gvr/shared';
|
||||
import { api, onApiSignal, type Me } from '../lib/api';
|
||||
import { live, type LiveConn } from '../lib/live';
|
||||
|
||||
// ── 로그인 ───────────────────────────────────────────
|
||||
type AuthState = { status: 'loading' } | { status: 'anon' } | { status: 'not_member' } | { status: 'ok'; me: Me };
|
||||
const AuthCtx = createContext<{ auth: AuthState; logout: () => void }>({ auth: { status: 'loading' }, logout: () => {} });
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [auth, setAuth] = useState<AuthState>({ status: 'loading' });
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api
|
||||
.me()
|
||||
.then((r) => alive && setAuth(r.ok ? { status: 'ok', me: r.me } : { status: r.reason }))
|
||||
.catch(() => alive && setAuth({ status: 'anon' }));
|
||||
const off = onApiSignal((s) => {
|
||||
if (s === 'unauthorized') setAuth({ status: 'anon' });
|
||||
if (s === 'not_member') setAuth({ status: 'not_member' });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
off();
|
||||
};
|
||||
}, []);
|
||||
const logout = useCallback(() => {
|
||||
void api.logout().finally(() => setAuth({ status: 'anon' }));
|
||||
}, []);
|
||||
return <AuthCtx.Provider value={{ auth, logout }}>{children}</AuthCtx.Provider>;
|
||||
}
|
||||
export const useAuth = () => useContext(AuthCtx);
|
||||
|
||||
// ── 게임 PC 연결 상태 + 실시간 이벤트 ─────────────────
|
||||
interface StatusValue {
|
||||
device: DeviceStatus | null;
|
||||
serverOk: boolean | null;
|
||||
conn: LiveConn;
|
||||
locked: boolean;
|
||||
/** 잠금이 풀릴 때마다 1씩 증가 → 페이지를 새로 불러오는 키 */
|
||||
epoch: number;
|
||||
recheck: () => Promise<void>;
|
||||
}
|
||||
const StatusCtx = createContext<StatusValue>(null as unknown as StatusValue);
|
||||
|
||||
type LiveFn = (e: LiveEvent) => void;
|
||||
const liveSubs = new Set<LiveFn>();
|
||||
/** 5장 실시간 이벤트 구독 */
|
||||
export function useLive(fn: LiveFn) {
|
||||
const ref = useRef(fn);
|
||||
ref.current = fn;
|
||||
useEffect(() => {
|
||||
const h: LiveFn = (e) => ref.current(e);
|
||||
liveSubs.add(h);
|
||||
return () => {
|
||||
liveSubs.delete(h);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
export function StatusProvider({ children }: { children: ReactNode }) {
|
||||
const [device, setDevice] = useState<DeviceStatus | null>(null);
|
||||
const [serverOk, setServerOk] = useState<boolean | null>(null);
|
||||
const [conn, setConn] = useState<LiveConn>(live.conn);
|
||||
const [epoch, setEpoch] = useState(0);
|
||||
|
||||
const recheck = useCallback(async () => {
|
||||
live.kick();
|
||||
try {
|
||||
const s = await api.status();
|
||||
setServerOk(true);
|
||||
setDevice(s.device);
|
||||
} catch {
|
||||
setServerOk(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void recheck();
|
||||
live.start();
|
||||
const offConn = live.onConn(setConn);
|
||||
const offMsg = live.onMessage((m) => {
|
||||
if (m.type === 'status') {
|
||||
setServerOk(true);
|
||||
setDevice(m.data.device);
|
||||
} else liveSubs.forEach((fn) => fn(m));
|
||||
});
|
||||
const offSig = onApiSignal((s) => {
|
||||
if (s === 'device_offline') setDevice((d) => ({ registered: d?.registered ?? true, online: false, name: d?.name ?? null, lastSeen: d?.lastSeen ?? null, version: d?.version ?? null }));
|
||||
});
|
||||
return () => {
|
||||
offConn();
|
||||
offMsg();
|
||||
offSig();
|
||||
live.stop();
|
||||
};
|
||||
}, [recheck]);
|
||||
|
||||
const locked = !!device && (!device.registered || !device.online);
|
||||
|
||||
// 잠겨 있는 동안 5초마다 상태 재확인 (WS 가 살아 있어도 이중 확인)
|
||||
useEffect(() => {
|
||||
if (!locked) return;
|
||||
const t = window.setInterval(() => void recheck(), 5000);
|
||||
return () => window.clearInterval(t);
|
||||
}, [locked, recheck]);
|
||||
|
||||
// 잠금 해제 → epoch 증가
|
||||
const wasLocked = useRef(false);
|
||||
useEffect(() => {
|
||||
if (wasLocked.current && !locked) setEpoch((e) => e + 1);
|
||||
wasLocked.current = locked;
|
||||
}, [locked]);
|
||||
|
||||
const value = useMemo(() => ({ device, serverOk, conn, locked, epoch, recheck }), [device, serverOk, conn, locked, epoch, recheck]);
|
||||
return <StatusCtx.Provider value={value}>{children}</StatusCtx.Provider>;
|
||||
}
|
||||
export const useStatus = () => useContext(StatusCtx);
|
||||
|
||||
// ── 개요 · 유저 ──────────────────────────────────────
|
||||
interface DataValue {
|
||||
overview: Overview | null;
|
||||
users: User[];
|
||||
userById: (id: string | undefined | null) => User | undefined;
|
||||
}
|
||||
const DataCtx = createContext<DataValue>({ overview: null, users: [], userById: () => undefined });
|
||||
|
||||
export function DataProvider({ children }: { children: ReactNode }) {
|
||||
const { epoch, locked } = useStatus();
|
||||
const [overview, setOverview] = useState<Overview | null>(null);
|
||||
useEffect(() => {
|
||||
if (locked) return;
|
||||
let alive = true;
|
||||
api
|
||||
.overview()
|
||||
.then((o) => alive && setOverview(o))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [epoch, locked]);
|
||||
useLive((e) => {
|
||||
if (e.type === 'users.updated') setOverview((o) => (o ? { ...o, users: e.data } : o));
|
||||
if (e.type === 'recording.state') setOverview((o) => (o ? { ...o, recording: e.data } : o));
|
||||
});
|
||||
const users = overview?.users ?? [];
|
||||
const map = useMemo(() => new Map(users.map((u) => [u.id, u])), [users]);
|
||||
const userById = useCallback((id: string | undefined | null) => (id ? map.get(id) : undefined), [map]);
|
||||
return <DataCtx.Provider value={{ overview, users, userById }}>{children}</DataCtx.Provider>;
|
||||
}
|
||||
export const useData = () => useContext(DataCtx);
|
||||
399
site/web/src/store/player.ts
Normal file
@@ -0,0 +1,399 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import type WaveSurfer from 'wavesurfer.js';
|
||||
import type { EventItem, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { audioCtx, dbToGain, playerOutput, resumeAudio } from '../lib/audio';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { settings } from './settings';
|
||||
|
||||
/**
|
||||
* 플레이어 엔진.
|
||||
* - single: 발화 하나를 <audio> 로 재생. MediaElementSource → GainNode(발화별 gainDb) → 리미터.
|
||||
* 재생 시 음량 정규화 설계: 조용한 사람은 gainDb 만큼 키워서 들린다.
|
||||
* - scene : "현장 모드". 구간 안 발화들을 실제 시각 순서대로 Web Audio 에 예약해 겹쳐서 재생.
|
||||
* sceneTs(현실 시각 ms 재생 위치)는 두 모드 공통이라 단어 강조 · 미니맵 연동이 같은 값을 쓴다.
|
||||
*/
|
||||
export interface SceneInfo {
|
||||
start: number;
|
||||
end: number;
|
||||
label: string;
|
||||
items: UtteranceItem[];
|
||||
}
|
||||
export interface PlayerState {
|
||||
mode: 'idle' | 'single' | 'scene';
|
||||
item: UtteranceItem | null;
|
||||
playing: boolean;
|
||||
loading: boolean;
|
||||
/** single: 파일 안 초 / scene: 구간 시작부터 초 */
|
||||
time: number;
|
||||
duration: number;
|
||||
sceneTs: number | null;
|
||||
scene: SceneInfo | null;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
export const DELETED_MSG = '음성 보관 기간(7일)이 지나 삭제됨';
|
||||
|
||||
interface SceneSlot {
|
||||
item: UtteranceItem;
|
||||
offset: number;
|
||||
buf: Promise<AudioBuffer | null> | null;
|
||||
pending: boolean;
|
||||
src: AudioBufferSourceNode | null;
|
||||
}
|
||||
|
||||
class Player {
|
||||
state: PlayerState = { mode: 'idle', item: null, playing: false, loading: false, time: 0, duration: 0, sceneTs: null, scene: null, message: null };
|
||||
private subs = new Set<() => void>();
|
||||
readonly el: HTMLAudioElement;
|
||||
private srcNode: MediaElementAudioSourceNode | null = null;
|
||||
private itemGain: GainNode | null = null;
|
||||
private ws: WaveSurfer | null = null;
|
||||
private loadedUrl: string | null = null;
|
||||
private token = 0;
|
||||
private raf = 0;
|
||||
private queue: UtteranceItem[] = [];
|
||||
private events: EventItem[] = [];
|
||||
private lastTs: number | null = null;
|
||||
// scene
|
||||
private slots: SceneSlot[] = [];
|
||||
private t0 = 0;
|
||||
private sceneElapsed = 0;
|
||||
private sceneRate = 1;
|
||||
private bufCache = new Map<string, Promise<AudioBuffer | null>>();
|
||||
|
||||
constructor() {
|
||||
this.el = new Audio();
|
||||
this.el.preload = 'auto';
|
||||
this.el.addEventListener('play', () => this.set({ playing: true }));
|
||||
this.el.addEventListener('playing', () => this.loop());
|
||||
this.el.addEventListener('pause', () => {
|
||||
if (this.state.mode === 'single') this.set({ playing: false });
|
||||
});
|
||||
this.el.addEventListener('ended', () => this.onEnded());
|
||||
let prev = settings.get();
|
||||
settings.subscribe(() => {
|
||||
const s = settings.get();
|
||||
if (s.rate !== prev.rate) this.applyRate(s.rate);
|
||||
if (s.normalize !== prev.normalize) this.applyGain();
|
||||
prev = s;
|
||||
});
|
||||
}
|
||||
|
||||
// ── 외부 구독 ──
|
||||
subscribe = (f: () => void) => {
|
||||
this.subs.add(f);
|
||||
return () => {
|
||||
this.subs.delete(f);
|
||||
};
|
||||
};
|
||||
getState = () => this.state;
|
||||
private set(p: Partial<PlayerState>) {
|
||||
this.state = { ...this.state, ...p };
|
||||
this.subs.forEach((f) => f());
|
||||
}
|
||||
|
||||
attachWave(ws: WaveSurfer | null) {
|
||||
this.ws = ws;
|
||||
this.loadedUrl = null;
|
||||
}
|
||||
|
||||
/** 현재 화면의 목록 (이어듣기 · ←/→ · 킬 효과음 기준) */
|
||||
setQueue(items: TimelineItem[]) {
|
||||
this.queue = items.filter((i): i is UtteranceItem => i.kind === 'utterance').sort((a, b) => a.ts - b.ts);
|
||||
this.events = items
|
||||
.filter((i): i is EventItem => i.kind === 'event' && (i.type === 'kill' || i.type === 'round_end' || i.type === 'multikill' || i.type === 'ace'))
|
||||
.sort((a, b) => a.ts - b.ts);
|
||||
}
|
||||
|
||||
private ensureGraph() {
|
||||
resumeAudio();
|
||||
if (this.srcNode) return;
|
||||
const ctx = audioCtx();
|
||||
this.srcNode = ctx.createMediaElementSource(this.el);
|
||||
this.itemGain = ctx.createGain();
|
||||
this.srcNode.connect(this.itemGain).connect(playerOutput());
|
||||
}
|
||||
|
||||
private gainFor(item: UtteranceItem | null) {
|
||||
if (!item?.audio || !settings.get().normalize) return 1;
|
||||
return dbToGain(item.audio.gainDb);
|
||||
}
|
||||
private applyGain() {
|
||||
if (this.itemGain) this.itemGain.gain.value = this.gainFor(this.state.item);
|
||||
}
|
||||
private applyRate(rate: number) {
|
||||
this.el.playbackRate = rate;
|
||||
if (this.state.mode === 'scene') {
|
||||
const was = this.state.playing;
|
||||
this.pauseScene();
|
||||
this.sceneRate = rate;
|
||||
if (was) this.resumeScene();
|
||||
}
|
||||
}
|
||||
|
||||
// ── single ──
|
||||
async play(item: UtteranceItem, seekSec = 0, opts: { auto?: boolean } = {}) {
|
||||
this.ensureGraph();
|
||||
if (this.state.mode === 'scene') this.stopScene();
|
||||
const my = ++this.token;
|
||||
const duration = (item.endTs - item.ts) / 1000;
|
||||
if (!item.audio) {
|
||||
this.el.pause();
|
||||
this.set({ mode: 'single', item, playing: false, loading: false, message: DELETED_MSG, time: 0, duration, sceneTs: item.ts, scene: null });
|
||||
return;
|
||||
}
|
||||
this.set({ mode: 'single', item, loading: true, message: null, time: seekSec, duration: item.audio.durationMs / 1000, sceneTs: item.ts + seekSec * 1000, scene: null });
|
||||
this.applyGain();
|
||||
const url = item.audio.url;
|
||||
if (this.loadedUrl !== url) {
|
||||
this.el.pause();
|
||||
try {
|
||||
if (this.ws) await this.ws.load(url);
|
||||
else this.el.src = url;
|
||||
this.loadedUrl = url;
|
||||
} catch {
|
||||
if (my !== this.token) return;
|
||||
this.set({ loading: false, playing: false, message: '음성을 불러오지 못했습니다' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (my !== this.token) return;
|
||||
this.el.playbackRate = settings.get().rate;
|
||||
try {
|
||||
this.el.currentTime = seekSec;
|
||||
await this.el.play();
|
||||
if (!opts.auto) sfx('play');
|
||||
} catch {
|
||||
if (my === this.token) this.set({ message: '재생할 수 없습니다' });
|
||||
}
|
||||
if (my === this.token) this.set({ loading: false });
|
||||
}
|
||||
|
||||
seekTo(item: UtteranceItem, sec: number) {
|
||||
if (this.state.mode === 'single' && this.state.item?.id === item.id && this.loadedUrl === item.audio?.url) {
|
||||
this.el.currentTime = sec;
|
||||
if (this.el.paused) void this.el.play();
|
||||
this.tick();
|
||||
return;
|
||||
}
|
||||
void this.play(item, sec);
|
||||
}
|
||||
|
||||
toggle() {
|
||||
const s = this.state;
|
||||
if (s.mode === 'single' && s.item) {
|
||||
if (!s.item.audio) return;
|
||||
if (this.el.paused) {
|
||||
resumeAudio();
|
||||
void this.el.play();
|
||||
sfx('play');
|
||||
} else this.el.pause();
|
||||
} else if (s.mode === 'scene') {
|
||||
if (s.playing) this.pauseScene();
|
||||
else {
|
||||
if (this.sceneElapsed >= (s.scene!.end - s.scene!.start)) this.sceneElapsed = 0;
|
||||
this.resumeScene();
|
||||
}
|
||||
} else if (this.queue.length) {
|
||||
void this.play(this.queue.find((q) => q.audio) ?? this.queue[0]);
|
||||
}
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.token++;
|
||||
this.el.pause();
|
||||
this.stopScene();
|
||||
this.set({ mode: 'idle', item: null, playing: false, loading: false, sceneTs: null, scene: null, message: null, time: 0 });
|
||||
}
|
||||
|
||||
private neighbor(dir: 1 | -1): UtteranceItem | null {
|
||||
const cur = this.state.item;
|
||||
const q = this.queue.filter((i) => i.audio || i === cur);
|
||||
if (!q.length) return null;
|
||||
if (!cur) return dir === 1 ? q[0] : q[q.length - 1];
|
||||
const idx = q.findIndex((i) => i.id === cur.id);
|
||||
if (idx >= 0) return q[idx + dir] ?? null;
|
||||
return dir === 1 ? q.find((i) => i.ts > cur.ts) ?? null : [...q].reverse().find((i) => i.ts < cur.ts) ?? null;
|
||||
}
|
||||
next() {
|
||||
const n = this.neighbor(1);
|
||||
if (n) void this.play(n);
|
||||
}
|
||||
prev() {
|
||||
if (this.state.mode === 'single' && this.el.currentTime > 1.5) {
|
||||
this.el.currentTime = 0;
|
||||
return;
|
||||
}
|
||||
const p = this.neighbor(-1);
|
||||
if (p) void this.play(p);
|
||||
}
|
||||
private onEnded() {
|
||||
if (this.state.mode !== 'single') return;
|
||||
this.tick();
|
||||
if (settings.get().continuous) {
|
||||
const n = this.neighbor(1);
|
||||
if (n) {
|
||||
void this.play(n, 0, { auto: true });
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.set({ playing: false });
|
||||
}
|
||||
|
||||
// ── scene (현장 모드) ──
|
||||
startScene(scene: SceneInfo) {
|
||||
this.ensureGraph();
|
||||
this.token++;
|
||||
this.el.pause();
|
||||
this.stopScene();
|
||||
const items = scene.items.filter((i) => i.audio && i.ts < scene.end && i.endTs > scene.start).sort((a, b) => a.ts - b.ts);
|
||||
this.slots = items.map((item) => ({ item, offset: item.ts - scene.start, buf: null, pending: false, src: null }));
|
||||
this.sceneRate = settings.get().rate;
|
||||
this.sceneElapsed = 0;
|
||||
this.set({ mode: 'scene', item: null, scene: { ...scene, items }, message: items.length ? null : '이 구간에는 들을 수 있는 발화가 없습니다', time: 0, duration: (scene.end - scene.start) / 1000, sceneTs: scene.start });
|
||||
sfx('play');
|
||||
this.resumeScene(0.15);
|
||||
}
|
||||
seekScene(ms: number) {
|
||||
if (this.state.mode !== 'scene') return;
|
||||
const was = this.state.playing;
|
||||
this.pauseScene();
|
||||
this.sceneElapsed = Math.max(0, ms);
|
||||
this.set({ time: this.sceneElapsed / 1000, sceneTs: this.state.scene!.start + this.sceneElapsed });
|
||||
if (was) this.resumeScene();
|
||||
}
|
||||
private resumeScene(lead = 0.03) {
|
||||
const ctx = audioCtx();
|
||||
this.t0 = ctx.currentTime + lead - this.sceneElapsed / 1000 / this.sceneRate;
|
||||
this.set({ playing: true });
|
||||
this.loop();
|
||||
}
|
||||
private pauseScene() {
|
||||
if (this.state.mode !== 'scene') return;
|
||||
if (this.state.playing) this.sceneElapsed = this.elapsed();
|
||||
for (const s of this.slots) {
|
||||
try {
|
||||
s.src?.stop();
|
||||
} catch {
|
||||
/* 이미 끝남 */
|
||||
}
|
||||
s.src = null;
|
||||
s.pending = false;
|
||||
}
|
||||
this.set({ playing: false });
|
||||
}
|
||||
private stopScene() {
|
||||
this.pauseScene();
|
||||
this.slots = [];
|
||||
}
|
||||
private elapsed() {
|
||||
return Math.max(0, (audioCtx().currentTime - this.t0) * this.sceneRate * 1000);
|
||||
}
|
||||
private fetchBuf(url: string) {
|
||||
let p = this.bufCache.get(url);
|
||||
if (!p) {
|
||||
p = fetch(url, { credentials: 'include' })
|
||||
.then((r) => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(String(r.status)))))
|
||||
.then((ab) => audioCtx().decodeAudioData(ab))
|
||||
.catch(() => null);
|
||||
if (this.bufCache.size > 200) this.bufCache.clear();
|
||||
this.bufCache.set(url, p);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
private schedule() {
|
||||
const el = this.elapsed();
|
||||
const ctx = audioCtx();
|
||||
const normalize = settings.get().normalize;
|
||||
for (const s of this.slots) {
|
||||
if (s.src || s.pending) continue;
|
||||
const durMs = s.item.endTs - s.item.ts;
|
||||
if (s.offset > el + 6000 || s.offset + durMs < el) continue;
|
||||
s.pending = true;
|
||||
s.buf ??= this.fetchBuf(s.item.audio!.url);
|
||||
const slots = this.slots;
|
||||
void s.buf.then((buf) => {
|
||||
if (!buf || this.slots !== slots || !this.state.playing || !s.pending || s.src) return;
|
||||
const at = this.t0 + s.offset / 1000 / this.sceneRate;
|
||||
const now = ctx.currentTime;
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
src.playbackRate.value = this.sceneRate;
|
||||
const g = ctx.createGain();
|
||||
g.gain.value = normalize && s.item.audio ? dbToGain(s.item.audio.gainDb) : 1;
|
||||
src.connect(g).connect(playerOutput());
|
||||
if (at >= now) src.start(at);
|
||||
else {
|
||||
const into = (now - at) * this.sceneRate;
|
||||
if (into >= buf.duration) return;
|
||||
src.start(now, into);
|
||||
}
|
||||
s.src = src;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── 시계 ──
|
||||
private loop() {
|
||||
if (this.raf) return;
|
||||
let lastSchedule = 0;
|
||||
const step = (t: number) => {
|
||||
this.raf = 0;
|
||||
if (!this.state.playing) {
|
||||
this.tick();
|
||||
return;
|
||||
}
|
||||
if (this.state.mode === 'scene' && t - lastSchedule > 200) {
|
||||
lastSchedule = t;
|
||||
this.schedule();
|
||||
}
|
||||
this.tick();
|
||||
if (this.state.playing) this.raf = requestAnimationFrame(step);
|
||||
};
|
||||
this.raf = requestAnimationFrame(step);
|
||||
}
|
||||
private tick() {
|
||||
const s = this.state;
|
||||
let sceneTs: number | null = null;
|
||||
let time = s.time;
|
||||
if (s.mode === 'single' && s.item) {
|
||||
time = this.el.currentTime;
|
||||
sceneTs = s.item.ts + time * 1000;
|
||||
} else if (s.mode === 'scene' && s.scene) {
|
||||
const el = s.playing ? this.elapsed() : this.sceneElapsed;
|
||||
time = el / 1000;
|
||||
sceneTs = s.scene.start + el;
|
||||
if (s.playing && sceneTs >= s.scene.end + 300) {
|
||||
this.sceneElapsed = s.scene.end - s.scene.start;
|
||||
this.pauseScene();
|
||||
sceneTs = s.scene.end;
|
||||
time = this.sceneElapsed / 1000;
|
||||
}
|
||||
}
|
||||
// 재생 위치가 킬 · 라운드 종료 시각을 지나가면 효과음
|
||||
if (sceneTs != null && this.lastTs != null && s.playing && sceneTs > this.lastTs && sceneTs - this.lastTs < 1500) {
|
||||
for (const e of this.events) {
|
||||
if (e.ts > this.lastTs && e.ts <= sceneTs) sfx(e.type === 'round_end' ? 'round' : 'kill');
|
||||
}
|
||||
}
|
||||
this.lastTs = sceneTs;
|
||||
if (time !== s.time || sceneTs !== s.sceneTs) this.set({ time, sceneTs });
|
||||
}
|
||||
}
|
||||
|
||||
export const player = new Player();
|
||||
|
||||
export function usePlayer<T>(sel: (s: PlayerState) => T): T {
|
||||
return useSyncExternalStore(player.subscribe, () => sel(player.state));
|
||||
}
|
||||
|
||||
/** 이 발화가 지금 재생 중(또는 선택됨)인지 */
|
||||
export function useIsActive(it: { id: string; ts: number; endTs: number }): boolean {
|
||||
return usePlayer((s) =>
|
||||
s.mode === 'single' ? s.item?.id === it.id : s.mode === 'scene' && s.sceneTs != null && s.sceneTs >= it.ts && s.sceneTs <= it.endTs,
|
||||
);
|
||||
}
|
||||
/** 발화 시작 기준 재생 위치(초). 재생 위치가 없으면 -1 */
|
||||
export function useLocalTime(ts: number): number {
|
||||
return usePlayer((s) => (s.sceneTs == null ? -1 : (s.sceneTs - ts) / 1000));
|
||||
}
|
||||
72
site/web/src/store/settings.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
export type SfxKind = 'click' | 'play' | 'kill' | 'round' | 'chime';
|
||||
export interface Settings {
|
||||
volume: number; // 효과음 전체 볼륨 0..1
|
||||
sfx: Record<SfxKind, boolean>;
|
||||
reduceMotion: boolean;
|
||||
rate: number;
|
||||
continuous: boolean;
|
||||
normalize: boolean;
|
||||
}
|
||||
|
||||
const KEY = 'gvr.settings.v1';
|
||||
const DEFAULTS: Settings = {
|
||||
volume: 0.5,
|
||||
sfx: { click: true, play: true, kill: true, round: true, chime: true },
|
||||
reduceMotion: false,
|
||||
rate: 1,
|
||||
continuous: true,
|
||||
normalize: true,
|
||||
};
|
||||
|
||||
function load(): Settings {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY);
|
||||
if (!raw) return DEFAULTS;
|
||||
const v = JSON.parse(raw) as Partial<Settings>;
|
||||
return { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) } };
|
||||
} catch {
|
||||
return DEFAULTS;
|
||||
}
|
||||
}
|
||||
|
||||
let state: Settings = load();
|
||||
const subs = new Set<() => void>();
|
||||
|
||||
export const settings = {
|
||||
get: () => state,
|
||||
set(patch: Partial<Settings>) {
|
||||
state = { ...state, ...patch };
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(state));
|
||||
} catch {
|
||||
/* 사생활 보호 모드 등 */
|
||||
}
|
||||
subs.forEach((f) => f());
|
||||
},
|
||||
subscribe(f: () => void) {
|
||||
subs.add(f);
|
||||
return () => {
|
||||
subs.delete(f);
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export function useSettings(): Settings {
|
||||
return useSyncExternalStore(settings.subscribe, settings.get);
|
||||
}
|
||||
|
||||
const mq = typeof window !== 'undefined' ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;
|
||||
/** 시스템 설정(prefers-reduced-motion) 또는 앱의 "모션 줄이기" */
|
||||
export function useReducedMotion(): boolean {
|
||||
const s = useSettings();
|
||||
const sys = useSyncExternalStore(
|
||||
(f) => {
|
||||
mq?.addEventListener('change', f);
|
||||
return () => mq?.removeEventListener('change', f);
|
||||
},
|
||||
() => !!mq?.matches,
|
||||
);
|
||||
return s.reduceMotion || sys;
|
||||
}
|
||||
3204
site/web/src/styles.css
Normal file
24
site/web/tsconfig.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"allowImportingTsExtensions": false,
|
||||
"useDefineForClassFields": true,
|
||||
"types": ["vite/client"],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@gvr/shared": ["../../packages/shared/src/index.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
23
site/web/vite.config.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const sharedSrc = fileURLToPath(new URL('../../packages/shared/src/index.ts', import.meta.url));
|
||||
// 목 서버(mock/server.mjs) 주소. 실제 배포에서는 사이트 서버가 같은 오리진으로 정적 파일을 서빙한다.
|
||||
const backend = process.env.GVR_BACKEND ?? 'http://127.0.0.1:18787';
|
||||
const proxy = {
|
||||
'/api': { target: backend, changeOrigin: false },
|
||||
'/auth': { target: backend, changeOrigin: false },
|
||||
'/game-assets': { target: backend, changeOrigin: false },
|
||||
'/mock': { target: backend, changeOrigin: false },
|
||||
'/ws': { target: backend.replace(/^http/, 'ws'), ws: true },
|
||||
};
|
||||
|
||||
export default defineConfig({
|
||||
base: '/',
|
||||
plugins: [react()],
|
||||
resolve: { alias: { '@gvr/shared': sharedSrc } },
|
||||
server: { port: 5173, host: '127.0.0.1', proxy, fs: { allow: ['.', '../../packages/shared'] } },
|
||||
preview: { port: 4173, host: '127.0.0.1', proxy },
|
||||
build: { outDir: 'dist', sourcemap: false, chunkSizeWarningLimit: 900 },
|
||||
});
|
||||