114 lines
7.9 KiB
TypeScript
114 lines
7.9 KiB
TypeScript
/** 관리자 → 원곡 찾기: tabs from a real matcher run, and the row actions (확정 · 확정 취소 · 원곡 없음 · 다시 찾기). */
|
|
import { afterEach, expect, test } from 'bun:test';
|
|
import { Catalog } from './collector/catalog';
|
|
import { matchYoutube } from './collector/match-youtube';
|
|
import { quizSong } from './songs/quiz';
|
|
import { parseLog, reviewJob } from './songs/youtube-review';
|
|
import { api, boot, discordLogin, TEST_SUPERADMINS } from './test-utils';
|
|
|
|
let s: ReturnType<typeof boot>;
|
|
afterEach(async () => s && (await s.stop()));
|
|
|
|
test('원곡 찾기 tabs and actions; admin choices stick across matcher runs', async () => {
|
|
s = boot(
|
|
{
|
|
discordExchange: async (code) => ({ id: code, username: 'u', global_name: '관리', avatar: null }),
|
|
checkEmbed: async (id) => ({ state: 'ok', author: 'X - Topic', title: `t${id}` }),
|
|
},
|
|
{ DISCORD_CLIENT_ID: 'c', DISCORD_CLIENT_SECRET: 's' },
|
|
);
|
|
const { cookie } = await discordLogin(s.base, TEST_SUPERADMINS[0]);
|
|
const call = (path: string, init: RequestInit = {}) => api(s.base, `/api/admin${path}`, { ...init, cookie: cookie! });
|
|
const c = new Catalog(s.db);
|
|
const [found] = c.upsert({ title: 'Love wins all', artists: [{ name: '아이유' }], durationSec: 272, source: 't', ref: '1' });
|
|
const [guess] = c.upsert({ title: '한사람을 위해', artists: [{ name: '안재모' }], durationSec: 293, source: 't', ref: '2' });
|
|
const [nothing] = c.upsert({ title: '없는노래', artists: [{ name: '누구' }], source: 't', ref: '3' });
|
|
const [later] = c.upsert({ title: '아직안찾음', artists: [{ name: '누구' }], source: 't', ref: '4' });
|
|
const searcher = {
|
|
searchSongs: async (q: string) =>
|
|
({
|
|
'아이유 Love wins all': [{ videoId: 'Wu5FY8J6P8Q', title: 'Love wins all', artists: '아이유', album: 'The Winning', durationSec: 272 }],
|
|
'안재모 한사람을 위해': [
|
|
{ videoId: 'othersong01', title: '한사람을 위해 (Live)', artists: '다른 가수', album: null, durationSec: 120 },
|
|
{ videoId: 'othersong02', title: '한사람을 위해', artists: '안재모 팬', album: null, durationSec: 400 },
|
|
],
|
|
})[q] ?? [],
|
|
};
|
|
// the matcher has looked at three of the four songs
|
|
s.db.query('UPDATE songs SET deleted_at = 1 WHERE id = ?').run(later);
|
|
await matchYoutube(s.db, searcher, { delayMs: 0 }, async (id) => ({ state: 'ok', author: id === 'Wu5FY8J6P8Q' ? 'IU - Topic' : 'fan', title: id }));
|
|
s.db.query('UPDATE songs SET deleted_at = NULL WHERE id = ?').run(later);
|
|
|
|
const tab = async (t: string) => (await call(`/youtube?tab=${t}`)).body;
|
|
const ids = async (t: string) => (await tab(t)).rows.map((r: any) => r.id);
|
|
const first = await tab('matched');
|
|
expect(first.counts).toEqual({ matched: 1, candidate: 1, missing: 1, noorig: 0, dead: 0, pending: 1 });
|
|
expect(first.job).toMatchObject({ status: 'done', done: 3, total: 3, result: { matched: 1, candidate: 1, none: 1 } });
|
|
expect(first.rows[0]).toMatchObject({ id: found, youtube_id: 'Wu5FY8J6P8Q', youtube_channel: 'IU - Topic' });
|
|
expect(first.rows[0].score).toBeGreaterThan(0);
|
|
expect(first.rows[0].candidates[0].video_id).toBe('Wu5FY8J6P8Q');
|
|
expect(await ids('candidate')).toEqual([guess]);
|
|
expect(await ids('missing')).toEqual([nothing]);
|
|
expect(await ids('pending')).toEqual([later]);
|
|
expect((await call('/youtube?tab=matched&q=아이유')).body.total).toBe(1);
|
|
expect((await call('/youtube?tab=matched&q=안재모')).body.total).toBe(0);
|
|
|
|
// 확정 취소: back to 후보, out of the game pool, and the matcher does not confirm it again
|
|
expect((await call(`/youtube/${found}/unconfirm`, { method: 'POST' })).res.status).toBe(200);
|
|
expect((await call(`/youtube/${found}/unconfirm`, { method: 'POST' })).res.status).toBe(400);
|
|
expect((await ids('candidate')).sort()).toEqual([found, guess].sort());
|
|
expect(quizSong(s.db, found)!.videoId).toBeNull();
|
|
s.db.query("DELETE FROM signals WHERE kind LIKE 'yt_tried_%'").run(); // a week later
|
|
await matchYoutube(s.db, searcher, { delayMs: 0 }, async () => ({ state: 'ok', author: 'IU - Topic', title: 'x' }));
|
|
expect((await call(`/songs/${found}`)).body.song).toMatchObject({ youtube_status: 'candidate', youtube_source: 'admin' });
|
|
|
|
// 확정 with another candidate (the existing save path)
|
|
expect((await call(`/songs/${guess}`, { method: 'PATCH', body: JSON.stringify({ youtube: 'https://youtu.be/othersong02' }) })).res.status).toBe(200);
|
|
expect((await tab('matched')).rows[0]).toMatchObject({ id: guess, youtube_id: 'othersong02', youtube_source: 'admin' });
|
|
|
|
// 원곡 없음: own tab, never searched again
|
|
expect((await call(`/youtube/${nothing}/no-original`, { method: 'POST' })).res.status).toBe(200);
|
|
expect(await ids('noorig')).toEqual([nothing]);
|
|
expect(await ids('missing')).toEqual([later]); // tried by the second run, nothing found
|
|
// 다시 찾기 brings it back to 대기
|
|
await call('/songs/bulk', { method: 'POST', body: JSON.stringify({ ids: [nothing], action: 'rematch' }) });
|
|
expect(await ids('pending')).toEqual([nothing]);
|
|
|
|
const audit = (await call('/audit')).body.entries.map((e: any) => e.action);
|
|
expect(audit).toEqual(expect.arrayContaining(['song.youtube.unconfirm', 'song.youtube.none', 'song.update']));
|
|
expect((await call('/youtube?tab=nope')).body.tab).toBe('candidate');
|
|
});
|
|
|
|
test('원곡 찾기 진행 상황: speed over the last 10 minutes, ETA, stale process, last songs, log across midnight, earlier runs', () => {
|
|
s = boot();
|
|
const c = new Catalog(s.db);
|
|
const ids = Array.from({ length: 30 }, (_, i) => c.upsert({ title: `곡${i}`, artists: [{ name: '가수' }], source: 't', ref: String(i) })[0]!);
|
|
const day = Date.UTC(2026, 9, 19);
|
|
const start = day + 23 * 3600_000 + 50 * 60_000; // 23:50 UTC
|
|
s.db.query("INSERT INTO collect_jobs (kind, status, done, total, started_at, finished_at) VALUES ('match-youtube', 'done', 5, 5, ?, ?)").run(start - 86400_000, start - 86000_000);
|
|
const log = ['23:50:00 start 100 songs via ytmusic deadline 2026-10-20T07:55:00.000Z', '23:59:59 youtube 50/100 matched 40 candidate 5 none 5', '00:01:00 search failed (429), waiting 60s', ''].join('\n');
|
|
const job = Number(s.db.query("INSERT INTO collect_jobs (kind, status, done, total, started_at, pid, log) VALUES ('match-youtube', 'running', 30, 100, ?, 4242, ?)").run(start, log).lastInsertRowid);
|
|
// 20 songs in the first 10 minutes, 10 in the last 10: the ETA follows the recent pace (1 song a minute)
|
|
const now = start + 20 * 60_000;
|
|
ids.forEach((id, i) => {
|
|
const at = i < 20 ? start + i * 30_000 : now - 10 * 60_000 + (i - 19) * 60_000 - 1;
|
|
s.db.query("INSERT INTO signals (song_id, kind, value, fetched_at) VALUES (?, 'yt_tried_ytmusic', ?, ?)").run(id, at, at);
|
|
});
|
|
s.db.query("UPDATE songs SET youtube_status = 'matched', youtube_id = 'v', youtube_title = '영상' WHERE id = ?").run(ids[29]!);
|
|
const alive: number[] = [];
|
|
const r = reviewJob(s.db, now, (pid) => (alive.push(pid), false))!;
|
|
expect(r).toMatchObject({ id: job, status: 'running', source: 'ytmusic', alive: false, lastAt: now - 1, deadline: Date.parse('2026-10-20T07:55:00.000Z') });
|
|
expect(alive).toEqual([4242]);
|
|
expect(r.perMin).toBe(1);
|
|
expect(r.eta).toBe(now + 70 * 60_000);
|
|
expect(r.result).toEqual({ matched: 1, candidate: 0, none: 29 });
|
|
expect(r.recent.map((x) => x.id)).toEqual(ids.slice(22).reverse());
|
|
expect(r.recent[0]).toMatchObject({ youtube_status: 'matched', youtube_title: '영상' });
|
|
expect(r.log.map((l) => l.at)).toEqual([start, day + 86400_000 - 1000, day + 86400_000 + 60_000]);
|
|
expect(r.history).toHaveLength(1);
|
|
// a finished run: no ETA, no process check
|
|
s.db.query("UPDATE collect_jobs SET status = 'done', finished_at = ? WHERE id = ?").run(now, job);
|
|
expect(reviewJob(s.db, now + 3600_000, () => true)).toMatchObject({ eta: null, alive: null, perMin: 1 });
|
|
expect(parseLog('garbage\n10:00:00 hi', Date.UTC(2026, 0, 1, 9))).toEqual([{ at: Date.UTC(2026, 0, 1, 10), text: 'hi' }]);
|
|
});
|