관리자 편집 보호: 자동 매칭은 관리자가 정한 영상을 덮어쓰지 않음(쓰기 시점 조건·실제 갱신만 집계), 다시 가져와도 관리자가 정한 장르(빈 선택 포함) 유지, 안 바꾼 유튜브 주소는 보내지 않음 + 후보 확정 버튼, 회귀 테스트 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);
|
||||
}
|
||||
|
||||
@@ -251,11 +251,14 @@ function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genr
|
||||
const [d, setD] = useState<Detail | null>(null);
|
||||
const [form, setForm] = useState({ title: '', artist: '', year: '', level: '', youtube: '', highlight: '', titleAliases: '', artistAliases: '', note: '', hidden: false, genres: [] as string[] });
|
||||
const [busy, setBusy] = useState(false);
|
||||
/** The address as loaded: `youtube` is only sent when the admin changed it (review 2026-10-18). */
|
||||
const [loadedYoutube, setLoadedYoutube] = useState('');
|
||||
const load = useCallback(() => {
|
||||
apiCall<Detail>('GET', `/api/admin/songs/${id}`)
|
||||
.then((x) => {
|
||||
setD(x);
|
||||
const lv = x.levels.find((l) => l.scope === 'all');
|
||||
setLoadedYoutube(x.song.youtube_id ? `https://youtu.be/${x.song.youtube_id}` : '');
|
||||
setForm({
|
||||
title: x.song.title,
|
||||
artist: x.song.artist,
|
||||
@@ -279,14 +282,13 @@ function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genr
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
const curYt = d.song.youtube_id ? `https://youtu.be/${d.song.youtube_id}` : '';
|
||||
await apiCall('PATCH', `/api/admin/songs/${id}`, {
|
||||
title: form.title,
|
||||
artist: form.artist,
|
||||
year: form.year ? Number(form.year) : null,
|
||||
level: form.level ? Number(form.level) : null,
|
||||
genres: form.genres,
|
||||
...(form.youtube.trim() !== curYt || d.song.youtube_status !== 'matched' ? { youtube: form.youtube.trim() || null } : {}),
|
||||
...(form.youtube.trim() !== loadedYoutube ? { youtube: form.youtube.trim() || null } : {}),
|
||||
highlightSec: form.highlight ? Number(form.highlight) : null,
|
||||
titleAliases: split(form.titleAliases),
|
||||
artistAliases: split(form.artistAliases),
|
||||
@@ -381,6 +383,28 @@ function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genr
|
||||
<span className={`badge ${YT_LABEL[d.song.youtube_status][1]}`}>{YT_LABEL[d.song.youtube_status][0]}</span>{' '}
|
||||
{d.song.youtube_channel && <span className="muted">{d.song.youtube_channel} · {d.song.youtube_title}</span>}
|
||||
</p>
|
||||
{d.song.youtube_status === 'candidate' && d.song.youtube_id && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await apiCall('PATCH', `/api/admin/songs/${id}`, { youtube: `https://youtu.be/${d.song.youtube_id}` });
|
||||
toast('이 영상으로 확정했어요.');
|
||||
load();
|
||||
onSaved();
|
||||
} catch (ex) {
|
||||
toast((ex as Error).message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
지금 후보 영상으로 확정
|
||||
</button>
|
||||
)}
|
||||
{videoId && (
|
||||
<div className="yt-preview">
|
||||
<iframe
|
||||
|
||||
@@ -162,6 +162,18 @@ try {
|
||||
await p.getByText('저장했어요.').first().waitFor();
|
||||
await p.locator('.data-table').getByText('확정').waitFor();
|
||||
expect(app.db.query<{ youtube_id: string }, []>("SELECT youtube_id FROM songs WHERE melon_id = 1").get()!.youtube_id === 'VO88htcm09E', '유튜브 저장 안 됨');
|
||||
// 회귀(리뷰 2026-10-18): 영상 없는 곡에 메모만 저장해도 자동 검색 대상에서 빠지지 않는다
|
||||
await p.getByLabel('노래 검색').fill('Love wins');
|
||||
await p.getByRole('button', { name: '검색' }).click();
|
||||
await p.getByRole('button', { name: 'Love wins all' }).click();
|
||||
await p.getByLabel('메모').fill('메모만 저장');
|
||||
const patchReq = p.waitForRequest((r) => r.method() === 'PATCH' && r.url().includes('/api/admin/songs/'));
|
||||
await p.getByRole('button', { name: '저장' }).click();
|
||||
const sent = JSON.parse((await patchReq).postData() ?? '{}');
|
||||
expect(!('youtube' in sent), `바꾸지 않은 유튜브 주소를 보냄: ${JSON.stringify(sent)}`);
|
||||
await p.getByText('저장했어요.').first().waitFor();
|
||||
const lw = app.db.query<{ note: string; youtube_source: string | null }, []>('SELECT note, youtube_source FROM songs WHERE melon_id = 2').get()!;
|
||||
expect(lw.note === '메모만 저장' && lw.youtube_source === null, `메모 저장 후 youtube_source=${lw.youtube_source}`);
|
||||
await side.getByRole('link', { name: /대시보드/ }).click();
|
||||
await p.getByRole('heading', { name: '대시보드' }).waitFor();
|
||||
await p.screenshot({ path: join(SHOTS, 'stage1-admin.png') });
|
||||
|
||||
Reference in New Issue
Block a user