77 Commits

Author SHA1 Message Date
EJClaw
320cc9babe v1.9.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:39:51 +09:00
EJClaw
b645d7575d 경기 기록 가져오기 취소 · 재개 보완: 받다가 멈춘 실행(취소 · 게임 시작 · 오류)은 history_pending 으로 남겨 다음 실행이 아는 경기 쪽에서 멈추지 않고 끝까지 훑게 (끝까지 훑은 계정에서 새 경기 일부만 받고 취소하면 나머지를 영영 못 받던 것) · 취소하면 다음 실행은 취소한 때부터 한 주기 뒤 (오래 돈 실행을 취소하면 바로 다시 시작하던 것) · 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:58:26 +09:00
EJClaw
63d0e43196 경기 기록 가져오기 진행 바 · 취소: Riot 경기 기록을 가져오는 동안 사이트 경기 탭 · 앱 게임 연동 탭에 목록 확인 중(얼마나 걸릴지 모름) → 받은 경기 / 받을 경기 · % · 남은 시간 진행 바와 취소 버튼 (취소하면 받은 경기는 남고 다음 주기에 남은 것부터 이어서) · 진행 상황은 games.state 의 history 로 보냄 · POST /api/games/history/cancel · 끝나면 경기 목록 새로 · 목록 불러오는 중 표시 · schema.ts 사본 다시 맞춤
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:54:09 +09:00
EJClaw
2a9a6496d8 v1.9.0 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:33:12 +09:00
EJClaw
b1568db8ca v1.9.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:43:45 +09:00
EJClaw
11db2e5104 경기 탭: 내가 플레이한 경기 전부 (Riot 경기 기록 포함) · 필터 (전체 경기 / 타임라인 있는 경기 / 목소리 녹음된 경기) · 지난 경기 더 보기 · 카드에 녹음 / 경기 기록만 표시 · 타임라인 사이드바는 타임라인 있는 경기만 · 목 서버에 기록 경기 70개
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:43:24 +09:00
EJClaw
f9fbf4c6c0 내 Riot 경기 기록 가져오기: 발로란트 match-history · 롤 LCU 기록을 게임 중이 아닐 때 30분마다 훑어 앱이 잡지 못한 경기를 source=history 로 저장 (처음은 끝까지, 다음부터 새 경기만, 상세 없는 경기는 건너뜀) · /api/matches has=timeline|voice 필터 · 경기 요약 source · voice · 녹음 없는 기록 경기의 킬 · 라운드는 타임라인 · 기록 관리에서 뺌
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:40:31 +09:00
EJClaw
9e1875b237 게임 중 GPU 아끼기: 게임(발로란트 실행 중 · 롤 경기 중)이 켜져 있으면 정밀 모델을 내리고 정밀 변환은 게임을 끈 뒤로 (16GB 카드는 경기 중에도 large-v3 를 올려 두고 다음 경기 중에도 지난 경기 정밀 변환을 돌리던 것, 메뉴에서는 새 발화를 large-v3 빔 5 로 변환하던 것) · 실시간 변환은 빔 1 · 발화 사이에 변환한 만큼 쉼 · 설정 토글 · 앱 창 하드웨어 가속 끔
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:36:03 +09:00
EJClaw
d0371fa0ac 3D 리플레이: 리플레이 파일이 없으면 '리플레이 파일 없음'과 새로고침 버튼 (내려받은 뒤 누르면 다시 찾아 변환) · 오류 상태에도 새로고침 · 목 서버는 리플레이 파일이 없으면 404
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:30:39 +09:00
EJClaw
cfe5075f76 v1.8.2 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 21:18:34 +09:00
EJClaw
96fb41748b 1인칭 조준점: 리플레이의 선수 조준점 · 사이트 전체 내 조준점 설정 · v1.8.2
- 변환기 Crosshair.cs: BombPlayerState 에 복제된 선수 조준점 프로필(주 · 정조준 · 저격 점 · 이름)을 두 번째 읽기로 읽어 players[].crosshair (바뀐 시각마다 전체 설정). 첫 읽기 필드 목록으로 번호를 찾고 패치로 밀려도 이름이 맞는 자리를 찾는다. --fields 디버그, --self-test 에 자리 찾기 · 기본색 검사
- 사이트 lib/crosshair.ts 그리기 · 발로란트 조준점 코드 읽기, CrosshairPanel: 선수 조준점(없으면 내 조준점) / 모든 선수에 내 조준점, 직접 고치기 · 코드 가져오기 · 선수 조준점 복사
- 1인칭: 정조준 조준점 · 저격 조준경 가운데 점 · 사격/이동 오차로 벌어짐
- 앱 1.8.2 (버전이 바뀌면 리플레이를 다시 변환해 조준점이 생긴다)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 20:44:50 +09:00
EJClaw
309974087b 1인칭: 요원 · 무기를 바꿔 다시 만들 때 눈 기준점을 팔 공간 좌표로 (이전 root 변환이 섞여 1.6m 밀리던 것) · 스파이크 설치 구간에 설치 동작(activate) 재생 (설치 시작 때 스파이크를 꺼내므로 꺼내기보다 먼저)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:35:24 +09:00
EJClaw
1fb8821663 3D 리플레이 실감 4단계: 1인칭 팔 · 총 · 동작 · 발로란트 조준점
- 추출기 viewmodels: 요원 1인칭 팔 fparms_* (30명) · 무기 1인칭 fpweapon_* (22종, 탄창 · 총 동작) · 팔 동작 fpanim_* (대기 · 사격 · 재장전 · 꺼내기 · 정조준 · 걷기 · 스파이크 작동). Agents.Skinned 로 스켈레탈 메시 내보내기를 나눠 3인칭 요원과 같이 쓴다
- pack.py · update.sh: viewmodels 압축 · index.json viewmodels, 갱신 때 같이 뽑는다
- 사이트 lib/viewmodel.ts: 카메라 공간 장면으로 맵 위에 그린다. 꺼내기 > 재장전 > 사격(총구 불꽃) > 걷기 > 정조준 > 대기를 리플레이 시각만으로 고른다
- 1인칭: 줌(소총 1.25배 · 저격 2.5/5배 + 조준경), 조준점을 발로란트 기본 십자(흰 선 · 틈 · 외곽선)로
- 작업 노트 docs/dev/replay-3d.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:21:47 +09:00
EJClaw
88e043da28 작업 노트: 13.09 전체 반영 결과 (구운 조명 22/23 맵)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:58:50 +09:00
EJClaw
626878e1d8 install.sh: 알림 채널 · 토큰 파일을 환경변수로 주지 않으면 이미 설치된 값을 그대로 쓴다 (다시 설치하면 알림이 빈 값으로 덮여 꺼지던 것)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:48:05 +09:00
EJClaw
a69ed57a0f 맵 3D 갱신: 사이트 맵 목록 대조를 대소문자 무시로 (13.09 에서 /Game/Maps/FoxTrot → Foxtrot 로만 바뀌어 '빠진 맵'으로 올리지 않던 것, 사이트도 대소문자 무시로 찾는다) · test-update.sh 가짜 추출기에 anims · abilities 명령 (스킬 재료 단계가 생긴 뒤 시험이 깨져 있던 것) · 대소문자 시험 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:46:25 +09:00
EJClaw
33e83256ed 라이트맵 추출 메모리: 칸 목록만 모으고 Build 에서 페이지를 하나씩 풀어 바로 줄인다 (펄 맵이 6GB 한도에서 OutOfMemory 이던 것, 고친 뒤 최대 2.7GB)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 16:41:06 +09:00
EJClaw
185e8c17bd 3D 리플레이 실감 3단계: 게임에 구워 둔 조명(라이트맵)으로 맵을 칠한다
- 추출기: 레벨 BuiltData 의 HQ 라이트맵을 메시 칸마다 풀어 irr · sh 아틀라스 두 장으로 (src/Lightmaps.cs), 조명 있는 배치는 LOD0 + 라이트맵 UV(TEXCOORD_1), ISM 은 인스턴스마다 칸
- glb: 재질 occlusionTexture(irr) · emissiveTexture(sh, 세기 0) · extras.lightmap.k. pack.py 는 맵 UV 를 실수로(-vtf, gltfpack 이 두 UV 채널을 한 범위로 양자화해서 라이트맵이 어긋나던 것)
- 사이트 map3d.ts: 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)). 옛 glb 는 그대로
- install.sh: 꺼 둔 자동 갱신 타이머는 다시 켜지 않는다
- 조사 명령 lmprobe · 작업 노트 docs/dev/replay-3d.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:45:43 +09:00
EJClaw
37c898cd73 종료 보완: DB 를 닫은 뒤 온 변환 성공 응답도 버림 · 트레이와 갱신 타이머를 TrayShell 로 묶어 종료 · 없어진 트레이 처리 회귀 시험
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 23:29:24 +09:00
EJClaw
cd4b7cb16f 종료 시 'Tray is destroyed' 오류 창: 트레이 · 상태 갱신 타이머를 멈추고 트레이를 비운 뒤 없앤다 · Electron 이 먼저 없앤 트레이도 건드리지 않음 · 종료 중 STT 는 새 작업을 꺼내지 않고 워커 종료로 실패한 작업을 닫힌 DB 에 기록하지 않음 (시험 추가)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 23:25:25 +09:00
EJClaw
dc36d094e9 v1.8.1 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:25:58 +09:00
EJClaw
a6cf73dee7 변환기: 무기 상태의 주인을 그 시각 주인으로 (마지막 주인이 과거 상태까지 덮어쓰던 것) · gvr-replay --self-test 회귀 검사 · CI 에서 실행 · v1.8.1
어비스 13.08 리플레이: 상태 16,974줄 중 1,189줄의 주인이 바뀜, 그중 그 시각 들고 있던 무기와 맞는 비율 24% → 75%

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:11:28 +09:00
EJClaw
ac70f7ce1f v1.8.0 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:06:57 +09:00
EJClaw
735783cd10 v1.8.0: 3D 리플레이 실감 (변환기 v2 · 요원 동작 · 게임 스킬 효과)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:51:51 +09:00
EJClaw
4cf4de0123 스킬 효과: 게임 효과가 아무것도 그리지 않는 동안은 예전 기본 모양으로 (짧게 끝나는 연막 등) · 오멘처럼 반투명 층뿐인 연막도 돔으로 · 아군/적 전용 시스템은 보는 쪽 것만
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:50:27 +09:00
EJClaw
a66f79d079 스킬 효과 추출: Zone_ 클래스도 (오멘 연막 Zone_Wraith_4_Smoke · 사이퍼 덫 Zone_Gumshoe_Q_Cage)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:35:58 +09:00
EJClaw
73e6173a59 3D 리플레이 실감 2단계: 게임 스킬 효과 추출(Abilities.cs: Cascade 파티클 · 메시 · 텍스처 → abilities.json) · 사이트 파티클 재생기(lib/vfx.ts: 시간만으로 계산 · 연막 돔 · 장판 칸 · 투사체 꼬리 · 설치물 메시) · maps3d json/png 제공 · update.sh/pack.py 연결
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:33:48 +09:00
EJClaw
c94edac147 3D 리플레이 실감 1단계: 변환기 v2 (스킬 주인 · 투사체 경로 · 앉기/점프 · 무기 상태 · 맞은 자리 · 사망 모션 · 설치/해체) · 공용 애니메이션 anims.glb · 요원 동작(앉기 · 점프 · 착지 · 조준 각 · 사격 반동 · 재장전 · 던지기 · 사망) · 예광 · 작은 이름표 · 요루 분신
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 00:29:09 +09:00
EJClaw
5c8ba05da4 사이트 CSP connect-src 에 blob: 추가: 3D 파일 안 텍스처를 막아 요원이 흰색 · 맵 3D 가 미니맵으로 나오던 문제
- three.js GLTFLoader 는 glb 안 이미지를 blob: 주소로 fetch 해 읽는데 connect-src 가 막아 텍스처가 모두 실패했다
  (요원 흰색, 두 층 맵 재질은 텍스처 실패로 맵 전체가 실패 → 미니맵 바닥)
