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