132 lines
6.6 KiB
TypeScript
132 lines
6.6 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 { isConfident, scoreResult, type Scored } from './score';
|
|
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;
|
|
}
|
|
|
|
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';
|
|
// 관리자 → 원곡 찾기 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) =>
|
|
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;
|
|
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;
|
|
}
|
|
let results: YtmSong[];
|
|
const query = `${s.artist.split(', ')[0]} ${s.title}`;
|
|
try {
|
|
results = 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);
|
|
results = await ytm.searchSongs(query);
|
|
}
|
|
const scored: Scored[] = results.slice(0, 8).map((r, rank) => scoreResult({ title: s.title, artist: s.artist, durationSec: s.duration_sec }, r, rank));
|
|
scored.sort((a, b) => b.score - a.score);
|
|
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(s.id, c.videoId, c.title, c.artists, c.durationSec, c.score, src);
|
|
}
|
|
let done = false;
|
|
for (const c of scored.filter(isConfident)) {
|
|
const e = await embed(c.videoId);
|
|
if (e.state === 'ok') {
|
|
done = true;
|
|
if (setVideo(s.id, 'matched', { videoId: c.videoId, author: e.author, title: e.title }, src)) {
|
|
if (!s.duration_sec && c.durationSec) db.query('UPDATE songs SET duration_sec = ? WHERE id = ?').run(c.durationSec, s.id);
|
|
stats.matched++;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
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;
|
|
}
|