release / web (push) Successful in 1m23s
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m16s
release / android (push) Successful in 4m50s
release / Build signed APK (push) Successful in 5m29s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
A Subsonic app reports "now playing" when a song starts and "played" when it ends. The played report used to close the now-playing row as a play of its own and write a second one, so every listen counted twice, and as a skip when the app sent the song's start time. The report now completes the app's own row for that song. A late report for an earlier song no longer cuts short the song playing now. Subsonic's scrobble doesn't say where a song was played from, so Minstrel remembers, per user and app, the daily mix the app last opened (for six hours). A play of a song in that mix is credited to it: the mix's metrics count it and its rotation moves on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
240 lines
7.4 KiB
Go
240 lines
7.4 KiB
Go
package subsonic
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
|
|
)
|
|
|
|
// mediaHandlers serves the bytes-on-the-wire endpoints: stream, download,
|
|
// getCoverArt, scrobble. Scrobble routes through playevents.Writer so
|
|
// Subsonic clients feed the same play_events table as the native /api/events.
|
|
type mediaHandlers struct {
|
|
pool *pgxpool.Pool
|
|
events *playevents.Writer
|
|
logger *slog.Logger
|
|
// recall credits a scrobble to the daily mix the app last opened
|
|
// (see mixRecall); nil credits nothing.
|
|
recall *mixRecall
|
|
}
|
|
|
|
func newMediaHandlers(pool *pgxpool.Pool, events *playevents.Writer, logger *slog.Logger) *mediaHandlers {
|
|
return &mediaHandlers{pool: pool, events: events, logger: logger}
|
|
}
|
|
|
|
// handleStream serves the raw track bytes. http.ServeContent gives us Range,
|
|
// If-Modified-Since, and ETag handling for free — the Subsonic spec requires
|
|
// Range support so clients can seek.
|
|
func (m *mediaHandlers) handleStream(w http.ResponseWriter, r *http.Request) {
|
|
m.serveTrack(w, r, false)
|
|
}
|
|
|
|
// handleDownload is stream with a filename and attachment disposition so
|
|
// browsers save rather than stream.
|
|
func (m *mediaHandlers) handleDownload(w http.ResponseWriter, r *http.Request) {
|
|
m.serveTrack(w, r, true)
|
|
}
|
|
|
|
func (m *mediaHandlers) serveTrack(w http.ResponseWriter, r *http.Request, attachment bool) {
|
|
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, "Track not found")
|
|
return
|
|
}
|
|
q := dbq.New(m.pool)
|
|
track, err := q.GetTrackByID(r.Context(), id)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
WriteFail(w, r, ErrDataNotFound, "Track not found")
|
|
return
|
|
}
|
|
WriteFail(w, r, ErrGeneric, "Failed to load track")
|
|
return
|
|
}
|
|
|
|
f, err := os.Open(track.FilePath)
|
|
if err != nil {
|
|
// File vanished between scan and now — treat as not found so clients
|
|
// can recover gracefully rather than assume a 5xx network blip.
|
|
WriteFail(w, r, ErrDataNotFound, "Track file not found")
|
|
return
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
|
|
info, err := f.Stat()
|
|
if err != nil {
|
|
WriteFail(w, r, ErrGeneric, "Failed to stat track file")
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", contentTypeForFormat(track.FileFormat))
|
|
w.Header().Set("Accept-Ranges", "bytes")
|
|
if attachment {
|
|
w.Header().Set("Content-Disposition",
|
|
fmt.Sprintf(`attachment; filename=%q`, filepath.Base(track.FilePath)))
|
|
}
|
|
http.ServeContent(w, r, filepath.Base(track.FilePath), info.ModTime(), f)
|
|
}
|
|
|
|
// handleGetCoverArt resolves an id (album, track, or cover-art id — all of
|
|
// which we key off the album UUID) to an image file. Scanner does not yet
|
|
// populate albums.cover_art_path, so the common path is the sidecar lookup.
|
|
func (m *mediaHandlers) handleGetCoverArt(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, "Cover art not found")
|
|
return
|
|
}
|
|
|
|
q := dbq.New(m.pool)
|
|
if path := coverArtPath(r.Context(), q, id); path != "" {
|
|
serveImage(w, r, path)
|
|
return
|
|
}
|
|
WriteFail(w, r, ErrDataNotFound, "Cover art not found")
|
|
}
|
|
|
|
// coverArtPath is the image for a cover-art id: an album's cover, a song's
|
|
// album cover, or an artist's picture (coverart.ResolveArtistPath). "" when
|
|
// the id names none of them or there is no image.
|
|
func coverArtPath(ctx context.Context, q *dbq.Queries, id pgtype.UUID) string {
|
|
if album, err := q.GetAlbumByID(ctx, id); err == nil {
|
|
return resolveAlbumCoverPath(ctx, q, album)
|
|
}
|
|
if track, err := q.GetTrackByID(ctx, id); err == nil {
|
|
album, err := q.GetAlbumByID(ctx, track.AlbumID)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return resolveAlbumCoverPath(ctx, q, album)
|
|
}
|
|
if artist, err := q.GetArtistByID(ctx, id); err == nil {
|
|
return coverart.ResolveArtistPath(ctx, q, artist)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// resolveAlbumCoverPath delegates to coverart.ResolveAlbumPath; kept as a
|
|
// local alias so the call sites in this file read naturally.
|
|
func resolveAlbumCoverPath(ctx context.Context, q *dbq.Queries, album dbq.Album) string {
|
|
return coverart.ResolveAlbumPath(ctx, q, album)
|
|
}
|
|
|
|
func serveImage(w http.ResponseWriter, r *http.Request, path string) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
WriteFail(w, r, ErrDataNotFound, "Cover art not found")
|
|
return
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
info, err := f.Stat()
|
|
if err != nil {
|
|
WriteFail(w, r, ErrGeneric, "Failed to stat cover art")
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", imageContentType(path))
|
|
http.ServeContent(w, r, filepath.Base(path), info.ModTime(), f)
|
|
}
|
|
|
|
func imageContentType(path string) string {
|
|
switch strings.ToLower(filepath.Ext(path)) {
|
|
case ".jpg", ".jpeg":
|
|
return "image/jpeg"
|
|
case ".png":
|
|
return "image/png"
|
|
case ".gif":
|
|
return "image/gif"
|
|
case ".webp":
|
|
return "image/webp"
|
|
default:
|
|
return "application/octet-stream"
|
|
}
|
|
}
|
|
|
|
// handleScrobble translates Subsonic scrobble calls into native play_events.
|
|
//
|
|
// submission=false (now playing) opens a play, leaving ended_at NULL.
|
|
// submission=true (played) completes that play when it is the same song,
|
|
// and otherwise writes a completed one; either way a listen is one row.
|
|
// play_events WHERE ended_at IS NULL is the source of truth for "currently
|
|
// playing". A song in the daily mix the app last opened is credited to
|
|
// that mix.
|
|
func (m *mediaHandlers) handleScrobble(w http.ResponseWriter, r *http.Request) {
|
|
params := r.URL.Query()
|
|
idStr := params.Get("id")
|
|
if idStr == "" {
|
|
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
|
|
return
|
|
}
|
|
trackID, ok := parseUUID(idStr)
|
|
if !ok {
|
|
WriteFail(w, r, ErrDataNotFound, "Track not found")
|
|
return
|
|
}
|
|
user, ok := UserFromContext(r.Context())
|
|
if !ok {
|
|
WriteFail(w, r, ErrGeneric, "Unauthenticated")
|
|
return
|
|
}
|
|
at := time.Now().UTC()
|
|
if t := params.Get("time"); t != "" {
|
|
// Subsonic spec uses ms-since-epoch; some clients send ISO 8601.
|
|
// Accept both for resilience.
|
|
if ms, err := strconv.ParseInt(t, 10, 64); err == nil {
|
|
at = time.UnixMilli(ms).UTC()
|
|
} else if parsed, err := time.Parse(time.RFC3339, t); err == nil {
|
|
at = parsed
|
|
}
|
|
}
|
|
clientID := params.Get("c")
|
|
source, err := m.recall.sourceFor(r.Context(), dbq.New(m.pool), user.ID, clientID, trackID)
|
|
if err != nil {
|
|
// Crediting a mix is a refinement; the play itself still counts.
|
|
m.logger.Warn("subsonic: scrobble mix lookup failed", "err", err)
|
|
source = ""
|
|
}
|
|
|
|
// Subsonic default is submission=true (completed play).
|
|
submission := strings.ToLower(params.Get("submission"))
|
|
switch submission {
|
|
case "true", "":
|
|
if err := m.events.RecordSyntheticCompletedPlay(r.Context(), user.ID, trackID, clientID, source, at); err != nil {
|
|
WriteFail(w, r, ErrGeneric, "Could not record play")
|
|
return
|
|
}
|
|
case "false":
|
|
if _, err := m.events.RecordPlayStartedWithSource(r.Context(), user.ID, trackID, clientID, source, "", at); err != nil {
|
|
WriteFail(w, r, ErrGeneric, "Could not record now-playing")
|
|
return
|
|
}
|
|
default:
|
|
// Unknown submission values: ack and ignore.
|
|
}
|
|
Write(w, r, struct{ Envelope }{Envelope: NewEnvelope("ok")})
|
|
}
|