package subsonic import ( "context" "errors" "log/slog" "math/rand/v2" "net/http" "strconv" "strings" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" "git.fabledsword.com/bvandeusen/minstrel/internal/recommendation" ) // pickHandlers serve what Minstrel chooses for the listener: their playlists // and daily mixes, the weighted shuffle, and radio. They answer from the same // code as Minstrel's own apps, so a Subsonic app gets the same picks. type pickHandlers struct { pool *pgxpool.Pool picker *recommendation.Picker playlists *playlists.Service logger *slog.Logger // recall notes the daily mix an app opens, so its plays are credited // to that mix (see mixRecall). recall *mixRecall } // ---- getPlaylists / getPlaylist ---- // PlaylistRef is one playlist in getPlaylists, and the head of getPlaylist. type PlaylistRef struct { ID string `json:"id" xml:"id,attr"` Name string `json:"name" xml:"name,attr"` Comment string `json:"comment,omitempty" xml:"comment,attr,omitempty"` Owner string `json:"owner,omitempty" xml:"owner,attr,omitempty"` Public bool `json:"public" xml:"public,attr"` SongCount int `json:"songCount" xml:"songCount,attr"` Duration int `json:"duration" xml:"duration,attr"` Created string `json:"created,omitempty" xml:"created,attr,omitempty"` Changed string `json:"changed,omitempty" xml:"changed,attr,omitempty"` CoverArt string `json:"coverArt,omitempty" xml:"coverArt,attr,omitempty"` } type PlaylistsContainer struct { Playlists []PlaylistRef `json:"playlist" xml:"playlist"` } type PlaylistsResponse struct { Envelope Playlists PlaylistsContainer `json:"playlists" xml:"playlists"` } // PlaylistWithSongs is getPlaylist's body: the playlist and its songs. type PlaylistWithSongs struct { PlaylistRef Entries []SongRef `json:"entry" xml:"entry"` } type PlaylistResponse struct { Envelope Playlist PlaylistWithSongs `json:"playlist" xml:"playlist"` } // playlistRef converts a playlist row. Its cover is the first album cover in // it: getCoverArt answers for an album id, and a Subsonic app shows that. func playlistRef(p *playlists.PlaylistRow) PlaylistRef { ref := PlaylistRef{ ID: uuidToID(p.ID), Name: p.Name, Comment: p.Description, Owner: p.OwnerUsername, Public: p.IsPublic, SongCount: int(p.TrackCount), Duration: int(p.DurationSec), Created: timestamptzToRFC3339(p.CreatedAt), Changed: timestamptzToRFC3339(p.UpdatedAt), } if len(p.CoverAlbumIDs) > 0 { ref.CoverArt = uuidToID(p.CoverAlbumIDs[0]) } return ref } // getPlaylists lists the caller's daily mixes first, then their own // playlists, then other people's public ones. The mixes lead because they are // what Minstrel makes fresh each day; within each group the service's order // (most recently changed first) stands. func (h *pickHandlers) getPlaylists(w http.ResponseWriter, r *http.Request) { user, ok := UserFromContext(r.Context()) if !ok { WriteFail(w, r, ErrNotAuthorized, "Not authenticated") return } rows, err := h.playlists.List(r.Context(), user.ID) if err != nil { h.logger.Error("subsonic: list playlists", "err", err) WriteFail(w, r, ErrGeneric, "Playlists unavailable") return } var mixes, own, others []PlaylistRef for i := range rows { p := &rows[i] switch { case p.UserID != user.ID: others = append(others, playlistRef(p)) case p.Kind == "system": mixes = append(mixes, playlistRef(p)) default: own = append(own, playlistRef(p)) } } out := make([]PlaylistRef, 0, len(rows)) out = append(append(append(out, mixes...), own...), others...) Write(w, r, PlaylistsResponse{ Envelope: NewEnvelope("ok"), Playlists: PlaylistsContainer{Playlists: out}, }) } // getPlaylist returns one playlist and its songs in playlist order. A song // whose file is missing, or that has left the library, keeps its place in // Minstrel but is not listed here, since a Subsonic app would try to play it. func (h *pickHandlers) getPlaylist(w http.ResponseWriter, r *http.Request) { user, ok := UserFromContext(r.Context()) if !ok { WriteFail(w, r, ErrNotAuthorized, "Not authenticated") return } raw := r.URL.Query().Get("id") if raw == "" { WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id") return } id, ok := parseUUID(raw) if !ok { WriteFail(w, r, ErrDataNotFound, "Playlist not found") return } detail, err := h.playlists.Get(r.Context(), user.ID, id) if err != nil { // Someone else's private playlist reads as absent, as it does in // the list. if errors.Is(err, playlists.ErrNotFound) || errors.Is(err, playlists.ErrForbidden) { WriteFail(w, r, ErrDataNotFound, "Playlist not found") return } h.logger.Error("subsonic: get playlist", "err", err) WriteFail(w, r, ErrGeneric, "Playlist unavailable") return } ids := make([]pgtype.UUID, 0, len(detail.Tracks)) for _, t := range detail.Tracks { if t.TrackID != nil && !t.Unavailable { ids = append(ids, *t.TrackID) } } q := dbq.New(h.pool) songs, err := songsInOrder(r.Context(), q, ids) if err != nil { h.logger.Error("subsonic: playlist songs", "err", err) WriteFail(w, r, ErrGeneric, "Playlist unavailable") return } if detail.Kind == "system" && detail.SystemVariant != nil { h.recall.remember(user.ID, r.URL.Query().Get("c"), *detail.SystemVariant) } head := playlistRef(&detail.PlaylistRow) head.SongCount = len(songs) head.Duration = 0 for _, s := range songs { head.Duration += s.Duration } Write(w, r, PlaylistResponse{ Envelope: NewEnvelope("ok"), Playlist: PlaylistWithSongs{PlaylistRef: head, Entries: songs}, }) } // songsInOrder looks up tracks by id and returns them as songs in the order // of ids; an id with no track is skipped. One query each for the tracks, // their albums, their artists and their gains. func songsInOrder(ctx context.Context, q *dbq.Queries, ids []pgtype.UUID) ([]SongRef, error) { if len(ids) == 0 { return []SongRef{}, nil } rows, err := q.GetTracksByIDs(ctx, ids) if err != nil { return nil, err } byID := make(map[pgtype.UUID]dbq.Track, len(rows)) for _, t := range rows { byID[t.ID] = t } tracks := make([]dbq.Track, 0, len(ids)) for _, id := range ids { if t, ok := byID[id]; ok { tracks = append(tracks, t) } } return songRefs(ctx, q, tracks) } // songRefs converts tracks to songs, keeping their order. func songRefs(ctx context.Context, q *dbq.Queries, tracks []dbq.Track) ([]SongRef, error) { albumTitles, artistNames, err := songParents(ctx, q, tracks) if err != nil { return nil, err } gains := replayGains(ctx, q, tracks) out := make([]SongRef, 0, len(tracks)) for _, t := range tracks { out = append(out, songRef(t, albumTitles[t.AlbumID], artistNames[t.ArtistID], gains[t.ID])) } return out, nil } func candidateTracks(picks []recommendation.Candidate) []dbq.Track { out := make([]dbq.Track, len(picks)) for i, p := range picks { out[i] = p.Track } return out } // ---- getRandomSongs ---- type RandomSongsContainer struct { Songs []SongRef `json:"song" xml:"song"` } type RandomSongsResponse struct { Envelope RandomSongs RandomSongsContainer `json:"randomSongs" xml:"randomSongs"` } // getRandomSongs is a Subsonic app's shuffle. Minstrel answers with its // weighted shuffle, the one its own apps use: songs the listener likes come // up more, songs they skip less, and songs heard in the last hour not at all. // size defaults to 10, as the Subsonic API defines it, and is capped at the // server's radio length. genre, fromYear and toYear narrow the library first. func (h *pickHandlers) getRandomSongs(w http.ResponseWriter, r *http.Request) { user, ok := UserFromContext(r.Context()) if !ok { WriteFail(w, r, ErrNotAuthorized, "Not authenticated") return } params := r.URL.Query() size := clampInt(atoiDefault(params.Get("size"), 10), 1, 500) q := dbq.New(h.pool) keep, err := randomSongsFilter(r.Context(), q, params.Get("genre"), params.Get("fromYear"), params.Get("toYear")) if err != nil { h.logger.Error("subsonic: random songs filter", "err", err) WriteFail(w, r, ErrGeneric, "Shuffle unavailable") return } picks, err := h.picker.Shuffle(r.Context(), q, user.ID, size, keep) if err != nil { h.logger.Error("subsonic: random songs", "err", err) WriteFail(w, r, ErrGeneric, "Shuffle unavailable") return } songs, err := songRefs(r.Context(), q, candidateTracks(picks)) if err != nil { h.logger.Error("subsonic: random songs", "err", err) WriteFail(w, r, ErrGeneric, "Shuffle unavailable") return } Write(w, r, RandomSongsResponse{ Envelope: NewEnvelope("ok"), RandomSongs: RandomSongsContainer{Songs: songs}, }) } // randomSongsFilter builds getRandomSongs' narrowing, or nil when nothing // narrows. A genre matches each of a track's genres, split on ; and , the way // getAlbumList2 byGenre splits them, so "Rock" reaches a track tagged // "Rock;Pop". The years are an album's release year, inclusive; either end // may be left open. func randomSongsFilter(ctx context.Context, q *dbq.Queries, genre, fromYear, toYear string) (func(dbq.Track) bool, error) { genre = strings.TrimSpace(genre) var albums map[pgtype.UUID]bool if fromYear != "" || toYear != "" { from, ferr := strconv.Atoi(fromYear) if ferr != nil { from = 0 } to, terr := strconv.Atoi(toYear) if terr != nil { to = 9999 } inRange, err := q.ListAlbumsByYearOrdered(ctx, dbq.ListAlbumsByYearOrderedParams{ FromYear: int32(from), ToYear: int32(to), Lim: 1 << 30, Off: 0, }) if err != nil { return nil, err } albums = make(map[pgtype.UUID]bool, len(inRange)) for _, a := range inRange { albums[a.ID] = true } } if genre == "" && albums == nil { return nil, nil } return func(t dbq.Track) bool { if albums != nil && !albums[t.AlbumID] { return false } return genre == "" || hasGenre(t.Genre, genre) }, nil } func hasGenre(tagged *string, genre string) bool { if tagged == nil { return false } for _, g := range strings.FieldsFunc(*tagged, func(r rune) bool { return r == ';' || r == ',' }) { if strings.EqualFold(strings.TrimSpace(g), genre) { return true } } return false } // ---- getSimilarSongs / getSimilarSongs2 ---- type SimilarSongsContainer struct { Songs []SongRef `json:"song" xml:"song"` } type SimilarSongsResponse struct { Envelope SimilarSongs SimilarSongsContainer `json:"similarSongs" xml:"similarSongs"` } type SimilarSongs2Response struct { Envelope SimilarSongs2 SimilarSongsContainer `json:"similarSongs2" xml:"similarSongs2"` } // getSimilarSongs is a Subsonic app's radio, or "instant mix". Minstrel // answers with its own radio. id may be a song, an album or an artist; an // album or artist seeds the radio from one of its songs, picked at random. // count defaults to 50, as the Subsonic API defines it. The seed song is not // in the answer: the app plays it already. func (h *pickHandlers) getSimilarSongs(w http.ResponseWriter, r *http.Request) { songs, ok := h.similar(w, r, true) if !ok { return } Write(w, r, SimilarSongsResponse{ Envelope: NewEnvelope("ok"), SimilarSongs: SimilarSongsContainer{Songs: songs}, }) } // getSimilarSongs2 is getSimilarSongs for an artist id, as the ID3 browse // methods give. func (h *pickHandlers) getSimilarSongs2(w http.ResponseWriter, r *http.Request) { songs, ok := h.similar(w, r, false) if !ok { return } Write(w, r, SimilarSongs2Response{ Envelope: NewEnvelope("ok"), SimilarSongs2: SimilarSongsContainer{Songs: songs}, }) } // similar runs radio for the request's id. anyKind also accepts a song or an // album id; otherwise only an artist id is a seed. It writes the failure // itself and reports false when there is nothing to answer. func (h *pickHandlers) similar(w http.ResponseWriter, r *http.Request, anyKind bool) ([]SongRef, bool) { user, ok := UserFromContext(r.Context()) if !ok { WriteFail(w, r, ErrNotAuthorized, "Not authenticated") return nil, false } params := r.URL.Query() raw := params.Get("id") if raw == "" { WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id") return nil, false } id, ok := parseUUID(raw) if !ok { WriteFail(w, r, ErrDataNotFound, "Not found") return nil, false } count := clampInt(atoiDefault(params.Get("count"), 50), 1, 500) q := dbq.New(h.pool) seed, found, err := radioSeed(r.Context(), q, user.ID, id, anyKind) if err != nil { h.logger.Error("subsonic: similar songs seed", "err", err) WriteFail(w, r, ErrGeneric, "Radio unavailable") return nil, false } if !found { WriteFail(w, r, ErrDataNotFound, "Not found") return nil, false } picks, err := h.picker.Radio(r.Context(), q, user.ID, seed, count, nil) if err != nil { h.logger.Error("subsonic: similar songs", "err", err) WriteFail(w, r, ErrGeneric, "Radio unavailable") return nil, false } songs, err := songRefs(r.Context(), q, candidateTracks(picks)) if err != nil { h.logger.Error("subsonic: similar songs", "err", err) WriteFail(w, r, ErrGeneric, "Radio unavailable") return nil, false } return songs, true } // radioSeed finds the song a radio starts from. A song id is its own seed; an // album or an artist gives one of its playable songs at random, so asking // twice for the same artist need not start from the same song. func radioSeed(ctx context.Context, q *dbq.Queries, userID, id pgtype.UUID, anyKind bool) (pgtype.UUID, bool, error) { if anyKind { if t, err := q.GetTrackByID(ctx, id); err == nil && !t.MissingSince.Valid { return t.ID, true, nil } if _, err := q.GetAlbumByID(ctx, id); err == nil { tracks, err := q.ListTracksByAlbum(ctx, dbq.ListTracksByAlbumParams{AlbumID: id, UserID: userID}) if err != nil { return pgtype.UUID{}, false, err } ids := make([]pgtype.UUID, 0, len(tracks)) for _, t := range tracks { if !t.MissingSince.Valid { ids = append(ids, t.ID) } } return pickOne(ids) } } if _, err := q.GetArtistByID(ctx, id); err != nil { return pgtype.UUID{}, false, nil } rows, err := q.ListArtistTracksForUser(ctx, dbq.ListArtistTracksForUserParams{ArtistID: id, UserID: userID}) if err != nil { return pgtype.UUID{}, false, err } ids := make([]pgtype.UUID, 0, len(rows)) for _, row := range rows { if !row.Track.MissingSince.Valid { ids = append(ids, row.Track.ID) } } return pickOne(ids) } func pickOne(ids []pgtype.UUID) (pgtype.UUID, bool, error) { if len(ids) == 0 { return pgtype.UUID{}, false, nil } return ids[rand.IntN(len(ids))], true, nil }