/** 이지선다 조회수 자동: 토픽 ↔ MV pair from a YouTube Music watch response, view counts, and the upload → fetch → editor flow. */ import { afterEach, expect, test } from 'bun:test'; import { duelViewsNote, type DuelViews, type QuizItem } from '@mq/shared'; import { CookieError, parseSongPair, RateLimited, type SongPair } from './collector/ytmusic'; import { fetchDuelViews, youtubeViewCount, type ViewsSource } from './quizzes/duel-views'; import { TEST_SUPERADMINS, api, boot, discordLogin } from './test-utils'; const ATV = 'MUSIC_VIDEO_TYPE_ATV'; const OMV = 'MUSIC_VIDEO_TYPE_OMV'; const panel = (videoId: string, type: string) => ({ videoId, title: { runs: [{ text: videoId }] }, navigationEndpoint: { watchEndpoint: { videoId, watchEndpointMusicSupportedConfigs: { watchEndpointMusicConfig: { musicVideoType: type } } } }, }); /** Shape of music.youtube.com /next: the queue's entries, a wrapper with the counterpart for songs that have both halves. */ const watch = (entries: unknown[]) => ({ contents: { singleColumnMusicWatchNextResultsRenderer: { tabbedRenderer: { watchNextTabbedResultsRenderer: { tabs: [{ tabRenderer: { content: { musicQueueRenderer: { content: { playlistPanelRenderer: { contents: entries } } } } } }] } }, }, }, }); const wrapper = (primary: [string, string], other: [string, string]) => ({ playlistPanelVideoWrapperRenderer: { primaryRenderer: { playlistPanelVideoRenderer: panel(...primary) }, counterpart: [{ counterpartRenderer: { playlistPanelVideoRenderer: panel(...other) }, segmentMap: {} }], }, }); test('parseSongPair: the entry of the asked video, its counterpart when YouTube Music has one', () => { const j = watch([wrapper(['topic000001', ATV], ['mv000000001', OMV]), { playlistPanelVideoRenderer: panel('next0000001', ATV) }]); expect(parseSongPair(j, 'topic000001')).toEqual({ type: ATV, other: { videoId: 'mv000000001', type: OMV } }); // a queue entry without a pair expect(parseSongPair(j, 'next0000001')).toEqual({ type: ATV, other: null }); // not in the queue at all expect(parseSongPair(j, 'zzzzzzzzzzz')).toEqual({ type: null, other: null }); }); const fakeSource = (pairs: Record, views: Record): ViewsSource & { calls: string[] } => { const calls: string[] = []; return { calls, songPair: async (id) => (calls.push(`pair ${id}`), pairs[id] ?? { type: 'MUSIC_VIDEO_TYPE_UGC', other: null }), viewCount: async (id) => { calls.push(`views ${id}`); if (!(id in views)) throw new Error(`no views ${id}`); return views[id]!; }, }; }; test('fetchDuelViews: either half may be linked; a song with one half keeps that one only', async () => { const src = fakeSource( { lilacTopic1: { type: ATV, other: { videoId: 'lilacMV0001', type: OMV } }, lilacMV0001: { type: OMV, other: { videoId: 'lilacTopic1', type: ATV } }, onlyTopic01: { type: ATV, other: null }, onlyMV00001: { type: OMV, other: null }, }, { lilacTopic1: 153021540, lilacMV0001: 120456643, onlyTopic01: 10, onlyMV00001: 20, fanUpload01: 7 }, ); const both = { state: 'done', topicId: 'lilacTopic1', topicViews: 153021540, mvId: 'lilacMV0001', mvViews: 120456643, error: null, at: 1 }; expect(await fetchDuelViews('lilacTopic1', src, 1)).toEqual(both as DuelViews); expect(await fetchDuelViews('lilacMV0001', src, 1)).toEqual(both as DuelViews); const topicOnly = await fetchDuelViews('onlyTopic01', src, 1); expect(topicOnly).toMatchObject({ topicId: 'onlyTopic01', topicViews: 10, mvId: null, mvViews: null }); const mvOnly = await fetchDuelViews('onlyMV00001', src, 1); expect(mvOnly).toMatchObject({ topicId: null, mvId: 'onlyMV00001', mvViews: 20 }); // any other upload without a 토픽 pair: that video's views expect(await fetchDuelViews('fanUpload01', src, 1)).toMatchObject({ topicId: null, mvId: 'fanUpload01', mvViews: 7 }); // signed in but the video is not in the answer (empty or changed response): unknown, not "토픽 없음" const empty = { ...src, songPair: async () => parseSongPair(watch([]), 'lilacMV0001') }; await expect(fetchDuelViews('lilacMV0001', empty, 1)).rejects.toThrow('곡 정보를 찾지 못했어요'); expect(src.calls.filter((c) => c === 'views lilacMV0001')).toHaveLength(2); // 비고 const it = (viewsAuto: DuelViews | null, views: number | null = 1, fromFile = true) => duelViewsNote({ views, viewsAuto, fromFile }); expect(it(both as DuelViews)).toBeNull(); expect(it(topicOnly)).toBe('MV 없음 (토픽 조회수만)'); expect(it(mvOnly)).toBe('토픽 없음 (MV 조회수만)'); expect(it(null)).toBe('파일에 적힌 조회수'); expect(it(null, 1, false)).toBe('직접 넣은 조회수'); expect(it(null, null)).toBeNull(); }); test('youtubeViewCount: the player count, else the watch page count, else an error', async () => { const fake = (player: unknown, next: string) => (async (url: string) => (String(url).includes('/player') ? Response.json(player) : new Response(next))) as unknown as typeof fetch; expect(await youtubeViewCount('v7bnOxV4jAc', fake({ videoDetails: { videoId: 'v7bnOxV4jAc', viewCount: '120456684' } }, ''))).toBe(120456684); const page = '{"videoViewCountRenderer":{"viewCount":{"simpleText":"조회수 120,456,684회"}}}'; expect(await youtubeViewCount('v7bnOxV4jAc', fake({ playabilityStatus: { status: 'LOGIN_REQUIRED' } }, page))).toBe(120456684); await expect(youtubeViewCount('v7bnOxV4jAc', fake({}, '{}'))).rejects.toThrow('조회수를 찾지 못했어요'); }); // ------------------------------------------------------------------ upload → fetch → editor let s: ReturnType; afterEach(async () => s && (await s.stop())); const row = (videoId: string, title: string, views: number | null = null) => ({ songId: null, videoId, title, artist: '가수', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views, viewsAuto: null, }); async function setup(source: () => Promise) { s = boot({ discordExchange: async (code: string) => ({ id: code, username: 'u', global_name: '관리', avatar: null }), quizAdmin: { viewsSource: source, viewsDelayMs: 0 } }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' }); const sa = (await discordLogin(s.base, TEST_SUPERADMINS[0])).cookie!; const call = (method: string, path: string, body?: unknown) => api(s.base, `/api/admin${path}`, { method, cookie: sa, ...(body ? { body: JSON.stringify(body) } : {}) }); const settled = async (id: number) => { for (let i = 0; i < 200; i++) { const r = await call('GET', `/quizzes/${id}/views`); if (!(r.body.items as { viewsAuto: DuelViews }[]).some((x) => x.viewsAuto.state === 'pending')) break; await Bun.sleep(10); } return (await call('GET', `/quizzes/${id}`)).body.quiz.items as QuizItem[]; }; return { sa, call, settled }; } test('파일로 만들기 without 조회수: the server fetches 토픽 + MV; a number in the file is kept; the editor cannot undo fetched values', async () => { const src = fakeSource( { lilacTopic1: { type: ATV, other: { videoId: 'lilacMV0001', type: OMV } }, onlyTopic01: { type: ATV, other: null }, newTopic001: { type: ATV, other: { videoId: 'newMV000001', type: OMV } }, newMV000001: { type: OMV, other: { videoId: 'newTopic001', type: ATV } }, }, { lilacTopic1: 153021540, lilacMV0001: 120456643, onlyTopic01: 10, newTopic001: 1, newMV000001: 2, manualMV001: 99 }, ); const { call, settled } = await setup(async () => src); const created = await call('POST', '/quizzes/file', { name: '자동 조회수', kind: 'duel', items: [row('lilacTopic1', '라일락'), row('onlyTopic01', '토픽만'), row('manualMV001', '직접', 5000)] }); expect(created.res.status).toBe(200); const id = created.body.id as number; let items = await settled(id); expect(items.map((i) => [i.title, i.views, duelViewsNote(i)])).toEqual([ ['라일락', 273478183, null], ['토픽만', 10, 'MV 없음 (토픽 조회수만)'], ['직접', 5000, '파일에 적힌 조회수'], ]); expect(items[0]!.viewsAuto).toMatchObject({ state: 'done', topicId: 'lilacTopic1', topicViews: 153021540, mvId: 'lilacMV0001', mvViews: 120456643 }); // the number written in the file is never fetched expect(src.calls.some((c) => c.includes('manualMV001'))).toBe(false); // the editor saves an older copy (still waiting, no views): the server keeps what it fetched const quiz = (await call('GET', `/quizzes/${id}`)).body.quiz; const stale = quiz.items.map((it: QuizItem) => (it.viewsAuto ? { ...it, views: null, viewsAuto: { ...it.viewsAuto, state: 'pending' } } : it)); // …and changes the second song's video, adds a song with no views, and types a number for the first stale[1] = { ...stale[1], videoId: 'newTopic001' }; const put = await call('PUT', `/quizzes/${id}`, { ...quiz, items: [...stale, { ...row('lilacTopic1', '중복 아님'), videoId: 'newMV000001', fromFile: false }] }); expect(put.res.status).toBe(200); expect(put.body.quiz.items.map((i: QuizItem) => [i.views, i.viewsAuto?.state ?? null])).toEqual([ [273478183, 'done'], [null, 'pending'], [5000, null], [null, 'pending'], ]); items = await settled(id); expect(items.map((i) => i.views)).toEqual([273478183, 3, 5000, 3]); // 조회수 다시 불러오기: only fetched songs; naming a song switches a written number to 자동 src.calls.length = 0; expect((await call('POST', `/quizzes/${id}/views`, {})).body.queued).toBe(3); await settled(id); expect(src.calls.filter((c) => c.startsWith('pair'))).toHaveLength(3); const manualId = items[2]!.id!; expect((await call('POST', `/quizzes/${id}/views`, { itemIds: [manualId] })).body.queued).toBe(1); items = await settled(id); expect(items[2]).toMatchObject({ views: 99, viewsAuto: { state: 'done', topicId: null, mvId: 'manualMV001' } }); // typing a number in the editor makes it a written one again const now = (await call('GET', `/quizzes/${id}`)).body.quiz; now.items[2] = { ...now.items[2], views: 7, viewsAuto: null }; expect((await call('PUT', `/quizzes/${id}`, now)).body.quiz.items[2]).toMatchObject({ views: 7, viewsAuto: null }); }); test('signed out (or a song that cannot be read): songs are marked failed with the reason and left out until fetched again', async () => { let signedIn = false; const src = fakeSource({ lilacTopic1: { type: ATV, other: { videoId: 'lilacMV0001', type: OMV } } }, { lilacTopic1: 1, lilacMV0001: 2 }); const { call, settled } = await setup(async () => ({ ...src, songPair: async (videoId) => { if (!signedIn) throw new CookieError('유튜브 뮤직 로그인이 풀렸어요 — 쿠키 갱신 필요'); return src.songPair(videoId); }, })); const id = (await call('POST', '/quizzes/file', { name: '쿠키 없음', kind: 'duel', items: [row('lilacTopic1', '라일락'), row('broken00001', '안 읽힘')] })).body.id as number; let items = await settled(id); expect(items.map((i) => [i.views, i.viewsAuto?.state])).toEqual([ [null, 'failed'], [null, 'failed'], ]); expect(duelViewsNote(items[0]!)).toContain('쿠키를 새로 넣은 뒤 다시 불러와 주세요'); // a new cookie, then 다시 불러오기 signedIn = true; expect((await call('POST', `/quizzes/${id}/views`, {})).body.queued).toBe(2); items = await settled(id); expect(items[0]).toMatchObject({ views: 3, viewsAuto: { state: 'done' } }); // UGC without a pair whose views cannot be read: failed with the reason expect(items[1]!.viewsAuto).toMatchObject({ state: 'failed' }); expect(duelViewsNote(items[1]!)).toContain('no views broken00001'); // only 이지선다 quizzes fetch views const normal = (await call('POST', '/quizzes/file', { name: '일반', items: [row('nnnnnnnnn01', '일반곡')] })).body.id as number; expect((await call('POST', `/quizzes/${normal}/views`, {})).res.status).toBe(400); expect((await call('GET', `/quizzes/${normal}`)).body.quiz.items[0]).toMatchObject({ views: null, viewsAuto: null }); }); test('429 from YouTube Music: every waiting song stops with the pause in its note (no retry)', async () => { let n = 0; const src = fakeSource({}, {}); const { call, settled } = await setup(async () => ({ ...src, songPair: async () => { n++; throw new RateLimited(Date.parse('2026-11-03T15:00:00Z')); }, })); const id = (await call('POST', '/quizzes/file', { name: '429', kind: 'duel', items: [row('aaaaaaaaaa1', '하나'), row('aaaaaaaaaa2', '둘')] })).body.id as number; const items = await settled(id); expect(n).toBe(1); expect(items.map((i) => i.viewsAuto?.state)).toEqual(['failed', 'failed']); expect(duelViewsNote(items[1]!)).toContain('00:00까지 쉬어요'); });