feat(library): Missing files says why each track waits, and can forget or export it
release / go (push) Successful in 1m49s
release / web (push) Successful in 1m26s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m29s
release / android (push) Successful in 4m43s
release / Build signed APK (push) Successful in 5m1s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped

- The missing list carries each track's disc and track number, its
  recording and release-group MBIDs, the Collection queue its file was
  removed from, and the admin who removed it.
- POST /api/admin/library/missing/forget deletes waiting tracks for good,
  tidying away an album or artist they leave empty, and writes a
  track_forget audit row naming each. It is all or nothing: a track that
  has its file again is refused with 409 track_has_file.
- GET /api/admin/library/missing.csv exports every waiting track (artist,
  album, disc, track, title, MBIDs, why, since) to hand to whatever finds
  music.
- DELETE /api/admin/tracks/{id} is retired. No client called it; its
  service becomes tracks.Service.ForgetTracks.

Grimoire #7744 (milestone 635).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 18:34:01 -05:00
co-authored by Claude Opus 5.5
parent 9462052625
commit 492eb2fb9a
16 changed files with 621 additions and 558 deletions
+164 -26
View File
@@ -1,29 +1,49 @@
package api
import (
"encoding/csv"
"encoding/json"
"errors"
"net/http"
"strconv"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
"git.fabledsword.com/bvandeusen/minstrel/internal/tracks"
)
// missingTrackView is one track whose file the scan could not find.
// missingTrackView is one track waiting for a file: removed by an admin from
// a Collection queue, or gone from disk.
//
// The text fields come from the tracks row, not from the filesystem, which is
// the point: the recording is still a known thing with a title, an artist and
// a play history — only its bytes are absent. LastPlayedAt is nullable because
// plenty of missing files were never played, and that is exactly the signal an
// operator wants when deciding whether a lost file is worth replacing.
//
// RemovedFor is the queue the file was removed from ("report", "duplicate",
// "suspect"), or null when the scan found it gone; RemovedBy is the admin who
// removed it, null for the duplicate resolver. The MBIDs let an export be
// matched exactly by whatever finds the good copy.
type missingTrackView struct {
TrackID string `json:"track_id"`
Title string `json:"title"`
ArtistID string `json:"artist_id"`
ArtistName string `json:"artist_name"`
AlbumID string `json:"album_id"`
AlbumTitle string `json:"album_title"`
FilePath string `json:"file_path"`
DurationSec int32 `json:"duration_sec"`
MissingSince string `json:"missing_since"`
LastPlayedAt *string `json:"last_played_at"`
TrackID string `json:"track_id"`
Title string `json:"title"`
ArtistID string `json:"artist_id"`
ArtistName string `json:"artist_name"`
AlbumID string `json:"album_id"`
AlbumTitle string `json:"album_title"`
FilePath string `json:"file_path"`
DurationSec int32 `json:"duration_sec"`
DiscNumber *int32 `json:"disc_number"`
TrackNumber *int32 `json:"track_number"`
RecordingMBID *string `json:"recording_mbid"`
ReleaseGroupMBID *string `json:"release_group_mbid"`
RemovedFor *string `json:"removed_for"`
RemovedBy *string `json:"removed_by"`
MissingSince string `json:"missing_since"`
LastPlayedAt *string `json:"last_played_at"`
}
// missingGroupView is a directory's worth of missing tracks.
@@ -49,12 +69,11 @@ type adminMissingResponse struct {
Groups []missingGroupView `json:"groups"`
}
// handleListMissingTracks implements GET /api/admin/library/missing.
//
// Read-only by design. Nothing on this surface deletes a track: a missing file
// keeps its row, its history and its likes because it may come back, and if it
// comes back renamed the scanner adopts it. The surface exists so an admin
// can SEE what the library has lost and act on it deliberately.
// handleListMissingTracks implements GET /api/admin/library/missing: the
// tracks waiting for a file. A waiting track keeps its row, its history and
// its likes because a file may come back, and a good copy that lands in the
// library is adopted or folded into it. Forgetting one is a separate,
// deliberate call (handleForgetMissingTracks).
func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Request) {
limit, offset, err := parsePaging(r.URL.Query())
if err != nil {
@@ -102,15 +121,21 @@ func groupMissingByDirectory(rows []dbq.ListMissingTracksRow) []missingGroupView
groups := make([]missingGroupView, 0, 8)
for _, row := range rows {
t := missingTrackView{
TrackID: uuidToString(row.ID),
Title: row.Title,
ArtistID: uuidToString(row.ArtistID),
ArtistName: row.ArtistName,
AlbumID: uuidToString(row.AlbumID),
AlbumTitle: row.AlbumTitle,
FilePath: row.FilePath,
DurationSec: row.DurationMs / 1000,
MissingSince: formatTimestamp(row.MissingSince),
TrackID: uuidToString(row.ID),
Title: row.Title,
ArtistID: uuidToString(row.ArtistID),
ArtistName: row.ArtistName,
AlbumID: uuidToString(row.AlbumID),
AlbumTitle: row.AlbumTitle,
FilePath: row.FilePath,
DurationSec: row.DurationMs / 1000,
DiscNumber: row.DiscNumber,
TrackNumber: row.TrackNumber,
RecordingMBID: row.Mbid,
ReleaseGroupMBID: row.ReleaseGroupMbid,
RemovedFor: row.RemovedReason,
RemovedBy: row.RemovedByName,
MissingSince: formatTimestamp(row.MissingSince),
}
if row.LastPlayedAt.Valid {
s := formatTimestamp(row.LastPlayedAt)
@@ -134,3 +159,116 @@ func groupMissingByDirectory(rows []dbq.ListMissingTracksRow) []missingGroupView
}
return groups
}
// forgetMissingRequest is the body of POST /api/admin/library/missing/forget:
// the waiting tracks to forget, one track or a whole folder's.
type forgetMissingRequest struct {
TrackIDs []string `json:"track_ids"`
}
// forgetMissingRequestLimit caps the body: a folder of a few hundred ids is
// a few tens of KB.
const forgetMissingRequestLimit = 1 << 20
// handleForgetMissingTracks implements POST
// /api/admin/library/missing/forget: the tracks go for good, with their
// likes, plays and playlist places, and an album or artist they leave empty
// goes too. It is all or nothing.
//
// Errors: 400 invalid_body / invalid_id; 404 track_not_found when an id is
// unknown; 409 track_has_file when one has its file again, since forgetting
// it would throw away music the library holds.
func (h *handlers) handleForgetMissingTracks(w http.ResponseWriter, r *http.Request) {
admin, ok := requireUser(w, r)
if !ok {
return
}
var body forgetMissingRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, forgetMissingRequestLimit)).Decode(&body); err != nil || len(body.TrackIDs) == 0 {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body")
return
}
ids := make([]pgtype.UUID, 0, len(body.TrackIDs))
for _, raw := range body.TrackIDs {
id, ok := parseUUID(raw)
if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
return
}
ids = append(ids, id)
}
gone, err := h.tracks.ForgetTracks(r.Context(), ids, admin.ID)
switch {
case errors.Is(err, tracks.ErrNotFound):
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found")
return
case errors.Is(err, library.ErrTrackPresent):
writeAdminJSONErr(w, http.StatusConflict, "track_has_file")
return
case err != nil:
h.logger.Error("admin: forget missing tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
return
}
writeJSON(w, http.StatusOK, map[string]int{"forgotten": len(gone)})
}
// missingCSVHeader is the export's columns. They name the song for whatever
// finds the good copy: the MBIDs match it exactly where the tags carried
// them, and the names do the rest.
var missingCSVHeader = []string{
"artist", "album", "disc", "track", "title",
"recording_mbid", "release_group_mbid", "why", "since",
}
// handleExportMissingTracks implements GET /api/admin/library/missing.csv:
// every track waiting for a file, in the list's folder order, as a CSV to
// hand to whatever finds music. "why" is the queue the file was removed from,
// or "missing" when the scan found it gone.
func (h *handlers) handleExportMissingTracks(w http.ResponseWriter, r *http.Request) {
q := dbq.New(h.pool)
total, err := q.CountMissingTracks(r.Context())
if err != nil {
h.logger.Error("admin: count missing tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
return
}
rows, err := q.ListMissingTracks(r.Context(), dbq.ListMissingTracksParams{PageLimit: int32(total), PageOffset: 0})
if err != nil {
h.logger.Error("admin: list missing tracks", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
return
}
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Header().Set("Content-Disposition", `attachment; filename="needs-a-file.csv"`)
out := csv.NewWriter(w)
_ = out.Write(missingCSVHeader)
for _, row := range rows {
why := "missing"
if row.RemovedReason != nil {
why = *row.RemovedReason
}
_ = out.Write([]string{
row.ArtistName, row.AlbumTitle, optInt(row.DiscNumber), optInt(row.TrackNumber), row.Title,
optString(row.Mbid), optString(row.ReleaseGroupMbid), why, formatTimestamp(row.MissingSince),
})
}
out.Flush()
if err := out.Error(); err != nil {
h.logger.Warn("admin: write missing-tracks csv", "err", err)
}
}
func optInt(v *int32) string {
if v == nil {
return ""
}
return strconv.Itoa(int(*v))
}
func optString(v *string) string {
if v == nil {
return ""
}
return *v
}
@@ -0,0 +1,108 @@
package api
import (
"bytes"
"context"
"encoding/csv"
"net/http"
"net/http/httptest"
"testing"
)
// The export names every waiting track and why it waits, with an empty cell
// for an MBID or a position the tags never carried.
func TestHandleExportMissingTracks_Integration(t *testing.T) {
h, pool := testHandlers(t)
truncateLibrary(t, pool)
admin := seedUser(t, pool, "export-admin", "pw", true)
artist := seedArtist(t, pool, "Boards of Canada")
album := seedAlbum(t, pool, artist.ID, "Geogaddi", 2002)
gone := seedTrack(t, pool, album.ID, artist.ID, "Music Is Math", 0, 300_000)
removed := seedTrack(t, pool, album.ID, artist.ID, "Dawn Chorus", 2, 240_000)
seedTrack(t, pool, album.ID, artist.ID, "Julie and Candy", 3, 200_000)
ctx := context.Background()
if _, err := pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE id = $1`, gone.ID); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `UPDATE tracks SET missing_since = now(), removed_reason = 'report', removed_by = $2,
mbid = 'rec-dawn', mbid_source = 'tag' WHERE id = $1`, removed.ID, admin.ID); err != nil {
t.Fatal(err)
}
req := withUser(httptest.NewRequest(http.MethodGet, "/api/admin/library/missing.csv", nil), admin)
w := httptest.NewRecorder()
h.handleExportMissingTracks(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
rows, err := csv.NewReader(bytes.NewReader(w.Body.Bytes())).ReadAll()
if err != nil {
t.Fatalf("parse csv: %v", err)
}
if len(rows) != 3 {
t.Fatalf("rows = %v, want a header and the two waiting tracks", rows)
}
byTitle := map[string][]string{}
for _, r := range rows[1:] {
byTitle[r[4]] = r
}
if r := byTitle["Music Is Math"]; r == nil || r[3] != "" || r[5] != "" || r[7] != "missing" {
t.Errorf("untagged missing row = %v, want no track number, no mbid, why missing", r)
}
if r := byTitle["Dawn Chorus"]; r == nil || r[3] != "2" || r[5] != "rec-dawn" || r[7] != "report" {
t.Errorf("removed row = %v, want track 2, its mbid, why report", r)
}
}
// Forget deletes waiting tracks, all or nothing: a track that has its file
// is refused, and nothing in that request goes.
func TestHandleForgetMissingTracks_Integration(t *testing.T) {
h, pool := testHandlers(t)
truncateLibrary(t, pool)
admin := seedUser(t, pool, "forget-admin", "pw", true)
artist := seedArtist(t, pool, "Autechre")
album := seedAlbum(t, pool, artist.ID, "Amber", 1994)
waiting := seedTrack(t, pool, album.ID, artist.ID, "Foil", 1, 300_000)
present := seedTrack(t, pool, album.ID, artist.ID, "Montreal", 2, 300_000)
ctx := context.Background()
if _, err := pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE id = $1`, waiting.ID); err != nil {
t.Fatal(err)
}
forget := func(ids ...string) int {
body := `{"track_ids":[`
for i, id := range ids {
if i > 0 {
body += ","
}
body += `"` + id + `"`
}
body += `]}`
req := withUser(httptest.NewRequest(http.MethodPost, "/api/admin/library/missing/forget", bytes.NewBufferString(body)), admin)
w := httptest.NewRecorder()
h.handleForgetMissingTracks(w, req)
return w.Code
}
exists := func(id string) bool {
var n int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM tracks WHERE id = $1`, id).Scan(&n); err != nil {
t.Fatal(err)
}
return n == 1
}
if code := forget(uuidToString(waiting.ID), uuidToString(present.ID)); code != http.StatusConflict {
t.Fatalf("forgetting a track with its file: status %d, want 409", code)
}
if !exists(uuidToString(waiting.ID)) || !exists(uuidToString(present.ID)) {
t.Fatalf("a refused forget removed a track")
}
if code := forget(uuidToString(waiting.ID)); code != http.StatusOK {
t.Fatalf("forgetting the waiting track: status %d, want 200", code)
}
if exists(uuidToString(waiting.ID)) {
t.Errorf("the forgotten track is still there")
}
if !exists(uuidToString(present.ID)) {
t.Errorf("the album's other track went too")
}
}
-76
View File
@@ -1,76 +0,0 @@
package api
import (
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/tracks"
)
// removeTrackResponse is DELETE /api/admin/tracks/{id}'s answer. The two
// optional fields are omitted unless the corresponding cleanup actually
// happened, so the response stays minimal in the common case.
type removeTrackResponse struct {
DeletedTrackID string `json:"deleted_track_id"`
DeletedAlbumID *string `json:"deleted_album_id,omitempty"`
DeletedArtistID *string `json:"deleted_artist_id,omitempty"`
}
// handleRemoveTrack implements DELETE /api/admin/tracks/{id}.
//
// Admin-only (gated by auth.RequireAdmin on the /admin route group). Deletes
// the file, then the DB row, and runs the album/artist cascade tidy-up — and
// deletes nothing at all when the file cannot be removed.
//
// The codes this handler emits are not_found,
// library_not_writable (409) and file_delete_failed when the file could not be
// removed, server_error, plus the auth codes the middleware emits upstream.
func (h *handlers) handleRemoveTrack(w http.ResponseWriter, r *http.Request) {
idStr := chi.URLParam(r, "id")
trackID, ok := parseUUID(idStr)
if !ok {
// Malformed id is functionally equivalent to "no such track" for
// the spec's error surface — collapse both to 404 not_found so
// the client doesn't have to handle a separate bad_request branch
// for a code path that's only reachable via UI bugs.
writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "track not found"})
return
}
// Defensive: RequireUser+RequireAdmin should have run upstream. If
// we got here without a user in context the routing is broken.
admin, ok := requireUser(w, r)
if !ok {
return
}
deletedAlbum, deletedArtist, err := h.tracks.RemoveTrack(r.Context(), trackID, admin.ID)
if err != nil {
if errors.Is(err, tracks.ErrNotFound) {
writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "track not found"})
return
}
if apiErr, ok := fileRemoveAPIError(err); ok {
logFileRemoveFailure(h.logger, apiErr, "track_id", idStr)
writeErr(w, apiErr)
return
}
h.logger.Error("api: remove track failed", "err", err, "track_id", idStr)
writeErr(w, apierror.InternalMsg("remove failed", err))
return
}
resp := removeTrackResponse{DeletedTrackID: idStr}
if deletedAlbum != nil {
s := uuidToString(*deletedAlbum)
resp.DeletedAlbumID = &s
}
if deletedArtist != nil {
s := uuidToString(*deletedArtist)
resp.DeletedArtistID = &s
}
writeJSON(w, http.StatusOK, resp)
}
-214
View File
@@ -1,214 +0,0 @@
package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/go-chi/chi/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// newAdminTracksRouter builds a test chi router with the admin-tracks
// endpoint. RequireAdmin middleware is applied; tests inject the user into
// context manually (RequireUser is bypassed). Mirrors the pattern from
// admin_quarantine_test.go.
func newAdminTracksRouter(h *handlers) chi.Router {
r := chi.NewRouter()
r.Route("/api/admin", func(admin chi.Router) {
admin.Use(auth.RequireAdmin())
admin.Delete("/tracks/{id}", h.handleRemoveTrack)
})
return r
}
// doAdminTracksReq fires an HTTP request against the admin-tracks router
// with the given user in context.
func doAdminTracksReq(t *testing.T, h *handlers, method, path string, user dbq.User) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, bytes.NewBuffer(nil))
req = withUser(req, user)
w := httptest.NewRecorder()
newAdminTracksRouter(h).ServeHTTP(w, req)
return w
}
// doAdminTracksReqNoUser fires a request directly at the handler with NO
// user injected into context. Used to exercise the defensive 401 branch
// inside the handler — real traffic hits RequireUser upstream, but the
// handler defends against routing misconfigurations and we test that path
// here. We bypass the admin router entirely since RequireAdmin would
// short-circuit with 500 internal_error on missing-user-in-context (which
// is its programmer-error contract); the handler's own 401 path is what
// we want to assert.
func doAdminTracksReqNoUser(t *testing.T, h *handlers, method, path, idParam string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, bytes.NewBuffer(nil))
rctx := chi.NewRouteContext()
rctx.URLParams.Add("id", idParam)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
w := httptest.NewRecorder()
h.handleRemoveTrack(w, req)
return w
}
// seedTrackForRemoveTest creates a fresh artist+album+track on disk and
// returns the track row. The mbids are set on the track and album when
// non-empty.
func seedTrackForRemoveTest(t *testing.T, h *handlers, unique, trackMbid, albumMbid string) (dbq.Track, string) {
t.Helper()
artist := seedArtist(t, h.pool, "RemoveTest Artist "+unique)
dir := t.TempDir()
path := filepath.Join(dir, "track-"+unique+".mp3")
if err := os.WriteFile(path, []byte("audio"), 0o644); err != nil {
t.Fatalf("write file: %v", err)
}
q := dbq.New(h.pool)
var albumMbidPtr *string
if albumMbid != "" {
albumMbidPtr = &albumMbid
}
album, err := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{
Title: "RemoveTest Album " + unique,
SortTitle: "RemoveTest Album " + unique,
ArtistID: artist.ID,
Mbid: albumMbidPtr,
})
if err != nil {
t.Fatalf("UpsertAlbum: %v", err)
}
one := int32(1)
var trackMbidPtr *string
if trackMbid != "" {
trackMbidPtr = &trackMbid
}
tr, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{
Title: "RemoveTest Track " + unique,
AlbumID: album.ID,
ArtistID: artist.ID,
TrackNumber: &one,
DurationMs: 30000,
FilePath: path,
FileSize: 5,
FileFormat: "mp3",
Mbid: trackMbidPtr,
})
if err != nil {
t.Fatalf("UpsertTrack: %v", err)
}
return tr, path
}
// TestHandleRemoveTrack_NonAdmin403 verifies the RequireAdmin middleware
// rejects non-admin callers, with the shared middleware's
// {"error":"not_authorized"} envelope, which this handler doesn't own.
func TestHandleRemoveTrack_NonAdmin403(t *testing.T) {
h, pool := testHandlers(t)
truncateLibrary(t, pool)
nonAdmin := seedUser(t, pool, "regular", "pw", false)
fakeID := "00000000-0000-0000-0000-000000000001"
w := doAdminTracksReq(t, h, http.MethodDelete, "/api/admin/tracks/"+fakeID, nonAdmin)
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())
}
var resp map[string]string
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if resp["error"] != "not_authorized" {
t.Errorf("error = %q, want not_authorized", resp["error"])
}
}
// TestHandleRemoveTrack_NoSession401 exercises the defensive no-user-in-
// context branch in the handler itself. Real traffic hits RequireUser
// upstream (which emits 401 with text "unauthenticated"), but the handler
// also defends against routing misconfigurations and we test that
// directly.
func TestHandleRemoveTrack_NoSession401(t *testing.T) {
h, pool := testHandlers(t)
truncateLibrary(t, pool)
tr, _ := seedTrackForRemoveTest(t, h, "no-session", "", "")
w := doAdminTracksReqNoUser(t, h, http.MethodDelete,
"/api/admin/tracks/"+uuidToString(tr.ID), uuidToString(tr.ID))
if w.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401; body = %s", w.Code, w.Body.String())
}
var env errorBody
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if env.Error.Code != "unauthenticated" {
t.Errorf("error.code = %q, want unauthenticated", env.Error.Code)
}
}
// TestHandleRemoveTrack_UnknownID404 verifies ErrNotFound from the service
// maps to 404 not_found in the spec envelope.
func TestHandleRemoveTrack_UnknownID404(t *testing.T) {
h, pool := testHandlers(t)
truncateLibrary(t, pool)
admin := seedUser(t, pool, "admin", "pw", true)
// Well-formed UUID with no matching row in the DB.
missing := "00000000-0000-0000-0000-0000000000aa"
w := doAdminTracksReq(t, h, http.MethodDelete, "/api/admin/tracks/"+missing, admin)
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404; body = %s", w.Code, w.Body.String())
}
var env errorBody
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if env.Error.Code != "not_found" {
t.Errorf("error.code = %q, want not_found", env.Error.Code)
}
}
// TestHandleRemoveTrack_HappyPath verifies the success envelope: 200 with
// deleted_track_id and the optional cascade fields when they fired.
func TestHandleRemoveTrack_HappyPath(t *testing.T) {
h, pool := testHandlers(t)
truncateLibrary(t, pool)
admin := seedUser(t, pool, "admin", "pw", true)
// Track with no mbid; sole track on its album/artist so the cascade
// fills both deleted_album_id and deleted_artist_id.
tr, path := seedTrackForRemoveTest(t, h, "noumon-happy", "", "")
w := doAdminTracksReq(t, h, http.MethodDelete,
"/api/admin/tracks/"+uuidToString(tr.ID), admin)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
}
var got removeTrackResponse
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if got.DeletedTrackID != uuidToString(tr.ID) {
t.Errorf("deleted_track_id = %q, want %q", got.DeletedTrackID, uuidToString(tr.ID))
}
if got.DeletedAlbumID == nil {
t.Error("deleted_album_id missing; expected sole-track cascade")
}
if got.DeletedArtistID == nil {
t.Error("deleted_artist_id missing; expected sole-track cascade")
}
// File is gone, DB row is gone.
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Errorf("file still exists: %v", err)
}
if _, err := dbq.New(pool).GetTrackByID(context.Background(), tr.ID); err == nil {
t.Error("track row still exists")
}
}
+4 -6
View File
@@ -205,8 +205,6 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
admin.Post("/quarantine/{track_id}/remove-file", h.handleRemoveQuarantineFile)
admin.Get("/quarantine/actions", h.handleListQuarantineActions)
admin.Delete("/tracks/{id}", h.handleRemoveTrack)
admin.Post("/albums/{id}/cover/refetch", h.handleAdminAlbumRefetchCover)
admin.Post("/covers/refetch-missing", h.handleAdminBulkRefetchCovers)
@@ -220,11 +218,11 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
admin.Get("/scan/status", h.handleGetScanStatus)
admin.Post("/scan/run", h.handleTriggerScan)
// Sits under /library rather than /tracks because what it
// reports is a property of the library's relationship to disk,
// and because the destructive /tracks/{id} route above must
// not be mistaken for it.
// Needs a file: tracks waiting for a good copy, what to give
// whatever finds music, and forgetting the ones not worth it.
admin.Get("/library/missing", h.handleListMissingTracks)
admin.Get("/library/missing.csv", h.handleExportMissingTracks)
admin.Post("/library/missing/forget", h.handleForgetMissingTracks)
admin.Get("/library/suspect-sources", h.handleListSuspectSources)
admin.Put("/library/suspect-sources/{id}", h.handleSetSuspectSourceVerdict)
admin.Post("/library/suspect-sources/{id}/remove", h.handleRemoveSuspectSourceFile)
+1 -1
View File
@@ -15,7 +15,7 @@ import (
const removeTestPath = "/music/Moe Shop/WWW (2020)/01 - WWW.mp3"
// removeFailure builds the error a delete service returns when the file would
// not go, wrapped the way quarantine.DeleteFile and tracks.RemoveTrack
// not go, wrapped the way quarantine.DeleteFile and quarantine.RemoveFile
// wrap it — the mapping has to see through that.
func removeFailure(errno syscall.Errno) error {
return fmt.Errorf("delete file: %w", &library.FileRemoveError{
+1 -1
View File
@@ -81,7 +81,7 @@ func TestCastStreamToken_Leveled(t *testing.T) {
}
h.leveled = r
user := seedUser(t, pool, "lev", "pw", false)
track, _ := seedTrackForRemoveTest(t, h, "lev", "", "")
track, _ := seedTrackOnDiskWithMBIDs(t, h, "lev", "", "")
trackID := uuidToString(track.ID)
lufs, peak := float32(-12.5), float32(-1)
if err := dbq.New(pool).UpsertTrackLoudness(context.Background(), dbq.UpsertTrackLoudnessParams{
+47
View File
@@ -187,3 +187,50 @@ func seedTrackWithFile(t *testing.T, pool *pgxpool.Pool, albumID, artistID pgtyp
}
return tr, dir
}
// seedTrackOnDiskWithMBIDs creates a fresh artist+album+track on disk and
// returns the track row. The mbids are set on the track and album when
// non-empty.
func seedTrackOnDiskWithMBIDs(t *testing.T, h *handlers, unique, trackMbid, albumMbid string) (dbq.Track, string) {
t.Helper()
artist := seedArtist(t, h.pool, "RemoveTest Artist "+unique)
dir := t.TempDir()
path := filepath.Join(dir, "track-"+unique+".mp3")
if err := os.WriteFile(path, []byte("audio"), 0o644); err != nil {
t.Fatalf("write file: %v", err)
}
q := dbq.New(h.pool)
var albumMbidPtr *string
if albumMbid != "" {
albumMbidPtr = &albumMbid
}
album, err := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{
Title: "RemoveTest Album " + unique,
SortTitle: "RemoveTest Album " + unique,
ArtistID: artist.ID,
Mbid: albumMbidPtr,
})
if err != nil {
t.Fatalf("UpsertAlbum: %v", err)
}
one := int32(1)
var trackMbidPtr *string
if trackMbid != "" {
trackMbidPtr = &trackMbid
}
tr, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{
Title: "RemoveTest Track " + unique,
AlbumID: album.ID,
ArtistID: artist.ID,
TrackNumber: &one,
DurationMs: 30000,
FilePath: path,
FileSize: 5,
FileFormat: "mp3",
Mbid: trackMbidPtr,
})
if err != nil {
t.Fatalf("UpsertTrack: %v", err)
}
return tr, path
}
+1 -1
View File
@@ -18,7 +18,7 @@ import (
// newPlaylistsRouter mounts the 9 playlist routes for an in-test chi
// instance. RequireUser is NOT applied — tests inject the user into
// context manually so we exercise the handler-owned auth defense
// directly. Mirrors the pattern from newAdminTracksRouter.
// directly.
func newPlaylistsRouter(h *handlers) chi.Router {
r := chi.NewRouter()
r.Get("/api/playlists", h.handleListPlaylists)
+2 -2
View File
@@ -16,8 +16,8 @@ import (
func TestGetReplayGain(t *testing.T) {
h, pool := testHandlers(t)
user := seedUser(t, pool, "rg1", "pw", false)
measured, _ := seedTrackForRemoveTest(t, h, "rg-measured", "", "")
unmeasured, _ := seedTrackForRemoveTest(t, h, "rg-unmeasured", "", "")
measured, _ := seedTrackOnDiskWithMBIDs(t, h, "rg-measured", "", "")
unmeasured, _ := seedTrackOnDiskWithMBIDs(t, h, "rg-unmeasured", "", "")
lufs, peak := float32(-12.5), float32(-1)
if err := dbq.New(pool).UpsertTrackLoudness(context.Background(), dbq.UpsertTrackLoudnessParams{
TrackID: measured.ID, IntegratedLufs: &lufs, TruePeakDbtp: &peak, AnalysisVersion: 1,