- CSP 를 csp.ts 하나로 모으고 vite preview 도 같은 CSP 로 열어 헤드리스 확인이 실제와 같은 제한에서 되게 함
- 맵 B 층 텍스처 하나를 못 읽어도 맵 전체를 버리지 않음
- 시험: connect-src 에 blob: 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 22:30:00 +09:00
EJClaw
759334ac79 맵 3D 자동 갱신: 요원 · 무기 추출 실패나 빠진 요원 · 무기가 있으면 올리지 않고 재시도 (기존 목록 보존) · 시험 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 21:00:08 +09:00
EJClaw
f584ba60b3 테스트 기록: v1.7.0 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:56:03 +09:00
EJClaw
4cd6f1103f v1.7.0: 3D 리플레이 완전 3D (맵 색 · 요원 · 총 · 스킬 모양 · 1인칭/자유시점) · 작업 노트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:37:47 +09:00
EJClaw
f82857f476 3D 리플레이: 스킬 종류별 모양(연막 · 장판 · 폭발 · 정찰 고리 · 설치물 · 스파이크 3D)과 요원 색
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:35:44 +09:00
EJClaw
86c42d99ca map-extract: __pycache__ 무시
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:25:32 +09:00
EJClaw
f8f585f230 3D 리플레이: 요원 3D 몸(뼈대 · 텍스처 · 공용 걷기/달리기 + 총 든 자세) · 총 22종 추출, 재생기가 원기둥 대신 요원과 손에 든 총을 그림
- map-extract agents: 요원 30명 agent_<코드>.glb (위/아래 몸 애니메이션 분리, ACL 풀기용 CUE4Parse-Natives 를 g++ 로 빌드), 무기 weapon_<이름>.glb
- pack.py: 요원 · 무기도 압축해 index.json agents · weapons
- 사이트: AgentRig (이동 방향 · 속도로 다리 애니메이션 섞기, 오른손에 총), 1인칭 · 자유시점에서 이름표 작게

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:25:27 +09:00
EJClaw
d87f4ade27 3D 리플레이: 1인칭 · 자유시점 카메라, 선수가 들고 있는 총 (변환기 equips · 이름표 · 킬 피드)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 19:48:48 +09:00
EJClaw
6d71abaabd 맵 3D: 재질 · 텍스처(디퓨즈 256px) · 두 층 섞기 · 법선 포함 glb, 사이트가 glb 재질로 그림
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 19:40:19 +09:00
EJClaw
1ee753bc79 테스트 기록: v1.6.0 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:41:59 +09:00
EJClaw
b9431c1a15 v1.6.0: 사이트 '내 정보'(표시 이름 · 색 · 라이엇 ID · 녹음 제외) · 관리 페이지
- 사이트 오른쪽 위 내 이름 → 내 정보: 표시 이름 바꾸기/되돌리기, 색, 라이엇 ID, 녹음 제외, 로그아웃
- 관리 페이지 /admin (관리자): 게임 PC 상태 · 앱 새 버전 안내, 유저별 표시 이름 · 색 · 라이엇 ID · 녹음 제외,
  앱 등록 · 역할 · 해제(최고 관리자). /site/admin/* 는 /app/admin/* 와 같은 처리
- 서버: 표시 이름 검사(길이 · 보이지 않는 글자 · 다른 사람과 겹침), 지우면 디스코드 이름으로 되돌림,
  바뀌면 게임 PC 앱에 바로 보냄 (PUT /api/internal/names)
- 앱: PATCH /api/users/:id (본인 또는 관리자, 남의 라이엇 ID 는 관리자만), PUT /api/internal/names
- 테스트: 앱 user-settings 3개, 사이트 서버 profile-admin 3개

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:27:17 +09:00
EJClaw
916b35c691 테스트 기록: v1.5.0 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:14:34 +09:00
EJClaw
84ba2e3e64 3D 리플레이: 사이트가 변환 실패 이유를 보여 주고 사이트 로그에 남김 · 작업 노트 v1.5.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 14:57:03 +09:00
EJClaw
adc1c66f47 v1.5.0: 게임 PC 앱이 발로란트 리플레이(.vrf)를 찾아 변환해 사이트 3D 재생기로 보냄
- 앱: %LOCALAPPDATA%\VALORANT\Saved 아래 <경기 ID>.vrf 를 찾아 gvr-replay.exe 로 변환,
  GVR-Data/replays/<경기 ID>.json.gz 로 보관 (원본 · 앱 버전이 같으면 다시 변환하지 않음)
- GET /api/matches/:id/replay: gzip JSON, 처음 변환이 15초를 넘으면 202 converting,
  실패 422 replay_failed(이유), 변환기 없음 500. GET /api/replays: 찾은 리플레이 목록
- 변환은 한 번에 하나, 낮은 우선순위. 실패한 파일은 다시 내려받을 때까지 다시 하지 않음
- 중계: content-encoding 이 있는 응답은 바이너리 조각으로 (gzip 이 깨지지 않게)
- 사이트: 변환 중(202)이면 3초마다 다시 묻고 '변환하는 중' 표시, 변환 실패 안내
- 빌드: win-ci 가 .NET 10 SDK 로 gvr-replay.exe(단일 파일)를 만들어 resources/replay 에 넣고,
  시험 리플레이로 변환기 · 포터블 앱 안 변환까지 확인 (smoke GVR_SMOKE_VRF)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 14:55:38 +09:00
EJClaw
cba50d60ab 검토 반영: 실시간 연결 권한 회수 · 맵 자동 갱신 재시도/누락 방지
- 사이트 /ws: 세션 삭제(서버 탈퇴 재확인) · 로그아웃이면 이미 열린 연결도 4401 로 끊는다 (30초마다 확인, 로그아웃은 바로)
- update.sh: 모든 단계 공통 실패 처리(ERR trap) · 같은 조합은 30분→6시간 간격으로 재시도 · 첫 실패/성공 알림
  · 지금 사이트에 있는 맵이 새 결과에 하나라도 없으면 올리지 않음 (--force 로만)
- gvr-map-extract: 맵 찾기 중 레벨 읽기 실패도 실패로 (빠진 맵으로 덮어쓰지 않게)
- 테스트: security.test.ts 연결 끊기 1개, scripts/test-update.sh 10개

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 14:15:52 +09:00
EJClaw
0c1e726168 발로란트 맵 3D: 모든 맵을 Riot CDN 에서 바로 추출해 3D 리플레이에 붙임 · 매핑 업데이트 자동 적용
- tools/map-extract (C#, CUE4Parse 고정 커밋): 게임 파일을 받지 않고 매니페스트 조각만 HTTP Range 로 읽어
  맵 22개(일반 13 · 팀 데스매치 5 · 스커미시 3 · 어빌리티 드래프트)를 월드 좌표 glb 로. 3.1분 · 587MB 받음
- scripts/pack.py (gltfpack -cc + gzip, 맵당 0.5~4.6MB) · update.sh (uedb 매핑 · 라이브 패치 확인 → 매핑 보관 →
  추출 → .5 data/maps3d 반영) · install.sh (systemd 사용자 타이머 30분, 메모리 6GB 상한)
- 사이트 서버: GET /site/maps3d* (로그인 필요, gzip 그대로). CSP 에 'wasm-unsafe-eval' (meshopt 압축 풀기만)
- 3D 재생기: 맵 3D 위에 선수 표시, 천장 자르기(자동 · 없음 · 직접), 높이 색칠. 맵이 없거나 실패하면 미니맵
- 리플레이 칸: 리플레이를 아직 안 보내는 앱 버전이면 그렇게 안내
- 테스트: maps3d.test.ts 2개, CSP 테스트 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 14:01:22 +09:00
EJClaw
86f422e8f0 사이트 로그인: 앱에서 녹음할 서버로 고른 서버 멤버만 (아니면 '봇과 다른 서버' 안내)
- 앱이 서버를 알려 준 뒤에는 ALLOWED_GUILD_IDS 대신 그 서버 하나만 허용
- 앱에서 녹음할 서버를 바꾸면 사이트 서버에 바로 다시 알린다 (hello)
- 로그인 화면: GET /auth/guild 로 서버 이름 안내
- 테스트 2개 (login-guild.test.ts)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 13:38:17 +09:00
EJClaw
c5100bce75 작업 노트: nextcloud 보관 위치를 claude/ 폴더로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 13:12:42 +09:00
EJClaw
84fa8e4a71 작업 노트: 발로란트 13.08 공개 매핑(uedb.dev)으로 어비스 맵 전체 추출 확인
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 13:11:59 +09:00
EJClaw
001788b7fb 작업 노트: 완전 3D 리플레이 조사 결과 (게임 파일 받기 · 매핑 문제 · 메모리 주의)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:18:50 +09:00
EJClaw
9592efeff6 3D 리플레이 1단계: .vrf 변환기(tools/replay-extract) · 사이트 3D 재생기 · 대화 동기화
- tools/replay-extract: ValorantReplayParser(MIT, 고정 커밋) → gvr-replay JSON v1
  (선수 이동 10Hz · 라운드 · 킬 · 사격 · 스킬/설치물 · 녹화 시작 시각)
- 사이트: 경기 화면 '3D 리플레이' 칸 (three.js 지연 로드). 미니맵 바닥 + 실제 높이,
  회전 · 확대 · 선수 선택 · 따라가기 · 킬피드 · 자막 · 말하는 사람 표시
- 동기화: 같은 킬의 경기 기록 시각과 리플레이 시각 차이 중앙값 (못 맞추면 라운드 시작)
  현장 모드 시계에 묶어 재생 · 멈춤 · 이동 · 배속이 대화와 같이 움직임
- 목 서버 데모(GVR_MOCK_REPLAY), 동기화 테스트 4개

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 03:56:43 +09:00
EJClaw
50fc90070b 테스트 기록: v1.4.3 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:42:10 +09:00
EJClaw
010d2475cc v1.4.3: 상대 닉네임을 말로 적던 문제 ("QQQWWWQ")
- 선수 이름은 한글이 들어간 것만 핫워드로 넣는다
- 결과가 선수 이름(조각)뿐이면 워커가 이름을 빼고 다시 변환 (is_name_echo, player_names)
- 예전에 이렇게 적힌 발화는 한 번만 정밀 모델로 다시 변환 (파일 없으면 숨김, 고친 발화 제외)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:30:21 +09:00
EJClaw
a4511a8eaf 사이트: 모르는 유저 다시 받기가 한 번 실패하면 영영 안 받던 문제
받는 중 중복만 막고, 실패하면 다음 이벤트에서 다시 받는다 (성공한 아이디만 기억).
lib/unknown-users.ts 로 빼고 테스트 추가, 목 서버에 /mock/users-fail · latejoin?again=1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 22:56:45 +09:00
EJClaw
0b8789c895 테스트 기록: v1.4.2 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 22:51:36 +09:00
EJClaw
79d6bb2aad v1.4.2: 녹음 중에 들어온 사람이 사이트에서 "알 수 없음"으로 뜨던 문제
- 앱: 녹음 중 새로 들어온 사람을 저장한 뒤 users.updated 를 보낸다
- 사이트: 실시간 발화 · 녹음 상태에 모르는 유저 아이디가 오면 유저 목록을 한 번 다시 받는다 (예전 앱 대비)
- 목 서버: /mock/latejoin 로 재현

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 22:41:48 +09:00
EJClaw
c6a8721fce 테스트 기록: v1.4.1 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:55:50 +09:00
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
EJClaw
b230443409 v1.3.3: 따라갈 사람 목록 · 롤 채팅 OCR 제거 · 표시 이름(실명 숨기기)
- 따라갈 사람: 봇이 서버를 지켜보기 전 멤버 요청을 사이트 서버가 forbidden 으로 거절하고 앱이 오류를 숨겨 빈 목록이 됐다
  → 가입한 서버면 지켜보기 전에도 응답(source.members 가 멤버 확인), 앱은 오류 · 다시 불러오기 표시
  → 내 계정 → 관리자(GET /app/admins) → 이름순, 녹음할 서버를 바꾸면 봇을 다시 붙여 새 서버를 지켜봄
- 롤 채팅 OCR 제거: 앱 설정 · 마법사 · 진단 · lol.ts · 워커 ocr.py/ocr_* op · pywinrt/mss/Pillow · win-ci ocr_lang
  롤은 게임 중 전체/팀 채팅 API 가 없어 LCU(챔피언 선택 · 게임 후) + r3dlog(남아 있을 때, LCU 채팅을 지우지 않고 추가)
- 표시 이름: 서버 store.displayNames (세션 · 앱 유저 · 접속 기록 이름까지 바꿈), GET /app/names, PUT /app/admin/names,
  cli name. 앱은 받아서 users · 지난 범인 분석 이름을 바꾸고 이후 디스코드 이름 대신 저장. 관리자 탭에 편집 UI
- 저장소 시연 · 테스트 데이터 · 화면 캡처 · 계획서 PDF 의 실제 이름을 가짜 이름으로 교체
- 테스트: 앱 41 · 서버 16 · 워커 39 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:42:57 +09:00
EJClaw
7db2a5d69f 테스트 기록: v1.3.2 릴리스 · 배포
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:20:57 +09:00
EJClaw
b8e76aba25 범인찾기 v1.3.2: 외부 전적 사이트 접속 제거 — OP.GG · LOL.PS 는 계산법만 참고
- 사용자 결정: 실제 OP.GG 연결이 아니라 계산법 참고 → 분석 때 OP.GG 를 찾아보던 opgg.ts · 결과의 OP.GG 점수 · 조회 상태 · 지시문 줄 · Riot 태그/경기 찾기 정보 제거
- 남은 것: 기록 점수(OP.GG OP스코어 계산법, 앱이 경기 기록으로 계산) · 10/15분 라인전(LOL.PS 정의)
- 실제 E2E (Claude Opus 5.5 high, 외부 접속 없음): 발로란트 33초 $0.138, 롤 36초 $0.123
- 테스트: 앱 40 · 서버 16 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:11:53 +09:00
EJClaw
2ddba2e4e5 README · 테스트 기록: v1.3.1 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:05:55 +09:00
248 changed files with 21470 additions and 1593 deletions

102
README.md
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.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.0) (`GameVoiceRecorder-1.3.0-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.0-portable.exe`) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
- Windows 실행 파일: Gitea 릴리스 [v1.9.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.9.0) (`GameVoiceRecorder-1.9.0-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.9.0-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,87 @@
- 앱은 시작할 때와 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.6.0 바뀐 점
- **내 정보** (사이트 오른쪽 위 내 이름 누르기, `site/web/src/components/UserEdit.tsx`): 표시 이름 바꾸기 · 되돌리기(디스코드 서버 별명으로), 내 색, 라이엇 ID, 녹음 제외, 내 기록 보기 · 관리 페이지 · 로그아웃
- 표시 이름은 사이트 서버에 저장하고(`PUT /site/profile/name`, 1~32자 · 보이지 않는 글자 금지 · 다른 사람 표시 이름과 겹치면 거절 · 10분에 10번) 게임 PC 앱에 바로 보낸다(`PUT /api/internal/names`, 예전 앱은 10분마다 받아 감)
- 색 · 라이엇 ID · 녹음 제외는 게임 PC 앱 기록에 저장 (`PATCH /api/users/:id`, 본인 또는 관리자. 다른 사람에게 연결된 라이엇 ID 는 본인이 가져갈 수 없음)
- **관리 페이지** `/admin` (관리자 · 최고 관리자, `site/web/src/pages/AdminPage.tsx`): 게임 PC 연결 · 앱 버전 · 새 버전 안내(Gitea 최신 릴리스), 녹음된 사람 + 앱 등록 유저 목록에서 표시 이름 · 색 · 라이엇 ID · 녹음 제외 바꾸기, 앱 등록 · 역할 · 해제(최고 관리자). 서버 `/site/admin/*` 는 앱 관리자 탭 `/app/admin/*` 와 같은 코드 (`site/server/src/app-auth.ts`). 표시 이름은 사이트에서는 관리자도 바꿀 수 있다
## v1.5.0 바뀐 점
- **3D 리플레이**: 발로란트 경력 탭에서 경기 리플레이를 내려받아 두면, 사이트 경기 화면 "3D 리플레이"를 열 때 게임 PC 앱이 `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<경기 ID>.vrf` 를 찾아 변환해 보낸다 (처음 한 번 10초 안팎, 그 뒤로는 `GVR-Data/replays/<경기 ID>.json.gz` 보관본). 선수 10명이 3D 맵 위에서 움직이고 그때 대화가 같이 재생된다
- 변환기 `resources/replay/gvr-replay.exe` (`tools/replay-extract`, .NET 단일 파일). 한 번에 하나 · 낮은 우선순위로 돌린다. 실패하면 이유를 사이트에 보여 주고, 같은 파일은 다시 내려받을 때까지 다시 하지 않는다
- 앱 `app/src/core/replays.ts`, API `GET /api/matches/:id/replay` (gzip JSON, 변환 중 202) · `GET /api/replays` (찾은 리플레이 목록)
## v1.4.3 바뀐 점
- 상대 닉네임을 말로 적던 문제 (예: 말소리가 "QQQWWWQ"로 나옴): 그 경기 선수 이름을 모두 핫워드로 넣어서, 말을 못 알아들으면 Whisper 가 닉네임을 그대로 적었다. 이제
- 선수 이름은 한글이 들어간 것만 핫워드로 넣는다 (영문 · 숫자 닉네임은 한국어 말로 나올 일이 거의 없음)
- 결과가 선수 이름(또는 그 조각)뿐이면 워커가 선수 이름을 빼고 한 번 더 변환한다 (`worker/gvr_worker/stt.py` `is_name_echo`, 앱이 `player_names` 로 넘김)
- 한 번만: 예전에 이렇게 적힌 발화를 정밀 모델로 다시 변환한다 (음성 파일이 지워졌으면 숨김, 사람이 고친 발화는 그대로). `app/src/core/stt/pipeline.ts` `recheckNameEchoes`
## v1.4.2 바뀐 점
- 녹음 중에 음성채널에 들어온 사람이 사이트에서 "알 수 없음"으로 뜨던 문제: 앱이 그 사람을 유저로 저장만 하고 `users.updated` 를 보내지 않았다. 이제 들어올 때 보낸다 (`app/src/core/discord/bot.ts` onVoiceState)
- 사이트도 실시간 발화 · 녹음 상태에 처음 보는 사람 아이디가 오면 유저 목록을 한 번 다시 받아 온다 (v1.4.1 이하 앱에서도 이름이 뜸)
## 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`
- **롤 채팅은 API 로만**: 화면 글자 인식(OCR)을 앱 · 워커 · 빌드에서 모두 뺐다 (pywinrt · mss · Pillow 의존성 제거). 롤 클라이언트(LCU) API 로 챔피언 선택 · 게임 후 채팅을 받는다. 롤은 게임 중 전체 · 팀 채팅을 주는 API 가 없다 (LCU · 게임 클라이언트 API 모두, 비공식 포함). 게임 로그 파일(r3dlog)에 채팅이 남아 있으면 경기 뒤에 붙인다
- **표시 이름 (실명 숨기기)**: 디스코드 아이디마다 보일 이름을 정하면 사이트(로그인 이름 · 대화 기록 · 유저 목록), 앱, 범인 분석에 그 이름만 쓰고 이미 저장된 이름도 바꾼다. 앱 🛡️ 관리자 탭에서 최고 관리자가 정한다. 서버: `GET /app/names`, `PUT /app/admin/names`, `node dist/cli.js name <아이디> [이름]`
- 저장소의 시연 · 테스트 데이터, 화면 캡처, 계획서 PDF 에서 실제 이름을 빼고 가짜 이름(하늘)으로 바꿨다
## 디스코드 봇
- 기본은 **겜녹이 봇으로 진행**: 토큰을 넣지 않아도 로그인만 하면 바로 연결된다. 봇은 사이트 서버가 디스코드에 연결하고, 앱은 로그인 토큰으로 서버 중계(`/app/bot/ws`)를 받는다.
@@ -37,17 +118,16 @@
- 사이트 서버: 보안 정책(CSP)으로 이 사이트 스크립트와 이 사이트로의 접속만 허용, 실시간 WebSocket 은 이 사이트에서 온 연결만, 로그인 세션 · 앱 토큰 · 기기 키는 해시로만 저장, 로그에서 로그인 code · state · 검색어를 지운다. 등록 코드 대입 · 로그인 요청 폭주는 IP 별로 막는다. HSTS · http→https 이동 · TLS 1.2 미만 차단은 앞단 프록시(NPMplus)가 한다.
- 디스코드 음성은 디스코드 자체 암호화(DAVE 종단간 암호화)로 간다.
## 🔍 범인찾기 (v1.3.0~)
## 🔍 범인찾기 (v1.3.2~)
끝난 경기를 고르고 "범인 분석"을 누르면 AI(Claude)가 그 경기의 음성 대화 · 킬 · 라운드/오브젝트 · 경제 · 채팅 · 10명 스탯을 읽고 10명 평점 · 태그 · 한 줄 평과 팀별 범인 1명(이유 + 근거)을 만든다. 근거를 누르면 그 순간의 음성 · 타임라인으로 간다. 계획서: [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf)
- 정한 것 (2026-10-15): 범인 = 가장 못함 + 가장 발목 + 결과의 원인을 종합해 팀마다 1명 · 분석 버튼은 등록된 앱 유저 이상(다시 분석은 관리자) · Claude Opus 5.5(생각 high) · 말투 중간맛 · 녹음 안내(TTS)에 "녹음된 대화는 AI 경기 분석에 쓰일 수 있어요" 추가
- **전적 사이트 점수 참고**: 평점과 범인은 전적 사이트 점수에서 출발해 승부처 · 역할 · 경제 · 음성 소통으로 더하고 뺀다 (지시문 v1.2)
- **기록 점수** (0~10, 모든 경기): OP.GG OP스코어를 우리 기록으로 다시 계산한 점수 + 경기/팀 순위 + MVP · ACE + 점수를 올리고 깎은 지표. 발로란트는 OP.GG 가 밝힌 입력(라운드 승률 · KAST · ACS · 피해 격차), 롤은 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드. 계수는 OP.GG 공식 MCP 로 받은 실제 경기의 OP스코어에 맞췄다 (교차 검증: 발로란트 상관 0.97 · 평균 오차 0.49점, 롤 상관 0.94 · 0.60점 · 팀 최하위 일치 85%). `packages/shared/src/rating.ts`, 맞추는 도구 `tools/opscore-fit/`
- **OP.GG 실제 OP스코어**: 분석할 때 OP.GG 공식 MCP(`mcp-api.op.gg`)에서 그 경기를 찾으면 그 사이트의 실제 점수를 같이 준다 (롤: 시작 시각 · 길이로 찾고 10명, 발로란트: 경기 번호로 선수마다). 내전(사용자 설정 게임)은 OP.GG 에 없어 기록 점수만 쓴다. `site/server/src/opgg.ts`, 끄기 `CULPRIT_OPGG=0`
- **전적 사이트 계산법 참고**: 평점과 범인은 기록 점수에서 출발해 승부처 · 역할 · 경제 · 음성 소통으로 더하고 뺀다 (지시문 v1.2). 분석할 때 외부 전적 사이트에는 접속하지 않고, 앱이 경기 기록으로 직접 계산한다
- **기록 점수** (0~10, 모든 경기): OP.GG OP스코어 계산법을 따라 우리 기록으로 계산한 점수 + 경기/팀 순위 + MVP · ACE + 점수를 올리고 깎은 지표. 발로란트는 OP.GG 가 밝힌 입력(라운드 승률 · KAST · ACS · 피해 격차), 롤은 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드. OP.GG 는 가중치를 공개하지 않아서, 계수는 개발할 때 한 번 OP.GG 공식 MCP 로 받은 실제 경기 점수에 맞춰 정했다 (교차 검증: 발로란트 상관 0.97 · 평균 오차 0.49점, 롤 상관 0.94 · 0.60점 · 팀 최하위 일치 85%). `packages/shared/src/rating.ts`, 맞추는 도구 `tools/opscore-fit/`
- **LOL.PS 라인전**: LOL.PS 라인전 점수의 입력과 같은 10 · 15분 맞라이너 CS · 골드 · 경험치 차 (LOL.PS 점수 모델은 공개되지 않아 차이 값만). 참고한 원문 · 구현 대응: [`tools/opscore-fit/README.md`](tools/opscore-fit/README.md)
- 실제 E2E (2026-10-15, `app/scripts/culprit-real-e2e.mts`): 실제 Claude Opus 5.5(생각 high) + 실제 OP.GG. 발로란트 시연 경기 42초 · $0.15, 롤 실제 랭크 경기(OP.GG 점수 10명 찾음) 36초 · $0.11. 기록 · [`docs/dev/test-results.md`](docs/dev/test-results.md)
- 리플레이 동기화: 공식 · 비공식 API 로 리플레이 시간을 읽을 수 있을 때만 넣는다 (화면 글자 인식(OCR) · 게임 설정 파일 고치기는 하지 않음). Windows 실기 확인 전이라 v1.3.0 에는 없다
- 실제 E2E (2026-10-15, v1.3.2, `app/scripts/culprit-real-e2e.mts`): 실제 Claude Opus 5.5(생각 high), 외부 사이트 접속 없음. 발로란트 시연 경기 33초 · $0.138, 롤 시연 경기 36초 · $0.123. 기록 · [`docs/dev/test-results.md`](docs/dev/test-results.md)
- 리플레이 동기화: 공식 · 비공식 API 로 리플레이 시간을 읽을 수 있을 때만 넣는다 (화면 글자 인식(OCR) · 게임 설정 파일 고치기는 하지 않음). Windows 실기 확인 전이라 v1.3.x 에는 없다
- 앱: 경기 상세에서 추가 지표 저장(발로란트 피해량 · 받은 피해 · KAST · 첫킬 · 설치/해체 · 라운드별 장비, 롤 포지션 · 딜량 · 시야 · 10/15분 CS), "분석할 수 있는 경기" 판정(경기 결과 · 녹음 공백 1분 · 음성 변환), 근거 번호가 달린 AI 자료 만들기, 결과 저장(`culprit_analyses`). `app/src/core/culprit.ts`
- 사이트 서버: Claude API 키는 서버 환경 변수 `ANTHROPIC_API_KEY` 에만 (`deploy/site/set-anthropic-key.sh`). 권한 · 월 $100 · 하루 20회 · 중복 잠금, 구조화 출력, 근거 번호 확인, 비용 장부(토큰 · 비용만, 대화 내용 없음). `site/server/src/culprit.ts`, 지시문 · 지식 묶음 `site/server/prompt/` (지식 묶음의 요원 · 챔피언 목록은 공식 데이터로 하루 한 번 갱신)
- 화면: 사이트 🔍 범인찾기 탭 (`site/web/src/pages/CulpritPage.tsx`), 경기 화면의 "🔍 범인 보기". 화면 확인: `node --import tsx app/scripts/culprit-shots.mts`
@@ -60,18 +140,18 @@
| M1 녹음 + STT 기본 | 따라가기·명령 참여, TTS 안내, 유저별 녹음, 대기열 STT, /녹음제외·참여 | ✅ 완료 ([실음성 테스트](docs/dev/test-results.md)) |
| M2 사이트 서버 · 사이트 v1 | 디스코드 로그인, 연결 확인·잠금, 타임라인·따라 읽기·필터·검색·실시간 | ✅ 완료 · https://gvr.tkrmagid.kr 배포 |
| M3 발로란트 연동 | 경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과 시간, 경기 상세 | ✅ 완료 ([전체 스택 테스트](docs/dev/test-results.md)) |
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ✅ 완료 (Windows 실기 확인: [기록](docs/dev/test-results.md)) |
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ✅ 완료 (Windows 실기 확인: [기록](docs/dev/test-results.md)) · v1.3.3 에서 OCR 은 빼고 LCU API · 로그 파일만 씀 |
| M5 exe · 설정 · 모델 | 포터블 exe, 첫 실행 마법사, GPU 감지·모델 다운로드, 암호화 저장, 7일 삭제 | ✅ 완료 (Windows 빌드·실행 확인) |
| 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.0) | AI(Claude Opus 5.5 high) 10명 평점 · 팀별 범인 · 근거, 기록 점수(OP.GG OP스코어 방식) · OP.GG 실제 점수 · LOL.PS 라인전 | ✅ 완료 (실제 Claude · OP.GG E2E, 사이트 배포, [v1.3.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.0) · 리플레이 동기화는 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 실기 확인 뒤) |
## 저장소 구조
```
app/ 게임 PC 앱 (Electron + Node.js 코어, TypeScript)
worker/ STT 워커 (Python, faster-whisper, OCR, 모델 관리, 파인튜닝)
worker/ STT 워커 (Python, faster-whisper, 롤 로그 채팅, 모델 관리, 파인튜닝)
site/server/ 사이트 서버 (Fastify, Discord OAuth2, 기기 중계)
site/web/ 사이트 화면 (React + Vite)
packages/shared/ 앱·사이트 공통 타입
@@ -95,5 +175,5 @@ deploy/site/deploy.sh # .5 배포 (deploy/README.md)
# 앱 코어 (헤드리스)
cd app && npm install && npm test
npm run core -- --diagnose # 게임 PC 진단 (GPU·STT 속도·Riot API·OCR)
npm run core -- --diagnose # 게임 PC 진단 (GPU·STT 속도·Riot API·롤 로그 채팅)
```

10
app/package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "gvr-app",
"version": "1.3.1",
"version": "1.9.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gvr-app",
"version": "1.3.1",
"version": "1.9.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.1",
"version": "1.9.1",
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
"private": true,
"main": "dist/main.cjs",
@@ -76,6 +76,13 @@
"from": "../worker/dist/gvr-worker",
"to": "worker"
},
{
"from": "../tools/replay-extract/out/win",
"to": "replay",
"filter": [
"gvr-replay.exe"
]
},
{
"from": "../assets/app",
"to": "brand",
@@ -107,7 +114,8 @@
},
"portable": {
"artifactName": "GameVoiceRecorder-${version}-portable.exe",
"unpackDirName": "GameVoiceRecorder"
"unpackDirName": "GameVoiceRecorder",
"splashImage": "../assets/app/splash.bmp"
}
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -1,119 +1,53 @@
// 범인찾기 실제 E2E: 실제 앱 코어 + 실제 사이트 서버 + 실제 Claude API(Opus 5.5, 생각 high) + 실제 OP.GG MCP + 헤드리스 브라우저.
// 1) 발로란트 시연 경기 (22라운드 · 대화) → OP.GG 에 없는 경기 → 기록 점수만으로 분석
// 2) 롤: OP.GG 에서 받은 실제 랭크 경기(10명 실제 스탯)에 우리 팀 2명의 대화를 붙인 경기 → OP.GG 실제 OP스코어를 찾아 같이 분석
// 비용이 든다 (경기당 약 $0.4). API 키는 secrets.json 에서 읽어 이 프로세스 안에서만 쓴다.
// 범인찾기 실제 E2E: 실제 앱 코어 + 실제 사이트 서버 + 실제 Claude API(Opus 5.5, 생각 high) + 헤드리스 브라우저.
// 외부 전적 사이트에는 접속하지 않는다 (기록 점수는 OP.GG 계산법을 따라 경기 기록으로 계산).
// 1) 발로란트 시연 경기 (22라운드 · 대화) 2) 롤 시연 경기 (10 · 15분 라인전 · 대화)
// 비용이 든다 (경기당 약 $0.1~0.4). API 키는 secrets.json 에서 읽어 이 프로세스 안에서만 쓴다.
// node --import tsx scripts/culprit-real-e2e.mts [결과 폴더]
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type { CulpritInput, CulpritMatchInfo, MatchPlayer } from '@gvr/shared';
import type { CulpritInput, CulpritMatchInfo } from '@gvr/shared';
import { makeDemoLol } from '../test/fixtures/demo-matches.ts';
import { culpritApi, MIN, seedValorant, setup } from '../test/fixtures/culprit-seed.ts';
const outDir = process.argv[2] || path.join(os.homedir(), '.tmp', 'culprit-real');
fs.mkdirSync(outDir, { recursive: true });
const root = path.resolve(import.meta.dirname, '..', '..');
const apiKey = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.config/ejclaw/secrets.json'), 'utf8')).credentials['anthropic.api/game-voice-recorder'].token as string;
const { opggCaller } = await import('../../site/server/src/opgg.ts');
const opgg = opggCaller();
const core = setup();
await core.assets.refresh(true).catch(() => undefined);
const { id: valId } = seedValorant(core);
// ---------------------------------------------------------------- 롤: OP.GG 의 실제 랭크 경기
const POS: Record<string, string> = { TOP: '탑', JUNGLE: '정글', MID: '미드', ADC: '원딜', SUPPORT: '서폿' };
const listOf = async (name: string, tag: string) =>
((await opgg('lol_list_summoner_matches', { game_name: name, tag_line: tag, region: 'KR', limit: 10, desired_output_fields: ['data.game_history[].{created_at,game_length_second,game_type,id}'] })) as any).data.game_history as any[];
const detailOf = async (g: any) =>
((await opgg('lol_get_summoner_game_detail', {
region: 'KR',
game_id: g.id,
created_at: g.created_at,
desired_output_fields: [
'data.game_detail.teams[].participants[].stats.{assist,champion_level,death,gold_earned,kill,minion_kill,neutral_minion_kill,op_score,time_ccing_others,total_damage_dealt_to_champions,total_damage_taken,vision_wards_bought_in_game,ward_place}',
'data.game_detail.teams[].participants[].{position,team_key,champion_id,champion_name}',
'data.game_detail.teams[].participants[].summoner.{puuid,game_name,tagline,player}',
'data.game_detail.teams[].game_stat.{champion_kill,is_win}',
],
})) as any).data.game_detail;
// 프로 선수가 아닌 사람의 최근 솔로 랭크 (15분 이상)
const seedGame = (await listOf('Hide on bush', 'KR1')).find((g) => g.game_type === 'SOLORANKED')!;
const seedDet = await detailOf(seedGame);
const pick = seedDet.teams.flatMap((t: any) => t.participants).find((p: any) => !p.summoner.player && p.summoner.game_name !== 'Hide on bush');
const g = (await listOf(pick.summoner.game_name, pick.summoner.tagline)).find((x) => x.game_type === 'SOLORANKED' && x.game_length_second > 1200)!;
const det = await detailOf(g);
const all = det.teams.flatMap((t: any) => t.participants.map((p: any) => ({ ...p, win: t.game_stat.is_win, teamKills: t.game_stat.champion_kill })));
const selfP = all.find((p: any) => p.summoner.puuid === pick.summoner.puuid) ?? all[0];
const opggTruth = new Map<string, number>(all.map((p: any) => [p.summoner.puuid, p.stats.op_score]));
const players: MatchPlayer[] = all.map((p: any) => ({
puuid: p.summoner.puuid,
name: p.summoner.game_name,
tag: p.summoner.tagline,
team: p.team_key,
ally: p.team_key === selfP.team_key,
character: { id: String(p.champion_id), name: p.champion_name, icon: null },
kills: p.stats.kill,
deaths: p.stats.death,
assists: p.stats.assist,
cs: (p.stats.minion_kill ?? 0) + (p.stats.neutral_minion_kill ?? 0),
gold: p.stats.gold_earned,
level: p.stats.champion_level,
stats: {
role: POS[p.position],
damage: p.stats.total_damage_dealt_to_champions,
damageTaken: p.stats.total_damage_taken,
ccSeconds: p.stats.time_ccing_others ?? 0,
wardsPlaced: p.stats.ward_place ?? 0,
controlWards: p.stats.vision_wards_bought_in_game ?? 0,
},
}));
const LS = Date.parse(g.created_at) + 60000;
const LEN = g.game_length_second * 1000;
const allyWin = !!selfP.win;
const allyKills = all.filter((p: any) => p.team_key === selfP.team_key)[0].teamKills;
const enemyKills = all.filter((p: any) => p.team_key !== selfP.team_key)[0].teamKills;
const lolId = `lol-${g.id.replace(/[^\w]/g, '').slice(0, 20)}`;
core.store.upsertMatch({
id: lolId,
game: 'lol',
started_at: LS,
ended_at: LS + LEN,
status: 'complete',
map: 'Map11',
mode: 'CLASSIC',
queue: '420',
result: JSON.stringify({ win: allyWin, score: { ally: allyKills, enemy: enemyKills } }),
detail: JSON.stringify({ live: false, players, goldDiff: [], self: selfP.summoner.puuid }),
});
// 우리 팀 두 명이 음성채널에 있었다고 하고 대화를 붙인다 (실제 경기 기록 + 시험용 대화)
const mates = players.filter((p) => p.ally);
const [a, b] = [mates.find((p) => p.puuid === selfP.summoner.puuid)!, mates.find((p) => p.puuid !== selfP.summoner.puuid)!];
core.store.upsertUser({ id: 'ua', name: '승한', avatar: null });
core.store.upsertUser({ id: 'ub', name: '민수', avatar: null });
core.store.setAccounts('ua', [{ puuid: a.puuid, riotId: `${a.name}#${a.tag}` }]);
core.store.setAccounts('ub', [{ puuid: b.puuid, riotId: `${b.name}#${b.tag}` }]);
// ---------------------------------------------------------------- 롤 시연 경기 + 우리 팀 2명 대화
const LS = Date.now() - 80 * MIN;
const lol = makeDemoLol();
const lolId = 'lol-demo';
core.store.setMeta('riot_self_puuid', 'l-sh');
core.store.setAccounts('u1', [{ puuid: 'p-sh', riotId: '하늘#V' }, { puuid: 'l-sh', riotId: '하늘#L' }]);
core.store.setAccounts('u2', [{ puuid: 'p-ms', riotId: '민수#V' }, { puuid: 'l-ms', riotId: '민수#L' }]);
core.store.startSession('s-lol', 'g', 'c', '음성', LS - MIN);
core.games.matchStarted({ id: lolId, game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
core.games.matchEnded(lolId, LS + lol.durationMs);
(core.games.adapters[1] as any).applyHistory(lolId, lol.game, lol.timeline, LS);
const talk: [string, number, string][] = [
['ua', 2.5, '정글 위쪽에서 시작했어 바텀 조심해'],
['ub', 6.2, '용 앞에 와드 박아 줘 시야 없어'],
['ua', 6.5, '알았어 지금 갈게'],
['ub', 11.0, '미드 미아 미드 미아 내려간다'],
['ua', 14.8, '용 한타 열지 마 아직 우리 텔 없어'],
['ub', 15.1, '아 들어갔다 아 죽었다 미안'],
['ua', 19.5, '바론 시야 먼저 잡고 하자 혼자 가지 마'],
['ub', 24.0, allyWin ? '좋아 한타 이겼다 미드 밀자' : '아 또 잡혔네 이거 그냥 서렌 치자'],
['ua', 24.3, allyWin ? '억제기 깨고 바로 빠지자' : '아직 안 끝났어 수비하자'],
['u1', 2.5, '정글 위쪽에서 시작했어 바텀 조심해'],
['u2', 6.2, '용 앞에 와드 박아 줘 시야 없어'],
['u1', 8.1, '용 같이 하자 바텀 밀었어'],
['u2', 8.3, '아니 탑 갱 각이야 잠깐만'],
['u1', 14.8, '용 한타 열지 마 아직 우리 텔 없어'],
['u2', 15.1, '아 들어갔다 아 죽었다 미안'],
['u1', 19.5, '바론 시야 먼저 잡고 하자 혼자 가지 마'],
];
for (const [uid, min, text] of talk) {
if (min * MIN > LEN) continue;
const ts = LS + min * MIN;
const id = `lol-${uid}-${min}`;
core.store.insertUtterance({ id, session_id: 's-lol', user_id: uid, started_at: ts, ended_at: ts + 1800, audio_path: null, match_id: lolId });
core.store.updateUtteranceResult(id, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'large-v3', status: 'precise' });
}
core.store.endSession('s-lol', LS + LEN + MIN);
core.store.endSession('s-lol', LS + lol.durationMs + MIN);
// ---------------------------------------------------------------- 사이트 서버 (실제 Claude · 실제 OP.GG)
// ---------------------------------------------------------------- 사이트 서버 (실제 Claude)
const local = await culpritApi(core);
const { buildServer } = await import('../../site/server/src/app.ts');
const port = 18961;
@@ -121,7 +55,7 @@ const site = await buildServer({
port, host: '127.0.0.1', publicUrl: `http://127.0.0.1:${port}`, clientId: 'x', clientSecret: 'x', botToken: 'x', allowedGuilds: [], owners: ['u1'], superAdmins: ['u1'],
sessionSecret: 'real-e2e-secret-'.repeat(3), dataDir: fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-real-')), webDir: path.join(root, 'site', 'web', 'dist'), version: 't', discordApi: 'http://127.0.0.1:1',
assetUpstream: { valmedia: 'https://media.valorant-api.com/', ddragon: 'https://ddragon.leagueoflegends.com/', cdragon: 'https://raw.communitydragon.org/' },
culprit: { apiKey, model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium', opgg: true },
culprit: { apiKey, model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium' },
});
site.app.log.level = 'info';
await site.app.listen({ host: '127.0.0.1', port });
@@ -132,7 +66,7 @@ const { RelayClient } = await import('../src/core/relay/client.ts');
const rc = new RelayClient(local as any, core.bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: 't', guildId: 'g' }));
rc.start();
while (!site.hub.status().online) await new Promise((r) => setTimeout(r, 100));
const sess = site.store.createSession({ id: 'u1', name: '승한', avatar: null });
const sess = site.store.createSession({ id: 'u1', name: '하늘', avatar: null });
const cookieHeader = `gvr_sid=${encodeURIComponent(site.app.signCookie(sess.token))}`;
const stages: Record<string, string[]> = {};
@@ -171,9 +105,9 @@ for (const id of [valId, lolId]) {
const ref = (pid: string) => a.players.find((p) => p.id === pid)!;
const rows = a.result.players.map((p) => {
const pl = ref(p.id);
return { id: p.id, team: pl.team, ai: p.score, rating: pl.rating?.score ?? null, opgg: pl.opgg?.score ?? null, truth: opggTruth.get(pl.puuid) ?? null, tag: p.tag, comment: p.comment };
return { id: p.id, team: pl.team, ai: p.score, rating: pl.rating?.score ?? null, lane: pl.rating?.lane ?? null, tag: p.tag, comment: p.comment };
});
const teamLowest = (team: string, key: 'rating' | 'opgg') => {
const teamLowest = (team: string, key: 'rating') => {
const ps = rows.filter((r) => r.team === team && r[key] !== null);
return ps.length ? ps.reduce((x, y) => ((x[key] as number) <= (y[key] as number) ? x : y)).id : null;
};
@@ -182,11 +116,10 @@ for (const id of [valId, lolId]) {
model: a.model,
costUsd: a.meta.costUsd,
usage: a.meta.usage,
opgg: a.meta.opgg,
stages: stages[id],
summary: a.result.summary,
confidence: a.result.confidence,
culprits: a.result.teams.map((t) => ({ team: t.team, culprit: t.culprit, reason: t.reason, evidence: t.evidence.map((e) => e.ref), lowestRating: teamLowest(t.team, 'rating'), lowestOpgg: teamLowest(t.team, 'opgg') })),
culprits: a.result.teams.map((t) => ({ team: t.team, culprit: t.culprit, reason: t.reason, evidence: t.evidence.map((e) => e.ref), lowestRating: teamLowest(t.team, 'rating') })),
players: rows,
};
console.log(JSON.stringify(report[id], null, 1));

View File

@@ -18,7 +18,7 @@ const { id: valId } = seedValorant(core);
const LS = Date.now() - 80 * MIN;
const lol = makeDemoLol();
core.store.setMeta('riot_self_puuid', 'l-sh');
core.store.setAccounts('u1', [{ puuid: 'p-sh', riotId: '승한#V' }, { puuid: 'l-sh', riotId: '승한#L' }]);
core.store.setAccounts('u1', [{ puuid: 'p-sh', riotId: '하늘#V' }, { puuid: 'l-sh', riotId: '하늘#L' }]);
core.store.setAccounts('u2', [{ puuid: 'p-ms', riotId: '민수#V' }, { puuid: 'l-ms', riotId: '민수#L' }]);
core.store.startSession('s2', 'g', 'c', '음성', LS - MIN);
core.games.matchStarted({ id: 'lol-demo', game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
@@ -60,13 +60,6 @@ const site = await buildServer(
},
{
culpritKnowledge: new KnowledgeAuto(async () => { throw new Error('offline'); }),
// OP.GG: 발로란트 시연 경기는 "찾음"(가짜 점수), 롤 시연 경기는 "없음"
culpritOpgg: async (name: string, args: any) => {
if (name !== 'valorant_list_player_matches') return {};
const input = (await local.inject({ url: `/api/culprit/internal/${valId}/input`, headers: { 'x-gvr-internal': '1' } })).json().input as CulpritInput;
const p = input.players.find((x) => x.name === args.game_name)!;
return [{ matchId: 'demo', puuid: p.puuid, opScore: Math.round((p.rating?.score ?? 5) * 100 + 30) }];
},
culpritCall: async (req) => {
await new Promise((r) => setTimeout(r, 2500));
const isVal = req.user.includes('# 경기 발로란트');
@@ -85,7 +78,7 @@ const rc = new RelayClient(local as any, core.bus, () => ({ serverUrl: base, dev
rc.start();
// 사이트 화면은 /api/overview · /api/users 도 부른다
while (!site.hub.status().online) await new Promise((r) => setTimeout(r, 100));
const sess = site.store.createSession({ id: 'u1', name: '승한', avatar: null });
const sess = site.store.createSession({ id: 'u1', name: '하늘', avatar: null });
const cookie = { name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base };
const puppeteer = (await import(path.join(os.homedir(), '.tmp/gvr-shot/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js'))).default;

View File

@@ -24,7 +24,7 @@ fs.symlinkSync(path.join(hf, fs.readdirSync(hf)[0]), path.join(work, 'models', m
fs.writeFileSync(path.join(work, 'settings.json'), JSON.stringify({ stt: { realtimeModel: model, preciseModel: model, device: 'cpu', computeType: 'int8' }, games: { valorant: false, lol: false } }));
const USERS = [
{ id: '100000000000000001', name: '승한', voice: 'ko-KR-InJoonNeural', val: 'p-sh', lol: 'l-sh' },
{ id: '100000000000000001', name: '하늘', voice: 'ko-KR-InJoonNeural', val: 'p-sh', lol: 'l-sh' },
{ id: '100000000000000002', name: '민수', voice: 'ko-KR-HyunsuMultilingualNeural', val: 'p-ms', lol: 'l-ms' },
{ id: '100000000000000003', name: '지우', voice: 'ko-KR-SunHiNeural', val: 'p-jw', lol: 'l-jw' },
{ id: '100000000000000004', name: '현우', voice: 'ko-KR-InJoonNeural', pitch: '-8Hz', val: 'p-hw', lol: 'l-hw' },
@@ -136,8 +136,8 @@ LINES.forEach((l, i) => {
});
for (const [m, name, ch, text, src] of [
[-1.5, '민수', 'team', '정글 갱 갈게요', 'lcu'],
[5.2, 'Lumi', 'all', '아리 잘하네', 'ocr'],
[11.4, '지우', 'team', '드래곤 가자', 'ocr'],
[5.2, 'Lumi', 'all', '아리 잘하네', 'log'],
[11.4, '지우', 'team', '드래곤 가자', 'log'],
[28.5, 'Kiwi', 'all', 'gg', 'lcu'],
] as const) {
games.event({ id: `${lolId}:chat:demo${m}`, match_id: lolId, game: 'lol', type: 'chat', ts: LS + m * 60_000, game_time_ms: m * 60_000, round: null, actor_puuid: null, target_puuid: null, data: JSON.stringify({ sender: { name }, channel: ch, text, source: src }) });
@@ -200,7 +200,7 @@ const reg = await registerDevice(base, code.code, 'GAME-PC');
core.settings.update({ site: { serverUrl: base, deviceId: reg.deviceId, deviceName: 'GAME-PC' } });
core.settings.setSecret('deviceKey', reg.deviceKey);
core.relay.restart();
const sess = site.store.createSession({ id: USERS[0].id, name: '승한', avatar: null });
const sess = site.store.createSession({ id: USERS[0].id, name: '하늘', avatar: null });
const cookie = { name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base };
while (core.relay.status.state !== 'online') await new Promise((r) => setTimeout(r, 100));
console.log(`사이트: ${base} (쿠키 gvr_sid=${cookie.value})`);

View File

@@ -1,14 +1,29 @@
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 type { Replays } from '../replays.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 +36,12 @@ export interface ApiDeps {
trainingDir: () => string;
overviewExtra: () => { guild: Overview['guild']; recording: Overview['recording'] };
version: string;
/** 기록 묶음 (없으면 /api/bundles 없음) */
bundles?: Bundles;
/** 발로란트 리플레이 (없으면 /api/replays 없음) */
replays?: Replays;
/** 사이트 서버가 새 표시 이름을 보내 왔을 때 (녹음 파일 이름 다시 맞추기) */
onNamesChanged?: () => void;
}
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
@@ -54,6 +75,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,
};
@@ -98,6 +120,47 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
return { user: toUser(u, store.listAccounts()), stats: { talkMs: st.ms, count: st.n, topWords }, matches };
});
// Riot 경기 기록 가져오기 취소 (v1.9.1, 사이트 경기 탭 진행 바). 받은 경기는 그대로 두고 다음 주기(30분 뒤)에 이어서 한다
app.post<{ Body: { game?: string } }>('/api/games/history/cancel', async (req) => {
const g = req.body?.game;
const r = d.games.cancelHistory(g === 'valorant' || g === 'lol' ? g : undefined);
if (r.cancelled.length) log.info(`경기 기록 가져오기 취소 (${r.cancelled.join(', ')}) · ${req.headers['x-gvr-user'] ? '사이트' : '이 PC'}`);
return { ok: true, ...r };
});
// 유저 설정 (v1.6.0, 사이트 "내 정보" · 관리 화면): 색 · 녹음 제외 · 라이엇 ID. 본인 또는 관리자만
app.patch<{ Params: { id: string }; Body: { color?: string; excluded?: boolean; riotIds?: string[] } }>('/api/users/:id', async (req, reply) => {
const u = store.getUser(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found', message: '이 PC 기록에 없는 유저입니다 (음성채널에서 한 번 녹음되면 생깁니다)' });
const admin = req.headers['x-gvr-role'] === 'admin' || !req.headers['x-gvr-user'];
if (!admin && !canDelete(req, u.id)) return reply.code(403).send({ error: 'forbidden', message: '본인 또는 관리자만 바꿀 수 있습니다' });
const b = req.body ?? {};
if (b.color !== undefined && !/^#[0-9a-fA-F]{6}$/.test(String(b.color))) return reply.code(400).send({ error: 'bad_color', message: '색은 #rrggbb 형식입니다' });
if (b.riotIds !== undefined && (!Array.isArray(b.riotIds) || b.riotIds.length > 5 || b.riotIds.some((r) => typeof r !== 'string' || r.length > 45)))
return reply.code(400).send({ error: 'bad_riot_ids', message: '라이엇 ID 는 5개까지, 이름#태그 형식입니다' });
let taken: string[] = [];
store.db.transaction(() => {
if (b.color !== undefined) store.setColor(u.id, String(b.color).toLowerCase());
if (b.excluded !== undefined) store.setExcluded(u.id, !!b.excluded);
if (b.riotIds !== undefined) taken = store.setRiotIds(u.id, b.riotIds, admin).taken;
})();
log.info(`유저 설정 바뀜 ${u.id}: ${Object.keys(b).join(', ')}${taken.length ? ` (이미 다른 사람에게 연결된 라이엇 ID ${taken.length}개 뺌)` : ''}`);
d.bus.live({ type: 'users.updated', data: [] });
return { user: toUser(store.getUser(u.id)!, store.listAccounts()), taken };
});
// 표시 이름 (v1.6.0): 사이트에서 이름을 바꾸면 사이트 서버가 바로 보낸다 (예전 앱은 10분마다 받아 감)
app.put<{ Body: { names?: Record<string, string> } }>('/api/internal/names', async (req, reply) => {
if (req.headers['x-gvr-internal'] !== '1') return reply.code(403).send({ error: 'forbidden' });
const names = req.body?.names;
if (!names || typeof names !== 'object') return reply.code(400).send({ error: 'bad_names' });
store.setDisplayNames(names);
timeline.invalidate();
d.onNamesChanged?.();
d.bus.live({ type: 'users.updated', data: [] });
return { ok: true };
});
app.get<{ Querystring: Record<string, string> }>('/api/timeline', async (req) => {
const q = req.query;
const tq: TimelineQuery = {
@@ -108,7 +171,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 +178,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' });
@@ -140,7 +318,13 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
app.get<{ Querystring: Record<string, string> }>('/api/matches', async (req) => {
const q = req.query;
return store
.listMatches({ game: q.game || undefined, before: q.before ? Number(q.before) : undefined, limit: q.limit ? Math.min(Number(q.limit), 200) : 50 })
.listMatches({
game: q.game || undefined,
before: q.before ? Number(q.before) : undefined,
limit: q.limit ? Math.min(Number(q.limit), 200) : 50,
// 사이트 경기 탭 필터 (v1.9.0): timeline = 타임라인에 나오는 경기, voice = 목소리가 녹음된 경기
has: q.has === 'timeline' || q.has === 'voice' ? q.has : undefined,
})
.map((m) => d.games.summary(m));
});
@@ -171,7 +355,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,
@@ -189,6 +373,31 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
};
});
// 3D 리플레이 (v1.5.0): 이 PC 에 내려받은 발로란트 리플레이(.vrf)를 변환해 보낸다 (gzip JSON).
// 처음 열 때 변환하느라 15초 넘게 걸리면 202 converting → 사이트가 몇 초 뒤 다시 묻는다
app.get<{ Params: { id: string } }>('/api/matches/:id/replay', async (req, reply) => {
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
if (m.game !== 'valorant' || !d.replays) return reply.code(404).send({ error: 'replay_not_found' });
const r = await d.replays.get(m.id.replace(/^val-/, ''));
if (r.state === 'ready')
return reply.header('content-type', 'application/json; charset=utf-8').header('content-encoding', 'gzip').header('cache-control', 'private, max-age=3600').send(fs.readFileSync(r.file));
if (r.state === 'converting') return reply.code(202).send({ status: 'converting' });
if (r.state === 'missing') return reply.code(404).send({ error: 'replay_not_found' });
if (r.state === 'no_tool') return reply.code(500).send({ error: 'replay_tool_missing', message: '리플레이 변환기가 없습니다 (앱을 다시 설치해 주세요)' });
return reply.code(422).send({ error: 'replay_failed', message: r.error });
});
// 이 PC 에서 찾은 리플레이 목록 (경기 기록이 있는지 · 변환했는지)
app.get('/api/replays', async (_req, reply) => {
if (!d.replays) return reply.code(404).send({ error: 'not_found' });
const rp = d.replays;
return rp.list().map((r) => {
const match = store.getMatch(`val-${r.matchId}`) ?? null;
return { matchId: r.matchId, file: path.basename(r.file), size: r.size, mtime: r.mtimeMs, match: match ? match.id : null, converted: !!rp.cached(r) };
});
});
app.patch<{ Params: { id: string }; Body: { text?: string } }>('/api/utterances/:id', async (req, reply) => {
const u = store.getUtterance(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found' });
@@ -213,6 +422,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();
}
}

View File

@@ -203,6 +203,21 @@ export class AppAuth extends EventEmitter {
if (token) await this.call('POST', '/auth/app/logout', {}, token).catch(() => undefined);
}
/** 관리자 · 최고 관리자 아이디 (따라갈 사람 목록 정렬용) */
async adminIds(): Promise<string[]> {
const r = await this.call<{ ids: string[] }>('GET', '/app/admins');
return Array.isArray(r?.ids) ? r.ids : [];
}
/** 표시 이름 (실명 숨기기): 디스코드 아이디 → 이름 */
async displayNames(): Promise<Record<string, string>> {
const r = await this.call<{ names: Record<string, string> }>('GET', '/app/names');
return r?.names && typeof r.names === 'object' ? r.names : {};
}
adminSetDisplayName(id: string, name: string): Promise<{ names: Record<string, string> }> {
return this.call('PUT', '/app/admin/names', { id: id.trim(), name: name.trim() });
}
// ---- 관리자 화면 (서버가 역할을 다시 확인한다)
adminUsers(): Promise<{ users: AppUserRow[] }> {
return this.call('GET', '/app/admin/users');

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

@@ -0,0 +1,457 @@
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) ?? [];
// Riot 경기 기록에서 가져오기만 한 경기(녹음 없음)는 기록 묶음으로 보이지 않는다
if (m.source === 'history' && !list.length) continue;
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,source) 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, m.source === 'history' ? 'history' : 'live');
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

@@ -33,6 +33,7 @@ async function main() {
worker,
version: process.env.npm_package_version || '1.0.0',
apiPort: Number(process.env.GVR_API_PORT || 0),
replayTool: process.env.GVR_REPLAY_TOOL || path.join(root, '..', 'tools', 'replay-extract', 'out', 'linux', 'gvr-replay'),
});
const shutdown = async () => {
await core.stop();

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)!;
@@ -173,7 +174,6 @@ export class Culprit {
character: p.character ?? null,
userId: userId ?? null,
voice: !!userId && speakers.has(userId),
...(p.tag ? { tag: p.tag } : {}),
...(ratings.get(p.puuid) ? { rating: ratings.get(p.puuid) } : {}),
hasExtraStats: !!p.stats,
};
@@ -334,12 +334,6 @@ export class Culprit {
refs,
players: players.map(({ hasExtraStats: _x, ...p }) => p),
stats: { utterances: utts.length, utterancesTotal: totalUtts, events: ei, chats: ci, rounds: rounds.length, basic },
lookup: {
riotMatchId: m.id.replace(/^(val|lol)-/, '') || null,
startedAt: realStart(m),
endedAt: m.ended_at ?? realStart(m),
durationSec: Math.round(((m.ended_at ?? realStart(m)) - realStart(m)) / 1000),
},
};
}
}
@@ -364,8 +358,8 @@ function ratingLines(game: string, players: CulpritPlayer[]): string[] {
if (!players.some((p) => p.rating)) return [];
const head =
game === 'valorant'
? '# 기록 점수 (0~10, OP.GG OP스코어 방식: 라운드 승률 · KAST · ACS · 피해 격차를 실제 OP.GG 점수에 맞춘 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점)'
: '# 기록 점수 (0~10, OP.GG OP스코어 방식: 킬 관여 · 데스 · 딜/받은 피해 · 골드 · CS · 레벨 · CC · 와드를 실제 OP.GG 점수에 맞춘 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점, 라인전 = LOL.PS 라인전 점수의 입력인 10 · 15분 맞라이너와의 CS · 골드 · 경험치 차)';
? '# 기록 점수 (0~10, OP.GG OP스코어 계산법: 라운드 승률 · KAST · ACS · 피해 격차로 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점)'
: '# 기록 점수 (0~10, OP.GG OP스코어 계산법: 역할 · 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드로 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점, 라인전 = LOL.PS 라인전 점수의 입력인 10 · 15분 맞라이너와의 CS · 골드 · 경험치 차)';
const out = [head];
if (players.some((p) => p.rating?.basic)) out.push('# (추가 지표가 없어 K/D/A · 골드 · CS 같은 기본 기록으로만 낸 점수다)');
const idOf = new Map(players.map((p) => [p.puuid, p.id]));

View File

@@ -50,6 +50,8 @@ export interface MatchRow {
detail: string | null;
status: string;
clock_offset: number;
/** live: 앱이 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 */
source: 'live' | 'history';
}
export interface RoundRow {
match_id: string;
@@ -87,6 +89,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;
@@ -99,6 +130,9 @@ export class Store {
/** 예전 DB 를 지금 스키마로 맞춘다 (스키마를 바꿀 때마다 여기에 단계 추가) */
private migrate(): void {
// v1.9.0: 경기 출처 (Riot 경기 기록에서 가져온 경기)
const mcols = this.db.prepare(`PRAGMA table_info(matches)`).all() as { name: string }[];
if (!mcols.some((c) => c.name === 'source')) this.db.exec(`ALTER TABLE matches ADD COLUMN source TEXT NOT NULL DEFAULT 'live'`);
// v1.0 개발 중: dictionary UNIQUE 에 pack 추가 (같은 단어가 여러 묶음에 들어갈 수 있게)
const idx = this.db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='dictionary'`).get() as { sql: string } | undefined;
if (idx && !/UNIQUE\s*\(kind,\s*word,\s*from_text,\s*pack\)/.test(idx.sql)) {
@@ -125,9 +159,84 @@ export class Store {
`INSERT INTO users(id,name,color,avatar,updated_at) VALUES(?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET name=excluded.name, avatar=excluded.avatar, updated_at=excluded.updated_at`,
)
.run(u.id, u.name, colorFor(u.id), u.avatar, now);
.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)!;
}
// 표시 이름 (실명 숨기기): 사이트 서버에 정해 둔 이름을 디스코드 이름 대신 저장한다
private names: Record<string, string> | null = null;
displayNames(): Record<string, string> {
if (!this.names) {
try {
this.names = JSON.parse(this.meta('display_names') || '{}');
} catch {
this.names = {};
}
}
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> = {};
for (const [id, name] of Object.entries(map)) if (typeof name === 'string' && name.trim()) names[id] = name.trim();
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();
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) return;
// 건너뛰지 않고 매번 모든 분석을 다시 훑는다 (이름을 바꾸기 전에 시작한 분석이 뒤늦게 저장된 경우도 고친다)
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 {
by = null;
}
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);
}
})();
}
getUser(id: string): UserRow | undefined {
return this.db.prepare('SELECT * FROM users WHERE id=?').get(id) as UserRow | undefined;
}
@@ -137,6 +246,10 @@ export class Store {
setExcluded(id: string, excluded: boolean): void {
this.db.prepare('UPDATE users SET excluded=?, updated_at=? WHERE id=?').run(excluded ? 1 : 0, Date.now(), id);
}
/** 사이트 · 타임라인에서 쓰는 유저 색 (#rrggbb) */
setColor(id: string, color: string): void {
this.db.prepare('UPDATE users SET color=?, updated_at=? WHERE id=?').run(color, Date.now(), id);
}
/** 유저 평소 음량 누적 평균 (최근값에 가중치) */
updateGainProfile(id: string, lufs: number): void {
const u = this.getUser(id);
@@ -148,6 +261,29 @@ export class Store {
listAccounts(): { user_id: string; puuid: string; riot_id: string }[] {
return this.db.prepare('SELECT * FROM game_accounts').all() as any[];
}
/**
* 라이엇 ID (이름#태그) 목록으로 연결 계정을 바꾼다. 이미 연결된 것은 puuid 를 그대로 두고, 새것은 riotid: 로 두었다가
* 경기에서 만나면 실제 puuid 로 바뀐다. 다른 사람에게 연결된 라이엇 ID 는 넣지 않고 돌려준다 (관리자는 allowTaken 으로 같이 연결)
*/
setRiotIds(userId: string, riotIds: string[], allowTaken = false): { taken: string[] } {
const all = this.listAccounts();
const cur = all.filter((a) => a.user_id === userId);
const taken: string[] = [];
const seen = new Set<string>();
const next: { puuid: string; riot_id: string }[] = [];
for (const raw of riotIds) {
const r = raw.trim();
if (!/^[^#]{1,32}#[^#]{1,8}$/.test(r) || seen.has(r.toLowerCase())) continue;
seen.add(r.toLowerCase());
if (!allowTaken && all.some((a) => a.user_id !== userId && a.riot_id.toLowerCase() === r.toLowerCase())) {
taken.push(r);
continue;
}
next.push(cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r });
}
this.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id })));
return { taken };
}
setAccounts(userId: string, accounts: { puuid: string; riotId: string }[]): void {
const tx = this.db.transaction(() => {
this.db.prepare('DELETE FROM game_accounts WHERE user_id=?').run(userId);
@@ -244,8 +380,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);
@@ -263,13 +411,14 @@ export class Store {
detail: null,
status: 'live',
clock_offset: 0,
source: 'live',
...(cur || {}),
...stripUndef(m),
} as MatchRow;
this.db
.prepare(
`INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset)
VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset)
`INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset,source)
VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset,@source)
ON CONFLICT(id) DO UPDATE SET started_at=@started_at, ended_at=@ended_at, map=@map, mode=@mode, queue=@queue,
result=@result, detail=@detail, status=@status, clock_offset=@clock_offset`,
)
@@ -279,9 +428,15 @@ export class Store {
getMatch(id: string): MatchRow | undefined {
return this.db.prepare('SELECT * FROM matches WHERE id=?').get(id) as MatchRow | undefined;
}
listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[] }): MatchRow[] {
/**
* has: timeline = 타임라인에 나오는 경기 (앱이 잡은 경기 · 기록에서 가져왔어도 대화가 붙은 경기), voice = 목소리가 녹음된 경기
*/
listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[]; has?: 'timeline' | 'voice' }): MatchRow[] {
const where: string[] = [];
const args: any[] = [];
const voice = `EXISTS (SELECT 1 FROM utterances u WHERE u.match_id = matches.id AND (u.noise = 0 OR u.corrected = 1))`;
if (opts.has === 'voice') where.push(voice);
else if (opts.has === 'timeline') where.push(`(source = 'live' OR ${voice})`);
if (opts.game) {
where.push('game=?');
args.push(opts.game);
@@ -395,9 +550,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

@@ -82,7 +82,9 @@ CREATE TABLE IF NOT EXISTS matches (
result TEXT,
detail TEXT,
status TEXT NOT NULL DEFAULT 'live',
clock_offset INTEGER NOT NULL DEFAULT 0
clock_offset INTEGER NOT NULL DEFAULT 0,
-- live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0)
source TEXT NOT NULL DEFAULT 'live'
);
CREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);
@@ -136,3 +138,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
);

