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
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:
@@ -1,29 +1,49 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/csv"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
"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 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
|
// 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
|
// 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
|
// 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.
|
// 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 {
|
type missingTrackView struct {
|
||||||
TrackID string `json:"track_id"`
|
TrackID string `json:"track_id"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
ArtistID string `json:"artist_id"`
|
ArtistID string `json:"artist_id"`
|
||||||
ArtistName string `json:"artist_name"`
|
ArtistName string `json:"artist_name"`
|
||||||
AlbumID string `json:"album_id"`
|
AlbumID string `json:"album_id"`
|
||||||
AlbumTitle string `json:"album_title"`
|
AlbumTitle string `json:"album_title"`
|
||||||
FilePath string `json:"file_path"`
|
FilePath string `json:"file_path"`
|
||||||
DurationSec int32 `json:"duration_sec"`
|
DurationSec int32 `json:"duration_sec"`
|
||||||
MissingSince string `json:"missing_since"`
|
DiscNumber *int32 `json:"disc_number"`
|
||||||
LastPlayedAt *string `json:"last_played_at"`
|
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.
|
// missingGroupView is a directory's worth of missing tracks.
|
||||||
@@ -49,12 +69,11 @@ type adminMissingResponse struct {
|
|||||||
Groups []missingGroupView `json:"groups"`
|
Groups []missingGroupView `json:"groups"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleListMissingTracks implements GET /api/admin/library/missing.
|
// handleListMissingTracks implements GET /api/admin/library/missing: the
|
||||||
//
|
// tracks waiting for a file. A waiting track keeps its row, its history and
|
||||||
// Read-only by design. Nothing on this surface deletes a track: a missing file
|
// its likes because a file may come back, and a good copy that lands in the
|
||||||
// keeps its row, its history and its likes because it may come back, and if it
|
// library is adopted or folded into it. Forgetting one is a separate,
|
||||||
// comes back renamed the scanner adopts it. The surface exists so an admin
|
// deliberate call (handleForgetMissingTracks).
|
||||||
// can SEE what the library has lost and act on it deliberately.
|
|
||||||
func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Request) {
|
func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Request) {
|
||||||
limit, offset, err := parsePaging(r.URL.Query())
|
limit, offset, err := parsePaging(r.URL.Query())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -102,15 +121,21 @@ func groupMissingByDirectory(rows []dbq.ListMissingTracksRow) []missingGroupView
|
|||||||
groups := make([]missingGroupView, 0, 8)
|
groups := make([]missingGroupView, 0, 8)
|
||||||
for _, row := range rows {
|
for _, row := range rows {
|
||||||
t := missingTrackView{
|
t := missingTrackView{
|
||||||
TrackID: uuidToString(row.ID),
|
TrackID: uuidToString(row.ID),
|
||||||
Title: row.Title,
|
Title: row.Title,
|
||||||
ArtistID: uuidToString(row.ArtistID),
|
ArtistID: uuidToString(row.ArtistID),
|
||||||
ArtistName: row.ArtistName,
|
ArtistName: row.ArtistName,
|
||||||
AlbumID: uuidToString(row.AlbumID),
|
AlbumID: uuidToString(row.AlbumID),
|
||||||
AlbumTitle: row.AlbumTitle,
|
AlbumTitle: row.AlbumTitle,
|
||||||
FilePath: row.FilePath,
|
FilePath: row.FilePath,
|
||||||
DurationSec: row.DurationMs / 1000,
|
DurationSec: row.DurationMs / 1000,
|
||||||
MissingSince: formatTimestamp(row.MissingSince),
|
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 {
|
if row.LastPlayedAt.Valid {
|
||||||
s := formatTimestamp(row.LastPlayedAt)
|
s := formatTimestamp(row.LastPlayedAt)
|
||||||
@@ -134,3 +159,116 @@ func groupMissingByDirectory(rows []dbq.ListMissingTracksRow) []missingGroupView
|
|||||||
}
|
}
|
||||||
return groups
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
|
||||||
}
|
|
||||||
@@ -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
@@ -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.Post("/quarantine/{track_id}/remove-file", h.handleRemoveQuarantineFile)
|
||||||
admin.Get("/quarantine/actions", h.handleListQuarantineActions)
|
admin.Get("/quarantine/actions", h.handleListQuarantineActions)
|
||||||
|
|
||||||
admin.Delete("/tracks/{id}", h.handleRemoveTrack)
|
|
||||||
|
|
||||||
admin.Post("/albums/{id}/cover/refetch", h.handleAdminAlbumRefetchCover)
|
admin.Post("/albums/{id}/cover/refetch", h.handleAdminAlbumRefetchCover)
|
||||||
admin.Post("/covers/refetch-missing", h.handleAdminBulkRefetchCovers)
|
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.Get("/scan/status", h.handleGetScanStatus)
|
||||||
admin.Post("/scan/run", h.handleTriggerScan)
|
admin.Post("/scan/run", h.handleTriggerScan)
|
||||||
// Sits under /library rather than /tracks because what it
|
// Needs a file: tracks waiting for a good copy, what to give
|
||||||
// reports is a property of the library's relationship to disk,
|
// whatever finds music, and forgetting the ones not worth it.
|
||||||
// and because the destructive /tracks/{id} route above must
|
|
||||||
// not be mistaken for it.
|
|
||||||
admin.Get("/library/missing", h.handleListMissingTracks)
|
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.Get("/library/suspect-sources", h.handleListSuspectSources)
|
||||||
admin.Put("/library/suspect-sources/{id}", h.handleSetSuspectSourceVerdict)
|
admin.Put("/library/suspect-sources/{id}", h.handleSetSuspectSourceVerdict)
|
||||||
admin.Post("/library/suspect-sources/{id}/remove", h.handleRemoveSuspectSourceFile)
|
admin.Post("/library/suspect-sources/{id}/remove", h.handleRemoveSuspectSourceFile)
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import (
|
|||||||
const removeTestPath = "/music/Moe Shop/WWW (2020)/01 - WWW.mp3"
|
const removeTestPath = "/music/Moe Shop/WWW (2020)/01 - WWW.mp3"
|
||||||
|
|
||||||
// removeFailure builds the error a delete service returns when the file would
|
// 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.
|
// wrap it — the mapping has to see through that.
|
||||||
func removeFailure(errno syscall.Errno) error {
|
func removeFailure(errno syscall.Errno) error {
|
||||||
return fmt.Errorf("delete file: %w", &library.FileRemoveError{
|
return fmt.Errorf("delete file: %w", &library.FileRemoveError{
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ func TestCastStreamToken_Leveled(t *testing.T) {
|
|||||||
}
|
}
|
||||||
h.leveled = r
|
h.leveled = r
|
||||||
user := seedUser(t, pool, "lev", "pw", false)
|
user := seedUser(t, pool, "lev", "pw", false)
|
||||||
track, _ := seedTrackForRemoveTest(t, h, "lev", "", "")
|
track, _ := seedTrackOnDiskWithMBIDs(t, h, "lev", "", "")
|
||||||
trackID := uuidToString(track.ID)
|
trackID := uuidToString(track.ID)
|
||||||
lufs, peak := float32(-12.5), float32(-1)
|
lufs, peak := float32(-12.5), float32(-1)
|
||||||
if err := dbq.New(pool).UpsertTrackLoudness(context.Background(), dbq.UpsertTrackLoudnessParams{
|
if err := dbq.New(pool).UpsertTrackLoudness(context.Background(), dbq.UpsertTrackLoudnessParams{
|
||||||
|
|||||||
@@ -187,3 +187,50 @@ func seedTrackWithFile(t *testing.T, pool *pgxpool.Pool, albumID, artistID pgtyp
|
|||||||
}
|
}
|
||||||
return tr, dir
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import (
|
|||||||
// newPlaylistsRouter mounts the 9 playlist routes for an in-test chi
|
// newPlaylistsRouter mounts the 9 playlist routes for an in-test chi
|
||||||
// instance. RequireUser is NOT applied — tests inject the user into
|
// instance. RequireUser is NOT applied — tests inject the user into
|
||||||
// context manually so we exercise the handler-owned auth defense
|
// context manually so we exercise the handler-owned auth defense
|
||||||
// directly. Mirrors the pattern from newAdminTracksRouter.
|
// directly.
|
||||||
func newPlaylistsRouter(h *handlers) chi.Router {
|
func newPlaylistsRouter(h *handlers) chi.Router {
|
||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
r.Get("/api/playlists", h.handleListPlaylists)
|
r.Get("/api/playlists", h.handleListPlaylists)
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ import (
|
|||||||
func TestGetReplayGain(t *testing.T) {
|
func TestGetReplayGain(t *testing.T) {
|
||||||
h, pool := testHandlers(t)
|
h, pool := testHandlers(t)
|
||||||
user := seedUser(t, pool, "rg1", "pw", false)
|
user := seedUser(t, pool, "rg1", "pw", false)
|
||||||
measured, _ := seedTrackForRemoveTest(t, h, "rg-measured", "", "")
|
measured, _ := seedTrackOnDiskWithMBIDs(t, h, "rg-measured", "", "")
|
||||||
unmeasured, _ := seedTrackForRemoveTest(t, h, "rg-unmeasured", "", "")
|
unmeasured, _ := seedTrackOnDiskWithMBIDs(t, h, "rg-unmeasured", "", "")
|
||||||
lufs, peak := float32(-12.5), float32(-1)
|
lufs, peak := float32(-12.5), float32(-1)
|
||||||
if err := dbq.New(pool).UpsertTrackLoudness(context.Background(), dbq.UpsertTrackLoudnessParams{
|
if err := dbq.New(pool).UpsertTrackLoudness(context.Background(), dbq.UpsertTrackLoudnessParams{
|
||||||
TrackID: measured.ID, IntegratedLufs: &lufs, TruePeakDbtp: &peak, AnalysisVersion: 1,
|
TrackID: measured.ID, IntegratedLufs: &lufs, TruePeakDbtp: &peak, AnalysisVersion: 1,
|
||||||
|
|||||||
@@ -62,11 +62,11 @@ const (
|
|||||||
ActionDuplicateDismiss Action = "duplicate_dismiss"
|
ActionDuplicateDismiss Action = "duplicate_dismiss"
|
||||||
ActionDuplicateWrongFile Action = "duplicate_wrong_file"
|
ActionDuplicateWrongFile Action = "duplicate_wrong_file"
|
||||||
|
|
||||||
// An admin removing a track: its file and row are deleted, with every
|
// An admin forgetting tracks that waited for a file: each row is deleted,
|
||||||
// like, play and playlist entry that hung off the row. The metadata names
|
// with every like, play and playlist entry that hung off it. The metadata
|
||||||
// the track and its file, so the log can say what went after the row is
|
// names each track and the file it had, so the log can say what went after
|
||||||
// gone.
|
// the rows are gone.
|
||||||
ActionTrackRemove Action = "track_remove"
|
ActionTrackForget Action = "track_forget"
|
||||||
// An admin removing a suspect source's file and keeping its track, which
|
// An admin removing a suspect source's file and keeping its track, which
|
||||||
// waits, missing, for a clean copy. (A report's removal is recorded in
|
// waits, missing, for a clean copy. (A report's removal is recorded in
|
||||||
// the Reports history instead, and a duplicate's under
|
// the Reports history instead, and a duplicate's under
|
||||||
|
|||||||
@@ -528,12 +528,21 @@ SELECT t.id,
|
|||||||
albums.title AS album_title,
|
albums.title AS album_title,
|
||||||
artists.id AS artist_id,
|
artists.id AS artist_id,
|
||||||
artists.name AS artist_name,
|
artists.name AS artist_name,
|
||||||
|
t.disc_number,
|
||||||
|
t.track_number,
|
||||||
|
t.mbid,
|
||||||
|
albums.release_group_mbid,
|
||||||
|
-- Why the track waits: the Collection queue its file was removed from,
|
||||||
|
-- and who removed it. NULL reason means the scan found the file gone.
|
||||||
|
t.removed_reason,
|
||||||
|
remover.username AS removed_by_name,
|
||||||
-- Cast is load-bearing: without it sqlc infers the correlated
|
-- Cast is load-bearing: without it sqlc infers the correlated
|
||||||
-- subquery as interface{} and the Go layer loses the timestamp type.
|
-- subquery as interface{} and the Go layer loses the timestamp type.
|
||||||
(SELECT MAX(pe.started_at) FROM play_events pe WHERE pe.track_id = t.id)::timestamptz AS last_played_at
|
(SELECT MAX(pe.started_at) FROM play_events pe WHERE pe.track_id = t.id)::timestamptz AS last_played_at
|
||||||
FROM tracks t
|
FROM tracks t
|
||||||
JOIN albums ON albums.id = t.album_id
|
JOIN albums ON albums.id = t.album_id
|
||||||
JOIN artists ON artists.id = t.artist_id
|
JOIN artists ON artists.id = t.artist_id
|
||||||
|
LEFT JOIN users remover ON remover.id = t.removed_by
|
||||||
WHERE t.missing_since IS NOT NULL
|
WHERE t.missing_since IS NOT NULL
|
||||||
ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title
|
ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title
|
||||||
LIMIT $2 OFFSET $1
|
LIMIT $2 OFFSET $1
|
||||||
@@ -545,17 +554,23 @@ type ListMissingTracksParams struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ListMissingTracksRow struct {
|
type ListMissingTracksRow struct {
|
||||||
ID pgtype.UUID
|
ID pgtype.UUID
|
||||||
Title string
|
Title string
|
||||||
FilePath string
|
FilePath string
|
||||||
Directory string
|
Directory string
|
||||||
MissingSince pgtype.Timestamptz
|
MissingSince pgtype.Timestamptz
|
||||||
DurationMs int32
|
DurationMs int32
|
||||||
AlbumID pgtype.UUID
|
AlbumID pgtype.UUID
|
||||||
AlbumTitle string
|
AlbumTitle string
|
||||||
ArtistID pgtype.UUID
|
ArtistID pgtype.UUID
|
||||||
ArtistName string
|
ArtistName string
|
||||||
LastPlayedAt pgtype.Timestamptz
|
DiscNumber *int32
|
||||||
|
TrackNumber *int32
|
||||||
|
Mbid *string
|
||||||
|
ReleaseGroupMbid *string
|
||||||
|
RemovedReason *string
|
||||||
|
RemovedByName *string
|
||||||
|
LastPlayedAt pgtype.Timestamptz
|
||||||
}
|
}
|
||||||
|
|
||||||
// The admin review surface for files the scan could not find.
|
// The admin review surface for files the scan could not find.
|
||||||
@@ -590,6 +605,12 @@ func (q *Queries) ListMissingTracks(ctx context.Context, arg ListMissingTracksPa
|
|||||||
&i.AlbumTitle,
|
&i.AlbumTitle,
|
||||||
&i.ArtistID,
|
&i.ArtistID,
|
||||||
&i.ArtistName,
|
&i.ArtistName,
|
||||||
|
&i.DiscNumber,
|
||||||
|
&i.TrackNumber,
|
||||||
|
&i.Mbid,
|
||||||
|
&i.ReleaseGroupMbid,
|
||||||
|
&i.RemovedReason,
|
||||||
|
&i.RemovedByName,
|
||||||
&i.LastPlayedAt,
|
&i.LastPlayedAt,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -946,6 +967,52 @@ func (q *Queries) ListTracksMissingMbidWithPath(ctx context.Context, limit int32
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const lockTracksForForget = `-- name: LockTracksForForget :many
|
||||||
|
SELECT id, album_id, title, file_path, missing_since
|
||||||
|
FROM tracks
|
||||||
|
WHERE id = ANY($1::uuid[])
|
||||||
|
ORDER BY id
|
||||||
|
FOR UPDATE
|
||||||
|
`
|
||||||
|
|
||||||
|
type LockTracksForForgetRow struct {
|
||||||
|
ID pgtype.UUID
|
||||||
|
AlbumID pgtype.UUID
|
||||||
|
Title string
|
||||||
|
FilePath string
|
||||||
|
MissingSince pgtype.Timestamptz
|
||||||
|
}
|
||||||
|
|
||||||
|
// Locks the tracks an admin asked to forget, for the forget's transaction,
|
||||||
|
// and returns what it re-checks: every one must still exist and still be
|
||||||
|
// missing. A track whose file came back since the page was read is playing
|
||||||
|
// again and is not forgotten.
|
||||||
|
func (q *Queries) LockTracksForForget(ctx context.Context, ids []pgtype.UUID) ([]LockTracksForForgetRow, error) {
|
||||||
|
rows, err := q.db.Query(ctx, lockTracksForForget, ids)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []LockTracksForForgetRow
|
||||||
|
for rows.Next() {
|
||||||
|
var i LockTracksForForgetRow
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.AlbumID,
|
||||||
|
&i.Title,
|
||||||
|
&i.FilePath,
|
||||||
|
&i.MissingSince,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const markTracksEmptied = `-- name: MarkTracksEmptied :exec
|
const markTracksEmptied = `-- name: MarkTracksEmptied :exec
|
||||||
UPDATE tracks
|
UPDATE tracks
|
||||||
SET emptied_at = missing_since
|
SET emptied_at = missing_since
|
||||||
|
|||||||
@@ -261,6 +261,17 @@ UPDATE tracks
|
|||||||
WHERE id = ANY(sqlc.arg(ids)::uuid[])
|
WHERE id = ANY(sqlc.arg(ids)::uuid[])
|
||||||
AND missing_since IS NOT NULL;
|
AND missing_since IS NOT NULL;
|
||||||
|
|
||||||
|
-- name: LockTracksForForget :many
|
||||||
|
-- Locks the tracks an admin asked to forget, for the forget's transaction,
|
||||||
|
-- and returns what it re-checks: every one must still exist and still be
|
||||||
|
-- missing. A track whose file came back since the page was read is playing
|
||||||
|
-- again and is not forgotten.
|
||||||
|
SELECT id, album_id, title, file_path, missing_since
|
||||||
|
FROM tracks
|
||||||
|
WHERE id = ANY(sqlc.arg(ids)::uuid[])
|
||||||
|
ORDER BY id
|
||||||
|
FOR UPDATE;
|
||||||
|
|
||||||
-- name: ListMissingTracks :many
|
-- name: ListMissingTracks :many
|
||||||
-- The admin review surface for files the scan could not find.
|
-- The admin review surface for files the scan could not find.
|
||||||
--
|
--
|
||||||
@@ -284,12 +295,21 @@ SELECT t.id,
|
|||||||
albums.title AS album_title,
|
albums.title AS album_title,
|
||||||
artists.id AS artist_id,
|
artists.id AS artist_id,
|
||||||
artists.name AS artist_name,
|
artists.name AS artist_name,
|
||||||
|
t.disc_number,
|
||||||
|
t.track_number,
|
||||||
|
t.mbid,
|
||||||
|
albums.release_group_mbid,
|
||||||
|
-- Why the track waits: the Collection queue its file was removed from,
|
||||||
|
-- and who removed it. NULL reason means the scan found the file gone.
|
||||||
|
t.removed_reason,
|
||||||
|
remover.username AS removed_by_name,
|
||||||
-- Cast is load-bearing: without it sqlc infers the correlated
|
-- Cast is load-bearing: without it sqlc infers the correlated
|
||||||
-- subquery as interface{} and the Go layer loses the timestamp type.
|
-- subquery as interface{} and the Go layer loses the timestamp type.
|
||||||
(SELECT MAX(pe.started_at) FROM play_events pe WHERE pe.track_id = t.id)::timestamptz AS last_played_at
|
(SELECT MAX(pe.started_at) FROM play_events pe WHERE pe.track_id = t.id)::timestamptz AS last_played_at
|
||||||
FROM tracks t
|
FROM tracks t
|
||||||
JOIN albums ON albums.id = t.album_id
|
JOIN albums ON albums.id = t.album_id
|
||||||
JOIN artists ON artists.id = t.artist_id
|
JOIN artists ON artists.id = t.artist_id
|
||||||
|
LEFT JOIN users remover ON remover.id = t.removed_by
|
||||||
WHERE t.missing_since IS NOT NULL
|
WHERE t.missing_since IS NOT NULL
|
||||||
ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title
|
ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title
|
||||||
LIMIT sqlc.arg(page_limit) OFFSET sqlc.arg(page_offset);
|
LIMIT sqlc.arg(page_limit) OFFSET sqlc.arg(page_offset);
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package library
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
|
||||||
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||||
|
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrTrackPresent means a track asked to be forgotten has its file: it plays,
|
||||||
|
// and forgetting it would throw away a track the library still holds.
|
||||||
|
var ErrTrackPresent = errors.New("library: track has its file")
|
||||||
|
|
||||||
|
// ForgottenTrack is one track Forget removed, named for the audit log.
|
||||||
|
type ForgottenTrack struct {
|
||||||
|
ID pgtype.UUID
|
||||||
|
Title string
|
||||||
|
FilePath string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ForgetMissingTracks removes tracks that wait for a file and that an admin
|
||||||
|
// has given up on: each row goes with its likes, plays and playlist places,
|
||||||
|
// and an album or artist it leaves empty goes too. There is no file to
|
||||||
|
// delete. It is all or nothing: if any of ids is unknown (ErrTrackNotFound) or
|
||||||
|
// has its file (ErrTrackPresent), nothing is forgotten.
|
||||||
|
//
|
||||||
|
// dataDir, when set, also clears the cached art of an artist that went.
|
||||||
|
func ForgetMissingTracks(
|
||||||
|
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, ids []pgtype.UUID,
|
||||||
|
) ([]ForgottenTrack, error) {
|
||||||
|
if logger == nil {
|
||||||
|
logger = slog.Default()
|
||||||
|
}
|
||||||
|
var gone []ForgottenTrack
|
||||||
|
var emptiedArtists []pgtype.UUID
|
||||||
|
err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
|
||||||
|
tq := dbq.New(tx)
|
||||||
|
rows, err := tq.LockTracksForForget(ctx, ids)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("lock tracks: %w", err)
|
||||||
|
}
|
||||||
|
if len(rows) != len(uniqueUUIDs(ids)) {
|
||||||
|
return ErrTrackNotFound
|
||||||
|
}
|
||||||
|
for _, r := range rows {
|
||||||
|
if !r.MissingSince.Valid {
|
||||||
|
return ErrTrackPresent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range rows {
|
||||||
|
if _, err := tq.DeleteTrack(ctx, r.ID); err != nil {
|
||||||
|
return fmt.Errorf("delete track: %w", err)
|
||||||
|
}
|
||||||
|
out, err := tidyEmptiedAlbum(ctx, tq, r.AlbumID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if out.ArtistID != nil {
|
||||||
|
emptiedArtists = append(emptiedArtists, *out.ArtistID)
|
||||||
|
}
|
||||||
|
gone = append(gone, ForgottenTrack{ID: r.ID, Title: r.Title, FilePath: r.FilePath})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// After the commit, so neither can undo a forget that happened: an
|
||||||
|
// unlogged change leaves the track in offline clients' caches until the
|
||||||
|
// next scan, and leftover art is only disk.
|
||||||
|
for _, t := range gone {
|
||||||
|
if err := syncpkg.LogChange(ctx, pool, syncpkg.EntityTrack, syncpkg.FormatUUID(t.ID), syncpkg.OpDelete); err != nil {
|
||||||
|
logger.Warn("forget: LogChange failed", "track_id", syncpkg.FormatUUID(t.ID), "err", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dataDir != "" {
|
||||||
|
for _, a := range emptiedArtists {
|
||||||
|
if err := coverart.CleanupArtistArt(dataDir, a); err != nil {
|
||||||
|
logger.Warn("forget: artist-art cleanup failed", "artist_id", syncpkg.FormatUUID(a), "err", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return gone, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func uniqueUUIDs(ids []pgtype.UUID) map[pgtype.UUID]bool {
|
||||||
|
out := make(map[pgtype.UUID]bool, len(ids))
|
||||||
|
for _, id := range ids {
|
||||||
|
out[id] = true
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
+20
-56
@@ -1,25 +1,17 @@
|
|||||||
// Package tracks owns the track-level admin actions behind DELETE
|
// Package tracks owns the track-level admin actions that are written to the
|
||||||
// /api/admin/tracks/{id} and the duplicate merge. RemoveTrack's destructive
|
// audit log: forgetting tracks that wait for a file, and the duplicate merge.
|
||||||
// part goes through library.DeleteTrackFile — the one path that deletes a
|
|
||||||
// track file.
|
|
||||||
//
|
|
||||||
// No client calls the endpoint today; it is kept for an admin surface to
|
|
||||||
// rebind.
|
|
||||||
package tracks
|
package tracks
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
||||||
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
|
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
|
||||||
)
|
)
|
||||||
@@ -30,7 +22,7 @@ import (
|
|||||||
// same pointer.
|
// same pointer.
|
||||||
var ErrNotFound = apierror.ErrNotFound
|
var ErrNotFound = apierror.ErrNotFound
|
||||||
|
|
||||||
// Service owns RemoveTrack and MergeDuplicates.
|
// Service owns ForgetTracks and MergeDuplicates.
|
||||||
type Service struct {
|
type Service struct {
|
||||||
pool *pgxpool.Pool
|
pool *pgxpool.Pool
|
||||||
logger *slog.Logger
|
logger *slog.Logger
|
||||||
@@ -47,55 +39,27 @@ func NewService(pool *pgxpool.Pool, logger *slog.Logger, dataDir string) *Servic
|
|||||||
return &Service{pool: pool, logger: logger, dataDir: dataDir}
|
return &Service{pool: pool, logger: logger, dataDir: dataDir}
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoveTrack deletes the track's file and then its row, and tidies away an
|
// ForgetTracks removes tracks waiting for a file that an admin has given up
|
||||||
// album or artist the delete empties.
|
// on (library.ForgetMissingTracks), and writes the forget to the audit log
|
||||||
//
|
// with adminID as the actor, naming each track and the file it had. It is all
|
||||||
// Returns:
|
// or nothing: a track that has its file again is library.ErrTrackPresent, and
|
||||||
// - deletedAlbumID: non-nil when removing the track left the album
|
// an unknown one is ErrNotFound.
|
||||||
// empty and the album row was deleted.
|
func (s *Service) ForgetTracks(ctx context.Context, ids []pgtype.UUID, adminID pgtype.UUID) ([]library.ForgottenTrack, error) {
|
||||||
// - deletedArtistID: non-nil when both album AND artist were left
|
gone, err := library.ForgetMissingTracks(ctx, s.pool, s.logger, s.dataDir, ids)
|
||||||
// empty (only set if deletedAlbumID is also set).
|
|
||||||
// - err: ErrNotFound, or a failure before anything was deleted. When the
|
|
||||||
// file cannot be removed it is a *library.FileRemoveError and NOTHING was
|
|
||||||
// deleted — see library.DeleteTrackFile for why that order is the contract.
|
|
||||||
//
|
|
||||||
// A removal is written to the audit log with adminID as the actor. The
|
|
||||||
// track's names are read before the delete, since the row, and perhaps its
|
|
||||||
// album and artist, are gone after it.
|
|
||||||
func (s *Service) RemoveTrack(
|
|
||||||
ctx context.Context, trackID, adminID pgtype.UUID,
|
|
||||||
) (deletedAlbumID *pgtype.UUID, deletedArtistID *pgtype.UUID, err error) {
|
|
||||||
q := dbq.New(s.pool)
|
|
||||||
track, err := q.GetTrackByID(ctx, trackID)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return nil, nil, ErrNotFound
|
|
||||||
}
|
|
||||||
return nil, nil, fmt.Errorf("get track: %w", err)
|
|
||||||
}
|
|
||||||
meta := map[string]any{
|
|
||||||
"track_id": syncpkg.FormatUUID(track.ID),
|
|
||||||
"title": track.Title,
|
|
||||||
"file_path": track.FilePath,
|
|
||||||
}
|
|
||||||
if artist, err := q.GetArtistByID(ctx, track.ArtistID); err == nil {
|
|
||||||
meta["artist"] = artist.Name
|
|
||||||
}
|
|
||||||
if album, err := q.GetAlbumByID(ctx, track.AlbumID); err == nil {
|
|
||||||
meta["album"] = album.Title
|
|
||||||
}
|
|
||||||
|
|
||||||
deleted, err := library.DeleteTrackFile(ctx, s.pool, s.logger, s.dataDir, trackID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, library.ErrTrackNotFound) {
|
if errors.Is(err, library.ErrTrackNotFound) {
|
||||||
return nil, nil, ErrNotFound
|
return nil, ErrNotFound
|
||||||
}
|
}
|
||||||
return nil, nil, fmt.Errorf("delete track: %w", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
meta["album_deleted"] = deleted.AlbumID != nil
|
named := make([]map[string]string, 0, len(gone))
|
||||||
meta["artist_deleted"] = deleted.ArtistID != nil
|
for _, t := range gone {
|
||||||
audit.WriteOrLog(ctx, s.pool, s.logger, adminID, pgtype.UUID{}, audit.ActionTrackRemove, meta)
|
named = append(named, map[string]string{
|
||||||
return deleted.AlbumID, deleted.ArtistID, nil
|
"track_id": syncpkg.FormatUUID(t.ID), "title": t.Title, "file_path": t.FilePath,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
audit.WriteOrLog(ctx, s.pool, s.logger, adminID, pgtype.UUID{}, audit.ActionTrackForget, map[string]any{"tracks": named})
|
||||||
|
return gone, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// MergeDuplicates merges a duplicate group into the copy to keep
|
// MergeDuplicates merges a duplicate group into the copy to keep
|
||||||
|
|||||||
+70
-159
@@ -15,6 +15,7 @@ import (
|
|||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
|
||||||
|
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
||||||
)
|
)
|
||||||
|
|
||||||
// --- test seed helpers (inlined; mirrors quarantine patterns) -----------
|
// --- test seed helpers (inlined; mirrors quarantine patterns) -----------
|
||||||
@@ -97,200 +98,110 @@ func seedArtistAlbumTrack(t *testing.T, pool *pgxpool.Pool, prefix, mbid, filePa
|
|||||||
|
|
||||||
// --- tests --------------------------------------------------------------
|
// --- tests --------------------------------------------------------------
|
||||||
|
|
||||||
func TestRemoveTrack_NotFound(t *testing.T) {
|
// markMissing marks tracks as waiting for a file, as a scan that could not
|
||||||
|
// find them would.
|
||||||
|
func markMissing(t *testing.T, pool *pgxpool.Pool, ids ...pgtype.UUID) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := dbq.New(pool).MarkTracksMissing(context.Background(), ids); err != nil {
|
||||||
|
t.Fatalf("mark missing: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestForgetTracks_NotFound(t *testing.T) {
|
||||||
pool := newPool(t)
|
pool := newPool(t)
|
||||||
admin := seedAdmin(t, pool, "alice")
|
admin := seedAdmin(t, pool, "alice")
|
||||||
|
|
||||||
var bogus pgtype.UUID
|
var bogus pgtype.UUID
|
||||||
bogus.Bytes = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
|
bogus.Bytes = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
|
||||||
bogus.Valid = true
|
bogus.Valid = true
|
||||||
|
|
||||||
svc := NewService(pool, nil, "")
|
_, err := NewService(pool, nil, "").ForgetTracks(context.Background(), []pgtype.UUID{bogus}, admin.ID)
|
||||||
_, _, err := svc.RemoveTrack(context.Background(), bogus, admin.ID)
|
|
||||||
if !errors.Is(err, ErrNotFound) {
|
if !errors.Is(err, ErrNotFound) {
|
||||||
t.Errorf("err = %v, want ErrNotFound", err)
|
t.Errorf("err = %v, want ErrNotFound", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRemoveTrack_LocalFile_HappyPath(t *testing.T) {
|
// A track that has its file plays, and is not forgotten; nor is the waiting
|
||||||
|
// track asked about with it.
|
||||||
|
func TestForgetTracks_RefusesATrackThatHasItsFile(t *testing.T) {
|
||||||
pool := newPool(t)
|
pool := newPool(t)
|
||||||
admin := seedAdmin(t, pool, "alice")
|
admin := seedAdmin(t, pool, "alice")
|
||||||
|
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
path := filepath.Join(dir, "track.mp3")
|
_, _, present := seedArtistAlbumTrack(t, pool, "Present", "", filepath.Join(dir, "p.mp3"))
|
||||||
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
|
_, _, waiting := seedArtistAlbumTrack(t, pool, "Waiting", "", filepath.Join(dir, "w.mp3"))
|
||||||
t.Fatal(err)
|
markMissing(t, pool, waiting.ID)
|
||||||
}
|
|
||||||
_, _, track := seedArtistAlbumTrack(t, pool, "Solo", "", path)
|
|
||||||
|
|
||||||
svc := NewService(pool, nil, "")
|
_, err := NewService(pool, nil, "").ForgetTracks(context.Background(), []pgtype.UUID{waiting.ID, present.ID}, admin.ID)
|
||||||
_, _, err := svc.RemoveTrack(context.Background(), track.ID, admin.ID)
|
if !errors.Is(err, library.ErrTrackPresent) {
|
||||||
if err != nil {
|
t.Fatalf("err = %v, want library.ErrTrackPresent", err)
|
||||||
t.Fatalf("RemoveTrack: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
|
|
||||||
t.Errorf("file still present: %v", err)
|
|
||||||
}
|
}
|
||||||
q := dbq.New(pool)
|
q := dbq.New(pool)
|
||||||
if _, err := q.GetTrackByID(context.Background(), track.ID); err == nil {
|
for _, id := range []pgtype.UUID{present.ID, waiting.ID} {
|
||||||
t.Errorf("track row still exists")
|
if _, err := q.GetTrackByID(context.Background(), id); err != nil {
|
||||||
|
t.Errorf("track %v was forgotten by a refused forget: %v", id, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRemoveTrack_WritesAuditRow(t *testing.T) {
|
// Forget deletes the waiting tracks, tidies away the album and artist they
|
||||||
|
// leave empty, and names each in the audit log.
|
||||||
|
func TestForgetTracks_DeletesWaitingTracksAndAudits(t *testing.T) {
|
||||||
pool := newPool(t)
|
pool := newPool(t)
|
||||||
admin := seedAdmin(t, pool, "alice")
|
admin := seedAdmin(t, pool, "alice")
|
||||||
if _, err := pool.Exec(context.Background(), `DELETE FROM audit_log`); err != nil {
|
if _, err := pool.Exec(context.Background(), `DELETE FROM audit_log`); err != nil {
|
||||||
t.Fatalf("reset audit_log: %v", err)
|
t.Fatalf("reset audit_log: %v", err)
|
||||||
}
|
}
|
||||||
|
path := filepath.Join(t.TempDir(), "lone.mp3")
|
||||||
|
artist, album, track := seedArtistAlbumTrack(t, pool, "Lone", "", path)
|
||||||
|
markMissing(t, pool, track.ID)
|
||||||
|
|
||||||
dir := t.TempDir()
|
gone, err := NewService(pool, nil, "").ForgetTracks(context.Background(), []pgtype.UUID{track.ID}, admin.ID)
|
||||||
path := filepath.Join(dir, "track.mp3")
|
|
||||||
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
_, _, track := seedArtistAlbumTrack(t, pool, "Audited", "", path)
|
|
||||||
|
|
||||||
svc := NewService(pool, nil, "")
|
|
||||||
if _, _, err := svc.RemoveTrack(context.Background(), track.ID, admin.ID); err != nil {
|
|
||||||
t.Fatalf("RemoveTrack: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var actor pgtype.UUID
|
|
||||||
var title, artist, album, filePath string
|
|
||||||
var albumDeleted bool
|
|
||||||
err := pool.QueryRow(context.Background(), `
|
|
||||||
SELECT actor_id, metadata->>'title', metadata->>'artist', metadata->>'album',
|
|
||||||
metadata->>'file_path', (metadata->>'album_deleted')::boolean
|
|
||||||
FROM audit_log WHERE action = 'track_remove'`).
|
|
||||||
Scan(&actor, &title, &artist, &album, &filePath, &albumDeleted)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("read audit row: %v", err)
|
t.Fatalf("ForgetTracks: %v", err)
|
||||||
}
|
}
|
||||||
if actor != admin.ID {
|
if len(gone) != 1 || gone[0].ID != track.ID {
|
||||||
t.Errorf("actor = %v, want the admin %v", actor, admin.ID)
|
t.Fatalf("forgotten = %+v, want the one track", gone)
|
||||||
}
|
|
||||||
if title != "Audited Track" || artist != "Audited Artist" || album != "Audited Album" || filePath != path {
|
|
||||||
t.Errorf("metadata = %q / %q / %q / %q", title, artist, album, filePath)
|
|
||||||
}
|
|
||||||
if !albumDeleted {
|
|
||||||
t.Errorf("album_deleted = false, want true: the track was its album's only one")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRemoveTrack_FileAlreadyMissing(t *testing.T) {
|
|
||||||
pool := newPool(t)
|
|
||||||
admin := seedAdmin(t, pool, "alice")
|
|
||||||
|
|
||||||
// Path doesn't exist on disk; service must tolerate and clean up DB.
|
|
||||||
missing := filepath.Join(t.TempDir(), "does-not-exist.mp3")
|
|
||||||
_, _, track := seedArtistAlbumTrack(t, pool, "Ghost", "", missing)
|
|
||||||
|
|
||||||
svc := NewService(pool, nil, "")
|
|
||||||
_, _, err := svc.RemoveTrack(context.Background(), track.ID, admin.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("RemoveTrack: %v", err)
|
|
||||||
}
|
}
|
||||||
q := dbq.New(pool)
|
q := dbq.New(pool)
|
||||||
if _, err := q.GetTrackByID(context.Background(), track.ID); err == nil {
|
if _, err := q.GetTrackByID(context.Background(), track.ID); err == nil {
|
||||||
t.Errorf("track row still exists")
|
t.Errorf("track row still exists")
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func TestRemoveTrack_Cascade_AlbumEmpty(t *testing.T) {
|
|
||||||
pool := newPool(t)
|
|
||||||
admin := seedAdmin(t, pool, "alice")
|
|
||||||
|
|
||||||
q := dbq.New(pool)
|
|
||||||
// Two-album artist: removing the sole track of album A leaves A
|
|
||||||
// orphaned, but the artist still has album B (so the artist cascade
|
|
||||||
// must NOT fire).
|
|
||||||
artist, err := q.UpsertArtist(context.Background(), dbq.UpsertArtistParams{
|
|
||||||
Name: "Cascade Artist", SortName: "Cascade Artist",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("artist: %v", err)
|
|
||||||
}
|
|
||||||
albumA, err := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{
|
|
||||||
Title: "Album A", SortTitle: "Album A", ArtistID: artist.ID,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("albumA: %v", err)
|
|
||||||
}
|
|
||||||
albumB, err := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{
|
|
||||||
Title: "Album B", SortTitle: "Album B", ArtistID: artist.ID,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("albumB: %v", err)
|
|
||||||
}
|
|
||||||
dir := t.TempDir()
|
|
||||||
pathA := filepath.Join(dir, "a.mp3")
|
|
||||||
pathB := filepath.Join(dir, "b.mp3")
|
|
||||||
_ = os.WriteFile(pathA, []byte("x"), 0o644)
|
|
||||||
_ = os.WriteFile(pathB, []byte("x"), 0o644)
|
|
||||||
trackA, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{
|
|
||||||
Title: "TA", AlbumID: albumA.ID, ArtistID: artist.ID,
|
|
||||||
DurationMs: 1000, FilePath: pathA, FileSize: 1, FileFormat: "mp3",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("trackA: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{
|
|
||||||
Title: "TB", AlbumID: albumB.ID, ArtistID: artist.ID,
|
|
||||||
DurationMs: 1000, FilePath: pathB, FileSize: 1, FileFormat: "mp3",
|
|
||||||
}); err != nil {
|
|
||||||
t.Fatalf("trackB: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
svc := NewService(pool, nil, "")
|
|
||||||
delAlbum, delArtist, err := svc.RemoveTrack(context.Background(), trackA.ID, admin.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("RemoveTrack: %v", err)
|
|
||||||
}
|
|
||||||
if delAlbum == nil || *delAlbum != albumA.ID {
|
|
||||||
t.Errorf("deletedAlbumID = %v, want %v", delAlbum, albumA.ID)
|
|
||||||
}
|
|
||||||
if delArtist != nil {
|
|
||||||
t.Errorf("deletedArtistID = %v, want nil (artist still has album B)", delArtist)
|
|
||||||
}
|
|
||||||
if _, err := q.GetAlbumByID(context.Background(), albumA.ID); err == nil {
|
|
||||||
t.Errorf("album A still exists after cascade")
|
|
||||||
}
|
|
||||||
if _, err := q.GetAlbumByID(context.Background(), albumB.ID); err != nil {
|
|
||||||
t.Errorf("album B unexpectedly removed: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := q.GetArtistByID(context.Background(), artist.ID); err != nil {
|
|
||||||
t.Errorf("artist unexpectedly removed: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRemoveTrack_Cascade_ArtistEmpty(t *testing.T) {
|
|
||||||
pool := newPool(t)
|
|
||||||
admin := seedAdmin(t, pool, "alice")
|
|
||||||
|
|
||||||
dir := t.TempDir()
|
|
||||||
path := filepath.Join(dir, "lone.mp3")
|
|
||||||
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
artist, album, track := seedArtistAlbumTrack(t, pool, "Lone", "", path)
|
|
||||||
|
|
||||||
svc := NewService(pool, nil, "")
|
|
||||||
delAlbum, delArtist, err := svc.RemoveTrack(context.Background(), track.ID, admin.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("RemoveTrack: %v", err)
|
|
||||||
}
|
|
||||||
if delAlbum == nil || *delAlbum != album.ID {
|
|
||||||
t.Errorf("deletedAlbumID = %v, want %v", delAlbum, album.ID)
|
|
||||||
}
|
|
||||||
if delArtist == nil || *delArtist != artist.ID {
|
|
||||||
t.Errorf("deletedArtistID = %v, want %v", delArtist, artist.ID)
|
|
||||||
}
|
|
||||||
q := dbq.New(pool)
|
|
||||||
if _, err := q.GetAlbumByID(context.Background(), album.ID); err == nil {
|
if _, err := q.GetAlbumByID(context.Background(), album.ID); err == nil {
|
||||||
t.Errorf("album still exists after cascade")
|
t.Errorf("album left empty still exists")
|
||||||
}
|
}
|
||||||
if _, err := q.GetArtistByID(context.Background(), artist.ID); err == nil {
|
if _, err := q.GetArtistByID(context.Background(), artist.ID); err == nil {
|
||||||
t.Errorf("artist still exists after cascade")
|
t.Errorf("artist left empty still exists")
|
||||||
|
}
|
||||||
|
var actor pgtype.UUID
|
||||||
|
var title, filePath string
|
||||||
|
if err := pool.QueryRow(context.Background(), `
|
||||||
|
SELECT actor_id, metadata->'tracks'->0->>'title', metadata->'tracks'->0->>'file_path'
|
||||||
|
FROM audit_log WHERE action = 'track_forget'`).Scan(&actor, &title, &filePath); err != nil {
|
||||||
|
t.Fatalf("read audit row: %v", err)
|
||||||
|
}
|
||||||
|
if actor != admin.ID || title != "Lone Track" || filePath != path {
|
||||||
|
t.Errorf("audit = actor %v, %q, %q", actor, title, filePath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// An album that keeps another track is left alone.
|
||||||
|
func TestForgetTracks_KeepsAnAlbumThatStillHasTracks(t *testing.T) {
|
||||||
|
pool := newPool(t)
|
||||||
|
admin := seedAdmin(t, pool, "alice")
|
||||||
|
q := dbq.New(pool)
|
||||||
|
ctx := context.Background()
|
||||||
|
_, album, first := seedArtistAlbumTrack(t, pool, "Shared", "", filepath.Join(t.TempDir(), "a.mp3"))
|
||||||
|
if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
|
||||||
|
Title: "Second", AlbumID: album.ID, ArtistID: first.ArtistID,
|
||||||
|
DurationMs: 1000, FilePath: filepath.Join(t.TempDir(), "b.mp3"), FileSize: 1, FileFormat: "mp3",
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
markMissing(t, pool, first.ID)
|
||||||
|
|
||||||
|
if _, err := NewService(pool, nil, "").ForgetTracks(ctx, []pgtype.UUID{first.ID}, admin.ID); err != nil {
|
||||||
|
t.Fatalf("ForgetTracks: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := q.GetAlbumByID(ctx, album.ID); err != nil {
|
||||||
|
t.Errorf("album with a track left was removed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user