제작된 퀴즈 4단계: 플레이리스트 가져오기(유튜브·유튜브 뮤직·스포티파이 주소를 .6 Lavalink로). 서버 DB 곡(같은 영상·같은 제목+가수)은 그 곡, 유튜브는 그 영상(Official MV 등 제목 정리, 퍼가기 막힌 영상 표시), 스포티파이는 유튜브 뮤직 검색을 원곡 찾기 기준으로(애매하면 확인 필요). 백그라운드 작업+진행률, 결과에서 골라 뒤에 추가 또는 목록 바꾸기(이미 있는 곡 제외). LAVALINK_URL·LAVALINK_PW 환경변수

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-22 13:03:11 +09:00
parent b56d1a8d0e
commit 4a40be696b
8 changed files with 497 additions and 9 deletions

View File

@@ -149,6 +149,7 @@ export function QuizEditor() {
const [leaveTo, setLeaveTo] = useState<string | null>(null);
const [confirmDelete, setConfirmDelete] = useState(false);
const [owner, setOwner] = useState<{ ownerName: string; plays: number } | null>(null);
const [importOpen, setImportOpen] = useState(false);
const load = useCallback(() => {
apiCall<{ quiz: QuizDetail; db: Record<number, DbInfo> }>('GET', `/api/admin/quizzes/${id}`)
@@ -272,8 +273,8 @@ export function QuizEditor() {
<div className="card stack">
<b>곡을 어떻게 넣을까요?</b>
<div className="row">
<button type="button" className="btn" disabled title="곧 추가돼요">
🔗 플레이리스트 가져오기 (준비 중)
<button type="button" className="btn" onClick={() => (setParams({}), setTab('songs'), setImportOpen(true))}>
🔗 플레이리스트 가져오기
</button>
<button type="button" className="btn btn-primary" onClick={() => setParams({})}>
✋ 직접 하나씩 추가
@@ -282,7 +283,7 @@ export function QuizEditor() {
</div>
)}
{tab === 'songs' ? (
<SongsTab items={draft.items} db={db} settings={draft.settings} onItems={(items) => set({ items })} />
<SongsTab items={draft.items} db={db} settings={draft.settings} onItems={(items) => set({ items })} importOpen={importOpen} setImportOpen={setImportOpen} />
) : (
<SettingsTab draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
)}
@@ -376,7 +377,21 @@ interface VideoInfo {
const looksLikeUrl = (s: string) => /^(https?:\/\/|www\.|youtu\.?be|m\.youtube|music\.youtube)/i.test(s.trim()) || /^[\w-]{11}$/.test(s.trim());
function SongsTab({ items, db, settings, onItems }: { items: DraftItem[]; db: Record<number, DbInfo>; settings: QuizSettings; onItems: (items: DraftItem[]) => void }) {
function SongsTab({
items,
db,
settings,
onItems,
importOpen,
setImportOpen,
}: {
items: DraftItem[];
db: Record<number, DbInfo>;
settings: QuizSettings;
onItems: (items: DraftItem[]) => void;
importOpen: boolean;
setImportOpen: (on: boolean) => void;
}) {
const [sel, setSel] = useState<string | null>(null);
const [dragKey, setDragKey] = useState<string | null>(null);
const [overKey, setOverKey] = useState<string | null>(null);
@@ -406,7 +421,29 @@ function SongsTab({ items, db, settings, onItems }: { items: DraftItem[]; db: Re
return (
<div className={`songs-layout quiz ${selected ? 'with-panel' : ''}`}>
<div className="stack" style={{ gap: 12, minWidth: 0 }}>
<AddSong onAdd={add} />
{importOpen ? (
<PlaylistImport
existing={items}
onClose={() => setImportOpen(false)}
onApply={(rows, replace) => {
const base = replace ? [] : items;
const seen = new Set(base.flatMap((x) => [x.videoId, x.songId ? `s${x.songId}` : '']));
const fresh: DraftItem[] = [];
for (const r of rows) {
if (seen.has(r.videoId!) || (r.songId && seen.has(`s${r.songId}`))) continue;
seen.add(r.videoId!);
if (r.songId) seen.add(`s${r.songId}`);
fresh.push({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec, titleAnswers: [], artistAnswers: [], auto: true, startSec: null, highlightSec: null, key: newKey() });
}
onItems([...base, ...fresh]);
setSel(null);
setImportOpen(false);
toast(`${fresh.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}${rows.length > fresh.length ? ` (이미 있는 ${rows.length - fresh.length}곡 제외)` : ''}. 저장해야 반영돼요.`);
}}
/>
) : (
<AddSong onAdd={add} onImport={() => setImportOpen(true)} />
)}
{items.length === 0 ? (
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
) : (
@@ -502,7 +539,7 @@ function SongsTab({ items, db, settings, onItems }: { items: DraftItem[]; db: Re
);
}
function AddSong({ onAdd }: { onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => boolean }) {
function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => boolean; onImport: () => void }) {
const [q, setQ] = useState('');
const [dbHits, setDbHits] = useState<DbHit[] | null>(null);
const [ytHits, setYtHits] = useState<YtHit[] | null>(null);
@@ -556,6 +593,9 @@ function AddSong({ onAdd }: { onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artis
닫기
</button>
)}
<button type="button" className="btn" onClick={onImport}>
🔗 플레이리스트 가져오기
</button>
</form>
{video && <VideoAdd v={video} onAdd={(it) => done(onAdd(it))} />}
{dbHits && (
@@ -645,6 +685,204 @@ function VideoAdd({ v, onAdd }: { v: VideoInfo; onAdd: (it: Omit<QuizItem, 'titl
);
}
// ------------------------------------------------------------------ 플레이리스트 가져오기
type ImportStatus = 'db' | 'video' | 'found' | 'check' | 'missing' | 'blocked';
interface ImportRow {
n: number;
source: { title: string; artist: string };
title: string;
artist: string;
durationSec: number | null;
videoId: string | null;
songId: number | null;
status: ImportStatus;
note: string;
}
interface ImportJob {
id: string;
name: string;
status: 'running' | 'done' | 'failed';
done: number;
total: number;
rows: ImportRow[];
error: string | null;
}
const IMPORT_LABEL: Record<ImportStatus, [string, string]> = {
db: ['서버 DB', 'ok'],
video: ['유튜브 영상', 'teal'],
found: ['찾음', 'ok'],
check: ['확인 필요', 'warn'],
missing: ['못 찾음', ''],
blocked: ['재생 불가', ''],
};
const usable = (r: ImportRow) => !!r.videoId && r.status !== 'missing' && r.status !== 'blocked';
function PlaylistImport({ existing, onApply, onClose }: { existing: QuizItem[]; onApply: (rows: ImportRow[], replace: boolean) => void; onClose: () => void }) {
const [url, setUrl] = useState('');
const [job, setJob] = useState<ImportJob | null>(null);
const [busy, setBusy] = useState(false);
const [pick, setPick] = useState<Set<number>>(new Set());
const [confirmReplace, setConfirmReplace] = useState(false);
const picked = useRef(false);
useEffect(() => {
if (!job || job.status !== 'running') return;
const t = setTimeout(() => {
apiCall<{ job: ImportJob }>('GET', `/api/admin/quizzes/pick/playlist/${job.id}`)
.then((r) => setJob(r.job))
.catch((e: Error) => toast(e.message, 'error'));
}, 1000);
return () => clearTimeout(t);
}, [job]);
// pre-tick what is safe once the rows are in: DB songs, the playlist's own videos, confident matches
useEffect(() => {
if (job?.status === 'done' && !picked.current) {
picked.current = true;
setPick(new Set(job.rows.filter((r) => usable(r) && r.status !== 'check').map((r) => r.n)));
}
}, [job]);
const begin = async () => {
setBusy(true);
picked.current = false;
try {
setJob((await apiCall<{ job: ImportJob }>('POST', '/api/admin/quizzes/pick/playlist', { url: url.trim() })).job);
} catch (e) {
toast((e as Error).message, 'error');
} finally {
setBusy(false);
}
};
const rows = job?.rows ?? [];
const chosen = rows.filter((r) => pick.has(r.n) && usable(r));
const inList = (r: ImportRow) => existing.some((x) => x.videoId === r.videoId || (r.songId && x.songId === r.songId));
const counts = rows.reduce<Record<string, number>>((a, r) => ((a[r.status] = (a[r.status] ?? 0) + 1), a), {});
return (
<div className="card stack" style={{ gap: 10 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<b>🔗 플레이리스트 가져오기</b>
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
✕
</button>
</div>
<form
className="row"
onSubmit={(e) => {
e.preventDefault();
if (url.trim()) void begin();
}}
>
<input className="input grow" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="유튜브·유튜브 뮤직·스포티파이 플레이리스트 주소" aria-label="플레이리스트 주소" />
<button className="btn btn-primary" disabled={busy || !url.trim() || job?.status === 'running'}>
{busy ? '불러오는 중…' : '가져오기'}
</button>
</form>
<p className="muted small" style={{ margin: 0 }}>
서버 DB에 있는 곡은 그 곡으로, 유튜브 플레이리스트는 그 영상으로, 스포티파이는 유튜브 뮤직에서 원곡을 찾아 넣어요. 확인이 끝나면 넣을 곡을 고를 수 있어요.
</p>
{job && (
<>
<div className="stack" style={{ gap: 4 }}>
<span className="small">
<b>{job.name || '플레이리스트'}</b> · {job.status === 'running' ? `확인 중 ${job.done}/${job.total}곡` : job.status === 'failed' ? `실패: ${job.error}` : `${job.total}곡 확인 끝`}
{rows.length > 0 && (
<span className="muted">
{' '}
· {(Object.keys(IMPORT_LABEL) as ImportStatus[])
.filter((k) => counts[k])
.map((k) => `${IMPORT_LABEL[k][0]} ${counts[k]}`)
.join(' · ')}
</span>
)}
</span>
<progress className="yt-progress" max={job.total} value={job.done} />
</div>
{rows.length > 0 && (
<div className="table-wrap" style={{ maxHeight: 460, overflowY: 'auto' }}>
<table className="data-table">
<thead>
<tr>
<th style={{ width: 36 }}>
<input
type="checkbox"
aria-label="모두 고르기"
checked={rows.filter(usable).every((r) => pick.has(r.n))}
onChange={(e) => setPick(e.target.checked ? new Set(rows.filter(usable).map((r) => r.n)) : new Set())}
/>
</th>
<th style={{ width: 40 }}>#</th>
<th>노래</th>
<th>상태</th>
<th>길이</th>
</tr>
</thead>
<tbody>
{rows.map((r) => (
<tr key={r.n}>
<td>
<input
type="checkbox"
aria-label={`${r.title} 넣기`}
disabled={!usable(r)}
checked={pick.has(r.n) && usable(r)}
onChange={(e) => {
const next = new Set(pick);
if (e.target.checked) next.add(r.n);
else next.delete(r.n);
setPick(next);
}}
/>
</td>
<td className="mono">{r.n}</td>
<td>
<b>{r.title}</b>
<div className="muted small">
{r.artist}
{(r.source.title !== r.title || r.source.artist !== r.artist) && <span> · 원래: {r.source.artist} - {r.source.title}</span>}
</div>
</td>
<td className="small">
<span className={`badge ${IMPORT_LABEL[r.status][1]}`}>{IMPORT_LABEL[r.status][0]}</span>
{inList(r) && <span className="badge" style={{ marginLeft: 4 }}>이미 목록에 있음</span>}
{r.note && <div className="muted">{r.note}</div>}
{r.videoId && (
<a className="small" href={`https://youtu.be/${r.videoId}`} target="_blank" rel="noreferrer">
영상 보기 ↗
</a>
)}
</td>
<td className="mono small">{mmss(r.durationSec)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{job.status === 'done' && (
<div className="row">
<button type="button" className="btn btn-primary" disabled={!chosen.length} onClick={() => onApply(chosen, false)}>
고른 {chosen.length}곡 목록 뒤에 추가
</button>
<button type="button" className="btn btn-danger" disabled={!chosen.length} onClick={() => setConfirmReplace(true)}>
지금 목록을 지우고 바꾸기
</button>
<span className="muted small">"확인 필요"는 영상을 보고 맞으면 체크해 주세요. "못 찾음"은 추가한 뒤 직접 넣어 주세요.</span>
</div>
)}
</>
)}
{confirmReplace && (
<ConfirmSheet
title="지금 목록을 바꿀까요?"
body={`지금 곡 목록 ${existing.length}곡과 그 곡들의 정답·위치 설정이 사라지고 고른 ${chosen.length}곡으로 바뀌어요. 저장하기 전에는 되돌릴 수 있어요(저장하지 않고 나가기).`}
confirm="목록 바꾸기"
danger
onClose={() => setConfirmReplace(false)}
onConfirm={() => onApply(chosen, true)}
/>
)}
</div>
);
}
/** Chips with an input: Enter or , adds, ✕ removes. */
function ChipsInput({ values, onChange, label, placeholder }: { values: string[]; onChange: (v: string[]) => void; label: string; placeholder: string }) {
const [text, setText] = useState('');