44 Commits

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:11:53 +09:00
EJClaw
2ddba2e4e5 README · 테스트 기록: v1.3.1 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:05:55 +09:00
EJClaw
0e0a2723e3 범인찾기 v1.3.1: OP.GG 세션 재시작 · 조회 실패 구분 · LOL.PS 라인전 10/15분
- opgg.ts: 세션 404 → 새 initialize 후 한 번 다시 (MCP 규격), 실패를 '경기 없음'과 나눠 meta.opgg.error · 화면 · 지시문에 반영
- rating.ts: 라인전을 LOL.PS 원문 정의대로 10 · 15분 맞라이너 CS · 골드 · 경험치 차로
- tools/opscore-fit/README.md: OP.GG(롤 · 발로란트) · LOL.PS 원문 인용과 구현 대응
- 테스트: 세션 재시작 · 503 · 일부 실패 · 서버 메타, 라인전 10/15분

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:57:00 +09:00
EJClaw
34b1822426 README · 테스트 기록: v1.3.0 릴리스 · 사이트 배포
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:49:44 +09:00
EJClaw
be893173a1 앱 v1.3.0: 범인찾기 실제 E2E (Claude Opus 5.5 high + OP.GG) · README · 테스트 기록
- app/scripts/culprit-real-e2e.mts: 실제 앱 코어 → 사이트 서버 → 실제 Claude API · 실제 OP.GG MCP → 결과 화면
  발로란트 시연 경기 42초 $0.146 (OP.GG 없음 → 기록 점수), 롤 실제 랭크 경기 36초 $0.109 (OP.GG 10명 찾음)
- 버전 1.3.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:40:43 +09:00
EJClaw
dc546951b5 범인찾기 C5: OP.GG 실제 OP스코어 찾기 · 지시문 v1.2 · 화면에 전적 사이트 점수
- site/server/src/opgg.ts: OP.GG 공식 MCP 로 이 경기를 찾아 실제 OP스코어를 붙인다 (롤: 시작 시각 · 길이로 경기 찾고 10명 op_score · 순위, 발로란트: 경기 UUID 로 선수마다 opScore). 내전 · 실패면 기록 점수만으로 계속
- 진행 단계에 'OP.GG 점수 찾는 중', 결과 meta.opgg (찾음 / 못 찾은 이유), CULPRIT_OPGG=0 이면 끔
- 지시문 v1.2: 평점은 전적 사이트 점수(OP.GG 실제 > 기록 점수)에서 출발해 승부처 · 역할 · 경제 · 소통으로 더하고 뺀다, 2점 넘게 다르면 근거, 범인 후보는 점수 낮은 사람부터 · 최하위가 아니면 이유
- 화면: 참가자 목록에 기록 점수 · MVP/ACE, 결과에 기록 점수 · 팀 순위 · OP.GG 점수 · 강점/약점 · 롤 15분 라인전
- 기록이 깨진 경기는 점수를 내지 않는다

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:36:07 +09:00
EJClaw
f8916829e1 범인찾기 C4: 기록 점수 (OP.GG OP스코어 방식) + LOL.PS 라인전
- packages/shared/src/rating.ts: 발로란트(라운드 승률 · KAST · ACS · 피해 격차) · 롤(킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드) 0~10 점수, 경기/팀 순위, MVP · ACE, 점수를 올리고 깎은 지표, 롤 15분 맞라인 비교
- 계수: OP.GG 공식 MCP 로 받은 실제 경기의 OP스코어에 맞춤 (tools/opscore-fit). 교차 검증 발로란트 상관 0.968 · 오차 0.49, 롤 상관 0.943 · 오차 0.60 · 팀 최하위 일치 85%
- 발로란트 경기 상세에 KAST 라운드 수(5초 트레이드) · 받은 피해 저장
- AI 자료에 '# 기록 점수' 칸, 참가자 줄에 KAST · 피해 격차, OP.GG 에서 경기를 찾을 정보(lookup), 참가자에 태그 · 기록 점수

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:29:59 +09:00
EJClaw
685e6a7ebe docs: 계획서 v1.2 — 정해 주신 8가지 반영, 실제 화면, 고정 프롬프트 토큰 실측으로 비용 재계산
- 범인 = 가장 못함 + 가장 발목 + 패배 원인 종합, 분석 버튼 = 등록된 앱 유저 이상, Opus 5.5 · 중간맛, TTS 안내 문구
- 리플레이 동기화: API(공식 · 비공식)로 시간을 읽을 수 있을 때만, OCR · game.cfg 수정 없음 → R0 는 API 확인만
- 화면 1~3 을 실제 구현 화면(시연 데이터 + 실제 Claude 결과)으로 교체, AI 자료 예시를 앱이 만든 실제 줄로
- 지시문 · 지식 묶음 · 출력 형식 실측 6,649 / 8,204 토큰 → 경기당 $0.40, $100 로 약 237경기 (v1.1 248)
- 9장 진행 상황(C1~C3 완료), 10장 정한 것 · 남은 일, 부록은 site/server/prompt 원문

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:41:51 +09:00
EJClaw
1cf7d7ebce 범인찾기 C3: 사이트 🔍 범인찾기 탭 · 결과 화면 · 경기 화면 버튼
- 경기 목록(분석 가능 · 분석 완료 · 준비 중 · 기록 부족 + 이유), 분석에 쓰는 기록 · 참가자(음성 표시) · 예상 비용 · 남은 예산 · 오늘 남은 횟수
- 진행 단계(기록 모으기 → AI가 읽는 중 → 근거 확인 → 완료) 실시간 표시, 실패 이유 표시
- 결과: 한 줄 요약 · 확신도, 팀별 범인 카드(이유 + 근거: 대화 ▶ 듣기 · 킬/라운드 → 타임라인 · 스탯 → 스코어보드), 10명 평점 · 태그 · 한 줄 평, 휴대폰 한 줄 배치
- 다시 분석은 관리자에게만 버튼, 예전 앱이면 "앱을 업데이트해 주세요"
- app/scripts/culprit-shots.mts: 실제 앱 코어 + 사이트 서버 + 헤드리스 브라우저로 화면 확인 (CSP 위반 · 오류 없음)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:35:12 +09:00
EJClaw
dc67f2105b 범인찾기 C2: 사이트 서버 Claude 호출 · 근거 확인 · 예산 장부
- POST /api/culprit/matches/:id/analyze: 등록된 앱 유저 이상(다시 분석은 관리자), 월 $100 · 하루 20회 · 중복 잠금
- Claude Opus 5.5 (생각 high, 구조화 출력, 출력 32k 상한, 거절 시 서버 측 fallback), 지시문 + 게임별 지식 묶음(자동 갱신 칸은 공식 데이터로 하루 한 번)
- 결과 확인: 10명 · 0.5 단위 점수 · 태그 · 팀마다 범인 1명(팀 최저점) · 없는 근거 번호 제거, 범인 근거가 안 맞으면 한 번 다시
- 비용 장부(culprit-ledger.json)는 토큰 · 비용만, 진행 단계는 실시간 알림(culprit.progress)
- 지시문 v1.1: 범인 = 가장 못함 + 가장 발목 + 결과의 원인 종합 판단, 자료 약어 설명 추가
- 배포: Dockerfile 에 prompt/ 복사, ANTHROPIC_API_KEY 넣는 스크립트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:27:59 +09:00
EJClaw
de64f9818d 범인찾기 C1: 경기 지표 보강, 분석 가능 판정, AI 자료 만들기, 결과 저장 + 녹음 안내에 AI 분석 문구
- 발로란트: 준 피해 · 헤드샷 · 첫킬/첫데스 · 설치/해체 · 스킬 사용 · 요원 역할, 라운드별 공수 · 장비 값 · 선수별 킬/피해
- 롤: 포지션(추정) · 챔피언 피해 · 받은 피해 · 시야 · 와드 · 오브젝트/포탑 피해 · CC · 10/15분 CS/골드/경험치
- culprit.ts: 녹음 공백 1분 · 경기 결과 · 음성 변환 판정, 근거 번호([u][e][c][r][s:P])가 달린 압축 텍스트, culprit_analyses 표
- API: /api/culprit/matches(목록 · 상세), /api/culprit/internal/*(사이트 서버 전용, x-gvr-internal 헤더)
- 녹음 안내 기본 문구에 "녹음된 대화는 AI 경기 분석에 쓰일 수 있어요" 추가, 기본 음성 다시 합성, 예전 기본 문구는 자동 교체

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:20:52 +09:00
EJClaw
b22e55cc64 docs: 계획서 v1.1 정정 — 발로란트 리플레이 지원 범위(12.10), 비용 5~95% 범위 표기, 롤 경기 식별은 R0 검증 대상
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:49:43 +09:00
EJClaw
639cb73a3c docs: 계획서 v1.1 — 리플레이 동기화, 범인찾기 프롬프트 · 지식 묶음 초안
- 리플레이 동기화 장: 롤 공식 Replay API(양쪽), 발로란트 OCR(한쪽, R0 검증 필요), 팝업 · 동기화 창 시안 2장
- prompt/: system.md, knowledge-valorant.md, knowledge-lol.md(패치 16.20.1 스냅샷), output-schema.json
- 비용 계산에 프롬프트 실측 길이 반영 ($100 ≈ 248경기)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:46:43 +09:00
EJClaw
2bb7d9909b docs: 범인찾기 탭 계획서 v1.0 (화면 시안 3장, $100 비용 몬테카를로 추정)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:36:32 +09:00
EJClaw
1429f74074 봇 중계: 연결한 뒤 권한을 잃으면 음성 연결을 끊는다
- 음성 연결을 가진 앱과 그 채널을 기록하고, 다시 확인해서 그 유저가 더는 들어갈 수 없으면
  음성 접속 정보 전달을 멈추고, 봇을 빼고(op 4 null), 앱에 taken 을 보낸다 (revoke)
- 다시 확인하는 때: 탈퇴 · 추방 · 역할 · 채널 권한 변경 이벤트(BotSource 'access', discord.js GuildMemberRemove/Update ·
  ChannelUpdate/Delete · GuildRoleUpdate/Delete · GuildDelete), vserver/vstate 를 넘기기 직전(봇이 옮겨진 채널 기준), 30초 주기
- 서버 멤버가 아니게 되면 지켜보기도 watch_denied 로 끊는다
- 테스트 (site/server/test/bot-broker.test.ts): 허용 → 연결 → 회수(탈퇴 · 채널 권한 제거 · 이벤트 없이 바뀜 · 권한 없는 채널로 옮겨짐)
  → 전달 차단 · 봇 퇴장 · 알림. 고치기 전 코드에서는 4건 모두 실패

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 11:34:45 +09:00
EJClaw
6721db23ac 보안 리뷰 반영: 봇 중계 유저별 서버 · 채널 권한, 인증서 검증 우회 차단
봇 중계 권한 (앱 유저의 디스코드 아이디 기준)
- 서버 목록 · watch: 그 유저가 가입한 서버만. 아니면 watch_denied (명령 등록 · 멤버 목록도 거절)
- 채널 · 음성 상태: 그 유저가 볼 수 있는(ViewChannel) 채널만. 볼 수 없는 채널로 옮기면 "나감"으로 가린다
- 음성 참여 op 4: 그 유저가 들어갈 수 있는(ViewChannel + Connect) 음성채널만
- /녹음시작 은 그 음성채널에 들어갈 수 있는 유저의 PC 로만, 다른 PC 로 가는 명령에는 볼 수 없는 채널 이름을 넣지 않는다

인증서
- 사이트 서버 https/wss(로그인 · 기기 등록 · 봇 중계 · 기기 중계)는 Node 내장 Mozilla 루트만 믿고 검증을 항상 켠다 (core/util/secure-http.ts)
  NODE_TLS_REJECT_UNAUTHORIZED=0 · 시스템 인증서 저장소의 가짜 루트로 엿볼 수 없다
- 시작할 때 NODE_TLS_REJECT_UNAUTHORIZED 를 지운다 (Electron main · 헤드리스 코어). fuses 로 막히지 않는 변수
- win smoke: 내장 루트만으로 실서버 https 가 검증되는지 확인 (siteTls)

테스트: 봇 중계 권한 1건(가입하지 않은 서버 · 비공개 채널 · 연결 권한 없는 채널 · 명령), 자체 서명 서버 + 검증 끄기 변수 1건(대조군 포함)
login-e2e 친구 계정을 실제 F&L 멤버(테스트봇)로

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 11:19:13 +09:00
EJClaw
b90a895501 앱 v1.2.2 · 사이트: 통신 · 데이터 보안 강화
앱
- 사이트 서버 주소는 https 만 (127.0.0.1 · localhost 만 http 허용). 로그인 · 봇 중계 · 기기 중계 · 기기 등록 모두
  암호화되지 않은 주소로는 아무것도 보내지 않고, 설정에서도 http 주소를 거절한다 (core/util/secure-url.ts)
- Riot 로컬 API 의 인증서 검증 예외를 이 PC 안 주소로만 제한 (local 을 잘못 넘겨도 바깥 주소는 거절)
- 설정 창: 바깥 주소로 이동 · 리다이렉트 · webview 를 막고 브라우저로 연다.
  막기 전에는 이동한 바깥 페이지에서도 window.gvr 가 살아 있었다 (login-e2e 로 재현 · 확인)
- 권한 요청은 클립보드 쓰기만 허용
- Electron fuses: RunAsNode · NODE_OPTIONS/NODE_EXTRA_CA_CERTS · --inspect 끄기, app.asar 만 로드, 쿠키 암호화

사이트 서버
- CSP (이 사이트 스크립트 · 접속만, frame-ancestors none), nosniff, COOP
- 실시간 WebSocket(/ws) 은 이 사이트 출처만 (Cross-Site WebSocket Hijacking 방지)
- 로그인 세션 토큰은 해시로만 저장 (예전 파일은 읽을 때 해시로 바꾸고 로그인 유지)
- 요청 로그에서 OAuth code · state, 앱 로그인 요청 아이디, 쿼리 값 제거
- IP 별 횟수 제한: 기기 등록 코드 10회 실패 · 앱 로그인 시작 10회 / 10분

검증: 앱 테스트 28 · 서버 테스트 9, login-e2e 20/20, demo-stack 화면 7종 CSP 위반 0 · 실시간 잠금/해제 정상

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:54:33 +09:00
EJClaw
68e0b43b77 봇 중계: 지켜보는 앱이 없는 서버의 슬래시 명령은 서버가 받지 않는다
봇 토큰을 직접 쓰는 v1.1.0 PC 가 아직 켜져 있으면 같은 명령을 서버와 PC 가 함께 받는다.
서버가 먼저 응답(defer)하면 PC 의 응답이 실패해 /녹음시작 이 동작하지 않으므로, 그 서버를 지켜보는 v1.2.1 앱이 있을 때만 받는다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:42:06 +09:00
EJClaw
6a03c67b54 앱 v1.2.1: 겜녹이 봇 토큰을 앱에 보내지 않고 사이트 서버가 봇을 대신 연결
- 사이트 서버: discord.js 로 디스코드 게이트웨이에 한 번 붙고(discord-source.ts), 로그인한 앱에 WS /app/bot/ws 로 중계(bot-broker.ts)
  · 앱이 보낸 op 4 는 지켜보는 서버의 음성채널 참여 · 나가기만 허용하고 필드를 다시 만들어 보낸다
  · 디스코드가 준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)는 음성을 가진 앱에만 넘긴다. 음성은 앱 ↔ 디스코드로 바로
  · 한 서버의 봇 음성은 마지막으로 요청한 앱이 가져가고 이전 앱은 taken. 이전 앱의 늦은 나가기 무시, 음성 가진 앱이 끊기면 봇을 뺀다
  · 슬래시 명령은 서버가 받아 defer 후 그 서버를 지켜보는 앱으로 보낸다
  · 등록 해제 · 로그아웃하면 그 유저의 중계 연결을 바로 끊는다 (4401), 30초마다 다시 확인
- /app/me 에서 botToken 제거. 앱은 v1.2.0 이 저장해 둔 봇 토큰을 시작할 때 지운다
- 앱: BotGateway 로 디스코드 연결을 분리 (RemoteGateway = 겜녹이 봇 서버 중계, LocalGateway = 다른 봇 토큰 직접 연결)
  Bot 은 discord.js 객체 대신 이 인터페이스만 쓴다. 중계가 로그인 만료를 알리면 바로 다시 확인해서 잠근다
- 로그인 확인: 잠그라는 응답(401 · 403)은 겹친 확인 때문에 늦게 와도 같은 토큰이면 따른다
  (겹친 두 번째 확인이 401 을 받아 "등록되지 않은 아이디" 대신 "로그인 만료"로 잠기던 문제). 미등록 화면은 다시 확인해도 유지
- 테스트: 봇 중계 4건(토큰 미노출 · 음성 정보 전달 · 다른 PC 인계 · 명령 라우팅 · 해제 시 끊김), 겹친 확인 1건
  실제 디스코드: voice-e2e GVR_E2E_RELAY=1 (서버 중계로 따라 들어가 녹음 · STT · 녹음 제외), login-e2e 19/19

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:30:14 +09:00
EJClaw
a2487e6241 앱 로그인: 늦게 도착한 이전 확인 응답이 잠금을 풀지 못하게
- 확인 요청마다 세대 번호를 붙이고, 새 확인 · 잠금(등록 해제) · 로그아웃 · 새 로그인 뒤에 도착한
  이전 응답(성공 · 실패 모두)은 버린다. 보낸 토큰과 지금 토큰이 다르면 역시 버린다
- 로그아웃은 서버 응답을 기다리기 전에 로컬에서 먼저 지우고 잠근다
- 회귀 테스트: 등록 해제 뒤 / 로그아웃 뒤 늦은 200 (이전 코드에서 둘 다 실패 확인)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:23:48 +09:00
EJClaw
c2a5547a68 앱 v1.2.0: exe 디스코드 로그인 · 유저 등록 · 관리자 페이지
- 사이트 서버: 앱 로그인(/auth/app/begin·start·poll, 기존 OAuth 콜백 재사용), 앱 토큰(/app/me, 해시 저장),
  유저 등록 API(/app/admin/users, 등록·역할·해제는 최고 관리자만, 목록은 관리자도). 최고 관리자 2명 고정
- 앱: 등록된 계정으로 로그인해야 코어(봇·녹음·사이트 연결)를 띄운다. 미등록이면 "등록되지 않은 아이디" + 아이디 표시.
  10분마다 재확인, 등록 해제 시 즉시 잠금. 서버 연결 실패 시 마지막 확인 후 3일 유예
- 겜녹이 봇 토큰을 exe 에 넣지 않고 로그인한 등록 유저에게 서버가 내려준다 (잠기면 삭제). win-ci 토큰 주입 제거
- 관리자 탭(유저 등록·목록·접속 기록), 관리자 전용 설정(봇 변경·TTS 안내·보관 기간·사이트·학습 데이터·파인튜닝)은
  일반 유저에게 잠금 표시 + 메인 프로세스에서 차단
- 테스트: 서버 앱 로그인 2건, 앱↔서버 통합 3건, Electron 로그인 E2E 스크립트(scripts/login-e2e.mts)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:08:44 +09:00
EJClaw
4d31cfc16a v1.1.0 리뷰 반영: 봇 전환 중 늦은 연결 결과 무시, win-ci 토큰 자동 정리, smoke 에 봇 ready 확인
- DiscordTab: 연결 테스트에 요청 번호를 두어 봇을 바꾼 뒤 도착한 이전 응답(성공·서버 목록·오류·진행 표시)을 버린다
- 다른 봇으로 바꿨는데 토큰이 아직 없으면 오류 대신 안내 문구를 보인다
- mock-gvr: testBotToken 이 부를 때의 모드로 토큰을 고르게 (실제 IPC 와 같게)
- win-ci: run.sh 가 토큰 형식 검사 후 systemd 사용자 유닛으로 자동 복원(restore.sh --wait)을 띄운다
- gvr.ps1: 토큰 환경변수 제거를 finally 로, 끝나면 게스트의 stage2 사본과 빌드 산출물을 지운다
- smoke: 봇 로그인이 끝나길 최대 30초 기다리고, 기본 봇이 든 빌드는 ready 여야 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 05:30:58 +09:00
EJClaw
165fc3a710 테스트: 가짜 기본 봇 토큰 앞부분을 실제 봇 ID 와 무관한 값으로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 04:55:10 +09:00
EJClaw
35d2cab792 앱 v1.1.0: 겜녹이 봇 기본 연결 + '다른 봇으로 진행하기'
- 설정 discord.botMode (builtin 기본 / custom). 겜녹이 봇은 토큰 입력 없이 연결
- 겜녹이 봇 토큰은 저장소에 두지 않고 빌드 때 GVR_BUILTIN_BOT_TOKEN 에서 읽어 감춘 값으로 박는다
- 마법사·디스코드 탭에 봇 선택 카드, 다른 봇일 때만 토큰 입력. 오가도 넣은 토큰 유지
- v1.0.0 에서 토큰을 넣어 쓰던 설치는 custom 으로 이어짐
- win-ci full 빌드가 서버 비밀 저장소에서 토큰을 넣고, smoke 에 기본 봇 로그인 결과 기록
- 테스트 6개 추가 (기본·다른 봇·전환·이전 설치·기본 봇 없는 빌드·개발 env)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 04:54:48 +09:00
245 changed files with 18520 additions and 1119 deletions

107
README.md
View File

@@ -6,8 +6,106 @@
- 게임 PC: 포터블 `GameVoiceRecorder.exe` 하나로 디스코드 봇, STT 엔진, 기록 저장소, 설정 화면이 돈다
- 사이트 서버: 디스코드 로그인(서버 멤버만), 게임 PC 연결 확인·잠금 화면, 기록 중계 (기록은 게임 PC 에만 있음)
- 설계·계획: [`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.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0) (`GameVoiceRecorder-1.0.0-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.0.0-portable.exe`)
- Windows 실행 파일: Gitea 릴리스 [v1.4.1](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.4.1) (`GameVoiceRecorder-1.4.1-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.4.1-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
## 로그인 · 관리자 (v1.2.0~)
- exe 는 **등록된 디스코드 계정으로 로그인**해야 열린다. 로그인 버튼 → 브라우저에서 디스코드 로그인 → 사이트 서버(gvr.tkrmagid.kr)가 등록 명단을 확인한다. 등록되지 않은 아이디면 "등록되지 않은 아이디입니다"와 디스코드 아이디를 보여 주고 앱을 열지 않는다.
- 역할: **최고 관리자**(`293719842274541579`, `1352267557213573160`, 서버에 고정) · **관리자** · **유저**. 유저 등록 · 역할 변경 · 등록 해제는 최고 관리자만, 등록 명단 보기와 관리자 전용 설정은 관리자도 할 수 있다.
- 설정 창 **🛡️ 관리자** 탭(관리자에게만 보임): 유저 등록(디스코드 아이디 + 역할), 등록 계정 목록(역할 · 마지막 접속 · 앱 버전 · 등록한 사람), 관리자 전용 기능 목록.
- 관리자 전용 (일반 유저 화면에서는 🔒 잠김, 메인 프로세스에서도 막음): 다른 봇으로 바꾸기 · 봇 토큰, 녹음 안내(TTS) 끄기 · 문구, 음성 보관 기간, 사이트 서버 주소 · PC 이름 · 등록/해제, 학습 데이터 삭제, 파인튜닝.
- 앱은 시작할 때와 10분마다 등록 여부를 다시 확인한다. 등록이 해제되면 바로 잠그고 봇 · 녹음 · 사이트 연결을 멈춘다. 사이트 서버에 못 붙으면 마지막 확인 뒤 3일까지는 그대로 쓴다.
- 서버 쪽: `site/server/src/app-auth.ts` (`/auth/app/*`, `/app/me`, `/app/admin/users`), 앱 쪽: `app/src/core/auth.ts`, 권한 목록: `app/src/core/roles.ts`. 로그인 E2E: `app/scripts/login-e2e.mts`.
## v1.4.1 바뀐 점
- 잡음으로 배운 문장 비교: v1.4.0 은 편집 거리로 비교해서, 배운 문장 뒤에 짧은 실제 말("네", "가자", "아니")이 붙은 발화까지 잡음으로 지웠다. 이제 글자 수가 같고 15% 안 글자만 바뀐 것(인식이 한두 글자 다르게 나온 것)만 같은 문장으로 본다
## v1.4.0 바뀐 점
- 사이트 발화 우클릭 → **삭제…**: 확인 창에서 "잡음이라 삭제" 또는 "그냥 삭제". 관리자나 말한 사람만 지울 수 있고, 글 · 음성 파일 · 교정 학습 데이터를 게임 PC 에서 지운다 (`POST /api/utterances/:id/delete`)
- "잡음이라 삭제"는 인식된 문장을 `noise_phrases` 에 배운다. 다음에 같은 문장(띄어쓰기 · 문장부호 무시, 8글자 이상이면 글자 수가 같고 15% 안 글자만 바뀐 것까지. 앞뒤에 말이 붙으면 그대로)이 인식되면 잡음(`noise_reason='learned'`)으로 숨기고 파일을 지운다. 배운 문장은 단어사전 화면에서 보고 지운다 (`GET/DELETE /api/noise-phrases`)
- 사이트 효과음: "새 발화 알림" · "재생 시작"을 기본으로 끈다 (예전에 저장한 설정도 한 번 꺼 줌, 그 뒤 다시 켜면 그대로)
## v1.3.9 바뀐 점
- 기록 zip 받아오기: 표시 이름에 `..` 이 있으면(예: `하늘..별`) 그 이름이 들어간 녹음 파일을 "음성 파일 이름이 잘못되었습니다"로 거절해, 내보낸 zip 을 다시 넣지 못했다. zip 안 이름은 꺼낼 때 찾는 열쇠로만 쓰고 이 PC 에 쓸 경로는 발화 ID 로 만들므로, 폴더 구분자(`/`, `\`)만 막는다
## v1.3.8 바뀐 점
- **녹음 파일 이름**: `날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg` (예: `2026-10-16_04-03-16_사금향_발로란트_경쟁전_어센트_R7_0mv9….ogg`, 롤은 라운드 대신 게임 시간 `12분30초`, 경기 밖은 `…_사금향_경기밖_….ogg`). 시각은 게임 PC 시각, Windows 에서 못 쓰는 글자는 뺀다. `app/src/core/audio-names.ts`
- 녹음이 끝나면 바로 이 이름으로 저장하고(경기 중에는 지금 라운드), 경기가 끝나 경기 상세(정확한 라운드)가 오거나 표시 이름이 바뀌면 다시 맞춘다. 예전 파일도 처음 켤 때 바꾼다
- 음성 인식이 그 파일을 읽는 중이거나 대기열에 있으면 바꾸지 않고, 변환이 끝난 뒤 바꾼다. 다른 프로그램이 파일을 열고 있으면 다음에 다시 한다
- 기록 zip 안 `audio/` 도 같은 이름, 사이트 ogg 다운로드 · 자세한 정보도 같은 이름 (v1.3.7 zip 의 `audio/<발화ID>.ogg` 도 그대로 받는다)
## v1.3.7 바뀐 점
- **기록 관리** (사이트 "기록" 탭, `site/web/src/pages/RecordsPage.tsx`): 기록을 경기 하나 = 묶음 하나로 보고, 경기 밖 대화는 녹음 세션 안에서 경기 사이마다 묶는다. 다음 경기가 30분 안에 시작하면 "경기 전 대화", 지난 경기가 30분 안에 끝났으면 "경기 후 대화", 아니면 "게임 밖 대화". 묶음을 골라 한 번에 zip 내려받기 · 지우기(관리자) · zip 받아오기(관리자). 앱 `app/src/core/bundles.ts`, API `GET /api/bundles` · `GET /api/bundles/export?ids=` · `POST /api/bundles/delete` · `POST /api/bundles/import`
- **zip 형식** `gvr-bundle` v1: `manifest.json`(형식 · 묶음 · 개수), `data.json`(유저 · 세션 · 경기 · 라운드 · 이벤트 · 범인 분석 · 발화), `audio/<발화ID>.ogg`, `대화.txt`. 받아오기는 형식 · 버전 · 발화 ID · 말한 사람 · 시각 · 경기 연결 · 음성 파일(ogg 머리) · 개수를 모두 확인하고 하나라도 빠지면 아무것도 넣지 않고 "받아오기 실패: (이유)"로 끝낸다. 이미 있는 발화는 건너뛴다. 받아온 녹음의 보관 기간은 받아온 날부터 센다 (`utterance_imports`)
- 사이트 ↔ 게임 PC 중계: 큰 zip 을 1MB 조각으로 주고받는다 (사이트 서버 → 앱 요청 본문, 앱 → 사이트 서버 응답 모두)
## v1.3.6 바뀐 점
- **목소리 깨짐**: 녹음기가 디스코드 패킷이 "도착한 간격"으로 말 사이 쉼을 채웠다. 게임 중(CPU 부하)에는 패킷이 2~3개씩 몰려 와서 말 중간에 20ms 무음이 계속 끼었다 (사용자 파일: 실제 7.0초 발화가 8.5초, 패킷 3개 중 1개가 무음). 이제 RTP 타임스탬프로 패킷 자리를 정한다 (`recorder.ts` `tapRtp` · `Utterance.place`). 예전 녹음은 처음 켤 때 한 번 끼운 무음을 빼고 다시 변환한다 (`ogg.ts` `removeInsertedSilence`)
- **말한 사람 "알 수 없음"**: 앱이 `users.updated` 를 빈 목록으로 보내 사이트가 유저 목록을 비웠다. 이제 실제 목록을 보낸다 (사이트도 빈 목록이면 다시 받아 옴)
- **잡음**: 목소리 없음 · 잡음에서 지어낸 문장 · 같은 말 반복은 사이트에 보이지 않고 ogg 도 지운다 (경기 중 실시간 판정은 경기 뒤 정밀 모델이 다시 본 다음). 로그에 "잡음 발화 … 숨김 · 음성 파일 삭제 (이유, 인식 문장)" 로 남는다. 목소리가 0.15초라도 있으면 Whisper 로 넘기고, 반복 고리는 한 번으로 줄여 남은 말을 보여 준다
- **시작 창**: 포터블 exe 를 푸는 동안 작은 그림 창(`assets/app/splash.bmp`), 앱이 켜지는 동안 "켜는 중" 창
- **녹음 안내 말 속도** 0.1~2.0 (Edge TTS 는 0.5~2.0, 그보다 느리면 워커 `tempo` 가 atempo 로 늘림)
- **사이트**: 재생 음량 0~200% · 발화 우클릭(재생 · 자세한 정보(원본 ogg 이름 · 게임 PC 경로 · 크기 · 인식 정보) · ogg 다운로드 · 내용 복사, 앱 `GET /api/utterances/:id/info`)
- **사이트 로그**: 사이트 서버가 `data/logs/site-날짜.log` 로 남긴다 (게임 PC 연결 · 끊김 · 기록 요청 결과 · 봇 중계 · 범인찾기 · 브라우저 오류). 관리자는 `https://gvr.tkrmagid.kr/logs` 에서 게임 PC 가 꺼져 있어도 보고 내려받는다 (잠금 화면 · 설정 메뉴에 링크). 14일 보관
- **지금 게임**: 앱 게임 연동 탭 · 사이트(머리글 · 타임라인 오른쪽)에 연결된 게임 · 상태(메뉴 · 대기열 · 요원/챔피언 선택 · 경기 중) · 모드 · 맵 · 라운드 · 점수 · 내 요원/챔피언 · KDA · 게임 시간
- 발로란트 데스매치 · 팀 데스매치 · 에스컬레이션: 킬 점수를 라운드로 착각해 "R63 승리" 같은 가짜 라운드와 에이스를 만들던 것 고침. 경기 상세에 선수 이름이 비어 오면 이름 서비스로 채운다 ("주인 계정 자동 연결: #" 고침)
## v1.3.5 바뀐 점
- **표시 이름 빈틈**: 표시 이름을 정하기 전에 시작한 범인 분석이 정한 뒤에 저장되면 결과 본문에 예전 이름이 남을 수 있었다 (이미 이름이 바뀐 유저는 다시 훑지 않았음). 이제 가린 예전 이름을 기억해 두고(`meta.hidden_names`), 분석을 저장할 때마다 · 이름을 다시 받을 때마다 모든 분석에서 바꾼다
- 상태 메시지 실제 확인: `site/server/scripts/presence-e2e.mts` (사이트 서버 코드로 봇을 빈 음성채널에 넣었다 빼며 확인)
## v1.3.4 바뀐 점
- **슬래시 명령 응답**: 그 디스코드 서버를 지켜보는 겜녹이 앱이 없으면 사이트 서버가 명령을 무시해서 디스코드에 "애플리케이션이 응답하지 않았어요"만 떴다 (봇 토큰을 직접 쓰는 옛 v1.1.0 PC 와 겹치지 않게 넣은 동작). 이제 1.5초 기다렸다가 아무도 받지 않았으면 이유를 답한다: 앱이 꺼져 있음 / 내 앱이 다른 서버를 녹음 대상으로 정해 둠 / 아직 연결 중. 앱은 서버가 권한을 다시 확인하다 지켜보기를 끊으면 1분 뒤 다시 요청한다
- **봇 상태 메시지**: 녹음 중(봇이 어느 서버에서든 음성채널에 있음)이면 빨간 상태(다른 용무 중) + "🔴 녹음 중", 아니면 "🎙️ 대기 중 · /녹음시작". 겜녹이 봇은 사이트 서버가, 다른 봇 모드는 앱이 바꾼다. 봇 하나가 여러 서버에 들어가 있어서 채널 이름은 넣지 않는다
## v1.3.3 바뀐 점
- **따라갈 사람 목록**: 녹음할 서버의 멤버가 모두 나온다. 내 계정이 맨 위, 그다음 관리자(최고 관리자 포함), 나머지는 이름순. 예전에는 봇이 서버를 지켜보기 전에 목록을 요청하면 사이트 서버가 거절했고 앱이 그 오류를 숨겨 "선택 안 함"만 보였다. 이제 가입한 서버면 바로 받고, 실패하면 오류와 다시 불러오기 버튼을 보여 준다. 녹음할 서버를 바꾸면 봇이 새 서버를 바로 지켜본다. 서버: `GET /app/admins`
- **롤 채팅은 API 로만**: 화면 글자 인식(OCR)을 앱 · 워커 · 빌드에서 모두 뺐다 (pywinrt · mss · Pillow 의존성 제거). 롤 클라이언트(LCU) API 로 챔피언 선택 · 게임 후 채팅을 받는다. 롤은 게임 중 전체 · 팀 채팅을 주는 API 가 없다 (LCU · 게임 클라이언트 API 모두, 비공식 포함). 게임 로그 파일(r3dlog)에 채팅이 남아 있으면 경기 뒤에 붙인다
- **표시 이름 (실명 숨기기)**: 디스코드 아이디마다 보일 이름을 정하면 사이트(로그인 이름 · 대화 기록 · 유저 목록), 앱, 범인 분석에 그 이름만 쓰고 이미 저장된 이름도 바꾼다. 앱 🛡️ 관리자 탭에서 최고 관리자가 정한다. 서버: `GET /app/names`, `PUT /app/admin/names`, `node dist/cli.js name <아이디> [이름]`
- 저장소의 시연 · 테스트 데이터, 화면 캡처, 계획서 PDF 에서 실제 이름을 빼고 가짜 이름(하늘)으로 바꿨다
## 디스코드 봇
- 기본은 **겜녹이 봇으로 진행**: 토큰을 넣지 않아도 로그인만 하면 바로 연결된다. 봇은 사이트 서버가 디스코드에 연결하고, 앱은 로그인 토큰으로 서버 중계(`/app/bot/ws`)를 받는다.
- **다른 봇으로 진행하기**(관리자만)를 고르면 직접 만든 봇 토큰을 넣는다 (암호화 저장). v1.0.0 에서 토큰을 넣어 쓰던 설치는 다른 봇 모드로 그대로 이어진다.
- v1.2.1 부터 **겜녹이 봇 토큰은 사이트 서버 밖으로 나가지 않는다** (v1.1.0 은 exe 에 감춰 넣었고, v1.2.0 은 로그인한 유저에게 내려줬다). 등록된 유저의 PC 에도 토큰이 없어서 PC 를 뒤지거나 통신을 가로채도 꺼낼 수 없다.
음성채널에 들어갈 때 서버가 디스코드에서 받은 일회용 음성 접속 정보만 그 PC 에 넘기고, 음성은 PC ↔ 디스코드로 바로 간다. 사이트 서버가 꺼져 있으면 겜녹이 봇은 쓸 수 없다 (다른 봇 모드는 상관없음). 구조: [`docs/dev/ARCHITECTURE.md` 8장](docs/dev/ARCHITECTURE.md)
- 빌드에 비밀값이 필요 없어 공개 릴리스에 올려도 된다. 등록되지 않은 사람은 exe 를 받아도 겜녹이 봇을 쓸 수 없다.
## 통신 · 데이터 보안 (v1.2.2~)
- 앱 ↔ 사이트 서버(로그인 토큰 · 기기 키 · 기록 중계 · 봇 중계)는 **https/wss 만** 쓴다. 사이트 서버 주소를 http 로 바꾸면 거절하고 아무것도 보내지 않는다 (이 PC 안 127.0.0.1 · localhost 만 예외, 개발용). `app/src/core/util/secure-url.ts`
- 사이트 서버 인증서는 앱에 들어 있는 Mozilla 루트 인증서로만 검증하고 검증을 끌 수 없다. `NODE_TLS_REJECT_UNAUTHORIZED=0`, Windows 인증서 저장소에 깐 가짜 루트 인증서(감시 · 프록시 프로그램)로는 통신을 엿볼 수 없다. 검증 끄기 변수는 시작할 때 지워서 사이트 밖 통신도 검증한다. `app/src/core/util/secure-http.ts`
- 겜녹이 봇 중계 권한: 앱 유저가 가입한 디스코드 서버, 그 유저가 볼 수 있는 채널만 보이고, 그 유저가 들어갈 수 있는 음성채널에만 봇을 부를 수 있다.
- 게임 연동(Riot 로컬 API)의 자체 서명 인증서 예외는 이 PC 안 주소에만 쓴다. Riot 원격 API 등 바깥 주소는 항상 인증서를 검증한다.
- exe(Electron) 잠금: `NODE_OPTIONS` · `NODE_EXTRA_CA_CERTS`(가짜 인증서를 끼워 통신을 엿보는 데 쓰임) · `ELECTRON_RUN_AS_NODE` · `--inspect` 를 무시하고 `app.asar` 만 읽는다 (Electron fuses). 설정 창은 앱 화면만 띄우고 바깥 주소는 브라우저로 연다. 권한 요청(마이크 · 카메라 등)은 거절한다.
- 사이트 서버: 보안 정책(CSP)으로 이 사이트 스크립트와 이 사이트로의 접속만 허용, 실시간 WebSocket 은 이 사이트에서 온 연결만, 로그인 세션 · 앱 토큰 · 기기 키는 해시로만 저장, 로그에서 로그인 code · state · 검색어를 지운다. 등록 코드 대입 · 로그인 요청 폭주는 IP 별로 막는다. HSTS · http→https 이동 · TLS 1.2 미만 차단은 앞단 프록시(NPMplus)가 한다.
- 디스코드 음성은 디스코드 자체 암호화(DAVE 종단간 암호화)로 간다.
## 🔍 범인찾기 (v1.3.2~)
끝난 경기를 고르고 "범인 분석"을 누르면 AI(Claude)가 그 경기의 음성 대화 · 킬 · 라운드/오브젝트 · 경제 · 채팅 · 10명 스탯을 읽고 10명 평점 · 태그 · 한 줄 평과 팀별 범인 1명(이유 + 근거)을 만든다. 근거를 누르면 그 순간의 음성 · 타임라인으로 간다. 계획서: [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf)
- 정한 것 (2026-10-15): 범인 = 가장 못함 + 가장 발목 + 결과의 원인을 종합해 팀마다 1명 · 분석 버튼은 등록된 앱 유저 이상(다시 분석은 관리자) · Claude Opus 5.5(생각 high) · 말투 중간맛 · 녹음 안내(TTS)에 "녹음된 대화는 AI 경기 분석에 쓰일 수 있어요" 추가
- **전적 사이트 계산법 참고**: 평점과 범인은 기록 점수에서 출발해 승부처 · 역할 · 경제 · 음성 소통으로 더하고 뺀다 (지시문 v1.2). 분석할 때 외부 전적 사이트에는 접속하지 않고, 앱이 경기 기록으로 직접 계산한다
- **기록 점수** (0~10, 모든 경기): OP.GG OP스코어 계산법을 따라 우리 기록으로 계산한 점수 + 경기/팀 순위 + MVP · ACE + 점수를 올리고 깎은 지표. 발로란트는 OP.GG 가 밝힌 입력(라운드 승률 · KAST · ACS · 피해 격차), 롤은 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드. OP.GG 는 가중치를 공개하지 않아서, 계수는 개발할 때 한 번 OP.GG 공식 MCP 로 받은 실제 경기 점수에 맞춰 정했다 (교차 검증: 발로란트 상관 0.97 · 평균 오차 0.49점, 롤 상관 0.94 · 0.60점 · 팀 최하위 일치 85%). `packages/shared/src/rating.ts`, 맞추는 도구 `tools/opscore-fit/`
- **LOL.PS 라인전**: LOL.PS 라인전 점수의 입력과 같은 10 · 15분 맞라이너 CS · 골드 · 경험치 차 (LOL.PS 점수 모델은 공개되지 않아 차이 값만). 참고한 원문 · 구현 대응: [`tools/opscore-fit/README.md`](tools/opscore-fit/README.md)
- 실제 E2E (2026-10-15, v1.3.2, `app/scripts/culprit-real-e2e.mts`): 실제 Claude Opus 5.5(생각 high), 외부 사이트 접속 없음. 발로란트 시연 경기 33초 · $0.138, 롤 시연 경기 36초 · $0.123. 기록 · [`docs/dev/test-results.md`](docs/dev/test-results.md)
- 리플레이 동기화: 공식 · 비공식 API 로 리플레이 시간을 읽을 수 있을 때만 넣는다 (화면 글자 인식(OCR) · 게임 설정 파일 고치기는 하지 않음). Windows 실기 확인 전이라 v1.3.x 에는 없다
- 앱: 경기 상세에서 추가 지표 저장(발로란트 피해량 · 받은 피해 · KAST · 첫킬 · 설치/해체 · 라운드별 장비, 롤 포지션 · 딜량 · 시야 · 10/15분 CS), "분석할 수 있는 경기" 판정(경기 결과 · 녹음 공백 1분 · 음성 변환), 근거 번호가 달린 AI 자료 만들기, 결과 저장(`culprit_analyses`). `app/src/core/culprit.ts`
- 사이트 서버: Claude API 키는 서버 환경 변수 `ANTHROPIC_API_KEY` 에만 (`deploy/site/set-anthropic-key.sh`). 권한 · 월 $100 · 하루 20회 · 중복 잠금, 구조화 출력, 근거 번호 확인, 비용 장부(토큰 · 비용만, 대화 내용 없음). `site/server/src/culprit.ts`, 지시문 · 지식 묶음 `site/server/prompt/` (지식 묶음의 요원 · 챔피언 목록은 공식 데이터로 하루 한 번 갱신)
- 화면: 사이트 🔍 범인찾기 탭 (`site/web/src/pages/CulpritPage.tsx`), 경기 화면의 "🔍 범인 보기". 화면 확인: `node --import tsx app/scripts/culprit-shots.mts`
## 진행 현황
@@ -17,17 +115,18 @@
| M1 녹음 + STT 기본 | 따라가기·명령 참여, TTS 안내, 유저별 녹음, 대기열 STT, /녹음제외·참여 | ✅ 완료 ([실음성 테스트](docs/dev/test-results.md)) |
| M2 사이트 서버 · 사이트 v1 | 디스코드 로그인, 연결 확인·잠금, 타임라인·따라 읽기·필터·검색·실시간 | ✅ 완료 · https://gvr.tkrmagid.kr 배포 |
| M3 발로란트 연동 | 경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과 시간, 경기 상세 | ✅ 완료 ([전체 스택 테스트](docs/dev/test-results.md)) |
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ✅ 완료 (Windows 실기 확인: [기록](docs/dev/test-results.md)) |
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ✅ 완료 (Windows 실기 확인: [기록](docs/dev/test-results.md)) · v1.3.3 에서 OCR 은 빼고 LCU API · 로그 파일만 씀 |
| M5 exe · 설정 · 모델 | 포터블 exe, 첫 실행 마법사, GPU 감지·모델 다운로드, 암호화 저장, 7일 삭제 | ✅ 완료 (Windows 빌드·실행 확인) |
| M6 단어사전 · UI/UX | 핫워드·교정 사전, 사이트 교정 반영, 테마·애니메이션·효과음 | ✅ 완료 ([사전 효과](docs/dev/test-results.md)) |
| M7 실사용 테스트 | 통합 테스트, 성능·안정화 | ✅ 완료 (GPU 실음성: CER 3.6%, 지연 1.05초 · [기록](docs/dev/test-results.md)) |
| M8 파인튜닝 | 교정 데이터 + 합성 음성 LoRA 학습, 오류율 비교 후 교체 | ✅ 완료 (GPU 시험 학습: CER 4.8% → 1.8%) |
| 범인찾기 (v1.3.x) | AI(Claude Opus 5.5 high) 10명 평점 · 팀별 범인 · 근거, 기록 점수(OP.GG OP스코어 계산법) · 10/15분 라인전(LOL.PS 정의) | ✅ 완료 (실제 Claude E2E, 사이트 배포, [v1.3.5](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.5) · 리플레이 동기화는 Windows 실기 확인 뒤) |
## 저장소 구조
```
app/ 게임 PC 앱 (Electron + Node.js 코어, TypeScript)
worker/ STT 워커 (Python, faster-whisper, OCR, 모델 관리, 파인튜닝)
worker/ STT 워커 (Python, faster-whisper, 롤 로그 채팅, 모델 관리, 파인튜닝)
site/server/ 사이트 서버 (Fastify, Discord OAuth2, 기기 중계)
site/web/ 사이트 화면 (React + Vite)
packages/shared/ 앱·사이트 공통 타입
@@ -51,5 +150,5 @@ deploy/site/deploy.sh # .5 배포 (deploy/README.md)
# 앱 코어 (헤드리스)
cd app && npm install && npm test
npm run core -- --diagnose # 게임 PC 진단 (GPU·STT 속도·Riot API·OCR)
npm run core -- --diagnose # 게임 PC 진단 (GPU·STT 속도·Riot API·롤 로그 채팅)
```

View File

@@ -10,6 +10,7 @@ fs.writeFileSync(
'// 자동 생성: schema.sql 사본 (npm run build 가 다시 만든다)\nexport const SCHEMA_SQL = ' + JSON.stringify(fs.readFileSync(path.join(root, 'src/core/db/schema.sql'), 'utf8')) + ';\n',
);
fs.rmSync(path.join(root, 'dist'), { recursive: true, force: true });
// 겜녹이 기본 봇 토큰은 exe 에 넣지 않는다. 로그인한 등록 유저에게 사이트 서버가 내려준다 (src/core/auth.ts)
const common = { bundle: true, platform: 'node', target: 'node22', format: 'cjs', sourcemap: true, alias: { '@gvr/shared': shared }, logLevel: 'info' };
await build({ ...common, entryPoints: ['src/main/main.ts'], outfile: 'dist/main.cjs', packages: 'external', external: ['electron'] });
await build({ ...common, entryPoints: ['src/main/preload.ts'], outfile: 'dist/preload.cjs', external: ['electron'] });

10
app/package-lock.json generated
View File

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

View File

@@ -1,7 +1,7 @@
{
"name": "gvr-app",
"productName": "겜녹이",
"version": "1.0.0",
"version": "1.4.1",
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
"private": true,
"main": "dist/main.cjs",
@@ -54,6 +54,13 @@
"package.json"
],
"asar": true,
"electronFuses": {
"runAsNode": false,
"enableNodeOptionsEnvironmentVariable": false,
"enableNodeCliInspectArguments": false,
"onlyLoadAppFromAsar": true,
"enableCookieEncryption": true
},
"asarUnpack": [
"node_modules/better-sqlite3/**",
"node_modules/@snazzah/**",
@@ -100,7 +107,8 @@
},
"portable": {
"artifactName": "GameVoiceRecorder-${version}-portable.exe",
"unpackDirName": "GameVoiceRecorder"
"unpackDirName": "GameVoiceRecorder",
"splashImage": "../assets/app/splash.bmp"
}
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -0,0 +1,148 @@
// 범인찾기 실제 E2E: 실제 앱 코어 + 실제 사이트 서버 + 실제 Claude API(Opus 5.5, 생각 high) + 헤드리스 브라우저.
// 외부 전적 사이트에는 접속하지 않는다 (기록 점수는 OP.GG 계산법을 따라 경기 기록으로 계산).
// 1) 발로란트 시연 경기 (22라운드 · 대화) 2) 롤 시연 경기 (10 · 15분 라인전 · 대화)
// 비용이 든다 (경기당 약 $0.1~0.4). API 키는 secrets.json 에서 읽어 이 프로세스 안에서만 쓴다.
// node --import tsx scripts/culprit-real-e2e.mts [결과 폴더]
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type { CulpritInput, CulpritMatchInfo } from '@gvr/shared';
import { makeDemoLol } from '../test/fixtures/demo-matches.ts';
import { culpritApi, MIN, seedValorant, setup } from '../test/fixtures/culprit-seed.ts';
const outDir = process.argv[2] || path.join(os.homedir(), '.tmp', 'culprit-real');
fs.mkdirSync(outDir, { recursive: true });
const root = path.resolve(import.meta.dirname, '..', '..');
const apiKey = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.config/ejclaw/secrets.json'), 'utf8')).credentials['anthropic.api/game-voice-recorder'].token as string;
const core = setup();
await core.assets.refresh(true).catch(() => undefined);
const { id: valId } = seedValorant(core);
// ---------------------------------------------------------------- 롤 시연 경기 + 우리 팀 2명 대화
const LS = Date.now() - 80 * MIN;
const lol = makeDemoLol();
const lolId = 'lol-demo';
core.store.setMeta('riot_self_puuid', 'l-sh');
core.store.setAccounts('u1', [{ puuid: 'p-sh', riotId: '하늘#V' }, { puuid: 'l-sh', riotId: '하늘#L' }]);
core.store.setAccounts('u2', [{ puuid: 'p-ms', riotId: '민수#V' }, { puuid: 'l-ms', riotId: '민수#L' }]);
core.store.startSession('s-lol', 'g', 'c', '음성', LS - MIN);
core.games.matchStarted({ id: lolId, game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
core.games.matchEnded(lolId, LS + lol.durationMs);
(core.games.adapters[1] as any).applyHistory(lolId, lol.game, lol.timeline, LS);
const talk: [string, number, string][] = [
['u1', 2.5, '정글 위쪽에서 시작했어 바텀 조심해'],
['u2', 6.2, '용 앞에 와드 박아 줘 시야 없어'],
['u1', 8.1, '용 같이 하자 바텀 밀었어'],
['u2', 8.3, '아니 탑 갱 각이야 잠깐만'],
['u1', 14.8, '용 한타 열지 마 아직 우리 텔 없어'],
['u2', 15.1, '아 들어갔다 아 죽었다 미안'],
['u1', 19.5, '바론 시야 먼저 잡고 하자 혼자 가지 마'],
];
for (const [uid, min, text] of talk) {
const ts = LS + min * MIN;
const id = `lol-${uid}-${min}`;
core.store.insertUtterance({ id, session_id: 's-lol', user_id: uid, started_at: ts, ended_at: ts + 1800, audio_path: null, match_id: lolId });
core.store.updateUtteranceResult(id, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'large-v3', status: 'precise' });
}
core.store.endSession('s-lol', LS + lol.durationMs + MIN);
// ---------------------------------------------------------------- 사이트 서버 (실제 Claude)
const local = await culpritApi(core);
const { buildServer } = await import('../../site/server/src/app.ts');
const port = 18961;
const site = await buildServer({
port, host: '127.0.0.1', publicUrl: `http://127.0.0.1:${port}`, clientId: 'x', clientSecret: 'x', botToken: 'x', allowedGuilds: [], owners: ['u1'], superAdmins: ['u1'],
sessionSecret: 'real-e2e-secret-'.repeat(3), dataDir: fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-real-')), webDir: path.join(root, 'site', 'web', 'dist'), version: 't', discordApi: 'http://127.0.0.1:1',
assetUpstream: { valmedia: 'https://media.valorant-api.com/', ddragon: 'https://ddragon.leagueoflegends.com/', cdragon: 'https://raw.communitydragon.org/' },
culprit: { apiKey, model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium' },
});
site.app.log.level = 'info';
await site.app.listen({ host: '127.0.0.1', port });
const base = `http://127.0.0.1:${port}`;
const code = site.store.createCode('real');
const reg = site.store.redeem(code.code, 'GAME-PC')!;
const { RelayClient } = await import('../src/core/relay/client.ts');
const rc = new RelayClient(local as any, core.bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: 't', guildId: 'g' }));
rc.start();
while (!site.hub.status().online) await new Promise((r) => setTimeout(r, 100));
const sess = site.store.createSession({ id: 'u1', name: '하늘', avatar: null });
const cookieHeader = `gvr_sid=${encodeURIComponent(site.app.signCookie(sess.token))}`;
const stages: Record<string, string[]> = {};
// 진행 단계 기록 (실시간 알림을 가로챈다)
const pub = site.hub.publish.bind(site.hub);
site.hub.publish = (e: any) => {
if (e.type === 'culprit.progress') (stages[e.data.matchId] ||= []).push(`${e.data.stage}${e.data.message ? `(${e.data.message})` : ''}`);
pub(e);
};
async function analyze(matchId: string) {
const input = (await local.inject({ url: `/api/culprit/internal/${matchId}/input`, headers: { 'x-gvr-internal': '1' } })).json().input as CulpritInput;
fs.writeFileSync(path.join(outDir, `${matchId}.input.txt`), input.text);
const t0 = Date.now();
const r = await fetch(`${base}/api/culprit/matches/${matchId}/analyze`, { method: 'POST', headers: { cookie: cookieHeader, 'content-type': 'application/json' }, body: '{}' });
if (r.status !== 202) throw new Error(`analyze ${r.status} ${await r.text()}`);
for (;;) {
await new Promise((res) => setTimeout(res, 3000));
const info = (await (await fetch(`${base}/api/culprit/matches/${matchId}`, { headers: { cookie: cookieHeader } })).json()) as CulpritMatchInfo;
if (info.analysis) return { info, ms: Date.now() - t0 };
if (Date.now() - t0 > 10 * MIN) throw new Error('10분 안에 끝나지 않음');
const b = await (await fetch(`${base}/api/culprit/budget`, { headers: { cookie: cookieHeader } })).json();
if (!b.running.includes(matchId)) {
// 실패
throw new Error(`분석 실패: ${JSON.stringify(stages[matchId] ?? [])}`);
}
}
}
const report: any = {};
for (const id of [valId, lolId]) {
console.log(`\n=== ${id} 분석 시작`);
const { info, ms } = await analyze(id);
const a = info.analysis!;
fs.writeFileSync(path.join(outDir, `${id}.result.json`), JSON.stringify(a, null, 1));
const ref = (pid: string) => a.players.find((p) => p.id === pid)!;
const rows = a.result.players.map((p) => {
const pl = ref(p.id);
return { id: p.id, team: pl.team, ai: p.score, rating: pl.rating?.score ?? null, lane: pl.rating?.lane ?? null, tag: p.tag, comment: p.comment };
});
const teamLowest = (team: string, key: 'rating') => {
const ps = rows.filter((r) => r.team === team && r[key] !== null);
return ps.length ? ps.reduce((x, y) => ((x[key] as number) <= (y[key] as number) ? x : y)).id : null;
};
report[id] = {
seconds: Math.round(ms / 1000),
model: a.model,
costUsd: a.meta.costUsd,
usage: a.meta.usage,
stages: stages[id],
summary: a.result.summary,
confidence: a.result.confidence,
culprits: a.result.teams.map((t) => ({ team: t.team, culprit: t.culprit, reason: t.reason, evidence: t.evidence.map((e) => e.ref), lowestRating: teamLowest(t.team, 'rating') })),
players: rows,
};
console.log(JSON.stringify(report[id], null, 1));
}
fs.writeFileSync(path.join(outDir, 'report.json'), JSON.stringify(report, null, 1));
// ---------------------------------------------------------------- 화면
const puppeteer = (await import(path.join(os.homedir(), '.tmp/gvr-shot/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js'))).default;
const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox', '--lang=ko-KR'] });
const page = await browser.newPage();
await page.setCookie({ name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base });
const errs: string[] = [];
page.on('pageerror', (e: any) => errs.push(e.message));
for (const [id, name] of [[valId, 'real-val.png'], [lolId, 'real-lol.png']] as const) {
await page.setViewport({ width: 1440, height: 2000 });
await page.goto(`${base}/culprit/${id}`, { waitUntil: 'networkidle2' });
await page.waitForSelector('.cu-card', { timeout: 20000 });
await new Promise((r) => setTimeout(r, 1500));
await page.screenshot({ path: path.join(outDir, name), fullPage: true });
}
console.log('\n화면 오류:', errs);
await browser.close();
rc.stop();
await site.app.close();
await local.close();
console.log('결과:', outDir);

View File

@@ -0,0 +1,134 @@
// 범인찾기 화면 확인: 실제 앱 코어(범인찾기 · 기록 DB) + 실제 사이트 서버 + 헤드리스 브라우저.
// AI 는 부르지 않는다: CULPRIT_ANSWER(JSON 파일)를 AI 답으로 돌려준다 (없으면 기본 답 생성).
// [SCALE=2] node --import tsx scripts/culprit-shots.mts [답.json] [스크린샷 폴더]
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type { CulpritInput } from '@gvr/shared';
import { makeDemoLol } from '../test/fixtures/demo-matches.ts';
import { culpritApi, MIN, seedValorant, setup } from '../test/fixtures/culprit-seed.ts';
const answerFile = process.argv[2];
const shotDir = process.argv[3] || path.join(os.homedir(), '.tmp', 'culprit-shots');
const root = path.resolve(import.meta.dirname, '..', '..');
const core = setup();
await core.assets.refresh(true);
const { id: valId } = seedValorant(core);
// 롤 경기 (음성 2명)
const LS = Date.now() - 80 * MIN;
const lol = makeDemoLol();
core.store.setMeta('riot_self_puuid', 'l-sh');
core.store.setAccounts('u1', [{ puuid: 'p-sh', riotId: '하늘#V' }, { puuid: 'l-sh', riotId: '하늘#L' }]);
core.store.setAccounts('u2', [{ puuid: 'p-ms', riotId: '민수#V' }, { puuid: 'l-ms', riotId: '민수#L' }]);
core.store.startSession('s2', 'g', 'c', '음성', LS - MIN);
core.games.matchStarted({ id: 'lol-demo', game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
core.games.matchEnded('lol-demo', LS + lol.durationMs);
(core.games.adapters[1] as any).applyHistory('lol-demo', lol.game, lol.timeline, LS);
for (const [uid, min, text] of [['u2', 8.1, '용 같이 하자 바텀 밀었어'], ['u1', 8.3, '아니 탑 갱 각이야 잠깐만']] as const) {
const ts = LS + min * MIN;
const id = `lol-${uid}-${min}`;
core.store.insertUtterance({ id, session_id: 's2', user_id: uid, started_at: ts, ended_at: ts + 1500, audio_path: null, match_id: 'lol-demo' });
core.store.updateUtteranceResult(id, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'small', status: 'precise' });
}
core.store.endSession('s2', LS + lol.durationMs + MIN);
// 녹음이 늦게 시작한 경기 (기록 부족 표시용)
core.store.upsertMatch({ id: 'val-late', game: 'valorant', started_at: Date.now() - 30 * 3600_000, ended_at: Date.now() - 29.3 * 3600_000, status: 'complete', map: '/Game/Maps/Bonsai/Bonsai', queue: 'competitive', mode: 'competitive', result: JSON.stringify({ win: true, score: { ally: 13, enemy: 10 } }), detail: JSON.stringify({ players: [{}, {}], roundsDetail: [{}] }) });
core.store.startSession('s3', 'g', 'c', null, Date.now() - 30 * 3600_000 + 12 * MIN);
core.store.endSession('s3', Date.now() - 29 * 3600_000);
const local = await culpritApi(core);
const saved = answerFile && fs.existsSync(answerFile) ? JSON.parse(fs.readFileSync(answerFile, 'utf8')) : null;
const fakeAnswer = (input: CulpritInput) => ({
summary: '초반 드래곤 세 개를 내줘 끌려갔지만 바론 앞 한타를 뒤집어 이겼다.',
confidence: 'medium',
confidence_note: '시연 데이터라 기록이 단순하다.',
teams: [
{ team: 'ally', culprit: 'P2', reason: '드래곤 앞 교전에서 시야 없이 싸우다 내줬고, 용 콜이 있었는데 탑 갱을 고집했다.', evidence: Object.keys(input.refs).filter((k) => k.startsWith('u') || k === 'e3').slice(0, 3).map((ref) => ({ ref, note: '근거' })).concat([{ ref: 's:P2', note: '킬 관여 낮음' }]) },
{ team: 'enemy', culprit: 'P10', reason: '레오나로 이니시를 열지 못하고 한타 직전에 먼저 잡혔다.', evidence: [{ ref: 's:P10', note: '데스 많음' }] },
],
players: input.players.map((p, i) => ({ id: p.id, score: p.id === 'P2' ? 4 : p.id === 'P10' ? 3 : 6 + (i % 4), tag: p.id === 'P2' || p.id === 'P10' ? '범인' : i === 0 ? '캐리' : '무난', comment: '한 줄 평 예시.', evidence: [] })),
});
const { buildServer } = await import('../../site/server/src/app.ts');
const { KnowledgeAuto } = await import('../../site/server/src/culprit-prompt.ts');
const port = 18960;
const site = await buildServer(
{
port, host: '127.0.0.1', publicUrl: `http://127.0.0.1:${port}`, clientId: 'x', clientSecret: 'x', botToken: 'x', allowedGuilds: [], owners: ['u1'], superAdmins: ['u1'],
sessionSecret: 'demo-secret-'.repeat(3), dataDir: fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-cs-')), webDir: path.join(root, 'site', 'web', 'dist'), version: 't', discordApi: 'http://127.0.0.1:1',
assetUpstream: { valmedia: 'https://media.valorant-api.com/', ddragon: 'https://ddragon.leagueoflegends.com/', cdragon: 'https://raw.communitydragon.org/' },
culprit: { apiKey: 'x', model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium' },
},
{
culpritKnowledge: new KnowledgeAuto(async () => { throw new Error('offline'); }),
culpritCall: async (req) => {
await new Promise((r) => setTimeout(r, 2500));
const isVal = req.user.includes('# 경기 발로란트');
const input = (await local.inject({ url: `/api/culprit/internal/${isVal ? valId : 'lol-demo'}/input`, headers: { 'x-gvr-internal': '1' } })).json().input;
return { text: JSON.stringify(isVal && saved ? saved : fakeAnswer(input)), stopReason: 'end_turn', usages: [{ model: 'claude-opus-5-5', input: 26077, output: 13997, cacheRead: 0, cacheWrite: 0 }], fallback: false };
},
},
);
site.app.log.level = 'warn';
await site.app.listen({ host: '127.0.0.1', port });
const base = `http://127.0.0.1:${port}`;
const code = site.store.createCode('demo');
const reg = site.store.redeem(code.code, 'GAME-PC')!;
const { RelayClient } = await import('../src/core/relay/client.ts');
const rc = new RelayClient(local as any, core.bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: 't', guildId: 'g' }));
rc.start();
// 사이트 화면은 /api/overview · /api/users 도 부른다
while (!site.hub.status().online) await new Promise((r) => setTimeout(r, 100));
const sess = site.store.createSession({ id: 'u1', name: '하늘', avatar: null });
const cookie = { name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base };
const puppeteer = (await import(path.join(os.homedir(), '.tmp/gvr-shot/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js'))).default;
const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox', '--lang=ko-KR'] });
const page = await browser.newPage();
await page.setCookie(cookie);
const errs: string[] = [];
page.on('pageerror', (e: any) => errs.push(e.message));
page.on('console', (m: any) => m.type() === 'error' && errs.push(m.text()));
const csp: string[] = [];
await page.exposeFunction('__csp', (v: string) => csp.push(v));
await page.evaluateOnNewDocument(() => document.addEventListener('securitypolicyviolation', (e) => (window as any).__csp(`${e.violatedDirective} ${e.blockedURI}`)));
fs.mkdirSync(shotDir, { recursive: true });
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const SCALE = Number(process.env.SCALE || 1);
const shot = async (name: string, w = 1440, h = 900, full = false) => {
await page.setViewport({ width: w, height: h, deviceScaleFactor: SCALE });
await sleep(600);
await page.screenshot({ path: path.join(shotDir, name), fullPage: full });
console.log('screenshot', name);
};
await page.setViewport({ width: 1440, height: 900 });
await page.goto(`${base}/culprit/${valId}`, { waitUntil: 'networkidle2' });
await sleep(1500);
await shot('1-list.png', 1440, 1100);
await page.click('.cu-btn');
await sleep(1200);
await shot('2-progress.png');
await page.waitForSelector('.cu-card', { timeout: 20000 });
await sleep(1200);
await shot('3-result-val.png', 1440, 1900);
await shot('4-result-mobile.png', 390, 3200);
await page.setViewport({ width: 1440, height: 900 });
await page.goto(`${base}/culprit/lol-demo`, { waitUntil: 'networkidle2' });
await sleep(1200);
await page.click('.cu-btn');
await page.waitForSelector('.cu-card', { timeout: 20000 });
await sleep(1200);
await shot('5-result-lol.png', 1440, 1900);
await page.goto(`${base}/culprit/val-late`, { waitUntil: 'networkidle2' });
await sleep(1200);
await shot('6-blocked.png');
await page.goto(`${base}/matches/${valId}`, { waitUntil: 'networkidle2' });
await sleep(800);
const hasBtn = await page.evaluate(() => [...document.querySelectorAll('.crumbs a')].some((a) => a.textContent?.includes('범인 보기')));
console.log('경기 화면 범인 보기 버튼', hasBtn);
console.log('브라우저 오류:', errs.filter((e) => !/favicon/.test(e)));
console.log('CSP 위반:', csp.length ? csp : '없음');
await browser.close();
rc.stop();
await site.app.close();
await local.close();
process.exit(0);

View File

@@ -24,7 +24,7 @@ fs.symlinkSync(path.join(hf, fs.readdirSync(hf)[0]), path.join(work, 'models', m
fs.writeFileSync(path.join(work, 'settings.json'), JSON.stringify({ stt: { realtimeModel: model, preciseModel: model, device: 'cpu', computeType: 'int8' }, games: { valorant: false, lol: false } }));
const USERS = [
{ id: '100000000000000001', name: '승한', voice: 'ko-KR-InJoonNeural', val: 'p-sh', lol: 'l-sh' },
{ id: '100000000000000001', name: '하늘', voice: 'ko-KR-InJoonNeural', val: 'p-sh', lol: 'l-sh' },
{ id: '100000000000000002', name: '민수', voice: 'ko-KR-HyunsuMultilingualNeural', val: 'p-ms', lol: 'l-ms' },
{ id: '100000000000000003', name: '지우', voice: 'ko-KR-SunHiNeural', val: 'p-jw', lol: 'l-jw' },
{ id: '100000000000000004', name: '현우', voice: 'ko-KR-InJoonNeural', pitch: '-8Hz', val: 'p-hw', lol: 'l-hw' },
@@ -136,8 +136,8 @@ LINES.forEach((l, i) => {
});
for (const [m, name, ch, text, src] of [
[-1.5, '민수', 'team', '정글 갱 갈게요', 'lcu'],
[5.2, 'Lumi', 'all', '아리 잘하네', 'ocr'],
[11.4, '지우', 'team', '드래곤 가자', 'ocr'],
[5.2, 'Lumi', 'all', '아리 잘하네', 'log'],
[11.4, '지우', 'team', '드래곤 가자', 'log'],
[28.5, 'Kiwi', 'all', 'gg', 'lcu'],
] as const) {
games.event({ id: `${lolId}:chat:demo${m}`, match_id: lolId, game: 'lol', type: 'chat', ts: LS + m * 60_000, game_time_ms: m * 60_000, round: null, actor_puuid: null, target_puuid: null, data: JSON.stringify({ sender: { name }, channel: ch, text, source: src }) });
@@ -173,10 +173,12 @@ console.log(`완전 일치 ${exact}/${total}`);
// ---- 로컬 사이트 서버 + 중계
const { buildServer } = await import('../../site/server/src/app.ts');
// 주소를 먼저 정한다 (사이트 서버가 실시간 WebSocket 의 출처를 publicUrl 과 비교한다)
const port = Number(process.env.DEMO_PORT || 18950);
const site = await buildServer({
port: 0,
port,
host: '127.0.0.1',
publicUrl: 'http://127.0.0.1',
publicUrl: `http://127.0.0.1:${port}`,
clientId: 'x',
clientSecret: 'x',
botToken: 'x',
@@ -190,7 +192,7 @@ const site = await buildServer({
assetUpstream: { valmedia: 'https://media.valorant-api.com/', ddragon: 'https://ddragon.leagueoflegends.com/', cdragon: 'https://raw.communitydragon.org/' },
});
site.app.log.level = 'warn';
await site.app.listen({ host: '127.0.0.1', port: Number(process.env.DEMO_PORT || 0) });
await site.app.listen({ host: '127.0.0.1', port });
const base = `http://127.0.0.1:${(site.app.server.address() as any).port}`;
const { registerDevice } = await import('../src/core/relay/client.ts');
const code = site.store.createCode('demo');
@@ -198,8 +200,8 @@ const reg = await registerDevice(base, code.code, 'GAME-PC');
core.settings.update({ site: { serverUrl: base, deviceId: reg.deviceId, deviceName: 'GAME-PC' } });
core.settings.setSecret('deviceKey', reg.deviceKey);
core.relay.restart();
const sess = site.store.createSession({ id: USERS[0].id, name: '승한', avatar: null });
const cookie = { name: 'gvr_sid', value: site.app.signCookie(sess.id), url: base };
const sess = site.store.createSession({ id: USERS[0].id, name: '하늘', avatar: null });
const cookie = { name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base };
while (core.relay.status.state !== 'online') await new Promise((r) => setTimeout(r, 100));
console.log(`사이트: ${base} (쿠키 gvr_sid=${cookie.value})`);
@@ -211,6 +213,10 @@ await page.setCookie(cookie);
const errs: string[] = [];
page.on('pageerror', (e: any) => errs.push(e.message));
page.on('console', (m: any) => m.type() === 'error' && errs.push(m.text()));
// 보안 정책(CSP)에 막힌 것이 있으면 화면 일부가 깨진다 → 모두 모은다
const cspViolations: string[] = [];
await page.exposeFunction('__csp', (v: string) => cspViolations.push(v));
await page.evaluateOnNewDocument(() => document.addEventListener('securitypolicyviolation', (e) => (window as any).__csp(`${e.violatedDirective} ${e.blockedURI}`)));
fs.mkdirSync(shotDir, { recursive: true });
const shot = async (url: string, name: string, w = 1440, h = 900, after?: () => Promise<void>) => {
await page.setViewport({ width: w, height: h });
@@ -251,10 +257,11 @@ await new Promise((r) => setTimeout(r, 4000));
const unlocked = await page.evaluate(() => !document.querySelector('.lock'));
console.log(`잠금 표시 ${lockedVisible}, 재연결 후 해제 ${unlocked}`);
console.log('브라우저 오류:', errs.filter((e) => !/favicon|401/.test(e)));
console.log('CSP 위반:', cspViolations.length ? cspViolations : '없음');
await browser.close();
if (!serve) {
await core.stop();
await site.app.close();
process.exit(lockedVisible && unlocked ? 0 : 1);
process.exit(lockedVisible && unlocked && !cspViolations.length ? 0 : 1);
}
console.log('--serve: Ctrl+C 로 종료');

225
app/scripts/login-e2e.mts Normal file
View File

@@ -0,0 +1,225 @@
// 로그인 E2E (리눅스 · Xvfb): 실제 Electron 앱 + 이 저장소의 사이트 서버 코드 + 가짜 디스코드 OAuth.
// 겜녹이 봇 토큰은 서버에만 있다. 서버가 디스코드에 붙고, 로그인한 앱이 서버 중계(/app/bot/ws)로 봇을 쓰는지까지 본다.
// GVR_E2E_BOT_TOKEN=<겜녹이 봇 토큰> node --import tsx scripts/login-e2e.mts [스크린샷 폴더]
// (먼저 npm run build)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import WebSocket from 'ws';
import { buildServer } from '../../site/server/src/app.ts';
import { DiscordSource } from '../../site/server/src/discord-source.ts';
import { AppAuth } from '../src/core/auth.ts';
import { SettingsStore } from '../src/core/settings.ts';
const BOT = process.env.GVR_E2E_BOT_TOKEN;
if (!BOT) throw new Error('GVR_E2E_BOT_TOKEN 이 필요합니다');
const shots = process.argv[2];
const SUPER = '293719842274541579';
// 친구 = 테스트봇 계정 (F&L 서버 멤버). 봇 중계는 앱 유저가 가입한 서버만 보여 주므로 실제 멤버여야 한다
const FRIEND = '1538122882528321536';
const PORT = 18931;
const base = `http://127.0.0.1:${PORT}`;
const work = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-login-e2e-'));
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const results: [string, boolean, string][] = [];
const check = (name: string, ok: boolean, detail = '') => {
results.push([name, ok, detail]);
console.log(`${ok ? '✔' : '✘'} ${name}${detail ? ` · ${detail}` : ''}`);
};
// ---- 가짜 디스코드: OAuth code = 로그인할 아이디, 봇 토큰으로 /users/:id 조회
const names: Record<string, string> = { [SUPER]: '사금향', [FRIEND]: '테스트친구' };
const dc = http.createServer((req, res) => {
const u = new URL(req.url!, 'http://x');
res.setHeader('content-type', 'application/json');
if (u.pathname === '/oauth2/token') {
let b = '';
req.on('data', (c) => (b += c));
req.on('end', () => res.end(JSON.stringify({ access_token: new URLSearchParams(b).get('code') })));
return;
}
if (u.pathname === '/users/@me') {
const id = String(req.headers.authorization).replace('Bearer ', '');
return res.end(JSON.stringify({ id, username: names[id] ?? 'x', global_name: names[id] ?? null, avatar: null }));
}
const m = /^\/users\/(\d+)$/.exec(u.pathname);
if (m && names[m[1]!]) return res.end(JSON.stringify({ id: m[1], username: names[m[1]!], global_name: names[m[1]!], avatar: null }));
res.statusCode = 404;
res.end('{}');
});
await new Promise<void>((r) => dc.listen(0, '127.0.0.1', () => r()));
const dcUrl = `http://127.0.0.1:${(dc.address() as any).port}`;
const source = new DiscordSource({ info: () => undefined, error: (o, m) => console.error(m, o) });
const { app: site } = await buildServer(
{
port: PORT, host: '127.0.0.1', publicUrl: base, clientId: 'cid', clientSecret: 's', botToken: BOT,
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: path.join(work, 'site'),
webDir: '/nonexistent', version: 'e2e', discordApi: dcUrl, assetUpstream: {},
},
{ botSource: source },
);
site.log.level = 'warn';
await site.listen({ host: '127.0.0.1', port: PORT });
await source.login(BOT);
// 브라우저 흉내: PATH 맨 앞에 가짜 xdg-open 을 둔다 (Electron shell.openExternal 이 부른다. 실제 브라우저는 열지 않는다)
// 로그인 주소 → 가짜 디스코드 → 콜백. 로그인할 아이디는 파일에서
const loginAs = path.join(work, 'login-as');
const binDir = path.join(work, 'bin');
fs.mkdirSync(binDir);
const browserSh = path.join(binDir, 'xdg-open');
fs.writeFileSync(
browserSh,
`#!/bin/sh\nJAR=$(mktemp)\nLOC=$(curl -s -c "$JAR" -o /dev/null -w '%{redirect_url}' "$1")\nSTATE=$(printf '%s' "$LOC" | sed -n 's/.*[?&]state=\\([^&]*\\).*/\\1/p')\ncurl -s -b "$JAR" -o /dev/null "${base}/auth/discord/callback?code=$(cat ${loginAs})&state=$STATE"\nrm -f "$JAR"\n`,
{ mode: 0o755 },
);
const browse = (who: string) => async (url: string) => {
const start = await fetch(url, { redirect: 'manual' });
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
await fetch(`${base}/auth/discord/callback?code=${who}&state=${encodeURIComponent(state)}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
};
// 최고 관리자 (관리자 화면 API 를 대신 부른다)
const adminSt = new SettingsStore(path.join(work, 'admin'));
adminSt.update({ site: { serverUrl: base } });
const admin = new AppAuth(adminSt, { version: 'e2e', openUrl: browse(SUPER), pollMs: 100 });
check('최고 관리자 로그인', (await admin.login()).role === 'superadmin');
await admin.adminAddUser(FRIEND, 'user');
check('최고 관리자가 친구를 유저로 등록', (await admin.adminUsers()).users.some((u) => u.id === FRIEND && u.role === 'user'));
// ---- Electron 앱
const data = path.join(work, 'app');
fs.mkdirSync(data);
fs.writeFileSync(path.join(data, 'settings.json'), JSON.stringify({ firstRunDone: true, site: { serverUrl: base }, games: { valorant: false, lol: false } }));
fs.writeFileSync(loginAs, FRIEND);
const electron = path.join(import.meta.dirname, '..', 'node_modules', '.bin', 'electron');
const proc = spawn('xvfb-run', ['-a', electron, '.', `--data-dir=${data}`, '--remote-debugging-port=9333', '--no-sandbox'], {
cwd: path.join(import.meta.dirname, '..'),
env: { ...process.env, PATH: `${binDir}:${process.env.PATH}`, WAYLAND_DISPLAY: '', XDG_SESSION_TYPE: 'x11', GVR_BOT_TOKEN: '', ELECTRON_ENABLE_LOGGING: '1' },
stdio: ['ignore', 'pipe', 'pipe'],
detached: true, // 끝날 때 xvfb-run · Electron 을 프로세스 그룹째 끈다
});
const logs: string[] = [];
proc.stdout.on('data', (b) => logs.push(...String(b).split('\n')));
proc.stderr.on('data', (b) => logs.push(...String(b).split('\n')));
// CDP: 설정 창에서 window.gvr 호출
let ws: WebSocket | null = null;
for (let i = 0; i < 60 && !ws; i++) {
await sleep(1000);
try {
const t = ((await (await fetch('http://127.0.0.1:9333/json')).json()) as any[]).find((x) => x.type === 'page');
if (t) {
ws = new WebSocket(t.webSocketDebuggerUrl);
await new Promise((r) => ws!.once('open', r));
}
} catch {
/* 아직 */
}
}
if (!ws) throw new Error('Electron 창에 붙지 못했습니다\n' + logs.join('\n'));
let seq = 0;
const cdp = (method: string, params: any = {}) =>
new Promise<any>((res) => {
const id = ++seq;
const on = (m: WebSocket.RawData) => {
const j = JSON.parse(String(m));
if (j.id === id) {
ws!.off('message', on);
res(j.result);
}
};
ws!.on('message', on);
ws!.send(JSON.stringify({ id, method, params }));
});
const gvr = async (expr: string): Promise<{ ok: boolean; v?: any; err?: string }> => {
const r = await cdp('Runtime.evaluate', { expression: `(async () => JSON.stringify(await (${expr})))()`, awaitPromise: true });
if (r.exceptionDetails) return { ok: false, err: r.exceptionDetails.exception?.description ?? r.exceptionDetails.text };
return { ok: true, v: r.result.value === undefined ? undefined : JSON.parse(r.result.value) };
};
const shot = async (name: string) => {
if (!shots) return;
await sleep(700);
const r = await cdp('Page.captureScreenshot', { format: 'png' });
fs.mkdirSync(shots, { recursive: true });
fs.writeFileSync(path.join(shots, `${name}.png`), Buffer.from(r.data, 'base64'));
};
try {
await sleep(1500);
let a = (await gvr('window.gvr.authState()')).v;
check('새 설치: 로그인 화면', a.status === 'signed_out' && !a.appReady, a.status);
check('로그인 전: 코어 요청 막힘', /로그인이 필요합니다/.test((await gvr('window.gvr.getState()')).err ?? ''));
await shot('electron-login');
// 로그인 (브라우저 → 가짜 디스코드 → 콜백 → 앱이 결과를 받아 감)
void gvr('window.gvr.authLogin()');
for (let i = 0; i < 60 && !(a?.status === 'ok' && a.appReady); i++) {
await sleep(500);
a = (await gvr('window.gvr.authState()')).v;
}
check('등록된 친구 로그인 → 앱 열림', a.status === 'ok' && a.appReady && a.role === 'user', `${a.status} ${a.role}`);
let st: any = null;
for (let i = 0; i < 90; i++) {
st = (await gvr('window.gvr.getState()')).v;
if (st?.bot.status === 'ready' || st?.bot.status === 'error') break;
await sleep(500);
}
check('겜녹이 봇이 사이트 서버 중계로 연결', st?.bot.status === 'ready' && st.builtinBot && /사이트 서버 중계/.test(logs.join('\n')), `${st?.bot.status} ${st?.bot.user?.name ?? ''} 서버 ${st?.bot.guilds.length ?? 0}곳 ${st?.bot.error ?? ''}`);
const t = (await gvr('window.gvr.testBotToken()')).v;
check('겜녹이 봇 연결 확인 버튼 (토큰 없이 서버 중계)', t?.ok && t.guilds.length > 0, JSON.stringify(t).slice(0, 120));
const mem = (await gvr('window.gvr.guildMembers()')).v;
check('따라갈 사람 목록 (서버 중계)', Array.isArray(mem) && mem.length > 0, `${mem?.length}명`);
const stored = fs.readdirSync(data).filter((f) => fs.statSync(path.join(data, f)).isFile() && fs.readFileSync(path.join(data, f)).includes(Buffer.from(BOT)));
check('로그인 후에도 앱 데이터에 봇 토큰 없음', stored.length === 0, stored.join(','));
check('계정 표시', st?.account.user?.id === FRIEND && st.account.role === 'user');
// 창 보안: 설정 창이 바깥 페이지로 넘어가지 않는다 (넘어가면 그 페이지가 window.gvr 를 쓸 수 있다)
await gvr(`(location.href = 'https://127.0.0.1:1/evil', 1)`);
await sleep(1500);
const where = (await gvr('location.protocol + (typeof window.gvr)')).v;
check('설정 창은 바깥 주소로 넘어가지 않는다', where === 'file:object', where);
// 일반 유저 권한
const r1 = await gvr(`window.gvr.updateSettings({ discord: { botMode: 'custom' } })`);
check('유저: 다른 봇으로 바꾸기 거절', !r1.ok && /관리자만/.test(r1.err ?? ''));
const r2 = await gvr(`window.gvr.updateSettings({ storage: { retentionDays: 30 } })`);
check('유저: 보관 기간 변경 거절', !r2.ok && /관리자만/.test(r2.err ?? ''));
const r3 = await gvr(`window.gvr.setSecret('botToken', 'x')`);
check('유저: 봇 토큰 입력 거절', !r3.ok);
const r4 = await gvr(`window.gvr.clearTrainingData()`);
check('유저: 학습 데이터 삭제 거절', !r4.ok && /관리자만/.test(r4.err ?? ''));
const r5 = await gvr(`window.gvr.updateSettings({ general: { sfx: false } })`);
check('유저: 일반 설정은 바꿀 수 있음', r5.ok && r5.v.general.sfx === false);
const r6 = await gvr(`window.gvr.adminAddUser('${SUPER}', 'user')`);
check('유저: 유저 등록 API 거절 (서버)', !r6.ok && /최고 관리자만/.test(r6.err ?? ''));
await gvr(`(location.hash = '#/settings/storage', 1)`);
await shot('electron-user-storage');
// 등록 해제 → 다시 확인하면 잠김 · 봇 멈춤
await admin.adminRemoveUser(FRIEND);
a = (await gvr('window.gvr.authRecheck()')).v;
check('등록 해제 후 확인 → 등록되지 않은 아이디로 잠김', a.status === 'not_registered' && !a.appReady, a.status);
check('잠긴 뒤 코어 요청 막힘', /로그인이 필요합니다/.test((await gvr('window.gvr.getState()')).err ?? ''));
const secrets = fs.existsSync(path.join(data, 'secrets.bin')) ? fs.readFileSync(path.join(data, 'secrets.bin')).toString('latin1') : '';
check('잠긴 뒤 앱 토큰 삭제', !secrets.includes('appToken'));
await shot('electron-not-registered');
} finally {
ws?.close();
try {
process.kill(-proc.pid!, 'SIGTERM');
} catch {
/* 이미 끝남 */
}
await sleep(1500);
await site.close();
await source.destroy();
dc.close();
fs.writeFileSync(path.join(work, 'electron.log'), logs.join('\n'));
console.log(`작업 폴더 ${work}`);
}
const failed = results.filter((r) => !r[1]);
console.log(`\n${results.length - failed.length}/${results.length} 통과`);
process.exit(failed.length ? 1 : 0);

View File

@@ -2,6 +2,8 @@
// node --import tsx scripts/voice-e2e.mts <guildId> <voiceChannelId>
// 필요: secrets.json 의 겜녹이·테스트봇 토큰, worker/.venv, tiny 모델(HF 캐시)
// M7 실사용 시험: GVR_E2E_SET=demo (시연 대화 28문장, 문장별 CER·지연), GVR_E2E_MODEL=<모델 폴더 경로>, GVR_E2E_DEVICE=cuda
// GVR_E2E_RELAY=1: 겜녹이 봇을 사이트 서버 중계로 쓴다 (이 저장소의 사이트 서버 코드를 띄워 봇 토큰은 서버에만 두고,
// 앱은 로그인 토큰으로 /app/bot/ws 에 붙는다. 디스코드 OAuth 만 가짜). 끝나면 앱 데이터 폴더에 봇 토큰이 없는지도 본다
import { Client, GatewayIntentBits } from 'discord.js';
import { joinVoiceChannel, entersState, VoiceConnectionStatus, createAudioPlayer, createAudioResource, StreamType, AudioPlayerStatus } from '@discordjs/voice';
import fs from 'node:fs';
@@ -32,7 +34,62 @@ fs.writeFileSync(
}),
);
process.env.GVR_RECORD_BOTS = '1';
process.env.GVR_BOT_TOKEN = GVR_TOKEN;
const RELAY = process.env.GVR_E2E_RELAY === '1';
let relayStop: (() => Promise<void>) | null = null;
let settings: any;
if (RELAY) {
delete process.env.GVR_BOT_TOKEN;
const http = await import('node:http');
const { buildServer } = await import('../../site/server/src/app.ts');
const { DiscordSource } = await import('../../site/server/src/discord-source.ts');
const { AppAuth } = await import('../src/core/auth.ts');
const { SettingsStore } = await import('../src/core/settings.ts');
const SUPER = '293719842274541579';
// 가짜 디스코드 OAuth: code = 로그인할 아이디
const dc = http.createServer((req, res) => {
res.setHeader('content-type', 'application/json');
if (req.url === '/oauth2/token') return void res.end(JSON.stringify({ access_token: SUPER }));
if (req.url === '/users/@me') return void res.end(JSON.stringify({ id: SUPER, username: 'e2e', global_name: 'e2e', avatar: null }));
res.statusCode = 404;
res.end('{}');
});
await new Promise<void>((r) => dc.listen(0, '127.0.0.1', () => r()));
const source = new DiscordSource({ info: (o, m) => console.log('[site]', m ?? '', JSON.stringify(o)), error: (o, m) => console.error('[site]', m ?? '', o) });
const { app: site } = await buildServer(
{
port: 0, host: '127.0.0.1', publicUrl: 'http://placeholder', clientId: 'cid', clientSecret: 's', botToken: GVR_TOKEN,
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: path.join(work, 'site'),
webDir: '/nonexistent', version: 'e2e', discordApi: `http://127.0.0.1:${(dc.address() as any).port}`, assetUpstream: {},
},
{ botSource: source },
);
site.log.level = 'warn';
await site.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(site.server.address() as any).port}`;
await source.login(GVR_TOKEN);
const appDir = path.join(work, 'app');
fs.mkdirSync(appDir);
fs.copyFileSync(path.join(work, 'settings.json'), path.join(appDir, 'settings.json'));
settings = new SettingsStore(appDir);
settings.update({ site: { serverUrl: base }, stt: { modelsDir: models } });
const auth = new AppAuth(settings, {
version: 'e2e',
pollMs: 100,
openUrl: async (url: string) => {
const start = await fetch(url.replace('http://placeholder', base), { redirect: 'manual' });
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
await fetch(`${base}/auth/discord/callback?code=${SUPER}&state=${encodeURIComponent(state)}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
},
});
const a = await auth.login();
if (a.status !== 'ok') throw new Error(`앱 로그인 실패: ${a.status} ${a.error}`);
console.log('앱 로그인 (서버 중계 모드):', a.user?.name, a.role);
relayStop = async () => {
await site.close();
await source.destroy();
dc.close();
};
} else process.env.GVR_BOT_TOKEN = GVR_TOKEN;
const DEMO = process.env.GVR_E2E_SET === 'demo';
const demoSrc = fs.readFileSync(path.join(import.meta.dirname, 'demo-stack.mts'), 'utf8');
const SENTENCES = DEMO
@@ -47,7 +104,7 @@ for (const [i, s] of SENTENCES.entries()) {
clips.push(f);
}
const { startCore } = await import('../src/core/index.ts');
const core = await startCore({ dataDir: work, resourcesDir: path.join(root, 'app', 'resources'), worker: { cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') }, version: 'e2e' });
const core = await startCore({ dataDir: RELAY ? path.join(work, 'app') : work, settings, resourcesDir: path.join(root, 'app', 'resources'), worker: { cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') }, version: 'e2e' });
const wait = async (fn: () => boolean, ms: number, label: string) => {
const t = Date.now();
while (!fn()) {
@@ -59,6 +116,7 @@ let ok = false;
const spk = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] });
try {
await wait(() => core.bot.state.status === 'ready', 30000, 'gvr bot ready');
if (RELAY) console.log('겜녹이 봇 연결:', core.bot.gateway?.kind, core.bot.state.user?.name);
await wait(() => core.stt.status.slots.realtime.state === 'loaded', 120000, 'model');
await spk.login(SPEAKER_TOKEN);
await new Promise((r) => spk.once('clientReady', r));
@@ -120,6 +178,20 @@ try {
console.log(`녹음 제외 후 새 발화: ${after - before}개 (0 이어야 함)`);
const texts = rows.map((r) => r.text || '').join(' ');
ok = rows.length >= SENTENCES.length && /레이즈|오퍼|치킨/.test(texts) && after === before && (!DEMO || cerAvg < 0.15);
if (RELAY) {
// 서버 중계 모드: 봇은 서버 연결이어야 하고, 앱 데이터 폴더 어디에도 봇 토큰이 없어야 한다
const leaked: string[] = [];
const scan = (d: string) => {
for (const f of fs.readdirSync(d, { withFileTypes: true })) {
const p = path.join(d, f.name);
if (f.isDirectory()) scan(p);
else if (f.isFile() && fs.statSync(p).size < 200 * 1024 * 1024 && fs.readFileSync(p).includes(Buffer.from(GVR_TOKEN))) leaked.push(p);
}
};
scan(path.join(work, 'app'));
console.log(`봇 연결 방식: ${core.bot.gateway?.kind} · 앱 데이터에 봇 토큰: ${leaked.length ? leaked.join(', ') : '없음'}`);
ok &&= core.bot.gateway?.kind === 'remote' && leaked.length === 0;
}
conn.destroy();
await wait(() => !core.bot.state.recording.active, 20000, 'gvr leaves after speaker').catch(() => console.log('(겜녹이 퇴장 대기 시간 초과)'));
console.log('겜녹이 퇴장:', !core.bot.state.recording.active);
@@ -128,6 +200,7 @@ try {
} finally {
await spk.destroy();
await core.stop();
await relayStop?.();
console.log(ok ? 'VOICE E2E PASS' : 'VOICE E2E FAIL');
process.exit(ok ? 0 : 1);
}

View File

@@ -1,24 +1,42 @@
import Fastify, { type FastifyInstance } from 'fastify';
import fs from 'node:fs';
import path from 'node:path';
import type { MatchDetail, MatchPlayer, Overview, User, UserProfile, Word } from '@gvr/shared';
import type { Store, UserRow } from '../db/db.js';
import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, UtteranceInfo, Word } from '@gvr/shared';
import type { Culprit } from '../culprit.js';
import { normalizePhrase, type Store, type UserRow } from '../db/db.js';
import type { Dictionary } from '../dict/dictionary.js';
import type { GameManager } from '../games/manager.js';
import type { Settings } from '../settings.js';
import { safeJson, type Timeline, type TimelineQuery } from '../timeline.js';
import type { Bus } from '../util/events.js';
import { BundleError, type Bundles } from '../bundles.js';
import { logger } from '../util/log.js';
const log = logger('api');
/** 파일 지우기. 음성 인식 · 다른 프로그램이 열고 있으면(Windows) 5초마다 다시 (1분까지) */
export function removeFile(f: string, tries = 12): void {
try {
fs.rmSync(f, { force: true });
} catch (e: any) {
if (tries <= 1) return void log.warn(`파일 삭제 실패 ${path.basename(f)}: ${e?.code ?? e?.message}`);
setTimeout(() => removeFile(f, tries - 1), 5000).unref?.();
}
}
export interface ApiDeps {
store: Store;
timeline: Timeline;
games: GameManager;
dict: Dictionary;
culprit: Culprit;
bus: Bus;
settings: () => Settings;
trainingDir: () => string;
overviewExtra: () => { guild: Overview['guild']; recording: Overview['recording'] };
version: string;
/** 기록 묶음 (없으면 /api/bundles 없음) */
bundles?: Bundles;
}
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
@@ -52,6 +70,7 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
recording: extra.recording,
users: users(),
games: { valorant: { connected: gs.valorant.connected, inMatch: gs.valorant.inMatch }, lol: { connected: gs.lol.connected, inMatch: gs.lol.inMatch } },
live: d.games.live(),
counts: store.counts(),
version: d.version,
};
@@ -106,7 +125,6 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
to: q.to ? Number(q.to) : undefined,
q: q.q || undefined,
types: q.types ? q.types.split(',').filter(Boolean) : undefined,
hideNoise: q.hideNoise === '1' || q.hideNoise === 'true',
cursor: q.cursor || undefined,
limit: q.limit ? Number(q.limit) : undefined,
order: q.order === 'asc' ? 'asc' : 'desc',
@@ -114,6 +132,122 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
return timeline.query(tq);
});
// 발화 자세한 정보: 원본 ogg 이름 · 경로 등 (사이트 우클릭 → 자세한 정보)
app.get<{ Params: { id: string } }>('/api/utterances/:id/info', async (req, reply): Promise<UtteranceInfo | void> => {
const u = store.getUtterance(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found' });
const exists = !!u.audio_path && !u.audio_deleted && fs.existsSync(u.audio_path);
const sess = u.session_id ? (store.db.prepare('SELECT channel_name FROM sessions WHERE id=?').get(u.session_id) as { channel_name: string | null } | undefined) : undefined;
const p = u.audio_path;
const win = p?.includes('\\') ?? false;
const sep = win ? '\\' : '/';
return {
id: u.id,
userId: u.user_id,
fileName: p ? p.split(/[\\/]/).pop() ?? null : null,
path: p,
folder: p ? p.slice(0, p.lastIndexOf(sep)) || null : null,
sizeBytes: exists ? fs.statSync(p!).size : null,
deleted: exists ? null : u.noise && !u.corrected ? 'noise' : u.audio_deleted ? 'retention' : 'missing',
startedAt: u.started_at,
endedAt: u.ended_at,
durationMs: u.ended_at - u.started_at,
sessionId: u.session_id,
channel: sess?.channel_name ?? null,
matchId: u.match_id,
status: u.status,
model: u.model,
confidence: u.confidence,
lufs: u.lufs,
gainDb: u.gain_db,
rawText: u.raw_text,
text: u.text,
corrected: !!u.corrected,
noise: !!u.noise,
noiseReason: u.noise_reason,
attempts: u.attempts,
createdAt: u.created_at,
};
});
// ---- 기록 묶음: 경기별 · 경기 전후 대화별로 보기 · 지우기 · zip 내보내기 · zip 받아오기 (v1.3.7)
// zip 은 사이트 서버가 조각으로 나눠 보낸다. 300MB 까지
app.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body));
const bundleErr = (reply: any, e: unknown) => {
if (e instanceof BundleError) return reply.code(e.code === 'not_found' ? 404 : e.code === 'busy' ? 409 : e.code === 'too_large' ? 413 : 400).send({ error: e.code, message: e.message });
throw e;
};
/** 사이트 중계로 온 요청이면 사이트 서버가 붙인 역할이 관리자여야 한다 (이 PC 안에서 부른 것은 그대로) */
const adminOnly = (req: any, reply: any): boolean => {
if (!req.headers['x-gvr-user']) return true;
if (req.headers['x-gvr-role'] === 'admin') return true;
reply.code(403).send({ error: 'forbidden', message: '기록 지우기 · 받아오기는 관리자만 할 수 있습니다' });
return false;
};
/** 발화 지우기: 이 PC 안에서 부른 것 · 관리자 · 말한 사람 본인 */
const canDelete = (req: any, speakerId: string): boolean => {
const raw = req.headers['x-gvr-user'];
if (!raw) return true;
if (req.headers['x-gvr-role'] === 'admin') return true;
try {
return JSON.parse(decodeURIComponent(String(raw)))?.id === speakerId;
} catch {
return false;
}
};
const exportZip = (reply: any, ids: string[]) => {
const { zip, fileName } = d.bundles!.export(ids);
return reply.header('content-type', 'application/zip').header('content-disposition', `attachment; filename="${fileName}"`).header('cache-control', 'no-store').send(zip);
};
app.get('/api/bundles', async (_req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
return { bundles: d.bundles.list() };
});
app.post<{ Body: { ids?: string[] } }>('/api/bundles/delete', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
if (!adminOnly(req, reply)) return;
try {
const ids = Array.isArray(req.body?.ids) ? req.body.ids.map(String) : [];
const r = d.bundles.delete(ids);
timeline.invalidate();
d.bus.live({ type: 'records.changed', data: { reason: 'deleted', ids } });
return r;
} catch (e) {
return bundleErr(reply, e);
}
});
app.get<{ Querystring: { ids?: string } }>('/api/bundles/export', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
try {
return exportZip(reply, String(req.query.ids ?? '').split(',').filter(Boolean));
} catch (e) {
return bundleErr(reply, e);
}
});
// 많이 고르면 주소가 너무 길어진다: 본문으로 받는 것도 둔다
app.post<{ Body: { ids?: string[] } }>('/api/bundles/export', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
try {
return exportZip(reply, Array.isArray(req.body?.ids) ? req.body.ids.map(String) : []);
} catch (e) {
return bundleErr(reply, e);
}
});
app.post('/api/bundles/import', async (req, reply) => {
if (!d.bundles) return reply.code(404).send({ error: 'not_found' });
if (!adminOnly(req, reply)) return;
if (!Buffer.isBuffer(req.body)) return reply.code(400).send({ error: 'invalid_bundle', message: '받아오기 실패: zip 파일을 보내 주세요' });
try {
const r = d.bundles.import(req.body);
timeline.invalidate();
d.bus.live({ type: 'records.changed', data: { reason: 'imported' } });
d.bus.live({ type: 'users.updated', data: [] });
return r;
} catch (e) {
return bundleErr(reply, e);
}
});
app.get<{ Params: { id: string } }>('/api/audio/:id', async (req, reply) => {
const u = store.getUtterance(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found' });
@@ -166,9 +300,10 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
items: p.items,
rank: p.rank ?? null,
userId: p.puuid ? userOf(p.puuid) : undefined,
stats: p.stats,
}));
const evRows = store.events(m.id);
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? ORDER BY started_at').all(m.id) as any[];
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? AND (noise=0 OR corrected=1) ORDER BY started_at').all(m.id) as any[];
const vmap = m.game === 'valorant' ? d.games.assets.valMap(m.map) : null;
return {
...sum,
@@ -210,6 +345,35 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
return item;
});
// 발화 지우기 (v1.4.0): 사이트 우클릭 메뉴. 관리자 또는 말한 사람만.
// noise=true 면 "잡음이라 삭제": 인식된 문장을 배워서, 같은 문장이 다시 나오면 잡음으로 본다
app.post<{ Params: { id: string }; Body: { noise?: boolean } }>('/api/utterances/:id/delete', async (req, reply) => {
const u = store.getUtterance(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found', message: '이미 지워진 발화입니다' });
if (!canDelete(req, u.user_id)) return reply.code(403).send({ error: 'forbidden', message: '발화는 관리자나 말한 사람만 지울 수 있습니다' });
let learned: string | null = null;
if (req.body?.noise) {
const sample = (u.raw_text ?? u.text ?? '').trim();
const phrase = normalizePhrase(sample);
if (phrase) {
store.addNoisePhrase(phrase, sample.slice(0, 200));
learned = sample.slice(0, 200);
}
}
const files = store.deleteUtterance(u.id);
for (const f of files) removeFile(f);
timeline.invalidate();
d.bus.live({ type: 'utterance.deleted', data: { id: u.id, noise: !!req.body?.noise } });
return { ok: true, learned };
});
app.get('/api/noise-phrases', async () => ({
phrases: store.listNoisePhrases().map((r) => ({ id: r.id, text: r.sample, hits: r.hits, createdAt: r.created_at })),
}));
app.delete<{ Params: { id: string } }>('/api/noise-phrases/:id', async (req, reply) => {
if (!store.deleteNoisePhrase(Number(req.params.id))) return reply.code(404).send({ error: 'not_found' });
return { ok: true };
});
// 사이트에서 단어·교정 규칙 추가/삭제 (보고서 5-4: 사이트·설정에서 직접 추가·수정)
app.post<{ Body: { word?: string; from?: string; to?: string } }>('/api/dictionary', async (req, reply) => {
const b = req.body || {};
@@ -251,6 +415,47 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
).map(([key, count]) => ({ key, label: d.dict.labels[key] ?? key, count })),
}));
// ---------------------------------------------------------------- 범인찾기 (계획서 v1.1)
// /api/culprit/matches* : 사이트(브라우저)가 보는 목록 · 상세
// /api/culprit/internal/* : 사이트 서버만 부른다 (AI 자료 만들기 · 결과 저장). 서버가 붙이는 x-gvr-internal 헤더가 있어야 하고,
// 서버 중계는 브라우저 요청의 이 헤더를 넘기지 않는다 (relay 가 range · content-type · accept 만 넘김)
const internalOnly = (req: { headers: Record<string, unknown> }) => req.headers['x-gvr-internal'] === '1';
app.get<{ Querystring: Record<string, string> }>('/api/culprit/matches', async (req) => {
const q = req.query;
return d.culprit.list({ game: q.game === 'valorant' || q.game === 'lol' ? q.game : undefined, limit: q.limit ? Number(q.limit) : 50 });
});
app.get<{ Params: { id: string } }>('/api/culprit/matches/:id', async (req, reply) => {
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
return d.culprit.info(m);
});
app.get<{ Params: { id: string } }>('/api/culprit/internal/:id/input', async (req, reply) => {
if (!internalOnly(req)) return reply.code(403).send({ error: 'forbidden' });
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
const eligibility = d.culprit.eligibility(m);
if (eligibility.state !== 'ready' && eligibility.state !== 'done') return reply.code(409).send({ error: 'not_ready', eligibility });
return { eligibility, input: d.culprit.buildInput(m) };
});
app.put<{ Params: { id: string }; Body: Partial<CulpritAnalysis> & { result?: CulpritResult } }>('/api/culprit/internal/:id/result', async (req, reply) => {
if (!internalOnly(req)) return reply.code(403).send({ error: 'forbidden' });
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
const b = req.body || {};
if (!b.result || !Array.isArray(b.result.players) || !Array.isArray(b.result.teams) || !b.model || !b.createdBy) return reply.code(400).send({ error: 'bad_result' });
const saved = d.culprit.save(m.id, {
createdAt: Date.now(),
createdBy: { id: String(b.createdBy.id), name: String(b.createdBy.name) },
model: String(b.model),
result: b.result,
players: b.players || [],
meta: b.meta || {},
});
d.games.emitMatch(m.id);
return saved;
});
return app;
}

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

234
app/src/core/auth.ts Normal file
View File

@@ -0,0 +1,234 @@
// 앱(exe) 디스코드 로그인. 사이트 서버(site/server/src/app-auth.ts)가 유저 명단을 갖고 있다.
// - 로그인: 서버에 요청을 만들고 브라우저로 디스코드 로그인 → 결과를 받아 온다 (토큰은 DPAPI 로 암호화 저장)
// - 확인: 시작할 때와 10분마다 /app/me. 등록 해제 · 로그아웃되면 바로 잠근다
// - 겜녹이 봇 토큰은 받지 않는다. 봇은 사이트 서버가 연결하고 앱은 앱 토큰으로 중계받는다 (discord/gateway.ts)
// - 서버에 잠깐 못 붙으면 마지막 확인 후 3일까지는 그대로 쓴다
import { EventEmitter } from 'node:events';
import type { AppLoginBegin, AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
import type { SettingsStore } from './settings.js';
import { logger } from './util/log.js';
import { secureFetch } from './util/secure-http.js';
import { secureServerUrl } from './util/secure-url.js';
const log = logger('auth');
export type AuthStatus = 'checking' | 'signed_out' | 'waiting' | 'ok' | 'not_registered' | 'error';
export interface AuthState {
status: AuthStatus;
user: AppUserInfo | null;
role: AppRole | null;
/** 서버에 못 붙어 마지막 확인 결과로 쓰는 중 */
offline: boolean;
error: string | null;
/** 브라우저 로그인 대기 중이면 연 주소 (브라우저가 안 열렸을 때 다시 열기용) */
loginUrl: string | null;
verifiedAt: number | null;
}
export interface AuthOptions {
version: string;
openUrl: (url: string) => void | Promise<void>;
/** 서버에 못 붙을 때 마지막 확인으로 버티는 시간 (기본 3일) */
offlineGraceMs?: number;
pollMs?: number;
}
class HttpError extends Error {
constructor(
public status: number,
public body: any,
) {
super(body?.message || body?.error || `HTTP ${status}`);
}
}
export class AppAuth extends EventEmitter {
state: AuthState = { status: 'checking', user: null, role: null, offline: false, error: null, loginUrl: null, verifiedAt: null };
private loginSeq = 0;
/**
* 인증 세대. 확인을 새로 시작하거나 토큰을 지우거나(등록 해제 · 로그아웃) 새로 받으면(로그인) 올라간다.
* 늦게 도착한 이전 확인 응답(성공 · 실패 모두)은 버린다 — 잠근 뒤 옛 200 이 앱을 다시 여는 일을 막는다
*/
private gen = 0;
constructor(
private settings: SettingsStore,
private opts: AuthOptions,
) {
super();
}
get ok(): boolean {
return this.state.status === 'ok';
}
private get server(): string {
return secureServerUrl(this.settings.get().site.serverUrl);
}
private set(patch: Partial<AuthState>): void {
this.state = { ...this.state, ...patch };
this.emit('change', this.state);
}
private async call<T>(method: string, path: string, body?: unknown, token = this.settings.getSecret('appToken')): Promise<T> {
const r = await secureFetch(this.server + path, {
method,
headers: {
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
...(token ? { authorization: `Bearer ${token}` } : {}),
'x-gvr-version': this.opts.version,
},
body: body !== undefined ? JSON.stringify(body) : undefined,
timeoutMs: 15000,
});
const text = await r.text();
let json: any = null;
try {
json = text ? JSON.parse(text) : null;
} catch {
/* JSON 아님 */
}
if (!r.ok) throw new HttpError(r.status, json);
return json as T;
}
/** 로그인 정보를 지운다 (등록 해제 · 로그아웃) */
private forget(): void {
this.gen++;
for (const k of ['appToken', 'auth'] as const) if (this.settings.hasSecret(k)) this.settings.setSecret(k, null);
}
/** 저장된 토큰으로 서버에 확인 */
async check(): Promise<AuthState> {
if (this.state.status === 'waiting') return this.state;
const token = this.settings.getSecret('appToken');
const gen = ++this.gen;
if (!token) {
// 등록 해제로 잠긴 화면은 다시 확인해도 그대로 둔다 (봇 중계가 끊기며 바로 확인한 뒤 또 확인이 와도 "등록되지 않은 아이디" 유지)
if (this.state.status === 'not_registered') return this.state;
this.set({ status: 'signed_out', user: null, role: null, offline: false, error: null, verifiedAt: null });
return this.state;
}
// 응답을 기다리는 사이 다른 확인 · 로그아웃 · 잠금 · 새 로그인이 있었으면 이 응답은 버린다
const stale = () => gen !== this.gen || this.settings.getSecret('appToken') !== token;
try {
const me = await this.call<AppMe>('GET', '/app/me', undefined, token);
if (stale()) return this.state;
const cache = { user: me.user, role: me.role, verifiedAt: Date.now() };
this.settings.setSecret('auth', cache);
this.set({ status: 'ok', user: me.user, role: me.role, offline: false, error: null, loginUrl: null, verifiedAt: cache.verifiedAt });
} catch (e: any) {
const lock = e instanceof HttpError && (e.status === 401 || e.status === 403);
// 잠그라는 응답(401 · 403)은 늦게 와도 같은 토큰이면 따른다. 두 확인이 겹치면 서버가 첫 403 에서 세션을 지워
// 뒤 확인은 401 을 받는데, 403 을 버리면 "등록되지 않은 아이디" 대신 "로그인 만료"로 잠긴다. 로그인 진행 중에는 건드리지 않는다
if (lock ? (this.state.status as AuthStatus) === 'waiting' || this.settings.getSecret('appToken') !== token : stale()) return this.state;
if (lock) {
const notReg = e.status === 403 && e.body?.error === 'not_registered';
log.warn(notReg ? '등록이 해제된 아이디라 잠급니다' : '로그인이 만료되어 잠급니다');
const user = notReg ? (e.body?.user ?? this.state.user) : null;
this.forget();
this.set({ status: notReg ? 'not_registered' : 'signed_out', user, role: null, offline: false, error: notReg ? null : '로그인이 만료되었습니다. 다시 로그인해 주세요', verifiedAt: null });
return this.state;
}
// 서버에 못 붙음: 마지막 확인이 유효 기간 안이면 그대로 쓴다
const cache = this.settings.getSecret('auth');
const grace = this.opts.offlineGraceMs ?? 3 * 24 * 3600 * 1000;
const msg = `사이트 서버에 연결할 수 없습니다 (${e.message})`;
if (cache && Date.now() - cache.verifiedAt < grace) {
log.warn(`${msg} · 마지막 확인 결과로 계속 사용`);
this.set({ status: 'ok', user: cache.user, role: cache.role, offline: true, error: msg, verifiedAt: cache.verifiedAt });
} else {
log.warn(msg);
this.set({ status: 'error', offline: false, error: msg });
}
}
return this.state;
}
/** 브라우저로 디스코드 로그인. 끝나거나 취소될 때까지 기다린다 */
async login(): Promise<AuthState> {
const seq = ++this.loginSeq;
this.gen++; // 진행 중이던 확인 응답은 버린다
let b: AppLoginBegin;
try {
b = await this.call<AppLoginBegin>('POST', '/auth/app/begin', {}, undefined);
} catch (e: any) {
this.set({ status: 'error', error: `사이트 서버에 연결할 수 없습니다 (${e.message})`, loginUrl: null });
return this.state;
}
this.set({ status: 'waiting', error: null, loginUrl: b.url, user: null, role: null });
await this.opts.openUrl(b.url);
while (seq === this.loginSeq && Date.now() < b.expiresAt) {
await new Promise((r) => setTimeout(r, this.opts.pollMs ?? 2000));
if (seq !== this.loginSeq) break;
let r: AppLoginPoll;
try {
r = await this.call<AppLoginPoll>('POST', '/auth/app/poll', { id: b.id, secret: b.secret }, undefined);
} catch (e: any) {
if (e instanceof HttpError) r = e.body?.state ? e.body : { state: 'error', error: e.message };
else continue; // 잠깐 끊김: 계속 기다린다
}
if (seq !== this.loginSeq) break;
if (r.state === 'pending') continue;
if (r.state === 'ok') {
this.gen++;
this.settings.setSecret('appToken', r.token);
this.state = { ...this.state, status: 'checking', loginUrl: null };
log.info(`로그인: ${r.user.name} (${r.role})`);
return this.check();
}
if (r.state === 'not_registered') {
log.warn(`등록되지 않은 아이디로 로그인 시도: ${r.user.id}`);
this.set({ status: 'not_registered', user: r.user, role: null, error: null, loginUrl: null });
return this.state;
}
this.set({ status: 'signed_out', error: r.error, loginUrl: null });
return this.state;
}
if (seq === this.loginSeq) this.set({ status: 'signed_out', error: '로그인 시간이 지났습니다. 다시 시도해 주세요', loginUrl: null });
return this.state;
}
cancelLogin(): void {
this.loginSeq++;
if (this.state.status === 'waiting') this.set({ status: 'signed_out', error: null, loginUrl: null });
}
async logout(): Promise<void> {
this.loginSeq++;
const token = this.settings.getSecret('appToken');
// 먼저 로컬에서 지우고 잠근다 (서버 응답을 기다리는 사이 도착한 확인 응답이 다시 열지 못하게)
this.forget();
this.set({ status: 'signed_out', user: null, role: null, offline: false, error: null, loginUrl: null, verifiedAt: null });
if (token) await this.call('POST', '/auth/app/logout', {}, token).catch(() => undefined);
}
/** 관리자 · 최고 관리자 아이디 (따라갈 사람 목록 정렬용) */
async adminIds(): Promise<string[]> {
const r = await this.call<{ ids: string[] }>('GET', '/app/admins');
return Array.isArray(r?.ids) ? r.ids : [];
}
/** 표시 이름 (실명 숨기기): 디스코드 아이디 → 이름 */
async displayNames(): Promise<Record<string, string>> {
const r = await this.call<{ names: Record<string, string> }>('GET', '/app/names');
return r?.names && typeof r.names === 'object' ? r.names : {};
}
adminSetDisplayName(id: string, name: string): Promise<{ names: Record<string, string> }> {
return this.call('PUT', '/app/admin/names', { id: id.trim(), name: name.trim() });
}
// ---- 관리자 화면 (서버가 역할을 다시 확인한다)
adminUsers(): Promise<{ users: AppUserRow[] }> {
return this.call('GET', '/app/admin/users');
}
adminAddUser(id: string, role: 'admin' | 'user'): Promise<{ users: AppUserRow[] }> {
return this.call('POST', '/app/admin/users', { id: id.trim(), role });
}
adminSetRole(id: string, role: 'admin' | 'user'): Promise<{ users: AppUserRow[] }> {
return this.call('PATCH', `/app/admin/users/${encodeURIComponent(id)}`, { role });
}
adminRemoveUser(id: string): Promise<{ users: AppUserRow[] }> {
return this.call('DELETE', `/app/admin/users/${encodeURIComponent(id)}`);
}
}

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

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

451
app/src/core/culprit.ts Normal file
View File

@@ -0,0 +1,451 @@
import type {
CulpritAnalysis,
CulpritEligibility,
CulpritInput,
CulpritMatchInfo,
CulpritMatchItem,
CulpritPlayer,
CulpritRefTarget,
LaneDiff,
MatchPlayer,
MatchRound,
PlayerRating,
} from '@gvr/shared';
import { rateLol, rateValorant } from '@gvr/shared';
import type { EventRow, MatchRow, Store, UtteranceRow } from './db/db.js';
import type { GameManager } from './games/manager.js';
import { safeJson, type Timeline } from './timeline.js';
/**
* 범인찾기 (계획서 v1.1 4장): "분석할 수 있는 경기" 판정, AI 에 보낼 경기 자료(압축 텍스트) 만들기, 결과 저장.
* AI 호출은 사이트 서버가 한다 (API 키는 서버에만 있다). 이 PC 는 자료를 만들고 결과를 저장만 한다.
*/
/** 녹음 공백 허용치: 경기 처음 · 끝 · 중간에 이보다 긴 빈 곳이 있으면 "기록 부족" */
export const COVERAGE_GAP_MS = 60000;
/** 대화가 이보다 많으면 짧은 잡담부터 줄여서 보낸다 (경기당 비용 상한, 계획서 7장) */
export const MAX_UTTERANCES = 2500;
export const CULPRIT_SCHEMA_SQL = `
CREATE TABLE IF NOT EXISTS culprit_analyses (
id TEXT PRIMARY KEY,
match_id TEXT NOT NULL,
created_at INTEGER NOT NULL,
created_by TEXT NOT NULL,
model TEXT NOT NULL,
current INTEGER NOT NULL DEFAULT 1,
result TEXT NOT NULL,
meta TEXT NOT NULL DEFAULT '{}'
);
CREATE INDEX IF NOT EXISTS culprit_match ON culprit_analyses(match_id, created_at);
`;
export class Culprit {
constructor(
private store: Store,
private timeline: Timeline,
private games: GameManager,
) {
store.db.exec(CULPRIT_SCHEMA_SQL);
}
// ---------------------------------------------------------------- 판정
eligibility(m: MatchRow): CulpritEligibility {
const reasons: string[] = [];
if (m.status !== 'complete' || !m.ended_at) return { state: 'pending', reasons: ['경기가 아직 끝나지 않았습니다'] };
const det = safeJson<any>(m.detail, {});
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);
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: [] };
}
/** 녹음(봇이 음성채널에 있던 구간)이 경기를 덮는지. 빈 곳이 1분 넘으면 이유 문장, 아니면 null */
coverageGap(start: number, end: number): string | null {
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 '녹음 기록이 없습니다';
let cursor = start;
let worst: { at: number; ms: number } | null = null;
for (const s of sess) {
const gs = Math.max(cursor, start);
if (s.started_at - gs > COVERAGE_GAP_MS && (!worst || s.started_at - gs > worst.ms)) worst = { at: gs, ms: s.started_at - gs };
cursor = Math.max(cursor, s.ended_at ?? Number.MAX_SAFE_INTEGER);
}
if (end - cursor > COVERAGE_GAP_MS && (!worst || end - cursor > worst.ms)) worst = { at: cursor, ms: end - cursor };
if (!worst) return null;
const min = Math.max(1, Math.round(worst.ms / 60000));
if (worst.at <= start) return `녹음이 경기 시작 ${min}분 뒤에 시작됐습니다`;
if (worst.at + worst.ms >= end) return `녹음이 경기 끝나기 ${min}분 전에 끝났습니다`;
return `녹음이 경기 중 ${min}분 끊겼습니다`;
}
// ---------------------------------------------------------------- 목록 · 상세
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');
return rows.map((m) => {
const cur = this.current(m.id);
const elig = this.eligibility(m);
return {
match: this.games.summary(m),
eligibility: elig,
culprits: cur
? cur.result.teams.map((t) => {
const p = cur.players.find((x) => x.id === t.culprit);
return { team: t.team, name: p?.name ?? t.culprit, character: p?.character ?? null };
})
: [],
};
});
}
info(m: MatchRow): CulpritMatchInfo {
const det = safeJson<any>(m.detail, {});
const players = this.players(m);
const utts = this.usableUtterances(m.id);
const events = this.store.events(m.id);
const history = (
this.store.db.prepare('SELECT id, created_at, created_by, model, current FROM culprit_analyses WHERE match_id=? ORDER BY created_at DESC').all(m.id) as any[]
).map((r) => ({ id: r.id, at: r.created_at, by: safeJson(r.created_by, { id: '', name: '?' }), model: r.model, current: !!r.current }));
return {
match: this.games.summary(m),
eligibility: this.eligibility(m),
sources: {
rounds: m.game === 'valorant' ? (det.roundsDetail || []).length : null,
events: events.filter((e) => e.type !== 'chat').length,
utterances: utts.length,
chats: events.filter((e) => e.type === 'chat').length,
extraStats: players.some((p) => p.hasExtraStats),
},
players: players.map(({ hasExtraStats: _x, ...p }) => p),
analysis: this.current(m.id),
history,
};
}
// ---------------------------------------------------------------- 결과
current(matchId: string): CulpritAnalysis | null {
const r = this.store.db.prepare('SELECT * FROM culprit_analyses WHERE match_id=? AND current=1 ORDER BY created_at DESC LIMIT 1').get(matchId) as any;
return r ? rowToAnalysis(r) : null;
}
save(matchId: string, a: Omit<CulpritAnalysis, 'id' | 'matchId'>): CulpritAnalysis {
const id = `ca-${matchId}-${a.createdAt}`;
const tx = this.store.db.transaction(() => {
this.store.db.prepare('UPDATE culprit_analyses SET current=0 WHERE match_id=?').run(matchId);
this.store.db
.prepare('INSERT OR REPLACE INTO culprit_analyses(id,match_id,created_at,created_by,model,current,result,meta) VALUES(?,?,?,?,?,1,?,?)')
// 표시 이름(실명 숨기기)을 정하기 전에 시작한 분석이 뒤늦게 와도 예전 이름이 남지 않게 저장할 때 바꾼다
.run(id, matchId, a.createdAt, JSON.stringify(this.store.scrubCreatedBy(a.createdBy)), a.model, this.store.scrubNames(JSON.stringify({ result: a.result, players: a.players })), JSON.stringify(a.meta));
});
tx();
return this.current(matchId)!;
}
// ---------------------------------------------------------------- AI 자료
/** 참가자 번호(P1~P10): 우리 팀 먼저, 팀 안에서는 경기 기록 순서 */
private players(m: MatchRow): (CulpritPlayer & { hasExtraStats: boolean })[] {
const det = safeJson<any>(m.detail, {});
const raw: MatchPlayer[] = det.players || [];
const selfTeam = det.self ? raw.find((p) => p.puuid === det.self)?.team : undefined;
const isAlly = (p: MatchPlayer) => p.ally ?? (selfTeam ? p.team === selfTeam : false);
const sorted = [...raw.filter(isAlly), ...raw.filter((p) => !isAlly(p))];
const accounts = this.store.listAccounts();
const speakers = new Set(this.usableUtterances(m.id).map((u) => u.user_id));
const ratings = ratePlayers(m, det, raw);
return sorted.map((p, i) => {
const userId = p.puuid ? accounts.find((a) => a.puuid === p.puuid)?.user_id : undefined;
return {
id: `P${i + 1}`,
puuid: p.puuid,
name: p.name ?? '?',
team: isAlly(p) ? 'ally' : 'enemy',
character: p.character ?? null,
userId: userId ?? null,
voice: !!userId && speakers.has(userId),
...(ratings.get(p.puuid) ? { rating: ratings.get(p.puuid) } : {}),
hasExtraStats: !!p.stats,
};
});
}
private usableUtterances(matchId: string): UtteranceRow[] {
return (
this.store.db
.prepare(`SELECT rowid,* FROM utterances WHERE match_id=? AND text IS NOT NULL AND text<>'' AND (noise=0 OR corrected=1) ORDER BY started_at, id`)
.all(matchId) as UtteranceRow[]
).filter((u) => !this.store.getUser(u.user_id)?.excluded);
}
/** AI 에 보낼 경기 자료. 숫자 덩어리(JSON) 대신 줄글로 보내 토큰을 아낀다 (계획서 5장) */
buildInput(m: MatchRow): CulpritInput {
const det = safeJson<any>(m.detail, {});
const raw: MatchPlayer[] = det.players || [];
const players = this.players(m);
const byPuuid = new Map(players.filter((p) => p.puuid).map((p) => [p.puuid, p]));
const byUser = new Map(players.filter((p) => p.userId).map((p) => [p.userId!, p]));
const statsOf = (p: CulpritPlayer) => raw.find((r) => r.puuid === p.puuid);
const refs: Record<string, CulpritRefTarget> = {};
const out: string[] = [];
const sum = this.games.summary(m);
const rounds: MatchRound[] = m.game === 'valorant' ? det.roundsDetail || [] : [];
const minutes = m.ended_at ? Math.round((m.ended_at - realStart(m)) / 60000) : 0;
const resultKo = sum.win === null ? '결과 모름' : sum.win ? '우리 팀 승리' : '우리 팀 패배';
const score = sum.score ? `${sum.score.ally}:${sum.score.enemy}` : '?';
const basic = !players.some((p) => p.hasExtraStats);
// 대화: 너무 많으면 짧은 말부터 뺀다
let utts = this.usableUtterances(m.id);
const totalUtts = utts.length;
if (utts.length > MAX_UTTERANCES) {
const keep = new Set([...utts].sort((a, b) => [...(b.text ?? '')].length - [...(a.text ?? '')].length).slice(0, MAX_UTTERANCES).map((u) => u.id));
utts = utts.filter((u) => keep.has(u.id));
}
if (m.game === 'valorant') {
out.push(`# 경기 발로란트 ${sum.mode} · ${sum.map.name} · ${score} (${resultKo}) · ${rounds.length}라운드 · ${minutes}분`);
} else {
out.push(`# 경기 리그 오브 레전드 ${sum.mode} · ${sum.map.name} · 킬 ${score} (${resultKo}) · ${minutes}분`);
}
if (basic) out.push('# 이 경기는 기본 기록만 있다 (피해량 · 첫킬 · 시야 같은 추가 지표 없음)');
if (totalUtts > utts.length) out.push(`# 대화가 많아 ${totalUtts}문장 중 짧은 말을 빼고 ${utts.length}문장만 보냄`);
// 참가자
if (m.game === 'valorant') {
const nRounds = rounds.length || 1;
out.push('# 참가자 (번호 이름 팀 요원(역할) K/D/A ACS 라운드당피해 KAST 라운드당피해격차 첫킬/첫데스 헤드샷 설치/해체 스킬사용 음성)');
for (const p of players) {
const s = statsOf(p);
const x = s?.stats;
const cols = [
p.id,
p.name,
p.team === 'ally' ? '우리' : '상대',
`${p.character?.name ?? '?'}${x?.role ? `(${x.role})` : ''}`,
`${s?.kills ?? 0}/${s?.deaths ?? 0}/${s?.assists ?? 0}`,
`ACS${Math.round((s?.score ?? 0) / (x?.rounds || nRounds))}`,
x ? `ADR${Math.round((x.damage ?? 0) / (x.rounds || nRounds))}` : 'ADR?',
x?.kastRounds !== undefined ? `KAST${Math.round((x.kastRounds / (x.rounds || nRounds)) * 100)}%` : '',
x?.damageTaken !== undefined ? `피해격차${signedNum(Math.round(((x.damage ?? 0) - x.damageTaken) / (x.rounds || nRounds)))}` : '',
x ? `첫킬${x.firstKills ?? 0}/첫데스${x.firstDeaths ?? 0}` : '',
x?.headshotPct !== undefined ? `HS${x.headshotPct}%` : '',
x ? `설치${x.plants ?? 0}/해체${x.defuses ?? 0}` : '',
x?.abilityCasts !== undefined ? `스킬${x.abilityCasts}` : '',
s?.rank ? `랭크:${s.rank}` : '',
p.voice ? '음성O' : '음성X',
];
out.push(cols.filter(Boolean).join(' '));
}
} else {
out.push('# 참가자 (번호 이름 팀 챔피언(포지션 추정) K/D/A CS 골드 챔피언피해 받은피해 시야 와드설치/제거/제어와드 10분CS·골드 15분CS·골드 음성)');
for (const p of players) {
const s = statsOf(p);
const x = s?.stats;
const at = (a?: { cs: number; gold: number }) => (a ? `${a.cs}·${a.gold}` : '?');
const cols = [
p.id,
p.name,
p.team === 'ally' ? '우리' : '상대',
`${p.character?.name ?? '?'}${x?.role ? `(${x.role})` : ''}`,
`${s?.kills ?? 0}/${s?.deaths ?? 0}/${s?.assists ?? 0}`,
`CS${s?.cs ?? '?'}`,
`골드${s?.gold ?? '?'}`,
x ? `딜${x.damage ?? '?'} 받은${x.damageTaken ?? '?'} 시야${x.vision ?? '?'} 와드${x.wardsPlaced ?? 0}/${x.wardsKilled ?? 0}/${x.controlWards ?? 0}` : '',
x ? `10분${at(x.at10)} 15분${at(x.at15)}` : '',
p.voice ? '음성O' : '음성X',
];
out.push(cols.filter(Boolean).join(' '));
}
}
for (const p of players) refs[`s:${p.id}`] = { kind: 'stat', pid: p.id };
out.push(...ratingLines(m.game, players));
// 게임 계정이 연결되지 않은 화자
const others = [...new Set(utts.map((u) => u.user_id))].filter((uid) => !byUser.has(uid));
const speakerName = new Map<string, string>();
for (const uid of others) speakerName.set(uid, `${this.store.getUser(uid)?.name ?? uid}(게임 계정 모름)`);
if (others.length) out.push(`# 음성 화자 중 게임 계정을 모르는 사람: ${others.map((u) => speakerName.get(u)).join(', ')}`);
const who = (uid: string) => byUser.get(uid)?.id ?? speakerName.get(uid) ?? uid;
const pRef = (r: any) => (r?.puuid && byPuuid.get(r.puuid)?.id) || r?.name || '?';
if (m.game === 'lol') {
const gd: { t: number; diff: number }[] = det.goldDiff || [];
const pts = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
.map((min) => gd.find((g) => Math.round(g.t / 60000) === min))
.filter(Boolean) as { t: number; diff: number }[];
if (pts.length) out.push(`# 골드 차(우리-상대): ${pts.map((g) => `${Math.round(g.t / 60000)}분 ${g.diff >= 0 ? '+' : ''}${g.diff.toLocaleString('en-US')}`).join(' · ')}`);
}
out.push('# 시간 순서 기록');
type Line = { ts: number; order: number; text: string };
const lines: Line[] = [];
let ei = 0;
let ci = 0;
const events = this.store.events(m.id);
for (const e of events) {
if (e.type === 'round_end' || e.type === 'match_start' || e.type === 'match_end') continue;
if (e.id.includes(':live-round:')) continue;
const d = safeJson<any>(e.data, {});
const t = this.timeline.eventItem(e).time.primary.replace(' · ', ' ');
if (e.type === 'chat') {
const key = `c${++ci}`;
refs[key] = { kind: 'event', id: e.id, ts: e.ts, round: e.round ?? undefined };
const ch = d.channel === 'all' ? '전체채팅' : d.channel === 'party' ? '파티채팅' : '팀채팅';
const sender = (d.sender?.puuid && byPuuid.get(d.sender.puuid)?.id) || d.sender?.name || '?';
lines.push({ ts: e.ts, order: 1, text: `[${key}] ${t} ${ch} ${sender}: ${clip(String(d.text ?? ''), 200)}` });
continue;
}
const desc = describeEvent(e, d, pRef);
if (!desc) continue;
const key = `e${++ei}`;
refs[key] = { kind: 'event', id: e.id, ts: e.ts, round: e.round ?? undefined };
lines.push({ ts: e.ts, order: 0, text: `[${key}] ${t} ${desc}` });
}
// 라운드 요약 (발로란트): 라운드 끝에 넣는다
for (const r of rounds) {
const key = `r${r.num}`;
refs[key] = { kind: 'round', round: r.num, ts: r.startedAt };
lines.push({ ts: r.endedAt, order: 2, text: `[${key}] ${roundLine(r, players)}` });
}
let ui = 0;
for (const u of utts) {
const key = `u${++ui}`;
refs[key] = { kind: 'utterance', id: u.id, ts: u.started_at };
const t = this.timeline.utteranceItem(u).time.primary.replace(' · ', ' ');
lines.push({ ts: u.started_at, order: 1, text: `[${key}] ${t} ${who(u.user_id)}: ${clip(u.text ?? '', 300)}` });
}
lines.sort((a, b) => a.ts - b.ts || a.order - b.order);
for (const l of lines) out.push(l.text);
return {
game: m.game,
text: out.join('\n'),
refs,
players: players.map(({ hasExtraStats: _x, ...p }) => p),
stats: { utterances: utts.length, utterancesTotal: totalUtts, events: ei, chats: ci, rounds: rounds.length, basic },
};
}
}
/** 기록 점수 (OP.GG OP스코어 방식, packages/shared/src/rating.ts). 경기 결과가 없으면 빈 값 */
function ratePlayers(m: MatchRow, det: any, list: MatchPlayer[]): Map<string, PlayerRating> {
if (det.live || list.length < 2) return new Map();
const selfTeam = det.self ? list.find((p) => p.puuid === det.self)?.team : undefined;
const raw = list.map((p) => ({ ...p, ally: p.ally ?? (selfTeam ? p.team === selfTeam : false) }));
if (m.game === 'valorant') {
const rounds: MatchRound[] = det.roundsDetail || [];
return rounds.length ? rateValorant(raw, rounds) : new Map();
}
const minutes = m.ended_at ? (m.ended_at - realStart(m)) / 60000 : 0;
if (minutes < 1) return new Map();
const win = safeJson<{ win?: boolean | null }>(m.result, {}).win;
return rateLol(raw, minutes, typeof win === 'boolean' ? win : null);
}
/** AI 자료의 "기록 점수" 칸: 점수 · 순위 · MVP/ACE · 점수를 올리고 깎은 지표 · 롤 라인전 */
function ratingLines(game: string, players: CulpritPlayer[]): string[] {
if (!players.some((p) => p.rating)) return [];
const head =
game === 'valorant'
? '# 기록 점수 (0~10, OP.GG OP스코어 계산법: 라운드 승률 · KAST · ACS · 피해 격차로 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점)'
: '# 기록 점수 (0~10, OP.GG OP스코어 계산법: 역할 · 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드로 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점, 라인전 = LOL.PS 라인전 점수의 입력인 10 · 15분 맞라이너와의 CS · 골드 · 경험치 차)';
const out = [head];
if (players.some((p) => p.rating?.basic)) out.push('# (추가 지표가 없어 K/D/A · 골드 · CS 같은 기본 기록으로만 낸 점수다)');
const idOf = new Map(players.map((p) => [p.puuid, p.id]));
for (const p of players) {
const r = p.rating;
if (!r) continue;
const up = r.parts.filter((x) => x.good).map((x) => x.text);
const down = r.parts.filter((x) => !x.good).map((x) => x.text);
const parts = [up.length ? `강점 ${up.join(', ')}` : '', down.length ? `약점 ${down.join(', ')}` : ''].filter(Boolean).join(' / ');
const at = (min: number, d?: LaneDiff) => (d ? ` ${min}분 CS${signedNum(d.cs)} 골드${signedNum(d.gold)} 경험치${signedNum(d.xp)}` : '');
const lane = r.lane ? ` 라인전(vs ${idOf.get(r.lane.vs) ?? '?'})${at(10, r.lane.at10)}${at(15, r.lane.at15)}` : '';
out.push(`${p.id} ${r.score.toFixed(1)}점 ${r.rank}위/팀${r.teamRank}위${r.badge ? ` ${r.badge}` : ''}${parts ? ` · ${parts}` : ''}${lane ? ` ·${lane}` : ''}`);
}
return out;
}
function signedNum(n: number): string {
return `${n >= 0 ? '+' : ''}${n.toLocaleString('en-US')}`;
}
function realStart(m: MatchRow): number {
return m.started_at + m.clock_offset;
}
function clip(s: string, n: number): string {
const t = s.replace(/\s+/g, ' ').trim();
return [...t].length > n ? [...t].slice(0, n).join('') + '…' : t;
}
function describeEvent(e: EventRow, d: any, pRef: (r: any) => string): string | null {
switch (e.type) {
case 'kill': {
const as = (d.assists || []).map(pRef);
const weapon = d.weapon?.name ? ` (${d.weapon.name})` : '';
return `킬 ${d.killer ? pRef(d.killer) : '?'} → ${pRef(d.victim)}${weapon}${as.length ? ` 어시 ${as.join(',')}` : ''}`;
}
case 'multikill':
return `멀티킬 ${pRef(d.player)} ${d.count}킬`;
case 'ace':
return `에이스 ${pRef(d.player)}`;
case 'spike':
return d.action === 'defuse' ? `스파이크 해체 ${pRef(d.player)}` : `스파이크 설치 ${pRef(d.player)}${d.site ? ` (${d.site})` : ''}`;
case 'object': {
const team = d.ally === true ? '우리 팀' : d.ally === false ? '상대 팀' : '';
const who = d.killer && d.object !== 'tower' && d.object !== 'inhibitor' ? ` · ${pRef(d.killer)}` : '';
return `${d.label || d.object} ${d.object === 'tower' || d.object === 'inhibitor' ? '' : '처치 '}${team}${who}`.replace(/\s+/g, ' ').trim();
}
default:
return null;
}
}
function roundLine(r: MatchRound, players: CulpritPlayer[]): string {
const side = r.allyAttack === undefined ? '' : r.allyAttack ? ' 우리 공격' : ' 우리 수비';
const avg = (team: 'ally' | 'enemy') => {
const vals = players
.filter((p) => p.team === team)
.map((p) => r.economy?.[p.puuid]?.loadout)
.filter((v): v is number => typeof v === 'number');
return vals.length ? Math.round(vals.reduce((a, b) => a + b, 0) / vals.length) : null;
};
const a = avg('ally');
const en = avg('enemy');
const eco = a !== null && en !== null ? ` · 평균 장비 우리 ${a.toLocaleString('en-US')} / 상대 ${en.toLocaleString('en-US')}` : '';
const per = players
.map((p) => {
const ec = r.economy?.[p.puuid];
const st = r.players?.[p.puuid];
if (!ec && !st) return null;
const lo = ec?.loadout !== undefined ? `${(ec.loadout / 1000).toFixed(1)}k` : ec ? `${(ec.spent / 1000).toFixed(1)}k쓴` : '?';
return `${p.id} ${lo}${st ? `/${st.damage}` : ''}`;
})
.filter(Boolean);
return `R${r.num}${side} 라운드 끝 · ${r.win ? '승리' : '패배'}(${r.result}) ${r.score.ally}:${r.score.enemy}${eco}${per.length ? ` · 선수 장비/피해: ${per.join(' ')}` : ''}`;
}
function rowToAnalysis(r: any): CulpritAnalysis {
const body = safeJson<any>(r.result, {});
return {
id: r.id,
matchId: r.match_id,
createdAt: r.created_at,
createdBy: safeJson(r.created_by, { id: '', name: '?' }),
model: r.model,
result: body.result,
players: body.players || [],
meta: safeJson(r.meta, {}),
};
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -10,36 +10,18 @@ import {
type AudioPlayer,
type VoiceConnection,
} from '@discordjs/voice';
import {
ChannelType,
Client,
Events,
GatewayIntentBits,
MessageFlags,
type ChatInputCommandInteraction,
type Guild,
type GuildMember,
type VoiceBasedChannel,
type VoiceState,
} from 'discord.js';
import fs from 'node:fs';
import type { Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { Bus } from '../util/events.js';
import { newId } from '../util/ids.js';
import type { BotGateway, GChannel, GCommand, GMember, GVoiceEvent } from './gateway.js';
import { logger } from '../util/log.js';
import type { Recorder } from './recorder.js';
import type { Announcer } from './tts.js';
import { isOgg, type Announcer } from './tts.js';
const log = logger('bot');
export const COMMANDS = [
{ name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' },
{ name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' },
{ name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' },
{ name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' },
];
export interface BotState {
status: 'off' | 'connecting' | 'ready' | 'error';
error: string | null;
@@ -52,9 +34,10 @@ export interface BotState {
/**
* 디스코드 봇: 나를 따라 음성채널에 들어가거나(/녹음시작) 명령으로 참여하고, TTS 로 녹음 사실을 알린다 (Q7, Q8).
* 채팅 메시지는 보내지 않는다. 명령 응답은 본인에게만 보인다.
* 디스코드 연결은 BotGateway 가 맡는다 (겜녹이 봇 = 사이트 서버 중계, 다른 봇 = 이 PC 가 직접 연결)
*/
export class Bot {
client: Client | null = null;
gateway: BotGateway | null = null;
private connection: VoiceConnection | null = null;
private player: AudioPlayer | null = null;
private sessionId: string | null = null;
@@ -77,134 +60,162 @@ export class Bot {
private onGuild?: (guildId: string) => void,
) {}
async start(token: string): Promise<void> {
async start(gw: BotGateway): Promise<void> {
await this.stop();
this.state.status = 'connecting';
this.state.error = null;
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers],
});
this.client = client;
client.on(Events.ClientReady, () => void this.onReady());
client.on(Events.VoiceStateUpdate, (o, n) => void this.onVoiceState(o, n).catch((e) => log.error('voiceState 처리 오류', e)));
client.on(Events.InteractionCreate, (i) => {
if (i.isChatInputCommand()) void this.onCommand(i).catch((e) => log.error('명령 처리 오류', e));
});
client.on(Events.Error, (e) => log.error('discord 오류', e));
client.on(Events.GuildCreate, () => this.refreshGuilds());
this.gateway = gw;
const mine = (fn: (...a: any[]) => void) => (...a: any[]) => {
if (this.gateway === gw) fn(...a);
};
gw.on('ready', mine(() => void this.onReady().catch((e) => log.error('봇 준비 처리 오류', e))));
gw.on('guilds', mine(() => this.refreshGuilds()));
gw.on('voiceState', mine((e: GVoiceEvent) => void this.onVoiceState(e).catch((err) => log.error('voiceState 처리 오류', err))));
gw.on('command', mine((c: GCommand, respond: (content: string) => void) => void this.onCommand(c).then(respond, (e) => respond(`처리하지 못했습니다: ${e.message}`))));
gw.on('taken', mine((guildId: string) => {
if (this.connection && this.state.recording.channelId && this.state.guild?.id === guildId) {
log.warn('다른 PC 가 이 서버에서 겜녹이 봇을 데려가 녹음을 멈춥니다');
this.leave('taken');
}
}));
gw.on('down', mine(() => {
this.leave('gateway-down');
this.state.status = 'connecting';
this.state.error = '연결이 끊겨 다시 연결하는 중입니다';
}));
gw.on('unauthorized', mine(() => {
this.state.status = 'error';
this.state.error = '로그인이 만료되었거나 등록이 해제되었습니다';
}));
try {
await client.login(token);
await gw.start();
} catch (e: any) {
if (this.gateway !== gw) return;
this.state.status = 'error';
this.state.error = e?.message?.includes('TOKEN_INVALID') || e?.code === 'TokenInvalid' ? '봇 토큰이 올바르지 않습니다' : e.message;
this.client = null;
// 겜녹이 봇(서버 중계)은 뒤에서 계속 다시 붙는다. 다른 봇은 토큰이 틀렸을 수 있으니 멈춘다
if (gw.kind === 'local') {
this.gateway = null;
await gw.stop().catch(() => undefined);
}
throw e;
}
}
async stop(): Promise<void> {
this.leave('stop');
if (this.client) {
await this.client.destroy();
this.client = null;
const gw = this.gateway;
this.gateway = null;
if (gw) {
gw.removeAllListeners();
await gw.stop();
}
this.state.status = 'off';
this.state.user = null;
}
/** 녹음에서 빼야 하는 다른 봇인지 */
isBot(userId: string): boolean {
return !!this.gateway?.isBot(userId);
}
private refreshGuilds(): void {
if (!this.client) return;
this.state.guilds = [...this.client.guilds.cache.values()].map((g) => ({ id: g.id, name: g.name }));
this.state.guilds = (this.gateway?.guilds() ?? []).map((g) => ({ id: g.id, name: g.name }));
}
guild(): Guild | null {
if (!this.client) return null;
/** 녹음할 디스코드 서버 아이디 (설정값, 없으면 봇이 들어간 첫 서버) */
guildId(): string | null {
const gs = this.gateway?.guilds() ?? [];
const id = this.settings().discord.guildId;
return (id && this.client.guilds.cache.get(id)) || this.client.guilds.cache.first() || null;
return (id && gs.find((g) => g.id === id)?.id) || gs[0]?.id || null;
}
members(): Promise<GMember[]> {
const gid = this.guildId();
return gid && this.gateway ? this.gateway.members(gid) : Promise.resolve([]);
}
private async onReady(): Promise<void> {
const c = this.client!;
const gw = this.gateway!;
const me = gw.me()!;
this.state.status = 'ready';
this.state.user = { id: c.user!.id, name: c.user!.username, avatar: c.user!.displayAvatarURL({ size: 128 }) };
this.state.error = null;
this.state.user = { id: me.id, name: me.name, avatar: me.avatar };
this.refreshGuilds();
const g = this.guild();
log.info(`봇 로그인: ${c.user!.tag}, 서버 ${this.state.guilds.map((x) => x.name).join(', ')}`);
if (!g) return;
this.state.guild = { id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) };
log.info(`봇 로그인: ${me.name}${gw.kind === 'remote' ? ' (사이트 서버 중계)' : ''}, 서버 ${this.state.guilds.map((x) => x.name).join(', ')}`);
const gid = this.guildId();
if (!gid) return;
const g = await gw.watch(gid, { commands: this.settings().discord.commandsEnabled });
if (!g || this.gateway !== gw) return;
this.state.guild = { id: g.id, name: g.name, icon: g.icon };
this.onGuild?.(g.id);
if (this.settings().discord.commandsEnabled) {
try {
await g.commands.set(COMMANDS);
log.info('슬래시 명령 등록 완료');
} catch (e) {
log.warn('슬래시 명령 등록 실패', e);
}
}
// 이미 따라갈 유저가 음성채널에 있으면 바로 들어간다
const follow = this.settings().discord.followUserId;
if (follow && this.settings().discord.followEnabled) {
const m = await g.members.fetch(follow).catch(() => null);
if (m?.voice.channel) await this.join(m.voice.channel, 'follow');
const ch = gw.voiceChannelOf(g.id, follow);
if (ch) await this.join(ch, 'follow').catch((e) => log.warn(`따라가기 실패: ${e.message}`));
}
}
private async onVoiceState(o: VoiceState, n: VoiceState): Promise<void> {
const g = this.guild();
if (!g || n.guild.id !== g.id) return;
private async onVoiceState(e: GVoiceEvent): Promise<void> {
const gid = this.state.guild?.id;
if (!gid || e.guildId !== gid) return;
const s = this.settings().discord;
const uid = n.id;
if (uid === this.client?.user?.id) {
const uid = e.member.id;
if (uid === this.state.user?.id) {
// 누군가 봇을 끊었으면 세션 종료
if (o.channelId && !n.channelId) this.leave('kicked');
if (e.oldChannelId && !e.newChannelId) this.leave('kicked');
return;
}
// 따라가기
if (s.followEnabled && s.followUserId === uid && o.channelId !== n.channelId) {
if (n.channel) await this.join(n.channel, 'follow');
if (s.followEnabled && s.followUserId === uid && e.oldChannelId !== e.newChannelId) {
if (e.channel) await this.join(e.channel, 'follow');
else if (this.state.recording.reason === 'follow') this.leave('follow-left');
}
const myCh = this.state.recording.channelId;
if (!myCh) return;
// 새 사람이 들어오면 안내를 다시 튼다
if (n.channelId === myCh && o.channelId !== myCh && n.member && (!n.member.user.bot || process.env.GVR_RECORD_BOTS === '1')) {
this.touchUser(n.member);
if (e.newChannelId === myCh && e.oldChannelId !== myCh && (!e.member.bot || process.env.GVR_RECORD_BOTS === '1')) {
this.touchUser(e.member);
this.updateParticipants();
if (s.ttsEnabled && s.ttsOnNewMember) void this.announce();
}
if (o.channelId === myCh && n.channelId !== myCh) this.updateParticipants();
if (e.oldChannelId === myCh && e.newChannelId !== myCh) this.updateParticipants();
}
private touchUser(m: GuildMember): void {
this.store.upsertUser({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }) });
private touchUser(m: GMember): void {
this.store.upsertUser({ id: m.id, name: m.name, avatar: m.avatar });
}
private channelMembers(): GMember[] {
const id = this.state.recording.channelId;
const gid = this.state.guild?.id;
return id && gid && this.gateway ? this.gateway.channelMembers(gid, id) : [];
}
private updateParticipants(): void {
const ch = this.currentChannel();
const inCh = !!this.state.recording.channelId;
// GVR_RECORD_BOTS=1 (테스트봇으로 시험할 때)이면 봇도 사람처럼 센다. 안 그러면 30초 뒤 '빈 방'으로 나가 버린다.
const humans = ch ? [...ch.members.values()].filter((m) => !m.user.bot || (process.env.GVR_RECORD_BOTS === '1' && m.id !== this.client?.user?.id)) : [];
const humans = this.channelMembers().filter((m) => !m.bot || (process.env.GVR_RECORD_BOTS === '1' && m.id !== this.state.user?.id));
this.state.recording.participants = humans.map((m) => m.id);
this.emitState();
// 사람이 아무도 없으면 30초 뒤 나간다
if (this.emptyTimer) clearTimeout(this.emptyTimer);
this.emptyTimer = null;
if (ch && humans.length === 0) this.emptyTimer = setTimeout(() => this.leave('empty'), 30000);
if (inCh && humans.length === 0) this.emptyTimer = setTimeout(() => this.leave('empty'), 30000);
}
private currentChannel(): VoiceBasedChannel | null {
const id = this.state.recording.channelId;
if (!id || !this.client) return null;
const ch = this.client.channels.cache.get(id);
return ch && (ch.type === ChannelType.GuildVoice || ch.type === ChannelType.GuildStageVoice) ? (ch as VoiceBasedChannel) : null;
}
async join(channel: VoiceBasedChannel, reason: 'follow' | 'command'): Promise<void> {
async join(channel: GChannel, reason: 'follow' | 'command'): Promise<void> {
const gw = this.gateway;
const gid = this.state.guild?.id;
if (!gw || !gid) throw new Error('봇이 준비되지 않았습니다');
if (this.state.recording.channelId === channel.id && this.connection) return;
if (this.connection) this.leave('move');
log.info(`음성채널 참여: ${channel.name} (${reason})`);
const conn = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
guildId: gid,
adapterCreator: gw.adapterCreator(gid),
selfDeaf: false,
selfMute: false,
daveEncryption: true,
@@ -221,20 +232,29 @@ export class Bot {
if (this.connection === conn) this.leave('disconnected');
}
});
// 연결 통로가 끊겨 어댑터가 사라진 경우 (서버 중계 끊김 등)
conn.on(VoiceConnectionStatus.Destroyed, () => {
if (this.connection === conn) this.leave('destroyed');
});
try {
await entersState(conn, VoiceConnectionStatus.Ready, 20000);
} catch (e) {
log.error('음성채널 연결 실패', e);
conn.destroy();
if (this.connection === conn) this.connection = null;
try {
conn.destroy();
} catch {
/* 이미 끊김 */
}
throw new Error('음성채널 연결 실패');
}
if (this.connection !== conn) throw new Error('음성채널 연결이 끊겼습니다');
const now = Date.now();
this.sessionId = newId(now);
this.store.startSession(this.sessionId, channel.guild.id, channel.id, channel.name, now);
for (const m of channel.members.values()) if (!m.user.bot || process.env.GVR_RECORD_BOTS === '1') this.touchUser(m);
this.bus.live({ type: 'users.updated', data: [] });
this.store.startSession(this.sessionId, gid, channel.id, channel.name, now);
this.state.recording = { active: true, channel: channel.name, channelId: channel.id, since: now, participants: [], reason };
for (const m of this.channelMembers()) if (!m.bot || process.env.GVR_RECORD_BOTS === '1') this.touchUser(m);
this.bus.live({ type: 'users.updated', data: [] });
this.recorder.attach(conn, this.sessionId);
this.player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause } });
conn.subscribe(this.player);
@@ -246,15 +266,16 @@ export class Bot {
if (this.emptyTimer) clearTimeout(this.emptyTimer);
this.emptyTimer = null;
this.recorder.detach();
if (this.connection) {
const conn = this.connection;
this.connection = null;
if (conn) {
log.info(`음성채널 나감 (${why})`);
try {
this.connection.destroy();
conn.destroy();
} catch {
/* 이미 끊김 */
}
}
this.connection = null;
this.player?.stop(true);
this.player = null;
if (this.sessionId) this.store.endSession(this.sessionId, Date.now());
@@ -269,9 +290,9 @@ export class Bot {
if (!this.player) return;
const s = this.settings().discord;
try {
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice);
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice, s.ttsRate);
if (!this.player) return;
const res = createAudioResource(fs.createReadStream(file), { inputType: StreamType.WebmOpus });
const res = createAudioResource(fs.createReadStream(file), { inputType: isOgg(file) ? StreamType.OggOpus : StreamType.WebmOpus });
this.player.play(res);
await entersState(this.player, AudioPlayerStatus.Playing, 5000).catch(() => undefined);
} catch (e) {
@@ -284,36 +305,35 @@ export class Bot {
this.bus.live({ type: 'recording.state', data: { active: r.active, channel: r.channel, since: r.since, participants: r.participants } });
}
private async onCommand(i: ChatInputCommandInteraction): Promise<void> {
const reply = (content: string) => i.reply({ content, flags: MessageFlags.Ephemeral });
const member = i.member as GuildMember | null;
switch (i.commandName) {
/** 슬래시 명령 처리. 돌려준 문장이 본인에게만 보이는 응답이 된다 */
private async onCommand(c: GCommand): Promise<string> {
if (c.guildId !== this.state.guild?.id) return '이 서버는 겜녹이 앱의 녹음 서버로 설정되어 있지 않습니다.';
switch (c.name) {
case '녹음시작': {
const ch = member?.voice?.channel;
if (!ch) return void (await reply('먼저 음성채널에 들어가 주세요.'));
await i.deferReply({ flags: MessageFlags.Ephemeral });
const ch = c.voiceChannel;
if (!ch) return '먼저 음성채널에 들어가 주세요.';
try {
await this.join(ch, 'command');
await i.editReply(`🎙️ ${ch.name} 채널 녹음을 시작했습니다.`);
return `🎙️ ${ch.name} 채널 녹음을 시작했습니다.`;
} catch (e: any) {
await i.editReply(`음성채널에 들어가지 못했습니다: ${e.message}`);
return `음성채널에 들어가지 못했습니다: ${e.message}`;
}
return;
}
case '녹음종료':
if (!this.connection) return void (await reply('지금은 녹음 중이 아닙니다.'));
if (!this.connection) return '지금은 녹음 중이 아닙니다.';
this.leave('command');
return void (await reply('⏹️ 녹음을 끝냈습니다.'));
return '⏹️ 녹음을 끝냈습니다.';
case '녹음제외':
if (member) this.touchUser(member);
this.store.setExcluded(i.user.id, true);
this.touchUser(c.user);
this.store.setExcluded(c.user.id, true);
this.bus.live({ type: 'users.updated', data: [] });
return void (await reply('🔇 이제부터 내 목소리는 녹음하지 않습니다. 다시 참여하려면 /녹음참여 를 입력하세요.'));
return '🔇 이제부터 내 목소리는 녹음하지 않습니다. 다시 참여하려면 /녹음참여 를 입력하세요.';
case '녹음참여':
if (member) this.touchUser(member);
this.store.setExcluded(i.user.id, false);
this.touchUser(c.user);
this.store.setExcluded(c.user.id, false);
this.bus.live({ type: 'users.updated', data: [] });
return void (await reply('🎙️ 다시 녹음에 참여합니다.'));
return '🎙️ 다시 녹음에 참여합니다.';
}
return '알 수 없는 명령입니다.';
}
}

View File

@@ -0,0 +1,488 @@
// 봇이 디스코드와 이야기하는 통로 두 가지
// - LocalGateway: '다른 봇으로 진행하기' (사용자가 넣은 봇 토큰으로 이 PC 가 직접 연결)
// - RemoteGateway: 겜녹이 봇. 봇 토큰은 사이트 서버에만 있고, 이 PC 는 서버(/app/bot/ws)를 거쳐 정보만 받는다.
// 음성채널에 들어갈 때 서버가 디스코드에서 받은 일회용 음성 접속 정보를 넘겨주고, 음성은 이 PC ↔ 디스코드로 바로 간다
import type { DiscordGatewayAdapterCreator, DiscordGatewayAdapterLibraryMethods } from '@discordjs/voice';
import type { BotGwChannel, BotGwFromApp, BotGwGuild, BotGwMember, BotGwToApp } from '@gvr/shared';
import { ActivityType, ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
import { EventEmitter } from 'node:events';
import WebSocket from 'ws';
import { logger } from '../util/log.js';
import { TLS_TRUST } from '../util/secure-http.js';
import { wsUrl } from '../util/secure-url.js';
const log = logger('gateway');
export type GMember = BotGwMember;
export type GGuild = BotGwGuild;
export type GChannel = BotGwChannel;
export interface GVoiceEvent {
guildId: string;
member: GMember;
oldChannelId: string | null;
newChannelId: string | null;
channel: GChannel | null;
}
export interface GCommand {
name: string;
guildId: string;
user: GMember;
voiceChannel: GChannel | null;
}
export const COMMANDS = [
{ name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' },
{ name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' },
{ name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' },
{ name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' },
];
/**
* 이벤트: 'ready' · 'guilds' · 'voiceState' (GVoiceEvent) · 'command' (GCommand, respond(content)) ·
* 'taken' (guildId: 다른 PC 가 봇을 데려감) · 'down' (연결 끊김) · 'unauthorized' (앱 로그인 만료 · 등록 해제)
*/
export interface BotGateway extends EventEmitter {
readonly kind: 'local' | 'remote';
me(): GMember | null;
guilds(): GGuild[];
start(): Promise<void>;
stop(): Promise<void>;
/** 이 서버의 음성 상태를 따라간다 (명령 등록 포함) */
watch(guildId: string, opts: { commands: boolean }): Promise<GGuild | null>;
voiceChannelOf(guildId: string, userId: string): GChannel | null;
channel(guildId: string, channelId: string): GChannel | null;
channelMembers(guildId: string, channelId: string): GMember[];
members(guildId: string): Promise<GMember[]>;
isBot(userId: string): boolean;
adapterCreator(guildId: string): DiscordGatewayAdapterCreator;
}
const gm = (m: GuildMember): GMember => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }), bot: m.user.bot });
const gg = (g: Guild): GGuild => ({ id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) });
const isVoice = (c: { type: ChannelType } | null | undefined): c is VoiceBasedChannel => !!c && (c.type === ChannelType.GuildVoice || c.type === ChannelType.GuildStageVoice);
// ------------------------------------------------------------------ 다른 봇 (토큰으로 직접 연결)
export class LocalGateway extends EventEmitter implements BotGateway {
readonly kind = 'local';
private client: Client | null = null;
constructor(private token: string) {
super();
}
/** 봇 상태 메시지: 음성채널에 있으면(= 녹음 중) 빨간 "녹음 중" (겜녹이 봇은 사이트 서버가 같은 일을 한다) */
private recording: boolean | null = null;
private updatePresence(): void {
const c = this.client;
if (!c?.isReady()) return;
const on = c.guilds.cache.some((g) => !!g.members.me?.voice.channelId);
if (on === this.recording) return;
this.recording = on;
c.user.setPresence(
on
? { status: 'dnd', activities: [{ type: ActivityType.Custom, name: 'custom', state: '🔴 녹음 중' }] }
: { status: 'online', activities: [{ type: ActivityType.Custom, name: 'custom', state: '🎙️ 대기 중 · /녹음시작' }] },
);
}
async start(): Promise<void> {
const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers] });
this.client = c;
this.recording = null;
c.on(Events.ClientReady, () => {
this.updatePresence();
this.emit('ready');
});
c.on(Events.GuildCreate, () => this.emit('guilds'));
c.on(Events.GuildDelete, () => this.emit('guilds'));
c.on(Events.Error, (e) => log.error('discord 오류', e));
c.on(Events.VoiceStateUpdate, (o, n) => {
if (n.id === c.user?.id) this.updatePresence();
const m = n.member ?? o.member;
if (!m) return;
const ch = n.channel;
this.emit('voiceState', { guildId: n.guild.id, member: gm(m), oldChannelId: o.channelId, newChannelId: n.channelId, channel: ch ? { id: ch.id, name: ch.name } : null } satisfies GVoiceEvent);
});
c.on(Events.InteractionCreate, async (i) => {
if (!i.isChatInputCommand() || !i.guildId) return;
try {
await i.deferReply({ flags: MessageFlags.Ephemeral });
} catch (e) {
log.error('명령 응답 실패', e);
return;
}
const m = (i.member as GuildMember | null) ?? null;
const vc = m?.voice?.channel ?? null;
const cmd: GCommand = {
name: i.commandName,
guildId: i.guildId,
user: m ? gm(m) : { id: i.user.id, name: i.user.username, avatar: null, bot: i.user.bot },
voiceChannel: vc ? { id: vc.id, name: vc.name } : null,
};
this.emit('command', cmd, (content: string) => void i.editReply(content).catch((e) => log.error('명령 응답 실패', e)));
});
try {
await c.login(this.token);
} catch (e) {
this.client = null;
throw e;
}
}
async stop(): Promise<void> {
const c = this.client;
this.client = null;
await c?.destroy();
}
me(): GMember | null {
const u = this.client?.isReady() ? this.client.user : null;
return u ? { id: u.id, name: u.username, avatar: u.displayAvatarURL({ size: 128 }), bot: true } : null;
}
guilds(): GGuild[] {
return this.client ? [...this.client.guilds.cache.values()].map(gg) : [];
}
private g(id: string): Guild | null {
return this.client?.guilds.cache.get(id) ?? null;
}
async watch(guildId: string, opts: { commands: boolean }): Promise<GGuild | null> {
const g = this.g(guildId);
if (!g) return null;
if (opts.commands) {
try {
await g.commands.set(COMMANDS);
log.info('슬래시 명령 등록 완료');
} catch (e) {
log.warn('슬래시 명령 등록 실패', e);
}
}
return gg(g);
}
voiceChannelOf(guildId: string, userId: string): GChannel | null {
const ch = this.g(guildId)?.voiceStates.cache.get(userId)?.channel;
return ch ? { id: ch.id, name: ch.name } : null;
}
channel(guildId: string, channelId: string): GChannel | null {
const ch = this.g(guildId)?.channels.cache.get(channelId);
return isVoice(ch) ? { id: ch.id, name: ch.name } : null;
}
channelMembers(guildId: string, channelId: string): GMember[] {
const ch = this.g(guildId)?.channels.cache.get(channelId);
return isVoice(ch) ? [...ch.members.values()].map(gm) : [];
}
async members(guildId: string): Promise<GMember[]> {
const g = this.g(guildId);
if (!g) return [];
const ms = await g.members.fetch().catch(() => g.members.cache);
return [...ms.values()].map(gm);
}
isBot(userId: string): boolean {
return !!this.client?.users.cache.get(userId)?.bot;
}
adapterCreator(guildId: string): DiscordGatewayAdapterCreator {
const g = this.g(guildId);
if (!g) throw new Error('디스코드 서버를 찾지 못했습니다');
return g.voiceAdapterCreator;
}
}
// ------------------------------------------------------------------ 겜녹이 봇 (사이트 서버 중계)
export interface RemoteGatewayOptions {
serverUrl: () => string;
appToken: () => string | null;
version: string;
}
export class RemoteGateway extends EventEmitter implements BotGateway {
readonly kind = 'remote';
private ws: WebSocket | null = null;
private stopped = true;
private retries = 0;
private retryTimer: NodeJS.Timeout | null = null;
private _me: GMember | null = null;
private _guilds: GGuild[] = [];
private watched: { id: string; commands: boolean } | null = null;
private wait: { resolve: (g: GGuild | null) => void } | null = null;
private channels = new Map<string, GChannel>();
/** userId → 음성채널 */
private voice = new Map<string, string>();
private known = new Map<string, GMember>();
private adapters = new Map<string, DiscordGatewayAdapterLibraryMethods>();
private reqs = new Map<string, { resolve: (v: any) => void; reject: (e: Error) => void }>();
private seq = 0;
lastError: string | null = null;
constructor(private opts: RemoteGatewayOptions) {
super();
}
/** 서버에 붙어 ready 를 받을 때까지 기다린다 (실패해도 뒤에서 계속 다시 붙는다) */
start(): Promise<void> {
try {
wsUrl(this.opts.serverUrl(), '/app/bot/ws');
} catch (e) {
return Promise.reject(e);
}
this.stopped = false;
return new Promise((resolve, reject) => {
const t = setTimeout(() => {
cleanup();
reject(new Error(this.lastError || '사이트 서버의 겜녹이 봇에 연결하지 못했습니다'));
}, 20000);
const ok = () => {
cleanup();
resolve();
};
const bad = () => {
cleanup();
reject(new Error(this.lastError || '다시 로그인해 주세요'));
};
const cleanup = () => {
clearTimeout(t);
this.off('ready', ok);
this.off('unauthorized', bad);
};
this.once('ready', ok);
this.once('unauthorized', bad);
this.connect();
});
}
async stop(): Promise<void> {
this.stopped = true;
if (this.retryTimer) clearTimeout(this.retryTimer);
this.retryTimer = null;
const ws = this.ws;
this.ws = null;
this.reset();
ws?.close(1000);
}
private reset(): void {
this._me = null;
for (const a of this.adapters.values()) a.destroy();
this.adapters.clear();
for (const r of this.reqs.values()) r.reject(new Error('사이트 서버 연결이 끊겼습니다'));
this.reqs.clear();
this.wait?.resolve(null);
this.wait = null;
}
private connect(): void {
if (this.stopped) return;
const token = this.opts.appToken();
if (!token) {
this.lastError = '로그인이 필요합니다';
this.emit('unauthorized');
return;
}
let url: string;
try {
url = wsUrl(this.opts.serverUrl(), '/app/bot/ws');
} catch (e: any) {
// 암호화되지 않은 주소로는 로그인 토큰을 보내지 않는다 (다시 시도하지 않음: 주소를 고쳐야 한다)
this.lastError = e.message;
log.error(e.message);
return;
}
const ws = new WebSocket(url, { headers: { authorization: `Bearer ${token}`, 'x-gvr-version': this.opts.version }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024, ...TLS_TRUST });
this.ws = ws;
let unauthorized = false;
let alive = Date.now();
const ping = setInterval(() => {
// 서버가 30초마다 ping 을 보낸다. 75초 동안 아무것도 없으면 끊고 다시 붙는다
if (Date.now() - alive > 75000) ws.terminate();
}, 15000);
ws.on('ping', () => (alive = Date.now()));
ws.on('open', () => {
this.retries = 0;
alive = Date.now();
log.info('사이트 서버 겜녹이 봇 중계 연결됨');
});
ws.on('message', (data) => {
alive = Date.now();
let m: BotGwToApp;
try {
m = JSON.parse(String(data));
} catch {
return;
}
this.onMessage(m);
});
ws.on('unexpected-response', (_req, res) => {
unauthorized = res.statusCode === 401;
this.lastError = unauthorized ? '로그인이 만료되었습니다. 다시 로그인해 주세요' : res.statusCode === 503 ? '사이트 서버에 겜녹이 봇이 켜져 있지 않습니다' : `사이트 서버 응답 ${res.statusCode}`;
});
ws.on('error', (e) => {
this.lastError ||= `사이트 서버에 연결할 수 없습니다 (${e.message})`;
});
ws.on('close', (code) => {
clearInterval(ping);
if (this.ws !== ws) return;
this.ws = null;
const wasReady = !!this._me;
this.reset();
if (wasReady) this.emit('down');
if (unauthorized || code === 4401) {
this.lastError = '로그인이 만료되었거나 등록이 해제되었습니다';
this.emit('unauthorized');
}
if (this.stopped) return;
const delay = Math.min(30000, 1000 * 2 ** Math.min(this.retries++, 5));
this.retryTimer = setTimeout(() => this.connect(), delay);
});
}
private send(m: BotGwFromApp): boolean {
if (this.ws?.readyState !== WebSocket.OPEN) return false;
this.ws.send(JSON.stringify(m));
return true;
}
private remember(m: GMember): void {
this.known.set(m.id, m);
}
private onMessage(m: BotGwToApp): void {
switch (m.t) {
case 'ready':
this.lastError = null;
this._me = m.me;
this._guilds = m.guilds;
this.emit('ready');
return;
case 'guilds':
this._guilds = m.guilds;
this.emit('guilds');
return;
case 'guild':
if (this.watched?.id !== m.guild.id) return;
this.channels.clear();
this.voice.clear();
for (const c of m.channels) this.channels.set(c.id, c);
for (const v of m.voice) {
this.remember(v.member);
this.voice.set(v.member.id, v.channelId);
}
this.wait?.resolve(m.guild);
this.wait = null;
return;
case 'watch_denied':
// 이 유저가 가입하지 않은 서버
if (this.watched?.id !== m.guildId) return;
log.warn('이 디스코드 서버에 가입되어 있지 않아 녹음할 수 없습니다');
if (this.wait) {
this.wait.resolve(null);
this.wait = null;
return;
}
// 지켜보던 중에 서버가 권한을 다시 확인하다 끊은 경우: 그대로 두면 슬래시 명령 · 음성 상태가 영영 안 오므로 1분 뒤 다시 요청한다
// (정말 탈퇴했으면 다시 거절될 뿐이다)
setTimeout(() => {
const w = this.watched;
if (w?.id === m.guildId && !this.wait) this.send({ t: 'watch', guildId: w.id, commands: w.commands });
}, 60000).unref();
return;
case 'voiceState':
if (this.watched?.id !== m.guildId) return;
this.remember(m.member);
if (m.channel) this.channels.set(m.channel.id, m.channel);
if (m.newChannelId) this.voice.set(m.member.id, m.newChannelId);
else this.voice.delete(m.member.id);
this.emit('voiceState', { guildId: m.guildId, member: m.member, oldChannelId: m.oldChannelId, newChannelId: m.newChannelId, channel: m.channel } satisfies GVoiceEvent);
return;
case 'cmd': {
this.remember(m.user);
const cmd: GCommand = { name: m.name, guildId: m.guildId, user: m.user, voiceChannel: m.voiceChannel };
this.emit('command', cmd, (content: string) => void this.send({ t: 'cmd_res', id: m.id, content }));
return;
}
case 'vserver':
this.adapters.get(m.guildId)?.onVoiceServerUpdate(m.data);
return;
case 'vstate':
this.adapters.get(m.guildId)?.onVoiceStateUpdate(m.data);
return;
case 'taken':
this.emit('taken', m.guildId);
return;
case 'res': {
const r = this.reqs.get(m.id);
if (!r) return;
this.reqs.delete(m.id);
if (m.ok) r.resolve(m.data);
else r.reject(new Error(m.error || '요청 실패'));
return;
}
}
}
me(): GMember | null {
return this._me;
}
guilds(): GGuild[] {
return this._me ? this._guilds : [];
}
watch(guildId: string, opts: { commands: boolean }): Promise<GGuild | null> {
this.watched = { id: guildId, ...opts };
this.wait?.resolve(null);
return new Promise((resolve) => {
if (!this.send({ t: 'watch', guildId, commands: opts.commands })) return resolve(null);
const t = setTimeout(() => {
if (this.wait?.resolve === done) this.wait = null;
resolve(null);
}, 10000);
const done = (g: GGuild | null) => {
clearTimeout(t);
resolve(g);
};
this.wait = { resolve: done };
});
}
voiceChannelOf(_guildId: string, userId: string): GChannel | null {
const id = this.voice.get(userId);
return id ? (this.channels.get(id) ?? { id, name: id }) : null;
}
channel(_guildId: string, channelId: string): GChannel | null {
return this.channels.get(channelId) ?? null;
}
channelMembers(_guildId: string, channelId: string): GMember[] {
const out: GMember[] = [];
for (const [uid, ch] of this.voice) if (ch === channelId) out.push(this.known.get(uid) ?? { id: uid, name: uid, avatar: null, bot: false });
return out;
}
members(guildId: string): Promise<GMember[]> {
const id = String(++this.seq);
return new Promise((resolve, reject) => {
if (!this.send({ t: 'req', id, op: 'members', guildId })) return reject(new Error('사이트 서버에 연결되어 있지 않습니다'));
const t = setTimeout(() => {
if (this.reqs.delete(id)) reject(new Error('사이트 서버 응답 없음'));
}, 20000);
this.reqs.set(id, {
resolve: (v) => {
clearTimeout(t);
for (const m of v as GMember[]) this.remember(m);
resolve(v);
},
reject: (e) => {
clearTimeout(t);
reject(e);
},
});
});
}
isBot(userId: string): boolean {
return !!this.known.get(userId)?.bot;
}
adapterCreator(guildId: string): DiscordGatewayAdapterCreator {
return (methods) => {
this.adapters.set(guildId, methods);
return {
sendPayload: (payload) => this.send({ t: 'voice', guildId, payload }),
destroy: () => {
if (this.adapters.get(guildId) === methods) this.adapters.delete(guildId);
},
};
};
}
}

View File

@@ -127,3 +127,58 @@ export class OggOpusWriter {
return Math.round(this.samples / 48);
}
}
/** Ogg 파일에서 Opus 패킷을 꺼낸다 (OpusHead · OpusTags 포함) */
export function readOggPackets(buf: Buffer): Buffer[] {
const out: Buffer[] = [];
let pos = 0;
let cur: Buffer[] = [];
while (pos + 27 <= buf.length && buf.toString('ascii', pos, pos + 4) === 'OggS') {
const nseg = buf[pos + 26];
const lacing = buf.subarray(pos + 27, pos + 27 + nseg);
let p = pos + 27 + nseg;
for (const l of lacing) {
cur.push(buf.subarray(p, p + l));
p += l;
if (l < 255) {
out.push(Buffer.concat(cur));
cur = [];
}
}
pos = p;
}
return out;
}
/**
* v1.3.5 이하 녹음 고치기: 패킷이 몰려 도착할 때 말 중간에 끼워 넣은 20~60ms 무음 프레임을 뺀다.
* 디스코드는 말하는 도중에 무음 프레임을 보내지 않으므로, 앞뒤가 목소리인 1~3개짜리 무음 묶음은 녹음기가 넣은 것이다.
* @returns 뺀 프레임 수 (0 이면 파일을 건드리지 않음)
*/
export function removeInsertedSilence(file: string): number {
const all = readOggPackets(fs.readFileSync(file));
if (all.length < 3) return 0;
const head = all[0];
const packets = all.slice(2);
const isSil = (p: Buffer) => p.equals(SILENCE_FRAME);
const keep: Buffer[] = [];
let removed = 0;
for (let i = 0; i < packets.length; ) {
if (!isSil(packets[i])) {
keep.push(packets[i++]);
continue;
}
let j = i;
while (j < packets.length && isSil(packets[j])) j++;
if (i > 0 && j < packets.length && j - i <= 3) removed += j - i;
else keep.push(...packets.slice(i, j));
i = j;
}
if (!removed) return 0;
const tmp = `${file}.fix`;
const w = new OggOpusWriter(tmp, head[9] || 2);
for (const p of keep) w.write(p);
w.close();
fs.renameSync(tmp, file);
return removed;
}

View File

@@ -19,14 +19,59 @@ export interface RecorderOptions {
skip: (userId: string) => boolean;
/** ts 시점 진행 중인 경기 ID */
matchAt: (ts: number) => string | null;
/** 저장 직후 (녹음 파일 이름을 날짜 · 말한 사람 · 게임 · 라운드로 바꾼다) */
onSaved?: (id: string) => void;
}
/** RTP 시각 (48kHz 샘플 단위 타임스탬프 + 순번) */
export interface RtpInfo {
seq: number;
ts: number;
}
/** 수신기가 꺼낸 Opus 패킷 → 그 패킷이 담겨 온 RTP 헤더 */
const rtpOf = new WeakMap<Buffer, RtpInfo>();
export function rtpInfo(packet: Buffer): RtpInfo | undefined {
return rtpOf.get(packet);
}
/** 테스트용: 패킷에 RTP 시각을 붙인다 */
export function tagRtp(packet: Buffer, info: RtpInfo): Buffer {
rtpOf.set(packet, info);
return packet;
}
/**
* @discordjs/voice 는 Opus 내용만 넘기고 RTP 순번 · 타임스탬프를 버린다.
* 패킷 도착 시각은 게임 중(CPU 부하)에 2~3개씩 몰려 와서 쉼 계산에 쓸 수 없다 (v1.3.5 까지 말 중간에 무음이 끼어 목소리가 깨짐).
* 그래서 복호화 함수를 감싸 RTP 헤더를 패킷에 붙여 둔다.
*/
export function tapRtp(receiver: unknown): boolean {
const r = receiver as { parsePacket?: (buf: Buffer, ...rest: unknown[]) => Buffer | undefined; __gvrRtp?: boolean };
if (r.__gvrRtp) return true;
if (typeof r.parsePacket !== 'function') return false;
const orig = r.parsePacket.bind(r);
r.parsePacket = (buf: Buffer, ...rest: unknown[]) => {
const packet = orig(buf, ...rest);
if (packet && buf.length >= 12) rtpOf.set(packet, { seq: buf.readUInt16BE(2), ts: buf.readUInt32BE(4) });
return packet;
};
r.__gvrRtp = true;
return true;
}
const FRAME = 960; // 20ms @48kHz
/** 발화 하나 = 파일 하나. 말이 0.8초 끊기면 끝, 최대 30초 (보고서 4장 1~3단계) */
class Utterance {
export class Utterance {
writer: OggOpusWriter;
id: string;
startedAt: number;
lastArrival: number;
/** 첫 패킷의 RTP 타임스탬프 - 그때까지 쓴 샘플 수. 패킷 자리 = ts - rtpBase */
rtpBase: number | null = null;
lastSeq = 0;
constructor(dir: string, now: number) {
this.id = newId(now);
this.startedAt = now;
@@ -36,6 +81,35 @@ class Utterance {
fs.mkdirSync(d, { recursive: true });
this.writer = new OggOpusWriter(path.join(d, `${this.id}.ogg`));
}
/**
* 패킷을 제자리에 쓴다. 디스코드는 말 사이 짧은 쉼에는 패킷을 안 보내므로 빈 자리를 무음 프레임으로 채운다.
* - RTP 타임스탬프가 있으면 그 값으로 자리를 정한다 (도착이 몰리거나 늦어도 소리가 늘어나지 않음)
* - 없으면 도착 시각으로 정하되, 실제 흐른 시간보다 0.2초 넘게 모자랄 때만 채운다 (몰려 온 패킷 사이에 무음을 넣지 않음)
* @returns 쓴 무음 프레임 수, 버린 패킷이면 -1
*/
place(packet: Buffer, now: number, maxGapMs: number): number {
const rtp = rtpOf.get(packet);
let fill = 0;
if (rtp && this.rtpBase !== null) {
const d = (rtp.seq - this.lastSeq) & 0xffff;
if (d === 0 || d > 0x8000) return -1; // 중복 · 순서가 뒤바뀌어 늦게 온 패킷 (그 자리는 이미 지나감)
const behind = ((rtp.ts - this.rtpBase) >>> 0) - this.writer.samples;
if (behind >= FRAME / 2 && behind <= maxGapMs * 48) fill = Math.round(behind / FRAME);
else if (behind > maxGapMs * 48 || behind < -48000) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0; // 타임스탬프가 튐: 다시 맞춘다
} else if (!rtp) {
const lag = now - this.startedAt - this.writer.samples / 48;
if (lag > 200) fill = Math.min(Math.floor((lag - 100) / 20), Math.ceil(maxGapMs / 20));
}
if (rtp) {
if (this.rtpBase === null) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0;
this.lastSeq = rtp.seq;
}
for (let i = 0; i < fill; i++) this.writer.write(SILENCE_FRAME);
this.lastArrival = now;
this.writer.write(packet);
return fill;
}
}
function localDay(ts: number): string {
@@ -61,6 +135,7 @@ export class Recorder {
this.detach();
this.connection = connection;
this.sessionId = sessionId;
if (!tapRtp(connection.receiver)) log.warn('RTP 시각을 읽을 수 없음: 도착 시각으로 쉼을 맞춤');
connection.receiver.speaking.on('start', this.onSpeak);
}
@@ -99,14 +174,8 @@ export class Recorder {
if (!u) {
u = new Utterance(this.opts.audioDir(), now - 20);
this.active.set(userId, u);
} else {
// 말 사이 짧은 쉼은 디스코드가 패킷을 안 보낸다. 무음 프레임으로 채워 실제 시간과 맞춘다.
const gap = now - u.lastArrival;
const missing = Math.round(gap / 20) - 1;
if (missing > 0 && missing * 20 < this.opts.silenceMs() + 200) for (let i = 0; i < missing; i++) u.writer.write(SILENCE_FRAME);
}
u.lastArrival = now;
u.writer.write(packet);
u.place(packet, now, this.opts.silenceMs() + 200);
if (u.writer.samples >= this.opts.maxUtteranceSec() * 48000) {
this.finish(userId);
}
@@ -131,7 +200,7 @@ export class Recorder {
}
const endedAt = u.startedAt + dur;
const matchId = this.opts.matchAt(u.startedAt);
const row = this.store.insertUtterance({
let row = this.store.insertUtterance({
id: u.id,
session_id: this.sessionId,
user_id: userId,
@@ -140,6 +209,12 @@ export class Recorder {
audio_path: u.writer.path,
match_id: matchId,
});
try {
this.opts.onSaved?.(row.id);
row = this.store.getUtterance(row.id) ?? row;
} catch (e) {
log.warn('녹음 파일 이름 바꾸기 실패', e);
}
this.bus.live({ type: 'utterance.created', data: this.timeline.utteranceItem(row) });
this.stt.enqueue(row.id, 'realtime');
log.debug(`발화 저장 ${userId} ${dur}ms ${u.writer.bytes}B`);

View File

@@ -7,6 +7,20 @@ import { logger } from '../util/log.js';
const log = logger('tts');
/** 0.5배보다 느린 부분을 늘리는 함수 (워커 atempo). src 를 tempo 배속으로 바꿔 dst(Ogg Opus)에 쓴다 */
export type TempoFn = (src: string, dst: string, tempo: number) => Promise<void>;
/** 말 속도 0.1~2.0 (Edge TTS 는 0.5~2.0 만 지원해서 그보다 느린 부분은 워커가 늘린다) */
export function clampRate(rate: unknown): number {
const r = typeof rate === 'number' && isFinite(rate) ? rate : 1;
return Math.round(Math.min(2, Math.max(0.1, r)) * 100) / 100;
}
/** 파일 확장자로 디스코드 재생 형식을 고른다 */
export function isOgg(file: string): boolean {
return file.endsWith('.ogg');
}
/**
* 녹음 안내 음성. 미리 합성해서 캐시하고, 문구를 바꾸면 다시 합성한다 (보고서 7-3).
* 합성은 Microsoft Edge 온라인 TTS(무료). 인터넷이 안 되면 기본 문구 음성(앱에 포함)을 쓴다.
@@ -15,38 +29,66 @@ export class Announcer {
constructor(
private cacheDir: string,
private resourcesDir: string,
private tempo: TempoFn | null = null,
) {}
private bundled(): string {
return path.join(this.resourcesDir, 'tts', 'announce-default.webm');
}
cachedPath(text: string, voice: string): string {
const h = crypto.createHash('sha1').update(`${voice}\n${text}`).digest('hex').slice(0, 16);
return path.join(this.cacheDir, `announce-${h}.webm`);
cachedPath(text: string, voice: string, rate = 1): string {
rate = clampRate(rate);
const key = rate === 1 ? `${voice}\n${text}` : `${voice}\n${rate}\n${text}`;
const h = crypto.createHash('sha1').update(key).digest('hex').slice(0, 16);
return path.join(this.cacheDir, `announce-${h}.${rate < 0.5 ? 'ogg' : 'webm'}`);
}
/** 안내 음성 파일 경로 (WebM Opus). 없으면 합성. */
async ensure(text: string, voice: string): Promise<string> {
const p = this.cachedPath(text, voice);
/** 안내 음성 파일 경로 (WebM Opus, 0.5배보다 느리면 Ogg Opus). 없으면 합성. */
async ensure(text: string, voice: string, rate = 1): Promise<string> {
rate = clampRate(rate);
const p = this.cachedPath(text, voice, rate);
if (fs.existsSync(p) && fs.statSync(p).size > 1000) return p;
if (text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled();
if (rate === 1 && text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled();
try {
await synthesize(text, voice, p);
log.info(`안내 음성 합성: ${path.basename(p)}`);
await render(text, voice, rate, p, this.tempo);
log.info(`안내 음성 합성: ${path.basename(p)} (속도 ${rate})`);
return p;
} catch (e) {
log.warn('안내 음성 합성 실패, 기본 음성 사용', e);
// 인터넷이 안 될 때: 기본 음성을 그 속도로만 바꿔 쓴다
if (rate !== 1 && this.tempo && fs.existsSync(this.bundled())) {
const q = path.join(this.cacheDir, `announce-default-${rate}.ogg`);
try {
if (!fs.existsSync(q)) await this.tempo(this.bundled(), q, rate);
return q;
} catch (e2) {
log.warn('기본 음성 속도 바꾸기 실패', e2);
}
}
return this.bundled();
}
}
}
/** 문구를 그 속도로 합성해 outFile 에 쓴다. 0.5배보다 느리면 0.5배로 합성한 뒤 워커가 더 늘린다 (outFile 은 .ogg) */
export async function render(text: string, voice: string, rate: number, outFile: string, tempo: TempoFn | null): Promise<void> {
rate = clampRate(rate);
if (rate >= 0.5) return synthesize(text, voice, outFile, 4, rate);
if (!tempo) throw new Error('0.5배보다 느린 속도는 음성 인식 엔진(워커)이 켜져 있어야 합니다');
const tmp = `${outFile}.half.webm`;
try {
await synthesize(text, voice, tmp, 4, 0.5);
await tempo(tmp, outFile, rate / 0.5);
} finally {
fs.rmSync(tmp, { force: true });
}
}
/** Edge TTS 는 짧은 시간에 여러 번 부르면 429 를 준다. 몇 번 쉬었다가 다시 시도한다. */
export async function synthesize(text: string, voice: string, outFile: string, tries = 4): Promise<void> {
export async function synthesize(text: string, voice: string, outFile: string, tries = 4, rate = 1): Promise<void> {
for (let i = 1; ; i++) {
try {
return await synthesizeOnce(text, voice, outFile);
return await synthesizeOnce(text, voice, outFile, rate);
} catch (e: any) {
if (i >= tries) throw e;
await new Promise((r) => setTimeout(r, 1500 * 2 ** i));
@@ -54,14 +96,14 @@ export async function synthesize(text: string, voice: string, outFile: string, t
}
}
async function synthesizeOnce(text: string, voice: string, outFile: string): Promise<void> {
async function synthesizeOnce(text: string, voice: string, outFile: string, rate: number): Promise<void> {
fs.mkdirSync(path.dirname(outFile), { recursive: true });
const tts = new MsEdgeTTS();
const tmpDir = fs.mkdtempSync(path.join(path.dirname(outFile), '.tts-'));
try {
await tts.setMetadata(voice, OUTPUT_FORMAT.WEBM_24KHZ_16BIT_MONO_OPUS);
const r = await Promise.race([
tts.toFile(tmpDir, text),
tts.toFile(tmpDir, text, rate === 1 ? undefined : { rate: Math.min(2, Math.max(0.5, rate)) }),
new Promise<never>((_, rej) => setTimeout(() => rej(new Error('TTS 시간 초과')), 20000)),
]);
fs.renameSync(r.audioFilePath, outFile);

View File

@@ -40,7 +40,7 @@ export function lolObjectIcon(key: string): string {
interface ValCatalog {
at: number;
agents: Record<string, { name: string; icon: string; abilities: Record<string, { name: string; icon: string | null }> }>;
agents: Record<string, { name: string; icon: string; role?: string; abilities: Record<string, { name: string; icon: string | null }> }>;
maps: Record<string, { uuid: string; name: string; image: string | null; xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }>;
weapons: Record<string, { name: string; icon: string | null }>;
tiers: Record<number, string>;
@@ -81,7 +81,9 @@ export class GameAssets {
}
async refreshVal(force = false): Promise<void> {
if (!force && this.val && Date.now() - this.val.at < DAY) return;
// v1.3: 요원 역할을 저장하지 않던 예전 캐시는 바로 다시 받는다
const hasRoles = this.val && Object.values(this.val.agents).some((a) => a.role);
if (!force && this.val && hasRoles && Date.now() - this.val.at < DAY) return;
const get = async (p: string) => (await request(`https://valorant-api.com/v1/${p}`, { timeoutMs: 20000 })).data?.data;
const [agents, maps, weapons, tiers, modes, version] = await Promise.all([
get('agents?language=ko-KR&isPlayableCharacter=true'),
@@ -95,7 +97,7 @@ export class GameAssets {
for (const a of agents || []) {
const abilities: ValCatalog['agents'][string]['abilities'] = {};
for (const ab of a.abilities || []) abilities[ab.slot] = { name: ab.displayName, icon: assetUrl(ab.displayIcon) };
cat.agents[a.uuid.toLowerCase()] = { name: a.displayName, icon: assetUrl(a.displayIcon)!, abilities };
cat.agents[a.uuid.toLowerCase()] = { name: a.displayName, icon: assetUrl(a.displayIcon)!, role: a.role?.displayName ?? undefined, abilities };
}
for (const m of maps || [])
cat.maps[m.mapUrl] = {
@@ -151,6 +153,10 @@ export class GameAssets {
const a = id ? this.val?.agents[id.toLowerCase()] : undefined;
return { id: id || '', name: a?.name ?? '?', icon: a?.icon ?? null };
}
/** 요원 역할 (타격대 · 척후대 · 전략가 · 감시자). 예전 캐시에는 없다 */
agentRole(id: string | null | undefined): string | null {
return (id && this.val?.agents[id.toLowerCase()]?.role) || null;
}
valMap(mapUrl: string | null | undefined) {
return mapUrl ? this.val?.maps[mapUrl] : undefined;
}

View File

@@ -1,4 +1,5 @@
import type { ChatData, KillData, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared';
import type { ChatData, KillData, LiveGame, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared';
import { lolModeKo } from './modes.js';
import type { EventRow } from '../db/db.js';
import { logger } from '../util/log.js';
import { lolObjectIcon } from './assets.js';
@@ -47,7 +48,8 @@ const DRAGON_KO: Record<string, string> = {
* 리그 오브 레전드 어댑터 (보고서 6-5).
* - 게임 클라이언트 API(127.0.0.1:2999): 게임 시간, 10명 KDA·CS·아이템, 킬·오브젝트 이벤트
* - 롤 클라이언트(LCU): 경기 ID·결과·경기 기록(타임라인), 챔피언 선택·게임 후 채팅
* - 게임 중 채팅: 화면 OCR (STT 워커) 또는 로그 파일(남아 있을 때)
* - 게임 중 전체 · 팀 채팅: 롤은 이걸 주는 API 가 없다 (LCU · 게임 클라이언트 API 모두). 화면 글자 인식(OCR)은 쓰지 않고,
* 게임 로그 파일(r3dlog)에 채팅이 남아 있을 때만 경기 뒤에 읽는다
*/
export class LolAdapter implements GameAdapter {
readonly game = 'lol' as const;
@@ -61,15 +63,16 @@ export class LolAdapter implements GameAdapter {
private pendingChat: EventRow[] = [];
private detailQueue = new Map<string, { gameId: number; tries: number; endedAt: number; startedAt: number }>();
private summonerNames = new Map<string, string>();
private ocrSeen = new Set<string>();
private lastMatchId: string | null = null;
private lastErr = '';
/** LCU 게임 진행 단계 (Lobby · Matchmaking · ChampSelect · InProgress …) */
private phase: string | null = null;
private queueName: string | null = null;
/** 게임 클라이언트 API 마지막 값 (지금 게임 상태 표시용) */
private snap: { at: number; gameTime: number; mode: string | null; champ: string | null; champIcon: string | null; kda: string | null; extra: string | null; teamKills: { ally: number; enemy: number } | null; players: number } | null = null;
private selfRiotId: string | null = null;
constructor(private host: AdapterHost) {
host.worker.on('event', (ev: any) => {
if (ev.event === 'ocr_line') this.onOcrLine(ev);
});
}
constructor(private host: AdapterHost) {}
start(): void {
if (this.timer) return;
@@ -80,12 +83,54 @@ export class LolAdapter implements GameAdapter {
if (this.timer) clearInterval(this.timer);
if (this.lcuTimer) clearInterval(this.lcuTimer);
this.timer = this.lcuTimer = null;
if (this.live) void this.host.worker.request('ocr_stop', {}, 5000).catch(() => undefined);
}
status() {
return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined };
}
liveGame(): LiveGame {
const enabled = this.host.settings().games.lol;
const inMatch = !!this.live && !this.live.ended;
const snap = inMatch && this.snap && Date.now() - this.snap.at < 15000 ? this.snap : null;
const PHASE: Record<string, string> = {
None: '메인 화면',
Lobby: '로비',
Matchmaking: '대기열',
CheckedIntoTournament: '토너먼트 대기',
ReadyCheck: '수락 대기',
ChampSelect: '챔피언 선택',
GameStart: '게임 불러오는 중',
FailedToLaunch: '게임 실행 실패',
InProgress: '경기 중',
Reconnect: '다시 연결 필요',
WaitingForStats: '결과 기다리는 중',
PreEndOfGame: '경기 끝',
EndOfGame: '경기 끝 · 결과 화면',
TerminatedInError: '오류로 종료',
};
const phase = !enabled ? '연동 꺼짐' : inMatch ? '경기 중' : this.lcu ? (PHASE[this.phase ?? ''] ?? this.phase ?? '연결됨') : '롤 클라이언트 꺼짐';
return {
game: 'lol',
enabled,
connected: !!this.lcu || !!this.live,
phase,
inMatch,
matchId: inMatch ? this.live!.id : null,
mode: this.queueName ?? snap?.mode ?? null,
map: inMatch ? (snap?.mode === '칼바람 나락' ? '칼바람 나락' : '소환사의 협곡') : null,
mapImage: null,
startedAt: inMatch ? this.live!.startedAt : null,
round: null,
score: null,
gameTimeSec: snap ? Math.round(snap.gameTime) : null,
teamKills: snap?.teamKills ?? null,
self: this.lcu || inMatch ? { name: this.selfRiotId, character: snap?.champ ?? null, characterImage: snap?.champIcon ?? null, kda: snap?.kda ?? null, extra: snap?.extra ?? null } : null,
players: snap?.players ?? null,
error: this.lastErr || null,
updatedAt: Date.now(),
};
}
private async lcuGet<T = any>(path: string): Promise<T | null> {
if (!this.lcu) return null;
try {
@@ -148,7 +193,6 @@ export class LolAdapter implements GameAdapter {
ended: false,
};
this.lastMatchId = id;
this.ocrSeen.clear();
this.host.matchStarted({
id,
game: 'lol',
@@ -161,12 +205,12 @@ export class LolAdapter implements GameAdapter {
// 버퍼해 둔 챔피언 선택 채팅을 이 경기에 붙인다
for (const e of this.pendingChat) this.host.event({ ...e, match_id: id, id: `${id}:${e.id}` });
this.pendingChat = [];
void this.startOcr();
log.info(`롤 경기 시작 감지 ${id}`);
}
const m = this.live;
m.failures = 0;
m.players = d.allPlayers || m.players;
this.snapshot(d, m);
// 게임 시간과 PC 시계로 시작 시각을 계속 다듬는다 (가장 이른 값 = 지연이 가장 적은 값)
m.startedAt = Math.min(m.startedAt, now - gameTime * 1000);
for (const ev of d.events?.Events || []) {
@@ -188,6 +232,26 @@ export class LolAdapter implements GameAdapter {
}
}
/** 지금 게임 상태 표시용: 게임 시간 · 내 챔피언 · KDA · 팀 킬 */
private snapshot(d: any, m: LiveMatch): void {
const all: any[] = d.allPlayers || [];
const me = all.find((p) => p.riotId === m.selfName || p.summonerName === m.selfName);
const sc = me?.scores;
const kills = (team: string | null | undefined) => all.filter((p) => p.team === team).reduce((n, p) => n + (p.scores?.kills ?? 0), 0);
const champ = me ? this.host.assets.champion(me.rawChampionName, me.championName) : null;
this.snap = {
at: Date.now(),
gameTime: Number(d.gameData?.gameTime) || 0,
mode: lolModeKo(d.gameData?.gameMode) ?? d.gameData?.gameMode ?? null,
champ: champ?.name ?? null,
champIcon: champ?.icon ?? null,
kda: sc ? `${sc.kills ?? 0}/${sc.deaths ?? 0}/${sc.assists ?? 0}` : null,
extra: me ? `레벨 ${me.level ?? '?'} · CS ${sc?.creepScore ?? 0}` : null,
teamKills: m.selfTeam ? { ally: kills(m.selfTeam), enemy: all.filter((p) => p.team !== m.selfTeam).reduce((n, p) => n + (p.scores?.kills ?? 0), 0) } : null,
players: all.length,
};
}
private findPlayer(m: LiveMatch, name: string | undefined): any {
if (!name) return null;
return m.players.find((p) => p.riotIdGameName === name || p.riotId === name || p.summonerName === name || p.riotId?.split('#')[0] === name) ?? null;
@@ -307,7 +371,6 @@ export class LolAdapter implements GameAdapter {
if (!m || m.ended) return;
m.ended = true;
const now = Date.now();
void this.host.worker.request('ocr_stop', {}, 5000).catch(() => undefined);
this.host.matchEnded(m.id, now);
this.host.matchUpdated(m.id, {
result: JSON.stringify({ win, score: null }),
@@ -323,19 +386,7 @@ export class LolAdapter implements GameAdapter {
}, 60000).unref();
}
// ------------------------------------------------------------------ 채팅 OCR · 로그
private async startOcr(): Promise<void> {
const s = this.host.settings().games;
if (!s.lolChatOcr || process.platform !== 'win32') return;
try {
await this.host.worker.request('ocr_start', { window_title: 'League of Legends (TM) Client', region: s.lolOcrRegion, fps: 3, lang: 'ko' }, 15000);
log.info('롤 채팅 OCR 시작');
} catch (e: any) {
this.lastErr = `채팅 OCR: ${e.message}`;
log.warn('채팅 OCR 시작 실패', e);
}
}
// ------------------------------------------------------------------ 게임 중 채팅 (로그 파일)
private chatRow(m: LiveMatch, key: string, gameTimeS: number | null, ts: number, p: any, source: ChatData['source']): EventRow {
const sender = this.findPlayer(m, p.sender);
const ts2 = gameTimeS !== null ? m.startedAt + gameTimeS * 1000 : ts;
@@ -363,18 +414,7 @@ export class LolAdapter implements GameAdapter {
};
}
private onOcrLine(ev: any): void {
const m = this.live;
if (!m || m.ended || !ev.parsed?.message) return;
const p = ev.parsed;
const key = `${p.game_time ?? ''}|${p.sender ?? ''}|${p.message}`;
if (this.ocrSeen.has(key)) return;
this.ocrSeen.add(key);
const gts = typeof p.game_time_s === 'number' ? p.game_time_s : null;
this.host.event(this.chatRow(m, hash(key), gts, ev.ts || Date.now(), p, 'ocr'));
}
/** 로그 파일에 채팅이 남아 있으면 OCR 보다 정확하므로 그걸로 바꾼다 */
/** 경기가 끝나면 로그 파일에 남은 게임 중 채팅을 붙인다 (LCU 로 받은 챔피언 선택 · 게임 후 채팅은 그대로 둔다) */
private async readLogChat(m: LiveMatch): Promise<void> {
const dir = this.host.settings().games.lolLogsDir || (this.lcu?.installDir ? `${this.lcu.installDir}\\Logs\\GameLogs` : null);
if (!dir) return;
@@ -385,8 +425,8 @@ export class LolAdapter implements GameAdapter {
const rows = lines.map((p: any, i: number) =>
this.chatRow(m, `${i}-${hash(`${p.game_time_s}|${p.sender}|${p.message}`)}`, typeof p.game_time_s === 'number' ? p.game_time_s : null, m.startedAt, p, 'log'),
);
this.host.replaceEvents(m.id, ['chat'], rows);
log.info(`로그 파일 채팅 ${rows.length}줄로 교체`);
for (const row of rows) this.host.event(row);
log.info(`로그 파일 채팅 ${rows.length}줄`);
} catch (e) {
log.debug('로그 파일 채팅 없음', e);
}
@@ -402,10 +442,22 @@ export class LolAdapter implements GameAdapter {
log.info('롤 클라이언트(LCU) 연결');
const me = await this.lcuGet<any>('/lol-summoner/v1/current-summoner');
if (me?.puuid) this.host.selfAccount(me.puuid, `${me.gameName}#${me.tagLine}`);
if (me?.gameName) this.selfRiotId = `${me.gameName}#${me.tagLine ?? ''}`;
}
}
if (!this.lcu) return;
if (!this.lcu) {
this.phase = null;
this.queueName = null;
return;
}
const phase = await this.lcuGet<string>('/lol-gameflow/v1/gameflow-phase');
if (phase !== this.phase) {
this.phase = phase;
// 큐 이름 (솔로 랭크 · 칼바람 나락 …): 단계가 바뀔 때만 다시 받는다
const sess = phase && phase !== 'None' ? await this.lcuGet<any>('/lol-gameflow/v1/session') : null;
const q = sess?.gameData?.queue;
this.queueName = q ? (lolModeKo(q.id) ?? q.description ?? null) : null;
}
if (phase === 'ChampSelect' || phase === 'InProgress' || phase === 'PreEndOfGame' || phase === 'EndOfGame') await this.pollLcuChat(phase);
}
@@ -530,6 +582,20 @@ export function processLolHistory(game: any, timeline: any, host: Pick<AdapterHo
const it = host.assets.item(x);
return { id: x, name: it.name, icon: it.icon };
}),
stats: {
role: lolPosition(p) ?? undefined,
damage: st.totalDamageDealtToChampions,
damageTaken: st.totalDamageTaken,
vision: st.visionScore,
wardsPlaced: st.wardsPlaced,
wardsKilled: st.wardsKilled,
controlWards: st.visionWardsBoughtInGame,
objectiveDamage: st.damageDealtToObjectives,
turretDamage: st.damageDealtToTurrets,
ccSeconds: st.timeCCingOthers,
at10: frameAt(timeline, p.participantId, 10),
at15: frameAt(timeline, p.participantId, 15),
},
};
});
const events: EventRow[] = [];
@@ -602,6 +668,25 @@ export function processLolHistory(game: any, timeline: any, host: Pick<AdapterHo
};
}
/** LCU 경기 기록의 라인 · 역할 → 포지션 (사용자 지정 게임은 틀릴 수 있어 "추정") */
export function lolPosition(p: any): string | null {
const lane = String(p.timeline?.lane || '').toUpperCase();
const role = String(p.timeline?.role || '').toUpperCase();
if (p.spell1Id === 11 || p.spell2Id === 11 || lane === 'JUNGLE') return '정글';
if (lane === 'TOP') return '탑';
if (lane === 'MIDDLE' || lane === 'MID') return '미드';
if (lane === 'BOTTOM' || lane === 'BOT') return role === 'DUO_SUPPORT' || role === 'SUPPORT' ? '서폿' : role === 'DUO_CARRY' || role === 'CARRY' ? '원딜' : '바텀';
return null;
}
/** 타임라인의 N분 프레임에서 그 선수 CS · 골드 · 경험치 */
function frameAt(timeline: any, pid: number, minute: number): { cs: number; gold: number; xp: number } | undefined {
const f = (timeline?.frames || []).find((x: any) => Math.round((x.timestamp ?? 0) / 60000) === minute);
const pf = f?.participantFrames?.[String(pid)] ?? f?.participantFrames?.[pid];
if (!pf) return undefined;
return { cs: (pf.minionsKilled ?? 0) + (pf.jungleMinionsKilled ?? 0), gold: pf.totalGold ?? 0, xp: pf.xp ?? 0 };
}
function prettyUnit(name: string): string {
if (/^Turret_/.test(name)) return '포탑';
if (/Minion/.test(name)) return '미니언';

View File

@@ -1,4 +1,4 @@
import type { MatchSummary } from '@gvr/shared';
import type { LiveGame, MatchSummary } from '@gvr/shared';
import type { EventRow, MatchRow, Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { SttPipeline } from '../stt/pipeline.js';
@@ -11,12 +11,20 @@ import type { GameAssets } from './assets.js';
import { LolAdapter } from './lol.js';
import type { AdapterHost, GameAdapter, MatchStart } from './types.js';
import { ValorantAdapter } from './valorant.js';
import { lolModeKo, valModeKo } from './modes.js';
const log = logger('games');
/** 게임 어댑터들을 묶고, 경기 시작·종료를 녹음/STT/타임라인에 반영한다 */
export class GameManager implements AdapterHost {
adapters: GameAdapter[];
/** 경기 정보가 바뀌어 녹음 파일 이름을 다시 맞출 때 (경기 끝 · 경기 상세 적용) */
onMatchFiles: ((matchId: string) => void) | null = null;
/** 진행 중인 발로란트 경기의 지금 라운드 (경기 중 녹음 파일 이름용) */
liveRound(matchId: string): number | null {
return this.live().find((g) => g.matchId === matchId && g.inMatch)?.round ?? null;
}
constructor(
readonly store: Store,
@@ -38,12 +46,15 @@ export class GameManager implements AdapterHost {
start(): void {
void this.assets.refresh();
for (const a of this.adapters) a.start();
this.watchLive();
// 앱이 꺼졌다 켜졌을 때 'live' 로 남은 경기는 끝난 것으로 정리
for (const m of this.store.listMatches({ limit: 20 }))
if (m.status === 'live') this.store.upsertMatch({ id: m.id, game: m.game, started_at: m.started_at, status: 'complete', ended_at: m.ended_at ?? Date.now() });
}
stop(): void {
for (const a of this.adapters) a.stop();
if (this.liveTimer) clearInterval(this.liveTimer);
this.liveTimer = null;
}
status() {
const out: Record<string, { connected: boolean; inMatch: boolean; detail?: string }> = {};
@@ -51,6 +62,25 @@ export class GameManager implements AdapterHost {
return out as { valorant: { connected: boolean; inMatch: boolean }; lol: { connected: boolean; inMatch: boolean } };
}
/** 지금 게임 상태 (앱 게임 연동 탭 · 사이트) */
live(): LiveGame[] {
return this.adapters.map((a) => a.liveGame());
}
private liveTimer: NodeJS.Timeout | null = null;
private lastLive = '';
/** 게임 상태가 바뀌면 사이트로 알린다 (2초마다 확인) */
private watchLive(): void {
if (this.liveTimer) return;
this.liveTimer = setInterval(() => {
const live = this.live();
const key = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest));
if (key === this.lastLive) return;
this.lastLive = key;
this.bus.live({ type: 'games.state', data: live });
}, 2000);
}
/** 지금 진행 중인 경기 (녹음 시 발화에 붙인다) */
liveMatchAt(ts: number): string | null {
const m = this.store.matchAt(ts);
@@ -84,6 +114,7 @@ export class GameManager implements AdapterHost {
const n = this.store.assignMatch(id, m.started_at + m.clock_offset - 2000, (m.ended_at ?? Date.now()) + 1000);
log.info(`경기 ${id}: 발화 ${n}개 연결`);
this.bus.live({ type: 'users.updated', data: [] });
this.onMatchFiles?.(id);
}
this.emitMatch(id);
}
@@ -94,7 +125,7 @@ export class GameManager implements AdapterHost {
this.store.upsertMatch({ id, game: cur.game, started_at: cur.started_at, ended_at: endedAt, status: 'pending_detail' });
this.store.assignMatch(id, cur.started_at, endedAt);
this.timeline.invalidate(id);
void this.stt.onMatchEnd(cur.started_at, endedAt);
void this.stt.onMatchEnd(cur.started_at, endedAt).finally(() => this.onMatchFiles?.(id));
this.emitMatch(id);
}
@@ -110,6 +141,8 @@ export class GameManager implements AdapterHost {
selfAccount(puuid: string, riotId: string): void {
const owner = this.ownerUserId();
this.store.setMeta('riot_self_puuid', puuid);
// 경기 상세에 이름이 빠져 오면("#") 연결하지 않는다 (v1.3.5: "주인 계정 자동 연결: #")
if (!/^[^#]+#[^#]+$/.test(riotId)) return;
if (!owner || !this.store.getUser(owner)) return;
const have = this.store.listAccounts().some((a) => a.user_id === owner && a.puuid === puuid);
if (have) return;
@@ -159,21 +192,6 @@ export class GameManager implements AdapterHost {
}
function modeKo(m: MatchRow): string {
const q = (m.queue || m.mode || '').toLowerCase();
if (m.game === 'valorant') {
const map: Record<string, string> = {
competitive: '경쟁전',
unrated: '일반전',
swiftplay: '신속플레이',
spikerush: '스파이크 돌격',
deathmatch: '데스매치',
hurm: '팀 데스매치',
premier: '프리미어',
custom: '사용자 지정',
ggteam: '에스컬레이션',
};
return map[q] || m.mode || '발로란트';
}
const lq: Record<string, string> = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', classic: '소환사의 협곡', aram: '칼바람 나락' };
return lq[q] || m.mode || '리그 오브 레전드';
const q = m.queue || m.mode || '';
return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드');
}

View File

@@ -0,0 +1,34 @@
// 게임 모드 이름 (경기 목록 · 지금 게임 상태에서 함께 쓴다)
/** 발로란트 큐 ID → 모드 이름 (모르는 큐면 null) */
export function valModeKo(queue: string | null | undefined): string | null {
const q = (queue || '').toLowerCase();
{
const map: Record<string, string> = {
competitive: '경쟁전',
unrated: '일반전',
swiftplay: '신속플레이',
spikerush: '스파이크 돌격',
deathmatch: '데스매치',
hurm: '팀 데스매치',
premier: '프리미어',
custom: '사용자 지정',
ggteam: '에스컬레이션',
newmap: '새 맵',
snowball: '눈싸움',
};
return map[q] || null;
}
}
/** 롤 큐 ID · 게임 모드 → 이름 (모르면 null) */
export function lolModeKo(queue: string | number | null | undefined): string | null {
const q = String(queue ?? '').toLowerCase();
const lq: Record<string, string> = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', '900': '우르프', '1900': '우르프', classic: '소환사의 협곡', aram: '칼바람 나락', cherry: '아레나', urf: '우르프', practicetool: '연습 모드', tutorial: '튜토리얼' };
return lq[q] || null;
}
/** 발로란트에서 라운드가 없는 모드 (점수 = 킬). 이 모드는 라운드 구분선 · 라운드 번호를 쓰지 않는다 */
export function valNoRounds(queue: string | null | undefined): boolean {
return ['deathmatch', 'hurm', 'ggteam', 'snowball'].includes((queue || '').toLowerCase());
}

View File

@@ -5,7 +5,7 @@ import https from 'node:https';
import os from 'node:os';
import path from 'node:path';
/** Riot 로컬 API 는 자체 서명 인증서라 검증을 끈 에이전트로만 부른다 (127.0.0.1 전용) */
/** Riot 로컬 API 는 자체 서명 인증서라 검증을 끈 에이전트로만 부른다. 이 PC 안(127.0.0.1 · localhost) 주소에만 쓴다 */
const localAgent = new https.Agent({ rejectUnauthorized: false, keepAlive: true });
export interface HttpResult<T = any> {
@@ -19,6 +19,8 @@ export function request<T = any>(
): Promise<HttpResult<T>> {
return new Promise((resolve, reject) => {
const u = new URL(url);
// 인증서 검증을 끄는 건 이 PC 안 주소뿐이다. 바깥 주소(Riot 원격 API 등)는 항상 검증한다 (local 을 잘못 넘겨도)
if (opts.local && !isLocal(u)) return reject(new Error(`로컬 API 가 아닌 주소입니다: ${u.host}`));
const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
const lib: any = u.protocol === 'http:' ? http : https;
const req = lib.request(
@@ -26,7 +28,7 @@ export function request<T = any>(
{
method: opts.method || 'GET',
headers: { accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}), ...opts.headers },
agent: u.protocol === 'https:' && (opts.local ?? isLocal(u)) ? localAgent : undefined,
agent: u.protocol === 'https:' && isLocal(u) ? localAgent : undefined,
timeout: opts.timeoutMs ?? 5000,
},
(res: any) => {
@@ -52,7 +54,7 @@ export function request<T = any>(
}
function isLocal(u: URL): boolean {
return u.hostname === '127.0.0.1' || u.hostname === 'localhost';
return u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]';
}
export interface Lockfile {

View File

@@ -1,3 +1,4 @@
import type { LiveGame } from '@gvr/shared';
import type { EventRow, MatchRow, Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { WorkerClient } from '../stt/worker.js';
@@ -38,4 +39,6 @@ export interface GameAdapter {
start(): void;
stop(): void;
status(): { connected: boolean; inMatch: boolean; detail?: string };
/** 지금 게임 상태 (자세히) */
liveGame(): LiveGame;
}

View File

@@ -1,4 +1,5 @@
import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound } from '@gvr/shared';
import type { KillData, ChatData, LiveGame, RoundEndData, PlayerRef, MatchPlayer, MatchRound, PlayerStats } from '@gvr/shared';
import { valModeKo, valNoRounds } from './modes.js';
import type { EventRow, RoundRow } from '../db/db.js';
import { logger } from '../util/log.js';
import type { GameAssets } from './assets.js';
@@ -21,6 +22,8 @@ interface Presence {
ally: number | null;
enemy: number | null;
provisioning: string | null;
/** 파티 상태: DEFAULT · MATCHMAKING · MATCHMADE_GAME_STARTING … */
partyState: string | null;
}
export function decodePresence(b64: string): Presence | null {
@@ -35,6 +38,7 @@ export function decodePresence(b64: string): Presence | null {
ally: num(pp.partyOwnerMatchScoreAllyTeam ?? p.partyOwnerMatchScoreAllyTeam),
enemy: num(pp.partyOwnerMatchScoreEnemyTeam ?? p.partyOwnerMatchScoreEnemyTeam),
provisioning: mp.provisioningFlow || p.provisioningFlow || null,
partyState: pp.partyState || p.partyState || null,
};
} catch {
return null;
@@ -65,7 +69,9 @@ export class ValorantAdapter implements GameAdapter {
private auth: Auth | null = null;
private authAt = 0;
private presence: Presence | null = null;
private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number } | null = null;
private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number; queue: string | null; selfAgent: string | null; players: number } | null = null;
/** 내 Riot ID (로컬 채팅 세션) */
private selfName: string | null = null;
private seenChat = new Set<string>();
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
private polling = false;
@@ -86,6 +92,54 @@ export class ValorantAdapter implements GameAdapter {
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
}
liveGame(): LiveGame {
const p = this.presence;
const m = this.match;
const enabled = this.host.settings().games.valorant;
const queue = m?.queue ?? p?.queue ?? null;
const custom = p?.provisioning === 'CustomGame';
const mapUrl = p?.map || null;
const map = this.host.assets.valMap(mapUrl);
const phase = !enabled
? '연동 꺼짐'
: !this.auth
? 'Riot 클라이언트 꺼짐'
: !p
? '발로란트 꺼짐'
: p.state === 'INGAME'
? '경기 중'
: p.state === 'PREGAME'
? '요원 선택'
: p.partyState === 'MATCHMAKING'
? '대기열'
: p.partyState === 'MATCHMADE_GAME_STARTING'
? '경기 찾음 · 시작 중'
: '메뉴';
const inGame = !!m && p?.state === 'INGAME';
const roundBased = !valNoRounds(queue);
const score = inGame && p?.ally != null && p?.enemy != null ? { ally: p.ally, enemy: p.enemy } : null;
return {
game: 'valorant',
enabled,
connected: !!this.auth,
phase,
inMatch: !!m,
matchId: m?.id ?? null,
mode: custom ? '사용자 지정' : queue ? (valModeKo(queue) ?? queue) : null,
map: map?.name ?? (mapUrl ? mapUrl.split('/').pop() ?? null : null),
mapImage: map?.image ?? null,
startedAt: m?.startedAt ?? null,
round: inGame && roundBased && score ? score.ally + score.enemy + 1 : null,
score,
gameTimeSec: null,
teamKills: null,
self: this.auth ? { name: this.selfName, character: m?.selfAgent ?? null, characterImage: null, kda: null, extra: null } : null,
players: m?.players || null,
error: this.lastErr || null,
updatedAt: Date.now(),
};
}
private async local<T = any>(path: string): Promise<T | null> {
const lock = this.auth?.lock ?? readLockfile(riotClientLockfilePath());
if (!lock) return null;
@@ -123,6 +177,8 @@ export class ValorantAdapter implements GameAdapter {
}
this.auth = { lock, accessToken: ent.data.accessToken, entitlement: ent.data.token, puuid: ent.data.subject, region, shard, clientVersion };
this.authAt = Date.now();
const chat = await request(`${base}/chat/v1/session`, { headers: h, local: true }).catch(() => null);
if (chat?.data?.game_name) this.selfName = `${chat.data.game_name}#${chat.data.game_tag ?? ''}`;
log.info(`Riot 클라이언트 연결 (region=${region}, shard=${shard})`);
return this.auth;
}
@@ -173,7 +229,8 @@ export class ValorantAdapter implements GameAdapter {
if (!p) return;
if (p.state === 'INGAME' && !this.match) await this.beginMatch(a, p);
else if (p.state !== 'INGAME' && this.match && prev?.state === 'INGAME') this.endMatch();
else if (this.match && p.ally !== null && p.enemy !== null) {
else if (this.match && p.ally !== null && p.enemy !== null && !valNoRounds(this.match.queue)) {
// 데스매치 · 팀 데스매치 · 에스컬레이션은 점수가 킬 수라서 라운드로 보지 않는다 (v1.3.5: "R63 승리 · 26:37" 같은 가짜 라운드)
const m = this.match;
const total = p.ally + p.enemy;
if (total > m.ally + m.enemy) {
@@ -220,7 +277,8 @@ export class ValorantAdapter implements GameAdapter {
team: pl.TeamID,
character: this.host.assets.agent(pl.CharacterID),
}));
this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0 };
const selfAgent = players.find((pl: { puuid: string }) => pl.puuid === a.puuid)?.character?.name ?? null;
this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0, queue: p.queue, selfAgent: selfAgent && selfAgent !== '?' ? selfAgent : null, players: players.length };
this.seenChat.clear();
this.host.matchStarted({
id,
@@ -299,6 +357,7 @@ export class ValorantAdapter implements GameAdapter {
const r = await request(`${this.pd(a)}/match-details/v1/matches/${matchId}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
if (r.status === 200 && r.data?.matchInfo) {
this.detailQueue.delete(id);
await this.fillNames(a, r.data);
this.applyDetails(id, r.data, a.puuid, q.startedLocal);
continue;
}
@@ -313,6 +372,30 @@ export class ValorantAdapter implements GameAdapter {
}
}
/**
* 경기 상세에 선수 이름이 비어 오면(Riot 이 이름을 가림) 이름 서비스로 채운다. 내 이름은 로컬 채팅 세션 값으로.
* v1.3.5 는 빈 이름을 그대로 써서 "주인 계정 자동 연결: #" 이 남았다.
*/
private async fillNames(a: Auth, md: any): Promise<void> {
const players: any[] = md.players || [];
const missing = players.filter((p) => !p.gameName).map((p) => p.subject);
if (!missing.length) return;
try {
const r = await request(`${this.pd(a)}/name-service/v2/players`, { method: 'PUT', headers: this.pvpHeaders(a), body: missing, timeoutMs: 8000 });
for (const n of Array.isArray(r.data) ? r.data : []) {
const p = players.find((x) => x.subject === n.Subject);
if (p && n.GameName) {
p.gameName = n.GameName;
p.tagLine = n.TagLine ?? p.tagLine;
}
}
} catch (e) {
log.debug('이름 서비스 조회 실패', e);
}
const me = players.find((p) => p.subject === a.puuid);
if (me && !me.gameName && this.selfName) [me.gameName, me.tagLine] = this.selfName.split('#');
}
applyDetails(id: string, md: any, selfPuuid: string, startedLocal: number): void {
const res = processMatchDetails(md, selfPuuid, this.host.assets, id, startedLocal);
this.host.store.replaceRounds(id, res.rounds);
@@ -359,6 +442,8 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
const rr: any[] = md.roundResults || [];
const n = rr.length;
// 데스매치 · 팀 데스매치 · 에스컬레이션: 경기 전체가 "라운드 1" 하나로 온다. 라운드 · 에이스(한 라운드 5킬)를 만들지 않는다
const noRounds = valNoRounds(info.queueID);
// 라운드 전투 시작 시각(게임 시간) = 킬 gameTime - roundTime
const combat: (number | null)[] = rr.map((r) => {
let best: number | null = null;
@@ -380,6 +465,17 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
}
combat[i] = prev !== null ? prev + avg : next !== null ? next : BUY_MS + i * avg;
}
// 범인찾기용 선수별 누적 지표
const tallies: Record<string, Tally> = {};
const tally = (puuid: string) => (tallies[puuid] ||= { damage: 0, taken: 0, head: 0, shots: 0, firstKills: 0, firstDeaths: 0, plants: 0, defuses: 0, kast: 0 });
// 공격 팀: 전반 12라운드는 Red, 후반은 Blue, 연장은 매 라운드 바뀜. 스파이크를 설치한 팀이 공격이므로 설치 기록이 반대면 뒤집는다
const ruleAttacker = (i: number) => (i < 12 ? 'Red' : i < 24 ? 'Blue' : i % 2 === 0 ? 'Red' : 'Blue');
let agree = 0;
for (let i = 0; i < n; i++) {
const planter = rr[i].bombPlanter ? players[rr[i].bombPlanter]?.teamId : null;
if (planter) agree += planter === ruleAttacker(i) ? 1 : -1;
}
const attackerTeam = (i: number) => (agree >= 0 ? ruleAttacker(i) : ruleAttacker(i) === 'Red' ? 'Blue' : 'Red');
const rounds: RoundRow[] = [];
const roundsDetail: MatchRound[] = [];
const events: EventRow[] = [];
@@ -394,16 +490,29 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
const win = r.winningTeam === selfTeam;
if (win) ally++;
else enemy++;
const economy: Record<string, { spent: number; remaining: number; weapon?: string }> = {};
const economy: Record<string, { spent: number; remaining: number; weapon?: string; loadout?: number }> = {};
const roundPlayers: Record<string, { kills: number; damage: number }> = {};
for (const ps of r.playerStats || []) {
if (ps.economy)
economy[ps.subject] = {
spent: ps.economy.spent ?? 0,
remaining: ps.economy.remaining ?? 0,
weapon: ps.economy.weapon ? assets.damageItem(null, 'Weapon', ps.economy.weapon)?.name : undefined,
loadout: typeof ps.economy.loadoutValue === 'number' ? ps.economy.loadoutValue : undefined,
};
const dmg = (ps.damage || []).reduce((n: number, d: any) => n + (d.damage ?? 0), 0);
roundPlayers[ps.subject] = { kills: (ps.kills || []).length, damage: dmg };
const t = tally(ps.subject);
t.damage += dmg;
for (const d of ps.damage || []) {
if (d.receiver) tally(d.receiver).taken += d.damage ?? 0;
t.head += d.headshots ?? 0;
t.shots += (d.headshots ?? 0) + (d.bodyshots ?? 0) + (d.legshots ?? 0);
}
}
rounds.push({
if (r.bombPlanter) tally(r.bombPlanter).plants++;
if (r.bombDefuser) tally(r.bombDefuser).defuses++;
if (!noRounds) rounds.push({
match_id: id,
num,
started_at: S + start,
@@ -415,10 +524,25 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
enemy_score: enemy,
economy: JSON.stringify(economy),
});
roundsDetail.push({ num, startedAt: S + start + clockOffset, endedAt: S + end + clockOffset, win, result: roundResultKo(r.roundResult), score: { ally, enemy }, economy });
if (!noRounds) roundsDetail.push({
num,
startedAt: S + start + clockOffset,
endedAt: S + end + clockOffset,
win,
result: roundResultKo(r.roundResult),
score: { ally, enemy },
economy,
allyAttack: attackerTeam(i) === selfTeam,
players: roundPlayers,
});
// 킬
const killsBy: Record<string, number> = {};
const kills = (r.playerStats || []).flatMap((ps: any) => ps.kills || []).sort((x: any, y: any) => x.gameTime - y.gameTime);
if (kills[0]) {
if (kills[0].killer) tally(kills[0].killer).firstKills++;
if (kills[0].victim) tally(kills[0].victim).firstDeaths++;
}
for (const puuid of kastRound(r, kills, players)) tally(puuid).kast++;
for (const k of kills) {
const killer = ref(k.killer);
const victim = ref(k.victim)!;
@@ -446,7 +570,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
});
}
for (const [puuid, cnt] of Object.entries(killsBy)) {
if (cnt >= 4) {
if (cnt >= 4 && !noRounds) {
const last = kills.filter((k: any) => k.killer === puuid).pop();
events.push({
id: `${id}:${cnt >= 5 ? 'ace' : 'multikill'}:${num}:${puuid}`,
@@ -491,7 +615,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
});
}
const rd: RoundEndData = { round: num, win, result: roundResultKo(r.roundResult), score: { ally, enemy } };
events.push({
if (!noRounds) events.push({
id: `${id}:round_end:${num}`,
match_id: id,
game: 'valorant',
@@ -516,6 +640,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
assists: p.stats?.assists ?? 0,
score: p.stats?.score ?? 0, // 총 전투 점수 (사이트가 라운드 수로 나눠 ACS 표시)
rank: assets.val?.tiers[p.competitiveTier] ?? null,
stats: playerStats(p, tallies[p.subject], assets),
}));
const selfTeamInfo = (md.teams || []).find((t: any) => t.teamId === selfTeam);
const enemyTeamInfo = (md.teams || []).find((t: any) => t.teamId !== selfTeam);
@@ -530,11 +655,55 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
mode: assets.val?.modes[info.gameMode] ?? info.queueID ?? null,
result: {
win: selfTeamInfo ? !!selfTeamInfo.won : null,
score: { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy },
score: noRounds ? null : { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy },
},
};
}
type Tally = { damage: number; taken: number; head: number; shots: number; firstKills: number; firstDeaths: number; plants: number; defuses: number; kast: number };
/** 트레이드로 치는 시간: 죽은 뒤 이 안에 팀원이 그 킬러를 잡으면 (vlr · tracker.gg 와 같은 5초) */
const TRADE_MS = 5000;
/** 이 라운드에서 KAST(킬 · 어시 · 생존 · 트레이드 중 하나)를 한 선수 */
export function kastRound(r: any, kills: any[], players: Record<string, any>): string[] {
const out: string[] = [];
for (const ps of r.playerStats || []) {
const me = ps.subject;
if (kills.some((k) => k.killer === me || (k.assistants || []).includes(me))) {
out.push(me);
continue;
}
const death = kills.find((k) => k.victim === me);
if (!death) {
out.push(me);
continue;
}
const traded = kills.some(
(k) => k.victim === death.killer && k.gameTime >= death.gameTime && k.gameTime - death.gameTime <= TRADE_MS && players[k.killer]?.teamId === players[me]?.teamId,
);
if (traded) out.push(me);
}
return out;
}
function playerStats(p: any, t: Tally | undefined, assets: GameAssets): PlayerStats {
const ac = p.stats?.abilityCasts;
return {
role: assets.agentRole(p.characterId) ?? undefined,
rounds: p.stats?.roundsPlayed ?? undefined,
damage: t?.damage ?? 0,
damageTaken: t?.taken ?? 0,
kastRounds: t?.kast ?? 0,
headshotPct: t && t.shots ? Math.round((t.head / t.shots) * 100) : undefined,
firstKills: t?.firstKills ?? 0,
firstDeaths: t?.firstDeaths ?? 0,
plants: t?.plants ?? 0,
defuses: t?.defuses ?? 0,
abilityCasts: ac ? (ac.grenadeCasts ?? 0) + (ac.ability1Casts ?? 0) + (ac.ability2Casts ?? 0) + (ac.ultimateCasts ?? 0) : undefined,
};
}
export function roundResultKo(r: string | undefined): string {
switch (r) {
case 'Eliminated':

View File

@@ -1,10 +1,14 @@
import fs from 'node:fs';
import path from 'node:path';
import type { FastifyInstance } from 'fastify';
import { buildApi } from './api/server.js';
import { buildApi, toUser } from './api/server.js';
import { Bundles } from './bundles.js';
import { AudioNamer } from './audio-names.js';
import { Culprit } from './culprit.js';
import { Store } from './db/db.js';
import { Dictionary } from './dict/dictionary.js';
import { Bot } from './discord/bot.js';
import { LocalGateway, RemoteGateway } from './discord/gateway.js';
import { Recorder } from './discord/recorder.js';
import { Announcer } from './discord/tts.js';
import { GameAssets } from './games/assets.js';
@@ -17,6 +21,7 @@ import { WorkerClient, type WorkerCommand } from './stt/worker.js';
import { Timeline } from './timeline.js';
import { Bus } from './util/events.js';
import { initLogFile, logger } from './util/log.js';
import { hardenTlsEnv } from './util/secure-http.js';
const log = logger('core');
@@ -26,16 +31,21 @@ export interface CoreOptions {
worker: WorkerCommand;
version: string;
codec?: SecretCodec;
/** 이미 연 설정 저장소 (Electron 은 로그인 확인 때문에 코어보다 먼저 연다) */
settings?: SettingsStore;
/** 로컬 API 를 127.0.0.1 포트로도 연다 (설정 창·디버그용). 0 이면 열지 않음 */
apiPort?: number;
/** 겜녹이 봇 중계에서 로그인 만료 · 등록 해제를 알려 왔을 때 (Electron: 바로 다시 확인해서 잠근다) */
onBotUnauthorized?: () => void;
}
export type Core = Awaited<ReturnType<typeof startCore>>;
/** 코어 조립 (Electron 메인 프로세스와 헤드리스 CLI 가 같이 쓴다) */
export async function startCore(opts: CoreOptions) {
hardenTlsEnv(); // 헤드리스 CLI 도 (Electron 은 main.ts 에서 먼저)
fs.mkdirSync(opts.dataDir, { recursive: true });
const settings = new SettingsStore(opts.dataDir, opts.codec);
const settings = opts.settings ?? new SettingsStore(opts.dataDir, opts.codec);
const S = () => settings.get();
const paths = () => resolvePaths(opts.dataDir, S());
initLogFile(paths().logs);
@@ -44,6 +54,10 @@ export async function startCore(opts: CoreOptions) {
const store = new Store(paths().db);
const bus = new Bus();
bus.setMaxListeners(50);
bus.usersProvider = () => {
const acc = store.listAccounts();
return store.listUsers().map((u) => toUser(u, acc));
};
const timeline = new Timeline(store);
const dict = new Dictionary(store, opts.resourcesDir, () => S().dictionary.packs);
dict.seed();
@@ -55,6 +69,7 @@ export async function startCore(opts: CoreOptions) {
const stt = new SttPipeline(worker, store, dict, timeline, bus, S);
const assets = new GameAssets(path.join(opts.dataDir, 'cache'));
const games = new GameManager(store, assets, worker, stt, timeline, bus, S, () => S().discord.followUserId);
const audioNames = new AudioNamer(store, games, (id) => stt.isBusy(id));
const recorder: Recorder = new Recorder(store, stt, timeline, bus, {
audioDir: () => paths().audio,
silenceMs: () => S().audio.silenceMs,
@@ -63,24 +78,30 @@ export async function startCore(opts: CoreOptions) {
const u = store.getUser(uid);
if (u?.excluded) return true;
// 다른 봇(음악봇 등)은 녹음하지 않는다. 자동 테스트에서만 GVR_RECORD_BOTS=1 로 연다.
return process.env.GVR_RECORD_BOTS !== '1' && !!bot.client?.users.cache.get(uid)?.bot;
return process.env.GVR_RECORD_BOTS !== '1' && bot.isBot(uid);
},
matchAt: (ts) => games.liveMatchAt(ts),
onSaved: (id) => audioNames.refresh(id),
});
const announcer = new Announcer(paths().tts, opts.resourcesDir, async (src, dst, tempo) => {
await worker.request('tempo', { src, dst, tempo }, 120000);
});
const announcer = new Announcer(paths().tts, opts.resourcesDir);
const bot: Bot = new Bot(store, recorder, announcer, bus, S, (gid) => {
if (!S().discord.guildId) settings.update({ discord: { guildId: gid } });
});
const culprit = new Culprit(store, timeline, games);
const api: FastifyInstance = await buildApi({
store,
timeline,
games,
dict,
culprit,
bus,
settings: S,
trainingDir: () => paths().training,
version: opts.version,
bundles: new Bundles(store, games, () => paths().audio, opts.version, (ids) => ids.forEach((id) => audioNames.refresh(id))),
overviewExtra: () => ({
guild: bot.state.guild,
recording: {
@@ -105,27 +126,59 @@ 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();
if (opts.apiPort) await api.listen({ host: '127.0.0.1', port: opts.apiPort });
// 겜녹이 봇: 봇 토큰은 사이트 서버에만 있다. 앱 로그인 토큰으로 서버 중계에 붙는다.
// 다른 봇: 사용자가 넣은 토큰으로 이 PC 가 직접 연결 (개발용 GVR_BOT_TOKEN 도 여기)
const startBot = async () => {
const token = settings.getSecret('botToken');
if (!token) {
const token = settings.activeBotToken();
let gw;
if (token) gw = new LocalGateway(token);
else if (S().discord.botMode === 'builtin') {
if (!settings.getSecret('appToken')) {
log.warn('로그인하지 않아 겜녹이 봇에 연결하지 않습니다');
return;
}
gw = new RemoteGateway({ serverUrl: () => S().site.serverUrl, appToken: () => settings.getSecret('appToken') ?? null, version: opts.version });
gw.on('unauthorized', () => opts.onBotUnauthorized?.());
} else {
log.warn('봇 토큰이 없습니다. 설정에서 입력해 주세요.');
return;
}
try {
await bot.start(token);
await bot.start(gw);
} catch (e: any) {
log.error(`봇 로그인 실패: ${e.message}`);
log.error(`봇 연결 실패: ${e.message}`);
}
};
await startBot();
// 녹음할 서버를 바꾸면 봇을 다시 붙여 새 서버를 지켜본다 (이전 서버의 녹음은 끝난다)
let watchedGuild = S().discord.guildId;
const offGuild = settings.onChange((s) => {
const g = s.discord.guildId;
if (g === watchedGuild) return;
watchedGuild = g;
if (bot.state.status !== 'ready' || !g || bot.state.guild?.id === g) return;
log.info('녹음할 서버가 바뀌어 봇을 다시 연결합니다');
void bot.stop().then(startBot);
});
const stop = async () => {
log.info('종료 중');
offGuild();
relay.stop();
retention.stop();
games.stop();
@@ -135,5 +188,5 @@ export async function startCore(opts: CoreOptions) {
store.close();
};
return { settings, store, bus, timeline, dict, worker, stt, assets, games, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir };
return { settings, store, bus, timeline, dict, worker, stt, assets, games, audioNames, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir };
}

View File

@@ -3,6 +3,11 @@ import WebSocket from 'ws';
import type { LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
import type { Bus } from '../util/events.js';
import { logger } from '../util/log.js';
import { secureFetch, TLS_TRUST } from '../util/secure-http.js';
import { secureServerUrl, wsUrl } from '../util/secure-url.js';
/** 바이너리 한 조각 (서버 · 앱 모두 메시지 크기 제한보다 작게) */
const RELAY_CHUNK = 1024 * 1024;
const log = logger('relay');
@@ -60,9 +65,16 @@ export class RelayClient {
this.status = { state: 'off', error: '사이트 서버에 등록되지 않았습니다', since: null, serverUrl: c.serverUrl };
return;
}
const url = c.serverUrl.replace(/^http/, 'ws').replace(/\/$/, '') + '/device/ws';
let url: string;
try {
url = wsUrl(c.serverUrl, '/device/ws');
} catch (e: any) {
// 암호화되지 않은 주소로는 기기 키 · 기록을 보내지 않는다
this.status = { state: 'error', error: e.message, since: null, serverUrl: c.serverUrl };
return;
}
this.status = { ...this.status, state: 'connecting', serverUrl: c.serverUrl };
const ws = new WebSocket(url, { headers: { authorization: `Device ${c.deviceId}.${c.deviceKey}` }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024 });
const ws = new WebSocket(url, { headers: { authorization: `Device ${c.deviceId}.${c.deviceKey}` }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024, ...TLS_TRUST });
this.ws = ws;
ws.on('open', () => {
this.retries = 0;
@@ -80,7 +92,9 @@ export class RelayClient {
}, 5000);
});
ws.on('message', (data, isBinary) => {
if (isBinary) return;
// 큰 zip 을 받는 동안에는 pong 이 조각 뒤에 밀린다. 무엇이든 받으면 살아 있는 것으로 본다
this.lastPong = Date.now();
if (isBinary) return this.onBinary(data as Buffer);
let msg: RelayToDevice;
try {
msg = JSON.parse(String(data));
@@ -115,28 +129,51 @@ export class RelayClient {
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(m));
}
/** 사이트 서버가 보낸 요청 본문 조각 (zip 받아오기): [id 길이 4바이트][id][조각] */
private bodyChunks = new Map<string, { chunks: Buffer[]; at: number }>();
private onBinary(buf: Buffer): void {
if (buf.length < 4) return;
const n = buf.readUInt32BE(0);
const id = buf.subarray(4, 4 + n).toString('utf8');
const cur = this.bodyChunks.get(id) ?? { chunks: [], at: Date.now() };
cur.chunks.push(Buffer.from(buf.subarray(4 + n)));
this.bodyChunks.set(id, cur);
// 끝내 요청이 오지 않은 조각은 10분 뒤 버린다
for (const [k, v] of this.bodyChunks) if (Date.now() - v.at > 10 * 60000) this.bodyChunks.delete(k);
}
private async handle(req: Extract<RelayToDevice, { t: 'req' }>): Promise<void> {
const bin = req.bin ? Buffer.concat(this.bodyChunks.get(req.id)?.chunks ?? []) : null;
this.bodyChunks.delete(req.id);
if (!req.path.startsWith('/api/')) {
this.send({ t: 'res', id: req.id, status: 403, headers: { 'content-type': 'application/json' }, body: '{"error":"forbidden"}' });
return;
}
try {
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = req.headers[k];
for (const k of ['range', 'content-type', 'accept', 'x-gvr-internal', 'x-gvr-role']) if (req.headers[k]) headers[k] = req.headers[k];
if (req.user) headers['x-gvr-user'] = encodeURIComponent(JSON.stringify(req.user));
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: req.body ?? undefined });
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: bin ?? req.body ?? undefined });
const outHeaders: Record<string, string> = {};
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length']) {
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length', 'content-disposition']) {
const v = res.headers[k];
if (v !== undefined) outHeaders[k] = String(v);
}
const ct = outHeaders['content-type'] || '';
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream')) {
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream') || ct.startsWith('application/zip')) {
this.send({ t: 'res_head', id: req.id, status: res.statusCode, headers: outHeaders });
const idBuf = Buffer.from(req.id, 'utf8');
const head = Buffer.alloc(4);
head.writeUInt32BE(idBuf.length, 0);
this.ws?.send(Buffer.concat([head, idBuf, res.rawPayload]), { binary: true });
// 사이트 서버는 한 메시지에 16MB 까지만 받는다. 1MB 씩 나눠 보낸다 (zip 내보내기)
const raw = res.rawPayload;
const ws = this.ws;
for (let i = 0; i < raw.length || i === 0; i += RELAY_CHUNK) {
// 보낼 것이 4MB 넘게 쌓이면 잠깐 기다린다 (ping 이 밀려 연결이 끊기지 않게)
while (ws && ws.readyState === WebSocket.OPEN && ws.bufferedAmount > 4 * RELAY_CHUNK) await new Promise((r) => setTimeout(r, 20));
if (!ws || ws.readyState !== WebSocket.OPEN) break;
ws.send(Buffer.concat([head, idBuf, raw.subarray(i, i + RELAY_CHUNK)]), { binary: true });
}
this.send({ t: 'res_end', id: req.id });
} else {
this.send({ t: 'res', id: req.id, status: res.statusCode, headers: outHeaders, body: res.payload });
@@ -149,12 +186,17 @@ export class RelayClient {
/** 1회용 등록 코드로 이 PC 를 사이트 서버에 등록한다 */
export async function registerDevice(serverUrl: string, code: string, name: string): Promise<{ deviceId: string; deviceKey: string }> {
const r = await fetch(serverUrl.replace(/\/$/, '') + '/device/register', {
const r = await secureFetch(secureServerUrl(serverUrl) + '/device/register', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ code: code.trim(), name }),
});
const data: any = await r.json().catch(() => ({}));
let data: any = {};
try {
data = JSON.parse(await r.text());
} catch {
/* JSON 아님 */
}
if (!r.ok) throw new Error(data.message || (r.status === 400 || r.status === 404 ? '등록 코드가 올바르지 않거나 만료되었습니다' : `서버 오류 ${r.status}`));
return { deviceId: data.deviceId, deviceKey: data.deviceKey };
}

43
app/src/core/roles.ts Normal file
View File

@@ -0,0 +1,43 @@
// 역할별 권한: 일반 유저(user)가 바꿀 수 없는 관리자 전용 설정 · 기능.
// 메인 프로세스(IPC)에서 막고, 설정 창은 같은 목록으로 잠금 표시만 한다.
import type { AppRole } from '@gvr/shared';
export const isAdminRole = (r: AppRole | null | undefined): boolean => r === 'admin' || r === 'superadmin';
export const ROLE_LABEL: Record<AppRole, string> = { superadmin: '최고 관리자', admin: '관리자', user: '유저' };
/**
* 관리자 전용 설정 (settings.json 경로 앞부분)
* - 봇 선택: 다른 봇으로 바꾸기
* - 녹음 안내(TTS): 녹음되는 사람들에게 알리는 장치라 끄거나 문구를 바꾸는 것은 관리자만
* - 음성 보관 기간: 다른 사람 목소리를 얼마나 남길지 정하는 정책
* - 사이트 서버: 주소 · PC 이름 · 등록 (모두가 보는 사이트에 연결되는 PC)
* - 파인튜닝 일정 · 모델 교체
*/
export const ADMIN_ONLY_SETTINGS = ['discord.botMode', 'discord.ttsEnabled', 'discord.ttsOnNewMember', 'discord.ttsText', 'storage.retentionDays', 'site', 'finetune'] as const;
/** 관리자 전용 기능 (IPC 이름) */
export const ADMIN_ONLY_ACTIONS = new Set([
'registerDevice',
'unregisterDevice',
'setExcluded',
'finetuneInstall',
'finetuneStart',
'finetuneStop',
'finetuneRollback',
'clearTrainingData',
]);
/** 설정 변경(patch) 중 관리자 전용 항목의 경로 목록. 비어 있으면 누구나 바꿀 수 있는 변경 */
export function adminOnlyPaths(patch: unknown, prefix = ''): string[] {
if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return [];
const out: string[] = [];
for (const [k, v] of Object.entries(patch)) {
const p = prefix ? `${prefix}.${k}` : k;
if (ADMIN_ONLY_SETTINGS.some((a) => p === a || p.startsWith(`${a}.`))) out.push(p);
else if (ADMIN_ONLY_SETTINGS.some((a) => a.startsWith(`${p}.`))) out.push(...adminOnlyPaths(v, p));
}
return out;
}
export const ADMIN_ONLY_MESSAGE = '관리자만 바꿀 수 있는 설정입니다';

View File

@@ -1,10 +1,13 @@
import fs from 'node:fs';
import path from 'node:path';
import type { AppRole, AppUserInfo } from '@gvr/shared';
export interface Settings {
version: 1;
firstRunDone: boolean;
discord: {
/** builtin = 앱에 들어 있는 겜녹이 봇, custom = 사용자가 넣은 다른 봇 토큰 */
botMode: 'builtin' | 'custom';
guildId: string | null;
/** 따라갈 유저 (보통 게임 PC 주인) */
followUserId: string | null;
@@ -14,12 +17,12 @@ export interface Settings {
ttsText: string;
ttsOnNewMember: boolean;
ttsVoice: string;
/** 녹음 안내 말 속도 0.1~2.0 (1.0 = 보통) */
ttsRate: number;
};
games: {
valorant: boolean;
lol: boolean;
lolChatOcr: boolean;
lolOcrRegion: { x: number; y: number; w: number; h: number };
lolLogsDir: string | null;
};
stt: {
@@ -66,16 +69,25 @@ export interface Secrets {
botToken?: string;
deviceKey?: string;
riotApiKey?: string;
/** 앱 로그인 토큰 (사이트 서버가 발급) */
appToken?: string;
/** v1.2.0 이 받아 두던 겜녹이 봇 토큰. 이제 쓰지 않고 시작할 때 지운다 */
builtinBotToken?: string;
/** 마지막으로 서버에서 확인한 로그인 정보 (서버에 잠깐 못 붙을 때 쓰는 사본) */
auth?: { user: AppUserInfo; role: AppRole; verifiedAt: number };
}
export const DEFAULT_TTS_TEXT =
'겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.';
'겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.';
/** v1.2.2 까지의 기본 문구. 이 문구를 그대로 쓰던 설치는 새 기본 문구(AI 분석 안내 포함)로 바꾼다 */
const OLD_DEFAULT_TTS_TEXTS = ['겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.'];
export function defaultSettings(): Settings {
return {
version: 1,
firstRunDone: false,
discord: {
botMode: 'builtin',
guildId: null,
followUserId: null,
followEnabled: true,
@@ -84,12 +96,11 @@ export function defaultSettings(): Settings {
ttsText: DEFAULT_TTS_TEXT,
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
ttsRate: 1,
},
games: {
valorant: true,
lol: true,
lolChatOcr: true,
lolOcrRegion: { x: 0.0, y: 0.6, w: 0.3, h: 0.27 },
lolLogsDir: null,
},
stt: {
@@ -144,6 +155,8 @@ export class SettingsStore {
private secrets: Secrets;
private listeners = new Set<(s: Settings) => void>();
private envBotToken: string | null;
constructor(
private dataDir: string,
private codec: SecretCodec = plainCodec,
@@ -151,8 +164,10 @@ export class SettingsStore {
this.file = path.join(dataDir, 'settings.json');
this.secretFile = path.join(dataDir, 'secrets.bin');
this.cur = defaultSettings();
let saved: any = null;
try {
this.cur = deepMerge(defaultSettings(), JSON.parse(fs.readFileSync(this.file, 'utf8')));
saved = JSON.parse(fs.readFileSync(this.file, 'utf8'));
this.cur = deepMerge(defaultSettings(), saved);
} catch {
/* 첫 실행 */
}
@@ -162,8 +177,24 @@ export class SettingsStore {
} catch {
/* 없음 */
}
// 개발/헤드리스: 환경변수로 비밀값 주입
if (process.env.GVR_BOT_TOKEN) this.secrets.botToken = process.env.GVR_BOT_TOKEN;
// v1.0.0 에서 직접 토큰을 넣어 쓰던 설치는 그 봇을 계속 쓴다
if (saved && !saved.discord?.botMode && this.secrets.botToken) this.cur.discord.botMode = 'custom';
// 범인찾기(AI 분석) 안내: 기본 문구를 바꾸지 않고 쓰던 설치는 새 기본 문구로 (직접 고친 문구는 그대로)
if (OLD_DEFAULT_TTS_TEXTS.includes(this.cur.discord.ttsText)) this.cur.discord.ttsText = DEFAULT_TTS_TEXT;
// 개발/헤드리스: 환경변수 토큰이 있으면 모드와 상관없이 그것을 쓴다
this.envBotToken = process.env.GVR_BOT_TOKEN || null;
// v1.2.0 은 서버에서 받은 겜녹이 봇 토큰을 저장해 두었다. 이제는 서버가 봇을 대신 연결하므로 남기지 않는다
if (this.secrets.builtinBotToken) this.setSecret('builtinBotToken', null);
}
/** 겜녹이 봇을 쓸 수 있는지 (로그인해 있으면 사이트 서버 중계로 연결한다. 봇 토큰은 이 PC 에 오지 않는다) */
get hasBuiltinBot(): boolean {
return !!this.secrets.appToken;
}
/** 이 PC 가 직접 로그인할 봇 토큰: 다른 봇 모드의 토큰 또는 개발용 GVR_BOT_TOKEN (겜녹이 봇은 null) */
activeBotToken(): string | null {
if (this.envBotToken) return this.envBotToken;
return this.cur.discord.botMode === 'custom' ? this.secrets.botToken || null : null;
}
get(): Settings {

View File

@@ -1,20 +1,31 @@
import fs from 'node:fs';
import type { Store, UtteranceRow } from '../db/db.js';
import { normalizePhrase, type Store, type UtteranceRow } from '../db/db.js';
import type { Dictionary, DictContext } from '../dict/dictionary.js';
import type { Settings } from '../settings.js';
import type { Timeline } from '../timeline.js';
import type { Bus } from '../util/events.js';
import { logger } from '../util/log.js';
import { removeInsertedSilence } from '../discord/ogg.js';
import { WorkerClient, WorkerError, type TranscribeResult } from './worker.js';
const log = logger('stt');
const NOISE_REASON: Record<string, string> = {
vad: '목소리 없음',
no_speech: '말소리 아님',
hallucination: '잡음에서 지어낸 문장',
repetition: '같은 말만 반복',
learned: '잡음으로 배운 문장',
};
type Slot = 'realtime' | 'precise';
interface Job {
id: string;
slot: Slot;
/** 낮을수록 먼저 */
prio: number;
/** 예전 녹음 고친 뒤 다시 변환: 잡음으로 나오면 이전 결과를 지키고, 정밀 결과로만 덮는다 */
repair?: boolean;
}
export interface SttStatus {
@@ -36,6 +47,22 @@ export class SttPipeline {
private queued = new Set<string>();
private busy = false;
private processing: string | null = null;
/** 한 발화의 변환이 끝났을 때 (녹음 파일 이름 맞추기) */
onDone: ((id: string) => void) | null = null;
/** 예전 녹음 고치기가 끝났을 때 */
onRepairDone: (() => void) | null = null;
/** 이 발화를 변환 중이거나 대기열에 있는가 (그동안은 파일 이름을 바꾸지 않는다) */
isBusy(id: string): boolean {
return this.processing === id || this.queued.has(`realtime:${id}`) || this.queued.has(`precise:${id}`);
}
/** 예전 녹음 고치기가 아직 남았는가 (끝나기 전에는 그 녹음들의 이름을 바꾸지 않는다) */
repairPendingBefore(): number | null {
if (this.store.meta('audio_repair_v136')) return null;
const c = this.store.meta('audio_repair_v136_before');
return c ? Number(c) : null;
}
private inMatch = false;
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
private bothFit = true;
@@ -132,16 +159,18 @@ export class SttPipeline {
/** 시작 시 미처리분 복구 */
resumePending(): void {
this.purgeOldNoise();
this.repairOldAudio();
const rows = this.store.pendingUtterances();
if (rows.length) log.info(`미처리 발화 ${rows.length}개 다시 대기열에 넣음`);
for (const r of rows) this.enqueue(r.id, 'realtime', 5);
}
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10): void {
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10, repair = false): void {
const key = `${slot}:${id}`;
if (this.queued.has(key)) return;
this.queued.add(key);
this.queue.push({ id, slot, prio });
this.queue.push({ id, slot, prio, ...(repair ? { repair } : {}) });
this.queue.sort((a, b) => a.prio - b.prio);
this.status.queue = this.queue.length;
this.pump();
@@ -190,6 +219,11 @@ export class SttPipeline {
this.busy = false;
this.processing = null;
this.status.processing = null;
try {
if (!this.isBusy(job.id)) this.onDone?.(job.id);
} catch (e) {
log.warn('변환 뒤 처리 실패', e);
}
setImmediate(() => this.pump());
});
}
@@ -224,7 +258,7 @@ export class SttPipeline {
this.store.markUtteranceFailed(u.id);
return;
}
if (job.slot === 'precise' && (u.corrected || u.status === 'precise')) return;
if (job.slot === 'precise' && (u.corrected || (u.status === 'precise' && !job.repair))) return;
const s = this.settings();
const ctx = this.dictContext(u);
const user = this.store.getUser(u.user_id);
@@ -258,6 +292,16 @@ export class SttPipeline {
} else this.enqueue(u.id, job.slot, job.prio + 2);
return;
}
// 변환하는 동안 사이트에서 지운 발화: 결과를 버린다
if (!this.store.getUtterance(u.id)) return;
// 사이트에서 "잡음이라 삭제"한 문장과 같으면 잡음으로 (v1.4.0)
if (!r.noise && this.store.hitNoisePhrase(normalizePhrase(r.raw_text ?? r.text))) {
r = { ...r, noise: true, noise_reason: 'learned', text: null, words: [] };
}
if (job.repair && r.noise) {
log.info(`예전 녹음 다시 변환: ${u.id} 는 잡음으로 나와 이전 결과를 그대로 둠`);
return;
}
this.store.updateUtteranceResult(u.id, {
text: r.text,
raw_text: r.raw_text,
@@ -270,11 +314,91 @@ export class SttPipeline {
model: r.model,
status: slot,
});
if (r.noise) this.onNoise(u, r, slot);
if (!r.noise && r.lufs !== null && r.duration_s >= 1) this.store.updateGainProfile(u.user_id, r.lufs);
if (r.text) this.store.hitDict(r.words.map((w) => w.w));
this.emit(u.id);
}
/**
* 잡음 발화: 사이트에 보이지 않고(타임라인 조회에서 뺌) 음성 파일도 지운다. 로그에는 "잡음"으로 남긴다.
* 경기 중 실시간 모델 결과는 경기 뒤 정밀 모델이 다시 보므로 그때까지 파일을 남긴다 (목소리 없음(VAD)은 모델과 상관없어 바로 지움).
*/
private onNoise(u: UtteranceRow, r: TranscribeResult, slot: Slot): void {
const s = this.settings().stt;
// 경기 중이거나 경기 뒤 정밀 변환이 이미 대기열에 있으면(실시간 변환이 늦게 끝난 경우) 그때까지 파일을 남긴다
const recheck = slot === 'realtime' && r.noise_reason !== 'vad' && (this.inMatch || this.queued.has(`precise:${u.id}`)) && s.reprocessAfterMatch && s.preciseModel !== s.realtimeModel;
const name = this.store.getUser(u.user_id)?.name ?? u.user_id;
const dur = ((u.ended_at - u.started_at) / 1000).toFixed(1);
const why = NOISE_REASON[r.noise_reason ?? ''] ?? r.noise_reason ?? '?';
const heard = r.raw_text ? `, 인식 "${r.raw_text.slice(0, 60)}"` : '';
if (recheck) {
log.info(`잡음 발화 ${u.id} (${name}, ${dur}초, ${why}${heard}) · 경기 뒤 정밀 모델로 다시 확인`);
return;
}
this.deleteAudio(u);
log.info(`잡음 발화 ${u.id} 숨김 · 음성 파일 삭제 (${name}, ${dur}초, ${why}${heard})`);
}
private deleteAudio(u: UtteranceRow): void {
if (u.audio_path) {
try {
fs.rmSync(u.audio_path, { force: true });
} catch (e) {
log.warn(`잡음 파일 삭제 실패 ${u.audio_path}`, e);
return;
}
}
this.store.markAudioDeleted(u.id);
}
/**
* 한 번만: v1.3.5 이하 녹음에서 말 중간에 끼운 무음을 빼고(목소리 깨짐) 다시 변환한다.
* 사람이 고친 발화는 파일만 고치고 글은 그대로 둔다.
*/
private repairOldAudio(): void {
const KEY = 'audio_repair_v136';
const CUT = 'audio_repair_v136_before';
if (this.store.meta(KEY)) return;
// 이 시각 전에 만든 녹음만 고친다 (새 녹음기는 진짜 쉼만 채우므로 건드리면 안 됨). 중간에 꺼져도 다음에 이어서
if (!this.store.meta(CUT)) this.store.setMeta(CUT, String(Date.now()));
const before = Number(this.store.meta(CUT));
const rows = this.store.db
.prepare(`SELECT rowid,* FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND noise=0 AND created_at<? ORDER BY started_at`)
.all(before) as UtteranceRow[];
let fixed = 0;
let i = 0;
// 한 번에 20개씩 (시작할 때 화면 · 녹음이 멈추지 않게)
const step = () => {
for (const u of rows.slice(i, i + 20)) {
if (!u.audio_path || !fs.existsSync(u.audio_path)) continue;
try {
const removed = removeInsertedSilence(u.audio_path);
if (!removed) continue;
fixed++;
this.store.db.prepare('UPDATE utterances SET ended_at=ended_at-? WHERE id=?').run(removed * 20, u.id);
// 정밀 모델로만 다시 변환한다 (실시간 모델로 정밀 결과를 덮지 않게)
if (!u.corrected) this.enqueue(u.id, 'precise', 20, true);
} catch (e) {
log.warn(`예전 녹음 고치기 실패 ${u.id}`, e);
}
}
i += 20;
if (i < rows.length) return void setTimeout(step, 0);
this.store.setMeta(KEY, String(Date.now()));
this.onRepairDone?.();
if (fixed) log.info(`예전 녹음 ${fixed}개에서 말 중간에 끼운 무음을 빼고 정밀 모델로 다시 변환`);
};
step();
}
/** v1.3.5 이하에서 잡음으로 판정된 발화의 남은 파일 정리 */
private purgeOldNoise(): void {
const rows = this.store.noiseWithAudio();
for (const r of rows) this.deleteAudio(r);
if (rows.length) log.info(`예전 잡음 발화 ${rows.length}개의 음성 파일 삭제`);
}
private emit(id: string): void {
const row = this.store.getUtterance(id);
if (row) this.bus.live({ type: 'utterance.updated', data: this.timeline.utteranceItem(row) });

View File

@@ -138,7 +138,8 @@ export class Timeline {
where.push('u.started_at <= ?');
args.push(q.to);
}
if (q.hideNoise) where.push('(u.noise = 0 OR u.corrected = 1)');
// 잡음은 보여 주지 않는다 (v1.3.6~, 파일도 지움). 사람이 고친 발화는 보인다
where.push('(u.noise = 0 OR u.corrected = 1)');
if (q.q) {
const kw = q.q.trim();
if ([...kw].length >= 3) {
@@ -224,7 +225,6 @@ export interface TimelineQuery {
to?: number;
q?: string;
types?: string[];
hideNoise?: boolean;
cursor?: string;
limit?: number;
order?: 'asc' | 'desc';

View File

@@ -1,9 +1,13 @@
import { EventEmitter } from 'node:events';
import type { LiveEvent } from '@gvr/shared';
import type { LiveEvent, User } from '@gvr/shared';
/** 코어 내부 이벤트 버스. 'live' 는 사이트로 그대로 나가는 이벤트. */
export class Bus extends EventEmitter {
/** 'users.updated' 에 실을 유저 목록. 보내는 쪽은 신호만 주고 목록은 여기서 채운다 (빈 목록이 나가면 사이트에서 모든 발화가 "알 수 없음"이 됨) */
usersProvider: (() => User[]) | null = null;
live(ev: LiveEvent): void {
if (ev.type === 'users.updated' && this.usersProvider) ev = { type: 'users.updated', data: this.usersProvider() };
this.emit('live', ev);
}
}

View File

@@ -10,6 +10,7 @@ const listeners = new Set<(line: string) => void>();
export function initLogFile(dir: string): void {
fs.mkdirSync(dir, { recursive: true });
const day = new Date().toISOString().slice(0, 10);
stream?.end(); // 로그아웃 후 다시 로그인하면 코어를 다시 띄운다
stream = fs.createWriteStream(path.join(dir, `gvr-${day}.log`), { flags: 'a' });
}
export function setLogLevel(l: Level): void {

View File

@@ -0,0 +1,45 @@
// 사이트 서버와의 https/wss 통신에 쓰는 인증서 신뢰 설정.
// Node 에 들어 있는 Mozilla 루트 인증서만 믿고, 검증은 항상 켠다. 그래서 아래 방법으로는 통신을 엿볼 수 없다
// - NODE_TLS_REJECT_UNAUTHORIZED=0 (검증 끄기), NODE_EXTRA_CA_CERTS · NODE_USE_SYSTEM_CA (가짜 루트 인증서 끼우기)
// - Windows 인증서 저장소에 가짜 루트 인증서 설치 (프록시 · 감시 프로그램)
import https from 'node:https';
import tls from 'node:tls';
export const TLS_TRUST: { ca: string[]; rejectUnauthorized: true } = { ca: [...tls.rootCertificates], rejectUnauthorized: true };
const agent = new https.Agent({ ...TLS_TRUST, keepAlive: true });
export interface SecureResponse {
status: number;
ok: boolean;
text(): Promise<string>;
}
/** fetch 와 비슷한 작은 요청 함수. https 는 위 신뢰 설정으로, http 는 이 PC 안 주소(개발 · 테스트, secureServerUrl 이 거른다)만 */
export function secureFetch(url: string, init: { method?: string; headers?: Record<string, string>; body?: string; timeoutMs?: number } = {}): Promise<SecureResponse> {
const u = new URL(url);
if (u.protocol === 'http:') {
return fetch(url, { method: init.method, headers: init.headers, body: init.body, signal: AbortSignal.timeout(init.timeoutMs ?? 15000) });
}
if (u.protocol !== 'https:') return Promise.reject(new Error(`지원하지 않는 주소: ${u.protocol}`));
return new Promise((resolve, reject) => {
const req = https.request(u, { method: init.method || 'GET', headers: init.headers, agent, ...TLS_TRUST, timeout: init.timeoutMs ?? 15000 }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('error', reject);
res.on('end', () => {
const status = res.statusCode || 0;
const body = Buffer.concat(chunks).toString('utf8');
resolve({ status, ok: status >= 200 && status < 300, text: async () => body });
});
});
req.on('timeout', () => req.destroy(new Error('timeout')));
req.on('error', reject);
if (init.body) req.write(init.body);
req.end();
});
}
/** 검증을 끄는 환경변수는 시작할 때 지운다 (사이트 밖 통신: 다른 봇 모드의 디스코드 연결 · Riot 원격 API 등도 검증하게) */
export function hardenTlsEnv(): void {
delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
}

View File

@@ -0,0 +1,22 @@
// 사이트 서버 주소 검사. 로그인 토큰 · 기기 키 · 기록이 오가므로 암호화(https/wss)되지 않은 주소로는 보내지 않는다.
// 이 PC 안(127.0.0.1 · localhost)만 http 를 허용한다 (개발 · 테스트용)
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]']);
export class InsecureServerUrlError extends Error {}
/** 안전한 주소면 끝의 / 를 뗀 주소를, 아니면 오류를 던진다 */
export function secureServerUrl(raw: string): string {
let u: URL;
try {
u = new URL(String(raw).trim());
} catch {
throw new InsecureServerUrlError('사이트 서버 주소가 올바르지 않습니다');
}
if (u.username || u.password) throw new InsecureServerUrlError('사이트 서버 주소에 아이디 · 비밀번호를 넣을 수 없습니다');
const ok = u.protocol === 'https:' || (u.protocol === 'http:' && LOOPBACK.has(u.hostname));
if (!ok) throw new InsecureServerUrlError('사이트 서버 주소는 https:// 로 시작해야 합니다 (암호화되지 않은 주소로는 로그인 정보와 기록을 보내지 않습니다)');
return u.origin + u.pathname.replace(/\/+$/, '');
}
/** http(s) 주소를 같은 보안 수준의 WebSocket 주소로 (https → wss, http → ws) */
export const wsUrl = (base: string, path: string) => secureServerUrl(base).replace(/^http/, 'ws') + path;

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

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

View File

@@ -1,5 +1,6 @@
// 설정 창(렌더러) ↔ Electron 메인 프로세스 IPC 계약. preload 가 window.gvr 로 노출한다.
import type { User } from '@gvr/shared';
import type { AppRole, AppUserInfo, AppUserRow, LiveGame, User } from '@gvr/shared';
import type { AuthState } from '../core/auth.js';
import type { DiagItem } from '../core/diagnostics.js';
import type { BotState } from '../core/discord/bot.js';
import type { RelayStatus } from '../core/relay/client.js';
@@ -40,11 +41,24 @@ export interface FinetuneStatus {
log: string[];
}
/** 로그인 화면용 상태. appReady = 로그인 후 코어(봇 · 녹음)가 다 떴는지 */
export interface AuthView extends AuthState {
appReady: boolean;
/** 로그인 후 코어 시작 실패 */
appError: string | null;
version: string;
serverUrl: string;
}
export interface AppState {
/** 로그인한 계정 · 역할 (user 는 관리자 전용 설정을 못 바꾼다) */
account: { user: AppUserInfo | null; role: AppRole | null; offline: boolean };
version: string;
dataDir: string;
portable: boolean;
settings: Settings;
/** 겜녹이 기본 봇 토큰을 서버에서 받아 두었는지 */
builtinBot: boolean;
secrets: { botToken: boolean; riotApiKey: boolean; deviceKey: boolean };
secretCodec: string;
bot: BotState;
@@ -52,20 +66,34 @@ export interface AppState {
stt: SttStatus;
relay: RelayStatus;
games: { valorant: { connected: boolean; inMatch: boolean; detail?: string }; lol: { connected: boolean; inMatch: boolean; detail?: string } };
/** 지금 게임 상태 (v1.3.6~) */
liveGames?: LiveGame[];
counts: { utterances: number; matches: number };
excludedUsers: { id: string; name: string }[];
autoStart: boolean;
}
export interface GvrApi {
authState(): Promise<AuthView>;
onAuth(cb: (s: AuthView) => void): () => void;
authLogin(): Promise<AuthView>;
authCancel(): Promise<void>;
authLogout(): Promise<void>;
authRecheck(): Promise<AuthView>;
adminUsers(): Promise<{ users: AppUserRow[] }>;
adminAddUser(id: string, role: 'admin' | 'user'): Promise<{ users: AppUserRow[] }>;
adminSetRole(id: string, role: 'admin' | 'user'): Promise<{ users: AppUserRow[] }>;
adminRemoveUser(id: string): Promise<{ users: AppUserRow[] }>;
adminDisplayNames(): Promise<Record<string, string>>;
adminSetDisplayName(id: string, name: string): Promise<Record<string, string>>;
getState(): Promise<AppState>;
onState(cb: (s: AppState) => void): () => void;
updateSettings(patch: DeepPartial<Settings>): Promise<Settings>;
setSecret(key: 'botToken' | 'riotApiKey', value: string | null): Promise<void>;
testBotToken(token?: string): Promise<{ ok: boolean; bot?: { id: string; name: string; avatar: string | null }; guilds?: { id: string; name: string }[]; error?: string }>;
restartBot(): Promise<{ ok: boolean; error?: string }>;
guildMembers(): Promise<{ id: string; name: string; avatar: string | null; bot: boolean }[]>;
previewTts(text: string, voice: string): Promise<{ ok: boolean; dataUrl?: string; error?: string }>;
guildMembers(): Promise<{ id: string; name: string; avatar: string | null; bot: boolean; me: boolean; admin: boolean }[]>;
previewTts(text: string, voice: string, rate?: number): Promise<{ ok: boolean; dataUrl?: string; error?: string }>;
gpuInfo(): Promise<GpuInfo | null>;
models(): Promise<ModelsInfo | null>;
download(target: 'model' | 'cuda_runtime', name?: string): Promise<{ ok: boolean; error?: string }>;

View File

@@ -2,23 +2,28 @@ import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
import { toUser } from '../core/api/server.js';
import type { AppAuth, AuthState } from '../core/auth.js';
import { runDiagnostics } from '../core/diagnostics.js';
import { synthesize } from '../core/discord/tts.js';
import { clampRate, isOgg, render } from '../core/discord/tts.js';
import type { Core } from '../core/index.js';
import { registerDevice } from '../core/relay/client.js';
import { dirSize } from '../core/retention.js';
import type { AppState, DownloadProgress, GvrApi } from './api-types.js';
import { secureServerUrl } from '../core/util/secure-url.js';
import { ADMIN_ONLY_ACTIONS, ADMIN_ONLY_MESSAGE, adminOnlyPaths, isAdminRole } from '../core/roles.js';
import type { AppState, AuthView, DownloadProgress, GvrApi } from './api-types.js';
import type { Finetuner } from './finetune.js';
type Handlers = { [K in keyof GvrApi]?: (...args: any[]) => any };
export function buildState(core: Core, opts: { dataDir: string; portable: boolean }): AppState {
export function buildState(core: Core, opts: { dataDir: string; portable: boolean; auth: AuthState }): AppState {
const s = core.settings.get();
return {
account: { user: opts.auth.user, role: opts.auth.role, offline: opts.auth.offline },
version: core.version,
dataDir: opts.dataDir,
portable: opts.portable,
settings: s,
builtinBot: core.settings.hasBuiltinBot,
secrets: { botToken: core.settings.hasSecret('botToken'), riotApiKey: core.settings.hasSecret('riotApiKey'), deviceKey: core.settings.hasSecret('deviceKey') },
secretCodec: core.settings.codecName,
bot: core.bot.state,
@@ -26,6 +31,7 @@ export function buildState(core: Core, opts: { dataDir: string; portable: boolea
stt: core.stt.status,
relay: core.relay.status,
games: core.games.status() as AppState['games'],
liveGames: core.games.live(),
counts: core.store.counts(),
excludedUsers: core.store
.listUsers()
@@ -35,18 +41,66 @@ export function buildState(core: Core, opts: { dataDir: string; portable: boolea
};
}
/** 설정 창의 window.gvr 요청 처리 (api-types.ts GvrApi) */
export function registerIpc(core: Core, ft: Finetuner, ctx: { dataDir: string; portable: boolean; win: () => BrowserWindow | null; finishWizard: () => void; quit: () => void }) {
export interface IpcContext {
dataDir: string;
portable: boolean;
win: () => BrowserWindow | null;
finishWizard: () => void;
quit: () => void;
auth: AppAuth;
/** 로그인해서 코어가 떠 있으면 코어 · 파인튜너 */
current: () => { core: Core; ft: Finetuner } | null;
authView: () => AuthView;
/** 로그인 화면에서 다시 확인 (서버 연결 실패 후 재시도) */
recheck: () => Promise<void>;
}
/** 설정 창의 window.gvr 요청 처리 (api-types.ts GvrApi). 로그인 · 관리자 요청은 코어 없이도 받는다 */
export function registerIpc(ctx: IpcContext) {
const send = (ch: string, payload: unknown) => ctx.win()?.webContents.send(ch, payload);
const progress = (p: DownloadProgress) => send('gvr:progress', p);
const role = () => (ctx.auth.ok ? ctx.auth.state.role : null);
// 로그인해야 쓰는 요청은 지금 떠 있는 코어로 보낸다 (로그아웃 후 다시 로그인하면 코어가 새로 뜬다)
const live = () => {
const c = ctx.auth.ok ? ctx.current() : null;
if (!c) throw new Error('로그인이 필요합니다');
return c;
};
const core = new Proxy({} as Core, { get: (_t, k) => (live().core as any)[k] });
const ft = new Proxy({} as Finetuner, {
get: (_t, k) => {
const f = live().ft as any;
return typeof f[k] === 'function' ? f[k].bind(f) : f[k];
},
});
const h: Handlers = {
getState: () => buildState(core, ctx),
updateSettings: (patch) => core.settings.update(patch),
setSecret: (key, value) => core.settings.setSecret(key, value),
getState: () => buildState(core, { ...ctx, auth: ctx.auth.state }),
updateSettings: (patch) => {
if (!isAdminRole(role()) && adminOnlyPaths(patch).length) throw new Error(ADMIN_ONLY_MESSAGE);
// 사이트 서버 주소는 https 만 (로그인 토큰 · 기기 키 · 기록이 오간다)
if (patch?.site?.serverUrl !== undefined) patch = { ...patch, site: { ...patch.site, serverUrl: secureServerUrl(patch.site.serverUrl) } };
return core.settings.update(patch);
},
setSecret: (key, value) => {
if (key !== 'botToken' && key !== 'riotApiKey') throw new Error('바꿀 수 없는 값입니다');
if (key === 'botToken' && !isAdminRole(role())) throw new Error(ADMIN_ONLY_MESSAGE);
return core.settings.setSecret(key, value);
},
testBotToken: async (token?: string) => {
const t = token || core.settings.getSecret('botToken');
const t = token || core.settings.activeBotToken();
// 겜녹이 봇은 토큰이 이 PC 에 없다: 사이트 서버 중계로 붙어 보고 결과를 알려 준다
if (!t && core.settings.get().discord.botMode === 'builtin') {
const b = core.bot;
if (b.state.status !== 'ready' || b.gateway?.kind !== 'remote') {
await b.stop();
await core.startBot();
}
if (b.state.status !== 'ready' || !b.state.user) return { ok: false, error: b.state.error ?? '사이트 서버의 겜녹이 봇에 연결하지 못했습니다' };
return { ok: true, bot: b.state.user, guilds: b.state.guilds };
}
if (!t) return { ok: false, error: '봇 토큰을 입력해 주세요' };
const get = (p: string) => fetch(`https://discord.com/api/v10${p}`, { headers: { authorization: `Bot ${t}` } });
try {
@@ -69,19 +123,23 @@ export function registerIpc(core: Core, ft: Finetuner, ctx: { dataDir: string; p
await core.startBot();
return core.bot.state.status === 'ready' || core.bot.state.status === 'connecting' ? { ok: true } : { ok: false, error: core.bot.state.error ?? '봇을 시작하지 못했습니다' };
},
// 따라갈 사람 목록: 내 계정 → 관리자 → 나머지(이름순). 실패하면 오류를 그대로 보여 준다
guildMembers: async () => {
const g = core.bot.guild();
if (!g) return [];
const ms = await g.members.fetch().catch(() => g.members.cache);
return [...ms.values()].map((m) => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 64 }), bot: m.user.bot })).sort((a, b) => a.name.localeCompare(b.name, 'ko'));
const [ms, admins] = await Promise.all([core.bot.members(), ctx.auth.adminIds().catch(() => [] as string[])]);
const meId = ctx.auth.state.user?.id ?? null;
const rank = (m: { me: boolean; admin: boolean }) => (m.me ? 0 : m.admin ? 1 : 2);
return ms
.map((m) => ({ id: m.id, name: core.store.displayNames()[m.id] ?? m.name, avatar: m.avatar, bot: m.bot, me: m.id === meId, admin: admins.includes(m.id) }))
.sort((a, b) => rank(a) - rank(b) || a.name.localeCompare(b.name, 'ko'));
},
previewTts: async (text: string, voice: string) => {
previewTts: async (text: string, voice: string, rate = 1) => {
try {
const f = path.join(core.paths().tts, `preview-${Date.now()}.webm`);
await synthesize(text, voice, f);
const r = clampRate(rate);
const f = path.join(core.paths().tts, `preview-${Date.now()}.${r < 0.5 ? 'ogg' : 'webm'}`);
await render(text, voice, r, f, (src, dst, tempo) => core.worker.request('tempo', { src, dst, tempo }, 120000));
const data = fs.readFileSync(f);
fs.rmSync(f, { force: true });
return { ok: true, dataUrl: `data:audio/webm;base64,${data.toString('base64')}` };
return { ok: true, dataUrl: `data:audio/${isOgg(f) ? 'ogg' : 'webm'};base64,${data.toString('base64')}` };
} catch (e: any) {
return { ok: false, error: `음성 합성 실패: ${e.message}` };
}
@@ -282,7 +340,33 @@ export function registerIpc(core: Core, ft: Finetuner, ctx: { dataDir: string; p
quit: () => ctx.quit(),
};
const authHandlers: Handlers = {
authState: () => ctx.authView(),
authLogin: () => ctx.auth.login().then(() => ctx.authView()),
authCancel: () => ctx.auth.cancelLogin(),
authLogout: () => ctx.auth.logout(),
authRecheck: () => ctx.recheck().then(() => ctx.authView()),
adminUsers: () => ctx.auth.adminUsers(),
adminAddUser: (id: string, r: 'admin' | 'user') => ctx.auth.adminAddUser(id, r),
adminSetRole: (id: string, r: 'admin' | 'user') => ctx.auth.adminSetRole(id, r),
adminRemoveUser: (id: string) => ctx.auth.adminRemoveUser(id),
adminDisplayNames: () => ctx.auth.displayNames(),
adminSetDisplayName: async (id: string, name: string) => {
if (role() !== 'superadmin') throw new Error('표시 이름은 최고 관리자만 바꿀 수 있습니다');
const r = await ctx.auth.adminSetDisplayName(id, name);
ctx.current()?.core.store.setDisplayNames(r.names);
return r.names;
},
openExternal: h.openExternal,
quit: h.quit,
};
for (const [name, fn] of Object.entries(authHandlers)) ipcMain.handle(`gvr:${name}`, async (_e, ...args) => fn!(...args));
for (const [name, fn] of Object.entries(h)) {
ipcMain.handle(`gvr:${name}`, async (_e, ...args) => fn!(...args));
if (name in authHandlers) continue;
ipcMain.handle(`gvr:${name}`, async (_e, ...args) => {
live();
if (ADMIN_ONLY_ACTIONS.has(name) && !isAdminRole(role())) throw new Error('관리자만 쓸 수 있는 기능입니다');
return fn!(...args);
});
}
}

View File

@@ -1,14 +1,20 @@
// 겜녹이 Electron 메인 프로세스: 트레이 아이콘 + 설정 창 + 첫 실행 마법사. 실제 일은 코어(src/core)가 한다.
import { app, BrowserWindow, Menu, nativeImage, safeStorage, shell, Tray } from 'electron';
import { app, BrowserWindow, Menu, nativeImage, safeStorage, session, shell, Tray } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { AppAuth } from '../core/auth.js';
import { startCore, type Core } from '../core/index.js';
import { plainCodec, type SecretCodec } from '../core/settings.js';
import { plainCodec, SettingsStore, type SecretCodec } from '../core/settings.js';
import { logger } from '../core/util/log.js';
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';
// 인증서 검증을 끄는 환경변수(NODE_TLS_REJECT_UNAUTHORIZED=0)는 무시한다. fuses 로 막지 못하는 변수라 가장 먼저 지운다
hardenTlsEnv();
const log = logger('app');
const argv = process.argv.slice(1);
const flag = (name: string) => argv.includes(`--${name}`);
@@ -23,11 +29,32 @@ if (!SMOKE && !app.requestSingleInstanceLock()) {
let core: Core | null = null;
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;
let quitting = false;
const dataDir = resolveDataDir(opt('data-dir'));
// 창 보안: 설정 창(window.gvr 로 로그인 · 관리자 기능을 부를 수 있다)에는 앱에 들어 있는 화면만 띄운다.
// 링크를 눌러 바깥 페이지가 이 창에 열리면 그 페이지가 window.gvr 를 쓸 수 있으므로, 바깥 주소는 브라우저로만 연다
app.on('web-contents-created', (_e, wc) => {
const own = pathToFileURL(path.join(rendererDir(), 'index.html')).href;
const guard = (e: Electron.Event, url: string) => {
if (url.split(/[?#]/)[0] === own) return;
e.preventDefault();
if (/^https?:\/\//.test(url)) void shell.openExternal(url);
};
wc.on('will-navigate', guard);
wc.on('will-redirect', guard);
wc.on('will-attach-webview', (e) => e.preventDefault());
wc.setWindowOpenHandler(({ url }) => {
if (/^https?:\/\//.test(url)) void shell.openExternal(url);
return { action: 'deny' };
});
});
function dpapiCodec(): SecretCodec {
// Windows: safeStorage = DPAPI (현재 사용자 계정에 묶인 암호화, N-03)
if (safeStorage.isEncryptionAvailable()) return { name: process.platform === 'win32' ? 'dpapi' : 'os-keychain', encrypt: (s) => safeStorage.encryptString(s), decrypt: (b) => safeStorage.decryptString(b) };
@@ -43,8 +70,9 @@ function trayImage(state: 'idle' | 'rec' | 'off'): Electron.NativeImage {
}
function openWindow(route?: string): void {
if (!core) return;
const r = route ?? (core.settings.get().firstRunDone ? '/settings/discord' : '/wizard');
if (!settings) return;
const first = settings.get().firstRunDone;
const r = route ?? (first ? '/settings/discord' : '/wizard');
if (win && !win.isDestroyed()) {
win.webContents.executeJavaScript(`location.hash = ${JSON.stringify('#' + r)}`).catch(() => undefined);
win.show();
@@ -56,7 +84,7 @@ function openWindow(route?: string): void {
height: 760,
minWidth: 960,
minHeight: 640,
title: core.settings.get().firstRunDone ? '겜녹이 · 설정' : '겜녹이 · 첫 실행 설정',
title: first ? '겜녹이 · 설정' : '겜녹이 · 첫 실행 설정',
icon: path.join(brandDir(), 'icon.png'),
backgroundColor: '#0b141c',
autoHideMenuBar: true,
@@ -66,7 +94,10 @@ function openWindow(route?: string): void {
win.setMenu(null);
win.on('page-title-updated', (e) => e.preventDefault());
win.loadFile(path.join(rendererDir(), 'index.html'), { hash: r });
win.once('ready-to-show', () => win?.show());
win.once('ready-to-show', () => {
win?.show();
closeSplash();
});
// 창을 닫아도 트레이에서 계속 돈다 (녹음·사이트 연결 유지)
win.on('close', (e) => {
if (!quitting) {
@@ -74,14 +105,55 @@ function openWindow(route?: string): void {
win?.hide();
}
});
win.webContents.setWindowOpenHandler(({ url }) => {
if (/^https?:\/\//.test(url)) void shell.openExternal(url);
return { action: 'deny' };
}
// ── 시작 창: 포터블 exe 는 풀고 켜는 데 시간이 걸린다. 큰 창이 뜨기 전까지 작은 "켜는 중" 창을 바로 띄운다 ──
let splash: BrowserWindow | null = null;
function showSplash(): void {
const banner = path.join(brandDir(), 'banner.png');
const img = fs.existsSync(banner) ? `data:image/png;base64,${fs.readFileSync(banner).toString('base64')}` : '';
const html = `<!doctype html><meta charset="utf-8"><style>
html,body{margin:0;height:100%;background:#0b141c;color:#e8dfcd;font:14px 'Malgun Gothic','Segoe UI',sans-serif;overflow:hidden;user-select:none;-webkit-app-region:drag}
img{display:block;width:480px;height:192px}
.bar{height:3px;background:#1d2a35;overflow:hidden}.bar i{display:block;height:100%;width:30%;background:#ff4d5a;animation:m 1.2s ease-in-out infinite}
@keyframes m{0%{transform:translateX(-100%)}100%{transform:translateX(340%)}}
#t{text-align:center;padding:9px 0 0}
</style>${img ? `<img src="${img}">` : '<div style="height:192px"></div>'}<div class="bar"><i></i></div><div id="t">겜녹이를 켜는 중입니다…</div>`;
splash = new BrowserWindow({
width: 480,
height: 232,
frame: false,
resizable: false,
movable: true,
center: true,
show: false,
title: '겜녹이 · 켜는 중',
icon: path.join(brandDir(), 'icon.png'),
backgroundColor: '#0b141c',
webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, javascript: true },
});
splash.once('ready-to-show', () => splash?.show());
splash.on('closed', () => (splash = null));
void splash.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`).catch(() => undefined);
}
function splashText(text: string): void {
if (splash && !splash.isDestroyed()) splash.webContents.executeJavaScript(`document.getElementById('t').textContent=${JSON.stringify(text)}`).catch(() => undefined);
}
function closeSplash(): void {
if (splash && !splash.isDestroyed()) splash.destroy();
splash = null;
}
function updateTray(): void {
if (!tray || !core) return;
if (!tray) return;
if (!core) {
tray.setImage(trayImage('off'));
tray.setToolTip(`겜녹이\n${auth?.state.status === 'not_registered' ? '등록되지 않은 아이디' : '로그인이 필요합니다'}`);
return;
}
const st = core.bot.state;
const rel = core.relay.status;
const rec = st.recording.active;
@@ -96,7 +168,17 @@ function updateTray(): void {
}
function buildTrayMenu(): void {
if (!tray || !core) return;
if (!tray) return;
if (!core) {
tray.setContextMenu(
Menu.buildFromTemplate([
{ label: '겜녹이 로그인', click: () => openWindow() },
{ type: 'separator' },
{ label: '종료', click: () => void quit() },
]),
);
return;
}
const c = core;
tray.setContextMenu(
Menu.buildFromTemplate([
@@ -116,8 +198,8 @@ async function quit(): Promise<void> {
if (quitting) return;
quitting = true;
try {
ft?.dispose();
await core?.stop();
auth?.cancelLogin();
await stopApp();
} catch (e) {
log.error('종료 중 오류', e);
}
@@ -130,8 +212,14 @@ async function smoke(): Promise<void> {
const out: Record<string, unknown> = { version: app.getVersion(), dataDir, resources: resourcesDir() };
let code = 1;
try {
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), codec: dpapiCodec() });
const st = new SettingsStore(dataDir, dpapiCodec());
// 로그인: 토큰이 없는 새 설치는 로그인 화면(signed_out)이어야 한다. exe 에는 겜녹이 봇 토큰이 없어야 한다
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 });
out.codec = c.settings.codecName;
out.botMode = c.settings.get().discord.botMode;
const ready = await new Promise<any>((res) => {
if (c.worker.ready) return res(true);
const t = setTimeout(() => res(false), 120000);
@@ -141,14 +229,22 @@ async function smoke(): Promise<void> {
});
});
out.worker = ready;
// 봇: 로그인 전이라 봇 토큰이 없으니 봇은 꺼져 있어야 한다 (토큰이 exe 에 들어 있지 않다는 확인)
out.bot = { status: c.bot.state.status, error: c.bot.state.error };
const botOk = a.status === 'signed_out' && !st.hasBuiltinBot && c.bot.state.status !== 'ready';
out.gpu = await c.worker.request('gpu_info', {}, 30000).catch((e) => String(e));
// 사이트 서버 https: 앱이 믿는 루트 인증서(Node 내장 Mozilla 목록)만으로 실제 서버 인증서가 검증되는지
out.siteTls = await secureFetch(`${c.settings.get().site.serverUrl}/healthz`, { timeoutMs: 20000 }).then(
(r) => r.ok,
(e) => String(e?.message ?? e),
);
c.settings.setSecret('riotApiKey', 'smoke-test');
out.secretRoundTrip = c.settings.getSecret('riotApiKey') === 'smoke-test';
c.settings.setSecret('riotApiKey', null);
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 && out.secretRoundTrip && out.renderer && out.tray ? 0 : 1;
code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray && out.siteTls === true ? 0 : 1;
await c.stop();
} catch (e: any) {
out.error = e.stack || e.message;
@@ -158,29 +254,144 @@ async function smoke(): Promise<void> {
app.exit(code);
}
app.whenReady().then(async () => {
if (SMOKE) return smoke();
core = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), codec: dpapiCodec() });
/** 로그인은 됐는데 코어가 못 뜬 경우의 오류 (로그인 화면에 보여 준다) */
let appError: string | null = null;
const authView = (): AuthView => ({ ...auth!.state, appReady: !!core, appError, version: app.getVersion(), serverUrl: settings!.get().site.serverUrl });
const pushAuth = () => {
if (win && !win.isDestroyed()) win.webContents.send('gvr:auth', authView());
};
const pushState = () => {
if (core && auth && win && !win.isDestroyed() && win.isVisible()) win.webContents.send('gvr:state', buildState(core, { dataDir, portable: app.isPackaged, auth: auth.state }));
};
const refreshShell = () => {
pushAuth();
buildTrayMenu();
updateTray();
};
let starting: Promise<void> | null = null;
/** 표시 이름(실명 숨기기)을 사이트 서버에서 받아 녹음 기록 · 범인 분석에 반영한다 (못 받으면 저장해 둔 것을 그대로 쓴다) */
async function syncNames(): Promise<void> {
const c = core;
ft = new Finetuner(c, () => win?.webContents.send('gvr:state', buildState(c, { dataDir, portable: app.isPackaged })));
ft.scheduleNightly();
registerIpc(c, ft, {
if (!c || !auth?.ok) return;
try {
const names = await auth.displayNames();
if (core === c) {
c.store.setDisplayNames(names);
// 녹음 파일 이름에도 표시 이름을 쓴다
c.audioNames.refreshAll();
}
} catch (e: any) {
log.warn(`표시 이름을 받지 못했습니다: ${e?.message ?? e}`);
}
}
/** 로그인 확인 후 코어 시작 */
function startApp(): Promise<void> {
if (core) return Promise.resolve();
starting ??= (async () => {
try {
// 겜녹이 봇 중계가 로그인 만료 · 등록 해제를 알려 오면 10분을 기다리지 않고 바로 확인해서 잠근다
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check() });
core = c;
void syncNames();
ft = new Finetuner(c, pushState);
ft.scheduleNightly();
appError = null;
} catch (e: any) {
log.error('코어 시작 실패', e);
appError = `겜녹이를 시작하지 못했습니다: ${e?.message ?? e}`;
} finally {
starting = null;
refreshShell();
}
})();
return starting;
}
/** 로그아웃 · 등록 해제: 봇 · 녹음 · 사이트 연결을 모두 멈춘다 */
async function stopApp(): Promise<void> {
if (starting) await starting;
if (!core) return;
const c = core;
core = null;
ft?.dispose();
ft = null;
try {
await c.stop();
} finally {
refreshShell();
}
}
let authChain: Promise<void> = Promise.resolve();
function onAuthChange(): void {
authChain = authChain
.then(async () => {
if (quitting) return;
pushAuth();
const st = auth!.state.status;
if (st === 'ok') {
if (!core) return startApp();
} else if (st !== 'checking' && st !== 'waiting') {
await stopApp();
openWindow();
}
})
.catch((e) => log.error('로그인 상태 처리 실패', e));
}
app.whenReady().then(async () => {
// 마이크 · 카메라 · 위치 · 알림 등 권한 요청은 모두 거절한다 (아이디 복사용 클립보드 쓰기만 허용)
session.defaultSession.setPermissionRequestHandler((_wc, perm, cb) => cb(perm === 'clipboard-sanitized-write'));
if (SMOKE) return smoke();
if (!flag('hidden')) showSplash();
settings = new SettingsStore(dataDir, dpapiCodec());
auth = new AppAuth(settings, { version: app.getVersion(), openUrl: (u) => shell.openExternal(u) });
const a = auth;
registerIpc({
dataDir,
portable: app.isPackaged,
win: () => (win && !win.isDestroyed() ? win : null),
finishWizard: () => win?.setTitle('겜녹이 · 설정'),
quit: () => void quit(),
auth: a,
current: () => (core && ft ? { core, ft } : null),
authView,
recheck: async () => {
await a.check();
await authChain;
if (starting) await starting;
},
});
tray = new Tray(trayImage('off'));
tray.on('click', () => openWindow());
buildTrayMenu();
updateTray();
refreshShell();
a.on('change', onAuthChange);
// 시작할 때 확인 → 10분마다 다시 확인 (등록 해제되면 바로 잠김). 서버에 못 붙어 막힌 상태면 1분마다 다시 시도
let lastCheck = Date.now();
const first = a.check();
setInterval(() => {
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(() => {
updateTray();
buildTrayMenu();
if (win && !win.isDestroyed() && win.isVisible()) win.webContents.send('gvr:state', buildState(c, { dataDir, portable: app.isPackaged }));
pushState();
}, 1500);
if (!flag('hidden') || !c.settings.get().firstRunDone) openWindow();
splashText('로그인 확인 중…');
await first;
if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…');
await authChain;
if (!flag('hidden') || !settings.get().firstRunDone || !a.ok) openWindow();
else closeSplash();
// 창이 끝내 안 뜨는 경우(오류 등)에도 시작 창이 남지 않게
setTimeout(closeSplash, 30000);
if (process.env.GVR_CAPTURE_DIR) void captureScreens(process.env.GVR_CAPTURE_DIR);
});

View File

@@ -1,12 +1,13 @@
import { contextBridge, ipcRenderer } from 'electron';
// window.gvr — api-types.ts 의 GvrApi. 이벤트 3개(onState, onProgress, onDiag)만 구독형이고 나머지는 invoke.
// window.gvr — api-types.ts 의 GvrApi. 이벤트 4개(onState, onProgress, onDiag, onAuth)만 구독형이고 나머지는 invoke.
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',
'finetuneStatus', 'finetuneInstall', 'finetuneStart', 'finetuneStop', 'finetuneRollback', 'clearTrainingData', 'openExternal',
'openPath', 'setAutoStart', 'finishWizard', 'recentLogs', 'quit',
'authState', 'authLogin', 'authCancel', 'authLogout', 'authRecheck', 'adminUsers', 'adminAddUser', 'adminSetRole', 'adminRemoveUser', 'adminDisplayNames', 'adminSetDisplayName',
];
const api: Record<string, unknown> = {};
for (const m of METHODS) api[m] = (...args: unknown[]) => ipcRenderer.invoke(`gvr:${m}`, ...args);
@@ -18,4 +19,5 @@ const sub = (ch: string) => (cb: (v: unknown) => void) => {
api.onState = sub('gvr:state');
api.onProgress = sub('gvr:progress');
api.onDiag = sub('gvr:diag');
api.onAuth = sub('gvr:auth');
contextBridge.exposeInMainWorld('gvr', api);

View File

@@ -0,0 +1,143 @@
// 로그인 화면 + 로그인 게이트. 등록된 디스코드 아이디로 로그인해야 설정 창(과 봇 · 녹음)이 열린다
import { useEffect, useState, type ReactNode } from 'react';
import type { AuthView } from '../../main/api-types';
import banner from '../assets/banner.png';
import { gvr } from '../store';
import { Avatar, Btn, Err, Spinner } from '../ui';
import { errMsg } from '../util';
export function AuthGate({ children }: { children: ReactNode }) {
const [auth, setAuth] = useState<AuthView | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
gvr.authState().then(
(s) => alive && setAuth(s),
(e) => alive && setLoadError(errMsg(e)),
);
const off = gvr.onAuth((s) => setAuth(s));
return () => {
alive = false;
off();
};
}, []);
if (!auth) return <div className="boot">{loadError ? <div className="err">메인 프로세스에 연결하지 못했습니다: {loadError}</div> : <Spinner big />}</div>;
if (auth.status === 'ok' && auth.appReady) return <>{children}</>;
return <LoginScreen auth={auth} />;
}
function LoginScreen({ auth }: { auth: AuthView }) {
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
useEffect(() => {
document.title = '겜녹이 · 로그인';
}, []);
const login = async () => {
setError(null);
try {
await gvr.authLogin();
} catch (e) {
setError(errMsg(e));
}
};
const st = auth.status;
const host = auth.serverUrl.replace(/^https?:\/\//, '');
let body: ReactNode;
if (st === 'ok' && !auth.appReady && auth.appError) {
body = (
<>
<Err>{auth.appError}</Err>
<div className="muted small">로그인은 되었습니다. 겜녹이를 종료한 뒤 다시 실행해 주세요. 계속되면 GVR-Data\logs 의 로그를 관리자에게 보내 주세요.</div>
</>
);
} else if (st === 'checking' || (st === 'ok' && !auth.appReady)) {
body = (
<div className="row gap muted">
<Spinner /> {st === 'ok' ? '겜녹이를 시작하는 중…' : '로그인 확인 중…'}
</div>
);
} else if (st === 'waiting') {
body = (
<>
<div className="row gap">
<Spinner /> 브라우저에서 디스코드 로그인을 마쳐 주세요
</div>
<div className="hint">
브라우저가 열리지 않았다면{' '}
<a href="#" onClick={(e) => (e.preventDefault(), auth.loginUrl && void gvr.openExternal(auth.loginUrl))}>
로그인 페이지 다시 열기 ↗
</a>
</div>
<div className="row end">
<Btn onClick={() => gvr.authCancel()}>취소</Btn>
</div>
</>
);
} else if (st === 'not_registered') {
body = (
<>
<div className="login-bad">⛔ 등록되지 않은 아이디입니다</div>
{auth.user && (
<div className="login-who">
<Avatar name={auth.user.name} src={auth.user.avatar} size={32} />
<div className="grow">
<div>{auth.user.name}</div>
<div className="id">{auth.user.id}</div>
</div>
<Btn
small
onClick={async () => {
await navigator.clipboard.writeText(auth.user!.id).catch(() => undefined);
setCopied(true);
}}
>
{copied ? '복사됨 ✓' : '아이디 복사'}
</Btn>
</div>
)}
<div className="muted small">이 계정은 겜녹이를 쓸 수 없습니다. 관리자에게 위 디스코드 아이디 등록을 요청한 뒤 다시 로그인해 주세요.</div>
<Btn primary onClick={login}>
다시 로그인
</Btn>
</>
);
} else {
body = (
<>
<div className="muted small">등록된 디스코드 계정으로 로그인해야 겜녹이를 쓸 수 있습니다. 로그인 버튼을 누르면 브라우저에서 디스코드 로그인 창이 열립니다.</div>
{st === 'error' && (
<div className="row gap">
<Err>{auth.error}</Err>
<span className="grow" />
<Btn small onClick={() => gvr.authRecheck()}>
다시 시도
</Btn>
</div>
)}
{st === 'signed_out' && auth.error && <Err>{auth.error}</Err>}
<Btn primary onClick={login}>
디스코드로 로그인
</Btn>
</>
);
}
return (
<div className="login">
<div className="login-card">
<img className="banner" src={banner} alt="겜녹이" />
<div className="h login-title">로그인</div>
{body}
<Err>{error}</Err>
<div className="login-foot">
겜녹이 v{auth.version} · {host}
<span className="grow" />
<Btn small ghost onClick={() => gvr.quit()}>
종료
</Btn>
</div>
</div>
</div>
);
}

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<!-- 브라우저 개발용: window.gvr 가 없으면 main.tsx 가 mock-gvr 로 대신한다.
?first=1 → 첫 실행(마법사) 상태, ?nogpu=1 → GPU 없음, ?empty=1 → 봇 토큰 없음 -->
?first=1 → 첫 실행(마법사) 상태, ?nogpu=1 → GPU 없음, ?empty=1 → 봇 토큰 없음, ?custom=1 → 다른 봇 모드, ?nobuiltin=1 → 기본 봇 없는 빌드 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>겜녹이 · 설정 (dev)</title>
<link rel="stylesheet" href="renderer.css">

View File

@@ -1,9 +1,12 @@
// 겜녹이 설정 창 렌더러 진입점. 라우팅: #/wizard[/단계] · #/settings/<탭>
import { useEffect, useState, type ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import { ROLE_LABEL, isAdminRole } from '../core/roles';
import tray from './assets/tray@2x.png';
import { AuthGate } from './auth/Login';
import { AppProvider, isMock, useApp } from './store';
import './styles.css';
import { AdminTab } from './tabs/AdminTab';
import { AudioTab } from './tabs/AudioTab';
import { DiagTab } from './tabs/DiagTab';
import { DictTab } from './tabs/DictTab';
@@ -12,7 +15,7 @@ import { GamesTab } from './tabs/GamesTab';
import { GeneralTab } from './tabs/GeneralTab';
import { StorageTab } from './tabs/StorageTab';
import { SttTab } from './tabs/SttTab';
import { Dot } from './ui';
import { Avatar, Dot } from './ui';
import { go } from './util';
import { Wizard } from './wizard/Wizard';
@@ -26,6 +29,9 @@ const TABS: { id: string; icon: string; label: string; el: () => ReactNode }[] =
{ id: 'diag', icon: '🔬', label: '진단', el: () => <DiagTab /> },
{ id: 'general', icon: '⚙️', label: '일반', el: () => <GeneralTab /> },
];
/** 관리자 · 최고 관리자에게만 보이는 탭 */
const ADMIN_TAB = { id: 'admin', icon: '🛡️', label: '관리자', el: () => <AdminTab /> };
const tabsFor = (role: string | null) => (isAdminRole(role as never) ? [...TABS, ADMIN_TAB] : TABS);
function useHash(): string {
const [h, setH] = useState(location.hash);
@@ -38,7 +44,7 @@ function useHash(): string {
}
function Router() {
const { settings } = useApp();
const { settings, state } = useApp();
const hash = useHash();
const parts = hash.replace(/^#\/?/, '').split('/');
@@ -53,10 +59,11 @@ function Router() {
}, [isWizard]);
if (isWizard) return <Wizard step={Math.max(1, Math.min(5, Number(parts[1]) || 1))} />;
const tab = TABS.find((t) => t.id === parts[1]) ?? TABS[0]!;
const tabs = tabsFor(state.account.role);
const tab = tabs.find((t) => t.id === parts[1]) ?? tabs[0]!;
return (
<div className="app">
<Nav current={tab.id} />
<Nav current={tab.id} tabs={tabs} />
<main className="content" key={tab.id}>
{tab.el()}
</main>
@@ -64,8 +71,9 @@ function Router() {
);
}
function Nav({ current }: { current: string }) {
function Nav({ current, tabs }: { current: string; tabs: typeof TABS }) {
const { state } = useApp();
const acc = state.account;
const bot = state.bot.status;
const botTone = bot === 'ready' ? 'ok' : bot === 'connecting' ? 'warn' : bot === 'error' ? 'err' : 'off';
const botText = bot === 'ready' ? (state.bot.recording.active ? '녹음 중' : '정상') : bot === 'connecting' ? '연결 중' : bot === 'error' ? '오류' : '꺼짐';
@@ -74,13 +82,21 @@ function Nav({ current }: { current: string }) {
const relayText = r === 'online' ? '연결됨' : r === 'connecting' ? '연결 중' : r === 'error' ? '오류' : '미등록';
return (
<nav className="side">
{TABS.map((t) => (
{tabs.map((t) => (
<a key={t.id} href={`#/settings/${t.id}`} className={`tab ${t.id === current ? 'on' : ''}`}>
<span className="ic">{t.icon}</span>
{t.label}
</a>
))}
<div className="nav-status">
{acc.user && (
<a href="#/settings/general" className="nav-account" title={acc.offline ? '사이트 서버에 연결되지 않아 마지막 확인 결과로 쓰는 중' : acc.user.id}>
<Avatar name={acc.user.name} src={acc.user.avatar} size={18} />
{acc.user.name}
{acc.role && <span className={`role ${acc.role}`}>{ROLE_LABEL[acc.role]}</span>}
{acc.offline && <span className="t-warn">·오프라인</span>}
</a>
)}
<div className="brand-mini">
<img src={tray} alt="" />
겜녹이 v{state.version}
@@ -101,7 +117,9 @@ function Nav({ current }: { current: string }) {
}
createRoot(document.getElementById('root')!).render(
<AppProvider>
<Router />
</AppProvider>,
<AuthGate>
<AppProvider>
<Router />
</AppProvider>
</AuthGate>,
);

View File

@@ -1,9 +1,10 @@
// 브라우저 개발/스크린샷용 가짜 GvrApi. window.gvr 가 없을 때만 쓴다.
// URL 옵션: ?first=1 (첫 실행 · 마법사), ?nogpu=1 (GPU 없음), ?empty=1 (봇 토큰 없음), ?dl=0.6 (다운로드 시작 위치 비율)
import type { User } from '@gvr/shared';
// ?login=signed_out|not_registered|error (로그인 화면), ?role=superadmin|admin|user (기본 superadmin)
import type { AppRole, AppUserRow, User } from '@gvr/shared';
import type { DiagItem } from '../core/diagnostics';
import type { Settings } from '../core/settings';
import type { AppState, DownloadProgress, FinetuneStatus, GvrApi, ModelsInfo } from '../main/api-types';
import type { AppState, AuthView, DownloadProgress, FinetuneStatus, GvrApi, ModelsInfo } from '../main/api-types';
import { MODEL_META } from './models-meta';
import { deepMerge, sleep } from './util';
@@ -14,16 +15,18 @@ function defaults(): Settings {
version: 1,
firstRunDone: false,
discord: {
botMode: 'builtin',
guildId: null,
followUserId: null,
followEnabled: true,
commandsEnabled: true,
ttsEnabled: true,
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
ttsRate: 1,
},
games: { valorant: true, lol: true, lolChatOcr: true, lolOcrRegion: { x: 0.0, y: 0.6, w: 0.3, h: 0.27 }, lolLogsDir: null },
games: { valorant: true, lol: true, lolLogsDir: null },
stt: {
realtimeModel: 'large-v3-turbo',
preciseModel: 'large-v3',
@@ -84,17 +87,50 @@ export function createMockGvr(): GvrApi {
const settings = defaults();
settings.firstRunDone = !first;
if (q.has('custom')) settings.discord.botMode = 'custom';
if (!noToken) {
settings.discord.guildId = 'g1';
settings.discord.followUserId = 'u1';
settings.site.deviceId = 'dev_8f2c';
}
const role = (q.get('role') as AppRole) || 'superadmin';
const me = { id: '293719842274541579', name: role === 'user' ? '민준' : '사금향', avatar: null };
const login = q.get('login');
const auth: AuthView = {
status: login === 'signed_out' || login === 'not_registered' || login === 'error' ? login : 'ok',
user: login === 'not_registered' ? { id: '987654321098765432', name: '모르는사람', avatar: null } : login ? null : me,
role: login ? null : role,
offline: false,
error: login === 'error' ? '사이트 서버에 연결할 수 없습니다 (fetch failed)' : null,
loginUrl: null,
verifiedAt: login ? null : now,
appReady: !login,
appError: null,
version: '1.2.0',
serverUrl: 'https://gvr.tkrmagid.kr',
};
const authListeners = new Set<(s: AuthView) => void>();
const emitAuth = () => authListeners.forEach((l) => l(structuredClone(auth)));
const displayNames: Record<string, string> = { '100000000000000003': '지호' };
let adminRows: AppUserRow[] = [
{ id: '293719842274541579', name: '사금향', avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: now - 60000, lastVersion: '1.2.0' },
{ id: '1352267557213573160', name: '두번째관리자', avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: now - 3 * 86400000, lastVersion: '1.2.0' },
{ id: '401234567890123456', name: '서연', avatar: null, role: 'admin', fixed: false, addedBy: '293719842274541579', addedAt: now - 5 * 86400000, lastSeenAt: now - 2 * 3600000, lastVersion: '1.2.0' },
{ id: '402345678901234567', name: '민준', avatar: null, role: 'user', fixed: false, addedBy: '293719842274541579', addedAt: now - 4 * 86400000, lastSeenAt: now - 20 * 60000, lastVersion: '1.2.0' },
{ id: '403456789012345678', name: '지호', avatar: null, role: 'user', fixed: false, addedBy: '293719842274541579', addedAt: now - 86400000, lastSeenAt: null, lastVersion: null },
];
const adminCheck = (lvl: 'admin' | 'superadmin') => {
if (lvl === 'superadmin' ? role !== 'superadmin' : role === 'user') throw new Error(lvl === 'superadmin' ? '유저 등록은 최고 관리자만 할 수 있습니다' : '관리자만 볼 수 있습니다');
};
const state: AppState = {
version: '1.0.0',
account: { user: me, role, offline: false },
version: '1.2.0',
dataDir: 'D:\\겜녹이\\GVR-Data',
portable: true,
settings,
builtinBot: !q.has('nobuiltin'),
secrets: { botToken: !noToken, riotApiKey: false, deviceKey: !noToken },
secretCodec: 'dpapi',
bot: noToken
@@ -123,6 +159,17 @@ export function createMockGvr(): GvrApi {
valorant: { connected: true, inMatch: false, detail: 'Riot Client 연결됨 · 대기실' },
lol: { connected: false, inMatch: false, detail: '클라이언트 꺼짐' },
},
liveGames: [
{
game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null,
startedAt: now - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null,
self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, updatedAt: now,
},
{
game: 'lol', enabled: true, connected: true, phase: '로비', inMatch: false, matchId: null, mode: '솔로 랭크', map: null, mapImage: null,
startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: null, characterImage: null, kda: null, extra: null }, players: null, error: null, updatedAt: now,
},
],
counts: { utterances: 1824, matches: 37 },
excludedUsers: noToken ? [] : [{ id: 'u4', name: '현우' }],
autoStart: false,
@@ -210,6 +257,71 @@ export function createMockGvr(): GvrApi {
}, 4000);
const api: GvrApi = {
async authState() {
await sleep(60);
return structuredClone(auth);
},
onAuth(cb) {
authListeners.add(cb);
return () => authListeners.delete(cb);
},
async authLogin() {
Object.assign(auth, { status: 'waiting', loginUrl: 'https://gvr.tkrmagid.kr/auth/app/start/mock', error: null });
emitAuth();
await sleep(2500);
if (auth.status !== 'waiting') return structuredClone(auth);
Object.assign(auth, { status: 'ok', user: me, role, loginUrl: null, appReady: true, verifiedAt: Date.now() });
emitAuth();
return structuredClone(auth);
},
async authCancel() {
Object.assign(auth, { status: 'signed_out', loginUrl: null });
emitAuth();
},
async authLogout() {
Object.assign(auth, { status: 'signed_out', user: null, role: null, appReady: false, error: null });
emitAuth();
},
async authRecheck() {
await sleep(600);
return structuredClone(auth);
},
async adminUsers() {
await sleep(200);
adminCheck('admin');
return { users: structuredClone(adminRows) };
},
async adminAddUser(id, r) {
await sleep(400);
adminCheck('superadmin');
if (!/^\d{17,20}$/.test(id.trim())) throw new Error('디스코드 아이디는 17~20자리 숫자입니다');
if (adminRows.some((u) => u.id === id.trim())) adminRows = adminRows.map((u) => (u.id === id.trim() && !u.fixed ? { ...u, role: r } : u));
else adminRows.push({ id: id.trim(), name: `새유저${adminRows.length}`, avatar: null, role: r, fixed: false, addedBy: me.id, addedAt: Date.now(), lastSeenAt: null, lastVersion: null });
return { users: structuredClone(adminRows) };
},
async adminSetRole(id, r) {
await sleep(200);
adminCheck('superadmin');
adminRows = adminRows.map((u) => (u.id === id && !u.fixed ? { ...u, role: r } : u));
return { users: structuredClone(adminRows) };
},
async adminDisplayNames() {
await sleep(150);
return { ...displayNames };
},
async adminSetDisplayName(id, name) {
await sleep(150);
adminCheck('superadmin');
if (name.trim()) displayNames[id] = name.trim();
else delete displayNames[id];
return { ...displayNames };
},
async adminRemoveUser(id) {
await sleep(200);
adminCheck('superadmin');
adminRows = adminRows.filter((u) => u.id !== id || u.fixed);
return { users: structuredClone(adminRows) };
},
async getState() {
await sleep(80);
return structuredClone(state);
@@ -229,9 +341,11 @@ export function createMockGvr(): GvrApi {
emit();
},
async testBotToken(token) {
// 실제 IPC 처럼 부를 때의 모드로 토큰을 고른다 (응답은 늦게 온다)
const noSaved = state.settings.discord.botMode === 'builtin' ? !state.builtinBot : !state.secrets.botToken;
await sleep(900);
if (token !== undefined && token.length < 20) return { ok: false, error: '토큰이 올바르지 않습니다 (401 Unauthorized)' };
if (token === undefined && !state.secrets.botToken) return { ok: false, error: '저장된 토큰이 없습니다' };
if (token === undefined && noSaved) return { ok: false, error: '저장된 토큰이 없습니다' };
return {
ok: true,
bot: { id: 'b1', name: '겜녹이#4821', avatar: null },
@@ -242,6 +356,11 @@ export function createMockGvr(): GvrApi {
};
},
async restartBot() {
if (state.settings.discord.botMode === 'builtin' ? !state.builtinBot : !state.secrets.botToken) {
state.bot = { ...state.bot, status: 'off', error: null, user: null, guild: null, guilds: [] };
emit();
return { ok: false, error: '봇 토큰이 없습니다' };
}
state.bot.status = 'connecting';
emit();
await sleep(900);
@@ -262,12 +381,12 @@ export function createMockGvr(): GvrApi {
async guildMembers() {
await sleep(300);
return [
{ id: 'u1', name: '민준', avatar: null, bot: false },
{ id: 'u2', name: '서연', avatar: null, bot: false },
{ id: 'u3', name: '지호', avatar: null, bot: false },
{ id: 'u4', name: '현우', avatar: null, bot: false },
{ id: 'b1', name: '겜녹이', avatar: null, bot: true },
{ id: 'b2', name: 'MEE6', avatar: null, bot: true },
{ id: 'u1', name: '민준', avatar: null, bot: false, me: true, admin: true },
{ id: 'u3', name: '지호', avatar: null, bot: false, me: false, admin: true },
{ id: 'u2', name: '서연', avatar: null, bot: false, me: false, admin: false },
{ id: 'u4', name: '현우', avatar: null, bot: false, me: false, admin: false },
{ id: 'b1', name: '겜녹이', avatar: null, bot: true, me: false, admin: false },
{ id: 'b2', name: 'MEE6', avatar: null, bot: true, me: false, admin: false },
];
},
async previewTts() {
@@ -367,7 +486,6 @@ export function createMockGvr(): GvrApi {
{ id: 'tts', label: 'TTS 안내 음성', ok: true, detail: 'Edge TTS 응답 0.6초' },
{ id: 'valorant', label: '발로란트 로컬 API', ok: true, detail: 'Riot Client 연결됨 (lockfile)' },
{ id: 'lol', label: '롤 Live Client API', ok: null, detail: '게임이 꺼져 있어 확인할 수 없습니다' },
{ id: 'ocr', label: '롤 채팅 OCR', ok: null, detail: '게임이 꺼져 있어 확인할 수 없습니다' },
{ id: 'relay', label: '사이트 서버', ok: state.relay.state === 'online', detail: state.relay.state === 'online' ? 'gvr.tkrmagid.kr 연결됨 · 왕복 38ms' : '등록되지 않음' },
{ id: 'disk', label: '저장 공간', ok: true, detail: 'D: 여유 412GB' },
];

View File

@@ -159,6 +159,7 @@ input[type='number'].input { flex: none; padding: 7px 8px; }
.radio button { flex: 1; text-align: left; border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; font-size: 13px; background: var(--field); cursor: pointer; }
.radio button.on { border: 2px solid var(--accent); background: #1e1419; padding: 11px 13px; }
.radio b { display: block; margin-bottom: 4px; font-size: 14px; }
.radio + .field, .radio + .lab { margin-top: 14px; }
.recstat { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font-size: 14px; }
.recstat.idle { color: var(--muted); font-size: 13px; }
.rec-dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 4px rgba(255, 70, 85, 0.2); animation: pulse 1.6s infinite; }
@@ -177,8 +178,6 @@ input[type='number'].input { flex: none; padding: 7px 8px; }
.game.lol.on { border: 2px solid var(--lol); background: linear-gradient(160deg, #241e13, var(--panel) 60%); padding: 15px 17px; }
.game.lol .game-name { color: var(--lol); }
.game.lol .tg.on { background: linear-gradient(180deg, #c8aa6e, #9a7b45); }
.region { display: flex; gap: 10px; }
.region label { display: flex; align-items: center; gap: 5px; }
/* 표 */
.table { width: 100%; border-collapse: collapse; font-size: 13px; }
@@ -295,3 +294,65 @@ input[type='number'].input { flex: none; padding: 7px 8px; }
.modal-bg { position: fixed; inset: 0; background: rgba(3, 8, 12, 0.66); display: flex; align-items: center; justify-content: center; z-index: 60; }
.modal { width: 420px; background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 22px; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); }
.modal-text { font-size: 14px; line-height: 1.6; margin-bottom: 18px; white-space: pre-wrap; }
/* ---------- 로그인 · 관리자 ---------- */
.admin-lock { border: 0; min-width: 0; padding: 0; margin: 0; }
.admin-lock .locked { opacity: 0.5; pointer-events: none; }
.lock-note { font-size: 12px; color: var(--gold); margin-bottom: 8px; }
.login { height: 100%; display: flex; align-items: center; justify-content: center; padding: 24px; }
.login-card { width: 440px; background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 28px 30px 22px; display: flex; flex-direction: column; gap: 14px; }
.login-card .banner { width: 100%; border-radius: 10px; border: 1px solid var(--line); display: block; }
.login-title { font-size: 20px; font-weight: 800; }
.login-card .btn.discord { background: #5865f2; border-color: #5865f2; color: #fff; font-weight: 700; padding: 12px 16px; font-size: 14px; }
.login-who { display: flex; align-items: center; gap: 10px; background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; }
.login-who .id { font-family: var(--font-mono); font-size: 12px; color: var(--muted); }
.login-bad { color: #ff6b77; font-weight: 700; font-size: 15px; }
.login-foot { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--dim); border-top: 1px solid var(--line); padding-top: 12px; }
.role { display: inline-block; font-size: 11px; padding: 2px 8px; border-radius: 6px; font-weight: 700; }
.role.superadmin { background: rgba(255, 70, 85, 0.16); color: #ff8a94; }
.role.admin { background: rgba(242, 178, 58, 0.16); color: var(--gold); }
.role.user { background: rgba(20, 193, 183, 0.14); color: var(--mint); }
.nav-account { display: flex; align-items: center; gap: 6px; margin-bottom: 4px; color: #b9c6d2; }
.admin-list { list-style: none; display: flex; flex-direction: column; gap: 6px; font-size: 13px; }
.admin-list li { display: flex; gap: 8px; align-items: baseline; }
.admin-list li .muted { font-size: 12px; }
/* 지금 게임 (게임 연동 탭) */
.live-games {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.live-game {
border: 1px solid var(--line, #22313f);
border-radius: 10px;
padding: 12px 14px;
background: rgba(255, 255, 255, 0.02);
}
.live-game.in-match.valorant {
border-color: rgba(255, 70, 85, 0.55);
}
.live-game.in-match.lol {
border-color: rgba(200, 170, 110, 0.6);
}
.live-game-top {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.live-game-top .badge {
margin-left: auto;
}
.live-rows {
width: 100%;
font-size: 12.5px;
border-collapse: collapse;
}
.live-rows td {
padding: 3px 0;
vertical-align: top;
}
.live-rows td:first-child {
width: 42%;
}

View File

@@ -0,0 +1,258 @@
// 관리자 탭: 유저 등록(최고 관리자만) · 등록 유저 목록 · 관리자 전용 기능 안내
import { useState } from 'react';
import type { AppUserRow } from '@gvr/shared';
import { ROLE_LABEL } from '../../core/roles';
import { gvr, useAction, useApp, useLoad } from '../store';
import { Avatar, Btn, Err, Page, Section, Select, Spinner } from '../ui';
import { fmtAgo, fmtDate } from '../util';
const ROLE_OPTIONS = [
{ value: 'user' as const, label: '유저' },
{ value: 'admin' as const, label: '관리자' },
];
/** 일반 유저가 바꿀 수 없는 것 (core/roles.ts 와 같은 목록) */
const ADMIN_FEATURES: { what: string; why: string; tab: string }[] = [
{ what: '다른 봇으로 바꾸기 · 봇 토큰 입력', why: '겜녹이 봇 대신 다른 봇을 붙이는 설정', tab: 'discord' },
{ what: '녹음 안내(TTS) 끄기 · 안내 문구 변경', why: '녹음되는 사람에게 알리는 장치', tab: 'discord' },
{ what: '음성 보관 기간', why: '다른 사람 목소리를 얼마나 남길지 정하는 정책', tab: 'storage' },
{ what: '사이트 서버 주소 · PC 이름 · 사이트 등록/해제', why: '모두가 보는 사이트에 연결되는 PC', tab: 'storage' },
{ what: '학습 데이터 삭제', why: '되돌릴 수 없는 삭제', tab: 'storage' },
{ what: '파인튜닝 (학습 · 되돌리기 · 자동 일정)', why: '인식 모델을 바꾸는 작업', tab: 'stt' },
];
function AddUser({ onDone }: { onDone: (users: AppUserRow[]) => void }) {
const { toast } = useApp();
const [id, setId] = useState('');
const [role, setRole] = useState<'user' | 'admin'>('user');
const act = useAction();
const valid = /^\d{17,20}$/.test(id.trim());
const add = async () => {
const r = await act.run(() => gvr.adminAddUser(id.trim(), role));
if (r) {
onDone(r.users);
setId('');
toast(`${r.users.find((u) => u.id === id.trim())?.name ?? id.trim()} 등록됨`);
}
};
return (
<>
<div className="field">
<input
className={`input mono ${id && !valid ? 'bad' : ''}`}
value={id}
placeholder="디스코드 아이디 (숫자 17~20자리)"
spellCheck={false}
onChange={(e) => setId(e.target.value.replace(/\s/g, ''))}
onKeyDown={(e) => e.key === 'Enter' && valid && void add()}
/>
<Select width={110} value={role} options={ROLE_OPTIONS} onChange={setRole} />
<Btn primary disabled={!valid} busy={act.busy} onClick={add}>
등록
</Btn>
</div>
<div className="hint">디스코드 설정 → 고급 → 개발자 모드를 켠 뒤, 프로필을 오른쪽 클릭 → '사용자 ID 복사'로 아이디를 얻습니다. 등록되지 않은 사람이 로그인하면 화면에 아이디가 나오니 그것을 받아도 됩니다.</div>
<Err>{act.error}</Err>
</>
);
}
function UserTable({ users, superAdmin, onChange }: { users: AppUserRow[]; superAdmin: boolean; onChange: (users: AppUserRow[]) => void }) {
const { state, confirm, toast } = useApp();
const act = useAction();
const name = (id: string | null) => (id ? (users.find((u) => u.id === id)?.name ?? id) : '-');
return (
<>
<div className="table-wrap" style={{ maxHeight: 460 }}>
<table className="table">
<thead>
<tr>
<th>계정</th>
<th>역할</th>
<th>마지막 접속</th>
<th>등록</th>
{superAdmin && <th />}
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id}>
<td>
<div className="row gap">
<Avatar name={u.name} src={u.avatar} size={24} />
<div>
<div>
{u.name}
{u.id === state.account.user?.id && <span className="muted small"> (나)</span>}
</div>
<div className="mono dim small">{u.id}</div>
</div>
</div>
</td>
<td>
{superAdmin && !u.fixed ? (
<Select
width={100}
value={u.role as 'user' | 'admin'}
options={ROLE_OPTIONS}
disabled={act.busy}
onChange={async (r) => {
const res = await act.run(() => gvr.adminSetRole(u.id, r));
if (res) {
onChange(res.users);
toast(`${u.name} → ${ROLE_LABEL[r]}`);
}
}}
/>
) : (
<span className={`role ${u.role}`}>{ROLE_LABEL[u.role]}</span>
)}
</td>
<td className="small">
{u.lastSeenAt ? (
<span title={fmtDate(u.lastSeenAt)}>
{fmtAgo(u.lastSeenAt)}
{u.lastVersion && <span className="dim"> · v{u.lastVersion}</span>}
</span>
) : (
<span className="dim">접속 기록 없음</span>
)}
</td>
<td className="small muted">{u.fixed ? '고정' : `${name(u.addedBy)} · ${u.addedAt ? fmtDate(u.addedAt) : '-'}`}</td>
{superAdmin && (
<td className="r">
{!u.fixed && (
<Btn
small
danger
disabled={act.busy}
onClick={async () => {
if (!(await confirm(`${u.name} (${u.id}) 등록을 해제할까요? 이 사람의 겜녹이는 다음 확인 때(최대 10분) 바로 잠깁니다.`, { ok: '등록 해제', danger: true }))) return;
const res = await act.run(() => gvr.adminRemoveUser(u.id));
if (res) {
onChange(res.users);
toast(`${u.name} 등록 해제`);
}
}}
>
해제
</Btn>
)}
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
<Err>{act.error}</Err>
</>
);
}
/** 표시 이름: 실명이 들어간 디스코드 이름 · 서버 별명 대신 사이트 · 녹음 기록 · 범인 분석에 쓸 이름 */
function DisplayNames({ superAdmin }: { superAdmin: boolean }) {
const { toast } = useApp();
const list = useLoad(() => gvr.adminDisplayNames());
const [id, setId] = useState('');
const [name, setName] = useState('');
const act = useAction();
const valid = /^\d{17,20}$/.test(id.trim()) && !!name.trim();
const save = async (uid: string, n: string) => {
const r = await act.run(() => gvr.adminSetDisplayName(uid, n));
if (r) {
list.setData(r);
toast(n ? `${uid} → ${n}` : `${uid} 표시 이름 지움`);
setId('');
setName('');
}
};
const rows = Object.entries(list.data ?? {});
return (
<>
{superAdmin && (
<div className="field">
<input className="input mono" value={id} placeholder="디스코드 아이디" spellCheck={false} onChange={(e) => setId(e.target.value.replace(/\s/g, ''))} />
<input className="input" value={name} placeholder="보일 이름" maxLength={32} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && valid && void save(id.trim(), name.trim())} />
<Btn primary disabled={!valid} busy={act.busy} onClick={() => save(id.trim(), name.trim())}>
저장
</Btn>
</div>
)}
{list.loading && !list.data ? (
<Spinner />
) : list.error ? (
<Err>{list.error}</Err>
) : rows.length ? (
<table className="table">
<tbody>
{rows.map(([uid, n]) => (
<tr key={uid}>
<td className="mono small">{uid}</td>
<td>{n}</td>
{superAdmin && (
<td className="r">
<Btn small ghost disabled={act.busy} onClick={() => save(uid, '')}>
지우기
</Btn>
</td>
)}
</tr>
))}
</tbody>
</table>
) : (
<div className="muted">정해 둔 표시 이름이 없습니다. 디스코드 이름(서버 별명)이 그대로 보입니다.</div>
)}
<div className="hint">디스코드 이름이나 서버 별명에 실명이 들어 있으면 여기서 다른 이름을 정해 주세요. 사이트, 녹음 기록, 범인 분석에 이 이름만 쓰고 이미 저장된 기록의 이름도 바꿉니다.</div>
<Err>{act.error}</Err>
</>
);
}
export function AdminTab() {
const { state } = useApp();
const superAdmin = state.account.role === 'superadmin';
const list = useLoad(() => gvr.adminUsers());
const users = list.data?.users ?? [];
const set = (u: AppUserRow[]) => list.setData({ users: u });
return (
<Page
title="관리자"
desc={
<>
겜녹이는 등록된 디스코드 계정으로 로그인해야 쓸 수 있습니다. 유저 등록 · 역할 변경은 <b>최고 관리자</b>만, 목록 보기와 관리자 전용 설정은 <b>관리자</b>도 할 수 있습니다.
{state.account.offline && <span className="t-warn"> 지금은 사이트 서버에 연결되지 않아 목록을 불러오지 못할 수 있습니다.</span>}
</>
}
>
<Section title="유저 등록" sub="최고 관리자만">
{superAdmin ? <AddUser onDone={set} /> : <div className="lock-note">🔒 유저 등록 · 역할 변경 · 등록 해제는 최고 관리자만 할 수 있습니다. 아래 목록은 볼 수 있습니다.</div>}
</Section>
<Section
title={`등록된 계정 ${users.length ? `${users.length}명` : ''}`}
right={
<Btn small ghost onClick={list.reload}>
새로고침
</Btn>
}
>
{list.loading && !list.data ? <Spinner /> : list.error ? <Err>{list.error}</Err> : <UserTable users={users} superAdmin={superAdmin} onChange={set} />}
</Section>
<Section title="표시 이름 (실명 숨기기)" sub="바꾸기는 최고 관리자만">
<DisplayNames superAdmin={superAdmin} />
</Section>
<Section title="관리자 전용 기능" sub="일반 유저 화면에서는 잠겨 있습니다">
<ul className="admin-list">
{ADMIN_FEATURES.map((f) => (
<li key={f.what}>
<span>🔒</span>
<a href={`#/settings/${f.tab}`}>{f.what}</a>
<span className="muted">· {f.why}</span>
</li>
))}
</ul>
</Section>
</Page>
);
}

View File

@@ -1,8 +1,8 @@
import { useEffect, useRef, useState } from 'react';
import type { GvrApi } from '../../main/api-types';
import { gvr, useAction, useApp, useLoad } from '../store';
import { Avatar, Btn, DraftInput, Err, Line, Ok, Page, Section, Select, ToggleLine } from '../ui';
import { fmtClock, fmtDuration } from '../util';
import { AdminOnly, Avatar, Btn, DraftInput, Err, Line, Ok, Page, Section, Select, Slider, ToggleLine, useIsAdmin } from '../ui';
import { errMsg, fmtClock, fmtDuration } from '../util';
type TestResult = Awaited<ReturnType<GvrApi['testBotToken']>>;
@@ -12,15 +12,24 @@ export const VOICES = [
{ value: 'ko-KR-HyunsuMultilingualNeural', label: '현수 · 남성 2' },
];
/** 봇 토큰 입력 + 연결 테스트 (+ 저장). 마법사에서는 테스트 성공 시 바로 저장한다. */
/** 봇 선택(겜녹이 기본 봇 / 다른 봇) + 연결 테스트. 다른 봇은 토큰 입력 · 저장. 마법사에서는 테스트 성공 시 바로 저장한다. */
export function BotTokenSection({ wizard, onResult }: { wizard?: boolean; onResult?: (r: TestResult) => void }) {
const { state, toast } = useApp();
const { state, settings, save, toast } = useApp();
const admin = useIsAdmin();
const mode = settings.discord.botMode;
const custom = mode === 'custom';
const [token, setToken] = useState('');
const [show, setShow] = useState(false);
const [result, setResult] = useState<TestResult | null>(null);
const test = useAction();
const [testing, setTesting] = useState(false);
const [testError, setTestError] = useState<string | null>(null);
const saver = useAction();
const report = (r: TestResult) => {
setResult(r);
onResult?.(r);
};
const saveToken = async (t: string) => {
const r = await saver.run(async () => {
await gvr.setSecret('botToken', t);
@@ -32,52 +41,137 @@ export function BotTokenSection({ wizard, onResult }: { wizard?: boolean; onResu
}
};
// 연결 테스트 요청 번호. 봇을 바꾸거나 새 테스트를 시작하면 올라가고, 늦게 온 이전 응답(결과 · 오류 · 진행 표시)은 버린다
const testSeq = useRef(0);
const cancelTest = () => {
testSeq.current++;
setTesting(false);
setTestError(null);
};
const testBot = async (t?: string): Promise<TestResult | undefined> => {
const id = ++testSeq.current;
setTesting(true);
setTestError(null);
try {
const r = await gvr.testBotToken(t);
if (id !== testSeq.current) return undefined;
if (!r.ok) setTestError(r.error ?? '실패했습니다');
return r;
} catch (e) {
if (id === testSeq.current) setTestError(errMsg(e));
return undefined;
} finally {
if (id === testSeq.current) setTesting(false);
}
};
const runTest = async () => {
const t = token.trim();
const r = await test.run(() => gvr.testBotToken(t || undefined));
const t = custom ? token.trim() : '';
const r = await testBot(t || undefined);
if (!r) return;
setResult(r);
onResult?.(r);
report(r);
if (r.ok && wizard && t) await saveToken(t);
};
// 봇 바꾸기: 모드를 저장하고 봇을 새 토큰으로 다시 띄운다 (다른 봇인데 토큰이 아직 없으면 봇은 꺼진 채로 둔다)
const switchMode = async (m: 'builtin' | 'custom') => {
if (m === mode || saver.busy) return;
cancelTest();
setResult(null);
setToken('');
onResult?.({ ok: false });
const r = await saver.run(async () => {
await save({ discord: { botMode: m } });
const res = await gvr.restartBot();
// 다른 봇인데 토큰을 아직 안 넣었으면 봇이 꺼진 채인 게 정상이다 (오류로 보이지 않게)
return m === 'custom' && !state.secrets.botToken ? { ok: true as const } : res;
});
if (m === 'builtin') {
if (r?.ok) toast('겜녹이 봇으로 연결');
const t = await testBot();
if (t) report(t);
} else if (state.secrets.botToken) {
if (r?.ok) toast('저장된 다른 봇으로 연결');
}
};
// 마법사에서 겜녹이 봇이면 들어오자마자 연결을 확인해 서버 목록을 채운다
const autoTested = useRef(false);
useEffect(() => {
if (!wizard || custom || !state.builtinBot || autoTested.current) return;
autoTested.current = true;
void runTest();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [wizard, custom, state.builtinBot]);
const bot = state.bot;
const inviteId = result?.ok ? result.bot?.id : bot.user?.id;
return (
<Section title="봇 연결">
<div className="lab">봇 토큰 (암호화 저장)</div>
<div className="field">
<input
className="input mono"
type={show ? 'text' : 'password'}
value={token}
spellCheck={false}
autoComplete="off"
placeholder={state.secrets.botToken ? '저장된 토큰 사용 중 · 바꾸려면 새 토큰 입력' : 'Discord Developer Portal → Bot → Reset Token 으로 받은 토큰'}
onChange={(e) => {
setToken(e.target.value);
setResult(null);
}}
onKeyDown={(e) => e.key === 'Enter' && void runTest()}
/>
<button type="button" className="btn icon" title={show ? '가리기' : '보기'} onClick={() => setShow(!show)}>
{show ? '🙈' : '👁'}
<div className="radio">
<button type="button" className={!custom ? 'on' : ''} disabled={saver.busy || (!admin && custom)} onClick={() => switchMode('builtin')}>
<b>🤖 겜녹이 봇으로 진행 {!custom && '✓'}</b>
<span className="muted">{state.builtinBot ? '기본값 · 사이트 서버를 거쳐 바로 연결' : '로그인해야 쓸 수 있습니다'}</span>
</button>
<button type="button" className={custom ? 'on' : ''} disabled={saver.busy || !admin} onClick={() => switchMode('custom')} title={admin ? undefined : '관리자만 바꿀 수 있습니다'}>
<b>🔑 다른 봇으로 진행하기 {custom && '✓'}</b>
<span className="muted">{admin ? '직접 만든 봇의 토큰을 넣어서 사용' : '🔒 관리자만 바꿀 수 있습니다'}</span>
</button>
{!wizard && token.trim() && (
<Btn onClick={() => saveToken(token.trim())} busy={saver.busy}>
저장
</Btn>
)}
<Btn primary onClick={runTest} busy={test.busy} disabled={!token.trim() && !state.secrets.botToken}>
연결 테스트
</Btn>
</div>
{custom && admin && (
<>
<div className="lab">봇 토큰 (암호화 저장)</div>
<div className="field">
<input
className="input mono"
type={show ? 'text' : 'password'}
value={token}
spellCheck={false}
autoComplete="off"
placeholder={state.secrets.botToken ? '저장된 토큰 사용 중 · 바꾸려면 새 토큰 입력' : 'Discord Developer Portal → Bot → Reset Token 으로 받은 토큰'}
onChange={(e) => {
setToken(e.target.value);
setResult(null);
}}
onKeyDown={(e) => e.key === 'Enter' && void runTest()}
/>
<button type="button" className="btn icon" title={show ? '가리기' : '보기'} onClick={() => setShow(!show)}>
{show ? '🙈' : '👁'}
</button>
{!wizard && token.trim() && (
<Btn onClick={() => saveToken(token.trim())} busy={saver.busy}>
저장
</Btn>
)}
<Btn primary onClick={runTest} busy={testing} disabled={!token.trim() && !state.secrets.botToken}>
연결 테스트
</Btn>
</div>
</>
)}
{!custom && (
<div className="field">
<Btn primary onClick={runTest} busy={testing || saver.busy} disabled={!state.builtinBot}>
연결 확인
</Btn>
{inviteId && (
<a
href="#"
className="small"
onClick={(e) => (e.preventDefault(), void gvr.openExternal(`https://discord.com/oauth2/authorize?client_id=${inviteId}&scope=bot%20applications.commands&permissions=3148800`))}
>
내 서버에 겜녹이 초대 ↗
</a>
)}
</div>
)}
<div className="result">
{test.error || saver.error ? (
<Err>{test.error || saver.error}</Err>
{testError || saver.error ? (
<Err>{testError || saver.error}</Err>
) : result ? (
result.ok ? (
<Ok>
연결 성공 · {result.bot?.name} · 서버 {result.guilds?.length ?? 0}곳{token.trim() && !wizard ? ' · 저장을 눌러야 적용됩니다' : ''}
연결 성공 · {result.bot?.name} · 서버 {result.guilds?.length ?? 0}곳{custom && token.trim() && !wizard ? ' · 저장을 눌러야 적용됩니다' : ''}
</Ok>
) : (
<Err>{result.error ?? '연결 실패'}</Err>
@@ -91,7 +185,7 @@ export function BotTokenSection({ wizard, onResult }: { wizard?: boolean; onResu
) : bot.status === 'error' ? (
<Err>{bot.error ?? '봇 연결 오류'}</Err>
) : (
<div className="muted">봇이 연결되지 않았습니다. 토큰을 넣고 연결 테스트를 눌러 주세요.</div>
<div className="muted">{custom ? '봇이 연결되지 않았습니다. 토큰을 넣고 연결 테스트를 눌러 주세요.' : '봇이 연결되지 않았습니다. 연결 확인을 눌러 주세요.'}</div>
)}
</div>
</Section>
@@ -126,13 +220,20 @@ export function GuildFollow({ guilds, compact }: { guilds?: { id: string; name:
disabled={!d.guildId || members.loading}
options={[
{ value: '', label: members.loading && d.guildId ? '불러오는 중…' : '선택 안 함' },
...people.map((m) => ({ value: m.id, label: m.name })),
...people.map((m) => ({ value: m.id, label: m.me ? `${m.name} (나)` : m.admin ? `${m.name} · 관리자` : m.name })),
...(d.followUserId && !people.some((p) => p.id === d.followUserId) && !members.loading ? [{ value: d.followUserId, label: `(알 수 없음 ${d.followUserId})` }] : []),
]}
onChange={(v) => save({ discord: { followUserId: v || null } })}
/>
</Line>
{members.error && <Err>{members.error}</Err>}
{members.error && (
<Err>
멤버 목록을 불러오지 못했습니다: {members.error}{' '}
<Btn small onClick={() => void members.reload()}>
다시 불러오기
</Btn>
</Err>
)}
</div>
);
}
@@ -147,7 +248,7 @@ function TtsPreview() {
<Btn
busy={act.busy}
onClick={async () => {
const r = await act.run(() => gvr.previewTts(settings.discord.ttsText, settings.discord.ttsVoice));
const r = await act.run(() => gvr.previewTts(settings.discord.ttsText, settings.discord.ttsVoice, settings.discord.ttsRate));
if (r?.ok && r.dataUrl) {
audio.current?.pause();
audio.current = new Audio(r.dataUrl);
@@ -221,17 +322,24 @@ export function DiscordTab() {
</div>
</Section>
<Section title="녹음 안내 (TTS 음성) · 개인정보">
<ToggleLine label="봇이 음성채널에 들어가면 TTS로 녹음 사실 안내" on={d.ttsEnabled} onChange={(v) => save({ discord: { ttsEnabled: v } })} />
<ToggleLine label="새 사람이 들어오면 다시 안내" on={d.ttsOnNewMember} disabled={!d.ttsEnabled} onChange={(v) => save({ discord: { ttsOnNewMember: v } })} />
<Line label="안내 문구">
<div className="tts-text">
<DraftInput multiline value={d.ttsText} onCommit={(v) => save({ discord: { ttsText: v } })} />
</div>
<AdminOnly note="녹음 안내를 끄거나 문구를 바꾸는 것은 관리자만 할 수 있습니다">
<ToggleLine label="봇이 음성채널에 들어가면 TTS로 녹음 사실 안내" on={d.ttsEnabled} onChange={(v) => save({ discord: { ttsEnabled: v } })} />
<ToggleLine label="새 사람이 들어오면 다시 안내" on={d.ttsOnNewMember} disabled={!d.ttsEnabled} onChange={(v) => save({ discord: { ttsOnNewMember: v } })} />
<Line label="안내 문구">
<div className="tts-text">
<DraftInput multiline value={d.ttsText} onCommit={(v) => save({ discord: { ttsText: v } })} />
</div>
</Line>
</AdminOnly>
<Line label="안내 미리듣기">
<TtsPreview />
</Line>
<Line label="목소리">
<Select width={200} value={d.ttsVoice} options={VOICES} onChange={(v) => save({ discord: { ttsVoice: v } })} />
</Line>
<Line label="말 속도" hint="0.1배(아주 느리게) ~ 2.0배(빠르게), 보통 1.0배">
<Slider value={d.ttsRate ?? 1} min={0.1} max={2} step={0.1} fmt={(v) => `${v.toFixed(1)}배`} onCommit={(v) => save({ discord: { ttsRate: Math.round(v * 10) / 10 } })} />
</Line>
<Line
label={
<>

View File

@@ -1,7 +1,7 @@
import { useState } from 'react';
import type { User } from '@gvr/shared';
import { GAME_NAME, liveGameRows, type LiveGame, type User } from '@gvr/shared';
import { gvr, useAction, useApp, useLoad } from '../store';
import { Avatar, Btn, Dot, Err, FolderRow, Line, NumInput, Page, Section, Spinner, Toggle, ToggleLine } from '../ui';
import { Avatar, Btn, Dot, Err, FolderRow, Page, Section, Spinner, Toggle } from '../ui';
/** 발로란트 / 롤 켜기 카드 (마법사에서도 사용) */
export function GameCards({ showStatus = true }: { showStatus?: boolean }) {
@@ -9,7 +9,7 @@ export function GameCards({ showStatus = true }: { showStatus?: boolean }) {
const g = settings.games;
const cards = [
{ id: 'valorant' as const, name: 'VALORANT', ko: '발로란트', desc: '라운드 · 킬 · 스파이크 이벤트와 대화를 함께 기록', on: g.valorant, st: state.games.valorant },
{ id: 'lol' as const, name: 'League of Legends', ko: '리그 오브 레전드', desc: '킬 · 오브젝트 · 채팅(OCR)과 대화를 함께 기록', on: g.lol, st: state.games.lol },
{ id: 'lol' as const, name: 'League of Legends', ko: '리그 오브 레전드', desc: '킬 · 오브젝트 · 채팅(API)과 대화를 함께 기록', on: g.lol, st: state.games.lol },
];
return (
<div className="games">
@@ -52,6 +52,38 @@ export function GameCards({ showStatus = true }: { showStatus?: boolean }) {
);
}
/** 지금 연결된 게임 · 진행 중인 경기 자세히 (v1.3.6~) */
function LiveGames() {
const { state } = useApp();
const live = state.liveGames ?? [];
if (!live.length) return null;
return (
<Section title="지금 게임" sub="2초마다 새로 고침">
<div className="live-games">
{live.map((g: LiveGame) => (
<div key={g.game} className={`live-game ${g.game}${g.inMatch ? ' in-match' : ''}`}>
<div className="live-game-top">
<Dot tone={!g.enabled ? 'off' : g.inMatch ? 'ok' : g.connected ? 'warn' : 'off'} />
<b>{GAME_NAME[g.game]}</b>
<span className={`badge ${g.inMatch ? 'b-ok' : 'b-dim'}`}>{g.phase}</span>
</div>
<table className="live-rows">
<tbody>
{liveGameRows(g).map(([k, v]) => (
<tr key={k}>
<td className="muted">{k}</td>
<td>{v}</td>
</tr>
))}
</tbody>
</table>
</div>
))}
</div>
</Section>
);
}
const RIOT_RE = /^[^#]{1,16}#[^#\s]{2,5}$/;
function RiotRow({ u }: { u: User }) {
@@ -143,23 +175,15 @@ export function GamesTab() {
const { settings, save } = useApp();
const g = settings.games;
const users = useLoad(() => gvr.users());
const region = g.lolOcrRegion;
return (
<Page title="게임 연동">
<GameCards />
<LiveGames />
<Section title="리그 오브 레전드 세부 설정" className={g.lol ? '' : 'disabled'}>
<ToggleLine label="롤 채팅 OCR" hint="게임 옵션에서 채팅 타임스탬프를 켜고 '테두리 없음' 창 모드를 쓰면 정확합니다" on={g.lolChatOcr} onChange={(v) => save({ games: { lolChatOcr: v } })} />
<Line label="채팅 영역" hint="화면 크기에 대한 비율 (0~1) · 왼쪽 아래 채팅창 기본값">
<div className="region">
{(['x', 'y', 'w', 'h'] as const).map((k) => (
<label key={k}>
<span className="muted mono">{k}</span>
<NumInput value={region[k]} min={0} max={1} step={0.01} width={70} onCommit={(n) => save({ games: { lolOcrRegion: { ...region, [k]: n } } })} />
</label>
))}
</div>
</Line>
<div className="lab" style={{ marginTop: 8 }}>
<div className="muted" style={{ marginBottom: 8 }}>
롤 채팅은 롤 클라이언트(LCU) API 로 챔피언 선택 · 게임 후 채팅을 받습니다. 게임 중 전체 · 팀 채팅은 롤이 API 로 주지 않아, 게임 로그 파일에 남아 있을 때만 경기 뒤에 붙입니다. 화면 글자 인식(OCR)은 쓰지 않습니다.
</div>
<div className="lab">
롤 로그 폴더 <span className="dim">(비워 두면 Riot Games 기본 위치에서 찾습니다)</span>
</div>
<FolderRow

View File

@@ -1,6 +1,7 @@
import { ROLE_LABEL } from '../../core/roles';
import icon from '../assets/icon.png';
import { gvr, useAction, useApp, useLoad } from '../store';
import { Btn, Err, Line, Page, Section, Spinner, Toggle, ToggleLine } from '../ui';
import { Avatar, Btn, Err, Line, Page, Section, Spinner, Toggle, ToggleLine } from '../ui';
const SITE = 'https://gvr.tkrmagid.kr';
@@ -8,8 +9,33 @@ export function GeneralTab() {
const { state, settings, save, confirm, toast } = useApp();
const logs = useLoad(() => gvr.recentLogs());
const auto = useAction();
const acc = state.account;
return (
<Page title="일반">
<Section title="계정">
<div className="row gap">
{acc.user && <Avatar name={acc.user.name} src={acc.user.avatar} size={32} />}
<div className="grow">
<div>
{acc.user?.name ?? '-'} {acc.role && <span className={`role ${acc.role}`}>{ROLE_LABEL[acc.role]}</span>}
</div>
<div className="mono dim small">
{acc.user?.id}
{acc.offline && <span className="t-warn"> · 사이트 서버에 연결되지 않아 마지막 확인 결과로 사용 중</span>}
</div>
</div>
<Btn
onClick={async () => {
if (await confirm('로그아웃할까요? 봇 · 녹음 · 사이트 연결이 멈추고, 다시 로그인해야 쓸 수 있습니다.', { ok: '로그아웃', danger: true })) await gvr.authLogout();
}}
>
로그아웃
</Btn>
</div>
<div className="hint" style={{ marginTop: 8 }}>
디스코드 계정으로 로그인했습니다. 10분마다 등록 여부를 다시 확인하며, 등록이 해제되면 바로 잠깁니다. 사이트 서버에 연결되지 않으면 마지막 확인 뒤 3일까지는 그대로 쓸 수 있습니다.
</div>
</Section>
<Section title="실행">
<Line label="윈도우 시작 시 자동 실행" hint="사이트를 계속 열어 두려면 권장">
<Toggle

View File

@@ -1,6 +1,6 @@
import { useState } from 'react';
import { gvr, useAction, useApp, useLoad } from '../store';
import { Btn, DraftInput, Err, FolderRow, Line, NumInput, Ok, Page, Section, Spinner } from '../ui';
import { AdminOnly, Btn, DraftInput, Err, FolderRow, Line, NumInput, Ok, Page, Section, Spinner, useIsAdmin } from '../ui';
import { fmtBytes, fmtDate } from '../util';
/** 녹음 폴더 + 보관 기간 (마법사에서도 사용) */
@@ -19,20 +19,24 @@ export function AudioStorage() {
}}
onReset={() => save({ storage: { audioDir: null } })}
/>
<Line label="음성 보관 기간" hint="지나면 음성 파일만 삭제, 텍스트 · 경기 기록은 보관">
<NumInput value={st.retentionDays} min={1} max={365} width={70} suffix="일" onCommit={(n) => save({ storage: { retentionDays: Math.round(n) } })} />
</Line>
<AdminOnly note="음성 보관 기간은 관리자만 바꿀 수 있습니다">
<Line label="음성 보관 기간" hint="지나면 음성 파일만 삭제, 텍스트 · 경기 기록은 보관">
<NumInput value={st.retentionDays} min={1} max={365} width={70} suffix="일" onCommit={(n) => save({ storage: { retentionDays: Math.round(n) } })} />
</Line>
</AdminOnly>
</>
);
}
/** 사이트 등록 코드 입력 (마법사에서도 사용) */
export function RegisterDevice() {
export function RegisterDevice({ quiet }: { quiet?: boolean }) {
const { state, settings, toast } = useApp();
const [code, setCode] = useState('');
const act = useAction();
const admin = useIsAdmin();
const registered = !!settings.site.deviceId && state.secrets.deviceKey;
if (registered) return null;
if (!admin) return quiet ? null : <div className="lock-note">🔒 사이트 등록은 관리자만 할 수 있습니다. 필요하면 관리자에게 요청해 주세요.</div>;
return (
<>
<div className="field">
@@ -127,6 +131,7 @@ function Usage() {
export function StorageTab() {
const { state, settings, save, confirm, toast } = useApp();
const admin = useIsAdmin();
const site = settings.site;
const relay = state.relay;
const registered = !!site.deviceId && state.secrets.deviceKey;
@@ -141,18 +146,20 @@ export function StorageTab() {
</Section>
<Usage />
<Section title="사이트 서버" sub="이 PC가 사이트로 연결을 열어 둡니다 (포트 개방 불필요)">
<Line label="서버 주소">
<DraftInput mono value={site.serverUrl} onCommit={(v) => save({ site: { serverUrl: v.trim() } })} className="w320" />
</Line>
<Line label="이 PC 이름" hint="사이트에 보이는 이름">
<DraftInput value={site.deviceName} onCommit={(v) => save({ site: { deviceName: v.trim() || 'GAME-PC' } })} className="w320" />
</Line>
<AdminOnly note="사이트 서버 설정은 관리자만 바꿀 수 있습니다">
<Line label="서버 주소">
<DraftInput mono value={site.serverUrl} onCommit={(v) => save({ site: { serverUrl: v.trim() } })} className="w320" />
</Line>
<Line label="이 PC 이름" hint="사이트에 보이는 이름">
<DraftInput value={site.deviceName} onCommit={(v) => save({ site: { deviceName: v.trim() || 'GAME-PC' } })} className="w320" />
</Line>
</AdminOnly>
<div className={`relay ${relay.state}`}>
<span className={`dot ${relay.state === 'online' ? 'ok' : relay.state === 'connecting' ? 'warn' : relay.state === 'error' ? 'err' : 'off'}`} />
<b>{relayText}</b>
{registered && <span className="muted mono small">기기 ID {site.deviceId}</span>}
<span className="grow" />
{registered && (
{registered && admin && (
<Btn
small
busy={unreg.busy}
@@ -165,22 +172,24 @@ export function StorageTab() {
</Btn>
)}
</div>
<RegisterDevice />
<RegisterDevice quiet />
<Err>{unreg.error}</Err>
</Section>
<Section title="학습 데이터">
<Line label="학습 데이터 전체 삭제" hint="교정한 문장의 음성 조각과 합성 음성을 지웁니다. 대화 기록과 모델은 남습니다">
<Btn
danger
busy={clear.busy}
onClick={async () => {
if (!(await confirm('학습 데이터를 모두 지울까요? 되돌릴 수 없습니다.', { ok: '전체 삭제', danger: true }))) return;
if (await clear.runOk(() => gvr.clearTrainingData())) toast('학습 데이터 삭제됨');
}}
>
전체 삭제
</Btn>
</Line>
<AdminOnly>
<Line label="학습 데이터 전체 삭제" hint="교정한 문장의 음성 조각과 합성 음성을 지웁니다. 대화 기록과 모델은 남습니다">
<Btn
danger
busy={clear.busy}
onClick={async () => {
if (!(await confirm('학습 데이터를 모두 지울까요? 되돌릴 수 없습니다.', { ok: '전체 삭제', danger: true }))) return;
if (await clear.runOk(() => gvr.clearTrainingData())) toast('학습 데이터 삭제됨');
}}
>
전체 삭제
</Btn>
</Line>
</AdminOnly>
<Err>{clear.error}</Err>
</Section>
</Page>

View File

@@ -3,7 +3,7 @@ import type { FinetuneStatus } from '../../main/api-types';
import { CARD_MODELS, COMPUTE_TYPES } from '../models-meta';
import { DownloadRow, GpuCard, ModelCard, useSttData, type ModelRole } from '../stt-parts';
import { gvr, useAction, useApp } from '../store';
import { Bar, Btn, Err, FolderRow, Line, NumInput, Page, Section, Select, Spinner, ToggleLine } from '../ui';
import { AdminOnly, Bar, Btn, Err, FolderRow, Line, NumInput, Page, Section, Select, Spinner, ToggleLine } from '../ui';
import { fmtDate, fmtMb } from '../util';
const SLOT_TEXT: Record<string, string> = { empty: '대기', loading: '불러오는 중', loaded: '사용 중', missing: '파일 없음', error: '오류' };
@@ -77,38 +77,40 @@ function Finetune() {
<Bar pct={st.step !== null && st.total ? (st.step / st.total) * 100 : 5} color="linear-gradient(90deg,#14c1b7,#5fe0d8)" />
</div>
)}
<div className="row wrap gap">
{!st.toolsInstalled && (
<Btn primary busy={st.installing} onClick={() => call(() => gvr.finetuneInstall(), '학습 도구 설치 시작')}>
학습 도구 설치 (약 3GB)
<AdminOnly note="파인튜닝은 관리자만 할 수 있습니다">
<div className="row wrap gap">
{!st.toolsInstalled && (
<Btn primary busy={st.installing} onClick={() => call(() => gvr.finetuneInstall(), '학습 도구 설치 시작')}>
학습 도구 설치 (약 3GB)
</Btn>
)}
<Btn primary={st.toolsInstalled} disabled={!st.toolsInstalled || st.running} onClick={() => call(() => gvr.finetuneStart(), '학습 시작')}>
지금 학습
</Btn>
)}
<Btn primary={st.toolsInstalled} disabled={!st.toolsInstalled || st.running} onClick={() => call(() => gvr.finetuneStart(), '학습 시작')}>
지금 학습
</Btn>
<Btn disabled={!st.running} onClick={() => call(() => gvr.finetuneStop(), '학습 중지')}>
중지
</Btn>
<Btn
disabled={!st.previousModel || st.running}
onClick={async () => {
if (await confirm(`이전 모델(${st.previousModel})로 되돌릴까요?`, { ok: '되돌리기' })) await call(() => gvr.finetuneRollback(), '이전 모델로 되돌림');
}}
>
이전 모델로 되돌리기
</Btn>
<span className="grow" />
<span className="muted small">자동 학습</span>
<Select
width={190}
value={settings.finetune.schedule}
options={[
{ value: 'off', label: '끔' },
{ value: 'nightly', label: '매일 새벽 자동' },
]}
onChange={(v) => save({ finetune: { schedule: v } })}
/>
</div>
<Btn disabled={!st.running} onClick={() => call(() => gvr.finetuneStop(), '학습 중지')}>
중지
</Btn>
<Btn
disabled={!st.previousModel || st.running}
onClick={async () => {
if (await confirm(`이전 모델(${st.previousModel})로 되돌릴까요?`, { ok: '되돌리기' })) await call(() => gvr.finetuneRollback(), '이전 모델로 되돌림');
}}
>
이전 모델로 되돌리기
</Btn>
<span className="grow" />
<span className="muted small">자동 학습</span>
<Select
width={190}
value={settings.finetune.schedule}
options={[
{ value: 'off', label: '끔' },
{ value: 'nightly', label: '매일 새벽 자동' },
]}
onChange={(v) => save({ finetune: { schedule: v } })}
/>
</div>
</AdminOnly>
<Err>{act.error}</Err>
<div className="hint" style={{ marginTop: 8 }}>
게임이 켜지면 학습을 바로 멈춥니다. 학습 전후 같은 검증 문장의 오류율(CER)이 좋아졌을 때만 새 모델로 바꿉니다.

View File

@@ -1,6 +1,7 @@
// 공용 UI 조각
import { useState, type ReactNode } from 'react';
import { useDraft } from './store';
import { isAdminRole } from '../core/roles';
import { useApp, useDraft } from './store';
import { errMsg } from './util';
export function Page({ title, desc, children }: { title: string; desc?: ReactNode; children: ReactNode }) {
@@ -226,3 +227,20 @@ export function FolderRow({ path, placeholder, onChoose, onReset }: { path: stri
</div>
);
}
/** 로그인한 계정이 관리자(최고 관리자 포함)인지 */
export function useIsAdmin(): boolean {
return isAdminRole(useApp().state.account.role);
}
/** 관리자 전용 설정: 일반 유저에게는 잠근 채로 보여 준다 (실제 차단은 메인 프로세스가 한다) */
export function AdminOnly({ children, note = '관리자만 바꿀 수 있습니다' }: { children: ReactNode; note?: ReactNode }) {
const admin = useIsAdmin();
if (admin) return <>{children}</>;
return (
<fieldset className="admin-lock" disabled>
{note && <div className="lock-note">🔒 {note}</div>}
<div className="locked">{children}</div>
</fieldset>
);
}

View File

@@ -13,8 +13,19 @@ export function deepMerge<T>(base: T, over: unknown): T {
}
export function errMsg(e: unknown): string {
if (e instanceof Error) return e.message;
return String(e);
const m = e instanceof Error ? e.message : String(e);
// IPC 오류는 "Error invoking remote method 'gvr:x': Error: 메시지" 로 온다
return m.replace(/^Error invoking remote method '[^']+': (?:\w*Error: )?/, '');
}
/** "3분 전" · "2시간 전" · "4일 전" */
export function fmtAgo(ts: number | null | undefined): string {
if (!ts) return '-';
const s = Math.max(0, (Date.now() - ts) / 1000);
if (s < 60) return '방금';
if (s < 3600) return `${Math.floor(s / 60)}분 전`;
if (s < 86400) return `${Math.floor(s / 3600)}시간 전`;
return `${Math.floor(s / 86400)}일 전`;
}
/** MB → "1.6GB" / "464MB" */

View File

@@ -30,12 +30,16 @@ function Step1({ onTested }: { onTested: (ok: boolean) => void }) {
<Head
title="디스코드 봇 연결"
desc={
<>
Discord Developer Portal에서 만든 봇의 토큰을 넣어 주세요. 봇에는 음성 연결 · 슬래시 명령 권한과 Server Members Intent가 필요합니다.{' '}
<a href="#" onClick={(e) => (e.preventDefault(), void gvr.openExternal('https://discord.com/developers/applications'))}>
포털 열기 ↗
</a>
</>
settings.discord.botMode === 'builtin' ? (
<>기본으로 겜녹이 봇을 씁니다. 토큰을 넣을 필요 없이 바로 연결됩니다. 직접 만든 봇을 쓰려면 '다른 봇으로 진행하기'를 골라 주세요.</>
) : (
<>
Discord Developer Portal에서 만든 봇의 토큰을 넣어 주세요. 봇에는 음성 연결 · 슬래시 명령 권한과 Server Members Intent가 필요합니다.{' '}
<a href="#" onClick={(e) => (e.preventDefault(), void gvr.openExternal('https://discord.com/developers/applications'))}>
포털 열기 ↗
</a>
</>
)
}
/>
<BotTokenSection
@@ -59,7 +63,7 @@ function Step2() {
<>
<Head title="게임 선택" desc="켠 게임의 경기 이벤트(킬 · 라운드 · 오브젝트)를 대화 기록과 같은 시간축에 함께 남깁니다. 나중에 게임 연동 탭에서 바꿀 수 있습니다." />
<GameCards showStatus={false} />
<div className="hint">롤은 채팅 OCR(화면 글자 읽기)도 함께 씁니다. 게임 옵션에서 채팅 타임스탬프를 켜고 '테두리 없음' 창 모드를 쓰면 정확합니다.</div>
<div className="hint">롤 채팅은 롤 클라이언트 API 로 받습니다 (챔피언 선택 · 게임 후 채팅). 화면 글자 인식(OCR)은 쓰지 않습니다.</div>
</>
);
}
@@ -209,10 +213,11 @@ function Step5() {
}
export function Wizard({ step }: { step: number }) {
const { state } = useApp();
const { state, settings } = useApp();
const [tokenOk, setTokenOk] = useState(false);
const finish = useAction();
const canNext1 = tokenOk || (state.secrets.botToken && state.bot.status === 'ready');
const hasToken = settings.discord.botMode === 'builtin' ? state.builtinBot : state.secrets.botToken;
const canNext1 = tokenOk || (hasToken && state.bot.status === 'ready');
const to = (n: number) => go(`#/wizard/${n}`);
return (

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

269
app/test/auth.test.ts Normal file
View File

@@ -0,0 +1,269 @@
// 앱 로그인(core/auth.ts) ↔ 실제 사이트 서버 코드(site/server) 통합 테스트. 디스코드만 가짜.
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 '../../site/server/src/app.ts';
import { AppAuth } from '../src/core/auth.ts';
import { adminOnlyPaths } from '../src/core/roles.ts';
import { SettingsStore } from '../src/core/settings.ts';
const SUPER = '1352267557213573160';
const FRIEND = '111111111111111111';
const STRANGER = '222222222222222222';
const BOT = 'MTExMTExMTExMTExMTExMTEx.FAKE00.server-delivered-token-xxxxxxxx';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-auth-'));
delete process.env.GVR_BOT_TOKEN;
async function fakeDiscord() {
const names: Record<string, string> = { [SUPER]: '관리자', [FRIEND]: '친구', [STRANGER]: '모르는사람' };
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') {
let b = '';
req.on('data', (c) => (b += c));
req.on('end', () => res.end(JSON.stringify({ access_token: new URLSearchParams(b).get('code') })));
return;
}
if (u.pathname === '/users/@me') {
const id = String(req.headers.authorization).replace('Bearer ', '');
return res.end(JSON.stringify({ id, username: names[id], global_name: names[id], avatar: null }));
}
const m = /^\/users\/(\d+)$/.exec(u.pathname);
if (m && names[m[1]!]) return res.end(JSON.stringify({ id: m[1], username: names[m[1]!], global_name: names[m[1]!], avatar: null }));
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 { app } = await buildServer({
port: 0, host: '127.0.0.1', publicUrl: 'http://placeholder', clientId: 'cid', clientSecret: 's', botToken: BOT,
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: dc.url, assetUpstream: {},
});
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
/** 브라우저 흉내: 로그인 주소 → 디스코드(가짜) → 콜백. who = 디스코드에서 로그인한 계정 */
const browser = (who: string) => async (url: string) => {
const start = await fetch(url.replace('http://placeholder', base), { redirect: 'manual' });
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
const cookie = start.headers.getSetCookie()[0]!.split(';')[0]!;
await fetch(`${base}/auth/discord/callback?code=${who}&state=${encodeURIComponent(state)}`, { headers: { cookie }, redirect: 'manual' });
};
const settingsFor = (dir = tmp()) => {
const s = new SettingsStore(dir);
s.update({ site: { serverUrl: base } });
return s;
};
return { base, browser, settingsFor, close: async () => (await app.close(), dc.close()) };
}
test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은 로그인해도 앱에 오지 않는다', async () => {
const s = await stack();
try {
// 로그인 전: 토큰 없음 → 로그인 화면
const st = s.settingsFor();
const auth = new AppAuth(st, { version: '1.2.0', openUrl: s.browser(STRANGER), pollMs: 20 });
assert.equal((await auth.check()).status, 'signed_out');
assert.equal(st.activeBotToken(), null);
// 미등록 아이디 → 등록되지 않은 아이디, 토큰 없음
const r1 = await auth.login();
assert.equal(r1.status, 'not_registered');
assert.equal(r1.user?.id, STRANGER);
assert.equal(st.hasSecret('appToken'), false);
assert.equal(st.activeBotToken(), null);
// 최고 관리자 로그인 → 앱 토큰만 받는다. 봇 토큰은 서버 응답 어디에도 없다
const adminSt = s.settingsFor();
const admin = new AppAuth(adminSt, { version: '1.2.0', openUrl: s.browser(SUPER), pollMs: 20 });
const r2 = await admin.login();
assert.equal(r2.status, 'ok');
assert.equal(r2.role, 'superadmin');
assert.equal(adminSt.hasBuiltinBot, true);
assert.equal(adminSt.activeBotToken(), null);
const me = await (await fetch(`${s.base}/app/me`, { headers: { authorization: `Bearer ${adminSt.getSecret('appToken')}` } })).text();
assert.ok(me.includes(SUPER) && !me.includes(BOT) && !me.includes('botToken'), me);
// 최고 관리자가 친구 등록 (관리자 화면 API)
const list = await admin.adminAddUser(FRIEND, 'user');
assert.ok(list.users.some((u) => u.id === FRIEND && u.role === 'user'));
// 친구 로그인 → 일반 유저
const dir = tmp();
const frSt = s.settingsFor(dir);
const fr = new AppAuth(frSt, { version: '1.2.0', openUrl: s.browser(FRIEND), pollMs: 20 });
const r3 = await fr.login();
assert.equal(r3.status, 'ok');
assert.equal(r3.role, 'user');
assert.equal(frSt.activeBotToken(), null);
await assert.rejects(fr.adminAddUser(STRANGER, 'user'), /최고 관리자만/);
await assert.rejects(fr.adminUsers(), /관리자만/);
// 일반 유저도 관리자 아이디는 받는다 (따라갈 사람 목록 정렬). 유저 자신은 관리자가 아니다
const ids = await fr.adminIds();
assert.ok(ids.includes(SUPER) && !ids.includes(FRIEND));
await admin.adminSetRole(FRIEND, 'admin');
assert.ok((await fr.adminIds()).includes(FRIEND));
await admin.adminSetRole(FRIEND, 'user');
// 표시 이름 (실명 숨기기): 최고 관리자만 정하고, 정하면 서버가 저장한 이름 · 로그인 정보가 모두 그 이름이 된다
await assert.rejects(fr.adminSetDisplayName(FRIEND, '별명'), /최고 관리자만/);
assert.deepEqual((await admin.adminSetDisplayName(FRIEND, '별명')).names, { [FRIEND]: '별명' });
assert.deepEqual(await fr.displayNames(), { [FRIEND]: '별명' });
assert.equal((await fr.check()).user?.name, '별명');
const rows = (await admin.adminUsers()).users;
assert.equal(rows.find((u) => u.id === FRIEND)?.name, '별명');
assert.deepEqual((await admin.adminSetDisplayName(FRIEND, '')).names, {});
// 다시 켜도 (새 SettingsStore) 로그인 유지
assert.equal((await new AppAuth(s.settingsFor(dir), { version: '1.2.0', openUrl: () => undefined }).check()).status, 'ok');
// 봇 토큰은 이 PC 어디에도 저장되지 않는다 (테스트는 평문 codec 이라 secrets.bin 도 그대로 읽힌다)
for (const f of fs.readdirSync(dir)) assert.ok(!fs.readFileSync(path.join(dir, f), 'utf8').includes(BOT), f);
// 등록 해제 → 다음 확인에서 잠기고 앱 토큰을 지운다
await admin.adminRemoveUser(FRIEND);
const r4 = await fr.check();
assert.equal(r4.status, 'not_registered');
assert.equal(r4.user?.id, FRIEND);
assert.equal((await fr.check()).status, 'not_registered', '다시 확인해도 "등록되지 않은 아이디" 화면 유지');
assert.equal(frSt.activeBotToken(), null);
assert.equal(frSt.hasSecret('appToken'), false);
// 로그아웃 → 토큰 삭제, 서버에서도 무효
await admin.logout();
assert.equal(admin.state.status, 'signed_out');
assert.equal(adminSt.hasBuiltinBot, false);
} finally {
await s.close();
}
});
test('앱 로그인: 서버에 못 붙으면 마지막 확인 후 유예 기간까지만 쓴다', async () => {
const s = await stack();
const dir = tmp();
const st = s.settingsFor(dir);
const auth = new AppAuth(st, { version: '1.2.0', openUrl: s.browser(SUPER), pollMs: 20 });
assert.equal((await auth.login()).status, 'ok');
await s.close();
// 서버 꺼짐 → 마지막 확인이 방금이라 오프라인으로 계속
const r = await auth.check();
assert.equal(r.status, 'ok');
assert.equal(r.offline, true);
assert.equal(st.hasSecret('appToken'), true);
// 유예 기간이 지나면 막힌다 (토큰은 남겨 두어 서버가 돌아오면 다시 확인)
const late = new AppAuth(st, { version: '1.2.0', openUrl: () => undefined, offlineGraceMs: 0 });
const r2 = await late.check();
assert.equal(r2.status, 'error');
assert.match(r2.error!, /연결할 수 없습니다/);
assert.equal(st.hasSecret('appToken'), true);
});
test('관리자 전용 설정: 일반 유저가 바꾸면 안 되는 경로만 골라낸다', () => {
assert.deepEqual(adminOnlyPaths({ discord: { botMode: 'custom' } }), ['discord.botMode']);
assert.deepEqual(adminOnlyPaths({ discord: { guildId: 'g', ttsVoice: 'x' }, stt: { realtimeModel: 'small' } }), []);
assert.deepEqual(adminOnlyPaths({ discord: { ttsEnabled: false, ttsText: 'x', ttsVoice: 'y' } }), ['discord.ttsEnabled', 'discord.ttsText']);
assert.deepEqual(adminOnlyPaths({ storage: { retentionDays: 30, audioDir: 'D:/a' } }), ['storage.retentionDays']);
assert.deepEqual(adminOnlyPaths({ site: { deviceName: 'x' } }), ['site']);
assert.deepEqual(adminOnlyPaths({ finetune: { schedule: 'nightly' } }), ['finetune']);
assert.deepEqual(adminOnlyPaths({ firstRunDone: true, general: { sfx: false } }), []);
});
/** /app/me 응답을 서버가 처리한 뒤 앱에 늦게 도착하게 붙잡는다 (hold() 로 다음 요청 하나를 잡고, 반환값으로 놓아준다) */
function holdMe() {
const real = globalThis.fetch;
let gate: { promise: Promise<void>; release: () => void } | null = null;
globalThis.fetch = (async (input: any, init?: any) => {
const r = await real(input, init);
if (gate && String(input).endsWith('/app/me')) {
const g = gate;
gate = null;
await g.promise;
}
return r;
}) as typeof fetch;
return {
hold: () => {
let release!: () => void;
const promise = new Promise<void>((r) => (release = r));
gate = { promise, release };
return release;
},
restore: () => (globalThis.fetch = real),
};
}
test('늦은 확인 응답: 등록 해제로 잠긴 뒤 이전 확인의 200 이 와도 다시 열리지 않는다', async () => {
const s = await stack();
const h = holdMe();
try {
const admin = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(SUPER), pollMs: 20 });
await admin.login();
await admin.adminAddUser(FRIEND, 'user');
const st = s.settingsFor();
const fr = new AppAuth(st, { version: 't', openUrl: s.browser(FRIEND), pollMs: 20 });
assert.equal((await fr.login()).status, 'ok');
// A: 서버는 200 을 줬지만 응답이 늦게 온다
const release = h.hold();
const a = fr.check();
await new Promise((r) => setTimeout(r, 100));
// 그 사이 등록 해제 → B: 403 → 잠김
await admin.adminRemoveUser(FRIEND);
assert.equal((await fr.check()).status, 'not_registered');
// A 의 늦은 200 도착
release();
await a;
assert.equal(fr.state.status, 'not_registered', '늦은 200 이 잠금을 풀면 안 된다');
assert.equal(st.hasSecret('appToken'), false, '지운 앱 토큰이 되살아나면 안 된다');
assert.equal(st.hasSecret('auth'), false);
} finally {
h.restore();
await s.close();
}
});
test('늦은 확인 응답: 로그아웃 뒤 이전 확인의 200 이 와도 다시 열리지 않는다', async () => {
const s = await stack();
const h = holdMe();
try {
const st = s.settingsFor();
const auth = new AppAuth(st, { version: 't', openUrl: s.browser(SUPER), pollMs: 20 });
assert.equal((await auth.login()).status, 'ok');
const release = h.hold();
const a = auth.check();
await new Promise((r) => setTimeout(r, 100));
await auth.logout();
assert.equal(auth.state.status, 'signed_out');
release();
await a;
assert.equal(auth.state.status, 'signed_out', '늦은 200 이 로그아웃을 되돌리면 안 된다');
assert.equal(st.hasSecret('appToken'), false);
assert.equal(st.hasSecret('auth'), false);
} finally {
h.restore();
await s.close();
}
});
test('겹친 확인: 등록 해제 뒤 확인 두 개가 겹쳐도 "로그인 만료"가 아니라 "등록되지 않은 아이디"로 잠긴다', async () => {
// 봇 중계가 끊기며 바로 확인하는 사이 10분 확인 · 다시 확인 버튼이 겹치는 경우. 서버는 첫 403 에서 세션을 지워 뒤 확인은 401 을 받는다
const s = await stack();
try {
const admin = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(SUPER), pollMs: 20 });
await admin.login();
await admin.adminAddUser(FRIEND, 'user');
const fr = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(FRIEND), pollMs: 20 });
assert.equal((await fr.login()).status, 'ok');
await admin.adminRemoveUser(FRIEND);
await Promise.all([fr.check(), fr.check()]);
assert.equal(fr.state.status, 'not_registered');
assert.equal(fr.state.user?.id, FRIEND);
} finally {
await s.close();
}
});

View File

@@ -0,0 +1,413 @@
// 겜녹이 봇 중계: 앱 RemoteGateway ↔ 실제 사이트 서버 코드(BotBroker). 디스코드 게이트웨이만 가짜(FakeSource).
// 핵심: 봇 토큰은 서버 밖으로 나가지 않고, 앱은 지켜보는 서버의 음성 참여 · 나가기만 요청할 수 있다
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import type { BotGwChannel, BotGwGuild, BotGwMember } from '@gvr/shared';
import { buildServer } from '../../site/server/src/app.ts';
import type { BotCommand, BotSource } from '../../site/server/src/bot-broker.ts';
import { AppAuth } from '../src/core/auth.ts';
import { RemoteGateway } from '../src/core/discord/gateway.ts';
import { SettingsStore } from '../src/core/settings.ts';
const SUPER = '1352267557213573160';
const FRIEND = '111111111111111111';
const BOT = 'MTExMTExMTExMTExMTExMTEx.FAKE00.server-only-bot-token-xxxxxxxxx';
const G = '900000000000000001';
const OTHER_G = '900000000000000002';
const VC1 = '910000000000000001';
const VC2 = '910000000000000002';
const TEXT = '910000000000000009';
/** 최고 관리자만 볼 수 있는 비공개 음성채널 */
const PRIV = '910000000000000003';
/** 모두 볼 수 있지만 최고 관리자만 들어갈 수 있는 음성채널 */
const LOCKED = '910000000000000004';
const OTHER_VC = '920000000000000001';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-botgw-'));
delete process.env.GVR_BOT_TOKEN;
const m = (id: string, name: string, bot = false): BotGwMember => ({ id, name, avatar: null, bot });
const ME = m('800000000000000001', '겜녹이', true);
class FakeSource extends EventEmitter implements BotSource {
sent: { guildId: string; payload: any }[] = [];
handlers = new Map<string, { server: (d: any) => void; state: (d: any) => void }>();
commands: string[] = [];
wants?: (guildId: string) => boolean;
me() {
return ME;
}
private all: BotGwGuild[] = [
{ id: G, name: 'M&L', icon: null },
{ id: OTHER_G, name: '다른 서버', icon: null },
];
/** 서버별 멤버: 친구는 M&L 에만 가입 */
private memberOf: Record<string, string[]> = { [G]: [SUPER, FRIEND], [OTHER_G]: [SUPER] };
private channels: Record<string, { id: string; name: string; voice: boolean; view: string[]; connect: string[] }[]> = {
[G]: [
{ id: VC1, name: '일반', voice: true, view: [SUPER, FRIEND], connect: [SUPER, FRIEND] },
{ id: VC2, name: '게임', voice: true, view: [SUPER, FRIEND], connect: [SUPER, FRIEND] },
{ id: PRIV, name: '운영진', voice: true, view: [SUPER], connect: [SUPER] },
{ id: LOCKED, name: '방송', voice: true, view: [SUPER, FRIEND], connect: [SUPER] },
{ id: TEXT, name: '채팅', voice: false, view: [SUPER, FRIEND], connect: [] },
],
[OTHER_G]: [{ id: OTHER_VC, name: '다른 음성', voice: true, view: [SUPER], connect: [SUPER] }],
};
/** 지금 음성채널에 있는 사람 */
voice: { member: BotGwMember; channelId: string; guildId: string }[] = [
{ member: m(SUPER, '관리자'), channelId: VC1, guildId: G },
{ member: m('300000000000000001', '운영진'), channelId: PRIV, guildId: G },
];
private ch(g: string, c: string) {
return this.channels[g]?.find((x) => x.id === c);
}
async guildsFor(userId: string) {
return this.all.filter((g) => this.memberOf[g.id]?.includes(userId));
}
async snapshot(guildId: string, userId: string) {
const g = this.all.find((x) => x.id === guildId);
if (!g || !this.memberOf[guildId]?.includes(userId)) return null;
const channels: BotGwChannel[] = this.channels[guildId]!.filter((c) => c.voice && c.view.includes(userId)).map((c) => ({ id: c.id, name: c.name }));
return { guild: g, channels, voice: this.voice.filter((v) => v.guildId === guildId && channels.some((c) => c.id === v.channelId)).map(({ member, channelId }) => ({ member, channelId })) };
}
canView(guildId: string, userId: string, channelId: string) {
return !!this.ch(guildId, channelId)?.view.includes(userId);
}
canConnect(guildId: string, userId: string, channelId: string) {
const c = this.ch(guildId, channelId);
return !!c?.voice && c.view.includes(userId) && c.connect.includes(userId);
}
async members(guildId: string, userId: string) {
if (!this.memberOf[guildId]?.includes(userId)) throw new Error('forbidden');
return [m(SUPER, '관리자'), m(FRIEND, '친구'), m('700000000000000001', '음악봇', true)];
}
async registerCommands(guildId: string) {
this.commands.push(guildId);
}
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }) {
this.handlers.set(guildId, handlers);
return {
send: (payload: any) => {
this.sent.push({ guildId, payload });
return true;
},
};
}
}
async function fakeDiscord() {
const names: Record<string, string> = { [SUPER]: '관리자', [FRIEND]: '친구' };
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') {
let b = '';
req.on('data', (c) => (b += c));
req.on('end', () => res.end(JSON.stringify({ access_token: new URLSearchParams(b).get('code') })));
return;
}
if (u.pathname === '/users/@me') {
const id = String(req.headers.authorization).replace('Bearer ', '');
return res.end(JSON.stringify({ id, username: names[id], global_name: names[id], avatar: null }));
}
const mm = /^\/users\/(\d+)$/.exec(u.pathname);
if (mm && names[mm[1]!]) return res.end(JSON.stringify({ id: mm[1], username: names[mm[1]!], global_name: names[mm[1]!], avatar: null }));
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 source = new FakeSource();
const { app } = await buildServer(
{
port: 0, host: '127.0.0.1', publicUrl: 'http://placeholder', clientId: 'cid', clientSecret: 's', botToken: BOT,
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: dc.url, assetUpstream: {},
},
{ botSource: source },
);
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
const browser = (who: string) => async (url: string) => {
const start = await fetch(url.replace('http://placeholder', base), { redirect: 'manual' });
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
const cookie = start.headers.getSetCookie()[0]!.split(';')[0]!;
await fetch(`${base}/auth/discord/callback?code=${who}&state=${encodeURIComponent(state)}`, { headers: { cookie }, redirect: 'manual' });
};
/** 로그인한 앱 하나 (설정 · 로그인 · 봇 중계) */
const pc = async (who: string) => {
const st = new SettingsStore(tmp());
st.update({ site: { serverUrl: base } });
const auth = new AppAuth(st, { version: 't', openUrl: browser(who), pollMs: 20 });
assert.equal((await auth.login()).status, 'ok');
const gw = new RemoteGateway({ serverUrl: () => base, appToken: () => st.getSecret('appToken') ?? null, version: 't' });
// 서버가 앱에 보낸 모든 메시지 (봇 토큰이 섞여 있지 않은지 본다)
const seen: string[] = [];
const orig = (gw as any).onMessage.bind(gw);
(gw as any).onMessage = (msg: any) => (seen.push(JSON.stringify(msg)), orig(msg));
return { st, auth, gw, seen };
};
return { base, source, pc, close: async () => (await app.close(), dc.close()) };
}
const until = async (cond: () => boolean, ms = 3000) => {
const end = Date.now() + ms;
while (!cond()) {
if (Date.now() > end) throw new Error('시간 초과');
await new Promise((r) => setTimeout(r, 10));
}
};
const op4 = (guildId: string, channelId: string | null) => ({ op: 4, d: { guild_id: guildId, channel_id: channelId, self_mute: false, self_deaf: false } });
test('봇 중계: 로그인 안 한 연결은 막히고, 로그인한 앱은 봇 토큰 없이 서버 정보 · 음성 상태를 받는다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
try {
// 앱 토큰이 틀리면 401 → unauthorized
const bad = new RemoteGateway({ serverUrl: () => s.base, appToken: () => 'wrong-token', version: 't' });
await assert.rejects(bad.start(), /로그인/);
await bad.stop();
await a.gw.start();
assert.deepEqual(a.gw.me(), ME);
assert.deepEqual(a.gw.guilds().map((g) => g.id), [G, OTHER_G]);
// 지켜보기 전에도 (설정 창이 봇 연결 직후 바로 요청) 가입한 서버 멤버 목록을 받는다
assert.equal((await a.gw.members(G)).length, 3);
const g = await a.gw.watch(G, { commands: true });
assert.equal(g?.name, 'M&L');
await until(() => s.source.commands.includes(G));
assert.deepEqual(a.gw.voiceChannelOf(G, SUPER), { id: VC1, name: '일반' });
assert.deepEqual(a.gw.channelMembers(G, VC1).map((x) => x.id), [SUPER]);
// 음성 상태 변화가 넘어온다
const evs: any[] = [];
a.gw.on('voiceState', (e) => evs.push(e));
s.source.emit('voiceState', { guildId: G, member: m(FRIEND, '친구'), oldChannelId: null, newChannelId: VC2, channel: { id: VC2, name: '게임' } });
s.source.emit('voiceState', { guildId: OTHER_G, member: m(FRIEND, '친구'), oldChannelId: null, newChannelId: '1', channel: null }); // 지켜보지 않는 서버
await until(() => evs.length === 1);
assert.deepEqual(a.gw.voiceChannelOf(G, FRIEND), { id: VC2, name: '게임' });
// 멤버 목록 (봇 판별)
const ms = await a.gw.members(G);
assert.equal(ms.length, 3);
assert.equal(a.gw.isBot('700000000000000001'), true);
assert.equal(a.gw.isBot(FRIEND), false);
assert.ok(a.seen.length > 3);
assert.ok(!a.seen.some((x) => x.includes(BOT)), '봇 토큰이 앱으로 가면 안 된다');
} finally {
await a.gw.stop();
await s.close();
}
});
test('봇 중계: 음성 참여는 서버가 대신 보내고 일회용 음성 접속 정보만 그 앱에 넘긴다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
try {
await a.gw.start();
await a.gw.watch(G, { commands: false });
const got: any[] = [];
const adapter = a.gw.adapterCreator(G)({
onVoiceServerUpdate: (d) => got.push(['server', d]),
onVoiceStateUpdate: (d) => got.push(['state', d]),
destroy: () => got.push(['destroy']),
});
// 지켜보지 않는 서버 · 음성채널이 아닌 곳 · op 4 가 아닌 것은 서버가 버린다
a.gw.adapterCreator(OTHER_G)({ onVoiceServerUpdate: () => undefined, onVoiceStateUpdate: () => undefined, destroy: () => undefined }).sendPayload(op4(OTHER_G, '1'));
adapter.sendPayload(op4(G, TEXT));
adapter.sendPayload({ op: 2, d: { token: 'x' } });
adapter.sendPayload({ op: 4, d: { guild_id: OTHER_G, channel_id: VC1 } });
// 정상 참여
assert.equal(adapter.sendPayload({ op: 4, d: { guild_id: G, channel_id: VC1, self_mute: false, self_deaf: false, extra: 'x' } }), true);
await until(() => s.source.sent.length === 1);
assert.deepEqual(s.source.sent[0], { guildId: G, payload: op4(G, VC1) }, '검사한 필드만 다시 만들어 보낸다');
// 디스코드가 준 음성 접속 정보 → 앱의 @discordjs/voice 로
s.source.handlers.get(G)!.state({ guild_id: G, user_id: ME.id, session_id: 'sess-1', channel_id: VC1 });
s.source.handlers.get(G)!.server({ guild_id: G, token: 'one-time-voice-token', endpoint: 'voice.example:443' });
await until(() => got.length === 2);
assert.equal(got[0][0], 'state');
assert.equal(got[0][1].session_id, 'sess-1');
assert.equal(got[1][1].token, 'one-time-voice-token');
// 나가기
adapter.sendPayload(op4(G, null));
await until(() => s.source.sent.length === 2);
assert.equal(s.source.sent[1]!.payload.d.channel_id, null);
assert.ok(!a.seen.some((x) => x.includes(BOT)));
} finally {
await a.gw.stop();
await s.close();
}
});
test('봇 중계: 다른 PC 가 봇을 데려가면 이전 PC 는 taken 을 받고, 이전 PC 가 봇을 빼거나 음성 정보를 받지 못한다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
const admin = new AppAuth(a.st, { version: 't', openUrl: () => undefined });
await admin.adminAddUser(FRIEND, 'user');
const b = await s.pc(FRIEND);
try {
await a.gw.start();
await b.gw.start();
await a.gw.watch(G, { commands: false });
await b.gw.watch(G, { commands: false });
const aGot: any[] = [];
const bGot: any[] = [];
const aAd = a.gw.adapterCreator(G)({ onVoiceServerUpdate: (d) => aGot.push(d), onVoiceStateUpdate: (d) => aGot.push(d), destroy: () => undefined });
const bAd = b.gw.adapterCreator(G)({ onVoiceServerUpdate: (d) => bGot.push(d), onVoiceStateUpdate: (d) => bGot.push(d), destroy: () => undefined });
const taken: string[] = [];
a.gw.on('taken', (g) => taken.push(g));
aAd.sendPayload(op4(G, VC1));
await until(() => s.source.sent.length === 1);
bAd.sendPayload(op4(G, VC2));
await until(() => taken.length === 1 && s.source.sent.length === 2);
assert.equal(taken[0], G);
// 이제 음성 접속 정보는 B 에게만
s.source.handlers.get(G)!.server({ guild_id: G, token: 'for-b' });
await until(() => bGot.length === 1);
assert.equal(aGot.length, 0);
// A 가 늦게 나가기를 보내도 B 의 봇을 빼지 않는다
aAd.sendPayload(op4(G, null));
await new Promise((r) => setTimeout(r, 100));
assert.equal(s.source.sent.length, 2);
// B 앱이 꺼지면 서버가 봇을 음성채널에서 뺀다
await b.gw.stop();
await until(() => s.source.sent.length === 3);
assert.equal(s.source.sent[2]!.payload.d.channel_id, null);
} finally {
await a.gw.stop();
await b.gw.stop();
await s.close();
}
});
test('봇 중계: 슬래시 명령은 그 서버를 지켜보는 앱으로 가고 앱의 답이 돌아간다. 등록 해제하면 바로 끊긴다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
const admin = new AppAuth(a.st, { version: 't', openUrl: () => undefined });
await admin.adminAddUser(FRIEND, 'user');
const b = await s.pc(FRIEND);
const cmd = (name: string, user: string) =>
new Promise<string>((resolve) => s.source.emit('command', { name, guildId: G, user: m(user, user), voiceChannel: { id: VC1, name: '일반' } } satisfies BotCommand, resolve));
try {
assert.match(await cmd('녹음시작', SUPER), /^지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다/);
// 지켜보는 앱이 없는 서버의 명령은 서버가 잠깐 기다렸다가 받는다 (봇 토큰을 직접 쓰는 v1.1.0 PC 가 먼저 응답하게)
assert.equal(s.source.wants?.(G), false);
await a.gw.start();
await b.gw.start();
// 내 앱이 켜져 있어도 다른 서버를 녹음 대상으로 정해 두면 그렇다고 알려 준다 ("응답하지 않았어요" 대신)
assert.match(await cmd('녹음시작', SUPER), /^내 겜녹이 앱이 이 서버에 아직 연결되지 않았습니다/);
await a.gw.watch(OTHER_G, { commands: false });
assert.match(await cmd('녹음시작', SUPER), /^내 겜녹이 앱이 다른 디스코드 서버를 녹음 대상으로 정해 두었습니다/);
await a.gw.watch(G, { commands: false });
assert.equal(s.source.wants?.(G), true);
assert.equal(s.source.wants?.(OTHER_G), false);
await b.gw.watch(G, { commands: false });
const seenBy: string[] = [];
a.gw.on('command', (c, respond) => (seenBy.push(`a:${c.name}`), respond(`A 가 ${c.name}`)));
b.gw.on('command', (c, respond) => (seenBy.push(`b:${c.name}`), respond(`B 가 ${c.name}`)));
// 명령한 사람의 PC 로
assert.equal(await cmd('녹음시작', FRIEND), 'B 가 녹음시작');
assert.equal(await cmd('녹음시작', SUPER), 'A 가 녹음시작');
// 녹음 중인 PC 가 없으면 종료할 것이 없다
assert.equal(await cmd('녹음종료', SUPER), '지금은 녹음 중이 아닙니다.');
// 녹음제외는 모든 PC 기록에 남긴다
await cmd('녹음제외', FRIEND);
await until(() => seenBy.includes('a:녹음제외') && seenBy.includes('b:녹음제외'));
// 등록 해제 → B 의 중계 연결이 바로 끊기고 unauthorized
let unauth = false;
b.gw.on('unauthorized', () => (unauth = true));
await admin.adminRemoveUser(FRIEND);
await until(() => unauth);
assert.equal(b.gw.me(), null);
// 로그아웃 → A 도 끊긴다
let aUnauth = false;
a.gw.on('unauthorized', () => (aUnauth = true));
await a.auth.logout();
await until(() => aUnauth);
} finally {
await a.gw.stop();
await b.gw.stop();
await s.close();
}
});
test('봇 중계 권한: 일반 유저는 가입한 서버 · 볼 수 있는 채널만 보이고, 들어갈 수 있는 음성채널에만 봇을 부른다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
const admin = new AppAuth(a.st, { version: 't', openUrl: () => undefined });
await admin.adminAddUser(FRIEND, 'user');
const b = await s.pc(FRIEND);
try {
await b.gw.start();
// 서버 목록: 가입한 M&L 만
assert.deepEqual(b.gw.guilds().map((g) => g.id), [G]);
// 가입하지 않은 서버는 지켜볼 수 없다 (바로 거절)
const t0 = Date.now();
assert.equal(await b.gw.watch(OTHER_G, { commands: true }), null);
assert.ok(Date.now() - t0 < 3000, '거절은 바로 온다');
assert.ok(!s.source.commands.includes(OTHER_G), '가입하지 않은 서버에 명령을 등록하지 않는다');
await assert.rejects(b.gw.members(OTHER_G), /forbidden/);
// M&L: 비공개 채널과 그 안의 사람은 안 보인다
assert.ok(await b.gw.watch(G, { commands: false }));
assert.deepEqual((b.gw as any).channels && [...(b.gw as any).channels.keys()].sort(), [VC1, VC2, LOCKED].sort());
assert.equal(b.gw.voiceChannelOf(G, '300000000000000001'), null);
assert.equal(b.gw.channel(G, PRIV), null);
// 비공개 채널 안의 움직임은 안 오고, 비공개 채널로 옮기면 "나감"으로만 보인다
const evs: any[] = [];
b.gw.on('voiceState', (e) => evs.push(e));
s.source.emit('voiceState', { guildId: G, member: m('300000000000000002', '운영진2'), oldChannelId: null, newChannelId: PRIV, channel: { id: PRIV, name: '운영진' } });
s.source.emit('voiceState', { guildId: G, member: m(SUPER, '관리자'), oldChannelId: VC1, newChannelId: PRIV, channel: { id: PRIV, name: '운영진' } });
await until(() => evs.length === 1);
await new Promise((r) => setTimeout(r, 100));
assert.equal(evs.length, 1);
assert.deepEqual([evs[0].member.id, evs[0].oldChannelId, evs[0].newChannelId, evs[0].channel], [SUPER, VC1, null, null]);
// 음성 참여: 비공개 · 연결 권한 없는 채널 · 다른 서버는 거절, 들어갈 수 있는 채널만
const ad = b.gw.adapterCreator(G)({ onVoiceServerUpdate: () => undefined, onVoiceStateUpdate: () => undefined, destroy: () => undefined });
ad.sendPayload(op4(G, PRIV));
ad.sendPayload(op4(G, LOCKED));
ad.sendPayload(op4(G, OTHER_VC));
ad.sendPayload(op4(G, VC2));
await until(() => s.source.sent.length === 1);
await new Promise((r) => setTimeout(r, 100));
assert.deepEqual(s.source.sent.map((x) => x.payload.d.channel_id), [VC2]);
// 슬래시 명령: 최고 관리자가 비공개 채널에서 /녹음시작 → 그 채널에 못 들어가는 친구 PC 로는 보내지 않는다
const cmds: any[] = [];
b.gw.on('command', (c, respond) => (cmds.push(c), respond('ok')));
const cmd = (name: string) =>
new Promise<string>((resolve) => s.source.emit('command', { name, guildId: G, user: m(SUPER, '관리자'), voiceChannel: { id: PRIV, name: '운영진' } } satisfies BotCommand, resolve));
assert.equal(await cmd('녹음시작'), '이 음성채널에 들어갈 수 있는 겜녹이 앱이 없습니다.');
// /녹음제외 는 친구 PC 기록에도 남기되 비공개 채널 이름은 보내지 않는다
assert.equal(await cmd('녹음제외'), 'ok');
assert.equal(cmds.length, 1);
assert.equal(cmds[0].voiceChannel, null);
// 친구 PC 가 받은 메시지 어디에도 비공개 채널 · 그 안의 사람 정보가 없다
const all = b.seen.join('\n');
// (OTHER_G 는 친구가 직접 보낸 watch 의 거절 응답에만 나온다)
for (const secret of [PRIV, '운영진', '300000000000000001', '300000000000000002', '다른 서버', OTHER_VC]) assert.ok(!all.includes(secret), secret);
} finally {
await a.gw.stop();
await b.gw.stop();
await s.close();
}
});

View File

@@ -0,0 +1,84 @@
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 { SettingsStore } from '../src/core/settings.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-bot-'));
const BUILTIN = 'MTExMTExMTExMTExMTExMTEx.FAKE00.builtin-token-for-tests-only-xxxxxxxx';
const APP = 'app-login-token-for-tests';
const OTHER = 'OTE4MTIzMzQ4NzIxMDA4NzAw.FAKE11.other-bot-token-for-tests-only-yyyy';
delete process.env.GVR_BOT_TOKEN;
/** 로그인한 상태 (앱 토큰만 있다. 겜녹이 봇 토큰은 서버에만 있다) */
const loggedIn = (dir = tmp()) => {
const s = new SettingsStore(dir);
s.setSecret('appToken', APP);
return s;
};
test('로그인 전: 겜녹이 봇 토큰이 없다 (exe 에 들어 있지 않다)', () => {
const s = new SettingsStore(tmp());
assert.equal(s.get().discord.botMode, 'builtin');
assert.equal(s.hasBuiltinBot, false);
assert.equal(s.activeBotToken(), null);
});
test('로그인 후: 겜녹이 봇이 기본이고, 이 PC 가 직접 로그인할 봇 토큰은 없다 (서버 중계)', () => {
const s = loggedIn();
assert.equal(s.hasBuiltinBot, true);
assert.equal(s.activeBotToken(), null);
});
test('v1.2.0 이 받아 둔 겜녹이 봇 토큰은 시작할 때 지운다', () => {
const dir = tmp();
loggedIn(dir).setSecret('builtinBotToken', BUILTIN);
const s = new SettingsStore(dir);
assert.equal(s.hasSecret('builtinBotToken'), false);
assert.ok(!fs.readFileSync(path.join(dir, 'secrets.bin'), 'utf8').includes(BUILTIN));
assert.equal(s.activeBotToken(), null);
});
test('다른 봇으로 진행하기: 넣은 토큰을 쓰고, 다시 겜녹이 봇으로 오가도 각자 유지된다', () => {
const dir = tmp();
const s = loggedIn(dir);
s.update({ discord: { botMode: 'custom' } });
assert.equal(s.activeBotToken(), null, '다른 봇인데 토큰이 아직 없으면 로그인하지 않는다');
s.setSecret('botToken', OTHER);
assert.equal(s.activeBotToken(), OTHER);
s.update({ discord: { botMode: 'builtin' } });
assert.equal(s.activeBotToken(), null);
s.update({ discord: { botMode: 'custom' } });
assert.equal(s.activeBotToken(), OTHER, '저장한 다른 봇 토큰은 지워지지 않는다');
// 다시 켜도 모드·토큰이 남는다
const again = new SettingsStore(dir);
assert.equal(again.get().discord.botMode, 'custom');
assert.equal(again.activeBotToken(), OTHER);
// 평문 설정 파일(settings.json)에는 토큰이 들어가지 않는다
assert.ok(!fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes(OTHER));
});
test('v1.0.0 에서 직접 토큰을 넣어 쓰던 설치는 다른 봇 모드로 이어진다', () => {
const dir = tmp();
const old = new SettingsStore(dir);
old.setSecret('botToken', OTHER);
const saved = JSON.parse(JSON.stringify(old.get()));
delete saved.discord.botMode;
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify(saved));
const s = new SettingsStore(dir);
assert.equal(s.get().discord.botMode, 'custom');
assert.equal(s.activeBotToken(), OTHER);
});
test('개발용 GVR_BOT_TOKEN 은 모드와 상관없이 우선한다', () => {
process.env.GVR_BOT_TOKEN = OTHER;
try {
assert.equal(loggedIn().activeBotToken(), OTHER);
} finally {
delete process.env.GVR_BOT_TOKEN;
}
});

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

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

View File

@@ -10,7 +10,8 @@ import { diffWords, Dictionary } from '../src/core/dict/dictionary.ts';
import { realignWords } from '../src/core/api/server.ts';
import { processMatchDetails } from '../src/core/games/valorant.ts';
import { GameAssets } from '../src/core/games/assets.ts';
import { OggOpusWriter, opusSamples, SILENCE_FRAME } from '../src/core/discord/ogg.ts';
import { OggOpusWriter, opusSamples, removeInsertedSilence, SILENCE_FRAME } from '../src/core/discord/ogg.ts';
import { Utterance, tagRtp, tapRtp } from '../src/core/discord/recorder.ts';
import { Retention } from '../src/core/retention.ts';
import { makeValDetails, SELF } from './fixtures/make-val-details.ts';
@@ -34,6 +35,81 @@ test('Ogg Opus writer: ffmpeg 가 읽을 수 있고 길이가 맞다', () => {
execFileSync('ffmpeg', ['-v', 'error', '-i', out, '-f', 'null', '-']);
});
test('녹음기: 패킷이 몰려 와도 말 중간에 무음을 넣지 않는다 (RTP 타임스탬프 기준)', () => {
// 게임 중 실제 수신 모양: 20ms 간격으로 만든 패킷이 40~60ms 마다 2~3개씩 한꺼번에 도착 (v1.3.5 사용자 파일 "##.##.##")
const dir = tmp();
const voice = Array.from({ length: 100 }, (_, i) => Buffer.from([0x78, i & 0xff, 0x01]));
const u = new Utterance(dir, 1_000_000);
let now = 1_000_020;
let seq = 65530; // 순번이 한 바퀴 도는 경우도 함께
let ts = 4294967296 - 960 * 10; // 타임스탬프도 한 바퀴 돔
let filled = 0;
for (let i = 0; i < voice.length; i++) {
if (i === 60) {
// 진짜 쉼 0.4초: 패킷 20개 자리가 비었다
seq = (seq + 20) & 0xffff;
ts = (ts + 960 * 20) >>> 0;
now += 400;
}
if (i % 3 === 0) now += 60; // 3개씩 몰려 도착
filled += Math.max(0, u.place(tagRtp(voice[i], { seq, ts }), now, 1000));
seq = (seq + 1) & 0xffff;
ts = (ts + 960) >>> 0;
}
// 중복 패킷은 버린다
assert.equal(u.place(tagRtp(Buffer.from([0x78, 0, 0]), { seq: (seq - 1) & 0xffff, ts: (ts - 960) >>> 0 }), now, 1000), -1);
assert.equal(filled, 20, '진짜 쉼만 채운다');
assert.equal(u.writer.samples, (100 + 20) * 960);
u.writer.close();
});
test('예전 녹음 고치기: 말 중간에 끼운 무음만 빼고 말 끝 무음은 남긴다', () => {
const f = path.join(tmp(), 'old.ogg');
const w = new OggOpusWriter(f);
const v = (i: number) => Buffer.from([0x78, i, 1]);
// "##.##.##" + 진짜 쉼(10) + "##" + 말 끝 무음 5
const seq = [v(1), v(2), SILENCE_FRAME, v(3), v(4), SILENCE_FRAME, v(5), v(6), ...Array(10).fill(SILENCE_FRAME), v(7), v(8), ...Array(5).fill(SILENCE_FRAME)];
for (const p of seq) w.write(p);
w.close();
assert.equal(removeInsertedSilence(f), 2);
const after = readOggPackets(fs.readFileSync(f)).slice(2);
assert.equal(after.length, seq.length - 2);
assert.equal(removeInsertedSilence(f), 0, '두 번 고치지 않는다');
execFileSync('ffmpeg', ['-v', 'error', '-i', f, '-f', 'null', '-']);
});
test('녹음기: RTP 시각이 없을 때도 몰려 온 패킷 사이에 무음을 넣지 않는다', () => {
const u = new Utterance(tmp(), 1_000_000);
let now = 1_000_020;
let filled = 0;
for (let i = 0; i < 60; i++) {
if (i % 3 === 0) now += 60;
filled += u.place(Buffer.from([0x78, i, 1]), now, 1000);
}
assert.equal(filled, 0);
now += 500; // 0.5초 쉼 뒤 말
filled += u.place(Buffer.from([0x78, 9, 1]), now, 1000);
assert.ok(filled >= 18 && filled <= 25, `filled ${filled}`);
u.writer.close();
});
test('녹음기: 디스코드 수신기의 RTP 헤더를 패킷에 붙인다', () => {
const rtp = Buffer.alloc(16);
rtp[0] = 0x80;
rtp.writeUInt16BE(1234, 2);
rtp.writeUInt32BE(99999, 4);
const opus = Buffer.from([0x78, 1, 2]);
const receiver = { parsePacket: (_b: Buffer) => opus };
assert.equal(tapRtp(receiver), true);
assert.equal(tapRtp(receiver), true); // 두 번 감싸지 않음
const out = receiver.parsePacket(rtp);
const u = new Utterance(tmp(), 0);
u.place(out, 20, 1000);
assert.equal(u.rtpBase, 99999);
assert.equal(u.lastSeq, 1234);
u.writer.close();
});
function readOggPackets(buf: Buffer): Buffer[] {
const out: Buffer[] = [];
let pos = 0;
@@ -132,7 +208,7 @@ test('타임라인 조회: 필터·검색·커서', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const tl = new Timeline(store);
store.upsertUser({ id: 'u1', name: '승한', avatar: null });
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
const t0 = Date.UTC(2026, 9, 15, 12, 0, 0);
const texts = ['스모크 깔게 미드로 와', '레이즈 궁 빠졌어', '오퍼 사줘', '배고프다 치킨 먹자', 'B 사이트 로테 하자'];
@@ -144,10 +220,10 @@ test('타임라인 조회: 필터·검색·커서', () => {
store.updateUtteranceResult('n1', { text: null, raw_text: '시청해 주셔서 감사합니다', words: [], noise: true, noise_reason: 'hallucination', confidence: 0.2, lufs: -40, gain_db: 20, model: 'tiny', status: 'realtime' });
let page = tl.query({ limit: 3 });
assert.equal(page.items.length, 3);
assert.equal(page.items[0].id, 'n1');
assert.equal(page.items[0].id, 'x4', '잡음은 보이지 않는다');
const page2 = tl.query({ limit: 3, cursor: page.next! });
assert.deepEqual(page2.items.map((i) => i.id), ['x2', 'x1', 'x0']);
assert.equal(tl.query({ hideNoise: true }).items.length, 5);
assert.deepEqual(page2.items.map((i) => i.id), ['x1', 'x0']);
assert.equal(tl.query({}).items.length, 5);
assert.deepEqual(tl.query({ q: '레이즈 궁' }).items.map((i) => i.id), ['x1']);
assert.deepEqual(tl.query({ q: '오퍼' }).items.map((i) => i.id), ['x2']);
assert.equal(tl.query({ users: ['u2'] }).items.length, 2);
@@ -183,3 +259,52 @@ test('7일 지난 음성만 삭제, 텍스트는 남음', () => {
assert.equal(store.getUtterance('old')!.audio_deleted, 1);
store.close();
});
test('표시 이름: 정한 이름으로 유저 이름 · 지난 범인 분석의 이름을 바꾸고, 새로 들어온 이름에도 쓴다', () => {
const store = new Store(path.join(tmp(), 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '실명이', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
store.db.exec(`CREATE TABLE culprit_analyses (id TEXT PRIMARY KEY, match_id TEXT NOT NULL, created_at INTEGER NOT NULL, created_by TEXT NOT NULL, model TEXT NOT NULL, current INTEGER NOT NULL DEFAULT 1, result TEXT NOT NULL, meta TEXT NOT NULL DEFAULT '{}')`);
store.db
.prepare('INSERT INTO culprit_analyses(id,match_id,created_at,created_by,model,result) VALUES(?,?,?,?,?,?)')
.run('a1', 'm1', 1, JSON.stringify({ id: 'u1', name: '실명이 다른표기' }), 'x', JSON.stringify({ result: { summary: '실명이가 캐리' }, players: [{ name: '실명이' }, { name: '민수' }] }));
store.setDisplayNames({ u1: '별명' });
assert.equal(store.getUser('u1')?.name, '별명');
assert.equal(store.getUser('u2')?.name, '민수');
const r = store.db.prepare('SELECT created_by, result FROM culprit_analyses').get() as any;
assert.equal(JSON.parse(r.created_by).name, '별명');
assert.ok(!r.result.includes('실명이') && r.result.includes('별명가 캐리'), r.result);
// 디스코드에서 예전 이름이 다시 와도 표시 이름으로 저장, 다시 열어도 유지
store.upsertUser({ id: 'u1', name: '실명이', avatar: null });
assert.equal(store.getUser('u1')?.name, '별명');
const file = store.db.name;
store.close();
const again = new Store(file);
again.upsertUser({ id: 'u1', name: '실명이', avatar: null });
assert.equal(again.getUser('u1')?.name, '별명');
again.close();
});
test('users.updated: 보내는 쪽이 빈 목록을 줘도 실제 유저 목록이 나간다 ("알 수 없음" 버그)', async () => {
const { Bus } = await import('../src/core/util/events.ts');
const bus = new Bus();
bus.usersProvider = () => [{ id: '1', name: '하늘', color: '#fff', avatar: null, excluded: false, riot: [] }];
const got: any[] = [];
bus.on('live', (e) => got.push(e));
bus.live({ type: 'users.updated', data: [] });
assert.equal(got[0].data.length, 1);
assert.equal(got[0].data[0].name, '하늘');
});
test('녹음 안내 말 속도: 0.1~2.0 으로 자르고 속도마다 따로 캐시한다', async () => {
const { Announcer, clampRate } = await import('../src/core/discord/tts.ts');
assert.equal(clampRate(0.05), 0.1);
assert.equal(clampRate(3), 2);
assert.equal(clampRate('x'), 1);
const a = new Announcer(tmp(), tmp());
const one = a.cachedPath('안내', 'v', 1);
assert.equal(one, a.cachedPath('안내', 'v'), '1.0배는 예전 캐시 그대로');
assert.notEqual(a.cachedPath('안내', 'v', 1.5), one);
assert.ok(a.cachedPath('안내', 'v', 0.3).endsWith('.ogg'), '0.5배보다 느리면 워커가 만든 Ogg');
assert.ok(a.cachedPath('안내', 'v', 0.5).endsWith('.webm'));
});

227
app/test/culprit.test.ts Normal file
View File

@@ -0,0 +1,227 @@
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 type { CulpritInput, CulpritMatchInfo, CulpritMatchItem } from '@gvr/shared';
import { SettingsStore, DEFAULT_TTS_TEXT } from '../src/core/settings.ts';
import { kastRound } from '../src/core/games/valorant.ts';
import { makeDemoLol } from './fixtures/demo-matches.ts';
import { culpritApi, MIN, seedValorant, setup } from './fixtures/culprit-seed.ts';
test('범인찾기: 발로란트 추가 지표 저장 (피해량 · 첫킬 · 설치 · 역할 · 라운드별 장비)', () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const det = JSON.parse(ctx.store.getMatch(id)!.detail!);
const jett = det.players.find((p: any) => p.puuid === 'p-sh');
assert.equal(jett.stats.role, '타격대');
assert.ok(jett.stats.damage > 0, '피해량');
assert.equal(typeof jett.stats.firstKills, 'number');
assert.ok(det.players.reduce((n: number, p: any) => n + p.stats.firstKills, 0) > 0, '첫킬 합 > 0');
const plants = det.players.reduce((n: number, p: any) => n + p.stats.plants, 0);
assert.ok(plants > 0, '설치 기록');
const r = det.roundsDetail[1];
assert.equal(typeof r.allyAttack, 'boolean');
assert.ok(r.players['p-sh'] !== undefined, '라운드별 선수 지표');
assert.ok(Object.values<any>(r.economy).every((e) => typeof e.loadout === 'number'), '라운드 장비 값');
// 전반(1~12)과 후반(13~)은 공수가 바뀐다
assert.notEqual(det.roundsDetail[0].allyAttack, det.roundsDetail[12].allyAttack);
// KAST · 받은 피해 (OP.GG 발로란트 OP스코어 입력)
assert.ok(det.players.every((p: any) => p.stats.kastRounds >= 0 && p.stats.kastRounds <= det.roundsDetail.length && p.stats.damageTaken > 0));
});
test('범인찾기: KAST 라운드 판정 (킬 · 어시 · 생존 · 5초 안 트레이드)', () => {
const players = { a1: { teamId: 'Red' }, a2: { teamId: 'Red' }, a3: { teamId: 'Red' }, b1: { teamId: 'Blue' }, b2: { teamId: 'Blue' } };
const r = { playerStats: Object.keys(players).map((subject) => ({ subject })) };
const kills = [
{ killer: 'b1', victim: 'a1', gameTime: 10000, assistants: [] }, // a1 죽음 → 3초 뒤 a2 가 b1 을 잡아 트레이드
{ killer: 'a2', victim: 'b1', gameTime: 13000, assistants: ['a3'] },
{ killer: 'b2', victim: 'a2', gameTime: 20000, assistants: [] }, // a2 는 킬이 있어 KAST
{ killer: 'b2', victim: 'a3', gameTime: 30000, assistants: [] }, // a3 는 어시가 있어 KAST
];
assert.deepEqual(kastRound(r, kills, players).sort(), ['a1', 'a2', 'a3', 'b1', 'b2']); // b1 은 킬이 있다
// 트레이드가 5초를 넘기면 KAST 아님
const late = [{ ...kills[0] }, { ...kills[1], gameTime: 16000 }];
assert.ok(!kastRound(r, late, players).includes('a1'));
});
test('범인찾기: 분석 가능 판정과 AI 자료', () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const m = ctx.store.getMatch(id)!;
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [] });
const input = ctx.culprit.buildInput(m);
const lines = input.text.split('\n');
assert.match(lines[0], /^# 경기 발로란트 .* 13:9 \(우리 팀 승리\) · 22라운드/);
// 우리 팀이 P1~P5, 하늘은 음성O, 디스코드 계정이 없는 상대는 음성X
const p1 = lines.find((l) => l.startsWith('P1 '))!;
assert.match(p1, /^P1 하늘 우리 제트\(타격대\) \d+\/\d+\/\d+ ACS\d+ ADR\d+ KAST\d+% 피해격차[+-]\d+ 첫킬\d+\/첫데스\d+ HS\d+% 설치\d+\/해체\d+ .*음성O$/);
// 기록 점수 (OP.GG OP스코어 계산법): 10명 모두, 이긴 팀 1등 MVP · 진 팀 1등 ACE
const head = lines.findIndex((l) => l.startsWith('# 기록 점수 (0~10, OP.GG OP스코어 계산법'));
assert.ok(head > 0, '기록 점수 칸');
const rl = lines.slice(head + 1, head + 11);
assert.ok(rl.every((l, i) => new RegExp(`^P${i + 1} \\d+\\.\\d점 \\d+위/팀\\d위`).test(l)), rl.join('\n'));
assert.equal(rl.filter((l) => / MVP( |$)/.test(l)).length, 1);
assert.equal(rl.filter((l) => / ACE( |$)/.test(l)).length, 1);
assert.ok(rl.slice(0, 5).some((l) => / MVP( |$)/.test(l)), 'MVP 는 이긴 우리 팀');
const rp = input.players.map((p) => p.rating!);
assert.ok(rp.every((r) => r && r.score >= 0 && r.score <= 10 && !r.basic));
assert.deepEqual(rp.map((r) => r.rank).sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert.equal(rp.find((r) => r.rank === 1)!.score, Math.max(...rp.map((r) => r.score)));
assert.match(lines.find((l) => l.startsWith('P6 '))!, /상대 .*음성X$/);
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, true, '민수는 대화가 있다');
assert.equal(input.players.find((p) => p.id === 'P3')!.voice, false);
// 게임 계정이 없는 화자는 디스코드 이름으로
assert.ok(lines.some((l) => l.includes('도윤(게임 계정 모름)')));
// 근거 번호: 대화 · 이벤트 · 라운드 · 스탯
const u1 = lines.find((l) => l.startsWith('[u1] '))!;
assert.match(u1, /^\[u1\] R3 0:05 P1: 현우야 같이 가 기다려 둘 있어$/);
assert.equal(input.refs.u1.kind, 'utterance');
assert.ok(lines.some((l) => /^\[e\d+\] R\d+ \d+:\d+ 킬 P\d+ → P\d+/.test(l)), '킬 줄');
assert.ok(lines.some((l) => /^\[r1\] R1 우리 (공격|수비) 라운드 끝 · (승리|패배)\(.+\) \d+:\d+ · 평균 장비 우리 [\d,]+ \/ 상대 [\d,]+ · 선수 장비\/피해: P1 /.test(l)), '라운드 줄');
assert.deepEqual(input.refs['s:P4'], { kind: 'stat', pid: 'P4' });
assert.equal(input.stats.utterances, 4);
assert.equal(input.stats.basic, false);
// 줄은 시간 순서
const u2Index = lines.findIndex((l) => l.startsWith('[u2] '));
assert.ok(lines.findIndex((l) => l.startsWith('[r2] ')) < lines.findIndex((l) => l.startsWith('[u1] ')));
assert.ok(u2Index > lines.findIndex((l) => l.startsWith('[u1] ')));
});
test('범인찾기: 녹음이 늦게 시작 · 음성 변환 중 · 녹음 제외', () => {
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분 뒤에 시작됐습니다']);
const pend = setup();
const b = seedValorant(pend, { pending: true });
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'] });
// 녹음 제외한 사람의 대화는 보내지 않는다
const ex = setup();
const c = seedValorant(ex);
ex.store.setExcluded('u2', true);
const input = ex.culprit.buildInput(ex.store.getMatch(c.id)!);
assert.ok(!input.text.includes('내가 뚫을게'));
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, false);
// 경기 결과를 못 받은 경기
const nd = setup();
nd.store.upsertMatch({ id: 'val-x', game: 'valorant', started_at: Date.now() - 50 * MIN, ended_at: Date.now() - 10 * MIN, status: 'complete', detail: JSON.stringify({ live: true }) });
nd.store.startSession('s', 'g', 'c', null, Date.now() - 60 * MIN);
assert.deepEqual(nd.culprit.eligibility(nd.store.getMatch('val-x')!), { state: 'blocked', reasons: ['경기 결과를 받지 못했습니다'] });
});
test('범인찾기: 롤 포지션 · 시야 · 10/15분 지표와 골드 차', () => {
const ctx = setup();
const LS = Date.now() - 80 * MIN;
const lol = makeDemoLol();
ctx.store.setMeta('riot_self_puuid', 'l-sh');
ctx.store.startSession('s', 'g', 'c', null, LS - MIN);
ctx.store.endSession('s', LS + lol.durationMs + MIN);
ctx.games.matchStarted({ id: 'lol-1', game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
ctx.games.matchEnded('lol-1', LS + lol.durationMs);
(ctx.games.adapters[1] as any).applyHistory('lol-1', lol.game, lol.timeline, LS);
const m = ctx.store.getMatch('lol-1')!;
const det = JSON.parse(m.detail!);
assert.deepEqual(
det.players.map((p: any) => p.stats.role),
['미드', '정글', '탑', '원딜', '서폿', '미드', '정글', '탑', '원딜', '서폿'],
);
assert.deepEqual(det.players[1].stats.at10, { cs: 60, gold: det.players[1].stats.at10.gold, xp: 4220 });
assert.equal(ctx.culprit.eligibility(m).state, 'ready');
const input = ctx.culprit.buildInput(m);
assert.match(input.text, /\nP5 Duck 우리 [^ ]+\(서폿\) \d+\/\d+\/\d+ CS\d+ 골드\d+ 딜17500 받은\d+ 시야62 와드48\/4\/9 10분\d+·\d+ 15분\d+·\d+ 음성X\n/);
assert.match(input.text, /\n# 골드 차\(우리-상대\): 5분 [+-][\d,]+ · 10분/);
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 킬 P\d+ → P\d+/);
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 내셔 남작 처치 우리 팀 · P2\n/);
// 기록 점수 + LOL.PS 라인전 점수의 입력 (10 · 15분 맞라이너와 차)
assert.match(input.text, /\n# 기록 점수 \(0~10, OP\.GG OP스코어 계산법/);
assert.match(input.text, /\nP1 \d+\.\d점 \d+위\/팀\d위.* · 라인전\(vs P6\) 10분 CS[+-][\d,]+ 골드[+-][\d,]+ 경험치[+-][\d,]+ 15분 CS[+-][\d,]+ 골드[+-][\d,]+ 경험치[+-][\d,]+\n/);
const p1 = input.players.find((p) => p.id === 'P1')!;
const p6 = input.players.find((p) => p.id === 'P6')!;
assert.equal(p1.rating!.lane!.at15!.cs, -p6.rating!.lane!.at15!.cs, '맞라인 차는 서로 반대');
assert.equal(p1.rating!.lane!.at10!.xp, -p6.rating!.lane!.at10!.xp);
assert.ok(p1.rating!.lane!.at10!.cs !== undefined && p1.rating!.lane!.at15!.gold !== undefined);
assert.equal(input.players.filter((p) => p.rating?.badge).length, 2);
});
test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const api = await culpritApi(ctx);
const list = (await api.inject({ url: '/api/culprit/matches' })).json() as CulpritMatchItem[];
assert.equal(list.length, 1);
assert.equal(list[0].eligibility.state, 'ready');
// 브라우저(사이트 중계)는 내부 경로를 쓸 수 없다
assert.equal((await api.inject({ url: `/api/culprit/internal/${id}/input` })).statusCode, 403);
assert.equal((await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, payload: {} })).statusCode, 403);
const r = await api.inject({ url: `/api/culprit/internal/${id}/input`, headers: { 'x-gvr-internal': '1' } });
assert.equal(r.statusCode, 200);
const input = r.json().input as CulpritInput;
assert.ok(input.text.length > 1000);
const result = {
summary: '요약',
confidence: 'high',
confidence_note: '',
teams: [
{ team: 'ally', culprit: 'P2', reason: '이유', evidence: [{ ref: 'u2', note: '"아 그냥 간다"', target: input.refs.u2 }] },
{ team: 'enemy', culprit: 'P8', reason: '이유', evidence: [] },
],
players: input.players.map((p) => ({ id: p.id, score: p.id === 'P2' || p.id === 'P8' ? 3 : 7, tag: p.id === 'P2' || p.id === 'P8' ? '범인' : '무난', comment: '평', evidence: [] })),
};
const put = await api.inject({
method: 'PUT',
url: `/api/culprit/internal/${id}/result`,
headers: { 'x-gvr-internal': '1' },
payload: { result, players: input.players, model: 'claude-opus-5-5', createdBy: { id: 'u1', name: '하늘' }, meta: { costUsd: 0.41 } },
});
assert.equal(put.statusCode, 200);
const info = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
assert.equal(info.eligibility.state, 'done');
assert.equal(info.analysis!.result.teams[0].culprit, 'P2');
assert.equal(info.analysis!.meta.costUsd, 0.41);
assert.equal(info.history.length, 1);
assert.equal(info.sources.utterances, 4);
const list2 = (await api.inject({ url: '/api/culprit/matches' })).json() as CulpritMatchItem[];
assert.deepEqual(
list2[0].culprits.map((c) => [c.team, c.name]),
[
['ally', '민수'],
['enemy', 'Kiwi'],
],
);
// 다시 분석하면 이전 결과는 기록으로 남는다
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result, players: input.players, model: 'm2', createdBy: { id: 'u1', name: '하늘' }, meta: {} } });
const info2 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
assert.equal(info2.history.length, 2);
assert.equal(info2.analysis!.model, 'm2');
assert.equal(info2.history.filter((h) => h.current).length, 1);
// 표시 이름(실명 숨기기): 이름을 바꾸기 전에 시작한 분석(자료 · 요약에 예전 이름)이 바꾼 뒤에 도착해도 예전 이름이 남지 않는다
ctx.store.setDisplayNames({ u1: '별명' });
assert.equal(ctx.store.getUser('u1')?.name, '별명');
const late = { ...result, summary: '하늘이 캐리했다' };
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result: late, players: input.players, model: 'm3', createdBy: { id: 'u1', name: '하늘' }, meta: {} } });
const raw = () => JSON.stringify(ctx.store.db.prepare('SELECT created_by, result FROM culprit_analyses').all());
assert.ok(!raw().includes('하늘'), raw());
const info3 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
assert.equal(info3.analysis!.result.summary, '별명이 캐리했다');
assert.equal(info3.analysis!.createdBy.name, '별명');
assert.ok(info3.analysis!.players.some((p) => p.name === '별명'));
// 같은 이름으로 다시 받아도(이미 바뀐 유저는 건너뛰는 경우) 그대로 깨끗하다
ctx.store.setDisplayNames({ u1: '별명' });
assert.ok(!raw().includes('하늘'));
await api.close();
});
test('녹음 안내 문구: 예전 기본 문구는 AI 분석 안내가 들어간 새 기본 문구로, 직접 고친 문구는 그대로', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-tts-'));
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ discord: { ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.' } }));
assert.equal(new SettingsStore(dir).get().discord.ttsText, DEFAULT_TTS_TEXT);
assert.match(DEFAULT_TTS_TEXT, /AI 경기 분석에 쓰일 수 있어요/);
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ discord: { ttsText: '녹음 중입니다' } }));
assert.equal(new SettingsStore(dir).get().discord.ttsText, '녹음 중입니다');
});

View File

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

92
app/test/fixtures/culprit-seed.ts vendored Normal file
View File

@@ -0,0 +1,92 @@
// 범인찾기 테스트용: 앱 코어 일부(기록 DB · 타임라인 · 게임 관리 · 범인찾기)와 시연 경기 (앱 · 사이트 서버 테스트가 같이 쓴다)
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 { GameAssets } from '../../src/core/games/assets.ts';
import { GameManager } from '../../src/core/games/manager.ts';
import { Culprit } from '../../src/core/culprit.ts';
import { buildApi } from '../../src/core/api/server.ts';
import { Bus } from '../../src/core/util/events.ts';
import { makeDemoValorant, AGENT } from './demo-matches.ts';
export const MIN = 60000;
export function setup() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-culprit-'));
const store = new Store(path.join(dir, 'db.sqlite'));
const timeline = new Timeline(store);
const assets = new GameAssets(path.join(dir, 'cache'));
// 네트워크 없이: 요원 이름 · 역할만 넣어 둔다
assets.val = {
at: Date.now(),
agents: {
[AGENT.jett]: { name: '제트', icon: '', role: '타격대', abilities: {} },
[AGENT.sage]: { name: '세이지', icon: '', role: '감시자', abilities: {} },
},
maps: {},
weapons: {},
tiers: {},
modes: {},
clientVersion: null,
} as any;
const bus = new Bus();
const stt: any = { onMatchStart: async () => undefined, onMatchEnd: async () => undefined };
const worker: any = { on: () => undefined, off: () => undefined };
const games = new GameManager(store, assets, worker, stt, timeline, bus, () => ({}) as any, () => null);
const culprit = new Culprit(store, timeline, games);
return { dir, store, timeline, assets, bus, games, culprit };
}
/** 발로란트 시연 경기 + 녹음 세션 + 대화 4문장 */
export function seedValorant(ctx: ReturnType<typeof setup>, opts: { sessionStartOffsetMs?: number; pending?: boolean } = {}) {
const { store, games } = ctx;
const VS = Date.now() - 3 * 3600_000;
const md = makeDemoValorant(VS);
const id = 'val-demo';
const users = [
{ id: 'u1', name: '하늘', puuid: 'p-sh' },
{ id: 'u2', name: '민수', puuid: 'p-ms' },
{ id: 'u9', name: '도윤', puuid: null },
];
for (const u of users) {
store.upsertUser({ id: u.id, name: u.name, avatar: null });
if (u.puuid) store.setAccounts(u.id, [{ puuid: u.puuid, riotId: `${u.name}#X` }]);
}
store.startSession('s1', 'g', 'c', '음성', VS - 5 * MIN + (opts.sessionStartOffsetMs ?? 0));
games.matchStarted({ id, game: 'valorant', startedAt: VS, map: md.matchInfo.mapId, mode: 'competitive', queue: 'competitive', detail: { live: true } });
games.matchEnded(id, VS + md.matchInfo.gameLengthMillis);
(games.adapters[0] as any).applyDetails(id, md, 'p-sh', VS);
const rounds = store.rounds(id);
const say = (uid: string, round: number, sec: number, text: string, status = 'realtime') => {
const ts = rounds[round - 1].combat_at + sec * 1000;
const uid2 = `${uid}-${round}-${sec}`;
store.insertUtterance({ id: uid2, session_id: 's1', user_id: uid, started_at: ts, ended_at: ts + 1500, audio_path: null, match_id: id });
if (status !== 'pending')
store.updateUtteranceResult(uid2, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'small', status: status as any });
};
say('u1', 3, 5, '현우야 같이 가 기다려 둘 있어');
say('u2', 3, 9, '아 그냥 간다 내가 뚫을게');
say('u9', 5, 2, '나 돈 없어 세이브할게');
say('u1', 7, 4, '스파이크 설치됐어 해체 들어가', opts.pending ? 'pending' : 'realtime');
store.endSession('s1', VS + md.matchInfo.gameLengthMillis + 5 * MIN);
return { id, VS, md };
}
/** 앱 로컬 API (사이트 서버가 중계로 부르는 것과 같은 Fastify) */
export function culpritApi(ctx: ReturnType<typeof setup>) {
return buildApi({
store: ctx.store,
timeline: ctx.timeline,
games: ctx.games,
dict: {} as any,
culprit: ctx.culprit,
bus: ctx.bus,
settings: () => ({}) as any,
trainingDir: () => ctx.dir,
overviewExtra: () => ({ guild: null, recording: { active: false, channel: null, since: null, participants: [] } }),
version: 'test',
});
}

View File

@@ -37,7 +37,7 @@ function loc() {
}
export const VAL_PLAYERS = [
{ subject: 'p-sh', gameName: '승한', tagLine: 'KR1', teamId: 'Blue', characterId: AGENT.jett },
{ subject: 'p-sh', gameName: '하늘', tagLine: 'KR1', teamId: 'Blue', characterId: AGENT.jett },
{ subject: 'p-ms', gameName: '민수', tagLine: '0707', teamId: 'Blue', characterId: AGENT.sova },
{ subject: 'p-jw', gameName: '지우', tagLine: 'KR2', teamId: 'Blue', characterId: AGENT.sage },
{ subject: 'p-hw', gameName: '현우', tagLine: 'HW1', teamId: 'Blue', characterId: AGENT.omen },
@@ -100,6 +100,11 @@ export function makeDemoValorant(gameStart: number) {
score: kills.filter((k) => k.killer === p.subject).length * 200 + range(0, 150),
economy: { spent: pistol ? 800 : range(1500, 4700), remaining: range(0, 3000), loadoutValue: 0, weapon: pistol ? WEAPON.classic : pick([WEAPON.vandal, WEAPON.phantom]), armor: '' },
}));
// 피해량 · 장비 값 (난수를 더 쓰지 않는다: 다른 시연 데이터가 바뀌지 않게)
for (const ps of playerStats as any[]) {
ps.damage = ps.kills.map((k: any) => ({ receiver: k.victim, damage: 140 + (k.gameTime % 61), headshots: k.gameTime % 3 === 0 ? 1 : 0, bodyshots: 2, legshots: k.gameTime % 5 === 0 ? 1 : 0 }));
ps.economy.loadoutValue = pistol ? 800 : ps.economy.spent + 900;
}
for (const ps of playerStats) stats[ps.subject].score += ps.score;
roundResults.push({
roundNum: i,
@@ -127,7 +132,7 @@ export function makeDemoValorant(gameStart: number) {
// ------------------------------------------------------------------ 롤
const LOL = [
{ pid: 1, champ: 103, team: 100, puuid: 'l-sh', name: '승한', tag: 'KR1' }, // 아리 미드
{ pid: 1, champ: 103, team: 100, puuid: 'l-sh', name: '하늘', tag: 'KR1' }, // 아리 미드
{ pid: 2, champ: 64, team: 100, puuid: 'l-ms', name: '민수', tag: '0707' }, // 리 신
{ pid: 3, champ: 86, team: 100, puuid: 'l-hw', name: '현우', tag: 'HW1' }, // 가렌
{ pid: 4, champ: 81, team: 100, puuid: 'l-jw', name: '지우', tag: 'KR2' }, // 이즈리얼
@@ -138,6 +143,13 @@ const LOL = [
{ pid: 9, champ: 222, team: 200, puuid: 'r-4', name: 'Nox', tag: '0420' }, // 징크스
{ pid: 10, champ: 89, team: 200, puuid: 'r-5', name: 'Mint', tag: '7777' }, // 레오나
];
const LANE = [
{ lane: 'MIDDLE', role: 'SOLO' },
{ lane: 'JUNGLE', role: 'NONE' },
{ lane: 'TOP', role: 'SOLO' },
{ lane: 'BOTTOM', role: 'DUO_CARRY' },
{ lane: 'BOTTOM', role: 'DUO_SUPPORT' },
];
export function makeDemoLol() {
seed = 23;
const dur = 28 * 60;
@@ -173,7 +185,13 @@ export function makeDemoLol() {
if ([13, 19].includes(m)) events.push({ type: 'BUILDING_KILL', timestamp: m * 60000 + 15000, killerId: 8, teamId: 100, buildingType: 'TOWER_BUILDING', position: { x: 5846, y: 6396 } });
events.sort((a, b) => a.timestamp - b.timestamp);
const pf: Record<string, any> = {};
for (const p of LOL) pf[String(p.pid)] = { totalGold: Math.round((p.team === 100 ? ga : gr) / 5) };
for (const p of LOL)
pf[String(p.pid)] = {
totalGold: Math.round((p.team === 100 ? ga : gr) / 5),
minionsKilled: (p.pid - 1) % 5 === 4 || (p.pid - 1) % 5 === 1 ? m : m * (6 + (p.pid % 3)),
jungleMinionsKilled: (p.pid - 1) % 5 === 1 ? m * 5 : 0,
xp: m * 420 + p.pid * 10,
};
frames.push({ timestamp: m * 60000, participantFrames: pf, events });
}
const items = [3031, 3089, 3157, 3020, 6655, 3135];
@@ -186,7 +204,31 @@ export function makeDemoLol() {
participantId: p.pid,
championId: p.champ,
teamId: p.team,
stats: { ...st[p.pid], totalMinionsKilled: range(30, 230), neutralMinionsKilled: p.pid === 2 || p.pid === 7 ? range(120, 180) : range(0, 15), goldEarned: Math.round((p.team === 100 ? ga : gr) / 5) + range(-800, 800), item0: pick(items), item1: pick(items), item2: pick(items), champLevel: range(13, 18), win: p.team === 100 },
spell1Id: p.pid === 2 || p.pid === 7 ? 11 : 4,
spell2Id: 14,
// 라인 · 역할 (LCU 경기 기록 형식)
timeline: LANE[(p.pid - 1) % 5],
stats: {
...st[p.pid],
totalMinionsKilled: range(30, 230),
neutralMinionsKilled: p.pid === 2 || p.pid === 7 ? range(120, 180) : range(0, 15),
goldEarned: Math.round((p.team === 100 ? ga : gr) / 5) + range(-800, 800),
item0: pick(items),
item1: pick(items),
item2: pick(items),
champLevel: range(13, 18),
win: p.team === 100,
// 범인찾기용 추가 지표 (난수를 더 쓰지 않는다: 다른 시연 데이터가 바뀌지 않게)
totalDamageDealtToChampions: 9000 + p.pid * 1700,
totalDamageTaken: 15000 + ((p.pid * 3700) % 11000),
visionScore: (p.pid - 1) % 5 === 4 ? 62 : 14 + p.pid * 2,
wardsPlaced: (p.pid - 1) % 5 === 4 ? 48 : 9 + p.pid,
wardsKilled: 3 + (p.pid % 4),
visionWardsBoughtInGame: (p.pid - 1) % 5 === 4 ? 9 : 2,
damageDealtToObjectives: 4000 + p.pid * 900,
damageDealtToTurrets: 1200 + p.pid * 400,
timeCCingOthers: 10 + p.pid * 3,
},
})),
participantIdentities: LOL.map((p) => ({ participantId: p.pid, player: { puuid: p.puuid, gameName: p.name, tagLine: p.tag } })),
teams: [

View File

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

1
app/test/fixtures/opgg-sample.json vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -50,7 +50,7 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
items: {},
};
const s = defaultSettings();
store.upsertUser({ id: 'owner', name: '승한', avatar: null });
store.upsertUser({ id: 'owner', name: '하늘', avatar: null });
const gm = new GameManager(store, assets, worker, stt, tl, bus, () => s, () => 'owner');
gm.start();
try {
@@ -65,6 +65,14 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
await until(() => store.events('val-m-0001').filter((e) => e.type === 'chat').length === 2, 5000, 'chat');
mock.st.ally = 1;
await until(() => store.events('val-m-0001').some((e) => e.type === 'round_end'), 5000, 'live round');
// 지금 게임 상태 (앱 게임 연동 탭 · 사이트)
const lv = gm.live().find((g) => g.game === 'valorant')!;
assert.equal(lv.phase, '경기 중');
assert.equal(lv.mode, '경쟁전');
assert.equal(lv.round, 2);
assert.deepEqual(lv.score, { ally: 1, enemy: 0 });
assert.equal(lv.self?.name, '하늘#KR1');
await until(() => live.some((e) => e.type === 'games.state' && e.data[0].inMatch), 5000, 'games.state');
// 발화 하나 (경기 중)
store.insertUtterance({ id: 'u-val', session_id: null, user_id: 'owner', started_at: Date.now(), ended_at: Date.now() + 500, audio_path: null, match_id: gm.liveMatchAt(Date.now()) });
assert.equal(store.getUtterance('u-val')!.match_id, 'val-m-0001');
@@ -87,12 +95,19 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
mock.st.lolPhase = 'InProgress';
mock.st.lolLive = lolLiveData(120, [
{ EventID: 0, EventName: 'GameStart', EventTime: 0.05 },
{ EventID: 1, EventName: 'ChampionKill', EventTime: 75.2, KillerName: '승한', VictimName: '적1', Assisters: ['민수'] },
{ EventID: 1, EventName: 'ChampionKill', EventTime: 75.2, KillerName: '하늘', VictimName: '적1', Assisters: ['민수'] },
{ EventID: 2, EventName: 'DragonKill', EventTime: 90.0, KillerName: '민수', DragonType: 'Fire', Stolen: 'False' },
{ EventID: 3, EventName: 'TurretKilled', EventTime: 95.0, KillerName: '승한', TurretKilled: 'Turret_T2_R_03_A' },
{ EventID: 3, EventName: 'TurretKilled', EventTime: 95.0, KillerName: '하늘', TurretKilled: 'Turret_T2_R_03_A' },
]);
await until(() => !!store.getMatch('lol-7001'), 5000, 'lol start');
await until(() => store.events('lol-7001').length >= 4, 5000, 'lol events');
const ll = gm.live().find((g) => g.game === 'lol')!;
assert.equal(ll.phase, '경기 중');
assert.equal(ll.mode, '솔로 랭크');
assert.equal(ll.self?.character, '아리');
assert.equal(ll.self?.kda, '3/1/2');
assert.deepEqual(ll.teamKills, { ally: 4, enemy: 2 });
assert.equal(ll.gameTimeSec, 120);
const lev = store.events('lol-7001');
const chat = lev.find((e) => e.type === 'chat')!;
assert.equal(JSON.parse(chat.data).text, '정글 갱 갈게요');
@@ -121,3 +136,23 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
store.close();
}
});
test('발로란트 데스매치: 경기 전체가 라운드 1개로 와도 라운드 · 에이스를 만들지 않는다', async () => {
const { processMatchDetails } = await import('../src/core/games/valorant.ts');
const { GameAssets } = await import('../src/core/games/assets.ts');
const { makeValDetails, SELF } = await import('./fixtures/make-val-details.ts');
const md = makeValDetails(1_000_000);
md.matchInfo.queueID = 'deathmatch';
// 한 "라운드"에 한 사람이 5킬 (데스매치에서는 흔함)
const r0 = md.roundResults[0];
const ps = r0.playerStats.find((p: any) => p.subject === SELF)!;
const k = ps.kills[0];
ps.kills = Array.from({ length: 6 }, (_, i) => ({ ...k, gameTime: k.gameTime + i * 1000, victim: `enemy-${i}` }));
md.roundResults = [r0];
const res = processMatchDetails(md, SELF, new GameAssets(tmp()), 'val-dm', 1_000_000);
assert.equal(res.rounds.length, 0);
assert.equal(res.roundsDetail.length, 0);
assert.ok(!res.events.some((e) => e.type === 'round_end' || e.type === 'ace' || e.type === 'multikill'));
assert.ok(res.events.filter((e) => e.type === 'kill').length >= 6);
assert.equal(res.result.score, null);
});

View File

@@ -61,6 +61,7 @@ export async function startMockRiot(dir: string) {
],
[/^\/chat\/v4\/presences$/, () => [200, { presences: [{ puuid: SELF, product: 'valorant', private: presence() }] }]],
[/^\/chat\/v6\/messages$/, () => [200, { messages: st.valMessages }]],
[/^\/chat\/v1\/session$/, () => [200, { game_name: '하늘', game_tag: 'KR1', puuid: SELF }]],
// ---- glz
[/^\/core-game\/v1\/players\/(.+)$/, () => (st.valState === 'INGAME' ? [200, { Subject: SELF, MatchID: st.valMatchId }] : [404, { errorCode: 'RESOURCE_NOT_FOUND' }])],
[
@@ -74,7 +75,7 @@ export async function startMockRiot(dir: string) {
// ---- LCU
[/^\/lol-gameflow\/v1\/gameflow-phase$/, () => [200, st.lolPhase]],
[/^\/lol-gameflow\/v1\/session$/, () => [200, { phase: st.lolPhase, gameData: { gameId: st.lolGameId, queue: { description: '솔로 랭크', id: 420 } } }]],
[/^\/lol-summoner\/v1\/current-summoner$/, () => [200, { puuid: 'lol-self', gameName: '승한', tagLine: 'KR1' }]],
[/^\/lol-summoner\/v1\/current-summoner$/, () => [200, { puuid: 'lol-self', gameName: '하늘', tagLine: 'KR1' }]],
[/^\/lol-chat\/v1\/conversations$/, () => [200, st.lolPhase === 'ChampSelect' ? [{ id: 'cs1@champ-select.kr', type: 'championSelect' }] : []]],
[/^\/lol-chat\/v1\/conversations\/(.+)\/messages$/, () => [200, [{ id: 'msg1', body: '정글 갱 갈게요', fromSummonerId: 11, timestamp: new Date(Date.now() - 5000).toISOString(), type: 'groupchat' }]]],
[/^\/lol-summoner\/v1\/summoners\/(\d+)$/, () => [200, { gameName: '민수' }]],
@@ -115,8 +116,8 @@ export function lolLiveData(gameTime: number, events: any[]) {
items: [{ itemID: 3031, displayName: '무한의 대검', count: 1 }],
});
return {
activePlayer: { riotId: '승한#KR1', summonerName: '승한', currentGold: 500 },
allPlayers: [player('승한', 'Ahri', '아리', 'ORDER', 3), player('민수', 'LeeSin', '리 신', 'ORDER', 1), player('적1', 'Garen', '가렌', 'CHAOS', 2)],
activePlayer: { riotId: '하늘#KR1', summonerName: '하늘', currentGold: 500 },
allPlayers: [player('하늘', 'Ahri', '아리', 'ORDER', 3), player('민수', 'LeeSin', '리 신', 'ORDER', 1), player('적1', 'Garen', '가렌', 'CHAOS', 2)],
events: { Events: events },
gameData: { gameMode: 'CLASSIC', gameTime, mapName: 'Map11', mapNumber: 11 },
};
@@ -133,7 +134,7 @@ function lolHistory() {
{ participantId: 6, championId: 86, teamId: 200, stats: { kills: 4, deaths: 6, assists: 2, totalMinionsKilled: 170, neutralMinionsKilled: 0, goldEarned: 8500, win: false } },
],
participantIdentities: [
{ participantId: 1, player: { puuid: 'lol-self', gameName: '승한', tagLine: 'KR1' } },
{ participantId: 1, player: { puuid: 'lol-self', gameName: '하늘', tagLine: 'KR1' } },
{ participantId: 2, player: { puuid: 'lol-2', gameName: '민수', tagLine: 'KR1' } },
{ participantId: 6, player: { puuid: 'lol-6', gameName: '적1', tagLine: 'KR9' } },
],

57
app/test/rating.test.ts Normal file
View File

@@ -0,0 +1,57 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { rateLol, rateValorant, type MatchPlayer, type MatchRound } from '@gvr/shared';
/** OP.GG 공식 MCP 에서 받은 실제 경기 (tools/opscore-fit/make_fixture.py). 우리 계산이 실제 OP.GG 점수와 가까운지 본다 */
const sample = JSON.parse(fs.readFileSync(new URL('./fixtures/opgg-sample.json', import.meta.url), 'utf8'));
test('기록 점수 (롤): 실제 OP.GG OP스코어와 평균 오차 · 팀 최하위 일치', () => {
let err = 0;
let n = 0;
let teams = 0;
let lowestHit = 0;
for (const g of sample.lol) {
const players = g.players as (MatchPlayer & { opgg: number })[];
const r = rateLol(players, g.minutes, g.allyWin);
for (const p of players) {
err += Math.abs(r.get(p.puuid)!.score - p.opgg);
n++;
}
for (const team of ['BLUE', 'RED']) {
const ps = players.filter((p) => p.team === team);
teams++;
const ours = ps.reduce((a, b) => (r.get(a.puuid)!.score <= r.get(b.puuid)!.score ? a : b));
const theirs = ps.reduce((a, b) => (a.opgg <= b.opgg ? a : b));
if (ours === theirs) lowestHit++;
}
// 이긴 팀 1등 MVP, 진 팀 1등 ACE
const badges = [...r.values()].map((x) => x.badge).filter(Boolean).sort();
assert.deepEqual(badges, ['ACE', 'MVP']);
}
const mae = err / n;
assert.ok(mae < 0.75, `평균 오차 ${mae.toFixed(2)}`);
assert.ok(lowestHit / teams >= 0.75, `팀 최하위 일치 ${lowestHit}/${teams}`);
});
test('기록 점수 (발로란트): 실제 OP.GG OP스코어와 평균 오차', () => {
let err = 0;
for (const v of sample.valorant) {
const rounds = Array.from({ length: v.rounds }, (_, i) => ({ win: i < v.wonRounds }) as MatchRound);
const r = rateValorant([v.player], rounds).get('v')!;
assert.equal(r.basic, false);
err += Math.abs(r.score - v.opgg);
}
const mae = err / sample.valorant.length;
assert.ok(mae < 0.7, `평균 오차 ${mae.toFixed(2)}`);
});
test('기록 점수: 추가 지표가 없는 예전 경기는 기본 기록 모델, 설명은 상식 방향만', () => {
const g = sample.lol[0];
const bare = g.players.map(({ stats: _s, ...p }: any) => p);
const r = rateLol(bare, g.minutes, g.allyWin);
assert.ok([...r.values()].every((x) => x.basic && x.score >= 0 && x.score <= 10));
// 데스가 가장 많은 사람에게 "데스" 가 강점으로 붙지 않는다
const full = rateLol(g.players, g.minutes, g.allyWin);
for (const x of full.values()) for (const part of x.parts) if (/데스/.test(part.text)) assert.equal(part.good, false, part.text);
});

121
app/test/security.test.ts Normal file
View File

@@ -0,0 +1,121 @@
// 앱 통신 보안: 사이트 서버 주소는 https 만 (로그인 토큰 · 기기 키 · 기록), 인증서 검증을 끄는 건 이 PC 안 주소뿐
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 { AppAuth } from '../src/core/auth.ts';
import { RemoteGateway } from '../src/core/discord/gateway.ts';
import { request } from '../src/core/games/riot.ts';
import { registerDevice } from '../src/core/relay/client.ts';
import { SettingsStore } from '../src/core/settings.ts';
import { secureServerUrl } from '../src/core/util/secure-url.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-sec-'));
test('사이트 서버 주소: https 와 이 PC 안 http 만 허용', () => {
assert.equal(secureServerUrl('https://gvr.tkrmagid.kr/'), 'https://gvr.tkrmagid.kr');
assert.equal(secureServerUrl(' https://gvr.tkrmagid.kr '), 'https://gvr.tkrmagid.kr');
assert.equal(secureServerUrl('http://127.0.0.1:8080'), 'http://127.0.0.1:8080');
assert.equal(secureServerUrl('http://localhost:8080/'), 'http://localhost:8080');
for (const bad of ['http://gvr.tkrmagid.kr', 'http://192.168.10.5:2972', 'ws://gvr.tkrmagid.kr', 'ftp://x', 'https://user:pw@gvr.tkrmagid.kr', 'gvr.tkrmagid.kr', 'http://127.0.0.1.evil.example'])
assert.throws(() => secureServerUrl(bad), /https|올바르지|아이디/, bad);
});
test('암호화되지 않은 주소로는 로그인 토큰 · 기기 등록 코드를 보내지 않는다', async () => {
const real = globalThis.fetch;
const sent: string[] = [];
globalThis.fetch = (async (u: any, init?: any) => (sent.push(String(u)), real(u, init))) as typeof fetch;
try {
const st = new SettingsStore(tmp());
st.update({ site: { serverUrl: 'http://gvr.tkrmagid.kr' } });
st.setSecret('appToken', 'secret-app-token');
const auth = new AppAuth(st, { version: 't', openUrl: () => undefined });
await auth.check();
await auth.login();
await assert.rejects(registerDevice('http://gvr.tkrmagid.kr', 'ABCD-EFGH', 'pc'), /https/);
const gw = new RemoteGateway({ serverUrl: () => 'http://gvr.tkrmagid.kr', appToken: () => 'secret-app-token', version: 't' });
await assert.rejects(gw.start(), /https/);
await gw.stop();
assert.deepEqual(sent, [], '아무 요청도 나가면 안 된다');
} finally {
globalThis.fetch = real;
}
});
test('게임 연동: 인증서 검증을 끄는 건 이 PC 안 주소뿐 (local 을 잘못 넘겨도 바깥 주소는 거절)', async () => {
await assert.rejects(request('https://pd.ap.a.pvp.net/x', { local: true }), /로컬 API 가 아닌 주소/);
});
test('인증서: NODE_TLS_REJECT_UNAUTHORIZED=0 이어도 믿을 수 없는 인증서의 서버로는 토큰 · 기기 키를 보내지 않는다 (https · wss)', async () => {
const { execFileSync } = await import('node:child_process');
const https = await import('node:https');
const { WebSocketServer } = await import('ws');
const { RelayClient } = await import('../src/core/relay/client.ts');
const { Bus } = await import('../src/core/util/events.ts');
// 가짜 서버 (자체 서명 인증서): 받은 요청의 인증 헤더를 모두 기록한다
const dir = tmp();
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-subj', '/CN=127.0.0.1', '-addext', 'subjectAltName=IP:127.0.0.1', '-days', '1', '-keyout', path.join(dir, 'k.pem'), '-out', path.join(dir, 'c.pem')], { stdio: 'ignore' });
const got: string[] = [];
const srv = https.createServer({ key: fs.readFileSync(path.join(dir, 'k.pem')), cert: fs.readFileSync(path.join(dir, 'c.pem')) }, (req, res) => {
got.push(`${req.url} ${req.headers.authorization ?? ''}`);
res.setHeader('content-type', 'application/json');
res.end('{"state":"pending","user":{"id":"1","name":"x","avatar":null},"role":"user","serverTime":0}');
});
const wss = new WebSocketServer({ noServer: true });
srv.on('upgrade', (req, socket, head) => {
got.push(`WS ${req.url} ${req.headers.authorization ?? ''}`);
wss.handleUpgrade(req, socket, head, (ws) => ws.close());
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
const base = `https://127.0.0.1:${(srv.address() as any).port}`;
const prev = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const origWarn = process.emitWarning;
process.emitWarning = () => undefined;
try {
// 대조군: 기본 fetch 는 이 변수 때문에 실제로 토큰을 보낸다 (테스트가 우회를 잡아낼 수 있는지 확인)
await fetch(`${base}/control`, { headers: { authorization: 'Bearer control' } });
assert.deepEqual(got, ['/control Bearer control']);
got.length = 0;
const st = new SettingsStore(tmp());
st.update({ site: { serverUrl: base, deviceId: 'dev1' } });
st.setSecret('appToken', 'secret-app-token');
st.setSecret('deviceKey', 'secret-device-key');
// 로그인 확인 (https)
const auth = new AppAuth(st, { version: 't', openUrl: () => undefined });
const a = await auth.check();
assert.notEqual(a.status, 'ok');
assert.match(a.error ?? '', /연결할 수 없습니다/);
// 기기 등록 (https)
await assert.rejects(registerDevice(base, 'ABCD-EFGH', 'pc'));
// 겜녹이 봇 중계 (wss)
const gw = new RemoteGateway({ serverUrl: () => base, appToken: () => 'secret-app-token', version: 't' });
const started = gw.start().then(() => 'ready', () => 'failed');
await new Promise((r) => setTimeout(r, 1500));
await gw.stop();
assert.equal(await Promise.race([started, new Promise((r) => setTimeout(() => r('pending'), 100))]) === 'ready', false);
// 사이트 기기 중계 (wss)
const relay = new RelayClient({} as any, new Bus(), () => ({ serverUrl: base, deviceId: 'dev1', deviceKey: 'secret-device-key', name: 'pc', version: 't', guildId: null }));
relay.start();
await new Promise((r) => setTimeout(r, 1500));
assert.notEqual(relay.status.state, 'online');
relay.stop();
assert.deepEqual(got, [], '믿을 수 없는 인증서의 서버에 요청 · 토큰이 가면 안 된다');
// 앱 시작 때 이 변수를 지우면 (main.ts · startCore) 사이트 밖 통신(일반 fetch: 다른 봇 · Riot 원격 API 등)도 다시 검증한다
const { hardenTlsEnv } = await import('../src/core/util/secure-http.ts');
hardenTlsEnv();
assert.equal(process.env.NODE_TLS_REJECT_UNAUTHORIZED, undefined);
await assert.rejects(fetch(`${base}/after-harden`, { headers: { authorization: 'Bearer x' } }));
assert.deepEqual(got, []);
} finally {
if (prev === undefined) delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
else process.env.NODE_TLS_REJECT_UNAUTHORIZED = prev;
process.emitWarning = origWarn;
srv.closeAllConnections();
srv.close();
}
});

View File

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

BIN
assets/app/splash.bmp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 326 KiB

View File

@@ -18,6 +18,8 @@ COPY site/server/package.json site/server/package-lock.json ./
RUN npm ci --omit=dev --no-audit --no-fund && npm cache clean --force
COPY --from=build /src/site/server/dist ./dist
COPY --from=build /src/site/web/dist ./web
# 범인찾기 지시문 · 지식 묶음 (dist/main.js 가 ../prompt 에서 읽는다)
COPY site/server/prompt ./prompt
VOLUME /data
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s CMD wget -qO- http://127.0.0.1:8080/healthz || exit 1

View File

@@ -13,5 +13,7 @@ print(f"DISCORD_BOT_TOKEN={c['token']}")
print(f"SESSION_SECRET={secrets.token_urlsafe(48)}")
print("ALLOWED_GUILD_IDS=457514742940958731")
print("OWNER_DISCORD_IDS=293719842274541579")
a = json.load(open('/home/claude/.config/ejclaw/secrets.json'))['credentials'].get('anthropic.api/game-voice-recorder')
if a: print(f"ANTHROPIC_API_KEY={a['token']}")
PY
echo ".env 작성 완료"

View File

@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# 범인찾기 Claude API 키를 .5 의 사이트 서버 .env 에 넣거나 바꾼다 (다른 값 · 로그인 세션은 그대로).
# 키는 secrets.json 에서 읽어 원격에 바로 쓰고, 로컬 파일 · 명령줄에 남기지 않는다. 적용: deploy/site/deploy.sh
set -euo pipefail
HOST=root@192.168.10.5
DIR=/root/other/game-voice-recorder
python3 - <<'PY' | ssh -o BatchMode=yes $HOST "cd $DIR && test -f .env && umask 077 && grep -v '^ANTHROPIC_API_KEY=' .env > .env.new; cat >> .env.new && mv .env.new .env && chmod 600 .env"
import json
print(f"ANTHROPIC_API_KEY={json.load(open('/home/claude/.config/ejclaw/secrets.json'))['credentials']['anthropic.api/game-voice-recorder']['token']}")
PY
echo "ANTHROPIC_API_KEY 설정 완료"

Binary file not shown.

View File

@@ -10,7 +10,7 @@ app/ 게임 PC 앱 (Electron + Node.js 코어, TypeScript)
src/core/ 헤드리스 코어. Electron 없이 `node` 로도 돈다 (리눅스 테스트용)
src/main/ Electron 메인 프로세스 (트레이, 창, 마법사, safeStorage)
src/renderer/ 설정 창 · 첫 실행 마법사 UI
worker/ Python STT 워커 (faster-whisper, VAD, 음량 정규화, OCR, 모델 관리, 파인튜닝)
worker/ Python STT 워커 (faster-whisper, VAD, 음량 정규화, 롤 로그 채팅, 모델 관리, 파인튜닝)
site/server/ 사이트 서버 (Fastify, Discord OAuth2, 기기 중계, 게임 이미지 캐시)
site/web/ 사이트 프런트엔드 (React + Vite)
packages/shared/ 앱·사이트가 같이 쓰는 TypeScript 타입 (protocol.ts)
@@ -71,13 +71,7 @@ tools/ 사전 생성기, 테스트 도구(목 Riot 서버, 음성
// "speech_ratio":0.82, "duration_s":2.4,
// "model":"large-v3-turbo", "elapsed_ms":310}}
{"id":"8","op":"ocr_start","window_title":"League of Legends (TM) Client",
"region":{"x":0,"y":0.62,"w":0.32,"h":0.25}, // 창 크기 대비 비율 (채팅 영역)
"fps":3, "lang":"ko"}
// 이벤트: {"event":"ocr_line","ts":1760000000000,"text":"[12:34] [팀] 민수 (아리): 드래곤 가자",
// "parsed":{"game_time":"12:34","channel":"team","sender":"민수","champion":"아리","message":"드래곤 가자"}}
{"id":"9","op":"ocr_stop"}
{"id":"10","op":"ocr_image","path":"..."} // 테스트용: 이미지 한 장 OCR → {"lines":[...]}
// 화면 OCR(ocr_start · ocr_stop · ocr_image)은 v1.3.3 에서 뺐다. 롤 게임 중 채팅은 r3dlog_read (worker/README.md)
{"id":"11","op":"train", ...} // 파인튜닝 (worker/gvr_worker/finetune 참고, M8)
{"id":"99","op":"shutdown"}
@@ -94,6 +88,7 @@ tools/ 사전 생성기, 테스트 도구(목 Riot 서버, 음성
GVR-Data/
settings.json 일반 설정 (평문)
secrets.bin 비밀값 (Windows: Electron safeStorage = DPAPI, 헤드리스: 0600 평문 JSON)
앱 로그인 토큰 · 마지막 로그인 확인(오프라인 3일 유예용) 포함. 겜녹이 봇 토큰은 없다 (8장)
gvr.sqlite 기록 DB
audio/YYYY-MM-DD/<utteranceId>.ogg
training/<sampleId>.ogg 교정한 문장의 음성 조각 (자동 삭제 제외, A3)
@@ -119,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) — 사이트 서버가 그대로 중계
@@ -136,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` ·
@@ -156,7 +155,7 @@ type TimelineItem =
```
`event.data` 예: 킬 `{killer:{puuid,name,agent|champion,team,userId?}, victim:{...}, assists:[...], weapon:{id,name,icon}, headshot?}` ·
채팅 `{sender:{name,puuid?,userId?}, channel:'team'|'all'|'party', text, source:'api'|'ocr'|'lcu'}` ·
채팅 `{sender:{name,puuid?,userId?}, channel:'team'|'all'|'party', text, source:'api'|'lcu'|'log'|'ocr'(v1.3.2 까지 기록)}` ·
오브젝트 `{object:'dragon'|'baron'|'herald'|'grub'|'tower'|'inhibitor', subtype?, team, killer}` ·
라운드 종료 `{round, winner:'ally'|'enemy'|teamId, result:'Elimination'|'Bomb detonated'|..., score:{ally,enemy}}`
@@ -208,4 +207,33 @@ type TimelineItem =
| `/api/*` | 로그인 + 기기 온라인이면 앱으로 중계, 오프라인이면 `503 {error:'device_offline'}` |
| `WS /ws` | 브라우저용. `{type:'status',data}` + 5장 이벤트 |
| `POST /admin/registration-code` | 관리자 전용 → `{code, expiresAt}` |
| `POST /auth/app/begin` | 앱 로그인 시작 → `{id, secret, url, expiresAt}` (url 을 브라우저로 연다, 10분 유효) |
| `GET /auth/app/start/:id` | 브라우저: state 쿠키(`app.<id>.<nonce>`) → 디스코드 OAuth → 같은 `/auth/discord/callback` |
| `POST /auth/app/poll` | `{id, secret}` → `{state:'pending'}` · `{state:'ok', token, user, role}` · `{state:'not_registered', user}` (결과는 한 번만) |
| `GET /app/me` | `Authorization: Bearer <앱 토큰>` → `{user, role, serverTime}`. 미등록 403 `not_registered`, 토큰 무효 401 |
| `WS /app/bot/ws` | `Authorization: Bearer <앱 토큰>`. 겜녹이 봇 중계 (8장). 토큰 무효 · 미등록 401, 연결 중 등록 해제 · 로그아웃되면 4401 로 끊는다 |
| `POST /auth/app/logout` | 앱 토큰 무효화 |
| `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 이미지 캐시 프록시 |
## 8. 겜녹이 봇 중계 (v1.2.1~)
겜녹이 봇 토큰은 사이트 서버에만 있다 (앱에 보내지 않는다). 서버가 discord.js 로 디스코드 게이트웨이에 한 번 붙고
(`site/server/src/discord-source.ts`), 로그인한 앱은 `WS /app/bot/ws` 로 필요한 정보만 받는다 (`site/server/src/bot-broker.ts`,
앱 쪽 `app/src/core/discord/gateway.ts` 의 `RemoteGateway`. 다른 봇 모드는 `LocalGateway` 로 PC 가 직접 연결). 형식은 `packages/shared` 의 `BotGw*`.
- 서버 → 앱: `ready{me, guilds}` · `guilds` · `guild{guild, channels, voice}`(watch 응답) · `voiceState`(지켜보는 서버만) · `cmd`(슬래시 명령) ·
`vserver`/`vstate`(봇 자신의 VOICE_SERVER/STATE_UPDATE 원문 = 일회용 음성 접속 정보) · `taken` · `res`
- 앱 → 서버: `watch{guildId, commands}` · `voice{guildId, payload}`(@discordjs/voice 어댑터의 op 4) · `cmd_res{id, content}` · `req{op:'members'}`
- 권한 (앱 유저의 디스코드 아이디 기준): 서버 목록 · watch 는 그 유저가 가입한 서버만 (아니면 `watch_denied`), 채널 · 음성 상태는 그 유저가 볼 수 있는(ViewChannel) 채널만
(볼 수 없는 채널로 옮기면 "나감"으로 가린다), 음성 참여는 그 유저가 들어갈 수 있는(ViewChannel + Connect) 음성채널만. 슬래시 명령 /녹음시작 도 그 채널에 들어갈 수 있는 유저의 PC 로만 보낸다
- 권한 회수: 연결한 뒤에도 탈퇴 · 추방 · 역할 · 채널 권한 변경 이벤트(`access`), 음성 접속 정보를 넘기기 직전, 30초 주기로 다시 확인한다.
봇이 있는 채널에 그 유저가 더는 들어갈 수 없으면 음성 접속 정보 전달을 멈추고 봇을 빼고(op 4 null) 앱에 `taken` 을 보낸다. 서버 멤버가 아니게 되면 `watch_denied`
- 음성채널 참여: 앱의 @discordjs/voice 가 어댑터로 op 4 를 보내면 서버가 검사(지켜보는 서버 · 들어갈 수 있는 음성채널 · op 4 만, 필드를 다시 만들어)한 뒤 대신 보내고,
디스코드가 준 session_id · 음성 서버 token · endpoint 를 그 앱에만 넘긴다. 음성(UDP · DAVE)은 앱 ↔ 디스코드 음성 서버로 바로 간다 (Lavalink 와 같은 방식)
- 한 서버에서 봇은 음성채널 하나에만 있을 수 있다: 마지막으로 참여를 요청한 앱이 가져가고 이전 앱은 `taken` 을 받는다. 이전 앱의 늦은 나가기는 무시한다.
음성을 가진 앱이 끊기면 서버가 봇을 음성채널에서 뺀다
- 슬래시 명령: 서버가 받아 바로 defer 하고, 그 서버를 지켜보는 앱에 보낸다 (녹음시작: 명령한 사람의 PC → 녹음 중인 PC → 가장 최근 PC, 녹음종료: 녹음 중인 PC, 녹음제외 · 참여: 모든 PC). 첫 응답을 답장으로 쓴다
- 사이트 서버에 못 붙으면 겜녹이 봇은 쓸 수 없다 (다른 봇 모드는 상관없음)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 451 KiB

After

Width:  |  Height:  |  Size: 454 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 380 KiB

After

Width:  |  Height:  |  Size: 382 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 328 KiB

After

Width:  |  Height:  |  Size: 331 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 215 KiB

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 187 KiB

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 170 KiB

After

Width:  |  Height:  |  Size: 170 KiB

View File

@@ -128,3 +128,126 @@ VOICE E2E PASS
원인: `<|notimestamps|>` 라벨로만 학습 → 앱(faster-whisper)이 쓰는 타임스탬프 모드에서 끝맺음을 잊음. 검증도 notimestamps 로 해서 못 걸렀음.
→ 절반은 `<|0.00|> 문장 <|말끝|>` 라벨로 학습, 검증도 타임스탬프 모드로 → 위 표처럼 사전 없이도 개선
- 한계: 합성 음성과 시연 대화가 같은 TTS 엔진이라 실제 목소리에서는 개선 폭이 작을 수 있다. 실사용 교정 데이터가 2주쯤 쌓이면 게임 PC(RTX 5070 Ti)에서 다시 학습해 비교한다
## 범인찾기 v1.3.0 실제 E2E (2026-10-15)
`node --import tsx app/scripts/culprit-real-e2e.mts` — 실제 앱 코어 → 실제 사이트 서버(중계) → **실제 Claude API (claude-opus-5-5, 생각 high, 구조화 출력)** · **실제 OP.GG MCP** → 근거 확인 → 게임 PC 에 저장 → 헤드리스 브라우저로 결과 화면
| 경기 | OP.GG | 걸린 시간 | 토큰 (입력 / 캐시 쓰기 / 출력) | 비용 | 범인 |
|---|---|---|---|---|---|
| 발로란트 시연 경기 (22라운드 · 킬 156 · 대화 4문장) | 없음 (시연 경기) → 기록 점수로 | 42초 | 10,579 / 7,486 / 3,320 | $0.146 | 우리 P5 (기록 점수 공동 최하위 5.0, 이유에 동점자 P4 와 비교) · 상대 P7 (기록 1.9 경기 최하위) |
| 롤 실제 솔로 랭크 (OP.GG 에서 받은 10명 실제 스탯 + 우리 팀 2명 시험용 대화 9문장) | **10명 찾음** (실제 OP스코어와 같음) | 36초 | 1,884 / 9,041 / 2,825 | $0.109 | 우리 P5 (OP.GG 3.0 · 기록 2.1 팀 최하위) · 상대 P8 (OP.GG 4.9 · 기록 5.1 팀 최하위) |
- 진행 단계: `OP.GG 점수 찾는 중 → AI 가 읽는 중 → 근거 확인 → 완료`, 화면 오류 · CSP 위반 없음
- AI 평점은 전적 사이트 점수에서 출발해 승부처 · 대화로 조정됨 (롤 10명 AI 평점과 OP.GG 점수 차 평균 0.2점, 최대 0.5점). 범인 이유에 "OP.GG 점수 3.0으로 경기 최하위", "기록 점수는 현우와 5.0점 공동 최하위 … 그래서 Duck" 처럼 점수와 근거를 같이 씀
- 이 롤 경기에서 기록 점수와 실제 OP.GG 점수 차: 평균 0.5점, 팀 최하위 2팀 모두 일치
- 단위 · 통합 테스트: 앱 40개 · 사이트 서버 18개 통과 (`rating.test.ts`: 실제 OP.GG 표본 20경기 · 발로란트 40명으로 평균 오차와 팀 최하위 일치 확인)
- 배포: 사이트 서버(.5 `gvr-web`)에 `ANTHROPIC_API_KEY` 넣고 배포, 컨테이너 안에서 Claude API(`claude-opus-5-5` 200) · OP.GG MCP(200, 세션 받음) 연결 확인, healthz 정상
- Windows CI (be89317, full): worker_setup · ocr_lang · worker_pytest · win_smoke · worker_build · worker_exe_smoke · app_build · app_smoke 모두 PASS, 앱 버전 1.3.0 → Gitea 릴리스 v1.3.0
## 범인찾기 v1.3.1 (2026-10-15)
- OP.GG 클라이언트: 세션이 끝났다는 404 를 받으면 MCP 규격대로 새로 `initialize` 하고 한 번 다시 부른다 (가짜 서버로 재시작 → 새 세션 → 계속 사용 확인, 503 은 다시 시작하지 않고 실패)
- OP.GG "조회 실패"와 "경기 없음"을 나눈다: 결과 `meta.opgg.error`, 화면 "OP.GG 조회 실패 · 기록 점수로 분석", 지시문 "이 줄이 없으면 OP.GG 에 없는 경기이거나 조회하지 못한 경기". 실제 OP.GG: 랭크 경기 10명 찾음, 잘못된 주소 → `error` (3번 중 3번 실패: OP.GG 404)
- LOL.PS 라인전: LOL.PS 원문 정의("10, 15분 맞라이너 골드차, 경험치차, cs차이")대로 10분 값을 더해 10 · 15분 차이를 보여 준다. 참고한 원문과 구현 대응은 `tools/opscore-fit/README.md`
- 테스트: 앱 40개 · 사이트 서버 20개 통과, 화면 오류 · CSP 위반 없음
- 배포: 사이트 서버 다시 배포(지시문 · 화면 반영 확인), Windows CI (0e0a272, full) 8개 모두 PASS · 앱 버전 1.3.1 → Gitea 릴리스 v1.3.1 (v1.3.0 에 새 버전 안내)
## 범인찾기 v1.3.2 — 외부 전적 사이트 접속 제거 (2026-10-15)
사용자 결정: 전적 사이트는 "계산법을 참고"하라는 뜻이었고 실제로 연결하는 것이 아니다 → 분석할 때 OP.GG 를 찾아보던 기능(`site/server/src/opgg.ts`, 결과의 OP.GG 점수 · 조회 상태, 지시문의 OP.GG 실제 점수 줄)을 뺐다. 기록 점수(OP.GG 계산법) · 10/15분 라인전(LOL.PS 정의)은 앱이 경기 기록으로 계산한다.
`node --import tsx app/scripts/culprit-real-e2e.mts` — 실제 Claude Opus 5.5(생각 high), 외부 사이트 접속 없음 (로그에 OP.GG 0건)
| 경기 | 걸린 시간 | 토큰 (입력 / 캐시 쓰기 / 출력) | 비용 | 범인 (기록 점수 팀 최하위) |
|---|---|---|---|---|
| 발로란트 시연 경기 (22라운드, 대화 4문장) | 33초 | 10,562 / 7,382 / 2,943 | $0.138 | 우리 P5 (공동 최하위 5.0, 동점자 P4 와 비교해 이유) · 상대 P7 (1.9, 최하위) |
| 롤 시연 경기 (10 · 15분 라인전, 대화 7문장) | 36초 | 3,186 / 8,937 / 3,300 | $0.123 | 우리 P1 (2.7, 최하위) · 상대 P7 (4.5, 최하위) |
- AI 평점과 기록 점수 차: 평균 0.4점 (롤 P2 는 "용 셋 · 유충 · 바론 싹쓸이"를 근거로 기록 3.0 → AI 5.0)
- 테스트: 앱 40개 · 사이트 서버 16개 통과 (서버 테스트에 "자료에 기록 점수 칸, 지시문 '평점은 기록 점수에서 출발', OP.GG 실제 점수 없음" 확인 추가)
- 배포: 사이트 서버 다시 배포 (서버 번들 · 화면에 OP.GG 접속 코드 없음 확인, 지시문 '평점은 기록 점수에서 출발'), Windows CI (b8e76ab, full) 8개 모두 PASS · 앱 버전 1.3.2 → Gitea 릴리스 v1.3.2 (v1.3.0 · v1.3.1 에 새 버전 안내)
## v1.3.3 — 따라갈 사람 목록 · 롤 채팅 OCR 제거 · 표시 이름 (2026-10-16)
- 따라갈 사람 원인: 사이트 서버 봇 중계가 "지켜보는 서버"가 아니면 멤버 요청을 `forbidden` 으로 거절했고, 앱(`guildMembers`)이 오류를 삼켜 빈 목록이 됐다. 설정 창은 봇이 준비되자마자(지켜보기 전) 요청하므로 "선택 안 함"만 남았다. `bot-gateway.test.ts` 에 지켜보기 전 요청을 넣어 예전 서버 코드에서 `forbidden` 으로 실패하는 것을 확인한 뒤 고침. 실제 사이트 서버 봇은 M&L 87명 · 다른 서버 27명을 정상으로 받음
- 정렬: 내 계정 → 관리자(`GET /app/admins`) → 이름순 (mock 화면 확인: `민준 (나)`, `지호 · 관리자`, 나머지)
- 롤 채팅: LCU · 게임 클라이언트 API(2999) 모두 게임 중 전체 · 팀 채팅을 주지 않는다 (`lol-game-client-chat` 은 귓속말 · 파티 메시지 보내기만, 게임 중 채팅 이벤트는 Overwolf 전용이며 저장 금지). OCR 코드 · 의존성(pywinrt · mss · Pillow) 제거, r3dlog 채팅은 LCU 채팅을 지우지 않고 추가
- 표시 이름: 서버 `displayNames` · `GET /app/names` · `PUT /app/admin/names`(최고 관리자), 앱은 users · 지난 범인 분석 이름 교체. 운영 서버에 두 최고 관리자 계정 표시 이름 설정, server.json 에 실명 0건
- 저장소: 시연 · 테스트 데이터 · 화면 캡처(`docs/dev/screens`, `docs/report/img`, `docs/report/culprit/img`) · 계획서 PDF 3개를 가짜 이름으로 다시 만듦 (PDF 쪽수 그대로)
- 테스트: 앱 41 · 사이트 서버 16 · 워커 39 통과, 앱/화면 타입 검사 통과
- 배포: 사이트 서버 다시 배포(화면 번들 실명 0건, 새 API 401 응답 확인), Windows CI (b230443, full) 7개 모두 PASS (ocr_lang 단계 삭제) · 앱 버전 1.3.3 → Gitea 릴리스 v1.3.3 (v1.3.2 에 새 버전 안내)
## v1.3.4 — 슬래시 명령 응답 · 녹음 중 봇 상태 메시지 (2026-10-16)
- 원인: 사이트 서버 `discord-source.ts` 가 "그 서버를 지켜보는 앱이 없으면" 슬래시 명령을 응답 없이 무시했다 (옛 v1.1.0 PC 와 응답이 겹치지 않게 넣은 동작) → 디스코드 "애플리케이션이 응답하지 않았어요". 이제 1.5초 기다린 뒤 이유를 답한다 (`bot-gateway.test.ts`: 앱 없음 · 내 앱이 다른 서버를 지켜봄 · 아직 연결 중 세 경우 확인)
- 앱: 지켜보던 중 `watch_denied` 를 받으면 1분 뒤 다시 지켜보기
- 상태 메시지: 테스트 봇으로 `dnd + "🔴 녹음 중"` · `online + "🎙️ 대기 중 · /녹음시작"` 을 디스코드가 받는 것 확인, 배포 뒤 실제 겜녹이 봇 상태가 "🎙️ 대기 중 · /녹음시작" 인 것을 같은 서버의 테스트 봇으로 읽어 확인
- 테스트: 앱 41 · 사이트 서버 16 통과. Windows CI (db2f186, full) 7개 모두 PASS · 앱 버전 1.3.4 → Gitea 릴리스 v1.3.4 (v1.3.3 에 새 버전 안내)
## v1.3.5 — 표시 이름 빈틈 · 상태 메시지 실제 확인 (2026-10-16)
- 표시 이름: 이름을 바꾸기 전에 시작한 분석이 바꾼 뒤 저장되면 예전 이름이 남던 빈틈 (`setDisplayNames` 가 이미 바뀐 유저를 건너뜀 + 저장 경로에서 이름을 바꾸지 않음). `culprit.test.ts` 에 "바꾼 뒤 도착한 분석 · 다시 받기" 회귀 테스트 추가, 예전 코드에서 실패하는 것 확인 뒤 고침
- 상태 메시지 실제 디스코드 확인 (`site/server/scripts/presence-e2e.mts`, 테스트 봇 · 빈 음성채널): 들어간 뒤 0.2초에 `dnd "🔴 녹음 중"`, 나온 뒤 0.2초에 `online "🎙️ 대기 중 · /녹음시작"` (디스코드가 보낸 음성 상태 이벤트로 바뀜)
- 테스트: 앱 41 · 사이트 서버 16 통과
- Windows CI (3f7bf1c, full) 7개 모두 PASS · 앱 버전 1.3.5 → Gitea 릴리스 v1.3.5 (v1.3.3 · v1.3.4 에 새 버전 안내)
## v1.3.6 — 목소리 깨짐 · 알 수 없음 · 잡음 숨기기 · 사이트 로그 · 지금 게임 (2026-10-16)
사용자가 보낸 GVR-Data(발화 40개 · 데스매치 1경기)를 분석했다.
- 목소리 깨짐 원인: ogg 패킷을 열어 보니 경기 중 파일이 `##.##.##` 모양 (목소리 2개 → 무음 1개 반복). "S매치" 발화 파일 8.48초 중 무음 132개(2.64초), 실제 수신 시간은 약 6.97초 (`created_at` - 끝 대기 0.8초 - 시작). 녹음기가 패킷 도착 간격(`now - lastArrival`)으로 쉼을 채웠는데 게임 중에는 패킷이 몰려 와서 말 중간에 무음이 끼었다. 경기 전 파일도 일부 같은 모양
- 확인: 끼운 무음을 뺀 파일과 원래 파일을 Whisper large-v3(CPU)로 비교 — "이제 게임을 좀 해봐봐 스태스트랜 맛있긴 하네" → "실제로 게임을 좀 해봐오면서 테스트를 했는데 맛있긴 하네", "왜는 리플레이가 귀하다" → "이거는 리플레이가 없긴 하다"
- 고침: RTP 타임스탬프로 자리 정하기. 테스트 `core.test.ts` "패킷이 몰려 와도 말 중간에 무음을 넣지 않는다" (3개씩 60ms 마다 도착 + 진짜 쉼 0.4초 → 진짜 쉼 20프레임만 채움, 순번 · 타임스탬프 한 바퀴 도는 경우 포함). 예전 파일 고치기를 사용자 파일 43개에 돌려 489프레임 제거, 결과 파일 ffmpeg 디코드 정상
- 잡음 판정: 잡음 19개를 Silero VAD 로 다시 재니 모두 말소리 0초 (Whisper 를 돌리면 "시청해주셔서 감사합니다" · "자막 제공 배달의민족" 만 나옴) → 판정은 맞았고, 이제 숨기고 파일을 지운다. 반복 판정 1개는 깨진 오디오에서 나온 것
- 알 수 없음 원인: `users.updated` 를 `data: []` 로 보내 사이트 유저 목록이 비었다 (녹음 시작 · 경기 끝 · Riot ID 저장 때마다). DB 의 user_id 는 모두 정상
- 데스매치: 실시간 점수(킬)를 라운드로 착각 → "R10 · R22 · R36 · R48 · R63" 가짜 라운드, 경기 상세는 344킬이 "라운드 1" 하나라 에이스 11개. 경기 상세의 선수 이름이 비어 와서 "주인 계정 자동 연결: #"
- 테스트: 앱 48 · 사이트 서버 16 · 워커 42 통과, 앱 · 화면 타입 검사 통과. 실제 STT 워커 E2E 에서 잡음 파일 삭제 · `/api/utterances/:id/info` 확인. 사이트 서버 테스트에서 게임 PC 끊긴 뒤 관리자만 로그를 보고 내려받는 것 확인
- 배포: 사이트 서버 다시 배포 (`data/logs/site-날짜.log` 생성 · `[discord]` · `[http]` 줄 확인, `/site/logs` 로그인 없이 401), Windows CI (fa6126e, full) 7개 모두 PASS (zip 안 워커에 `av/filter` 포함) · 앱 버전 1.3.6 → Gitea 릴리스 v1.3.6 (v1.3.5 에 새 버전 안내)
## v1.3.7 — 기록 관리(경기별 묶음 · zip 내보내기/받아오기) · 검토로 찾은 오류 고침 (2026-10-16)
- 기록 묶음: 경기 = 묶음 하나, 경기 밖 대화는 녹음 세션 안에서 경기 사이마다 묶고 30분 기준으로 "경기 전 대화" · "경기 후 대화" · "게임 밖 대화". 사용자 실제 데이터(사본)로 확인: 경기 전 대화 7개 → 데스매치 11개 → 경기 후 대화 3개, 3묶음 zip 1.0MB
- 테스트 `bundles.test.ts`: 나누기, 내보내기 → 지우기 → 받아오기 그대로 복원(경기 · 라운드 · 이벤트 · 음성), 같은 zip 다시 받기는 건너뜀, 받아온 녹음은 보관 기간을 받아온 날부터, 다른 프로그램으로 다시 압축(deflate)한 zip, 받아오기 실패 9가지(zip 아님 · manifest · data 없음 · 음성 없음 · ogg 아님 · 다른 형식 · 말한 사람 없음 · 경기 기록 없음 · 발화 수 다름 → 아무것도 넣지 않음), 진행 중인 경기는 지우지 않음
- 사이트 서버 테스트: 20MB zip 내보내기 · 받아오기가 1MB 조각으로 그대로 오가는 것, 지우기 · 받아오기는 관리자만 (`/api/%62undles/delete` 같은 우회도 403)
- 전체 검토(v1.3.6 · v1.3.7 변경 3,600줄)로 찾아 고친 오류:
1. 기록 지우기 관리자 확인을 주소 %인코딩으로 우회 가능 → 주소를 풀어서 확인, 앱도 사이트가 붙인 역할로 한 번 더 확인
2. 큰 zip 을 주고받는 동안 앱이 pong 을 못 받아 사이트 연결을 스스로 끊음 → 무엇이든 받으면 살아 있는 것으로, 보낼 것이 4MB 넘게 쌓이면 기다림
3. 진행 중인 경기를 지우면 경기 끝 처리(정밀 변환 등)가 멈춤 → 진행 중인 경기는 지울 수 없음
4. 내보낸 zip 이 받아오기 한도(300MB)보다 클 수 있음 → 280MB 넘으면 나눠 받게 안내
5. 예전 녹음 고치기가 정밀 결과를 실시간 모델 결과로 덮고, 잡음으로 나오면 파일을 지울 수 있었음 · 시작할 때 한꺼번에 처리 → 정밀 모델로만, 잡음이면 이전 결과 유지, 20개씩, 중간에 꺼져도 이어서 (업그레이드 전에 만든 녹음만)
6. 타임라인 최신순에서 오래된 발화가 고쳐지면 맨 아래에 붙음 → 더 불러올 페이지가 남아 있으면 넣지 않음
7. 반복 줄이기가 숫자를 망가뜨림 ("1000원 줘 줘 줘" → "10원 줘") → 숫자 · 붙은 한 글자 반복은 그대로
8. TTS 속도 바꾸기가 중간에 죽으면 반쪽 파일이 계속 쓰임 → 다 만든 뒤 이름 바꾸기
- 그 밖: 브라우저 오류 로그에 검색어가 남던 것, 경기 끝 직후 늦게 끝난 실시간 변환의 잡음 파일을 정밀 확인 전에 지우던 것, 많이 골랐을 때 내려받기 주소가 너무 길던 것(본문으로 보냄), zip 풀기 메모리 한도 600MB, 날짜 묶음이 "10월"로만 나오던 것(경기 · 기록 목록)
- 테스트: 앱 53 · 사이트 서버 16 · 워커 42 통과, 타입 검사 통과
- 배포: 사이트 서버 다시 배포 (`/api/%62undles/delete` 로그인 없이 401), Windows CI (5d494eb, full) 7개 모두 PASS · 앱 버전 1.3.7 → Gitea 릴리스 v1.3.7 (v1.3.6 에 새 버전 안내) · 보고서 `docs/gemnoki-v1.3.7-report.pdf`
## v1.3.8 — 녹음 파일 이름 (2026-10-16)
- 이름 규칙 `날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg` (롤은 게임 시간, 경기 밖은 `경기밖`). 테스트 `audio-names.test.ts`: 이름 만들기 · Windows 금지 글자, 실제 파일 바꾸기, 경기 중 지금 라운드 → 경기 뒤 라운드 표로 다시 맞춤, 음성 인식 중이면 건드리지 않음, 표시 이름 바뀌면 전체 다시, zip 안 이름 · 받아오기 뒤 이름
- 실제 STT 워커 E2E: 변환이 끝난 뒤 파일 이름이 `…_하늘_경기밖_speech.ogg` 로 바뀌고 자세한 정보 경로도 같음
- 사용자 데이터 사본: 21개 이름 바꿈 (`2026-10-16_04-05-52_사금향_발로란트_데스매치_어비스_0mv9wsvgh48a56ebde5.ogg`, 데스매치는 라운드 없음, 경기 전후는 `경기밖`)
- 배포: 사이트 서버 다시 배포, Windows CI (249ead8, full) 7개 모두 PASS · 앱 버전 1.3.8 → Gitea 릴리스 v1.3.8 (v1.3.7 에 새 버전 안내)
## v1.3.9 — 받아오기: 이름 안의 ".." (2026-10-16)
- 원인: 받아오기 검사가 zip 안 음성 파일 이름에 `..` 이 있으면 거절했다. v1.3.8 부터 파일 이름에 표시 이름이 들어가므로 `하늘..별` 같은 이름이면 내보낸 zip 을 다시 넣지 못했다 (백업 뒤 지우면 되살릴 수 없음)
- 고침: zip 안 이름은 zip 에서 꺼낼 열쇠로만 쓰고, 이 PC 에 쓰는 경로는 발화 ID 로 만든다. 폴더 구분자만 막는다
- 테스트: `audio-names.test.ts` "표시 이름에 .. 이 있어도 내보내기 → 지우기 → 받아오기" (예전 코드에서 실패 확인 뒤 고침), "폴더를 넘나드는 zip 안 이름(audio/../, audio/..\, audio/sub/, ../)은 막는다". 앱 57 통과
- 배포: Windows CI (55ec58f, full) 7개 모두 PASS · 앱 버전 1.3.9 → Gitea 릴리스 v1.3.9 (v1.3.8 에 새 버전 안내). 사이트 서버는 바뀐 것 없음
## v1.4.0 — 발화 우클릭 삭제 · 잡음 문장 배우기 · 알림 기본 끄기 (2026-10-16)
- 사이트 우클릭 → 삭제… → "잡음이라 삭제" / "그냥 삭제" / 취소. 관리자 · 말한 사람만 (사이트 서버가 붙인 역할 · 유저로 앱이 확인)
- 테스트 `utterance-delete.test.ts`: 다른 멤버 403 · 본인 · 관리자 · 이 PC 안에서는 지움, 글 · 음성 · 교정 학습 음성 조각까지 지움, `utterance.deleted` 실시간 이벤트, 이미 지운 발화 404, 잘못된 사용자 머리글 403. 잡음이라 삭제 → 문장 배움(같은 문장은 하나로) · 목록 · 지우기. 음성 인식: 배운 문장과 같거나 거의 같으면(`…사용하였습니다` / `…사용했습니다`) 잡음 · 파일 삭제, 문장이 더 붙으면 그대로, 변환하는 동안 지운 발화는 결과 · 평소 음량에 넣지 않음 (이 확인을 빼면 실패하는 것 확인)
- 실제 STT 워커 E2E: "잡음이라 삭제"한 녹음을 다시 넣으니 인식이 한 글자 달랐다 ("레이드 공 빠졌어…" → "레이드 궁 빠졌어…", 교정 사전이 바뀌어 핫워드가 달라짐). 그래서 통째로 같을 때만이 아니라 8글자 이상이면 15% 안 글자 차이까지 같은 문장으로 본다 → `learned` 잡음, 파일 삭제, 타임라인에서 빠짐
- 사이트(목 서버 + 실제 빌드, 브라우저): 우클릭 메뉴 삭제 → 확인 창 → 잡음이라 삭제 → 줄이 사라지고 "앞으로 … 는 잡음으로 거릅니다", 단어사전 "잡음으로 배운 문장"에 추가. 인식된 글이 없으면 "잡음이라 삭제" 꺼짐. 효과음: 저장된 설정이 없으면 새 기본값, 예전 설정(전부 켜짐)은 두 알림만 한 번 끄고, 그 뒤 다시 켠 것은 그대로
- 테스트: 앱 62 · 사이트 서버 16 · 워커 42 통과, 앱 · 화면 · 서버 타입 검사 통과
- 배포: 사이트 서버 다시 배포 (배포된 화면 번들에 "잡음이라 삭제" · `noise-phrases` 확인), Windows CI (3115337, full) 7개 모두 PASS · 앱 버전 1.4.0 → Gitea 릴리스 v1.4.0 (v1.3.9 에 새 버전 안내)
## v1.4.1 — 잡음 문장 비교: 앞뒤에 붙은 실제 말은 지우지 않음 (2026-10-16)
- 원인: v1.4.0 의 "거의 같은 문장"이 편집 거리 15% 였다. 배운 문장 `자막 제공 및 자막을 사용하였습니다`(15글자) 뒤에 `네` · `가자` · `아니`가 붙어도 거리 1~2 라 잡음으로 지워 실제 음성을 잃었다
- 고침: 글자 수가 같고(8글자 이상) 바뀐 글자가 15% 이하일 때만 (실제 엔진에서 본 "레이드 공" / "레이드 궁" 은 그대로 잡음). 글자가 붙거나 빠지면 다른 말
- 테스트 `utterance-delete.test.ts`: 앞뒤에 `네` · `가자` · `아니`를 붙인 문장은 비슷하지 않음, 음성 인식에서 그 발화들의 글 · 음성 파일이 남음 (v1.4.0 코드에서 실패 확인 뒤 고침)

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,463 @@
"""계획서 HTML 만들기: python3 build.py (sim.json 숫자를 그대로 넣는다) → plan.html"""
import json, html
d = json.load(open('sim.json'))
src = open('../report.html').read()
STYLE = src[src.index('<style>') + 7: src.index('</style>')]
B = d['base']; PM = d['per_model']; SC = d['scenarios']; MED = d['opus_medium']
import re as _re
def _load(f): return html.escape(_re.sub(r'<!--.*?-->\n?', '', open('../../../site/server/prompt/' + f).read(), flags=_re.S).strip())
FIX = {'valorant': 6649, 'lol': 8204} # 토큰 세기 API 실측 (v1.2)
def usd(x, n=2): return f"${x:.{n}f}"
def k(x): return f"{x/1000:.1f}k" if x >= 1000 else f"{x:.0f}"
# ── 그래프 1: 경기당 비용 히스토그램 (SVG) ──
def hist_svg():
bins = [(float(b), c) for b, c in d['hist']]
W, H, L, Bm, T = 640, 190, 44, 30, 14
lo, hi = 0.15, 0.90
mx = max(c for _, c in bins)
pw = W - L - 10; ph = H - Bm - T
x = lambda v: L + (v - lo) / (hi - lo) * pw
y = lambda c: T + ph - c / mx * ph
bw = 0.025 / (hi - lo) * pw
out = [f'<svg viewBox="0 0 {W} {H}" width="100%" xmlns="http://www.w3.org/2000/svg" font-family="Noto Sans CJK KR" font-size="10">']
for gy in range(0, int(mx) + 1, 1000):
out.append(f'<line x1="{L}" x2="{W-10}" y1="{y(gy):.1f}" y2="{y(gy):.1f}" stroke="#e6e9ee" stroke-width="1"/>')
out.append(f'<text x="{L-6}" y="{y(gy)+3:.1f}" text-anchor="end" fill="#7a8492">{gy/d["hist_n"]*100:.0f}%</text>')
for b, c in bins:
if b < lo or b >= hi: continue
x0 = x(b) + 1; w = bw - 2; y0 = y(c); h = T + ph - y0
r = min(4, h / 2, w / 2)
out.append(f'<path d="M{x0:.1f},{T+ph:.1f} V{y0+r:.1f} Q{x0:.1f},{y0:.1f} {x0+r:.1f},{y0:.1f} H{x0+w-r:.1f} Q{x0+w:.1f},{y0:.1f} {x0+w:.1f},{y0+r:.1f} V{T+ph:.1f} Z" fill="#2a78d6"/>')
out.append(f'<line x1="{L}" x2="{W-10}" y1="{T+ph}" y2="{T+ph}" stroke="#9aa6b5"/>')
for v in [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]:
out.append(f'<text x="{x(v):.1f}" y="{H-12}" text-anchor="middle" fill="#5d6675">${v:.1f}</text>')
for v, lab in [(B['cost']['mean'], f"평균 {usd(B['cost']['mean'])}"), (B['cost']['p90'], f"10판 중 9판은 {usd(B['cost']['p90'])} 이하")]:
out.append(f'<line x1="{x(v):.1f}" x2="{x(v):.1f}" y1="{T}" y2="{T+ph}" stroke="#1b1f27" stroke-dasharray="3 3"/>')
out.append(f'<text x="{x(v)+5:.1f}" y="{T+10}" fill="#1b1f27" font-weight="700">{lab}</text>')
out.append(f'<text x="{W-10}" y="{H-1}" text-anchor="end" fill="#7a8492">경기당 비용 (Claude Opus 5.5, 실패·재분석 여유 빼고)</text>')
out.append('</svg>')
return ''.join(out)
# ── 그래프 2: $100 로 분석할 수 있는 경기 수 (가로 막대) ──
def bars_html():
rows = [
('Opus 5.5 · 말 많은 방', SC['loud/mix']['per100'], False),
('Opus 5.5 · 보통 (기준)', PM['opus-5.5']['p50'], True),
('Opus 5.5 · 조용한 방', SC['quiet/mix']['per100'], False),
('Opus 5.5 · 생각 medium', MED['p50'], False),
('Sonnet 5.5 · 보통', PM['sonnet-5.5']['p50'], False),
('Haiku 4.5 · 보통', PM['haiku-4.5']['p50'], False),
]
mx = 1050
h = []
for lab, v, hl in rows:
col = '#ff4655' if hl else '#2a78d6'
h.append(f'<div class="vbar"><div class="lab">{lab}</div><div class="track"><div class="seg" style="width:{v/mx*100:.1f}%;background:{col};border-radius:0 4px 4px 0"></div></div><div class="tot" style="width:62px"><b style="color:#1b1f27">{v:,}</b>경기</div></div>')
return ''.join(h)
opus = PM['opus-5.5']
days = 31
per_day = opus['p50'] / days
HTML = f'''<!doctype html><html lang="ko"><head><meta charset="utf-8"><title>겜녹이 범인찾기 · 리플레이 동기화 계획서 v1.2</title>
<style>{STYLE}
.cover .wave span:nth-child(3n) {{ opacity:.55 }}
pre.box {{ background:#0f1923; color:#d7dee6; border-radius:8px; padding:9px 12px; font-size:8.2pt; line-height:1.55; white-space:pre-wrap; break-inside:avoid; font-family:"D2Coding ligature","DejaVu Sans Mono",monospace; }}
pre.box .c {{ color:#7f8b99 }} pre.box .h {{ color:#ffc86a }} pre.box .v {{ color:#4fd8cf }}
pre.box.ap {{ font-size:7.3pt; line-height:1.45; break-inside:auto; }}
.cover h1 {{ font-size:25pt; }}
.big-num {{ font-family:"NanumSquare Neo",sans-serif; font-weight:800; }}
td.num, th.num {{ text-align:right; white-space:nowrap; }}
tr.hl td {{ background:#fff3f4 !important; font-weight:700; }}
.done {{ color:#0f8a5f; font-weight:700; white-space:nowrap; }} .todo {{ color:#8a6a10; font-weight:700; white-space:nowrap; }}
.mob {{ display:grid; grid-template-columns: 0.62fr 1.38fr; gap:12px; align-items:start; }}
</style></head><body>
<section class="cover">
<div class="bar"></div>
<h1>범인찾기 · 리플레이 동기화 계획서</h1>
<div class="sub">AI가 경기 기록을 읽고 10명 평가 · 팀별 범인을 찾습니다.<br>리플레이를 보면 그때 한 말을 시간에 맞춰 보여 줍니다.</div>
<table class="meta">
<tr><td>프로젝트</td><td>겜녹이 (Game Voice Recorder) · v1.2.2 다음 기능</td></tr>
<tr><td>문서</td><td>계획서 v1.2 · 정해 주신 8가지 반영 (v1.1 + 결정 사항 · 실제 화면 · 토큰 실측)</td></tr>
<tr><td>진행</td><td>범인찾기 C1~C3(앱 · 사이트 서버 · 화면) 구현 완료, 배포 전 · 리플레이 동기화는 API 확인 뒤 결정</td></tr>
<tr><td>작성일</td><td>2026-10-15</td></tr>
<tr><td>AI</td><td>Claude API (Anthropic) · 기본 모델 Claude Opus 5.5</td></tr>
<tr><td>예산</td><td>API 크레딧 $100 (2026-11-15 만료)</td></tr>
</table>
<div class="hero"><img src="img/real-result.png" alt=""></div>
<div class="foot">gvr.tkrmagid.kr · 표지 화면은 실제 구현 화면(시연 데이터 + 실제 Claude Opus 5.5 분석 결과)입니다</div>
</section>
<section class="page">
<h2><span class="num">1</span>한눈에 보기</h2>
<div class="stats">
<div class="stat"><div class="v">{opus['p50']}<small>경기</small></div><div class="l">$100로 분석할 수 있는 경기 수<br>(Opus 5.5 · 가정한 조건에서<br>10번 중 9번 {opus['p5']}~{opus['p95']})</div></div>
<div class="stat"><div class="v">{usd(B['cost']['mean'])}</div><div class="l">경기당 평균 비용<br>(10판 중 8판은 {usd(B['cost']['p10'])}~{usd(B['cost']['p90'])})</div></div>
<div class="stat"><div class="v">1~2<small>분</small></div><div class="l">버튼을 누르고 결과가 나올 때까지</div></div>
<div class="stat"><div class="v">{per_day:.0f}<small>판/일</small></div><div class="l">크레딧 만료(11/15)까지 다 쓰려면<br>하루에 분석해야 하는 경기 수</div></div>
</div>
<ul>
<li><b>무엇을 하나</b>: 사이트에 <b>🔍 범인찾기</b> 탭을 새로 만듭니다. 끝난 경기를 고르고 <b>범인 분석</b>을 누르면, AI가 그 경기의 음성 대화 · 킬 · 라운드/오브젝트 · 경제 · 채팅 · 10명 스탯을 모두 읽고 아래를 만들어 줍니다.
<ul><li>10명 전부 평점(10점 만점), 별명 태그(캐리 · 숨은 MVP · 무난 · 범인), 한 줄 평</li>
<li>팀별 범인 1명씩(우리 팀 · 상대 팀), 왜 범인인지 설명, 근거 3~4개</li>
<li>근거마다 실제 순간(대화 · 킬 · 라운드)이 연결돼 누르면 타임라인에서 바로 듣고 볼 수 있음</li></ul></li>
<li><b>대상 경기</b>: 끝났고 기록이 모두 남아 있는 경기만 고를 수 있습니다. 녹음이 중간에 시작됐거나, 경기 결과를 못 받았거나, 음성 변환이 덜 끝난 경기는 이유를 보여 주고 막습니다 (4장).</li>
<li><b>범인</b>: 팀마다 1명. <b>가장 못한 사람 + 가장 발목을 잡은 사람 + 결과(패배)의 원인</b>을 모두 합쳐 종합으로 고릅니다 (3장).</li>
<li><b>AI는 사이트 서버가 부릅니다</b>. Claude Opus 5.5 · 말투 중간맛. API 키는 받아서 서버 비밀 저장소에만 두었고, 배포 때 사이트 서버 환경 변수로만 넣습니다. exe에는 넣지 않습니다 (5장).</li>
<li><b>분석 버튼</b>은 등록된 앱 유저 이상만 누를 수 있습니다(다시 분석은 관리자). 결과는 로그인한 멤버 모두가 봅니다.</li>
<li><b>비용</b>: 경기 길이와 말하는 양을 무작위로 바꿔 가며 2만 경기를 계산했습니다. Opus 5.5로 <b>$100이면 약 {opus['p50']}경기</b>입니다(지시문 · 지식 묶음 토큰을 실제로 재서 다시 계산, v1.1의 248경기에서 조정). 방이 조용하면 약 {SC['quiet/mix']['per100']}경기, 말이 많으면 약 {SC['loud/mix']['per100']}경기입니다 (7장).</li>
<li><b>예산 보호</b>: 월 $100 상한, 하루 횟수 제한, 경기당 최대 약 $1 상한, 한 경기는 한 번만 분석(다시 분석은 관리자만)을 둡니다.</li>
<li><b>프롬프트 · 지식 묶음은 미리 써 두었습니다</b>: 지시문, 발로란트 · 롤 지식 묶음(규칙 · 경제 · 역할 기준 · 은어 · 음성 인식 오류 · 최신 요원 · 챔피언 목록), 출력 형식. 매 분석마다 같이 보내 AI가 “배운 상태”로 분석합니다 (6장 · 부록).</li>
<li><b>멤버 공지</b>: 녹음 안내(TTS) 문구에 “녹음된 대화는 AI 경기 분석에 쓰일 수 있어요”를 넣었습니다. 기본 문구를 쓰던 PC는 새 문구로 자동으로 바뀝니다.</li>
<li><b>리플레이 동기화</b>: 게임 안 리플레이를 보면 exe가 알아채고 “리플레이와 동기화하시겠습니까?”를 묻는 기능입니다. <b>게임이 API(공식 · 비공식)로 리플레이 시간을 알려 줄 때만 넣습니다.</b> 화면 글자 인식(OCR)이나 게임 설정 파일 고치기는 하지 않습니다. 그래서 먼저 Windows PC에서 롤 · 발로란트가 어떤 API를 주는지 확인(R0)하고, 되는 게임만 만듭니다 (8장). AI를 쓰지 않아 비용이 없습니다.</li>
</ul>
<div class="callout info"><b class="t">정한 것 (2026-10-15 답변 · 자세한 내용은 10장)</b>
① 범인 = 가장 못함 + 가장 발목 + 패배 원인 종합 ② 분석 버튼 = 등록된 앱 유저 이상 ③ 모델 = Opus 5.5 ④ API 키 = 받음(서버에만) ⑤ 말투 = 중간맛 ⑥ 공지 = 녹음 안내(TTS) 문구에 추가 ⑦ 발로란트 리플레이 = API에 없으면 넣지 않음(OCR 안 함) ⑧ 롤 리플레이 = API에 없으면 넣지 않음(설정 파일 안 고침)</div>
<h3>목차</h3>
<ol class="toc">
<li>한눈에 보기</li><li>쓰는 흐름 · 화면 예시</li><li>범인을 고르는 기준</li><li>분석에 쓰는 기록 · 분석할 수 있는 경기</li>
<li>구조 · 보안 · 개인정보</li><li>범인찾기 프롬프트 · 지식 묶음</li><li>비용 예상: $100로 몇 경기?</li><li>리플레이 동기화</li><li>만드는 순서 · 확인 방법</li><li>정한 것 · 남은 일</li><li>부록: 프롬프트 · 지식 묶음 · 출력 형식 원문</li></ol>
</section>
<section class="page">
<h2><span class="num">2</span>쓰는 흐름 · 화면 예시</h2>
<div class="flow">
<div class="s"><div class="ic">🎮</div><div class="t">경기 끝</div><div class="d">결과 · 10명 스탯 받음<br>음성 변환 끝</div></div>
<div class="s"><div class="ic">🔍</div><div class="t">범인찾기 탭</div><div class="d">분석 가능한 경기만<br>고를 수 있음</div></div>
<div class="s"><div class="ic">💰</div><div class="t">범인 분석</div><div class="d">예상 비용 · 남은 예산<br>확인 후 시작</div></div>
<div class="s"><div class="ic">🧠</div><div class="t">AI 분석</div><div class="d">1~2분<br>진행 단계 표시</div></div>
<div class="s"><div class="ic">🚨</div><div class="t">결과</div><div class="d">팀별 범인 · 10명 평가<br>모두가 같이 봄</div></div>
</div>
<figure><img class="shot" src="img/real-list.png" alt=""><figcaption><b>화면 1 · 범인찾기 탭 (경기 고르기)</b> 왼쪽은 끝난 경기 목록입니다. 경기마다 <b>분석 가능 · 분석 완료 · 준비 중 · 기록 부족</b>을 표시하고, 기록이 부족하면 이유(“녹음이 12분 뒤에 시작됨” 등)를 보여 줍니다. 오른쪽은 고른 경기에서 분석에 쓰는 기록과 참가자 10명(음성이 있는 사람 표시), 예상 비용 · 남은 예산 · 오늘 남은 횟수입니다. <span class="ex">실제 화면 · 시연 데이터</span></figcaption></figure>
<figure><img class="shot" src="img/real-result.png" alt=""><figcaption><b>화면 2 · 분석 결과 (발로란트)</b> 맨 위는 한 줄 요약, 가운데는 팀별 범인 카드(이유 + 근거), 아래는 10명 평가입니다. 근거의 대화는 <b>▶ 듣기</b>로 그 문장 음성을 바로 재생하고(7일 보관 기간 안), 킬 · 라운드는 타임라인으로 이동합니다. 상대 팀처럼 음성이 없는 사람은 “게임 기록으로 판단”이라고 밝힙니다. 결과 글은 실제 Claude Opus 5.5가 쓴 것입니다. 시연 데이터의 앞뒤가 안 맞는 곳을 AI가 스스로 찾아 확신도를 “낮음”으로 적었습니다. <span class="ex">실제 화면 · 시연 데이터</span></figcaption></figure>
</section>
<section class="page">
<div class="mob">
<figure style="margin-top:0"><img class="shot" src="img/real-mobile.png" alt=""><figcaption><b>화면 3 · 분석 결과 (휴대폰)</b> 이긴 경기에서도 팀마다 범인을 뽑습니다. 휴대폰에서는 요약, 범인 카드, 10명 평가를 차례로 보여 줍니다. <span class="ex">실제 화면 · 시연 데이터</span></figcaption></figure>
<div>
<h3 style="margin-top:0">결과 화면에 들어가는 것</h3>
<table>
<tr><th>칸</th><th>내용</th></tr>
<tr><td>한 줄 요약</td><td>경기가 어떻게 흘러갔는지 1~2문장</td></tr>
<tr><td>팀별 범인</td><td>팀마다 1명. 평점, 이유 2~3문장, 근거 3~4개(대화 · 킬 · 경제 · 스탯)</td></tr>
<tr><td>10명 평가</td><td>평점(10점 만점, 0.5 단위), 태그, 한 줄 평. 음성 유무 표시</td></tr>
<tr><td>분석 정보</td><td>분석 시각, 모델, 쓴 문장 · 이벤트 수, 실제 비용</td></tr>
<tr><td>주의 문구</td><td>“재미로 보는 AI 분석입니다. 음성 인식 오류나 기록에 없는 상황 때문에 틀릴 수 있어요.”</td></tr>
</table>
<h3>분석하는 동안</h3>
<p>버튼을 누르면 결과 자리에 진행 단계가 나옵니다: <b>기록 모으기 → AI가 읽는 중 → 근거 확인 → 완료</b>. 창을 닫아도 분석은 계속되고, 끝나면 사이트 실시간 알림으로 결과가 뜹니다. 같은 경기를 다른 사람이 동시에 눌러도 한 번만 돕니다.</p>
<h3>결과를 보는 사람 · 다시 분석</h3>
<ul>
<li>결과는 사이트에 로그인한 서버 멤버 모두가 봅니다 (기존 기록과 같은 권한).</li>
<li>한 경기는 한 번만 분석합니다. 다시 분석은 관리자만 할 수 있고, 이전 결과는 기록으로 남깁니다.</li>
<li>사이트 <b>경기</b> 화면에도 “🔍 범인 보기” 버튼을 달아 바로 옮겨 갑니다.</li>
</ul>
</div></div>
<h2 style="margin-top:14px"><span class="num">3</span>범인을 고르는 기준</h2>
<div class="callout"><b class="t">"범인"의 뜻 (정함 · ①)</b>
<b>팀마다 1명</b>을 고르고, 아래 셋을 <b>모두 합쳐 종합으로</b> 판단합니다. 한 가지만 보지 않습니다.
<ul style="margin:4px 0 0"><li><b>가장 못한 사람</b>: 자기 역할 · 포지션 기준으로 플레이가 가장 나빴다</li>
<li><b>가장 발목을 잡은 사람</b>: 팀의 계획 · 경제 · 콜을 가장 많이 망쳤다</li>
<li><b>결과의 원인</b>: 진 팀이면 패배에 가장 큰 책임, 이긴 팀이면 이기는 데 가장 방해가 된 사람</li></ul>
그래서 이긴 경기에도 범인이 있습니다. 범인은 그 팀에서 평점이 가장 낮아야 합니다(서버가 확인).</div>
<table>
<tr><th style="width:18%">보는 것</th><th>발로란트</th><th>리그 오브 레전드</th></tr>
<tr><td>플레이</td><td>첫 킬 · 첫 데스, 전투 점수(ACS), 라운드당 피해량, 클러치, 스파이크 설치 · 해체, 연속 데스</td><td>포지션별 기준: 라인 CS · 골드 차, 킬 관여율, 딜량 · 받은 피해, 데스 시점(오브젝트 직전 등)</td></tr>
<tr><td>팀 운영</td><td>경제(혼자 장비 안 사기 · 세이브 무시), 요원 역할 수행(연막 · 정찰 · 부활)</td><td>드래곤 · 바론 · 전령 · 포탑 관여, 시야 점수, 한타 합류</td></tr>
<tr><td>소통 (음성 · 채팅)</td><td colspan="2">정확한 콜, 콜 무시(“기다려” 뒤 혼자 진입 등), 남 탓 · 짜증, 포기 발언(“ff”), 팀 분위기를 살린 말</td></tr>
</table>
<h3>공정하게 보는 규칙 (AI 지시문에 넣음)</h3>
<ul>
<li><b>KDA만 보지 않습니다.</b> 역할을 따집니다. 세이지 · 쓰레쉬처럼 킬이 적은 역할은 그 역할로 평가합니다.</li>
<li><b>음성이 없는 사람은 소통 항목을 빼고</b> 플레이와 채팅으로만 평가합니다. 말이 없다고 깎지도, 말실수가 안 잡혔다고 올리지도 않습니다. 결과에 “게임 기록으로 판단”이라고 적습니다.</li>
<li><b>근거 없는 말 금지.</b> 근거마다 실제 기록 번호(문장 · 이벤트 · 라운드)를 달게 하고, 서버가 그 번호가 이 경기에 정말 있는지 확인한 뒤에만 보여 줍니다. 없는 근거가 나오면 그 근거를 빼고, 범인 근거가 하나도 안 남으면 다시 분석합니다.</li>
<li><b>음성 인식 오류를 감안</b>합니다. 뜻이 애매한 문장 하나로 범인을 정하지 않습니다.</li>
<li><b>재미용 말투</b>: 가볍게 놀리되 욕설 · 외모 · 인신공격은 쓰지 않습니다. 녹음 제외한 사람의 대화는 애초에 없습니다.</li>
</ul>
</section>
<section class="page">
<h2><span class="num">4</span>분석에 쓰는 기록 · 분석할 수 있는 경기</h2>
<table>
<tr><th style="width:22%">기록</th><th style="width:36%">원래 저장하던 것</th><th>범인찾기를 위해 더 저장 (구현 완료)</th></tr>
<tr><td>음성 대화</td><td>유저별 문장, 시각, 경기 · 라운드 연결 (텍스트는 계속 남음)</td><td>없음. 음성 파일은 7일 뒤 지워져도 분석은 텍스트로 함</td></tr>
<tr><td>발로란트 경기</td><td>10명 KDA · 전투 점수 · 랭크, 라운드 결과, 라운드별 경제(쓴 돈 · 무기), 킬(무기 · 헤드샷 · 위치)</td><td>선수별 준 피해 · 헤드샷 비율 · 첫킬/첫데스 · 설치/해체 · 스킬 사용 · 요원 역할, 라운드별 공격/수비 · 장비 값 · 선수별 킬/피해</td></tr>
<tr><td>롤 경기</td><td>10명 KDA · CS · 골드 · 아이템, 골드 차 그래프, 킬 · 오브젝트 이벤트</td><td>포지션(추정), 챔피언 피해 · 받은 피해, 시야 점수 · 와드 설치/제거/제어 와드, 오브젝트 · 포탑 피해, CC 시간, 10분 · 15분 CS · 골드</td></tr>
<tr><td>채팅</td><td>팀 · 전체 채팅 (API · OCR)</td><td>없음</td></tr>
<tr><td>디스코드 ↔ 게임 계정</td><td>Riot ID로 누가 누구인지 연결</td><td>연결 안 된 화자는 디스코드 이름으로 보내고 “게임 계정 모름”으로 표시</td></tr>
</table>
<p class="small">이미 저장된 예전 경기는 지금 있는 기록만으로 분석합니다(피해량 · 시야 같은 지표 없이). 결과에 “기본 기록으로 분석”이라고 표시합니다.</p>
<h3>"기록이 전부 남아 있는" 경기 = 아래를 모두 만족</h3>
<div class="dtree">
<div class="col"><div class="qq">경기가 끝났나?</div><div class="noise">아니면: 목록에 안 보임</div></div><div class="ar">→</div>
<div class="col"><div class="qq">경기 결과 상세(10명)를 받았나?</div><div class="noise">“결과 못 받음”</div></div><div class="ar">→</div>
<div class="col"><div class="qq">녹음이 경기 처음~끝을 덮나? (1분 넘게 빈 곳 없음)</div><div class="noise">“녹음이 12분 뒤에 시작됨”</div></div><div class="ar">→</div>
<div class="col"><div class="qq">그 시간 문장이 모두 텍스트로 바뀌었나?</div><div class="noise">“음성 변환 중” (잠시 뒤 가능)</div></div><div class="ar">→</div>
<div class="col"><div class="ok"><b>분석 가능</b><br>이미 했으면 “분석 완료”</div></div>
</div>
<div class="callout warn"><b class="t">한계</b>
<ul style="margin:2px 0">
<li>겜녹이 봇은 한 디스코드 서버에서 음성채널 하나에만 들어갑니다. 그래서 <b>음성은 봇이 있는 채널 사람만</b> 있습니다. 보통 상대 팀은 게임 기록과 채팅으로만 평가합니다.</li>
<li>내전에서 두 팀이 다른 채널로 나뉘면 한 팀 음성만 남습니다. 두 팀 모두 녹음하려면 봇이 한 채널씩 따로 들어가야 해서, 이번 기능 범위 밖으로 둡니다(필요하면 따로 계획).</li>
<li>경기 기록은 게임 PC에만 있으므로 <b>게임 PC가 켜져 있어야</b> 분석하고 결과를 볼 수 있습니다(지금 사이트와 같음).</li>
</ul></div>
</section>
<section class="page">
<h2><span class="num">5</span>구조 · 보안 · 개인정보</h2>
<div class="pipe">
<div class="st"><span class="n">1</span><b>브라우저</b>범인 분석 누름 → 사이트 서버</div>
<div class="st"><span class="n">2</span><b>사이트 서버</b>로그인 · 권한 · 예산 · 하루 횟수 확인, 이 경기 잠금</div>
<div class="st"><span class="n">3</span><b>게임 PC (기존 중계)</b>분석 가능 확인 후 분석 자료(압축 텍스트) 만들어 보냄</div>
<div class="st"><span class="n">4</span><b>Claude API</b>서버가 호출 (스트리밍) · 정해진 JSON 형식으로 받음</div>
<div class="st"><span class="n">5</span><b>사이트 서버</b>10명 · 근거 번호 확인, 실제 비용 기록</div>
<div class="st"><span class="n">6</span><b>게임 PC</b>결과 저장 → 사이트 실시간 알림</div>
</div>
<ul>
<li><b>API 키는 사이트 서버에만</b> 둡니다(환경 변수 <code>ANTHROPIC_API_KEY</code>, root만 읽기). 봇 토큰과 같은 원칙으로, exe에도 브라우저에도 가지 않습니다. 게임 PC가 직접 부르게 하면 키가 PC에 남아 꺼낼 수 있어서 쓰지 않습니다.</li>
<li><b>결과는 게임 PC 기록 DB에 저장</b>합니다(새 표 <code>culprit_analyses</code>). 기록은 게임 PC에만 둔다는 지금 원칙을 지킵니다. 서버에는 비용 장부만 남깁니다(경기 번호 · 누른 사람 · 토큰 수 · 비용 · 시각, 대화 내용 없음).</li>
<li><b>예산 장부</b>: 서버가 매번 실제 사용량(응답의 토큰 수)으로 비용을 계산해 쌓습니다. 월 상한을 넘으면 버튼을 잠급니다. Claude Console에도 지출 한도를 걸어 두 번 막습니다.</li>
<li><b>AI 설정</b>: 지시문 · 지식 묶음은 6장, Claude Opus 5.5, 생각 깊이 high, 말투 중간맛, 출력은 JSON 형식 고정(구조화 출력), 출력 상한 32k 토큰. AI가 응답을 거절하면 Anthropic 서버가 권장 모델로 한 번 자동 재시도합니다. 실패하면 비용이 든 만큼만 기록하고, 다시 누를 수 있게 잠금을 풉니다.</li>
</ul>
<h3>AI에 보내는 자료 모양 (예시)</h3>
<pre class="box"><span class="h"># 경기 발로란트 경쟁전 · 어센트 · 13:9 (우리 팀 승리) · 22라운드 · 46분</span>
<span class="h"># 참가자 (번호 이름 팀 요원(역할) K/D/A ACS 라운드당피해 첫킬/첫데스 헤드샷 설치/해체 스킬사용 음성)</span>
P1 하늘 우리 제트(타격대) 19/12/7 ACS244 ADR148 첫킬1/첫데스2 HS15% 설치0/해체0 랭크:플래티넘 1 음성O
P5 Duck 우리 킬조이(감시자) 12/15/8 ACS194 ADR92 첫킬2/첫데스2 HS16% 설치0/해체1 랭크:골드 3 음성X
<span class="c">[e1] R1 0:08 킬 P2 → P6 (클래식)</span>
<span class="v">[u1] R3 0:05 P1: 현우야 같이 가 기다려 둘 있어</span>
<span class="v">[u2] R3 0:09 P2: 아 그냥 간다 내가 뚫을게</span>
<span class="c">[r3] R3 우리 공격 라운드 끝 · 패배(전멸) 2:1 · 평균 장비 우리 3,714 / 상대 3,582 · 선수 장비/피해: P1 2.4k/185 P2 4.3k/0 …</span>
<span class="v">[u3] R5 0:02 도윤(게임 계정 모름): 나 돈 없어 세이브할게</span></pre>
<p class="small">앱이 실제로 만드는 모양입니다(시연 경기). [u…] = 대화 문장, [e…] = 게임 이벤트, [c…] = 채팅, [r…] = 라운드 요약, [s:P…] = 그 사람 경기 전체 스탯 번호. AI는 근거를 이 번호로 답하고, 서버가 번호를 확인합니다. 숫자 덩어리(JSON)가 아니라 이런 줄글로 보내 토큰을 아낍니다.</p>
<h3>개인정보</h3>
<ul>
<li>분석하면 그 경기의 <b>대화 텍스트</b>와 게임 기록이 Anthropic(Claude API)으로 갑니다. 음성 파일은 보내지 않습니다.</li>
<li>Claude API로 보낸 내용은 기본적으로 AI 학습에 쓰이지 않고, Anthropic 정책에 정해진 기간만 보관됩니다.</li>
<li>녹음 제외(/녹음제외)한 사람의 대화는 원래 없으므로 보내지 않습니다. 서버 로그에는 대화 내용을 남기지 않습니다.</li>
<li>멤버 공지(⑥): 녹음 시작 안내(TTS) 문구를 “겜녹이가 이 음성채널을 녹음합니다. <b>녹음된 대화는 AI 경기 분석에 쓰일 수 있어요.</b> 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.”로 바꾸고 기본 음성을 다시 합성했습니다. 관리자가 문구를 직접 고친 PC는 그 문구를 그대로 둡니다.</li>
</ul>
</section>
<section class="page">
<h2><span class="num">6</span>범인찾기 프롬프트 · 지식 묶음</h2>
<div class="callout info"><b class="t">"미리 학습"은 이렇게 합니다</b>
Claude API는 우리가 모델을 따로 학습(파인튜닝)시킬 수 없습니다. 대신 <b>분석할 때마다 지시문과 지식 묶음을 경기 자료 앞에 같이 보냅니다</b>. 그래서 AI는 매번 게임 규칙 · 역할 기준 · 은어 · 음성 인식 오류를 “배운 상태”로 분석합니다. 이 부분은 경기마다 똑같아 프롬프트 캐시를 쓰면 1시간 안의 다음 분석부터 이 부분 값이 약 5%로 줄어듭니다(비용 계산에는 캐시 없이 넣었습니다).</div>
<table>
<tr><th style="width:30%">파일</th><th>내용</th></tr>
<tr><td><code>prompt/system.md</code> 지시문 v1.1</td><td>역할 · 할 일 · 범인 기준(종합 판단) · 판단 원칙 · 태그 · 말투(중간맛) · 자료 약어 설명 · 출력 규칙</td></tr>
<tr><td><code>prompt/knowledge-valorant.md</code></td><td>규칙 · 경제 · 역할별 기준 · 지표 기준 · 콜아웃 · 은어 · 음성 인식 오류 + 자동 갱신(요원 29명 역할 · 맵 13개 · 무기 가격)</td></tr>
<tr><td><code>prompt/knowledge-lol.md</code></td><td>기본 규칙 · 포지션별 기준 · 지표 기준 · 은어 · 음성 인식 오류 + 자동 갱신(챔피언 173명 분류)</td></tr>
<tr><td><code>prompt/output-schema.json</code></td><td>결과 JSON 형식: 요약 · 확신도 · 팀별 범인 · 10명 평가 · 근거 번호</td></tr>
</table>
<p class="small">파일은 <code>site/server/prompt/</code>에 있고(사이트 서버가 그대로 읽음) 전문은 부록에 있습니다. 토큰 세기 API(claude-opus-5-5)로 잰 고정 부분(지시문 + 지식 묶음 + 출력 형식)은 <b>발로란트 {FIX['valorant']:,} · 롤 {FIX['lol']:,}토큰</b>입니다. v1.1에서 글자 수로 잡은 3,900 · 5,000보다 많아서 7장 비용을 다시 계산했습니다(경기당 약 +$0.017).</p>
<h3>지식 묶음 = 손으로 쓴 부분 + 패치마다 자동 갱신하는 부분</h3>
<div class="grid2">
<div class="card"><h4>손으로 쓴 부분 (사람이 고침)</h4><ul style="margin:0">
<li>경기 규칙 · 경제(발로) / 포지션 · 오브젝트(롤)</li>
<li>역할 · 포지션별 평가 기준: 무엇을 잘하면 잘한 것인지</li>
<li>지표 기준값: 전투 점수 · 라운드당 피해량 · 분당 CS · 시야 점수</li>
<li>판단 함정: 에코 킬, 막판 정리 킬, 팀 세이브, 탱커 · 서폿 KDA</li>
<li>콜아웃 · 은어 뜻: 원탭, 로테, 리테이크, 갱, 다이브, 던졌다, 버스 등</li>
<li>음성 인식이 자주 틀리는 말: 앱 교정 사전 28개와 같은 목록</li></ul></div>
<div class="card"><h4>자동 갱신 부분 (패치마다 새로 만듦)</h4><ul style="margin:0">
<li>발로란트: 요원 이름과 역할(타격대 · 척후대 · 전략가 · 감시자), 맵, 무기 가격 ← valorant-api.com 한국어</li>
<li>롤: 챔피언 이름과 분류 ← Riot Data Dragon 한국어 (지금 16.20.1)</li>
<li>사이트 서버가 공식 데이터에서 하루에 한 번 새로 만들고, 못 받으면 파일의 스냅샷을 씀</li>
<li>AI가 원래 모를 수 있는 최신 요원 · 무기(믹스 · 비토 · 웨이레이 · 테호 · 워든 등)를 채워 줌</li></ul></div>
</div>
<h3>지시문의 핵심 규칙 (발췌)</h3>
<pre class="box"><span class="h">판단 원칙</span>
- 숫자보다 결과에 준 영향을 본다. 승부처의 실수는 무겁게, 승부가 갈린 뒤의 스탯과 에코 라운드 킬은 가볍게.
- 역할로 평가한다. 킬이 적은 역할이 킬이 적다고 범인이 되지 않는다.
- 음성X 인 사람은 소통 항목 없이 평가한다. 음성O 인 사람을 범인으로 고를 때는 플레이 근거가 최소 1개 있어야 한다.
- "콜 무시"는 콜이 있었고, 다르게 움직인 것이 이벤트로 확인될 때만 쓴다.
- 음성 인식 오류를 감안한다. 뜻이 분명하지 않은 문장은 근거로 쓰지 않는다.
- 자료에 없는 것을 지어내지 않는다. 근거는 자료의 번호로만, 인용은 원문 그대로.
<span class="h">출력</span> 10명 모두 · 팀마다 "범인" 태그 정확히 1명 · 범인은 그 팀 최저점 · 판단이 약하면 confidence 를 낮춤</pre>
<h3>프롬프트가 제대로 도는지 확인하는 방법</h3>
<table>
<tr><th style="width:4%">#</th><th style="width:38%">시험 경기 (테스트 자료로 만듦)</th><th>기대하는 결과</th></tr>
<tr><td>1</td><td>킬이 적은 세이지 · 쓰레쉬가 부활 · 시야로 기여</td><td>범인이 되지 않고, 한 줄 평에 기여가 나옴</td></tr>
<tr><td>2</td><td>상대 에코 라운드에서만 킬을 몰아 딴 사람</td><td>전투 점수만큼 높게 평가하지 않음</td></tr>
<tr><td>3</td><td>“기다려” 콜 뒤 혼자 진입해 첫 데스 3번 (음성O)</td><td>범인. 근거에 대화 + 킬 이벤트가 같이 나옴</td></tr>
<tr><td>4</td><td>음성X 팀원이 스탯은 평균</td><td>소통으로 감점 · 가점하지 않음</td></tr>
<tr><td>5</td><td>음성 인식이 깨진 문장이 섞인 경기</td><td>깨진 문장을 근거로 쓰지 않음</td></tr>
<tr><td>6</td><td>크게 이긴 경기</td><td>이긴 팀에서도 범인 1명, 말투가 과하지 않음</td></tr>
</table>
<p class="small">지시문이나 지식 묶음을 고칠 때마다 6경기를 다시 돌립니다(한 번에 약 $2.5). 결과 화면 아래에 👍 / 👎(이유 한 줄)를 달아, 친구들이 납득하지 못한 판정을 모아 지식 묶음을 고치는 데 씁니다.</p>
</section>
<section class="page">
<h2><span class="num">7</span>비용 예상: $100로 몇 경기?</h2>
<h3>가격 (Anthropic API, 100만 토큰당)</h3>
<table>
<tr><th>모델</th><th class="num">입력</th><th class="num">출력(생각 포함)</th><th>특징</th></tr>
<tr class="hl"><td>Claude Opus 5.5 (추천)</td><td class="num">$4</td><td class="num">$20</td><td>가장 꼼꼼함. 대화 · 기록을 엮어 판단하는 데 유리</td></tr>
<tr><td>Claude Sonnet 5.5</td><td class="num">$2</td><td class="num">$10</td><td>절반 가격. 품질은 실측으로 비교 필요</td></tr>
<tr><td>Claude Haiku 4.5</td><td class="num">$1</td><td class="num">$5</td><td>가장 쌈. 긴 대화에서 근거를 놓칠 수 있음</td></tr>
</table>
<p class="small">한국어는 영어보다 토큰을 많이 씁니다. 계산에서는 한글 1글자 ≈ 1토큰으로 넉넉하게 잡았습니다. 배치(최대 24시간 안에 결과)로 보내면 모든 토큰이 반값이지만, 버튼을 누르고 기다리는 기능이라 기본은 즉시 분석입니다.</p>
<h3>경기 길이는 무작위: 이렇게 계산했습니다</h3>
<table>
<tr><th style="width:20%">바뀌는 값</th><th>계산 방법</th><th style="width:28%">결과 (10판 중 8판 범위)</th></tr>
<tr><td>발로란트 길이</td><td>경기마다 두 팀 실력 차를 뽑고 라운드를 하나씩 진행. 13승제, 12:12면 2점 차가 날 때까지 연장. 라운드 = 구매 30초 + 교전 15~145초 + 끝 7초</td><td>{B['rounds_val']['p10']}~{B['rounds_val']['p90']}라운드, {B['minutes_val']['p10']:.0f}~{B['minutes_val']['p90']:.0f}분 (중간 {B['minutes_val']['p50']:.0f}분)</td></tr>
<tr><td>롤 길이</td><td>12%는 15~22분 조기 항복, 나머지는 평균 31분 ±7분 (18~60분)</td><td>{B['minutes_lol']['p10']:.0f}~{B['minutes_lol']['p90']:.0f}분 (중간 {B['minutes_lol']['p50']:.0f}분)</td></tr>
<tr><td>말하는 양</td><td>음성채널 전체가 1분에 하는 문장 수. 경기마다 무작위(중간 18문장, 조용한 방 9 · 말 많은 방 32)</td><td>경기당 {B['lines']['p10']:.0f}~{B['lines']['p90']:.0f}문장</td></tr>
<tr><td>AI 생각 길이</td><td>자료가 길수록 길게, 경기마다 무작위</td><td>출력 {k(B['out']['p10'])}~{k(B['out']['p90'])} 토큰</td></tr>
<tr><td>게임 비율</td><td>발로란트 · 롤 반반</td><td>입력 {k(B['in']['p10'])}~{k(B['in']['p90'])} 토큰</td></tr>
</table>
<p class="small">이 값으로 2만 경기의 비용을 계산하고, $100을 다 쓸 때까지 분석하는 시행을 1,500번 돌렸습니다. 실패 · 다시 분석 여유로 5%를 더 잡았습니다. 계산 코드: <code>docs/report/culprit/cost_sim.py</code></p>
<div class="viz"><div class="vt">경기당 비용 분포 (Opus 5.5, 2만 경기)</div><div class="vs">길고 말 많은 경기일수록 오른쪽. {usd(B['cost']['p99'])}를 넘는 경기는 100판 중 1판입니다.</div>{hist_svg()}</div>
</section>
<section class="page">
<h3 style="margin-top:0">경기 하나에 드는 토큰 (Opus 5.5, 평균)</h3>
<table>
<tr><th>부분</th><th class="num">토큰</th><th class="num">비용</th><th>설명</th></tr>
<tr><td>지시문 · 지식 묶음 · 출력 형식</td><td class="num">약 {(FIX['valorant']+FIX['lol'])//2:,}</td><td class="num">{usd((FIX['valorant']+FIX['lol'])/2*4/1e6,3)}</td><td>토큰 세기 API 실측. 발로 {FIX['valorant']:,} · 롤 {FIX['lol']:,}</td></tr>
<tr><td>경기 기록 (10명 · 라운드 · 이벤트)</td><td class="num">약 6,100</td><td class="num">$0.025</td><td>가정: 발로 약 8,100 · 롤 약 4,200. 시연 경기 실측: 발로 22라운드 약 9,400 · 롤 28분 약 1,900</td></tr>
<tr><td>음성 대화</td><td class="num">약 {B['lines']['mean']*24:,.0f}</td><td class="num">{usd(B['lines']['mean']*24*4/1e6,3)}</td><td>평균 {B['lines']['mean']:.0f}문장 × 24토큰. <b>가장 크게 흔들리는 값</b></td></tr>
<tr><td>채팅</td><td class="num">약 250</td><td class="num">$0.001</td><td></td></tr>
<tr><td>AI 답 (10명 평가 · 범인 · 근거)</td><td class="num">약 3,300</td><td class="num">$0.066</td><td>JSON</td></tr>
<tr><td>AI 생각</td><td class="num">약 {B['out']['mean']-3280:,.0f}</td><td class="num">{usd((B['out']['mean']-3280)*20/1e6,3)}</td><td>출력 값으로 계산. <b>비용의 절반 이상</b></td></tr>
<tr class="hl"><td>합계</td><td class="num">입력 {B['in']['mean']:,.0f} · 출력 {B['out']['mean']:,.0f}</td><td class="num">{usd(B['cost']['mean'],3)}</td><td>발로 {usd(B['cost_val']['mean'])} · 롤 {usd(B['cost_lol']['mean'])}</td></tr>
</table>
<div class="viz"><div class="vt">$100로 분석할 수 있는 경기 수</div><div class="vs">발로 · 롤 반반, 실패 · 다시 분석 여유 5% 포함. 빨간 막대가 추천 설정입니다.</div>{bars_html()}</div>
<table>
<tr><th>설정</th><th class="num">경기당 평균</th><th class="num">$100당 경기 수 (5~95%)</th><th class="num">배치(반값)라면</th></tr>
<tr class="hl"><td>Opus 5.5 · 생각 high (추천)</td><td class="num">{usd(B['cost']['mean'])}</td><td class="num">{opus['p50']} ({opus['p5']}~{opus['p95']})</td><td class="num">약 {opus['batch_p50']}</td></tr>
<tr><td>Opus 5.5 · 생각 medium</td><td class="num">{usd(100/MED['mean']/1.05)}</td><td class="num">{MED['p50']} ({MED['p5']}~{MED['p95']})</td><td class="num">약 {MED['p50']*2:,}</td></tr>
<tr><td>Sonnet 5.5</td><td class="num">{usd(B['cost']['mean']/2)}</td><td class="num">{PM['sonnet-5.5']['p50']:,}</td><td class="num">약 {PM['sonnet-5.5']['batch_p50']:,}</td></tr>
<tr><td>Haiku 4.5</td><td class="num">{usd(B['cost']['mean']/4)}</td><td class="num">{PM['haiku-4.5']['p50']:,}</td><td class="num">약 {PM['haiku-4.5']['batch_p50']:,}</td></tr>
</table>
<table>
<tr><th>Opus 5.5 · 방 분위기별</th><th class="num">발로란트만</th><th class="num">롤만</th><th class="num">반반</th></tr>
<tr><td>조용한 방 (1분 9문장)</td><td class="num">{SC['quiet/valorant']['per100']}경기</td><td class="num">{SC['quiet/lol']['per100']}경기</td><td class="num">{SC['quiet/mix']['per100']}경기</td></tr>
<tr class="hl"><td>보통 (1분 18문장)</td><td class="num">{SC['normal/valorant']['per100']}경기</td><td class="num">{SC['normal/lol']['per100']}경기</td><td class="num">{SC['normal/mix']['per100']}경기</td></tr>
<tr><td>말 많은 방 (1분 32문장)</td><td class="num">{SC['loud/valorant']['per100']}경기</td><td class="num">{SC['loud/lol']['per100']}경기</td><td class="num">{SC['loud/mix']['per100']}경기</td></tr>
</table>
<div class="callout info"><b class="t">결론</b>
Opus 5.5로 <b>$100이면 약 {opus['p50']}경기</b>(방 분위기에 따라 약 {SC['loud/mix']['per100']}~{SC['quiet/mix']['per100']}경기)입니다. 경기 길이가 무작위여도 판 수가 많아 평균에 가까워지므로, 가정한 조건 안에서는 1,500번 시행 중 10번에 9번꼴로 {opus['p5']}~{opus['p95']}경기(5~95% 범위)가 나왔습니다. 이 범위는 계산에 넣은 가정 안의 결과이고, 실제 비용을 보장하는 범위는 아닙니다. 더 크게 흔들리는 것은 <b>방에서 말하는 양</b>과 <b>AI가 생각하는 길이</b>입니다.<br>
크레딧은 <b>11월 15일에 만료</b>됩니다. {opus['p50']}경기를 다 쓰려면 하루 {per_day:.0f}판씩 분석해야 하므로, 크레딧을 아끼려고 더 싼 모델을 쓸 이유는 적습니다. 그래서 Opus 5.5를 추천합니다.</div>
<p class="small">고정 프롬프트는 실측값이고, 경기 기록 · 대화 양 · AI 생각 길이는 아직 가정값입니다. 실제 경기 3~5판을 분석하면 사이트 서버 비용 장부에 실제 토큰 · 비용이 남으므로, 그 값으로 이 표를 다시 고칩니다.</p>
</section>
<section class="page">
<h3 style="margin-top:0">예산이 새지 않게 막는 장치</h3>
<table>
<tr><th style="width:26%">장치</th><th>내용</th></tr>
<tr><td>월 상한</td><td>$100 (설정 가능). 넘으면 버튼 잠금, 남은 예산을 화면에 표시</td></tr>
<tr><td>경기당 상한</td><td>출력 32k 토큰 상한 + 입력이 너무 길면(대화 2,500문장 넘음) 잡담 구간을 줄여서 보냄 → 경기 하나가 약 $1을 넘지 않음</td></tr>
<tr><td>하루 횟수</td><td>사이트 전체 하루 20회 (설정 가능)</td></tr>
<tr><td>중복 방지</td><td>한 경기 한 번. 동시에 눌러도 한 번만 실행. 다시 분석은 관리자만</td></tr>
<tr><td>두 번째 방어선</td><td>Claude Console 조직 지출 한도를 $100로 설정</td></tr>
</table>
</section>
<section class="page">
<h2><span class="num">8</span>리플레이 동기화</h2>
<div class="flow">
<div class="s"><div class="ic">🎬</div><div class="t">리플레이 재생</div><div class="d">롤 · 발로란트<br>게임 안 리플레이</div></div>
<div class="s"><div class="ic">👀</div><div class="t">exe가 알아챔</div><div class="d">어느 경기인지 찾아<br>기록이 있는지 확인</div></div>
<div class="s"><div class="ic">💬</div><div class="t">팝업으로 물음</div><div class="d">“리플레이와<br>동기화하시겠습니까?”</div></div>
<div class="s"><div class="ic">🔗</div><div class="t">동기화</div><div class="d">리플레이 시간 따라<br>대화 · 이벤트 · 음성</div></div>
<div class="s"><div class="ic">⏩</div><div class="t">계속 따라감</div><div class="d">멈춤 · 배속 · 되감기<br>모두 따라감</div></div>
</div>
<div class="callout"><b class="t">정한 원칙 (⑦ · ⑧): API로 될 때만 넣습니다</b>
게임이 <b>공식 · 비공식 API로 리플레이 재생 시간을 알려 줄 때만</b> 그 게임의 동기화를 만듭니다. 화면 글자 인식(OCR)으로 시간을 읽거나, 앱이 게임 설정 파일(game.cfg)을 고치는 방법은 쓰지 않습니다. 그래서 먼저 Windows PC에서 어떤 API가 리플레이 중에 무엇을 알려 주는지 확인(R0)하고, 되는 게임만 R1~R3을 진행합니다. 둘 다 안 되면 리플레이 동기화는 넣지 않습니다.</div>
<figure><img class="shot" src="img/replay-popup.png" alt=""><figcaption><b>화면 예시 4 · 동기화 묻기 (exe 팝업)</b> 리플레이를 틀면 exe가 그 경기의 기록을 찾아 오른쪽 위에 묻습니다. 남은 기록(대화 텍스트 · 음성 파일 · 이벤트 · 범인 분석)을 보여 주고, 음성 파일이 7일이 지나 지워졌으면 “글자만 동기화”로 바뀝니다. 뒤 배경은 자리 표시용입니다. <span class="ex">시안 · API 확인 뒤 만듦</span></figcaption></figure>
<figure><img class="shot" src="img/replay-sync.png" alt=""><figcaption><b>화면 예시 5 · 동기화 창 (exe)</b> 리플레이 시간(오른쪽 위)에 맞춰 지금 말하는 문장을 단어 단위로 짚고 음성을 들려 줍니다. 지나간 줄은 흐리게, 다음 줄은 미리 보입니다. 아래 막대는 경기 전체의 대화 · 킬 · 오브젝트 · 범인 근거 위치입니다. 리플레이를 옮기는 API까지 있으면 줄을 눌러 리플레이를 그 시간으로 옮깁니다. <span class="ex">시안 · 이름과 기록은 예시</span></figcaption></figure>
</section>
<section class="page">
<h3 style="margin-top:0">R0에서 확인할 것 (Windows PC, 리플레이 1판씩)</h3>
<table>
<tr><th style="width:16%"></th><th style="width:42%">리그 오브 레전드</th><th>발로란트</th></tr>
<tr><td>리플레이</td><td>클라이언트 “경기 기록”에서 내려받아 재생 (.rofl 파일, 같은 패치 안에서만)</td><td>패치 12.10부터 <b>경쟁전 · 일반전 · 신속플레이 · 프리미어 · 사용자 지정 게임</b>, 친구 경기도 경력 탭에서 볼 수 있음. <b>내전(사용자 지정)은 방장이 경기마다 시작 전에 녹화를 켜야</b> 리플레이가 남음</td></tr>
<tr><td>확인할 API</td><td>① 롤 클라이언트 로컬 API(LCU, 비공식): 리플레이 보는 중인지, 어느 경기(경기 번호)인지<br>② 게임 로컬 API(이 PC 안 <code>127.0.0.1:2999</code>): 설정을 바꾸지 않은 상태에서 리플레이 중에 게임 시간이 나오는지<br>③ 공식 Replay API(<code>/replay/playback</code>): 재생 시간 · 멈춤 · 배속 · 옮기기. <b>game.cfg 에 한 줄을 넣어야 켜지므로 앱이 켜지 않음</b>. 이미 켜져 있는 PC에서만 씀</td><td>① Riot 클라이언트 로컬 API(비공식, 지금 경기 감지에 쓰는 상태 정보): 리플레이 보는 중인지, 어느 경기인지<br>② 같은 API에서 리플레이 재생 시간이나 라운드가 나오는지</td></tr>
<tr><td>되면</td><td>시간을 0.25초마다 읽어 동기화(목표 오차 ±0.5초). ③이 켜져 있으면 줄을 눌러 리플레이도 옮김</td><td>시간을 읽어 동기화. 정확도는 API가 주는 값의 간격에 따라 R0에서 정함</td></tr>
<tr><td>안 되면</td><td colspan="2"><b>그 게임은 리플레이 동기화를 넣지 않습니다.</b> 화면 글자 인식(OCR) · 수동 맞춤 · 설정 파일 고치기로 대신하지 않습니다.</td></tr>
<tr><td>확인 방법</td><td colspan="2">새 exe에 “리플레이 API 확인” 기능을 넣어, 리플레이를 1판씩 틀고 버튼을 누르면 위 API들이 리플레이 중에 무엇을 주는지 기록 파일로 남깁니다. 그 기록으로 게임별로 만들지 정합니다.</td></tr>
</table>
<h3>시간을 맞추는 원리</h3>
<ul>
<li>겜녹이는 경기마다 <b>게임 시간</b>(킬 · 라운드 이벤트)과 <b>실제 시각</b>(음성 문장)을 같이 저장하고, 둘의 차이를 이미 맞춰 둡니다(지금 사이트의 “R7 · 0:42” 표시가 이 값).</li>
<li>롤: 리플레이 재생 시간 = 게임 시간 → 실제 시각 = 경기 시작 시각 + 재생 시간. 그 시각의 음성 문장과 이벤트를 띄웁니다.</li>
<li>발로란트: API가 주는 리플레이 시간(또는 라운드 + 라운드 안 시간) → Riot 경기 결과에 있는 그 라운드 시작 게임 시간 → 실제 시각.</li>
<li>조금 어긋나면 동기화 창의 <b>±0.5초</b> 버튼으로 맞추고, 그 경기에 저장합니다.</li>
</ul>
<h3>팝업 · 음성 재생 규칙</h3>
<ul>
<li><b>묻는 조건</b>: 그 경기 기록(대화 텍스트나 이벤트)이 있을 때만 묻습니다. 어느 경기인지 하나로 정하지 못하면 후보 경기(맵 · 점수 · 날짜 · 길이)를 보여 주고 고르게 합니다. 기록이 없거나, 녹음 중이거나, “이 경기는 다시 묻지 않기”를 고른 경기는 묻지 않습니다.</li>
<li><b>전체 화면 게임</b>: 게임이 “전체 화면” 모드면 다른 창이 위에 뜨지 못합니다. 그때는 알림 소리 + Windows 알림을 보내고, 게임 안에서 <b>Ctrl+Shift+G</b>(동기화) · <b>Ctrl+Shift+H</b>(무시)로 답할 수 있게 합니다. “테두리 없는 창 모드”를 권합니다.</li>
<li><b>동기화 창</b>: exe의 새 창입니다. 두 번째 모니터에 두거나, 📌 항상 위 · 작게 보기로 게임 옆에 띄웁니다.</li>
<li><b>음성</b>: 리플레이를 멈추면 같이 멈추고, 되감으면 그 지점부터 다시 들려 줍니다. 2배속까지는 같이 빨라지고, 더 빠르면 글자만 보여 줍니다. 여러 명이 동시에 말한 구간은 겹쳐서 재생합니다. 음성 파일이 지워진 경기는 글자만 보여 줍니다.</li>
<li><b>범인 분석과 연결</b>: 분석 결과가 있으면 범인 근거 순간에 🔍 표시를 붙입니다.</li>
<li><b>보안 · 비용</b>: 모두 이 PC 안(127.0.0.1)에서만 일어나고 사이트 서버 · 인터넷 · AI를 쓰지 않습니다. 비용 0. 게임 메모리를 읽거나 게임 파일 · 설정 파일을 고치지 않고, 화면을 읽지도 않습니다. Riot 로컬 API의 자체 서명 인증서는 지금처럼 이 PC 안 주소에만 예외를 둡니다.</li>
</ul>
</section>
<section class="page">
<h2 style="margin-top:0"><span class="num">9</span>만드는 순서 · 진행 상황</h2>
<table>
<tr><th style="width:15%">단계</th><th>할 일</th><th style="width:30%">확인 방법</th><th style="width:11%">상태</th></tr>
<tr><td><b>C1</b> 기록 보강</td><td>경기 상세에서 추가 지표 저장(4장). “분석 가능” 판정(경기 결과 · 녹음 공백 1분 · 음성 변환). 근거 번호가 달린 분석 자료 만들기, 결과 저장. 녹음 안내 문구에 AI 분석 안내</td><td>시연 22라운드 · 롤 경기로 판정 · 자료 모양 자동 테스트. 녹음 늦게 시작 · 변환 대기 · 녹음 제외 경기가 막히는지</td><td class="done">완료</td></tr>
<tr><td><b>C2</b> 서버 분석</td><td>Claude 호출(구조화 출력), 근거 번호 확인, 예산 장부 · 하루 횟수 · 중복 방지, 결과를 게임 PC에 저장</td><td>가짜 AI 응답 자동 테스트(없는 근거 · 빠진 사람 · 예산 초과 · 동시 클릭 · 거절). 실제 Claude 1회 호출 성공</td><td class="done">완료</td></tr>
<tr><td><b>C3</b> 화면</td><td>범인찾기 탭, 진행 단계, 결과 화면(PC · 휴대폰), 근거 → 듣기 · 타임라인, 경기 화면 버튼</td><td>실제 앱 코어 + 사이트 서버 + 브라우저로 화면 캡처(2장), 보안 정책(CSP) 위반 · 오류 없음</td><td class="done">완료</td></tr>
<tr><td><b>C5</b> 배포</td><td>사이트 서버 배포(API 키 넣기), 앱 새 버전(v1.3.0) exe 빌드 · 릴리스</td><td>배포 전 백업, 배포 뒤 상태 확인 · 실제 분석 1회</td><td class="todo">승인 대기</td></tr>
<tr><td><b>C4</b> 실측 · 조정</td><td>새 exe로 실제 경기 3~5판 분석, 결과 품질과 실제 비용 확인, 지시문 · 지식 묶음 · 생각 깊이 조정, 7장 표 갱신</td><td>같이 결과 검토 (범인 판정이 납득되는지)</td><td class="todo">배포 뒤</td></tr>
<tr><td><b>R0</b> 리플레이 API 확인</td><td>새 exe의 “리플레이 API 확인” 기능으로 롤 · 발로란트 리플레이 중 API가 주는 값 기록(8장)</td><td>롤 리플레이 1판, 발로란트 리플레이 1판</td><td class="todo">배포 뒤</td></tr>
<tr><td><b>R1~R3</b> 리플레이 동기화</td><td>R0에서 API로 시간을 읽을 수 있는 게임만: 감지 · 팝업, 동기화 창(시간 따라가기 · 음성 · 범인 근거 표시)</td><td>가짜 API로 자동 테스트, 실제 리플레이로 멈춤 · 배속 · 되감기 따라가는지</td><td class="todo">R0 결과에 따라</td></tr>
</table>
<p class="small">예전 exe로도 사이트는 열리지만 범인찾기는 “게임 PC 앱을 업데이트해 주세요”로 막습니다. 코드: 앱 <code>app/src/core/culprit.ts</code>, 서버 <code>site/server/src/culprit.ts</code>, 화면 <code>site/web/src/pages/CulpritPage.tsx</code>.</p>
<h2 style="margin-top:14px"><span class="num">10</span>정한 것 · 남은 일</h2>
<table>
<tr><th style="width:24%">질문</th><th style="width:30%">답 (2026-10-15)</th><th>반영</th></tr>
<tr><td>① "범인"의 뜻</td><td>가장 못했다 + 가장 발목을 잡았다 + 패배의 원인 등 모두 종합</td><td>지시문 v1.1에 세 기준을 종합하도록 넣음. 팀마다 1명, 팀 최저점(서버 확인)</td></tr>
<tr><td>② 분석 버튼</td><td>(가) 등록된 앱 유저 이상</td><td>서버가 앱 유저 명단으로 확인. 다시 분석은 관리자 이상, 결과 보기는 모두</td></tr>
<tr><td>③ 모델</td><td>Opus 5.5</td><td>Claude Opus 5.5 · 생각 깊이 high</td></tr>
<tr><td>④ API 키</td><td>받음</td><td>동작 확인. 서버 비밀 저장소에만 보관, 배포 때 사이트 서버 환경 변수로만 넣음</td></tr>
<tr><td>⑤ 말투</td><td>(나) 중간맛</td><td>기본 말투 medium</td></tr>
<tr><td>⑥ 멤버 공지</td><td>TTS 문구에 추가</td><td>녹음 안내 문구 · 기본 음성 교체 (5장)</td></tr>
<tr><td>⑦ 발로란트 리플레이</td><td>비공식 API에 없으면 추가하지 않기</td><td>OCR 안 함. R0에서 API 확인 뒤 결정 (8장)</td></tr>
<tr><td>⑧ 롤 리플레이</td><td>비공식 API에 없으면 추가하지 않기</td><td>앱이 game.cfg 를 고치지 않음. R0에서 API 확인 뒤 결정 (8장)</td></tr>
</table>
<div class="q"><div class="qh"><span class="id">A</span>배포 승인</div>사이트 서버 배포(API 키 넣기)와 새 exe(v1.3.0) 릴리스를 진행해도 될지. <span class="rec">→ 승인하시면 배포하고, 새 exe로 실제 경기 3~5판을 분석해 같이 결과를 봅니다(C4).</span></div>
<div class="q"><div class="qh"><span class="id">B</span>API 키 관리</div>키가 디스코드 채팅에 그대로 올라왔습니다. <span class="rec">→ 그 메시지를 지워 주시고, 오래 쓰실 거면 Console에서 키를 새로 만들어 주세요. Console 월 지출 한도 $100도 걸어 두시면 사이트 서버 한도와 함께 두 번 막힙니다.</span></div>
<div class="q"><div class="qh"><span class="id">C</span>리플레이 API 확인 (R0)</div>새 exe에 “리플레이 API 확인” 기능을 같이 넣을지. <span class="rec">→ 넣으면 리플레이를 1판씩 틀고 버튼만 눌러 주시면 됩니다. 롤 Replay API를 이미 켜 둔 PC가 아니면, 롤은 클라이언트 API 결과로만 정합니다.</span></div>
</section>
<section class="page">
<h2><span class="num">부록</span>프롬프트 · 지식 묶음 · 출력 형식 원문</h2>
<p class="small">사이트 서버가 실제로 쓰는 원문(<code>site/server/prompt/</code>, 지시문 v1.1). 실제 경기 분석(C4)과 시험 경기(6장)를 거치며 고칩니다. 지시문의 tone 자리는 말투 설정(중간맛)으로 바뀌고, 자동 갱신 칸은 사이트 서버가 하루에 한 번 공식 데이터로 다시 만듭니다.</p>
<h3>A. 지시문 <code>prompt/system.md</code></h3>
<pre class="box ap">{_load('system.md')}</pre>
<h3>B. 발로란트 지식 묶음 <code>prompt/knowledge-valorant.md</code></h3>
<pre class="box ap">{_load('knowledge-valorant.md')}</pre>
<h3>C. 롤 지식 묶음 <code>prompt/knowledge-lol.md</code></h3>
<pre class="box ap">{_load('knowledge-lol.md')}</pre>
<h3>D. 출력 형식 <code>prompt/output-schema.json</code></h3>
<pre class="box ap">{_load('output-schema.json')}</pre>
</section>
</body></html>'''
open('plan.html', 'w').write(HTML)
print('ok', len(HTML))

View File

@@ -0,0 +1,141 @@
"""범인찾기 분석 비용 몬테카를로 추정 (계획서용).
경기 길이·말하는 양·모델 생각 길이를 무작위로 뽑아 경기당 토큰과 비용을 만들고,
$100 을 다 쓸 때까지 경기를 분석하는 시행을 여러 번 돌려 분석 가능 경기 수 분포를 낸다.
결과는 JSON 으로 stdout 에 쓴다. python3 cost_sim.py > sim.json
"""
import json, math, random, statistics as st
R = random.Random(20261015)
# ── 가격 ($ / 1M tokens, Anthropic 1st-party, 2026-09-25 기준) ──
MODELS = {
'opus-5.5': {'in': 4.0, 'out': 20.0, 'label': 'Claude Opus 5.5'},
'sonnet-5.5': {'in': 2.0, 'out': 10.0, 'label': 'Claude Sonnet 5.5'},
'haiku-4.5': {'in': 1.0, 'out': 5.0, 'label': 'Claude Haiku 4.5'},
}
# ── 토큰 가정 ──
# 지시문(prompt/system.md) + 게임별 지식 묶음(prompt/knowledge-*.md) + 출력 형식(prompt/output-schema.json).
# 2026-10-15 v1.2: 토큰 세기 API(claude-opus-5-5)로 실측. 지시문 v1.1 + 지식 묶음(자동 갱신 칸 포함) + 구조화 출력 형식
# (v1.1 초안은 글자 수로 3,900 / 5,000 으로 잡았다)
FIXED_PROMPT = {'valorant': 6649, 'lol': 8204}
VOICE_LINE = 24 # "[R7 0:42] 민수: 레이즈 궁 빠졌어" 한 줄 (한글 1글자≈1토큰, 보수적)
CHAT_LINE = 20
VISIBLE_OUT = 3200 # 10명 평가 + 팀별 범인 2명 근거 + 요약 (JSON)
TALK = { # 음성채널 전체 분당 문장 수 (5명 기준) 중앙값
'quiet': 9, 'normal': 18, 'loud': 32,
}
def lognorm(median, sigma):
return median * math.exp(R.gauss(0, sigma))
def clamp(x, a, b):
return max(a, min(b, x))
def valorant_match():
"""13승제 경쟁전. 경기마다 팀 실력 차를 뽑고 라운드를 하나씩 진행, 12:12 이후 2점 차 연장."""
p = R.uniform(0.35, 0.65)
a = b = 0
rounds = 0
secs = 60 # 시작 전 · 끝 화면
while True:
rounds += 1
secs += 30 + clamp(R.gauss(62, 22), 15, 145) + 7 # 구매 + 교전 + 종료
if R.random() < p: a += 1
else: b += 1
if a >= 12 and b >= 12:
if abs(a - b) >= 2: break
elif a == 13 or b == 13:
break
minutes = secs / 60
data = 800 + rounds * 340 # 10명 표 + 라운드당 킬·경제·피해량·결과
chat = int(minutes * 0.3)
return 'valorant', minutes, rounds, data, chat
def lol_match():
"""솔로/자유 랭크 + 내전. 12% 는 15~22분 조기 항복, 나머지는 평균 31분."""
if R.random() < 0.12:
minutes = R.uniform(15, 22)
else:
minutes = clamp(R.gauss(31, 7), 18, 60)
data = 900 + minutes * 110 # 10명 표(아이템·피해량·시야) + 분당 킬·오브젝트·2분 단위 골드/CS
chat = int(minutes * 0.5)
return 'lol', minutes, None, data, chat
def one_match(game_mix=0.5, talk='normal', effort='high'):
g = valorant_match() if R.random() < game_mix else lol_match()
game, minutes, rounds, data, chat = g
per_min = clamp(lognorm(TALK[talk], 0.35), 2, 70)
lines = int(per_min * minutes)
tin = FIXED_PROMPT[game] + data + lines * VOICE_LINE + chat * CHAT_LINE
think_med = {'medium': 4000, 'high': 8000}[effort]
think = clamp(lognorm(think_med + 0.08 * tin, 0.35), 1500, 30000)
tout = VISIBLE_OUT * R.uniform(0.85, 1.2) + think
return {'game': game, 'minutes': minutes, 'rounds': rounds, 'lines': lines, 'in': tin, 'out': tout}
def cost(m, model, batch=False):
c = (m['in'] * MODELS[model]['in'] + m['out'] * MODELS[model]['out']) / 1e6
return c * (0.5 if batch else 1.0)
RETRY = 1.05 # 실패·재분석 여유 5%
def matches_per_budget(model, budget=100.0, trials=4000, **kw):
counts = []
for _ in range(trials):
spent, n = 0.0, 0
while True:
c = cost(one_match(**kw), model) * RETRY
if spent + c > budget: break
spent += c; n += 1
counts.append(n)
counts.sort()
q = lambda f: counts[int(f * (len(counts) - 1))]
return {'p5': q(0.05), 'p50': q(0.5), 'p95': q(0.95), 'mean': st.mean(counts)}
def pct(xs, f):
xs = sorted(xs); return xs[int(f * (len(xs) - 1))]
out = {}
# 1) 기준 시나리오 표본 (Opus 5.5, 발로·롤 반반, 보통 수다, effort high)
sample = [one_match() for _ in range(20000)]
for m in sample: m['cost'] = cost(m, 'opus-5.5')
def summ(xs):
return {k: round(pct(xs, f), 4) for k, f in (('p10', .1), ('p50', .5), ('p90', .9), ('p99', .99))} | {'mean': round(st.mean(xs), 4)}
out['base'] = {
'minutes_val': summ([m['minutes'] for m in sample if m['game'] == 'valorant']),
'rounds_val': summ([m['rounds'] for m in sample if m['game'] == 'valorant']),
'minutes_lol': summ([m['minutes'] for m in sample if m['game'] == 'lol']),
'lines': summ([m['lines'] for m in sample]),
'in': summ([m['in'] for m in sample]),
'out': summ([m['out'] for m in sample]),
'cost': summ([m['cost'] for m in sample]),
'cost_val': summ([m['cost'] for m in sample if m['game'] == 'valorant']),
'cost_lol': summ([m['cost'] for m in sample if m['game'] == 'lol']),
}
# 히스토그램 (경기당 비용, $0.025 간격)
bins = {}
for m in sample:
b = round(math.floor(m['cost'] / 0.025) * 0.025, 3); bins[b] = bins.get(b, 0) + 1
out['hist'] = sorted(bins.items())
out['hist_n'] = len(sample)
# 2) 모델별 $100 경기 수 (보통, 반반)
out['per_model'] = {}
for mk in MODELS:
r = matches_per_budget(mk, trials=1500)
r['batch_p50'] = round(r['p50'] * 2) # 배치는 모든 토큰 50% → 경기 수 2배
out['per_model'][mk] = r
# 3) 수다 정도 × 게임 (Opus 5.5)
out['scenarios'] = {}
for talk in ('quiet', 'normal', 'loud'):
for mix, name in ((1.0, 'valorant'), (0.0, 'lol'), (0.5, 'mix')):
xs = []
for _ in range(6000):
m = one_match(game_mix=mix, talk=talk); xs.append(cost(m, 'opus-5.5'))
mean = st.mean(xs)
out['scenarios'][f'{talk}/{name}'] = {'mean': round(mean, 4), 'p90': round(pct(xs, .9), 4),
'per100': int(100 / (mean * RETRY))}
# 4) effort medium (Opus 5.5)
out['opus_medium'] = matches_per_budget('opus-5.5', trials=1500, effort='medium')
print(json.dumps(out, ensure_ascii=False, indent=1))

Binary file not shown.

After

Width:  |  Height:  |  Size: 632 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 KiB

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