sonda/internal/opensubsonic/handler.go
tgiachi 1ae8e77d81 feat: OpenSubsonic core, login with a device password
/rest speaks the OpenSubsonic API (Subsonic 1.16.1) so that other apps can browse
the music of a server. A call logs in with the password of a device: an apiKey,
Subsonic's token (u, t, s) or the password itself (u, p). The account password is
never accepted there.

- devices: ByKey, ByToken, ByPassword and the note of last use
- opensubsonic package: JSON and XML answers, ping, getLicense,
  getOpenSubsonicExtensions, tokenInfo, getMusicFolders, getArtists, getArtist,
  getAlbum, getSong, getGenres
- storage.SubsonicRepo: year, genres, size, bitrate, suffix and added date
2026-11-16 09:32:11 +01:00

192 lines
6.7 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
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,
"getOpenSubsonicExtensions": nil, // answered before the login: see serve
}
r.GET("/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}
}
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 || fn == nil {
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...))
}