feat: OpenSubsonic playlists and listens
Apps can use the playlists of a person and report what they listened to. - getPlaylists, getPlaylist, createPlaylist (with songs, or in place of an existing one), updatePlaylist (name, comment, songs to add, places to remove), deletePlaylist: the same playlists as the web app - scrobble records a complete listen once however many times an app tries again, and shares it on Mastodon when the person connected it; a now playing message records nothing; getNowPlaying answers with nothing - README section on connecting other apps
This commit is contained in:
parent
2cb67b1bdc
commit
a0dc4458ef
7 changed files with 838 additions and 3 deletions
|
|
@ -148,6 +148,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
|
|||
Libraries: deps.Libraries.(opensubsonic.Libraries), ServerVersion: "test",
|
||||
Extras: subsonic, Lists: subsonic, Streams: deps.Streams.(opensubsonic.Streams),
|
||||
Covers: deps.Images.(opensubsonic.Covers), ArtistImages: deps.ArtistImages.(opensubsonic.ArtistImages),
|
||||
Playlists: deps.Playlists.(opensubsonic.Playlists), Listens: deps.Listening.(opensubsonic.Listens), Announcer: deps.Mastodon.(opensubsonic.Announcer),
|
||||
}
|
||||
}
|
||||
if deps.About == nil {
|
||||
|
|
|
|||
|
|
@ -361,3 +361,56 @@ func errorFrom(t *testing.T, rec *httptest.ResponseRecorder) int {
|
|||
}
|
||||
return errorCode(out.R)
|
||||
}
|
||||
|
||||
func TestPlaylistsAndListensOfAnAppAreThoseOfThePerson(t *testing.T) {
|
||||
e := newCoversEnv(t)
|
||||
secret := do(t, e.h, "POST", "/api/v1/me/devices", e.token, map[string]any{"name": "Phone"}).Body["secret"].(string)
|
||||
var song int64
|
||||
if err := e.db.QueryRow("SELECT id FROM tracks WHERE title = 'With Art song'").Scan(&song); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rest := func(path string, q url.Values) map[string]any {
|
||||
q.Set("apiKey", secret)
|
||||
q.Set("f", "json")
|
||||
rec := httptest.NewRecorder()
|
||||
e.h.ServeHTTP(rec, httptest.NewRequest("GET", "/rest/"+path+"?"+q.Encode(), nil))
|
||||
var out struct {
|
||||
R map[string]any `json:"subsonic-response"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.R["status"] != "ok" {
|
||||
t.Fatalf("%s: %v %s", path, err, rec.Body.String())
|
||||
}
|
||||
return out.R
|
||||
}
|
||||
|
||||
// A playlist made in the app is in the web app, and the other way round.
|
||||
made := rest("createPlaylist", url.Values{"name": {"From the phone"}, "songId": {"tr-" + itoa(song)}})["playlist"].(map[string]any)
|
||||
if made["songCount"].(float64) != 1 {
|
||||
t.Fatalf("made %v", made)
|
||||
}
|
||||
listed := do(t, e.h, "GET", "/api/v1/playlists", e.token, nil)
|
||||
items, _ := listed.Body["items"].([]any)
|
||||
if len(items) != 1 || items[0].(map[string]any)["name"] != "From the phone" {
|
||||
t.Fatalf("the web app sees %v", listed.Body)
|
||||
}
|
||||
web := do(t, e.h, "POST", "/api/v1/playlists", e.token, map[string]any{"name": "From the web"})
|
||||
if web.Code != 201 {
|
||||
t.Fatalf("%d %v", web.Code, web.Body)
|
||||
}
|
||||
if n := len(rest("getPlaylists", url.Values{})["playlists"].(map[string]any)["playlist"].([]any)); n != 2 {
|
||||
t.Fatalf("the app sees %d playlists", n)
|
||||
}
|
||||
rest("deletePlaylist", url.Values{"id": {made["id"].(string)}})
|
||||
if n := len(do(t, e.h, "GET", "/api/v1/playlists", e.token, nil).Body["items"].([]any)); n != 1 {
|
||||
t.Fatalf("after delete the web app sees %d", n)
|
||||
}
|
||||
|
||||
// A listen reported by the app is in the history of the person, once.
|
||||
for i := 0; i < 2; i++ {
|
||||
rest("scrobble", url.Values{"id": {"tr-" + itoa(song)}, "time": {"1700000000000"}})
|
||||
}
|
||||
hist := do(t, e.h, "GET", "/api/v1/listens", e.token, nil)
|
||||
if got := hist.Body["total"]; got != float64(1) {
|
||||
t.Fatalf("history %v", hist.Body)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,11 @@ func idParam(k *call, prefix string) (int64, *Error) {
|
|||
if raw == "" {
|
||||
return 0, missing("id")
|
||||
}
|
||||
return idOf(raw, prefix)
|
||||
}
|
||||
|
||||
// idOf reads an id of the kind the prefix says.
|
||||
func idOf(raw, prefix string) (int64, *Error) {
|
||||
n, err := strconv.ParseInt(strings.TrimPrefix(raw, prefix), 10, 64)
|
||||
if !strings.HasPrefix(raw, prefix) || err != nil || n < 1 {
|
||||
return 0, notFound()
|
||||
|
|
|
|||
|
|
@ -53,6 +53,9 @@ type Deps struct {
|
|||
Streams Streams
|
||||
Covers Covers
|
||||
ArtistImages ArtistImages
|
||||
Playlists Playlists
|
||||
Listens Listens
|
||||
Announcer Announcer // optional
|
||||
ServerVersion string
|
||||
}
|
||||
|
||||
|
|
@ -95,6 +98,13 @@ func Register(r gin.IRoutes, d Deps) {
|
|||
"stream": h.stream,
|
||||
"download": h.download,
|
||||
"getCoverArt": h.coverArt,
|
||||
"getPlaylists": h.playlists,
|
||||
"getPlaylist": h.playlist,
|
||||
"createPlaylist": h.createPlaylist,
|
||||
"updatePlaylist": h.updatePlaylist,
|
||||
"deletePlaylist": h.deletePlaylist,
|
||||
"scrobble": h.scrobble,
|
||||
"getNowPlaying": h.nowPlaying,
|
||||
}
|
||||
r.GET("/rest/:method", h.serve)
|
||||
r.HEAD("/rest/:method", h.serve)
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ import (
|
|||
"git.kmalloc.org/squid/sonda/internal/devices"
|
||||
"git.kmalloc.org/squid/sonda/internal/images"
|
||||
"git.kmalloc.org/squid/sonda/internal/library"
|
||||
"git.kmalloc.org/squid/sonda/internal/listening"
|
||||
"git.kmalloc.org/squid/sonda/internal/playlists"
|
||||
"git.kmalloc.org/squid/sonda/internal/streaming"
|
||||
)
|
||||
|
||||
|
|
@ -799,3 +801,349 @@ func TestSearchReadsAsManyAsAskedEvenAboveAPageOfTheCatalogue(t *testing.T) {
|
|||
t.Fatalf("%v", r)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- playlists and listens ----
|
||||
|
||||
type fakePlaylists struct {
|
||||
next int64
|
||||
lists map[int64]*fakeList
|
||||
}
|
||||
|
||||
type fakeList struct {
|
||||
name, desc string
|
||||
items []playlists.Item
|
||||
nextItem int64
|
||||
}
|
||||
|
||||
func newFakePlaylists() *fakePlaylists { return &fakePlaylists{next: 1, lists: map[int64]*fakeList{}} }
|
||||
|
||||
var changedAt = time.Unix(1_700_000_500, 0)
|
||||
|
||||
func (f *fakePlaylists) view(id int64, l *fakeList) playlists.Playlist {
|
||||
p := playlists.Playlist{ID: id, Name: l.name, Description: l.desc, TrackCount: len(l.items), CreatedAt: time.Unix(1_700_000_000, 0), UpdatedAt: changedAt}
|
||||
for _, it := range l.items {
|
||||
p.DurationMs += it.Track.DurationMs
|
||||
}
|
||||
if len(l.items) > 0 && l.items[0].Track.Album != nil {
|
||||
p.AlbumIDs = []int64{l.items[0].Track.Album.ID}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (f *fakePlaylists) Create(_ context.Context, _ int64, name, desc string) (playlists.Playlist, error) {
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return playlists.Playlist{}, playlists.ErrInvalidInput
|
||||
}
|
||||
id := f.next
|
||||
f.next++
|
||||
f.lists[id] = &fakeList{name: name, desc: desc}
|
||||
return f.view(id, f.lists[id]), nil
|
||||
}
|
||||
|
||||
func (f *fakePlaylists) List(_ context.Context, _ int64, p playlists.Page) (playlists.Listing, error) {
|
||||
var all []playlists.Playlist
|
||||
for id := int64(1); id < f.next; id++ {
|
||||
if l, ok := f.lists[id]; ok {
|
||||
all = append(all, f.view(id, l))
|
||||
}
|
||||
}
|
||||
if p.Offset >= len(all) {
|
||||
return playlists.Listing{Items: []playlists.Playlist{}, Total: len(all)}, nil
|
||||
}
|
||||
return playlists.Listing{Items: all[p.Offset:], Total: len(all), Limit: p.Limit, Offset: p.Offset}, nil
|
||||
}
|
||||
|
||||
func (f *fakePlaylists) Get(_ context.Context, _, id int64) (playlists.Playlist, error) {
|
||||
l, ok := f.lists[id]
|
||||
if !ok {
|
||||
return playlists.Playlist{}, playlists.ErrNotFound
|
||||
}
|
||||
return f.view(id, l), nil
|
||||
}
|
||||
|
||||
func (f *fakePlaylists) Update(_ context.Context, _, id int64, name, desc *string) (playlists.Playlist, error) {
|
||||
l, ok := f.lists[id]
|
||||
if !ok {
|
||||
return playlists.Playlist{}, playlists.ErrNotFound
|
||||
}
|
||||
if name != nil {
|
||||
l.name = *name
|
||||
}
|
||||
if desc != nil {
|
||||
l.desc = *desc
|
||||
}
|
||||
return f.view(id, l), nil
|
||||
}
|
||||
|
||||
func (f *fakePlaylists) Delete(_ context.Context, _, id int64) error {
|
||||
if _, ok := f.lists[id]; !ok {
|
||||
return playlists.ErrNotFound
|
||||
}
|
||||
delete(f.lists, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakePlaylists) Items(_ context.Context, _, id int64, p playlists.Page) (playlists.ItemsListing, error) {
|
||||
l, ok := f.lists[id]
|
||||
if !ok {
|
||||
return playlists.ItemsListing{}, playlists.ErrNotFound
|
||||
}
|
||||
if p.Offset >= len(l.items) {
|
||||
return playlists.ItemsListing{Items: []playlists.Item{}, Total: len(l.items)}, nil
|
||||
}
|
||||
return playlists.ItemsListing{Items: l.items[p.Offset:], Total: len(l.items), Limit: p.Limit, Offset: p.Offset}, nil
|
||||
}
|
||||
|
||||
func (f *fakePlaylists) AddTracks(_ context.Context, _, id int64, ids []int64, _ *int) (playlists.Playlist, error) {
|
||||
l, ok := f.lists[id]
|
||||
if !ok {
|
||||
return playlists.Playlist{}, playlists.ErrNotFound
|
||||
}
|
||||
for _, t := range ids {
|
||||
var track catalog.Track
|
||||
switch t {
|
||||
case 70:
|
||||
track = airbag
|
||||
case 71:
|
||||
track = karma
|
||||
default:
|
||||
return playlists.Playlist{}, playlists.ErrTrackNotFound
|
||||
}
|
||||
l.nextItem++
|
||||
l.items = append(l.items, playlists.Item{ID: id*100 + l.nextItem, Position: len(l.items), Track: track, Available: true})
|
||||
}
|
||||
return f.view(id, l), nil
|
||||
}
|
||||
|
||||
func (f *fakePlaylists) RemoveItem(_ context.Context, _, id, itemID int64) error {
|
||||
l, ok := f.lists[id]
|
||||
if !ok {
|
||||
return playlists.ErrNotFound
|
||||
}
|
||||
for i, it := range l.items {
|
||||
if it.ID == itemID {
|
||||
l.items = append(l.items[:i], l.items[i+1:]...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return playlists.ErrItemNotFound
|
||||
}
|
||||
|
||||
type fakeListens struct {
|
||||
events []listening.Event
|
||||
announced [][2]int64
|
||||
}
|
||||
|
||||
func (f *fakeListens) Record(_ context.Context, e listening.Event) (listening.Result, error) {
|
||||
if e.TrackID == 99 {
|
||||
return listening.Result{}, listening.ErrTrackNotFound
|
||||
}
|
||||
for _, old := range f.events {
|
||||
if old.IdempotencyKey == e.IdempotencyKey {
|
||||
return listening.Result{Created: false, Counted: true}, nil
|
||||
}
|
||||
}
|
||||
f.events = append(f.events, e)
|
||||
return listening.Result{Created: true, Counted: true}, nil
|
||||
}
|
||||
|
||||
func (f *fakeListens) Announce(userID, trackID int64) {
|
||||
f.announced = append(f.announced, [2]int64{userID, trackID})
|
||||
}
|
||||
|
||||
type withLists struct {
|
||||
h http.Handler
|
||||
lists *fakePlaylists
|
||||
listens *fakeListens
|
||||
}
|
||||
|
||||
func newListServer() withLists {
|
||||
gin.SetMode(gin.TestMode)
|
||||
w := withLists{lists: newFakePlaylists(), listens: &fakeListens{}}
|
||||
r := gin.New()
|
||||
Register(r, Deps{
|
||||
Login: fakeLogin{}, Catalog: &fakeCatalog{}, Libraries: fakeLibraries{}, Extras: fakeExtras{}, ServerVersion: "9.9",
|
||||
Playlists: w.lists, Listens: w.listens, Announcer: w.listens,
|
||||
})
|
||||
w.h = r
|
||||
return w
|
||||
}
|
||||
|
||||
func ids(r map[string]any) []string {
|
||||
var out []string
|
||||
for _, e := range r["entry"].([]any) {
|
||||
out = append(out, e.(map[string]any)["id"].(string))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (w withLists) q(extra ...string) url.Values { return ok(extra...) }
|
||||
|
||||
func TestAPlaylistIsMadeWithItsSongs(t *testing.T) {
|
||||
w := newListServer()
|
||||
q := ok("name", "Evening")
|
||||
q.Add("songId", "tr-70")
|
||||
q.Add("songId", "tr-71")
|
||||
p := good(t, get(t, w.h, "POST", "/rest/createPlaylist", q))["playlist"].(map[string]any)
|
||||
if p["id"] != "pl-1" || p["name"] != "Evening" || p["songCount"].(float64) != 2 || p["owner"] != "tom@example.org" || p["public"] != false ||
|
||||
p["duration"].(float64) != 548 || p["coverArt"] != "al-7" {
|
||||
t.Fatalf("playlist %v", p)
|
||||
}
|
||||
if got := strings.Join(ids(p), ","); got != "tr-70,tr-71" {
|
||||
t.Fatalf("entries %s", got)
|
||||
}
|
||||
if p["changed"] != "2023-11-14T22:21:40.000Z" || p["created"] != "2023-11-14T22:13:20.000Z" {
|
||||
t.Fatalf("dates %v %v", p["created"], p["changed"])
|
||||
}
|
||||
|
||||
// With no name and no playlist there is nothing to make.
|
||||
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", ok()), ErrMissingParam)
|
||||
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", ok("name", " ")), ErrGeneric)
|
||||
bad := ok("name", "x")
|
||||
bad.Add("songId", "tr-99")
|
||||
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", bad), ErrNotFound)
|
||||
bad = ok("name", "x")
|
||||
bad.Add("songId", "al-7")
|
||||
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", bad), ErrNotFound)
|
||||
}
|
||||
|
||||
func TestAPlaylistThatExistsIsReplaced(t *testing.T) {
|
||||
w := newListServer()
|
||||
q := ok("name", "Evening")
|
||||
q.Add("songId", "tr-70")
|
||||
q.Add("songId", "tr-71")
|
||||
get(t, w.h, "GET", "/rest/createPlaylist", q)
|
||||
|
||||
q = ok("playlistId", "pl-1")
|
||||
q.Add("songId", "tr-71")
|
||||
p := good(t, get(t, w.h, "GET", "/rest/createPlaylist", q))["playlist"].(map[string]any)
|
||||
if p["name"] != "Evening" || strings.Join(ids(p), ",") != "tr-71" {
|
||||
t.Fatalf("playlist %v", p)
|
||||
}
|
||||
failed(t, get(t, w.h, "GET", "/rest/createPlaylist", ok("playlistId", "pl-9")), ErrNotFound)
|
||||
}
|
||||
|
||||
func TestPlaylistsAreListedAndOpened(t *testing.T) {
|
||||
w := newListServer()
|
||||
q := ok("name", "One")
|
||||
q.Add("songId", "tr-70")
|
||||
get(t, w.h, "GET", "/rest/createPlaylist", q)
|
||||
get(t, w.h, "GET", "/rest/createPlaylist", ok("name", "Two"))
|
||||
|
||||
list := good(t, get(t, w.h, "GET", "/rest/getPlaylists", ok()))["playlists"].(map[string]any)["playlist"].([]any)
|
||||
if len(list) != 2 || list[0].(map[string]any)["name"] != "One" || list[0].(map[string]any)["songCount"].(float64) != 1 {
|
||||
t.Fatalf("playlists %v", list)
|
||||
}
|
||||
if _, has := list[0].(map[string]any)["entry"]; has {
|
||||
t.Fatalf("the list holds the songs: %v", list[0])
|
||||
}
|
||||
|
||||
p := good(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", "pl-1")))["playlist"].(map[string]any)
|
||||
if strings.Join(ids(p), ",") != "tr-70" || p["entry"].([]any)[0].(map[string]any)["title"] != "Airbag" {
|
||||
t.Fatalf("playlist %v", p)
|
||||
}
|
||||
empty := good(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", "pl-2")))["playlist"].(map[string]any)
|
||||
if _, has := empty["entry"]; has || empty["songCount"].(float64) != 0 {
|
||||
t.Fatalf("empty playlist %v", empty)
|
||||
}
|
||||
for _, id := range []string{"pl-9", "tr-70", "1", "pl-x"} {
|
||||
failed(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", id)), ErrNotFound)
|
||||
}
|
||||
failed(t, get(t, w.h, "GET", "/rest/getPlaylist", ok()), ErrMissingParam)
|
||||
}
|
||||
|
||||
func TestAPlaylistIsChangedAndDeleted(t *testing.T) {
|
||||
w := newListServer()
|
||||
q := ok("name", "One")
|
||||
q.Add("songId", "tr-70")
|
||||
q.Add("songId", "tr-71")
|
||||
get(t, w.h, "GET", "/rest/createPlaylist", q)
|
||||
|
||||
// Rename, comment, add one song, take out the first (by its place in the list).
|
||||
u := ok("playlistId", "pl-1", "name", "Renamed", "comment", "for the car")
|
||||
u.Add("songIdToAdd", "tr-70")
|
||||
u.Add("songIndexToRemove", "0")
|
||||
good(t, get(t, w.h, "GET", "/rest/updatePlaylist", u))
|
||||
p := good(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", "pl-1")))["playlist"].(map[string]any)
|
||||
if p["name"] != "Renamed" || p["comment"] != "for the car" || strings.Join(ids(p), ",") != "tr-71,tr-70" {
|
||||
t.Fatalf("playlist %v", p)
|
||||
}
|
||||
|
||||
r := ok("playlistId", "pl-1")
|
||||
r.Add("songIndexToRemove", "5")
|
||||
failed(t, get(t, w.h, "GET", "/rest/updatePlaylist", r), ErrGeneric)
|
||||
failed(t, get(t, w.h, "GET", "/rest/updatePlaylist", ok("playlistId", "pl-9", "name", "x")), ErrNotFound)
|
||||
failed(t, get(t, w.h, "GET", "/rest/updatePlaylist", ok()), ErrMissingParam)
|
||||
|
||||
good(t, get(t, w.h, "GET", "/rest/deletePlaylist", ok("id", "pl-1")))
|
||||
failed(t, get(t, w.h, "GET", "/rest/getPlaylist", ok("id", "pl-1")), ErrNotFound)
|
||||
failed(t, get(t, w.h, "GET", "/rest/deletePlaylist", ok("id", "pl-1")), ErrNotFound)
|
||||
failed(t, get(t, w.h, "GET", "/rest/deletePlaylist", ok()), ErrMissingParam)
|
||||
}
|
||||
|
||||
func TestAListenIsRecordedOnceWhateverTheNumberOfTries(t *testing.T) {
|
||||
w := newListServer()
|
||||
q := ok("submission", "true", "time", "1700000000000")
|
||||
q.Add("id", "tr-70")
|
||||
good(t, get(t, w.h, "GET", "/rest/scrobble", q))
|
||||
good(t, get(t, w.h, "GET", "/rest/scrobble", q)) // an app tries again
|
||||
if len(w.listens.events) != 1 {
|
||||
t.Fatalf("events %+v", w.listens.events)
|
||||
}
|
||||
e := w.listens.events[0]
|
||||
if e.UserID != 1 || e.TrackID != 70 || e.Type != listening.Complete || e.OccurredAt.UnixMilli() != 1_700_000_000_000 || e.DurationPlayedMs != 284_000 || e.IdempotencyKey == "" {
|
||||
t.Fatalf("event %+v", e)
|
||||
}
|
||||
if len(w.listens.announced) != 1 || w.listens.announced[0] != [2]int64{1, 70} {
|
||||
t.Fatalf("announced %v", w.listens.announced)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeveralListensWithTheirTimes(t *testing.T) {
|
||||
w := newListServer()
|
||||
q := ok()
|
||||
q.Add("id", "tr-70")
|
||||
q.Add("id", "tr-71")
|
||||
q.Add("time", "1700000000000")
|
||||
q.Add("time", "1700000300000")
|
||||
good(t, get(t, w.h, "GET", "/rest/scrobble", q))
|
||||
if len(w.listens.events) != 2 || w.listens.events[1].TrackID != 71 || w.listens.events[1].OccurredAt.UnixMilli() != 1_700_000_300_000 {
|
||||
t.Fatalf("events %+v", w.listens.events)
|
||||
}
|
||||
if w.listens.events[0].IdempotencyKey == w.listens.events[1].IdempotencyKey {
|
||||
t.Fatal("two listens share a key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAListenWithNoTimeIsNow(t *testing.T) {
|
||||
w := newListServer()
|
||||
before := time.Now()
|
||||
good(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-70")))
|
||||
if at := w.listens.events[0].OccurredAt; at.Before(before.Add(-time.Second)) || at.After(time.Now().Add(time.Second)) {
|
||||
t.Fatalf("occurred at %v", at)
|
||||
}
|
||||
}
|
||||
|
||||
func TestANowPlayingMessageIsNotAListen(t *testing.T) {
|
||||
w := newListServer()
|
||||
good(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-70", "submission", "false")))
|
||||
if len(w.listens.events) != 0 || len(w.listens.announced) != 0 {
|
||||
t.Fatalf("events %+v", w.listens.events)
|
||||
}
|
||||
np := good(t, get(t, w.h, "GET", "/rest/getNowPlaying", ok()))["nowPlaying"].(map[string]any)
|
||||
if len(np) != 0 {
|
||||
t.Fatalf("now playing %v", np)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAListenOfWhatIsNotThereOrIsBadlyAskedFor(t *testing.T) {
|
||||
w := newListServer()
|
||||
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-99")), ErrNotFound)
|
||||
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "al-7")), ErrNotFound)
|
||||
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok()), ErrMissingParam)
|
||||
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-70", "time", "soon")), ErrGeneric)
|
||||
failed(t, get(t, w.h, "GET", "/rest/scrobble", ok("id", "tr-70", "submission", "maybe")), ErrGeneric)
|
||||
if len(w.listens.events) != 0 {
|
||||
t.Fatalf("events %+v", w.listens.events)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
358
internal/opensubsonic/playlists.go
Normal file
358
internal/opensubsonic/playlists.go
Normal file
|
|
@ -0,0 +1,358 @@
|
|||
package opensubsonic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.kmalloc.org/squid/sonda/internal/catalog"
|
||||
"git.kmalloc.org/squid/sonda/internal/listening"
|
||||
"git.kmalloc.org/squid/sonda/internal/playlists"
|
||||
)
|
||||
|
||||
const playlistPrefix = "pl-"
|
||||
|
||||
func playlistID(id int64) string { return playlistPrefix + strconv.FormatInt(id, 10) }
|
||||
|
||||
// Playlists keeps the playlists of a person: *playlists.Service.
|
||||
type Playlists interface {
|
||||
Create(ctx context.Context, userID int64, name, description string) (playlists.Playlist, error)
|
||||
List(ctx context.Context, userID int64, p playlists.Page) (playlists.Listing, error)
|
||||
Get(ctx context.Context, userID, id int64) (playlists.Playlist, error)
|
||||
Update(ctx context.Context, userID, id int64, name, description *string) (playlists.Playlist, error)
|
||||
Delete(ctx context.Context, userID, id int64) error
|
||||
Items(ctx context.Context, userID, id int64, p playlists.Page) (playlists.ItemsListing, error)
|
||||
AddTracks(ctx context.Context, userID, id int64, trackIDs []int64, position *int) (playlists.Playlist, error)
|
||||
RemoveItem(ctx context.Context, userID, id, itemID int64) error
|
||||
}
|
||||
|
||||
// Listens records what a person listened to: *listening.Service.
|
||||
type Listens interface {
|
||||
Record(ctx context.Context, e listening.Event) (listening.Result, error)
|
||||
}
|
||||
|
||||
// Announcer is told of every listen that counts, to share it where the person asked for it (Mastodon).
|
||||
type Announcer interface {
|
||||
Announce(userID, trackID int64)
|
||||
}
|
||||
|
||||
func playlistFailure(err error) *Error {
|
||||
switch {
|
||||
case errors.Is(err, playlists.ErrNotFound), errors.Is(err, playlists.ErrTrackNotFound), errors.Is(err, playlists.ErrItemNotFound):
|
||||
return notFound()
|
||||
case errors.Is(err, playlists.ErrInvalidInput), errors.Is(err, playlists.ErrPosition), errors.Is(err, playlists.ErrTooMany):
|
||||
return &Error{Code: ErrGeneric, Message: err.Error()}
|
||||
}
|
||||
return &Error{Code: ErrGeneric, Message: "the playlist could not be changed"}
|
||||
}
|
||||
|
||||
func playlistOf(p playlists.Playlist, owner string) Playlist {
|
||||
out := Playlist{
|
||||
ID: playlistID(p.ID), Name: p.Name, Comment: p.Description, Owner: owner, SongCount: p.TrackCount,
|
||||
Duration: seconds(p.DurationMs), Created: stamp(p.CreatedAt), Changed: stamp(p.UpdatedAt),
|
||||
}
|
||||
if len(p.AlbumIDs) > 0 {
|
||||
out.CoverArt = albumID(p.AlbumIDs[0])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *handler) playlists(k *call) (*Response, *Error) {
|
||||
var all []playlists.Playlist
|
||||
for {
|
||||
p, err := h.Playlists.List(k.ctx, k.principal.UserID, playlists.Page{Limit: playlists.MaxLimit, Offset: len(all)})
|
||||
if err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
all = append(all, p.Items...)
|
||||
if len(p.Items) == 0 || len(all) >= p.Total {
|
||||
break
|
||||
}
|
||||
}
|
||||
out := make([]Playlist, len(all))
|
||||
for i, p := range all {
|
||||
out[i] = playlistOf(p, k.principal.Email)
|
||||
}
|
||||
return &Response{Playlists: &PlaylistList{Playlist: out}}, nil
|
||||
}
|
||||
|
||||
// entries are the songs of a playlist that can be played, in order, with the id of the item that holds each.
|
||||
func (h *handler) entries(k *call, id int64) ([]playlists.Item, *Error) {
|
||||
var all []playlists.Item
|
||||
for {
|
||||
p, err := h.Playlists.Items(k.ctx, k.principal.UserID, id, playlists.Page{Limit: playlists.MaxLimit, Offset: len(all)})
|
||||
if err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
all = append(all, p.Items...)
|
||||
if len(p.Items) == 0 || len(all) >= p.Total {
|
||||
break
|
||||
}
|
||||
}
|
||||
playable := all[:0]
|
||||
for _, it := range all {
|
||||
if it.Available {
|
||||
playable = append(playable, it)
|
||||
}
|
||||
}
|
||||
return playable, nil
|
||||
}
|
||||
|
||||
// opened is the playlist with its songs.
|
||||
func (h *handler) opened(k *call, id int64) (*Response, *Error) {
|
||||
p, err := h.Playlists.Get(k.ctx, k.principal.UserID, id)
|
||||
if err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
items, bad := h.entries(k, id)
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
tracks := make([]catalog.Track, len(items))
|
||||
for i, it := range items {
|
||||
tracks[i] = it.Track
|
||||
}
|
||||
songs, err := h.songs(k.ctx, tracks)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
out := playlistOf(p, k.principal.Email)
|
||||
out.Entry = songs
|
||||
return &Response{Playlist: &out}, nil
|
||||
}
|
||||
|
||||
func (h *handler) playlist(k *call) (*Response, *Error) {
|
||||
id, bad := idParam(k, playlistPrefix)
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
return h.opened(k, id)
|
||||
}
|
||||
|
||||
// songIDs reads a parameter that may be given many times, each a song.
|
||||
func songIDs(k *call, name string) ([]int64, *Error) {
|
||||
var out []int64
|
||||
for _, raw := range k.c.Request.Form[name] {
|
||||
n, err := strconv.ParseInt(strings.TrimPrefix(raw, trackPrefix), 10, 64)
|
||||
if !strings.HasPrefix(raw, trackPrefix) || err != nil || n < 1 {
|
||||
return nil, notFound()
|
||||
}
|
||||
out = append(out, n)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// add puts songs at the end of a playlist, as many as the service takes at once.
|
||||
func (h *handler) add(k *call, id int64, songs []int64) *Error {
|
||||
for len(songs) > 0 {
|
||||
chunk := songs[:min(len(songs), playlists.MaxAddAtOnce)]
|
||||
songs = songs[len(chunk):]
|
||||
if _, err := h.Playlists.AddTracks(k.ctx, k.principal.UserID, id, chunk, nil); err != nil {
|
||||
return playlistFailure(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// createPlaylist makes a playlist with songs, or, given the id of one, puts these songs in its place.
|
||||
func (h *handler) createPlaylist(k *call) (*Response, *Error) {
|
||||
name, rawID := k.param("name"), k.param("playlistId")
|
||||
if name == "" && rawID == "" {
|
||||
return nil, missing("name or playlistId")
|
||||
}
|
||||
songs, bad := songIDs(k, "songId")
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
var id int64
|
||||
if rawID != "" {
|
||||
n, bad := idOf(rawID, playlistPrefix)
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
id = n
|
||||
if _, err := h.Playlists.Get(k.ctx, k.principal.UserID, id); err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
items, bad := h.allItems(k, id)
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
for _, it := range items {
|
||||
if err := h.Playlists.RemoveItem(k.ctx, k.principal.UserID, id, it.ID); err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
}
|
||||
if name != "" {
|
||||
if _, err := h.Playlists.Update(k.ctx, k.principal.UserID, id, &name, nil); err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
p, err := h.Playlists.Create(k.ctx, k.principal.UserID, name, "")
|
||||
if err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
id = p.ID
|
||||
}
|
||||
if bad := h.add(k, id, songs); bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
return h.opened(k, id)
|
||||
}
|
||||
|
||||
// allItems are every item of a playlist, the ones that cannot be played too.
|
||||
func (h *handler) allItems(k *call, id int64) ([]playlists.Item, *Error) {
|
||||
var all []playlists.Item
|
||||
for {
|
||||
p, err := h.Playlists.Items(k.ctx, k.principal.UserID, id, playlists.Page{Limit: playlists.MaxLimit, Offset: len(all)})
|
||||
if err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
all = append(all, p.Items...)
|
||||
if len(p.Items) == 0 || len(all) >= p.Total {
|
||||
return all, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// updatePlaylist renames a playlist, changes its comment, takes songs out by their place in the list the app was
|
||||
// shown, and adds songs at the end.
|
||||
func (h *handler) updatePlaylist(k *call) (*Response, *Error) {
|
||||
raw := k.param("playlistId")
|
||||
if raw == "" {
|
||||
return nil, missing("playlistId")
|
||||
}
|
||||
id, bad := idOf(raw, playlistPrefix)
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
if _, err := h.Playlists.Get(k.ctx, k.principal.UserID, id); err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
add, bad := songIDs(k, "songIdToAdd")
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
var remove []int
|
||||
for _, v := range k.c.Request.Form["songIndexToRemove"] {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 0 {
|
||||
return nil, &Error{Code: ErrGeneric, Message: "invalid songIndexToRemove"}
|
||||
}
|
||||
remove = append(remove, n)
|
||||
}
|
||||
|
||||
var name, comment *string
|
||||
if _, given := k.c.Request.Form["name"]; given {
|
||||
v := k.param("name")
|
||||
name = &v
|
||||
}
|
||||
if _, given := k.c.Request.Form["comment"]; given {
|
||||
v := k.param("comment")
|
||||
comment = &v
|
||||
}
|
||||
if name != nil || comment != nil {
|
||||
if _, err := h.Playlists.Update(k.ctx, k.principal.UserID, id, name, comment); err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
}
|
||||
if len(remove) > 0 {
|
||||
items, bad := h.entries(k, id) // the places are those of the list the app was shown
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
gone := map[int64]bool{}
|
||||
for _, n := range remove {
|
||||
if n >= len(items) {
|
||||
return nil, &Error{Code: ErrGeneric, Message: "songIndexToRemove is past the end of the playlist"}
|
||||
}
|
||||
gone[items[n].ID] = true
|
||||
}
|
||||
for itemID := range gone {
|
||||
if err := h.Playlists.RemoveItem(k.ctx, k.principal.UserID, id, itemID); err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if bad := h.add(k, id, add); bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
return &Response{}, nil
|
||||
}
|
||||
|
||||
func (h *handler) deletePlaylist(k *call) (*Response, *Error) {
|
||||
id, bad := idParam(k, playlistPrefix)
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
if err := h.Playlists.Delete(k.ctx, k.principal.UserID, id); err != nil {
|
||||
return nil, playlistFailure(err)
|
||||
}
|
||||
return &Response{}, nil
|
||||
}
|
||||
|
||||
// nowPlaying is always empty: what a person plays is nobody else's business.
|
||||
func (h *handler) nowPlaying(*call) (*Response, *Error) {
|
||||
return &Response{NowPlaying: &NowPlaying{}}, nil
|
||||
}
|
||||
|
||||
// scrobble records the songs an app says were listened to. With submission=false the app only says it started
|
||||
// one: nothing is recorded, because only a listen counts. A retry of the same listen is recorded once.
|
||||
func (h *handler) scrobble(k *call) (*Response, *Error) {
|
||||
rawIDs := k.c.Request.Form["id"]
|
||||
if len(rawIDs) == 0 {
|
||||
return nil, missing("id")
|
||||
}
|
||||
songs, bad := songIDs(k, "id")
|
||||
if bad != nil {
|
||||
return nil, bad
|
||||
}
|
||||
submission := true
|
||||
switch k.param("submission") {
|
||||
case "", "true":
|
||||
case "false":
|
||||
submission = false
|
||||
default:
|
||||
return nil, &Error{Code: ErrGeneric, Message: "submission must be true or false"}
|
||||
}
|
||||
var times []time.Time
|
||||
for _, v := range k.c.Request.Form["time"] {
|
||||
ms, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil || ms < 0 {
|
||||
return nil, &Error{Code: ErrGeneric, Message: "invalid time"}
|
||||
}
|
||||
times = append(times, time.UnixMilli(ms))
|
||||
}
|
||||
if !submission {
|
||||
return &Response{}, nil
|
||||
}
|
||||
for i, id := range songs {
|
||||
at := time.Now()
|
||||
if i < len(times) {
|
||||
at = times[i]
|
||||
}
|
||||
t, err := h.Catalog.Track(k.ctx, id)
|
||||
if err != nil {
|
||||
return nil, failure(err)
|
||||
}
|
||||
res, err := h.Listens.Record(k.ctx, listening.Event{
|
||||
UserID: k.principal.UserID, TrackID: id, Type: listening.Complete, OccurredAt: at, DurationPlayedMs: t.DurationMs,
|
||||
IdempotencyKey: "subsonic-" + strconv.FormatInt(k.principal.DeviceID, 10) + "-" + strconv.FormatInt(id, 10) + "-" + strconv.FormatInt(at.UnixMilli(), 10),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, listening.ErrTrackNotFound):
|
||||
return nil, notFound()
|
||||
case errors.Is(err, listening.ErrInvalidEvent):
|
||||
return nil, &Error{Code: ErrGeneric, Message: err.Error()}
|
||||
case err != nil:
|
||||
return nil, &Error{Code: ErrGeneric, Message: "the listen could not be recorded"}
|
||||
}
|
||||
if res.Created && res.Counted && h.Announcer != nil {
|
||||
h.Announcer.Announce(k.principal.UserID, id)
|
||||
}
|
||||
}
|
||||
return &Response{}, nil
|
||||
}
|
||||
|
|
@ -34,6 +34,34 @@ type Response struct {
|
|||
SongsByGenre *SongList `xml:"songsByGenre" json:"songsByGenre,omitempty"`
|
||||
SearchResult3 *SearchResult `xml:"searchResult3" json:"searchResult3,omitempty"`
|
||||
Starred2 *SearchResult `xml:"starred2" json:"starred2,omitempty"`
|
||||
Playlists *PlaylistList `xml:"playlists" json:"playlists,omitempty"`
|
||||
Playlist *Playlist `xml:"playlist" json:"playlist,omitempty"`
|
||||
NowPlaying *NowPlaying `xml:"nowPlaying" json:"nowPlaying,omitempty"`
|
||||
}
|
||||
|
||||
// PlaylistList are the playlists of a person.
|
||||
type PlaylistList struct {
|
||||
Playlist []Playlist `xml:"playlist" json:"playlist,omitempty"`
|
||||
}
|
||||
|
||||
// Playlist is a playlist; Entry holds its songs when it is opened.
|
||||
type Playlist struct {
|
||||
ID string `xml:"id,attr" json:"id"`
|
||||
Name string `xml:"name,attr" json:"name"`
|
||||
Comment string `xml:"comment,attr,omitempty" json:"comment,omitempty"`
|
||||
Owner string `xml:"owner,attr,omitempty" json:"owner,omitempty"`
|
||||
Public bool `xml:"public,attr" json:"public"`
|
||||
SongCount int `xml:"songCount,attr" json:"songCount"`
|
||||
Duration int `xml:"duration,attr" json:"duration"`
|
||||
Created string `xml:"created,attr" json:"created"`
|
||||
Changed string `xml:"changed,attr" json:"changed"`
|
||||
CoverArt string `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
|
||||
Entry []Child `xml:"entry" json:"entry,omitempty"`
|
||||
}
|
||||
|
||||
// NowPlaying is what is being played now. Sonda tells nobody what a person plays, so it is always empty.
|
||||
type NowPlaying struct {
|
||||
Entry []Child `xml:"entry" json:"entry,omitempty"`
|
||||
}
|
||||
|
||||
// AlbumList2 is a list of albums.
|
||||
|
|
|
|||
Loading…
Reference in a new issue