File diff suppressed because one or more lines are too long

View File

@@ -128,24 +128,13 @@ export async function runDiagnostics(opts: {
});
}
// 5. 채팅 OCR (한국어 OCR 설치 여부 + 정확도)
try {
const r = await opts.worker.request('ocr_image', { path: path.join(opts.resourcesDir, 'diag', 'lol-chat-sample.png'), lang: 'ko' }, 60000);
const lines: string[] = (r.lines || []).map((l: any) => l.text ?? l);
const expect = ['드래곤 가자', 'gg', '바텀 갱 간다'];
const hit = expect.filter((e) => lines.some((l) => l.replace(/\s/g, '').includes(e.replace(/\s/g, '')))).length;
add({ id: 'ocr', label: '채팅 OCR (한국어)', ok: hit >= 2, detail: `예시 3줄 중 ${hit}줄 인식: ${lines.join(' / ')}`, data: r });
} catch (e: any) {
add({ id: 'ocr', label: '채팅 OCR (한국어)', ok: false, detail: e.message });
}
// 6. r3dlog 채팅
// 5. r3dlog 채팅 (롤은 게임 중 채팅 API 가 없어 로그 파일에 남을 때만 쓴다)
const logs = opts.lolLogsDir || (lcu?.installDir ? path.join(lcu.installDir, 'Logs', 'GameLogs') : null);
if (!logs || !fs.existsSync(logs)) add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: null, detail: '로그 폴더를 찾지 못했습니다 (롤을 한 판 한 뒤 확인)' });
else {
try {
const r = await opts.worker.request('r3dlog_check', { logs_dir: logs }, 30000);
add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: r.found_chat, detail: r.found_chat ? `채팅이 남아 있음 → OCR 대신 사용 (${r.file})` : '로그에 채팅이 없음 → 화면 OCR 사용', data: r });
add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: r.found_chat ? true : null, detail: r.found_chat ? `채팅이 남아 있음 → 게임 중 채팅을 경기 뒤에 붙임 (${r.file})` : '로그에 채팅이 없음 → 게임 중 전체 · 팀 채팅은 기록되지 않음 (챔피언 선택 · 게임 후 채팅은 LCU 로 기록)', data: r });
} catch (e: any) {
add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: false, detail: e.message });
}

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');
@@ -177,6 +177,8 @@ export class Bot {
// 새 사람이 들어오면 안내를 다시 튼다
if (e.newChannelId === myCh && e.oldChannelId !== myCh && (!e.member.bot || process.env.GVR_RECORD_BOTS === '1')) {
this.touchUser(e.member);
// 녹음 중에 들어온 사람도 사이트가 이름을 알게 한다 (안 보내면 그 사람 발화가 "알 수 없음"으로 뜸)
this.bus.live({ type: 'users.updated', data: [] });
this.updateParticipants();
if (s.ttsEnabled && s.ttsOnNewMember) void this.announce();
}
@@ -290,9 +292,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

@@ -0,0 +1,155 @@
import type { HistoryProgress } from '@gvr/shared';
import type { Store } from '../db/db.js';
import { logger } from '../util/log.js';
const log = logger('history');
/** 게임별 Riot 경기 기록 읽기 */
export interface HistorySource {
readonly game: 'valorant' | 'lol';
/** 지금 가져와도 되는가 (게임 중 · 요원 선택 중이면 false) */
idle(): boolean;
/** 이 PC 에 로그인한 계정 (계정이 바뀌면 처음부터 다시 훑는다) */
account(): string | null;
/** start 번째부터 n 개 (새것부터). 경기 행 ID 로 돌려준다. 'retry' = 지금은 못 읽음 */
page(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'>;
/** 경기 하나를 받아 저장. gone = 기록이 없음(다시 묻지 않음), retry = 나중에 */
fetch(id: string): Promise<'ok' | 'gone' | 'retry'>;
}
export interface HistoryOptions {
pageSize: number;
/** 최대 몇 경기 전까지 훑을지 */
max: number;
/** 경기 상세 요청 사이 간격 (Riot 요청 한도) */
gapMs: number;
}
/**
* 내 Riot 경기 기록 → 경기 목록 (v1.9.0). 앱이 꺼져 있을 때 한 경기도 사이트 경기 탭에 보이게 한다.
* 처음에는 끝까지 훑고, 그다음부터는 이미 아는 경기만 나오는 쪽까지만 본다. 게임이 시작되면 바로 멈춘다.
*/
export class HistorySync {
private running = false;
private lastAt = 0;
private everyMs = 0;
/** 지금 가져오는 중이면 진행 상황 (사이트 · 앱 화면 진행 바, v1.9.1) */
private prog: HistoryProgress | null = null;
/** 사용자가 취소함: 이번 실행만 멈추고 다음 주기에 이어서 한다 */
private cancelled = false;
constructor(
private store: Store,
private src: HistorySource,
private opts: HistoryOptions,
) {}
/** 주기 확인: 앞 실행에서 everyMs 가 지났고 게임 중이 아니면 백그라운드로 돌린다 */
maybeRun(everyMs: number, firstDelayMs = 60000): void {
const now = Date.now();
this.everyMs = everyMs;
if (!this.lastAt) this.lastAt = now - everyMs + Math.min(firstDelayMs, everyMs);
if (this.running || now - this.lastAt < everyMs || !this.src.idle()) return;
this.lastAt = now;
void this.run().catch((e) => log.warn(`${this.src.game} 경기 기록 가져오기 실패`, e));
}
/** 진행 상황 (가져오는 중이 아니면 null). 남은 시간은 지금까지 한 경기에 걸린 평균으로 잰다 */
progress(): HistoryProgress | null {
const p = this.prog;
if (!p) return null;
let etaMs: number | null = null;
if (p.phase === 'fetch' && p.done > 0 && this.fetchStartedAt) {
const per = (Date.now() - this.fetchStartedAt) / p.done;
etaMs = Math.round(per * (p.total - p.done));
}
return { ...p, etaMs };
}
private fetchStartedAt = 0;
/** 지금 가져오기 취소. 받은 경기는 그대로 두고, 다음 주기(everyMs 뒤)에 남은 것부터 이어서 한다 */
cancel(): { cancelled: boolean; resumeAt: number | null } {
if (!this.running || this.cancelled) return { cancelled: false, resumeAt: null };
this.cancelled = true;
this.prog = null;
// 다음 실행은 취소한 때부터 한 주기 뒤 (오래 돈 실행을 취소해도 바로 다시 시작하지 않게)
this.lastAt = Date.now();
log.info(`${this.src.game} 경기 기록 가져오기: 사용자가 취소함`);
return { cancelled: true, resumeAt: this.everyMs ? this.lastAt + this.everyMs : null };
}
/** 멈춰야 하나 (게임 시작 · 취소) */
private halted(): boolean {
return this.cancelled || !this.src.idle();
}
private skipKey(): string {
return `history_skip:${this.src.game}`;
}
private skipped(): Set<string> {
try {
return new Set(JSON.parse(this.store.meta(this.skipKey()) || '[]'));
} catch {
return new Set();
}
}
/** 한 번 훑기. 새로 저장한 경기 수 */
async run(): Promise<number> {
if (this.running) return 0;
const acct = this.src.account();
if (!acct) return 0;
this.running = true;
this.cancelled = false;
try {
const fullKey = `history_full:${this.src.game}:${acct}`;
// 받다가 멈춘 실행 (취소 · 게임 시작 · 오류): 받은 경기 뒤쪽에 못 받은 경기가 남아 있으니 이번에는 끝까지 훑는다
const pendingKey = `history_pending:${this.src.game}:${acct}`;
const full = !!this.store.meta(fullKey);
const pending = !!this.store.meta(pendingKey);
const skip = this.skipped();
const todo: string[] = [];
this.prog = { phase: 'scan', first: !full, scanned: 0, done: 0, total: 0, startedAt: Date.now(), etaMs: null };
for (let start = 0; start < this.opts.max; start += this.opts.pageSize) {
if (this.halted()) return 0;
const p = await this.src.page(start, this.opts.pageSize);
if (p === 'retry' || this.cancelled) return 0;
const fresh = p.ids.filter((id) => !skip.has(id) && !this.store.getMatch(id) && !todo.includes(id));
todo.push(...fresh);
this.prog = { ...this.prog, scanned: this.prog.scanned + p.ids.length, total: todo.length };
if (!p.ids.length || p.ids.length < this.opts.pageSize || (p.total !== null && start + this.opts.pageSize >= p.total)) break;
// 한 번 끝까지 훑은 뒤에는 아는 경기만 나오는 쪽에서 멈춘다 (지난 실행이 받다가 멈췄으면 끝까지)
if (full && !pending && !fresh.length) break;
}
if (todo.length) log.info(`${this.src.game} 경기 기록: 새 경기 ${todo.length}개 가져오는 중`);
let added = 0;
this.fetchStartedAt = Date.now();
if (this.prog) this.prog = { ...this.prog, phase: 'fetch', done: 0, total: todo.length };
if (todo.length && !pending) this.store.setMeta(pendingKey, '1');
for (const [i, id] of todo.entries()) {
if (this.halted()) {
log.info(`${this.src.game} 경기 기록: ${this.cancelled ? '취소해서' : '게임이 시작돼'} 멈춤 (${added}/${todo.length})`);
return added;
}
const r = await this.src.fetch(id).catch(() => 'retry' as const);
if (r === 'retry') return added;
if (r === 'ok') added++;
else {
skip.add(id);
this.store.setMeta(this.skipKey(), JSON.stringify([...skip].slice(-2000)));
}
if (this.prog) this.prog = { ...this.prog, done: i + 1 };
await new Promise((res) => setTimeout(res, this.opts.gapMs));
}
if (this.cancelled) return added;
// 끝(또는 max)까지 다 받았다: 다음부터는 새 경기만 본다
this.store.setMeta(fullKey, '1');
if (this.store.meta(pendingKey)) this.store.setMeta(pendingKey, '');
if (added) log.info(`${this.src.game} 경기 기록: ${added}개 저장`);
return added;
} finally {
this.running = false;
this.prog = null;
}
}
}

View File

@@ -1,9 +1,11 @@
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';
import { basicAuth, findLcu, request } from './riot.js';
import type { AdapterHost, GameAdapter } from './types.js';
import { HistorySync } from './history.js';
const log = logger('lol');
@@ -47,7 +49,8 @@ const DRAGON_KO: Record<string, string> = {
* 리그 오브 레전드 어댑터 (보고서 6-5).
* - 게임 클라이언트 API(127.0.0.1:2999): 게임 시간, 10명 KDA·CS·아이템, 킬·오브젝트 이벤트
* - 롤 클라이언트(LCU): 경기 ID·결과·경기 기록(타임라인), 챔피언 선택·게임 후 채팅
* - 게임 중 채팅: 화면 OCR (STT 워커) 또는 로그 파일(남아 있을 때)
* - 게임 중 전체 · 팀 채팅: 롤은 이걸 주는 API 가 없다 (LCU · 게임 클라이언트 API 모두). 화면 글자 인식(OCR)은 쓰지 않고,
* 게임 로그 파일(r3dlog)에 채팅이 남아 있을 때만 경기 뒤에 읽는다
*/
export class LolAdapter implements GameAdapter {
readonly game = 'lol' as const;
@@ -61,14 +64,49 @@ export class LolAdapter implements GameAdapter {
private pendingChat: EventRow[] = [];
private detailQueue = new Map<string, { gameId: number; tries: number; endedAt: number; startedAt: number }>();
private summonerNames = new Map<string, string>();
private ocrSeen = new Set<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;
private selfPuuid: string | null = null;
/** 내 경기 기록 (LCU, 앱이 꺼져 있을 때 한 경기도 경기 목록에) */
readonly history: HistorySync;
constructor(private host: AdapterHost) {
host.worker.on('event', (ev: any) => {
if (ev.event === 'ocr_line') this.onOcrLine(ev);
});
this.history = new HistorySync(
host.store,
{
game: 'lol',
idle: () => !!this.lcu && !(this.live && !this.live.ended) && !['ChampSelect', 'GameStart', 'InProgress', 'Reconnect'].includes(this.phase ?? ''),
account: () => this.selfPuuid,
page: (start, n) => this.historyPage(start, n),
fetch: (id) => this.historyFetch(id),
},
{ pageSize: 20, max: Number(process.env.GVR_HISTORY_MAX) || 200, gapMs: Number(process.env.GVR_HISTORY_GAP_MS) || 500 },
);
}
private async historyPage(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'> {
const r = await this.lcuGet<any>(`/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=${start}&endIndex=${start + n}`);
const games = r?.games?.games;
if (!Array.isArray(games)) return 'retry';
return { ids: games.filter((g: any) => g?.gameId).map((g: any) => `lol-${g.gameId}`), total: null };
}
private async historyFetch(id: string): Promise<'ok' | 'gone' | 'retry'> {
if (!this.lcu) return 'retry';
const gameId = id.replace(/^lol-/, '');
const game = await this.lcuGet<any>(`/lol-match-history/v1/games/${gameId}`);
if (!this.lcu) return 'retry';
if (!game?.participants || !game.gameCreation) return 'gone';
const timeline = await this.lcuGet<any>(`/lol-match-history/v1/game-timelines/${gameId}`);
this.host.historyMatch({ id, game: 'lol', startedAt: game.gameCreation, map: game.mapId ? `Map${game.mapId}` : 'Map11', mode: game.gameMode ?? null, queue: game.queueId ? String(game.queueId) : null });
this.applyHistory(id, game, timeline, game.gameCreation);
return 'ok';
}
start(): void {
@@ -80,11 +118,58 @@ export class LolAdapter implements GameAdapter {
if (this.timer) clearInterval(this.timer);
if (this.lcuTimer) clearInterval(this.lcuTimer);
this.timer = this.lcuTimer = null;
if (this.live) void this.host.worker.request('ocr_stop', {}, 5000).catch(() => undefined);
}
status() {
return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined };
}
/** 롤은 경기 중에만 (클라이언트 화면은 가볍다) */
gameRunning(): boolean {
return !!this.live && !this.live.ended;
}
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,
history: this.history.progress(),
updatedAt: Date.now(),
};
}
private async lcuGet<T = any>(path: string): Promise<T | null> {
if (!this.lcu) return null;
@@ -148,7 +233,6 @@ export class LolAdapter implements GameAdapter {
ended: false,
};
this.lastMatchId = id;
this.ocrSeen.clear();
this.host.matchStarted({
id,
game: 'lol',
@@ -161,12 +245,12 @@ export class LolAdapter implements GameAdapter {
// 버퍼해 둔 챔피언 선택 채팅을 이 경기에 붙인다
for (const e of this.pendingChat) this.host.event({ ...e, match_id: id, id: `${id}:${e.id}` });
this.pendingChat = [];
void this.startOcr();
log.info(`롤 경기 시작 감지 ${id}`);
}
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 || []) {
@@ -188,6 +272,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;
@@ -307,7 +411,6 @@ export class LolAdapter implements GameAdapter {
if (!m || m.ended) return;
m.ended = true;
const now = Date.now();
void this.host.worker.request('ocr_stop', {}, 5000).catch(() => undefined);
this.host.matchEnded(m.id, now);
this.host.matchUpdated(m.id, {
result: JSON.stringify({ win, score: null }),
@@ -323,19 +426,7 @@ export class LolAdapter implements GameAdapter {
}, 60000).unref();
}
// ------------------------------------------------------------------ 채팅 OCR · 로그
private async startOcr(): Promise<void> {
const s = this.host.settings().games;
if (!s.lolChatOcr || process.platform !== 'win32') return;
try {
await this.host.worker.request('ocr_start', { window_title: 'League of Legends (TM) Client', region: s.lolOcrRegion, fps: 3, lang: 'ko' }, 15000);
log.info('롤 채팅 OCR 시작');
} catch (e: any) {
this.lastErr = `채팅 OCR: ${e.message}`;
log.warn('채팅 OCR 시작 실패', e);
}
}
// ------------------------------------------------------------------ 게임 중 채팅 (로그 파일)
private chatRow(m: LiveMatch, key: string, gameTimeS: number | null, ts: number, p: any, source: ChatData['source']): EventRow {
const sender = this.findPlayer(m, p.sender);
const ts2 = gameTimeS !== null ? m.startedAt + gameTimeS * 1000 : ts;
@@ -363,18 +454,7 @@ export class LolAdapter implements GameAdapter {
};
}
private onOcrLine(ev: any): void {
const m = this.live;
if (!m || m.ended || !ev.parsed?.message) return;
const p = ev.parsed;
const key = `${p.game_time ?? ''}|${p.sender ?? ''}|${p.message}`;
if (this.ocrSeen.has(key)) return;
this.ocrSeen.add(key);
const gts = typeof p.game_time_s === 'number' ? p.game_time_s : null;
this.host.event(this.chatRow(m, hash(key), gts, ev.ts || Date.now(), p, 'ocr'));
}
/** 로그 파일에 채팅이 남아 있으면 OCR 보다 정확하므로 그걸로 바꾼다 */
/** 경기가 끝나면 로그 파일에 남은 게임 중 채팅을 붙인다 (LCU 로 받은 챔피언 선택 · 게임 후 채팅은 그대로 둔다) */
private async readLogChat(m: LiveMatch): Promise<void> {
const dir = this.host.settings().games.lolLogsDir || (this.lcu?.installDir ? `${this.lcu.installDir}\\Logs\\GameLogs` : null);
if (!dir) return;
@@ -385,8 +465,8 @@ export class LolAdapter implements GameAdapter {
const rows = lines.map((p: any, i: number) =>
this.chatRow(m, `${i}-${hash(`${p.game_time_s}|${p.sender}|${p.message}`)}`, typeof p.game_time_s === 'number' ? p.game_time_s : null, m.startedAt, p, 'log'),
);
this.host.replaceEvents(m.id, ['chat'], rows);
log.info(`로그 파일 채팅 ${rows.length}줄로 교체`);
for (const row of rows) this.host.event(row);
log.info(`로그 파일 채팅 ${rows.length}줄`);
} catch (e) {
log.debug('로그 파일 채팅 없음', e);
}
@@ -402,11 +482,25 @@ 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}`);
this.selfPuuid = me?.puuid ?? null;
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);
this.history.maybeRun(Number(process.env.GVR_HISTORY_EVERY_MS) || 30 * 60000);
}
private async pollLcuChat(phase: string): Promise<void> {

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,46 @@ 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());
}
/** Riot 경기 기록 가져오기 취소 (사이트 경기 탭 · 앱 게임 연동 탭의 취소 버튼, v1.9.1). game 이 없으면 둘 다 */
cancelHistory(game?: 'valorant' | 'lol'): { cancelled: ('valorant' | 'lol')[]; resumeAt: number | null } {
const cancelled: ('valorant' | 'lol')[] = [];
let resumeAt: number | null = null;
for (const a of this.adapters) {
if (game && a.game !== game) continue;
const r = a.history.cancel();
if (!r.cancelled) continue;
cancelled.push(a.game);
if (r.resumeAt && (!resumeAt || r.resumeAt < resumeAt)) resumeAt = r.resumeAt;
}
// 화면에서 진행 바가 바로 사라지게
if (cancelled.length) {
const live = this.live();
this.lastLive = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest));
this.bus.live({ type: 'games.state', data: live });
}
return { cancelled, resumeAt };
}
private liveTimer: NodeJS.Timeout | null = null;
private lastLive = '';
/** 게임 상태가 바뀌면 사이트로 알린다 (2초마다 확인) */
private watchLive(): void {
if (this.liveTimer) return;
this.liveTimer = setInterval(() => {
void this.stt.setGameActive(this.adapters.some((a) => this.settings().games[a.game] && a.gameRunning()));
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);
@@ -73,6 +124,22 @@ export class GameManager implements AdapterHost {
this.emitMatch(m.id);
}
/** Riot 경기 기록에서 가져온 경기 (상세는 바로 이어서 matchUpdated 로 채운다). 녹음 · STT 와는 상관없다 */
historyMatch(m: MatchStart): void {
if (this.store.getMatch(m.id)) return;
this.store.upsertMatch({
id: m.id,
game: m.game,
started_at: m.startedAt,
map: m.map ?? null,
mode: m.mode ?? null,
queue: m.queue ?? null,
detail: m.detail ? JSON.stringify(m.detail) : null,
status: 'pending_detail',
source: 'history',
});
}
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void {
const cur = this.store.getMatch(id);
if (!cur) return;
@@ -84,6 +151,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 +162,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 +178,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;
@@ -149,6 +219,8 @@ export class GameManager implements AdapterHost {
score: result.score,
status: m.status as MatchSummary['status'],
participants,
source: m.source === 'history' ? 'history' : 'live',
voice: !!this.store.db.prepare('SELECT 1 FROM utterances WHERE match_id=? AND (noise=0 OR corrected=1) LIMIT 1').get(m.id),
};
}
@@ -159,21 +231,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,7 +1,9 @@
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';
import type { GameAssets } from './assets.js';
import type { HistorySync } from './history.js';
export interface MatchStart {
id: string;
@@ -20,6 +22,8 @@ export interface AdapterHost {
worker: WorkerClient;
settings(): Settings;
matchStarted(m: MatchStart): void;
/** Riot 경기 기록에서 가져온 경기 행 만들기 (이미 있으면 그대로) */
historyMatch(m: MatchStart): void;
/** 경기 정보 갱신 (상세가 채워졌을 때 등) */
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void;
matchEnded(id: string, endedAt: number): void;
@@ -38,4 +42,10 @@ export interface GameAdapter {
start(): void;
stop(): void;
status(): { connected: boolean; inMatch: boolean; detail?: string };
/** 게임이 켜져 있어 GPU 를 쓰고 있는가 (발로란트: 게임 실행 중 · 롤: 경기 중) */
gameRunning(): boolean;
/** 지금 게임 상태 (자세히) */
liveGame(): LiveGame;
/** Riot 경기 기록 가져오기 */
readonly history: HistorySync;
}

View File

@@ -1,9 +1,11 @@
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';
import { basicAuth, readLockfile, request, riotClientLockfilePath, type Lockfile } from './riot.js';
import type { AdapterHost, GameAdapter } from './types.js';
import { HistorySync } from './history.js';
const log = logger('valorant');
@@ -21,6 +23,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 +39,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,13 +70,58 @@ 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;
private lastErr = '';
/** 내 경기 기록 (앱이 꺼져 있을 때 한 경기도 경기 목록에) */
readonly history: HistorySync;
constructor(private host: AdapterHost) {}
constructor(private host: AdapterHost) {
this.history = new HistorySync(
host.store,
{
game: 'valorant',
idle: () => {
const st = this.presence?.state;
return !!this.auth && !this.match && st !== 'INGAME' && st !== 'PREGAME';
},
account: () => this.auth?.puuid ?? null,
page: (start, n) => this.historyPage(start, n),
fetch: (id) => this.historyFetch(id),
},
{ pageSize: 20, max: Number(process.env.GVR_HISTORY_MAX) || 500, gapMs: Number(process.env.GVR_HISTORY_GAP_MS) || 1500 },
);
}
private async historyPage(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'> {
const a = this.auth;
if (!a) return 'retry';
const r = await request(`${this.pd(a)}/match-history/v1/history/${a.puuid}?startIndex=${start}&endIndex=${start + n}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
if (r.status !== 200 || !Array.isArray(r.data?.History)) {
log.debug(`경기 기록 목록 실패 (${r.status})`);
return 'retry';
}
return { ids: r.data.History.map((h: any) => `val-${h.MatchID}`), total: typeof r.data.Total === 'number' ? r.data.Total : null };
}
private async historyFetch(id: string): Promise<'ok' | 'gone' | 'retry'> {
const a = this.auth;
if (!a) return 'retry';
const r = await request(`${this.pd(a)}/match-details/v1/matches/${id.replace(/^val-/, '')}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
if (r.status === 404 || r.status === 400) return 'gone';
if (r.status !== 200 || !r.data?.matchInfo) return 'retry';
const md = r.data;
const S: number = md.matchInfo.gameStartMillis;
if (!S) return 'gone';
this.host.historyMatch({ id, game: 'valorant', startedAt: S, map: md.matchInfo.mapId ?? null, mode: md.matchInfo.queueID ?? null, queue: md.matchInfo.queueID ?? null });
await this.fillNames(a, md);
this.applyDetails(id, md, a.puuid, S);
return 'ok';
}
start(): void {
if (this.timer) return;
@@ -85,6 +135,59 @@ export class ValorantAdapter implements GameAdapter {
status() {
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
}
/** 발로란트는 메뉴에서도 게임 화면을 그린다: 게임이 켜져 있으면(내 발로란트 상태가 있으면) 켜짐 */
gameRunning(): boolean {
return !!this.match || (!!this.auth && !!this.presence);
}
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,
history: this.history.progress(),
updatedAt: Date.now(),
};
}
private async local<T = any>(path: string): Promise<T | null> {
const lock = this.auth?.lock ?? readLockfile(riotClientLockfilePath());
@@ -123,6 +226,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;
}
@@ -150,9 +255,11 @@ export class ValorantAdapter implements GameAdapter {
if (a) {
await this.pollPresence(a);
if (this.match) await this.pollChat(a);
} else if (this.match) {
else this.history.maybeRun(Number(process.env.GVR_HISTORY_EVERY_MS) || 30 * 60000);
} else {
this.presence = null;
// 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다
this.endMatch();
if (this.match) this.endMatch();
}
await this.pollDetails();
this.lastErr = '';
@@ -173,7 +280,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 +328,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 +408,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 +423,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 +493,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 +563,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 +575,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 +621,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 +666,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 +706,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';
@@ -12,6 +14,7 @@ import { Announcer } from './discord/tts.js';
import { GameAssets } from './games/assets.js';
import { GameManager } from './games/manager.js';
import { RelayClient } from './relay/client.js';
import { defaultReplayDirs, Replays } from './replays.js';
import { Retention } from './retention.js';
import { SettingsStore, resolvePaths, type SecretCodec } from './settings.js';
import { SttPipeline } from './stt/pipeline.js';
@@ -35,6 +38,8 @@ export interface CoreOptions {
apiPort?: number;
/** 겜녹이 봇 중계에서 로그인 만료 · 등록 해제를 알려 왔을 때 (Electron: 바로 다시 확인해서 잠근다) */
onBotUnauthorized?: () => void;
/** 발로란트 리플레이 변환기 (gvr-replay.exe). 없으면 3D 리플레이를 보내지 않는다 */
replayTool?: string | null;
}
export type Core = Awaited<ReturnType<typeof startCore>>;
@@ -52,6 +57,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 +72,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,13 +84,17 @@ 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 } });
});
const culprit = new Culprit(store, timeline, games);
const replays = new Replays({ dirs: defaultReplayDirs, tool: opts.replayTool ?? null, cacheDir: () => path.join(opts.dataDir, 'replays'), version: opts.version });
const api: FastifyInstance = await buildApi({
store,
timeline,
@@ -91,6 +105,9 @@ export async function startCore(opts: CoreOptions) {
settings: S,
trainingDir: () => paths().training,
version: opts.version,
replays,
onNamesChanged: () => audioNames.refreshAll(),
bundles: new Bundles(store, games, () => paths().audio, opts.version, (ids) => ids.forEach((id) => audioNames.refresh(id))),
overviewExtra: () => ({
guild: bot.state.guild,
recording: {
@@ -115,6 +132,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();
@@ -145,16 +171,30 @@ export async function startCore(opts: CoreOptions) {
};
await startBot();
// 녹음할 서버를 바꾸면 봇을 다시 붙여 새 서버를 지켜본다 (이전 서버의 녹음은 끝난다)
let watchedGuild = S().discord.guildId;
const offGuild = settings.onChange((s) => {
const g = s.discord.guildId;
if (g === watchedGuild) return;
watchedGuild = g;
relay.sendHello();
if (bot.state.status !== 'ready' || !g || bot.state.guild?.id === g) return;
log.info('녹음할 서버가 바뀌어 봇을 다시 연결합니다');
void bot.stop().then(startBot);
});
const stop = async () => {
log.info('종료 중');
offGuild();
relay.stop();
retention.stop();
games.stop();
stt.stop();
await bot.stop();
await worker.stop();
await api.close();
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, replays, 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 {
@@ -56,6 +59,12 @@ export class RelayClient {
this.start();
}
/** 녹음할 서버를 바꾸면 사이트 서버에 다시 알린다 (사이트 로그인은 이 서버 멤버만 된다) */
sendHello(): void {
const c = this.cfg();
this.send({ t: 'hello', name: c.name, version: c.version, guildId: c.guildId });
}
private connect(): void {
const c = this.cfg();
if (!c.deviceId || !c.deviceKey) {
@@ -89,7 +98,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 +135,52 @@ 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-encoding', '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')) {
// 압축한 본문(리플레이 gzip JSON)도 글자로 바꾸면 깨지므로 바이너리로 보낸다
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream') || ct.startsWith('application/zip') || outHeaders['content-encoding']) {
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 });

203
app/src/core/replays.ts Normal file
View File

@@ -0,0 +1,203 @@
import { execFile } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import zlib from 'node:zlib';
import { logger } from './util/log.js';
const log = logger('replay');
/** 발로란트 경기 ID (리플레이 파일 이름이 `<경기 ID>.vrf`) */
const MATCH_ID = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
/** 리플레이를 찾지 않는 하위 폴더 (Saved 아래 로그 · 오류 덤프 · 설정 · 브라우저 캐시) */
const SKIP_DIRS = new Set(['logs', 'crashes', 'config', 'webcache', 'webcache_4430', 'cefcache']);
export interface ReplayFileInfo {
matchId: string;
file: string;
size: number;
mtimeMs: number;
}
export type ReplayState =
| { state: 'ready'; file: string }
| { state: 'converting' }
| { state: 'missing' }
| { state: 'no_tool' }
| { state: 'failed'; error: string };
export interface ReplaysOptions {
/** 리플레이(.vrf)를 찾을 폴더들 */
dirs: () => string[];
/** 변환기 (gvr-replay.exe). 없으면 변환하지 않는다 */
tool: string | null;
/** 변환 결과 보관 폴더 (<경기 ID>.json.gz) */
cacheDir: () => string;
/** 변환기가 바뀌면(앱 업데이트) 다시 변환한다 */
version: string;
/** 변환 시간 제한 (기본 3분) */
timeoutMs?: number;
/** 사이트 요청이 변환을 기다리는 시간 (기본 15초, 사이트 서버는 20초 뒤 시간 초과) */
waitMs?: number;
}
/** 발로란트가 리플레이를 내려받는 곳: %LOCALAPPDATA%\VALORANT\Saved (보통 Demos\<경기 ID>.vrf). GVR_REPLAY_DIRS 로 바꿀 수 있다 */
export function defaultReplayDirs(): string[] {
const env = process.env.GVR_REPLAY_DIRS;
if (env) return env.split(path.delimiter).filter(Boolean);
const local = process.env.LOCALAPPDATA;
return local ? [path.join(local, 'VALORANT', 'Saved')] : [];
}
/**
* 발로란트 리플레이(.vrf) 찾기 · 변환 (docs/dev/replay-3d.md).
* 사이트에서 경기의 3D 리플레이를 열면 그때 이 PC 에서 `.vrf` 를 찾아 gvr-replay 로 변환하고 gzip 으로 보관해 둔다.
* 변환은 한 번에 하나, 낮은 우선순위로 (게임 중일 수 있다). 실패하면 같은 파일 · 같은 앱 버전으로는 다시 하지 않는다.
*/
export class Replays {
private scanCache: { at: number; list: ReplayFileInfo[] } | null = null;
private running = new Map<string, Promise<void>>();
private failed = new Map<string, string>();
private queue: Promise<unknown> = Promise.resolve();
constructor(private o: ReplaysOptions) {}
/** 찾은 리플레이 (새것부터). 10초 동안은 다시 훑지 않는다 */
list(): ReplayFileInfo[] {
if (this.scanCache && Date.now() - this.scanCache.at < 10000) return this.scanCache.list;
const byId = new Map<string, ReplayFileInfo>();
const walk = (dir: string, depth: number) => {
let ents: fs.Dirent[];
try {
ents = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const e of ents) {
const p = path.join(dir, e.name);
if (e.isDirectory()) {
if (depth > 0 && !SKIP_DIRS.has(e.name.toLowerCase())) walk(p, depth - 1);
continue;
}
if (!(e.isFile() || e.isSymbolicLink()) || !e.name.toLowerCase().endsWith('.vrf')) continue;
const m = MATCH_ID.exec(e.name);
if (!m) continue;
try {
const st = fs.statSync(p);
const info = { matchId: m[1].toLowerCase(), file: p, size: st.size, mtimeMs: Math.floor(st.mtimeMs) };
const prev = byId.get(info.matchId);
if (!prev || prev.mtimeMs < info.mtimeMs) byId.set(info.matchId, info);
} catch {
/* 그 사이 지워짐 */
}
}
};
for (const d of this.o.dirs()) walk(d, 3);
const list = [...byId.values()].sort((a, b) => b.mtimeMs - a.mtimeMs);
this.scanCache = { at: Date.now(), list };
return list;
}
find(matchId: string): ReplayFileInfo | null {
const id = matchId.toLowerCase();
return this.list().find((r) => r.matchId === id) ?? null;
}
/** 변환 결과 파일 (원본 · 변환기가 그대로일 때만) */
cached(r: ReplayFileInfo): string | null {
const out = this.outFile(r.matchId);
try {
if (fs.readFileSync(out + '.src', 'utf8') === this.stamp(r) && fs.existsSync(out)) return out;
} catch {
/* 아직 없음 */
}
return null;
}
/** 경기 리플레이 상태. 변환이 필요하면 시작하고 waitMs 까지 기다린다 (그때까지 안 끝나면 converting) */
async get(matchId: string, waitMs = this.o.waitMs ?? 15000): Promise<ReplayState> {
this.scanCache = null; // 사이트에서 열 때는 방금 내려받은 파일도 보이게
const r = this.find(matchId);
if (!r) return { state: 'missing' };
const done = this.cached(r);
if (done) return { state: 'ready', file: done };
const key = this.stamp(r);
const err = this.failed.get(key);
if (err) return { state: 'failed', error: err };
if (!this.o.tool || !fs.existsSync(this.o.tool)) return { state: 'no_tool' };
let job = this.running.get(r.matchId);
if (!job) {
job = this.enqueue(r).finally(() => this.running.delete(r.matchId));
this.running.set(r.matchId, job);
}
if (waitMs > 0) await Promise.race([job, new Promise((res) => setTimeout(res, waitMs).unref?.())]);
if (this.running.has(r.matchId)) return { state: 'converting' };
const out = this.cached(r);
if (out) return { state: 'ready', file: out };
return { state: 'failed', error: this.failed.get(key) ?? '변환 결과 없음' };
}
private outFile(matchId: string): string {
return path.join(this.o.cacheDir(), `${matchId}.json.gz`);
}
private stamp(r: ReplayFileInfo): string {
return `${r.size}:${r.mtimeMs}:${this.o.version}`;
}
private enqueue(r: ReplayFileInfo): Promise<void> {
const run = this.queue.then(() => this.convert(r));
this.queue = run.catch(() => undefined);
return run;
}
private async convert(r: ReplayFileInfo): Promise<void> {
const dir = this.o.cacheDir();
fs.mkdirSync(dir, { recursive: true });
const out = this.outFile(r.matchId);
const tmpJson = path.join(dir, `${r.matchId}.json.tmp-${process.pid}`);
const t0 = Date.now();
log.info(`리플레이 변환 시작 ${r.matchId} (${(r.size / 1048576).toFixed(1)}MB)`);
try {
const summary = await this.run([r.file, tmpJson]);
if (!summary?.ok) throw new Error(summary?.error || '변환기가 결과를 알리지 않음');
const gz = zlib.gzipSync(fs.readFileSync(tmpJson), { level: 6 });
fs.writeFileSync(out + '.tmp', gz);
fs.renameSync(out + '.tmp', out);
fs.writeFileSync(out + '.src', this.stamp(r));
log.info(
`리플레이 변환 완료 ${r.matchId}: ${summary.map ?? '?'} · 선수 ${summary.players} · 라운드 ${summary.rounds} · 킬 ${summary.kills} · ${((Date.now() - t0) / 1000).toFixed(1)}초 · ${(gz.length / 1048576).toFixed(1)}MB`,
);
} catch (e: any) {
const msg = String(e?.message ?? e).slice(0, 300);
this.failed.set(this.stamp(r), msg);
log.warn(`리플레이 변환 실패 ${r.matchId}: ${msg}`);
} finally {
fs.rmSync(tmpJson, { force: true });
}
}
/** 변환기 실행. 마지막 줄 JSON 요약을 돌려준다 */
private run(args: string[]): Promise<any> {
return new Promise((resolve, reject) => {
const child = execFile(this.o.tool!, args, { timeout: this.o.timeoutMs ?? 180000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => {
const last = String(stdout).trim().split(/\r?\n/).pop() ?? '';
let summary: any = null;
try {
summary = JSON.parse(last);
} catch {
/* JSON 아님 */
}
if (summary) return resolve(summary);
if (err) return reject(new Error((err as any).killed ? '변환 시간 초과' : String(stderr).trim().split(/\r?\n/).pop() || err.message));
reject(new Error('변환기 출력 없음'));
});
// 게임 중일 수 있으니 낮은 우선순위로
try {
if (child.pid) os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL);
} catch {
/* 권한 없음 */
}
});
}
}

View File

@@ -17,12 +17,12 @@ export interface Settings {
ttsText: string;
ttsOnNewMember: boolean;
ttsVoice: string;
/** 녹음 안내 말 속도 0.1~2.0 (1.0 = 보통) */
ttsRate: number;
};
games: {
valorant: boolean;
lol: boolean;
lolChatOcr: boolean;
lolOcrRegion: { x: number; y: number; w: number; h: number };
lolLogsDir: string | null;
};
stt: {
@@ -33,6 +33,8 @@ export interface Settings {
modelsDir: string | null;
reprocessAfterMatch: boolean;
gameVramReserveMb: number;
/** 게임이 켜져 있는 동안 GPU 를 아낀다: 실시간 모델만 가볍게(빔 1) · 쉬어 가며, 정밀 모델 변환은 게임을 끈 뒤로 (v1.9.0) */
gameSaver: boolean;
};
audio: {
targetLufs: number;
@@ -96,12 +98,11 @@ export function defaultSettings(): Settings {
ttsText: DEFAULT_TTS_TEXT,
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
ttsRate: 1,
},
games: {
valorant: true,
lol: true,
lolChatOcr: true,
lolOcrRegion: { x: 0.0, y: 0.6, w: 0.3, h: 0.27 },
lolLogsDir: null,
},
stt: {
@@ -112,6 +113,7 @@ export function defaultSettings(): Settings {
modelsDir: null,
reprocessAfterMatch: true,
gameVramReserveMb: 3072,
gameSaver: true,
},
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
dictionary: {

View File

@@ -1,20 +1,65 @@
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 HANGUL = /[가-힣]/;
/** 이 경기 상세에 나온 선수 이름 (양 팀 모두) */
export function matchPlayerNames(store: Store, matchId: string | null): string[] {
if (!matchId) return [];
const m = store.getMatch(matchId);
if (!m?.detail) return [];
try {
const det = JSON.parse(m.detail);
return (det.players || []).map((p: any) => (typeof p.name === 'string' ? p.name.trim() : '')).filter((n: string) => n && n !== '?');
} catch {
return [];
}
}
const normName = (s: string) => [...s.toLowerCase()].filter((ch) => /[\p{L}\p{N}]/u.test(ch)).join('');
/**
* 인식 결과가 선수 이름(또는 그 조각)뿐인가. 워커의 is_name_echo 와 같은 기준.
* 예: 이름 "QQQWWWQQQ" → "QQQWWWQ" 는 되풀이, "QQQ 잡았다" 는 아님.
*/
export function isNameEcho(text: string | null, names: string[]): boolean {
if (!text) return false;
const keys = names.map(normName).filter((k) => k.length >= 2);
const toks = text.split(/\s+/).map(normName).filter(Boolean);
if (!keys.length || !toks.length) return false;
const whole = toks.join('');
if (whole.length >= 2 && keys.some((k) => k.includes(whole))) return true;
return toks.every((t) => t.length >= 2 && keys.some((k) => k.includes(t)));
}
const NOISE_REASON: Record<string, string> = {
vad: '목소리 없음',
no_speech: '말소리 아님',
hallucination: '잡음에서 지어낸 문장',
repetition: '같은 말만 반복',
learned: '잡음으로 배운 문장',
name_echo: '선수 이름을 잘못 적음',
};
type Slot = 'realtime' | 'precise';
interface Job {
id: string;
slot: Slot;
/** 낮을수록 먼저 */
prio: number;
/** 예전 녹음 고친 뒤 다시 변환: 잡음으로 나오면 이전 결과를 지키고, 정밀 결과로만 덮는다 */
repair?: boolean;
/** 이미 정밀 모델로 변환한 발화도 다시 변환한다 (잡음으로 나오면 잡음으로 숨김) */
redo?: boolean;
}
export interface SttStatus {
@@ -36,7 +81,31 @@ export class SttPipeline {
private queued = new Set<string>();
private busy = false;
private processing: string | null = null;
/** 앱 종료 중: 새 작업을 꺼내지 않고, 워커가 끊겨 실패한 작업은 DB(곧 닫힘)에 기록하지 않는다. 남은 발화는 다음 시작 때 다시 처리 */
private stopped = false;
/** 한 발화의 변환이 끝났을 때 (녹음 파일 이름 맞추기) */
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;
/** 게임(발로란트 · 롤 경기)이 켜져 있다 (GameManager 가 2초마다 알려 줌) */
private gameActive = false;
/** 게임 중 GPU 아끼기: 켜져 있고 게임 중일 때 */
private saving(): boolean {
return this.gameActive && this.settings().stt.gameSaver !== false;
}
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
private bothFit = true;
status: SttStatus = {
@@ -80,10 +149,46 @@ export class SttPipeline {
this.bothFit = false;
}
await this.load('realtime', s.realtimeModel);
if (this.bothFit && !this.inMatch) await this.load('precise', s.preciseModel);
if (this.bothFit && !this.inMatch && !this.saving()) await this.load('precise', s.preciseModel);
this.pump();
}
/**
* 게임이 켜지고 꺼질 때 (v1.9.0). 게임 중 GPU 아끼기가 켜져 있으면
* 켜질 때 정밀 모델을 내리고(정밀 변환은 대기열에서 기다림), 꺼지면 다시 올려 밀린 정밀 변환을 한다.
*/
async setGameActive(on: boolean): Promise<void> {
if (this.gameActive === on) return;
this.gameActive = on;
const s = this.settings().stt;
if (on) {
if (s.gameSaver === false) return;
log.info('게임 켜짐: GPU 아끼기 (실시간 모델만 가볍게, 정밀 변환은 게임을 끈 뒤)');
if (this.status.slots.precise.state === 'loaded') await this.unload('precise');
return;
}
if (s.gameSaver !== false || this.queue.some((j) => j.slot === 'precise')) log.info('게임 꺼짐: 밀린 정밀 변환 시작');
if (this.status.worker !== 'ready') return; // 워커가 켜지면 prepareModels 가 이어서 한다
const wantPrecise = this.queue.some((j) => j.slot === 'precise') || this.bothFit;
if (wantPrecise) await this.load('precise', s.preciseModel);
if (this.gameActive) return; // 올리는 동안 게임이 다시 켜짐
// 정밀 모델이 없으면(설치 안 됨 · 실패) 기다리던 정밀 변환은 버린다 (실시간 결과가 그대로 남음)
if (this.status.slots.precise.state !== 'loaded') this.dropPrecise();
else if (!this.bothFit && !this.queue.some((j) => j.slot === 'precise')) await this.unload('precise');
this.pump();
}
private dropPrecise(): void {
const before = this.queue.length;
this.queue = this.queue.filter((j) => {
if (j.slot !== 'precise') return true;
this.queued.delete(`precise:${j.id}`);
return false;
});
this.status.queue = this.queue.length;
if (before !== this.queue.length) log.info(`정밀 모델이 없어 정밀 변환 ${before - this.queue.length}개를 건너뜀`);
}
private async installed(): Promise<Set<string>> {
try {
const r = await this.worker.request('models', {}, 30000);
@@ -132,16 +237,19 @@ export class SttPipeline {
/** 시작 시 미처리분 복구 */
resumePending(): void {
this.purgeOldNoise();
this.repairOldAudio();
this.recheckNameEchoes();
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, redo = 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 } : {}), ...(redo ? { redo } : {}) });
this.queue.sort((a, b) => a.prio - b.prio);
this.status.queue = this.queue.length;
this.pump();
@@ -157,6 +265,13 @@ export class SttPipeline {
this.inMatch = false;
const s = this.settings().stt;
if (!s.reprocessAfterMatch || s.preciseModel === s.realtimeModel) return;
if (this.saving()) {
// 게임(발로란트 메뉴 등)이 아직 켜져 있으면 정밀 변환은 대기열에서 게임이 꺼질 때까지 기다린다
const rows = this.store.realtimeUtterancesInRange(from, to);
log.info(`경기 종료: ${rows.length}개 발화의 정밀 변환은 게임을 끈 뒤에`);
for (const r of rows) this.enqueue(r.id, 'precise', 10);
return;
}
if (this.status.slots.precise.state !== 'loaded') await this.load('precise', s.preciseModel);
if (this.status.slots.precise.state !== 'loaded') return;
const rows = this.store.realtimeUtterancesInRange(from, to);
@@ -166,6 +281,11 @@ export class SttPipeline {
private pickSlot(job: Job): Slot | null {
const { realtime, precise } = this.status.slots;
if (this.saving()) {
// 게임 중: 정밀 변환은 기다리고, 새 발화는 실시간 모델로만
if (job.slot === 'precise') return null;
return realtime.state === 'loaded' ? 'realtime' : null;
}
if (job.slot === 'precise') return precise.state === 'loaded' ? 'precise' : null;
// 경기 밖이고 정밀 모델이 올라와 있으면 처음부터 정밀 모델로
if (!this.inMatch && precise.state === 'loaded' && this.queue.length < 20) return 'precise';
@@ -174,8 +294,13 @@ export class SttPipeline {
return null;
}
/** 종료 시작 (워커 · DB 를 닫기 전에 부른다) */
stop(): void {
this.stopped = true;
}
private pump(): void {
if (this.busy || !this.worker.ready) return;
if (this.stopped || this.busy || !this.worker.ready) return;
const idx = this.queue.findIndex((j) => this.pickSlot(j) !== null);
if (idx < 0) return;
const job = this.queue.splice(idx, 1)[0];
@@ -184,32 +309,42 @@ export class SttPipeline {
this.busy = true;
this.processing = job.id;
this.status.processing = job.id;
const t0 = Date.now();
this.run(job, this.pickSlot(job)!)
.catch((e) => log.error('STT 작업 오류', e))
.finally(() => {
this.busy = false;
this.processing = null;
this.status.processing = null;
setImmediate(() => this.pump());
if (this.stopped) return;
try {
if (!this.isBusy(job.id)) this.onDone?.(job.id);
} catch (e) {
log.warn('변환 뒤 처리 실패', e);
}
// 게임 중에는 변환한 만큼(최대 3초) 쉬고 다음 발화로: 여러 명이 연달아 말해도 GPU 를 계속 붙잡지 않는다
if (this.saving()) setTimeout(() => this.pump(), Math.min(Date.now() - t0, 3000));
else setImmediate(() => this.pump());
});
}
/** 이 경기에 나온 요원·챔피언·선수 이름 → 핫워드 맨 앞 */
private matchWords(u: UtteranceRow): string[] {
if (!u.match_id) return [];
const m = this.store.getMatch(u.match_id);
if (!m?.detail) return [];
try {
const det = JSON.parse(m.detail);
const out: string[] = [];
for (const p of det.players || []) {
if (p.character?.name && p.character.name !== '?') out.push(p.character.name);
/**
* 이 경기에 나온 요원·챔피언·선수 이름 → 핫워드 맨 앞.
* 선수 이름은 한글이 들어간 것만 넣는다: "QQQWWWQQQ" 같은 영문 · 숫자 닉네임은 한국어 말로 나올 일이 거의 없고,
* 말을 못 알아들을 때 Whisper 가 그 이름을 그대로 적어 버린다 (v1.4.3).
*/
private matchWords(u: UtteranceRow): { words: string[]; players: string[] } {
const players = matchPlayerNames(this.store, u.match_id).filter((n) => HANGUL.test(n));
const words: string[] = [];
if (u.match_id) {
try {
const det = JSON.parse(this.store.getMatch(u.match_id)?.detail || '{}');
for (const p of det.players || []) if (p.character?.name && p.character.name !== '?') words.push(p.character.name);
} catch {
/* 경기 상세가 깨졌으면 요원 이름 없이 */
}
for (const p of det.players || []) if (p.name && p.name !== '?') out.push(p.name);
return out;
} catch {
return [];
}
return { words: [...words, ...players], players };
}
private dictContext(u: UtteranceRow): DictContext {
@@ -224,10 +359,11 @@ 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 && !job.redo))) return;
const s = this.settings();
const ctx = this.dictContext(u);
const user = this.store.getUser(u.user_id);
const mw = this.matchWords(u);
let r: TranscribeResult;
try {
r = await this.worker.request<TranscribeResult>(
@@ -235,7 +371,9 @@ export class SttPipeline {
{
slot,
path: u.audio_path,
hotwords: this.dict.hotwords(ctx, this.matchWords(u)),
hotwords: this.dict.hotwords(ctx, mw.words),
// 결과가 이 이름(조각)뿐이면 워커가 이름을 빼고 다시 변환한다
player_names: mw.players,
initial_prompt: null,
corrections: this.dict.corrections(),
dictionary: this.dict.candidates(ctx),
@@ -243,10 +381,13 @@ export class SttPipeline {
target_lufs: s.audio.targetLufs,
noise_sensitivity: s.audio.noiseSensitivity,
denoise: s.audio.denoise,
// 게임 중에는 빔 1 (빔 3 보다 가볍다. 경기 뒤 정밀 모델이 다시 변환한다)
...(this.saving() && slot === 'realtime' ? { beam_size: 1 } : {}),
},
5 * 60000,
);
} catch (e: any) {
if (this.stopped) return;
const attempts = this.store.bumpAttempt(u.id);
this.status.lastError = e.message;
log.warn(`STT 실패 (${u.id}, ${attempts}회): ${e.message}`);
@@ -258,6 +399,18 @@ export class SttPipeline {
} else this.enqueue(u.id, job.slot, job.prio + 2);
return;
}
// 종료 중에 결과가 왔으면 버린다 (DB 가 이미 닫혔을 수 있다. 발화는 다음 시작 때 다시 처리)
if (this.stopped) 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 +423,134 @@ 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.4.3): 예전 버전이 선수 이름 핫워드를 그대로 적은 발화(예: 상대 닉네임 "QQQWWWQ")를 다시 본다.
* 음성 파일이 있으면 새 기준(한글 이름만 핫워드 · 이름 되풀이면 이름 없이 다시)으로 정밀 모델이 다시 변환하고,
* 파일이 지워졌으면 다시 들을 수 없으니 잡음으로 숨긴다. 사람이 고친 발화는 건드리지 않는다.
*/
private recheckNameEchoes(): void {
const KEY = 'name_echo_recheck_v143';
if (this.store.meta(KEY)) return;
const rows = this.store.db
.prepare(`SELECT rowid,* FROM utterances WHERE noise=0 AND corrected=0 AND match_id IS NOT NULL AND text IS NOT NULL ORDER BY started_at`)
.all() as UtteranceRow[];
const names = new Map<string, string[]>();
let redo = 0;
let hidden = 0;
for (const u of rows) {
if (!names.has(u.match_id!)) names.set(u.match_id!, matchPlayerNames(this.store, u.match_id));
if (!isNameEcho(u.text, names.get(u.match_id!)!)) continue;
if (u.audio_path && !u.audio_deleted && fs.existsSync(u.audio_path)) {
log.info(`선수 이름을 잘못 적은 발화 ${u.id} ("${u.text}") → 정밀 모델로 다시 변환`);
this.enqueue(u.id, 'precise', 20, false, true);
redo++;
} else {
log.info(`선수 이름을 잘못 적은 발화 ${u.id} ("${u.text}") → 음성 파일이 없어 숨김`);
this.store.updateUtteranceResult(u.id, {
text: null,
raw_text: u.raw_text,
words: [],
noise: true,
noise_reason: 'name_echo',
confidence: u.confidence,
lufs: u.lufs,
gain_db: u.gain_db,
model: u.model ?? '',
status: u.status === 'precise' ? 'precise' : 'realtime',
});
this.emit(u.id);
hidden++;
}
}
this.store.setMeta(KEY, String(Date.now()));
if (redo || hidden) log.info(`선수 이름을 잘못 적은 예전 발화: ${redo}개 다시 변환, ${hidden}개(음성 파일 없음) 숨김`);
}
/** 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) {
@@ -172,9 +173,15 @@ export class Timeline {
if (q.match) {
where.push('e.match_id = ?');
args.push(q.match);
} else if (q.game) {
where.push('e.game = ?');
args.push(q.game);
} else {
if (q.game) {
where.push('e.game = ?');
args.push(q.game);
}
// Riot 경기 기록에서 가져오기만 한 경기(앱이 녹음하지 않은 경기)의 킬 · 라운드는 타임라인에 넣지 않는다 (경기 화면에서는 보인다)
where.push(
`(e.match_id IS NULL OR e.match_id NOT IN (SELECT m.id FROM matches m WHERE m.source = 'history' AND NOT EXISTS (SELECT 1 FROM utterances x WHERE x.match_id = m.id)))`,
);
}
if (q.users?.length) {
// 선택하지 않은 (디스코드에 연결된) 유저가 주인공인 이벤트만 뺀다. 라운드·오브젝트·상대 킬처럼 유저가 없는 이벤트는 남긴다.
@@ -224,7 +231,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;
@@ -82,14 +84,16 @@ export interface GvrApi {
adminAddUser(id: string, role: 'admin' | 'user'): Promise<{ users: AppUserRow[] }>;
adminSetRole(id: string, role: 'admin' | 'user'): Promise<{ users: AppUserRow[] }>;
adminRemoveUser(id: string): Promise<{ users: AppUserRow[] }>;
adminDisplayNames(): Promise<Record<string, string>>;
adminSetDisplayName(id: string, name: string): Promise<Record<string, string>>;
getState(): Promise<AppState>;
onState(cb: (s: AppState) => void): () => void;
updateSettings(patch: DeepPartial<Settings>): Promise<Settings>;
setSecret(key: 'botToken' | 'riotApiKey', value: string | null): Promise<void>;
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 }[]>;
previewTts(text: string, voice: string): Promise<{ ok: boolean; dataUrl?: string; error?: string }>;
guildMembers(): Promise<{ id: string; name: string; avatar: string | null; bot: boolean; me: boolean; admin: boolean }[]>;
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 }>;
@@ -106,6 +110,8 @@ export interface GvrApi {
users(): Promise<User[]>;
setRiotIds(userId: string, riotIds: string[]): Promise<void>;
setExcluded(userId: string, excluded: boolean): Promise<void>;
/** Riot 경기 기록 가져오기 취소 (v1.9.1). game 이 없으면 둘 다. resumeAt = 다시 이어서 하는 시각 */
cancelHistory(game?: 'valorant' | 'lol'): Promise<{ cancelled: ('valorant' | 'lol')[]; resumeAt: number | null }>;
dictionary(): Promise<{ labels: Record<string, string>; packs: { key: string; label: string; count: number }[]; entries: { id: number; word: string; from: string | null; kind: 'hotword' | 'correction'; pack: string; source: string; enabled: boolean; hits: number }[] }>;
addWord(word: string): Promise<void>;
addCorrection(from: string, to: string): Promise<void>;

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()
@@ -122,17 +123,23 @@ export function registerIpc(ctx: IpcContext) {
await core.startBot();
return core.bot.state.status === 'ready' || core.bot.state.status === 'connecting' ? { ok: true } : { ok: false, error: core.bot.state.error ?? '봇을 시작하지 못했습니다' };
},
// 따라갈 사람 목록: 내 계정 → 관리자 → 나머지(이름순). 실패하면 오류를 그대로 보여 준다
guildMembers: async () => {
const ms = await core.bot.members().catch(() => []);
return ms.map((m) => ({ id: m.id, name: m.name, avatar: m.avatar, bot: m.bot })).sort((a, b) => a.name.localeCompare(b.name, 'ko'));
const [ms, admins] = await Promise.all([core.bot.members(), ctx.auth.adminIds().catch(() => [] as string[])]);
const meId = ctx.auth.state.user?.id ?? null;
const rank = (m: { me: boolean; admin: boolean }) => (m.me ? 0 : m.admin ? 1 : 2);
return ms
.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}` };
}
@@ -234,13 +241,10 @@ export function registerIpc(ctx: IpcContext) {
return core.store.listUsers().map((u) => toUser(u, acc));
},
setRiotIds: (userId: string, riotIds: string[]) => {
const cur = core.store.listAccounts().filter((a) => a.user_id === userId);
const next = riotIds
.map((r) => r.trim())
.filter((r) => /^.+#.+$/.test(r))
.map((r) => cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r });
core.store.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id })));
core.store.setRiotIds(userId, riotIds, true);
core.bus.live({ type: 'users.updated', data: [] });
},
cancelHistory: (game?: 'valorant' | 'lol') => core.games.cancelHistory(game),
setExcluded: (userId: string, excluded: boolean) => {
core.store.setExcluded(userId, excluded);
core.bus.live({ type: 'users.updated', data: [] });
@@ -343,6 +347,13 @@ export function registerIpc(ctx: IpcContext) {
adminAddUser: (id: string, r: 'admin' | 'user') => ctx.auth.adminAddUser(id, r),
adminSetRole: (id: string, r: 'admin' | 'user') => ctx.auth.adminSetRole(id, r),
adminRemoveUser: (id: string) => ctx.auth.adminRemoveUser(id),
adminDisplayNames: () => ctx.auth.displayNames(),
adminSetDisplayName: async (id: string, name: string) => {
if (role() !== 'superadmin') throw new Error('표시 이름은 최고 관리자만 바꿀 수 있습니다');
const r = await ctx.auth.adminSetDisplayName(id, name);
ctx.current()?.core.store.setDisplayNames(r.names);
return r.names;
},
openExternal: h.openExternal,
quit: h.quit,
};

View File

@@ -11,7 +11,8 @@ import { hardenTlsEnv, secureFetch } from '../core/util/secure-http.js';
import { Finetuner } from './finetune.js';
import type { AuthView } from './api-types.js';
import { buildState, registerIpc } from './ipc.js';
import { brandDir, rendererDir, resolveDataDir, resourcesDir, workerCommand } from './paths.js';
import { brandDir, rendererDir, replayToolPath, resolveDataDir, resourcesDir, workerCommand } from './paths.js';
import { TrayShell } from './tray-shell.js';
// 인증서 검증을 끄는 환경변수(NODE_TLS_REJECT_UNAUTHORIZED=0)는 무시한다. fuses 로 막지 못하는 변수라 가장 먼저 지운다
hardenTlsEnv();
@@ -22,6 +23,8 @@ const opt = (name: string) => argv.find((a) => a.startsWith(`--${name}=`))?.spli
const SMOKE = flag('smoke');
app.setAppUserModelId('kr.tkrmagid.gvr');
// 설정 창은 글자 · 버튼뿐이라 GPU 로 그릴 필요가 없다. 게임 · 브라우저와 GPU 를 나눠 쓰지 않게 끈다 (v1.9.0)
app.disableHardwareAcceleration();
if (!SMOKE && !app.requestSingleInstanceLock()) {
app.quit();
process.exit(0);
@@ -33,7 +36,7 @@ let ft: Finetuner | null = null;
let settings: SettingsStore | null = null;
let auth: AppAuth | null = null;
let win: BrowserWindow | null = null;
let tray: Tray | null = null;
const trayShell = new TrayShell<Tray>();
let quitting = false;
const dataDir = resolveDataDir(opt('data-dir'));
@@ -94,7 +97,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,7 +110,48 @@ 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 {
const tray = trayShell.get();
if (!tray) return;
if (!core) {
tray.setImage(trayImage('off'));
@@ -125,6 +172,7 @@ function updateTray(): void {
}
function buildTrayMenu(): void {
const tray = trayShell.get();
if (!tray) return;
if (!core) {
tray.setContextMenu(
@@ -160,7 +208,8 @@ async function quit(): Promise<void> {
} catch (e) {
log.error('종료 중 오류', e);
}
tray?.destroy();
// 트레이 갱신 타이머가 app.exit 사이에 한 번 더 돌면 'Tray is destroyed' 오류 창이 뜬다
trayShell.dispose();
app.exit(0);
}
@@ -174,7 +223,7 @@ async function smoke(): Promise<void> {
const a = await new AppAuth(st, { version: app.getVersion(), openUrl: () => undefined }).check();
out.auth = a.status;
out.builtinBot = st.hasBuiltinBot;
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: st });
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: st, replayTool: replayToolPath() });
out.codec = c.settings.codecName;
out.botMode = c.settings.get().discord.botMode;
const ready = await new Promise<any>((res) => {
@@ -201,7 +250,18 @@ async function smoke(): Promise<void> {
out.dict = c.store.listDict().length;
out.renderer = fs.existsSync(path.join(rendererDir(), 'index.html'));
out.tray = fs.existsSync(path.join(brandDir(), 'tray.png'));
code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray && out.siteTls === true ? 0 : 1;
// 3D 리플레이 변환기 (v1.5.0): 배포본 안에 있어야 한다. GVR_SMOKE_VRF 가 있으면 실제로 변환해 본다
out.replayTool = fs.existsSync(replayToolPath());
if (process.env.GVR_SMOKE_VRF) {
const vrf = process.env.GVR_SMOKE_VRF;
const id = path.basename(vrf).replace(/\.vrf$/i, '');
process.env.GVR_REPLAY_DIRS = path.dirname(vrf);
const t0 = Date.now();
const r = await c.replays.get(id, 170000);
out.replayConvert = r.state === 'ready' ? { ok: true, ms: Date.now() - t0, gz: fs.statSync(r.file).size } : r;
}
const replayOk = out.replayTool === true && (!process.env.GVR_SMOKE_VRF || (out.replayConvert as any)?.ok === true);
code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray && out.siteTls === true && replayOk ? 0 : 1;
await c.stop();
} catch (e: any) {
out.error = e.stack || e.message;
@@ -228,14 +288,31 @@ const refreshShell = () => {
let starting: Promise<void> | null = null;
/** 표시 이름(실명 숨기기)을 사이트 서버에서 받아 녹음 기록 · 범인 분석에 반영한다 (못 받으면 저장해 둔 것을 그대로 쓴다) */
async function syncNames(): Promise<void> {
const c = core;
if (!c || !auth?.ok) return;
try {
const names = await auth.displayNames();
if (core === c) {
c.store.setDisplayNames(names);
// 녹음 파일 이름에도 표시 이름을 쓴다
c.audioNames.refreshAll();
}
} catch (e: any) {
log.warn(`표시 이름을 받지 못했습니다: ${e?.message ?? e}`);
}
}
/** 로그인 확인 후 코어 시작 */
function startApp(): Promise<void> {
if (core) return Promise.resolve();
starting ??= (async () => {
try {
// 겜녹이 봇 중계가 로그인 만료 · 등록 해제를 알려 오면 10분을 기다리지 않고 바로 확인해서 잠근다
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check() });
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check(), replayTool: replayToolPath() });
core = c;
void syncNames();
ft = new Finetuner(c, pushState);
ft.scheduleNightly();
appError = null;
@@ -286,6 +363,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;
@@ -304,28 +382,34 @@ app.whenReady().then(async () => {
if (starting) await starting;
},
});
tray = new Tray(trayImage('off'));
const tray = new Tray(trayImage('off'));
tray.on('click', () => openWindow());
trayShell.set(tray);
refreshShell();
a.on('change', onAuthChange);
// 시작할 때 확인 → 10분마다 다시 확인 (등록 해제되면 바로 잠김). 서버에 못 붙어 막힌 상태면 1분마다 다시 시도
let lastCheck = Date.now();
const first = a.check();
setInterval(() => {
trayShell.every(15000, () => {
const st = a.state.status;
if ((st === 'ok' && Date.now() - lastCheck > 10 * 60000) || (st === 'error' && Date.now() - lastCheck > 60000) || (st === 'ok' && a.state.offline && Date.now() - lastCheck > 60000)) {
lastCheck = Date.now();
void a.check();
void a.check().then(syncNames);
}
}, 15000);
setInterval(() => {
});
trayShell.every(1500, () => {
updateTray();
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

@@ -55,3 +55,10 @@ export function workerCommand(): { cmd: string; args: string[]; cwd?: string } {
export function finetuneScriptsDir(): string {
return app.isPackaged ? path.join(process.resourcesPath, 'worker', '_internal', 'gvr_worker', 'finetune') : path.join(appRoot, '..', 'worker', 'gvr_worker', 'finetune');
}
/** 발로란트 리플레이 변환기 (tools/replay-extract, 배포본은 resources/replay/gvr-replay.exe) */
export function replayToolPath(): string {
if (process.env.GVR_REPLAY_TOOL) return process.env.GVR_REPLAY_TOOL;
if (app.isPackaged) return path.join(process.resourcesPath, 'replay', process.platform === 'win32' ? 'gvr-replay.exe' : 'gvr-replay');
return path.join(appRoot, '..', 'tools', 'replay-extract', 'out', process.platform === 'win32' ? 'win/gvr-replay.exe' : 'linux/gvr-replay');
}

View File

@@ -4,10 +4,10 @@ import { contextBridge, ipcRenderer } from 'electron';
const METHODS = [
'getState', 'updateSettings', 'setSecret', 'testBotToken', 'restartBot', 'guildMembers', 'previewTts', 'gpuInfo', 'models',
'download', 'deleteModel', 'applyModels', 'chooseFolder', 'registerDevice', 'unregisterDevice', 'runDiagnostics', 'storageUsage',
'runRetention', 'users', 'setRiotIds', 'setExcluded', 'dictionary', 'addWord', 'addCorrection', 'deleteDict', 'setDictEnabled',
'runRetention', 'users', 'setRiotIds', 'setExcluded', 'cancelHistory', 'dictionary', 'addWord', 'addCorrection', 'deleteDict', 'setDictEnabled',
'finetuneStatus', 'finetuneInstall', 'finetuneStart', 'finetuneStop', 'finetuneRollback', 'clearTrainingData', 'openExternal',
'openPath', 'setAutoStart', 'finishWizard', 'recentLogs', 'quit',
'authState', 'authLogin', 'authCancel', 'authLogout', 'authRecheck', 'adminUsers', 'adminAddUser', 'adminSetRole', 'adminRemoveUser',
'authState', 'authLogin', 'authCancel', 'authLogout', 'authRecheck', 'adminUsers', 'adminAddUser', 'adminSetRole', 'adminRemoveUser', 'adminDisplayNames', 'adminSetDisplayName',
];
const api: Record<string, unknown> = {};
for (const m of METHODS) api[m] = (...args: unknown[]) => ipcRenderer.invoke(`gvr:${m}`, ...args);

View File

@@ -0,0 +1,31 @@
/** 트레이 아이콘과 그 갱신 타이머. 종료할 때 타이머를 먼저 멈추고 트레이를 없앤다 (v1.8.2: 'Tray is destroyed' 오류 창) */
export interface TrayLike {
isDestroyed(): boolean;
destroy(): void;
}
export class TrayShell<T extends TrayLike> {
private tray: T | null = null;
private timers: NodeJS.Timeout[] = [];
set(tray: T): void {
this.tray = tray;
}
/** 쓸 수 있는 트레이 (없거나, 종료했거나, Windows 로그오프 등으로 Electron 이 먼저 없앴으면 null) */
get(): T | null {
return this.tray && !this.tray.isDestroyed() ? this.tray : null;
}
every(ms: number, fn: () => void): void {
this.timers.push(setInterval(fn, ms));
}
dispose(): void {
for (const t of this.timers) clearInterval(t);
this.timers = [];
const tray = this.get();
this.tray = null;
tray?.destroy();
}
}

View File

@@ -24,8 +24,9 @@ function defaults(): Settings {
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
ttsRate: 1,
},
games: { valorant: true, lol: true, lolChatOcr: true, lolOcrRegion: { x: 0.0, y: 0.6, w: 0.3, h: 0.27 }, lolLogsDir: null },
games: { valorant: true, lol: true, lolLogsDir: null },
stt: {
realtimeModel: 'large-v3-turbo',
preciseModel: 'large-v3',
@@ -34,6 +35,7 @@ function defaults(): Settings {
modelsDir: null,
reprocessAfterMatch: true,
gameVramReserveMb: 3072,
gameSaver: true,
},
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
dictionary: {
@@ -111,6 +113,7 @@ export function createMockGvr(): GvrApi {
};
const authListeners = new Set<(s: AuthView) => void>();
const emitAuth = () => authListeners.forEach((l) => l(structuredClone(auth)));
const displayNames: Record<string, string> = { '100000000000000003': '지호' };
let adminRows: AppUserRow[] = [
{ id: '293719842274541579', name: '사금향', avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: now - 60000, lastVersion: '1.2.0' },
{ id: '1352267557213573160', name: '두번째관리자', avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: now - 3 * 86400000, lastVersion: '1.2.0' },
@@ -157,6 +160,18 @@ 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,
history: q.has('nohistory') ? null : { phase: 'fetch', first: true, scanned: 140, done: 37, total: 120, startedAt: now - 40000, etaMs: 90000 }, updatedAt: now,
},
],
counts: { utterances: 1824, matches: 37 },
excludedUsers: noToken ? [] : [{ id: 'u4', name: '현우' }],
autoStart: false,
@@ -292,6 +307,17 @@ export function createMockGvr(): GvrApi {
adminRows = adminRows.map((u) => (u.id === id && !u.fixed ? { ...u, role: r } : u));
return { users: structuredClone(adminRows) };
},
async adminDisplayNames() {
await sleep(150);
return { ...displayNames };
},
async adminSetDisplayName(id, name) {
await sleep(150);
adminCheck('superadmin');
if (name.trim()) displayNames[id] = name.trim();
else delete displayNames[id];
return { ...displayNames };
},
async adminRemoveUser(id) {
await sleep(200);
adminCheck('superadmin');
@@ -357,12 +383,12 @@ export function createMockGvr(): GvrApi {
async guildMembers() {
await sleep(300);
return [
{ id: 'u1', name: '민준', avatar: null, bot: false },
{ id: 'u2', name: '서연', avatar: null, bot: false },
{ id: 'u3', name: '지호', avatar: null, bot: false },
{ id: 'u4', name: '현우', avatar: null, bot: false },
{ id: 'b1', name: '겜녹이', avatar: null, bot: true },
{ id: 'b2', name: 'MEE6', avatar: null, bot: true },
{ id: 'u1', name: '민준', avatar: null, bot: false, me: true, admin: true },
{ id: 'u3', name: '지호', avatar: null, bot: false, me: false, admin: true },
{ id: 'u2', name: '서연', avatar: null, bot: false, me: false, admin: false },
{ id: 'u4', name: '현우', avatar: null, bot: false, me: false, admin: false },
{ id: 'b1', name: '겜녹이', avatar: null, bot: true, me: false, admin: false },
{ id: 'b2', name: 'MEE6', avatar: null, bot: true, me: false, admin: false },
];
},
async previewTts() {
@@ -462,7 +488,6 @@ export function createMockGvr(): GvrApi {
{ id: 'tts', label: 'TTS 안내 음성', ok: true, detail: 'Edge TTS 응답 0.6초' },
{ id: 'valorant', label: '발로란트 로컬 API', ok: true, detail: 'Riot Client 연결됨 (lockfile)' },
{ id: 'lol', label: '롤 Live Client API', ok: null, detail: '게임이 꺼져 있어 확인할 수 없습니다' },
{ id: 'ocr', label: '롤 채팅 OCR', ok: null, detail: '게임이 꺼져 있어 확인할 수 없습니다' },
{ id: 'relay', label: '사이트 서버', ok: state.relay.state === 'online', detail: state.relay.state === 'online' ? 'gvr.tkrmagid.kr 연결됨 · 왕복 38ms' : '등록되지 않음' },
{ id: 'disk', label: '저장 공간', ok: true, detail: 'D: 여유 412GB' },
];
@@ -495,6 +520,18 @@ export function createMockGvr(): GvrApi {
const u = users.find((x) => x.id === userId);
if (u) u.riot = riotIds.map((r, i) => ({ puuid: `${userId}-${i}`, riotId: r }));
},
async cancelHistory(game) {
await sleep(150);
const cancelled: ('valorant' | 'lol')[] = [];
for (const g of state.liveGames ?? []) {
if (g.history && (!game || g.game === game)) {
g.history = null;
cancelled.push(g.game);
}
}
emit();
return { cancelled, resumeAt: cancelled.length ? Date.now() + 30 * 60000 : null };
},
async setExcluded(userId, excluded) {
const u = users.find((x) => x.id === userId);
if (u) u.excluded = excluded;

View File

@@ -149,6 +149,10 @@ input[type='number'].input { flex: none; padding: 7px 8px; }
.pbar i { display: block; height: 100%; background: linear-gradient(90deg, var(--accent), #ff7a85); border-radius: 5px; transition: width 0.25s; }
.pbar.done i { background: linear-gradient(90deg, #1fb383, var(--good)); }
.pbar.error i { background: #6b2a33; }
.pbar.indet i { width: 35%; animation: pbar-indet 1.4s ease-in-out infinite; }
@keyframes pbar-indet { 0% { transform: translateX(-100%); } 100% { transform: translateX(290%); } }
.hist-row + .hist-row { margin-top: 12px; }
.hist-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.prog { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; }
.prog-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; font-size: 13px; }
.dl-list { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; }
@@ -178,8 +182,6 @@ input[type='number'].input { flex: none; padding: 7px 8px; }
.game.lol.on { border: 2px solid var(--lol); background: linear-gradient(160deg, #241e13, var(--panel) 60%); padding: 15px 17px; }
.game.lol .game-name { color: var(--lol); }
.game.lol .tg.on { background: linear-gradient(180deg, #c8aa6e, #9a7b45); }
.region { display: flex; gap: 10px; }
.region label { display: flex; align-items: center; gap: 5px; }
/* 표 */
.table { width: 100%; border-collapse: collapse; font-size: 13px; }
@@ -318,3 +320,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

@@ -150,6 +150,66 @@ function UserTable({ users, superAdmin, onChange }: { users: AppUserRow[]; super
);
}
/** 표시 이름: 실명이 들어간 디스코드 이름 · 서버 별명 대신 사이트 · 녹음 기록 · 범인 분석에 쓸 이름 */
function DisplayNames({ superAdmin }: { superAdmin: boolean }) {
const { toast } = useApp();
const list = useLoad(() => gvr.adminDisplayNames());
const [id, setId] = useState('');
const [name, setName] = useState('');
const act = useAction();
const valid = /^\d{17,20}$/.test(id.trim()) && !!name.trim();
const save = async (uid: string, n: string) => {
const r = await act.run(() => gvr.adminSetDisplayName(uid, n));
if (r) {
list.setData(r);
toast(n ? `${uid} → ${n}` : `${uid} 표시 이름 지움`);
setId('');
setName('');
}
};
const rows = Object.entries(list.data ?? {});
return (
<>
{superAdmin && (
<div className="field">
<input className="input mono" value={id} placeholder="디스코드 아이디" spellCheck={false} onChange={(e) => setId(e.target.value.replace(/\s/g, ''))} />
<input className="input" value={name} placeholder="보일 이름" maxLength={32} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && valid && void save(id.trim(), name.trim())} />
<Btn primary disabled={!valid} busy={act.busy} onClick={() => save(id.trim(), name.trim())}>
저장
</Btn>
</div>
)}
{list.loading && !list.data ? (
<Spinner />
) : list.error ? (
<Err>{list.error}</Err>
) : rows.length ? (
<table className="table">
<tbody>
{rows.map(([uid, n]) => (
<tr key={uid}>
<td className="mono small">{uid}</td>
<td>{n}</td>
{superAdmin && (
<td className="r">
<Btn small ghost disabled={act.busy} onClick={() => save(uid, '')}>
지우기
</Btn>
</td>
)}
</tr>
))}
</tbody>
</table>
) : (
<div className="muted">정해 둔 표시 이름이 없습니다. 디스코드 이름(서버 별명)이 그대로 보입니다.</div>
)}
<div className="hint">디스코드 이름이나 서버 별명에 실명이 들어 있으면 여기서 다른 이름을 정해 주세요. 사이트, 녹음 기록, 범인 분석에 이 이름만 쓰고 이미 저장된 기록의 이름도 바꿉니다.</div>
<Err>{act.error}</Err>
</>
);
}
export function AdminTab() {
const { state } = useApp();
const superAdmin = state.account.role === 'superadmin';
@@ -179,6 +239,9 @@ export function AdminTab() {
>
{list.loading && !list.data ? <Spinner /> : list.error ? <Err>{list.error}</Err> : <UserTable users={users} superAdmin={superAdmin} onChange={set} />}
</Section>
<Section title="표시 이름 (실명 숨기기)" sub="바꾸기는 최고 관리자만">
<DisplayNames superAdmin={superAdmin} />
</Section>
<Section title="관리자 전용 기능" sub="일반 유저 화면에서는 잠겨 있습니다">
<ul className="admin-list">
{ADMIN_FEATURES.map((f) => (

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']>>;
@@ -220,13 +220,20 @@ export function GuildFollow({ guilds, compact }: { guilds?: { id: string; name:
disabled={!d.guildId || members.loading}
options={[
{ value: '', label: members.loading && d.guildId ? '불러오는 중…' : '선택 안 함' },
...people.map((m) => ({ value: m.id, label: m.name })),
...people.map((m) => ({ value: m.id, label: m.me ? `${m.name} (나)` : m.admin ? `${m.name} · 관리자` : m.name })),
...(d.followUserId && !people.some((p) => p.id === d.followUserId) && !members.loading ? [{ value: d.followUserId, label: `(알 수 없음 ${d.followUserId})` }] : []),
]}
onChange={(v) => save({ discord: { followUserId: v || null } })}
/>
</Line>
{members.error && <Err>{members.error}</Err>}
{members.error && (
<Err>
멤버 목록을 불러오지 못했습니다: {members.error}{' '}
<Btn small onClick={() => void members.reload()}>
다시 불러오기
</Btn>
</Err>
)}
</div>
);
}
@@ -241,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);
@@ -330,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,7 +1,7 @@
import { useState } from 'react';
import type { User } from '@gvr/shared';
import { GAME_NAME, historyStatus, liveGameRows, resumeText, type LiveGame, type User } from '@gvr/shared';
import { gvr, useAction, useApp, useLoad } from '../store';
import { Avatar, Btn, Dot, Err, FolderRow, Line, NumInput, Page, Section, Spinner, Toggle, ToggleLine } from '../ui';
import { Avatar, Btn, Dot, Err, FolderRow, Page, Section, Spinner, Toggle } from '../ui';
/** 발로란트 / 롤 켜기 카드 (마법사에서도 사용) */
export function GameCards({ showStatus = true }: { showStatus?: boolean }) {
@@ -9,7 +9,7 @@ export function GameCards({ showStatus = true }: { showStatus?: boolean }) {
const g = settings.games;
const cards = [
{ id: 'valorant' as const, name: 'VALORANT', ko: '발로란트', desc: '라운드 · 킬 · 스파이크 이벤트와 대화를 함께 기록', on: g.valorant, st: state.games.valorant },
{ id: 'lol' as const, name: 'League of Legends', ko: '리그 오브 레전드', desc: '킬 · 오브젝트 · 채팅(OCR)과 대화를 함께 기록', on: g.lol, st: state.games.lol },
{ id: 'lol' as const, name: 'League of Legends', ko: '리그 오브 레전드', desc: '킬 · 오브젝트 · 채팅(API)과 대화를 함께 기록', on: g.lol, st: state.games.lol },
];
return (
<div className="games">
@@ -52,6 +52,76 @@ 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>
);
}
/** Riot 경기 기록 가져오기 진행 바 · 취소 (v1.9.1). 게임 중이 아닐 때 30분마다 돈다 */
function HistoryImport() {
const { state, toast } = useApp();
const act = useAction();
const rows = (state.liveGames ?? []).filter((g) => g.history);
if (!rows.length) return null;
const cancel = async (game: LiveGame['game']) => {
const r = await act.run(() => gvr.cancelHistory(game));
if (r?.cancelled.length) toast(`${GAME_NAME[game]} 경기 기록 가져오기를 멈췄습니다. 받은 경기는 남고, ${resumeText(r.resumeAt)} 남은 것부터 이어서 가져옵니다`);
};
return (
<Section title="Riot 경기 기록" sub="사이트 경기 탭에 지난 경기 채우기">
{rows.map((g) => {
const st = historyStatus(g.history!);
return (
<div key={g.game} className="hist-row">
<div className="hist-top">
<Spinner />
<b>{GAME_NAME[g.game]}</b>
<span>{st.title}</span>
<span className="muted">{st.detail}</span>
<span style={{ flex: 1 }} />
<Btn small ghost busy={act.busy} onClick={() => cancel(g.game)}>
취소
</Btn>
</div>
<div className={`pbar${st.pct == null ? ' indet' : ''}`}>
<i style={{ width: st.pct == null ? undefined : `${st.pct}%` }} />
</div>
{g.history!.first && <div className="hint">처음 한 번은 지난 경기를 끝까지 가져와서 오래 걸립니다. 게임을 켜면 바로 멈추고, 다음부터는 새 경기만 가져옵니다.</div>}
</div>
);
})}
<Err>{act.error}</Err>
</Section>
);
}
const RIOT_RE = /^[^#]{1,16}#[^#\s]{2,5}$/;
function RiotRow({ u }: { u: User }) {
@@ -143,23 +213,16 @@ export function GamesTab() {
const { settings, save } = useApp();
const g = settings.games;
const users = useLoad(() => gvr.users());
const region = g.lolOcrRegion;
return (
<Page title="게임 연동">
<GameCards />
<HistoryImport />
<LiveGames />
<Section title="리그 오브 레전드 세부 설정" className={g.lol ? '' : 'disabled'}>
<ToggleLine label="롤 채팅 OCR" hint="게임 옵션에서 채팅 타임스탬프를 켜고 '테두리 없음' 창 모드를 쓰면 정확합니다" on={g.lolChatOcr} onChange={(v) => save({ games: { lolChatOcr: v } })} />
<Line label="채팅 영역" hint="화면 크기에 대한 비율 (0~1) · 왼쪽 아래 채팅창 기본값">
<div className="region">
{(['x', 'y', 'w', 'h'] as const).map((k) => (
<label key={k}>
<span className="muted mono">{k}</span>
<NumInput value={region[k]} min={0} max={1} step={0.01} width={70} onCommit={(n) => save({ games: { lolOcrRegion: { ...region, [k]: n } } })} />
</label>
))}
</div>
</Line>
<div className="lab" style={{ marginTop: 8 }}>
<div className="muted" style={{ marginBottom: 8 }}>
롤 채팅은 롤 클라이언트(LCU) API 로 챔피언 선택 · 게임 후 채팅을 받습니다. 게임 중 전체 · 팀 채팅은 롤이 API 로 주지 않아, 게임 로그 파일에 남아 있을 때만 경기 뒤에 붙입니다. 화면 글자 인식(OCR)은 쓰지 않습니다.
</div>
<div className="lab">
롤 로그 폴더 <span className="dim">(비워 두면 Riot Games 기본 위치에서 찾습니다)</span>
</div>
<FolderRow

View File

@@ -184,6 +184,12 @@ export function SttTab() {
<div className="warn-text small">⚠ RTX 50 시리즈(Blackwell)에서 int8 계열은 cuBLAS 오류 사례가 있습니다. 문제가 생기면 float16으로 돌려 주세요.</div>
)}
<ToggleLine label="경기가 끝나면 정밀 모델로 다시 변환" on={s.reprocessAfterMatch} onChange={(v) => save({ stt: { reprocessAfterMatch: v } })} />
<ToggleLine
label="게임 중 GPU 아끼기"
hint="게임이 켜져 있으면 실시간 모델만 가볍게 쉬어 가며 돌리고, 정밀 모델 변환은 게임을 끈 뒤에 합니다"
on={s.gameSaver}
onChange={(v) => save({ stt: { gameSaver: v } })}
/>
<Line label="게임용 VRAM 예약" hint="두 게임 중 큰 값 · 실측 후 조정">
<NumInput value={s.gameVramReserveMb} min={0} max={24576} step={256} width={90} suffix="MB" onCommit={(n) => save({ stt: { gameVramReserveMb: n } })} />
</Line>

View File

@@ -63,7 +63,7 @@ function Step2() {
<>
<Head title="게임 선택" desc="켠 게임의 경기 이벤트(킬 · 라운드 · 오브젝트)를 대화 기록과 같은 시간축에 함께 남깁니다. 나중에 게임 연동 탭에서 바꿀 수 있습니다." />
<GameCards showStatus={false} />
<div className="hint">롤은 채팅 OCR(화면 글자 읽기)도 함께 씁니다. 게임 옵션에서 채팅 타임스탬프를 켜고 '테두리 없음' 창 모드를 쓰면 정확합니다.</div>
<div className="hint">롤 채팅은 롤 클라이언트 API 로 받습니다 (챔피언 선택 · 게임 후 채팅). 화면 글자 인식(OCR)은 쓰지 않습니다.</div>
</>
);
}

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

@@ -106,6 +106,20 @@ test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은
assert.equal(frSt.activeBotToken(), null);
await assert.rejects(fr.adminAddUser(STRANGER, 'user'), /최고 관리자만/);
await assert.rejects(fr.adminUsers(), /관리자만/);
// 일반 유저도 관리자 아이디는 받는다 (따라갈 사람 목록 정렬). 유저 자신은 관리자가 아니다
const ids = await fr.adminIds();
assert.ok(ids.includes(SUPER) && !ids.includes(FRIEND));
await admin.adminSetRole(FRIEND, 'admin');
assert.ok((await fr.adminIds()).includes(FRIEND));
await admin.adminSetRole(FRIEND, 'user');
// 표시 이름 (실명 숨기기): 최고 관리자만 정하고, 정하면 서버가 저장한 이름 · 로그인 정보가 모두 그 이름이 된다
await assert.rejects(fr.adminSetDisplayName(FRIEND, '별명'), /최고 관리자만/);
assert.deepEqual((await admin.adminSetDisplayName(FRIEND, '별명')).names, { [FRIEND]: '별명' });
assert.deepEqual(await fr.displayNames(), { [FRIEND]: '별명' });
assert.equal((await fr.check()).user?.name, '별명');
const rows = (await admin.adminUsers()).users;
assert.equal(rows.find((u) => u.id === FRIEND)?.name, '별명');
assert.deepEqual((await admin.adminSetDisplayName(FRIEND, '')).names, {});
// 다시 켜도 (새 SettingsStore) 로그인 유지
assert.equal((await new AppAuth(s.settingsFor(dir), { version: '1.2.0', openUrl: () => undefined }).check()).status, 'ok');
// 봇 토큰은 이 PC 어디에도 저장되지 않는다 (테스트는 평문 codec 이라 secrets.bin 도 그대로 읽힌다)

View File

@@ -179,6 +179,8 @@ test('봇 중계: 로그인 안 한 연결은 막히고, 로그인한 앱은 봇
await a.gw.start();
assert.deepEqual(a.gw.me(), ME);
assert.deepEqual(a.gw.guilds().map((g) => g.id), [G, OTHER_G]);
// 지켜보기 전에도 (설정 창이 봇 연결 직후 바로 요청) 가입한 서버 멤버 목록을 받는다
assert.equal((await a.gw.members(G)).length, 3);
const g = await a.gw.watch(G, { commands: true });
assert.equal(g?.name, 'M&L');
await until(() => s.source.commands.includes(G));
@@ -302,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;
@@ -132,7 +208,7 @@ test('타임라인 조회: 필터·검색·커서', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const tl = new Timeline(store);
store.upsertUser({ id: 'u1', name: '승한', avatar: null });
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
const t0 = Date.UTC(2026, 9, 15, 12, 0, 0);
const texts = ['스모크 깔게 미드로 와', '레이즈 궁 빠졌어', '오퍼 사줘', '배고프다 치킨 먹자', 'B 사이트 로테 하자'];
@@ -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);
@@ -183,3 +259,75 @@ test('7일 지난 음성만 삭제, 텍스트는 남음', () => {
assert.equal(store.getUtterance('old')!.audio_deleted, 1);
store.close();
});
test('표시 이름: 정한 이름으로 유저 이름 · 지난 범인 분석의 이름을 바꾸고, 새로 들어온 이름에도 쓴다', () => {
const store = new Store(path.join(tmp(), 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '실명이', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
store.db.exec(`CREATE TABLE culprit_analyses (id TEXT PRIMARY KEY, match_id TEXT NOT NULL, created_at INTEGER NOT NULL, created_by TEXT NOT NULL, model TEXT NOT NULL, current INTEGER NOT NULL DEFAULT 1, result TEXT NOT NULL, meta TEXT NOT NULL DEFAULT '{}')`);
store.db
.prepare('INSERT INTO culprit_analyses(id,match_id,created_at,created_by,model,result) VALUES(?,?,?,?,?,?)')
.run('a1', 'm1', 1, JSON.stringify({ id: 'u1', name: '실명이 다른표기' }), 'x', JSON.stringify({ result: { summary: '실명이가 캐리' }, players: [{ name: '실명이' }, { name: '민수' }] }));
store.setDisplayNames({ u1: '별명' });
assert.equal(store.getUser('u1')?.name, '별명');
assert.equal(store.getUser('u2')?.name, '민수');
const r = store.db.prepare('SELECT created_by, result FROM culprit_analyses').get() as any;
assert.equal(JSON.parse(r.created_by).name, '별명');
assert.ok(!r.result.includes('실명이') && r.result.includes('별명가 캐리'), r.result);
// 디스코드에서 예전 이름이 다시 와도 표시 이름으로 저장, 다시 열어도 유지
store.upsertUser({ id: 'u1', name: '실명이', avatar: null });
assert.equal(store.getUser('u1')?.name, '별명');
const file = store.db.name;
store.close();
const again = new Store(file);
again.upsertUser({ id: 'u1', name: '실명이', avatar: null });
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('녹음 중에 들어온 사람: 유저로 저장하고 users.updated 를 보낸다 (중간 참여자 "알 수 없음" 버그)', async () => {
const { Bus } = await import('../src/core/util/events.ts');
const { Bot } = await import('../src/core/discord/bot.ts');
const store = new Store(path.join(tmp(), 'db.sqlite'));
const bus = new Bus();
bus.usersProvider = () => store.listUsers().map((u) => ({ id: u.id, name: u.name, color: u.color, avatar: u.avatar, excluded: false, riot: [] }));
const got: any[] = [];
bus.on('live', (e) => got.push(e));
const settings = () => ({ discord: { followEnabled: false, followUserId: null, ttsEnabled: false, ttsOnNewMember: false } }) as any;
const bot = new Bot(store, {} as any, {} as any, bus, settings);
const late = { id: '42', name: '늦게온사람', avatar: null, bot: false };
bot.gateway = { channelMembers: () => [late] } as any;
bot.state.guild = { id: 'g', name: 'g', icon: null };
bot.state.recording = { active: true, channel: '음성', channelId: 'vc', since: 1, participants: [], reason: 'command' };
await (bot as any).onVoiceState({ guildId: 'g', member: late, oldChannelId: null, newChannelId: 'vc', channel: { id: 'vc', name: '음성' } });
assert.equal(store.getUser('42')?.name, '늦게온사람');
const upd = got.filter((e) => e.type === 'users.updated');
assert.equal(upd.length, 1);
assert.ok(upd[0].data.some((u: any) => u.id === '42' && u.name === '늦게온사람'));
assert.deepEqual(bot.state.recording.participants, ['42']);
store.close();
});
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

@@ -53,11 +53,11 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
const input = ctx.culprit.buildInput(m);
const lines = input.text.split('\n');
assert.match(lines[0], /^# 경기 발로란트 .* 13:9 \(우리 팀 승리\) · 22라운드/);
// 우리 팀이 P1~P5, 승한은 음성O, 디스코드 계정이 없는 상대는 음성X
// 우리 팀이 P1~P5, 하늘은 음성O, 디스코드 계정이 없는 상대는 음성X
const p1 = lines.find((l) => l.startsWith('P1 '))!;
assert.match(p1, /^P1 승한 우리 제트\(타격대\) \d+\/\d+\/\d+ ACS\d+ ADR\d+ KAST\d+% 피해격차[+-]\d+ 첫킬\d+\/첫데스\d+ HS\d+% 설치\d+\/해체\d+ .*음성O$/);
// 기록 점수 (OP.GG OP스코어 방식): 10명 모두, 이긴 팀 1등 MVP · 진 팀 1등 ACE
const head = lines.findIndex((l) => l.startsWith('# 기록 점수 (0~10, OP.GG OP스코어 방식'));
assert.match(p1, /^P1 하늘 우리 제트\(타격대\) \d+\/\d+\/\d+ ACS\d+ ADR\d+ KAST\d+% 피해격차[+-]\d+ 첫킬\d+\/첫데스\d+ HS\d+% 설치\d+\/해체\d+ .*음성O$/);
// 기록 점수 (OP.GG OP스코어 계산법): 10명 모두, 이긴 팀 1등 MVP · 진 팀 1등 ACE
const head = lines.findIndex((l) => l.startsWith('# 기록 점수 (0~10, OP.GG OP스코어 계산법'));
assert.ok(head > 0, '기록 점수 칸');
const rl = lines.slice(head + 1, head + 11);
assert.ok(rl.every((l, i) => new RegExp(`^P${i + 1} \\d+\\.\\d점 \\d+위/팀\\d위`).test(l)), rl.join('\n'));
@@ -68,7 +68,6 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
assert.ok(rp.every((r) => r && r.score >= 0 && r.score <= 10 && !r.basic));
assert.deepEqual(rp.map((r) => r.rank).sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert.equal(rp.find((r) => r.rank === 1)!.score, Math.max(...rp.map((r) => r.score)));
assert.equal(input.lookup?.riotMatchId, 'demo');
assert.match(lines.find((l) => l.startsWith('P6 '))!, /상대 .*음성X$/);
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, true, '민수는 대화가 있다');
assert.equal(input.players.find((p) => p.id === 'P3')!.voice, false);
@@ -139,7 +138,7 @@ test('범인찾기: 롤 포지션 · 시야 · 10/15분 지표와 골드 차', (
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 킬 P\d+ → P\d+/);
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 내셔 남작 처치 우리 팀 · P2\n/);
// 기록 점수 + LOL.PS 라인전 점수의 입력 (10 · 15분 맞라이너와 차)
assert.match(input.text, /\n# 기록 점수 \(0~10, OP\.GG OP스코어 방식/);
assert.match(input.text, /\n# 기록 점수 \(0~10, OP\.GG OP스코어 계산법/);
assert.match(input.text, /\nP1 \d+\.\d점 \d+위\/팀\d위.* · 라인전\(vs P6\) 10분 CS[+-][\d,]+ 골드[+-][\d,]+ 경험치[+-][\d,]+ 15분 CS[+-][\d,]+ 골드[+-][\d,]+ 경험치[+-][\d,]+\n/);
const p1 = input.players.find((p) => p.id === 'P1')!;
const p6 = input.players.find((p) => p.id === 'P6')!;
@@ -147,7 +146,6 @@ test('범인찾기: 롤 포지션 · 시야 · 10/15분 지표와 골드 차', (
assert.equal(p1.rating!.lane!.at10!.xp, -p6.rating!.lane!.at10!.xp);
assert.ok(p1.rating!.lane!.at10!.cs !== undefined && p1.rating!.lane!.at15!.gold !== undefined);
assert.equal(input.players.filter((p) => p.rating?.badge).length, 2);
assert.equal(p1.tag !== undefined, true);
});
test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
@@ -178,7 +176,7 @@ test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
method: 'PUT',
url: `/api/culprit/internal/${id}/result`,
headers: { 'x-gvr-internal': '1' },
payload: { result, players: input.players, model: 'claude-opus-5-5', createdBy: { id: 'u1', name: '승한' }, meta: { costUsd: 0.41 } },
payload: { result, players: input.players, model: 'claude-opus-5-5', createdBy: { id: 'u1', name: '하늘' }, meta: { costUsd: 0.41 } },
});
assert.equal(put.statusCode, 200);
const info = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
@@ -196,11 +194,26 @@ test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
],
);
// 다시 분석하면 이전 결과는 기록으로 남는다
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result, players: input.players, model: 'm2', createdBy: { id: 'u1', name: '승한' }, meta: {} } });
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result, players: input.players, model: 'm2', createdBy: { id: 'u1', name: '하늘' }, meta: {} } });
const info2 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
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

@@ -38,7 +38,7 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
}
};
await wait(() => core.stt.status.slots.realtime.state === 'loaded', 60000, 'model load');
core.store.upsertUser({ id: 'u1', name: '승한', avatar: null });
core.store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
const fx = path.join(root, 'worker', 'tests', 'fixtures');
const items: [string, string][] = [
['speech', 'speech_ko.ogg'],
@@ -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

@@ -46,7 +46,7 @@ export function seedValorant(ctx: ReturnType<typeof setup>, opts: { sessionStart
const md = makeDemoValorant(VS);
const id = 'val-demo';
const users = [
{ id: 'u1', name: '승한', puuid: 'p-sh' },
{ id: 'u1', name: '하늘', puuid: 'p-sh' },
{ id: 'u2', name: '민수', puuid: 'p-ms' },
{ id: 'u9', name: '도윤', puuid: null },
];

View File

@@ -37,7 +37,7 @@ function loc() {
}
export const VAL_PLAYERS = [
{ subject: 'p-sh', gameName: '승한', tagLine: 'KR1', teamId: 'Blue', characterId: AGENT.jett },
{ subject: 'p-sh', gameName: '하늘', tagLine: 'KR1', teamId: 'Blue', characterId: AGENT.jett },
{ subject: 'p-ms', gameName: '민수', tagLine: '0707', teamId: 'Blue', characterId: AGENT.sova },
{ subject: 'p-jw', gameName: '지우', tagLine: 'KR2', teamId: 'Blue', characterId: AGENT.sage },
{ subject: 'p-hw', gameName: '현우', tagLine: 'HW1', teamId: 'Blue', characterId: AGENT.omen },
@@ -132,7 +132,7 @@ export function makeDemoValorant(gameStart: number) {
// ------------------------------------------------------------------ 롤
const LOL = [
{ pid: 1, champ: 103, team: 100, puuid: 'l-sh', name: '승한', tag: 'KR1' }, // 아리 미드
{ pid: 1, champ: 103, team: 100, puuid: 'l-sh', name: '하늘', tag: 'KR1' }, // 아리 미드
{ pid: 2, champ: 64, team: 100, puuid: 'l-ms', name: '민수', tag: '0707' }, // 리 신
{ pid: 3, champ: 86, team: 100, puuid: 'l-hw', name: '현우', tag: 'HW1' }, // 가렌
{ pid: 4, champ: 81, team: 100, puuid: 'l-jw', name: '지우', tag: 'KR2' }, // 이즈리얼

View File

@@ -8,7 +8,7 @@ const VANDAL = '9c82e19d-4575-0200-1a81-3eacf00cf872';
export function makeValDetails(gameStart: number) {
const players = [
{ subject: SELF, gameName: '승한', tagLine: 'KR1', teamId: 'Blue', characterId: JETT, competitiveTier: 15, stats: { score: 4200, roundsPlayed: 3, kills: 3, deaths: 1, assists: 1 } },
{ subject: SELF, gameName: '하늘', tagLine: 'KR1', teamId: 'Blue', characterId: JETT, competitiveTier: 15, stats: { score: 4200, roundsPlayed: 3, kills: 3, deaths: 1, assists: 1 } },
{ subject: 'ally-2', gameName: '민수', tagLine: 'KR1', teamId: 'Blue', characterId: SAGE, competitiveTier: 14, stats: { score: 1800, roundsPlayed: 3, kills: 1, deaths: 2, assists: 3 } },
{ subject: 'enemy-1', gameName: '상대1', tagLine: '0000', teamId: 'Red', characterId: REYNA, competitiveTier: 15, stats: { score: 3000, roundsPlayed: 3, kills: 2, deaths: 3, assists: 0 } },
];

103
app/test/game-saver.test.ts Normal file
View File

@@ -0,0 +1,103 @@
// v1.9.0: 게임 중 GPU 아끼기 (발로란트 + 브라우저 + 겜녹이를 같이 켜면 GPU 가 100% 가까이 차던 것)
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 } from '../src/core/db/db.ts';
import { Timeline } from '../src/core/timeline.ts';
import { Bus } from '../src/core/util/events.ts';
import { SttPipeline } from '../src/core/stt/pipeline.ts';
function setup(gameSaver = true) {
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-saver-'));
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
const t0 = Date.now() - 600000;
store.upsertMatch({ id: 'm1', game: 'valorant', started_at: t0, status: 'live' });
const mk = (id: string, at = Date.now()) => {
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: at, ended_at: at + 1000, audio_path: f, match_id: 'm1' });
};
const reqs: any[] = [];
const ops: string[] = [];
const worker: any = Object.assign(new EventEmitter(), {
ready: true,
request: async (op: string, req: any) => {
if (op === 'gpu_info') return { gpus: [{ vram_total_mb: 16303 }] }; // 두 모델을 같이 올릴 수 있는 카드
if (op === 'models') return { models: [{ name: 'rt', installed: true }, { name: 'pr', installed: true }] };
if (op === 'load' || op === 'unload') {
ops.push(`${op}:${req.slot}`);
return {};
}
reqs.push(req);
await new Promise((r) => setTimeout(r, 40));
return { text: '말', raw_text: '말', words: [], noise: false, noise_reason: null, confidence: 0.5, lufs: -30, gain_db: 0, speech_ratio: 1, duration_s: 1, model: req.slot, elapsed_ms: 40 };
},
});
const settings: any = () => ({
stt: { realtimeModel: 'rt', preciseModel: 'pr', device: 'cuda', computeType: 'float16', gameVramReserveMb: 3072, reprocessAfterMatch: true, gameSaver },
audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false },
});
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
stt.status.worker = 'ready';
const wait = async (fn: () => boolean, ms = 5000) => {
const t = Date.now();
while (!fn()) {
if (Date.now() - t > ms) throw new Error('timeout');
await new Promise((r) => setTimeout(r, 10));
}
};
return { store, stt, mk, reqs, ops, wait, t0 };
}
test('게임 중: 정밀 모델을 내리고, 새 발화는 실시간 모델 · 빔 1 로만, 발화 사이에 쉰다', async () => {
const s = setup();
await s.stt.prepareModels();
assert.equal(s.stt.status.slots.precise.state, 'loaded', '게임 밖에서는 두 모델 모두');
await s.stt.setGameActive(true);
assert.equal(s.stt.status.slots.precise.state, 'empty', '게임이 켜지면 정밀 모델을 내린다');
s.mk('a1');
s.mk('a2');
s.stt.enqueue('a1', 'realtime');
s.stt.enqueue('a2', 'realtime');
const t = Date.now();
await s.wait(() => s.reqs.length === 2 && !s.stt.status.processing);
assert.ok(Date.now() - t >= 75, '두 번째 발화 전에 앞 변환만큼 쉰다');
assert.deepEqual(s.reqs.map((r) => [r.slot, r.beam_size]), [['realtime', 1], ['realtime', 1]]);
});
test('경기가 끝나도 게임(메뉴)이 켜져 있으면 정밀 변환은 기다리고, 게임을 끄면 정밀 모델을 올려 한다', async () => {
const s = setup();
await s.stt.prepareModels();
await s.stt.setGameActive(true);
await s.stt.onMatchStart();
s.mk('b1', s.t0 + 1000);
s.stt.enqueue('b1', 'realtime');
await s.wait(() => s.store.getUtterance('b1')!.status === 'realtime');
await s.stt.onMatchEnd(s.t0, Date.now());
await new Promise((r) => setTimeout(r, 100));
assert.equal(s.reqs.length, 1, '게임이 켜져 있는 동안 정밀 변환 안 함');
assert.equal(s.stt.status.queue, 1);
assert.equal(s.stt.status.slots.precise.state, 'empty');
await s.stt.setGameActive(false);
await s.wait(() => s.store.getUtterance('b1')!.status === 'precise');
assert.equal(s.reqs[1].slot, 'precise');
assert.equal(s.reqs[1].beam_size, undefined, '게임 밖에서는 기본 빔');
});
test('게임 중 GPU 아끼기를 끄면 예전처럼 (정밀 모델 유지 · 기본 빔)', async () => {
const s = setup(false);
await s.stt.prepareModels();
await s.stt.setGameActive(true);
assert.equal(s.stt.status.slots.precise.state, 'loaded');
await s.stt.onMatchStart();
s.mk('c1');
s.stt.enqueue('c1', 'realtime');
await s.wait(() => s.reqs.length === 1);
assert.equal(s.reqs[0].beam_size, undefined);
});

View File

@@ -40,7 +40,7 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
const tl = new Timeline(store);
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
const sttCalls: string[] = [];
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end') };
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end'), setGameActive: async () => undefined };
const assets = new GameAssets(path.join(dir, 'cache'));
(assets as any).refresh = async () => undefined; // 네트워크 없이
assets.lol = {
@@ -50,7 +50,7 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
items: {},
};
const s = defaultSettings();
store.upsertUser({ id: 'owner', name: '승한', avatar: null });
store.upsertUser({ id: 'owner', name: '하늘', avatar: null });
const gm = new GameManager(store, assets, worker, stt, tl, bus, () => s, () => 'owner');
gm.start();
try {
@@ -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');
@@ -87,12 +95,19 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
mock.st.lolPhase = 'InProgress';
mock.st.lolLive = lolLiveData(120, [
{ EventID: 0, EventName: 'GameStart', EventTime: 0.05 },
{ EventID: 1, EventName: 'ChampionKill', EventTime: 75.2, KillerName: '승한', VictimName: '적1', Assisters: ['민수'] },
{ EventID: 1, EventName: 'ChampionKill', EventTime: 75.2, KillerName: '하늘', VictimName: '적1', Assisters: ['민수'] },
{ EventID: 2, EventName: 'DragonKill', EventTime: 90.0, KillerName: '민수', DragonType: 'Fire', Stolen: 'False' },
{ EventID: 3, EventName: 'TurretKilled', EventTime: 95.0, KillerName: '승한', TurretKilled: 'Turret_T2_R_03_A' },
{ EventID: 3, EventName: 'TurretKilled', EventTime: 95.0, KillerName: '하늘', TurretKilled: 'Turret_T2_R_03_A' },
]);
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);
});

331
app/test/history.test.ts Normal file
View File

@@ -0,0 +1,331 @@
// v1.9.0: 내 Riot 경기 기록 가져오기 (앱이 꺼져 있을 때 한 경기도 사이트 경기 탭에)
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 { startMockRiot } from './mock/riot.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-hist-'));
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function until(fn: () => boolean, ms = 10000, label = 'condition') {
const t = Date.now();
while (!fn()) {
if (Date.now() - t > ms) throw new Error(`timeout: ${label}`);
await sleep(50);
}
}
test('경기 기록: 발로란트 · 롤 기록을 가져와 history 경기로 저장, 필터 · 타임라인 · 다시 훑기', async () => {
const dir = tmp();
const mock = await startMockRiot(path.join(dir, 'mock'));
Object.assign(process.env, {
GVR_RIOT_LOCKFILE: mock.lockfile,
GVR_LCU_LOCKFILE: mock.lockfile,
GVR_VAL_GLZ: mock.base,
GVR_VAL_PD: mock.base,
GVR_LOL_LIVE_URL: mock.base,
GVR_POLL_MS: '150',
GVR_HISTORY_EVERY_MS: '400',
GVR_HISTORY_GAP_MS: '5',
});
const { Store } = await import('../src/core/db/db.ts');
const { Timeline } = await import('../src/core/timeline.ts');
const { GameAssets } = await import('../src/core/games/assets.ts');
const { GameManager } = await import('../src/core/games/manager.ts');
const { Bus } = await import('../src/core/util/events.ts');
const { defaultSettings } = await import('../src/core/settings.ts');
const store = new Store(path.join(dir, 'db.sqlite'));
const tl = new Timeline(store);
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
const stt: any = { onMatchStart: async () => undefined, onMatchEnd: async () => undefined, setGameActive: async () => undefined };
const assets = new GameAssets(path.join(dir, 'cache'));
(assets as any).refresh = async () => undefined;
const s = defaultSettings();
store.upsertUser({ id: 'owner', name: '하늘', avatar: null });
const H = Date.now() - 30 * 86400000;
// 발로란트 23경기 (두 쪽): 하나는 앱이 이미 잡은 경기, 하나는 상세가 없는 경기
mock.st.valHistory = Array.from({ length: 23 }, (_, i) => ({ MatchID: i === 5 ? 'gone-5' : `h-${i}`, GameStartTime: H - i * 3600000 }));
store.upsertMatch({ id: 'val-h-0', game: 'valorant', started_at: H, status: 'complete' });
// 앱이 녹음하던 때 잡지 못한 경기: 그 시간 발화가 경기에 붙는다
store.insertUtterance({ id: 'u1', session_id: null, user_id: 'owner', started_at: H - 3600000 + 60000, ended_at: H - 3600000 + 62000, audio_path: null, match_id: null });
mock.st.lolHistoryList = [
{ gameId: 9001, gameCreation: H - 100000 },
{ gameId: 9002, gameCreation: H - 200000 },
];
const gm = new GameManager(store, assets, worker, stt, tl, bus(), () => s, () => 'owner');
function bus() {
return new Bus();
}
gm.start();
try {
await until(() => !!store.getMatch('val-h-22') && store.getMatch('val-h-22')!.status === 'complete', 15000, 'val history');
await until(() => !!store.getMatch('lol-9002') && store.getMatch('lol-9002')!.status === 'complete', 15000, 'lol history');
const vals = store.listMatches({ game: 'valorant', limit: 100 });
assert.equal(vals.length, 22, '23경기 중 상세 없는 1경기 빼고');
assert.equal(store.getMatch('val-h-0')!.source, 'live', '앱이 잡은 경기는 그대로');
const h1 = store.getMatch('val-h-1')!;
assert.equal(h1.source, 'history');
assert.equal(h1.started_at, H - 3600000);
assert.ok(store.events('val-h-1').some((e) => e.type === 'kill'), '킬 기록도 (경기 화면용)');
assert.equal(store.getUtterance('u1')!.match_id, 'val-h-1', '그 시간 발화가 붙는다');
assert.equal(store.getMatch('lol-9001')!.source, 'history');
assert.ok(!store.getMatch('val-gone-5'));
assert.ok(JSON.parse(store.meta('history_skip:valorant')!).includes('val-gone-5'));
// 필터
const ids = (has?: 'timeline' | 'voice') => store.listMatches({ limit: 100, has }).map((m) => m.id).sort();
assert.equal(ids().length, 24);
assert.deepEqual(ids('timeline'), ['val-h-0', 'val-h-1'], '타임라인: 앱이 잡은 경기 + 대화가 붙은 기록 경기');
store.updateUtteranceResult('u1', { text: '가자', raw_text: '가자', words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'm', status: 'precise' });
assert.deepEqual(ids('voice'), ['val-h-1']);
const sum = gm.summary(store.getMatch('val-h-2')!);
assert.equal(sum.source, 'history');
assert.equal(sum.voice, false);
assert.equal(gm.summary(store.getMatch('val-h-1')!).voice, true);
// 타임라인: 녹음 없는 기록 경기의 이벤트는 빼고, 그 경기를 고르면 보인다
const page = tl.query({ limit: 500 });
const evMatches = new Set(page.items.filter((it: any) => it.kind === 'event').map((it: any) => it.matchId));
assert.ok(!evMatches.has('val-h-2') && !evMatches.has('lol-9001'));
assert.ok(evMatches.has('val-h-1'), '대화가 붙은 기록 경기는 타임라인에');
assert.ok(tl.query({ match: 'val-h-2', limit: 50 }).items.length > 0);
// 다시 훑기: 한 번 끝까지 본 뒤에는 첫 쪽만 (새 경기 1개)
const before = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length;
mock.st.valHistory.unshift({ MatchID: 'h-new', GameStartTime: Date.now() - 3600000 });
await until(() => store.getMatch('val-h-new')?.status === 'complete', 10000, 'new match');
await sleep(100);
const pages = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length - before;
assert.ok(pages >= 1 && pages <= 3, `다시 훑을 때는 첫 쪽만 (${pages})`);
// 경기 중에는 가져오지 않는다
mock.st.valState = 'INGAME';
await until(() => gm.status().valorant.inMatch, 5000, 'in match');
const n = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length;
await sleep(1200);
assert.equal(mock.st.hits.filter((h) => h.startsWith('/match-history/')).length, n);
} finally {
gm.stop();
await mock.close();
store.close();
for (const k of ['GVR_HISTORY_EVERY_MS', 'GVR_HISTORY_GAP_MS']) delete process.env[k];
}
});
test('경기 기록: 진행 상황 (목록 확인 → 경기 받기 · 남은 시간) · 취소하면 멈추고 다음에 이어서', async () => {
const dir = tmp();
const { Store } = await import('../src/core/db/db.ts');
const { HistorySync } = await import('../src/core/games/history.ts');
const store = new Store(path.join(dir, 'db.sqlite'));
const all = Array.from({ length: 30 }, (_, i) => `val-p-${i}`);
let gate: (() => void) | null = null;
const fetched: string[] = [];
const src = {
game: 'valorant' as const,
idle: () => true,
account: () => 'me',
page: async (start: number, n: number) => {
// 첫 쪽은 화면에서 목록 확인 중을 볼 수 있게 잠깐 멈춘다
if (start === 0) await new Promise<void>((r) => (gate = r));
return { ids: all.slice(start, start + n), total: all.length };
},
fetch: async (id: string) => {
await sleep(15);
store.upsertMatch({ id, game: 'valorant', started_at: Date.now(), status: 'complete' });
fetched.push(id);
return 'ok' as const;
},
};
const h = new HistorySync(store, src, { pageSize: 10, max: 500, gapMs: 5 });
try {
assert.equal(h.progress(), null, '가져오는 중이 아니면 없음');
assert.deepEqual(h.cancel(), { cancelled: false, resumeAt: null }, '돌지 않을 때 취소는 아무 일 없음');
h.maybeRun(60000, 0);
await until(() => !!gate, 2000, 'scan start');
const s0 = h.progress()!;
assert.equal(s0.phase, 'scan');
assert.equal(s0.first, true, '처음 끝까지 훑는 중');
assert.equal(s0.etaMs, null);
gate!();
await until(() => h.progress()?.phase === 'fetch' && h.progress()!.done >= 5, 5000, 'fetching');
const p = h.progress()!;
assert.equal(p.total, 30);
assert.equal(p.scanned, 30);
assert.ok(p.etaMs !== null && p.etaMs > 0 && p.etaMs < 10000, `남은 시간 (${p.etaMs})`);
// 취소: 진행 상황은 바로 사라지고, 루프는 다음 경기 전에 멈춘다
const c = h.cancel();
assert.equal(c.cancelled, true);
assert.ok(c.resumeAt && c.resumeAt > Date.now() + 50000, '다음 주기에 이어서');
assert.equal(h.progress(), null);
const n = fetched.length;
await sleep(150);
assert.ok(fetched.length <= n + 1, `취소 뒤 더 받지 않음 (${n} → ${fetched.length})`);
assert.ok(fetched.length < 30);
assert.ok(!store.meta('history_full:valorant:me'), '끝까지 받지 않았으니 다음에도 끝까지 훑는다');
// 다음 실행: 받은 경기는 건너뛰고 남은 것만
gate = null;
const run = h.run();
await until(() => !!gate, 2000, 'scan 2');
gate!();
const before = fetched.length;
await run;
assert.equal(fetched.length, 30, '남은 것부터 끝까지');
assert.equal(new Set(fetched).size, 30, '같은 경기를 두 번 받지 않음');
assert.ok(fetched.length - before === 30 - before);
assert.equal(store.meta('history_full:valorant:me'), '1');
assert.equal(h.progress(), null, '끝나면 진행 상황 없음');
} finally {
store.close();
}
});
test('경기 기록: 진행 상황은 지금 게임 상태(games.state)로 나가고, 사이트에서 POST /api/games/history/cancel 로 취소', async () => {
const dir = tmp();
const { Store } = await import('../src/core/db/db.ts');
const { Timeline } = await import('../src/core/timeline.ts');
const { GameAssets } = await import('../src/core/games/assets.ts');
const { GameManager } = await import('../src/core/games/manager.ts');
const { Bus } = await import('../src/core/util/events.ts');
const { buildApi } = await import('../src/core/api/server.ts');
const { defaultSettings } = await import('../src/core/settings.ts');
const { historyStatus, fmtEta } = await import('@gvr/shared');
const store = new Store(path.join(dir, 'db.sqlite'));
const bus = new Bus();
const sent: any[] = [];
bus.on('live', (e) => sent.push(e));
const s = defaultSettings();
const stt: any = { setGameActive: async () => undefined };
const gm = new GameManager(store, new GameAssets(path.join(dir, 'cache')), Object.assign(new EventEmitter(), { request: async () => ({}) }) as any, stt, new Timeline(store), bus, () => s, () => null);
// 롤만 가져오는 중
let lolRunning = true;
const fake = (game: 'valorant' | 'lol') => ({
progress: () => (game === 'lol' && lolRunning ? { phase: 'fetch', first: true, scanned: 40, done: 10, total: 40, startedAt: Date.now() - 20000, etaMs: 60000 } : null),
cancel: () => {
if (game !== 'lol' || !lolRunning) return { cancelled: false, resumeAt: null };
lolRunning = false;
return { cancelled: true, resumeAt: Date.now() + 30 * 60000 };
},
});
for (const a of gm.adapters) (a as any).history = fake(a.game);
const app = await buildApi({
store,
timeline: new Timeline(store),
games: gm,
dict: {} as any,
culprit: {} as any,
bus,
settings: () => s,
trainingDir: () => dir,
overviewExtra: () => ({ guild: null, recording: {} as any }),
version: 'test',
});
try {
const lol = gm.live().find((g) => g.game === 'lol')!;
assert.equal(lol.history?.done, 10);
assert.equal(gm.live().find((g) => g.game === 'valorant')!.history, null);
assert.deepEqual(historyStatus(lol.history!), { title: '경기 기록 가져오는 중', detail: '10 / 40경기 (25%) · 약 1분 남음', pct: 25 });
assert.equal(historyStatus({ ...lol.history!, phase: 'scan', total: 3 }).pct, null, '목록 확인 중에는 얼마나 걸릴지 모름');
assert.equal(fmtEta(null), '남은 시간 계산 중');
assert.equal(fmtEta(25000), '30초 남음');
assert.equal(fmtEta(2 * 3600000 + 5 * 60000), '약 2시간 5분 남음');
const member = { 'x-gvr-user': encodeURIComponent(JSON.stringify({ id: 'm1', name: 'm1', avatar: null })), 'x-gvr-role': 'member' };
const r = await app.inject({ method: 'POST', url: '/api/games/history/cancel', headers: member, payload: { game: 'lol' } });
assert.equal(r.statusCode, 200);
const b = r.json();
assert.deepEqual(b.cancelled, ['lol'], '서버 멤버 누구나 취소 (다음 주기에 이어서 하니 지워지는 것 없음)');
assert.ok(b.resumeAt > Date.now());
const st = sent.filter((e) => e.type === 'games.state').at(-1);
assert.ok(st, '취소하면 바로 게임 상태를 보낸다');
assert.equal(st.data.find((g: any) => g.game === 'lol').history, null);
const again = await app.inject({ method: 'POST', url: '/api/games/history/cancel', payload: {} });
assert.deepEqual(again.json().cancelled, [], '이미 멈췄으면 아무 일 없음');
} finally {
await app.close();
store.close();
}
});
test('경기 기록: 끝까지 훑은 계정에서 새 경기를 받다가 취소해도, 다음 실행이 남은 경기를 모두 받는다 · 취소 뒤 한 주기 동안은 다시 시작하지 않는다', async () => {
const dir = tmp();
const { Store } = await import('../src/core/db/db.ts');
const { HistorySync } = await import('../src/core/games/history.ts');
const store = new Store(path.join(dir, 'db.sqlite'));
// 예전 경기 20개는 이미 받았고 끝까지 훑은 계정
const old = Array.from({ length: 20 }, (_, i) => `val-old-${i}`);
for (const id of old) store.upsertMatch({ id, game: 'valorant', started_at: 1, status: 'complete' });
store.setMeta('history_full:valorant:me', '1');
// 새 경기 30개 (새것부터 = 목록 앞쪽)
const fresh = Array.from({ length: 30 }, (_, i) => `val-new-${i}`);
const all = [...fresh, ...old];
const fetched: string[] = [];
let pages = 0;
let h!: InstanceType<typeof HistorySync>;
const src = {
game: 'valorant' as const,
idle: () => true,
account: () => 'me',
page: async (start: number, n: number) => {
pages++;
return { ids: all.slice(start, start + n), total: all.length };
},
fetch: async (id: string) => {
await sleep(5);
store.upsertMatch({ id, game: 'valorant', started_at: 2, status: 'complete' });
fetched.push(id);
// 첫 쪽 10경기를 받은 뒤 취소
if (fetched.length === 10) h.cancel();
return 'ok' as const;
},
};
h = new HistorySync(store, src, { pageSize: 10, max: 500, gapMs: 1 });
try {
assert.equal(await h.run(), 10);
assert.equal(fetched.length, 10);
assert.equal(store.meta('history_pending:valorant:me'), '1', '받다가 멈춤');
// 다음 실행: 첫 쪽은 다 아는 경기지만 멈추지 않고 끝까지 훑어 남은 20경기를 받는다
assert.equal(await h.run(), 20, '남은 경기 모두');
assert.deepEqual([...fetched].sort(), [...fresh].sort());
assert.ok(!store.meta('history_pending:valorant:me'), '다 받았으면 표시를 지운다');
// 그다음부터는 다시 첫 쪽만
pages = 0;
assert.equal(await h.run(), 0);
assert.equal(pages, 1, '아는 경기만 나오는 첫 쪽에서 멈춤');
// 취소한 때부터 한 주기 뒤에 이어서: 오래(주기보다 길게) 돈 실행을 취소해도 바로 다시 시작하지 않는다
const every = 60000;
fetched.length = 0;
all.unshift(...Array.from({ length: 15 }, (_, i) => `val-more-${i}`));
let gate!: () => void;
const slowFetch = src.fetch;
src.fetch = async (id: string) => {
await new Promise<void>((r) => (gate = r));
return slowFetch(id);
};
// 위에서 취소한 때부터 한 주기가 지나지 않았으니 maybeRun 은 아직 돌지 않는다
h.maybeRun(every, 0);
assert.equal((h as any).running, false, '취소 뒤 한 주기 안에는 다시 시작하지 않음');
(h as any).lastAt = 0;
h.maybeRun(every, 0);
await until(() => h.progress()?.phase === 'fetch', 2000, 'fetch start');
(h as any).lastAt -= 2 * every; // 두 주기 넘게 돈 것처럼
const c = h.cancel();
assert.equal(c.cancelled, true);
assert.ok(c.resumeAt! >= Date.now() + every - 1000, `취소한 때부터 한 주기 뒤 (${c.resumeAt! - Date.now()}ms)`);
gate();
await until(() => !(h as any).running, 2000, 'stopped');
pages = 0;
h.maybeRun(every, 0);
await sleep(50);
assert.equal(pages, 0, '다음 확인에서 바로 다시 시작하지 않음');
assert.equal(h.progress(), null);
} finally {
store.close();
}
});

View File

@@ -18,6 +18,12 @@ export interface MockState {
lolGameId: number;
lolHistoryReady: boolean;
lolStart: number;
/** 발로란트 경기 기록 (새것부터): MatchID → 경기 시작 시각 */
valHistory: { MatchID: string; GameStartTime: number }[];
/** 롤 경기 기록 (LCU, 새것부터) */
lolHistoryList: { gameId: number; gameCreation: number }[];
/** 요청 기록 (경로) */
hits: string[];
}
export async function startMockRiot(dir: string) {
@@ -38,6 +44,9 @@ export async function startMockRiot(dir: string) {
lolGameId: 7001,
lolHistoryReady: false,
lolStart: 0,
valHistory: [],
lolHistoryList: [],
hits: [],
};
const password = 'pw-test';
const presence = () => {
@@ -52,7 +61,7 @@ export async function startMockRiot(dir: string) {
};
return Buffer.from(JSON.stringify(priv)).toString('base64');
};
const routes: [RegExp, (m: RegExpMatchArray, auth: string) => [number, any]][] = [
const routes: [RegExp, (m: RegExpMatchArray, auth: string, url: URL) => [number, any]][] = [
// ---- Riot Client local
[/^\/entitlements\/v1\/token$/, () => [200, { accessToken: 'acc-token', token: 'ent-token', subject: SELF, issuer: 'x' }]],
[
@@ -61,6 +70,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' }])],
[
@@ -68,17 +78,49 @@ export async function startMockRiot(dir: string) {
() => [200, { MatchID: st.valMatchId, MapID: ASCENT, Players: [{ Subject: SELF, TeamID: 'Blue', CharacterID: 'add6443a-41bd-e414-f6ad-e58d267f4e95' }] }],
],
// ---- pd
[/^\/match-details\/v1\/matches\/(.+)$/, (_m, auth) => (auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}])],
[
/^\/match-history\/v1\/history\/(.+)$/,
(_m, auth, url) => {
if (!auth.startsWith('Bearer ')) return [401, {}];
const s = Number(url.searchParams.get('startIndex') ?? 0);
const e = Number(url.searchParams.get('endIndex') ?? 20);
return [200, { Subject: SELF, BeginIndex: s, EndIndex: e, Total: st.valHistory.length, History: st.valHistory.slice(s, e).map((h) => ({ ...h, QueueID: 'competitive' })) }];
},
],
[
/^\/match-details\/v1\/matches\/(.+)$/,
(m, auth) => {
const h = st.valHistory.find((x) => x.MatchID === m[1]);
if (h) return m[1].startsWith('gone') ? [404, {}] : [200, { ...makeValDetails(h.GameStartTime), matchInfo: { ...makeValDetails(h.GameStartTime).matchInfo, matchId: h.MatchID } }];
return auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}];
},
],
// ---- LoL Live Client Data
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
// ---- LCU
[/^\/lol-gameflow\/v1\/gameflow-phase$/, () => [200, st.lolPhase]],
[/^\/lol-gameflow\/v1\/session$/, () => [200, { phase: st.lolPhase, gameData: { gameId: st.lolGameId, queue: { description: '솔로 랭크', id: 420 } } }]],
[/^\/lol-summoner\/v1\/current-summoner$/, () => [200, { puuid: 'lol-self', gameName: '승한', tagLine: 'KR1' }]],
[/^\/lol-summoner\/v1\/current-summoner$/, () => [200, { puuid: 'lol-self', gameName: '하늘', tagLine: 'KR1' }]],
[/^\/lol-chat\/v1\/conversations$/, () => [200, st.lolPhase === 'ChampSelect' ? [{ id: 'cs1@champ-select.kr', type: 'championSelect' }] : []]],
[/^\/lol-chat\/v1\/conversations\/(.+)\/messages$/, () => [200, [{ id: 'msg1', body: '정글 갱 갈게요', fromSummonerId: 11, timestamp: new Date(Date.now() - 5000).toISOString(), type: 'groupchat' }]]],
[/^\/lol-summoner\/v1\/summoners\/(\d+)$/, () => [200, { gameName: '민수' }]],
[/^\/lol-match-history\/v1\/games\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolHistory()] : [404, {}])],
[
/^\/lol-match-history\/v1\/products\/lol\/current-summoner\/matches$/,
(_m, _a, url) => {
const s = Number(url.searchParams.get('begIndex') ?? 0);
const e = Number(url.searchParams.get('endIndex') ?? 20);
const games = st.lolHistoryList.slice(s, e);
return [200, { games: { gameCount: games.length, gameIndexBegin: s, gameIndexEnd: e, games } }];
},
],
[
/^\/lol-match-history\/v1\/games\/(\d+)$/,
(m) => {
const h = st.lolHistoryList.find((x) => String(x.gameId) === m[1]);
if (h) return [200, { ...lolHistory(), gameId: h.gameId, gameCreation: h.gameCreation }];
return st.lolHistoryReady ? [200, lolHistory()] : [404, {}];
},
],
[/^\/lol-match-history\/v1\/game-timelines\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolTimeline()] : [404, {}])],
];
const server = https.createServer({ key: fs.readFileSync(key), cert: fs.readFileSync(cert) }, (req, res) => {
@@ -86,7 +128,8 @@ export async function startMockRiot(dir: string) {
for (const [re, fn] of routes) {
const m = url.pathname.match(re);
if (!m) continue;
const [code, body] = fn(m, String(req.headers.authorization || ''));
st.hits.push(url.pathname);
const [code, body] = fn(m, String(req.headers.authorization || ''), url);
res.writeHead(code, { 'content-type': 'application/json' });
res.end(JSON.stringify(body));
return;
@@ -115,8 +158,8 @@ export function lolLiveData(gameTime: number, events: any[]) {
items: [{ itemID: 3031, displayName: '무한의 대검', count: 1 }],
});
return {
activePlayer: { riotId: '승한#KR1', summonerName: '승한', currentGold: 500 },
allPlayers: [player('승한', 'Ahri', '아리', 'ORDER', 3), player('민수', 'LeeSin', '리 신', 'ORDER', 1), player('적1', 'Garen', '가렌', 'CHAOS', 2)],
activePlayer: { riotId: '하늘#KR1', summonerName: '하늘', currentGold: 500 },
allPlayers: [player('하늘', 'Ahri', '아리', 'ORDER', 3), player('민수', 'LeeSin', '리 신', 'ORDER', 1), player('적1', 'Garen', '가렌', 'CHAOS', 2)],
events: { Events: events },
gameData: { gameMode: 'CLASSIC', gameTime, mapName: 'Map11', mapNumber: 11 },
};
@@ -133,7 +176,7 @@ function lolHistory() {
{ participantId: 6, championId: 86, teamId: 200, stats: { kills: 4, deaths: 6, assists: 2, totalMinionsKilled: 170, neutralMinionsKilled: 0, goldEarned: 8500, win: false } },
],
participantIdentities: [
{ participantId: 1, player: { puuid: 'lol-self', gameName: '승한', tagLine: 'KR1' } },
{ participantId: 1, player: { puuid: 'lol-self', gameName: '하늘', tagLine: 'KR1' } },
{ participantId: 2, player: { puuid: 'lol-2', gameName: '민수', tagLine: 'KR1' } },
{ participantId: 6, player: { puuid: 'lol-6', gameName: '적1', tagLine: 'KR9' } },
],

113
app/test/name-echo.test.ts Normal file
View File

@@ -0,0 +1,113 @@
// v1.4.3: 상대 닉네임("QQQWWWQQQ")을 핫워드로 넣었더니 말소리를 "QQQWWWQ" 로 적던 문제
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 } from '../src/core/db/db.ts';
import { Timeline } from '../src/core/timeline.ts';
import { Bus } from '../src/core/util/events.ts';
import { SttPipeline, isNameEcho } from '../src/core/stt/pipeline.ts';
const NAMES = ['QQQWWWQQQ', '노곤노곤탐방가', '하늘 별'];
test('선수 이름 되풀이 판정: 이름(조각)만 있으면 되풀이, 실제 말이 붙으면 아님 (워커 is_name_echo 와 같은 기준)', () => {
for (const t of ['QQQWWWQ', ' QQQWWWQ.', 'qqqwwwqqq', 'QQQWWWQ QQQWWWQ', '노곤노곤탐방가', '하늘 별']) assert.ok(isNameEcho(t, NAMES), t);
for (const t of ['QQQ 잡았다', '노곤노곤탐방가 죽였어', '아이고, 점프티... 아, 갔다.', 'Q', '', null]) assert.ok(!isNameEcho(t, NAMES), String(t));
assert.ok(!isNameEcho('QQQWWWQ', []));
});
function setup() {
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-echo-'));
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '안정우', avatar: null });
const players = [
{ name: 'QQQWWWQQQ', character: { name: '제트' } },
{ name: '노곤노곤탐방가', character: { name: '레이즈' } },
{ name: 'Sky', character: { name: '세이지' } },
];
store.upsertMatch({ id: 'm1', game: 'valorant', started_at: Date.now() - 60000, status: 'ended', detail: JSON.stringify({ players }) });
const mk = (id: string, text: string | null) => {
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: 'm1' });
if (text !== null)
store.updateUtteranceResult(id, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.4, lufs: -30, gain_db: 0, model: 'm', status: 'precise' });
return f;
};
const reqs: any[] = [];
const results: Record<string, any> = {};
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 {};
reqs.push(req);
const id = path.basename(req.path, '.ogg');
return { text: '말', raw_text: '말', 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, ...results[id] };
},
});
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: (_ctx: string, extra: string[] = []) => [...extra, '로테'].join(' '), corrections: () => [], candidates: () => [] };
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
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));
}
};
return { store, stt, mk, reqs, results, wait };
}
test('핫워드: 선수 이름은 한글이 들어간 것만 넣고, 그 이름을 워커에 되풀이 확인용으로 넘긴다', async () => {
const s = setup();
await s.stt.load('realtime', 'm');
s.mk('a1', null);
s.stt.enqueue('a1', 'realtime');
await s.wait(() => s.store.getUtterance('a1')!.status !== 'pending');
const hw: string[] = s.reqs[0].hotwords.split(' ');
assert.ok(hw.includes('제트') && hw.includes('레이즈') && hw.includes('세이지'), '요원 이름은 그대로');
assert.ok(hw.includes('노곤노곤탐방가'));
assert.ok(!hw.includes('QQQWWWQQQ') && !hw.includes('Sky'), '한글 없는 닉네임은 핫워드에 넣지 않는다');
assert.deepEqual(s.reqs[0].player_names, ['노곤노곤탐방가']);
});
test('예전 발화 다시 보기 (한 번만): 이름을 잘못 적은 발화는 정밀 모델로 다시 변환, 음성 파일이 없으면 숨김, 고친 발화 · 실제 말은 그대로', async () => {
const s = setup();
const fRedo = s.mk('e1', 'QQQWWWQ');
s.mk('e2', 'QQQWWWQ');
s.store.markAudioDeleted('e2');
s.mk('e3', '아이고, 점프티... 아, 갔다.');
s.mk('e4', 'QQQWWWQ');
s.store.db.prepare('UPDATE utterances SET corrected=1 WHERE id=?').run('e4');
const fFixed = s.mk('e5', 'QQQWWWQ');
// e1: 다시 들어 보니 말소리가 아니었다 → 잡음으로 숨기고 파일 삭제. e5: 다시 들어 보니 실제 말
s.results.e1 = { text: null, raw_text: null, noise: true, noise_reason: 'vad' };
s.results.e5 = { text: '아 갔다', raw_text: '아 갔다' };
await s.stt.load('precise', 'm');
s.stt.resumePending();
await s.wait(() => s.reqs.length >= 2 && !s.stt.status.processing && s.stt.status.queue === 0);
assert.deepEqual(s.reqs.map((r) => path.basename(r.path, '.ogg')).sort(), ['e1', 'e5'], '정밀 모델로 이미 변환한 발화도 다시 변환');
assert.equal(s.reqs[0].slot, 'precise');
const e1 = s.store.getUtterance('e1')!;
assert.equal(e1.noise, 1);
assert.equal(e1.text, null);
assert.ok(!fs.existsSync(fRedo));
const e2 = s.store.getUtterance('e2')!;
assert.equal(e2.noise, 1);
assert.equal(e2.noise_reason, 'name_echo');
assert.equal(e2.text, null);
assert.equal(s.store.getUtterance('e3')!.text, '아이고, 점프티... 아, 갔다.');
assert.equal(s.store.getUtterance('e4')!.text, 'QQQWWWQ', '사람이 고친 발화는 그대로');
assert.equal(s.store.getUtterance('e5')!.text, '아 갔다');
assert.ok(fs.existsSync(fFixed));
// 두 번째 시작에서는 다시 보지 않는다
s.mk('e6', 'QQQWWWQ');
s.stt.resumePending();
await new Promise((r) => setTimeout(r, 50));
assert.equal(s.reqs.length, 2);
});

184
app/test/replays.test.ts Normal file
View File

@@ -0,0 +1,184 @@
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 zlib from 'node:zlib';
import WebSocket from 'ws';
import { Store } 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 { Replays } from '../src/core/replays.ts';
import { RelayClient } from '../src/core/relay/client.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-replay-'));
const ID = '4145f041-7d83-4785-ac4b-b532154f14a4';
const ID2 = '0e1f2a3b-0000-4000-8000-000000000002';
/** 가짜 변환기: 호출 횟수를 세고, 모드 파일에 따라 성공 · 실패 · 느림 */
function fakeTool(dir: string): { tool: string; calls: () => number; mode: (m: 'ok' | 'fail' | 'slow') => void } {
const tool = path.join(dir, 'gvr-replay');
const count = path.join(dir, 'calls');
const modeFile = path.join(dir, 'mode');
fs.writeFileSync(modeFile, 'ok');
fs.writeFileSync(
tool,
`#!/bin/sh
echo x >> "${count}"
mode=$(cat "${modeFile}")
if [ "$mode" = fail ]; then echo '{"ok":false,"error":"InvalidDataException: bad chunk"}'; exit 1; fi
if [ "$mode" = slow ]; then sleep 2; fi
printf '{"format":"gvr-replay","v":1,"matchId":"%s","players":[]}' "$(basename "$1" .vrf)" > "$2"
echo '{"ok":true,"map":"/Game/Maps/Infinity/Infinity","players":10,"rounds":20,"kills":146}'
`,
{ mode: 0o755 },
);
return { tool, calls: () => (fs.existsSync(count) ? fs.readFileSync(count, 'utf8').split('\n').filter(Boolean).length : 0), mode: (m) => fs.writeFileSync(modeFile, m) };
}
function setup(waitMs = 15000) {
const dir = tmp();
const saved = path.join(dir, 'VALORANT', 'Saved');
const demos = path.join(saved, 'Demos');
fs.mkdirSync(demos, { recursive: true });
const t = fakeTool(dir);
const replays = new Replays({ dirs: () => [saved], tool: t.tool, cacheDir: () => path.join(dir, 'GVR-Data', 'replays'), version: '1.5.0', waitMs });
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertMatch({ id: `val-${ID}`, game: 'valorant', started_at: Date.now() - 3600000 });
store.upsertMatch({ id: `val-${ID2}`, game: 'valorant', started_at: Date.now() - 7200000 });
store.upsertMatch({ id: 'lol-KR_1', game: 'lol', started_at: Date.now() - 7200000 });
return { dir, saved, demos, replays, store, ...t };
}
const api = (s: ReturnType<typeof setup>) =>
buildApi({
store: s.store,
timeline: new Timeline(s.store),
games: {} as any,
dict: {} as any,
culprit: {} as any,
bus: new Bus(),
settings: () => ({}) as any,
trainingDir: () => path.join(s.dir, 'training'),
overviewExtra: () => ({ guild: null, recording: {} as any }),
version: 'test',
replays: s.replays,
});
test('리플레이 찾기: Saved 아래 <경기 ID>.vrf (하위 폴더 포함), 로그 폴더 · 이름이 다른 파일은 무시', () => {
const s = setup();
fs.writeFileSync(path.join(s.demos, `${ID.toUpperCase()}.vrf`), 'a');
fs.mkdirSync(path.join(s.demos, 'old'), { recursive: true });
fs.writeFileSync(path.join(s.demos, 'old', `${ID2}.vrf`), 'b');
fs.writeFileSync(path.join(s.demos, 'notes.vrf'), 'c');
fs.mkdirSync(path.join(s.saved, 'Logs'), { recursive: true });
fs.writeFileSync(path.join(s.saved, 'Logs', '11111111-1111-4111-8111-111111111111.vrf'), 'd');
const ids = s.replays.list().map((r) => r.matchId);
assert.deepEqual(ids.sort(), [ID, ID2].sort());
assert.equal(s.replays.find(ID.toUpperCase())?.matchId, ID);
});
test('3D 리플레이 API: 처음 열면 변환해서 gzip JSON, 다음부터는 보관본 (변환 한 번)', async () => {
const s = setup();
const app = await api(s);
const miss = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(miss.statusCode, 404);
assert.equal(miss.json().error, 'replay_not_found');
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
const r = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(r.statusCode, 200);
assert.equal(r.headers['content-encoding'], 'gzip');
assert.match(String(r.headers['content-type']), /application\/json/);
const body = JSON.parse(zlib.gunzipSync(r.rawPayload).toString('utf8'));
assert.equal(body.format, 'gvr-replay');
assert.equal(body.matchId, ID);
const again = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(again.statusCode, 200);
assert.equal(s.calls(), 1, '두 번째는 변환하지 않는다');
// 목록: 경기 기록과 변환 여부
const list = (await app.inject({ url: '/api/replays' })).json();
assert.deepEqual(list.map((x: any) => [x.matchId, x.match, x.converted]), [[ID, `val-${ID}`, true]]);
// 롤 경기 · 없는 경기
assert.equal((await app.inject({ url: '/api/matches/lol-KR_1/replay' })).json().error, 'replay_not_found');
assert.equal((await app.inject({ url: '/api/matches/val-nope/replay' })).statusCode, 404);
});
test('변환 실패는 422 로 이유를 알리고, 같은 파일은 다시 변환하지 않는다 (파일이 바뀌면 다시)', async () => {
const s = setup();
const app = await api(s);
const vrf = path.join(s.demos, `${ID}.vrf`);
fs.writeFileSync(vrf, 'broken');
s.mode('fail');
const r = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(r.statusCode, 422);
assert.equal(r.json().error, 'replay_failed');
assert.match(r.json().message, /bad chunk/);
await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(s.calls(), 1);
// 다시 내려받음 (크기 · 시각이 바뀜) → 다시 변환
s.mode('ok');
fs.writeFileSync(vrf, 'fixed replay');
fs.utimesSync(vrf, new Date(), new Date(Date.now() + 5000));
const ok = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(ok.statusCode, 200);
assert.equal(s.calls(), 2);
});
test('변환이 기다리는 시간보다 길면 202 converting, 끝나면 200 (같은 파일을 두 번 변환하지 않음)', async () => {
const s = setup(300);
const app = await api(s);
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
s.mode('slow');
const r1 = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(r1.statusCode, 202);
assert.equal(r1.json().status, 'converting');
const r2 = await app.inject({ url: `/api/matches/val-${ID}/replay` });
assert.equal(r2.statusCode, 202);
let last = r2;
for (let i = 0; i < 20 && last.statusCode === 202; i++) {
await new Promise((res) => setTimeout(res, 300));
last = await app.inject({ url: `/api/matches/val-${ID}/replay` });
}
assert.equal(last.statusCode, 200);
assert.equal(s.calls(), 1);
});
test('변환기가 없으면 500 replay_tool_missing', async () => {
const s = setup();
const replays = new Replays({ dirs: () => [s.saved], tool: path.join(s.dir, 'none.exe'), cacheDir: () => path.join(s.dir, 'c'), version: '1' });
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
assert.deepEqual(await replays.get(ID), { state: 'no_tool' });
});
test('중계: gzip 리플레이는 바이너리 조각 + content-encoding 으로 사이트 서버에 간다', async () => {
const s = setup();
const app = await api(s);
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
const relay = new RelayClient(app, new Bus(), () => ({ serverUrl: 'https://x', deviceId: null, deviceKey: null, name: 'pc', version: 't', guildId: null }));
const sent: any[] = [];
(relay as any).ws = { readyState: WebSocket.OPEN, bufferedAmount: 0, send: (m: any) => sent.push(m) };
await (relay as any).handle({ t: 'req', id: 'r1', method: 'GET', path: `/api/matches/val-${ID}/replay`, headers: {}, user: { id: 'u', name: 'u', avatar: null }, body: null });
const head = JSON.parse(sent[0]);
assert.equal(head.t, 'res_head');
assert.equal(head.status, 200);
assert.equal(head.headers['content-encoding'], 'gzip');
const chunks = sent.slice(1, -1).map((b: Buffer) => b.subarray(4 + b.readUInt32BE(0)));
assert.equal(JSON.parse(sent.at(-1)).t, 'res_end');
assert.equal(JSON.parse(zlib.gunzipSync(Buffer.concat(chunks)).toString()).matchId, ID);
});
test('실제 변환기 (tools/replay-extract 리눅스 빌드 + 13.08 리플레이가 있을 때만)', { skip: !fs.existsSync(path.join(os.homedir(), 'work/vrf/match.vrf')) || !fs.existsSync(path.resolve(import.meta.dirname, '../../tools/replay-extract/out/linux/gvr-replay')) }, async () => {
if (!process.env.DOTNET_ROOT && fs.existsSync(path.join(os.homedir(), '.dotnet'))) process.env.DOTNET_ROOT = path.join(os.homedir(), '.dotnet');
const dir = tmp();
const demos = path.join(dir, 'Demos');
fs.mkdirSync(demos);
fs.symlinkSync(path.join(os.homedir(), 'work/vrf/match.vrf'), path.join(demos, `${ID}.vrf`));
const replays = new Replays({ dirs: () => [dir], tool: path.resolve(import.meta.dirname, '../../tools/replay-extract/out/linux/gvr-replay'), cacheDir: () => path.join(dir, 'c'), version: '1' });
const r = await replays.get(ID, 120000);
assert.equal(r.state, 'ready');
const j = JSON.parse(zlib.gunzipSync(fs.readFileSync((r as any).file)).toString());
assert.equal(j.matchId, ID);
assert.equal(j.players.length, 10);
assert.ok(j.kills.length > 100);
});

View File

@@ -0,0 +1,142 @@
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 } from '../src/core/db/db.ts';
import { Timeline } from '../src/core/timeline.ts';
import { Bus } from '../src/core/util/events.ts';
import { SttPipeline } from '../src/core/stt/pipeline.ts';
import { WorkerError } from '../src/core/stt/worker.ts';
import { TrayShell } from '../src/main/tray-shell.ts';
test('앱 종료: 변환 중이던 작업이 워커 종료로 실패해도 닫힌 DB 를 건드리지 않고, 남은 작업을 꺼내지 않는다', async () => {
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
for (const id of ['s1', 's2']) {
const f = path.join(dir, `${id}.ogg`);
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 });
}
const transcribing: string[] = [];
let fail: ((e: Error) => void) | null = null;
const worker: any = Object.assign(new EventEmitter(), {
ready: true,
request: async (op: string, req: any) => {
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
if (op !== 'transcribe') return {};
transcribing.push(path.basename(req.path, '.ogg'));
return new Promise((_, rej) => (fail = rej));
},
});
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm' }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
await stt.load('realtime', 'm');
const done: string[] = [];
stt.onDone = (id) => {
done.push(id);
store.getUtterance(id); // 실제 앱의 녹음 파일 이름 맞추기도 DB 를 읽는다
};
stt.enqueue('s1', 'realtime');
stt.enqueue('s2', 'realtime');
assert.deepEqual(transcribing, ['s1']);
// core.stop 순서: stt.stop → 워커 종료 → DB 닫기 → (워커 프로세스 종료 이벤트로) 변환 요청 실패
stt.stop();
store.close();
fail!(new WorkerError('worker_exit', '워커 종료'));
await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(done, [], '종료 중에는 변환 뒤 처리를 하지 않는다');
assert.deepEqual(transcribing, ['s1']);
assert.equal(stt.status.queue, 1, '종료 중에는 다음 작업을 꺼내지 않는다 (다음 시작 때 다시 처리)');
});
test('앱 종료: DB 를 닫은 뒤 변환 성공 응답이 와도 닫힌 DB 를 건드리지 않는다', async () => {
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
const f = path.join(dir, 's1.ogg');
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
store.insertUtterance({ id: 's1', session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
let ok: ((r: unknown) => void) | null = null;
const worker: any = Object.assign(new EventEmitter(), {
ready: true,
request: async (op: string) => {
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
if (op !== 'transcribe') return {};
return new Promise((res) => (ok = res));
},
});
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm' }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
await stt.load('realtime', 'm');
const errors: unknown[] = [];
const done: string[] = [];
stt.onDone = (id) => done.push(id);
// run() 의 오류는 pump 의 catch 가 log.error 로만 남기므로, DB 접근을 감시한다
const prepare = (store as any).db.prepare.bind((store as any).db);
(store as any).db.prepare = (sql: string) => {
try {
return prepare(sql);
} catch (e) {
errors.push(e);
throw e;
}
};
stt.enqueue('s1', 'realtime');
stt.stop();
store.close();
ok!({ text: '가자', raw_text: '가자', words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, speech_ratio: 1, duration_s: 1, model: 'm', elapsed_ms: 1 });
await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(errors, [], '닫힌 DB 에 접근하지 않는다');
assert.deepEqual(done, []);
});
test('트레이: 종료하면 갱신 타이머가 멈추고 트레이를 한 번만 없앤다 · 이미 없어진 트레이는 건드리지 않는다', (t) => {
t.mock.timers.enable({ apis: ['setInterval'] });
const fake = () => {
const tr = { destroyed: false, destroys: 0, updates: 0, isDestroyed: () => tr.destroyed, destroy: () => ((tr.destroyed = true), tr.destroys++) };
return tr;
};
// 갱신 함수는 main.ts 의 updateTray 처럼 shell.get() 으로 트레이를 얻는다 (없어진 트레이에 쓰면 Electron 이 던지는 것을 흉내)
const shell = new TrayShell<ReturnType<typeof fake>>();
let ticks = 0;
const update = () => {
ticks++;
const tr = shell.get();
if (!tr) return;
if (tr.destroyed) throw new Error('Tray is destroyed');
tr.updates++;
};
const a = fake();
shell.set(a);
shell.every(1500, update);
t.mock.timers.tick(3000);
assert.equal(a.updates, 2);
shell.dispose();
assert.equal(a.destroys, 1);
assert.equal(shell.get(), null);
t.mock.timers.tick(3000);
assert.equal(a.updates, 2, '종료 뒤에는 갱신하지 않는다');
assert.equal(ticks, 2, '종료하면 갱신 타이머가 멈춘다');
shell.dispose();
assert.equal(a.destroys, 1, '두 번 없애지 않는다');
// Windows 로그오프 등으로 Electron 이 트레이를 먼저 없앤 경우
const b = fake();
const shell2 = new TrayShell<ReturnType<typeof fake>>();
shell2.set(b);
shell2.every(1500, () => {
const tr = shell2.get();
if (tr?.destroyed) throw new Error('Tray is destroyed');
});
b.destroyed = true;
assert.equal(shell2.get(), null);
assert.doesNotThrow(() => t.mock.timers.tick(1500));
shell2.dispose();
assert.equal(b.destroys, 0, '이미 없어진 트레이는 다시 없애지 않는다');
});

View File

@@ -0,0 +1,82 @@
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 { buildApi } from '../src/core/api/server.ts';
import { Timeline } from '../src/core/timeline.ts';
import { Bus } from '../src/core/util/events.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-uset-'));
const as = (id: string, role: 'admin' | 'member' = 'member') => ({ 'x-gvr-user': encodeURIComponent(JSON.stringify({ id, name: id, avatar: null })), 'x-gvr-role': role });
async function setup() {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const bus = new Bus();
bus.usersProvider = () => store.listUsers().map((u) => ({ id: u.id, name: u.name, color: u.color, avatar: u.avatar, excluded: !!u.excluded, riot: [] }));
const live: any[] = [];
bus.on('live', (e) => live.push(e));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
store.setAccounts('u2', [{ puuid: 'p2', riotId: '민수#KR1' }]);
let renamed = 0;
const app = await buildApi({
store,
timeline: new Timeline(store),
games: {} as any,
dict: {} as any,
culprit: {} as any,
bus,
settings: () => ({}) as any,
trainingDir: () => path.join(dir, 'training'),
overviewExtra: () => ({ guild: null, recording: {} as any }),
version: 'test',
onNamesChanged: () => renamed++,
});
return { store, app, live, renamed: () => renamed };
}
test('유저 설정: 본인은 색 · 녹음 제외 · 라이엇 ID 를 바꾸고, 바뀌면 사이트에 실시간으로 알린다', async () => {
const s = await setup();
const r = await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { color: '#45D39A', excluded: true, riotIds: ['하늘#KR1', ' 하늘#KR1 ', '별빛#0001'] } });
assert.equal(r.statusCode, 200);
const u = r.json().user;
assert.equal(u.color, '#45d39a');
assert.equal(u.excluded, true);
assert.deepEqual(u.riot.map((x: any) => x.riotId), ['하늘#KR1', '별빛#0001'], '같은 ID 는 한 번만');
assert.equal(s.live.at(-1).type, 'users.updated');
assert.ok(s.live.at(-1).data.length >= 2, '실제 유저 목록을 보낸다');
// 이미 연결된 puuid 는 그대로 둔다
s.store.setAccounts('u1', [{ puuid: 'p1', riotId: '하늘#KR1' }]);
await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['하늘#KR1'] } });
assert.deepEqual(s.store.listAccounts().filter((a) => a.user_id === 'u1'), [{ user_id: 'u1', puuid: 'p1', riot_id: '하늘#KR1' }]);
});
test('유저 설정: 다른 사람 것은 관리자만, 남의 라이엇 ID 는 본인이 가져갈 수 없다, 형식 검사', async () => {
const s = await setup();
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u2', headers: as('u1'), payload: { excluded: true } })).statusCode, 403);
assert.equal(s.store.getUser('u2')!.excluded, 0);
const taken = await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['민수#KR1', '하늘#KR1'] } });
assert.deepEqual(taken.json().taken, ['민수#KR1']);
assert.deepEqual(taken.json().user.riot.map((x: any) => x.riotId), ['하늘#KR1']);
// 관리자는 다른 사람 설정도 바꾼다
const adm = await s.app.inject({ method: 'PATCH', url: '/api/users/u2', headers: as('u1', 'admin'), payload: { excluded: true, color: '#ff4655' } });
assert.equal(adm.statusCode, 200);
assert.equal(s.store.getUser('u2')!.excluded, 1);
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { color: 'red' } })).statusCode, 400);
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['a#1', 'b#2', 'c#3', 'd#4', 'e#5', 'f#6'] } })).statusCode, 400);
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/nobody', headers: as('nobody'), payload: { excluded: true } })).statusCode, 404);
});
test('표시 이름: 사이트 서버(내부 요청)만 보낼 수 있고, 받으면 이름 · 녹음 파일 이름을 맞추고 알린다', async () => {
const s = await setup();
const bad = await s.app.inject({ method: 'PUT', url: '/api/internal/names', headers: as('u1', 'admin'), payload: { names: { u1: '해커' } } });
assert.equal(bad.statusCode, 403);
const ok = await s.app.inject({ method: 'PUT', url: '/api/internal/names', headers: { ...as('server'), 'x-gvr-internal': '1' }, payload: { names: { u1: '하늘별' } } });
assert.equal(ok.statusCode, 200);
assert.equal(s.store.getUser('u1')!.name, '하늘별');
assert.equal(s.renamed(), 1);
assert.equal(s.live.at(-1).type, 'users.updated');
});

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

