82 Commits

Author SHA1 Message Date
EJClaw
e8a1c4d5b3 경기 탭 리플레이 필터: 리플레이 있는 경기 / 없는 경기 (게임 PC 에 발로란트 .vrf 가 있는지, GET /api/matches?replay=yes|no · 롤 제외 · 요약에 replay) · 예전 앱이면 업데이트 안내 · 롤을 고르면 숨김 · '필터 초기화' · 목 서버 · 시험 · v1.12.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:49:18 +09:00
EJClaw
1e892d1523 경기 탭: 더 보기 요청 중 새로고침 · 필터 변경하면 늦게 온 더 보기 응답은 버림 (moreGen 세대)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:40:45 +09:00
EJClaw
83cc9d1596 경기 탭 새로고침 버튼 (지금 필터로 첫 쪽부터 다시 받음 · 받는 동안 '불러오는 중…' 으로 잠금, useLoad loading)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:37:54 +09:00
EJClaw
ba45aa8792 v1.11.2 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:08:31 +09:00
EJClaw
d2372283db 게임 연동 탭 Riot ID 칸: 고치는 중에 바뀐 이름은 고치기를 그만두면(입력을 되돌림) 반영 (useEffect 의존성 [server, dirty]) · v1.11.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:53:55 +09:00
EJClaw
977390078e v1.11.1 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:50:06 +09:00
EJClaw
673f2423d5 앱 게임 연동 탭 Riot ID 표: 앱이 유저 목록을 바꾸면(users.updated → state.usersRev) 다시 받고, 고치는 중이 아닌 입력칸은 새 Riot ID 로 맞춤 (탭을 열어 둔 채 자동 갱신된 이름이 보이게) · 목 __gvrMockRename · 시험 · v1.11.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:35:37 +09:00
EJClaw
c86c3ee8de v1.11.0 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:30:39 +09:00
EJClaw
cec5e3537c v1.11.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:15:00 +09:00
EJClaw
5e756f9eb8 Riot ID 자동 갱신 (Riot 클라이언트에 붙으면 바로 · 10분마다 이름 서비스로 연결 계정의 지금 Riot ID 확인, puuid 는 그대로 두고 표시 이름만) · 경기 탭 데스매치 숨김 · 모드(GET /api/matches/modes) · 날짜(after) 필터 (예전 앱은 사이트가 거름) · 범인찾기 목록 데스매치 숨김 · 녹음 없거나 끊긴 경기도 범인찾기 (eligibility.notes, AI 자료에 안내 줄) · Riot 경기 기록 마지막 확인 시각(historyAt) 안내 · 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:14:07 +09:00
EJClaw
8782df2111 v1.10.0 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:07:00 +09:00
EJClaw
dd9564dfc2 v1.10.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:40:45 +09:00
EJClaw
56242cd8ca 맵 자동 갱신 매핑: uedb 가 새 패치 매핑을 늦게 올리면(13.10 패치 11-07, uedb 는 11-20 에도 13.09) valorant-api.com 의 매니페스트가 지금 라이브와 같을 때 그쪽 매핑을 쓴다 (응답 없음 · 다른 매니페스트면 uedb 그대로) · 시험 2개
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:35:45 +09:00
EJClaw
fa9929145e 스킨 목록은 리플레이를 열 때마다 새로 받음 (그사이 뽑힌 스킨이 보이게) · 없는 스킨 요청을 100개씩 나눠 전부 · 맵 · 스킨 타이머를 OnCalendar 로 02:00~07:00 제외 (맵 타이머 Persistent · OnBootSec 뺌) · 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:32:01 +09:00
EJClaw
200dbceece 3D 리플레이 무기 스킨: 뽑아 둔 스킨이면 3인칭 손의 총 · 1인칭 총을 그 모델로 (없거나 못 받으면 기본 총), 없는 스킨은 POST /site/maps3d/skins/want 로 요청 (기본 스킨 · 실패한 것 제외) · 서버 GET /site/maps3d/skins · want.json (형식 검사 · 중복 제거 · 다른 사이트 요청 막음 · 최대 2000) · 목 서버 · 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:28:13 +09:00
EJClaw
0da993928e 맵 텍스처 1024px · 무기 스킨 추출: GVR_TEX 기본 256 → 1024 (원본 대부분 512, 어센트 이미지 8 → 24MB) · gvr-map-extract skins (스킨 · 단계 · 색상 → 단계 블루프린트 부모 사슬 + 색상 재질 교체, 꾸밈 메시 · 칼 NewMesh · 재질만 바꾸는 스킨은 기본 메시, skin3p_/skin1p_<서명>.glb, 모습이 같으면 파일 하나) · skins-update.sh + skins-merge.py (사이트 요청만 3분마다 뽑아 올림, 실패는 패치가 바뀌면 다시) · install.sh 에 gvr-skins-update.timer · update.sh 는 skins/ 를 지우지 않음 · test-skins.sh · 작업 노트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:28:13 +09:00
EJClaw
96f6957422 리플레이 변환기 무기 스킨: 총 · 칼 액터의 SkinDataAsset · SkinLevelDataAsset · ChromaDataAsset · Charm(Level)DataAsset 을 두 번째 읽기로 (첫 읽기 필드 목록에서 이 필드가 있는 무기 클래스를 찾음) · 출력 skins[] {skin, level, chroma, charm, charmLevel} · equips 4번째 열 = 스킨 번호 (같은 총이라도 스킨이 다르면 새 줄) · self-test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:28:13 +09:00
EJClaw
a5a1c8406a 자동 시점 · 점수판 보완: 궁극기 점수는 공수 교대(선수 시작 자리가 40m 넘게 옮겨 간 라운드) 초기화를 사용으로 보지 않음 (한 명만 점수가 있어도) · 전략 보기 카메라 거리를 시야각 · 화면비 · 기울기로 계산해 모든 선수가 화면 안 (fitDistance) · 라운드가 끝난 뒤 점수판 팀 점수는 그 라운드까지 (최종 점수) · 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:54:41 +09:00
EJClaw
c36db3ef9a 3D 리플레이 자동 시점 · Tab 점수판: 카메라 "자동"(교전 직전에 이긴 선수 1인칭, 직전 우리 팀 콜이 있으면 그 말부터 · 설치/해체 · 혼자 남은 선수 · 교전이 없으면 살아 있는 선수가 다 보이게 위에서) · Tab 을 누르고 있으면 게임처럼 팀 점수 · 궁극기 · K/D/A · 주무기 · 크레딧 · 변환기 scoreboard (크레딧 · 궁 점수 · 킬/데스/어시 · 전투 점수, BasicCombatStats · PlayerScore 하위 객체 읽기) · self-test · 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:46:54 +09:00
EJClaw
c539c2b9dc v1.9.1 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:58:01 +09:00
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
147 changed files with 19242 additions and 259 deletions

View File

@@ -8,7 +8,7 @@
- 설계·계획: [`docs/gemnoki-project-plan.pdf`](docs/gemnoki-project-plan.pdf), 개발 구조·인터페이스: [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
- 범인찾기 · 리플레이 동기화 계획서 v1.2 (결정 반영): [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf) · 원본 · 비용 계산 · 프롬프트 초안: `docs/report/culprit/` (실제로 쓰는 프롬프트는 `site/server/prompt/`)
- **제작 완료 보고서 (M0~M8)**: [`docs/gemnoki-final-report.pdf`](docs/gemnoki-final-report.pdf) · 단계별 테스트 기록: [`docs/dev/test-results.md`](docs/dev/test-results.md)
- Windows 실행 파일: Gitea 릴리스 [v1.3.7](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.7) (`GameVoiceRecorder-1.3.7-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.7-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)
- Windows 실행 파일: Gitea 릴리스 [v1.11.2](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.11.2) (`GameVoiceRecorder-1.11.2-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.11.2-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,52 @@
- 앱은 시작할 때와 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`

10
app/package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "gvr-app",
"version": "1.3.7",
"version": "1.12.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gvr-app",
"version": "1.3.7",
"version": "1.12.0",
"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.7",
"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.7",
"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.7",
"version": "1.12.0",
"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",

View File

@@ -3,13 +3,28 @@ import fs from 'node:fs';
import path from 'node:path';
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 { HIDDEN_MODE } from '../games/modes.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;
@@ -24,6 +39,10 @@ export interface ApiDeps {
version: string;
/** 기록 묶음 (없으면 /api/bundles 없음) */
bundles?: Bundles;
/** 발로란트 리플레이 (없으면 /api/replays 없음) */
replays?: Replays;
/** 사이트 서버가 새 표시 이름을 보내 왔을 때 (녹음 파일 이름 다시 맞추기) */
onNamesChanged?: () => void;
}
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
@@ -102,6 +121,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 = {
@@ -171,6 +231,17 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
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);
@@ -247,10 +318,33 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
app.get<{ Querystring: Record<string, string> }>('/api/matches', async (req) => {
const q = req.query;
// 리플레이 필터 (v1.12.0): yes = 이 PC 에 리플레이 파일(.vrf)이 있는 발로란트 경기, no = 없는 발로란트 경기
const replay = q.replay === 'yes' || q.replay === 'no' ? q.replay : undefined;
if (replay && q.game && q.game !== 'valorant') return [];
const replayIds = d.replays ? d.replays.list().map((r) => `val-${r.matchId}`) : [];
const hasReplay = new Set(replayIds);
return store
.listMatches({ game: q.game || undefined, before: q.before ? Number(q.before) : undefined, limit: q.limit ? Math.min(Number(q.limit), 200) : 50 })
.map((m) => d.games.summary(m));
.listMatches({
game: replay ? 'valorant' : q.game || undefined,
ids: replay === 'yes' ? replayIds : undefined,
skipIds: replay === 'no' ? replayIds : undefined,
before: q.before ? Number(q.before) : undefined,
after: q.after ? Number(q.after) : 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,
// 모드 필터 (v1.11.0, 모드 이름 "경쟁전" 등) · 데스매치는 늘 뺀다
onlyModes: q.mode ? d.games.modeKeys((name) => name === q.mode) : undefined,
skipModes: d.games.modeKeys((name) => name === HIDDEN_MODE),
})
.map((m) => {
const s = d.games.summary(m);
if (d.replays && m.game === 'valorant') s.replay = hasReplay.has(m.id);
return s;
});
});
// 모드 필터 목록 (v1.11.0): 모드 이름별 경기 수
app.get<{ Querystring: Record<string, string> }>('/api/matches/modes', async (req) => d.games.modeList(req.query.game || undefined));
app.get<{ Params: { id: string } }>('/api/matches/:id', async (req, reply): Promise<MatchDetail | void> => {
const m = store.getMatch(req.params.id);
@@ -297,6 +391,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' });
@@ -321,6 +440,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

@@ -49,6 +49,8 @@ export class Bundles {
private games: GameManager,
private audioDir: () => string,
private version: string,
/** 받아온 발화들 (녹음 파일 이름 맞추기) */
private afterImport?: (ids: string[]) => void,
) {}
private groups(): Group[] {
@@ -73,6 +75,8 @@ export class Bundles {
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}` : '';
@@ -231,7 +235,8 @@ export class Bundles {
delete (rest as any).rowid;
let audio: string | null = null;
if (audio_path && !u.audio_deleted && fs.existsSync(audio_path)) {
audio = `audio/${u.id}.ogg`;
// zip 안에서도 알아볼 수 있게 녹음 파일 이름 그대로 (날짜 · 시각 · 말한 사람 · 게임 · 라운드 · 발화 ID)
audio = `audio/${path.basename(audio_path)}`;
entries.push({ name: audio, data: fs.readFileSync(audio_path) });
}
return { ...rest, audio };
@@ -298,6 +303,7 @@ export class Bundles {
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) {
@@ -310,8 +316,8 @@ export class Bundles {
if (s?.id) db.prepare('INSERT OR IGNORE INTO sessions(id,guild_id,channel_id,channel_name,started_at,ended_at) VALUES(?,?,?,?,?,?)').run(s.id, String(s.guild_id ?? ''), String(s.channel_id ?? ''), s.channel_name ?? null, Number(s.started_at) || 0, s.ended_at ?? null);
for (const m of data.matches ?? []) {
const r = db
.prepare('INSERT OR IGNORE INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset) VALUES(?,?,?,?,?,?,?,?,?,?,?)')
.run(m.id, m.game, m.started_at, m.ended_at ?? null, m.map ?? null, m.mode ?? null, m.queue ?? null, m.result ?? null, m.detail ?? null, m.status === 'live' ? 'complete' : (m.status ?? 'complete'), Number(m.clock_offset) || 0);
.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 ?? [])
@@ -359,6 +365,7 @@ export class Bundles {
);
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) {
@@ -366,6 +373,11 @@ export class Bundles {
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;
}
@@ -417,6 +429,7 @@ export function validate(files: Map<string, Buffer>, store?: Store): { manifest:
}
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} 가 두 번 들어 있습니다`);
@@ -426,7 +439,12 @@ export function validate(files: Map<string, Buffer>, store?: Store): { manifest:
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) {
if (u.audio !== `audio/${u.id}.ogg`) fail(`발화 ${u.id} 의 음성 파일 이름이 잘못되었습니다`);
// 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 가 아닙니다`);

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

@@ -14,6 +14,7 @@ import type {
import { rateLol, rateValorant } from '@gvr/shared';
import type { EventRow, MatchRow, Store, UtteranceRow } from './db/db.js';
import type { GameManager } from './games/manager.js';
import { HIDDEN_MODE } from './games/modes.js';
import { safeJson, type Timeline } from './timeline.js';
/**
@@ -23,6 +24,7 @@ import { safeJson, type Timeline } from './timeline.js';
/** 녹음 공백 허용치: 경기 처음 · 끝 · 중간에 이보다 긴 빈 곳이 있으면 "기록 부족" */
export const COVERAGE_GAP_MS = 60000;
const NO_RECORDING = '녹음 기록이 없습니다';
/** 대화가 이보다 많으면 짧은 잡담부터 줄여서 보낸다 (경기당 비용 상한, 계획서 7장) */
export const MAX_UTTERANCES = 2500;
@@ -57,17 +59,22 @@ export class Culprit {
const players: any[] = det.players || [];
const gotResult = !det.live && players.length >= 2 && (m.game !== 'valorant' || (det.roundsDetail || []).length > 0);
if (!gotResult) reasons.push('경기 결과를 받지 못했습니다');
const start = realStart(m);
const end = m.ended_at;
const gap = this.coverageGap(start, end);
if (gap) reasons.push(gap);
// 녹음이 없거나 끊긴 경기도 분석한다 (v1.11.0, 앱을 켜지 않고 한 경기): 플레이 기록 · 채팅과 녹음된 대화만 쓴다
const notes = this.recordingNotes(m);
const pending = (
this.store.db.prepare(`SELECT count(*) n FROM utterances WHERE match_id=? AND status='pending' AND audio_deleted=0`).get(m.id) as { n: number }
).n;
if (reasons.length) return { state: 'blocked', reasons };
if (pending) return { state: 'pending', reasons: [`음성 변환 중 (${pending}문장 남음)`] };
if (this.current(m.id)) return { state: 'done', reasons: [] };
return { state: 'ready', reasons: [] };
if (pending) return { state: 'pending', reasons: [`음성 변환 중 (${pending}문장 남음)`], notes };
if (this.current(m.id)) return { state: 'done', reasons: [], notes };
return { state: 'ready', reasons: [], notes };
}
/** 녹음이 경기를 다 덮지 못하면 알림 문장 (분석은 그대로 한다) */
private recordingNotes(m: MatchRow): string[] {
const gap = m.ended_at ? this.coverageGap(realStart(m), m.ended_at) : null;
if (!gap) return [];
return [gap === NO_RECORDING ? '녹음 없음: 플레이 기록 · 채팅으로만 분석합니다' : `${gap}: 녹음된 대화만 씁니다`];
}
/** 녹음(봇이 음성채널에 있던 구간)이 경기를 덮는지. 빈 곳이 1분 넘으면 이유 문장, 아니면 null */
@@ -75,7 +82,7 @@ export class Culprit {
const sess = this.store.db
.prepare('SELECT started_at, ended_at FROM sessions WHERE started_at < ? AND (ended_at IS NULL OR ended_at > ?) ORDER BY started_at')
.all(end, start) as { started_at: number; ended_at: number | null }[];
if (!sess.length) return '녹음 기록이 없습니다';
if (!sess.length) return NO_RECORDING;
let cursor = start;
let worst: { at: number; ms: number } | null = null;
for (const s of sess) {
@@ -93,7 +100,9 @@ export class Culprit {
// ---------------------------------------------------------------- 목록 · 상세
list(opts: { game?: string; limit?: number }): CulpritMatchItem[] {
const rows = this.store.listMatches({ game: opts.game, limit: Math.min(opts.limit ?? 50, 200) }).filter((m) => m.status !== 'live');
const rows = this.store
.listMatches({ game: opts.game, limit: Math.min(opts.limit ?? 50, 200), skipModes: this.games.modeKeys((name) => name === HIDDEN_MODE) })
.filter((m) => m.status !== 'live');
return rows.map((m) => {
const cur = this.current(m.id);
const elig = this.eligibility(m);
@@ -219,6 +228,9 @@ export class Culprit {
out.push(`# 경기 리그 오브 레전드 ${sum.mode} · ${sum.map.name} · 킬 ${score} (${resultKo}) · ${minutes}분`);
}
if (basic) out.push('# 이 경기는 기본 기록만 있다 (피해량 · 첫킬 · 시야 같은 추가 지표 없음)');
const gap = m.ended_at ? this.coverageGap(realStart(m), m.ended_at) : null;
if (gap === NO_RECORDING) out.push('# 이 경기는 음성 녹음이 없다. 모두 음성X 로 보고 플레이 기록과 채팅으로만 평가한다');
else if (gap) out.push(`# ${gap}. 녹음이 빠진 구간의 대화는 없다`);
if (totalUtts > utts.length) out.push(`# 대화가 많아 ${totalUtts}문장 중 짧은 말을 빼고 ${utts.length}문장만 보냄`);
// 참가자

View File

@@ -38,6 +38,12 @@ export interface UtteranceRow {
attempts: number;
created_at: number;
}
/** 경기 모드를 가르는 칸 조합 (모드 이름은 games/modes.ts matchModeKo) */
export interface ModeKey {
game: string;
queue: string | null;
mode: string | null;
}
export interface MatchRow {
id: string;
game: 'valorant' | 'lol';
@@ -50,6 +56,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 +95,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 +136,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)) {
@@ -212,6 +252,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);
@@ -223,6 +267,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);
@@ -350,13 +417,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`,
)
@@ -366,9 +434,43 @@ 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 = 목소리가 녹음된 경기
*/
/**
* onlyModes = 이 (게임, 큐, 모드) 조합만 · skipModes = 이 조합은 빼고 (경기 탭 모드 필터 · 데스매치 숨기기, v1.11.0).
* after = 이 시각 이후에 시작한 경기만 (날짜 필터)
*/
listMatches(opts: {
game?: string;
before?: number;
after?: number;
limit?: number;
ids?: string[];
/** 이 경기들은 빼고 (리플레이 없는 경기 필터, v1.12.0) */
skipIds?: string[];
has?: 'timeline' | 'voice';
onlyModes?: ModeKey[];
skipModes?: ModeKey[];
}): MatchRow[] {
const where: string[] = [];
const args: any[] = [];
const modeCond = (keys: ModeKey[]) => {
args.push(...keys.flatMap((k) => [k.game, k.queue, k.mode]));
return `(${keys.map(() => '(game=? AND queue IS ? AND mode IS ?)').join(' OR ')})`;
};
if (opts.onlyModes) {
if (!opts.onlyModes.length) return [];
where.push(modeCond(opts.onlyModes));
}
if (opts.skipModes?.length) where.push(`NOT ${modeCond(opts.skipModes)}`);
if (opts.after) {
where.push('started_at>=?');
args.push(opts.after);
}
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);
@@ -382,10 +484,18 @@ export class Store {
where.push(`id IN (${opts.ids.map(() => '?').join(',')})`);
args.push(...opts.ids);
}
if (opts.skipIds?.length) {
where.push(`id NOT IN (${opts.skipIds.map(() => '?').join(',')})`);
args.push(...opts.skipIds);
}
return this.db
.prepare(`SELECT * FROM matches ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY started_at DESC LIMIT ?`)
.all(...args, opts.limit ?? 50) as MatchRow[];
}
/** 경기 행의 (게임, 큐, 모드) 조합과 경기 수 */
matchModeRows(): (ModeKey & { n: number })[] {
return this.db.prepare('SELECT game, queue, mode, count(*) n FROM matches GROUP BY game, queue, mode').all() as (ModeKey & { n: number })[];
}
/** ts 시점에 진행 중이던 경기 */
matchAt(ts: number): MatchRow | undefined {
return this.db
@@ -482,6 +592,43 @@ 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 WHERE noise=0 OR corrected=1').get() as any).n;

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);
@@ -142,3 +144,12 @@ 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

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

View File

@@ -19,6 +19,8 @@ export interface RecorderOptions {
skip: (userId: string) => boolean;
/** ts 시점 진행 중인 경기 ID */
matchAt: (ts: number) => string | null;
/** 저장 직후 (녹음 파일 이름을 날짜 · 말한 사람 · 게임 · 라운드로 바꾼다) */
onSaved?: (id: string) => void;
}
/** RTP 시각 (48kHz 샘플 단위 타임스탬프 + 순번) */
@@ -198,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,
@@ -207,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

@@ -0,0 +1,164 @@
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();
}
/** 마지막으로 끝까지 확인한 때 (사이트 경기 탭 안내, v1.11.0). 아직 없으면 null */
lastDoneAt(): number | null {
return Number(this.store.meta(this.lastKey())) || null;
}
private lastKey(): string {
return `history_last:${this.src.game}`;
}
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');
this.store.setMeta(this.lastKey(), String(Date.now()));
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

@@ -5,6 +5,7 @@ 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');
@@ -71,8 +72,42 @@ export class LolAdapter implements GameAdapter {
/** 게임 클라이언트 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) {}
constructor(private host: AdapterHost) {
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 {
if (this.timer) return;
@@ -87,6 +122,10 @@ export class LolAdapter implements GameAdapter {
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;
@@ -127,6 +166,8 @@ export class LolAdapter implements GameAdapter {
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(),
historyAt: this.history.lastDoneAt(),
updatedAt: Date.now(),
};
}
@@ -442,6 +483,7 @@ 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 ?? ''}`;
}
}
@@ -459,6 +501,7 @@ export class LolAdapter implements GameAdapter {
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,5 +1,5 @@
import type { LiveGame, MatchSummary } from '@gvr/shared';
import type { EventRow, MatchRow, Store } from '../db/db.js';
import type { EventRow, MatchRow, ModeKey, Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { SttPipeline } from '../stt/pipeline.js';
import type { WorkerClient } from '../stt/worker.js';
@@ -11,13 +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';
import { HIDDEN_MODE, matchModeKo } 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,
@@ -60,12 +67,33 @@ export class GameManager implements AdapterHost {
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;
@@ -96,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;
@@ -107,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);
}
@@ -117,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);
}
@@ -154,6 +199,41 @@ export class GameManager implements AdapterHost {
}
}
renameAccounts(names: { puuid: string; riotId: string }[]): number {
let n = 0;
for (const x of names) {
if (!/^[^#]{1,32}#[^#]{1,8}$/.test(x.riotId)) continue;
const old = this.store.listAccounts().find((a) => a.puuid === x.puuid && a.riot_id !== x.riotId);
if (!old) continue;
n += this.store.db.prepare('UPDATE game_accounts SET riot_id=? WHERE puuid=? AND riot_id<>?').run(x.riotId, x.puuid, x.riotId).changes;
log.info(`Riot ID 바뀜: ${old.riot_id} → ${x.riotId}`);
}
if (n) this.bus.live({ type: 'users.updated', data: [] });
return n;
}
/** 모드 이름이 맞는 (게임, 큐, 모드) 조합 (경기 목록 모드 필터 · 데스매치 숨기기) */
modeKeys(pick: (name: string, game: string) => boolean): ModeKey[] {
return this.store
.matchModeRows()
.filter((r) => pick(matchModeKo(r), r.game))
.map(({ game, queue, mode }) => ({ game, queue, mode }));
}
/** 경기 탭 모드 필터 목록: 모드 이름별 경기 수, 많은 것부터. 데스매치는 경기 목록에 나오지 않아 뺀다 */
modeList(game?: string): { game: string; mode: string; count: number }[] {
const by = new Map<string, { game: string; mode: string; count: number }>();
for (const r of this.store.matchModeRows()) {
const mode = matchModeKo(r);
if (mode === HIDDEN_MODE || (game && r.game !== game)) continue;
const k = `${r.game}\n${mode}`;
const cur = by.get(k) ?? { game: r.game, mode, count: 0 };
cur.count += r.n;
by.set(k, cur);
}
return [...by.values()].sort((a, b) => b.count - a.count || a.mode.localeCompare(b.mode));
}
summary(m: MatchRow): MatchSummary {
const result = safeJson<{ win: boolean | null; score: { ally: number; enemy: number } | null }>(m.result, { win: null, score: null });
const map = m.game === 'valorant' ? this.assets.valMap(m.map) : null;
@@ -169,11 +249,13 @@ export class GameManager implements AdapterHost {
m.game === 'valorant'
? { id: m.map ?? '', name: map?.name ?? m.map ?? '?', image: map?.image ?? null }
: { id: m.map ?? 'Map11', name: '소환사의 협곡', image: this.assets.lolMapImage() },
mode: modeKo(m),
mode: matchModeKo(m),
win: result.win,
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),
};
}
@@ -182,8 +264,3 @@ export class GameManager implements AdapterHost {
if (m) this.bus.live({ type: 'match.updated', data: this.summary(m) });
}
}
function modeKo(m: MatchRow): string {
const q = m.queue || m.mode || '';
return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드');
}

View File

@@ -32,3 +32,12 @@ export function lolModeKo(queue: string | number | null | undefined): string | n
export function valNoRounds(queue: string | null | undefined): boolean {
return ['deathmatch', 'hurm', 'ggteam', 'snowball'].includes((queue || '').toLowerCase());
}
/** 경기 목록 · 범인찾기 목록에 보이지 않는 모드 (연습용 데스매치, v1.11.0) */
export const HIDDEN_MODE = '데스매치';
/** 경기 행의 모드 이름 (경기 목록 · 모드 필터) */
export function matchModeKo(m: { game: string; queue: string | null; mode: string | null }): string {
const q = m.queue || m.mode || '';
return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드');
}

View File

@@ -3,6 +3,7 @@ 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;
@@ -21,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;
@@ -32,6 +35,8 @@ export interface AdapterHost {
selfAccount(puuid: string, riotId: string): void;
/** 경기 참가자 Riot ID 로 디스코드 유저 연결 갱신 */
resolvePlayers(players: { puuid: string; riotId: string }[]): void;
/** Riot 이름 서비스가 알려 준 지금 Riot ID 로 연결된 계정 이름을 바꾼다 (닉네임 · 태그를 바꾼 사람). 바꾼 수 */
renameAccounts(names: { puuid: string; riotId: string }[]): number;
}
export interface GameAdapter {
@@ -39,6 +44,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

@@ -5,6 +5,7 @@ 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');
@@ -76,8 +77,53 @@ export class ValorantAdapter implements GameAdapter {
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
private polling = false;
private lastErr = '';
/** 연결된 계정 Riot ID 를 마지막으로 확인한 때 (닉네임 · 태그 바꾼 사람) */
private namesAt = 0;
/** 내 경기 기록 (앱이 꺼져 있을 때 한 경기도 경기 목록에) */
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;
@@ -91,6 +137,10 @@ 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;
@@ -136,6 +186,8 @@ export class ValorantAdapter implements GameAdapter {
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(),
historyAt: this.history.lastDoneAt(),
updatedAt: Date.now(),
};
}
@@ -206,9 +258,14 @@ 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);
await this.refreshNames(a);
}
} else {
this.presence = null;
// 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다
this.endMatch();
if (this.match) this.endMatch();
}
await this.pollDetails();
this.lastErr = '';
@@ -372,6 +429,25 @@ export class ValorantAdapter implements GameAdapter {
}
}
/**
* 디스코드 유저에 연결된 Riot 계정의 지금 Riot ID 를 이름 서비스로 확인한다 (Riot 클라이언트에 붙은 뒤 바로, 그 뒤 10분마다).
* 닉네임이나 태그를 바꾼 사람은 연결은 그대로(puuid) 두고 표시되는 Riot ID 만 새 이름으로 바꾼다.
* 아직 경기에서 만나지 못한 계정(riotid: 자리표시)은 puuid 를 몰라 물을 수 없다.
*/
private async refreshNames(a: Auth): Promise<void> {
if (Date.now() - this.namesAt < (Number(process.env.GVR_NAMES_EVERY_MS) || 10 * 60000)) return;
this.namesAt = Date.now();
const puuids = [...new Set(this.host.store.listAccounts().map((x) => x.puuid))].filter((p) => p && !p.startsWith('riotid:') && !p.includes('#'));
if (!puuids.length) return;
try {
const r = await request(`${this.pd(a)}/name-service/v2/players`, { method: 'PUT', headers: this.pvpHeaders(a), body: puuids, timeoutMs: 8000 });
if (r.status !== 200 || !Array.isArray(r.data)) return void log.debug(`Riot ID 확인 실패 (${r.status})`);
this.host.renameAccounts(r.data.filter((n: any) => n?.Subject && n.GameName && n.TagLine).map((n: any) => ({ puuid: n.Subject, riotId: `${n.GameName}#${n.TagLine}` })));
} catch (e) {
log.debug('Riot ID 확인 실패', e);
}
}
/**
* 경기 상세에 선수 이름이 비어 오면(Riot 이 이름을 가림) 이름 서비스로 채운다. 내 이름은 로컬 채팅 세션 값으로.
* v1.3.5 는 빈 이름을 그대로 써서 "주인 계정 자동 연결: #" 이 남았다.

View File

@@ -3,6 +3,7 @@ import path from 'node:path';
import type { FastifyInstance } from 'fastify';
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';
@@ -13,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';
@@ -36,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>>;
@@ -68,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,
@@ -79,6 +84,7 @@ 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);
@@ -88,6 +94,7 @@ export async function startCore(opts: CoreOptions) {
});
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,
@@ -98,7 +105,9 @@ export async function startCore(opts: CoreOptions) {
settings: S,
trainingDir: () => paths().training,
version: opts.version,
bundles: new Bundles(store, games, () => paths().audio, 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: {
@@ -123,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();
@@ -159,6 +177,7 @@ export async function startCore(opts: CoreOptions) {
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);
@@ -170,11 +189,12 @@ export async function startCore(opts: CoreOptions) {
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

@@ -59,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) {
@@ -155,12 +161,13 @@ export class RelayClient {
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: bin ?? req.body ?? undefined });
const outHeaders: Record<string, string> = {};
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length', 'content-disposition']) {
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') || ct.startsWith('application/zip')) {
// 압축한 본문(리플레이 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);

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

@@ -33,6 +33,8 @@ export interface Settings {
modelsDir: string | null;
reprocessAfterMatch: boolean;
gameVramReserveMb: number;
/** 게임이 켜져 있는 동안 GPU 를 아낀다: 실시간 모델만 가볍게(빔 1) · 쉬어 가며, 정밀 모델 변환은 게임을 끈 뒤로 (v1.9.0) */
gameSaver: boolean;
};
audio: {
targetLufs: number;
@@ -111,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,5 +1,5 @@
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';
@@ -10,11 +10,44 @@ 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';
@@ -25,6 +58,8 @@ interface Job {
prio: number;
/** 예전 녹음 고친 뒤 다시 변환: 잡음으로 나오면 이전 결과를 지키고, 정밀 결과로만 덮는다 */
repair?: boolean;
/** 이미 정밀 모델로 변환한 발화도 다시 변환한다 (잡음으로 나오면 잡음으로 숨김) */
redo?: boolean;
}
export interface SttStatus {
@@ -46,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 = {
@@ -90,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);
@@ -144,16 +239,17 @@ 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, repair = false): 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, ...(repair ? { repair } : {}) });
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();
@@ -169,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);
@@ -178,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';
@@ -186,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];
@@ -196,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 {
@@ -236,10 +359,11 @@ export class SttPipeline {
this.store.markUtteranceFailed(u.id);
return;
}
if (job.slot === 'precise' && (u.corrected || (u.status === 'precise' && !job.repair))) 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>(
@@ -247,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),
@@ -255,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}`);
@@ -270,6 +399,14 @@ 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;
@@ -358,11 +495,55 @@ export class SttPipeline {
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();

View File

@@ -173,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) {
// 선택하지 않은 (디스코드에 연결된) 유저가 주인공인 이벤트만 뺀다. 라운드·오브젝트·상대 킬처럼 유저가 없는 이벤트는 남긴다.

View File

@@ -5,8 +5,11 @@ import type { LiveEvent, User } from '@gvr/shared';
export class Bus extends EventEmitter {
/** 'users.updated' 에 실을 유저 목록. 보내는 쪽은 신호만 주고 목록은 여기서 채운다 (빈 목록이 나가면 사이트에서 모든 발화가 "알 수 없음"이 됨) */
usersProvider: (() => User[]) | null = null;
/** 'users.updated' 를 보낸 횟수: 앱 설정 창이 바뀐 것을 알고 유저 목록을 다시 받는다 (Riot ID 자동 갱신 등, v1.11.1) */
usersRev = 0;
live(ev: LiveEvent): void {
if (ev.type === 'users.updated') this.usersRev++;
if (ev.type === 'users.updated' && this.usersProvider) ev = { type: 'users.updated', data: this.usersProvider() };
this.emit('live', ev);
}

View File

@@ -69,6 +69,8 @@ export interface AppState {
/** 지금 게임 상태 (v1.3.6~) */
liveGames?: LiveGame[];
counts: { utterances: number; matches: number };
/** 유저 목록이 바뀐 횟수 (바뀌면 게임 연동 탭 Riot ID 표를 다시 받는다, v1.11.1) */
usersRev: number;
excludedUsers: { id: string; name: string }[];
autoStart: boolean;
}
@@ -110,6 +112,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

@@ -33,6 +33,7 @@ export function buildState(core: Core, opts: { dataDir: string; portable: boolea
games: core.games.status() as AppState['games'],
liveGames: core.games.live(),
counts: core.store.counts(),
usersRev: core.bus.usersRev,
excludedUsers: core.store
.listUsers()
.filter((u) => u.excluded)
@@ -241,13 +242,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: [] });

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'));
@@ -148,6 +151,7 @@ function closeSplash(): void {
}
function updateTray(): void {
const tray = trayShell.get();
if (!tray) return;
if (!core) {
tray.setImage(trayImage('off'));
@@ -168,6 +172,7 @@ function updateTray(): void {
}
function buildTrayMenu(): void {
const tray = trayShell.get();
if (!tray) return;
if (!core) {
tray.setContextMenu(
@@ -203,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);
}
@@ -217,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) => {
@@ -244,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;
@@ -277,7 +294,11 @@ async function syncNames(): Promise<void> {
if (!c || !auth?.ok) return;
try {
const names = await auth.displayNames();
if (core === c) c.store.setDisplayNames(names);
if (core === c) {
c.store.setDisplayNames(names);
// 녹음 파일 이름에도 표시 이름을 쓴다
c.audioNames.refreshAll();
}
} catch (e: any) {
log.warn(`표시 이름을 받지 못했습니다: ${e?.message ?? e}`);
}
@@ -289,7 +310,7 @@ function startApp(): Promise<void> {
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);
@@ -361,25 +382,26 @@ 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().then(syncNames);
}
}, 15000);
setInterval(() => {
});
trayShell.every(1500, () => {
updateTray();
buildTrayMenu();
pushState();
}, 1500);
});
splashText('로그인 확인 중…');
await first;
if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…');

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,7 +4,7 @@ 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', 'adminDisplayNames', 'adminSetDisplayName',

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

@@ -35,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: {
@@ -167,10 +168,12 @@ export function createMockGvr(): GvrApi {
},
{
game: 'lol', enabled: true, connected: true, phase: '로비', inMatch: false, matchId: null, mode: '솔로 랭크', map: null, mapImage: null,
startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: null, characterImage: null, kda: null, extra: null }, players: null, error: null, updatedAt: now,
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 },
usersRev: 0,
excludedUsers: noToken ? [] : [{ id: 'u4', name: '현우' }],
autoStart: false,
};
@@ -250,6 +253,14 @@ export function createMockGvr(): GvrApi {
listeners.forEach((l) => l(snap));
};
// 앱이 Riot ID 를 바꾼 것 흉내 (닉네임 · 태그를 바꾼 사람): 콘솔에서 __gvrMockRename('u1', '새이름#KR9')
(window as any).__gvrMockRename = (userId: string, riotId: string) => {
const u = users.find((x) => x.id === userId);
if (u?.riot[0]) u.riot[0].riotId = riotId;
state.usersRev++;
emit();
};
// 녹음 참가자/대기열이 조금씩 바뀌는 흉내
setInterval(() => {
state.stt.queue = Math.random() < 0.7 ? 0 : Math.floor(Math.random() * 3);
@@ -518,6 +529,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; }

View File

@@ -1,5 +1,5 @@
import { useState } from 'react';
import { GAME_NAME, liveGameRows, type LiveGame, type User } from '@gvr/shared';
import { useEffect, useState } from 'react';
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, Page, Section, Spinner, Toggle } from '../ui';
@@ -84,12 +84,51 @@ function LiveGames() {
);
}
/** 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 }) {
const { toast } = useApp();
const server = u.riot.map((r) => r.riotId).join(',');
const [v, setV] = useState(u.riot.map((r) => r.riotId).join(', '));
const [saved, setSaved] = useState(u.riot.map((r) => r.riotId).join(','));
const [saved, setSaved] = useState(server);
const act = useAction();
const ids = v
.split(',')
@@ -97,6 +136,14 @@ function RiotRow({ u }: { u: User }) {
.filter(Boolean);
const bad = ids.filter((s) => !RIOT_RE.test(s));
const dirty = ids.join(',') !== saved;
// 앱이 Riot ID 를 바꾸면(닉네임 · 태그를 바꾼 사람, v1.11.1) 입력칸도 새 값으로. 고치는 중인 칸은 그대로 두고,
// 고치기를 그만두면(입력을 원래대로 되돌림) 그사이 바뀐 이름을 반영한다 (v1.11.2)
useEffect(() => {
if (server === saved || dirty) return;
setV(u.riot.map((r) => r.riotId).join(', '));
setSaved(server);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [server, dirty]);
const savedCount = saved ? saved.split(',').length : 0;
const commit = async () => {
if (!dirty || bad.length) return;
@@ -172,12 +219,14 @@ function RiotKey() {
}
export function GamesTab() {
const { settings, save } = useApp();
const { settings, save, state } = useApp();
const g = settings.games;
const users = useLoad(() => gvr.users());
// 앱이 유저 목록을 바꾸면(Riot ID 자동 갱신 · 녹음 중 새 사람 등) 다시 받는다
const users = useLoad(() => gvr.users(), [state.usersRev]);
return (
<Page title="게임 연동">
<GameCards />
<HistoryImport />
<LiveGames />
<Section title="리그 오브 레전드 세부 설정" className={g.lol ? '' : 'disabled'}>
<div className="muted" style={{ marginBottom: 8 }}>

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

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

@@ -296,6 +296,29 @@ test('users.updated: 보내는 쪽이 빈 목록을 줘도 실제 유저 목록
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);

View File

@@ -49,8 +49,9 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const m = ctx.store.getMatch(id)!;
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [] });
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [], notes: [] });
const input = ctx.culprit.buildInput(m);
assert.ok(!input.text.includes('녹음'), '녹음이 경기를 다 덮으면 녹음 안내 줄 없음');
const lines = input.text.split('\n');
assert.match(lines[0], /^# 경기 발로란트 .* 13:9 \(우리 팀 승리\) · 22라운드/);
// 우리 팀이 P1~P5, 하늘은 음성O, 디스코드 계정이 없는 상대는 음성X
@@ -88,16 +89,30 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
assert.ok(u2Index > lines.findIndex((l) => l.startsWith('[u1] ')));
});
test('범인찾기: 녹음이 늦게 시작 · 음성 변환 중 · 녹음 제외', () => {
test('범인찾기: 녹음이 늦게 시작 · 녹음 없음 · 음성 변환 중 · 녹음 제외', () => {
// 녹음이 끊긴 경기도 분석한다 (v1.11.0): 녹음된 대화만 쓰고 AI 에 알린다
const late = setup();
const a = seedValorant(late, { sessionStartOffsetMs: 17 * MIN });
const e = late.culprit.eligibility(late.store.getMatch(a.id)!);
assert.equal(e.state, 'blocked');
assert.deepEqual(e.reasons, ['녹음이 경기 시작 12분 뒤에 시작됐습니다']);
assert.deepEqual(e, { state: 'ready', reasons: [], notes: ['녹음이 경기 시작 12분 뒤에 시작됐습니다: 녹음된 대화만 씁니다'] });
assert.ok(late.culprit.buildInput(late.store.getMatch(a.id)!).text.includes('\n# 녹음이 경기 시작 12분 뒤에 시작됐습니다. 녹음이 빠진 구간의 대화는 없다\n'));
// 앱을 켜지 않고 한 경기 (녹음 · 대화 없음): 플레이 기록 · 채팅으로만
const none = setup();
const n = seedValorant(none);
none.store.db.prepare('DELETE FROM utterances').run();
none.store.db.prepare('DELETE FROM sessions').run();
const nm = none.store.getMatch(n.id)!;
assert.deepEqual(none.culprit.eligibility(nm), { state: 'ready', reasons: [], notes: ['녹음 없음: 플레이 기록 · 채팅으로만 분석합니다'] });
const ni = none.culprit.buildInput(nm);
assert.ok(ni.text.includes('\n# 이 경기는 음성 녹음이 없다. 모두 음성X 로 보고 플레이 기록과 채팅으로만 평가한다\n'));
assert.ok(ni.players.every((p) => !p.voice));
assert.equal(ni.stats.utterances, 0);
assert.ok(ni.stats.events > 0 && ni.stats.rounds > 0);
const pend = setup();
const b = seedValorant(pend, { pending: true });
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'] });
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'], notes: [] });
// 녹음 제외한 사람의 대화는 보내지 않는다
const ex = setup();

View File

@@ -73,9 +73,12 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
assert.deepEqual(page.items.map((i: any) => i.id).sort(), ['quiet', 'speech']);
// 우클릭 → 자세한 정보: 원본 ogg 이름 · 경로
const info = (await core.api.inject({ method: 'GET', url: '/api/utterances/speech/info' })).json();
assert.equal(info.fileName, 'speech.ogg');
assert.equal(info.path, sp.audio_path);
assert.equal(info.folder, path.dirname(sp.audio_path!));
// 변환이 끝나면 녹음 파일 이름을 날짜 · 시각 · 말한 사람 · 경기 밖 · 발화 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');
@@ -110,6 +113,24 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
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();
}

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

@@ -27,6 +27,7 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
process.env.GVR_LOL_LIVE_URL = mock.base;
process.env.GVR_POLL_MS = '150';
process.env.GVR_DETAIL_RETRY_MS = '100';
process.env.GVR_NAMES_EVERY_MS = '200';
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');
@@ -40,7 +41,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 = {
@@ -89,6 +90,18 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
assert.deepEqual(sum.score, { ally: 2, enemy: 1 });
assert.equal(sum.win, true);
// ---- Riot ID 를 바꾼 사람: 연결(puuid)은 그대로, 표시되는 Riot ID 만 새 이름으로
store.upsertUser({ id: 'friend', name: '민수', avatar: null });
store.setAccounts('friend', [{ puuid: 'riotid:아직모름#KR1', riotId: '아직모름#KR1' }]);
const before = live.filter((e) => e.type === 'users.updated').length;
const revBefore = bus.usersRev;
mock.st.names = { 'self-puuid-0001': ['새하늘', 'KR2'] };
await until(() => store.listAccounts().some((a) => a.puuid === 'self-puuid-0001' && a.riot_id === '새하늘#KR2'), 5000, 'rename');
assert.equal(store.userIdForPuuid('self-puuid-0001'), 'owner');
assert.ok(live.filter((e) => e.type === 'users.updated').length > before, '사이트에 유저 목록 다시 보냄');
assert.ok(bus.usersRev > revBefore, '앱 설정 창도 유저 목록을 다시 받게 (state.usersRev)');
assert.ok(store.listAccounts().some((a) => a.user_id === 'friend' && a.riot_id === '아직모름#KR1'), 'puuid 모르는 계정은 그대로');
// ---- 롤
mock.st.lolPhase = 'ChampSelect';
await until(() => (gm as any).adapters[1].pendingChat.length === 1, 5000, 'champ select chat');

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

@@ -0,0 +1,387 @@
// 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'));
// 사이트 경기 탭 안내: 마지막으로 끝까지 확인한 때
await until(() => gm.live().every((g) => typeof g.historyAt === 'number'), 5000, 'historyAt');
// 필터
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') => ({
lastDoneAt: () => null,
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();
}
});
test('경기 목록: 데스매치는 빼고, 모드 · 날짜로 거른다 · 모드 목록 (v1.11.0)', 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 { Culprit } = await import('../src/core/culprit.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 store = new Store(path.join(dir, 'db.sqlite'));
const bus = new Bus();
const s = defaultSettings();
const tl = new Timeline(store);
const gm = new GameManager(store, new GameAssets(path.join(dir, 'cache')), Object.assign(new EventEmitter(), { request: async () => ({}) }) as any, { setGameActive: async () => undefined } as any, tl, bus, () => s, () => null);
const DAY = 86400000;
const T = Date.UTC(2026, 10, 20, 12);
const add = (id: string, game: 'valorant' | 'lol', queue: string | null, at: number, mode: string | null = queue) =>
store.upsertMatch({ id, game, started_at: at, ended_at: at + 1800000, queue, mode, status: 'complete', source: 'history' });
add('val-comp1', 'valorant', 'competitive', T);
add('val-dm', 'valorant', 'deathmatch', T - 1000);
add('val-unr', 'valorant', 'unrated', T - DAY);
add('val-comp2', 'valorant', 'competitive', T - 3 * DAY);
add('val-prem', 'valorant', 'premier', T - 4 * DAY);
add('val-dm-live', 'valorant', '', T - 5 * DAY, 'deathmatch'); // 큐가 비고 모드 칸에만 있는 데스매치
add('lol-1', 'lol', '420', T - 2 * DAY, 'CLASSIC');
const app = await buildApi({ store, timeline: tl, games: gm, dict: {} as any, culprit: new Culprit(store, tl, gm), bus, settings: () => s, trainingDir: () => dir, overviewExtra: () => ({ guild: null, recording: {} as any }), version: 'test' });
const ids = async (qs: string) => (await app.inject({ url: `/api/matches${qs}` })).json().map((m: any) => m.id);
try {
assert.deepEqual(await ids(''), ['val-comp1', 'val-unr', 'lol-1', 'val-comp2', 'val-prem'], '데스매치는 목록에 없다');
assert.deepEqual(await ids('?mode=' + encodeURIComponent('경쟁전')), ['val-comp1', 'val-comp2']);
assert.deepEqual(await ids('?mode=' + encodeURIComponent('데스매치')), [], '데스매치는 모드로 골라도 나오지 않는다');
assert.deepEqual(await ids('?mode=' + encodeURIComponent('없는모드')), []);
// 날짜: after 이상 · before 미만 (사이트는 고른 날의 0시 · 다음 날 0시를 보낸다)
assert.deepEqual(await ids(`?after=${T - 3 * DAY}&before=${T}`), ['val-unr', 'lol-1', 'val-comp2']);
assert.deepEqual(await ids(`?game=valorant&mode=${encodeURIComponent('경쟁전')}&after=${T - DAY}`), ['val-comp1']);
const modes = (await app.inject({ url: '/api/matches/modes' })).json();
assert.deepEqual(modes, [
{ game: 'valorant', mode: '경쟁전', count: 2 },
{ game: 'lol', mode: '솔로 랭크', count: 1 },
{ game: 'valorant', mode: '일반전', count: 1 },
{ game: 'valorant', mode: '프리미어', count: 1 },
]);
assert.deepEqual((await app.inject({ url: '/api/matches/modes?game=lol' })).json(), [{ game: 'lol', mode: '솔로 랭크', count: 1 }]);
// 범인찾기 목록에도 데스매치는 없다
const cu = (await app.inject({ url: '/api/culprit/matches' })).json().map((x: any) => x.match.id);
assert.ok(cu.includes('val-comp1') && !cu.includes('val-dm') && !cu.includes('val-dm-live'));
} finally {
await app.close();
store.close();
}
});

View File

@@ -18,6 +18,14 @@ export interface MockState {
lolGameId: number;
lolHistoryReady: boolean;
lolStart: number;
/** 발로란트 경기 기록 (새것부터): MatchID → 경기 시작 시각 */
valHistory: { MatchID: string; GameStartTime: number }[];
/** 롤 경기 기록 (LCU, 새것부터) */
lolHistoryList: { gameId: number; gameCreation: number }[];
/** 이름 서비스: puuid → [이름, 태그] (Riot ID 를 바꾼 사람 흉내) */
names: Record<string, [string, string]>;
/** 요청 기록 (경로) */
hits: string[];
}
export async function startMockRiot(dir: string) {
@@ -38,6 +46,10 @@ export async function startMockRiot(dir: string) {
lolGameId: 7001,
lolHistoryReady: false,
lolStart: 0,
valHistory: [],
lolHistoryList: [],
names: {},
hits: [],
};
const password = 'pw-test';
const presence = () => {
@@ -52,7 +64,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' }]],
[
@@ -69,7 +81,27 @@ 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, {}];
},
],
[
/^\/name-service\/v2\/players$/,
(_m, auth) => (auth.startsWith('Bearer ') ? [200, Object.entries(st.names).map(([Subject, [GameName, TagLine]]) => ({ Subject, GameName, TagLine }))] : [401, {}]),
],
// ---- LoL Live Client Data
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
// ---- LCU
@@ -79,7 +111,23 @@ export async function startMockRiot(dir: string) {
[/^\/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) => {
@@ -87,7 +135,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;

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

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

@@ -0,0 +1,212 @@
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);
});
test('경기 목록 리플레이 필터: yes = 리플레이 파일이 있는 발로란트 경기, no = 없는 발로란트 경기 (롤 제외) · 요약에 replay', async () => {
const s = setup();
const app = await buildApi({
store: s.store,
timeline: new Timeline(s.store),
games: { modeKeys: () => [], summary: (m: any) => ({ id: m.id, game: m.game }) } 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,
});
const get = async (qs: string) => (await app.inject({ url: `/api/matches${qs}` })).json() as { id: string; replay?: boolean }[];
// 리플레이를 하나도 안 받았으면 yes 는 빈 목록, no 는 발로란트 경기 전부
assert.deepEqual(await get('?replay=yes'), []);
assert.deepEqual((await get('?replay=no')).map((m) => m.id), [`val-${ID}`, `val-${ID2}`]);
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
(s.replays as any).scanCache = null; // 10초 목록 캐시 무시
const all = await get('');
assert.deepEqual(Object.fromEntries(all.map((m) => [m.id, m.replay])), { [`val-${ID}`]: true, [`val-${ID2}`]: false, 'lol-KR_1': undefined });
assert.deepEqual((await get('?replay=yes')).map((m) => m.id), [`val-${ID}`]);
assert.deepEqual((await get('?replay=no')).map((m) => m.id), [`val-${ID2}`]);
assert.deepEqual(await get('?replay=no&game=lol'), []);
});

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 가 지움)');
});

View File

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

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

@@ -0,0 +1,131 @@
# 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인칭 동작, 재장전 중 탄창이 손으로 옮겨 가는 것(소켓 바꾸기라 탄창이 잠깐 안 보임).
## 맵 텍스처 1024px · 무기 스킨 (2026-11-20, 실감 5단계)
- 맵 텍스처: `GVR_TEX` 기본 256 → 1024. 원본이 대부분 512 라 크게 늘지 않는다 (13.09 어센트: 이미지 366장 8MB → 24MB, 512px 246장 · 1024px 55장, 그래픽 메모리 추정 약 620MB, 맵 추출 최대 메모리 2.5GB · 3.7분).
- 계기: open-aim(브라우저 에임 연습장)의 맵 · 스킨 파일을 그대로 쓰는 안을 비교했다. 맵은 11개뿐(브리즈 · 프랙처 · 팀 데스매치 없음)이고 좌표계가 달라 우리 추출 맵이 낫고, 스킨은 손으로 옮긴 20개 정도라 리플레이에 기록된 실제 스킨을 쓰기로 했다. 그 사이트 파일은 쓰지 않는다.
- 리플레이: 총 · 칼 액터마다 `SkinDataAsset` · `SkinLevelDataAsset` · `ChromaDataAsset` · `CharmDataAsset` · `CharmLevelDataAsset` (게임 데이터 에셋 경로)가 복제된다. 파서에 무기 액터 형식이 없어 변환기 `src/Skins.cs` 가 첫 읽기 필드 목록에서 이 필드가 있는 묶음(무기 클래스)을 찾아 두 번째 읽기 (13.08 어비스: 총 · 칼 기록 5,686개 모두 스킨, 서로 다른 스킨 79개, 변환 6.8 → 7.0초).
- 출력: `skins[]` {skin, level, chroma, charm, charmLevel} (경로의 `.Default__…_C` 는 뗌), `equips` 4번째 열 = skins 번호(-1 모름). 줍거나 떨어뜨려도 총의 스킨은 처음 주인 것 (게임과 같다). 같은 총이라도 스킨이 다르면(주운 총) 새 줄.
- 게임 쪽 구조: 스킨 PrimaryAsset `Levels[]`(단계 PrimaryAsset → `SkinAttachment` = 단계 블루프린트) · `Chromas[]`(색상 PrimaryAsset → `EquippableSkinChroma`). 높은 단계 블루프린트는 낮은 단계의 자식 클래스라 부모 사슬을 합치면 그 단계까지의 모습. 단계: `Weapon 1P` · `Weapon 1P Cosmetic`(있으면 보이는 총은 이것, 1인칭 재질도 이것 기준) · `Magazine 1P` · `1p MaterialOverrides` · `1pMagazine MaterialOverrides` · `Weapon 3P` · `Magazine 3P` · `3p Material Overrides` · `3pMagazineMaterial Overrides`, 칼은 `NewMesh` · `3p Mesh`. 색상: `MaterialOverrides`(1인칭) · `3p Material Overrides` … (재질 칸 번호대로, 기본 색상은 비어 있다). 게임 전체 색상 약 2,969개라 미리 다 뽑지 않는다.
- 추출 `gvr-map-extract skins <폴더> <요청 파일> [skins.json]` (`src/Skins.cs`): 열쇠 "스킨|단계|색상" 마다 `skin3p_<서명>.glb`(weapon_*.glb 형식, 512px) · `skin1p_<서명>.glb`(fpweapon_*.glb 형식, 1024px `GVR_SKIN_TEX1P`, 총 동작은 기본 무기 GN_Core_*). 서명 = 메시 · 재질 경로 해시라 모습이 같은 단계 · 색상은 파일 하나.
- 요청 흐름: 사이트가 리플레이를 열면 없는 스킨을 `POST /site/maps3d/skins/want` → `.5 data/maps3d/skins/want.json`. 이 서버 `gvr-skins-update.timer`(3분마다 `scripts/skins-update.sh`)가 요청을 가져와(한 번에 40개) 올린 맵과 같은 매니페스트 · 매핑으로 뽑고 gltfpack + gzip 해서 `skins/` 에 올리고 `skins/index.json` 을 합친다(`skins-merge.py`). 못 뽑은 것은 `failed` (매핑 버전이 바뀌면 다시). 맵 갱신과 같은 잠금. `update.sh` 는 `skins/` 를 지우지 않는다. 시험: `scripts/test-skins.sh`.
- 사이트 `lib/skins.ts`: 뽑아 둔 스킨이면 3인칭 손의 총(`AgentRig.setWeapon`) · 1인칭 총(`Viewmodel.set`)을 그 모델로, 아니면 기본 총. 기본 스킨(`…/Standard/…_PrimaryAsset`)은 요청하지 않는다. 처음 본 스킨은 다음에 열 때부터 보인다.
- 13.10 전체 (2026-11-20): 맵 23개 68분 · 받은 양 2.5GB (텍스처 큰 밉을 받느라 256px 때 26분보다 길다), 맵 압축 13~56MB, 사이트 폴더 818MB. 매핑은 uedb 가 13.09 에 멈춰 있어 valorant-api.com (`/v1/version` 의 manifestId 가 라이브와 같을 때 mappingsUrl) 으로 받았다 (`update.sh`).
- 한계: 총 장식(참) · 스킨 전용 동작 · 효과(빛나는 재질 · 단계별 VFX) · 처치 연출은 없다. 재질은 디퓨즈 텍스처만이라 빛나는 부분은 평평하다.
## 남은 일
- 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 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 로 올리면 다음에 열 때 생긴다.
## 자동 시점 · Tab 점수판 (2026-11-08)
- 변환기: `scoreboard` 행 `[t, 선수, 크레딧, 궁 점수, 킬, 데스, 어시, 전투 점수]` (바뀔 때마다 그 선수 전체 값, 모르는 값 -1). 크레딧은 `MoneyManagementComponent.Money`, 궁은 `BombPlayerState.NumUltimatePoints` (파서 기본 목록), 킬/데스/어시 · 전투 점수는 PlayerState 하위 객체 `BasicCombatStatsComponent` · `PlayerScoreComponent` 를 이름으로 목록에 더해 읽는다 (`Collector.Catalog`, 하위 객체 이름 → 클래스 `AddSubobjectClassPath` 가 없으면 그룹이 비어 온다). 게임은 기본값(0)과 다를 때만 보내므로 사이트는 안 온 숫자를 0 으로 본다.
- 13.08 어비스: 행 1706개, 변환 6.8초(+0.2초). 체력 · 방어구(`ChildDamageSectionComponent`)는 리플레이에 값이 오지 않는다.
- 궁극기 점수는 리플레이에 없다: 사이트가 궁을 쓴 순간(0 으로 떨어지기 직전 값)으로 정하고 (공수 교대 초기화는 뺀다: 교대 라운드 = 선수 시작 자리 중앙값이 40m 넘게 옮겨 간 라운드(13.08 실측 교대 93~109m · 평소 13m 이하), 그 앞 라운드 끝 ~ 교대 라운드 구매 3초 뒤에 0 이 된 것), 쓴 적이 없으면 요원 표(`lib/scoreboard.ts` ULT_COST)와 모은 최대값 중 큰 것. 13.08 실측 피닉스 7 · 나머지 8.
- 사이트 `lib/scoreboard.ts` · `components/ReplayScoreboard.tsx`: 재생기 위에 마우스가 있거나 재생기 안을 누른 뒤 Tab 을 누르고 있는 동안 (버튼으로 켜고 끌 수도). 팀 점수(그 라운드 전까지, 라운드가 끝난 뒤면 그 라운드까지) · 궁극기 점 · K/D/A · 이 라운드 주무기 · 크레딧, 전투 점수 순, 죽은 선수 흐리게. 옛 JSON 은 킬 · 데스만 킬 기록으로.
- 자동 시점 `lib/director.ts` (카메라 "자동"): 시각만으로 장면을 정한다 (되감기 · 배속에도 같음).
- 교전: 킬마다 죽인 선수 1인칭. 교전 시작(둘 사이 첫 맞은 기록 · 죽인 선수의 이어진 사격, 8초 안) 2.5초 전부터. 우리 팀이 낀 교전이면 교전 시작 6초 안에 시작한 대화(콜)부터 보여 주고 화면에 콜 글. 같은 선수가 이어 죽이면 한 장면, 다음 킬은 앞 킬 0.5초 뒤에 넘어가고 넘어간 뒤 0.7초 안에 킬이면 넘어가지 않는다 (맞킬).
- 빈 곳: 스파이크 설치 · 해체 > 킬 없는 교전(가장 많이 맞힌 산 선수) > 혼자 남은 선수(1 대 N) > 위에서 (구매 · 전략 보기 · 라운드 끝). 위에서는 살아 있는 선수가 모두 들어오게 부드럽게 따라간다 (거리 = 시야각 · 화면비 · 기울기로 가장 바깥 선수가 화면 85% 에 닿는 값, `fitDistance`). 2초보다 짧은 위에서 보기 · 0.9초보다 짧은 1인칭은 앞 장면에 붙인다.
- 13.08 어비스: 장면 265개 · 계산 15ms, 상대 팀끼리 킬 145개 중 126개를 죽인 선수 1인칭으로 (나머지는 1초 안 맞킬).
- 시험: `site/server/test/replay-director.test.ts`, 변환기 `gvr-replay --self-test` (점수판 줄 합치기).

View File

@@ -222,3 +222,132 @@ VOICE E2E PASS
- 그 밖: 브라우저 오류 로그에 검색어가 남던 것, 경기 끝 직후 늦게 끝난 실시간 변환의 잡음 파일을 정밀 확인 전에 지우던 것, 많이 골랐을 때 내려받기 주소가 너무 길던 것(본문으로 보냄), 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.11.2 — Riot ID 칸 고치기 취소 뒤 새 이름 반영 (2026-11-21)
- 앱 (d237228): `RiotRow` 동기화 효과 의존성 `[server, dirty]` — 고치는 중에 이름이 바뀌면 미뤘다가, 입력을 되돌려 고치기를 그만두면 새 이름으로. 렌더러 목 + 헤드리스 크롬: 탭을 연 채 `민준#KR1` → `민준바꿈#KR9`, 현우 칸을 고치는 중 `HW#7777` → `HW새이름#8888` 로 바뀌어도 입력 유지 → 입력을 `HW#7777` 로 되돌리니 `HW새이름#8888` · `✓ 1개`. 앱 테스트 87개 PASS · 타입 검사(앱 · 렌더러) 통과
- 배포: Windows CI (d237228, full) 8개 모두 PASS (앱 smoke 버전 1.11.2) · Gitea 릴리스 v1.11.2 (portable.exe 206,693,515 B · win-x64.zip 302,941,251 B, 올린 파일 sha256 일치) (v1.11.1 ~ v1.8.0 에 새 버전 안내)
## v1.11.1 — 앱 게임 연동 탭 Riot ID 표 실시간 갱신 (2026-11-21)
- 앱 (673f242): `Bus.usersRev`(users.updated 횟수) → `AppState.usersRev` → 게임 연동 탭이 유저 목록을 다시 받고, 고치는 중이 아닌 Riot ID 입력칸을 새 값으로. 앱 테스트 87개 PASS · 타입 검사(앱 · 렌더러) 통과. 렌더러 목(`__gvrMockRename`) + 헤드리스 크롬: 탭을 연 채 `민준#KR1` → `민준바꿈#KR9` 로 바뀜, 입력 중인 칸(서연)은 그대로
- 배포: Windows CI (673f242, full) 8개 모두 PASS (앱 smoke 버전 1.11.1) · Gitea 릴리스 v1.11.1 (portable.exe 206,706,031 B · win-x64.zip 302,939,652 B, 올린 파일 sha256 일치) (v1.11.0 ~ v1.8.0 에 새 버전 안내)
## v1.11.0 — Riot ID 자동 갱신 · 녹음 없는 경기 범인찾기 · 경기 탭 모드/날짜 필터 · 데스매치 숨김 (2026-11-21)
- 앱 (5e756f9): Riot 클라이언트에 붙으면 바로 · 10분마다 `PUT name-service/v2/players` 로 연결 계정(puuid 아는 것)의 지금 Riot ID 확인 → `game_accounts.riot_id` 갱신 · `users.updated`. `/api/matches` 에 `mode` · `after`, 데스매치 늘 뺌, `GET /api/matches/modes`. 범인찾기 목록 데스매치 뺌, 녹음 없음 · 끊김은 막지 않고 `eligibility.notes` + AI 자료 안내 줄. `LiveGame.historyAt` (Riot 경기 기록 마지막 확인). 앱 테스트 87개 PASS (이름 바뀜 · 필터 · 모드 목록 · 녹음 없는 경기 분석 시험 추가), 타입 검사 통과
- 사이트: 경기 탭 모드 선택 · 날짜(시작 ~ 끝) · 초기화, 예전 앱이면 사이트가 데스매치 · 모드 · 날짜를 거름, Riot 경기 기록 확인 안내, 범인찾기 녹음 없음 안내. 사이트 서버 테스트 43개 · 웹 빌드 통과, 목 서버 + 헤드리스 크롬으로 모드 목록(데스매치 없음) · 일반전 16경기만 · 11-18~11-19 거르기 확인 (콘솔 오류 없음)
- 배포: 사이트 서버 다시 배포 (번들에 새 문구 · `/api/matches/modes` 로그인 없이 401). Windows CI (cec5e35, full) 8개 모두 PASS (앱 smoke 버전 1.11.0) · Gitea 릴리스 v1.11.0 (portable.exe 206,703,268 B · win-x64.zip 302,940,533 B, 올린 파일 sha256 일치) (v1.10.0 ~ v1.8.0 에 새 버전 안내)
## v1.10.0 — 3D 리플레이 무기 스킨 · 자동 시점 · Tab 점수판 · 맵 텍스처 1024px (2026-11-20)
- 변환기: 무기 스킨(스킨 · 단계 · 색상 · 총 장식) 두 번째 읽기 · equips 4번째 열 (96f6957), 점수판 (c36db3e · a5a1c84). 자체 시험 통과, 13.08 어비스 리플레이 스킨 79개 · 조준점 10명 (리눅스 7.0초, Windows CI 8.8초)
- 추출기 · 자동 갱신: 맵 텍스처 1024px · `skins` 명령 · `skins-update.sh` 3분 타이머 (0da9939), 타이머 02:00~07:00 제외 (fa99291), uedb 가 늦으면 라이브 매니페스트와 같은 valorant-api.com 매핑 (56242cd). 맵 갱신 시험 18개 · 스킨 갱신 시험 5개 통과
- 사이트: 3인칭 · 1인칭 총에 스킨, 없는 스킨 요청 (200dbce · fa99291). 사이트 서버 테스트 43개 통과 · 웹 타입 검사 통과 · 목 서버 + 헤드리스 크롬으로 홀로그램 밴달 · 이온 팬텀 · 고스트 · 홀로그램 칼 1인칭과 3인칭 손의 스킨 총 확인
- 배포: 사이트 서버 다시 배포 (`/site/maps3d/skins` · `POST /site/maps3d/skins/want` 로그인 없이 401, 번들에 요청 코드), 맵 재추출 13.10 (매핑 valorant-api.com, 23/23 맵 68분 · 받은 양 2.5GB · 서비스 최대 메모리 약 3GB, 맵 압축 13~56MB · 폴더 818MB), 스킨 타이머 실제 요청 1개 추출 · 반영 확인 (모습 66개). Windows CI (dd9564d, full) 8개 모두 PASS (앱 smoke 버전 1.10.0 · 실제 변환 11.1초 · gzip 1.62MB) · 앱 버전 1.10.0 → Gitea 릴리스 v1.10.0 (portable.exe 206,700,418 B · win-x64.zip 302,935,640 B, 올린 파일 sha256 일치) (v1.9.1 · v1.9.0 · v1.8.2 · v1.8.1 · v1.8.0 에 새 버전 안내, 컨테이너에서 최신 릴리스 v1.10.0 조회 확인)
## v1.9.1 — 경기 기록 가져오기 진행 바 · 취소 (2026-11-05)
- 앱 · 사이트: Riot 경기 기록을 가져오는 동안 사이트 경기 탭 · 앱 게임 연동 탭에 목록 확인 중 → 받은 경기 / 받을 경기 · % · 남은 시간 진행 바와 취소 버튼 (63d0e43), 받다가 멈춘 실행(취소 · 게임 시작 · 오류)은 다음 실행이 끝까지 다시 훑고 취소하면 취소한 때부터 한 주기 뒤 재개 (b645d75). 앱 테스트 86개 PASS
- 배포: 사이트 서버 다시 배포 (번들에 새 문구 · `POST /api/games/history/cancel` 로그인 없이 401), Windows CI (320cc9b, full) 8개 모두 PASS (실제 리플레이 crosshairs 10, 앱 smoke 버전 1.9.1 · 실제 변환 9.2초 · gzip 1.60MB) · 앱 버전 1.9.1 → Gitea 릴리스 v1.9.1 (portable.exe 206,691,291 B · win-x64.zip 302,930,242 B, 올린 파일 sha256 일치) (v1.9.0 · v1.8.2 · v1.8.1 · v1.8.0 에 새 버전 안내, 컨테이너에서 최신 릴리스 v1.9.1 조회 확인)
## 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 에 새 버전 안내)

View File

@@ -1,4 +1,4 @@
import type { LiveGame } from './protocol.js';
import type { HistoryProgress, LiveGame } from './protocol.js';
import { fmtClock } from './time.js';
export const GAME_NAME: Record<LiveGame['game'], string> = { valorant: '발로란트', lol: '리그 오브 레전드' };
@@ -33,3 +33,25 @@ export function liveGameRows(g: LiveGame, now = Date.now()): [string, string][]
if (g.error) rows.push(['오류', g.error]);
return rows;
}
/** 남은 시간 글자: "약 3분 남음" · "40초 남음" · "남은 시간 계산 중" */
export function fmtEta(ms: number | null): string {
if (ms == null) return '남은 시간 계산 중';
if (ms < 60000) return `${Math.max(1, Math.ceil(ms / 10000) * 10)}초 남음`;
const min = Math.ceil(ms / 60000);
return min < 60 ? `약 ${min}분 남음` : `약 ${Math.floor(min / 60)}시간 ${min % 60}분 남음`;
}
/** 경기 기록 가져오기 진행 바 글자 (v1.9.1, 사이트 경기 탭 · 앱 게임 연동 탭). pct = null 이면 얼마나 걸릴지 아직 모름 */
export function historyStatus(p: HistoryProgress): { title: string; detail: string; pct: number | null } {
if (p.phase === 'scan')
return { title: '경기 기록 목록 확인 중', detail: `${p.scanned}경기 확인${p.total ? ` · 새 경기 ${p.total}개` : ''}`, pct: null };
const pct = p.total ? Math.min(100, Math.round((p.done / p.total) * 100)) : 100;
return { title: '경기 기록 가져오는 중', detail: `${p.done} / ${p.total}경기 (${pct}%) · ${fmtEta(p.etaMs)}`, pct };
}
/** 취소한 가져오기를 다시 하는 때: "약 30분 뒤" (모르면 "다음 확인 때") */
export function resumeText(resumeAt: number | null, now = Date.now()): string {
if (!resumeAt) return '다음 확인 때';
return `약 ${Math.max(1, Math.ceil((resumeAt - now) / 60000))}분 뒤`;
}

View File

@@ -165,6 +165,12 @@ export interface MatchSummary {
score: { ally: number; enemy: number } | null;
status: 'live' | 'pending_detail' | 'complete';
participants: string[];
/** live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0 앱부터, 없으면 live) */
source?: 'live' | 'history';
/** 목소리가 녹음된 경기 (잡음 제외, v1.9.0 앱부터) */
voice?: boolean;
/** 발로란트: 이 PC 에 리플레이 파일(.vrf)이 있는 경기 (경기 목록, v1.12.0 앱부터) */
replay?: boolean;
}
export interface MatchPlayer {
@@ -275,9 +281,30 @@ export interface LiveGame {
players: number | null;
/** 마지막 오류 (연결 실패 등) */
error: string | null;
/** Riot 경기 기록 가져오는 중이면 진행 상황 (v1.9.1~, 예전 앱은 없음) */
history?: HistoryProgress | null;
/** Riot 경기 기록을 마지막으로 끝까지 확인한 때 (v1.11.0~, 아직 한 번도 못 했으면 null) */
historyAt?: number | null;
updatedAt: number;
}
/** Riot 경기 기록 가져오기 진행 상황 (v1.9.1~). 사이트 경기 탭 · 앱 게임 연동 탭에 진행 바로 보여 준다 */
export interface HistoryProgress {
/** scan = 경기 목록 훑는 중 (몇 경기를 받을지 아직 모름), fetch = 경기 하나씩 받는 중 */
phase: 'scan' | 'fetch';
/** 처음 끝까지 훑는 중 (오래 걸림) */
first: boolean;
/** 경기 목록에서 확인한 경기 수 (scan) */
scanned: number;
/** 받은 경기 수 / 받을 경기 수 (fetch) */
done: number;
total: number;
/** 시작 시각 (PC 시계) */
startedAt: number;
/** 남은 시간 예상 (ms). scan 중이거나 아직 모르면 null */
etaMs: number | null;
}
/** 기록 묶음 (사이트 기록 관리, v1.3.7~): 경기 하나 또는 경기 밖 대화 한 덩어리 */
export interface BundleInfo {
/** match-<경기ID> 또는 talk-<첫 발화ID> */
@@ -333,6 +360,8 @@ export interface UserProfile {
export interface CulpritEligibility {
state: 'ready' | 'done' | 'pending' | 'blocked';
reasons: string[];
/** 분석은 되지만 알려 둘 것 (녹음 없음 · 녹음이 끊김, v1.11.0 앱부터) */
notes?: string[];
}
export interface CulpritPlayer {
/** P1~P10 (우리 팀 먼저) */
@@ -427,7 +456,18 @@ export type LiveEvent =
| { type: 'recording.state'; data: Overview['recording'] }
| { type: 'users.updated'; data: User[] }
| { type: 'games.state'; data: LiveGame[] }
| { type: 'records.changed'; data: { reason: 'deleted' | 'imported'; ids?: string[] } };
| { type: 'records.changed'; data: { reason: 'deleted' | 'imported'; ids?: string[] } }
/** 사이트 우클릭으로 발화 하나를 지움 (v1.4.0). noise = "잡음이라 삭제" */
| { type: 'utterance.deleted'; data: { id: string; noise: boolean } };
/** "잡음이라 삭제"로 배운 문장 (GET /api/noise-phrases) */
export interface NoisePhrase {
id: number;
text: string;
/** 그 뒤로 이 문장을 잡음으로 걸러 낸 횟수 */
hits: number;
createdAt: number;
}
export interface DeviceStatus {
registered: boolean;

View File

@@ -28,7 +28,17 @@ const sha = (s: string) => crypto.createHash('sha256').update(s).digest();
export function registerAppAuth(
app: FastifyInstance,
deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean; onRevoke?: (by: { userId?: string; token?: string }) => void },
deps: {
cfg: Config;
store: ServerStore;
discord: DiscordApi;
secure: boolean;
onRevoke?: (by: { userId?: string; token?: string }) => void;
/** 사이트 로그인 세션 (사이트 관리 화면 /site/admin/*). app.ts 가 나중에 넣는다 */
siteSession?: (req: FastifyRequest, reply: FastifyReply) => Promise<{ user: { id: string } } | null>;
/** 표시 이름이 바뀌었을 때 (게임 PC 앱에 바로 보낸다) */
onNamesChanged?: (id: string, name: string | null) => void;
},
) {
const { cfg, store, discord, secure } = deps;
const revoke = (by: { userId?: string; token?: string }) => deps.onRevoke?.(by);
@@ -186,64 +196,109 @@ export function registerAppAuth(
if (!(await auth(req, reply))) return;
return { names: store.displayNames() };
});
app.put<{ Body: { id?: string; name?: string | null } }>('/app/admin/names', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
const name = String(req.body?.name ?? '').trim().slice(0, 32);
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
store.setDisplayName(id, name || null);
req.log.info({ by: a.id, user: id, set: !!name }, '표시 이름 변경');
return { names: store.displayNames() };
});
app.get('/app/admin/users', async (req, reply) => {
if (!(await need(req, reply, 'admin'))) return;
return { users: rows() };
});
app.post<{ Body: { id?: string; role?: string } }>('/app/admin/users', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
const r = role(req.body?.role ?? 'user');
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 이미 등록되어 있습니다' });
let du: DiscordUser | null;
try {
du = await fetchDiscordUser(cfg, id);
} catch (e) {
req.log.warn(e, '디스코드 계정 조회 실패');
return reply.code(502).send({ error: 'discord_error', message: '디스코드에서 계정을 확인하지 못했습니다. 잠시 뒤 다시 시도해 주세요' });
// 관리 API 는 두 곳에서 부른다: 앱 관리자 탭(/app/admin/*, 앱 토큰) · 사이트 관리 화면(/site/admin/*, 사이트 로그인 v1.6.0~)
const siteNeed = async (req: FastifyRequest, reply: FastifyReply, level: 'admin' | 'superadmin') => {
const s = deps.siteSession ? await deps.siteSession(req, reply) : null;
if (!s) {
if (!reply.sent) reply.code(401).send({ error: 'unauthorized' });
return null;
}
if (!du) return reply.code(404).send({ error: 'unknown_user', message: '디스코드에 없는 아이디입니다' });
if ((du as any).bot) return reply.code(400).send({ error: 'bot', message: '봇 계정은 등록할 수 없습니다' });
store.upsertAppUser({ id, name: du.global_name || du.username, avatar: avatarUrl(du), role: r, addedBy: a.id });
req.log.info({ by: a.id, user: id, role: r }, '앱 유저 등록');
return { users: rows() };
});
// 쓰기 요청은 같은 사이트에서 온 것만 (CSRF)
const origin = String(req.headers.origin || '');
if (req.method !== 'GET' && origin && origin !== cfg.publicUrl) {
reply.code(403).send({ error: 'bad_origin' });
return null;
}
const r = siteRole(s.user.id);
const ok = r && (level === 'superadmin' ? r === 'superadmin' : r !== 'user');
if (!ok) {
reply.code(403).send({ error: 'forbidden', message: level === 'superadmin' ? '유저 등록 · 역할 바꾸기는 최고 관리자만 할 수 있습니다' : '관리자만 볼 수 있습니다' });
return null;
}
return { id: s.user.id, role: r };
};
for (const [prefix, who] of [
['/app/admin', need],
['/site/admin', siteNeed],
] as const) {
// 표시 이름: 앱에서는 최고 관리자만 (v1.2~), 사이트 관리 화면에서는 관리자도 (v1.6.0)
app.put<{ Body: { id?: string; name?: string | null } }>(`${prefix}/names`, async (req, reply) => {
const a = await who(req, reply, prefix === '/app/admin' ? 'superadmin' : 'admin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
const v = checkName(req.body?.name, id);
if ('error' in v) return reply.code(400).send({ error: 'bad_name', message: v.error });
store.setDisplayName(id, v.name);
req.log.info({ by: a.id, user: id, set: !!v.name }, '표시 이름 변경');
deps.onNamesChanged?.(id, v.name);
return { names: store.displayNames() };
});
app.patch<{ Params: { id: string }; Body: { role?: string } }>('/app/admin/users/:id', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
const r = role(req.body?.role);
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 바꿀 수 없습니다' });
if (!store.setAppUserRole(req.params.id, r)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
req.log.info({ by: a.id, user: req.params.id, role: r }, '앱 유저 역할 변경');
return { users: rows() };
});
app.get(`${prefix}/users`, async (req, reply) => {
if (!(await who(req, reply, 'admin'))) return;
return { users: rows(), names: store.displayNames() };
});
app.delete<{ Params: { id: string } }>('/app/admin/users/:id', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
revoke({ userId: req.params.id });
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
return { users: rows() };
});
app.post<{ Body: { id?: string; role?: string } }>(`${prefix}/users`, async (req, reply) => {
const a = await who(req, reply, 'superadmin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
const r = role(req.body?.role ?? 'user');
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 이미 등록되어 있습니다' });
let du: DiscordUser | null;
try {
du = await fetchDiscordUser(cfg, id);
} catch (e) {
req.log.warn(e, '디스코드 계정 조회 실패');
return reply.code(502).send({ error: 'discord_error', message: '디스코드에서 계정을 확인하지 못했습니다. 잠시 뒤 다시 시도해 주세요' });
}
if (!du) return reply.code(404).send({ error: 'unknown_user', message: '디스코드에 없는 아이디입니다' });
if ((du as any).bot) return reply.code(400).send({ error: 'bot', message: '봇 계정은 등록할 수 없습니다' });
store.upsertAppUser({ id, name: store.nameOf(id, du.global_name || du.username), avatar: avatarUrl(du), role: r, addedBy: a.id });
req.log.info({ by: a.id, user: id, role: r }, '앱 유저 등록');
return { users: rows() };
});
app.patch<{ Params: { id: string }; Body: { role?: string } }>(`${prefix}/users/:id`, async (req, reply) => {
const a = await who(req, reply, 'superadmin');
if (!a) return;
const r = role(req.body?.role);
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 바꿀 수 없습니다' });
if (!store.setAppUserRole(req.params.id, r)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
req.log.info({ by: a.id, user: req.params.id, role: r }, '앱 유저 역할 변경');
return { users: rows() };
});
app.delete<{ Params: { id: string } }>(`${prefix}/users/:id`, async (req, reply) => {
const a = await who(req, reply, 'superadmin');
if (!a) return;
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
revoke({ userId: req.params.id });
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
return { users: rows() };
});
}
/**
* 표시 이름 확인: 빈 값이면 지우기(디스코드 이름으로), 아니면 1~32자 · 제어 문자 없음 · 다른 사람의 표시 이름과 겹치지 않음
* (같은 이름이 둘이면 기록 · 범인 분석에서 누가 누군지 알 수 없다)
*/
function checkName(raw: unknown, id: string): { name: string | null } | { error: string } {
if (raw === null || raw === undefined) return { name: null };
const name = String(raw).normalize('NFC').replace(/\s+/g, ' ').trim();
if (!name) return { name: null };
if ([...name].length > 32) return { error: '이름은 32자까지입니다' };
if (/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/.test(name)) return { error: '이름에 쓸 수 없는 글자가 있습니다' };
const key = name.toLowerCase();
for (const [other, n] of Object.entries(store.displayNames())) if (other !== id && n.toLowerCase() === key) return { error: '다른 사람이 이미 쓰는 이름입니다' };
return { name };
}
const siteRole = (id: string): AppRole | null => roleOf(id) ?? (cfg.owners.includes(id) ? 'admin' : null);
/** 겜녹이 봇 중계 연결 확인: 살아 있는 앱 토큰 + 등록된 아이디 */
const verifyToken = (token: string): { userId: string; role: AppRole } | null => {
@@ -252,7 +307,7 @@ export function registerAppAuth(
return s && r ? { userId: s.userId, role: r } : null;
};
return { completeLogin, verifyToken, roleOf };
return { completeLogin, verifyToken, roleOf, siteRole, checkName };
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

View File

@@ -9,7 +9,9 @@ import { registerAppAuth } from './app-auth.js';
import { BotBroker, type BotSource } from './bot-broker.js';
import { registerCulprit, type ModelCall } from './culprit.js';
import type { KnowledgeAuto } from './culprit-prompt.js';
import { avatarUrl, DiscordApi } from './discord.js';
import { avatarUrl, DiscordApi, fetchDiscordUser } from './discord.js';
import { registerMaps3d } from './maps3d.js';
import { contentSecurityPolicy } from './csp.js';
import { RateLimiter } from './rate-limit.js';
import { RelayHub } from './relay.js';
import { SiteLog } from './site-log.js';
@@ -21,7 +23,7 @@ const RECHECK_MS = 10 * 60000;
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
export async function buildServer(
cfg: Config,
opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; logEcho?: boolean } = {},
opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; logEcho?: boolean; browserRecheckMs?: number } = {},
) {
// 사이트 로그: 날짜별 파일(data/logs/site-날짜.log)로 남기고 관리자가 사이트에서 본다. 게임 PC 가 꺼져 있어도 볼 수 있다
const siteLog = new SiteLog(path.join(cfg.dataDir, 'logs'), { echo: opts.logEcho ?? true });
@@ -45,25 +47,20 @@ export async function buildServer(
await app.register(cookie, { secret: cfg.sessionSecret });
const secure = cfg.publicUrl.startsWith('https://');
let broker: BotBroker | null = null;
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
const appAuth = registerAppAuth(app, {
cfg,
store,
discord,
secure,
onRevoke: (by) => broker?.kick(by),
siteSession: (req, reply) => requireSession(req, reply),
onNamesChanged: (id, name) => (name ? pushNames() : void restoreName(id).then(pushNames)),
});
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log.child({ area: 'bot' }), opts.botRecheckMs);
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
// CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게)
const wsOrigin = cfg.publicUrl.replace(/^http/, 'ws');
const csp = [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob: https://cdn.discordapp.com",
"media-src 'self' blob: data:",
"font-src 'self' data:",
`connect-src 'self' ${wsOrigin}`,
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
].join('; ');
// CSP 내용과 이유는 csp.ts
const csp = contentSecurityPolicy(cfg.publicUrl.replace(/^http/, 'ws'));
app.addHook('onSend', async (_req, reply, payload) => {
reply.header('content-security-policy', csp);
reply.header('x-content-type-options', 'nosniff');
@@ -71,11 +68,11 @@ export async function buildServer(
return payload;
});
/** 사이트에 들어올 수 있는 서버: 게임 PC 앱에서 녹음할 서버로 고른 곳 하나.
* 앱이 아직 한 번도 알려 주지 않았을 때만 ALLOWED_GUILD_IDS 를 쓴다 */
const allowedGuilds = (): string[] => {
const g = new Set(cfg.allowedGuilds);
const dg = store.device()?.guildId;
if (dg) g.add(dg);
return [...g];
return dg ? [dg] : cfg.allowedGuilds;
};
/** 세션 확인. 10분마다 서버 멤버인지 다시 확인 (서버에서 나가면 바로 막힘) */
@@ -191,11 +188,20 @@ export async function buildServer(
}
});
/** 로그인 화면: 들어올 수 있는 서버 이름 (봇과 같은 서버) */
app.get('/auth/guild', async () => {
const g = allowedGuilds()[0];
return { name: g ? await discord.guildName(g) : null };
});
app.post('/auth/logout', async (req, reply) => {
const raw = req.cookies[SID];
const un = raw ? req.unsignCookie(raw) : null;
const s = un?.valid && un.value ? store.session(un.value) : null;
if (s) store.deleteSession(s.id);
if (s) {
store.deleteSession(s.id);
hub.closeSession(s.id);
}
reply.clearCookie(SID, { path: '/' });
return { ok: true };
});
@@ -203,7 +209,78 @@ export async function buildServer(
app.get('/auth/me', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id) };
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id), role: appAuth.siteRole(s.user.id) };
});
// ------------------------------------------------------------------ 내 정보 · 표시 이름 (v1.6.0)
/** 표시 이름을 게임 PC 앱에 바로 보낸다 (v1.6.0 앱. 예전 앱은 10분마다 받아 간다) */
function pushNames(): void {
if (!hub.status().online) return;
hub
.request('PUT', '/api/internal/names', { 'x-gvr-internal': '1', 'content-type': 'application/json', accept: 'application/json' }, { id: 'server', name: '사이트 서버', avatar: null }, JSON.stringify({ names: store.displayNames() }), 10000)
.then((r) => r.status >= 400 && app.log.info({ area: 'names', status: r.status }, '게임 PC 앱이 표시 이름을 바로 받지 못함 (예전 앱은 10분 안에 받아 감)'))
.catch(() => undefined);
}
/** 표시 이름을 지우면 디스코드 이름(서버 별명 → 전역 이름 → 아이디)으로 되돌린다 */
async function restoreName(id: string): Promise<void> {
try {
let nick: string | null = null;
for (const g of allowedGuilds()) {
const m = await discord.memberOf(g, id);
if (m?.nick) nick = m.nick;
if (m) break;
}
const u = nick ? null : await fetchDiscordUser(cfg, id);
const name = nick || u?.global_name || u?.username;
if (name) store.restoreDiscordName(id, name);
} catch (e) {
app.log.warn({ area: 'names', err: String(e) }, '디스코드 이름 다시 받기 실패');
}
}
// 관리 화면 머리: 게임 PC 상태 + 최신 앱 릴리스 (Gitea, 1시간 보관). 새 버전이 있으면 관리자에게 알린다
let latest: { at: number; v: { version: string; url: string; publishedAt: string | null } | null } = { at: 0, v: null };
async function latestRelease() {
if (!cfg.releasesApi || Date.now() - latest.at < 3600000) return latest.v;
latest.at = Date.now();
try {
const r = await fetch(cfg.releasesApi, { signal: AbortSignal.timeout(5000), headers: { accept: 'application/json' } });
if (r.ok) {
const j: any = await r.json();
if (typeof j.tag_name === 'string') latest.v = { version: j.tag_name.replace(/^v/, ''), url: String(j.html_url ?? ''), publishedAt: j.published_at ?? null };
}
} catch {
/* 다음에 다시 */
latest.at = Date.now() - 3300000;
}
return latest.v;
}
app.get('/site/admin/overview', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
const r = appAuth.siteRole(s.user.id);
if (!r || r === 'user') return reply.code(403).send({ error: 'forbidden', message: '관리자만 볼 수 있습니다' });
const dev = store.device();
return { device: { ...hub.status(), guildId: dev?.guildId ?? null }, latest: await latestRelease(), role: r, serverVersion: cfg.version };
});
const nameLimit = new RateLimiter(10, 10 * 60000);
app.get('/site/profile', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
return { user: s.user, customName: store.displayNames()[s.user.id] ?? null, role: appAuth.siteRole(s.user.id) };
});
app.put<{ Body: { name?: string | null } }>('/site/profile/name', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
const origin = String(req.headers.origin || '');
if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' });
if (!nameLimit.hit(s.user.id)) return reply.code(429).send({ error: 'rate_limited', message: '이름을 너무 자주 바꿨습니다. 10분 뒤 다시 해 주세요' });
const v = appAuth.checkName(req.body?.name, s.user.id);
if ('error' in v) return reply.code(400).send({ error: 'bad_name', message: v.error });
store.setDisplayName(s.user.id, v.name);
if (!v.name) await restoreName(s.user.id);
req.log.info({ user: s.user.id, set: !!v.name }, '내 표시 이름 변경');
pushNames();
return { user: s.user, customName: v.name };
});
// ------------------------------------------------------------------ 상태 · 관리
@@ -290,6 +367,9 @@ export async function buildServer(
return reply.send(buf);
});
// ------------------------------------------------------------------ 발로란트 맵 3D (로그인 필요)
registerMaps3d(app, cfg.dataDir, requireSession, cfg.publicUrl);
app.get('/healthz', async () => 'ok\n');
// ------------------------------------------------------------------ 사이트 화면
@@ -341,7 +421,8 @@ export async function buildServer(
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
return socket.destroy();
}
hub.browserWss.handleUpgrade(req, socket, head, (ws) => hub.attachBrowser(ws));
// 연결한 뒤에도 세션 삭제 · 로그아웃 · 서버 탈퇴(getSession 이 10분마다 확인)면 끊는다
hub.browserWss.handleUpgrade(req, socket, head, (ws) => hub.attachBrowser(ws, s.id, async () => !!(await getSession(fakeReq)), opts.browserRecheckMs));
return;
}
socket.destroy();

View File

@@ -20,6 +20,8 @@ export interface Config {
/** 테스트용: 디스코드 API 주소 바꾸기 */
discordApi: string;
assetUpstream: Record<string, string>;
/** 최신 앱 릴리스 (Gitea API, 관리 화면에서 새 버전 안내) */
releasesApi?: string;
/** 범인찾기 (Claude API). apiKey 가 없으면 꺼진다 (없으면 CULPRIT_DEFAULTS) */
culprit?: {
apiKey: string | null;
@@ -59,6 +61,7 @@ export function loadConfig(env = process.env): Config {
webDir: env.WEB_DIR || path.resolve('../web/dist'),
version: env.GVR_VERSION || '1.0.0',
discordApi: env.DISCORD_API || 'https://discord.com/api/v10',
releasesApi: env.RELEASES_API || 'https://git.tkrmagid.kr/api/v1/repos/tkrmagid/game_voice_recorder/releases/latest',
assetUpstream: {
valmedia: 'https://media.valorant-api.com/',
ddragon: 'https://ddragon.leagueoflegends.com/',

22
site/server/src/csp.ts Normal file
View File

@@ -0,0 +1,22 @@
/**
* 사이트 CSP. 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게).
* 사이트 서버(app.ts)와 화면 미리보기(site/web vite preview)가 같은 값을 쓴다 → 헤드리스 확인도 실제와 같은 제한에서 한다.
* 'wasm-unsafe-eval': 맵 3D 압축 풀기(meshopt, WebAssembly)만 허용. 자바스크립트 eval 은 여전히 막힌다
* connect-src blob: 3D 파일(glb) 안 텍스처를 three.js 가 blob: 주소로 fetch 해 읽는다 (페이지가 만든 blob 만, 바깥 접속은 아님).
* 없으면 텍스처를 못 읽어 요원이 흰색, 맵 3D 는 통째로 실패해 미니맵으로 나온다
*/
export function contentSecurityPolicy(wsOrigin: string): string {
return [
"default-src 'self'",
"script-src 'self' 'wasm-unsafe-eval'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob: https://cdn.discordapp.com",
"media-src 'self' blob: data:",
"font-src 'self' data:",
`connect-src 'self' blob: ${wsOrigin}`,
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
].join('; ');
}

View File

@@ -52,6 +52,22 @@ export class DiscordApi {
const m: any = await r.json();
return { nick: m.nick ?? null, avatar: m.avatar ?? null };
}
private guildNames = new Map<string, { name: string | null; at: number }>();
/** 서버 이름 (로그인 화면 안내용, 10분 캐시). 모르면 null */
async guildName(guildId: string): Promise<string | null> {
const c = this.guildNames.get(guildId);
if (c && Date.now() - c.at < 600_000) return c.name;
let name: string | null = null;
try {
const r = await fetch(`${this.cfg.discordApi}/guilds/${guildId}`, { headers: { authorization: `Bot ${this.cfg.botToken}` } });
if (r.ok) name = ((await r.json()) as { name?: string }).name ?? null;
} catch {
/* 디스코드 장애면 이름 없이 안내 */
}
this.guildNames.set(guildId, { name, at: Date.now() });
return name;
}
}
/** 봇 토큰으로 디스코드 계정 조회 (유저 등록 때 이름 확인). 없는 아이디면 null */

141
site/server/src/maps3d.ts Normal file
View File

@@ -0,0 +1,141 @@
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
/**
* 발로란트 맵 3D 모양 (tools/map-extract 가 Riot CDN 에서 뽑아 tools/map-extract/scripts/update.sh 가 올린다).
* 게임 파일에서 나온 것이라 로그인한 사람(봇과 같은 서버 멤버)에게만 준다.
*
* <dataDir>/maps3d/index.json {version, dir, updatedAt, maps:{<맵 경로>:{code,file,bytes,triangles}}}
* <dataDir>/maps3d/<dir>/<code>.glb.gz meshopt 압축 glb 를 gzip 한 것. 위치는 UE 월드 좌표(cm)
* <dataDir>/maps3d/<dir>/abilities.json.gz · m_*.glb.gz · t_*.png.gz 스킬 목록 · 모델 · 텍스처 (모두 gzip)
*
* GET /site/maps3d → index.json (없으면 {maps:{}})
* GET /site/maps3d/:dir/:f → glb · json · png · jpg (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다
*
* 무기 스킨 (본 것만 뽑는다, tools/map-extract/scripts/skins-update.sh 가 몇 분마다 요청을 가져가 뽑아 올린다):
* <dataDir>/maps3d/skins/index.json {skins:{"스킨|단계|색상":{weapon, sig}}, looks:{서명:{w3p, points, w1p, points1p, gunClips}}, failed:{열쇠:이유}}
* <dataDir>/maps3d/skins/skin3p_<서명>.glb.gz · skin1p_<서명>.glb.gz (파일 이름이 모습마다 달라 오래 캐시한다)
* <dataDir>/maps3d/skins/want.json 사이트가 받은 요청 (아직 없는 열쇠, 시간 순 · 최대 MAX_WANT)
* GET /site/maps3d/skins → skins/index.json (없으면 빈 목록)
* POST /site/maps3d/skins/want {keys:[열쇠]} → 없는 것만 want.json 에 더한다
*/
export interface Maps3dIndex {
version: string;
dir: string;
updatedAt: string;
maps: Record<string, { code: string; file: string; bytes: number; triangles: number }>;
}
/** 보내는 파일 종류: 3D (맵 · 요원 · 무기 · 스킬 모델 · 공용 애니메이션) · 스킬 목록 · 스킬 텍스처 */
const TYPES: Record<string, string> = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' };
/** 스킨 요청 열쇠 "스킨|단계|색상" (게임 데이터 에셋 경로, 단계 · 색상은 비어도 된다). 추출기 Skins.ValidKey 와 같다 */
const SKIN_KEY = /^\/Game\/Equippables\/[A-Za-z0-9_/-]+\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?$/;
export const isSkinKey = (k: unknown): k is string => typeof k === 'string' && k.length < 600 && SKIN_KEY.test(k);
const MAX_WANT = 2000;
const MAX_WANT_PER_REQUEST = 100;
/** JSON 파일을 mtime 이 바뀔 때만 다시 읽는다 (없거나 깨졌으면 null) */
function jsonFile<T>(file: string): () => T | null {
let cache: { mtime: number; data: T | null } = { mtime: -1, data: null };
return () => {
let st: fs.Stats;
try {
st = fs.statSync(file);
} catch {
return null;
}
if (st.mtimeMs !== cache.mtime) {
try {
cache = { mtime: st.mtimeMs, data: JSON.parse(fs.readFileSync(file, 'utf8')) as T };
} catch {
cache = { mtime: st.mtimeMs, data: null };
}
}
return cache.data;
};
}
export interface SkinsIndex {
skins: Record<string, { weapon: string; sig: string }>;
looks: Record<string, { w3p?: string; points?: Record<string, number[]>; w1p?: string; points1p?: Record<string, number[]>; gunClips?: string[] }>;
failed?: Record<string, string>;
}
export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<unknown>, publicUrl?: string) {
const root = path.join(dataDir, 'maps3d');
let cache: { mtime: number; data: Maps3dIndex | null } = { mtime: -1, data: null };
const index = (): Maps3dIndex | null => {
const f = path.join(root, 'index.json');
let st: fs.Stats;
try {
st = fs.statSync(f);
} catch {
return null;
}
if (st.mtimeMs !== cache.mtime) {
try {
cache = { mtime: st.mtimeMs, data: JSON.parse(fs.readFileSync(f, 'utf8')) as Maps3dIndex };
} catch {
cache = { mtime: st.mtimeMs, data: null };
}
}
return cache.data;
};
app.get('/site/maps3d', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
reply.header('cache-control', 'private, no-cache');
return index() ?? { version: null, dir: null, maps: {} };
});
const skinsDir = path.join(root, 'skins');
const skins = jsonFile<SkinsIndex>(path.join(skinsDir, 'index.json'));
app.get('/site/maps3d/skins', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
reply.header('cache-control', 'private, no-cache');
return skins() ?? { skins: {}, looks: {} };
});
app.post<{ Body: { keys?: unknown } }>('/site/maps3d/skins/want', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
const origin = String(req.headers.origin || '');
if (origin && publicUrl && origin !== publicUrl) return reply.code(403).send({ error: 'bad_origin' });
const keys = Array.isArray(req.body?.keys) ? req.body.keys.slice(0, MAX_WANT_PER_REQUEST).filter(isSkinKey) : [];
const idx = skins();
const file = path.join(skinsDir, 'want.json');
let want: string[] = [];
try {
const w = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;
if (Array.isArray(w)) want = w.filter(isSkinKey);
} catch {
/* 처음이거나 깨졌으면 새로 */
}
const have = new Set(want);
const add = [...new Set(keys)].filter((k) => !have.has(k) && !idx?.skins?.[k] && !idx?.failed?.[k]);
if (add.length === 0) return { queued: 0 };
// 다 뽑은 것은 뺀다 (뽑는 쪽은 이 파일을 읽기만 한다)
want = [...want.filter((k) => !idx?.skins?.[k] && !idx?.failed?.[k]), ...add].slice(-MAX_WANT);
fs.mkdirSync(skinsDir, { recursive: true });
fs.writeFileSync(file + '.tmp', JSON.stringify(want));
fs.renameSync(file + '.tmp', file);
req.log.info({ area: 'skins', add: add.length, total: want.length }, '무기 스킨 요청');
return { queued: add.length };
});
app.get<{ Params: { dir: string; file: string } }>('/site/maps3d/:dir/:file', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
const { dir, file } = req.params;
const type = TYPES[path.extname(file).toLowerCase()];
if (!/^[\w.-]+$/.test(dir) || !/^[\w.-]+$/.test(file) || !type || dir.includes('..')) return reply.code(404).send({ error: 'not_found' });
const gz = path.join(root, dir, file + '.gz');
if (!fs.existsSync(gz)) return reply.code(404).send({ error: 'not_found' });
reply.header('cache-control', 'private, max-age=31536000, immutable').type(type);
if (/\bgzip\b/.test(String(req.headers['accept-encoding'] ?? ''))) {
reply.header('content-encoding', 'gzip').header('content-length', fs.statSync(gz).size);
return reply.send(fs.createReadStream(gz));
}
return reply.send(fs.createReadStream(gz).pipe(zlib.createGunzip()));
});
}

View File

@@ -30,6 +30,7 @@ export interface RelayResponse {
export class RelayHub {
private device: { ws: WebSocket; id: string; name: string; version: string | null; lastMsg: number } | null = null;
private browsers = new Set<WebSocket>();
private browserSessions = new Map<WebSocket, string>();
private pending = new Map<string, Pending>();
readonly deviceWss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024 });
readonly browserWss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 });
@@ -224,17 +225,38 @@ export class RelayHub {
}
// ------------------------------------------------------------------ 브라우저
attachBrowser(ws: WebSocket): void {
/**
* sessionId: 로그아웃하면 바로 끊는다 (closeSession).
* stillAllowed: 주기적으로(기본 30초) 세션이 살아 있고 봇과 같은 서버 멤버인지 다시 확인해, 아니면 4401 로 끊는다
*/
attachBrowser(ws: WebSocket, sessionId?: string, stillAllowed?: () => Promise<boolean>, recheckMs = 30000): void {
this.browsers.add(ws);
if (sessionId) this.browserSessions.set(ws, sessionId);
ws.send(JSON.stringify({ type: 'status', data: { device: this.status() } } satisfies BrowserMessage));
const ping = setInterval(() => ws.readyState === WebSocket.OPEN && ws.ping(), 25000);
const recheck = stillAllowed
? setInterval(() => {
void stillAllowed()
.catch(() => true) // 확인 자체가 실패하면(디스코드 장애) 유지
.then((ok) => {
if (!ok && ws.readyState === WebSocket.OPEN) ws.close(4401, 'unauthorized');
});
}, recheckMs)
: null;
ws.on('close', () => {
clearInterval(ping);
if (recheck) clearInterval(recheck);
this.browsers.delete(ws);
this.browserSessions.delete(ws);
});
ws.on('message', () => undefined);
}
/** 로그아웃: 그 세션의 실시간 연결을 끊는다 */
closeSession(sessionId: string): void {
for (const [ws, sid] of this.browserSessions) if (sid === sessionId) ws.close(4401, 'logged_out');
}
/** 로그아웃·세션 만료 시 해당 브라우저 연결 끊기용 */
get browserCount(): number {
return this.browsers.size;

View File

@@ -212,6 +212,15 @@ export class ServerStore {
} else delete this.d.displayNames[id];
this.save(true);
}
/** 표시 이름을 지운 뒤 디스코드에서 다시 받은 이름으로 세션 · 앱 유저 이름을 되돌린다 (예전 표시 이름이 남지 않게) */
restoreDiscordName(id: string, name: string): void {
if (this.d.displayNames[id]) return;
for (const s of this.d.sessions) if (s.user.id === id) s.user.name = name;
const u = this.appUser(id);
if (u) u.name = name;
if (this.d.appSeen[id]) this.d.appSeen[id].name = name;
this.save(true);
}
// ---- 앱 유저 등록 · 앱 로그인 토큰
appUsers(): AppUser[] {

View File

@@ -0,0 +1,71 @@
// 사이트 로그인: 게임 PC 앱에서 녹음할 서버로 고른 서버의 멤버만 들어온다.
// 앱이 서버를 알려 주기 전에만 ALLOWED_GUILD_IDS 를 쓴다.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { buildServer } from '../src/app.ts';
import type { Config } from '../src/config.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-guild-'));
// member1 은 111 서버에만 있다. 222 서버 이름은 "앱 서버"
async function fakeDiscord() {
const srv = http.createServer((req, res) => {
const u = new URL(req.url!, 'http://x');
res.setHeader('content-type', 'application/json');
if (u.pathname === '/oauth2/token') return res.end(JSON.stringify({ access_token: 'at' }));
if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'm', global_name: '멤버', avatar: null }));
if (u.pathname === '/guilds/111/members/member1') return res.end(JSON.stringify({ nick: '멤버', avatar: null }));
if (u.pathname === '/guilds/222') return res.end(JSON.stringify({ id: '222', name: '앱 서버' }));
res.statusCode = 404;
res.end('{}');
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
}
async function stack() {
const dc = await fakeDiscord();
const cfg: Config = {
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
allowedGuilds: ['111'], owners: [], superAdmins: [], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: dc.url, assetUpstream: {},
};
const { app, store } = await buildServer(cfg);
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
const login = async () => {
const start = await fetch(base + '/auth/discord', { redirect: 'manual' });
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
const cb = await fetch(`${base}/auth/discord/callback?code=c&state=${state}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
return cb.headers.get('location');
};
return { base, store, login, close: async () => (await app.close(), dc.close()) };
}
test('로그인: 앱이 서버를 알려 주기 전에는 ALLOWED_GUILD_IDS 멤버가 들어온다', async () => {
const s = await stack();
try {
assert.equal(await s.login(), '/');
} finally {
await s.close();
}
});
test('로그인: 앱에서 고른 서버의 멤버가 아니면 (ALLOWED_GUILD_IDS 멤버라도) 봇과 다른 서버라 막는다', async () => {
const s = await stack();
try {
const { code } = s.store.createCode('owner');
const dev = s.store.redeem(code, 'PC')!;
s.store.touchDevice(dev.deviceId, { guildId: '222' });
assert.equal(await s.login(), '/?login=not_member');
// 로그인 화면은 그 서버 이름으로 안내한다
const g = await (await fetch(s.base + '/auth/guild')).json();
assert.deepEqual(g, { name: '앱 서버' });
} finally {
await s.close();
}
});

View File

@@ -0,0 +1,129 @@
// 맵 3D (/site/maps3d): 로그인한 사람에게만, gzip 그대로 보낸다
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import zlib from 'node:zlib';
import { buildServer } from '../src/app.ts';
import type { Config } from '../src/config.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-maps3d-'));
// member1 은 111 서버에만 있다. 222 서버 이름은 "앱 서버"
async function fakeDiscord() {
const srv = http.createServer((req, res) => {
const u = new URL(req.url!, 'http://x');
res.setHeader('content-type', 'application/json');
if (u.pathname === '/oauth2/token') return res.end(JSON.stringify({ access_token: 'at' }));
if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'm', global_name: '멤버', avatar: null }));
if (u.pathname === '/guilds/111/members/member1') return res.end(JSON.stringify({ nick: '멤버', avatar: null }));
if (u.pathname === '/guilds/222') return res.end(JSON.stringify({ id: '222', name: '앱 서버' }));
res.statusCode = 404;
res.end('{}');
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
}
async function stack() {
const dc = await fakeDiscord();
const cfg: Config = {
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
allowedGuilds: ['111'], owners: [], superAdmins: [], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: dc.url, assetUpstream: {},
};
// 올려 둔 맵 3D (update.sh 가 만드는 모양)
const dir = path.join(cfg.dataDir, 'maps3d', 'V1-1');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'Ascent.glb.gz'), zlib.gzipSync(Buffer.from('glTF-test')));
fs.writeFileSync(path.join(dir, 'abilities.json.gz'), zlib.gzipSync(Buffer.from('{"classes":{}}')));
fs.writeFileSync(path.join(dir, 't_Smoke.png.gz'), zlib.gzipSync(Buffer.from('png-test')));
fs.writeFileSync(path.join(dir, 'secret.txt.gz'), zlib.gzipSync(Buffer.from('no')));
fs.writeFileSync(path.join(cfg.dataDir, 'maps3d', 'index.json'), JSON.stringify({ version: 'V1', dir: 'V1-1', updatedAt: 'x', maps: { '/Game/Maps/Ascent/Ascent': { code: 'Ascent', file: 'Ascent.glb', bytes: 1, triangles: 1 } } }));
const { app, store } = await buildServer(cfg);
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
const login = async () => {
const start = await fetch(base + '/auth/discord', { redirect: 'manual' });
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
const cb = await fetch(`${base}/auth/discord/callback?code=c&state=${state}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
return cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0]!;
};
return { base, store, login, dataDir: cfg.dataDir, close: async () => (await app.close(), dc.close()) };
}
test('맵 3D: 로그인 안 하면 목록 · 파일 모두 401', async () => {
const s = await stack();
try {
assert.equal((await fetch(s.base + '/site/maps3d')).status, 401);
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Ascent.glb')).status, 401);
} finally {
await s.close();
}
});
test('맵 3D: 로그인하면 목록과 glb 를 받는다 (gzip), 이상한 경로는 404', async () => {
const s = await stack();
try {
const cookie = await s.login();
const idx = (await (await fetch(s.base + '/site/maps3d', { headers: { cookie } })).json()) as any;
assert.equal(idx.dir, 'V1-1');
assert.ok(idx.maps['/Game/Maps/Ascent/Ascent']);
const r = await fetch(s.base + '/site/maps3d/V1-1/Ascent.glb', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(r.status, 200);
assert.equal(r.headers.get('content-encoding'), 'gzip');
assert.equal(await r.text(), 'glTF-test'); // fetch 가 gzip 을 풀어 준다
// 스킬 목록 · 텍스처도 같은 폴더에서 (gzip, 종류에 맞는 content-type)
const j = await fetch(s.base + '/site/maps3d/V1-1/abilities.json', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(j.status, 200);
assert.match(j.headers.get('content-type') ?? '', /application\/json/);
assert.deepEqual(await j.json(), { classes: {} });
const t = await fetch(s.base + '/site/maps3d/V1-1/t_Smoke.png', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(t.status, 200);
assert.equal(t.headers.get('content-type'), 'image/png');
// 정해진 종류(glb · json · png · jpg)가 아니면 404
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/secret.txt', { headers: { cookie } })).status, 404);
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/..%2Findex.json', { headers: { cookie } })).status, 404);
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Nope.glb', { headers: { cookie } })).status, 404);
} finally {
await s.close();
}
});
test('무기 스킨: 목록 · 파일은 로그인한 사람만, 요청은 없는 것만 want.json 에 쌓인다', async () => {
const s = await stack();
try {
const sk = path.join(s.dataDir, 'maps3d', 'skins');
fs.mkdirSync(sk, { recursive: true });
const have = '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset||';
const bad = '/Game/Equippables/Melee/Broken/Melee_Broken_PrimaryAsset||';
fs.writeFileSync(path.join(sk, 'index.json'), JSON.stringify({ skins: { [have]: { weapon: 'Vandal', sig: 'abc' } }, looks: { abc: { w3p: 'skin3p_abc.glb' } }, failed: { [bad]: '메시 없음' } }));
fs.writeFileSync(path.join(sk, 'skin3p_abc.glb.gz'), zlib.gzipSync(Buffer.from('skin')));
assert.equal((await fetch(s.base + '/site/maps3d/skins')).status, 401);
assert.equal((await fetch(s.base + '/site/maps3d/skins/want', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"keys":[]}' })).status, 401);
const cookie = await s.login();
const idx = (await (await fetch(s.base + '/site/maps3d/skins', { headers: { cookie } })).json()) as any;
assert.equal(idx.skins[have].sig, 'abc');
const f = await fetch(s.base + '/site/maps3d/skins/skin3p_abc.glb', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(f.status, 200);
assert.equal(await f.text(), 'skin');
const want = (keys: unknown[], origin?: string) =>
fetch(s.base + '/site/maps3d/skins/want', { method: 'POST', headers: { cookie, 'content-type': 'application/json', ...(origin ? { origin } : {}) }, body: JSON.stringify({ keys }) });
const k1 = '/Game/Equippables/Guns/Rifles/Carbine/SpecOps/Carbine_SpecOps_PrimaryAsset|/Game/Equippables/Guns/Rifles/Carbine/SpecOps/Levels/Carbine_SpecOps_Lv2_PrimaryAsset|';
// 이미 있는 것 · 실패한 것 · 형식이 틀린 것은 넣지 않는다
const r = await want([k1, have, bad, '../../etc/passwd||', 7, k1]);
assert.equal(r.status, 200);
assert.deepEqual(await r.json(), { queued: 1 });
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(sk, 'want.json'), 'utf8')), [k1]);
// 같은 것을 다시 요청하면 그대로
assert.deepEqual(await (await want([k1])).json(), { queued: 0 });
// 다른 사이트에서 온 요청은 막는다
assert.equal((await want([k1.replace('Lv2', 'Lv3')], 'https://evil.example')).status, 403);
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(sk, 'want.json'), 'utf8')), [k1]);
} finally {
await s.close();
}
});

View File

@@ -0,0 +1,132 @@
// 사이트 "내 정보" (표시 이름) · 관리 화면 API (v1.6.0)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { buildServer } from '../src/app.ts';
import type { Config } from '../src/config.ts';
const SUPER = '293719842274541579';
const ADMIN = '111111111111111111';
const MEMBER = '222222222222222222';
const OTHER = '333333333333333333';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-profile-'));
const NICK: Record<string, string> = { [SUPER]: '사금향', [ADMIN]: '관리', [MEMBER]: '멤버닉', [OTHER]: '다른' };
async function fakeDiscord() {
const srv = http.createServer((req, res) => {
const u = new URL(req.url!, 'http://x');
res.setHeader('content-type', 'application/json');
const m = /^\/guilds\/111\/members\/(\d+)$/.exec(u.pathname);
if (m && NICK[m[1]!]) return res.end(JSON.stringify({ nick: NICK[m[1]!], avatar: null }));
const usr = /^\/users\/(\d+)$/.exec(u.pathname);
if (usr && NICK[usr[1]!]) return res.end(JSON.stringify({ id: usr[1], username: 'u' + usr[1], global_name: NICK[usr[1]!], avatar: null }));
if (u.pathname === '/releases/latest') return res.end(JSON.stringify({ tag_name: 'v1.6.0', html_url: 'https://git.example/releases/tag/v1.6.0', published_at: '2026-10-17T00:00:00Z' }));
res.statusCode = 404;
res.end('{}');
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
}
async function stack() {
const dc = await fakeDiscord();
const cfg: Config = {
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
allowedGuilds: ['111'], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: dc.url, assetUpstream: {}, releasesApi: `${dc.url}/releases/latest`,
};
const { app, store } = await buildServer(cfg);
store.upsertAppUser({ id: ADMIN, name: '관리', avatar: null, role: 'admin', addedBy: SUPER });
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
const cookieOf = (id: string) => {
const s = store.createSession({ id, name: NICK[id]!, avatar: null });
return `gvr_sid=${app.signCookie(s.token)}`;
};
const as = (id: string) => {
const cookie = cookieOf(id);
const call = async (method: string, p: string, body?: unknown, origin = 'https://gvr.example') => {
const r = await fetch(base + p, { method, headers: { cookie, ...(body !== undefined ? { 'content-type': 'application/json', origin } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
return { status: r.status, json: (await r.json().catch(() => null)) as any };
};
return { get: (p: string) => call('GET', p), put: (p: string, b: unknown, o?: string) => call('PUT', p, b, o), post: (p: string, b: unknown) => call('POST', p, b), patch: (p: string, b: unknown) => call('PATCH', p, b), del: (p: string) => call('DELETE', p, {}) };
};
return { store, as, close: async () => (await app.close(), dc.close()) };
}
test('내 정보: 누구나 자기 표시 이름을 바꾸고, 지우면 디스코드 별명으로 돌아간다', async () => {
const s = await stack();
try {
const me = s.as(MEMBER);
assert.deepEqual((await me.get('/site/profile')).json, { user: { id: MEMBER, name: '멤버닉', avatar: null }, customName: null, role: null });
const r = await me.put('/site/profile/name', { name: ' 하늘 별 ' });
assert.equal(r.status, 200);
assert.equal(r.json.user.name, '하늘 별');
assert.equal((await me.get('/auth/me')).json.user.name, '하늘 별');
assert.equal(s.store.displayNames()[MEMBER], '하늘 별');
// 지우기 → 디스코드 서버 별명
const back = await me.put('/site/profile/name', { name: '' });
assert.equal(back.status, 200);
assert.equal(back.json.customName, null);
assert.equal((await me.get('/auth/me')).json.user.name, '멤버닉');
assert.equal(s.store.displayNames()[MEMBER], undefined);
} finally {
await s.close();
}
});
test('내 정보: 다른 사람 이름 · 너무 긴 이름 · 보이지 않는 글자 · 다른 사이트에서 온 요청은 막는다', async () => {
const s = await stack();
try {
assert.equal((await s.as(OTHER).put('/site/profile/name', { name: '하늘' })).status, 200);
const me = s.as(MEMBER);
const dup = await me.put('/site/profile/name', { name: '하늘' });
assert.equal(dup.status, 400);
assert.match(dup.json.message, /이미 쓰는 이름/);
assert.equal((await me.put('/site/profile/name', { name: '가'.repeat(33) })).status, 400);
assert.equal((await me.put('/site/profile/name', { name: '하​늘' })).status, 400);
assert.equal((await me.put('/site/profile/name', { name: '별' }, 'https://evil.example')).status, 403);
assert.equal(s.store.displayNames()[MEMBER], undefined);
} finally {
await s.close();
}
});
test('관리 화면: 관리자는 목록 · 남의 표시 이름, 등록 · 역할 · 해제는 최고 관리자만, 일반 멤버는 못 들어온다', async () => {
const s = await stack();
try {
const member = s.as(MEMBER);
const admin = s.as(ADMIN);
const sup = s.as(SUPER);
assert.equal((await member.get('/site/admin/users')).status, 403);
assert.equal((await member.get('/site/admin/overview')).status, 403);
assert.equal((await member.put('/site/admin/names', { id: OTHER, name: 'x' })).status, 403);
const list = await admin.get('/site/admin/users');
assert.equal(list.status, 200);
assert.deepEqual(list.json.users.map((u: any) => [u.id, u.role]), [[SUPER, 'superadmin'], [ADMIN, 'admin']]);
const ov = await admin.get('/site/admin/overview');
assert.equal(ov.json.role, 'admin');
assert.equal(ov.json.latest.version, '1.6.0');
assert.equal(ov.json.device.registered, false);
const named = await admin.put('/site/admin/names', { id: MEMBER, name: '지호' });
assert.equal(named.status, 200);
assert.equal(named.json.names[MEMBER], '지호');
assert.equal((await member.get('/auth/me')).json.user.name, '지호', '로그인해 있는 세션 이름도 바뀐다');
assert.equal((await admin.post('/site/admin/users', { id: MEMBER, role: 'user' })).status, 403);
const added = await sup.post('/site/admin/users', { id: MEMBER, role: 'user' });
assert.equal(added.status, 200);
assert.equal(added.json.users.find((u: any) => u.id === MEMBER).name, '지호', '등록할 때도 표시 이름으로');
assert.equal((await sup.patch(`/site/admin/users/${MEMBER}`, { role: 'admin' })).json.users.find((u: any) => u.id === MEMBER).role, 'admin');
assert.equal((await sup.patch(`/site/admin/users/${SUPER}`, { role: 'user' })).status, 400);
assert.equal((await sup.del(`/site/admin/users/${MEMBER}`)).status, 200);
assert.equal((await member.get('/site/admin/users')).status, 403);
} finally {
await s.close();
}
});

View File

@@ -0,0 +1,182 @@
// 사이트 3D 리플레이: 자동 시점(관전) 장면 나누기 · 점수판 (site/web/src/lib/director.ts · scoreboard.ts)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import type { ReplayFile } from '../../web/src/lib/replay.ts';
import { buildDirector, shotIndexAt, FIGHT_LEAD, type Shot } from '../../web/src/lib/director.ts';
import { boardAt, boardIndex, loadoutAt, sideSwaps, teamScoreAt } from '../../web/src/lib/scoreboard.ts';
import { fitDistance } from '../../web/src/lib/director.ts';
import * as THREE from '../../web/node_modules/three/build/three.module.js';
// 선수 0·1·4 아군, 2·3·5 상대. 라운드 1: 구매 0~30초, 교전 30초~, 끝 90초. 라운드 2: 100초~ (공수 교대: 시작 자리가 100m 옮겨 감)
const still = (n = 2000, swapAt = 100_000) => {
const t = Array.from({ length: n }, (_, i) => i * 100);
return { t, x: t.map((v) => (v >= swapAt ? 10_000 : 0)), y: t.map(() => 0), z: t.map(() => 100), yaw: t.map(() => 0), pitch: t.map(() => 0) };
};
function replay(extra: Partial<ReplayFile> = {}): ReplayFile {
return {
format: 'gvr-replay', v: 2, matchId: 'm1', map: null, build: null, recordedAt: 0, durationMs: 200_000, sampleMs: 100,
players: [0, 1, 2, 3, 4, 5].map((i) => ({ puuid: `p${i}`, character: i === 1 ? 'Phoenix_PC_C' : 'Wushu_PC_C', track: still() })),
rounds: [{ num: 1, buy: 0, combat: 30_000, end: 90_000 }, { num: 2, buy: 100_000, combat: 130_000, end: -1 }],
phases: [], shots: [], objects: [], objectKinds: [], kills: [], hits: [],
...extra,
};
}
const ally = [true, true, false, false, true, false];
const at = (shots: Shot[], t: number) => shots[shotIndexAt(shots, t)];
const hit = (t: number, a: number, v: number, killed = 0) => [t, a, v, 0, 0, 0, 0, 0, 0, 2, killed];
test('교전: 킬 시각에는 이긴(죽인) 선수 1인칭, 교전 시작보다 먼저 넘어간다', () => {
const r = replay({ kills: [[40_000, 0, 2, -1]], hits: [hit(38_000, 2, 0), hit(39_000, 0, 2), hit(40_000, 0, 2, 1)] });
const shots = buildDirector({ replay: r, ally, talks: [] });
const s = at(shots, 40_000);
assert.equal(s.kind, 'fight');
assert.equal(s.pov, 0);
// 둘 사이 첫 맞은 기록(38초)보다 FIGHT_LEAD 앞에서 시작
assert.ok(s.t0 <= 38_000 - FIGHT_LEAD, `시작 ${s.t0}`);
// 교전이 없을 때: 구매 단계 · 전략 보기는 위에서
assert.equal(at(shots, 10_000).kind, 'buy');
assert.equal(at(shots, 10_000).pov, null);
assert.equal(at(shots, 70_000).kind, 'overview');
assert.equal(at(shots, 70_000).pov, null);
assert.equal(at(shots, 95_000).kind, 'post');
// 빈틈 · 겹침 없이 처음부터 끝까지
assert.equal(shots[0].t0, 0);
assert.equal(shots[shots.length - 1].t1, r.durationMs);
for (let i = 1; i < shots.length; i++) assert.equal(shots[i].t0, shots[i - 1].t1);
});
test('교전 직전 우리 팀 콜이 있으면 그 말부터 보여 주고 콜 글을 단다', () => {
const r = replay({ kills: [[40_000, 2, 0, -1]], hits: [hit(38_000, 2, 0), hit(40_000, 2, 0, 1)] });
const shots = buildDirector({ replay: r, ally, talks: [{ t0: 33_000, t1: 34_500, text: '비 메인 두 명' }] });
const s = at(shots, 40_000);
// 상대가 이겼으면 상대 시점
assert.equal(s.pov, 2);
assert.equal(s.call, '비 메인 두 명');
assert.ok(s.t0 <= 33_000 && s.t0 >= 32_000, `시작 ${s.t0}`);
// 교전과 먼 대화는 콜로 보지 않는다
const far = buildDirector({ replay: r, ally, talks: [{ t0: 20_000, t1: 21_000, text: '사러 가자' }] });
assert.equal(at(far, 40_000).call, undefined);
});
test('같은 선수가 이어서 죽이면 한 장면 · 거의 동시에 맞바꾼 킬은 넘어가지 않는다 · 짧은 장면 없음', () => {
const r = replay({
kills: [[40_000, 0, 2, -1], [42_000, 0, 3, -1], [60_000, 1, 2, -1], [60_300, 3, 1, -1]],
hits: [hit(39_500, 0, 2, 1), hit(41_800, 0, 3, 1), hit(59_000, 1, 2), hit(60_200, 3, 1)],
});
const shots = buildDirector({ replay: r, ally, talks: [] });
const multi = at(shots, 41_000);
assert.equal(multi.pov, 0);
assert.equal(multi.kills, 2);
assert.equal(at(shots, 42_000), multi);
// 0.3초 뒤 맞킬: 앞 킬을 보여 주던 선수 시점 그대로
assert.equal(at(shots, 60_300).pov, 1);
for (const s of shots) if (s.pov != null) assert.ok(s.t1 - s.t0 >= 900, `짧은 1인칭 ${s.t0}~${s.t1}`);
});
test('스파이크 설치 · 해체는 하는 선수 시점, 혼자 남은 선수는 그 선수 시점', () => {
const r = replay({
actions: [[50_000, 54_000, 3, 0]],
actionKinds: ['Plant'],
kills: [[60_000, 2, 0, -1], [62_000, 3, 4, -1]],
hits: [hit(59_000, 2, 0, 1), hit(61_500, 3, 4, 1)],
});
const shots = buildDirector({ replay: r, ally, talks: [] });
assert.equal(at(shots, 52_000).kind, 'plant');
assert.equal(at(shots, 52_000).pov, 3);
// 60초에 0 이 죽고, 62초에 4 가 죽어 아군은 1 혼자
const c = at(shots, 75_000);
assert.equal(c.kind, 'clutch');
assert.equal(c.pov, 1);
});
test('점수판: 궁극기 점수는 쓴 기록에서 · 공수 교대 초기화는 쓴 것이 아니다 · 안 온 숫자는 0', () => {
// [t, 선수, 크레딧, 궁, 킬, 데스, 어시, 점수]
const sb = [
[1000, 0, 800, -1, -1, -1, -1, -1],
[1000, 1, 800, -1, -1, -1, -1, -1],
[20_000, 1, 800, 7, -1, -1, -1, -1],
[25_000, 1, 800, 0, -1, -1, -1, -1], // 1 이 궁을 씀 (7점)
[40_000, 0, 3900, 5, 2, 1, 1, 400],
[41_000, 1, 2000, 3, -1, -1, -1, -1],
[42_000, 2, 800, 2, -1, -1, -1, -1],
[42_000, 3, 800, 1, -1, -1, -1, -1],
// 공수 교대: 모두 0
[95_000, 0, 800, 0, 2, 1, 1, 400],
[95_000, 1, 800, 0, -1, -1, -1, -1],
[95_100, 2, 800, 0, -1, -1, -1, -1],
[95_100, 3, 800, 0, -1, -1, -1, -1],
];
const r = replay({ scoreboard: sb, kills: [[40_000, 0, 2, -1]], equips: [[31_000, 0, 0], [32_000, 0, 1], [33_000, 0, 2]], equipKinds: ['Classic', 'Vandal', 'Melee'] });
const ix = boardIndex(r);
assert.equal(ix.has, true);
assert.equal(ix.ultMax[1], 7); // 쓴 기록 (요원 표와 상관없이)
assert.equal(ix.ultMax[0], 8); // 쓴 기록 없음: 요원 표 (제트 8)
const b = boardAt(r, ix, 0, 50_000);
assert.deepEqual([b.money, b.ult, b.kills, b.deaths, b.assists, b.score, b.weapon], [3900, 5, 2, 1, 1, 400, 'Vandal']);
// 아직 안 온 킬 · 어시는 0, 크레딧은 처음 값
const b1 = boardAt(r, ix, 1, 50_000);
assert.deepEqual([b1.money, b1.ult, b1.kills, b1.assists], [2000, 3, 0, 0]);
// 주무기는 라운드마다: 다음 라운드에는 아직 없음
assert.equal(loadoutAt(r, 0, 120_000), null);
// 죽은 선수 (시험 이동 기록은 죽은 뒤에도 표본이 있어 죽은 직후로 본다)
assert.equal(boardAt(r, ix, 2, 41_000).dead, true);
});
test('점수판: 예전 리플레이(값 없음)는 킬 · 데스를 킬 기록으로 세고 나머지는 비운다 · 팀 점수는 그 라운드 전까지', () => {
const r = replay({ kills: [[40_000, 0, 2, -1], [50_000, 3, 0, -1]] });
const ix = boardIndex(r);
assert.equal(ix.has, false);
const b = boardAt(r, ix, 0, 60_000);
assert.deepEqual([b.kills, b.deaths, b.money, b.ult, b.assists], [1, 1, null, null, null]);
const rounds = [{ num: 1, score: { ally: 1, enemy: 0 } }, { num: 2, score: { ally: 1, enemy: 1 } }];
assert.deepEqual(teamScoreAt(r, rounds, 50_000), { round: 1, ally: 0, enemy: 0 });
assert.deepEqual(teamScoreAt(r, rounds, 150_000), { round: 2, ally: 1, enemy: 0 });
});
test('점수판: 한 명만 궁 점수가 있어도 공수 교대 초기화는 궁 사용이 아니다 · 교대가 없으면 라운드 끝 0 은 사용', () => {
// 선수 1(피닉스)만 3점을 모은 채 1라운드가 끝나고(90초) 2라운드 구매 시작(100초) 직전에 0
const sb = [[20_000, 1, 800, 3, -1, -1, -1, -1], [99_000, 1, 800, 0, -1, -1, -1, -1]];
const r = replay({ scoreboard: sb });
assert.deepEqual([...sideSwaps(r)], [1]);
const ix = boardIndex(r);
assert.equal(ix.ultMax[1], 7); // 요원 표 (피닉스 7), 3 이 아니다
assert.equal(boardAt(r, ix, 1, 50_000).ult, 3);
// 같은 기록이라도 교대가 아니면(시작 자리 그대로) 쓴 것으로 본다
const same = replay({ scoreboard: sb, players: [0, 1, 2, 3, 4, 5].map((i) => ({ puuid: `p${i}`, character: 'Phoenix_PC_C', track: still(2000, Infinity) })) });
assert.deepEqual([...sideSwaps(same)], []);
assert.equal(boardIndex(same).ultMax[1], 3);
});
test('점수판: 마지막 라운드가 끝난 뒤에는 최종 점수', () => {
const r = replay({ rounds: [{ num: 1, buy: 0, combat: 30_000, end: 90_000 }, { num: 2, buy: 100_000, combat: 130_000, end: 180_000 }] });
const rounds = [{ num: 1, score: { ally: 1, enemy: 0 } }, { num: 2, score: { ally: 2, enemy: 0 } }];
assert.deepEqual(teamScoreAt(r, rounds, 170_000), { round: 2, ally: 1, enemy: 0 });
assert.deepEqual(teamScoreAt(r, rounds, 190_000), { round: 2, ally: 2, enemy: 0 });
// 1라운드 끝 ~ 2라운드 구매 사이도 그 라운드 결과까지
assert.deepEqual(teamScoreAt(r, rounds, 95_000), { round: 1, ally: 1, enemy: 0 });
});
test('전략 보기 카메라: 시야각 · 화면비 · 기울기를 넣어 구한 거리면 모든 선수가 화면 안 (three.js 투영으로 확인)', () => {
const dir: [number, number, number] = [0, 0.92 / Math.hypot(0.92, 0.42), 0.42 / Math.hypot(0.92, 0.42)];
const cases: { pts: [number, number, number][]; aspect: number }[] = [
{ pts: [[-35, 0, -40], [35, 0, 40]], aspect: 1 },
{ pts: [[-45, 2, 10], [40, 8, -45], [0, 0, 48]], aspect: 16 / 9 },
{ pts: [[-10, 0, -45], [10, 0, 45]], aspect: 0.6 },
];
for (const { pts, aspect } of cases) {
const c = pts.reduce((a, p) => [a[0] + p[0] / pts.length, a[1] + p[1] / pts.length, a[2] + p[2] / pts.length], [0, 0, 0]) as [number, number, number];
const d = fitDistance(pts, c, dir, 45, aspect);
const cam = new THREE.PerspectiveCamera(45, aspect, 0.5, 2000);
cam.position.set(c[0] + dir[0] * d, c[1] + dir[1] * d, c[2] + dir[2] * d);
cam.lookAt(c[0], c[1], c[2]);
cam.updateMatrixWorld();
let edge = 0;
for (const p of pts) {
const v = new THREE.Vector3(...p).project(cam);
assert.ok(Math.abs(v.x) <= 0.86 && Math.abs(v.y) <= 0.86, `화면 밖 ${p} → ${v.x.toFixed(3)},${v.y.toFixed(3)} (화면비 ${aspect})`);
edge = Math.max(edge, Math.abs(v.x), Math.abs(v.y));
}
// 가장 짧은 거리: 가장 바깥 선수가 가장자리(0.85)에 닿는다
assert.ok(edge > 0.84, `너무 멀다 ${edge}`);
}
});

View File

@@ -0,0 +1,56 @@
// 사이트 3D 리플레이: 무기 스킨 찾기 (site/web/src/lib/skins.ts · replay.ts skinTracks)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { equipAt, skinTracks, type ReplayFile, type SkinInfo } from '../../web/src/lib/replay.ts';
import { chunks, isDefaultSkin, lookOf, missingSkins, skinKey, WANT_CHUNK } from '../../web/src/lib/skins.ts';
const hype: SkinInfo = {
skin: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset',
level: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_Lv4_PrimaryAsset',
chroma: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/Chromas/Blue/AssaultRifle_AK_HypeBeast_Blue_PrimaryAsset',
};
const knife: SkinInfo = { skin: '/Game/Equippables/Melee/Standard/Melee_Base_Standard_PrimaryAsset', level: null, chroma: '/Game/Equippables/Melee/Standard/Chromas/Standard/Melee_Base_Standard_Standard_PrimaryAsset' };
const ghost: SkinInfo = { skin: '/Game/Equippables/Guns/Sidearms/Luger/Sovereign/Luger_Sovereign_PrimaryAsset', level: null, chroma: null };
test('스킨: 선수가 그 시각에 든 총의 스킨 (주운 총은 그 총의 스킨, 옛 JSON 은 -1)', () => {
const r = {
players: [{}, {}],
skins: [hype, ghost],
// 선수 0: 1초 밴달(hype) · 5초 칼(스킨 기록 없음) · 9초 주운 고스트. 선수 1: 옛 3열 줄
equips: [[1000, 0, 0, 0], [5000, 0, 1, -1], [9000, 0, 2, 1], [2000, 1, 0]],
} as unknown as ReplayFile;
const tr = skinTracks(r);
assert.equal(equipAt(tr[0], 500), -1);
assert.equal(equipAt(tr[0], 3000), 0);
assert.equal(equipAt(tr[0], 6000), -1);
assert.equal(equipAt(tr[0], 9500), 1);
assert.equal(equipAt(tr[1], 3000), -1);
});
test('스킨: 뽑아 둔 것은 그 모습, 기본 스킨 · 없는 것은 null, 없는 것만 요청 목록에', () => {
assert.equal(isDefaultSkin(knife), true);
assert.equal(isDefaultSkin(hype), false);
assert.equal(isDefaultSkin({ skin: '/Game/Equippables/Guns/Sidearms/Compact/Compact_Standard_PrimaryAsset', level: null, chroma: null }), true);
const idx = {
skins: { [skinKey(hype)]: { weapon: 'Vandal', sig: 's1' } },
looks: { s1: { w3p: 'skin3p_s1.glb', w1p: 'skin1p_s1.glb' } },
failed: {} as Record<string, string>,
};
assert.equal(lookOf(idx, hype)?.w3p, 'skin3p_s1.glb');
assert.equal(lookOf(idx, ghost), null);
assert.equal(lookOf(idx, knife), null);
// 같은 스킨이 여러 번 나와도 한 번, 기본 스킨은 요청하지 않는다
assert.deepEqual(missingSkins(idx, { skins: [hype, ghost, knife, { ...ghost }] }), [skinKey(ghost)]);
// 뽑다 실패한 것은 다시 요청하지 않는다
idx.failed[skinKey(ghost)] = '메시 없음';
assert.deepEqual(missingSkins(idx, { skins: [ghost] }), []);
assert.equal(skinKey(ghost), '/Game/Equippables/Guns/Sidearms/Luger/Sovereign/Luger_Sovereign_PrimaryAsset||');
});
test('스킨 요청: 서버 한도(100개)씩 나눠 빠짐없이', () => {
const keys = Array.from({ length: 2 * WANT_CHUNK + 1 }, (_, i) => `k${i}`);
const parts = chunks(keys);
assert.deepEqual(parts.map((p) => p.length), [100, 100, 1]);
assert.deepEqual(parts.flat(), keys);
assert.deepEqual(chunks([]), []);
});

View File

@@ -0,0 +1,59 @@
// 사이트 3D 리플레이: 리플레이 시간 ↔ 기록 시각 맞추기 · 위치 보간 · 죽음 판정 (site/web/src/lib/replay.ts)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { computeSync, isDead, samplePlayer, type ReplayFile } from '../../web/src/lib/replay.ts';
const track = (pts: [number, number][]) => ({ t: pts.map((p) => p[0]), x: pts.map((p) => p[1]), y: pts.map(() => 0), z: pts.map(() => 100), yaw: pts.map(() => 350), pitch: pts.map(() => 0) });
function replay(): ReplayFile {
return {
format: 'gvr-replay', v: 1, matchId: 'm1', map: null, build: null, recordedAt: 1_000_000, durationMs: 200_000, sampleMs: 100,
players: [
{ puuid: 'a', character: null, track: track([[0, 0], [10_000, 1000], [50_000, 1000]]) },
{ puuid: 'b', character: null, track: track([[0, 0], [40_000, 500]]) },
{ puuid: 'c', character: null, track: track([[0, 0], [90_000, 0]]) },
],
rounds: [{ num: 1, buy: 0, combat: 30_000, end: 80_000 }, { num: 2, buy: 100_000, combat: 130_000, end: -1 }],
phases: [], shots: [], objects: [], objectKinds: [],
kills: [[40_000, 0, 1], [60_000, 2, 0], [140_000, 0, 2]],
};
}
const kill = (id: string, ts: number, killer: string, victim: string) => ({ kind: 'event', id, ts, type: 'kill', data: { killer: { puuid: killer, name: killer }, victim: { puuid: victim, name: victim }, assists: [], weapon: null } });
test('킬 시각 차이의 중앙값으로 맞추고, 킬별 오차를 낸다', () => {
const r = replay();
// 경기 기록이 리플레이보다 2.5초 늦게 찍혔고, 한 킬은 0.2초 더 늦다
const m: any = { startedAt: 0, rounds: [], events: [kill('k1', 1_000_000 + 40_000 + 2500, 'a', 'b'), kill('k2', 1_000_000 + 60_000 + 2500, 'c', 'a'), kill('k3', 1_000_000 + 140_000 + 2700, 'a', 'c')] };
const s = computeSync(m, r);
assert.equal(s.matched, 3);
assert.equal(s.offset, 2500);
assert.equal(s.spreadMs, 200);
});
test('킬을 못 맞추면 라운드 교전 시작(앱이 저장한 라운드 시작 + 30초)으로 맞춘다', () => {
const r = replay();
const m: any = { startedAt: 0, events: [], rounds: [{ num: 1, startedAt: 1_000_000 + 30_000 - 30_000 + 4000 }, { num: 2, startedAt: 1_000_000 + 130_000 - 30_000 + 4000 }] };
const s = computeSync(m, r);
assert.equal(s.matched, 0);
assert.equal(s.offset, 4000);
assert.equal(s.spreadMs, null);
});
test('위치는 앞뒤 표본 사이를 보간하고, 방향은 짧은 쪽으로 돈다', () => {
const tr = track([[0, 0], [100, 100]]);
tr.yaw = [350, 10];
const p = samplePlayer(tr, 50, 600)!;
assert.equal(p.x, 50);
assert.equal(p.yaw, 360);
assert.equal(samplePlayer(tr, -1000, 600), null);
});
test('죽음: 이 라운드에서 죽은 뒤 다시 움직이지 않으면 죽은 상태, 다음 라운드엔 살아남', () => {
const r = replay();
assert.equal(isDead(r, 1, 39_000), false);
assert.equal(isDead(r, 1, 45_000), true);
// a 는 60초에 죽었지만 기록은 50초까지뿐 → 죽음. 다음 라운드(100초~)에는 다시 산다
assert.equal(isDead(r, 0, 70_000), true);
assert.equal(isDead(r, 0, 110_000), false);
// c 는 60초 킬 뒤에도 90초까지 움직였으므로 140초 킬 전까지 살아 있음
assert.equal(isDead(r, 2, 120_000), false);
});

View File

@@ -26,7 +26,7 @@ async function fakeDiscord() {
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
}
async function stack(dataDir = tmp()) {
async function stack(dataDir = tmp(), opts: { browserRecheckMs?: number } = {}) {
const dc = await fakeDiscord();
const cfg: Config = {
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
@@ -34,7 +34,7 @@ async function stack(dataDir = tmp()) {
version: 'test', discordApi: dc.url, assetUpstream: {},
};
const lines: string[] = [];
const { app, store } = await buildServer(cfg);
const { app, store } = await buildServer(cfg, opts);
// 서버 로그를 모아 둔다 (비밀값이 남는지 본다)
const orig = process.stdout.write.bind(process.stdout);
(process.stdout as any).write = (chunk: any, ...rest: any[]) => (lines.push(String(chunk)), orig(chunk, ...rest));
@@ -62,8 +62,8 @@ test('보안 헤더: CSP 는 이 사이트 스크립트 · 접속만 허용하
const r = await fetch(s.base + '/healthz');
const csp = r.headers.get('content-security-policy') ?? '';
assert.match(csp, /default-src 'self'/);
assert.match(csp, /script-src 'self'(;|$)/);
assert.match(csp, /connect-src 'self' wss:\/\/gvr\.example/);
assert.match(csp, /script-src 'self' 'wasm-unsafe-eval'(;|$)/); // WebAssembly(맵 3D 압축 풀기)만, eval 은 안 됨
assert.match(csp, /connect-src 'self' blob: wss:\/\/gvr\.example(;|$)/); // blob: = 3D 파일 안 텍스처 (없으면 요원 흰색 · 맵 3D 실패)
assert.match(csp, /frame-ancestors 'none'/);
assert.equal(r.headers.get('x-content-type-options'), 'nosniff');
} finally {
@@ -89,6 +89,28 @@ test('실시간 WebSocket: 다른 사이트에서 로그인 쿠키로 붙으면
}
});
test('실시간 WebSocket: 세션이 지워지거나(서버 탈퇴 등) 로그아웃하면 이미 열린 연결도 끊는다', async () => {
const s = await stack(tmp(), { browserRecheckMs: 50 });
try {
const connect = async (sid: string) => {
const ws = new WebSocket(s.base.replace('http', 'ws') + '/ws', { headers: { cookie: sid, origin: 'https://gvr.example' } });
await new Promise((r) => ws.on('open', r));
return { ws, closed: new Promise<number>((r) => ws.on('close', (code) => r(code))) };
};
// 1) 세션 삭제 (getSession 의 서버 멤버 재확인이 실패하면 이렇게 지운다) → 다음 확인 때 끊김
const a = await connect(await s.login());
for (const x of [...(s.store as any).d.sessions]) s.store.deleteSession(x.id);
assert.equal(await a.closed, 4401);
// 2) 로그아웃 → 바로 끊김
const sid = await s.login();
const b = await connect(sid);
await fetch(s.base + '/auth/logout', { method: 'POST', headers: { cookie: sid } });
assert.equal(await b.closed, 4401);
} finally {
await s.close();
}
});
test('세션: 서버 파일에는 세션 토큰 대신 해시만 남고, 예전 파일의 세션도 그대로 이어진다', async () => {
const s = await stack();
try {

View File

@@ -0,0 +1,51 @@
// 사이트 화면: 처음 보는 유저 아이디가 오면 유저 목록을 다시 받는 규칙 (site/web/src/lib/unknown-users.ts)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { makeUnknownUserCheck } from '../../web/src/lib/unknown-users.ts';
const tick = () => new Promise((r) => setTimeout(r, 0));
test('모르는 유저: 받는 중에는 또 부르지 않고, 실패하면 다음 이벤트에서 다시 받는다', async () => {
const known = new Set(['a']);
let calls = 0;
let fail = true;
let release!: () => void;
const check = makeUnknownUserCheck(() => {
calls++;
return new Promise<void>((ok, no) => {
release = () => (fail ? no(new Error('500')) : (known.add('late'), ok()));
});
});
const has = (id: string) => known.has(id);
check(['a'], has);
assert.equal(calls, 0, '아는 사람은 부르지 않음');
check(['late'], has);
check(['late'], has);
assert.equal(calls, 1, '받는 중에는 한 번만');
release(); // 500
await tick();
check(['late'], has);
assert.equal(calls, 2, '실패 뒤 다음 발화에서 다시 받음');
fail = false;
release();
await tick();
assert.ok(known.has('late'));
check(['late'], has);
assert.equal(calls, 2, '받은 뒤에는 부르지 않음');
});
test('모르는 유저: 받았는데도 목록에 없는 아이디는 발화마다 다시 부르지 않는다', async () => {
let calls = 0;
const check = makeUnknownUserCheck(async () => {
calls++;
});
const has = () => false;
check(['ghost'], has);
await tick();
check(['ghost'], has);
check(['ghost', ''], has);
assert.equal(calls, 1);
check(['other'], has);
assert.equal(calls, 2, '다른 새 아이디는 다시 받음');
});

View File

@@ -2,6 +2,8 @@
// 롤 1판(19:40 무렵) → 발로란트 바인드(패) → 발로란트 어센트(13:9 승) → 경기 후 잡담.
// 이미지 URL 은 실제 사이트 서버 캐시 경로 형식(/game-assets/...)을 흉내 낸 /game-assets/mock/...
import fs from 'node:fs';
export const A = (p) => `/game-assets/mock/${p}`;
function mulberry32(a) {
@@ -505,6 +507,107 @@ post.forEach(([u, text, status], i) => {
addUtt({ user: u, ts, text, status, time: realLabel(ts) });
});
// ── 3D 리플레이 데모 (선택) ─────────────────────────────
// GVR_MOCK_REPLAY=<gvr-replay JSON 경로> (+ GVR_MOCK_REPLAY_MAP_FILE=<어비스 미니맵 png>) 를 주면 그 리플레이로 경기 하나를 만든다 (실제 리플레이는 저장소에 넣지 않는다).
// 경기 기록(킬 시각)은 리플레이보다 MOCK_SYNC_OFFSET 만큼 늦게 찍어, 사이트가 그 차이를 맞추는지 본다.
export const MOCK_SYNC_OFFSET = 1234;
function genReplayDemo(file) {
const r = JSON.parse(fs.readFileSync(file, 'utf8'));
const id = 'val-replay-demo';
const base = r.recordedAt + MOCK_SYNC_OFFSET;
// 팀: 같은 팀끼리는 (거의) 안 죽이므로 킬 관계로 두 편을 나눈다 (실제 사이트는 경기 기록의 팀을 쓴다)
const adj = r.players.map(() => new Set());
for (const [, k, v] of r.kills) if (k >= 0 && v >= 0 && k !== v) (adj[k].add(v), adj[v].add(k));
const side = new Map([[0, 0]]);
const stack = [0];
while (stack.length) {
const x = stack.pop();
for (const y of adj[x]) if (!side.has(y)) (side.set(y, 1 - side.get(x)), stack.push(y));
}
const allyIdx = new Set(r.players.map((_, i) => i).filter((i) => side.get(i) === 0));
const AGK = { Wushu_PC_C: AG.jett, Hunter_PC_C: AG.sova, Thorne_PC_C: AG.sage, Wraith_PC_C: AG.omen, Killjoy_PC_C: AG.killjoy, Clay_PC_C: AG.raze, Vampire_PC_C: AG.reyna };
let si = 0;
let an = 0;
let en = 0;
const players = r.players.map((p, i) => {
const ally = allyIdx.has(i);
const user = ally && si < SPEAKERS.length ? SPEAKERS[si++] : null;
const name = user ? user.name : ally ? `아군${++an}` : `상대${++en}`;
const cls = (p.character ?? '').replace(/_PC_C$/, '');
return { puuid: p.puuid, name, tag: 'KR1', team: ally ? 'Blue' : 'Red', ally, character: AGK[p.character] ?? { id: cls, name: cls, icon: null }, userId: user?.id, kills: 0, deaths: 0, assists: 0, score: 0, rank: null };
});
const ref = (i) => (i >= 0 ? { puuid: players[i].puuid, name: players[i].name, team: players[i].team, character: players[i].character, userId: players[i].userId } : null);
const mEvents = [];
const mUtts = [];
const rounds = [];
let score = { ally: 0, enemy: 0 };
r.rounds.forEach((rd, k) => {
const next = r.rounds[k + 1];
const startedAt = base + (rd.combat >= 0 ? rd.combat - 30000 : rd.buy);
const endedAt = base + (next ? (next.combat >= 0 ? next.combat - 30000 : next.buy) : r.durationMs);
const kills = r.kills.filter(([t]) => t >= rd.buy && (!next || t < next.buy));
const allyDead = kills.filter(([, , v]) => allyIdx.has(v)).length;
const enemyDead = kills.filter(([, , v]) => !allyIdx.has(v)).length;
const win = enemyDead >= allyDead;
win ? score.ally++ : score.enemy++;
rounds.push({ num: rd.num, startedAt, endedAt, win, result: 'Elimination', score: { ...score }, economy: {}, players: {} });
const label = (ts) => {
const inRound = ts - startedAt;
return { primary: inRound < 30000 ? `R${rd.num} · 구매` : `R${rd.num} · ${fmtClock(inRound - 30000)}`, secondary: fmtClock(ts - base), real: ts };
};
for (const [t, ki, vi] of kills) {
const ts = base + t;
if (ki >= 0) players[ki].kills++;
if (vi >= 0) players[vi].deaths++;
mEvents.push({ kind: 'event', id: nid('ev_'), ts, game: 'valorant', matchId: id, type: 'kill', round: rd.num, data: { killer: ref(ki), victim: ref(vi), assists: [], weapon: null, location: null, ally: ki >= 0 && allyIdx.has(ki) }, time: label(ts) });
}
mEvents.push({ kind: 'event', id: nid('ev_'), ts: endedAt - 1, game: 'valorant', matchId: id, type: 'round_end', round: rd.num, data: { round: rd.num, win, result: 'Elimination', score: { ...score } }, time: label(endedAt - 1) });
// 대화: 라운드마다 3~5개
const n = irange(3, 5);
for (let j = 0; j < n; j++) {
const ts = startedAt + irange(5, Math.max(6, Math.floor((endedAt - startedAt) / 1000) - 3)) * 1000;
mUtts.push(addUtt({ user: pick(SPEAKERS), ts, text: pick(VAL_LINES), game: { type: 'valorant', matchId: id, round: rd.num }, time: label(ts) }));
}
});
const endedAt = base + r.durationMs;
events.push(...mEvents);
const T = { xMultiplier: 8.1e-5, yMultiplier: -8.1e-5, xScalarToAdd: 0.5, yScalarToAdd: 0.5 };
const summary = {
id, game: 'valorant', startedAt: base, endedAt, map: { id: '/Game/Maps/Infinity/Infinity', name: '어비스', image: process.env.GVR_MOCK_REPLAY_MAP_FILE ? A('replay-map.png') : null },
mode: '경쟁전', win: score.ally > score.enemy, score, status: 'complete', participants: SPEAKERS.map((u) => u.id),
};
matches.push({ ...summary, players, rounds, events: mEvents, utterances: mUtts, mapTransform: { valorant: T }, replayPath: file });
}
if (process.env.GVR_MOCK_REPLAY) genReplayDemo(process.env.GVR_MOCK_REPLAY);
// Riot 경기 기록에서 가져온 경기 (v1.9.0, 겜녹이가 꺼져 있을 때 한 경기): 녹음 · 타임라인 없음
{
const base = matches.find((m) => m.game === 'valorant');
const MAPS = ['어센트', '바인드', '헤이븐', '로터스', '선셋'];
for (let i = 0; i < 70; i++) {
const start = NOW - (1 + i * 0.37) * 24 * 60 * MIN;
const ally = 13;
const enemy = (i * 5) % 12;
const win = i % 3 !== 0;
matches.push({
...base,
id: `val-hist-${i}`,
startedAt: start,
endedAt: start + 38 * MIN,
map: { ...base.map, name: MAPS[i % MAPS.length] },
mode: i % 7 === 3 ? '데스매치' : i % 4 === 0 ? '일반전' : '경쟁전',
win,
score: win ? { ally, enemy } : { ally: enemy, enemy: ally },
status: 'complete',
participants: [],
source: 'history',
utterances: [],
events: [],
replayPath: undefined,
});
}
}
// ── 내보내기 ─────────────────────────────────────────
export const db = {
users: USERS,

View File

@@ -6,6 +6,8 @@
// GET /mock/device?registered=0|1 등록 안 된 상태 흉내
// GET /mock/live?on=0|1 주기적 가짜 실시간 발화 켜기/끄기
// GET /mock/emit 가짜 실시간 발화 하나 즉시 만들기
// GET /mock/latejoin 녹음 중에 새 사람이 들어와 말함 (v1.4.1 이하 앱처럼 users.updated 없이 발화만 보냄). ?again=1 이면 마지막에 들어온 사람이 또 말함
// GET /mock/users-fail?n=1 다음 n 번 /api/users 를 500 으로 실패
// GET /auth/discord?as=notmember 길드 멤버가 아닌 계정으로 로그인 흉내 (403 not_member)
import http from 'node:http';
import fs from 'node:fs';
@@ -19,11 +21,40 @@ const here = path.dirname(fileURLToPath(import.meta.url));
const ASSET_DIR = path.resolve(here, '../../../docs/report/mock/assets');
const ME = { id: '310482915522101248', name: '하늘', avatar: null };
let m0;
/** 표시 이름: 목에서는 유저 목록 이름도 같이 바꾼다 (실제로는 게임 PC 앱이 받아서 바꿈) */
function setName(id, n) {
const u = db.users.find((x) => x.id === id);
if (u) u._orig ??= u.name;
if (n) state.names[id] = n;
else delete state.names[id];
if (u) u.name = n || u._orig;
broadcast({ type: 'users.updated', data: db.users });
}
const state = {
names: {},
regs: [
{ id: ME.id, name: ME.name, avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: Date.now() - 3600000, lastVersion: '1.5.0' },
],
device: { registered: true, online: process.env.MOCK_OFFLINE !== '1', name: '하늘의 게임 PC', lastSeen: Date.now(), version: '1.0.0' },
live: process.env.MOCK_LIVE !== '0',
liveInterval: Number(process.env.MOCK_LIVE_INTERVAL ?? 15000),
// 롤 경기 기록 가져오기 흉내 (v1.9.1 진행 바): 1.5초에 한 경기, MOCK_HISTORY=0 이면 끔
hist: process.env.MOCK_HISTORY === '0' ? null : { startedAt: Date.now(), total: Number(process.env.MOCK_HISTORY_TOTAL ?? 120) },
};
const histProgress = () => {
const h = state.hist;
if (!h) return null;
const el = Date.now() - h.startedAt;
if (el < 4000) return { phase: 'scan', first: true, scanned: Math.floor(el / 400) * 20, done: 0, total: Math.floor(el / 400) * 12, startedAt: h.startedAt, etaMs: null };
const done = Math.min(h.total, Math.floor((el - 4000) / 1500));
if (done >= h.total) return (state.hist = null);
return { phase: 'fetch', first: true, scanned: 200, done, total: h.total, startedAt: h.startedAt, etaMs: done ? (h.total - done) * 1500 : null };
};
const liveGames = () => [
{ game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, startedAt: Date.now() - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, historyAt: Date.now() - 12 * 60000, updatedAt: Date.now() },
{ game: 'lol', enabled: true, connected: !!state.hist, phase: state.hist ? '로비' : '롤 클라이언트 꺼짐', inMatch: false, matchId: null, mode: null, map: null, mapImage: null, startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: null, players: null, error: null, history: histProgress(), historyAt: null, updatedAt: Date.now() },
];
const json = (res, status, body, headers = {}) => {
const s = JSON.stringify(body, (k, v) => (k.startsWith('_') ? undefined : v));
@@ -99,7 +130,12 @@ function timeline(q) {
return { items: page, next: items.length > limit ? enc(page[page.length - 1]) : null };
}
const summary = (m) => ({ id: m.id, game: m.game, startedAt: m.startedAt, endedAt: m.endedAt, map: m.map, mode: m.mode, win: m.win, score: m.score, status: m.status, participants: m.participants });
const hasReplay = (m) => !!m.replayPath && fs.existsSync(m.replayPath);
const summary = (m) => ({
id: m.id, game: m.game, startedAt: m.startedAt, endedAt: m.endedAt, map: m.map, mode: m.mode, win: m.win, score: m.score, status: m.status, participants: m.participants,
source: m.source ?? 'live', voice: m.utterances.length > 0,
...(m.game === 'valorant' ? { replay: hasReplay(m) } : {}),
});
function userProfile(id) {
const user = db.users.find((u) => u.id === id);
@@ -117,6 +153,9 @@ function userProfile(id) {
// ── WS ───────────────────────────────────────────────
let wss;
// "잡음이라 삭제"로 배운 문장 (v1.4.0)
const noisePhrases = [{ id: 1, text: '시청해 주셔서 감사합니다 자막 제공', hits: 3, createdAt: Date.now() - 86400000 }];
let noiseSeq = 1;
const broadcast = (msg) => {
const s = JSON.stringify(msg, (k, v) => (k.startsWith('_') ? undefined : v));
wss?.clients.forEach((c) => c.readyState === 1 && c.send(s));
@@ -163,8 +202,44 @@ async function handle(req, res) {
return json(res, 200, { live: state.live });
}
if (p === '/mock/emit') return json(res, 200, emitLive() ?? { error: 'device_offline' });
if (p === '/mock/users-fail') {
state.usersFail = Number(q.get('n') ?? 1);
return json(res, 200, { usersFail: state.usersFail });
}
if (p === '/mock/latejoin') {
const n = db.users.length;
const u = q.get('again') === '1' ? db.users[n - 1] : { id: `41000000000000${String(n).padStart(4, '0')}`, name: `늦게온사람${n}`, color: '#d4537e', avatar: null, excluded: false, riot: [] };
if (q.get('again') !== '1') db.users.push(u);
const it = db.addLiveUtterance(u, '나 지금 들어왔어');
broadcast({ type: 'utterance.created', data: it });
return json(res, 200, { user: u, utterance: it.id });
}
// 맵 3D (GVR_MOCK_MAPS3D=<사이트 서버 data/maps3d 와 같은 구조의 폴더>: index.json + <dir>/<code>.glb.gz)
if (p === '/site/maps3d' || p.startsWith('/site/maps3d/')) {
const root = process.env.GVR_MOCK_MAPS3D;
if (!root) return p === '/site/maps3d' ? json(res, 200, { version: null, dir: null, maps: {} }) : json(res, 404, { error: 'not_found' });
if (p === '/site/maps3d') return json(res, 200, JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8')));
// 무기 스킨: <폴더>/skins/index.json (없으면 빈 목록), 요청은 받기만 한다 (뽑는 쪽이 없다)
if (p === '/site/maps3d/skins') {
const f = path.join(root, 'skins', 'index.json');
return json(res, 200, fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : { skins: {}, looks: {} });
}
if (p === '/site/maps3d/skins/want') return json(res, 200, { queued: 0 });
const [dir, file] = p.slice('/site/maps3d/'.length).split('/').map(decodeURIComponent);
const f = path.join(root, dir ?? '', (file ?? '') + '.gz');
const type = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' }[path.extname(file ?? '').toLowerCase()];
if (!/^[\w.-]+$/.test(dir ?? '') || !/^[\w.-]+$/.test(file ?? '') || !type || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' });
res.writeHead(200, { 'content-type': type, 'content-encoding': 'gzip', 'content-length': fs.statSync(f).size });
return fs.createReadStream(f).pipe(res);
}
// 게임 이미지 (목: docs/report/mock/assets)
// 3D 리플레이 데모 바닥 미니맵 (GVR_MOCK_REPLAY_MAP_FILE, 데이터 생성은 data.mjs genReplayDemo)
if (p === '/game-assets/mock/replay-map.png' && process.env.GVR_MOCK_REPLAY_MAP_FILE) {
res.writeHead(200, { 'content-type': 'image/png' });
return fs.createReadStream(process.env.GVR_MOCK_REPLAY_MAP_FILE).pipe(res);
}
if (p.startsWith('/game-assets/mock/')) {
const f = path.resolve(ASSET_DIR, decodeURIComponent(p.slice('/game-assets/mock/'.length)));
if (!f.startsWith(ASSET_DIR) || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' });
@@ -207,7 +282,35 @@ async function handle(req, res) {
if (p === '/auth/me') {
if (!sess) return json(res, 401, { error: 'unauthorized' });
if (sess === 'nm') return json(res, 403, { error: 'not_member' });
return json(res, 200, { user: ME, isOwner: true, canViewLogs: true });
return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, isOwner: true, canViewLogs: true, role: 'superadmin' });
}
// 내 정보 · 관리 화면 (v1.6.0)
if (p === '/site/profile') return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null, role: 'superadmin' });
if (p === '/site/profile/name' && req.method === 'PUT') {
const b = JSON.parse((await readBody(req)) || '{}');
const n = String(b.name ?? '').trim();
if (n && Object.entries(state.names).some(([id, x]) => id !== ME.id && x === n)) return json(res, 400, { error: 'bad_name', message: '다른 사람이 이미 쓰는 이름입니다' });
setName(ME.id, n);
return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null });
}
if (p === '/site/admin/overview') return json(res, 200, { device: { ...deviceStatus(), guildId: '1200000000000000000' }, latest: { version: '1.6.0', url: 'https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.6.0', publishedAt: null }, role: 'superadmin', serverVersion: '1.0.0' });
if (p === '/site/admin/users' && req.method === 'GET') return json(res, 200, { users: state.regs, names: state.names });
if (p === '/site/admin/names' && req.method === 'PUT') {
const b = JSON.parse((await readBody(req)) || '{}');
setName(String(b.id), String(b.name ?? '').trim());
return json(res, 200, { names: state.names });
}
if (p === '/site/admin/users' && req.method === 'POST') {
const b = JSON.parse((await readBody(req)) || '{}');
const u = db.users.find((x) => x.id === b.id);
state.regs.push({ id: b.id, name: u?.name ?? b.id, avatar: null, role: b.role, fixed: false, addedBy: ME.id, addedAt: Date.now(), lastSeenAt: null, lastVersion: null });
return json(res, 200, { users: state.regs });
}
if ((m0 = p.match(/^\/site\/admin\/users\/(\d+)$/))) {
const b = req.method === 'PATCH' ? JSON.parse((await readBody(req)) || '{}') : {};
if (req.method === 'PATCH') state.regs = state.regs.map((r) => (r.id === m0[1] ? { ...r, role: b.role } : r));
if (req.method === 'DELETE') state.regs = state.regs.filter((r) => r.id !== m0[1]);
return json(res, 200, { users: state.regs });
}
if (p.startsWith('/api/')) {
@@ -223,16 +326,29 @@ async function handle(req, res) {
recording: { active: true, channel: '발로 음성방', since: NOW - 150 * 60000, participants: db.SPEAKERS.map((u) => u.id) },
users: db.users,
games: { valorant: { connected: true, inMatch: false }, lol: { connected: false, inMatch: false } },
live: [
{ game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, startedAt: Date.now() - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, updatedAt: Date.now() },
{ game: 'lol', enabled: true, connected: false, phase: '롤 클라이언트 꺼짐', inMatch: false, matchId: null, mode: null, map: null, mapImage: null, startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: null, players: null, error: null, updatedAt: Date.now() },
],
live: liveGames(),
counts: { utterances: db.utterances.length, matches: db.matches.length },
version: '1.0.0',
});
}
if (p === '/api/users') return json(res, 200, db.users);
if (p === '/api/users') {
if (state.usersFail > 0) {
state.usersFail--;
return json(res, 500, { error: 'mock_fail' });
}
return json(res, 200, db.users);
}
let m;
if ((m = p.match(/^\/api\/users\/([^/]+)$/)) && req.method === 'PATCH') {
const u = db.users.find((x) => x.id === decodeURIComponent(m[1]));
if (!u) return json(res, 404, { error: 'not_found', message: '이 PC 기록에 없는 유저입니다' });
const b = JSON.parse((await readBody(req)) || '{}');
if (b.color) u.color = b.color;
if (b.excluded !== undefined) u.excluded = !!b.excluded;
if (b.riotIds) u.riot = b.riotIds.map((r) => ({ puuid: `riotid:${r}`, riotId: r }));
broadcast({ type: 'users.updated', data: db.users });
return json(res, 200, { user: u, taken: [] });
}
if ((m = p.match(/^\/api\/users\/([^/]+)$/))) {
const prof = userProfile(decodeURIComponent(m[1]));
return prof ? json(res, 200, prof) : json(res, 404, { error: 'not_found' });
@@ -242,12 +358,44 @@ async function handle(req, res) {
const game = q.get('game');
const before = q.get('before') ? Number(q.get('before')) : Infinity;
const limit = Number(q.get('limit') ?? 20);
const list = db.matches.filter((x) => (!game || x.game === game) && x.startedAt < before).sort((a, b) => b.startedAt - a.startedAt).slice(0, limit).map(summary);
const has = q.get('has');
const keep = (x) => (has === 'voice' ? x.utterances.length > 0 : has === 'timeline' ? x.source !== 'history' || x.utterances.length > 0 : true);
// 모드 · 날짜 필터, 데스매치는 늘 뺀다 (v1.11.0 앱과 같게)
const mode = q.get('mode');
const after = q.get('after') ? Number(q.get('after')) : 0;
// 리플레이 필터 (v1.12.0 앱과 같게): 발로란트 경기만
const replay = q.get('replay');
const keepReplay = (x) => (replay === 'yes' || replay === 'no' ? x.game === 'valorant' && hasReplay(x) === (replay === 'yes') : true);
const list = db.matches
.filter((x) => (!game || x.game === game) && x.startedAt < before && x.startedAt >= after && keep(x) && keepReplay(x) && x.mode !== '데스매치' && (!mode || x.mode === mode))
.sort((a, b) => b.startedAt - a.startedAt)
.slice(0, limit)
.map(summary);
return json(res, 200, list);
}
if (p === '/api/matches/modes') {
const game = q.get('game');
const by = new Map();
for (const x of db.matches) {
if (x.mode === '데스매치' || (game && x.game !== game)) continue;
const k = `${x.game}\n${x.mode}`;
by.set(k, { game: x.game, mode: x.mode, count: (by.get(k)?.count ?? 0) + 1 });
}
return json(res, 200, [...by.values()].sort((a, b) => b.count - a.count));
}
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
return mt ? json(res, 200, mt) : json(res, 404, { error: 'not_found' });
if (!mt) return json(res, 404, { error: 'not_found' });
const { replayPath, ...rest } = mt;
return json(res, 200, rest);
}
if ((m = p.match(/^\/api\/matches\/([^/]+)\/replay$/))) {
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
if (!mt) return json(res, 404, { error: 'not_found' });
// 파일을 지웠다가 다시 두면 "리플레이 없음 → 내려받고 새로고침" 을 흉내 낼 수 있다
if (!mt.replayPath || !fs.existsSync(mt.replayPath)) return json(res, 404, { error: 'replay_not_found' });
res.writeHead(200, { 'content-type': 'application/json' });
return fs.createReadStream(mt.replayPath).pipe(res);
}
if ((m = p.match(/^\/api\/utterances\/([^/]+)$/)) && req.method === 'PATCH') {
const it = db.utterances.find((u) => u.id === decodeURIComponent(m[1]));
@@ -264,6 +412,35 @@ async function handle(req, res) {
broadcast({ type: 'utterance.updated', data: it });
return json(res, 200, it);
}
if ((m = p.match(/^\/api\/utterances\/([^/]+)\/delete$/)) && req.method === 'POST') {
const i = db.utterances.findIndex((u) => u.id === decodeURIComponent(m[1]));
if (i < 0) return json(res, 404, { error: 'not_found' });
const body = JSON.parse((await readBody(req)) || '{}');
const [it] = db.utterances.splice(i, 1);
let learned = null;
if (body.noise && it.text) {
learned = it.text;
noisePhrases.unshift({ id: ++noiseSeq, text: it.text, hits: 0, createdAt: Date.now() });
}
broadcast({ type: 'utterance.deleted', data: { id: it.id, noise: !!body.noise } });
return json(res, 200, { ok: true, learned });
}
if (p === '/api/dictionary')
return json(res, 200, {
labels: { valorant: '발로란트', lol: '롤' },
entries: [
{ id: 1, word: '로테', from: null, kind: 'hotword', pack: 'site', source: 'site', enabled: true, hits: 12 },
{ id: 2, word: '레이즈', from: '레이저', kind: 'correction', pack: 'site', source: 'site', enabled: true, hits: 0 },
],
packs: [{ key: 'valorant', label: '발로란트', count: 420 }],
});
if (p === '/api/noise-phrases') return json(res, 200, { phrases: noisePhrases });
if ((m = p.match(/^\/api\/noise-phrases\/(\d+)$/)) && req.method === 'DELETE') {
const i = noisePhrases.findIndex((x) => x.id === Number(m[1]));
if (i < 0) return json(res, 404, { error: 'not_found' });
noisePhrases.splice(i, 1);
return json(res, 200, { ok: true });
}
if (p === '/api/bundles') {
const out = [];
for (const mt of db.matches) {
@@ -285,6 +462,12 @@ async function handle(req, res) {
}
return json(res, 200, { bundles: out.sort((a, b) => b.from - a.from) });
}
if (p === '/api/games/history/cancel' && req.method === 'POST') {
const was = !!histProgress();
state.hist = null;
broadcast({ type: 'games.state', data: liveGames() });
return json(res, 200, { ok: true, cancelled: was ? ['lol'] : [], resumeAt: was ? Date.now() + 30 * 60000 : null });
}
if (p === '/api/bundles/delete' && req.method === 'POST') return json(res, 200, { bundles: 1, utterances: 12, files: 12 });
if (p === '/api/bundles/export' && req.method === 'POST') {
req.resume();
@@ -354,10 +537,17 @@ export function startMock({ port = Number(process.env.MOCK_PORT ?? 18787) } = {}
if (state.live && wss.clients.size) emitLive();
}, state.liveInterval);
const hb = setInterval(() => deviceOk() && pushStatus(), 20000);
// 경기 기록 가져오기 진행 (앱은 2초마다 바뀌면 보낸다)
const histTimer = setInterval(() => {
if (!wss.clients.size) return;
const had = !!state.hist;
if (had) broadcast({ type: 'games.state', data: liveGames() });
}, 2000);
server.listen(port, '127.0.0.1', () => console.log(`[mock] http://127.0.0.1:${port} (데이터: 발화 ${db.utterances.length} · 이벤트 ${db.events.length} · 경기 ${db.matches.length} · 기준 ${fmtClock(0)})`));
server.on('close', () => {
clearInterval(timer);
clearInterval(hb);
clearInterval(histTimer);
});
return server;
}

View File

@@ -12,12 +12,14 @@
"react": "^19.3.0",
"react-dom": "^19.3.0",
"react-router": "^7.18.4",
"three": "^0.180.0",
"wavesurfer.js": "^7.12.12"
},
"devDependencies": {
"@types/node": "^22.20.5",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.2.0",
"@types/three": "^0.180.0",
"@vitejs/plugin-react": "^5.2.0",
"typescript": "~5.9.3",
"vite": "^7.3.7",
@@ -287,6 +289,12 @@
"node": ">=6.9.0"
}
},
"node_modules/@dimforge/rapier3d-compat": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
"integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
"dev": true
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
@@ -1095,6 +1103,12 @@
"win32"
]
},
"node_modules/@tweenjs/tween.js": {
"version": "23.1.3",
"resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
"dev": true
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -1169,6 +1183,33 @@
"@types/react": "^19.3.0"
}
},
"node_modules/@types/stats.js": {
"version": "0.17.4",
"resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
"dev": true
},
"node_modules/@types/three": {
"version": "0.180.0",
"resolved": "https://registry.npmjs.org/@types/three/-/three-0.180.0.tgz",
"integrity": "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg==",
"dev": true,
"dependencies": {
"@dimforge/rapier3d-compat": "~0.12.0",
"@tweenjs/tween.js": "~23.1.3",
"@types/stats.js": "*",
"@types/webxr": "*",
"@webgpu/types": "*",
"fflate": "~0.8.2",
"meshoptimizer": "~0.22.0"
}
},
"node_modules/@types/webxr": {
"version": "0.5.24",
"resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
"integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
"dev": true
},
"node_modules/@vitejs/plugin-react": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz",
@@ -1189,6 +1230,12 @@
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/@webgpu/types": {
"version": "0.1.74",
"resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.74.tgz",
"integrity": "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==",
"dev": true
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.28",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.28.tgz",
@@ -1368,6 +1415,12 @@
}
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"dev": true
},
"node_modules/framer-motion": {
"version": "12.43.0",
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.43.0.tgz",
@@ -1456,6 +1509,12 @@
"yallist": "^3.0.2"
}
},
"node_modules/meshoptimizer": {
"version": "0.22.0",
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.22.0.tgz",
"integrity": "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==",
"dev": true
},
"node_modules/motion-dom": {
"version": "12.43.0",
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.43.0.tgz",
@@ -1670,6 +1729,11 @@
"node": ">=0.10.0"
}
},
"node_modules/three": {
"version": "0.180.0",
"resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz",
"integrity": "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",

View File

@@ -16,12 +16,14 @@
"react": "^19.3.0",
"react-dom": "^19.3.0",
"react-router": "^7.18.4",
"three": "^0.180.0",
"wavesurfer.js": "^7.12.12"
},
"devDependencies": {
"@types/node": "^22.20.5",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.2.0",
"@types/three": "^0.180.0",
"@vitejs/plugin-react": "^5.2.0",
"typescript": "~5.9.3",
"vite": "^7.3.7",

View File

@@ -18,6 +18,7 @@ import { CulpritPage } from './pages/CulpritPage';
import { MatchesPage, UserPage, UsersPage } from './pages/UserPages';
import { LogsPage } from './pages/LogsPage';
import { RecordsPage } from './pages/RecordsPage';
import { AdminPage } from './pages/AdminPage';
import { installErrorReporting } from './lib/report';
import { useLocation } from 'react-router';
@@ -75,6 +76,7 @@ function Shell() {
<Route path="/dictionary" element={<DictionaryPage />} />
<Route path="/culprit" element={<CulpritPage />} />
<Route path="/culprit/:id" element={<CulpritPage />} />
<Route path="/admin" element={<AdminPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</div>

View File

@@ -0,0 +1,166 @@
import { useEffect, useRef, useState } from 'react';
import { settings, useSettings } from '../store/settings';
import { CROSS_COLORS, DEFAULT_CROSSHAIR, drawCrosshair, parseCrosshairCode, prepCanvas, type CrossLines, type CrossSet, type CrosshairAt, type CrosshairProfile } from '../lib/crosshair';
/** 조준점 미리보기 (어두운 바탕) */
function Preview({ set }: { set: CrossSet }) {
const ref = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const g = ref.current && prepCanvas(ref.current);
if (g) drawCrosshair(g.ctx, g.cx, g.cy, set);
}, [set]);
return <canvas ref={ref} className="r3d-xprev" aria-label="조준점 미리보기" />;
}
function Range({ label, value, min, max, step, onChange }: { label: string; value: number; min: number; max: number; step: number; onChange: (v: number) => void }) {
return (
<label className="r3d-xrow">
<span>{label}</span>
<input type="range" min={min} max={max} step={step} value={value} onChange={(e) => onChange(Number(e.target.value))} />
<span className="mono">{step < 1 ? value.toFixed(2) : value}</span>
</label>
);
}
function Check({ label, value, onChange }: { label: string; value: boolean; onChange: (v: boolean) => void }) {
return (
<label className="r3d-xcheck">
<input type="checkbox" checked={value} onChange={(e) => onChange(e.target.checked)} /> {label}
</label>
);
}
function LinesEdit({ title, l, maxOffset, onChange }: { title: string; l: CrossLines; maxOffset: number; onChange: (l: CrossLines) => void }) {
const up = (p: Partial<CrossLines>) => onChange({ ...l, ...p, ...(p.length != null ? { vLength: p.length } : {}) });
return (
<fieldset className="r3d-xset">
<legend>
<Check label={title} value={l.on} onChange={(on) => up({ on })} />
</legend>
{l.on && (
<>
<Range label="불투명도" value={l.opacity} min={0} max={1} step={0.05} onChange={(opacity) => up({ opacity })} />
<Range label="길이" value={l.length} min={0} max={20} step={1} onChange={(length) => up({ length })} />
<Range label="두께" value={l.thickness} min={0} max={10} step={1} onChange={(thickness) => up({ thickness })} />
<Range label="간격" value={l.offset} min={0} max={maxOffset} step={1} onChange={(offset) => up({ offset })} />
<Check label="이동 오차" value={l.moveError} onChange={(moveError) => up({ moveError })} />
<Check label="사격 오차" value={l.fireError} onChange={(fireError) => up({ fireError })} />
</>
)}
</fieldset>
);
}
/**
* 1인칭 조준점 설정: 선수 조준점을 쓸지, 사이트 전체에 쓰는 내 조준점 (직접 고치기 · 발로란트 조준점 코드 가져오기).
* 설정은 이 브라우저에 저장한다
*/
export default function CrosshairPanel({ playerName, player, hasAny, onClose }: { playerName: string | null; player: CrosshairAt | null; hasAny: boolean; onClose: () => void }) {
const cfg = useSettings().crosshair;
const mine = cfg.mine;
const [code, setCode] = useState(cfg.code ?? '');
const [err, setErr] = useState<string | null>(null);
const save = (p: Partial<typeof cfg>) => settings.set({ crosshair: { ...cfg, ...p } });
const setMine = (m: CrosshairProfile, c?: string) => save({ mine: m, code: c });
// 직접 고치면 정조준 조준점도 같이 (발로란트 '정조준에도 주 조준점')
const upSet = (p: Partial<CrossSet>) => {
const primary = { ...mine.primary, ...p };
setMine({ ...mine, primary, ads: primary, adsFromPrimary: true });
};
const presetIdx = CROSS_COLORS.findIndex((c) => c.hex === mine.primary.color.toLowerCase());
const importCode = () => {
const p = parseCrosshairCode(code);
if (!p) {
setErr('조준점 코드 형식이 아닙니다 (예: 0;P;c;5;h;0;0l;4;0o;2;0a;1;0f;0;1b;0)');
return;
}
setErr(null);
setMine(p, code.trim());
};
const s = mine.primary;
return (
<div className="r3d-xpanel" role="dialog" aria-label="조준점 설정">
<div className="r3d-xhead">
<b>조준점</b>
<button className="chip" onClick={onClose} aria-label="닫기">
✕
</button>
</div>
<label className="r3d-xcheck">
<input type="radio" name="xmode" checked={cfg.usePlayer} onChange={() => save({ usePlayer: true })} /> 선수 조준점 (리플레이에 없으면 내 조준점)
</label>
<label className="r3d-xcheck">
<input type="radio" name="xmode" checked={!cfg.usePlayer} onChange={() => save({ usePlayer: false })} /> 모든 선수에 내 조준점
</label>
{player ? (
<div className="r3d-xplayer">
<Preview set={player.primary} />
<div>
<div className="small">
{playerName ?? '이 선수'} 조준점{player.name ? <span className="muted"> · {player.name}</span> : null}
</div>
<button className="chip" onClick={() => setMine({ primary: player.primary, ads: player.ads, sniper: player.sniper, adsFromPrimary: player.adsFromPrimary, advanced: player.advanced })}>
내 조준점으로 복사
</button>
</div>
</div>
) : (
<div className="muted small">
{hasAny ? '이 선수는 조준점 기록이 없어 내 조준점을 씁니다.' : '이 리플레이에는 선수 조준점 기록이 없어 내 조준점을 씁니다. 게임 PC 앱을 1.8.2 이상으로 올리면 리플레이를 열 때 다시 변환해 기록이 생깁니다.'}
</div>
)}
<div className="r3d-xmine">
<div className="r3d-xhead">
<b className="small">내 조준점</b>
<button className="chip" onClick={() => setMine(DEFAULT_CROSSHAIR)} title="발로란트 기본 조준점으로">
기본값
</button>
</div>
<Preview set={s} />
<div className="r3d-xcode">
<input value={code} onChange={(e) => setCode(e.target.value)} placeholder="발로란트 조준점 코드 붙여넣기" aria-label="조준점 코드" onKeyDown={(e) => e.key === 'Enter' && importCode()} />
<button className="chip" onClick={importCode}>
가져오기
</button>
</div>
{err && <div className="small r3d-xerr">{err}</div>}
<label className="r3d-xrow">
<span>색</span>
<select value={presetIdx >= 0 ? presetIdx : -1} onChange={(e) => Number(e.target.value) >= 0 && upSet({ color: CROSS_COLORS[Number(e.target.value)].hex })}>
{CROSS_COLORS.map((c, i) => (
<option key={c.hex} value={i}>
{c.name}
</option>
))}
<option value={-1}>사용자 지정</option>
</select>
<input type="color" value={s.color} onChange={(e) => upSet({ color: e.target.value })} aria-label="사용자 지정 색" />
</label>
<fieldset className="r3d-xset">
<legend>
<Check label="외곽선" value={s.outline} onChange={(outline) => upSet({ outline })} />
</legend>
{s.outline && (
<>
<Range label="불투명도" value={s.outlineOpacity} min={0} max={1} step={0.05} onChange={(outlineOpacity) => upSet({ outlineOpacity })} />
<Range label="두께" value={s.outlineThickness} min={1} max={6} step={1} onChange={(outlineThickness) => upSet({ outlineThickness })} />
</>
)}
</fieldset>
<fieldset className="r3d-xset">
<legend>
<Check label="가운데 점" value={s.dot} onChange={(dot) => upSet({ dot })} />
</legend>
{s.dot && (
<>
<Range label="불투명도" value={s.dotOpacity} min={0} max={1} step={0.05} onChange={(dotOpacity) => upSet({ dotOpacity })} />
<Range label="두께" value={s.dotSize} min={1} max={6} step={1} onChange={(dotSize) => upSet({ dotSize })} />
</>
)}
</fieldset>
<LinesEdit title="안쪽 선" l={s.inner} maxOffset={20} onChange={(inner) => upSet({ inner })} />
<LinesEdit title="바깥쪽 선" l={s.outer} maxOffset={40} onChange={(outer) => upSet({ outer })} />
</div>
</div>
);
}

View File

@@ -6,7 +6,8 @@ import { settings, useSettings, type SfxKind } from '../store/settings';
import { sfx, SFX_LABEL } from '../lib/sfx';
import { resumeAudio } from '../lib/audio';
import { Avatar, Brand } from './common';
import { IGear, ILogout, ISearch } from './Icons';
import { IGear, ISearch } from './Icons';
import { ProfilePopover } from './UserEdit';
import { GAME_NAME, liveGameLine, liveGameRows } from '@gvr/shared';
function SettingsPopover({ onClose }: { onClose: () => void }) {
@@ -165,10 +166,11 @@ export function SearchBox() {
}
export function Header() {
const { auth, logout } = useAuth();
const { overview } = useData();
const { auth } = useAuth();
const { overview, userById } = useData();
const { device, locked, conn } = useStatus();
const [open, setOpen] = useState(false);
const [profile, setProfile] = useState(false);
const me = auth.status === 'ok' ? auth.me.user : null;
const rec = overview?.recording;
const nav = [
@@ -178,6 +180,7 @@ export function Header() {
['/users', '유저'],
['/dictionary', '단어사전'],
['/culprit', '🔍 범인찾기'],
...(auth.status === 'ok' && auth.me.canViewLogs ? ([['/admin', '🛡️ 관리']] as const) : []),
] as const;
return (
<header className="topbar">
@@ -211,14 +214,13 @@ export function Header() {
</button>
<AnimatePresence>{open && <SettingsPopover onClose={() => setOpen(false)} />}</AnimatePresence>
{me && (
<div className="me">
<Avatar name={me.name} src={me.avatar} color="#5865f2" size={26} />
<button className="me me-btn" onClick={() => setProfile((o) => !o)} aria-expanded={profile} title="내 정보 · 표시 이름 · 색 · 로그아웃">
<Avatar name={me.name} src={me.avatar} color={userById(me.id)?.color ?? '#5865f2'} size={26} />
<span className="me-nm">{me.name}</span>
<button className="icon-btn" onClick={logout} title="로그아웃" aria-label="로그아웃">
<ILogout width={16} height={16} />
</button>
</div>
<span className="me-caret">▾</span>
</button>
)}
<AnimatePresence>{profile && <ProfilePopover onClose={() => setProfile(false)} />}</AnimatePresence>
</div>
</header>
);

View File

@@ -0,0 +1,100 @@
import { useEffect, useRef, useState } from 'react';
import { GAME_NAME, historyStatus, resumeText, type GameType } from '@gvr/shared';
import { api } from '../lib/api';
import { fmtWhen } from '../lib/format';
import { useData } from '../store/app';
/**
* Riot 경기 기록 가져오기 진행 바 (v1.9.1, 경기 탭 위). 게임 PC 앱이 게임 중이 아닐 때 30분마다 지난 경기를 받아 온다.
* 받을 경기 수 · 남은 시간을 보여 주고 취소할 수 있다. 끝나면 onDone 으로 경기 목록을 다시 받게 한다.
*/
export function HistoryImport({ onDone }: { onDone: () => void }) {
const { overview } = useData();
const rows = (overview?.live ?? []).filter((g) => g.history);
const [busy, setBusy] = useState<GameType | null>(null);
const [msg, setMsg] = useState<{ text: string; bad?: boolean } | null>(null);
// 가져오기가 끝나거나 멈추면 경기 목록을 새로
const active = rows.map((g) => g.game).join(',');
const prev = useRef(active);
useEffect(() => {
const now = active.split(',');
if (prev.current.split(',').some((g) => g && !now.includes(g))) onDone();
prev.current = active;
}, [active, onDone]);
const cancel = (game: GameType) => {
setBusy(game);
setMsg(null);
api
.cancelHistory(game)
.then((r) => {
if (r.cancelled.length) setMsg({ text: `${GAME_NAME[game]} 경기 기록 가져오기를 멈췄습니다. 받은 경기는 그대로 있고, ${resumeText(r.resumeAt)} 남은 것부터 이어서 가져옵니다.` });
})
.catch((e) => setMsg({ text: `취소하지 못했습니다: ${e instanceof Error ? e.message : String(e)}`, bad: true }))
.finally(() => setBusy(null));
};
if (!rows.length && !msg) return null;
return (
<div className="hist-import">
{rows.map((g) => {
const st = historyStatus(g.history!);
return (
<div key={g.game} className={`hist-card ${g.game}`} role="status">
<div className="hist-top">
<span className="hist-dot" />
<b>{GAME_NAME[g.game]}</b>
<span>{st.title}</span>
<span className="dim small">{st.detail}</span>
<span className="hist-gap" />
<button className="btn small" disabled={busy === g.game} onClick={() => cancel(g.game)}>
{busy === g.game ? '멈추는 중…' : '취소'}
</button>
</div>
<span className={`bar hist-bar${st.pct == null ? ' indet' : ''}`}>
<i style={st.pct == null ? undefined : { width: `${st.pct}%` }} />
</span>
<div className="dim small">
{g.history!.first ? '처음 한 번은 지난 경기를 끝까지 가져와서 오래 걸립니다. ' : ''}
게임을 켜면 바로 멈추고, 끝나면 이 목록에 자동으로 나타납니다.
</div>
</div>
);
})}
{msg && (
<div className={`hist-msg${msg.bad ? ' bad' : ''}`}>
{msg.text}
<button className="btn small" onClick={() => setMsg(null)}>
닫기
</button>
</div>
)}
</div>
);
}
/**
* Riot 경기 기록을 언제 확인했는지 (v1.11.0 앱부터, 경기 탭). 앱이 꺼져 있던 때 한 경기는 이 PC 에서 Riot 클라이언트에
* 로그인해 있어야 가져올 수 있어서, 아직 못 가져왔으면 그 방법을 알려 준다. 가져오는 중이면 위 진행 바가 대신 보인다.
*/
export function HistoryHint() {
const { overview } = useData();
const rows = (overview?.live ?? []).filter((g) => g.enabled && !g.history && g.historyAt !== undefined);
if (!rows.length) return null;
return (
<div className="hist-hint dim small">
{rows.map((g) => {
const client = g.game === 'valorant' ? 'Riot 클라이언트' : '롤 클라이언트';
const text =
g.historyAt != null
? `Riot 경기 기록 ${fmtWhen(g.historyAt)} 확인${g.connected ? ' · 30분마다 새 경기를 가져옵니다' : ` · ${client}를 켜면 그사이 한 경기를 가져옵니다`}`
: g.connected
? '앱이 꺼져 있던 때 한 경기를 곧 가져옵니다'
: `앱이 꺼져 있던 때 한 경기는 아직 못 가져왔습니다. 이 PC 에서 ${client}에 로그인해 두면 자동으로 가져옵니다`;
return (
<div key={g.game}>
<b>{GAME_NAME[g.game]}</b> {text}
</div>
);
})}
</div>
);
}

View File

@@ -1,3 +1,4 @@
import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { IDiscord } from './Icons';
@@ -31,6 +32,15 @@ function FakeBackdrop() {
}
export function LoginPage({ notMember = false, error }: { notMember?: boolean; error?: string }) {
// 들어올 수 있는 서버 = 게임 PC 앱에서 녹음할 서버로 고른 곳 (겜녹이 봇이 있는 서버)
const [guild, setGuild] = useState<string | null>(null);
useEffect(() => {
fetch('/auth/guild')
.then((r) => (r.ok ? r.json() : null))
.then((d: { name?: string | null } | null) => setGuild(d?.name ?? null))
.catch(() => undefined);
}, []);
const g = guild ? `(${guild})` : '';
return (
<div className="login">
<FakeBackdrop />
@@ -43,9 +53,9 @@ export function LoginPage({ notMember = false, error }: { notMember?: boolean; e
<div className="in">
{notMember ? (
<>
<div className="t h">들어올 수 없는 계정입니다</div>
<div className="nm-warn">M&amp;L 서버 멤버만 들어올 수 있습니다</div>
<div className="d">겜녹이 봇이 있는 디스코드 서버(M&amp;L)에 참여한 계정으로 다시 로그인해 주세요.</div>
<div className="t h">로그인할 수 없습니다</div>
<div className="nm-warn">봇과 다른 서버에 있는 계정입니다</div>
<div className="d">겜녹이 봇이 있는 디스코드 서버{g}에 참여한 계정만 들어올 수 있습니다. 그 서버에 참여한 계정으로 다시 로그인해 주세요.</div>
<a className="dc" href="/auth/discord">
<IDiscord />
다른 계정으로 로그인
@@ -56,7 +66,7 @@ export function LoginPage({ notMember = false, error }: { notMember?: boolean; e
<div className="t h">디스코드 계정으로 로그인</div>
{error && <div className="nm-warn">{error}</div>}
<div className="d">
겜녹이 봇이 있는 디스코드 서버(M&amp;L)의 멤버만 들어올 수 있어요.
겜녹이 봇이 있는 디스코드 서버{g}의 멤버만 들어올 수 있어요.
<br />
로그인하면 녹음된 대화와 경기 기록을 볼 수 있습니다.
</div>

View File

@@ -0,0 +1,111 @@
import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
import type { MatchDetail } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { computeSync, type ReplayFile } from '../lib/replay';
import { reportClient } from '../lib/report';
import { Panel, Spinner } from './common';
// three.js 는 크므로 3D 리플레이를 열 때만 받는다
const ReplayViewer = lazy(() => import('./ReplayViewer'));
/** 경기 화면의 "3D 리플레이" 칸. 열면 게임 PC 에서 리플레이 데이터를 받아 온다 */
export function ReplayPanel({ m }: { m: MatchDetail }) {
const [open, setOpen] = useState(false);
const [replay, setReplay] = useState<ReplayFile | null>(null);
const [err, setErr] = useState<unknown>(null);
const [converting, setConverting] = useState(false);
// 새로고침을 누를 때마다 1씩 올려 리플레이를 다시 묻는다
const [reload, setReload] = useState(0);
useEffect(() => {
if (!open || replay) return;
let alive = true;
let timer: ReturnType<typeof setTimeout> | undefined;
setErr(null);
// 처음 열면 게임 PC 가 리플레이를 변환한다 (보통 10초 안팎). 변환 중(202)이면 3초 뒤 다시 묻는다 (5분까지)
const ask = (tries: number) =>
api
.replay(m.id, reload > 0)
.then((r) => {
if (!alive) return;
if ('status' in r && r.status === 'converting') {
setConverting(true);
if (tries >= 100) setErr(new Error('게임 PC 가 리플레이 변환을 끝내지 못했습니다'));
else timer = setTimeout(() => ask(tries + 1), 3000);
return;
}
setConverting(false);
setReplay(r as ReplayFile);
})
.catch((e) => {
if (!alive) return;
setConverting(false);
setErr(e);
// 변환 실패 이유는 게임 PC 에만 남으므로 사이트 로그에도 남긴다
if (e instanceof ApiError && e.status === 422) reportClient('warn', `리플레이 변환 실패 ${m.id}: ${e.detail ?? e.code}`);
});
void ask(0);
return () => {
alive = false;
if (timer) clearTimeout(timer);
};
}, [open, m.id, replay, reload]);
const sync = useMemo(() => (replay ? computeSync(m, replay) : null), [m, replay]);
// replay_not_found: 앱이 리플레이를 못 찾음. 다른 404: 이 앱 버전에는 리플레이 기능이 아직 없음
const missing = err instanceof ApiError && err.status === 404 && err.code === 'replay_not_found';
const appTooOld = err instanceof ApiError && err.status === 404 && err.code === 'Not Found'; // Fastify 기본 404 (경로 없음)
const failed = err instanceof ApiError && err.status === 422 && err.code === 'replay_failed';
const refresh = (
<button className="mini-btn" onClick={() => setReload((n) => n + 1)}>
새로고침
</button>
);
return (
<Panel
className={`replay-panel${open ? ' open' : ''}`}
title="3D 리플레이 · 대화 동기화"
right={
<button className="mini-btn" onClick={() => setOpen((o) => !o)} aria-expanded={open}>
{open ? '닫기' : '열기'}
</button>
}
>
{!open ? (
<div className="dim small">
발로란트에서 이 경기 리플레이를 내려받으면 선수 10명의 움직임을 3D로 보면서 그때 나눈 대화를 같이 들을 수 있습니다.
</div>
) : missing ? (
<div className="replay-msg">
<div>
<b>리플레이 파일 없음</b>
<div className="dim small">
게임 PC 에 이 경기의 리플레이 파일이 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받은 뒤 새로고침을 누르면 게임 PC 앱이 찾아서
변환합니다 (몇 초 걸림).
</div>
</div>
{refresh}
</div>
) : appTooOld ? (
<div className="replay-msg">
<div className="dim small">지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.</div>
{refresh}
</div>
) : failed ? (
<div className="replay-msg">
<div className="dim small">게임 PC 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다. ({(err as ApiError).detail ?? '이유 모름'})</div>
{refresh}
</div>
) : err ? (
<div className="replay-msg">
<div className="dim small">리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}</div>
{refresh}
</div>
) : !replay || !sync ? (
<Spinner label={converting ? '게임 PC 가 리플레이를 변환하는 중 (처음 한 번, 10초 안팎)' : '리플레이 불러오는 중'} />
) : (
<Suspense fallback={<Spinner label="3D 화면 준비 중" />}>
<ReplayViewer m={m} replay={replay} sync={sync} />
</Suspense>
)}
</Panel>
);
}

View File

@@ -0,0 +1,78 @@
import type { MatchDetail, MatchPlayer } from '@gvr/shared';
import { equipLabel, type ReplayFile } from '../lib/replay';
import { boardAt, teamScoreAt, type BoardIndex, type BoardRow } from '../lib/scoreboard';
interface RosterItem {
idx: number;
info: MatchPlayer | null;
name: string;
ally: boolean;
}
/** 리플레이 점수판: 게임에서 Tab 을 누른 것처럼 그 시각의 팀 점수 · 궁극기 · K/D/A · 무기 · 크레딧 */
export default function ReplayScoreboard({ m, replay, ix, roster, t }: { m: MatchDetail; replay: ReplayFile; ix: BoardIndex; roster: RosterItem[]; t: number }) {
const rows = roster.map((r) => ({ r, b: boardAt(replay, ix, r.idx, t) }));
// 게임처럼 전투 점수 순 (없으면 킬 순)
const order = (a: { b: BoardRow }, c: { b: BoardRow }) => (c.b.score ?? -1) - (a.b.score ?? -1) || c.b.kills - a.b.kills || a.b.deaths - c.b.deaths;
const ally = rows.filter((x) => x.r.ally).sort(order);
const enemy = rows.filter((x) => !x.r.ally).sort(order);
const sc = teamScoreAt(replay, m.rounds, t);
const team = (list: typeof rows, side: 'a' | 'e') => (
<tbody className={`r3d-sb-team ${side}`}>
{list.map(({ r, b }) => (
<tr key={r.idx} className={b.dead ? 'dead' : undefined}>
<td className="ag">
{r.info?.character?.icon ? <img src={r.info.character.icon} alt="" /> : <span className="ag-ph" />}
</td>
<td className="nm">
<b>{r.name}</b>
{r.info?.character?.name && <span className="muted"> {r.info.character.name}</span>}
</td>
<td className="ult" title={b.ult == null ? '궁극기 점수 모름' : `궁극기 ${b.ult} / ${b.ultMax}`}>
{b.ult == null ? (
<span className="muted">-</span>
) : b.ult >= b.ultMax ? (
<span className="ult-ready">궁 준비</span>
) : (
<span className="ult-dots" aria-label={`궁극기 ${b.ult} / ${b.ultMax}`}>
{Array.from({ length: b.ultMax }, (_, i) => (
<i key={i} className={i < b.ult! ? 'on' : undefined} />
))}
</span>
)}
</td>
<td className="num">{b.kills}</td>
<td className="num">{b.deaths}</td>
<td className="num">{b.assists ?? '-'}</td>
<td className="wp">{equipLabel(b.weapon ?? undefined) ?? '-'}</td>
<td className="num money">{b.money == null ? '-' : `${b.money.toLocaleString('ko-KR')}`}</td>
</tr>
))}
</tbody>
);
return (
<div className="r3d-sb" role="dialog" aria-label="점수판">
<div className="r3d-sb-head">
<span className="a">아군 {sc.ally}</span>
<span className="muted">R{sc.round}</span>
<span className="e">{sc.enemy} 상대</span>
</div>
<table>
<thead>
<tr>
<th colSpan={2}>선수</th>
<th>궁극기</th>
<th className="num">K</th>
<th className="num">D</th>
<th className="num">A</th>
<th>무기</th>
<th className="num">크레딧</th>
</tr>
</thead>
{team(ally, 'a')}
{team(enemy, 'e')}
</table>
{!ix.has && <div className="muted small r3d-sb-note">이 리플레이는 예전 변환 결과라 크레딧 · 궁극기 · 어시스트가 없습니다. 게임 PC 앱을 1.10.0 이상으로 올리면 다음에 열 때 다시 변환합니다.</div>}
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,234 @@
// 유저 설정 고치기 (v1.6.0): 머리글 "내 정보" 와 관리 화면이 같이 쓴다
// - 표시 이름: 사이트 서버에 저장 (디스코드 이름 대신 보일 이름, 게임 PC 앱에 바로 전달)
// - 색 · 녹음 제외 · 라이엇 ID: 게임 PC 앱 기록에 저장 (앱 v1.6.0~)
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router';
import { motion } from 'framer-motion';
import type { User } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { sfx } from '../lib/sfx';
import { useAuth, useData } from '../store/app';
import { Avatar } from './common';
import { ILogout } from './Icons';
/** 타임라인에서 잘 보이는 색들 (어두운 배경) */
export const USER_COLORS = ['#ff4655', '#ff8a3d', '#f2b23a', '#c8e04a', '#45d39a', '#14c1b7', '#3db8ff', '#5b8cff', '#9a7bff', '#d46bff', '#ff6fb1', '#c9d1dc'];
/** 오류를 사람이 읽을 말로 */
export function errText(e: unknown): string {
if (e instanceof ApiError) {
if (e.status === 404 && e.code === 'Not Found') return '게임 PC 앱이 아직 이 기능을 모릅니다. 앱을 v1.6.0 이상으로 업데이트해 주세요';
if (e.status === 503 && e.code === 'device_offline') return '게임 PC 가 꺼져 있어 저장하지 못했습니다';
if (e.status === 504) return '게임 PC 가 답하지 않습니다. 잠시 뒤 다시 해 주세요';
if (e.detail) return e.detail;
if (e.status === 0) return '서버에 연결하지 못했습니다';
return `저장하지 못했습니다 (${e.status} ${e.code})`;
}
return e instanceof Error ? e.message : String(e);
}
/** 표시 이름 입력: 저장 · 디스코드 이름으로 되돌리기 */
export function NameEditor({ value, custom, onSave, placeholder }: { value: string; custom: boolean; onSave: (name: string) => Promise<void>; placeholder?: string }) {
const [v, setV] = useState(value);
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
useEffect(() => setV(value), [value]);
const save = async (name: string) => {
setBusy(true);
setMsg(null);
try {
await onSave(name);
setMsg({ ok: true, text: name ? '저장했습니다' : '디스코드 이름으로 되돌렸습니다' });
sfx('click');
} catch (e) {
setMsg({ ok: false, text: errText(e) });
} finally {
setBusy(false);
}
};
return (
<div className="ue-block">
<form
className="ue-row"
onSubmit={(e) => {
e.preventDefault();
if (v.trim() && v.trim() !== value) void save(v.trim());
}}
>
<input className="ue-input" value={v} maxLength={32} placeholder={placeholder ?? '표시 이름'} onChange={(e) => setV(e.target.value)} aria-label="표시 이름" />
<button className="btn sm primary" disabled={busy || !v.trim() || v.trim() === value}>
저장
</button>
{custom && (
<button type="button" className="btn sm" disabled={busy} onClick={() => void save('')} title="표시 이름을 지우고 디스코드 서버 별명으로 보이게">
되돌리기
</button>
)}
</form>
{msg && <div className={`ue-msg${msg.ok ? ' ok' : ' bad'}`}>{msg.text}</div>}
</div>
);
}
/** 색 · 녹음 제외 · 라이엇 ID (게임 PC 앱에 저장) */
export function AppUserEditor({ user, self }: { user: User; self: boolean }) {
const { reloadUsers } = useData();
const [riot, setRiot] = useState(user.riot.map((r) => r.riotId).join(', '));
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const riotNow = user.riot.map((r) => r.riotId).join(', ');
useEffect(() => setRiot(riotNow), [riotNow]);
const colorRef = useRef<HTMLInputElement>(null);
const patch = async (p: { color?: string; excluded?: boolean; riotIds?: string[] }, okText: string) => {
setBusy(true);
setMsg(null);
try {
const r = await api.updateUser(user.id, p);
reloadUsers();
setMsg(r.taken.length ? { ok: false, text: `다른 사람에게 연결된 라이엇 ID 는 빼고 저장했습니다: ${r.taken.join(', ')}` } : { ok: true, text: okText });
sfx('click');
} catch (e) {
setMsg({ ok: false, text: errText(e) });
} finally {
setBusy(false);
}
};
const riotIds = riot
.split(/[,\n]/)
.map((x) => x.trim())
.filter(Boolean);
const riotBad = riotIds.filter((r) => !/^[^#]{1,32}#[^#]{1,8}$/.test(r));
return (
<div className="ue-block">
<div className="ue-label">색</div>
<div className="ue-colors" role="radiogroup" aria-label="유저 색">
{USER_COLORS.map((c) => (
<button
key={c}
className={`ue-sw${user.color.toLowerCase() === c ? ' on' : ''}`}
style={{ background: c }}
role="radio"
aria-checked={user.color.toLowerCase() === c}
aria-label={c}
disabled={busy}
onClick={() => void patch({ color: c }, '색을 바꿨습니다')}
/>
))}
<button className="ue-sw custom" title="다른 색 고르기" aria-label="다른 색 고르기" disabled={busy} onClick={() => colorRef.current?.click()}>
+
</button>
<input ref={colorRef} type="color" className="ue-hidden" defaultValue={user.color} onChange={(e) => void patch({ color: e.target.value }, '색을 바꿨습니다')} />
</div>
<div className="ue-label">라이엇 ID</div>
<form
className="ue-row"
onSubmit={(e) => {
e.preventDefault();
if (!riotBad.length) void patch({ riotIds }, '라이엇 ID 를 저장했습니다');
}}
>
<input className="ue-input" value={riot} placeholder="이름#태그 (여러 개는 쉼표로)" onChange={(e) => setRiot(e.target.value)} aria-label="라이엇 ID" />
<button className="btn sm" disabled={busy || riot.trim() === riotNow || riotBad.length > 0 || riotIds.length > 5}>
저장
</button>
</form>
{riotBad.length > 0 && <div className="ue-msg bad">이름#태그 형식이 아닙니다: {riotBad.join(', ')}</div>}
<div className="ue-hint">경기 기록의 선수와 연결됩니다. 새로 넣은 ID 는 다음 경기에서 확인됩니다.</div>
<label className="ue-check">
<input type="checkbox" checked={user.excluded} disabled={busy} onChange={(e) => void patch({ excluded: e.target.checked }, e.target.checked ? '앞으로 녹음하지 않습니다' : '다시 녹음합니다')} />
<span>
<b>녹음 제외</b>
<span className="ue-hint">{self ? '켜면 앞으로 내 목소리를 녹음하지 않습니다 (이미 녹음된 기록은 그대로).' : '켜면 앞으로 이 사람 목소리를 녹음하지 않습니다.'}</span>
</span>
</label>
{msg && <div className={`ue-msg${msg.ok ? ' ok' : ' bad'}`}>{msg.text}</div>}
</div>
);
}
/** 머리글 오른쪽 위 내 이름을 누르면 나오는 "내 정보" */
export function ProfilePopover({ onClose }: { onClose: () => void }) {
const { auth, logout, refreshMe } = useAuth();
const { userById } = useData();
const ref = useRef<HTMLDivElement>(null);
const [custom, setCustom] = useState<boolean | null>(null);
useEffect(() => {
const down = (e: PointerEvent) => {
if (ref.current && !ref.current.contains(e.target as Node) && !(e.target as HTMLElement).closest('.me-btn')) onClose();
};
const key = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
document.addEventListener('pointerdown', down);
document.addEventListener('keydown', key);
return () => {
document.removeEventListener('pointerdown', down);
document.removeEventListener('keydown', key);
};
}, [onClose]);
useEffect(() => {
let alive = true;
fetch('/site/profile', { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((p) => alive && p && setCustom(!!p.customName))
.catch(() => undefined);
return () => {
alive = false;
};
}, []);
if (auth.status !== 'ok') return null;
const me = auth.me.user;
const u = userById(me.id);
const admin = auth.me.canViewLogs;
const roleLabel = auth.me.role === 'superadmin' ? '최고 관리자' : auth.me.role === 'admin' ? '관리자' : auth.me.role === 'user' ? '앱 유저' : admin ? '관리자' : '서버 멤버';
return (
<motion.div
ref={ref}
className="popover profile-pop"
initial={{ opacity: 0, y: -6, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: -6, scale: 0.98 }}
transition={{ duration: 0.16 }}
role="dialog"
aria-label="내 정보"
>
<div className="pp-head">
<Avatar name={me.name} src={me.avatar} color={u?.color ?? '#5865f2'} size={40} />
<div>
<b style={u ? { color: u.color } : undefined}>{me.name}</b>
<div className="dim small">
{roleLabel} · <span className="mono">{me.id}</span>
</div>
</div>
</div>
<h5>표시 이름</h5>
<NameEditor
value={me.name}
custom={!!custom}
onSave={async (name) => {
const r = await api.setMyName(name);
setCustom(!!r.customName);
await refreshMe();
}}
/>
<div className="ue-hint">사이트 · 게임 PC 기록 · 범인 분석에서 디스코드 이름 대신 보입니다.</div>
<h5>녹음 기록 설정</h5>
{u ? <AppUserEditor user={u} self /> : <div className="ue-hint">아직 녹음된 적이 없습니다. 음성채널에서 한 번 녹음되면 색 · 라이엇 ID · 녹음 제외를 바꿀 수 있습니다.</div>}
<div className="pp-links">
{u && (
<Link to={`/users/${me.id}`} className="mini-btn" onClick={onClose}>
내 기록 보기
</Link>
)}
{admin && (
<Link to="/admin" className="mini-btn" onClick={onClose}>
🛡️ 관리 페이지
</Link>
)}
<button className="mini-btn" onClick={logout}>
<ILogout width={13} height={13} /> 로그아웃
</button>
</div>
</motion.div>
);
}

View File

@@ -3,13 +3,16 @@ import type { UtteranceInfo, UtteranceItem } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { fmtWhen } from '../lib/format';
import { player } from '../store/player';
import { useData } from '../store/app';
import { useAuth, useData, useLive } from '../store/app';
import { IClose, IDownload, IPlay } from './Icons';
/** 발화 우클릭 메뉴 · 자세한 정보 창 (앱에 하나만 띄운다) */
type MenuState = { item: UtteranceItem; x: number; y: number } | null;
let menu: MenuState = null;
let infoFor: UtteranceItem | null = null;
let deleteFor: UtteranceItem | null = null;
/** 이 화면에서 지운 발화 (다른 사람이 지운 것도 실시간으로). 목록마다 따로 고치지 않고 줄이 스스로 숨는다 */
const deleted = new Set<string>();
const subs = new Set<() => void>();
const notify = () => subs.forEach((f) => f());
const subscribe = (f: () => void) => {
@@ -36,9 +39,30 @@ function closeInfo(): void {
infoFor = null;
notify();
}
function openDelete(item: UtteranceItem): void {
menu = null;
deleteFor = item;
notify();
}
function closeDelete(): void {
deleteFor = null;
notify();
}
function markDeleted(id: string): void {
if (deleted.has(id)) return;
deleted.add(id);
if (player.state.item?.id === id) player.stop();
notify();
}
/** 지운 발화인가 (줄을 숨긴다) */
export function useDeleted(id: string): boolean {
return useSyncExternalStore(subscribe, () => deleted.has(id));
}
/** 녹음 원본(.ogg)을 내려받는다. 게임 PC → 사이트 서버 중계로 받은 파일을 그대로 저장 */
export async function downloadAudio(item: UtteranceItem, fileName?: string | null): Promise<void> {
// 파일 이름: 게임 PC 의 녹음 파일 이름 그대로 (날짜 · 시각 · 말한 사람 · 게임 · 라운드). 예전 앱이면 발화 ID
if (!fileName) fileName = await api.utteranceInfo(item.id).then((i) => i.fileName).catch(() => null);
const res = await fetch(`/api/audio/${encodeURIComponent(item.id)}`, { credentials: 'include' });
if (!res.ok) throw new Error(res.status === 410 ? '음성 파일이 삭제되었습니다' : `받지 못했습니다 (${res.status})`);
const blob = await res.blob();
@@ -57,7 +81,16 @@ const copy = (text: string) => navigator.clipboard?.writeText(text).catch(() =>
export function UttMenuHost() {
const m = useSyncExternalStore(subscribe, () => menu);
const info = useSyncExternalStore(subscribe, () => infoFor);
const del = useSyncExternalStore(subscribe, () => deleteFor);
const [err, setErr] = useState<string | null>(null);
const [okMsg, setOkMsg] = useState<string | null>(null);
const { auth } = useAuth();
// 지우기: 관리자나 말한 사람만 (게임 PC 도 한 번 더 확인한다)
const canDelete = (it: UtteranceItem) => auth.status === 'ok' && (!!auth.me.canViewLogs || auth.me.user.id === it.userId);
useLive((e) => {
if (e.type === 'utterance.deleted') markDeleted(e.data.id);
});
useEffect(() => {
if (!m) return;
@@ -80,6 +113,11 @@ export function UttMenuHost() {
const t = setTimeout(() => setErr(null), 4000);
return () => clearTimeout(t);
}, [err]);
useEffect(() => {
if (!okMsg) return;
const t = setTimeout(() => setOkMsg(null), 4000);
return () => clearTimeout(t);
}, [okMsg]);
const act = (fn: () => unknown) => (e: React.PointerEvent | React.MouseEvent) => {
e.stopPropagation();
@@ -93,7 +131,7 @@ export function UttMenuHost() {
<div
className="ctx-menu"
role="menu"
style={{ left: Math.min(m.x, window.innerWidth - 230), top: Math.min(m.y, window.innerHeight - 190) }}
style={{ left: Math.min(m.x, window.innerWidth - 230), top: Math.min(m.y, window.innerHeight - 240) }}
onPointerDown={(e) => e.stopPropagation()}
onContextMenu={(e) => e.preventDefault()}
>
@@ -109,10 +147,32 @@ export function UttMenuHost() {
<button role="menuitem" disabled={!m.item.text} onClick={act(() => copy(m.item.text ?? ''))}>
<span className="ctx-ic">⧉</span> 내용 복사
</button>
<div className="ctx-sep" />
<button
role="menuitem"
className="danger"
disabled={!canDelete(m.item)}
title={canDelete(m.item) ? undefined : '관리자나 말한 사람만 지울 수 있습니다'}
onClick={act(() => openDelete(m.item))}
>
<span className="ctx-ic">🗑</span> 삭제…
</button>
</div>
)}
{info && <InfoDialog item={info} onError={setErr} />}
{del && (
<DeleteDialog
key={del.id}
item={del}
onDone={(learned) => {
markDeleted(del.id);
closeDelete();
setOkMsg(learned ? `삭제했습니다. 앞으로 "${learned.length > 40 ? learned.slice(0, 40) + '…' : learned}" 는 잡음으로 거릅니다` : '삭제했습니다');
}}
/>
)}
{err && <div className="ctx-toast">{err}</div>}
{okMsg && !err && <div className="ctx-toast ok">{okMsg}</div>}
</>
);
}
@@ -216,3 +276,73 @@ function InfoDialog({ item, onError }: { item: UtteranceItem; onError: (m: strin
</div>
);
}
/** 삭제 확인: 잡음이라 삭제(같은 문장을 다음부터 잡음으로 거름) · 그냥 삭제 · 취소 */
function DeleteDialog({ item, onDone }: { item: UtteranceItem; onDone: (learned: string | null) => void }) {
const { userById } = useData();
const [busy, setBusy] = useState<'noise' | 'plain' | null>(null);
const [failed, setFailed] = useState<string | null>(null);
const text = item.text?.trim() || null;
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && closeDelete();
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [busy]);
const run = async (noise: boolean) => {
setBusy(noise ? 'noise' : 'plain');
setFailed(null);
try {
const r = await api.deleteUtterance(item.id, noise);
onDone(r.learned);
} catch (e) {
setBusy(null);
if (e instanceof ApiError && e.status === 404 && e.code === 'not_found') return onDone(null); // 이미 지워짐
setFailed(
e instanceof ApiError && e.status === 404
? '게임 PC 의 겜녹이가 예전 버전입니다. v1.4.0 이상으로 업데이트하면 지울 수 있습니다.'
: e instanceof ApiError && e.status === 403
? '관리자나 말한 사람만 지울 수 있습니다.'
: e instanceof ApiError && e.status === 503
? '게임 PC 가 꺼져 있어 지우지 못했습니다.'
: '지우지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
);
}
};
return (
<div className="ctx-dim" onPointerDown={() => !busy && closeDelete()}>
<div className="ctx-dialog del-dialog" role="dialog" aria-label="발화 삭제" onPointerDown={(e) => e.stopPropagation()}>
<div className="ctx-head">
<b>발화 삭제</b>
<button className="icon-btn" onClick={closeDelete} disabled={!!busy} aria-label="닫기">
<IClose width={16} height={16} />
</button>
</div>
<div className="del-quote">
<span className="dim">{userById(item.userId)?.name ?? '알 수 없음'} · {fmtWhen(item.ts)}</span>
<p>{text ?? '(인식된 글 없음)'}</p>
</div>
<p className="del-help">
글과 음성 파일을 게임 PC 에서 지웁니다. 되돌릴 수 없습니다.
<br />
<b>잡음이라 삭제</b>를 고르면 이 문장을 잡음으로 배워서, 다음에 같은 문장이 인식되면 자동으로 잡음 처리합니다 (띄어쓰기 · 문장부호는 무시하고, 긴 문장은 글자 수가 같고 한두 글자만 바뀐 것까지 같은 문장으로 봅니다. 앞뒤에 다른 말이 붙은 발화는 지우지 않습니다).
배운 문장은 사전 화면에서 지울 수 있습니다.
</p>
{failed && <p className="del-err">{failed}</p>}
<div className="ctx-foot">
<button className="chip" onClick={closeDelete} disabled={!!busy}>
취소
</button>
<button className="chip danger" onClick={() => void run(false)} disabled={!!busy}>
{busy === 'plain' ? '지우는 중…' : '그냥 삭제'}
</button>
<button className="chip danger on" onClick={() => void run(true)} disabled={!!busy || !text} title={text ? undefined : '인식된 글이 없어 배울 문장이 없습니다'}>
{busy === 'noise' ? '지우는 중…' : '잡음이라 삭제'}
</button>
</div>
</div>
</div>
);
}

View File

@@ -7,7 +7,7 @@ import { sfx } from '../lib/sfx';
import { realTip } from '../lib/format';
import { Avatar, TimeCell } from './common';
import { IEdit } from './Icons';
import { openUttMenu } from './UttMenu';
import { openUttMenu, useDeleted } from './UttMenu';
const STATUS: Record<UtteranceItem['status'], [string, string]> = {
realtime: ['실시간', 'st-rt'],
@@ -147,6 +147,7 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
const playing = usePlayer((s) => active && s.playing);
const [editing, setEditing] = useState(false);
const [st, stCls] = STATUS[item.status];
const gone = useDeleted(item.id);
const click = () => {
if (editing) return;
@@ -183,6 +184,9 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
</button>
);
// 우클릭으로 지운 발화 (경기 화면 · 유저 화면 등 어느 목록이든 줄이 숨는다)
if (gone) return null;
if (variant === 'compact') {
return (
<div className={`l utt${active ? ' cur' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} onContextMenu={menu} data-id={item.id}>

View File

@@ -0,0 +1,75 @@
/**
* 리플레이 스킬 · 설치물 (변환기 objectKinds: GameObject_Sarge_4_Smoke_… 같은 게임 클래스 이름) → 3D 모양 · 색.
* 게임의 효과(파티클)는 그대로 옮길 수 없어서 종류별로 비슷한 모양을 그린다:
* smoke 연막(요원 색 구), fire 장판(바닥 원), burst 폭발 · 섬광(커지며 사라지는 구), pulse 정찰 · 소리(퍼지는 고리),
* projectile 날아가는 것(작은 빛 구), device 설치물 · 함정 · 드론(작은 다이아몬드), spike 스파이크(총 모델 대신 스파이크 3D)
*/
export type AbilityShape = 'smoke' | 'fire' | 'burst' | 'pulse' | 'projectile' | 'device' | 'spike';
export interface AbilityLook {
shape: AbilityShape;
/** 0xRRGGBB */
color: number;
/** 게임 단위(cm) 반지름 */
radiusCm: number;
/** 사라진 시각을 모를 때 보여 줄 시간 (ms) */
defaultMs: number;
/** 요원 코드 (Sarge 등), 모르면 null */
agent: string | null;
}
/** 요원 코드(게임 내부 이름) → 대표 색. 연막 · 장판은 게임에서 보이는 색에 가깝게 */
const AGENT_COLOR: Record<string, number> = {
Sarge: 0xd9a066, // 브림스톤: 주황빛 연막
Wraith: 0x5a3f8f, // 오멘: 짙은 보라
Rift: 0x9a5fd6, // 아스트라: 보라
Smonk: 0xe48ac6, // 클로브: 분홍
Wushu: 0xe9f2ff, // 제트: 흰 바람
Mage: 0x2fa9c9, // 하버: 물
Pandemic: 0x41c25a, // 바이퍼: 초록 독
Phoenix: 0xff7a2f, // 피닉스: 불
Hunter: 0x4fb3ff, // 소바: 정찰
Deadeye: 0xd9b25a, // 체임버: 금색
Killjoy: 0xffd23f, // 킬조이: 노랑
Gumshoe: 0xd7dde6, // 사이퍼: 흰 철사
Thorne: 0x4fe0c9, // 세이지: 청록
Clay: 0xff8a3d, // 레이즈
Breach: 0xff9a3d, // 브리치
Vampire: 0xc23fd6, // 레이나
Stealth: 0x4f6fff, // 요루: 파랑
Guide: 0x7ad65a, // 스카이
BountyHunter: 0x6b3f8f, // 페이드
Grenadier: 0x7fd6ff, // 케이오
AggroBot: 0xb6f04a, // 게코
Sprinter: 0x3fd0ff, // 네온
Cable: 0x9fe8ff, // 데드록
Sequoia: 0xb07cff, // 아이소
Nox: 0x7d8cff, // 바이스
Cashew: 0xffb347, // 테호
Terra: 0xff6fa8, // 웨이레이
Pine: 0x9ad4ff,
Iris: 0xffc0f0,
};
const DEFAULT_COLOR = 0x9fffe0;
/** 클래스 이름에서 요원 코드: GameObject_<요원>_… / Projectile_<요원>_… / Ability_Q_<요원>_… */
export function abilityAgent(kind: string): string | null {
const parts = kind.split('_');
for (const p of parts.slice(1, 4)) if (AGENT_COLOR[p] != null) return p;
return null;
}
export function abilityLook(kind: string): AbilityLook {
const agent = abilityAgent(kind);
const color = agent ? AGENT_COLOR[agent] : DEFAULT_COLOR;
const k = kind.toLowerCase();
const base = { color, agent };
if (kind === 'TimedBomb_C') return { ...base, shape: 'spike', color: 0xff2d3d, radiusCm: 40, defaultMs: 45000 };
if (/^projectile_/.test(k)) return { ...base, shape: 'projectile', radiusCm: /flash/.test(k) ? 25 : 18, defaultMs: 3000 };
// 연막: 관리자 · 생성기는 실제 연막이 아니다
if (/smoke|cloud|nebula|dome/.test(k) && !/manager|spawner|projectile/.test(k)) return { ...base, shape: 'smoke', radiusCm: 450, defaultMs: 15000 };
if (/^patch_|molotov|fire|acid|slow|snakebite|nanoswarm|paint/.test(k)) return { ...base, shape: 'fire', radiusCm: /slow/.test(k) ? 550 : 450, defaultMs: 7000 };
if (/explosion|explode|blast|flash|stun|concuss|beam|strike|decay/.test(k)) return { ...base, shape: 'burst', radiusCm: /strike|beam/.test(k) ? 700 : 400, defaultMs: 1200 };
if (/sonar|ping|reveal|recon|scan|pulse|alarm/.test(k)) return { ...base, shape: 'pulse', radiusCm: 1500, defaultMs: 2500 };
return { ...base, shape: 'device', radiusCm: 30, defaultMs: 12000 };
}

View File

@@ -0,0 +1,392 @@
import * as THREE from 'three';
import { GLTFLoader, type GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
import { clone as cloneSkinned } from 'three/examples/jsm/utils/SkeletonUtils.js';
import { loadIndex } from './map3d';
import { skinFileUrl, type SkinLook } from './skins';
/**
* 요원 3D 몸 · 총 (tools/map-extract agents → 사이트 서버 /site/maps3d, 맵과 같은 폴더).
* 좌표는 게임(UE) 그대로: cm, 발 = 원점 근처, 앞 = +X (애니메이션의 Root 회전 포함).
* 애니메이션: 요원 glb 안의 기본(ub_rifle · lb_idle/run/walk) + 공용 anims.glb (tools/map-extract anims:
* 앉기 · 점프 · 착지 · 무기별 자세 · 재장전 · 꺼내기 · 던지기 · 칼 · 해체 · 죽음). 공용 애니메이션은 뼈 이름으로 붙이고,
* 이동 트랙은 (요원 참조 자세 − 공용 파일 참조 자세)만큼 옮긴다 (요원마다 키가 달라서).
* 위 몸(ub_*) · 아래 몸(lb_*)을 따로 섞고, 죽으면 온몸(fb_*) 하나만.
*/
const cache = new Map<string, Promise<GLTF>>();
function load(url: string): Promise<GLTF> {
let p = cache.get(url);
if (!p) {
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
p = loader.loadAsync(url);
p.catch(() => cache.delete(url)); // 실패하면 다음에 다시
cache.set(url, p);
}
return p;
}
export function assetUrl(dir: string, file: string) {
return `/site/maps3d/${encodeURIComponent(dir)}/${encodeURIComponent(file)}`;
}
/** 리플레이 캐릭터 클래스(Wushu_PC_C)의 몸. 없으면 null */
export async function loadAgent(characterClass: string): Promise<GLTF | null> {
const idx = await loadIndex();
const a = idx?.dir ? idx.agents?.[characterClass] : undefined;
return a && idx?.dir ? load(assetUrl(idx.dir, a.file)) : null;
}
/** 총 (리플레이 equipKinds 이름: Vandal · Classic · Melee …). 스킨 3인칭 모델이 있으면 그것 (받지 못하면 기본 스킨). 없으면 null */
export async function loadWeapon(name: string, skin?: SkinLook | null): Promise<GLTF | null> {
if (skin?.w3p) {
const g = await load(skinFileUrl(skin.w3p)).catch(() => null);
if (g) return g;
}
const idx = await loadIndex();
const w = idx?.dir ? idx.weapons?.[name] : undefined;
return w && idx?.dir ? load(assetUrl(idx.dir, w.file)) : null;
}
/** 공용 애니메이션. 없으면 null (요원 glb 안의 기본 애니메이션만 쓴다) */
export async function loadAnims(): Promise<GLTF | null> {
const idx = await loadIndex();
return idx?.dir && idx.anims ? load(assetUrl(idx.dir, idx.anims.file)).catch(() => null) : null;
}
/** 손에 든 것의 자세 종류 */
export type WeaponCat = 'rifle' | 'pistol' | 'sniper' | 'knife' | 'ability';
const PISTOLS = new Set(['Classic', 'Shorty', 'Frenzy', 'Ghost', 'Sheriff', 'Compact Pistol']);
const SNIPERS = new Set(['Marshal', 'Outlaw', 'Operator']);
/** 리플레이 equipKinds 이름 → 자세 종류 */
export function weaponCat(kind: string | undefined | null): WeaponCat {
if (!kind) return 'ability';
if (kind === 'Melee') return 'knife';
if (PISTOLS.has(kind)) return 'pistol';
if (SNIPERS.has(kind)) return 'sniper';
if (/^(Ability_|Equippable_)|Unarmed|Spike|Bomb_Defuser/.test(kind)) return 'ability';
return 'rifle';
}
/** 손에 3D 총을 그릴 것 (스킬 · 맨손 · 해체기는 없음) */
export function isGun(kind: string | undefined | null): kind is string {
return !!kind && !/^(Ability_|Equippable_)|Unarmed|Bomb_Defuser/.test(kind);
}
/** 경기 기록 사망 모션 이름 (TP_Core_Death_Head_Front_SM_Montage) → 공용 애니메이션 이름 (fb_Head_Front_SM) */
export function deathClipName(montage: string | undefined | null): string {
const m = montage?.match(/^TP_Core_Death_(.+?)(_Montage)?$/);
return m ? `fb_${m[1]}` : 'fb_Body_Front_LG';
}
/** 애니메이션이 만든 속도 (cm/s): 이보다 빠르면 빨리 돌린다 */
const RUN_CM_S = 540;
const WALK_CM_S = 300;
const CROUCH_CM_S = 200;
/** 한 프레임의 몸 상태 (뷰어가 리플레이에서 계산해 넣는다). 시간은 모두 리플레이 기준이라 되감기 · 멈춤에도 같은 자세 */
export interface RigInput {
/** 지난 프레임부터 리플레이 시간 (초, 되감으면 0) */
dt: number;
/** 몸 기준 이동 속도 (cm/s, UE: 앞 +X · 오른쪽 +Y) */
fwd: number;
right: number;
/** 위아래 보는 각 (도) */
pitch: number;
crouch: boolean;
/** 공중에 뜬 지 (ms, 땅이면 null) · 내려앉은 지 (ms, 오래됐으면 null) */
airMs: number | null;
landMs: number | null;
cat: WeaponCat;
/** 위 몸 한 번 동작 (재장전 · 꺼내기 · 던지기 · 칼 · 해체): 공용 애니메이션 이름과 시작한 지 (ms). loop 면 반복 */
overlay: { clip: string; ms: number; loop?: boolean } | null;
/** 죽음: 온몸 애니메이션 이름과 죽은 지 (ms) */
death: { clip: string; ms: number } | null;
}
/** 공용 애니메이션을 이 요원 뼈 길이에 맞춘 복제본 (요원 glb 하나당 한 번) */
const retargeted = new WeakMap<object, Map<string, THREE.AnimationClip>>();
function sharedClips(model: THREE.Object3D, agent: GLTF, anims: GLTF | null): Map<string, THREE.AnimationClip> {
const out = new Map<string, THREE.AnimationClip>();
for (const c of agent.animations) out.set(c.name, c);
if (!anims) return out;
let cached = retargeted.get(agent);
if (!cached) {
cached = new Map();
const offset = new Map<string, THREE.Vector3>();
const delta = (bone: string) => {
let d = offset.get(bone);
if (!d) {
const mine = model.getObjectByName(bone);
const core = anims.scene.getObjectByName(bone);
d = mine && core ? mine.position.clone().sub(core.position) : new THREE.Vector3();
offset.set(bone, d);
}
return d;
};
const has = new Set<string>();
model.traverse((o) => has.add(o.name));
for (const c of anims.animations) {
// 이 요원에게 없는 뼈(눈꺼풀 · 카메라 등)는 뺀다
const own = c.tracks.filter((tr) => has.has(tr.name.slice(0, tr.name.lastIndexOf('.'))));
const tracks = own.map((tr) => {
if (!tr.name.endsWith('.position')) return tr;
const d = delta(tr.name.slice(0, -'.position'.length));
if (!d.lengthSq()) return tr;
const t2 = tr.clone();
const v = t2.values;
for (let i = 0; i < v.length; i += 3) {
v[i] += d.x;
v[i + 1] += d.y;
v[i + 2] += d.z;
}
return t2;
});
cached.set(c.name, new THREE.AnimationClip(c.name, c.duration, tracks));
}
retargeted.set(agent, cached);
}
for (const [n, c] of cached) out.set(n, c); // 공용이 있으면 공용 (ub_rifle 등 같은 이름은 공용 자세가 게임과 같다)
return out;
}
/** 선수 한 명의 몸 (복제본) · 애니메이션 · 손에 든 총 */
export class AgentRig {
/** UE 좌표(cm) 공간의 선수 자리. 뷰어가 위치 · yaw 를 넣는다 */
readonly root = new THREE.Group();
private readonly model: THREE.Object3D;
private readonly mixer: THREE.AnimationMixer;
private readonly clips: Map<string, THREE.AnimationClip>;
private readonly actions = new Map<string, THREE.AnimationAction>();
private readonly hand: THREE.Object3D | null;
private readonly gunSlot = new THREE.Group();
/** 총구 불꽃 (사격 순간에 잠깐) */
readonly muzzle: THREE.Sprite;
private gunName: string | null = null;
private gunSkin: SkinLook | null = null;
private gunReq = 0;
private gunTip = 60;
private readonly tmp = new THREE.Vector3();
/** 사격 반동 (0~1, 줄어든다) */
private kick = 0;
private shotMs: number | null = null;
constructor(gltf: GLTF, anims: GLTF | null) {
this.model = cloneSkinned(gltf.scene);
this.model.traverse((o) => {
const m = o as THREE.Mesh;
if (m.isMesh) m.frustumCulled = false;
});
this.root.add(this.model);
this.root.add(this.gunSlot);
this.muzzle = new THREE.Sprite(new THREE.SpriteMaterial({ map: muzzleTexture(), color: 0xffd38a, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true }));
this.muzzle.scale.setScalar(26);
this.muzzle.visible = false;
this.gunSlot.add(this.muzzle);
this.mixer = new THREE.AnimationMixer(this.model);
this.clips = sharedClips(this.model, gltf, anims);
// R_WeaponPoint 는 공용 애니메이션이 움직이지 않아 손에서 떨어져 있다 → 손목(R_Hand) 기준
this.hand = this.model.getObjectByName('R_Hand') ?? null;
}
private action(name: string): THREE.AnimationAction | null {
let a = this.actions.get(name);
if (a) return a;
const c = this.clips.get(name);
if (!c) return null;
a = this.mixer.clipAction(c);
a.play();
a.setEffectiveWeight(0);
this.actions.set(name, a);
return a;
}
/** 들고 있는 총 바꾸기 (이름 없으면 맨손, 스킨 모습이 있으면 그 스킨) */
setWeapon(name: string | null, skin?: SkinLook | null) {
if (name === this.gunName && (skin ?? null) === this.gunSkin) return;
this.gunName = name;
this.gunSkin = skin ?? null;
const req = ++this.gunReq;
for (const c of [...this.gunSlot.children]) if (c !== this.muzzle) this.gunSlot.remove(c);
if (!name) return;
void loadWeapon(name, skin)
.then((g) => {
if (!g || req !== this.gunReq) return;
const gun = g.scene.clone(true);
gun.traverse((o) => {
const m = o as THREE.Mesh;
if (m.isMesh) m.frustumCulled = false;
});
gun.position.x = 7; // 손목 → 손바닥 (총 원점 = 손잡이)
if (name === 'Melee') gun.rotation.y = Math.PI / 2; // 칼은 날이 +Z → 앞(+X)으로
const box = new THREE.Box3().setFromObject(gun);
this.gunTip = Number.isFinite(box.max.x) ? box.max.x : 60;
this.gunSlot.add(gun);
})
.catch(() => {});
}
/** 마지막 사격에서 지난 시간 (ms, 없으면 null): 반동 · 총구 불꽃 */
setShot(ms: number | null) {
this.shotMs = ms != null && ms >= 0 ? ms : null;
this.kick = this.shotMs != null && this.shotMs < 90 ? 1 - this.shotMs / 90 : 0;
}
/** 이 애니메이션이 있는지 (뷰어가 대신 할 것을 고를 때) */
has(name: string) {
return this.clips.has(name);
}
update(inp: RigInput) {
const set = (name: string, w: number, opts?: { time?: number; scale?: number }) => {
const a = w > 0.001 ? this.action(name) : this.actions.get(name);
if (!a) return w > 0.001 ? false : true;
a.setEffectiveWeight(w);
if (opts?.time != null) {
a.paused = true;
a.time = Math.min(opts.time, a.getClip().duration - 1e-3);
} else {
a.paused = false;
a.setEffectiveTimeScale(opts?.scale ?? 1);
}
return true;
};
const zero = new Set(this.actions.keys());
const use = (name: string, w: number, opts?: { time?: number; scale?: number }) => {
if (w <= 0.001) return;
if (set(name, w, opts)) zero.delete(name);
};
if (inp.death && this.clips.has(inp.death.clip)) {
// 죽음: 온몸 한 번 (끝 자세로 누워 있다)
use(inp.death.clip, 1, { time: inp.death.ms / 1000 });
} else if (inp.death) {
use('fb_Body_Front_LG', 1, { time: inp.death.ms / 1000 });
} else {
this.lowerBody(inp, use);
this.upperBody(inp, use);
}
for (const n of zero) this.actions.get(n)?.setEffectiveWeight(0);
this.mixer.update(inp.dt);
// 총: 오른손 자리에, 몸 앞(+X)을 보는 방향 + 위아래 각, 사격하면 뒤로 살짝
this.muzzle.visible = this.kick > 0.55 && this.gunName != null && this.gunName !== 'Melee';
if (this.muzzle.visible) {
this.muzzle.position.set(this.gunTip + 6, 0, 2);
this.muzzle.material.rotation = Math.random() * Math.PI;
}
if (this.hand && this.gunSlot.children.length > 1) {
this.root.updateWorldMatrix(true, true);
this.hand.getWorldPosition(this.tmp);
this.root.worldToLocal(this.tmp);
this.gunSlot.position.copy(this.tmp);
const pr = (-THREE.MathUtils.clamp(inp.pitch, -80, 80) * Math.PI) / 180;
this.gunSlot.rotation.set(0, pr - this.kick * 0.12, 0);
this.gunSlot.translateX(-this.kick * 4);
}
this.gunSlot.visible = !inp.death;
}
private lowerBody(inp: RigInput, use: (n: string, w: number, o?: { time?: number; scale?: number }) => void) {
const has = (n: string) => this.clips.has(n);
// 공중: 뛴 처음 0.45초는 점프 동작, 그 뒤는 떨어지는 자세
if (inp.airMs != null && (has('lb_fall') || has('lb_jump'))) {
const jumpW = has('lb_jump') ? 1 - THREE.MathUtils.smoothstep(inp.airMs, 300, 500) : 0;
if (jumpW > 0) use('lb_jump', jumpW, { time: inp.airMs / 1000 });
if (1 - jumpW > 0) use(has('lb_fall') ? 'lb_fall' : 'lb_jump', 1 - jumpW, has('lb_fall') ? undefined : { time: 0.45 });
return;
}
const speed = Math.hypot(inp.fwd, inp.right);
const moving = THREE.MathUtils.smoothstep(speed, 40, 140);
const sum = Math.abs(inp.fwd) + Math.abs(inp.right) || 1;
const dir = (n: number) => (moving * Math.max(0, n)) / sum;
// 내려앉음: 0.35초 동안 착지 동작을 섞는다
const landW = inp.landMs != null && has('lb_land') ? 1 - THREE.MathUtils.smoothstep(inp.landMs, 150, 450) : 0;
const rest = 1 - landW;
if (landW > 0) use('lb_land', landW, { time: inp.landMs! / 1000 });
const crouch = inp.crouch && has('lb_crouch');
let g: string;
let base: number;
if (crouch) {
g = 'lb_crouch';
base = CROUCH_CM_S;
use('lb_crouch', rest * (1 - moving));
} else {
g = speed > 400 ? 'lb_run' : 'lb_walk';
base = speed > 400 ? RUN_CM_S : WALK_CM_S;
use('lb_idle', rest * (1 - moving));
}
const scale = THREE.MathUtils.clamp(speed / base, 0.6, 1.5);
use(`${g}N`, rest * dir(inp.fwd), { scale });
use(`${g}S`, rest * dir(-inp.fwd), { scale });
use(`${g}E`, rest * dir(inp.right), { scale });
use(`${g}W`, rest * dir(-inp.right), { scale });
}
private upperBody(inp: RigInput, use: (n: string, w: number, o?: { time?: number; scale?: number }) => void) {
const has = (n: string) => this.clips.has(n);
let ow = 0;
if (inp.overlay && has(inp.overlay.clip)) {
const dur = this.clips.get(inp.overlay.clip)!.duration * 1000;
const ms = inp.overlay.loop ? inp.overlay.ms % dur : inp.overlay.ms;
if (inp.overlay.loop || ms < dur) {
// 들어갈 때 · 끝날 때 0.12초씩 섞는다
ow = inp.overlay.loop ? THREE.MathUtils.smoothstep(inp.overlay.ms, 0, 120) : Math.min(THREE.MathUtils.smoothstep(ms, 0, 120), 1 - THREE.MathUtils.smoothstep(ms, dur - 150, dur));
use(inp.overlay.clip, ow, { time: ms / 1000 });
}
}
const cat = inp.cat;
let pose = `ub_${cat}${inp.crouch ? 'Crouch' : ''}`;
if (!has(pose)) pose = `ub_${cat}`;
if (!has(pose)) pose = 'ub_rifle';
let rest = 1 - ow;
// 사격: 반동 자세 (쏜 뒤 0.35초 동안 줄어든다)
const fire = `ub_${cat}Fire`;
if (rest > 0 && this.shotMs != null && this.shotMs < 350 && has(fire)) {
const fw = rest * (1 - THREE.MathUtils.smoothstep(this.shotMs, 120, 350));
use(fire, fw, { time: this.shotMs / 1000 });
rest -= fw;
}
// 조준 각: 위(+90°) · 아래(-90°) 자세를 비율로 섞는다 (게임의 AimOffset)
const up = THREE.MathUtils.clamp(inp.pitch / 90, 0, 1);
const down = THREE.MathUtils.clamp(-inp.pitch / 90, 0, 1);
const hasUp = has(`${pose}Up`) && has(`${pose}Down`);
if (hasUp) {
use(`${pose}Up`, rest * up);
use(`${pose}Down`, rest * down);
use(pose, rest * (1 - up - down));
} else use(pose, rest);
}
dispose() {
this.mixer.stopAllAction();
this.gunSlot.clear();
}
}
let muzzleTex: THREE.Texture | null = null;
/** 총구 불꽃 (가운데가 밝은 별 모양) */
function muzzleTexture() {
if (muzzleTex) return muzzleTex;
const c = document.createElement('canvas');
c.width = c.height = 64;
const g = c.getContext('2d')!;
const rg = g.createRadialGradient(32, 32, 0, 32, 32, 32);
rg.addColorStop(0, 'rgba(255,255,240,1)');
rg.addColorStop(0.25, 'rgba(255,210,120,0.9)');
rg.addColorStop(1, 'rgba(255,120,20,0)');
g.fillStyle = rg;
g.beginPath();
for (let i = 0; i < 12; i++) {
const a = (i / 12) * Math.PI * 2;
const r = i % 2 ? 12 : 32;
g.lineTo(32 + Math.cos(a) * r, 32 + Math.sin(a) * r);
}
g.fill();
muzzleTex = new THREE.CanvasTexture(c);
muzzleTex.colorSpace = THREE.SRGBColorSpace;
return muzzleTex;
}

View File

@@ -14,9 +14,13 @@ import type {
GameType,
BundleInfo,
BundleImportResult,
NoisePhrase,
AppRole,
AppUserRow,
} from '@gvr/shared';
import { reportClient } from './report';
import type { ReplayFile } from './replay';
/** 전역 신호: 401 → 로그인 화면, 503 device_offline → 잠금 화면 */
type Signal = 'unauthorized' | 'not_member' | 'device_offline';
@@ -31,11 +35,17 @@ export class ApiError extends Error {
constructor(
public status: number,
public code: string,
/** 서버가 함께 보낸 설명 (있으면) */
public detail?: string,
) {
super(`${status} ${code}`);
}
}
/** 경기 탭 필터 */
export type MatchHas = 'timeline' | 'voice';
export type MatchReplay = 'yes' | 'no';
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
let res: Response;
try {
@@ -52,8 +62,11 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
return (await res.json()) as T;
}
let code = 'error';
let detail: string | undefined;
try {
code = ((await res.json()) as { error?: string }).error ?? code;
const b = (await res.json()) as { error?: string; message?: string };
code = b.error ?? code;
if (typeof b.message === 'string') detail = b.message;
} catch {
/* 본문 없음 */
}
@@ -62,7 +75,7 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
else if (res.status === 503 && code === 'device_offline') emit('device_offline');
// 게임 PC 쪽 오류 · 시간 초과는 사이트 로그에도 남긴다 (게임 PC 꺼짐은 서버가 이미 남김)
else if (res.status >= 500) reportClient('error', `요청 실패 ${res.status} ${code}: ${init.method ?? 'GET'} ${path.split('?')[0]}`);
throw new ApiError(res.status, code);
throw new ApiError(res.status, code, detail);
}
export interface Me {
@@ -70,6 +83,16 @@ export interface Me {
isOwner: boolean;
/** 사이트 로그를 볼 수 있는지 (관리자 · 최고 관리자, v1.3.6~) */
canViewLogs?: boolean;
/** 앱 역할 (등록 안 된 멤버는 null, v1.6.0~) */
role?: AppRole | null;
}
/** 관리 화면 머리 (v1.6.0) */
export interface AdminOverview {
device: DeviceStatus & { guildId: string | null };
latest: { version: string; url: string; publishedAt: string | null } | null;
role: AppRole;
serverVersion: string;
}
export interface StatusResponse {
device: DeviceStatus;
@@ -112,6 +135,17 @@ export const api = {
/** 관리자(OWNER_DISCORD_IDS) 전용: 게임 PC 1회용 등록 코드 (10분) */
registrationCode: () => request<{ code: string; expiresAt: number }>('/admin/registration-code', { method: 'POST' }),
status: () => request<StatusResponse>('/api/status'),
// 내 정보 · 관리 화면 (v1.6.0)
setMyName: (name: string) => request<{ user: Me['user']; customName: string | null }>('/site/profile/name', { method: 'PUT', body: JSON.stringify({ name }) }),
/** 색 · 녹음 제외 · 라이엇 ID (게임 PC 앱 v1.6.0~, 본인 또는 관리자) */
updateUser: (id: string, patch: { color?: string; excluded?: boolean; riotIds?: string[] }) =>
request<{ user: User; taken: string[] }>(`/api/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) }),
adminOverview: () => request<AdminOverview>('/site/admin/overview'),
adminUsers: () => request<{ users: AppUserRow[]; names: Record<string, string> }>('/site/admin/users'),
adminSetName: (id: string, name: string) => request<{ names: Record<string, string> }>('/site/admin/names', { method: 'PUT', body: JSON.stringify({ id, name }) }),
adminAddUser: (id: string, role: 'admin' | 'user') => request<{ users: AppUserRow[] }>('/site/admin/users', { method: 'POST', body: JSON.stringify({ id, role }) }),
adminSetRole: (id: string, role: 'admin' | 'user') => request<{ users: AppUserRow[] }>(`/site/admin/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ role }) }),
adminRemoveUser: (id: string) => request<{ users: AppUserRow[] }>(`/site/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' }),
overview: () => request<Overview>('/api/overview'),
users: () => request<User[]>('/api/users'),
user: (id: string) => request<UserProfile>(`/api/users/${encodeURIComponent(id)}`),
@@ -132,8 +166,18 @@ export const api = {
hideNoise: 1,
})}`,
),
matches: (o: { game?: GameType; limit?: number; before?: number } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
// has: timeline = 타임라인에 나오는 경기, voice = 목소리가 녹음된 경기 (v1.9.0 앱부터, 예전 앱은 무시하고 다 보냄)
// mode · after (v1.11.0 앱부터): 모드 이름("경쟁전") · 이 시각 이후 시작한 경기. 데스매치는 앱이 늘 뺀다 (예전 앱은 사이트가 거름)
// replay (v1.12.0 앱부터): yes = 게임 PC 에 리플레이 파일이 있는 발로란트 경기, no = 없는 발로란트 경기 (예전 앱은 무시하고 다 보냄)
matches: (o: { game?: GameType; limit?: number; before?: number; after?: number; has?: MatchHas; mode?: string; replay?: MatchReplay } = {}) =>
request<MatchSummary[]>(`/api/matches${qs(o)}`),
/** 경기 탭 모드 필터 목록 (v1.11.0 앱부터, 예전 앱은 404) */
matchModes: (game?: GameType) => request<{ game: GameType; mode: string; count: number }[]>(`/api/matches/modes${qs({ game })}`),
match: (id: string) => request<MatchDetail>(`/api/matches/${encodeURIComponent(id)}`),
/** 발로란트 리플레이(.vrf)에서 뽑은 재생 데이터. 없으면 404 replay_not_found, 게임 PC 가 변환 중이면 202 { status: 'converting' } */
// fresh: 새로고침 때는 브라우저 캐시를 거치지 않는다 (방금 내려받은 리플레이가 보이게)
replay: (id: string, fresh = false) =>
request<ReplayFile | { status: 'converting' }>(`/api/matches/${encodeURIComponent(id)}/replay`, fresh ? { cache: 'no-cache' } : {}),
culpritMatches: (o: { game?: GameType; limit?: number } = {}) => request<CulpritMatchItem[]>(`/api/culprit/matches${qs(o)}`),
culpritMatch: (id: string) => request<CulpritMatchInfo>(`/api/culprit/matches/${encodeURIComponent(id)}`),
culpritBudget: () => request<CulpritBudget>('/api/culprit/budget'),
@@ -191,6 +235,14 @@ export const api = {
utteranceInfo: (id: string) => request<UtteranceInfo>(`/api/utterances/${encodeURIComponent(id)}/info`),
correct: (id: string, text: string) =>
request<UtteranceItem>(`/api/utterances/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ text }) }),
/** 발화 지우기 (v1.4.0). noise = 잡음이라 삭제 (같은 문장을 다음부터 잡음으로) */
deleteUtterance: (id: string, noise: boolean) =>
request<{ ok: true; learned: string | null }>(`/api/utterances/${encodeURIComponent(id)}/delete`, { method: 'POST', body: JSON.stringify({ noise }) }),
/** Riot 경기 기록 가져오기 취소 (v1.9.1). 받은 경기는 남고 resumeAt 에 이어서 한다 */
cancelHistory: (game?: GameType) =>
request<{ ok: true; cancelled: GameType[]; resumeAt: number | null }>('/api/games/history/cancel', { method: 'POST', body: JSON.stringify({ game }) }),
noisePhrases: () => request<{ phrases: NoisePhrase[] }>('/api/noise-phrases'),
deleteNoisePhrase: (id: number) => request<{ ok: true }>(`/api/noise-phrases/${id}`, { method: 'DELETE' }),
};
export interface DictionaryEntry {

View File

@@ -0,0 +1,230 @@
/**
* 발로란트 조준점: 리플레이의 선수 조준점(변환기 players[].crosshair) · 사이트 전체 조준점 설정 · 조준점 코드 · 그리기.
* 크기는 발로란트 설정 값 그대로 화면 픽셀로 그린다.
*/
export interface CrossLines {
on: boolean;
length: number;
/** 세로 길이 (따로 쓰지 않으면 length 와 같다) */
vLength: number;
thickness: number;
offset: number;
opacity: number;
moveError: boolean;
fireError: boolean;
moveScale: number;
fireScale: number;
}
export interface CrossSet {
/** 보이는 색 #rrggbb */
color: string;
outline: boolean;
outlineThickness: number;
outlineOpacity: number;
dot: boolean;
dotSize: number;
dotOpacity: number;
inner: CrossLines;
outer: CrossLines;
}
export interface SniperDot {
color: string;
dot: boolean;
dotSize: number;
dotOpacity: number;
}
export interface CrosshairProfile {
primary: CrossSet;
ads: CrossSet;
sniper: SniperDot;
/** 정조준에도 주 조준점 */
adsFromPrimary: boolean;
advanced: boolean;
}
/** 리플레이 기록: t(ms) 부터 이 설정 */
export interface CrosshairAt extends CrosshairProfile {
t: number;
name: string;
}
/** 발로란트 색 목록 (조준점 코드 c 번호 순, 8 = 사용자 지정) */
export const CROSS_COLORS: { name: string; hex: string }[] = [
{ name: '흰색', hex: '#ffffff' },
{ name: '초록색', hex: '#00ff00' },
{ name: '연두색', hex: '#7fff00' },
{ name: '황록색', hex: '#dfff00' },
{ name: '노란색', hex: '#ffff00' },
{ name: '청록색', hex: '#00ffff' },
{ name: '분홍색', hex: '#ff00ff' },
{ name: '빨간색', hex: '#ff0000' },
];
const INNER: CrossLines = { on: true, length: 6, vLength: 6, thickness: 2, offset: 3, opacity: 0.8, moveError: false, fireError: true, moveScale: 1, fireScale: 1 };
const OUTER: CrossLines = { on: true, length: 2, vLength: 2, thickness: 2, offset: 10, opacity: 0.35, moveError: true, fireError: true, moveScale: 1, fireScale: 1 };
const SET: CrossSet = { color: '#ffffff', outline: true, outlineThickness: 1, outlineOpacity: 0.5, dot: false, dotSize: 2, dotOpacity: 1, inner: INNER, outer: OUTER };
/** 발로란트 기본 조준점 */
export const DEFAULT_CROSSHAIR: CrosshairProfile = {
primary: SET,
ads: SET,
sniper: { color: '#ff0000', dot: true, dotSize: 1, dotOpacity: 0.75 },
adsFromPrimary: true,
advanced: false,
};
/** t 시점 선수 조준점 (그 전이면 첫 기록, 기록이 없으면 null) */
export function crosshairAt(list: CrosshairAt[] | null | undefined, t: number): CrosshairAt | null {
if (!list?.length) return null;
let c = list[0];
for (const x of list) {
if (x.t > t) break;
c = x;
}
return c;
}
/** 지금 쓸 조준점 묶음: 정조준(저격총 아님) 중이고 정조준 조준점을 따로 쓰면 ads */
export function crossFor(p: CrosshairProfile, ads: boolean): CrossSet {
return ads && p.advanced && !p.adsFromPrimary ? p.ads : p.primary;
}
const num = (v: string | undefined, d: number) => {
const n = v == null ? NaN : Number(v);
return Number.isFinite(n) ? n : d;
};
/**
* 발로란트 조준점 코드 (설정 → 조준점 → 프로필 내보내기, 예: 0;P;c;5;h;0;0l;4;0o;2;0a;1;0f;0;1b;0) → 설정.
* 코드에 없는 값은 발로란트 기본값. 형식이 아니면 null
*/
export function parseCrosshairCode(code: string): CrosshairProfile | null {
const tok = code.trim().split(';').map((s) => s.trim());
if (tok.length < 1 || !/^\d+$/.test(tok[0])) return null;
const sec: Record<'G' | 'P' | 'A' | 'S', Record<string, string>> = { G: {}, P: {}, A: {}, S: {} };
let cur: keyof typeof sec = 'G';
for (let i = 1; i < tok.length; i++) {
const k = tok[i];
if (k === 'P' || k === 'A' || k === 'S') {
cur = k;
continue;
}
if (!k) continue;
if (i + 1 >= tok.length) return null;
sec[cur][k] = tok[++i];
}
const color = (s: Record<string, string>, d: string) => {
const c = num(s.c, -1);
if ((c === 8 || s.b === '1') && /^[0-9a-fA-F]{6}/.test(s.u ?? '')) return `#${s.u.slice(0, 6).toLowerCase()}`;
return CROSS_COLORS[c]?.hex ?? d;
};
const lines = (s: Record<string, string>, p: '0' | '1', d: CrossLines): CrossLines => {
const length = num(s[p + 'l'], d.length);
return {
on: s[p + 'b'] !== '0' && (s[p + 'b'] === '1' || d.on),
length,
vLength: s[p + 'g'] === '1' ? num(s[p + 'v'], length) : length,
thickness: num(s[p + 't'], d.thickness),
offset: num(s[p + 'o'], d.offset),
opacity: num(s[p + 'a'], d.opacity),
moveError: s[p + 'm'] != null ? s[p + 'm'] === '1' : d.moveError,
fireError: s[p + 'f'] != null ? s[p + 'f'] === '1' : d.fireError,
moveScale: num(s[p + 's'], d.moveScale),
fireScale: num(s[p + 'e'], d.fireScale),
};
};
const set = (s: Record<string, string>): CrossSet => ({
color: color(s, SET.color),
outline: s.h != null ? s.h === '1' : SET.outline,
outlineThickness: num(s.t, SET.outlineThickness),
outlineOpacity: num(s.o, SET.outlineOpacity),
dot: s.d != null ? s.d === '1' : SET.dot,
dotSize: num(s.z, SET.dotSize),
dotOpacity: num(s.a, SET.dotOpacity),
inner: lines(s, '0', INNER),
outer: lines(s, '1', OUTER),
});
const S = sec.S;
const sd = DEFAULT_CROSSHAIR.sniper;
return {
primary: set(sec.P),
ads: set(sec.A),
sniper: {
color: color(S, sd.color),
dot: S.d != null ? S.d === '1' : sd.dot,
dotSize: num(S.s, sd.dotSize),
dotOpacity: num(S.o, sd.dotOpacity),
},
adsFromPrimary: sec.G.p !== '0',
advanced: sec.G.s === '1',
};
}
/** 사격 · 이동으로 벌어지는 정도 (픽셀): fire 0..1 (막 쏨 = 1), move 0..1 */
export interface Spread {
fire: number;
move: number;
}
const FIRE_PX = 6;
const MOVE_PX = 4;
function rgba(hex: string, a: number) {
const n = parseInt(hex.slice(1, 7), 16);
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${Math.max(0, Math.min(1, a))})`;
}
/** (cx, cy) 를 가운데로 조준점을 그린다. 크기는 CSS 픽셀 (ctx 는 devicePixelRatio 로 미리 늘려 둔다) */
export function drawCrosshair(ctx: CanvasRenderingContext2D, cx: number, cy: number, s: CrossSet, spread: Spread = { fire: 0, move: 0 }) {
const rects: [number, number, number, number, number][] = [];
const line = (l: CrossLines) => {
if (!l.on || l.opacity <= 0 || l.thickness <= 0) return;
const gap = l.offset + (l.fireError ? spread.fire * FIRE_PX * l.fireScale : 0) + (l.moveError ? spread.move * MOVE_PX * l.moveScale : 0);
const th = l.thickness;
if (l.length > 0) {
rects.push([cx - gap - l.length, cy - th / 2, l.length, th, l.opacity]);
rects.push([cx + gap, cy - th / 2, l.length, th, l.opacity]);
}
if (l.vLength > 0) {
rects.push([cx - th / 2, cy - gap - l.vLength, th, l.vLength, l.opacity]);
rects.push([cx - th / 2, cy + gap, th, l.vLength, l.opacity]);
}
};
line(s.outer);
line(s.inner);
if (s.dot && s.dotSize > 0 && s.dotOpacity > 0) rects.push([cx - s.dotSize / 2, cy - s.dotSize / 2, s.dotSize, s.dotSize, s.dotOpacity]);
// 픽셀 경계에 맞춘다 (두께 1 · 2 선이 흐려지지 않게)
const px = rects.map(([x, y, w, h, a]) => [Math.round(x), Math.round(y), Math.max(1, Math.round(w)), Math.max(1, Math.round(h)), a] as const);
if (s.outline && s.outlineThickness > 0 && s.outlineOpacity > 0) {
const o = s.outlineThickness;
ctx.fillStyle = rgba('#000000', s.outlineOpacity);
for (const [x, y, w, h] of px) ctx.fillRect(x - o, y - o, w + o * 2, h + o * 2);
}
for (const [x, y, w, h, a] of px) {
ctx.fillStyle = rgba(s.color, a);
ctx.fillRect(x, y, w, h);
}
}
/** 저격총 조준경 가운데 점 */
export function drawSniperDot(ctx: CanvasRenderingContext2D, cx: number, cy: number, d: SniperDot) {
if (!d.dot || d.dotSize <= 0 || d.dotOpacity <= 0) return;
ctx.fillStyle = rgba(d.color, d.dotOpacity);
ctx.beginPath();
ctx.arc(cx, cy, Math.max(1, d.dotSize * 2), 0, Math.PI * 2);
ctx.fill();
}
/** 캔버스를 화면 크기 · devicePixelRatio 에 맞추고 지운 뒤 가운데 좌표 */
export function prepCanvas(c: HTMLCanvasElement): { ctx: CanvasRenderingContext2D; cx: number; cy: number } | null {
const ctx = c.getContext('2d');
if (!ctx) return null;
const dpr = window.devicePixelRatio || 1;
const w = c.clientWidth;
const h = c.clientHeight;
if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) {
c.width = Math.round(w * dpr);
c.height = Math.round(h * dpr);
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
return { ctx, cx: Math.floor(w / 2), cy: Math.floor(h / 2) };
}

View File

@@ -0,0 +1,301 @@
import { isDead, type ReplayFile } from './replay';
/**
* 자동 관전 (자동 시점): 리플레이 기록(맞은 것 · 킬 · 사격 · 설치/해체)과 그때 나눈 대화로 장면을 나눈다.
* - 교전: 킬마다 이긴 선수(죽인 선수) 1인칭. 교전이 시작되기 FIGHT_LEAD 전에 미리 넘어간다.
* 교전 직전에 우리 팀이 말을 했으면(콜) 그 말이 시작될 때부터 보여 준다 (최대 CALL_LEAD).
* - 스파이크 설치 · 해체: 하는 선수 1인칭
* - 혼자 남은 선수(1 대 N): 그 선수 1인칭
* - 교전이 없을 때: 살아 있는 선수 모두가 보이게 위에서 (전략 보기)
* 시각(t)만으로 정해지므로 되감기 · 건너뛰기 · 배속에도 같은 장면이 나온다.
*/
export type ShotKind = 'fight' | 'skirmish' | 'plant' | 'defuse' | 'clutch' | 'buy' | 'overview' | 'post';
export interface Shot {
t0: number;
t1: number;
kind: ShotKind;
/** 1인칭으로 볼 선수 (리플레이 선수 번호). null 이면 위에서 */
pov: number | null;
/** 이 장면에서 pov 가 낸 킬 수 (교전) */
kills?: number;
/** 교전 직전 콜 (대화 글) */
call?: string;
}
export interface Talk {
/** 리플레이 시각 (ms) */
t0: number;
t1: number;
text: string;
}
export interface DirectorInput {
replay: ReplayFile;
/** 선수별 우리 팀 여부 */
ally: boolean[];
/** 우리 팀 대화 (녹음된 사람은 모두 우리 팀) */
talks: Talk[];
}
/** 교전 시작 전에 미리 넘어가는 시간 */
export const FIGHT_LEAD = 2500;
/** 교전 직전 콜을 찾는 범위 · 콜부터 보여 줄 때 가장 이른 시각 (교전 시작 기준) */
export const CALL_LEAD = 6000;
/** 킬 뒤에 그 선수를 더 보여 주는 시간 */
const FIGHT_TAIL = 1200;
/** 같은 교전으로 보는 사격 간격 · 킬 전에 교전 시작을 찾는 범위 */
const BURST_GAP = 1500;
const DUEL_BACK = 8000;
/** 다음 킬로 넘어갈 때 앞 킬 뒤로 최소 이만큼은 보여 준다 */
const AFTER_KILL = 500;
/** 넘어간 뒤 킬까지 이보다 짧으면 넘어가지 않는다 (무슨 일인지 볼 틈이 없음) */
const MIN_ORIENT = 700;
/** 1인칭 장면 사이 위에서 보기가 이보다 짧으면 앞 장면을 늘린다 · 이보다 짧은 1인칭은 앞 장면에 붙인다 */
const MIN_OVERVIEW = 2000;
const MIN_POV = 900;
type Seg = Shot;
export function buildDirector({ replay: r, ally, talks }: DirectorInput): Shot[] {
const end = r.durationMs;
const team = (p: number) => (p >= 0 ? (ally[p] ? 0 : 1) : -1);
const rounds = r.rounds.map((rd, i) => ({ ...rd, next: r.rounds[i + 1]?.buy ?? end }));
const roundOf = (t: number) => {
let cur = rounds[0];
for (const rd of rounds) if (rd.buy <= t) cur = rd;
return cur;
};
const roundStart = (t: number) => roundOf(t)?.buy ?? 0;
const hits = (r.hits ?? []).filter((h) => h[1] >= 0 && h[2] >= 0 && h[1] !== h[2] && team(h[1]) !== team(h[2])).sort((a, b) => a[0] - b[0]);
const shotsBy: number[][] = r.players.map(() => []);
for (const s of r.shots) if (s[1] >= 0) shotsBy[s[1]]?.push(s[0]);
for (const a of shotsBy) a.sort((x, y) => x - y);
const talksSorted = [...talks].filter((x) => x.text?.trim()).sort((a, b) => a.t0 - b.t0);
// ── 교전 (킬마다) ─────────────────────────────
const duels: { start: number; kill: number; pov: number; call?: string; victim: number }[] = [];
const kills = [...r.kills].sort((a, b) => a[0] - b[0]);
for (const [tk, k, v] of kills) {
if (k < 0 || v < 0 || k === v || team(k) === team(v)) continue;
const floor = Math.max(roundStart(tk), tk - DUEL_BACK);
// 둘 사이 첫 맞은 기록
let start = tk;
for (const h of hits) {
if (h[0] < floor) continue;
if (h[0] > tk) break;
if ((h[1] === k && h[2] === v) || (h[1] === v && h[2] === k)) {
start = Math.min(start, h[0]);
break;
}
}
// 죽인 선수의 이어진 사격 (킬에서 거슬러 올라가며 간격 BURST_GAP 안)
const st = shotsBy[k] ?? [];
let j = upper(st, tk) - 1;
let burst = tk;
while (j >= 0 && st[j] >= floor && burst - st[j] <= BURST_GAP) burst = st[j--];
start = Math.min(start, burst, tk - 1000);
let from = Math.max(floor, start - FIGHT_LEAD);
// 교전 직전 콜: 우리 팀이 낀 교전이면, 교전 시작 CALL_LEAD 안에 시작한 말부터
let call: string | undefined;
if (ally[k] || ally[v]) {
const lo = start - CALL_LEAD;
for (const x of talksSorted) {
if (x.t0 > start) break;
if (x.t0 >= lo && x.t1 >= lo) {
call = x.text.trim();
from = Math.max(roundStart(tk), Math.min(from, x.t0 - 300));
break;
}
}
}
duels.push({ start: from, kill: tk, pov: k, call, victim: v });
}
const segs: Seg[] = [];
for (const d of duels) {
const prev = segs[segs.length - 1];
if (prev && prev.kind === 'fight' && prev.pov === d.pov && d.start <= prev.t1 + MIN_OVERVIEW) {
// 같은 선수가 이어서 죽였다 (멀티킬): 그대로 이어 본다
prev.t1 = Math.max(prev.t1, d.kill + FIGHT_TAIL);
prev.kills = (prev.kills ?? 1) + 1;
prev.call ??= d.call;
continue;
}
let from = d.start;
if (prev && from < prev.t1) {
// 앞 장면과 겹친다: 앞 킬을 보여 준 뒤 넘어간다. 볼 틈이 없으면 넘어가지 않는다
const prevKill = prev.t1 - FIGHT_TAIL;
from = Math.max(from, prevKill + AFTER_KILL);
if (d.kill - from < MIN_ORIENT) continue;
prev.t1 = from;
}
segs.push({ t0: from, t1: Math.min(end, d.kill + FIGHT_TAIL), kind: 'fight', pov: d.pov, kills: 1, call: d.call });
}
// ── 그 밖의 장면: 빈 곳에만 채운다 (설치 · 해체 > 킬 없는 교전 > 혼자 남은 선수) ─────────
const fill: Seg[] = [];
for (const [a0, a1, p, ak] of r.actions ?? []) {
const kind = r.actionKinds?.[ak];
if (kind !== 'Plant' && kind !== 'Defuse') continue;
fill.push({ t0: a0 - 800, t1: (a1 >= a0 ? a1 : a0 + 4000) + 800, kind: kind === 'Plant' ? 'plant' : 'defuse', pov: p });
}
// 킬 없는 교전: 서로 맞힌 기록 묶음 (간격 2.5초 안). 가장 많이 맞힌 선수
const covered = (t: number) => segs.some((s) => s.t0 <= t && t <= s.t1);
for (let i = 0; i < hits.length; ) {
let j = i;
while (j + 1 < hits.length && hits[j + 1][0] - hits[j][0] <= 2500 && roundOf(hits[j + 1][0]) === roundOf(hits[i][0])) j++;
const group = hits.slice(i, j + 1);
i = j + 1;
// 라운드가 끝난 뒤 쏜 것은 교전이 아니다
const rd = roundOf(group[0][0]);
if (rd && rd.end >= 0 && group[0][0] >= rd.end) continue;
if (group.some((h) => covered(h[0]))) continue;
const by = new Map<number, number>();
for (const h of group) by.set(h[1], (by.get(h[1]) ?? 0) + 1);
const last = group[group.length - 1][0];
const best = [...by.entries()].filter(([p]) => !isDead(r, p, last)).sort((a, b) => b[1] - a[1])[0];
if (!best) continue;
fill.push({ t0: Math.max(roundStart(group[0][0]), group[0][0] - FIGHT_LEAD), t1: last + 1000, kind: 'skirmish', pov: best[0] });
}
// 혼자 남은 선수: 킬 뒤 한 팀이 1명이고 상대가 1명 이상이면, 라운드가 끝날 때까지 (그 선수가 죽으면 거기까지)
for (const rd of rounds) {
if (rd.combat < 0) continue;
const stop = rd.end >= 0 ? rd.end : rd.next;
let clutch: { p: number; from: number } | null = null;
for (const [tk] of kills) {
if (tk < rd.combat || tk >= stop) continue;
const alive = [0, 1].map((tm) => r.players.map((_, p) => p).filter((p) => team(p) === tm && !isDead(r, p, tk + 1)));
if (clutch && isDead(r, clutch.p, tk + 1)) {
fill.push({ t0: clutch.from, t1: tk + FIGHT_TAIL, kind: 'clutch', pov: clutch.p });
clutch = null;
}
if (!clutch) {
for (const tm of [0, 1]) {
if (alive[tm].length === 1 && alive[1 - tm].length >= 1) {
clutch = { p: alive[tm][0], from: tk + FIGHT_TAIL };
break;
}
}
}
}
if (clutch) fill.push({ t0: clutch.from, t1: stop, kind: 'clutch', pov: clutch.p });
}
let out = segs;
for (const f of fill) out = paint(out, f);
// ── 나머지: 위에서 (구매 · 전략 보기 · 라운드 끝) ─────────
for (const rd of rounds) {
const combat = rd.combat >= 0 ? rd.combat : rd.buy;
const stop = rd.end >= 0 ? rd.end : rd.next;
out = paint(out, { t0: rd.buy, t1: combat, kind: 'buy', pov: null });
out = paint(out, { t0: combat, t1: stop, kind: 'overview', pov: null });
out = paint(out, { t0: stop, t1: rd.next, kind: 'post', pov: null });
}
out = paint(out, { t0: 0, t1: end, kind: 'overview', pov: null });
return tidy(out.filter((s) => s.t1 > s.t0).map((s) => ({ ...s, t0: Math.max(0, s.t0), t1: Math.min(end, s.t1) })));
}
/** 빈 곳에만 칠한다 (segs 는 시간 순 · 겹치지 않음) */
function paint(segs: Seg[], c: Seg): Seg[] {
if (c.t1 <= c.t0) return segs;
const out: Seg[] = [];
let cur = c.t0;
for (const s of segs) {
if (s.t0 > cur && cur < c.t1) out.push({ ...c, t0: cur, t1: Math.min(s.t0, c.t1) });
out.push(s);
cur = Math.max(cur, s.t1);
}
if (cur < c.t1) out.push({ ...c, t0: cur, t1: c.t1 });
return out.sort((a, b) => a.t0 - b.t0);
}
/** 깜빡이지 않게: 1인칭 사이 짧은 위에서 보기는 앞 장면을 늘리고, 짧은 1인칭은 앞 장면에 붙이고, 같은 장면은 합친다 */
function tidy(segs: Seg[]): Shot[] {
const out: Seg[] = [];
for (let i = 0; i < segs.length; i++) {
const s = { ...segs[i] };
const prev = out[out.length - 1];
const next = segs[i + 1];
const len = s.t1 - s.t0;
if (prev && s.pov == null && prev.pov != null && next?.pov != null && len < MIN_OVERVIEW) {
prev.t1 = s.t1;
continue;
}
if (prev && s.pov != null && len < MIN_POV) {
prev.t1 = s.t1;
continue;
}
if (prev && prev.kind === s.kind && prev.pov === s.pov && prev.t1 >= s.t0) {
prev.t1 = s.t1;
prev.kills = (prev.kills ?? 0) + (s.kills ?? 0) || undefined;
prev.call ??= s.call;
continue;
}
out.push(s);
}
return out;
}
/** t 시점 장면 (번호). 없으면 -1 */
export function shotIndexAt(shots: Shot[], t: number): number {
let lo = 0;
let hi = shots.length - 1;
if (hi < 0 || t < shots[0].t0) return shots.length ? 0 : -1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (shots[mid].t0 <= t) lo = mid;
else hi = mid - 1;
}
return lo;
}
function upper(a: number[], t: number) {
let lo = 0;
let hi = a.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (a[mid] <= t) lo = mid + 1;
else hi = mid;
}
return lo;
}
export const SHOT_LABEL: Record<ShotKind, string> = {
fight: '교전',
skirmish: '교전 (킬 없음)',
plant: '스파이크 설치',
defuse: '스파이크 해체',
clutch: '혼자 남음',
buy: '구매 단계 · 전체 보기',
overview: '전략 보기',
post: '라운드 끝',
};
type V3 = [number, number, number];
const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
const unit = (a: V3): V3 => {
const l = Math.hypot(...a) || 1;
return [a[0] / l, a[1] / l, a[2] / l];
};
/**
* 전략 보기 카메라 거리: 카메라를 target + dir × 거리 에 두고 target 을 볼 때 모든 점이 화면(가장자리 margin 남김) 안에 들어오는 가장 짧은 거리.
* 카메라 공간에서 점의 깊이 = dot(q, f) + 거리 (f = -dir), 가로 · 세로 = dot(q, 오른쪽) · dot(q, 위). |가로| ≤ tan(가로 시야/2) × 깊이 를 거리로 푼다.
* dir 은 위쪽(y) 성분이 있어야 한다 (내려다보기)
*/
export function fitDistance(points: V3[], target: V3, dir: V3, fovDeg: number, aspect: number, margin = 0.85): number {
const d = unit(dir);
const f: V3 = [-d[0], -d[1], -d[2]];
const right = unit(cross(f, [0, 1, 0]));
const up = cross(right, f);
const tv = Math.tan(((fovDeg / 2) * Math.PI) / 180) * margin;
const th = tv * aspect;
let need = 0;
for (const p of points) {
const q: V3 = [p[0] - target[0], p[1] - target[1], p[2] - target[2]];
const z = dot(q, f);
need = Math.max(need, Math.abs(dot(q, right)) / th - z, Math.abs(dot(q, up)) / tv - z);
}
return need;
}

232
site/web/src/lib/map3d.ts Normal file
View File

@@ -0,0 +1,232 @@
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
/**
* 발로란트 맵 3D 모양 (사이트 서버 /site/maps3d, 로그인 필요).
* glb 의 위치는 UE 월드 좌표(cm) 그대로다. 리플레이 선수 x,y,z 와 같은 좌표라 같은 변환으로 옮기면 겹친다.
*/
interface Index {
dir: string | null;
version: string | null;
maps: Record<string, { code: string; file: string; bytes: number; triangles: number }>;
/** 요원 몸 (리플레이 캐릭터 클래스 → glb), 무기 (equipKinds 이름 → glb). 옛 index 에는 없다 */
agents?: Record<string, { code: string; file: string; bytes: number }>;
weapons?: Record<string, { file: string; bytes: number }>;
/** 모든 요원 공용 애니메이션 (앉기 · 점프 · 무기별 자세 · 재장전 · 죽음 …). 옛 index 에는 없다 */
anims?: { file: string; bytes: number } | null;
/** 스킬 모델 · 파티클 · 텍스처 (abilities.json). 옛 index 에는 없다 */
abilities?: { file: string; bytes: number } | null;
}
let indexP: Promise<Index | null> | null = null;
export function loadIndex(): Promise<Index | null> {
indexP ??= fetch('/site/maps3d', { credentials: 'same-origin' })
.then((r) => (r.ok ? (r.json() as Promise<Index>) : null))
.catch(() => null)
.then((d) => {
if (!d) indexP = null; // 실패하면 다음에 다시
return d;
});
return indexP;
}
export interface Map3dInfo {
url: string;
bytes: number;
triangles: number;
version: string | null;
}
/** 경기 맵 경로(/Game/Maps/Ascent/Ascent)의 3D 파일. 없으면 null. 폴더 대소문자는 게임 파일과 다를 수 있어 무시한다 */
export async function findMap3d(mapUrl: string): Promise<Map3dInfo | null> {
const idx = await loadIndex();
if (!idx?.dir || !mapUrl) return null;
const key = mapUrl.toLowerCase();
const hit = Object.entries(idx.maps).find(([k]) => k.toLowerCase() === key)?.[1];
return hit ? { url: `/site/maps3d/${encodeURIComponent(idx.dir)}/${encodeURIComponent(hit.file)}`, bytes: hit.bytes, triangles: hit.triangles, version: idx.version } : null;
}
/**
* glb 를 받아 장면 하나로. onProgress: 0~1
* 재질이 든 glb(텍스처 · 색)는 그 재질에 천장 자르기만 붙이고, 재질이 없는 옛 glb 는 fallback(높이 색) 재질을 쓴다.
* 두 층 재질(extras.blend = {texture, tint})은 정점 색 R 로 A 층(기본 텍스처) · B 층을 섞는다.
* 구운 조명(extras.lightmap = {k}): 추출기가 aoMap(irr) · emissiveMap(sh) 자리에 TEXCOORD_1 로 넣어 둔 아틀라스로
* 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)) (N 은 UE 월드 법선, tools/map-extract/src/Lightmaps.cs). 장면 조명은 쓰지 않는다.
*/
export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.Material, onProgress?: (p: number) => void): Promise<THREE.Object3D> {
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
return new Promise((resolve, reject) => {
loader.load(
url,
(gltf) => {
const hasMats = !!gltf.parser.json.materials?.length;
const fb = hasMats ? null : fallback();
const pending: Promise<unknown>[] = [];
const done = new Map<THREE.Material, THREE.Material>();
gltf.scene.traverse((o) => {
const mesh = o as THREE.Mesh;
if (!mesh.isMesh) return;
mesh.frustumCulled = false;
if (fb) {
mesh.material = fb;
return;
}
const src = mesh.material as THREE.MeshStandardMaterial;
const blend = src.userData?.blend as { texture?: number; tint?: number[] } | undefined;
const lm = src.userData?.lightmap as { k?: number } | undefined;
// 정점 색은 색칠이 아니라 두 층 섞는 비율이다
const col = mesh.geometry.getAttribute('color');
if (col) {
mesh.geometry.setAttribute('blendCol', col);
mesh.geometry.deleteAttribute('color');
}
let mat = done.get(src);
if (!mat) {
const m = src.clone() as THREE.MeshStandardMaterial;
m.vertexColors = false;
// 게임(UE) 좌표를 그대로 쓰고 행렬로 옮기므로 면 방향이 뒤집혀 보일 수 있다 → 양면
m.side = THREE.DoubleSide;
m.clippingPlanes = [clip];
m.clipShadows = true;
m.roughness = 1;
m.metalness = 0;
if (m.map) m.map.anisotropy = 4;
if (m.transparent) m.depthWrite = false;
const shader: ShaderParts = {};
if (lm?.k && m.aoMap && m.emissiveMap) {
shader.lightmap = { k: lm.k };
for (const t of [m.aoMap, m.emissiveMap]) {
t.colorSpace = THREE.NoColorSpace; // 셰이더에서 직접 푼다
t.anisotropy = 4;
}
} else {
// 조명 없는 재질에 붙은 조명 텍스처는 쓰지 않는다
m.aoMap = null;
m.emissiveMap = null;
}
const ready = blend ? blendLayer(gltf.parser, blend).then((b) => void (shader.blend = b)) : Promise.resolve();
pending.push(ready.then(() => installShader(m, shader)));
done.set(src, m);
mat = m;
}
mesh.material = mat;
});
void Promise.all(pending).then(() => resolve(gltf.scene), reject);
},
(e) => onProgress?.(e.total ? e.loaded / e.total : 0),
reject,
);
});
}
interface ShaderParts {
blend?: { texB: THREE.Texture | null; tintB: THREE.Color };
lightmap?: { k: number };
}
/** B 층 텍스처 · 색 (셰이더에서 정점 색 R 로 섞는다) */
async function blendLayer(parser: { getDependency: (type: string, i: number) => Promise<unknown> }, b: { texture?: number; tint?: number[] }) {
let texB: THREE.Texture | null = null;
if (b.texture != null) {
// 텍스처 하나를 못 읽어도 맵 전체를 버리지 않고 B 층 색만 쓴다
texB = (await parser.getDependency('texture', b.texture).catch(() => null)) as THREE.Texture | null;
if (texB) {
texB.colorSpace = THREE.SRGBColorSpace;
texB.anisotropy = 4;
}
}
const tintB = new THREE.Color().setRGB(b.tint?.[0] ?? 1, b.tint?.[1] ?? 1, b.tint?.[2] ?? 1, THREE.SRGBColorSpace);
return { texB, tintB };
}
/** 두 층 섞기 · 구운 조명을 셰이더에 넣는다 */
function installShader(m: THREE.MeshStandardMaterial, parts: ShaderParts) {
const { blend, lightmap } = parts;
if (!blend && !lightmap) return;
const md = m as unknown as { defines?: Record<string, string> };
md.defines = { ...(md.defines ?? {}) };
if (blend) {
md.defines.GVR_BLEND = '';
if (blend.texB) md.defines.GVR_BLEND_MAP = '';
}
if (lightmap) md.defines.GVR_LIGHTMAP = '';
// 같은 프로그램을 나눠 쓰도록 (uniform 값만 재질마다 다름)
m.customProgramCacheKey = () => `gvr:${blend ? (blend.texB ? 'bm' : 'b') : ''}:${lightmap ? 'l' : ''}`;
m.onBeforeCompile = (sh) => {
if (blend) {
sh.uniforms.mapB = { value: blend.texB };
sh.uniforms.tintB = { value: blend.tintB };
sh.vertexShader = sh.vertexShader
.replace('#include <common>', '#include <common>\nattribute vec4 blendCol;\nvarying float vBlend;\nvarying vec2 vUvB;')
.replace('#include <uv_vertex>', '#include <uv_vertex>\nvBlend = blendCol.r;\nvUvB = uv;');
sh.fragmentShader = sh.fragmentShader
.replace('#include <common>', '#include <common>\nuniform sampler2D mapB;\nuniform vec3 tintB;\nvarying float vBlend;\nvarying vec2 vUvB;')
.replace(
'#include <map_fragment>',
`#include <map_fragment>
#ifdef GVR_BLEND_MAP
vec3 layerB = texture2D(mapB, vUvB).rgb * tintB;
#else
vec3 layerB = tintB;
#endif
diffuseColor.rgb = mix(layerB, diffuseColor.rgb, vBlend);`,
);
}
if (lightmap) {
sh.uniforms.lmK = { value: lightmap.k };
sh.vertexShader = sh.vertexShader
.replace('#include <common>', '#include <common>\nvarying vec3 vUeN;')
.replace('#include <beginnormal_vertex>', '#include <beginnormal_vertex>\nvUeN = objectNormal;');
sh.fragmentShader = sh.fragmentShader
.replace('#include <common>', '#include <common>\nuniform float lmK;\nvarying vec3 vUeN;')
.replace(
'#include <opaque_fragment>',
`{
// 구운 조명 (UE HQ 라이트맵을 추출기가 풀어 둔 값): irr 는 sRGB, sh 는 ±2 → 0~1
vec3 lmIrr = texture2D(aoMap, vAoMapUv).rgb;
lmIrr = mix(lmIrr / 12.92, pow((lmIrr + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), lmIrr));
vec3 lmSh = texture2D(emissiveMap, vEmissiveMapUv).rgb * 4.0 - 2.0;
vec3 n = normalize(vUeN);
float lmDir = max(0.0, 1.0 + dot(lmSh, n.yzx));
vec3 lit = diffuseColor.rgb * lmIrr * (lmK * lmDir);
// 밝은 곳이 하얗게 날아가지 않게 살짝 누른다
outgoingLight = lit / (1.0 + max(lit - 0.8, 0.0));
}
#include <opaque_fragment>`,
);
}
};
m.needsUpdate = true;
}
/** UE 월드 좌표(cm) → 3D 리플레이 화면 좌표. ReplayViewer 의 toWorld 와 같은 식을 행렬로 */
export function worldMatrix(T: { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }, S: number, zBase: number, vex: number) {
const h = Math.abs(T.xMultiplier) * S * vex;
return new THREE.Matrix4().set(
0, T.xMultiplier * S, 0, (T.xScalarToAdd - 0.5) * S,
0, 0, h, -zBase * h,
T.yMultiplier * S, 0, 0, (T.yScalarToAdd - 0.5) * S,
0, 0, 0, 1,
);
}
/** 높이에 따라 색이 바뀌는 맵 재질 (낮은 곳 푸른 회색 → 높은 곳 밝은 베이지). 천장 자르기 평면을 쓴다 */
export function mapMaterial(clip: THREE.Plane, yRange: { lo: number; hi: number }) {
const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.92, metalness: 0, flatShading: true, side: THREE.DoubleSide, clippingPlanes: [clip], clipShadows: true });
mat.onBeforeCompile = (sh) => {
sh.uniforms.uLo = { value: yRange.lo };
sh.uniforms.uHi = { value: yRange.hi };
sh.vertexShader = sh.vertexShader
.replace('#include <common>', '#include <common>\nvarying float vH;')
.replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvH = (modelMatrix * vec4(transformed, 1.0)).y;');
sh.fragmentShader = sh.fragmentShader
.replace('#include <common>', '#include <common>\nvarying float vH;\nuniform float uLo;\nuniform float uHi;')
.replace(
'vec4 diffuseColor = vec4( diffuse, opacity );',
'float hN = clamp((vH - uLo) / max(uHi - uLo, 0.001), 0.0, 1.0);\nvec4 diffuseColor = vec4(mix(vec3(0.20, 0.25, 0.32), vec3(0.62, 0.57, 0.48), hN), opacity);',
);
};
return mat;
}

300
site/web/src/lib/replay.ts Normal file
View File

@@ -0,0 +1,300 @@
import type { KillData, MatchDetail } from '@gvr/shared';
import type { CrosshairAt } from './crosshair';
/**
* tools/replay-extract (gvr-replay v1 · v2) 출력. t 는 리플레이 시작부터 ms, 좌표는 게임 월드 단위(cm).
* v2 는 v1 열을 그대로 두고 뒤에 열 · 필드를 더했다 (옛 JSON 은 없는 필드 → 빈 것으로 본다).
*/
export interface ReplayFile {
format: 'gvr-replay';
v: 1 | 2;
matchId: string | null;
map: string | null;
build: string | null;
/** 리플레이 녹화 시작 (서버 시계, 유닉스 ms) */
recordedAt: number;
durationMs: number;
sampleMs: number;
players: {
puuid: string | null;
character: string | null;
track: { t: number[]; x: number[]; y: number[]; z: number[]; yaw: number[]; pitch: number[]; f?: number[] };
/** 조준점 설정이 바뀐 시각마다 전체 설정 (변환기 1.8.2~, 옛 JSON 은 없다) */
crosshair?: CrosshairAt[] | null;
}[];
rounds: { num: number; buy: number; combat: number; end: number }[];
phases: [number, number][];
/** [t, killer, victim, deathAnim(v2, deathAnims 번호 · -1)] */
kills: [number, number, number, number?][];
/** 죽는 모션 이름 (TP_Core_Death_Head_Front_SM_Montage …) */
deathAnims?: string[];
/** [t, player, x, y, z, yaw, pitch] */
shots: [number, number, number, number, number, number, number][];
/** [t0, t1, kind, x, y, z, owner, yaw(v2), pitch(v2)]. 날아가는 것은 t1 = 부딪힌 시각 (v2) */
objects: [number, number, number, number, number, number, number, number?, number?][];
objectKinds: string[];
/** 움직이는 스킬 경로 (투사체 비행 · 드론 · 분신), o = objects 번호 */
objectPaths?: ObjectPath[];
/** 무기 · 스킬 상태 [t, player, equipKind, stateKind] */
states?: [number, number, number, number][];
stateKinds?: string[];
/** 맞은 것 [t, attacker, victim, ox, oy, oz, ix, iy, iz, 부위(1 머리 2 몸 3 다리), 죽였으면 1] */
hits?: number[][];
/** 스파이크 설치 [t, player, x, y, z] */
plants?: number[][];
/** 이어지는 동작 [t0, t1, player, actionKind] (Plant · Defuse · Rope) */
actions?: [number, number, number, number][];
actionKinds?: string[];
/** 들고 있는 것이 바뀐 시각 [t, player, kind, skin] (변환기 새 버전부터. 옛 리플레이 JSON 에는 없다. skin = skins 번호 · 모르면 -1, 변환기 1.10.0~) */
equips?: [number, number, number, number?][];
equipKinds?: string[];
/** 무기 스킨 (게임 데이터 에셋 경로). 줍거나 떨어뜨려도 그 총의 스킨은 처음 주인 것 (변환기 1.10.0~) */
skins?: SkinInfo[];
/** 점수판 (게임 Tab): 선수 값이 바뀔 때마다 [t, player, 크레딧, 궁극기 점수, 킬, 데스, 어시스트, 전투 점수] (모르는 값 -1, 변환기 1.10.0~) */
scoreboard?: number[][];
}
/** 무기 스킨: 스킨 · 단계 · 색상 · 총 장식 (예: /Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset) */
export interface SkinInfo {
skin: string;
level: string | null;
chroma: string | null;
charm?: string | null;
charmLevel?: string | null;
}
export interface ObjectPath {
o: number;
t: number[];
x: number[];
y: number[];
z: number[];
/** 드론 · 분신만 */
yaw: number[];
}
/** 움직임 상태 비트 (track.f) */
export const MOVE_CROUCH = 1;
export const MOVE_WALK = 2;
export const MOVE_AIR = 4;
export const MOVE_FLY = 8;
/** 표본 배열 t 에서 t 이하 마지막 번호 (없으면 -1) */
export function indexAt(T: ArrayLike<number>, t: number): number {
if (!T.length || t < T[0]) return -1;
let lo = 0;
let hi = T.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (T[mid] <= t) lo = mid;
else hi = mid - 1;
}
return lo;
}
/** t 시점 움직임 상태 비트 (옛 리플레이는 0) */
export function moveFlagsAt(tr: ReplayFile['players'][number]['track'], t: number): number {
if (!tr.f) return 0;
const i = indexAt(tr.t, t);
return i < 0 ? 0 : tr.f[i] ?? 0;
}
/** 경로 위 t 시점 위치 (앞뒤 표본을 Catmull-Rom 으로 부드럽게). 경로 밖이면 null */
export function samplePath(p: ObjectPath, t: number): { x: number; y: number; z: number; yaw: number | null; vx: number; vy: number; vz: number } | null {
const T = p.t;
if (T.length < 2 || t < T[0] || t > T[T.length - 1]) return null;
const i = Math.min(indexAt(T, t), T.length - 2);
const j = i + 1;
const h = i > 0 ? i - 1 : i;
const k2 = j < T.length - 1 ? j + 1 : j;
const span = T[j] - T[i] || 1;
const u = (t - T[i]) / span;
const cr = (a: number[]) => {
const p0 = a[h], p1 = a[i], p2 = a[j], p3 = a[k2];
const m1 = ((p2 - p0) / (T[j] - T[h] || 1)) * span;
const m2 = ((p3 - p1) / (T[k2] - T[i] || 1)) * span;
const u2 = u * u, u3 = u2 * u;
return (2 * u3 - 3 * u2 + 1) * p1 + (u3 - 2 * u2 + u) * m1 + (-2 * u3 + 3 * u2) * p2 + (u3 - u2) * m2;
};
let yaw: number | null = null;
if (p.yaw.length === T.length) {
let d = p.yaw[j] - p.yaw[i];
if (d > 180) d -= 360;
if (d < -180) d += 360;
yaw = p.yaw[i] + d * u;
}
return { x: cr(p.x), y: cr(p.y), z: cr(p.z), yaw, vx: (p.x[j] - p.x[i]) / span * 1000, vy: (p.y[j] - p.y[i]) / span * 1000, vz: (p.z[j] - p.z[i]) / span * 1000 };
}
/** 선수별 무기 · 스킬 상태 [t, equipKind, stateName] (시간 순) */
export function stateTracks(r: ReplayFile): [number, number, string][][] {
const out: [number, number, string][][] = r.players.map(() => []);
for (const [t, p, ek, sk] of r.states ?? []) out[p]?.push([t, ek, r.stateKinds?.[sk] ?? '']);
return out;
}
const WEAPON_KO: Record<string, string> = {
Classic: '클래식', Shorty: '쇼티', Frenzy: '프렌지', Ghost: '고스트', Sheriff: '셰리프', 'Compact Pistol': '밴딧',
Stinger: '스팅어', Spectre: '스펙터', Bucky: '버키', Judge: '저지', Bulldog: '불독', Guardian: '가디언', Phantom: '팬텀', Vandal: '밴달',
Marshal: '마셜', Outlaw: '아웃로', Operator: '오퍼레이터', Ares: '아레스', Odin: '오딘',
Melee: '칼', Spike: '스파이크', Unarmed: '맨손', Headhunter: '헤드헌터', 'Tour de Force': '투르 드 포스', Bomb_Defuser_C: '스파이크 해체',
};
/** 들고 있는 것 이름 (한국어). 스킬은 "스킬", 모르면 null */
export function equipLabel(kind: string | undefined): string | null {
if (!kind) return null;
if (WEAPON_KO[kind]) return WEAPON_KO[kind];
if (/^Ability_/.test(kind)) return '스킬';
if (/Unarmed/.test(kind)) return null;
return null;
}
/** 선수별 [t, kind] 목록 (시간 순) */
export function equipTracks(r: ReplayFile): [number, number][][] {
const out: [number, number][][] = r.players.map(() => []);
for (const [t, p, k] of r.equips ?? []) out[p]?.push([t, k]);
return out;
}
/** 선수별 [t, skin] 목록 (equipTracks 와 같은 시각, equipAt 으로 찾는다. 스킨 기록이 없으면 -1) */
export function skinTracks(r: ReplayFile): [number, number][][] {
const out: [number, number][][] = r.players.map(() => []);
for (const [t, p, , s] of r.equips ?? []) out[p]?.push([t, s ?? -1]);
return out;
}
/** t 시점에 들고 있던 것 (kind 번호, 없으면 -1) */
export function equipAt(track: [number, number][] | undefined, t: number): number {
if (!track?.length || t < track[0][0]) return -1;
let lo = 0;
let hi = track.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (track[mid][0] <= t) lo = mid;
else hi = mid - 1;
}
return track[lo][1];
}
/**
* 리플레이 시간(t) ↔ 기록 시각(ts, 게임 PC 시계) 맞추기.
* 기본: ts = recordedAt + t + offset. offset 은 같은 킬(죽인 사람 · 죽은 사람이 같은 것)이
* 경기 기록(match-details → 킬 이벤트 ts)과 리플레이에서 각각 언제인지 비교한 차이의 중앙값.
* 킬을 못 맞추면 라운드 교전 시작으로 맞춘다 (정확도 낮음).
*/
export interface ReplaySync {
offset: number;
/** 맞춘 킬 수 */
matched: number;
/** 킬별 차이가 중앙값에서 벗어난 정도 (절대값 최대, ms). 이게 작아야 동기화가 정확하다 */
spreadMs: number | null;
/** 킬별 차이 (ms, 중앙값 기준) */
residuals: number[];
}
export function computeSync(m: MatchDetail, r: ReplayFile): ReplaySync {
const kills = m.events.filter((e) => e.type === 'kill');
const used = new Set<string>();
const diffs: number[] = [];
for (const [t, ki, vi] of r.kills) {
const killer = r.players[ki]?.puuid;
const victim = r.players[vi]?.puuid;
if (!victim) continue;
const at = r.recordedAt + t;
let best: { id: string; d: number } | null = null;
for (const e of kills) {
if (used.has(e.id)) continue;
const d = e.data as KillData;
if (d.victim?.puuid !== victim) continue;
if (killer && d.killer?.puuid && d.killer.puuid !== killer) continue;
const diff = e.ts - at;
// 1분 넘게 차이 나면 다른 라운드의 킬
if (Math.abs(diff - (diffs.length ? median(diffs) : diff)) > 60000) continue;
if (!best || Math.abs(diff) < Math.abs(best.d)) best = { id: e.id, d: diff };
}
if (best) {
used.add(best.id);
diffs.push(best.d);
}
}
if (diffs.length >= 3) {
const off = median(diffs);
const residuals = diffs.map((d) => d - off);
return { offset: off, matched: diffs.length, spreadMs: Math.max(...residuals.map(Math.abs)), residuals };
}
// 킬로 못 맞추면 라운드 교전 시작으로 맞춘다. 앱은 라운드 시작을 "교전 시작 - 30초" 로 저장한다 (valorant.ts BUY_MS)
const rd: number[] = [];
for (const mr of m.rounds ?? []) {
const rr = r.rounds.find((x) => x.num === mr.num);
if (rr && rr.combat >= 0) rd.push(mr.startedAt + 30000 - (r.recordedAt + rr.combat));
}
if (rd.length) return { offset: median(rd), matched: 0, spreadMs: null, residuals: [] };
return { offset: 0, matched: 0, spreadMs: null, residuals: [] };
}
function median(a: number[]): number {
const s = [...a].sort((x, y) => x - y);
const n = s.length;
return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
}
/** 이동 기록에서 t 시점 위치 (앞뒤 표본 사이 직선 보간). 표본이 sampleMs*5 넘게 끊겼으면 그 사이는 없음 */
export function samplePlayer(tr: ReplayFile['players'][number]['track'], t: number, gapMs: number) {
const T = tr.t;
if (!T.length || t < T[0] - gapMs) return null;
let lo = 0;
let hi = T.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (T[mid] <= t) lo = mid;
else hi = mid - 1;
}
const i = lo;
const j = Math.min(i + 1, T.length - 1);
if (t - T[i] > gapMs) return { x: tr.x[i], y: tr.y[i], z: tr.z[i], yaw: tr.yaw[i], pitch: signedDeg(tr.pitch[i]), stale: true };
const span = T[j] - T[i];
const k = j === i || span > gapMs || span <= 0 ? 0 : Math.min(1, Math.max(0, (t - T[i]) / span));
let dy = tr.yaw[j] - tr.yaw[i];
if (dy > 180) dy -= 360;
if (dy < -180) dy += 360;
return {
x: tr.x[i] + (tr.x[j] - tr.x[i]) * k,
y: tr.y[i] + (tr.y[j] - tr.y[i]) * k,
z: tr.z[i] + (tr.z[j] - tr.z[i]) * k,
yaw: tr.yaw[i] + dy * k,
pitch: signedDeg(tr.pitch[i]) + (signedDeg(tr.pitch[j]) - signedDeg(tr.pitch[i])) * k,
stale: false,
};
}
/** 게임 각도(0~360) → -180~180 (아래를 보면 음수) */
function signedDeg(a: number) {
const v = ((a % 360) + 360) % 360;
return v > 180 ? v - 360 : v;
}
/** t 가 속한 라운드 (구매 단계 시작 기준) */
export function roundAt(r: ReplayFile, t: number) {
let cur = r.rounds[0] ?? null;
for (const rd of r.rounds) if (rd.buy <= t) cur = rd;
return cur;
}
/** 이 라운드에서 t 전에 죽었는지 (다시 움직인 기록이 있으면 부활로 본다) */
export function isDead(r: ReplayFile, player: number, t: number) {
const rd = roundAt(r, t);
if (!rd) return false;
let death = -1;
for (const [kt, , v] of r.kills) if (v === player && kt >= rd.buy && kt <= t) death = kt;
if (death < 0) return false;
const T = r.players[player]?.track.t ?? [];
// 죽은 뒤 2초 넘어 움직인 표본이 t 전에 있으면 살아난 것
let lo = 0;
let hi = T.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (T[mid] <= death + 2000) lo = mid + 1;
else hi = mid;
}
return !(lo < T.length && T[lo] <= t);
}

View File

@@ -0,0 +1,120 @@
import { deathClipName, weaponCat, type RigInput } from './agents3d';
import { equipAt, indexAt, MOVE_AIR, MOVE_CROUCH, MOVE_FLY, roundAt, type ReplayFile } from './replay';
/**
* 리플레이 기록 → 요원 몸 동작 (agents3d RigInput). 모두 t 하나로 정해지므로 되감기 · 멈춤 · 배속에도 같은 자세다.
* 공중 · 착지: track.f 공중 비트가 이어진 구간
* 위 몸 한 번 동작: 해체 · 설치(이어지는 동작) > 던지기(이 선수 투사체가 생김) > 재장전 · 칼 휘두르기(무기 상태) > 꺼내기(들고 있는 것이 바뀜)
* 죽음: 이 라운드에서 죽은 킬 (사망 모션 이름)
*/
export interface AnimIndex {
equips: [number, number][][];
/** 선수별 [t, equipKind, state] */
states: [number, number, string][][];
/** 선수별 던진 시각 (Projectile_* 생김) */
throws: number[][];
/** 선수별 이어지는 동작 [t0, t1, kind] */
actions: [number, number, string][][];
/** 선수별 사격 시각 */
shots: number[][];
/** states · equips 의 시각만 (찾기용) */
stateT: number[][];
equipT: number[][];
}
export function buildAnimIndex(r: ReplayFile, equips: [number, number][][]): AnimIndex {
const n = r.players.length;
const states: AnimIndex['states'] = Array.from({ length: n }, () => []);
for (const [t, p, ek, sk] of r.states ?? []) states[p]?.push([t, ek, r.stateKinds?.[sk] ?? '']);
const throws: number[][] = Array.from({ length: n }, () => []);
for (const o of r.objects) if (o[6] >= 0 && /^Projectile_/.test(r.objectKinds[o[2]] ?? '')) throws[o[6]]?.push(o[0]);
for (const a of throws) a.sort((x, y) => x - y);
const actions: AnimIndex['actions'] = Array.from({ length: n }, () => []);
for (const [t0, t1, p, k] of r.actions ?? []) actions[p]?.push([t0, t1 < 0 ? t0 + 7000 : t1, r.actionKinds?.[k] ?? '']);
const shots: number[][] = Array.from({ length: n }, () => []);
for (const s of r.shots) if (s[1] >= 0) shots[s[1]]?.push(s[0]);
return { equips, states, throws, actions, shots, stateT: states.map((a) => a.map((x) => x[0])), equipT: equips.map((a) => a.map((x) => x[0])) };
}
function lastBefore(a: number[], t: number): number | null {
const i = indexAt(a, t);
return i < 0 ? null : a[i];
}
/** 공중에 뜬 지 · 내려앉은 지 (ms) */
export function airState(tr: ReplayFile['players'][number]['track'], t: number): { airMs: number | null; landMs: number | null; crouch: boolean } {
const f = tr.f;
if (!f) return { airMs: null, landMs: null, crouch: false };
const i = indexAt(tr.t, t);
if (i < 0) return { airMs: null, landMs: null, crouch: false };
const air = (k: number) => (f[k] & (MOVE_AIR | MOVE_FLY)) !== 0;
const crouch = (f[i] & MOVE_CROUCH) !== 0;
if (air(i)) {
let k = i;
while (k > 0 && air(k - 1) && tr.t[k] - tr.t[k - 1] < 400) k--;
return { airMs: t - tr.t[k], landMs: null, crouch };
}
// 바로 전에 공중이었으면 착지
let k = i;
while (k > 0 && !air(k - 1) && tr.t[i] - tr.t[k - 1] < 600) k--;
if (k > 0 && air(k - 1)) return { airMs: null, landMs: t - tr.t[k], crouch };
return { airMs: null, landMs: null, crouch };
}
export function rigInput(
r: ReplayFile,
ix: AnimIndex,
p: number,
t: number,
base: { dt: number; fwd: number; right: number; pitch: number },
): RigInput & { shotMs: number | null } {
const tr = r.players[p].track;
const air = airState(tr, t);
const ek = equipAt(ix.equips[p], t);
const kind = r.equipKinds?.[ek];
const cat = weaponCat(kind);
let crouch = air.crouch;
let overlay: RigInput['overlay'] = null;
// 이어지는 동작 (해체 · 설치): 앉아서 손
for (const [a0, a1, k] of ix.actions[p]) {
if (a0 <= t && t <= a1 && (k === 'Defuse' || k === 'Plant')) {
crouch = true;
overlay = { clip: 'ub_defuse', ms: t - a0, loop: true };
}
}
if (!overlay) {
const th = lastBefore(ix.throws[p], t + 300);
// 던지는 동작은 손을 놓는 때(투사체가 생긴 때)보다 0.3초 먼저 시작한다
if (th != null && t - (th - 300) < 1500) overlay = { clip: 'ub_throw', ms: t - (th - 300) };
}
if (!overlay) {
const st = ix.states[p];
const i = indexAt(ix.stateT[p], t);
if (i >= 0) {
const [ts, sek, name] = st[i];
if (sek === ek && name === 'ReloadState') overlay = { clip: cat === 'pistol' ? 'ub_reloadPistol' : cat === 'sniper' ? 'ub_reloadSniper' : 'ub_reloadRifle', ms: t - ts };
else if (sek === ek && /^AnimTriggeredState/.test(name) && t - ts < 1500) overlay = { clip: /Alt/.test(name) ? 'ub_knifeAlt' : name.endsWith('2') ? 'ub_knifeAttack2' : 'ub_knifeAttack', ms: t - ts };
}
}
if (!overlay) {
const eq = ix.equips[p];
const i = indexAt(ix.equipT[p], t);
if (i >= 0 && t - eq[i][0] < 1500) {
const clip = cat === 'ability' ? 'ub_equipAbility' : cat === 'knife' ? 'ub_equipKnife' : cat === 'pistol' ? 'ub_equipPistol' : cat === 'sniper' ? 'ub_equipSniper' : 'ub_equipRifle';
overlay = { clip, ms: t - eq[i][0] };
}
}
// 죽음: 이 라운드에서 죽은 킬
let death: RigInput['death'] = null;
const rd = roundAt(r, t);
if (rd) {
for (const k of r.kills) {
if (k[2] !== p || k[0] < rd.buy || k[0] > t) continue;
death = { clip: deathClipName(k[3] != null && k[3] >= 0 ? r.deathAnims?.[k[3]] : null), ms: t - k[0] };
}
}
const sh = lastBefore(ix.shots[p], t);
return { ...base, crouch, airMs: air.airMs, landMs: air.landMs, cat, overlay, death, shotMs: sh == null ? null : t - sh };
}

View File

@@ -0,0 +1,171 @@
import { indexAt, isDead, roundAt, samplePlayer, type ReplayFile } from './replay';
/**
* 리플레이 점수판 (게임에서 Tab 을 누른 화면): 크레딧 · 궁극기 점수 · 킬/데스/어시 · 전투 점수.
* 값은 변환기(1.10.0~)의 scoreboard 행 [t, 선수, 크레딧, 궁 점수, 킬, 데스, 어시, 전투 점수] (모르는 값 -1).
* 옛 리플레이 JSON 에는 없어서 킬 · 데스만 리플레이 킬 기록으로 센다.
*/
const MONEY = 2;
const ULT = 3;
const KILLS = 4;
const DEATHS = 5;
const ASSISTS = 6;
const SCORE = 7;
/** 요원(캐릭터 클래스 코드)별 궁극기 점수. 경기에서 궁을 쓴 기록이 있으면 그 값을 쓰고, 없을 때만 이 표 (패치로 바뀔 수 있다) */
const ULT_COST: Record<string, number> = {
Wushu: 8, Sarge: 8, Phoenix: 7, Hunter: 8, Thorne: 8, Pandemic: 9, Wraith: 7, Clay: 8, Vampire: 7, Breach: 8, Gumshoe: 6,
Killjoy: 9, Guide: 8, Stealth: 8, Rift: 7, Grenadier: 8, Deadeye: 8, Sprinter: 7, BountyHunter: 8, Mage: 7, AggroBot: 8,
Cable: 7, Sequoia: 7, Smonk: 8, Nox: 8, Cashew: 8, Terra: 8,
};
const DEFAULT_ULT = 8;
const PRIMARY = new Set(['Stinger', 'Spectre', 'Bucky', 'Judge', 'Bulldog', 'Guardian', 'Phantom', 'Vandal', 'Marshal', 'Outlaw', 'Operator', 'Ares', 'Odin']);
const SIDEARM = new Set(['Classic', 'Shorty', 'Frenzy', 'Ghost', 'Sheriff', 'Compact Pistol']);
export interface BoardIndex {
/** 선수별 행 · 행 시각 */
rows: number[][][];
times: number[][];
/** 선수별 궁극기 점수 (다 모으면 궁 준비) */
ultMax: number[];
has: boolean;
}
export function boardIndex(r: ReplayFile): BoardIndex {
const rows: number[][][] = r.players.map(() => []);
for (const row of r.scoreboard ?? []) rows[row[1]]?.push(row);
for (const a of rows) a.sort((x, y) => x[0] - y[0]);
const times = rows.map((a) => a.map((x) => x[0]));
return { rows, times, ultMax: ultCosts(r, rows), has: rows.some((a) => a.length > 0) };
}
/** 공수 교대로 시작한 라운드 번호 (rounds 의 순번): 선수들 시작 자리가 크게 바뀐 라운드 (같은 편이면 13m 안, 교대하면 90m 넘게, 13.08 어비스 실측) */
const SWAP_CM = 4000;
export function sideSwaps(r: ReplayFile): Set<number> {
const out = new Set<number>();
const spawn = (p: number, k: number) => samplePlayer(r.players[p].track, r.rounds[k].buy + 1500, r.sampleMs * 30);
for (let k = 1; k < r.rounds.length; k++) {
const d: number[] = [];
for (let p = 0; p < r.players.length; p++) {
const a = spawn(p, k - 1);
const b = spawn(p, k);
if (a && b) d.push(Math.hypot(a.x - b.x, a.y - b.y));
}
d.sort((x, y) => x - y);
if (d.length && d[Math.floor(d.length / 2)] > SWAP_CM) out.add(k);
}
return out;
}
/**
* 궁극기 점수: 궁을 쓴 순간(점수가 0 으로 떨어짐) 바로 앞 점수.
* 공수 교대 초기화(교대 직전 라운드가 끝난 뒤 ~ 교대 라운드 구매 시작 3초 뒤 사이에 0 이 된 것)는 쓴 것이 아니다. 한 명만 점수가 있어도 같다.
* 쓴 기록이 없으면 요원 표 값과 경기에서 모은 가장 큰 점수 중 큰 것
*/
export function ultCosts(r: ReplayFile, rows: number[][][]): number[] {
const drops: { t: number; p: number; from: number }[] = [];
const maxSeen = rows.map(() => 0);
rows.forEach((a, p) => {
let last = -1;
for (const row of a) {
const v = row[ULT];
if (v < 0) continue;
maxSeen[p] = Math.max(maxSeen[p], v);
if (last > 0 && v === 0) drops.push({ t: row[0], p, from: last });
last = v;
}
});
const resets = [...sideSwaps(r)].map((k) => {
const prev = r.rounds[k - 1];
return [prev.end >= 0 ? prev.end : prev.combat >= 0 ? prev.combat : prev.buy, r.rounds[k].buy + 3000];
});
const used: number[][] = rows.map(() => []);
for (const d of drops) {
if (resets.some(([a, b]) => d.t >= a && d.t <= b)) continue; // 공수 교대 초기화
used[d.p].push(d.from);
}
return r.players.map((pl, p) => {
if (used[p].length) return mode(used[p]);
const code = (pl.character ?? '').replace(/_PC_C$/, '');
return Math.max(ULT_COST[code] ?? DEFAULT_ULT, maxSeen[p]);
});
}
export interface BoardRow {
idx: number;
money: number | null;
ult: number | null;
ultMax: number;
kills: number;
deaths: number;
assists: number | null;
score: number | null;
/** 이 라운드에 가진 주무기 (없으면 보조무기) 영어 이름 */
weapon: string | null;
dead: boolean;
}
export function boardAt(r: ReplayFile, ix: BoardIndex, p: number, t: number): BoardRow {
const i = indexAt(ix.times[p] ?? [], t);
const row = i >= 0 ? ix.rows[p][i] : null;
// 게임은 기본값(0)과 다를 때만 값을 보낸다: 점수판이 있는 리플레이에서 안 온 숫자는 0. 크레딧은 처음부터 오므로 모르면 비운다
const val = (k: number) => (row && row[k] >= 0 ? row[k] : ix.has && k !== MONEY ? 0 : null);
let kills = val(KILLS);
let deaths = val(DEATHS);
if (kills == null || deaths == null) {
// 옛 리플레이: 킬 기록으로 센다
let k = 0;
let d = 0;
for (const [kt, ki, vi] of r.kills) {
if (kt > t) continue;
if (ki === p && vi !== p) k++;
if (vi === p) d++;
}
kills ??= k;
deaths ??= d;
}
return {
idx: p,
money: val(MONEY),
ult: val(ULT),
ultMax: ix.ultMax[p] ?? DEFAULT_ULT,
kills,
deaths,
assists: val(ASSISTS),
score: val(SCORE),
weapon: loadoutAt(r, p, t),
dead: isDead(r, p, t),
};
}
/** 이 라운드(구매 단계부터 t 까지) 마지막으로 든 주무기, 없으면 보조무기 */
export function loadoutAt(r: ReplayFile, p: number, t: number): string | null {
const rd = roundAt(r, t);
const from = rd?.buy ?? 0;
let primary: string | null = null;
let side: string | null = null;
for (const [et, ep, k] of r.equips ?? []) {
if (ep !== p || et < from || et > t) continue;
const name = r.equipKinds?.[k] ?? '';
if (PRIMARY.has(name)) primary = name;
else if (SIDEARM.has(name)) side = name;
}
return primary ?? side;
}
/** 라운드 · 팀 점수: t 가 속한 라운드 번호와 그 라운드 전까지 이긴 수 (라운드가 끝난 뒤면 그 라운드까지) */
export function teamScoreAt(r: ReplayFile, rounds: { num: number; score: { ally: number; enemy: number } }[] | undefined, t: number) {
const rd = roundAt(r, t);
const num = rd?.num ?? 1;
// 라운드가 끝났으면(승패 확정) 그 라운드까지 (마지막 라운드가 끝난 뒤 최종 점수)
const done = !!rd && rd.end >= 0 && t >= rd.end;
const before = rounds?.filter((x) => (done ? x.num <= num : x.num < num)).sort((a, b) => b.num - a.num)[0];
return { round: num, ally: before?.score.ally ?? 0, enemy: before?.score.enemy ?? 0 };
}
function mode(a: number[]) {
const c = new Map<number, number>();
for (const v of a) c.set(v, (c.get(v) ?? 0) + 1);
return [...c.entries()].sort((x, y) => y[1] - x[1] || y[0] - x[0])[0][0];
}

83
site/web/src/lib/skins.ts Normal file
View File

@@ -0,0 +1,83 @@
import type { ReplayFile, SkinInfo } from './replay';
/**
* 무기 스킨 3D (사이트 서버 /site/maps3d/skins, 로그인 필요).
* 리플레이 skins 의 스킨 · 단계 · 색상으로 찾는다. 아직 없는 스킨은 요청만 해 두고 기본 스킨으로 그린다
* (이 서버가 몇 분 안에 그 스킨만 뽑아 올리므로 다음에 열면 보인다, tools/map-extract/scripts/skins-update.sh).
* skins[열쇠] = {weapon, sig}, looks[sig] = {w3p(3인칭 glb), w1p(1인칭 glb, 총 동작 포함), …}. 파일은 /site/maps3d/skins/<파일>
*/
export interface SkinLook {
w3p?: string;
w1p?: string;
points?: Record<string, number[]>;
points1p?: Record<string, number[]>;
gunClips?: string[];
}
interface SkinsIndex {
skins: Record<string, { weapon: string; sig: string }>;
looks: Record<string, SkinLook>;
failed?: Record<string, string>;
}
export const skinKey = (s: SkinInfo) => `${s.skin}|${s.level ?? ''}|${s.chroma ?? ''}`;
/** 기본 스킨 (…_Standard_PrimaryAsset, 예: Melee_Base_Standard · Compact_Standard): 따로 뽑지 않고 기본 무기 모델을 쓴다 */
export const isDefaultSkin = (s: SkinInfo) => /_Standard_PrimaryAsset$/.test(s.skin);
export const skinFileUrl = (file: string) => `/site/maps3d/skins/${encodeURIComponent(file)}`;
/** 스킨 목록. 부를 때마다 새로 받는다 (리플레이를 다시 열면 그사이 뽑힌 스킨이 보이게). 받는 중이면 그 요청을 같이 쓴다 */
let indexP: Promise<SkinsIndex | null> | null = null;
export function loadSkins(): Promise<SkinsIndex | null> {
indexP ??= fetch('/site/maps3d/skins', { credentials: 'same-origin', cache: 'no-store' })
.then((r) => (r.ok ? (r.json() as Promise<SkinsIndex>) : null))
.catch(() => null)
.finally(() => {
indexP = null;
});
return indexP;
}
/** 이 스킨의 모습 (없거나 기본 스킨이면 null) */
export function lookOf(idx: SkinsIndex | null, s: SkinInfo | undefined | null): SkinLook | null {
if (!idx || !s || isDefaultSkin(s)) return null;
const e = idx.skins[skinKey(s)];
return (e && idx.looks[e.sig]) || null;
}
/** 리플레이에 나온 스킨 중 아직 없는 것 (기본 스킨 · 실패한 것은 빼고) */
export function missingSkins(idx: SkinsIndex, r: Pick<ReplayFile, 'skins'>): string[] {
const out = new Set<string>();
for (const s of r.skins ?? []) {
if (isDefaultSkin(s)) continue;
const k = skinKey(s);
if (!idx.skins[k] && !idx.failed?.[k]) out.add(k);
}
return [...out];
}
/** 요청 한 번에 보내는 열쇠 수 (서버 MAX_WANT_PER_REQUEST 와 같다) */
export const WANT_CHUNK = 100;
/** 열쇠를 WANT_CHUNK 개씩 나눈다 */
export function chunks<T>(list: T[], n = WANT_CHUNK): T[][] {
const out: T[][] = [];
for (let i = 0; i < list.length; i += n) out.push(list.slice(i, i + n));
return out;
}
/** 없는 스킨을 뽑아 달라고 요청한다 (100개씩 나눠 전부, 실패해도 그냥 기본 스킨). 넣은 개수 */
export async function requestMissing(idx: SkinsIndex, r: Pick<ReplayFile, 'skins'>): Promise<number> {
let queued = 0;
for (const keys of chunks(missingSkins(idx, r))) {
const res = await fetch('/site/maps3d/skins/want', {
method: 'POST',
credentials: 'same-origin',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ keys }),
}).catch(() => null);
if (!res?.ok) break;
queued += ((await res.json()) as { queued?: number }).queued ?? 0;
}
return queued;
}

View File

@@ -0,0 +1,24 @@
/**
* 처음 보는 유저 아이디가 오면 유저 목록을 다시 받아 온다 (v1.4.1 이하 앱은 녹음 중에 들어온 사람을 알려 주지 않아 "알 수 없음"으로 뜸).
* - 받는 중에는 또 부르지 않는다
* - 받기에 성공한 아이디는 다시 묻지 않는다 (목록에 없어도 매 발화마다 부르지 않게)
* - 실패하면 기억하지 않아 다음 이벤트에서 다시 받는다
*/
export function makeUnknownUserCheck(load: () => Promise<unknown>) {
const done = new Set<string>();
let busy = false;
return (ids: string[], known: (id: string) => boolean): void => {
if (busy) return;
const fresh = ids.filter((id) => id && !known(id) && !done.has(id));
if (!fresh.length) return;
busy = true;
load()
.then(
() => fresh.forEach((id) => done.add(id)),
() => {},
)
.finally(() => {
busy = false;
});
};
}

1830
site/web/src/lib/vfx.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,239 @@
import * as THREE from 'three';
import { GLTFLoader, type GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
import { clone as cloneSkinned } from 'three/examples/jsm/utils/SkeletonUtils.js';
import { assetUrl } from './agents3d';
import { loadIndex } from './map3d';
import { skinFileUrl, type SkinLook } from './skins';
/**
* 1인칭 화면 팔 · 총 (tools/map-extract viewmodels → index.json viewmodels).
* arms[캐릭터 클래스] 요원 1인칭 팔 (뼈대는 모든 요원 공용, Camera 뼈 = 눈)
* weapons[무기 이름] 무기 1인칭 모델(총 동작 gun_*) + 그 무기를 든 팔 동작(idle · fire · reload · equip · ads · walk · activate)
* 좌표는 게임(UE) cm. 무기 뿌리는 팔 뼈 MasterWeapon 에 GUN_Q 만큼 돌려 붙인다 (총 몸의 앞 = 팔의 앞, 탄창 = 아래).
* 자세는 시각(ms)만으로 정한다 (되감기 · 멈춤 · 배속에도 같은 자세).
*/
export interface VmIndex {
arms: Record<string, { code: string; file: string }>;
weapons: Record<string, { file: string; anim: string; clips: string[]; gunClips: string[]; points?: { muzzle?: number[] } }>;
}
const GUN_Q = new THREE.Quaternion(0.5, -0.5, 0.5, 0.5);
/** UE(cm, X 앞 · Y 오른쪽 · Z 위) → 카메라 공간(m, -Z 앞 · X 오른쪽 · Y 위) */
const UE_TO_VIEW = new THREE.Matrix4().set(0, 0.01, 0, 0, 0, 0, 0.01, 0, -0.01, 0, 0, 0, 0, 0, 0, 1);
const cache = new Map<string, Promise<GLTF>>();
function load(url: string): Promise<GLTF> {
let p = cache.get(url);
if (!p) {
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
p = loader.loadAsync(url);
p.catch(() => cache.delete(url));
cache.set(url, p);
}
return p;
}
export async function viewmodelIndex(): Promise<(VmIndex & { dir: string }) | null> {
const idx = (await loadIndex()) as { dir: string | null; viewmodels?: VmIndex | null } | null;
return idx?.dir && idx.viewmodels ? { ...idx.viewmodels, dir: idx.dir } : null;
}
/** 지금 자세를 정하는 입력 (모두 ms, 없으면 null) */
export interface VmInput {
/** 이 무기를 꺼낸 지 */
equipMs: number | null;
/** 마지막 사격 뒤 */
shotMs: number | null;
/** 재장전 시작 뒤 */
reloadMs: number | null;
/** 정조준(줌) 중 */
ads: boolean;
/** 걷는 중이면 걸은 시간 (반복 동작 위치) */
walkMs: number | null;
/** 스파이크 설치 시작 뒤 (설치하는 동안만) */
activateMs?: number | null;
}
function findBone(root: THREE.Object3D, name: string): THREE.Object3D | null {
let b: THREE.Object3D | null = null;
root.traverse((o) => {
if (!b && o.name === name) b = o;
});
return b;
}
function prep(root: THREE.Object3D) {
root.traverse((o) => {
const m = o as THREE.Mesh;
if (!m.isMesh) return;
m.frustumCulled = false;
const mat = m.material as THREE.MeshStandardMaterial;
mat.side = THREE.DoubleSide;
});
}
/**
* 1인칭 팔 + 무기. scene 을 따로 두고 카메라 공간에서 그린다 (맵보다 앞에, 깊이 따로).
* set() 으로 요원 · 무기를 바꾸고(받는 동안은 이전 것), pose() 로 자세를 정한 뒤 render().
*/
export class Viewmodel {
readonly scene = new THREE.Scene();
readonly camera = new THREE.PerspectiveCamera(70, 1, 0.01, 20);
private root = new THREE.Group();
private arms: THREE.Object3D | null = null;
private armsMixer: THREE.AnimationMixer | null = null;
private gunMixer: THREE.AnimationMixer | null = null;
private armClips = new Map<string, THREE.AnimationClip>();
private gunClips = new Map<string, THREE.AnimationClip>();
private flash: THREE.Sprite;
private muzzle: THREE.Object3D | null = null;
private want = '';
private have = '';
private disposed = false;
constructor(private readonly idx: VmIndex & { dir: string }) {
this.root.matrixAutoUpdate = false;
this.scene.add(this.root);
this.scene.add(new THREE.HemisphereLight(0xffffff, 0x8a8f99, 2.2));
const sun = new THREE.DirectionalLight(0xfff4e0, 1.6);
sun.position.set(0.4, 1, 0.6);
this.scene.add(sun);
// 총구 불꽃 (사격 직후 잠깐)
const c = document.createElement('canvas');
c.width = c.height = 64;
const g = c.getContext('2d')!;
const grd = g.createRadialGradient(32, 32, 0, 32, 32, 32);
grd.addColorStop(0, 'rgba(255,250,220,1)');
grd.addColorStop(0.3, 'rgba(255,200,90,0.85)');
grd.addColorStop(1, 'rgba(255,120,20,0)');
g.fillStyle = grd;
g.fillRect(0, 0, 64, 64);
this.flash = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), blending: THREE.AdditiveBlending, depthTest: false, transparent: true }));
this.flash.scale.setScalar(0.12);
this.flash.visible = false;
this.scene.add(this.flash);
}
/** 이 요원 · 무기에 1인칭 모델이 있는지 */
has(character: string | null | undefined, weapon: string | null | undefined): boolean {
return !!character && !!weapon && !!this.idx.arms[character] && !!this.idx.weapons[weapon];
}
/** 요원 · 무기(· 스킨)를 바꾼다 (같으면 그대로). 받는 동안은 이전 모델을 그린다. 스킨 1인칭 모델을 받지 못하면 기본 스킨 */
set(character: string, weapon: string, skin?: SkinLook | null) {
const key = `${character}|${weapon}|${skin?.w1p ?? ''}`;
if (key === this.want) return;
this.want = key;
const a = this.idx.arms[character];
const w = this.idx.weapons[weapon];
if (!a || !w) return;
const url = (f: string) => assetUrl(this.idx.dir, f);
const gun = skin?.w1p ? load(skinFileUrl(skin.w1p)).catch(() => load(url(w.file))) : load(url(w.file));
void Promise.all([load(url(a.file)), gun, load(url(w.anim))])
.then(([ag, wg, an]) => {
if (this.disposed || this.want !== key) return;
this.build(ag, wg, an);
this.have = key;
})
.catch(() => undefined);
}
private build(ag: GLTF, wg: GLTF, an: GLTF) {
if (this.arms) this.root.remove(this.arms);
const arms = cloneSkinned(ag.scene);
const gun = cloneSkinned(wg.scene);
prep(arms);
prep(gun);
const attach = findBone(arms, 'MasterWeapon');
if (attach) {
gun.quaternion.copy(GUN_Q);
attach.add(gun);
}
this.root.add(arms);
this.arms = arms;
this.muzzle = findBone(gun, 'Muzzle');
this.armsMixer = new THREE.AnimationMixer(arms);
this.gunMixer = new THREE.AnimationMixer(gun);
this.armClips = new Map(an.animations.map((c) => [c.name, c]));
this.gunClips = new Map(wg.animations.map((c) => [c.name, c]));
// 눈 = 팔 Camera 뼈 (대기 자세)
this.play(this.armsMixer, this.armClips.get('idle'), 0, false);
arms.updateMatrixWorld(true);
// 팔 공간 좌표로 (root 에 이전 요원 · 무기의 변환이 남아 있어도 같은 값)
const cam = findBone(arms, 'Camera');
const cp = cam ? arms.worldToLocal(new THREE.Vector3().setFromMatrixPosition(cam.matrixWorld)) : new THREE.Vector3(0, 0, 166);
this.root.matrix.copy(UE_TO_VIEW).multiply(new THREE.Matrix4().makeTranslation(-cp.x, -cp.y, -cp.z));
this.root.matrixWorldNeedsUpdate = true;
}
get ready() {
return this.have !== '' && this.have === this.want;
}
private play(mixer: THREE.AnimationMixer, clip: THREE.AnimationClip | undefined, ms: number, loop: boolean) {
mixer.stopAllAction();
if (!clip) return false;
const a = mixer.clipAction(clip);
a.reset();
a.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, Infinity);
a.clampWhenFinished = true;
a.play();
const d = Math.max(clip.duration, 1e-3);
a.time = loop ? (ms / 1000) % d : Math.min(ms / 1000, d);
mixer.update(0);
return true;
}
/** 시각만으로 자세: 스파이크 설치 > 꺼내기 > 재장전 > 사격 > 걷기 > 정조준 > 대기 (설치 시작 때 스파이크를 꺼내므로 설치가 먼저) */
pose(i: VmInput) {
if (!this.armsMixer || !this.gunMixer) return;
const dur = (n: string) => (this.armClips.get(n)?.duration ?? 0) * 1000;
let role = 'idle';
let ms = 0;
let loop = false;
if (i.activateMs != null && this.armClips.has('activate')) [role, ms] = ['activate', i.activateMs];
else if (i.equipMs != null && i.equipMs < dur('equip')) [role, ms] = ['equip', i.equipMs];
else if (i.reloadMs != null && i.reloadMs < dur('reload')) [role, ms] = ['reload', i.reloadMs];
else if (i.shotMs != null && i.shotMs < dur('fire')) [role, ms] = ['fire', i.shotMs];
else if (i.walkMs != null && this.armClips.has('walk') && !i.ads) [role, ms, loop] = ['walk', i.walkMs, true];
else if (i.ads && this.armClips.has('ads')) role = 'ads';
if (!this.play(this.armsMixer, this.armClips.get(role), ms, loop)) this.play(this.armsMixer, this.armClips.get('idle'), 0, false);
if (!this.play(this.gunMixer, this.gunClips.get('gun_' + role), ms, false)) this.gunMixer.stopAllAction();
// 총구 불꽃: 사격 뒤 60ms
const on = i.shotMs != null && i.shotMs < 60 && role === 'fire' && !!this.muzzle;
this.flash.visible = on;
if (on) {
this.root.updateMatrixWorld(true);
this.flash.position.setFromMatrixPosition(this.muzzle!.matrixWorld);
this.flash.material.rotation = (i.shotMs! * 7) % (Math.PI * 2);
}
}
/** 맵을 그린 뒤 깊이만 지우고 그 위에 그린다 */
render(renderer: THREE.WebGLRenderer, fov: number, aspect: number) {
if (!this.arms) return;
if (this.camera.fov !== fov || this.camera.aspect !== aspect) {
this.camera.fov = fov;
this.camera.aspect = aspect;
this.camera.updateProjectionMatrix();
}
const clip = renderer.localClippingEnabled;
const auto = renderer.autoClear;
renderer.localClippingEnabled = false;
renderer.autoClear = false;
renderer.clearDepth();
renderer.render(this.scene, this.camera);
renderer.autoClear = auto;
renderer.localClippingEnabled = clip;
}
dispose() {
this.disposed = true;
this.armsMixer?.stopAllAction();
this.gunMixer?.stopAllAction();
this.flash.material.map?.dispose();
this.flash.material.dispose();
}
}

View File

@@ -0,0 +1,299 @@
// 관리 페이지 (v1.6.0, 관리자 · 최고 관리자)
// - 게임 PC: 연결 · 앱 버전 · 새 버전 안내
// - 유저: 표시 이름 · 색 · 녹음 제외 · 라이엇 ID (녹음된 사람), 앱 등록 · 역할 · 해제 (최고 관리자)
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router';
import type { AppUserRow, User } from '@gvr/shared';
import { api, type AdminOverview } from '../lib/api';
import { fmtDay } from '../lib/format';
import { useAuth, useData } from '../store/app';
import { Avatar, ErrorBox, Panel, Spinner } from '../components/common';
import { AppUserEditor, errText, NameEditor } from '../components/UserEdit';
const ROLE: Record<string, string> = { superadmin: '최고 관리자', admin: '관리자', user: '앱 유저' };
/** "1.4.1" < "1.5.0" */
export function olderVersion(a: string | null | undefined, b: string | null | undefined): boolean {
if (!a || !b) return false;
const pa = a.split('.').map((x) => parseInt(x, 10) || 0);
const pb = b.split('.').map((x) => parseInt(x, 10) || 0);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) < (pb[i] ?? 0);
return false;
}
const when = (t: number | null) => (t ? `${fmtDay(t)} ${new Date(t).toLocaleTimeString('ko-KR', { hour12: false, hour: '2-digit', minute: '2-digit' })}` : '—');
interface Row {
id: string;
name: string;
avatar: string | null;
/** 녹음 기록에 있는 사람 (게임 PC 앱) */
user: User | null;
/** 앱 등록 (사이트 서버) */
reg: AppUserRow | null;
}
export function AdminPage() {
const { auth } = useAuth();
const { users } = useData();
const [ov, setOv] = useState<AdminOverview | null>(null);
const [regs, setRegs] = useState<AppUserRow[] | null>(null);
const [names, setNames] = useState<Record<string, string>>({});
const [err, setErr] = useState<unknown>(null);
const [open, setOpen] = useState<string | null>(null);
const [q, setQ] = useState('');
const load = useCallback(() => {
setErr(null);
Promise.all([api.adminOverview(), api.adminUsers()])
.then(([o, u]) => {
setOv(o);
setRegs(u.users);
setNames(u.names ?? {});
})
.catch(setErr);
}, []);
useEffect(load, [load]);
const sup = ov?.role === 'superadmin';
const rows = useMemo<Row[]>(() => {
const m = new Map<string, Row>();
for (const u of users) m.set(u.id, { id: u.id, name: u.name, avatar: u.avatar, user: u, reg: null });
for (const r of regs ?? []) {
const cur = m.get(r.id);
if (cur) cur.reg = r;
else m.set(r.id, { id: r.id, name: r.name, avatar: r.avatar, user: null, reg: r });
}
const order = (r: Row) => (r.reg?.role === 'superadmin' ? 0 : r.reg?.role === 'admin' ? 1 : r.reg ? 2 : 3);
const k = q.trim().toLowerCase();
return [...m.values()]
.filter((r) => !k || r.name.toLowerCase().includes(k) || r.id.includes(k) || r.user?.riot.some((x) => x.riotId.toLowerCase().includes(k)))
.sort((a, b) => order(a) - order(b) || a.name.localeCompare(b.name, 'ko'));
}, [users, regs, q]);
if (auth.status !== 'ok' || !auth.me.canViewLogs)
return (
<main className="page-pad">
<h2 className="page-h h">관리</h2>
<div className="dim">관리자만 볼 수 있습니다.</div>
</main>
);
if (err) return <main className="page-pad"><ErrorBox error={err} onRetry={load} /></main>;
if (!ov || !regs) return <main className="page-pad"><Spinner /></main>;
const dev = ov.device;
const outdated = olderVersion(dev.version, ov.latest?.version);
return (
<main className="page-pad admin-page">
<div className="page-h-row">
<h2 className="page-h h">🛡️ 관리</h2>
<div className="chips-wrap">
<a className="mini-btn" href="/logs">
📄 사이트 로그
</a>
<button className="mini-btn" onClick={load}>
새로고침
</button>
</div>
</div>
<Panel title="게임 PC">
<div className="adm-dev">
<div>
<span className={`dot-st ${dev.online ? 'on' : 'off'}`} /> <b>{dev.name ?? '등록된 PC 없음'}</b>
<span className="dim small"> · {dev.online ? '연결됨' : dev.lastSeen ? `마지막 연결 ${when(dev.lastSeen)}` : '연결 안 됨'}</span>
</div>
<div>
앱 <b className="mono">{dev.version ?? '?'}</b>
{ov.latest && (
<span className="dim small">
{' '}
· 최신 <span className="mono">{ov.latest.version}</span>
</span>
)}
{outdated && ov.latest && (
<a className="adm-update" href={ov.latest.url} target="_blank" rel="noreferrer">
새 버전 v{ov.latest.version} 받기 →
</a>
)}
</div>
{outdated && <div className="ue-hint">게임 PC 앱이 최신이 아닙니다. 색 · 녹음 제외 · 라이엇 ID 바꾸기와 3D 리플레이는 최신 앱에서 됩니다.</div>}
</div>
</Panel>
<Panel
title={`유저 ${rows.length}명`}
right={<input className="ue-input adm-search" value={q} placeholder="이름 · 아이디 · 라이엇 ID 찾기" onChange={(e) => setQ(e.target.value)} aria-label="유저 찾기" />}
>
<div className="ue-hint adm-note">
표시 이름은 디스코드 이름 대신 사이트 · 게임 PC 기록 · 범인 분석에 보입니다 (관리자). 앱 등록 · 역할 바꾸기 · 등록 해제는 최고 관리자만 할 수 있습니다.
</div>
<div className="adm-list">
{rows.map((r) => (
<AdminUserRow
key={r.id}
r={r}
custom={!!names[r.id]}
sup={sup}
open={open === r.id}
onToggle={() => setOpen((o) => (o === r.id ? null : r.id))}
onNames={setNames}
onRegs={setRegs}
/>
))}
</div>
{sup && <AddUser onRegs={setRegs} />}
</Panel>
</main>
);
}
function AdminUserRow({
r,
custom,
sup,
open,
onToggle,
onNames,
onRegs,
}: {
r: Row;
custom: boolean;
sup: boolean;
open: boolean;
onToggle: () => void;
onNames: (n: Record<string, string>) => void;
onRegs: (u: AppUserRow[]) => void;
}) {
const { reloadUsers } = useData();
const { auth, refreshMe } = useAuth();
const [msg, setMsg] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const act = async (fn: () => Promise<{ users: AppUserRow[] }>) => {
setBusy(true);
setMsg(null);
try {
onRegs((await fn()).users);
} catch (e) {
setMsg(errText(e));
} finally {
setBusy(false);
}
};
const role = r.reg?.role ?? null;
return (
<div className={`adm-row${open ? ' open' : ''}`}>
<button className="adm-sum" onClick={onToggle} aria-expanded={open}>
<Avatar user={r.user} name={r.name} src={r.avatar} size={30} />
<span className="adm-nm">
<b style={r.user ? { color: r.user.color } : undefined}>{r.name}</b>
{custom && <span className="badge b-name">표시 이름</span>}
{r.user?.excluded && <span className="badge b-excl">녹음 제외</span>}
<span className="dim small mono">{r.id}</span>
</span>
<span className="adm-role">{role ? <span className={`badge b-role ${role}`}>{ROLE[role]}</span> : <span className="dim small">앱 미등록</span>}</span>
<span className="adm-seen dim small">{r.reg?.lastSeenAt ? `앱 ${when(r.reg.lastSeenAt)}${r.reg.lastVersion ? ` · v${r.reg.lastVersion}` : ''}` : r.user ? '녹음 기록 있음' : ''}</span>
<span className="adm-caret">{open ? '▴' : '▾'}</span>
</button>
{open && (
<div className="adm-body">
<div className="ue-label">표시 이름</div>
<NameEditor
value={r.name}
custom={custom}
onSave={async (name) => {
const res = await api.adminSetName(r.id, name);
onNames(res.names);
// 게임 PC 앱이 이름을 받아 유저 목록을 다시 보낸다. 조금 기다렸다가 다시 받는다
window.setTimeout(reloadUsers, 1500);
if (auth.status === 'ok' && auth.me.user.id === r.id) await refreshMe();
const regs = await api.adminUsers().catch(() => null);
if (regs) onRegs(regs.users);
}}
/>
{r.user ? (
<AppUserEditor user={r.user} self={false} />
) : (
<div className="ue-hint">이 PC 녹음 기록에 없는 사람입니다. 음성채널에서 한 번 녹음되면 색 · 라이엇 ID · 녹음 제외를 바꿀 수 있습니다.</div>
)}
{r.user && (
<Link className="mini-btn" to={`/users/${r.id}`}>
기록 보기
</Link>
)}
{sup && role !== 'superadmin' && (
<div className="adm-acts">
<div className="ue-label">앱 사용 (게임 PC 앱 로그인)</div>
{role ? (
<>
<button className="btn sm" disabled={busy} onClick={() => void act(() => api.adminSetRole(r.id, role === 'admin' ? 'user' : 'admin'))}>
{role === 'admin' ? '관리자 → 앱 유저로' : '앱 유저 → 관리자로'}
</button>
<button
className="btn sm danger"
disabled={busy}
onClick={() => {
if (window.confirm(`${r.name} 님의 앱 등록을 해제할까요? 그 사람의 겜녹이 앱이 바로 잠깁니다.`)) void act(() => api.adminRemoveUser(r.id));
}}
>
등록 해제
</button>
</>
) : (
<>
<button className="btn sm" disabled={busy} onClick={() => void act(() => api.adminAddUser(r.id, 'user'))}>
앱 유저로 등록
</button>
<button className="btn sm" disabled={busy} onClick={() => void act(() => api.adminAddUser(r.id, 'admin'))}>
관리자로 등록
</button>
</>
)}
</div>
)}
{msg && <div className="ue-msg bad">{msg}</div>}
</div>
)}
</div>
);
}
function AddUser({ onRegs }: { onRegs: (u: AppUserRow[]) => void }) {
const [id, setId] = useState('');
const [role, setRole] = useState<'user' | 'admin'>('user');
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const ok = /^\d{17,20}$/.test(id.trim());
return (
<form
className="adm-add"
onSubmit={(e) => {
e.preventDefault();
if (!ok) return;
setBusy(true);
setMsg(null);
api
.adminAddUser(id.trim(), role)
.then((r) => {
onRegs(r.users);
setMsg({ ok: true, text: '등록했습니다. 그 사람은 이제 겜녹이 앱에 로그인할 수 있습니다' });
setId('');
})
.catch((e) => setMsg({ ok: false, text: errText(e) }))
.finally(() => setBusy(false));
}}
>
<div className="ue-label">디스코드 아이디로 앱 유저 등록</div>
<div className="ue-row">
<input className="ue-input mono" value={id} inputMode="numeric" placeholder="디스코드 아이디 (17~20자리 숫자)" onChange={(e) => setId(e.target.value)} aria-label="디스코드 아이디" />
<select className="ue-input adm-sel" value={role} onChange={(e) => setRole(e.target.value as 'user' | 'admin')} aria-label="역할">
<option value="user">앱 유저</option>
<option value="admin">관리자</option>
</select>
<button className="btn sm primary" disabled={busy || !ok}>
등록
</button>
</div>
{msg && <div className={`ue-msg${msg.ok ? ' ok' : ' bad'}`}>{msg.text}</div>}
</form>
);
}

View File

@@ -188,7 +188,7 @@ function MatchRow({ x, on, running, onClick }: { x: CulpritMatchItem; on: boolea
<small>
{m.mode} · {fmtWhen(m.startedAt)}
{m.endedAt ? ` · ${fmtDuration(m.endedAt - m.startedAt)}` : ''}
{x.eligibility.reasons[0] ? ` · ${x.eligibility.reasons[0]}` : ''}
{x.eligibility.reasons[0] ? ` · ${x.eligibility.reasons[0]}` : x.eligibility.notes?.[0] ? ` · ${x.eligibility.notes[0].split(':')[0]}` : ''}
</small>
</span>
<span className={`cu-score ${m.win === null ? '' : m.win ? 'win' : 'loss'}`}>{score}</span>
@@ -236,7 +236,8 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM
[true, m.game === 'valorant' ? '킬 · 스파이크 · 라운드 결과 이벤트' : '킬 · 오브젝트 이벤트', `${s.events}개`],
[e.state !== 'pending' || !e.reasons[0]?.startsWith('음성 변환'), '음성 대화 (텍스트 변환 완료)', `${s.utterances}문장`],
[true, '인게임 채팅 (팀 · 전체)', `${s.chats}개`],
[!e.reasons.some((r) => r.startsWith('녹음')), '녹음이 경기 시작부터 끝까지 이어짐', ''],
// 녹음이 없거나 끊겨도 분석은 된다 (v1.11.0 앱): 빠진 것만 ✕ 로 보이고 아래 안내를 단다
[!e.reasons.some((r) => r.startsWith('녹음')) && !e.notes?.length, '녹음이 경기 시작부터 끝까지 이어짐', e.notes?.length ? '없어도 분석 가능' : ''],
];
return (
<>
@@ -261,7 +262,7 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM
<section className="panel">
<h4>
<span>분석에 쓰는 기록</span>
<span className={`cu-st ${e.state}`}>{e.state === 'ready' || e.state === 'done' ? '모두 있음' : STATE_LABEL[e.state]}</span>
<span className={`cu-st ${e.state}`}>{e.state === 'ready' || e.state === 'done' ? (e.notes?.length ? '분석 가능' : '모두 있음') : STATE_LABEL[e.state]}</span>
</h4>
{checks.map(([ok, label, val]) => (
<div key={label} className={`cu-check${ok ? '' : ' no'}`}>
@@ -272,6 +273,7 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM
))}
{!s.extraStats && <div className="dim small cu-note">이 경기는 피해량 · 시야 같은 추가 지표가 없어 기본 기록으로 분석합니다.</div>}
{e.reasons.length > 0 && <div className="cu-reason">{e.reasons.join(' · ')}</div>}
{!!e.notes?.length && <div className="dim small cu-note">{e.notes.join(' · ')}</div>}
<div className="dim small cu-note">음성 파일은 7일 뒤 지워져도 괜찮습니다. 분석은 텍스트로 합니다.</div>
</section>
<section className="panel">

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