feat(subsonic): an artist's top songs, and the play queue carried between devices
release / go (push) Successful in 1m50s
release / web (push) Successful in 1m14s
release / govulncheck (push) Successful in 44s
release / integration (push) Successful in 4m11s
release / android (push) Successful in 6m15s
release / Build signed APK (push) Successful in 7m51s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
release / go (push) Successful in 1m50s
release / web (push) Successful in 1m14s
release / govulncheck (push) Successful in 44s
release / integration (push) Successful in 4m11s
release / android (push) Successful in 6m15s
release / Build signed APK (push) Successful in 7m51s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
getTopSongs ranks the named artist's songs by how often they were played through on this server, then by likes, then in album order, so an artist nobody has played yet still has songs to offer. Missing files and the listener's quarantined songs are left out. savePlayQueue keeps one queue per listener: the songs in order, the one playing, how far into it, and the app that saved it. getPlayQueue gives it back to that listener only; a song no longer in the library drops out. Saving no songs clears it. The queue lives in a new play_queues table, which backups carry. 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**
|
||||
- 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.
|
||||
- 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.
|
||||
- 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, carry a play queue from one device to another, 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.
|
||||
|
||||
## Scope and responsible use
|
||||
|
||||
@@ -150,6 +150,8 @@ func TestARestoredInstanceHoldsWhatTheBackupHeld_Integration(t *testing.T) {
|
||||
session := mustID(t, pool, `INSERT INTO play_sessions (user_id, started_at, last_event_at) VALUES ($1, now(), now()) RETURNING id::text`, user)
|
||||
mustExec(t, pool, `INSERT INTO play_events (user_id, track_id, session_id, started_at) VALUES ($1, $2, $3, now())`, user, track, session)
|
||||
mustExec(t, pool, `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2)`, user, track)
|
||||
mustExec(t, pool, `INSERT INTO play_queues (user_id, track_ids, current_track_id, position_ms, changed_by)
|
||||
VALUES ($1, ARRAY[$2::uuid, $2::uuid], $2, 61000, 'an app')`, user, track)
|
||||
playlist := mustID(t, pool, `INSERT INTO playlists (user_id, name) VALUES ($1, 'Mine') RETURNING id::text`, user)
|
||||
mustExec(t, pool, `INSERT INTO playlist_tracks (playlist_id, position, track_id, title, artist_name, album_title, duration_sec)
|
||||
VALUES ($1, 0, $2, 'Track', 'Artist', 'Album', 180)`, playlist, track)
|
||||
@@ -172,7 +174,7 @@ func TestARestoredInstanceHoldsWhatTheBackupHeld_Integration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, tbl := range []string{"users", "tracks", "play_events", "general_likes", "playlist_tracks", "library_changes"} {
|
||||
for _, tbl := range []string{"users", "tracks", "play_events", "general_likes", "play_queues", "playlist_tracks", "library_changes"} {
|
||||
if len(first.Tables[tbl]) == 0 {
|
||||
t.Errorf("the backup holds no %s", tbl)
|
||||
}
|
||||
|
||||
@@ -79,6 +79,8 @@ var Tables = []Table{
|
||||
|
||||
// Per-user preferences and notifications.
|
||||
{Name: "user_normalization_prefs"},
|
||||
// The queue a Subsonic app saved, so it resumes where it was.
|
||||
{Name: "play_queues"},
|
||||
{Name: "user_notification_prefs"},
|
||||
{Name: "user_notification_email_state"},
|
||||
{Name: "user_notifications"},
|
||||
|
||||
@@ -411,6 +411,15 @@ type PlayEvent struct {
|
||||
DeviceClass *string
|
||||
}
|
||||
|
||||
type PlayQueue struct {
|
||||
UserID pgtype.UUID
|
||||
TrackIds []pgtype.UUID
|
||||
CurrentTrackID pgtype.UUID
|
||||
PositionMs int64
|
||||
ChangedAt pgtype.Timestamptz
|
||||
ChangedBy string
|
||||
}
|
||||
|
||||
type PlaySession struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: play_queue.sql
|
||||
|
||||
package dbq
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deletePlayQueue = `-- name: DeletePlayQueue :exec
|
||||
DELETE FROM play_queues WHERE user_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeletePlayQueue(ctx context.Context, userID pgtype.UUID) error {
|
||||
_, err := q.db.Exec(ctx, deletePlayQueue, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
const getPlayQueue = `-- name: GetPlayQueue :one
|
||||
SELECT user_id, track_ids, current_track_id, position_ms, changed_at, changed_by FROM play_queues WHERE user_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetPlayQueue(ctx context.Context, userID pgtype.UUID) (PlayQueue, error) {
|
||||
row := q.db.QueryRow(ctx, getPlayQueue, userID)
|
||||
var i PlayQueue
|
||||
err := row.Scan(
|
||||
&i.UserID,
|
||||
&i.TrackIds,
|
||||
&i.CurrentTrackID,
|
||||
&i.PositionMs,
|
||||
&i.ChangedAt,
|
||||
&i.ChangedBy,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const savePlayQueue = `-- name: SavePlayQueue :exec
|
||||
INSERT INTO play_queues (user_id, track_ids, current_track_id, position_ms, changed_at, changed_by)
|
||||
VALUES ($1, $2::uuid[], $3, $4, now(), $5)
|
||||
ON CONFLICT (user_id) DO UPDATE
|
||||
SET track_ids = EXCLUDED.track_ids,
|
||||
current_track_id = EXCLUDED.current_track_id,
|
||||
position_ms = EXCLUDED.position_ms,
|
||||
changed_at = EXCLUDED.changed_at,
|
||||
changed_by = EXCLUDED.changed_by
|
||||
`
|
||||
|
||||
type SavePlayQueueParams struct {
|
||||
UserID pgtype.UUID
|
||||
TrackIds []pgtype.UUID
|
||||
CurrentTrackID pgtype.UUID
|
||||
PositionMs int64
|
||||
ChangedBy string
|
||||
}
|
||||
|
||||
// Replaces the user's saved queue.
|
||||
func (q *Queries) SavePlayQueue(ctx context.Context, arg SavePlayQueueParams) error {
|
||||
_, err := q.db.Exec(ctx, savePlayQueue,
|
||||
arg.UserID,
|
||||
arg.TrackIds,
|
||||
arg.CurrentTrackID,
|
||||
arg.PositionMs,
|
||||
arg.ChangedBy,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -833,6 +833,96 @@ func (q *Queries) ListSuspectSourceTracks(ctx context.Context, arg ListSuspectSo
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listTopTracksForArtistName = `-- name: ListTopTracksForArtistName :many
|
||||
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit
|
||||
FROM tracks t
|
||||
JOIN artists ar ON ar.id = t.artist_id
|
||||
JOIN albums al ON al.id = t.album_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT count(*) AS plays FROM play_events pe
|
||||
WHERE pe.track_id = t.id AND pe.was_skipped = false
|
||||
) p ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT count(*) AS likes FROM general_likes gl WHERE gl.track_id = t.id
|
||||
) l ON true
|
||||
WHERE lower(ar.name) = lower($1::text)
|
||||
AND t.missing_since IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM quarantine q
|
||||
WHERE q.user_id = $2 AND q.track_id = t.id
|
||||
)
|
||||
ORDER BY p.plays DESC, l.likes DESC,
|
||||
al.release_date NULLS LAST, al.sort_title, al.id,
|
||||
t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.id
|
||||
LIMIT $3
|
||||
`
|
||||
|
||||
type ListTopTracksForArtistNameParams struct {
|
||||
ArtistName string
|
||||
UserID pgtype.UUID
|
||||
Lim int32
|
||||
}
|
||||
|
||||
type ListTopTracksForArtistNameRow struct {
|
||||
Track Track
|
||||
}
|
||||
|
||||
// An artist's top songs for the Subsonic getTopSongs, which names the artist
|
||||
// rather than giving an id; the name matches regardless of case. "Top" is
|
||||
// this server's own listening: the songs played through most often (skips
|
||||
// not counted) by everyone on it, then the most liked. Songs nobody has
|
||||
// played or liked follow in album order, so an artist with no history still
|
||||
// has songs to play. Missing files and the listener's quarantined songs are
|
||||
// left out.
|
||||
func (q *Queries) ListTopTracksForArtistName(ctx context.Context, arg ListTopTracksForArtistNameParams) ([]ListTopTracksForArtistNameRow, error) {
|
||||
rows, err := q.db.Query(ctx, listTopTracksForArtistName, arg.ArtistName, arg.UserID, arg.Lim)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListTopTracksForArtistNameRow
|
||||
for rows.Next() {
|
||||
var i ListTopTracksForArtistNameRow
|
||||
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
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listTrackPathsForReconcile = `-- name: ListTrackPathsForReconcile :many
|
||||
SELECT id, file_path, missing_since FROM tracks
|
||||
`
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE play_queues;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- The play queue a Subsonic app saves (savePlayQueue) so another app or
|
||||
-- device can pick up where it left off (getPlayQueue): one queue per user,
|
||||
-- the songs in order, the one playing and how far into it. track_ids is not
|
||||
-- a foreign key: a song removed from the library drops out of the queue
|
||||
-- when it is read, rather than blocking the removal.
|
||||
CREATE TABLE play_queues (
|
||||
user_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
track_ids uuid[] NOT NULL DEFAULT '{}',
|
||||
current_track_id uuid,
|
||||
position_ms bigint NOT NULL DEFAULT 0,
|
||||
changed_at timestamptz NOT NULL DEFAULT now(),
|
||||
-- The app that saved it, from the Subsonic c parameter.
|
||||
changed_by text NOT NULL DEFAULT ''
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
-- name: GetPlayQueue :one
|
||||
SELECT * FROM play_queues WHERE user_id = $1;
|
||||
|
||||
-- name: SavePlayQueue :exec
|
||||
-- Replaces the user's saved queue.
|
||||
INSERT INTO play_queues (user_id, track_ids, current_track_id, position_ms, changed_at, changed_by)
|
||||
VALUES (sqlc.arg(user_id), sqlc.arg(track_ids)::uuid[], sqlc.narg(current_track_id), sqlc.arg(position_ms), now(), sqlc.arg(changed_by))
|
||||
ON CONFLICT (user_id) DO UPDATE
|
||||
SET track_ids = EXCLUDED.track_ids,
|
||||
current_track_id = EXCLUDED.current_track_id,
|
||||
position_ms = EXCLUDED.position_ms,
|
||||
changed_at = EXCLUDED.changed_at,
|
||||
changed_by = EXCLUDED.changed_by;
|
||||
|
||||
-- name: DeletePlayQueue :exec
|
||||
DELETE FROM play_queues WHERE user_id = $1;
|
||||
@@ -394,3 +394,33 @@ SELECT ar.name AS artist_name, t.title
|
||||
WHERE t.id = ANY(sqlc.arg(ids)::uuid[])
|
||||
AND t.missing_since IS NOT NULL
|
||||
ORDER BY ar.name, t.title;
|
||||
|
||||
-- name: ListTopTracksForArtistName :many
|
||||
-- An artist's top songs for the Subsonic getTopSongs, which names the artist
|
||||
-- rather than giving an id; the name matches regardless of case. "Top" is
|
||||
-- this server's own listening: the songs played through most often (skips
|
||||
-- not counted) by everyone on it, then the most liked. Songs nobody has
|
||||
-- played or liked follow in album order, so an artist with no history still
|
||||
-- has songs to play. Missing files and the listener's quarantined songs are
|
||||
-- left out.
|
||||
SELECT sqlc.embed(t)
|
||||
FROM tracks t
|
||||
JOIN artists ar ON ar.id = t.artist_id
|
||||
JOIN albums al ON al.id = t.album_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT count(*) AS plays FROM play_events pe
|
||||
WHERE pe.track_id = t.id AND pe.was_skipped = false
|
||||
) p ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT count(*) AS likes FROM general_likes gl WHERE gl.track_id = t.id
|
||||
) l ON true
|
||||
WHERE lower(ar.name) = lower(sqlc.arg(artist_name)::text)
|
||||
AND t.missing_since IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM quarantine q
|
||||
WHERE q.user_id = sqlc.arg(user_id) AND q.track_id = t.id
|
||||
)
|
||||
ORDER BY p.plays DESC, l.likes DESC,
|
||||
al.release_date NULLS LAST, al.sort_title, al.id,
|
||||
t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.id
|
||||
LIMIT sqlc.arg(lim);
|
||||
|
||||
@@ -64,6 +64,7 @@ var dataTables = []string{
|
||||
// would make it look already-settled and thus ineligible.
|
||||
"playlist_tracks",
|
||||
"playlists",
|
||||
"play_queues",
|
||||
"library_changes", // reset so each test's sync cursor starts clean
|
||||
// SettingsService.reconcile() idempotently re-UpsertProviderSettings
|
||||
// for every registered provider at boot, so truncating this is the
|
||||
|
||||
@@ -2,6 +2,7 @@ package subsonic
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
@@ -92,3 +93,52 @@ func (b *browseHandlers) getSongsByGenre(w http.ResponseWriter, r *http.Request)
|
||||
SongsByGenre: SongsByGenreContainer{Songs: songs},
|
||||
})
|
||||
}
|
||||
|
||||
type TopSongsContainer struct {
|
||||
Songs []SongRef `json:"song" xml:"song"`
|
||||
}
|
||||
|
||||
type TopSongsResponse struct {
|
||||
Envelope
|
||||
TopSongs TopSongsContainer `json:"topSongs" xml:"topSongs"`
|
||||
}
|
||||
|
||||
// getTopSongs returns an artist's most played songs on this server, then the
|
||||
// most liked, then the rest in album order (ListTopTracksForArtistName). The
|
||||
// app names the artist rather than giving an id. count defaults to 50 and is
|
||||
// at most 500.
|
||||
func (b *browseHandlers) getTopSongs(w http.ResponseWriter, r *http.Request) {
|
||||
params := r.URL.Query()
|
||||
artist := strings.TrimSpace(params.Get("artist"))
|
||||
if artist == "" {
|
||||
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: artist")
|
||||
return
|
||||
}
|
||||
user, ok := UserFromContext(r.Context())
|
||||
if !ok {
|
||||
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
||||
return
|
||||
}
|
||||
count := clampInt(atoiDefault(params.Get("count"), 50), 1, 500)
|
||||
q := dbq.New(b.pool)
|
||||
rows, err := q.ListTopTracksForArtistName(r.Context(), dbq.ListTopTracksForArtistNameParams{
|
||||
ArtistName: artist, UserID: user.ID, Lim: int32(count),
|
||||
})
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to load top 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 top songs")
|
||||
return
|
||||
}
|
||||
Write(w, r, TopSongsResponse{
|
||||
Envelope: NewEnvelope("ok"),
|
||||
TopSongs: TopSongsContainer{Songs: songs},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package subsonic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// A Subsonic app saves its play queue (savePlayQueue) so the same app on
|
||||
// another device, or another app, can carry on from it (getPlayQueue). The
|
||||
// server keeps one queue per user and does nothing else with it: Minstrel's
|
||||
// own apps keep their queue on the device.
|
||||
|
||||
// maxPlayQueue is the most songs one saved queue holds. A queue longer than
|
||||
// any app sends is refused rather than stored, so one request cannot grow a
|
||||
// row without bound.
|
||||
const maxPlayQueue = 10000
|
||||
|
||||
// PlayQueue is the body of getPlayQueue. Position is milliseconds into the
|
||||
// current song.
|
||||
type PlayQueue struct {
|
||||
Current string `json:"current,omitempty" xml:"current,attr,omitempty"`
|
||||
Position int64 `json:"position,omitempty" xml:"position,attr,omitempty"`
|
||||
Username string `json:"username" xml:"username,attr"`
|
||||
Changed string `json:"changed" xml:"changed,attr"`
|
||||
ChangedBy string `json:"changedBy" xml:"changedBy,attr"`
|
||||
Entries []SongRef `json:"entry" xml:"entry"`
|
||||
}
|
||||
|
||||
// PlayQueueResponse carries no playQueue when nothing has been saved, which
|
||||
// is how the Subsonic server answers too.
|
||||
type PlayQueueResponse struct {
|
||||
Envelope
|
||||
PlayQueue *PlayQueue `json:"playQueue,omitempty" xml:"playQueue,omitempty"`
|
||||
}
|
||||
|
||||
// getPlayQueue returns the queue the listener last saved. A song no longer
|
||||
// in the library drops out of it; if that was the current song, the queue
|
||||
// has no current song.
|
||||
func (b *browseHandlers) getPlayQueue(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := UserFromContext(r.Context())
|
||||
if !ok {
|
||||
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
||||
return
|
||||
}
|
||||
q := dbq.New(b.pool)
|
||||
saved, err := q.GetPlayQueue(r.Context(), user.ID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
Write(w, r, PlayQueueResponse{Envelope: NewEnvelope("ok")})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to load the play queue")
|
||||
return
|
||||
}
|
||||
songs, err := songsInOrder(r.Context(), q, saved.TrackIds)
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to load the play queue")
|
||||
return
|
||||
}
|
||||
queue := &PlayQueue{
|
||||
Username: user.Username,
|
||||
Changed: timestamptzToRFC3339(saved.ChangedAt),
|
||||
ChangedBy: saved.ChangedBy,
|
||||
Entries: songs,
|
||||
}
|
||||
current := uuidToID(saved.CurrentTrackID)
|
||||
if current != "" && slices.ContainsFunc(songs, func(s SongRef) bool { return s.ID == current }) {
|
||||
queue.Current = current
|
||||
queue.Position = saved.PositionMs
|
||||
}
|
||||
Write(w, r, PlayQueueResponse{Envelope: NewEnvelope("ok"), PlayQueue: queue})
|
||||
}
|
||||
|
||||
// savePlayQueue replaces the listener's saved queue with the songs given as
|
||||
// repeated id parameters, in order, with current the one playing and
|
||||
// position the milliseconds into it. With no id the saved queue is cleared,
|
||||
// as OpenSubsonic specifies.
|
||||
func (b *browseHandlers) savePlayQueue(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := UserFromContext(r.Context())
|
||||
if !ok {
|
||||
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
||||
return
|
||||
}
|
||||
params := r.URL.Query()
|
||||
q := dbq.New(b.pool)
|
||||
raw := params["id"]
|
||||
if len(raw) == 0 {
|
||||
if err := q.DeletePlayQueue(r.Context(), user.ID); err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to clear the play queue")
|
||||
return
|
||||
}
|
||||
Write(w, r, NewEnvelope("ok"))
|
||||
return
|
||||
}
|
||||
if len(raw) > maxPlayQueue {
|
||||
WriteFail(w, r, ErrGeneric, "A play queue holds at most "+strconv.Itoa(maxPlayQueue)+" songs")
|
||||
return
|
||||
}
|
||||
ids := make([]pgtype.UUID, 0, len(raw))
|
||||
for _, s := range raw {
|
||||
id, ok := parseUUID(s)
|
||||
if !ok {
|
||||
WriteFail(w, r, ErrDataNotFound, "Song not found: "+s)
|
||||
return
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
var current pgtype.UUID
|
||||
if s := params.Get("current"); s != "" {
|
||||
if current, ok = parseUUID(s); !ok {
|
||||
WriteFail(w, r, ErrDataNotFound, "Song not found: "+s)
|
||||
return
|
||||
}
|
||||
}
|
||||
position, err := strconv.ParseInt(params.Get("position"), 10, 64)
|
||||
if err != nil || position < 0 {
|
||||
position = 0
|
||||
}
|
||||
if err := q.SavePlayQueue(r.Context(), dbq.SavePlayQueueParams{
|
||||
UserID: user.ID, TrackIds: ids, CurrentTrackID: current,
|
||||
PositionMs: position, ChangedBy: params.Get("c"),
|
||||
}); err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to save the play queue")
|
||||
return
|
||||
}
|
||||
Write(w, r, NewEnvelope("ok"))
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package subsonic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// play records plays of a track by a listener, skipped or played through.
|
||||
func (f picksFixture) play(t *testing.T, user dbq.User, track string, times int, skipped bool) {
|
||||
t.Helper()
|
||||
var session pgtype.UUID
|
||||
if err := f.pool.QueryRow(context.Background(), `INSERT INTO play_sessions (user_id, started_at, last_event_at, client_id)
|
||||
VALUES ($1, now() - interval '2 days', now() - interval '2 days', 'top-songs-test') RETURNING id`,
|
||||
user.ID).Scan(&session); err != nil {
|
||||
t.Fatalf("play session: %v", err)
|
||||
}
|
||||
for range times {
|
||||
f.exec(t, `INSERT INTO play_events (user_id, track_id, session_id, started_at, was_skipped)
|
||||
VALUES ($1, $2, $3, now() - interval '2 days', $4)`, user.ID, f.tracks[track].ID, session, skipped)
|
||||
}
|
||||
}
|
||||
|
||||
func (f picksFixture) topSongs(t *testing.T, query string) ([]string, int) {
|
||||
t.Helper()
|
||||
var got struct {
|
||||
TopSongs struct {
|
||||
Songs *[]SongRef `json:"song"`
|
||||
} `json:"topSongs"`
|
||||
}
|
||||
if code := call(t, f.browse().getTopSongs, f.user, query, &got); code != 0 {
|
||||
return nil, code
|
||||
}
|
||||
if got.TopSongs.Songs == nil {
|
||||
t.Fatalf("getTopSongs %s: song is null or absent, want a list", query)
|
||||
}
|
||||
return titles(*got.TopSongs.Songs), 0
|
||||
}
|
||||
|
||||
// An artist's top songs are the ones played through most on this server, by
|
||||
// anyone, then the most liked, then the rest in album order. Skips don't
|
||||
// count, and the listener's quarantined song and the missing file are left
|
||||
// out.
|
||||
func TestGetTopSongs_RanksByPlaysThenLikesThenAlbumOrder(t *testing.T) {
|
||||
f := seedPicks(t)
|
||||
// The fixture's listener played Flint once.
|
||||
f.play(t, f.other, "Harbour", 2, false)
|
||||
f.play(t, f.other, "Inlet", 3, true)
|
||||
f.exec(t, `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2)`, f.other.ID, f.tracks["Gale"].ID)
|
||||
|
||||
cases := []struct {
|
||||
query string
|
||||
want []string
|
||||
}{
|
||||
{"artist=Tin+Orchard", []string{"Harbour", "Flint", "Gale", "Dusk", "Inlet"}},
|
||||
{"artist=tin+orchard&count=2", []string{"Harbour", "Flint"}},
|
||||
{"artist=Nobody+Here", []string{}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got, code := f.topSongs(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.topSongs(t, ""); code != ErrMissingParameter {
|
||||
t.Errorf("no artist: code %d, want %d", code, ErrMissingParameter)
|
||||
}
|
||||
}
|
||||
|
||||
func (f picksFixture) playQueue(t *testing.T, user dbq.User) *PlayQueue {
|
||||
t.Helper()
|
||||
var got struct {
|
||||
PlayQueue *PlayQueue `json:"playQueue"`
|
||||
}
|
||||
if code := call(t, f.browse().getPlayQueue, user, "", &got); code != 0 {
|
||||
t.Fatalf("getPlayQueue: error %d", code)
|
||||
}
|
||||
return got.PlayQueue
|
||||
}
|
||||
|
||||
func (f picksFixture) saveQueue(t *testing.T, query string) int {
|
||||
t.Helper()
|
||||
return call(t, f.browse().savePlayQueue, f.user, query, nil)
|
||||
}
|
||||
|
||||
// A saved queue comes back to the same listener, in order with repeats, with
|
||||
// the current song and position; nobody else sees it; saving no songs clears
|
||||
// it.
|
||||
func TestPlayQueue_SavedByOneAppIsWhatTheNextOneGets(t *testing.T) {
|
||||
f := seedPicks(t)
|
||||
id := func(title string) string { return uuidToID(f.tracks[title].ID) }
|
||||
|
||||
if q := f.playQueue(t, f.user); q != nil {
|
||||
t.Fatalf("before any save: queue %+v, want none", q)
|
||||
}
|
||||
if code := f.saveQueue(t, "id="+id("Gale")+"&id="+id("Harbour")+"&id="+id("Gale")+
|
||||
"¤t="+id("Harbour")+"&position=61000&c=DSub"); code != 0 {
|
||||
t.Fatalf("savePlayQueue: error %d", code)
|
||||
}
|
||||
q := f.playQueue(t, f.user)
|
||||
if q == nil {
|
||||
t.Fatal("after a save: no queue")
|
||||
}
|
||||
if got, want := titles(q.Entries), []string{"Gale", "Harbour", "Gale"}; !slices.Equal(got, want) {
|
||||
t.Errorf("entries = %v, want %v", got, want)
|
||||
}
|
||||
if q.Current != id("Harbour") || q.Position != 61000 {
|
||||
t.Errorf("current %q at %d, want Harbour (%s) at 61000", q.Current, q.Position, id("Harbour"))
|
||||
}
|
||||
if q.ChangedBy != "DSub" || q.Username != f.user.Username || q.Changed == "" {
|
||||
t.Errorf("changed by %q, user %q, changed %q; want DSub, %q and a time", q.ChangedBy, q.Username, q.Changed, f.user.Username)
|
||||
}
|
||||
if other := f.playQueue(t, f.other); other != nil {
|
||||
t.Errorf("another listener sees queue %+v, want none", other)
|
||||
}
|
||||
|
||||
// A song that is no longer in the library drops out, and a current song
|
||||
// that went with it leaves the queue with none.
|
||||
gone := "00000000-0000-4000-8000-000000000001"
|
||||
if code := f.saveQueue(t, "id="+id("Gale")+"&id="+gone+"¤t="+gone+"&position=5000"); code != 0 {
|
||||
t.Fatalf("savePlayQueue: error %d", code)
|
||||
}
|
||||
q = f.playQueue(t, f.user)
|
||||
if got := titles(q.Entries); !slices.Equal(got, []string{"Gale"}) || q.Current != "" || q.Position != 0 {
|
||||
t.Errorf("queue = %v current %q at %d, want [Gale] with no current song", got, q.Current, q.Position)
|
||||
}
|
||||
|
||||
if code := f.saveQueue(t, "id=not-a-song"); code != ErrDataNotFound {
|
||||
t.Errorf("an id that is not a song: code %d, want %d", code, ErrDataNotFound)
|
||||
}
|
||||
if code := f.saveQueue(t, ""); code != 0 {
|
||||
t.Fatalf("savePlayQueue with no songs: error %d", code)
|
||||
}
|
||||
if q := f.playQueue(t, f.user); q != nil {
|
||||
t.Errorf("after saving no songs: queue %+v, want none", q)
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,9 @@ func mountAuthed(sub chi.Router, b *browseHandlers, m *mediaHandlers, u *userHan
|
||||
register(sub, "/search2", b.search2)
|
||||
register(sub, "/getGenres", b.getGenres)
|
||||
register(sub, "/getSongsByGenre", b.getSongsByGenre)
|
||||
register(sub, "/getTopSongs", b.getTopSongs)
|
||||
register(sub, "/getPlayQueue", b.getPlayQueue)
|
||||
register(sub, "/savePlayQueue", b.savePlayQueue)
|
||||
register(sub, "/stream", m.handleStream)
|
||||
register(sub, "/download", m.handleDownload)
|
||||
register(sub, "/getCoverArt", m.handleGetCoverArt)
|
||||
|
||||
Reference in New Issue
Block a user