diff --git a/apps/server/src/collector/ytmusic.ts b/apps/server/src/collector/ytmusic.ts index cbd689d..ec97936 100644 --- a/apps/server/src/collector/ytmusic.ts +++ b/apps/server/src/collector/ytmusic.ts @@ -78,12 +78,12 @@ export class YtMusic { this.mtime = mtime; } - async searchSongs(query: string): Promise { + private async post(endpoint: 'search' | 'next', body: Record): Promise { await this.reload(); const sapisid = /(?:^|; )SAPISID=([^;]+)/.exec(this.cookie)![1]!; const ts = Math.floor(Date.now() / 1000); const hash = new Bun.CryptoHasher('sha1').update(`${ts} ${sapisid} ${ORIGIN}`).digest('hex'); - const res = await this.fetchImpl(`${ORIGIN}/youtubei/v1/search?prettyPrint=false`, { + const res = await this.fetchImpl(`${ORIGIN}/youtubei/v1/${endpoint}?prettyPrint=false`, { method: 'POST', headers: { 'content-type': 'application/json', @@ -94,17 +94,70 @@ export class YtMusic { 'x-goog-authuser': '0', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36', }, - body: JSON.stringify({ context: { client: { clientName: 'WEB_REMIX', clientVersion: '1.20251015.01.00', hl: 'ko', gl: 'KR' } }, query, params: decodeURIComponent(SONGS_PARAMS) }), + body: JSON.stringify({ context: { client: { clientName: 'WEB_REMIX', clientVersion: '1.20251015.01.00', hl: 'ko', gl: 'KR' } }, ...body }), signal: AbortSignal.timeout(15_000), }); if (res.status === 401 || res.status === 403) throw new CookieError(`유튜브 뮤직 인증 실패(${res.status}) — 쿠키 갱신 필요`); if (res.status === 429) throw new Error('rate limited (429)'); - if (!res.ok) throw new Error(`ytmusic search ${res.status}`); - const json: any = await res.json(); - const loggedIn = JSON.stringify(json?.responseContext?.serviceTrackingParams ?? []).includes('"logged_in","value":"1"'); - if (!loggedIn) throw new CookieError('유튜브 뮤직 로그인이 풀렸어요 — 쿠키 갱신 필요'); + if (!res.ok) throw new Error(`ytmusic ${endpoint} ${res.status}`); + return res.json(); + } + + async searchSongs(query: string): Promise { + const json = await this.post('search', { query, params: decodeURIComponent(SONGS_PARAMS) }); + if (!loggedIn(json)) throw new CookieError('유튜브 뮤직 로그인이 풀렸어요 — 쿠키 갱신 필요'); return parseSearch(json); } + + /** The 노래 ↔ 동영상 pair of a video (이지선다 조회수 자동): what the video is and the other half, if YouTube Music has one. */ + async songPair(videoId: string): Promise { + const json = await this.post('next', { + videoId, + playlistId: `RDAMVM${videoId}`, + isAudioOnly: true, + enablePersistentPlaylistPanel: true, + tunerSettingValue: 'AUTOMIX_SETTING_NORMAL', + watchEndpointMusicSupportedConfigs: { watchEndpointMusicConfig: { hasPersistentPlaylistPanel: true, musicVideoType: 'MUSIC_VIDEO_TYPE_ATV' } }, + }); + const pair = parseSongPair(json, videoId); + // signed out, YouTube Music sends the queue without the pairs + if (!pair.other && !loggedIn(json)) throw new CookieError('유튜브 뮤직 로그인이 풀렸어요 — 쿠키 갱신 필요'); + return pair; + } +} + +const loggedIn = (json: any) => JSON.stringify(json?.responseContext?.serviceTrackingParams ?? []).includes('"logged_in","value":"1"'); + +/** ATV = 토픽 (art track, the 노래 side) · OMV = official music video · UGC = other uploads · … */ +export interface SongPair { + type: string | null; + other: { videoId: string; type: string | null } | null; +} + +const videoType = (r: any): string | null => r?.navigationEndpoint?.watchEndpoint?.watchEndpointMusicSupportedConfigs?.watchEndpointMusicConfig?.musicVideoType ?? null; + +/** + * The queue of a watch response: each entry is a playlistPanelVideoRenderer, or for songs that have both halves a + * playlistPanelVideoWrapperRenderer with the one asked for (primaryRenderer) and its counterpart. The entry of `videoId`. + */ +export function parseSongPair(json: unknown, videoId: string): SongPair { + const entries: any[] = []; + const walk = (v: unknown) => { + if (!v || typeof v !== 'object') return; + if (Array.isArray(v)) return v.forEach(walk); + const o = v as Record; + if (o.playlistPanelVideoWrapperRenderer || o.playlistPanelVideoRenderer) return void entries.push(o); + for (const x of Object.values(o)) walk(x); + }; + walk(json); + for (const e of entries) { + const w = e.playlistPanelVideoWrapperRenderer; + const self = w ? w.primaryRenderer?.playlistPanelVideoRenderer : e.playlistPanelVideoRenderer; + if (self?.videoId !== videoId) continue; + const c = w?.counterpart?.[0]?.counterpartRenderer?.playlistPanelVideoRenderer; + return { type: videoType(self), other: c?.videoId && c.videoId !== videoId ? { videoId: c.videoId, type: videoType(c) } : null }; + } + return { type: null, other: null }; } /** diff --git a/apps/server/src/db/migrations/014_duel_views.sql b/apps/server/src/db/migrations/014_duel_views.sql new file mode 100644 index 0000000..5e84ff3 --- /dev/null +++ b/apps/server/src/db/migrations/014_duel_views.sql @@ -0,0 +1,2 @@ +-- 이지선다 조회수 자동: the 토픽 + MV views the server fetched (JSON DuelViews); NULL = written by hand / in the file +ALTER TABLE custom_quiz_items ADD COLUMN views_auto TEXT; diff --git a/apps/server/src/duel-views.test.ts b/apps/server/src/duel-views.test.ts new file mode 100644 index 0000000..96154bf --- /dev/null +++ b/apps/server/src/duel-views.test.ts @@ -0,0 +1,211 @@ +/** 이지선다 조회수 자동: 토픽 ↔ 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, 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 }); + // 비고 + 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); + 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 }); +}); diff --git a/apps/server/src/duel.test.ts b/apps/server/src/duel.test.ts index 8d7930a..2c90eaf 100644 --- a/apps/server/src/duel.test.ts +++ b/apps/server/src/duel.test.ts @@ -35,8 +35,8 @@ async function setup() { s = boot({ gameTiming: { countdownMs: 40, revealMs: 120, resumeLeadMs: 30, clipGraceMs: 150, lateMs: 150, tickMs: 20, limitMs: 400 }, discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' }); const sa = (await discordLogin(s.base, TEST_SUPERADMINS[0])).cookie!; const file = (body: Record) => api(s.base, '/api/admin/quizzes/file', { method: 'POST', cookie: sa, body: JSON.stringify(body) }); - // views are required for an 이지선다 quiz - expect((await file({ name: 'x', kind: 'duel', items: [{ ...duelItem('vvvvvvvvv01'), views: null }, duelItem('vvvvvvvvv02')] })).res.status).toBe(400); + // an 이지선다 quiz needs 2 songs or more + expect((await file({ name: 'x', kind: 'duel', items: [duelItem('vvvvvvvvv01')] })).res.status).toBe(400); const duel = await file({ name: '조회수 대결', kind: 'duel', items: Object.keys(VIEWS).map(duelItem) }); expect(duel.res.status).toBe(200); const normal = await file({ name: '일반 퀴즈', items: [{ ...duelItem('nnnnnnnnn01'), views: 5 }] }); diff --git a/apps/server/src/http/admin-quizzes.ts b/apps/server/src/http/admin-quizzes.ts index 5711391..9403c16 100644 --- a/apps/server/src/http/admin-quizzes.ts +++ b/apps/server/src/http/admin-quizzes.ts @@ -15,6 +15,7 @@ import { audioFile, type AudioLinks } from '../songs/audio'; import { getImportJob, startImport, type Lavalink } from '../quizzes/playlist'; import { applyReview, listReviews, pendingCount, rejectReview, syncReviews } from '../quizzes/review'; import { checkEmbed, type EmbedState } from '../collector/oembed'; +import { DuelViewsJob, type ViewsSource } from '../quizzes/duel-views'; type Env = { Variables: { userId: string | null; role: Role } }; @@ -33,6 +34,9 @@ export interface QuizAdminDeps { importDelayMs?: number; videoOf: (url: string) => Promise<{ id: string; author: string; title: string } | string>; onChange?: () => void; + /** 이지선다 조회수 자동: where pairs and view counts come from (tests inject a fake) and the pause between songs. */ + viewsSource?: () => Promise; + viewsDelayMs?: number; } let searcher: Promise<(q: string) => Promise> | null = null; @@ -46,6 +50,9 @@ function defaultSearch(q: string): Promise { } export function mountQuizAdmin(app: Hono, d: QuizAdminDeps, h: { actor: (c: Context) => string; body: (c: Context) => Promise }) { + // 이지선다 조회수 자동: songs left waiting by a restart go on right away + const views = new DuelViewsJob(d.db, d.viewsSource, { delayMs: d.viewsDelayMs, retryMs: d.viewsDelayMs, onChange: d.onChange }); + views.kick(); const mine = (c: Context) => { const q = d.quizzes.row(Number(c.req.param('id'))); if (!q) return null; @@ -71,18 +78,19 @@ export function mountQuizAdmin(app: Hono, d: QuizAdminDeps, h: { actor: (c: if (!p.success) return c.json({ error: `만들 내용이 올바르지 않아요: ${p.error.issues.slice(0, 3).map((i) => i.path.join('.') || i.message).join(', ')}` }, 400); const duel = p.data.kind === 'duel'; if (duel && p.data.items.length < 2) return c.json({ error: '이지선다 퀴즈에는 곡이 2곡 이상 있어야 해요.' }, 400); - if (duel && p.data.items.some((it) => it.views === null)) return c.json({ error: '이지선다 퀴즈의 곡에는 모두 조회수가 있어야 해요.' }, 400); const limits = d.limits(); if (limits.maxSongs && p.data.items.length > limits.maxSongs) return c.json({ error: `퀴즈 하나에는 곡을 ${limits.maxSongs}곡까지 넣을 수 있어요.` }, 400); const id = d.quizzes.create(h.actor(c), p.data.name, limits, Date.now(), p.data.kind); if (typeof id === 'string') return c.json({ error: id }, 400); - const items = p.data.items.map((it) => ({ ...it, id: undefined, songId: null, fromFile: true, ...(duel ? {} : { views: null }) })); + // 이지선다: a 조회수 written in the file is used as is, the others are fetched (토픽 + MV) after saving + const items = p.data.items.map((it) => ({ ...it, id: undefined, songId: null, fromFile: true, viewsAuto: null, ...(duel ? {} : { views: null }) })); // songs with their own hints: hints come by vote unless the maker changes it in 설정 const settings = { ...DEFAULT_QUIZ_SETTINGS, ...(items.some((it) => it.hints.length) ? { hint: 'manual' as const } : {}) }; const saved = d.quizzes.save(id, { name: p.data.name, description: '', visibility: 'private', settings, items }, limits); if (typeof saved === 'string') return c.json({ error: saved }, 400); d.audit.log(h.actor(c), 'quiz.create', String(id), null, { name: p.data.name, songs: items.length, from: 'file', kind: p.data.kind }); d.onChange?.(); + if (duel) views.kick(); return c.json({ id }); }); @@ -255,9 +263,30 @@ export function mountQuizAdmin(app: Hono, d: QuizAdminDeps, h: { actor: (c: const reviews = syncReviews(d.db, q.id); d.audit.log(h.actor(c), 'quiz.save', String(q.id), { name: q.name, songs: q.songs, visibility: q.visibility }, { name: saved.name, songs: saved.items.length, visibility: saved.visibility }); d.onChange?.(); + if (q.kind === 'duel') views.kick(); return c.json({ quiz: saved, reviews }); }); + /** 이지선다 조회수 자동: where each fetched song stands (the editor polls this while songs are waiting). */ + app.get('/quizzes/:id/views', (c) => { + const q = mine(c); + if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404); + const items = d.quizzes.items(q.id).flatMap((it) => (it.viewsAuto ? [{ id: it.id!, videoId: it.videoId, views: it.views, viewsAuto: it.viewsAuto }] : [])); + return c.json({ items }); + }); + + /** 조회수 다시 불러오기: every fetched song of the saved quiz, or the songs named (which then switch from a written number to 자동). */ + app.post('/quizzes/:id/views', async (c) => { + const q = mine(c); + if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404); + if (q.kind !== 'duel') return c.json({ error: '이지선다 퀴즈에서만 조회수를 불러와요.' }, 400); + const p = z.object({ itemIds: z.array(z.number().int().positive()).max(5000).optional() }).safeParse(await h.body(c)); + if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400); + const queued = views.refresh(q.id, p.data.itemIds); + d.audit.log(h.actor(c), 'quiz.views', String(q.id), null, { queued, items: p.data.itemIds?.length ?? 'all' }); + return c.json({ queued }); + }); + app.delete('/quizzes/:id', (c) => { const q = mine(c); if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404); diff --git a/apps/server/src/http/admin.ts b/apps/server/src/http/admin.ts index 7239569..88c238a 100644 --- a/apps/server/src/http/admin.ts +++ b/apps/server/src/http/admin.ts @@ -46,6 +46,9 @@ export interface AdminDeps { importDelayMs?: number; /** 연령제한 곡's downloaded audio, for the quiz editor's position bar. */ audio?: AudioLinks; + /** 이지선다 조회수 자동 (tests inject a fake source). */ + viewsSource?: () => Promise; + viewsDelayMs?: number; } type Env = { Variables: { userId: string | null; role: Role } }; @@ -129,6 +132,8 @@ export function createAdminApp(d: AdminDeps) { lavalink: d.lavalink, lavalinkFetch: d.lavalinkFetch, importDelayMs: d.importDelayMs, + viewsSource: d.viewsSource, + viewsDelayMs: d.viewsDelayMs, videoOf, }, { actor, body }, diff --git a/apps/server/src/quizzes/duel-views.ts b/apps/server/src/quizzes/duel-views.ts new file mode 100644 index 0000000..28d2d8d --- /dev/null +++ b/apps/server/src/quizzes/duel-views.ts @@ -0,0 +1,148 @@ +/** + * 이지선다 조회수 자동 (docs/12 이지선다 7): a song's views = its 토픽 음원 (art track) + its MV. + * YouTube Music pairs the two (the 노래 ↔ 동영상 switch); that pair needs the signed-in cookie. The view counts themselves + * come from plain YouTube without login. Songs wait as `views_auto.state = 'pending'` and are fetched one by one in the + * background, so the work goes on after a restart; the editor polls the result. + */ +import type { Database } from 'bun:sqlite'; +import { PENDING_VIEWS, type DuelViews } from '@mq/shared'; +import { CookieError, YtMusic, type SongPair } from '../collector/ytmusic'; +import type { LogFn } from '../server'; + +export interface ViewsSource { + songPair(videoId: string): Promise; + viewCount(videoId: string): Promise; +} + +const TOPIC = 'MUSIC_VIDEO_TYPE_ATV'; +const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36'; + +/** The linked video may be either half: a 토픽 pairs with its MV, anything else (MV, other upload) with its 토픽. */ +export async function fetchDuelViews(videoId: string, src: ViewsSource, now = Date.now()): Promise { + const pair = await src.songPair(videoId); + const selfTopic = pair.type === TOPIC; + const topicId = selfTopic ? videoId : pair.other?.type === TOPIC ? pair.other.videoId : null; + const mvId = !selfTopic ? videoId : pair.other && pair.other.type !== TOPIC ? pair.other.videoId : null; + const [topicViews, mvViews] = await Promise.all([topicId ? src.viewCount(topicId) : null, mvId ? src.viewCount(mvId) : null]); + return { state: 'done', topicId, topicViews, mvId, mvViews, error: null, at: now }; +} + +export const totalViews = (v: DuelViews) => (v.topicViews ?? 0) + (v.mvViews ?? 0); + +/** Exact view count of one video: the player's videoDetails (also given for videos that cannot be embedded), else the watch page's count. */ +export async function youtubeViewCount(videoId: string, fetchImpl: typeof fetch = fetch): Promise { + const call = (endpoint: 'player' | 'next') => + fetchImpl(`https://www.youtube.com/youtubei/v1/${endpoint}?prettyPrint=false`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'user-agent': UA }, + body: JSON.stringify({ context: { client: { clientName: 'WEB', clientVersion: '2.20261031.01.00', hl: 'ko', gl: 'KR' } }, videoId }), + signal: AbortSignal.timeout(15_000), + }); + const player = await call('player'); + if (player.ok) { + const j: any = await player.json(); + const n = j?.videoDetails?.videoId === videoId ? j.videoDetails.viewCount : undefined; + if (typeof n === 'string' && /^\d+$/.test(n)) return Number(n); + } + const next = await call('next'); + if (next.ok) { + const text = await next.text(); + const m = /"videoViewCountRenderer":\{"viewCount":\{"simpleText":"([^"]+)"/.exec(text); + const digits = m?.[1]?.replace(/\D/g, ''); + if (digits) return Number(digits); + } + throw new Error(`조회수를 찾지 못했어요 (${videoId})`); +} + +/** Production source: the cookie file (read again when it changes) for the pair, plain YouTube for the numbers. */ +export async function defaultViewsSource(): Promise { + const path = process.env.YT_COOKIE_PATH ?? '/run/secrets/music_quiz/ytm_cookie.txt'; + let ytm: YtMusic; + try { + ytm = await YtMusic.fromFile(path); + } catch (e) { + throw e instanceof CookieError ? e : new CookieError(`유튜브 뮤직 쿠키 파일을 읽지 못했어요 (${(e as Error).message})`); + } + return { songPair: (id) => ytm.songPair(id), viewCount: (id) => youtubeViewCount(id) }; +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const PENDING = "json_extract(views_auto, '$.state') = 'pending'"; + +export class DuelViewsJob { + private running: Promise | null = null; + private again = false; + + constructor( + private db: Database, + private source: () => Promise = defaultViewsSource, + private opts: { delayMs?: number; retryMs?: number; log?: LogFn; onChange?: () => void } = {}, + ) {} + + /** Starts working through the waiting songs (again after the current run when it is already busy). */ + kick(): void { + if (this.running) { + this.again = true; + return; + } + this.running = (async () => { + do { + this.again = false; + await this.drain(); + } while (this.again); + })() + .catch((e) => this.opts.log?.('error', 'duel views', { err: String(e) })) + .finally(() => (this.running = null)); + } + + /** Resolves when nothing is being fetched (tests). */ + async idle(): Promise { + while (this.running) await this.running; + } + + /** Marks songs of a quiz to be fetched again (only fetched ones unless `itemIds` names songs, which then switch to 자동). */ + refresh(quizId: number, itemIds?: number[]): number { + const pending = JSON.stringify(PENDING_VIEWS); + const n = itemIds + ? itemIds.reduce((sum, id) => sum + this.db.query('UPDATE custom_quiz_items SET views_auto = ? WHERE quiz_id = ? AND id = ?').run(pending, quizId, id).changes, 0) + : this.db.query('UPDATE custom_quiz_items SET views_auto = ? WHERE quiz_id = ? AND views_auto IS NOT NULL').run(pending, quizId).changes; + if (n) this.kick(); + return n; + } + + private async drain(): Promise { + const next = this.db.query<{ id: number; video_id: string }, []>(`SELECT id, video_id FROM custom_quiz_items WHERE ${PENDING} ORDER BY id LIMIT 1`); + // only while the row still waits for this very video (the editor may have changed it meanwhile) + const write = this.db.query(`UPDATE custom_quiz_items SET views = ?, views_auto = ? WHERE id = ? AND video_id = ? AND ${PENDING}`); + let src: ViewsSource | null = null; + let changed = false; + for (let row = next.get(); row; row = next.get()) { + let result: DuelViews; + try { + src ??= await this.source(); + result = await fetchDuelViews(row.video_id, src).catch(async (e) => { + if (e instanceof CookieError) throw e; + await sleep(this.opts.retryMs ?? 3000); + return fetchDuelViews(row!.video_id, src!); + }); + } catch (e) { + if (e instanceof CookieError) { + // every waiting song would fail the same way: they wait for 다시 불러오기 after a new cookie + const failed = JSON.stringify(failure(`유튜브 뮤직 로그인이 필요해요 — 쿠키를 새로 넣은 뒤 다시 불러와 주세요 (${e.message})`)); + this.db.query(`UPDATE custom_quiz_items SET views_auto = ? WHERE ${PENDING}`).run(failed); + this.opts.log?.('warn', 'duel views: cookie', { message: e.message }); + break; + } + result = failure(`조회수를 불러오지 못했어요: ${(e as Error).message}`.slice(0, 300)); + } + const views = result.state === 'done' ? totalViews(result) : null; + if (views !== null) write.run(views, JSON.stringify(result), row.id, row.video_id); + else this.db.query(`UPDATE custom_quiz_items SET views_auto = ? WHERE id = ? AND video_id = ? AND ${PENDING}`).run(JSON.stringify(result), row.id, row.video_id); + changed = true; + await sleep(this.opts.delayMs ?? 500); + } + if (changed) this.opts.onChange?.(); + } +} + +const failure = (error: string): DuelViews => ({ state: 'failed', topicId: null, topicViews: null, mvId: null, mvViews: null, error, at: Date.now() }); diff --git a/apps/server/src/quizzes/store.ts b/apps/server/src/quizzes/store.ts index 0562900..bf70c0c 100644 --- a/apps/server/src/quizzes/store.ts +++ b/apps/server/src/quizzes/store.ts @@ -3,7 +3,7 @@ * Saving is all at once (the editor saves by hand): name, settings, visibility and the whole song list. */ import type { Database } from 'bun:sqlite'; -import { parseQuizSettings, type QuizDetail, type QuizItem, type QuizKind, type QuizSave, type QuizSummary, type QuizVisibility, type Role } from '@mq/shared'; +import { PENDING_VIEWS, parseQuizSettings, type DuelViews, type QuizDetail, type QuizItem, type QuizKind, type QuizSave, type QuizSummary, type QuizVisibility, type Role } from '@mq/shared'; interface QuizRow { id: number; @@ -34,9 +34,10 @@ interface ItemRow { start_sec: number | null; highlight_sec: number | null; views: number | null; + views_auto: string | null; } -const ITEM_COLS = 'id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec, views'; +const ITEM_COLS = 'id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec, views, views_auto'; const SELECT = `SELECT q.id, q.kind, q.owner_id, u.nickname owner_name, q.name, q.description, q.visibility, q.settings_json, q.plays, q.updated_at, (SELECT COUNT(*) FROM custom_quiz_items i WHERE i.quiz_id = q.id) songs @@ -76,6 +77,7 @@ const item = (r: ItemRow): QuizItem => ({ startSec: r.start_sec, highlightSec: r.highlight_sec, views: r.views, + viewsAuto: r.views_auto ? (JSON.parse(r.views_auto) as DuelViews) : null, }); /** Who may pick a quiz for a room: 비공개 the maker, 일부공개 the maker and admins, 전체공개 everyone. */ @@ -140,30 +142,44 @@ export class CustomQuizzes { /** * Saves everything the editor holds. Items keep their id (sent back), new ones get one; missing ones are removed. * Extra answers of songs that are in the server DB also become that song's aliases (source 'quiz'). + * 이지선다: views written by hand are kept as sent; the others are the server's (조회수 자동) — a song that is new, has a + * different video or had none waits to be fetched (`pending`), the rest keep what the server has (the editor's copy may be older). * Returns the saved quiz or an error message. */ save(id: number, data: QuizSave, limits: QuizLimits, now = Date.now()): QuizDetail | string { if (limits.maxSongs && data.items.length > limits.maxSongs) return `퀴즈 하나에는 곡을 ${limits.maxSongs}곡까지 넣을 수 있어요.`; const existing = new Set(this.db.query<{ id: number }, [number]>('SELECT id FROM custom_quiz_items WHERE quiz_id = ?').all(id).map((r) => r.id)); const songExists = this.db.query<{ n: number }, [number]>('SELECT COUNT(*) n FROM songs WHERE id = ? AND deleted_at IS NULL'); + const duel = this.db.query<{ kind: QuizKind }, [number]>('SELECT kind FROM custom_quizzes WHERE id = ?').get(id)?.kind === 'duel'; + const serverViews = this.db.query<{ video_id: string; views: number | null; views_auto: string | null }, [number, number]>( + 'SELECT video_id, views, views_auto FROM custom_quiz_items WHERE id = ? AND quiz_id = ?', + ); + const viewsOf = (it: QuizSave['items'][number]): [number | null, string | null] => { + if (!duel) return [null, null]; + if (it.views !== null && !it.viewsAuto) return [it.views, null]; + const old = it.id ? serverViews.get(it.id, id) : null; + if (old?.views_auto && old.video_id === it.videoId) return [old.views, old.views_auto]; + return [null, JSON.stringify(PENDING_VIEWS)]; + }; this.db.transaction(() => { this.db .query('UPDATE custom_quizzes SET name = ?, description = ?, visibility = ?, settings_json = ?, updated_at = ? WHERE id = ?') .run(data.name, data.description, data.visibility, JSON.stringify(data.settings), now, id); const keep = new Set(); const ins = this.db.query( - `INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec, views) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + `INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec, views, views_auto) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ); const upd = this.db.query( `UPDATE custom_quiz_items SET pos = ?, song_id = ?, video_id = ?, title = ?, artist = ?, title_answers = ?, artist_answers = ?, hints = ?, from_file = ?, duration_sec = ?, auto = ?, - start_sec = ?, highlight_sec = ?, views = ? WHERE id = ? AND quiz_id = ?`, + start_sec = ?, highlight_sec = ?, views = ?, views_auto = ? WHERE id = ? AND quiz_id = ?`, ); const alias = this.db.query("INSERT OR IGNORE INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, 'quiz')"); for (const [pos, it] of data.items.entries()) { const songId = it.songId && songExists.get(it.songId)!.n ? it.songId : null; const titleAnswers = [...new Set(it.titleAnswers)]; const artistAnswers = [...new Set(it.artistAnswers)]; + const [views, viewsAuto] = viewsOf(it); const args = [ songId, it.videoId, @@ -177,7 +193,8 @@ export class CustomQuizzes { it.auto ? 1 : 0, it.auto ? null : it.startSec, it.auto ? null : it.highlightSec, - it.views ?? null, + views, + viewsAuto, ] as const; if (it.id && existing.has(it.id)) { upd.run(pos, ...args, it.id, id); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 5fd962c..fb4d573 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -44,7 +44,7 @@ export interface StartOptions { /** Quiz editor externals (YouTube search, Lavalink playlists); tests inject fakes. */ /** 유튜브 뮤직 쿠키 상태 for 관리자 → 수집 (index.ts starts the keeper in production). */ cookieStatus?: () => import('./collector/cookie-keeper').CookieStatus; - quizAdmin?: Pick; + quizAdmin?: Pick; } export function startServer(opts: StartOptions) { diff --git a/apps/web/src/components/RoomSettings.tsx b/apps/web/src/components/RoomSettings.tsx index ce58647..8bf8592 100644 --- a/apps/web/src/components/RoomSettings.tsx +++ b/apps/web/src/components/RoomSettings.tsx @@ -292,7 +292,7 @@ export function RoomSettings({ /> {allowQuiz && duel && ( -
+
onPatch({ quizId })} />
)} @@ -642,7 +642,7 @@ function QuizPicker({ kind, chosen, songs, ro, onPick }: { kind: QuizKind; chose
{list?.length === 0 && ( - {q.trim() ? '검색 결과가 없어요.' : kind === 'duel' ? '고를 수 있는 이지선다 퀴즈가 없어요. 관리자 → 퀴즈 → 파일로 만들기에서 조회수가 든 파일로 만들 수 있어요.' : '고를 수 있는 퀴즈가 없어요.'} + {q.trim() ? '검색 결과가 없어요.' : kind === 'duel' ? '고를 수 있는 이지선다 퀴즈가 없어요. 관리자 → 퀴즈 → 파일로 만들기에서 이지선다로 만들 수 있어요.' : '고를 수 있는 퀴즈가 없어요.'} )} {list?.map((x) => ( diff --git a/apps/web/src/pages/admin/QuizFile.tsx b/apps/web/src/pages/admin/QuizFile.tsx index 6c9c8d5..301bd03 100644 --- a/apps/web/src/pages/admin/QuizFile.tsx +++ b/apps/web/src/pages/admin/QuizFile.tsx @@ -84,8 +84,8 @@ export function QuizFileImport({ setHeaderAt(h); const cols = guessColumns(rows[h] ?? []); setColumns(cols); - // a 조회수 column: this is an 이지선다 file - if (!fixedKind) setChosenKind(cols.includes('views') ? 'duel' : 'normal'); + // a 조회수 column: this is an 이지선다 file (without one the kind picked above stays: the 이지선다 양식 has none) + if (!fixedKind && cols.includes('views')) setChosenKind('duel'); }; const open = async (f: File) => { if (f.size > MAX_BYTES) return toast('파일이 너무 커요(20MB까지).', 'error'); @@ -105,7 +105,7 @@ export function QuizFileImport({ const sheet = file?.sheets[sheetIdx]; const header = sheet?.rows[headerAt] ?? []; const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt, kind) : null), [sheet, columns, headerAt, kind]); - const missing = (kind === 'duel' ? (['link', 'answer', 'views'] as const) : (['link', 'answer'] as const)).filter((c) => !columns.includes(c)); + const missing = (['link', 'answer'] as const).filter((c) => !columns.includes(c)); const duel = kind === 'duel'; const bad = parsed?.rows.filter((r) => r.problem) ?? []; const items = parsed?.items ?? []; @@ -178,8 +178,9 @@ export function QuizFileImport({
{!file && duel && (

- 한 줄에 한 곡씩, 첫 줄은 열 이름이에요. 유튜브 영상 링크, 제목, 조회수는 꼭 있어야 하고 가수는 카드에 같이 보여요. 조회수는 1234567, 1,234,567, - 123만, 1.2억처럼 써도 돼요. 게임에서는 곡을 무작위로 두 개씩 짝지어 A/B 카드로 보여 줘요. + 한 줄에 한 곡씩, 첫 줄은 열 이름이에요. 유튜브 영상 링크와 제목은 꼭 있어야 하고 가수는 카드에 같이 보여요. 조회수는 올린 뒤 서버가 곡마다 + 유튜브 뮤직의 토픽 음원 + MV 조회수를 더해 불러와요(링크는 토픽이든 MV든 괜찮아요). 직접 정한 숫자를 쓰려면 조회수 열에 1234567, 123만, 1.2억처럼 적으면 그 숫자를 + 그대로 써요. 게임에서는 곡을 무작위로 두 개씩 짝지어 A/B 카드로 보여 줘요.

)} {!file && !duel && ( @@ -279,8 +280,8 @@ export function QuizFileImport({ {it.artist || -} {duel ? ( - - {viewsLabel(it.views ?? 0)}회 + + {it.views !== null ? `${viewsLabel(it.views)}회` : 자동} ) : ( {[...it.hints, '초성'].join(' → ')} diff --git a/apps/web/src/pages/admin/QuizzesPage.tsx b/apps/web/src/pages/admin/QuizzesPage.tsx index 50cc6e3..77fe1d7 100644 --- a/apps/web/src/pages/admin/QuizzesPage.tsx +++ b/apps/web/src/pages/admin/QuizzesPage.tsx @@ -10,10 +10,13 @@ import { DUEL_FLOWS, DUEL_SECS, LISTEN_SECS, + PENDING_VIEWS, QUIZ_VISIBILITIES, + duelViewsNote, listenLabel, parseViews, viewsLabel, + type DuelViews, type QuizDetail, type QuizItem, type QuizKind, @@ -70,8 +73,8 @@ export function QuizzesPage() { )}

- 직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 조회수가 든 파일로 만들고, 이지선다 - 모드에서만 쓸 수 있어요. + 직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 파일로 만들고(조회수는 + 서버가 토픽 + MV로 불러와요), 이지선다 모드에서만 쓸 수 있어요.

{fromFile && ( ; -const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null, views: null }); +type NewSong = Omit; +const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null, views: null, viewsAuto: null }); + +/** 이지선다 조회수 자동: what the server fetched, put into the editor's copy (songs still 자동 there with the same video). */ +type FetchedViews = { id: number; videoId: string; views: number | null; viewsAuto: DuelViews }; +function withFetched(items: T[], fetched: FetchedViews[]): T[] { + const by = new Map(fetched.map((f) => [f.id, f])); + return items.map((it) => { + const f = it.id ? by.get(it.id) : undefined; + return f && it.viewsAuto && f.videoId === it.videoId ? { ...it, views: f.views, viewsAuto: f.viewsAuto } : it; + }); +} let keySeq = 0; const newKey = () => `k${++keySeq}`; @@ -236,6 +249,46 @@ export function QuizEditor() { setBusy(false); } }, [id]); + // 이지선다 조회수 자동: while songs wait, the server's results are taken in (also into the saved copy: not a change) + const waiting = !!draft?.items.some((i) => i.viewsAuto?.state === 'pending'); + useEffect(() => { + if (!waiting) return; + const t = setInterval(() => { + apiCall<{ items: FetchedViews[] }>('GET', `/api/admin/quizzes/${id}/views`) + .then((r) => { + setDraft((d) => (d ? { ...d, items: withFetched(d.items, r.items) } : d)); + setSaved((json) => { + if (!json) return json; + const p = JSON.parse(json) as ReturnType; + return JSON.stringify({ ...p, items: withFetched(p.items, r.items) }); + }); + }) + .catch(() => {}); + }, 2000); + return () => clearInterval(t); + }, [waiting, id]); + const refreshViews = useCallback( + async (itemIds?: number[]) => { + try { + const r = await apiCall<{ queued: number }>('POST', `/api/admin/quizzes/${id}/views`, itemIds ? { itemIds } : {}); + if (!r.queued) return toast('다시 불러올 곡이 없어요. 새로 넣은 곡은 저장하면 불러와요.'); + const ids = itemIds ? new Set(itemIds) : null; + // waiting from now on (a written number named here becomes 자동): the poll above brings the results + const mark = (items: T[]) => + items.map((it) => (it.id && (ids ? ids.has(it.id) : it.viewsAuto) ? { ...it, viewsAuto: { ...(it.viewsAuto ?? PENDING_VIEWS), state: 'pending' as const } } : it)); + setDraft((d) => (d ? { ...d, items: mark(d.items) } : d)); + setSaved((json) => { + if (!json) return json; + const p = JSON.parse(json) as ReturnType; + return JSON.stringify({ ...p, items: mark(p.items) }); + }); + toast(`${r.queued}곡의 조회수를 다시 불러와요.`); + } catch (e) { + toast((e as Error).message, 'error'); + } + }, + [id], + ); // DB facts (aliases, the DB highlight for 자동) of songs added since loading: fetched as soon as they appear const asked = useRef(new Set()); useEffect(() => { @@ -312,6 +365,17 @@ export function QuizEditor() {

{draft.name || '이름 없는 퀴즈'}

{dirty ? ● 저장하지 않은 변경이 있어요 : 저장됨} + {kind === 'duel' && ( + + )} @@ -361,6 +425,7 @@ export function QuizEditor() { fileOpen={fileOpen} setFileOpen={setFileOpen} onHints={() => draft.settings.hint === 'none' && set({ settings: { ...draft.settings, hint: 'manual' } })} + onRefreshViews={(itemId) => void refreshViews([itemId])} /> ) : ( setConfirmDelete(true)} /> @@ -466,6 +531,7 @@ function SongsTab({ fileOpen, setFileOpen, onHints, + onRefreshViews, }: { kind: QuizKind; items: DraftItem[]; @@ -478,6 +544,7 @@ function SongsTab({ setFileOpen: (on: boolean) => void; /** Songs with their own hints came in: hints should not stay off. */ onHints: () => void; + onRefreshViews: (itemId: number) => void; }) { const [sel, setSel] = useState(null); const [dragKey, setDragKey] = useState(null); @@ -551,9 +618,15 @@ function SongsTab({

아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.

) : (
- {duel && items.some((i) => i.views === null) && ( + {duel && items.some((i) => i.viewsAuto?.state === 'pending') && ( +

+ ⏳ 토픽·MV 조회수를 불러오는 중이에요 ({items.filter((i) => i.viewsAuto?.state === 'pending').length}곡 남음). 다 불러오면 저절로 채워져요. +

+ )} + {duel && items.some((i) => i.views === null && i.viewsAuto?.state !== 'pending') && (

- 조회수가 없는 곡 {items.filter((i) => i.views === null).length}곡은 게임에 나오지 않아요. 곡을 눌러 조회수를 넣어 주세요. + 조회수가 없는 곡 {items.filter((i) => i.views === null && i.viewsAuto?.state !== 'pending').length}곡은 게임에 나오지 않아요. 곡을 눌러 조회수를 직접 넣거나 다시 + 불러와 주세요.{items.some((i) => i.views === null && !i.viewsAuto) && ' 새로 넣은 곡은 저장하면 불러와요.'}

)} @@ -563,6 +636,7 @@ function SongsTab({ + {duel && } + <> + + + ) : ( )} @@ -649,6 +726,7 @@ function SongsTab({ onRemove={() => remove(selected.key)} onClose={() => setSel(null)} isDuplicate={(videoId) => items.some((x) => x.key !== selected.key && x.videoId === videoId)} + onRefreshViews={selected.id ? () => onRefreshViews(selected.id!) : null} /> )} @@ -1038,6 +1116,24 @@ function ChipsInput({ values, onChange, label, placeholder }: { values: string[] ); } +/** 이지선다 조회수 칸: the number the game uses, how it stands when fetched (토픽 · MV each). */ +function ViewsCell({ item }: { item: QuizItem }) { + const a = item.viewsAuto; + const total = item.views !== null ? `${viewsLabel(item.views)}회` : null; + if (a?.state === 'pending') return 불러오는 중…{total && ` (${total})`}; + if (item.views === null) return a ? 없음 : 저장하면 불러와요; + return ( + <> + {total} + {a?.state === 'done' && ( +
{[a.topicViews !== null && `토픽 ${viewsLabel(a.topicViews)}`, a.mvViews !== null && `MV ${viewsLabel(a.mvViews)}`].filter(Boolean).join(' · ')}
+ )} + + ); +} + +const fullViews = (n: number | null) => (n === null ? '-' : `${n.toLocaleString('ko-KR')}회`); + function ItemPanel({ duel, item, @@ -1050,6 +1146,7 @@ function ItemPanel({ onRemove, onClose, isDuplicate, + onRefreshViews, }: { duel: boolean; item: DraftItem; @@ -1063,12 +1160,20 @@ function ItemPanel({ onRemove: () => void; onClose: () => void; isDuplicate: (videoId: string) => boolean; + /** 이지선다: fetch this saved song's views again (null: not saved yet — saving fetches them). */ + onRefreshViews: (() => void) | null; }) { const [url, setUrl] = useState(''); const [pos, setPos] = useState(String(index + 1)); useEffect(() => setPos(String(index + 1)), [index]); - const [viewsText, setViewsText] = useState(item.views === null ? '' : String(item.views)); + // 자동 songs show the fetched numbers above; the box is for a number of one's own + const [viewsText, setViewsText] = useState(item.viewsAuto || item.views === null ? '' : String(item.views)); + const isAuto = !!item.viewsAuto; + useEffect(() => { + if (isAuto) setViewsText(''); + }, [isAuto]); const viewsBad = parseViews(viewsText) === undefined; + const a = item.viewsAuto; const changeVideo = async () => { try { const v = await apiCall('POST', '/api/admin/quizzes/pick/video', { url: url.trim() }); @@ -1108,21 +1213,63 @@ function ItemPanel({ onPatch({ artist: e.target.value })} /> {duel && ( -
번호 노래 {duel ? '조회수' : '추가 정답'}비고길이 재생 위치 @@ -607,9 +681,12 @@ function SongsTab({ {it.hints.length > 0 &&
힌트: {it.hints.join(' → ')}
} {duel ? ( -
- {it.views !== null ? `${viewsLabel(it.views)}회` : 없음} - + + {duelViewsNote(it) ?? -}{[...it.titleAnswers, ...it.artistAnswers].join(', ') || -}