A new setting, radio_in_apps, off until the person turns it on (Settings, Apps and devices, or PATCH /me/settings). With it off, the list of playlists of an OpenSubsonic app is only the playlists of the person, and a station asked for by id is not found. With it on, the stations come as playlists called Radio · Rock. - migration 0036: user_settings.radio_in_apps - usersettings, the settings API and the OpenAPI spec have the new field; the PATCH now keeps each setting apart (naming one no longer sets the other) - Settings has a switch
242 lines
9.6 KiB
Go
242 lines
9.6 KiB
Go
// Package opensubsonic speaks the OpenSubsonic API (Subsonic 1.16.1 and its open extensions), so that apps like
|
|
// Symfonium, Feishin or Amperfy can play the music of a Sonda server.
|
|
//
|
|
// It is mounted at /rest. A call logs in with the password of a device (see package devices), never with the account
|
|
// password: as an API key (`apiKey`), as Subsonic's token (`u`, `t`, `s`) or as the password itself (`u`, `p`). What
|
|
// a call can do is limited to the music of the person whose device it is.
|
|
package opensubsonic
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"encoding/xml"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"git.kmalloc.org/squid/sonda/internal/catalog"
|
|
"git.kmalloc.org/squid/sonda/internal/devices"
|
|
"git.kmalloc.org/squid/sonda/internal/library"
|
|
)
|
|
|
|
// Login checks the passwords of devices: *devices.Service.
|
|
type Login interface {
|
|
ByKey(ctx context.Context, key string) (devices.Principal, error)
|
|
ByToken(ctx context.Context, email, token, salt string) (devices.Principal, error)
|
|
ByPassword(ctx context.Context, email, password string) (devices.Principal, error)
|
|
}
|
|
|
|
// Catalog is what the calls need from catalog.Service.
|
|
type Catalog interface {
|
|
Artists(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Artist], error)
|
|
Albums(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Album], error)
|
|
Tracks(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Track], error)
|
|
Artist(ctx context.Context, id int64) (catalog.Artist, error)
|
|
Album(ctx context.Context, id int64) (catalog.Album, error)
|
|
Track(ctx context.Context, id int64) (catalog.Track, error)
|
|
}
|
|
|
|
// Libraries lists the libraries: *library.Libraries.
|
|
type Libraries interface {
|
|
List(ctx context.Context) ([]library.Library, error)
|
|
}
|
|
|
|
// Deps are the services the calls use.
|
|
type Deps struct {
|
|
Login Login
|
|
Catalog Catalog
|
|
Libraries Libraries
|
|
Extras Extras
|
|
Lists Lists
|
|
Streams Streams
|
|
Covers Covers
|
|
ArtistImages ArtistImages
|
|
Playlists Playlists
|
|
Favorites Favorites // optional: with none nothing is a favourite
|
|
Radio Radio // optional: with none the list of playlists is only the playlists of the person
|
|
Settings Settings // optional: with none the stations of the radio are not shown to apps
|
|
Listens Listens
|
|
Announcer Announcer // optional
|
|
ServerVersion string
|
|
}
|
|
|
|
type handler struct {
|
|
Deps
|
|
calls map[string]func(*call) (*Response, *Error)
|
|
}
|
|
|
|
// call is one request, with who made it.
|
|
type call struct {
|
|
c *gin.Context
|
|
ctx context.Context
|
|
principal devices.Principal
|
|
}
|
|
|
|
// param is the value of a parameter, from the address or the form.
|
|
func (k *call) param(name string) string { return k.c.Request.Form.Get(name) }
|
|
|
|
// Register mounts the API at /rest/{method} and /rest/{method}.view, for GET and for a form POST.
|
|
func Register(r gin.IRoutes, d Deps) {
|
|
h := &handler{Deps: d}
|
|
h.calls = map[string]func(*call) (*Response, *Error){
|
|
"ping": func(*call) (*Response, *Error) { return &Response{}, nil },
|
|
"getLicense": func(*call) (*Response, *Error) { return &Response{License: &License{Valid: true}}, nil },
|
|
"tokenInfo": h.tokenInfo,
|
|
"getMusicFolders": h.musicFolders,
|
|
"getArtists": h.artists,
|
|
"getArtist": h.artist,
|
|
"getAlbum": h.album,
|
|
"getSong": h.song,
|
|
"getGenres": h.genres,
|
|
"getAlbumList2": h.albumList2,
|
|
"getRandomSongs": h.randomSongs,
|
|
"getSongsByGenre": h.songsByGenre,
|
|
"search3": h.search3,
|
|
"getStarred2": h.starred2,
|
|
"star": h.star,
|
|
"unstar": h.unstar,
|
|
"setRating": nothing,
|
|
"stream": h.stream,
|
|
"download": h.download,
|
|
"getCoverArt": h.coverArt,
|
|
"getUser": h.user,
|
|
"getStarred": h.starred,
|
|
"getLyricsBySongId": func(*call) (*Response, *Error) { return &Response{LyricsList: &Empty{}}, nil },
|
|
"getLyrics": func(*call) (*Response, *Error) { return &Response{Lyrics: &Empty{}}, nil },
|
|
"getPlayQueueByIndex": nothing,
|
|
"savePlayQueueByIndex": nothing,
|
|
"startScan": func(*call) (*Response, *Error) { return &Response{ScanStatus: &ScanStatus{}}, nil },
|
|
"getArtistInfo": func(*call) (*Response, *Error) { return &Response{ArtistInfo: &Empty{}}, nil },
|
|
"getArtistInfo2": func(*call) (*Response, *Error) { return &Response{ArtistInfo2: &Empty{}}, nil },
|
|
"getAlbumInfo": func(*call) (*Response, *Error) { return &Response{AlbumInfo: &Empty{}}, nil },
|
|
"getAlbumInfo2": func(*call) (*Response, *Error) { return &Response{AlbumInfo: &Empty{}}, nil },
|
|
"getTopSongs": func(*call) (*Response, *Error) { return &Response{TopSongs: &Empty{}}, nil },
|
|
"getSimilarSongs": func(*call) (*Response, *Error) { return &Response{SimilarSongs: &Empty{}}, nil },
|
|
"getSimilarSongs2": func(*call) (*Response, *Error) { return &Response{SimilarSongs2: &Empty{}}, nil },
|
|
"getInternetRadioStations": func(*call) (*Response, *Error) { return &Response{InternetRadioStations: &Empty{}}, nil },
|
|
"getScanStatus": func(*call) (*Response, *Error) { return &Response{ScanStatus: &ScanStatus{}}, nil },
|
|
"getPlayQueue": nothing,
|
|
"savePlayQueue": nothing,
|
|
"getPlaylists": h.playlists,
|
|
"getPlaylist": h.playlist,
|
|
"createPlaylist": h.createPlaylist,
|
|
"updatePlaylist": h.updatePlaylist,
|
|
"deletePlaylist": h.deletePlaylist,
|
|
"scrobble": h.scrobble,
|
|
"getNowPlaying": h.nowPlaying,
|
|
}
|
|
r.GET("/rest/:method", h.serve)
|
|
r.HEAD("/rest/:method", h.serve)
|
|
r.POST("/rest/:method", h.serve)
|
|
}
|
|
|
|
// extensions are the OpenSubsonic extensions that are spoken.
|
|
var extensions = []Extension{
|
|
{Name: "apiKeyAuthentication", Versions: []int{1}},
|
|
{Name: "formPost", Versions: []int{1}},
|
|
}
|
|
|
|
func (h *handler) serve(c *gin.Context) {
|
|
// A web app on another address reads the answers too. What opens a call is a password of its own, never a cookie.
|
|
c.Header("Access-Control-Allow-Origin", "*")
|
|
_ = c.Request.ParseForm() // a malformed form only means the parameters are missing
|
|
method := strings.TrimSuffix(c.Param("method"), ".view")
|
|
asJSON := c.Request.Form.Get("f") == "json"
|
|
|
|
resp, fail := h.dispatch(c, method)
|
|
if fail != nil {
|
|
resp = &Response{Error: fail}
|
|
} else if resp == served {
|
|
return // the call wrote its own answer
|
|
}
|
|
h.write(c, asJSON, resp)
|
|
}
|
|
|
|
func (h *handler) dispatch(c *gin.Context, method string) (*Response, *Error) {
|
|
if method == "getOpenSubsonicExtensions" { // an app asks what is spoken before it has a password
|
|
return &Response{OpenSubsonicExtensions: extensions}, nil
|
|
}
|
|
fn, known := h.calls[method]
|
|
if !known {
|
|
// The request log shows the path and the error: what an app asks that Sonda does not answer is worth seeing.
|
|
_ = c.Error(errors.New("opensubsonic: unknown method " + method))
|
|
return nil, &Error{Code: ErrGeneric, Message: "unknown method: " + method}
|
|
}
|
|
k := &call{c: c, ctx: c.Request.Context()}
|
|
p, fail := h.login(k)
|
|
if fail != nil {
|
|
return nil, fail
|
|
}
|
|
k.principal = p
|
|
return fn(k)
|
|
}
|
|
|
|
// login checks who is calling: an API key, or an address with a token or a password.
|
|
func (h *handler) login(k *call) (devices.Principal, *Error) {
|
|
key, user, token, salt, password := k.param("apiKey"), k.param("u"), k.param("t"), k.param("s"), k.param("p")
|
|
if key != "" {
|
|
if user != "" || token != "" || salt != "" || password != "" {
|
|
return devices.Principal{}, &Error{Code: ErrAuthConflict, Message: "apiKey cannot be used with u, p, t or s"}
|
|
}
|
|
p, err := h.Login.ByKey(k.ctx, key)
|
|
return h.checked(p, err, ErrBadAPIKey, "invalid API key")
|
|
}
|
|
if user == "" {
|
|
return devices.Principal{}, missing("u")
|
|
}
|
|
switch {
|
|
case (token != "" || salt != "") && password != "":
|
|
return devices.Principal{}, &Error{Code: ErrAuthConflict, Message: "use either p or t and s"}
|
|
case token != "" && salt != "":
|
|
p, err := h.Login.ByToken(k.ctx, user, token, salt)
|
|
return h.checked(p, err, ErrWrongLogin, "wrong username or password")
|
|
case token != "" || salt != "":
|
|
return devices.Principal{}, missing("s and t")
|
|
case password != "":
|
|
p, err := h.Login.ByPassword(k.ctx, user, password)
|
|
return h.checked(p, err, ErrWrongLogin, "wrong username or password")
|
|
}
|
|
return devices.Principal{}, missing("p")
|
|
}
|
|
|
|
func (h *handler) checked(p devices.Principal, err error, code int, message string) (devices.Principal, *Error) {
|
|
switch {
|
|
case err == nil:
|
|
return p, nil
|
|
case errors.Is(err, devices.ErrBadCredentials):
|
|
return p, &Error{Code: code, Message: message}
|
|
default:
|
|
return p, &Error{Code: ErrGeneric, Message: "the login could not be checked"}
|
|
}
|
|
}
|
|
|
|
func missing(name string) *Error {
|
|
return &Error{Code: ErrMissingParam, Message: "required parameter is missing: " + name}
|
|
}
|
|
|
|
// write fills the envelope and writes the answer as JSON or as XML.
|
|
func (h *handler) write(c *gin.Context, asJSON bool, r *Response) {
|
|
r.Xmlns = "http://subsonic.org/restapi"
|
|
r.Version, r.Type, r.ServerVersion, r.OpenSubsonic = APIVersion, "sonda", h.ServerVersion, true
|
|
r.Status = "ok"
|
|
if r.Error != nil {
|
|
r.Status = "failed"
|
|
}
|
|
if asJSON {
|
|
out, err := json.Marshal(map[string]*Response{"subsonic-response": r})
|
|
if err != nil {
|
|
c.Status(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
c.Data(http.StatusOK, "application/json; charset=utf-8", out)
|
|
return
|
|
}
|
|
out, err := xml.Marshal(r)
|
|
if err != nil {
|
|
c.Status(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
c.Data(http.StatusOK, "text/xml; charset=utf-8", append([]byte(xml.Header), out...))
|
|
}
|