18 Commits

Author SHA1 Message Date
EJClaw
df0c8267c9 v1.4.1: 잡음 문장 비교를 글자 바뀜만으로 — 배운 문장 앞뒤에 붙은 실제 말은 지우지 않음
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:45:50 +09:00
EJClaw
a6c681e44e 테스트 기록: v1.4.0 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:41:16 +09:00
EJClaw
3115337706 v1.4.0: 발화 우클릭 삭제(잡음이라 삭제 · 그냥 삭제) · 잡음 문장 배우기 · 새 발화/재생 시작 알림 기본 끄기
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:30:33 +09:00
EJClaw
8047a2e948 테스트 기록: v1.3.9 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:01:53 +09:00
EJClaw
55ec58f343 v1.3.9: 받아오기 — 표시 이름에 '..' 이 든 녹음 파일 이름도 받는다 (폴더 구분자만 막음)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 06:02:36 +09:00
EJClaw
6a32bedfe3 테스트 기록: v1.3.8 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:59:30 +09:00
EJClaw
249ead887a v1.3.8: 녹음 파일 이름을 날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg 로
- 저장 직후 이름 붙이기(경기 중엔 지금 라운드), 경기 상세 · 표시 이름이 바뀌면 다시 맞춤, 예전 파일도 바꿈
- 음성 인식이 읽는 중이면 끝난 뒤 바꿈, 기록 zip · 사이트 다운로드도 같은 이름

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:49:57 +09:00
EJClaw
31fd18a0e9 v1.3.7 보고서 PDF · 테스트 기록
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:44:07 +09:00
EJClaw
5d494eb8e8 v1.3.7: 기록 관리(경기 · 경기 전후 대화 묶음, 한 번에 지우기 · zip 내보내기/받아오기) · 검토로 찾은 오류 고침
- 기록 묶음 API · zip 형식(gvr-bundle v1) · 받아오기 검사(꼭 필요한 내용이 없으면 실패, 아무것도 넣지 않음)
- 사이트 기록 탭, 큰 zip 조각 중계
- 관리자 확인 %인코딩 우회, 큰 전송 중 연결 끊김, 진행 중 경기 지우기, 예전 녹음 고치기 덮어쓰기,
  타임라인 끼워 넣기, 숫자 반복 줄이기, TTS 반쪽 파일 등

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:34:39 +09:00
EJClaw
c397bacf8c WIP v1.3.7: 기록 묶음(경기 · 경기 전후 대화) 관리 · zip 내보내기/받아오기
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:21:32 +09:00
EJClaw
98b8342678 테스트 기록: v1.3.6 릴리스 · 배포
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:11:39 +09:00
EJClaw
0ce9235a8e 사이트: 예전 앱(v1.3.5 이하)에도 잡음을 빼 달라고 요청
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:01:38 +09:00
EJClaw
fa6126e17f v1.3.6: 목소리 깨짐(RTP 기준 쉼 채우기) · 알 수 없음 · 잡음 숨기기/삭제 · 사이트 로그 · 지금 게임 · TTS 속도 · 시작 창
- 녹음기: 패킷 도착 간격 대신 RTP 타임스탬프로 자리를 정한다. 게임 중 몰려 온 패킷 사이에 무음이 끼어 목소리가 깨졌다. 예전 녹음은 한 번 고친 뒤 다시 변환
- users.updated 를 빈 목록으로 보내 사이트에서 말한 사람이 '알 수 없음'이 되던 것
- 잡음은 숨기고 ogg 삭제, 로그에 잡음으로 남김. 짧은 목소리도 Whisper 로, 반복 고리는 줄여서 보여 줌
- 사이트: 재생 음량, 발화 우클릭(자세한 정보 · ogg 다운로드), 사이트 로그(/logs, 게임 PC 꺼져도), 지금 게임 상태
- 앱: 지금 게임 상태, 녹음 안내 말 속도 0.1~2.0, 포터블 · 앱 시작 창
- 발로란트 데스매치 가짜 라운드 · 에이스, 빈 선수 이름

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:01:14 +09:00
EJClaw
2ffb18263c 테스트 기록: v1.3.5 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:22:45 +09:00
EJClaw
3f7bf1cb86 v1.3.5: 표시 이름 빈틈 — 이름 바꾼 뒤 도착한 범인 분석에도 예전 이름이 남지 않게
- 가린 예전 이름을 meta.hidden_names 에 기억, 분석 저장(Culprit.save) · 이름 다시 받기(setDisplayNames, 건너뛰기 없이 전체)에서 바꿈
- 회귀 테스트: 이름을 바꾼 뒤 예전 이름이 든 분석 저장 → DB 에 예전 이름 0건 (예전 코드에서 실패 확인)
- site/server/scripts/presence-e2e.mts: 실제 디스코드에서 봇 음성 입장/퇴장 → 상태 메시지 녹음 중/대기 중 전환 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:14:00 +09:00
EJClaw
0dd46a5e16 테스트 기록: v1.3.4 릴리스 · 배포
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:07:40 +09:00
EJClaw
db2f1866e4 v1.3.4: 슬래시 명령 무응답 고침 · 녹음 중 봇 상태 메시지
- 원인: 그 서버를 지켜보는 앱이 없으면 discord-source 가 명령을 그냥 무시 → 디스코드 "애플리케이션이 응답하지 않았어요"
  → 1.5초 기다린 뒤(옛 v1.1.0 PC 가 먼저 받았으면 '이미 응답함'으로 빠짐) 이유를 답한다:
    앱 없음 / 내 앱이 다른 서버를 녹음 대상으로 정함 / 내 앱이 아직 연결 중. 서버 로그에 남김
- 앱: 지켜보던 중 권한 재확인으로 watch_denied 를 받으면 1분 뒤 다시 지켜보기 요청 (명령 · 음성 상태가 영영 끊기지 않게)
- 상태 메시지: 봇이 어느 서버에서든 음성채널에 있으면 dnd + "🔴 녹음 중", 아니면 online + "🎙️ 대기 중 · /녹음시작"
  (겜녹이 봇은 사이트 서버, 다른 봇 모드는 LocalGateway). 테스트 봇으로 실제 디스코드가 형식을 받는 것 확인
- 테스트: 앱 41 · 서버 16 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:58:26 +09:00
EJClaw
125e2a22ee 테스트 기록: v1.3.3 릴리스 · 배포
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:54:05 +09:00
102 changed files with 5377 additions and 175 deletions

View File

@@ -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.3](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.3) (`GameVoiceRecorder-1.3.3-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.3-portable.exe`) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
- Windows 실행 파일: Gitea 릴리스 [v1.4.1](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.4.1) (`GameVoiceRecorder-1.4.1-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.4.1-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
## 로그인 · 관리자 (v1.2.0~)
@@ -19,6 +19,55 @@
- 앱은 시작할 때와 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.4.1 바뀐 점
- 잡음으로 배운 문장 비교: v1.4.0 은 편집 거리로 비교해서, 배운 문장 뒤에 짧은 실제 말("네", "가자", "아니")이 붙은 발화까지 잡음으로 지웠다. 이제 글자 수가 같고 15% 안 글자만 바뀐 것(인식이 한두 글자 다르게 나온 것)만 같은 문장으로 본다
## v1.4.0 바뀐 점
- 사이트 발화 우클릭 → **삭제…**: 확인 창에서 "잡음이라 삭제" 또는 "그냥 삭제". 관리자나 말한 사람만 지울 수 있고, 글 · 음성 파일 · 교정 학습 데이터를 게임 PC 에서 지운다 (`POST /api/utterances/:id/delete`)
- "잡음이라 삭제"는 인식된 문장을 `noise_phrases` 에 배운다. 다음에 같은 문장(띄어쓰기 · 문장부호 무시, 8글자 이상이면 글자 수가 같고 15% 안 글자만 바뀐 것까지. 앞뒤에 말이 붙으면 그대로)이 인식되면 잡음(`noise_reason='learned'`)으로 숨기고 파일을 지운다. 배운 문장은 단어사전 화면에서 보고 지운다 (`GET/DELETE /api/noise-phrases`)
- 사이트 효과음: "새 발화 알림" · "재생 시작"을 기본으로 끈다 (예전에 저장한 설정도 한 번 꺼 줌, 그 뒤 다시 켜면 그대로)
## v1.3.9 바뀐 점
- 기록 zip 받아오기: 표시 이름에 `..` 이 있으면(예: `하늘..별`) 그 이름이 들어간 녹음 파일을 "음성 파일 이름이 잘못되었습니다"로 거절해, 내보낸 zip 을 다시 넣지 못했다. zip 안 이름은 꺼낼 때 찾는 열쇠로만 쓰고 이 PC 에 쓸 경로는 발화 ID 로 만들므로, 폴더 구분자(`/`, `\`)만 막는다
## v1.3.8 바뀐 점
- **녹음 파일 이름**: `날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg` (예: `2026-10-16_04-03-16_사금향_발로란트_경쟁전_어센트_R7_0mv9….ogg`, 롤은 라운드 대신 게임 시간 `12분30초`, 경기 밖은 `…_사금향_경기밖_….ogg`). 시각은 게임 PC 시각, Windows 에서 못 쓰는 글자는 뺀다. `app/src/core/audio-names.ts`
- 녹음이 끝나면 바로 이 이름으로 저장하고(경기 중에는 지금 라운드), 경기가 끝나 경기 상세(정확한 라운드)가 오거나 표시 이름이 바뀌면 다시 맞춘다. 예전 파일도 처음 켤 때 바꾼다
- 음성 인식이 그 파일을 읽는 중이거나 대기열에 있으면 바꾸지 않고, 변환이 끝난 뒤 바꾼다. 다른 프로그램이 파일을 열고 있으면 다음에 다시 한다
- 기록 zip 안 `audio/` 도 같은 이름, 사이트 ogg 다운로드 · 자세한 정보도 같은 이름 (v1.3.7 zip 의 `audio/<발화ID>.ogg` 도 그대로 받는다)
## v1.3.7 바뀐 점
- **기록 관리** (사이트 "기록" 탭, `site/web/src/pages/RecordsPage.tsx`): 기록을 경기 하나 = 묶음 하나로 보고, 경기 밖 대화는 녹음 세션 안에서 경기 사이마다 묶는다. 다음 경기가 30분 안에 시작하면 "경기 전 대화", 지난 경기가 30분 안에 끝났으면 "경기 후 대화", 아니면 "게임 밖 대화". 묶음을 골라 한 번에 zip 내려받기 · 지우기(관리자) · zip 받아오기(관리자). 앱 `app/src/core/bundles.ts`, API `GET /api/bundles` · `GET /api/bundles/export?ids=` · `POST /api/bundles/delete` · `POST /api/bundles/import`
- **zip 형식** `gvr-bundle` v1: `manifest.json`(형식 · 묶음 · 개수), `data.json`(유저 · 세션 · 경기 · 라운드 · 이벤트 · 범인 분석 · 발화), `audio/<발화ID>.ogg`, `대화.txt`. 받아오기는 형식 · 버전 · 발화 ID · 말한 사람 · 시각 · 경기 연결 · 음성 파일(ogg 머리) · 개수를 모두 확인하고 하나라도 빠지면 아무것도 넣지 않고 "받아오기 실패: (이유)"로 끝낸다. 이미 있는 발화는 건너뛴다. 받아온 녹음의 보관 기간은 받아온 날부터 센다 (`utterance_imports`)
- 사이트 ↔ 게임 PC 중계: 큰 zip 을 1MB 조각으로 주고받는다 (사이트 서버 → 앱 요청 본문, 앱 → 사이트 서버 응답 모두)
## 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`), 분석을 저장할 때마다 · 이름을 다시 받을 때마다 모든 분석에서 바꾼다
- 상태 메시지 실제 확인: `site/server/scripts/presence-e2e.mts` (사이트 서버 코드로 봇을 빈 음성채널에 넣었다 빼며 확인)
## v1.3.4 바뀐 점
- **슬래시 명령 응답**: 그 디스코드 서버를 지켜보는 겜녹이 앱이 없으면 사이트 서버가 명령을 무시해서 디스코드에 "애플리케이션이 응답하지 않았어요"만 떴다 (봇 토큰을 직접 쓰는 옛 v1.1.0 PC 와 겹치지 않게 넣은 동작). 이제 1.5초 기다렸다가 아무도 받지 않았으면 이유를 답한다: 앱이 꺼져 있음 / 내 앱이 다른 서버를 녹음 대상으로 정해 둠 / 아직 연결 중. 앱은 서버가 권한을 다시 확인하다 지켜보기를 끊으면 1분 뒤 다시 요청한다
- **봇 상태 메시지**: 녹음 중(봇이 어느 서버에서든 음성채널에 있음)이면 빨간 상태(다른 용무 중) + "🔴 녹음 중", 아니면 "🎙️ 대기 중 · /녹음시작". 겜녹이 봇은 사이트 서버가, 다른 봇 모드는 앱이 바꾼다. 봇 하나가 여러 서버에 들어가 있어서 채널 이름은 넣지 않는다
## v1.3.3 바뀐 점
- **따라갈 사람 목록**: 녹음할 서버의 멤버가 모두 나온다. 내 계정이 맨 위, 그다음 관리자(최고 관리자 포함), 나머지는 이름순. 예전에는 봇이 서버를 지켜보기 전에 목록을 요청하면 사이트 서버가 거절했고 앱이 그 오류를 숨겨 "선택 안 함"만 보였다. 이제 가입한 서버면 바로 받고, 실패하면 오류와 다시 불러오기 버튼을 보여 준다. 녹음할 서버를 바꾸면 봇이 새 서버를 바로 지켜본다. 서버: `GET /app/admins`
@@ -71,7 +120,7 @@
| M6 단어사전 · UI/UX | 핫워드·교정 사전, 사이트 교정 반영, 테마·애니메이션·효과음 | ✅ 완료 ([사전 효과](docs/dev/test-results.md)) |
| M7 실사용 테스트 | 통합 테스트, 성능·안정화 | ✅ 완료 (GPU 실음성: CER 3.6%, 지연 1.05초 · [기록](docs/dev/test-results.md)) |
| M8 파인튜닝 | 교정 데이터 + 합성 음성 LoRA 학습, 오류율 비교 후 교체 | ✅ 완료 (GPU 시험 학습: CER 4.8% → 1.8%) |
| 범인찾기 (v1.3.x) | AI(Claude Opus 5.5 high) 10명 평점 · 팀별 범인 · 근거, 기록 점수(OP.GG OP스코어 계산법) · 10/15분 라인전(LOL.PS 정의) | ✅ 완료 (실제 Claude E2E, 사이트 배포, [v1.3.2](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.2) · 리플레이 동기화는 Windows 실기 확인 뒤) |
| 범인찾기 (v1.3.x) | AI(Claude Opus 5.5 high) 10명 평점 · 팀별 범인 · 근거, 기록 점수(OP.GG OP스코어 계산법) · 10/15분 라인전(LOL.PS 정의) | ✅ 완료 (실제 Claude E2E, 사이트 배포, [v1.3.5](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.5) · 리플레이 동기화는 Windows 실기 확인 뒤) |
## 저장소 구조

10
app/package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "gvr-app",
"version": "1.3.3",
"version": "1.4.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gvr-app",
"version": "1.3.3",
"version": "1.4.1",
"license": "UNLICENSED",
"dependencies": {
"@discordjs/voice": "^0.19.2",
@@ -3897,7 +3897,7 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
"node_modules/ini": {
"version": "1.3.8",
"version": "1.3.9",
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="
},
@@ -4677,7 +4677,7 @@
}
},
"node_modules/prism-media": {
"version": "1.3.5",
"version": "1.3.9",
"resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz",
"integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==",
"peerDependencies": {
@@ -4782,7 +4782,7 @@
}
},
"node_modules/pvtsutils": {
"version": "1.3.6",
"version": "1.3.9",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
"dev": true,

View File

@@ -1,7 +1,7 @@
{
"name": "gvr-app",
"productName": "겜녹이",
"version": "1.3.3",
"version": "1.4.1",
"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"
}
}
}

View File

