- 서버 테스트 49개, 브라우저 e2e(e2e/rooms.e2e.ts, 3명) 11단계 - 사용자 결정(추천안)은 docs/12 "4단계 확인" Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
94 lines
4.6 KiB
TypeScript
94 lines
4.6 KiB
TypeScript
/**
|
|
* Which songs a room's settings select (docs/04, docs/12 Q7·Q9).
|
|
* - 장르: same group "또는", different groups "그리고"; empty = 전체
|
|
* - 난이도 N: a song qualifies when any applicable scope has level N: 'all', each chosen genre, each decade the year range touches
|
|
* - 재생 가능: listening modes need a confirmed (matched, embeddable) YouTube video; the lyrics mode needs lyrics
|
|
*/
|
|
import type { Database } from 'bun:sqlite';
|
|
import type { RoomConfig } from '@mq/shared';
|
|
|
|
type Args = (string | number)[];
|
|
|
|
function where(db: Database, c: RoomConfig): { sql: string; args: Args } {
|
|
const w: string[] = ['s.deleted_at IS NULL', 's.hidden = 0'];
|
|
const args: Args = [];
|
|
if (c.genres.length) {
|
|
const groups = new Map<string, string[]>();
|
|
const known = db.query<{ id: string; grp: string }, []>('SELECT id, grp FROM genres').all();
|
|
for (const g of c.genres) {
|
|
const grp = known.find((k) => k.id === g)?.grp;
|
|
if (!grp) continue;
|
|
groups.set(grp, [...(groups.get(grp) ?? []), g]);
|
|
}
|
|
for (const ids of groups.values()) {
|
|
w.push(`EXISTS (SELECT 1 FROM song_genres g WHERE g.song_id = s.id AND g.genre_id IN (${ids.map(() => '?').join(',')}))`);
|
|
args.push(...ids);
|
|
}
|
|
}
|
|
if (c.yearFrom) (w.push('s.year >= ?'), args.push(c.yearFrom));
|
|
if (c.yearTo) (w.push('s.year <= ?'), args.push(c.yearTo));
|
|
const scopes = ['all', ...c.genres.map((g) => `genre:${g}`)];
|
|
if (c.yearFrom || c.yearTo) {
|
|
const from = Math.floor((c.yearFrom ?? 1950) / 10) * 10;
|
|
const to = Math.floor((c.yearTo ?? new Date().getFullYear()) / 10) * 10;
|
|
for (let d = from; d <= to; d += 10) scopes.push(`decade:${d}`);
|
|
}
|
|
w.push(`EXISTS (SELECT 1 FROM song_levels l WHERE l.song_id = s.id AND l.level = ? AND l.scope IN (${scopes.map(() => '?').join(',')}))`);
|
|
args.push(c.level, ...scopes);
|
|
if (c.mode === 'artist') {
|
|
if (!c.artistIds.length) w.push('0');
|
|
else {
|
|
w.push(`EXISTS (SELECT 1 FROM song_artists a WHERE a.song_id = s.id AND a.artist_id IN (${c.artistIds.map(() => '?').join(',')}))`);
|
|
args.push(...c.artistIds);
|
|
}
|
|
}
|
|
return { sql: w.join(' AND '), args };
|
|
}
|
|
|
|
function playable(c: RoomConfig): string {
|
|
return c.mode === 'lyrics' ? 'EXISTS (SELECT 1 FROM lyrics y WHERE y.song_id = s.id)' : "s.youtube_status = 'matched' AND s.embeddable = 1";
|
|
}
|
|
|
|
/** playable = songs a game can use now; total = also those still waiting for a YouTube match (lyrics mode: same). */
|
|
export function countPool(db: Database, c: RoomConfig): { playable: number; total: number } {
|
|
const { sql, args } = where(db, c);
|
|
const r = db
|
|
.query<{ total: number; playable: number | null }, Args>(`SELECT COUNT(*) total, SUM(${playable(c)}) playable FROM songs s WHERE ${sql}`)
|
|
.get(...args)!;
|
|
return { total: r.total, playable: r.playable ?? 0 };
|
|
}
|
|
|
|
/** Playable song ids for a game (stage 5 shuffles and picks from these), excluding already played ones. */
|
|
export function poolIds(db: Database, c: RoomConfig, exclude: number[] = []): number[] {
|
|
const { sql, args } = where(db, c);
|
|
const ex = exclude.length ? ` AND s.id NOT IN (${exclude.map(() => '?').join(',')})` : '';
|
|
return db
|
|
.query<{ id: number }, Args>(`SELECT s.id FROM songs s WHERE ${sql} AND ${playable(c)}${ex}`)
|
|
.all(...args, ...exclude)
|
|
.map((r) => r.id);
|
|
}
|
|
|
|
/** Year span of the catalog, for the 연도 slider. */
|
|
export function yearBounds(db: Database): { min: number; max: number } {
|
|
const r = db.query<{ min: number | null; max: number | null }, []>('SELECT MIN(year) min, MAX(year) max FROM songs WHERE deleted_at IS NULL AND year IS NOT NULL').get()!;
|
|
return { min: r.min ?? 1980, max: Math.max(r.max ?? 0, new Date().getFullYear()) };
|
|
}
|
|
|
|
/** 가수 선택 search (docs/04 가수노래): name or alias, with song counts. */
|
|
export function searchArtists(db: Database, q: string, limit = 20) {
|
|
const like = `%${q.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
|
|
return db
|
|
.query<{ id: number; name: string; songs: number }, [string, string, number]>(
|
|
`SELECT a.id, a.name, COUNT(DISTINCT sa.song_id) songs FROM artists a
|
|
JOIN song_artists sa ON sa.artist_id = a.id JOIN songs s ON s.id = sa.song_id AND s.deleted_at IS NULL
|
|
WHERE a.name LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM artist_aliases x WHERE x.artist_id = a.id AND x.alias LIKE ? ESCAPE '\\')
|
|
GROUP BY a.id ORDER BY songs DESC, a.name LIMIT ?`,
|
|
)
|
|
.all(like, like, limit);
|
|
}
|
|
|
|
export function artistsByIds(db: Database, ids: number[]) {
|
|
if (!ids.length) return [];
|
|
return db.query<{ id: number; name: string }, number[]>(`SELECT id, name FROM artists WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids);
|
|
}
|