311 lines
16 KiB
TypeScript
311 lines
16 KiB
TypeScript
/**
|
|
* Finds the official audio (Topic / Art Track) for each song via YouTube Music song search (docs/08 §1),
|
|
* checks it can be embedded (IFrame playback, docs/12 Q1) and records candidates for the admin.
|
|
* Resumable: songs tried in the last `retryDays` are skipped. Stops on cookie problems.
|
|
*/
|
|
import type { Database } from 'bun:sqlite';
|
|
import { Job, sleep } from './catalog';
|
|
import { checkEmbed } from './oembed';
|
|
import { confirmedDespiteLength, isConfident, isJunkTitle, isVideoTitle, namesOtherCut, scoreResult, type Scored } from './score';
|
|
import { learnArtistAliases } from './artist-aliases';
|
|
import { otherScriptNames } from './other-names';
|
|
import { CookieError, type YtMusic, type YtmSong } from './ytmusic';
|
|
|
|
interface Row {
|
|
id: number;
|
|
title: string;
|
|
artist: string;
|
|
duration_sec: number | null;
|
|
}
|
|
|
|
export interface MatchOptions {
|
|
limit?: number;
|
|
delayMs?: number;
|
|
retryDays?: number;
|
|
/** Stop cleanly (job done) once this time (epoch ms) has passed, e.g. before the nightly cron. */
|
|
deadline?: number;
|
|
/** Where results come from: recorded on songs and candidates. */
|
|
source?: 'ytmusic' | 'youtube';
|
|
log?: (s: string) => void;
|
|
}
|
|
|
|
/** Writes an automatic result only while the song is still open for automatic matching (no admin choice meanwhile). */
|
|
function setAutoVideo(db: Database, id: number, status: 'matched' | 'candidate', v: { videoId: string; author: string; title: string }, source: string): boolean {
|
|
return (
|
|
db
|
|
.query(
|
|
`UPDATE songs SET youtube_id = ?, youtube_status = ?, youtube_source = ?, youtube_channel = ?, youtube_title = ?, embeddable = 1,
|
|
youtube_checked_at = ?, updated_at = ?
|
|
WHERE id = ? AND COALESCE(youtube_source, '') <> 'admin' AND youtube_status IN ('none','candidate')`,
|
|
)
|
|
.run(v.videoId, status, source, v.author, v.title, Date.now(), Date.now(), id).changes === 1
|
|
);
|
|
}
|
|
|
|
/**
|
|
* A result confirmed despite a length difference (title + artist) whose actual video turns out to be a music video,
|
|
* inst., live, another mix … (the YouTube title, not the search row): left as 후보.
|
|
*/
|
|
function isOtherCut(c: Scored, videoTitle: string, songTitle: string): boolean {
|
|
if (!confirmedDespiteLength(c)) return false;
|
|
return (isVideoTitle(videoTitle) && !isVideoTitle(songTitle)) || (isJunkTitle(videoTitle) && !isJunkTitle(songTitle)) || namesOtherCut(videoTitle, songTitle);
|
|
}
|
|
|
|
async function searchRetry(ytm: Pick<YtMusic, 'searchSongs'>, query: string, job: Job | null): Promise<YtmSong[]> {
|
|
try {
|
|
return await ytm.searchSongs(query);
|
|
} catch (e) {
|
|
if (e instanceof CookieError) throw e;
|
|
job?.log(`search failed (${(e as Error).message}), waiting 60s`);
|
|
await sleep(60_000);
|
|
return ytm.searchSongs(query);
|
|
}
|
|
}
|
|
|
|
/** Results of another search added to the ones we have (the same video once, its better score kept). */
|
|
function mergeScored(a: Scored[], b: Scored[]): Scored[] {
|
|
const byId = new Map(a.map((c) => [c.videoId, c]));
|
|
for (const c of b) if (!byId.has(c.videoId) || byId.get(c.videoId)!.score < c.score) byId.set(c.videoId, c);
|
|
return [...byId.values()];
|
|
}
|
|
|
|
/** Keeps the best 5 results (already sorted) for the admin and for reconfirm-youtube. */
|
|
function saveCandidates(db: Database, songId: number, scored: Scored[], src: string) {
|
|
for (const c of scored.slice(0, 5)) {
|
|
db.query(
|
|
`INSERT INTO youtube_candidates (song_id, video_id, title, channel, duration_sec, score, source) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(song_id, video_id) DO UPDATE SET title = excluded.title, channel = excluded.channel, duration_sec = excluded.duration_sec, score = excluded.score`,
|
|
).run(songId, c.videoId, c.title, c.artists, c.durationSec, c.score, src);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Confirms the best confident result that plays (and is not an MV/other cut when the length is off).
|
|
* Returns null when none did, true when the song was changed, false when an admin had settled it meanwhile.
|
|
*/
|
|
async function confirmFirst(db: Database, s: Row, scored: Scored[], src: string, embed: typeof checkEmbed, delayMs = 0): Promise<boolean | null> {
|
|
for (const c of scored.filter(isConfident)) {
|
|
const e = await embed(c.videoId);
|
|
if (delayMs) await sleep(delayMs);
|
|
if (e.state !== 'ok' || isOtherCut(c, e.title, s.title)) continue;
|
|
const changed = setAutoVideo(db, s.id, 'matched', { videoId: c.videoId, author: e.author, title: e.title }, src);
|
|
if (changed && !s.duration_sec && c.durationSec) db.query('UPDATE songs SET duration_sec = ? WHERE id = ?').run(c.durationSec, s.id);
|
|
return changed;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export async function matchYoutube(db: Database, ytm: Pick<YtMusic, 'searchSongs'>, opts: MatchOptions = {}, embed = checkEmbed) {
|
|
const retryBefore = Date.now() - (opts.retryDays ?? 7) * 86400_000;
|
|
// Tries are remembered per search method: songs the weaker fallback could not settle are retried once the cookie works.
|
|
const triedKind = `yt_tried_${opts.source ?? 'ytmusic'}`;
|
|
const rows = db
|
|
.query<Row, [string, number, number]>(
|
|
`SELECT s.id, s.title, s.artist, s.duration_sec FROM songs s
|
|
LEFT JOIN signals t ON t.song_id = s.id AND t.kind = ?
|
|
LEFT JOIN song_levels l ON l.song_id = s.id AND l.scope = 'all'
|
|
WHERE s.deleted_at IS NULL AND s.youtube_status IN ('none','candidate') AND COALESCE(s.youtube_source, '') <> 'admin'
|
|
AND (t.value IS NULL OR t.value < ?)
|
|
ORDER BY l.level IS NULL, l.level, s.id LIMIT ?`,
|
|
)
|
|
.all(triedKind, retryBefore, opts.limit ?? 1_000_000);
|
|
const job = new Job(db, 'match-youtube', rows.length);
|
|
const stats = { matched: 0, candidate: 0, none: 0 };
|
|
let tried = 0;
|
|
const src = opts.source ?? 'ytmusic';
|
|
const aliases = learnArtistAliases(db);
|
|
const otherNames = otherScriptNames(db);
|
|
// 관리자 → 원곡 찾기 reads the deadline back from this line
|
|
job.log(`start ${rows.length} songs via ${src}${opts.deadline !== undefined ? ` deadline ${new Date(opts.deadline).toISOString()}` : ''}`);
|
|
/**
|
|
* Writes the result only if the song is still open for automatic matching: an admin may have saved a video
|
|
* while we were waiting on the search. Returns whether the row was changed.
|
|
*/
|
|
const setVideo = (id: number, status: 'matched' | 'candidate', v: { videoId: string; author: string; title: string }, source: string) => setAutoVideo(db, id, status, v, source);
|
|
const adminOwned = (id: number) =>
|
|
db.query<{ n: number }, [number]>("SELECT COUNT(*) n FROM songs WHERE id = ? AND COALESCE(youtube_source, '') = 'admin'").get(id)!.n > 0;
|
|
try {
|
|
for (const [i, s] of rows.entries()) {
|
|
if (opts.deadline !== undefined && Date.now() >= opts.deadline) {
|
|
job.log(`deadline reached after ${i}/${rows.length}`);
|
|
break;
|
|
}
|
|
const song = { title: s.title, artist: s.artist, durationSec: s.duration_sec };
|
|
let scored = (await searchRetry(ytm, `${s.artist.split(', ')[0]} ${s.title}`, job)).slice(0, 8).map((r, rank) => scoreResult(song, r, rank, aliases));
|
|
// Melon wrote the artist in the other script ("디제이디오씨" for DJ DOC) and no result is by them: search again by that name
|
|
if (!scored.some(isConfident) && !scored.some((c) => c.artistOk || c.artistSound)) {
|
|
for (const name of otherNames(s.artist)) {
|
|
await sleep(opts.delayMs ?? 2000);
|
|
// only that artist's songs count from this search: the same title by someone else is not the song
|
|
const byArtist = (await searchRetry(ytm, `${name} ${s.title}`, job)).slice(0, 8).map((r, rank) => scoreResult(song, r, rank, aliases)).filter((c) => c.artistOk || c.artistSound);
|
|
scored = mergeScored(scored, byArtist);
|
|
if (scored.some(isConfident)) break;
|
|
}
|
|
}
|
|
scored.sort((a, b) => b.score - a.score);
|
|
saveCandidates(db, s.id, scored, src);
|
|
const confirmed = await confirmFirst(db, s, scored, src, embed);
|
|
let done = confirmed !== null;
|
|
if (confirmed) stats.matched++;
|
|
if (!done && adminOwned(s.id)) done = true; // an admin settled it meanwhile
|
|
if (!done) {
|
|
// Not sure: keep the best playable guess as a candidate for the admin (title match first, then norabose's video).
|
|
const fallbacks: { videoId: string; source: string }[] = [
|
|
...scored.filter((c) => c.titleOk).slice(0, 2).map((c) => ({ videoId: c.videoId, source: src })),
|
|
...db.query<{ video_id: string }, [number]>("SELECT video_id FROM youtube_candidates WHERE song_id = ? AND source = 'norabose'").all(s.id).map((r) => ({ videoId: r.video_id, source: 'norabose' })),
|
|
];
|
|
for (const f of fallbacks) {
|
|
const e = await embed(f.videoId);
|
|
if (e.state === 'ok') {
|
|
if (setVideo(s.id, 'candidate', { videoId: f.videoId, author: e.author, title: e.title }, f.source)) stats.candidate++;
|
|
done = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!done) stats.none++;
|
|
}
|
|
db.query('INSERT INTO signals (song_id, kind, value, fetched_at) VALUES (?, ?, ?, ?) ON CONFLICT(song_id, kind) DO UPDATE SET value = excluded.value, fetched_at = excluded.fetched_at').run(s.id, triedKind, Date.now(), Date.now());
|
|
tried = i + 1;
|
|
job.progress(tried);
|
|
if ((i + 1) % 50 === 0) job.log(`youtube ${i + 1}/${rows.length} matched ${stats.matched} candidate ${stats.candidate} none ${stats.none}`);
|
|
await sleep(opts.delayMs ?? 2000);
|
|
}
|
|
job.log(`youtube done ${tried}/${rows.length}: matched ${stats.matched} candidate ${stats.candidate} none ${stats.none}`);
|
|
job.finish('done');
|
|
} catch (e) {
|
|
job.log(`stopped: ${(e as Error).message}`);
|
|
job.finish(e instanceof CookieError ? 'stopped' : 'failed');
|
|
throw e;
|
|
}
|
|
return stats;
|
|
}
|
|
|
|
/**
|
|
* Re-checks songs left as 후보 (or 못 찾음 with saved results) against the YouTube Music results already saved for them, with the current rules
|
|
* (accent-insensitive names, 및/with separators, learnt Korean/English artist names, benign "Radio Edit Version",
|
|
* "한글 English" names split, Hangul/Latin artist names that sound the same, title + artist whatever the length).
|
|
* No search: only the embed check per confirmed video. `dryRun` counts without writing or calling YouTube.
|
|
*/
|
|
export async function reconfirmCandidates(db: Database, opts: { dryRun?: boolean; delayMs?: number; log?: (s: string) => void } = {}, embed = checkEmbed) {
|
|
const aliases = learnArtistAliases(db);
|
|
const songs = db
|
|
.query<Row, []>(
|
|
`SELECT id, title, artist, duration_sec FROM songs
|
|
WHERE deleted_at IS NULL AND youtube_status IN ('candidate','none') AND COALESCE(youtube_source, '') <> 'admin' ORDER BY id`,
|
|
)
|
|
.all();
|
|
const cands = db.query<{ video_id: string; title: string | null; channel: string | null; duration_sec: number | null }, [number]>(
|
|
"SELECT video_id, title, channel, duration_sec FROM youtube_candidates WHERE song_id = ? AND source = 'ytmusic' ORDER BY score DESC",
|
|
);
|
|
const job = opts.dryRun ? null : new Job(db, 'reconfirm-youtube', songs.length);
|
|
job?.log(`start ${songs.length} candidate songs, ${aliases.size} learnt artist names`);
|
|
const stats = { checked: songs.length, matched: 0, unconfirmed: 0, aliases: aliases.size };
|
|
try {
|
|
for (const [i, s] of songs.entries()) {
|
|
const scored = cands
|
|
.all(s.id)
|
|
.map((c) => scoreResult({ title: s.title, artist: s.artist, durationSec: s.duration_sec }, { videoId: c.video_id, title: c.title ?? '', artists: c.channel ?? '', album: null, durationSec: c.duration_sec }, -1, aliases))
|
|
.filter(isConfident)
|
|
.sort((a, b) => b.score - a.score);
|
|
// unconfirmed: none of them plays, or the video turned out to be an MV/another cut
|
|
if (opts.dryRun) {
|
|
const c = scored[0];
|
|
if (c) {
|
|
stats.matched++;
|
|
opts.log?.(`${s.id}\t${s.artist} - ${s.title}\t→ ${c.artists} - ${c.title} (${c.lengthDiff ?? '?'}s)`);
|
|
}
|
|
} else if (scored.length) {
|
|
const r = await confirmFirst(db, s, scored, 'ytmusic', embed, opts.delayMs ?? 300);
|
|
if (r) stats.matched++;
|
|
else if (r === null) stats.unconfirmed++;
|
|
}
|
|
job?.progress(i + 1);
|
|
}
|
|
job?.log(`reconfirm done: matched ${stats.matched} of ${songs.length}`);
|
|
job?.finish('done');
|
|
} catch (e) {
|
|
job?.log(`stopped: ${(e as Error).message}`);
|
|
job?.finish('failed');
|
|
throw e;
|
|
}
|
|
return stats;
|
|
}
|
|
|
|
/**
|
|
* Searches again, by the artist's name in the other script, the 후보/못 찾음 songs whose saved results have no song by
|
|
* that artist at all ("디제이디오씨 Everybody" → "DJ DOC Everybody"). Only confirms: an unsure song keeps its 후보 video.
|
|
* Each song is searched again once per search method (signal yt_research_<source>).
|
|
*/
|
|
export async function researchYoutube(
|
|
db: Database,
|
|
ytm: Pick<YtMusic, 'searchSongs'>,
|
|
opts: { limit?: number; delayMs?: number; deadline?: number; dryRun?: boolean; source?: 'ytmusic' | 'youtube'; log?: (s: string) => void } = {},
|
|
embed = checkEmbed,
|
|
) {
|
|
const src = opts.source ?? 'ytmusic';
|
|
const kind = `yt_research_${src}`;
|
|
const aliases = learnArtistAliases(db);
|
|
const otherNames = otherScriptNames(db);
|
|
const cands = db.query<{ video_id: string; title: string | null; channel: string | null; duration_sec: number | null }, [number]>(
|
|
"SELECT video_id, title, channel, duration_sec FROM youtube_candidates WHERE song_id = ? AND source IN ('ytmusic','youtube')",
|
|
);
|
|
const targets: (Row & { names: string[] })[] = [];
|
|
for (const s of db
|
|
.query<Row, [string]>(
|
|
`SELECT s.id, s.title, s.artist, s.duration_sec FROM songs s
|
|
LEFT JOIN signals t ON t.song_id = s.id AND t.kind = ?
|
|
LEFT JOIN song_levels l ON l.song_id = s.id AND l.scope = 'all'
|
|
WHERE s.deleted_at IS NULL AND s.youtube_status IN ('candidate','none') AND COALESCE(s.youtube_source, '') <> 'admin' AND t.value IS NULL
|
|
ORDER BY l.level IS NULL, l.level, s.id`,
|
|
)
|
|
.all(kind)) {
|
|
const song = { title: s.title, artist: s.artist, durationSec: s.duration_sec };
|
|
const saved = cands.all(s.id).map((c) => scoreResult(song, { videoId: c.video_id, title: c.title ?? '', artists: c.channel ?? '', album: null, durationSec: c.duration_sec }, -1, aliases));
|
|
if (saved.some((c) => isConfident(c) || c.artistOk || c.artistSound)) continue;
|
|
const names = otherNames(s.artist);
|
|
if (names.length) targets.push({ ...s, names });
|
|
if (opts.limit !== undefined && targets.length >= opts.limit) break;
|
|
}
|
|
const stats = { songs: targets.length, searches: 0, matched: 0 };
|
|
if (opts.dryRun) {
|
|
for (const s of targets) opts.log?.(`${s.id}\t${s.artist} - ${s.title}\t→ ${s.names.join(' | ')}`);
|
|
return stats;
|
|
}
|
|
const job = new Job(db, 'research-youtube', targets.length);
|
|
job.log(`start ${targets.length} songs via ${src}, searching again by the artist's other-script name`);
|
|
try {
|
|
for (const [i, s] of targets.entries()) {
|
|
if (opts.deadline !== undefined && Date.now() >= opts.deadline) {
|
|
job.log(`deadline reached after ${i}/${targets.length}`);
|
|
break;
|
|
}
|
|
const song = { title: s.title, artist: s.artist, durationSec: s.duration_sec };
|
|
let scored: Scored[] = [];
|
|
for (const name of s.names) {
|
|
// only that artist's songs: the same title by someone else is not the song
|
|
const found = (await searchRetry(ytm, `${name} ${s.title}`, job)).slice(0, 8).map((r, rank) => scoreResult(song, r, rank, aliases)).filter((c) => c.artistOk || c.artistSound);
|
|
stats.searches++;
|
|
scored = mergeScored(scored, found);
|
|
await sleep(opts.delayMs ?? 2000);
|
|
if (scored.some(isConfident)) break;
|
|
}
|
|
scored.sort((a, b) => b.score - a.score);
|
|
saveCandidates(db, s.id, scored, src);
|
|
if (await confirmFirst(db, s, scored, src, embed)) {
|
|
stats.matched++;
|
|
opts.log?.(`${s.id}\t${s.artist} - ${s.title}\t→ ${scored.find(isConfident)?.artists} - ${scored.find(isConfident)?.title}`);
|
|
}
|
|
db.query('INSERT INTO signals (song_id, kind, value, fetched_at) VALUES (?, ?, ?, ?) ON CONFLICT(song_id, kind) DO UPDATE SET value = excluded.value, fetched_at = excluded.fetched_at').run(s.id, kind, Date.now(), Date.now());
|
|
job.progress(i + 1);
|
|
if ((i + 1) % 25 === 0) job.log(`research ${i + 1}/${targets.length} matched ${stats.matched}`);
|
|
}
|
|
job.log(`research done: matched ${stats.matched} of ${targets.length} (${stats.searches} searches)`);
|
|
job.finish('done');
|
|
} catch (e) {
|
|
job.log(`stopped: ${(e as Error).message}`);
|
|
job.finish(e instanceof CookieError ? 'stopped' : 'failed');
|
|
throw e;
|
|
}
|
|
return stats;
|
|
}
|