diff --git a/internal/api/playlists.go b/internal/api/playlists.go index 9225b33f..01a970c4 100644 --- a/internal/api/playlists.go +++ b/internal/api/playlists.go @@ -4,7 +4,9 @@ import ( "context" "errors" "fmt" + "io/fs" "net/http" + "os" "path/filepath" "strconv" "strings" @@ -452,6 +454,17 @@ func (h *handlers) handleGetPlaylistCover(w http.ResponseWriter, r *http.Request return } full := filepath.Join(h.dataDir, *detail.CoverPath) + if _, err := os.Stat(full); errors.Is(err, fs.ErrNotExist) { + // The row names a collage the data directory no longer holds (it + // was lost or moved without the database). Draw it again rather + // than answer with a broken image. + rel, gerr := playlists.GenerateCollage(r.Context(), h.pool, playlistID, h.dataDir) + if gerr != nil || rel == "" { + writeErr(w, &apierror.Error{Status: 404, Code: "not_found", Message: "no cover"}) + return + } + full = filepath.Join(h.dataDir, rel) + } // Playlist collages recompute when the playlist's tracks change // (system playlists re-rendered on rebuild, user playlists when // modified). 5 minutes is short enough for normal edits to feel diff --git a/internal/backup/tables.go b/internal/backup/tables.go index 3afc0766..62aa83e1 100644 --- a/internal/backup/tables.go +++ b/internal/backup/tables.go @@ -70,7 +70,9 @@ var Tables = []Table{ // Playlists and what is built from history. The taste profile and the // "you might like" rows are rebuilt nightly from the history above; they // travel so a restored Home is full before that first nightly pass. - {Name: "playlists"}, + // A collage is a file in the data directory, which the backup doesn't + // carry; the restored server draws each one again. + {Name: "playlists", Omit: []string{"cover_path"}}, {Name: "playlist_tracks"}, {Name: "system_playlist_runs"}, {Name: "system_playlist_rotation_state"}, diff --git a/internal/db/dbq/playlists.sql.go b/internal/db/dbq/playlists.sql.go index 3f6d6e6d..8a67c78a 100644 --- a/internal/db/dbq/playlists.sql.go +++ b/internal/db/dbq/playlists.sql.go @@ -488,6 +488,31 @@ func (q *Queries) ListPlaylistsForUser(ctx context.Context, userID pgtype.UUID) return items, nil } +const listUserPlaylistIDsForOwner = `-- name: ListUserPlaylistIDsForOwner :many +SELECT id FROM playlists WHERE user_id = $1 AND kind = 'user' ORDER BY id +` + +// The playlists a person made, not their system mixes. +func (q *Queries) ListUserPlaylistIDsForOwner(ctx context.Context, userID pgtype.UUID) ([]pgtype.UUID, error) { + rows, err := q.db.Query(ctx, listUserPlaylistIDsForOwner, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []pgtype.UUID + for rows.Next() { + var id pgtype.UUID + if err := rows.Scan(&id); err != nil { + return nil, err + } + items = append(items, id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const renumberPlaylistTracksAfter = `-- name: RenumberPlaylistTracksAfter :exec UPDATE playlist_tracks SET position = position - 1 @@ -506,7 +531,8 @@ func (q *Queries) RenumberPlaylistTracksAfter(ctx context.Context, arg RenumberP } const setPlaylistCover = `-- name: SetPlaylistCover :exec -UPDATE playlists SET cover_path = $2, updated_at = now() WHERE id = $1 +UPDATE playlists SET cover_path = $2, updated_at = now() + WHERE id = $1 AND cover_path IS DISTINCT FROM $2 ` type SetPlaylistCoverParams struct { @@ -514,6 +540,8 @@ type SetPlaylistCoverParams struct { CoverPath *string } +// Only a changed path counts as a change to the playlist: a collage drawn +// again to the same file leaves updated_at alone. func (q *Queries) SetPlaylistCover(ctx context.Context, arg SetPlaylistCoverParams) error { _, err := q.db.Exec(ctx, setPlaylistCover, arg.ID, arg.CoverPath) return err diff --git a/internal/db/queries/playlists.sql b/internal/db/queries/playlists.sql index 92527b7d..36cbf4cf 100644 --- a/internal/db/queries/playlists.sql +++ b/internal/db/queries/playlists.sql @@ -46,7 +46,14 @@ SET WHERE id = $1; -- name: SetPlaylistCover :exec -UPDATE playlists SET cover_path = $2, updated_at = now() WHERE id = $1; +-- Only a changed path counts as a change to the playlist: a collage drawn +-- again to the same file leaves updated_at alone. +UPDATE playlists SET cover_path = $2, updated_at = now() + WHERE id = $1 AND cover_path IS DISTINCT FROM $2; + +-- name: ListUserPlaylistIDsForOwner :many +-- The playlists a person made, not their system mixes. +SELECT id FROM playlists WHERE user_id = $1 AND kind = 'user' ORDER BY id; -- name: DeletePlaylist :one -- Returns cover_path so the caller can clean up the cached collage on disk. diff --git a/internal/playlists/collage.go b/internal/playlists/collage.go index b035de63..040cec0f 100644 --- a/internal/playlists/collage.go +++ b/internal/playlists/collage.go @@ -7,6 +7,7 @@ import ( "image/color" "image/draw" "image/jpeg" + "log/slog" "os" "path/filepath" "strings" @@ -239,3 +240,25 @@ func pgtypeUUIDStringForCollage(u pgtype.UUID) string { b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]) } + +// RedrawUserPlaylistCollages draws the collage of each playlist userID made +// again, from its albums' covers as they are now. The nightly rebuild calls +// it. A collage is otherwise drawn only when a playlist's songs change, so +// without this one drawn before its albums had covers (after a restore, or +// on a library still fetching art) would keep its placeholder cells for good. +// A failure on one playlist is logged and the rest are still drawn. +func RedrawUserPlaylistCollages(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, userID pgtype.UUID, dataDir string) { + if dataDir == "" { + return + } + ids, err := dbq.New(pool).ListUserPlaylistIDsForOwner(ctx, userID) + if err != nil { + logger.Warn("playlists: list for collage redraw failed", "user_id", pgtypeUUIDStringForCollage(userID), "err", err) + return + } + for _, id := range ids { + if _, err := GenerateCollage(ctx, pool, id, dataDir); err != nil { + logger.Warn("playlists: collage redraw failed", "playlist_id", pgtypeUUIDStringForCollage(id), "err", err) + } + } +} diff --git a/internal/playlists/collage_test.go b/internal/playlists/collage_test.go index 4fccbac2..80d27c8b 100644 --- a/internal/playlists/collage_test.go +++ b/internal/playlists/collage_test.go @@ -4,6 +4,8 @@ import ( "context" "image" _ "image/jpeg" + "io" + "log/slog" "os" "path/filepath" "testing" @@ -74,3 +76,41 @@ func TestGenerateCollage_OneTrack(t *testing.T) { t.Errorf("dimensions = %dx%d, want 600x600", img.Bounds().Dx(), img.Bounds().Dy()) } } + +// The nightly redraw draws a collage for a playlist that has none, as after +// a restore (which leaves cover_path out and carries no collage files). +func TestRedrawUserPlaylistCollages_DrawsAMissingCollage(t *testing.T) { + pool := dbtest.Pool(t) + ctx := context.Background() + user := seedUser(t, pool, "alice") + tk := seedTrack(t, pool, "Prismatic", "FoO") + dir := t.TempDir() + svc := playlists.NewService(pool, nil, dir) + pl, err := svc.Create(ctx, user.ID, "Restored", "", false) + if err != nil { + t.Fatalf("Create: %v", err) + } + if err := svc.AppendTracks(ctx, user.ID, pl.ID, []pgtype.UUID{tk.ID}); err != nil { + t.Fatalf("AppendTracks: %v", err) + } + // As a restore leaves it: no cover_path, and no file. + if _, err := pool.Exec(ctx, `UPDATE playlists SET cover_path = NULL WHERE id = $1`, pl.ID); err != nil { + t.Fatalf("clear cover_path: %v", err) + } + if err := os.RemoveAll(filepath.Join(dir, "playlist_covers")); err != nil { + t.Fatalf("remove covers: %v", err) + } + + playlists.RedrawUserPlaylistCollages(ctx, pool, slog.New(slog.NewTextHandler(io.Discard, nil)), user.ID, dir) + + got, err := svc.Get(ctx, user.ID, pl.ID) + if err != nil { + t.Fatalf("Get: %v", err) + } + if got.CoverPath == nil || *got.CoverPath == "" { + t.Fatal("no collage after the redraw") + } + if _, err := os.Stat(filepath.Join(dir, *got.CoverPath)); err != nil { + t.Fatalf("collage file: %v", err) + } +} diff --git a/internal/playlists/scheduler.go b/internal/playlists/scheduler.go index 70b1057c..2db54ce9 100644 --- a/internal/playlists/scheduler.go +++ b/internal/playlists/scheduler.go @@ -241,6 +241,7 @@ func (s *Scheduler) rebuildUserDaily(ctx context.Context, userID pgtype.UUID, no s.logger.Warn("scheduler: taste profile rebuild failed", "user_id", uuidStringPL(userID), "err", err) } + RedrawUserPlaylistCollages(ctx, s.pool, s.logger, userID, s.dataDir) if err := BuildSystemPlaylists(ctx, s.pool, s.logger, userID, now, s.dataDir); err != nil { s.logger.Warn("scheduler: build failed", "user_id", uuidStringPL(userID), "err", err)