@@ -1,14 +1,28 @@
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 { normalizePhrase, type Store, type UserRow } from '../db/db.js';
import type { Dictionary } from '../dict/dictionary.js';
import type { GameManager } from '../games/manager.js';
import type { Settings } from '../settings.js';
import { safeJson, type Timeline, type TimelineQuery } from '../timeline.js';
import type { Bus } from '../util/events.js';
import { BundleError, type Bundles } from '../bundles.js';
import { logger } from '../util/log.js';
const log = logger('api');
/** 파일 지우기. 음성 인식 · 다른 프로그램이 열고 있으면(Windows) 5초마다 다시 (1분까지) */
export function removeFile(f: string, tries = 12): void {
try {
fs.rmSync(f, { force: true });
} catch (e: any) {
if (tries <= 1) return void log.warn(`파일 삭제 실패 ${path.basename(f)}: ${e?.code ?? e?.message}`);
setTimeout(() => removeFile(f, tries - 1), 5000).unref?.();
}
}
export interface ApiDeps {
store: Store;
@@ -21,6 +35,8 @@ export interface ApiDeps {
trainingDir: () => string;
overviewExtra: () => { guild: Overview['guild']; recording: Overview['recording'] };
version: string;
/** 기록 묶음 (없으면 /api/bundles 없음) */
bundles?: Bundles;
}
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
@@ -54,6 +70,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 +125,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 +132,122 @@ 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,
};
});
// ---- 기록 묶음: 경기별 · 경기 전후 대화별로 보기 · 지우기 · zip 내보내기 · zip 받아오기 (v1.3.7)
// zip 은 사이트 서버가 조각으로 나눠 보낸다. 300MB 까지
app.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body));
const bundleErr = (reply: any, e: unknown) => {
if (e instanceof BundleError) return reply.code(e.code === 'not_found' ? 404 : e.code === 'busy' ? 409 : e.code === 'too_large' ? 413 : 400).send({ error: e.code, message: e.message });
throw e;
};
/** 사이트 중계로 온 요청이면 사이트 서버가 붙인 역할이 관리자여야 한다 (이 PC 안에서 부른 것은 그대로) */
const adminOnly = (req: any, reply: any): boolean => {
if (!req.headers['x-gvr-user']) return true;
if (req.headers['x-gvr-role'] === 'admin') return true;
reply.code(403).send({ error: 'forbidden', message: '기록 지우기 · 받아오기는 관리자만 할 수 있습니다' });
return false;
};
/** 발화 지우기: 이 PC 안에서 부른 것 · 관리자 · 말한 사람 본인 */
const canDelete = (req: any, speakerId: string): boolean => {
const raw = req.headers['x-gvr-user'];
if (!raw) return true;
if (req.headers['x-gvr-role'] === 'admin') return true;
try {
return JSON.parse(decodeURIComponent(String(raw)))?.id === speakerId;
} catch {
return false;
}
};
const exportZip = (reply: any, ids: string[]) => {
const { zip, fileName } = d.bundles!.export(ids);
return reply.header('content-type', 'application/zip').header('content-disposition', `attachment; filename="${fileName}"`).header('cache-control', 'no-store').send(zip);
};
app.get('/api/bundles', async (_req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
return { bundles: d.bundles.list() };
});
app.post<{ Body: { ids?: string[] } }>('/api/bundles/delete', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
if (!adminOnly(req, reply)) return;
try {
const ids = Array.isArray(req.body?.ids) ? req.body.ids.map(String) : [];
const r = d.bundles.delete(ids);
timeline.invalidate();
d.bus.live({ type: 'records.changed', data: { reason: 'deleted', ids } });
return r;
} catch (e) {
return bundleErr(reply, e);
}
});
app.get<{ Querystring: { ids?: string } }>('/api/bundles/export', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
try {
return exportZip(reply, String(req.query.ids ?? '').split(',').filter(Boolean));
} catch (e) {
return bundleErr(reply, e);
}
});
// 많이 고르면 주소가 너무 길어진다: 본문으로 받는 것도 둔다
app.post<{ Body: { ids?: string[] } }>('/api/bundles/export', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
try {
return exportZip(reply, Array.isArray(req.body?.ids) ? req.body.ids.map(String) : []);
} catch (e) {
return bundleErr(reply, e);
}
});
app.post('/api/bundles/import', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
if (!adminOnly(req, reply)) return;
if (!Buffer.isBuffer(req.body)) return reply.code(400).send({ error: 'invalid_bundle', message: '받아오기 실패: zip 파일을 보내 주세요' });
try {
const r = d.bundles.import(req.body);
timeline.invalidate();
d.bus.live({ type: 'records.changed', data: { reason: 'imported' } });
d.bus.live({ type: 'users.updated', data: [] });
return r;
} catch (e) {
return bundleErr(reply, e);
}
});
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 +303,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,
@@ -213,6 +345,35 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
return item;
});
// 발화 지우기 (v1.4.0): 사이트 우클릭 메뉴. 관리자 또는 말한 사람만.
// noise=true 면 "잡음이라 삭제": 인식된 문장을 배워서, 같은 문장이 다시 나오면 잡음으로 본다
app.post<{ Params: { id: string }; Body: { noise?: boolean } }>('/api/utterances/:id/delete', async (req, reply) => {
const u = store.getUtterance(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found', message: '이미 지워진 발화입니다' });
if (!canDelete(req, u.user_id)) return reply.code(403).send({ error: 'forbidden', message: '발화는 관리자나 말한 사람만 지울 수 있습니다' });
let learned: string | null = null;
if (req.body?.noise) {
const sample = (u.raw_text ?? u.text ?? '').trim();
const phrase = normalizePhrase(sample);
if (phrase) {
store.addNoisePhrase(phrase, sample.slice(0, 200));
learned = sample.slice(0, 200);
}
}
const files = store.deleteUtterance(u.id);
for (const f of files) removeFile(f);
timeline.invalidate();
d.bus.live({ type: 'utterance.deleted', data: { id: u.id, noise: !!req.body?.noise } });
return { ok: true, learned };
});
app.get('/api/noise-phrases', async () => ({
phrases: store.listNoisePhrases().map((r) => ({ id: r.id, text: r.sample, hits: r.hits, createdAt: r.created_at })),
}));
app.delete<{ Params: { id: string } }>('/api/noise-phrases/:id', async (req, reply) => {
if (!store.deleteNoisePhrase(Number(req.params.id))) return reply.code(404).send({ error: 'not_found' });
return { ok: true };
});
// 사이트에서 단어·교정 규칙 추가/삭제 (보고서 5-4: 사이트·설정에서 직접 추가·수정)
app.post<{ Body: { word?: string; from?: string; to?: string } }>('/api/dictionary', async (req, reply) => {
const b = req.body || {};

156
app/src/core/audio-names.ts Normal file
View File

@@ -0,0 +1,156 @@
import fs from 'node:fs';
import path from 'node:path';
import type { MatchRow, Store, UtteranceRow } from './db/db.js';
import type { GameManager } from './games/manager.js';
import { valNoRounds } from './games/modes.js';
import { logger } from './util/log.js';
const log = logger('audio');
/**
* 녹음 파일 이름 (v1.3.8): 파일만 봐도 무슨 녹음인지 알 수 있게
* 2026-10-16_04-03-16_사금향_발로란트_경쟁전_어센트_R7_<발화ID>.ogg
* 2026-10-16_21-10-05_하늘_롤_솔로랭크_12분30초_<발화ID>.ogg
* 2026-10-16_03-58-56_사금향_경기밖_<발화ID>.ogg
* 날짜 · 시각은 이 PC 시각, 끝의 발화 ID 로 이름이 겹치지 않는다. 경기가 끝나 라운드가 정확해지면 이름을 다시 맞춘다.
*/
export interface NameInfo {
id: string;
startedAt: number;
speaker: string;
/** 경기 밖이면 null */
game: 'valorant' | 'lol' | null;
mode?: string | null;
map?: string | null;
round?: number | null;
/** 롤: 경기 시작부터 지난 시간 */
gameTimeMs?: number | null;
}
const pad = (n: number) => String(n).padStart(2, '0');
/** 파일 이름에 못 쓰는 글자(Windows) · 공백을 뺀다 */
export function safePart(s: string | null | undefined, max = 24): string {
return String(s ?? '')
.replace(/[\\/:*?"<>|\x00-\x1f]/g, '')
.replace(/[\s_]+/g, '')
.replace(/\.+$/, '')
.slice(0, max);
}
export function audioFileName(o: NameInfo): string {
const d = new Date(o.startedAt);
const when = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}_${pad(d.getHours())}-${pad(d.getMinutes())}-${pad(d.getSeconds())}`;
const parts = [when, safePart(o.speaker) || '알수없음'];
if (!o.game) parts.push('경기밖');
else {
parts.push(o.game === 'valorant' ? '발로란트' : '롤');
const mode = safePart(o.mode);
const map = safePart(o.map);
if (mode) parts.push(mode);
if (map && map !== mode) parts.push(map);
if (o.game === 'valorant' && o.round) parts.push(`R${o.round}`);
if (o.game === 'lol' && o.gameTimeMs != null && o.gameTimeMs >= 0) {
const s = Math.floor(o.gameTimeMs / 1000);
parts.push(`${Math.floor(s / 60)}분${pad(s % 60)}초`);
}
}
parts.push(o.id);
return `${parts.join('_')}.ogg`;
}
export class AudioNamer {
constructor(
private store: Store,
private games: GameManager,
/** STT 가 이 발화를 읽는 중이거나 대기열에 있으면 true (이름을 바꾸면 워커가 파일을 못 찾는다) */
private busy: (id: string) => boolean,
) {}
private matchCache = new Map<string, { m: MatchRow; mode: string; map: string; at: number }>();
private matchInfo(id: string) {
const c = this.matchCache.get(id);
if (c && Date.now() - c.at < 5000) return c;
const m = this.store.getMatch(id);
if (!m) return null;
const sum = this.games.summary(m);
const v = { m, mode: sum.mode, map: sum.map.name, at: Date.now() };
this.matchCache.set(id, v);
return v;
}
info(u: UtteranceRow): NameInfo {
const speaker = this.store.getUser(u.user_id)?.name ?? u.user_id;
const mi = u.match_id ? this.matchInfo(u.match_id) : null;
if (!mi) return { id: u.id, startedAt: u.started_at, speaker, game: null };
const { m } = mi;
const gameTs = u.started_at - m.clock_offset;
let round: number | null = null;
if (m.game === 'valorant' && !valNoRounds(m.queue)) {
const rounds = this.store.rounds(m.id);
round = rounds.find((r) => gameTs >= r.started_at && gameTs <= r.ended_at)?.num ?? rounds.find((r) => gameTs < r.started_at)?.num ?? null;
// 경기 중에는 라운드 표가 아직 없다: 지금 라운드를 쓴다 (경기 뒤 정확한 값으로 다시 맞춤)
if (!rounds.length) round = this.games.liveRound(m.id);
}
return {
id: u.id,
startedAt: u.started_at,
speaker,
game: m.game as 'valorant' | 'lol',
mode: mi.mode,
map: m.game === 'lol' ? null : mi.map,
round,
gameTimeMs: m.game === 'lol' ? gameTs - m.started_at : null,
};
}
/** 발화 하나의 파일 이름을 맞춘다. 바꿨으면 true */
refresh(id: string): boolean {
const u = this.store.getUtterance(id);
if (!u || !u.audio_path || u.audio_deleted || this.busy(id)) return false;
const want = audioFileName(this.info(u));
const cur = u.audio_path;
const dir = path.dirname(cur);
if (path.basename(cur) === want) return false;
const next = path.join(dir, want);
try {
if (!fs.existsSync(cur) || fs.existsSync(next)) return false;
fs.renameSync(cur, next);
} catch (e: any) {
// 다른 프로그램이 파일을 열고 있으면(Windows) 다음에 다시 한다
log.debug(`파일 이름 바꾸기 실패 ${path.basename(cur)}: ${e?.code ?? e?.message}`);
return false;
}
this.store.db.prepare('UPDATE utterances SET audio_path=? WHERE id=?').run(next, id);
return true;
}
refreshMatch(matchId: string): number {
this.matchCache.delete(matchId);
const ids = this.store.db.prepare('SELECT id FROM utterances WHERE match_id=? AND audio_deleted=0').all(matchId) as { id: string }[];
let n = 0;
for (const { id } of ids) if (this.refresh(id)) n++;
if (n) log.info(`경기 ${matchId}: 녹음 파일 ${n}개 이름 맞춤`);
return n;
}
private allRunning = false;
/** 모든 녹음 파일 이름을 맞춘다 (예전 이름 · 표시 이름 바뀜). 50개씩 나눠서 */
refreshAll(skip?: (u: { id: string; created_at: number }) => boolean): void {
if (this.allRunning) return;
this.allRunning = true;
this.matchCache.clear();
const rows = this.store.db.prepare('SELECT id, created_at FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL ORDER BY started_at').all() as { id: string; created_at: number }[];
let i = 0;
let n = 0;
const step = () => {
for (const r of rows.slice(i, i + 50)) if (!skip?.(r) && this.refresh(r.id)) n++;
i += 50;
if (i < rows.length) return void setTimeout(step, 0);
this.allRunning = false;
if (n) log.info(`녹음 파일 ${n}개 이름을 바꿈 (날짜 · 시각 · 말한 사람 · 게임 · 라운드)`);
};
step();
}
}

455
app/src/core/bundles.ts Normal file
View File

@@ -0,0 +1,455 @@
import fs from 'node:fs';
import path from 'node:path';
import type { BundleImportResult, BundleInfo, GameType } from '@gvr/shared';
import { fmtReal } from '@gvr/shared';
import type { MatchRow, Store, UtteranceRow } from './db/db.js';
import type { GameManager } from './games/manager.js';
import { logger } from './util/log.js';
import { readZip, writeZip, ZipError, type ZipEntry } from './util/zip.js';
const log = logger('bundles');
/** 기록 묶음 zip 형식 (manifest.json · data.json · audio/<발화ID>.ogg · 대화.txt) */
export const BUNDLE_FORMAT = 'gvr-bundle';
export const BUNDLE_VERSION = 1;
/** 경기와 대화를 같은 판으로 볼 최대 간격 */
const NEAR_MS = 30 * 60000;
/** 세션 없는 대화를 나누는 쉼 */
const TALK_GAP_MS = 30 * 60000;
const SAFE_ID = /^[\w.-]{1,80}$/;
/** 내보내기 음성 합계 한도 (받아오기 한도 300MB 안에 들어가게) */
export const EXPORT_MAX = 280 * 1024 * 1024;
export class BundleError extends Error {
constructor(
message: string,
readonly code = 'invalid_bundle',
) {
super(message);
}
}
interface Group {
info: BundleInfo;
/** 이 묶음의 발화 (잡음 포함: 지울 때 함께 지운다) */
ids: string[];
match: MatchRow | null;
}
type Row = Pick<UtteranceRow, 'id' | 'session_id' | 'user_id' | 'started_at' | 'ended_at' | 'match_id' | 'audio_path' | 'audio_deleted' | 'noise' | 'corrected'>;
/**
* 기록 묶음 (v1.3.7): 경기 하나 = 묶음 하나, 경기 밖 대화는 녹음 세션 안에서 경기 사이마다 한 묶음.
* 다음 경기가 30분 안에 시작하면 "경기 전 대화", 지난 경기가 30분 안에 끝났으면 "경기 후 대화", 아니면 "게임 밖 대화".
* 묶음 단위로 지우기 · zip 내보내기 · zip 받아오기를 한다.
*/
export class Bundles {
constructor(
private store: Store,
private games: GameManager,
private audioDir: () => string,
private version: string,
/** 받아온 발화들 (녹음 파일 이름 맞추기) */
private afterImport?: (ids: string[]) => void,
) {}
private groups(): Group[] {
const db = this.store.db;
const rows = db
.prepare('SELECT id, session_id, user_id, started_at, ended_at, match_id, audio_path, audio_deleted, noise, corrected FROM utterances ORDER BY started_at, id')
.all() as Row[];
const matches = this.store.listMatches({ limit: 100000 });
const mStart = (m: MatchRow) => m.started_at + m.clock_offset;
const mEnd = (m: MatchRow) => m.ended_at ?? mStart(m);
const evCount = new Map((db.prepare('SELECT match_id, count(*) n FROM game_events GROUP BY match_id').all() as { match_id: string; n: number }[]).map((r) => [r.match_id, r.n]));
const byMatch = new Map<string, Row[]>();
const talk: Row[] = [];
const known = new Set(matches.map((m) => m.id));
for (const r of rows) {
if (r.match_id && known.has(r.match_id)) {
const list = byMatch.get(r.match_id) ?? [];
list.push(r);
byMatch.set(r.match_id, list);
} else talk.push(r);
}
const out: Group[] = [];
for (const m of matches) {
const list = byMatch.get(m.id) ?? [];
const sum = this.games.summary(m);
const label = `${m.game === 'valorant' ? '발로란트' : '롤'} · ${sum.mode} · ${sum.map.name}`;
const score = sum.score ? ` ${sum.score.ally}:${sum.score.enemy}` : '';
const result = sum.win === true ? '승리' : sum.win === false ? '패배' : null;
const mi = this.info(`match-${m.id}`, 'match', label, [result, score.trim()].filter(Boolean).join(' ') || null, m.game, m.id, Math.min(mStart(m), ...list.map((r) => r.started_at)), Math.max(mEnd(m), ...list.map((r) => r.ended_at)), list, evCount.get(m.id) ?? 0);
mi.live = m.status === 'live';
out.push({ info: mi, ids: list.map((r) => r.id), match: m });
}
// 경기 밖 대화: 세션이 바뀌거나, 사이에 경기가 시작했거나, 30분 넘게 쉬면 새 묶음
const starts = matches.map(mStart).sort((a, b) => a - b);
const runs: Row[][] = [];
for (const r of talk) {
const cur = runs[runs.length - 1];
const prev = cur?.[cur.length - 1];
const split =
!prev ||
(prev.session_id ?? '') !== (r.session_id ?? '') ||
r.started_at - prev.ended_at > TALK_GAP_MS ||
starts.some((s) => s > prev.started_at && s <= r.started_at);
if (split) runs.push([r]);
else cur.push(r);
}
for (const run of runs) {
const from = run[0].started_at;
const to = Math.max(...run.map((r) => r.ended_at));
const next = matches.filter((m) => mStart(m) >= to - 1000 && mStart(m) - to <= NEAR_MS).sort((a, b) => mStart(a) - mStart(b))[0];
const prev = matches.filter((m) => mEnd(m) <= from + 1000 && from - mEnd(m) <= NEAR_MS).sort((a, b) => mEnd(b) - mEnd(a))[0];
const name = (m: MatchRow) => {
const s = this.games.summary(m);
return `${m.game === 'valorant' ? '발로란트' : '롤'} ${s.map.name}`;
};
const [label, sub] = next ? ['경기 전 대화', `다음 경기: ${name(next)}`] : prev ? ['경기 후 대화', `지난 경기: ${name(prev)}`] : ['게임 밖 대화', null];
const info = this.info(`talk-${run[0].id}`, 'talk', label, sub, null, null, from, to, run, 0);
if (!info.utterances) continue; // 잡음만 남은 묶음은 보이지 않는다
out.push({ info, ids: run.map((r) => r.id), match: null });
}
return out.sort((a, b) => b.info.from - a.info.from);
}
private info(id: string, kind: BundleInfo['kind'], label: string, sub: string | null, game: GameType | null, matchId: string | null, from: number, to: number, rows: Row[], events: number): BundleInfo {
const shown = rows.filter((r) => !r.noise || r.corrected);
let audio = 0;
let bytes = 0;
for (const r of shown) {
if (!r.audio_path || r.audio_deleted) continue;
try {
bytes += fs.statSync(r.audio_path).size;
audio++;
} catch {
/* 파일 없음 */
}
}
return {
id,
kind,
label,
sub,
game,
matchId,
from: isFinite(from) ? from : 0,
to: isFinite(to) ? to : from,
utterances: shown.length,
audio,
audioBytes: bytes,
events,
talkMs: shown.reduce((n, r) => n + (r.ended_at - r.started_at), 0),
users: [...new Set(shown.map((r) => r.user_id))],
live: false,
};
}
list(): BundleInfo[] {
return this.groups().map((g) => g.info);
}
private pick(ids: string[]): Group[] {
if (!ids.length) throw new BundleError('고른 묶음이 없습니다', 'bad_request');
const all = new Map(this.groups().map((g) => [g.info.id, g]));
const out: Group[] = [];
for (const id of ids) {
const g = all.get(id);
if (!g) throw new BundleError(`묶음을 찾을 수 없습니다: ${id} (목록을 새로 고쳐 주세요)`, 'not_found');
out.push(g);
}
return out;
}
// ------------------------------------------------------------------ 지우기
delete(ids: string[]): { bundles: number; utterances: number; files: number } {
const groups = this.pick(ids);
// 진행 중인 경기는 지우지 않는다 (경기가 끝날 때 녹음 · 음성 인식 · 경기 상세가 이 경기를 찾는다)
const live = groups.find((g) => g.match && g.match.status === 'live');
if (live) throw new BundleError(`진행 중인 경기는 지울 수 없습니다: ${live.info.label} (경기가 끝난 뒤 지워 주세요)`, 'busy');
const db = this.store.db;
const uttIds = groups.flatMap((g) => g.ids);
const matchIds = groups.flatMap((g) => (g.match ? [g.match.id] : []));
const files: string[] = [];
const culprit = !!db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='culprit_analyses'`).get();
db.transaction(() => {
for (const id of uttIds) {
const u = this.store.getUtterance(id);
if (u?.audio_path) files.push(u.audio_path);
for (const t of db.prepare('SELECT audio_path FROM training_samples WHERE utterance_id=?').all(id) as { audio_path: string }[]) files.push(t.audio_path);
db.prepare('DELETE FROM training_samples WHERE utterance_id=?').run(id);
db.prepare('DELETE FROM utterance_imports WHERE id=?').run(id);
db.prepare('DELETE FROM utterances WHERE id=?').run(id);
}
for (const m of matchIds) {
db.prepare('DELETE FROM game_events WHERE match_id=?').run(m);
db.prepare('DELETE FROM rounds WHERE match_id=?').run(m);
if (culprit) db.prepare('DELETE FROM culprit_analyses WHERE match_id=?').run(m);
db.prepare('DELETE FROM matches WHERE id=?').run(m);
}
})();
let removed = 0;
for (const f of files) {
try {
if (fs.existsSync(f)) {
fs.rmSync(f, { force: true });
removed++;
}
} catch (e) {
log.warn(`파일 삭제 실패 ${f}`, e);
}
}
log.info(`기록 묶음 ${groups.length}개 삭제: ${groups.map((g) => g.info.label).join(', ')} (발화 ${uttIds.length}개, 파일 ${removed}개)`);
return { bundles: groups.length, utterances: uttIds.length, files: removed };
}
// ------------------------------------------------------------------ 내보내기
export(ids: string[]): { zip: Buffer; fileName: string } {
const groups = this.pick(ids);
const db = this.store.db;
const uttIds = new Set(groups.flatMap((g) => g.ids));
// 잡음 발화(사람이 고치지 않은 것)는 내보내지 않는다
const utts = [...uttIds].map((id) => this.store.getUtterance(id)!).filter((u) => u && (!u.noise || u.corrected));
const matches = groups.flatMap((g) => (g.match ? [g.match] : []));
const userIds = new Set(utts.map((u) => u.user_id));
const users = this.store.listUsers().filter((u) => userIds.has(u.id));
const accounts = this.store.listAccounts().filter((a) => userIds.has(a.user_id));
const sessIds = [...new Set(utts.map((u) => u.session_id).filter((s): s is string => !!s))];
const sessions = sessIds.map((s) => db.prepare('SELECT * FROM sessions WHERE id=?').get(s)).filter(Boolean);
const culprit = !!db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='culprit_analyses'`).get();
// 받아오기 한도(300MB)보다 크면 다시 넣을 수 없으니 나눠 받게 한다
const total = utts.reduce((n, u) => {
try {
return n + (u.audio_path && !u.audio_deleted ? fs.statSync(u.audio_path).size : 0);
} catch {
return n;
}
}, 0);
if (total > EXPORT_MAX) throw new BundleError(`한 번에 내려받기에는 너무 큽니다 (음성 ${Math.round(total / 1048576)}MB). 받아오기 한도가 ${EXPORT_MAX / 1048576}MB 라서, 묶음을 나눠서 골라 주세요`, 'too_large');
const entries: ZipEntry[] = [];
const outUtts = utts.map((u) => {
const { audio_path, ...rest } = u as UtteranceRow & { rowid?: number };
delete (rest as any).rowid;
let audio: string | null = null;
if (audio_path && !u.audio_deleted && fs.existsSync(audio_path)) {
// zip 안에서도 알아볼 수 있게 녹음 파일 이름 그대로 (날짜 · 시각 · 말한 사람 · 게임 · 라운드 · 발화 ID)
audio = `audio/${path.basename(audio_path)}`;
entries.push({ name: audio, data: fs.readFileSync(audio_path) });
}
return { ...rest, audio };
});
const data = {
users: users.map((u) => ({ id: u.id, name: u.name, color: u.color, avatar: u.avatar, excluded: u.excluded })),
accounts,
sessions,
matches,
rounds: matches.flatMap((m) => this.store.rounds(m.id)),
events: matches.flatMap((m) => this.store.events(m.id)),
culprit: culprit ? matches.flatMap((m) => db.prepare('SELECT * FROM culprit_analyses WHERE match_id=?').all(m.id)) : [],
utterances: outUtts,
};
const manifest = {
format: BUNDLE_FORMAT,
version: BUNDLE_VERSION,
app: this.version,
exportedAt: Date.now(),
bundles: groups.map((g) => g.info),
counts: { utterances: outUtts.length, audio: outUtts.filter((u) => u.audio).length, matches: matches.length, events: data.events.length },
};
const name = (id: string) => users.find((u) => u.id === id)?.name ?? id;
const transcript = groups
.map((g) => {
const head = `■ ${g.info.label}${g.info.sub ? ` (${g.info.sub})` : ''} · ${fmtReal(g.info.from)} ~ ${fmtReal(g.info.to)}`;
const lines = outUtts
.filter((u) => g.ids.includes(u.id) && (!u.noise || u.corrected) && u.text)
.sort((a, b) => a.started_at - b.started_at)
.map((u) => `[${fmtReal(u.started_at)}] ${name(u.user_id)}: ${u.text}`);
return [head, ...lines].join('\r\n');
})
.join('\r\n\r\n');
entries.unshift(
{ name: 'manifest.json', data: Buffer.from(JSON.stringify(manifest, null, 2)) },
{ name: 'data.json', data: Buffer.from(JSON.stringify(data)) },
{ name: '대화.txt', data: Buffer.from('' + transcript + '\r\n', 'utf8') },
{
name: '읽어 주세요.txt',
data: Buffer.from(
'겜녹이 기록 묶음입니다.\r\n사이트(gvr.tkrmagid.kr) → 기록 관리 → "받아오기"로 이 zip 을 그대로 넣으면 기록이 다시 추가됩니다.\r\nmanifest.json · data.json · audio 폴더를 지우거나 고치면 받아오기가 실패합니다.\r\n',
'utf8',
),
},
);
const first = groups.map((g) => g.info.from).sort((a, b) => a - b)[0] ?? Date.now();
const d = new Date(first);
const stamp = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}`;
const kind = groups.length > 1 ? `${groups.length}bundles` : groups[0].info.kind === 'match' ? (groups[0].info.game ?? 'match') : 'talk';
log.info(`기록 묶음 ${groups.length}개 내보내기 (발화 ${outUtts.length}개, 음성 ${manifest.counts.audio}개)`);
return { zip: writeZip(entries), fileName: `gvr-${kind}-${stamp}.zip` };
}
// ------------------------------------------------------------------ 받아오기
import(buf: Buffer): BundleImportResult {
let files: Map<string, Buffer>;
try {
files = readZip(buf, 600 * 1024 * 1024);
} catch (e) {
throw new BundleError(`받아오기 실패: ${e instanceof ZipError ? e.message : 'zip 파일을 읽지 못했습니다'}`);
}
const { manifest, data } = validate(files, this.store);
const db = this.store.db;
const now = Date.now();
const res: BundleImportResult = { bundles: manifest.bundles.map((b: any) => String(b.label ?? b.id)), added: { utterances: 0, audio: 0, matches: 0, events: 0, users: 0 }, skipped: 0 };
const written: string[] = [];
const addedIds: string[] = [];
try {
db.transaction(() => {
for (const u of data.users) {
if (this.store.getUser(u.id)) continue;
db.prepare('INSERT INTO users(id,name,color,avatar,excluded,updated_at) VALUES(?,?,?,?,?,?)').run(u.id, String(u.name ?? u.id), String(u.color ?? '#8696a6'), u.avatar ?? null, u.excluded ? 1 : 0, now);
res.added.users++;
}
for (const a of data.accounts ?? []) if (a?.user_id && a?.puuid && this.store.getUser(a.user_id)) db.prepare('INSERT OR IGNORE INTO game_accounts(user_id,puuid,riot_id) VALUES(?,?,?)').run(a.user_id, a.puuid, String(a.riot_id ?? ''));
for (const s of data.sessions ?? [])
if (s?.id) db.prepare('INSERT OR IGNORE INTO sessions(id,guild_id,channel_id,channel_name,started_at,ended_at) VALUES(?,?,?,?,?,?)').run(s.id, String(s.guild_id ?? ''), String(s.channel_id ?? ''), s.channel_name ?? null, Number(s.started_at) || 0, s.ended_at ?? null);
for (const m of data.matches ?? []) {
const r = db
.prepare('INSERT OR IGNORE INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset) VALUES(?,?,?,?,?,?,?,?,?,?,?)')
.run(m.id, m.game, m.started_at, m.ended_at ?? null, m.map ?? null, m.mode ?? null, m.queue ?? null, m.result ?? null, m.detail ?? null, m.status === 'live' ? 'complete' : (m.status ?? 'complete'), Number(m.clock_offset) || 0);
res.added.matches += r.changes;
}
for (const r of data.rounds ?? [])
db.prepare('INSERT OR IGNORE INTO rounds(match_id,num,started_at,combat_at,ended_at,win,result,ally_score,enemy_score,economy) VALUES(?,?,?,?,?,?,?,?,?,?)').run(
r.match_id, r.num, r.started_at, r.combat_at, r.ended_at, r.win ?? null, r.result ?? null, r.ally_score ?? null, r.enemy_score ?? null, r.economy ?? null,
);
for (const e of data.events ?? []) {
const r = db
.prepare('INSERT OR IGNORE INTO game_events(id,match_id,game,type,ts,game_time_ms,round,actor_puuid,target_puuid,data) VALUES(?,?,?,?,?,?,?,?,?,?)')
.run(e.id, e.match_id, e.game, e.type, e.ts, e.game_time_ms ?? null, e.round ?? null, e.actor_puuid ?? null, e.target_puuid ?? null, typeof e.data === 'string' ? e.data : JSON.stringify(e.data ?? {}));
res.added.events += r.changes;
}
const hasCulprit = !!db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='culprit_analyses'`).get();
if (hasCulprit)
for (const c of data.culprit ?? [])
if (c?.id && c?.match_id)
db.prepare('INSERT OR IGNORE INTO culprit_analyses(id,match_id,created_at,created_by,model,current,result,meta) VALUES(?,?,?,?,?,?,?,?)').run(
c.id, c.match_id, c.created_at, c.created_by, c.model, c.current ?? 1, c.result, c.meta ?? '{}',
);
for (const u of data.utterances) {
if (this.store.getUtterance(u.id)) {
res.skipped++;
continue;
}
let audioPath: string | null = null;
if (u.audio) {
const d = new Date(u.started_at);
const day = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
const dir = path.join(this.audioDir(), day);
fs.mkdirSync(dir, { recursive: true });
audioPath = path.join(dir, `${u.id}.ogg`);
if (!fs.existsSync(audioPath)) {
fs.writeFileSync(audioPath, files.get(u.audio)!);
written.push(audioPath);
}
res.added.audio++;
}
db.prepare(
`INSERT INTO utterances(id,session_id,user_id,started_at,ended_at,audio_path,audio_deleted,text,raw_text,words,noise,noise_reason,confidence,lufs,gain_db,model,status,match_id,corrected,attempts,created_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
).run(
u.id, u.session_id ?? null, u.user_id, u.started_at, u.ended_at, audioPath, audioPath ? 0 : 1, u.text ?? null, u.raw_text ?? null,
typeof u.words === 'string' ? u.words : JSON.stringify(u.words ?? []), u.noise ? 1 : 0, u.noise_reason ?? null, u.confidence ?? null, u.lufs ?? null,
Number(u.gain_db) || 0, u.model ?? null, u.status === 'pending' && !audioPath ? 'failed' : (u.status ?? 'precise'), u.match_id ?? null, u.corrected ? 1 : 0, 0, now,
);
db.prepare('INSERT OR REPLACE INTO utterance_imports(id, imported_at) VALUES(?,?)').run(u.id, now);
res.added.utterances++;
addedIds.push(u.id);
}
})();
} catch (e) {
// DB 에 못 넣었으면 쓴 음성 파일도 지운다
for (const f of written) fs.rmSync(f, { force: true });
throw e instanceof BundleError ? e : new BundleError(`받아오기 실패: 기록을 저장하지 못했습니다 (${(e as Error).message})`, 'import_failed');
}
try {
this.afterImport?.(addedIds);
} catch (e) {
log.warn('받아온 녹음 파일 이름 맞추기 실패', e);
}
log.info(`기록 묶음 받아오기: ${res.bundles.join(', ')} (발화 ${res.added.utterances}개 추가, 음성 ${res.added.audio}개, 이미 있음 ${res.skipped}개)`);
return res;
}
}
const num = (v: unknown) => typeof v === 'number' && isFinite(v);
/** 받아오기 검사: 꼭 필요한 내용이 하나라도 없으면 BundleError (무엇이 빠졌는지 알려 준다) */
export function validate(files: Map<string, Buffer>, store?: Store): { manifest: any; data: any } {
const fail = (why: string): never => {
throw new BundleError(`받아오기 실패: ${why}`);
};
const json = (name: string): any => {
const b = files.get(name);
if (!b) fail(`${name} 이 없습니다 (겜녹이에서 내보낸 기록 zip 이 아닙니다)`);
try {
return JSON.parse(b!.toString('utf8').replace(/^/, ''));
} catch {
return fail(`${name} 을 읽을 수 없습니다 (내용이 깨졌습니다)`);
}
};
const manifest = json('manifest.json');
if (manifest?.format !== BUNDLE_FORMAT) fail('겜녹이 기록 묶음 형식이 아닙니다 (manifest.json 의 format)');
if (!num(manifest.version) || manifest.version > BUNDLE_VERSION) fail(`이 앱이 모르는 묶음 형식 버전입니다 (${manifest.version}). 앱을 업데이트해 주세요`);
if (!Array.isArray(manifest.bundles) || !manifest.bundles.length) fail('묶음 정보(manifest.json 의 bundles)가 없습니다');
const data = json('data.json');
if (!Array.isArray(data?.utterances)) fail('발화 목록(data.json 의 utterances)이 없습니다');
if (!Array.isArray(data.users)) fail('유저 목록(data.json 의 users)이 없습니다');
for (const k of ['matches', 'rounds', 'events', 'sessions', 'accounts', 'culprit']) if (data[k] !== undefined && !Array.isArray(data[k])) fail(`data.json 의 ${k} 가 목록이 아닙니다`);
const userIds = new Set<string>();
for (const u of data.users) {
if (typeof u?.id !== 'string' || !u.id) fail('이름 없는 유저가 있습니다 (data.json 의 users)');
userIds.add(u.id);
}
const matchIds = new Set<string>();
for (const m of data.matches ?? []) {
if (typeof m?.id !== 'string' || !SAFE_ID.test(m.id)) fail('경기 ID 가 잘못되었습니다');
if (m.game !== 'valorant' && m.game !== 'lol') fail(`경기 ${m.id} 의 게임 종류가 없습니다`);
if (!num(m.started_at)) fail(`경기 ${m.id} 의 시작 시각이 없습니다`);
matchIds.add(m.id);
}
for (const b of manifest.bundles) {
if (b?.kind !== 'match' && b?.kind !== 'talk') fail('묶음 종류(match/talk)가 잘못되었습니다');
if (b.kind === 'match' && !matchIds.has(b.matchId)) fail(`경기 묶음 "${b.label ?? b.id}" 의 경기 기록이 data.json 에 없습니다`);
}
for (const e of data.events ?? []) {
if (typeof e?.id !== 'string' || typeof e?.type !== 'string' || !num(e?.ts)) fail('경기 이벤트에 꼭 필요한 값(id · type · ts)이 없습니다');
if (!matchIds.has(e.match_id)) fail(`이벤트 ${e.id} 의 경기(${e.match_id})가 data.json 에 없습니다`);
}
for (const r of data.rounds ?? []) if (!matchIds.has(r?.match_id) || !num(r?.num) || !num(r?.started_at) || !num(r?.combat_at) || !num(r?.ended_at)) fail('라운드 기록에 꼭 필요한 값이 없습니다');
const seen = new Set<string>();
const audioSeen = new Set<string>();
for (const u of data.utterances) {
if (typeof u?.id !== 'string' || !SAFE_ID.test(u.id)) fail('발화 ID 가 잘못되었습니다');
if (seen.has(u.id)) fail(`발화 ${u.id} 가 두 번 들어 있습니다`);
seen.add(u.id);
if (typeof u.user_id !== 'string' || !u.user_id) fail(`발화 ${u.id} 에 말한 사람이 없습니다`);
if (!userIds.has(u.user_id) && !store?.getUser(u.user_id)) fail(`발화 ${u.id} 의 말한 사람(${u.user_id})이 유저 목록에 없습니다`);
if (!num(u.started_at) || !num(u.ended_at) || u.ended_at < u.started_at) fail(`발화 ${u.id} 의 시각이 잘못되었습니다`);
if (u.match_id && !matchIds.has(u.match_id) && !store?.getMatch(u.match_id)) fail(`발화 ${u.id} 의 경기(${u.match_id})가 없습니다`);
if (u.audio) {
// v1.3.7: audio/<발화ID>.ogg, v1.3.8~: audio/<날짜_시각_말한사람_…_발화ID>.ogg
// zip 안 이름은 zip 에서 꺼낼 때 찾는 열쇠로만 쓴다 (이 PC 에 쓸 경로는 발화 ID 로 만든다). 폴더 구분자만 막으면 상위 폴더로 갈 수 없다.
// 이름 안의 ".." (예: 표시 이름 "하늘..별")은 정상 이름이다
if (typeof u.audio !== 'string' || !/^audio\/[^/\\]{1,200}\.ogg$/.test(u.audio)) fail(`발화 ${u.id} 의 음성 파일 이름이 잘못되었습니다`);
if (audioSeen.has(u.audio)) fail(`음성 파일 ${u.audio} 를 두 발화가 같이 씁니다`);
audioSeen.add(u.audio);
const a = files.get(u.audio);
if (!a) fail(`음성 파일 ${u.audio} 가 zip 안에 없습니다`);
if (a!.length < 4 || a!.toString('ascii', 0, 4) !== 'OggS') fail(`음성 파일 ${u.audio} 가 ogg 가 아닙니다`);
}
}
if (!data.utterances.length && !matchIds.size) fail('넣을 발화 · 경기가 하나도 없습니다');
const c = manifest.counts;
if (c && num(c.utterances) && c.utterances !== data.utterances.length) fail(`발화 수가 맞지 않습니다 (manifest ${c.utterances}개, data ${data.utterances.length}개). zip 이 잘렸거나 고쳐졌습니다`);
return { manifest, data };
}

View File

@@ -146,7 +146,8 @@ export class Culprit {
this.store.db.prepare('UPDATE culprit_analyses SET current=0 WHERE match_id=?').run(matchId);
this.store.db
.prepare('INSERT OR REPLACE INTO culprit_analyses(id,match_id,created_at,created_by,model,current,result,meta) VALUES(?,?,?,?,?,1,?,?)')
.run(id, matchId, a.createdAt, JSON.stringify(a.createdBy), a.model, JSON.stringify({ result: a.result, players: a.players }), JSON.stringify(a.meta));
// 표시 이름(실명 숨기기)을 정하기 전에 시작한 분석이 뒤늦게 와도 예전 이름이 남지 않게 저장할 때 바꾼다
.run(id, matchId, a.createdAt, JSON.stringify(this.store.scrubCreatedBy(a.createdBy)), a.model, this.store.scrubNames(JSON.stringify({ result: a.result, players: a.players })), JSON.stringify(a.meta));
});
tx();
return this.current(matchId)!;

View File

