관리자 편집 보호: 자동 매칭은 관리자가 정한 영상을 덮어쓰지 않음(쓰기 시점 조건·실제 갱신만 집계), 다시 가져와도 관리자가 정한 장르(빈 선택 포함) 유지, 안 바꾼 유튜브 주소는 보내지 않음 + 후보 확정 버튼, 회귀 테스트 3개·e2e
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
60
apps/server/src/collector/admin-guard.test.ts
Normal file
60
apps/server/src/collector/admin-guard.test.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
/** Regressions: automatic collectors must never undo an admin's edits (review 2026-10-18). */
|
||||
import { afterEach, expect, test } from 'bun:test';
|
||||
import { openDb } from '../db';
|
||||
import { Catalog } from './catalog';
|
||||
import { matchYoutube } from './match-youtube';
|
||||
import { updateSong } from '../songs/store';
|
||||
import { TEST_SUPERADMINS, api, boot, discordLogin, tempDbPath } from '../test-utils';
|
||||
|
||||
test('an admin URL saved while the matcher is searching is not overwritten', async () => {
|
||||
const db = openDb(tempDbPath());
|
||||
const [id] = new Catalog(db).upsert({ title: 'Love wins all', artists: [{ name: '아이유' }], durationSec: 272, source: 't', ref: '1' });
|
||||
const stats = await matchYoutube(
|
||||
db,
|
||||
{
|
||||
searchSongs: async () => {
|
||||
// the admin saves a video while the search is in flight
|
||||
updateSong(db, id, { youtubeId: 'ADMINvideo1' }, { author: 'IU - Topic', title: 'Love wins all' });
|
||||
return [{ videoId: 'Wu5FY8J6P8Q', title: 'Love wins all', artists: '아이유', album: null, durationSec: 272 }];
|
||||
},
|
||||
},
|
||||
{ delayMs: 0 },
|
||||
async () => ({ state: 'ok', author: 'auto', title: 'auto' }),
|
||||
);
|
||||
const row = db.query<{ youtube_id: string; youtube_source: string }, [number]>('SELECT youtube_id, youtube_source FROM songs WHERE id = ?').get(id)!;
|
||||
expect(row).toEqual({ youtube_id: 'ADMINvideo1', youtube_source: 'admin' });
|
||||
expect(stats.matched).toBe(0);
|
||||
});
|
||||
|
||||
test('re-import does not bring back genres the admin removed (also an empty choice)', () => {
|
||||
const db = openDb(tempDbPath());
|
||||
const c = new Catalog(db);
|
||||
const song = { melonId: 5, title: '광', artists: [{ name: 'SG워너비' }], genres: ['ballad', 'kpop'], source: 'norabose', ref: '5' };
|
||||
const [a] = c.upsert(song);
|
||||
updateSong(db, a, { genres: ['rock'] });
|
||||
c.upsert(song);
|
||||
const genres = (id: number) => db.query<{ genre_id: string }, [number]>('SELECT genre_id FROM song_genres WHERE song_id = ? ORDER BY genre_id').all(id).map((r) => r.genre_id);
|
||||
expect(genres(a)).toEqual(['rock']);
|
||||
updateSong(db, a, { genres: [] });
|
||||
c.upsert(song);
|
||||
expect(genres(a)).toEqual([]);
|
||||
});
|
||||
|
||||
let s: ReturnType<typeof boot> | null = null;
|
||||
afterEach(async () => {
|
||||
await s?.stop();
|
||||
s = null;
|
||||
});
|
||||
|
||||
test('saving only a note on a song without video keeps it in the automatic search', async () => {
|
||||
s = boot({ discordExchange: async (code) => ({ id: code, username: 'u', global_name: '관리', avatar: null }) }, { DISCORD_CLIENT_ID: 'c', DISCORD_CLIENT_SECRET: 's' });
|
||||
const [id] = new Catalog(s.db).upsert({ title: '없는영상', artists: [{ name: '누구' }], source: 't', ref: '1' });
|
||||
const sa = await discordLogin(s.base, TEST_SUPERADMINS[0]);
|
||||
// what the editor used to send for a song with no video: youtube: null alongside the note
|
||||
const r = await api(s.base, `/api/admin/songs/${id}`, { method: 'PATCH', cookie: sa.cookie, body: JSON.stringify({ note: '메모', youtube: null }) });
|
||||
expect(r.res.status).toBe(200);
|
||||
expect(r.body.song.youtube_source).toBeNull();
|
||||
let searches = 0;
|
||||
await matchYoutube(s.db, { searchSongs: async () => (searches++, []) }, { delayMs: 0 });
|
||||
expect(searches).toBe(1);
|
||||
});
|
||||
@@ -62,7 +62,9 @@ export class Catalog {
|
||||
this.db.query('INSERT OR IGNORE INTO song_artists (song_id, artist_id, role) VALUES (?, ?, ?)').run(id, this.artistId(a.name, a.melonArtistId), 'main');
|
||||
});
|
||||
}
|
||||
for (const g of s.genres ?? []) this.db.query('INSERT OR IGNORE INTO song_genres (song_id, genre_id, source) VALUES (?, ?, ?)').run(id, g, s.source);
|
||||
// Genres an admin has set (even to none) are final: imports only add genres to songs nobody edited.
|
||||
const adminGenres = this.db.query<{ g: string | null }, [number]>('SELECT genres_source g FROM songs WHERE id = ?').get(id)?.g === 'admin';
|
||||
if (!adminGenres) for (const g of s.genres ?? []) this.db.query('INSERT OR IGNORE INTO song_genres (song_id, genre_id, source) VALUES (?, ?, ?)').run(id, g, s.source);
|
||||
if (s.lyrics) this.db.query('INSERT OR IGNORE INTO lyrics (song_id, text, source, fetched_at) VALUES (?, ?, ?, ?)').run(id, s.lyrics, s.source, now);
|
||||
this.db.query('INSERT OR IGNORE INTO song_sources (song_id, source, ref) VALUES (?, ?, ?)').run(id, s.source, s.ref);
|
||||
return [id, created];
|
||||
|
||||
@@ -41,13 +41,20 @@ export async function matchYoutube(db: Database, ytm: Pick<YtMusic, 'searchSongs
|
||||
const job = new Job(db, 'match-youtube', rows.length);
|
||||
const stats = { matched: 0, candidate: 0, none: 0 };
|
||||
const src = opts.source ?? 'ytmusic';
|
||||
/**
|
||||
* 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 = ?`,
|
||||
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);
|
||||
.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()) {
|
||||
let results: YtmSong[];
|
||||
@@ -72,13 +79,15 @@ export async function matchYoutube(db: Database, ytm: Pick<YtMusic, 'searchSongs
|
||||
for (const c of scored.filter(isConfident)) {
|
||||
const e = await embed(c.videoId);
|
||||
if (e.state === 'ok') {
|
||||
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++;
|
||||
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 }[] = [
|
||||
@@ -88,8 +97,7 @@ export async function matchYoutube(db: Database, ytm: Pick<YtMusic, 'searchSongs
|
||||
for (const f of fallbacks) {
|
||||
const e = await embed(f.videoId);
|
||||
if (e.state === 'ok') {
|
||||
setVideo(s.id, 'candidate', { videoId: f.videoId, author: e.author, title: e.title }, f.source);
|
||||
stats.candidate++;
|
||||
if (setVideo(s.id, 'candidate', { videoId: f.videoId, author: e.author, title: e.title }, f.source)) stats.candidate++;
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
|
||||
2
apps/server/src/db/migrations/003_genres_source.sql
Normal file
2
apps/server/src/db/migrations/003_genres_source.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- 'admin' once an admin has set the genres (even to none): imports then leave the song's genres alone.
|
||||
ALTER TABLE songs ADD COLUMN genres_source TEXT;
|
||||
@@ -149,13 +149,15 @@ export function updateSong(db: Database, id: number, p: SongPatch, embed?: { aut
|
||||
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);
|
||||
// Clearing a video that isn't there is no change: it must not take the song out of the automatic search.
|
||||
if (p.youtubeId === null) db.query("UPDATE songs SET youtube_id = NULL, youtube_status = 'none', youtube_source = 'admin' WHERE id = ? AND youtube_id IS NOT NULL").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("UPDATE songs SET genres_source = 'admin' WHERE id = ?").run(id);
|
||||
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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user