Merge branch master into ldap_auth

This commit is contained in:
Daniel
2023-11-10 13:47:47 -08:00
131 changed files with 6250 additions and 4887 deletions

No files matched your search

@@ -1,122 +0,0 @@
//nolint:revive
package artistinfocache
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/jinzhu/gorm"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/scrobble/lastfm"
)
const keepFor = 30 * time.Hour * 24
type ArtistInfoCache struct {
db *db.DB
lastfmClient *lastfm.Client
}
func New(db *db.DB, lastfmClient *lastfm.Client) *ArtistInfoCache {
return &ArtistInfoCache{db: db, lastfmClient: lastfmClient}
}
func (a *ArtistInfoCache) GetOrLookup(ctx context.Context, apiKey string, artistID int) (*db.ArtistInfo, error) {
var artist db.Artist
if err := a.db.Find(&artist, "id=?", artistID).Error; err != nil {
return nil, fmt.Errorf("find artist in db: %w", err)
}
var artistInfo db.ArtistInfo
if err := a.db.Find(&artistInfo, "id=?", artistID).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("find artist info in db: %w", err)
}
if artistInfo.ID == 0 || artistInfo.Biography == "" /* prev not found maybe */ || time.Since(artistInfo.UpdatedAt) > keepFor {
return a.Lookup(ctx, apiKey, &artist)
}
return &artistInfo, nil
}
func (a *ArtistInfoCache) Get(ctx context.Context, artistID int) (*db.ArtistInfo, error) {
var artistInfo db.ArtistInfo
if err := a.db.Find(&artistInfo, "id=?", artistID).Error; err != nil {
return nil, fmt.Errorf("find artist info in db: %w", err)
}
return &artistInfo, nil
}
func (a *ArtistInfoCache) Lookup(ctx context.Context, apiKey string, artist *db.Artist) (*db.ArtistInfo, error) {
var artistInfo db.ArtistInfo
artistInfo.ID = artist.ID
if err := a.db.FirstOrCreate(&artistInfo, "id=?", artistInfo.ID).Error; err != nil {
return nil, fmt.Errorf("first or create artist info: %w", err)
}
info, err := a.lastfmClient.ArtistGetInfo(apiKey, artist.Name)
if err != nil {
return nil, fmt.Errorf("get upstream info: %w", err)
}
artistInfo.ID = artist.ID
artistInfo.Biography = info.Bio.Summary
artistInfo.MusicBrainzID = info.MBID
artistInfo.LastFMURL = info.URL
var similar []string
for _, sim := range info.Similar.Artists {
similar = append(similar, sim.Name)
}
artistInfo.SetSimilarArtists(similar)
url, _ := a.lastfmClient.StealArtistImage(info.URL)
artistInfo.ImageURL = url
topTracksResponse, err := a.lastfmClient.ArtistGetTopTracks(apiKey, artist.Name)
if err != nil {
return nil, fmt.Errorf("get top tracks: %w", err)
}
var topTracks []string
for _, tr := range topTracksResponse.Tracks {
topTracks = append(topTracks, tr.Name)
}
artistInfo.SetTopTracks(topTracks)
if err := a.db.Save(&artistInfo).Error; err != nil {
return nil, fmt.Errorf("save upstream info: %w", err)
}
return &artistInfo, nil
}
func (a *ArtistInfoCache) Refresh(apiKey string, interval time.Duration) error {
ticker := time.NewTicker(interval)
for range ticker.C {
q := a.db.
Where("artist_infos.id IS NULL OR artist_infos.updated_at<?", time.Now().Add(-keepFor)).
Joins("LEFT JOIN artist_infos ON artist_infos.id=artists.id")
var artist db.Artist
if err := q.Find(&artist).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
log.Printf("error finding non cached artist: %v", err)
continue
}
if artist.ID == 0 {
continue
}
if _, err := a.Lookup(context.Background(), apiKey, &artist); err != nil {
log.Printf("error looking up non cached artist %s: %v", artist.Name, err)
continue
}
log.Printf("cached artist info for %q", artist.Name)
}
return nil
}
@@ -1,52 +0,0 @@
package artistinfocache
import (
"context"
"net/http"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/mockfs"
"go.senan.xyz/gonic/scrobble/lastfm"
"go.senan.xyz/gonic/scrobble/lastfm/mockclient"
)
func TestInfoCache(t *testing.T) {
m := mockfs.New(t)
m.AddItems()
m.ScanAndClean()
assert := assert.New(t)
var artist db.Artist
assert.NoError(m.DB().Preload("Info").Find(&artist).Error)
assert.Greater(artist.ID, 0)
assert.Nil(artist.Info)
var count atomic.Int32
lastfmClient := lastfm.NewClientCustom(mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
switch method := r.URL.Query().Get("method"); method {
case "artist.getInfo":
count.Add(1)
w.Write(mockclient.ArtistGetInfoResponse)
case "artist.getTopTracks":
w.Write(mockclient.ArtistGetTopTracksResponse)
}
}))
cache := New(m.DB(), lastfmClient)
_, err := cache.GetOrLookup(context.Background(), "", artist.ID)
require.NoError(t, err)
_, err = cache.GetOrLookup(context.Background(), "", artist.ID)
require.NoError(t, err)
require.Equal(t, int32(1), count.Load())
assert.NoError(m.DB().Preload("Info").Find(&artist, "id=?", artist.ID).Error)
assert.Greater(artist.ID, 0)
assert.NotNil(artist.Info)
assert.Equal("Summary", artist.Info.Biography)
}
+360 -42
View File
@@ -1,7 +1,9 @@
// Package ctrlsubsonic provides HTTP handlers for subsonic API
package ctrlsubsonic
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"encoding/xml"
"fmt"
@@ -9,12 +11,16 @@ import (
"log"
"net/http"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/handlerutil"
"go.senan.xyz/gonic/infocache/albuminfocache"
"go.senan.xyz/gonic/infocache/artistinfocache"
"go.senan.xyz/gonic/jukebox"
"go.senan.xyz/gonic/podcasts"
"go.senan.xyz/gonic/lastfm"
"go.senan.xyz/gonic/playlist"
"go.senan.xyz/gonic/podcast"
"go.senan.xyz/gonic/scanner"
"go.senan.xyz/gonic/scrobble"
"go.senan.xyz/gonic/scrobble/lastfm"
"go.senan.xyz/gonic/server/ctrlbase"
"go.senan.xyz/gonic/server/ctrlsubsonic/artistinfocache"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/transcode"
@@ -32,7 +38,7 @@ type MusicPath struct {
Alias, Path string
}
func PathsOf(paths []MusicPath) []string {
func MusicPaths(paths []MusicPath) []string {
var r []string
for _, p := range paths {
r = append(r, p.Path)
@@ -40,23 +46,346 @@ func PathsOf(paths []MusicPath) []string {
return r
}
type ProxyPathResolver func(in string) string
type Controller struct {
*ctrlbase.Controller
MusicPaths []MusicPath
PodcastsPath string
CacheAudioPath string
CacheCoverPath string
Jukebox *jukebox.Jukebox
Scrobblers []scrobble.Scrobbler
Podcasts *podcasts.Podcasts
Transcoder transcode.Transcoder
LastFMClient *lastfm.Client
ArtistInfoCache *artistinfocache.ArtistInfoCache
*http.ServeMux
dbc *db.DB
scanner *scanner.Scanner
musicPaths []MusicPath
podcastsPath string
cacheAudioPath string
cacheCoverPath string
jukebox *jukebox.Jukebox
playlistStore *playlist.Store
scrobblers []scrobble.Scrobbler
podcasts *podcast.Podcasts
transcoder transcode.Transcoder
lastFMClient *lastfm.Client
artistInfoCache *artistinfocache.ArtistInfoCache
albumInfoCache *albuminfocache.AlbumInfoCache
resolveProxyPath ProxyPathResolver
}
type metaResponse struct {
XMLName xml.Name `xml:"subsonic-response" json:"-"`
*spec.Response `json:"subsonic-response"`
func New(dbc *db.DB, scannr *scanner.Scanner, musicPaths []MusicPath, podcastsPath string, cacheAudioPath string, cacheCoverPath string, jukebox *jukebox.Jukebox, playlistStore *playlist.Store, scrobblers []scrobble.Scrobbler, podcasts *podcast.Podcasts, transcoder transcode.Transcoder, lastFMClient *lastfm.Client, artistInfoCache *artistinfocache.ArtistInfoCache, albumInfoCache *albuminfocache.AlbumInfoCache, resolveProxyPath ProxyPathResolver) (*Controller, error) {
c := Controller{
ServeMux: http.NewServeMux(),
dbc: dbc,
scanner: scannr,
musicPaths: musicPaths,
podcastsPath: podcastsPath,
cacheAudioPath: cacheAudioPath,
cacheCoverPath: cacheCoverPath,
jukebox: jukebox,
playlistStore: playlistStore,
scrobblers: scrobblers,
podcasts: podcasts,
transcoder: transcoder,
lastFMClient: lastFMClient,
artistInfoCache: artistInfoCache,
albumInfoCache: albumInfoCache,
resolveProxyPath: resolveProxyPath,
}
chain := handlerutil.Chain(
withParams,
withRequiredParams,
withUser(dbc),
)
c.Handle("/getLicense", chain(resp(c.ServeGetLicence)))
c.Handle("/ping", chain(resp(c.ServePing)))
c.Handle("/getOpenSubsonicExtensions", chain(resp(c.ServeGetOpenSubsonicExtensions)))
c.Handle("/getMusicFolders", chain(resp(c.ServeGetMusicFolders)))
c.Handle("/getScanStatus", chain(resp(c.ServeGetScanStatus)))
c.Handle("/scrobble", chain(resp(c.ServeScrobble)))
c.Handle("/startScan", chain(resp(c.ServeStartScan)))
c.Handle("/getUser", chain(resp(c.ServeGetUser)))
c.Handle("/getPlaylists", chain(resp(c.ServeGetPlaylists)))
c.Handle("/getPlaylist", chain(resp(c.ServeGetPlaylist)))
c.Handle("/createPlaylist", chain(resp(c.ServeCreatePlaylist)))
c.Handle("/updatePlaylist", chain(resp(c.ServeUpdatePlaylist)))
c.Handle("/deletePlaylist", chain(resp(c.ServeDeletePlaylist)))
c.Handle("/savePlayQueue", chain(resp(c.ServeSavePlayQueue)))
c.Handle("/getPlayQueue", chain(resp(c.ServeGetPlayQueue)))
c.Handle("/getSong", chain(resp(c.ServeGetSong)))
c.Handle("/getRandomSongs", chain(resp(c.ServeGetRandomSongs)))
c.Handle("/getSongsByGenre", chain(resp(c.ServeGetSongsByGenre)))
c.Handle("/jukeboxControl", chain(resp(c.ServeJukebox)))
c.Handle("/getBookmarks", chain(resp(c.ServeGetBookmarks)))
c.Handle("/createBookmark", chain(resp(c.ServeCreateBookmark)))
c.Handle("/deleteBookmark", chain(resp(c.ServeDeleteBookmark)))
c.Handle("/getTopSongs", chain(resp(c.ServeGetTopSongs)))
c.Handle("/getSimilarSongs", chain(resp(c.ServeGetSimilarSongs)))
c.Handle("/getSimilarSongs2", chain(resp(c.ServeGetSimilarSongsTwo)))
c.Handle("/getLyrics", chain(resp(c.ServeGetLyrics)))
// raw
c.Handle("/getCoverArt", chain(respRaw(c.ServeGetCoverArt)))
c.Handle("/stream", chain(respRaw(c.ServeStream)))
c.Handle("/download", chain(respRaw(c.ServeStream)))
c.Handle("/getAvatar", chain(respRaw(c.ServeGetAvatar)))
// browse by tag
c.Handle("/getAlbum", chain(resp(c.ServeGetAlbum)))
c.Handle("/getAlbumList2", chain(resp(c.ServeGetAlbumListTwo)))
c.Handle("/getArtist", chain(resp(c.ServeGetArtist)))
c.Handle("/getArtists", chain(resp(c.ServeGetArtists)))
c.Handle("/search3", chain(resp(c.ServeSearchThree)))
c.Handle("/getStarred2", chain(resp(c.ServeGetStarredTwo)))
c.Handle("/getArtistInfo2", chain(resp(c.ServeGetArtistInfoTwo)))
c.Handle("/getAlbumInfo2", chain(resp(c.ServeGetAlbumInfoTwo)))
// browse by folder
c.Handle("/getIndexes", chain(resp(c.ServeGetIndexes)))
c.Handle("/getMusicDirectory", chain(resp(c.ServeGetMusicDirectory)))
c.Handle("/getAlbumList", chain(resp(c.ServeGetAlbumList)))
c.Handle("/search2", chain(resp(c.ServeSearchTwo)))
c.Handle("/getGenres", chain(resp(c.ServeGetGenres)))
c.Handle("/getArtistInfo", chain(resp(c.ServeGetArtistInfo)))
c.Handle("/getStarred", chain(resp(c.ServeGetStarred)))
// star / rating
c.Handle("/star", chain(resp(c.ServeStar)))
c.Handle("/unstar", chain(resp(c.ServeUnstar)))
c.Handle("/setRating", chain(resp(c.ServeSetRating)))
// podcasts
c.Handle("/getPodcasts", chain(resp(c.ServeGetPodcasts)))
c.Handle("/getNewestPodcasts", chain(resp(c.ServeGetNewestPodcasts)))
c.Handle("/downloadPodcastEpisode", chain(resp(c.ServeDownloadPodcastEpisode)))
c.Handle("/createPodcastChannel", chain(resp(c.ServeCreatePodcastChannel)))
c.Handle("/refreshPodcasts", chain(resp(c.ServeRefreshPodcasts)))
c.Handle("/deletePodcastChannel", chain(resp(c.ServeDeletePodcastChannel)))
c.Handle("/deletePodcastEpisode", chain(resp(c.ServeDeletePodcastEpisode)))
// internet radio
c.Handle("/getInternetRadioStations", chain(resp(c.ServeGetInternetRadioStations)))
c.Handle("/createInternetRadioStation", chain(resp(c.ServeCreateInternetRadioStation)))
c.Handle("/updateInternetRadioStation", chain(resp(c.ServeUpdateInternetRadioStation)))
c.Handle("/deleteInternetRadioStation", chain(resp(c.ServeDeleteInternetRadioStation)))
c.Handle("/", chain(resp(c.ServeNotFound)))
return &c, nil
}
type (
handlerSubsonic func(r *http.Request) *spec.Response
handlerSubsonicRaw func(w http.ResponseWriter, r *http.Request) *spec.Response
)
func resp(h handlerSubsonic) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := writeResp(w, r, h(r)); err != nil {
log.Printf("error writing subsonic response: %v\n", err)
}
})
}
func respRaw(h handlerSubsonicRaw) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := writeResp(w, r, h(w, r)); err != nil {
log.Printf("error writing raw subsonic response: %v\n", err)
}
})
}
func withParams(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := params.New(r)
withParams := context.WithValue(r.Context(), CtxParams, params)
next.ServeHTTP(w, r.WithContext(withParams))
})
}
func withRequiredParams(next http.Handler) http.Handler {
requiredParameters := []string{
"u", "c",
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := r.Context().Value(CtxParams).(params.Params)
for _, req := range requiredParameters {
if _, err := params.Get(req); err != nil {
_ = writeResp(w, r, spec.NewError(10, "please provide a %q parameter", req))
return
}
}
next.ServeHTTP(w, r)
})
}
func (c *Controller) WithUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := r.Context().Value(CtxParams).(params.Params)
// ignoring errors here, a middleware has already ensured they exist
username, _ := params.Get("u")
password, _ := params.Get("p")
token, _ := params.Get("t")
salt, _ := params.Get("s")
passwordAuth := token == "" && salt == ""
tokenAuth := password == ""
if tokenAuth == passwordAuth {
_ = writeResp(w, r, spec.NewError(10,
"please provide `t` and `s`, or just `p`"))
return
}
user := c.DB.GetUserByName(username)
newLDAPUser := false
if user == nil {
newLDAPUser = true
// Because the user wasn't found we can now try
// to use LDAP. ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
if ldapFQDN != "" && err == nil {
// The configuration page wouldn't allow these setting to not be set
// while LDAP is enabled (a FQDN/IP is set).
bindUID, _ := c.DB.GetSetting("ldap_bind_user")
bindPWD, _ := c.DB.GetSetting("ldap_bind_user_password")
ldapPort, _ := c.DB.GetSetting("ldap_port")
baseDN, _ := c.DB.GetSetting("ldap_base_dn")
filter, _ := c.DB.GetSetting("ldap_filter")
tls, _ := c.DB.GetSetting("ldap_tls")
// Now, we can try to connect to the LDAP server.
l, err := createLDAPconnection(tls, ldapFQDN, ldapPort)
if err != nil {
// Return a generic error.
_ = writeResp(w, r, spec.NewError(0, "Failed to connect to LDAP server."))
return
}
defer l.Close()
// After we have a connection, let's try binding
_, err = l.SimpleBind(&ldap.SimpleBindRequest{
Username: fmt.Sprintf("uid=%s,%s", bindUID, baseDN),
Password: bindPWD,
})
if err != nil {
log.Println("Failed to bind to LDAP:", err)
_ = writeResp(w, r, spec.NewError(40, "Wrong username or password."))
return
}
searchReq := ldap.NewSearchRequest(
baseDN,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&%s(uid=%s))", filter, ldap.EscapeFilter(username)),
[]string{"dn"},
nil,
)
result, err := l.Search(searchReq)
if err != nil {
log.Println("failed to query LDAP:", err)
}
if len(result.Entries) > 1 {
_ = writeResp(w, r, spec.NewError(40, "Ambiguous user: `%s`", username))
} else if len(result.Entries) == 1 {
user := db.User{
Name: username,
Password: "", // no password because we want auth to fail.
}
if err := c.DB.Create(&user).Error; err != nil {
fmt.Println("User created via LDAP:", username)
}
} else {
_ = writeResp(w, r, spec.NewError(40, "invalid username `%s`", username))
return
}
} else {
_ = writeResp(w, r, spec.NewError(40,
"invalid username `%s`", username))
return
}
}
var credsOk bool
if tokenAuth && !newLDAPUser && user != nil {
credsOk = checkCredsToken(user.Password, token, salt)
} else if !newLDAPUser && user != nil {
credsOk = checkCredsBasic(user.Password, password)
}
if !credsOk {
// Because internal authentication failed, we can now try to use LDAP, if
// it was enabled by the user.
ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
if ldapFQDN != "" && err == nil {
// The configuration page wouldn't allow these setting to not be set
// while LDAP is enabled (a FQDN/IP is set).
ldapPort, _ := c.DB.GetSetting("ldap_port")
baseDN, _ := c.DB.GetSetting("ldap_base_dn")
tls, _ := c.DB.GetSetting("ldap_tls")
// Now, we can try to connect to the LDAP server.
l, err := createLDAPconnection(tls, ldapFQDN, ldapPort)
if err != nil {
// Return a generic error.
_ = writeResp(w, r, spec.NewError(0, "Failed to connect to LDAP server."))
return
}
defer l.Close()
// After we have a connection, let's try binding
_, err = l.SimpleBind(&ldap.SimpleBindRequest{
Username: fmt.Sprintf("uid=%s,%s", username, baseDN),
Password: password,
})
if err == nil {
withUser := context.WithValue(r.Context(), CtxUser, user)
next.ServeHTTP(w, r.WithContext(withUser))
return
}
}
_ = writeResp(w, r, spec.NewError(40, "invalid password"))
return
}
withUser := context.WithValue(r.Context(), CtxUser, user)
next.ServeHTTP(w, r.WithContext(withUser))
})
}
func createLDAPconnection(tls string, fqdn string, port string) (*ldap.Conn, error) {
protocol := "ldap"
if tls == "true" {
protocol = "ldaps"
}
// Now, we can try to connect to the LDAP server.
l, err := ldap.DialURL(fmt.Sprintf("%s://%s:%s", protocol, fqdn, port))
if err != nil {
// Warn the server and return a generic error.
log.Println("Failed to connect to LDAP server", err)
return nil, err
}
return l, nil
}
func checkCredsToken(password, token, salt string) bool {
toHash := fmt.Sprintf("%s%s", password, salt)
hash := md5.Sum([]byte(toHash))
expToken := hex.EncodeToString(hash[:])
return token == expToken
}
func checkCredsBasic(password, given string) bool {
if len(given) >= 4 && given[:4] == "enc:" {
bytes, _ := hex.DecodeString(given[4:])
given = string(bytes)
}
return password == given
}
type errWriter struct {
@@ -79,8 +408,14 @@ func writeResp(w http.ResponseWriter, r *http.Request, resp *spec.Response) erro
log.Printf("subsonic error code %d: %s", resp.Error.Code, resp.Error.Message)
}
res := metaResponse{Response: resp}
var res struct {
XMLName xml.Name `xml:"subsonic-response" json:"-"`
*spec.Response `json:"subsonic-response"`
}
res.Response = resp
params := r.Context().Value(CtxParams).(params.Params)
ew := &errWriter{w: w}
switch v, _ := params.Get("f"); v {
case "json":
@@ -90,6 +425,7 @@ func writeResp(w http.ResponseWriter, r *http.Request, resp *spec.Response) erro
return fmt.Errorf("marshal to json: %w", err)
}
ew.write(data)
case "jsonp":
w.Header().Set("Content-Type", "application/javascript")
data, err := json.Marshal(res)
@@ -102,34 +438,16 @@ func writeResp(w http.ResponseWriter, r *http.Request, resp *spec.Response) erro
ew.write([]byte("("))
ew.write(data)
ew.write([]byte(");"))
default:
w.Header().Set("Content-Type", "application/xml")
data, err := xml.MarshalIndent(res, "", " ")
if err != nil {
return fmt.Errorf("marshal to xml: %w", err)
}
ew.write(data)
}
return ew.err
}
type (
handlerSubsonic func(r *http.Request) *spec.Response
handlerSubsonicRaw func(w http.ResponseWriter, r *http.Request) *spec.Response
)
func (c *Controller) H(h handlerSubsonic) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := writeResp(w, r, h(r)); err != nil {
log.Printf("error writing subsonic response: %v\n", err)
}
})
}
func (c *Controller) HR(h handlerSubsonicRaw) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := writeResp(w, r, h(w, r)); err != nil {
log.Printf("error writing raw subsonic response: %v\n", err)
}
})
}
+23 -22
View File
@@ -1,3 +1,4 @@
//nolint:thelper
package ctrlsubsonic
import (
@@ -8,7 +9,6 @@ import (
"net/http/httptest"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
@@ -19,11 +19,16 @@ import (
"go.senan.xyz/gonic"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/mockfs"
"go.senan.xyz/gonic/server/ctrlbase"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/transcode"
)
func TestMain(m *testing.M) {
gonic.Version = ""
log.SetOutput(io.Discard)
os.Exit(m.Run())
}
var testCamelExpr = regexp.MustCompile("([a-z0-9])([A-Z])")
const (
@@ -48,7 +53,7 @@ func makeGoldenPath(test string) string {
snake := testCamelExpr.ReplaceAllString(test, "${1}_${2}")
lower := strings.ToLower(snake)
relPath := strings.ReplaceAll(lower, "/", "_")
return path.Join("testdata", relPath)
return filepath.Join("testdata", relPath)
}
func makeHTTPMock(query url.Values) (*httptest.ResponseRecorder, *http.Request) {
@@ -78,12 +83,16 @@ func makeHTTPMockWithAdmin(query url.Values) (*httptest.ResponseRecorder, *http.
return rr, req
}
func runQueryCases(t *testing.T, contr *Controller, h handlerSubsonic, cases []*queryCase) {
func runQueryCases(t *testing.T, h handlerSubsonic, cases []*queryCase) {
t.Helper()
for _, qc := range cases {
qc := qc
t.Run(qc.expectPath, func(t *testing.T) {
t.Helper()
t.Parallel()
rr, req := makeHTTPMock(qc.params)
contr.H(h).ServeHTTP(rr, req)
resp(h).ServeHTTP(rr, req)
body := rr.Body.String()
if status := rr.Code; status != http.StatusOK {
t.Fatalf("didn't give a 200\n%s", body)
@@ -92,7 +101,7 @@ func runQueryCases(t *testing.T, contr *Controller, h handlerSubsonic, cases []*
goldenPath := makeGoldenPath(t.Name())
goldenRegen := os.Getenv("GONIC_REGEN")
if goldenRegen == "*" || (goldenRegen != "" && strings.HasPrefix(t.Name(), goldenRegen)) {
_ = os.WriteFile(goldenPath, []byte(body), 0600)
_ = os.WriteFile(goldenPath, []byte(body), 0o600)
t.Logf("golden file %q regenerated for %s", goldenPath, t.Name())
t.SkipNow()
}
@@ -121,14 +130,13 @@ func runQueryCases(t *testing.T, contr *Controller, h handlerSubsonic, cases []*
}
}
func makeController(t *testing.T) *Controller { return makec(t, []string{""}, false) }
func makeControllerRoots(t *testing.T, r []string) *Controller { return makec(t, r, false) }
func makeControllerAudio(t *testing.T) *Controller { return makec(t, []string{""}, true) }
func makeController(tb testing.TB) *Controller { return makec(tb, []string{""}, false) }
func makeControllerRoots(tb testing.TB, r []string) *Controller { return makec(tb, r, false) }
func makec(t *testing.T, roots []string, audio bool) *Controller {
t.Helper()
func makec(tb testing.TB, roots []string, audio bool) *Controller {
tb.Helper()
m := mockfs.NewWithDirs(t, roots)
m := mockfs.NewWithDirs(tb, roots)
for _, root := range roots {
m.AddItemsPrefixWithCovers(root)
if !audio {
@@ -147,18 +155,11 @@ func makec(t *testing.T, roots []string, audio bool) *Controller {
absRoots = append(absRoots, MusicPath{Path: filepath.Join(m.TmpDir(), root)})
}
base := &ctrlbase.Controller{DB: m.DB()}
contr := &Controller{
Controller: base,
MusicPaths: absRoots,
Transcoder: transcode.NewFFmpegTranscoder(),
dbc: m.DB(),
musicPaths: absRoots,
transcoder: transcode.NewFFmpegTranscoder(),
}
return contr
}
func TestMain(m *testing.M) {
gonic.Version = ""
log.SetOutput(io.Discard)
os.Exit(m.Run())
}
+5 -5
View File
@@ -15,7 +15,7 @@ import (
func (c *Controller) ServeGetBookmarks(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User)
bookmarks := []*db.Bookmark{}
err := c.DB.
err := c.dbc.
Where("user_id=?", user.ID).
Find(&bookmarks).
Error
@@ -40,7 +40,7 @@ func (c *Controller) ServeGetBookmarks(r *http.Request) *spec.Response {
switch specid.IDT(bookmark.EntryIDType) {
case specid.Track:
var track db.Track
err := c.DB.
err := c.dbc.
Preload("Album").
Find(&track, "id=?", bookmark.EntryID).
Error
@@ -64,14 +64,14 @@ func (c *Controller) ServeCreateBookmark(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an `id` parameter")
}
bookmark := &db.Bookmark{}
c.DB.FirstOrCreate(bookmark, db.Bookmark{
c.dbc.FirstOrCreate(bookmark, db.Bookmark{
UserID: user.ID,
EntryIDType: string(id.Type),
EntryID: id.Value,
})
bookmark.Comment = params.GetOr("comment", "")
bookmark.Position = params.GetOrInt("position", 0)
c.DB.Save(bookmark)
c.dbc.Save(bookmark)
return spec.NewResponse()
}
@@ -82,7 +82,7 @@ func (c *Controller) ServeDeleteBookmark(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "please provide an `id` parameter")
}
c.DB.
c.dbc.
Where("user_id=? AND entry_id_type=? AND entry_id=?", user.ID, id.Type, id.Value).
Delete(&db.Bookmark{})
return spec.NewResponse()
+42 -37
View File
@@ -21,16 +21,16 @@ import (
func (c *Controller) ServeGetIndexes(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
rootQ := c.DB.
rootQ := c.dbc.
Select("id").
Model(&db.Album{}).
Where("parent_id IS NULL")
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
rootQ = rootQ.
Where("root_dir=?", m)
}
var folders []*db.Album
c.DB.
c.dbc.
Select("*, count(sub.id) child_count").
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID).
@@ -70,13 +70,13 @@ func (c *Controller) ServeGetMusicDirectory(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User)
childrenObj := []*spec.TrackChild{}
folder := &db.Album{}
c.DB.
c.dbc.
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID).
First(folder, id.Value)
// start looking for child childFolders in the current dir
var childFolders []*db.Album
c.DB.
c.dbc.
Where("parent_id=?", id.Value).
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID).
@@ -87,16 +87,17 @@ func (c *Controller) ServeGetMusicDirectory(r *http.Request) *spec.Response {
}
// start looking for child childTracks in the current dir
var childTracks []*db.Track
c.DB.
c.dbc.
Where("album_id=?", id.Value).
Preload("Album").
Preload("Album.Artists").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Order("filename").
Find(&childTracks)
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, ch := range childTracks {
toAppend := spec.NewTCTrackByFolder(ch, folder)
@@ -105,8 +106,7 @@ func (c *Controller) ServeGetMusicDirectory(r *http.Request) *spec.Response {
toAppend.ContentType = "audio/mpeg"
toAppend.Suffix = "mp3"
}
toAppend.TranscodedContentType = transcodeMIME
toAppend.TranscodedSuffix = transcodeSuffix
toAppend.TranscodeMeta = transcodeMeta
childrenObj = append(childrenObj, toAppend)
}
// respond section
@@ -116,12 +116,12 @@ func (c *Controller) ServeGetMusicDirectory(r *http.Request) *spec.Response {
}
// ServeGetAlbumList handles the getAlbumList view.
// changes to this function should be reflected in in _by_tags.go's
// changes to this function should be reflected in _by_tags.go's
// getAlbumListTwo() function
func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
q := c.DB.DB
q := c.dbc.DB
switch v, _ := params.Get("type"); v {
case "alphabeticalByArtist":
q = q.Joins(`
@@ -131,8 +131,7 @@ func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
case "alphabeticalByName":
q = q.Order("right_path")
case "byYear":
y1, y2 :=
params.GetOrInt("fromYear", 1800),
y1, y2 := params.GetOrInt("fromYear", 1800),
params.GetOrInt("toYear", 2200)
// support some clients sending wrong order like DSub
q = q.Where("tag_year BETWEEN ? AND ?", min(y1, y2), max(y1, y2))
@@ -161,11 +160,14 @@ func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
case "starred":
q = q.Joins("JOIN album_stars ON albums.id=album_stars.album_id AND album_stars.user_id=?", user.ID)
q = q.Order("right_path")
case "highest":
q = q.Joins("JOIN album_ratings ON album_ratings.album_id=albums.id AND album_ratings.user_id=?", user.ID)
q = q.Order("album_ratings.rating DESC")
default:
return spec.NewError(10, "unknown value `%s` for parameter 'type'", v)
return spec.NewError(10, "unknown value %q for parameter 'type'", v)
}
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
var folders []*db.Album
@@ -207,16 +209,16 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
results := &spec.SearchResultTwo{}
// search "artists"
rootQ := c.DB.
rootQ := c.dbc.
Select("id").
Model(&db.Album{}).
Where("parent_id IS NULL")
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
rootQ = rootQ.Where("root_dir=?", m)
}
var artists []*db.Album
q := c.DB.Where(`parent_id IN ?`, rootQ.SubQuery())
q := c.dbc.Where(`parent_id IN ?`, rootQ.SubQuery())
for _, s := range queries {
q = q.Where(`right_path LIKE ? OR right_path_u_dec LIKE ?`, s, s)
}
@@ -233,15 +235,17 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
// search "albums"
var albums []*db.Album
q = c.DB.Joins("JOIN album_artists ON album_artists.album_id=albums.id")
q = c.dbc.
Joins("JOIN album_artists ON album_artists.album_id=albums.id")
for _, s := range queries {
q = q.Where(`right_path LIKE ? OR right_path_u_dec LIKE ?`, s, s)
}
q = q.Preload("AlbumStar", "user_id=?", user.ID).
q = q.
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID).
Offset(params.GetOrInt("albumOffset", 0)).
Limit(params.GetOrInt("albumCount", 20))
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
if err := q.Find(&albums).Error; err != nil {
@@ -253,15 +257,17 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
// search tracks
var tracks []*db.Track
q = c.DB.Preload("Album")
q = c.dbc.Preload("Album")
for _, s := range queries {
q = q.Where(`filename LIKE ? OR filename LIKE ?`, s, s)
}
q = q.Preload("TrackStar", "user_id=?", user.ID).
q = q.
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Offset(params.GetOrInt("songOffset", 0)).
Limit(params.GetOrInt("songCount", 20))
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.
Joins("JOIN albums ON albums.id=tracks.album_id").
Where("albums.root_dir=?", m)
@@ -270,12 +276,11 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
return spec.NewError(0, "find tracks: %v", err)
}
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, t := range tracks {
track := spec.NewTCTrackByFolder(t, t.Album)
track.TranscodedContentType = transcodeMIME
track.TranscodedSuffix = transcodeSuffix
track.TranscodeMeta = transcodeMeta
results.Tracks = append(results.Tracks, track)
}
@@ -295,16 +300,16 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
results := &spec.Starred{}
// "artists"
rootQ := c.DB.
rootQ := c.dbc.
Select("id").
Model(&db.Album{}).
Where("parent_id IS NULL")
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
rootQ = rootQ.Where("root_dir=?", m)
}
var artists []*db.Album
q := c.DB.
q := c.dbc.
Where(`parent_id IN ?`, rootQ.SubQuery()).
Joins("JOIN album_stars ON albums.id=album_stars.album_id").
Where("album_stars.user_id=?", user.ID).
@@ -319,13 +324,13 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
// "albums"
var albums []*db.Album
q = c.DB.
q = c.dbc.
Joins("JOIN album_artists ON album_artists.album_id=albums.id").
Joins("JOIN album_stars ON albums.id=album_stars.album_id").
Where("album_stars.user_id=?", user.ID).
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID)
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
if err := q.Find(&albums).Error; err != nil {
@@ -337,13 +342,14 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
// tracks
var tracks []*db.Track
q = c.DB.
q = c.dbc.
Preload("Album").
Joins("JOIN track_stars ON tracks.id=track_stars.track_id").
Where("track_stars.user_id=?", user.ID).
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID)
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.
Joins("JOIN albums ON albums.id=tracks.album_id").
Where("albums.root_dir=?", m)
@@ -352,12 +358,11 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
return spec.NewError(0, "find tracks: %v", err)
}
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, t := range tracks {
track := spec.NewTCTrackByFolder(t, t.Album)
track.TranscodedContentType = transcodeMIME
track.TranscodedSuffix = transcodeSuffix
track.TranscodeMeta = transcodeMeta
results.Tracks = append(results.Tracks, track)
}
@@ -8,9 +8,9 @@ import (
)
func TestGetIndexes(t *testing.T) {
t.Parallel()
contr := makeControllerRoots(t, []string{"m-0", "m-1"})
runQueryCases(t, contr, contr.ServeGetIndexes, []*queryCase{
runQueryCases(t, contr.ServeGetIndexes, []*queryCase{
{url.Values{}, "no_args", false},
{url.Values{"musicFolderId": {"0"}}, "with_music_folder_1", false},
{url.Values{"musicFolderId": {"1"}}, "with_music_folder_2", false},
@@ -18,9 +18,9 @@ func TestGetIndexes(t *testing.T) {
}
func TestGetMusicDirectory(t *testing.T) {
t.Parallel()
contr := makeController(t)
runQueryCases(t, contr, contr.ServeGetMusicDirectory, []*queryCase{
runQueryCases(t, contr.ServeGetMusicDirectory, []*queryCase{
{url.Values{"id": {"al-2"}}, "without_tracks", false},
{url.Values{"id": {"al-3"}}, "with_tracks", false},
})
@@ -29,8 +29,7 @@ func TestGetMusicDirectory(t *testing.T) {
func TestGetAlbumList(t *testing.T) {
t.Parallel()
contr := makeController(t)
runQueryCases(t, contr, contr.ServeGetAlbumList, []*queryCase{
runQueryCases(t, contr.ServeGetAlbumList, []*queryCase{
{url.Values{"type": {"alphabeticalByArtist"}}, "alpha_artist", false},
{url.Values{"type": {"alphabeticalByName"}}, "alpha_name", false},
{url.Values{"type": {"newest"}}, "newest", false},
@@ -41,8 +40,7 @@ func TestGetAlbumList(t *testing.T) {
func TestSearchTwo(t *testing.T) {
t.Parallel()
contr := makeController(t)
runQueryCases(t, contr, contr.ServeSearchTwo, []*queryCase{
runQueryCases(t, contr.ServeSearchTwo, []*queryCase{
{url.Values{"query": {"art"}}, "q_art", false},
{url.Values{"query": {"alb"}}, "q_alb", false},
{url.Values{"query": {"tra"}}, "q_tra", false},
+165 -135
View File
@@ -3,6 +3,7 @@ package ctrlsubsonic
import (
"errors"
"fmt"
"log"
"math"
"net/http"
"net/url"
@@ -13,6 +14,7 @@ import (
"github.com/jinzhu/gorm"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/handlerutil"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
@@ -22,17 +24,18 @@ func (c *Controller) ServeGetArtists(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
var artists []*db.Artist
q := c.DB.
Select("*, count(sub.id) album_count").
q := c.dbc.
Select("*, count(album_artists.album_id) album_count").
Joins("JOIN album_artists ON album_artists.artist_id=artists.id").
Joins("JOIN albums sub ON sub.id=album_artists.album_id").
Preload("ArtistStar", "user_id=?", user.ID).
Preload("ArtistRating", "user_id=?", user.ID).
Preload("Info").
Group("artists.id").
Order("artists.name COLLATE NOCASE")
if m := getMusicFolder(c.MusicPaths, params); m != "" {
q = q.Where("sub.root_dir=?", m)
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.
Joins("JOIN albums ON albums.id=album_artists.album_id").
Where("albums.root_dir=?", m)
}
if err := q.Find(&artists).Error; err != nil {
return spec.NewError(10, "error finding artists: %v", err)
@@ -65,28 +68,29 @@ func (c *Controller) ServeGetArtist(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "please provide an `id` parameter")
}
artist := &db.Artist{}
c.DB.
Preload("Albums", func(db *gorm.DB) *gorm.DB {
var artist db.Artist
c.dbc.
Preload("Appearances", func(db *gorm.DB) *gorm.DB {
return db.
Select("*, count(sub.id) child_count, sum(sub.length) duration").
Joins("LEFT JOIN tracks sub ON albums.id=sub.album_id").
Order("albums.right_path").
Group("albums.id")
}).
Preload("Albums.Artists").
Preload("Albums.Genres").
Preload("Appearances.Artists").
Preload("Appearances.Genres").
Preload("Info").
Preload("ArtistStar", "user_id=?", user.ID).
Preload("ArtistRating", "user_id=?", user.ID).
First(artist, id.Value)
First(&artist, id.Value)
sub := spec.NewResponse()
sub.Artist = spec.NewArtistByTags(artist)
sub.Artist.Albums = make([]*spec.Album, len(artist.Albums))
for i, album := range artist.Albums {
sub.Artist = spec.NewArtistByTags(&artist)
sub.Artist.Albums = make([]*spec.Album, len(artist.Appearances))
for i, album := range artist.Appearances {
sub.Artist.Albums[i] = spec.NewAlbumByTags(album, album.Artists)
}
sub.Artist.AlbumCount = len(artist.Albums)
sub.Artist.AlbumCount = len(artist.Appearances)
return sub
}
@@ -98,7 +102,7 @@ func (c *Controller) ServeGetAlbum(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an `id` parameter")
}
album := &db.Album{}
err = c.DB.
err = c.dbc.
Select("albums.*, count(tracks.id) child_count, sum(tracks.length) duration").
Joins("LEFT JOIN tracks ON tracks.album_id=albums.id").
Preload("Artists").
@@ -106,6 +110,7 @@ func (c *Controller) ServeGetAlbum(r *http.Request) *spec.Response {
Preload("Tracks", func(db *gorm.DB) *gorm.DB {
return db.
Order("tracks.tag_disc_number, tracks.tag_track_number").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID)
}).
@@ -120,18 +125,17 @@ func (c *Controller) ServeGetAlbum(r *http.Request) *spec.Response {
sub.Album = spec.NewAlbumByTags(album, album.Artists)
sub.Album.Tracks = make([]*spec.TrackChild, len(album.Tracks))
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, track := range album.Tracks {
sub.Album.Tracks[i] = spec.NewTrackByTags(track, album)
sub.Album.Tracks[i].TranscodedContentType = transcodeMIME
sub.Album.Tracks[i].TranscodedSuffix = transcodeSuffix
sub.Album.Tracks[i].TranscodeMeta = transcodeMeta
}
return sub
}
// ServeGetAlbumListTwo handles the getAlbumList2 view.
// changes to this function should be reflected in in _by_folder.go's
// changes to this function should be reflected in _by_folder.go's
// getAlbumList() function
func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
@@ -140,7 +144,7 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "please provide a `type` parameter")
}
q := c.DB.DB
q := c.dbc.DB
switch listType {
case "alphabeticalByArtist":
q = q.Joins("JOIN artists ON artists.id=album_artists.artist_id")
@@ -148,8 +152,7 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
case "alphabeticalByName":
q = q.Order("tag_title")
case "byYear":
y1, y2 :=
params.GetOrInt("fromYear", 1800),
y1, y2 := params.GetOrInt("fromYear", 1800),
params.GetOrInt("toYear", 2200)
// support some clients sending wrong order like DSub
q = q.Where("tag_year BETWEEN ? AND ?", min(y1, y2), max(y1, y2))
@@ -173,10 +176,13 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
case "starred":
q = q.Joins("JOIN album_stars ON albums.id=album_stars.album_id AND album_stars.user_id=?", user.ID)
q = q.Order("tag_title")
case "highest":
q = q.Joins("JOIN album_ratings ON album_ratings.album_id=albums.id AND album_ratings.user_id=?", user.ID)
q = q.Order("album_ratings.rating DESC")
default:
return spec.NewError(10, "unknown value `%s` for parameter 'type'", listType)
return spec.NewError(10, "unknown value %q for parameter 'type'", listType)
}
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
var albums []*db.Album
@@ -219,7 +225,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
// search artists
var artists []*db.Artist
q := c.DB.
q := c.dbc.
Select("*, count(albums.id) album_count").
Group("artists.id")
for _, s := range queries {
@@ -233,7 +239,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
Preload("Info").
Offset(params.GetOrInt("artistOffset", 0)).
Limit(params.GetOrInt("artistCount", 20))
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m)
}
if err := q.Find(&artists).Error; err != nil {
@@ -245,7 +251,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
// search albums
var albums []*db.Album
q = c.DB.
q = c.dbc.
Preload("Artists").
Preload("Genres").
Preload("AlbumStar", "user_id=?", user.ID).
@@ -256,7 +262,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
q = q.
Offset(params.GetOrInt("albumOffset", 0)).
Limit(params.GetOrInt("albumCount", 20))
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
if err := q.Find(&albums).Error; err != nil {
@@ -268,10 +274,11 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
// search tracks
var tracks []*db.Track
q = c.DB.
q = c.dbc.
Preload("Album").
Preload("Album.Artists").
Preload("Genres").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID)
for _, s := range queries {
@@ -279,7 +286,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
}
q = q.Offset(params.GetOrInt("songOffset", 0)).
Limit(params.GetOrInt("songCount", 20))
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.
Joins("JOIN albums ON albums.id=tracks.album_id").
Where("albums.root_dir=?", m)
@@ -288,12 +295,11 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
return spec.NewError(0, "find tracks: %v", err)
}
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, t := range tracks {
track := spec.NewTrackByTags(t, t.Album)
track.TranscodedContentType = transcodeMIME
track.TranscodedSuffix = transcodeSuffix
track.TranscodeMeta = transcodeMeta
results.Tracks = append(results.Tracks, track)
}
@@ -310,25 +316,21 @@ func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
}
var artist db.Artist
err = c.DB.
err = c.dbc.
Where("id=?", id.Value).
Find(&artist).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(70, "artist with id `%s` not found", id)
return spec.NewError(70, "artist with id %q not found", id)
}
sub := spec.NewResponse()
sub.ArtistInfoTwo = &spec.ArtistInfo{}
apiKey, _ := c.DB.GetSetting(db.LastFMAPIKey)
if apiKey == "" {
return sub
}
info, err := c.ArtistInfoCache.GetOrLookup(r.Context(), apiKey, artist.ID)
info, err := c.artistInfoCache.GetOrLookup(r.Context(), artist.ID)
if err != nil {
return spec.NewError(0, "fetching artist info: %v", err)
log.Printf("error fetching artist info from lastfm: %v", err)
return sub
}
sub.ArtistInfoTwo.Biography = info.Biography
@@ -354,13 +356,13 @@ func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
break
}
var artist db.Artist
err = c.DB.
err = c.dbc.
Preload("Info").
Select("artists.*, count(albums.id) album_count").
Where("name=?", similarName).
Joins("LEFT JOIN album_artists ON album_artists.artist_id=artists.id").
Joins("LEFT JOIN albums ON albums.id=album_artists.album_id").
Joins("LEFT JOIN artist_appearances ON artist_appearances.artist_id=artists.id").
Joins("LEFT JOIN albums ON albums.id=artist_appearances.album_id").
Group("artists.id").
Preload("Info").
Find(&artist).
Error
if errors.Is(err, gorm.ErrRecordNotFound) && !inclNotPresent {
@@ -382,9 +384,41 @@ func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
return sub
}
func (c *Controller) ServeGetAlbumInfoTwo(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
if err != nil {
return spec.NewError(10, "please provide an `id` parameter")
}
var album db.Album
err = c.dbc.
Where("id=?", id.Value).
Find(&album).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(70, "album with id %q not found", id)
}
sub := spec.NewResponse()
sub.AlbumInfo = &spec.AlbumInfo{}
info, err := c.albumInfoCache.GetOrLookup(r.Context(), album.ID)
if err != nil {
log.Printf("error fetching album info from lastfm: %v", err)
return sub
}
sub.AlbumInfo.Notes = info.Notes
sub.AlbumInfo.MusicBrainzID = info.MusicBrainzID
sub.AlbumInfo.LastFMURL = info.LastFMURL
return sub
}
func (c *Controller) ServeGetGenres(_ *http.Request) *spec.Response {
var genres []*db.Genre
c.DB.
c.dbc.
Select(`*,
(SELECT count(1) FROM album_genres WHERE genre_id=genres.id) album_count,
(SELECT count(1) FROM track_genres WHERE genre_id=genres.id) track_count`).
@@ -408,17 +442,18 @@ func (c *Controller) ServeGetSongsByGenre(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an `genre` parameter")
}
var tracks []*db.Track
q := c.DB.
q := c.dbc.
Joins("JOIN albums ON tracks.album_id=albums.id").
Joins("JOIN track_genres ON track_genres.track_id=tracks.id").
Joins("JOIN genres ON track_genres.genre_id=genres.id AND genres.name=?", genre).
Preload("Album").
Preload("Album.Artists").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Offset(params.GetOrInt("offset", 0)).
Limit(params.GetOrInt("count", 10))
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m)
}
q = q.Group("tracks.id")
@@ -430,12 +465,11 @@ func (c *Controller) ServeGetSongsByGenre(r *http.Request) *spec.Response {
List: make([]*spec.TrackChild, len(tracks)),
}
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, t := range tracks {
sub.TracksByGenre.List[i] = spec.NewTrackByTags(t, t.Album)
sub.TracksByGenre.List[i].TranscodedContentType = transcodeMIME
sub.TracksByGenre.List[i].TranscodedSuffix = transcodeSuffix
sub.TracksByGenre.List[i].TranscodeMeta = transcodeMeta
}
return sub
@@ -449,16 +483,18 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
// artists
var artists []*db.Artist
q := c.DB.
q := c.dbc.
Select("artists.*, count(albums.id) album_count").
Joins("JOIN artist_stars ON artist_stars.artist_id=artists.id").
Where("artist_stars.user_id=?", user.ID).
Joins("JOIN album_artists ON album_artists.artist_id=artists.id").
Joins("JOIN albums ON albums.id=album_artists.album_id").
Joins("JOIN artist_appearances ON artist_appearances.artist_id=artists.id").
Joins("JOIN albums ON albums.id=artist_appearances.album_id").
Order("artist_stars.star_date DESC").
Preload("ArtistStar", "user_id=?", user.ID).
Preload("ArtistRating", "user_id=?", user.ID).
Preload("Info").
Group("artists.id")
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m)
}
if err := q.Find(&artists).Error; err != nil {
@@ -470,13 +506,14 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
// albums
var albums []*db.Album
q = c.DB.
q = c.dbc.
Joins("JOIN album_stars ON album_stars.album_id=albums.id").
Where("album_stars.user_id=?", user.ID).
Order("album_stars.star_date DESC").
Preload("Artists").
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID)
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m)
}
if err := q.Find(&albums).Error; err != nil {
@@ -488,13 +525,16 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
// tracks
var tracks []*db.Track
q = c.DB.
q = c.dbc.
Joins("JOIN track_stars ON tracks.id=track_stars.track_id").
Where("track_stars.user_id=?", user.ID).
Order("track_stars.star_date DESC").
Preload("Album").
Preload("Album.Artists").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID)
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.
Joins("JOIN albums ON albums.id=tracks.album_id").
Where("albums.root_dir=?", m)
@@ -503,12 +543,11 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
return spec.NewError(0, "find tracks: %v", err)
}
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, t := range tracks {
track := spec.NewTrackByTags(t, t.Album)
track.TranscodedContentType = transcodeMIME
track.TranscodedSuffix = transcodeSuffix
track.TranscodeMeta = transcodeMeta
results.Tracks = append(results.Tracks, track)
}
@@ -518,8 +557,8 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
}
func (c *Controller) genArtistCoverURL(r *http.Request, artist *db.Artist, size int) string {
coverURL, _ := url.Parse(c.BaseURL(r))
coverURL.Path = c.Path("/rest/getCoverArt")
coverURL, _ := url.Parse(handlerutil.BaseURL(r))
coverURL.Path = c.resolveProxyPath("/rest/getCoverArt")
query := r.URL.Query()
query.Set("id", artist.SID().String())
@@ -538,17 +577,14 @@ func (c *Controller) ServeGetTopSongs(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an `artist` parameter")
}
var artist db.Artist
if err := c.DB.Where("name=?", artistName).Find(&artist).Error; err != nil {
if err := c.dbc.Where("name=?", artistName).Find(&artist).Error; err != nil {
return spec.NewError(0, "finding artist by name: %v", err)
}
apiKey, _ := c.DB.GetSetting(db.LastFMAPIKey)
if apiKey == "" {
return spec.NewResponse()
}
info, err := c.ArtistInfoCache.GetOrLookup(r.Context(), apiKey, artist.ID)
info, err := c.artistInfoCache.GetOrLookup(r.Context(), artist.ID)
if err != nil {
return spec.NewError(0, "fetching artist top tracks: %v", err)
log.Printf("error fetching artist info from lastfm: %v", err)
return spec.NewResponse()
}
sub := spec.NewResponse()
@@ -562,15 +598,17 @@ func (c *Controller) ServeGetTopSongs(r *http.Request) *spec.Response {
}
var tracks []*db.Track
err = c.DB.
err = c.dbc.
Where("tracks.tag_title IN (?)", topTrackNames).
Joins("JOIN track_artists ON track_artists.track_id=tracks.id").
Joins("JOIN artists ON artists.id=track_artists.artist_id").
Where("artists.id=?", artist.ID).
Preload("Album").
Joins("JOIN albums ON albums.id=tracks.album_id").
Joins("JOIN album_artists ON album_artists.album_id=albums.id").
Where("album_artists.artist_id=? AND tracks.tag_title IN (?)", artist.ID, topTrackNames).
Limit(count).
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Group("tracks.id").
Limit(count).
Find(&tracks).
Error
if err != nil {
@@ -580,12 +618,11 @@ func (c *Controller) ServeGetTopSongs(r *http.Request) *spec.Response {
return sub
}
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, track := range tracks {
tc := spec.NewTrackByTags(track, track.Album)
tc.TranscodedContentType = transcodeMIME
tc.TranscodedSuffix = transcodeSuffix
tc.TranscodeMeta = transcodeMeta
sub.TopSongs.Tracks = append(sub.TopSongs.Tracks, tc)
}
return sub
@@ -599,13 +636,9 @@ func (c *Controller) ServeGetSimilarSongs(r *http.Request) *spec.Response {
if err != nil || id.Type != specid.Track {
return spec.NewError(10, "please provide an track `id` parameter")
}
apiKey, _ := c.DB.GetSetting(db.LastFMAPIKey)
if apiKey == "" {
return spec.NewResponse()
}
var track db.Track
err = c.DB.
err = c.dbc.
Preload("Album").
Where("id=?", id.Value).
First(&track).
@@ -614,10 +647,12 @@ func (c *Controller) ServeGetSimilarSongs(r *http.Request) *spec.Response {
return spec.NewError(10, "couldn't find a track with that id")
}
similarTracks, err := c.LastFMClient.TrackGetSimilarTracks(apiKey, track.TagTrackArtist, track.TagTitle)
similarTracks, err := c.lastFMClient.TrackGetSimilarTracks(track.TagTrackArtist, track.TagTitle)
if err != nil {
return spec.NewError(0, "fetching track similar tracks: %v", err)
log.Printf("error fetching similar songs from lastfm: %v", err)
return spec.NewResponse()
}
if len(similarTracks.Tracks) == 0 {
return spec.NewError(70, "no similar songs found for track: %v", track.TagTitle)
}
@@ -628,9 +663,10 @@ func (c *Controller) ServeGetSimilarSongs(r *http.Request) *spec.Response {
}
var tracks []*db.Track
err = c.DB.
err = c.dbc.
Select("tracks.*").
Preload("Album").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Where("tracks.tag_title IN (?)", similarTrackNames).
@@ -650,12 +686,11 @@ func (c *Controller) ServeGetSimilarSongs(r *http.Request) *spec.Response {
Tracks: make([]*spec.TrackChild, len(tracks)),
}
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, track := range tracks {
sub.SimilarSongs.Tracks[i] = spec.NewTrackByTags(track, track.Album)
sub.SimilarSongs.Tracks[i].TranscodedContentType = transcodeMIME
sub.SimilarSongs.Tracks[i].TranscodedSuffix = transcodeSuffix
sub.SimilarSongs.Tracks[i].TranscodeMeta = transcodeMeta
}
return sub
}
@@ -669,23 +704,19 @@ func (c *Controller) ServeGetSimilarSongsTwo(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an artist `id` parameter")
}
apiKey, _ := c.DB.GetSetting(db.LastFMAPIKey)
if apiKey == "" {
return spec.NewResponse()
}
var artist db.Artist
err = c.DB.
err = c.dbc.
Where("id=?", id.Value).
First(&artist).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "artist with id `%s` not found", id)
return spec.NewError(0, "artist with id %q not found", id)
}
similarArtists, err := c.LastFMClient.ArtistGetSimilar(apiKey, artist.Name)
similarArtists, err := c.lastFMClient.ArtistGetSimilar(artist.Name)
if err != nil {
return spec.NewError(0, "fetching artist similar artists: %v", err)
log.Printf("error fetching artist info from lastfm: %v", err)
return spec.NewResponse()
}
if len(similarArtists.Artists) == 0 {
return spec.NewError(0, "no similar artist found for: %v", artist.Name)
@@ -697,12 +728,13 @@ func (c *Controller) ServeGetSimilarSongsTwo(r *http.Request) *spec.Response {
}
var tracks []*db.Track
err = c.DB.
err = c.dbc.
Preload("Album").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Joins("JOIN album_artists ON album_artists.album_id=tracks.album_id").
Joins("JOIN artists ON artists.id=album_artists.artist_id").
Joins("JOIN track_artists ON track_artists.track_id=tracks.id").
Joins("JOIN artists ON artists.id=track_artists.artist_id").
Where("artists.name IN (?)", artistNames).
Order(gorm.Expr("random()")).
Group("tracks.id").
@@ -721,12 +753,10 @@ func (c *Controller) ServeGetSimilarSongsTwo(r *http.Request) *spec.Response {
Tracks: make([]*spec.TrackChild, len(tracks)),
}
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, track := range tracks {
sub.SimilarSongsTwo.Tracks[i] = spec.NewTrackByTags(track, track.Album)
sub.SimilarSongsTwo.Tracks[i].TranscodedContentType = transcodeMIME
sub.SimilarSongsTwo.Tracks[i].TranscodedSuffix = transcodeSuffix
sub.SimilarSongsTwo.Tracks[i].TranscodeMeta = transcodeMeta
}
return sub
}
@@ -754,33 +784,33 @@ func (c *Controller) ServeStar(r *http.Request) *spec.Response {
stardate := time.Now()
for _, id := range starIDsOfType(params, specid.Album) {
var albumstar db.AlbumStar
_ = c.DB.Where("user_id=? AND album_id=?", user.ID, id).First(&albumstar).Error
_ = c.dbc.Where("user_id=? AND album_id=?", user.ID, id).First(&albumstar).Error
albumstar.UserID = user.ID
albumstar.AlbumID = id
albumstar.StarDate = stardate
if err := c.DB.Save(&albumstar).Error; err != nil {
if err := c.dbc.Save(&albumstar).Error; err != nil {
return spec.NewError(0, "save album star: %v", err)
}
}
for _, id := range starIDsOfType(params, specid.Artist) {
var artiststar db.ArtistStar
_ = c.DB.Where("user_id=? AND artist_id=?", user.ID, id).First(&artiststar).Error
_ = c.dbc.Where("user_id=? AND artist_id=?", user.ID, id).First(&artiststar).Error
artiststar.UserID = user.ID
artiststar.ArtistID = id
artiststar.StarDate = stardate
if err := c.DB.Save(&artiststar).Error; err != nil {
if err := c.dbc.Save(&artiststar).Error; err != nil {
return spec.NewError(0, "save artist star: %v", err)
}
}
for _, id := range starIDsOfType(params, specid.Track) {
var trackstar db.TrackStar
_ = c.DB.Where("user_id=? AND track_id=?", user.ID, id).First(&trackstar).Error
_ = c.dbc.Where("user_id=? AND track_id=?", user.ID, id).First(&trackstar).Error
trackstar.UserID = user.ID
trackstar.TrackID = id
trackstar.StarDate = stardate
if err := c.DB.Save(&trackstar).Error; err != nil {
if err := c.dbc.Save(&trackstar).Error; err != nil {
return spec.NewError(0, "save track star: %v", err)
}
}
@@ -793,19 +823,19 @@ func (c *Controller) ServeUnstar(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User)
for _, id := range starIDsOfType(params, specid.Album) {
if err := c.DB.Where("user_id=? AND album_id=?", user.ID, id).Delete(db.AlbumStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
if err := c.dbc.Where("user_id=? AND album_id=?", user.ID, id).Delete(db.AlbumStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "delete album star: %v", err)
}
}
for _, id := range starIDsOfType(params, specid.Artist) {
if err := c.DB.Where("user_id=? AND artist_id=?", user.ID, id).Delete(db.ArtistStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
if err := c.dbc.Where("user_id=? AND artist_id=?", user.ID, id).Delete(db.ArtistStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "delete artist star: %v", err)
}
}
for _, id := range starIDsOfType(params, specid.Track) {
if err := c.DB.Where("user_id=? AND track_id=?", user.ID, id).Delete(db.TrackStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
if err := c.dbc.Where("user_id=? AND track_id=?", user.ID, id).Delete(db.TrackStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "delete track star: %v", err)
}
}
@@ -830,95 +860,95 @@ func (c *Controller) ServeSetRating(r *http.Request) *spec.Response {
switch id.Type {
case specid.Album:
var album db.Album
err := c.DB.Where("id=?", id.Value).First(&album).Error
err := c.dbc.Where("id=?", id.Value).First(&album).Error
if err != nil {
return spec.NewError(0, "fetch album: %v", err)
}
var albumRating db.AlbumRating
if err := c.DB.Where("user_id=? AND album_id=?", user.ID, id.Value).First(&albumRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
if err := c.dbc.Where("user_id=? AND album_id=?", user.ID, id.Value).First(&albumRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "fetch album rating: %v", err)
}
switch {
case rating == 0 && albumRating.AlbumID == album.ID:
if err := c.DB.Delete(&albumRating).Error; err != nil {
if err := c.dbc.Delete(&albumRating).Error; err != nil {
return spec.NewError(0, "delete album rating: %v", err)
}
case rating > 0:
albumRating.UserID = user.ID
albumRating.AlbumID = id.Value
albumRating.Rating = rating
if err := c.DB.Save(&albumRating).Error; err != nil {
if err := c.dbc.Save(&albumRating).Error; err != nil {
return spec.NewError(0, "save album rating: %v", err)
}
}
var averageRating float64
if err := c.DB.Model(db.AlbumRating{}).Select("coalesce(avg(rating), 0)").Where("album_id=?", id.Value).Row().Scan(&averageRating); err != nil {
if err := c.dbc.Model(db.AlbumRating{}).Select("coalesce(avg(rating), 0)").Where("album_id=?", id.Value).Row().Scan(&averageRating); err != nil {
return spec.NewError(0, "find average album rating: %v", err)
}
album.AverageRating = math.Trunc(averageRating*100) / 100
if err := c.DB.Save(&album).Error; err != nil {
if err := c.dbc.Save(&album).Error; err != nil {
return spec.NewError(0, "save album: %v", err)
}
case specid.Artist:
var artist db.Artist
err := c.DB.Where("id=?", id.Value).First(&artist).Error
err := c.dbc.Where("id=?", id.Value).First(&artist).Error
if err != nil {
return spec.NewError(0, "fetch artist: %v", err)
}
var artistRating db.ArtistRating
if err := c.DB.Where("user_id=? AND artist_id=?", user.ID, id.Value).First(&artistRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
if err := c.dbc.Where("user_id=? AND artist_id=?", user.ID, id.Value).First(&artistRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "fetch artist rating: %v", err)
}
switch {
case rating == 0 && artistRating.ArtistID == artist.ID:
if err := c.DB.Delete(&artistRating).Error; err != nil {
if err := c.dbc.Delete(&artistRating).Error; err != nil {
return spec.NewError(0, "delete artist rating: %v", err)
}
case rating > 0:
artistRating.UserID = user.ID
artistRating.ArtistID = id.Value
artistRating.Rating = rating
if err := c.DB.Save(&artistRating).Error; err != nil {
if err := c.dbc.Save(&artistRating).Error; err != nil {
return spec.NewError(0, "save artist rating: %v", err)
}
}
var averageRating float64
if err := c.DB.Model(db.ArtistRating{}).Select("coalesce(avg(rating), 0)").Where("artist_id=?", id.Value).Row().Scan(&averageRating); err != nil {
if err := c.dbc.Model(db.ArtistRating{}).Select("coalesce(avg(rating), 0)").Where("artist_id=?", id.Value).Row().Scan(&averageRating); err != nil {
return spec.NewError(0, "find average artist rating: %v", err)
}
artist.AverageRating = math.Trunc(averageRating*100) / 100
if err := c.DB.Save(&artist).Error; err != nil {
if err := c.dbc.Save(&artist).Error; err != nil {
return spec.NewError(0, "save artist: %v", err)
}
case specid.Track:
var track db.Track
err := c.DB.Where("id=?", id.Value).First(&track).Error
err := c.dbc.Where("id=?", id.Value).First(&track).Error
if err != nil {
return spec.NewError(0, "fetch track: %v", err)
}
var trackRating db.TrackRating
if err := c.DB.Where("user_id=? AND track_id=?", user.ID, id.Value).First(&trackRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
if err := c.dbc.Where("user_id=? AND track_id=?", user.ID, id.Value).First(&trackRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "fetch track rating: %v", err)
}
switch {
case rating == 0 && trackRating.TrackID == track.ID:
if err := c.DB.Delete(&trackRating).Error; err != nil {
if err := c.dbc.Delete(&trackRating).Error; err != nil {
return spec.NewError(0, "delete track rating: %v", err)
}
case rating > 0:
trackRating.UserID = user.ID
trackRating.TrackID = id.Value
trackRating.Rating = rating
if err := c.DB.Save(&trackRating).Error; err != nil {
if err := c.dbc.Save(&trackRating).Error; err != nil {
return spec.NewError(0, "save track rating: %v", err)
}
}
var averageRating float64
if err := c.DB.Model(db.TrackRating{}).Select("coalesce(avg(rating), 0)").Where("track_id=?", id.Value).Row().Scan(&averageRating); err != nil {
if err := c.dbc.Model(db.TrackRating{}).Select("coalesce(avg(rating), 0)").Where("track_id=?", id.Value).Row().Scan(&averageRating); err != nil {
return spec.NewError(0, "find average track rating: %v", err)
}
track.AverageRating = math.Trunc(averageRating*100) / 100
if err := c.DB.Save(&track).Error; err != nil {
if err := c.dbc.Save(&track).Error; err != nil {
return spec.NewError(0, "save track: %v", err)
}
default:
+5 -10
View File
@@ -8,8 +8,7 @@ import (
func TestGetArtists(t *testing.T) {
t.Parallel()
contr := makeControllerRoots(t, []string{"m-0", "m-1"})
runQueryCases(t, contr, contr.ServeGetArtists, []*queryCase{
runQueryCases(t, contr.ServeGetArtists, []*queryCase{
{url.Values{}, "no_args", false},
{url.Values{"musicFolderId": {"0"}}, "with_music_folder_1", false},
{url.Values{"musicFolderId": {"1"}}, "with_music_folder_2", false},
@@ -19,8 +18,7 @@ func TestGetArtists(t *testing.T) {
func TestGetArtist(t *testing.T) {
t.Parallel()
contr := makeController(t)
runQueryCases(t, contr, contr.ServeGetArtist, []*queryCase{
runQueryCases(t, contr.ServeGetArtist, []*queryCase{
{url.Values{"id": {"ar-1"}}, "id_one", false},
{url.Values{"id": {"ar-2"}}, "id_two", false},
{url.Values{"id": {"ar-3"}}, "id_three", false},
@@ -30,8 +28,7 @@ func TestGetArtist(t *testing.T) {
func TestGetAlbum(t *testing.T) {
t.Parallel()
contr := makeController(t)
runQueryCases(t, contr, contr.ServeGetAlbum, []*queryCase{
runQueryCases(t, contr.ServeGetAlbum, []*queryCase{
{url.Values{"id": {"al-2"}}, "without_cover", false},
{url.Values{"id": {"al-3"}}, "with_cover", false},
})
@@ -40,8 +37,7 @@ func TestGetAlbum(t *testing.T) {
func TestGetAlbumListTwo(t *testing.T) {
t.Parallel()
contr := makeController(t)
runQueryCases(t, contr, contr.ServeGetAlbumListTwo, []*queryCase{
runQueryCases(t, contr.ServeGetAlbumListTwo, []*queryCase{
{url.Values{"type": {"alphabeticalByArtist"}}, "alpha_artist", false},
{url.Values{"type": {"alphabeticalByName"}}, "alpha_name", false},
{url.Values{"type": {"newest"}}, "newest", false},
@@ -52,8 +48,7 @@ func TestGetAlbumListTwo(t *testing.T) {
func TestSearchThree(t *testing.T) {
t.Parallel()
contr := makeController(t)
runQueryCases(t, contr, contr.ServeSearchThree, []*queryCase{
runQueryCases(t, contr.ServeSearchThree, []*queryCase{
{url.Values{"query": {"art"}}, "q_art", false},
{url.Values{"query": {"alb"}}, "q_alb", false},
{url.Values{"query": {"tit"}}, "q_tra", false},
+166 -74
View File
@@ -6,39 +6,24 @@ import (
"log"
"math"
"net/http"
"os"
"path/filepath"
"sync"
"time"
"unicode"
"github.com/google/uuid"
"github.com/jinzhu/gorm"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/scanner"
"go.senan.xyz/gonic/scrobble"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
"go.senan.xyz/gonic/server/ctrlsubsonic/specidpaths"
)
func lowerUDecOrHash(in string) string {
lower := unicode.ToLower(rune(in[0]))
if !unicode.IsLetter(lower) {
return "#"
}
return string(lower)
}
func getMusicFolder(musicPaths []MusicPath, p params.Params) string {
idx, err := p.GetInt("musicFolderId")
if err != nil {
return ""
}
if idx < 0 || idx >= len(musicPaths) {
return ""
}
return musicPaths[idx].Path
}
func (c *Controller) ServeGetLicence(_ *http.Request) *spec.Response {
sub := spec.NewResponse()
sub.Licence = &spec.Licence{
@@ -51,35 +36,87 @@ func (c *Controller) ServePing(_ *http.Request) *spec.Response {
return spec.NewResponse()
}
func (c *Controller) ServeGetOpenSubsonicExtensions(_ *http.Request) *spec.Response {
sub := spec.NewResponse()
sub.OpenSubsonicExtensions = &spec.OpenSubsonicExtensions{
{Name: "transcodeOffset", Versions: []int{1}},
}
return sub
}
func (c *Controller) ServeScrobble(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User)
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
if err != nil || id.Type != specid.Track {
return spec.NewError(10, "please provide a track `id` track parameter")
}
track := &db.Track{}
if err := c.DB.Preload("Album").Preload("Album.Artists").First(track, id.Value).Error; err != nil {
return spec.NewError(0, "error finding track: %v", err)
if err != nil {
return spec.NewError(10, "please provide a `id` parameter")
}
optStamp := params.GetOrTime("time", time.Now())
optSubmission := params.GetOrBool("submission", true)
if err := streamUpdateStats(c.DB, user.ID, track, optStamp); err != nil {
return spec.NewError(0, "error updating stats: %v", err)
}
var scrobbleTrack scrobble.Track
var scrobbleErrs []error
for _, scrobbler := range c.Scrobblers {
if err := scrobbler.Scrobble(user, track, optStamp, optSubmission); err != nil {
scrobbleErrs = append(scrobbleErrs, err)
switch id.Type {
case specid.Track:
var track db.Track
if err := c.dbc.Preload("Album").Preload("Album.Artists").First(&track, id.Value).Error; err != nil {
return spec.NewError(0, "error finding track: %v", err)
}
if track.Album == nil {
return spec.NewError(0, "track has no album %d", track.ID)
}
scrobbleTrack.Track = track.TagTitle
scrobbleTrack.Artist = track.TagTrackArtist
scrobbleTrack.Album = track.Album.TagTitle
scrobbleTrack.AlbumArtist = track.Album.TagAlbumArtist
scrobbleTrack.TrackNumber = uint(track.TagTrackNumber)
scrobbleTrack.Duration = time.Second * time.Duration(track.Length)
if _, err := uuid.Parse(track.TagBrainzID); err == nil {
scrobbleTrack.MusicBrainzID = track.TagBrainzID
}
if err := scrobbleStatsUpdateTrack(c.dbc, &track, user.ID, optStamp); err != nil {
return spec.NewError(0, "error updating stats: %v", err)
}
case specid.PodcastEpisode:
var podcastEpisode db.PodcastEpisode
if err := c.dbc.Preload("Podcast").First(&podcastEpisode, id.Value).Error; err != nil {
return spec.NewError(0, "error finding podcast episode: %v", err)
}
if err := scrobbleStatsUpdatePodcastEpisode(c.dbc, id.Value); err != nil {
return spec.NewError(0, "error updating stats: %v", err)
}
}
if len(scrobbleErrs) > 0 {
return spec.NewError(0, "error when submitting: %v", errors.Join(scrobbleErrs...))
if scrobbleTrack.Track == "" {
return spec.NewResponse()
}
var wg sync.WaitGroup
scrobbleErrs := make([]error, len(c.scrobblers))
for i := range c.scrobblers {
if !c.scrobblers[i].IsUserAuthenticated(*user) {
continue
}
wg.Add(1)
go func(i int) {
defer wg.Done()
if err := c.scrobblers[i].Scrobble(*user, scrobbleTrack, optStamp, optSubmission); err != nil {
scrobbleErrs[i] = err
}
}(i)
}
wg.Wait()
if err := errors.Join(scrobbleErrs...); err != nil {
return spec.NewError(0, "error when submitting: %v", err)
}
return spec.NewResponse()
@@ -88,7 +125,7 @@ func (c *Controller) ServeScrobble(r *http.Request) *spec.Response {
func (c *Controller) ServeGetMusicFolders(_ *http.Request) *spec.Response {
sub := spec.NewResponse()
sub.MusicFolders = &spec.MusicFolders{}
for i, mp := range c.MusicPaths {
for i, mp := range c.musicPaths {
alias := mp.Alias
if alias == "" {
alias = filepath.Base(mp.Path)
@@ -100,7 +137,7 @@ func (c *Controller) ServeGetMusicFolders(_ *http.Request) *spec.Response {
func (c *Controller) ServeStartScan(r *http.Request) *spec.Response {
go func() {
if _, err := c.Scanner.ScanAndClean(scanner.ScanOptions{}); err != nil {
if _, err := c.scanner.ScanAndClean(scanner.ScanOptions{}); err != nil {
log.Printf("error while scanning: %v\n", err)
}
}()
@@ -109,13 +146,13 @@ func (c *Controller) ServeStartScan(r *http.Request) *spec.Response {
func (c *Controller) ServeGetScanStatus(_ *http.Request) *spec.Response {
var trackCount int
if err := c.DB.Model(db.Track{}).Count(&trackCount).Error; err != nil {
if err := c.dbc.Model(db.Track{}).Count(&trackCount).Error; err != nil {
return spec.NewError(0, "error finding track count: %v", err)
}
sub := spec.NewResponse()
sub.ScanStatus = &spec.ScanStatus{
Scanning: c.Scanner.IsScanning(),
Scanning: c.scanner.IsScanning(),
Count: trackCount,
}
return sub
@@ -130,8 +167,8 @@ func (c *Controller) ServeGetUser(r *http.Request) *spec.Response {
sub.User = &spec.User{
Username: user.Name,
AdminRole: user.IsAdmin,
JukeboxRole: c.Jukebox != nil,
PodcastRole: c.Podcasts != nil,
JukeboxRole: c.jukebox != nil,
PodcastRole: c.podcasts != nil,
DownloadRole: true,
ScrobblingEnabled: hasLastFM || hasListenBrainz,
Folder: []int{1},
@@ -147,7 +184,7 @@ func (c *Controller) ServeGetPlayQueue(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
var queue db.PlayQueue
err := c.DB.
err := c.dbc.
Where("user_id=?", user.ID).
Find(&queue).
Error
@@ -165,33 +202,28 @@ func (c *Controller) ServeGetPlayQueue(r *http.Request) *spec.Response {
trackIDs := queue.GetItems()
sub.PlayQueue.List = make([]*spec.TrackChild, len(trackIDs))
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, id := range trackIDs {
switch id.Type {
case specid.Track:
track := db.Track{}
c.DB.
c.dbc.
Where("id=?", id.Value).
Preload("Album").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Find(&track)
sub.PlayQueue.List[i] = spec.NewTCTrackByFolder(&track, track.Album)
sub.PlayQueue.List[i].TranscodedContentType = transcodeMIME
sub.PlayQueue.List[i].TranscodedSuffix = transcodeSuffix
sub.PlayQueue.List[i].TranscodeMeta = transcodeMeta
case specid.PodcastEpisode:
pe := db.PodcastEpisode{}
c.DB.
c.dbc.
Where("id=?", id.Value).
Find(&pe)
p := db.Podcast{}
c.DB.
Where("id=?", pe.PodcastID).
Find(&p)
sub.PlayQueue.List[i] = spec.NewTCPodcastEpisode(&pe, &p)
sub.PlayQueue.List[i].TranscodedContentType = transcodeMIME
sub.PlayQueue.List[i].TranscodedSuffix = transcodeSuffix
sub.PlayQueue.List[i] = spec.NewTCPodcastEpisode(&pe)
sub.PlayQueue.List[i].TranscodeMeta = transcodeMeta
}
}
return sub
@@ -214,13 +246,13 @@ func (c *Controller) ServeSavePlayQueue(r *http.Request) *spec.Response {
}
user := r.Context().Value(CtxUser).(*db.User)
var queue db.PlayQueue
c.DB.Where("user_id=?", user.ID).First(&queue)
c.dbc.Where("user_id=?", user.ID).First(&queue)
queue.UserID = user.ID
queue.Current = params.GetOrID("current", specid.ID{}).String()
queue.Position = params.GetOrInt("position", 0)
queue.ChangedBy = params.GetOr("c", "") // must exist, middleware checks
queue.SetItems(trackIDs)
c.DB.Save(&queue)
c.dbc.Save(&queue)
return spec.NewResponse()
}
@@ -232,10 +264,11 @@ func (c *Controller) ServeGetSong(r *http.Request) *spec.Response {
return spec.NewError(10, "provide an `id` parameter")
}
var track db.Track
err = c.DB.
err = c.dbc.
Where("id=?", id.Value).
Preload("Album").
Preload("Album.Artists").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
First(&track).
@@ -243,8 +276,14 @@ func (c *Controller) ServeGetSong(r *http.Request) *spec.Response {
if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(10, "couldn't find a track with that id")
}
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
sub := spec.NewResponse()
sub.Track = spec.NewTrackByTags(&track, track.Album)
sub.Track.TranscodeMeta = transcodeMeta
return sub
}
@@ -252,10 +291,11 @@ func (c *Controller) ServeGetRandomSongs(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
var tracks []*db.Track
q := c.DB.DB.
q := c.dbc.DB.
Limit(params.GetOrInt("size", 10)).
Preload("Album").
Preload("Album.Artists").
Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Joins("JOIN albums ON tracks.album_id=albums.id").
@@ -270,7 +310,7 @@ func (c *Controller) ServeGetRandomSongs(r *http.Request) *spec.Response {
q = q.Joins("JOIN track_genres ON track_genres.track_id=tracks.id")
q = q.Joins("JOIN genres ON genres.id=track_genres.genre_id AND genres.name=?", genre)
}
if m := getMusicFolder(c.MusicPaths, params); m != "" {
if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m)
}
if err := q.Find(&tracks).Error; err != nil {
@@ -280,12 +320,11 @@ func (c *Controller) ServeGetRandomSongs(r *http.Request) *spec.Response {
sub.RandomTracks = &spec.RandomTracks{}
sub.RandomTracks.List = make([]*spec.TrackChild, len(tracks))
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, track := range tracks {
sub.RandomTracks.List[i] = spec.NewTrackByTags(track, track.Album)
sub.RandomTracks.List[i].TranscodedContentType = transcodeMIME
sub.RandomTracks.List[i].TranscodedSuffix = transcodeSuffix
sub.RandomTracks.List[i].TranscodeMeta = transcodeMeta
}
return sub
}
@@ -297,7 +336,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
trackPaths := func(ids []specid.ID) ([]string, error) {
var paths []string
for _, id := range ids {
r, err := specidpaths.Locate(c.DB, c.PodcastsPath, id)
r, err := specidpaths.Locate(c.dbc, id)
if err != nil {
return nil, fmt.Errorf("find track by id: %w", err)
}
@@ -306,7 +345,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
return paths, nil
}
getSpecStatus := func() (*spec.JukeboxStatus, error) {
status, err := c.Jukebox.GetStatus()
status, err := c.jukebox.GetStatus()
if err != nil {
return nil, fmt.Errorf("get status: %w", err)
}
@@ -319,12 +358,12 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
}
getSpecPlaylist := func() ([]*spec.TrackChild, error) {
var ret []*spec.TrackChild
playlist, err := c.Jukebox.GetPlaylist()
playlist, err := c.jukebox.GetPlaylist()
if err != nil {
return nil, fmt.Errorf("get playlist: %w", err)
}
for _, path := range playlist {
file, err := specidpaths.Lookup(c.DB, PathsOf(c.MusicPaths), c.PodcastsPath, path)
file, err := specidpaths.Lookup(c.dbc, MusicPaths(c.musicPaths), c.podcastsPath, path)
if err != nil {
return nil, fmt.Errorf("fetch track: %w", err)
}
@@ -344,7 +383,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
if err != nil {
return spec.NewError(0, "error creating playlist items: %v", err)
}
if err := c.Jukebox.SetPlaylist(paths); err != nil {
if err := c.jukebox.SetPlaylist(paths); err != nil {
return spec.NewError(0, "error setting playlist: %v", err)
}
case "add":
@@ -353,11 +392,11 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
if err != nil {
return spec.NewError(10, "error creating playlist items: %v", err)
}
if err := c.Jukebox.AppendToPlaylist(paths); err != nil {
if err := c.jukebox.AppendToPlaylist(paths); err != nil {
return spec.NewError(0, "error appending to playlist: %v", err)
}
case "clear":
if err := c.Jukebox.ClearPlaylist(); err != nil {
if err := c.jukebox.ClearPlaylist(); err != nil {
return spec.NewError(0, "error clearing playlist: %v", err)
}
case "remove":
@@ -365,15 +404,15 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
if err != nil {
return spec.NewError(10, "please provide an id for remove actions")
}
if err := c.Jukebox.RemovePlaylistIndex(index); err != nil {
if err := c.jukebox.RemovePlaylistIndex(index); err != nil {
return spec.NewError(0, "error removing: %v", err)
}
case "stop":
if err := c.Jukebox.Pause(); err != nil {
if err := c.jukebox.Pause(); err != nil {
return spec.NewError(0, "error stopping: %v", err)
}
case "start":
if err := c.Jukebox.Play(); err != nil {
if err := c.jukebox.Play(); err != nil {
return spec.NewError(0, "error starting: %v", err)
}
case "skip":
@@ -382,7 +421,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
return spec.NewError(10, "please provide an index for skip actions")
}
offset, _ := params.GetInt("offset")
if err := c.Jukebox.SkipToPlaylistIndex(index, offset); err != nil {
if err := c.jukebox.SkipToPlaylistIndex(index, offset); err != nil {
return spec.NewError(0, "error skipping: %v", err)
}
case "get":
@@ -405,7 +444,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
if err != nil {
return spec.NewError(10, "please provide a valid gain param")
}
if err := c.Jukebox.SetVolumePct(int(math.Min(gain, 1) * 100)); err != nil {
if err := c.jukebox.SetVolumePct(int(math.Min(gain, 1) * 100)); err != nil {
return spec.NewError(0, "error setting gain: %v", err)
}
}
@@ -424,3 +463,56 @@ func (c *Controller) ServeGetLyrics(_ *http.Request) *spec.Response {
sub.Lyrics = &spec.Lyrics{}
return sub
}
func scrobbleStatsUpdateTrack(dbc *db.DB, track *db.Track, userID int, playTime time.Time) error {
var play db.Play
if err := dbc.Where("album_id=? AND user_id=?", track.AlbumID, userID).First(&play).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return fmt.Errorf("find stat: %w", err)
}
play.AlbumID = track.AlbumID
play.UserID = userID
play.Count++ // for getAlbumList?type=frequent
play.Length += track.Length
if playTime.After(play.Time) {
play.Time = playTime // for getAlbumList?type=recent
}
if err := dbc.Save(&play).Error; err != nil {
return fmt.Errorf("save stat: %w", err)
}
return nil
}
func scrobbleStatsUpdatePodcastEpisode(dbc *db.DB, peID int) error {
var pe db.PodcastEpisode
if err := dbc.Where("id=?", peID).First(&pe).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return fmt.Errorf("find podcast episode: %w", err)
}
pe.ModifiedAt = time.Now()
if err := dbc.Save(&pe).Error; err != nil {
return fmt.Errorf("save podcast episode: %w", err)
}
return nil
}
func getMusicFolder(musicPaths []MusicPath, p params.Params) string {
idx, err := p.GetInt("musicFolderId")
if err != nil {
return ""
}
if idx < 0 || idx >= len(musicPaths) {
return os.DevNull
}
return musicPaths[idx].Path
}
func lowerUDecOrHash(in string) string {
lower := unicode.ToLower(rune(in[0]))
if !unicode.IsLetter(lower) {
return "#"
}
return string(lower)
}
@@ -11,7 +11,7 @@ import (
func (c *Controller) ServeGetInternetRadioStations(_ *http.Request) *spec.Response {
var stations []*db.InternetRadioStation
if err := c.DB.Find(&stations).Error; err != nil {
if err := c.dbc.Find(&stations).Error; err != nil {
return spec.NewError(0, "find stations: %v", err)
}
sub := spec.NewResponse()
@@ -55,7 +55,7 @@ func (c *Controller) ServeCreateInternetRadioStation(r *http.Request) *spec.Resp
station.Name = name
station.HomepageURL = homepageURL
if err := c.DB.Save(&station).Error; err != nil {
if err := c.dbc.Save(&station).Error; err != nil {
return spec.NewError(0, "save station: %v", err)
}
@@ -92,7 +92,7 @@ func (c *Controller) ServeUpdateInternetRadioStation(r *http.Request) *spec.Resp
}
var station db.InternetRadioStation
if err := c.DB.Where("id=?", stationID.Value).First(&station).Error; err != nil {
if err := c.dbc.Where("id=?", stationID.Value).First(&station).Error; err != nil {
return spec.NewError(70, "id not found: %v", err)
}
@@ -100,7 +100,7 @@ func (c *Controller) ServeUpdateInternetRadioStation(r *http.Request) *spec.Resp
station.Name = name
station.HomepageURL = homepageURL
if err := c.DB.Save(&station).Error; err != nil {
if err := c.dbc.Save(&station).Error; err != nil {
return spec.NewError(0, "save station: %v", err)
}
return spec.NewResponse()
@@ -119,11 +119,11 @@ func (c *Controller) ServeDeleteInternetRadioStation(r *http.Request) *spec.Resp
}
var station db.InternetRadioStation
if err := c.DB.Where("id=?", stationID.Value).First(&station).Error; err != nil {
if err := c.dbc.Where("id=?", stationID.Value).First(&station).Error; err != nil {
return spec.NewError(70, "id not found: %v", err)
}
if err := c.DB.Delete(&station).Error; err != nil {
if err := c.dbc.Delete(&station).Error; err != nil {
return spec.NewError(70, "id not found: %v", err)
}
@@ -1,7 +1,9 @@
//nolint:tparallel,paralleltest,thelper
package ctrlsubsonic
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"net/url"
@@ -37,8 +39,10 @@ const (
newstation1HomepageURL = "https://www.kcrw.com/music/shows/eclectic24"
)
const newstation2StreamURL = "http://media.kcrw.com/pls/kcrwsantabarbara.pls"
const newstation2Name = "KCRW Santa Barbara"
const (
newstation2StreamURL = "http://media.kcrw.com/pls/kcrwsantabarbara.pls"
newstation2Name = "KCRW Santa Barbara"
)
const station3ID = "ir-3"
@@ -48,16 +52,18 @@ func TestInternetRadio(t *testing.T) {
t.Parallel()
contr := makeController(t)
t.Run("TestInternetRadioInitialEmpty", func(t *testing.T) { testInternetRadioInitialEmpty(t, contr) })
t.Run("TestInternetRadioBadCreates", func(t *testing.T) { testInternetRadioBadCreates(t, contr) })
t.Run("TestInternetRadioInitialAdds", func(t *testing.T) { testInternetRadioInitialAdds(t, contr) })
t.Run("TestInternetRadioUpdateHomepage", func(t *testing.T) { testInternetRadioUpdateHomepage(t, contr) })
t.Run("TestInternetRadioNotAdmin", func(t *testing.T) { testInternetRadioNotAdmin(t, contr) })
t.Run("TestInternetRadioUpdates", func(t *testing.T) { testInternetRadioUpdates(t, contr) })
t.Run("TestInternetRadioDeletes", func(t *testing.T) { testInternetRadioDeletes(t, contr) })
t.Run("initial empty", func(t *testing.T) { testInternetRadioInitialEmpty(t, contr) })
t.Run("bad creates", func(t *testing.T) { testInternetRadioBadCreates(t, contr) })
t.Run("initial adds", func(t *testing.T) { testInternetRadioInitialAdds(t, contr) })
t.Run("update home page", func(t *testing.T) { testInternetRadioUpdateHomepage(t, contr) })
t.Run("not admin", func(t *testing.T) { testInternetRadioNotAdmin(t, contr) })
t.Run("updates", func(t *testing.T) { testInternetRadioUpdates(t, contr) })
t.Run("deletes", func(t *testing.T) { testInternetRadioDeletes(t, contr) })
}
func runTestCase(t *testing.T, contr *Controller, h handlerSubsonic, q url.Values, admin bool) *spec.SubsonicResponse {
func runTestCase(t *testing.T, h handlerSubsonic, q url.Values, admin bool) *spec.SubsonicResponse {
t.Helper()
var rr *httptest.ResponseRecorder
var req *http.Request
@@ -66,7 +72,7 @@ func runTestCase(t *testing.T, contr *Controller, h handlerSubsonic, q url.Value
} else {
rr, req = makeHTTPMock(q)
}
contr.H(h).ServeHTTP(rr, req)
resp(h).ServeHTTP(rr, req)
body := rr.Body.String()
if status := rr.Code; status != http.StatusOK {
t.Fatalf("didn't give a 200\n%s", body)
@@ -74,18 +80,17 @@ func runTestCase(t *testing.T, contr *Controller, h handlerSubsonic, q url.Value
var response spec.SubsonicResponse
if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil {
switch ty := err.(type) {
case *json.SyntaxError:
jsn := body[0:ty.Offset]
jsn += "<--(Invalid Character)"
t.Fatalf("invalid character at offset %v\n %s", ty.Offset, jsn)
case *json.UnmarshalTypeError:
jsn := body[0:ty.Offset]
jsn += "<--(Invalid Type)"
t.Fatalf("invalid type at offset %v\n %s", ty.Offset, jsn)
default:
t.Fatalf("json unmarshal failed: %s", err.Error())
var jsonSyntaxError *json.SyntaxError
if errors.As(err, &jsonSyntaxError) {
t.Fatalf("invalid character at offset %v\n %s <--", jsonSyntaxError.Offset, body[0:jsonSyntaxError.Offset])
}
var jsonUnmarshalTypeError *json.UnmarshalTypeError
if errors.As(err, &jsonSyntaxError) {
t.Fatalf("invalid type at offset %v\n %s <--", jsonUnmarshalTypeError.Offset, body[0:jsonUnmarshalTypeError.Offset])
}
t.Fatalf("json unmarshal failed: %v", err)
}
return &response
@@ -129,29 +134,29 @@ func testInternetRadioBadCreates(t *testing.T, contr *Controller) {
var response *spec.SubsonicResponse
// no parameters
response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation, url.Values{}, true)
response = runTestCase(t, contr.ServeCreateInternetRadioStation, url.Values{}, true)
checkMissingParameter(t, response)
// just one required parameter
response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station1StreamURL}}, true)
checkMissingParameter(t, response)
response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"name": {station1Name}}, true)
checkMissingParameter(t, response)
// bad URLs
response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station1StreamURL}, "name": {station1Name}, "homepageUrl": {notAURL}}, true)
checkBadParameter(t, response)
response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {notAURL}, "name": {station1Name}, "homepageUrl": {station1HomepageURL}}, true)
checkBadParameter(t, response)
// check for empty get after
response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if (response.Response.InternetRadioStations == nil) || (len(response.Response.InternetRadioStations.List) != 0) {
@@ -161,7 +166,7 @@ func testInternetRadioBadCreates(t *testing.T, contr *Controller) {
func testInternetRadioInitialEmpty(t *testing.T, contr *Controller) {
// check for empty get on new DB
response := runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response := runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if (response.Response.InternetRadioStations == nil) || (len(response.Response.InternetRadioStations.List) != 0) {
@@ -171,15 +176,15 @@ func testInternetRadioInitialEmpty(t *testing.T, contr *Controller) {
func testInternetRadioInitialAdds(t *testing.T, contr *Controller) {
// successful adds and read back
response := runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
response := runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station1StreamURL}, "name": {station1Name}, "homepageUrl": {station1HomepageURL}}, true)
checkSuccess(t, response)
response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station2StreamURL}, "name": {station2Name}}, true) // NOTE: no homepage Url
checkSuccess(t, response)
response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -202,16 +207,16 @@ func testInternetRadioInitialAdds(t *testing.T, contr *Controller) {
func testInternetRadioUpdateHomepage(t *testing.T, contr *Controller) {
// update empty homepage URL without other parameters (fails)
response := runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
response := runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station2ID}, "homepageUrl": {station2HomepageURL}}, true)
checkMissingParameter(t, response)
// update empty homepage URL properly and read back
response = runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
response = runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station2ID}, "streamUrl": {station2StreamURL}, "name": {station2Name}, "homepageUrl": {station2HomepageURL}}, true)
checkSuccess(t, response)
response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -234,19 +239,19 @@ func testInternetRadioUpdateHomepage(t *testing.T, contr *Controller) {
func testInternetRadioNotAdmin(t *testing.T, contr *Controller) {
// create, update, delete w/o admin privileges (fails and does not modify data)
response := runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
response := runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station1StreamURL}, "name": {station1Name}, "homepageUrl": {station1HomepageURL}}, false)
checkNotAdmin(t, response)
response = runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
response = runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station1ID}, "streamUrl": {newstation1StreamURL}, "name": {newstation1Name}, "homepageUrl": {newstation1HomepageURL}}, false)
checkNotAdmin(t, response)
response = runTestCase(t, contr, contr.ServeDeleteInternetRadioStation,
response = runTestCase(t, contr.ServeDeleteInternetRadioStation,
url.Values{"id": {station1ID}}, false)
checkNotAdmin(t, response)
response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -269,11 +274,11 @@ func testInternetRadioNotAdmin(t *testing.T, contr *Controller) {
func testInternetRadioUpdates(t *testing.T, contr *Controller) {
// replace station 1 and read back
response := runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
response := runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station1ID}, "streamUrl": {newstation1StreamURL}, "name": {newstation1Name}, "homepageUrl": {newstation1HomepageURL}}, true)
checkSuccess(t, response)
response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -294,11 +299,11 @@ func testInternetRadioUpdates(t *testing.T, contr *Controller) {
}
// update station 2 but without homepage URL and read back
response = runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
response = runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station2ID}, "streamUrl": {newstation2StreamURL}, "name": {newstation2Name}}, true)
checkSuccess(t, response)
response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -321,11 +326,11 @@ func testInternetRadioUpdates(t *testing.T, contr *Controller) {
func testInternetRadioDeletes(t *testing.T, contr *Controller) {
// delete non-existent station 3 (fails and does not modify data)
response := runTestCase(t, contr, contr.ServeDeleteInternetRadioStation,
response := runTestCase(t, contr.ServeDeleteInternetRadioStation,
url.Values{"id": {station3ID}}, true)
checkBadParameter(t, response)
response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -346,11 +351,11 @@ func testInternetRadioDeletes(t *testing.T, contr *Controller) {
}
// delete station 1 and recheck
response = runTestCase(t, contr, contr.ServeDeleteInternetRadioStation,
response = runTestCase(t, contr.ServeDeleteInternetRadioStation,
url.Values{"id": {station1ID}}, true)
checkSuccess(t, response)
response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -367,11 +372,11 @@ func testInternetRadioDeletes(t *testing.T, contr *Controller) {
}
// delete station 2 and check that they're all gone
response = runTestCase(t, contr, contr.ServeDeleteInternetRadioStation,
response = runTestCase(t, contr.ServeDeleteInternetRadioStation,
url.Values{"id": {station2ID}}, true)
checkSuccess(t, response)
response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if (response.Response.InternetRadioStations == nil) || (len(response.Response.InternetRadioStations.List) != 0) {
+18 -22
View File
@@ -22,7 +22,7 @@ import (
func (c *Controller) ServeGetPlaylists(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
paths, err := c.PlaylistStore.List()
paths, err := c.playlistStore.List()
if err != nil {
return spec.NewError(0, "error listing playlists: %v", err)
}
@@ -31,7 +31,7 @@ func (c *Controller) ServeGetPlaylists(r *http.Request) *spec.Response {
List: []*spec.Playlist{},
}
for _, path := range paths {
playlist, err := c.PlaylistStore.Read(path)
playlist, err := c.playlistStore.Read(path)
if err != nil {
return spec.NewError(0, "error reading playlist %q: %v", path, err)
}
@@ -54,7 +54,7 @@ func (c *Controller) ServeGetPlaylist(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "please provide an `id` parameter")
}
playlist, err := c.PlaylistStore.Read(playlistIDDecode(playlistID))
playlist, err := c.playlistStore.Read(playlistIDDecode(playlistID))
if err != nil {
return spec.NewError(70, "playlist with id %s not found", playlistID)
}
@@ -75,7 +75,7 @@ func (c *Controller) ServeCreatePlaylist(r *http.Request) *spec.Response {
playlistPath := playlistIDDecode(playlistID)
var playlist playlistp.Playlist
if pl, _ := c.PlaylistStore.Read(playlistPath); pl != nil {
if pl, _ := c.playlistStore.Read(playlistPath); pl != nil {
playlist = *pl
}
@@ -94,7 +94,7 @@ func (c *Controller) ServeCreatePlaylist(r *http.Request) *spec.Response {
playlist.Items = nil
ids := params.GetOrIDList("songId", nil)
for _, id := range ids {
r, err := specidpaths.Locate(c.DB, c.PodcastsPath, id)
r, err := specidpaths.Locate(c.dbc, id)
if err != nil {
return spec.NewError(0, "lookup id %v: %v", id, err)
}
@@ -104,7 +104,7 @@ func (c *Controller) ServeCreatePlaylist(r *http.Request) *spec.Response {
if playlistPath == "" {
playlistPath = playlistp.NewPath(user.ID, fmt.Sprint(time.Now().UnixMilli()))
}
if err := c.PlaylistStore.Write(playlistPath, &playlist); err != nil {
if err := c.playlistStore.Write(playlistPath, &playlist); err != nil {
return spec.NewError(0, "save playlist: %v", err)
}
@@ -123,7 +123,7 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
playlistID := params.GetFirstOr( /* default */ "", "id", "playlistId")
playlistPath := playlistIDDecode(playlistID)
playlist, err := c.PlaylistStore.Read(playlistPath)
playlist, err := c.playlistStore.Read(playlistPath)
if err != nil {
return spec.NewError(0, "find playlist: %v", err)
}
@@ -154,7 +154,7 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
// add items
if ids, err := params.GetIDList("songIdToAdd"); err == nil {
for _, id := range ids {
item, err := specidpaths.Locate(c.DB, c.PodcastsPath, id)
item, err := specidpaths.Locate(c.dbc, id)
if err != nil {
return spec.NewError(0, "locate id %q: %v", id, err)
}
@@ -162,7 +162,7 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
}
}
if err := c.PlaylistStore.Write(playlistPath, playlist); err != nil {
if err := c.playlistStore.Write(playlistPath, playlist); err != nil {
return spec.NewError(0, "save playlist: %v", err)
}
return spec.NewResponse()
@@ -171,7 +171,7 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
func (c *Controller) ServeDeletePlaylist(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
playlistID := params.GetFirstOr( /* default */ "", "id", "playlistId")
if err := c.PlaylistStore.Delete(playlistIDDecode(playlistID)); err != nil {
if err := c.playlistStore.Delete(playlistIDDecode(playlistID)); err != nil {
return spec.NewError(0, "delete playlist: %v", err)
}
return spec.NewResponse()
@@ -180,6 +180,7 @@ func (c *Controller) ServeDeletePlaylist(r *http.Request) *spec.Response {
func playlistIDEncode(path string) string {
return base64.URLEncoding.EncodeToString([]byte(path))
}
func playlistIDDecode(id string) string {
path, _ := base64.URLEncoding.DecodeString(id)
return string(path)
@@ -187,7 +188,7 @@ func playlistIDDecode(id string) string {
func playlistRender(c *Controller, params params.Params, playlistID string, playlist *playlistp.Playlist, withItems bool) (*spec.Playlist, error) {
user := &db.User{}
if err := c.DB.Where("id=?", playlist.UserID).Find(user).Error; err != nil {
if err := c.dbc.Where("id=?", playlist.UserID).Find(user).Error; err != nil {
return nil, fmt.Errorf("find user by id: %w", err)
}
@@ -204,10 +205,10 @@ func playlistRender(c *Controller, params params.Params, playlistID string, play
return resp, nil
}
transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, path := range playlist.Items {
file, err := specidpaths.Lookup(c.DB, PathsOf(c.MusicPaths), c.PodcastsPath, path)
file, err := specidpaths.Lookup(c.dbc, MusicPaths(c.musicPaths), c.podcastsPath, path)
if err != nil {
log.Printf("error looking up path %q: %s", path, err)
continue
@@ -217,27 +218,22 @@ func playlistRender(c *Controller, params params.Params, playlistID string, play
switch id := file.SID(); id.Type {
case specid.Track:
var track db.Track
if err := c.DB.Where("id=?", id.Value).Preload("Album").Preload("Album.Artists").Preload("TrackStar", "user_id=?", user.ID).Preload("TrackRating", "user_id=?", user.ID).Find(&track).Error; errors.Is(err, gorm.ErrRecordNotFound) {
if err := c.dbc.Where("id=?", id.Value).Preload("Album").Preload("Album.Artists").Preload("Artists").Preload("TrackStar", "user_id=?", user.ID).Preload("TrackRating", "user_id=?", user.ID).Find(&track).Error; errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("load track by id: %w", err)
}
trch = spec.NewTCTrackByFolder(&track, track.Album)
resp.Duration += track.Length
case specid.PodcastEpisode:
var pe db.PodcastEpisode
if err := c.DB.Where("id=?", id.Value).Find(&pe).Error; errors.Is(err, gorm.ErrRecordNotFound) {
if err := c.dbc.Preload("Podcast").Where("id=?", id.Value).Find(&pe).Error; errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("load podcast episode by id: %w", err)
}
var p db.Podcast
if err := c.DB.Where("id=?", pe.PodcastID).Find(&p).Error; errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("load podcast by id: %w", err)
}
trch = spec.NewTCPodcastEpisode(&pe, &p)
trch = spec.NewTCPodcastEpisode(&pe)
resp.Duration += pe.Length
default:
continue
}
trch.TranscodedContentType = transcodeMIME
trch.TranscodedSuffix = transcodeSuffix
trch.TranscodeMeta = transcodeMeta
resp.List = append(resp.List, trch)
}
+7 -7
View File
@@ -15,7 +15,7 @@ func (c *Controller) ServeGetPodcasts(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
isIncludeEpisodes := params.GetOrBool("includeEpisodes", true)
id, _ := params.GetID("id")
podcasts, err := c.Podcasts.GetPodcastOrAll(id.Value, isIncludeEpisodes)
podcasts, err := c.podcasts.GetPodcastOrAll(id.Value, isIncludeEpisodes)
if err != nil {
return spec.NewError(10, "failed get podcast(s): %s", err)
}
@@ -31,7 +31,7 @@ func (c *Controller) ServeGetPodcasts(r *http.Request) *spec.Response {
func (c *Controller) ServeGetNewestPodcasts(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
count := params.GetOrInt("count", 10)
episodes, err := c.Podcasts.GetNewestPodcastEpisodes(count)
episodes, err := c.podcasts.GetNewestPodcastEpisodes(count)
if err != nil {
return spec.NewError(10, "failed get podcast(s): %s", err)
}
@@ -53,7 +53,7 @@ func (c *Controller) ServeDownloadPodcastEpisode(r *http.Request) *spec.Response
if err != nil || id.Type != specid.PodcastEpisode {
return spec.NewError(10, "please provide a valid podcast episode id")
}
if err := c.Podcasts.DownloadEpisode(id.Value); err != nil {
if err := c.podcasts.DownloadEpisode(id.Value); err != nil {
return spec.NewError(10, "failed to download episode: %s", err)
}
return spec.NewResponse()
@@ -71,7 +71,7 @@ func (c *Controller) ServeCreatePodcastChannel(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "failed to parse feed: %s", err)
}
if _, err = c.Podcasts.AddNewPodcast(rssURL, feed); err != nil {
if _, err = c.podcasts.AddNewPodcast(rssURL, feed); err != nil {
return spec.NewError(10, "failed to add feed: %s", err)
}
return spec.NewResponse()
@@ -82,7 +82,7 @@ func (c *Controller) ServeRefreshPodcasts(r *http.Request) *spec.Response {
if !user.IsAdmin {
return spec.NewError(50, "user not admin")
}
if err := c.Podcasts.RefreshPodcasts(); err != nil {
if err := c.podcasts.RefreshPodcasts(); err != nil {
return spec.NewError(10, "failed to refresh feeds: %s", err)
}
return spec.NewResponse()
@@ -98,7 +98,7 @@ func (c *Controller) ServeDeletePodcastChannel(r *http.Request) *spec.Response {
if err != nil || id.Type != specid.Podcast {
return spec.NewError(10, "please provide a valid podcast id")
}
if err := c.Podcasts.DeletePodcast(id.Value); err != nil {
if err := c.podcasts.DeletePodcast(id.Value); err != nil {
return spec.NewError(10, "failed to delete podcast: %s", err)
}
return spec.NewResponse()
@@ -114,7 +114,7 @@ func (c *Controller) ServeDeletePodcastEpisode(r *http.Request) *spec.Response {
if err != nil || id.Type != specid.PodcastEpisode {
return spec.NewError(10, "please provide a valid podcast episode id")
}
if err := c.Podcasts.DeletePodcastEpisode(id.Value); err != nil {
if err := c.podcasts.DeletePodcastEpisode(id.Value); err != nil {
return spec.NewError(10, "failed to delete podcast: %s", err)
}
return spec.NewResponse()
+95 -154
View File
@@ -9,14 +9,14 @@ import (
"log"
"net/http"
"os"
"path"
"path/filepath"
"time"
"github.com/disintegration/imaging"
"github.com/jinzhu/gorm"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/server/ctrlsubsonic/artistinfocache"
"go.senan.xyz/gonic/infocache/artistinfocache"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
@@ -30,110 +30,72 @@ import (
// b) return a non-nil spec.Response
// _but not both_
func streamGetTransPref(dbc *db.DB, userID int, client string) (*db.TranscodePreference, error) {
var pref db.TranscodePreference
err := dbc.
Where("user_id=?", userID).
Where("client COLLATE NOCASE IN (?)", []string{"*", client}).
Order("client DESC"). // ensure "*" is last if it's there
First(&pref).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("find transcode preference: %w", err)
}
return &pref, nil
}
func streamGetTransPrefProfile(dbc *db.DB, userID int, client string) (mime string, suffix string) {
pref, _ := streamGetTransPref(dbc, userID, client)
if pref == nil {
return "", ""
}
profile, ok := transcode.UserProfiles[pref.Profile]
if !ok {
return "", ""
}
return profile.MIME(), profile.Suffix()
}
var errUnknownMediaType = fmt.Errorf("media type is unknown")
func streamUpdateStats(dbc *db.DB, userID int, track *db.Track, playTime time.Time) error {
var play db.Play
err := dbc.
Where("album_id=? AND user_id=?", track.AlbumID, userID).
First(&play).
Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return fmt.Errorf("find stat: %w", err)
}
play.AlbumID = track.AlbumID
play.UserID = userID
play.Count++ // for getAlbumList?type=frequent
play.Length += track.Length
if playTime.After(play.Time) {
play.Time = playTime // for getAlbumList?type=recent
}
if err := dbc.Save(&play).Error; err != nil {
return fmt.Errorf("save stat: %w", err)
}
return nil
}
func streamUpdatePodcastEpisodeStats(dbc *db.DB, peID int) error {
var pe db.PodcastEpisode
err := dbc.
Where("id=?", peID).
First(&pe).
Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return fmt.Errorf("find podcast episode: %w", err)
}
pe.ModifiedAt = time.Now()
if err := dbc.Save(&pe).Error; err != nil {
return fmt.Errorf("save podcast episode: %w", err)
}
return nil
}
const (
coverDefaultSize = 600
coverCacheFormat = "png"
)
func (c *Controller) ServeGetCoverArt(w http.ResponseWriter, r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
if err != nil {
return spec.NewError(10, "please provide an `id` parameter")
}
size := params.GetOrInt("size", coverDefaultSize)
cachePath := filepath.Join(
c.cacheCoverPath,
fmt.Sprintf("%s-%d.%s", id.String(), size, coverCacheFormat),
)
_, err = os.Stat(cachePath)
switch {
case os.IsNotExist(err):
reader, err := coverFor(c.dbc, c.artistInfoCache, id)
if err != nil {
return spec.NewError(10, "couldn't find cover %q: %v", id, err)
}
defer reader.Close()
if err := coverScaleAndSave(reader, cachePath, size); err != nil {
log.Printf("error scaling cover: %v", err)
return nil
}
case err != nil:
log.Printf("error stating %q: %v", cachePath, err)
return nil
}
w.Header().Set("Cache-Control", "public, max-age=3600")
http.ServeFile(w, r, cachePath)
return nil
}
var (
errCoverNotFound = errors.New("could not find a cover with that id")
errCoverEmpty = errors.New("no cover found")
)
// TODO: can we use specidpaths.Locate here?
func coverFor(dbc *db.DB, artistInfoCache *artistinfocache.ArtistInfoCache, podcastPath string, id specid.ID) (io.ReadCloser, error) {
func coverFor(dbc *db.DB, artistInfoCache *artistinfocache.ArtistInfoCache, id specid.ID) (io.ReadCloser, error) {
switch id.Type {
case specid.Album:
return coverForAlbum(dbc, id.Value)
case specid.Artist:
return coverForArtist(artistInfoCache, id.Value)
case specid.Podcast:
return coverForPodcast(dbc, podcastPath, id.Value)
return coverForPodcast(dbc, id.Value)
case specid.PodcastEpisode:
return coverGetPathPodcastEpisode(dbc, podcastPath, id.Value)
return coverGetPathPodcastEpisode(dbc, id.Value)
default:
return nil, errCoverNotFound
}
}
func coverForAlbum(dbc *db.DB, id int) (*os.File, error) {
folder := &db.Album{}
var folder db.Album
err := dbc.DB.
Select("id, root_dir, left_path, right_path, cover").
First(folder, id).
First(&folder, id).
Error
if err != nil {
return nil, fmt.Errorf("select album: %w", err)
@@ -141,7 +103,7 @@ func coverForAlbum(dbc *db.DB, id int) (*os.File, error) {
if folder.Cover == "" {
return nil, errCoverEmpty
}
return os.Open(path.Join(folder.RootDir, folder.LeftPath, folder.RightPath, folder.Cover))
return os.Open(filepath.Join(folder.RootDir, folder.LeftPath, folder.RightPath, folder.Cover))
}
func coverForArtist(artistInfoCache *artistinfocache.ArtistInfoCache, id int) (io.ReadCloser, error) {
@@ -159,39 +121,33 @@ func coverForArtist(artistInfoCache *artistinfocache.ArtistInfoCache, id int) (i
return resp.Body, nil
}
func coverForPodcast(dbc *db.DB, podcastPath string, id int) (*os.File, error) {
podcast := &db.Podcast{}
func coverForPodcast(dbc *db.DB, id int) (*os.File, error) {
var podcast db.Podcast
err := dbc.
First(podcast, id).
First(&podcast, id).
Error
if err != nil {
return nil, fmt.Errorf("select podcast: %w", err)
}
if podcast.ImagePath == "" {
if podcast.Image == "" {
return nil, errCoverEmpty
}
return os.Open(path.Join(podcastPath, podcast.ImagePath))
return os.Open(filepath.Join(podcast.RootDir, podcast.Image))
}
func coverGetPathPodcastEpisode(dbc *db.DB, podcastPath string, id int) (*os.File, error) {
episode := &db.PodcastEpisode{}
func coverGetPathPodcastEpisode(dbc *db.DB, id int) (*os.File, error) {
var pe db.PodcastEpisode
err := dbc.
First(episode, id).
Preload("Podcast").
First(&pe, id).
Error
if err != nil {
return nil, fmt.Errorf("select episode: %w", err)
}
podcast := &db.Podcast{}
err = dbc.
First(podcast, episode.PodcastID).
Error
if err != nil {
return nil, fmt.Errorf("select podcast: %w", err)
}
if podcast.ImagePath == "" {
if pe.Podcast == nil || pe.Podcast.Image == "" {
return nil, errCoverEmpty
}
return os.Open(path.Join(podcastPath, podcast.ImagePath))
return os.Open(filepath.Join(pe.Podcast.RootDir, pe.Podcast.Image))
}
func coverScaleAndSave(reader io.Reader, cachePath string, size int) error {
@@ -205,46 +161,11 @@ func coverScaleAndSave(reader io.Reader, cachePath string, size int) error {
width = src.Bounds().Dx()
}
if err = imaging.Save(imaging.Resize(src, width, 0, imaging.Lanczos), cachePath); err != nil {
return fmt.Errorf("caching `%s`: %w", cachePath, err)
return fmt.Errorf("caching %q: %w", cachePath, err)
}
return nil
}
func (c *Controller) ServeGetCoverArt(w http.ResponseWriter, r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
if err != nil {
return spec.NewError(10, "please provide an `id` parameter")
}
size := params.GetOrInt("size", coverDefaultSize)
cachePath := path.Join(
c.CacheCoverPath,
fmt.Sprintf("%s-%d.%s", id.String(), size, coverCacheFormat),
)
_, err = os.Stat(cachePath)
switch {
case os.IsNotExist(err):
reader, err := coverFor(c.DB, c.ArtistInfoCache, c.PodcastsPath, id)
if err != nil {
return spec.NewError(10, "couldn't find cover `%s`: %v", id, err)
}
defer reader.Close()
if err := coverScaleAndSave(reader, cachePath, size); err != nil {
log.Printf("error scaling cover: %v", err)
return nil
}
case err != nil:
log.Printf("error stating `%s`: %v", cachePath, err)
return nil
}
w.Header().Set("Cache-Control", "public, max-age=3600")
http.ServeFile(w, r, cachePath)
return nil
}
func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
@@ -253,7 +174,7 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
return spec.NewError(10, "please provide an `id` parameter")
}
file, err := specidpaths.Locate(c.DB, c.PodcastsPath, id)
file, err := specidpaths.Locate(c.dbc, id)
if err != nil {
return spec.NewError(0, "error looking up id %s: %v", id, err)
}
@@ -263,31 +184,16 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
return spec.NewError(0, "type of id does not contain audio")
}
if track, ok := audioFile.(*db.Track); ok && track.Album != nil {
defer func() {
if err := streamUpdateStats(c.DB, user.ID, track, time.Now()); err != nil {
log.Printf("error updating track status: %v", err)
}
}()
}
if pe, ok := audioFile.(*db.PodcastEpisode); ok {
defer func() {
if err := streamUpdatePodcastEpisodeStats(c.DB, pe.ID); err != nil {
log.Printf("error updating podcast episode status: %v", err)
}
}()
}
maxBitRate, _ := params.GetInt("maxBitRate")
format, _ := params.Get("format")
timeOffset, _ := params.GetInt("timeOffset")
if format == "raw" || maxBitRate >= audioFile.AudioBitrate() {
http.ServeFile(w, r, file.AbsPath())
return nil
}
pref, err := streamGetTransPref(c.DB, user.ID, params.GetOr("c", ""))
pref, err := streamGetTransodePreference(c.dbc, user.ID, params.GetOr("c", ""))
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "couldn't find transcode preference: %v", err)
}
@@ -303,11 +209,14 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
if maxBitRate > 0 && int(profile.BitRate()) > maxBitRate {
profile = transcode.WithBitrate(profile, transcode.BitRate(maxBitRate))
}
if timeOffset > 0 {
profile = transcode.WithSeek(profile, time.Second*time.Duration(timeOffset))
}
log.Printf("trancoding to %q with max bitrate %dk", profile.MIME(), profile.BitRate())
w.Header().Set("Content-Type", profile.MIME())
if err := c.Transcoder.Transcode(r.Context(), profile, file.AbsPath(), w); err != nil && !errors.Is(err, transcode.ErrFFmpegKilled) {
if err := c.transcoder.Transcode(r.Context(), profile, file.AbsPath(), w); err != nil && !errors.Is(err, transcode.ErrFFmpegKilled) {
return spec.NewError(0, "error transcoding: %v", err)
}
@@ -324,10 +233,42 @@ func (c *Controller) ServeGetAvatar(w http.ResponseWriter, r *http.Request) *spe
if err != nil {
return spec.NewError(10, "please provide an `username` parameter")
}
reqUser := c.DB.GetUserByName(username)
reqUser := c.dbc.GetUserByName(username)
if (user != reqUser) && !user.IsAdmin {
return spec.NewError(50, "user not admin")
}
http.ServeContent(w, r, "", time.Now(), bytes.NewReader(reqUser.Avatar))
return nil
}
func streamGetTransodePreference(dbc *db.DB, userID int, client string) (*db.TranscodePreference, error) {
var pref db.TranscodePreference
err := dbc.
Where("user_id=?", userID).
Where("client COLLATE NOCASE IN (?)", []string{"*", client}).
Order("client DESC"). // ensure "*" is last if it's there
First(&pref).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("find transcode preference: %w", err)
}
return &pref, nil
}
func streamGetTranscodeMeta(dbc *db.DB, userID int, client string) spec.TranscodeMeta {
pref, _ := streamGetTransodePreference(dbc, userID, client)
if pref == nil {
return spec.TranscodeMeta{}
}
profile, ok := transcode.UserProfiles[pref.Profile]
if !ok {
return spec.TranscodeMeta{}
}
return spec.TranscodeMeta{
TranscodedContentType: profile.MIME(),
TranscodedSuffix: profile.Suffix(),
}
}
-211
View File
@@ -1,211 +0,0 @@
package ctrlsubsonic
import (
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"log"
"net/http"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"github.com/go-ldap/ldap"
)
func checkCredsToken(password, token, salt string) bool {
toHash := fmt.Sprintf("%s%s", password, salt)
hash := md5.Sum([]byte(toHash))
expToken := hex.EncodeToString(hash[:])
return token == expToken
}
func checkCredsBasic(password, given string) bool {
if len(given) >= 4 && given[:4] == "enc:" {
bytes, _ := hex.DecodeString(given[4:])
given = string(bytes)
}
return password == given
}
func (c *Controller) WithParams(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := params.New(r)
withParams := context.WithValue(r.Context(), CtxParams, params)
next.ServeHTTP(w, r.WithContext(withParams))
})
}
func (c *Controller) WithRequiredParams(next http.Handler) http.Handler {
requiredParameters := []string{
"u", "c",
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := r.Context().Value(CtxParams).(params.Params)
for _, req := range requiredParameters {
if _, err := params.Get(req); err != nil {
_ = writeResp(w, r, spec.NewError(10,
"please provide a `%s` parameter", req))
return
}
}
next.ServeHTTP(w, r)
})
}
func (c *Controller) WithUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := r.Context().Value(CtxParams).(params.Params)
// ignoring errors here, a middleware has already ensured they exist
username, _ := params.Get("u")
password, _ := params.Get("p")
token, _ := params.Get("t")
salt, _ := params.Get("s")
passwordAuth := token == "" && salt == ""
tokenAuth := password == ""
if tokenAuth == passwordAuth {
_ = writeResp(w, r, spec.NewError(10,
"please provide `t` and `s`, or just `p`"))
return
}
user := c.DB.GetUserByName(username)
newLDAPUser := false
if user == nil {
newLDAPUser = true
// Because the user wasn't found we can now try
// to use LDAP. ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
if ldapFQDN != "" && err == nil {
// The configuration page wouldn't allow these setting to not be set
// while LDAP is enabled (a FQDN/IP is set).
bindUID, _ := c.DB.GetSetting("ldap_bind_user")
bindPWD, _ := c.DB.GetSetting("ldap_bind_user_password")
ldapPort, _ := c.DB.GetSetting("ldap_port")
baseDN, _ := c.DB.GetSetting("ldap_base_dn")
filter, _ := c.DB.GetSetting("ldap_filter")
tls, _ := c.DB.GetSetting("ldap_tls")
// Now, we can try to connect to the LDAP server.
l, err := createLDAPconnection(tls, ldapFQDN, ldapPort)
if err != nil {
// Return a generic error.
_ = writeResp(w, r, spec.NewError(0, "Failed to connect to LDAP server."))
return
}
defer l.Close()
// After we have a connection, let's try binding
_, err = l.SimpleBind(&ldap.SimpleBindRequest{
Username: fmt.Sprintf("uid=%s,%s", bindUID, baseDN),
Password: bindPWD,
})
if err != nil {
log.Println("Failed to bind to LDAP:", err)
_ = writeResp(w, r, spec.NewError(40, "Wrong username or password."))
return
}
searchReq := ldap.NewSearchRequest(
baseDN,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&%s(uid=%s))", filter, ldap.EscapeFilter(username)),
[]string{"dn"},
nil,
)
result, err := l.Search(searchReq)
if err != nil {
log.Println("failed to query LDAP:", err)
}
if len(result.Entries) > 1 {
_ = writeResp(w, r, spec.NewError(40, "Ambiguous user: `%s`", username))
} else if len(result.Entries) == 1 {
user := db.User{
Name: username,
Password: "", // no password because we want auth to fail.
}
if err := c.DB.Create(&user).Error; err != nil {
fmt.Println("User created via LDAP:", username)
}
} else {
_ = writeResp(w, r, spec.NewError(40, "invalid username `%s`", username))
return
}
} else {
_ = writeResp(w, r, spec.NewError(40,
"invalid username `%s`", username))
return
}
}
var credsOk bool
if tokenAuth && !newLDAPUser && user != nil {
credsOk = checkCredsToken(user.Password, token, salt)
} else if !newLDAPUser && user != nil {
credsOk = checkCredsBasic(user.Password, password)
}
if !credsOk {
// Because internal authentication failed, we can now try to use LDAP, if
// it was enabled by the user.
ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
if ldapFQDN != "" && err == nil {
// The configuration page wouldn't allow these setting to not be set
// while LDAP is enabled (a FQDN/IP is set).
ldapPort, _ := c.DB.GetSetting("ldap_port")
baseDN, _ := c.DB.GetSetting("ldap_base_dn")
tls, _ := c.DB.GetSetting("ldap_tls")
// Now, we can try to connect to the LDAP server.
l, err := createLDAPconnection(tls, ldapFQDN, ldapPort)
if err != nil {
// Return a generic error.
_ = writeResp(w, r, spec.NewError(0, "Failed to connect to LDAP server."))
return
}
defer l.Close()
// After we have a connection, let's try binding
_, err = l.SimpleBind(&ldap.SimpleBindRequest{
Username: fmt.Sprintf("uid=%s,%s", username, baseDN),
Password: password,
})
if err == nil {
withUser := context.WithValue(r.Context(), CtxUser, user)
next.ServeHTTP(w, r.WithContext(withUser))
return
}
}
_ = writeResp(w, r, spec.NewError(40, "invalid password"))
return
}
withUser := context.WithValue(r.Context(), CtxUser, user)
next.ServeHTTP(w, r.WithContext(withUser))
})
}
func createLDAPconnection(tls string, fqdn string, port string) (*ldap.Conn, error) {
protocol := "ldap"
if tls == "true" {
protocol = "ldaps"
}
// Now, we can try to connect to the LDAP server.
l, err := ldap.DialURL(fmt.Sprintf("%s://%s:%s", protocol, fqdn, port))
if err != nil {
// Warn the server and return a generic error.
log.Println("Failed to connect to LDAP server", err)
return nil, err
}
return l, nil
}
+91 -94
View File
@@ -35,100 +35,7 @@ import (
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
)
var (
ErrNoValues = errors.New("no values provided")
)
// some thin wrappers
// may be needed when cleaning up parse() below
func parseStr(in string) (string, error) { return in, nil }
func parseInt(in string) (int, error) { return strconv.Atoi(in) }
func parseFloat(in string) (float64, error) { return strconv.ParseFloat(in, 64) }
func parseID(in string) (specid.ID, error) { return specid.New(in) }
func parseBool(in string) (bool, error) { return strconv.ParseBool(in) }
func parseTime(in string) (time.Time, error) {
ms, err := strconv.Atoi(in)
if err != nil {
return time.Time{}, err
}
ns := int64(ms) * 1e6
return time.Unix(0, ns), nil
}
func parse(values []string, i interface{}) error {
if len(values) == 0 {
return ErrNoValues
}
var err error
switch v := i.(type) {
// *T
case *string:
*v, err = parseStr(values[0])
case *int:
*v, err = parseInt(values[0])
case *float64:
*v, err = parseFloat(values[0])
case *specid.ID:
*v, err = parseID(values[0])
case *bool:
*v, err = parseBool(values[0])
case *time.Time:
*v, err = parseTime(values[0])
// *[]T
case *[]string:
for _, value := range values {
parsed, err := parseStr(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]int:
for _, value := range values {
parsed, err := parseInt(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]float64:
for _, value := range values {
parsed, err := parseFloat(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]specid.ID:
for _, value := range values {
parsed, err := parseID(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]bool:
for _, value := range values {
parsed, err := parseBool(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]time.Time:
for _, value := range values {
parsed, err := parseTime(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
}
return err
}
var ErrNoValues = errors.New("no values provided")
type Params url.Values
@@ -464,3 +371,93 @@ func (p Params) GetFirstOrTime(or time.Time, keys ...string) time.Time {
}
return or
}
// some thin wrappers
// may be needed when cleaning up parse() below
func parseStr(in string) (string, error) { return in, nil }
func parseInt(in string) (int, error) { return strconv.Atoi(in) }
func parseFloat(in string) (float64, error) { return strconv.ParseFloat(in, 64) }
func parseID(in string) (specid.ID, error) { return specid.New(in) }
func parseBool(in string) (bool, error) { return strconv.ParseBool(in) }
func parseTime(in string) (time.Time, error) {
ms, err := strconv.Atoi(in)
if err != nil {
return time.Time{}, err
}
ns := int64(ms) * 1e6
return time.Unix(0, ns), nil
}
func parse(values []string, i interface{}) error {
if len(values) == 0 {
return ErrNoValues
}
var err error
switch v := i.(type) {
// *T
case *string:
*v, err = parseStr(values[0])
case *int:
*v, err = parseInt(values[0])
case *float64:
*v, err = parseFloat(values[0])
case *specid.ID:
*v, err = parseID(values[0])
case *bool:
*v, err = parseBool(values[0])
case *time.Time:
*v, err = parseTime(values[0])
// *[]T
case *[]string:
for _, value := range values {
parsed, err := parseStr(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]int:
for _, value := range values {
parsed, err := parseInt(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]float64:
for _, value := range values {
parsed, err := parseFloat(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]specid.ID:
for _, value := range values {
parsed, err := parseID(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]bool:
for _, value := range values {
parsed, err := parseBool(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
case *[]time.Time:
for _, value := range values {
parsed, err := parseTime(value)
if err != nil {
return err
}
*v = append(*v, parsed)
}
}
return err
}
-86
View File
@@ -1,86 +0,0 @@
package ctrlsubsonic
import "github.com/gorilla/mux"
func AddRoutes(c *Controller, r *mux.Router) {
r.Use(c.WithParams)
r.Use(c.WithRequiredParams)
r.Use(c.WithUser)
// common
r.Handle("/getLicense{_:(?:\\.view)?}", c.H(c.ServeGetLicence))
r.Handle("/getMusicFolders{_:(?:\\.view)?}", c.H(c.ServeGetMusicFolders))
r.Handle("/getScanStatus{_:(?:\\.view)?}", c.H(c.ServeGetScanStatus))
r.Handle("/ping{_:(?:\\.view)?}", c.H(c.ServePing))
r.Handle("/scrobble{_:(?:\\.view)?}", c.H(c.ServeScrobble))
r.Handle("/startScan{_:(?:\\.view)?}", c.H(c.ServeStartScan))
r.Handle("/getUser{_:(?:\\.view)?}", c.H(c.ServeGetUser))
r.Handle("/getPlaylists{_:(?:\\.view)?}", c.H(c.ServeGetPlaylists))
r.Handle("/getPlaylist{_:(?:\\.view)?}", c.H(c.ServeGetPlaylist))
r.Handle("/createPlaylist{_:(?:\\.view)?}", c.H(c.ServeCreatePlaylist))
r.Handle("/updatePlaylist{_:(?:\\.view)?}", c.H(c.ServeUpdatePlaylist))
r.Handle("/deletePlaylist{_:(?:\\.view)?}", c.H(c.ServeDeletePlaylist))
r.Handle("/savePlayQueue{_:(?:\\.view)?}", c.H(c.ServeSavePlayQueue))
r.Handle("/getPlayQueue{_:(?:\\.view)?}", c.H(c.ServeGetPlayQueue))
r.Handle("/getSong{_:(?:\\.view)?}", c.H(c.ServeGetSong))
r.Handle("/getRandomSongs{_:(?:\\.view)?}", c.H(c.ServeGetRandomSongs))
r.Handle("/getSongsByGenre{_:(?:\\.view)?}", c.H(c.ServeGetSongsByGenre))
r.Handle("/jukeboxControl{_:(?:\\.view)?}", c.H(c.ServeJukebox))
r.Handle("/getBookmarks{_:(?:\\.view)?}", c.H(c.ServeGetBookmarks))
r.Handle("/createBookmark{_:(?:\\.view)?}", c.H(c.ServeCreateBookmark))
r.Handle("/deleteBookmark{_:(?:\\.view)?}", c.H(c.ServeDeleteBookmark))
r.Handle("/getTopSongs{_:(?:\\.view)?}", c.H(c.ServeGetTopSongs))
r.Handle("/getSimilarSongs{_:(?:\\.view)?}", c.H(c.ServeGetSimilarSongs))
r.Handle("/getSimilarSongs2{_:(?:\\.view)?}", c.H(c.ServeGetSimilarSongsTwo))
r.Handle("/getLyrics{_:(?:\\.view)?}", c.H(c.ServeGetLyrics))
// raw
r.Handle("/getCoverArt{_:(?:\\.view)?}", c.HR(c.ServeGetCoverArt))
r.Handle("/stream{_:(?:\\.view)?}", c.HR(c.ServeStream))
r.Handle("/download{_:(?:\\.view)?}", c.HR(c.ServeStream))
r.Handle("/getAvatar{_:(?:\\.view)?}", c.HR(c.ServeGetAvatar))
// browse by tag
r.Handle("/getAlbum{_:(?:\\.view)?}", c.H(c.ServeGetAlbum))
r.Handle("/getAlbumList2{_:(?:\\.view)?}", c.H(c.ServeGetAlbumListTwo))
r.Handle("/getArtist{_:(?:\\.view)?}", c.H(c.ServeGetArtist))
r.Handle("/getArtists{_:(?:\\.view)?}", c.H(c.ServeGetArtists))
r.Handle("/search3{_:(?:\\.view)?}", c.H(c.ServeSearchThree))
r.Handle("/getArtistInfo2{_:(?:\\.view)?}", c.H(c.ServeGetArtistInfoTwo))
r.Handle("/getStarred2{_:(?:\\.view)?}", c.H(c.ServeGetStarredTwo))
// browse by folder
r.Handle("/getIndexes{_:(?:\\.view)?}", c.H(c.ServeGetIndexes))
r.Handle("/getMusicDirectory{_:(?:\\.view)?}", c.H(c.ServeGetMusicDirectory))
r.Handle("/getAlbumList{_:(?:\\.view)?}", c.H(c.ServeGetAlbumList))
r.Handle("/search2{_:(?:\\.view)?}", c.H(c.ServeSearchTwo))
r.Handle("/getGenres{_:(?:\\.view)?}", c.H(c.ServeGetGenres))
r.Handle("/getArtistInfo{_:(?:\\.view)?}", c.H(c.ServeGetArtistInfo))
r.Handle("/getStarred{_:(?:\\.view)?}", c.H(c.ServeGetStarred))
// star / rating
r.Handle("/star{_:(?:\\.view)?}", c.H(c.ServeStar))
r.Handle("/unstar{_:(?:\\.view)?}", c.H(c.ServeUnstar))
r.Handle("/setRating{_:(?:\\.view)?}", c.H(c.ServeSetRating))
// podcasts
r.Handle("/getPodcasts{_:(?:\\.view)?}", c.H(c.ServeGetPodcasts))
r.Handle("/getNewestPodcasts{_:(?:\\.view)?}", c.H(c.ServeGetNewestPodcasts))
r.Handle("/downloadPodcastEpisode{_:(?:\\.view)?}", c.H(c.ServeDownloadPodcastEpisode))
r.Handle("/createPodcastChannel{_:(?:\\.view)?}", c.H(c.ServeCreatePodcastChannel))
r.Handle("/refreshPodcasts{_:(?:\\.view)?}", c.H(c.ServeRefreshPodcasts))
r.Handle("/deletePodcastChannel{_:(?:\\.view)?}", c.H(c.ServeDeletePodcastChannel))
r.Handle("/deletePodcastEpisode{_:(?:\\.view)?}", c.H(c.ServeDeletePodcastEpisode))
// internet radio
r.Handle("/getInternetRadioStations{_:(?:\\.view)?}", c.H(c.ServeGetInternetRadioStations))
r.Handle("/createInternetRadioStation{_:(?:\\.view)?}", c.H(c.ServeCreateInternetRadioStation))
r.Handle("/updateInternetRadioStation{_:(?:\\.view)?}", c.H(c.ServeUpdateInternetRadioStation))
r.Handle("/deleteInternetRadioStation{_:(?:\\.view)?}", c.H(c.ServeDeleteInternetRadioStation))
// middlewares should be run for not found handler
// https://github.com/gorilla/mux/issues/416
notFoundHandler := c.H(c.ServeNotFound)
notFoundRoute := r.NewRoute().Handler(notFoundHandler)
r.NotFoundHandler = notFoundRoute.GetHandler()
}
@@ -1,8 +1,7 @@
package spec
import (
"path"
"strings"
"path/filepath"
"go.senan.xyz/gonic/db"
)
@@ -13,6 +12,8 @@ func NewAlbumByFolder(f *db.Album) *Album {
ID: f.SID(),
IsDir: true,
ParentID: f.ParentSID(),
Album: f.RightPath,
Name: f.RightPath,
Title: f.RightPath,
TrackCount: f.ChildCount,
Duration: f.Duration,
@@ -62,14 +63,13 @@ func NewTCTrackByFolder(t *db.Track, parent *db.Album) *TrackChild {
Title: t.TagTitle,
TrackNumber: t.TagTrackNumber,
DiscNumber: t.TagDiscNumber,
Path: path.Join(
Path: filepath.Join(
parent.LeftPath,
parent.RightPath,
t.Filename,
),
ParentID: parent.SID(),
Duration: t.Length,
Genre: strings.Join(t.GenreStrings(), ", "),
Year: parent.TagYear,
Bitrate: t.Bitrate,
IsDir: false,
@@ -92,24 +92,36 @@ func NewTCTrackByFolder(t *db.Track, parent *db.Album) *TrackChild {
if t.TrackRating != nil {
trCh.UserRating = t.TrackRating.Rating
}
if len(t.Genres) > 0 {
trCh.Genre = t.Genres[0].Name
}
for _, g := range t.Genres {
trCh.Genres = append(trCh.Genres, &GenreRef{Name: g.Name})
}
for _, a := range t.Artists {
trCh.Artists = append(trCh.Artists, &ArtistRef{ID: a.SID(), Name: a.Name})
}
return trCh
}
func NewTCPodcastEpisode(pe *db.PodcastEpisode, parent *db.Podcast) *TrackChild {
func NewTCPodcastEpisode(pe *db.PodcastEpisode) *TrackChild {
trCh := &TrackChild{
ID: pe.SID(),
ContentType: pe.MIME(),
Suffix: pe.Ext(),
Size: pe.Size,
Title: pe.Title,
Path: pe.Path,
ParentID: parent.SID(),
ParentID: pe.SID(),
Duration: pe.Length,
Bitrate: pe.Bitrate,
IsDir: false,
Type: "podcastepisode",
CreatedAt: pe.CreatedAt,
}
if pe.Podcast != nil {
trCh.ParentID = pe.Podcast.SID()
trCh.Path = pe.AbsPath()
}
return trCh
}
+30 -15
View File
@@ -1,9 +1,8 @@
package spec
import (
"path"
"path/filepath"
"sort"
"strings"
"go.senan.xyz/gonic/db"
)
@@ -12,10 +11,13 @@ func NewAlbumByTags(a *db.Album, artists []*db.Artist) *Album {
ret := &Album{
Created: a.CreatedAt,
ID: a.SID(),
Album: a.TagTitle,
Name: a.TagTitle,
Title: a.TagTitle,
Year: a.TagYear,
TrackCount: a.ChildCount,
Duration: a.Duration,
DisplayArtist: a.TagAlbumArtist,
AverageRating: formatRating(a.AverageRating),
}
if a.Cover != "" {
@@ -44,31 +46,32 @@ func NewAlbumByTags(a *db.Album, artists []*db.Artist) *Album {
ret.Genre = a.Genres[0].Name
}
for _, g := range a.Genres {
ret.Genres = append(ret.Genres, g.Name)
ret.Genres = append(ret.Genres, &GenreRef{Name: g.Name})
}
return ret
}
func NewTrackByTags(t *db.Track, album *db.Album) *TrackChild {
ret := &TrackChild{
ID: t.SID(),
ContentType: t.MIME(),
Suffix: formatExt(t.Ext()),
ParentID: t.AlbumSID(),
CreatedAt: t.CreatedAt,
Size: t.Size,
Title: t.TagTitle,
Artist: t.TagTrackArtist,
TrackNumber: t.TagTrackNumber,
DiscNumber: t.TagDiscNumber,
Path: path.Join(
ID: t.SID(),
ContentType: t.MIME(),
Suffix: formatExt(t.Ext()),
ParentID: t.AlbumSID(),
CreatedAt: t.CreatedAt,
Size: t.Size,
Title: t.TagTitle,
Artist: t.TagTrackArtist,
DisplayArtist: t.TagTrackArtist,
AlbumDisplayArtist: album.TagAlbumArtist,
TrackNumber: t.TagTrackNumber,
DiscNumber: t.TagDiscNumber,
Path: filepath.Join(
album.LeftPath,
album.RightPath,
t.Filename,
),
Album: album.TagTitle,
AlbumID: album.SID(),
Genre: strings.Join(t.GenreStrings(), ", "),
Duration: t.Length,
Bitrate: t.Bitrate,
Type: "music",
@@ -90,6 +93,18 @@ func NewTrackByTags(t *db.Track, album *db.Album) *TrackChild {
})
ret.ArtistID = album.Artists[0].SID()
}
if len(t.Genres) > 0 {
ret.Genre = t.Genres[0].Name
}
for _, g := range t.Genres {
ret.Genres = append(ret.Genres, &GenreRef{Name: g.Name})
}
for _, a := range t.Artists {
ret.Artists = append(ret.Artists, &ArtistRef{ID: a.SID(), Name: a.Name})
}
for _, a := range album.Artists {
ret.AlbumArtists = append(ret.AlbumArtists, &ArtistRef{ID: a.SID(), Name: a.Name})
}
return ret
}
+24 -21
View File
@@ -1,13 +1,13 @@
package spec
import (
"jaytaylor.com/html2text"
"go.senan.xyz/gonic/db"
"jaytaylor.com/html2text"
)
func NewPodcastChannel(p *db.Podcast) *PodcastChannel {
desc, err := html2text.FromString(p.Description, html2text.Options{TextOnly: true})
if (err != nil) {
if err != nil {
desc = ""
}
ret := &PodcastChannel{
@@ -26,31 +26,34 @@ func NewPodcastChannel(p *db.Podcast) *PodcastChannel {
return ret
}
func NewPodcastEpisode(e *db.PodcastEpisode) *PodcastEpisode {
if e == nil {
func NewPodcastEpisode(pe *db.PodcastEpisode) *PodcastEpisode {
if pe == nil {
return nil
}
desc, err := html2text.FromString(e.Description, html2text.Options{TextOnly: true})
if (err != nil) {
desc, err := html2text.FromString(pe.Description, html2text.Options{TextOnly: true})
if err != nil {
desc = ""
}
return &PodcastEpisode{
ID: e.SID(),
StreamID: e.SID(),
ContentType: e.MIME(),
ChannelID: e.PodcastSID(),
Title: e.Title,
r := &PodcastEpisode{
ID: pe.SID(),
StreamID: pe.SID(),
ContentType: pe.MIME(),
ChannelID: pe.PodcastSID(),
Title: pe.Title,
Description: desc,
Status: string(e.Status),
CoverArt: e.PodcastSID(),
PublishDate: *e.PublishDate,
Status: string(pe.Status),
CoverArt: pe.PodcastSID(),
PublishDate: *pe.PublishDate,
Genre: "Podcast",
Duration: e.Length,
Year: e.PublishDate.Year(),
Suffix: formatExt(e.Ext()),
BitRate: e.Bitrate,
Duration: pe.Length,
Year: pe.PublishDate.Year(),
Suffix: formatExt(pe.Ext()),
BitRate: pe.Bitrate,
IsDir: false,
Path: e.Path,
Size: e.Size,
Size: pe.Size,
}
if pe.Podcast != nil {
r.Path = pe.AbsPath()
}
return r
}
+89 -50
View File
@@ -26,8 +26,10 @@ type Response struct {
XMLNS string `xml:"xmlns,attr" json:"-"`
// https://opensubsonic.netlify.app/docs/responses/subsonic-response/
Type string `xml:"type,attr" json:"type"`
ServerVersion string `xml:"serverVersion,attr" json:"serverVersion"`
Type string `xml:"type,attr" json:"type"`
ServerVersion string `xml:"serverVersion,attr" json:"serverVersion"`
OpenSubsonic bool `xml:"openSubsonic,attr" json:"openSubsonic"`
OpenSubsonicExtensions *OpenSubsonicExtensions `xml:"openSubsonicExtensions" json:"openSubsonicExtensions,omitempty"`
Error *Error `xml:"error" json:"error,omitempty"`
Albums *Albums `xml:"albumList" json:"albumList,omitempty"`
@@ -50,6 +52,7 @@ type Response struct {
Playlist *Playlist `xml:"playlist" json:"playlist,omitempty"`
ArtistInfo *ArtistInfo `xml:"artistInfo" json:"artistInfo,omitempty"`
ArtistInfoTwo *ArtistInfo `xml:"artistInfo2" json:"artistInfo2,omitempty"`
AlbumInfo *AlbumInfo `xml:"albumInfo" json:"albumInfo,omitempty"`
Genres *Genres `xml:"genres" json:"genres,omitempty"`
PlayQueue *PlayQueue `xml:"playQueue" json:"playQueue,omitempty"`
JukeboxStatus *JukeboxStatus `xml:"jukeboxStatus" json:"jukeboxStatus,omitempty"`
@@ -73,6 +76,7 @@ func NewResponse() *Response {
Version: apiVersion,
Type: gonic.Name,
ServerVersion: gonic.Version,
OpenSubsonic: true,
}
}
@@ -94,17 +98,13 @@ type Error struct {
}
func NewError(code int, message string, a ...interface{}) *Response {
return &Response{
Status: "failed",
XMLNS: xmlns,
Version: apiVersion,
Error: &Error{
Code: code,
Message: fmt.Sprintf(message, a...),
},
Type: gonic.Name,
ServerVersion: gonic.Version,
r := NewResponse()
r.Status = "failed"
r.Error = &Error{
Code: code,
Message: fmt.Sprintf(message, a...),
}
return r
}
type Albums struct {
@@ -116,27 +116,37 @@ type ArtistRef struct {
Name string `xml:"name,attr" json:"name"`
}
type GenreRef struct {
Name string `xml:"name,attr" json:"name"`
}
// https://opensubsonic.netlify.app/docs/responses/albumid3/
type Album struct {
// common
ID *specid.ID `xml:"id,attr,omitempty" json:"id"`
CoverID *specid.ID `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
ArtistID *specid.ID `xml:"artistId,attr,omitempty" json:"artistId,omitempty"`
Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"`
Artists []*ArtistRef `xml:"artists,omitempty" json:"artists,omitempty"`
Created time.Time `xml:"created,attr,omitempty" json:"created,omitempty"`
// browsing by folder (eg. getAlbumList)
ID *specid.ID `xml:"id,attr,omitempty" json:"id"`
Created time.Time `xml:"created,attr,omitempty" json:"created,omitempty"`
// legacy or single tag mode
ArtistID *specid.ID `xml:"artistId,attr,omitempty" json:"artistId,omitempty"`
Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"`
Artists []*ArtistRef `xml:"artists,omitempty" json:"artists,omitempty"`
DisplayArtist string `xml:"diplayArtist,attr,omitempty" json:"displayArtist,omitempty"`
// folder stuff
Title string `xml:"title,attr,omitempty" json:"title"`
Album string `xml:"album,attr,omitempty" json:"album"`
ParentID *specid.ID `xml:"parent,attr,omitempty" json:"parent,omitempty"`
IsDir bool `xml:"isDir,attr,omitempty" json:"isDir,omitempty"`
// browsing by tags (eg. getAlbumList2)
CoverID *specid.ID `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
Name string `xml:"name,attr" json:"name"`
TrackCount int `xml:"songCount,attr" json:"songCount"`
Duration int `xml:"duration,attr" json:"duration"`
Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"`
Genres []string `xml:"genres,omitempty" json:"genres,omitempty"`
Genres []*GenreRef `xml:"genres,omitempty" json:"genres,omitempty"`
Year int `xml:"year,attr,omitempty" json:"year,omitempty"`
Tracks []*TrackChild `xml:"song,omitempty" json:"song,omitempty"`
// star / rating
Starred *time.Time `xml:"starred,attr,omitempty" json:"starred,omitempty"`
UserRating int `xml:"userRating,attr,omitempty" json:"userRating,omitempty"`
@@ -151,35 +161,51 @@ type TracksByGenre struct {
List []*TrackChild `xml:"song" json:"song"`
}
type TranscodeMeta struct {
TranscodedContentType string `xml:"transcodedContentType,attr,omitempty" json:"transcodedContentType,omitempty"`
TranscodedSuffix string `xml:"transcodedSuffix,attr,omitempty" json:"transcodedSuffix,omitempty"`
}
// https://opensubsonic.netlify.app/docs/responses/child/
type TrackChild struct {
ID *specid.ID `xml:"id,attr,omitempty" json:"id,omitempty"`
Album string `xml:"album,attr,omitempty" json:"album,omitempty"`
AlbumID *specid.ID `xml:"albumId,attr,omitempty" json:"albumId,omitempty"`
Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"`
ArtistID *specid.ID `xml:"artistId,attr,omitempty" json:"artistId,omitempty"`
Bitrate int `xml:"bitRate,attr,omitempty" json:"bitRate,omitempty"`
ContentType string `xml:"contentType,attr,omitempty" json:"contentType,omitempty"`
TranscodedContentType string `xml:"transcodedContentType,attr,omitempty" json:"transcodedContentType,omitempty"`
CoverID *specid.ID `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
CreatedAt time.Time `xml:"created,attr,omitempty" json:"created,omitempty"`
Duration int `xml:"duration,attr,omitempty" json:"duration,omitempty"`
Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"`
IsDir bool `xml:"isDir,attr" json:"isDir"`
IsVideo bool `xml:"isVideo,attr" json:"isVideo"`
ParentID *specid.ID `xml:"parent,attr,omitempty" json:"parent,omitempty"`
Path string `xml:"path,attr,omitempty" json:"path,omitempty"`
Size int `xml:"size,attr,omitempty" json:"size,omitempty"`
Suffix string `xml:"suffix,attr,omitempty" json:"suffix,omitempty"`
TranscodedSuffix string `xml:"transcodedSuffix,attr,omitempty" json:"transcodedSuffix,omitempty"`
Title string `xml:"title,attr" json:"title"`
TrackNumber int `xml:"track,attr,omitempty" json:"track,omitempty"`
DiscNumber int `xml:"discNumber,attr,omitempty" json:"discNumber,omitempty"`
Type string `xml:"type,attr,omitempty" json:"type,omitempty"`
Year int `xml:"year,attr,omitempty" json:"year,omitempty"`
ID *specid.ID `xml:"id,attr,omitempty" json:"id,omitempty"`
Album string `xml:"album,attr,omitempty" json:"album,omitempty"`
AlbumID *specid.ID `xml:"albumId,attr,omitempty" json:"albumId,omitempty"`
// legacy or single tag mode
Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"`
ArtistID *specid.ID `xml:"artistId,attr,omitempty" json:"artistId,omitempty"`
Artists []*ArtistRef `xml:"artists,omitempty" json:"artists,omitempty"`
DisplayArtist string `xml:"diplayArtist,attr,omitempty" json:"displayArtist,omitempty"`
AlbumArtists []*ArtistRef `xml:"albumArtists,omitempty" json:"albumArtists,omitempty"`
AlbumDisplayArtist string `xml:"diplayAlbumArtist,attr,omitempty" json:"displayAlbumArtist,omitempty"`
Bitrate int `xml:"bitRate,attr,omitempty" json:"bitRate,omitempty"`
ContentType string `xml:"contentType,attr,omitempty" json:"contentType,omitempty"`
CoverID *specid.ID `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
CreatedAt time.Time `xml:"created,attr,omitempty" json:"created,omitempty"`
Duration int `xml:"duration,attr,omitempty" json:"duration,omitempty"`
Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"`
Genres []*GenreRef `xml:"genres,omitempty" json:"genres,omitempty"`
IsDir bool `xml:"isDir,attr" json:"isDir"`
IsVideo bool `xml:"isVideo,attr" json:"isVideo"`
ParentID *specid.ID `xml:"parent,attr,omitempty" json:"parent,omitempty"`
Path string `xml:"path,attr,omitempty" json:"path,omitempty"`
Size int `xml:"size,attr,omitempty" json:"size,omitempty"`
Suffix string `xml:"suffix,attr,omitempty" json:"suffix,omitempty"`
Title string `xml:"title,attr" json:"title"`
TrackNumber int `xml:"track,attr,omitempty" json:"track,omitempty"`
DiscNumber int `xml:"discNumber,attr,omitempty" json:"discNumber,omitempty"`
Type string `xml:"type,attr,omitempty" json:"type,omitempty"`
Year int `xml:"year,attr,omitempty" json:"year,omitempty"`
// star / rating
Starred *time.Time `xml:"starred,attr,omitempty" json:"starred,omitempty"`
UserRating int `xml:"userRating,attr,omitempty" json:"userRating,omitempty"`
AverageRating string `xml:"averageRating,attr,omitempty" json:"averageRating,omitempty"`
TranscodeMeta
}
type Artists struct {
@@ -292,7 +318,13 @@ type ArtistInfo struct {
MediumImageURL string `xml:"mediumImageUrl" json:"mediumImageUrl"`
LargeImageURL string `xml:"largeImageUrl" json:"largeImageUrl"`
ArtistImageURL string `xml:"artistImageUrl" json:"artistImageUrl"` // not sure where this comes from but other clients seem to expect it
Similar []*Artist `xml:"similarArtist,omitempty" json:"similarArtist,omitempty"`
Similar []*Artist `xml:"similarArtist,omitempty" json:"similarArtist,omitempty"`
}
type AlbumInfo struct {
Notes string `xml:"notes" json:"notes"`
MusicBrainzID string `xml:"musicBrainzId" json:"musicBrainzId"`
LastFMURL string `xml:"lastFmUrl" json:"lastFmUrl"`
}
type Genres struct {
@@ -300,9 +332,9 @@ type Genres struct {
}
type Genre struct {
Name string `xml:",chardata" json:"value"`
SongCount int `xml:"songCount,attr,omitempty" json:"songCount,omitempty"`
AlbumCount int `xml:"albumCount,attr,omitempty" json:"albumCount,omitempty"`
Name string `xml:",chardata" json:"value"`
SongCount int `xml:"songCount,attr" json:"songCount"`
AlbumCount int `xml:"albumCount,attr" json:"albumCount"`
}
type PlayQueue struct {
@@ -420,6 +452,13 @@ type Lyrics struct {
Title string `xml:"title,attr,omitempty" json:"title,omitempty"`
}
type OpenSubsonicExtension struct {
Name string `xml:"name,attr" json:"name"`
Versions []int `xml:"versions" json:"versions"`
}
type OpenSubsonicExtensions []OpenSubsonicExtension
func formatRating(rating float64) string {
if rating == 0 {
return ""
+3 -4
View File
@@ -30,18 +30,17 @@ const (
separator = "-"
)
//nolint:musttag
type ID struct {
Type IDT
Value int
}
func New(in string) (ID, error) {
parts := strings.Split(in, separator)
if len(parts) != 2 {
partType, partValue, ok := strings.Cut(in, separator)
if !ok {
return ID{}, ErrBadSeparator
}
partType := parts[0]
partValue := parts[1]
val, err := strconv.Atoi(partValue)
if err != nil {
return ID{}, fmt.Errorf("%q: %w", partValue, ErrNotAnInt)
+5
View File
@@ -6,6 +6,8 @@ import (
)
func TestParseID(t *testing.T) {
t.Parallel()
tcases := []struct {
param string
expType IDT
@@ -20,9 +22,12 @@ func TestParseID(t *testing.T) {
{param: "1", expErr: ErrBadSeparator},
{param: "al-howdy", expErr: ErrNotAnInt},
}
for _, tcase := range tcases {
tcase := tcase // pin
t.Run(tcase.param, func(t *testing.T) {
t.Parallel()
act, err := New(tcase.param)
if !errors.Is(err, tcase.expErr) {
t.Fatalf("expected err %q, got %q", tcase.expErr, err)
+15 -13
View File
@@ -9,8 +9,10 @@ import (
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
)
var ErrNotAbs = errors.New("not abs")
var ErrNotFound = errors.New("not found")
var (
ErrNotAbs = errors.New("not abs")
ErrNotFound = errors.New("not found")
)
type Result interface {
SID() *specid.ID
@@ -18,21 +20,17 @@ type Result interface {
}
// Locate maps a specid to its location on the filesystem
func Locate(dbc *db.DB, podcastsPath string, id specid.ID) (Result, error) {
func Locate(dbc *db.DB, id specid.ID) (Result, error) {
switch id.Type {
case specid.Track:
var track db.Track
if err := dbc.Preload("Album").Where("id=?", id.Value).Find(&track).Error; err == nil {
return &track, nil
}
return &track, dbc.Preload("Album").Where("id=?", id.Value).Find(&track).Error
case specid.PodcastEpisode:
var pe db.PodcastEpisode
if err := dbc.Where("id=? AND status=?", id.Value, db.PodcastEpisodeStatusCompleted).Find(&pe).Error; err == nil {
pe.AbsP = filepath.Join(podcastsPath, pe.Path)
return &pe, err
}
return &pe, dbc.Preload("Podcast").Where("id=? AND status=?", id.Value, db.PodcastEpisodeStatusCompleted).Find(&pe).Error
default:
return nil, ErrNotFound
}
return nil, ErrNotFound
}
// Locate maps a location on the filesystem to a specid
@@ -42,9 +40,13 @@ func Lookup(dbc *db.DB, musicPaths []string, podcastsPath string, path string) (
}
if strings.HasPrefix(path, podcastsPath) {
path, _ = filepath.Rel(podcastsPath, path)
podcastPath, episodeFilename := filepath.Split(path)
q := dbc.
Joins(`JOIN podcasts ON podcasts.id=podcast_episodes.podcast_id`).
Where(`podcasts.root_dir=? AND podcast_episodes.filename=?`, filepath.Clean(podcastPath), filepath.Clean(episodeFilename))
var pe db.PodcastEpisode
if err := dbc.Where(`path=?`, path).First(&pe).Error; err == nil {
if err := q.First(&pe).Error; err == nil {
return &pe, nil
}
return nil, ErrNotFound
+37 -36
View File
@@ -4,122 +4,123 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"albumList": {
"album": [
{
"id": "al-3",
"coverArt": "al-3",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-4",
"coverArt": "al-4",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-5",
"coverArt": "al-5",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-2",
"album": "",
"album": "album-2",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-7",
"coverArt": "al-7",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-8",
"coverArt": "al-8",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-9",
"coverArt": "al-9",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-2",
"album": "",
"album": "album-2",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-11",
"coverArt": "al-11",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-12",
"coverArt": "al-12",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-13",
"coverArt": "al-13",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-2",
"album": "",
"album": "album-2",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300
}
+37 -36
View File
@@ -4,122 +4,123 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"albumList": {
"album": [
{
"id": "al-3",
"coverArt": "al-3",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-7",
"coverArt": "al-7",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-11",
"coverArt": "al-11",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-4",
"coverArt": "al-4",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-8",
"coverArt": "al-8",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-12",
"coverArt": "al-12",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-5",
"coverArt": "al-5",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-2",
"album": "",
"album": "album-2",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-9",
"coverArt": "al-9",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-2",
"album": "",
"album": "album-2",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-13",
"coverArt": "al-13",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-2",
"album": "",
"album": "album-2",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300
}
+37 -36
View File
@@ -4,122 +4,123 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"albumList": {
"album": [
{
"id": "al-3",
"coverArt": "al-3",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-4",
"coverArt": "al-4",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-5",
"coverArt": "al-5",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-2",
"album": "",
"album": "album-2",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-7",
"coverArt": "al-7",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-8",
"coverArt": "al-8",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-9",
"coverArt": "al-9",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-2",
"album": "",
"album": "album-2",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-11",
"coverArt": "al-11",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-12",
"coverArt": "al-12",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-13",
"coverArt": "al-13",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-2",
"album": "",
"album": "album-2",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300
}
+94 -93
View File
@@ -4,122 +4,123 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"albumList": {
"album": [
{
"id": "al-3",
"coverArt": "al-3",
"artist": "artist-0",
"id": "al-4",
"created": "2019-11-30T00:00:00Z",
"title": "album-0",
"album": "",
"artist": "artist-0",
"title": "album-1",
"album": "album-1",
"parent": "al-2",
"isDir": true,
"name": "",
"songCount": 3,
"duration": 300
},
{
"id": "al-13",
"coverArt": "al-13",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"title": "album-2",
"album": "",
"parent": "al-10",
"isDir": true,
"name": "",
"songCount": 3,
"duration": 300
},
{
"id": "al-7",
"coverArt": "al-7",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"title": "album-0",
"album": "",
"parent": "al-6",
"isDir": true,
"name": "",
"songCount": 3,
"duration": 300
},
{
"id": "al-5",
"coverArt": "al-5",
"artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
"title": "album-2",
"album": "",
"parent": "al-2",
"isDir": true,
"name": "",
"songCount": 3,
"duration": 300
},
{
"id": "al-12",
"coverArt": "al-12",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"title": "album-1",
"album": "",
"parent": "al-10",
"isDir": true,
"name": "",
"songCount": 3,
"duration": 300
},
{
"id": "al-8",
"coverArt": "al-8",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"title": "album-1",
"album": "",
"parent": "al-6",
"isDir": true,
"name": "",
"songCount": 3,
"duration": 300
},
{
"id": "al-9",
"coverArt": "al-9",
"artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
"title": "album-2",
"album": "",
"parent": "al-6",
"isDir": true,
"name": "",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-11",
"coverArt": "al-11",
"artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-0",
"album": "",
"album": "album-0",
"parent": "al-10",
"isDir": true,
"name": "",
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-4",
"coverArt": "al-4",
"artist": "artist-0",
"id": "al-7",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-0",
"album": "album-0",
"parent": "al-6",
"isDir": true,
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-8",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-1",
"album": "",
"album": "album-1",
"parent": "al-6",
"isDir": true,
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-9",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"title": "album-2",
"album": "album-2",
"parent": "al-6",
"isDir": true,
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-13",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-2",
"album": "album-2",
"parent": "al-10",
"isDir": true,
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-3",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-0",
"album": "album-0",
"parent": "al-2",
"isDir": true,
"name": "",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-5",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"title": "album-2",
"album": "album-2",
"parent": "al-2",
"isDir": true,
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-12",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"title": "album-1",
"album": "album-1",
"parent": "al-10",
"isDir": true,
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300
}
@@ -4,17 +4,19 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"albumList2": {
"album": [
{
"id": "al-3",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-0",
"album": "album-0",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -22,13 +24,14 @@
},
{
"id": "al-4",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-1",
"album": "album-1",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -36,13 +39,14 @@
},
{
"id": "al-5",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-2",
"album": "album-2",
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -50,13 +54,14 @@
},
{
"id": "al-7",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-0",
"album": "album-0",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -64,13 +69,14 @@
},
{
"id": "al-8",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-1",
"album": "album-1",
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -78,13 +84,14 @@
},
{
"id": "al-9",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-2",
"album": "album-2",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -92,13 +99,14 @@
},
{
"id": "al-11",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-0",
"album": "album-0",
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -106,13 +114,14 @@
},
{
"id": "al-12",
"coverArt": "al-12",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-1",
"album": "album-1",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -120,13 +129,14 @@
},
{
"id": "al-13",
"coverArt": "al-13",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-2",
"album": "album-2",
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -4,17 +4,19 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"albumList2": {
"album": [
{
"id": "al-3",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-0",
"album": "album-0",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -22,13 +24,14 @@
},
{
"id": "al-7",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-0",
"album": "album-0",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -36,13 +39,14 @@
},
{
"id": "al-11",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-0",
"album": "album-0",
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -50,13 +54,14 @@
},
{
"id": "al-4",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-1",
"album": "album-1",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -64,13 +69,14 @@
},
{
"id": "al-8",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-1",
"album": "album-1",
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -78,13 +84,14 @@
},
{
"id": "al-12",
"coverArt": "al-12",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-1",
"album": "album-1",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -92,13 +99,14 @@
},
{
"id": "al-5",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-2",
"album": "album-2",
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -106,13 +114,14 @@
},
{
"id": "al-9",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-2",
"album": "album-2",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -120,13 +129,14 @@
},
{
"id": "al-13",
"coverArt": "al-13",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-2",
"album": "album-2",
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
+46 -36
View File
@@ -4,17 +4,19 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"albumList2": {
"album": [
{
"id": "al-3",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-0",
"album": "album-0",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -22,13 +24,14 @@
},
{
"id": "al-4",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-1",
"album": "album-1",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -36,13 +39,14 @@
},
{
"id": "al-5",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-2",
"album": "album-2",
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -50,13 +54,14 @@
},
{
"id": "al-7",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-0",
"album": "album-0",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -64,13 +69,14 @@
},
{
"id": "al-8",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-1",
"album": "album-1",
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -78,13 +84,14 @@
},
{
"id": "al-9",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-2",
"album": "album-2",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -92,13 +99,14 @@
},
{
"id": "al-11",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-0",
"album": "album-0",
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -106,13 +114,14 @@
},
{
"id": "al-12",
"coverArt": "al-12",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-1",
"album": "album-1",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -120,13 +129,14 @@
},
{
"id": "al-13",
"coverArt": "al-13",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-2",
"album": "album-2",
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
+108 -98
View File
@@ -4,101 +4,19 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"albumList2": {
"album": [
{
"id": "al-8",
"coverArt": "al-8",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"name": "album-1",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-11",
"coverArt": "al-11",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"name": "album-0",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-5",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"title": "album-2",
"album": "album-2",
"coverArt": "al-5",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"name": "album-2",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-3",
"coverArt": "al-3",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"name": "album-0",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-9",
"coverArt": "al-9",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"name": "album-2",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-7",
"coverArt": "al-7",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"name": "album-0",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-13",
"coverArt": "al-13",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -106,31 +24,123 @@
},
{
"id": "al-4",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-1",
"album": "album-1",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-7",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"title": "album-0",
"album": "album-0",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-12",
"coverArt": "al-12",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-1",
"album": "album-1",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-9",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"title": "album-2",
"album": "album-2",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-8",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"title": "album-1",
"album": "album-1",
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-11",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"displayArtist": "artist-2",
"title": "album-0",
"album": "album-0",
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-3",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"title": "album-0",
"album": "album-0",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-13",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"displayArtist": "artist-2",
"title": "album-2",
"album": "album-2",
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
"year": 2021
}
]
}
+22 -8
View File
@@ -4,20 +4,22 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"album": {
"id": "al-3",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-0",
"album": "album-0",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021,
"song": [
{
@@ -26,8 +28,12 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -48,8 +54,12 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -70,8 +80,12 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"album": {
"id": "al-2",
"created": "2019-11-30T00:00:00Z",
+19 -15
View File
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"artist": {
"id": "ar-1",
"name": "artist-0",
@@ -11,50 +12,53 @@
"album": [
{
"id": "al-3",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-0",
"album": "album-0",
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-4",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-1",
"album": "album-1",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-5",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-2",
"album": "album-2",
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
}
]
+19 -15
View File
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"artist": {
"id": "ar-3",
"name": "artist-2",
@@ -11,50 +12,53 @@
"album": [
{
"id": "al-11",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-0",
"album": "album-0",
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-12",
"coverArt": "al-12",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-1",
"album": "album-1",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-13",
"coverArt": "al-13",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-2",
"album": "album-2",
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
}
]
+19 -15
View File
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"artist": {
"id": "ar-2",
"name": "artist-1",
@@ -11,50 +12,53 @@
"album": [
{
"id": "al-7",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-0",
"album": "album-0",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-8",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-1",
"album": "album-1",
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-9",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-2",
"album": "album-2",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
}
]
+1
View File
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"artists": {
"ignoredArticles": "",
"index": [
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"artists": {
"ignoredArticles": "",
"index": [
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"artists": {
"ignoredArticles": "",
"index": [
+1
View File
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"indexes": {
"lastModified": 0,
"ignoredArticles": "",
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"indexes": {
"lastModified": 0,
"ignoredArticles": "",
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"indexes": {
"lastModified": 0,
"ignoredArticles": "",
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"directory": {
"id": "al-3",
"parent": "al-2",
@@ -13,8 +14,9 @@
"id": "tr-1",
"album": "album-0",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -33,8 +35,9 @@
"id": "tr-2",
"album": "album-0",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -53,8 +56,9 @@
"id": "tr-3",
"album": "album-0",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"directory": {
"id": "al-2",
"parent": "al-1",
+55 -45
View File
@@ -4,150 +4,160 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"searchResult3": {
"album": [
{
"id": "al-3",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-0",
"album": "album-0",
"coverArt": "al-3",
"name": "album-0",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-4",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-1",
"album": "album-1",
"coverArt": "al-4",
"name": "album-1",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-5",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-0",
"title": "album-2",
"album": "album-2",
"coverArt": "al-5",
"name": "album-2",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-7",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-0",
"album": "album-0",
"coverArt": "al-7",
"name": "album-0",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-8",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-1",
"album": "album-1",
"coverArt": "al-8",
"name": "album-1",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-9",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-1",
"title": "album-2",
"album": "album-2",
"coverArt": "al-9",
"name": "album-2",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-11",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-0",
"album": "album-0",
"coverArt": "al-11",
"name": "album-0",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-12",
"coverArt": "al-12",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-1",
"album": "album-1",
"coverArt": "al-12",
"name": "album-1",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-13",
"coverArt": "al-13",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"created": "2019-11-30T00:00:00Z",
"title": "",
"album": "",
"displayArtist": "artist-2",
"title": "album-2",
"album": "album-2",
"coverArt": "al-13",
"name": "album-2",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
"genres": ["Unknown Genre"],
"genres": [{ "name": "Unknown Genre" }],
"year": 2021
}
]
+1
View File
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"searchResult3": {
"artist": [
{ "id": "ar-1", "name": "artist-0", "albumCount": 3 },
+121 -20
View File
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"searchResult3": {
"song": [
{
@@ -12,12 +13,17 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-3",
@@ -35,12 +41,17 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-3",
@@ -58,12 +69,17 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-3",
@@ -81,12 +97,17 @@
"albumId": "al-4",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-4",
@@ -104,12 +125,17 @@
"albumId": "al-4",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-4",
@@ -127,12 +153,17 @@
"albumId": "al-4",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-4",
@@ -150,12 +181,17 @@
"albumId": "al-5",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-5",
@@ -173,12 +209,17 @@
"albumId": "al-5",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-5",
@@ -196,12 +237,17 @@
"albumId": "al-5",
"artist": "artist-0",
"artistId": "ar-1",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
"displayAlbumArtist": "artist-0",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-5",
@@ -219,12 +265,17 @@
"albumId": "al-7",
"artist": "artist-1",
"artistId": "ar-2",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
"displayAlbumArtist": "artist-1",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-7",
@@ -242,12 +293,17 @@
"albumId": "al-7",
"artist": "artist-1",
"artistId": "ar-2",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
"displayAlbumArtist": "artist-1",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-7",
@@ -265,12 +321,17 @@
"albumId": "al-7",
"artist": "artist-1",
"artistId": "ar-2",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
"displayAlbumArtist": "artist-1",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-7",
@@ -288,12 +349,17 @@
"albumId": "al-8",
"artist": "artist-1",
"artistId": "ar-2",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
"displayAlbumArtist": "artist-1",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-8",
@@ -311,12 +377,17 @@
"albumId": "al-8",
"artist": "artist-1",
"artistId": "ar-2",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
"displayAlbumArtist": "artist-1",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-8",
@@ -334,12 +405,17 @@
"albumId": "al-8",
"artist": "artist-1",
"artistId": "ar-2",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
"displayAlbumArtist": "artist-1",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-8",
@@ -357,12 +433,17 @@
"albumId": "al-9",
"artist": "artist-1",
"artistId": "ar-2",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
"displayAlbumArtist": "artist-1",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-9",
@@ -380,12 +461,17 @@
"albumId": "al-9",
"artist": "artist-1",
"artistId": "ar-2",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
"displayAlbumArtist": "artist-1",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-9",
@@ -403,12 +489,17 @@
"albumId": "al-9",
"artist": "artist-1",
"artistId": "ar-2",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
"displayAlbumArtist": "artist-1",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-9",
@@ -426,12 +517,17 @@
"albumId": "al-11",
"artist": "artist-2",
"artistId": "ar-3",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"displayArtist": "artist-2",
"albumArtists": [{ "id": "ar-3", "name": "artist-2" }],
"displayAlbumArtist": "artist-2",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-11",
@@ -449,12 +545,17 @@
"albumId": "al-11",
"artist": "artist-2",
"artistId": "ar-3",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"displayArtist": "artist-2",
"albumArtists": [{ "id": "ar-3", "name": "artist-2" }],
"displayAlbumArtist": "artist-2",
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-11",
+1
View File
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"searchResult2": {
"album": [
{
+1
View File
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"searchResult2": {
"artist": [
{ "id": "al-2", "parent": "al-1", "name": "artist-0" },
+41 -20
View File
@@ -4,14 +4,16 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
"openSubsonic": true,
"searchResult2": {
"song": [
{
"id": "tr-1",
"album": "album-0",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -30,8 +32,9 @@
"id": "tr-2",
"album": "album-0",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -50,8 +53,9 @@
"id": "tr-3",
"album": "album-0",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -70,8 +74,9 @@
"id": "tr-4",
"album": "album-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -90,8 +95,9 @@
"id": "tr-5",
"album": "album-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -110,8 +116,9 @@
"id": "tr-6",
"album": "album-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -130,8 +137,9 @@
"id": "tr-7",
"album": "album-2",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -150,8 +158,9 @@
"id": "tr-8",
"album": "album-2",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -170,8 +179,9 @@
"id": "tr-9",
"album": "album-2",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -190,8 +200,9 @@
"id": "tr-10",
"album": "album-0",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -210,8 +221,9 @@
"id": "tr-11",
"album": "album-0",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -230,8 +242,9 @@
"id": "tr-12",
"album": "album-0",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -250,8 +263,9 @@
"id": "tr-13",
"album": "album-1",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -270,8 +284,9 @@
"id": "tr-14",
"album": "album-1",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -290,8 +305,9 @@
"id": "tr-15",
"album": "album-1",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -310,8 +326,9 @@
"id": "tr-16",
"album": "album-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -330,8 +347,9 @@
"id": "tr-17",
"album": "album-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -350,8 +368,9 @@
"id": "tr-18",
"album": "album-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -370,8 +389,9 @@
"id": "tr-19",
"album": "album-0",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -390,8 +410,9 @@
"id": "tr-20",
"album": "album-0",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"bitRate": 100,
"contentType": "audio/x-flac",
"contentType": "audio/flac",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"duration": 100,