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 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"` 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. // // Grouping is the whole ergonomic argument for this surface: a reorganised // album shows up as dozens of individually missing files, which presented flat // reads as dozens of problems and presented by folder reads as one. // MissingSince is the EARLIEST mark in the group, so a directory sorts and // reads by when it first went away. type missingGroupView struct { Directory string `json:"directory"` MissingSince string `json:"missing_since"` Tracks []missingTrackView `json:"tracks"` } // adminMissingResponse is the paged envelope. Total counts TRACKS, not // groups — it is what the nav badge shows, and "12 files missing" is the // honest number even when they happen to sit in two folders. type adminMissingResponse struct { Total int64 `json:"total"` Limit int `json:"limit"` Offset int `json:"offset"` Groups []missingGroupView `json:"groups"` } // 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 { writeAdminJSONErr(w, http.StatusBadRequest, "invalid_paging") return } 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(limit), PageOffset: int32(offset), }) if err != nil { h.logger.Error("admin: list missing tracks", "err", err) writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") return } groups := groupMissingByDirectory(rows) out := adminMissingResponse{ Total: total, Limit: limit, Offset: offset, Groups: groups, } writeJSON(w, http.StatusOK, out) } // groupMissingByDirectory folds the ordered rows into per-directory groups. // // It relies on ListMissingTracks ordering by directory, so a simple run-length // fold is enough and no map is needed — which also preserves the query's // ordering in the response instead of Go's random map iteration. A page // boundary can split one directory across two pages; that is accepted rather // than paging by group, because the alternative costs a second query to find // the page's directories and this surface's realistic N is small. 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, 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) t.LastPlayedAt = &s } 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, missingGroupView{ Directory: row.Directory, // First row of a run carries the group's timestamp. Rows are // ordered within a directory by disc/track, not by mark time, so // this is "the mark on the first track" rather than the minimum — // they are the same value in the case that matters (a whole folder // vanishing at once) and close enough otherwise. MissingSince: t.MissingSince, Tracks: []missingTrackView{t}, }) } 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 }