sonda/internal/api/http/handlers_duplicates.go
tgiachi 30f45bb383 feat(api): list the duplicate songs, check their files and delete the extra copies
Admin only. GET /library/duplicates lists the groups with what is needed to choose and never a path; POST|GET|DELETE /library/duplicates/check is the job that fingerprints the files; POST /library/duplicates/clean deletes the chosen copies of one song, each refusal with its own status and code (deletion_disabled, scan_running, invalid_input, track_not_found, duplicate_changed, library_read_only). In the spec with the contract test, and wired in main, where an info line says when library.allow_delete is on.
2026-11-12 16:46:50 +01:00

169 lines
5.6 KiB
Go

package httpapi
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"codeberg.org/squidd/sonda/internal/duplicates"
"codeberg.org/squidd/sonda/internal/jobs"
)
// duplicateHandlers serve the admin's view of the songs that are in more than one file, and the
// removal of the extra copies. File paths never appear in any answer.
type duplicateHandlers struct{ svc duplicateService }
const (
defaultDuplicatesLimit = 50
maxDuplicatesLimit = 200
)
type duplicateFileJSON struct {
TrackID int64 `json:"track_id"`
Album *albumRefJSON `json:"album"`
Format string `json:"format"`
Bitrate int `json:"bitrate"`
SizeBytes int64 `json:"size_bytes"`
DurationMs int64 `json:"duration_ms"`
Hashed bool `json:"hashed"`
}
type duplicateGroupJSON struct {
Title string `json:"title"`
Artists []artistRefJSON `json:"artists"`
Files []duplicateFileJSON `json:"files"`
Hashed bool `json:"hashed"`
Identical bool `json:"identical"`
SuggestedID int64 `json:"suggested_keep_track_id"`
FreedBytes int64 `json:"freed_bytes"`
}
type duplicatePageJSON struct {
DeletionAllowed bool `json:"deletion_allowed"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Groups []duplicateGroupJSON `json:"groups"`
}
// list gives the groups of copies, a page at a time.
func (h *duplicateHandlers) list(c *gin.Context) {
limit, ok := queryInt(c, "limit")
if !ok {
return
}
offset, ok := queryInt(c, "offset")
if !ok {
return
}
if limit < 0 || offset < 0 {
writeError(c, http.StatusBadRequest, "invalid_input", "limit and offset cannot be negative")
return
}
size := clampInt(limit)
if size == 0 {
size = defaultDuplicatesLimit
}
size = min(size, maxDuplicatesLimit)
page, err := h.svc.Groups(c.Request.Context(), size, clampInt(offset))
if err != nil {
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
out := duplicatePageJSON{
DeletionAllowed: page.DeletionAllowed, Total: page.Total, Limit: size, Offset: clampInt(offset),
Groups: make([]duplicateGroupJSON, len(page.Groups)),
}
for i, g := range page.Groups {
out.Groups[i] = toDuplicateGroupJSON(g)
}
c.JSON(http.StatusOK, out)
}
func toDuplicateGroupJSON(g duplicates.Group) duplicateGroupJSON {
out := duplicateGroupJSON{
Title: g.Title, Artists: make([]artistRefJSON, len(g.Artists)), Files: make([]duplicateFileJSON, len(g.Files)),
Hashed: g.Hashed, Identical: g.Identical, SuggestedID: g.KeepTrackID, FreedBytes: g.FreedBytes,
}
for i, a := range g.Artists {
out.Artists[i] = artistRefJSON{ID: a.ID, Name: a.Name}
}
for i, f := range g.Files {
file := duplicateFileJSON{
TrackID: f.TrackID, Format: f.Format, Bitrate: f.BitRate, SizeBytes: f.SizeBytes, DurationMs: f.DurationMs, Hashed: f.Hash != "",
}
if f.AlbumID != 0 {
file.Album = &albumRefJSON{ID: f.AlbumID, Title: f.Album}
}
out.Files[i] = file
}
return out
}
type cleanRequest struct {
KeepTrackID int64 `json:"keep_track_id"`
RemoveTrackIDs []int64 `json:"remove_track_ids"`
}
// clean removes the copies named of one song, keeping the one named.
func (h *duplicateHandlers) clean(c *gin.Context) {
var req cleanRequest
if !bindJSON(c, &req) {
return
}
if req.KeepTrackID <= 0 || len(req.RemoveTrackIDs) == 0 {
writeError(c, http.StatusBadRequest, "invalid_input", "name the copy to keep and at least one copy to remove")
return
}
for _, id := range req.RemoveTrackIDs {
if id <= 0 {
writeError(c, http.StatusBadRequest, "invalid_input", "track ids must be positive numbers")
return
}
}
res, err := h.svc.Clean(c.Request.Context(), req.KeepTrackID, req.RemoveTrackIDs)
if err != nil {
writeDuplicatesError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"removed": res.Removed, "freed_bytes": res.FreedBytes})
}
// writeDuplicatesError gives each way a removal is refused its own status and code, so a client can tell them apart.
func writeDuplicatesError(c *gin.Context, err error) {
switch {
case errors.Is(err, duplicates.ErrDisabled):
writeError(c, http.StatusConflict, "deletion_disabled", "deleting files is not turned on: set library.allow_delete")
case errors.Is(err, duplicates.ErrScanRunning):
writeError(c, http.StatusConflict, "scan_running", "wait for the running scan to finish")
case errors.Is(err, duplicates.ErrInvalid):
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
case errors.Is(err, duplicates.ErrTrackNotFound):
writeError(c, http.StatusNotFound, "track_not_found", "no such track")
case errors.Is(err, duplicates.ErrChanged):
writeError(c, http.StatusConflict, "duplicate_changed", "a file is not what the last scan saw: scan again")
case errors.Is(err, duplicates.ErrReadOnly):
writeError(c, http.StatusConflict, "library_read_only", "the music folder cannot be written to")
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
}
type duplicatesCheckSummaryJSON struct {
Checked int `json:"checked"`
Hashed int `json:"hashed"`
Skipped int `json:"skipped"`
Failed int `json:"failed"`
Stopped bool `json:"stopped"`
}
// duplicatesCheckSummary is the summary of the job that fingerprints the files of the groups.
func duplicatesCheckSummary(s *jobs.Summary) any {
return duplicatesCheckSummaryJSON{
Checked: s.Checked, Hashed: s.Outcomes[duplicates.OutcomeHashed], Skipped: s.Skipped, Failed: s.Failed, Stopped: s.Stopped,
}
}