Files
minstrel/internal/subsonic/star.go
T
bvandeusenandClaude Opus 5.5 e1f270362d
release / go (push) Successful in 2m7s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m30s
release / android (push) Successful in 4m39s
release / Build signed APK (push) Successful in 5m10s
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
chore(release): everything that ships points at GitHub and GHCR (#7897)
- Module path: github.com/Fabled-Sword/minstrel, in go.mod, every
  import and the Dockerfile's version ldflags.
- buildinfo.ProjectURL, the contact outside services see in Minstrel's
  User-Agent: https://github.com/Fabled-Sword/minstrel.
- README's compose example pulls ghcr.io/fabled-sword/minstrel:latest.
- docs/security.md sends problem reports to the GitHub issues.
- The demo-library stack builds Minstrel from the checkout, since :dev
  is not published to GHCR.
- hygiene.go's same-site example uses example.com names.

The workbench CI (.gitea/, ci/, export-ignored) still builds and
publishes :dev to the private registry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:28:16 -05:00

283 lines
8.6 KiB
Go

package subsonic
import (
"context"
"errors"
"net/http"
"slices"
"strconv"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
"github.com/Fabled-Sword/minstrel/internal/eventbus"
"github.com/Fabled-Sword/minstrel/internal/playevents"
)
// handleStar implements /rest/star. Accepts any combination of id (track),
// albumId, artistId. All entities are validated before any insert; a single
// missing entity fails the whole call with Subsonic error 70.
func (m *mediaHandlers) handleStar(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
return
}
params := r.URL.Query()
q := dbq.New(m.pool)
trackID, err := resolveStarID(r.Context(), q, params.Get("id"), entityKindTrack)
if err != nil {
WriteFail(w, r, ErrDataNotFound, err.Error())
return
}
albumID, err := resolveStarID(r.Context(), q, params.Get("albumId"), entityKindAlbum)
if err != nil {
WriteFail(w, r, ErrDataNotFound, err.Error())
return
}
artistID, err := resolveStarID(r.Context(), q, params.Get("artistId"), entityKindArtist)
if err != nil {
WriteFail(w, r, ErrDataNotFound, err.Error())
return
}
if trackID.Valid {
// Stars the song: every copy of it.
liked, err := q.LikeTrack(r.Context(), dbq.LikeTrackParams{UserID: user.ID, TrackID: trackID})
if err != nil {
WriteFail(w, r, ErrGeneric, "Could not star track")
return
}
if slices.Contains(liked, trackID) {
_ = playevents.CaptureContextualLikeIfPlaying(r.Context(), q, user.ID, trackID, m.logger)
}
m.publishLike(user.ID, "track", true, eventbus.LedBy(trackID, liked)...)
}
if albumID.Valid {
if err := q.LikeAlbum(r.Context(), dbq.LikeAlbumParams{UserID: user.ID, AlbumID: albumID}); err != nil {
WriteFail(w, r, ErrGeneric, "Could not star album")
return
}
m.publishLike(user.ID, "album", true, albumID)
}
if artistID.Valid {
if err := q.LikeArtist(r.Context(), dbq.LikeArtistParams{UserID: user.ID, ArtistID: artistID}); err != nil {
WriteFail(w, r, ErrGeneric, "Could not star artist")
return
}
m.publishLike(user.ID, "artist", true, artistID)
}
Write(w, r, struct{ Envelope }{Envelope: NewEnvelope("ok")})
}
// handleUnstar mirrors handleStar but DELETEs. Missing entities are treated
// as a no-op rather than an error — Subsonic clients commonly call unstar
// on entities the server has never seen (cross-server library moves).
func (m *mediaHandlers) handleUnstar(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
return
}
params := r.URL.Query()
q := dbq.New(m.pool)
if t, ok := parseUUID(params.Get("id")); ok {
unliked, err := q.UnlikeTrack(r.Context(), dbq.UnlikeTrackParams{UserID: user.ID, TrackID: t})
_ = playevents.SoftDeleteContextualLikes(r.Context(), q, user.ID, t)
if err == nil {
m.publishLike(user.ID, "track", false, eventbus.LedBy(t, unliked)...)
}
}
if a, ok := parseUUID(params.Get("albumId")); ok {
if q.UnlikeAlbum(r.Context(), dbq.UnlikeAlbumParams{UserID: user.ID, AlbumID: a}) == nil {
m.publishLike(user.ID, "album", false, a)
}
}
if a, ok := parseUUID(params.Get("artistId")); ok {
if q.UnlikeArtist(r.Context(), dbq.UnlikeArtistParams{UserID: user.ID, ArtistID: a}) == nil {
m.publishLike(user.ID, "artist", false, a)
}
}
Write(w, r, struct{ Envelope }{Envelope: NewEnvelope("ok")})
}
type entityKind int
const (
entityKindTrack entityKind = iota
entityKindAlbum
entityKindArtist
)
// resolveStarID returns (uuid, nil) if the param is empty (no-op), or
// (uuid, nil) if the entity exists, or (zero, error) if the entity is
// missing/malformed. Non-empty malformed UUID is treated as a 'not found'
// per Subsonic semantics.
func resolveStarID(ctx context.Context, q *dbq.Queries, raw string, kind entityKind) (pgtype.UUID, error) {
if raw == "" {
return pgtype.UUID{}, nil
}
id, ok := parseUUID(raw)
if !ok {
return pgtype.UUID{}, errors.New("not found")
}
switch kind {
case entityKindTrack:
if _, err := q.GetTrackByID(ctx, id); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return pgtype.UUID{}, errors.New("track not found")
}
return pgtype.UUID{}, err
}
case entityKindAlbum:
if _, err := q.GetAlbumByID(ctx, id); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return pgtype.UUID{}, errors.New("album not found")
}
return pgtype.UUID{}, err
}
case entityKindArtist:
if _, err := q.GetArtistByID(ctx, id); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return pgtype.UUID{}, errors.New("artist not found")
}
return pgtype.UUID{}, err
}
}
return id, nil
}
func (m *mediaHandlers) handleGetStarred(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
return
}
q := dbq.New(m.pool)
songs, albums, artists, err := loadStarred(r.Context(), q, user.ID)
if err != nil {
WriteFail(w, r, ErrGeneric, "Could not load starred")
return
}
Write(w, r, GetStarredResponse{
Envelope: NewEnvelope("ok"),
Starred: GetStarredContainer{
Artists: artists,
Albums: albums,
Songs: songs,
},
})
}
func (m *mediaHandlers) handleGetStarred2(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
return
}
q := dbq.New(m.pool)
songs, albums, artists, err := loadStarred(r.Context(), q, user.ID)
if err != nil {
WriteFail(w, r, ErrGeneric, "Could not load starred")
return
}
Write(w, r, GetStarred2Response{
Envelope: NewEnvelope("ok"),
Starred2: StarredContainer{
Artists: artists,
Albums: albums,
Songs: songs,
},
})
}
// loadStarred fetches the user's full starred set in liked_at DESC order,
// projects to Subsonic refs (Song / Album / Artist).
func loadStarred(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) ([]SongRef, []AlbumRef, []ArtistRef, error) {
const cap = 500 // bounded for safety; getStarred is not paginated
songs := []SongRef{}
albums := []AlbumRef{}
artists := []ArtistRef{}
trackRows, err := q.ListPlayableLikedTrackRows(ctx, dbq.ListPlayableLikedTrackRowsParams{
UserID: userID, RowLimit: cap,
})
if err != nil {
return nil, nil, nil, err
}
gains := replayGains(ctx, q, trackRows)
for _, t := range trackRows {
album, err := q.GetAlbumByID(ctx, t.AlbumID)
if err != nil {
return nil, nil, nil, err
}
artist, err := q.GetArtistByID(ctx, t.ArtistID)
if err != nil {
return nil, nil, nil, err
}
songs = append(songs, songRef(t, album.Title, artist.Name, gains[t.ID]))
}
albumRows, err := q.ListLikedAlbumRows(ctx, dbq.ListLikedAlbumRowsParams{
UserID: userID, Limit: cap, Offset: 0,
})
if err != nil {
return nil, nil, nil, err
}
counts, err := playableCounts(ctx, q, albumRows)
if err != nil {
return nil, nil, nil, err
}
for _, a := range albumRows {
artist, err := q.GetArtistByID(ctx, a.ArtistID)
if err != nil {
return nil, nil, nil, err
}
albums = append(albums, albumRef(a, artist.Name, counts[a.ID], 0))
}
artistRows, err := q.ListLikedArtistRows(ctx, dbq.ListLikedArtistRowsParams{
UserID: userID, Limit: cap, Offset: 0,
})
if err != nil {
return nil, nil, nil, err
}
for _, a := range artistRows {
albums, err := q.ListAlbumsByArtist(ctx, a.ID)
if err != nil {
return nil, nil, nil, err
}
artists = append(artists, artistRef(a, len(albums)))
}
return songs, albums, artists, nil
}
// handleSetRating accepts a rating and keeps none. Minstrel's only rating is
// a like, which apps set with star. A rating is not turned into a like,
// because a rating is not a yes or no; and a low rating is never read as a
// dislike, because what a listener doesn't want is learned from skips. The
// call answers ok so an app's rating control does not show an error.
// rating must still be 0 to 5, as the spec has it.
func (m *mediaHandlers) handleSetRating(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
if params.Get("id") == "" || params.Get("rating") == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id and rating")
return
}
rating, err := strconv.Atoi(params.Get("rating"))
if err != nil || rating < 0 || rating > 5 {
WriteFail(w, r, ErrGeneric, "rating must be 0 to 5")
return
}
Write(w, r, NewEnvelope("ok"))
}
// publishLike tells the user's web and Android apps that a star changed
// here, with the same events the native like endpoints send, so an open
// tab's hearts and Liked list follow a like made in a Subsonic app.
func (m *mediaHandlers) publishLike(userID pgtype.UUID, entityType string, liked bool, ids ...pgtype.UUID) {
if m.bus == nil {
return
}
for _, id := range ids {
m.bus.Publish(eventbus.LikeChanged(userID.String(), entityType, id.String(), liked))
}
}