diff --git a/apps/server/src/custom-quiz.test.ts b/apps/server/src/custom-quiz.test.ts index 5519af1..2f4638c 100644 --- a/apps/server/src/custom-quiz.test.ts +++ b/apps/server/src/custom-quiz.test.ts @@ -2,7 +2,7 @@ import { afterEach, expect, test } from 'bun:test'; import type { ServerMessage } from '@mq/shared'; import { Catalog } from './collector/catalog'; -import { cleanVideoTitle } from './quizzes/playlist'; +import { cleanVideoTitle, getImportJob, startImport } from './quizzes/playlist'; import { Client, TEST_SUPERADMINS, api, boot, discordLogin, guest, sleep } from './test-utils'; type Msg = Extract; @@ -325,3 +325,25 @@ test('영상 제목 정리: 가수 - 제목 / 가수 \'제목\' / 토픽은 그 expect(cleanVideoTitle('Ditto', 'NewJeans - Topic')).toEqual({ title: 'Ditto', artist: 'NewJeans', guessed: false }); expect(cleanVideoTitle('밤편지 (Official MV)', '아이유 공식')).toEqual({ title: '밤편지', artist: '아이유', guessed: true }); }); + +test('플레이리스트 가져오기: 서버 DB 곡으로 바꾼 스포티파이 곡도 그 영상이 다른 사이트에서 재생되는지 확인 (막혔으면 재생 불가)', async () => { + start(); + const embedded: string[] = []; + const job = await startImport( + { + db: s.db, + lavalink: { url: 'http://lavalink.test', password: 'pw' }, + fetchImpl: (async () => + Response.json({ loadType: 'playlist', data: { info: { name: 'p' }, tracks: [{ info: { identifier: 'sp9', title: '좋은 날', author: '아이유', length: 230000, sourceName: 'spotify' } }] } })) as unknown as typeof fetch, + search: async () => [], + embed: async (v) => (embedded.push(v), { state: 'noembed' }), + delayMs: 0, + }, + 'owner', + 'https://open.spotify.com/playlist/y', + ); + if (typeof job === 'string') throw new Error(job); + for (let i = 0; i < 100 && getImportJob(job.id, 'owner')!.status === 'running'; i++) await sleep(5); + expect(embedded).toEqual(['goodday0001']); + expect(getImportJob(job.id, 'owner')!.rows).toMatchObject([{ status: 'blocked', videoId: 'goodday0001', note: '다른 사이트 재생이 막힌 영상' }]); +}); diff --git a/apps/server/src/quizzes/playlist.ts b/apps/server/src/quizzes/playlist.ts index f27483d..12019b2 100644 --- a/apps/server/src/quizzes/playlist.ts +++ b/apps/server/src/quizzes/playlist.ts @@ -134,14 +134,19 @@ async function runImport(d: ImportDeps, job: ImportJob, tracks: LavalinkTrack[]) const named = yt ? cleanVideoTitle(t.title, t.author) : { title: t.title, artist: t.author, guessed: false }; 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)); + // the video must play on other sites, the DB song's own video too (the DB state may be old) + const playable = async (videoId: string) => { + const e = await d.embed(videoId); + if (e.state !== 'ok') Object.assign(row, { status: 'blocked', note: e.state === 'noembed' ? '다른 사이트 재생이 막힌 영상' : e.state === 'dead' ? '없는 영상' : '영상 확인 실패' }); + }; 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 Object.assign(row, { status: 'video', note: named.guessed ? '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)' : '' }); - const e = await d.embed(t.identifier); - if (e.state !== 'ok') Object.assign(row, { status: 'blocked', note: e.state === 'noembed' ? '다른 사이트 재생이 막힌 영상' : e.state === 'dead' ? '없는 영상' : '영상 확인 실패' }); + await playable(t.identifier); } 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 곡' }); + await playable(dbSong.youtube_id); } else { // Spotify (or any non-YouTube source): find the official audio like 원곡 찾기 let results: YtmSong[] = []; diff --git a/apps/web/src/pages/admin/PlaylistSheet.tsx b/apps/web/src/pages/admin/PlaylistSheet.tsx index 05b1c75..0a62141 100644 --- a/apps/web/src/pages/admin/PlaylistSheet.tsx +++ b/apps/web/src/pages/admin/PlaylistSheet.tsx @@ -5,7 +5,7 @@ */ import { useEffect, useMemo, useState } from 'react'; import { playlistSheets, writeXlsxSheets, type PlaylistSheetRow } from '@mq/shared/lite'; -import { apiCall } from '../../net/api'; +import { ApiError, apiCall } from '../../net/api'; import { toast } from '../../store/toast'; import { download } from './QuizFile'; @@ -23,17 +23,31 @@ export function PlaylistSheet({ onClose }: { onClose: () => void }) { const [url, setUrl] = useState(''); const [job, setJob] = useState(null); const [busy, setBusy] = useState(false); + /** Polls in a row that failed: the job goes on on the server, so polling keeps going (slower) until it answers. */ + const [fails, setFails] = useState(0); 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); + const t = setTimeout( + () => { + apiCall<{ job: ImportJob }>('GET', `/api/admin/quizzes/pick/playlist/${job.id}`) + .then((r) => { + setFails(0); + setJob(r.job); + }) + .catch((e: ApiError) => { + // the job is gone (server restarted or an hour passed): nothing more will come + if (e.status === 404) return setJob({ ...job, status: 'failed', error: `${e.message} 다시 검토해 주세요.` }); + if (!fails) toast(`검토 상황을 못 받았어요. 계속 다시 물어볼게요: ${e.message}`, 'error'); + setFails((n) => n + 1); + }); + }, + fails ? Math.min(10_000, 1000 * 2 ** fails) : 1000, + ); return () => clearTimeout(t); - }, [job]); + }, [job, fails]); const begin = async () => { setBusy(true); + setFails(0); try { setJob((await apiCall<{ job: ImportJob }>('POST', '/api/admin/quizzes/pick/playlist', { url: url.trim() })).job); } catch (e) { @@ -75,7 +89,7 @@ export function PlaylistSheet({ onClose }: { onClose: () => void }) { {job && (
- {job.name || '재생목록'} · {job.status === 'running' ? `검토 중 ${job.done}/${job.total}곡` : job.status === 'failed' ? `실패: ${job.error}` : `${job.total}곡 검토 끝`} + {job.name || '재생목록'} · {job.status === 'running' ? `검토 중 ${job.done}/${job.total}곡${fails ? ' (연결 다시 시도 중)' : ''}` : job.status === 'failed' ? `실패: ${job.error}` : `${job.total}곡 검토 끝`} {sheets && ( {' '} diff --git a/e2e/quiz.e2e.ts b/e2e/quiz.e2e.ts index b01c5f5..dd6c1bd 100644 --- a/e2e/quiz.e2e.ts +++ b/e2e/quiz.e2e.ts @@ -201,9 +201,17 @@ try { await p.goto(`${ORIGIN}/admin/quizzes`); await p.getByRole('button', { name: /재생목록으로 엑셀 만들기/ }).click(); await p.getByLabel('재생목록 주소').fill('https://www.youtube.com/playlist?list=PLe2e'); + // the first poll fails (network blip): polling goes on and the file still comes + let failedPolls = 0; + await p.route(`${ORIGIN}/api/admin/quizzes/pick/playlist/*`, async (route) => { + if (failedPolls++ === 0) return route.fulfill({ status: 502, contentType: 'application/json', body: '{"error":"잠깐 끊김"}' }); + await route.continue(); + }); await p.getByRole('button', { name: '검토 시작' }).click(); const get = p.getByRole('button', { name: /엑셀 받기/ }); await get.waitFor(); + expect(failedPolls >= 2, `다시 묻지 않음: ${failedPolls}`); + await p.unroute(`${ORIGIN}/api/admin/quizzes/pick/playlist/*`); expect((await get.innerText()).includes('2곡'), `받기 버튼: ${await get.innerText()}`); await p.getByText('재생목록 1번 곡과 같은 영상').waitFor(); await p.screenshot({ path: join(SHOTS, 'quiz-playlist-sheet.png'), fullPage: true });