이지선다 조회수 자동: 빈 양식에서 조회수 열을 빼고, 올린 뒤 서버가 곡마다 토픽 음원 + 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:
@@ -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 };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
2
apps/server/src/db/migrations/014_duel_views.sql
Normal file
2
apps/server/src/db/migrations/014_duel_views.sql
Normal 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;
|
||||
211
apps/server/src/duel-views.test.ts
Normal file
211
apps/server/src/duel-views.test.ts
Normal 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 });
|
||||
});
|
||||
@@ -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 }] });
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 },
|
||||
|
||||
148
apps/server/src/quizzes/duel-views.ts
Normal file
148
apps/server/src/quizzes/duel-views.ts
Normal 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() });
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -292,7 +292,7 @@ export function RoomSettings({
|
||||
/>
|
||||
</Section>
|
||||
{allowQuiz && duel && (
|
||||
<Section title="이지선다 퀴즈" tip="조회수가 든 파일로 만든 이지선다 퀴즈만 고를 수 있어요">
|
||||
<Section title="이지선다 퀴즈" tip="관리자 → 퀴즈에서 이지선다로 만든 퀴즈만 고를 수 있어요">
|
||||
<QuizPicker kind="duel" chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />
|
||||
</Section>
|
||||
)}
|
||||
@@ -642,7 +642,7 @@ function QuizPicker({ kind, chosen, songs, ro, onPick }: { kind: QuizKind; chose
|
||||
<div className="quiz-pick" role="listbox" aria-label={kind === 'duel' ? '이지선다 퀴즈 목록' : '제작된 퀴즈 목록'}>
|
||||
{list?.length === 0 && (
|
||||
<span className="muted small" style={{ padding: 10 }}>
|
||||
{q.trim() ? '검색 결과가 없어요.' : kind === 'duel' ? '고를 수 있는 이지선다 퀴즈가 없어요. 관리자 → 퀴즈 → 파일로 만들기에서 조회수가 든 파일로 만들 수 있어요.' : '고를 수 있는 퀴즈가 없어요.'}
|
||||
{q.trim() ? '검색 결과가 없어요.' : kind === 'duel' ? '고를 수 있는 이지선다 퀴즈가 없어요. 관리자 → 퀴즈 → 파일로 만들기에서 이지선다로 만들 수 있어요.' : '고를 수 있는 퀴즈가 없어요.'}
|
||||
</span>
|
||||
)}
|
||||
{list?.map((x) => (
|
||||
|
||||
@@ -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({
|
||||
</div>
|
||||
{!file && duel && (
|
||||
<p className="muted small" style={{ margin: 0 }}>
|
||||
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>, <b>제목</b>, <b>조회수</b>는 꼭 있어야 하고 <b>가수</b>는 카드에 같이 보여요. 조회수는 1234567, 1,234,567,
|
||||
123만, 1.2억처럼 써도 돼요. 게임에서는 곡을 무작위로 두 개씩 짝지어 A/B 카드로 보여 줘요.
|
||||
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>와 <b>제목</b>은 꼭 있어야 하고 <b>가수</b>는 카드에 같이 보여요. 조회수는 올린 뒤 서버가 곡마다
|
||||
유튜브 뮤직의 <b>토픽 음원 + MV</b> 조회수를 더해 불러와요(링크는 토픽이든 MV든 괜찮아요). 직접 정한 숫자를 쓰려면 <b>조회수</b> 열에 1234567, 123만, 1.2억처럼 적으면 그 숫자를
|
||||
그대로 써요. 게임에서는 곡을 무작위로 두 개씩 짝지어 A/B 카드로 보여 줘요.
|
||||
</p>
|
||||
)}
|
||||
{!file && !duel && (
|
||||
@@ -279,8 +280,8 @@ export function QuizFileImport({
|
||||
</td>
|
||||
<td className="small">{it.artist || <span className="muted">-</span>}</td>
|
||||
{duel ? (
|
||||
<td className="small mono" title={`${it.views?.toLocaleString('ko-KR')}회`}>
|
||||
{viewsLabel(it.views ?? 0)}회
|
||||
<td className="small mono" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회 (파일에 적힌 값)` : '올린 뒤 토픽 + MV 조회수를 불러와요'}>
|
||||
{it.views !== null ? `${viewsLabel(it.views)}회` : <span className="muted">자동</span>}
|
||||
</td>
|
||||
) : (
|
||||
<td className="small">{[...it.hints, '초성'].join(' → ')}</td>
|
||||
|
||||
@@ -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() {
|
||||
)}
|
||||
</div>
|
||||
<p className="muted">
|
||||
직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 조회수가 든 파일로 만들고, 이지선다
|
||||
모드에서만 쓸 수 있어요.
|
||||
직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 파일로 만들고(조회수는
|
||||
서버가 토픽 + MV로 불러와요), 이지선다 모드에서만 쓸 수 있어요.
|
||||
</p>
|
||||
{fromFile && (
|
||||
<QuizFileImport
|
||||
@@ -159,8 +162,18 @@ export interface DbInfo {
|
||||
}
|
||||
|
||||
/** A song picked in the editor (search, address, playlist): answers, hints and positions start empty. */
|
||||
type NewSong = Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec' | 'views'>;
|
||||
const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null, views: null });
|
||||
type NewSong = Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec' | 'views' | 'viewsAuto'>;
|
||||
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<T extends QuizItem>(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<typeof payload>;
|
||||
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 = <T extends QuizItem>(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<typeof payload>;
|
||||
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<number>());
|
||||
useEffect(() => {
|
||||
@@ -312,6 +365,17 @@ export function QuizEditor() {
|
||||
</Link>
|
||||
<h1 className="grow">{draft.name || '이름 없는 퀴즈'}</h1>
|
||||
{dirty ? <span className="badge warn" role="status">● 저장하지 않은 변경이 있어요</span> : <span className="muted small">저장됨</span>}
|
||||
{kind === 'duel' && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn"
|
||||
disabled={!draft.items.some((i) => i.id && i.viewsAuto && i.viewsAuto.state !== 'pending')}
|
||||
onClick={() => void refreshViews()}
|
||||
title="자동으로 불러온 곡의 토픽·MV 조회수를 지금 값으로 다시 불러와요 (직접 넣은 조회수는 그대로)"
|
||||
>
|
||||
🔄 조회수 다시 불러오기
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn" disabled={!draft.items.length} onClick={() => exportQuiz(draft.name, draft.items, kind)} title="곡 목록을 다시 올릴 수 있는 엑셀 파일로 받아요">
|
||||
📥 엑셀로 내보내기
|
||||
</button>
|
||||
@@ -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])}
|
||||
/>
|
||||
) : (
|
||||
<SettingsTab kind={kind} draft={draft} onChange={set} onDelete={() => 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<string | null>(null);
|
||||
const [dragKey, setDragKey] = useState<string | null>(null);
|
||||
@@ -551,9 +618,15 @@ function SongsTab({
|
||||
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
{duel && items.some((i) => i.views === null) && (
|
||||
{duel && items.some((i) => i.viewsAuto?.state === 'pending') && (
|
||||
<p className="muted small" role="status" style={{ margin: '8px 10px' }}>
|
||||
⏳ 토픽·MV 조회수를 불러오는 중이에요 ({items.filter((i) => i.viewsAuto?.state === 'pending').length}곡 남음). 다 불러오면 저절로 채워져요.
|
||||
</p>
|
||||
)}
|
||||
{duel && items.some((i) => i.views === null && i.viewsAuto?.state !== 'pending') && (
|
||||
<p className="warn-text small" style={{ margin: '8px 10px' }}>
|
||||
조회수가 없는 곡 {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) && ' 새로 넣은 곡은 저장하면 불러와요.'}
|
||||
</p>
|
||||
)}
|
||||
<table className="data-table quiz-songs">
|
||||
@@ -563,6 +636,7 @@ function SongsTab({
|
||||
<th style={{ width: 44 }}>번호</th>
|
||||
<th>노래</th>
|
||||
<th>{duel ? '조회수' : '추가 정답'}</th>
|
||||
{duel && <th>비고</th>}
|
||||
<th>길이</th>
|
||||
<th>재생 위치</th>
|
||||
<th style={{ width: 120 }} />
|
||||
@@ -607,9 +681,12 @@ function SongsTab({
|
||||
{it.hints.length > 0 && <div className="muted small">힌트: {it.hints.join(' → ')}</div>}
|
||||
</td>
|
||||
{duel ? (
|
||||
<td className="mono small" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회` : undefined}>
|
||||
{it.views !== null ? `${viewsLabel(it.views)}회` : <span className="warn-text">없음</span>}
|
||||
</td>
|
||||
<>
|
||||
<td className="mono small" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회` : undefined}>
|
||||
<ViewsCell item={it} />
|
||||
</td>
|
||||
<td className="small">{duelViewsNote(it) ?? <span className="muted">-</span>}</td>
|
||||
</>
|
||||
) : (
|
||||
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
|
||||
)}
|
||||
@@ -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}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -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 <span className="muted">불러오는 중…{total && ` (${total})`}</span>;
|
||||
if (item.views === null) return a ? <span className="warn-text">없음</span> : <span className="muted">저장하면 불러와요</span>;
|
||||
return (
|
||||
<>
|
||||
{total}
|
||||
{a?.state === 'done' && (
|
||||
<div className="muted">{[a.topicViews !== null && `토픽 ${viewsLabel(a.topicViews)}`, a.mvViews !== null && `MV ${viewsLabel(a.mvViews)}`].filter(Boolean).join(' · ')}</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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<VideoInfo>('POST', '/api/admin/quizzes/pick/video', { url: url.trim() });
|
||||
@@ -1108,21 +1213,63 @@ function ItemPanel({
|
||||
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
|
||||
</label>
|
||||
{duel && (
|
||||
<label className="field">
|
||||
조회수 (예: 1234567, 123만, 1.2억)
|
||||
<div className="field">
|
||||
조회수
|
||||
{a ? (
|
||||
<div className="stack small" style={{ gap: 4 }} role="status">
|
||||
{a.state === 'pending' ? (
|
||||
<span className="muted">토픽·MV 조회수를 불러오는 중이에요…</span>
|
||||
) : a.state === 'failed' ? (
|
||||
<span className="warn-text">{a.error}</span>
|
||||
) : (
|
||||
<>
|
||||
<span>
|
||||
<b>{fullViews(item.views)}</b> = 토픽 {fullViews(a.topicViews)} + MV {fullViews(a.mvViews)}
|
||||
</span>
|
||||
<span className="muted">
|
||||
{a.topicId && (
|
||||
<a href={`https://youtu.be/${a.topicId}`} target="_blank" rel="noreferrer">
|
||||
토픽 영상 ↗
|
||||
</a>
|
||||
)}
|
||||
{a.topicId && a.mvId && ' · '}
|
||||
{a.mvId && (
|
||||
<a href={`https://youtu.be/${a.mvId}`} target="_blank" rel="noreferrer">
|
||||
MV ↗
|
||||
</a>
|
||||
)}
|
||||
{a.at && ` · ${new Date(a.at).toLocaleString('ko-KR')}에 불러옴`}
|
||||
</span>
|
||||
{duelViewsNote(item) && <span className="badge warn" style={{ alignSelf: 'flex-start' }}>비고: {duelViewsNote(item)}</span>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<span className="muted small">
|
||||
{item.views === null ? '저장하면 토픽·MV 조회수를 자동으로 불러와요.' : item.fromFile ? '파일에 적힌 조회수를 써요.' : '직접 넣은 조회수를 써요.'}
|
||||
</span>
|
||||
)}
|
||||
<input
|
||||
className="input"
|
||||
value={viewsText}
|
||||
inputMode="numeric"
|
||||
aria-label="조회수 직접 넣기"
|
||||
placeholder={a ? '직접 넣기 (예: 1234567, 123만, 1.2억)' : '예: 1234567, 123만, 1.2억 (비우면 자동)'}
|
||||
onChange={(e) => {
|
||||
setViewsText(e.target.value);
|
||||
const v = parseViews(e.target.value);
|
||||
if (v !== undefined) onPatch({ views: v });
|
||||
// a number of one's own replaces the fetched one; emptying the box goes back to 자동 (fetched on save)
|
||||
if (v !== undefined && (v !== null || !a)) onPatch({ views: v, viewsAuto: null });
|
||||
}}
|
||||
aria-invalid={viewsBad}
|
||||
/>
|
||||
{viewsBad ? <span className="field-error small">조회수를 읽을 수 없어요.</span> : item.views !== null && <span className="muted small">{item.views.toLocaleString('ko-KR')}회</span>}
|
||||
</label>
|
||||
{viewsBad ? <span className="field-error small">조회수를 읽을 수 없어요.</span> : !a && item.views !== null && <span className="muted small">{item.views.toLocaleString('ko-KR')}회</span>}
|
||||
{onRefreshViews && (
|
||||
<button type="button" className="btn btn-sm" style={{ alignSelf: 'flex-start' }} disabled={a?.state === 'pending'} onClick={onRefreshViews}>
|
||||
🔄 {a ? '조회수 다시 불러오기' : '자동으로 불러오기 (토픽 + MV)'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!duel && (
|
||||
<>
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
- 가사 4줄 → 시간이 갈수록 2줄씩 추가, 제목 단어는 ○로 가림
|
||||
|
||||
### 이지선다 (조회수가 더 높은 곡 고르기)
|
||||
- 이지선다 퀴즈(관리자 → 퀴즈 → 파일로 만들기에서 조회수가 든 파일로 만든 퀴즈)로만 한다. 일반 퀴즈·직접 선택은 고를 수 없다
|
||||
- 이지선다 퀴즈(관리자 → 퀴즈 → 파일로 만들기에서 이지선다로 만든 퀴즈, 조회수는 서버가 토픽 + MV로 불러옴)로만 한다. 일반 퀴즈·직접 선택은 고를 수 없다
|
||||
- **제한 시간**: 10·15·20·30(기본)·45·60·90초. **진행 방식**: 매번 새 두 곡 / 이긴 곡이 남기(연속). **재생위치**: 처음부터 / 하이라이트부터
|
||||
- 문제 수: 10~100 또는 전부(매번 새 두 곡 = 곡 수÷2, 연속 = 곡 수-1). 다음 문제까지·다음문제인원은 그대로, 정답방식·힌트·스킵·다시듣기는 없다
|
||||
- 규칙은 12 문서 "이지선다"
|
||||
|
||||
@@ -34,3 +34,4 @@
|
||||
- 2026-10-22 제작된 퀴즈 4~6단계: 플레이리스트 가져오기(.6 Lavalink, 유튜브·스포티파이), 검토 대기(전체공개 퀴즈 → 서버 DB, 난이도 조정), 통계 상세(힌트·오답·다시듣기·퀴즈별). 서버 테스트 132개, e2e 전체 통과
|
||||
- 2026-10-23 퀴즈 파일 A단계: 관리자 → 퀴즈 "파일로 만들기"(.xlsx·.csv, 라이브러리 없이 브라우저가 읽음 — `packages/shared/src/sheet.ts`), 열 이름으로 링크·정답·설명·힌트·순번 등을 찾고(`quiz-file.ts`) 못 찾은 열만 고름, 시트 고르기, 잘못된 링크·같은 영상 줄 표시. 편집 화면 "파일에서 가져오기"(뒤에 추가·목록 바꾸기), "엑셀로 내보내기"(다시 올릴 수 있는 형식)·빈 양식. 파일 곡은 적힌 값 그대로(서버 DB 연결·검토 대기 없음, 설명 비어도 됨). 곡별 힌트(`custom_quiz_items.hints`): 힌트를 하나씩 → 마지막에 초성(자동은 N초마다, 직접선택은 투표마다). 사용자 BGM 파일 390곡 그대로 생성 확인. 테스트 140개, e2e quiz·game·admin·a11y 통과
|
||||
- 2026-10-23 이지선다(B단계): 모드 "이지선다"와 이지선다 퀴즈(파일의 조회수, `kind`/`views` 013 마이그레이션). 서버 `game/duel.ts`(A/B 카드, 고르기·바꾸기, 시간 끝나면 조회수 공개, 1점·역배 2점, 매번 새 두 곡/연속), 화면 `DuelScreen.tsx`(카드마다 숨은 플레이어 `net/duel-player.ts`로 각자 듣고 이어 듣기, 고른 사람 프로필), 방 설정(제한 시간·진행 방식·재생위치·문제 수), 관리자 파일로 만들기 종류 선택·조회수 편집·내보내기. 테스트 146개, e2e duel(실제 유튜브 이어 듣기 포함)·game·quiz·admin·rooms·login·a11y 통과
|
||||
- 2026-11-03 이지선다 조회수 자동: 빈 양식에서 조회수 열을 빼고, 올린 뒤 서버가 곡마다 토픽 + MV 조회수를 불러와 더함(유튜브 뮤직 노래↔동영상 짝, 쿠키 필요 · 조회수는 로그인 없이). 편집기에 곡마다 토픽·MV 조회수, 비고(한쪽만 있는 곡·직접 넣은 값·실패 이유), 불러오는 중 표시, 조회수 다시 불러오기(전체/곡). 파일에 적힌 숫자는 그대로 씀. 014 마이그레이션, 단위·API 테스트, e2e duel 단계 추가
|
||||
|
||||
@@ -184,12 +184,13 @@
|
||||
12. 플레이 통계: 문제마다 힌트(시간/투표), 정답이 아닌 입력 수와 사람 수, 다시듣기 수, 제작된 퀴즈·곡을 함께 저장(DB에 없는 퀴즈 곡도 퀴즈 통계에 들어감). 관리자 통계는 곡별·퀴즈별 탭. 난이도 제안은 힌트도 본다(80% 넘게 8초 안에 힌트 30% 미만 → 쉽게, 30% 이하 또는 50% 이하+힌트 60% 이상 → 어렵게)이고 검토 대기 → 난이도 조정에 근거와 함께 나온다. "반영 안 함"은 5번 더 나온 뒤 다시 계산
|
||||
|
||||
## 이지선다 (2026-10-22~23, 사용자 답변)
|
||||
1. 조회수가 더 높은 곡을 고르는 모드. 곡 목록과 조회수는 사용자가 파일(.xlsx·.csv: 영상 링크·제목·가수·조회수, 조회수는 1,234,567·123만·1.2억도 읽음)로 올린다. 서버가 조회수를 모으지 않는다. 조회수 없는 줄은 빠진다
|
||||
2. 이지선다 퀴즈(`custom_quizzes.kind = 'duel'`, `custom_quiz_items.views`)는 이지선다에서만, 일반 퀴즈는 듣고맞추기에서만 쓴다. 파일로 만들기에서 조회수 열이 있으면 이지선다로 골라진다
|
||||
1. 조회수가 더 높은 곡을 고르는 모드. 곡 목록은 사용자가 파일(.xlsx·.csv: 영상 링크·제목·가수, 조회수는 선택)로 올린다. 조회수는 아래 7번(2026-11-03)처럼 서버가 불러온다. 조회수 칸에 숫자(1,234,567·123만·1.2억도 읽음)가 적혀 있으면 그 숫자를 그대로 쓰고, 읽을 수 없는 값이 적힌 줄은 빠진다
|
||||
2. 이지선다 퀴즈(`custom_quizzes.kind = 'duel'`, `custom_quiz_items.views`)는 이지선다에서만, 일반 퀴즈는 듣고맞추기에서만 쓴다. 파일로 만들기에서 조회수 열이 있으면 이지선다로 골라지고, 없으면 고른 종류가 그대로 남는다(이지선다 빈 양식에는 조회수 열이 없음)
|
||||
3. 문제마다 곡 2개를 무작위로 A/B 카드(썸네일·제목·가수)에 놓는다. 진행 방식은 방에서 고른다: 매번 새 두 곡 / 연속(조회수가 더 높은 곡이 조회수를 보인 채 A로 남고 새 곡이 B로 들어옴, 같으면 A가 남음). 틀려도 탈락 없이 곡이 떨어질 때까지 계속
|
||||
4. 카드를 누르면 그 곡이 자기 화면에서만 재생되고(모두 같은 순간에 듣지 않음), 누른 카드가 그 사람의 선택이다. 다른 카드를 누르면 그 곡으로 바뀌고, 다시 누르면 멈춘 곳부터 이어서 나온다(카드마다 숨은 플레이어 하나). 재생 중인 카드를 또 누르면 멈춘다. 선택은 제한 시간 전까지 몇 번이든 바꿀 수 있고, 고른 사람의 프로필이 카드 밑에 바로 보인다
|
||||
5. 제한 시간 기본 30초(방 설정). 시간이 끝나면 두 곡의 조회수를 공개하고 높은 쪽을 고른 사람이 1점. 역배: 맞힌 사람이 딱 1명이고 반대쪽에 2명 이상이면 2점(4:1에서 혼자 맞히면 2점, 1:1·3:2는 1점). 안 고른 사람은 0점(감점 없음), 조회수가 같으면 둘 다 정답
|
||||
6. 결과 화면은 점수·맞힌 문제·역배 성공 수, 곡 목록에 두 곡과 조회수와 받은 점수
|
||||
7. **조회수 자동 (2026-11-03, 사용자 답변)**: 곡의 조회수 = 토픽 음원 조회수 + MV 조회수. 링크는 토픽이든 MV든 되고, 짝은 유튜브 뮤직의 "노래 ↔ 동영상" 전환(watch 응답의 `playlistPanelVideoWrapperRenderer.counterpart`)으로 찾는다 — 로그인 쿠키가 있어야 짝이 온다. 정확한 조회수는 로그인 없이 유튜브 player의 `videoDetails.viewCount`(안 되면 watch 화면 숫자)로 받는다. 서버가 올린 뒤(`views_auto` 014 마이그레이션, `quizzes/duel-views.ts`) 한 곡씩 불러오고 재시작해도 이어서 한다. 짝이 없는 곡은 있는 영상 하나만 쓰고 비고에 "토픽 없음 (MV 조회수만)"/"MV 없음 (토픽 조회수만)". 다시 불러오기는 편집기의 "조회수 다시 불러오기"(자동 곡 전체) / 곡 패널(그 곡, 직접 넣은 숫자도 자동으로 바꿈)로만 — 매일 자동 갱신 없음. 직접 넣은 숫자(파일·편집기)는 다시 불러오기에서 빠지고, 칸을 비우고 저장하면 자동으로 돌아간다. 못 불러온 곡(쿠키 만료 등)은 이유를 비고에 보이고 게임에서 빠진다. 내보내기는 직접 넣은 숫자만 조회수 열에 적는다
|
||||
|
||||
## 원곡 찾기 자동 확정 기준 (2026-10-22)
|
||||
1. 제목 일치 + 가수 일치(라틴 악센트 무시 JAŸ-Z=JAY-Z, `및`·with·feat 구분, 앞 The 무시, 확정곡 2곡 이상에서 확인된 한글/영문 이름 짝 태연=TAEYEON) + 길이 차이 15초 이내 + 커버·노래방·라이브·다른 버전 아님. "Radio Edit/Original Version"은 같은 녹음으로 본다
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* 이지선다 in real browsers (fake player, no YouTube):
|
||||
* - 관리자 → 퀴즈 → 파일로 만들기: a CSV with a 조회수 column is taken as 이지선다 (rows without views left out), 엑셀로 내보내기
|
||||
* - 관리자 → 퀴즈 → 파일로 만들기: a CSV with a 조회수 column is taken as 이지선다 (numbers used as written, bad ones left out), 엑셀로 내보내기
|
||||
* - 이지선다 양식 without 조회수: the server fetches 토픽 + MV (fake YouTube Music), the editor shows them and the 비고
|
||||
* - 방 설정 → 이지선다 → only 이지선다 퀴즈 are listed; 2 questions from 4 songs
|
||||
* - three players: tapping a card plays it and picks it, picks move, avatars show under the cards, the views come at
|
||||
* the end, alone on the higher card against two = 역배 +2; results with the 역배 column (phone screen too)
|
||||
@@ -28,6 +29,17 @@ const app = startServer({
|
||||
stopWaitMs: 200,
|
||||
discordExchange: async (code) => ({ id: code, username: 'u', global_name: '사금향', avatar: null }),
|
||||
gameTiming: { limitMs: 9000, revealMs: 6000 },
|
||||
// 조회수 자동: duelvid0006 has 토픽 + MV, duelvid0007 only a 토픽
|
||||
quizAdmin: {
|
||||
viewsDelayMs: 300,
|
||||
viewsSource: async () => ({
|
||||
songPair: async (id) =>
|
||||
id === 'duelvid0006'
|
||||
? { type: 'MUSIC_VIDEO_TYPE_ATV', other: { videoId: 'duelmv00006', type: 'MUSIC_VIDEO_TYPE_OMV' } }
|
||||
: { type: 'MUSIC_VIDEO_TYPE_ATV', other: null },
|
||||
viewCount: async (id) => ({ duelvid0006: 153_021_540, duelmv00006: 120_456_643, duelvid0007: 4_321 })[id] ?? 0,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const db = app.db;
|
||||
|
||||
@@ -94,14 +106,14 @@ try {
|
||||
await host.waitForURL(`${ORIGIN}/**`);
|
||||
let quizId = 0;
|
||||
|
||||
await step('파일로 만들기: 조회수 열이 있는 CSV → 이지선다로 골라짐, 조회수 없는 줄은 빠짐 → 4곡으로 만들기 → 내보내기', async () => {
|
||||
const csv = ['유튜브 링크,제목,가수,조회수', 'https://youtu.be/duelvid0001,노래1,가수1,1.2억', 'duelvid0002,노래2,가수2,"34,000,000"', 'https://youtu.be/duelvid0003,노래3,가수3,500만', 'https://youtu.be/duelvid0004,노래4,가수4,12345회', 'https://youtu.be/duelvid0005,노래5,가수5,'].join('\n');
|
||||
await step('파일로 만들기: 조회수 열이 있는 CSV → 이지선다로 골라짐, 읽을 수 없는 조회수 줄은 빠짐 → 4곡으로 만들기 → 내보내기', async () => {
|
||||
const csv = ['유튜브 링크,제목,가수,조회수', 'https://youtu.be/duelvid0001,노래1,가수1,1.2억', 'duelvid0002,노래2,가수2,"34,000,000"', 'https://youtu.be/duelvid0003,노래3,가수3,500만', 'https://youtu.be/duelvid0004,노래4,가수4,12345회', 'https://youtu.be/duelvid0005,노래5,가수5,많음'].join('\n');
|
||||
await host.goto(`${ORIGIN}/admin/quizzes`);
|
||||
await host.getByRole('button', { name: /파일로 만들기/ }).click();
|
||||
await host.getByLabel('퀴즈 파일').setInputFiles({ name: '조회수 대결.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) });
|
||||
await host.getByText('빠지는 줄 1개').waitFor();
|
||||
expect((await host.getByRole('radio', { name: /이지선다/ }).getAttribute('aria-checked')) === 'true', '조회수 열이 있는데 이지선다로 골라지지 않음');
|
||||
await host.getByText('조회수가 비어 있어요').waitFor();
|
||||
await host.getByText('조회수를 읽을 수 없어요 (많음)').waitFor();
|
||||
await host.locator('td', { hasText: '1.2억회' }).waitFor();
|
||||
await host.screenshot({ path: join(SHOTS, 'duel-file-preview.png'), fullPage: true });
|
||||
await host.getByRole('button', { name: '4곡으로 이지선다 만들기' }).click();
|
||||
@@ -118,6 +130,35 @@ try {
|
||||
expect(back[0]!.includes('조회수') && back[1]![4] === '120000000', `내보낸 내용: ${JSON.stringify(back.slice(0, 2))}`);
|
||||
});
|
||||
|
||||
await step('이지선다 양식(조회수 열 없음) → 자동: 올린 뒤 토픽 + MV 조회수를 불러오고, 토픽만 있는 곡은 비고로 표시', async () => {
|
||||
await host.goto(`${ORIGIN}/admin/quizzes`);
|
||||
await host.getByRole('button', { name: /파일로 만들기/ }).click();
|
||||
await host.getByRole('radio', { name: /이지선다/ }).click();
|
||||
const [dl] = await Promise.all([host.waitForEvent('download'), host.getByRole('button', { name: /빈 양식 받기/ }).click()]);
|
||||
const template = (await readXlsx(new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer())))[0]!.rows;
|
||||
expect(!template[0]!.includes('조회수'), `양식 열: ${JSON.stringify(template[0])}`);
|
||||
const csv = [template[0]!.join(','), '1,https://youtu.be/duelvid0006,라일락,아이유,,', '2,https://youtu.be/duelvid0007,토픽만,누구,,'].join('\n');
|
||||
await host.getByLabel('퀴즈 파일').setInputFiles({ name: '자동 조회수.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) });
|
||||
// no 조회수 column: the 이지선다 picked above stays
|
||||
await host.locator('td', { hasText: '토픽만' }).waitFor();
|
||||
expect((await host.getByRole('radio', { name: /이지선다/ }).getAttribute('aria-checked')) === 'true', '조회수 열이 없는 파일에서 이지선다 선택이 풀림');
|
||||
expect((await host.locator('td', { hasText: /^자동$/ }).count()) === 2, '미리보기의 조회수가 자동으로 안 보임');
|
||||
await host.getByRole('button', { name: '2곡으로 이지선다 만들기' }).click();
|
||||
await host.waitForURL(/\/admin\/quizzes\/\d+$/);
|
||||
const rows = host.locator('.quiz-songs tbody tr');
|
||||
await rows.nth(0).getByText('2.7억회').waitFor();
|
||||
await rows.nth(0).getByText('토픽 1.5억 · MV 1.2억').waitFor();
|
||||
await rows.nth(1).getByText('MV 없음 (토픽 조회수만)').waitFor();
|
||||
// taking in the fetched numbers is not an unsaved change
|
||||
await host.getByText('저장됨').waitFor();
|
||||
await rows.nth(0).click();
|
||||
await host.getByText(/273,478,183회.*= 토픽 153,021,540회 \+ MV 120,456,643회/).waitFor();
|
||||
await host.screenshot({ path: join(SHOTS, 'duel-views-auto.png'), fullPage: true });
|
||||
const id = Number(new URL(host.url()).pathname.split('/').pop());
|
||||
const saved = db.query<{ title: string; views: number }, [number]>('SELECT title, views FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos').all(id);
|
||||
expect(JSON.stringify(saved) === JSON.stringify([{ title: '라일락', views: 273_478_183 }, { title: '토픽만', views: 4_321 }]), `저장된 조회수: ${JSON.stringify(saved)}`);
|
||||
});
|
||||
|
||||
let code = '';
|
||||
const g1 = await guestPage('철수');
|
||||
const g2 = await guestPage('영희', { width: 390, height: 844, mobile: true });
|
||||
@@ -131,7 +172,9 @@ try {
|
||||
await host.getByText('방 설정에서 이지선다 퀴즈를 골라 주세요.').waitFor();
|
||||
const list = host.getByRole('listbox', { name: '이지선다 퀴즈 목록' });
|
||||
await list.getByRole('option').first().waitFor();
|
||||
expect((await list.getByRole('option').count()) === 1, '이지선다 퀴즈가 아닌 것도 보임');
|
||||
// the two 이지선다 quizzes made above, no 일반 퀴즈
|
||||
const names = await list.getByRole('option').allInnerTexts();
|
||||
expect(names.length === 2 && names.some((n) => n.includes('조회수 대결')) && names.some((n) => n.includes('자동 조회수')), `이지선다 퀴즈 목록: ${JSON.stringify(names)}`);
|
||||
await list.getByRole('option', { name: /조회수 대결/ }).click();
|
||||
await host.getByText('퀴즈 곡 4곡').waitFor();
|
||||
await host.locator('.pool-banner', { hasText: '2문제' }).waitFor();
|
||||
|
||||
@@ -30,6 +30,18 @@ export const QuizItemSchema = z.object({
|
||||
startSec: sec,
|
||||
highlightSec: sec,
|
||||
views: z.number().int().min(0).max(1e15).nullable().default(null),
|
||||
viewsAuto: z
|
||||
.object({
|
||||
state: z.enum(['pending', 'done', 'failed']),
|
||||
topicId: z.string().regex(/^[\w-]{11}$/).nullable(),
|
||||
topicViews: z.number().int().min(0).max(1e15).nullable(),
|
||||
mvId: z.string().regex(/^[\w-]{11}$/).nullable(),
|
||||
mvViews: z.number().int().min(0).max(1e15).nullable(),
|
||||
error: z.string().max(300).nullable(),
|
||||
at: z.number().int().nullable(),
|
||||
})
|
||||
.nullable()
|
||||
.default(null),
|
||||
}).refine((it) => it.fromFile || it.artist.length > 0, { path: ['artist'], message: '가수를 넣어 주세요.' });
|
||||
|
||||
export const QuizSaveSchema = z.object({
|
||||
|
||||
@@ -49,8 +49,40 @@ export interface QuizItem {
|
||||
auto: boolean;
|
||||
startSec: number | null;
|
||||
highlightSec: number | null;
|
||||
/** 이지선다 퀴즈: the video's view count as written in the file (null = not given; such songs are left out of games). */
|
||||
/**
|
||||
* 이지선다 퀴즈: the view count the game compares (null = none yet; such songs are left out of games).
|
||||
* Written by hand / in the file (viewsAuto null) or the server's 토픽 + MV sum (viewsAuto).
|
||||
*/
|
||||
views: number | null;
|
||||
/** 이지선다 퀴즈: views the server fetched (토픽 음원 + its MV, paired by YouTube Music); null = written by hand / in the file. */
|
||||
viewsAuto: DuelViews | null;
|
||||
}
|
||||
|
||||
/** 조회수 자동: the 토픽 (art track) and MV of one song, paired by YouTube Music's 노래 ↔ 동영상 switch. */
|
||||
export interface DuelViews {
|
||||
/** pending: waiting for the server · done: views = topicViews + mvViews · failed: see error (views stays as it was). */
|
||||
state: 'pending' | 'done' | 'failed';
|
||||
topicId: string | null;
|
||||
topicViews: number | null;
|
||||
/** The music video, or the linked video itself when it is not a 토픽 and has no 토픽 pair. */
|
||||
mvId: string | null;
|
||||
mvViews: number | null;
|
||||
error: string | null;
|
||||
/** When it was last fetched. */
|
||||
at: number | null;
|
||||
}
|
||||
|
||||
export const PENDING_VIEWS: DuelViews = { state: 'pending', topicId: null, topicViews: null, mvId: null, mvViews: null, error: null, at: null };
|
||||
|
||||
/** 비고 of an 이지선다 song: where its views come from when that is not the usual 토픽 + MV. */
|
||||
export function duelViewsNote(it: Pick<QuizItem, 'views' | 'viewsAuto' | 'fromFile'>): string | null {
|
||||
const a = it.viewsAuto;
|
||||
if (!a) return it.views === null ? null : it.fromFile ? '파일에 적힌 조회수' : '직접 넣은 조회수';
|
||||
if (a.state === 'failed') return a.error;
|
||||
if (a.state !== 'done') return null;
|
||||
if (!a.topicId) return '토픽 없음 (MV 조회수만)';
|
||||
if (!a.mvId) return 'MV 없음 (토픽 조회수만)';
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface QuizSummary {
|
||||
|
||||
@@ -74,8 +74,8 @@ test('rows → quiz songs: as written, 순번 order, bad links / no answer / rep
|
||||
|
||||
test('our export reads back to the same songs (answers, own positions, several hints) and the template is valid', () => {
|
||||
const items = [
|
||||
{ songId: null, videoId: 'iIIjS6yDMQo', title: '감옥탈출', artist: '트레일러', titleAnswers: ['구토할배'], artistAnswers: ['trailer'], hints: ['방탈출', '플래시'], fromFile: true, durationSec: null, auto: false, startSec: 12, highlightSec: 61.5, views: null },
|
||||
{ songId: 3, videoId: 'x0-xFqvJ-U8', title: '갓 오브 워 2', artist: '', titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, durationSec: 200, auto: true, startSec: null, highlightSec: null, views: null },
|
||||
{ songId: null, videoId: 'iIIjS6yDMQo', title: '감옥탈출', artist: '트레일러', titleAnswers: ['구토할배'], artistAnswers: ['trailer'], hints: ['방탈출', '플래시'], fromFile: true, durationSec: null, auto: false, startSec: 12, highlightSec: 61.5, views: null, viewsAuto: null },
|
||||
{ songId: 3, videoId: 'x0-xFqvJ-U8', title: '갓 오브 워 2', artist: '', titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, durationSec: 200, auto: true, startSec: null, highlightSec: null, views: null, viewsAuto: null },
|
||||
];
|
||||
const { rows } = quizToRows(items);
|
||||
const text = rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
|
||||
@@ -111,7 +111,7 @@ test('조회수 as people write it', () => {
|
||||
expect(parseViews('많음')).toBeUndefined();
|
||||
});
|
||||
|
||||
test('이지선다 파일: 제목·가수·조회수, rows without views are left out, export and template read back', () => {
|
||||
test('이지선다 파일: 제목·가수, 조회수 optional (empty = fetched by the server), export and template read back', () => {
|
||||
const rows = [
|
||||
['순번', '유튜브 링크', '제목', '가수', '조회수'],
|
||||
['2', 'https://youtu.be/iIIjS6yDMQo', '감옥탈출', '트레일러', '1.2억'],
|
||||
@@ -122,17 +122,23 @@ test('이지선다 파일: 제목·가수·조회수, rows without views are lef
|
||||
const cols = guessColumns(rows[0]!);
|
||||
expect(cols).toEqual(['order', 'link', 'answer', 'desc', 'views']);
|
||||
const p = parseQuizRows(rows, cols, 0, 'duel');
|
||||
expect(p.items.map((i) => [i.title, i.artist, i.views])).toEqual([
|
||||
['갓 오브 워', '', 3456789],
|
||||
['감옥탈출', '트레일러', 120000000],
|
||||
expect(p.items.map((i) => [i.title, i.artist, i.views, i.viewsAuto])).toEqual([
|
||||
['갓 오브 워', '', 3456789, null],
|
||||
['감옥탈출', '트레일러', 120000000, null],
|
||||
['조회수 없음', '누구', null, null],
|
||||
]);
|
||||
expect(p.rows.filter((r) => r.problem).map((r) => [r.line, r.problem])).toEqual([
|
||||
[4, '조회수가 비어 있어요'],
|
||||
[5, '조회수를 읽을 수 없어요 (많음)'],
|
||||
]);
|
||||
const { rows: out } = quizToRows(p.items, 'duel');
|
||||
expect(p.rows.filter((r) => r.problem).map((r) => [r.line, r.problem])).toEqual([[5, '조회수를 읽을 수 없어요 (많음)']]);
|
||||
// export: written numbers come back as written, fetched ones (and empty ones) come back empty
|
||||
const fetched = { state: 'done' as const, topicId: 'aaaaaaaaaaa', topicViews: 10, mvId: 'bbbbbbbbbbb', mvViews: 20, error: null, at: 1 };
|
||||
const withAuto = p.items.map((it, i) => (i === 1 ? { ...it, views: 30, viewsAuto: fetched } : it));
|
||||
const { rows: out } = quizToRows(withAuto, 'duel');
|
||||
expect(out[0]).toEqual(['순번', '유튜브 영상 링크', '제목', '가수', '조회수', '시작(초)', '하이라이트(초)']);
|
||||
const text = out.map((r) => r.map((c) => (c === null ? '' : String(c))));
|
||||
expect(parseQuizRows(text, guessColumns(text[0]!), 0, 'duel').items).toEqual(p.items);
|
||||
expect(parseQuizRows(text, guessColumns(text[0]!), 0, 'duel').items.map((i) => i.views)).toEqual([3456789, null, null]);
|
||||
// nothing written by hand: no 조회수 column at all
|
||||
expect(quizToRows([{ ...p.items[2]! }], 'duel').rows[0]).not.toContain('조회수');
|
||||
// 빈 양식: no 조회수 column, the example row reads back with its views left to the server
|
||||
const t = quizTemplateRows('duel').rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
|
||||
expect(parseQuizRows(t, guessColumns(t[0]!), 0, 'duel').items).toHaveLength(1);
|
||||
expect(t[0]).toEqual(['순번', '유튜브 영상 링크', '제목', '가수', '시작(초)', '하이라이트(초)']);
|
||||
expect(parseQuizRows(t, guessColumns(t[0]!), 0, 'duel').items.map((i) => [i.title, i.views])).toEqual([['라일락', null]]);
|
||||
});
|
||||
|
||||
@@ -133,7 +133,8 @@ export interface ParsedQuizFile {
|
||||
/**
|
||||
* Sheet rows (header at `headerAt`) → quiz songs. Empty rows are skipped silently; rows with a bad link, no answer or a
|
||||
* video already used above are listed with the reason and left out. A 순번 column decides the order (rows without one last).
|
||||
* 이지선다 (`kind` duel): 정답 = 제목, 설명 = 가수, and every song needs its 조회수.
|
||||
* 이지선다 (`kind` duel): 정답 = 제목, 설명 = 가수. 조회수 is optional: a number written there is used as is,
|
||||
* an empty one is fetched by the server after upload (토픽 + MV).
|
||||
*/
|
||||
export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[], headerAt = 0, kind: QuizKind = 'normal'): ParsedQuizFile {
|
||||
const duel = kind === 'duel';
|
||||
@@ -167,9 +168,7 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
|
||||
? duel
|
||||
? '제목이 비어 있어요'
|
||||
: '정답이 비어 있어요'
|
||||
: views === null && duel
|
||||
? '조회수가 비어 있어요'
|
||||
: views === undefined
|
||||
: views === undefined
|
||||
? `조회수를 읽을 수 없어요 (${cell(r, at('views')).slice(0, 30)})`
|
||||
: seen.has(videoId)
|
||||
? `${seen.get(videoId)}번째 줄과 같은 영상이에요`
|
||||
@@ -200,6 +199,7 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
|
||||
startSec: own ? (start ?? 0) : null,
|
||||
highlightSec: own ? (highlight ?? null) : null,
|
||||
views: duel ? (views ?? null) : null,
|
||||
viewsAuto: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -209,9 +209,12 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
|
||||
/** Quiz songs → sheet rows with the headers this file format reads back (내보내기, 빈 양식). */
|
||||
export function quizToRows(items: QuizItem[], kind: QuizKind = 'normal'): { rows: (string | number | null)[][]; widths: number[] } {
|
||||
if (kind === 'duel') {
|
||||
const header = ['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', '조회수', '시작(초)', '하이라이트(초)'];
|
||||
const rows = items.map((it, i) => [i + 1, `https://youtu.be/${it.videoId}`, it.title, it.artist, it.views, it.auto ? null : (it.startSec ?? 0), it.auto ? null : it.highlightSec]);
|
||||
return { rows: [header, ...rows], widths: [6, 32, 30, 24, 16, 10, 14] };
|
||||
// 조회수 only for numbers written by hand: fetched ones (and empty ones) are fetched again when the file comes back
|
||||
const own = (it: QuizItem) => (it.viewsAuto ? null : it.views);
|
||||
const withViews = items.some((it) => own(it) !== null);
|
||||
const header = ['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', ...(withViews ? ['조회수'] : []), '시작(초)', '하이라이트(초)'];
|
||||
const rows = items.map((it, i) => [i + 1, `https://youtu.be/${it.videoId}`, it.title, it.artist, ...(withViews ? [own(it)] : []), it.auto ? null : (it.startSec ?? 0), it.auto ? null : it.highlightSec]);
|
||||
return { rows: [header, ...rows], widths: [6, 32, 30, 24, ...(withViews ? [16] : []), 10, 14] };
|
||||
}
|
||||
const hintN = Math.max(1, ...items.map((i) => i.hints.length));
|
||||
const hintHeads = hintN === 1 ? ['힌트'] : Array.from({ length: hintN }, (_, i) => `힌트${i + 1}`);
|
||||
@@ -235,7 +238,7 @@ export function quizTemplateRows(kind: QuizKind = 'normal'): { rows: (string | n
|
||||
if (kind === 'duel')
|
||||
return quizToRows(
|
||||
[
|
||||
{ songId: null, videoId: 'v7bnOxV4jAc', title: '라일락', artist: '아이유', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views: 123456789 },
|
||||
{ songId: null, videoId: 'v7bnOxV4jAc', title: '라일락', artist: '아이유', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views: null, viewsAuto: null },
|
||||
],
|
||||
'duel',
|
||||
);
|
||||
@@ -254,6 +257,7 @@ export function quizTemplateRows(kind: QuizKind = 'normal'): { rows: (string | n
|
||||
startSec: null,
|
||||
highlightSec: null,
|
||||
views: null,
|
||||
viewsAuto: null,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user