Binary file not shown.

View File

@@ -10,7 +10,7 @@ app/ 게임 PC 앱 (Electron + Node.js 코어, TypeScript)
src/core/ 헤드리스 코어. Electron 없이 `node` 로도 돈다 (리눅스 테스트용)
src/main/ Electron 메인 프로세스 (트레이, 창, 마법사, safeStorage)
src/renderer/ 설정 창 · 첫 실행 마법사 UI
worker/ Python STT 워커 (faster-whisper, VAD, 음량 정규화, OCR, 모델 관리, 파인튜닝)
worker/ Python STT 워커 (faster-whisper, VAD, 음량 정규화, 롤 로그 채팅, 모델 관리, 파인튜닝)
site/server/ 사이트 서버 (Fastify, Discord OAuth2, 기기 중계, 게임 이미지 캐시)
site/web/ 사이트 프런트엔드 (React + Vite)
packages/shared/ 앱·사이트가 같이 쓰는 TypeScript 타입 (protocol.ts)
@@ -71,13 +71,7 @@ tools/ 사전 생성기, 테스트 도구(목 Riot 서버, 음성
// "speech_ratio":0.82, "duration_s":2.4,
// "model":"large-v3-turbo", "elapsed_ms":310}}
{"id":"8","op":"ocr_start","window_title":"League of Legends (TM) Client",
"region":{"x":0,"y":0.62,"w":0.32,"h":0.25}, // 창 크기 대비 비율 (채팅 영역)
"fps":3, "lang":"ko"}
// 이벤트: {"event":"ocr_line","ts":1760000000000,"text":"[12:34] [팀] 민수 (아리): 드래곤 가자",
// "parsed":{"game_time":"12:34","channel":"team","sender":"민수","champion":"아리","message":"드래곤 가자"}}
{"id":"9","op":"ocr_stop"}
{"id":"10","op":"ocr_image","path":"..."} // 테스트용: 이미지 한 장 OCR → {"lines":[...]}
// 화면 OCR(ocr_start · ocr_stop · ocr_image)은 v1.3.3 에서 뺐다. 롤 게임 중 채팅은 r3dlog_read (worker/README.md)
{"id":"11","op":"train", ...} // 파인튜닝 (worker/gvr_worker/finetune 참고, M8)
{"id":"99","op":"shutdown"}
@@ -120,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) — 사이트 서버가 그대로 중계
@@ -137,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` ·
@@ -157,7 +155,7 @@ type TimelineItem =
```
`event.data` 예: 킬 `{killer:{puuid,name,agent|champion,team,userId?}, victim:{...}, assists:[...], weapon:{id,name,icon}, headshot?}` ·
채팅 `{sender:{name,puuid?,userId?}, channel:'team'|'all'|'party', text, source:'api'|'ocr'|'lcu'}` ·
채팅 `{sender:{name,puuid?,userId?}, channel:'team'|'all'|'party', text, source:'api'|'lcu'|'log'|'ocr'(v1.3.2 까지 기록)}` ·
오브젝트 `{object:'dragon'|'baron'|'herald'|'grub'|'tower'|'inhibitor', subtype?, team, killer}` ·
라운드 종료 `{round, winner:'ally'|'enemy'|teamId, result:'Elimination'|'Bomb detonated'|..., score:{ally,enemy}}`
@@ -202,7 +200,7 @@ type TimelineItem =
| Path | 설명 |
|---|---|
| `GET /auth/discord` | OAuth2 시작 (`identify guilds`) |
| `GET /auth/discord/callback` | 코드 교환 → 봇 토큰으로 `GET /guilds/{GUILD_ID}/members/{uid}` 확인 → 세션 쿠키 |
| `GET /auth/discord/callback` | 코드 교환 → 봇 토큰으로 `GET /guilds/{GUILD_ID}/members/{uid}` 확인 → 세션 쿠키. GUILD_ID = 게임 PC 앱에서 녹음할 서버로 고른 서버 (앱이 hello 로 알려 줌, 그 전에는 ALLOWED_GUILD_IDS). 아니면 `/?login=not_member` ("봇과 다른 서버") |
| `POST /auth/logout` | |
| `GET /auth/me` | `{user:{id,name,avatar}, isOwner}` 또는 401 |
| `GET /api/status` | `{device:{registered, online, name, lastSeen, version}, server:{version}}` (로그인 필요) |
@@ -218,6 +216,8 @@ type TimelineItem =
| `GET /app/admin/users` | 관리자 이상 → `{users: AppUserRow[]}` (최고 관리자 고정 행 포함) |
| `POST /app/admin/users` · `PATCH`/`DELETE /app/admin/users/:id` | 최고 관리자만: 등록(`{id, role:'admin'|'user'}`, 디스코드에서 계정 확인) · 역할 변경 · 등록 해제 |
| `GET /game-assets/<source>/<path>` | valorant-api.com · ddragon · cdragon 이미지 캐시 프록시 |
| `GET /auth/guild` | 로그인 화면 안내용 `{name}`: 들어올 수 있는 서버 이름 |
| `GET /site/maps3d` · `GET /site/maps3d/:dir/:code.glb` | 로그인 필요. 발로란트 맵 3D (data/maps3d, `tools/map-extract`). glb 는 gzip 그대로 보낸다 |
## 8. 겜녹이 봇 중계 (v1.2.1~)

