제작된 퀴즈 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

@@ -11,8 +11,34 @@ const fakeDiscord = async (code: string) => ({ id: code, username: 'u', global_n
let s: ReturnType<typeof boot>;
afterEach(async () => s && (await s.stop()));
const PLAYLIST = {
loadType: 'playlist',
data: {
info: { name: '내 플레이리스트' },
tracks: [
{ info: { identifier: 'goodday0001', title: '아이유 - 좋은 날 (Official MV)', author: 'LOEN', length: 230000, sourceName: 'youtube' } },
{ info: { identifier: 'lovedive001', title: "IVE 아이브 'LOVE DIVE' MV", author: 'STARSHIP', length: 180000, sourceName: 'youtube' } },
{ info: { identifier: 'sp1', title: 'Hype Boy', author: 'NewJeans', length: 179000, sourceName: 'spotify' } },
{ info: { identifier: 'sp2', title: '없는 노래', author: '아무개', length: 200000, sourceName: 'spotify' } },
],
},
};
function start() {
s = boot({ gameTiming: TIMING, discordExchange: fakeDiscord, checkEmbed: async () => ({ state: 'ok', author: 'IU - Topic', title: 'x' }) }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' });
s = boot(
{
gameTiming: TIMING,
discordExchange: fakeDiscord,
checkEmbed: async () => ({ state: 'ok', author: 'IU - Topic', title: 'x' }),
quizAdmin: {
lavalink: { url: 'http://lavalink.test', password: 'pw' },
lavalinkFetch: (async () => new Response(JSON.stringify(PLAYLIST))) as unknown as typeof fetch,
searchYoutube: async (q) => (q.includes('Hype Boy') ? [{ videoId: 'hypeboy0001', title: 'Hype Boy', artists: 'NewJeans', album: null, durationSec: 180 }] : []),
importDelayMs: 0,
},
},
{ DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' },
);
const c = new Catalog(s.db);
const [song] = c.upsert({ title: '좋은 날', artists: [{ name: '아이유' }], year: 2010, durationSec: 230, source: 't', ref: '1' });
s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'goodday0001', highlight_sec = 61 WHERE id = ?").run(song!);
@@ -157,3 +183,24 @@ test('a quiz game plays every song in order from its own 처음 position and acc
}
expect(s.db.query<{ plays: number }, [number]>('SELECT plays FROM custom_quizzes WHERE id = ?').get(q.id)!.plays).toBe(1);
});
test('플레이리스트 가져오기: DB songs by video, cleaned YouTube titles, Spotify tracks found on YouTube Music, misses marked', async () => {
const song = start();
const sa = await adminCookie(TEST_SUPERADMINS[0]);
const r = await api(s.base, '/api/admin/quizzes/pick/playlist', { method: 'POST', cookie: sa, body: JSON.stringify({ url: 'https://open.spotify.com/playlist/x' }) });
expect(r.res.status).toBe(200);
let job = r.body.job;
for (let i = 0; i < 100 && job.status === 'running'; i++) {
await sleep(10);
job = (await api(s.base, `/api/admin/quizzes/pick/playlist/${job.id}`, { cookie: sa })).body.job;
}
expect(job).toMatchObject({ status: 'done', name: '내 플레이리스트', total: 4 });
const rows = job.rows as { title: string; artist: string; videoId: string | null; songId: number | null; status: string }[];
expect(rows[0]).toMatchObject({ status: 'db', songId: song, title: '좋은 날', artist: '아이유', videoId: 'goodday0001' });
expect(rows[1]).toMatchObject({ status: 'video', title: 'LOVE DIVE', artist: 'IVE 아이브', videoId: 'lovedive001' });
expect(rows[2]).toMatchObject({ status: 'found', videoId: 'hypeboy0001' });
expect(rows[3]).toMatchObject({ status: 'missing', videoId: null });
// someone else's job is not visible
const g = await guest(s.base, '손님');
expect((await api(s.base, `/api/admin/quizzes/pick/playlist/${job.id}`, { cookie: g.cookie })).res.status).toBe(403);
});

View File

@@ -11,6 +11,8 @@ import type { YtmSong } from '../collector/ytmusic';
import { pickSearcher } from '../collector/ytmusic';
import { listSongs } from '../songs/store';
import { audioFile, type AudioLinks } from '../songs/audio';
import { getImportJob, startImport, type Lavalink } from '../quizzes/playlist';
import { checkEmbed, type EmbedState } from '../collector/oembed';
type Env = { Variables: { userId: string | null; role: Role } };
@@ -22,6 +24,11 @@ export interface QuizAdminDeps {
/** YouTube Music song search (cookie) with the plain YouTube fallback; injected in tests. */
searchYoutube?: (q: string) => Promise<YtmSong[]>;
audio?: AudioLinks;
/** 플레이리스트 가져오기 through the .6 Lavalink (LAVALINK_URL / LAVALINK_PW); tests inject a fake fetch. */
lavalink?: Lavalink | null;
lavalinkFetch?: typeof fetch;
checkEmbed?: (videoId: string) => Promise<EmbedState>;
importDelayMs?: number;
videoOf: (url: string) => Promise<{ id: string; author: string; title: string } | string>;
onChange?: () => void;
}
@@ -132,6 +139,25 @@ export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c:
return c.json({ src: d.audio.link(v) });
});
/** 플레이리스트 가져오기: starts a background job; the editor polls it. */
app.post('/quizzes/pick/playlist', async (c) => {
const p = z.object({ url: z.string().trim().min(1).max(500) }).safeParse(await h.body(c));
if (!p.success) return c.json({ error: '플레이리스트 주소를 넣어 주세요.' }, 400);
const lavalink =
d.lavalink !== undefined ? d.lavalink : process.env.LAVALINK_URL && process.env.LAVALINK_PW ? { url: process.env.LAVALINK_URL, password: process.env.LAVALINK_PW } : null;
const job = await startImport(
{ db: d.db, lavalink, search: d.searchYoutube ?? defaultSearch, embed: d.checkEmbed ?? ((id) => checkEmbed(id)), delayMs: d.importDelayMs, fetchImpl: d.lavalinkFetch },
h.actor(c),
p.data.url,
);
if (typeof job === 'string') return c.json({ error: job }, 400);
return c.json({ job });
});
app.get('/quizzes/pick/playlist/:job', (c) => {
const job = getImportJob(c.req.param('job'), h.actor(c));
return job ? c.json({ job }) : c.json({ error: '가져오기 작업을 찾을 수 없어요.' }, 404);
});
// ---------------------------------------------------------------- one quiz
app.get('/quizzes/:id', (c) => {
const q = mine(c);

View File

@@ -37,6 +37,10 @@ export interface AdminDeps {
collect?: CollectControl;
/** 퀴즈 편집기의 유튜브 검색 (tests inject a fake). */
searchYoutube?: (q: string) => Promise<YtmSong[]>;
/** 플레이리스트 가져오기 (tests inject these; production reads LAVALINK_URL / LAVALINK_PW). */
lavalink?: { url: string; password: string } | null;
lavalinkFetch?: typeof fetch;
importDelayMs?: number;
/** 연령제한 곡's downloaded audio, for the quiz editor's position bar. */
audio?: AudioLinks;
}
@@ -129,6 +133,10 @@ export function createAdminApp(d: AdminDeps) {
audit: d.audit,
searchYoutube: d.searchYoutube,
audio: d.audio,
checkEmbed: d.checkEmbed,
lavalink: d.lavalink,
lavalinkFetch: d.lavalinkFetch,
importDelayMs: d.importDelayMs,
videoOf,
},
{ actor, body },

View File

@@ -0,0 +1,165 @@
/**
* 플레이리스트 가져오기 (관리자 → 퀴즈): YouTube / YouTube Music / Spotify playlists through the .6 Lavalink
* (music_bot_v2's; Spotify's own API no longer lists playlist tracks without a user login). Each track becomes a quiz song:
* - already in the server DB (same video, or same title+artist key) → that song and its video
* - a YouTube track → its own video (title cleaned of "Official MV" etc.)
* - a Spotify track → YouTube Music song search, confirmed with the same rules as 원곡 찾기 (else "확인 필요"/"못 찾음")
* Runs as a background job (searches are paced); the editor polls it and adds what the admin keeps.
*/
import type { Database } from 'bun:sqlite';
import { randomUUID } from 'node:crypto';
import { songMatchKey } from '@mq/shared';
import { isConfident, scoreResult } from '../collector/score';
import type { YtmSong } from '../collector/ytmusic';
import type { EmbedState } from '../collector/oembed';
import { aliasesOf } from '../songs/youtube-review';
export interface LavalinkTrack {
identifier: string;
title: string;
author: string;
length: number;
sourceName: string;
isrc?: string | null;
}
export interface Lavalink {
url: string;
password: string;
}
export async function loadPlaylist(ll: Lavalink, url: string, fetchImpl: typeof fetch = fetch): Promise<{ name: string; tracks: LavalinkTrack[] } | string> {
let res: Response;
try {
res = await fetchImpl(`${ll.url.replace(/\/$/, '')}/v4/loadtracks?identifier=${encodeURIComponent(url)}`, { headers: { Authorization: ll.password }, signal: AbortSignal.timeout(90_000) });
} catch (e) {
return `플레이리스트 서버(Lavalink)에 연결하지 못했어요: ${(e as Error).message}`;
}
if (!res.ok) return `플레이리스트 서버 오류(${res.status})`;
const j = (await res.json()) as { loadType: string; data: any };
if (j.loadType === 'playlist') return { name: j.data.info?.name ?? '', tracks: (j.data.tracks ?? []).map((t: { info: LavalinkTrack }) => t.info) };
if (j.loadType === 'track') return { name: '', tracks: [j.data.info] };
if (j.loadType === 'empty') return '플레이리스트를 찾지 못했어요. 공개(또는 일부 공개) 플레이리스트 주소인지 확인해 주세요.';
if (j.loadType === 'error') return `플레이리스트를 불러오지 못했어요: ${j.data?.message ?? '알 수 없는 오류'}`;
return '플레이리스트 주소를 알아볼 수 없어요.';
}
const NOISE = /\s*[([【][^)\]】]*(official|m\/?v|music video|lyric|audio|visuali[sz]er|performance|teaser|live clip|가사|뮤직비디오)[^)\]】]*[)\]】]\s*/gi;
/** "아이유(IU) - 좋은 날 (Official MV)" → 좋은 날 / 아이유(IU); "IVE 아이브 'LOVE DIVE' MV" → LOVE DIVE / IVE 아이브; Topic channels are the artist. */
export function cleanVideoTitle(title: string, channel: string): { title: string; artist: string } {
const t = title.replace(NOISE, ' ').replace(/\s+(M\/?V|MV|Official Video)$/i, '').replace(/\s+/g, ' ').trim();
if (/ - Topic$/.test(channel)) return { title: t, artist: channel.replace(/ - Topic$/, '') };
const dash = /^(.+?)\s+[-–—]\s+(.+)$/.exec(t);
if (dash) return { artist: dash[1]!.trim(), title: dash[2]!.trim() };
const quoted = /^(.+?)\s*['"‘“『「](.+?)['"’”』」]/.exec(t);
if (quoted) return { artist: quoted[1]!.trim(), title: quoted[2]!.trim() };
return { title: t, artist: channel.replace(/(Official|VEVO|공식)$/i, '').trim() || channel };
}
export type ImportStatus = 'db' | 'video' | 'found' | 'check' | 'missing' | 'blocked';
export interface ImportRow {
n: number;
/** As the playlist has it. */
source: { title: string; artist: string };
title: string;
artist: string;
durationSec: number | null;
videoId: string | null;
songId: number | null;
status: ImportStatus;
note: string;
}
export interface ImportJob {
id: string;
owner: string;
url: string;
name: string;
status: 'running' | 'done' | 'failed';
done: number;
total: number;
rows: ImportRow[];
error: string | null;
startedAt: number;
}
const jobs = new Map<string, ImportJob>();
const JOB_TTL = 3600_000;
export function getImportJob(id: string, owner: string): ImportJob | null {
const j = jobs.get(id);
return j && j.owner === owner ? j : null;
}
export interface ImportDeps {
db: Database;
lavalink: Lavalink | null;
search: (q: string) => Promise<YtmSong[]>;
embed: (videoId: string) => Promise<EmbedState>;
delayMs?: number;
fetchImpl?: typeof fetch;
}
/** Starts an import job and returns it at once (rows fill in while it runs). */
export async function startImport(d: ImportDeps, owner: string, url: string, now = Date.now()): Promise<ImportJob | string> {
for (const [k, j] of jobs) if (now - j.startedAt > JOB_TTL) jobs.delete(k);
if (!d.lavalink) return '플레이리스트 서버(Lavalink)가 설정되지 않았어요(LAVALINK_URL·LAVALINK_PW).';
const pl = await loadPlaylist(d.lavalink, url, d.fetchImpl);
if (typeof pl === 'string') return pl;
if (!pl.tracks.length) return '플레이리스트에 곡이 없어요.';
const job: ImportJob = { id: randomUUID(), owner, url, name: pl.name, status: 'running', done: 0, total: pl.tracks.length, rows: [], error: null, startedAt: now };
jobs.set(job.id, job);
void runImport(d, job, pl.tracks).catch((e) => {
job.status = 'failed';
job.error = (e as Error).message;
});
return job;
}
async function runImport(d: ImportDeps, job: ImportJob, tracks: LavalinkTrack[]): Promise<void> {
const byVideo = d.db.query<{ id: number; title: string; artist: string; youtube_id: string | null; youtube_status: string; duration_sec: number | null }, [string]>(
"SELECT id, title, artist, youtube_id, youtube_status, duration_sec FROM songs WHERE youtube_id = ? AND deleted_at IS NULL ORDER BY youtube_status = 'matched' DESC LIMIT 1",
);
const byKey = d.db.query<{ id: number; title: string; artist: string; youtube_id: string | null; youtube_status: string; duration_sec: number | null }, [string]>(
'SELECT id, title, artist, youtube_id, youtube_status, duration_sec FROM songs WHERE match_key = ? AND deleted_at IS NULL ORDER BY youtube_status = \'matched\' DESC LIMIT 1',
);
const aliases = aliasesOf(d.db);
for (const [i, t] of tracks.entries()) {
const dur = t.length ? Math.round(t.length / 1000) : null;
const yt = t.sourceName === 'youtube';
const named = yt ? cleanVideoTitle(t.title, t.author) : { title: t.title, artist: t.author };
const row: ImportRow = { n: i + 1, source: { title: t.title, artist: t.author }, title: named.title, artist: named.artist, durationSec: dur, videoId: null, songId: null, status: 'missing', note: '' };
const dbSong = (yt ? byVideo.get(t.identifier) : null) ?? byKey.get(songMatchKey(named.title, named.artist));
if (yt) {
row.videoId = t.identifier;
if (dbSong) Object.assign(row, { songId: dbSong.id, title: dbSong.title, artist: dbSong.artist, status: 'db', note: '서버 DB 곡 (플레이리스트 영상 사용)' });
else row.status = 'video';
const e = await d.embed(t.identifier);
if (e.state !== 'ok') Object.assign(row, { status: 'blocked', note: e.state === 'noembed' ? '다른 사이트 재생이 막힌 영상' : e.state === 'dead' ? '없는 영상' : '영상 확인 실패' });
} else if (dbSong?.youtube_id && dbSong.youtube_status === 'matched') {
Object.assign(row, { songId: dbSong.id, videoId: dbSong.youtube_id, title: dbSong.title, artist: dbSong.artist, durationSec: dbSong.duration_sec ?? dur, status: 'db', note: '서버 DB 곡' });
} else {
// Spotify (or any non-YouTube source): find the official audio like 원곡 찾기
let results: YtmSong[] = [];
try {
results = await d.search(`${t.author.split(', ')[0]} ${t.title}`);
} catch (e) {
row.note = `검색 실패: ${(e as Error).message}`;
}
const scored = results.slice(0, 8).map((r, rank) => scoreResult({ title: t.title, artist: t.author, durationSec: dur }, r, rank, aliases)).sort((a, b) => b.score - a.score);
const best = scored.find(isConfident) ?? scored.find((s) => s.titleOk) ?? null;
if (best) {
const e = await d.embed(best.videoId);
if (e.state === 'ok') {
Object.assign(row, { videoId: best.videoId, status: isConfident(best) ? 'found' : 'check', note: isConfident(best) ? `찾음: ${best.artists} - ${best.title}` : `확인 필요: ${best.artists} - ${best.title}` });
if (dbSong) row.songId = dbSong.id;
} else row.note = '찾은 영상이 다른 사이트 재생이 막혀 있어요';
} else if (!row.note) row.note = '유튜브에서 못 찾았어요';
if (i < tracks.length - 1) await Bun.sleep(d.delayMs ?? 700);
}
job.rows.push(row);
job.done = i + 1;
}
job.status = 'done';
}

View File

@@ -41,6 +41,8 @@ export interface StartOptions {
gameTiming?: Partial<import('./game/engine').GameTiming>;
/** Collector runner for the admin page (tests inject a fake). */
collect?: CollectControl;
/** Quiz editor externals (YouTube search, Lavalink playlists); tests inject fakes. */
quizAdmin?: Pick<import('./http/admin').AdminDeps, 'searchYoutube' | 'lavalink' | 'lavalinkFetch' | 'importDelayMs'>;
}
export function startServer(opts: StartOptions) {
@@ -124,6 +126,7 @@ export function startServer(opts: StartOptions) {
audit,
db,
checkEmbed: opts.checkEmbed,
...opts.quizAdmin,
onCatalogChange: () => rooms.recountAll(),
onGenresChange: loadGenres,
rooms,

View File

@@ -8,7 +8,7 @@ import { notConfidentReasons, scoreResult, type ArtistAliases } from '../collect
let aliasCache: { db: Database; at: number; map: ArtistAliases } | null = null;
/** Learnt artist names change only when songs get confirmed: re-learn at most every 10 minutes. */
function aliasesOf(db: Database, now = Date.now()): ArtistAliases {
export function aliasesOf(db: Database, now = Date.now()): ArtistAliases {
if (!aliasCache || aliasCache.db !== db || now - aliasCache.at > 600_000) aliasCache = { db, at: now, map: learnArtistAliases(db) };
return aliasCache.map;
}

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

View File

@@ -178,7 +178,8 @@
7. 곡마다 "처음"·"하이라이트" 위치를 직접 정한다(영상+소리+큰 재생바, 끌기·지금 위치로·여기서 듣기·±1초). 자동(기본 켜짐) = 처음 0초, 하이라이트는 서버 DB 값(그 영상일 때만, 없으면 곡 길이 30%). 표시를 옮기면 자동이 꺼진다. 연령제한 영상은 서버가 받아 둔 음원으로 듣는다
8. 퀴즈당 곡 수·계정당 퀴즈 수 제한은 관리자 → 사이트에서 정하고 기본은 무제한(0)
9. 게임 중 "퀴즈 저장·불러오기"(진행 상황 저장)는 이름이 헷갈려서 "진행 저장·불러오기"로 바꿨다
10. 다음 단계: 플레이리스트 가져오기(유튜브, 스포티파이는 .6 Lavalink로 — 스포티파이 키로는 플레이리스트를 못 읽음), 전체공개 퀴즈 곡·하이라이트 → 관리자 검토 대기 → 서버 DB, 플레이 통계(힌트·오답·다시듣기·퀴즈별) → 난이도 조정 검토 대기
10. 플레이리스트 가져오기: 유튜브·유튜브 뮤직·스포티파이 주소를 .6 Lavalink(`LAVALINK_URL`·`LAVALINK_PW`)로 읽는다(스포티파이 키로는 플레이리스트를 못 읽음). 서버 DB에 있는 곡은 그 곡, 유튜브는 그 영상(제목의 Official MV 등 정리), 스포티파이는 유튜브 뮤직에서 원곡 찾기와 같은 기준으로 찾고 애매하면 "확인 필요". 결과에서 고른 곡만 뒤에 추가하거나 목록을 바꾼다
11. 다음 단계: 전체공개 퀴즈 곡·하이라이트 → 관리자 검토 대기 → 서버 DB, 플레이 통계(힌트·오답·다시듣기·퀴즈별) → 난이도 조정 검토 대기
## 원곡 찾기 자동 확정 기준 (2026-10-22)
1. 제목 일치 + 가수 일치(라틴 악센트 무시 JAŸ-Z=JAY-Z, `및`·with·feat 구분, 앞 The 무시, 확정곡 2곡 이상에서 확인된 한글/영문 이름 짝 태연=TAEYEON) + 길이 차이 15초 이내 + 커버·노래방·라이브·다른 버전 아님. "Radio Edit/Original Version"은 같은 녹음으로 본다