Files
minstrel/internal/api/admin_suspect_sources.go
T
bvandeusenandClaude Opus 5.5 0811775af6 fix(api): every /api error answers in one envelope, so Android shows the real reason (#8002)
Three error shapes were on the wire: {"error":{"code","message"}} from
writeErr, a flat {"error":"code"} from the admin queues, playback errors
and RequireAdmin, and plain text from RequireUser's 401s. Android reads
only the first, so an admin's quarantine, duplicate or suspect-file
error, and "you're not an admin", all showed "Something went wrong."

apierror.Write is now the one writer, and api.writeErr, RequireAdmin,
RequireUser, the client-APK endpoints, the events stream, the unknown-
route 404 and the admin scan all go through it. The flat writers are
gone, and the web client drops its second branch. The admin codes keep
their names; each now carries a message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:43:27 -05:00

218 lines
8.0 KiB
Go

package api
import (
"encoding/json"
"errors"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
)
// suspectTrackView is one flagged track. FilePath is the evidence: the
// markers are read from its basename, and an admin needs to see it to
// judge whether the flag is right.
type suspectTrackView 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"`
DiscNumber *int32 `json:"disc_number"`
TrackNumber *int32 `json:"track_number"`
Markers []string `json:"markers"`
// Verdict is "suspect" while the track is held back from radio and the
// mixes, "fine" once an admin let it back, null before the resolver's
// first pass. VerdictAt is when it was last set.
Verdict *string `json:"verdict"`
VerdictAt *string `json:"verdict_at"`
}
// suspectGroupView is a folder's worth of flagged tracks. As on the
// missing-files report, the folder is the unit of decision: Mammalz was 62 rows
// in one folder, which is one problem to look at, not 62.
type suspectGroupView struct {
Directory string `json:"directory"`
Tracks []suspectTrackView `json:"tracks"`
}
// adminSuspectSourcesResponse is the paged envelope. Total counts tracks.
type adminSuspectSourcesResponse struct {
Total int64 `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Groups []suspectGroupView `json:"groups"`
}
// handleListSuspectSources implements GET /api/admin/library/suspect-sources.
//
// A marker is a reason to look, not proof: a band can title a song "Music
// Video". The duplicate resolver holds a flagged track back from radio and the
// mixes and merges it away where a clean copy exists; this report
// is where an admin sees that and can say a track is fine.
func (h *handlers) handleListSuspectSources(w http.ResponseWriter, r *http.Request) {
limit, offset, err := parsePaging(r.URL.Query())
if err != nil {
writeErr(w, apierror.BadRequest("invalid_paging", "invalid limit or offset"))
return
}
q := dbq.New(h.pool)
total, err := q.CountSuspectSourceTracks(r.Context(), library.SuspectSourcePattern)
if err != nil {
h.logger.Error("admin: count suspect-source tracks", "err", err)
writeErr(w, apierror.Internal(err))
return
}
rows, err := q.ListSuspectSourceTracks(r.Context(), dbq.ListSuspectSourceTracksParams{
Pattern: library.SuspectSourcePattern,
PageLimit: int32(limit),
PageOffset: int32(offset),
})
if err != nil {
h.logger.Error("admin: list suspect-source tracks", "err", err)
writeErr(w, apierror.Internal(err))
return
}
writeJSON(w, http.StatusOK, adminSuspectSourcesResponse{
Total: total,
Limit: limit,
Offset: offset,
Groups: groupSuspectByDirectory(rows),
})
}
// groupSuspectByDirectory folds the directory-ordered rows into per-folder
// groups, the same run-length fold as groupMissingByDirectory. A page boundary
// can split a folder; the web page joins the halves.
func groupSuspectByDirectory(rows []dbq.ListSuspectSourceTracksRow) []suspectGroupView {
groups := make([]suspectGroupView, 0, 8)
for _, row := range rows {
t := suspectTrackView{
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,
Markers: library.SourceMarkersFor(row.FilePath),
Verdict: row.SourceVerdict,
}
if row.SourceVerdictAt.Valid {
at := row.SourceVerdictAt.Time.UTC().Format(time.RFC3339)
t.VerdictAt = &at
}
if n := len(groups); n > 0 && groups[n-1].Directory == row.Directory {
groups[n-1].Tracks = append(groups[n-1].Tracks, t)
continue
}
groups = append(groups, suspectGroupView{
Directory: row.Directory,
Tracks: []suspectTrackView{t},
})
}
return groups
}
type suspectVerdictRequest struct {
Verdict string `json:"verdict"`
}
// handleSetSuspectSourceVerdict implements PUT
// /api/admin/library/suspect-sources/{id}: {"verdict": "fine"} lets a flagged
// track back into radio and the mixes for good, {"verdict": "suspect"} holds
// it back again. 404 suspect_track_not_found when the track was never flagged.
func (h *handlers) handleSetSuspectSourceVerdict(w http.ResponseWriter, r *http.Request) {
id, ok := parseUUID(chi.URLParam(r, "id"))
if !ok {
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return
}
var req suspectVerdictRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, apierror.BadRequest("invalid_body", "invalid request body"))
return
}
if req.Verdict != "fine" && req.Verdict != "suspect" {
writeErr(w, apierror.BadRequest("invalid_verdict", "verdict must be fine or suspect"))
return
}
n, err := dbq.New(h.pool).SetTrackSourceVerdict(r.Context(), dbq.SetTrackSourceVerdictParams{Verdict: req.Verdict, ID: id})
if err != nil {
h.logger.Error("admin: set suspect-source verdict", "err", err)
writeErr(w, apierror.Internal(err))
return
}
if n == 0 {
writeErr(w, apierror.New(http.StatusNotFound, "suspect_track_not_found", "that track is not on the suspect list"))
return
}
writeJSON(w, http.StatusOK, map[string]string{"verdict": req.Verdict})
}
// handleRemoveSuspectSourceFile implements POST
// /api/admin/library/suspect-sources/{id}/remove: the rip's file goes and the
// track stays, missing, until a clean copy lands in the library. Its
// recording MBID goes with the file, since a video rip is often another
// recording of the song (a live take, a video edit).
//
// Errors: 404 suspect_track_not_found when the track is gone, missing, or its
// file name carries no video-title marker; 409 library_not_writable / 500
// file_delete_failed when the file could not be removed.
func (h *handlers) handleRemoveSuspectSourceFile(w http.ResponseWriter, r *http.Request) {
admin, ok := requireUser(w, r)
if !ok {
return
}
id, ok := parseUUID(chi.URLParam(r, "id"))
if !ok {
writeErr(w, apierror.BadRequest("invalid_id", "invalid id"))
return
}
track, err := dbq.New(h.pool).GetTrackByID(r.Context(), id)
if errors.Is(err, pgx.ErrNoRows) || (err == nil && (track.MissingSince.Valid || len(library.SourceMarkersFor(track.FilePath)) == 0)) {
writeErr(w, apierror.New(http.StatusNotFound, "suspect_track_not_found", "that track is not on the suspect list"))
return
}
if err != nil {
h.logger.Error("admin: read suspect track", "err", err)
writeErr(w, apierror.Internal(err))
return
}
if _, err := library.RemoveFile(r.Context(), h.pool, h.logger, library.RemoveFileParams{
TrackID: id, ActorID: admin.ID, Reason: library.RemovedForSuspect, ForgetMBID: true,
}); err != nil {
if apiErr, ok := fileRemoveAPIError(err); ok {
logFileRemoveFailure(h.logger, apiErr, "track_id", uuidToString(id))
writeErr(w, apiErr)
return
}
if errors.Is(err, library.ErrTrackNotFound) {
writeErr(w, apierror.New(http.StatusNotFound, "suspect_track_not_found", "that track is not on the suspect list"))
return
}
h.logger.Error("admin: remove suspect file", "err", err)
writeErr(w, apierror.New(http.StatusInternalServerError, "file_delete_failed", "the file could not be deleted"))
return
}
audit.WriteOrLog(r.Context(), h.pool, h.logger, admin.ID, pgtype.UUID{}, audit.ActionSuspectFileRemove, map[string]any{
"track_id": uuidToString(id), "title": track.Title, "file_path": track.FilePath,
})
w.WriteHeader(http.StatusNoContent)
}