Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ce9235a8e | ||
|
|
fa6126e17f | ||
|
|
2ffb18263c |
14
README.md
14
README.md
@@ -8,7 +8,7 @@
|
||||
- 설계·계획: [`docs/gemnoki-project-plan.pdf`](docs/gemnoki-project-plan.pdf), 개발 구조·인터페이스: [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
|
||||
- 범인찾기 · 리플레이 동기화 계획서 v1.2 (결정 반영): [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf) · 원본 · 비용 계산 · 프롬프트 초안: `docs/report/culprit/` (실제로 쓰는 프롬프트는 `site/server/prompt/`)
|
||||
- **제작 완료 보고서 (M0~M8)**: [`docs/gemnoki-final-report.pdf`](docs/gemnoki-final-report.pdf) · 단계별 테스트 기록: [`docs/dev/test-results.md`](docs/dev/test-results.md)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.3.5](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.5) (`GameVoiceRecorder-1.3.5-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.5-portable.exe`) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.3.6](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.6) (`GameVoiceRecorder-1.3.6-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.6-portable.exe`) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
|
||||
## 로그인 · 관리자 (v1.2.0~)
|
||||
|
||||
@@ -19,6 +19,18 @@
|
||||
- 앱은 시작할 때와 10분마다 등록 여부를 다시 확인한다. 등록이 해제되면 바로 잠그고 봇 · 녹음 · 사이트 연결을 멈춘다. 사이트 서버에 못 붙으면 마지막 확인 뒤 3일까지는 그대로 쓴다.
|
||||
- 서버 쪽: `site/server/src/app-auth.ts` (`/auth/app/*`, `/app/me`, `/app/admin/users`), 앱 쪽: `app/src/core/auth.ts`, 권한 목록: `app/src/core/roles.ts`. 로그인 E2E: `app/scripts/login-e2e.mts`.
|
||||
|
||||
## v1.3.6 바뀐 점
|
||||
|
||||
- **목소리 깨짐**: 녹음기가 디스코드 패킷이 "도착한 간격"으로 말 사이 쉼을 채웠다. 게임 중(CPU 부하)에는 패킷이 2~3개씩 몰려 와서 말 중간에 20ms 무음이 계속 끼었다 (사용자 파일: 실제 7.0초 발화가 8.5초, 패킷 3개 중 1개가 무음). 이제 RTP 타임스탬프로 패킷 자리를 정한다 (`recorder.ts` `tapRtp` · `Utterance.place`). 예전 녹음은 처음 켤 때 한 번 끼운 무음을 빼고 다시 변환한다 (`ogg.ts` `removeInsertedSilence`)
|
||||
- **말한 사람 "알 수 없음"**: 앱이 `users.updated` 를 빈 목록으로 보내 사이트가 유저 목록을 비웠다. 이제 실제 목록을 보낸다 (사이트도 빈 목록이면 다시 받아 옴)
|
||||
- **잡음**: 목소리 없음 · 잡음에서 지어낸 문장 · 같은 말 반복은 사이트에 보이지 않고 ogg 도 지운다 (경기 중 실시간 판정은 경기 뒤 정밀 모델이 다시 본 다음). 로그에 "잡음 발화 … 숨김 · 음성 파일 삭제 (이유, 인식 문장)" 로 남는다. 목소리가 0.15초라도 있으면 Whisper 로 넘기고, 반복 고리는 한 번으로 줄여 남은 말을 보여 준다
|
||||
- **시작 창**: 포터블 exe 를 푸는 동안 작은 그림 창(`assets/app/splash.bmp`), 앱이 켜지는 동안 "켜는 중" 창
|
||||
- **녹음 안내 말 속도** 0.1~2.0 (Edge TTS 는 0.5~2.0, 그보다 느리면 워커 `tempo` 가 atempo 로 늘림)
|
||||
- **사이트**: 재생 음량 0~200% · 발화 우클릭(재생 · 자세한 정보(원본 ogg 이름 · 게임 PC 경로 · 크기 · 인식 정보) · ogg 다운로드 · 내용 복사, 앱 `GET /api/utterances/:id/info`)
|
||||
- **사이트 로그**: 사이트 서버가 `data/logs/site-날짜.log` 로 남긴다 (게임 PC 연결 · 끊김 · 기록 요청 결과 · 봇 중계 · 범인찾기 · 브라우저 오류). 관리자는 `https://gvr.tkrmagid.kr/logs` 에서 게임 PC 가 꺼져 있어도 보고 내려받는다 (잠금 화면 · 설정 메뉴에 링크). 14일 보관
|
||||
- **지금 게임**: 앱 게임 연동 탭 · 사이트(머리글 · 타임라인 오른쪽)에 연결된 게임 · 상태(메뉴 · 대기열 · 요원/챔피언 선택 · 경기 중) · 모드 · 맵 · 라운드 · 점수 · 내 요원/챔피언 · KDA · 게임 시간
|
||||
- 발로란트 데스매치 · 팀 데스매치 · 에스컬레이션: 킬 점수를 라운드로 착각해 "R63 승리" 같은 가짜 라운드와 에이스를 만들던 것 고침. 경기 상세에 선수 이름이 비어 오면 이름 서비스로 채운다 ("주인 계정 자동 연결: #" 고침)
|
||||
|
||||
## v1.3.5 바뀐 점
|
||||
|
||||
- **표시 이름 빈틈**: 표시 이름을 정하기 전에 시작한 범인 분석이 정한 뒤에 저장되면 결과 본문에 예전 이름이 남을 수 있었다 (이미 이름이 바뀐 유저는 다시 훑지 않았음). 이제 가린 예전 이름을 기억해 두고(`meta.hidden_names`), 분석을 저장할 때마다 · 이름을 다시 받을 때마다 모든 분석에서 바꾼다
|
||||
|
||||
6
app/package-lock.json
generated
6
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"version": "1.3.5",
|
||||
"version": "1.3.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gvr-app",
|
||||
"version": "1.3.5",
|
||||
"version": "1.3.6",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@discordjs/voice": "^0.19.2",
|
||||
@@ -4677,7 +4677,7 @@
|
||||
}
|
||||
},
|
||||
"node_modules/prism-media": {
|
||||
"version": "1.3.5",
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz",
|
||||
"integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==",
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"productName": "겜녹이",
|
||||
"version": "1.3.5",
|
||||
"version": "1.3.6",
|
||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||
"private": true,
|
||||
"main": "dist/main.cjs",
|
||||
@@ -107,7 +107,8 @@
|
||||
},
|
||||
"portable": {
|
||||
"artifactName": "GameVoiceRecorder-${version}-portable.exe",
|
||||
"unpackDirName": "GameVoiceRecorder"
|
||||
"unpackDirName": "GameVoiceRecorder",
|
||||
"splashImage": "../assets/app/splash.bmp"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, Word } from '@gvr/shared';
|
||||
import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, UtteranceInfo, Word } from '@gvr/shared';
|
||||
import type { Culprit } from '../culprit.js';
|
||||
import type { Store, UserRow } from '../db/db.js';
|
||||
import type { Dictionary } from '../dict/dictionary.js';
|
||||
@@ -54,6 +54,7 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
recording: extra.recording,
|
||||
users: users(),
|
||||
games: { valorant: { connected: gs.valorant.connected, inMatch: gs.valorant.inMatch }, lol: { connected: gs.lol.connected, inMatch: gs.lol.inMatch } },
|
||||
live: d.games.live(),
|
||||
counts: store.counts(),
|
||||
version: d.version,
|
||||
};
|
||||
@@ -108,7 +109,6 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
to: q.to ? Number(q.to) : undefined,
|
||||
q: q.q || undefined,
|
||||
types: q.types ? q.types.split(',').filter(Boolean) : undefined,
|
||||
hideNoise: q.hideNoise === '1' || q.hideNoise === 'true',
|
||||
cursor: q.cursor || undefined,
|
||||
limit: q.limit ? Number(q.limit) : undefined,
|
||||
order: q.order === 'asc' ? 'asc' : 'desc',
|
||||
@@ -116,6 +116,44 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
return timeline.query(tq);
|
||||
});
|
||||
|
||||
// 발화 자세한 정보: 원본 ogg 이름 · 경로 등 (사이트 우클릭 → 자세한 정보)
|
||||
app.get<{ Params: { id: string } }>('/api/utterances/:id/info', async (req, reply): Promise<UtteranceInfo | void> => {
|
||||
const u = store.getUtterance(req.params.id);
|
||||
if (!u) return reply.code(404).send({ error: 'not_found' });
|
||||
const exists = !!u.audio_path && !u.audio_deleted && fs.existsSync(u.audio_path);
|
||||
const sess = u.session_id ? (store.db.prepare('SELECT channel_name FROM sessions WHERE id=?').get(u.session_id) as { channel_name: string | null } | undefined) : undefined;
|
||||
const p = u.audio_path;
|
||||
const win = p?.includes('\\') ?? false;
|
||||
const sep = win ? '\\' : '/';
|
||||
return {
|
||||
id: u.id,
|
||||
userId: u.user_id,
|
||||
fileName: p ? p.split(/[\\/]/).pop() ?? null : null,
|
||||
path: p,
|
||||
folder: p ? p.slice(0, p.lastIndexOf(sep)) || null : null,
|
||||
sizeBytes: exists ? fs.statSync(p!).size : null,
|
||||
deleted: exists ? null : u.noise && !u.corrected ? 'noise' : u.audio_deleted ? 'retention' : 'missing',
|
||||
startedAt: u.started_at,
|
||||
endedAt: u.ended_at,
|
||||
durationMs: u.ended_at - u.started_at,
|
||||
sessionId: u.session_id,
|
||||
channel: sess?.channel_name ?? null,
|
||||
matchId: u.match_id,
|
||||
status: u.status,
|
||||
model: u.model,
|
||||
confidence: u.confidence,
|
||||
lufs: u.lufs,
|
||||
gainDb: u.gain_db,
|
||||
rawText: u.raw_text,
|
||||
text: u.text,
|
||||
corrected: !!u.corrected,
|
||||
noise: !!u.noise,
|
||||
noiseReason: u.noise_reason,
|
||||
attempts: u.attempts,
|
||||
createdAt: u.created_at,
|
||||
};
|
||||
});
|
||||
|
||||
app.get<{ Params: { id: string } }>('/api/audio/:id', async (req, reply) => {
|
||||
const u = store.getUtterance(req.params.id);
|
||||
if (!u) return reply.code(404).send({ error: 'not_found' });
|
||||
@@ -171,7 +209,7 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
stats: p.stats,
|
||||
}));
|
||||
const evRows = store.events(m.id);
|
||||
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? ORDER BY started_at').all(m.id) as any[];
|
||||
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? AND (noise=0 OR corrected=1) ORDER BY started_at').all(m.id) as any[];
|
||||
const vmap = m.game === 'valorant' ? d.games.assets.valMap(m.map) : null;
|
||||
return {
|
||||
...sum,
|
||||
|
||||
@@ -322,6 +322,15 @@ export class Store {
|
||||
.prepare('SELECT id, audio_path FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND started_at<?')
|
||||
.all(before) as any[];
|
||||
}
|
||||
/** 잡음으로 끝난 발화 중 아직 음성 파일이 남은 것 (v1.3.5 이하에서 녹음한 것) */
|
||||
noiseWithAudio(): UtteranceRow[] {
|
||||
return this.db
|
||||
.prepare(
|
||||
`SELECT rowid,* FROM utterances WHERE noise=1 AND corrected=0 AND audio_deleted=0 AND audio_path IS NOT NULL
|
||||
AND (status='precise' OR noise_reason='vad')`,
|
||||
)
|
||||
.all() as UtteranceRow[];
|
||||
}
|
||||
markAudioDeleted(id: string): void {
|
||||
this.db.prepare('UPDATE utterances SET audio_deleted=1 WHERE id=?').run(id);
|
||||
}
|
||||
@@ -472,7 +481,7 @@ export class Store {
|
||||
|
||||
// ---------------------------------------------------------------- stats
|
||||
counts(): { utterances: number; matches: number } {
|
||||
const u = (this.db.prepare('SELECT count(*) n FROM utterances').get() as any).n;
|
||||
const u = (this.db.prepare('SELECT count(*) n FROM utterances WHERE noise=0 OR corrected=1').get() as any).n;
|
||||
const m = (this.db.prepare('SELECT count(*) n FROM matches').get() as any).n;
|
||||
return { utterances: u, matches: m };
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import { newId } from '../util/ids.js';
|
||||
import type { BotGateway, GChannel, GCommand, GMember, GVoiceEvent } from './gateway.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import type { Recorder } from './recorder.js';
|
||||
import type { Announcer } from './tts.js';
|
||||
import { isOgg, type Announcer } from './tts.js';
|
||||
|
||||
const log = logger('bot');
|
||||
|
||||
@@ -290,9 +290,9 @@ export class Bot {
|
||||
if (!this.player) return;
|
||||
const s = this.settings().discord;
|
||||
try {
|
||||
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice);
|
||||
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice, s.ttsRate);
|
||||
if (!this.player) return;
|
||||
const res = createAudioResource(fs.createReadStream(file), { inputType: StreamType.WebmOpus });
|
||||
const res = createAudioResource(fs.createReadStream(file), { inputType: isOgg(file) ? StreamType.OggOpus : StreamType.WebmOpus });
|
||||
this.player.play(res);
|
||||
await entersState(this.player, AudioPlayerStatus.Playing, 5000).catch(() => undefined);
|
||||
} catch (e) {
|
||||
|
||||
@@ -127,3 +127,58 @@ export class OggOpusWriter {
|
||||
return Math.round(this.samples / 48);
|
||||
}
|
||||
}
|
||||
|
||||
/** Ogg 파일에서 Opus 패킷을 꺼낸다 (OpusHead · OpusTags 포함) */
|
||||
export function readOggPackets(buf: Buffer): Buffer[] {
|
||||
const out: Buffer[] = [];
|
||||
let pos = 0;
|
||||
let cur: Buffer[] = [];
|
||||
while (pos + 27 <= buf.length && buf.toString('ascii', pos, pos + 4) === 'OggS') {
|
||||
const nseg = buf[pos + 26];
|
||||
const lacing = buf.subarray(pos + 27, pos + 27 + nseg);
|
||||
let p = pos + 27 + nseg;
|
||||
for (const l of lacing) {
|
||||
cur.push(buf.subarray(p, p + l));
|
||||
p += l;
|
||||
if (l < 255) {
|
||||
out.push(Buffer.concat(cur));
|
||||
cur = [];
|
||||
}
|
||||
}
|
||||
pos = p;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.3.5 이하 녹음 고치기: 패킷이 몰려 도착할 때 말 중간에 끼워 넣은 20~60ms 무음 프레임을 뺀다.
|
||||
* 디스코드는 말하는 도중에 무음 프레임을 보내지 않으므로, 앞뒤가 목소리인 1~3개짜리 무음 묶음은 녹음기가 넣은 것이다.
|
||||
* @returns 뺀 프레임 수 (0 이면 파일을 건드리지 않음)
|
||||
*/
|
||||
export function removeInsertedSilence(file: string): number {
|
||||
const all = readOggPackets(fs.readFileSync(file));
|
||||
if (all.length < 3) return 0;
|
||||
const head = all[0];
|
||||
const packets = all.slice(2);
|
||||
const isSil = (p: Buffer) => p.equals(SILENCE_FRAME);
|
||||
const keep: Buffer[] = [];
|
||||
let removed = 0;
|
||||
for (let i = 0; i < packets.length; ) {
|
||||
if (!isSil(packets[i])) {
|
||||
keep.push(packets[i++]);
|
||||
continue;
|
||||
}
|
||||
let j = i;
|
||||
while (j < packets.length && isSil(packets[j])) j++;
|
||||
if (i > 0 && j < packets.length && j - i <= 3) removed += j - i;
|
||||
else keep.push(...packets.slice(i, j));
|
||||
i = j;
|
||||
}
|
||||
if (!removed) return 0;
|
||||
const tmp = `${file}.fix`;
|
||||
const w = new OggOpusWriter(tmp, head[9] || 2);
|
||||
for (const p of keep) w.write(p);
|
||||
w.close();
|
||||
fs.renameSync(tmp, file);
|
||||
return removed;
|
||||
}
|
||||
|
||||
@@ -21,12 +21,55 @@ export interface RecorderOptions {
|
||||
matchAt: (ts: number) => string | null;
|
||||
}
|
||||
|
||||
/** RTP 시각 (48kHz 샘플 단위 타임스탬프 + 순번) */
|
||||
export interface RtpInfo {
|
||||
seq: number;
|
||||
ts: number;
|
||||
}
|
||||
|
||||
/** 수신기가 꺼낸 Opus 패킷 → 그 패킷이 담겨 온 RTP 헤더 */
|
||||
const rtpOf = new WeakMap<Buffer, RtpInfo>();
|
||||
|
||||
export function rtpInfo(packet: Buffer): RtpInfo | undefined {
|
||||
return rtpOf.get(packet);
|
||||
}
|
||||
|
||||
/** 테스트용: 패킷에 RTP 시각을 붙인다 */
|
||||
export function tagRtp(packet: Buffer, info: RtpInfo): Buffer {
|
||||
rtpOf.set(packet, info);
|
||||
return packet;
|
||||
}
|
||||
|
||||
/**
|
||||
* @discordjs/voice 는 Opus 내용만 넘기고 RTP 순번 · 타임스탬프를 버린다.
|
||||
* 패킷 도착 시각은 게임 중(CPU 부하)에 2~3개씩 몰려 와서 쉼 계산에 쓸 수 없다 (v1.3.5 까지 말 중간에 무음이 끼어 목소리가 깨짐).
|
||||
* 그래서 복호화 함수를 감싸 RTP 헤더를 패킷에 붙여 둔다.
|
||||
*/
|
||||
export function tapRtp(receiver: unknown): boolean {
|
||||
const r = receiver as { parsePacket?: (buf: Buffer, ...rest: unknown[]) => Buffer | undefined; __gvrRtp?: boolean };
|
||||
if (r.__gvrRtp) return true;
|
||||
if (typeof r.parsePacket !== 'function') return false;
|
||||
const orig = r.parsePacket.bind(r);
|
||||
r.parsePacket = (buf: Buffer, ...rest: unknown[]) => {
|
||||
const packet = orig(buf, ...rest);
|
||||
if (packet && buf.length >= 12) rtpOf.set(packet, { seq: buf.readUInt16BE(2), ts: buf.readUInt32BE(4) });
|
||||
return packet;
|
||||
};
|
||||
r.__gvrRtp = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
const FRAME = 960; // 20ms @48kHz
|
||||
|
||||
/** 발화 하나 = 파일 하나. 말이 0.8초 끊기면 끝, 최대 30초 (보고서 4장 1~3단계) */
|
||||
class Utterance {
|
||||
export class Utterance {
|
||||
writer: OggOpusWriter;
|
||||
id: string;
|
||||
startedAt: number;
|
||||
lastArrival: number;
|
||||
/** 첫 패킷의 RTP 타임스탬프 - 그때까지 쓴 샘플 수. 패킷 자리 = ts - rtpBase */
|
||||
rtpBase: number | null = null;
|
||||
lastSeq = 0;
|
||||
constructor(dir: string, now: number) {
|
||||
this.id = newId(now);
|
||||
this.startedAt = now;
|
||||
@@ -36,6 +79,35 @@ class Utterance {
|
||||
fs.mkdirSync(d, { recursive: true });
|
||||
this.writer = new OggOpusWriter(path.join(d, `${this.id}.ogg`));
|
||||
}
|
||||
|
||||
/**
|
||||
* 패킷을 제자리에 쓴다. 디스코드는 말 사이 짧은 쉼에는 패킷을 안 보내므로 빈 자리를 무음 프레임으로 채운다.
|
||||
* - RTP 타임스탬프가 있으면 그 값으로 자리를 정한다 (도착이 몰리거나 늦어도 소리가 늘어나지 않음)
|
||||
* - 없으면 도착 시각으로 정하되, 실제 흐른 시간보다 0.2초 넘게 모자랄 때만 채운다 (몰려 온 패킷 사이에 무음을 넣지 않음)
|
||||
* @returns 쓴 무음 프레임 수, 버린 패킷이면 -1
|
||||
*/
|
||||
place(packet: Buffer, now: number, maxGapMs: number): number {
|
||||
const rtp = rtpOf.get(packet);
|
||||
let fill = 0;
|
||||
if (rtp && this.rtpBase !== null) {
|
||||
const d = (rtp.seq - this.lastSeq) & 0xffff;
|
||||
if (d === 0 || d > 0x8000) return -1; // 중복 · 순서가 뒤바뀌어 늦게 온 패킷 (그 자리는 이미 지나감)
|
||||
const behind = ((rtp.ts - this.rtpBase) >>> 0) - this.writer.samples;
|
||||
if (behind >= FRAME / 2 && behind <= maxGapMs * 48) fill = Math.round(behind / FRAME);
|
||||
else if (behind > maxGapMs * 48 || behind < -48000) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0; // 타임스탬프가 튐: 다시 맞춘다
|
||||
} else if (!rtp) {
|
||||
const lag = now - this.startedAt - this.writer.samples / 48;
|
||||
if (lag > 200) fill = Math.min(Math.floor((lag - 100) / 20), Math.ceil(maxGapMs / 20));
|
||||
}
|
||||
if (rtp) {
|
||||
if (this.rtpBase === null) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0;
|
||||
this.lastSeq = rtp.seq;
|
||||
}
|
||||
for (let i = 0; i < fill; i++) this.writer.write(SILENCE_FRAME);
|
||||
this.lastArrival = now;
|
||||
this.writer.write(packet);
|
||||
return fill;
|
||||
}
|
||||
}
|
||||
|
||||
function localDay(ts: number): string {
|
||||
@@ -61,6 +133,7 @@ export class Recorder {
|
||||
this.detach();
|
||||
this.connection = connection;
|
||||
this.sessionId = sessionId;
|
||||
if (!tapRtp(connection.receiver)) log.warn('RTP 시각을 읽을 수 없음: 도착 시각으로 쉼을 맞춤');
|
||||
connection.receiver.speaking.on('start', this.onSpeak);
|
||||
}
|
||||
|
||||
@@ -99,14 +172,8 @@ export class Recorder {
|
||||
if (!u) {
|
||||
u = new Utterance(this.opts.audioDir(), now - 20);
|
||||
this.active.set(userId, u);
|
||||
} else {
|
||||
// 말 사이 짧은 쉼은 디스코드가 패킷을 안 보낸다. 무음 프레임으로 채워 실제 시간과 맞춘다.
|
||||
const gap = now - u.lastArrival;
|
||||
const missing = Math.round(gap / 20) - 1;
|
||||
if (missing > 0 && missing * 20 < this.opts.silenceMs() + 200) for (let i = 0; i < missing; i++) u.writer.write(SILENCE_FRAME);
|
||||
}
|
||||
u.lastArrival = now;
|
||||
u.writer.write(packet);
|
||||
u.place(packet, now, this.opts.silenceMs() + 200);
|
||||
if (u.writer.samples >= this.opts.maxUtteranceSec() * 48000) {
|
||||
this.finish(userId);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,20 @@ import { logger } from '../util/log.js';
|
||||
|
||||
const log = logger('tts');
|
||||
|
||||
/** 0.5배보다 느린 부분을 늘리는 함수 (워커 atempo). src 를 tempo 배속으로 바꿔 dst(Ogg Opus)에 쓴다 */
|
||||
export type TempoFn = (src: string, dst: string, tempo: number) => Promise<void>;
|
||||
|
||||
/** 말 속도 0.1~2.0 (Edge TTS 는 0.5~2.0 만 지원해서 그보다 느린 부분은 워커가 늘린다) */
|
||||
export function clampRate(rate: unknown): number {
|
||||
const r = typeof rate === 'number' && isFinite(rate) ? rate : 1;
|
||||
return Math.round(Math.min(2, Math.max(0.1, r)) * 100) / 100;
|
||||
}
|
||||
|
||||
/** 파일 확장자로 디스코드 재생 형식을 고른다 */
|
||||
export function isOgg(file: string): boolean {
|
||||
return file.endsWith('.ogg');
|
||||
}
|
||||
|
||||
/**
|
||||
* 녹음 안내 음성. 미리 합성해서 캐시하고, 문구를 바꾸면 다시 합성한다 (보고서 7-3).
|
||||
* 합성은 Microsoft Edge 온라인 TTS(무료). 인터넷이 안 되면 기본 문구 음성(앱에 포함)을 쓴다.
|
||||
@@ -15,38 +29,66 @@ export class Announcer {
|
||||
constructor(
|
||||
private cacheDir: string,
|
||||
private resourcesDir: string,
|
||||
private tempo: TempoFn | null = null,
|
||||
) {}
|
||||
|
||||
private bundled(): string {
|
||||
return path.join(this.resourcesDir, 'tts', 'announce-default.webm');
|
||||
}
|
||||
|
||||
cachedPath(text: string, voice: string): string {
|
||||
const h = crypto.createHash('sha1').update(`${voice}\n${text}`).digest('hex').slice(0, 16);
|
||||
return path.join(this.cacheDir, `announce-${h}.webm`);
|
||||
cachedPath(text: string, voice: string, rate = 1): string {
|
||||
rate = clampRate(rate);
|
||||
const key = rate === 1 ? `${voice}\n${text}` : `${voice}\n${rate}\n${text}`;
|
||||
const h = crypto.createHash('sha1').update(key).digest('hex').slice(0, 16);
|
||||
return path.join(this.cacheDir, `announce-${h}.${rate < 0.5 ? 'ogg' : 'webm'}`);
|
||||
}
|
||||
|
||||
/** 안내 음성 파일 경로 (WebM Opus). 없으면 합성. */
|
||||
async ensure(text: string, voice: string): Promise<string> {
|
||||
const p = this.cachedPath(text, voice);
|
||||
/** 안내 음성 파일 경로 (WebM Opus, 0.5배보다 느리면 Ogg Opus). 없으면 합성. */
|
||||
async ensure(text: string, voice: string, rate = 1): Promise<string> {
|
||||
rate = clampRate(rate);
|
||||
const p = this.cachedPath(text, voice, rate);
|
||||
if (fs.existsSync(p) && fs.statSync(p).size > 1000) return p;
|
||||
if (text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled();
|
||||
if (rate === 1 && text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled();
|
||||
try {
|
||||
await synthesize(text, voice, p);
|
||||
log.info(`안내 음성 합성: ${path.basename(p)}`);
|
||||
await render(text, voice, rate, p, this.tempo);
|
||||
log.info(`안내 음성 합성: ${path.basename(p)} (속도 ${rate})`);
|
||||
return p;
|
||||
} catch (e) {
|
||||
log.warn('안내 음성 합성 실패, 기본 음성 사용', e);
|
||||
// 인터넷이 안 될 때: 기본 음성을 그 속도로만 바꿔 쓴다
|
||||
if (rate !== 1 && this.tempo && fs.existsSync(this.bundled())) {
|
||||
const q = path.join(this.cacheDir, `announce-default-${rate}.ogg`);
|
||||
try {
|
||||
if (!fs.existsSync(q)) await this.tempo(this.bundled(), q, rate);
|
||||
return q;
|
||||
} catch (e2) {
|
||||
log.warn('기본 음성 속도 바꾸기 실패', e2);
|
||||
}
|
||||
}
|
||||
return this.bundled();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 문구를 그 속도로 합성해 outFile 에 쓴다. 0.5배보다 느리면 0.5배로 합성한 뒤 워커가 더 늘린다 (outFile 은 .ogg) */
|
||||
export async function render(text: string, voice: string, rate: number, outFile: string, tempo: TempoFn | null): Promise<void> {
|
||||
rate = clampRate(rate);
|
||||
if (rate >= 0.5) return synthesize(text, voice, outFile, 4, rate);
|
||||
if (!tempo) throw new Error('0.5배보다 느린 속도는 음성 인식 엔진(워커)이 켜져 있어야 합니다');
|
||||
const tmp = `${outFile}.half.webm`;
|
||||
try {
|
||||
await synthesize(text, voice, tmp, 4, 0.5);
|
||||
await tempo(tmp, outFile, rate / 0.5);
|
||||
} finally {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Edge TTS 는 짧은 시간에 여러 번 부르면 429 를 준다. 몇 번 쉬었다가 다시 시도한다. */
|
||||
export async function synthesize(text: string, voice: string, outFile: string, tries = 4): Promise<void> {
|
||||
export async function synthesize(text: string, voice: string, outFile: string, tries = 4, rate = 1): Promise<void> {
|
||||
for (let i = 1; ; i++) {
|
||||
try {
|
||||
return await synthesizeOnce(text, voice, outFile);
|
||||
return await synthesizeOnce(text, voice, outFile, rate);
|
||||
} catch (e: any) {
|
||||
if (i >= tries) throw e;
|
||||
await new Promise((r) => setTimeout(r, 1500 * 2 ** i));
|
||||
@@ -54,14 +96,14 @@ export async function synthesize(text: string, voice: string, outFile: string, t
|
||||
}
|
||||
}
|
||||
|
||||
async function synthesizeOnce(text: string, voice: string, outFile: string): Promise<void> {
|
||||
async function synthesizeOnce(text: string, voice: string, outFile: string, rate: number): Promise<void> {
|
||||
fs.mkdirSync(path.dirname(outFile), { recursive: true });
|
||||
const tts = new MsEdgeTTS();
|
||||
const tmpDir = fs.mkdtempSync(path.join(path.dirname(outFile), '.tts-'));
|
||||
try {
|
||||
await tts.setMetadata(voice, OUTPUT_FORMAT.WEBM_24KHZ_16BIT_MONO_OPUS);
|
||||
const r = await Promise.race([
|
||||
tts.toFile(tmpDir, text),
|
||||
tts.toFile(tmpDir, text, rate === 1 ? undefined : { rate: Math.min(2, Math.max(0.5, rate)) }),
|
||||
new Promise<never>((_, rej) => setTimeout(() => rej(new Error('TTS 시간 초과')), 20000)),
|
||||
]);
|
||||
fs.renameSync(r.audioFilePath, outFile);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ChatData, KillData, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared';
|
||||
import type { ChatData, KillData, LiveGame, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared';
|
||||
import { lolModeKo } from './modes.js';
|
||||
import type { EventRow } from '../db/db.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import { lolObjectIcon } from './assets.js';
|
||||
@@ -64,6 +65,12 @@ export class LolAdapter implements GameAdapter {
|
||||
private summonerNames = new Map<string, string>();
|
||||
private lastMatchId: string | null = null;
|
||||
private lastErr = '';
|
||||
/** LCU 게임 진행 단계 (Lobby · Matchmaking · ChampSelect · InProgress …) */
|
||||
private phase: string | null = null;
|
||||
private queueName: string | null = null;
|
||||
/** 게임 클라이언트 API 마지막 값 (지금 게임 상태 표시용) */
|
||||
private snap: { at: number; gameTime: number; mode: string | null; champ: string | null; champIcon: string | null; kda: string | null; extra: string | null; teamKills: { ally: number; enemy: number } | null; players: number } | null = null;
|
||||
private selfRiotId: string | null = null;
|
||||
|
||||
constructor(private host: AdapterHost) {}
|
||||
|
||||
@@ -81,6 +88,49 @@ export class LolAdapter implements GameAdapter {
|
||||
return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined };
|
||||
}
|
||||
|
||||
liveGame(): LiveGame {
|
||||
const enabled = this.host.settings().games.lol;
|
||||
const inMatch = !!this.live && !this.live.ended;
|
||||
const snap = inMatch && this.snap && Date.now() - this.snap.at < 15000 ? this.snap : null;
|
||||
const PHASE: Record<string, string> = {
|
||||
None: '메인 화면',
|
||||
Lobby: '로비',
|
||||
Matchmaking: '대기열',
|
||||
CheckedIntoTournament: '토너먼트 대기',
|
||||
ReadyCheck: '수락 대기',
|
||||
ChampSelect: '챔피언 선택',
|
||||
GameStart: '게임 불러오는 중',
|
||||
FailedToLaunch: '게임 실행 실패',
|
||||
InProgress: '경기 중',
|
||||
Reconnect: '다시 연결 필요',
|
||||
WaitingForStats: '결과 기다리는 중',
|
||||
PreEndOfGame: '경기 끝',
|
||||
EndOfGame: '경기 끝 · 결과 화면',
|
||||
TerminatedInError: '오류로 종료',
|
||||
};
|
||||
const phase = !enabled ? '연동 꺼짐' : inMatch ? '경기 중' : this.lcu ? (PHASE[this.phase ?? ''] ?? this.phase ?? '연결됨') : '롤 클라이언트 꺼짐';
|
||||
return {
|
||||
game: 'lol',
|
||||
enabled,
|
||||
connected: !!this.lcu || !!this.live,
|
||||
phase,
|
||||
inMatch,
|
||||
matchId: inMatch ? this.live!.id : null,
|
||||
mode: this.queueName ?? snap?.mode ?? null,
|
||||
map: inMatch ? (snap?.mode === '칼바람 나락' ? '칼바람 나락' : '소환사의 협곡') : null,
|
||||
mapImage: null,
|
||||
startedAt: inMatch ? this.live!.startedAt : null,
|
||||
round: null,
|
||||
score: null,
|
||||
gameTimeSec: snap ? Math.round(snap.gameTime) : null,
|
||||
teamKills: snap?.teamKills ?? null,
|
||||
self: this.lcu || inMatch ? { name: this.selfRiotId, character: snap?.champ ?? null, characterImage: snap?.champIcon ?? null, kda: snap?.kda ?? null, extra: snap?.extra ?? null } : null,
|
||||
players: snap?.players ?? null,
|
||||
error: this.lastErr || null,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
private async lcuGet<T = any>(path: string): Promise<T | null> {
|
||||
if (!this.lcu) return null;
|
||||
try {
|
||||
@@ -160,6 +210,7 @@ export class LolAdapter implements GameAdapter {
|
||||
const m = this.live;
|
||||
m.failures = 0;
|
||||
m.players = d.allPlayers || m.players;
|
||||
this.snapshot(d, m);
|
||||
// 게임 시간과 PC 시계로 시작 시각을 계속 다듬는다 (가장 이른 값 = 지연이 가장 적은 값)
|
||||
m.startedAt = Math.min(m.startedAt, now - gameTime * 1000);
|
||||
for (const ev of d.events?.Events || []) {
|
||||
@@ -181,6 +232,26 @@ export class LolAdapter implements GameAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/** 지금 게임 상태 표시용: 게임 시간 · 내 챔피언 · KDA · 팀 킬 */
|
||||
private snapshot(d: any, m: LiveMatch): void {
|
||||
const all: any[] = d.allPlayers || [];
|
||||
const me = all.find((p) => p.riotId === m.selfName || p.summonerName === m.selfName);
|
||||
const sc = me?.scores;
|
||||
const kills = (team: string | null | undefined) => all.filter((p) => p.team === team).reduce((n, p) => n + (p.scores?.kills ?? 0), 0);
|
||||
const champ = me ? this.host.assets.champion(me.rawChampionName, me.championName) : null;
|
||||
this.snap = {
|
||||
at: Date.now(),
|
||||
gameTime: Number(d.gameData?.gameTime) || 0,
|
||||
mode: lolModeKo(d.gameData?.gameMode) ?? d.gameData?.gameMode ?? null,
|
||||
champ: champ?.name ?? null,
|
||||
champIcon: champ?.icon ?? null,
|
||||
kda: sc ? `${sc.kills ?? 0}/${sc.deaths ?? 0}/${sc.assists ?? 0}` : null,
|
||||
extra: me ? `레벨 ${me.level ?? '?'} · CS ${sc?.creepScore ?? 0}` : null,
|
||||
teamKills: m.selfTeam ? { ally: kills(m.selfTeam), enemy: all.filter((p) => p.team !== m.selfTeam).reduce((n, p) => n + (p.scores?.kills ?? 0), 0) } : null,
|
||||
players: all.length,
|
||||
};
|
||||
}
|
||||
|
||||
private findPlayer(m: LiveMatch, name: string | undefined): any {
|
||||
if (!name) return null;
|
||||
return m.players.find((p) => p.riotIdGameName === name || p.riotId === name || p.summonerName === name || p.riotId?.split('#')[0] === name) ?? null;
|
||||
@@ -371,10 +442,22 @@ export class LolAdapter implements GameAdapter {
|
||||
log.info('롤 클라이언트(LCU) 연결');
|
||||
const me = await this.lcuGet<any>('/lol-summoner/v1/current-summoner');
|
||||
if (me?.puuid) this.host.selfAccount(me.puuid, `${me.gameName}#${me.tagLine}`);
|
||||
if (me?.gameName) this.selfRiotId = `${me.gameName}#${me.tagLine ?? ''}`;
|
||||
}
|
||||
}
|
||||
if (!this.lcu) return;
|
||||
if (!this.lcu) {
|
||||
this.phase = null;
|
||||
this.queueName = null;
|
||||
return;
|
||||
}
|
||||
const phase = await this.lcuGet<string>('/lol-gameflow/v1/gameflow-phase');
|
||||
if (phase !== this.phase) {
|
||||
this.phase = phase;
|
||||
// 큐 이름 (솔로 랭크 · 칼바람 나락 …): 단계가 바뀔 때만 다시 받는다
|
||||
const sess = phase && phase !== 'None' ? await this.lcuGet<any>('/lol-gameflow/v1/session') : null;
|
||||
const q = sess?.gameData?.queue;
|
||||
this.queueName = q ? (lolModeKo(q.id) ?? q.description ?? null) : null;
|
||||
}
|
||||
if (phase === 'ChampSelect' || phase === 'InProgress' || phase === 'PreEndOfGame' || phase === 'EndOfGame') await this.pollLcuChat(phase);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { MatchSummary } from '@gvr/shared';
|
||||
import type { LiveGame, MatchSummary } from '@gvr/shared';
|
||||
import type { EventRow, MatchRow, Store } from '../db/db.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import type { SttPipeline } from '../stt/pipeline.js';
|
||||
@@ -11,6 +11,7 @@ import type { GameAssets } from './assets.js';
|
||||
import { LolAdapter } from './lol.js';
|
||||
import type { AdapterHost, GameAdapter, MatchStart } from './types.js';
|
||||
import { ValorantAdapter } from './valorant.js';
|
||||
import { lolModeKo, valModeKo } from './modes.js';
|
||||
|
||||
const log = logger('games');
|
||||
|
||||
@@ -38,12 +39,15 @@ export class GameManager implements AdapterHost {
|
||||
start(): void {
|
||||
void this.assets.refresh();
|
||||
for (const a of this.adapters) a.start();
|
||||
this.watchLive();
|
||||
// 앱이 꺼졌다 켜졌을 때 'live' 로 남은 경기는 끝난 것으로 정리
|
||||
for (const m of this.store.listMatches({ limit: 20 }))
|
||||
if (m.status === 'live') this.store.upsertMatch({ id: m.id, game: m.game, started_at: m.started_at, status: 'complete', ended_at: m.ended_at ?? Date.now() });
|
||||
}
|
||||
stop(): void {
|
||||
for (const a of this.adapters) a.stop();
|
||||
if (this.liveTimer) clearInterval(this.liveTimer);
|
||||
this.liveTimer = null;
|
||||
}
|
||||
status() {
|
||||
const out: Record<string, { connected: boolean; inMatch: boolean; detail?: string }> = {};
|
||||
@@ -51,6 +55,25 @@ export class GameManager implements AdapterHost {
|
||||
return out as { valorant: { connected: boolean; inMatch: boolean }; lol: { connected: boolean; inMatch: boolean } };
|
||||
}
|
||||
|
||||
/** 지금 게임 상태 (앱 게임 연동 탭 · 사이트) */
|
||||
live(): LiveGame[] {
|
||||
return this.adapters.map((a) => a.liveGame());
|
||||
}
|
||||
|
||||
private liveTimer: NodeJS.Timeout | null = null;
|
||||
private lastLive = '';
|
||||
/** 게임 상태가 바뀌면 사이트로 알린다 (2초마다 확인) */
|
||||
private watchLive(): void {
|
||||
if (this.liveTimer) return;
|
||||
this.liveTimer = setInterval(() => {
|
||||
const live = this.live();
|
||||
const key = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest));
|
||||
if (key === this.lastLive) return;
|
||||
this.lastLive = key;
|
||||
this.bus.live({ type: 'games.state', data: live });
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
/** 지금 진행 중인 경기 (녹음 시 발화에 붙인다) */
|
||||
liveMatchAt(ts: number): string | null {
|
||||
const m = this.store.matchAt(ts);
|
||||
@@ -110,6 +133,8 @@ export class GameManager implements AdapterHost {
|
||||
selfAccount(puuid: string, riotId: string): void {
|
||||
const owner = this.ownerUserId();
|
||||
this.store.setMeta('riot_self_puuid', puuid);
|
||||
// 경기 상세에 이름이 빠져 오면("#") 연결하지 않는다 (v1.3.5: "주인 계정 자동 연결: #")
|
||||
if (!/^[^#]+#[^#]+$/.test(riotId)) return;
|
||||
if (!owner || !this.store.getUser(owner)) return;
|
||||
const have = this.store.listAccounts().some((a) => a.user_id === owner && a.puuid === puuid);
|
||||
if (have) return;
|
||||
@@ -159,21 +184,6 @@ export class GameManager implements AdapterHost {
|
||||
}
|
||||
|
||||
function modeKo(m: MatchRow): string {
|
||||
const q = (m.queue || m.mode || '').toLowerCase();
|
||||
if (m.game === 'valorant') {
|
||||
const map: Record<string, string> = {
|
||||
competitive: '경쟁전',
|
||||
unrated: '일반전',
|
||||
swiftplay: '신속플레이',
|
||||
spikerush: '스파이크 돌격',
|
||||
deathmatch: '데스매치',
|
||||
hurm: '팀 데스매치',
|
||||
premier: '프리미어',
|
||||
custom: '사용자 지정',
|
||||
ggteam: '에스컬레이션',
|
||||
};
|
||||
return map[q] || m.mode || '발로란트';
|
||||
}
|
||||
const lq: Record<string, string> = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', classic: '소환사의 협곡', aram: '칼바람 나락' };
|
||||
return lq[q] || m.mode || '리그 오브 레전드';
|
||||
const q = m.queue || m.mode || '';
|
||||
return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드');
|
||||
}
|
||||
|
||||
34
app/src/core/games/modes.ts
Normal file
34
app/src/core/games/modes.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
// 게임 모드 이름 (경기 목록 · 지금 게임 상태에서 함께 쓴다)
|
||||
|
||||
/** 발로란트 큐 ID → 모드 이름 (모르는 큐면 null) */
|
||||
export function valModeKo(queue: string | null | undefined): string | null {
|
||||
const q = (queue || '').toLowerCase();
|
||||
{
|
||||
const map: Record<string, string> = {
|
||||
competitive: '경쟁전',
|
||||
unrated: '일반전',
|
||||
swiftplay: '신속플레이',
|
||||
spikerush: '스파이크 돌격',
|
||||
deathmatch: '데스매치',
|
||||
hurm: '팀 데스매치',
|
||||
premier: '프리미어',
|
||||
custom: '사용자 지정',
|
||||
ggteam: '에스컬레이션',
|
||||
newmap: '새 맵',
|
||||
snowball: '눈싸움',
|
||||
};
|
||||
return map[q] || null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 롤 큐 ID · 게임 모드 → 이름 (모르면 null) */
|
||||
export function lolModeKo(queue: string | number | null | undefined): string | null {
|
||||
const q = String(queue ?? '').toLowerCase();
|
||||
const lq: Record<string, string> = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', '900': '우르프', '1900': '우르프', classic: '소환사의 협곡', aram: '칼바람 나락', cherry: '아레나', urf: '우르프', practicetool: '연습 모드', tutorial: '튜토리얼' };
|
||||
return lq[q] || null;
|
||||
}
|
||||
|
||||
/** 발로란트에서 라운드가 없는 모드 (점수 = 킬). 이 모드는 라운드 구분선 · 라운드 번호를 쓰지 않는다 */
|
||||
export function valNoRounds(queue: string | null | undefined): boolean {
|
||||
return ['deathmatch', 'hurm', 'ggteam', 'snowball'].includes((queue || '').toLowerCase());
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { LiveGame } from '@gvr/shared';
|
||||
import type { EventRow, MatchRow, Store } from '../db/db.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import type { WorkerClient } from '../stt/worker.js';
|
||||
@@ -38,4 +39,6 @@ export interface GameAdapter {
|
||||
start(): void;
|
||||
stop(): void;
|
||||
status(): { connected: boolean; inMatch: boolean; detail?: string };
|
||||
/** 지금 게임 상태 (자세히) */
|
||||
liveGame(): LiveGame;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound, PlayerStats } from '@gvr/shared';
|
||||
import type { KillData, ChatData, LiveGame, RoundEndData, PlayerRef, MatchPlayer, MatchRound, PlayerStats } from '@gvr/shared';
|
||||
import { valModeKo, valNoRounds } from './modes.js';
|
||||
import type { EventRow, RoundRow } from '../db/db.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import type { GameAssets } from './assets.js';
|
||||
@@ -21,6 +22,8 @@ interface Presence {
|
||||
ally: number | null;
|
||||
enemy: number | null;
|
||||
provisioning: string | null;
|
||||
/** 파티 상태: DEFAULT · MATCHMAKING · MATCHMADE_GAME_STARTING … */
|
||||
partyState: string | null;
|
||||
}
|
||||
|
||||
export function decodePresence(b64: string): Presence | null {
|
||||
@@ -35,6 +38,7 @@ export function decodePresence(b64: string): Presence | null {
|
||||
ally: num(pp.partyOwnerMatchScoreAllyTeam ?? p.partyOwnerMatchScoreAllyTeam),
|
||||
enemy: num(pp.partyOwnerMatchScoreEnemyTeam ?? p.partyOwnerMatchScoreEnemyTeam),
|
||||
provisioning: mp.provisioningFlow || p.provisioningFlow || null,
|
||||
partyState: pp.partyState || p.partyState || null,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
@@ -65,7 +69,9 @@ export class ValorantAdapter implements GameAdapter {
|
||||
private auth: Auth | null = null;
|
||||
private authAt = 0;
|
||||
private presence: Presence | null = null;
|
||||
private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number } | null = null;
|
||||
private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number; queue: string | null; selfAgent: string | null; players: number } | null = null;
|
||||
/** 내 Riot ID (로컬 채팅 세션) */
|
||||
private selfName: string | null = null;
|
||||
private seenChat = new Set<string>();
|
||||
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
|
||||
private polling = false;
|
||||
@@ -86,6 +92,54 @@ export class ValorantAdapter implements GameAdapter {
|
||||
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
|
||||
}
|
||||
|
||||
liveGame(): LiveGame {
|
||||
const p = this.presence;
|
||||
const m = this.match;
|
||||
const enabled = this.host.settings().games.valorant;
|
||||
const queue = m?.queue ?? p?.queue ?? null;
|
||||
const custom = p?.provisioning === 'CustomGame';
|
||||
const mapUrl = p?.map || null;
|
||||
const map = this.host.assets.valMap(mapUrl);
|
||||
const phase = !enabled
|
||||
? '연동 꺼짐'
|
||||
: !this.auth
|
||||
? 'Riot 클라이언트 꺼짐'
|
||||
: !p
|
||||
? '발로란트 꺼짐'
|
||||
: p.state === 'INGAME'
|
||||
? '경기 중'
|
||||
: p.state === 'PREGAME'
|
||||
? '요원 선택'
|
||||
: p.partyState === 'MATCHMAKING'
|
||||
? '대기열'
|
||||
: p.partyState === 'MATCHMADE_GAME_STARTING'
|
||||
? '경기 찾음 · 시작 중'
|
||||
: '메뉴';
|
||||
const inGame = !!m && p?.state === 'INGAME';
|
||||
const roundBased = !valNoRounds(queue);
|
||||
const score = inGame && p?.ally != null && p?.enemy != null ? { ally: p.ally, enemy: p.enemy } : null;
|
||||
return {
|
||||
game: 'valorant',
|
||||
enabled,
|
||||
connected: !!this.auth,
|
||||
phase,
|
||||
inMatch: !!m,
|
||||
matchId: m?.id ?? null,
|
||||
mode: custom ? '사용자 지정' : queue ? (valModeKo(queue) ?? queue) : null,
|
||||
map: map?.name ?? (mapUrl ? mapUrl.split('/').pop() ?? null : null),
|
||||
mapImage: map?.image ?? null,
|
||||
startedAt: m?.startedAt ?? null,
|
||||
round: inGame && roundBased && score ? score.ally + score.enemy + 1 : null,
|
||||
score,
|
||||
gameTimeSec: null,
|
||||
teamKills: null,
|
||||
self: this.auth ? { name: this.selfName, character: m?.selfAgent ?? null, characterImage: null, kda: null, extra: null } : null,
|
||||
players: m?.players || null,
|
||||
error: this.lastErr || null,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
private async local<T = any>(path: string): Promise<T | null> {
|
||||
const lock = this.auth?.lock ?? readLockfile(riotClientLockfilePath());
|
||||
if (!lock) return null;
|
||||
@@ -123,6 +177,8 @@ export class ValorantAdapter implements GameAdapter {
|
||||
}
|
||||
this.auth = { lock, accessToken: ent.data.accessToken, entitlement: ent.data.token, puuid: ent.data.subject, region, shard, clientVersion };
|
||||
this.authAt = Date.now();
|
||||
const chat = await request(`${base}/chat/v1/session`, { headers: h, local: true }).catch(() => null);
|
||||
if (chat?.data?.game_name) this.selfName = `${chat.data.game_name}#${chat.data.game_tag ?? ''}`;
|
||||
log.info(`Riot 클라이언트 연결 (region=${region}, shard=${shard})`);
|
||||
return this.auth;
|
||||
}
|
||||
@@ -173,7 +229,8 @@ export class ValorantAdapter implements GameAdapter {
|
||||
if (!p) return;
|
||||
if (p.state === 'INGAME' && !this.match) await this.beginMatch(a, p);
|
||||
else if (p.state !== 'INGAME' && this.match && prev?.state === 'INGAME') this.endMatch();
|
||||
else if (this.match && p.ally !== null && p.enemy !== null) {
|
||||
else if (this.match && p.ally !== null && p.enemy !== null && !valNoRounds(this.match.queue)) {
|
||||
// 데스매치 · 팀 데스매치 · 에스컬레이션은 점수가 킬 수라서 라운드로 보지 않는다 (v1.3.5: "R63 승리 · 26:37" 같은 가짜 라운드)
|
||||
const m = this.match;
|
||||
const total = p.ally + p.enemy;
|
||||
if (total > m.ally + m.enemy) {
|
||||
@@ -220,7 +277,8 @@ export class ValorantAdapter implements GameAdapter {
|
||||
team: pl.TeamID,
|
||||
character: this.host.assets.agent(pl.CharacterID),
|
||||
}));
|
||||
this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0 };
|
||||
const selfAgent = players.find((pl: { puuid: string }) => pl.puuid === a.puuid)?.character?.name ?? null;
|
||||
this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0, queue: p.queue, selfAgent: selfAgent && selfAgent !== '?' ? selfAgent : null, players: players.length };
|
||||
this.seenChat.clear();
|
||||
this.host.matchStarted({
|
||||
id,
|
||||
@@ -299,6 +357,7 @@ export class ValorantAdapter implements GameAdapter {
|
||||
const r = await request(`${this.pd(a)}/match-details/v1/matches/${matchId}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
|
||||
if (r.status === 200 && r.data?.matchInfo) {
|
||||
this.detailQueue.delete(id);
|
||||
await this.fillNames(a, r.data);
|
||||
this.applyDetails(id, r.data, a.puuid, q.startedLocal);
|
||||
continue;
|
||||
}
|
||||
@@ -313,6 +372,30 @@ export class ValorantAdapter implements GameAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 경기 상세에 선수 이름이 비어 오면(Riot 이 이름을 가림) 이름 서비스로 채운다. 내 이름은 로컬 채팅 세션 값으로.
|
||||
* v1.3.5 는 빈 이름을 그대로 써서 "주인 계정 자동 연결: #" 이 남았다.
|
||||
*/
|
||||
private async fillNames(a: Auth, md: any): Promise<void> {
|
||||
const players: any[] = md.players || [];
|
||||
const missing = players.filter((p) => !p.gameName).map((p) => p.subject);
|
||||
if (!missing.length) return;
|
||||
try {
|
||||
const r = await request(`${this.pd(a)}/name-service/v2/players`, { method: 'PUT', headers: this.pvpHeaders(a), body: missing, timeoutMs: 8000 });
|
||||
for (const n of Array.isArray(r.data) ? r.data : []) {
|
||||
const p = players.find((x) => x.subject === n.Subject);
|
||||
if (p && n.GameName) {
|
||||
p.gameName = n.GameName;
|
||||
p.tagLine = n.TagLine ?? p.tagLine;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.debug('이름 서비스 조회 실패', e);
|
||||
}
|
||||
const me = players.find((p) => p.subject === a.puuid);
|
||||
if (me && !me.gameName && this.selfName) [me.gameName, me.tagLine] = this.selfName.split('#');
|
||||
}
|
||||
|
||||
applyDetails(id: string, md: any, selfPuuid: string, startedLocal: number): void {
|
||||
const res = processMatchDetails(md, selfPuuid, this.host.assets, id, startedLocal);
|
||||
this.host.store.replaceRounds(id, res.rounds);
|
||||
@@ -359,6 +442,8 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
|
||||
const rr: any[] = md.roundResults || [];
|
||||
const n = rr.length;
|
||||
// 데스매치 · 팀 데스매치 · 에스컬레이션: 경기 전체가 "라운드 1" 하나로 온다. 라운드 · 에이스(한 라운드 5킬)를 만들지 않는다
|
||||
const noRounds = valNoRounds(info.queueID);
|
||||
// 라운드 전투 시작 시각(게임 시간) = 킬 gameTime - roundTime
|
||||
const combat: (number | null)[] = rr.map((r) => {
|
||||
let best: number | null = null;
|
||||
@@ -427,7 +512,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
}
|
||||
if (r.bombPlanter) tally(r.bombPlanter).plants++;
|
||||
if (r.bombDefuser) tally(r.bombDefuser).defuses++;
|
||||
rounds.push({
|
||||
if (!noRounds) rounds.push({
|
||||
match_id: id,
|
||||
num,
|
||||
started_at: S + start,
|
||||
@@ -439,7 +524,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
enemy_score: enemy,
|
||||
economy: JSON.stringify(economy),
|
||||
});
|
||||
roundsDetail.push({
|
||||
if (!noRounds) roundsDetail.push({
|
||||
num,
|
||||
startedAt: S + start + clockOffset,
|
||||
endedAt: S + end + clockOffset,
|
||||
@@ -485,7 +570,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
});
|
||||
}
|
||||
for (const [puuid, cnt] of Object.entries(killsBy)) {
|
||||
if (cnt >= 4) {
|
||||
if (cnt >= 4 && !noRounds) {
|
||||
const last = kills.filter((k: any) => k.killer === puuid).pop();
|
||||
events.push({
|
||||
id: `${id}:${cnt >= 5 ? 'ace' : 'multikill'}:${num}:${puuid}`,
|
||||
@@ -530,7 +615,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
});
|
||||
}
|
||||
const rd: RoundEndData = { round: num, win, result: roundResultKo(r.roundResult), score: { ally, enemy } };
|
||||
events.push({
|
||||
if (!noRounds) events.push({
|
||||
id: `${id}:round_end:${num}`,
|
||||
match_id: id,
|
||||
game: 'valorant',
|
||||
@@ -570,7 +655,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
mode: assets.val?.modes[info.gameMode] ?? info.queueID ?? null,
|
||||
result: {
|
||||
win: selfTeamInfo ? !!selfTeamInfo.won : null,
|
||||
score: { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy },
|
||||
score: noRounds ? null : { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { buildApi } from './api/server.js';
|
||||
import { buildApi, toUser } from './api/server.js';
|
||||
import { Culprit } from './culprit.js';
|
||||
import { Store } from './db/db.js';
|
||||
import { Dictionary } from './dict/dictionary.js';
|
||||
@@ -52,6 +52,10 @@ export async function startCore(opts: CoreOptions) {
|
||||
const store = new Store(paths().db);
|
||||
const bus = new Bus();
|
||||
bus.setMaxListeners(50);
|
||||
bus.usersProvider = () => {
|
||||
const acc = store.listAccounts();
|
||||
return store.listUsers().map((u) => toUser(u, acc));
|
||||
};
|
||||
const timeline = new Timeline(store);
|
||||
const dict = new Dictionary(store, opts.resourcesDir, () => S().dictionary.packs);
|
||||
dict.seed();
|
||||
@@ -75,7 +79,9 @@ export async function startCore(opts: CoreOptions) {
|
||||
},
|
||||
matchAt: (ts) => games.liveMatchAt(ts),
|
||||
});
|
||||
const announcer = new Announcer(paths().tts, opts.resourcesDir);
|
||||
const announcer = new Announcer(paths().tts, opts.resourcesDir, async (src, dst, tempo) => {
|
||||
await worker.request('tempo', { src, dst, tempo }, 120000);
|
||||
});
|
||||
const bot: Bot = new Bot(store, recorder, announcer, bus, S, (gid) => {
|
||||
if (!S().discord.guildId) settings.update({ discord: { guildId: gid } });
|
||||
});
|
||||
|
||||
@@ -17,6 +17,8 @@ export interface Settings {
|
||||
ttsText: string;
|
||||
ttsOnNewMember: boolean;
|
||||
ttsVoice: string;
|
||||
/** 녹음 안내 말 속도 0.1~2.0 (1.0 = 보통) */
|
||||
ttsRate: number;
|
||||
};
|
||||
games: {
|
||||
valorant: boolean;
|
||||
@@ -94,6 +96,7 @@ export function defaultSettings(): Settings {
|
||||
ttsText: DEFAULT_TTS_TEXT,
|
||||
ttsOnNewMember: true,
|
||||
ttsVoice: 'ko-KR-SunHiNeural',
|
||||
ttsRate: 1,
|
||||
},
|
||||
games: {
|
||||
valorant: true,
|
||||
|
||||
@@ -5,10 +5,18 @@ import type { Settings } from '../settings.js';
|
||||
import type { Timeline } from '../timeline.js';
|
||||
import type { Bus } from '../util/events.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import { removeInsertedSilence } from '../discord/ogg.js';
|
||||
import { WorkerClient, WorkerError, type TranscribeResult } from './worker.js';
|
||||
|
||||
const log = logger('stt');
|
||||
|
||||
const NOISE_REASON: Record<string, string> = {
|
||||
vad: '목소리 없음',
|
||||
no_speech: '말소리 아님',
|
||||
hallucination: '잡음에서 지어낸 문장',
|
||||
repetition: '같은 말만 반복',
|
||||
};
|
||||
|
||||
type Slot = 'realtime' | 'precise';
|
||||
interface Job {
|
||||
id: string;
|
||||
@@ -132,6 +140,8 @@ export class SttPipeline {
|
||||
|
||||
/** 시작 시 미처리분 복구 */
|
||||
resumePending(): void {
|
||||
this.purgeOldNoise();
|
||||
this.repairOldAudio();
|
||||
const rows = this.store.pendingUtterances();
|
||||
if (rows.length) log.info(`미처리 발화 ${rows.length}개 다시 대기열에 넣음`);
|
||||
for (const r of rows) this.enqueue(r.id, 'realtime', 5);
|
||||
@@ -270,11 +280,77 @@ export class SttPipeline {
|
||||
model: r.model,
|
||||
status: slot,
|
||||
});
|
||||
if (r.noise) this.onNoise(u, r, slot);
|
||||
if (!r.noise && r.lufs !== null && r.duration_s >= 1) this.store.updateGainProfile(u.user_id, r.lufs);
|
||||
if (r.text) this.store.hitDict(r.words.map((w) => w.w));
|
||||
this.emit(u.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 잡음 발화: 사이트에 보이지 않고(타임라인 조회에서 뺌) 음성 파일도 지운다. 로그에는 "잡음"으로 남긴다.
|
||||
* 경기 중 실시간 모델 결과는 경기 뒤 정밀 모델이 다시 보므로 그때까지 파일을 남긴다 (목소리 없음(VAD)은 모델과 상관없어 바로 지움).
|
||||
*/
|
||||
private onNoise(u: UtteranceRow, r: TranscribeResult, slot: Slot): void {
|
||||
const s = this.settings().stt;
|
||||
const recheck = slot === 'realtime' && r.noise_reason !== 'vad' && this.inMatch && s.reprocessAfterMatch && s.preciseModel !== s.realtimeModel;
|
||||
const name = this.store.getUser(u.user_id)?.name ?? u.user_id;
|
||||
const dur = ((u.ended_at - u.started_at) / 1000).toFixed(1);
|
||||
const why = NOISE_REASON[r.noise_reason ?? ''] ?? r.noise_reason ?? '?';
|
||||
const heard = r.raw_text ? `, 인식 "${r.raw_text.slice(0, 60)}"` : '';
|
||||
if (recheck) {
|
||||
log.info(`잡음 발화 ${u.id} (${name}, ${dur}초, ${why}${heard}) · 경기 뒤 정밀 모델로 다시 확인`);
|
||||
return;
|
||||
}
|
||||
this.deleteAudio(u);
|
||||
log.info(`잡음 발화 ${u.id} 숨김 · 음성 파일 삭제 (${name}, ${dur}초, ${why}${heard})`);
|
||||
}
|
||||
|
||||
private deleteAudio(u: UtteranceRow): void {
|
||||
if (u.audio_path) {
|
||||
try {
|
||||
fs.rmSync(u.audio_path, { force: true });
|
||||
} catch (e) {
|
||||
log.warn(`잡음 파일 삭제 실패 ${u.audio_path}`, e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.store.markAudioDeleted(u.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 번만: v1.3.5 이하 녹음에서 말 중간에 끼운 무음을 빼고(목소리 깨짐) 다시 변환한다.
|
||||
* 사람이 고친 발화는 파일만 고치고 글은 그대로 둔다.
|
||||
*/
|
||||
private repairOldAudio(): void {
|
||||
const KEY = 'audio_repair_v136';
|
||||
if (this.store.meta(KEY)) return;
|
||||
this.store.setMeta(KEY, String(Date.now()));
|
||||
const rows = this.store.db
|
||||
.prepare(`SELECT rowid,* FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND noise=0 ORDER BY started_at`)
|
||||
.all() as UtteranceRow[];
|
||||
let fixed = 0;
|
||||
for (const u of rows) {
|
||||
if (!u.audio_path || !fs.existsSync(u.audio_path)) continue;
|
||||
try {
|
||||
const removed = removeInsertedSilence(u.audio_path);
|
||||
if (!removed) continue;
|
||||
fixed++;
|
||||
this.store.db.prepare('UPDATE utterances SET ended_at=ended_at-? WHERE id=?').run(removed * 20, u.id);
|
||||
if (!u.corrected) this.enqueue(u.id, 'realtime', 20);
|
||||
} catch (e) {
|
||||
log.warn(`예전 녹음 고치기 실패 ${u.id}`, e);
|
||||
}
|
||||
}
|
||||
if (fixed) log.info(`예전 녹음 ${fixed}개에서 말 중간에 끼운 무음을 빼고 다시 변환`);
|
||||
}
|
||||
|
||||
/** v1.3.5 이하에서 잡음으로 판정된 발화의 남은 파일 정리 */
|
||||
private purgeOldNoise(): void {
|
||||
const rows = this.store.noiseWithAudio();
|
||||
for (const r of rows) this.deleteAudio(r);
|
||||
if (rows.length) log.info(`예전 잡음 발화 ${rows.length}개의 음성 파일 삭제`);
|
||||
}
|
||||
|
||||
private emit(id: string): void {
|
||||
const row = this.store.getUtterance(id);
|
||||
if (row) this.bus.live({ type: 'utterance.updated', data: this.timeline.utteranceItem(row) });
|
||||
|
||||
@@ -138,7 +138,8 @@ export class Timeline {
|
||||
where.push('u.started_at <= ?');
|
||||
args.push(q.to);
|
||||
}
|
||||
if (q.hideNoise) where.push('(u.noise = 0 OR u.corrected = 1)');
|
||||
// 잡음은 보여 주지 않는다 (v1.3.6~, 파일도 지움). 사람이 고친 발화는 보인다
|
||||
where.push('(u.noise = 0 OR u.corrected = 1)');
|
||||
if (q.q) {
|
||||
const kw = q.q.trim();
|
||||
if ([...kw].length >= 3) {
|
||||
@@ -224,7 +225,6 @@ export interface TimelineQuery {
|
||||
to?: number;
|
||||
q?: string;
|
||||
types?: string[];
|
||||
hideNoise?: boolean;
|
||||
cursor?: string;
|
||||
limit?: number;
|
||||
order?: 'asc' | 'desc';
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { LiveEvent } from '@gvr/shared';
|
||||
import type { LiveEvent, User } from '@gvr/shared';
|
||||
|
||||
/** 코어 내부 이벤트 버스. 'live' 는 사이트로 그대로 나가는 이벤트. */
|
||||
export class Bus extends EventEmitter {
|
||||
/** 'users.updated' 에 실을 유저 목록. 보내는 쪽은 신호만 주고 목록은 여기서 채운다 (빈 목록이 나가면 사이트에서 모든 발화가 "알 수 없음"이 됨) */
|
||||
usersProvider: (() => User[]) | null = null;
|
||||
|
||||
live(ev: LiveEvent): void {
|
||||
if (ev.type === 'users.updated' && this.usersProvider) ev = { type: 'users.updated', data: this.usersProvider() };
|
||||
this.emit('live', ev);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 설정 창(렌더러) ↔ Electron 메인 프로세스 IPC 계약. preload 가 window.gvr 로 노출한다.
|
||||
import type { AppRole, AppUserInfo, AppUserRow, User } from '@gvr/shared';
|
||||
import type { AppRole, AppUserInfo, AppUserRow, LiveGame, User } from '@gvr/shared';
|
||||
import type { AuthState } from '../core/auth.js';
|
||||
import type { DiagItem } from '../core/diagnostics.js';
|
||||
import type { BotState } from '../core/discord/bot.js';
|
||||
@@ -66,6 +66,8 @@ export interface AppState {
|
||||
stt: SttStatus;
|
||||
relay: RelayStatus;
|
||||
games: { valorant: { connected: boolean; inMatch: boolean; detail?: string }; lol: { connected: boolean; inMatch: boolean; detail?: string } };
|
||||
/** 지금 게임 상태 (v1.3.6~) */
|
||||
liveGames?: LiveGame[];
|
||||
counts: { utterances: number; matches: number };
|
||||
excludedUsers: { id: string; name: string }[];
|
||||
autoStart: boolean;
|
||||
@@ -91,7 +93,7 @@ export interface GvrApi {
|
||||
testBotToken(token?: string): Promise<{ ok: boolean; bot?: { id: string; name: string; avatar: string | null }; guilds?: { id: string; name: string }[]; error?: string }>;
|
||||
restartBot(): Promise<{ ok: boolean; error?: string }>;
|
||||
guildMembers(): Promise<{ id: string; name: string; avatar: string | null; bot: boolean; me: boolean; admin: boolean }[]>;
|
||||
previewTts(text: string, voice: string): Promise<{ ok: boolean; dataUrl?: string; error?: string }>;
|
||||
previewTts(text: string, voice: string, rate?: number): Promise<{ ok: boolean; dataUrl?: string; error?: string }>;
|
||||
gpuInfo(): Promise<GpuInfo | null>;
|
||||
models(): Promise<ModelsInfo | null>;
|
||||
download(target: 'model' | 'cuda_runtime', name?: string): Promise<{ ok: boolean; error?: string }>;
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from 'node:path';
|
||||
import { toUser } from '../core/api/server.js';
|
||||
import type { AppAuth, AuthState } from '../core/auth.js';
|
||||
import { runDiagnostics } from '../core/diagnostics.js';
|
||||
import { synthesize } from '../core/discord/tts.js';
|
||||
import { clampRate, isOgg, render } from '../core/discord/tts.js';
|
||||
import type { Core } from '../core/index.js';
|
||||
import { registerDevice } from '../core/relay/client.js';
|
||||
import { dirSize } from '../core/retention.js';
|
||||
@@ -31,6 +31,7 @@ export function buildState(core: Core, opts: { dataDir: string; portable: boolea
|
||||
stt: core.stt.status,
|
||||
relay: core.relay.status,
|
||||
games: core.games.status() as AppState['games'],
|
||||
liveGames: core.games.live(),
|
||||
counts: core.store.counts(),
|
||||
excludedUsers: core.store
|
||||
.listUsers()
|
||||
@@ -131,13 +132,14 @@ export function registerIpc(ctx: IpcContext) {
|
||||
.map((m) => ({ id: m.id, name: core.store.displayNames()[m.id] ?? m.name, avatar: m.avatar, bot: m.bot, me: m.id === meId, admin: admins.includes(m.id) }))
|
||||
.sort((a, b) => rank(a) - rank(b) || a.name.localeCompare(b.name, 'ko'));
|
||||
},
|
||||
previewTts: async (text: string, voice: string) => {
|
||||
previewTts: async (text: string, voice: string, rate = 1) => {
|
||||
try {
|
||||
const f = path.join(core.paths().tts, `preview-${Date.now()}.webm`);
|
||||
await synthesize(text, voice, f);
|
||||
const r = clampRate(rate);
|
||||
const f = path.join(core.paths().tts, `preview-${Date.now()}.${r < 0.5 ? 'ogg' : 'webm'}`);
|
||||
await render(text, voice, r, f, (src, dst, tempo) => core.worker.request('tempo', { src, dst, tempo }, 120000));
|
||||
const data = fs.readFileSync(f);
|
||||
fs.rmSync(f, { force: true });
|
||||
return { ok: true, dataUrl: `data:audio/webm;base64,${data.toString('base64')}` };
|
||||
return { ok: true, dataUrl: `data:audio/${isOgg(f) ? 'ogg' : 'webm'};base64,${data.toString('base64')}` };
|
||||
} catch (e: any) {
|
||||
return { ok: false, error: `음성 합성 실패: ${e.message}` };
|
||||
}
|
||||
|
||||
@@ -94,7 +94,10 @@ function openWindow(route?: string): void {
|
||||
win.setMenu(null);
|
||||
win.on('page-title-updated', (e) => e.preventDefault());
|
||||
win.loadFile(path.join(rendererDir(), 'index.html'), { hash: r });
|
||||
win.once('ready-to-show', () => win?.show());
|
||||
win.once('ready-to-show', () => {
|
||||
win?.show();
|
||||
closeSplash();
|
||||
});
|
||||
// 창을 닫아도 트레이에서 계속 돈다 (녹음·사이트 연결 유지)
|
||||
win.on('close', (e) => {
|
||||
if (!quitting) {
|
||||
@@ -104,6 +107,46 @@ function openWindow(route?: string): void {
|
||||
});
|
||||
}
|
||||
|
||||
// ── 시작 창: 포터블 exe 는 풀고 켜는 데 시간이 걸린다. 큰 창이 뜨기 전까지 작은 "켜는 중" 창을 바로 띄운다 ──
|
||||
let splash: BrowserWindow | null = null;
|
||||
|
||||
function showSplash(): void {
|
||||
const banner = path.join(brandDir(), 'banner.png');
|
||||
const img = fs.existsSync(banner) ? `data:image/png;base64,${fs.readFileSync(banner).toString('base64')}` : '';
|
||||
const html = `<!doctype html><meta charset="utf-8"><style>
|
||||
html,body{margin:0;height:100%;background:#0b141c;color:#e8dfcd;font:14px 'Malgun Gothic','Segoe UI',sans-serif;overflow:hidden;user-select:none;-webkit-app-region:drag}
|
||||
img{display:block;width:480px;height:192px}
|
||||
.bar{height:3px;background:#1d2a35;overflow:hidden}.bar i{display:block;height:100%;width:30%;background:#ff4d5a;animation:m 1.2s ease-in-out infinite}
|
||||
@keyframes m{0%{transform:translateX(-100%)}100%{transform:translateX(340%)}}
|
||||
#t{text-align:center;padding:9px 0 0}
|
||||
</style>${img ? `<img src="${img}">` : '<div style="height:192px"></div>'}<div class="bar"><i></i></div><div id="t">겜녹이를 켜는 중입니다…</div>`;
|
||||
splash = new BrowserWindow({
|
||||
width: 480,
|
||||
height: 232,
|
||||
frame: false,
|
||||
resizable: false,
|
||||
movable: true,
|
||||
center: true,
|
||||
show: false,
|
||||
title: '겜녹이 · 켜는 중',
|
||||
icon: path.join(brandDir(), 'icon.png'),
|
||||
backgroundColor: '#0b141c',
|
||||
webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, javascript: true },
|
||||
});
|
||||
splash.once('ready-to-show', () => splash?.show());
|
||||
splash.on('closed', () => (splash = null));
|
||||
void splash.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`).catch(() => undefined);
|
||||
}
|
||||
|
||||
function splashText(text: string): void {
|
||||
if (splash && !splash.isDestroyed()) splash.webContents.executeJavaScript(`document.getElementById('t').textContent=${JSON.stringify(text)}`).catch(() => undefined);
|
||||
}
|
||||
|
||||
function closeSplash(): void {
|
||||
if (splash && !splash.isDestroyed()) splash.destroy();
|
||||
splash = null;
|
||||
}
|
||||
|
||||
function updateTray(): void {
|
||||
if (!tray) return;
|
||||
if (!core) {
|
||||
@@ -299,6 +342,7 @@ app.whenReady().then(async () => {
|
||||
// 마이크 · 카메라 · 위치 · 알림 등 권한 요청은 모두 거절한다 (아이디 복사용 클립보드 쓰기만 허용)
|
||||
session.defaultSession.setPermissionRequestHandler((_wc, perm, cb) => cb(perm === 'clipboard-sanitized-write'));
|
||||
if (SMOKE) return smoke();
|
||||
if (!flag('hidden')) showSplash();
|
||||
settings = new SettingsStore(dataDir, dpapiCodec());
|
||||
auth = new AppAuth(settings, { version: app.getVersion(), openUrl: (u) => shell.openExternal(u) });
|
||||
const a = auth;
|
||||
@@ -336,9 +380,14 @@ app.whenReady().then(async () => {
|
||||
buildTrayMenu();
|
||||
pushState();
|
||||
}, 1500);
|
||||
splashText('로그인 확인 중…');
|
||||
await first;
|
||||
if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…');
|
||||
await authChain;
|
||||
if (!flag('hidden') || !settings.get().firstRunDone || !a.ok) openWindow();
|
||||
else closeSplash();
|
||||
// 창이 끝내 안 뜨는 경우(오류 등)에도 시작 창이 남지 않게
|
||||
setTimeout(closeSplash, 30000);
|
||||
if (process.env.GVR_CAPTURE_DIR) void captureScreens(process.env.GVR_CAPTURE_DIR);
|
||||
});
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ function defaults(): Settings {
|
||||
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
|
||||
ttsOnNewMember: true,
|
||||
ttsVoice: 'ko-KR-SunHiNeural',
|
||||
ttsRate: 1,
|
||||
},
|
||||
games: { valorant: true, lol: true, lolLogsDir: null },
|
||||
stt: {
|
||||
@@ -158,6 +159,17 @@ export function createMockGvr(): GvrApi {
|
||||
valorant: { connected: true, inMatch: false, detail: 'Riot Client 연결됨 · 대기실' },
|
||||
lol: { connected: false, inMatch: false, detail: '클라이언트 꺼짐' },
|
||||
},
|
||||
liveGames: [
|
||||
{
|
||||
game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null,
|
||||
startedAt: now - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null,
|
||||
self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, updatedAt: now,
|
||||
},
|
||||
{
|
||||
game: 'lol', enabled: true, connected: true, phase: '로비', inMatch: false, matchId: null, mode: '솔로 랭크', map: null, mapImage: null,
|
||||
startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: null, characterImage: null, kda: null, extra: null }, players: null, error: null, updatedAt: now,
|
||||
},
|
||||
],
|
||||
counts: { utterances: 1824, matches: 37 },
|
||||
excludedUsers: noToken ? [] : [{ id: 'u4', name: '현우' }],
|
||||
autoStart: false,
|
||||
|
||||
@@ -316,3 +316,43 @@ input[type='number'].input { flex: none; padding: 7px 8px; }
|
||||
.admin-list { list-style: none; display: flex; flex-direction: column; gap: 6px; font-size: 13px; }
|
||||
.admin-list li { display: flex; gap: 8px; align-items: baseline; }
|
||||
.admin-list li .muted { font-size: 12px; }
|
||||
|
||||
/* 지금 게임 (게임 연동 탭) */
|
||||
.live-games {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
.live-game {
|
||||
border: 1px solid var(--line, #22313f);
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
.live-game.in-match.valorant {
|
||||
border-color: rgba(255, 70, 85, 0.55);
|
||||
}
|
||||
.live-game.in-match.lol {
|
||||
border-color: rgba(200, 170, 110, 0.6);
|
||||
}
|
||||
.live-game-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.live-game-top .badge {
|
||||
margin-left: auto;
|
||||
}
|
||||
.live-rows {
|
||||
width: 100%;
|
||||
font-size: 12.5px;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.live-rows td {
|
||||
padding: 3px 0;
|
||||
vertical-align: top;
|
||||
}
|
||||
.live-rows td:first-child {
|
||||
width: 42%;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { GvrApi } from '../../main/api-types';
|
||||
import { gvr, useAction, useApp, useLoad } from '../store';
|
||||
import { AdminOnly, Avatar, Btn, DraftInput, Err, Line, Ok, Page, Section, Select, ToggleLine, useIsAdmin } from '../ui';
|
||||
import { AdminOnly, Avatar, Btn, DraftInput, Err, Line, Ok, Page, Section, Select, Slider, ToggleLine, useIsAdmin } from '../ui';
|
||||
import { errMsg, fmtClock, fmtDuration } from '../util';
|
||||
|
||||
type TestResult = Awaited<ReturnType<GvrApi['testBotToken']>>;
|
||||
@@ -248,7 +248,7 @@ function TtsPreview() {
|
||||
<Btn
|
||||
busy={act.busy}
|
||||
onClick={async () => {
|
||||
const r = await act.run(() => gvr.previewTts(settings.discord.ttsText, settings.discord.ttsVoice));
|
||||
const r = await act.run(() => gvr.previewTts(settings.discord.ttsText, settings.discord.ttsVoice, settings.discord.ttsRate));
|
||||
if (r?.ok && r.dataUrl) {
|
||||
audio.current?.pause();
|
||||
audio.current = new Audio(r.dataUrl);
|
||||
@@ -337,6 +337,9 @@ export function DiscordTab() {
|
||||
<Line label="목소리">
|
||||
<Select width={200} value={d.ttsVoice} options={VOICES} onChange={(v) => save({ discord: { ttsVoice: v } })} />
|
||||
</Line>
|
||||
<Line label="말 속도" hint="0.1배(아주 느리게) ~ 2.0배(빠르게), 보통 1.0배">
|
||||
<Slider value={d.ttsRate ?? 1} min={0.1} max={2} step={0.1} fmt={(v) => `${v.toFixed(1)}배`} onCommit={(v) => save({ discord: { ttsRate: Math.round(v * 10) / 10 } })} />
|
||||
</Line>
|
||||
<Line
|
||||
label={
|
||||
<>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import type { User } from '@gvr/shared';
|
||||
import { GAME_NAME, liveGameRows, type LiveGame, type User } from '@gvr/shared';
|
||||
import { gvr, useAction, useApp, useLoad } from '../store';
|
||||
import { Avatar, Btn, Dot, Err, FolderRow, Page, Section, Spinner, Toggle } from '../ui';
|
||||
|
||||
@@ -52,6 +52,38 @@ export function GameCards({ showStatus = true }: { showStatus?: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** 지금 연결된 게임 · 진행 중인 경기 자세히 (v1.3.6~) */
|
||||
function LiveGames() {
|
||||
const { state } = useApp();
|
||||
const live = state.liveGames ?? [];
|
||||
if (!live.length) return null;
|
||||
return (
|
||||
<Section title="지금 게임" sub="2초마다 새로 고침">
|
||||
<div className="live-games">
|
||||
{live.map((g: LiveGame) => (
|
||||
<div key={g.game} className={`live-game ${g.game}${g.inMatch ? ' in-match' : ''}`}>
|
||||
<div className="live-game-top">
|
||||
<Dot tone={!g.enabled ? 'off' : g.inMatch ? 'ok' : g.connected ? 'warn' : 'off'} />
|
||||
<b>{GAME_NAME[g.game]}</b>
|
||||
<span className={`badge ${g.inMatch ? 'b-ok' : 'b-dim'}`}>{g.phase}</span>
|
||||
</div>
|
||||
<table className="live-rows">
|
||||
<tbody>
|
||||
{liveGameRows(g).map(([k, v]) => (
|
||||
<tr key={k}>
|
||||
<td className="muted">{k}</td>
|
||||
<td>{v}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
const RIOT_RE = /^[^#]{1,16}#[^#\s]{2,5}$/;
|
||||
|
||||
function RiotRow({ u }: { u: User }) {
|
||||
@@ -146,6 +178,7 @@ export function GamesTab() {
|
||||
return (
|
||||
<Page title="게임 연동">
|
||||
<GameCards />
|
||||
<LiveGames />
|
||||
<Section title="리그 오브 레전드 세부 설정" className={g.lol ? '' : 'disabled'}>
|
||||
<div className="muted" style={{ marginBottom: 8 }}>
|
||||
롤 채팅은 롤 클라이언트(LCU) API 로 챔피언 선택 · 게임 후 채팅을 받습니다. 게임 중 전체 · 팀 채팅은 롤이 API 로 주지 않아, 게임 로그 파일에 남아 있을 때만 경기 뒤에 붙입니다. 화면 글자 인식(OCR)은 쓰지 않습니다.
|
||||
|
||||
@@ -10,7 +10,8 @@ import { diffWords, Dictionary } from '../src/core/dict/dictionary.ts';
|
||||
import { realignWords } from '../src/core/api/server.ts';
|
||||
import { processMatchDetails } from '../src/core/games/valorant.ts';
|
||||
import { GameAssets } from '../src/core/games/assets.ts';
|
||||
import { OggOpusWriter, opusSamples, SILENCE_FRAME } from '../src/core/discord/ogg.ts';
|
||||
import { OggOpusWriter, opusSamples, removeInsertedSilence, SILENCE_FRAME } from '../src/core/discord/ogg.ts';
|
||||
import { Utterance, tagRtp, tapRtp } from '../src/core/discord/recorder.ts';
|
||||
import { Retention } from '../src/core/retention.ts';
|
||||
import { makeValDetails, SELF } from './fixtures/make-val-details.ts';
|
||||
|
||||
@@ -34,6 +35,81 @@ test('Ogg Opus writer: ffmpeg 가 읽을 수 있고 길이가 맞다', () => {
|
||||
execFileSync('ffmpeg', ['-v', 'error', '-i', out, '-f', 'null', '-']);
|
||||
});
|
||||
|
||||
test('녹음기: 패킷이 몰려 와도 말 중간에 무음을 넣지 않는다 (RTP 타임스탬프 기준)', () => {
|
||||
// 게임 중 실제 수신 모양: 20ms 간격으로 만든 패킷이 40~60ms 마다 2~3개씩 한꺼번에 도착 (v1.3.5 사용자 파일 "##.##.##")
|
||||
const dir = tmp();
|
||||
const voice = Array.from({ length: 100 }, (_, i) => Buffer.from([0x78, i & 0xff, 0x01]));
|
||||
const u = new Utterance(dir, 1_000_000);
|
||||
let now = 1_000_020;
|
||||
let seq = 65530; // 순번이 한 바퀴 도는 경우도 함께
|
||||
let ts = 4294967296 - 960 * 10; // 타임스탬프도 한 바퀴 돔
|
||||
let filled = 0;
|
||||
for (let i = 0; i < voice.length; i++) {
|
||||
if (i === 60) {
|
||||
// 진짜 쉼 0.4초: 패킷 20개 자리가 비었다
|
||||
seq = (seq + 20) & 0xffff;
|
||||
ts = (ts + 960 * 20) >>> 0;
|
||||
now += 400;
|
||||
}
|
||||
if (i % 3 === 0) now += 60; // 3개씩 몰려 도착
|
||||
filled += Math.max(0, u.place(tagRtp(voice[i], { seq, ts }), now, 1000));
|
||||
seq = (seq + 1) & 0xffff;
|
||||
ts = (ts + 960) >>> 0;
|
||||
}
|
||||
// 중복 패킷은 버린다
|
||||
assert.equal(u.place(tagRtp(Buffer.from([0x78, 0, 0]), { seq: (seq - 1) & 0xffff, ts: (ts - 960) >>> 0 }), now, 1000), -1);
|
||||
assert.equal(filled, 20, '진짜 쉼만 채운다');
|
||||
assert.equal(u.writer.samples, (100 + 20) * 960);
|
||||
u.writer.close();
|
||||
});
|
||||
|
||||
test('예전 녹음 고치기: 말 중간에 끼운 무음만 빼고 말 끝 무음은 남긴다', () => {
|
||||
const f = path.join(tmp(), 'old.ogg');
|
||||
const w = new OggOpusWriter(f);
|
||||
const v = (i: number) => Buffer.from([0x78, i, 1]);
|
||||
// "##.##.##" + 진짜 쉼(10) + "##" + 말 끝 무음 5
|
||||
const seq = [v(1), v(2), SILENCE_FRAME, v(3), v(4), SILENCE_FRAME, v(5), v(6), ...Array(10).fill(SILENCE_FRAME), v(7), v(8), ...Array(5).fill(SILENCE_FRAME)];
|
||||
for (const p of seq) w.write(p);
|
||||
w.close();
|
||||
assert.equal(removeInsertedSilence(f), 2);
|
||||
const after = readOggPackets(fs.readFileSync(f)).slice(2);
|
||||
assert.equal(after.length, seq.length - 2);
|
||||
assert.equal(removeInsertedSilence(f), 0, '두 번 고치지 않는다');
|
||||
execFileSync('ffmpeg', ['-v', 'error', '-i', f, '-f', 'null', '-']);
|
||||
});
|
||||
|
||||
test('녹음기: RTP 시각이 없을 때도 몰려 온 패킷 사이에 무음을 넣지 않는다', () => {
|
||||
const u = new Utterance(tmp(), 1_000_000);
|
||||
let now = 1_000_020;
|
||||
let filled = 0;
|
||||
for (let i = 0; i < 60; i++) {
|
||||
if (i % 3 === 0) now += 60;
|
||||
filled += u.place(Buffer.from([0x78, i, 1]), now, 1000);
|
||||
}
|
||||
assert.equal(filled, 0);
|
||||
now += 500; // 0.5초 쉼 뒤 말
|
||||
filled += u.place(Buffer.from([0x78, 9, 1]), now, 1000);
|
||||
assert.ok(filled >= 18 && filled <= 25, `filled ${filled}`);
|
||||
u.writer.close();
|
||||
});
|
||||
|
||||
test('녹음기: 디스코드 수신기의 RTP 헤더를 패킷에 붙인다', () => {
|
||||
const rtp = Buffer.alloc(16);
|
||||
rtp[0] = 0x80;
|
||||
rtp.writeUInt16BE(1234, 2);
|
||||
rtp.writeUInt32BE(99999, 4);
|
||||
const opus = Buffer.from([0x78, 1, 2]);
|
||||
const receiver = { parsePacket: (_b: Buffer) => opus };
|
||||
assert.equal(tapRtp(receiver), true);
|
||||
assert.equal(tapRtp(receiver), true); // 두 번 감싸지 않음
|
||||
const out = receiver.parsePacket(rtp);
|
||||
const u = new Utterance(tmp(), 0);
|
||||
u.place(out, 20, 1000);
|
||||
assert.equal(u.rtpBase, 99999);
|
||||
assert.equal(u.lastSeq, 1234);
|
||||
u.writer.close();
|
||||
});
|
||||
|
||||
function readOggPackets(buf: Buffer): Buffer[] {
|
||||
const out: Buffer[] = [];
|
||||
let pos = 0;
|
||||
@@ -144,10 +220,10 @@ test('타임라인 조회: 필터·검색·커서', () => {
|
||||
store.updateUtteranceResult('n1', { text: null, raw_text: '시청해 주셔서 감사합니다', words: [], noise: true, noise_reason: 'hallucination', confidence: 0.2, lufs: -40, gain_db: 20, model: 'tiny', status: 'realtime' });
|
||||
let page = tl.query({ limit: 3 });
|
||||
assert.equal(page.items.length, 3);
|
||||
assert.equal(page.items[0].id, 'n1');
|
||||
assert.equal(page.items[0].id, 'x4', '잡음은 보이지 않는다');
|
||||
const page2 = tl.query({ limit: 3, cursor: page.next! });
|
||||
assert.deepEqual(page2.items.map((i) => i.id), ['x2', 'x1', 'x0']);
|
||||
assert.equal(tl.query({ hideNoise: true }).items.length, 5);
|
||||
assert.deepEqual(page2.items.map((i) => i.id), ['x1', 'x0']);
|
||||
assert.equal(tl.query({}).items.length, 5);
|
||||
assert.deepEqual(tl.query({ q: '레이즈 궁' }).items.map((i) => i.id), ['x1']);
|
||||
assert.deepEqual(tl.query({ q: '오퍼' }).items.map((i) => i.id), ['x2']);
|
||||
assert.equal(tl.query({ users: ['u2'] }).items.length, 2);
|
||||
@@ -208,3 +284,27 @@ test('표시 이름: 정한 이름으로 유저 이름 · 지난 범인 분석
|
||||
assert.equal(again.getUser('u1')?.name, '별명');
|
||||
again.close();
|
||||
});
|
||||
|
||||
test('users.updated: 보내는 쪽이 빈 목록을 줘도 실제 유저 목록이 나간다 ("알 수 없음" 버그)', async () => {
|
||||
const { Bus } = await import('../src/core/util/events.ts');
|
||||
const bus = new Bus();
|
||||
bus.usersProvider = () => [{ id: '1', name: '하늘', color: '#fff', avatar: null, excluded: false, riot: [] }];
|
||||
const got: any[] = [];
|
||||
bus.on('live', (e) => got.push(e));
|
||||
bus.live({ type: 'users.updated', data: [] });
|
||||
assert.equal(got[0].data.length, 1);
|
||||
assert.equal(got[0].data[0].name, '하늘');
|
||||
});
|
||||
|
||||
test('녹음 안내 말 속도: 0.1~2.0 으로 자르고 속도마다 따로 캐시한다', async () => {
|
||||
const { Announcer, clampRate } = await import('../src/core/discord/tts.ts');
|
||||
assert.equal(clampRate(0.05), 0.1);
|
||||
assert.equal(clampRate(3), 2);
|
||||
assert.equal(clampRate('x'), 1);
|
||||
const a = new Announcer(tmp(), tmp());
|
||||
const one = a.cachedPath('안내', 'v', 1);
|
||||
assert.equal(one, a.cachedPath('안내', 'v'), '1.0배는 예전 캐시 그대로');
|
||||
assert.notEqual(a.cachedPath('안내', 'v', 1.5), one);
|
||||
assert.ok(a.cachedPath('안내', 'v', 0.3).endsWith('.ogg'), '0.5배보다 느리면 워커가 만든 Ogg');
|
||||
assert.ok(a.cachedPath('안내', 'v', 0.5).endsWith('.webm'));
|
||||
});
|
||||
|
||||
@@ -63,11 +63,22 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
|
||||
assert.ok(q.gain_db > 15, `quiet gain ${q.gain_db}`);
|
||||
const k = core.store.getUtterance('keys')!;
|
||||
assert.equal(k.noise, 1);
|
||||
// 잡음: 파일을 지우고 사이트에 보이지 않는다
|
||||
assert.equal(k.audio_deleted, 1);
|
||||
assert.ok(!fs.existsSync(k.audio_path!));
|
||||
assert.ok(live.filter((e) => e.type === 'utterance.updated').length >= 3);
|
||||
// 기록 API (사이트가 중계로 부르는 것과 같은 경로)
|
||||
const res = await core.api.inject({ method: 'GET', url: '/api/timeline?limit=10' });
|
||||
const page = res.json();
|
||||
assert.equal(page.items.length, 3);
|
||||
assert.deepEqual(page.items.map((i: any) => i.id).sort(), ['quiet', 'speech']);
|
||||
// 우클릭 → 자세한 정보: 원본 ogg 이름 · 경로
|
||||
const info = (await core.api.inject({ method: 'GET', url: '/api/utterances/speech/info' })).json();
|
||||
assert.equal(info.fileName, 'speech.ogg');
|
||||
assert.equal(info.path, sp.audio_path);
|
||||
assert.equal(info.folder, path.dirname(sp.audio_path!));
|
||||
assert.ok(info.sizeBytes > 1000);
|
||||
assert.equal(info.deleted, null);
|
||||
assert.equal((await core.api.inject({ method: 'GET', url: '/api/utterances/keys/info' })).json().deleted, 'noise');
|
||||
const audio = await core.api.inject({ method: 'GET', url: '/api/audio/speech', headers: { range: 'bytes=0-99' } });
|
||||
assert.equal(audio.statusCode, 206);
|
||||
assert.equal(audio.rawPayload.length, 100);
|
||||
|
||||
@@ -65,6 +65,14 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
|
||||
await until(() => store.events('val-m-0001').filter((e) => e.type === 'chat').length === 2, 5000, 'chat');
|
||||
mock.st.ally = 1;
|
||||
await until(() => store.events('val-m-0001').some((e) => e.type === 'round_end'), 5000, 'live round');
|
||||
// 지금 게임 상태 (앱 게임 연동 탭 · 사이트)
|
||||
const lv = gm.live().find((g) => g.game === 'valorant')!;
|
||||
assert.equal(lv.phase, '경기 중');
|
||||
assert.equal(lv.mode, '경쟁전');
|
||||
assert.equal(lv.round, 2);
|
||||
assert.deepEqual(lv.score, { ally: 1, enemy: 0 });
|
||||
assert.equal(lv.self?.name, '하늘#KR1');
|
||||
await until(() => live.some((e) => e.type === 'games.state' && e.data[0].inMatch), 5000, 'games.state');
|
||||
// 발화 하나 (경기 중)
|
||||
store.insertUtterance({ id: 'u-val', session_id: null, user_id: 'owner', started_at: Date.now(), ended_at: Date.now() + 500, audio_path: null, match_id: gm.liveMatchAt(Date.now()) });
|
||||
assert.equal(store.getUtterance('u-val')!.match_id, 'val-m-0001');
|
||||
@@ -93,6 +101,13 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
|
||||
]);
|
||||
await until(() => !!store.getMatch('lol-7001'), 5000, 'lol start');
|
||||
await until(() => store.events('lol-7001').length >= 4, 5000, 'lol events');
|
||||
const ll = gm.live().find((g) => g.game === 'lol')!;
|
||||
assert.equal(ll.phase, '경기 중');
|
||||
assert.equal(ll.mode, '솔로 랭크');
|
||||
assert.equal(ll.self?.character, '아리');
|
||||
assert.equal(ll.self?.kda, '3/1/2');
|
||||
assert.deepEqual(ll.teamKills, { ally: 4, enemy: 2 });
|
||||
assert.equal(ll.gameTimeSec, 120);
|
||||
const lev = store.events('lol-7001');
|
||||
const chat = lev.find((e) => e.type === 'chat')!;
|
||||
assert.equal(JSON.parse(chat.data).text, '정글 갱 갈게요');
|
||||
@@ -121,3 +136,23 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('발로란트 데스매치: 경기 전체가 라운드 1개로 와도 라운드 · 에이스를 만들지 않는다', async () => {
|
||||
const { processMatchDetails } = await import('../src/core/games/valorant.ts');
|
||||
const { GameAssets } = await import('../src/core/games/assets.ts');
|
||||
const { makeValDetails, SELF } = await import('./fixtures/make-val-details.ts');
|
||||
const md = makeValDetails(1_000_000);
|
||||
md.matchInfo.queueID = 'deathmatch';
|
||||
// 한 "라운드"에 한 사람이 5킬 (데스매치에서는 흔함)
|
||||
const r0 = md.roundResults[0];
|
||||
const ps = r0.playerStats.find((p: any) => p.subject === SELF)!;
|
||||
const k = ps.kills[0];
|
||||
ps.kills = Array.from({ length: 6 }, (_, i) => ({ ...k, gameTime: k.gameTime + i * 1000, victim: `enemy-${i}` }));
|
||||
md.roundResults = [r0];
|
||||
const res = processMatchDetails(md, SELF, new GameAssets(tmp()), 'val-dm', 1_000_000);
|
||||
assert.equal(res.rounds.length, 0);
|
||||
assert.equal(res.roundsDetail.length, 0);
|
||||
assert.ok(!res.events.some((e) => e.type === 'round_end' || e.type === 'ace' || e.type === 'multikill'));
|
||||
assert.ok(res.events.filter((e) => e.type === 'kill').length >= 6);
|
||||
assert.equal(res.result.score, null);
|
||||
});
|
||||
|
||||
@@ -61,6 +61,7 @@ export async function startMockRiot(dir: string) {
|
||||
],
|
||||
[/^\/chat\/v4\/presences$/, () => [200, { presences: [{ puuid: SELF, product: 'valorant', private: presence() }] }]],
|
||||
[/^\/chat\/v6\/messages$/, () => [200, { messages: st.valMessages }]],
|
||||
[/^\/chat\/v1\/session$/, () => [200, { game_name: '하늘', game_tag: 'KR1', puuid: SELF }]],
|
||||
// ---- glz
|
||||
[/^\/core-game\/v1\/players\/(.+)$/, () => (st.valState === 'INGAME' ? [200, { Subject: SELF, MatchID: st.valMatchId }] : [404, { errorCode: 'RESOURCE_NOT_FOUND' }])],
|
||||
[
|
||||
|
||||
BIN
assets/app/splash.bmp
Normal file
BIN
assets/app/splash.bmp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 326 KiB |
@@ -190,3 +190,16 @@ VOICE E2E PASS
|
||||
- 표시 이름: 이름을 바꾸기 전에 시작한 분석이 바꾼 뒤 저장되면 예전 이름이 남던 빈틈 (`setDisplayNames` 가 이미 바뀐 유저를 건너뜀 + 저장 경로에서 이름을 바꾸지 않음). `culprit.test.ts` 에 "바꾼 뒤 도착한 분석 · 다시 받기" 회귀 테스트 추가, 예전 코드에서 실패하는 것 확인 뒤 고침
|
||||
- 상태 메시지 실제 디스코드 확인 (`site/server/scripts/presence-e2e.mts`, 테스트 봇 · 빈 음성채널): 들어간 뒤 0.2초에 `dnd "🔴 녹음 중"`, 나온 뒤 0.2초에 `online "🎙️ 대기 중 · /녹음시작"` (디스코드가 보낸 음성 상태 이벤트로 바뀜)
|
||||
- 테스트: 앱 41 · 사이트 서버 16 통과
|
||||
- Windows CI (3f7bf1c, full) 7개 모두 PASS · 앱 버전 1.3.5 → Gitea 릴리스 v1.3.5 (v1.3.3 · v1.3.4 에 새 버전 안내)
|
||||
|
||||
## v1.3.6 — 목소리 깨짐 · 알 수 없음 · 잡음 숨기기 · 사이트 로그 · 지금 게임 (2026-10-16)
|
||||
|
||||
사용자가 보낸 GVR-Data(발화 40개 · 데스매치 1경기)를 분석했다.
|
||||
|
||||
- 목소리 깨짐 원인: ogg 패킷을 열어 보니 경기 중 파일이 `##.##.##` 모양 (목소리 2개 → 무음 1개 반복). "S매치" 발화 파일 8.48초 중 무음 132개(2.64초), 실제 수신 시간은 약 6.97초 (`created_at` - 끝 대기 0.8초 - 시작). 녹음기가 패킷 도착 간격(`now - lastArrival`)으로 쉼을 채웠는데 게임 중에는 패킷이 몰려 와서 말 중간에 무음이 끼었다. 경기 전 파일도 일부 같은 모양
|
||||
- 확인: 끼운 무음을 뺀 파일과 원래 파일을 Whisper large-v3(CPU)로 비교 — "이제 게임을 좀 해봐봐 스태스트랜 맛있긴 하네" → "실제로 게임을 좀 해봐오면서 테스트를 했는데 맛있긴 하네", "왜는 리플레이가 귀하다" → "이거는 리플레이가 없긴 하다"
|
||||
- 고침: RTP 타임스탬프로 자리 정하기. 테스트 `core.test.ts` "패킷이 몰려 와도 말 중간에 무음을 넣지 않는다" (3개씩 60ms 마다 도착 + 진짜 쉼 0.4초 → 진짜 쉼 20프레임만 채움, 순번 · 타임스탬프 한 바퀴 도는 경우 포함). 예전 파일 고치기를 사용자 파일 43개에 돌려 489프레임 제거, 결과 파일 ffmpeg 디코드 정상
|
||||
- 잡음 판정: 잡음 19개를 Silero VAD 로 다시 재니 모두 말소리 0초 (Whisper 를 돌리면 "시청해주셔서 감사합니다" · "자막 제공 배달의민족" 만 나옴) → 판정은 맞았고, 이제 숨기고 파일을 지운다. 반복 판정 1개는 깨진 오디오에서 나온 것
|
||||
- 알 수 없음 원인: `users.updated` 를 `data: []` 로 보내 사이트 유저 목록이 비었다 (녹음 시작 · 경기 끝 · Riot ID 저장 때마다). DB 의 user_id 는 모두 정상
|
||||
- 데스매치: 실시간 점수(킬)를 라운드로 착각 → "R10 · R22 · R36 · R48 · R63" 가짜 라운드, 경기 상세는 344킬이 "라운드 1" 하나라 에이스 11개. 경기 상세의 선수 이름이 비어 와서 "주인 계정 자동 연결: #"
|
||||
- 테스트: 앱 48 · 사이트 서버 16 · 워커 42 통과, 앱 · 화면 타입 검사 통과. 실제 STT 워커 E2E 에서 잡음 파일 삭제 · `/api/utterances/:id/info` 확인. 사이트 서버 테스트에서 게임 PC 끊긴 뒤 관리자만 로그를 보고 내려받는 것 확인
|
||||
|
||||
@@ -2,3 +2,4 @@ export * from './protocol.js';
|
||||
export * from './time.js';
|
||||
export * from './rating.js';
|
||||
export * from './rating-model.js';
|
||||
export * from './live-game.js';
|
||||
|
||||
35
packages/shared/src/live-game.ts
Normal file
35
packages/shared/src/live-game.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import type { LiveGame } from './protocol.js';
|
||||
import { fmtClock } from './time.js';
|
||||
|
||||
export const GAME_NAME: Record<LiveGame['game'], string> = { valorant: '발로란트', lol: '리그 오브 레전드' };
|
||||
|
||||
/** 지금 게임 상태를 한 줄로 (헤더 · 알림용): "경쟁전 · 어센트 · R15 8:6" */
|
||||
export function liveGameLine(g: LiveGame): string {
|
||||
if (!g.inMatch) return g.phase + (g.mode && g.connected ? ` · ${g.mode}` : '');
|
||||
const parts = [g.mode, g.map].filter(Boolean) as string[];
|
||||
if (g.round != null && g.score) parts.push(`R${g.round} ${g.score.ally}:${g.score.enemy}`);
|
||||
else if (g.score) parts.push(`${g.score.ally}:${g.score.enemy}`);
|
||||
if (g.gameTimeSec != null) parts.push(fmtClock(g.gameTimeSec * 1000));
|
||||
return parts.join(' · ') || '경기 중';
|
||||
}
|
||||
|
||||
/** 지금 게임 상태 자세히 (앱 게임 연동 탭 · 사이트 패널): [항목, 값] */
|
||||
export function liveGameRows(g: LiveGame, now = Date.now()): [string, string][] {
|
||||
const rows: [string, string][] = [['상태', g.phase]];
|
||||
if (g.self?.name) rows.push(['내 계정', g.self.name]);
|
||||
if (g.mode) rows.push(['모드', g.mode]);
|
||||
if (g.map) rows.push(['맵', g.map]);
|
||||
if (g.inMatch) {
|
||||
if (g.round != null) rows.push(['라운드', `${g.round}라운드`]);
|
||||
if (g.score) rows.push([g.round != null ? '점수 (우리 : 상대)' : '점수', `${g.score.ally} : ${g.score.enemy}`]);
|
||||
if (g.gameTimeSec != null) rows.push(['게임 시간', fmtClock(g.gameTimeSec * 1000)]);
|
||||
else if (g.startedAt) rows.push(['경과', fmtClock(Math.max(0, now - g.startedAt))]);
|
||||
if (g.teamKills) rows.push(['팀 킬 (우리 : 상대)', `${g.teamKills.ally} : ${g.teamKills.enemy}`]);
|
||||
if (g.self?.character) rows.push([g.game === 'lol' ? '내 챔피언' : '내 요원', g.self.character]);
|
||||
if (g.self?.kda) rows.push(['KDA', g.self.kda]);
|
||||
if (g.self?.extra) rows.push(['내 성적', g.self.extra]);
|
||||
if (g.players) rows.push(['인원', `${g.players}명`]);
|
||||
}
|
||||
if (g.error) rows.push(['오류', g.error]);
|
||||
return rows;
|
||||
}
|
||||
@@ -32,6 +32,42 @@ export interface User {
|
||||
|
||||
export type UtteranceStatus = 'pending' | 'realtime' | 'precise' | 'failed';
|
||||
|
||||
/** 발화 자세한 정보 (사이트 우클릭 → 자세한 정보, v1.3.6~) */
|
||||
export interface UtteranceInfo {
|
||||
id: string;
|
||||
userId: string;
|
||||
/** 원본 음성 파일 이름 (예: 0mv9wpior2f765541ac.ogg) */
|
||||
fileName: string | null;
|
||||
/** 게임 PC 안의 전체 경로 */
|
||||
path: string | null;
|
||||
/** 파일이 있는 폴더 */
|
||||
folder: string | null;
|
||||
/** 파일 크기 (바이트), 지워졌으면 null */
|
||||
sizeBytes: number | null;
|
||||
/** 파일이 지워진 이유: 보관 기간 · 잡음 · 파일 없음 */
|
||||
deleted: null | 'retention' | 'noise' | 'missing';
|
||||
startedAt: number;
|
||||
endedAt: number;
|
||||
durationMs: number;
|
||||
/** 녹음 세션 · 음성채널 */
|
||||
sessionId: string | null;
|
||||
channel: string | null;
|
||||
matchId: string | null;
|
||||
status: string;
|
||||
model: string | null;
|
||||
confidence: number | null;
|
||||
lufs: number | null;
|
||||
gainDb: number | null;
|
||||
/** 사전 교정 전 원래 인식 결과 */
|
||||
rawText: string | null;
|
||||
text: string | null;
|
||||
corrected: boolean;
|
||||
noise: boolean;
|
||||
noiseReason: string | null;
|
||||
attempts: number;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface UtteranceItem {
|
||||
kind: 'utterance';
|
||||
id: string;
|
||||
@@ -208,11 +244,47 @@ export interface MatchDetail extends MatchSummary {
|
||||
| null;
|
||||
}
|
||||
|
||||
/** 지금 연결된 게임 · 진행 중인 경기 (앱 게임 연동 탭 · 사이트, v1.3.6~) */
|
||||
export interface LiveGame {
|
||||
game: GameType;
|
||||
/** 연동을 켰는지 */
|
||||
enabled: boolean;
|
||||
/** 게임 클라이언트(Riot 클라이언트 · 롤 클라이언트)에 연결됨 */
|
||||
connected: boolean;
|
||||
/** 지금 상태: 꺼짐 · 메뉴 · 대기열 · 요원 선택 · 경기 중 · 경기 끝 … */
|
||||
phase: string;
|
||||
inMatch: boolean;
|
||||
matchId: string | null;
|
||||
/** 모드 이름 (경쟁전, 신속플레이, 데스매치, 솔로 랭크, 칼바람 나락 …) */
|
||||
mode: string | null;
|
||||
map: string | null;
|
||||
mapImage: string | null;
|
||||
/** 경기 시작 시각 (PC 시계) */
|
||||
startedAt: number | null;
|
||||
/** 발로란트 라운드제 모드: 지금 라운드 */
|
||||
round: number | null;
|
||||
/** 발로란트 점수. 라운드제는 팀 점수, 데스매치 등은 게임이 주는 점수 */
|
||||
score: { ally: number; enemy: number } | null;
|
||||
/** 롤: 게임 시간(초) */
|
||||
gameTimeSec: number | null;
|
||||
/** 롤: 팀 킬 */
|
||||
teamKills: { ally: number; enemy: number } | null;
|
||||
/** 내 계정 · 요원/챔피언 · 성적 */
|
||||
self: { name: string | null; character: string | null; characterImage: string | null; kda: string | null; extra: string | null } | null;
|
||||
/** 경기 인원 */
|
||||
players: number | null;
|
||||
/** 마지막 오류 (연결 실패 등) */
|
||||
error: string | null;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface Overview {
|
||||
guild: { id: string; name: string; icon: string | null } | null;
|
||||
recording: { active: boolean; channel: string | null; since: number | null; participants: string[] };
|
||||
users: User[];
|
||||
games: { valorant: { connected: boolean; inMatch: boolean }; lol: { connected: boolean; inMatch: boolean } };
|
||||
/** 지금 게임 상태 (v1.3.6~ 앱만 보냄) */
|
||||
live?: LiveGame[];
|
||||
counts: { utterances: number; matches: number };
|
||||
version: string;
|
||||
}
|
||||
@@ -320,7 +392,8 @@ export type LiveEvent =
|
||||
| { type: 'event.created'; data: EventItem }
|
||||
| { type: 'match.updated'; data: MatchSummary }
|
||||
| { type: 'recording.state'; data: Overview['recording'] }
|
||||
| { type: 'users.updated'; data: User[] };
|
||||
| { type: 'users.updated'; data: User[] }
|
||||
| { type: 'games.state'; data: LiveGame[] };
|
||||
|
||||
export interface DeviceStatus {
|
||||
registered: boolean;
|
||||
|
||||
@@ -252,7 +252,7 @@ export function registerAppAuth(
|
||||
return s && r ? { userId: s.userId, role: r } : null;
|
||||
};
|
||||
|
||||
return { completeLogin, verifyToken };
|
||||
return { completeLogin, verifyToken, roleOf };
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
||||
|
||||
@@ -12,15 +12,24 @@ import type { KnowledgeAuto } from './culprit-prompt.js';
|
||||
import { avatarUrl, DiscordApi } from './discord.js';
|
||||
import { RateLimiter } from './rate-limit.js';
|
||||
import { RelayHub } from './relay.js';
|
||||
import { SiteLog } from './site-log.js';
|
||||
import { ServerStore, type Session } from './store.js';
|
||||
|
||||
const SID = 'gvr_sid';
|
||||
const RECHECK_MS = 10 * 60000;
|
||||
|
||||
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
|
||||
export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto } = {}) {
|
||||
export async function buildServer(
|
||||
cfg: Config,
|
||||
opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; logEcho?: boolean } = {},
|
||||
) {
|
||||
// 사이트 로그: 날짜별 파일(data/logs/site-날짜.log)로 남기고 관리자가 사이트에서 본다. 게임 PC 가 꺼져 있어도 볼 수 있다
|
||||
const siteLog = new SiteLog(path.join(cfg.dataDir, 'logs'), { echo: opts.logEcho ?? true });
|
||||
const app = Fastify({
|
||||
// 요청 기록은 아래 onResponse 에서 한 줄로 남긴다 (pino 기본 요청 로그는 두 줄 + 상태 확인 폴링으로 너무 많음)
|
||||
disableRequestLogging: true,
|
||||
logger: {
|
||||
stream: siteLog,
|
||||
level: process.env.LOG_LEVEL || 'info',
|
||||
// 로그에 비밀값을 남기지 않는다: 로그인 주소의 code · state, 앱 로그인 요청 아이디, 기록 검색어(쿼리)는 지운다
|
||||
serializers: { req: (req) => ({ method: req.method, url: safeLogUrl(req.url), remoteAddress: req.ip }) },
|
||||
@@ -31,12 +40,13 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
});
|
||||
const store = new ServerStore(cfg.dataDir);
|
||||
const hub = new RelayHub(store);
|
||||
hub.log = app.log.child({ area: 'relay' });
|
||||
const discord = new DiscordApi(cfg);
|
||||
await app.register(cookie, { secret: cfg.sessionSecret });
|
||||
const secure = cfg.publicUrl.startsWith('https://');
|
||||
let broker: BotBroker | null = null;
|
||||
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
|
||||
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log, opts.botRecheckMs);
|
||||
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log.child({ area: 'bot' }), opts.botRecheckMs);
|
||||
|
||||
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
|
||||
// CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게)
|
||||
@@ -98,9 +108,54 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
reply.code(401).send({ error: 'unauthorized' });
|
||||
return null;
|
||||
}
|
||||
(req as any).gvrUser = s.user.id;
|
||||
return s;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ 사이트 로그
|
||||
// 요청 한 줄 기록: 기록 API · 로그인 · 앱 요청은 모두, 화면 파일은 실패만. 자주 부르는 상태 확인 · 음성 파일은 실패만 남긴다
|
||||
app.addHook('onResponse', async (req, reply) => {
|
||||
const url = safeLogUrl(req.url);
|
||||
const st = reply.statusCode;
|
||||
const p = url.split('?')[0];
|
||||
const api = /^\/(api|auth|app|admin|device|site)\//.test(p);
|
||||
if (st < 400 && (!api || p === '/api/status' || p.startsWith('/api/audio/') || p.startsWith('/site/logs') || p === '/site/client-log')) return;
|
||||
const o = { area: 'http', status: st, ms: Math.round(reply.elapsedTime), ...((req as any).gvrUser ? { user: (req as any).gvrUser } : {}) };
|
||||
if (st >= 500 && st !== 503) req.log.error(o, `${req.method} ${url}`);
|
||||
else if (st >= 400 && st !== 401) req.log.warn(o, `${req.method} ${url}`);
|
||||
else req.log.info(o, `${req.method} ${url}`);
|
||||
});
|
||||
const canViewLogs = (userId: string) => cfg.owners.includes(userId) || ['admin', 'superadmin'].includes(appAuth.roleOf(userId) ?? '');
|
||||
app.get('/site/logs', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
if (!canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '사이트 로그는 관리자만 볼 수 있습니다' });
|
||||
return { days: siteLog.days(), now: Date.now() };
|
||||
});
|
||||
app.get<{ Params: { date: string }; Querystring: { download?: string } }>('/site/logs/:date', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
if (!canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '사이트 로그는 관리자만 볼 수 있습니다' });
|
||||
const text = siteLog.read(req.params.date);
|
||||
if (text === null) return reply.code(404).send({ error: 'not_found' });
|
||||
reply.header('cache-control', 'no-store').type('text/plain; charset=utf-8');
|
||||
if (req.query.download) reply.header('content-disposition', `attachment; filename="gvr-site-${req.params.date}.log"`);
|
||||
return text;
|
||||
});
|
||||
// 브라우저 오류(화면 오류 · 처리 안 된 오류 · 요청 실패)를 사이트 로그에 남긴다. 로그인한 사람만, 1분에 30개까지
|
||||
const clientLogLimit = new RateLimiter(30, 60000);
|
||||
app.post<{ Body: { level?: string; message?: string; detail?: string; page?: string } }>('/site/client-log', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
if (!clientLogLimit.hit(s.user.id)) return reply.code(429).send({ error: 'rate_limited' });
|
||||
const b = req.body ?? {};
|
||||
const cut = (v: unknown, n: number) => String(v ?? '').slice(0, n);
|
||||
const o = { area: 'web', user: s.user.id, page: cut(b.page, 200), ...(b.detail ? { detail: cut(b.detail, 2000) } : {}), ua: cut(req.headers['user-agent'], 160) };
|
||||
if (b.level === 'error') req.log.error(o, cut(b.message, 500));
|
||||
else req.log.warn(o, cut(b.message, 500));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 로그인
|
||||
app.get('/auth/discord', async (req, reply) => {
|
||||
const state = crypto.randomBytes(16).toString('base64url');
|
||||
@@ -148,7 +203,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
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) };
|
||||
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id) };
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 상태 · 관리
|
||||
@@ -177,7 +232,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 범인찾기 (Claude API 는 이 서버만 부른다)
|
||||
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log, call: opts.culpritCall, knowledge: opts.culpritKnowledge });
|
||||
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log.child({ area: 'culprit' }), call: opts.culpritCall, knowledge: opts.culpritKnowledge });
|
||||
|
||||
// ------------------------------------------------------------------ 기록 API 중계
|
||||
const relay = async (req: FastifyRequest, reply: FastifyReply) => {
|
||||
@@ -226,7 +281,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
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('/app/') && !req.url.startsWith('/game-assets/'))
|
||||
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/app/') && !req.url.startsWith('/site/') && !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' });
|
||||
});
|
||||
@@ -284,9 +339,10 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
});
|
||||
app.addHook('onClose', async () => {
|
||||
store.flush();
|
||||
siteLog.close();
|
||||
});
|
||||
|
||||
return { app, store, hub, broker, culprit };
|
||||
return { app, store, hub, broker, culprit, siteLog };
|
||||
}
|
||||
|
||||
/** 로그에 남길 주소: /auth/* 는 쿼리를 지우고 앱 로그인 요청 아이디를 가린다, 다른 주소도 쿼리 값은 지운다 */
|
||||
|
||||
@@ -7,7 +7,7 @@ const cfg = loadConfig();
|
||||
let log: { info: (o: any, m?: string) => void; error: (o: any, m?: string) => void } = { info: () => undefined, error: (o, m) => console.error(m, o) };
|
||||
const botSource = process.env.BOT_GATEWAY === '0' ? undefined : new DiscordSource({ info: (o, m) => log.info(o, m), error: (o, m) => log.error(o, m) });
|
||||
const { app } = await buildServer(cfg, { botSource });
|
||||
log = app.log;
|
||||
log = app.log.child({ area: 'discord' });
|
||||
await app.listen({ host: cfg.host, port: cfg.port });
|
||||
if (botSource) {
|
||||
// 디스코드에 못 붙어도 사이트는 계속 돈다 (discord.js 가 알아서 다시 연결)
|
||||
|
||||
@@ -4,6 +4,9 @@ import { WebSocket, WebSocketServer } from 'ws';
|
||||
import type { BrowserMessage, DeviceStatus, LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
|
||||
import type { ServerStore } from './store.js';
|
||||
|
||||
type Log = { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void };
|
||||
const NOLOG: Log = { info: () => undefined, warn: () => undefined };
|
||||
|
||||
const OFFLINE_AFTER_MS = 15000;
|
||||
|
||||
interface Pending {
|
||||
@@ -33,6 +36,9 @@ export class RelayHub {
|
||||
private watchdog: NodeJS.Timeout;
|
||||
private lastStatus = '';
|
||||
|
||||
/** 사이트 로그 (app.ts 가 [relay] 영역 로거를 넣는다) */
|
||||
log: Log = NOLOG;
|
||||
|
||||
constructor(private store: ServerStore) {
|
||||
this.watchdog = setInterval(() => this.checkAlive(), 2000);
|
||||
}
|
||||
@@ -74,6 +80,7 @@ export class RelayHub {
|
||||
|
||||
private checkAlive(): void {
|
||||
if (this.device && Date.now() - this.device.lastMsg > OFFLINE_AFTER_MS) {
|
||||
this.log.warn({ name: this.device.name, silentMs: Date.now() - this.device.lastMsg }, '게임 PC 응답 없음 (15초) → 연결 끊음');
|
||||
this.device.ws.terminate();
|
||||
this.dropDevice(this.device.ws);
|
||||
}
|
||||
@@ -92,11 +99,13 @@ export class RelayHub {
|
||||
attachDevice(ws: WebSocket, id: string): void {
|
||||
if (this.device) {
|
||||
// 같은 기기가 다시 연결 (네트워크 재연결) → 이전 연결을 끊는다
|
||||
this.log.info({ name: this.device.name }, '게임 PC 가 다시 연결해서 이전 연결을 닫음');
|
||||
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.log.info({ name: this.device.name }, '게임 PC 연결');
|
||||
this.store.touchDevice(id, { lastSeen: Date.now() });
|
||||
ws.send(JSON.stringify({ t: 'welcome', deviceId: id } satisfies RelayToDevice));
|
||||
ws.on('message', (data, isBinary) => {
|
||||
@@ -111,13 +120,14 @@ export class RelayHub {
|
||||
}
|
||||
this.onDeviceMessage(m);
|
||||
});
|
||||
ws.on('close', () => this.dropDevice(ws));
|
||||
ws.on('error', () => this.dropDevice(ws));
|
||||
ws.on('close', (code, reason) => this.dropDevice(ws, `닫힘 ${code}${reason?.length ? ' ' + String(reason) : ''}`));
|
||||
ws.on('error', (e) => this.dropDevice(ws, `오류 ${e.message}`));
|
||||
this.broadcastStatus(true);
|
||||
}
|
||||
|
||||
private dropDevice(ws: WebSocket): void {
|
||||
private dropDevice(ws: WebSocket, why = '응답 없음'): void {
|
||||
if (!this.device || this.device.ws !== ws) return;
|
||||
this.log.warn({ name: this.device.name, why, pending: this.pending.size }, '게임 PC 연결 끊김 (사이트 잠김)');
|
||||
this.store.touchDevice(this.device.id, { lastSeen: this.device.lastMsg });
|
||||
this.device = null;
|
||||
for (const [id, p] of this.pending) {
|
||||
@@ -134,6 +144,7 @@ export class RelayHub {
|
||||
case 'hello':
|
||||
dev.name = m.name;
|
||||
dev.version = m.version;
|
||||
this.log.info({ name: m.name, version: m.version, guild: m.guildId ?? null }, '게임 PC 정보');
|
||||
this.store.touchDevice(dev.id, { name: m.name, version: m.version, guildId: m.guildId ?? null, lastSeen: Date.now() });
|
||||
this.broadcastStatus(true);
|
||||
break;
|
||||
@@ -183,7 +194,10 @@ export class RelayHub {
|
||||
const id = crypto.randomBytes(8).toString('hex');
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
if (this.pending.delete(id)) reject(new Error('timeout'));
|
||||
if (this.pending.delete(id)) {
|
||||
this.log.warn({ method, path: path.split('?')[0], ms: timeoutMs }, '게임 PC 가 기록 요청에 답하지 않음 (시간 초과)');
|
||||
reject(new Error('timeout'));
|
||||
}
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, { resolve, reject, timer, chunks: [] });
|
||||
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body };
|
||||
|
||||
109
site/server/src/site-log.ts
Normal file
109
site/server/src/site-log.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* 사이트 서버 로그 (v1.3.6~). exe 로그(gvr-날짜.log)와 같은 모양의 글 로그를 날짜별 파일로 남긴다.
|
||||
* 게임 PC 와 연결이 끊겨도 사이트에서 볼 수 있다 (관리자만, /site/logs).
|
||||
*
|
||||
* Fastify(pino)가 한 줄씩 쓰는 JSON 을 받아 "시각 수준 [영역] 내용 {추가 값}" 으로 바꾼다. 표준 출력(docker logs)에도 그대로 낸다.
|
||||
*/
|
||||
const LEVELS: Record<number, string> = { 10: 'TRACE', 20: 'DEBUG', 30: 'INFO ', 40: 'WARN ', 50: 'ERROR', 60: 'FATAL' };
|
||||
const SKIP_KEYS = new Set(['level', 'time', 'pid', 'hostname', 'msg', 'area', 'reqId', 'err', 'v']);
|
||||
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
export interface SiteLogOptions {
|
||||
keepDays?: number;
|
||||
/** 표준 출력에도 쓰기 (테스트에서는 끈다) */
|
||||
echo?: boolean;
|
||||
}
|
||||
|
||||
export class SiteLog {
|
||||
private day = '';
|
||||
private fd: number | null = null;
|
||||
private keepDays: number;
|
||||
private echo: boolean;
|
||||
|
||||
constructor(
|
||||
readonly dir: string,
|
||||
opts: SiteLogOptions = {},
|
||||
) {
|
||||
this.keepDays = opts.keepDays ?? 14;
|
||||
this.echo = opts.echo ?? true;
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
/** pino destination: JSON 한 줄(또는 여러 줄) */
|
||||
write(chunk: string): void {
|
||||
if (this.echo) process.stdout.write(chunk);
|
||||
for (const line of String(chunk).split('\n')) {
|
||||
if (!line.trim()) continue;
|
||||
let o: Record<string, any>;
|
||||
try {
|
||||
o = JSON.parse(line);
|
||||
} catch {
|
||||
o = { level: 30, time: Date.now(), msg: line };
|
||||
}
|
||||
this.append(format(o), typeof o.time === 'number' ? o.time : Date.now());
|
||||
}
|
||||
}
|
||||
|
||||
private append(text: string, ts: number): void {
|
||||
const day = new Date(ts).toISOString().slice(0, 10);
|
||||
try {
|
||||
if (day !== this.day || this.fd === null) {
|
||||
if (this.fd !== null) fs.closeSync(this.fd);
|
||||
this.day = day;
|
||||
this.fd = fs.openSync(this.file(day), 'a');
|
||||
this.cleanup();
|
||||
}
|
||||
fs.writeSync(this.fd, text + '\n');
|
||||
} catch {
|
||||
/* 디스크 문제로 로그를 못 써도 서버는 계속 돈다 */
|
||||
}
|
||||
}
|
||||
|
||||
file(day: string): string {
|
||||
return path.join(this.dir, `site-${day}.log`);
|
||||
}
|
||||
|
||||
/** 남아 있는 로그 날짜 (최신 먼저) */
|
||||
days(): { date: string; size: number }[] {
|
||||
return fs
|
||||
.readdirSync(this.dir)
|
||||
.map((f) => /^site-(\d{4}-\d{2}-\d{2})\.log$/.exec(f)?.[1])
|
||||
.filter((d): d is string => !!d)
|
||||
.sort()
|
||||
.reverse()
|
||||
.map((date) => ({ date, size: fs.statSync(this.file(date)).size }));
|
||||
}
|
||||
|
||||
/** 그날 로그 원문. 없으면 null */
|
||||
read(day: string): string | null {
|
||||
if (!DATE_RE.test(day)) return null;
|
||||
const f = this.file(day);
|
||||
return fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : null;
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
const cut = new Date(Date.now() - this.keepDays * 86400000).toISOString().slice(0, 10);
|
||||
for (const { date } of this.days()) if (date < cut) fs.rmSync(this.file(date), { force: true });
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.fd !== null) fs.closeSync(this.fd);
|
||||
this.fd = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** exe 로그와 같은 모양: 2026-10-15T17:15:59.289Z INFO [relay] 게임 PC 연결 {"name":"TKRMAGID-PC"} */
|
||||
export function format(o: Record<string, any>): string {
|
||||
const time = new Date(typeof o.time === 'number' ? o.time : Date.now()).toISOString();
|
||||
const lv = LEVELS[o.level] ?? 'INFO ';
|
||||
const area = o.area || 'server';
|
||||
const extra: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(o)) if (!SKIP_KEYS.has(k) && v !== undefined) extra[k] = v;
|
||||
let s = `${time} ${lv} [${area}] ${o.msg ?? ''}`;
|
||||
if (Object.keys(extra).length) s += ' ' + JSON.stringify(extra);
|
||||
if (o.err) s += `\n ${String(o.err.stack || `${o.err.type ?? 'Error'}: ${o.err.message}`).replace(/\n/g, '\n ')}`;
|
||||
return s;
|
||||
}
|
||||
@@ -50,7 +50,7 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
|
||||
discordApi: dc.url,
|
||||
assetUpstream: {},
|
||||
};
|
||||
const { app, store } = await buildServer(cfg);
|
||||
const { app, store } = await buildServer(cfg, { logEcho: false });
|
||||
await app.listen({ host: '127.0.0.1', port: 0 });
|
||||
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
|
||||
try {
|
||||
@@ -134,6 +134,20 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
|
||||
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);
|
||||
// 사이트 로그: 게임 PC 가 끊겨도 관리자는 볼 수 있다. 일반 유저는 못 본다
|
||||
assert.equal((await fetch(base + '/site/logs', { headers: { cookie: sid } })).status, 403);
|
||||
assert.equal(((await (await fetch(base + '/auth/me', { headers: { cookie: sid } })).json()) as any).canViewLogs, false);
|
||||
assert.equal((await fetch(base + '/site/client-log', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/json' }, body: JSON.stringify({ level: 'error', message: '화면 오류 테스트', page: '/' }) })).status, 204);
|
||||
store.upsertAppUser({ id: 'member1', name: '하늘', avatar: null, role: 'admin', addedBy: 'test' });
|
||||
assert.equal(((await (await fetch(base + '/auth/me', { headers: { cookie: sid } })).json()) as any).canViewLogs, true);
|
||||
const days = ((await (await fetch(base + '/site/logs', { headers: { cookie: sid } })).json()) as any).days;
|
||||
assert.equal(days.length, 1);
|
||||
const logText = await (await fetch(`${base}/site/logs/${days[0].date}`, { headers: { cookie: sid } })).text();
|
||||
for (const want of ['[relay] 게임 PC 연결', '[relay] 게임 PC 정보', '[relay] 게임 PC 연결 끊김', 'GET /api/timeline?limit=***', '"status":503', '[web] 화면 오류 테스트']) assert.ok(logText.includes(want), `로그에 "${want}" 없음\n${logText}`);
|
||||
assert.ok(!/GET \/api\/status \{"status":200/.test(logText), '성공한 상태 확인 폴링은 남기지 않는다');
|
||||
const dl = await fetch(`${base}/site/logs/${days[0].date}?download=1`, { headers: { cookie: sid } });
|
||||
assert.match(dl.headers.get('content-disposition') ?? '', /gvr-site-\d{4}-\d{2}-\d{2}\.log/);
|
||||
assert.equal((await fetch(`${base}/site/logs/..%2F..%2Fetc`, { headers: { cookie: sid } })).status, 404);
|
||||
// 서버 멤버가 아니면 로그인 거절
|
||||
members.clear();
|
||||
const s2 = await fetch(base + '/auth/discord', { redirect: 'manual' });
|
||||
|
||||
@@ -53,7 +53,6 @@ function filterItems(q) {
|
||||
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;
|
||||
@@ -69,7 +68,7 @@ function filterItems(q) {
|
||||
}
|
||||
if (it.kind === 'utterance') {
|
||||
if (users && !users.has(it.userId)) return false;
|
||||
if (hideNoise && it.noise) return false;
|
||||
if (it.noise) return false;
|
||||
if (kw && !(it.text ?? '').toLowerCase().includes(kw)) return false;
|
||||
} else {
|
||||
if (users && it.userId && !users.has(it.userId)) return false;
|
||||
@@ -184,10 +183,31 @@ async function handle(req, res) {
|
||||
return res.end();
|
||||
}
|
||||
const sess = session(req);
|
||||
if (p === '/site/logs') return json(res, 200, { days: [{ date: '2026-10-16', size: 18234 }, { date: '2026-10-15', size: 40211 }], now: Date.now() });
|
||||
if (p.startsWith('/site/logs/')) {
|
||||
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
|
||||
return res.end(
|
||||
[
|
||||
'2026-10-16T03:55:46.679Z INFO [relay] 게임 PC 연결 {"name":"TKRMAGID-PC"}',
|
||||
'2026-10-16T03:55:46.690Z INFO [relay] 게임 PC 정보 {"name":"TKRMAGID-PC","version":"1.3.6","guild":"789051930965835810"}',
|
||||
'2026-10-16T03:55:47.353Z INFO [bot] 겜녹이 봇 중계 연결 {"user":"293719842274541579","conn":"a1"}',
|
||||
'2026-10-16T03:56:59.564Z INFO [http] GET /api/timeline?limit=*** {"status":200,"ms":38,"user":"293719842274541579"}',
|
||||
'2026-10-16T04:01:10.710Z WARN [http] GET /api/matches/val-1 {"status":404,"ms":12,"user":"293719842274541579"}',
|
||||
'2026-10-16T04:12:58.961Z ERROR [web] 화면 오류: Cannot read properties of undefined (reading \'name\') {"user":"293719842274541579","page":"/matches/val-1"}',
|
||||
" TypeError: Cannot read properties of undefined (reading 'name')",
|
||||
' at MatchPage (index-abc.js:1:2345)',
|
||||
'2026-10-16T04:13:41.000Z WARN [relay] 게임 PC 연결 끊김 (사이트 잠김) {"name":"TKRMAGID-PC","why":"닫힘 1006","pending":0}',
|
||||
].join('\n') + '\n',
|
||||
);
|
||||
}
|
||||
if (p === '/site/client-log') {
|
||||
res.writeHead(204);
|
||||
return res.end();
|
||||
}
|
||||
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 });
|
||||
return json(res, 200, { user: ME, isOwner: true, canViewLogs: true });
|
||||
}
|
||||
|
||||
if (p.startsWith('/api/')) {
|
||||
@@ -203,6 +223,10 @@ async function handle(req, res) {
|
||||
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 } },
|
||||
live: [
|
||||
{ game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, startedAt: Date.now() - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, updatedAt: Date.now() },
|
||||
{ game: 'lol', enabled: true, connected: false, phase: '롤 클라이언트 꺼짐', inMatch: false, matchId: null, mode: null, map: null, mapImage: null, startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: null, players: null, error: null, updatedAt: Date.now() },
|
||||
],
|
||||
counts: { utterances: db.utterances.length, matches: db.matches.length },
|
||||
version: '1.0.0',
|
||||
});
|
||||
@@ -240,6 +264,17 @@ async function handle(req, res) {
|
||||
broadcast({ type: 'utterance.updated', data: it });
|
||||
return json(res, 200, it);
|
||||
}
|
||||
if ((m = p.match(/^\/api\/utterances\/([^/]+)\/info$/))) {
|
||||
const u = db.utterances.find((x) => x.id === m[1]);
|
||||
if (!u) return json(res, 404, { error: 'not_found' });
|
||||
const path = `C:\\Users\\gamer\\Desktop\\GameVoiceRecorder\\GVR-Data\\audio\\2026-10-16\\${u.id}.ogg`;
|
||||
return json(res, 200, {
|
||||
id: u.id, userId: u.userId, fileName: `${u.id}.ogg`, path, folder: path.slice(0, path.lastIndexOf('\\')),
|
||||
sizeBytes: u.audio ? 41230 : null, deleted: u.audio ? null : 'retention', startedAt: u.ts, endedAt: u.endTs, durationMs: u.endTs - u.ts,
|
||||
sessionId: 'sess1', channel: '음성', matchId: u.game?.matchId ?? null, status: u.status, model: u.model, confidence: u.confidence,
|
||||
lufs: -36.4, gainDb: u.audio?.gainDb ?? null, rawText: u.text, text: u.text, corrected: u.corrected, noise: u.noise, noiseReason: null, attempts: 0, createdAt: u.endTs + 400,
|
||||
});
|
||||
}
|
||||
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' });
|
||||
|
||||
@@ -10,11 +10,15 @@ import { Header } from './components/Header';
|
||||
import { LockOverlay } from './components/LockOverlay';
|
||||
import { LoginPage } from './components/LoginPage';
|
||||
import { PlayerBar } from './components/PlayerBar';
|
||||
import { UttMenuHost } from './components/UttMenu';
|
||||
import { Spinner } from './components/common';
|
||||
import { TimelinePage } from './pages/TimelinePage';
|
||||
import { MatchPage } from './pages/MatchPage';
|
||||
import { CulpritPage } from './pages/CulpritPage';
|
||||
import { MatchesPage, UserPage, UsersPage } from './pages/UserPages';
|
||||
import { LogsPage } from './pages/LogsPage';
|
||||
import { installErrorReporting } from './lib/report';
|
||||
import { useLocation } from 'react-router';
|
||||
|
||||
/** Space 재생/일시정지 · ←/→ 이전/다음 발화 · / 검색 */
|
||||
function useShortcuts() {
|
||||
@@ -74,6 +78,7 @@ function Shell() {
|
||||
</div>
|
||||
<PlayerBar />
|
||||
</div>
|
||||
<UttMenuHost />
|
||||
<LockOverlay />
|
||||
</div>
|
||||
);
|
||||
@@ -81,6 +86,10 @@ function Shell() {
|
||||
|
||||
function Gate() {
|
||||
const { auth } = useAuth();
|
||||
const loc = useLocation();
|
||||
useEffect(() => {
|
||||
if (auth.status === 'ok') installErrorReporting();
|
||||
}, [auth.status]);
|
||||
if (auth.status === 'loading')
|
||||
return (
|
||||
<div className="boot">
|
||||
@@ -94,6 +103,8 @@ function Gate() {
|
||||
return <LoginPage notMember={q === 'not_member'} error={q === 'error' || q === 'invalid' ? '로그인 중 문제가 생겼습니다. 다시 시도해 주세요.' : undefined} />;
|
||||
}
|
||||
if (auth.status === 'not_member') return <LoginPage notMember />;
|
||||
// 사이트 로그: 게임 PC 연결(잠금)과 상관없이 연다
|
||||
if (loc.pathname === '/logs') return <LogsPage />;
|
||||
return (
|
||||
<StatusProvider>
|
||||
<DataProvider>
|
||||
|
||||
@@ -7,9 +7,12 @@ import { sfx, SFX_LABEL } from '../lib/sfx';
|
||||
import { resumeAudio } from '../lib/audio';
|
||||
import { Avatar, Brand } from './common';
|
||||
import { IGear, ILogout, ISearch } from './Icons';
|
||||
import { GAME_NAME, liveGameLine, liveGameRows } from '@gvr/shared';
|
||||
|
||||
function SettingsPopover({ onClose }: { onClose: () => void }) {
|
||||
const s = useSettings();
|
||||
const { auth } = useAuth();
|
||||
const canViewLogs = auth.status === 'ok' && !!auth.me.canViewLogs;
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const down = (e: PointerEvent) => {
|
||||
@@ -80,11 +83,36 @@ function SettingsPopover({ onClose }: { onClose: () => void }) {
|
||||
<input type="checkbox" checked={s.reduceMotion} onChange={(e) => settings.set({ reduceMotion: e.target.checked })} />
|
||||
<span>모션 줄이기</span>
|
||||
</label>
|
||||
{canViewLogs && (
|
||||
<>
|
||||
<h5>문제 해결</h5>
|
||||
<a className="row" href="/logs">
|
||||
📄 사이트 로그 보기 · 내려받기
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
<div className="pop-foot">단축키: Space 재생 · ←/→ 이전·다음 발화 · / 검색 · Esc 닫기</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 지금 게임: 경기 중이면 "발로란트 · 경쟁전 · 어센트 · R15 8:6", 아니면 연결된 게임 상태 */
|
||||
function GamePill() {
|
||||
const { overview } = useData();
|
||||
const live = (overview?.live ?? []).filter((g) => g.enabled && g.connected);
|
||||
const g = live.find((x) => x.inMatch) ?? live[0];
|
||||
if (!g) return null;
|
||||
const tip = liveGameRows(g)
|
||||
.map(([k, v]) => `${k}: ${v}`)
|
||||
.join('\n');
|
||||
return (
|
||||
<div className={`game-pill ${g.game}${g.inMatch ? ' in' : ''}`} title={tip}>
|
||||
<span className="gp-name">{GAME_NAME[g.game]}</span>
|
||||
<span className="gp-txt">{liveGameLine(g)}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SearchBox() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const loc = useLocation();
|
||||
@@ -170,6 +198,7 @@ export function Header() {
|
||||
<span className="rec-short">녹음 중</span>
|
||||
</div>
|
||||
)}
|
||||
{!locked && <GamePill />}
|
||||
{device && (
|
||||
<div className={`conn ${locked ? 'off' : conn === 'open' ? 'on' : 'warn'}`} title={conn === 'open' ? '실시간 연결됨' : '실시간 연결 재시도 중'}>
|
||||
<span className="dot" />
|
||||
|
||||
@@ -65,6 +65,17 @@ export const IVolume = (p: SVGProps<SVGSVGElement>) => (
|
||||
<path d="M19 5a10 10 0 0 1 0 14" />
|
||||
</svg>
|
||||
);
|
||||
export const IMute = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M11 5 6 9H2v6h4l5 4V5z" />
|
||||
<path d="m23 9-6 6M17 9l6 6" />
|
||||
</svg>
|
||||
);
|
||||
export const IDownload = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M12 3v12M7 10l5 5 5-5M4 21h16" />
|
||||
</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" />
|
||||
|
||||
@@ -123,6 +123,11 @@ export function LockOverlay() {
|
||||
>
|
||||
↻ {checking ? '확인 중…' : '지금 다시 확인'}
|
||||
</button>
|
||||
{auth.status === 'ok' && auth.me.canViewLogs && (
|
||||
<a className="btn" href="/logs">
|
||||
📄 사이트 로그 보기
|
||||
</a>
|
||||
)}
|
||||
<button className="btn" onClick={logout}>
|
||||
로그아웃
|
||||
</button>
|
||||
|
||||
@@ -6,7 +6,8 @@ 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';
|
||||
import { IClose, ILoop, IMute, INext, IPause, IPlay, IPrev, IVolume } from './Icons';
|
||||
import { clampVolume } from '../lib/audio';
|
||||
|
||||
const RATES = [1, 1.25, 1.5, 2];
|
||||
|
||||
@@ -51,6 +52,32 @@ function SceneLanes({ scene }: { scene: SceneInfo }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** 녹음 재생 음량 0~200% (아이콘을 누르면 음소거 / 되돌리기) */
|
||||
function VolumeControl() {
|
||||
const cfg = useSettings();
|
||||
const v = clampVolume(cfg.playVolume);
|
||||
const last = useRef(v || 1);
|
||||
if (v > 0) last.current = v;
|
||||
return (
|
||||
<div className="pb-vol" title={`재생 음량 ${Math.round(v * 100)}%`}>
|
||||
<button className={`icon-btn${v === 0 ? ' muted-on' : ''}`} onClick={() => settings.set({ playVolume: v === 0 ? last.current : 0 })} aria-label={v === 0 ? '소리 켜기' : '음소거'}>
|
||||
{v === 0 ? <IMute width={16} height={16} /> : <IVolume width={16} height={16} />}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={200}
|
||||
step={5}
|
||||
value={Math.round(v * 100)}
|
||||
onChange={(e) => settings.set({ playVolume: Number(e.target.value) / 100 })}
|
||||
aria-label="재생 음량"
|
||||
style={{ ['--p' as string]: `${(v / 2) * 100}%` }}
|
||||
/>
|
||||
<span className="mono pb-vol-n">{Math.round(v * 100)}%</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlayerBar() {
|
||||
const s = usePlayer((x) => x);
|
||||
const cfg = useSettings();
|
||||
@@ -145,6 +172,7 @@ export function PlayerBar() {
|
||||
<button className="chip mono" onClick={click(() => settings.set({ rate: RATES[(RATES.indexOf(cfg.rate) + 1) % RATES.length] }))} title="재생 속도">
|
||||
{cfg.rate}x
|
||||
</button>
|
||||
<VolumeControl />
|
||||
<button
|
||||
className={`chip${cfg.normalize ? ' on-mint' : ''}`}
|
||||
onClick={click(() => settings.set({ normalize: !cfg.normalize }))}
|
||||
|
||||
218
site/web/src/components/UttMenu.tsx
Normal file
218
site/web/src/components/UttMenu.tsx
Normal file
@@ -0,0 +1,218 @@
|
||||
import { useEffect, useState, useSyncExternalStore, type ReactNode } from 'react';
|
||||
import type { UtteranceInfo, UtteranceItem } from '@gvr/shared';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { fmtWhen } from '../lib/format';
|
||||
import { player } from '../store/player';
|
||||
import { useData } from '../store/app';
|
||||
import { IClose, IDownload, IPlay } from './Icons';
|
||||
|
||||
/** 발화 우클릭 메뉴 · 자세한 정보 창 (앱에 하나만 띄운다) */
|
||||
type MenuState = { item: UtteranceItem; x: number; y: number } | null;
|
||||
let menu: MenuState = null;
|
||||
let infoFor: UtteranceItem | null = null;
|
||||
const subs = new Set<() => void>();
|
||||
const notify = () => subs.forEach((f) => f());
|
||||
const subscribe = (f: () => void) => {
|
||||
subs.add(f);
|
||||
return () => {
|
||||
subs.delete(f);
|
||||
};
|
||||
};
|
||||
|
||||
export function openUttMenu(item: UtteranceItem, x: number, y: number): void {
|
||||
menu = { item, x, y };
|
||||
notify();
|
||||
}
|
||||
function closeMenu(): void {
|
||||
menu = null;
|
||||
notify();
|
||||
}
|
||||
function openInfo(item: UtteranceItem): void {
|
||||
menu = null;
|
||||
infoFor = item;
|
||||
notify();
|
||||
}
|
||||
function closeInfo(): void {
|
||||
infoFor = null;
|
||||
notify();
|
||||
}
|
||||
|
||||
/** 녹음 원본(.ogg)을 내려받는다. 게임 PC → 사이트 서버 중계로 받은 파일을 그대로 저장 */
|
||||
export async function downloadAudio(item: UtteranceItem, fileName?: string | null): Promise<void> {
|
||||
const res = await fetch(`/api/audio/${encodeURIComponent(item.id)}`, { credentials: 'include' });
|
||||
if (!res.ok) throw new Error(res.status === 410 ? '음성 파일이 삭제되었습니다' : `받지 못했습니다 (${res.status})`);
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = fileName || `${item.id}.ogg`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||||
}
|
||||
|
||||
const copy = (text: string) => navigator.clipboard?.writeText(text).catch(() => undefined);
|
||||
|
||||
export function UttMenuHost() {
|
||||
const m = useSyncExternalStore(subscribe, () => menu);
|
||||
const info = useSyncExternalStore(subscribe, () => infoFor);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!m) return;
|
||||
const close = () => closeMenu();
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeMenu();
|
||||
window.addEventListener('pointerdown', close);
|
||||
window.addEventListener('scroll', close, true);
|
||||
window.addEventListener('resize', close);
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
window.removeEventListener('pointerdown', close);
|
||||
window.removeEventListener('scroll', close, true);
|
||||
window.removeEventListener('resize', close);
|
||||
window.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [m]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!err) return;
|
||||
const t = setTimeout(() => setErr(null), 4000);
|
||||
return () => clearTimeout(t);
|
||||
}, [err]);
|
||||
|
||||
const act = (fn: () => unknown) => (e: React.PointerEvent | React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
closeMenu();
|
||||
fn();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{m && (
|
||||
<div
|
||||
className="ctx-menu"
|
||||
role="menu"
|
||||
style={{ left: Math.min(m.x, window.innerWidth - 230), top: Math.min(m.y, window.innerHeight - 190) }}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
<button role="menuitem" disabled={!m.item.audio} onClick={act(() => void player.play(m.item))}>
|
||||
<IPlay width={14} height={14} /> 재생
|
||||
</button>
|
||||
<button role="menuitem" onClick={act(() => openInfo(m.item))}>
|
||||
<span className="ctx-ic">ℹ</span> 자세한 정보
|
||||
</button>
|
||||
<button role="menuitem" disabled={!m.item.audio} onClick={act(() => downloadAudio(m.item).catch((e) => setErr(e.message)))}>
|
||||
<IDownload width={14} height={14} /> 음성 다운로드 (.ogg)
|
||||
</button>
|
||||
<button role="menuitem" disabled={!m.item.text} onClick={act(() => copy(m.item.text ?? ''))}>
|
||||
<span className="ctx-ic">⧉</span> 내용 복사
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{info && <InfoDialog item={info} onError={setErr} />}
|
||||
{err && <div className="ctx-toast">{err}</div>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const STATUS: Record<string, string> = { pending: '변환 대기', realtime: '실시간 모델', precise: '정밀 모델', failed: '인식 실패' };
|
||||
const DELETED: Record<string, string> = { retention: '보관 기간이 지나 삭제됨', noise: '잡음이라 삭제됨', missing: '파일을 찾을 수 없음' };
|
||||
|
||||
function fmtBytes(n: number): string {
|
||||
return n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(2)} MB` : `${(n / 1024).toFixed(1)} KB`;
|
||||
}
|
||||
|
||||
function InfoDialog({ item, onError }: { item: UtteranceItem; onError: (m: string) => void }) {
|
||||
const { userById } = useData();
|
||||
const [info, setInfo] = useState<UtteranceInfo | null>(null);
|
||||
const [failed, setFailed] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api
|
||||
.utteranceInfo(item.id)
|
||||
.then((r) => alive && setInfo(r))
|
||||
.catch((e) => {
|
||||
if (!alive) return;
|
||||
// v1.3.5 이하 앱에는 이 기능이 없다
|
||||
setFailed(e instanceof ApiError && e.status === 404 ? '게임 PC 의 겜녹이가 예전 버전입니다. v1.3.6 이상으로 업데이트하면 볼 수 있습니다.' : '정보를 받지 못했습니다.');
|
||||
});
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeInfo();
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
alive = false;
|
||||
window.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [item.id]);
|
||||
|
||||
const doCopy = (label: string, v: string) => {
|
||||
void copy(v);
|
||||
setCopied(label);
|
||||
setTimeout(() => setCopied(null), 1500);
|
||||
};
|
||||
const user = userById(item.userId);
|
||||
const rows: [string, ReactNode][] = info
|
||||
? [
|
||||
['말한 사람', user?.name ?? info.userId],
|
||||
['원본 파일', <span className="mono">{info.fileName ?? '-'}</span>],
|
||||
[
|
||||
'경로 (게임 PC)',
|
||||
info.path ? (
|
||||
<span className="mono path">
|
||||
{info.path}{' '}
|
||||
<button className="link-btn" onClick={() => doCopy('path', info.path!)}>
|
||||
{copied === 'path' ? '복사됨' : '복사'}
|
||||
</button>
|
||||
</span>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
],
|
||||
['파일 상태', info.deleted ? DELETED[info.deleted] : info.sizeBytes != null ? `있음 · ${fmtBytes(info.sizeBytes)}` : '-'],
|
||||
['녹음 시각', `${fmtWhen(info.startedAt)} · ${(info.durationMs / 1000).toFixed(1)}초`],
|
||||
['음성채널', info.channel ?? '-'],
|
||||
['경기', info.matchId ?? '경기 밖'],
|
||||
['인식', `${STATUS[info.status] ?? info.status}${info.model ? ` · ${info.model}` : ''}${info.confidence != null ? ` · 신뢰도 ${Math.round(info.confidence * 100)}%` : ''}`],
|
||||
['원래 인식 결과', info.rawText ?? '-'],
|
||||
...(info.corrected ? ([['교정', '사람이 고친 글']] as [string, ReactNode][]) : []),
|
||||
['음량', `${info.lufs != null ? `${info.lufs.toFixed(1)} LUFS` : '-'} · 재생 보정 ${info.gainDb != null ? `${info.gainDb > 0 ? '+' : ''}${info.gainDb.toFixed(1)} dB` : '-'}`],
|
||||
['발화 ID', <span className="mono">{info.id}</span>],
|
||||
]
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="ctx-dim" onPointerDown={closeInfo}>
|
||||
<div className="ctx-dialog" role="dialog" aria-label="발화 자세한 정보" onPointerDown={(e) => e.stopPropagation()}>
|
||||
<div className="ctx-head">
|
||||
<b>발화 자세한 정보</b>
|
||||
<button className="icon-btn" onClick={closeInfo} aria-label="닫기">
|
||||
<IClose width={16} height={16} />
|
||||
</button>
|
||||
</div>
|
||||
{failed && <p className="dim">{failed}</p>}
|
||||
{!info && !failed && <p className="dim">불러오는 중…</p>}
|
||||
{info && (
|
||||
<dl className="ctx-rows">
|
||||
{rows.map(([k, v]) => (
|
||||
<div key={k}>
|
||||
<dt>{k}</dt>
|
||||
<dd>{v}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
<div className="ctx-foot">
|
||||
<button className="chip on" disabled={!item.audio || !!info?.deleted} onClick={() => downloadAudio(item, info?.fileName).catch((e) => onError(e.message))}>
|
||||
<IDownload width={14} height={14} /> 원본 ogg 다운로드
|
||||
</button>
|
||||
<button className="chip" onClick={closeInfo}>
|
||||
닫기
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { sfx } from '../lib/sfx';
|
||||
import { realTip } from '../lib/format';
|
||||
import { Avatar, TimeCell } from './common';
|
||||
import { IEdit } from './Icons';
|
||||
import { openUttMenu } from './UttMenu';
|
||||
|
||||
const STATUS: Record<UtteranceItem['status'], [string, string]> = {
|
||||
realtime: ['실시간', 'st-rt'],
|
||||
@@ -152,6 +153,12 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
|
||||
if (active && player.state.mode === 'single') player.toggle();
|
||||
else void player.play(item);
|
||||
};
|
||||
// 우클릭: 재생 · 자세한 정보(원본 ogg 이름 · 경로) · 다운로드
|
||||
const menu = (e: MouseEvent) => {
|
||||
if (editing) return;
|
||||
e.preventDefault();
|
||||
openUttMenu(item, e.clientX, e.clientY);
|
||||
};
|
||||
const edit = (e: MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
sfx('click');
|
||||
@@ -178,7 +185,7 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
|
||||
|
||||
if (variant === 'compact') {
|
||||
return (
|
||||
<div className={`l utt${active ? ' cur' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} data-id={item.id}>
|
||||
<div className={`l utt${active ? ' cur' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} onContextMenu={menu} data-id={item.id}>
|
||||
<span className="t mono" data-tip={realTip(item.ts)}>
|
||||
{timeText ?? item.time.primary}
|
||||
</span>
|
||||
@@ -199,7 +206,7 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`it utt${active ? ' playing' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} data-id={item.id}>
|
||||
<div className={`it utt${active ? ' playing' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} onContextMenu={menu} data-id={item.id}>
|
||||
<TimeCell time={item.time} real={!item.game} />
|
||||
<Avatar user={user} size={30} />
|
||||
<div className="body">
|
||||
|
||||
@@ -10,9 +10,12 @@ import type {
|
||||
UserProfile,
|
||||
User,
|
||||
UtteranceItem,
|
||||
UtteranceInfo,
|
||||
GameType,
|
||||
} from '@gvr/shared';
|
||||
|
||||
import { reportClient } from './report';
|
||||
|
||||
/** 전역 신호: 401 → 로그인 화면, 503 device_offline → 잠금 화면 */
|
||||
type Signal = 'unauthorized' | 'not_member' | 'device_offline';
|
||||
const listeners = new Set<(s: Signal) => void>();
|
||||
@@ -55,12 +58,16 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
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');
|
||||
// 게임 PC 쪽 오류 · 시간 초과는 사이트 로그에도 남긴다 (게임 PC 꺼짐은 서버가 이미 남김)
|
||||
else if (res.status >= 500) reportClient('error', `요청 실패 ${res.status} ${code}: ${init.method ?? 'GET'} ${path.split('?')[0]}`);
|
||||
throw new ApiError(res.status, code);
|
||||
}
|
||||
|
||||
export interface Me {
|
||||
user: { id: string; name: string; avatar: string | null };
|
||||
isOwner: boolean;
|
||||
/** 사이트 로그를 볼 수 있는지 (관리자 · 최고 관리자, v1.3.6~) */
|
||||
canViewLogs?: boolean;
|
||||
}
|
||||
export interface StatusResponse {
|
||||
device: DeviceStatus;
|
||||
@@ -75,7 +82,6 @@ export interface TimelineQuery {
|
||||
to?: number;
|
||||
q?: string;
|
||||
types?: string[];
|
||||
hideNoise?: boolean;
|
||||
cursor?: string | null;
|
||||
limit?: number;
|
||||
order?: 'asc' | 'desc';
|
||||
@@ -117,10 +123,11 @@ export const api = {
|
||||
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,
|
||||
// v1.3.5 이하 앱은 이 값이 있어야 잡음을 뺀다 (v1.3.6~ 앱은 늘 뺌)
|
||||
hideNoise: 1,
|
||||
})}`,
|
||||
),
|
||||
matches: (o: { game?: GameType; limit?: number; before?: number } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
|
||||
@@ -152,6 +159,7 @@ export const api = {
|
||||
if (res.status === 503 && b.error === 'device_offline') emit('device_offline');
|
||||
return { ok: false, status: res.status, error: b.error ?? 'error', message: b.message ?? '분석을 시작하지 못했습니다' };
|
||||
},
|
||||
utteranceInfo: (id: string) => request<UtteranceInfo>(`/api/utterances/${encodeURIComponent(id)}/info`),
|
||||
correct: (id: string, text: string) =>
|
||||
request<UtteranceItem>(`/api/utterances/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ text }) }),
|
||||
};
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { settings } from '../store/settings';
|
||||
|
||||
/** 공용 AudioContext 와 출력 체인 (플레이어 + 효과음) */
|
||||
let ctx: AudioContext | null = null;
|
||||
let playerBus: GainNode | null = null;
|
||||
@@ -14,6 +16,11 @@ export function audioCtx(): AudioContext {
|
||||
limiter.attack.value = 0.002;
|
||||
limiter.release.value = 0.12;
|
||||
playerBus = ctx.createGain();
|
||||
// 녹음 재생 음량 (플레이어 막대의 음량 조절). 리미터 앞에서 바꿔 크게 키워도 찢어지지 않는다
|
||||
playerBus.gain.value = clampVolume(settings.get().playVolume);
|
||||
settings.subscribe(() => {
|
||||
if (playerBus) playerBus.gain.value = clampVolume(settings.get().playVolume);
|
||||
});
|
||||
playerBus.connect(limiter).connect(ctx.destination);
|
||||
sfxBus = ctx.createGain();
|
||||
sfxBus.connect(ctx.destination);
|
||||
@@ -35,4 +42,6 @@ export function sfxOutput(): GainNode {
|
||||
return sfxBus!;
|
||||
}
|
||||
|
||||
export const clampVolume = (v: unknown) => (typeof v === 'number' && isFinite(v) ? Math.min(2, Math.max(0, v)) : 1);
|
||||
|
||||
export const dbToGain = (db: number) => Math.pow(10, db / 20);
|
||||
|
||||
@@ -11,7 +11,6 @@ export interface Filters {
|
||||
to: number | undefined;
|
||||
q: string;
|
||||
types: TypeGroup[];
|
||||
hideNoise: boolean;
|
||||
order: 'asc' | 'desc' | null;
|
||||
}
|
||||
|
||||
@@ -28,7 +27,6 @@ export function parseFilters(p: URLSearchParams): Filters {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -42,7 +40,6 @@ export function writeFilters(f: Filters): URLSearchParams {
|
||||
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;
|
||||
}
|
||||
@@ -59,7 +56,6 @@ export function toQuery(f: Filters): TimelineQuery {
|
||||
to: f.to,
|
||||
q: f.q || undefined,
|
||||
types: f.types,
|
||||
hideNoise: f.hideNoise,
|
||||
order: effectiveOrder(f),
|
||||
};
|
||||
}
|
||||
@@ -76,7 +72,7 @@ export function matchesFilter(it: TimelineItem, f: Filters): boolean {
|
||||
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 (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;
|
||||
|
||||
29
site/web/src/lib/report.ts
Normal file
29
site/web/src/lib/report.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
/** 브라우저 오류를 사이트 로그([web])에 남긴다. 같은 내용은 30초에 한 번만 */
|
||||
const recent = new Map<string, number>();
|
||||
|
||||
export function reportClient(level: 'warn' | 'error', message: string, detail?: string): void {
|
||||
const key = `${level}:${message}`;
|
||||
const now = Date.now();
|
||||
if ((recent.get(key) ?? 0) > now - 30000) return;
|
||||
recent.set(key, now);
|
||||
if (recent.size > 200) recent.clear();
|
||||
void fetch('/site/client-log', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ level, message: message.slice(0, 500), detail: detail?.slice(0, 2000), page: location.pathname + location.search }),
|
||||
keepalive: true,
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
export function installErrorReporting(): void {
|
||||
if (installed) return;
|
||||
installed = true;
|
||||
window.addEventListener('error', (e) => reportClient('error', `화면 오류: ${e.message}`, e.error?.stack ?? `${e.filename}:${e.lineno}:${e.colno}`));
|
||||
window.addEventListener('unhandledrejection', (e) => {
|
||||
const r = e.reason;
|
||||
if (r?.name === 'AbortError') return;
|
||||
reportClient('error', `처리 안 된 오류: ${r?.message ?? String(r)}`, r?.stack);
|
||||
});
|
||||
}
|
||||
121
site/web/src/pages/LogsPage.tsx
Normal file
121
site/web/src/pages/LogsPage.tsx
Normal file
@@ -0,0 +1,121 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useAuth } from '../store/app';
|
||||
import { Brand } from '../components/common';
|
||||
|
||||
/**
|
||||
* 사이트 로그 (관리자만). 게임 PC 와 연결이 끊겨 사이트가 잠겨 있어도 볼 수 있게 잠금 화면 밖에서 그린다.
|
||||
* exe 로그(게임 PC 의 GVR-Data\logs\gvr-날짜.log)와 이 로그를 같이 보내면 대부분의 문제를 찾을 수 있다.
|
||||
*/
|
||||
type Level = 'all' | 'warn' | 'error';
|
||||
const LEVEL_RE: Record<Level, RegExp> = { all: /./, warn: /^\S+ (WARN|ERROR|FATAL)/, error: /^\S+ (ERROR|FATAL)/ };
|
||||
|
||||
export function LogsPage() {
|
||||
const { auth } = useAuth();
|
||||
const [days, setDays] = useState<{ date: string; size: number }[] | null>(null);
|
||||
const [date, setDate] = useState<string | null>(null);
|
||||
const [text, setText] = useState('');
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [level, setLevel] = useState<Level>('all');
|
||||
const [q, setQ] = useState('');
|
||||
const [live, setLive] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/site/logs', { credentials: 'include' })
|
||||
.then(async (r) => {
|
||||
if (r.status === 403) throw new Error('사이트 로그는 관리자만 볼 수 있습니다.');
|
||||
if (!r.ok) throw new Error(`로그 목록을 받지 못했습니다 (${r.status})`);
|
||||
const b = (await r.json()) as { days: { date: string; size: number }[] };
|
||||
setDays(b.days);
|
||||
setDate((d) => d ?? b.days[0]?.date ?? null);
|
||||
})
|
||||
.catch((e) => setErr(e.message));
|
||||
}, []);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!date) return;
|
||||
const r = await fetch(`/site/logs/${date}`, { credentials: 'include', cache: 'no-store' });
|
||||
if (r.ok) setText(await r.text());
|
||||
}, [date]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
// 오늘 로그는 5초마다 새로 받는다
|
||||
if (!live || date !== days?.[0]?.date) return;
|
||||
const t = window.setInterval(() => void load(), 5000);
|
||||
return () => window.clearInterval(t);
|
||||
}, [load, live, date, days]);
|
||||
|
||||
// 줄 단위로 나누되, 오류 스택(들여쓴 줄)은 위 줄에 붙인다
|
||||
const entries = useMemo(() => {
|
||||
const out: string[] = [];
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line) continue;
|
||||
if (line.startsWith(' ') && out.length) out[out.length - 1] += '\n' + line;
|
||||
else out.push(line);
|
||||
}
|
||||
return out;
|
||||
}, [text]);
|
||||
const shown = useMemo(() => {
|
||||
const kw = q.trim().toLowerCase();
|
||||
return entries.filter((e) => LEVEL_RE[level].test(e) && (!kw || e.toLowerCase().includes(kw))).reverse();
|
||||
}, [entries, level, q]);
|
||||
|
||||
const name = auth.status === 'ok' ? auth.me.user.name : '';
|
||||
return (
|
||||
<div className="logs-page">
|
||||
<header className="logs-head">
|
||||
<a href="/" className="logs-back">
|
||||
<Brand />
|
||||
</a>
|
||||
<h1>사이트 로그</h1>
|
||||
<span className="dim">{name}</span>
|
||||
</header>
|
||||
<p className="logs-help">
|
||||
사이트 서버(gvr.tkrmagid.kr)가 남긴 기록입니다. 게임 PC 프로그램과 연결이 끊겨도 볼 수 있습니다. 문제를 알릴 때는 이 로그와 게임 PC 의 exe 로그(
|
||||
<span className="mono">GVR-Data\logs\gvr-날짜.log</span>)를 같이 보내 주세요. 시각은 UTC(한국 시각 -9시간)입니다.
|
||||
</p>
|
||||
{err && <div className="logs-err">{err}</div>}
|
||||
{days && (
|
||||
<div className="logs-bar">
|
||||
<select value={date ?? ''} onChange={(e) => setDate(e.target.value)} aria-label="날짜">
|
||||
{days.map((d) => (
|
||||
<option key={d.date} value={d.date}>
|
||||
{d.date} ({(d.size / 1024).toFixed(0)} KB)
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="logs-seg">
|
||||
{(['all', 'warn', 'error'] as Level[]).map((l) => (
|
||||
<button key={l} className={`chip${level === l ? ' on' : ''}`} onClick={() => setLevel(l)}>
|
||||
{l === 'all' ? '전체' : l === 'warn' ? '경고 이상' : '오류만'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<input className="logs-q" value={q} onChange={(e) => setQ(e.target.value)} placeholder="찾기 (예: 게임 PC, 503, 범인찾기)" />
|
||||
{date === days[0]?.date && (
|
||||
<label className="logs-live">
|
||||
<input type="checkbox" checked={live} onChange={(e) => setLive(e.target.checked)} /> 자동 새로 고침
|
||||
</label>
|
||||
)}
|
||||
{date && (
|
||||
<a className="chip on" href={`/site/logs/${date}?download=1`} download>
|
||||
⬇ 내려받기 (gvr-site-{date}.log)
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{days && !days.length && <p className="dim">아직 로그가 없습니다.</p>}
|
||||
<div className="logs-list mono" role="log">
|
||||
{shown.map((e, i) => {
|
||||
const lv = /^\S+ (\w+)/.exec(e)?.[1] ?? 'INFO';
|
||||
return (
|
||||
<pre key={i} className={`lg lg-${lv.toLowerCase()}`}>
|
||||
{e}
|
||||
</pre>
|
||||
);
|
||||
})}
|
||||
{days && date && !shown.length && <p className="dim">조건에 맞는 줄이 없습니다.</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -105,12 +105,7 @@ export function Sidebar({ f, update, users, matches, detail }: { f: Filters; upd
|
||||
</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 className="link-btn" onClick={tap(() => update({ users: [], game: null, match: null, from: undefined, to: undefined, q: '', types: [], order: null }))}>
|
||||
필터 초기화
|
||||
</button>
|
||||
</div>
|
||||
@@ -151,9 +146,6 @@ export function MobileFilters({ f, update, users, matches }: { f: Filters; updat
|
||||
{t.icon} {t.label}
|
||||
</button>
|
||||
))}
|
||||
<button className={`chip${f.hideNoise ? ' on' : ''}`} onClick={() => update({ hideNoise: !f.hideNoise })}>
|
||||
잡음 숨기기
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Avatar, ErrorBox, Spinner } from '../components/common';
|
||||
import { IWaves } from '../components/Icons';
|
||||
import { MobileFilters, Sidebar } from './Sidebar';
|
||||
import { TalkBars } from '../components/TalkBars';
|
||||
import { GAME_NAME, liveGameRows } from '@gvr/shared';
|
||||
|
||||
function NowPlayingCard() {
|
||||
const item = usePlayer((s) => (s.mode === 'single' ? s.item : null));
|
||||
@@ -143,6 +144,7 @@ function RightPanel({ items, detail }: { items: TimelineItem[]; detail: MatchDet
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!detail && <LiveGamesCard />}
|
||||
<div className="card">
|
||||
<h5>{detail ? '이 경기 발화량' : '지금 목록의 발화량'}</h5>
|
||||
<TalkBars utts={utts} />
|
||||
@@ -151,6 +153,37 @@ function RightPanel({ items, detail }: { items: TimelineItem[]; detail: MatchDet
|
||||
);
|
||||
}
|
||||
|
||||
/** 게임 PC 에 지금 연결된 게임 · 진행 중인 경기 */
|
||||
function LiveGamesCard() {
|
||||
const { overview } = useData();
|
||||
const live = (overview?.live ?? []).filter((g) => g.enabled);
|
||||
if (!overview?.live) return null;
|
||||
return (
|
||||
<div className="card live-card">
|
||||
<h5>게임 상태</h5>
|
||||
{!live.length && <div className="dim small">게임 연동이 꺼져 있습니다.</div>}
|
||||
{live.map((g) => (
|
||||
<div key={g.game} className={`live-g ${g.game}${g.inMatch ? ' in' : ''}`}>
|
||||
<div className="live-g-top">
|
||||
<span className={`ldot${g.inMatch ? ' on' : g.connected ? ' mid' : ''}`} />
|
||||
<b>{GAME_NAME[g.game]}</b>
|
||||
<span className="dim small">{g.phase}</span>
|
||||
</div>
|
||||
{(g.connected || g.inMatch) &&
|
||||
liveGameRows(g)
|
||||
.slice(1)
|
||||
.map(([k, v]) => (
|
||||
<div className="kv" key={k}>
|
||||
<span className="muted">{k}</span>
|
||||
<span>{v}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TimelinePage() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const f = useMemo(() => parseFilters(params), [params]);
|
||||
@@ -277,7 +310,16 @@ export function TimelinePage() {
|
||||
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 it = e.data;
|
||||
// 잡음으로 판정되면 목록에서 뺀다. 경기 뒤 정밀 변환에서 말이 나오면 다시 넣는다
|
||||
if (!matchesFilter(it, f)) setItems((prev) => prev.filter((p) => p.id !== it.id));
|
||||
else
|
||||
setItems((prev) => {
|
||||
if (prev.some((p) => p.id === it.id)) return prev.map((p) => (p.id === it.id ? it : p));
|
||||
const i = prev.findIndex((p) => (order === 'desc' ? p.ts < it.ts : p.ts > it.ts));
|
||||
if (i < 0) return order === 'asc' && next ? prev : [...prev, it];
|
||||
return [...prev.slice(0, i), it, ...prev.slice(i)];
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -140,8 +140,17 @@ export function DataProvider({ children }: { children: ReactNode }) {
|
||||
};
|
||||
}, [epoch, locked]);
|
||||
useLive((e) => {
|
||||
if (e.type === 'users.updated') setOverview((o) => (o ? { ...o, users: e.data } : o));
|
||||
if (e.type === 'users.updated') {
|
||||
// v1.3.5 이하 앱은 빈 목록을 보낸다: 그대로 쓰면 모든 발화가 "알 수 없음"이 되니 다시 받아 온다
|
||||
if (e.data.length) setOverview((o) => (o ? { ...o, users: e.data } : o));
|
||||
else
|
||||
api
|
||||
.users()
|
||||
.then((users) => setOverview((o) => (o ? { ...o, users } : o)))
|
||||
.catch(() => {});
|
||||
}
|
||||
if (e.type === 'recording.state') setOverview((o) => (o ? { ...o, recording: e.data } : o));
|
||||
if (e.type === 'games.state') setOverview((o) => (o ? { ...o, live: e.data } : o));
|
||||
});
|
||||
const users = overview?.users ?? [];
|
||||
const map = useMemo(() => new Map(users.map((u) => [u.id, u])), [users]);
|
||||
|
||||
@@ -8,6 +8,8 @@ export interface Settings {
|
||||
rate: number;
|
||||
continuous: boolean;
|
||||
normalize: boolean;
|
||||
/** 녹음 재생 음량 0..2 (1 = 원래 크기) */
|
||||
playVolume: number;
|
||||
}
|
||||
|
||||
const KEY = 'gvr.settings.v1';
|
||||
@@ -18,6 +20,7 @@ const DEFAULTS: Settings = {
|
||||
rate: 1,
|
||||
continuous: true,
|
||||
normalize: true,
|
||||
playVolume: 1,
|
||||
};
|
||||
|
||||
function load(): Settings {
|
||||
|
||||
@@ -3430,3 +3430,316 @@ button.match:hover {
|
||||
.cu-row { grid-template-columns: 34px 1fr auto; }
|
||||
.cu-row .cu-st { grid-column: 2 / -1; justify-self: start; }
|
||||
}
|
||||
|
||||
/* ── 재생 음량 (플레이어 막대) ── */
|
||||
.pb-vol {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex: none;
|
||||
}
|
||||
.pb-vol .icon-btn {
|
||||
color: var(--muted);
|
||||
}
|
||||
.pb-vol .icon-btn.muted-on {
|
||||
color: var(--accent);
|
||||
}
|
||||
.pb-vol input[type='range'] {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
width: 90px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: linear-gradient(90deg, var(--mint, #14c1b7) var(--p, 50%), #2a3a4a var(--p, 50%));
|
||||
cursor: pointer;
|
||||
}
|
||||
.pb-vol input[type='range']::-webkit-slider-thumb {
|
||||
-webkit-appearance: none;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
}
|
||||
.pb-vol input[type='range']::-moz-range-thumb {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
}
|
||||
.pb-vol-n {
|
||||
font-size: 11.5px;
|
||||
width: 36px;
|
||||
color: var(--muted);
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.pb-vol input[type='range'],
|
||||
.pb-vol-n {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── 발화 우클릭 메뉴 · 자세한 정보 ── */
|
||||
.ctx-menu {
|
||||
position: fixed;
|
||||
z-index: 80;
|
||||
min-width: 210px;
|
||||
background: #0f1923;
|
||||
border: 1px solid #2c3f52;
|
||||
border-radius: 10px;
|
||||
padding: 5px;
|
||||
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
.ctx-menu button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border-radius: 7px;
|
||||
font-size: 13px;
|
||||
color: var(--text, #e6edf3);
|
||||
text-align: left;
|
||||
}
|
||||
.ctx-menu button:hover:not(:disabled) {
|
||||
background: #1b2a38;
|
||||
}
|
||||
.ctx-menu button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
.ctx-ic {
|
||||
width: 14px;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
}
|
||||
.ctx-dim {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 90;
|
||||
background: rgba(3, 8, 12, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 16px;
|
||||
}
|
||||
.ctx-dialog {
|
||||
width: min(620px, 100%);
|
||||
max-height: 90vh;
|
||||
overflow: auto;
|
||||
background: #0f1923;
|
||||
border: 1px solid #2c3f52;
|
||||
border-radius: 14px;
|
||||
padding: 16px 18px;
|
||||
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
.ctx-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.ctx-rows {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.ctx-rows > div {
|
||||
display: grid;
|
||||
grid-template-columns: 120px 1fr;
|
||||
gap: 10px;
|
||||
padding: 6px 0;
|
||||
border-bottom: 1px solid #1c2a37;
|
||||
}
|
||||
.ctx-rows dt {
|
||||
color: var(--muted);
|
||||
}
|
||||
.ctx-rows dd {
|
||||
margin: 0;
|
||||
word-break: break-all;
|
||||
}
|
||||
.ctx-rows .path {
|
||||
font-size: 12px;
|
||||
}
|
||||
.ctx-foot {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.ctx-toast {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
bottom: calc(var(--player-h) + 16px);
|
||||
transform: translateX(-50%);
|
||||
z-index: 95;
|
||||
background: #2a1418;
|
||||
border: 1px solid #5a2630;
|
||||
color: #ffb3bb;
|
||||
padding: 8px 14px;
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* ── 사이트 로그 (/logs) ── */
|
||||
.logs-page {
|
||||
min-height: 100vh;
|
||||
padding: 18px 26px 40px;
|
||||
max-width: 1500px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.logs-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.logs-head h1 {
|
||||
font-size: 18px;
|
||||
margin: 0;
|
||||
}
|
||||
.logs-back {
|
||||
display: flex;
|
||||
}
|
||||
.logs-help {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
.logs-err {
|
||||
background: #2a1418;
|
||||
border: 1px solid #5a2630;
|
||||
color: #ffb3bb;
|
||||
padding: 10px 14px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.logs-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.logs-bar select,
|
||||
.logs-q {
|
||||
background: #0f1923;
|
||||
border: 1px solid #2c3f52;
|
||||
color: inherit;
|
||||
border-radius: 8px;
|
||||
padding: 7px 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.logs-q {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
}
|
||||
.logs-seg {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
.logs-live {
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
.logs-list {
|
||||
background: #0a121a;
|
||||
border: 1px solid #1c2a37;
|
||||
border-radius: 10px;
|
||||
padding: 8px 0;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.logs-list pre {
|
||||
margin: 0;
|
||||
padding: 3px 14px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
font: inherit;
|
||||
}
|
||||
.logs-list pre:hover {
|
||||
background: #111d28;
|
||||
}
|
||||
.lg-warn {
|
||||
color: #ffd27a;
|
||||
}
|
||||
.lg-error,
|
||||
.lg-fatal {
|
||||
color: #ff8a95;
|
||||
}
|
||||
.lg-info {
|
||||
color: #c9d4de;
|
||||
}
|
||||
|
||||
/* ── 지금 게임 (헤더 · 타임라인 오른쪽) ── */
|
||||
.game-pill {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
border-radius: 999px;
|
||||
padding: 5px 10px;
|
||||
white-space: nowrap;
|
||||
border: 1px solid #2c3f52;
|
||||
color: #b9c6d2;
|
||||
max-width: 260px;
|
||||
min-width: 0;
|
||||
flex-shrink: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
.me-nm {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.game-pill .gp-name {
|
||||
font-weight: 700;
|
||||
}
|
||||
.game-pill .gp-txt {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.game-pill.valorant.in {
|
||||
border-color: rgba(255, 70, 85, 0.6);
|
||||
color: #ffd0d4;
|
||||
}
|
||||
.game-pill.lol.in {
|
||||
border-color: rgba(200, 170, 110, 0.6);
|
||||
color: #f0e2c0;
|
||||
}
|
||||
@media (max-width: 1500px) {
|
||||
.game-pill .gp-txt {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
.live-g + .live-g {
|
||||
margin-top: 10px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid #1c2a37;
|
||||
}
|
||||
.live-g-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.live-g-top .dim {
|
||||
margin-left: auto;
|
||||
}
|
||||
.ldot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: #4d5d6c;
|
||||
}
|
||||
.ldot.mid {
|
||||
background: #e3b341;
|
||||
}
|
||||
.ldot.on {
|
||||
background: #45d39a;
|
||||
box-shadow: 0 0 6px rgba(69, 211, 154, 0.6);
|
||||
}
|
||||
.live-g.valorant.in .ldot.on {
|
||||
background: var(--accent);
|
||||
box-shadow: 0 0 6px rgba(255, 70, 85, 0.6);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ const proxy = {
|
||||
'/auth': { target: backend, changeOrigin: false },
|
||||
'/game-assets': { target: backend, changeOrigin: false },
|
||||
'/mock': { target: backend, changeOrigin: false },
|
||||
'/site': { target: backend, changeOrigin: false },
|
||||
'/ws': { target: backend.replace(/^http/, 'ws'), ws: true },
|
||||
};
|
||||
|
||||
|
||||
@@ -80,6 +80,15 @@ def build_server(writer: Writer) -> Server:
|
||||
raise WorkerError("bad_request", "since_ms 는 숫자(Unix ms) 또는 null 이어야 합니다")
|
||||
return read(require(req, "logs_dir"), since)
|
||||
|
||||
@server.route("tempo", "thread")
|
||||
def tempo(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
|
||||
from .tempo import change_tempo
|
||||
|
||||
t = req.get("tempo")
|
||||
if not isinstance(t, (int, float)):
|
||||
raise WorkerError("bad_request", "tempo 는 숫자여야 합니다")
|
||||
return change_tempo(require(req, "src"), require(req, "dst"), float(t))
|
||||
|
||||
@server.route("train", "thread")
|
||||
def train(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
|
||||
return run_finetune(req, ctx)
|
||||
|
||||
@@ -95,7 +95,6 @@ class SegInfo:
|
||||
|
||||
@dataclass
|
||||
class Thresholds:
|
||||
vad_ratio: float
|
||||
vad_min_speech_s: float
|
||||
no_speech_prob: float
|
||||
logprob: float
|
||||
@@ -109,7 +108,6 @@ class Thresholds:
|
||||
def thresholds(sensitivity: float) -> Thresholds:
|
||||
s = min(max(float(sensitivity), 0.0), 1.0)
|
||||
return Thresholds(
|
||||
vad_ratio=0.03 + 0.17 * s, # 0.5 → 0.115
|
||||
vad_min_speech_s=0.08 + 0.14 * s, # 0.5 → 0.15s
|
||||
no_speech_prob=0.85 - 0.3 * s, # 0.5 → 0.70
|
||||
logprob=-1.3 + 0.6 * s, # 0.5 → -1.0
|
||||
@@ -122,8 +120,13 @@ def thresholds(sensitivity: float) -> Thresholds:
|
||||
|
||||
|
||||
def judge_vad(speech_ratio: float, speech_s: float, sensitivity: float) -> bool:
|
||||
"""목소리가 조금이라도(0.5 기준 0.15초) 있으면 Whisper 로 넘긴다.
|
||||
|
||||
v1.3.5 까지는 말소리 비율(길이 대비 11.5%)도 봐서, 긴 잡음 속 짧은 한마디도 잡음으로 버렸다.
|
||||
"""
|
||||
del speech_ratio # 비율은 보지 않는다 (호환용 인자)
|
||||
t = thresholds(sensitivity)
|
||||
return speech_ratio < t.vad_ratio or speech_s < t.vad_min_speech_s
|
||||
return speech_s < t.vad_min_speech_s
|
||||
|
||||
|
||||
def judge_no_speech(segs: list[SegInfo], text: str, sensitivity: float) -> bool:
|
||||
@@ -180,6 +183,20 @@ def judge_repetition(text: str, segs: list[SegInfo], sensitivity: float) -> bool
|
||||
return any(s.compression_ratio > t.compression + 0.4 for s in segs) and len(norm) >= 12
|
||||
|
||||
|
||||
_REPEAT_RE = re.compile(r"(.{1,10}?)(?:\s*\1){2,}")
|
||||
|
||||
|
||||
def collapse_repetition(text: str) -> str:
|
||||
"""Whisper 반복 고리("페이스페이스페이스…", "아 아 아 아")를 한 번으로 줄인다."""
|
||||
out = text.strip()
|
||||
for _ in range(3):
|
||||
nxt = _REPEAT_RE.sub(lambda m: m.group(1), out)
|
||||
if nxt == out:
|
||||
break
|
||||
out = nxt
|
||||
return re.sub(r"\s{2,}", " ", out).strip()
|
||||
|
||||
|
||||
def judge_text(
|
||||
text: str, segs: list[SegInfo], confidence: float, duration_s: float, sensitivity: float
|
||||
) -> str | None:
|
||||
|
||||
@@ -196,6 +196,12 @@ class SttEngine:
|
||||
result.update(raw_text=raw_text or None, confidence=round(confidence, 3))
|
||||
|
||||
reason = noise.judge_text(raw_text, infos, confidence, prep.duration_s, sensitivity)
|
||||
if reason == "repetition":
|
||||
# 반복 고리는 한 번으로 줄여서, 알아들은 말이 남으면 그 말을 쓴다 (단어 하나라도 있으면 보여 준다)
|
||||
collapsed = noise.collapse_repetition(raw_text)
|
||||
if noise.normalize(collapsed) and noise.judge_hallucination(collapsed, confidence, prep.duration_s, sensitivity) is False:
|
||||
raw_text, words, reason = collapsed, [], None
|
||||
result.update(raw_text=raw_text, collapsed_repetition=True)
|
||||
if reason:
|
||||
return done(reason)
|
||||
|
||||
|
||||
69
worker/gvr_worker/tempo.py
Normal file
69
worker/gvr_worker/tempo.py
Normal file
@@ -0,0 +1,69 @@
|
||||
"""녹음 안내(TTS) 속도 바꾸기.
|
||||
|
||||
Edge TTS 는 말 속도를 0.5배까지만 늦춘다. 그보다 느리게(0.1~0.5배) 하려면 0.5배로 합성한 음성을
|
||||
여기서 atempo 필터로 한 번 더 늘린다. 결과는 디스코드에 바로 보낼 수 있는 Ogg Opus (48kHz).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fractions import Fraction
|
||||
|
||||
from .protocol import WorkerError
|
||||
|
||||
|
||||
def atempo_chain(tempo: float) -> list[float]:
|
||||
"""atempo 한 단계는 0.5~2.0 만 받는다. 0.5 보다 느리면 여러 단계로 나눈다."""
|
||||
if not 0.05 <= tempo <= 2.0:
|
||||
raise WorkerError("bad_request", "tempo 는 0.05~2.0 이어야 합니다")
|
||||
out: list[float] = []
|
||||
t = tempo
|
||||
while t < 0.5:
|
||||
out.append(0.5)
|
||||
t /= 0.5
|
||||
out.append(round(t, 6))
|
||||
return out
|
||||
|
||||
|
||||
def change_tempo(src: str, dst: str, tempo: float) -> dict[str, float]:
|
||||
import av
|
||||
import av.filter
|
||||
|
||||
chain = atempo_chain(tempo)
|
||||
with av.open(src) as inp, av.open(dst, "w", format="ogg") as out:
|
||||
ist = inp.streams.audio[0]
|
||||
ost = out.add_stream("libopus", rate=48000)
|
||||
ost.layout = "mono"
|
||||
graph = av.filter.Graph()
|
||||
node = graph.add_abuffer(template=ist)
|
||||
for t in chain:
|
||||
nxt = graph.add("atempo", str(t))
|
||||
node.link_to(nxt)
|
||||
node = nxt
|
||||
fmt = graph.add("aformat", "sample_fmts=s16:sample_rates=48000:channel_layouts=mono")
|
||||
node.link_to(fmt)
|
||||
sink = graph.add("abuffersink")
|
||||
fmt.link_to(sink)
|
||||
graph.configure()
|
||||
dur = 0.0
|
||||
|
||||
def drain() -> None:
|
||||
nonlocal dur
|
||||
while True:
|
||||
try:
|
||||
f = sink.pull()
|
||||
except (av.error.BlockingIOError, av.error.EOFError):
|
||||
return
|
||||
f.pts = None
|
||||
f.time_base = Fraction(1, 48000)
|
||||
dur += f.samples / 48000
|
||||
for p in ost.encode(f):
|
||||
out.mux(p)
|
||||
|
||||
for frame in inp.decode(ist):
|
||||
graph.push(frame)
|
||||
drain()
|
||||
graph.push(None)
|
||||
drain()
|
||||
for p in ost.encode(None):
|
||||
out.mux(p)
|
||||
return {"duration_s": round(dur, 3), "stages": len(chain)}
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from gvr_worker.noise import HALLUCINATION_PHRASES, SegInfo, judge_text, judge_vad, thresholds
|
||||
from gvr_worker.noise import HALLUCINATION_PHRASES, SegInfo, collapse_repetition, judge_text, judge_vad, thresholds
|
||||
|
||||
GOOD = [SegInfo(0.05, -0.3, 1.2)]
|
||||
|
||||
@@ -36,5 +36,14 @@ def test_vad_and_sensitivity() -> None:
|
||||
assert judge_vad(0.0, 0.0, 0.5)
|
||||
assert not judge_vad(0.7, 2.0, 0.5)
|
||||
lo, hi = thresholds(0.0), thresholds(1.0)
|
||||
assert lo.vad_ratio < hi.vad_ratio and lo.no_speech_prob > hi.no_speech_prob
|
||||
assert judge_vad(0.15, 0.4, 1.0) and not judge_vad(0.15, 0.4, 0.0)
|
||||
assert lo.vad_min_speech_s < hi.vad_min_speech_s and lo.no_speech_prob > hi.no_speech_prob
|
||||
assert judge_vad(0.02, 0.2, 1.0) and not judge_vad(0.02, 0.2, 0.0)
|
||||
# 긴 잡음 속 짧은 한마디(0.3초)도 Whisper 로 넘긴다 (예전: 비율 5% 라 잡음)
|
||||
assert not judge_vad(0.05, 0.3, 0.5)
|
||||
|
||||
|
||||
def test_collapse_repetition() -> None:
|
||||
assert collapse_repetition("엘리베이 아이스페이스페이스페이스페이스페이스") == "엘리베이 아이스페이스"
|
||||
assert collapse_repetition("아 아 아 아 아 아 아 아") == "아"
|
||||
assert collapse_repetition("가자 가자") == "가자 가자"
|
||||
assert collapse_repetition("레이즈 궁 빠졌어") == "레이즈 궁 빠졌어"
|
||||
|
||||
32
worker/tests/test_tempo.py
Normal file
32
worker/tests/test_tempo.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from gvr_worker.protocol import WorkerError
|
||||
from gvr_worker.tempo import atempo_chain, change_tempo
|
||||
|
||||
SRC = Path(__file__).resolve().parents[2] / "app" / "resources" / "tts" / "announce-default.webm"
|
||||
|
||||
|
||||
def test_chain() -> None:
|
||||
assert atempo_chain(1.0) == [1.0]
|
||||
assert atempo_chain(0.2) == [0.5, 0.5, 0.8]
|
||||
assert atempo_chain(2.0) == [2.0]
|
||||
with pytest.raises(WorkerError):
|
||||
atempo_chain(0.01)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not SRC.exists(), reason="기본 안내 음성 없음")
|
||||
def test_change_tempo(tmp_path: Path) -> None:
|
||||
import av
|
||||
|
||||
with av.open(str(SRC)) as f:
|
||||
base = sum(fr.samples / fr.sample_rate for fr in f.decode(audio=0))
|
||||
out = tmp_path / "slow.ogg"
|
||||
r = change_tempo(str(SRC), str(out), 0.4)
|
||||
assert abs(r["duration_s"] - base / 0.4) < 0.5
|
||||
with av.open(str(out)) as f:
|
||||
s = f.streams.audio[0]
|
||||
assert s.codec_context.name == "opus" and s.rate == 48000
|
||||
Reference in New Issue
Block a user