이지선다 조회수 자동: 빈 양식에서 조회수 열을 빼고, 올린 뒤 서버가 곡마다 토픽 음원 + MV 조회수를 불러와 더함. 짝은 유튜브 뮤직 노래↔동영상 전환(watch 응답의 counterpart, 쿠키 필요), 조회수는 로그인 없이 player videoDetails.viewCount(안 되면 watch 화면 숫자). quizzes/duel-views.ts가 pending 곡을 한 곡씩 처리(재시작해도 이어서), 쿠키 만료면 남은 곡 모두 이유와 함께 failed. 짝이 없는 곡은 있는 영상 하나만 쓰고 비고 표시. 파일·편집기에 적은 숫자는 그대로 쓰고 다시 불러오기에서 빠짐, 칸을 비우고 저장하면 자동. 편집기: 조회수(토픽·MV)·비고 칸, 불러오는 중 표시와 2초 폴링(저장 안 됨으로 안 잡힘), 조회수 다시 불러오기(전체/곡), 저장 때 편집기의 옛 사본이 서버가 불러온 값을 덮지 않음. 내보내기는 직접 넣은 숫자만 조회수 열에. 파일로 만들기는 조회수 열이 없으면 고른 종류 유지. 014 마이그레이션, 단위·API 테스트, e2e duel 단계, docs 04·10·12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-03 21:07:10 +09:00
parent c55702d440
commit aacc4133b5
20 changed files with 784 additions and 72 deletions

View File

@@ -78,12 +78,12 @@ export class YtMusic {
this.mtime = mtime;
}
async searchSongs(query: string): Promise<YtmSong[]> {
private async post(endpoint: 'search' | 'next', body: Record<string, unknown>): Promise<any> {
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<YtmSong[]> {
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<SongPair> {
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<string, any>;
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 };
}
/**

View File

@@ -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;

View File

@@ -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<string, SongPair>, views: Record<string, number>): 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<typeof boot>;
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<ViewsSource>) {
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 });
});

View File

@@ -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<string, unknown>) => 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 }] });

View File

@@ -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<ViewsSource>;
viewsDelayMs?: number;
}
let searcher: Promise<(q: string) => Promise<YtmSong[]>> | null = null;
@@ -46,6 +50,9 @@ function defaultSearch(q: string): Promise<YtmSong[]> {
}
export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c: Context<Env>) => string; body: (c: Context<Env>) => Promise<unknown> }) {
// 이지선다 조회수 자동: 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<Env>) => {
const q = d.quizzes.row(Number(c.req.param('id')));
if (!q) return null;
@@ -71,18 +78,19 @@ export function mountQuizAdmin(app: Hono<Env>, 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<Env>, 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);

View File

@@ -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<import('../quizzes/duel-views').ViewsSource>;
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 },

View File

@@ -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<SongPair>;
viewCount(videoId: string): Promise<number>;
}
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<DuelViews> {
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<number> {
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<ViewsSource> {
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<void> | null = null;
private again = false;
constructor(
private db: Database,
private source: () => Promise<ViewsSource> = 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<void> {
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<void> {
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() });

View File

@@ -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<number>();
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);

View File

@@ -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<import('./http/admin').AdminDeps, 'searchYoutube' | 'lavalink' | 'lavalinkFetch' | 'importDelayMs'>;
quizAdmin?: Pick<import('./http/admin').AdminDeps, 'searchYoutube' | 'lavalink' | 'lavalinkFetch' | 'importDelayMs' | 'viewsSource' | 'viewsDelayMs'>;
}
export function startServer(opts: StartOptions) {