Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ce9235a8e | ||
|
|
fa6126e17f | ||
|
|
2ffb18263c | ||
|
|
3f7bf1cb86 | ||
|
|
0dd46a5e16 | ||
|
|
db2f1866e4 | ||
|
|
125e2a22ee | ||
|
|
b230443409 | ||
|
|
7db2a5d69f | ||
|
|
b8e76aba25 | ||
|
|
2ddba2e4e5 |
50
README.md
@@ -8,7 +8,7 @@
|
||||
- 설계·계획: [`docs/gemnoki-project-plan.pdf`](docs/gemnoki-project-plan.pdf), 개발 구조·인터페이스: [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
|
||||
- 범인찾기 · 리플레이 동기화 계획서 v1.2 (결정 반영): [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf) · 원본 · 비용 계산 · 프롬프트 초안: `docs/report/culprit/` (실제로 쓰는 프롬프트는 `site/server/prompt/`)
|
||||
- **제작 완료 보고서 (M0~M8)**: [`docs/gemnoki-final-report.pdf`](docs/gemnoki-final-report.pdf) · 단계별 테스트 기록: [`docs/dev/test-results.md`](docs/dev/test-results.md)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.3.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.0) (`GameVoiceRecorder-1.3.0-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.0-portable.exe`) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.3.6](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.6) (`GameVoiceRecorder-1.3.6-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.6-portable.exe`) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
|
||||
## 로그인 · 관리자 (v1.2.0~)
|
||||
|
||||
@@ -19,6 +19,35 @@
|
||||
- 앱은 시작할 때와 10분마다 등록 여부를 다시 확인한다. 등록이 해제되면 바로 잠그고 봇 · 녹음 · 사이트 연결을 멈춘다. 사이트 서버에 못 붙으면 마지막 확인 뒤 3일까지는 그대로 쓴다.
|
||||
- 서버 쪽: `site/server/src/app-auth.ts` (`/auth/app/*`, `/app/me`, `/app/admin/users`), 앱 쪽: `app/src/core/auth.ts`, 권한 목록: `app/src/core/roles.ts`. 로그인 E2E: `app/scripts/login-e2e.mts`.
|
||||
|
||||
## v1.3.6 바뀐 점
|
||||
|
||||
- **목소리 깨짐**: 녹음기가 디스코드 패킷이 "도착한 간격"으로 말 사이 쉼을 채웠다. 게임 중(CPU 부하)에는 패킷이 2~3개씩 몰려 와서 말 중간에 20ms 무음이 계속 끼었다 (사용자 파일: 실제 7.0초 발화가 8.5초, 패킷 3개 중 1개가 무음). 이제 RTP 타임스탬프로 패킷 자리를 정한다 (`recorder.ts` `tapRtp` · `Utterance.place`). 예전 녹음은 처음 켤 때 한 번 끼운 무음을 빼고 다시 변환한다 (`ogg.ts` `removeInsertedSilence`)
|
||||
- **말한 사람 "알 수 없음"**: 앱이 `users.updated` 를 빈 목록으로 보내 사이트가 유저 목록을 비웠다. 이제 실제 목록을 보낸다 (사이트도 빈 목록이면 다시 받아 옴)
|
||||
- **잡음**: 목소리 없음 · 잡음에서 지어낸 문장 · 같은 말 반복은 사이트에 보이지 않고 ogg 도 지운다 (경기 중 실시간 판정은 경기 뒤 정밀 모델이 다시 본 다음). 로그에 "잡음 발화 … 숨김 · 음성 파일 삭제 (이유, 인식 문장)" 로 남는다. 목소리가 0.15초라도 있으면 Whisper 로 넘기고, 반복 고리는 한 번으로 줄여 남은 말을 보여 준다
|
||||
- **시작 창**: 포터블 exe 를 푸는 동안 작은 그림 창(`assets/app/splash.bmp`), 앱이 켜지는 동안 "켜는 중" 창
|
||||
- **녹음 안내 말 속도** 0.1~2.0 (Edge TTS 는 0.5~2.0, 그보다 느리면 워커 `tempo` 가 atempo 로 늘림)
|
||||
- **사이트**: 재생 음량 0~200% · 발화 우클릭(재생 · 자세한 정보(원본 ogg 이름 · 게임 PC 경로 · 크기 · 인식 정보) · ogg 다운로드 · 내용 복사, 앱 `GET /api/utterances/:id/info`)
|
||||
- **사이트 로그**: 사이트 서버가 `data/logs/site-날짜.log` 로 남긴다 (게임 PC 연결 · 끊김 · 기록 요청 결과 · 봇 중계 · 범인찾기 · 브라우저 오류). 관리자는 `https://gvr.tkrmagid.kr/logs` 에서 게임 PC 가 꺼져 있어도 보고 내려받는다 (잠금 화면 · 설정 메뉴에 링크). 14일 보관
|
||||
- **지금 게임**: 앱 게임 연동 탭 · 사이트(머리글 · 타임라인 오른쪽)에 연결된 게임 · 상태(메뉴 · 대기열 · 요원/챔피언 선택 · 경기 중) · 모드 · 맵 · 라운드 · 점수 · 내 요원/챔피언 · KDA · 게임 시간
|
||||
- 발로란트 데스매치 · 팀 데스매치 · 에스컬레이션: 킬 점수를 라운드로 착각해 "R63 승리" 같은 가짜 라운드와 에이스를 만들던 것 고침. 경기 상세에 선수 이름이 비어 오면 이름 서비스로 채운다 ("주인 계정 자동 연결: #" 고침)
|
||||
|
||||
## v1.3.5 바뀐 점
|
||||
|
||||
- **표시 이름 빈틈**: 표시 이름을 정하기 전에 시작한 범인 분석이 정한 뒤에 저장되면 결과 본문에 예전 이름이 남을 수 있었다 (이미 이름이 바뀐 유저는 다시 훑지 않았음). 이제 가린 예전 이름을 기억해 두고(`meta.hidden_names`), 분석을 저장할 때마다 · 이름을 다시 받을 때마다 모든 분석에서 바꾼다
|
||||
- 상태 메시지 실제 확인: `site/server/scripts/presence-e2e.mts` (사이트 서버 코드로 봇을 빈 음성채널에 넣었다 빼며 확인)
|
||||
|
||||
## v1.3.4 바뀐 점
|
||||
|
||||
- **슬래시 명령 응답**: 그 디스코드 서버를 지켜보는 겜녹이 앱이 없으면 사이트 서버가 명령을 무시해서 디스코드에 "애플리케이션이 응답하지 않았어요"만 떴다 (봇 토큰을 직접 쓰는 옛 v1.1.0 PC 와 겹치지 않게 넣은 동작). 이제 1.5초 기다렸다가 아무도 받지 않았으면 이유를 답한다: 앱이 꺼져 있음 / 내 앱이 다른 서버를 녹음 대상으로 정해 둠 / 아직 연결 중. 앱은 서버가 권한을 다시 확인하다 지켜보기를 끊으면 1분 뒤 다시 요청한다
|
||||
- **봇 상태 메시지**: 녹음 중(봇이 어느 서버에서든 음성채널에 있음)이면 빨간 상태(다른 용무 중) + "🔴 녹음 중", 아니면 "🎙️ 대기 중 · /녹음시작". 겜녹이 봇은 사이트 서버가, 다른 봇 모드는 앱이 바꾼다. 봇 하나가 여러 서버에 들어가 있어서 채널 이름은 넣지 않는다
|
||||
|
||||
## v1.3.3 바뀐 점
|
||||
|
||||
- **따라갈 사람 목록**: 녹음할 서버의 멤버가 모두 나온다. 내 계정이 맨 위, 그다음 관리자(최고 관리자 포함), 나머지는 이름순. 예전에는 봇이 서버를 지켜보기 전에 목록을 요청하면 사이트 서버가 거절했고 앱이 그 오류를 숨겨 "선택 안 함"만 보였다. 이제 가입한 서버면 바로 받고, 실패하면 오류와 다시 불러오기 버튼을 보여 준다. 녹음할 서버를 바꾸면 봇이 새 서버를 바로 지켜본다. 서버: `GET /app/admins`
|
||||
- **롤 채팅은 API 로만**: 화면 글자 인식(OCR)을 앱 · 워커 · 빌드에서 모두 뺐다 (pywinrt · mss · Pillow 의존성 제거). 롤 클라이언트(LCU) API 로 챔피언 선택 · 게임 후 채팅을 받는다. 롤은 게임 중 전체 · 팀 채팅을 주는 API 가 없다 (LCU · 게임 클라이언트 API 모두, 비공식 포함). 게임 로그 파일(r3dlog)에 채팅이 남아 있으면 경기 뒤에 붙인다
|
||||
- **표시 이름 (실명 숨기기)**: 디스코드 아이디마다 보일 이름을 정하면 사이트(로그인 이름 · 대화 기록 · 유저 목록), 앱, 범인 분석에 그 이름만 쓰고 이미 저장된 이름도 바꾼다. 앱 🛡️ 관리자 탭에서 최고 관리자가 정한다. 서버: `GET /app/names`, `PUT /app/admin/names`, `node dist/cli.js name <아이디> [이름]`
|
||||
- 저장소의 시연 · 테스트 데이터, 화면 캡처, 계획서 PDF 에서 실제 이름을 빼고 가짜 이름(하늘)으로 바꿨다
|
||||
|
||||
## 디스코드 봇
|
||||
|
||||
- 기본은 **겜녹이 봇으로 진행**: 토큰을 넣지 않아도 로그인만 하면 바로 연결된다. 봇은 사이트 서버가 디스코드에 연결하고, 앱은 로그인 토큰으로 서버 중계(`/app/bot/ws`)를 받는다.
|
||||
@@ -37,17 +66,16 @@
|
||||
- 사이트 서버: 보안 정책(CSP)으로 이 사이트 스크립트와 이 사이트로의 접속만 허용, 실시간 WebSocket 은 이 사이트에서 온 연결만, 로그인 세션 · 앱 토큰 · 기기 키는 해시로만 저장, 로그에서 로그인 code · state · 검색어를 지운다. 등록 코드 대입 · 로그인 요청 폭주는 IP 별로 막는다. HSTS · http→https 이동 · TLS 1.2 미만 차단은 앞단 프록시(NPMplus)가 한다.
|
||||
- 디스코드 음성은 디스코드 자체 암호화(DAVE 종단간 암호화)로 간다.
|
||||
|
||||
## 🔍 범인찾기 (v1.3.0~)
|
||||
## 🔍 범인찾기 (v1.3.2~)
|
||||
|
||||
끝난 경기를 고르고 "범인 분석"을 누르면 AI(Claude)가 그 경기의 음성 대화 · 킬 · 라운드/오브젝트 · 경제 · 채팅 · 10명 스탯을 읽고 10명 평점 · 태그 · 한 줄 평과 팀별 범인 1명(이유 + 근거)을 만든다. 근거를 누르면 그 순간의 음성 · 타임라인으로 간다. 계획서: [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf)
|
||||
|
||||
- 정한 것 (2026-10-15): 범인 = 가장 못함 + 가장 발목 + 결과의 원인을 종합해 팀마다 1명 · 분석 버튼은 등록된 앱 유저 이상(다시 분석은 관리자) · Claude Opus 5.5(생각 high) · 말투 중간맛 · 녹음 안내(TTS)에 "녹음된 대화는 AI 경기 분석에 쓰일 수 있어요" 추가
|
||||
- **전적 사이트 점수 참고**: 평점과 범인은 전적 사이트 점수에서 출발해 승부처 · 역할 · 경제 · 음성 소통으로 더하고 뺀다 (지시문 v1.2)
|
||||
- **기록 점수** (0~10, 모든 경기): OP.GG OP스코어를 우리 기록으로 다시 계산한 점수 + 경기/팀 순위 + MVP · ACE + 점수를 올리고 깎은 지표. 발로란트는 OP.GG 가 밝힌 입력(라운드 승률 · KAST · ACS · 피해 격차), 롤은 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드. 계수는 OP.GG 공식 MCP 로 받은 실제 경기의 OP스코어에 맞췄다 (교차 검증: 발로란트 상관 0.97 · 평균 오차 0.49점, 롤 상관 0.94 · 0.60점 · 팀 최하위 일치 85%). `packages/shared/src/rating.ts`, 맞추는 도구 `tools/opscore-fit/`
|
||||
- **OP.GG 실제 OP스코어**: 분석할 때 OP.GG 공식 MCP(`mcp-api.op.gg`)에서 그 경기를 찾으면 그 사이트의 실제 점수를 같이 준다 (롤: 시작 시각 · 길이로 찾고 10명, 발로란트: 경기 번호로 선수마다). 내전(사용자 설정 게임)은 OP.GG 에 없어 기록 점수만 쓴다. `site/server/src/opgg.ts`, 끄기 `CULPRIT_OPGG=0`
|
||||
- **전적 사이트 계산법 참고**: 평점과 범인은 기록 점수에서 출발해 승부처 · 역할 · 경제 · 음성 소통으로 더하고 뺀다 (지시문 v1.2). 분석할 때 외부 전적 사이트에는 접속하지 않고, 앱이 경기 기록으로 직접 계산한다
|
||||
- **기록 점수** (0~10, 모든 경기): OP.GG OP스코어 계산법을 따라 우리 기록으로 계산한 점수 + 경기/팀 순위 + MVP · ACE + 점수를 올리고 깎은 지표. 발로란트는 OP.GG 가 밝힌 입력(라운드 승률 · KAST · ACS · 피해 격차), 롤은 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드. OP.GG 는 가중치를 공개하지 않아서, 계수는 개발할 때 한 번 OP.GG 공식 MCP 로 받은 실제 경기 점수에 맞춰 정했다 (교차 검증: 발로란트 상관 0.97 · 평균 오차 0.49점, 롤 상관 0.94 · 0.60점 · 팀 최하위 일치 85%). `packages/shared/src/rating.ts`, 맞추는 도구 `tools/opscore-fit/`
|
||||
- **LOL.PS 라인전**: LOL.PS 라인전 점수의 입력과 같은 10 · 15분 맞라이너 CS · 골드 · 경험치 차 (LOL.PS 점수 모델은 공개되지 않아 차이 값만). 참고한 원문 · 구현 대응: [`tools/opscore-fit/README.md`](tools/opscore-fit/README.md)
|
||||
- 실제 E2E (2026-10-15, `app/scripts/culprit-real-e2e.mts`): 실제 Claude Opus 5.5(생각 high) + 실제 OP.GG. 발로란트 시연 경기 42초 · $0.15, 롤 실제 랭크 경기(OP.GG 점수 10명 찾음) 36초 · $0.11. 기록 · [`docs/dev/test-results.md`](docs/dev/test-results.md)
|
||||
- 리플레이 동기화: 공식 · 비공식 API 로 리플레이 시간을 읽을 수 있을 때만 넣는다 (화면 글자 인식(OCR) · 게임 설정 파일 고치기는 하지 않음). Windows 실기 확인 전이라 v1.3.0 에는 없다
|
||||
- 실제 E2E (2026-10-15, v1.3.2, `app/scripts/culprit-real-e2e.mts`): 실제 Claude Opus 5.5(생각 high), 외부 사이트 접속 없음. 발로란트 시연 경기 33초 · $0.138, 롤 시연 경기 36초 · $0.123. 기록 · [`docs/dev/test-results.md`](docs/dev/test-results.md)
|
||||
- 리플레이 동기화: 공식 · 비공식 API 로 리플레이 시간을 읽을 수 있을 때만 넣는다 (화면 글자 인식(OCR) · 게임 설정 파일 고치기는 하지 않음). Windows 실기 확인 전이라 v1.3.x 에는 없다
|
||||
- 앱: 경기 상세에서 추가 지표 저장(발로란트 피해량 · 받은 피해 · KAST · 첫킬 · 설치/해체 · 라운드별 장비, 롤 포지션 · 딜량 · 시야 · 10/15분 CS), "분석할 수 있는 경기" 판정(경기 결과 · 녹음 공백 1분 · 음성 변환), 근거 번호가 달린 AI 자료 만들기, 결과 저장(`culprit_analyses`). `app/src/core/culprit.ts`
|
||||
- 사이트 서버: Claude API 키는 서버 환경 변수 `ANTHROPIC_API_KEY` 에만 (`deploy/site/set-anthropic-key.sh`). 권한 · 월 $100 · 하루 20회 · 중복 잠금, 구조화 출력, 근거 번호 확인, 비용 장부(토큰 · 비용만, 대화 내용 없음). `site/server/src/culprit.ts`, 지시문 · 지식 묶음 `site/server/prompt/` (지식 묶음의 요원 · 챔피언 목록은 공식 데이터로 하루 한 번 갱신)
|
||||
- 화면: 사이트 🔍 범인찾기 탭 (`site/web/src/pages/CulpritPage.tsx`), 경기 화면의 "🔍 범인 보기". 화면 확인: `node --import tsx app/scripts/culprit-shots.mts`
|
||||
@@ -60,18 +88,18 @@
|
||||
| M1 녹음 + STT 기본 | 따라가기·명령 참여, TTS 안내, 유저별 녹음, 대기열 STT, /녹음제외·참여 | ✅ 완료 ([실음성 테스트](docs/dev/test-results.md)) |
|
||||
| M2 사이트 서버 · 사이트 v1 | 디스코드 로그인, 연결 확인·잠금, 타임라인·따라 읽기·필터·검색·실시간 | ✅ 완료 · https://gvr.tkrmagid.kr 배포 |
|
||||
| M3 발로란트 연동 | 경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과 시간, 경기 상세 | ✅ 완료 ([전체 스택 테스트](docs/dev/test-results.md)) |
|
||||
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ✅ 완료 (Windows 실기 확인: [기록](docs/dev/test-results.md)) |
|
||||
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ✅ 완료 (Windows 실기 확인: [기록](docs/dev/test-results.md)) · v1.3.3 에서 OCR 은 빼고 LCU API · 로그 파일만 씀 |
|
||||
| M5 exe · 설정 · 모델 | 포터블 exe, 첫 실행 마법사, GPU 감지·모델 다운로드, 암호화 저장, 7일 삭제 | ✅ 완료 (Windows 빌드·실행 확인) |
|
||||
| M6 단어사전 · UI/UX | 핫워드·교정 사전, 사이트 교정 반영, 테마·애니메이션·효과음 | ✅ 완료 ([사전 효과](docs/dev/test-results.md)) |
|
||||
| M7 실사용 테스트 | 통합 테스트, 성능·안정화 | ✅ 완료 (GPU 실음성: CER 3.6%, 지연 1.05초 · [기록](docs/dev/test-results.md)) |
|
||||
| M8 파인튜닝 | 교정 데이터 + 합성 음성 LoRA 학습, 오류율 비교 후 교체 | ✅ 완료 (GPU 시험 학습: CER 4.8% → 1.8%) |
|
||||
| 범인찾기 (v1.3.0) | AI(Claude Opus 5.5 high) 10명 평점 · 팀별 범인 · 근거, 기록 점수(OP.GG OP스코어 방식) · OP.GG 실제 점수 · LOL.PS 라인전 | ✅ 완료 (실제 Claude · OP.GG E2E, 사이트 배포, [v1.3.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.0) · 리플레이 동기화는 Windows 실기 확인 뒤) |
|
||||
| 범인찾기 (v1.3.x) | AI(Claude Opus 5.5 high) 10명 평점 · 팀별 범인 · 근거, 기록 점수(OP.GG OP스코어 계산법) · 10/15분 라인전(LOL.PS 정의) | ✅ 완료 (실제 Claude E2E, 사이트 배포, [v1.3.5](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.5) · 리플레이 동기화는 Windows 실기 확인 뒤) |
|
||||
|
||||
## 저장소 구조
|
||||
|
||||
```
|
||||
app/ 게임 PC 앱 (Electron + Node.js 코어, TypeScript)
|
||||
worker/ STT 워커 (Python, faster-whisper, OCR, 모델 관리, 파인튜닝)
|
||||
worker/ STT 워커 (Python, faster-whisper, 롤 로그 채팅, 모델 관리, 파인튜닝)
|
||||
site/server/ 사이트 서버 (Fastify, Discord OAuth2, 기기 중계)
|
||||
site/web/ 사이트 화면 (React + Vite)
|
||||
packages/shared/ 앱·사이트 공통 타입
|
||||
@@ -95,5 +123,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·롤 로그 채팅)
|
||||
```
|
||||
|
||||
6
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"version": "1.3.1",
|
||||
"version": "1.3.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gvr-app",
|
||||
"version": "1.3.1",
|
||||
"version": "1.3.6",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@discordjs/voice": "^0.19.2",
|
||||
@@ -4677,7 +4677,7 @@
|
||||
}
|
||||
},
|
||||
"node_modules/prism-media": {
|
||||
"version": "1.3.5",
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz",
|
||||
"integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==",
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"productName": "겜녹이",
|
||||
"version": "1.3.1",
|
||||
"version": "1.3.6",
|
||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||
"private": true,
|
||||
"main": "dist/main.cjs",
|
||||
@@ -107,7 +107,8 @@
|
||||
},
|
||||
"portable": {
|
||||
"artifactName": "GameVoiceRecorder-${version}-portable.exe",
|
||||
"unpackDirName": "GameVoiceRecorder"
|
||||
"unpackDirName": "GameVoiceRecorder",
|
||||
"splashImage": "../assets/app/splash.bmp"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 12 KiB |
@@ -1,119 +1,53 @@
|
||||
// 범인찾기 실제 E2E: 실제 앱 코어 + 실제 사이트 서버 + 실제 Claude API(Opus 5.5, 생각 high) + 실제 OP.GG MCP + 헤드리스 브라우저.
|
||||
// 1) 발로란트 시연 경기 (22라운드 · 대화) → OP.GG 에 없는 경기 → 기록 점수만으로 분석
|
||||
// 2) 롤: OP.GG 에서 받은 실제 랭크 경기(10명 실제 스탯)에 우리 팀 2명의 대화를 붙인 경기 → OP.GG 실제 OP스코어를 찾아 같이 분석
|
||||
// 비용이 든다 (경기당 약 $0.4). API 키는 secrets.json 에서 읽어 이 프로세스 안에서만 쓴다.
|
||||
// 범인찾기 실제 E2E: 실제 앱 코어 + 실제 사이트 서버 + 실제 Claude API(Opus 5.5, 생각 high) + 헤드리스 브라우저.
|
||||
// 외부 전적 사이트에는 접속하지 않는다 (기록 점수는 OP.GG 계산법을 따라 경기 기록으로 계산).
|
||||
// 1) 발로란트 시연 경기 (22라운드 · 대화) 2) 롤 시연 경기 (10 · 15분 라인전 · 대화)
|
||||
// 비용이 든다 (경기당 약 $0.1~0.4). API 키는 secrets.json 에서 읽어 이 프로세스 안에서만 쓴다.
|
||||
// node --import tsx scripts/culprit-real-e2e.mts [결과 폴더]
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { CulpritInput, CulpritMatchInfo, MatchPlayer } from '@gvr/shared';
|
||||
import type { CulpritInput, CulpritMatchInfo } from '@gvr/shared';
|
||||
import { makeDemoLol } from '../test/fixtures/demo-matches.ts';
|
||||
import { culpritApi, MIN, seedValorant, setup } from '../test/fixtures/culprit-seed.ts';
|
||||
|
||||
const outDir = process.argv[2] || path.join(os.homedir(), '.tmp', 'culprit-real');
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
const root = path.resolve(import.meta.dirname, '..', '..');
|
||||
const apiKey = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.config/ejclaw/secrets.json'), 'utf8')).credentials['anthropic.api/game-voice-recorder'].token as string;
|
||||
const { opggCaller } = await import('../../site/server/src/opgg.ts');
|
||||
const opgg = opggCaller();
|
||||
|
||||
const core = setup();
|
||||
await core.assets.refresh(true).catch(() => undefined);
|
||||
const { id: valId } = seedValorant(core);
|
||||
|
||||
// ---------------------------------------------------------------- 롤: OP.GG 의 실제 랭크 경기
|
||||
const POS: Record<string, string> = { TOP: '탑', JUNGLE: '정글', MID: '미드', ADC: '원딜', SUPPORT: '서폿' };
|
||||
const listOf = async (name: string, tag: string) =>
|
||||
((await opgg('lol_list_summoner_matches', { game_name: name, tag_line: tag, region: 'KR', limit: 10, desired_output_fields: ['data.game_history[].{created_at,game_length_second,game_type,id}'] })) as any).data.game_history as any[];
|
||||
const detailOf = async (g: any) =>
|
||||
((await opgg('lol_get_summoner_game_detail', {
|
||||
region: 'KR',
|
||||
game_id: g.id,
|
||||
created_at: g.created_at,
|
||||
desired_output_fields: [
|
||||
'data.game_detail.teams[].participants[].stats.{assist,champion_level,death,gold_earned,kill,minion_kill,neutral_minion_kill,op_score,time_ccing_others,total_damage_dealt_to_champions,total_damage_taken,vision_wards_bought_in_game,ward_place}',
|
||||
'data.game_detail.teams[].participants[].{position,team_key,champion_id,champion_name}',
|
||||
'data.game_detail.teams[].participants[].summoner.{puuid,game_name,tagline,player}',
|
||||
'data.game_detail.teams[].game_stat.{champion_kill,is_win}',
|
||||
],
|
||||
})) as any).data.game_detail;
|
||||
// 프로 선수가 아닌 사람의 최근 솔로 랭크 (15분 이상)
|
||||
const seedGame = (await listOf('Hide on bush', 'KR1')).find((g) => g.game_type === 'SOLORANKED')!;
|
||||
const seedDet = await detailOf(seedGame);
|
||||
const pick = seedDet.teams.flatMap((t: any) => t.participants).find((p: any) => !p.summoner.player && p.summoner.game_name !== 'Hide on bush');
|
||||
const g = (await listOf(pick.summoner.game_name, pick.summoner.tagline)).find((x) => x.game_type === 'SOLORANKED' && x.game_length_second > 1200)!;
|
||||
const det = await detailOf(g);
|
||||
const all = det.teams.flatMap((t: any) => t.participants.map((p: any) => ({ ...p, win: t.game_stat.is_win, teamKills: t.game_stat.champion_kill })));
|
||||
const selfP = all.find((p: any) => p.summoner.puuid === pick.summoner.puuid) ?? all[0];
|
||||
const opggTruth = new Map<string, number>(all.map((p: any) => [p.summoner.puuid, p.stats.op_score]));
|
||||
const players: MatchPlayer[] = all.map((p: any) => ({
|
||||
puuid: p.summoner.puuid,
|
||||
name: p.summoner.game_name,
|
||||
tag: p.summoner.tagline,
|
||||
team: p.team_key,
|
||||
ally: p.team_key === selfP.team_key,
|
||||
character: { id: String(p.champion_id), name: p.champion_name, icon: null },
|
||||
kills: p.stats.kill,
|
||||
deaths: p.stats.death,
|
||||
assists: p.stats.assist,
|
||||
cs: (p.stats.minion_kill ?? 0) + (p.stats.neutral_minion_kill ?? 0),
|
||||
gold: p.stats.gold_earned,
|
||||
level: p.stats.champion_level,
|
||||
stats: {
|
||||
role: POS[p.position],
|
||||
damage: p.stats.total_damage_dealt_to_champions,
|
||||
damageTaken: p.stats.total_damage_taken,
|
||||
ccSeconds: p.stats.time_ccing_others ?? 0,
|
||||
wardsPlaced: p.stats.ward_place ?? 0,
|
||||
controlWards: p.stats.vision_wards_bought_in_game ?? 0,
|
||||
},
|
||||
}));
|
||||
const LS = Date.parse(g.created_at) + 60000;
|
||||
const LEN = g.game_length_second * 1000;
|
||||
const allyWin = !!selfP.win;
|
||||
const allyKills = all.filter((p: any) => p.team_key === selfP.team_key)[0].teamKills;
|
||||
const enemyKills = all.filter((p: any) => p.team_key !== selfP.team_key)[0].teamKills;
|
||||
const lolId = `lol-${g.id.replace(/[^\w]/g, '').slice(0, 20)}`;
|
||||
core.store.upsertMatch({
|
||||
id: lolId,
|
||||
game: 'lol',
|
||||
started_at: LS,
|
||||
ended_at: LS + LEN,
|
||||
status: 'complete',
|
||||
map: 'Map11',
|
||||
mode: 'CLASSIC',
|
||||
queue: '420',
|
||||
result: JSON.stringify({ win: allyWin, score: { ally: allyKills, enemy: enemyKills } }),
|
||||
detail: JSON.stringify({ live: false, players, goldDiff: [], self: selfP.summoner.puuid }),
|
||||
});
|
||||
// 우리 팀 두 명이 음성채널에 있었다고 하고 대화를 붙인다 (실제 경기 기록 + 시험용 대화)
|
||||
const mates = players.filter((p) => p.ally);
|
||||
const [a, b] = [mates.find((p) => p.puuid === selfP.summoner.puuid)!, mates.find((p) => p.puuid !== selfP.summoner.puuid)!];
|
||||
core.store.upsertUser({ id: 'ua', name: '승한', avatar: null });
|
||||
core.store.upsertUser({ id: 'ub', name: '민수', avatar: null });
|
||||
core.store.setAccounts('ua', [{ puuid: a.puuid, riotId: `${a.name}#${a.tag}` }]);
|
||||
core.store.setAccounts('ub', [{ puuid: b.puuid, riotId: `${b.name}#${b.tag}` }]);
|
||||
// ---------------------------------------------------------------- 롤 시연 경기 + 우리 팀 2명 대화
|
||||
const LS = Date.now() - 80 * MIN;
|
||||
const lol = makeDemoLol();
|
||||
const lolId = 'lol-demo';
|
||||
core.store.setMeta('riot_self_puuid', 'l-sh');
|
||||
core.store.setAccounts('u1', [{ puuid: 'p-sh', riotId: '하늘#V' }, { puuid: 'l-sh', riotId: '하늘#L' }]);
|
||||
core.store.setAccounts('u2', [{ puuid: 'p-ms', riotId: '민수#V' }, { puuid: 'l-ms', riotId: '민수#L' }]);
|
||||
core.store.startSession('s-lol', 'g', 'c', '음성', LS - MIN);
|
||||
core.games.matchStarted({ id: lolId, game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
|
||||
core.games.matchEnded(lolId, LS + lol.durationMs);
|
||||
(core.games.adapters[1] as any).applyHistory(lolId, lol.game, lol.timeline, LS);
|
||||
const talk: [string, number, string][] = [
|
||||
['ua', 2.5, '정글 위쪽에서 시작했어 바텀 조심해'],
|
||||
['ub', 6.2, '용 앞에 와드 박아 줘 시야 없어'],
|
||||
['ua', 6.5, '알았어 지금 갈게'],
|
||||
['ub', 11.0, '미드 미아 미드 미아 내려간다'],
|
||||
['ua', 14.8, '용 한타 열지 마 아직 우리 텔 없어'],
|
||||
['ub', 15.1, '아 들어갔다 아 죽었다 미안'],
|
||||
['ua', 19.5, '바론 시야 먼저 잡고 하자 혼자 가지 마'],
|
||||
['ub', 24.0, allyWin ? '좋아 한타 이겼다 미드 밀자' : '아 또 잡혔네 이거 그냥 서렌 치자'],
|
||||
['ua', 24.3, allyWin ? '억제기 깨고 바로 빠지자' : '아직 안 끝났어 수비하자'],
|
||||
['u1', 2.5, '정글 위쪽에서 시작했어 바텀 조심해'],
|
||||
['u2', 6.2, '용 앞에 와드 박아 줘 시야 없어'],
|
||||
['u1', 8.1, '용 같이 하자 바텀 밀었어'],
|
||||
['u2', 8.3, '아니 탑 갱 각이야 잠깐만'],
|
||||
['u1', 14.8, '용 한타 열지 마 아직 우리 텔 없어'],
|
||||
['u2', 15.1, '아 들어갔다 아 죽었다 미안'],
|
||||
['u1', 19.5, '바론 시야 먼저 잡고 하자 혼자 가지 마'],
|
||||
];
|
||||
for (const [uid, min, text] of talk) {
|
||||
if (min * MIN > LEN) continue;
|
||||
const ts = LS + min * MIN;
|
||||
const id = `lol-${uid}-${min}`;
|
||||
core.store.insertUtterance({ id, session_id: 's-lol', user_id: uid, started_at: ts, ended_at: ts + 1800, audio_path: null, match_id: lolId });
|
||||
core.store.updateUtteranceResult(id, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'large-v3', status: 'precise' });
|
||||
}
|
||||
core.store.endSession('s-lol', LS + LEN + MIN);
|
||||
core.store.endSession('s-lol', LS + lol.durationMs + MIN);
|
||||
|
||||
// ---------------------------------------------------------------- 사이트 서버 (실제 Claude · 실제 OP.GG)
|
||||
// ---------------------------------------------------------------- 사이트 서버 (실제 Claude)
|
||||
const local = await culpritApi(core);
|
||||
const { buildServer } = await import('../../site/server/src/app.ts');
|
||||
const port = 18961;
|
||||
@@ -121,7 +55,7 @@ const site = await buildServer({
|
||||
port, host: '127.0.0.1', publicUrl: `http://127.0.0.1:${port}`, clientId: 'x', clientSecret: 'x', botToken: 'x', allowedGuilds: [], owners: ['u1'], superAdmins: ['u1'],
|
||||
sessionSecret: 'real-e2e-secret-'.repeat(3), dataDir: fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-real-')), webDir: path.join(root, 'site', 'web', 'dist'), version: 't', discordApi: 'http://127.0.0.1:1',
|
||||
assetUpstream: { valmedia: 'https://media.valorant-api.com/', ddragon: 'https://ddragon.leagueoflegends.com/', cdragon: 'https://raw.communitydragon.org/' },
|
||||
culprit: { apiKey, model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium', opgg: true },
|
||||
culprit: { apiKey, model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium' },
|
||||
});
|
||||
site.app.log.level = 'info';
|
||||
await site.app.listen({ host: '127.0.0.1', port });
|
||||
@@ -132,7 +66,7 @@ const { RelayClient } = await import('../src/core/relay/client.ts');
|
||||
const rc = new RelayClient(local as any, core.bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: 't', guildId: 'g' }));
|
||||
rc.start();
|
||||
while (!site.hub.status().online) await new Promise((r) => setTimeout(r, 100));
|
||||
const sess = site.store.createSession({ id: 'u1', name: '승한', avatar: null });
|
||||
const sess = site.store.createSession({ id: 'u1', name: '하늘', avatar: null });
|
||||
const cookieHeader = `gvr_sid=${encodeURIComponent(site.app.signCookie(sess.token))}`;
|
||||
|
||||
const stages: Record<string, string[]> = {};
|
||||
@@ -171,9 +105,9 @@ for (const id of [valId, lolId]) {
|
||||
const ref = (pid: string) => a.players.find((p) => p.id === pid)!;
|
||||
const rows = a.result.players.map((p) => {
|
||||
const pl = ref(p.id);
|
||||
return { id: p.id, team: pl.team, ai: p.score, rating: pl.rating?.score ?? null, opgg: pl.opgg?.score ?? null, truth: opggTruth.get(pl.puuid) ?? null, tag: p.tag, comment: p.comment };
|
||||
return { id: p.id, team: pl.team, ai: p.score, rating: pl.rating?.score ?? null, lane: pl.rating?.lane ?? null, tag: p.tag, comment: p.comment };
|
||||
});
|
||||
const teamLowest = (team: string, key: 'rating' | 'opgg') => {
|
||||
const teamLowest = (team: string, key: 'rating') => {
|
||||
const ps = rows.filter((r) => r.team === team && r[key] !== null);
|
||||
return ps.length ? ps.reduce((x, y) => ((x[key] as number) <= (y[key] as number) ? x : y)).id : null;
|
||||
};
|
||||
@@ -182,11 +116,10 @@ for (const id of [valId, lolId]) {
|
||||
model: a.model,
|
||||
costUsd: a.meta.costUsd,
|
||||
usage: a.meta.usage,
|
||||
opgg: a.meta.opgg,
|
||||
stages: stages[id],
|
||||
summary: a.result.summary,
|
||||
confidence: a.result.confidence,
|
||||
culprits: a.result.teams.map((t) => ({ team: t.team, culprit: t.culprit, reason: t.reason, evidence: t.evidence.map((e) => e.ref), lowestRating: teamLowest(t.team, 'rating'), lowestOpgg: teamLowest(t.team, 'opgg') })),
|
||||
culprits: a.result.teams.map((t) => ({ team: t.team, culprit: t.culprit, reason: t.reason, evidence: t.evidence.map((e) => e.ref), lowestRating: teamLowest(t.team, 'rating') })),
|
||||
players: rows,
|
||||
};
|
||||
console.log(JSON.stringify(report[id], null, 1));
|
||||
|
||||
@@ -18,7 +18,7 @@ const { id: valId } = seedValorant(core);
|
||||
const LS = Date.now() - 80 * MIN;
|
||||
const lol = makeDemoLol();
|
||||
core.store.setMeta('riot_self_puuid', 'l-sh');
|
||||
core.store.setAccounts('u1', [{ puuid: 'p-sh', riotId: '승한#V' }, { puuid: 'l-sh', riotId: '승한#L' }]);
|
||||
core.store.setAccounts('u1', [{ puuid: 'p-sh', riotId: '하늘#V' }, { puuid: 'l-sh', riotId: '하늘#L' }]);
|
||||
core.store.setAccounts('u2', [{ puuid: 'p-ms', riotId: '민수#V' }, { puuid: 'l-ms', riotId: '민수#L' }]);
|
||||
core.store.startSession('s2', 'g', 'c', '음성', LS - MIN);
|
||||
core.games.matchStarted({ id: 'lol-demo', game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
|
||||
@@ -60,13 +60,6 @@ const site = await buildServer(
|
||||
},
|
||||
{
|
||||
culpritKnowledge: new KnowledgeAuto(async () => { throw new Error('offline'); }),
|
||||
// OP.GG: 발로란트 시연 경기는 "찾음"(가짜 점수), 롤 시연 경기는 "없음"
|
||||
culpritOpgg: async (name: string, args: any) => {
|
||||
if (name !== 'valorant_list_player_matches') return {};
|
||||
const input = (await local.inject({ url: `/api/culprit/internal/${valId}/input`, headers: { 'x-gvr-internal': '1' } })).json().input as CulpritInput;
|
||||
const p = input.players.find((x) => x.name === args.game_name)!;
|
||||
return [{ matchId: 'demo', puuid: p.puuid, opScore: Math.round((p.rating?.score ?? 5) * 100 + 30) }];
|
||||
},
|
||||
culpritCall: async (req) => {
|
||||
await new Promise((r) => setTimeout(r, 2500));
|
||||
const isVal = req.user.includes('# 경기 발로란트');
|
||||
@@ -85,7 +78,7 @@ const rc = new RelayClient(local as any, core.bus, () => ({ serverUrl: base, dev
|
||||
rc.start();
|
||||
// 사이트 화면은 /api/overview · /api/users 도 부른다
|
||||
while (!site.hub.status().online) await new Promise((r) => setTimeout(r, 100));
|
||||
const sess = site.store.createSession({ id: 'u1', name: '승한', avatar: null });
|
||||
const sess = site.store.createSession({ id: 'u1', name: '하늘', avatar: null });
|
||||
const cookie = { name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base };
|
||||
|
||||
const puppeteer = (await import(path.join(os.homedir(), '.tmp/gvr-shot/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js'))).default;
|
||||
|
||||
@@ -24,7 +24,7 @@ fs.symlinkSync(path.join(hf, fs.readdirSync(hf)[0]), path.join(work, 'models', m
|
||||
fs.writeFileSync(path.join(work, 'settings.json'), JSON.stringify({ stt: { realtimeModel: model, preciseModel: model, device: 'cpu', computeType: 'int8' }, games: { valorant: false, lol: false } }));
|
||||
|
||||
const USERS = [
|
||||
{ id: '100000000000000001', name: '승한', voice: 'ko-KR-InJoonNeural', val: 'p-sh', lol: 'l-sh' },
|
||||
{ id: '100000000000000001', name: '하늘', voice: 'ko-KR-InJoonNeural', val: 'p-sh', lol: 'l-sh' },
|
||||
{ id: '100000000000000002', name: '민수', voice: 'ko-KR-HyunsuMultilingualNeural', val: 'p-ms', lol: 'l-ms' },
|
||||
{ id: '100000000000000003', name: '지우', voice: 'ko-KR-SunHiNeural', val: 'p-jw', lol: 'l-jw' },
|
||||
{ id: '100000000000000004', name: '현우', voice: 'ko-KR-InJoonNeural', pitch: '-8Hz', val: 'p-hw', lol: 'l-hw' },
|
||||
@@ -136,8 +136,8 @@ LINES.forEach((l, i) => {
|
||||
});
|
||||
for (const [m, name, ch, text, src] of [
|
||||
[-1.5, '민수', 'team', '정글 갱 갈게요', 'lcu'],
|
||||
[5.2, 'Lumi', 'all', '아리 잘하네', 'ocr'],
|
||||
[11.4, '지우', 'team', '드래곤 가자', 'ocr'],
|
||||
[5.2, 'Lumi', 'all', '아리 잘하네', 'log'],
|
||||
[11.4, '지우', 'team', '드래곤 가자', 'log'],
|
||||
[28.5, 'Kiwi', 'all', 'gg', 'lcu'],
|
||||
] as const) {
|
||||
games.event({ id: `${lolId}:chat:demo${m}`, match_id: lolId, game: 'lol', type: 'chat', ts: LS + m * 60_000, game_time_ms: m * 60_000, round: null, actor_puuid: null, target_puuid: null, data: JSON.stringify({ sender: { name }, channel: ch, text, source: src }) });
|
||||
@@ -200,7 +200,7 @@ const reg = await registerDevice(base, code.code, 'GAME-PC');
|
||||
core.settings.update({ site: { serverUrl: base, deviceId: reg.deviceId, deviceName: 'GAME-PC' } });
|
||||
core.settings.setSecret('deviceKey', reg.deviceKey);
|
||||
core.relay.restart();
|
||||
const sess = site.store.createSession({ id: USERS[0].id, name: '승한', avatar: null });
|
||||
const sess = site.store.createSession({ id: USERS[0].id, name: '하늘', avatar: null });
|
||||
const cookie = { name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base };
|
||||
while (core.relay.status.state !== 'online') await new Promise((r) => setTimeout(r, 100));
|
||||
console.log(`사이트: ${base} (쿠키 gvr_sid=${cookie.value})`);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, Word } from '@gvr/shared';
|
||||
import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, UtteranceInfo, Word } from '@gvr/shared';
|
||||
import type { Culprit } from '../culprit.js';
|
||||
import type { Store, UserRow } from '../db/db.js';
|
||||
import type { Dictionary } from '../dict/dictionary.js';
|
||||
@@ -54,6 +54,7 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
recording: extra.recording,
|
||||
users: users(),
|
||||
games: { valorant: { connected: gs.valorant.connected, inMatch: gs.valorant.inMatch }, lol: { connected: gs.lol.connected, inMatch: gs.lol.inMatch } },
|
||||
live: d.games.live(),
|
||||
counts: store.counts(),
|
||||
version: d.version,
|
||||
};
|
||||
@@ -108,7 +109,6 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
to: q.to ? Number(q.to) : undefined,
|
||||
q: q.q || undefined,
|
||||
types: q.types ? q.types.split(',').filter(Boolean) : undefined,
|
||||
hideNoise: q.hideNoise === '1' || q.hideNoise === 'true',
|
||||
cursor: q.cursor || undefined,
|
||||
limit: q.limit ? Number(q.limit) : undefined,
|
||||
order: q.order === 'asc' ? 'asc' : 'desc',
|
||||
@@ -116,6 +116,44 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
return timeline.query(tq);
|
||||
});
|
||||
|
||||
// 발화 자세한 정보: 원본 ogg 이름 · 경로 등 (사이트 우클릭 → 자세한 정보)
|
||||
app.get<{ Params: { id: string } }>('/api/utterances/:id/info', async (req, reply): Promise<UtteranceInfo | void> => {
|
||||
const u = store.getUtterance(req.params.id);
|
||||
if (!u) return reply.code(404).send({ error: 'not_found' });
|
||||
const exists = !!u.audio_path && !u.audio_deleted && fs.existsSync(u.audio_path);
|
||||
const sess = u.session_id ? (store.db.prepare('SELECT channel_name FROM sessions WHERE id=?').get(u.session_id) as { channel_name: string | null } | undefined) : undefined;
|
||||
const p = u.audio_path;
|
||||
const win = p?.includes('\\') ?? false;
|
||||
const sep = win ? '\\' : '/';
|
||||
return {
|
||||
id: u.id,
|
||||
userId: u.user_id,
|
||||
fileName: p ? p.split(/[\\/]/).pop() ?? null : null,
|
||||
path: p,
|
||||
folder: p ? p.slice(0, p.lastIndexOf(sep)) || null : null,
|
||||
sizeBytes: exists ? fs.statSync(p!).size : null,
|
||||
deleted: exists ? null : u.noise && !u.corrected ? 'noise' : u.audio_deleted ? 'retention' : 'missing',
|
||||
startedAt: u.started_at,
|
||||
endedAt: u.ended_at,
|
||||
durationMs: u.ended_at - u.started_at,
|
||||
sessionId: u.session_id,
|
||||
channel: sess?.channel_name ?? null,
|
||||
matchId: u.match_id,
|
||||
status: u.status,
|
||||
model: u.model,
|
||||
confidence: u.confidence,
|
||||
lufs: u.lufs,
|
||||
gainDb: u.gain_db,
|
||||
rawText: u.raw_text,
|
||||
text: u.text,
|
||||
corrected: !!u.corrected,
|
||||
noise: !!u.noise,
|
||||
noiseReason: u.noise_reason,
|
||||
attempts: u.attempts,
|
||||
createdAt: u.created_at,
|
||||
};
|
||||
});
|
||||
|
||||
app.get<{ Params: { id: string } }>('/api/audio/:id', async (req, reply) => {
|
||||
const u = store.getUtterance(req.params.id);
|
||||
if (!u) return reply.code(404).send({ error: 'not_found' });
|
||||
@@ -171,7 +209,7 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
stats: p.stats,
|
||||
}));
|
||||
const evRows = store.events(m.id);
|
||||
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? ORDER BY started_at').all(m.id) as any[];
|
||||
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? AND (noise=0 OR corrected=1) ORDER BY started_at').all(m.id) as any[];
|
||||
const vmap = m.game === 'valorant' ? d.games.assets.valMap(m.map) : null;
|
||||
return {
|
||||
...sum,
|
||||
|
||||
@@ -203,6 +203,21 @@ export class AppAuth extends EventEmitter {
|
||||
if (token) await this.call('POST', '/auth/app/logout', {}, token).catch(() => undefined);
|
||||
}
|
||||
|
||||
/** 관리자 · 최고 관리자 아이디 (따라갈 사람 목록 정렬용) */
|
||||
async adminIds(): Promise<string[]> {
|
||||
const r = await this.call<{ ids: string[] }>('GET', '/app/admins');
|
||||
return Array.isArray(r?.ids) ? r.ids : [];
|
||||
}
|
||||
|
||||
/** 표시 이름 (실명 숨기기): 디스코드 아이디 → 이름 */
|
||||
async displayNames(): Promise<Record<string, string>> {
|
||||
const r = await this.call<{ names: Record<string, string> }>('GET', '/app/names');
|
||||
return r?.names && typeof r.names === 'object' ? r.names : {};
|
||||
}
|
||||
adminSetDisplayName(id: string, name: string): Promise<{ names: Record<string, string> }> {
|
||||
return this.call('PUT', '/app/admin/names', { id: id.trim(), name: name.trim() });
|
||||
}
|
||||
|
||||
// ---- 관리자 화면 (서버가 역할을 다시 확인한다)
|
||||
adminUsers(): Promise<{ users: AppUserRow[] }> {
|
||||
return this.call('GET', '/app/admin/users');
|
||||
|
||||
@@ -146,7 +146,8 @@ export class Culprit {
|
||||
this.store.db.prepare('UPDATE culprit_analyses SET current=0 WHERE match_id=?').run(matchId);
|
||||
this.store.db
|
||||
.prepare('INSERT OR REPLACE INTO culprit_analyses(id,match_id,created_at,created_by,model,current,result,meta) VALUES(?,?,?,?,?,1,?,?)')
|
||||
.run(id, matchId, a.createdAt, JSON.stringify(a.createdBy), a.model, JSON.stringify({ result: a.result, players: a.players }), JSON.stringify(a.meta));
|
||||
// 표시 이름(실명 숨기기)을 정하기 전에 시작한 분석이 뒤늦게 와도 예전 이름이 남지 않게 저장할 때 바꾼다
|
||||
.run(id, matchId, a.createdAt, JSON.stringify(this.store.scrubCreatedBy(a.createdBy)), a.model, this.store.scrubNames(JSON.stringify({ result: a.result, players: a.players })), JSON.stringify(a.meta));
|
||||
});
|
||||
tx();
|
||||
return this.current(matchId)!;
|
||||
@@ -173,7 +174,6 @@ export class Culprit {
|
||||
character: p.character ?? null,
|
||||
userId: userId ?? null,
|
||||
voice: !!userId && speakers.has(userId),
|
||||
...(p.tag ? { tag: p.tag } : {}),
|
||||
...(ratings.get(p.puuid) ? { rating: ratings.get(p.puuid) } : {}),
|
||||
hasExtraStats: !!p.stats,
|
||||
};
|
||||
@@ -334,12 +334,6 @@ export class Culprit {
|
||||
refs,
|
||||
players: players.map(({ hasExtraStats: _x, ...p }) => p),
|
||||
stats: { utterances: utts.length, utterancesTotal: totalUtts, events: ei, chats: ci, rounds: rounds.length, basic },
|
||||
lookup: {
|
||||
riotMatchId: m.id.replace(/^(val|lol)-/, '') || null,
|
||||
startedAt: realStart(m),
|
||||
endedAt: m.ended_at ?? realStart(m),
|
||||
durationSec: Math.round(((m.ended_at ?? realStart(m)) - realStart(m)) / 1000),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -364,8 +358,8 @@ function ratingLines(game: string, players: CulpritPlayer[]): string[] {
|
||||
if (!players.some((p) => p.rating)) return [];
|
||||
const head =
|
||||
game === 'valorant'
|
||||
? '# 기록 점수 (0~10, OP.GG OP스코어 방식: 라운드 승률 · KAST · ACS · 피해 격차를 실제 OP.GG 점수에 맞춘 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점)'
|
||||
: '# 기록 점수 (0~10, OP.GG OP스코어 방식: 킬 관여 · 데스 · 딜/받은 피해 · 골드 · CS · 레벨 · CC · 와드를 실제 OP.GG 점수에 맞춘 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점, 라인전 = LOL.PS 라인전 점수의 입력인 10 · 15분 맞라이너와의 CS · 골드 · 경험치 차)';
|
||||
? '# 기록 점수 (0~10, OP.GG OP스코어 계산법: 라운드 승률 · KAST · ACS · 피해 격차로 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점)'
|
||||
: '# 기록 점수 (0~10, OP.GG OP스코어 계산법: 역할 · 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드로 계산. 경기 순위/팀 순위, 경기 평균보다 점수를 올린 강점 · 깎은 약점, 라인전 = LOL.PS 라인전 점수의 입력인 10 · 15분 맞라이너와의 CS · 골드 · 경험치 차)';
|
||||
const out = [head];
|
||||
if (players.some((p) => p.rating?.basic)) out.push('# (추가 지표가 없어 K/D/A · 골드 · CS 같은 기본 기록으로만 낸 점수다)');
|
||||
const idOf = new Map(players.map((p) => [p.puuid, p.id]));
|
||||
|
||||
@@ -125,9 +125,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;
|
||||
}
|
||||
@@ -247,6 +322,15 @@ export class Store {
|
||||
.prepare('SELECT id, audio_path FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND started_at<?')
|
||||
.all(before) as any[];
|
||||
}
|
||||
/** 잡음으로 끝난 발화 중 아직 음성 파일이 남은 것 (v1.3.5 이하에서 녹음한 것) */
|
||||
noiseWithAudio(): UtteranceRow[] {
|
||||
return this.db
|
||||
.prepare(
|
||||
`SELECT rowid,* FROM utterances WHERE noise=1 AND corrected=0 AND audio_deleted=0 AND audio_path IS NOT NULL
|
||||
AND (status='precise' OR noise_reason='vad')`,
|
||||
)
|
||||
.all() as UtteranceRow[];
|
||||
}
|
||||
markAudioDeleted(id: string): void {
|
||||
this.db.prepare('UPDATE utterances SET audio_deleted=1 WHERE id=?').run(id);
|
||||
}
|
||||
@@ -397,7 +481,7 @@ export class Store {
|
||||
|
||||
// ---------------------------------------------------------------- stats
|
||||
counts(): { utterances: number; matches: number } {
|
||||
const u = (this.db.prepare('SELECT count(*) n FROM utterances').get() as any).n;
|
||||
const u = (this.db.prepare('SELECT count(*) n FROM utterances WHERE noise=0 OR corrected=1').get() as any).n;
|
||||
const m = (this.db.prepare('SELECT count(*) n FROM matches').get() as any).n;
|
||||
return { utterances: u, matches: m };
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import { newId } from '../util/ids.js';
|
||||
import type { BotGateway, GChannel, GCommand, GMember, GVoiceEvent } from './gateway.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import type { Recorder } from './recorder.js';
|
||||
import type { Announcer } from './tts.js';
|
||||
import { isOgg, type Announcer } from './tts.js';
|
||||
|
||||
const log = logger('bot');
|
||||
|
||||
@@ -290,9 +290,9 @@ export class Bot {
|
||||
if (!this.player) return;
|
||||
const s = this.settings().discord;
|
||||
try {
|
||||
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice);
|
||||
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice, s.ttsRate);
|
||||
if (!this.player) return;
|
||||
const res = createAudioResource(fs.createReadStream(file), { inputType: StreamType.WebmOpus });
|
||||
const res = createAudioResource(fs.createReadStream(file), { inputType: isOgg(file) ? StreamType.OggOpus : StreamType.WebmOpus });
|
||||
this.player.play(res);
|
||||
await entersState(this.player, AudioPlayerStatus.Playing, 5000).catch(() => undefined);
|
||||
} catch (e) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// 음성채널에 들어갈 때 서버가 디스코드에서 받은 일회용 음성 접속 정보를 넘겨주고, 음성은 이 PC ↔ 디스코드로 바로 간다
|
||||
import type { DiscordGatewayAdapterCreator, DiscordGatewayAdapterLibraryMethods } from '@discordjs/voice';
|
||||
import type { BotGwChannel, BotGwFromApp, BotGwGuild, BotGwMember, BotGwToApp } from '@gvr/shared';
|
||||
import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
|
||||
import { ActivityType, ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import WebSocket from 'ws';
|
||||
import { logger } from '../util/log.js';
|
||||
@@ -70,14 +70,34 @@ export class LocalGateway extends EventEmitter implements BotGateway {
|
||||
super();
|
||||
}
|
||||
|
||||
/** 봇 상태 메시지: 음성채널에 있으면(= 녹음 중) 빨간 "녹음 중" (겜녹이 봇은 사이트 서버가 같은 일을 한다) */
|
||||
private recording: boolean | null = null;
|
||||
private updatePresence(): void {
|
||||
const c = this.client;
|
||||
if (!c?.isReady()) return;
|
||||
const on = c.guilds.cache.some((g) => !!g.members.me?.voice.channelId);
|
||||
if (on === this.recording) return;
|
||||
this.recording = on;
|
||||
c.user.setPresence(
|
||||
on
|
||||
? { status: 'dnd', activities: [{ type: ActivityType.Custom, name: 'custom', state: '🔴 녹음 중' }] }
|
||||
: { status: 'online', activities: [{ type: ActivityType.Custom, name: 'custom', state: '🎙️ 대기 중 · /녹음시작' }] },
|
||||
);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers] });
|
||||
this.client = c;
|
||||
c.on(Events.ClientReady, () => this.emit('ready'));
|
||||
this.recording = null;
|
||||
c.on(Events.ClientReady, () => {
|
||||
this.updatePresence();
|
||||
this.emit('ready');
|
||||
});
|
||||
c.on(Events.GuildCreate, () => this.emit('guilds'));
|
||||
c.on(Events.GuildDelete, () => this.emit('guilds'));
|
||||
c.on(Events.Error, (e) => log.error('discord 오류', e));
|
||||
c.on(Events.VoiceStateUpdate, (o, n) => {
|
||||
if (n.id === c.user?.id) this.updatePresence();
|
||||
const m = n.member ?? o.member;
|
||||
if (!m) return;
|
||||
const ch = n.channel;
|
||||
@@ -351,8 +371,17 @@ export class RemoteGateway extends EventEmitter implements BotGateway {
|
||||
// 이 유저가 가입하지 않은 서버
|
||||
if (this.watched?.id !== m.guildId) return;
|
||||
log.warn('이 디스코드 서버에 가입되어 있지 않아 녹음할 수 없습니다');
|
||||
this.wait?.resolve(null);
|
||||
this.wait = null;
|
||||
if (this.wait) {
|
||||
this.wait.resolve(null);
|
||||
this.wait = null;
|
||||
return;
|
||||
}
|
||||
// 지켜보던 중에 서버가 권한을 다시 확인하다 끊은 경우: 그대로 두면 슬래시 명령 · 음성 상태가 영영 안 오므로 1분 뒤 다시 요청한다
|
||||
// (정말 탈퇴했으면 다시 거절될 뿐이다)
|
||||
setTimeout(() => {
|
||||
const w = this.watched;
|
||||
if (w?.id === m.guildId && !this.wait) this.send({ t: 'watch', guildId: w.id, commands: w.commands });
|
||||
}, 60000).unref();
|
||||
return;
|
||||
case 'voiceState':
|
||||
if (this.watched?.id !== m.guildId) return;
|
||||
|
||||
@@ -127,3 +127,58 @@ export class OggOpusWriter {
|
||||
return Math.round(this.samples / 48);
|
||||
}
|
||||
}
|
||||
|
||||
/** Ogg 파일에서 Opus 패킷을 꺼낸다 (OpusHead · OpusTags 포함) */
|
||||
export function readOggPackets(buf: Buffer): Buffer[] {
|
||||
const out: Buffer[] = [];
|
||||
let pos = 0;
|
||||
let cur: Buffer[] = [];
|
||||
while (pos + 27 <= buf.length && buf.toString('ascii', pos, pos + 4) === 'OggS') {
|
||||
const nseg = buf[pos + 26];
|
||||
const lacing = buf.subarray(pos + 27, pos + 27 + nseg);
|
||||
let p = pos + 27 + nseg;
|
||||
for (const l of lacing) {
|
||||
cur.push(buf.subarray(p, p + l));
|
||||
p += l;
|
||||
if (l < 255) {
|
||||
out.push(Buffer.concat(cur));
|
||||
cur = [];
|
||||
}
|
||||
}
|
||||
pos = p;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.3.5 이하 녹음 고치기: 패킷이 몰려 도착할 때 말 중간에 끼워 넣은 20~60ms 무음 프레임을 뺀다.
|
||||
* 디스코드는 말하는 도중에 무음 프레임을 보내지 않으므로, 앞뒤가 목소리인 1~3개짜리 무음 묶음은 녹음기가 넣은 것이다.
|
||||
* @returns 뺀 프레임 수 (0 이면 파일을 건드리지 않음)
|
||||
*/
|
||||
export function removeInsertedSilence(file: string): number {
|
||||
const all = readOggPackets(fs.readFileSync(file));
|
||||
if (all.length < 3) return 0;
|
||||
const head = all[0];
|
||||
const packets = all.slice(2);
|
||||
const isSil = (p: Buffer) => p.equals(SILENCE_FRAME);
|
||||
const keep: Buffer[] = [];
|
||||
let removed = 0;
|
||||
for (let i = 0; i < packets.length; ) {
|
||||
if (!isSil(packets[i])) {
|
||||
keep.push(packets[i++]);
|
||||
continue;
|
||||
}
|
||||
let j = i;
|
||||
while (j < packets.length && isSil(packets[j])) j++;
|
||||
if (i > 0 && j < packets.length && j - i <= 3) removed += j - i;
|
||||
else keep.push(...packets.slice(i, j));
|
||||
i = j;
|
||||
}
|
||||
if (!removed) return 0;
|
||||
const tmp = `${file}.fix`;
|
||||
const w = new OggOpusWriter(tmp, head[9] || 2);
|
||||
for (const p of keep) w.write(p);
|
||||
w.close();
|
||||
fs.renameSync(tmp, file);
|
||||
return removed;
|
||||
}
|
||||
|
||||
@@ -21,12 +21,55 @@ export interface RecorderOptions {
|
||||
matchAt: (ts: number) => string | null;
|
||||
}
|
||||
|
||||
/** RTP 시각 (48kHz 샘플 단위 타임스탬프 + 순번) */
|
||||
export interface RtpInfo {
|
||||
seq: number;
|
||||
ts: number;
|
||||
}
|
||||
|
||||
/** 수신기가 꺼낸 Opus 패킷 → 그 패킷이 담겨 온 RTP 헤더 */
|
||||
const rtpOf = new WeakMap<Buffer, RtpInfo>();
|
||||
|
||||
export function rtpInfo(packet: Buffer): RtpInfo | undefined {
|
||||
return rtpOf.get(packet);
|
||||
}
|
||||
|
||||
/** 테스트용: 패킷에 RTP 시각을 붙인다 */
|
||||
export function tagRtp(packet: Buffer, info: RtpInfo): Buffer {
|
||||
rtpOf.set(packet, info);
|
||||
return packet;
|
||||
}
|
||||
|
||||
/**
|
||||
* @discordjs/voice 는 Opus 내용만 넘기고 RTP 순번 · 타임스탬프를 버린다.
|
||||
* 패킷 도착 시각은 게임 중(CPU 부하)에 2~3개씩 몰려 와서 쉼 계산에 쓸 수 없다 (v1.3.5 까지 말 중간에 무음이 끼어 목소리가 깨짐).
|
||||
* 그래서 복호화 함수를 감싸 RTP 헤더를 패킷에 붙여 둔다.
|
||||
*/
|
||||
export function tapRtp(receiver: unknown): boolean {
|
||||
const r = receiver as { parsePacket?: (buf: Buffer, ...rest: unknown[]) => Buffer | undefined; __gvrRtp?: boolean };
|
||||
if (r.__gvrRtp) return true;
|
||||
if (typeof r.parsePacket !== 'function') return false;
|
||||
const orig = r.parsePacket.bind(r);
|
||||
r.parsePacket = (buf: Buffer, ...rest: unknown[]) => {
|
||||
const packet = orig(buf, ...rest);
|
||||
if (packet && buf.length >= 12) rtpOf.set(packet, { seq: buf.readUInt16BE(2), ts: buf.readUInt32BE(4) });
|
||||
return packet;
|
||||
};
|
||||
r.__gvrRtp = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
const FRAME = 960; // 20ms @48kHz
|
||||
|
||||
/** 발화 하나 = 파일 하나. 말이 0.8초 끊기면 끝, 최대 30초 (보고서 4장 1~3단계) */
|
||||
class Utterance {
|
||||
export class Utterance {
|
||||
writer: OggOpusWriter;
|
||||
id: string;
|
||||
startedAt: number;
|
||||
lastArrival: number;
|
||||
/** 첫 패킷의 RTP 타임스탬프 - 그때까지 쓴 샘플 수. 패킷 자리 = ts - rtpBase */
|
||||
rtpBase: number | null = null;
|
||||
lastSeq = 0;
|
||||
constructor(dir: string, now: number) {
|
||||
this.id = newId(now);
|
||||
this.startedAt = now;
|
||||
@@ -36,6 +79,35 @@ class Utterance {
|
||||
fs.mkdirSync(d, { recursive: true });
|
||||
this.writer = new OggOpusWriter(path.join(d, `${this.id}.ogg`));
|
||||
}
|
||||
|
||||
/**
|
||||
* 패킷을 제자리에 쓴다. 디스코드는 말 사이 짧은 쉼에는 패킷을 안 보내므로 빈 자리를 무음 프레임으로 채운다.
|
||||
* - RTP 타임스탬프가 있으면 그 값으로 자리를 정한다 (도착이 몰리거나 늦어도 소리가 늘어나지 않음)
|
||||
* - 없으면 도착 시각으로 정하되, 실제 흐른 시간보다 0.2초 넘게 모자랄 때만 채운다 (몰려 온 패킷 사이에 무음을 넣지 않음)
|
||||
* @returns 쓴 무음 프레임 수, 버린 패킷이면 -1
|
||||
*/
|
||||
place(packet: Buffer, now: number, maxGapMs: number): number {
|
||||
const rtp = rtpOf.get(packet);
|
||||
let fill = 0;
|
||||
if (rtp && this.rtpBase !== null) {
|
||||
const d = (rtp.seq - this.lastSeq) & 0xffff;
|
||||
if (d === 0 || d > 0x8000) return -1; // 중복 · 순서가 뒤바뀌어 늦게 온 패킷 (그 자리는 이미 지나감)
|
||||
const behind = ((rtp.ts - this.rtpBase) >>> 0) - this.writer.samples;
|
||||
if (behind >= FRAME / 2 && behind <= maxGapMs * 48) fill = Math.round(behind / FRAME);
|
||||
else if (behind > maxGapMs * 48 || behind < -48000) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0; // 타임스탬프가 튐: 다시 맞춘다
|
||||
} else if (!rtp) {
|
||||
const lag = now - this.startedAt - this.writer.samples / 48;
|
||||
if (lag > 200) fill = Math.min(Math.floor((lag - 100) / 20), Math.ceil(maxGapMs / 20));
|
||||
}
|
||||
if (rtp) {
|
||||
if (this.rtpBase === null) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0;
|
||||
this.lastSeq = rtp.seq;
|
||||
}
|
||||
for (let i = 0; i < fill; i++) this.writer.write(SILENCE_FRAME);
|
||||
this.lastArrival = now;
|
||||
this.writer.write(packet);
|
||||
return fill;
|
||||
}
|
||||
}
|
||||
|
||||
function localDay(ts: number): string {
|
||||
@@ -61,6 +133,7 @@ export class Recorder {
|
||||
this.detach();
|
||||
this.connection = connection;
|
||||
this.sessionId = sessionId;
|
||||
if (!tapRtp(connection.receiver)) log.warn('RTP 시각을 읽을 수 없음: 도착 시각으로 쉼을 맞춤');
|
||||
connection.receiver.speaking.on('start', this.onSpeak);
|
||||
}
|
||||
|
||||
@@ -99,14 +172,8 @@ export class Recorder {
|
||||
if (!u) {
|
||||
u = new Utterance(this.opts.audioDir(), now - 20);
|
||||
this.active.set(userId, u);
|
||||
} else {
|
||||
// 말 사이 짧은 쉼은 디스코드가 패킷을 안 보낸다. 무음 프레임으로 채워 실제 시간과 맞춘다.
|
||||
const gap = now - u.lastArrival;
|
||||
const missing = Math.round(gap / 20) - 1;
|
||||
if (missing > 0 && missing * 20 < this.opts.silenceMs() + 200) for (let i = 0; i < missing; i++) u.writer.write(SILENCE_FRAME);
|
||||
}
|
||||
u.lastArrival = now;
|
||||
u.writer.write(packet);
|
||||
u.place(packet, now, this.opts.silenceMs() + 200);
|
||||
if (u.writer.samples >= this.opts.maxUtteranceSec() * 48000) {
|
||||
this.finish(userId);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,20 @@ import { logger } from '../util/log.js';
|
||||
|
||||
const log = logger('tts');
|
||||
|
||||
/** 0.5배보다 느린 부분을 늘리는 함수 (워커 atempo). src 를 tempo 배속으로 바꿔 dst(Ogg Opus)에 쓴다 */
|
||||
export type TempoFn = (src: string, dst: string, tempo: number) => Promise<void>;
|
||||
|
||||
/** 말 속도 0.1~2.0 (Edge TTS 는 0.5~2.0 만 지원해서 그보다 느린 부분은 워커가 늘린다) */
|
||||
export function clampRate(rate: unknown): number {
|
||||
const r = typeof rate === 'number' && isFinite(rate) ? rate : 1;
|
||||
return Math.round(Math.min(2, Math.max(0.1, r)) * 100) / 100;
|
||||
}
|
||||
|
||||
/** 파일 확장자로 디스코드 재생 형식을 고른다 */
|
||||
export function isOgg(file: string): boolean {
|
||||
return file.endsWith('.ogg');
|
||||
}
|
||||
|
||||
/**
|
||||
* 녹음 안내 음성. 미리 합성해서 캐시하고, 문구를 바꾸면 다시 합성한다 (보고서 7-3).
|
||||
* 합성은 Microsoft Edge 온라인 TTS(무료). 인터넷이 안 되면 기본 문구 음성(앱에 포함)을 쓴다.
|
||||
@@ -15,38 +29,66 @@ export class Announcer {
|
||||
constructor(
|
||||
private cacheDir: string,
|
||||
private resourcesDir: string,
|
||||
private tempo: TempoFn | null = null,
|
||||
) {}
|
||||
|
||||
private bundled(): string {
|
||||
return path.join(this.resourcesDir, 'tts', 'announce-default.webm');
|
||||
}
|
||||
|
||||
cachedPath(text: string, voice: string): string {
|
||||
const h = crypto.createHash('sha1').update(`${voice}\n${text}`).digest('hex').slice(0, 16);
|
||||
return path.join(this.cacheDir, `announce-${h}.webm`);
|
||||
cachedPath(text: string, voice: string, rate = 1): string {
|
||||
rate = clampRate(rate);
|
||||
const key = rate === 1 ? `${voice}\n${text}` : `${voice}\n${rate}\n${text}`;
|
||||
const h = crypto.createHash('sha1').update(key).digest('hex').slice(0, 16);
|
||||
return path.join(this.cacheDir, `announce-${h}.${rate < 0.5 ? 'ogg' : 'webm'}`);
|
||||
}
|
||||
|
||||
/** 안내 음성 파일 경로 (WebM Opus). 없으면 합성. */
|
||||
async ensure(text: string, voice: string): Promise<string> {
|
||||
const p = this.cachedPath(text, voice);
|
||||
/** 안내 음성 파일 경로 (WebM Opus, 0.5배보다 느리면 Ogg Opus). 없으면 합성. */
|
||||
async ensure(text: string, voice: string, rate = 1): Promise<string> {
|
||||
rate = clampRate(rate);
|
||||
const p = this.cachedPath(text, voice, rate);
|
||||
if (fs.existsSync(p) && fs.statSync(p).size > 1000) return p;
|
||||
if (text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled();
|
||||
if (rate === 1 && text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled();
|
||||
try {
|
||||
await synthesize(text, voice, p);
|
||||
log.info(`안내 음성 합성: ${path.basename(p)}`);
|
||||
await render(text, voice, rate, p, this.tempo);
|
||||
log.info(`안내 음성 합성: ${path.basename(p)} (속도 ${rate})`);
|
||||
return p;
|
||||
} catch (e) {
|
||||
log.warn('안내 음성 합성 실패, 기본 음성 사용', e);
|
||||
// 인터넷이 안 될 때: 기본 음성을 그 속도로만 바꿔 쓴다
|
||||
if (rate !== 1 && this.tempo && fs.existsSync(this.bundled())) {
|
||||
const q = path.join(this.cacheDir, `announce-default-${rate}.ogg`);
|
||||
try {
|
||||
if (!fs.existsSync(q)) await this.tempo(this.bundled(), q, rate);
|
||||
return q;
|
||||
} catch (e2) {
|
||||
log.warn('기본 음성 속도 바꾸기 실패', e2);
|
||||
}
|
||||
}
|
||||
return this.bundled();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 문구를 그 속도로 합성해 outFile 에 쓴다. 0.5배보다 느리면 0.5배로 합성한 뒤 워커가 더 늘린다 (outFile 은 .ogg) */
|
||||
export async function render(text: string, voice: string, rate: number, outFile: string, tempo: TempoFn | null): Promise<void> {
|
||||
rate = clampRate(rate);
|
||||
if (rate >= 0.5) return synthesize(text, voice, outFile, 4, rate);
|
||||
if (!tempo) throw new Error('0.5배보다 느린 속도는 음성 인식 엔진(워커)이 켜져 있어야 합니다');
|
||||
const tmp = `${outFile}.half.webm`;
|
||||
try {
|
||||
await synthesize(text, voice, tmp, 4, 0.5);
|
||||
await tempo(tmp, outFile, rate / 0.5);
|
||||
} finally {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Edge TTS 는 짧은 시간에 여러 번 부르면 429 를 준다. 몇 번 쉬었다가 다시 시도한다. */
|
||||
export async function synthesize(text: string, voice: string, outFile: string, tries = 4): Promise<void> {
|
||||
export async function synthesize(text: string, voice: string, outFile: string, tries = 4, rate = 1): Promise<void> {
|
||||
for (let i = 1; ; i++) {
|
||||
try {
|
||||
return await synthesizeOnce(text, voice, outFile);
|
||||
return await synthesizeOnce(text, voice, outFile, rate);
|
||||
} catch (e: any) {
|
||||
if (i >= tries) throw e;
|
||||
await new Promise((r) => setTimeout(r, 1500 * 2 ** i));
|
||||
@@ -54,14 +96,14 @@ export async function synthesize(text: string, voice: string, outFile: string, t
|
||||
}
|
||||
}
|
||||
|
||||
async function synthesizeOnce(text: string, voice: string, outFile: string): Promise<void> {
|
||||
async function synthesizeOnce(text: string, voice: string, outFile: string, rate: number): Promise<void> {
|
||||
fs.mkdirSync(path.dirname(outFile), { recursive: true });
|
||||
const tts = new MsEdgeTTS();
|
||||
const tmpDir = fs.mkdtempSync(path.join(path.dirname(outFile), '.tts-'));
|
||||
try {
|
||||
await tts.setMetadata(voice, OUTPUT_FORMAT.WEBM_24KHZ_16BIT_MONO_OPUS);
|
||||
const r = await Promise.race([
|
||||
tts.toFile(tmpDir, text),
|
||||
tts.toFile(tmpDir, text, rate === 1 ? undefined : { rate: Math.min(2, Math.max(0.5, rate)) }),
|
||||
new Promise<never>((_, rej) => setTimeout(() => rej(new Error('TTS 시간 초과')), 20000)),
|
||||
]);
|
||||
fs.renameSync(r.audioFilePath, outFile);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ChatData, KillData, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared';
|
||||
import type { ChatData, KillData, LiveGame, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared';
|
||||
import { lolModeKo } from './modes.js';
|
||||
import type { EventRow } from '../db/db.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import { lolObjectIcon } from './assets.js';
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { MatchSummary } from '@gvr/shared';
|
||||
import type { LiveGame, MatchSummary } from '@gvr/shared';
|
||||
import type { EventRow, MatchRow, Store } from '../db/db.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import type { SttPipeline } from '../stt/pipeline.js';
|
||||
@@ -11,6 +11,7 @@ import type { GameAssets } from './assets.js';
|
||||
import { LolAdapter } from './lol.js';
|
||||
import type { AdapterHost, GameAdapter, MatchStart } from './types.js';
|
||||
import { ValorantAdapter } from './valorant.js';
|
||||
import { lolModeKo, valModeKo } from './modes.js';
|
||||
|
||||
const log = logger('games');
|
||||
|
||||
@@ -38,12 +39,15 @@ export class GameManager implements AdapterHost {
|
||||
start(): void {
|
||||
void this.assets.refresh();
|
||||
for (const a of this.adapters) a.start();
|
||||
this.watchLive();
|
||||
// 앱이 꺼졌다 켜졌을 때 'live' 로 남은 경기는 끝난 것으로 정리
|
||||
for (const m of this.store.listMatches({ limit: 20 }))
|
||||
if (m.status === 'live') this.store.upsertMatch({ id: m.id, game: m.game, started_at: m.started_at, status: 'complete', ended_at: m.ended_at ?? Date.now() });
|
||||
}
|
||||
stop(): void {
|
||||
for (const a of this.adapters) a.stop();
|
||||
if (this.liveTimer) clearInterval(this.liveTimer);
|
||||
this.liveTimer = null;
|
||||
}
|
||||
status() {
|
||||
const out: Record<string, { connected: boolean; inMatch: boolean; detail?: string }> = {};
|
||||
@@ -51,6 +55,25 @@ export class GameManager implements AdapterHost {
|
||||
return out as { valorant: { connected: boolean; inMatch: boolean }; lol: { connected: boolean; inMatch: boolean } };
|
||||
}
|
||||
|
||||
/** 지금 게임 상태 (앱 게임 연동 탭 · 사이트) */
|
||||
live(): LiveGame[] {
|
||||
return this.adapters.map((a) => a.liveGame());
|
||||
}
|
||||
|
||||
private liveTimer: NodeJS.Timeout | null = null;
|
||||
private lastLive = '';
|
||||
/** 게임 상태가 바뀌면 사이트로 알린다 (2초마다 확인) */
|
||||
private watchLive(): void {
|
||||
if (this.liveTimer) return;
|
||||
this.liveTimer = setInterval(() => {
|
||||
const live = this.live();
|
||||
const key = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest));
|
||||
if (key === this.lastLive) return;
|
||||
this.lastLive = key;
|
||||
this.bus.live({ type: 'games.state', data: live });
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
/** 지금 진행 중인 경기 (녹음 시 발화에 붙인다) */
|
||||
liveMatchAt(ts: number): string | null {
|
||||
const m = this.store.matchAt(ts);
|
||||
@@ -110,6 +133,8 @@ export class GameManager implements AdapterHost {
|
||||
selfAccount(puuid: string, riotId: string): void {
|
||||
const owner = this.ownerUserId();
|
||||
this.store.setMeta('riot_self_puuid', puuid);
|
||||
// 경기 상세에 이름이 빠져 오면("#") 연결하지 않는다 (v1.3.5: "주인 계정 자동 연결: #")
|
||||
if (!/^[^#]+#[^#]+$/.test(riotId)) return;
|
||||
if (!owner || !this.store.getUser(owner)) return;
|
||||
const have = this.store.listAccounts().some((a) => a.user_id === owner && a.puuid === puuid);
|
||||
if (have) return;
|
||||
@@ -159,21 +184,6 @@ export class GameManager implements AdapterHost {
|
||||
}
|
||||
|
||||
function modeKo(m: MatchRow): string {
|
||||
const q = (m.queue || m.mode || '').toLowerCase();
|
||||
if (m.game === 'valorant') {
|
||||
const map: Record<string, string> = {
|
||||
competitive: '경쟁전',
|
||||
unrated: '일반전',
|
||||
swiftplay: '신속플레이',
|
||||
spikerush: '스파이크 돌격',
|
||||
deathmatch: '데스매치',
|
||||
hurm: '팀 데스매치',
|
||||
premier: '프리미어',
|
||||
custom: '사용자 지정',
|
||||
ggteam: '에스컬레이션',
|
||||
};
|
||||
return map[q] || m.mode || '발로란트';
|
||||
}
|
||||
const lq: Record<string, string> = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', classic: '소환사의 협곡', aram: '칼바람 나락' };
|
||||
return lq[q] || m.mode || '리그 오브 레전드';
|
||||
const q = m.queue || m.mode || '';
|
||||
return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드');
|
||||
}
|
||||
|
||||
34
app/src/core/games/modes.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
// 게임 모드 이름 (경기 목록 · 지금 게임 상태에서 함께 쓴다)
|
||||
|
||||
/** 발로란트 큐 ID → 모드 이름 (모르는 큐면 null) */
|
||||
export function valModeKo(queue: string | null | undefined): string | null {
|
||||
const q = (queue || '').toLowerCase();
|
||||
{
|
||||
const map: Record<string, string> = {
|
||||
competitive: '경쟁전',
|
||||
unrated: '일반전',
|
||||
swiftplay: '신속플레이',
|
||||
spikerush: '스파이크 돌격',
|
||||
deathmatch: '데스매치',
|
||||
hurm: '팀 데스매치',
|
||||
premier: '프리미어',
|
||||
custom: '사용자 지정',
|
||||
ggteam: '에스컬레이션',
|
||||
newmap: '새 맵',
|
||||
snowball: '눈싸움',
|
||||
};
|
||||
return map[q] || null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 롤 큐 ID · 게임 모드 → 이름 (모르면 null) */
|
||||
export function lolModeKo(queue: string | number | null | undefined): string | null {
|
||||
const q = String(queue ?? '').toLowerCase();
|
||||
const lq: Record<string, string> = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', '900': '우르프', '1900': '우르프', classic: '소환사의 협곡', aram: '칼바람 나락', cherry: '아레나', urf: '우르프', practicetool: '연습 모드', tutorial: '튜토리얼' };
|
||||
return lq[q] || null;
|
||||
}
|
||||
|
||||
/** 발로란트에서 라운드가 없는 모드 (점수 = 킬). 이 모드는 라운드 구분선 · 라운드 번호를 쓰지 않는다 */
|
||||
export function valNoRounds(queue: string | null | undefined): boolean {
|
||||
return ['deathmatch', 'hurm', 'ggteam', 'snowball'].includes((queue || '').toLowerCase());
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { LiveGame } from '@gvr/shared';
|
||||
import type { EventRow, MatchRow, Store } from '../db/db.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import type { WorkerClient } from '../stt/worker.js';
|
||||
@@ -38,4 +39,6 @@ export interface GameAdapter {
|
||||
start(): void;
|
||||
stop(): void;
|
||||
status(): { connected: boolean; inMatch: boolean; detail?: string };
|
||||
/** 지금 게임 상태 (자세히) */
|
||||
liveGame(): LiveGame;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound, PlayerStats } from '@gvr/shared';
|
||||
import type { KillData, ChatData, LiveGame, RoundEndData, PlayerRef, MatchPlayer, MatchRound, PlayerStats } from '@gvr/shared';
|
||||
import { valModeKo, valNoRounds } from './modes.js';
|
||||
import type { EventRow, RoundRow } from '../db/db.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import type { GameAssets } from './assets.js';
|
||||
@@ -21,6 +22,8 @@ interface Presence {
|
||||
ally: number | null;
|
||||
enemy: number | null;
|
||||
provisioning: string | null;
|
||||
/** 파티 상태: DEFAULT · MATCHMAKING · MATCHMADE_GAME_STARTING … */
|
||||
partyState: string | null;
|
||||
}
|
||||
|
||||
export function decodePresence(b64: string): Presence | null {
|
||||
@@ -35,6 +38,7 @@ export function decodePresence(b64: string): Presence | null {
|
||||
ally: num(pp.partyOwnerMatchScoreAllyTeam ?? p.partyOwnerMatchScoreAllyTeam),
|
||||
enemy: num(pp.partyOwnerMatchScoreEnemyTeam ?? p.partyOwnerMatchScoreEnemyTeam),
|
||||
provisioning: mp.provisioningFlow || p.provisioningFlow || null,
|
||||
partyState: pp.partyState || p.partyState || null,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
@@ -65,7 +69,9 @@ export class ValorantAdapter implements GameAdapter {
|
||||
private auth: Auth | null = null;
|
||||
private authAt = 0;
|
||||
private presence: Presence | null = null;
|
||||
private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number } | null = null;
|
||||
private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number; queue: string | null; selfAgent: string | null; players: number } | null = null;
|
||||
/** 내 Riot ID (로컬 채팅 세션) */
|
||||
private selfName: string | null = null;
|
||||
private seenChat = new Set<string>();
|
||||
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
|
||||
private polling = false;
|
||||
@@ -86,6 +92,54 @@ export class ValorantAdapter implements GameAdapter {
|
||||
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
|
||||
}
|
||||
|
||||
liveGame(): LiveGame {
|
||||
const p = this.presence;
|
||||
const m = this.match;
|
||||
const enabled = this.host.settings().games.valorant;
|
||||
const queue = m?.queue ?? p?.queue ?? null;
|
||||
const custom = p?.provisioning === 'CustomGame';
|
||||
const mapUrl = p?.map || null;
|
||||
const map = this.host.assets.valMap(mapUrl);
|
||||
const phase = !enabled
|
||||
? '연동 꺼짐'
|
||||
: !this.auth
|
||||
? 'Riot 클라이언트 꺼짐'
|
||||
: !p
|
||||
? '발로란트 꺼짐'
|
||||
: p.state === 'INGAME'
|
||||
? '경기 중'
|
||||
: p.state === 'PREGAME'
|
||||
? '요원 선택'
|
||||
: p.partyState === 'MATCHMAKING'
|
||||
? '대기열'
|
||||
: p.partyState === 'MATCHMADE_GAME_STARTING'
|
||||
? '경기 찾음 · 시작 중'
|
||||
: '메뉴';
|
||||
const inGame = !!m && p?.state === 'INGAME';
|
||||
const roundBased = !valNoRounds(queue);
|
||||
const score = inGame && p?.ally != null && p?.enemy != null ? { ally: p.ally, enemy: p.enemy } : null;
|
||||
return {
|
||||
game: 'valorant',
|
||||
enabled,
|
||||
connected: !!this.auth,
|
||||
phase,
|
||||
inMatch: !!m,
|
||||
matchId: m?.id ?? null,
|
||||
mode: custom ? '사용자 지정' : queue ? (valModeKo(queue) ?? queue) : null,
|
||||
map: map?.name ?? (mapUrl ? mapUrl.split('/').pop() ?? null : null),
|
||||
mapImage: map?.image ?? null,
|
||||
startedAt: m?.startedAt ?? null,
|
||||
round: inGame && roundBased && score ? score.ally + score.enemy + 1 : null,
|
||||
score,
|
||||
gameTimeSec: null,
|
||||
teamKills: null,
|
||||
self: this.auth ? { name: this.selfName, character: m?.selfAgent ?? null, characterImage: null, kda: null, extra: null } : null,
|
||||
players: m?.players || null,
|
||||
error: this.lastErr || null,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
private async local<T = any>(path: string): Promise<T | null> {
|
||||
const lock = this.auth?.lock ?? readLockfile(riotClientLockfilePath());
|
||||
if (!lock) return null;
|
||||
@@ -123,6 +177,8 @@ export class ValorantAdapter implements GameAdapter {
|
||||
}
|
||||
this.auth = { lock, accessToken: ent.data.accessToken, entitlement: ent.data.token, puuid: ent.data.subject, region, shard, clientVersion };
|
||||
this.authAt = Date.now();
|
||||
const chat = await request(`${base}/chat/v1/session`, { headers: h, local: true }).catch(() => null);
|
||||
if (chat?.data?.game_name) this.selfName = `${chat.data.game_name}#${chat.data.game_tag ?? ''}`;
|
||||
log.info(`Riot 클라이언트 연결 (region=${region}, shard=${shard})`);
|
||||
return this.auth;
|
||||
}
|
||||
@@ -173,7 +229,8 @@ export class ValorantAdapter implements GameAdapter {
|
||||
if (!p) return;
|
||||
if (p.state === 'INGAME' && !this.match) await this.beginMatch(a, p);
|
||||
else if (p.state !== 'INGAME' && this.match && prev?.state === 'INGAME') this.endMatch();
|
||||
else if (this.match && p.ally !== null && p.enemy !== null) {
|
||||
else if (this.match && p.ally !== null && p.enemy !== null && !valNoRounds(this.match.queue)) {
|
||||
// 데스매치 · 팀 데스매치 · 에스컬레이션은 점수가 킬 수라서 라운드로 보지 않는다 (v1.3.5: "R63 승리 · 26:37" 같은 가짜 라운드)
|
||||
const m = this.match;
|
||||
const total = p.ally + p.enemy;
|
||||
if (total > m.ally + m.enemy) {
|
||||
@@ -220,7 +277,8 @@ export class ValorantAdapter implements GameAdapter {
|
||||
team: pl.TeamID,
|
||||
character: this.host.assets.agent(pl.CharacterID),
|
||||
}));
|
||||
this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0 };
|
||||
const selfAgent = players.find((pl: { puuid: string }) => pl.puuid === a.puuid)?.character?.name ?? null;
|
||||
this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0, queue: p.queue, selfAgent: selfAgent && selfAgent !== '?' ? selfAgent : null, players: players.length };
|
||||
this.seenChat.clear();
|
||||
this.host.matchStarted({
|
||||
id,
|
||||
@@ -299,6 +357,7 @@ export class ValorantAdapter implements GameAdapter {
|
||||
const r = await request(`${this.pd(a)}/match-details/v1/matches/${matchId}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
|
||||
if (r.status === 200 && r.data?.matchInfo) {
|
||||
this.detailQueue.delete(id);
|
||||
await this.fillNames(a, r.data);
|
||||
this.applyDetails(id, r.data, a.puuid, q.startedLocal);
|
||||
continue;
|
||||
}
|
||||
@@ -313,6 +372,30 @@ export class ValorantAdapter implements GameAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 경기 상세에 선수 이름이 비어 오면(Riot 이 이름을 가림) 이름 서비스로 채운다. 내 이름은 로컬 채팅 세션 값으로.
|
||||
* v1.3.5 는 빈 이름을 그대로 써서 "주인 계정 자동 연결: #" 이 남았다.
|
||||
*/
|
||||
private async fillNames(a: Auth, md: any): Promise<void> {
|
||||
const players: any[] = md.players || [];
|
||||
const missing = players.filter((p) => !p.gameName).map((p) => p.subject);
|
||||
if (!missing.length) return;
|
||||
try {
|
||||
const r = await request(`${this.pd(a)}/name-service/v2/players`, { method: 'PUT', headers: this.pvpHeaders(a), body: missing, timeoutMs: 8000 });
|
||||
for (const n of Array.isArray(r.data) ? r.data : []) {
|
||||
const p = players.find((x) => x.subject === n.Subject);
|
||||
if (p && n.GameName) {
|
||||
p.gameName = n.GameName;
|
||||
p.tagLine = n.TagLine ?? p.tagLine;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.debug('이름 서비스 조회 실패', e);
|
||||
}
|
||||
const me = players.find((p) => p.subject === a.puuid);
|
||||
if (me && !me.gameName && this.selfName) [me.gameName, me.tagLine] = this.selfName.split('#');
|
||||
}
|
||||
|
||||
applyDetails(id: string, md: any, selfPuuid: string, startedLocal: number): void {
|
||||
const res = processMatchDetails(md, selfPuuid, this.host.assets, id, startedLocal);
|
||||
this.host.store.replaceRounds(id, res.rounds);
|
||||
@@ -359,6 +442,8 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
|
||||
const rr: any[] = md.roundResults || [];
|
||||
const n = rr.length;
|
||||
// 데스매치 · 팀 데스매치 · 에스컬레이션: 경기 전체가 "라운드 1" 하나로 온다. 라운드 · 에이스(한 라운드 5킬)를 만들지 않는다
|
||||
const noRounds = valNoRounds(info.queueID);
|
||||
// 라운드 전투 시작 시각(게임 시간) = 킬 gameTime - roundTime
|
||||
const combat: (number | null)[] = rr.map((r) => {
|
||||
let best: number | null = null;
|
||||
@@ -427,7 +512,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
}
|
||||
if (r.bombPlanter) tally(r.bombPlanter).plants++;
|
||||
if (r.bombDefuser) tally(r.bombDefuser).defuses++;
|
||||
rounds.push({
|
||||
if (!noRounds) rounds.push({
|
||||
match_id: id,
|
||||
num,
|
||||
started_at: S + start,
|
||||
@@ -439,7 +524,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
enemy_score: enemy,
|
||||
economy: JSON.stringify(economy),
|
||||
});
|
||||
roundsDetail.push({
|
||||
if (!noRounds) roundsDetail.push({
|
||||
num,
|
||||
startedAt: S + start + clockOffset,
|
||||
endedAt: S + end + clockOffset,
|
||||
@@ -485,7 +570,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
});
|
||||
}
|
||||
for (const [puuid, cnt] of Object.entries(killsBy)) {
|
||||
if (cnt >= 4) {
|
||||
if (cnt >= 4 && !noRounds) {
|
||||
const last = kills.filter((k: any) => k.killer === puuid).pop();
|
||||
events.push({
|
||||
id: `${id}:${cnt >= 5 ? 'ace' : 'multikill'}:${num}:${puuid}`,
|
||||
@@ -530,7 +615,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
});
|
||||
}
|
||||
const rd: RoundEndData = { round: num, win, result: roundResultKo(r.roundResult), score: { ally, enemy } };
|
||||
events.push({
|
||||
if (!noRounds) events.push({
|
||||
id: `${id}:round_end:${num}`,
|
||||
match_id: id,
|
||||
game: 'valorant',
|
||||
@@ -570,7 +655,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
|
||||
mode: assets.val?.modes[info.gameMode] ?? info.queueID ?? null,
|
||||
result: {
|
||||
win: selfTeamInfo ? !!selfTeamInfo.won : null,
|
||||
score: { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy },
|
||||
score: noRounds ? null : { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { buildApi } from './api/server.js';
|
||||
import { buildApi, toUser } from './api/server.js';
|
||||
import { Culprit } from './culprit.js';
|
||||
import { Store } from './db/db.js';
|
||||
import { Dictionary } from './dict/dictionary.js';
|
||||
@@ -52,6 +52,10 @@ export async function startCore(opts: CoreOptions) {
|
||||
const store = new Store(paths().db);
|
||||
const bus = new Bus();
|
||||
bus.setMaxListeners(50);
|
||||
bus.usersProvider = () => {
|
||||
const acc = store.listAccounts();
|
||||
return store.listUsers().map((u) => toUser(u, acc));
|
||||
};
|
||||
const timeline = new Timeline(store);
|
||||
const dict = new Dictionary(store, opts.resourcesDir, () => S().dictionary.packs);
|
||||
dict.seed();
|
||||
@@ -75,7 +79,9 @@ export async function startCore(opts: CoreOptions) {
|
||||
},
|
||||
matchAt: (ts) => games.liveMatchAt(ts),
|
||||
});
|
||||
const announcer = new Announcer(paths().tts, opts.resourcesDir);
|
||||
const announcer = new Announcer(paths().tts, opts.resourcesDir, async (src, dst, tempo) => {
|
||||
await worker.request('tempo', { src, dst, tempo }, 120000);
|
||||
});
|
||||
const bot: Bot = new Bot(store, recorder, announcer, bus, S, (gid) => {
|
||||
if (!S().discord.guildId) settings.update({ discord: { guildId: gid } });
|
||||
});
|
||||
@@ -145,8 +151,20 @@ export async function startCore(opts: CoreOptions) {
|
||||
};
|
||||
await startBot();
|
||||
|
||||
// 녹음할 서버를 바꾸면 봇을 다시 붙여 새 서버를 지켜본다 (이전 서버의 녹음은 끝난다)
|
||||
let watchedGuild = S().discord.guildId;
|
||||
const offGuild = settings.onChange((s) => {
|
||||
const g = s.discord.guildId;
|
||||
if (g === watchedGuild) return;
|
||||
watchedGuild = g;
|
||||
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();
|
||||
|
||||
@@ -17,12 +17,12 @@ export interface Settings {
|
||||
ttsText: string;
|
||||
ttsOnNewMember: boolean;
|
||||
ttsVoice: string;
|
||||
/** 녹음 안내 말 속도 0.1~2.0 (1.0 = 보통) */
|
||||
ttsRate: number;
|
||||
};
|
||||
games: {
|
||||
valorant: boolean;
|
||||
lol: boolean;
|
||||
lolChatOcr: boolean;
|
||||
lolOcrRegion: { x: number; y: number; w: number; h: number };
|
||||
lolLogsDir: string | null;
|
||||
};
|
||||
stt: {
|
||||
@@ -96,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: {
|
||||
|
||||
@@ -5,10 +5,18 @@ import type { Settings } from '../settings.js';
|
||||
import type { Timeline } from '../timeline.js';
|
||||
import type { Bus } from '../util/events.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import { removeInsertedSilence } from '../discord/ogg.js';
|
||||
import { WorkerClient, WorkerError, type TranscribeResult } from './worker.js';
|
||||
|
||||
const log = logger('stt');
|
||||
|
||||
const NOISE_REASON: Record<string, string> = {
|
||||
vad: '목소리 없음',
|
||||
no_speech: '말소리 아님',
|
||||
hallucination: '잡음에서 지어낸 문장',
|
||||
repetition: '같은 말만 반복',
|
||||
};
|
||||
|
||||
type Slot = 'realtime' | 'precise';
|
||||
interface Job {
|
||||
id: string;
|
||||
@@ -132,6 +140,8 @@ export class SttPipeline {
|
||||
|
||||
/** 시작 시 미처리분 복구 */
|
||||
resumePending(): void {
|
||||
this.purgeOldNoise();
|
||||
this.repairOldAudio();
|
||||
const rows = this.store.pendingUtterances();
|
||||
if (rows.length) log.info(`미처리 발화 ${rows.length}개 다시 대기열에 넣음`);
|
||||
for (const r of rows) this.enqueue(r.id, 'realtime', 5);
|
||||
@@ -270,11 +280,77 @@ export class SttPipeline {
|
||||
model: r.model,
|
||||
status: slot,
|
||||
});
|
||||
if (r.noise) this.onNoise(u, r, slot);
|
||||
if (!r.noise && r.lufs !== null && r.duration_s >= 1) this.store.updateGainProfile(u.user_id, r.lufs);
|
||||
if (r.text) this.store.hitDict(r.words.map((w) => w.w));
|
||||
this.emit(u.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 잡음 발화: 사이트에 보이지 않고(타임라인 조회에서 뺌) 음성 파일도 지운다. 로그에는 "잡음"으로 남긴다.
|
||||
* 경기 중 실시간 모델 결과는 경기 뒤 정밀 모델이 다시 보므로 그때까지 파일을 남긴다 (목소리 없음(VAD)은 모델과 상관없어 바로 지움).
|
||||
*/
|
||||
private onNoise(u: UtteranceRow, r: TranscribeResult, slot: Slot): void {
|
||||
const s = this.settings().stt;
|
||||
const recheck = slot === 'realtime' && r.noise_reason !== 'vad' && this.inMatch && s.reprocessAfterMatch && s.preciseModel !== s.realtimeModel;
|
||||
const name = this.store.getUser(u.user_id)?.name ?? u.user_id;
|
||||
const dur = ((u.ended_at - u.started_at) / 1000).toFixed(1);
|
||||
const why = NOISE_REASON[r.noise_reason ?? ''] ?? r.noise_reason ?? '?';
|
||||
const heard = r.raw_text ? `, 인식 "${r.raw_text.slice(0, 60)}"` : '';
|
||||
if (recheck) {
|
||||
log.info(`잡음 발화 ${u.id} (${name}, ${dur}초, ${why}${heard}) · 경기 뒤 정밀 모델로 다시 확인`);
|
||||
return;
|
||||
}
|
||||
this.deleteAudio(u);
|
||||
log.info(`잡음 발화 ${u.id} 숨김 · 음성 파일 삭제 (${name}, ${dur}초, ${why}${heard})`);
|
||||
}
|
||||
|
||||
private deleteAudio(u: UtteranceRow): void {
|
||||
if (u.audio_path) {
|
||||
try {
|
||||
fs.rmSync(u.audio_path, { force: true });
|
||||
} catch (e) {
|
||||
log.warn(`잡음 파일 삭제 실패 ${u.audio_path}`, e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.store.markAudioDeleted(u.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 번만: v1.3.5 이하 녹음에서 말 중간에 끼운 무음을 빼고(목소리 깨짐) 다시 변환한다.
|
||||
* 사람이 고친 발화는 파일만 고치고 글은 그대로 둔다.
|
||||
*/
|
||||
private repairOldAudio(): void {
|
||||
const KEY = 'audio_repair_v136';
|
||||
if (this.store.meta(KEY)) return;
|
||||
this.store.setMeta(KEY, String(Date.now()));
|
||||
const rows = this.store.db
|
||||
.prepare(`SELECT rowid,* FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND noise=0 ORDER BY started_at`)
|
||||
.all() as UtteranceRow[];
|
||||
let fixed = 0;
|
||||
for (const u of rows) {
|
||||
if (!u.audio_path || !fs.existsSync(u.audio_path)) continue;
|
||||
try {
|
||||
const removed = removeInsertedSilence(u.audio_path);
|
||||
if (!removed) continue;
|
||||
fixed++;
|
||||
this.store.db.prepare('UPDATE utterances SET ended_at=ended_at-? WHERE id=?').run(removed * 20, u.id);
|
||||
if (!u.corrected) this.enqueue(u.id, 'realtime', 20);
|
||||
} catch (e) {
|
||||
log.warn(`예전 녹음 고치기 실패 ${u.id}`, e);
|
||||
}
|
||||
}
|
||||
if (fixed) log.info(`예전 녹음 ${fixed}개에서 말 중간에 끼운 무음을 빼고 다시 변환`);
|
||||
}
|
||||
|
||||
/** v1.3.5 이하에서 잡음으로 판정된 발화의 남은 파일 정리 */
|
||||
private purgeOldNoise(): void {
|
||||
const rows = this.store.noiseWithAudio();
|
||||
for (const r of rows) this.deleteAudio(r);
|
||||
if (rows.length) log.info(`예전 잡음 발화 ${rows.length}개의 음성 파일 삭제`);
|
||||
}
|
||||
|
||||
private emit(id: string): void {
|
||||
const row = this.store.getUtterance(id);
|
||||
if (row) this.bus.live({ type: 'utterance.updated', data: this.timeline.utteranceItem(row) });
|
||||
|
||||
@@ -138,7 +138,8 @@ export class Timeline {
|
||||
where.push('u.started_at <= ?');
|
||||
args.push(q.to);
|
||||
}
|
||||
if (q.hideNoise) where.push('(u.noise = 0 OR u.corrected = 1)');
|
||||
// 잡음은 보여 주지 않는다 (v1.3.6~, 파일도 지움). 사람이 고친 발화는 보인다
|
||||
where.push('(u.noise = 0 OR u.corrected = 1)');
|
||||
if (q.q) {
|
||||
const kw = q.q.trim();
|
||||
if ([...kw].length >= 3) {
|
||||
@@ -224,7 +225,6 @@ export interface TimelineQuery {
|
||||
to?: number;
|
||||
q?: string;
|
||||
types?: string[];
|
||||
hideNoise?: boolean;
|
||||
cursor?: string;
|
||||
limit?: number;
|
||||
order?: 'asc' | 'desc';
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { LiveEvent } from '@gvr/shared';
|
||||
import type { LiveEvent, User } from '@gvr/shared';
|
||||
|
||||
/** 코어 내부 이벤트 버스. 'live' 는 사이트로 그대로 나가는 이벤트. */
|
||||
export class Bus extends EventEmitter {
|
||||
/** 'users.updated' 에 실을 유저 목록. 보내는 쪽은 신호만 주고 목록은 여기서 채운다 (빈 목록이 나가면 사이트에서 모든 발화가 "알 수 없음"이 됨) */
|
||||
usersProvider: (() => User[]) | null = null;
|
||||
|
||||
live(ev: LiveEvent): void {
|
||||
if (ev.type === 'users.updated' && this.usersProvider) ev = { type: 'users.updated', data: this.usersProvider() };
|
||||
this.emit('live', ev);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 설정 창(렌더러) ↔ Electron 메인 프로세스 IPC 계약. preload 가 window.gvr 로 노출한다.
|
||||
import type { AppRole, AppUserInfo, AppUserRow, User } from '@gvr/shared';
|
||||
import type { AppRole, AppUserInfo, AppUserRow, LiveGame, User } from '@gvr/shared';
|
||||
import type { AuthState } from '../core/auth.js';
|
||||
import type { DiagItem } from '../core/diagnostics.js';
|
||||
import type { BotState } from '../core/discord/bot.js';
|
||||
@@ -66,6 +66,8 @@ export interface AppState {
|
||||
stt: SttStatus;
|
||||
relay: RelayStatus;
|
||||
games: { valorant: { connected: boolean; inMatch: boolean; detail?: string }; lol: { connected: boolean; inMatch: boolean; detail?: string } };
|
||||
/** 지금 게임 상태 (v1.3.6~) */
|
||||
liveGames?: LiveGame[];
|
||||
counts: { utterances: number; matches: number };
|
||||
excludedUsers: { id: string; name: string }[];
|
||||
autoStart: boolean;
|
||||
@@ -82,14 +84,16 @@ export interface GvrApi {
|
||||
adminAddUser(id: string, role: 'admin' | 'user'): Promise<{ users: AppUserRow[] }>;
|
||||
adminSetRole(id: string, role: 'admin' | 'user'): Promise<{ users: AppUserRow[] }>;
|
||||
adminRemoveUser(id: string): Promise<{ users: AppUserRow[] }>;
|
||||
adminDisplayNames(): Promise<Record<string, string>>;
|
||||
adminSetDisplayName(id: string, name: string): Promise<Record<string, string>>;
|
||||
getState(): Promise<AppState>;
|
||||
onState(cb: (s: AppState) => void): () => void;
|
||||
updateSettings(patch: DeepPartial<Settings>): Promise<Settings>;
|
||||
setSecret(key: 'botToken' | 'riotApiKey', value: string | null): Promise<void>;
|
||||
testBotToken(token?: string): Promise<{ ok: boolean; bot?: { id: string; name: string; avatar: string | null }; guilds?: { id: string; name: string }[]; error?: string }>;
|
||||
restartBot(): Promise<{ ok: boolean; error?: string }>;
|
||||
guildMembers(): Promise<{ id: string; name: string; avatar: string | null; bot: boolean }[]>;
|
||||
previewTts(text: string, voice: string): Promise<{ ok: boolean; dataUrl?: string; error?: string }>;
|
||||
guildMembers(): Promise<{ id: string; name: string; avatar: string | null; bot: boolean; me: boolean; admin: boolean }[]>;
|
||||
previewTts(text: string, voice: string, rate?: number): Promise<{ ok: boolean; dataUrl?: string; error?: string }>;
|
||||
gpuInfo(): Promise<GpuInfo | null>;
|
||||
models(): Promise<ModelsInfo | null>;
|
||||
download(target: 'model' | 'cuda_runtime', name?: string): Promise<{ ok: boolean; error?: string }>;
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from 'node:path';
|
||||
import { toUser } from '../core/api/server.js';
|
||||
import type { AppAuth, AuthState } from '../core/auth.js';
|
||||
import { runDiagnostics } from '../core/diagnostics.js';
|
||||
import { synthesize } from '../core/discord/tts.js';
|
||||
import { clampRate, isOgg, render } from '../core/discord/tts.js';
|
||||
import type { Core } from '../core/index.js';
|
||||
import { registerDevice } from '../core/relay/client.js';
|
||||
import { dirSize } from '../core/retention.js';
|
||||
@@ -31,6 +31,7 @@ export function buildState(core: Core, opts: { dataDir: string; portable: boolea
|
||||
stt: core.stt.status,
|
||||
relay: core.relay.status,
|
||||
games: core.games.status() as AppState['games'],
|
||||
liveGames: core.games.live(),
|
||||
counts: core.store.counts(),
|
||||
excludedUsers: core.store
|
||||
.listUsers()
|
||||
@@ -122,17 +123,23 @@ export function registerIpc(ctx: IpcContext) {
|
||||
await core.startBot();
|
||||
return core.bot.state.status === 'ready' || core.bot.state.status === 'connecting' ? { ok: true } : { ok: false, error: core.bot.state.error ?? '봇을 시작하지 못했습니다' };
|
||||
},
|
||||
// 따라갈 사람 목록: 내 계정 → 관리자 → 나머지(이름순). 실패하면 오류를 그대로 보여 준다
|
||||
guildMembers: async () => {
|
||||
const ms = await core.bot.members().catch(() => []);
|
||||
return ms.map((m) => ({ id: m.id, name: m.name, avatar: m.avatar, bot: m.bot })).sort((a, b) => a.name.localeCompare(b.name, 'ko'));
|
||||
const [ms, admins] = await Promise.all([core.bot.members(), ctx.auth.adminIds().catch(() => [] as string[])]);
|
||||
const meId = ctx.auth.state.user?.id ?? null;
|
||||
const rank = (m: { me: boolean; admin: boolean }) => (m.me ? 0 : m.admin ? 1 : 2);
|
||||
return ms
|
||||
.map((m) => ({ id: m.id, name: core.store.displayNames()[m.id] ?? m.name, avatar: m.avatar, bot: m.bot, me: m.id === meId, admin: admins.includes(m.id) }))
|
||||
.sort((a, b) => rank(a) - rank(b) || a.name.localeCompare(b.name, 'ko'));
|
||||
},
|
||||
previewTts: async (text: string, voice: string) => {
|
||||
previewTts: async (text: string, voice: string, rate = 1) => {
|
||||
try {
|
||||
const f = path.join(core.paths().tts, `preview-${Date.now()}.webm`);
|
||||
await synthesize(text, voice, f);
|
||||
const r = clampRate(rate);
|
||||
const f = path.join(core.paths().tts, `preview-${Date.now()}.${r < 0.5 ? 'ogg' : 'webm'}`);
|
||||
await render(text, voice, r, f, (src, dst, tempo) => core.worker.request('tempo', { src, dst, tempo }, 120000));
|
||||
const data = fs.readFileSync(f);
|
||||
fs.rmSync(f, { force: true });
|
||||
return { ok: true, dataUrl: `data:audio/webm;base64,${data.toString('base64')}` };
|
||||
return { ok: true, dataUrl: `data:audio/${isOgg(f) ? 'ogg' : 'webm'};base64,${data.toString('base64')}` };
|
||||
} catch (e: any) {
|
||||
return { ok: false, error: `음성 합성 실패: ${e.message}` };
|
||||
}
|
||||
@@ -343,6 +350,13 @@ export function registerIpc(ctx: IpcContext) {
|
||||
adminAddUser: (id: string, r: 'admin' | 'user') => ctx.auth.adminAddUser(id, r),
|
||||
adminSetRole: (id: string, r: 'admin' | 'user') => ctx.auth.adminSetRole(id, r),
|
||||
adminRemoveUser: (id: string) => ctx.auth.adminRemoveUser(id),
|
||||
adminDisplayNames: () => ctx.auth.displayNames(),
|
||||
adminSetDisplayName: async (id: string, name: string) => {
|
||||
if (role() !== 'superadmin') throw new Error('표시 이름은 최고 관리자만 바꿀 수 있습니다');
|
||||
const r = await ctx.auth.adminSetDisplayName(id, name);
|
||||
ctx.current()?.core.store.setDisplayNames(r.names);
|
||||
return r.names;
|
||||
},
|
||||
openExternal: h.openExternal,
|
||||
quit: h.quit,
|
||||
};
|
||||
|
||||
@@ -94,7 +94,10 @@ function openWindow(route?: string): void {
|
||||
win.setMenu(null);
|
||||
win.on('page-title-updated', (e) => e.preventDefault());
|
||||
win.loadFile(path.join(rendererDir(), 'index.html'), { hash: r });
|
||||
win.once('ready-to-show', () => win?.show());
|
||||
win.once('ready-to-show', () => {
|
||||
win?.show();
|
||||
closeSplash();
|
||||
});
|
||||
// 창을 닫아도 트레이에서 계속 돈다 (녹음·사이트 연결 유지)
|
||||
win.on('close', (e) => {
|
||||
if (!quitting) {
|
||||
@@ -104,6 +107,46 @@ function openWindow(route?: string): void {
|
||||
});
|
||||
}
|
||||
|
||||
// ── 시작 창: 포터블 exe 는 풀고 켜는 데 시간이 걸린다. 큰 창이 뜨기 전까지 작은 "켜는 중" 창을 바로 띄운다 ──
|
||||
let splash: BrowserWindow | null = null;
|
||||
|
||||
function showSplash(): void {
|
||||
const banner = path.join(brandDir(), 'banner.png');
|
||||
const img = fs.existsSync(banner) ? `data:image/png;base64,${fs.readFileSync(banner).toString('base64')}` : '';
|
||||
const html = `<!doctype html><meta charset="utf-8"><style>
|
||||
html,body{margin:0;height:100%;background:#0b141c;color:#e8dfcd;font:14px 'Malgun Gothic','Segoe UI',sans-serif;overflow:hidden;user-select:none;-webkit-app-region:drag}
|
||||
img{display:block;width:480px;height:192px}
|
||||
.bar{height:3px;background:#1d2a35;overflow:hidden}.bar i{display:block;height:100%;width:30%;background:#ff4d5a;animation:m 1.2s ease-in-out infinite}
|
||||
@keyframes m{0%{transform:translateX(-100%)}100%{transform:translateX(340%)}}
|
||||
#t{text-align:center;padding:9px 0 0}
|
||||
</style>${img ? `<img src="${img}">` : '<div style="height:192px"></div>'}<div class="bar"><i></i></div><div id="t">겜녹이를 켜는 중입니다…</div>`;
|
||||
splash = new BrowserWindow({
|
||||
width: 480,
|
||||
height: 232,
|
||||
frame: false,
|
||||
resizable: false,
|
||||
movable: true,
|
||||
center: true,
|
||||
show: false,
|
||||
title: '겜녹이 · 켜는 중',
|
||||
icon: path.join(brandDir(), 'icon.png'),
|
||||
backgroundColor: '#0b141c',
|
||||
webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, javascript: true },
|
||||
});
|
||||
splash.once('ready-to-show', () => splash?.show());
|
||||
splash.on('closed', () => (splash = null));
|
||||
void splash.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`).catch(() => undefined);
|
||||
}
|
||||
|
||||
function splashText(text: string): void {
|
||||
if (splash && !splash.isDestroyed()) splash.webContents.executeJavaScript(`document.getElementById('t').textContent=${JSON.stringify(text)}`).catch(() => undefined);
|
||||
}
|
||||
|
||||
function closeSplash(): void {
|
||||
if (splash && !splash.isDestroyed()) splash.destroy();
|
||||
splash = null;
|
||||
}
|
||||
|
||||
function updateTray(): void {
|
||||
if (!tray) return;
|
||||
if (!core) {
|
||||
@@ -228,6 +271,18 @@ const refreshShell = () => {
|
||||
|
||||
let starting: Promise<void> | null = null;
|
||||
|
||||
/** 표시 이름(실명 숨기기)을 사이트 서버에서 받아 녹음 기록 · 범인 분석에 반영한다 (못 받으면 저장해 둔 것을 그대로 쓴다) */
|
||||
async function syncNames(): Promise<void> {
|
||||
const c = core;
|
||||
if (!c || !auth?.ok) return;
|
||||
try {
|
||||
const names = await auth.displayNames();
|
||||
if (core === c) c.store.setDisplayNames(names);
|
||||
} catch (e: any) {
|
||||
log.warn(`표시 이름을 받지 못했습니다: ${e?.message ?? e}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 로그인 확인 후 코어 시작 */
|
||||
function startApp(): Promise<void> {
|
||||
if (core) return Promise.resolve();
|
||||
@@ -236,6 +291,7 @@ function startApp(): Promise<void> {
|
||||
// 겜녹이 봇 중계가 로그인 만료 · 등록 해제를 알려 오면 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;
|
||||
@@ -286,6 +342,7 @@ app.whenReady().then(async () => {
|
||||
// 마이크 · 카메라 · 위치 · 알림 등 권한 요청은 모두 거절한다 (아이디 복사용 클립보드 쓰기만 허용)
|
||||
session.defaultSession.setPermissionRequestHandler((_wc, perm, cb) => cb(perm === 'clipboard-sanitized-write'));
|
||||
if (SMOKE) return smoke();
|
||||
if (!flag('hidden')) showSplash();
|
||||
settings = new SettingsStore(dataDir, dpapiCodec());
|
||||
auth = new AppAuth(settings, { version: app.getVersion(), openUrl: (u) => shell.openExternal(u) });
|
||||
const a = auth;
|
||||
@@ -315,7 +372,7 @@ app.whenReady().then(async () => {
|
||||
const st = a.state.status;
|
||||
if ((st === 'ok' && Date.now() - lastCheck > 10 * 60000) || (st === 'error' && Date.now() - lastCheck > 60000) || (st === 'ok' && a.state.offline && Date.now() - lastCheck > 60000)) {
|
||||
lastCheck = Date.now();
|
||||
void a.check();
|
||||
void a.check().then(syncNames);
|
||||
}
|
||||
}, 15000);
|
||||
setInterval(() => {
|
||||
@@ -323,9 +380,14 @@ app.whenReady().then(async () => {
|
||||
buildTrayMenu();
|
||||
pushState();
|
||||
}, 1500);
|
||||
splashText('로그인 확인 중…');
|
||||
await first;
|
||||
if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…');
|
||||
await authChain;
|
||||
if (!flag('hidden') || !settings.get().firstRunDone || !a.ok) openWindow();
|
||||
else closeSplash();
|
||||
// 창이 끝내 안 뜨는 경우(오류 등)에도 시작 창이 남지 않게
|
||||
setTimeout(closeSplash, 30000);
|
||||
if (process.env.GVR_CAPTURE_DIR) void captureScreens(process.env.GVR_CAPTURE_DIR);
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ const METHODS = [
|
||||
'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',
|
||||
'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);
|
||||
|
||||
@@ -24,8 +24,9 @@ function defaults(): Settings {
|
||||
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
|
||||
ttsOnNewMember: true,
|
||||
ttsVoice: 'ko-KR-SunHiNeural',
|
||||
ttsRate: 1,
|
||||
},
|
||||
games: { valorant: true, lol: true, lolChatOcr: true, lolOcrRegion: { x: 0.0, y: 0.6, w: 0.3, h: 0.27 }, lolLogsDir: null },
|
||||
games: { valorant: true, lol: true, lolLogsDir: null },
|
||||
stt: {
|
||||
realtimeModel: 'large-v3-turbo',
|
||||
preciseModel: 'large-v3',
|
||||
@@ -111,6 +112,7 @@ export function createMockGvr(): GvrApi {
|
||||
};
|
||||
const authListeners = new Set<(s: AuthView) => void>();
|
||||
const emitAuth = () => authListeners.forEach((l) => l(structuredClone(auth)));
|
||||
const displayNames: Record<string, string> = { '100000000000000003': '지호' };
|
||||
let adminRows: AppUserRow[] = [
|
||||
{ id: '293719842274541579', name: '사금향', avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: now - 60000, lastVersion: '1.2.0' },
|
||||
{ id: '1352267557213573160', name: '두번째관리자', avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: now - 3 * 86400000, lastVersion: '1.2.0' },
|
||||
@@ -157,6 +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,
|
||||
@@ -292,6 +305,17 @@ export function createMockGvr(): GvrApi {
|
||||
adminRows = adminRows.map((u) => (u.id === id && !u.fixed ? { ...u, role: r } : u));
|
||||
return { users: structuredClone(adminRows) };
|
||||
},
|
||||
async adminDisplayNames() {
|
||||
await sleep(150);
|
||||
return { ...displayNames };
|
||||
},
|
||||
async adminSetDisplayName(id, name) {
|
||||
await sleep(150);
|
||||
adminCheck('superadmin');
|
||||
if (name.trim()) displayNames[id] = name.trim();
|
||||
else delete displayNames[id];
|
||||
return { ...displayNames };
|
||||
},
|
||||
async adminRemoveUser(id) {
|
||||
await sleep(200);
|
||||
adminCheck('superadmin');
|
||||
@@ -357,12 +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() {
|
||||
@@ -462,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' },
|
||||
];
|
||||
|
||||
@@ -178,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; }
|
||||
@@ -318,3 +316,43 @@ input[type='number'].input { flex: none; padding: 7px 8px; }
|
||||
.admin-list { list-style: none; display: flex; flex-direction: column; gap: 6px; font-size: 13px; }
|
||||
.admin-list li { display: flex; gap: 8px; align-items: baseline; }
|
||||
.admin-list li .muted { font-size: 12px; }
|
||||
|
||||
/* 지금 게임 (게임 연동 탭) */
|
||||
.live-games {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
.live-game {
|
||||
border: 1px solid var(--line, #22313f);
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
.live-game.in-match.valorant {
|
||||
border-color: rgba(255, 70, 85, 0.55);
|
||||
}
|
||||
.live-game.in-match.lol {
|
||||
border-color: rgba(200, 170, 110, 0.6);
|
||||
}
|
||||
.live-game-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.live-game-top .badge {
|
||||
margin-left: auto;
|
||||
}
|
||||
.live-rows {
|
||||
width: 100%;
|
||||
font-size: 12.5px;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.live-rows td {
|
||||
padding: 3px 0;
|
||||
vertical-align: top;
|
||||
}
|
||||
.live-rows td:first-child {
|
||||
width: 42%;
|
||||
}
|
||||
|
||||
@@ -150,6 +150,66 @@ function UserTable({ users, superAdmin, onChange }: { users: AppUserRow[]; super
|
||||
);
|
||||
}
|
||||
|
||||
/** 표시 이름: 실명이 들어간 디스코드 이름 · 서버 별명 대신 사이트 · 녹음 기록 · 범인 분석에 쓸 이름 */
|
||||
function DisplayNames({ superAdmin }: { superAdmin: boolean }) {
|
||||
const { toast } = useApp();
|
||||
const list = useLoad(() => gvr.adminDisplayNames());
|
||||
const [id, setId] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const act = useAction();
|
||||
const valid = /^\d{17,20}$/.test(id.trim()) && !!name.trim();
|
||||
const save = async (uid: string, n: string) => {
|
||||
const r = await act.run(() => gvr.adminSetDisplayName(uid, n));
|
||||
if (r) {
|
||||
list.setData(r);
|
||||
toast(n ? `${uid} → ${n}` : `${uid} 표시 이름 지움`);
|
||||
setId('');
|
||||
setName('');
|
||||
}
|
||||
};
|
||||
const rows = Object.entries(list.data ?? {});
|
||||
return (
|
||||
<>
|
||||
{superAdmin && (
|
||||
<div className="field">
|
||||
<input className="input mono" value={id} placeholder="디스코드 아이디" spellCheck={false} onChange={(e) => setId(e.target.value.replace(/\s/g, ''))} />
|
||||
<input className="input" value={name} placeholder="보일 이름" maxLength={32} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && valid && void save(id.trim(), name.trim())} />
|
||||
<Btn primary disabled={!valid} busy={act.busy} onClick={() => save(id.trim(), name.trim())}>
|
||||
저장
|
||||
</Btn>
|
||||
</div>
|
||||
)}
|
||||
{list.loading && !list.data ? (
|
||||
<Spinner />
|
||||
) : list.error ? (
|
||||
<Err>{list.error}</Err>
|
||||
) : rows.length ? (
|
||||
<table className="table">
|
||||
<tbody>
|
||||
{rows.map(([uid, n]) => (
|
||||
<tr key={uid}>
|
||||
<td className="mono small">{uid}</td>
|
||||
<td>{n}</td>
|
||||
{superAdmin && (
|
||||
<td className="r">
|
||||
<Btn small ghost disabled={act.busy} onClick={() => save(uid, '')}>
|
||||
지우기
|
||||
</Btn>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<div className="muted">정해 둔 표시 이름이 없습니다. 디스코드 이름(서버 별명)이 그대로 보입니다.</div>
|
||||
)}
|
||||
<div className="hint">디스코드 이름이나 서버 별명에 실명이 들어 있으면 여기서 다른 이름을 정해 주세요. 사이트, 녹음 기록, 범인 분석에 이 이름만 쓰고 이미 저장된 기록의 이름도 바꿉니다.</div>
|
||||
<Err>{act.error}</Err>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function AdminTab() {
|
||||
const { state } = useApp();
|
||||
const superAdmin = state.account.role === 'superadmin';
|
||||
@@ -179,6 +239,9 @@ export function AdminTab() {
|
||||
>
|
||||
{list.loading && !list.data ? <Spinner /> : list.error ? <Err>{list.error}</Err> : <UserTable users={users} superAdmin={superAdmin} onChange={set} />}
|
||||
</Section>
|
||||
<Section title="표시 이름 (실명 숨기기)" sub="바꾸기는 최고 관리자만">
|
||||
<DisplayNames superAdmin={superAdmin} />
|
||||
</Section>
|
||||
<Section title="관리자 전용 기능" sub="일반 유저 화면에서는 잠겨 있습니다">
|
||||
<ul className="admin-list">
|
||||
{ADMIN_FEATURES.map((f) => (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { GvrApi } from '../../main/api-types';
|
||||
import { gvr, useAction, useApp, useLoad } from '../store';
|
||||
import { AdminOnly, Avatar, Btn, DraftInput, Err, Line, Ok, Page, Section, Select, ToggleLine, useIsAdmin } from '../ui';
|
||||
import { AdminOnly, Avatar, Btn, DraftInput, Err, Line, Ok, Page, Section, Select, Slider, ToggleLine, useIsAdmin } from '../ui';
|
||||
import { errMsg, fmtClock, fmtDuration } from '../util';
|
||||
|
||||
type TestResult = Awaited<ReturnType<GvrApi['testBotToken']>>;
|
||||
@@ -220,13 +220,20 @@ export function GuildFollow({ guilds, compact }: { guilds?: { id: string; name:
|
||||
disabled={!d.guildId || members.loading}
|
||||
options={[
|
||||
{ value: '', label: members.loading && d.guildId ? '불러오는 중…' : '선택 안 함' },
|
||||
...people.map((m) => ({ value: m.id, label: m.name })),
|
||||
...people.map((m) => ({ value: m.id, label: m.me ? `${m.name} (나)` : m.admin ? `${m.name} · 관리자` : m.name })),
|
||||
...(d.followUserId && !people.some((p) => p.id === d.followUserId) && !members.loading ? [{ value: d.followUserId, label: `(알 수 없음 ${d.followUserId})` }] : []),
|
||||
]}
|
||||
onChange={(v) => save({ discord: { followUserId: v || null } })}
|
||||
/>
|
||||
</Line>
|
||||
{members.error && <Err>{members.error}</Err>}
|
||||
{members.error && (
|
||||
<Err>
|
||||
멤버 목록을 불러오지 못했습니다: {members.error}{' '}
|
||||
<Btn small onClick={() => void members.reload()}>
|
||||
다시 불러오기
|
||||
</Btn>
|
||||
</Err>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -241,7 +248,7 @@ function TtsPreview() {
|
||||
<Btn
|
||||
busy={act.busy}
|
||||
onClick={async () => {
|
||||
const r = await act.run(() => gvr.previewTts(settings.discord.ttsText, settings.discord.ttsVoice));
|
||||
const r = await act.run(() => gvr.previewTts(settings.discord.ttsText, settings.discord.ttsVoice, settings.discord.ttsRate));
|
||||
if (r?.ok && r.dataUrl) {
|
||||
audio.current?.pause();
|
||||
audio.current = new Audio(r.dataUrl);
|
||||
@@ -330,6 +337,9 @@ export function DiscordTab() {
|
||||
<Line label="목소리">
|
||||
<Select width={200} value={d.ttsVoice} options={VOICES} onChange={(v) => save({ discord: { ttsVoice: v } })} />
|
||||
</Line>
|
||||
<Line label="말 속도" hint="0.1배(아주 느리게) ~ 2.0배(빠르게), 보통 1.0배">
|
||||
<Slider value={d.ttsRate ?? 1} min={0.1} max={2} step={0.1} fmt={(v) => `${v.toFixed(1)}배`} onCommit={(v) => save({ discord: { ttsRate: Math.round(v * 10) / 10 } })} />
|
||||
</Line>
|
||||
<Line
|
||||
label={
|
||||
<>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -63,7 +63,7 @@ function Step2() {
|
||||
<>
|
||||
<Head title="게임 선택" desc="켠 게임의 경기 이벤트(킬 · 라운드 · 오브젝트)를 대화 기록과 같은 시간축에 함께 남깁니다. 나중에 게임 연동 탭에서 바꿀 수 있습니다." />
|
||||
<GameCards showStatus={false} />
|
||||
<div className="hint">롤은 채팅 OCR(화면 글자 읽기)도 함께 씁니다. 게임 옵션에서 채팅 타임스탬프를 켜고 '테두리 없음' 창 모드를 쓰면 정확합니다.</div>
|
||||
<div className="hint">롤 채팅은 롤 클라이언트 API 로 받습니다 (챔피언 선택 · 게임 후 채팅). 화면 글자 인식(OCR)은 쓰지 않습니다.</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -106,6 +106,20 @@ test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은
|
||||
assert.equal(frSt.activeBotToken(), null);
|
||||
await assert.rejects(fr.adminAddUser(STRANGER, 'user'), /최고 관리자만/);
|
||||
await assert.rejects(fr.adminUsers(), /관리자만/);
|
||||
// 일반 유저도 관리자 아이디는 받는다 (따라갈 사람 목록 정렬). 유저 자신은 관리자가 아니다
|
||||
const ids = await fr.adminIds();
|
||||
assert.ok(ids.includes(SUPER) && !ids.includes(FRIEND));
|
||||
await admin.adminSetRole(FRIEND, 'admin');
|
||||
assert.ok((await fr.adminIds()).includes(FRIEND));
|
||||
await admin.adminSetRole(FRIEND, 'user');
|
||||
// 표시 이름 (실명 숨기기): 최고 관리자만 정하고, 정하면 서버가 저장한 이름 · 로그인 정보가 모두 그 이름이 된다
|
||||
await assert.rejects(fr.adminSetDisplayName(FRIEND, '별명'), /최고 관리자만/);
|
||||
assert.deepEqual((await admin.adminSetDisplayName(FRIEND, '별명')).names, { [FRIEND]: '별명' });
|
||||
assert.deepEqual(await fr.displayNames(), { [FRIEND]: '별명' });
|
||||
assert.equal((await fr.check()).user?.name, '별명');
|
||||
const rows = (await admin.adminUsers()).users;
|
||||
assert.equal(rows.find((u) => u.id === FRIEND)?.name, '별명');
|
||||
assert.deepEqual((await admin.adminSetDisplayName(FRIEND, '')).names, {});
|
||||
// 다시 켜도 (새 SettingsStore) 로그인 유지
|
||||
assert.equal((await new AppAuth(s.settingsFor(dir), { version: '1.2.0', openUrl: () => undefined }).check()).status, 'ok');
|
||||
// 봇 토큰은 이 PC 어디에도 저장되지 않는다 (테스트는 평문 codec 이라 secrets.bin 도 그대로 읽힌다)
|
||||
|
||||
@@ -179,6 +179,8 @@ test('봇 중계: 로그인 안 한 연결은 막히고, 로그인한 앱은 봇
|
||||
await a.gw.start();
|
||||
assert.deepEqual(a.gw.me(), ME);
|
||||
assert.deepEqual(a.gw.guilds().map((g) => g.id), [G, OTHER_G]);
|
||||
// 지켜보기 전에도 (설정 창이 봇 연결 직후 바로 요청) 가입한 서버 멤버 목록을 받는다
|
||||
assert.equal((await a.gw.members(G)).length, 3);
|
||||
const g = await a.gw.watch(G, { commands: true });
|
||||
assert.equal(g?.name, 'M&L');
|
||||
await until(() => s.source.commands.includes(G));
|
||||
@@ -302,11 +304,15 @@ test('봇 중계: 슬래시 명령은 그 서버를 지켜보는 앱으로 가
|
||||
const cmd = (name: string, user: string) =>
|
||||
new Promise<string>((resolve) => s.source.emit('command', { name, guildId: G, user: m(user, user), voiceChannel: { id: VC1, name: '일반' } } satisfies BotCommand, resolve));
|
||||
try {
|
||||
assert.equal(await cmd('녹음시작', SUPER), '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.');
|
||||
// 지켜보는 앱이 없는 서버의 명령은 서버가 받지 않는다 (봇 토큰을 직접 쓰는 v1.1.0 PC 가 응답하게)
|
||||
assert.match(await cmd('녹음시작', SUPER), /^지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다/);
|
||||
// 지켜보는 앱이 없는 서버의 명령은 서버가 잠깐 기다렸다가 받는다 (봇 토큰을 직접 쓰는 v1.1.0 PC 가 먼저 응답하게)
|
||||
assert.equal(s.source.wants?.(G), false);
|
||||
await a.gw.start();
|
||||
await b.gw.start();
|
||||
// 내 앱이 켜져 있어도 다른 서버를 녹음 대상으로 정해 두면 그렇다고 알려 준다 ("응답하지 않았어요" 대신)
|
||||
assert.match(await cmd('녹음시작', SUPER), /^내 겜녹이 앱이 이 서버에 아직 연결되지 않았습니다/);
|
||||
await a.gw.watch(OTHER_G, { commands: false });
|
||||
assert.match(await cmd('녹음시작', SUPER), /^내 겜녹이 앱이 다른 디스코드 서버를 녹음 대상으로 정해 두었습니다/);
|
||||
await a.gw.watch(G, { commands: false });
|
||||
assert.equal(s.source.wants?.(G), true);
|
||||
assert.equal(s.source.wants?.(OTHER_G), false);
|
||||
|
||||
@@ -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'));
|
||||
});
|
||||
|
||||
@@ -53,11 +53,11 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
|
||||
const input = ctx.culprit.buildInput(m);
|
||||
const lines = input.text.split('\n');
|
||||
assert.match(lines[0], /^# 경기 발로란트 .* 13:9 \(우리 팀 승리\) · 22라운드/);
|
||||
// 우리 팀이 P1~P5, 승한은 음성O, 디스코드 계정이 없는 상대는 음성X
|
||||
// 우리 팀이 P1~P5, 하늘은 음성O, 디스코드 계정이 없는 상대는 음성X
|
||||
const p1 = lines.find((l) => l.startsWith('P1 '))!;
|
||||
assert.match(p1, /^P1 승한 우리 제트\(타격대\) \d+\/\d+\/\d+ ACS\d+ ADR\d+ KAST\d+% 피해격차[+-]\d+ 첫킬\d+\/첫데스\d+ HS\d+% 설치\d+\/해체\d+ .*음성O$/);
|
||||
// 기록 점수 (OP.GG OP스코어 방식): 10명 모두, 이긴 팀 1등 MVP · 진 팀 1등 ACE
|
||||
const head = lines.findIndex((l) => l.startsWith('# 기록 점수 (0~10, OP.GG OP스코어 방식'));
|
||||
assert.match(p1, /^P1 하늘 우리 제트\(타격대\) \d+\/\d+\/\d+ ACS\d+ ADR\d+ KAST\d+% 피해격차[+-]\d+ 첫킬\d+\/첫데스\d+ HS\d+% 설치\d+\/해체\d+ .*음성O$/);
|
||||
// 기록 점수 (OP.GG OP스코어 계산법): 10명 모두, 이긴 팀 1등 MVP · 진 팀 1등 ACE
|
||||
const head = lines.findIndex((l) => l.startsWith('# 기록 점수 (0~10, OP.GG OP스코어 계산법'));
|
||||
assert.ok(head > 0, '기록 점수 칸');
|
||||
const rl = lines.slice(head + 1, head + 11);
|
||||
assert.ok(rl.every((l, i) => new RegExp(`^P${i + 1} \\d+\\.\\d점 \\d+위/팀\\d위`).test(l)), rl.join('\n'));
|
||||
@@ -68,7 +68,6 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
|
||||
assert.ok(rp.every((r) => r && r.score >= 0 && r.score <= 10 && !r.basic));
|
||||
assert.deepEqual(rp.map((r) => r.rank).sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
|
||||
assert.equal(rp.find((r) => r.rank === 1)!.score, Math.max(...rp.map((r) => r.score)));
|
||||
assert.equal(input.lookup?.riotMatchId, 'demo');
|
||||
assert.match(lines.find((l) => l.startsWith('P6 '))!, /상대 .*음성X$/);
|
||||
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, true, '민수는 대화가 있다');
|
||||
assert.equal(input.players.find((p) => p.id === 'P3')!.voice, false);
|
||||
@@ -139,7 +138,7 @@ test('범인찾기: 롤 포지션 · 시야 · 10/15분 지표와 골드 차', (
|
||||
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 킬 P\d+ → P\d+/);
|
||||
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 내셔 남작 처치 우리 팀 · P2\n/);
|
||||
// 기록 점수 + LOL.PS 라인전 점수의 입력 (10 · 15분 맞라이너와 차)
|
||||
assert.match(input.text, /\n# 기록 점수 \(0~10, OP\.GG OP스코어 방식/);
|
||||
assert.match(input.text, /\n# 기록 점수 \(0~10, OP\.GG OP스코어 계산법/);
|
||||
assert.match(input.text, /\nP1 \d+\.\d점 \d+위\/팀\d위.* · 라인전\(vs P6\) 10분 CS[+-][\d,]+ 골드[+-][\d,]+ 경험치[+-][\d,]+ 15분 CS[+-][\d,]+ 골드[+-][\d,]+ 경험치[+-][\d,]+\n/);
|
||||
const p1 = input.players.find((p) => p.id === 'P1')!;
|
||||
const p6 = input.players.find((p) => p.id === 'P6')!;
|
||||
@@ -147,7 +146,6 @@ test('범인찾기: 롤 포지션 · 시야 · 10/15분 지표와 골드 차', (
|
||||
assert.equal(p1.rating!.lane!.at10!.xp, -p6.rating!.lane!.at10!.xp);
|
||||
assert.ok(p1.rating!.lane!.at10!.cs !== undefined && p1.rating!.lane!.at15!.gold !== undefined);
|
||||
assert.equal(input.players.filter((p) => p.rating?.badge).length, 2);
|
||||
assert.equal(p1.tag !== undefined, true);
|
||||
});
|
||||
|
||||
test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
|
||||
@@ -178,7 +176,7 @@ test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
|
||||
method: 'PUT',
|
||||
url: `/api/culprit/internal/${id}/result`,
|
||||
headers: { 'x-gvr-internal': '1' },
|
||||
payload: { result, players: input.players, model: 'claude-opus-5-5', createdBy: { id: 'u1', name: '승한' }, meta: { costUsd: 0.41 } },
|
||||
payload: { result, players: input.players, model: 'claude-opus-5-5', createdBy: { id: 'u1', name: '하늘' }, meta: { costUsd: 0.41 } },
|
||||
});
|
||||
assert.equal(put.statusCode, 200);
|
||||
const info = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
|
||||
@@ -196,11 +194,26 @@ test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
|
||||
],
|
||||
);
|
||||
// 다시 분석하면 이전 결과는 기록으로 남는다
|
||||
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result, players: input.players, model: 'm2', createdBy: { id: 'u1', name: '승한' }, meta: {} } });
|
||||
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result, players: input.players, model: 'm2', createdBy: { id: 'u1', name: '하늘' }, meta: {} } });
|
||||
const info2 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
|
||||
assert.equal(info2.history.length, 2);
|
||||
assert.equal(info2.analysis!.model, 'm2');
|
||||
assert.equal(info2.history.filter((h) => h.current).length, 1);
|
||||
|
||||
// 표시 이름(실명 숨기기): 이름을 바꾸기 전에 시작한 분석(자료 · 요약에 예전 이름)이 바꾼 뒤에 도착해도 예전 이름이 남지 않는다
|
||||
ctx.store.setDisplayNames({ u1: '별명' });
|
||||
assert.equal(ctx.store.getUser('u1')?.name, '별명');
|
||||
const late = { ...result, summary: '하늘이 캐리했다' };
|
||||
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result: late, players: input.players, model: 'm3', createdBy: { id: 'u1', name: '하늘' }, meta: {} } });
|
||||
const raw = () => JSON.stringify(ctx.store.db.prepare('SELECT created_by, result FROM culprit_analyses').all());
|
||||
assert.ok(!raw().includes('하늘'), raw());
|
||||
const info3 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
|
||||
assert.equal(info3.analysis!.result.summary, '별명이 캐리했다');
|
||||
assert.equal(info3.analysis!.createdBy.name, '별명');
|
||||
assert.ok(info3.analysis!.players.some((p) => p.name === '별명'));
|
||||
// 같은 이름으로 다시 받아도(이미 바뀐 유저는 건너뛰는 경우) 그대로 깨끗하다
|
||||
ctx.store.setDisplayNames({ u1: '별명' });
|
||||
assert.ok(!raw().includes('하늘'));
|
||||
await api.close();
|
||||
});
|
||||
|
||||
|
||||
@@ -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,22 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
|
||||
assert.ok(q.gain_db > 15, `quiet gain ${q.gain_db}`);
|
||||
const k = core.store.getUtterance('keys')!;
|
||||
assert.equal(k.noise, 1);
|
||||
// 잡음: 파일을 지우고 사이트에 보이지 않는다
|
||||
assert.equal(k.audio_deleted, 1);
|
||||
assert.ok(!fs.existsSync(k.audio_path!));
|
||||
assert.ok(live.filter((e) => e.type === 'utterance.updated').length >= 3);
|
||||
// 기록 API (사이트가 중계로 부르는 것과 같은 경로)
|
||||
const res = await core.api.inject({ method: 'GET', url: '/api/timeline?limit=10' });
|
||||
const page = res.json();
|
||||
assert.equal(page.items.length, 3);
|
||||
assert.deepEqual(page.items.map((i: any) => i.id).sort(), ['quiet', 'speech']);
|
||||
// 우클릭 → 자세한 정보: 원본 ogg 이름 · 경로
|
||||
const info = (await core.api.inject({ method: 'GET', url: '/api/utterances/speech/info' })).json();
|
||||
assert.equal(info.fileName, 'speech.ogg');
|
||||
assert.equal(info.path, sp.audio_path);
|
||||
assert.equal(info.folder, path.dirname(sp.audio_path!));
|
||||
assert.ok(info.sizeBytes > 1000);
|
||||
assert.equal(info.deleted, null);
|
||||
assert.equal((await core.api.inject({ method: 'GET', url: '/api/utterances/keys/info' })).json().deleted, 'noise');
|
||||
const audio = await core.api.inject({ method: 'GET', url: '/api/audio/speech', headers: { range: 'bytes=0-99' } });
|
||||
assert.equal(audio.statusCode, 206);
|
||||
assert.equal(audio.rawPayload.length, 100);
|
||||
|
||||
2
app/test/fixtures/culprit-seed.ts
vendored
@@ -46,7 +46,7 @@ export function seedValorant(ctx: ReturnType<typeof setup>, opts: { sessionStart
|
||||
const md = makeDemoValorant(VS);
|
||||
const id = 'val-demo';
|
||||
const users = [
|
||||
{ id: 'u1', name: '승한', puuid: 'p-sh' },
|
||||
{ id: 'u1', name: '하늘', puuid: 'p-sh' },
|
||||
{ id: 'u2', name: '민수', puuid: 'p-ms' },
|
||||
{ id: 'u9', name: '도윤', puuid: null },
|
||||
];
|
||||
|
||||
4
app/test/fixtures/demo-matches.ts
vendored
@@ -37,7 +37,7 @@ function loc() {
|
||||
}
|
||||
|
||||
export const VAL_PLAYERS = [
|
||||
{ subject: 'p-sh', gameName: '승한', tagLine: 'KR1', teamId: 'Blue', characterId: AGENT.jett },
|
||||
{ subject: 'p-sh', gameName: '하늘', tagLine: 'KR1', teamId: 'Blue', characterId: AGENT.jett },
|
||||
{ subject: 'p-ms', gameName: '민수', tagLine: '0707', teamId: 'Blue', characterId: AGENT.sova },
|
||||
{ subject: 'p-jw', gameName: '지우', tagLine: 'KR2', teamId: 'Blue', characterId: AGENT.sage },
|
||||
{ subject: 'p-hw', gameName: '현우', tagLine: 'HW1', teamId: 'Blue', characterId: AGENT.omen },
|
||||
@@ -132,7 +132,7 @@ export function makeDemoValorant(gameStart: number) {
|
||||
|
||||
// ------------------------------------------------------------------ 롤
|
||||
const LOL = [
|
||||
{ pid: 1, champ: 103, team: 100, puuid: 'l-sh', name: '승한', tag: 'KR1' }, // 아리 미드
|
||||
{ pid: 1, champ: 103, team: 100, puuid: 'l-sh', name: '하늘', tag: 'KR1' }, // 아리 미드
|
||||
{ pid: 2, champ: 64, team: 100, puuid: 'l-ms', name: '민수', tag: '0707' }, // 리 신
|
||||
{ pid: 3, champ: 86, team: 100, puuid: 'l-hw', name: '현우', tag: 'HW1' }, // 가렌
|
||||
{ pid: 4, champ: 81, team: 100, puuid: 'l-jw', name: '지우', tag: 'KR2' }, // 이즈리얼
|
||||
|
||||
2
app/test/fixtures/make-val-details.ts
vendored
@@ -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 } },
|
||||
];
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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' } },
|
||||
],
|
||||
|
||||
BIN
assets/app/splash.bmp
Normal file
|
After Width: | Height: | Size: 326 KiB |
@@ -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"}
|
||||
@@ -157,7 +151,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}}`
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 130 KiB |
|
Before Width: | Height: | Size: 451 KiB After Width: | Height: | Size: 454 KiB |
|
Before Width: | Height: | Size: 380 KiB After Width: | Height: | Size: 382 KiB |
|
Before Width: | Height: | Size: 328 KiB After Width: | Height: | Size: 331 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 215 KiB After Width: | Height: | Size: 214 KiB |
|
Before Width: | Height: | Size: 187 KiB After Width: | Height: | Size: 187 KiB |
|
Before Width: | Height: | Size: 170 KiB After Width: | Height: | Size: 170 KiB |
@@ -151,3 +151,55 @@ VOICE E2E PASS
|
||||
- OP.GG "조회 실패"와 "경기 없음"을 나눈다: 결과 `meta.opgg.error`, 화면 "OP.GG 조회 실패 · 기록 점수로 분석", 지시문 "이 줄이 없으면 OP.GG 에 없는 경기이거나 조회하지 못한 경기". 실제 OP.GG: 랭크 경기 10명 찾음, 잘못된 주소 → `error` (3번 중 3번 실패: OP.GG 404)
|
||||
- LOL.PS 라인전: LOL.PS 원문 정의("10, 15분 맞라이너 골드차, 경험치차, cs차이")대로 10분 값을 더해 10 · 15분 차이를 보여 준다. 참고한 원문과 구현 대응은 `tools/opscore-fit/README.md`
|
||||
- 테스트: 앱 40개 · 사이트 서버 20개 통과, 화면 오류 · CSP 위반 없음
|
||||
- 배포: 사이트 서버 다시 배포(지시문 · 화면 반영 확인), Windows CI (0e0a272, full) 8개 모두 PASS · 앱 버전 1.3.1 → Gitea 릴리스 v1.3.1 (v1.3.0 에 새 버전 안내)
|
||||
|
||||
## 범인찾기 v1.3.2 — 외부 전적 사이트 접속 제거 (2026-10-15)
|
||||
|
||||
사용자 결정: 전적 사이트는 "계산법을 참고"하라는 뜻이었고 실제로 연결하는 것이 아니다 → 분석할 때 OP.GG 를 찾아보던 기능(`site/server/src/opgg.ts`, 결과의 OP.GG 점수 · 조회 상태, 지시문의 OP.GG 실제 점수 줄)을 뺐다. 기록 점수(OP.GG 계산법) · 10/15분 라인전(LOL.PS 정의)은 앱이 경기 기록으로 계산한다.
|
||||
|
||||
`node --import tsx app/scripts/culprit-real-e2e.mts` — 실제 Claude Opus 5.5(생각 high), 외부 사이트 접속 없음 (로그에 OP.GG 0건)
|
||||
|
||||
| 경기 | 걸린 시간 | 토큰 (입력 / 캐시 쓰기 / 출력) | 비용 | 범인 (기록 점수 팀 최하위) |
|
||||
|---|---|---|---|---|
|
||||
| 발로란트 시연 경기 (22라운드, 대화 4문장) | 33초 | 10,562 / 7,382 / 2,943 | $0.138 | 우리 P5 (공동 최하위 5.0, 동점자 P4 와 비교해 이유) · 상대 P7 (1.9, 최하위) |
|
||||
| 롤 시연 경기 (10 · 15분 라인전, 대화 7문장) | 36초 | 3,186 / 8,937 / 3,300 | $0.123 | 우리 P1 (2.7, 최하위) · 상대 P7 (4.5, 최하위) |
|
||||
|
||||
- AI 평점과 기록 점수 차: 평균 0.4점 (롤 P2 는 "용 셋 · 유충 · 바론 싹쓸이"를 근거로 기록 3.0 → AI 5.0)
|
||||
- 테스트: 앱 40개 · 사이트 서버 16개 통과 (서버 테스트에 "자료에 기록 점수 칸, 지시문 '평점은 기록 점수에서 출발', OP.GG 실제 점수 없음" 확인 추가)
|
||||
- 배포: 사이트 서버 다시 배포 (서버 번들 · 화면에 OP.GG 접속 코드 없음 확인, 지시문 '평점은 기록 점수에서 출발'), Windows CI (b8e76ab, full) 8개 모두 PASS · 앱 버전 1.3.2 → Gitea 릴리스 v1.3.2 (v1.3.0 · v1.3.1 에 새 버전 안내)
|
||||
|
||||
## v1.3.3 — 따라갈 사람 목록 · 롤 채팅 OCR 제거 · 표시 이름 (2026-10-16)
|
||||
|
||||
- 따라갈 사람 원인: 사이트 서버 봇 중계가 "지켜보는 서버"가 아니면 멤버 요청을 `forbidden` 으로 거절했고, 앱(`guildMembers`)이 오류를 삼켜 빈 목록이 됐다. 설정 창은 봇이 준비되자마자(지켜보기 전) 요청하므로 "선택 안 함"만 남았다. `bot-gateway.test.ts` 에 지켜보기 전 요청을 넣어 예전 서버 코드에서 `forbidden` 으로 실패하는 것을 확인한 뒤 고침. 실제 사이트 서버 봇은 M&L 87명 · 다른 서버 27명을 정상으로 받음
|
||||
- 정렬: 내 계정 → 관리자(`GET /app/admins`) → 이름순 (mock 화면 확인: `민준 (나)`, `지호 · 관리자`, 나머지)
|
||||
- 롤 채팅: LCU · 게임 클라이언트 API(2999) 모두 게임 중 전체 · 팀 채팅을 주지 않는다 (`lol-game-client-chat` 은 귓속말 · 파티 메시지 보내기만, 게임 중 채팅 이벤트는 Overwolf 전용이며 저장 금지). OCR 코드 · 의존성(pywinrt · mss · Pillow) 제거, r3dlog 채팅은 LCU 채팅을 지우지 않고 추가
|
||||
- 표시 이름: 서버 `displayNames` · `GET /app/names` · `PUT /app/admin/names`(최고 관리자), 앱은 users · 지난 범인 분석 이름 교체. 운영 서버에 두 최고 관리자 계정 표시 이름 설정, server.json 에 실명 0건
|
||||
- 저장소: 시연 · 테스트 데이터 · 화면 캡처(`docs/dev/screens`, `docs/report/img`, `docs/report/culprit/img`) · 계획서 PDF 3개를 가짜 이름으로 다시 만듦 (PDF 쪽수 그대로)
|
||||
- 테스트: 앱 41 · 사이트 서버 16 · 워커 39 통과, 앱/화면 타입 검사 통과
|
||||
- 배포: 사이트 서버 다시 배포(화면 번들 실명 0건, 새 API 401 응답 확인), Windows CI (b230443, full) 7개 모두 PASS (ocr_lang 단계 삭제) · 앱 버전 1.3.3 → Gitea 릴리스 v1.3.3 (v1.3.2 에 새 버전 안내)
|
||||
|
||||
## v1.3.4 — 슬래시 명령 응답 · 녹음 중 봇 상태 메시지 (2026-10-16)
|
||||
|
||||
- 원인: 사이트 서버 `discord-source.ts` 가 "그 서버를 지켜보는 앱이 없으면" 슬래시 명령을 응답 없이 무시했다 (옛 v1.1.0 PC 와 응답이 겹치지 않게 넣은 동작) → 디스코드 "애플리케이션이 응답하지 않았어요". 이제 1.5초 기다린 뒤 이유를 답한다 (`bot-gateway.test.ts`: 앱 없음 · 내 앱이 다른 서버를 지켜봄 · 아직 연결 중 세 경우 확인)
|
||||
- 앱: 지켜보던 중 `watch_denied` 를 받으면 1분 뒤 다시 지켜보기
|
||||
- 상태 메시지: 테스트 봇으로 `dnd + "🔴 녹음 중"` · `online + "🎙️ 대기 중 · /녹음시작"` 을 디스코드가 받는 것 확인, 배포 뒤 실제 겜녹이 봇 상태가 "🎙️ 대기 중 · /녹음시작" 인 것을 같은 서버의 테스트 봇으로 읽어 확인
|
||||
- 테스트: 앱 41 · 사이트 서버 16 통과. Windows CI (db2f186, full) 7개 모두 PASS · 앱 버전 1.3.4 → Gitea 릴리스 v1.3.4 (v1.3.3 에 새 버전 안내)
|
||||
|
||||
## v1.3.5 — 표시 이름 빈틈 · 상태 메시지 실제 확인 (2026-10-16)
|
||||
|
||||
- 표시 이름: 이름을 바꾸기 전에 시작한 분석이 바꾼 뒤 저장되면 예전 이름이 남던 빈틈 (`setDisplayNames` 가 이미 바뀐 유저를 건너뜀 + 저장 경로에서 이름을 바꾸지 않음). `culprit.test.ts` 에 "바꾼 뒤 도착한 분석 · 다시 받기" 회귀 테스트 추가, 예전 코드에서 실패하는 것 확인 뒤 고침
|
||||
- 상태 메시지 실제 디스코드 확인 (`site/server/scripts/presence-e2e.mts`, 테스트 봇 · 빈 음성채널): 들어간 뒤 0.2초에 `dnd "🔴 녹음 중"`, 나온 뒤 0.2초에 `online "🎙️ 대기 중 · /녹음시작"` (디스코드가 보낸 음성 상태 이벤트로 바뀜)
|
||||
- 테스트: 앱 41 · 사이트 서버 16 통과
|
||||
- Windows CI (3f7bf1c, full) 7개 모두 PASS · 앱 버전 1.3.5 → Gitea 릴리스 v1.3.5 (v1.3.3 · v1.3.4 에 새 버전 안내)
|
||||
|
||||
## v1.3.6 — 목소리 깨짐 · 알 수 없음 · 잡음 숨기기 · 사이트 로그 · 지금 게임 (2026-10-16)
|
||||
|
||||
사용자가 보낸 GVR-Data(발화 40개 · 데스매치 1경기)를 분석했다.
|
||||
|
||||
- 목소리 깨짐 원인: ogg 패킷을 열어 보니 경기 중 파일이 `##.##.##` 모양 (목소리 2개 → 무음 1개 반복). "S매치" 발화 파일 8.48초 중 무음 132개(2.64초), 실제 수신 시간은 약 6.97초 (`created_at` - 끝 대기 0.8초 - 시작). 녹음기가 패킷 도착 간격(`now - lastArrival`)으로 쉼을 채웠는데 게임 중에는 패킷이 몰려 와서 말 중간에 무음이 끼었다. 경기 전 파일도 일부 같은 모양
|
||||
- 확인: 끼운 무음을 뺀 파일과 원래 파일을 Whisper large-v3(CPU)로 비교 — "이제 게임을 좀 해봐봐 스태스트랜 맛있긴 하네" → "실제로 게임을 좀 해봐오면서 테스트를 했는데 맛있긴 하네", "왜는 리플레이가 귀하다" → "이거는 리플레이가 없긴 하다"
|
||||
- 고침: RTP 타임스탬프로 자리 정하기. 테스트 `core.test.ts` "패킷이 몰려 와도 말 중간에 무음을 넣지 않는다" (3개씩 60ms 마다 도착 + 진짜 쉼 0.4초 → 진짜 쉼 20프레임만 채움, 순번 · 타임스탬프 한 바퀴 도는 경우 포함). 예전 파일 고치기를 사용자 파일 43개에 돌려 489프레임 제거, 결과 파일 ffmpeg 디코드 정상
|
||||
- 잡음 판정: 잡음 19개를 Silero VAD 로 다시 재니 모두 말소리 0초 (Whisper 를 돌리면 "시청해주셔서 감사합니다" · "자막 제공 배달의민족" 만 나옴) → 판정은 맞았고, 이제 숨기고 파일을 지운다. 반복 판정 1개는 깨진 오디오에서 나온 것
|
||||
- 알 수 없음 원인: `users.updated` 를 `data: []` 로 보내 사이트 유저 목록이 비었다 (녹음 시작 · 경기 끝 · Riot ID 저장 때마다). DB 의 user_id 는 모두 정상
|
||||
- 데스매치: 실시간 점수(킬)를 라운드로 착각 → "R10 · R22 · R36 · R48 · R63" 가짜 라운드, 경기 상세는 344킬이 "라운드 1" 하나라 에이스 11개. 경기 상세의 선수 이름이 비어 와서 "주인 계정 자동 연결: #"
|
||||
- 테스트: 앱 48 · 사이트 서버 16 · 워커 42 통과, 앱 · 화면 타입 검사 통과. 실제 STT 워커 E2E 에서 잡음 파일 삭제 · `/api/utterances/:id/info` 확인. 사이트 서버 테스트에서 게임 PC 끊긴 뒤 관리자만 로그를 보고 내려받는 것 확인
|
||||
|
||||
@@ -229,7 +229,7 @@ tr.hl td {{ background:#fff3f4 !important; font-weight:700; }}
|
||||
<h3>AI에 보내는 자료 모양 (예시)</h3>
|
||||
<pre class="box"><span class="h"># 경기 발로란트 경쟁전 · 어센트 · 13:9 (우리 팀 승리) · 22라운드 · 46분</span>
|
||||
<span class="h"># 참가자 (번호 이름 팀 요원(역할) K/D/A ACS 라운드당피해 첫킬/첫데스 헤드샷 설치/해체 스킬사용 음성)</span>
|
||||
P1 승한 우리 제트(타격대) 19/12/7 ACS244 ADR148 첫킬1/첫데스2 HS15% 설치0/해체0 랭크:플래티넘 1 음성O
|
||||
P1 하늘 우리 제트(타격대) 19/12/7 ACS244 ADR148 첫킬1/첫데스2 HS15% 설치0/해체0 랭크:플래티넘 1 음성O
|
||||
P5 Duck 우리 킬조이(감시자) 12/15/8 ACS194 ADR92 첫킬2/첫데스2 HS16% 설치0/해체1 랭크:골드 3 음성X
|
||||
<span class="c">[e1] R1 0:08 킬 P2 → P6 (클래식)</span>
|
||||
<span class="v">[u1] R3 0:05 P1: 현우야 같이 가 기다려 둘 있어</span>
|
||||
|
||||
|
Before Width: | Height: | Size: 633 KiB After Width: | Height: | Size: 632 KiB |
|
Before Width: | Height: | Size: 543 KiB After Width: | Height: | Size: 542 KiB |
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 472 KiB After Width: | Height: | Size: 488 KiB |
|
Before Width: | Height: | Size: 752 KiB After Width: | Height: | Size: 760 KiB |
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 1.3 MiB |
|
Before Width: | Height: | Size: 1.6 MiB After Width: | Height: | Size: 1.6 MiB |
|
Before Width: | Height: | Size: 447 KiB After Width: | Height: | Size: 446 KiB |
@@ -28,7 +28,7 @@ main{flex:1;display:grid;grid-template-columns:520px 1fr;gap:18px;padding:20px 2
|
||||
<div class="brand"><img src="../../../../assets/app/icon.png" alt=""><div><div class="nm">겜녹이</div><div class="en">GAME VOICE RECORDER</div></div></div>
|
||||
<span class="chip">타임라인</span><span class="chip">경기</span><span class="chip">유저</span><span class="chip">단어사전</span><span class="chip on new">🔍 범인찾기</span>
|
||||
<div class="search">🔍 대화 내용 검색 (예: 스파이크)</div>
|
||||
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">승</span>승한</div>
|
||||
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">하</span>하늘</div>
|
||||
</header>
|
||||
<main>
|
||||
<div class="panel list">
|
||||
@@ -61,7 +61,7 @@ main{flex:1;display:grid;grid-template-columns:520px 1fr;gap:18px;padding:20px 2
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h4><span>참가자 10명</span><span>음성 = 대화 기록 있음</span></h4>
|
||||
<div class="pl"><img class="ag" src="../../mock/assets/val/a-jett.png">승한 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 제트</span></div>
|
||||
<div class="pl"><img class="ag" src="../../mock/assets/val/a-jett.png">하늘 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 제트</span></div>
|
||||
<div class="pl"><img class="ag" src="../../mock/assets/val/a-sova.png">민수 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 소바</span></div>
|
||||
<div class="pl"><img class="ag" src="../../mock/assets/val/a-sage.png">지우 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 세이지</span></div>
|
||||
<div class="pl"><img class="ag" src="../../mock/assets/val/a-omen.png">현우 <span class="tag ok" style="font-size:10px;padding:0 5px">음성</span><span class="d">우리 팀 · 오멘</span></div>
|
||||
|
||||
@@ -26,7 +26,7 @@ main{padding:12px;display:flex;flex-direction:column;gap:10px}
|
||||
.p.bad{border-color:#6a2430;background:rgba(255,70,85,.08)}
|
||||
.sn{font-weight:800}
|
||||
</style></head><body>
|
||||
<div class="mh"><div class="brand"><img src="../../../../assets/app/icon.png"><div><div class="nm">겜녹이</div></div></div><span class="chip on new" style="margin-left:auto;font-size:12px;padding:4px 10px">🔍 범인찾기</span><span class="av" style="background:#5865f2;width:26px;height:26px">승</span></div>
|
||||
<div class="mh"><div class="brand"><img src="../../../../assets/app/icon.png"><div><div class="nm">겜녹이</div></div></div><span class="chip on new" style="margin-left:auto;font-size:12px;padding:4px 10px">🔍 범인찾기</span><span class="av" style="background:#5865f2;width:26px;height:26px">하</span></div>
|
||||
<main>
|
||||
<div class="hero">
|
||||
<div class="h" style="font-size:11px;color:var(--lol);font-weight:800;letter-spacing:2px">범인 분석 · LEAGUE OF LEGENDS</div>
|
||||
@@ -48,7 +48,7 @@ main{padding:12px;display:flex;flex-direction:column;gap:10px}
|
||||
<div class="why">라인전에서 다섯 번 죽어 탑 1차·2차 포탑을 15분 안에 내줬다. 바론 한타에 텔레포트 없이 늦게 합류.</div>
|
||||
</div>
|
||||
<div class="sec">우리 팀</div>
|
||||
<div class="p"><img src="../../mock/assets/lol/c-Ahri.png"><div class="b"><div class="l1"><b>승한</b><span class="muted" style="font-size:12px">아리</span><span class="tag done">캐리</span><span class="k"><span class="sn" style="color:var(--ink)">9.0</span> · 11/2/8</span></div><div class="c">바론 한타 매혹 세 명. 콜도 정확했다.</div></div></div>
|
||||
<div class="p"><img src="../../mock/assets/lol/c-Ahri.png"><div class="b"><div class="l1"><b>하늘</b><span class="muted" style="font-size:12px">아리</span><span class="tag done">캐리</span><span class="k"><span class="sn" style="color:var(--ink)">9.0</span> · 11/2/8</span></div><div class="c">바론 한타 매혹 세 명. 콜도 정확했다.</div></div></div>
|
||||
<div class="p"><img src="../../mock/assets/lol/c-Thresh.png"><div class="b"><div class="l1"><b>지우</b><span class="muted" style="font-size:12px">쓰레쉬</span><span class="tag ok">숨은 MVP</span><span class="k"><span class="sn" style="color:var(--ink)">7.5</span> · 1/5/19</span></div><div class="c">시야 점수 1위. 용 콜을 가장 먼저 했다.</div></div></div>
|
||||
<div class="p"><img src="../../mock/assets/lol/c-Ezreal.png"><div class="b"><div class="l1"><b>현우</b><span class="muted" style="font-size:12px">이즈리얼</span><span class="tag wait">무난</span><span class="k"><span class="sn" style="color:var(--ink)">7.0</span> · 8/4/9</span></div><div class="c">안정적. 딜량 팀 2위.</div></div></div>
|
||||
<div class="p"><img src="../../mock/assets/lol/c-Darius.png"><div class="b"><div class="l1"><b>준호</b><span class="muted" style="font-size:12px">다리우스</span><span class="tag wait">무난</span><span class="k"><span class="sn" style="color:var(--ink)">6.5</span> · 8/5/4</span></div><div class="c">라인전 압승, 한타 진입은 한 박자 빨랐다.</div></div></div>
|
||||
|
||||
@@ -41,7 +41,7 @@ main{flex:1;display:flex;flex-direction:column;gap:14px;padding:18px 24px;min-he
|
||||
<div class="brand"><img src="../../../../assets/app/icon.png" alt=""><div><div class="nm">겜녹이</div><div class="en">GAME VOICE RECORDER</div></div></div>
|
||||
<span class="chip">타임라인</span><span class="chip">경기</span><span class="chip">유저</span><span class="chip">단어사전</span><span class="chip on new">🔍 범인찾기</span>
|
||||
<div class="search">🔍 대화 내용 검색 (예: 스파이크)</div>
|
||||
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">승</span>승한</div>
|
||||
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">하</span>하늘</div>
|
||||
</header>
|
||||
<main>
|
||||
<div class="hero">
|
||||
@@ -56,7 +56,7 @@ main{flex:1;display:flex;flex-direction:column;gap:14px;padding:18px 24px;min-he
|
||||
<div class="lab">우리 팀 범인</div>
|
||||
<div class="who"><img src="../../mock/assets/val/a-omen.png"><div><div class="nm">현우<small>오멘 · 14 / 19 / 6 · ACS 171</small></div><div class="muted" style="font-size:13px">평점 3.5 / 10</div></div><div class="stamp">범인</div></div>
|
||||
<div class="why">마지막 네 라운드 중 세 번(R21·R23·R24)을 혼자 B 메인으로 먼저 들어가 첫 데스. 팀이 "기다려"라고 두 번 말했는데 그대로 진입했고, 첫 데스 7회로 팀에서 가장 많다. 스모크도 R22 리테이크에서 늦게 깔려 수적 우위를 잃었다.</div>
|
||||
<div class="ev"><span class="t">R21 0:22</span><span class="ty v">대화</span><b style="color:var(--u1)">승한</b> 현우야 같이 가 기다려 둘 있어<span class="pl">▶ 듣기</span></div>
|
||||
<div class="ev"><span class="t">R21 0:22</span><span class="ty v">대화</span><b style="color:var(--u1)">하늘</b> 현우야 같이 가 기다려 둘 있어<span class="pl">▶ 듣기</span></div>
|
||||
<div class="ev"><span class="t">R21 0:25</span><span class="ty v">대화</span><b style="color:var(--u4)">현우</b> 아 그냥 간다 내가 뚫을게<span class="pl">▶ 듣기</span></div>
|
||||
<div class="ev"><span class="t">R21 0:29</span><span class="ty k">킬</span>Nox (사이퍼) ▶ 현우 · 첫 데스, 덫에 걸림<span class="pl">타임라인 →</span></div>
|
||||
<div class="ev"><span class="t">경기 전체</span><span class="ty s">스탯</span>첫 데스 7회 (팀 1위) · 첫 킬 2회<span class="pl">스코어보드 →</span></div>
|
||||
@@ -67,14 +67,14 @@ main{flex:1;display:flex;flex-direction:column;gap:14px;padding:18px 24px;min-he
|
||||
<div class="why">10명 중 ACS 가장 낮고, 상대가 이긴 13라운드 중 Kiwi 가 기여(킬·어시스트·생존)한 라운드는 5번뿐. R15 에 혼자 장비를 안 사서 4:5 로 싸웠고, 같은 라운드에 전체 채팅으로 "ff" 를 쳤다. 팀이 이긴 건 Lumi 와 Haru 덕분.</div>
|
||||
<div class="ev"><span class="t">R15 0:00</span><span class="ty s">경제</span>Kiwi 혼자 900 크레딧 사용 (팀 평균 4,200)<span class="pl">라운드 →</span></div>
|
||||
<div class="ev"><span class="t">R15 1:12</span><span class="ty c">채팅</span><span class="tag wait" style="font-size:10px">전체</span> <b>Kiwi</b> ff 그냥<span class="pl">타임라인 →</span></div>
|
||||
<div class="ev"><span class="t">R17 0:41</span><span class="ty k">킬</span>승한 (제트) ▶ Kiwi · 혼자 A 메인 정찰하다 잡힘<span class="pl">타임라인 →</span></div>
|
||||
<div class="ev"><span class="t">R17 0:41</span><span class="ty k">킬</span>하늘 (제트) ▶ Kiwi · 혼자 A 메인 정찰하다 잡힘<span class="pl">타임라인 →</span></div>
|
||||
<div class="ev"><span class="t">경기 전체</span><span class="ty s">스탯</span>ACS 132 (10명 중 10위) · 피해량 라운드당 88<span class="pl">스코어보드 →</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="teams">
|
||||
<div class="panel">
|
||||
<h4><span>우리 팀 5명 평가</span><span>평점 · 한 줄 평</span></h4>
|
||||
<div class="row"><img class="ag" src="../../mock/assets/val/a-jett.png"><div class="n"><b>승한</b><span>제트 · 음성 O</span></div><div class="kda"><b>24/15/5</b><br>ACS 272</div><div><div class="sc"><span class="num">8.5</span><span class="bar"><i style="width:85%"></i></span><span class="tag done">캐리</span></div><div class="cm">오퍼레이터 첫 킬 8회. 콜도 가장 많고 정확했다. 후반에 혼자 남아도 끝까지 침착.</div></div></div>
|
||||
<div class="row"><img class="ag" src="../../mock/assets/val/a-jett.png"><div class="n"><b>하늘</b><span>제트 · 음성 O</span></div><div class="kda"><b>24/15/5</b><br>ACS 272</div><div><div class="sc"><span class="num">8.5</span><span class="bar"><i style="width:85%"></i></span><span class="tag done">캐리</span></div><div class="cm">오퍼레이터 첫 킬 8회. 콜도 가장 많고 정확했다. 후반에 혼자 남아도 끝까지 침착.</div></div></div>
|
||||
<div class="row"><img class="ag" src="../../mock/assets/val/a-sage.png"><div class="n"><b>지우</b><span>세이지 · 음성 O</span></div><div class="kda"><b>12/16/13</b><br>ACS 168</div><div><div class="sc"><span class="num">7.5</span><span class="bar"><i style="width:75%"></i></span><span class="tag ok">숨은 MVP</span></div><div class="cm">부활 5번 중 3번이 라운드 승리로 이어짐. 킬은 적어도 벽 타이밍이 좋았다.</div></div></div>
|
||||
<div class="row"><img class="ag" src="../../mock/assets/val/a-sova.png"><div class="n"><b>민수</b><span>소바 · 음성 O</span></div><div class="kda"><b>16/17/9</b><br>ACS 204</div><div><div class="sc"><span class="num">7.0</span><span class="bar"><i style="width:70%"></i></span><span class="tag wait">무난</span></div><div class="cm">정찰 화살 정보 콜이 꾸준했다. R14 리테이크는 민수 드론 정보로 이김.</div></div></div>
|
||||
<div class="row"><img class="ag" src="../../mock/assets/val/a-phoenix.png"><div class="n"><b>Duck#KR3</b><span>피닉스 · 음성 X</span></div><div class="kda"><b>15/17/4</b><br>ACS 196</div><div><div class="sc"><span class="num">5.5</span><span class="bar"><i style="width:55%"></i></span><span class="tag wait">무난</span></div><div class="cm">음성채널에 없어 기록으로만 봄. 스탯은 평균, 세이브 라운드에 무기를 사서 경제가 두 번 꼬임.</div></div></div>
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
<div class="brand"><img src="../../../../assets/app/icon.png" alt=""><div><div class="nm">겜녹이</div><div class="en">GAME VOICE RECORDER</div></div></div>
|
||||
<span class="chip">타임라인</span><span class="chip">경기</span><span class="chip">유저</span><span class="chip">단어사전</span><span class="chip on new">🔍 범인찾기</span>
|
||||
<div class="search">🔍 대화 내용 검색 (예: 스파이크)</div>
|
||||
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">승</span>승한</div>
|
||||
<div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">하</span>하늘</div>
|
||||
</header>
|
||||
|
||||
@@ -35,7 +35,7 @@ body{width:1440px;height:810px;overflow:hidden;position:relative;background:#050
|
||||
<div class="bd">
|
||||
<h3>이 리플레이의 녹음 기록이 있어요</h3>
|
||||
<div class="muted" style="font-size:13.5px">리플레이와 동기화하시겠습니까? 리플레이 시간에 맞춰 그때 한 말과 이벤트를 보여 주고 음성을 들려 줍니다.</div>
|
||||
<div class="m"><img src="../../mock/assets/lol/c-Ahri.png"><div><b style="font-size:15px">소환사의 협곡 · 내전</b> <span class="tag ok" style="background:#0f2a22;color:#7fe0b8;border:1px solid #1d5141;font-size:11px;padding:1px 7px;border-radius:6px;font-weight:700">승리</span><div class="muted" style="font-size:12.5px">10월 15일 21:55 · 38분 · 승한(아리) 외 4명 녹음</div></div></div>
|
||||
<div class="m"><img src="../../mock/assets/lol/c-Ahri.png"><div><b style="font-size:15px">소환사의 협곡 · 내전</b> <span class="tag ok" style="background:#0f2a22;color:#7fe0b8;border:1px solid #1d5141;font-size:11px;padding:1px 7px;border-radius:6px;font-weight:700">승리</span><div class="muted" style="font-size:12.5px">10월 15일 21:55 · 38분 · 하늘(아리) 외 4명 녹음</div></div></div>
|
||||
<div class="ck"><i>✓</i>음성 대화 텍스트<span class="v">655문장</span></div>
|
||||
<div class="ck"><i>✓</i>음성 파일<span class="v">남아 있음 · 10월 22일 삭제 예정</span></div>
|
||||
<div class="ck"><i>✓</i>킬 · 오브젝트 · 채팅<span class="v">112개</span></div>
|
||||
|
||||
@@ -49,19 +49,19 @@ main{flex:1;display:grid;grid-template-columns:1fr 300px;min-height:0}
|
||||
<main>
|
||||
<div class="feed">
|
||||
<div class="it past"><span class="t">7:55</span><div><div class="who" style="color:var(--u3)">지우 <span class="dim" style="font-weight:400">쓰레쉬</span></div><div class="tx">용 쪽 시야 없어 와드 하나 박을게</div></div></div>
|
||||
<div class="it past"><span class="t">8:05</span><div><div class="who" style="color:var(--u1)">승한 <span class="dim" style="font-weight:400">아리</span></div><div class="tx">미드 밀고 갈게 민수야 용 앞으로 와</div></div></div>
|
||||
<div class="it past"><span class="t">8:05</span><div><div class="who" style="color:var(--u1)">하늘 <span class="dim" style="font-weight:400">아리</span></div><div class="tx">미드 밀고 갈게 민수야 용 앞으로 와</div></div></div>
|
||||
<div class="it past"><span class="t">8:12</span><div><div class="who" style="color:var(--u3)">지우 <span class="dim" style="font-weight:400">쓰레쉬</span> <span style="font-size:11px;color:#ff8a94;background:#3a141a;border-radius:5px;padding:1px 6px;margin-left:4px">🔍 범인 근거</span></div><div class="tx">민수야 용 같이 하자 바텀 밀었어</div></div></div>
|
||||
<div class="nowline">지금 8:21</div>
|
||||
<div class="it now"><span class="t">8:20</span><div><div class="who" style="color:var(--u2)">민수 <span class="dim" style="font-weight:400">리 신</span> <span style="font-size:11px;color:#ff8a94;background:#3a141a;border-radius:5px;padding:1px 6px;margin-left:4px">🔍 범인 근거</span></div><div class="tx"><span class="w done">아니</span> <span class="w done">탑</span> <span class="w now">갱</span> <span class="w next">각이야</span> <span class="w next">잠깐만</span></div></div><span style="margin-left:auto;color:var(--accent);font-size:13px">🔊 재생 중</span></div>
|
||||
<div class="it"><span class="t">8:41</span><div><div class="who" style="color:var(--u3)">지우 <span class="dim" style="font-weight:400">쓰레쉬</span></div><div class="tx">아 용 지금 하는데 상대 정글 보여</div></div></div>
|
||||
<div class="it"><span class="t">8:55</span><div class="ev"><img src="../../mock/assets/lol/c-Sejuani.png"><b>Kiwi</b> ▶ <img src="../../mock/assets/lol/c-Thresh.png"><b>지우</b><span class="dim">· 어시 Lumi</span></div></div>
|
||||
<div class="it"><span class="t">9:02</span><div class="ev"><img src="../../mock/assets/lol/o-dragon_ocean.png">상대 팀 <b>바다 드래곤</b> 처치 · Kiwi</div></div>
|
||||
<div class="it"><span class="t">9:06</span><div><div class="who" style="color:var(--u1)">승한 <span class="dim" style="font-weight:400">아리</span></div><div class="tx">괜찮아 다음 용 준비하자</div></div></div>
|
||||
<div class="it"><span class="t">9:06</span><div><div class="who" style="color:var(--u1)">하늘 <span class="dim" style="font-weight:400">아리</span></div><div class="tx">괜찮아 다음 용 준비하자</div></div></div>
|
||||
</div>
|
||||
<div class="side">
|
||||
<div><h4>지금 말하는 사람</h4>
|
||||
<div class="sp talk"><img src="../../mock/assets/lol/c-LeeSin.png">민수<div class="meter"><i style="width:78%"></i></div></div>
|
||||
<div class="sp"><img src="../../mock/assets/lol/c-Ahri.png">승한<div class="meter"><i style="width:0%"></i></div></div>
|
||||
<div class="sp"><img src="../../mock/assets/lol/c-Ahri.png">하늘<div class="meter"><i style="width:0%"></i></div></div>
|
||||
<div class="sp"><img src="../../mock/assets/lol/c-Thresh.png">지우<div class="meter"><i style="width:12%"></i></div></div>
|
||||
<div class="sp"><img src="../../mock/assets/lol/c-Ezreal.png">현우<div class="meter"><i style="width:0%"></i></div></div>
|
||||
<div class="sp"><img src="../../mock/assets/lol/c-Darius.png">준호<div class="meter"><i style="width:0%"></i></div></div>
|
||||
|
||||
@@ -298,7 +298,7 @@ tr.hl td { background:#fff3f4 !important; font-weight:700; }
|
||||
<h3>AI에 보내는 자료 모양 (예시)</h3>
|
||||
<pre class="box"><span class="h"># 경기 발로란트 경쟁전 · 어센트 · 13:9 (우리 팀 승리) · 22라운드 · 46분</span>
|
||||
<span class="h"># 참가자 (번호 이름 팀 요원(역할) K/D/A ACS 라운드당피해 첫킬/첫데스 헤드샷 설치/해체 스킬사용 음성)</span>
|
||||
P1 승한 우리 제트(타격대) 19/12/7 ACS244 ADR148 첫킬1/첫데스2 HS15% 설치0/해체0 랭크:플래티넘 1 음성O
|
||||
P1 하늘 우리 제트(타격대) 19/12/7 ACS244 ADR148 첫킬1/첫데스2 HS15% 설치0/해체0 랭크:플래티넘 1 음성O
|
||||
P5 Duck 우리 킬조이(감시자) 12/15/8 ACS194 ADR92 첫킬2/첫데스2 HS16% 설치0/해체1 랭크:골드 3 음성X
|
||||
<span class="c">[e1] R1 0:08 킬 P2 → P6 (클래식)</span>
|
||||
<span class="v">[u1] R3 0:05 P1: 현우야 같이 가 기다려 둘 있어</span>
|
||||
|
||||
|
Before Width: | Height: | Size: 186 KiB After Width: | Height: | Size: 184 KiB |
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.1 MiB |
|
Before Width: | Height: | Size: 985 KiB After Width: | Height: | Size: 984 KiB |
|
Before Width: | Height: | Size: 834 KiB After Width: | Height: | Size: 832 KiB |
|
Before Width: | Height: | Size: 124 KiB After Width: | Height: | Size: 123 KiB |
|
Before Width: | Height: | Size: 480 KiB After Width: | Height: | Size: 477 KiB |
@@ -40,7 +40,7 @@ body{width:1040px;height:600px;overflow:hidden;background:#313338;color:#dbdee1;
|
||||
<div class="ch on"># 일반</div><div class="ch"># 전적-공유</div>
|
||||
<div class="cat">음성 채널</div>
|
||||
<div class="ch" style="color:#fff">🔊 발로 음성방</div>
|
||||
<div class="vu"><span class="a" style="background:#3987e5">승</span>승한</div>
|
||||
<div class="vu"><span class="a" style="background:#3987e5">하</span>하늘</div>
|
||||
<div class="vu"><span class="a" style="background:#e5743f">민</span>민수</div>
|
||||
<div class="vu"><span class="a" style="background:#1fb383">지</span>지우</div>
|
||||
<div class="vu ex"><span class="a" style="background:#9085e9;opacity:.6">현</span>현우 <span style="font-size:11px">🚫녹음 제외</span></div>
|
||||
@@ -55,7 +55,7 @@ body{width:1040px;height:600px;overflow:hidden;background:#313338;color:#dbdee1;
|
||||
<div class="main">
|
||||
<div class="hd"># 일반</div>
|
||||
<div class="msgs">
|
||||
<div class="msg"><div class="pf" style="background:#3987e5">승</div><div><span class="nm">승한</span><span class="tm">오늘 오후 9:07</span><div>다들 들어와 랭겜 ㄱㄱ</div></div></div>
|
||||
<div class="msg"><div class="pf" style="background:#3987e5">하</div><div><span class="nm">하늘</span><span class="tm">오늘 오후 9:07</span><div>다들 들어와 랭겜 ㄱㄱ</div></div></div>
|
||||
<div class="eph"><div class="msg"><div class="pf" style="background:#0b141c;padding:0;overflow:hidden"><img src="../../../assets/app/icon.png" alt="" style="width:100%;height:100%;border-radius:50%;display:block"></div><div>
|
||||
<div class="used">현우 님이 <b>/녹음제외</b> 사용</div>
|
||||
<span class="nm">겜녹이</span> <span class="bot">앱</span><span class="tm">오늘 오후 9:09</span>
|
||||
|
||||
@@ -27,7 +27,7 @@ body{width:1440px;height:820px;overflow:hidden;position:relative}
|
||||
<div class="d">기록은 게임 PC에만 저장되어 있어서, 프로그램이 켜져 있을 때만 볼 수 있어요.<br>프로그램이 다시 연결되면 이 화면은 자동으로 사라집니다.</div>
|
||||
<div class="st">
|
||||
<div><span class="muted">사이트 서버</span><span class="g">● 정상</span></div>
|
||||
<div><span class="muted">등록된 게임 PC</span><span>승한의 게임 PC <span class="dim">(RTX 5070 Ti)</span></span></div>
|
||||
<div><span class="muted">등록된 게임 PC</span><span>하늘의 게임 PC <span class="dim">(RTX 5070 Ti)</span></span></div>
|
||||
<div><span class="muted">프로그램 상태</span><span class="r">● 연결 해제됨 · 마지막 응답 오늘 23:41 (12분 전)</span></div>
|
||||
<div><span class="muted">다시 확인</span><span class="y">5초마다 자동 확인 중<span class="dots"><i></i><i style="opacity:.6"></i><i style="opacity:.3"></i></span></span></div>
|
||||
</div>
|
||||
|
||||
@@ -66,8 +66,8 @@ td{text-align:right;padding:8px 4px;border-bottom:1px solid #18283a}
|
||||
<h4><span>대화 · 킬 · 오브젝트 (게임 시간)</span><span>현실 시간은 마우스를 올리면 표시</span></h4>
|
||||
<div class="it"><div class="tm mono">20:41</div><div><div class="who" style="color:var(--u2)">민수 <span class="dim" style="font-weight:400">· 리 신</span></div><div class="tx">드래곤 30초 남았어 바텀 웨이브 밀고 와</div></div></div>
|
||||
<div class="it"><div class="tm mono">21:02</div><div class="ev t"><img class="ci" src="assets/lol/c-Thresh.png"> <b style="color:var(--u3)">지우</b> 드래곤 앞 제어 와드 설치</div></div>
|
||||
<div class="it cur"><div class="tm mono">21:14</div><div><div class="who" style="color:var(--u1)">승한 <span class="dim" style="font-weight:400">· 아리 ▶ 재생 중</span></div><div class="tx"><span>지금</span> <span class="w now">이니시</span> <span class="dim">걸어</span> <span class="dim">내가</span> <span class="dim">매혹</span> <span class="dim">맞췄어</span></div></div></div>
|
||||
<div class="it"><div class="tm mono">21:16</div><div class="ev k"><img class="ci" src="assets/lol/c-Ahri.png"> <b style="color:var(--u1)">승한</b> ▶ <img class="ci" src="assets/lol/c-Leblanc.png"> <b>르블랑</b> <span class="dim">· 어시 민수, 지우</span></div></div>
|
||||
<div class="it cur"><div class="tm mono">21:14</div><div><div class="who" style="color:var(--u1)">하늘 <span class="dim" style="font-weight:400">· 아리 ▶ 재생 중</span></div><div class="tx"><span>지금</span> <span class="w now">이니시</span> <span class="dim">걸어</span> <span class="dim">내가</span> <span class="dim">매혹</span> <span class="dim">맞췄어</span></div></div></div>
|
||||
<div class="it"><div class="tm mono">21:16</div><div class="ev k"><img class="ci" src="assets/lol/c-Ahri.png"> <b style="color:var(--u1)">하늘</b> ▶ <img class="ci" src="assets/lol/c-Leblanc.png"> <b>르블랑</b> <span class="dim">· 어시 민수, 지우</span></div></div>
|
||||
<div class="it"><div class="tm mono">21:19</div><div class="ev k"><img class="ci" src="assets/lol/c-LeeSin.png"> <b style="color:var(--u2)">민수</b> ▶ <img class="ci" src="assets/lol/c-Sejuani.png"> <b>세주아니</b> <span class="badge" style="background:#3a1a1f;color:#ff8a94">더블 킬</span></div></div>
|
||||
<div class="it"><div class="tm mono">21:24</div><div><div class="who" style="color:var(--u3)">지우 <span class="dim" style="font-weight:400">· 쓰레쉬</span></div><div class="tx">한타 이겼다 용 먹자 용</div></div></div>
|
||||
<div class="it"><div class="tm mono">21:31</div><div class="ev t" style="border-left-color:#40c1ff">💬 <span class="badge" style="background:#0e2a3a;color:#40c1ff">팀</span> <b style="color:var(--u2)">민수</b> <span class="dim">(리 신)</span> 용 치자 바론 말고 <span class="badge" style="background:#1d2a36;color:var(--dim);margin-left:auto">OCR</span></div></div>
|
||||
@@ -79,7 +79,7 @@ td{text-align:right;padding:8px 4px;border-bottom:1px solid #18283a}
|
||||
<h4><span>스코어보드 · 우리 팀</span><span>21:14 기준</span></h4>
|
||||
<table>
|
||||
<tr><th>소환사</th><th>K/D/A</th><th>CS</th><th>골드</th></tr>
|
||||
<tr style="background:rgba(200,170,110,.08)"><td><img class="ch" src="assets/lol/c-Ahri.png"><b style="color:var(--u1)">승한</b></td><td class="mono">6/1/4</td><td class="mono">188</td><td class="mono">9.4k</td></tr>
|
||||
<tr style="background:rgba(200,170,110,.08)"><td><img class="ch" src="assets/lol/c-Ahri.png"><b style="color:var(--u1)">하늘</b></td><td class="mono">6/1/4</td><td class="mono">188</td><td class="mono">9.4k</td></tr>
|
||||
<tr><td><img class="ch" src="assets/lol/c-LeeSin.png"><b style="color:var(--u2)">민수</b></td><td class="mono">4/2/7</td><td class="mono">132</td><td class="mono">8.1k</td></tr>
|
||||
<tr><td><img class="ch" src="assets/lol/c-Garen.png"><b style="color:var(--u5)">현우</b></td><td class="mono">2/3/3</td><td class="mono">170</td><td class="mono">7.6k</td></tr>
|
||||
<tr><td><img class="ch" src="assets/lol/c-Ezreal.png">Ezreal#KR7</td><td class="mono">5/2/5</td><td class="mono">201</td><td class="mono">9.0k</td></tr>
|
||||
@@ -87,7 +87,7 @@ td{text-align:right;padding:8px 4px;border-bottom:1px solid #18283a}
|
||||
</table>
|
||||
<div style="margin-top:16px;font-size:12px;color:var(--muted)">이 경기 발화량</div>
|
||||
<div style="display:flex;flex-direction:column;gap:7px;margin-top:8px;font-size:13px">
|
||||
<div style="display:flex;justify-content:space-between"><span>승한</span><span class="mono">7분 02초</span></div><div style="height:7px;border-radius:4px;background:#18283a"><i style="display:block;height:100%;width:78%;background:var(--u1);border-radius:4px"></i></div>
|
||||
<div style="display:flex;justify-content:space-between"><span>하늘</span><span class="mono">7분 02초</span></div><div style="height:7px;border-radius:4px;background:#18283a"><i style="display:block;height:100%;width:78%;background:var(--u1);border-radius:4px"></i></div>
|
||||
<div style="display:flex;justify-content:space-between"><span>민수</span><span class="mono">5분 48초</span></div><div style="height:7px;border-radius:4px;background:#18283a"><i style="display:block;height:100%;width:64%;background:var(--u2);border-radius:4px"></i></div>
|
||||
<div style="display:flex;justify-content:space-between"><span>지우</span><span class="mono">4분 11초</span></div><div style="height:7px;border-radius:4px;background:#18283a"><i style="display:block;height:100%;width:46%;background:var(--u3);border-radius:4px"></i></div>
|
||||
</div>
|
||||
|
||||
@@ -54,16 +54,16 @@ td{text-align:right;padding:7px 4px;border-bottom:1px solid #1c2b39}
|
||||
<div class="panel">
|
||||
<h4><span>ROUND 7 · 대화 + 킬피드</span><span>🔁 라운드 전체 이어듣기</span></h4>
|
||||
<div class="feed">
|
||||
<div class="k me"><span class="t mono">0:40</span><span class="av" style="background:var(--u1);width:22px;height:22px;font-size:10px">승</span><b>승한</b><img class="wk" src="assets/val/w-operator-kill.png"><span class="dim">▶</span><img class="ag" src="assets/val/a-raze.png"><b>Lumi#KR1</b><span class="dim">헤드샷</span></div>
|
||||
<div class="k me"><span class="t mono">0:40</span><span class="av" style="background:var(--u1);width:22px;height:22px;font-size:10px">하</span><b>하늘</b><img class="wk" src="assets/val/w-operator-kill.png"><span class="dim">▶</span><img class="ag" src="assets/val/a-raze.png"><b>Lumi#KR1</b><span class="dim">헤드샷</span></div>
|
||||
<div class="k"><span class="t mono">0:47</span><span class="av" style="background:var(--u3);width:22px;height:22px;font-size:10px">지</span><b>지우</b><img class="wk" src="assets/val/w-vandal-kill.png"><span class="dim">▶</span><img class="ag" src="assets/val/a-killjoy.png"><b>Nox#0420</b></div>
|
||||
<div class="k"><span class="t mono">1:08</span><img class="ag" src="assets/val/a-reyna.png"><b>Haru#KR2</b><img class="wk" src="assets/val/w-sheriff-kill.png"><span class="dim">▶</span><span class="av" style="background:var(--u2);width:22px;height:22px;font-size:10px">민</span><b>민수</b><span class="dim">· 데스</span></div>
|
||||
</div>
|
||||
<div class="talk" style="margin-top:8px">
|
||||
<div class="l"><span class="t mono">0:31</span><b style="color:var(--u1)">승한</b> A 메인 둘 봤어 하나 체력 낮아</div>
|
||||
<div class="l"><span class="t mono">0:31</span><b style="color:var(--u1)">하늘</b> A 메인 둘 봤어 하나 체력 낮아</div>
|
||||
<div class="l cur"><span class="t mono">0:38</span><b style="color:var(--u3)">지우</b> 내가 <span style="background:var(--accent);border-radius:3px;padding:0 4px">스모크</span> 깔게 들어가 들어가</div>
|
||||
<div class="l"><span class="t mono">0:41</span><b style="color:var(--u2)">민수</b> 나이스 원탭!</div>
|
||||
<div class="l"><span class="t mono">0:51</span><span class="badge" style="background:#3a2c10;color:var(--gold)">💬 팀</span> <b style="color:var(--u2)">민수</b> 스파이크 설치함 B로 돌지마</div>
|
||||
<div class="l"><span class="t mono">1:02</span><b style="color:var(--u1)">승한</b> 레이즈 하나 남았어 메인 쪽에서 와 시간 끌어</div>
|
||||
<div class="l"><span class="t mono">1:02</span><b style="color:var(--u1)">하늘</b> 레이즈 하나 남았어 메인 쪽에서 와 시간 끌어</div>
|
||||
<div class="l"><span class="t mono">1:09</span><b style="color:var(--u2)">민수</b> 아 미안 셰리프 맞았다</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -71,7 +71,7 @@ td{text-align:right;padding:7px 4px;border-bottom:1px solid #1c2b39}
|
||||
<h4><span>우리 팀 스코어보드</span></h4>
|
||||
<table>
|
||||
<tr><th>플레이어</th><th>K</th><th>D</th><th>A</th><th>ACS</th></tr>
|
||||
<tr><td><img class="ag" src="assets/val/a-jett.png"> 승한 <span class="dim">제트</span></td><td>21</td><td>14</td><td>5</td><td style="color:var(--accent)">268</td></tr>
|
||||
<tr><td><img class="ag" src="assets/val/a-jett.png"> 하늘 <span class="dim">제트</span></td><td>21</td><td>14</td><td>5</td><td style="color:var(--accent)">268</td></tr>
|
||||
<tr><td><img class="ag" src="assets/val/a-sova.png"> 민수 <span class="dim">소바</span></td><td>15</td><td>16</td><td>9</td><td>201</td></tr>
|
||||
<tr><td><img class="ag" src="assets/val/a-sage.png"> 지우 <span class="dim">세이지</span></td><td>11</td><td>15</td><td>12</td><td>164</td></tr>
|
||||
<tr><td><img class="ag" src="assets/val/a-omen.png"> 현우 <span class="dim">오멘</span></td><td>16</td><td>13</td><td>7</td><td>222</td></tr>
|
||||
|
||||
@@ -27,12 +27,12 @@ header{padding:6px 16px 10px;display:flex;align-items:center;gap:10px}
|
||||
<div class="chips"><span class="chip on">어센트 13:9</span><span class="chip">👥 전체 유저</span><span class="chip">💬 채팅</span><span class="chip">⚔ 킬</span></div>
|
||||
<div class="list">
|
||||
<div class="div"><b>R7</b>공격 · 4 : 2</div>
|
||||
<div class="it"><span class="av" style="background:var(--u1)">승</span><div><div class="t mono">R7 · 0:31 <span style="color:var(--u1);font-family:'Noto Sans CJK KR'">승한</span></div><div class="x">A 메인 둘 봤어 하나 체력 낮아</div></div></div>
|
||||
<div class="it"><span class="av" style="background:var(--u1)">하</span><div><div class="t mono">R7 · 0:31 <span style="color:var(--u1);font-family:'Noto Sans CJK KR'">하늘</span></div><div class="x">A 메인 둘 봤어 하나 체력 낮아</div></div></div>
|
||||
<div class="it p"><span class="av" style="background:var(--u3)">지</span><div><div class="t mono">R7 · 0:38 <span style="color:var(--u3);font-family:'Noto Sans CJK KR'">지우</span></div><div class="x">내가 <span style="background:var(--accent);border-radius:3px;padding:0 3px">스모크</span> <span class="dim">깔게 들어가 들어가</span></div></div></div>
|
||||
<div class="ev"><img class="ag" src="assets/val/a-jett.png"> <b style="color:var(--u1)">승한</b> <img class="wk" src="assets/val/w-operator-kill.png"> ▶ <img class="ag" src="assets/val/a-raze.png"> Lumi#KR1 <span class="dim">· 헤드샷</span></div>
|
||||
<div class="ev"><img class="ag" src="assets/val/a-jett.png"> <b style="color:var(--u1)">하늘</b> <img class="wk" src="assets/val/w-operator-kill.png"> ▶ <img class="ag" src="assets/val/a-raze.png"> Lumi#KR1 <span class="dim">· 헤드샷</span></div>
|
||||
<div class="it"><span class="av" style="background:var(--u2)">민</span><div><div class="t mono">R7 · 0:44 <span style="color:var(--u2);font-family:'Noto Sans CJK KR'">민수</span></div><div class="x dim" style="font-style:italic">[잡음]</div></div></div>
|
||||
<div class="ev" style="border-left-color:var(--gold)">💬 [팀] 민수: 스파이크 설치함</div>
|
||||
<div class="it"><span class="av" style="background:var(--u1)">승</span><div><div class="t mono">R7 · 1:02 <span style="color:var(--u1);font-family:'Noto Sans CJK KR'">승한</span></div><div class="x">레이즈 하나 남았어 메인 쪽에서 와 시간 끌어</div></div></div>
|
||||
<div class="it"><span class="av" style="background:var(--u1)">하</span><div><div class="t mono">R7 · 1:02 <span style="color:var(--u1);font-family:'Noto Sans CJK KR'">하늘</span></div><div class="x">레이즈 하나 남았어 메인 쪽에서 와 시간 끌어</div></div></div>
|
||||
<div class="ev" style="border-left-color:var(--mint)">🏆 라운드 승리 · 5 : 2</div>
|
||||
<div class="div"><b>R8</b>공격 · 5 : 2</div>
|
||||
<div class="it"><span class="av" style="background:var(--u2)">민</span><div><div class="t mono">R8 · 구매 <span style="color:var(--u2);font-family:'Noto Sans CJK KR'">민수</span></div><div class="x">나 오퍼 사줄 사람</div></div></div>
|
||||
|
||||
@@ -64,13 +64,13 @@ footer{height:96px;border-top:1px solid var(--line);background:#0f1b26;display:f
|
||||
<div class="brand"><img src="../../../assets/app/icon.png" alt=""><div><div class="nm">겜녹이</div><div class="en">GAME VOICE RECORDER</div></div></div>
|
||||
<span class="chip on">타임라인</span><span class="chip">경기</span><span class="chip">유저</span><span class="chip">단어사전</span>
|
||||
<div class="search" style="margin-left:24px">🔍 대화 내용 검색 (예: 스파이크)</div>
|
||||
<div class="rec"><i></i> 녹음 중 · #발로 음성방 · 4명</div><div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">승</span>승한</div>
|
||||
<div class="rec"><i></i> 녹음 중 · #발로 음성방 · 4명</div><div class="conn">● 게임 PC 연결됨</div><div class="me"><span class="av" style="background:#5865f2;width:26px;height:26px">하</span>하늘</div>
|
||||
</header>
|
||||
<main>
|
||||
<aside>
|
||||
<div>
|
||||
<h4>유저</h4>
|
||||
<div class="urow sel"><span class="chk on"></span><span class="av" style="background:var(--u1)">승</span><img class="ag" src="assets/val/a-jett.png" style="margin-left:-4px"><span class="n">승한</span><span class="c">제트</span></div>
|
||||
<div class="urow sel"><span class="chk on"></span><span class="av" style="background:var(--u1)">하</span><img class="ag" src="assets/val/a-jett.png" style="margin-left:-4px"><span class="n">하늘</span><span class="c">제트</span></div>
|
||||
<div class="urow sel"><span class="chk on"></span><span class="av" style="background:var(--u2)">민</span><img class="ag" src="assets/val/a-sova.png" style="margin-left:-4px"><span class="n">민수</span><span class="c">소바</span></div>
|
||||
<div class="urow sel"><span class="chk on"></span><span class="av" style="background:var(--u3)">지</span><img class="ag" src="assets/val/a-sage.png" style="margin-left:-4px"><span class="n">지우</span><span class="c">세이지</span></div>
|
||||
<div class="urow"><span class="chk"></span><span class="av" style="background:var(--u5)">현</span><img class="ag" src="assets/val/a-omen.png" style="margin-left:-4px"><span class="n muted">현우</span><span class="c">오멘</span></div>
|
||||
@@ -94,12 +94,12 @@ footer{height:96px;border-top:1px solid var(--line);background:#0f1b26;display:f
|
||||
<div class="div"><span>경기 전 · 현실 시간</span></div>
|
||||
<div class="it"><div class="time real mono">21:08:44<small>현실 시간</small></div><div class="body"><div class="who" style="color:var(--u2)">민수</div><div class="txt">큐 돌리자 이번 판은 어센트 나왔으면 좋겠다</div></div></div>
|
||||
<div class="div"><span class="pill">ROUND 7</span><span>어센트 · 공격</span><span class="score">4 : 2</span></div>
|
||||
<div class="it"><div class="time mono">R7 · 0:31<small>12:07</small></div><div class="body"><div class="who" style="color:var(--u1)">승한</div><div class="txt">A 메인 둘 봤어 하나 체력 낮아 <span class="dim" style="font-size:12px">· 74 HP 남음</span></div></div></div>
|
||||
<div class="it"><div class="time mono">R7 · 0:31<small>12:07</small></div><div class="body"><div class="who" style="color:var(--u1)">하늘</div><div class="txt">A 메인 둘 봤어 하나 체력 낮아 <span class="dim" style="font-size:12px">· 74 HP 남음</span></div></div></div>
|
||||
<div class="it playing"><div class="time mono">R7 · 0:38<small>12:14</small></div><div class="body"><div class="who" style="color:var(--u3)">지우 <span class="dim" style="font-weight:400;font-size:12px">▶ 재생 중</span></div><div class="txt"><span class="w done">내가</span> <span class="w now">스모크</span> <span class="w todo">깔게</span> <span class="w todo">들어가</span> <span class="w todo">들어가</span></div></div></div>
|
||||
<div class="it"><div class="time mono">R7 · 0:40<small>12:16</small></div><div class="body"><div class="ev kill"><img class="ag" src="assets/val/a-jett.png"> <b style="color:var(--u1)">승한</b> <img class="wk" src="assets/val/w-operator-kill.png"> ▶ <img class="ag" src="assets/val/a-raze.png"> <b>Lumi#KR1</b> <span class="dim">헤드샷</span></div></div></div>
|
||||
<div class="it"><div class="time mono">R7 · 0:40<small>12:16</small></div><div class="body"><div class="ev kill"><img class="ag" src="assets/val/a-jett.png"> <b style="color:var(--u1)">하늘</b> <img class="wk" src="assets/val/w-operator-kill.png"> ▶ <img class="ag" src="assets/val/a-raze.png"> <b>Lumi#KR1</b> <span class="dim">헤드샷</span></div></div></div>
|
||||
<div class="it"><div class="time mono">R7 · 0:44<small>12:20</small></div><div class="body"><div class="who" style="color:var(--u2)">민수</div><div class="txt noise">[잡음] <span class="mini-wave"><i style="height:6px"></i><i style="height:12px"></i><i style="height:5px"></i><i style="height:9px"></i><i style="height:4px"></i></span></div></div></div>
|
||||
<div class="it"><div class="time mono">R7 · 0:51<small>12:27</small></div><div class="body"><div class="ev chat">💬 <span class="badge" style="background:#3a2c10;color:var(--gold)">팀</span> <b style="color:var(--u2)">민수</b> 스파이크 설치함 B로 돌지마</div></div></div>
|
||||
<div class="it"><div class="time mono">R7 · 1:02<small>12:38</small></div><div class="body"><div class="who" style="color:var(--u1)">승한</div><div class="txt">레이즈 하나 남았어 메인 쪽에서 와 시간 끌어</div></div></div>
|
||||
<div class="it"><div class="time mono">R7 · 1:02<small>12:38</small></div><div class="body"><div class="who" style="color:var(--u1)">하늘</div><div class="txt">레이즈 하나 남았어 메인 쪽에서 와 시간 끌어</div></div></div>
|
||||
<div class="it"><div class="time mono">R7 · 1:20<small>12:56</small></div><div class="body"><div class="ev win">🏆 라운드 승리 · 스파이크 폭발 · <span class="mono">5 : 2</span></div></div></div>
|
||||
</section>
|
||||
<div class="right">
|
||||
@@ -112,7 +112,7 @@ footer{height:96px;border-top:1px solid var(--line);background:#0f1b26;display:f
|
||||
<div class="bar"><i style="width:94%;background:var(--mint)"></i></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h5>이 경기 · 승한</h5>
|
||||
<h5>이 경기 · 하늘</h5>
|
||||
<div style="display:flex;justify-content:space-around;text-align:center">
|
||||
<div><div class="h" style="font-size:24px;font-weight:800">21</div><div class="dim" style="font-size:12px">킬</div></div>
|
||||
<div><div class="h" style="font-size:24px;font-weight:800">14</div><div class="dim" style="font-size:12px">데스</div></div>
|
||||
@@ -122,7 +122,7 @@ footer{height:96px;border-top:1px solid var(--line);background:#0f1b26;display:f
|
||||
</div>
|
||||
<div class="card">
|
||||
<h5>이 경기 발화량</h5>
|
||||
<div class="kv"><span>승한</span><span class="mono">8분 12초</span></div><div class="bar"><i style="width:82%;background:var(--u1)"></i></div>
|
||||
<div class="kv"><span>하늘</span><span class="mono">8분 12초</span></div><div class="bar"><i style="width:82%;background:var(--u1)"></i></div>
|
||||
<div class="kv"><span>민수</span><span class="mono">6분 40초</span></div><div class="bar"><i style="width:66%;background:var(--u2)"></i></div>
|
||||
<div class="kv"><span>지우</span><span class="mono">4분 05초</span></div><div class="bar"><i style="width:41%;background:var(--u3)"></i></div>
|
||||
</div>
|
||||
|
||||
@@ -2,3 +2,4 @@ export * from './protocol.js';
|
||||
export * from './time.js';
|
||||
export * from './rating.js';
|
||||
export * from './rating-model.js';
|
||||
export * from './live-game.js';
|
||||
|
||||
35
packages/shared/src/live-game.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import type { LiveGame } from './protocol.js';
|
||||
import { fmtClock } from './time.js';
|
||||
|
||||
export const GAME_NAME: Record<LiveGame['game'], string> = { valorant: '발로란트', lol: '리그 오브 레전드' };
|
||||
|
||||
/** 지금 게임 상태를 한 줄로 (헤더 · 알림용): "경쟁전 · 어센트 · R15 8:6" */
|
||||
export function liveGameLine(g: LiveGame): string {
|
||||
if (!g.inMatch) return g.phase + (g.mode && g.connected ? ` · ${g.mode}` : '');
|
||||
const parts = [g.mode, g.map].filter(Boolean) as string[];
|
||||
if (g.round != null && g.score) parts.push(`R${g.round} ${g.score.ally}:${g.score.enemy}`);
|
||||
else if (g.score) parts.push(`${g.score.ally}:${g.score.enemy}`);
|
||||
if (g.gameTimeSec != null) parts.push(fmtClock(g.gameTimeSec * 1000));
|
||||
return parts.join(' · ') || '경기 중';
|
||||
}
|
||||
|
||||
/** 지금 게임 상태 자세히 (앱 게임 연동 탭 · 사이트 패널): [항목, 값] */
|
||||
export function liveGameRows(g: LiveGame, now = Date.now()): [string, string][] {
|
||||
const rows: [string, string][] = [['상태', g.phase]];
|
||||
if (g.self?.name) rows.push(['내 계정', g.self.name]);
|
||||
if (g.mode) rows.push(['모드', g.mode]);
|
||||
if (g.map) rows.push(['맵', g.map]);
|
||||
if (g.inMatch) {
|
||||
if (g.round != null) rows.push(['라운드', `${g.round}라운드`]);
|
||||
if (g.score) rows.push([g.round != null ? '점수 (우리 : 상대)' : '점수', `${g.score.ally} : ${g.score.enemy}`]);
|
||||
if (g.gameTimeSec != null) rows.push(['게임 시간', fmtClock(g.gameTimeSec * 1000)]);
|
||||
else if (g.startedAt) rows.push(['경과', fmtClock(Math.max(0, now - g.startedAt))]);
|
||||
if (g.teamKills) rows.push(['팀 킬 (우리 : 상대)', `${g.teamKills.ally} : ${g.teamKills.enemy}`]);
|
||||
if (g.self?.character) rows.push([g.game === 'lol' ? '내 챔피언' : '내 요원', g.self.character]);
|
||||
if (g.self?.kda) rows.push(['KDA', g.self.kda]);
|
||||
if (g.self?.extra) rows.push(['내 성적', g.self.extra]);
|
||||
if (g.players) rows.push(['인원', `${g.players}명`]);
|
||||
}
|
||||
if (g.error) rows.push(['오류', g.error]);
|
||||
return rows;
|
||||
}
|
||||
@@ -32,6 +32,42 @@ export interface User {
|
||||
|
||||
export type UtteranceStatus = 'pending' | 'realtime' | 'precise' | 'failed';
|
||||
|
||||
/** 발화 자세한 정보 (사이트 우클릭 → 자세한 정보, v1.3.6~) */
|
||||
export interface UtteranceInfo {
|
||||
id: string;
|
||||
userId: string;
|
||||
/** 원본 음성 파일 이름 (예: 0mv9wpior2f765541ac.ogg) */
|
||||
fileName: string | null;
|
||||
/** 게임 PC 안의 전체 경로 */
|
||||
path: string | null;
|
||||
/** 파일이 있는 폴더 */
|
||||
folder: string | null;
|
||||
/** 파일 크기 (바이트), 지워졌으면 null */
|
||||
sizeBytes: number | null;
|
||||
/** 파일이 지워진 이유: 보관 기간 · 잡음 · 파일 없음 */
|
||||
deleted: null | 'retention' | 'noise' | 'missing';
|
||||
startedAt: number;
|
||||
endedAt: number;
|
||||
durationMs: number;
|
||||
/** 녹음 세션 · 음성채널 */
|
||||
sessionId: string | null;
|
||||
channel: string | null;
|
||||
matchId: string | null;
|
||||
status: string;
|
||||
model: string | null;
|
||||
confidence: number | null;
|
||||
lufs: number | null;
|
||||
gainDb: number | null;
|
||||
/** 사전 교정 전 원래 인식 결과 */
|
||||
rawText: string | null;
|
||||
text: string | null;
|
||||
corrected: boolean;
|
||||
noise: boolean;
|
||||
noiseReason: string | null;
|
||||
attempts: number;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface UtteranceItem {
|
||||
kind: 'utterance';
|
||||
id: string;
|
||||
@@ -208,11 +244,47 @@ export interface MatchDetail extends MatchSummary {
|
||||
| null;
|
||||
}
|
||||
|
||||
/** 지금 연결된 게임 · 진행 중인 경기 (앱 게임 연동 탭 · 사이트, v1.3.6~) */
|
||||
export interface LiveGame {
|
||||
game: GameType;
|
||||
/** 연동을 켰는지 */
|
||||
enabled: boolean;
|
||||
/** 게임 클라이언트(Riot 클라이언트 · 롤 클라이언트)에 연결됨 */
|
||||
connected: boolean;
|
||||
/** 지금 상태: 꺼짐 · 메뉴 · 대기열 · 요원 선택 · 경기 중 · 경기 끝 … */
|
||||
phase: string;
|
||||
inMatch: boolean;
|
||||
matchId: string | null;
|
||||
/** 모드 이름 (경쟁전, 신속플레이, 데스매치, 솔로 랭크, 칼바람 나락 …) */
|
||||
mode: string | null;
|
||||
map: string | null;
|
||||
mapImage: string | null;
|
||||
/** 경기 시작 시각 (PC 시계) */
|
||||
startedAt: number | null;
|
||||
/** 발로란트 라운드제 모드: 지금 라운드 */
|
||||
round: number | null;
|
||||
/** 발로란트 점수. 라운드제는 팀 점수, 데스매치 등은 게임이 주는 점수 */
|
||||
score: { ally: number; enemy: number } | null;
|
||||
/** 롤: 게임 시간(초) */
|
||||
gameTimeSec: number | null;
|
||||
/** 롤: 팀 킬 */
|
||||
teamKills: { ally: number; enemy: number } | null;
|
||||
/** 내 계정 · 요원/챔피언 · 성적 */
|
||||
self: { name: string | null; character: string | null; characterImage: string | null; kda: string | null; extra: string | null } | null;
|
||||
/** 경기 인원 */
|
||||
players: number | null;
|
||||
/** 마지막 오류 (연결 실패 등) */
|
||||
error: string | null;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface Overview {
|
||||
guild: { id: string; name: string; icon: string | null } | null;
|
||||
recording: { active: boolean; channel: string | null; since: number | null; participants: string[] };
|
||||
users: User[];
|
||||
games: { valorant: { connected: boolean; inMatch: boolean }; lol: { connected: boolean; inMatch: boolean } };
|
||||
/** 지금 게임 상태 (v1.3.6~ 앱만 보냄) */
|
||||
live?: LiveGame[];
|
||||
counts: { utterances: number; matches: number };
|
||||
version: string;
|
||||
}
|
||||
@@ -239,12 +311,8 @@ export interface CulpritPlayer {
|
||||
userId: string | null;
|
||||
/** 이 경기 음성 대화가 있는지 */
|
||||
voice: boolean;
|
||||
/** Riot ID 태그 (OP.GG 에서 경기를 찾을 때, v1.3~) */
|
||||
tag?: string;
|
||||
/** 기록 점수: OP.GG OP스코어 방식으로 우리 기록에서 계산 (v1.3~) */
|
||||
/** 기록 점수: OP.GG OP스코어 계산법을 따라 우리 기록에서 계산 (v1.3~) */
|
||||
rating?: PlayerRating;
|
||||
/** OP.GG 에 이 경기가 있으면 그 사이트의 실제 OP스코어 (사이트 서버가 분석할 때 붙인다) */
|
||||
opgg?: { score: number; rank: number | null };
|
||||
}
|
||||
/** 근거 번호가 가리키는 것 (사이트에서 누르면 그 순간으로 이동) */
|
||||
export type CulpritRefTarget =
|
||||
@@ -259,8 +327,6 @@ export interface CulpritInput {
|
||||
refs: Record<string, CulpritRefTarget>;
|
||||
players: CulpritPlayer[];
|
||||
stats: { utterances: number; utterancesTotal: number; events: number; chats: number; rounds: number; basic: boolean };
|
||||
/** OP.GG 에서 같은 경기를 찾을 정보 (v1.3~). riotMatchId = 발로란트 경기 UUID · 롤 gameId */
|
||||
lookup?: { riotMatchId: string | null; startedAt: number; endedAt: number; durationSec: number };
|
||||
}
|
||||
export interface CulpritEvidence {
|
||||
ref: string;
|
||||
@@ -290,8 +356,6 @@ export interface CulpritAnalysis {
|
||||
usage?: { input: number; output: number; cacheRead?: number; cacheWrite?: number };
|
||||
inputStats?: CulpritInput['stats'];
|
||||
fallback?: boolean;
|
||||
/** OP.GG 실제 점수를 찾았는지 · 못 찾은 이유. error = 조회 실패로 확인 못 함 (경기 없음과 다르다) */
|
||||
opgg?: { found: boolean; error?: boolean; note?: string };
|
||||
};
|
||||
}
|
||||
export interface CulpritMatchItem {
|
||||
@@ -328,7 +392,8 @@ export type LiveEvent =
|
||||
| { type: 'event.created'; data: EventItem }
|
||||
| { type: 'match.updated'; data: MatchSummary }
|
||||
| { type: 'recording.state'; data: Overview['recording'] }
|
||||
| { type: 'users.updated'; data: User[] };
|
||||
| { type: 'users.updated'; data: User[] }
|
||||
| { type: 'games.state'; data: LiveGame[] };
|
||||
|
||||
export interface DeviceStatus {
|
||||
registered: boolean;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!-- 겜녹이 범인찾기 시스템 프롬프트 v1.2 (2026-10-15, 사용자 결정 반영: 범인 = 종합 판단, 말투 기본 중간맛,
|
||||
전적 사이트 점수 참고: 기록 점수 = OP.GG OP스코어 방식, OP.GG 실제 점수, LOL.PS 방식 라인전)
|
||||
전적 사이트 계산법 참고: 기록 점수 = OP.GG OP스코어 계산법, 라인전 = LOL.PS 라인전 점수의 입력. 외부 사이트에 접속하지 않고 경기 기록으로 계산)
|
||||
서버가 이 파일 + 게임별 knowledge-*.md 를 system 에 넣고, 경기 자료는 user 메시지로 보낸다.
|
||||
{{tone}} 은 말투 설정(mild|medium|spicy)으로 바꾼다. 이 파일과 knowledge 는 경기마다 같아서 프롬프트 캐시 대상이다. -->
|
||||
너는 겜녹이의 경기 분석가다. 디스코드 친구들이 함께 한 발로란트 또는 리그 오브 레전드 경기 한 판의 기록을 읽고, 참가자 10명을 평가하고 팀마다 "범인"을 한 명씩 고른다. 결과는 친구들이 재미로 보는 사이트에 그대로 뜬다. 정확하고 공정해야 웃고 넘길 수 있다.
|
||||
@@ -8,10 +8,9 @@
|
||||
user 메시지의 <match> 안에 경기 자료가 온다.
|
||||
- 경기: 게임, 모드, 맵, 최종 점수, 길이. "우리 팀" = 음성을 녹음한 쪽 팀, "상대 팀" = 다른 팀.
|
||||
- 참가자: P1~P10 번호, 이름, 팀, 요원·챔피언과 역할(포지션), 스탯, 음성 유무(음성O / 음성X).
|
||||
- 기록 점수: 전적 사이트 OP.GG 의 OP스코어를 같은 방식으로 이 경기 기록에서 다시 계산한 0~10점. 경기 순위 · 팀 순위, 이긴 팀 1등 MVP · 진 팀 1등 ACE, 그 점수를 경기 평균보다 올린 강점과 깎은 약점이 붙는다.
|
||||
발로란트는 라운드 승률 · KAST · ACS · 피해 격차, 롤은 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드로 낸다. 실제 OP.GG 점수와 평균 0.5~0.6점 차이다.
|
||||
- 기록 점수: 전적 사이트 OP.GG 의 OP스코어 계산법을 따라 이 경기 기록으로 계산한 0~10점. 경기 순위 · 팀 순위, 이긴 팀 1등 MVP · 진 팀 1등 ACE, 그 점수를 경기 평균보다 올린 강점과 깎은 약점이 붙는다.
|
||||
발로란트는 라운드 승률 · KAST · ACS · 피해 격차, 롤은 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드로 낸다. OP.GG 가 매기는 점수와 평균 0.5~0.6점 차이다.
|
||||
롤 "라인전(vs P6) 10분 CS+5 골드+300 경험치+120 15분 CS+12 골드+640 경험치+210" = 전적 사이트 LOL.PS 가 라인전 점수를 낼 때 쓰는 값. 10분 · 15분에 맞라이너보다 앞선(+) · 뒤진(-) CS · 골드 · 경험치.
|
||||
- "OP.GG 실제 OP스코어" 줄이 있으면 이 경기를 OP.GG 에서 찾은 그 사이트의 실제 점수다. 기록 점수보다 이것을 먼저 본다. 이 줄이 없으면 OP.GG 에 없는 경기(내전 등)이거나 조회하지 못한 경기다.
|
||||
- 시간 순서의 줄. 줄 앞 번호가 근거 번호다.
|
||||
- [e번호] 게임 이벤트 (킬, 스파이크, 오브젝트, 라운드 결과 등)
|
||||
- [u번호] 음성 문장. 디스코드 음성채널에서 자동 음성 인식으로 받아 적은 것이라 글자가 틀릴 수 있다.
|
||||
@@ -28,13 +27,13 @@ user 메시지의 <match> 안에 경기 자료가 온다.
|
||||
<task>
|
||||
1. 경기 흐름을 먼저 파악한다. 어느 라운드·시간대에서 승부가 갈렸는지 찾는다.
|
||||
2. 10명 모두 평가한다: 평점(1.0~10.0, 0.5 단위), 태그 하나, 한 줄 평(40자 안팎).
|
||||
- 평점은 전적 사이트 점수(OP.GG 실제 점수가 있으면 그것, 없으면 기록 점수)에서 출발한다. 여기에 그 점수가 못 보는 것을 더하고 뺀다: 승부처에서 한 일, 역할 수행, 경제, 음성 소통과 콜.
|
||||
- 출발 점수와 2점 넘게 다르게 줄 때는 그 이유가 되는 근거를 그 사람 evidence 에 단다.
|
||||
- 평점은 기록 점수에서 출발한다. 여기에 그 점수가 못 보는 것을 더하고 뺀다: 승부처에서 한 일, 역할 수행, 경제, 음성 소통과 콜.
|
||||
- 기록 점수와 2점 넘게 다르게 줄 때는 그 이유가 되는 근거를 그 사람 evidence 에 단다.
|
||||
3. 팀마다 범인을 한 명씩 고른다. 범인은 아래를 모두 합쳐 종합으로 판단한다. 한 가지만 보지 않는다.
|
||||
- 가장 못한 사람: 자기 역할·포지션 기준으로 플레이가 가장 나빴다.
|
||||
- 가장 발목을 잡은 사람: 팀의 계획·경제·콜을 가장 많이 망쳤다.
|
||||
- 결과의 원인: 진 팀이면 패배에 가장 큰 책임, 이긴 팀이면 이기는 데 가장 방해가 된 사람.
|
||||
- 범인 후보는 그 팀에서 전적 사이트 점수가 낮은 사람부터 본다. 점수가 팀 최하위가 아닌 사람을 범인으로 고르면, 최하위보다 책임이 더 큰 이유(점수가 못 보는 근거)를 reason 에 쓴다.
|
||||
- 범인 후보는 그 팀에서 기록 점수가 낮은 사람부터 본다. 점수가 팀 최하위가 아닌 사람을 범인으로 고르면, 최하위보다 책임이 더 큰 이유(점수가 못 보는 근거)를 reason 에 쓴다.
|
||||
- 범인은 그 팀에서 평점이 가장 낮아야 한다. 동점이면 근거가 더 분명한 사람.
|
||||
4. 범인마다 이유(2~3문장)와 근거 3~4개, 나머지 사람은 근거 0~2개를 단다.
|
||||
5. 경기 전체 한 줄 요약(1~2문장)을 쓴다.
|
||||
|
||||
25
site/server/scripts/presence-e2e.mts
Normal file
@@ -0,0 +1,25 @@
|
||||
// 실제 디스코드: DiscordSource(사이트 서버 코드)로 봇을 음성채널에 넣었다 빼며 상태 메시지가 바뀌는지 본다
|
||||
import { Client, GatewayIntentBits } from 'discord.js';
|
||||
import { DiscordSource } from '../src/discord-source.ts';
|
||||
// 사용: TB=<봇 토큰> GUILD=<서버 아이디> VC=<빈 음성채널 아이디> node --import tsx scripts/presence-e2e.mts
|
||||
const G = process.env.GUILD!, VC = process.env.VC!;
|
||||
const t0 = Date.now();
|
||||
const at = () => `${((Date.now() - t0) / 1000).toFixed(1)}s`;
|
||||
const log = { info: (o: any, m?: string) => console.log(at(), 'LOG', m, JSON.stringify(o)), error: (o: any, m?: string) => console.log(at(), 'ERR', m, o?.message ?? o) };
|
||||
const src = new DiscordSource(log);
|
||||
// 관찰자: 같은 서버의 다른 세션이 디스코드에서 받은 봇 상태 (presence intent 가 있으면)
|
||||
const obs = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMembers] });
|
||||
obs.on('presenceUpdate', (_o, n) => n.userId === src.client.user?.id && console.log(at(), 'OBSERVED', n.status, JSON.stringify(n.activities.map((a) => a.state))));
|
||||
await src.login(process.env.TB!);
|
||||
await new Promise((r) => src.once('ready', r));
|
||||
await obs.login(process.env.TB!).catch((e) => console.log('observer off:', e.message));
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
const send = (ch: string | null) => src.voiceAdapter(G, { server: () => undefined, state: () => undefined }).send({ op: 4, d: { guild_id: G, channel_id: ch, self_mute: true, self_deaf: true } });
|
||||
console.log(at(), 'JOIN'); send(VC);
|
||||
await new Promise((r) => setTimeout(r, 5000));
|
||||
console.log(at(), 'presence now', src.client.user!.presence.status, JSON.stringify(src.client.user!.presence.activities.map((a) => a.state)), 'inVoice', !!src.client.guilds.cache.get(G)!.members.me!.voice.channelId);
|
||||
console.log(at(), 'LEAVE'); send(null);
|
||||
await new Promise((r) => setTimeout(r, 5000));
|
||||
console.log(at(), 'presence now', src.client.user!.presence.status, JSON.stringify(src.client.user!.presence.activities.map((a) => a.state)), 'inVoice', !!src.client.guilds.cache.get(G)!.members.me!.voice.channelId);
|
||||
await obs.destroy().catch(() => undefined);
|
||||
await src.destroy();
|
||||
@@ -95,7 +95,7 @@ export function registerAppAuth(
|
||||
p.result = { state: 'error', error: '디스코드 로그인에 실패했습니다. 다시 시도해 주세요' };
|
||||
return page(reply, 502, '디스코드 로그인 실패', '잠시 뒤 겜녹이 앱에서 다시 시도해 주세요.');
|
||||
}
|
||||
const user: AppUserInfo = { id: u.id, name: u.global_name || u.username, avatar: avatarUrl(u) };
|
||||
const user: AppUserInfo = { id: u.id, name: store.nameOf(u.id, u.global_name || u.username), avatar: avatarUrl(u) };
|
||||
const role = roleOf(u.id);
|
||||
if (!role) {
|
||||
log.info({ user: u.id }, '앱 로그인 거절: 등록되지 않은 아이디');
|
||||
@@ -173,6 +173,30 @@ export function registerAppAuth(
|
||||
};
|
||||
const role = (v: unknown): 'admin' | 'user' | null => (v === 'admin' || v === 'user' ? v : null);
|
||||
|
||||
// 관리자 아이디 (등록된 유저 누구나): 앱의 따라갈 사람 목록에서 관리자를 위에 보여 준다
|
||||
app.get('/app/admins', async (req, reply) => {
|
||||
if (!(await auth(req, reply))) return;
|
||||
const ids = new Set(cfg.superAdmins);
|
||||
for (const u of store.appUsers()) if (u.role === 'admin') ids.add(u.id);
|
||||
return { ids: [...ids] };
|
||||
});
|
||||
|
||||
// 표시 이름 (실명 숨기기): 등록된 유저는 누구나 받아 앱의 녹음 기록 · 멤버 목록에 쓴다. 바꾸기는 최고 관리자만
|
||||
app.get('/app/names', async (req, reply) => {
|
||||
if (!(await auth(req, reply))) return;
|
||||
return { names: store.displayNames() };
|
||||
});
|
||||
app.put<{ Body: { id?: string; name?: string | null } }>('/app/admin/names', async (req, reply) => {
|
||||
const a = await need(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
const id = String(req.body?.id ?? '').trim();
|
||||
const name = String(req.body?.name ?? '').trim().slice(0, 32);
|
||||
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
|
||||
store.setDisplayName(id, name || null);
|
||||
req.log.info({ by: a.id, user: id, set: !!name }, '표시 이름 변경');
|
||||
return { names: store.displayNames() };
|
||||
});
|
||||
|
||||
app.get('/app/admin/users', async (req, reply) => {
|
||||
if (!(await need(req, reply, 'admin'))) return;
|
||||
return { users: rows() };
|
||||
@@ -228,7 +252,7 @@ export function registerAppAuth(
|
||||
return s && r ? { userId: s.userId, role: r } : null;
|
||||
};
|
||||
|
||||
return { completeLogin, verifyToken };
|
||||
return { completeLogin, verifyToken, roleOf };
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
||||
|
||||
@@ -8,20 +8,28 @@ import type { Config } from './config.js';
|
||||
import { registerAppAuth } from './app-auth.js';
|
||||
import { BotBroker, type BotSource } from './bot-broker.js';
|
||||
import { registerCulprit, type ModelCall } from './culprit.js';
|
||||
import type { ToolCaller } from './opgg.js';
|
||||
import type { KnowledgeAuto } from './culprit-prompt.js';
|
||||
import { avatarUrl, DiscordApi } from './discord.js';
|
||||
import { RateLimiter } from './rate-limit.js';
|
||||
import { RelayHub } from './relay.js';
|
||||
import { SiteLog } from './site-log.js';
|
||||
import { ServerStore, type Session } from './store.js';
|
||||
|
||||
const SID = 'gvr_sid';
|
||||
const RECHECK_MS = 10 * 60000;
|
||||
|
||||
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
|
||||
export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; culpritOpgg?: ToolCaller | null } = {}) {
|
||||
export async function buildServer(
|
||||
cfg: Config,
|
||||
opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; logEcho?: boolean } = {},
|
||||
) {
|
||||
// 사이트 로그: 날짜별 파일(data/logs/site-날짜.log)로 남기고 관리자가 사이트에서 본다. 게임 PC 가 꺼져 있어도 볼 수 있다
|
||||
const siteLog = new SiteLog(path.join(cfg.dataDir, 'logs'), { echo: opts.logEcho ?? true });
|
||||
const app = Fastify({
|
||||
// 요청 기록은 아래 onResponse 에서 한 줄로 남긴다 (pino 기본 요청 로그는 두 줄 + 상태 확인 폴링으로 너무 많음)
|
||||
disableRequestLogging: true,
|
||||
logger: {
|
||||
stream: siteLog,
|
||||
level: process.env.LOG_LEVEL || 'info',
|
||||
// 로그에 비밀값을 남기지 않는다: 로그인 주소의 code · state, 앱 로그인 요청 아이디, 기록 검색어(쿼리)는 지운다
|
||||
serializers: { req: (req) => ({ method: req.method, url: safeLogUrl(req.url), remoteAddress: req.ip }) },
|
||||
@@ -32,12 +40,13 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
});
|
||||
const store = new ServerStore(cfg.dataDir);
|
||||
const hub = new RelayHub(store);
|
||||
hub.log = app.log.child({ area: 'relay' });
|
||||
const discord = new DiscordApi(cfg);
|
||||
await app.register(cookie, { secret: cfg.sessionSecret });
|
||||
const secure = cfg.publicUrl.startsWith('https://');
|
||||
let broker: BotBroker | null = null;
|
||||
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
|
||||
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log, opts.botRecheckMs);
|
||||
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log.child({ area: 'bot' }), opts.botRecheckMs);
|
||||
|
||||
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
|
||||
// CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게)
|
||||
@@ -99,9 +108,54 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
reply.code(401).send({ error: 'unauthorized' });
|
||||
return null;
|
||||
}
|
||||
(req as any).gvrUser = s.user.id;
|
||||
return s;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ 사이트 로그
|
||||
// 요청 한 줄 기록: 기록 API · 로그인 · 앱 요청은 모두, 화면 파일은 실패만. 자주 부르는 상태 확인 · 음성 파일은 실패만 남긴다
|
||||
app.addHook('onResponse', async (req, reply) => {
|
||||
const url = safeLogUrl(req.url);
|
||||
const st = reply.statusCode;
|
||||
const p = url.split('?')[0];
|
||||
const api = /^\/(api|auth|app|admin|device|site)\//.test(p);
|
||||
if (st < 400 && (!api || p === '/api/status' || p.startsWith('/api/audio/') || p.startsWith('/site/logs') || p === '/site/client-log')) return;
|
||||
const o = { area: 'http', status: st, ms: Math.round(reply.elapsedTime), ...((req as any).gvrUser ? { user: (req as any).gvrUser } : {}) };
|
||||
if (st >= 500 && st !== 503) req.log.error(o, `${req.method} ${url}`);
|
||||
else if (st >= 400 && st !== 401) req.log.warn(o, `${req.method} ${url}`);
|
||||
else req.log.info(o, `${req.method} ${url}`);
|
||||
});
|
||||
const canViewLogs = (userId: string) => cfg.owners.includes(userId) || ['admin', 'superadmin'].includes(appAuth.roleOf(userId) ?? '');
|
||||
app.get('/site/logs', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
if (!canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '사이트 로그는 관리자만 볼 수 있습니다' });
|
||||
return { days: siteLog.days(), now: Date.now() };
|
||||
});
|
||||
app.get<{ Params: { date: string }; Querystring: { download?: string } }>('/site/logs/:date', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
if (!canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '사이트 로그는 관리자만 볼 수 있습니다' });
|
||||
const text = siteLog.read(req.params.date);
|
||||
if (text === null) return reply.code(404).send({ error: 'not_found' });
|
||||
reply.header('cache-control', 'no-store').type('text/plain; charset=utf-8');
|
||||
if (req.query.download) reply.header('content-disposition', `attachment; filename="gvr-site-${req.params.date}.log"`);
|
||||
return text;
|
||||
});
|
||||
// 브라우저 오류(화면 오류 · 처리 안 된 오류 · 요청 실패)를 사이트 로그에 남긴다. 로그인한 사람만, 1분에 30개까지
|
||||
const clientLogLimit = new RateLimiter(30, 60000);
|
||||
app.post<{ Body: { level?: string; message?: string; detail?: string; page?: string } }>('/site/client-log', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
if (!clientLogLimit.hit(s.user.id)) return reply.code(429).send({ error: 'rate_limited' });
|
||||
const b = req.body ?? {};
|
||||
const cut = (v: unknown, n: number) => String(v ?? '').slice(0, n);
|
||||
const o = { area: 'web', user: s.user.id, page: cut(b.page, 200), ...(b.detail ? { detail: cut(b.detail, 2000) } : {}), ua: cut(req.headers['user-agent'], 160) };
|
||||
if (b.level === 'error') req.log.error(o, cut(b.message, 500));
|
||||
else req.log.warn(o, cut(b.message, 500));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 로그인
|
||||
app.get('/auth/discord', async (req, reply) => {
|
||||
const state = crypto.randomBytes(16).toString('base64url');
|
||||
@@ -149,7 +203,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
app.get('/auth/me', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
return { user: s.user, isOwner: cfg.owners.includes(s.user.id) };
|
||||
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id) };
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 상태 · 관리
|
||||
@@ -178,7 +232,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 범인찾기 (Claude API 는 이 서버만 부른다)
|
||||
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log, call: opts.culpritCall, knowledge: opts.culpritKnowledge, opgg: opts.culpritOpgg });
|
||||
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log.child({ area: 'culprit' }), call: opts.culpritCall, knowledge: opts.culpritKnowledge });
|
||||
|
||||
// ------------------------------------------------------------------ 기록 API 중계
|
||||
const relay = async (req: FastifyRequest, reply: FastifyReply) => {
|
||||
@@ -227,7 +281,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
if (fs.existsSync(cfg.webDir)) {
|
||||
await app.register(fastifyStatic, { root: cfg.webDir, wildcard: false, index: ['index.html'] });
|
||||
app.setNotFoundHandler((req, reply) => {
|
||||
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/app/') && !req.url.startsWith('/game-assets/'))
|
||||
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/app/') && !req.url.startsWith('/site/') && !req.url.startsWith('/game-assets/'))
|
||||
return reply.type('text/html').send(fs.readFileSync(path.join(cfg.webDir, 'index.html')));
|
||||
return reply.code(404).send({ error: 'not_found' });
|
||||
});
|
||||
@@ -285,9 +339,10 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
|
||||
});
|
||||
app.addHook('onClose', async () => {
|
||||
store.flush();
|
||||
siteLog.close();
|
||||
});
|
||||
|
||||
return { app, store, hub, broker, culprit };
|
||||
return { app, store, hub, broker, culprit, siteLog };
|
||||
}
|
||||
|
||||
/** 로그에 남길 주소: /auth/* 는 쿼리를 지우고 앱 로그인 요청 아이디를 가린다, 다른 주소도 쿼리 값은 지운다 */
|
||||
|
||||
@@ -268,7 +268,8 @@ export class BotBroker {
|
||||
return;
|
||||
}
|
||||
case 'req': {
|
||||
if (m.op !== 'members' || m.guildId !== c.guildId) return this.send(c, { t: 'res', id: m.id, ok: false, error: 'forbidden' });
|
||||
// 지켜보기 전이어도 받을 수 있다 (가입한 서버인지는 source.members 가 확인한다)
|
||||
if (m.op !== 'members' || !SNOWFLAKE.test(String(m.guildId))) return this.send(c, { t: 'res', id: m.id, ok: false, error: 'forbidden' });
|
||||
this.source.members(m.guildId, c.userId).then(
|
||||
(data) => this.send(c, { t: 'res', id: m.id, ok: true, data }),
|
||||
(e) => this.send(c, { t: 'res', id: m.id, ok: false, error: String(e?.message ?? e) }),
|
||||
@@ -301,7 +302,14 @@ export class BotBroker {
|
||||
/** 슬래시 명령을 맞는 앱으로 보내고 첫 응답을 돌려준다 */
|
||||
private async onCommand(cmd: BotCommand): Promise<string> {
|
||||
const here = [...this.conns].filter((c) => c.guildId === cmd.guildId).sort((a, b) => b.at - a.at);
|
||||
if (!here.length) return '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.';
|
||||
if (!here.length) {
|
||||
// 명령한 사람의 앱이 켜져 있는데 다른 서버를 녹음 대상으로 잡아 둔 경우를 알려 준다
|
||||
const own = [...this.conns].filter((c) => c.userId === cmd.user.id);
|
||||
this.log.info({ guild: cmd.guildId, user: cmd.user.id, cmd: cmd.name, apps: this.conns.size, own: own.map((c) => c.guildId) }, '슬래시 명령: 이 서버를 지켜보는 앱 없음');
|
||||
if (own.some((c) => c.guildId)) return '내 겜녹이 앱이 다른 디스코드 서버를 녹음 대상으로 정해 두었습니다. 게임 PC 의 겜녹이 설정 → 디스코드 → "녹음할 서버"를 이 서버로 바꿔 주세요.';
|
||||
if (own.length) return '내 겜녹이 앱이 이 서버에 아직 연결되지 않았습니다. 잠시 뒤 다시 시도하거나, 겜녹이 설정 → 디스코드에서 "녹음할 서버"를 확인해 주세요.';
|
||||
return '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다. 게임 PC 에서 겜녹이를 켜고 로그인해 주세요.';
|
||||
}
|
||||
const owner = this.owners.get(cmd.guildId)?.conn;
|
||||
const mine = here.find((c) => c.userId === cmd.user.id);
|
||||
let targets: Conn[];
|
||||
|
||||
@@ -12,8 +12,12 @@ if (cmd === 'code') {
|
||||
console.log(JSON.stringify(store.device(), (k, v) => (k === 'keyHash' ? undefined : v), 2));
|
||||
} else if (cmd === 'unregister') {
|
||||
console.log(`등록 해제: ${store.removeDevices()}대 (서버를 다시 시작하면 연결도 끊긴다)`);
|
||||
} else if (cmd === 'name' && /^\d{17,20}$/.test(process.argv[3] ?? '')) {
|
||||
// 표시 이름 (실명 숨기기). 서버가 떠 있으면 서버가 덮어쓸 수 있으니 컨테이너를 멈춘 상태에서 쓴다 (평소에는 앱 관리자 탭)
|
||||
store.setDisplayName(process.argv[3]!, process.argv.slice(4).join(' ').trim() || null);
|
||||
console.log(JSON.stringify(store.displayNames()));
|
||||
} else {
|
||||
console.log('사용법: node dist/cli.js code [분] | device | unregister');
|
||||
console.log('사용법: node dist/cli.js code [분] | device | unregister | name <디스코드 아이디> [표시 이름]');
|
||||
}
|
||||
store.flush();
|
||||
|
||||
|
||||
@@ -28,8 +28,6 @@ export interface Config {
|
||||
monthLimitUsd: number;
|
||||
dailyLimit: number;
|
||||
tone: 'mild' | 'medium' | 'spicy';
|
||||
/** 분석할 때 OP.GG 실제 OP스코어를 찾을지 (기본 켬, CULPRIT_OPGG=0 이면 끔) */
|
||||
opgg?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -74,7 +72,6 @@ export function loadConfig(env = process.env): Config {
|
||||
monthLimitUsd: Number(env.CULPRIT_MONTH_LIMIT_USD || 100),
|
||||
dailyLimit: Number(env.CULPRIT_DAILY_LIMIT || 20),
|
||||
tone: (env.CULPRIT_TONE as any) || 'medium',
|
||||
opgg: env.CULPRIT_OPGG !== '0',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||