범인찾기 C1: 경기 지표 보강, 분석 가능 판정, AI 자료 만들기, 결과 저장 + 녹음 안내에 AI 분석 문구

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 14:20:52 +09:00
parent b22e55cc64
commit de64f9818d
13 changed files with 974 additions and 13 deletions

View File

@@ -1,7 +1,8 @@
import Fastify, { type FastifyInstance } from 'fastify';
import fs from 'node:fs';
import path from 'node:path';
import type { MatchDetail, MatchPlayer, Overview, User, UserProfile, Word } from '@gvr/shared';
import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, 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';
import type { GameManager } from '../games/manager.js';
@@ -14,6 +15,7 @@ export interface ApiDeps {
timeline: Timeline;
games: GameManager;
dict: Dictionary;
culprit: Culprit;
bus: Bus;
settings: () => Settings;
trainingDir: () => string;
@@ -166,6 +168,7 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
items: p.items,
rank: p.rank ?? null,
userId: p.puuid ? userOf(p.puuid) : undefined,
stats: p.stats,
}));
const evRows = store.events(m.id);
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? ORDER BY started_at').all(m.id) as any[];
@@ -251,6 +254,47 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
).map(([key, count]) => ({ key, label: d.dict.labels[key] ?? key, count })),
}));
// ---------------------------------------------------------------- 범인찾기 (계획서 v1.1)
// /api/culprit/matches* : 사이트(브라우저)가 보는 목록 · 상세
// /api/culprit/internal/* : 사이트 서버만 부른다 (AI 자료 만들기 · 결과 저장). 서버가 붙이는 x-gvr-internal 헤더가 있어야 하고,
// 서버 중계는 브라우저 요청의 이 헤더를 넘기지 않는다 (relay 가 range · content-type · accept 만 넘김)
const internalOnly = (req: { headers: Record<string, unknown> }) => req.headers['x-gvr-internal'] === '1';
app.get<{ Querystring: Record<string, string> }>('/api/culprit/matches', async (req) => {
const q = req.query;
return d.culprit.list({ game: q.game === 'valorant' || q.game === 'lol' ? q.game : undefined, limit: q.limit ? Number(q.limit) : 50 });
});
app.get<{ Params: { id: string } }>('/api/culprit/matches/:id', async (req, reply) => {
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
return d.culprit.info(m);
});
app.get<{ Params: { id: string } }>('/api/culprit/internal/:id/input', async (req, reply) => {
if (!internalOnly(req)) return reply.code(403).send({ error: 'forbidden' });
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
const eligibility = d.culprit.eligibility(m);
if (eligibility.state !== 'ready' && eligibility.state !== 'done') return reply.code(409).send({ error: 'not_ready', eligibility });
return { eligibility, input: d.culprit.buildInput(m) };
});
app.put<{ Params: { id: string }; Body: Partial<CulpritAnalysis> & { result?: CulpritResult } }>('/api/culprit/internal/:id/result', async (req, reply) => {
if (!internalOnly(req)) return reply.code(403).send({ error: 'forbidden' });
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
const b = req.body || {};
if (!b.result || !Array.isArray(b.result.players) || !Array.isArray(b.result.teams) || !b.model || !b.createdBy) return reply.code(400).send({ error: 'bad_result' });
const saved = d.culprit.save(m.id, {
createdAt: Date.now(),
createdBy: { id: String(b.createdBy.id), name: String(b.createdBy.name) },
model: String(b.model),
result: b.result,
players: b.players || [],
meta: b.meta || {},
});
d.games.emitMatch(m.id);
return saved;
});
return app;
}

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

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

View File

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

View File

