Merge remote-tracking branch 'origin/main' into feat/duplicates-api

This commit is contained in:
tgiachi 2026-11-12 17:00:00 +01:00
commit 3d986f051d
16 changed files with 2732 additions and 2 deletions

View file

@ -21,6 +21,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
- **Artist descriptions.** `GET /artists/{id}/description` shows what Wikipedia says about an artist: a short text, with the page it comes from, a link to it and the licence (CC BY-SA 4.0), which you must show next to it. With the `wikipedia` provider and the `musicbrainz` one switched on (the link to Wikidata comes from MusicBrainz), Sonda follows ids and never a name: the artist's MusicBrainz id, then the Wikidata item that MusicBrainz links to it, then the Wikipedia page that Wikidata names in the first of your languages (`[wikipedia] languages`, the code of that Wikipedia, for example `["it", "en"]`) that has one. An artist without a MusicBrainz id has no description. It is kept for 30 days and removed with the provider's data. To read the descriptions of the whole library in one go, an admin starts a background job like a scan: `POST /library/descriptions` (follow it with `GET /library/descriptions`, stop it with `DELETE /library/descriptions`; `?refresh=true` reads every artist again). It only goes through artists that have a MusicBrainz id, never replaces a description by a failure, and ends at once, saying so, when a provider it needs is off. See [External providers](#external-providers).
- **Artist photos.** `GET /artists/{id}/image` serves a free picture of an artist from Wikimedia Commons, and `GET /artists/{id}/image/credit` says whose it is and under which licence, which you must show next to it. Only free licences are kept (public domain, CC0, CC BY, CC BY-SA): non-commercial, no-derivatives, fair-use and unknown ones are refused, because Sonda stores a copy (`?size=small` is 300 pixels, `large` 1000) in the data folder. With the `commons` provider and the `musicbrainz` one switched on, Sonda follows ids and never a name: the artist's MusicBrainz id, the Wikidata item MusicBrainz links to it, the picture Wikidata names for it, and Commons for its licence. Many artists will have none. Kept for 30 days (a week when there is none) and removed, files included, with the provider's data. To look for the pictures of the whole library in one go, an admin starts a background job like a scan: `POST /library/artist-images` (follow it with `GET /library/artist-images`, stop it with `DELETE /library/artist-images`; `?refresh=true` searches every artist again). It only goes through artists that have a MusicBrainz id, never replaces a picture by a failure, and ends at once, saying so, when a provider it needs is off. See [External providers](#external-providers).
- **Album covers.** `GET /albums/{id}/cover` serves the cover of an album from your own files: the picture embedded in them, or else a `cover`, `folder`, `front`, `album` or `albumart` image in the album's folder. It is built the first time it is asked for (a few at a time), scaled (`?size=small` is 300 pixels, `large` 1000) and kept in the data folder (`storage.data_dir`, you can delete it: covers are built again). A picture you replace in a folder is noticed within a week, or at once after a full rescan. When your files have no picture at all and an admin switched on the `coverartarchive` provider, the cover is asked from the Cover Art Archive by the MusicBrainz release group id that the tags of the album's files carry (`MUSICBRAINZ_RELEASEGROUPID`; run a full rescan to read it for music you already indexed); your own files always come first, and only that id leaves the server. An album whose files have no id is looked up in MusicBrainz by its artist and title when the `musicbrainz` provider is on too (see the list of what leaves your server). For an album split in `CD1`/`Disc 2` folders, the picture in the folder above is used. Nothing is sent anywhere unless you switched on the `coverartarchive` provider (see [External providers](#external-providers)). It also takes `?access_token=`, so an `<img>` element can use it. To build the covers of the whole library in one go instead of one album at a time, an admin starts a background job like a scan: `POST /library/covers` (follow it with `GET /library/covers`, stop it with `DELETE /library/covers`; `?refresh=true` searches every album again; it never replaces a cover by "no cover" because a disk was not mounted, and keeps the covers that came from the archive if you switched it off).
- **Playlists.** `POST /playlists` makes a playlist (a name and an optional description) and `GET /playlists` lists yours, the one changed last first. `POST /playlists/{id}/tracks` adds 1 to 500 tracks at the end or at a `position`, `GET /playlists/{id}/tracks` lists them in order, `PATCH /playlists/{id}/tracks/{item}` moves one and `DELETE` takes one out; `PATCH /playlists/{id}` renames and `DELETE /playlists/{id}` deletes (the tracks stay in the library). A track can be in a playlist more than once, which is why each place has its own item id. A playlist is yours alone: someone else's answers `playlist_not_found`, as one that does not exist. A track whose files were deleted or moved away stays in the playlist and shows `available: false`; it plays again when the files come back and a scan finds them. A user can have 1000 playlists of up to 10000 tracks. Nothing is shared and nothing leaves your server.
- **Wishlist and "not interested".** `PUT /wishlist/{artist}` puts an artist on your wishlist (`GET /wishlist` lists it, `DELETE` takes it off), and `POST /discover/{artist}/dismiss` hides an artist from your Discover for good (`DELETE` brings it back, `GET /discover/dismissed` lists them). An artist is wished or dismissed, never both, and both lists are yours alone. Discover marks the wished artists it shows (`wishlisted`) and never suggests a dismissed one. The wishlist is a list for you and sends nothing anywhere; Sonda downloads nothing, but an admin can send an artist that Discover showed to their own Lidarr (see [External providers](#external-providers)), which works for an artist that has a MusicBrainz id and that Sonda knows of from a list or from your files. An artist that only Last.fm named is kept while you have it marked (your lists still show it, but other users cannot see that it exists), and goes with the rest of Last.fm's data if an admin removes Last.fm's data. Removing MusicBrainz's data does not touch it.
- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so this setting never sends your listening to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on). What Last.fm answers is kept in the shared database like any other lookup, so another local user can see, from `retrieved_at` of `GET /artists/{id}/similar`, that someone looked up an artist, but not who.
- **Tags.** `GET /artists/{id}/tags` shows what Last.fm and MusicBrainz say kind of music an artist plays, each with its own weights, and the genres of the artist's own files, read offline. See [External providers](#external-providers).
@ -291,6 +292,8 @@ Everything lives under `/api/v1`. Bodies are JSON. Errors always look like `{"er
| signed in | `GET /listens` | Your own history, newest first, with `counted` per event. Query: `limit`, `offset`, `counted=true`. |
| signed in | `GET /discover` | Artists you may like, with a score and its parts. Query: `seed` (an artist id, up to 5 times), `limit` (default 20, max 30), `in_library=true\|false`. |
| signed in | `GET`, `HEAD /albums/{id}/cover` | The cover of an album, a JPEG made from your own files. Query: `size=small\|large`. Also accepts `?access_token=`. |
| signed in | `GET /playlists`, `POST /playlists`, `GET`, `PATCH`, `DELETE /playlists/{id}` | Your playlists: list them (query `limit`, `offset`), make one, read, rename or delete one. Never anybody else's. |
| signed in | `GET /playlists/{id}/tracks`, `POST /playlists/{id}/tracks`, `PATCH`, `DELETE /playlists/{id}/tracks/{item}` | The tracks of a playlist: list them in order, add some (at the end or at a `position`), move or remove an item. |
| signed in | `GET /wishlist`, `PUT /wishlist/{id}`, `DELETE /wishlist/{id}` | Your wishlist: list it (query `limit`, `offset`), add an artist, take one off. |
| signed in | `GET /discover/dismissed`, `POST /discover/{id}/dismiss`, `DELETE /discover/{id}/dismiss` | The artists you are not interested in: list them, dismiss one, bring it back. |
| signed in | `GET /me/taste` | The artists and tags Sonda learned you like, from your own listening. Query: `limit` (default 20, max 50). |
@ -374,6 +377,7 @@ internal/listening/ listen events
internal/taste/ what the listener likes, learned from the listening history
internal/discover/ the score of an artist you may like, and the suggestions
internal/feedback/ the wishlist and the artists a user is not interested in
internal/playlists/ the playlists of each user
internal/images/ covers made from the pictures in the user's own files
internal/usersettings/ the settings that belong to one user
internal/storage/ SQLite and PostgreSQL through bun, the repositories

View file

@ -27,6 +27,7 @@ import (
"codeberg.org/squidd/sonda/internal/jobs"
"codeberg.org/squidd/sonda/internal/library"
"codeberg.org/squidd/sonda/internal/listening"
"codeberg.org/squidd/sonda/internal/playlists"
"codeberg.org/squidd/sonda/internal/providers"
"codeberg.org/squidd/sonda/internal/providers/commons"
"codeberg.org/squidd/sonda/internal/providers/coverart"
@ -289,6 +290,7 @@ func run() error {
Taste: tasteService,
Discover: discover.NewService(tasteService, discoveries, tags, tasteRepo, userSettings, feedbacks, weights),
Feedback: feedbacks,
Playlists: playlists.NewService(storage.NewPlaylistRepo(db)),
Images: pictures,
CoversJob: jobs.Runner{Ctx: ctx, Job: images.NewCoversJob(pictures, imageRepo)},
ArtistImagesJob: jobs.Runner{Ctx: ctx, Job: images.NewArtistImagesJob(pictures, imageRepo)},

View file

@ -26,6 +26,7 @@ import (
"codeberg.org/squidd/sonda/internal/jobs"
"codeberg.org/squidd/sonda/internal/library"
"codeberg.org/squidd/sonda/internal/listening"
"codeberg.org/squidd/sonda/internal/playlists"
"codeberg.org/squidd/sonda/internal/providers"
"codeberg.org/squidd/sonda/internal/storage"
"codeberg.org/squidd/sonda/internal/streaming"
@ -104,6 +105,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
}
feedbackSvc := feedback.NewService(storage.NewFeedbackRepo(db))
deps.Feedback = feedbackSvc
deps.Playlists = playlists.NewService(storage.NewPlaylistRepo(db))
imageRepo := storage.NewImageRepo(db)
imageSvc := images.NewService(filepath.Join(t.TempDir(), "data"), imageRepo, imageRepo)
deps.Images, deps.ArtistImages = imageSvc, imageSvc

View file

@ -282,6 +282,15 @@ func (c *contract) expect(rec *httptest.ResponseRecorder, want int, what string,
return out
}
func mustInt(t *testing.T, s string) int64 {
t.Helper()
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
t.Fatal(err)
}
return n
}
func idOf(m map[string]any) string { return strconv.FormatInt(int64(m["id"].(float64)), 10) }
// scanDone waits for the running scan to finish.
@ -742,6 +751,42 @@ func TestResponsesMatchTheSpec(t *testing.T) {
}
c.expect(c.call("PATCH", "/me/settings", token, map[string]any{"discover_from_listening": false}), 200, "forbid it again")
// ---- playlists ----
c.expect(c.call("GET", "/playlists", "", nil), 401, "playlists without a token", "unauthorized")
c.expect(c.call("POST", "/playlists", token, map[string]string{"name": " "}), 400, "playlist with a blank name", "invalid_input")
plID := idOf(c.expect(c.call("POST", "/playlists", token, map[string]string{"name": "Road trip", "description": "for the car"}), 201, "create a playlist"))
if pls := c.expect(c.call("GET", "/playlists?limit=5", token, nil), 200, "list playlists"); pls["total"] != float64(1) {
t.Fatalf("playlists = %v", pls)
}
c.expect(c.call("GET", "/playlists?limit=-1", token, nil), 400, "playlists with a bad limit", "invalid_input")
c.expect(c.call("GET", "/playlists/"+plID, token, nil), 200, "get a playlist")
c.expect(c.call("GET", "/playlists/999", token, nil), 404, "get an unknown playlist", "playlist_not_found")
c.expect(c.call("PATCH", "/playlists/"+plID, token, map[string]string{"name": "Road trip 2"}), 200, "rename a playlist")
c.expect(c.call("PATCH", "/playlists/"+plID, token, map[string]string{}), 400, "patch a playlist with nothing", "invalid_input")
c.expect(c.call("PATCH", "/playlists/999", token, map[string]string{"name": "x"}), 404, "patch an unknown playlist", "playlist_not_found")
c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []string{trackID, trackID}}), 400, "track ids as strings", "invalid_input")
if pl := c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []int64{mustInt(t, trackID), mustInt(t, trackID)}}), 200, "add tracks to a playlist"); pl["track_count"] != float64(2) {
t.Fatalf("playlist = %v", pl)
}
c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []int64{mustInt(t, trackID)}, "position": 0}), 200, "add a track at the front")
c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []int64{mustInt(t, trackID)}, "position": 9}), 400, "add beyond the end", "invalid_position")
c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []int64{999999}}), 422, "add an unknown track", "track_not_found")
c.expect(c.call("POST", "/playlists/999/tracks", token, map[string]any{"track_ids": []int64{mustInt(t, trackID)}}), 404, "add to an unknown playlist", "playlist_not_found")
plItems := c.expect(c.call("GET", "/playlists/"+plID+"/tracks?limit=10", token, nil), 200, "the tracks of a playlist")
if plItems["total"] != float64(3) {
t.Fatalf("items = %v", plItems)
}
firstItem := idOf(plItems["items"].([]any)[0].(map[string]any))
c.expect(c.call("GET", "/playlists/999/tracks", token, nil), 404, "tracks of an unknown playlist", "playlist_not_found")
c.expect(c.call("PATCH", "/playlists/"+plID+"/tracks/"+firstItem, token, map[string]int{"position": 2}), 204, "move an item")
c.expect(c.call("PATCH", "/playlists/"+plID+"/tracks/"+firstItem, token, map[string]int{"position": 3}), 400, "move beyond the end", "invalid_position")
c.expect(c.call("PATCH", "/playlists/"+plID+"/tracks/"+firstItem, token, map[string]string{}), 400, "move with no position", "invalid_input")
c.expect(c.call("PATCH", "/playlists/"+plID+"/tracks/999999", token, map[string]int{"position": 0}), 404, "move an unknown item", "item_not_found")
c.expect(c.call("DELETE", "/playlists/"+plID+"/tracks/"+firstItem, token, nil), 204, "remove an item")
c.expect(c.call("DELETE", "/playlists/"+plID+"/tracks/"+firstItem, token, nil), 404, "remove it twice", "item_not_found")
c.expect(c.call("DELETE", "/playlists/"+plID, token, nil), 204, "delete a playlist")
c.expect(c.call("DELETE", "/playlists/"+plID, token, nil), 404, "delete it twice", "playlist_not_found")
// ---- wishlist and dismissed ----
gammaID := idOf(found["items"].([]any)[0].(map[string]any)["artist"].(map[string]any))
c.expect(c.call("PUT", "/wishlist/"+gammaID, token, nil), 204, "wish for an artist")

View file

@ -0,0 +1,268 @@
package httpapi
import (
"errors"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"codeberg.org/squidd/sonda/internal/playlists"
)
// playlistHandlers serve the signed-in user's playlists. They are theirs alone: a playlist of
// somebody else answers playlist_not_found, as one that does not exist.
type playlistHandlers struct{ svc playlistService }
type playlistJSON struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
TrackCount int `json:"track_count"`
DurationMs int64 `json:"duration_ms"`
CreatedAt *string `json:"created_at"`
UpdatedAt *string `json:"updated_at"`
}
type playlistPageJSON struct {
Items []playlistJSON `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type playlistItemJSON struct {
ID int64 `json:"id"`
Position int `json:"position"`
Available bool `json:"available"`
AddedAt *string `json:"added_at"`
Track trackJSON `json:"track"`
}
type playlistItemsJSON struct {
Items []playlistItemJSON `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
func toPlaylistJSON(p playlists.Playlist) playlistJSON {
return playlistJSON{
ID: p.ID, Name: p.Name, Description: p.Description, TrackCount: p.TrackCount, DurationMs: p.DurationMs,
CreatedAt: rfc3339(p.CreatedAt), UpdatedAt: rfc3339(p.UpdatedAt),
}
}
func writePlaylistError(c *gin.Context, err error) {
switch {
case errors.Is(err, playlists.ErrInvalidInput):
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
case errors.Is(err, playlists.ErrNotFound):
writeError(c, http.StatusNotFound, "playlist_not_found", "no such playlist")
case errors.Is(err, playlists.ErrItemNotFound):
writeError(c, http.StatusNotFound, "item_not_found", "the playlist has no such item")
case errors.Is(err, playlists.ErrTrackNotFound):
writeError(c, http.StatusUnprocessableEntity, "track_not_found", "one of the tracks does not exist")
case errors.Is(err, playlists.ErrPosition):
writeError(c, http.StatusBadRequest, "invalid_position", err.Error())
case errors.Is(err, playlists.ErrTooMany):
writeError(c, http.StatusConflict, "limit_reached", err.Error())
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
}
// itemID reads the item of the path.
func itemID(c *gin.Context) (int64, bool) {
id, err := strconv.ParseInt(c.Param("item"), 10, 64)
if err != nil || id <= 0 {
writeError(c, http.StatusBadRequest, "invalid_input", "item must be a positive number")
return 0, false
}
return id, true
}
// pageOf reads limit and offset from the query string.
func pageOf(c *gin.Context) (playlists.Page, bool) {
limit, ok := queryInt(c, "limit")
if !ok {
return playlists.Page{}, false
}
offset, ok := queryInt(c, "offset")
if !ok {
return playlists.Page{}, false
}
return playlists.Page{Limit: clampInt(limit), Offset: clampInt(offset)}, true
}
type createPlaylistRequest struct {
Name string `json:"name"`
Description string `json:"description"`
}
func (h *playlistHandlers) create(c *gin.Context) {
var req createPlaylistRequest
if !bindJSON(c, &req) {
return
}
p, err := h.svc.Create(c.Request.Context(), currentUserID(c), req.Name, req.Description)
if err != nil {
writePlaylistError(c, err)
return
}
c.JSON(http.StatusCreated, toPlaylistJSON(p))
}
func (h *playlistHandlers) list(c *gin.Context) {
page, ok := pageOf(c)
if !ok {
return
}
l, err := h.svc.List(c.Request.Context(), currentUserID(c), page)
if err != nil {
writePlaylistError(c, err)
return
}
out := playlistPageJSON{Items: make([]playlistJSON, len(l.Items)), Total: l.Total, Limit: l.Limit, Offset: l.Offset}
for i, p := range l.Items {
out.Items[i] = toPlaylistJSON(p)
}
c.JSON(http.StatusOK, out)
}
func (h *playlistHandlers) get(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
p, err := h.svc.Get(c.Request.Context(), currentUserID(c), id)
if err != nil {
writePlaylistError(c, err)
return
}
c.JSON(http.StatusOK, toPlaylistJSON(p))
}
type updatePlaylistRequest struct {
Name *string `json:"name"` // pointers: absent must not mean empty
Description *string `json:"description"` // an empty one clears it
}
func (h *playlistHandlers) update(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req updatePlaylistRequest
if !bindJSON(c, &req) {
return
}
p, err := h.svc.Update(c.Request.Context(), currentUserID(c), id, req.Name, req.Description)
if err != nil {
writePlaylistError(c, err)
return
}
c.JSON(http.StatusOK, toPlaylistJSON(p))
}
func (h *playlistHandlers) remove(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
if err := h.svc.Delete(c.Request.Context(), currentUserID(c), id); err != nil {
writePlaylistError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *playlistHandlers) items(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
page, ok := pageOf(c)
if !ok {
return
}
l, err := h.svc.Items(c.Request.Context(), currentUserID(c), id, page)
if err != nil {
writePlaylistError(c, err)
return
}
out := playlistItemsJSON{Items: make([]playlistItemJSON, len(l.Items)), Total: l.Total, Limit: l.Limit, Offset: l.Offset}
for i, it := range l.Items {
out.Items[i] = playlistItemJSON{
ID: it.ID, Position: it.Position, Available: it.Available, AddedAt: rfc3339(it.AddedAt), Track: toTrackJSON(it.Track),
}
}
c.JSON(http.StatusOK, out)
}
type addTracksRequest struct {
TrackIDs []int64 `json:"track_ids"`
Position *int `json:"position"` // absent: at the end
}
func (h *playlistHandlers) addTracks(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req addTracksRequest
if !bindJSON(c, &req) {
return
}
p, err := h.svc.AddTracks(c.Request.Context(), currentUserID(c), id, req.TrackIDs, req.Position)
if err != nil {
writePlaylistError(c, err)
return
}
c.JSON(http.StatusOK, toPlaylistJSON(p))
}
func (h *playlistHandlers) removeItem(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
item, ok := itemID(c)
if !ok {
return
}
if err := h.svc.RemoveItem(c.Request.Context(), currentUserID(c), id, item); err != nil {
writePlaylistError(c, err)
return
}
c.Status(http.StatusNoContent)
}
type moveItemRequest struct {
Position *int `json:"position"`
}
func (h *playlistHandlers) moveItem(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
item, ok := itemID(c)
if !ok {
return
}
var req moveItemRequest
if !bindJSON(c, &req) {
return
}
if req.Position == nil {
writeError(c, http.StatusBadRequest, "invalid_input", "position is required")
return
}
if err := h.svc.MoveItem(c.Request.Context(), currentUserID(c), id, item, *req.Position); err != nil {
writePlaylistError(c, err)
return
}
c.Status(http.StatusNoContent)
}

View file

@ -0,0 +1,261 @@
package httpapi
import (
"net/http"
"strings"
"testing"
"github.com/uptrace/bun"
)
// plAPI is a server with an admin (alice), a second user (bob) and four tracks.
type plAPI struct {
h http.Handler
alice string
bob string
tracks []int64
}
func newPlAPI(t *testing.T) *plAPI {
t.Helper()
h, database := newTestEnvDB(t, func(*Deps, *bun.DB) {})
alice := registerAndLogin(t, h)
_, bob := addUser(t, h, alice, "bob", false)
for _, title := range []string{"one", "two", "three"} {
if _, err := database.Exec("INSERT INTO tracks (title) VALUES (?)", title); err != nil {
t.Fatal(err)
}
}
var tracks []int64
rows, err := database.Query("SELECT id FROM tracks ORDER BY id")
if err != nil {
t.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
t.Fatal(err)
}
tracks = append(tracks, id)
}
return &plAPI{h: h, alice: alice, bob: bob, tracks: tracks}
}
func (p *plAPI) create(t *testing.T, token, name string) int64 {
t.Helper()
r := do(t, p.h, "POST", "/api/v1/playlists", token, map[string]any{"name": name})
if r.Code != http.StatusCreated {
t.Fatalf("create %q: %d %v", name, r.Code, r.Body)
}
return int64(r.Body["id"].(float64))
}
func (p *plAPI) add(t *testing.T, token string, pl int64, ids ...int64) resp {
t.Helper()
return do(t, p.h, "POST", "/api/v1/playlists/"+id(pl)+"/tracks", token, map[string]any{"track_ids": ids})
}
func (p *plAPI) titles(t *testing.T, token string, pl int64) []string {
t.Helper()
r := do(t, p.h, "GET", "/api/v1/playlists/"+id(pl)+"/tracks", token, nil)
if r.Code != http.StatusOK {
t.Fatalf("items: %d %v", r.Code, r.Body)
}
var out []string
for _, it := range r.Body["items"].([]any) {
out = append(out, it.(map[string]any)["track"].(map[string]any)["title"].(string))
}
return out
}
func TestPlaylistRoutesNeedASignedInUser(t *testing.T) {
p := newPlAPI(t)
for _, rt := range []struct{ method, path string }{
{"GET", "/api/v1/playlists"}, {"POST", "/api/v1/playlists"},
{"GET", "/api/v1/playlists/1"}, {"PATCH", "/api/v1/playlists/1"}, {"DELETE", "/api/v1/playlists/1"},
{"GET", "/api/v1/playlists/1/tracks"}, {"POST", "/api/v1/playlists/1/tracks"},
{"DELETE", "/api/v1/playlists/1/tracks/1"}, {"PATCH", "/api/v1/playlists/1/tracks/1"},
} {
if r := do(t, p.h, rt.method, rt.path, "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("%s %s without a token: %d", rt.method, rt.path, r.Code)
}
}
}
func TestCreateListGetUpdateAndDeleteAPlaylist(t *testing.T) {
p := newPlAPI(t)
r := do(t, p.h, "POST", "/api/v1/playlists", p.alice, map[string]any{"name": " Road trip ", "description": "for the car"})
if r.Code != http.StatusCreated || r.Body["name"] != "Road trip" || r.Body["description"] != "for the car" ||
r.Body["track_count"] != float64(0) || r.Body["duration_ms"] != float64(0) || r.Body["created_at"] == nil || r.Body["updated_at"] == nil {
t.Fatalf("create: %d %v", r.Code, r.Body)
}
pl := int64(r.Body["id"].(float64))
second := p.create(t, p.alice, "Second")
list := do(t, p.h, "GET", "/api/v1/playlists", p.alice, nil)
items, _ := list.Body["items"].([]any)
if list.Code != http.StatusOK || list.Body["total"] != float64(2) || len(items) != 2 || items[0].(map[string]any)["id"] != float64(second) {
t.Fatalf("list: %d %v", list.Code, list.Body)
}
if got := do(t, p.h, "GET", "/api/v1/playlists?limit=1&offset=1", p.alice, nil); len(got.Body["items"].([]any)) != 1 || got.Body["limit"] != float64(1) || got.Body["offset"] != float64(1) {
t.Errorf("paging: %v", got.Body)
}
if got := do(t, p.h, "GET", "/api/v1/playlists/"+id(pl), p.alice, nil); got.Code != http.StatusOK || got.Body["name"] != "Road trip" {
t.Errorf("get: %d %v", got.Code, got.Body)
}
upd := do(t, p.h, "PATCH", "/api/v1/playlists/"+id(pl), p.alice, map[string]any{"name": "Renamed"})
if upd.Code != http.StatusOK || upd.Body["name"] != "Renamed" || upd.Body["description"] != "for the car" {
t.Errorf("rename: %d %v", upd.Code, upd.Body)
}
upd = do(t, p.h, "PATCH", "/api/v1/playlists/"+id(pl), p.alice, map[string]any{"description": ""})
if upd.Code != http.StatusOK || upd.Body["description"] != "" || upd.Body["name"] != "Renamed" {
t.Errorf("clear the description: %d %v", upd.Code, upd.Body)
}
if r := do(t, p.h, "DELETE", "/api/v1/playlists/"+id(pl), p.alice, nil); r.Code != http.StatusNoContent {
t.Errorf("delete: %d %v", r.Code, r.Body)
}
if r := do(t, p.h, "GET", "/api/v1/playlists/"+id(pl), p.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "playlist_not_found" {
t.Errorf("get after delete: %d %v", r.Code, r.Body)
}
}
func TestPlaylistInputIsChecked(t *testing.T) {
p := newPlAPI(t)
pl := p.create(t, p.alice, "P")
long := strings.Repeat("a", 201)
for name, tt := range map[string]struct {
method, path string
body any
}{
"no name": {"POST", "/api/v1/playlists", map[string]any{}},
"a blank name": {"POST", "/api/v1/playlists", map[string]any{"name": " "}},
"a long name": {"POST", "/api/v1/playlists", map[string]any{"name": long}},
"not json": {"POST", "/api/v1/playlists", "{"},
"a name that is a number": {"POST", "/api/v1/playlists", `{"name": 5}`},
"nothing to change": {"PATCH", "/api/v1/playlists/" + id(pl), map[string]any{}},
"an empty new name": {"PATCH", "/api/v1/playlists/" + id(pl), map[string]any{"name": ""}},
"no track ids": {"POST", "/api/v1/playlists/" + id(pl) + "/tracks", map[string]any{}},
"an empty list": {"POST", "/api/v1/playlists/" + id(pl) + "/tracks", map[string]any{"track_ids": []int64{}}},
"a zero track id": {"POST", "/api/v1/playlists/" + id(pl) + "/tracks", map[string]any{"track_ids": []int64{0}}},
"a negative position": {"POST", "/api/v1/playlists/" + id(pl) + "/tracks", map[string]any{"track_ids": []int64{p.tracks[0]}, "position": -1}},
"a move with no place": {"PATCH", "/api/v1/playlists/" + id(pl) + "/tracks/1", map[string]any{}},
"a negative place": {"PATCH", "/api/v1/playlists/" + id(pl) + "/tracks/1", map[string]any{"position": -1}},
"a bad id": {"GET", "/api/v1/playlists/abc", nil},
"a zero id": {"GET", "/api/v1/playlists/0", nil},
"a bad limit": {"GET", "/api/v1/playlists?limit=x", nil},
"a negative offset": {"GET", "/api/v1/playlists/" + id(pl) + "/tracks?offset=-1", nil},
} {
if r := do(t, p.h, tt.method, tt.path, p.alice, tt.body); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("%s: %d %v, want 400 invalid_input", name, r.Code, r.Body)
}
}
}
func TestAddTracksListThemMoveAndRemove(t *testing.T) {
p := newPlAPI(t)
pl := p.create(t, p.alice, "P")
a, b, c := p.tracks[1], p.tracks[2], p.tracks[3]
r := p.add(t, p.alice, pl, a, b, a)
if r.Code != http.StatusOK || r.Body["track_count"] != float64(3) {
t.Fatalf("add: %d %v", r.Code, r.Body)
}
if got := p.titles(t, p.alice, pl); strings.Join(got, ",") != "one,two,one" {
t.Fatalf("titles = %v", got)
}
// In the middle.
if r := do(t, p.h, "POST", "/api/v1/playlists/"+id(pl)+"/tracks", p.alice, map[string]any{"track_ids": []int64{c}, "position": 1}); r.Code != http.StatusOK {
t.Fatalf("add at 1: %d %v", r.Code, r.Body)
}
if got := p.titles(t, p.alice, pl); strings.Join(got, ",") != "one,three,two,one" {
t.Fatalf("titles = %v", got)
}
page := do(t, p.h, "GET", "/api/v1/playlists/"+id(pl)+"/tracks?limit=2&offset=1", p.alice, nil)
items := page.Body["items"].([]any)
first := items[0].(map[string]any)
if page.Code != http.StatusOK || len(items) != 2 || page.Body["total"] != float64(4) || first["position"] != float64(1) ||
first["id"] == nil || first["available"] != false || first["added_at"] == nil || first["track"].(map[string]any)["title"] != "three" {
t.Fatalf("page: %d %v", page.Code, page.Body)
}
// Move the item at 3 to the front, then remove the one now at 1.
all := do(t, p.h, "GET", "/api/v1/playlists/"+id(pl)+"/tracks", p.alice, nil).Body["items"].([]any)
itemID := func(i int) string { return id(int64(all[i].(map[string]any)["id"].(float64))) }
if r := do(t, p.h, "PATCH", "/api/v1/playlists/"+id(pl)+"/tracks/"+itemID(3), p.alice, map[string]any{"position": 0}); r.Code != http.StatusNoContent {
t.Fatalf("move: %d %v", r.Code, r.Body)
}
if got := p.titles(t, p.alice, pl); strings.Join(got, ",") != "one,one,three,two" {
t.Fatalf("after the move: %v", got)
}
if r := do(t, p.h, "DELETE", "/api/v1/playlists/"+id(pl)+"/tracks/"+itemID(1), p.alice, nil); r.Code != http.StatusNoContent {
t.Fatalf("remove: %d %v", r.Code, r.Body)
}
// itemID(1) was "three" before the move: it is the one that goes.
if got := p.titles(t, p.alice, pl); strings.Join(got, ",") != "one,one,two" {
t.Fatalf("after the removal: %v", got)
}
if got := do(t, p.h, "GET", "/api/v1/playlists/"+id(pl), p.alice, nil); got.Body["track_count"] != float64(3) {
t.Errorf("track count = %v", got.Body["track_count"])
}
}
func TestPlaylistErrorsHaveTheirOwnCodes(t *testing.T) {
p := newPlAPI(t)
pl := p.create(t, p.alice, "P")
if r := p.add(t, p.alice, pl, p.tracks[1]); r.Code != http.StatusOK {
t.Fatal(r.Body)
}
if r := p.add(t, p.alice, pl, p.tracks[1], 99999); r.Code != http.StatusUnprocessableEntity || errCode(r) != "track_not_found" {
t.Errorf("unknown track: %d %v", r.Code, r.Body)
}
if r := do(t, p.h, "POST", "/api/v1/playlists/"+id(pl)+"/tracks", p.alice, map[string]any{"track_ids": []int64{p.tracks[1]}, "position": 5}); r.Code != http.StatusBadRequest || errCode(r) != "invalid_position" {
t.Errorf("position beyond the end: %d %v", r.Code, r.Body)
}
if r := do(t, p.h, "PATCH", "/api/v1/playlists/"+id(pl)+"/tracks/99999", p.alice, map[string]any{"position": 0}); r.Code != http.StatusNotFound || errCode(r) != "item_not_found" {
t.Errorf("move an unknown item: %d %v", r.Code, r.Body)
}
if r := do(t, p.h, "DELETE", "/api/v1/playlists/"+id(pl)+"/tracks/99999", p.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "item_not_found" {
t.Errorf("remove an unknown item: %d %v", r.Code, r.Body)
}
items := do(t, p.h, "GET", "/api/v1/playlists/"+id(pl)+"/tracks", p.alice, nil).Body["items"].([]any)
itemID := id(int64(items[0].(map[string]any)["id"].(float64)))
if r := do(t, p.h, "PATCH", "/api/v1/playlists/"+id(pl)+"/tracks/"+itemID, p.alice, map[string]any{"position": 1}); r.Code != http.StatusBadRequest || errCode(r) != "invalid_position" {
t.Errorf("move beyond the end: %d %v", r.Code, r.Body)
}
if r := do(t, p.h, "GET", "/api/v1/playlists/99999/tracks", p.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "playlist_not_found" {
t.Errorf("items of an unknown playlist: %d %v", r.Code, r.Body)
}
}
func TestAPlaylistIsOnlyItsOwnersAndAnyoneElseGetsNotFound(t *testing.T) {
p := newPlAPI(t)
pl := p.create(t, p.alice, "Private")
if r := p.add(t, p.alice, pl, p.tracks[1]); r.Code != http.StatusOK {
t.Fatal(r.Body)
}
items := do(t, p.h, "GET", "/api/v1/playlists/"+id(pl)+"/tracks", p.alice, nil).Body["items"].([]any)
itemID := id(int64(items[0].(map[string]any)["id"].(float64)))
base := "/api/v1/playlists/" + id(pl)
for _, rt := range []struct {
method, path string
body any
}{
{"GET", base, nil}, {"PATCH", base, map[string]any{"name": "mine now"}}, {"DELETE", base, nil},
{"GET", base + "/tracks", nil}, {"POST", base + "/tracks", map[string]any{"track_ids": []int64{p.tracks[1]}}},
{"DELETE", base + "/tracks/" + itemID, nil}, {"PATCH", base + "/tracks/" + itemID, map[string]any{"position": 0}},
} {
if r := do(t, p.h, rt.method, rt.path, p.bob, rt.body); r.Code != http.StatusNotFound || errCode(r) != "playlist_not_found" {
t.Errorf("bob %s %s: %d %v, want 404 playlist_not_found", rt.method, rt.path, r.Code, r.Body)
}
}
if list := do(t, p.h, "GET", "/api/v1/playlists", p.bob, nil); list.Body["total"] != float64(0) {
t.Errorf("bob's list: %v", list.Body)
}
if got := do(t, p.h, "GET", base, p.alice, nil); got.Code != http.StatusOK || got.Body["name"] != "Private" || got.Body["track_count"] != float64(1) {
t.Errorf("alice's playlist was changed: %v", got.Body)
}
}

View file

@ -24,6 +24,7 @@ import (
"codeberg.org/squidd/sonda/internal/jobs"
"codeberg.org/squidd/sonda/internal/library"
"codeberg.org/squidd/sonda/internal/listening"
"codeberg.org/squidd/sonda/internal/playlists"
"codeberg.org/squidd/sonda/internal/providers"
"codeberg.org/squidd/sonda/internal/streaming"
"codeberg.org/squidd/sonda/internal/taste"
@ -85,6 +86,19 @@ type discoverService interface {
Discover(ctx context.Context, userID int64, q discover.Query) (discover.Result, error)
}
// playlistService is what the handlers need from playlists.Service.
type playlistService 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
MoveItem(ctx context.Context, userID, id, itemID int64, position int) error
}
type feedbackService interface {
Add(ctx context.Context, userID, artistID int64, kind feedback.Kind) error
Remove(ctx context.Context, userID, artistID int64, kind feedback.Kind) error
@ -157,6 +171,7 @@ type Deps struct {
Taste tasteService
Discover discoverService
Feedback feedbackService
Playlists playlistService
Images coverService
CoversJob jobService
ArtistImagesJob jobService
@ -226,6 +241,16 @@ func NewRouter(d Deps) *gin.Engine {
protected.GET("/discover/dismissed", fb.list(feedback.Dismissed))
protected.POST("/discover/:id/dismiss", fb.add(feedback.Dismissed))
protected.DELETE("/discover/:id/dismiss", fb.remove(feedback.Dismissed))
pl := &playlistHandlers{svc: d.Playlists}
protected.GET("/playlists", pl.list)
protected.POST("/playlists", pl.create)
protected.GET("/playlists/:id", pl.get)
protected.PATCH("/playlists/:id", pl.update)
protected.DELETE("/playlists/:id", pl.remove)
protected.GET("/playlists/:id/tracks", pl.items)
protected.POST("/playlists/:id/tracks", pl.addTracks)
protected.DELETE("/playlists/:id/tracks/:item", pl.removeItem)
protected.PATCH("/playlists/:id/tracks/:item", pl.moveItem)
protected.GET("/wishlist", fb.list(feedback.Wishlist))
protected.PUT("/wishlist/:id", fb.add(feedback.Wishlist))
protected.DELETE("/wishlist/:id", fb.remove(feedback.Wishlist))

View file

@ -35,6 +35,8 @@ tags:
description: Streaming and listening history.
- name: Taste
description: What Sonda has learned from your listening, and the settings that are yours.
- name: Playlists
description: Ordered lists of tracks that belong to one user.
- name: Discovery
description: Music outside the library, from external providers an admin switched on, and suggestions scored for you.
- name: Providers
@ -1194,6 +1196,210 @@ paths:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/playlists:
get:
tags: [Playlists]
operationId: listPlaylists
summary: Your playlists
description: |
The playlists you made, the one changed last first. Only yours: nobody else's are ever
listed.
security: [{bearerAuth: []}]
parameters:
- {$ref: '#/components/parameters/Limit'}
- {$ref: '#/components/parameters/Offset'}
responses:
'200':
description: A page of playlists.
content:
application/json:
schema: {$ref: '#/components/schemas/PlaylistPage'}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
post:
tags: [Playlists]
operationId: createPlaylist
summary: Make a playlist
description: |
Makes an empty playlist. A user can have 1000. Names can repeat.
security: [{bearerAuth: []}]
requestBody:
required: true
content:
application/json:
schema: {$ref: '#/components/schemas/CreatePlaylist'}
responses:
'201':
description: The playlist.
content:
application/json:
schema: {$ref: '#/components/schemas/Playlist'}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
'409': {$ref: '#/components/responses/PlaylistLimit'}
/playlists/{id}:
parameters:
- {$ref: '#/components/parameters/Id'}
get:
tags: [Playlists]
operationId: getPlaylist
summary: A playlist
description: |
Its name, description, how many tracks it has and how long they are. The tracks come from
`GET /playlists/{id}/tracks`. A playlist of somebody else answers `playlist_not_found`.
security: [{bearerAuth: []}]
responses:
'200':
description: The playlist.
content:
application/json:
schema: {$ref: '#/components/schemas/Playlist'}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404': {$ref: '#/components/responses/PlaylistNotFound'}
patch:
tags: [Playlists]
operationId: updatePlaylist
summary: Rename a playlist or change its description
description: |
Changes what is given. An empty description clears it; a name cannot be empty.
security: [{bearerAuth: []}]
requestBody:
required: true
content:
application/json:
schema: {$ref: '#/components/schemas/UpdatePlaylist'}
responses:
'200':
description: The playlist as it is now.
content:
application/json:
schema: {$ref: '#/components/schemas/Playlist'}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404': {$ref: '#/components/responses/PlaylistNotFound'}
delete:
tags: [Playlists]
operationId: deletePlaylist
summary: Delete a playlist
description: Deletes the playlist and its list of tracks. The tracks themselves stay in the library.
security: [{bearerAuth: []}]
responses:
'204': {description: Deleted.}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404': {$ref: '#/components/responses/PlaylistNotFound'}
/playlists/{id}/tracks:
parameters:
- {$ref: '#/components/parameters/Id'}
get:
tags: [Playlists]
operationId: listPlaylistTracks
summary: The tracks of a playlist
description: |
The items in order, each with its own `id` (a track can be in a playlist more than once),
its `position` (counted from 0, without gaps) and the track. A track whose files were
deleted or moved away stays in the playlist with `available` false: it is not lost, and
it plays again when the files are back and a scan has found them.
security: [{bearerAuth: []}]
parameters:
- {$ref: '#/components/parameters/Limit'}
- {$ref: '#/components/parameters/Offset'}
responses:
'200':
description: A page of items.
content:
application/json:
schema: {$ref: '#/components/schemas/PlaylistItemPage'}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404': {$ref: '#/components/responses/PlaylistNotFound'}
post:
tags: [Playlists]
operationId: addPlaylistTracks
summary: Add tracks to a playlist
description: |
Puts 1 to 500 tracks, in the order given, at `position` (the tracks from there on move
down) or at the end when it is absent. A track can be added again. If one id is not a
track nothing is added. A playlist holds up to 10000 tracks.
security: [{bearerAuth: []}]
requestBody:
required: true
content:
application/json:
schema: {$ref: '#/components/schemas/AddPlaylistTracks'}
responses:
'200':
description: The playlist as it is now.
content:
application/json:
schema: {$ref: '#/components/schemas/Playlist'}
'400':
description: The request is malformed, or `position` is beyond the end (`invalid_position`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404': {$ref: '#/components/responses/PlaylistNotFound'}
'409': {$ref: '#/components/responses/PlaylistLimit'}
'422':
description: One of the tracks does not exist (`track_not_found`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/playlists/{id}/tracks/{item}:
parameters:
- {$ref: '#/components/parameters/Id'}
- name: item
in: path
required: true
description: The `id` of the item, not of the track.
schema: {type: integer, format: int64, minimum: 1}
patch:
tags: [Playlists]
operationId: movePlaylistItem
summary: Move a track inside a playlist
description: |
Puts the item at `position`, from 0 to the number of items less one; the ones in between
shift by one.
security: [{bearerAuth: []}]
requestBody:
required: true
content:
application/json:
schema: {$ref: '#/components/schemas/MovePlaylistItem'}
responses:
'204': {description: Moved.}
'400':
description: The request is malformed, or `position` is beyond the end (`invalid_position`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404':
description: No such playlist (`playlist_not_found`) or no such item in it (`item_not_found`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
delete:
tags: [Playlists]
operationId: removePlaylistItem
summary: Take a track out of a playlist
description: Removes that one item; the ones after it move up by one.
security: [{bearerAuth: []}]
responses:
'204': {description: Removed.}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404':
description: No such playlist (`playlist_not_found`) or no such item in it (`item_not_found`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/wishlist:
get:
tags: [Discovery]
@ -2248,6 +2454,16 @@ components:
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
PlaylistNotFound:
description: No such playlist, or it is somebody else's (`playlist_not_found`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
PlaylistLimit:
description: A limit was reached, 1000 playlists for a user or 10000 tracks in a playlist (`limit_reached`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
LibraryNotFound:
description: No such library (`library_not_found`).
content:
@ -2833,6 +3049,89 @@ components:
type: array
items: {$ref: '#/components/schemas/Suggestion'}
Playlist:
type: object
additionalProperties: false
required: [id, name, description, track_count, duration_ms, created_at, updated_at]
properties:
id: {type: integer, format: int64}
name: {type: string}
description: {type: string}
track_count: {type: integer, description: "Items in the playlist, available or not."}
duration_ms: {type: integer, format: int64, description: "Their total length."}
created_at: {type: string, format: date-time}
updated_at: {type: string, format: date-time, description: "When it was last changed, tracks included."}
PlaylistPage:
type: object
additionalProperties: false
required: [items, total, limit, offset]
properties:
items:
type: array
items: {$ref: '#/components/schemas/Playlist'}
total: {type: integer, description: "Size of the whole list, not of this page."}
limit: {type: integer}
offset: {type: integer}
PlaylistItem:
type: object
additionalProperties: false
required: [id, position, available, added_at, track]
properties:
id: {type: integer, format: int64, description: "Identifies this place of the playlist; the track may be there twice."}
position: {type: integer, minimum: 0}
available: {type: boolean, description: "False when the track has no file to play now."}
added_at: {type: string, format: date-time}
track: {$ref: '#/components/schemas/Track'}
PlaylistItemPage:
type: object
additionalProperties: false
required: [items, total, limit, offset]
properties:
items:
type: array
items: {$ref: '#/components/schemas/PlaylistItem'}
total: {type: integer, description: "Items in the whole playlist."}
limit: {type: integer}
offset: {type: integer}
CreatePlaylist:
type: object
additionalProperties: false
required: [name]
properties:
name: {type: string, minLength: 1, maxLength: 200, description: Trimmed.}
description: {type: string, maxLength: 2000}
UpdatePlaylist:
type: object
additionalProperties: false
description: At least one of the two.
properties:
name: {type: string, minLength: 1, maxLength: 200}
description: {type: string, maxLength: 2000, description: "An empty one clears it."}
AddPlaylistTracks:
type: object
additionalProperties: false
required: [track_ids]
properties:
track_ids:
type: array
minItems: 1
maxItems: 500
items: {type: integer, format: int64, minimum: 1}
position: {type: integer, minimum: 0, description: "Where the first one goes, up to the number of items; absent means the end."}
MovePlaylistItem:
type: object
additionalProperties: false
required: [position]
properties:
position: {type: integer, minimum: 0}
MarkedPage:
type: object
additionalProperties: false

View file

@ -0,0 +1,275 @@
// Package playlists keeps the playlists of each user: named, ordered lists of tracks that only
// their owner sees. Nothing here contacts anyone.
//
// A track can be in a playlist more than once, so an item has an id of its own, and the place of
// an item (its position) counts from 0 without gaps. A track whose files were deleted or moved
// away stays in its playlists and is listed as not available: it is not lost.
//
// A playlist that belongs to somebody else is as if it did not exist (ErrNotFound), so nobody
// can find out which ids are in use.
package playlists
import (
"context"
"errors"
"fmt"
"strings"
"time"
"unicode/utf8"
"codeberg.org/squidd/sonda/internal/catalog"
)
// Limits. They keep one user from filling the database and one request from doing too much.
const (
MaxNameLen = 200
MaxDescriptionLen = 2000
MaxAddAtOnce = 500 // track ids in one request
MaxItems = 10_000 // tracks in one playlist
MaxPlaylists = 1_000 // playlists of one user
DefaultLimit = 50
MaxLimit = 200
)
// Errors returned by the service and the store.
var (
ErrInvalidInput = errors.New("invalid input")
ErrNotFound = errors.New("playlist not found")
ErrItemNotFound = errors.New("item not found in the playlist")
ErrTrackNotFound = errors.New("track not found")
ErrPosition = errors.New("position out of range")
ErrTooMany = errors.New("limit reached")
)
// Playlist is a playlist and what it holds, counted over all its items, available or not.
type Playlist struct {
ID int64
Name string
Description string
TrackCount int
DurationMs int64
CreatedAt time.Time
UpdatedAt time.Time
}
// Item is one place of a playlist. Available says whether the track has a file to play.
type Item struct {
ID int64
Position int
Track catalog.Track
Available bool
AddedAt time.Time
}
// Page says which part of a list is wanted.
type Page struct {
Limit int
Offset int
}
// Store keeps the playlists. Every call is for one user and gives ErrNotFound for a playlist
// that does not exist or is not theirs. Calls that change a playlist do it in one transaction
// and set its updated time.
type Store interface {
// Create makes an empty playlist, or gives ErrTooMany when the user has MaxPlaylists.
Create(ctx context.Context, userID int64, name, description string, now time.Time) (Playlist, error)
// List returns a page of the user's playlists, the one changed last first, and how many there are.
List(ctx context.Context, userID int64, limit, offset int) ([]Playlist, int, error)
Get(ctx context.Context, userID, id int64) (Playlist, error)
// Update changes the name and/or the description that are not nil.
Update(ctx context.Context, userID, id int64, name, description *string, now time.Time) (Playlist, error)
Delete(ctx context.Context, userID, id int64) error
// Items returns a page of the playlist in order, and how many items it has.
Items(ctx context.Context, userID, id int64, limit, offset int) ([]Item, int, error)
// AddTracks puts the tracks at position (at the end when nil), in the order given, and
// returns the playlist. It gives ErrTrackNotFound when one of them does not exist (nothing
// is added), ErrPosition when position is beyond the end, and ErrTooMany when the
// playlist would have more than MaxItems.
AddTracks(ctx context.Context, userID, id int64, trackIDs []int64, position *int, now time.Time) (Playlist, error)
// RemoveItem takes an item out and closes the gap; ErrItemNotFound for one that is not in it.
RemoveItem(ctx context.Context, userID, id, itemID int64, now time.Time) error
// MoveItem puts an item at a position (0 to the number of items less one), ErrPosition otherwise.
MoveItem(ctx context.Context, userID, id, itemID int64, position int, now time.Time) error
}
// Service validates what it is given and keeps the playlists.
type Service struct{ store Store }
// NewService builds a Service.
func NewService(store Store) *Service { return &Service{store: store} }
func invalid(format string, a ...any) error {
return fmt.Errorf("%w: %s", ErrInvalidInput, fmt.Sprintf(format, a...))
}
func cleanName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" || utf8.RuneCountInString(name) > MaxNameLen {
return "", invalid("the name must have 1 to %d characters", MaxNameLen)
}
return name, nil
}
func cleanDescription(d string) (string, error) {
d = strings.TrimSpace(d)
if utf8.RuneCountInString(d) > MaxDescriptionLen {
return "", invalid("the description can have up to %d characters", MaxDescriptionLen)
}
return d, nil
}
func cleanPage(p Page) (Page, error) {
if p.Limit < 0 || p.Offset < 0 {
return p, invalid("limit and offset cannot be negative")
}
switch {
case p.Limit == 0:
p.Limit = DefaultLimit
case p.Limit > MaxLimit:
p.Limit = MaxLimit
}
return p, nil
}
// Create makes a playlist.
func (s *Service) Create(ctx context.Context, userID int64, name, description string) (Playlist, error) {
name, err := cleanName(name)
if err != nil {
return Playlist{}, err
}
description, err = cleanDescription(description)
if err != nil {
return Playlist{}, err
}
return s.store.Create(ctx, userID, name, description, time.Now())
}
// List returns a page of the user's playlists.
func (s *Service) List(ctx context.Context, userID int64, p Page) (Listing, error) {
p, err := cleanPage(p)
if err != nil {
return Listing{}, err
}
items, total, err := s.store.List(ctx, userID, p.Limit, p.Offset)
if err != nil {
return Listing{}, err
}
return Listing{Items: items, Total: total, Limit: p.Limit, Offset: p.Offset}, nil
}
// Listing is a page of playlists.
type Listing struct {
Items []Playlist
Total int
Limit int
Offset int
}
// Get returns a playlist.
func (s *Service) Get(ctx context.Context, userID, id int64) (Playlist, error) {
if id <= 0 {
return Playlist{}, ErrNotFound
}
return s.store.Get(ctx, userID, id)
}
// Update changes the name and/or the description. An empty description clears it.
func (s *Service) Update(ctx context.Context, userID, id int64, name, description *string) (Playlist, error) {
if id <= 0 {
return Playlist{}, ErrNotFound
}
if name == nil && description == nil {
return Playlist{}, invalid("nothing to change: give a name or a description")
}
if name != nil {
n, err := cleanName(*name)
if err != nil {
return Playlist{}, err
}
name = &n
}
if description != nil {
d, err := cleanDescription(*description)
if err != nil {
return Playlist{}, err
}
description = &d
}
return s.store.Update(ctx, userID, id, name, description, time.Now())
}
// Delete removes a playlist and its items; the tracks stay.
func (s *Service) Delete(ctx context.Context, userID, id int64) error {
if id <= 0 {
return ErrNotFound
}
return s.store.Delete(ctx, userID, id)
}
// ItemsListing is a page of the items of a playlist.
type ItemsListing struct {
Items []Item
Total int
Limit int
Offset int
}
// Items returns a page of the playlist, in order.
func (s *Service) Items(ctx context.Context, userID, id int64, p Page) (ItemsListing, error) {
if id <= 0 {
return ItemsListing{}, ErrNotFound
}
p, err := cleanPage(p)
if err != nil {
return ItemsListing{}, err
}
items, total, err := s.store.Items(ctx, userID, id, p.Limit, p.Offset)
if err != nil {
return ItemsListing{}, err
}
return ItemsListing{Items: items, Total: total, Limit: p.Limit, Offset: p.Offset}, nil
}
// AddTracks puts tracks in a playlist, at the end or at position, in the order given.
func (s *Service) AddTracks(ctx context.Context, userID, id int64, trackIDs []int64, position *int) (Playlist, error) {
if id <= 0 {
return Playlist{}, ErrNotFound
}
if len(trackIDs) == 0 || len(trackIDs) > MaxAddAtOnce {
return Playlist{}, invalid("give 1 to %d track ids", MaxAddAtOnce)
}
for _, t := range trackIDs {
if t <= 0 {
return Playlist{}, invalid("a track id must be positive")
}
}
if position != nil && *position < 0 {
return Playlist{}, invalid("the position cannot be negative")
}
return s.store.AddTracks(ctx, userID, id, trackIDs, position, time.Now())
}
// RemoveItem takes an item out of a playlist.
func (s *Service) RemoveItem(ctx context.Context, userID, id, itemID int64) error {
if id <= 0 {
return ErrNotFound
}
if itemID <= 0 {
return ErrItemNotFound
}
return s.store.RemoveItem(ctx, userID, id, itemID, time.Now())
}
// MoveItem puts an item at another place of its playlist.
func (s *Service) MoveItem(ctx context.Context, userID, id, itemID int64, position int) error {
if id <= 0 {
return ErrNotFound
}
if itemID <= 0 {
return ErrItemNotFound
}
if position < 0 {
return invalid("the position cannot be negative")
}
return s.store.MoveItem(ctx, userID, id, itemID, position, time.Now())
}

View file

@ -0,0 +1,188 @@
package playlists
import (
"context"
"errors"
"strings"
"testing"
"time"
)
// fakeStore records what the service asks and answers what the test sets.
type fakeStore struct {
created []string // name|description
updated [][2]*string
listLimit int
listOffset int
itemsLimit int
itemsOffset int
addIDs []int64
addPos *int
movedTo int
err error
}
func (f *fakeStore) Create(_ context.Context, _ int64, name, description string, _ time.Time) (Playlist, error) {
f.created = append(f.created, name+"|"+description)
return Playlist{ID: 1, Name: name, Description: description}, f.err
}
func (f *fakeStore) List(_ context.Context, _ int64, limit, offset int) ([]Playlist, int, error) {
f.listLimit, f.listOffset = limit, offset
return nil, 0, f.err
}
func (f *fakeStore) Get(context.Context, int64, int64) (Playlist, error) { return Playlist{}, f.err }
func (f *fakeStore) Update(_ context.Context, _, _ int64, name, description *string, _ time.Time) (Playlist, error) {
f.updated = append(f.updated, [2]*string{name, description})
return Playlist{}, f.err
}
func (f *fakeStore) Delete(context.Context, int64, int64) error { return f.err }
func (f *fakeStore) Items(_ context.Context, _, _ int64, limit, offset int) ([]Item, int, error) {
f.itemsLimit, f.itemsOffset = limit, offset
return nil, 0, f.err
}
func (f *fakeStore) AddTracks(_ context.Context, _, _ int64, ids []int64, pos *int, _ time.Time) (Playlist, error) {
f.addIDs, f.addPos = ids, pos
return Playlist{}, f.err
}
func (f *fakeStore) RemoveItem(context.Context, int64, int64, int64, time.Time) error { return f.err }
func (f *fakeStore) MoveItem(_ context.Context, _, _, _ int64, pos int, _ time.Time) error {
f.movedTo = pos
return f.err
}
func newSvc() (*Service, *fakeStore) {
f := &fakeStore{}
return NewService(f), f
}
func TestCreateTrimsTheNameAndChecksItsSize(t *testing.T) {
s, f := newSvc()
if _, err := s.Create(context.Background(), 1, " Road trip ", " for the car "); err != nil {
t.Fatal(err)
}
if len(f.created) != 1 || f.created[0] != "Road trip|for the car" {
t.Errorf("created = %q", f.created)
}
for name, tt := range map[string]struct{ name, desc string }{
"empty": {"", ""},
"only spaces": {" ", ""},
"name too long": {strings.Repeat("a", MaxNameLen+1), ""},
"too long, accent": {strings.Repeat("é", MaxNameLen+1), ""},
"description long": {"ok", strings.Repeat("a", MaxDescriptionLen+1)},
} {
if _, err := s.Create(context.Background(), 1, tt.name, tt.desc); !errors.Is(err, ErrInvalidInput) {
t.Errorf("%s: err = %v, want ErrInvalidInput", name, err)
}
}
// 200 letters with an accent are 200 characters, not 400 bytes.
if _, err := s.Create(context.Background(), 1, strings.Repeat("é", MaxNameLen), ""); err != nil {
t.Errorf("a name of %d characters: %v", MaxNameLen, err)
}
}
func TestUpdateNeedsSomethingToChangeAndAValidValue(t *testing.T) {
s, f := newSvc()
ctx := context.Background()
name, empty := " New ", " "
if _, err := s.Update(ctx, 1, 2, nil, nil); !errors.Is(err, ErrInvalidInput) {
t.Errorf("nothing to change: err = %v", err)
}
if _, err := s.Update(ctx, 1, 2, &empty, nil); !errors.Is(err, ErrInvalidInput) {
t.Errorf("an empty name: err = %v", err)
}
if _, err := s.Update(ctx, 1, 2, &name, &empty); err != nil {
t.Fatal(err)
}
if got := f.updated[0]; *got[0] != "New" || *got[1] != "" {
t.Errorf("updated = %q %q: the name is trimmed and an empty description clears it", *got[0], *got[1])
}
}
func TestListsArePagedWithDefaultsAndACap(t *testing.T) {
s, f := newSvc()
ctx := context.Background()
if _, err := s.List(ctx, 1, Page{}); err != nil || f.listLimit != DefaultLimit {
t.Errorf("default: limit = %d err = %v", f.listLimit, err)
}
if _, err := s.List(ctx, 1, Page{Limit: 100000, Offset: 5}); err != nil || f.listLimit != MaxLimit || f.listOffset != 5 {
t.Errorf("cap: limit = %d offset = %d err = %v", f.listLimit, f.listOffset, err)
}
if _, err := s.Items(ctx, 1, 2, Page{Limit: 100000}); err != nil || f.itemsLimit != MaxLimit {
t.Errorf("items cap: limit = %d err = %v", f.itemsLimit, err)
}
for _, p := range []Page{{Limit: -1}, {Offset: -1}} {
if _, err := s.List(ctx, 1, p); !errors.Is(err, ErrInvalidInput) {
t.Errorf("%+v: err = %v", p, err)
}
if _, err := s.Items(ctx, 1, 2, p); !errors.Is(err, ErrInvalidInput) {
t.Errorf("items %+v: err = %v", p, err)
}
}
}
func TestAddTracksChecksWhatIsAdded(t *testing.T) {
s, f := newSvc()
ctx := context.Background()
two := 2
if _, err := s.AddTracks(ctx, 1, 2, []int64{5, 5, 6}, &two); err != nil {
t.Fatal(err)
}
if len(f.addIDs) != 3 || f.addPos == nil || *f.addPos != 2 {
t.Errorf("ids = %v pos = %v: repeated tracks are allowed", f.addIDs, f.addPos)
}
neg := -1
big := make([]int64, MaxAddAtOnce+1)
for i := range big {
big[i] = int64(i + 1)
}
for name, tt := range map[string]struct {
ids []int64
pos *int
}{
"nothing": {nil, nil},
"too many": {big, nil},
"a zero id": {[]int64{1, 0}, nil},
"a negative id": {[]int64{-3}, nil},
"a negative place": {[]int64{1}, &neg},
} {
if _, err := s.AddTracks(ctx, 1, 2, tt.ids, tt.pos); !errors.Is(err, ErrInvalidInput) {
t.Errorf("%s: err = %v, want ErrInvalidInput", name, err)
}
}
}
func TestMoveNeedsAPlaceFromZero(t *testing.T) {
s, f := newSvc()
if err := s.MoveItem(context.Background(), 1, 2, 3, 4); err != nil || f.movedTo != 4 {
t.Errorf("moved to %d err = %v", f.movedTo, err)
}
if err := s.MoveItem(context.Background(), 1, 2, 3, -1); !errors.Is(err, ErrInvalidInput) {
t.Errorf("err = %v", err)
}
}
func TestIdsThatCannotExistAreNotFoundWithoutAskingTheStore(t *testing.T) {
s, f := newSvc()
f.err = errors.New("the store must not be asked")
ctx := context.Background()
if _, err := s.Get(ctx, 1, 0); !errors.Is(err, ErrNotFound) {
t.Errorf("get: err = %v", err)
}
if err := s.Delete(ctx, 1, -1); !errors.Is(err, ErrNotFound) {
t.Errorf("delete: err = %v", err)
}
if err := s.RemoveItem(ctx, 1, 2, 0); !errors.Is(err, ErrItemNotFound) {
t.Errorf("remove: err = %v", err)
}
if err := s.MoveItem(ctx, 1, 2, -5, 0); !errors.Is(err, ErrItemNotFound) {
t.Errorf("move: err = %v", err)
}
}

View file

@ -0,0 +1,377 @@
package storage
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/catalog"
"codeberg.org/squidd/sonda/internal/playlists"
)
type playlistRow struct {
bun.BaseModel `bun:"table:playlists"`
ID int64 `bun:"id,pk,autoincrement"`
UserID int64 `bun:"user_id,notnull"`
Name string `bun:"name,notnull"`
Description string `bun:"description,notnull"`
CreatedAt int64 `bun:"created_at,notnull"`
UpdatedAt int64 `bun:"updated_at,notnull"`
}
type playlistItemRow struct {
bun.BaseModel `bun:"table:playlist_items"`
ID int64 `bun:"id,pk,autoincrement"`
PlaylistID int64 `bun:"playlist_id,notnull"`
TrackID int64 `bun:"track_id,notnull"`
Position int `bun:"position,notnull"`
AddedAt int64 `bun:"added_at,notnull"`
}
// PlaylistRepo stores playlists. It implements playlists.Store.
type PlaylistRepo struct {
db *bun.DB
cat *CatalogRepo // reads the tracks of the items
}
// NewPlaylistRepo builds a PlaylistRepo.
func NewPlaylistRepo(db *bun.DB) *PlaylistRepo { return &PlaylistRepo{db: db, cat: NewCatalogRepo(db)} }
// summarySelect reads playlists with the number of their items and how long they are, over all
// the items, available or not.
const summarySelect = `SELECT p.id, p.name, p.description, p.created_at, p.updated_at,
COUNT(i.id), COALESCE(SUM(t.duration_ms), 0)
FROM playlists p
LEFT JOIN playlist_items i ON i.playlist_id = p.id
LEFT JOIN tracks t ON t.id = i.track_id`
func scanSummary(rows interface{ Scan(...any) error }) (playlists.Playlist, error) {
var (
p playlists.Playlist
created, updated int64
count, durationSum int64
)
if err := rows.Scan(&p.ID, &p.Name, &p.Description, &created, &updated, &count, &durationSum); err != nil {
return playlists.Playlist{}, err
}
p.CreatedAt, p.UpdatedAt = time.Unix(created, 0), time.Unix(updated, 0)
p.TrackCount, p.DurationMs = int(count), durationSum
return p, nil
}
// summary reads one playlist of a user, or playlists.ErrNotFound.
func summary(ctx context.Context, db bun.IDB, userID, id int64) (playlists.Playlist, error) {
p, err := scanSummary(db.QueryRowContext(ctx, summarySelect+" WHERE p.id = ? AND p.user_id = ? GROUP BY p.id", id, userID))
if errors.Is(err, sql.ErrNoRows) {
return playlists.Playlist{}, playlists.ErrNotFound
}
if err != nil {
return playlists.Playlist{}, fmt.Errorf("read playlist: %w", err)
}
return p, nil
}
// touch sets the updated time of a playlist of the user and so takes its row lock, which is what
// serialises two changes of the same playlist on PostgreSQL. It gives ErrNotFound when the
// playlist is not the user's.
func touch(ctx context.Context, tx bun.Tx, userID, id int64, now time.Time) error {
res, err := tx.ExecContext(ctx, "UPDATE playlists SET updated_at = ? WHERE id = ? AND user_id = ?", now.Unix(), id, userID)
if err != nil {
return fmt.Errorf("lock playlist: %w", err)
}
if n, _ := res.RowsAffected(); n == 0 {
return playlists.ErrNotFound
}
return nil
}
func countItems(ctx context.Context, tx bun.Tx, id int64) (int, error) {
var n int
if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM playlist_items WHERE playlist_id = ?", id).Scan(&n); err != nil {
return 0, fmt.Errorf("count items: %w", err)
}
return n, nil
}
// Create makes an empty playlist.
func (r *PlaylistRepo) Create(ctx context.Context, userID int64, name, description string, now time.Time) (playlists.Playlist, error) {
var out playlists.Playlist
err := r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
// The row of the user is the lock that makes the count below hold for two requests at once.
res, err := tx.ExecContext(ctx, "UPDATE users SET is_admin = is_admin WHERE id = ?", userID)
if err != nil {
return fmt.Errorf("lock user: %w", err)
}
if n, _ := res.RowsAffected(); n == 0 {
return playlists.ErrNotFound // the account is gone
}
var have int
if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM playlists WHERE user_id = ?", userID).Scan(&have); err != nil {
return fmt.Errorf("count playlists: %w", err)
}
if have >= playlists.MaxPlaylists {
return fmt.Errorf("%w: a user can have %d playlists", playlists.ErrTooMany, playlists.MaxPlaylists)
}
row := &playlistRow{UserID: userID, Name: name, Description: description, CreatedAt: now.Unix(), UpdatedAt: now.Unix()}
if _, err := tx.NewInsert().Model(row).Exec(ctx); err != nil {
return fmt.Errorf("insert playlist: %w", err)
}
out, err = summary(ctx, tx, userID, row.ID)
return err
})
return out, err
}
// List returns a page of the user's playlists, the one changed last first.
func (r *PlaylistRepo) List(ctx context.Context, userID int64, limit, offset int) ([]playlists.Playlist, int, error) {
var total int
if err := r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM playlists WHERE user_id = ?", userID).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count playlists: %w", err)
}
out := []playlists.Playlist{}
if offset >= total {
return out, total, nil
}
rows, err := r.db.QueryContext(ctx,
summarySelect+" WHERE p.user_id = ? GROUP BY p.id ORDER BY p.updated_at DESC, p.id DESC LIMIT ? OFFSET ?", userID, limit, offset)
if err != nil {
return nil, 0, fmt.Errorf("list playlists: %w", err)
}
defer rows.Close()
for rows.Next() {
p, err := scanSummary(rows)
if err != nil {
return nil, 0, err
}
out = append(out, p)
}
return out, total, rows.Err()
}
// Get returns a playlist of the user.
func (r *PlaylistRepo) Get(ctx context.Context, userID, id int64) (playlists.Playlist, error) {
return summary(ctx, r.db, userID, id)
}
// Update changes the name and/or the description that are not nil.
func (r *PlaylistRepo) Update(ctx context.Context, userID, id int64, name, description *string, now time.Time) (playlists.Playlist, error) {
var out playlists.Playlist
err := r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
q := tx.NewUpdate().Model((*playlistRow)(nil)).Set("updated_at = ?", now.Unix()).Where("id = ?", id).Where("user_id = ?", userID)
if name != nil {
q = q.Set("name = ?", *name)
}
if description != nil {
q = q.Set("description = ?", *description)
}
res, err := q.Exec(ctx)
if err := affectedOrNotFoundPlaylist(res, err); err != nil {
return err
}
out, err = summary(ctx, tx, userID, id)
return err
})
return out, err
}
func affectedOrNotFoundPlaylist(res sql.Result, err error) error {
if err != nil {
return fmt.Errorf("change playlist: %w", err)
}
if n, _ := res.RowsAffected(); n == 0 {
return playlists.ErrNotFound
}
return nil
}
// Delete removes a playlist and, through the foreign key, its items.
func (r *PlaylistRepo) Delete(ctx context.Context, userID, id int64) error {
res, err := r.db.ExecContext(ctx, "DELETE FROM playlists WHERE id = ? AND user_id = ?", id, userID)
return affectedOrNotFoundPlaylist(res, err)
}
// Items returns a page of the playlist in order. The tracks are read with the same three queries
// as any list of tracks, whatever the page size, and also when a track has no file to play.
func (r *PlaylistRepo) Items(ctx context.Context, userID, id int64, limit, offset int) ([]playlists.Item, int, error) {
p, err := summary(ctx, r.db, userID, id)
if err != nil {
return nil, 0, err
}
items := []playlists.Item{}
if offset >= p.TrackCount {
return items, p.TrackCount, nil
}
rows, err := r.db.QueryContext(ctx,
`SELECT i.id, i.position, i.added_at, t.id, t.title, COALESCE(t.duration_ms, 0), COALESCE(t.track_no, 0),
COALESCE(t.disc_no, 0), t.album_id,
EXISTS (SELECT 1 FROM audio_files f WHERE f.track_id = t.id AND f.missing_at IS NULL)
FROM playlist_items i JOIN tracks t ON t.id = i.track_id
WHERE i.playlist_id = ? ORDER BY i.position, i.id LIMIT ? OFFSET ?`, id, limit, offset)
if err != nil {
return nil, 0, fmt.Errorf("list items: %w", err)
}
defer rows.Close()
albumOf := map[int64]int64{}
page := catalog.Page[catalog.Track]{}
var trackIDs []int64
seen := map[int64]bool{}
for rows.Next() {
var (
it playlists.Item
added int64
albumID sql.NullInt64
)
t := &it.Track
if err := rows.Scan(&it.ID, &it.Position, &added, &t.ID, &t.Title, &t.DurationMs, &t.TrackNo, &t.DiscNo, &albumID, &it.Available); err != nil {
return nil, 0, err
}
it.AddedAt = time.Unix(added, 0)
t.Artists = []catalog.ArtistRef{}
if albumID.Valid {
albumOf[t.ID] = albumID.Int64
}
if !seen[t.ID] {
seen[t.ID] = true
trackIDs = append(trackIDs, t.ID)
}
items = append(items, it)
page.Items = append(page.Items, *t)
}
if err := rows.Err(); err != nil {
return nil, 0, err
}
if err := r.cat.attachTrackDetails(ctx, &page, trackIDs, albumOf, 0); err != nil {
return nil, 0, err
}
for i := range items {
items[i].Track = page.Items[i]
}
return items, p.TrackCount, nil
}
// AddTracks puts the tracks at position (at the end when nil), in the order given.
func (r *PlaylistRepo) AddTracks(ctx context.Context, userID, id int64, trackIDs []int64, position *int, now time.Time) (playlists.Playlist, error) {
var out playlists.Playlist
err := r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
if err := touch(ctx, tx, userID, id, now); err != nil {
return err
}
have, err := countItems(ctx, tx, id)
if err != nil {
return err
}
at := have
if position != nil {
at = *position
}
if at > have {
return fmt.Errorf("%w: the playlist has %d tracks", playlists.ErrPosition, have)
}
if have+len(trackIDs) > playlists.MaxItems {
return fmt.Errorf("%w: a playlist can have %d tracks", playlists.ErrTooMany, playlists.MaxItems)
}
distinct := map[int64]bool{}
var ids []int64
for _, t := range trackIDs {
if !distinct[t] {
distinct[t] = true
ids = append(ids, t)
}
}
var known int
if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM tracks WHERE id IN (?)", bun.In(ids)).Scan(&known); err != nil {
return fmt.Errorf("check tracks: %w", err)
}
if known != len(ids) {
return playlists.ErrTrackNotFound
}
if at < have {
if _, err := tx.ExecContext(ctx, "UPDATE playlist_items SET position = position + ? WHERE playlist_id = ? AND position >= ?", len(trackIDs), id, at); err != nil {
return fmt.Errorf("make room: %w", err)
}
}
rows := make([]playlistItemRow, len(trackIDs))
for i, t := range trackIDs {
rows[i] = playlistItemRow{PlaylistID: id, TrackID: t, Position: at + i, AddedAt: now.Unix()}
}
if _, err := tx.NewInsert().Model(&rows).Exec(ctx); err != nil {
return fmt.Errorf("insert items: %w", err)
}
out, err = summary(ctx, tx, userID, id)
return err
})
return out, err
}
// RemoveItem takes an item out and closes the gap.
func (r *PlaylistRepo) RemoveItem(ctx context.Context, userID, id, itemID int64, now time.Time) error {
return r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
if err := touch(ctx, tx, userID, id, now); err != nil {
return err
}
at, err := itemPosition(ctx, tx, id, itemID)
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "DELETE FROM playlist_items WHERE id = ?", itemID); err != nil {
return fmt.Errorf("delete item: %w", err)
}
if _, err := tx.ExecContext(ctx, "UPDATE playlist_items SET position = position - 1 WHERE playlist_id = ? AND position > ?", id, at); err != nil {
return fmt.Errorf("close the gap: %w", err)
}
return nil
})
}
func itemPosition(ctx context.Context, tx bun.Tx, id, itemID int64) (int, error) {
var at int
err := tx.QueryRowContext(ctx, "SELECT position FROM playlist_items WHERE id = ? AND playlist_id = ?", itemID, id).Scan(&at)
if errors.Is(err, sql.ErrNoRows) {
return 0, playlists.ErrItemNotFound
}
if err != nil {
return 0, fmt.Errorf("read item: %w", err)
}
return at, nil
}
// MoveItem puts an item at a position.
func (r *PlaylistRepo) MoveItem(ctx context.Context, userID, id, itemID int64, position int, now time.Time) error {
return r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
if err := touch(ctx, tx, userID, id, now); err != nil {
return err
}
from, err := itemPosition(ctx, tx, id, itemID)
if err != nil {
return err
}
have, err := countItems(ctx, tx, id)
if err != nil {
return err
}
if position >= have {
return fmt.Errorf("%w: the playlist has %d tracks", playlists.ErrPosition, have)
}
switch {
case from < position:
_, err = tx.ExecContext(ctx, "UPDATE playlist_items SET position = position - 1 WHERE playlist_id = ? AND position > ? AND position <= ?", id, from, position)
case from > position:
_, err = tx.ExecContext(ctx, "UPDATE playlist_items SET position = position + 1 WHERE playlist_id = ? AND position >= ? AND position < ?", id, position, from)
default:
return nil
}
if err != nil {
return fmt.Errorf("shift items: %w", err)
}
if _, err := tx.ExecContext(ctx, "UPDATE playlist_items SET position = ? WHERE id = ?", position, itemID); err != nil {
return fmt.Errorf("move item: %w", err)
}
return nil
})
}

View file

@ -0,0 +1,449 @@
package storage
import (
"context"
"errors"
"slices"
"sync"
"testing"
"time"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/playlists"
)
// plEnv is two users and four tracks (a, b, c, d), each 60 seconds long.
type plEnv struct {
t *testing.T
db *bun.DB
repo *PlaylistRepo
alice int64
bob int64
tracks map[string]int64
now time.Time
}
func newPlEnv(t *testing.T, db *bun.DB) *plEnv {
t.Helper()
ctx := context.Background()
users := NewUserRepo(db)
a, err := users.CreateUser(ctx, "alice@example.org", "hash", false)
if err != nil {
t.Fatal(err)
}
b, err := users.CreateUser(ctx, "bob@example.org", "hash", false)
if err != nil {
t.Fatal(err)
}
lib := NewLibraryRepo(db)
l, err := lib.CreateLibrary(ctx, "m", "/lib/m")
if err != nil {
t.Fatal(err)
}
e := &plEnv{t: t, db: db, repo: NewPlaylistRepo(db), alice: a.ID, bob: b.ID, tracks: map[string]int64{}, now: time.Unix(1_700_000_000, 0)}
for i, title := range []string{"a", "b", "c", "d"} {
if _, err := lib.SaveFile(ctx, l.ID, pf("x/"+title+".flac", title, "Album", "Band", i+1, 1, "flac", "Band"), 0); err != nil {
t.Fatal(err)
}
var id int64
if err := db.QueryRow("SELECT id FROM tracks WHERE title = ?", title).Scan(&id); err != nil {
t.Fatal(err)
}
e.tracks[title] = id
}
return e
}
// tick moves the clock on, so "changed last" has an order.
func (e *plEnv) tick() time.Time { e.now = e.now.Add(time.Minute); return e.now }
func (e *plEnv) create(user int64, name string) playlists.Playlist {
e.t.Helper()
p, err := e.repo.Create(context.Background(), user, name, "", e.tick())
if err != nil {
e.t.Fatal(err)
}
return p
}
// add puts tracks by name (at the end when pos < 0).
func (e *plEnv) add(user, id int64, pos int, names ...string) (playlists.Playlist, error) {
e.t.Helper()
ids := make([]int64, len(names))
for i, n := range names {
ids[i] = e.tracks[n]
}
var p *int
if pos >= 0 {
p = &pos
}
return e.repo.AddTracks(context.Background(), user, id, ids, p, e.tick())
}
// order is the titles of a playlist in order.
func (e *plEnv) order(user, id int64) []string {
e.t.Helper()
items, total, err := e.repo.Items(context.Background(), user, id, 1000, 0)
if err != nil {
e.t.Fatal(err)
}
if total != len(items) {
e.t.Fatalf("total = %d, items = %d", total, len(items))
}
out := make([]string, len(items))
for i, it := range items {
if it.Position != i {
e.t.Fatalf("item %d has position %d: positions must count from 0 without gaps", i, it.Position)
}
out[i] = it.Track.Title
}
return out
}
func (e *plEnv) itemIDs(id int64) []int64 {
e.t.Helper()
items, _, err := e.repo.Items(context.Background(), e.alice, id, 1000, 0)
if err != nil {
e.t.Fatal(err)
}
ids := make([]int64, len(items))
for i, it := range items {
ids[i] = it.ID
}
return ids
}
func plBackends(t *testing.T, fn func(t *testing.T, e *plEnv)) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { fn(t, newPlEnv(t, db)) })
}
func TestPlaylistsAreCreatedListedAndKeptApartPerUser(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
first := e.create(e.alice, "First")
second := e.create(e.alice, "Second")
other := e.create(e.bob, "Bobs")
if first.ID == 0 || first.Name != "First" || first.TrackCount != 0 || first.DurationMs != 0 || first.CreatedAt.IsZero() {
t.Errorf("first = %+v", first)
}
got, total, err := e.repo.List(ctx, e.alice, 10, 0)
if err != nil || total != 2 || len(got) != 2 || got[0].ID != second.ID || got[1].ID != first.ID {
t.Fatalf("list = %+v total %d err %v: the one changed last comes first", got, total, err)
}
// Changing the first one puts it on top.
if _, err := e.add(e.alice, first.ID, -1, "a"); err != nil {
t.Fatal(err)
}
got, _, _ = e.repo.List(ctx, e.alice, 10, 0)
if got[0].ID != first.ID || got[0].TrackCount != 1 || got[0].DurationMs != 60000 {
t.Errorf("after adding: %+v", got[0])
}
if page, total, _ := e.repo.List(ctx, e.alice, 1, 1); len(page) != 1 || total != 2 || page[0].ID != second.ID {
t.Errorf("page 2 = %+v total %d", page, total)
}
if _, err := e.repo.Get(ctx, e.alice, other.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user's playlist: err = %v, want ErrNotFound", err)
}
if _, err := e.repo.Get(ctx, e.alice, 99999); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("unknown playlist: err = %v", err)
}
if mine, total, _ := e.repo.List(ctx, e.bob, 10, 0); total != 1 || mine[0].ID != other.ID {
t.Errorf("bob sees %+v", mine)
}
})
}
func TestAddingAtTheEndAndInTheMiddleKeepsTheOrderWithoutGaps(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
p := e.create(e.alice, "P")
got, err := e.add(e.alice, p.ID, -1, "a", "b", "a")
if err != nil || got.TrackCount != 3 || got.DurationMs != 180000 {
t.Fatalf("playlist = %+v err %v", got, err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"a", "b", "a"}) {
t.Fatalf("order = %v: a track can be there twice", o)
}
if ids := e.itemIDs(p.ID); ids[0] == ids[2] {
t.Error("the same track twice must be two items")
}
if _, err := e.add(e.alice, p.ID, 1, "c", "d"); err != nil {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"a", "c", "d", "b", "a"}) {
t.Errorf("order = %v, want c and d at 1 and 2", o)
}
if _, err := e.add(e.alice, p.ID, 0, "d"); err != nil {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"d", "a", "c", "d", "b", "a"}) {
t.Errorf("order = %v, want d first", o)
}
if _, err := e.add(e.alice, p.ID, 6, "b"); err != nil { // the end, as a position
t.Errorf("a position at the end: %v", err)
}
if _, err := e.add(e.alice, p.ID, 8, "b"); !errors.Is(err, playlists.ErrPosition) {
t.Errorf("a position beyond the end: err = %v, want ErrPosition", err)
}
})
}
func TestAddingAnUnknownTrackOrToAnotherUsersPlaylistChangesNothing(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.repo.AddTracks(ctx, e.alice, p.ID, []int64{e.tracks["a"], 99999}, nil, e.tick()); !errors.Is(err, playlists.ErrTrackNotFound) {
t.Errorf("unknown track: err = %v", err)
}
if o := e.order(e.alice, p.ID); len(o) != 0 {
t.Errorf("order = %v: nothing must be added when one track is unknown", o)
}
if _, err := e.add(e.bob, p.ID, -1, "a"); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user's playlist: err = %v", err)
}
if _, err := e.add(e.alice, 99999, -1, "a"); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("unknown playlist: err = %v", err)
}
})
}
func TestRemovingAnItemClosesTheGap(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
other := e.create(e.alice, "Other")
if _, err := e.add(e.alice, p.ID, -1, "a", "b", "c", "d"); err != nil {
t.Fatal(err)
}
if _, err := e.add(e.alice, other.ID, -1, "a"); err != nil {
t.Fatal(err)
}
ids := e.itemIDs(p.ID)
if err := e.repo.RemoveItem(ctx, e.alice, p.ID, ids[1], e.tick()); err != nil {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"a", "c", "d"}) {
t.Errorf("order = %v", o)
}
if err := e.repo.RemoveItem(ctx, e.alice, p.ID, ids[1], e.tick()); !errors.Is(err, playlists.ErrItemNotFound) {
t.Errorf("a second time: err = %v", err)
}
if err := e.repo.RemoveItem(ctx, e.alice, other.ID, ids[0], e.tick()); !errors.Is(err, playlists.ErrItemNotFound) {
t.Errorf("an item of another playlist: err = %v", err)
}
if err := e.repo.RemoveItem(ctx, e.bob, p.ID, ids[0], e.tick()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user: err = %v", err)
}
if got, _ := e.repo.Get(ctx, e.alice, p.ID); got.TrackCount != 3 || got.DurationMs != 180000 {
t.Errorf("after removing: %+v", got)
}
})
}
func TestMovingAnItem(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.add(e.alice, p.ID, -1, "a", "b", "c", "d"); err != nil {
t.Fatal(err)
}
move := func(from, to int) error {
return e.repo.MoveItem(ctx, e.alice, p.ID, e.itemIDs(p.ID)[from], to, e.tick())
}
for _, step := range []struct {
from, to int
want []string
}{
{0, 2, []string{"b", "c", "a", "d"}},
{3, 0, []string{"d", "b", "c", "a"}},
{1, 1, []string{"d", "b", "c", "a"}},
{2, 3, []string{"d", "b", "a", "c"}},
{3, 2, []string{"d", "b", "c", "a"}},
{0, 3, []string{"b", "c", "a", "d"}},
} {
if err := move(step.from, step.to); err != nil {
t.Fatalf("move %d to %d: %v", step.from, step.to, err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, step.want) {
t.Fatalf("after %d to %d: order = %v, want %v", step.from, step.to, o, step.want)
}
}
if err := move(0, 4); !errors.Is(err, playlists.ErrPosition) {
t.Errorf("beyond the end: err = %v", err)
}
if err := e.repo.MoveItem(ctx, e.alice, p.ID, 99999, 0, e.tick()); !errors.Is(err, playlists.ErrItemNotFound) {
t.Errorf("unknown item: err = %v", err)
}
if err := e.repo.MoveItem(ctx, e.bob, p.ID, e.itemIDs(p.ID)[0], 0, e.tick()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user: err = %v", err)
}
})
}
func TestATrackWithoutFilesStaysAndIsListedAsNotAvailable(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.add(e.alice, p.ID, -1, "a", "b"); err != nil {
t.Fatal(err)
}
if _, err := e.db.ExecContext(ctx, "UPDATE audio_files SET missing_at = ? WHERE track_id = ?", 1_700_000_100, e.tracks["a"]); err != nil {
t.Fatal(err)
}
items, total, err := e.repo.Items(ctx, e.alice, p.ID, 10, 0)
if err != nil || total != 2 || len(items) != 2 {
t.Fatalf("items = %+v total %d err %v: the track must stay", items, total, err)
}
if items[0].Available || items[0].Track.Title != "a" || items[0].Track.Album == nil || len(items[0].Track.Artists) != 1 {
t.Errorf("the missing one = %+v", items[0])
}
if !items[1].Available || items[1].Track.Format != "flac" {
t.Errorf("the other = %+v", items[1])
}
if got, _ := e.repo.Get(ctx, e.alice, p.ID); got.TrackCount != 2 {
t.Errorf("track count = %d, want both", got.TrackCount)
}
})
}
func TestItemsArePaged(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.add(e.alice, p.ID, -1, "a", "b", "c", "d"); err != nil {
t.Fatal(err)
}
items, total, err := e.repo.Items(ctx, e.alice, p.ID, 2, 1)
if err != nil || total != 4 || len(items) != 2 || items[0].Track.Title != "b" || items[1].Position != 2 {
t.Errorf("page = %+v total %d err %v", items, total, err)
}
if items, total, _ := e.repo.Items(ctx, e.alice, p.ID, 2, 10); len(items) != 0 || total != 4 {
t.Errorf("beyond the end = %+v total %d", items, total)
}
if _, _, err := e.repo.Items(ctx, e.bob, p.ID, 2, 0); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user: err = %v", err)
}
})
}
func TestUpdatingAndDeletingAPlaylist(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p, err := e.repo.Create(ctx, e.alice, "Old", "about it", e.tick())
if err != nil {
t.Fatal(err)
}
if _, err := e.add(e.alice, p.ID, -1, "a", "b"); err != nil {
t.Fatal(err)
}
name, empty := "New", ""
got, err := e.repo.Update(ctx, e.alice, p.ID, &name, nil, e.tick())
if err != nil || got.Name != "New" || got.Description != "about it" || got.TrackCount != 2 {
t.Errorf("name only: %+v err %v", got, err)
}
got, err = e.repo.Update(ctx, e.alice, p.ID, nil, &empty, e.tick())
if err != nil || got.Name != "New" || got.Description != "" {
t.Errorf("description only: %+v err %v", got, err)
}
if _, err := e.repo.Update(ctx, e.bob, p.ID, &name, nil, e.tick()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user updates: err = %v", err)
}
if err := e.repo.Delete(ctx, e.bob, p.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user deletes: err = %v", err)
}
if err := e.repo.Delete(ctx, e.alice, p.ID); err != nil {
t.Fatal(err)
}
if err := e.repo.Delete(ctx, e.alice, p.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("a second time: err = %v", err)
}
if n := count(t, e.db, "SELECT COUNT(*) FROM playlist_items"); n != 0 {
t.Errorf("%d items left", n)
}
if n := count(t, e.db, "SELECT COUNT(*) FROM tracks"); n != 4 {
t.Errorf("%d tracks left, want all 4", n)
}
})
}
func TestDeletingAUserDeletesTheirPlaylists(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
p := e.create(e.alice, "P")
keep := e.create(e.bob, "Keep")
if _, err := e.add(e.alice, p.ID, -1, "a"); err != nil {
t.Fatal(err)
}
if err := NewUserRepo(e.db).DeleteUser(context.Background(), e.alice); err != nil {
t.Fatal(err)
}
if n := count(t, e.db, "SELECT COUNT(*) FROM playlists"); n != 1 {
t.Errorf("%d playlists, want only bob's", n)
}
if _, err := e.repo.Get(context.Background(), e.bob, keep.ID); err != nil {
t.Errorf("bob's: %v", err)
}
})
}
func TestThereAreLimitsOnPlaylistsAndOnTheirSize(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "Big")
// Fill the playlist up to the limit with a direct insert, 1,000 rows at a time.
for start := 0; start < playlists.MaxItems; start += 1000 {
rows := make([]playlistItemRow, 0, 1000)
for i := start; i < start+1000; i++ {
rows = append(rows, playlistItemRow{PlaylistID: p.ID, TrackID: e.tracks["a"], Position: i, AddedAt: 1})
}
if _, err := e.db.NewInsert().Model(&rows).Exec(ctx); err != nil {
t.Fatal(err)
}
}
if _, err := e.add(e.alice, p.ID, -1, "b"); !errors.Is(err, playlists.ErrTooMany) {
t.Errorf("one more than %d: err = %v, want ErrTooMany", playlists.MaxItems, err)
}
if got, _ := e.repo.Get(ctx, e.alice, p.ID); got.TrackCount != playlists.MaxItems {
t.Errorf("track count = %d", got.TrackCount)
}
for i := 1; i < playlists.MaxPlaylists; i++ {
if _, err := e.repo.Create(ctx, e.alice, "x", "", e.tick()); err != nil {
t.Fatalf("playlist %d: %v", i+1, err)
}
}
if _, err := e.repo.Create(ctx, e.alice, "one more", "", e.tick()); !errors.Is(err, playlists.ErrTooMany) {
t.Errorf("one more than %d playlists: err = %v", playlists.MaxPlaylists, err)
}
if _, err := e.repo.Create(ctx, e.bob, "bobs", "", e.tick()); err != nil {
t.Errorf("the limit is per user: %v", err)
}
})
}
func TestAddingAtTheSameTimeKeepsEveryPositionUnique(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
var wg sync.WaitGroup
errs := make(chan error, 8)
for g := 0; g < 8; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 3; i++ {
if _, err := e.repo.AddTracks(ctx, e.alice, p.ID, []int64{e.tracks["a"], e.tracks["b"]}, nil, time.Now()); err != nil {
errs <- err
return
}
}
}()
}
wg.Wait()
close(errs)
for err := range errs {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); len(o) != 48 {
t.Errorf("%d items, want 48", len(o))
}
})
}

View file

@ -156,8 +156,8 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) {
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil {
t.Fatal(err)
}
if applied != 18 {
t.Errorf("applied migrations = %d, want 18", applied)
if applied != 19 {
t.Errorf("applied migrations = %d, want 19", applied)
}
})
}

View file

@ -0,0 +1,24 @@
-- Playlists: named, ordered lists of tracks that belong to one user. PostgreSQL flavour of
-- sqlite/0019_playlists.sql.
CREATE TABLE playlists (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
created_at BIGINT NOT NULL, -- unix seconds
updated_at BIGINT NOT NULL
);
CREATE INDEX idx_playlists_user ON playlists(user_id, updated_at);
CREATE TABLE playlist_items (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
playlist_id BIGINT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
track_id BIGINT NOT NULL REFERENCES tracks(id) ON DELETE CASCADE,
position INTEGER NOT NULL CHECK (position >= 0),
added_at BIGINT NOT NULL
);
CREATE INDEX idx_playlist_items_order ON playlist_items(playlist_id, position);
CREATE INDEX idx_playlist_items_track ON playlist_items(track_id);

View file

@ -0,0 +1,27 @@
-- Playlists: named, ordered lists of tracks that belong to one user.
--
-- position is the place of an item in its playlist, counted from 0 without gaps; the code keeps it
-- that way inside a transaction (it is not unique, so a shift never trips over itself). A track
-- can be in a playlist more than once, which is why an item has its own id.
CREATE TABLE playlists (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL, -- unix seconds
updated_at INTEGER NOT NULL
);
CREATE INDEX idx_playlists_user ON playlists(user_id, updated_at);
CREATE TABLE playlist_items (
id INTEGER PRIMARY KEY,
playlist_id INTEGER NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
track_id INTEGER NOT NULL REFERENCES tracks(id) ON DELETE CASCADE,
position INTEGER NOT NULL CHECK (position >= 0),
added_at INTEGER NOT NULL
);
CREATE INDEX idx_playlist_items_order ON playlist_items(playlist_id, position);
CREATE INDEX idx_playlist_items_track ON playlist_items(track_id);

View file

@ -705,6 +705,122 @@ export interface paths {
patch?: never;
trace?: never;
};
"/playlists": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Your playlists
* @description The playlists you made, the one changed last first. Only yours: nobody else's are ever
* listed.
*/
get: operations["listPlaylists"];
put?: never;
/**
* Make a playlist
* @description Makes an empty playlist. A user can have 1000. Names can repeat.
*/
post: operations["createPlaylist"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/playlists/{id}": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
/**
* A playlist
* @description Its name, description, how many tracks it has and how long they are. The tracks come from
* `GET /playlists/{id}/tracks`. A playlist of somebody else answers `playlist_not_found`.
*/
get: operations["getPlaylist"];
put?: never;
post?: never;
/**
* Delete a playlist
* @description Deletes the playlist and its list of tracks. The tracks themselves stay in the library.
*/
delete: operations["deletePlaylist"];
options?: never;
head?: never;
/**
* Rename a playlist or change its description
* @description Changes what is given. An empty description clears it; a name cannot be empty.
*/
patch: operations["updatePlaylist"];
trace?: never;
};
"/playlists/{id}/tracks": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
/**
* The tracks of a playlist
* @description The items in order, each with its own `id` (a track can be in a playlist more than once),
* its `position` (counted from 0, without gaps) and the track. A track whose files were
* deleted or moved away stays in the playlist with `available` false: it is not lost, and
* it plays again when the files are back and a scan has found them.
*/
get: operations["listPlaylistTracks"];
put?: never;
/**
* Add tracks to a playlist
* @description Puts 1 to 500 tracks, in the order given, at `position` (the tracks from there on move
* down) or at the end when it is absent. A track can be added again. If one id is not a
* track nothing is added. A playlist holds up to 10000 tracks.
*/
post: operations["addPlaylistTracks"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/playlists/{id}/tracks/{item}": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
/** @description The `id` of the item, not of the track. */
item: number;
};
cookie?: never;
};
get?: never;
put?: never;
post?: never;
/**
* Take a track out of a playlist
* @description Removes that one item; the ones after it move up by one.
*/
delete: operations["removePlaylistItem"];
options?: never;
head?: never;
/**
* Move a track inside a playlist
* @description Puts the item at `position`, from 0 to the number of items less one; the ones in between
* shift by one.
*/
patch: operations["movePlaylistItem"];
trace?: never;
};
"/wishlist": {
parameters: {
query?: never;
@ -1776,6 +1892,72 @@ export interface components {
seeds: components["schemas"]["DiscoverSeed"][];
items: components["schemas"]["Suggestion"][];
};
Playlist: {
/** Format: int64 */
id: number;
name: string;
description: string;
/** @description Items in the playlist, available or not. */
track_count: number;
/**
* Format: int64
* @description Their total length.
*/
duration_ms: number;
/** Format: date-time */
created_at: string;
/**
* Format: date-time
* @description When it was last changed, tracks included.
*/
updated_at: string;
};
PlaylistPage: {
items: components["schemas"]["Playlist"][];
/** @description Size of the whole list, not of this page. */
total: number;
limit: number;
offset: number;
};
PlaylistItem: {
/**
* Format: int64
* @description Identifies this place of the playlist; the track may be there twice.
*/
id: number;
position: number;
/** @description False when the track has no file to play now. */
available: boolean;
/** Format: date-time */
added_at: string;
track: components["schemas"]["Track"];
};
PlaylistItemPage: {
items: components["schemas"]["PlaylistItem"][];
/** @description Items in the whole playlist. */
total: number;
limit: number;
offset: number;
};
CreatePlaylist: {
/** @description Trimmed. */
name: string;
description?: string;
};
/** @description At least one of the two. */
UpdatePlaylist: {
name?: string;
/** @description An empty one clears it. */
description?: string;
};
AddPlaylistTracks: {
track_ids: number[];
/** @description Where the first one goes, up to the number of items; absent means the end. */
position?: number;
};
MovePlaylistItem: {
position: number;
};
MarkedPage: {
items: components["schemas"]["MarkedArtist"][];
/** @description Size of the whole list, not of this page. */
@ -1960,6 +2142,24 @@ export interface components {
"application/json": components["schemas"]["Error"];
};
};
/** @description No such playlist, or it is somebody else's (`playlist_not_found`). */
PlaylistNotFound: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description A limit was reached, 1000 playlists for a user or 10000 tracks in a playlist (`limit_reached`). */
PlaylistLimit: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description No such library (`library_not_found`). */
LibraryNotFound: {
headers: {
@ -3186,6 +3386,290 @@ export interface operations {
};
};
};
listPlaylists: {
parameters: {
query?: {
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
limit?: components["parameters"]["Limit"];
offset?: components["parameters"]["Offset"];
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description A page of playlists. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PlaylistPage"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
};
};
createPlaylist: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["CreatePlaylist"];
};
};
responses: {
/** @description The playlist. */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Playlist"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
409: components["responses"]["PlaylistLimit"];
};
};
getPlaylist: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The playlist. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Playlist"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
404: components["responses"]["PlaylistNotFound"];
};
};
deletePlaylist: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Deleted. */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
404: components["responses"]["PlaylistNotFound"];
};
};
updatePlaylist: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["UpdatePlaylist"];
};
};
responses: {
/** @description The playlist as it is now. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Playlist"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
404: components["responses"]["PlaylistNotFound"];
};
};
listPlaylistTracks: {
parameters: {
query?: {
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
limit?: components["parameters"]["Limit"];
offset?: components["parameters"]["Offset"];
};
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description A page of items. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PlaylistItemPage"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
404: components["responses"]["PlaylistNotFound"];
};
};
addPlaylistTracks: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["AddPlaylistTracks"];
};
};
responses: {
/** @description The playlist as it is now. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Playlist"];
};
};
/** @description The request is malformed, or `position` is beyond the end (`invalid_position`). */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
401: components["responses"]["Unauthorized"];
404: components["responses"]["PlaylistNotFound"];
409: components["responses"]["PlaylistLimit"];
/** @description One of the tracks does not exist (`track_not_found`). */
422: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
removePlaylistItem: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
/** @description The `id` of the item, not of the track. */
item: number;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Removed. */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
/** @description No such playlist (`playlist_not_found`) or no such item in it (`item_not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
movePlaylistItem: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
/** @description The `id` of the item, not of the track. */
item: number;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["MovePlaylistItem"];
};
};
responses: {
/** @description Moved. */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
/** @description The request is malformed, or `position` is beyond the end (`invalid_position`). */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
401: components["responses"]["Unauthorized"];
/** @description No such playlist (`playlist_not_found`) or no such item in it (`item_not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
listWishlist: {
parameters: {
query?: {