feat(subsonic): browse by genre and by folder
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m47s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 3m59s
release / android (push) Successful in 4m30s
release / Build signed APK (push) Successful in 4m56s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 15s
release / Verify release artifacts (tag releases only) (push) Skipped
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m47s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 3m59s
release / android (push) Successful in 4m30s
release / Build signed APK (push) Successful in 4m56s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 15s
release / Verify release artifacts (tag releases only) (push) Skipped
Subsonic apps can now list genres and play one (getGenres, getSongsByGenre), and apps that browse by folder, such as DSub, can open an artist to its albums and an album to its songs (getMusicDirectory), with the album lists and search they use in that mode (getAlbumList, search2). Genres are split and counted as the web's genre index counts them, now with an album count beside the song count. A genre's songs leave out the listener's quarantined ones and missing files. Folders are Minstrel's artists and albums, under the same ids as the tag-based calls. getAlbumList2 and search3 now share their selection with the folder versions, so the two modes list and find the same things. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -113,7 +113,7 @@ Every image carries a signed Android app, all with the same key, so a phone can
|
|||||||
**Clients and accounts**
|
**Clients and accounts**
|
||||||
- A full web app, built into the server.
|
- A full web app, built into the server.
|
||||||
- A native Android app that ships inside the server image, keeps playing what it has cached when the server is out of reach, and updates itself from your server.
|
- A native Android app that ships inside the server image, keeps playing what it has cached when the server is out of reach, and updates itself from your server.
|
||||||
- OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse, search, play, like and scrobble, see the daily mixes and your playlists, and get Minstrel's smart shuffle and radio when they ask for random songs or similar songs.
|
- OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse by artist, album, genre or folder, search, play, like and scrobble, see the daily mixes and your playlists, and get Minstrel's smart shuffle and radio when they ask for random songs or similar songs.
|
||||||
- Separate accounts for each person, with invites, and an inbox for what happened while you were away.
|
- Separate accounts for each person, with invites, and an inbox for what happened while you were away.
|
||||||
|
|
||||||
## Scope and responsible use
|
## Scope and responsible use
|
||||||
|
|||||||
@@ -367,7 +367,8 @@ func (q *Queries) ListGenresForArtist(ctx context.Context, artistID pgtype.UUID)
|
|||||||
|
|
||||||
const listGenresWithCount = `-- name: ListGenresWithCount :many
|
const listGenresWithCount = `-- name: ListGenresWithCount :many
|
||||||
|
|
||||||
SELECT trim(g.genre) AS genre, COUNT(DISTINCT tracks.id)::bigint AS track_count
|
SELECT trim(g.genre) AS genre, COUNT(DISTINCT tracks.id)::bigint AS track_count,
|
||||||
|
COUNT(DISTINCT tracks.album_id)::bigint AS album_count
|
||||||
FROM tracks
|
FROM tracks
|
||||||
JOIN LATERAL regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre) ON true
|
JOIN LATERAL regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre) ON true
|
||||||
WHERE trim(g.genre) <> ''
|
WHERE trim(g.genre) <> ''
|
||||||
@@ -379,6 +380,7 @@ ORDER BY track_count DESC, trim(g.genre)
|
|||||||
type ListGenresWithCountRow struct {
|
type ListGenresWithCountRow struct {
|
||||||
Genre string
|
Genre string
|
||||||
TrackCount int64
|
TrackCount int64
|
||||||
|
AlbumCount int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// Every query in this file filters `tracks.missing_since IS NULL`. A row whose
|
// Every query in this file filters `tracks.missing_since IS NULL`. A row whose
|
||||||
@@ -417,6 +419,9 @@ type ListGenresWithCountRow struct {
|
|||||||
// Ordered by count first: raw ID3 data has a long tail of one-off junk tags,
|
// Ordered by count first: raw ID3 data has a long tail of one-off junk tags,
|
||||||
// so alphabetical would bury the handful of genres a library actually has
|
// so alphabetical would bury the handful of genres a library actually has
|
||||||
// a lot of. Name breaks ties for a stable order.
|
// a lot of. Name breaks ties for a stable order.
|
||||||
|
//
|
||||||
|
// album_count is the albums holding at least one of those tracks, which is
|
||||||
|
// what a Subsonic app shows beside the genre.
|
||||||
// Ordered by the expression, not the output alias: `ORDER BY genre` is
|
// Ordered by the expression, not the output alias: `ORDER BY genre` is
|
||||||
// ambiguous between the alias and tracks.genre, and sqlc rejects it.
|
// ambiguous between the alias and tracks.genre, and sqlc rejects it.
|
||||||
func (q *Queries) ListGenresWithCount(ctx context.Context) ([]ListGenresWithCountRow, error) {
|
func (q *Queries) ListGenresWithCount(ctx context.Context) ([]ListGenresWithCountRow, error) {
|
||||||
@@ -428,7 +433,96 @@ func (q *Queries) ListGenresWithCount(ctx context.Context) ([]ListGenresWithCoun
|
|||||||
var items []ListGenresWithCountRow
|
var items []ListGenresWithCountRow
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var i ListGenresWithCountRow
|
var i ListGenresWithCountRow
|
||||||
if err := rows.Scan(&i.Genre, &i.TrackCount); err != nil {
|
if err := rows.Scan(&i.Genre, &i.TrackCount, &i.AlbumCount); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const listTracksByGenre = `-- name: ListTracksByGenre :many
|
||||||
|
SELECT tracks.id, tracks.title, tracks.album_id, tracks.artist_id, tracks.track_number, tracks.disc_number, tracks.duration_ms, tracks.file_path, tracks.file_size, tracks.file_format, tracks.bitrate, tracks.mbid, tracks.genre, tracks.added_at, tracks.updated_at, tracks.tag_source, tracks.tag_sources_version, tracks.tag_read_version, tracks.missing_since, tracks.mbid_source, tracks.song_id, tracks.song_key, tracks.source_verdict, tracks.source_verdict_at, tracks.emptied_at, tracks.removed_reason, tracks.removed_by, tracks.artist_credit
|
||||||
|
FROM tracks
|
||||||
|
JOIN albums ON albums.id = tracks.album_id
|
||||||
|
WHERE tracks.missing_since IS NULL
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre)
|
||||||
|
WHERE trim(g.genre) = trim($1::text)
|
||||||
|
)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM quarantine q
|
||||||
|
WHERE q.user_id = $2 AND q.track_id = tracks.id
|
||||||
|
)
|
||||||
|
ORDER BY albums.sort_title, albums.id,
|
||||||
|
tracks.disc_number NULLS FIRST, tracks.track_number NULLS FIRST, tracks.id
|
||||||
|
LIMIT $4 OFFSET $3
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListTracksByGenreParams struct {
|
||||||
|
Genre string
|
||||||
|
UserID pgtype.UUID
|
||||||
|
Off int32
|
||||||
|
Lim int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListTracksByGenreRow struct {
|
||||||
|
Track Track
|
||||||
|
}
|
||||||
|
|
||||||
|
// One genre's songs for the Subsonic getSongsByGenre, a page at a time.
|
||||||
|
// Splits and trims identically to ListGenresWithCount, so the songs a genre
|
||||||
|
// leads to are the ones it counted. The listener's quarantined tracks are
|
||||||
|
// left out: an app asks for these to play them. Album by album in track
|
||||||
|
// order, so paging walks a stable order.
|
||||||
|
func (q *Queries) ListTracksByGenre(ctx context.Context, arg ListTracksByGenreParams) ([]ListTracksByGenreRow, error) {
|
||||||
|
rows, err := q.db.Query(ctx, listTracksByGenre,
|
||||||
|
arg.Genre,
|
||||||
|
arg.UserID,
|
||||||
|
arg.Off,
|
||||||
|
arg.Lim,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []ListTracksByGenreRow
|
||||||
|
for rows.Next() {
|
||||||
|
var i ListTracksByGenreRow
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.Track.ID,
|
||||||
|
&i.Track.Title,
|
||||||
|
&i.Track.AlbumID,
|
||||||
|
&i.Track.ArtistID,
|
||||||
|
&i.Track.TrackNumber,
|
||||||
|
&i.Track.DiscNumber,
|
||||||
|
&i.Track.DurationMs,
|
||||||
|
&i.Track.FilePath,
|
||||||
|
&i.Track.FileSize,
|
||||||
|
&i.Track.FileFormat,
|
||||||
|
&i.Track.Bitrate,
|
||||||
|
&i.Track.Mbid,
|
||||||
|
&i.Track.Genre,
|
||||||
|
&i.Track.AddedAt,
|
||||||
|
&i.Track.UpdatedAt,
|
||||||
|
&i.Track.TagSource,
|
||||||
|
&i.Track.TagSourcesVersion,
|
||||||
|
&i.Track.TagReadVersion,
|
||||||
|
&i.Track.MissingSince,
|
||||||
|
&i.Track.MbidSource,
|
||||||
|
&i.Track.SongID,
|
||||||
|
&i.Track.SongKey,
|
||||||
|
&i.Track.SourceVerdict,
|
||||||
|
&i.Track.SourceVerdictAt,
|
||||||
|
&i.Track.EmptiedAt,
|
||||||
|
&i.Track.RemovedReason,
|
||||||
|
&i.Track.RemovedBy,
|
||||||
|
&i.Track.ArtistCredit,
|
||||||
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
items = append(items, i)
|
items = append(items, i)
|
||||||
|
|||||||
@@ -36,7 +36,11 @@
|
|||||||
-- Ordered by count first: raw ID3 data has a long tail of one-off junk tags,
|
-- Ordered by count first: raw ID3 data has a long tail of one-off junk tags,
|
||||||
-- so alphabetical would bury the handful of genres a library actually has
|
-- so alphabetical would bury the handful of genres a library actually has
|
||||||
-- a lot of. Name breaks ties for a stable order.
|
-- a lot of. Name breaks ties for a stable order.
|
||||||
SELECT trim(g.genre) AS genre, COUNT(DISTINCT tracks.id)::bigint AS track_count
|
--
|
||||||
|
-- album_count is the albums holding at least one of those tracks, which is
|
||||||
|
-- what a Subsonic app shows beside the genre.
|
||||||
|
SELECT trim(g.genre) AS genre, COUNT(DISTINCT tracks.id)::bigint AS track_count,
|
||||||
|
COUNT(DISTINCT tracks.album_id)::bigint AS album_count
|
||||||
FROM tracks
|
FROM tracks
|
||||||
JOIN LATERAL regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre) ON true
|
JOIN LATERAL regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre) ON true
|
||||||
WHERE trim(g.genre) <> ''
|
WHERE trim(g.genre) <> ''
|
||||||
@@ -66,6 +70,29 @@ WHERE EXISTS (
|
|||||||
ORDER BY albums.sort_title, albums.id
|
ORDER BY albums.sort_title, albums.id
|
||||||
LIMIT sqlc.arg(lim) OFFSET sqlc.arg(off);
|
LIMIT sqlc.arg(lim) OFFSET sqlc.arg(off);
|
||||||
|
|
||||||
|
-- name: ListTracksByGenre :many
|
||||||
|
-- One genre's songs for the Subsonic getSongsByGenre, a page at a time.
|
||||||
|
-- Splits and trims identically to ListGenresWithCount, so the songs a genre
|
||||||
|
-- leads to are the ones it counted. The listener's quarantined tracks are
|
||||||
|
-- left out: an app asks for these to play them. Album by album in track
|
||||||
|
-- order, so paging walks a stable order.
|
||||||
|
SELECT sqlc.embed(tracks)
|
||||||
|
FROM tracks
|
||||||
|
JOIN albums ON albums.id = tracks.album_id
|
||||||
|
WHERE tracks.missing_since IS NULL
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM regexp_split_to_table(coalesce(tracks.genre, ''), '[;,]') AS g(genre)
|
||||||
|
WHERE trim(g.genre) = trim(sqlc.arg(genre)::text)
|
||||||
|
)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM quarantine q
|
||||||
|
WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = tracks.id
|
||||||
|
)
|
||||||
|
ORDER BY albums.sort_title, albums.id,
|
||||||
|
tracks.disc_number NULLS FIRST, tracks.track_number NULLS FIRST, tracks.id
|
||||||
|
LIMIT sqlc.arg(lim) OFFSET sqlc.arg(off);
|
||||||
|
|
||||||
-- name: CountAlbumsByGenre :one
|
-- name: CountAlbumsByGenre :one
|
||||||
-- Total for the paging envelope. EXISTS mirrors the list query exactly; a
|
-- Total for the paging envelope. EXISTS mirrors the list query exactly; a
|
||||||
-- JOIN + DISTINCT here would count differently the moment an album has two
|
-- JOIN + DISTINCT here would count differently the moment an album has two
|
||||||
|
|||||||
+99
-66
@@ -181,26 +181,36 @@ func (b *browseHandlers) getAlbum(w http.ResponseWriter, r *http.Request) {
|
|||||||
WriteFail(w, r, ErrGeneric, "Failed to load album artist")
|
WriteFail(w, r, ErrGeneric, "Failed to load album artist")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
tracks, err := q.ListTracksByAlbum(r.Context(), dbq.ListTracksByAlbumParams{AlbumID: id})
|
songs, err := albumSongs(r.Context(), q, album, artist.Name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
WriteFail(w, r, ErrGeneric, "Failed to load tracks")
|
WriteFail(w, r, ErrGeneric, "Failed to load tracks")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
gains := replayGains(r.Context(), q, tracks)
|
|
||||||
// Each song is credited to its own artist: on a compilation or a track
|
|
||||||
// with a guest, that is not the album's. A failed lookup credits the
|
|
||||||
// album's artist rather than failing the album.
|
|
||||||
names, _ := db.TrackArtistNames(r.Context(), q, album.ID)
|
|
||||||
songs := make([]SongRef, 0, len(tracks))
|
|
||||||
for _, t := range tracks {
|
|
||||||
songs = append(songs, songRef(t, album.Title, names.For(t.ArtistID, artist.Name), gains[t.ID]))
|
|
||||||
}
|
|
||||||
Write(w, r, AlbumResponse{
|
Write(w, r, AlbumResponse{
|
||||||
Envelope: NewEnvelope("ok"),
|
Envelope: NewEnvelope("ok"),
|
||||||
Album: albumDetail(album, artist.Name, songs),
|
Album: albumDetail(album, artist.Name, songs),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// albumSongs is an album's songs in disc and track order, as getAlbum and
|
||||||
|
// getMusicDirectory both list them.
|
||||||
|
func albumSongs(ctx context.Context, q *dbq.Queries, album dbq.Album, artistName string) ([]SongRef, error) {
|
||||||
|
tracks, err := q.ListTracksByAlbum(ctx, dbq.ListTracksByAlbumParams{AlbumID: album.ID})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
gains := replayGains(ctx, q, tracks)
|
||||||
|
// Each song is credited to its own artist: on a compilation or a track
|
||||||
|
// with a guest, that is not the album's. A failed lookup credits the
|
||||||
|
// album's artist rather than failing the album.
|
||||||
|
names, _ := db.TrackArtistNames(ctx, q, album.ID)
|
||||||
|
songs := make([]SongRef, 0, len(tracks))
|
||||||
|
for _, t := range tracks {
|
||||||
|
songs = append(songs, songRef(t, album.Title, names.For(t.ArtistID, artistName), gains[t.ID]))
|
||||||
|
}
|
||||||
|
return songs, nil
|
||||||
|
}
|
||||||
|
|
||||||
// getSong returns a single track by id. Parent metadata (album/artist name)
|
// getSong returns a single track by id. Parent metadata (album/artist name)
|
||||||
// is included so clients can render the song outside an album context.
|
// is included so clients can render the song outside an album context.
|
||||||
func (b *browseHandlers) getSong(w http.ResponseWriter, r *http.Request) {
|
func (b *browseHandlers) getSong(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -240,17 +250,36 @@ func (b *browseHandlers) getSong(w http.ResponseWriter, r *http.Request) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// getAlbumList2 returns a paged album list filtered by type. Supported types
|
// getAlbumList2 returns a paged album list filtered by type (listAlbums).
|
||||||
// match the Subsonic spec § getAlbumList2. "recent" and "frequent" read the
|
|
||||||
// caller's own play history: most recently played first, and most played
|
|
||||||
// first. "starred" and "highest" are both the caller's liked albums, newest
|
|
||||||
// like first: a like is the only rating Minstrel keeps.
|
|
||||||
func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
|
func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
|
||||||
|
q := dbq.New(b.pool)
|
||||||
|
albums, ok := b.listAlbums(w, r, q)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
refs, err := b.albumRefs(r.Context(), q, albums)
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to resolve albums")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Write(w, r, AlbumList2Response{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
AlbumList2: AlbumList2Container{Albums: refs},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// listAlbums is the page of albums getAlbumList and getAlbumList2 ask for,
|
||||||
|
// or false once it has written the failure. Supported types match the
|
||||||
|
// Subsonic spec § getAlbumList2. "recent" and "frequent" read the caller's
|
||||||
|
// own play history: most recently played first, and most played first.
|
||||||
|
// "starred" and "highest" are both the caller's liked albums, newest like
|
||||||
|
// first: a like is the only rating Minstrel keeps.
|
||||||
|
func (b *browseHandlers) listAlbums(w http.ResponseWriter, r *http.Request, q *dbq.Queries) ([]dbq.Album, bool) {
|
||||||
params := r.URL.Query()
|
params := r.URL.Query()
|
||||||
listType := params.Get("type")
|
listType := params.Get("type")
|
||||||
if listType == "" {
|
if listType == "" {
|
||||||
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: type")
|
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: type")
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
size := clampInt(atoiDefault(params.Get("size"), 10), 1, 500)
|
size := clampInt(atoiDefault(params.Get("size"), 10), 1, 500)
|
||||||
offset := atoiDefault(params.Get("offset"), 0)
|
offset := atoiDefault(params.Get("offset"), 0)
|
||||||
@@ -258,7 +287,6 @@ func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
|
|||||||
offset = 0
|
offset = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
q := dbq.New(b.pool)
|
|
||||||
var albums []dbq.Album
|
var albums []dbq.Album
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
@@ -289,7 +317,7 @@ func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
|
|||||||
genre := params.Get("genre")
|
genre := params.Get("genre")
|
||||||
if genre == "" {
|
if genre == "" {
|
||||||
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: genre")
|
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: genre")
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
// The query splits tracks.genre on [;,] rather than comparing the
|
// The query splits tracks.genre on [;,] rather than comparing the
|
||||||
// whole column, so a client asking for "Rock" also reaches tracks
|
// whole column, so a client asking for "Rock" also reaches tracks
|
||||||
@@ -302,7 +330,7 @@ func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
|
|||||||
to, terr := strconv.Atoi(params.Get("toYear"))
|
to, terr := strconv.Atoi(params.Get("toYear"))
|
||||||
if ferr != nil || terr != nil {
|
if ferr != nil || terr != nil {
|
||||||
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: fromYear and toYear")
|
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: fromYear and toYear")
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
albums, err = q.ListAlbumsByYearOrdered(r.Context(), dbq.ListAlbumsByYearOrderedParams{
|
albums, err = q.ListAlbumsByYearOrdered(r.Context(), dbq.ListAlbumsByYearOrderedParams{
|
||||||
FromYear: int32(from), ToYear: int32(to), Lim: int32(size), Off: int32(offset),
|
FromYear: int32(from), ToYear: int32(to), Lim: int32(size), Off: int32(offset),
|
||||||
@@ -311,7 +339,7 @@ func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
|
|||||||
user, ok := UserFromContext(r.Context())
|
user, ok := UserFromContext(r.Context())
|
||||||
if !ok {
|
if !ok {
|
||||||
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
albums, err = q.ListLikedAlbumRows(r.Context(), dbq.ListLikedAlbumRowsParams{
|
albums, err = q.ListLikedAlbumRows(r.Context(), dbq.ListLikedAlbumRowsParams{
|
||||||
UserID: user.ID, Limit: int32(size), Offset: int32(offset),
|
UserID: user.ID, Limit: int32(size), Offset: int32(offset),
|
||||||
@@ -320,7 +348,7 @@ func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
|
|||||||
user, ok := UserFromContext(r.Context())
|
user, ok := UserFromContext(r.Context())
|
||||||
if !ok {
|
if !ok {
|
||||||
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
if listType == "recent" {
|
if listType == "recent" {
|
||||||
albums, err = q.ListAlbumsRecentlyPlayedByUser(r.Context(), dbq.ListAlbumsRecentlyPlayedByUserParams{
|
albums, err = q.ListAlbumsRecentlyPlayedByUser(r.Context(), dbq.ListAlbumsRecentlyPlayedByUserParams{
|
||||||
@@ -333,37 +361,59 @@ func (b *browseHandlers) getAlbumList2(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
WriteFail(w, r, ErrGeneric, "Invalid list type: "+listType)
|
WriteFail(w, r, ErrGeneric, "Invalid list type: "+listType)
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
WriteFail(w, r, ErrGeneric, "Failed to list albums")
|
WriteFail(w, r, ErrGeneric, "Failed to list albums")
|
||||||
return
|
return nil, false
|
||||||
}
|
}
|
||||||
|
return albums, true
|
||||||
refs, err := b.albumRefs(r.Context(), q, albums)
|
|
||||||
if err != nil {
|
|
||||||
WriteFail(w, r, ErrGeneric, "Failed to resolve albums")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
Write(w, r, AlbumList2Response{
|
|
||||||
Envelope: NewEnvelope("ok"),
|
|
||||||
AlbumList2: AlbumList2Container{Albums: refs},
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// search3 runs three independent searches — artist name, album title, song
|
// search3 runs three independent searches — artist name, album title, song
|
||||||
// title — each bounded by its own count/offset. The Subsonic spec lets the
|
// title — each bounded by its own count/offset (search).
|
||||||
// caller page each facet separately, which is why the params triplicate.
|
func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
|
||||||
|
q := dbq.New(b.pool)
|
||||||
|
hits, ok := b.search(w, r, q)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
albums, err := b.albumRefs(r.Context(), q, hits.albums)
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Album search failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Write(w, r, SearchResult3Response{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
SearchResult3: SearchResult3Container{
|
||||||
|
Artists: hits.artists,
|
||||||
|
Albums: albums,
|
||||||
|
Songs: hits.songs,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// searchHits is what one search found, before its albums are rendered as
|
||||||
|
// ID3 albums (search3) or as folders (search2).
|
||||||
|
type searchHits struct {
|
||||||
|
artists []ArtistRef
|
||||||
|
albums []dbq.Album
|
||||||
|
songs []SongRef
|
||||||
|
}
|
||||||
|
|
||||||
|
// search runs the three searches search2 and search3 share, or returns false
|
||||||
|
// once it has written the failure. The Subsonic spec lets the caller page
|
||||||
|
// each facet separately, which is why the params triplicate.
|
||||||
//
|
//
|
||||||
// An empty query matches everything, paged in a stable order. Apps that keep
|
// An empty query matches everything, paged in a stable order. Apps that keep
|
||||||
// a copy of the library (Symfonium) download it this way, a page of songs at
|
// a copy of the library (Symfonium) download it this way, a page of songs at
|
||||||
// a time; refusing it leaves them a request per album or an empty library.
|
// a time; refusing it leaves them a request per album or an empty library.
|
||||||
// Some send the empty query as two quote marks.
|
// Some send the empty query as two quote marks.
|
||||||
func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
|
func (b *browseHandlers) search(w http.ResponseWriter, r *http.Request, q *dbq.Queries) (searchHits, bool) {
|
||||||
params := r.URL.Query()
|
params := r.URL.Query()
|
||||||
if !params.Has("query") {
|
if !params.Has("query") {
|
||||||
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: query")
|
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: query")
|
||||||
return
|
return searchHits{}, false
|
||||||
}
|
}
|
||||||
query := strings.TrimSpace(params.Get("query"))
|
query := strings.TrimSpace(params.Get("query"))
|
||||||
if query == `""` {
|
if query == `""` {
|
||||||
@@ -376,18 +426,13 @@ func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
|
|||||||
songCount := clampInt(atoiDefault(params.Get("songCount"), 20), 0, 500)
|
songCount := clampInt(atoiDefault(params.Get("songCount"), 20), 0, 500)
|
||||||
songOffset := atoiDefault(params.Get("songOffset"), 0)
|
songOffset := atoiDefault(params.Get("songOffset"), 0)
|
||||||
|
|
||||||
q := dbq.New(b.pool)
|
|
||||||
// The query goes through ILIKE '%' || query || '%', so it matches
|
// The query goes through ILIKE '%' || query || '%', so it matches
|
||||||
// substrings, and an empty query matches every row.
|
// substrings, and an empty query matches every row.
|
||||||
needle := &query
|
needle := &query
|
||||||
|
|
||||||
// JSON marshaling of nil slices produces `null`, which some clients reject.
|
// JSON marshaling of nil slices produces `null`, which some clients reject.
|
||||||
// Initialize each facet to an empty slice so absent matches render as `[]`.
|
// Initialize each facet to an empty slice so absent matches render as `[]`.
|
||||||
result := SearchResult3Container{
|
hits := searchHits{artists: []ArtistRef{}, songs: []SongRef{}}
|
||||||
Artists: []ArtistRef{},
|
|
||||||
Albums: []AlbumRef{},
|
|
||||||
Songs: []SongRef{},
|
|
||||||
}
|
|
||||||
|
|
||||||
if artistCount > 0 {
|
if artistCount > 0 {
|
||||||
artists, err := q.SearchArtists(r.Context(), dbq.SearchArtistsParams{
|
artists, err := q.SearchArtists(r.Context(), dbq.SearchArtistsParams{
|
||||||
@@ -395,15 +440,15 @@ func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
WriteFail(w, r, ErrGeneric, "Artist search failed")
|
WriteFail(w, r, ErrGeneric, "Artist search failed")
|
||||||
return
|
return searchHits{}, false
|
||||||
}
|
}
|
||||||
for _, a := range artists {
|
for _, a := range artists {
|
||||||
albums, aerr := q.ListAlbumsByArtist(r.Context(), a.ID)
|
albums, aerr := q.ListAlbumsByArtist(r.Context(), a.ID)
|
||||||
if aerr != nil {
|
if aerr != nil {
|
||||||
WriteFail(w, r, ErrGeneric, "Artist search failed")
|
WriteFail(w, r, ErrGeneric, "Artist search failed")
|
||||||
return
|
return searchHits{}, false
|
||||||
}
|
}
|
||||||
result.Artists = append(result.Artists, artistRef(a, len(albums)))
|
hits.artists = append(hits.artists, artistRef(a, len(albums)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -413,14 +458,9 @@ func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
WriteFail(w, r, ErrGeneric, "Album search failed")
|
WriteFail(w, r, ErrGeneric, "Album search failed")
|
||||||
return
|
return searchHits{}, false
|
||||||
}
|
}
|
||||||
refs, rerr := b.albumRefs(r.Context(), q, albums)
|
hits.albums = albums
|
||||||
if rerr != nil {
|
|
||||||
WriteFail(w, r, ErrGeneric, "Album search failed")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
result.Albums = refs
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if songCount > 0 {
|
if songCount > 0 {
|
||||||
@@ -429,25 +469,18 @@ func (b *browseHandlers) search3(w http.ResponseWriter, r *http.Request) {
|
|||||||
}) // UserID left zero (NULL) — Subsonic has no per-user quarantine context
|
}) // UserID left zero (NULL) — Subsonic has no per-user quarantine context
|
||||||
if err != nil {
|
if err != nil {
|
||||||
WriteFail(w, r, ErrGeneric, "Song search failed")
|
WriteFail(w, r, ErrGeneric, "Song search failed")
|
||||||
return
|
return searchHits{}, false
|
||||||
}
|
}
|
||||||
gains := replayGains(r.Context(), q, tracks)
|
|
||||||
// One query each for the page's albums and artists, not two per
|
// One query each for the page's albums and artists, not two per
|
||||||
// song: a library download asks for every song in pages of 500.
|
// song: a library download asks for every song in pages of 500.
|
||||||
albumTitles, artistNames, perr := songParents(r.Context(), q, tracks)
|
songs, serr := songRefs(r.Context(), q, tracks)
|
||||||
if perr != nil {
|
if serr != nil {
|
||||||
WriteFail(w, r, ErrGeneric, "Song search failed")
|
WriteFail(w, r, ErrGeneric, "Song search failed")
|
||||||
return
|
return searchHits{}, false
|
||||||
}
|
|
||||||
for _, t := range tracks {
|
|
||||||
result.Songs = append(result.Songs, songRef(t, albumTitles[t.AlbumID], artistNames[t.ArtistID], gains[t.ID]))
|
|
||||||
}
|
}
|
||||||
|
hits.songs = songs
|
||||||
}
|
}
|
||||||
|
return hits, true
|
||||||
Write(w, r, SearchResult3Response{
|
|
||||||
Envelope: NewEnvelope("ok"),
|
|
||||||
SearchResult3: result,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// songParents reads the album titles and artist names of tracks, in one
|
// songParents reads the album titles and artist names of tracks, in one
|
||||||
|
|||||||
@@ -0,0 +1,199 @@
|
|||||||
|
package subsonic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
|
|
||||||
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Folder browsing is the older half of the Subsonic API, which apps such as
|
||||||
|
// DSub use unless told to browse by tags. Its folders are Minstrel's artists
|
||||||
|
// and albums, not directories on disk: getIndexes lists the artists,
|
||||||
|
// getMusicDirectory opens an artist to its albums and an album to its songs,
|
||||||
|
// and getAlbumList and search2 show albums as folders to open. The ids are
|
||||||
|
// the same as the ID3 calls use, so starring, streaming and cover art take
|
||||||
|
// them unchanged.
|
||||||
|
|
||||||
|
// Directory is the body of getMusicDirectory.
|
||||||
|
type Directory struct {
|
||||||
|
ID string `json:"id" xml:"id,attr"`
|
||||||
|
Parent string `json:"parent,omitempty" xml:"parent,attr,omitempty"`
|
||||||
|
Name string `json:"name" xml:"name,attr"`
|
||||||
|
Children []SongRef `json:"child" xml:"child"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type DirectoryResponse struct {
|
||||||
|
Envelope
|
||||||
|
Directory Directory `json:"directory" xml:"directory"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AlbumListContainer is the body of getAlbumList: albums as folders.
|
||||||
|
type AlbumListContainer struct {
|
||||||
|
Albums []SongRef `json:"album" xml:"album"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AlbumListResponse struct {
|
||||||
|
Envelope
|
||||||
|
AlbumList AlbumListContainer `json:"albumList" xml:"albumList"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SearchResult2Container is the body of search2: search3's hits, with the
|
||||||
|
// albums as folders.
|
||||||
|
type SearchResult2Container struct {
|
||||||
|
Artists []ArtistRef `json:"artist" xml:"artist"`
|
||||||
|
Albums []SongRef `json:"album" xml:"album"`
|
||||||
|
Songs []SongRef `json:"song" xml:"song"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SearchResult2Response struct {
|
||||||
|
Envelope
|
||||||
|
SearchResult2 SearchResult2Container `json:"searchResult2" xml:"searchResult2"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// albumFolder is an album as a folder inside its artist's.
|
||||||
|
func albumFolder(a dbq.Album, artistName string) SongRef {
|
||||||
|
return SongRef{
|
||||||
|
ID: uuidToID(a.ID),
|
||||||
|
Parent: uuidToID(a.ArtistID),
|
||||||
|
Title: a.Title,
|
||||||
|
Album: a.Title,
|
||||||
|
AlbumID: uuidToID(a.ID),
|
||||||
|
Artist: artistName,
|
||||||
|
ArtistID: uuidToID(a.ArtistID),
|
||||||
|
CoverArt: coverArtID(a),
|
||||||
|
Year: yearFromDate(a.ReleaseDate),
|
||||||
|
Created: timestamptzToRFC3339(a.CreatedAt),
|
||||||
|
IsDir: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// albumFolders renders albums as folders, each under its own artist.
|
||||||
|
func albumFolders(ctx context.Context, q *dbq.Queries, albums []dbq.Album) ([]SongRef, error) {
|
||||||
|
out := make([]SongRef, 0, len(albums))
|
||||||
|
if len(albums) == 0 {
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
ids := make([]pgtype.UUID, 0, len(albums))
|
||||||
|
for _, a := range albums {
|
||||||
|
ids = append(ids, a.ArtistID)
|
||||||
|
}
|
||||||
|
names, err := resolveArtistNames(ctx, q, ids)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, a := range albums {
|
||||||
|
out = append(out, albumFolder(a, names[uuidToID(a.ArtistID)]))
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// getMusicDirectory opens a folder: an artist id gives the artist's albums,
|
||||||
|
// an album id gives the album's songs.
|
||||||
|
func (b *browseHandlers) getMusicDirectory(w http.ResponseWriter, r *http.Request) {
|
||||||
|
idStr := r.URL.Query().Get("id")
|
||||||
|
if idStr == "" {
|
||||||
|
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, ok := parseUUID(idStr)
|
||||||
|
if !ok {
|
||||||
|
WriteFail(w, r, ErrDataNotFound, "Directory not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
q := dbq.New(b.pool)
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
artist, err := q.GetArtistByID(ctx, id)
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
albums, err := q.ListAlbumsByArtist(ctx, artist.ID)
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to load albums")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
children := make([]SongRef, 0, len(albums))
|
||||||
|
for _, a := range albums {
|
||||||
|
children = append(children, albumFolder(a, artist.Name))
|
||||||
|
}
|
||||||
|
Write(w, r, DirectoryResponse{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
Directory: Directory{ID: uuidToID(artist.ID), Name: artist.Name, Children: children},
|
||||||
|
})
|
||||||
|
return
|
||||||
|
case !errors.Is(err, pgx.ErrNoRows):
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to load directory")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
album, err := q.GetAlbumByID(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
WriteFail(w, r, ErrDataNotFound, "Directory not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to load directory")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
albumArtist, err := q.GetArtistByID(ctx, album.ArtistID)
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to load album artist")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
songs, err := albumSongs(ctx, q, album, albumArtist.Name)
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to load tracks")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Write(w, r, DirectoryResponse{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
Directory: Directory{
|
||||||
|
ID: uuidToID(album.ID), Parent: uuidToID(album.ArtistID), Name: album.Title, Children: songs,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// getAlbumList is getAlbumList2 with the albums as folders: the same list
|
||||||
|
// types, paged the same way (listAlbums).
|
||||||
|
func (b *browseHandlers) getAlbumList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
q := dbq.New(b.pool)
|
||||||
|
albums, ok := b.listAlbums(w, r, q)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
folders, err := albumFolders(r.Context(), q, albums)
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to resolve albums")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Write(w, r, AlbumListResponse{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
AlbumList: AlbumListContainer{Albums: folders},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// search2 is search3 with the albums as folders (search).
|
||||||
|
func (b *browseHandlers) search2(w http.ResponseWriter, r *http.Request) {
|
||||||
|
q := dbq.New(b.pool)
|
||||||
|
hits, ok := b.search(w, r, q)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
albums, err := albumFolders(r.Context(), q, hits.albums)
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Album search failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Write(w, r, SearchResult2Response{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
SearchResult2: SearchResult2Container{
|
||||||
|
Artists: hits.artists,
|
||||||
|
Albums: albums,
|
||||||
|
Songs: hits.songs,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
package subsonic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/xml"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The XML forms an app reads: a genre's name is the element's text, and a
|
||||||
|
// folder's entries are <child> elements.
|
||||||
|
func TestGenreAndDirectoryXML(t *testing.T) {
|
||||||
|
out, err := xml.Marshal(GenresResponse{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
Genres: GenresContainer{Genres: []Genre{{Value: "Jazz", SongCount: 3, AlbumCount: 2}}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal genres: %v", err)
|
||||||
|
}
|
||||||
|
if want := `<genres><genre songCount="3" albumCount="2">Jazz</genre></genres>`; !strings.Contains(string(out), want) {
|
||||||
|
t.Errorf("genres XML = %s, want it to hold %s", out, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err = xml.Marshal(DirectoryResponse{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
Directory: Directory{ID: "a", Name: "Tin Orchard", Children: []SongRef{
|
||||||
|
{ID: "b", Parent: "a", Title: "Paper Boats", IsDir: true},
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal directory: %v", err)
|
||||||
|
}
|
||||||
|
if want := `<directory id="a" name="Tin Orchard"><child id="b" parent="a" title="Paper Boats" isDir="true"></child></directory>`; !strings.Contains(string(out), want) {
|
||||||
|
t.Errorf("directory XML = %s, want it to hold %s", out, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f picksFixture) browse() *browseHandlers { return &browseHandlers{pool: f.pool} }
|
||||||
|
|
||||||
|
// A tag of several genres counts toward each; the missing file counts toward
|
||||||
|
// none; the genres with the most songs come first, then by name.
|
||||||
|
func TestGetGenres_CountsEachGenreOfASplitTag(t *testing.T) {
|
||||||
|
f := seedPicks(t)
|
||||||
|
var got struct {
|
||||||
|
Genres GenresContainer `json:"genres"`
|
||||||
|
}
|
||||||
|
if code := call(t, f.browse().getGenres, f.user, "", &got); code != 0 {
|
||||||
|
t.Fatalf("getGenres: error %d", code)
|
||||||
|
}
|
||||||
|
want := []Genre{
|
||||||
|
{Value: "Jazz", SongCount: 3, AlbumCount: 2},
|
||||||
|
{Value: "Rock", SongCount: 3, AlbumCount: 2},
|
||||||
|
{Value: "Funk", SongCount: 1, AlbumCount: 1},
|
||||||
|
}
|
||||||
|
if !slices.Equal(got.Genres.Genres, want) {
|
||||||
|
t.Errorf("genres = %+v, want %+v", got.Genres.Genres, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f picksFixture) songsByGenre(t *testing.T, query string) ([]string, int) {
|
||||||
|
t.Helper()
|
||||||
|
var got struct {
|
||||||
|
SongsByGenre struct {
|
||||||
|
Songs *[]SongRef `json:"song"`
|
||||||
|
} `json:"songsByGenre"`
|
||||||
|
}
|
||||||
|
code := call(t, f.browse().getSongsByGenre, f.user, query, &got)
|
||||||
|
if code != 0 {
|
||||||
|
return nil, code
|
||||||
|
}
|
||||||
|
if got.SongsByGenre.Songs == nil {
|
||||||
|
t.Fatalf("getSongsByGenre %s: song is null or absent, want a list", query)
|
||||||
|
}
|
||||||
|
return titles(*got.SongsByGenre.Songs), 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// A genre's songs are its playable ones, without the listener's quarantined
|
||||||
|
// song, album by album in track order, a page at a time.
|
||||||
|
func TestGetSongsByGenre_PagesTheGenresPlayableSongs(t *testing.T) {
|
||||||
|
f := seedPicks(t)
|
||||||
|
cases := []struct {
|
||||||
|
query string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"genre=Jazz", []string{"Dusk", "Harbour"}},
|
||||||
|
{"genre=Rock", []string{"Flint", "Gale", "Inlet"}},
|
||||||
|
{"genre=Rock&count=2&offset=1", []string{"Gale", "Inlet"}},
|
||||||
|
// Ember is the only Funk song, and the listener quarantined it.
|
||||||
|
{"genre=Funk", []string{}},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
got, code := f.songsByGenre(t, c.query)
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("%s: error %d", c.query, code)
|
||||||
|
}
|
||||||
|
if !slices.Equal(got, c.want) {
|
||||||
|
t.Errorf("%s = %v, want %v", c.query, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, code := f.songsByGenre(t, ""); code != ErrMissingParameter {
|
||||||
|
t.Errorf("no genre: code %d, want %d", code, ErrMissingParameter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f picksFixture) directory(t *testing.T, id string) (Directory, int) {
|
||||||
|
t.Helper()
|
||||||
|
var got struct {
|
||||||
|
Directory Directory `json:"directory"`
|
||||||
|
}
|
||||||
|
code := call(t, f.browse().getMusicDirectory, f.user, "id="+id, &got)
|
||||||
|
return got.Directory, code
|
||||||
|
}
|
||||||
|
|
||||||
|
// An artist's folder holds its albums as folders; an album's holds its songs.
|
||||||
|
func TestGetMusicDirectory_OpensAnArtistToAlbumsAndAnAlbumToSongs(t *testing.T) {
|
||||||
|
f := seedPicks(t)
|
||||||
|
artistID := uuidToID(f.artist.ID)
|
||||||
|
|
||||||
|
dir, code := f.directory(t, artistID)
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("artist folder: error %d", code)
|
||||||
|
}
|
||||||
|
if dir.ID != artistID || dir.Name != "Tin Orchard" {
|
||||||
|
t.Errorf("artist folder = %q %q, want %q Tin Orchard", dir.ID, dir.Name, artistID)
|
||||||
|
}
|
||||||
|
// By release date, then title, as getArtist lists them.
|
||||||
|
if got, want := titles(dir.Children), []string{"Lantern Hours", "Gone Tide", "Paper Boats"}; !slices.Equal(got, want) {
|
||||||
|
t.Errorf("artist folder holds %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
for _, c := range dir.Children {
|
||||||
|
if !c.IsDir || c.Parent != artistID || c.Type != "" {
|
||||||
|
t.Errorf("album %s: isDir=%v parent=%q type=%q, want a folder under the artist", c.Title, c.IsDir, c.Parent, c.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
paper := uuidToID(f.albums["Paper Boats"].ID)
|
||||||
|
if dir.Children[2].ID != paper || dir.Children[2].Year != 2012 {
|
||||||
|
t.Errorf("Paper Boats folder = %+v, want id %s and year 2012", dir.Children[2], paper)
|
||||||
|
}
|
||||||
|
dir, code = f.directory(t, paper)
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("album folder: error %d", code)
|
||||||
|
}
|
||||||
|
if dir.ID != paper || dir.Parent != artistID || dir.Name != "Paper Boats" {
|
||||||
|
t.Errorf("album folder = %q parent %q %q, want %q under %q", dir.ID, dir.Parent, dir.Name, paper, artistID)
|
||||||
|
}
|
||||||
|
if got, want := titles(dir.Children), []string{"Gale", "Harbour", "Inlet"}; !slices.Equal(got, want) {
|
||||||
|
t.Errorf("album folder holds %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
for _, c := range dir.Children {
|
||||||
|
if c.IsDir || c.Parent != paper || c.Type != "music" {
|
||||||
|
t.Errorf("song %s: isDir=%v parent=%q type=%q, want a song in the album", c.Title, c.IsDir, c.Parent, c.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, code := f.directory(t, uuidToID(f.tracks["Gale"].ID)); code != ErrDataNotFound {
|
||||||
|
t.Errorf("a song id: code %d, want %d", code, ErrDataNotFound)
|
||||||
|
}
|
||||||
|
if _, code := f.directory(t, ""); code != ErrMissingParameter {
|
||||||
|
t.Errorf("no id: code %d, want %d", code, ErrMissingParameter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// getAlbumList offers getAlbumList2's lists, with each album a folder.
|
||||||
|
func TestGetAlbumList_IsAlbumList2AsFolders(t *testing.T) {
|
||||||
|
f := seedPicks(t)
|
||||||
|
var got struct {
|
||||||
|
AlbumList AlbumListContainer `json:"albumList"`
|
||||||
|
}
|
||||||
|
if code := call(t, f.browse().getAlbumList, f.user, "type=alphabeticalByName", &got); code != 0 {
|
||||||
|
t.Fatalf("getAlbumList: error %d", code)
|
||||||
|
}
|
||||||
|
if names, want := titles(got.AlbumList.Albums), []string{"Gone Tide", "Lantern Hours", "Paper Boats"}; !slices.Equal(names, want) {
|
||||||
|
t.Errorf("albums = %v, want %v", names, want)
|
||||||
|
}
|
||||||
|
for _, a := range got.AlbumList.Albums {
|
||||||
|
if !a.IsDir || a.Artist != "Tin Orchard" || a.Parent != uuidToID(f.artist.ID) {
|
||||||
|
t.Errorf("album %s: isDir=%v artist=%q parent=%q, want a folder under Tin Orchard", a.Title, a.IsDir, a.Artist, a.Parent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code := call(t, f.browse().getAlbumList, f.user, "", nil); code != ErrMissingParameter {
|
||||||
|
t.Errorf("no type: code %d, want %d", code, ErrMissingParameter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// search2 finds what search3 finds, with the albums as folders.
|
||||||
|
func TestSearch2_FindsWhatSearch3FindsWithAlbumsAsFolders(t *testing.T) {
|
||||||
|
f := seedPicks(t)
|
||||||
|
var got struct {
|
||||||
|
SearchResult2 SearchResult2Container `json:"searchResult2"`
|
||||||
|
}
|
||||||
|
if code := call(t, f.browse().search2, f.user, "query=Paper", &got); code != 0 {
|
||||||
|
t.Fatalf("search2: error %d", code)
|
||||||
|
}
|
||||||
|
res := got.SearchResult2
|
||||||
|
if len(res.Albums) != 1 || res.Albums[0].Title != "Paper Boats" || !res.Albums[0].IsDir {
|
||||||
|
t.Errorf("albums = %+v, want the Paper Boats folder", res.Albums)
|
||||||
|
}
|
||||||
|
if res.Artists == nil || len(res.Artists) != 0 || res.Songs == nil || len(res.Songs) != 0 {
|
||||||
|
t.Errorf("artists = %v, songs = %v, want both empty lists", res.Artists, res.Songs)
|
||||||
|
}
|
||||||
|
|
||||||
|
if code := call(t, f.browse().search2, f.user, "query=Harbour", &got); code != 0 {
|
||||||
|
t.Fatalf("search2: error %d", code)
|
||||||
|
}
|
||||||
|
if songs := titles(got.SearchResult2.Songs); !slices.Equal(songs, []string{"Harbour"}) {
|
||||||
|
t.Errorf("songs = %v, want [Harbour]", songs)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package subsonic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Genre is one entry of getGenres. In XML the name is the element's text.
|
||||||
|
type Genre struct {
|
||||||
|
Value string `json:"value" xml:",chardata"`
|
||||||
|
SongCount int `json:"songCount" xml:"songCount,attr"`
|
||||||
|
AlbumCount int `json:"albumCount" xml:"albumCount,attr"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GenresContainer struct {
|
||||||
|
Genres []Genre `json:"genre" xml:"genre"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GenresResponse struct {
|
||||||
|
Envelope
|
||||||
|
Genres GenresContainer `json:"genres" xml:"genres"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SongsByGenreContainer struct {
|
||||||
|
Songs []SongRef `json:"song" xml:"song"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SongsByGenreResponse struct {
|
||||||
|
Envelope
|
||||||
|
SongsByGenre SongsByGenreContainer `json:"songsByGenre" xml:"songsByGenre"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// getGenres lists the library's genres as the web app's genre index does: a
|
||||||
|
// tag of several genres ("Rock;Pop") counts toward each, missing files count
|
||||||
|
// toward none, and the genres with the most songs come first.
|
||||||
|
func (b *browseHandlers) getGenres(w http.ResponseWriter, r *http.Request) {
|
||||||
|
rows, err := dbq.New(b.pool).ListGenresWithCount(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to load genres")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
genres := make([]Genre, 0, len(rows))
|
||||||
|
for _, row := range rows {
|
||||||
|
genres = append(genres, Genre{
|
||||||
|
Value: row.Genre, SongCount: int(row.TrackCount), AlbumCount: int(row.AlbumCount),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Write(w, r, GenresResponse{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
Genres: GenresContainer{Genres: genres},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// getSongsByGenre pages one genre's songs, album by album in track order.
|
||||||
|
// The listener's quarantined songs are left out, since an app asks for these
|
||||||
|
// to play them. count defaults to 10 and is at most 500, as in the spec.
|
||||||
|
func (b *browseHandlers) getSongsByGenre(w http.ResponseWriter, r *http.Request) {
|
||||||
|
params := r.URL.Query()
|
||||||
|
genre := params.Get("genre")
|
||||||
|
if genre == "" {
|
||||||
|
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: genre")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, ok := UserFromContext(r.Context())
|
||||||
|
if !ok {
|
||||||
|
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
count := clampInt(atoiDefault(params.Get("count"), 10), 1, 500)
|
||||||
|
offset := max(atoiDefault(params.Get("offset"), 0), 0)
|
||||||
|
|
||||||
|
q := dbq.New(b.pool)
|
||||||
|
rows, err := q.ListTracksByGenre(r.Context(), dbq.ListTracksByGenreParams{
|
||||||
|
Genre: genre, UserID: user.ID, Lim: int32(count), Off: int32(offset),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to load songs")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tracks := make([]dbq.Track, len(rows))
|
||||||
|
for i, row := range rows {
|
||||||
|
tracks[i] = row.Track
|
||||||
|
}
|
||||||
|
songs, err := songRefs(r.Context(), q, tracks)
|
||||||
|
if err != nil {
|
||||||
|
WriteFail(w, r, ErrGeneric, "Failed to load songs")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Write(w, r, SongsByGenreResponse{
|
||||||
|
Envelope: NewEnvelope("ok"),
|
||||||
|
SongsByGenre: SongsByGenreContainer{Songs: songs},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -66,6 +66,11 @@ func mountAuthed(sub chi.Router, b *browseHandlers, m *mediaHandlers, u *userHan
|
|||||||
register(sub, "/getAlbumList2", b.getAlbumList2)
|
register(sub, "/getAlbumList2", b.getAlbumList2)
|
||||||
register(sub, "/getSong", b.getSong)
|
register(sub, "/getSong", b.getSong)
|
||||||
register(sub, "/search3", b.search3)
|
register(sub, "/search3", b.search3)
|
||||||
|
register(sub, "/getMusicDirectory", b.getMusicDirectory)
|
||||||
|
register(sub, "/getAlbumList", b.getAlbumList)
|
||||||
|
register(sub, "/search2", b.search2)
|
||||||
|
register(sub, "/getGenres", b.getGenres)
|
||||||
|
register(sub, "/getSongsByGenre", b.getSongsByGenre)
|
||||||
register(sub, "/stream", m.handleStream)
|
register(sub, "/stream", m.handleStream)
|
||||||
register(sub, "/download", m.handleDownload)
|
register(sub, "/download", m.handleDownload)
|
||||||
register(sub, "/getCoverArt", m.handleGetCoverArt)
|
register(sub, "/getCoverArt", m.handleGetCoverArt)
|
||||||
|
|||||||
@@ -160,8 +160,8 @@ type AlbumResponse struct {
|
|||||||
Album AlbumDetail `json:"album" xml:"album"`
|
Album AlbumDetail `json:"album" xml:"album"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SongRef is the track projection used in album detail, getSong, search3,
|
// SongRef is Subsonic's Child: a song in album detail, getSong, search3 and
|
||||||
// and later streaming/now-playing responses.
|
// the lists of songs, and in folder browsing an album too (albumFolder).
|
||||||
//
|
//
|
||||||
// It carries no XMLName: the field that holds it names the element, "song"
|
// It carries no XMLName: the field that holds it names the element, "song"
|
||||||
// in most responses and "entry" in a playlist.
|
// in most responses and "entry" in a playlist.
|
||||||
@@ -182,8 +182,11 @@ type SongRef struct {
|
|||||||
Suffix string `json:"suffix,omitempty" xml:"suffix,attr,omitempty"`
|
Suffix string `json:"suffix,omitempty" xml:"suffix,attr,omitempty"`
|
||||||
Duration int `json:"duration,omitempty" xml:"duration,attr,omitempty"`
|
Duration int `json:"duration,omitempty" xml:"duration,attr,omitempty"`
|
||||||
BitRate int `json:"bitRate,omitempty" xml:"bitRate,attr,omitempty"`
|
BitRate int `json:"bitRate,omitempty" xml:"bitRate,attr,omitempty"`
|
||||||
|
Year int `json:"year,omitempty" xml:"year,attr,omitempty"`
|
||||||
|
Created string `json:"created,omitempty" xml:"created,attr,omitempty"`
|
||||||
IsDir bool `json:"isDir" xml:"isDir,attr"`
|
IsDir bool `json:"isDir" xml:"isDir,attr"`
|
||||||
Type string `json:"type" xml:"type,attr"`
|
// Type is "music" on a song; an album shown as a folder has none.
|
||||||
|
Type string `json:"type,omitempty" xml:"type,attr,omitempty"`
|
||||||
// ReplayGain is OpenSubsonic's replayGain: Minstrel's own
|
// ReplayGain is OpenSubsonic's replayGain: Minstrel's own
|
||||||
// measurements, so third-party clients that level by ReplayGain do it
|
// measurements, so third-party clients that level by ReplayGain do it
|
||||||
// from the same numbers the Minstrel apps use. Omitted until measured.
|
// from the same numbers the Minstrel apps use. Omitted until measured.
|
||||||
|
|||||||
Reference in New Issue
Block a user