- 노라보세: 8,572곡(멜론 ID·연도·최고순위·장르·5단계 난이도·가사), 500 나는 묶음은 반씩 나눠 재요청, 원본 캐시로 재실행 안전 - 스타맵 803곡: 같은 곡은 합치고(363) 새 곡 440, 맵 제작자 연도(올해)는 버림 - 유튜브: 제목·가수·길이 점수로 확정/후보, 퍼가기 금지 영상 제외, 검색 방식별로 시도 기록 - 관리자: 노래 검색·장르·연도·난이도·유튜브 상태·출처 필터, 편집 패널(미리듣기·후보 선택·하이라이트·별칭·숨김), 수집 기록 - 테스트 32개, e2e에 노래 편집 단계 추가 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
191 lines
9.8 KiB
TypeScript
191 lines
9.8 KiB
TypeScript
/** Song catalog queries for the admin pages (docs/02 노래 관리 화면). */
|
|
import type { Database } from 'bun:sqlite';
|
|
import { songMatchKey } from '@mq/shared';
|
|
|
|
export function catalogStats(db: Database) {
|
|
const one = <T>(sql: string) => db.query<T, []>(sql).get()!;
|
|
const songs = one<{ total: number; matched: number; candidate: number; none: number; dead: number; hidden: number }>(
|
|
`SELECT COUNT(*) total, SUM(youtube_status='matched') matched, SUM(youtube_status='candidate') candidate,
|
|
SUM(youtube_status='none') none, SUM(youtube_status='dead') dead, SUM(hidden) hidden FROM songs WHERE deleted_at IS NULL`,
|
|
);
|
|
const lyrics = one<{ n: number }>('SELECT COUNT(*) n FROM lyrics l JOIN songs s ON s.id = l.song_id WHERE s.deleted_at IS NULL').n;
|
|
const sources = db.query<{ source: string; n: number }, []>('SELECT source, COUNT(DISTINCT song_id) n FROM song_sources GROUP BY source').all();
|
|
const tried = one<{ n: number }>("SELECT COUNT(DISTINCT song_id) n FROM signals WHERE kind LIKE 'yt_tried_%'").n;
|
|
const jobs = db.query<{ id: number; kind: string; status: string; done: number; total: number; started_at: number; finished_at: number | null }, []>(
|
|
'SELECT id, kind, status, done, total, started_at, finished_at FROM collect_jobs ORDER BY id DESC LIMIT 5',
|
|
).all();
|
|
const z = (n: number | null) => n ?? 0;
|
|
return {
|
|
total: songs.total,
|
|
youtube: { matched: z(songs.matched), candidate: z(songs.candidate), none: z(songs.none), dead: z(songs.dead), tried },
|
|
hidden: z(songs.hidden),
|
|
lyrics,
|
|
sources: Object.fromEntries(sources.map((r) => [r.source, r.n])),
|
|
jobs,
|
|
};
|
|
}
|
|
|
|
export interface SongFilter {
|
|
q?: string;
|
|
genres?: string[];
|
|
yearFrom?: number;
|
|
yearTo?: number;
|
|
level?: number;
|
|
youtube?: 'matched' | 'candidate' | 'none' | 'dead';
|
|
source?: string;
|
|
hidden?: boolean;
|
|
lyrics?: boolean;
|
|
sort?: 'recent' | 'year' | 'level' | 'peak' | 'title';
|
|
page?: number;
|
|
}
|
|
|
|
export const PAGE = 50;
|
|
|
|
export function listSongs(db: Database, f: SongFilter) {
|
|
const where: string[] = ['s.deleted_at IS NULL'];
|
|
const args: (string | number)[] = [];
|
|
if (f.q) {
|
|
const like = `%${f.q.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
|
|
where.push(`(s.title LIKE ? ESCAPE '\\' OR s.artist LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM song_aliases a WHERE a.song_id = s.id AND a.alias LIKE ? ESCAPE '\\') OR s.youtube_id = ? OR CAST(s.melon_id AS TEXT) = ?)`);
|
|
args.push(like, like, like, f.q, f.q);
|
|
}
|
|
if (f.genres?.length) {
|
|
where.push(`EXISTS (SELECT 1 FROM song_genres g WHERE g.song_id = s.id AND g.genre_id IN (${f.genres.map(() => '?').join(',')}))`);
|
|
args.push(...f.genres);
|
|
}
|
|
if (f.yearFrom) (where.push('s.year >= ?'), args.push(f.yearFrom));
|
|
if (f.yearTo) (where.push('s.year <= ?'), args.push(f.yearTo));
|
|
if (f.level) (where.push('EXISTS (SELECT 1 FROM song_levels l WHERE l.song_id = s.id AND l.level = ?)'), args.push(f.level));
|
|
if (f.youtube) (where.push('s.youtube_status = ?'), args.push(f.youtube));
|
|
if (f.source) (where.push('EXISTS (SELECT 1 FROM song_sources x WHERE x.song_id = s.id AND x.source = ?)'), args.push(f.source));
|
|
if (f.hidden !== undefined) (where.push('s.hidden = ?'), args.push(f.hidden ? 1 : 0));
|
|
if (f.lyrics !== undefined) where.push(`${f.lyrics ? '' : 'NOT '}EXISTS (SELECT 1 FROM lyrics y WHERE y.song_id = s.id)`);
|
|
const order = {
|
|
recent: 's.id DESC',
|
|
year: 's.year DESC NULLS LAST, s.id',
|
|
level: 'lv.level NULLS LAST, s.id',
|
|
peak: 's.peak_rank NULLS LAST, s.id',
|
|
title: 's.title COLLATE NOCASE',
|
|
}[f.sort ?? 'recent'];
|
|
const w = where.join(' AND ');
|
|
const total = db.query<{ n: number }, (string | number)[]>(`SELECT COUNT(*) n FROM songs s WHERE ${w}`).get(...args)!.n;
|
|
const page = Math.max(0, f.page ?? 0);
|
|
const rows = db
|
|
.query<Record<string, unknown>, (string | number)[]>(
|
|
`SELECT s.id, s.melon_id, s.title, s.artist, s.year, s.duration_sec, s.youtube_id, s.youtube_status, s.youtube_source, s.youtube_channel,
|
|
s.peak_rank, s.hidden, s.highlight_sec, lv.level,
|
|
(SELECT group_concat(genre_id) FROM song_genres g WHERE g.song_id = s.id) genres,
|
|
(SELECT group_concat(DISTINCT source) FROM song_sources x WHERE x.song_id = s.id) sources,
|
|
EXISTS (SELECT 1 FROM lyrics y WHERE y.song_id = s.id) has_lyrics
|
|
FROM songs s LEFT JOIN song_levels lv ON lv.song_id = s.id AND lv.scope = 'all'
|
|
WHERE ${w} ORDER BY ${order} LIMIT ${PAGE} OFFSET ${page * PAGE}`,
|
|
)
|
|
.all(...args)
|
|
.map((r) => ({
|
|
...r,
|
|
genres: r.genres ? String(r.genres).split(',') : [],
|
|
sources: r.sources ? String(r.sources).split(',') : [],
|
|
hidden: !!r.hidden,
|
|
has_lyrics: !!r.has_lyrics,
|
|
}));
|
|
return { total, page, pageSize: PAGE, rows };
|
|
}
|
|
|
|
export function getSong(db: Database, id: number) {
|
|
const song = db.query<Record<string, unknown>, [number]>('SELECT * FROM songs WHERE id = ? AND deleted_at IS NULL').get(id);
|
|
if (!song) return null;
|
|
return {
|
|
song: { ...(song as { id: number; title: string; artist: string } & Record<string, unknown>), hidden: !!song.hidden },
|
|
genres: db.query<{ genre_id: string; source: string }, [number]>('SELECT genre_id, source FROM song_genres WHERE song_id = ?').all(id),
|
|
levels: db.query<{ scope: string; level: number; source: string }, [number]>('SELECT scope, level, source FROM song_levels WHERE song_id = ? ORDER BY scope').all(id),
|
|
aliases: db.query<{ part: string; alias: string; source: string }, [number]>('SELECT part, alias, source FROM song_aliases WHERE song_id = ?').all(id),
|
|
lyrics: db.query<{ text: string; source: string }, [number]>('SELECT text, source FROM lyrics WHERE song_id = ?').get(id),
|
|
sources: db.query<{ source: string; ref: string }, [number]>('SELECT source, ref FROM song_sources WHERE song_id = ?').all(id),
|
|
candidates: db
|
|
.query<Record<string, unknown>, [number]>('SELECT video_id, title, channel, duration_sec, score, source FROM youtube_candidates WHERE song_id = ? ORDER BY score DESC')
|
|
.all(id),
|
|
signals: db.query<{ kind: string; value: number }, [number]>('SELECT kind, value FROM signals WHERE song_id = ?').all(id),
|
|
};
|
|
}
|
|
|
|
export interface SongPatch {
|
|
title?: string;
|
|
artist?: string;
|
|
year?: number | null;
|
|
genres?: string[];
|
|
level?: number | null;
|
|
youtubeId?: string | null;
|
|
highlightSec?: number | null;
|
|
hidden?: boolean;
|
|
note?: string | null;
|
|
titleAliases?: string[];
|
|
artistAliases?: string[];
|
|
lyrics?: string | null;
|
|
}
|
|
|
|
/** Admin edit. Anything set here is marked as admin so collectors never overwrite it. */
|
|
export function updateSong(db: Database, id: number, p: SongPatch, embed?: { author: string; title: string }, now = Date.now()) {
|
|
db.transaction(() => {
|
|
const cur = db.query<{ title: string; artist: string }, [number]>('SELECT title, artist FROM songs WHERE id = ?').get(id)!;
|
|
const title = p.title ?? cur.title;
|
|
const artist = p.artist ?? cur.artist;
|
|
db.query(
|
|
`UPDATE songs SET title = ?, artist = ?, match_key = ?, year = CASE WHEN ? THEN ? ELSE year END,
|
|
highlight_sec = CASE WHEN ? THEN ? ELSE highlight_sec END, highlight_source = CASE WHEN ? THEN 'admin' ELSE highlight_source END,
|
|
hidden = COALESCE(?, hidden), note = CASE WHEN ? THEN ? ELSE note END, updated_at = ? WHERE id = ?`,
|
|
).run(
|
|
title,
|
|
artist,
|
|
songMatchKey(title, artist),
|
|
p.year !== undefined ? 1 : 0,
|
|
p.year ?? null,
|
|
p.highlightSec !== undefined ? 1 : 0,
|
|
p.highlightSec ?? null,
|
|
p.highlightSec !== undefined && p.highlightSec !== null ? 1 : 0,
|
|
p.hidden === undefined ? null : p.hidden ? 1 : 0,
|
|
p.note !== undefined ? 1 : 0,
|
|
p.note ?? null,
|
|
now,
|
|
id,
|
|
);
|
|
if (p.youtubeId !== undefined) {
|
|
if (p.youtubeId === null) db.query("UPDATE songs SET youtube_id = NULL, youtube_status = 'none', youtube_source = 'admin' WHERE id = ?").run(id);
|
|
else
|
|
db.query(
|
|
"UPDATE songs SET youtube_id = ?, youtube_status = 'matched', youtube_source = 'admin', youtube_channel = ?, youtube_title = ?, embeddable = 1, youtube_checked_at = ? WHERE id = ?",
|
|
).run(p.youtubeId, embed?.author ?? null, embed?.title ?? null, now, id);
|
|
}
|
|
if (p.genres) {
|
|
db.query('DELETE FROM song_genres WHERE song_id = ?').run(id);
|
|
for (const g of p.genres) db.query("INSERT INTO song_genres (song_id, genre_id, source) VALUES (?, ?, 'admin')").run(id, g);
|
|
}
|
|
if (p.level !== undefined) {
|
|
if (p.level === null) db.query("DELETE FROM song_levels WHERE song_id = ? AND scope = 'all'").run(id);
|
|
else
|
|
db.query("INSERT INTO song_levels (song_id, scope, level, source) VALUES (?, 'all', ?, 'admin') ON CONFLICT(song_id, scope) DO UPDATE SET level = excluded.level, source = 'admin'").run(id, p.level);
|
|
}
|
|
for (const [part, list] of [
|
|
['title', p.titleAliases],
|
|
['artist', p.artistAliases],
|
|
] as const) {
|
|
if (!list) continue;
|
|
db.query('DELETE FROM song_aliases WHERE song_id = ? AND part = ?').run(id, part);
|
|
for (const a of new Set(list.map((x) => x.trim()).filter(Boolean))) db.query("INSERT INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, 'admin')").run(id, part, a);
|
|
}
|
|
if (p.lyrics !== undefined) {
|
|
if (p.lyrics) db.query("INSERT INTO lyrics (song_id, text, source, fetched_at) VALUES (?, ?, 'admin', ?) ON CONFLICT(song_id) DO UPDATE SET text = excluded.text, source = 'admin', fetched_at = excluded.fetched_at").run(id, p.lyrics, now);
|
|
else db.query('DELETE FROM lyrics WHERE song_id = ?').run(id);
|
|
}
|
|
})();
|
|
}
|
|
|
|
export function genreList(db: Database) {
|
|
return db
|
|
.query<{ id: string; name: string; grp: string; sort: number; hidden: number; songs: number }, []>(
|
|
`SELECT g.*, (SELECT COUNT(*) FROM song_genres sg JOIN songs s ON s.id = sg.song_id WHERE sg.genre_id = g.id AND s.deleted_at IS NULL) songs
|
|
FROM genres g ORDER BY sort`,
|
|
)
|
|
.all()
|
|
.map((g) => ({ ...g, hidden: !!g.hidden }));
|
|
}
|