M2: 사이트 서버 · 사이트 v1 - gvr.tkrmagid.kr 배포
- site/server: Discord OAuth2 + 봇 토큰 멤버 확인, 세션, 1회용 등록 코드·기기 키 인증, 게임 PC WebSocket 중계(JSON·음성 바이너리), 15초 무응답 잠금, 게임 이미지 캐시, 관리 CLI - site/web: 타임라인·따라 읽기 재생(단어 강조·이어듣기·현장 모드·재생 게인)·필터·검색·실시간·교정, 발로란트/롤 경기 상세, 잠금 화면(관리자 등록 코드), 모바일, 효과음 - deploy/site: Dockerfile·compose·deploy.sh·make-env.sh (.5, 포트 2972) - 앱 코어: 사이트 필터 묶음(킬·라운드)과 유저 필터 규칙 맞춤, hello 에 서버 ID Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
123
site/web/src/lib/api.ts
Normal file
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
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
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
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
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
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
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: '새 발화 알림',
|
||||
};
|
||||
Reference in New Issue
Block a user