sonda/internal/opensubsonic/media.go
tgiachi ccee5e8719 feat: OpenSubsonic playback, covers, lists and search
Apps can play and browse: stream and download send the original file (Range,
HEAD), getCoverArt serves the cover of an album, an artist or the album of a
song (300 pixels or less is the small one), getAlbumList2 knows every kind of
list, getRandomSongs and getSongsByGenre list songs, search3 finds artists,
albums and songs, and the starred calls answer with nothing so apps do not break.

- catalog.Filter has IDs to read albums and songs by id
- storage.SubsonicRepo answers the album and song lists (random, newest,
  frequent, recent, by name, by artist, by year, by genre)
2026-11-16 09:45:07 +01:00

437 lines
12 KiB
Go

package opensubsonic
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/images"
"git.kmalloc.org/squid/sonda/internal/streaming"
)
// Streams opens the audio file of a song: *streaming.Service.
type Streams interface {
Open(ctx context.Context, trackID int64) (*streaming.Stream, error)
}
// Covers builds the cover of an album: *images.Service.
type Covers interface {
AlbumCover(ctx context.Context, albumID int64, size images.Size) (*images.Cover, error)
}
// ArtistImages builds the picture of an artist: *images.Service.
type ArtistImages interface {
ArtistImage(ctx context.Context, artistID int64, size images.Size) (*images.Cover, error)
}
// served is what a call that wrote its own answer (a file, a picture) returns: there is nothing more to write.
var served = &Response{}
// stream sends the original file of a song, with Range, HEAD and conditional requests done by http.ServeContent.
// The file is sent as it is: Sonda does not transcode, so what an app asks for (format, bit rate) is ignored.
func (h *handler) stream(k *call) (*Response, *Error) { return h.send(k, false) }
// download sends the original file as an attachment.
func (h *handler) download(k *call) (*Response, *Error) { return h.send(k, true) }
func (h *handler) send(k *call, attachment bool) (*Response, *Error) {
id, bad := idParam(k, trackPrefix)
if bad != nil {
return nil, bad
}
st, err := h.Streams.Open(k.ctx, id)
switch {
case errors.Is(err, streaming.ErrNotFound), errors.Is(err, streaming.ErrFileMissing), errors.Is(err, streaming.ErrUnsafePath):
_ = k.c.Error(err)
return nil, notFound()
case err != nil:
_ = k.c.Error(err)
return nil, &Error{Code: ErrGeneric, Message: "the file could not be read"}
}
defer st.Close()
hdr := k.c.Writer.Header()
hdr.Set("Content-Type", st.ContentType)
hdr.Set("X-Content-Type-Options", "nosniff")
// The address carries the password of the device: never leak it through Referer.
hdr.Set("Referrer-Policy", "no-referrer")
hdr.Set("Cache-Control", "private, no-cache")
if attachment {
hdr.Set("Content-Disposition", `attachment; filename="`+safeName(st.Name)+`"`)
}
http.ServeContent(k.c.Writer, k.c.Request, st.Name, st.ModTime, st.File)
return served, nil
}
// safeName keeps a file name from closing the quotes of the header or adding a line to it.
func safeName(name string) string {
return strings.Map(func(r rune) rune {
if r == '"' || r == '\\' || r < ' ' || r == 0x7f {
return '_'
}
return r
}, name)
}
// smallest is the biggest size, in pixels, that is served from the small picture.
const smallest = 300
// coverArt sends the picture of an album, of an artist, or of the album of a song.
func (h *handler) coverArt(k *call) (*Response, *Error) {
raw := k.param("id")
if raw == "" {
return nil, missing("id")
}
size := images.Large
if px, err := strconv.Atoi(k.param("size")); err == nil && px > 0 && px <= smallest {
size = images.Small
}
var (
cover *images.Cover
err error
)
switch {
case strings.HasPrefix(raw, artistPrefix):
id, bad := idParam(k, artistPrefix)
if bad != nil {
return nil, bad
}
cover, err = h.ArtistImages.ArtistImage(k.ctx, id, size)
case strings.HasPrefix(raw, albumPrefix), strings.HasPrefix(raw, trackPrefix):
albumID, bad := h.albumOfCover(k, raw)
if bad != nil {
return nil, bad
}
cover, err = h.Covers.AlbumCover(k.ctx, albumID, size)
default:
return nil, notFound()
}
switch {
case err == nil:
case errors.Is(err, context.Canceled):
return served, nil // the app left: nobody is waiting
case errors.Is(err, images.ErrNoCover), errors.Is(err, images.ErrAlbumNotFound), errors.Is(err, images.ErrNoImage),
errors.Is(err, images.ErrArtistNotFound), errors.Is(err, images.ErrProviderDisabled), errors.Is(err, images.ErrNoID):
return nil, notFound()
default:
_ = k.c.Error(err)
return nil, &Error{Code: ErrGeneric, Message: "the picture could not be made"}
}
defer cover.File.Close()
hdr := k.c.Writer.Header()
hdr.Set("Content-Type", "image/jpeg")
hdr.Set("ETag", `"`+cover.ETag+`"`)
hdr.Set("Cache-Control", "private, max-age=3600") // it is the listener's own library
hdr.Set("X-Content-Type-Options", "nosniff")
hdr.Set("Referrer-Policy", "no-referrer")
http.ServeContent(k.c.Writer, k.c.Request, "cover.jpg", cover.ModTime, cover.File)
return served, nil
}
// albumOfCover is the album an id stands for: the album itself, or the album of a song.
func (h *handler) albumOfCover(k *call, raw string) (int64, *Error) {
if strings.HasPrefix(raw, albumPrefix) {
return idParam(k, albumPrefix)
}
id, bad := idParam(k, trackPrefix)
if bad != nil {
return 0, bad
}
t, err := h.Catalog.Track(k.ctx, id)
if err != nil {
return 0, failure(err)
}
if t.Album == nil {
return 0, notFound()
}
return t.Album.ID, nil
}
// ---- lists ----
const (
defaultCount = 10
maxCount = 500
defaultFind = 20
)
// count reads a whole number parameter that must be 0 or more. An absent one is the default; the answer never
// exceeds max.
func count(k *call, name string, def, max int) (int, *Error) {
raw := k.param(name)
if raw == "" {
return def, nil
}
n, err := strconv.Atoi(raw)
if err != nil || n < 0 {
return 0, &Error{Code: ErrGeneric, Message: "invalid value for " + name}
}
return min(n, max), nil
}
// folder reads musicFolderId: 0 is every library.
func folder(k *call) (int64, *Error) {
raw := k.param("musicFolderId")
if raw == "" {
return 0, nil
}
n, err := strconv.ParseInt(raw, 10, 64)
if err != nil || n < 1 {
return 0, notFound()
}
return n, nil
}
var listTypes = map[string]bool{
ListRandom: true, ListNewest: true, ListFrequent: true, ListRecent: true, ListStarred: true,
ListByName: true, ListByArtist: true, ListByYear: true, ListByGenre: true,
}
func (h *handler) albumList2(k *call) (*Response, *Error) {
kind := k.param("type")
if kind == "" {
return nil, missing("type")
}
if !listTypes[kind] {
return nil, &Error{Code: ErrGeneric, Message: "unknown list type: " + kind}
}
q := AlbumQuery{Type: kind, UserID: k.principal.UserID, Genre: k.param("genre")}
var bad *Error
if q.Size, bad = count(k, "size", defaultCount, maxCount); bad != nil {
return nil, bad
}
if q.Offset, bad = count(k, "offset", 0, 1<<30); bad != nil {
return nil, bad
}
if q.LibraryID, bad = folder(k); bad != nil {
return nil, bad
}
switch kind {
case ListByYear:
if k.param("fromYear") == "" || k.param("toYear") == "" {
return nil, missing("fromYear and toYear")
}
if q.FromYear, bad = count(k, "fromYear", 0, 9999); bad != nil {
return nil, bad
}
if q.ToYear, bad = count(k, "toYear", 0, 9999); bad != nil {
return nil, bad
}
case ListByGenre:
if q.Genre == "" {
return nil, missing("genre")
}
}
ids, err := h.Lists.AlbumIDs(k.ctx, q)
if err != nil {
return nil, failure(err)
}
albums, err := h.albumsByID(k.ctx, ids)
if err != nil {
return nil, failure(err)
}
out, err := h.albums(k.ctx, albums)
if err != nil {
return nil, failure(err)
}
return &Response{AlbumList2: &AlbumList2{Album: out}}, nil
}
func (h *handler) randomSongs(k *call) (*Response, *Error) {
q := SongQuery{Random: true, Genre: k.param("genre")}
var bad *Error
if q.Size, bad = count(k, "size", defaultCount, maxCount); bad != nil {
return nil, bad
}
if q.FromYear, bad = count(k, "fromYear", 0, 9999); bad != nil {
return nil, bad
}
if q.ToYear, bad = count(k, "toYear", 0, 9999); bad != nil {
return nil, bad
}
if q.LibraryID, bad = folder(k); bad != nil {
return nil, bad
}
songs, fail := h.songList(k, q)
if fail != nil {
return nil, fail
}
return &Response{RandomSongs: &SongList{Song: songs}}, nil
}
func (h *handler) songsByGenre(k *call) (*Response, *Error) {
q := SongQuery{Genre: k.param("genre")}
if q.Genre == "" {
return nil, missing("genre")
}
var bad *Error
if q.Size, bad = count(k, "count", defaultCount, maxCount); bad != nil {
return nil, bad
}
if q.Offset, bad = count(k, "offset", 0, 1<<30); bad != nil {
return nil, bad
}
if q.LibraryID, bad = folder(k); bad != nil {
return nil, bad
}
songs, fail := h.songList(k, q)
if fail != nil {
return nil, fail
}
return &Response{SongsByGenre: &SongList{Song: songs}}, nil
}
func (h *handler) songList(k *call, q SongQuery) ([]Child, *Error) {
ids, err := h.Lists.SongIDs(k.ctx, q)
if err != nil {
return nil, failure(err)
}
tracks, err := h.tracksByID(k.ctx, ids)
if err != nil {
return nil, failure(err)
}
songs, err := h.songs(k.ctx, tracks)
if err != nil {
return nil, failure(err)
}
return songs, nil
}
// albumsByID reads albums by their ids, in the order of the ids; an id that cannot be played is left out.
func (h *handler) albumsByID(ctx context.Context, ids []int64) ([]catalog.Album, error) {
byID := map[int64]catalog.Album{}
rest := ids
for len(rest) > 0 {
chunk := rest[:min(len(rest), catalog.MaxLimit)]
rest = rest[len(chunk):]
p, err := h.Catalog.Albums(ctx, catalog.Filter{IDs: chunk, Limit: len(chunk)})
if err != nil {
return nil, err
}
for _, a := range p.Items {
byID[a.ID] = a
}
}
return inOrder(ids, byID), nil
}
// tracksByID is the same for songs.
func (h *handler) tracksByID(ctx context.Context, ids []int64) ([]catalog.Track, error) {
byID := map[int64]catalog.Track{}
rest := ids
for len(rest) > 0 {
chunk := rest[:min(len(rest), catalog.MaxLimit)]
rest = rest[len(chunk):]
p, err := h.Catalog.Tracks(ctx, catalog.Filter{IDs: chunk, Limit: len(chunk)})
if err != nil {
return nil, err
}
for _, t := range p.Items {
byID[t.ID] = t
}
}
return inOrder(ids, byID), nil
}
func inOrder[T any](ids []int64, byID map[int64]T) []T {
out := make([]T, 0, len(ids))
for _, id := range ids {
if v, ok := byID[id]; ok {
out = append(out, v)
}
}
return out
}
// ---- search ----
func (h *handler) search3(k *call) (*Response, *Error) {
if _, given := k.c.Request.Form["query"]; !given {
return nil, missing("query")
}
query := strings.Trim(k.param("query"), `"`) // some apps send an empty search as ""
lib, bad := folder(k)
if bad != nil {
return nil, bad
}
var n [3]struct{ count, offset int }
for i, name := range []string{"artist", "album", "song"} {
if n[i].count, bad = count(k, name+"Count", defaultFind, maxCount); bad != nil {
return nil, bad
}
if n[i].offset, bad = count(k, name+"Offset", 0, 1<<30); bad != nil {
return nil, bad
}
}
filter := catalog.Filter{Query: query, LibraryID: lib}
res := &SearchResult{}
if n[0].count > 0 {
artists, err := window(n[0].count, n[0].offset, func(limit, offset int) (catalog.Page[catalog.Artist], error) {
f := filter
f.Limit, f.Offset = limit, offset
return h.Catalog.Artists(k.ctx, f)
})
if err != nil {
return nil, failure(err)
}
for _, a := range artists {
res.Artist = append(res.Artist, artistOf(a))
}
}
if n[1].count > 0 {
albums, err := window(n[1].count, n[1].offset, func(limit, offset int) (catalog.Page[catalog.Album], error) {
f := filter
f.Limit, f.Offset = limit, offset
return h.Catalog.Albums(k.ctx, f)
})
if err != nil {
return nil, failure(err)
}
if res.Album, err = h.albums(k.ctx, albums); err != nil {
return nil, failure(err)
}
}
if n[2].count > 0 {
tracks, err := window(n[2].count, n[2].offset, func(limit, offset int) (catalog.Page[catalog.Track], error) {
f := filter
f.Limit, f.Offset = limit, offset
return h.Catalog.Tracks(k.ctx, f)
})
if err != nil {
return nil, failure(err)
}
if res.Song, err = h.songs(k.ctx, tracks); err != nil {
return nil, failure(err)
}
}
return &Response{SearchResult3: res}, nil
}
// window reads n items from an offset, a page of the catalogue at a time: an app may ask for more than a page holds,
// and one that gets fewer than it asked for takes the list for ended.
func window[T any](n, offset int, fetch func(limit, offset int) (catalog.Page[T], error)) ([]T, error) {
var out []T
for len(out) < n {
p, err := fetch(min(n-len(out), catalog.MaxLimit), offset+len(out))
if err != nil {
return nil, err
}
out = append(out, p.Items...)
if len(p.Items) == 0 || offset+len(out) >= p.Total {
break
}
}
return out, nil
}
func (h *handler) starred2(*call) (*Response, *Error) {
return &Response{Starred2: &SearchResult{}}, nil
}
// nothing answers the calls that star, unstar or rate: Sonda has no stars yet, and an app should not break for it.
func nothing(*call) (*Response, *Error) { return &Response{}, nil }