@@ -530,6 +530,20 @@ export function processLolHistory(game: any, timeline: any, host: Pick<AdapterHo
const it = host.assets.item(x);
return { id: x, name: it.name, icon: it.icon };
}),
stats: {
role: lolPosition(p) ?? undefined,
damage: st.totalDamageDealtToChampions,
damageTaken: st.totalDamageTaken,
vision: st.visionScore,
wardsPlaced: st.wardsPlaced,
wardsKilled: st.wardsKilled,
controlWards: st.visionWardsBoughtInGame,
objectiveDamage: st.damageDealtToObjectives,
turretDamage: st.damageDealtToTurrets,
ccSeconds: st.timeCCingOthers,
at10: frameAt(timeline, p.participantId, 10),
at15: frameAt(timeline, p.participantId, 15),
},
};
});
const events: EventRow[] = [];
@@ -602,6 +616,25 @@ export function processLolHistory(game: any, timeline: any, host: Pick<AdapterHo
};
}
/** LCU 경기 기록의 라인 · 역할 → 포지션 (사용자 지정 게임은 틀릴 수 있어 "추정") */
export function lolPosition(p: any): string | null {
const lane = String(p.timeline?.lane || '').toUpperCase();
const role = String(p.timeline?.role || '').toUpperCase();
if (p.spell1Id === 11 || p.spell2Id === 11 || lane === 'JUNGLE') return '정글';
if (lane === 'TOP') return '탑';
if (lane === 'MIDDLE' || lane === 'MID') return '미드';
if (lane === 'BOTTOM' || lane === 'BOT') return role === 'DUO_SUPPORT' || role === 'SUPPORT' ? '서폿' : role === 'DUO_CARRY' || role === 'CARRY' ? '원딜' : '바텀';
return null;
}
/** 타임라인의 N분 프레임에서 그 선수 CS · 골드 · 경험치 */
function frameAt(timeline: any, pid: number, minute: number): { cs: number; gold: number; xp: number } | undefined {
const f = (timeline?.frames || []).find((x: any) => Math.round((x.timestamp ?? 0) / 60000) === minute);
const pf = f?.participantFrames?.[String(pid)] ?? f?.participantFrames?.[pid];
if (!pf) return undefined;
return { cs: (pf.minionsKilled ?? 0) + (pf.jungleMinionsKilled ?? 0), gold: pf.totalGold ?? 0, xp: pf.xp ?? 0 };
}
function prettyUnit(name: string): string {
if (/^Turret_/.test(name)) return '포탑';
if (/Minion/.test(name)) return '미니언';

View File

@@ -1,4 +1,4 @@
import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound } from '@gvr/shared';
import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound, PlayerStats } from '@gvr/shared';
import type { EventRow, RoundRow } from '../db/db.js';
import { logger } from '../util/log.js';
import type { GameAssets } from './assets.js';
@@ -380,6 +380,17 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
}
combat[i] = prev !== null ? prev + avg : next !== null ? next : BUY_MS + i * avg;
}
// 범인찾기용 선수별 누적 지표
const tallies: Record<string, { damage: number; head: number; shots: number; firstKills: number; firstDeaths: number; plants: number; defuses: number }> = {};
const tally = (puuid: string) => (tallies[puuid] ||= { damage: 0, head: 0, shots: 0, firstKills: 0, firstDeaths: 0, plants: 0, defuses: 0 });
// 공격 팀: 전반 12라운드는 Red, 후반은 Blue, 연장은 매 라운드 바뀜. 스파이크를 설치한 팀이 공격이므로 설치 기록이 반대면 뒤집는다
const ruleAttacker = (i: number) => (i < 12 ? 'Red' : i < 24 ? 'Blue' : i % 2 === 0 ? 'Red' : 'Blue');
let agree = 0;
for (let i = 0; i < n; i++) {
const planter = rr[i].bombPlanter ? players[rr[i].bombPlanter]?.teamId : null;
if (planter) agree += planter === ruleAttacker(i) ? 1 : -1;
}
const attackerTeam = (i: number) => (agree >= 0 ? ruleAttacker(i) : ruleAttacker(i) === 'Red' ? 'Blue' : 'Red');
const rounds: RoundRow[] = [];
const roundsDetail: MatchRound[] = [];
const events: EventRow[] = [];
@@ -394,15 +405,27 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
const win = r.winningTeam === selfTeam;
if (win) ally++;
else enemy++;
const economy: Record<string, { spent: number; remaining: number; weapon?: string }> = {};
const economy: Record<string, { spent: number; remaining: number; weapon?: string; loadout?: number }> = {};
const roundPlayers: Record<string, { kills: number; damage: number }> = {};
for (const ps of r.playerStats || []) {
if (ps.economy)
economy[ps.subject] = {
spent: ps.economy.spent ?? 0,
remaining: ps.economy.remaining ?? 0,
weapon: ps.economy.weapon ? assets.damageItem(null, 'Weapon', ps.economy.weapon)?.name : undefined,
loadout: typeof ps.economy.loadoutValue === 'number' ? ps.economy.loadoutValue : undefined,
};
const dmg = (ps.damage || []).reduce((n: number, d: any) => n + (d.damage ?? 0), 0);
roundPlayers[ps.subject] = { kills: (ps.kills || []).length, damage: dmg };
const t = tally(ps.subject);
t.damage += dmg;
for (const d of ps.damage || []) {
t.head += d.headshots ?? 0;
t.shots += (d.headshots ?? 0) + (d.bodyshots ?? 0) + (d.legshots ?? 0);
}
}
if (r.bombPlanter) tally(r.bombPlanter).plants++;
if (r.bombDefuser) tally(r.bombDefuser).defuses++;
rounds.push({
match_id: id,
num,
@@ -415,10 +438,24 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
enemy_score: enemy,
economy: JSON.stringify(economy),
});
roundsDetail.push({ num, startedAt: S + start + clockOffset, endedAt: S + end + clockOffset, win, result: roundResultKo(r.roundResult), score: { ally, enemy }, economy });
roundsDetail.push({
num,
startedAt: S + start + clockOffset,
endedAt: S + end + clockOffset,
win,
result: roundResultKo(r.roundResult),
score: { ally, enemy },
economy,
allyAttack: attackerTeam(i) === selfTeam,
players: roundPlayers,
});
// 킬
const killsBy: Record<string, number> = {};
const kills = (r.playerStats || []).flatMap((ps: any) => ps.kills || []).sort((x: any, y: any) => x.gameTime - y.gameTime);
if (kills[0]) {
if (kills[0].killer) tally(kills[0].killer).firstKills++;
if (kills[0].victim) tally(kills[0].victim).firstDeaths++;
}
for (const k of kills) {
const killer = ref(k.killer);
const victim = ref(k.victim)!;
@@ -516,6 +553,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
assists: p.stats?.assists ?? 0,
score: p.stats?.score ?? 0, // 총 전투 점수 (사이트가 라운드 수로 나눠 ACS 표시)
rank: assets.val?.tiers[p.competitiveTier] ?? null,
stats: playerStats(p, tallies[p.subject], assets),
}));
const selfTeamInfo = (md.teams || []).find((t: any) => t.teamId === selfTeam);
const enemyTeamInfo = (md.teams || []).find((t: any) => t.teamId !== selfTeam);
@@ -535,6 +573,21 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
};
}
function playerStats(p: any, t: { damage: number; head: number; shots: number; firstKills: number; firstDeaths: number; plants: number; defuses: number } | undefined, assets: GameAssets): PlayerStats {
const ac = p.stats?.abilityCasts;
return {
role: assets.agentRole(p.characterId) ?? undefined,
rounds: p.stats?.roundsPlayed ?? undefined,
damage: t?.damage ?? 0,
headshotPct: t && t.shots ? Math.round((t.head / t.shots) * 100) : undefined,
firstKills: t?.firstKills ?? 0,
firstDeaths: t?.firstDeaths ?? 0,
plants: t?.plants ?? 0,
defuses: t?.defuses ?? 0,
abilityCasts: ac ? (ac.grenadeCasts ?? 0) + (ac.ability1Casts ?? 0) + (ac.ability2Casts ?? 0) + (ac.ultimateCasts ?? 0) : undefined,
};
}
export function roundResultKo(r: string | undefined): string {
switch (r) {
case 'Eliminated':

View File

@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import type { FastifyInstance } from 'fastify';
import { buildApi } from './api/server.js';
import { Culprit } from './culprit.js';
import { Store } from './db/db.js';
import { Dictionary } from './dict/dictionary.js';
import { Bot } from './discord/bot.js';
@@ -79,11 +80,13 @@ export async function startCore(opts: CoreOptions) {
if (!S().discord.guildId) settings.update({ discord: { guildId: gid } });
});
const culprit = new Culprit(store, timeline, games);
const api: FastifyInstance = await buildApi({
store,
timeline,
games,
dict,
culprit,
bus,
settings: S,
trainingDir: () => paths().training,

View File

@@ -131,7 +131,7 @@ export class RelayClient {
}
try {
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = req.headers[k];
for (const k of ['range', 'content-type', 'accept', 'x-gvr-internal']) if (req.headers[k]) headers[k] = req.headers[k];
if (req.user) headers['x-gvr-user'] = encodeURIComponent(JSON.stringify(req.user));
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: req.body ?? undefined });
const outHeaders: Record<string, string> = {};

View File

@@ -78,7 +78,9 @@ export interface Secrets {
}
export const DEFAULT_TTS_TEXT =
'겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.';
'겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.';
/** v1.2.2 까지의 기본 문구. 이 문구를 그대로 쓰던 설치는 새 기본 문구(AI 분석 안내 포함)로 바꾼다 */
const OLD_DEFAULT_TTS_TEXTS = ['겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.'];
export function defaultSettings(): Settings {
return {
@@ -178,6 +180,8 @@ export class SettingsStore {
}
// v1.0.0 에서 직접 토큰을 넣어 쓰던 설치는 그 봇을 계속 쓴다
if (saved && !saved.discord?.botMode && this.secrets.botToken) this.cur.discord.botMode = 'custom';
// 범인찾기(AI 분석) 안내: 기본 문구를 바꾸지 않고 쓰던 설치는 새 기본 문구로 (직접 고친 문구는 그대로)
if (OLD_DEFAULT_TTS_TEXTS.includes(this.cur.discord.ttsText)) this.cur.discord.ttsText = DEFAULT_TTS_TEXT;
// 개발/헤드리스: 환경변수 토큰이 있으면 모드와 상관없이 그것을 쓴다
this.envBotToken = process.env.GVR_BOT_TOKEN || null;
// v1.2.0 은 서버에서 받은 겜녹이 봇 토큰을 저장해 두었다. 이제는 서버가 봇을 대신 연결하므로 남기지 않는다

View File

@@ -21,7 +21,7 @@ function defaults(): Settings {
followEnabled: true,
commandsEnabled: true,
ttsEnabled: true,
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
},