mirror of
https://github.com/rommapp/romm.git
synced 2026-12-04 21:02:21 +01:00
refactor(soundtrack): give each song its own track id
Favorites and playlist entries pointed at (rom_file_id, song), a position the database couldn't enforce, so rescans had to move them by hand. Now every track_meta row has its own id, and favorites and playlist entries reference it with a cascading foreign key. - track_meta: `id` primary key, unique (rom_file_id, song) - music_favorite_tracks: (user_id, track_id); music_playlist_tracks: unique (playlist_id, track_id); both drop rom_file_id and song - a rescan matches songs to their rows by tags, then position, and only renumbers the rows, so saved songs follow without extra bookkeeping - the API takes `track_ids`, still accepting `rom_file_ids` for 5.3.1 clients; tracks carry `id` - the frontend keys favorites and queue entries by track id - migration 0145 moves existing favorites and playlist entries onto their file's first song, and back again on downgrade Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01A33pL6e6MvvBwhpcbXX9pH
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
"""key soundtrack tracks by song, so a file can hold several
|
||||
"""give each soundtrack song its own track row, so a file can hold several
|
||||
|
||||
Revision ID: 0145_track_meta_songs
|
||||
Revises: 0144_user_oidc_sub
|
||||
@@ -17,78 +17,178 @@ down_revision = "0144_user_oidc_sub"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_SONG_TABLES = ("track_meta", "music_favorite_tracks", "music_playlist_tracks")
|
||||
_FILE_SONG_UNIQUE = "uq_track_meta_file_song"
|
||||
_M3U_FK = "fk_track_meta_m3u_file"
|
||||
_M3U_INDEX = "ix_track_meta_m3u_file_id"
|
||||
_PLAYLIST_UNIQUE = "unique_music_playlist_track"
|
||||
|
||||
# The tables that point at a track, each with the other column in its key.
|
||||
_REFERENCES = {
|
||||
"music_favorite_tracks": "user_id",
|
||||
"music_playlist_tracks": "playlist_id",
|
||||
}
|
||||
|
||||
def _song_column() -> sa.Column[int]:
|
||||
return sa.Column(
|
||||
"song", sa.SmallInteger(), nullable=False, server_default=sa.text("0")
|
||||
|
||||
def _pk_columns(conn: sa.Connection, table: str) -> tuple[str, ...]:
|
||||
return tuple(sa.inspect(conn).get_pk_constraint(table)["constrained_columns"])
|
||||
|
||||
|
||||
def _fk_name(conn: sa.Connection, table: str, column: str) -> str | None:
|
||||
for key in sa.inspect(conn).get_foreign_keys(table):
|
||||
if key["constrained_columns"] == [column]:
|
||||
return key["name"]
|
||||
return None
|
||||
|
||||
|
||||
def _is_nullable(conn: sa.Connection, table: str, column: str) -> bool:
|
||||
return any(
|
||||
c["name"] == column and c["nullable"]
|
||||
for c in sa.inspect(conn).get_columns(table)
|
||||
)
|
||||
|
||||
|
||||
def _replace_primary_key(table: str, columns: tuple[str, ...]) -> None:
|
||||
def _unique_columns(conn: sa.Connection, table: str, name: str) -> tuple[str, ...]:
|
||||
inspector = sa.inspect(conn)
|
||||
for constraint in inspector.get_unique_constraints(table):
|
||||
if constraint["name"] == name:
|
||||
return tuple(constraint["column_names"])
|
||||
# MariaDB and MySQL report a unique constraint as a unique index.
|
||||
for index in inspector.get_indexes(table):
|
||||
if index["name"] == name:
|
||||
return tuple(str(column) for column in index["column_names"])
|
||||
return ()
|
||||
|
||||
|
||||
def _replace_key(table: str, columns: tuple[str, ...]) -> None:
|
||||
"""Swap a favorites primary key, or a playlist's unique key."""
|
||||
conn = op.get_bind()
|
||||
current = sa.inspect(conn).get_pk_constraint(table)
|
||||
if tuple(current["constrained_columns"]) == columns:
|
||||
return
|
||||
listed = ", ".join(columns)
|
||||
# One statement, since MariaDB refuses to drop a key a foreign key relies on.
|
||||
if is_postgresql(conn):
|
||||
if table == "music_playlist_tracks":
|
||||
if _unique_columns(conn, table, _PLAYLIST_UNIQUE) == columns:
|
||||
return
|
||||
drop = "DROP CONSTRAINT" if is_postgresql(conn) else "DROP INDEX"
|
||||
op.execute(
|
||||
f"ALTER TABLE {table} DROP CONSTRAINT {current['name']}, "
|
||||
f"ADD PRIMARY KEY ({listed})"
|
||||
f"ALTER TABLE {table} {drop} {_PLAYLIST_UNIQUE}, "
|
||||
f"ADD CONSTRAINT {_PLAYLIST_UNIQUE} UNIQUE ({listed})"
|
||||
)
|
||||
return
|
||||
if _pk_columns(conn, table) == columns:
|
||||
return
|
||||
if is_postgresql(conn):
|
||||
name = sa.inspect(conn).get_pk_constraint(table)["name"]
|
||||
op.execute(
|
||||
f"ALTER TABLE {table} DROP CONSTRAINT {name}, ADD PRIMARY KEY ({listed})"
|
||||
)
|
||||
else:
|
||||
op.execute(f"ALTER TABLE {table} DROP PRIMARY KEY, ADD PRIMARY KEY ({listed})")
|
||||
|
||||
|
||||
def _playlist_unique_columns(conn: sa.Connection) -> tuple[str, ...] | None:
|
||||
inspector = sa.inspect(conn)
|
||||
for constraint in inspector.get_unique_constraints("music_playlist_tracks"):
|
||||
if constraint["name"] == _PLAYLIST_UNIQUE:
|
||||
return tuple(constraint["column_names"])
|
||||
# MariaDB and MySQL report a unique constraint as a unique index.
|
||||
for index in inspector.get_indexes("music_playlist_tracks"):
|
||||
if index["name"] == _PLAYLIST_UNIQUE:
|
||||
return tuple(str(column) for column in index["column_names"])
|
||||
return None
|
||||
|
||||
|
||||
def _replace_playlist_unique(columns: tuple[str, ...]) -> None:
|
||||
conn = op.get_bind()
|
||||
current = _playlist_unique_columns(conn)
|
||||
if current == columns:
|
||||
return
|
||||
add = f"ADD CONSTRAINT {_PLAYLIST_UNIQUE} UNIQUE ({', '.join(columns)})"
|
||||
if current is None:
|
||||
op.execute(f"ALTER TABLE music_playlist_tracks {add}")
|
||||
return
|
||||
drop = "DROP CONSTRAINT" if is_postgresql(conn) else "DROP INDEX"
|
||||
op.execute(f"ALTER TABLE music_playlist_tracks {drop} {_PLAYLIST_UNIQUE}, {add}")
|
||||
|
||||
|
||||
def _has_m3u_foreign_key(conn: sa.Connection) -> bool:
|
||||
return any(
|
||||
key["name"] == _M3U_FK
|
||||
for key in sa.inspect(conn).get_foreign_keys("track_meta")
|
||||
def _backfill(table: str, target: str, source: str) -> None:
|
||||
"""Fill `target` through each row's first song, dropping rows that have none."""
|
||||
ref = sa.table(table, sa.column(target), sa.column(source))
|
||||
track = sa.table(
|
||||
"track_meta", sa.column("id"), sa.column("rom_file_id"), sa.column("song")
|
||||
)
|
||||
by_name = {"track_id": track.c.id, "rom_file_id": track.c.rom_file_id}
|
||||
op.execute(
|
||||
ref.update()
|
||||
.where(ref.c[target].is_(None))
|
||||
.values(
|
||||
{
|
||||
target: sa.select(by_name[target])
|
||||
.where(by_name[source] == ref.c[source], track.c.song == 0)
|
||||
.scalar_subquery()
|
||||
}
|
||||
)
|
||||
)
|
||||
op.execute(ref.delete().where(ref.c[target].is_(None)))
|
||||
|
||||
|
||||
def _repoint(table: str, lead: str, old: str, new: str) -> None:
|
||||
"""Move a reference table's key from its `old` column to `new`."""
|
||||
conn = op.get_bind()
|
||||
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(new, sa.Integer(), nullable=True), if_not_exists=True
|
||||
)
|
||||
if has_column(conn, table, old):
|
||||
_backfill(table, new, old)
|
||||
if _is_nullable(conn, table, new):
|
||||
op.alter_column(table, new, existing_type=sa.Integer(), nullable=False)
|
||||
|
||||
old_fk = _fk_name(conn, table, old)
|
||||
if old_fk:
|
||||
op.drop_constraint(old_fk, table, type_="foreignkey")
|
||||
_replace_key(table, (lead, new))
|
||||
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||
if old == "track_id":
|
||||
batch_op.drop_index(f"ix_{table}_track_id", if_exists=True)
|
||||
batch_op.drop_column(old, if_exists=True)
|
||||
|
||||
if new == "track_id":
|
||||
op.create_index(f"ix_{table}_track_id", table, ["track_id"], if_not_exists=True)
|
||||
target, name = "track_meta", f"fk_{table}_track"
|
||||
else:
|
||||
# 0124 indexed these foreign keys on PostgreSQL only.
|
||||
if is_postgresql(conn):
|
||||
op.create_index(
|
||||
f"ix_{table}_rom_file_id", table, ["rom_file_id"], if_not_exists=True
|
||||
)
|
||||
target, name = "rom_files", f"fk_{table}_rom_file"
|
||||
if not _fk_name(conn, table, new):
|
||||
op.create_foreign_key(name, table, target, [new], ["id"], ondelete="CASCADE")
|
||||
|
||||
|
||||
def _give_tracks_ids() -> None:
|
||||
conn = op.get_bind()
|
||||
if has_column(conn, "track_meta", "id"):
|
||||
return
|
||||
unique = f"ADD CONSTRAINT {_FILE_SONG_UNIQUE} UNIQUE (rom_file_id, song)"
|
||||
if is_postgresql(conn):
|
||||
name = sa.inspect(conn).get_pk_constraint("track_meta")["name"]
|
||||
op.execute(
|
||||
f"ALTER TABLE track_meta DROP CONSTRAINT {name}, "
|
||||
f"ADD COLUMN id SERIAL PRIMARY KEY, {unique}"
|
||||
)
|
||||
else:
|
||||
op.execute(
|
||||
"ALTER TABLE track_meta DROP PRIMARY KEY, "
|
||||
f"ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, {unique}"
|
||||
)
|
||||
|
||||
|
||||
def _drop_track_ids() -> None:
|
||||
conn = op.get_bind()
|
||||
if not has_column(conn, "track_meta", "id"):
|
||||
return
|
||||
if is_postgresql(conn):
|
||||
name = sa.inspect(conn).get_pk_constraint("track_meta")["name"]
|
||||
op.execute(
|
||||
f"ALTER TABLE track_meta DROP CONSTRAINT {_FILE_SONG_UNIQUE}, "
|
||||
f"DROP CONSTRAINT {name}, DROP COLUMN id, ADD PRIMARY KEY (rom_file_id)"
|
||||
)
|
||||
else:
|
||||
op.execute(
|
||||
f"ALTER TABLE track_meta DROP INDEX {_FILE_SONG_UNIQUE}, "
|
||||
"DROP PRIMARY KEY, DROP COLUMN id, ADD PRIMARY KEY (rom_file_id)"
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
for table in _SONG_TABLES:
|
||||
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||
batch_op.add_column(_song_column(), if_not_exists=True)
|
||||
|
||||
with op.batch_alter_table("track_meta", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"song", sa.SmallInteger(), nullable=False, server_default=sa.text("0")
|
||||
),
|
||||
if_not_exists=True,
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column("m3u_file_id", sa.Integer(), nullable=True), if_not_exists=True
|
||||
)
|
||||
batch_op.create_index(_M3U_INDEX, ["m3u_file_id"], if_not_exists=True)
|
||||
if not _has_m3u_foreign_key(conn):
|
||||
if not _fk_name(conn, "track_meta", "m3u_file_id"):
|
||||
op.create_foreign_key(
|
||||
_M3U_FK,
|
||||
"track_meta",
|
||||
@@ -97,30 +197,26 @@ def upgrade() -> None:
|
||||
["id"],
|
||||
ondelete="SET NULL",
|
||||
)
|
||||
_give_tracks_ids()
|
||||
|
||||
_replace_primary_key("track_meta", ("rom_file_id", "song"))
|
||||
_replace_primary_key("music_favorite_tracks", ("user_id", "rom_file_id", "song"))
|
||||
_replace_playlist_unique(("playlist_id", "rom_file_id", "song"))
|
||||
for table, lead in _REFERENCES.items():
|
||||
_repoint(table, lead, old="rom_file_id", new="track_id")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
# Only a file's first song survives, as the old schema had one row per file.
|
||||
for table in _SONG_TABLES:
|
||||
if has_column(conn, table, "song"):
|
||||
song = sa.column("song", sa.SmallInteger())
|
||||
op.execute(sa.table(table, song).delete().where(song > 0))
|
||||
for table, lead in _REFERENCES.items():
|
||||
_repoint(table, lead, old="track_id", new="rom_file_id")
|
||||
if has_column(conn, "track_meta", "song"):
|
||||
song = sa.column("song", sa.SmallInteger())
|
||||
op.execute(sa.table("track_meta", song).delete().where(song > 0))
|
||||
_drop_track_ids()
|
||||
|
||||
_replace_playlist_unique(("playlist_id", "rom_file_id"))
|
||||
_replace_primary_key("music_favorite_tracks", ("user_id", "rom_file_id"))
|
||||
_replace_primary_key("track_meta", ("rom_file_id",))
|
||||
|
||||
if _has_m3u_foreign_key(conn):
|
||||
op.drop_constraint(_M3U_FK, "track_meta", type_="foreignkey")
|
||||
m3u_fk = _fk_name(conn, "track_meta", "m3u_file_id")
|
||||
if m3u_fk:
|
||||
op.drop_constraint(m3u_fk, "track_meta", type_="foreignkey")
|
||||
with op.batch_alter_table("track_meta", schema=None) as batch_op:
|
||||
batch_op.drop_index(_M3U_INDEX, if_exists=True)
|
||||
batch_op.drop_column("m3u_file_id", if_exists=True)
|
||||
|
||||
for table in _SONG_TABLES:
|
||||
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||
batch_op.drop_column("song", if_exists=True)
|
||||
batch_op.drop_column("song", if_exists=True)
|
||||
|
||||
@@ -16,7 +16,6 @@ from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.auth.permissions import ResolvedPermissions
|
||||
from handler.database import db_music_playlist_handler, db_rom_handler
|
||||
from models.music import TrackKey
|
||||
from utils.router import APIRouter, as_query_dependency
|
||||
|
||||
router = APIRouter(prefix="/music", tags=["music"])
|
||||
@@ -35,64 +34,64 @@ class MusicPage[T: BaseModel](LimitOffsetPage[T]):
|
||||
pass
|
||||
|
||||
|
||||
class MusicTrackRef(BaseModel):
|
||||
rom_file_id: int = Field(ge=1)
|
||||
song: int = Field(0, ge=0, description="Song within the file; 0 for most audio.")
|
||||
|
||||
|
||||
class MusicTrackIdsPayload(BaseModel):
|
||||
tracks: list[MusicTrackRef] = Field(default_factory=list)
|
||||
track_ids: list[Annotated[int, Field(ge=1)]] = Field(default_factory=list)
|
||||
rom_file_ids: list[Annotated[int, Field(ge=1)]] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={"deprecated": True},
|
||||
description="The first song of each file. Use `tracks` instead.",
|
||||
description="The first song of each file. Use `track_ids` instead.",
|
||||
)
|
||||
|
||||
@property
|
||||
def refs(self) -> list[MusicTrackRef]:
|
||||
legacy = [MusicTrackRef(rom_file_id=i, song=0) for i in self.rom_file_ids]
|
||||
return self.tracks + legacy
|
||||
|
||||
def _not_found(ids: list[int]) -> HTTPException:
|
||||
# Hidden and missing tracks get the same message so existence is not leaked.
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Tracks not found: {sorted(set(ids))}",
|
||||
)
|
||||
|
||||
|
||||
def resolve_track_ids(
|
||||
refs: list[MusicTrackRef], perms: ResolvedPermissions
|
||||
) -> list[TrackKey]:
|
||||
"""Validate references as music tracks the requester may see.
|
||||
|
||||
Raises 400 when any reference does not point to a visible music track;
|
||||
hidden and missing files get the same message so existence is not leaked."""
|
||||
tracks = list(dict.fromkeys(TrackKey(ref.rom_file_id, ref.song) for ref in refs))
|
||||
def _first_songs(rom_file_ids: list[int], perms: ResolvedPermissions) -> list[int]:
|
||||
files = {
|
||||
f.id: f
|
||||
for f in db_rom_handler.get_rom_files_by_ids(
|
||||
list(dict.fromkeys(track.rom_file_id for track in tracks))
|
||||
)
|
||||
for f in db_rom_handler.get_rom_files_by_ids(list(dict.fromkeys(rom_file_ids)))
|
||||
}
|
||||
missing = [
|
||||
track.rom_file_id
|
||||
for track in tracks
|
||||
if track.rom_file_id not in files
|
||||
or not perms.can_see_rom(
|
||||
files[track.rom_file_id].rom_id, files[track.rom_file_id].rom.platform_id
|
||||
)
|
||||
fid
|
||||
for fid in rom_file_ids
|
||||
if fid not in files
|
||||
or not perms.can_see_rom(files[fid].rom_id, files[fid].rom.platform_id)
|
||||
]
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Tracks not found: {sorted(set(missing))}",
|
||||
)
|
||||
not_tracks = [
|
||||
track.rom_file_id
|
||||
for track in tracks
|
||||
if track.song
|
||||
not in {meta.song for meta in files[track.rom_file_id].track_metas}
|
||||
]
|
||||
raise _not_found(missing)
|
||||
firsts = {fid: files[fid].track_meta for fid in rom_file_ids}
|
||||
not_tracks = [fid for fid, track in firsts.items() if track is None]
|
||||
if not_tracks:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Files are not music tracks: {sorted(set(not_tracks))}",
|
||||
)
|
||||
return tracks
|
||||
return [track.id for track in firsts.values() if track is not None]
|
||||
|
||||
|
||||
def resolve_track_ids(
|
||||
payload: MusicTrackIdsPayload, perms: ResolvedPermissions
|
||||
) -> list[int]:
|
||||
"""The payload's tracks, in order, once each is shown to be visible.
|
||||
|
||||
Raises 400 when any id is not a track the requester may see."""
|
||||
track_ids = list(dict.fromkeys(payload.track_ids))
|
||||
owners = db_rom_handler.get_track_owners(track_ids)
|
||||
missing = [
|
||||
track_id
|
||||
for track_id in track_ids
|
||||
if track_id not in owners or not perms.can_see_rom(*owners[track_id])
|
||||
]
|
||||
if missing:
|
||||
raise _not_found(missing)
|
||||
if payload.rom_file_ids:
|
||||
track_ids += _first_songs(payload.rom_file_ids, perms)
|
||||
return list(dict.fromkeys(track_ids))
|
||||
|
||||
|
||||
@protected_route(router.get, "/tracks", [Scope.ROMS_READ])
|
||||
@@ -230,7 +229,7 @@ def add_music_favorites(
|
||||
) -> dict[str, Any]:
|
||||
"""Mark tracks as favorites; already-favorited tracks are ignored."""
|
||||
perms = get_permissions(request)
|
||||
tracks = resolve_track_ids(payload.refs, perms)
|
||||
tracks = resolve_track_ids(payload, perms)
|
||||
added = db_music_playlist_handler.add_favorite_tracks(request.user.id, tracks)
|
||||
return {"added": added}
|
||||
|
||||
@@ -241,7 +240,7 @@ def remove_music_favorites(
|
||||
) -> dict[str, Any]:
|
||||
"""Unmark tracks as favorites."""
|
||||
perms = get_permissions(request)
|
||||
tracks = resolve_track_ids(payload.refs, perms)
|
||||
tracks = resolve_track_ids(payload, perms)
|
||||
removed = db_music_playlist_handler.remove_favorite_tracks(request.user.id, tracks)
|
||||
return {"removed": removed}
|
||||
|
||||
|
||||
@@ -27,7 +27,6 @@ from models.music import (
|
||||
PLAYLIST_DESCRIPTION_MAX_LENGTH,
|
||||
PLAYLIST_NAME_MAX_LENGTH,
|
||||
MusicPlaylist,
|
||||
TrackKey,
|
||||
)
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -193,7 +192,7 @@ def add_playlist_tracks(
|
||||
"""Append tracks to the playlist; tracks already present are ignored."""
|
||||
playlist = _get_owned_playlist(request, id)
|
||||
perms = get_permissions(request)
|
||||
tracks = resolve_track_ids(payload.refs, perms)
|
||||
tracks = resolve_track_ids(payload, perms)
|
||||
added = db_music_playlist_handler.add_tracks_to_playlist(playlist.id, tracks)
|
||||
return {"added": added}
|
||||
|
||||
@@ -206,7 +205,7 @@ def remove_playlist_tracks(
|
||||
) -> dict[str, Any]:
|
||||
playlist = _get_owned_playlist(request, id)
|
||||
perms = get_permissions(request)
|
||||
tracks = resolve_track_ids(payload.refs, perms)
|
||||
tracks = resolve_track_ids(payload, perms)
|
||||
removed = db_music_playlist_handler.remove_tracks_from_playlist(playlist.id, tracks)
|
||||
return {"removed": removed}
|
||||
|
||||
@@ -223,9 +222,9 @@ def set_playlist_track_order(
|
||||
listed tracks."""
|
||||
playlist = _get_owned_playlist(request, id)
|
||||
perms = get_permissions(request)
|
||||
tracks = resolve_track_ids(payload.refs, perms)
|
||||
tracks = resolve_track_ids(payload, perms)
|
||||
entries = db_music_playlist_handler.get_playlist_entries(playlist.id)
|
||||
entry_by_track = {TrackKey(e.rom_file_id, e.song): e.id for e in entries}
|
||||
entry_by_track = {e.track_id: e.id for e in entries}
|
||||
if any(track not in entry_by_track for track in tracks):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
|
||||
@@ -17,6 +17,7 @@ def _content_url(rom_file_id: int, file_name: str) -> str:
|
||||
class MusicTrackSchema(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
rom_file_id: int
|
||||
song: int = 0
|
||||
rom_id: int
|
||||
@@ -53,6 +54,7 @@ class MusicTrackSchema(BaseModel):
|
||||
@classmethod
|
||||
def from_row(cls, row: Any) -> MusicTrackSchema:
|
||||
return cls(
|
||||
id=row.id,
|
||||
rom_file_id=row.rom_file_id,
|
||||
song=row.song,
|
||||
rom_id=row.rom_id,
|
||||
|
||||
@@ -216,6 +216,7 @@ class RomUserSchema(BaseModel):
|
||||
class TrackMetaSchema(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
song: int = 0
|
||||
m3u_file_id: int | None = None
|
||||
title: str | None = None
|
||||
|
||||
@@ -2,17 +2,12 @@ from collections.abc import Sequence
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, func, insert, or_, select, tuple_, update
|
||||
from sqlalchemy import delete, func, insert, or_, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from decorators.database import INJECTED_SESSION, begin_session
|
||||
from models.music import (
|
||||
MusicFavoriteTrack,
|
||||
MusicPlaylist,
|
||||
MusicPlaylistTrack,
|
||||
TrackKey,
|
||||
)
|
||||
from models.music import MusicFavoriteTrack, MusicPlaylist, MusicPlaylistTrack
|
||||
|
||||
from .base_handler import DBBaseHandler, affected_rows
|
||||
|
||||
@@ -132,22 +127,20 @@ class DBMusicPlaylistsHandler(DBBaseHandler):
|
||||
def add_tracks_to_playlist(
|
||||
self,
|
||||
playlist_id: int,
|
||||
tracks: Sequence[TrackKey],
|
||||
track_ids: Sequence[int],
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> int:
|
||||
candidates = list(dict.fromkeys(tracks))
|
||||
candidates = list(dict.fromkeys(track_ids))
|
||||
if not candidates:
|
||||
return 0
|
||||
playlist_key = tuple_(MusicPlaylistTrack.rom_file_id, MusicPlaylistTrack.song)
|
||||
existing = {
|
||||
TrackKey(*row)
|
||||
for row in session.execute(
|
||||
select(MusicPlaylistTrack.rom_file_id, MusicPlaylistTrack.song).where(
|
||||
existing = set(
|
||||
session.scalars(
|
||||
select(MusicPlaylistTrack.track_id).where(
|
||||
MusicPlaylistTrack.playlist_id == playlist_id,
|
||||
playlist_key.in_(candidates),
|
||||
MusicPlaylistTrack.track_id.in_(candidates),
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
new_entries = [e for e in candidates if e not in existing]
|
||||
if not new_entries:
|
||||
return 0
|
||||
@@ -161,14 +154,13 @@ class DBMusicPlaylistsHandler(DBBaseHandler):
|
||||
or 0
|
||||
) + 1
|
||||
added = 0
|
||||
for track in new_entries:
|
||||
for track_id in new_entries:
|
||||
try:
|
||||
with session.begin_nested():
|
||||
session.execute(
|
||||
insert(MusicPlaylistTrack).values(
|
||||
playlist_id=playlist_id,
|
||||
rom_file_id=track.rom_file_id,
|
||||
song=track.song,
|
||||
track_id=track_id,
|
||||
position=next_position + added,
|
||||
)
|
||||
)
|
||||
@@ -183,17 +175,15 @@ class DBMusicPlaylistsHandler(DBBaseHandler):
|
||||
def remove_tracks_from_playlist(
|
||||
self,
|
||||
playlist_id: int,
|
||||
tracks: Sequence[TrackKey],
|
||||
track_ids: Sequence[int],
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> int:
|
||||
if not tracks:
|
||||
if not track_ids:
|
||||
return 0
|
||||
result = session.execute(
|
||||
delete(MusicPlaylistTrack).where(
|
||||
MusicPlaylistTrack.playlist_id == playlist_id,
|
||||
tuple_(MusicPlaylistTrack.rom_file_id, MusicPlaylistTrack.song).in_(
|
||||
list(tracks)
|
||||
),
|
||||
MusicPlaylistTrack.track_id.in_(list(track_ids)),
|
||||
)
|
||||
)
|
||||
if affected_rows(result) > 0:
|
||||
@@ -227,34 +217,30 @@ class DBMusicPlaylistsHandler(DBBaseHandler):
|
||||
def add_favorite_tracks(
|
||||
self,
|
||||
user_id: int,
|
||||
tracks: Sequence[TrackKey],
|
||||
track_ids: Sequence[int],
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> int:
|
||||
candidates = list(dict.fromkeys(tracks))
|
||||
candidates = list(dict.fromkeys(track_ids))
|
||||
if not candidates:
|
||||
return 0
|
||||
favorite_key = tuple_(MusicFavoriteTrack.rom_file_id, MusicFavoriteTrack.song)
|
||||
existing = {
|
||||
TrackKey(*row)
|
||||
for row in session.execute(
|
||||
select(MusicFavoriteTrack.rom_file_id, MusicFavoriteTrack.song).where(
|
||||
existing = set(
|
||||
session.scalars(
|
||||
select(MusicFavoriteTrack.track_id).where(
|
||||
MusicFavoriteTrack.user_id == user_id,
|
||||
favorite_key.in_(candidates),
|
||||
MusicFavoriteTrack.track_id.in_(candidates),
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
new_entries = [e for e in candidates if e not in existing]
|
||||
if not new_entries:
|
||||
return 0
|
||||
added = 0
|
||||
for track in new_entries:
|
||||
for track_id in new_entries:
|
||||
try:
|
||||
with session.begin_nested():
|
||||
session.execute(
|
||||
insert(MusicFavoriteTrack).values(
|
||||
user_id=user_id,
|
||||
rom_file_id=track.rom_file_id,
|
||||
song=track.song,
|
||||
user_id=user_id, track_id=track_id
|
||||
)
|
||||
)
|
||||
except IntegrityError:
|
||||
@@ -266,17 +252,15 @@ class DBMusicPlaylistsHandler(DBBaseHandler):
|
||||
def remove_favorite_tracks(
|
||||
self,
|
||||
user_id: int,
|
||||
tracks: Sequence[TrackKey],
|
||||
track_ids: Sequence[int],
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> int:
|
||||
if not tracks:
|
||||
if not track_ids:
|
||||
return 0
|
||||
result = session.execute(
|
||||
delete(MusicFavoriteTrack).where(
|
||||
MusicFavoriteTrack.user_id == user_id,
|
||||
tuple_(MusicFavoriteTrack.rom_file_id, MusicFavoriteTrack.song).in_(
|
||||
list(tracks)
|
||||
),
|
||||
MusicFavoriteTrack.track_id.in_(list(track_ids)),
|
||||
)
|
||||
)
|
||||
return affected_rows(result)
|
||||
|
||||
@@ -346,62 +346,34 @@ def _song_identity(meta: TrackMeta) -> SongIdentity:
|
||||
return (meta.title, meta.artist, meta.album)
|
||||
|
||||
|
||||
def _song_moves(
|
||||
def _match_songs(
|
||||
old: dict[int, SongIdentity], new: dict[int, SongIdentity]
|
||||
) -> dict[int, int | None]:
|
||||
"""Where each stored song went in a rescan: its new index, or None if gone.
|
||||
) -> dict[int, int]:
|
||||
"""Which stored song each rescanned one is, as {stored index: new index}.
|
||||
|
||||
A song that kept its index and tags is left out. One whose tags turn up at
|
||||
a single other index has moved there, as when an .m3u is reordered.
|
||||
A song keeps its row when its index and tags are unchanged, or when its tags
|
||||
turn up at exactly one other index, as when an .m3u is reordered. When the
|
||||
file has as many songs as before, a song left at its index was only
|
||||
retagged. Stored songs matched to nothing are gone.
|
||||
"""
|
||||
if len(old) == 1 and len(new) == 1 and 0 in old and 0 in new:
|
||||
# A lone song is the same song however its tags were edited.
|
||||
return {}
|
||||
new_by_identity: dict[SongIdentity, list[int]] = {}
|
||||
for song, identity in new.items():
|
||||
new_by_identity.setdefault(identity, []).append(song)
|
||||
old_counts = Counter(old.values())
|
||||
kept = {song: song for song, identity in old.items() if new.get(song) == identity}
|
||||
free = [song for song in new if song not in kept]
|
||||
|
||||
moves: dict[int, int | None] = {}
|
||||
unmatched = Counter(identity for song, identity in old.items() if song not in kept)
|
||||
for song, identity in old.items():
|
||||
if new.get(song) == identity:
|
||||
if song in kept or unmatched[identity] != 1:
|
||||
continue
|
||||
matches = new_by_identity.get(identity, [])
|
||||
unique = len(matches) == 1 and old_counts[identity] == 1
|
||||
moves[song] = matches[0] if unique else None
|
||||
return moves
|
||||
matches = [target for target in free if new[target] == identity]
|
||||
if len(matches) == 1:
|
||||
kept[song] = matches[0]
|
||||
free.remove(matches[0])
|
||||
|
||||
|
||||
def _move_song_references(
|
||||
session: Session, rom_file_id: int, moves: dict[int, int | None]
|
||||
) -> None:
|
||||
"""Point favorites and playlist entries at where their songs went."""
|
||||
gone = [song for song, target in moves.items() if target is None]
|
||||
moved = {song: target for song, target in moves.items() if target is not None}
|
||||
for model in (MusicFavoriteTrack, MusicPlaylistTrack):
|
||||
same_file = model.rom_file_id == rom_file_id
|
||||
if gone:
|
||||
session.execute(
|
||||
delete(model)
|
||||
.where(same_file, model.song.in_(gone))
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
if not moved:
|
||||
continue
|
||||
# Parked past every real index first, so a swap never collides.
|
||||
for song, target in moved.items():
|
||||
session.execute(
|
||||
update(model)
|
||||
.where(same_file, model.song == song)
|
||||
.values(song=target + MAX_SONGS)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
session.execute(
|
||||
update(model)
|
||||
.where(same_file, model.song >= MAX_SONGS)
|
||||
.values(song=model.song - MAX_SONGS)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
if len(old) == len(new):
|
||||
for song in old:
|
||||
if song not in kept and song in free:
|
||||
kept[song] = song
|
||||
free.remove(song)
|
||||
return kept
|
||||
|
||||
|
||||
class SyncedRomFiles(NamedTuple):
|
||||
@@ -2536,11 +2508,11 @@ class DBRomsHandler(DBBaseHandler):
|
||||
row: RomFile,
|
||||
scanned: RomFile,
|
||||
rom_id: int,
|
||||
) -> tuple[str | None, dict[int, int | None]]:
|
||||
"""Copy a scanned file onto its row, with its track metadata.
|
||||
session: Session,
|
||||
) -> str | None:
|
||||
"""Copy a scanned file onto its row, with a track row per song.
|
||||
|
||||
Returns the cover path this update orphaned, if any, and where each
|
||||
stored song went (see `_song_moves`).
|
||||
Returns the cover path this update orphaned, if any.
|
||||
"""
|
||||
_copy_scanned_columns(scanned, row, ROM_FILE_SCANNED_COLUMNS, RomFile)
|
||||
|
||||
@@ -2549,22 +2521,30 @@ class DBRomsHandler(DBBaseHandler):
|
||||
|
||||
# A song left unset reads as None until the insert applies its default.
|
||||
scanned_songs = {meta.song or 0: meta for meta in scanned.track_metas}
|
||||
moves = _song_moves(
|
||||
{meta.song: _song_identity(meta) for meta in row.track_metas},
|
||||
stored = {meta.song: meta for meta in row.track_metas}
|
||||
kept = _match_songs(
|
||||
{song: _song_identity(meta) for song, meta in stored.items()},
|
||||
{song: _song_identity(meta) for song, meta in scanned_songs.items()},
|
||||
)
|
||||
orphaned: str | None = None
|
||||
for stale in list(row.track_metas):
|
||||
if stale.song not in scanned_songs:
|
||||
for song, stale in stored.items():
|
||||
if song not in kept:
|
||||
orphaned = stale.cover_path or orphaned
|
||||
row.track_metas.remove(stale)
|
||||
moving = {song: target for song, target in kept.items() if song != target}
|
||||
for song, target in moving.items():
|
||||
# Parked past every real index, so no step breaks the unique key.
|
||||
stored[song].song = target + MAX_SONGS
|
||||
if moving or len(kept) < len(stored):
|
||||
session.flush()
|
||||
|
||||
existing = {meta.song: meta for meta in row.track_metas}
|
||||
existing = {target: stored[song] for song, target in kept.items()}
|
||||
for song, scanned_meta in sorted(scanned_songs.items()):
|
||||
meta = existing.get(song)
|
||||
if meta is None:
|
||||
meta = TrackMeta(rom_id=rom_id, song=song)
|
||||
meta = TrackMeta(rom_id=rom_id)
|
||||
row.track_metas.append(meta)
|
||||
meta.song = song
|
||||
meta.rom_id = rom_id
|
||||
# The scanner only flags whether a cover exists
|
||||
_copy_scanned_columns(
|
||||
@@ -2575,7 +2555,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
keep_when_unset=frozenset({"cover_path"}),
|
||||
)
|
||||
|
||||
return orphaned, moves
|
||||
return orphaned
|
||||
|
||||
@begin_session
|
||||
def sync_rom_files(
|
||||
@@ -2647,11 +2627,9 @@ class DBRomsHandler(DBBaseHandler):
|
||||
if row is None:
|
||||
row = RomFile(rom_id=rom_id)
|
||||
session.add(row)
|
||||
orphaned, moves = self._apply_scanned_rom_file(row, scanned, rom_id)
|
||||
orphaned = self._apply_scanned_rom_file(row, scanned, rom_id, session)
|
||||
if orphaned:
|
||||
orphaned_cover_paths.append(orphaned)
|
||||
if moves and row.id is not None:
|
||||
_move_song_references(session, row.id, moves)
|
||||
saved.append(row)
|
||||
|
||||
if unmatched:
|
||||
@@ -2794,7 +2772,9 @@ class DBRomsHandler(DBBaseHandler):
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> TrackMeta:
|
||||
"""Write a file's first-song metadata, where its embedded cover lives."""
|
||||
existing = session.get(TrackMeta, (rom_file_id, 0))
|
||||
existing = session.scalar(
|
||||
select(TrackMeta).filter_by(rom_file_id=rom_file_id, song=0).limit(1)
|
||||
)
|
||||
if existing:
|
||||
for key, val in values.items():
|
||||
setattr(existing, key, val)
|
||||
@@ -2806,6 +2786,24 @@ class DBRomsHandler(DBBaseHandler):
|
||||
session.flush()
|
||||
return track
|
||||
|
||||
@begin_session
|
||||
def get_track_owners(
|
||||
self,
|
||||
track_ids: Sequence[int],
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> dict[int, tuple[int, int]]:
|
||||
"""Each existing track's rom and platform, keyed by track id."""
|
||||
if not track_ids:
|
||||
return {}
|
||||
rows = session.execute(
|
||||
select(TrackMeta.id, Rom.id, Rom.platform_id)
|
||||
.join(Rom, TrackMeta.rom_id == Rom.id)
|
||||
.where(TrackMeta.id.in_(list(track_ids)))
|
||||
).all()
|
||||
return {
|
||||
track_id: (rom_id, platform_id) for track_id, rom_id, platform_id in rows
|
||||
}
|
||||
|
||||
@begin_session
|
||||
def delete_track_meta(
|
||||
self,
|
||||
@@ -3002,6 +3000,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
m3u_file = aliased(RomFile)
|
||||
base = (
|
||||
select(
|
||||
TrackMeta.id,
|
||||
TrackMeta.rom_file_id,
|
||||
TrackMeta.song,
|
||||
TrackMeta.rom_id,
|
||||
@@ -3037,8 +3036,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
if is_favorite_user_id is not None:
|
||||
favorite_on = and_(
|
||||
MusicFavoriteTrack.user_id == is_favorite_user_id,
|
||||
MusicFavoriteTrack.rom_file_id == TrackMeta.rom_file_id,
|
||||
MusicFavoriteTrack.song == TrackMeta.song,
|
||||
MusicFavoriteTrack.track_id == TrackMeta.id,
|
||||
)
|
||||
base = (
|
||||
base.join(MusicFavoriteTrack, favorite_on)
|
||||
@@ -3050,14 +3048,13 @@ class DBRomsHandler(DBBaseHandler):
|
||||
MusicPlaylistTrack,
|
||||
and_(
|
||||
MusicPlaylistTrack.playlist_id == playlist_id,
|
||||
MusicPlaylistTrack.rom_file_id == TrackMeta.rom_file_id,
|
||||
MusicPlaylistTrack.song == TrackMeta.song,
|
||||
MusicPlaylistTrack.track_id == TrackMeta.id,
|
||||
),
|
||||
)
|
||||
base = base.where(*where)
|
||||
# Count over a single-column projection: the full select carries a JSON
|
||||
# genres blob that would otherwise be materialized just to be counted.
|
||||
count_subquery = base.with_only_columns(TrackMeta.rom_file_id).subquery()
|
||||
count_subquery = base.with_only_columns(TrackMeta.id).subquery()
|
||||
total = session.scalar(select(func.count()).select_from(count_subquery)) or 0
|
||||
order_map = {
|
||||
"title": TrackMeta.title,
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import (
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
SmallInteger,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
@@ -24,13 +23,6 @@ PLAYLIST_NAME_MAX_LENGTH = 400
|
||||
PLAYLIST_DESCRIPTION_MAX_LENGTH = 65535 # TEXT
|
||||
|
||||
|
||||
class TrackKey(NamedTuple):
|
||||
"""A music track: a soundtrack file and the song within it."""
|
||||
|
||||
rom_file_id: int
|
||||
song: int = 0
|
||||
|
||||
|
||||
class MusicPlaylist(BaseModel):
|
||||
__tablename__ = "music_playlists"
|
||||
|
||||
@@ -59,32 +51,29 @@ class MusicPlaylistTrack(BaseModel):
|
||||
__tablename__ = "music_playlist_tracks"
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"playlist_id", "rom_file_id", "song", name="unique_music_playlist_track"
|
||||
),
|
||||
UniqueConstraint("playlist_id", "track_id", name="unique_music_playlist_track"),
|
||||
Index("idx_music_playlist_tracks_playlist_position", "playlist_id", "position"),
|
||||
Index("ix_music_playlist_tracks_track_id", "track_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
playlist_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("music_playlists.id", ondelete="CASCADE")
|
||||
)
|
||||
rom_file_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("rom_files.id", ondelete="CASCADE")
|
||||
track_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("track_meta.id", ondelete="CASCADE")
|
||||
)
|
||||
song: Mapped[int] = mapped_column(SmallInteger(), default=0, server_default="0")
|
||||
position: Mapped[int] = mapped_column(Integer())
|
||||
|
||||
|
||||
class MusicFavoriteTrack(BaseModel):
|
||||
__tablename__ = "music_favorite_tracks"
|
||||
|
||||
__table_args__ = (Index("ix_music_favorite_tracks_track_id", "track_id"),)
|
||||
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
rom_file_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("rom_files.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
song: Mapped[int] = mapped_column(
|
||||
SmallInteger(), primary_key=True, default=0, server_default="0"
|
||||
track_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("track_meta.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
|
||||
@@ -405,15 +405,15 @@ class TrackMeta(BaseModel):
|
||||
Index("idx_track_meta_artist", "artist"),
|
||||
Index("idx_track_meta_album", "album"),
|
||||
Index("ix_track_meta_m3u_file_id", "m3u_file_id"),
|
||||
UniqueConstraint("rom_file_id", "song", name="uq_track_meta_file_song"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
rom_file_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("rom_files.id", ondelete="CASCADE"), primary_key=True
|
||||
ForeignKey("rom_files.id", ondelete="CASCADE")
|
||||
)
|
||||
# The song's index within its file as libgme numbers it; 0 for other audio.
|
||||
song: Mapped[int] = mapped_column(
|
||||
SmallInteger(), primary_key=True, default=0, server_default="0"
|
||||
)
|
||||
song: Mapped[int] = mapped_column(SmallInteger(), default=0, server_default="0")
|
||||
rom_id: Mapped[int] = mapped_column(ForeignKey("roms.id", ondelete="CASCADE"))
|
||||
# The sidecar .m3u that names and orders the file's songs, if any.
|
||||
m3u_file_id: Mapped[int | None] = mapped_column(
|
||||
|
||||
@@ -379,9 +379,7 @@ def test_facet_excludes_hidden_platform(music_library):
|
||||
|
||||
def _track_id(client: TestClient, token: str, title: str) -> int:
|
||||
body = client.get("/api/music/tracks", headers=_auth(token)).json()
|
||||
return cast(
|
||||
int, next(i["rom_file_id"] for i in body["items"] if i["title"] == title)
|
||||
)
|
||||
return cast(int, next(i["id"] for i in body["items"] if i["title"] == title))
|
||||
|
||||
|
||||
def _make_chiptune(admin_id: int, platform: Platform, songs: int) -> RomFile:
|
||||
@@ -443,11 +441,14 @@ def test_each_song_of_a_chiptune_is_its_own_track(
|
||||
def test_favorites_are_per_song(
|
||||
client: TestClient, access_token: str, admin_user: User
|
||||
):
|
||||
chiptune = _make_chiptune(admin_user.id, _make_platform("nes"), songs=2)
|
||||
_make_chiptune(admin_user.id, _make_platform("nes"), songs=2)
|
||||
|
||||
items = client.get("/api/music/tracks", headers=_auth(access_token)).json()
|
||||
songs = {i["song"]: i["id"] for i in items["items"]}
|
||||
|
||||
r = client.post(
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": chiptune.id, "song": 1}]},
|
||||
json={"track_ids": [songs[1]]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.json()["added"] == 1
|
||||
@@ -458,13 +459,6 @@ def test_favorites_are_per_song(
|
||||
(1, True),
|
||||
]
|
||||
|
||||
r = client.post(
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": chiptune.id, "song": 5}]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
|
||||
def test_favorites_take_the_older_file_id_list(
|
||||
client: TestClient, access_token: str, admin_user: User
|
||||
@@ -488,11 +482,11 @@ def test_favorites_take_the_older_file_id_list(
|
||||
def test_favorites_add_list_remove(
|
||||
client: TestClient, access_token: str, music_library
|
||||
):
|
||||
rf_id = _track_id(client, access_token, "Green Hill")
|
||||
track_id = _track_id(client, access_token, "Green Hill")
|
||||
|
||||
r = client.post(
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": rf_id}]},
|
||||
json={"track_ids": [track_id]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == status.HTTP_200_OK and r.json()["added"] == 1
|
||||
@@ -500,7 +494,7 @@ def test_favorites_add_list_remove(
|
||||
# idempotent re-add
|
||||
r = client.post(
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": rf_id}]},
|
||||
json={"track_ids": [track_id]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.json()["added"] == 0
|
||||
@@ -518,7 +512,7 @@ def test_favorites_add_list_remove(
|
||||
r = client.request(
|
||||
"DELETE",
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": rf_id}]},
|
||||
json={"track_ids": [track_id]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == status.HTTP_200_OK and r.json()["removed"] == 1
|
||||
@@ -534,10 +528,10 @@ def test_favorites_are_per_user(
|
||||
editor_access_token: str,
|
||||
music_library,
|
||||
):
|
||||
rf_id = _track_id(client, access_token, "Green Hill")
|
||||
track_id = _track_id(client, access_token, "Green Hill")
|
||||
client.post(
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": rf_id}]},
|
||||
json={"track_ids": [track_id]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
@@ -551,10 +545,10 @@ def test_favorites_survive_a_rescan(
|
||||
client: TestClient, access_token: str, music_library
|
||||
):
|
||||
"""Rescans reconcile rom_files in place, so favorites keep resolving."""
|
||||
rf_id = _track_id(client, access_token, "Green Hill")
|
||||
track_id = _track_id(client, access_token, "Green Hill")
|
||||
client.post(
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": rf_id}]},
|
||||
json={"track_ids": [track_id]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
@@ -577,7 +571,7 @@ def test_favorites_survive_a_rescan(
|
||||
|
||||
favs = client.get("/api/music/favorites", headers=_auth(access_token)).json()
|
||||
assert favs["total"] == 1
|
||||
assert favs["items"][0]["rom_file_id"] == rf_id
|
||||
assert favs["items"][0]["id"] == track_id
|
||||
|
||||
|
||||
def test_favorites_reject_non_track_and_unknown_ids(
|
||||
@@ -594,7 +588,7 @@ def test_favorites_reject_non_track_and_unknown_ids(
|
||||
)
|
||||
r = client.post(
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": non_track.id}]},
|
||||
json={"rom_file_ids": [non_track.id]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == status.HTTP_400_BAD_REQUEST
|
||||
@@ -602,7 +596,7 @@ def test_favorites_reject_non_track_and_unknown_ids(
|
||||
|
||||
r = client.post(
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": 999_999}]},
|
||||
json={"track_ids": [999_999]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@@ -35,7 +35,7 @@ def _add_tracks(client: TestClient, token: str, playlist: int, titles: list[str]
|
||||
ids = [_track_id(client, token, t) for t in titles]
|
||||
r = client.post(
|
||||
f"/api/music/playlists/{playlist}/tracks",
|
||||
json={"tracks": [{"rom_file_id": i} for i in ids]},
|
||||
json={"track_ids": ids},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert r.status_code == status.HTTP_200_OK
|
||||
@@ -154,17 +154,17 @@ def test_public_playlist_readable_not_writable_by_others(
|
||||
(
|
||||
"POST",
|
||||
f"/api/music/playlists/{playlist_id}/tracks",
|
||||
{"tracks": [{"rom_file_id": 1}]},
|
||||
{"track_ids": [1]},
|
||||
),
|
||||
(
|
||||
"DELETE",
|
||||
f"/api/music/playlists/{playlist_id}/tracks",
|
||||
{"tracks": [{"rom_file_id": 1}]},
|
||||
{"track_ids": [1]},
|
||||
),
|
||||
(
|
||||
"PUT",
|
||||
f"/api/music/playlists/{playlist_id}/tracks/order",
|
||||
{"tracks": [{"rom_file_id": 1}]},
|
||||
{"track_ids": [1]},
|
||||
),
|
||||
]:
|
||||
r = client.request(
|
||||
@@ -191,7 +191,7 @@ def test_playlist_tracks_ordered_and_deduped(
|
||||
# re-adding an existing track is a no-op
|
||||
r = client.post(
|
||||
f"/api/music/playlists/{playlist_id}/tracks",
|
||||
json={"tracks": [{"rom_file_id": ids[0]}]},
|
||||
json={"track_ids": [ids[0]]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.json()["added"] == 0
|
||||
@@ -204,11 +204,14 @@ def test_playlist_holds_songs_of_one_file(
|
||||
client: TestClient, access_token: str, playlist_id: int, admin_user: User
|
||||
):
|
||||
chiptune = _make_chiptune(admin_user.id, _make_platform("sms"), songs=3)
|
||||
songs = [{"rom_file_id": chiptune.id, "song": song} for song in (2, 0)]
|
||||
stored = db_rom_handler.get_rom_file_by_id(chiptune.id)
|
||||
assert stored is not None
|
||||
by_song = {meta.song: meta.id for meta in stored.track_metas}
|
||||
songs = [by_song[2], by_song[0]]
|
||||
|
||||
r = client.post(
|
||||
f"/api/music/playlists/{playlist_id}/tracks",
|
||||
json={"tracks": songs},
|
||||
json={"track_ids": songs},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.json()["added"] == 2
|
||||
@@ -216,7 +219,7 @@ def test_playlist_holds_songs_of_one_file(
|
||||
|
||||
r = client.put(
|
||||
f"/api/music/playlists/{playlist_id}/tracks/order",
|
||||
json={"tracks": songs[::-1]},
|
||||
json={"track_ids": songs[::-1]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == status.HTTP_204_NO_CONTENT
|
||||
@@ -225,7 +228,7 @@ def test_playlist_holds_songs_of_one_file(
|
||||
r = client.request(
|
||||
"DELETE",
|
||||
f"/api/music/playlists/{playlist_id}/tracks",
|
||||
json={"tracks": songs[:1]},
|
||||
json={"track_ids": songs[:1]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.json()["removed"] == 1
|
||||
@@ -254,7 +257,7 @@ def test_playlist_reorder(client: TestClient, access_token: str, playlist_id: in
|
||||
)
|
||||
r = client.put(
|
||||
f"/api/music/playlists/{playlist_id}/tracks/order",
|
||||
json={"tracks": [{"rom_file_id": ids[i]} for i in (2, 0, 1)]},
|
||||
json={"track_ids": [ids[i] for i in (2, 0, 1)]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == status.HTTP_204_NO_CONTENT
|
||||
@@ -273,7 +276,7 @@ def test_playlist_partial_reorder_keeps_rest_after(
|
||||
)
|
||||
client.put(
|
||||
f"/api/music/playlists/{playlist_id}/tracks/order",
|
||||
json={"tracks": [{"rom_file_id": ids[2]}]},
|
||||
json={"track_ids": [ids[2]]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert _playlist_titles(client, access_token, playlist_id) == [
|
||||
@@ -290,7 +293,7 @@ def test_playlist_reorder_foreign_track_400(
|
||||
outsider = _track_id(client, access_token, "Overworld")
|
||||
r = client.put(
|
||||
f"/api/music/playlists/{playlist_id}/tracks/order",
|
||||
json={"tracks": [{"rom_file_id": outsider}]},
|
||||
json={"track_ids": [outsider]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == status.HTTP_400_BAD_REQUEST
|
||||
@@ -305,7 +308,7 @@ def test_playlist_remove_tracks(
|
||||
r = client.request(
|
||||
"DELETE",
|
||||
f"/api/music/playlists/{playlist_id}/tracks",
|
||||
json={"tracks": [{"rom_file_id": ids[1]}]},
|
||||
json={"track_ids": [ids[1]]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.json()["removed"] == 1
|
||||
@@ -345,14 +348,16 @@ def test_playlist_survives_a_rescan(
|
||||
f"/api/music/playlists/{playlist_id}/tracks", headers=_auth(access_token)
|
||||
).json()
|
||||
assert [i["title"] for i in body["items"]] == ["Green Hill", "Jingle"]
|
||||
assert body["items"][0]["rom_file_id"] == ids[0]
|
||||
assert body["items"][0]["id"] == ids[0]
|
||||
|
||||
|
||||
def test_playlist_entry_dropped_when_file_leaves_library(
|
||||
client: TestClient, access_token: str, playlist_id: int # noqa: F811
|
||||
):
|
||||
ids = _add_tracks(client, access_token, playlist_id, ["Green Hill", "Jingle"])
|
||||
db_rom_handler.delete_rom_file(ids[0])
|
||||
catalog = client.get("/api/music/tracks", headers=_auth(access_token)).json()
|
||||
file_of = {i["id"]: i["rom_file_id"] for i in catalog["items"]}
|
||||
db_rom_handler.delete_rom_file(file_of[ids[0]])
|
||||
|
||||
tracks = client.get(
|
||||
f"/api/music/playlists/{playlist_id}/tracks", headers=_auth(access_token)
|
||||
@@ -389,7 +394,7 @@ def test_playlist_rows_carry_is_favorite(
|
||||
ids = _add_tracks(client, access_token, playlist_id, ["Green Hill", "Jingle"])
|
||||
client.post(
|
||||
"/api/music/favorites",
|
||||
json={"tracks": [{"rom_file_id": ids[0]}]},
|
||||
json={"track_ids": [ids[0]]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
body = client.get(
|
||||
@@ -418,16 +423,19 @@ def test_identical_copies_are_separate_entries(
|
||||
track_metas=[TrackMeta(rom_id=rom.id, title="Green Hill")],
|
||||
)
|
||||
)
|
||||
stored = db_rom_handler.get_rom_file_by_id(copy.id)
|
||||
assert stored is not None and stored.track_meta is not None
|
||||
copy_track = stored.track_meta.id
|
||||
client.post(
|
||||
f"/api/music/playlists/{playlist_id}/tracks",
|
||||
json={"tracks": [{"rom_file_id": copy.id}]},
|
||||
json={"track_ids": [copy_track]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
body = client.get(
|
||||
f"/api/music/playlists/{playlist_id}/tracks", headers=_auth(access_token)
|
||||
).json()
|
||||
assert body["total"] == 2
|
||||
assert [i["rom_file_id"] for i in body["items"]] == [ids[0], copy.id]
|
||||
assert [i["id"] for i in body["items"]] == [ids[0], copy_track]
|
||||
|
||||
|
||||
# ---------- scopes ----------
|
||||
|
||||
@@ -2,7 +2,7 @@ import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from handler.database import db_music_playlist_handler, db_rom_handler, db_user_handler
|
||||
from models.music import MusicPlaylist, TrackKey
|
||||
from models.music import MusicPlaylist
|
||||
from models.rom import Rom, RomFile, RomFileCategory
|
||||
from models.user import Role, User
|
||||
|
||||
@@ -15,8 +15,8 @@ def playlist(admin_user: User) -> MusicPlaylist:
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def track_ids(rom: Rom) -> list[int]:
|
||||
"""Three soundtrack files on `rom`, referenced by id throughout."""
|
||||
def track_files(rom: Rom) -> list[int]:
|
||||
"""Three soundtrack files on `rom`."""
|
||||
return [
|
||||
db_rom_handler.add_rom_file(
|
||||
RomFile(
|
||||
@@ -31,8 +31,13 @@ def track_ids(rom: Rom) -> list[int]:
|
||||
]
|
||||
|
||||
|
||||
def _keys(*rom_file_ids: int) -> list[TrackKey]:
|
||||
return [TrackKey(rom_file_id) for rom_file_id in rom_file_ids]
|
||||
@pytest.fixture
|
||||
def track_ids(rom: Rom, track_files: list[int]) -> list[int]:
|
||||
"""The track of each of `track_files`, referenced by id throughout."""
|
||||
return [
|
||||
db_rom_handler.upsert_track_meta(file_id, rom.id, {}).id
|
||||
for file_id in track_files
|
||||
]
|
||||
|
||||
|
||||
def test_playlist_crud(admin_user: User, playlist: MusicPlaylist):
|
||||
@@ -100,17 +105,15 @@ def test_get_playlists_own_and_public(admin_user: User, playlist: MusicPlaylist)
|
||||
def test_add_tracks_positions_and_dedupe(track_ids, playlist: MusicPlaylist):
|
||||
aaa, bbb, ccc = track_ids
|
||||
added = db_music_playlist_handler.add_tracks_to_playlist(
|
||||
playlist.id, _keys(aaa, bbb, aaa)
|
||||
playlist.id, [aaa, bbb, aaa]
|
||||
)
|
||||
assert added == 2
|
||||
|
||||
added = db_music_playlist_handler.add_tracks_to_playlist(
|
||||
playlist.id, _keys(bbb, ccc)
|
||||
)
|
||||
added = db_music_playlist_handler.add_tracks_to_playlist(playlist.id, [bbb, ccc])
|
||||
assert added == 1
|
||||
|
||||
entries = db_music_playlist_handler.get_playlist_entries(playlist.id)
|
||||
assert [(e.rom_file_id, e.position) for e in entries] == [
|
||||
assert [(e.track_id, e.position) for e in entries] == [
|
||||
(aaa, 1),
|
||||
(bbb, 2),
|
||||
(ccc, 3),
|
||||
@@ -119,26 +122,26 @@ def test_add_tracks_positions_and_dedupe(track_ids, playlist: MusicPlaylist):
|
||||
|
||||
def test_remove_tracks_keeps_order(track_ids, playlist: MusicPlaylist):
|
||||
aaa, bbb, ccc = track_ids
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, _keys(aaa, bbb, ccc))
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, [aaa, bbb, ccc])
|
||||
removed = db_music_playlist_handler.remove_tracks_from_playlist(
|
||||
playlist.id, _keys(bbb, 999999)
|
||||
playlist.id, [bbb, 999999]
|
||||
)
|
||||
assert removed == 1
|
||||
entries = db_music_playlist_handler.get_playlist_entries(playlist.id)
|
||||
assert [e.rom_file_id for e in entries] == [aaa, ccc]
|
||||
assert [e.track_id for e in entries] == [aaa, ccc]
|
||||
|
||||
|
||||
def test_set_order_rewrites_and_appends_unlisted(track_ids, playlist: MusicPlaylist):
|
||||
aaa, bbb, ccc = track_ids
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, _keys(aaa, bbb, ccc))
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, [aaa, bbb, ccc])
|
||||
entries = db_music_playlist_handler.get_playlist_entries(playlist.id)
|
||||
entry_id = {e.rom_file_id: e.id for e in entries}
|
||||
entry_id = {e.track_id: e.id for e in entries}
|
||||
|
||||
db_music_playlist_handler.set_playlist_track_order(
|
||||
playlist.id, [entry_id[ccc], entry_id[aaa]]
|
||||
)
|
||||
entries = db_music_playlist_handler.get_playlist_entries(playlist.id)
|
||||
assert [(e.rom_file_id, e.position) for e in entries] == [
|
||||
assert [(e.track_id, e.position) for e in entries] == [
|
||||
(ccc, 0),
|
||||
(aaa, 1),
|
||||
(bbb, 2),
|
||||
@@ -149,7 +152,7 @@ def test_track_counts(track_ids, playlist: MusicPlaylist, admin_user: User):
|
||||
other = db_music_playlist_handler.add_playlist(
|
||||
MusicPlaylist(name="Empty", user_id=admin_user.id)
|
||||
)
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, _keys(*track_ids[:2]))
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, track_ids[:2])
|
||||
counts = db_music_playlist_handler.get_playlist_track_counts(
|
||||
[playlist.id, other.id]
|
||||
)
|
||||
@@ -159,37 +162,28 @@ def test_track_counts(track_ids, playlist: MusicPlaylist, admin_user: User):
|
||||
|
||||
def test_favorites_add_remove_idempotent(track_ids, admin_user: User):
|
||||
aaa = track_ids[0]
|
||||
assert (
|
||||
db_music_playlist_handler.add_favorite_tracks(admin_user.id, _keys(aaa, aaa))
|
||||
== 1
|
||||
)
|
||||
assert db_music_playlist_handler.add_favorite_tracks(admin_user.id, _keys(aaa)) == 0
|
||||
assert (
|
||||
db_music_playlist_handler.remove_favorite_tracks(admin_user.id, _keys(aaa)) == 1
|
||||
)
|
||||
assert (
|
||||
db_music_playlist_handler.remove_favorite_tracks(admin_user.id, _keys(aaa)) == 0
|
||||
)
|
||||
assert db_music_playlist_handler.add_favorite_tracks(admin_user.id, [aaa, aaa]) == 1
|
||||
assert db_music_playlist_handler.add_favorite_tracks(admin_user.id, [aaa]) == 0
|
||||
assert db_music_playlist_handler.remove_favorite_tracks(admin_user.id, [aaa]) == 1
|
||||
assert db_music_playlist_handler.remove_favorite_tracks(admin_user.id, [aaa]) == 0
|
||||
|
||||
|
||||
def test_playlist_tracks_cascade_on_playlist_delete(track_ids, playlist: MusicPlaylist):
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, _keys(*track_ids[:1]))
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, track_ids[:1])
|
||||
db_music_playlist_handler.delete_playlist(playlist.id)
|
||||
assert db_music_playlist_handler.get_playlist_entries(playlist.id) == []
|
||||
|
||||
|
||||
def test_playlist_tracks_cascade_on_rom_file_delete(
|
||||
track_ids, playlist: MusicPlaylist, admin_user: User
|
||||
track_files, track_ids, playlist: MusicPlaylist, admin_user: User
|
||||
):
|
||||
"""A file that leaves the library takes its entries with it."""
|
||||
aaa, bbb, _ = track_ids
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, _keys(aaa, bbb))
|
||||
db_music_playlist_handler.add_favorite_tracks(admin_user.id, _keys(aaa))
|
||||
db_music_playlist_handler.add_tracks_to_playlist(playlist.id, [aaa, bbb])
|
||||
db_music_playlist_handler.add_favorite_tracks(admin_user.id, [aaa])
|
||||
|
||||
db_rom_handler.delete_rom_file(aaa)
|
||||
db_rom_handler.delete_rom_file(track_files[0])
|
||||
|
||||
entries = db_music_playlist_handler.get_playlist_entries(playlist.id)
|
||||
assert [e.rom_file_id for e in entries] == [bbb]
|
||||
assert (
|
||||
db_music_playlist_handler.remove_favorite_tracks(admin_user.id, _keys(aaa)) == 0
|
||||
)
|
||||
assert [e.track_id for e in entries] == [bbb]
|
||||
assert db_music_playlist_handler.remove_favorite_tracks(admin_user.id, [aaa]) == 0
|
||||
|
||||
@@ -18,7 +18,7 @@ from handler.database import (
|
||||
)
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.assets import Save, State
|
||||
from models.music import MusicFavoriteTrack, MusicPlaylist, TrackKey
|
||||
from models.music import MusicFavoriteTrack, MusicPlaylist
|
||||
from models.platform import Platform
|
||||
from models.rom import (
|
||||
HAS_FILE_ON_DISK_FILTERS,
|
||||
@@ -277,14 +277,23 @@ def _chiptune(rom: Rom, titles: list[str]) -> RomFile:
|
||||
)
|
||||
|
||||
|
||||
def _favorite_songs(user_id: int) -> list[tuple[int, int]]:
|
||||
def _songs(rom_file_id: int) -> dict[int, int]:
|
||||
"""A file's track ids by song."""
|
||||
row = db_rom_handler.get_rom_file_by_id(rom_file_id)
|
||||
assert row is not None
|
||||
return {meta.song: meta.id for meta in row.track_metas}
|
||||
|
||||
|
||||
def _favorite_songs(user_id: int) -> list[tuple[str | None, int]]:
|
||||
"""The user's favorites, as each track's title and current song."""
|
||||
with sync_session.begin() as session:
|
||||
return [
|
||||
(row.rom_file_id, row.song)
|
||||
for row in session.scalars(
|
||||
select(MusicFavoriteTrack)
|
||||
.filter_by(user_id=user_id)
|
||||
.order_by(MusicFavoriteTrack.song)
|
||||
(title, song)
|
||||
for title, song in session.execute(
|
||||
select(TrackMeta.title, TrackMeta.song)
|
||||
.join(MusicFavoriteTrack, MusicFavoriteTrack.track_id == TrackMeta.id)
|
||||
.where(MusicFavoriteTrack.user_id == user_id)
|
||||
.order_by(TrackMeta.song)
|
||||
)
|
||||
]
|
||||
|
||||
@@ -480,37 +489,46 @@ class TestSyncRomFiles:
|
||||
|
||||
def test_saved_songs_follow_a_reordered_playlist(self, rom: Rom, admin_user: User):
|
||||
(chiptune,) = _sync(rom, [_chiptune(rom, ["Intro", "Stage", "Boss"])])
|
||||
before = _songs(chiptune.id)
|
||||
db_music_playlist_handler.add_favorite_tracks(
|
||||
admin_user.id, [TrackKey(chiptune.id, 1), TrackKey(chiptune.id, 2)]
|
||||
admin_user.id, [before[1], before[2]]
|
||||
)
|
||||
playlist = db_music_playlist_handler.add_playlist(
|
||||
MusicPlaylist(name="Mix", user_id=admin_user.id)
|
||||
)
|
||||
db_music_playlist_handler.add_tracks_to_playlist(
|
||||
playlist.id, [TrackKey(chiptune.id, 2), TrackKey(chiptune.id, 1)]
|
||||
playlist.id, [before[2], before[1]]
|
||||
)
|
||||
|
||||
# Boss and Stage swap places, and Intro leaves the list.
|
||||
# Boss moves to the front, and Intro leaves the list.
|
||||
_sync(rom, [_chiptune(rom, ["Boss", "Stage"])])
|
||||
|
||||
assert _favorite_songs(admin_user.id) == [
|
||||
(chiptune.id, 0),
|
||||
(chiptune.id, 1),
|
||||
]
|
||||
after = _songs(chiptune.id)
|
||||
assert after == {0: before[2], 1: before[1]}
|
||||
assert _favorite_songs(admin_user.id) == [("Boss", 0), ("Stage", 1)]
|
||||
entries = db_music_playlist_handler.get_playlist_entries(playlist.id)
|
||||
assert [(e.song, e.position) for e in entries] == [(0, 1), (1, 2)]
|
||||
assert [e.track_id for e in entries] == [before[2], before[1]]
|
||||
|
||||
def test_songs_that_swap_places_keep_their_rows(self, rom: Rom):
|
||||
(chiptune,) = _sync(rom, [_chiptune(rom, ["Intro", "Stage"])])
|
||||
before = _songs(chiptune.id)
|
||||
|
||||
_sync(rom, [_chiptune(rom, ["Stage", "Intro"])])
|
||||
|
||||
assert _songs(chiptune.id) == {0: before[1], 1: before[0]}
|
||||
|
||||
def test_saved_songs_that_are_gone_are_dropped(self, rom: Rom, admin_user: User):
|
||||
(chiptune,) = _sync(rom, [_chiptune(rom, ["Intro", "Stage", "Boss"])])
|
||||
before = _songs(chiptune.id)
|
||||
db_music_playlist_handler.add_favorite_tracks(
|
||||
admin_user.id, [TrackKey(chiptune.id, 0), TrackKey(chiptune.id, 2)]
|
||||
admin_user.id, [before[0], before[2]]
|
||||
)
|
||||
|
||||
_sync(rom, [_chiptune(rom, ["Intro", "Stage"])])
|
||||
|
||||
assert _favorite_songs(admin_user.id) == [(chiptune.id, 0)]
|
||||
assert _favorite_songs(admin_user.id) == [("Intro", 0)]
|
||||
|
||||
def test_a_retagged_lone_track_stays_saved(self, rom: Rom, admin_user: User):
|
||||
def test_a_retagged_track_stays_saved(self, rom: Rom, admin_user: User):
|
||||
def song(title: str) -> RomFile:
|
||||
return _scanned_file(
|
||||
rom,
|
||||
@@ -521,12 +539,12 @@ class TestSyncRomFiles:
|
||||
|
||||
(track,) = _sync(rom, [song("Theme")])
|
||||
db_music_playlist_handler.add_favorite_tracks(
|
||||
admin_user.id, [TrackKey(track.id)]
|
||||
admin_user.id, list(_songs(track.id).values())
|
||||
)
|
||||
|
||||
_sync(rom, [song("Main Theme")])
|
||||
|
||||
assert _favorite_songs(admin_user.id) == [(track.id, 0)]
|
||||
assert _favorite_songs(admin_user.id) == [("Main Theme", 0)]
|
||||
|
||||
def test_unset_columns_do_not_overwrite_not_null_values(self, rom: Rom):
|
||||
"""A scanned row leaves unset columns as None, and the model defaults
|
||||
|
||||
@@ -20,11 +20,24 @@ from sqlalchemy import DefaultClause, FetchedValue, Table, UniqueConstraint
|
||||
from sqlalchemy.sql.schema import NULL_UNSPECIFIED
|
||||
|
||||
import models
|
||||
from handler.database import db_platform_handler
|
||||
from handler.database import (
|
||||
db_music_playlist_handler,
|
||||
db_platform_handler,
|
||||
db_rom_handler,
|
||||
)
|
||||
from handler.database.base_handler import sync_engine
|
||||
from models.base import BaseModel
|
||||
from models.music import MusicPlaylist
|
||||
from models.platform import Platform
|
||||
from models.rom import FULL_PATH_HASH_LENGTH, Rom, compute_full_path_hash
|
||||
from models.rom import (
|
||||
FULL_PATH_HASH_LENGTH,
|
||||
Rom,
|
||||
RomFile,
|
||||
RomFileCategory,
|
||||
TrackMeta,
|
||||
compute_full_path_hash,
|
||||
)
|
||||
from models.user import User
|
||||
from utils.database import (
|
||||
AUTOGENERATE_EXEMPT_INDEX_NAMES,
|
||||
HLTB_MAIN_STORY_COLUMN,
|
||||
@@ -332,7 +345,7 @@ def test_the_user_oidc_sub_revision_reverses_and_replays():
|
||||
assert _schema_of(connection, "users") == before
|
||||
|
||||
|
||||
def _song_keys(connection: sa.Connection) -> dict[str, tuple[str, ...]]:
|
||||
def _track_keys(connection: sa.Connection) -> dict[str, tuple[str, ...]]:
|
||||
inspector = sa.inspect(connection)
|
||||
keys = {
|
||||
table: tuple(inspector.get_pk_constraint(table)["constrained_columns"])
|
||||
@@ -344,29 +357,89 @@ def _song_keys(connection: sa.Connection) -> dict[str, tuple[str, ...]]:
|
||||
return keys
|
||||
|
||||
|
||||
def test_the_track_meta_songs_revision_reverses_and_replays():
|
||||
"""0145 swaps primary and unique keys, so each swap checks the current key."""
|
||||
def _referenced_files(connection: sa.Connection) -> dict[str, set[int]]:
|
||||
"""The files each favorite and playlist entry points at, by either column."""
|
||||
files = {}
|
||||
for table in ("music_favorite_tracks", "music_playlist_tracks"):
|
||||
if has_column(connection, table, "track_id"):
|
||||
query = (
|
||||
f"SELECT t.rom_file_id FROM {table} r" # nosec B608
|
||||
" JOIN track_meta t ON t.id = r.track_id"
|
||||
)
|
||||
else:
|
||||
query = f"SELECT rom_file_id FROM {table}" # nosec B608
|
||||
files[table] = set(connection.execute(sa.text(query)).scalars())
|
||||
return files
|
||||
|
||||
|
||||
def test_the_track_meta_songs_revision_reverses_and_replays(rom: Rom, admin_user: User):
|
||||
"""0145 moves favorites and playlist entries between file and track keys.
|
||||
|
||||
Going back keeps only what a file's first song held; each step checks the
|
||||
current schema, so both directions replay.
|
||||
"""
|
||||
theme, chips = (
|
||||
db_rom_handler.add_rom_file(
|
||||
RomFile(
|
||||
rom_id=rom.id,
|
||||
file_name=name,
|
||||
file_path=rom.fs_path,
|
||||
file_size_bytes=1,
|
||||
category=RomFileCategory.SOUNDTRACK,
|
||||
track_metas=[TrackMeta(rom_id=rom.id, song=s) for s in songs],
|
||||
)
|
||||
).id
|
||||
for name, songs in (("theme.mp3", [0]), ("chips.nsf", [0, 1]))
|
||||
)
|
||||
tracks = {
|
||||
(file_id, song): track_id
|
||||
for file_id in (theme, chips)
|
||||
for song, track_id in _file_tracks(file_id).items()
|
||||
}
|
||||
db_music_playlist_handler.add_favorite_tracks(
|
||||
admin_user.id, [tracks[theme, 0], tracks[chips, 1]]
|
||||
)
|
||||
playlist = db_music_playlist_handler.add_playlist(
|
||||
MusicPlaylist(name="Mix", user_id=admin_user.id)
|
||||
)
|
||||
db_music_playlist_handler.add_tracks_to_playlist(
|
||||
playlist.id, [tracks[chips, 0], tracks[chips, 1]]
|
||||
)
|
||||
|
||||
migration = _load_migration("0145_track_meta_songs.py")
|
||||
tables = ("track_meta", "music_favorite_tracks", "music_playlist_tracks")
|
||||
|
||||
with sync_engine.begin() as connection:
|
||||
before = {table: _schema_of(connection, table) for table in tables}
|
||||
keys = _song_keys(connection)
|
||||
keys = _track_keys(connection)
|
||||
with Operations.context(MigrationContext.configure(connection)):
|
||||
migration.downgrade()
|
||||
assert _song_keys(connection) == {
|
||||
assert _track_keys(connection) == {
|
||||
"track_meta": ("rom_file_id",),
|
||||
"music_favorite_tracks": ("user_id", "rom_file_id"),
|
||||
"music_playlist_tracks": ("playlist_id", "rom_file_id"),
|
||||
}
|
||||
assert not has_column(connection, "track_meta", "m3u_file_id")
|
||||
assert not has_column(connection, "track_meta", "id")
|
||||
assert _referenced_files(connection) == {
|
||||
"music_favorite_tracks": {theme},
|
||||
"music_playlist_tracks": {chips},
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
migration.upgrade()
|
||||
migration.upgrade()
|
||||
|
||||
assert _song_keys(connection) == keys
|
||||
assert _track_keys(connection) == keys
|
||||
assert {table: _schema_of(connection, table) for table in tables} == before
|
||||
assert _referenced_files(connection) == {
|
||||
"music_favorite_tracks": {theme},
|
||||
"music_playlist_tracks": {chips},
|
||||
}
|
||||
|
||||
|
||||
def _file_tracks(rom_file_id: int) -> dict[int, int]:
|
||||
row = db_rom_handler.get_rom_file_by_id(rom_file_id)
|
||||
assert row is not None
|
||||
return {meta.song: meta.id for meta in row.track_metas}
|
||||
|
||||
|
||||
def _slot_collations(connection: sa.Connection) -> dict[str, str | None]:
|
||||
|
||||
@@ -17,8 +17,6 @@ POSTGRESQL_FK_INDEXES: tuple[tuple[str, str, str], ...] = (
|
||||
("rom_notes", "ix_rom_notes_user_id", "user_id"),
|
||||
("firmware", "ix_firmware_platform_id", "platform_id"),
|
||||
("collections_roms", "ix_collections_roms_rom_id", "rom_id"),
|
||||
("music_playlist_tracks", "ix_music_playlist_tracks_rom_file_id", "rom_file_id"),
|
||||
("music_favorite_tracks", "ix_music_favorite_tracks_rom_file_id", "rom_file_id"),
|
||||
("play_sessions", "ix_play_sessions_rom_id", "rom_id"),
|
||||
("play_sessions", "ix_play_sessions_device_id", "device_id"),
|
||||
("saves", "ix_saves_user_id", "user_id"),
|
||||
|
||||
1
frontend/src/__generated__/index.ts
generated
1
frontend/src/__generated__/index.ts
generated
@@ -173,7 +173,6 @@ export type { MusicPlaylistSchema } from './models/MusicPlaylistSchema';
|
||||
export type { MusicPlaylistUpdateRequest } from './models/MusicPlaylistUpdateRequest';
|
||||
export type { MusicStatsSchema } from './models/MusicStatsSchema';
|
||||
export type { MusicTrackIdsPayload } from './models/MusicTrackIdsPayload';
|
||||
export type { MusicTrackRef } from './models/MusicTrackRef';
|
||||
export type { MusicTrackSchema } from './models/MusicTrackSchema';
|
||||
export type { MuteRequest } from './models/MuteRequest';
|
||||
export type { MuteResponse } from './models/MuteResponse';
|
||||
|
||||
@@ -2,11 +2,10 @@
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { MusicTrackRef } from './MusicTrackRef';
|
||||
export type MusicTrackIdsPayload = {
|
||||
tracks?: Array<MusicTrackRef>;
|
||||
track_ids?: Array<number>;
|
||||
/**
|
||||
* The first song of each file. Use `tracks` instead.
|
||||
* The first song of each file. Use `track_ids` instead.
|
||||
* @deprecated
|
||||
*/
|
||||
rom_file_ids?: Array<number>;
|
||||
|
||||
12
frontend/src/__generated__/models/MusicTrackRef.ts
generated
12
frontend/src/__generated__/models/MusicTrackRef.ts
generated
@@ -1,12 +0,0 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type MusicTrackRef = {
|
||||
rom_file_id: number;
|
||||
/**
|
||||
* Song within the file; 0 for most audio.
|
||||
*/
|
||||
song?: number;
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type MusicTrackSchema = {
|
||||
id: number;
|
||||
rom_file_id: number;
|
||||
song?: number;
|
||||
rom_id: number;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type TrackMetaSchema = {
|
||||
id: number;
|
||||
song?: number;
|
||||
m3u_file_id?: (number | null);
|
||||
title?: (string | null);
|
||||
|
||||
@@ -22,10 +22,10 @@ describe("music favorites store", () => {
|
||||
it("seeds from a payload without forgetting tracks outside it", () => {
|
||||
const store = useMusicFavorites();
|
||||
store.merge([
|
||||
{ rom_file_id: 1, is_favorite: true },
|
||||
{ rom_file_id: 2, is_favorite: false },
|
||||
{ id: 1, is_favorite: true },
|
||||
{ id: 2, is_favorite: false },
|
||||
]);
|
||||
store.merge([{ rom_file_id: 3, is_favorite: true }]);
|
||||
store.merge([{ id: 3, is_favorite: true }]);
|
||||
|
||||
expect(store.isFavorite(1)).toBe(true);
|
||||
expect(store.isFavorite(2)).toBe(false);
|
||||
@@ -33,24 +33,10 @@ describe("music favorites store", () => {
|
||||
expect(store.count).toBe(2);
|
||||
});
|
||||
|
||||
it("tells the songs of one file apart", async () => {
|
||||
const store = useMusicFavorites();
|
||||
store.merge([{ rom_file_id: 7, song: 2, is_favorite: true }]);
|
||||
expect(store.isFavorite(7, 2)).toBe(true);
|
||||
expect(store.isFavorite(7)).toBe(false);
|
||||
|
||||
await store.toggle(7, 1);
|
||||
expect(addFavorites).toHaveBeenCalledWith({
|
||||
tracks: [{ rom_file_id: 7, song: 1 }],
|
||||
});
|
||||
expect(store.isFavorite(7, 1)).toBe(true);
|
||||
expect(store.count).toBe(2);
|
||||
});
|
||||
|
||||
it("un-favorites a track that a later payload reports as not favorite", () => {
|
||||
const store = useMusicFavorites();
|
||||
store.merge([{ rom_file_id: 1, is_favorite: true }]);
|
||||
store.merge([{ rom_file_id: 1, is_favorite: false }]);
|
||||
store.merge([{ id: 1, is_favorite: true }]);
|
||||
store.merge([{ id: 1, is_favorite: false }]);
|
||||
expect(store.isFavorite(1)).toBe(false);
|
||||
});
|
||||
|
||||
@@ -58,15 +44,11 @@ describe("music favorites store", () => {
|
||||
const store = useMusicFavorites();
|
||||
|
||||
await expect(store.toggle(4)).resolves.toBe(true);
|
||||
expect(addFavorites).toHaveBeenCalledWith({
|
||||
tracks: [{ rom_file_id: 4, song: 0 }],
|
||||
});
|
||||
expect(addFavorites).toHaveBeenCalledWith({ track_ids: [4] });
|
||||
expect(store.isFavorite(4)).toBe(true);
|
||||
|
||||
await expect(store.toggle(4)).resolves.toBe(false);
|
||||
expect(removeFavorites).toHaveBeenCalledWith({
|
||||
tracks: [{ rom_file_id: 4, song: 0 }],
|
||||
});
|
||||
expect(removeFavorites).toHaveBeenCalledWith({ track_ids: [4] });
|
||||
expect(store.isFavorite(4)).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,60 +1,46 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref } from "vue";
|
||||
import musicApi from "@/services/api/music";
|
||||
import { playerTrackKey } from "@/stores/soundtrackPlayer";
|
||||
|
||||
/** A favorited track: its file, and the song within it for multi-song files. */
|
||||
interface FavoriteTrack {
|
||||
rom_file_id: number;
|
||||
song?: number;
|
||||
is_favorite?: boolean;
|
||||
}
|
||||
|
||||
function keyOf(fileId: number, song = 0): string {
|
||||
return playerTrackKey({ fileId, song });
|
||||
}
|
||||
|
||||
const useMusicFavorites = defineStore("musicFavorites", () => {
|
||||
const favoriteIds = ref<Set<string>>(new Set());
|
||||
const pendingIds = ref<Set<string>>(new Set());
|
||||
const favoriteIds = ref<Set<number>>(new Set());
|
||||
const pendingIds = ref<Set<number>>(new Set());
|
||||
|
||||
const count = computed(() => favoriteIds.value.size);
|
||||
|
||||
function isFavorite(fileId: number, song = 0): boolean {
|
||||
return favoriteIds.value.has(keyOf(fileId, song));
|
||||
function isFavorite(trackId: number): boolean {
|
||||
return favoriteIds.value.has(trackId);
|
||||
}
|
||||
|
||||
function isPending(fileId: number, song = 0): boolean {
|
||||
return pendingIds.value.has(keyOf(fileId, song));
|
||||
function isPending(trackId: number): boolean {
|
||||
return pendingIds.value.has(trackId);
|
||||
}
|
||||
|
||||
/** Seed from any payload that carries `is_favorite`, without dropping
|
||||
* knowledge of tracks outside it. */
|
||||
function merge(tracks: FavoriteTrack[]) {
|
||||
function merge(tracks: { id: number; is_favorite?: boolean }[]) {
|
||||
for (const track of tracks) {
|
||||
const key = keyOf(track.rom_file_id, track.song);
|
||||
if (track.is_favorite) favoriteIds.value.add(key);
|
||||
else favoriteIds.value.delete(key);
|
||||
if (track.is_favorite) favoriteIds.value.add(track.id);
|
||||
else favoriteIds.value.delete(track.id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Flips one track and returns the new state, or null if the call failed. */
|
||||
async function toggle(fileId: number, song = 0): Promise<boolean | null> {
|
||||
const key = keyOf(fileId, song);
|
||||
if (pendingIds.value.has(key)) return null;
|
||||
const next = !favoriteIds.value.has(key);
|
||||
pendingIds.value.add(key);
|
||||
async function toggle(trackId: number): Promise<boolean | null> {
|
||||
if (pendingIds.value.has(trackId)) return null;
|
||||
const next = !favoriteIds.value.has(trackId);
|
||||
pendingIds.value.add(trackId);
|
||||
try {
|
||||
const payload = { tracks: [{ rom_file_id: fileId, song }] };
|
||||
const payload = { track_ids: [trackId] };
|
||||
if (next) await musicApi.addFavorites(payload);
|
||||
else await musicApi.removeFavorites(payload);
|
||||
if (next) favoriteIds.value.add(key);
|
||||
else favoriteIds.value.delete(key);
|
||||
if (next) favoriteIds.value.add(trackId);
|
||||
else favoriteIds.value.delete(trackId);
|
||||
return next;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
pendingIds.value.delete(key);
|
||||
pendingIds.value.delete(trackId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ export interface SoundtrackSink {
|
||||
export interface PlayerTrack {
|
||||
romId: number;
|
||||
fileId: number;
|
||||
/** The track's own id; queues built without one (v1) go by file. */
|
||||
trackId?: number;
|
||||
/** The song within the file, for chiptune files that hold several. */
|
||||
song?: number;
|
||||
fileName: string;
|
||||
@@ -30,11 +32,11 @@ export interface PlayerTrack {
|
||||
m3uUrl?: string;
|
||||
}
|
||||
|
||||
/** A track's identity within a ROM: its file, plus the song for all but the first. */
|
||||
/** The key a queue entry's metadata is stored under. */
|
||||
export function playerTrackKey(
|
||||
track: Pick<PlayerTrack, "fileId" | "song">,
|
||||
track: Pick<PlayerTrack, "fileId" | "trackId">,
|
||||
): string {
|
||||
return track.song ? `${track.fileId}:${track.song}` : String(track.fileId);
|
||||
return track.trackId != null ? `t${track.trackId}` : String(track.fileId);
|
||||
}
|
||||
|
||||
function sameTrack(a: PlayerTrack, b: PlayerTrack): boolean {
|
||||
|
||||
@@ -158,6 +158,7 @@ function buildPlayerPayload(): {
|
||||
playerTracks.push({
|
||||
romId: track.romId,
|
||||
fileId: track.id,
|
||||
trackId: track.trackId,
|
||||
song: track.song,
|
||||
fileName: track.fileName,
|
||||
url: track.url,
|
||||
@@ -295,7 +296,8 @@ function onDelete(track: PanelTrack) {
|
||||
}
|
||||
|
||||
async function onToggleFavorite(track: PanelTrack) {
|
||||
const next = await favorites.toggle(track.id, track.song);
|
||||
if (track.trackId == null) return;
|
||||
const next = await favorites.toggle(track.trackId);
|
||||
if (next === null) {
|
||||
snackbar.error(t("common.soundtrack-favorite-failed"), {
|
||||
icon: "mdi-alert-circle-outline",
|
||||
@@ -487,7 +489,9 @@ function downloadTrack(track: PanelTrack) {
|
||||
activeTrackKey === (item as PanelTrack).key && isBuffering
|
||||
"
|
||||
:deletable="deletable"
|
||||
:favoritable="canEditPlaylists"
|
||||
:favoritable="
|
||||
canEditPlaylists && (item as PanelTrack).trackId != null
|
||||
"
|
||||
@select="selectTrack"
|
||||
@download="downloadTrack"
|
||||
@delete="onDelete"
|
||||
|
||||
@@ -29,11 +29,12 @@ const emit = defineEmits<{
|
||||
const { t } = useI18n();
|
||||
const favorites = useMusicFavorites();
|
||||
|
||||
const isFavorite = computed(() =>
|
||||
favorites.isFavorite(props.track.id, props.track.song),
|
||||
const isFavorite = computed(
|
||||
() =>
|
||||
props.track.trackId != null && favorites.isFavorite(props.track.trackId),
|
||||
);
|
||||
const isPending = computed(() =>
|
||||
favorites.isPending(props.track.id, props.track.song),
|
||||
const isPending = computed(
|
||||
() => props.track.trackId != null && favorites.isPending(props.track.trackId),
|
||||
);
|
||||
</script>
|
||||
|
||||
|
||||
@@ -84,16 +84,16 @@ describe("panelTracksFromRom", () => {
|
||||
|
||||
it("lists each song of a chiptune file, with its sidecar playlist", () => {
|
||||
const songs = [
|
||||
{ song: 0, title: "Intro", m3u_file_id: 2 },
|
||||
{ song: 1, title: null, track: 2, m3u_file_id: 2 },
|
||||
{ id: 11, song: 0, title: "Intro", m3u_file_id: 2 },
|
||||
{ id: 12, song: 1, title: null, track: 2, m3u_file_id: 2 },
|
||||
] as TrackMetaSchema[];
|
||||
const tracks = panelTracksFromRom(
|
||||
rom([romFile(1, "Game.nsf"), romFile(2, "Game.m3u")]),
|
||||
new Map([[1, songs]]),
|
||||
);
|
||||
expect(tracks.map((t) => [t.key, t.song, t.title])).toEqual([
|
||||
["1", 0, "Intro"],
|
||||
["1:1", 1, "Game #2"],
|
||||
expect(tracks.map((t) => [t.key, t.trackId, t.song, t.title])).toEqual([
|
||||
["t11", 11, 0, "Intro"],
|
||||
["t12", 12, 1, "Game #2"],
|
||||
]);
|
||||
expect(tracks[1].m3uUrl).toContain("Game.m3u");
|
||||
});
|
||||
|
||||
@@ -9,9 +9,11 @@ import { romFileUrl } from "@/v2/utils/romFiles";
|
||||
export interface PanelTrack {
|
||||
/** `rom_file_id`, shared by the songs of one file. */
|
||||
id: number;
|
||||
/** The track's own id, once its metadata has loaded. */
|
||||
trackId?: number;
|
||||
/** The song within the file; 0 unless the file holds several. */
|
||||
song: number;
|
||||
/** Identifies the track within its ROM, song included. */
|
||||
/** Identifies the track within its ROM (see `playerTrackKey`). */
|
||||
key: string;
|
||||
romId: number;
|
||||
fileName: string;
|
||||
@@ -112,11 +114,11 @@ export function panelTracksFromRom(
|
||||
.flatMap((file) => {
|
||||
const songs = songsByFileId.get(file.id);
|
||||
return (songs?.length ? songs : [undefined]).map((meta) => {
|
||||
const song = meta?.song ?? 0;
|
||||
return {
|
||||
id: file.id,
|
||||
song,
|
||||
key: playerTrackKey({ fileId: file.id, song }),
|
||||
trackId: meta?.id,
|
||||
song: meta?.song ?? 0,
|
||||
key: playerTrackKey({ fileId: file.id, trackId: meta?.id }),
|
||||
romId: rom.id,
|
||||
fileName: file.file_name,
|
||||
title: meta?.title ?? fallbackTitle(file.file_name, meta?.track),
|
||||
@@ -139,11 +141,11 @@ export function panelTracksFromCatalog(
|
||||
): PanelTrack[] {
|
||||
return tracks.map((track) => {
|
||||
const title = track.title || fallbackTitle(track.file_name, track.track);
|
||||
const song = track.song ?? 0;
|
||||
return {
|
||||
id: track.rom_file_id,
|
||||
song,
|
||||
key: playerTrackKey({ fileId: track.rom_file_id, song }),
|
||||
trackId: track.id,
|
||||
song: track.song ?? 0,
|
||||
key: playerTrackKey({ fileId: track.rom_file_id, trackId: track.id }),
|
||||
romId: track.rom_id,
|
||||
fileName: track.file_name,
|
||||
title,
|
||||
|
||||
Reference in New Issue
Block a user