Apps can use the playlists of a person and report what they listened to. - getPlaylists, getPlaylist, createPlaylist (with songs, or in place of an existing one), updatePlaylist (name, comment, songs to add, places to remove), deletePlaylist: the same playlists as the web app - scrobble records a complete listen once however many times an app tries again, and shares it on Mastodon when the person connected it; a now playing message records nothing; getNowPlaying answers with nothing - README section on connecting other apps
360 lines
9.7 KiB
Go
360 lines
9.7 KiB
Go
package opensubsonic
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode"
|
|
|
|
"golang.org/x/text/unicode/norm"
|
|
|
|
"git.kmalloc.org/squid/sonda/internal/catalog"
|
|
)
|
|
|
|
// 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)
|
|
}
|
|
var index []Index
|
|
at := map[string]int{}
|
|
for _, 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, artistOf(a))
|
|
}
|
|
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.ctx, albums)
|
|
if err != nil {
|
|
return nil, failure(err)
|
|
}
|
|
return &Response{Artist: &ArtistWithAlbums{ArtistID3: artistOf(a), Album: out}}, nil
|
|
}
|
|
|
|
// albums describes albums, with what the catalogue does not carry.
|
|
func (h *handler) albums(ctx context.Context, list []catalog.Album) ([]AlbumID3, error) {
|
|
ids := make([]int64, len(list))
|
|
for i, a := range list {
|
|
ids[i] = a.ID
|
|
}
|
|
extras, err := h.Extras.Albums(ctx, ids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]AlbumID3, len(list))
|
|
for i, a := range list {
|
|
out[i] = albumOf(a, extras[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.ctx, []catalog.Album{al})
|
|
if err != nil {
|
|
return nil, failure(err)
|
|
}
|
|
songs, err := h.songs(k.ctx, 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.ctx, []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(ctx context.Context, list []catalog.Track) ([]Child, error) {
|
|
ids := make([]int64, len(list))
|
|
for i, t := range list {
|
|
ids[i] = t.ID
|
|
}
|
|
extras, err := h.Extras.Tracks(ctx, ids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]Child, len(list))
|
|
for i, t := range list {
|
|
out[i] = childOf(t, extras[t.ID])
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
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")
|
|
}
|