@@ -87,6 +87,35 @@ export interface DictRow {
created_at: number;
}
export interface NoisePhraseRow {
id: number;
phrase: string;
sample: string;
hits: number;
created_at: number;
}
/** 잡음 문장 비교용: 띄어쓰기 · 문장부호 · 기호를 빼고 소문자로 (워커 noise.normalize 와 같은 규칙) */
export function normalizePhrase(text: string | null | undefined): string {
return String(text ?? '')
.replace(/[^\p{L}\p{N}\p{M}]+/gu, '')
.toLowerCase();
}
/**
* 거의 같은 문장인가: 글자 수가 같고(8글자 이상) 다른 글자가 15% 이하 (글자 바뀜만).
* Whisper 는 같은 잡음 · 같은 녹음에서도 한두 글자를 다르게 낸다 ("레이드 공" / "레이드 궁").
* 글자가 더 붙거나 빠지면 다른 말로 본다: 배운 문장 앞뒤에 실제 말("네", "가자")이 붙은 발화는 지우지 않는다
*/
export function similarPhrase(a: string, b: string): boolean {
const A = [...a];
const B = [...b];
if (A.length !== B.length || A.length < 8) return false;
let diff = 0;
for (let i = 0; i < A.length; i++) if (A[i] !== B[i]) diff++;
return diff <= Math.floor(A.length * 0.15);
}
export class Store {
readonly db: Database.Database;
@@ -126,6 +155,7 @@ export class Store {
ON CONFLICT(id) DO UPDATE SET name=excluded.name, avatar=excluded.avatar, updated_at=excluded.updated_at`,
)
.run(u.id, this.displayNames()[u.id] ?? u.name, colorFor(u.id), u.avatar, now);
this.rememberHidden(u.id, u.name);
return this.getUser(u.id)!;
}
@@ -141,6 +171,38 @@ export class Store {
}
return this.names!;
}
/** 표시 이름으로 가린 예전 이름들 (아이디 → 디스코드에서 받은 이름들). 범인 분석 본문 등 글 속 이름을 바꿀 때 쓴다 */
private hiddenNames(): Record<string, string[]> {
try {
return JSON.parse(this.meta('hidden_names') || '{}');
} catch {
return {};
}
}
private rememberHidden(id: string, old: string): void {
const name = this.displayNames()[id];
if (!name || old === name || old.trim().length < 2) return;
const h = this.hiddenNames();
if (h[id]?.includes(old)) return;
(h[id] ||= []).push(old);
this.setMeta('hidden_names', JSON.stringify(h));
}
/** 글(JSON 문자열 포함) 속 예전 이름을 표시 이름으로 바꾼다. 긴 이름부터 (짧은 이름이 긴 이름의 일부일 수 있어서) */
scrubNames(text: string): string {
const names = this.displayNames();
const pairs: [string, string][] = [];
for (const [id, olds] of Object.entries(this.hiddenNames())) if (names[id]) for (const o of olds) pairs.push([o, names[id]]);
pairs.sort((x, y) => y[0].length - x[0].length);
const j = (x: string) => JSON.stringify(x).slice(1, -1);
for (const [o, n] of pairs) text = text.split(j(o)).join(j(n));
return text;
}
/** 분석을 만든 사람 { id, name }: 표시 이름이 있으면 그것으로 */
scrubCreatedBy<T extends { id?: string; name?: string }>(by: T): T {
const n = by?.id ? this.displayNames()[by.id] : undefined;
if (n && by.name && by.name !== n) this.rememberHidden(by.id!, by.name);
return n ? { ...by, name: n } : by;
}
/** 새 표시 이름을 저장하고, 이미 저장된 유저 이름 · 지난 범인 분석에 남은 예전 이름도 바꾼다 */
setDisplayNames(map: Record<string, string>): void {
const names: Record<string, string> = {};
@@ -148,23 +210,25 @@ export class Store {
this.names = names;
this.setMeta('display_names', JSON.stringify(names));
const culprit = !!this.db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='culprit_analyses'`).get();
const j = (x: string) => JSON.stringify(x).slice(1, -1);
this.db.transaction(() => {
for (const [id, name] of Object.entries(names)) {
const u = this.getUser(id);
if (!u || u.name === name) continue;
this.rememberHidden(id, u.name);
this.db.prepare('UPDATE users SET name=? WHERE id=?').run(name, id);
if (culprit && u.name.length >= 2) this.db.prepare('UPDATE culprit_analyses SET result=replace(result,?,?)').run(j(u.name), j(name));
}
if (!culprit) return;
for (const r of this.db.prepare('SELECT id, created_by FROM culprit_analyses').all() as { id: string; created_by: string }[]) {
// 건너뛰지 않고 매번 모든 분석을 다시 훑는다 (이름을 바꾸기 전에 시작한 분석이 뒤늦게 저장된 경우도 고친다)
for (const r of this.db.prepare('SELECT id, created_by, result FROM culprit_analyses').all() as { id: string; created_by: string; result: string }[]) {
let by: any;
try {
by = JSON.parse(r.created_by);
} catch {
continue;
by = null;
}
if (by?.id && names[by.id] && by.name !== names[by.id]) this.db.prepare('UPDATE culprit_analyses SET created_by=? WHERE id=?').run(JSON.stringify({ ...by, name: names[by.id] }), r.id);
const createdBy = by ? JSON.stringify(this.scrubCreatedBy(by)) : r.created_by;
const result = this.scrubNames(r.result);
if (createdBy !== r.created_by || result !== r.result) this.db.prepare('UPDATE culprit_analyses SET created_by=?, result=? WHERE id=?').run(createdBy, result, r.id);
}
})();
}
@@ -284,8 +348,20 @@ export class Store {
/** 보관 기간 지난 음성 파일 목록 */
expiredAudio(before: number): { id: string; audio_path: string }[] {
return this.db
.prepare('SELECT id, audio_path FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND started_at<?')
.all(before) as any[];
.prepare(
`SELECT id, audio_path FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND started_at<?
AND NOT EXISTS (SELECT 1 FROM utterance_imports i WHERE i.id=utterances.id AND i.imported_at>=?)`,
)
.all(before, 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);
@@ -435,9 +511,46 @@ export class Store {
this.db.prepare('DELETE FROM training_samples').run();
}
// ---------------------------------------------------------------- 발화 지우기 · 잡음으로 배운 문장 (v1.4.0)
/** 발화 하나를 지운다 (교정 학습 데이터 포함). 지울 파일 경로를 돌려준다 */
deleteUtterance(id: string): string[] {
const files: string[] = [];
this.db.transaction(() => {
const u = this.getUtterance(id);
if (!u) return;
if (u.audio_path && !u.audio_deleted) files.push(u.audio_path);
for (const t of this.db.prepare('SELECT audio_path FROM training_samples WHERE utterance_id=?').all(id) as { audio_path: string }[]) files.push(t.audio_path);
this.db.prepare('DELETE FROM training_samples WHERE utterance_id=?').run(id);
this.db.prepare('DELETE FROM utterance_imports WHERE id=?').run(id);
this.db.prepare('DELETE FROM utterances WHERE id=?').run(id);
})();
return files;
}
/** 잡음 문장 배우기. phrase 는 normalizePhrase 를 거친 값 */
addNoisePhrase(phrase: string, sample: string): void {
this.db
.prepare('INSERT INTO noise_phrases(phrase,sample,created_at) VALUES(?,?,?) ON CONFLICT(phrase) DO UPDATE SET sample=excluded.sample')
.run(phrase, sample, Date.now());
}
listNoisePhrases(): NoisePhraseRow[] {
return this.db.prepare('SELECT * FROM noise_phrases ORDER BY created_at DESC').all() as NoisePhraseRow[];
}
deleteNoisePhrase(id: number): boolean {
return this.db.prepare('DELETE FROM noise_phrases WHERE id=?').run(id).changes > 0;
}
/** 배운 잡음 문장과 같거나 거의 같으면 true (맞힌 횟수를 센다). phrase 는 normalizePhrase 를 거친 값 */
hitNoisePhrase(phrase: string): boolean {
if (!phrase) return false;
const rows = this.db.prepare('SELECT id, phrase FROM noise_phrases').all() as { id: number; phrase: string }[];
const hit = rows.find((r) => r.phrase === phrase) ?? rows.find((r) => similarPhrase(r.phrase, phrase));
if (!hit) return false;
this.db.prepare('UPDATE noise_phrases SET hits=hits+1 WHERE id=?').run(hit.id);
return true;
}
// ---------------------------------------------------------------- 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 };
}

View File

@@ -136,3 +136,18 @@ CREATE TABLE IF NOT EXISTS training_samples (
used INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
-- 받아오기(zip)로 넣은 발화: 보관 기간은 녹음 날짜가 아니라 받아온 날부터 센다
CREATE TABLE IF NOT EXISTS utterance_imports (
id TEXT PRIMARY KEY,
imported_at INTEGER NOT NULL
);
-- 사이트에서 "잡음이라 삭제"한 문장 (v1.4.0). 같은 문장(띄어쓰기 · 문장부호 무시, 긴 문장은 글자 한두 개 바뀐 것까지)이 다시 인식되면 잡음으로 본다
CREATE TABLE IF NOT EXISTS noise_phrases (
id INTEGER PRIMARY KEY AUTOINCREMENT,
phrase TEXT NOT NULL UNIQUE,
sample TEXT NOT NULL,
hits INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);

View File

@@ -1,2 +1,2 @@
// 자동 생성: schema.sql 사본 (npm run build 가 다시 만든다)
export const SCHEMA_SQL = "PRAGMA journal_mode = WAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);\n\nCREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n color TEXT NOT NULL,\n avatar TEXT,\n excluded INTEGER NOT NULL DEFAULT 0,\n gain_lufs REAL,\n gain_n INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS game_accounts (\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n puuid TEXT NOT NULL,\n riot_id TEXT NOT NULL,\n PRIMARY KEY (user_id, puuid)\n);\nCREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);\n\nCREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n guild_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n channel_name TEXT,\n started_at INTEGER NOT NULL,\n ended_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS utterances (\n id TEXT PRIMARY KEY,\n session_id TEXT,\n user_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n audio_path TEXT,\n audio_deleted INTEGER NOT NULL DEFAULT 0,\n text TEXT,\n raw_text TEXT,\n words TEXT NOT NULL DEFAULT '[]',\n noise INTEGER NOT NULL DEFAULT 0,\n noise_reason TEXT,\n confidence REAL,\n lufs REAL,\n gain_db REAL NOT NULL DEFAULT 0,\n model TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n match_id TEXT,\n corrected INTEGER NOT NULL DEFAULT 0,\n attempts INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);\nCREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');\nCREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\n\nCREATE TABLE IF NOT EXISTS matches (\n id TEXT PRIMARY KEY,\n game TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER,\n map TEXT,\n mode TEXT,\n queue TEXT,\n result TEXT,\n detail TEXT,\n status TEXT NOT NULL DEFAULT 'live',\n clock_offset INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);\n\nCREATE TABLE IF NOT EXISTS rounds (\n match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,\n num INTEGER NOT NULL,\n started_at INTEGER NOT NULL,\n combat_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n win INTEGER,\n result TEXT,\n ally_score INTEGER,\n enemy_score INTEGER,\n economy TEXT,\n PRIMARY KEY (match_id, num)\n);\n\nCREATE TABLE IF NOT EXISTS game_events (\n id TEXT PRIMARY KEY,\n match_id TEXT NOT NULL,\n game TEXT NOT NULL,\n type TEXT NOT NULL,\n ts INTEGER NOT NULL,\n game_time_ms INTEGER,\n round INTEGER,\n actor_puuid TEXT,\n target_puuid TEXT,\n data TEXT NOT NULL DEFAULT '{}'\n);\nCREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);\nCREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);\n\nCREATE TABLE IF NOT EXISTS dictionary (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n word TEXT NOT NULL,\n pack TEXT NOT NULL,\n kind TEXT NOT NULL,\n from_text TEXT NOT NULL DEFAULT '',\n source TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n UNIQUE (kind, word, from_text, pack)\n);\n\nCREATE TABLE IF NOT EXISTS training_samples (\n id TEXT PRIMARY KEY,\n utterance_id TEXT,\n text TEXT NOT NULL,\n audio_path TEXT NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n";
export const SCHEMA_SQL = "PRAGMA journal_mode = WAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);\n\nCREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n color TEXT NOT NULL,\n avatar TEXT,\n excluded INTEGER NOT NULL DEFAULT 0,\n gain_lufs REAL,\n gain_n INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS game_accounts (\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n puuid TEXT NOT NULL,\n riot_id TEXT NOT NULL,\n PRIMARY KEY (user_id, puuid)\n);\nCREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);\n\nCREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n guild_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n channel_name TEXT,\n started_at INTEGER NOT NULL,\n ended_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS utterances (\n id TEXT PRIMARY KEY,\n session_id TEXT,\n user_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n audio_path TEXT,\n audio_deleted INTEGER NOT NULL DEFAULT 0,\n text TEXT,\n raw_text TEXT,\n words TEXT NOT NULL DEFAULT '[]',\n noise INTEGER NOT NULL DEFAULT 0,\n noise_reason TEXT,\n confidence REAL,\n lufs REAL,\n gain_db REAL NOT NULL DEFAULT 0,\n model TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n match_id TEXT,\n corrected INTEGER NOT NULL DEFAULT 0,\n attempts INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);\nCREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');\nCREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\n\nCREATE TABLE IF NOT EXISTS matches (\n id TEXT PRIMARY KEY,\n game TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER,\n map TEXT,\n mode TEXT,\n queue TEXT,\n result TEXT,\n detail TEXT,\n status TEXT NOT NULL DEFAULT 'live',\n clock_offset INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);\n\nCREATE TABLE IF NOT EXISTS rounds (\n match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,\n num INTEGER NOT NULL,\n started_at INTEGER NOT NULL,\n combat_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n win INTEGER,\n result TEXT,\n ally_score INTEGER,\n enemy_score INTEGER,\n economy TEXT,\n PRIMARY KEY (match_id, num)\n);\n\nCREATE TABLE IF NOT EXISTS game_events (\n id TEXT PRIMARY KEY,\n match_id TEXT NOT NULL,\n game TEXT NOT NULL,\n type TEXT NOT NULL,\n ts INTEGER NOT NULL,\n game_time_ms INTEGER,\n round INTEGER,\n actor_puuid TEXT,\n target_puuid TEXT,\n data TEXT NOT NULL DEFAULT '{}'\n);\nCREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);\nCREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);\n\nCREATE TABLE IF NOT EXISTS dictionary (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n word TEXT NOT NULL,\n pack TEXT NOT NULL,\n kind TEXT NOT NULL,\n from_text TEXT NOT NULL DEFAULT '',\n source TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n UNIQUE (kind, word, from_text, pack)\n);\n\nCREATE TABLE IF NOT EXISTS training_samples (\n id TEXT PRIMARY KEY,\n utterance_id TEXT,\n text TEXT NOT NULL,\n audio_path TEXT NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\n-- 받아오기(zip)로 넣은 발화: 보관 기간은 녹음 날짜가 아니라 받아온 날부터 센다\nCREATE TABLE IF NOT EXISTS utterance_imports (\n id TEXT PRIMARY KEY,\n imported_at INTEGER NOT NULL\n);\n\n-- 사이트에서 \"잡음이라 삭제\"한 문장 (v1.4.0). 같은 문장(띄어쓰기 · 문장부호 무시, 긴 문장은 글자 한두 개 바뀐 것까지)이 다시 인식되면 잡음으로 본다\nCREATE TABLE IF NOT EXISTS noise_phrases (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n phrase TEXT NOT NULL UNIQUE,\n sample TEXT NOT NULL,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n";

View File

@@ -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) {

View File

@@ -4,7 +4,7 @@
// 음성채널에 들어갈 때 서버가 디스코드에서 받은 일회용 음성 접속 정보를 넘겨주고, 음성은 이 PC ↔ 디스코드로 바로 간다
import type { DiscordGatewayAdapterCreator, DiscordGatewayAdapterLibraryMethods } from '@discordjs/voice';
import type { BotGwChannel, BotGwFromApp, BotGwGuild, BotGwMember, BotGwToApp } from '@gvr/shared';
import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
import { ActivityType, ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
import { EventEmitter } from 'node:events';
import WebSocket from 'ws';
import { logger } from '../util/log.js';
@@ -70,14 +70,34 @@ export class LocalGateway extends EventEmitter implements BotGateway {
super();
}
/** 봇 상태 메시지: 음성채널에 있으면(= 녹음 중) 빨간 "녹음 중" (겜녹이 봇은 사이트 서버가 같은 일을 한다) */
private recording: boolean | null = null;
private updatePresence(): void {
const c = this.client;
if (!c?.isReady()) return;
const on = c.guilds.cache.some((g) => !!g.members.me?.voice.channelId);
if (on === this.recording) return;
this.recording = on;
c.user.setPresence(
on
? { status: 'dnd', activities: [{ type: ActivityType.Custom, name: 'custom', state: '🔴 녹음 중' }] }
: { status: 'online', activities: [{ type: ActivityType.Custom, name: 'custom', state: '🎙️ 대기 중 · /녹음시작' }] },
);
}
async start(): Promise<void> {
const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers] });
this.client = c;
c.on(Events.ClientReady, () => this.emit('ready'));
this.recording = null;
c.on(Events.ClientReady, () => {
this.updatePresence();
this.emit('ready');
});
c.on(Events.GuildCreate, () => this.emit('guilds'));
c.on(Events.GuildDelete, () => this.emit('guilds'));
c.on(Events.Error, (e) => log.error('discord 오류', e));
c.on(Events.VoiceStateUpdate, (o, n) => {
if (n.id === c.user?.id) this.updatePresence();
const m = n.member ?? o.member;
if (!m) return;
const ch = n.channel;
@@ -351,8 +371,17 @@ export class RemoteGateway extends EventEmitter implements BotGateway {
// 이 유저가 가입하지 않은 서버
if (this.watched?.id !== m.guildId) return;
log.warn('이 디스코드 서버에 가입되어 있지 않아 녹음할 수 없습니다');
this.wait?.resolve(null);
this.wait = null;
if (this.wait) {
this.wait.resolve(null);
this.wait = null;
return;
}
// 지켜보던 중에 서버가 권한을 다시 확인하다 끊은 경우: 그대로 두면 슬래시 명령 · 음성 상태가 영영 안 오므로 1분 뒤 다시 요청한다
// (정말 탈퇴했으면 다시 거절될 뿐이다)
setTimeout(() => {
const w = this.watched;
if (w?.id === m.guildId && !this.wait) this.send({ t: 'watch', guildId: w.id, commands: w.commands });
}, 60000).unref();
return;
case 'voiceState':
if (this.watched?.id !== m.guildId) return;

View File

@@ -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;
}

View File

@@ -19,14 +19,59 @@ export interface RecorderOptions {
skip: (userId: string) => boolean;
/** ts 시점 진행 중인 경기 ID */
matchAt: (ts: number) => string | null;
/** 저장 직후 (녹음 파일 이름을 날짜 · 말한 사람 · 게임 · 라운드로 바꾼다) */
onSaved?: (id: string) => void;
}
/** 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 +81,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 +135,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 +174,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);
}
@@ -131,7 +200,7 @@ export class Recorder {
}
const endedAt = u.startedAt + dur;
const matchId = this.opts.matchAt(u.startedAt);
const row = this.store.insertUtterance({
let row = this.store.insertUtterance({
id: u.id,
session_id: this.sessionId,
user_id: userId,
@@ -140,6 +209,12 @@ export class Recorder {
audio_path: u.writer.path,
match_id: matchId,
});
try {
this.opts.onSaved?.(row.id);
row = this.store.getUtterance(row.id) ?? row;
} catch (e) {
log.warn('녹음 파일 이름 바꾸기 실패', e);
}
this.bus.live({ type: 'utterance.created', data: this.timeline.utteranceItem(row) });
this.stt.enqueue(row.id, 'realtime');
log.debug(`발화 저장 ${userId} ${dur}ms ${u.writer.bytes}B`);

View File

@@ -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);

View File

@@ -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);
}

View File

@@ -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,12 +11,20 @@ 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');
/** 게임 어댑터들을 묶고, 경기 시작·종료를 녹음/STT/타임라인에 반영한다 */
export class GameManager implements AdapterHost {
adapters: GameAdapter[];
/** 경기 정보가 바뀌어 녹음 파일 이름을 다시 맞출 때 (경기 끝 · 경기 상세 적용) */
onMatchFiles: ((matchId: string) => void) | null = null;
/** 진행 중인 발로란트 경기의 지금 라운드 (경기 중 녹음 파일 이름용) */
liveRound(matchId: string): number | null {
return this.live().find((g) => g.matchId === matchId && g.inMatch)?.round ?? null;
}
constructor(
readonly store: Store,
@@ -38,12 +46,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 +62,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);
@@ -84,6 +114,7 @@ export class GameManager implements AdapterHost {
const n = this.store.assignMatch(id, m.started_at + m.clock_offset - 2000, (m.ended_at ?? Date.now()) + 1000);
log.info(`경기 ${id}: 발화 ${n}개 연결`);
this.bus.live({ type: 'users.updated', data: [] });
this.onMatchFiles?.(id);
}
this.emitMatch(id);
}
@@ -94,7 +125,7 @@ export class GameManager implements AdapterHost {
this.store.upsertMatch({ id, game: cur.game, started_at: cur.started_at, ended_at: endedAt, status: 'pending_detail' });
this.store.assignMatch(id, cur.started_at, endedAt);
this.timeline.invalidate(id);
void this.stt.onMatchEnd(cur.started_at, endedAt);
void this.stt.onMatchEnd(cur.started_at, endedAt).finally(() => this.onMatchFiles?.(id));
this.emitMatch(id);
}
@@ -110,6 +141,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 +192,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 ?? '리그 오브 레전드');
}

View 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());
}

View File

@@ -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;
}

View File

@@ -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 },
},
};
}

View File

@@ -1,7 +1,9 @@
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 { Bundles } from './bundles.js';
import { AudioNamer } from './audio-names.js';
import { Culprit } from './culprit.js';
import { Store } from './db/db.js';
import { Dictionary } from './dict/dictionary.js';
@@ -52,6 +54,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();
@@ -63,6 +69,7 @@ export async function startCore(opts: CoreOptions) {
const stt = new SttPipeline(worker, store, dict, timeline, bus, S);
const assets = new GameAssets(path.join(opts.dataDir, 'cache'));
const games = new GameManager(store, assets, worker, stt, timeline, bus, S, () => S().discord.followUserId);
const audioNames = new AudioNamer(store, games, (id) => stt.isBusy(id));
const recorder: Recorder = new Recorder(store, stt, timeline, bus, {
audioDir: () => paths().audio,
silenceMs: () => S().audio.silenceMs,
@@ -74,8 +81,11 @@ export async function startCore(opts: CoreOptions) {
return process.env.GVR_RECORD_BOTS !== '1' && bot.isBot(uid);
},
matchAt: (ts) => games.liveMatchAt(ts),
onSaved: (id) => audioNames.refresh(id),
});
const announcer = new Announcer(paths().tts, opts.resourcesDir, async (src, dst, tempo) => {
await worker.request('tempo', { src, dst, tempo }, 120000);
});
const announcer = new Announcer(paths().tts, opts.resourcesDir);
const bot: Bot = new Bot(store, recorder, announcer, bus, S, (gid) => {
if (!S().discord.guildId) settings.update({ discord: { guildId: gid } });
});
@@ -91,6 +101,7 @@ export async function startCore(opts: CoreOptions) {
settings: S,
trainingDir: () => paths().training,
version: opts.version,
bundles: new Bundles(store, games, () => paths().audio, opts.version, (ids) => ids.forEach((id) => audioNames.refresh(id))),
overviewExtra: () => ({
guild: bot.state.guild,
recording: {
@@ -115,6 +126,15 @@ export async function startCore(opts: CoreOptions) {
worker.start();
stt.resumePending();
games.start();
// 녹음 파일 이름 (날짜 · 시각 · 말한 사람 · 게임 · 라운드): 변환이 끝난 발화, 경기가 끝난 경기, 시작할 때 전체를 맞춘다
stt.onDone = (id) => audioNames.refresh(id);
games.onMatchFiles = (id) => audioNames.refreshMatch(id);
const renameAll = () => {
const before = stt.repairPendingBefore();
audioNames.refreshAll(before ? (u) => u.created_at < before : undefined);
};
stt.onRepairDone = renameAll;
renameAll();
void assets.refresh().then(() => dict.syncGameNames(assets.names())).catch(() => undefined);
retention.start();
relay.start();
@@ -168,5 +188,5 @@ export async function startCore(opts: CoreOptions) {
store.close();
};
return { settings, store, bus, timeline, dict, worker, stt, assets, games, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir };
return { settings, store, bus, timeline, dict, worker, stt, assets, games, audioNames, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir };
}

View File

@@ -6,6 +6,9 @@ import { logger } from '../util/log.js';
import { secureFetch, TLS_TRUST } from '../util/secure-http.js';
import { secureServerUrl, wsUrl } from '../util/secure-url.js';
/** 바이너리 한 조각 (서버 · 앱 모두 메시지 크기 제한보다 작게) */
const RELAY_CHUNK = 1024 * 1024;
const log = logger('relay');
export interface RelayStatus {
@@ -89,7 +92,9 @@ export class RelayClient {
}, 5000);
});
ws.on('message', (data, isBinary) => {
if (isBinary) return;
// 큰 zip 을 받는 동안에는 pong 이 조각 뒤에 밀린다. 무엇이든 받으면 살아 있는 것으로 본다
this.lastPong = Date.now();
if (isBinary) return this.onBinary(data as Buffer);
let msg: RelayToDevice;
try {
msg = JSON.parse(String(data));
@@ -124,28 +129,51 @@ export class RelayClient {
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(m));
}
/** 사이트 서버가 보낸 요청 본문 조각 (zip 받아오기): [id 길이 4바이트][id][조각] */
private bodyChunks = new Map<string, { chunks: Buffer[]; at: number }>();
private onBinary(buf: Buffer): void {
if (buf.length < 4) return;
const n = buf.readUInt32BE(0);
const id = buf.subarray(4, 4 + n).toString('utf8');
const cur = this.bodyChunks.get(id) ?? { chunks: [], at: Date.now() };
cur.chunks.push(Buffer.from(buf.subarray(4 + n)));
this.bodyChunks.set(id, cur);
// 끝내 요청이 오지 않은 조각은 10분 뒤 버린다
for (const [k, v] of this.bodyChunks) if (Date.now() - v.at > 10 * 60000) this.bodyChunks.delete(k);
}
private async handle(req: Extract<RelayToDevice, { t: 'req' }>): Promise<void> {
const bin = req.bin ? Buffer.concat(this.bodyChunks.get(req.id)?.chunks ?? []) : null;
this.bodyChunks.delete(req.id);
if (!req.path.startsWith('/api/')) {
this.send({ t: 'res', id: req.id, status: 403, headers: { 'content-type': 'application/json' }, body: '{"error":"forbidden"}' });
return;
}
try {
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept', 'x-gvr-internal']) if (req.headers[k]) headers[k] = req.headers[k];
for (const k of ['range', 'content-type', 'accept', 'x-gvr-internal', 'x-gvr-role']) if (req.headers[k]) headers[k] = req.headers[k];
if (req.user) headers['x-gvr-user'] = encodeURIComponent(JSON.stringify(req.user));
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: req.body ?? undefined });
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: bin ?? req.body ?? undefined });
const outHeaders: Record<string, string> = {};
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length']) {
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length', 'content-disposition']) {
const v = res.headers[k];
if (v !== undefined) outHeaders[k] = String(v);
}
const ct = outHeaders['content-type'] || '';
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream')) {
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream') || ct.startsWith('application/zip')) {
this.send({ t: 'res_head', id: req.id, status: res.statusCode, headers: outHeaders });
const idBuf = Buffer.from(req.id, 'utf8');
const head = Buffer.alloc(4);
head.writeUInt32BE(idBuf.length, 0);
this.ws?.send(Buffer.concat([head, idBuf, res.rawPayload]), { binary: true });
// 사이트 서버는 한 메시지에 16MB 까지만 받는다. 1MB 씩 나눠 보낸다 (zip 내보내기)
const raw = res.rawPayload;
const ws = this.ws;
for (let i = 0; i < raw.length || i === 0; i += RELAY_CHUNK) {
// 보낼 것이 4MB 넘게 쌓이면 잠깐 기다린다 (ping 이 밀려 연결이 끊기지 않게)
while (ws && ws.readyState === WebSocket.OPEN && ws.bufferedAmount > 4 * RELAY_CHUNK) await new Promise((r) => setTimeout(r, 20));
if (!ws || ws.readyState !== WebSocket.OPEN) break;
ws.send(Buffer.concat([head, idBuf, raw.subarray(i, i + RELAY_CHUNK)]), { binary: true });
}
this.send({ t: 'res_end', id: req.id });
} else {
this.send({ t: 'res', id: req.id, status: res.statusCode, headers: outHeaders, body: res.payload });

View File

@@ -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,

View File

@@ -1,20 +1,31 @@
import fs from 'node:fs';
import type { Store, UtteranceRow } from '../db/db.js';
import { normalizePhrase, type Store, type UtteranceRow } from '../db/db.js';
import type { Dictionary, DictContext } from '../dict/dictionary.js';
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: '같은 말만 반복',
learned: '잡음으로 배운 문장',
};
type Slot = 'realtime' | 'precise';
interface Job {
id: string;
slot: Slot;
/** 낮을수록 먼저 */
prio: number;
/** 예전 녹음 고친 뒤 다시 변환: 잡음으로 나오면 이전 결과를 지키고, 정밀 결과로만 덮는다 */
repair?: boolean;
}
export interface SttStatus {
@@ -36,6 +47,22 @@ export class SttPipeline {
private queued = new Set<string>();
private busy = false;
private processing: string | null = null;
/** 한 발화의 변환이 끝났을 때 (녹음 파일 이름 맞추기) */
onDone: ((id: string) => void) | null = null;
/** 예전 녹음 고치기가 끝났을 때 */
onRepairDone: (() => void) | null = null;
/** 이 발화를 변환 중이거나 대기열에 있는가 (그동안은 파일 이름을 바꾸지 않는다) */
isBusy(id: string): boolean {
return this.processing === id || this.queued.has(`realtime:${id}`) || this.queued.has(`precise:${id}`);
}
/** 예전 녹음 고치기가 아직 남았는가 (끝나기 전에는 그 녹음들의 이름을 바꾸지 않는다) */
repairPendingBefore(): number | null {
if (this.store.meta('audio_repair_v136')) return null;
const c = this.store.meta('audio_repair_v136_before');
return c ? Number(c) : null;
}
private inMatch = false;
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
private bothFit = true;
@@ -132,16 +159,18 @@ 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);
}
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10): void {
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10, repair = false): void {
const key = `${slot}:${id}`;
if (this.queued.has(key)) return;
this.queued.add(key);
this.queue.push({ id, slot, prio });
this.queue.push({ id, slot, prio, ...(repair ? { repair } : {}) });
this.queue.sort((a, b) => a.prio - b.prio);
this.status.queue = this.queue.length;
this.pump();
@@ -190,6 +219,11 @@ export class SttPipeline {
this.busy = false;
this.processing = null;
this.status.processing = null;
try {
if (!this.isBusy(job.id)) this.onDone?.(job.id);
} catch (e) {
log.warn('변환 뒤 처리 실패', e);
}
setImmediate(() => this.pump());
});
}
@@ -224,7 +258,7 @@ export class SttPipeline {
this.store.markUtteranceFailed(u.id);
return;
}
if (job.slot === 'precise' && (u.corrected || u.status === 'precise')) return;
if (job.slot === 'precise' && (u.corrected || (u.status === 'precise' && !job.repair))) return;
const s = this.settings();
const ctx = this.dictContext(u);
const user = this.store.getUser(u.user_id);
@@ -258,6 +292,16 @@ export class SttPipeline {
} else this.enqueue(u.id, job.slot, job.prio + 2);
return;
}
// 변환하는 동안 사이트에서 지운 발화: 결과를 버린다
if (!this.store.getUtterance(u.id)) return;
// 사이트에서 "잡음이라 삭제"한 문장과 같으면 잡음으로 (v1.4.0)
if (!r.noise && this.store.hitNoisePhrase(normalizePhrase(r.raw_text ?? r.text))) {
r = { ...r, noise: true, noise_reason: 'learned', text: null, words: [] };
}
if (job.repair && r.noise) {
log.info(`예전 녹음 다시 변환: ${u.id} 는 잡음으로 나와 이전 결과를 그대로 둠`);
return;
}
this.store.updateUtteranceResult(u.id, {
text: r.text,
raw_text: r.raw_text,
@@ -270,11 +314,91 @@ 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 || this.queued.has(`precise:${u.id}`)) && 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';
const CUT = 'audio_repair_v136_before';
if (this.store.meta(KEY)) return;
// 이 시각 전에 만든 녹음만 고친다 (새 녹음기는 진짜 쉼만 채우므로 건드리면 안 됨). 중간에 꺼져도 다음에 이어서
if (!this.store.meta(CUT)) this.store.setMeta(CUT, String(Date.now()));
const before = Number(this.store.meta(CUT));
const rows = this.store.db
.prepare(`SELECT rowid,* FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND noise=0 AND created_at<? ORDER BY started_at`)
.all(before) as UtteranceRow[];
let fixed = 0;
let i = 0;
// 한 번에 20개씩 (시작할 때 화면 · 녹음이 멈추지 않게)
const step = () => {
for (const u of rows.slice(i, i + 20)) {
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, 'precise', 20, true);
} catch (e) {
log.warn(`예전 녹음 고치기 실패 ${u.id}`, e);
}
}
i += 20;
if (i < rows.length) return void setTimeout(step, 0);
this.store.setMeta(KEY, String(Date.now()));
this.onRepairDone?.();
if (fixed) log.info(`예전 녹음 ${fixed}개에서 말 중간에 끼운 무음을 빼고 정밀 모델로 다시 변환`);
};
step();
}
/** 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) });

View File

@@ -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';

View File

@@ -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);
}
}

135
app/src/core/util/zip.ts Normal file
View File

@@ -0,0 +1,135 @@
import zlib from 'node:zlib';
// 작은 ZIP 읽기 · 쓰기 (기록 묶음 내보내기 · 받아오기). 의존성 없이 쓰려고 직접 만든다.
// - 쓰기: 압축 안 함(store). ogg 는 이미 압축되어 있어 deflate 해도 거의 줄지 않는다
// - 읽기: store · deflate 둘 다 (다른 프로그램으로 다시 압축한 zip 도 받는다). ZIP64 · 암호는 안 받음
const CRC_TABLE = (() => {
const t = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
t[n] = c >>> 0;
}
return t;
})();
export function crc32(buf: Buffer): number {
let c = 0xffffffff;
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function dosTime(d: Date): { time: number; date: number } {
return {
time: (d.getHours() << 11) | (d.getMinutes() << 5) | Math.floor(d.getSeconds() / 2),
date: ((Math.max(1980, d.getFullYear()) - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate(),
};
}
export interface ZipEntry {
name: string;
data: Buffer;
}
/** 파일 목록 → zip (store) */
export function writeZip(entries: ZipEntry[], when = new Date()): Buffer {
const { time, date } = dosTime(when);
const parts: Buffer[] = [];
const central: Buffer[] = [];
let offset = 0;
for (const e of entries) {
const name = Buffer.from(e.name, 'utf8');
const crc = crc32(e.data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x0800, 6); // UTF-8 이름
local.writeUInt16LE(0, 8); // store
local.writeUInt16LE(time, 10);
local.writeUInt16LE(date, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(e.data.length, 18);
local.writeUInt32LE(e.data.length, 22);
local.writeUInt16LE(name.length, 26);
local.writeUInt16LE(0, 28);
parts.push(local, name, e.data);
const cen = Buffer.alloc(46);
cen.writeUInt32LE(0x02014b50, 0);
cen.writeUInt16LE(20, 4);
cen.writeUInt16LE(20, 6);
cen.writeUInt16LE(0x0800, 8);
cen.writeUInt16LE(0, 10);
cen.writeUInt16LE(time, 12);
cen.writeUInt16LE(date, 14);
cen.writeUInt32LE(crc, 16);
cen.writeUInt32LE(e.data.length, 20);
cen.writeUInt32LE(e.data.length, 24);
cen.writeUInt16LE(name.length, 28);
cen.writeUInt32LE(offset, 42);
central.push(cen, name);
offset += 30 + name.length + e.data.length;
}
const cenBuf = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(entries.length, 8);
end.writeUInt16LE(entries.length, 10);
end.writeUInt32LE(cenBuf.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...parts, cenBuf, end]);
}
export class ZipError extends Error {}
/** zip → 파일 이름별 내용. 폴더 항목은 뺀다. 깨진 파일이면 ZipError */
export function readZip(buf: Buffer, maxTotal = 2 * 1024 * 1024 * 1024): Map<string, Buffer> {
// 끝 레코드 찾기 (주석이 있을 수 있어 뒤에서부터)
let eocd = -1;
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) {
if (buf.readUInt32LE(i) === 0x06054b50) {
eocd = i;
break;
}
}
if (eocd < 0) throw new ZipError('zip 파일이 아닙니다');
const count = buf.readUInt16LE(eocd + 10);
let p = buf.readUInt32LE(eocd + 16);
const out = new Map<string, Buffer>();
let total = 0;
for (let i = 0; i < count; i++) {
if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) throw new ZipError('zip 목록이 깨졌습니다');
const flags = buf.readUInt16LE(p + 8);
const method = buf.readUInt16LE(p + 10);
const crc = buf.readUInt32LE(p + 16);
const csize = buf.readUInt32LE(p + 20);
const size = buf.readUInt32LE(p + 24);
const nlen = buf.readUInt16LE(p + 28);
const xlen = buf.readUInt16LE(p + 30);
const clen = buf.readUInt16LE(p + 32);
const loc = buf.readUInt32LE(p + 42);
const name = buf.toString(flags & 0x0800 ? 'utf8' : 'latin1', p + 46, p + 46 + nlen).replace(/\\/g, '/');
p += 46 + nlen + xlen + clen;
if (name.endsWith('/')) continue;
if (flags & 1) throw new ZipError(`암호가 걸린 파일은 받을 수 없습니다: ${name}`);
if (csize === 0xffffffff || size === 0xffffffff) throw new ZipError('너무 큰 zip(ZIP64)은 받을 수 없습니다');
if (loc + 30 > buf.length || buf.readUInt32LE(loc) !== 0x04034b50) throw new ZipError(`zip 안 파일이 깨졌습니다: ${name}`);
const start = loc + 30 + buf.readUInt16LE(loc + 26) + buf.readUInt16LE(loc + 28);
const raw = buf.subarray(start, start + csize);
if (raw.length !== csize) throw new ZipError(`zip 안 파일이 잘렸습니다: ${name}`);
total += size;
if (total > maxTotal) throw new ZipError('zip 내용이 너무 큽니다');
let data: Buffer;
if (method === 0) data = Buffer.from(raw);
else if (method === 8) {
try {
data = zlib.inflateRawSync(raw, { maxOutputLength: size + 1024 });
} catch {
throw new ZipError(`zip 안 파일을 풀지 못했습니다: ${name}`);
}
} else throw new ZipError(`지원하지 않는 압축 방식(${method})입니다: ${name}`);
if (data.length !== size || crc32(data) !== crc) throw new ZipError(`zip 안 파일이 손상되었습니다: ${name}`);
out.set(name, data);
}
return out;
}