108
docs/dev/replay-3d.md Normal file
View File

@@ -0,0 +1,108 @@
# 3D 리플레이 · 대화 동기화 (작업 노트, 2026-10-17)
## 결론 (조사)
- 발로란트는 리플레이 재생 위치를 주는 API가 없다 (로컬 API는 "리플레이 보는 중"까지). 2026-10-17 사용자 ShooterGame.log 에도 재생 위치는 없다 (열기 · 닫기 · 매치 ID · 시간 옮길 때 선수 재생성만 남음).
- 그래서 인게임 리플레이를 따라가지 않고, `.vrf` 를 풀어 **사이트에서 재생**한다. 대화는 사이트 플레이어 "현장 모드" 시계(sceneTs)에 묶여 재생 · 멈춤 · 이동 · 배속이 같이 움직인다.
## 구성
- `tools/replay-extract/` (C#, net10): ValorantReplayParser(MIT, `fetch-parser.sh` 로 고정 커밋을 vendor/ 에 받음) → `gvr-replay` JSON v1
- 선수 10명 이동 10Hz (x,y,z,yaw,pitch) · 라운드(구매/교전/끝) · 킬 · 사격 · 스킬/설치물(스파이크 TimedBomb_C 포함) · `recordedAt`(녹화 시작, ReplayInfo.Timestamp)
- 13.08 실제 경기(73.8MB): 6초, JSON 5.3MB / gzip 1.4MB, 진단 0
- 사이트 `site/web/src/lib/replay.ts` (동기화 · 보간 · 죽음 판정), `components/ReplayViewer.tsx` (three.js, 지연 로드), `ReplayPanel.tsx`
- 동기화: `ts = recordedAt + t + offset`, offset = 같은 킬(죽인/죽은 puuid)의 경기 기록 ts − 리플레이 시각의 중앙값. 킬이 3개 미만이면 라운드 교전 시작으로.
- 3D: 맵 3D 모양(아래 "맵 3D") 위에 선수를 실제 높이로. 맵 3D 가 없으면 미니맵 바닥
- 목 서버: `GVR_MOCK_REPLAY=<json> GVR_MOCK_REPLAY_MAP_FILE=<어비스 png> npm run dev` → `/matches/val-replay-demo` (경기 기록 킬을 1234ms 늦게 찍어 동기화 확인)
## 맵 3D (2026-10-17, 모든 맵)
- `tools/map-extract/` (C#, CUE4Parse 고정 커밋 `fetch-cue4parse.sh`): **게임 파일을 받지 않고** Riot CDN 번들에서 필요한 조각만 HTTP Range 로 읽는다 (매니페스트 RMAN 파싱 `src/Rman.cs`, 원격 임의 읽기 `src/Cdn.cs`, 메모리 캐시 1.5GB, 디스크 안 씀).
- 맵 = 하위 레벨을 불러오는 영구 레벨 (경기 기록 맵 경로 `/Game/Maps/Ascent/Ascent` 와 같다). 하위 레벨 중 `LevelStreamingAlwaysLoaded` 이고 이름이 빛 · 소리 · 게임 규칙 · 부피 · 먼 배경 · 이벤트 장식이 아닌 것만 (`MapScene.NotVisual`).
- StaticMesh(+인스턴스) 가장 낮은 LOD 를 월드 좌표(cm)로 구워 맵마다 glb 하나 (위치 + 삼각형만, 재질 없음). 사이트가 높이로 색칠.
- 13.08 실측: 22개 맵(일반 13 · 팀 데스매치 5 · 스커미시 3 · 어빌리티 드래프트 1) 3.1분, 받은 양 587MB, 최대 메모리 약 1.9GB. `scripts/pack.py` → gltfpack `-cc` + gzip 으로 맵당 0.5~4.6MB (합계 52MB).
- 사이트: 서버 `data/maps3d/index.json` + `<dir>/<code>.glb.gz`, `GET /site/maps3d*` (로그인 필요). 재생기 `lib/map3d.ts` 가 meshopt 로 풀어 리플레이와 같은 좌표 변환 행렬로 놓는다. 맵이 있으면 미니맵 바닥 · 선수 그림자는 숨긴다.
- meshopt 는 WebAssembly 라 CSP `script-src` 에 `'wasm-unsafe-eval'` 가 필요하다 (없으면 미니맵으로 대체됨, 헤드리스 크롬으로 둘 다 확인).
- 천장 자르기: 자동(고른 선수 · 없으면 가장 높은 산 선수 몸 중심 + 380cm 위를 자름) · 없음 · 직접(슬라이더).
- 자동 갱신: `scripts/install.sh` 가 `~/gvr-maps` 에 설치, `gvr-maps-update.timer` 30분마다 `update.sh`: uedb 매핑(버전 · 갱신 시각) 또는 라이브 매니페스트가 바뀌면 매핑을 받아 `~/gvr-maps/mappings/` + nextcloud `claude/game-voice-recorder/valorant/mappings/` 에 보관 → 전체 추출 → .5 `data/maps3d` 에 올리고 index.json 교체 (이전 폴더 1개만 남김). 어느 단계든 실패하면 이전 맵 유지, 같은 조합은 30분 · 1 · 2 · 4 · 6시간 간격으로 재시도 (첫 실패 · 성공 때 이 방 채널에 한 줄 알림, uedb/패치 확인 자체는 6번 연속 실패 때 알림). 지금 사이트에 있는 맵이 하나라도 새 결과에 없으면 올리지 않는다 (추출기도 맵 찾기 중 레벨 읽기 실패를 실패로 친다). 강제(대기 · 누락 검사 무시): `~/gvr-maps/scripts/update.sh --force`. 시험: `scripts/test-update.sh`.
## 앱 (v1.5.0)
- `app/src/core/replays.ts`: `%LOCALAPPDATA%\VALORANT\Saved` 아래(깊이 3, Logs · Crashes · Config 제외) `<경기 ID>.vrf` → 사이트가 열 때 `gvr-replay.exe <vrf> <tmp.json>` (낮은 우선순위, 한 번에 하나, 3분 제한) → gzip → `GVR-Data/replays/<경기 ID>.json.gz` + `.src`(크기:수정시각:앱 버전). 실패는 메모리에 기억 (파일이 바뀌거나 앱을 다시 켜면 다시)
- `GET /api/matches/:id/replay`: 15초 안에 끝나면 200 (content-encoding gzip), 아니면 202 `{status:'converting'}` → 사이트가 3초마다 다시. 중계는 content-encoding 이 있으면 바이너리 조각 (`relay/client.ts`)
- 빌드: win-ci `replay_build` 단계 (.NET 10 SDK `C:\win-ci\dotnet`, `dotnet publish -r win-x64` 단일 파일 38MB) → electron-builder extraResources `replay/`. 호스트 `~/win-ci/serve/gvr-test.vrf`(13.08 어비스 경기) 가 있으면 변환기 · 포터블 앱 smoke(`GVR_SMOKE_VRF`) 둘 다 실제 변환
- 리눅스 실측(13.08, 73.8MB vrf): 5.5초, 최대 메모리 347MB, gzip 1.4MB
## 완전 3D (2026-10-17, v1.7.0)
- 맵 색: `MapScene` 이 재질마다 primitive 하나 (법선 · UV, 디퓨즈 텍스처 256px JPEG/PNG(알파), `DiffuseColor` 색). 두 층 재질(`BaseEnv_Blend_*`, Diffuse A/B)은 정점 색 R 로 섞는다 (`extras.blend`, 사이트 `map3d.ts` 셰이더). UE 왼손 → glTF 앞면에 맞춰 삼각형을 뒤집는다. 어비스 압축 12MB.
- 요원: `gvr-map-extract agents <폴더>` → `agent_<코드>.glb` (요원 블루프린트 `Characters/<코드>/<코드>_PC` 의 3인칭 메시 LOD1, 512px 텍스처, 뼈대 + 공용 애니메이션 `ub_rifle`(Core_Rifle_Idle 위 몸) · `lb_idle/run*/walk*`(아래 몸, Skeleton·Root 는 회전만)). 애니메이션은 ACL 압축이라 CUE4Parse-Natives(ACL 만)를 g++ 로 빌드해 실행 파일 옆에 둔다 (`install.sh`). 30명 46초, 압축 6.4MB.
- 무기: `weapon_<이름>.glb` (기본 스킨 몸 + 탄창, 원점 = 손잡이, 총구 +X). 사이트는 손목(R_Hand) 에 붙이고 보는 방향(pitch)으로 돌린다 (공용 애니메이션은 R_WeaponPoint 를 움직이지 않아 손과 떨어져 있다). 22종 1.5MB.
- 변환기: `equips` [t, 선수, 종류] / `equipKinds` (총 영어 이름 · Melee · Spike · 스킬 클래스). 사이트 이름표 "🔫 밴달", 킬 피드에 무기. 옛 리플레이 JSON 에는 없다 (앱 v1.7.0 부터).
- 재생기: 카메라 위에서 / 1인칭(고른 선수 눈 + 60cm, pitch) / 자유시점(WASD · Q/E · Shift, 끌어서 둘러보기). 요원은 이동 방향 · 속도로 아래 몸 애니메이션을 섞는다. 스킬은 `lib/abilities.ts` 가 클래스 이름으로 연막(요원 색 구) · 장판 · 폭발 · 정찰 고리 · 설치물 · 스파이크로 나눈다.
- 한계: 스킬 효과(파티클) · 벽 스킬 방향 · 앉기 · 점프 자세 · 스킨은 없다. 리플레이 위치는 10Hz 라 빠른 움직임은 보간이다.
## 스킬 효과 (2026-10-18, 실감 2단계)
- 추출: `gvr-map-extract abilities <폴더>` (`src/Abilities.cs`) → `abilities.json` + `m_*.glb`(스킬 · 투사체 · 설치물 메시, 파티클 메시) + `t_*.png`(256px, 큰 것 512px). 13.08 전체: 스킬 클래스 217 · 파티클 시스템 520 · 메시 373 · 텍스처 1054, 받은 양 341MB · 3.9분 · 최대 메모리 1.7GB, gzip 합계 약 40MB (json 0.8MB).
- 발로란트 효과는 전부 Cascade `ParticleSystem` 이다 (Niagara 0개). 이미터마다 모양(sprite · mesh · decal · ribbon) · 재질 · 분포 표(구운 FRawDistribution) 를 그대로 옮긴다. 형식 설명은 `Abilities.cs` 머리말.
- 클래스(리플레이 objectKinds) → 블루프린트 → FXC 효과 묶음 · 패치 · 투사체 컴포넌트에서 역할(loop · intro · outro · warn · trail · explode · patch · decal) 별 시스템(아군 · 적 따로).
- `update.sh` 가 맵 · 요원 · 애니메이션 다음에 돌리고 `pack.py` 가 `abilities/` 를 gzip 해 index.json `abilities` 로 올린다.
- 사이트 `lib/vfx.ts`: 입자 상태를 "켜진 뒤 지난 시간" 만으로 계산 (입자마다 고정 난수) → 되감기 · 배속에도 같은 장면. 이미터 종류별로 인스턴스 사각형 · 인스턴스 메시 · 바닥에 눕힌 사각형 · 지나간 길(리본).
- 재질 그래프는 쿡된 파일에 없다(매개변수 · 텍스처만). 이름 점수로 색 · 알파 텍스처를 고르고, 텍스처 채널 상관으로 색 그림 · 흑백/묶음 마스크(R)를 가린다. UE 반투명처럼 (HDR 색 × 불투명도) 를 미리 곱한 알파로 더하고 채널마다 0.8 위를 눌러 불꽃이 주황 · 노랑이 된다.
- 연막 돔(불투명 · 마스크 큰 구)은 요원별 색(`DOME`) + noise + 가장자리 빛(게임 팀 색). 돔 위 반투명 층은 돔 색으로 옅게.
- 장판(CellularPatch): 게임처럼 반지름 안 칸마다 불 효과 하나, 가운데서 SpreadSpeed 로 번진다. 그을음은 반지름 크기.
- 뺀 것: 벽 너머 표시 · HUD · 1인칭 · 사거리 표시 · 팀 구별 층(FoF) · beam · 화면 아이콘 메시. 데이터가 예상과 다른 이미터는 그 이미터만 끈다.
- 효과가 없는 클래스는 예전 종류별 모양, 날아가는 모습이 없는 투사체(요루 섬광 등)는 예전 빛 구 + 터지는 효과. 요루 분신 · 스파이크는 원래 그리던 것 + 효과.
- 개발 확인: 효과 하나만 따로 그리는 판(`~/.tmp/gvr/vfxHarness.ts` 를 `site/web/src/dev/` 에 잠시 두고 vite dev 에서 `import('/src/dev/vfxHarness.ts')`). 저장소에는 넣지 않았다.
- 한계: 재질 그래프 근사라 색 · 무늬가 게임과 조금 다르다. 리본 · beam 일부, 화면 효과(섬광 눈부심 등)는 없다. 오멘 연막처럼 추출기가 클래스를 못 찾은 것은 예전 모양.
## 구운 조명 (2026-10-29, 실감 3단계)
- 계기: aim.sheepu.dev(브라우저 발로란트 에임 연습장)의 맵이 게임처럼 보이는 이유를 보니 게임이 구워 둔 라이트맵(밝기 + SH 방향)을 그대로 쓴다. 우리 맵은 텍스처 × 장면 조명(하늘빛 + 해)이라 평평했다. 그 사이트 파일은 쓰지 않고 우리 추출기로 게임 파일에서 직접 뽑는다.
- 게임 쪽: 레벨마다 `<레벨>_BuiltData` (UMapBuildDataRegistry). 컴포넌트 `LODData[0].MapBuildDataId` → FMeshMapBuildData → FLightMap2D (텍스처 · ScaleVectors/AddVectors · CoordinateScale/Bias), ISM 은 인스턴스마다 `PerInstanceLightmapData[i].LightmapUVBias` (HISM 은 `InstanceReorderTable`). 라이트맵 UV 채널은 메시 `LightMapCoordinateIndex`, LOD0 에만 있다 (구운 조명이 있는 배치는 LOD0, 삼각형은 거의 같다: 어센트 233만 → 235만).
- HQ_Lightmap 텍스처(DXT5 1024²)는 위 절반 = 계수 0(UVW² · 로그 밝기), 아래 절반 = 계수 1(SH 방향 xyz · 밝기 나머지). 푸는 식은 UE `LightmapCommon.ush` GetLightMapColorHQ 와 같다. 햇빛 그림자까지 다 구워져 있다 (정적 조명).
- 추출기 `src/Lightmaps.cs`: 메시가 차지한 칸마다 그 메시 범위로 풀어 irr(L·UVW·L0, sRGB/K) · sh(방향/L0, ±2) 두 장으로 → 칸 밖은 이웃 값으로 채움 → 1/2 씩 줄여 선반 쌓기 아틀라스(너비 `GVR_LIGHTMAP` 기본 2048, 넓이 약 그 제곱 안). 조명 없는 배치는 (0,0) 기본 칸(맵 평균 밝기).
- glb: 모든 재질에 `occlusionTexture`(irr) · `emissiveTexture`(sh, 세기 0) 를 TEXCOORD_1 로, `extras.lightmap.k`. gltfpack 이 쓰지 않는 UV 채널을 버리지 않게 텍스처가 그 채널을 가리켜야 한다. 옛 사이트는 aoMap 으로만 써서(어두워지기만) 깨지지 않는다.
- pack.py 는 맵을 `-vtf`(UV 실수) 로: gltfpack 은 재질마다 TEXCOORD_0(반복, 수십 단위) · TEXCOORD_1 을 한 범위로 양자화해서 정수로 줄이면 라이트맵이 몇 텍셀씩 어긋난다.
- 13.09 실측: 어센트 페이지 72 → 1864×1360(1/4) 2.5MB, 어비스 116 → 1864×2176(1/4) 3.4MB. 맵 압축 크기 어센트 14.7 → 18.8MB, 어비스 12.1 → 17.4MB.
- 메모리: 배치를 모으는 동안은 칸 목록만 두고 Build 에서 페이지를 하나씩 풀어 바로 줄인다. 처음(모든 페이지를 원래 크기로 들고 있던 것)에는 페이지 200개 넘는 펄(Pitt)이 서비스 한도 6GB 에서 OutOfMemory 였다. 고친 뒤 펄 최대 2.7GB.
- 사이트 `lib/map3d.ts` `installShader`: 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)) (N 은 glb 법선 = UE 월드 법선 그대로), 0.8 위는 살짝 눌러 하얗게 날지 않게. 장면 조명은 맵에 쓰지 않는다 (요원 · 효과는 그대로 장면 조명).
- 조사 명령: `gvr-map-extract lmprobe <레벨.umap>` (빌드 데이터 · 텍스처 · 연결 통계, `GVR_LM_DUMP=<폴더>` 면 라이트맵 png).
- 13.09 전체 (2026-10-29 반영): 맵 23개 중 22개에 조명 (아이스박스 Port 는 BuiltData 에 라이트맵이 없어 예전 장면 조명), 아틀라스 1.2~4.7MB, 사이트 폴더 303 → 403MB. 맵 추출 26분 · 서비스 최대 메모리 5.9GB(스킬 재료 단계 포함).
- 한계: 1/4 로 줄여 그림자 가장자리가 흐리다. 움직이는 것(요원)은 구운 조명을 받지 않는다 (볼륨 라이트맵은 아직 안 씀). 어비스 낭떠러지처럼 게임에서 어두운 곳은 그대로 어둡다.
## 1인칭 팔 · 총 · 조준점 (2026-10-29, 실감 4단계)
- 계기: aim.sheepu.dev 훈련 화면(밴달 + 피닉스 팔 1인칭, 흰 십자 조준점, 탄흔 · 총소리)을 보고 우리 1인칭에 없던 것을 게임 파일에서 직접 뽑았다 (그 사이트 파일은 쓰지 않음).
- 추출 `gvr-map-extract viewmodels <폴더>` (`src/Viewmodels.cs`, 13.09 전체 39초 · 최대 1.1GB):
- `fparms_<코드>.glb` 요원 1인칭 팔 `Characters/<코드>/S0/1P/Models/FP_<코드>[_New]_S0_Skelmesh` (30명, 브리치는 `_New`). 팔 메시에 같이 든 스킬 · 3인칭 조각(재질 AB_ · ABTP_ · CS_ · TP_)은 뺀다 (네온 칼날 모양, 소바 활 장갑 등).
- `fpweapon_<이름>.glb` 무기 1인칭 `<무기 폴더>/S0/1P/Models/(GN|EQ)_*_S0_Skelmesh` + 탄창(Magazine_Main 뼈 자식) + `GN_Core_*_S0_{Fire,Reload,Equip}` → gun_fire · gun_reload · gun_equip (22종, 칼 · 스파이크 포함).
- `fpanim_<이름>.glb` 팔 동작(뼈 노드만, 공용 뼈대 `FP_Core_Retarget_Skelmesh`): `FP_Core_*_S0_` IdlePose|Idle · Fire|FireAdd · Reload · Equip · AltIdlePose(정조준) · WalkAdd · Activate(스파이크). 덧셈 동작은 CUE4Parse 가 기준 자세에 더해 준다.
- 압축 합계 7.4MB, index.json `viewmodels`. update.sh 가 anims 다음에 돌린다.
- 사이트 `lib/viewmodel.ts`: 맵과 따로 장면 하나(카메라 공간, 깊이를 지우고 맵 위에 그림). 무기 뿌리 = 팔 뼈 MasterWeapon × 회전 (0.5,−0.5,0.5,0.5) (총구 → 팔 앞, 탄창 → 아래가 되는 축 맞춤, 모든 총 같음). 눈 = 팔 Camera 뼈(대기 자세).
- 자세는 시각만으로: 꺼내기(equips) > 재장전(states ReloadState) > 사격(shots, 60ms 총구 불꽃) > 걷기(0.2초에 30cm 넘게 움직임) > 정조준(ZoomState*) > 대기. 죽었거나 스킬 · 맨손이면 숨긴다.
- 줌: 소총 등 1.25배, 저격총 2.5배(2단 5배) + 조준경 테두리(검은 원 · 가는 십자선), 저격 줌 중에는 팔 · 총을 숨긴다.
- 조준점: 녹색 점 → 발로란트 기본 (흰 선 4개 · 가운데 틈 · 검은 외곽선). 1.8.2 부터 선수 조준점 · 내 조준점 (아래).
- 안 한 것: 총소리 · 발소리(Wwise 사운드뱅크라 따로 풀어야 함), HUD 체력 · 탄약(리플레이에 값 없음), 탄흔(맞은 자리 `hits` 로 가능), 스킨(기본 스킨만), 스킬 1인칭 동작, 재장전 중 탄창이 손으로 옮겨 가는 것(소켓 바꾸기라 탄창이 잠깐 안 보임).
## 남은 일
- 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")
## 완전 3D (맵 · 캐릭터 · 총 · 효과) 조사 (2026-10-17)
- 게임 파일: Riot CDN 에서 바로 받을 수 있다 (게임 PC 불필요). 매니페스트는
`https://clientconfig.rpg.riotgames.com/api/v1/config/public?namespace=keystone.products.valorant.patchlines` 의 `*.manifest`,
받기는 Morilli/ManifestDownloader (`-b https://valorant.secure.dyn.riotcdn.net/channels/public/bundles --no-langs -f 'ShooterGame/Content/Paks/(pakchunk|global)'`), 13.08 기준 34GB · 10분.
- 열기: CUE4Parse (`EGame.GAME_Valorant`, 공개 AES 키, 리눅스 Oodle 자동 다운로드) → 파일 396,466개, `Maps/Infinity/*.umap` 확인.
- 매핑: 13.08 부터 패키지가 unversioned → `.usmap` 필요. **공개 배포처가 있다**: `https://uedb.dev/svc/api/v1/valorant/mappings` (패치별 JSON → Brotli/ZStandard usmap URL, 13.08 은 2026-10-16 갱신), AES 는 `.../valorant/aes`. 출처: sinnafuls/cue4parse-mcp `games.example.json`.
- 이전에 시도한 다른 게임 매핑(Remnant2 등)은 틀린 매핑이라 배열 길이를 잘못 읽어 메모리가 폭주했다 (17.6GB). 올바른 매핑으로는 어비스 전체 읽기 최대 1.3GB · 9초.
- Uiana-MapImporter(djhaled) 는 UE4 시절(2023, 매핑 불필요) 코드라 그대로는 안 됨 (발로란트 UE5.3 전환은 11.02).
- 어비스 결과 (2026-10-17): `Maps/Infinity/Infinity_Art_*.umap` 17개 → StaticMesh 컴포넌트 2,237 + ISM 인스턴스 1,833 = 배치 3,632, 고유 메시 991 (전부 pakchunk0/1 안, 받기 11GB · 3분), 삼각형 136만 (최저 LOD). glb 146MB.
- 좌표: 리플레이 선수 x,y,z 와 맵 월드 좌표(UE cm)가 변환 없이 일치 (선수 점이 통로 위에만 찍힘). glb 는 (x,z,y)*0.01 로 저장되므로 되돌릴 때 주의.
- 위에서 볼 때 지붕을 걸러야 한다 (Z 1500cm 이상 삼각형 제외로 미리보기 확인).
- 추출기: `~/work/valoexp` (CUE4Parse, 명령 `where/deps/scene/export`), 합성 · 미리보기 `~/work/valomap/tools/compose.py`. CUE4Parse glTF 내보내기가 리눅스에서 `\` 경로로 파일을 쓰는 버그가 있어 옮겨야 함.
- 보관: nextcloud `claude/game-voice-recorder/valorant/13.08/` (nextcloud 에서는 `claude/` 폴더 안만 다룬다, 사용자 규칙) (abyss-13.08.tar.gz = glb · scene.json · 미리보기 · usmap · 도구 사본, usmap 단독). 계정은 secrets `nextcloud.192.168.10.10`.
- 실험은 반드시 `systemd-run --user --scope -p MemoryMax=6G -p MemorySwapMax=0` 안에서.
- 디스크: .9 는 150GB 이상 비워 둔다 (사용자 요청). 게임 파일은 다시 받을 수 있으므로 지웠다. 큰 결과물은 nextcloud(.10:8080)로 (로그인 정보 필요).
## 선수 조준점 · 내 조준점 (2026-10-29, v1.8.2)
- 리플레이에 있다: `BombPlayerState` 에 선수마다 조준점 프로필이 복제된다 (관전자에게 보이는 조준점). 파서 형식에는 없어서 `gvr-replay <vrf> --fields` 로 필드 이름을 보고 찾았다.
- 13.08 번호: 39~85 주 조준점, 86~132 정조준, 133~179 (값이 온 적 없음), 180~197 저격 조준경(가운데 점 색 · 크기 · 불투명도 · 표시) · `bUsePrimaryCrosshairForADS` · `bUseAdvancedOptions` · `ProfileName`.
- 묶음 안 순서: 색 BGRA · 사용자 지정 색 BGRA · bUseCustomColor · 외곽선(켬 · 두께 · 색 · 불투명도) · 가운데 점(크기 · 불투명도 · 켬) · … · 안쪽 선 12개 · 바깥쪽 선 12개 (두께 · 길이 · 세로 길이 · 간격 · 세로 따로 · 이동 오차 · 사격 오차 · 최소 오차 · 불투명도 · 켬 · 사격 배율 · 이동 배율).
- 기본값과 다를 때만 오고(색 흰색 255 · 숫자 0 · 끔), 바뀐 것만 다시 온다. 확인: 프로필 이름 "1 4 2 0" 선수 = 불투명도 1 · 길이 4 · 두께 2 · 간격 0, "점" 선수들 = 가운데 점만. 저격 점은 10명 모두 빨강(게임 기본).
- 변환기 `src/Crosshair.cs`: 첫 읽기의 필드 목록에서 기준 번호를 찾고(이름이 모두 맞는 자리, 패치로 밀리면 ±80 안에서 찾음, 못 찾으면 조준점 없이 변환) 이 필드만 읽는 두 번째 읽기 (`IncludedPaths`, 어비스 리플레이 +0.4초). 출력 `players[].crosshair` = 바뀐 시각마다 전체 설정 (`t · name · primary · ads · sniper · adsFromPrimary · advanced`, color 는 실제 보이는 색).
- 사이트 `lib/crosshair.ts` (그리기 · 발로란트 조준점 코드 읽기) · `components/CrosshairPanel.tsx`: 1인칭 "조준점" 버튼 → 선수 조준점(없으면 내 조준점) / 모든 선수에 내 조준점, 내 조준점 직접 고치기 · 코드 가져오기 · 선수 조준점 복사. 설정은 브라우저 `gvr.settings.v1` `crosshair`.
- 정조준(저격총 아님) 중에 고급 설정 + 정조준 조준점 따로면 ads, 저격 줌은 조준경 가운데 점. 사격 오차 · 이동 오차 켠 선은 쏜 뒤 0.35초 · 걷는 동안 벌어진다 (총마다 다른 실제 퍼짐이 아니라 대략).
- 옛 리플레이 JSON 에는 없다. 앱은 버전이 바뀌면 다시 변환하므로 1.8.2 로 올리면 다음에 열 때 생긴다.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 451 KiB

After

Width:  |  Height:  |  Size: 454 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 380 KiB

After

Width:  |  Height:  |  Size: 382 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 328 KiB

After

Width:  |  Height:  |  Size: 331 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 215 KiB

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 187 KiB

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 170 KiB

After

Width:  |  Height:  |  Size: 170 KiB

View File

@@ -151,3 +151,175 @@ VOICE E2E PASS
- OP.GG "조회 실패"와 "경기 없음"을 나눈다: 결과 `meta.opgg.error`, 화면 "OP.GG 조회 실패 · 기록 점수로 분석", 지시문 "이 줄이 없으면 OP.GG 에 없는 경기이거나 조회하지 못한 경기". 실제 OP.GG: 랭크 경기 10명 찾음, 잘못된 주소 → `error` (3번 중 3번 실패: OP.GG 404)
- LOL.PS 라인전: LOL.PS 원문 정의("10, 15분 맞라이너 골드차, 경험치차, cs차이")대로 10분 값을 더해 10 · 15분 차이를 보여 준다. 참고한 원문과 구현 대응은 `tools/opscore-fit/README.md`
- 테스트: 앱 40개 · 사이트 서버 20개 통과, 화면 오류 · CSP 위반 없음
- 배포: 사이트 서버 다시 배포(지시문 · 화면 반영 확인), Windows CI (0e0a272, full) 8개 모두 PASS · 앱 버전 1.3.1 → Gitea 릴리스 v1.3.1 (v1.3.0 에 새 버전 안내)
## 범인찾기 v1.3.2 — 외부 전적 사이트 접속 제거 (2026-10-15)
사용자 결정: 전적 사이트는 "계산법을 참고"하라는 뜻이었고 실제로 연결하는 것이 아니다 → 분석할 때 OP.GG 를 찾아보던 기능(`site/server/src/opgg.ts`, 결과의 OP.GG 점수 · 조회 상태, 지시문의 OP.GG 실제 점수 줄)을 뺐다. 기록 점수(OP.GG 계산법) · 10/15분 라인전(LOL.PS 정의)은 앱이 경기 기록으로 계산한다.
`node --import tsx app/scripts/culprit-real-e2e.mts` — 실제 Claude Opus 5.5(생각 high), 외부 사이트 접속 없음 (로그에 OP.GG 0건)
| 경기 | 걸린 시간 | 토큰 (입력 / 캐시 쓰기 / 출력) | 비용 | 범인 (기록 점수 팀 최하위) |
|---|---|---|---|---|
| 발로란트 시연 경기 (22라운드, 대화 4문장) | 33초 | 10,562 / 7,382 / 2,943 | $0.138 | 우리 P5 (공동 최하위 5.0, 동점자 P4 와 비교해 이유) · 상대 P7 (1.9, 최하위) |
| 롤 시연 경기 (10 · 15분 라인전, 대화 7문장) | 36초 | 3,186 / 8,937 / 3,300 | $0.123 | 우리 P1 (2.7, 최하위) · 상대 P7 (4.5, 최하위) |
- 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 코드에서 실패 확인 뒤 고침)
- 배포: 사이트 서버 다시 배포 (바뀐 안내 문구 확인), Windows CI (df0c826, full) 7개 모두 PASS · 앱 버전 1.4.1 → Gitea 릴리스 v1.4.1 (v1.4.0 에 새 버전 안내). 실제 STT 워커 E2E 에서 "레이드 공/궁" 은 그대로 learned 잡음
## v1.4.2 — 녹음 중에 들어온 사람이 "알 수 없음"으로 뜨던 문제 (2026-10-16)
- 원인: 녹음 시작 때 채널에 있던 사람만 `users.updated` 를 보냈다. 녹음 중에 들어온 사람은 `onVoiceState` 에서 DB 에 저장만 하고 알리지 않아, 사이트의 유저 목록에 없어 발화가 "알 수 없음"으로 떴다 (새로고침하면 보임)
- 고침: 앱은 들어올 때 `users.updated` 를 보낸다. 사이트는 `utterance.created/updated` · `recording.state` 에 모르는 아이디가 오면 `/api/users` 를 한 번 다시 받는다 (같은 아이디는 한 번만)
- 테스트 `core.test.ts` "녹음 중에 들어온 사람": 고치기 전 코드에서 실패(users.updated 0번) 확인 뒤 통과
- 사이트(목 서버 `/mock/latejoin`, 브라우저): 고치기 전 화면은 새 발화 2곳이 "알 수 없음", 고친 화면은 이름이 바로 뜨고 왼쪽 유저 목록에도 추가
- 테스트: 앱 63 · 사이트 서버 16 통과, 앱 · 화면 · 서버 타입 검사 · 화면 빌드 통과
- 배포: 사이트 서버 다시 배포 (배포된 화면 번들 `index-Cbz_E9Kc.js` 에 모르는 아이디 다시 받기 확인), Windows CI (79d6bb2, full) 7개 모두 PASS · 앱 버전 1.4.2 → Gitea 릴리스 v1.4.2 (v1.4.1 에 새 버전 안내)
- 보완 (사이트만): 모르는 아이디를 받기 전에 영구히 기억해서 `/api/users` 가 한 번 실패하면 그 사람은 계속 "알 수 없음"이었다. `site/web/src/lib/unknown-users.ts` 로 빼서, 받는 중에는 또 부르지 않고 실패하면 다음 이벤트에서 다시 받는다 (성공한 아이디만 기억). 테스트 `site/server/test/unknown-users.test.ts` 2개. 목 서버 `/mock/users-fail?n=1` + `/mock/latejoin?again=1`: 고치기 전 화면은 요청 1번에 이름 없음, 고친 화면은 다음 발화에서 다시 받아 이름 표시
- 테스트: 앱 63 · 사이트 서버 18 통과, 앱 · 화면 · 서버 타입 검사 · 화면 빌드 통과. 앱 코드는 그대로라 v1.4.2 릴리스는 그대로
## v1.4.3 — 상대 닉네임을 말로 적던 문제 (2026-10-17)
- 증상: 사이트 대화에 "QQQWWWQ" 라는 말이 여러 사람 발화로 뜸. 같은 경기 상대 선수 이름이 "QQQWWWQQQ"
- 원인: `pipeline.ts` `matchWords` 가 그 경기 10명의 선수 이름을 핫워드 맨 앞에 넣었다. 말을 못 알아들으면 Whisper 가 핫워드를 그대로 적는데, 기존 되풀이 확인(`is_hotword_echo`)은 3단어 이상만 봐서 이름 하나(조각)는 지나갔다
- 고침: 선수 이름은 한글이 들어간 것만 핫워드로. 결과가 선수 이름(조각)뿐이면 워커가 이름을 빼고 다시 변환. 예전 발화는 한 번만 다시 변환(파일 없으면 숨김, 고친 발화 제외)
- 테스트: 워커 `test_hotword_echo.py` 이름 되풀이 3개, 앱 `name-echo.test.ts` 3개(판정 · 핫워드에 영문 닉네임 빠짐 · 예전 발화 다시 보기 한 번만)
- 실제 모델(faster-whisper small, CPU): 실제 말소리 · 키보드 · 잡음 파일에 영문 닉네임 핫워드를 넣어도 정상, 결과 전체를 선수 이름으로 준 경우 되풀이로 잡고 이름 없이 다시 변환해 실제 말을 돌려줌
- 배포: Windows CI (010d247, full) 7개 모두 PASS · 앱 버전 1.4.3 → Gitea 릴리스 v1.4.3 (v1.4.2 에 새 버전 안내). 사이트 서버는 바뀐 것 없음
## v1.5.0 — 3D 리플레이: 앱이 리플레이를 찾아 변환 (2026-10-17)
- 앱 `replays.ts`: `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<경기 ID>.vrf` → 사이트가 열 때 `gvr-replay.exe` 로 변환 → `GVR-Data/replays/<경기 ID>.json.gz`. API `GET /api/matches/:id/replay` (gzip, 변환 중 202, 실패 422) · `GET /api/replays`
- 테스트: 앱 73(새 `replays.test.ts` 7개: 찾기 · 변환 후 보관본 · 실패 기억과 다시 내려받으면 다시 · 202 → 200 · 변환기 없음 · 중계 gzip 바이너리 · 실제 리눅스 변환기로 13.08 리플레이) · 사이트 서버 27 통과, 타입 검사 · 화면 빌드 통과
- Windows CI (adc1c66, full) 8개 모두 PASS: 새 `replay_build` (.NET 10.0.402, gvr-replay.exe 36.3MB, 13.08 어비스 리플레이 6.8초 변환), `app_smoke` 에서 포터블 앱 안 변환기로 같은 리플레이 9.1초 변환(gzip 1.39MB)
- 배포: 사이트 서버 다시 배포 (화면 번들에 '변환하는 중' 확인), 앱 버전 1.5.0 → Gitea 릴리스 v1.5.0 (v1.4.3 에 새 버전 안내)
## v1.6.0 — 사이트 내 정보 · 관리 페이지 (2026-10-17)
- 사이트: 머리글 내 이름 → 내 정보 (표시 이름 · 색 · 라이엇 ID · 녹음 제외 · 로그아웃), `/admin` 관리 페이지 (게임 PC · 새 버전 안내 · 유저별 설정 · 앱 등록/역할/해제)
- 테스트: 앱 76 (새 `user-settings.test.ts` 3개) · 사이트 서버 30 (새 `profile-admin.test.ts` 3개) 통과, 타입 검사 · 화면 빌드 통과
- 화면: 목 서버 + 헤드리스 크롬(playwright-core)으로 내 정보(이름 저장 · 머리글 반영 · 색 · 녹음 제외 · 되돌리기) · 관리 페이지(새 버전 링크 · 이름 바꾸기 · 앱 유저 등록) · 모바일 390px 확인, 콘솔 오류 0
- 배포: 사이트 서버 다시 배포 (`/site/admin/overview` · `/site/profile/name` 로그인 없이 401, 컨테이너에서 Gitea 최신 릴리스 조회 확인), Windows CI (b9431c1, full) 8개 모두 PASS · 앱 버전 1.6.0 → Gitea 릴리스 v1.6.0 (v1.5.0 · v1.4.3 에 새 버전 안내)
## v1.9.0 — 내 Riot 경기 기록 · 경기 탭 필터 · 게임 중 GPU 아끼기 · 리플레이 파일 없음 (2026-11-04)
- 앱: 게임 중이 아닐 때 30분마다 발로란트 match-history · 롤 LCU 기록을 훑어 앱이 잡지 못한 경기를 `source=history` 로 저장 (f9fbf4c) · 게임 중 GPU 아끼기 (발로란트 실행 중 · 롤 경기 중 정밀 모델 내림, 실시간 빔 1 · 발화 사이 쉼, 설정 토글 기본 켜짐, 앱 창 하드웨어 가속 끔, 9e1875b)
- 사이트: 경기 탭 필터 (전체 / 타임라인 있는 경기 / 목소리 녹음된 경기) · 지난 경기 더 보기 (11db2e5), 3D 리플레이 '리플레이 파일 없음' · 새로고침 버튼 (d0371fa). 사이트는 앱보다 먼저 배포
- 배포: Windows CI (b1568db, full) 8개 모두 PASS (변환기 회귀 검사 · 실제 리플레이 crosshairs 10, 앱 smoke 버전 1.9.0 · 실제 변환 11.0초 · gzip 1.60MB) · 앱 버전 1.9.0 → Gitea 릴리스 v1.9.0 (portable.exe 206,687,273 B · win-x64.zip 302,928,085 B, 올린 파일 sha256 일치) (v1.8.2 · v1.8.1 · v1.8.0 에 새 버전 안내)
## v1.8.2 — 3D 리플레이 선수 조준점 · 내 조준점 설정 (2026-10-29)
- 변환기: `BombPlayerState` 에 복제된 선수 조준점 프로필을 두 번째 읽기로 뽑아 `players[].crosshair` (`src/Crosshair.cs`). 어비스 13.08 리플레이 10명 모두, 프로필 이름 "1 4 2 0" = 불투명도 1 · 길이 4 · 두께 2 · 간격 0 으로 값 해독 확인. 두 번째 읽기 +0.4초 (리눅스 6.2초)
- 회귀 검사 `--self-test`: 조준점 필드 자리(13.08 번호 · 2칸 밀린 패치 · 이름 어긋남) · 기본색 · 사용자 지정 색 추가, 통과
- 사이트: 1인칭 "조준점" 버튼 · 설정 창 (선수 조준점 / 모든 선수에 내 조준점, 직접 고치기 · 발로란트 조준점 코드 가져오기 · 선수 조준점 복사). 조준점 코드 읽기 · 시각별 조준점 고르기를 esbuild 로 묶어 node 로 확인
- 테스트: 앱 테스트 통과, 화면 타입 검사 · 빌드 통과
- 화면: 목 서버 + 헤드리스 크롬으로 새 변환 결과 열어 하늘(1 4 2 0 흰 십자) · 상대5(빨강 굵은 십자 + 점) 선수 조준점, 코드 가져오기(초록 · 외곽선 · 점) · 모든 선수에 내 조준점 저장 확인, 콘솔 오류 0
- 배포: 사이트 서버 다시 배포 (화면 번들에 '모든 선수에 내 조준점' 확인), Windows CI (96fb417, full) 8개 모두 PASS (변환기 실제 리플레이 crosshairs 10, 앱 smoke 실제 변환 16.3초 · gzip 1.60MB) · 앱 버전 1.8.2 → Gitea 릴리스 v1.8.2 (v1.8.1 · v1.8.0 · v1.7.0 에 새 버전 안내)
## v1.8.1 — 변환기: 무기 상태의 주인을 그 시각 주인으로 (2026-10-18)
- 고침: 무기 상태(재장전 · 사격 등)의 주인을 장비의 마지막 주인으로 정해, 무기를 넘겨받으면 넘기기 전 상태까지 새 주인 것이 되던 문제 → 인벤토리 기록 시간표에서 상태가 생긴 시각의 주인 (`EquipOwners`)
- 회귀 검사: `gvr-replay --self-test` (넘기기 전 · 넘긴 순간 · 뒤 · 첫 기록 전 · 기록 없음 · 순서 섞임 · 모르는 선수). 옛 동작(마지막 주인)으로 바꾸면 3개 실패하는 것 확인. Windows CI `replay_build` 에서 실행
- 어비스 13.08 리플레이: 상태 16,974줄 중 1,189줄의 주인이 바뀜. 그중 그 시각 그 선수가 같은 무기를 들고 있던 비율 24% → 75%
- Windows CI (a6cf73d, full) 8개 모두 PASS (self-test 통과 포함) → Gitea 릴리스 v1.8.1 (v1.8.0 · v1.7.0 에 새 버전 안내)
## v1.8.0 — 3D 리플레이 실감: 게임 스킬 효과 · 요원 동작 · 투사체 경로 (2026-10-18)
- 스킬 효과 추출기(`abilities`): 13.08 스킬 클래스 219 · 파티클 시스템 526 · 메시 377 · 텍스처 1064, 3.8분, 최대 메모리 1.7GB, 압축 41.8MB. 맵 · 요원 · 애니메이션과 함께 강제 갱신 13.9분 (서비스 최대 메모리 5.6GB, 상한 6GB) → .5 `data/maps3d/VALORANT_13.08-202610171648` (index.json `anims` · `abilities`)
- 테스트: 앱 76 · 사이트 서버 30 통과, 타입 검사 · 화면 빌드 통과
- 화면: 효과 하나씩 그리는 판 + 목 서버(사이트와 같은 CSP 미리보기, 오류 0)로 브림스톤 · 오멘 · 아스트라 · 클로브 · 제트 연막, 브림스톤 · 피닉스 장판, 피닉스 · 케이오 · 브리치 · 스카이 섬광, 소바 화살 · 브림스톤 몰리 꼬리, 체임버 덫 · 소바 드론 · 킬조이 포탑/알람봇 · 사이퍼 덫 확인. 바이퍼 연막 · 세이지 벽처럼 효과를 못 뽑은 것은 예전 기본 모양
- 배포: 사이트 서버 다시 배포 (화면 번들에 vfx 코드 확인), Windows CI (735783c, full) 8개 모두 PASS (변환기 어비스 리플레이 7.0초, 앱 smoke 실제 변환 8.3초 · gzip 1.60MB) · 앱 버전 1.8.0 → Gitea 릴리스 v1.8.0 (v1.7.0 에 새 버전 안내)
## v1.7.0 — 3D 리플레이 완전 3D: 맵 색 · 요원 · 총 · 스킬 모양 · 1인칭/자유시점 (2026-10-17)
- 맵 추출기: 재질 · 텍스처(256px) · 두 층 섞기 · 법선. 22개 맵 9.7분, 받은 양 961MB, 압축 합계 약 255MB (맵당 4~19MB). 요원 30명 · 총 22종 0.9분 (압축 6.4MB · 1.5MB). 갱신 서비스 최대 메모리 5.7GB (상한 6GB)
- 변환기: `equips` · `equipKinds` (13.08 어비스 리플레이: 6,539줄, 총 이름 전부 풀림, 5.9초)
- 테스트: 앱 76 · 사이트 서버 30 통과, 타입 검사 · 화면 빌드 통과
- 화면: 목 서버 + 헤드리스 크롬으로 어비스(텍스처) · 어센트 · 로터스 맵, 요원 몸 · 손에 든 총(밴달 · 클래식 · 오퍼레이터 · 칼), 1인칭 · 자유시점, 연막 색 · 장판 확인
- 배포: 사이트 서버 다시 배포 (화면 번들에 '자유시점' 확인), 맵 3D 강제 갱신으로 .5 `data/maps3d` 에 맵 22 · 요원 30 · 무기 22 반영, Windows CI (4cd6f11, full) 8개 모두 PASS (앱 smoke 실제 리플레이 변환 8.5초, gzip 1.42MB) · 앱 버전 1.7.0 → Gitea 릴리스 v1.7.0 (v1.6.0 에 새 버전 안내)

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -229,7 +229,7 @@ tr.hl td {{ background:#fff3f4 !important; font-weight:700; }}
<h3>AI에 보내는 자료 모양 (예시)</h3>
<pre class="box"><span class="h"># 경기 발로란트 경쟁전 · 어센트 · 13:9 (우리 팀 승리) · 22라운드 · 46분</span>
<span class="h"># 참가자 (번호 이름 팀 요원(역할) K/D/A ACS 라운드당피해 첫킬/첫데스 헤드샷 설치/해체 스킬사용 음성)</span>
P1 승한 우리 제트(타격대) 19/12/7 ACS244 ADR148 첫킬1/첫데스2 HS15% 설치0/해체0 랭크:플래티넘 1 음성O
P1 하늘 우리 제트(타격대) 19/12/7 ACS244 ADR148 첫킬1/첫데스2 HS15% 설치0/해체0 랭크:플래티넘 1 음성O
P5 Duck 우리 킬조이(감시자) 12/15/8 ACS194 ADR92 첫킬2/첫데스2 HS16% 설치0/해체1 랭크:골드 3 음성X
<span class="c">[e1] R1 0:08 킬 P2 → P6 (클래식)</span>
<span class="v">[u1] R3 0:05 P1: 현우야 같이 가 기다려 둘 있어</span>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 633 KiB

After

Width:  |  Height:  |  Size: 632 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 543 KiB

After

Width:  |  Height:  |  Size: 542 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 472 KiB

After

Width:  |  Height:  |  Size: 488 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 752 KiB

After

Width:  |  Height:  |  Size: 760 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 MiB

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 447 KiB

After

Width:  |  Height:  |  Size: 446 KiB

View File

@@ -28,7 +28,7 @@ main{flex:1;display:grid;grid-template-columns:520px 1fr;gap:18px;padding:20px 2
<div class="brand"><img src="../../../../assets/app/icon.png" alt=""><div><div class="nm">겜녹이</div><div class="en">GAME VOICE RECORDER</div></div></div>
<span class="chip">타임라인</span><span class="chip">경기</span><span class="chip">유저</span><span class="chip">단어사전</span><span class="chip on new">🔍 범인찾기</span>
<div class="search">🔍 대화 내용 검색 (예: 스파이크)</div>
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">승</span>승한</div>
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">하</span>하늘</div>
</header>
<main>
<div class="panel list">
@@ -61,7 +61,7 @@ main{flex:1;display:grid;grid-template-columns:520px 1fr;gap:18px;padding:20px 2
</div>
<div class="panel">
<h4><span>참가자 10명</span><span>음성 = 대화 기록 있음</span></h4>
<div class="pl"><img class="ag" src="../../mock/assets/val/a-jett.png">승한 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 제트</span></div>
<div class="pl"><img class="ag" src="../../mock/assets/val/a-jett.png">하늘 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 제트</span></div>
<div class="pl"><img class="ag" src="../../mock/assets/val/a-sova.png">민수 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 소바</span></div>
<div class="pl"><img class="ag" src="../../mock/assets/val/a-sage.png">지우 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 세이지</span></div>
<div class="pl"><img class="ag" src="../../mock/assets/val/a-omen.png">현우 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 오멘</span></div>

View File

@@ -26,7 +26,7 @@ main{padding:12px;display:flex;flex-direction:column;gap:10px}
.p.bad{border-color:#6a2430;background:rgba(255,70,85,.08)}
.sn{font-weight:800}
</style></head><body>
<div class="mh"><div class="brand"><img src="../../../../assets/app/icon.png"><div><div class="nm">겜녹이</div></div></div><span class="chip on new" style="margin-left:auto;font-size:12px;padding:4px 10px">🔍 범인찾기</span><span class="av" style="background:#5865f2;width:26px;height:26px">승</span></div>
<div class="mh"><div class="brand"><img src="../../../../assets/app/icon.png"><div><div class="nm">겜녹이</div></div></div><span class="chip on new" style="margin-left:auto;font-size:12px;padding:4px 10px">🔍 범인찾기</span><span class="av" style="background:#5865f2;width:26px;height:26px">하</span></div>
<main>
<div class="hero">
<div class="h" style="font-size:11px;color:var(--lol);font-weight:800;letter-spacing:2px">범인 분석 · LEAGUE OF LEGENDS</div>
@@ -48,7 +48,7 @@ main{padding:12px;display:flex;flex-direction:column;gap:10px}
<div class="why">라인전에서 다섯 번 죽어 탑 1차·2차 포탑을 15분 안에 내줬다. 바론 한타에 텔레포트 없이 늦게 합류.</div>
</div>
<div class="sec">우리 팀</div>
<div class="p"><img src="../../mock/assets/lol/c-Ahri.png"><div class="b"><div class="l1"><b>승한</b><span class="muted" style="font-size:12px">아리</span><span class="tag done">캐리</span><span class="k"><span class="sn" style="color:var(--ink)">9.0</span> · 11/2/8</span></div><div class="c">바론 한타 매혹 세 명. 콜도 정확했다.</div></div></div>
<div class="p"><img src="../../mock/assets/lol/c-Ahri.png"><div class="b"><div class="l1"><b>하늘</b><span class="muted" style="font-size:12px">아리</span><span class="tag done">캐리</span><span class="k"><span class="sn" style="color:var(--ink)">9.0</span> · 11/2/8</span></div><div class="c">바론 한타 매혹 세 명. 콜도 정확했다.</div></div></div>
<div class="p"><img src="../../mock/assets/lol/c-Thresh.png"><div class="b"><div class="l1"><b>지우</b><span class="muted" style="font-size:12px">쓰레쉬</span><span class="tag ok">숨은 MVP</span><span class="k"><span class="sn" style="color:var(--ink)">7.5</span> · 1/5/19</span></div><div class="c">시야 점수 1위. 용 콜을 가장 먼저 했다.</div></div></div>
<div class="p"><img src="../../mock/assets/lol/c-Ezreal.png"><div class="b"><div class="l1"><b>현우</b><span class="muted" style="font-size:12px">이즈리얼</span><span class="tag wait">무난</span><span class="k"><span class="sn" style="color:var(--ink)">7.0</span> · 8/4/9</span></div><div class="c">안정적. 딜량 팀 2위.</div></div></div>
<div class="p"><img src="../../mock/assets/lol/c-Darius.png"><div class="b"><div class="l1"><b>준호</b><span class="muted" style="font-size:12px">다리우스</span><span class="tag wait">무난</span><span class="k"><span class="sn" style="color:var(--ink)">6.5</span> · 8/5/4</span></div><div class="c">라인전 압승, 한타 진입은 한 박자 빨랐다.</div></div></div>

View File

@@ -41,7 +41,7 @@ main{flex:1;display:flex;flex-direction:column;gap:14px;padding:18px 24px;min-he
<div class="brand"><img src="../../../../assets/app/icon.png" alt=""><div><div class="nm">겜녹이</div><div class="en">GAME VOICE RECORDER</div></div></div>
<span class="chip">타임라인</span><span class="chip">경기</span><span class="chip">유저</span><span class="chip">단어사전</span><span class="chip on new">🔍 범인찾기</span>
<div class="search">🔍 대화 내용 검색 (예: 스파이크)</div>
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">승</span>승한</div>
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">하</span>하늘</div>
</header>
<main>
<div class="hero">
@@ -56,7 +56,7 @@ main{flex:1;display:flex;flex-direction:column;gap:14px;padding:18px 24px;min-he
<div class="lab">우리 팀 범인</div>
<div class="who"><img src="../../mock/assets/val/a-omen.png"><div><div class="nm">현우<small>오멘 · 14 / 19 / 6 · ACS 171</small></div><div class="muted" style="font-size:13px">평점 3.5 / 10</div></div><div class="stamp">범인</div></div>
<div class="why">마지막 네 라운드 중 세 번(R21·R23·R24)을 혼자 B 메인으로 먼저 들어가 첫 데스. 팀이 "기다려"라고 두 번 말했는데 그대로 진입했고, 첫 데스 7회로 팀에서 가장 많다. 스모크도 R22 리테이크에서 늦게 깔려 수적 우위를 잃었다.</div>
<div class="ev"><span class="t">R21 0:22</span><span class="ty v">대화</span><b style="color:var(--u1)">승한</b>&nbsp;현우야 같이 가 기다려 둘 있어<span class="pl">▶ 듣기</span></div>
<div class="ev"><span class="t">R21 0:22</span><span class="ty v">대화</span><b style="color:var(--u1)">하늘</b>&nbsp;현우야 같이 가 기다려 둘 있어<span class="pl">▶ 듣기</span></div>
<div class="ev"><span class="t">R21 0:25</span><span class="ty v">대화</span><b style="color:var(--u4)">현우</b>&nbsp;아 그냥 간다 내가 뚫을게<span class="pl">▶ 듣기</span></div>
<div class="ev"><span class="t">R21 0:29</span><span class="ty k">킬</span>Nox (사이퍼) ▶ 현우 · 첫 데스, 덫에 걸림<span class="pl">타임라인 →</span></div>
<div class="ev"><span class="t">경기 전체</span><span class="ty s">스탯</span>첫 데스 7회 (팀 1위) · 첫 킬 2회<span class="pl">스코어보드 →</span></div>
@@ -67,14 +67,14 @@ main{flex:1;display:flex;flex-direction:column;gap:14px;padding:18px 24px;min-he
<div class="why">10명 중 ACS 가장 낮고, 상대가 이긴 13라운드 중 Kiwi 가 기여(킬·어시스트·생존)한 라운드는 5번뿐. R15 에 혼자 장비를 안 사서 4:5 로 싸웠고, 같은 라운드에 전체 채팅으로 "ff" 를 쳤다. 팀이 이긴 건 Lumi 와 Haru 덕분.</div>
<div class="ev"><span class="t">R15 0:00</span><span class="ty s">경제</span>Kiwi 혼자 900 크레딧 사용 (팀 평균 4,200)<span class="pl">라운드 →</span></div>
<div class="ev"><span class="t">R15 1:12</span><span class="ty c">채팅</span><span class="tag wait" style="font-size:10px">전체</span>&nbsp;<b>Kiwi</b>&nbsp;ff 그냥<span class="pl">타임라인 →</span></div>
<div class="ev"><span class="t">R17 0:41</span><span class="ty k">킬</span>승한 (제트) ▶ Kiwi · 혼자 A 메인 정찰하다 잡힘<span class="pl">타임라인 →</span></div>
<div class="ev"><span class="t">R17 0:41</span><span class="ty k">킬</span>하늘 (제트) ▶ Kiwi · 혼자 A 메인 정찰하다 잡힘<span class="pl">타임라인 →</span></div>
<div class="ev"><span class="t">경기 전체</span><span class="ty s">스탯</span>ACS 132 (10명 중 10위) · 피해량 라운드당 88<span class="pl">스코어보드 →</span></div>
</div>
</div>
<div class="teams">
<div class="panel">
<h4><span>우리 팀 5명 평가</span><span>평점 · 한 줄 평</span></h4>
<div class="row"><img class="ag" src="../../mock/assets/val/a-jett.png"><div class="n"><b>승한</b><span>제트 · 음성 O</span></div><div class="kda"><b>24/15/5</b><br>ACS 272</div><div><div class="sc"><span class="num">8.5</span><span class="bar"><i style="width:85%"></i></span><span class="tag done">캐리</span></div><div class="cm">오퍼레이터 첫 킬 8회. 콜도 가장 많고 정확했다. 후반에 혼자 남아도 끝까지 침착.</div></div></div>
<div class="row"><img class="ag" src="../../mock/assets/val/a-jett.png"><div class="n"><b>하늘</b><span>제트 · 음성 O</span></div><div class="kda"><b>24/15/5</b><br>ACS 272</div><div><div class="sc"><span class="num">8.5</span><span class="bar"><i style="width:85%"></i></span><span class="tag done">캐리</span></div><div class="cm">오퍼레이터 첫 킬 8회. 콜도 가장 많고 정확했다. 후반에 혼자 남아도 끝까지 침착.</div></div></div>
<div class="row"><img class="ag" src="../../mock/assets/val/a-sage.png"><div class="n"><b>지우</b><span>세이지 · 음성 O</span></div><div class="kda"><b>12/16/13</b><br>ACS 168</div><div><div class="sc"><span class="num">7.5</span><span class="bar"><i style="width:75%"></i></span><span class="tag ok">숨은 MVP</span></div><div class="cm">부활 5번 중 3번이 라운드 승리로 이어짐. 킬은 적어도 벽 타이밍이 좋았다.</div></div></div>
<div class="row"><img class="ag" src="../../mock/assets/val/a-sova.png"><div class="n"><b>민수</b><span>소바 · 음성 O</span></div><div class="kda"><b>16/17/9</b><br>ACS 204</div><div><div class="sc"><span class="num">7.0</span><span class="bar"><i style="width:70%"></i></span><span class="tag wait">무난</span></div><div class="cm">정찰 화살 정보 콜이 꾸준했다. R14 리테이크는 민수 드론 정보로 이김.</div></div></div>
<div class="row"><img class="ag" src="../../mock/assets/val/a-phoenix.png"><div class="n"><b>Duck#KR3</b><span>피닉스 · 음성 X</span></div><div class="kda"><b>15/17/4</b><br>ACS 196</div><div><div class="sc"><span class="num">5.5</span><span class="bar"><i style="width:55%"></i></span><span class="tag wait">무난</span></div><div class="cm">음성채널에 없어 기록으로만 봄. 스탯은 평균, 세이브 라운드에 무기를 사서 경제가 두 번 꼬임.</div></div></div>

View File

@@ -2,5 +2,5 @@
<div class="brand"><img src="../../../../assets/app/icon.png" alt=""><div><div class="nm">겜녹이</div><div class="en">GAME VOICE RECORDER</div></div></div>
<span class="chip">타임라인</span><span class="chip">경기</span><span class="chip">유저</span><span class="chip">단어사전</span><span class="chip on new">🔍 범인찾기</span>
<div class="search">🔍 대화 내용 검색 (예: 스파이크)</div>
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">승</span>승한</div>
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">하</span>하늘</div>
</header>

View File

@@ -35,7 +35,7 @@ body{width:1440px;height:810px;overflow:hidden;position:relative;background:#050
<div class="bd">
<h3>이 리플레이의 녹음 기록이 있어요</h3>
<div class="muted" style="font-size:13.5px">리플레이와 동기화하시겠습니까? 리플레이 시간에 맞춰 그때 한 말과 이벤트를 보여 주고 음성을 들려 줍니다.</div>
<div class="m"><img src="../../mock/assets/lol/c-Ahri.png"><div><b style="font-size:15px">소환사의 협곡 · 내전</b> <span class="tag ok" style="background:#0f2a22;color:#7fe0b8;border:1px solid #1d5141;font-size:11px;padding:1px 7px;border-radius:6px;font-weight:700">승리</span><div class="muted" style="font-size:12.5px">10월 15일 21:55 · 38분 · 승한(아리) 외 4명 녹음</div></div></div>
<div class="m"><img src="../../mock/assets/lol/c-Ahri.png"><div><b style="font-size:15px">소환사의 협곡 · 내전</b> <span class="tag ok" style="background:#0f2a22;color:#7fe0b8;border:1px solid #1d5141;font-size:11px;padding:1px 7px;border-radius:6px;font-weight:700">승리</span><div class="muted" style="font-size:12.5px">10월 15일 21:55 · 38분 · 하늘(아리) 외 4명 녹음</div></div></div>
<div class="ck"><i>✓</i>음성 대화 텍스트<span class="v">655문장</span></div>
<div class="ck"><i>✓</i>음성 파일<span class="v">남아 있음 · 10월 22일 삭제 예정</span></div>
<div class="ck"><i>✓</i>킬 · 오브젝트 · 채팅<span class="v">112개</span></div>

View File

@@ -49,19 +49,19 @@ main{flex:1;display:grid;grid-template-columns:1fr 300px;min-height:0}
<main>
<div class="feed">
<div class="it past"><span class="t">7:55</span><div><div class="who" style="color:var(--u3)">지우 <span class="dim" style="font-weight:400">쓰레쉬</span></div><div class="tx">용 쪽 시야 없어 와드 하나 박을게</div></div></div>
<div class="it past"><span class="t">8:05</span><div><div class="who" style="color:var(--u1)">승한 <span class="dim" style="font-weight:400">아리</span></div><div class="tx">미드 밀고 갈게 민수야 용 앞으로 와</div></div></div>
<div class="it past"><span class="t">8:05</span><div><div class="who" style="color:var(--u1)">하늘 <span class="dim" style="font-weight:400">아리</span></div><div class="tx">미드 밀고 갈게 민수야 용 앞으로 와</div></div></div>
<div class="it past"><span class="t">8:12</span><div><div class="who" style="color:var(--u3)">지우 <span class="dim" style="font-weight:400">쓰레쉬</span> <span style="font-size:11px;color:#ff8a94;background:#3a141a;border-radius:5px;padding:1px 6px;margin-left:4px">🔍 범인 근거</span></div><div class="tx">민수야 용 같이 하자 바텀 밀었어</div></div></div>
<div class="nowline">지금 8:21</div>
<div class="it now"><span class="t">8:20</span><div><div class="who" style="color:var(--u2)">민수 <span class="dim" style="font-weight:400">리 신</span> <span style="font-size:11px;color:#ff8a94;background:#3a141a;border-radius:5px;padding:1px 6px;margin-left:4px">🔍 범인 근거</span></div><div class="tx"><span class="w done">아니</span> <span class="w done">탑</span> <span class="w now">갱</span> <span class="w next">각이야</span> <span class="w next">잠깐만</span></div></div><span style="margin-left:auto;color:var(--accent);font-size:13px">🔊 재생 중</span></div>
<div class="it"><span class="t">8:41</span><div><div class="who" style="color:var(--u3)">지우 <span class="dim" style="font-weight:400">쓰레쉬</span></div><div class="tx">아 용 지금 하는데 상대 정글 보여</div></div></div>
<div class="it"><span class="t">8:55</span><div class="ev"><img src="../../mock/assets/lol/c-Sejuani.png"><b>Kiwi</b>&nbsp;▶&nbsp;<img src="../../mock/assets/lol/c-Thresh.png"><b>지우</b><span class="dim">· 어시 Lumi</span></div></div>
<div class="it"><span class="t">9:02</span><div class="ev"><img src="../../mock/assets/lol/o-dragon_ocean.png">상대 팀 <b>바다 드래곤</b> 처치 · Kiwi</div></div>
<div class="it"><span class="t">9:06</span><div><div class="who" style="color:var(--u1)">승한 <span class="dim" style="font-weight:400">아리</span></div><div class="tx">괜찮아 다음 용 준비하자</div></div></div>
<div class="it"><span class="t">9:06</span><div><div class="who" style="color:var(--u1)">하늘 <span class="dim" style="font-weight:400">아리</span></div><div class="tx">괜찮아 다음 용 준비하자</div></div></div>
</div>
<div class="side">
<div><h4>지금 말하는 사람</h4>
<div class="sp talk"><img src="../../mock/assets/lol/c-LeeSin.png">민수<div class="meter"><i style="width:78%"></i></div></div>
<div class="sp"><img src="../../mock/assets/lol/c-Ahri.png">승한<div class="meter"><i style="width:0%"></i></div></div>
<div class="sp"><img src="../../mock/assets/lol/c-Ahri.png">하늘<div class="meter"><i style="width:0%"></i></div></div>
<div class="sp"><img src="../../mock/assets/lol/c-Thresh.png">지우<div class="meter"><i style="width:12%"></i></div></div>
<div class="sp"><img src="../../mock/assets/lol/c-Ezreal.png">현우<div class="meter"><i style="width:0%"></i></div></div>
<div class="sp"><img src="../../mock/assets/lol/c-Darius.png">준호<div class="meter"><i style="width:0%"></i></div></div>

View File

@@ -298,7 +298,7 @@ tr.hl td { background:#fff3f4 !important; font-weight:700; }
<h3>AI에 보내는 자료 모양 (예시)</h3>
<pre class="box"><span class="h"># 경기 발로란트 경쟁전 · 어센트 · 13:9 (우리 팀 승리) · 22라운드 · 46분</span>
<span class="h"># 참가자 (번호 이름 팀 요원(역할) K/D/A ACS 라운드당피해 첫킬/첫데스 헤드샷 설치/해체 스킬사용 음성)</span>
P1 승한 우리 제트(타격대) 19/12/7 ACS244 ADR148 첫킬1/첫데스2 HS15% 설치0/해체0 랭크:플래티넘 1 음성O
P1 하늘 우리 제트(타격대) 19/12/7 ACS244 ADR148 첫킬1/첫데스2 HS15% 설치0/해체0 랭크:플래티넘 1 음성O
P5 Duck 우리 킬조이(감시자) 12/15/8 ACS194 ADR92 첫킬2/첫데스2 HS16% 설치0/해체1 랭크:골드 3 음성X
<span class="c">[e1] R1 0:08 킬 P2 → P6 (클래식)</span>
<span class="v">[u1] R3 0:05 P1: 현우야 같이 가 기다려 둘 있어</span>

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