WIP v1.3.7: 기록 묶음(경기 · 경기 전후 대화) 관리 · zip 내보내기/받아오기

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-16 05:21:32 +09:00
parent 98b8342678
commit c397bacf8c
23 changed files with 1376 additions and 17 deletions

View File

@@ -17,6 +17,7 @@ import { MatchPage } from './pages/MatchPage';
import { CulpritPage } from './pages/CulpritPage';
import { MatchesPage, UserPage, UsersPage } from './pages/UserPages';
import { LogsPage } from './pages/LogsPage';
import { RecordsPage } from './pages/RecordsPage';
import { installErrorReporting } from './lib/report';
import { useLocation } from 'react-router';
@@ -67,6 +68,7 @@ function Shell() {
<Routes>
<Route path="/" element={<TimelinePage />} />
<Route path="/matches" element={<MatchesPage />} />
<Route path="/records" element={<RecordsPage />} />
<Route path="/matches/:id" element={<MatchPage />} />
<Route path="/users" element={<UsersPage />} />
<Route path="/users/:id" element={<UserPage />} />

View File

@@ -174,6 +174,7 @@ export function Header() {
const nav = [
['/', '타임라인'],
['/matches', '경기'],
['/records', '기록'],
['/users', '유저'],
['/dictionary', '단어사전'],
['/culprit', '🔍 범인찾기'],

View File

@@ -12,6 +12,8 @@ import type {
UtteranceItem,
UtteranceInfo,
GameType,
BundleInfo,
BundleImportResult,
} from '@gvr/shared';
import { reportClient } from './report';
@@ -159,6 +161,23 @@ export const api = {
if (res.status === 503 && b.error === 'device_offline') emit('device_offline');
return { ok: false, status: res.status, error: b.error ?? 'error', message: b.message ?? '분석을 시작하지 못했습니다' };
},
/** 기록 묶음 (v1.3.7~ 앱) */
bundles: () => request<{ bundles: BundleInfo[] }>('/api/bundles').then((r) => r.bundles),
deleteBundles: (ids: string[]) => request<{ bundles: number; utterances: number; files: number }>('/api/bundles/delete', { method: 'POST', body: JSON.stringify({ ids }) }),
bundleExportUrl: (ids: string[]) => `/api/bundles/export?ids=${ids.map(encodeURIComponent).join(',')}`,
/** zip 받아오기. 실패하면 서버가 준 이유("받아오기 실패: …")를 담은 Error */
importBundle: async (file: Blob): Promise<BundleImportResult> => {
let res: Response;
try {
res = await fetch('/api/bundles/import', { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/zip', accept: 'application/json' }, body: file });
} catch {
throw new Error('받아오기 실패: 네트워크 오류');
}
const b = await res.json().catch(() => ({}));
if (res.ok) return b as BundleImportResult;
if (res.status === 503) emit('device_offline');
throw new Error(b.message ?? (res.status === 413 ? '받아오기 실패: zip 이 너무 큽니다 (300MB 까지)' : `받아오기 실패 (${res.status} ${b.error ?? ''})`));
},
utteranceInfo: (id: string) => request<UtteranceInfo>(`/api/utterances/${encodeURIComponent(id)}/info`),
correct: (id: string, text: string) =>
request<UtteranceItem>(`/api/utterances/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ text }) }),

View File

@@ -15,6 +15,11 @@ export function fmtWhen(ts: number): string {
return `${md} ${hm}`;
}
/** 날짜만: "오늘" · "어제" · "10월 7일" (fmtWhen 에서 시각을 뺀 것) */
export function fmtDay(ts: number): string {
return fmtWhen(ts).replace(/\s\d{2}:\d{2}$/, '');
}
export function fmtHM(ts: number): string {
return new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, hour: '2-digit', minute: '2-digit', hour12: false }).format(ts);
}
@@ -54,7 +59,7 @@ export function fmtSec(sec: number): string {
}
export function realTip(ts: number) {
return `현실 시간 ${fmtWhen(ts).split(' ')[0]} ${fmtReal(ts)}`;
return `현실 시간 ${fmtDay(ts)} ${fmtReal(ts)}`;
}
/** "YYYY-MM-DD" (KST) ↔ ms */

View File

@@ -0,0 +1,263 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
import type { BundleInfo, BundleImportResult } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { fmtDuration, fmtHM, fmtWhen, fmtDay } from '../lib/format';
import { sfx } from '../lib/sfx';
import { useAuth, useData, useLive, useStatus } from '../store/app';
import { Avatar, ErrorBox, Spinner } from '../components/common';
import { IDownload } from '../components/Icons';
/**
* 기록 관리 (v1.3.7): 경기 하나 · 경기 전 대화 · 경기 후 대화 · 게임 밖 대화를 묶음으로 보고,
* 묶음 단위로 기록 보기 · zip 내려받기 · 지우기(관리자) · zip 받아오기(관리자)를 한다.
*/
const fmtMB = (b: number) => (b >= 1024 * 1024 ? `${(b / 1024 / 1024).toFixed(1)}MB` : `${Math.max(1, Math.round(b / 1024))}KB`);
const MAX_ZIP = 300 * 1024 * 1024;
export function RecordsPage() {
const { epoch } = useStatus();
const { auth } = useAuth();
const admin = auth.status === 'ok' && !!auth.me.canViewLogs;
const nav = useNavigate();
const [list, setList] = useState<BundleInfo[] | null>(null);
const [err, setErr] = useState<unknown>(null);
const [old, setOld] = useState(false);
const [sel, setSel] = useState<Set<string>>(new Set());
const [confirm, setConfirm] = useState<BundleInfo[] | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [kind, setKind] = useState<'all' | 'match' | 'talk'>('all');
const file = useRef<HTMLInputElement>(null);
const load = useCallback(() => {
setErr(null);
api
.bundles()
.then((b) => {
setList(b);
setSel((s) => new Set([...s].filter((id) => b.some((x) => x.id === id))));
})
.catch((e) => {
if (e instanceof ApiError && e.status === 404) setOld(true);
else setErr(e);
});
}, []);
useEffect(load, [load, epoch]);
useLive((e) => {
if (e.type === 'records.changed') load();
});
const shown = useMemo(() => (list ?? []).filter((b) => kind === 'all' || b.kind === kind), [list, kind]);
const days = useMemo(() => {
const g = new Map<string, BundleInfo[]>();
for (const b of shown) {
const d = fmtDay(b.from);
g.set(d, [...(g.get(d) ?? []), b]);
}
return [...g];
}, [shown]);
const picked = (list ?? []).filter((b) => sel.has(b.id));
const toggle = (id: string) => setSel((s) => (s.has(id) ? new Set([...s].filter((x) => x !== id)) : new Set([...s, id])));
const download = (ids: string[]) => {
sfx('click');
const a = document.createElement('a');
a.href = api.bundleExportUrl(ids);
a.download = '';
document.body.appendChild(a);
a.click();
a.remove();
setMsg({ ok: true, text: `zip 을 만드는 중입니다. 묶음이 크면 내려받기가 시작될 때까지 조금 걸립니다.` });
};
const doDelete = async (bs: BundleInfo[]) => {
setBusy('delete');
try {
const r = await api.deleteBundles(bs.map((b) => b.id));
setMsg({ ok: true, text: `묶음 ${r.bundles}개를 지웠습니다 (발화 ${r.utterances}개, 음성 파일 ${r.files}개)` });
setSel(new Set());
setConfirm(null);
load();
} catch (e) {
setMsg({ ok: false, text: e instanceof ApiError && e.status === 403 ? '지우기는 관리자만 할 수 있습니다' : '지우지 못했습니다' });
} finally {
setBusy(null);
}
};
const doImport = async (f: File) => {
if (f.size > MAX_ZIP) return setMsg({ ok: false, text: '받아오기 실패: zip 이 너무 큽니다 (300MB 까지)' });
setBusy('import');
setMsg(null);
try {
const r: BundleImportResult = await api.importBundle(f);
setMsg({
ok: true,
text: `받아오기 완료: ${r.bundles.join(', ')} · 발화 ${r.added.utterances}개 추가 (음성 ${r.added.audio}개${r.added.matches ? `, 경기 ${r.added.matches}개` : ''})${r.skipped ? ` · 이미 있는 발화 ${r.skipped}개는 건너뜀` : ''}`,
});
load();
} catch (e) {
setMsg({ ok: false, text: (e as Error).message });
} finally {
setBusy(null);
if (file.current) file.current.value = '';
}
};
const view = (b: BundleInfo) => {
sfx('click');
if (b.kind === 'match' && b.matchId) nav(`/?match=${encodeURIComponent(b.matchId)}`);
else nav(`/?game=none&from=${b.from}&to=${b.to}&order=asc`);
};
if (old)
return (
<main className="page-pad">
<h2 className="page-h h">기록 관리</h2>
<div className="empty">게임 PC 의 겜녹이가 예전 버전입니다. v1.3.7 이상으로 업데이트하면 경기별로 묶어 보고 지우기 · zip 내려받기 · 받아오기를 할 수 있습니다.</div>
</main>
);
return (
<main className="page-pad records">
<div className="page-h-row">
<h2 className="page-h h">기록 관리</h2>
<div className="chips-wrap">
{(
[
['all', '전체'],
['match', '경기'],
['talk', '경기 밖 대화'],
] as const
).map(([k, l]) => (
<button key={k} className={`chip${kind === k ? ' on' : ''}`} onClick={() => setKind(k)}>
{l}
</button>
))}
</div>
<div className="rec-actions">
{admin && (
<>
<input ref={file} type="file" accept=".zip,application/zip" hidden onChange={(e) => e.target.files?.[0] && void doImport(e.target.files[0])} />
<button className="chip" disabled={busy === 'import'} onClick={() => file.current?.click()} title="내려받아 둔 기록 zip 을 다시 넣습니다">
⬆ {busy === 'import' ? '받아오는 중…' : '받아오기 (zip)'}
</button>
</>
)}
</div>
</div>
<p className="rec-help dim">
경기 하나가 묶음 하나입니다. 경기 밖 대화는 다음 경기 30분 전 안이면 "경기 전 대화", 지난 경기 30분 안이면 "경기 후 대화"로 묶습니다. 묶음을 골라 한 번에 zip 으로 내려받거나{admin ? ' 지울 수 있고, 받아 둔 zip 은 "받아오기"로 다시 넣을 수 있습니다' : ' 할 수 있습니다 (지우기 · 받아오기는 관리자만)'}.
</p>
{msg && <div className={`rec-msg ${msg.ok ? 'ok' : 'bad'}`}>{msg.text}</div>}
{picked.length > 0 && (
<div className="rec-selbar">
<b>{picked.length}개 선택</b>
<span className="dim">
발화 {picked.reduce((n, b) => n + b.utterances, 0)}개 · 음성 {fmtMB(picked.reduce((n, b) => n + b.audioBytes, 0))}
</span>
<button className="chip on" onClick={() => download(picked.map((b) => b.id))}>
<IDownload width={14} height={14} /> 한 번에 zip
</button>
{admin && (
<button className="chip danger" onClick={() => setConfirm(picked)}>
🗑 한 번에 지우기
</button>
)}
<button className="link-btn" onClick={() => setSel(new Set())}>
선택 해제
</button>
</div>
)}
{err != null && <ErrorBox error={err} onRetry={load} />}
{!list && !err && <Spinner />}
{list && !shown.length && <div className="empty">기록이 없습니다.</div>}
{days.map(([day, bs]) => (
<section key={day} className="rec-day">
<h4>
<label>
<input
type="checkbox"
checked={bs.every((b) => sel.has(b.id))}
onChange={(e) => setSel((s) => (e.target.checked ? new Set([...s, ...bs.map((b) => b.id)]) : new Set([...s].filter((id) => !bs.some((b) => b.id === id)))))}
/>{' '}
{day}
</label>
</h4>
{bs.map((b) => (
<BundleRow key={b.id} b={b} on={sel.has(b.id)} admin={admin} onToggle={() => toggle(b.id)} onView={() => view(b)} onZip={() => download([b.id])} onDelete={() => setConfirm([b])} />
))}
</section>
))}
{confirm && (
<div className="ctx-dim" onPointerDown={() => busy !== 'delete' && setConfirm(null)}>
<div className="ctx-dialog" role="alertdialog" aria-label="기록 지우기" onPointerDown={(e) => e.stopPropagation()}>
<div className="ctx-head">
<b>기록 {confirm.length}묶음을 지울까요?</b>
</div>
<ul className="rec-del-list">
{confirm.map((b) => (
<li key={b.id}>
{b.label} · {fmtWhen(b.from)} · 발화 {b.utterances}개
</li>
))}
</ul>
<p className="dim small">발화 · 음성 파일 · 경기 기록(킬 · 라운드 · 범인 분석)이 게임 PC 에서 지워지고 되돌릴 수 없습니다. 먼저 zip 으로 받아 두면 "받아오기"로 다시 넣을 수 있습니다.</p>
<div className="ctx-foot">
<button className="chip" onClick={() => download(confirm.map((b) => b.id))}>
<IDownload width={14} height={14} /> 먼저 zip 받기
</button>
<button className="chip danger" disabled={busy === 'delete'} onClick={() => void doDelete(confirm)}>
{busy === 'delete' ? '지우는 중…' : '🗑 지우기'}
</button>
<button className="chip" onClick={() => setConfirm(null)}>
취소
</button>
</div>
</div>
</div>
)}
</main>
);
}
function BundleRow({ b, on, admin, onToggle, onView, onZip, onDelete }: { b: BundleInfo; on: boolean; admin: boolean; onToggle: () => void; onView: () => void; onZip: () => void; onDelete: () => void }) {
const { userById } = useData();
const icon = b.kind === 'match' ? (b.game === 'lol' ? '🏆' : '🎯') : '💬';
return (
<div className={`rec-row k-${b.kind}${b.game ? ` g-${b.game}` : ''}${on ? ' sel' : ''}`}>
<input type="checkbox" checked={on} onChange={onToggle} aria-label={`${b.label} 선택`} />
<span className="rec-ic">{icon}</span>
<div className="rec-main" onClick={onView} role="button" title="기록 보기">
<div className="rec-title">
<b>{b.label}</b>
{b.sub && <span className="dim">· {b.sub}</span>}
</div>
<div className="rec-meta dim">
<span className="mono">
{fmtHM(b.from)} ~ {fmtHM(b.to)}
</span>{' '}
({fmtDuration(Math.max(0, b.to - b.from))}) · 발화 {b.utterances}개 · 말한 시간 {fmtDuration(b.talkMs)} · 음성 {b.audio}개 {b.audioBytes ? `(${fmtMB(b.audioBytes)})` : ''}
{b.kind === 'match' ? ` · 경기 이벤트 ${b.events}개` : ''}
</div>
</div>
<div className="rec-avs">
{b.users.slice(0, 6).map((id) => (
<Avatar key={id} user={userById(id)} size={24} />
))}
</div>
<div className="rec-btns">
<button className="chip" onClick={onView}>
기록 보기
</button>
<button className="chip" onClick={onZip} title="이 묶음을 zip 으로 내려받기 (음성 ogg · 대화.txt 포함)">
<IDownload width={14} height={14} /> zip
</button>
{admin && (
<button className="chip danger" onClick={onDelete} title="이 묶음 지우기">
🗑
</button>
)}
</div>
</div>
);
}

View File

@@ -2,7 +2,7 @@ import type { MatchDetail, MatchSummary, User } from '@gvr/shared';
import type { Filters } from '../lib/filters';
import { Avatar, CharIcon } from '../components/common';
import { sfx } from '../lib/sfx';
import { dateInputToMs, dateInputValue, fmtHM, fmtWhen } from '../lib/format';
import { dateInputToMs, dateInputValue, fmtHM, fmtDay } from '../lib/format';
import { TYPE_GROUPS } from '../lib/game';
type Update = (p: Partial<Filters>) => void;
@@ -45,7 +45,7 @@ export function Sidebar({ f, update, users, matches, detail }: { f: Filters; upd
sfx('click');
fn();
};
const today = matches.length ? fmtWhen(matches[0].startedAt).split(' ')[0] : '';
const today = matches.length ? fmtDay(matches[0].startedAt) : '';
return (
<aside className="side">
<div>

View File

@@ -3,7 +3,7 @@ import { Link, useNavigate, useParams } from 'react-router';
import type { GameType, MatchSummary, User, UserProfile } from '@gvr/shared';
import { api } from '../lib/api';
import { useStatus } from '../store/app';
import { fmtDuration, fmtWhen } from '../lib/format';
import { fmtDuration, fmtDay } from '../lib/format';
import { sfx } from '../lib/sfx';
import { Avatar, ErrorBox, Spinner } from '../components/common';
import { MatchItem } from './Sidebar';
@@ -57,7 +57,7 @@ export function MatchesPage() {
const groups = useMemo(() => {
const g = new Map<string, MatchSummary[]>();
for (const m of data ?? []) {
const d = fmtWhen(m.startedAt).split(' ')[0];
const d = fmtDay(m.startedAt);
g.set(d, [...(g.get(d) ?? []), m]);
}
return [...g];

View File

@@ -3743,3 +3743,135 @@ button.match:hover {
background: var(--accent);
box-shadow: 0 0 6px rgba(255, 70, 85, 0.6);
}
/* ── 기록 관리 (/records) ── */
.records .page-h-row {
flex-wrap: wrap;
}
.rec-actions {
margin-left: auto;
display: flex;
gap: 8px;
}
.rec-help {
font-size: 13px;
margin: 4px 0 14px;
line-height: 1.6;
}
.rec-msg {
padding: 9px 14px;
border-radius: 8px;
font-size: 13px;
margin-bottom: 12px;
}
.rec-msg.ok {
background: rgba(69, 211, 154, 0.1);
border: 1px solid rgba(69, 211, 154, 0.35);
color: #9ff0cc;
}
.rec-msg.bad {
background: #2a1418;
border: 1px solid #5a2630;
color: #ffb3bb;
}
.rec-selbar {
position: sticky;
top: 0;
z-index: 5;
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
padding: 10px 14px;
margin-bottom: 12px;
background: #13202c;
border: 1px solid #2c3f52;
border-radius: 10px;
font-size: 13px;
}
.chip.danger {
border-color: rgba(255, 70, 85, 0.5);
color: #ff9aa3;
}
.chip.danger:hover:not(:disabled) {
background: rgba(255, 70, 85, 0.15);
}
.rec-day h4 {
font-size: 12.5px;
color: var(--muted);
margin: 18px 0 8px;
}
.rec-day h4 label {
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
}
.rec-row {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 14px;
border: 1px solid #1c2a37;
border-left: 3px solid #3a4d60;
border-radius: 10px;
background: #0f1923;
margin-bottom: 8px;
}
.rec-row.k-match.g-valorant {
border-left-color: var(--accent);
}
.rec-row.k-match.g-lol {
border-left-color: var(--lol);
}
.rec-row.k-talk {
border-left-color: var(--mint);
}
.rec-row.sel {
background: #14222f;
border-color: #2c3f52;
}
.rec-ic {
font-size: 18px;
width: 24px;
text-align: center;
}
.rec-main {
flex: 1;
min-width: 0;
cursor: pointer;
}
.rec-title {
display: flex;
gap: 6px;
align-items: baseline;
font-size: 14px;
flex-wrap: wrap;
}
.rec-meta {
font-size: 12px;
margin-top: 3px;
}
.rec-avs {
display: flex;
gap: 2px;
}
.rec-btns {
display: flex;
gap: 6px;
}
.rec-del-list {
font-size: 13px;
margin: 6px 0 10px;
padding-left: 18px;
max-height: 240px;
overflow: auto;
}
@media (max-width: 720px) {
.rec-row {
flex-wrap: wrap;
}
.rec-avs {
display: none;
}
}