View File

@@ -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 }>;

View File

@@ -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}` };
}

View File

@@ -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) {
@@ -234,7 +277,11 @@ async function syncNames(): Promise<void> {
if (!c || !auth?.ok) return;
try {
const names = await auth.displayNames();
if (core === c) c.store.setDisplayNames(names);
if (core === c) {
c.store.setDisplayNames(names);
// 녹음 파일 이름에도 표시 이름을 쓴다
c.audioNames.refreshAll();
}
} catch (e: any) {
log.warn(`표시 이름을 받지 못했습니다: ${e?.message ?? e}`);
}
@@ -299,6 +346,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 +384,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);
});

View File

@@ -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,

View File

@@ -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%;
}

View File

@@ -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={
<>

View File

@@ -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)은 쓰지 않습니다.

View File

@@ -0,0 +1,125 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Store } from '../src/core/db/db.ts';
import { AudioNamer, audioFileName, safePart } from '../src/core/audio-names.ts';
import { Bundles } from '../src/core/bundles.ts';
import { readZip, writeZip } from '../src/core/util/zip.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-names-'));
const at = (h: number, m: number, s: number) => new Date(2026, 9, 16, h, m, s).getTime();
test('녹음 파일 이름: 날짜 · 시각 · 말한 사람 · 게임 · 모드 · 맵 · 라운드 · 발화 ID', () => {
assert.equal(
audioFileName({ id: 'u1', startedAt: at(4, 3, 16), speaker: '사금향', game: 'valorant', mode: '경쟁전', map: '어센트', round: 7 }),
'2026-10-16_04-03-16_사금향_발로란트_경쟁전_어센트_R7_u1.ogg',
);
assert.equal(audioFileName({ id: 'u2', startedAt: at(21, 10, 5), speaker: '하늘', game: 'lol', mode: '솔로 랭크', gameTimeMs: 750_400 }), '2026-10-16_21-10-05_하늘_롤_솔로랭크_12분30초_u2.ogg');
assert.equal(audioFileName({ id: 'u3', startedAt: at(3, 58, 56), speaker: '사금향', game: null }), '2026-10-16_03-58-56_사금향_경기밖_u3.ogg');
// Windows 에서 못 쓰는 글자는 뺀다
assert.equal(safePart('a/b:c*d?"e<f>g|h i_j.'), 'abcdefghij');
assert.equal(audioFileName({ id: 'u4', startedAt: at(1, 2, 3), speaker: '', game: null }), '2026-10-16_01-02-03_알수없음_경기밖_u4.ogg');
});
test('녹음 파일 이름: 실제 파일을 바꾸고, 경기 뒤 라운드 · 표시 이름이 바뀌면 다시 맞추고, zip 에도 그 이름으로 넣는다', () => {
const dir = tmp();
const audio = path.join(dir, 'audio');
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
const games: any = { summary: (m: any) => ({ mode: m.game === 'lol' ? '솔로 랭크' : '경쟁전', map: { name: m.game === 'lol' ? '소환사의 협곡' : '어센트' } }), liveRound: () => 3 };
const busy = new Set<string>();
const namer = new AudioNamer(store, games, (id) => busy.has(id));
const S = at(4, 0, 0);
store.upsertMatch({ id: 'val-1', game: 'valorant', started_at: S, ended_at: S + 40 * 60000, map: 'Ascent', queue: 'competitive', status: 'live' });
const mk = (id: string, ts: number, match: string | null) => {
const f = path.join(audio, 'day', `${id}.ogg`);
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: ts, ended_at: ts + 1000, audio_path: f, match_id: match });
store.updateUtteranceResult(id, { text: `말 ${id}`, raw_text: null, words: [], noise: false, noise_reason: null, confidence: 1, lufs: -20, gain_db: 0, model: 'm', status: 'precise' });
};
mk('a1', S + 5 * 60000, 'val-1');
mk('a2', S - 60000, null);
// 경기 중: 라운드 표가 없어서 지금 라운드(3)를 쓴다
assert.equal(namer.refresh('a1'), true);
assert.equal(path.basename(store.getUtterance('a1')!.audio_path!), '2026-10-16_04-05-00_하늘_발로란트_경쟁전_어센트_R3_a1.ogg');
assert.ok(fs.existsSync(store.getUtterance('a1')!.audio_path!));
assert.ok(!fs.existsSync(path.join(audio, 'day', 'a1.ogg')));
// 경기 뒤 라운드 표가 생기면 정확한 라운드로 다시 맞춘다 (음성 인식 중인 발화는 건드리지 않음)
store.replaceRounds('val-1', [
{ match_id: 'val-1', num: 1, started_at: S, combat_at: S + 30000, ended_at: S + 2 * 60000, win: 1, result: null, ally_score: 1, enemy_score: 0, economy: '{}' },
{ match_id: 'val-1', num: 2, started_at: S + 2 * 60000, combat_at: S + 150000, ended_at: S + 6 * 60000, win: 1, result: null, ally_score: 2, enemy_score: 0, economy: '{}' },
]);
busy.add('a1');
assert.equal(namer.refreshMatch('val-1'), 0);
busy.delete('a1');
assert.equal(namer.refreshMatch('val-1'), 1);
assert.match(store.getUtterance('a1')!.audio_path!, /_R2_a1\.ogg$/);
// 표시 이름이 바뀌면 전체를 다시 맞춘다
store.setDisplayNames({ u1: '사금향' });
namer.refreshAll();
assert.match(path.basename(store.getUtterance('a2')!.audio_path!), /^2026-10-16_03-59-00_사금향_경기밖_a2\.ogg$/);
assert.match(path.basename(store.getUtterance('a1')!.audio_path!), /_사금향_발로란트_/);
// zip 안에도 같은 이름, 받아오면 받은 PC 에서도 같은 규칙으로
const b = new Bundles(store, { summary: (m: any) => ({ ...games.summary(m), score: null, win: null }) } as any, () => audio, 'test', (ids) => ids.forEach((id) => namer.refresh(id)));
const id = b.list().find((x) => x.kind === 'match')!.id;
store.db.prepare(`UPDATE matches SET status='complete' WHERE id='val-1'`).run();
const { zip } = b.export([id]);
assert.ok([...readZip(zip).keys()].includes('audio/2026-10-16_04-05-00_사금향_발로란트_경쟁전_어센트_R2_a1.ogg'));
b.delete([id]);
assert.equal(b.import(zip).added.utterances, 1);
assert.equal(path.basename(store.getUtterance('a1')!.audio_path!), '2026-10-16_04-05-00_사금향_발로란트_경쟁전_어센트_R2_a1.ogg');
assert.ok(fs.existsSync(store.getUtterance('a1')!.audio_path!));
store.close();
});
test('녹음 파일 이름: 표시 이름에 ".." 이 있어도 zip 내보내기 → 지우기 → 받아오기로 되살린다', () => {
const dir = tmp();
const audio = path.join(dir, 'audio');
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '하늘..별', avatar: null });
const namer = new AudioNamer(store, { summary: () => ({ mode: '', map: { name: '' } }), liveRound: () => null } as any, () => false);
const f = path.join(audio, 'day', 'x1.ogg');
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
const ts = at(5, 0, 0);
store.insertUtterance({ id: 'x1', session_id: null, user_id: 'u1', started_at: ts, ended_at: ts + 1000, audio_path: f, match_id: null });
store.updateUtteranceResult('x1', { text: '안녕', raw_text: null, words: [], noise: false, noise_reason: null, confidence: 1, lufs: -20, gain_db: 0, model: 'm', status: 'precise' });
assert.equal(namer.refresh('x1'), true);
assert.equal(path.basename(store.getUtterance('x1')!.audio_path!), '2026-10-16_05-00-00_하늘..별_경기밖_x1.ogg');
const b = new Bundles(store, { summary: () => ({ mode: '', map: { name: '' }, score: null, win: null }) } as any, () => audio, 'test', (ids) => ids.forEach((id) => namer.refresh(id)));
const id = b.list()[0].id;
const { zip } = b.export([id]);
assert.ok(readZip(zip).has('audio/2026-10-16_05-00-00_하늘..별_경기밖_x1.ogg'));
b.delete([id]);
assert.equal(store.getUtterance('x1'), undefined);
const r = b.import(zip);
assert.equal(r.added.utterances, 1);
assert.equal(r.added.audio, 1);
const back = store.getUtterance('x1')!;
assert.equal(back.text, '안녕');
assert.ok(fs.existsSync(back.audio_path!));
assert.ok(back.audio_path!.startsWith(audio), '받은 파일은 이 PC 의 audio 폴더 안에만 쓴다');
store.close();
});
test('받아오기: 폴더를 넘나드는 zip 안 이름은 막는다', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
const b = new Bundles(store, { summary: () => ({ mode: '', map: { name: '' }, score: null, win: null }) } as any, () => path.join(dir, 'audio'), 'test');
for (const bad of ['audio/../x1.ogg', 'audio/..\\x1.ogg', 'audio/sub/x1.ogg', '../x1.ogg']) {
const data = { users: [{ id: 'u1', name: '하늘' }], utterances: [{ id: 'x1', user_id: 'u1', started_at: 1, ended_at: 2, audio: bad }] };
const manifest = { format: 'gvr-bundle', version: 1, bundles: [{ kind: 'talk', id: 'talk-x1' }], counts: { utterances: 1 } };
const zip = writeZip([
{ name: 'manifest.json', data: Buffer.from(JSON.stringify(manifest)) },
{ name: 'data.json', data: Buffer.from(JSON.stringify(data)) },
{ name: bad, data: Buffer.from('OggS....') },
]);
assert.throws(() => b.import(zip), /음성 파일 이름이 잘못되었습니다/, bad);
}
assert.equal(store.getUtterance('x1'), undefined);
store.close();
});

View File

@@ -304,11 +304,15 @@ test('봇 중계: 슬래시 명령은 그 서버를 지켜보는 앱으로 가
const cmd = (name: string, user: string) =>
new Promise<string>((resolve) => s.source.emit('command', { name, guildId: G, user: m(user, user), voiceChannel: { id: VC1, name: '일반' } } satisfies BotCommand, resolve));
try {
assert.equal(await cmd('녹음시작', SUPER), '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.');
// 지켜보는 앱이 없는 서버의 명령은 서버가 받지 않는다 (봇 토큰을 직접 쓰는 v1.1.0 PC 가 응답하게)
assert.match(await cmd('녹음시작', SUPER), /^지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다/);
// 지켜보는 앱이 없는 서버의 명령은 서버가 잠깐 기다렸다가 받는다 (봇 토큰을 직접 쓰는 v1.1.0 PC 가 먼저 응답하게)
assert.equal(s.source.wants?.(G), false);
await a.gw.start();
await b.gw.start();
// 내 앱이 켜져 있어도 다른 서버를 녹음 대상으로 정해 두면 그렇다고 알려 준다 ("응답하지 않았어요" 대신)
assert.match(await cmd('녹음시작', SUPER), /^내 겜녹이 앱이 이 서버에 아직 연결되지 않았습니다/);
await a.gw.watch(OTHER_G, { commands: false });
assert.match(await cmd('녹음시작', SUPER), /^내 겜녹이 앱이 다른 디스코드 서버를 녹음 대상으로 정해 두었습니다/);
await a.gw.watch(G, { commands: false });
assert.equal(s.source.wants?.(G), true);
assert.equal(s.source.wants?.(OTHER_G), false);

196
app/test/bundles.test.ts Normal file
View File

@@ -0,0 +1,196 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { Store } from '../src/core/db/db.ts';
import { Bundles, BundleError } from '../src/core/bundles.ts';
import { readZip, writeZip } from '../src/core/util/zip.ts';
import { Retention } from '../src/core/retention.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-bundle-'));
const MIN = 60000;
// 20일 전 새벽 3시 (보관 기간 7일보다 오래된 녹음)
const T0 = (() => {
const d = new Date(Date.now() - 20 * 86400000);
d.setHours(3, 0, 0, 0);
return d.getTime();
})();
const OGG = (n: number) => Buffer.concat([Buffer.from('OggS'), Buffer.alloc(200, n)]);
const games: any = {
summary: (m: any) => ({ mode: '경쟁전', map: { name: '어센트' }, score: { ally: 13, enemy: 9 }, win: true, startedAt: m.started_at }),
};
function seed(dir: string) {
const store = new Store(path.join(dir, 'db.sqlite'));
const audio = path.join(dir, 'audio');
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
store.db.prepare('INSERT INTO sessions(id,guild_id,channel_id,channel_name,started_at,ended_at) VALUES(?,?,?,?,?,?)').run('s1', 'g', 'c', '음성', T0, T0 + 60 * MIN);
const utt = (id: string, user: string, at: number, opts: { match?: string; noise?: boolean; session?: string | null } = {}) => {
const f = path.join(audio, 'day', `${id}.ogg`);
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(f, OGG(at % 250));
store.insertUtterance({ id, session_id: opts.session === undefined ? 's1' : opts.session, user_id: user, started_at: at, ended_at: at + 1500, audio_path: f, match_id: opts.match ?? null });
store.updateUtteranceResult(id, { text: opts.noise ? null : `말 ${id}`, raw_text: null, words: [], noise: !!opts.noise, noise_reason: opts.noise ? 'vad' : null, confidence: 0.9, lufs: -20, gain_db: 2, model: 'm', status: 'precise' });
};
// 경기 전 대화 (경기 10분 전부터) → 경기 (10~40분) → 경기 후 대화 (42분) → 다른 날 게임 밖 대화
utt('pre1', 'u1', T0);
utt('pre2', 'u2', T0 + 2 * MIN);
utt('preNoise', 'u1', T0 + 3 * MIN, { noise: true });
store.upsertMatch({ id: 'val-1', game: 'valorant', started_at: T0 + 10 * MIN, ended_at: T0 + 40 * MIN, map: 'Ascent', mode: '경쟁전', queue: 'competitive', status: 'complete' });
store.insertEvent({ id: 'val-1:kill:1', match_id: 'val-1', game: 'valorant', type: 'kill', ts: T0 + 12 * MIN, game_time_ms: 120000, round: 1, actor_puuid: null, target_puuid: null, data: '{}' });
store.replaceRounds('val-1', [{ match_id: 'val-1', num: 1, started_at: T0 + 10 * MIN, combat_at: T0 + 10.5 * MIN, ended_at: T0 + 12 * MIN, win: 1, result: 'Elim', ally_score: 1, enemy_score: 0, economy: '{}' }]);
utt('in1', 'u1', T0 + 15 * MIN, { match: 'val-1' });
utt('in2', 'u2', T0 + 16 * MIN, { match: 'val-1' });
utt('post1', 'u2', T0 + 42 * MIN);
utt('other1', 'u1', T0 + 24 * 60 * MIN, { session: null });
return { store, audio, b: new Bundles(store, games, () => audio, 'test') };
}
test('기록 묶음: 경기 · 경기 전 대화 · 경기 후 대화 · 게임 밖 대화로 나눈다', () => {
const { store, b } = seed(tmp());
const list = b.list();
assert.deepEqual(
list.map((x) => [x.kind, x.label, x.utterances]),
[
['talk', '게임 밖 대화', 1],
['talk', '경기 후 대화', 1],
['match', '발로란트 · 경쟁전 · 어센트', 2],
['talk', '경기 전 대화', 2],
],
);
const pre = list.find((x) => x.label === '경기 전 대화')!;
assert.equal(pre.sub, '다음 경기: 발로란트 어센트');
assert.equal(pre.audio, 2, '잡음은 세지 않는다');
const m = list.find((x) => x.kind === 'match')!;
assert.equal(m.events, 1);
assert.deepEqual(m.users.sort(), ['u1', 'u2']);
store.close();
});
test('기록 묶음: zip 내보내기 → 지우기 → 받아오기로 그대로 되돌린다', () => {
const dir = tmp();
const { store, audio, b } = seed(dir);
const ids = b.list().filter((x) => x.label !== '게임 밖 대화').map((x) => x.id);
const { zip, fileName } = b.export(ids);
assert.match(fileName, /^gvr-3bundles-\d{8}-0300\.zip$/);
const zf = path.join(dir, fileName);
fs.writeFileSync(zf, zip);
execFileSync('unzip', ['-tq', zf]); // 다른 프로그램으로도 열린다
const files = readZip(zip);
assert.ok(files.has('manifest.json') && files.has('data.json') && files.has('대화.txt') && files.has('audio/in1.ogg'));
assert.match(files.get('대화.txt')!.toString('utf8'), /하늘: 말 in1/);
// 지우기: 발화 · 파일 · 경기 · 이벤트 · 라운드
const r = b.delete(ids);
assert.equal(r.bundles, 3);
assert.equal(r.utterances, 6, '잡음 발화도 함께 지운다');
assert.equal(store.getUtterance('in1'), undefined);
assert.equal(store.getMatch('val-1'), undefined);
assert.equal(store.events('val-1').length, 0);
assert.equal(store.rounds('val-1').length, 0);
assert.ok(!fs.existsSync(path.join(audio, 'day', 'in1.ogg')));
assert.equal(b.list().length, 1);
// 받아오기
const imp = b.import(zip);
assert.equal(imp.added.utterances, 5, '잡음 발화는 내보내지 않는다');
assert.equal(imp.added.matches, 1);
assert.equal(imp.added.events, 1);
assert.equal(imp.skipped, 0);
assert.equal(b.list().length, 4);
assert.equal(store.getUtterance('in1')!.text, '말 in1');
assert.ok(fs.existsSync(store.getUtterance('in1')!.audio_path!));
assert.equal(store.rounds('val-1').length, 1);
// 같은 zip 을 또 받으면 건너뛴다
assert.equal(b.import(zip).skipped, 5);
// 받아온 녹음은 보관 기간을 받아온 날부터 센다 (녹음 날짜가 오래돼도 바로 지우지 않음)
const ret = new Retention(store, () => 7, () => audio).run(Date.now());
assert.equal(ret.deleted, 1, '받아오지 않은 다른 날 발화만 지운다');
assert.equal(store.getUtterance('in1')!.audio_deleted, 0);
store.close();
});
test('기록 묶음: 진행 중인 경기는 지우지 않는다', () => {
const { store, b } = seed(tmp());
store.db.prepare(`UPDATE matches SET status='live' WHERE id='val-1'`).run();
const m = b.list().find((x) => x.kind === 'match')!;
assert.equal(m.live, true);
assert.throws(() => b.delete([m.id]), (e: any) => e instanceof BundleError && e.code === 'busy');
assert.ok(store.getMatch('val-1'));
store.close();
});
test('기록 묶음: 다른 프로그램으로 다시 압축한(deflate) zip 도 받는다', () => {
const dir = tmp();
const { store, b } = seed(dir);
const id = b.list().find((x) => x.kind === 'match')!.id;
const { zip } = b.export([id]);
const x = path.join(dir, 'x');
fs.mkdirSync(x);
fs.writeFileSync(path.join(dir, 'a.zip'), zip);
execFileSync('unzip', ['-q', path.join(dir, 'a.zip'), '-d', x]);
execFileSync('zip', ['-q', '-r', '-9', path.join(dir, 'b.zip'), '.'], { cwd: x });
b.delete([id]);
const r = b.import(fs.readFileSync(path.join(dir, 'b.zip')));
assert.equal(r.added.utterances, 2);
store.close();
});
test('기록 묶음 받아오기: 꼭 필요한 내용이 없으면 실패', () => {
const { store, b } = seed(tmp());
const { zip } = b.export([b.list().find((x) => x.kind === 'match')!.id]);
const files = readZip(zip);
const make = (patch: (m: Map<string, Buffer>) => void) => {
const m = new Map(files);
patch(m);
return writeZip([...m].map(([name, data]) => ({ name, data })));
};
const data = () => JSON.parse(files.get('data.json')!.toString());
const cases: [string, Buffer, RegExp][] = [
['zip 아님', Buffer.from('hello'), /zip 파일이 아닙니다/],
['manifest 없음', make((m) => m.delete('manifest.json')), /manifest\.json 이 없습니다/],
['data 없음', make((m) => m.delete('data.json')), /data\.json 이 없습니다/],
['음성 없음', make((m) => m.delete('audio/in1.ogg')), /audio\/in1\.ogg 가 zip 안에 없습니다/],
['ogg 아님', make((m) => m.set('audio/in1.ogg', Buffer.from('not ogg'))), /ogg 가 아닙니다/],
['다른 형식', make((m) => m.set('manifest.json', Buffer.from(JSON.stringify({ format: 'other' })))), /형식이 아닙니다/],
[
'말한 사람 없음',
make((m) => {
const d = data();
d.users = [];
d.utterances[0].user_id = 'nobody';
m.set('data.json', Buffer.from(JSON.stringify(d)));
}),
/말한 사람\(nobody\)이 유저 목록에 없습니다/,
],
[
'경기 기록 없음',
make((m) => {
const d = data();
d.matches = [];
m.set('data.json', Buffer.from(JSON.stringify(d)));
}),
/경기 기록이 data\.json 에 없습니다/,
],
[
'발화 수 다름',
make((m) => {
const d = data();
d.utterances.pop();
m.set('data.json', Buffer.from(JSON.stringify(d)));
}),
/발화 수가 맞지 않습니다/,
],
];
const before = store.db.prepare('SELECT count(*) n FROM utterances').get() as { n: number };
for (const [name, buf, re] of cases) {
assert.throws(
() => b.import(buf),
(e: any) => e instanceof BundleError && re.test(e.message) && e.message.startsWith('받아오기 실패'),
name,
);
}
assert.deepEqual(store.db.prepare('SELECT count(*) n FROM utterances').get(), before, '실패하면 아무것도 넣지 않는다');
store.close();
});

View File

@@ -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'));
});

View File

@@ -199,6 +199,21 @@ test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
assert.equal(info2.history.length, 2);
assert.equal(info2.analysis!.model, 'm2');
assert.equal(info2.history.filter((h) => h.current).length, 1);
// 표시 이름(실명 숨기기): 이름을 바꾸기 전에 시작한 분석(자료 · 요약에 예전 이름)이 바꾼 뒤에 도착해도 예전 이름이 남지 않는다
ctx.store.setDisplayNames({ u1: '별명' });
assert.equal(ctx.store.getUser('u1')?.name, '별명');
const late = { ...result, summary: '하늘이 캐리했다' };
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result: late, players: input.players, model: 'm3', createdBy: { id: 'u1', name: '하늘' }, meta: {} } });
const raw = () => JSON.stringify(ctx.store.db.prepare('SELECT created_by, result FROM culprit_analyses').all());
assert.ok(!raw().includes('하늘'), raw());
const info3 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
assert.equal(info3.analysis!.result.summary, '별명이 캐리했다');
assert.equal(info3.analysis!.createdBy.name, '별명');
assert.ok(info3.analysis!.players.some((p) => p.name === '별명'));
// 같은 이름으로 다시 받아도(이미 바뀐 유저는 건너뛰는 경우) 그대로 깨끗하다
ctx.store.setDisplayNames({ u1: '별명' });
assert.ok(!raw().includes('하늘'));
await api.close();
});

View File

@@ -63,11 +63,25 @@ 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();
// 변환이 끝나면 녹음 파일 이름을 날짜 · 시각 · 말한 사람 · 경기 밖 · 발화 ID 로 바꾼다
assert.match(info.fileName, /^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_하늘_경기밖_speech\.ogg$/);
const sp2 = core.store.getUtterance('speech')!;
assert.equal(info.path, sp2.audio_path);
assert.ok(fs.existsSync(sp2.audio_path!));
assert.equal(info.folder, path.dirname(sp2.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);
@@ -78,6 +92,45 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
assert.ok(fs.existsSync(core.store.trainingSamples()[0].audio_path));
const search = (await core.api.inject({ method: 'GET', url: '/api/timeline?q=' + encodeURIComponent('궁 빠졌어') })).json();
assert.deepEqual(search.items.map((i: any) => i.id), ['speech']);
// 기록 묶음 API: 목록 → zip → 지우기 → 받아오기
const bl = (await core.api.inject({ method: 'GET', url: '/api/bundles' })).json().bundles;
assert.equal(bl.length, 1);
assert.equal(bl[0].label, '게임 밖 대화');
const ex = await core.api.inject({ method: 'GET', url: `/api/bundles/export?ids=${bl[0].id}` });
assert.equal(ex.headers['content-type'], 'application/zip');
assert.match(String(ex.headers['content-disposition']), /attachment; filename="gvr-talk-\d{8}-\d{4}\.zip"/);
// 사이트 중계로 온 요청은 사이트 서버가 붙인 역할이 관리자여야 한다
const user = encodeURIComponent(JSON.stringify({ id: 'm1', name: 'x', avatar: null }));
assert.equal((await core.api.inject({ method: 'POST', url: '/api/bundles/delete', headers: { 'x-gvr-user': user, 'x-gvr-role': 'member' }, payload: { ids: [bl[0].id] } })).statusCode, 403);
assert.equal((await core.api.inject({ method: 'POST', url: '/api/bundles/delete', headers: { 'x-gvr-user': user }, payload: { ids: [bl[0].id] } })).statusCode, 403);
const del = (await core.api.inject({ method: 'POST', url: '/api/bundles/delete', payload: { ids: [bl[0].id] } })).json();
assert.equal(del.utterances, 3);
assert.equal((await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.length, 0);
const bad = await core.api.inject({ method: 'POST', url: '/api/bundles/import', headers: { 'content-type': 'application/zip' }, payload: Buffer.from('PK nope') });
assert.equal(bad.statusCode, 400);
assert.match(bad.json().message, /^받아오기 실패/);
const imp = (await core.api.inject({ method: 'POST', url: '/api/bundles/import', headers: { 'content-type': 'application/zip' }, payload: ex.rawPayload })).json();
assert.equal(imp.added.utterances, 2, '잡음(keys)은 내보내지 않는다');
assert.equal((await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.length, 2);
assert.ok(live.some((e) => e.type === 'records.changed'));
// 우클릭 → 삭제 → "잡음이라 삭제" (v1.4.0): 인식된 문장을 배우고, 같은 녹음이 다시 들어오면 잡음으로 숨긴다
const heard = core.store.getUtterance('speech')!.raw_text!;
const nd = await core.api.inject({ method: 'POST', url: '/api/utterances/speech/delete', headers: { 'x-gvr-user': encodeURIComponent(JSON.stringify({ id: 'u1', name: '하늘', avatar: null })), 'x-gvr-role': 'member' }, payload: { noise: true } });
assert.deepEqual(nd.json(), { ok: true, learned: heard });
assert.equal(core.store.getUtterance('speech'), undefined);
const again = path.join(core.paths().audio, 'test', 'again.ogg');
fs.copyFileSync(path.join(fx, 'speech_ko.ogg'), again);
core.store.insertUtterance({ id: 'again', session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 3000, audio_path: again, match_id: null });
core.stt.enqueue('again', 'realtime');
await wait(() => core.store.getUtterance('again')!.status !== 'pending', 60000, 'transcribe again');
const ag = core.store.getUtterance('again')!;
console.log('again →', ag.noise, ag.noise_reason, '| raw:', ag.raw_text);
assert.equal(ag.noise, 1);
assert.equal(ag.noise_reason, 'learned');
assert.equal(ag.audio_deleted, 1);
assert.ok(!fs.existsSync(again));
assert.equal(core.store.listNoisePhrases()[0].hits, 1);
assert.ok(!(await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.some((i: any) => i.id === 'again'));
} finally {
await core.stop();
}

View File

@@ -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);
});

View File

@@ -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' }])],
[

View File

@@ -0,0 +1,209 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Store, normalizePhrase, similarPhrase } from '../src/core/db/db.ts';
import { buildApi } from '../src/core/api/server.ts';
import { Timeline } from '../src/core/timeline.ts';
import { Bus } from '../src/core/util/events.ts';
import { SttPipeline } from '../src/core/stt/pipeline.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-del-'));
const as = (id: string, role: 'admin' | 'member' = 'member') => ({ 'x-gvr-user': encodeURIComponent(JSON.stringify({ id, name: id, avatar: null })), 'x-gvr-role': role });
function setup() {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const timeline = new Timeline(store);
const bus = new Bus();
const live: any[] = [];
bus.on('live', (e) => live.push(e));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
const mk = (id: string, raw: string | null, text: string | null = raw) => {
const f = path.join(dir, 'audio', `${id}.ogg`);
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
if (raw !== null || text !== null)
store.updateUtteranceResult(id, { text, raw_text: raw, words: [], noise: false, noise_reason: null, confidence: 0.4, lufs: -30, gain_db: 0, model: 'm', status: 'precise' });
return f;
};
return { dir, store, timeline, bus, live, mk };
}
const api = (s: ReturnType<typeof setup>) =>
buildApi({
store: s.store,
timeline: s.timeline,
games: {} as any,
dict: { learn() {}, invalidate() {} } as any,
culprit: {} as any,
bus: s.bus,
settings: () => ({ dictionary: { applySiteCorrections: false } }) as any,
trainingDir: () => path.join(s.dir, 'training'),
overviewExtra: () => ({ guild: null, recording: {} as any }),
version: 'test',
});
test('잡음 문장 비교: 띄어쓰기 · 문장부호 · 대소문자를 무시한다 (워커 noise.normalize 와 같게)', () => {
assert.equal(normalizePhrase('자막 제공 및 자막을 사용하였습니다.'), '자막제공및자막을사용하였습니다');
assert.equal(normalizePhrase(' 자막제공, 및 자막을...사용하였습니다!! '), '자막제공및자막을사용하였습니다');
assert.equal(normalizePhrase('MBC 뉴스_이덕영입니다'), 'mbc뉴스이덕영입니다');
assert.equal(normalizePhrase('ㅋㅋㅋ'), 'ㅋㅋㅋ');
assert.equal(normalizePhrase('... !!'), '');
assert.equal(normalizePhrase(null), '');
});
test('거의 같은 문장: 글자 수가 같고(8글자 이상) 15% 이하 글자만 바뀐 것, 짧은 말은 통째로 같을 때만', () => {
const n = normalizePhrase;
assert.ok(similarPhrase(n('레이드 공 빠졌어 비 사이트로테 하자'), n('레이드 궁 빠졌어 비 사이트로테 하자')));
assert.ok(similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n('자막 재공 및 자막을 사용하였습니다')));
// 배운 잡음 문장 앞뒤에 실제 말이 붙으면 다른 말이다 (지우면 실제 음성을 잃는다)
for (const real of ['네', '가자', '아니']) {
assert.ok(!similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n(`자막 제공 및 자막을 사용하였습니다 ${real}`)), `뒤에 "${real}"`);
assert.ok(!similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n(`${real} 자막 제공 및 자막을 사용하였습니다`)), `앞에 "${real}"`);
}
assert.ok(!similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n('자막 제공 및 자막을 사용했습니다')), '글자 수가 다르면 아니다');
assert.ok(!similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n('자막 제공 및 자막을 사용하였습니다 그리고 레이즈 궁')));
assert.ok(!similarPhrase(n('시청해 주셔서'), n('시청해 주셨어')), '8글자 미만은 거의 같아도 아니다');
assert.ok(!similarPhrase(n('오늘 저녁 뭐 먹을래'), n('내일 아침 뭐 먹을래')));
});
test('발화 지우기: 관리자 · 말한 사람만, 글 · 음성 · 학습 데이터를 지우고 실시간으로 알린다', async () => {
const s = setup();
const app = await api(s);
const f1 = s.mk('a1', '그냥 말');
// 교정해서 학습 데이터가 생긴 발화
s.mk('a2', '레이저 궁', '레이저 궁');
const patched = await app.inject({ method: 'PATCH', url: '/api/utterances/a2', payload: { text: '레이즈 궁' } });
assert.equal(patched.statusCode, 200);
const sample = s.store.trainingSamples()[0].audio_path;
assert.ok(fs.existsSync(sample));
s.mk('a3', '아무 말');
// 다른 멤버는 못 지운다 (사이트 서버가 붙인 역할 · 유저로 판단)
const no = await app.inject({ method: 'POST', url: '/api/utterances/a1/delete', headers: as('m9'), payload: { noise: false } });
assert.equal(no.statusCode, 403);
assert.ok(s.store.getUtterance('a1'));
// 말한 사람 본인
const r1 = await app.inject({ method: 'POST', url: '/api/utterances/a1/delete', headers: as('u1'), payload: { noise: false } });
assert.equal(r1.statusCode, 200);
assert.deepEqual(r1.json(), { ok: true, learned: null });
assert.equal(s.store.getUtterance('a1'), undefined);
assert.ok(!fs.existsSync(f1));
assert.deepEqual(s.live.at(-1), { type: 'utterance.deleted', data: { id: 'a1', noise: false } });
// "그냥 삭제"는 아무것도 배우지 않는다
assert.equal(s.store.listNoisePhrases().length, 0);
// 관리자: 교정 학습 데이터(음성 조각)도 같이 지운다
const r2 = await app.inject({ method: 'POST', url: '/api/utterances/a2/delete', headers: as('m9', 'admin'), payload: {} });
assert.equal(r2.statusCode, 200);
assert.equal(s.store.trainingSamples().length, 0);
assert.ok(!fs.existsSync(sample));
// 이 PC 안에서 부른 것 (설정 창)
assert.equal((await app.inject({ method: 'POST', url: '/api/utterances/a3/delete', payload: {} })).statusCode, 200);
// 이미 지운 발화
assert.equal((await app.inject({ method: 'POST', url: '/api/utterances/a3/delete', payload: {} })).statusCode, 404);
// 타임라인에서 빠진다
assert.equal((await app.inject({ url: '/api/timeline' })).json().items.length, 0);
// 잘못된 사용자 머리글은 거절
s.mk('a4', '말');
assert.equal((await app.inject({ method: 'POST', url: '/api/utterances/a4/delete', headers: { 'x-gvr-user': '%E0%A4%A' }, payload: {} })).statusCode, 403);
await app.close();
});
test('잡음이라 삭제: 인식 문장을 배우고, 목록 · 지우기 API 로 볼 수 있다', async () => {
const s = setup();
const app = await api(s);
s.mk('n1', '자막 제공 및 자막을 사용하였습니다.');
s.mk('n2', null); // 아직 인식 전: 배울 문장 없음
const r = await app.inject({ method: 'POST', url: '/api/utterances/n1/delete', headers: as('u1'), payload: { noise: true } });
assert.deepEqual(r.json(), { ok: true, learned: '자막 제공 및 자막을 사용하였습니다.' });
assert.deepEqual(s.live.at(-1), { type: 'utterance.deleted', data: { id: 'n1', noise: true } });
const r2 = await app.inject({ method: 'POST', url: '/api/utterances/n2/delete', headers: as('u1'), payload: { noise: true } });
assert.deepEqual(r2.json(), { ok: true, learned: null });
const list = (await app.inject({ url: '/api/noise-phrases' })).json().phrases;
assert.equal(list.length, 1);
assert.equal(list[0].text, '자막 제공 및 자막을 사용하였습니다.');
assert.equal(list[0].hits, 0);
assert.equal(s.store.listNoisePhrases()[0].phrase, '자막제공및자막을사용하였습니다');
// 같은 문장을 또 배우면 하나로
s.mk('n3', '자막제공 및 자막을 사용하였습니다');
await app.inject({ method: 'POST', url: '/api/utterances/n3/delete', payload: { noise: true } });
assert.equal(s.store.listNoisePhrases().length, 1);
assert.equal((await app.inject({ method: 'DELETE', url: `/api/noise-phrases/${list[0].id}` })).statusCode, 200);
assert.equal((await app.inject({ method: 'DELETE', url: `/api/noise-phrases/${list[0].id}` })).statusCode, 404);
assert.equal(s.store.listNoisePhrases().length, 0);
await app.close();
});
test('음성 인식: 배운 잡음 문장과 같으면 잡음으로 숨기고 파일을 지운다 · 변환 중에 지운 발화는 결과를 버린다', async () => {
const s = setup();
s.store.addNoisePhrase(normalizePhrase('자막 제공 및 자막을 사용하였습니다.'), '자막 제공 및 자막을 사용하였습니다.');
const results: Record<string, string> = { p1: '자막 재공 및 자막을 사용하였습니다', p2: '자막 제공 및 자막을 사용하였습니다. 그리고 레이즈 궁', p3: '아무 말' };
let hold: (() => void) | null = null;
const worker: any = Object.assign(new EventEmitter(), {
ready: true,
request: async (op: string, req: any) => {
if (op === 'gpu_info') return { gpus: [] };
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
if (op === 'load') return {};
const id = path.basename(req.path, '.ogg');
if (id === 'p3') await new Promise<void>((r) => (hold = r));
const t = results[id];
return { text: t, raw_text: t, words: [], noise: false, noise_reason: null, confidence: 0.5, lufs: -30, gain_db: 0, speech_ratio: 1, duration_s: 1, model: 'm', elapsed_ms: 1 };
},
});
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm', device: 'cpu', computeType: 'int8', gameVramReserveMb: 0, reprocessAfterMatch: false }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
const stt = new SttPipeline(worker, s.store, dict, s.timeline, s.bus, settings);
await stt.load('realtime', 'm');
const f1 = s.mk('p1', null);
const f2 = s.mk('p2', null);
const f3 = s.mk('p3', null);
const wait = async (fn: () => boolean) => {
const t = Date.now();
while (!fn()) {
if (Date.now() - t > 5000) throw new Error('timeout');
await new Promise((r) => setTimeout(r, 10));
}
};
stt.enqueue('p1', 'realtime');
stt.enqueue('p2', 'realtime');
await wait(() => s.store.getUtterance('p2')!.status !== 'pending');
const p1 = s.store.getUtterance('p1')!;
assert.equal(p1.noise, 1);
assert.equal(p1.noise_reason, 'learned');
assert.equal(p1.text, null);
assert.equal(p1.audio_deleted, 1);
assert.ok(!fs.existsSync(f1));
assert.equal(s.store.listNoisePhrases()[0].hits, 1, '한두 글자 다른 문장도 거른다');
// 문장이 더 붙으면 다른 말이다: 음성 · 글을 그대로 둔다
const p2 = s.store.getUtterance('p2')!;
assert.equal(p2.noise, 0);
assert.ok(fs.existsSync(f2));
for (const [i, real] of ['네', '가자', '아니'].entries()) {
const id = `r${i}`;
results[id] = `자막 제공 및 자막을 사용하였습니다. ${real}`;
const f = s.mk(id, null);
stt.enqueue(id, 'realtime');
await wait(() => s.store.getUtterance(id)!.status !== 'pending');
const u = s.store.getUtterance(id)!;
assert.equal(u.noise, 0, `뒤에 "${real}" 이 붙은 발화는 잡음이 아니다`);
assert.equal(u.text, results[id]);
assert.ok(fs.existsSync(f), `뒤에 "${real}" 이 붙은 발화의 음성은 남는다`);
}
assert.equal(s.store.listNoisePhrases()[0].hits, 1);
// 변환하는 동안 지우면 결과를 DB 에 되살리지 않는다
stt.enqueue('p3', 'realtime');
await wait(() => !!hold);
s.store.deleteUtterance('p3');
const gainN = s.store.getUser('u1')!.gain_n;
hold!();
await wait(() => !stt.isBusy('p3'));
assert.equal(s.store.getUser('u1')!.gain_n, gainN, '지운 발화의 음량은 평소 음량에 넣지 않는다');
assert.equal(s.store.getUtterance('p3'), undefined);
assert.ok(!s.live.some((e) => e.type === 'utterance.updated' && e.data.id === 'p3'));
assert.ok(fs.existsSync(f3), 'store.deleteUtterance 는 파일을 직접 지우지 않는다 (API 가 지움)');
});

BIN
assets/app/splash.bmp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 326 KiB

View File

@@ -114,6 +114,7 @@ GVR-Data/
- `game_events(id PK, match_id, game, type, ts INT ms(real), game_time_ms, round, actor_puuid, target_puuid, data JSON)`
- `dictionary(id PK, word, pack, kind ('hotword'|'correction'), from_text, source ('builtin'|'user'|'site'), enabled)`
- `training_samples(id PK, utterance_id, text, audio_path, used INT, created_at)`
- `noise_phrases(id PK, phrase UNIQUE (띄어쓰기 · 문장부호 뺀 값), sample, hits, created_at)` — "잡음이라 삭제"로 배운 문장 (v1.4.0)
## 4. 앱 HTTP API (코어 Fastify, 127.0.0.1) — 사이트 서버가 그대로 중계
@@ -131,6 +132,9 @@ GVR-Data/
| GET | `/api/matches/:id` | `MatchDetail` |
| PATCH | `/api/utterances/:id` | `{text}` → 교정 저장, 교정 사전·학습 데이터 반영. 응답 `TimelineItem` |
| GET | `/api/dictionary` | 사전 목록 |
| POST | `/api/utterances/:id/delete` | `{noise}` → 발화 · 음성 · 학습 데이터 지우기 (관리자 · 말한 사람). noise=true 면 문장을 잡음으로 배움. 응답 `{ok, learned}`, 실시간 `utterance.deleted` |
| GET | `/api/noise-phrases` | `{phrases:[{id,text,hits,createdAt}]}` 잡음으로 배운 문장 |
| DELETE | `/api/noise-phrases/:id` | 배운 문장 지우기 |
`/api/timeline` 쿼리: `users=a,b` · `game=valorant|lol|none` · `match=<id>` · `from=<ms>&to=<ms>` ·
`q=<키워드>` · `types=utterance,kill,chat,object,round` · `hideNoise=1` · `cursor=<opaque>` · `limit=100` ·

View File

@@ -167,3 +167,87 @@ VOICE E2E PASS
- AI 평점과 기록 점수 차: 평균 0.4점 (롤 P2 는 "용 셋 · 유충 · 바론 싹쓸이"를 근거로 기록 3.0 → AI 5.0)
- 테스트: 앱 40개 · 사이트 서버 16개 통과 (서버 테스트에 "자료에 기록 점수 칸, 지시문 '평점은 기록 점수에서 출발', OP.GG 실제 점수 없음" 확인 추가)
- 배포: 사이트 서버 다시 배포 (서버 번들 · 화면에 OP.GG 접속 코드 없음 확인, 지시문 '평점은 기록 점수에서 출발'), Windows CI (b8e76ab, full) 8개 모두 PASS · 앱 버전 1.3.2 → Gitea 릴리스 v1.3.2 (v1.3.0 · v1.3.1 에 새 버전 안내)
## v1.3.3 — 따라갈 사람 목록 · 롤 채팅 OCR 제거 · 표시 이름 (2026-10-16)
- 따라갈 사람 원인: 사이트 서버 봇 중계가 "지켜보는 서버"가 아니면 멤버 요청을 `forbidden` 으로 거절했고, 앱(`guildMembers`)이 오류를 삼켜 빈 목록이 됐다. 설정 창은 봇이 준비되자마자(지켜보기 전) 요청하므로 "선택 안 함"만 남았다. `bot-gateway.test.ts` 에 지켜보기 전 요청을 넣어 예전 서버 코드에서 `forbidden` 으로 실패하는 것을 확인한 뒤 고침. 실제 사이트 서버 봇은 M&L 87명 · 다른 서버 27명을 정상으로 받음
- 정렬: 내 계정 → 관리자(`GET /app/admins`) → 이름순 (mock 화면 확인: `민준 (나)`, `지호 · 관리자`, 나머지)
- 롤 채팅: LCU · 게임 클라이언트 API(2999) 모두 게임 중 전체 · 팀 채팅을 주지 않는다 (`lol-game-client-chat` 은 귓속말 · 파티 메시지 보내기만, 게임 중 채팅 이벤트는 Overwolf 전용이며 저장 금지). OCR 코드 · 의존성(pywinrt · mss · Pillow) 제거, r3dlog 채팅은 LCU 채팅을 지우지 않고 추가
- 표시 이름: 서버 `displayNames` · `GET /app/names` · `PUT /app/admin/names`(최고 관리자), 앱은 users · 지난 범인 분석 이름 교체. 운영 서버에 두 최고 관리자 계정 표시 이름 설정, server.json 에 실명 0건
- 저장소: 시연 · 테스트 데이터 · 화면 캡처(`docs/dev/screens`, `docs/report/img`, `docs/report/culprit/img`) · 계획서 PDF 3개를 가짜 이름으로 다시 만듦 (PDF 쪽수 그대로)
- 테스트: 앱 41 · 사이트 서버 16 · 워커 39 통과, 앱/화면 타입 검사 통과
- 배포: 사이트 서버 다시 배포(화면 번들 실명 0건, 새 API 401 응답 확인), Windows CI (b230443, full) 7개 모두 PASS (ocr_lang 단계 삭제) · 앱 버전 1.3.3 → Gitea 릴리스 v1.3.3 (v1.3.2 에 새 버전 안내)
## v1.3.4 — 슬래시 명령 응답 · 녹음 중 봇 상태 메시지 (2026-10-16)
- 원인: 사이트 서버 `discord-source.ts` 가 "그 서버를 지켜보는 앱이 없으면" 슬래시 명령을 응답 없이 무시했다 (옛 v1.1.0 PC 와 응답이 겹치지 않게 넣은 동작) → 디스코드 "애플리케이션이 응답하지 않았어요". 이제 1.5초 기다린 뒤 이유를 답한다 (`bot-gateway.test.ts`: 앱 없음 · 내 앱이 다른 서버를 지켜봄 · 아직 연결 중 세 경우 확인)
- 앱: 지켜보던 중 `watch_denied` 를 받으면 1분 뒤 다시 지켜보기
- 상태 메시지: 테스트 봇으로 `dnd + "🔴 녹음 중"` · `online + "🎙️ 대기 중 · /녹음시작"` 을 디스코드가 받는 것 확인, 배포 뒤 실제 겜녹이 봇 상태가 "🎙️ 대기 중 · /녹음시작" 인 것을 같은 서버의 테스트 봇으로 읽어 확인
- 테스트: 앱 41 · 사이트 서버 16 통과. Windows CI (db2f186, full) 7개 모두 PASS · 앱 버전 1.3.4 → Gitea 릴리스 v1.3.4 (v1.3.3 에 새 버전 안내)
## v1.3.5 — 표시 이름 빈틈 · 상태 메시지 실제 확인 (2026-10-16)
- 표시 이름: 이름을 바꾸기 전에 시작한 분석이 바꾼 뒤 저장되면 예전 이름이 남던 빈틈 (`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 끊긴 뒤 관리자만 로그를 보고 내려받는 것 확인
- 배포: 사이트 서버 다시 배포 (`data/logs/site-날짜.log` 생성 · `[discord]` · `[http]` 줄 확인, `/site/logs` 로그인 없이 401), Windows CI (fa6126e, full) 7개 모두 PASS (zip 안 워커에 `av/filter` 포함) · 앱 버전 1.3.6 → Gitea 릴리스 v1.3.6 (v1.3.5 에 새 버전 안내)
## v1.3.7 — 기록 관리(경기별 묶음 · zip 내보내기/받아오기) · 검토로 찾은 오류 고침 (2026-10-16)
- 기록 묶음: 경기 = 묶음 하나, 경기 밖 대화는 녹음 세션 안에서 경기 사이마다 묶고 30분 기준으로 "경기 전 대화" · "경기 후 대화" · "게임 밖 대화". 사용자 실제 데이터(사본)로 확인: 경기 전 대화 7개 → 데스매치 11개 → 경기 후 대화 3개, 3묶음 zip 1.0MB
- 테스트 `bundles.test.ts`: 나누기, 내보내기 → 지우기 → 받아오기 그대로 복원(경기 · 라운드 · 이벤트 · 음성), 같은 zip 다시 받기는 건너뜀, 받아온 녹음은 보관 기간을 받아온 날부터, 다른 프로그램으로 다시 압축(deflate)한 zip, 받아오기 실패 9가지(zip 아님 · manifest · data 없음 · 음성 없음 · ogg 아님 · 다른 형식 · 말한 사람 없음 · 경기 기록 없음 · 발화 수 다름 → 아무것도 넣지 않음), 진행 중인 경기는 지우지 않음
- 사이트 서버 테스트: 20MB zip 내보내기 · 받아오기가 1MB 조각으로 그대로 오가는 것, 지우기 · 받아오기는 관리자만 (`/api/%62undles/delete` 같은 우회도 403)
- 전체 검토(v1.3.6 · v1.3.7 변경 3,600줄)로 찾아 고친 오류:
1. 기록 지우기 관리자 확인을 주소 %인코딩으로 우회 가능 → 주소를 풀어서 확인, 앱도 사이트가 붙인 역할로 한 번 더 확인
2. 큰 zip 을 주고받는 동안 앱이 pong 을 못 받아 사이트 연결을 스스로 끊음 → 무엇이든 받으면 살아 있는 것으로, 보낼 것이 4MB 넘게 쌓이면 기다림
3. 진행 중인 경기를 지우면 경기 끝 처리(정밀 변환 등)가 멈춤 → 진행 중인 경기는 지울 수 없음
4. 내보낸 zip 이 받아오기 한도(300MB)보다 클 수 있음 → 280MB 넘으면 나눠 받게 안내
5. 예전 녹음 고치기가 정밀 결과를 실시간 모델 결과로 덮고, 잡음으로 나오면 파일을 지울 수 있었음 · 시작할 때 한꺼번에 처리 → 정밀 모델로만, 잡음이면 이전 결과 유지, 20개씩, 중간에 꺼져도 이어서 (업그레이드 전에 만든 녹음만)
6. 타임라인 최신순에서 오래된 발화가 고쳐지면 맨 아래에 붙음 → 더 불러올 페이지가 남아 있으면 넣지 않음
7. 반복 줄이기가 숫자를 망가뜨림 ("1000원 줘 줘 줘" → "10원 줘") → 숫자 · 붙은 한 글자 반복은 그대로
8. TTS 속도 바꾸기가 중간에 죽으면 반쪽 파일이 계속 쓰임 → 다 만든 뒤 이름 바꾸기
- 그 밖: 브라우저 오류 로그에 검색어가 남던 것, 경기 끝 직후 늦게 끝난 실시간 변환의 잡음 파일을 정밀 확인 전에 지우던 것, 많이 골랐을 때 내려받기 주소가 너무 길던 것(본문으로 보냄), zip 풀기 메모리 한도 600MB, 날짜 묶음이 "10월"로만 나오던 것(경기 · 기록 목록)
- 테스트: 앱 53 · 사이트 서버 16 · 워커 42 통과, 타입 검사 통과
- 배포: 사이트 서버 다시 배포 (`/api/%62undles/delete` 로그인 없이 401), Windows CI (5d494eb, full) 7개 모두 PASS · 앱 버전 1.3.7 → Gitea 릴리스 v1.3.7 (v1.3.6 에 새 버전 안내) · 보고서 `docs/gemnoki-v1.3.7-report.pdf`
## v1.3.8 — 녹음 파일 이름 (2026-10-16)
- 이름 규칙 `날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg` (롤은 게임 시간, 경기 밖은 `경기밖`). 테스트 `audio-names.test.ts`: 이름 만들기 · Windows 금지 글자, 실제 파일 바꾸기, 경기 중 지금 라운드 → 경기 뒤 라운드 표로 다시 맞춤, 음성 인식 중이면 건드리지 않음, 표시 이름 바뀌면 전체 다시, zip 안 이름 · 받아오기 뒤 이름
- 실제 STT 워커 E2E: 변환이 끝난 뒤 파일 이름이 `…_하늘_경기밖_speech.ogg` 로 바뀌고 자세한 정보 경로도 같음
- 사용자 데이터 사본: 21개 이름 바꿈 (`2026-10-16_04-05-52_사금향_발로란트_데스매치_어비스_0mv9wsvgh48a56ebde5.ogg`, 데스매치는 라운드 없음, 경기 전후는 `경기밖`)
- 배포: 사이트 서버 다시 배포, Windows CI (249ead8, full) 7개 모두 PASS · 앱 버전 1.3.8 → Gitea 릴리스 v1.3.8 (v1.3.7 에 새 버전 안내)
## v1.3.9 — 받아오기: 이름 안의 ".." (2026-10-16)
- 원인: 받아오기 검사가 zip 안 음성 파일 이름에 `..` 이 있으면 거절했다. v1.3.8 부터 파일 이름에 표시 이름이 들어가므로 `하늘..별` 같은 이름이면 내보낸 zip 을 다시 넣지 못했다 (백업 뒤 지우면 되살릴 수 없음)
- 고침: zip 안 이름은 zip 에서 꺼낼 열쇠로만 쓰고, 이 PC 에 쓰는 경로는 발화 ID 로 만든다. 폴더 구분자만 막는다
- 테스트: `audio-names.test.ts` "표시 이름에 .. 이 있어도 내보내기 → 지우기 → 받아오기" (예전 코드에서 실패 확인 뒤 고침), "폴더를 넘나드는 zip 안 이름(audio/../, audio/..\, audio/sub/, ../)은 막는다". 앱 57 통과
- 배포: Windows CI (55ec58f, full) 7개 모두 PASS · 앱 버전 1.3.9 → Gitea 릴리스 v1.3.9 (v1.3.8 에 새 버전 안내). 사이트 서버는 바뀐 것 없음
## v1.4.0 — 발화 우클릭 삭제 · 잡음 문장 배우기 · 알림 기본 끄기 (2026-10-16)
- 사이트 우클릭 → 삭제… → "잡음이라 삭제" / "그냥 삭제" / 취소. 관리자 · 말한 사람만 (사이트 서버가 붙인 역할 · 유저로 앱이 확인)
- 테스트 `utterance-delete.test.ts`: 다른 멤버 403 · 본인 · 관리자 · 이 PC 안에서는 지움, 글 · 음성 · 교정 학습 음성 조각까지 지움, `utterance.deleted` 실시간 이벤트, 이미 지운 발화 404, 잘못된 사용자 머리글 403. 잡음이라 삭제 → 문장 배움(같은 문장은 하나로) · 목록 · 지우기. 음성 인식: 배운 문장과 같거나 거의 같으면(`…사용하였습니다` / `…사용했습니다`) 잡음 · 파일 삭제, 문장이 더 붙으면 그대로, 변환하는 동안 지운 발화는 결과 · 평소 음량에 넣지 않음 (이 확인을 빼면 실패하는 것 확인)
- 실제 STT 워커 E2E: "잡음이라 삭제"한 녹음을 다시 넣으니 인식이 한 글자 달랐다 ("레이드 공 빠졌어…" → "레이드 궁 빠졌어…", 교정 사전이 바뀌어 핫워드가 달라짐). 그래서 통째로 같을 때만이 아니라 8글자 이상이면 15% 안 글자 차이까지 같은 문장으로 본다 → `learned` 잡음, 파일 삭제, 타임라인에서 빠짐
- 사이트(목 서버 + 실제 빌드, 브라우저): 우클릭 메뉴 삭제 → 확인 창 → 잡음이라 삭제 → 줄이 사라지고 "앞으로 … 는 잡음으로 거릅니다", 단어사전 "잡음으로 배운 문장"에 추가. 인식된 글이 없으면 "잡음이라 삭제" 꺼짐. 효과음: 저장된 설정이 없으면 새 기본값, 예전 설정(전부 켜짐)은 두 알림만 한 번 끄고, 그 뒤 다시 켠 것은 그대로
- 테스트: 앱 62 · 사이트 서버 16 · 워커 42 통과, 앱 · 화면 · 서버 타입 검사 통과
- 배포: 사이트 서버 다시 배포 (배포된 화면 번들에 "잡음이라 삭제" · `noise-phrases` 확인), Windows CI (3115337, full) 7개 모두 PASS · 앱 버전 1.4.0 → Gitea 릴리스 v1.4.0 (v1.3.9 에 새 버전 안내)
## v1.4.1 — 잡음 문장 비교: 앞뒤에 붙은 실제 말은 지우지 않음 (2026-10-16)
- 원인: v1.4.0 의 "거의 같은 문장"이 편집 거리 15% 였다. 배운 문장 `자막 제공 및 자막을 사용하였습니다`(15글자) 뒤에 `네` · `가자` · `아니`가 붙어도 거리 1~2 라 잡음으로 지워 실제 음성을 잃었다
- 고침: 글자 수가 같고(8글자 이상) 바뀐 글자가 15% 이하일 때만 (실제 엔진에서 본 "레이드 공" / "레이드 궁" 은 그대로 잡음). 글자가 붙거나 빠지면 다른 말
- 테스트 `utterance-delete.test.ts`: 앞뒤에 `네` · `가자` · `아니`를 붙인 문장은 비슷하지 않음, 음성 인식에서 그 발화들의 글 · 음성 파일이 남음 (v1.4.0 코드에서 실패 확인 뒤 고침)

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 609 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -0,0 +1,296 @@
<!doctype html>
<html lang="ko"><head><meta charset="utf-8"><title>겜녹이 v1.3.6 · v1.3.7 수정 보고서</title>
<style>
@page { size: A4; margin: 16mm 15mm 18mm 15mm; }
:root {
--ink: #1b1f27; --muted: #5d6675; --line: #d9dee6; --soft: #f3f5f8;
--accent: #ff4655; --accent2: #0fb5ae; --warn: #f2a516; --dark: #0f1923;
}
* { box-sizing: border-box; }
body { font-family: "Noto Sans CJK KR", "NanumBarunGothic", sans-serif; color: var(--ink);
font-size: 10pt; line-height: 1.6; margin: 0; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
h1, h2, h3 { font-family: "NanumSquare Neo", "Noto Sans CJK KR", sans-serif; line-height: 1.3; }
h2 { font-size: 16pt; margin: 0 0 10px; padding-bottom: 6px; border-bottom: 3px solid var(--dark); }
h2 .num { color: var(--accent); margin-right: 8px; }
h3 { font-size: 11.5pt; margin: 16px 0 6px; color: var(--dark); }
p { margin: 4px 0 8px; }
code, .mono { font-family: "D2Coding ligature", "DejaVu Sans Mono", monospace; font-size: 9pt; }
.page { margin-bottom: 22px; }
.cover { page-break-after: always; }
h2, h3 { break-after: avoid; }
tr, .card, .q, .callout, .arch, .pipe, .row { break-inside: avoid; }
table { width: 100%; border-collapse: collapse; margin: 6px 0 10px; font-size: 9pt; }
th, td { border: 1px solid var(--line); padding: 5px 7px; vertical-align: top; text-align: left; }
th { background: var(--dark); color: #fff; font-weight: 600; }
tr:nth-child(even) td { background: #fafbfc; }
ul { margin: 4px 0 8px; padding-left: 18px; }
li { margin: 2px 0; }
.callout { border-left: 4px solid var(--accent); background: #fff3f4; padding: 8px 12px; margin: 8px 0; border-radius: 0 6px 6px 0; }
.callout.info { border-color: var(--accent2); background: #ecfaf9; }
.callout.warn { border-color: var(--warn); background: #fff8e8; }
.callout b.t { display: block; margin-bottom: 2px; }
.tag { display: inline-block; font-size: 8pt; padding: 1px 6px; border-radius: 9px; background: var(--soft); border: 1px solid var(--line); margin-right: 3px; }
.tag.red { background: #ffe5e7; border-color: #ffb3b9; color: #b0122a; }
.tag.green { background: #e2f7ef; border-color: #a6e3c9; color: #116b47; }
.tag.yellow { background: #fff2cf; border-color: #f5d27a; color: #7a5600; }
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.card { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; background: #fff; }
.card h4 { margin: 0 0 4px; font-size: 10pt; font-family: "NanumSquare Neo", sans-serif; }
.small { font-size: 8.5pt; color: var(--muted); }
/* cover */
.cover { height: 260mm; background: var(--dark); color: #fff; padding: 16mm 18mm; position: relative; overflow: hidden; }
.cover .bar { width: 70px; height: 6px; background: var(--accent); margin-bottom: 18px; }
.cover h1 { font-size: 30pt; margin: 0 0 6px; letter-spacing: -0.5px; }
.cover .sub { font-size: 12pt; color: #c9d1dc; margin-bottom: 12px; }
.cover .meta td { border: none; color: #c9d1dc; padding: 1.5px 12px 1.5px 0; background: transparent !important; font-size: 10pt; }
.cover .meta td:first-child { color: #7f8b99; width: 100px; white-space: nowrap; }
.cover .wave { position: absolute; left: 18mm; right: 18mm; bottom: 40mm; display: flex; align-items: center; gap: 4px; height: 70px; }
.cover .wave span { flex: 1; background: linear-gradient(var(--accent), #ff8a94); border-radius: 3px; opacity: .85; }
.cover .foot { position: absolute; left: 18mm; bottom: 18mm; color: #7f8b99; font-size: 9pt; }
/* architecture diagram */
.arch { border: 2px dashed #9aa6b5; border-radius: 10px; padding: 10px; position: relative; margin-top: 6px; }
.arch .label { position: absolute; top: -10px; left: 12px; background: #fff; padding: 0 6px; font-weight: 700; font-size: 9pt; color: var(--muted); }
.box { border-radius: 7px; padding: 6px 8px; font-size: 8.6pt; border: 1px solid; }
.box b { display: block; font-size: 9pt; }
.b-core { background: #eef2f8; border-color: #b9c6d9; }
.b-stt { background: #ecfaf9; border-color: #94dcd8; }
.b-ui { background: #fff3f4; border-color: #ffb3b9; }
.b-ext { background: #fff8e8; border-color: #f2d083; }
.row { display: flex; gap: 8px; margin: 6px 0; }
.row > * { flex: 1; }
.arrow { text-align: center; color: var(--muted); font-size: 9pt; margin: 2px 0; }
/* pipeline */
.pipe { display: flex; gap: 4px; align-items: stretch; margin: 8px 0; }
.pipe .st { flex: 1; background: var(--soft); border: 1px solid var(--line); border-radius: 6px; padding: 6px; font-size: 8.2pt; position: relative; }
.pipe .st b { display: block; font-size: 8.8pt; color: var(--dark); }
.pipe .st .n { position: absolute; top: -8px; left: 6px; background: var(--accent); color: #fff; border-radius: 8px; font-size: 7.5pt; padding: 0 5px; }
.q { border: 1px solid var(--line); border-radius: 8px; padding: 7px 10px; margin: 6px 0; break-inside: avoid; }
.q .qh { font-weight: 700; font-family: "NanumSquare Neo", sans-serif; }
.q .qh .id { color: #fff; background: var(--accent); border-radius: 5px; padding: 0 6px; margin-right: 6px; font-size: 9pt; }
.q .rec { color: #116b47; font-size: 9pt; }
.q .ans { background:#f6f1e6; border-left:3px solid #c8aa6e; padding:3px 8px; margin:4px 0 3px; border-radius:0 5px 5px 0; font-size:9.2pt; }
.q .ans b { color:#8a6d35; margin-right:4px; }
.toc li { margin: 3px 0; }
/* figures & infographics */
figure { margin: 10px 0 12px; break-inside: avoid; }
figure img.shot { width: 100%; border-radius: 8px; box-shadow: 0 4px 14px rgba(15,25,35,.25); border: 1px solid #263544; display: block; }
figcaption { font-size: 8.5pt; color: var(--muted); margin-top: 5px; }
figcaption b { color: var(--ink); }
.ex { display:inline-block; font-size:7.5pt; background:#eef1f5; border:1px solid var(--line); border-radius:4px; padding:0 5px; margin-left:4px; color:var(--muted); }
.flow { display:flex; align-items:flex-start; margin: 10px 0 6px; position:relative; break-inside: avoid; }
.flow:before { content:""; position:absolute; left:6%; right:6%; top:23px; height:3px; background: linear-gradient(90deg, var(--accent), var(--accent2)); border-radius:2px; }
.flow .s { flex:1; text-align:center; position:relative; padding:0 2px; }
.flow .ic { width:46px; height:46px; border-radius:50%; background:#fff; border:3px solid var(--dark); margin:0 auto 5px; display:flex; align-items:center; justify-content:center; font-size:19px; position:relative; z-index:1; }
.flow .s:nth-child(odd) .ic { border-color: var(--accent); }
.flow .s:nth-child(even) .ic { border-color: var(--accent2); }
.flow .t { font-weight:700; font-size:8.6pt; font-family:"NanumSquare Neo",sans-serif; line-height:1.3; }
.flow .d { font-size:7.6pt; color:var(--muted); line-height:1.35; margin-top:2px; }
.flow .n { position:absolute; top:-4px; left:50%; margin-left:12px; background:var(--dark); color:#fff; font-size:7pt; border-radius:7px; padding:0 4px; z-index:2; }
.stats { display:grid; grid-template-columns: repeat(4, 1fr); gap:8px; margin: 8px 0 10px; break-inside: avoid; }
.stat { background: var(--dark); color:#fff; border-radius:10px; padding:10px 12px; }
.stat .v { font-family:"NanumSquare Neo",sans-serif; font-size:19pt; font-weight:800; line-height:1.1; }
.stat .v small { font-size:10pt; font-weight:700; color:#c9d1dc; margin-left:2px; }
.stat .l { font-size:8pt; color:#c9d1dc; margin-top:3px; line-height:1.35; }
.stat:nth-child(1) .v { color:#ff7a85; } .stat:nth-child(2) .v { color:#4fd8cf; } .stat:nth-child(3) .v { color:#ffc86a; } .stat:nth-child(4) .v { color:#9fc4ff; }
.viz { border:1px solid var(--line); border-radius:10px; padding:10px 12px; background:#fcfcfb; break-inside: avoid; margin: 8px 0 10px; }
.viz .vt { font-weight:700; font-size:9.5pt; font-family:"NanumSquare Neo",sans-serif; margin-bottom:2px; }
.viz .vs { font-size:8pt; color:var(--muted); margin-bottom:6px; }
.legend { display:flex; gap:14px; font-size:8pt; color:#52514e; margin:4px 0 6px; flex-wrap:wrap; }
.legend i { display:inline-block; width:10px; height:10px; border-radius:2px; margin-right:4px; vertical-align:-1px; }
.vbar { display:flex; align-items:center; gap:8px; margin:5px 0; font-size:8.4pt; }
.vbar .lab { width:150px; flex:none; color:#0b0b0b; }
.vbar .lab small { color:#52514e; }
.vbar .track { flex:1; display:flex; gap:2px; height:20px; }
.vbar .seg { height:100%; display:flex; align-items:center; justify-content:center; font-size:7.6pt; color:#fff; white-space:nowrap; overflow:hidden; }
.vbar .seg:first-child { border-radius:4px 0 0 4px; } .vbar .seg:last-child { border-radius:0 4px 4px 0; }
.vbar .tot { width:38px; text-align:right; color:#52514e; font-size:8pt; }
.dtree { display:flex; align-items:stretch; gap:6px; margin:8px 0; break-inside: avoid; }
.dtree .col { flex:1; display:flex; flex-direction:column; align-items:center; gap:4px; }
.dtree .qq { margin:0; width:100%; text-align:center; font-size:8.2pt; padding:6px; background:#fff; border:1.5px solid var(--dark); border-radius:8px; }
.dtree .yes { font-size:7.6pt; color:#b0122a; font-weight:700; }
.dtree .noise { width:100%; text-align:center; background:#eef0f3; color:#5d6675; border:1px dashed #9aa6b5; border-radius:8px; padding:4px; font-size:8pt; font-style:italic; }
.dtree .ar { align-self:center; color:var(--muted); font-size:13pt; margin-top:-26px; }
.dtree .ok { background:#ecfaf9; border:1.5px solid var(--accent2); border-radius:8px; padding:6px; text-align:center; font-size:8.2pt; width:100%; }
.gantt { border:1px solid var(--line); border-radius:10px; padding:10px 12px; background:#fcfcfb; break-inside: avoid; }
.gantt .hd, .gantt .gr { display:grid; grid-template-columns: 170px repeat(12, 1fr); align-items:center; }
.gantt .gr .b.opt2 { background:#c8aa6e; color:#1e1a12; }
.gantt .hd div { font-size:7.8pt; color:#52514e; text-align:center; border-left:1px dashed #e1e4e8; }
.gantt .hd div:first-child { border:none; text-align:left; }
.gantt .gr { height:24px; font-size:8.4pt; }
.gantt .gr .nm { color:#0b0b0b; }
.gantt .gr .b { height:14px; border-radius:4px; background:#2a78d6; color:#fff; font-size:7.4pt; display:flex; align-items:center; padding-left:6px; white-space:nowrap; }
.gantt .gr .b.opt { background: repeating-linear-gradient(45deg,#cfd6df,#cfd6df 4px,#e6eaef 4px,#e6eaef 8px); color:#52514e; }
.shots2 { display:grid; grid-template-columns: 1.7fr 1fr; gap:10px; align-items:start; }
.cover .hero { position:absolute; left:18mm; right:-14mm; top:164mm; height:64mm; overflow:hidden; border-radius:10px; }
.brandrow { display:grid; grid-template-columns: 1fr 3.2fr; gap:12px; align-items:start; margin:8px 0 10px; }
.sw { display:inline-block; width:12px; height:12px; border-radius:3px; vertical-align:-1px; margin-right:6px; border:1px solid #c9d1dc; }
.cover .ban { display:block; width:100%; border-radius:10px; border:1px solid #2f4152; margin:0 0 14px; box-shadow:0 12px 40px rgba(0,0,0,.5); }
.cover .hero img { width:100%; border-radius:10px; box-shadow: 0 20px 60px rgba(0,0,0,.6); border:1px solid #2f4152; }
figure { margin: 8px 0 12px; break-inside: avoid; }
figure img { width: 100%; border: 1px solid var(--line); border-radius: 6px; display: block; }
figcaption { font-size: 8.5pt; color: var(--muted); margin-top: 3px; }
.two { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.legend i { display: inline-block; width: 10px; height: 10px; border-radius: 2px; vertical-align: -1px; margin: 0 3px 0 8px; }
.pb { page-break-before: always; }
td.num { text-align: right; white-space: nowrap; }
</style>
</head><body>
<section class="cover">
<div class="bar"></div>
<h1>겜녹이 수정 보고서</h1>
<div class="sub">v1.3.6 · v1.3.7 — 목소리 깨짐 분석, 요청 사항 반영, 오류 점검</div>
<table class="meta">
<tr><td>작성일</td><td>2026-10-16</td></tr>
<tr><td>대상 버전</td><td>게임 PC 앱 v1.3.7 (v1.3.6 포함) · 사이트 gvr.tkrmagid.kr</td></tr>
<tr><td>릴리스</td><td>git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.7</td></tr>
<tr><td>분석 자료</td><td>사용자가 보낸 GVR-Data (발화 40개 · 데스매치 1경기 · exe 로그) · 사이트 화면 캡처 2장</td></tr>
<tr><td>확인</td><td>앱 테스트 53 · 사이트 서버 16 · 음성 인식 워커 42 통과, Windows 빌드 검사 7개 통과</td></tr>
</table>
<div class="wave"><span style="height:30%"></span><span style="height:55%"></span><span style="height:80%"></span><span style="height:45%"></span><span style="height:95%"></span><span style="height:60%"></span><span style="height:35%"></span><span style="height:70%"></span><span style="height:88%"></span><span style="height:50%"></span><span style="height:25%"></span><span style="height:65%"></span><span style="height:90%"></span><span style="height:40%"></span><span style="height:75%"></span><span style="height:55%"></span><span style="height:30%"></span><span style="height:85%"></span><span style="height:60%"></span><span style="height:45%"></span><span style="height:70%"></span><span style="height:95%"></span><span style="height:50%"></span><span style="height:35%"></span><span style="height:80%"></span><span style="height:60%"></span><span style="height:40%"></span><span style="height:72%"></span><span style="height:92%"></span><span style="height:48%"></span></div>
<div class="foot">Game Voice Recorder · 겜녹이</div>
</section>
<section class="page">
<h2><span class="num">1</span>요약</h2>
<table>
<tr><th style="width:28%">요청 · 문제</th><th style="width:12%">결과</th><th>한 줄 설명</th></tr>
<tr><td>목소리가 깨져서 저장됨</td><td><span class="tag green">고침</span></td><td>녹음기가 패킷 도착 간격으로 쉼을 채워, 게임 중 몰려 온 패킷 사이에 20ms 무음이 계속 끼었다. 디스코드 RTP 시각 기준으로 바꾸고 예전 녹음도 고친다</td></tr>
<tr><td>말한 사람 "알 수 없음"</td><td><span class="tag green">고침</span></td><td>앱이 유저 목록 갱신을 빈 목록으로 보내 사이트 목록이 비었다</td></tr>
<tr><td>잡음만 있으면 표시하지 않기 · ogg 삭제 · 로그에 잡음</td><td><span class="tag green">완료</span></td><td>사이트에 안 보이고 파일도 지운다. 로그에 "잡음 발화 … 숨김 · 음성 파일 삭제 (이유, 인식 문장)"</td></tr>
<tr><td>켜는 중 작은 창</td><td><span class="tag green">완료</span></td><td>포터블 exe 를 푸는 동안 그림 창, 앱이 켜지는 동안 "켜는 중" 창</td></tr>
<tr><td>녹음 안내 TTS 속도 0.1~2.0</td><td><span class="tag green">완료</span></td><td>디스코드 탭 "말 속도". 0.5배보다 느린 부분은 음성 인식 엔진이 늘린다</td></tr>
<tr><td>사이트 재생 음량</td><td><span class="tag green">완료</span></td><td>플레이어 막대 0~200%, 음소거</td></tr>
<tr><td>사이트 로그 (게임 PC 꺼져도)</td><td><span class="tag green">완료</span></td><td>gvr.tkrmagid.kr/logs (관리자), 날짜별 보기 · 내려받기, 14일 보관</td></tr>
<tr><td>우클릭 → 자세한 정보 · 다운로드</td><td><span class="tag green">완료</span></td><td>원본 ogg 이름 · 게임 PC 경로 · 크기 · 인식 정보, ogg 다운로드</td></tr>
<tr><td>지금 게임 자세한 정보 (앱 · 사이트)</td><td><span class="tag green">완료</span></td><td>상태 · 모드 · 맵 · 라운드 · 점수 · 내 요원/챔피언 · KDA · 게임 시간</td></tr>
<tr><td>경기별 묶어 관리 · 경기 전후 대화 묶음</td><td><span class="tag green">완료</span></td><td>사이트 "기록" 탭. 한 번에 지우기 · zip 내려받기 · zip 받아오기(빠진 내용이 있으면 실패)</td></tr>
<tr><td>분석 중 찾은 문제</td><td><span class="tag green">고침</span></td><td>데스매치 가짜 라운드 · 에이스, 빈 선수 이름("주인 계정 자동 연결: #")</td></tr>
<tr><td>전체 코드 검토로 찾은 오류 8개 + 5개</td><td><span class="tag green">고침</span></td><td>관리자 확인 우회, 큰 zip 전송 중 연결 끊김, 진행 중 경기 지우기 등 (6장)</td></tr>
</table>
</section>
<section class="page pb">
<h2><span class="num">2</span>목소리 깨짐 분석</h2>
<h3>보내 주신 파일에서 본 것</h3>
<p>ogg 파일을 패킷(20ms) 단위로 열어 보니, 게임 중 파일은 거의 모두 "목소리 2개 → 무음 1개"가 되풀이되었다. 아래는 "S매치 되는지 한번 해봐야겠다…" 발화의 앞 200개 패킷이다.</p>
<figure><img src="img/packets.png"><figcaption class="legend"><i style="background:#14aaa0"></i>목소리 패킷 <i style="background:#e63c46"></i>녹음기가 끼워 넣은 무음 (가운데 긴 빨간 부분은 실제로 말을 쉰 곳)</figcaption></figure>
<table>
<tr><th>파일</th><th class="num">파일 길이</th><th class="num">끼운 무음</th><th class="num">고친 뒤</th></tr>
<tr><td>"S매치 되는지 한번 해봐야겠다…" (경기 전)</td><td class="num">8.48초</td><td class="num">132개 (2.64초)</td><td class="num">7.32초</td></tr>
<tr><td>"…게임을 좀 해봐오면…" (경기 중)</td><td class="num">6.40초</td><td class="num">117개</td><td class="num">5.02초</td></tr>
<tr><td>"…홈 워치카라드 런던 키위드" (경기 중)</td><td class="num">4.64초</td><td class="num">69개</td><td class="num">3.54초</td></tr>
<tr><td>"운동을 싫어하면 별로 안 맞네" (경기 중)</td><td class="num">6.50초</td><td class="num">143개</td><td class="num">5.38초</td></tr>
</table>
<h3>원인</h3>
<p>디스코드는 말하는 동안 20ms 마다 패킷을 보낸다. 녹음기는 "앞 패킷이 도착한 뒤 흐른 시간"으로 빈 자리를 무음으로 채웠다. 그런데 게임 중에는 PC 부하로 패킷이 2~3개씩 몰려 도착한다. 녹음기는 몰려 오기 전의 기다림을 쉼으로 보고 무음을 넣었다. 그래서 말 사이사이에 20ms 구멍이 계속 생겼고 소리가 늘어났다. 실제 수신 시간은 약 7.0초인데 파일은 8.5초였다.</p>
<figure><img src="img/wave-compare.png" style="width:82%;margin:0 auto"><figcaption>같은 발화 앞 1.6초 (음량 키움). 위: 저장된 파일 (끊김), 아래: 끼운 무음을 뺀 것</figcaption></figure>
<h3>고친 방법</h3>
<ul>
<li>디스코드가 패킷마다 붙여 보내는 시각(RTP 타임스탬프)으로 패킷 자리를 정한다. 도착이 몰리거나 늦어도 소리가 늘어나지 않는다. 중복 패킷은 버리고, 시각이 튀면 다시 맞춘다.</li>
<li>예전 녹음은 v1.3.7 을 처음 켤 때 한 번 고친다. 앞뒤가 목소리인 1~3개짜리 무음 묶음을 빼고, 정밀 모델로 다시 글자로 바꾼다. 업그레이드 전에 만든 녹음만 고치고, 20개씩 나눠 처리한다. 중간에 꺼져도 다음에 이어서 한다. 다시 인식한 결과가 잡음이면 원래 글을 그대로 둔다.</li>
</ul>
<h3>인식 결과 비교 (같은 Whisper large-v3 로 다시 인식)</h3>
<table>
<tr><th style="width:50%">저장된 파일 (깨짐)</th><th>끼운 무음을 뺀 파일</th></tr>
<tr><td>이제 게임을 좀 해봐봐 스태스트랜 맛있긴 하네</td><td>실제로 게임을 좀 해봐오면서 테스트를 했는데 맛있긴 하네</td></tr>
<tr><td>왜는 리플레이가 귀하다</td><td>이거는 리플레이가 없긴 하다</td></tr>
<tr><td>이거 시험은 별로 안 맞네</td><td>이만큼만 시도하면 별로 안 맞네</td></tr>
</table>
</section>
<section class="page pb">
<h2><span class="num">3</span>말한 사람 "알 수 없음" · 잡음</h2>
<h3>"알 수 없음"</h3>
<p>녹음 기록에는 말한 사람(사금향)이 제대로 저장되어 있었다. 녹음 시작, 경기 끝, Riot ID 저장 때 앱이 사이트에 "유저 목록이 바뀌었음"을 보낸다. 이때 목록을 빈 목록으로 보냈고, 사이트는 그 빈 목록으로 유저 목록을 덮어썼다. 그래서 새로 고침 전까지 모든 발화가 "알 수 없음"으로 나왔다. 이제 실제 목록을 보낸다. 사이트도 빈 목록을 받으면 목록을 다시 받아 온다.</p>
<h3>잡음</h3>
<ul>
<li>보내 주신 잡음 19개를 음성 검출기로 다시 쟀다. 모두 목소리 0초였다. 이런 소리를 Whisper 에 그냥 넣으면 "시청해주셔서 감사합니다", "자막 제공 배달의민족" 같은 문장을 지어낸다. 그래서 판정은 맞았다.</li>
<li>이제 잡음은 사이트에 보이지 않고 ogg 도 지운다. 경기 중 실시간 판정은 경기가 끝난 뒤 정밀 모델로 다시 확인하고 나서 지운다.</li>
<li>로그 예: <code>잡음 발화 0mv9… 숨김 · 음성 파일 삭제 (사금향, 0.6초, 잡음에서 지어낸 문장, 인식 "자막 제공 배달의민족")</code></li>
<li>목소리가 0.15초만 있어도 인식을 돌린다. 예전에는 길이 대비 비율도 봐서, 긴 잡음 속 짧은 한마디가 버려졌다.</li>
<li>Whisper 가 같은 말을 되풀이하는 오류("페이스페이스페이스…")는 한 번으로 줄여 남은 말을 보여 준다. 숫자("1000원")나 붙어 있는 한 글자 반복은 줄이지 않는다.</li>
</ul>
<h3>데스매치 · 선수 이름 (분석 중 찾은 문제)</h3>
<ul>
<li>데스매치는 점수가 킬 수다. 앱은 이 점수를 라운드로 착각해 "R10 · R22 · R63 승리" 같은 가짜 라운드를 만들었다. 경기 상세에서는 344킬이 "라운드 1" 하나에 들어가서 에이스(한 라운드 5킬)가 11개 생겼다. 이제 데스매치, 팀 데스매치, 에스컬레이션에는 라운드와 에이스를 만들지 않는다.</li>
<li>Riot 경기 상세에 선수 이름이 비어 와서 로그에 "주인 계정 자동 연결: #"이 남았다. 이제 이름 서비스로 채우고, 내 이름은 Riot 클라이언트에서 받는다. 이름이 비어 있으면 계정을 연결하지 않는다.</li>
</ul>
</section>
<section class="page pb">
<h2><span class="num">4</span>기록 관리 (경기별 묶음 · zip)</h2>
<p>사이트 상단 <b>기록</b> 탭에서 녹음을 묶음 단위로 보고 관리한다.</p>
<ul>
<li><b>묶는 규칙</b>
<ul>
<li>경기 하나가 묶음 하나다.</li>
<li>경기 밖 대화는 녹음 세션 안에서 경기 사이마다 하나로 묶는다.</li>
<li>다음 경기가 30분 안에 시작하면 <b>경기 전 대화</b>, 지난 경기가 30분 안에 끝났으면 <b>경기 후 대화</b>, 둘 다 아니면 <b>게임 밖 대화</b>다.</li>
<li>보내 주신 데이터로 확인한 결과: 경기 전 대화 7개 → 데스매치 11개 → 경기 후 대화 3개.</li>
</ul></li>
<li><b>기록 보기</b>: 경기는 경기 타임라인으로, 대화 묶음은 그 시간대의 "게임 외 대화"로 이동한다.</li>
<li><b>한 번에 zip 내려받기</b>: 묶음 여러 개를 골라 zip 하나로 받는다. zip 에는 <code>manifest.json</code>, <code>data.json</code>, <code>audio/발화ID.ogg</code>, <code>대화.txt</code>(시각 · 이름 · 내용)가 들어 있다. 한 번에 음성 280MB 까지 받는다.</li>
<li><b>한 번에 지우기</b> (관리자만): 발화, 음성 파일, 경기 기록(킬 · 라운드 · 범인 분석)을 함께 지운다. 진행 중인 경기는 지울 수 없다. 지우기 전에 확인 창에서 "먼저 zip 받기"를 할 수 있다.</li>
<li><b>받아오기</b> (관리자만): 받아 둔 zip 을 그대로 넣으면 기록이 다시 추가된다. 이미 있는 발화는 건너뛴다. 받아온 녹음의 보관 기간(7일)은 받아온 날부터 센다.</li>
</ul>
<div class="callout warn"><b class="t">받아오기 실패 조건 (하나라도 해당하면 아무것도 넣지 않음)</b>
zip 이 아님 · 손상 · 암호 · manifest.json 없음 · 겜녹이 형식(gvr-bundle)이 아님 · 모르는 형식 버전 · data.json 없음 · 발화 · 유저 목록 없음 · 발화 ID 잘못됨 · 중복 · 말한 사람이 유저 목록에 없음 · 시각 잘못됨 · 경기 묶음인데 경기 기록 없음 · 이벤트의 경기 없음 · 음성 파일이 zip 에 없음 · ogg 가 아님 · manifest 의 발화 수와 다름 · 300MB 초과</div>
<figure><img src="img/7-records.jpg"><figcaption>기록 탭: 날짜별 묶음, 묶음마다 기록 보기 · zip · 지우기, 날짜 전체 선택</figcaption></figure>
<div class="two">
<figure><img src="img/8-records-delete.jpg"><figcaption>골라서 한 번에 지우기 확인 창</figcaption></figure>
<figure><img src="img/9-records-import-fail.jpg"><figcaption>필요한 내용이 없는 zip → "받아오기 실패: (이유)"</figcaption></figure>
</div>
</section>
<section class="page pb">
<h2><span class="num">5</span>그 밖의 요청</h2>
<div class="two">
<figure><img src="img/splash.jpg"><figcaption>켜는 중 창 (포터블 exe 는 압축을 푸는 동안 같은 그림 창)</figcaption></figure>
<figure><img src="img/6-app-tts.jpg"><figcaption>디스코드 탭 "말 속도" 0.1~2.0배</figcaption></figure>
</div>
<figure><img src="img/2-context.jpg"><figcaption>발화 우클릭 메뉴 · 플레이어 막대 재생 음량(오른쪽 아래) · 머리글 지금 게임 · 오른쪽 게임 상태</figcaption></figure>
<div class="two">
<figure><img src="img/3-info.jpg"><figcaption>자세한 정보: 원본 ogg 이름 · 게임 PC 경로(복사) · 크기 · 인식 정보 · 원본 다운로드</figcaption></figure>
<figure><img src="img/4-logs.jpg"><figcaption>사이트 로그 (/logs): 게임 PC 연결 · 끊김, 요청 결과, 봇, 화면 오류. 전체 · 경고 이상 · 오류만, 찾기, 내려받기</figcaption></figure>
</div>
<figure><img src="img/5-app-games.jpg"><figcaption>앱 게임 연동 탭 "지금 게임"</figcaption></figure>
<p class="small">사이트 로그에는 게임 PC 연결 · 끊김(이유), 정보(버전 · 서버), 기록 요청(주소 · 결과 · 걸린 시간 · 누가), 응답 없는 요청, 겜녹이 봇 중계, 범인찾기, 브라우저 화면 오류가 남는다. 로그인 code · 검색어 같은 쿼리 값은 남기지 않는다. 문제가 생기면 이 로그와 게임 PC 의 <code>GVR-Data\logs\gvr-날짜.log</code> 를 같이 보내면 된다.</p>
</section>
<section class="page pb s6">
<h2><span class="num">6</span>오류 점검 (전체 코드 검토)</h2>
<style>.s6 table{font-size:8.3pt}.s6 td,.s6 th{padding:3px 6px}</style><p>v1.3.6 · v1.3.7 에서 바뀐 코드 약 3,600줄을 다시 검토했다. 실제 오류 8개와 작은 문제 5개를 찾아 모두 고쳤고, 고친 내용마다 테스트를 넣었다.</p>
<table>
<tr><th style="width:4%">#</th><th style="width:22%">문제</th><th style="width:40%">어떻게 생기나</th><th>고친 것</th></tr>
<tr><td>1</td><td>기록 지우기 관리자 확인 우회</td><td>주소를 <code>/api/%62undles/delete</code> 처럼 %인코딩하면 사이트 서버의 확인을 건너뛰고 게임 PC 가 지웠다</td><td>주소를 풀어서 확인하고, 게임 PC 도 사이트가 붙인 역할로 한 번 더 확인한다. 우회 주소 4가지가 403 인 것을 테스트로 확인했다</td></tr>
<tr><td>2</td><td>큰 zip 을 주고받을 때 연결이 끊김</td><td>조각이 쌓여 확인 신호(pong)가 20초 넘게 밀리면 앱이 사이트 연결을 스스로 끊었다</td><td>무엇이든 받으면 연결이 살아 있는 것으로 본다. 보낼 것이 4MB 넘게 쌓이면 기다린다. 20MB zip 이 오가는 것을 테스트로 확인했다</td></tr>
<tr><td>3</td><td>진행 중인 경기 지우기</td><td>경기가 끝날 때 할 일(정밀 변환 · 경기 상세)이 경기를 못 찾아 멈췄다</td><td>진행 중인 경기는 지울 수 없게 했다 (화면에 "● 진행 중" 표시)</td></tr>
<tr><td>4</td><td>다시 넣을 수 없는 zip</td><td>내보내기에는 한도가 없고 받아오기는 300MB 까지라, "먼저 zip 받기" 뒤에 지우면 되살리지 못할 수 있었다</td><td>음성이 280MB 를 넘으면 나눠 받으라고 안내한다</td></tr>
<tr><td>5</td><td>예전 녹음 고치기가 결과를 나쁘게 덮음</td><td>정밀 모델 결과를 실시간 모델 결과로 덮었다. 잡음으로 나오면 파일을 지웠다. 켤 때 한꺼번에 처리했다</td><td>정밀 모델로만 다시 변환하고, 잡음이면 원래 결과를 둔다. 20개씩 처리하고, 중간에 꺼져도 이어서 한다</td></tr>
<tr><td>6</td><td>타임라인 순서</td><td>최신순 목록에서 오래된 발화가 고쳐지면 맨 아래에 붙었다. "더 보기"를 누르면 같은 발화가 두 번 나왔다</td><td>더 불러올 페이지가 남아 있으면 넣지 않는다</td></tr>
<tr><td>7</td><td>반복 줄이기가 숫자를 망가뜨림</td><td>"1000원 줘 줘 줘" → "10원 줘", "www" → "w"</td><td>숫자와 붙은 한 글자 반복은 그대로 둔다</td></tr>
<tr><td>8</td><td>TTS 속도 파일이 반쪽으로 남음</td><td>변환 중 엔진이 죽으면 반쪽 파일이 계속 안내 음성으로 쓰였다</td><td>다 만든 뒤에만 파일 이름을 바꾼다</td></tr>
<tr><td>+</td><td>작은 문제 5개</td><td colspan="2">브라우저 오류 로그에 검색어가 남던 것 · 경기 끝 직후 늦게 끝난 실시간 변환의 잡음 파일을 정밀 확인 전에 지우던 것 · 많이 골랐을 때 내려받기 주소가 너무 길던 것 · zip 풀기 메모리 한도(600MB) · 경기 · 기록 목록의 날짜가 "10월"로만 묶이던 것</td></tr>
</table>
<h3>확인</h3>
<table>
<tr><th>항목</th><th>결과</th></tr>
<tr><td>앱 테스트</td><td>53개 통과 (녹음기 RTP · 예전 녹음 고치기 · 유저 목록 · 잡음 · TTS 속도 · 지금 게임 · 데스매치 · 기록 묶음 5개 · 실제 음성 인식 엔진 E2E)</td></tr>
<tr><td>사이트 서버 테스트</td><td>16개 통과 (사이트 로그 · 큰 zip 중계 · 관리자 확인 우회 차단 포함)</td></tr>
<tr><td>음성 인식 워커 테스트</td><td>42개 통과 (잡음 규칙 · 반복 줄이기 · TTS 속도)</td></tr>
<tr><td>화면</td><td>사이트 · 앱 화면을 띄워 확인, 화면 오류 없음</td></tr>
<tr><td>Windows 빌드 검사</td><td>7개 통과 (워커 테스트 · STT · 워커 exe · 앱 빌드 · 앱 실행)</td></tr>
<tr><td>사용자 데이터 사본</td><td>예전 녹음 43개 고치기 (끼운 무음 489개 제거), 기록 묶음 3개 → zip 1.0MB</td></tr>
</table>
<div class="callout info"><b class="t">아직 실제로 확인하지 못한 것</b>새 녹음 방식(RTP 기준)은 실제 디스코드 통화가 있는 Windows 게임 PC 에서 아직 돌려 보지 못했다. 테스트는 사용자 파일과 같은 도착 모양을 흉내 내서 했다. 한 판 해 보고 목소리가 깨끗한지 확인해 주세요.</div>
</section>
</body></html>

View File

@@ -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';

View 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;
}

View File

@@ -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,80 @@ 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;
}
/** 기록 묶음 (사이트 기록 관리, v1.3.7~): 경기 하나 또는 경기 밖 대화 한 덩어리 */
export interface BundleInfo {
/** match-<경기ID> 또는 talk-<첫 발화ID> */
id: string;
kind: 'match' | 'talk';
/** "발로란트 · 경쟁전 · 어센트" · "경기 전 대화" · "경기 후 대화" · "게임 밖 대화" */
label: string;
/** 경기: "승리 13:9", 대화: "다음 경기: 발로란트 어센트" */
sub: string | null;
game: GameType | null;
matchId: string | null;
from: number;
to: number;
/** 보이는 발화 수 (잡음 뺌) */
utterances: number;
/** 음성 파일이 남은 발화 수 */
audio: number;
audioBytes: number;
/** 경기 이벤트 수 (킬 · 라운드 …) */
events: number;
talkMs: number;
users: string[];
/** 진행 중인 경기 (지울 수 없음) */
live: boolean;
}
export interface BundleImportResult {
bundles: string[];
added: { utterances: number; audio: number; matches: number; events: number; users: number };
/** 이미 있어서 건너뛴 발화 */
skipped: 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 +425,20 @@ 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[] }
| { type: 'records.changed'; data: { reason: 'deleted' | 'imported'; ids?: string[] } }
/** 사이트 우클릭으로 발화 하나를 지움 (v1.4.0). noise = "잡음이라 삭제" */
| { type: 'utterance.deleted'; data: { id: string; noise: boolean } };
/** "잡음이라 삭제"로 배운 문장 (GET /api/noise-phrases) */
export interface NoisePhrase {
id: number;
text: string;
/** 그 뒤로 이 문장을 잡음으로 걸러 낸 횟수 */
hits: number;
createdAt: number;
}
export interface DeviceStatus {
registered: boolean;
@@ -342,6 +460,8 @@ export type RelayToDevice =
headers: Record<string, string>;
user: { id: string; name: string; avatar: string | null } | null;
body: string | null;
/** 본문이 바이너리(zip 등)면 true. 본문은 이 메시지 앞에 같은 id 의 바이너리 조각으로 먼저 온다 (v1.3.7~) */
bin?: boolean;
}
| { t: 'cancel'; id: string }
| { t: 'pong'; ts: number }

View File

@@ -0,0 +1,25 @@
// 실제 디스코드: DiscordSource(사이트 서버 코드)로 봇을 음성채널에 넣었다 빼며 상태 메시지가 바뀌는지 본다
import { Client, GatewayIntentBits } from 'discord.js';
import { DiscordSource } from '../src/discord-source.ts';
// 사용: TB=<봇 토큰> GUILD=<서버 아이디> VC=<빈 음성채널 아이디> node --import tsx scripts/presence-e2e.mts
const G = process.env.GUILD!, VC = process.env.VC!;
const t0 = Date.now();
const at = () => `${((Date.now() - t0) / 1000).toFixed(1)}s`;
const log = { info: (o: any, m?: string) => console.log(at(), 'LOG', m, JSON.stringify(o)), error: (o: any, m?: string) => console.log(at(), 'ERR', m, o?.message ?? o) };
const src = new DiscordSource(log);
// 관찰자: 같은 서버의 다른 세션이 디스코드에서 받은 봇 상태 (presence intent 가 있으면)
const obs = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMembers] });
obs.on('presenceUpdate', (_o, n) => n.userId === src.client.user?.id && console.log(at(), 'OBSERVED', n.status, JSON.stringify(n.activities.map((a) => a.state))));
await src.login(process.env.TB!);
await new Promise((r) => src.once('ready', r));
await obs.login(process.env.TB!).catch((e) => console.log('observer off:', e.message));
await new Promise((r) => setTimeout(r, 3000));
const send = (ch: string | null) => src.voiceAdapter(G, { server: () => undefined, state: () => undefined }).send({ op: 4, d: { guild_id: G, channel_id: ch, self_mute: true, self_deaf: true } });
console.log(at(), 'JOIN'); send(VC);
await new Promise((r) => setTimeout(r, 5000));
console.log(at(), 'presence now', src.client.user!.presence.status, JSON.stringify(src.client.user!.presence.activities.map((a) => a.state)), 'inVoice', !!src.client.guilds.cache.get(G)!.members.me!.voice.channelId);
console.log(at(), 'LEAVE'); send(null);
await new Promise((r) => setTimeout(r, 5000));
console.log(at(), 'presence now', src.client.user!.presence.status, JSON.stringify(src.client.user!.presence.activities.map((a) => a.state)), 'inVoice', !!src.client.guilds.cache.get(G)!.members.me!.voice.channelId);
await obs.destroy().catch(() => undefined);
await src.destroy();

View File

@@ -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)};`);

View File

@@ -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) => {
@@ -188,11 +243,24 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
const origin = String(req.headers.origin || '');
if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' });
}
// 기록 묶음 지우기 · 받아오기는 관리자만 (보기 · zip 내려받기는 서버 멤버 누구나)
// 주소는 풀어서(%62undles 같은 우회 막기) 소문자로 본다. 앱도 역할 헤더로 한 번 더 막는다
let p: string;
try {
p = decodeURIComponent(req.url.split('?')[0]).toLowerCase();
} catch {
return reply.code(400).send({ error: 'bad_path' });
}
const bundles = p.startsWith('/api/bundles');
const admin = canViewLogs(s.user.id);
if (bundles && p !== '/api/bundles' && p !== '/api/bundles/export' && !admin) return reply.code(403).send({ error: 'forbidden', message: '기록 지우기 · 받아오기는 관리자만 할 수 있습니다' });
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = String(req.headers[k]);
const body = req.body === undefined || req.body === null ? null : typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
headers['x-gvr-role'] = admin ? 'admin' : 'member';
const body = req.body === undefined || req.body === null ? null : Buffer.isBuffer(req.body) || typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
try {
const r = await hub.request(req.method, req.url, headers, s.user, body);
// zip 만들기 · 받아오기는 오래 걸릴 수 있다
const r = await hub.request(req.method, req.url, headers, s.user, body, bundles ? 180000 : 20000);
for (const [k, v] of Object.entries(r.headers)) if (k !== 'content-length') reply.header(k, v);
return reply.code(r.status).send(r.body);
} catch (e: any) {
@@ -200,6 +268,8 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
return reply.code(504).send({ error: 'timeout' });
}
};
// zip 받아오기 본문 (300MB 까지)
app.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body));
app.route({ method: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'], url: '/api/*', handler: relay });
// ------------------------------------------------------------------ 게임 이미지 캐시 (보고서 7-7)
@@ -226,7 +296,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 +354,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/* 는 쿼리를 지우고 앱 로그인 요청 아이디를 가린다, 다른 주소도 쿼리 값은 지운다 */

View File

@@ -302,7 +302,14 @@ export class BotBroker {
/** 슬래시 명령을 맞는 앱으로 보내고 첫 응답을 돌려준다 */
private async onCommand(cmd: BotCommand): Promise<string> {
const here = [...this.conns].filter((c) => c.guildId === cmd.guildId).sort((a, b) => b.at - a.at);
if (!here.length) return '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.';
if (!here.length) {
// 명령한 사람의 앱이 켜져 있는데 다른 서버를 녹음 대상으로 잡아 둔 경우를 알려 준다
const own = [...this.conns].filter((c) => c.userId === cmd.user.id);
this.log.info({ guild: cmd.guildId, user: cmd.user.id, cmd: cmd.name, apps: this.conns.size, own: own.map((c) => c.guildId) }, '슬래시 명령: 이 서버를 지켜보는 앱 없음');
if (own.some((c) => c.guildId)) return '내 겜녹이 앱이 다른 디스코드 서버를 녹음 대상으로 정해 두었습니다. 게임 PC 의 겜녹이 설정 → 디스코드 → "녹음할 서버"를 이 서버로 바꿔 주세요.';
if (own.length) return '내 겜녹이 앱이 이 서버에 아직 연결되지 않았습니다. 잠시 뒤 다시 시도하거나, 겜녹이 설정 → 디스코드에서 "녹음할 서버"를 확인해 주세요.';
return '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다. 게임 PC 에서 겜녹이를 켜고 로그인해 주세요.';
}
const owner = this.owners.get(cmd.guildId)?.conn;
const mine = here.find((c) => c.userId === cmd.user.id);
let targets: Conn[];

View File

@@ -1,6 +1,6 @@
// 서버의 겜녹이 봇 디스코드 연결 (discord.js). bot-broker.ts 의 BotSource 구현
import { EventEmitter } from 'node:events';
import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, PermissionFlagsBits, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
import { ActivityType, ChannelType, Client, Events, GatewayIntentBits, MessageFlags, PermissionFlagsBits, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
import type { BotGwChannel, BotGwGuild, BotGwMember } from '@gvr/shared';
import type { BotCommand, BotSource, BotVoiceEvent } from './bot-broker.js';
@@ -14,6 +14,13 @@ export const COMMANDS = [
const member = (m: GuildMember): BotGwMember => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }), bot: m.user.bot });
const guild = (g: Guild): BotGwGuild => ({ id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) });
/** 봇 상태 메시지: 어느 서버에서든 음성채널에 들어가 있으면(= 녹음 중) 빨간 "녹음 중", 아니면 대기 */
export function botPresence(recording: boolean) {
return recording
? { status: 'dnd' as const, activities: [{ type: ActivityType.Custom, name: 'custom', state: '🔴 녹음 중' }] }
: { status: 'online' as const, activities: [{ type: ActivityType.Custom, name: 'custom', state: '🎙️ 대기 중 · /녹음시작' }] };
}
const isVoice = (c: { type: ChannelType } | null | undefined): c is VoiceBasedChannel => !!c && (c.type === ChannelType.GuildVoice || c.type === ChannelType.GuildStageVoice);
export class DiscordSource extends EventEmitter implements BotSource {
@@ -26,6 +33,8 @@ export class DiscordSource extends EventEmitter implements BotSource {
this.client = c;
c.on(Events.ClientReady, () => {
log.info({ bot: c.user?.tag, guilds: c.guilds.cache.size }, '겜녹이 봇 디스코드 연결');
this.recording = null;
this.updatePresence();
this.emit('ready');
});
c.on(Events.GuildCreate, () => this.emit('guilds'));
@@ -41,6 +50,7 @@ export class DiscordSource extends EventEmitter implements BotSource {
c.on(Events.GuildDelete, () => this.emit('guilds'));
c.on(Events.Error, (e) => log.error(e, '디스코드 오류'));
c.on(Events.VoiceStateUpdate, (o, n) => {
if (n.id === c.user?.id) this.updatePresence();
const m = n.member ?? o.member;
if (!m) return;
const ch = n.channel;
@@ -49,10 +59,14 @@ export class DiscordSource extends EventEmitter implements BotSource {
});
c.on(Events.InteractionCreate, async (i) => {
if (!i.isChatInputCommand() || !i.guildId || !COMMANDS.some((x) => x.name === i.commandName)) return;
if (this.wants && !this.wants(i.guildId)) return;
// 이 서버를 지켜보는 앱이 없으면 1.5초 기다렸다가 응답한다: 봇 토큰을 직접 쓰는 옛 PC(v1.1.0)가 먼저 받았으면
// 그쪽 응답을 그대로 두고(아래 deferReply 가 '이미 응답함'으로 실패), 아무도 받지 않았으면 이유를 알려 준다.
// (예전에는 그냥 무시해서 디스코드에 "애플리케이션이 응답하지 않았어요"만 떴다)
if (this.wants && !this.wants(i.guildId)) await new Promise((r) => setTimeout(r, 1500));
try {
await i.deferReply({ flags: MessageFlags.Ephemeral });
} catch (e) {
} catch (e: any) {
if (e?.code === 40060 || e?.code === 'InteractionAlreadyReplied') return;
log.error(e, '명령 응답 실패');
return;
}
@@ -68,6 +82,18 @@ export class DiscordSource extends EventEmitter implements BotSource {
});
}
private recording: boolean | null = null;
/** 봇이 어느 서버에서든 음성채널에 있으면 녹음 중으로 상태 메시지를 바꾼다 */
private updatePresence(): void {
const c = this.client;
if (!c.isReady()) return;
const on = c.guilds.cache.some((g) => !!g.members.me?.voice.channelId);
if (on === this.recording) return;
this.recording = on;
c.user.setPresence(botPresence(on));
this.log.info({ recording: on }, '봇 상태 메시지 변경');
}
login(token: string): Promise<string> {
return this.client.login(token);
}

View File

@@ -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 가 알아서 다시 연결)

View File

@@ -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;
@@ -177,15 +188,36 @@ export class RelayHub {
}
/** 브라우저 요청 하나를 게임 PC 로 넘긴다 */
request(method: string, path: string, headers: Record<string, string>, user: { id: string; name: string; avatar: string | null }, body: string | null, timeoutMs = 20000): Promise<RelayResponse> {
request(method: string, path: string, headers: Record<string, string>, user: { id: string; name: string; avatar: string | null }, body: string | Buffer | null, timeoutMs = 20000): Promise<RelayResponse> {
const dev = this.device;
if (!dev || !this.status().online) return Promise.reject(new Error('device_offline'));
const id = crypto.randomBytes(8).toString('hex');
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (this.pending.delete(id)) reject(new Error('timeout'));
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: [] });
if (Buffer.isBuffer(body)) {
// 바이너리 본문(zip 받아오기): 1MB 조각으로 먼저 보내고 요청을 보낸다 (앱은 한 메시지 8MB 까지).
// 보낼 것이 4MB 넘게 쌓이면 기다려서 ping · pong 이 너무 밀리지 않게 한다
const idBuf = Buffer.from(id, 'utf8');
const head = Buffer.alloc(4);
head.writeUInt32BE(idBuf.length, 0);
const CH = 1024 * 1024;
void (async () => {
for (let i = 0; i < body.length; i += CH) {
while (dev.ws.readyState === WebSocket.OPEN && dev.ws.bufferedAmount > 4 * CH) await new Promise((r) => setTimeout(r, 20));
if (dev.ws.readyState !== WebSocket.OPEN) return;
dev.ws.send(Buffer.concat([head, idBuf, body.subarray(i, i + CH)]), { binary: true });
}
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body: null, bin: true };
dev.ws.send(JSON.stringify(msg));
})();
return;
}
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body };
dev.ws.send(JSON.stringify(msg));
});

109
site/server/src/site-log.ts Normal file
View 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;
}

View File

@@ -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 {
@@ -99,6 +99,12 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
local.get('/api/timeline', async (req) => ({ items: [], next: null, user: req.headers['x-gvr-user'] }));
local.get('/api/audio/:id', async (_req, reply) => reply.header('content-type', 'audio/ogg').send(Buffer.from('OggS' + 'x'.repeat(5000))));
local.patch('/api/utterances/:id', async (req) => ({ ok: true, body: req.body }));
// 큰 zip (20MB: 한 메시지 한도 16MB 넘음) 내보내기 · 받아오기
const big = Buffer.alloc(20 * 1024 * 1024);
for (let i = 0; i < big.length; i += 4096) big[i] = (i / 4096) & 0xff;
local.get('/api/bundles/export', async (_req, reply) => reply.header('content-type', 'application/zip').header('content-disposition', 'attachment; filename="gvr-test.zip"').send(big));
local.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body));
local.post('/api/bundles/import', async (req) => ({ size: (req.body as Buffer).length, same: (req.body as Buffer).equals(big) }));
const bus = new Bus();
const rc = new RelayClient(local as any, bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: '1.0.0', guildId: '222' }));
rc.start();
@@ -121,6 +127,18 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
const au = await fetch(base + '/api/audio/abc', { headers: { cookie: sid } });
assert.equal(au.headers.get('content-type'), 'audio/ogg');
assert.equal((await au.arrayBuffer()).byteLength, 5004);
// 큰 zip 내보내기: 조각으로 나눠 와서 그대로 붙는다 (content-disposition 도 전달)
const ex = await fetch(base + '/api/bundles/export?ids=match-1', { headers: { cookie: sid } });
assert.equal(ex.headers.get('content-disposition'), 'attachment; filename="gvr-test.zip"');
assert.ok(Buffer.from(await ex.arrayBuffer()).equals(big));
// 받아오기 · 지우기는 관리자만 (주소를 %인코딩해 돌아가도 막힌다)
for (const u of ['/api/bundles/delete', '/api/%62undles/delete', '/api/BUNDLES/delete', '/api/bundles%2Fdelete'])
assert.equal((await fetch(base + u, { method: 'POST', headers: { cookie: sid, 'content-type': 'application/json', origin: cfg.publicUrl }, body: '{"ids":["x"]}' })).status, 403, u);
assert.equal((await fetch(base + '/api/bundles/import', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/zip', origin: cfg.publicUrl }, body: big })).status, 403);
store.upsertAppUser({ id: 'member1', name: '하늘', avatar: null, role: 'admin', addedBy: 'test' });
const im = (await (await fetch(base + '/api/bundles/import', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/zip', origin: cfg.publicUrl }, body: big })).json()) as any;
assert.deepEqual(im, { size: big.length, same: true });
store.setAppUserRole('member1', 'user');
// 쓰기 요청: 다른 사이트 Origin 은 거절
assert.equal((await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: 'https://evil.example' }, body: '{"text":"x"}' })).status, 403);
const pr = (await (await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: cfg.publicUrl }, body: '{"text":"고침"}' })).json()) as any;
@@ -134,6 +152,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' });

View File

@@ -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;
@@ -118,6 +117,9 @@ function userProfile(id) {
// ── WS ───────────────────────────────────────────────
let wss;
// "잡음이라 삭제"로 배운 문장 (v1.4.0)
const noisePhrases = [{ id: 1, text: '시청해 주셔서 감사합니다 자막 제공', hits: 3, createdAt: Date.now() - 86400000 }];
let noiseSeq = 1;
const broadcast = (msg) => {
const s = JSON.stringify(msg, (k, v) => (k.startsWith('_') ? undefined : v));
wss?.clients.forEach((c) => c.readyState === 1 && c.send(s));
@@ -184,10 +186,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 +226,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 +267,77 @@ async function handle(req, res) {
broadcast({ type: 'utterance.updated', data: it });
return json(res, 200, it);
}
if ((m = p.match(/^\/api\/utterances\/([^/]+)\/delete$/)) && req.method === 'POST') {
const i = db.utterances.findIndex((u) => u.id === decodeURIComponent(m[1]));
if (i < 0) return json(res, 404, { error: 'not_found' });
const body = JSON.parse((await readBody(req)) || '{}');
const [it] = db.utterances.splice(i, 1);
let learned = null;
if (body.noise && it.text) {
learned = it.text;
noisePhrases.unshift({ id: ++noiseSeq, text: it.text, hits: 0, createdAt: Date.now() });
}
broadcast({ type: 'utterance.deleted', data: { id: it.id, noise: !!body.noise } });
return json(res, 200, { ok: true, learned });
}
if (p === '/api/dictionary')
return json(res, 200, {
labels: { valorant: '발로란트', lol: '롤' },
entries: [
{ id: 1, word: '로테', from: null, kind: 'hotword', pack: 'site', source: 'site', enabled: true, hits: 12 },
{ id: 2, word: '레이즈', from: '레이저', kind: 'correction', pack: 'site', source: 'site', enabled: true, hits: 0 },
],
packs: [{ key: 'valorant', label: '발로란트', count: 420 }],
});
if (p === '/api/noise-phrases') return json(res, 200, { phrases: noisePhrases });
if ((m = p.match(/^\/api\/noise-phrases\/(\d+)$/)) && req.method === 'DELETE') {
const i = noisePhrases.findIndex((x) => x.id === Number(m[1]));
if (i < 0) return json(res, 404, { error: 'not_found' });
noisePhrases.splice(i, 1);
return json(res, 200, { ok: true });
}
if (p === '/api/bundles') {
const out = [];
for (const mt of db.matches) {
const us = db.utterances.filter((u) => u.game?.matchId === mt.id);
out.push({ id: `match-${mt.id}`, kind: 'match', label: `${mt.game === 'valorant' ? '발로란트' : '롤'} · ${mt.mode} · ${mt.map.name}`, sub: mt.score ? `${mt.win ? '승리' : '패배'} ${mt.score.ally}:${mt.score.enemy}` : null, game: mt.game, matchId: mt.id, from: mt.startedAt, to: mt.endedAt ?? mt.startedAt, utterances: us.length, audio: us.filter((u) => u.audio).length, audioBytes: us.length * 41230, events: mt.events.length, talkMs: us.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(us.map((u) => u.userId))], live: false });
}
const talk = db.utterances.filter((u) => !u.game && !u.noise).sort((a, b) => a.ts - b.ts);
const runs = [];
for (const u of talk) {
const cur = runs[runs.length - 1];
if (!cur || u.ts - cur[cur.length - 1].endTs > 30 * 60000 || db.matches.some((mt) => mt.startedAt > cur[cur.length - 1].ts && mt.startedAt <= u.ts)) runs.push([u]);
else cur.push(u);
}
for (const r of runs) {
const from = r[0].ts, to = r[r.length - 1].endTs;
const next = db.matches.find((mt) => mt.startedAt >= to && mt.startedAt - to < 30 * 60000);
const prev = db.matches.find((mt) => (mt.endedAt ?? 0) <= from && from - (mt.endedAt ?? 0) < 30 * 60000);
out.push({ id: `talk-${r[0].id}`, kind: 'talk', label: next ? '경기 전 대화' : prev ? '경기 후 대화' : '게임 밖 대화', sub: next ? `다음 경기: ${next.map.name}` : prev ? `지난 경기: ${prev.map.name}` : null, game: null, matchId: null, from, to, utterances: r.length, audio: r.filter((u) => u.audio).length, audioBytes: r.length * 41230, events: 0, talkMs: r.reduce((n, u) => n + u.endTs - u.ts, 0), users: [...new Set(r.map((u) => u.userId))], live: false });
}
return json(res, 200, { bundles: out.sort((a, b) => b.from - a.from) });
}
if (p === '/api/bundles/delete' && req.method === 'POST') return json(res, 200, { bundles: 1, utterances: 12, files: 12 });
if (p === '/api/bundles/export' && req.method === 'POST') {
req.resume();
res.writeHead(200, { 'content-type': 'application/zip', 'content-disposition': 'attachment; filename="gvr-valorant-20261016-0430.zip"' });
return res.end(Buffer.from('PK\x05\x06' + '\0'.repeat(18)));
}
if (p === '/api/bundles/import' && req.method === 'POST') {
req.resume();
return json(res, 400, { error: 'invalid_bundle', message: '받아오기 실패: manifest.json 이 없습니다 (겜녹이에서 내보낸 기록 zip 이 아닙니다)' });
}
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' });

View File

@@ -10,11 +10,16 @@ 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 { RecordsPage } from './pages/RecordsPage';
import { installErrorReporting } from './lib/report';
import { useLocation } from 'react-router';
/** Space 재생/일시정지 · ←/→ 이전/다음 발화 · / 검색 */
function useShortcuts() {
@@ -63,6 +68,7 @@ function Shell() {
<Routes>
<Route path="/" element={<TimelinePage />} />
<Route path="/matches" element={<MatchesPage />} />
<Route path="/records" element={<RecordsPage />} />
<Route path="/matches/:id" element={<MatchPage />} />
<Route path="/users" element={<UsersPage />} />
<Route path="/users/:id" element={<UserPage />} />
@@ -74,6 +80,7 @@ function Shell() {
</div>
<PlayerBar />
</div>
<UttMenuHost />
<LockOverlay />
</div>
);
@@ -81,6 +88,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 +105,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>

View File

@@ -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();
@@ -146,6 +174,7 @@ export function Header() {
const nav = [
['/', '타임라인'],
['/matches', '경기'],
['/records', '기록'],
['/users', '유저'],
['/dictionary', '단어사전'],
['/culprit', '🔍 범인찾기'],
@@ -170,6 +199,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" />

View File

@@ -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" />

View File

@@ -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>

View File

@@ -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 }))}

View File

@@ -0,0 +1,348 @@
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 { useAuth, useData, useLive } 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;
let deleteFor: UtteranceItem | null = null;
/** 이 화면에서 지운 발화 (다른 사람이 지운 것도 실시간으로). 목록마다 따로 고치지 않고 줄이 스스로 숨는다 */
const deleted = new Set<string>();
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();
}
function openDelete(item: UtteranceItem): void {
menu = null;
deleteFor = item;
notify();
}
function closeDelete(): void {
deleteFor = null;
notify();
}
function markDeleted(id: string): void {
if (deleted.has(id)) return;
deleted.add(id);
if (player.state.item?.id === id) player.stop();
notify();
}
/** 지운 발화인가 (줄을 숨긴다) */
export function useDeleted(id: string): boolean {
return useSyncExternalStore(subscribe, () => deleted.has(id));
}
/** 녹음 원본(.ogg)을 내려받는다. 게임 PC → 사이트 서버 중계로 받은 파일을 그대로 저장 */
export async function downloadAudio(item: UtteranceItem, fileName?: string | null): Promise<void> {
// 파일 이름: 게임 PC 의 녹음 파일 이름 그대로 (날짜 · 시각 · 말한 사람 · 게임 · 라운드). 예전 앱이면 발화 ID
if (!fileName) fileName = await api.utteranceInfo(item.id).then((i) => i.fileName).catch(() => null);
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 del = useSyncExternalStore(subscribe, () => deleteFor);
const [err, setErr] = useState<string | null>(null);
const [okMsg, setOkMsg] = useState<string | null>(null);
const { auth } = useAuth();
// 지우기: 관리자나 말한 사람만 (게임 PC 도 한 번 더 확인한다)
const canDelete = (it: UtteranceItem) => auth.status === 'ok' && (!!auth.me.canViewLogs || auth.me.user.id === it.userId);
useLive((e) => {
if (e.type === 'utterance.deleted') markDeleted(e.data.id);
});
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]);
useEffect(() => {
if (!okMsg) return;
const t = setTimeout(() => setOkMsg(null), 4000);
return () => clearTimeout(t);
}, [okMsg]);
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 - 240) }}
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 className="ctx-sep" />
<button
role="menuitem"
className="danger"
disabled={!canDelete(m.item)}
title={canDelete(m.item) ? undefined : '관리자나 말한 사람만 지울 수 있습니다'}
onClick={act(() => openDelete(m.item))}
>
<span className="ctx-ic">🗑</span> 삭제…
</button>
</div>
)}
{info && <InfoDialog item={info} onError={setErr} />}
{del && (
<DeleteDialog
key={del.id}
item={del}
onDone={(learned) => {
markDeleted(del.id);
closeDelete();
setOkMsg(learned ? `삭제했습니다. 앞으로 "${learned.length > 40 ? learned.slice(0, 40) + '…' : learned}" 는 잡음으로 거릅니다` : '삭제했습니다');
}}
/>
)}
{err && <div className="ctx-toast">{err}</div>}
{okMsg && !err && <div className="ctx-toast ok">{okMsg}</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>
);
}
/** 삭제 확인: 잡음이라 삭제(같은 문장을 다음부터 잡음으로 거름) · 그냥 삭제 · 취소 */
function DeleteDialog({ item, onDone }: { item: UtteranceItem; onDone: (learned: string | null) => void }) {
const { userById } = useData();
const [busy, setBusy] = useState<'noise' | 'plain' | null>(null);
const [failed, setFailed] = useState<string | null>(null);
const text = item.text?.trim() || null;
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && closeDelete();
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [busy]);
const run = async (noise: boolean) => {
setBusy(noise ? 'noise' : 'plain');
setFailed(null);
try {
const r = await api.deleteUtterance(item.id, noise);
onDone(r.learned);
} catch (e) {
setBusy(null);
if (e instanceof ApiError && e.status === 404 && e.code === 'not_found') return onDone(null); // 이미 지워짐
setFailed(
e instanceof ApiError && e.status === 404
? '게임 PC 의 겜녹이가 예전 버전입니다. v1.4.0 이상으로 업데이트하면 지울 수 있습니다.'
: e instanceof ApiError && e.status === 403
? '관리자나 말한 사람만 지울 수 있습니다.'
: e instanceof ApiError && e.status === 503
? '게임 PC 가 꺼져 있어 지우지 못했습니다.'
: '지우지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
);
}
};
return (
<div className="ctx-dim" onPointerDown={() => !busy && closeDelete()}>
<div className="ctx-dialog del-dialog" role="dialog" aria-label="발화 삭제" onPointerDown={(e) => e.stopPropagation()}>
<div className="ctx-head">
<b>발화 삭제</b>
<button className="icon-btn" onClick={closeDelete} disabled={!!busy} aria-label="닫기">
<IClose width={16} height={16} />
</button>
</div>
<div className="del-quote">
<span className="dim">{userById(item.userId)?.name ?? '알 수 없음'} · {fmtWhen(item.ts)}</span>
<p>{text ?? '(인식된 글 없음)'}</p>
</div>
<p className="del-help">
글과 음성 파일을 게임 PC 에서 지웁니다. 되돌릴 수 없습니다.
<br />
<b>잡음이라 삭제</b>를 고르면 이 문장을 잡음으로 배워서, 다음에 같은 문장이 인식되면 자동으로 잡음 처리합니다 (띄어쓰기 · 문장부호는 무시하고, 긴 문장은 글자 수가 같고 한두 글자만 바뀐 것까지 같은 문장으로 봅니다. 앞뒤에 다른 말이 붙은 발화는 지우지 않습니다).
배운 문장은 사전 화면에서 지울 수 있습니다.
</p>
{failed && <p className="del-err">{failed}</p>}
<div className="ctx-foot">
<button className="chip" onClick={closeDelete} disabled={!!busy}>
취소
</button>
<button className="chip danger" onClick={() => void run(false)} disabled={!!busy}>
{busy === 'plain' ? '지우는 중…' : '그냥 삭제'}
</button>
<button className="chip danger on" onClick={() => void run(true)} disabled={!!busy || !text} title={text ? undefined : '인식된 글이 없어 배울 문장이 없습니다'}>
{busy === 'noise' ? '지우는 중…' : '잡음이라 삭제'}
</button>
</div>
</div>
</div>
);
}

View File

@@ -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, useDeleted } from './UttMenu';
const STATUS: Record<UtteranceItem['status'], [string, string]> = {
realtime: ['실시간', 'st-rt'],
@@ -146,12 +147,19 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
const playing = usePlayer((s) => active && s.playing);
const [editing, setEditing] = useState(false);
const [st, stCls] = STATUS[item.status];
const gone = useDeleted(item.id);
const click = () => {
if (editing) return;
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');
@@ -176,9 +184,12 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
</button>
);
// 우클릭으로 지운 발화 (경기 화면 · 유저 화면 등 어느 목록이든 줄이 숨는다)
if (gone) return null;
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 +210,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">

View File

@@ -10,9 +10,15 @@ import type {
UserProfile,
User,
UtteranceItem,
UtteranceInfo,
GameType,
BundleInfo,
BundleImportResult,
NoisePhrase,
} 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 +61,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 +85,6 @@ export interface TimelineQuery {
to?: number;
q?: string;
types?: string[];
hideNoise?: boolean;
cursor?: string | null;
limit?: number;
order?: 'asc' | 'desc';
@@ -117,10 +126,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,8 +162,41 @@ 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 ?? '분석을 시작하지 못했습니다' };
},
/** 기록 묶음 (v1.3.7~ 앱) */
bundles: () => request<{ bundles: BundleInfo[] }>('/api/bundles').then((r) => r.bundles),
deleteBundles: (ids: string[]) => request<{ bundles: number; utterances: number; files: number }>('/api/bundles/delete', { method: 'POST', body: JSON.stringify({ ids }) }),
/** zip 내려받기 (많이 골라도 되게 본문으로 보낸다). 파일 이름은 앱이 정한 것 */
exportBundles: async (ids: string[]): Promise<{ blob: Blob; fileName: string }> => {
const res = await fetch('/api/bundles/export', { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ids }) });
if (!res.ok) {
const b = await res.json().catch(() => ({}));
if (res.status === 503) emit('device_offline');
throw new Error(b.message ?? `zip 을 받지 못했습니다 (${res.status})`);
}
const cd = res.headers.get('content-disposition') ?? '';
return { blob: await res.blob(), fileName: /filename="([^"]+)"/.exec(cd)?.[1] ?? 'gvr-records.zip' };
},
/** zip 받아오기. 실패하면 서버가 준 이유("받아오기 실패: …")를 담은 Error */
importBundle: async (file: Blob): Promise<BundleImportResult> => {
let res: Response;
try {
res = await fetch('/api/bundles/import', { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/zip', accept: 'application/json' }, body: file });
} catch {
throw new Error('받아오기 실패: 네트워크 오류');
}
const b = await res.json().catch(() => ({}));
if (res.ok) return b as BundleImportResult;
if (res.status === 503) emit('device_offline');
throw new Error(b.message ?? (res.status === 413 ? '받아오기 실패: zip 이 너무 큽니다 (300MB 까지)' : `받아오기 실패 (${res.status} ${b.error ?? ''})`));
},
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 }) }),
/** 발화 지우기 (v1.4.0). noise = 잡음이라 삭제 (같은 문장을 다음부터 잡음으로) */
deleteUtterance: (id: string, noise: boolean) =>
request<{ ok: true; learned: string | null }>(`/api/utterances/${encodeURIComponent(id)}/delete`, { method: 'POST', body: JSON.stringify({ noise }) }),
noisePhrases: () => request<{ phrases: NoisePhrase[] }>('/api/noise-phrases'),
deleteNoisePhrase: (id: number) => request<{ ok: true }>(`/api/noise-phrases/${id}`, { method: 'DELETE' }),
};
export interface DictionaryEntry {

View File

@@ -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);

View File

@@ -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;

View File

@@ -15,6 +15,11 @@ export function fmtWhen(ts: number): string {
return `${md} ${hm}`;
}
/** 날짜만: "오늘" · "어제" · "10월 7일" (fmtWhen 에서 시각을 뺀 것) */
export function fmtDay(ts: number): string {
return fmtWhen(ts).replace(/\s\d{2}:\d{2}$/, '');
}
export function fmtHM(ts: number): string {
return new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, hour: '2-digit', minute: '2-digit', hour12: false }).format(ts);
}
@@ -54,7 +59,7 @@ export function fmtSec(sec: number): string {
}
export function realTip(ts: number) {
return `현실 시간 ${fmtWhen(ts).split(' ')[0]} ${fmtReal(ts)}`;
return `현실 시간 ${fmtDay(ts)} ${fmtReal(ts)}`;
}
/** "YYYY-MM-DD" (KST) ↔ ms */

View 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 /* 검색어 등 쿼리는 남기지 않는다 */ }),
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);
});
}

View File

@@ -1,4 +1,5 @@
import { useEffect, useMemo, useState } from 'react';
import type { NoisePhrase } from '@gvr/shared';
import { api, type DictionaryResponse } from '../lib/api';
import { useStatus } from '../store/app';
import { sfx } from '../lib/sfx';
@@ -17,12 +18,18 @@ export function DictionaryPage() {
const [from, setFrom] = useState('');
const [to, setTo] = useState('');
const [busy, setBusy] = useState(false);
// "잡음이라 삭제"로 배운 문장 (v1.4.0). 예전 앱이면 null → 칸을 숨긴다
const [noise, setNoise] = useState<NoisePhrase[] | null>(null);
useEffect(() => {
let alive = true;
api
.dictionary()
.then((d) => alive && setData(d))
.catch((e) => alive && setErr(e));
api
.noisePhrases()
.then((r) => alive && setNoise(r.phrases))
.catch(() => alive && setNoise(null));
return () => {
alive = false;
};
@@ -110,6 +117,34 @@ export function DictionaryPage() {
</table>
</section>
</div>
{noise && (
<section className="card dict-noise">
<h3 className="h">
잡음으로 배운 문장 <span className="dim small">{noise.length}</span>
</h3>
<p className="muted small">타임라인에서 우클릭 → 삭제 → "잡음이라 삭제"로 넣은 문장입니다. 같은 문장이 다시 인식되면 자동으로 잡음 처리합니다 (띄어쓰기 · 문장부호 무시, 8글자 이상이면 글자 수가 같고 한두 글자만 바뀐 것까지. 앞뒤에 다른 말이 붙으면 그대로 둡니다). 실제 말까지 걸러지면 여기서 지워 주세요.</p>
<table className="dict-table">
<tbody>
{noise.length === 0 && (
<tr>
<td className="dim small">아직 없습니다</td>
</tr>
)}
{noise.map((p) => (
<tr key={p.id}>
<td className="from">{p.text}</td>
<td className="dim small">{p.hits ? `${p.hits}번 거름` : ''}</td>
<td>
<button className="link" disabled={busy} onClick={() => void run(() => api.deleteNoisePhrase(p.id))}>
삭제
</button>
</td>
</tr>
))}
</tbody>
</table>
</section>
)}
</main>
);
}

View 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>
);
}

View File

@@ -0,0 +1,275 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
import type { BundleInfo, BundleImportResult } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { fmtDuration, fmtHM, fmtWhen, fmtDay } from '../lib/format';
import { sfx } from '../lib/sfx';
import { useAuth, useData, useLive, useStatus } from '../store/app';
import { Avatar, ErrorBox, Spinner } from '../components/common';
import { IDownload } from '../components/Icons';
/**
* 기록 관리 (v1.3.7): 경기 하나 · 경기 전 대화 · 경기 후 대화 · 게임 밖 대화를 묶음으로 보고,
* 묶음 단위로 기록 보기 · zip 내려받기 · 지우기(관리자) · zip 받아오기(관리자)를 한다.
*/
const fmtMB = (b: number) => (b >= 1024 * 1024 ? `${(b / 1024 / 1024).toFixed(1)}MB` : `${Math.max(1, Math.round(b / 1024))}KB`);
const MAX_ZIP = 300 * 1024 * 1024;
export function RecordsPage() {
const { epoch } = useStatus();
const { auth } = useAuth();
const admin = auth.status === 'ok' && !!auth.me.canViewLogs;
const nav = useNavigate();
const [list, setList] = useState<BundleInfo[] | null>(null);
const [err, setErr] = useState<unknown>(null);
const [old, setOld] = useState(false);
const [sel, setSel] = useState<Set<string>>(new Set());
const [confirm, setConfirm] = useState<BundleInfo[] | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [kind, setKind] = useState<'all' | 'match' | 'talk'>('all');
const file = useRef<HTMLInputElement>(null);
const load = useCallback(() => {
setErr(null);
api
.bundles()
.then((b) => {
setList(b);
setSel((s) => new Set([...s].filter((id) => b.some((x) => x.id === id))));
})
.catch((e) => {
if (e instanceof ApiError && e.status === 404) setOld(true);
else setErr(e);
});
}, []);
useEffect(load, [load, epoch]);
useLive((e) => {
if (e.type === 'records.changed') load();
});
const shown = useMemo(() => (list ?? []).filter((b) => kind === 'all' || b.kind === kind), [list, kind]);
const days = useMemo(() => {
const g = new Map<string, BundleInfo[]>();
for (const b of shown) {
const d = fmtDay(b.from);
g.set(d, [...(g.get(d) ?? []), b]);
}
return [...g];
}, [shown]);
const picked = (list ?? []).filter((b) => sel.has(b.id));
const toggle = (id: string) => setSel((s) => (s.has(id) ? new Set([...s].filter((x) => x !== id)) : new Set([...s, id])));
const download = async (ids: string[]) => {
sfx('click');
setBusy('export');
setMsg({ ok: true, text: 'zip 을 만들어 받는 중입니다. 묶음이 크면 조금 걸립니다…' });
try {
const { blob, fileName } = await api.exportBundles(ids);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 30000);
setMsg({ ok: true, text: `${fileName} (${fmtMB(blob.size)}) 내려받기를 시작했습니다` });
} catch (e) {
setMsg({ ok: false, text: (e as Error).message });
} finally {
setBusy(null);
}
};
const doDelete = async (bs: BundleInfo[]) => {
setBusy('delete');
try {
const r = await api.deleteBundles(bs.map((b) => b.id));
setMsg({ ok: true, text: `묶음 ${r.bundles}개를 지웠습니다 (발화 ${r.utterances}개, 음성 파일 ${r.files}개)` });
setSel(new Set());
setConfirm(null);
load();
} catch (e) {
setMsg({ ok: false, text: e instanceof ApiError && e.status === 403 ? '지우기는 관리자만 할 수 있습니다' : e instanceof ApiError && e.status === 409 ? '진행 중인 경기는 지울 수 없습니다 (경기가 끝난 뒤 지워 주세요)' : '지우지 못했습니다' });
} finally {
setBusy(null);
}
};
const doImport = async (f: File) => {
if (f.size > MAX_ZIP) return setMsg({ ok: false, text: '받아오기 실패: zip 이 너무 큽니다 (300MB 까지)' });
setBusy('import');
setMsg(null);
try {
const r: BundleImportResult = await api.importBundle(f);
setMsg({
ok: true,
text: `받아오기 완료: ${r.bundles.join(', ')} · 발화 ${r.added.utterances}개 추가 (음성 ${r.added.audio}개${r.added.matches ? `, 경기 ${r.added.matches}개` : ''})${r.skipped ? ` · 이미 있는 발화 ${r.skipped}개는 건너뜀` : ''}`,
});
load();
} catch (e) {
setMsg({ ok: false, text: (e as Error).message });
} finally {
setBusy(null);
if (file.current) file.current.value = '';
}
};
const view = (b: BundleInfo) => {
sfx('click');
if (b.kind === 'match' && b.matchId) nav(`/?match=${encodeURIComponent(b.matchId)}`);
else nav(`/?game=none&from=${b.from}&to=${b.to}&order=asc`);
};
if (old)
return (
<main className="page-pad">
<h2 className="page-h h">기록 관리</h2>
<div className="empty">게임 PC 의 겜녹이가 예전 버전입니다. v1.3.7 이상으로 업데이트하면 경기별로 묶어 보고 지우기 · zip 내려받기 · 받아오기를 할 수 있습니다.</div>
</main>
);
return (
<main className="page-pad records">
<div className="page-h-row">
<h2 className="page-h h">기록 관리</h2>
<div className="chips-wrap">
{(
[
['all', '전체'],
['match', '경기'],
['talk', '경기 밖 대화'],
] as const
).map(([k, l]) => (
<button key={k} className={`chip${kind === k ? ' on' : ''}`} onClick={() => setKind(k)}>
{l}
</button>
))}
</div>
<div className="rec-actions">
{admin && (
<>
<input ref={file} type="file" accept=".zip,application/zip" hidden onChange={(e) => e.target.files?.[0] && void doImport(e.target.files[0])} />
<button className="chip" disabled={busy === 'import'} onClick={() => file.current?.click()} title="내려받아 둔 기록 zip 을 다시 넣습니다">
⬆ {busy === 'import' ? '받아오는 중…' : '받아오기 (zip)'}
</button>
</>
)}
</div>
</div>
<p className="rec-help dim">
경기 하나가 묶음 하나입니다. 경기 밖 대화는 다음 경기 30분 전 안이면 "경기 전 대화", 지난 경기 30분 안이면 "경기 후 대화"로 묶습니다. 묶음을 골라 한 번에 zip 으로 내려받거나{admin ? ' 지울 수 있고, 받아 둔 zip 은 "받아오기"로 다시 넣을 수 있습니다' : ' 할 수 있습니다 (지우기 · 받아오기는 관리자만)'}.
</p>
{msg && <div className={`rec-msg ${msg.ok ? 'ok' : 'bad'}`}>{msg.text}</div>}
{picked.length > 0 && (
<div className="rec-selbar">
<b>{picked.length}개 선택</b>
<span className="dim">
발화 {picked.reduce((n, b) => n + b.utterances, 0)}개 · 음성 {fmtMB(picked.reduce((n, b) => n + b.audioBytes, 0))}
</span>
<button className="chip on" disabled={busy === 'export'} onClick={() => void download(picked.map((b) => b.id))}>
<IDownload width={14} height={14} /> 한 번에 zip
</button>
{admin && (
<button className="chip danger" disabled={picked.some((b) => b.live)} title={picked.some((b) => b.live) ? '진행 중인 경기는 지울 수 없습니다' : undefined} onClick={() => setConfirm(picked)}>
🗑 한 번에 지우기
</button>
)}
<button className="link-btn" onClick={() => setSel(new Set())}>
선택 해제
</button>
</div>
)}
{err != null && <ErrorBox error={err} onRetry={load} />}
{!list && !err && <Spinner />}
{list && !shown.length && <div className="empty">기록이 없습니다.</div>}
{days.map(([day, bs]) => (
<section key={day} className="rec-day">
<h4>
<label>
<input
type="checkbox"
checked={bs.every((b) => sel.has(b.id))}
onChange={(e) => setSel((s) => (e.target.checked ? new Set([...s, ...bs.map((b) => b.id)]) : new Set([...s].filter((id) => !bs.some((b) => b.id === id)))))}
/>{' '}
{day}
</label>
</h4>
{bs.map((b) => (
<BundleRow key={b.id} b={b} on={sel.has(b.id)} admin={admin} busy={busy === 'export'} onToggle={() => toggle(b.id)} onView={() => view(b)} onZip={() => void download([b.id])} onDelete={() => setConfirm([b])} />
))}
</section>
))}
{confirm && (
<div className="ctx-dim" onPointerDown={() => busy !== 'delete' && setConfirm(null)}>
<div className="ctx-dialog" role="alertdialog" aria-label="기록 지우기" onPointerDown={(e) => e.stopPropagation()}>
<div className="ctx-head">
<b>기록 {confirm.length}묶음을 지울까요?</b>
</div>
<ul className="rec-del-list">
{confirm.map((b) => (
<li key={b.id}>
{b.label} · {fmtWhen(b.from)} · 발화 {b.utterances}개
</li>
))}
</ul>
<p className="dim small">발화 · 음성 파일 · 경기 기록(킬 · 라운드 · 범인 분석)이 게임 PC 에서 지워지고 되돌릴 수 없습니다. 먼저 zip 으로 받아 두면 "받아오기"로 다시 넣을 수 있습니다.</p>
<div className="ctx-foot">
<button className="chip" disabled={busy === 'export'} onClick={() => void download(confirm.map((b) => b.id))}>
<IDownload width={14} height={14} /> 먼저 zip 받기
</button>
<button className="chip danger" disabled={busy === 'delete'} onClick={() => void doDelete(confirm)}>
{busy === 'delete' ? '지우는 중…' : '🗑 지우기'}
</button>
<button className="chip" onClick={() => setConfirm(null)}>
취소
</button>
</div>
</div>
</div>
)}
</main>
);
}
function BundleRow({ b, on, admin, busy, onToggle, onView, onZip, onDelete }: { b: BundleInfo; on: boolean; admin: boolean; busy: boolean; onToggle: () => void; onView: () => void; onZip: () => void; onDelete: () => void }) {
const { userById } = useData();
const icon = b.kind === 'match' ? (b.game === 'lol' ? '🏆' : '🎯') : '💬';
return (
<div className={`rec-row k-${b.kind}${b.game ? ` g-${b.game}` : ''}${on ? ' sel' : ''}`}>
<input type="checkbox" checked={on} onChange={onToggle} aria-label={`${b.label} 선택`} />
<span className="rec-ic">{icon}</span>
<div className="rec-main" onClick={onView} role="button" title="기록 보기">
<div className="rec-title">
<b>{b.label}</b>
{b.live && <span className="rec-live">● 진행 중</span>}
{b.sub && <span className="dim">· {b.sub}</span>}
</div>
<div className="rec-meta dim">
<span className="mono">
{fmtHM(b.from)} ~ {fmtHM(b.to)}
</span>{' '}
({fmtDuration(Math.max(0, b.to - b.from))}) · 발화 {b.utterances}개 · 말한 시간 {fmtDuration(b.talkMs)} · 음성 {b.audio}개 {b.audioBytes ? `(${fmtMB(b.audioBytes)})` : ''}
{b.kind === 'match' ? ` · 경기 이벤트 ${b.events}개` : ''}
</div>
</div>
<div className="rec-avs">
{b.users.slice(0, 6).map((id) => (
<Avatar key={id} user={userById(id)} size={24} />
))}
</div>
<div className="rec-btns">
<button className="chip" onClick={onView}>
기록 보기
</button>
<button className="chip" disabled={busy} onClick={onZip} title="이 묶음을 zip 으로 내려받기 (음성 ogg · 대화.txt 포함)">
<IDownload width={14} height={14} /> zip
</button>
{admin && (
<button className="chip danger" disabled={b.live} onClick={onDelete} title={b.live ? '진행 중인 경기는 끝난 뒤 지울 수 있습니다' : '이 묶음 지우기'}>
🗑
</button>
)}
</div>
</div>
);
}

View File

@@ -2,7 +2,7 @@ import type { MatchDetail, MatchSummary, User } from '@gvr/shared';
import type { Filters } from '../lib/filters';
import { Avatar, CharIcon } from '../components/common';
import { sfx } from '../lib/sfx';
import { dateInputToMs, dateInputValue, fmtHM, fmtWhen } from '../lib/format';
import { dateInputToMs, dateInputValue, fmtHM, fmtDay } from '../lib/format';
import { TYPE_GROUPS } from '../lib/game';
type Update = (p: Partial<Filters>) => void;
@@ -45,7 +45,7 @@ export function Sidebar({ f, update, users, matches, detail }: { f: Filters; upd
sfx('click');
fn();
};
const today = matches.length ? fmtWhen(matches[0].startedAt).split(' ')[0] : '';
const today = matches.length ? fmtDay(matches[0].startedAt) : '';
return (
<aside className="side">
<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>
);
}

View File

@@ -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,20 @@ 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 next ? prev : [...prev, it];
return [...prev.slice(0, i), it, ...prev.slice(i)];
});
} else if (e.type === 'utterance.deleted') {
// 우클릭으로 지운 발화 (v1.4.0)
setItems((prev) => prev.filter((p) => p.id !== e.data.id));
}
});

View File

@@ -3,7 +3,7 @@ import { Link, useNavigate, useParams } from 'react-router';
import type { GameType, MatchSummary, User, UserProfile } from '@gvr/shared';
import { api } from '../lib/api';
import { useStatus } from '../store/app';
import { fmtDuration, fmtWhen } from '../lib/format';
import { fmtDuration, fmtDay } from '../lib/format';
import { sfx } from '../lib/sfx';
import { Avatar, ErrorBox, Spinner } from '../components/common';
import { MatchItem } from './Sidebar';
@@ -57,7 +57,7 @@ export function MatchesPage() {
const groups = useMemo(() => {
const g = new Map<string, MatchSummary[]>();
for (const m of data ?? []) {
const d = fmtWhen(m.startedAt).split(' ')[0];
const d = fmtDay(m.startedAt);
g.set(d, [...(g.get(d) ?? []), m]);
}
return [...g];

View File

@@ -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]);

View File

@@ -8,16 +8,23 @@ export interface Settings {
rate: number;
continuous: boolean;
normalize: boolean;
/** 녹음 재생 음량 0..2 (1 = 원래 크기) */
playVolume: number;
/** 기본값을 바꾼 횟수 (예전에 저장한 설정을 한 번만 새 기본값으로 맞춘다) */
defaultsRev?: number;
}
const KEY = 'gvr.settings.v1';
const DEFAULTS: Settings = {
volume: 0.5,
sfx: { click: true, play: true, kill: true, round: true, chime: true },
// 새 발화 알림 · 재생 시작 효과음은 기본으로 끈다 (v1.4.0)
sfx: { click: true, play: false, kill: true, round: true, chime: false },
reduceMotion: false,
rate: 1,
continuous: true,
normalize: true,
playVolume: 1,
defaultsRev: 1,
};
function load(): Settings {
@@ -25,7 +32,18 @@ function load(): Settings {
const raw = localStorage.getItem(KEY);
if (!raw) return DEFAULTS;
const v = JSON.parse(raw) as Partial<Settings>;
return { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) } };
const out = { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) } };
// 예전 사이트는 설정을 하나만 바꿔도 효과음 켜짐/꺼짐을 전부 저장했다: 새 기본값(두 알림 끄기)을 한 번 적용
if ((v.defaultsRev ?? 0) < 1) {
out.sfx = { ...out.sfx, play: false, chime: false };
out.defaultsRev = 1;
try {
localStorage.setItem(KEY, JSON.stringify(out));
} catch {
/* 사생활 보호 모드 등 */
}
}
return out;
} catch {
return DEFAULTS;
}

View File

@@ -3211,6 +3211,9 @@ button.match:hover {
@media (max-width: 900px) { .dict-grid { grid-template-columns: 1fr; } }
.dict-grid .card { background: #121e29; border: 1px solid #243545; border-radius: 12px; padding: 16px 18px; }
.dict-grid h3 { font-size: 15px; margin-bottom: 12px; }
.dict-noise { margin-top: 16px; background: #121e29; border: 1px solid #243545; border-radius: 12px; padding: 16px 18px; }
.dict-noise h3 { font-size: 15px; margin-bottom: 6px; }
.dict-noise p { margin: 0 0 10px; }
.dict-form { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; }
.dict-form input { flex: 1; min-width: 0; background: #0d1720; border: 1px solid #243545; border-radius: 8px; padding: 9px 12px; color: inherit; }
.dict-list { display: flex; flex-wrap: wrap; gap: 8px; }
@@ -3430,3 +3433,504 @@ 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;
}
.ctx-toast.ok {
background: #102a1f;
border-color: #23573f;
color: #a6f0c6;
}
.ctx-sep {
height: 1px;
margin: 4px 6px;
background: #22323f;
}
.ctx-menu button.danger:not(:disabled) {
color: #ff9aa3;
}
.ctx-menu button.danger:hover:not(:disabled) {
background: rgba(255, 70, 85, 0.14);
}
.del-dialog {
width: min(480px, 100%);
}
.del-quote {
padding: 10px 12px;
border-radius: 9px;
background: #13202c;
border: 1px solid #22323f;
font-size: 12px;
}
.del-quote p {
margin: 4px 0 0;
font-size: 14px;
word-break: break-all;
}
.del-help {
font-size: 12.5px;
line-height: 1.6;
color: var(--muted);
margin: 12px 0 0;
}
.del-err {
font-size: 13px;
color: #ff9aa3;
margin: 10px 0 0;
}
.chip.danger.on {
background: rgba(255, 70, 85, 0.22);
border-color: rgba(255, 70, 85, 0.7);
color: #ffd0d4;
}
/* ── 사이트 로그 (/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);
}
/* ── 기록 관리 (/records) ── */
.records .page-h-row {
flex-wrap: wrap;
}
.rec-actions {
margin-left: auto;
display: flex;
gap: 8px;
}
.rec-help {
font-size: 13px;
margin: 4px 0 14px;
line-height: 1.6;
}
.rec-msg {
padding: 9px 14px;
border-radius: 8px;
font-size: 13px;
margin-bottom: 12px;
}
.rec-msg.ok {
background: rgba(69, 211, 154, 0.1);
border: 1px solid rgba(69, 211, 154, 0.35);
color: #9ff0cc;
}
.rec-msg.bad {
background: #2a1418;
border: 1px solid #5a2630;
color: #ffb3bb;
}
.rec-selbar {
position: sticky;
top: 0;
z-index: 5;
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
padding: 10px 14px;
margin-bottom: 12px;
background: #13202c;
border: 1px solid #2c3f52;
border-radius: 10px;
font-size: 13px;
}
.chip.danger {
border-color: rgba(255, 70, 85, 0.5);
color: #ff9aa3;
}
.chip.danger:hover:not(:disabled) {
background: rgba(255, 70, 85, 0.15);
}
.rec-day h4 {
font-size: 12.5px;
color: var(--muted);
margin: 18px 0 8px;
}
.rec-day h4 label {
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
}
.rec-row {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 14px;
border: 1px solid #1c2a37;
border-left: 3px solid #3a4d60;
border-radius: 10px;
background: #0f1923;
margin-bottom: 8px;
}
.rec-row.k-match.g-valorant {
border-left-color: var(--accent);
}
.rec-row.k-match.g-lol {
border-left-color: var(--lol);
}
.rec-row.k-talk {
border-left-color: var(--mint);
}
.rec-row.sel {
background: #14222f;
border-color: #2c3f52;
}
.rec-ic {
font-size: 18px;
width: 24px;
text-align: center;
}
.rec-main {
flex: 1;
min-width: 0;
cursor: pointer;
}
.rec-title {
display: flex;
gap: 6px;
align-items: baseline;
font-size: 14px;
flex-wrap: wrap;
}
.rec-meta {
font-size: 12px;
margin-top: 3px;
}
.rec-avs {
display: flex;
gap: 2px;
}
.rec-btns {
display: flex;
gap: 6px;
}
.rec-del-list {
font-size: 13px;
margin: 6px 0 10px;
padding-left: 18px;
max-height: 240px;
overflow: auto;
}
@media (max-width: 720px) {
.rec-row {
flex-wrap: wrap;
}
.rec-avs {
display: none;
}
}
.rec-live {
color: var(--accent);
font-size: 12px;
font-weight: 700;
}
.chip:disabled {
opacity: 0.45;
cursor: default;
}

View File

@@ -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 },
};

View File

@@ -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)

View File

@@ -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,31 @@ 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"(\S{1,10}?)((?:\s*\1){2,})")
def _collapse_one(m: re.Match[str]) -> str:
unit, rest = m.group(1), m.group(2)
# 숫자는 줄이지 않는다 ("1000원" → "10원" 이 되면 안 됨)
if any(ch.isdigit() for ch in unit):
return m.group(0)
# 한 글자 반복은 띄어 쓴 경우("아 아 아")만 고리로 본다 ("www", "ㅋㅋㅋ" 같은 한 덩어리는 그대로)
if len(unit) == 1 and not rest[:1].isspace():
return m.group(0)
return unit
def collapse_repetition(text: str) -> str:
"""Whisper 반복 고리("페이스페이스페이스…", "아 아 아 아")를 한 번으로 줄인다. 숫자 · 붙어 있는 한 글자 반복은 그대로."""
out = text.strip()
for _ in range(3):
nxt = _REPEAT_RE.sub(_collapse_one, 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:

View File

@@ -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)

View File

@@ -0,0 +1,73 @@
"""녹음 안내(TTS) 속도 바꾸기.
Edge TTS 는 말 속도를 0.5배까지만 늦춘다. 그보다 느리게(0.1~0.5배) 하려면 0.5배로 합성한 음성을
여기서 atempo 필터로 한 번 더 늘린다. 결과는 디스코드에 바로 보낼 수 있는 Ogg Opus (48kHz).
"""
from __future__ import annotations
import os
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)
# 다 만든 뒤에만 이름을 바꾼다 (중간에 죽어도 반쪽 파일이 안내 음성으로 남지 않게)
tmp = f"{dst}.part"
with av.open(src) as inp, av.open(tmp, "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)
os.replace(tmp, dst)
return {"duration_s": round(dur, 3), "stages": len(chain)}

Some files were not shown because too many files have changed in this diff Show More