sonda/internal/opensubsonic/browse.go
tgiachi d6064763e7 fix: OpenSubsonic apps can log in: getUser and the calls that follow
Feishin asks getUser right after the login and failed on the missing user. getUser
now says who the login is, with the roles of an app (play, download, playlists,
covers; never admin), and only about the person of the login.

Also answered with nothing, because apps ask them straight away: getArtistInfo(2),
getAlbumInfo(2), getTopSongs, getSimilarSongs(2), getLyrics, getLyricsBySongId,
getInternetRadioStations, getScanStatus, startScan and the play queue calls, and
getStarred, the older way to ask for the favourites.

A call that is not known is now in the server log with its name.
2026-11-16 11:50:44 +01:00

424 lines
12 KiB
Go

package opensubsonic
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
"unicode"
"golang.org/x/text/unicode/norm"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/favorites"
)
// Ids are strings that say what they are: ar-12 an artist, al-7 an album, tr-99 a song.
const (
artistPrefix = "ar-"
albumPrefix = "al-"
trackPrefix = "tr-"
)
func artistID(id int64) string { return artistPrefix + strconv.FormatInt(id, 10) }
func albumID(id int64) string { return albumPrefix + strconv.FormatInt(id, 10) }
func trackID(id int64) string { return trackPrefix + strconv.FormatInt(id, 10) }
// idParam reads the id parameter, which must start with the prefix. A parameter that is not there is a missing one;
// one that is not an id of that kind is an id that is not found.
func idParam(k *call, prefix string) (int64, *Error) {
raw := k.param("id")
if raw == "" {
return 0, missing("id")
}
return idOf(raw, prefix)
}
// idOf reads an id of the kind the prefix says.
func idOf(raw, prefix string) (int64, *Error) {
n, err := strconv.ParseInt(strings.TrimPrefix(raw, prefix), 10, 64)
if !strings.HasPrefix(raw, prefix) || err != nil || n < 1 {
return 0, notFound()
}
return n, nil
}
func notFound() *Error { return &Error{Code: ErrNotFound, Message: "data not found"} }
func failure(err error) *Error {
if errors.Is(err, catalog.ErrNotFound) {
return notFound()
}
return &Error{Code: ErrGeneric, Message: "the music could not be read"}
}
// every reads all the pages of a list.
func every[T any](fetch func(offset int) (catalog.Page[T], error)) ([]T, error) {
var all []T
for {
p, err := fetch(len(all))
if err != nil {
return nil, err
}
all = append(all, p.Items...)
if len(p.Items) == 0 || len(all) >= p.Total {
return all, nil
}
}
}
func (h *handler) tokenInfo(k *call) (*Response, *Error) {
return &Response{TokenInfo: &TokenInfo{Username: k.principal.Email}}, nil
}
func (h *handler) musicFolders(k *call) (*Response, *Error) {
libs, err := h.Libraries.List(k.ctx)
if err != nil {
return nil, failure(err)
}
out := make([]MusicFolder, len(libs))
for i, l := range libs {
out[i] = MusicFolder{ID: l.ID, Name: l.Name}
}
return &Response{MusicFolders: &MusicFolders{MusicFolder: out}}, nil
}
func (h *handler) artists(k *call) (*Response, *Error) {
var lib int64
if v := k.param("musicFolderId"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 1 {
return nil, notFound()
}
lib = n
}
list, err := every(func(offset int) (catalog.Page[catalog.Artist], error) {
return h.Catalog.Artists(k.ctx, catalog.Filter{LibraryID: lib, Limit: catalog.MaxLimit, Offset: offset})
})
if err != nil {
return nil, failure(err)
}
described, err := h.artistList(k, list)
if err != nil {
return nil, failure(err)
}
var index []Index
at := map[string]int{}
for n, a := range list {
letter := indexLetter(a.Name)
i, ok := at[letter]
if !ok {
i = len(index)
at[letter] = i
index = append(index, Index{Name: letter, Artist: []ArtistID3{}})
}
index[i].Artist = append(index[i].Artist, described[n])
}
sortIndex(index)
if index == nil {
index = []Index{}
}
return &Response{Artists: &ArtistsID3{Index: index}}, nil
}
// indexLetter is the letter an artist is listed under: its first letter in capitals, or # for a name that starts
// with anything else.
func indexLetter(name string) string {
for _, r := range name {
if unicode.IsLetter(r) {
// "É" is listed with E: take the letter that is left when the accent is taken off.
for _, base := range norm.NFD.String(string(r)) {
return string(unicode.ToUpper(base))
}
}
break
}
return "#"
}
// sortIndex puts # first and the letters in order. The artists inside a group keep the order of the catalogue.
func sortIndex(index []Index) {
for i := 1; i < len(index); i++ {
for j := i; j > 0 && indexBefore(index[j].Name, index[j-1].Name); j-- {
index[j], index[j-1] = index[j-1], index[j]
}
}
}
func indexBefore(a, b string) bool {
if a == "#" || b == "#" {
return a == "#" && b != "#"
}
return a < b
}
func artistOf(a catalog.Artist) ArtistID3 {
return ArtistID3{ID: artistID(a.ID), Name: a.Name, AlbumCount: a.AlbumCount}
}
func (h *handler) artist(k *call) (*Response, *Error) {
id, bad := idParam(k, artistPrefix)
if bad != nil {
return nil, bad
}
a, err := h.Catalog.Artist(k.ctx, id)
if err != nil {
return nil, failure(err)
}
albums, err := every(func(offset int) (catalog.Page[catalog.Album], error) {
return h.Catalog.Albums(k.ctx, catalog.Filter{ArtistID: id, Limit: catalog.MaxLimit, Offset: offset})
})
if err != nil {
return nil, failure(err)
}
out, err := h.albums(k, albums)
if err != nil {
return nil, failure(err)
}
self, err := h.artistList(k, []catalog.Artist{a})
if err != nil {
return nil, failure(err)
}
return &Response{Artist: &ArtistWithAlbums{ArtistID3: self[0], Album: out}}, nil
}
// albums describes albums, with what the catalogue does not carry.
func (h *handler) albums(k *call, list []catalog.Album) ([]AlbumID3, error) {
ids := make([]int64, len(list))
for i, a := range list {
ids[i] = a.ID
}
extras, err := h.Extras.Albums(k.ctx, ids)
if err != nil {
return nil, err
}
marks, err := h.marks(k, favorites.Album, ids)
if err != nil {
return nil, err
}
out := make([]AlbumID3, len(list))
for i, a := range list {
out[i] = albumOf(a, extras[a.ID])
out[i].Starred = stamp(marks[a.ID])
}
return out, nil
}
func albumOf(a catalog.Album, e AlbumExtra) AlbumID3 {
out := AlbumID3{
ID: albumID(a.ID), Name: a.Title, CoverArt: albumID(a.ID), SongCount: a.TrackCount, Duration: seconds(a.DurationMs),
Created: stamp(e.AddedAt), Year: e.Year, Genres: genresOf(e.Genres),
}
if len(e.Genres) > 0 {
out.Genre = e.Genres[0]
}
if a.Artist != nil {
out.Artist, out.ArtistID, out.DisplayArtist = a.Artist.Name, artistID(a.Artist.ID), a.Artist.Name
out.Artists = []ArtistRef{{ID: artistID(a.Artist.ID), Name: a.Artist.Name}}
}
return out
}
func (h *handler) album(k *call) (*Response, *Error) {
id, bad := idParam(k, albumPrefix)
if bad != nil {
return nil, bad
}
al, err := h.Catalog.Album(k.ctx, id)
if err != nil {
return nil, failure(err)
}
tracks, err := every(func(offset int) (catalog.Page[catalog.Track], error) {
return h.Catalog.Tracks(k.ctx, catalog.Filter{AlbumID: id, Limit: catalog.MaxLimit, Offset: offset})
})
if err != nil {
return nil, failure(err)
}
out, err := h.albums(k, []catalog.Album{al})
if err != nil {
return nil, failure(err)
}
songs, err := h.songs(k, tracks)
if err != nil {
return nil, failure(err)
}
return &Response{Album: &AlbumWithSongs{AlbumID3: out[0], Song: songs}}, nil
}
func (h *handler) song(k *call) (*Response, *Error) {
id, bad := idParam(k, trackPrefix)
if bad != nil {
return nil, bad
}
t, err := h.Catalog.Track(k.ctx, id)
if err != nil {
return nil, failure(err)
}
songs, err := h.songs(k, []catalog.Track{t})
if err != nil {
return nil, failure(err)
}
return &Response{Song: &songs[0]}, nil
}
func (h *handler) genres(k *call) (*Response, *Error) {
list, err := h.Extras.Genres(k.ctx)
if err != nil {
return nil, failure(err)
}
out := make([]GenreEntry, len(list))
for i, g := range list {
out[i] = GenreEntry{Value: g.Name, SongCount: g.Songs, AlbumCount: g.Albums}
}
return &Response{Genres: &Genres{Genre: out}}, nil
}
// songs describes songs, with what the catalogue does not carry.
func (h *handler) songs(k *call, list []catalog.Track) ([]Child, error) {
ids := make([]int64, len(list))
for i, t := range list {
ids[i] = t.ID
}
extras, err := h.Extras.Tracks(k.ctx, ids)
if err != nil {
return nil, err
}
marks, err := h.marks(k, favorites.Track, ids)
if err != nil {
return nil, err
}
out := make([]Child, len(list))
for i, t := range list {
out[i] = childOf(t, extras[t.ID])
out[i].Starred = stamp(marks[t.ID])
}
return out, nil
}
// artistList describes artists, with the date each became a favourite of the person.
func (h *handler) artistList(k *call, list []catalog.Artist) ([]ArtistID3, error) {
ids := make([]int64, len(list))
for i, a := range list {
ids[i] = a.ID
}
marks, err := h.marks(k, favorites.Artist, ids)
if err != nil {
return nil, err
}
out := make([]ArtistID3, len(list))
for i, a := range list {
out[i] = artistOf(a)
out[i].Starred = stamp(marks[a.ID])
}
return out, nil
}
// marks says when each of the ids became a favourite of the person; it is empty when there are no favourites to ask.
func (h *handler) marks(k *call, kind favorites.Kind, ids []int64) (map[int64]time.Time, error) {
if h.Favorites == nil || len(ids) == 0 {
return nil, nil
}
return h.Favorites.Marks(k.ctx, k.principal.UserID, kind, ids)
}
func childOf(t catalog.Track, e TrackExtra) Child {
c := Child{
ID: trackID(t.ID), Title: t.Title, Track: t.TrackNo, DiscNumber: t.DiscNo, Duration: seconds(t.DurationMs),
Year: e.Year, Size: e.Size, BitRate: e.BitrateKbps, Suffix: e.Suffix, ContentType: contentType(e.Suffix),
Created: stamp(e.AddedAt), Type: "music", MediaType: "song", Genres: genresOf(e.Genres),
}
if len(e.Genres) > 0 {
c.Genre = e.Genres[0]
}
names := make([]string, len(t.Artists))
for i, a := range t.Artists {
names[i] = a.Name
c.Artists = append(c.Artists, ArtistRef{ID: artistID(a.ID), Name: a.Name})
}
if len(names) > 0 {
c.Artist = strings.Join(names, " & ")
c.DisplayArtist = c.Artist
c.ArtistID = artistID(t.Artists[0].ID)
}
albumName := ""
if t.Album != nil {
albumName = t.Album.Title
c.Album, c.AlbumID, c.Parent, c.CoverArt = t.Album.Title, albumID(t.Album.ID), albumID(t.Album.ID), albumID(t.Album.ID)
}
c.Path = pathOf(c.Artist, albumName, t, e.Suffix)
if g := t.ReplayGain; g != nil {
c.ReplayGain = &ReplayGain{TrackGain: g.TrackGain, AlbumGain: g.AlbumGain, TrackPeak: g.TrackPeak, AlbumPeak: g.AlbumPeak}
}
return c
}
// pathOf is a made-up path, "Artist/Album/01 - Title.flac": Sonda does not tell where its files are.
func pathOf(artist, album string, t catalog.Track, suffix string) string {
clean := strings.NewReplacer("/", "-", "\\", "-").Replace
name := t.Title
if t.TrackNo > 0 {
name = fmt.Sprintf("%02d - %s", t.TrackNo, name)
}
if suffix != "" {
name += "." + suffix
}
var parts []string
for _, p := range []string{artist, album} {
if p != "" {
parts = append(parts, clean(p))
}
}
return strings.Join(append(parts, clean(name)), "/")
}
func contentType(suffix string) string {
switch suffix {
case "mp3":
return "audio/mpeg"
case "flac":
return "audio/flac"
case "":
return ""
}
return "application/octet-stream"
}
func genresOf(names []string) []ItemGenre {
var out []ItemGenre
for _, n := range names {
out = append(out, ItemGenre{Name: n})
}
return out
}
// seconds rounds milliseconds to the seconds an app shows.
func seconds(ms int64) int { return int((ms + 500) / 1000) }
// stamp is a moment in the form of the Subsonic API: UTC, to the millisecond. A moment that is not known is left out.
func stamp(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format("2006-01-02T15:04:05.000Z")
}
// user tells who the login is and what the app may do. An app is for the music: it can play, make playlists and read
// covers, and it is never an admin, whoever the person is. It cannot ask about anybody else.
func (h *handler) user(k *call) (*Response, *Error) {
if name := k.param("username"); name != "" && !strings.EqualFold(strings.TrimSpace(name), k.principal.Email) {
return nil, &Error{Code: ErrNotAuthorized, Message: "an app can only ask about its own user"}
}
libs, err := h.Libraries.List(k.ctx)
if err != nil {
return nil, failure(err)
}
folders := make([]int64, len(libs))
for i, l := range libs {
folders[i] = l.ID
}
return &Response{User: &User{
Username: k.principal.Email, Email: k.principal.Email, ScrobblingEnabled: true,
DownloadRole: true, PlaylistRole: true, CoverArtRole: true, StreamRole: true, Folder: folders,
}}, nil
}