feat: Minstrel stops acquiring music and drops Discover
release / go (push) Successful in 1m54s
release / web (push) Failing after 5s
release / integration (push) Failing after 3m44s
release / govulncheck (push) Successful in 20s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 19s
release / android (push) Canceled after 2m37s
release / go (push) Successful in 1m54s
release / web (push) Failing after 5s
release / integration (push) Failing after 3m44s
release / govulncheck (push) Successful in 20s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 19s
release / android (push) Canceled after 2m37s
Minstrel is now a viewer of the library it is pointed at. Finding, downloading and filing music moves out of it. Removed from the server: - the request flow (requests, approval, auto-approve) and the wanted list, follows, release profiles and release blocks; - searching indexers, the download clients, the importer, the album lifecycle and missing-file re-acquisition; - the catalogue's discography, search and art (the MusicBrainz release and track-list cache stays, for the duplicate resolver); - Discover: its suggestions of artists not in the library, snoozes, the candidate-artist tag enrichment and its tuning scope; - writes to acquisition tables from moving the library folder and from merging duplicates, the want-list join on Suspect sources, the sealing of acquisition credentials, and the release-group lookup only re-acquisition used. Settling a wrong-slot duplicate no longer sets the release aside: the copies go and their slots show as missing until a good copy is in the library. Removed from the web: Admin > Acquisition and Requests, /requests, /discover, Follow on the artist page, the auto-approve toggle, and the Collection's wanted-list tabs. The Collection is now the library's health: an overview, Reports, Duplicates, Suspect sources and Missing files. The README and docs no longer describe getting music. The tables stay for now; a later migration drops them. The request notification kinds and the Android screens are still to go. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,210 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/acquire"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// Indexers and download clients, admin side. Rows an admin
|
||||
// adds and configures; nothing is seeded. Secrets are write-only: no response
|
||||
// carries one, only whether it is set.
|
||||
|
||||
// acquisitionBodyLimit caps a settings body. The largest is a full form of
|
||||
// short strings.
|
||||
const acquisitionBodyLimit = 64 << 10
|
||||
|
||||
type acquisitionServiceResp struct {
|
||||
Code string `json:"code"`
|
||||
Kind string `json:"kind"`
|
||||
Protocol string `json:"protocol"`
|
||||
Label string `json:"label"`
|
||||
Enabled bool `json:"enabled"`
|
||||
BaseURL string `json:"base_url"`
|
||||
HasAPIKey bool `json:"has_api_key"`
|
||||
HasPassword bool `json:"has_password"`
|
||||
Username string `json:"username"`
|
||||
Category string `json:"category"`
|
||||
TimeoutMs int32 `json:"timeout_ms"`
|
||||
ServesSearch bool `json:"serves_search"`
|
||||
ServesDownloads bool `json:"serves_downloads"`
|
||||
ServesEnrichment bool `json:"serves_enrichment"`
|
||||
LocalPath string `json:"local_path"`
|
||||
RemotePath string `json:"remote_path"`
|
||||
SearchesPerHour int32 `json:"searches_per_hour"`
|
||||
// Usable is switched on and addressed: the state the jobs read.
|
||||
Usable bool `json:"usable"`
|
||||
}
|
||||
|
||||
func acquisitionRespOf(r dbq.AcquisitionService) acquisitionServiceResp {
|
||||
return acquisitionServiceResp{
|
||||
Code: r.Code, Kind: r.Kind, Protocol: r.Protocol, Label: r.Label,
|
||||
Enabled: r.Enabled, BaseURL: r.BaseUrl,
|
||||
HasAPIKey: r.ApiKey != "", HasPassword: r.Password != "",
|
||||
Username: r.Username, Category: r.Category, TimeoutMs: r.TimeoutMs,
|
||||
ServesSearch: r.ServesSearch, ServesDownloads: r.ServesDownloads,
|
||||
ServesEnrichment: r.ServesEnrichment,
|
||||
LocalPath: r.LocalPath, RemotePath: r.RemotePath,
|
||||
SearchesPerHour: r.SearchesPerHour,
|
||||
Usable: r.Enabled && r.BaseUrl != "",
|
||||
}
|
||||
}
|
||||
|
||||
// handleListAcquisitionServices implements GET /api/admin/acquisition/services.
|
||||
func (h *handlers) handleListAcquisitionServices(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := h.acquisition.List(r.Context())
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin: list acquisition services", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := make([]acquisitionServiceResp, len(rows))
|
||||
for i, row := range rows {
|
||||
out[i] = acquisitionRespOf(dbq.AcquisitionService{
|
||||
Code: row.Code, Kind: row.Kind, Protocol: row.Protocol, Label: row.Label,
|
||||
Enabled: row.Enabled, BaseUrl: row.BaseUrl, Username: row.Username,
|
||||
Category: row.Category, TimeoutMs: row.TimeoutMs,
|
||||
ServesSearch: row.ServesSearch, ServesDownloads: row.ServesDownloads,
|
||||
ServesEnrichment: row.ServesEnrichment, LocalPath: row.LocalPath,
|
||||
RemotePath: row.RemotePath, SearchesPerHour: row.SearchesPerHour,
|
||||
})
|
||||
out[i].HasAPIKey, out[i].HasPassword = row.HasApiKey, row.HasPassword
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"services": out})
|
||||
}
|
||||
|
||||
// handleCreateAcquisitionService implements POST
|
||||
// /api/admin/acquisition/services with {"protocol":
|
||||
// "prowlarr"|"torznab"|"qbittorrent"|"exchange"}. The row starts switched off,
|
||||
// with no address.
|
||||
func (h *handlers) handleCreateAcquisitionService(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Protocol string `json:"protocol"`
|
||||
}
|
||||
if !decodeAcquisitionBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
row, err := h.acquisition.Create(r.Context(), body.Protocol)
|
||||
if err != nil {
|
||||
h.writeAcquisitionErr(w, "admin: create acquisition service", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, acquisitionRespOf(row))
|
||||
}
|
||||
|
||||
type updateAcquisitionBody struct {
|
||||
Label string `json:"label"`
|
||||
Enabled bool `json:"enabled"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
Category string `json:"category"`
|
||||
TimeoutMs int32 `json:"timeout_ms"`
|
||||
ServesSearch bool `json:"serves_search"`
|
||||
ServesDownloads bool `json:"serves_downloads"`
|
||||
ServesEnrichment bool `json:"serves_enrichment"`
|
||||
LocalPath string `json:"local_path"`
|
||||
RemotePath string `json:"remote_path"`
|
||||
SearchesPerHour int32 `json:"searches_per_hour"`
|
||||
}
|
||||
|
||||
// handleUpdateAcquisitionService implements PUT
|
||||
// /api/admin/acquisition/services/{code}: the whole form except credentials.
|
||||
func (h *handlers) handleUpdateAcquisitionService(w http.ResponseWriter, r *http.Request) {
|
||||
var body updateAcquisitionBody
|
||||
if !decodeAcquisitionBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
row, err := h.acquisition.Save(r.Context(), chi.URLParam(r, "code"), acquire.Update(body))
|
||||
if err != nil {
|
||||
h.writeAcquisitionErr(w, "admin: update acquisition service", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, acquisitionRespOf(row))
|
||||
}
|
||||
|
||||
// handleDeleteAcquisitionService implements DELETE
|
||||
// /api/admin/acquisition/services/{code}.
|
||||
func (h *handlers) handleDeleteAcquisitionService(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h.acquisition.Delete(r.Context(), chi.URLParam(r, "code")); err != nil {
|
||||
h.writeAcquisitionErr(w, "admin: delete acquisition service", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleTestAcquisitionService implements POST
|
||||
// /api/admin/acquisition/services/{code}/test. POST because it reaches
|
||||
// another machine, which a prefetch must not trigger. Always 200 with
|
||||
// {ok, detail}: a failed connection is the answer, not an error.
|
||||
func (h *handlers) handleTestAcquisitionService(w http.ResponseWriter, r *http.Request) {
|
||||
row, err := h.acquisition.Get(r.Context(), chi.URLParam(r, "code"))
|
||||
if err != nil {
|
||||
h.writeAcquisitionErr(w, "admin: test acquisition service", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, acquire.Test(r.Context(), row))
|
||||
}
|
||||
|
||||
// handleSetAcquisitionSecret implements PUT and DELETE on
|
||||
// /api/admin/acquisition/services/{code}/api-key and .../password. PUT takes
|
||||
// {"value": "..."}; DELETE clears it. 204 with no body either way: echoing
|
||||
// anything here is how a secret ends up in a response.
|
||||
func (h *handlers) handleSetAcquisitionSecret(field string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
value := ""
|
||||
if r.Method == http.MethodPut {
|
||||
var body struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
if !decodeAcquisitionBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if body.Value == "" {
|
||||
writeErr(w, apierror.BadRequest("invalid_setting", "Paste a value, or use Remove to clear the one that is set."))
|
||||
return
|
||||
}
|
||||
value = body.Value
|
||||
}
|
||||
code := chi.URLParam(r, "code")
|
||||
var err error
|
||||
if field == "password" {
|
||||
err = h.acquisition.SetPassword(r.Context(), code, value)
|
||||
} else {
|
||||
err = h.acquisition.SetAPIKey(r.Context(), code, value)
|
||||
}
|
||||
if err != nil {
|
||||
h.writeAcquisitionErr(w, "admin: set acquisition "+field, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeAcquisitionBody(w http.ResponseWriter, r *http.Request, into any) bool {
|
||||
err := json.NewDecoder(http.MaxBytesReader(w, r.Body, acquisitionBodyLimit)).Decode(into)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *handlers) writeAcquisitionErr(w http.ResponseWriter, msg string, err error) {
|
||||
var invalid *acquire.InvalidError
|
||||
switch {
|
||||
case errors.As(err, &invalid):
|
||||
writeErr(w, apierror.BadRequest("invalid_setting", invalid.Message))
|
||||
case errors.Is(err, acquire.ErrNotFound):
|
||||
writeErr(w, apierror.NotFound("service"))
|
||||
case errors.Is(err, acquire.ErrTooMany):
|
||||
writeErr(w, apierror.Conflict("too_many_services", "There are already twenty of these. Remove one you no longer use first."))
|
||||
default:
|
||||
writeErrWithLog(w, h.logger, msg, apierror.Internal(err))
|
||||
}
|
||||
}
|
||||
@@ -459,21 +459,19 @@ type refetchDuplicateRequest struct {
|
||||
KeepTrackID string `json:"keep_track_id"`
|
||||
}
|
||||
|
||||
// refetchDuplicateResponse reports what went. Blocked names the releases set
|
||||
// aside; empty when the album came from before Minstrel downloaded anything.
|
||||
// refetchDuplicateResponse reports what went.
|
||||
type refetchDuplicateResponse struct {
|
||||
KeptTrackID *string `json:"kept_track_id"`
|
||||
RemovedPaths []string `json:"removed_paths"`
|
||||
Blocked []string `json:"blocked"`
|
||||
}
|
||||
|
||||
// handleRefetchDuplicateGroup implements POST
|
||||
// /api/admin/library/duplicates/{id}/refetch: settle a group of one
|
||||
// recording in several slots of an album the way the resolver would, with an
|
||||
// admin's answer. The copies in slots that are not the recording's are
|
||||
// removed and marked missing, the release they came from is set aside, and the
|
||||
// album is wanted again. Merge is the wrong action there: it keeps one title
|
||||
// whether or not it is the audio's, and fetches nothing.
|
||||
// removed and marked missing, so the slot shows as missing until a good copy
|
||||
// arrives in the library. Merge is the wrong action there: it keeps one title
|
||||
// whether or not it is the audio's.
|
||||
//
|
||||
// Errors:
|
||||
// - 409 library_not_writable / 500 file_delete_failed when a file could not be
|
||||
@@ -525,10 +523,7 @@ func (h *handlers) handleRefetchDuplicateGroup(w http.ResponseWriter, r *http.Re
|
||||
return
|
||||
}
|
||||
|
||||
resp := refetchDuplicateResponse{RemovedPaths: make([]string, 0, len(res.Removed)), Blocked: res.Blocked}
|
||||
if resp.Blocked == nil {
|
||||
resp.Blocked = []string{}
|
||||
}
|
||||
resp := refetchDuplicateResponse{RemovedPaths: make([]string, 0, len(res.Removed))}
|
||||
if res.Kept != nil {
|
||||
id := uuidToString(res.Kept.TrackID)
|
||||
resp.KeptTrackID = &id
|
||||
|
||||
@@ -1,285 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/importer"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/lifecycle"
|
||||
)
|
||||
|
||||
// Downloads and their imports: the Wanted view's Activity tab,
|
||||
// a person's "import anyway", "refuse" and "retry", and the Blocked tab.
|
||||
|
||||
// downloadView is one grab and what its import made of it.
|
||||
type downloadView struct {
|
||||
ID string `json:"id"`
|
||||
WantID *string `json:"want_id"`
|
||||
WantTitle string `json:"want_title"`
|
||||
WantArtist string `json:"want_artist"`
|
||||
Name string `json:"name"`
|
||||
Indexer string `json:"indexer"`
|
||||
Client string `json:"client"`
|
||||
Quality string `json:"quality"`
|
||||
Origin string `json:"origin"`
|
||||
GrabbedAt string `json:"grabbed_at"`
|
||||
EndedAt *string `json:"ended_at"`
|
||||
EndReason string `json:"end_reason"`
|
||||
Progress float32 `json:"progress"`
|
||||
ImportState string `json:"import_state"`
|
||||
ImportReason string `json:"import_reason"`
|
||||
ImportedAt *string `json:"imported_at"`
|
||||
ImportedFiles int32 `json:"imported_files"`
|
||||
Destination string `json:"destination"`
|
||||
Edition string `json:"edition,omitempty"`
|
||||
Evidence *importer.Evidence `json:"evidence,omitempty"`
|
||||
Files []string `json:"files"`
|
||||
Skipped int `json:"skipped"`
|
||||
RehomedFrom string `json:"rehomed_from,omitempty"`
|
||||
// EndDetail says why an ended download ended.
|
||||
EndDetail string `json:"end_detail"`
|
||||
// Seeding: imported and still sharing; Ratio its share ratio as last
|
||||
// read; SeedReleasedAt when it was removed once it had shared enough.
|
||||
Seeding bool `json:"seeding"`
|
||||
Ratio float32 `json:"ratio"`
|
||||
SeedReleasedAt *string `json:"seed_released_at"`
|
||||
// Condition is what is wrong with it now, if anything.
|
||||
Condition *conditionView `json:"condition"`
|
||||
}
|
||||
|
||||
// conditionView is an open row of the intervention ledger: what was seen,
|
||||
// since when, and how many times it was retried.
|
||||
type conditionView struct {
|
||||
Trigger string `json:"trigger"`
|
||||
Detail string `json:"detail"`
|
||||
Retries int32 `json:"retries"`
|
||||
Since string `json:"since"`
|
||||
}
|
||||
|
||||
func downloadFrom(g dbq.ListGrabsRow) downloadView {
|
||||
v := downloadView{
|
||||
ID: uuidToString(g.ID), Name: g.Name, Indexer: g.Indexer, Client: g.Client, Quality: g.Quality,
|
||||
Origin: g.Origin, GrabbedAt: formatTimestamp(g.GrabbedAt), EndReason: g.EndReason,
|
||||
Progress: g.Progress, ImportState: g.ImportState, ImportReason: g.ImportReason,
|
||||
ImportedFiles: g.ImportedFiles, Destination: g.Destination, Files: []string{},
|
||||
EndDetail: g.EndDetail, Seeding: g.Seeding, Ratio: g.Ratio,
|
||||
}
|
||||
if g.SeedReleasedAt.Valid {
|
||||
at := formatTimestamp(g.SeedReleasedAt)
|
||||
v.SeedReleasedAt = &at
|
||||
}
|
||||
if g.Condition != nil {
|
||||
v.Condition = &conditionView{Trigger: *g.Condition, Detail: deref(g.ConditionDetail),
|
||||
Since: formatTimestamp(g.ConditionSince)}
|
||||
if g.ConditionRetries != nil {
|
||||
v.Condition.Retries = *g.ConditionRetries
|
||||
}
|
||||
}
|
||||
if g.WantID.Valid {
|
||||
id := uuidToString(g.WantID)
|
||||
v.WantID = &id
|
||||
}
|
||||
if g.WantTitle != nil {
|
||||
v.WantTitle = *g.WantTitle
|
||||
}
|
||||
if g.WantArtist != nil {
|
||||
v.WantArtist = *g.WantArtist
|
||||
}
|
||||
if g.EndedAt.Valid {
|
||||
at := formatTimestamp(g.EndedAt)
|
||||
v.EndedAt = &at
|
||||
}
|
||||
if g.ImportedAt.Valid {
|
||||
at := formatTimestamp(g.ImportedAt)
|
||||
v.ImportedAt = &at
|
||||
}
|
||||
var det importer.Detail
|
||||
if len(g.ImportDetail) > 0 && json.Unmarshal(g.ImportDetail, &det) == nil && det.Verdict.Outcome != "" {
|
||||
ev := det.Verdict.Evidence
|
||||
v.Evidence, v.Edition, v.Skipped, v.RehomedFrom = &ev, det.Edition, det.Skipped, det.RehomedFrom
|
||||
if det.Files != nil {
|
||||
v.Files = det.Files
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
type downloadsPage struct {
|
||||
Items []downloadView `json:"items"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
// ClientsDown are the download clients not answering now.
|
||||
ClientsDown []clientDownView `json:"clients_down"`
|
||||
}
|
||||
|
||||
type clientDownView struct {
|
||||
Client string `json:"client"`
|
||||
Detail string `json:"detail"`
|
||||
Since string `json:"since"`
|
||||
}
|
||||
|
||||
// handleListDownloads implements GET /api/admin/downloads?offset=: running
|
||||
// downloads first, then the rest newest first.
|
||||
func (h *handlers) handleListDownloads(w http.ResponseWriter, r *http.Request) {
|
||||
limit, offset, err := parsePaging(r.URL.Query())
|
||||
if err != nil {
|
||||
writeErr(w, apierror.BadRequest("invalid_paging", "limit and offset must be numbers"))
|
||||
return
|
||||
}
|
||||
rows, err := dbq.New(h.pool).ListGrabs(r.Context(), dbq.ListGrabsParams{MaxRows: int32(limit), Skip: int32(offset)})
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin downloads: list", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
down, err := dbq.New(h.pool).ListClientsDown(r.Context())
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin downloads: clients down", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := downloadsPage{Items: make([]downloadView, 0, len(rows)), Limit: limit, Offset: offset,
|
||||
ClientsDown: make([]clientDownView, 0, len(down))}
|
||||
for _, g := range rows {
|
||||
out.Items = append(out.Items, downloadFrom(g))
|
||||
}
|
||||
for _, c := range down {
|
||||
out.ClientsDown = append(out.ClientsDown, clientDownView{Client: c.Client, Detail: c.Detail,
|
||||
Since: formatTimestamp(c.FirstSeen)})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// handleAbandonDownload implements POST /api/admin/downloads/{id}/abandon: a
|
||||
// running download is given up, its release set aside, the download removed
|
||||
// and the album searched again.
|
||||
func (h *handlers) handleAbandonDownload(w http.ResponseWriter, r *http.Request) {
|
||||
admin, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.lifecycle.Abandon(r.Context(), id, admin.ID); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows), errors.Is(err, lifecycle.ErrNotAbandonable):
|
||||
writeErr(w, apierror.Conflict("not_running", "that download is no longer running"))
|
||||
default:
|
||||
writeErrWithLog(w, h.logger, "admin downloads: abandon", apierror.Internal(err))
|
||||
}
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleImportAnyway implements POST /api/admin/downloads/{id}/import: a
|
||||
// download the check held for a person (or one that failed) is imported on
|
||||
// the next pass whatever the check says.
|
||||
func (h *handlers) handleImportAnyway(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := dbq.New(h.pool).ForceGrabImport(r.Context(), id); err != nil {
|
||||
h.writeImportErr(w, "import anyway", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleRetryImport implements POST /api/admin/downloads/{id}/retry.
|
||||
func (h *handlers) handleRetryImport(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := dbq.New(h.pool).RetryGrabImport(r.Context(), id); err != nil {
|
||||
h.writeImportErr(w, "retry", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleRefuseDownload implements POST /api/admin/downloads/{id}/refuse: the
|
||||
// release is blocked, the download removed and the album searched again.
|
||||
func (h *handlers) handleRefuseDownload(w http.ResponseWriter, r *http.Request) {
|
||||
admin, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.importer.Refuse(r.Context(), id, admin.ID); err != nil {
|
||||
h.writeImportErr(w, "refuse", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *handlers) writeImportErr(w http.ResponseWriter, what string, err error) {
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows), errors.Is(err, importer.ErrNotDecidable):
|
||||
writeErr(w, apierror.Conflict("not_decidable", "that download is not waiting on a decision"))
|
||||
default:
|
||||
writeErrWithLog(w, h.logger, "admin downloads: "+what, apierror.Internal(err))
|
||||
}
|
||||
}
|
||||
|
||||
type releaseBlockView struct {
|
||||
InfoHash string `json:"info_hash"`
|
||||
Name string `json:"name"`
|
||||
Reason string `json:"reason"`
|
||||
Detail string `json:"detail"`
|
||||
BlockedAt string `json:"blocked_at"`
|
||||
// ExpiresAt is when a release given up on may be taken again; null is
|
||||
// for good.
|
||||
ExpiresAt *string `json:"expires_at"`
|
||||
WantTitle string `json:"want_title"`
|
||||
WantArtist string `json:"want_artist"`
|
||||
}
|
||||
|
||||
type releaseBlocksPage struct {
|
||||
Items []releaseBlockView `json:"items"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
|
||||
// handleListReleaseBlocks implements GET /api/admin/release-blocks?offset=:
|
||||
// every release set aside, by a person or by a check, newest first.
|
||||
func (h *handlers) handleListReleaseBlocks(w http.ResponseWriter, r *http.Request) {
|
||||
limit, offset, err := parsePaging(r.URL.Query())
|
||||
if err != nil {
|
||||
writeErr(w, apierror.BadRequest("invalid_paging", "limit and offset must be numbers"))
|
||||
return
|
||||
}
|
||||
rows, err := dbq.New(h.pool).ListReleaseBlocksPage(r.Context(), dbq.ListReleaseBlocksPageParams{
|
||||
MaxRows: int32(limit), Skip: int32(offset)})
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin release blocks: list", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := releaseBlocksPage{Items: make([]releaseBlockView, 0, len(rows)), Limit: limit, Offset: offset}
|
||||
for _, b := range rows {
|
||||
v := releaseBlockView{InfoHash: b.InfoHash, Name: b.Name, Reason: b.Reason, Detail: b.Detail,
|
||||
BlockedAt: formatTimestamp(b.BlockedAt)}
|
||||
if b.ExpiresAt.Valid {
|
||||
at := formatTimestamp(b.ExpiresAt)
|
||||
v.ExpiresAt = &at
|
||||
}
|
||||
if b.WantTitle != nil {
|
||||
v.WantTitle = *b.WantTitle
|
||||
}
|
||||
if b.WantArtist != nil {
|
||||
v.WantArtist = *b.WantArtist
|
||||
}
|
||||
out.Items = append(out.Items, v)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
@@ -2,9 +2,6 @@ package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
@@ -15,7 +12,7 @@ import (
|
||||
// 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 to bother re-acquiring one.
|
||||
// operator wants when deciding whether a lost file is worth replacing.
|
||||
type missingTrackView struct {
|
||||
TrackID string `json:"track_id"`
|
||||
Title string `json:"title"`
|
||||
@@ -29,18 +26,6 @@ type missingTrackView struct {
|
||||
LastPlayedAt *string `json:"last_played_at"`
|
||||
}
|
||||
|
||||
// reacquisitionStateView is what the wanted list says about one album: when
|
||||
// it was wanted back, and when the library
|
||||
// held it again. A missing album with no want yet is still inside the grace
|
||||
// window, or MusicBrainz cannot name it. Want is that want as the wanted list
|
||||
// sends it, so the Missing page can show its search and download and act on
|
||||
// it.
|
||||
type reacquisitionStateView struct {
|
||||
WantedAt *string `json:"wanted_at"`
|
||||
HeldAt *string `json:"held_at"`
|
||||
Want *wantView `json:"want"`
|
||||
}
|
||||
|
||||
// missingGroupView is a directory's worth of missing tracks.
|
||||
//
|
||||
// Grouping is the whole ergonomic argument for this surface: a reorganised
|
||||
@@ -52,10 +37,6 @@ type missingGroupView struct {
|
||||
Directory string `json:"directory"`
|
||||
MissingSince string `json:"missing_since"`
|
||||
Tracks []missingTrackView `json:"tracks"`
|
||||
// Nil when nothing has been attempted for this group's album — the
|
||||
// common case for a folder that just went missing, and distinct from
|
||||
// an attempts:0 record, which cannot occur.
|
||||
Reacquisition *reacquisitionStateView `json:"reacquisition"`
|
||||
}
|
||||
|
||||
// adminMissingResponse is the paged envelope. Total counts TRACKS, not
|
||||
@@ -99,7 +80,6 @@ func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Reques
|
||||
}
|
||||
|
||||
groups := groupMissingByDirectory(rows)
|
||||
h.attachReacquisitionState(r, q, rows, groups)
|
||||
|
||||
out := adminMissingResponse{
|
||||
Total: total,
|
||||
@@ -154,109 +134,3 @@ func groupMissingByDirectory(rows []dbq.ListMissingTracksRow) []missingGroupView
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
// attachReacquisitionState decorates each group with its album's want.
|
||||
//
|
||||
// Best-effort: this is context on a list whose primary job is showing what is
|
||||
// missing, so a failure here leaves the groups bare rather than failing the
|
||||
// page. One batched query for the whole page, not one per group.
|
||||
//
|
||||
// A group is keyed by directory while a want is keyed by album, and those
|
||||
// line up in practice (an album's files live in one folder) but are not
|
||||
// guaranteed to — a directory holding two albums takes the first album's
|
||||
// state, which is the same album its first track belongs to.
|
||||
func (h *handlers) attachReacquisitionState(
|
||||
r *http.Request,
|
||||
q *dbq.Queries,
|
||||
rows []dbq.ListMissingTracksRow,
|
||||
groups []missingGroupView,
|
||||
) {
|
||||
if len(groups) == 0 {
|
||||
return
|
||||
}
|
||||
// Directory -> the album its first row belongs to, matching the order
|
||||
// groupMissingByDirectory folded them in.
|
||||
dirAlbum := make(map[string]pgtype.UUID, len(groups))
|
||||
ids := make([]pgtype.UUID, 0, len(groups))
|
||||
// The latest loss in each folder: a want held before it is the album
|
||||
// as it was before its files went, not the library holding it again.
|
||||
dirLost := make(map[string]time.Time, len(groups))
|
||||
for _, row := range rows {
|
||||
if row.MissingSince.Valid && row.MissingSince.Time.After(dirLost[row.Directory]) {
|
||||
dirLost[row.Directory] = row.MissingSince.Time
|
||||
}
|
||||
if _, seen := dirAlbum[row.Directory]; seen {
|
||||
continue
|
||||
}
|
||||
dirAlbum[row.Directory] = row.AlbumID
|
||||
ids = append(ids, row.AlbumID)
|
||||
}
|
||||
|
||||
wants, err := q.GetWantsForAlbums(r.Context(), ids)
|
||||
if err != nil {
|
||||
h.logger.Warn("admin missing: want lookup failed", "err", err)
|
||||
return
|
||||
}
|
||||
// Newest want first, so the first seen per album is its current one.
|
||||
byAlbum := make(map[string]dbq.GetWantsForAlbumsRow, len(wants))
|
||||
for _, w := range wants {
|
||||
if _, seen := byAlbum[uuidToString(w.AlbumID)]; !seen {
|
||||
byAlbum[uuidToString(w.AlbumID)] = w
|
||||
}
|
||||
}
|
||||
full := h.wantViewsByID(r, q, byAlbum)
|
||||
for i := range groups {
|
||||
albumID, ok := dirAlbum[groups[i].Directory]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
w, ok := byAlbum[uuidToString(albumID)]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// Held before its files went (every library album is on the list,
|
||||
// held): not wanted back yet, which the sweep does once
|
||||
// the grace window has passed.
|
||||
if w.FulfilledAt.Valid && !w.FulfilledAt.Time.After(dirLost[groups[i].Directory]) {
|
||||
continue
|
||||
}
|
||||
view := &reacquisitionStateView{}
|
||||
wantedAt := formatTimestamp(w.WantedAt)
|
||||
view.WantedAt = &wantedAt
|
||||
if w.FulfilledAt.Valid {
|
||||
heldAt := formatTimestamp(w.FulfilledAt)
|
||||
view.HeldAt = &heldAt
|
||||
}
|
||||
if v, ok := full[uuidToString(w.WantID)]; ok {
|
||||
view.Want = &v
|
||||
}
|
||||
groups[i].Reacquisition = view
|
||||
}
|
||||
}
|
||||
|
||||
// wantViewsByID reads each album's current want in full, keyed by want id.
|
||||
// Best-effort like the state it decorates: a failure leaves the groups with
|
||||
// their dates and no want.
|
||||
func (h *handlers) wantViewsByID(
|
||||
r *http.Request,
|
||||
q *dbq.Queries,
|
||||
byAlbum map[string]dbq.GetWantsForAlbumsRow,
|
||||
) map[string]wantView {
|
||||
ids := make([]pgtype.UUID, 0, len(byAlbum))
|
||||
for _, w := range byAlbum {
|
||||
ids = append(ids, w.WantID)
|
||||
}
|
||||
out := make(map[string]wantView, len(ids))
|
||||
if len(ids) == 0 {
|
||||
return out
|
||||
}
|
||||
rows, err := q.ListWants(r.Context(), dbq.ListWantsParams{State: "all", WantIds: ids, MaxRows: int32(len(ids))})
|
||||
if err != nil {
|
||||
h.logger.Warn("admin missing: want detail lookup failed", "err", err)
|
||||
return out
|
||||
}
|
||||
for _, row := range rows {
|
||||
out[uuidToString(row.ID)] = wantViewOf(row)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
// seedMissingWant marks a track's file missing for two days and puts its
|
||||
// album on the wanted list, held at heldDaysAgo (0 for an open want) and
|
||||
// last searched with nothing found.
|
||||
func seedMissingWant(t *testing.T, h *handlers, trackID, albumID pgtype.UUID, group string, heldDaysAgo int) string {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
if _, err := h.pool.Exec(ctx,
|
||||
`UPDATE tracks SET missing_since = now() - interval '2 days' WHERE id = $1`, trackID); err != nil {
|
||||
t.Fatalf("mark missing: %v", err)
|
||||
}
|
||||
if _, err := h.pool.Exec(ctx, `DELETE FROM wants WHERE release_group_mbid = $1`, group); err != nil {
|
||||
t.Fatalf("clear want: %v", err)
|
||||
}
|
||||
var id pgtype.UUID
|
||||
if err := h.pool.QueryRow(ctx,
|
||||
`INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id,
|
||||
wanted_at, fulfilled_at, searched_at, search_outcome)
|
||||
VALUES ($1, 'artist-'||$1, 'Artist', 'Album '||$1, 'library', $2,
|
||||
now() - interval '30 days',
|
||||
CASE WHEN $3::int > 0 THEN now() - make_interval(days => $3::int) END,
|
||||
now() - interval '1 hour', 'nothing')
|
||||
RETURNING id`, group, albumID, heldDaysAgo).Scan(&id); err != nil {
|
||||
t.Fatalf("insert want: %v", err)
|
||||
}
|
||||
return uuidToString(id)
|
||||
}
|
||||
|
||||
// A folder's album that was held before its files went is not wanted back
|
||||
// yet (every library album is on the list, held); an open want comes with
|
||||
// its search, so the Missing page can show it and act on it.
|
||||
func TestListMissingTracks_WantState(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
admin := seedUser(t, pool, "admin", "pw", true)
|
||||
|
||||
heldTrack, _ := seedTrackOnDisk(t, h, "missheld")
|
||||
openTrack, _ := seedTrackOnDisk(t, h, "missopen")
|
||||
seedMissingWant(t, h, heldTrack.ID, heldTrack.AlbumID, "rg-missing-held", 10)
|
||||
openID := seedMissingWant(t, h, openTrack.ID, openTrack.AlbumID, "rg-missing-open", 0)
|
||||
|
||||
req := withUser(httptest.NewRequest(http.MethodGet, "/api/admin/library/missing", nil), admin)
|
||||
w := httptest.NewRecorder()
|
||||
h.handleListMissingTracks(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp adminMissingResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(resp.Groups) != 2 {
|
||||
t.Fatalf("groups = %d, want 2", len(resp.Groups))
|
||||
}
|
||||
byTitle := map[string]missingGroupView{}
|
||||
for _, g := range resp.Groups {
|
||||
byTitle[g.Tracks[0].Title] = g
|
||||
}
|
||||
|
||||
if r := byTitle["AdmQ Track missheld"].Reacquisition; r != nil {
|
||||
t.Errorf("held before the loss: reacquisition = %+v, want none", r)
|
||||
}
|
||||
r := byTitle["AdmQ Track missopen"].Reacquisition
|
||||
if r == nil || r.WantedAt == nil || r.HeldAt != nil {
|
||||
t.Fatalf("open want: reacquisition = %+v, want wanted and not held", r)
|
||||
}
|
||||
if r.Want == nil || r.Want.ID != openID {
|
||||
t.Fatalf("open want: want = %+v, want id %s", r.Want, openID)
|
||||
}
|
||||
if r.Want.Search == nil || r.Want.Search.Outcome != "nothing" {
|
||||
t.Errorf("open want: search = %+v, want outcome nothing", r.Want.Search)
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/reacquisition"
|
||||
)
|
||||
|
||||
// reacquisitionSettingsResp is the admin card's payload.
|
||||
//
|
||||
// Carries more than the stored settings: [UnnameableAlbums] is the count of
|
||||
// albums with missing files that can never be wanted automatically because
|
||||
// neither they nor their artist has an MBID. The card states that number
|
||||
// rather than leaving an admin to wonder why some rows never get wanted —
|
||||
// a feature that silently does nothing for part of its input reads as broken.
|
||||
type reacquisitionSettingsResp struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
GraceHours int32 `json:"grace_hours"`
|
||||
MaxPerPass int32 `json:"max_per_pass"`
|
||||
|
||||
UnnameableAlbums int64 `json:"unnameable_albums"`
|
||||
}
|
||||
|
||||
// handleGetReacquisitionSettings implements GET
|
||||
// /api/admin/library/reacquisition.
|
||||
func (h *handlers) handleGetReacquisitionSettings(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, h.reacquisitionPayload(r))
|
||||
}
|
||||
|
||||
// handleUpdateReacquisitionSettings implements PUT
|
||||
// /api/admin/library/reacquisition.
|
||||
func (h *handlers) handleUpdateReacquisitionSettings(w http.ResponseWriter, r *http.Request) {
|
||||
var req reacquisitionSettingsResp
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON"))
|
||||
return
|
||||
}
|
||||
_, err := h.reacqSettings.Set(r.Context(), reacquisition.Settings{
|
||||
Enabled: req.Enabled,
|
||||
GraceHours: req.GraceHours,
|
||||
MaxPerPass: req.MaxPerPass,
|
||||
})
|
||||
if err != nil {
|
||||
// The Go-side validation mirrors migration 0056's CHECKs so the
|
||||
// operator gets a readable message naming the field, rather than a
|
||||
// constraint-violation string leaking through as a 500.
|
||||
if errors.Is(err, reacquisition.ErrOutOfRange) {
|
||||
writeErr(w, apierror.BadRequest("invalid_setting", err.Error()))
|
||||
return
|
||||
}
|
||||
writeErrWithLog(w, h.logger, "admin reacquisition: update failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
// Echo the payload recomputed under the new values so the card reflects
|
||||
// what it just did without a reload.
|
||||
writeJSON(w, http.StatusOK, h.reacquisitionPayload(r))
|
||||
}
|
||||
|
||||
func (h *handlers) reacquisitionPayload(r *http.Request) reacquisitionSettingsResp {
|
||||
cur := h.reacqSettings.Get()
|
||||
out := reacquisitionSettingsResp{
|
||||
Enabled: cur.Enabled,
|
||||
GraceHours: cur.GraceHours,
|
||||
MaxPerPass: cur.MaxPerPass,
|
||||
}
|
||||
// Best-effort: the settings are the point of this endpoint, and failing
|
||||
// the whole card because a count query hiccuped would be the wrong trade.
|
||||
if n, err := dbq.New(h.pool).CountAlbumsMissingWithoutMbid(r.Context()); err == nil {
|
||||
out.UnnameableAlbums = n
|
||||
} else {
|
||||
h.logger.Warn("admin reacquisition: unnameable count failed", "err", err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -67,30 +67,15 @@ func tasteRespFrom(t recsettings.TasteTuning) tasteTuningResp {
|
||||
}
|
||||
}
|
||||
|
||||
// discoverTuningResp is the Discover scope on the wire.
|
||||
type discoverTuningResp struct {
|
||||
TagOverlapWeight float64 `json:"tag_overlap_weight"`
|
||||
SnoozeDays float64 `json:"snooze_days"`
|
||||
}
|
||||
|
||||
func discoverRespFrom(d recsettings.DiscoverTuning) discoverTuningResp {
|
||||
return discoverTuningResp{
|
||||
TagOverlapWeight: d.TagOverlapWeight,
|
||||
SnoozeDays: d.SnoozeDays,
|
||||
}
|
||||
}
|
||||
|
||||
// tuningSnapshot is both the GET response and the post-mutation echo:
|
||||
// current values alongside shipped defaults so the card can mark
|
||||
// which knobs deviate.
|
||||
type tuningSnapshot struct {
|
||||
Profiles map[string]weightsResp `json:"profiles"`
|
||||
Taste tasteTuningResp `json:"taste"`
|
||||
Discover discoverTuningResp `json:"discover"`
|
||||
Shipped struct {
|
||||
Profiles map[string]weightsResp `json:"profiles"`
|
||||
Taste tasteTuningResp `json:"taste"`
|
||||
Discover discoverTuningResp `json:"discover"`
|
||||
} `json:"shipped"`
|
||||
}
|
||||
|
||||
@@ -102,14 +87,12 @@ func (h *handlers) tuningSnapshot() tuningSnapshot {
|
||||
recsettings.ScopeSongsLike: weightsRespFrom(h.recSettings.Weights(recsettings.ScopeSongsLike)),
|
||||
}
|
||||
out.Taste = tasteRespFrom(h.recSettings.Taste())
|
||||
out.Discover = discoverRespFrom(h.recSettings.Discover())
|
||||
out.Shipped.Profiles = map[string]weightsResp{
|
||||
recsettings.ScopeRadio: weightsRespFrom(recsettings.ShippedRadioWeights()),
|
||||
recsettings.ScopeDailyMix: weightsRespFrom(recsettings.ShippedDailyMixWeights()),
|
||||
recsettings.ScopeSongsLike: weightsRespFrom(recsettings.ShippedSongsLikeWeights()),
|
||||
}
|
||||
out.Shipped.Taste = tasteRespFrom(recsettings.ShippedTasteTuning())
|
||||
out.Shipped.Discover = discoverRespFrom(recsettings.ShippedDiscoverTuning())
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -143,8 +126,6 @@ func (h *handlers) handlePatchRecommendationTuning(w http.ResponseWriter, r *htt
|
||||
switch scope {
|
||||
case recsettings.ScopeTaste:
|
||||
err = h.recSettings.UpdateTaste(r.Context(), body.Values)
|
||||
case recsettings.ScopeDiscover:
|
||||
err = h.recSettings.UpdateDiscover(r.Context(), body.Values)
|
||||
default:
|
||||
err = h.recSettings.UpdateProfile(r.Context(), scope, body.Values)
|
||||
}
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/notifications"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/requests"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/wanted"
|
||||
)
|
||||
|
||||
// validRequestStatuses is the set of allowed values for the ?status= param.
|
||||
var validRequestStatuses = map[string]bool{
|
||||
"pending": true,
|
||||
"approved": true,
|
||||
"rejected": true,
|
||||
"completed": true,
|
||||
"failed": true,
|
||||
}
|
||||
|
||||
// handleListAdminRequests implements GET /api/admin/requests.
|
||||
// ?status= defaults to "pending"; ?limit= defaults to 50, max 200.
|
||||
func (h *handlers) handleListAdminRequests(w http.ResponseWriter, r *http.Request) {
|
||||
status := r.URL.Query().Get("status")
|
||||
if status == "" {
|
||||
status = "pending"
|
||||
}
|
||||
if !validRequestStatuses[status] {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_status")
|
||||
return
|
||||
}
|
||||
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
limit := 50
|
||||
if limitStr != "" {
|
||||
v, err := strconv.Atoi(limitStr)
|
||||
if err != nil || v <= 0 {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_limit")
|
||||
return
|
||||
}
|
||||
if v > 200 {
|
||||
v = 200
|
||||
}
|
||||
limit = v
|
||||
}
|
||||
|
||||
rows, err := h.requests.ListByStatus(r.Context(), status, int32(limit))
|
||||
if err != nil {
|
||||
h.logger.Error("admin: list requests", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
return
|
||||
}
|
||||
|
||||
q := dbq.New(h.pool)
|
||||
names := requesterNames(r.Context(), q, rows)
|
||||
out := make([]requestView, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
v := requestViewFrom(row)
|
||||
v.Username = names[row.UserID]
|
||||
fillProgress(r.Context(), q, row, &v)
|
||||
out = append(out, v)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// requesterNames maps each request's user id to that user's username, in one
|
||||
// query for the whole page. Like fillProgress, a failed lookup is swallowed:
|
||||
// the names are a reporting nicety, and the page falls back to the id.
|
||||
func requesterNames(ctx context.Context, q *dbq.Queries, rows []dbq.Request) map[pgtype.UUID]string {
|
||||
ids := make([]pgtype.UUID, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.UserID)
|
||||
}
|
||||
names := make(map[pgtype.UUID]string, len(rows))
|
||||
users, err := q.ListUsernamesByIDs(ctx, ids)
|
||||
if err != nil {
|
||||
return names
|
||||
}
|
||||
for _, u := range users {
|
||||
names[u.ID] = u.Username
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// approveRequestBody is the optional JSON body for POST
|
||||
// /api/admin/requests/:id/approve. profile_id picks the release-type profile an
|
||||
// artist request is followed on; omitted, the default profile.
|
||||
type approveRequestBody struct {
|
||||
ProfileID string `json:"profile_id"`
|
||||
}
|
||||
|
||||
// handleApproveRequest implements POST /api/admin/requests/:id/approve. The
|
||||
// request goes on the wanted list: an album or track request
|
||||
// wants its album, an artist request follows the artist.
|
||||
func (h *handlers) handleApproveRequest(w http.ResponseWriter, r *http.Request) {
|
||||
admin, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
id, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
return
|
||||
}
|
||||
|
||||
var body approveRequestBody
|
||||
// Body is entirely optional; ignore decode errors.
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
var profile pgtype.UUID
|
||||
if body.ProfileID != "" {
|
||||
if profile, ok = parseUUID(body.ProfileID); !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_profile")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
row, err := h.requests.Approve(r.Context(), id, admin.ID, profile)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, requests.ErrNotFound):
|
||||
writeAdminJSONErr(w, http.StatusNotFound, "request_not_found")
|
||||
case errors.Is(err, requests.ErrNotPending):
|
||||
writeAdminJSONErr(w, http.StatusConflict, "request_not_pending")
|
||||
case errors.Is(err, wanted.ErrProfileNotFound):
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "profile_not_found")
|
||||
case errors.Is(err, wanted.ErrNotFollowable):
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "not_followable")
|
||||
default:
|
||||
h.logger.Error("admin: approve request", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
h.notifyRequestDecided(r.Context(), notifications.KindRequestApproved, admin, row, "")
|
||||
h.publishRequestStatusChanged(row)
|
||||
writeJSON(w, http.StatusOK, requestViewFrom(row))
|
||||
}
|
||||
|
||||
// rejectRequestBody is the optional JSON body for POST
|
||||
// /api/admin/requests/:id/reject.
|
||||
type rejectRequestBody struct {
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
// handleRejectRequest implements POST /api/admin/requests/:id/reject.
|
||||
func (h *handlers) handleRejectRequest(w http.ResponseWriter, r *http.Request) {
|
||||
admin, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
id, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
|
||||
return
|
||||
}
|
||||
|
||||
var body rejectRequestBody
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
|
||||
row, err := h.requests.Reject(r.Context(), id, admin.ID, body.Notes)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, requests.ErrNotFound):
|
||||
writeAdminJSONErr(w, http.StatusNotFound, "request_not_found")
|
||||
case errors.Is(err, requests.ErrNotPending):
|
||||
writeAdminJSONErr(w, http.StatusConflict, "request_not_pending")
|
||||
default:
|
||||
h.logger.Error("admin: reject request", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
h.notifyRequestDecided(r.Context(), notifications.KindRequestRejected, admin, row, body.Notes)
|
||||
h.publishRequestStatusChanged(row)
|
||||
writeJSON(w, http.StatusOK, requestViewFrom(row))
|
||||
}
|
||||
@@ -1,335 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// newAdminRequestsRouter builds a test chi router with the three admin/requests
|
||||
// endpoints. RequireAdmin middleware is applied. Tests inject a user into
|
||||
// context directly (skipping RequireUser).
|
||||
func newAdminRequestsRouter(h *handlers) chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Route("/api/admin", func(admin chi.Router) {
|
||||
admin.Use(auth.RequireAdmin())
|
||||
admin.Get("/requests", h.handleListAdminRequests)
|
||||
admin.Post("/requests/{id}/approve", h.handleApproveRequest)
|
||||
admin.Post("/requests/{id}/reject", h.handleRejectRequest)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
// doAdminRequestReq fires an HTTP request at the admin requests router with
|
||||
// the given user injected into context (bypassing RequireUser).
|
||||
func doAdminRequestReq(t *testing.T, h *handlers, method, path string, body []byte, user dbq.User) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var reqBody *bytes.Buffer
|
||||
if body != nil {
|
||||
reqBody = bytes.NewBuffer(body)
|
||||
} else {
|
||||
reqBody = bytes.NewBuffer(nil)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, reqBody)
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
newAdminRequestsRouter(h).ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// seedPendingArtistRequest creates a pending artist-kind request row
|
||||
// for the given user and returns its parsed requestView.
|
||||
func seedPendingArtistRequest(t *testing.T, h *handlers, user dbq.User, artistMBID, artistName string) requestView {
|
||||
t.Helper()
|
||||
return createArtistRequest(t, h, user, artistMBID, artistName)
|
||||
}
|
||||
|
||||
// TestHandleListAdminRequests_DefaultStatus_Pending seeds 2 pending + 1
|
||||
// rejected and verifies that GET without ?status returns only the 2 pending
|
||||
// rows.
|
||||
func TestHandleListAdminRequests_DefaultStatus_Pending(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, h.pool, "alice", "pw", false)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
|
||||
createArtistRequest(t, h, alice, "mbid-pending-1", "Pending Artist 1")
|
||||
createArtistRequest(t, h, alice, "mbid-pending-2", "Pending Artist 2")
|
||||
|
||||
// Reject one request directly via service.
|
||||
rv3 := createArtistRequest(t, h, alice, "mbid-reject-1", "Reject Me")
|
||||
_, err := h.requests.Reject(context.Background(), rv3.ID, admin.ID, "test")
|
||||
if err != nil {
|
||||
t.Fatalf("reject seed: %v", err)
|
||||
}
|
||||
|
||||
w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests", nil, admin)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var results []requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if len(results) != 2 {
|
||||
t.Fatalf("len(results) = %d, want 2 (pending only)", len(results))
|
||||
}
|
||||
for _, rv := range results {
|
||||
if rv.Status != "pending" {
|
||||
t.Errorf("result status = %q, want pending", rv.Status)
|
||||
}
|
||||
if rv.Username != alice.Username {
|
||||
t.Errorf("result username = %q, want %q (the requester)", rv.Username, alice.Username)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleListAdminRequests_StatusFilter verifies GET ?status=rejected
|
||||
// returns only rejected rows.
|
||||
func TestHandleListAdminRequests_StatusFilter(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, h.pool, "alice", "pw", false)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
|
||||
createArtistRequest(t, h, alice, "mbid-pending-f1", "Pending Filter 1")
|
||||
|
||||
rv2 := createArtistRequest(t, h, alice, "mbid-rejected-f1", "Rejected Filter 1")
|
||||
_, err := h.requests.Reject(context.Background(), rv2.ID, admin.ID, "")
|
||||
if err != nil {
|
||||
t.Fatalf("reject seed: %v", err)
|
||||
}
|
||||
|
||||
w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=rejected", nil, admin)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var results []requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("len(results) = %d, want 1 rejected row", len(results))
|
||||
}
|
||||
if results[0].Status != "rejected" {
|
||||
t.Errorf("status = %q, want rejected", results[0].Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleListAdminRequests_BadStatus_400 verifies GET with an invalid
|
||||
// ?status returns 400.
|
||||
func TestHandleListAdminRequests_BadStatus_400(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
|
||||
w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=garbage", nil, admin)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400; 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"] != "invalid_status" {
|
||||
t.Errorf("error = %q, want invalid_status", resp["error"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleApproveRequest_NotPending_409 pre-rejects a row and verifies
|
||||
// POST /approve → 409 request_not_pending.
|
||||
func TestHandleApproveRequest_NotPending_409(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, h.pool, "alice", "pw", false)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
|
||||
rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-notpending", "Not Pending")
|
||||
|
||||
// Pre-reject the row.
|
||||
_, err := h.requests.Reject(context.Background(), rv.ID, admin.ID, "pre-rejected")
|
||||
if err != nil {
|
||||
t.Fatalf("pre-reject: %v", err)
|
||||
}
|
||||
|
||||
w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want 409; 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"] != "request_not_pending" {
|
||||
t.Errorf("error = %q, want request_not_pending", resp["error"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleRejectRequest_HappyPath verifies POST /reject with notes returns
|
||||
// 200 and the row transitions to rejected with notes saved.
|
||||
func TestHandleRejectRequest_HappyPath(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, h.pool, "alice", "pw", false)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
|
||||
rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject", "Reject Me")
|
||||
|
||||
body := []byte(`{"notes":"low-quality release; will look for the remaster"}`)
|
||||
w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", body, admin)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var got requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if got.Status != "rejected" {
|
||||
t.Errorf("status = %q, want rejected", got.Status)
|
||||
}
|
||||
if got.Notes == nil || *got.Notes != "low-quality release; will look for the remaster" {
|
||||
t.Errorf("notes = %v, want expected string", got.Notes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleRejectRequest_NoNotes_OK verifies POST /reject with empty body
|
||||
// returns 200 (notes are optional).
|
||||
func TestHandleRejectRequest_NoNotes_OK(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, h.pool, "alice", "pw", false)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
|
||||
rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject-nonotes", "Reject No Notes")
|
||||
|
||||
w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", nil, admin)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var got requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if got.Status != "rejected" {
|
||||
t.Errorf("status = %q, want rejected", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdminRequestsEndpoints_NonAdmin403 is a table-driven test verifying that
|
||||
// all 3 admin request endpoints reject non-admin users with 403.
|
||||
func TestAdminRequestsEndpoints_NonAdmin403(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
nonAdmin := seedUser(t, h.pool, "regular", "pw", false)
|
||||
|
||||
// Use a placeholder UUID for the ID endpoints.
|
||||
fakeID := "00000000-0000-0000-0000-000000000001"
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
body []byte
|
||||
}{
|
||||
{http.MethodGet, "/api/admin/requests", nil},
|
||||
{http.MethodPost, "/api/admin/requests/" + fakeID + "/approve", nil},
|
||||
{http.MethodPost, "/api/admin/requests/" + fakeID + "/reject", nil},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
tc := tc
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
w := doAdminRequestReq(t, h, tc.method, tc.path, tc.body, 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"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleApproveRequest_AlbumBecomesAWant: approving an album request puts
|
||||
// its release group on the wanted list, as the requester's.
|
||||
func TestHandleApproveRequest_AlbumBecomesAWant(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
alice := seedUser(t, h.pool, "alice", "pw", false)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
|
||||
w := doCreateRequest(h, alice, `{"kind":"album","artist_mbid":"artist-x","artist_name":"Gorillaz","album_mbid":"group-x","album_title":"Demon Days"}`)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
var rv requestView
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &rv)
|
||||
|
||||
resp := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin)
|
||||
if resp.Code != http.StatusOK {
|
||||
t.Fatalf("approve: %d %s", resp.Code, resp.Body.String())
|
||||
}
|
||||
want, err := dbq.New(h.pool).GetWantByReleaseGroup(context.Background(), "group-x")
|
||||
if err != nil {
|
||||
t.Fatalf("no want recorded: %v", err)
|
||||
}
|
||||
if want.Title != "Demon Days" || want.CreatedBy != alice.ID || want.Reason != "request" {
|
||||
t.Errorf("want = %+v", want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleApproveRequest_ArtistOnTheChosenProfile: an artist request is
|
||||
// followed on the profile the admin picked; an unknown profile is a 400.
|
||||
func TestHandleApproveRequest_ArtistOnTheChosenProfile(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
alice := seedUser(t, h.pool, "alice", "pw", false)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
ctx := context.Background()
|
||||
|
||||
profile, err := dbq.New(h.pool).CreateReleaseTypeProfile(ctx, dbq.CreateReleaseTypeProfileParams{
|
||||
Name: "Albums only", PrimaryTypes: []string{"Album"}, SecondaryTypes: []string{},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rv := seedPendingArtistRequest(t, h, alice, "artist-profiled", "Profiled")
|
||||
path := "/api/admin/requests/" + uuidToString(rv.ID) + "/approve"
|
||||
|
||||
if resp := doAdminRequestReq(t, h, http.MethodPost, path, []byte(`{"profile_id":"00000000-0000-4000-8000-000000000000"}`), admin); resp.Code != http.StatusBadRequest {
|
||||
t.Fatalf("unknown profile: %d %s", resp.Code, resp.Body.String())
|
||||
}
|
||||
body := []byte(`{"profile_id":"` + uuidToString(profile.ID) + `"}`)
|
||||
if resp := doAdminRequestReq(t, h, http.MethodPost, path, body, admin); resp.Code != http.StatusOK {
|
||||
t.Fatalf("approve: %d %s", resp.Code, resp.Body.String())
|
||||
}
|
||||
f, err := dbq.New(h.pool).GetFollow(ctx, "artist-profiled")
|
||||
if err != nil || f.ProfileID != profile.ID || !f.WantExisting {
|
||||
t.Errorf("follow = %+v, %v: on Albums only, wanting what exists", f, err)
|
||||
}
|
||||
}
|
||||
@@ -1,340 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/acquire"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/release"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/wanted"
|
||||
)
|
||||
|
||||
// Searching for wants and grabbing releases: the schedule's
|
||||
// settings, each want's candidates, and a person's Search, Grab and "never
|
||||
// this one".
|
||||
|
||||
// searchTimeout bounds a search a person waits on: a Prowlarr fanning out to
|
||||
// many trackers can take most of a minute.
|
||||
const searchTimeout = 2 * time.Minute
|
||||
|
||||
type searchSettingsView struct {
|
||||
AutoGrab bool `json:"auto_grab"`
|
||||
SearchIntervalHours int32 `json:"search_interval_hours"`
|
||||
AllowedQualities []string `json:"allowed_qualities"`
|
||||
Tiers []release.TierInfo `json:"tiers"`
|
||||
LastPassAt *string `json:"last_pass_at"`
|
||||
LastPass json.RawMessage `json:"last_pass"`
|
||||
// ImportRoot is the library folder new music is filed into; ""
|
||||
// is the first of ScanPaths, the library's folders.
|
||||
ImportRoot string `json:"import_root"`
|
||||
ScanPaths []string `json:"scan_paths"`
|
||||
// The download lifecycle: seed an imported download to this
|
||||
// ratio or for this many days; give up on one nobody shares after this
|
||||
// many hours. 0 is: remove once imported, no time limit, never.
|
||||
SeedRatio float32 `json:"seed_ratio"`
|
||||
SeedDays int32 `json:"seed_days"`
|
||||
StallHours int32 `json:"stall_hours"`
|
||||
// UpgradeUntil is the tier a held album is upgraded to; "" is
|
||||
// no quality upgrades.
|
||||
UpgradeUntil string `json:"upgrade_until"`
|
||||
}
|
||||
|
||||
func searchSettings(s dbq.AcquisitionSetting, roots []string) searchSettingsView {
|
||||
v := searchSettingsView{
|
||||
AutoGrab: s.AutoGrab, SearchIntervalHours: s.SearchIntervalHours,
|
||||
AllowedQualities: s.AllowedQualities, Tiers: release.Tiers, LastPass: s.LastPass,
|
||||
ImportRoot: s.ImportRoot, ScanPaths: roots,
|
||||
SeedRatio: s.SeedRatio, SeedDays: s.SeedDays, StallHours: s.StallHours,
|
||||
UpgradeUntil: s.UpgradeUntil,
|
||||
}
|
||||
if v.ScanPaths == nil {
|
||||
v.ScanPaths = []string{}
|
||||
}
|
||||
if v.AllowedQualities == nil {
|
||||
v.AllowedQualities = []string{}
|
||||
}
|
||||
if len(v.LastPass) == 0 {
|
||||
v.LastPass = json.RawMessage("{}")
|
||||
}
|
||||
if s.LastPassAt.Valid {
|
||||
at := formatTimestamp(s.LastPassAt)
|
||||
v.LastPassAt = &at
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// handleGetSearchSettings implements GET /api/admin/acquisition/settings.
|
||||
func (h *handlers) handleGetSearchSettings(w http.ResponseWriter, r *http.Request) {
|
||||
s, err := dbq.New(h.pool).GetAcquisitionSettings(r.Context())
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin search settings: get", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, searchSettings(s, h.importer.Roots()))
|
||||
}
|
||||
|
||||
type putSearchSettingsBody struct {
|
||||
AutoGrab bool `json:"auto_grab"`
|
||||
SearchIntervalHours int32 `json:"search_interval_hours"`
|
||||
AllowedQualities []string `json:"allowed_qualities"`
|
||||
ImportRoot string `json:"import_root"`
|
||||
SeedRatio float32 `json:"seed_ratio"`
|
||||
SeedDays int32 `json:"seed_days"`
|
||||
StallHours int32 `json:"stall_hours"`
|
||||
UpgradeUntil string `json:"upgrade_until"`
|
||||
}
|
||||
|
||||
// handlePutSearchSettings implements PUT /api/admin/acquisition/settings.
|
||||
func (h *handlers) handlePutSearchSettings(w http.ResponseWriter, r *http.Request) {
|
||||
var body putSearchSettingsBody
|
||||
if !decodeBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if body.SearchIntervalHours < 0 || body.SearchIntervalHours > 720 {
|
||||
writeErr(w, apierror.BadRequest("bad_interval", "search_interval_hours must be between 0 and 720"))
|
||||
return
|
||||
}
|
||||
if len(body.AllowedQualities) == 0 {
|
||||
writeErr(w, apierror.BadRequest("bad_quality", "allow at least one quality"))
|
||||
return
|
||||
}
|
||||
for _, t := range body.AllowedQualities {
|
||||
if !release.KnownTier(t) {
|
||||
writeErr(w, apierror.BadRequest("bad_quality", "unknown quality "+t))
|
||||
return
|
||||
}
|
||||
}
|
||||
if body.UpgradeUntil != "" && !release.KnownTier(body.UpgradeUntil) {
|
||||
writeErr(w, apierror.BadRequest("bad_upgrade_until", "unknown quality "+body.UpgradeUntil))
|
||||
return
|
||||
}
|
||||
if body.ImportRoot != "" && !slices.Contains(h.importer.Roots(), body.ImportRoot) {
|
||||
writeErr(w, apierror.BadRequest("bad_import_root", "file new music into one of the library's folders"))
|
||||
return
|
||||
}
|
||||
if body.SeedRatio < 0 || body.SeedRatio > 100 || body.SeedDays < 0 || body.SeedDays > 365 ||
|
||||
body.StallHours < 0 || body.StallHours > 720 {
|
||||
writeErr(w, apierror.BadRequest("bad_lifecycle",
|
||||
"seed ratio must be 0 to 100, seed days 0 to 365 and stall hours 0 to 720"))
|
||||
return
|
||||
}
|
||||
s, err := dbq.New(h.pool).UpdateAcquisitionSettings(r.Context(), dbq.UpdateAcquisitionSettingsParams{
|
||||
AutoGrab: body.AutoGrab, SearchIntervalHours: body.SearchIntervalHours, AllowedQualities: body.AllowedQualities,
|
||||
ImportRoot: body.ImportRoot, SeedRatio: body.SeedRatio, SeedDays: body.SeedDays, StallHours: body.StallHours,
|
||||
UpgradeUntil: body.UpgradeUntil,
|
||||
})
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin search settings: put", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, searchSettings(s, h.importer.Roots()))
|
||||
}
|
||||
|
||||
// candidateView is one release a want's last search found.
|
||||
type candidateView struct {
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
InfoHash string `json:"info_hash"`
|
||||
Indexer string `json:"indexer"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Seeders int32 `json:"seeders"`
|
||||
FilesCount int32 `json:"files_count"`
|
||||
Format string `json:"format"`
|
||||
Quality string `json:"quality"`
|
||||
Year int32 `json:"year"`
|
||||
Verdict string `json:"verdict"`
|
||||
Reason string `json:"reason"`
|
||||
Reasons json.RawMessage `json:"reasons"`
|
||||
FoldedFrom []string `json:"folded_from"`
|
||||
SearchedAt string `json:"searched_at"`
|
||||
Downloading bool `json:"downloading"`
|
||||
}
|
||||
|
||||
// handleListCandidates implements GET /api/admin/wanted/{id}/candidates.
|
||||
func (h *handlers) handleListCandidates(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := dbq.New(h.pool)
|
||||
rows, err := q.ListWantCandidates(r.Context(), id)
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: candidates", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
live, err := q.GetLiveGrab(r.Context(), id)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: live grab", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := make([]candidateView, 0, len(rows))
|
||||
for _, c := range rows {
|
||||
v := candidateView{
|
||||
Key: c.Key, Name: c.Name, InfoHash: c.InfoHash, Indexer: c.Indexer, SizeBytes: c.SizeBytes,
|
||||
Seeders: c.Seeders, FilesCount: c.FilesCount, Format: c.Format, Quality: c.Quality, Year: c.Year,
|
||||
Verdict: c.Verdict, Reason: c.Reason, Reasons: c.Reasons, FoldedFrom: c.FoldedFrom,
|
||||
SearchedAt: formatTimestamp(c.SearchedAt),
|
||||
Downloading: live.ID.Valid && live.Key == c.Key,
|
||||
}
|
||||
if v.FoldedFrom == nil {
|
||||
v.FoldedFrom = []string{}
|
||||
}
|
||||
if len(v.Reasons) == 0 {
|
||||
v.Reasons = json.RawMessage("[]")
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": out})
|
||||
}
|
||||
|
||||
// handleSearchWant implements POST /api/admin/wanted/{id}/search: search
|
||||
// now, as the schedule would, taking the best release when auto-grab is on.
|
||||
func (h *handlers) handleSearchWant(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), searchTimeout)
|
||||
defer cancel()
|
||||
res, err := h.searcher.SearchNow(ctx, id)
|
||||
if h.writeSearchErr(w, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, res)
|
||||
}
|
||||
|
||||
type grabBody struct {
|
||||
Key string `json:"key"`
|
||||
Force bool `json:"force"`
|
||||
}
|
||||
|
||||
// grabView is what came of a person's grab.
|
||||
type grabView struct {
|
||||
Added bool `json:"added"`
|
||||
Refused bool `json:"refused"`
|
||||
Gone bool `json:"gone"`
|
||||
Unconfigured bool `json:"unconfigured"`
|
||||
Missing string `json:"missing,omitempty"`
|
||||
Kept bool `json:"kept"`
|
||||
Replaced bool `json:"replaced"`
|
||||
Verdict string `json:"verdict,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// handleGrabCandidate implements POST /api/admin/wanted/{id}/grab: take the
|
||||
// release named by key. The search runs again first, so the indexer's link
|
||||
// never leaves the server; force takes what the verdict would not.
|
||||
func (h *handlers) handleGrabCandidate(w http.ResponseWriter, r *http.Request) {
|
||||
admin, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body grabBody
|
||||
if !decodeBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), searchTimeout)
|
||||
defer cancel()
|
||||
took, err := h.searcher.Take(ctx, id, body.Key, body.Force, admin.ID)
|
||||
if h.writeSearchErr(w, err) {
|
||||
return
|
||||
}
|
||||
v := grabView{
|
||||
Added: took.Added, Refused: took.Refused, Gone: took.Gone, Unconfigured: took.Unconfigured,
|
||||
Missing: took.Missing, Error: took.Error,
|
||||
}
|
||||
if took.Chosen != nil {
|
||||
v.Verdict, v.Reason = string(took.Chosen.Verdict), took.Chosen.Reason
|
||||
}
|
||||
if took.Contest != nil {
|
||||
v.Kept, v.Replaced = took.Contest.Kept, took.Contest.Replaced
|
||||
if took.Contest.Kept {
|
||||
v.Reason = took.Contest.Reason
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, v)
|
||||
}
|
||||
|
||||
type blockBody struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
// handleBlockCandidate implements POST /api/admin/wanted/{id}/block: never
|
||||
// take this release again, for any want.
|
||||
func (h *handlers) handleBlockCandidate(w http.ResponseWriter, r *http.Request) {
|
||||
admin, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body blockBody
|
||||
if !decodeBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
c, err := dbq.New(h.pool).GetWantCandidate(r.Context(), dbq.GetWantCandidateParams{WantID: id, Key: body.Key})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeErr(w, apierror.NotFound("candidate"))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: block", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
if c.InfoHash == "" {
|
||||
writeErr(w, apierror.BadRequest("no_infohash", "this release has no infohash to set aside by"))
|
||||
return
|
||||
}
|
||||
if err := acquire.NewMemory(h.pool).Block(r.Context(), dbq.BlockReleaseParams{
|
||||
InfoHash: c.InfoHash, Name: c.Name, Reason: acquire.BlockOperator, WantID: id, BlockedBy: admin.ID,
|
||||
}); err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: block", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleUnblockRelease implements DELETE /api/admin/release-blocks/{hash}.
|
||||
func (h *handlers) handleUnblockRelease(w http.ResponseWriter, r *http.Request) {
|
||||
removed, err := acquire.NewMemory(h.pool).Unblock(r.Context(), chi.URLParam(r, "hash"))
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: unblock", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
if !removed {
|
||||
writeErr(w, apierror.NotFound("block"))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// writeSearchErr answers a Searcher error, and says whether there was one.
|
||||
func (h *handlers) writeSearchErr(w http.ResponseWriter, err error) bool {
|
||||
switch {
|
||||
case err == nil:
|
||||
return false
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
writeErr(w, apierror.NotFound("want"))
|
||||
case errors.Is(err, wanted.ErrWantHeld):
|
||||
writeErr(w, apierror.Conflict("want_held", "the library already holds this album, and it isn't wanted for a better copy"))
|
||||
default:
|
||||
writeErrWithLog(w, h.logger, "admin wanted: search", apierror.Internal(err))
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
// The admin Overview's status sections: after the verdict, who is
|
||||
// listening, what is downloading, what the library holds and how much room
|
||||
// listening, what the library holds and how much room
|
||||
// it has, and how the server itself is doing. One read for the page, polled
|
||||
// while it is open.
|
||||
|
||||
@@ -36,17 +36,6 @@ type listeningStatusView struct {
|
||||
LastPlayAt *string `json:"last_play_at"`
|
||||
}
|
||||
|
||||
type downloadsStatusView struct {
|
||||
Running int64 `json:"running"`
|
||||
NeedsYou int64 `json:"needs_you"`
|
||||
NeedsYouSince *string `json:"needs_you_since"`
|
||||
ImportedDay int64 `json:"imported_day"`
|
||||
GivenUpDay int64 `json:"given_up_day"`
|
||||
// Live is the downloads not yet ended, the ones needing a person first.
|
||||
Live []downloadView `json:"live"`
|
||||
ClientsDown []clientDownView `json:"clients_down"`
|
||||
}
|
||||
|
||||
// diskView is the filesystem one library folder, or the data folder, sits
|
||||
// on.
|
||||
type diskView struct {
|
||||
@@ -91,15 +80,10 @@ type serverStatusView struct {
|
||||
|
||||
type adminStatusView struct {
|
||||
Listening listeningStatusView `json:"listening"`
|
||||
Downloads downloadsStatusView `json:"downloads"`
|
||||
Library libraryStatusView `json:"library"`
|
||||
Server serverStatusView `json:"server"`
|
||||
}
|
||||
|
||||
// overviewLiveDownloads is how many running downloads the Overview lists;
|
||||
// Activity has the rest.
|
||||
const overviewLiveDownloads = 5
|
||||
|
||||
// overviewErrors is how many recent errors the Overview lists.
|
||||
const overviewErrors = 10
|
||||
|
||||
@@ -136,12 +120,6 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request)
|
||||
out.Listening.LastPlayAt = &at
|
||||
}
|
||||
|
||||
if err := h.downloadsStatus(r, q, &out.Downloads); err != nil {
|
||||
h.logger.Error("admin status: downloads", "err", err)
|
||||
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
|
||||
return
|
||||
}
|
||||
|
||||
lib, err := q.LibraryStatus(ctx)
|
||||
if err != nil {
|
||||
h.logger.Error("admin status: library", "err", err)
|
||||
@@ -150,8 +128,8 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
out.Library = libraryStatusView{Tracks: lib.Tracks, Albums: lib.Albums, Artists: lib.Artists,
|
||||
Bytes: lib.Bytes, Disks: []diskView{}}
|
||||
if h.importer != nil {
|
||||
for _, root := range h.importer.Roots() {
|
||||
if h.scanner != nil {
|
||||
for _, root := range h.scanner.Roots() {
|
||||
out.Library.Disks = append(out.Library.Disks, diskOf(root))
|
||||
}
|
||||
}
|
||||
@@ -170,39 +148,6 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (h *handlers) downloadsStatus(r *http.Request, q *dbq.Queries, out *downloadsStatusView) error {
|
||||
st, err := q.DownloadsStatus(r.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*out = downloadsStatusView{Running: st.Running, NeedsYou: st.NeedsYou,
|
||||
ImportedDay: st.ImportedDay, GivenUpDay: st.GivenUpDay,
|
||||
Live: []downloadView{}, ClientsDown: []clientDownView{}}
|
||||
if st.NeedsYou > 0 && st.NeedsYouSince.Valid {
|
||||
since := formatTimestamp(st.NeedsYouSince)
|
||||
out.NeedsYouSince = &since
|
||||
}
|
||||
// ListGrabs puts the ones needing a person first, then the running ones.
|
||||
rows, err := q.ListGrabs(r.Context(), dbq.ListGrabsParams{MaxRows: overviewLiveDownloads})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, g := range rows {
|
||||
if !g.EndedAt.Valid {
|
||||
out.Live = append(out.Live, downloadFrom(g))
|
||||
}
|
||||
}
|
||||
down, err := q.ListClientsDown(r.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range down {
|
||||
out.ClientsDown = append(out.ClientsDown, clientDownView{Client: c.Client, Detail: c.Detail,
|
||||
Since: formatTimestamp(c.FirstSeen)})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// diskOf reads the size and free space of the filesystem path is on.
|
||||
func diskOf(path string) diskView {
|
||||
var st syscall.Statfs_t
|
||||
|
||||
@@ -76,7 +76,7 @@ func TestAdminStatus_ListeningAndServer(t *testing.T) {
|
||||
if got.Library.Tracks != 2 || got.Library.Albums != 2 || got.Library.Bytes != 10 {
|
||||
t.Errorf("library = %+v, want 2 tracks, 2 albums, 10 bytes", got.Library)
|
||||
}
|
||||
if got.Downloads.Live == nil || got.Downloads.ClientsDown == nil || got.Library.Disks == nil {
|
||||
if got.Library.Disks == nil {
|
||||
t.Error("lists must be [], never null")
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ type adminQueueView struct {
|
||||
// every queue an admin acts on, in one response, so each admin page pays one
|
||||
// cheap read for its rail.
|
||||
type adminSummaryView struct {
|
||||
Requests adminQueueView `json:"requests"`
|
||||
Reports adminQueueView `json:"reports"`
|
||||
Duplicates adminQueueView `json:"duplicates"`
|
||||
Suspect adminQueueView `json:"suspect"`
|
||||
@@ -37,7 +36,6 @@ func queueView(count int64, since pgtype.Timestamptz) adminQueueView {
|
||||
|
||||
func adminSummaryFrom(row dbq.AdminSummaryRow) adminSummaryView {
|
||||
return adminSummaryView{
|
||||
Requests: queueView(row.Requests, row.RequestsSince),
|
||||
Reports: queueView(row.Reports, row.ReportsSince),
|
||||
Duplicates: queueView(row.Duplicates, row.DuplicatesSince),
|
||||
Suspect: queueView(row.Suspect, row.SuspectSince),
|
||||
|
||||
@@ -35,6 +35,7 @@ func getAdminSummary(t *testing.T, h *handlers, user dbq.User) (int, adminSummar
|
||||
// oldest item has waited; an empty queue has no since.
|
||||
func TestAdminSummary_CountsTheQueuesAndSinceWhen(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
truncateLibrary(t, h.pool)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
listener := seedUser(t, h.pool, "listener", "pw", false)
|
||||
ctx := context.Background()
|
||||
@@ -43,19 +44,17 @@ func TestAdminSummary_CountsTheQueuesAndSinceWhen(t *testing.T) {
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("status = %d", code)
|
||||
}
|
||||
if empty.Requests.Count != 0 || empty.Requests.Since != nil || empty.Missing.Count != 0 {
|
||||
if empty.Missing.Count != 0 || empty.Missing.Since != nil {
|
||||
t.Errorf("empty summary = %+v", empty)
|
||||
}
|
||||
|
||||
if _, err := dbq.New(h.pool).CreateRequest(ctx, dbq.CreateRequestParams{
|
||||
UserID: listener.ID, Kind: dbq.RequestKindArtist, ArtistMbid: "a0000000-0000-4000-8000-000000000001",
|
||||
ArtistName: "Annadale",
|
||||
}); err != nil {
|
||||
track := seedQuarantineTrack(t, h, "sum-missing")
|
||||
if _, err := h.pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE id = $1`, track.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, got := getAdminSummary(t, h, admin)
|
||||
if got.Requests.Count != 1 || got.Requests.Since == nil {
|
||||
t.Errorf("requests = %+v, want 1 with a since", got.Requests)
|
||||
if got.Missing.Count != 1 || got.Missing.Since == nil {
|
||||
t.Errorf("missing = %+v, want 1 with a since", got.Missing)
|
||||
}
|
||||
|
||||
if code, _ := getAdminSummary(t, h, listener); code != http.StatusForbidden {
|
||||
|
||||
@@ -31,10 +31,6 @@ type suspectTrackView struct {
|
||||
// first pass. VerdictAt is when it was last set.
|
||||
Verdict *string `json:"verdict"`
|
||||
VerdictAt *string `json:"verdict_at"`
|
||||
// Replacing: the album is on the wanted list for a clean copy;
|
||||
// SearchedAt is when one was last searched for, null before the first.
|
||||
Replacing bool `json:"replacing"`
|
||||
SearchedAt *string `json:"searched_at"`
|
||||
}
|
||||
|
||||
// suspectGroupView is a folder's worth of flagged tracks. As on the
|
||||
@@ -116,11 +112,6 @@ func groupSuspectByDirectory(rows []dbq.ListSuspectSourceTracksRow) []suspectGro
|
||||
at := row.SourceVerdictAt.Time.UTC().Format(time.RFC3339)
|
||||
t.VerdictAt = &at
|
||||
}
|
||||
t.Replacing = row.WantUpgrade == "rip"
|
||||
if t.Replacing && row.SearchedAt.Valid {
|
||||
at := row.SearchedAt.Time.UTC().Format(time.RFC3339)
|
||||
t.SearchedAt = &at
|
||||
}
|
||||
if n := len(groups); n > 0 && groups[n-1].Directory == row.Directory {
|
||||
groups[n-1].Tracks = append(groups[n-1].Tracks, t)
|
||||
continue
|
||||
|
||||
+24
-76
@@ -17,13 +17,12 @@ import (
|
||||
)
|
||||
|
||||
type adminUserView struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
AutoApproveRequests bool `json:"auto_approve_requests"`
|
||||
DebugModeEnabled bool `json:"debug_mode_enabled"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
DebugModeEnabled bool `json:"debug_mode_enabled"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type listUsersResp struct {
|
||||
@@ -40,13 +39,12 @@ func (h *handlers) handleAdminListUsers(w http.ResponseWriter, r *http.Request)
|
||||
out := make([]adminUserView, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
v := adminUserView{
|
||||
ID: uuidToString(row.ID),
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
IsAdmin: row.IsAdmin,
|
||||
AutoApproveRequests: row.AutoApproveRequests,
|
||||
DebugModeEnabled: row.DebugModeEnabled,
|
||||
CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339),
|
||||
ID: uuidToString(row.ID),
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
IsAdmin: row.IsAdmin,
|
||||
DebugModeEnabled: row.DebugModeEnabled,
|
||||
CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339),
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
@@ -117,13 +115,12 @@ func (h *handlers) handleUpdateUserAdmin(w http.ResponseWriter, r *http.Request)
|
||||
audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, action, nil)
|
||||
|
||||
writeJSON(w, http.StatusOK, adminUserView{
|
||||
ID: uuidToString(updated.ID),
|
||||
Username: updated.Username,
|
||||
DisplayName: updated.DisplayName,
|
||||
IsAdmin: updated.IsAdmin,
|
||||
AutoApproveRequests: updated.AutoApproveRequests,
|
||||
DebugModeEnabled: updated.DebugModeEnabled,
|
||||
CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339),
|
||||
ID: uuidToString(updated.ID),
|
||||
Username: updated.Username,
|
||||
DisplayName: updated.DisplayName,
|
||||
IsAdmin: updated.IsAdmin,
|
||||
DebugModeEnabled: updated.DebugModeEnabled,
|
||||
CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -187,13 +184,12 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request)
|
||||
map[string]any{"is_admin": req.IsAdmin})
|
||||
|
||||
writeJSON(w, http.StatusOK, adminUserView{
|
||||
ID: uuidToString(user.ID),
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
IsAdmin: user.IsAdmin,
|
||||
AutoApproveRequests: user.AutoApproveRequests,
|
||||
DebugModeEnabled: user.DebugModeEnabled,
|
||||
CreatedAt: user.CreatedAt.Time.UTC().Format(time.RFC3339),
|
||||
ID: uuidToString(user.ID),
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
IsAdmin: user.IsAdmin,
|
||||
DebugModeEnabled: user.DebugModeEnabled,
|
||||
CreatedAt: user.CreatedAt.Time.UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -302,51 +298,3 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// --- Admin auto-approve toggle ---------------------------------------------
|
||||
|
||||
type adminAutoApproveReq struct {
|
||||
AutoApprove bool `json:"auto_approve"`
|
||||
}
|
||||
|
||||
func (h *handlers) handleAdminAutoApproveToggle(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
targetID, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req adminAutoApproveReq
|
||||
if !decodeBody(w, r, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
q := dbq.New(h.pool)
|
||||
updated, err := q.UpdateUserAutoApprove(r.Context(), dbq.UpdateUserAutoApproveParams{
|
||||
ID: targetID,
|
||||
AutoApproveRequests: req.AutoApprove,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: ""})
|
||||
return
|
||||
}
|
||||
writeErrWithLog(w, h.logger, "admin auto-approve: update failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, audit.ActionAutoApproveToggle,
|
||||
map[string]any{"auto_approve": req.AutoApprove})
|
||||
|
||||
writeJSON(w, http.StatusOK, adminUserView{
|
||||
ID: uuidToString(updated.ID),
|
||||
Username: updated.Username,
|
||||
DisplayName: updated.DisplayName,
|
||||
IsAdmin: updated.IsAdmin,
|
||||
AutoApproveRequests: updated.AutoApproveRequests,
|
||||
DebugModeEnabled: updated.DebugModeEnabled,
|
||||
CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@ func newAdminUsersRouter(h *handlers) chi.Router {
|
||||
admin.Post("/users", h.handleAdminCreateUser)
|
||||
admin.Delete("/users/{id}", h.handleAdminDeleteUser)
|
||||
admin.Post("/users/{id}/reset-password", h.handleAdminResetPassword)
|
||||
admin.Put("/users/{id}/auto-approve", h.handleAdminAutoApproveToggle)
|
||||
})
|
||||
return r
|
||||
}
|
||||
@@ -271,40 +270,3 @@ func TestAdminResetPassword_TooShort_400(t *testing.T) {
|
||||
t.Errorf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminAutoApproveToggle(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
}
|
||||
h, pool := testHandlers(t)
|
||||
admin := seedUser(t, pool, "aacaller", "pw", true)
|
||||
target := seedUser(t, pool, "aatarget", "pw", false)
|
||||
|
||||
body := `{"auto_approve":true}`
|
||||
req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(target.ID)+"/auto-approve",
|
||||
bytes.NewReader([]byte(body)))
|
||||
req = withUser(req, admin)
|
||||
rec := httptest.NewRecorder()
|
||||
newAdminUsersRouter(h).ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp adminUserView
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if !resp.AutoApproveRequests {
|
||||
t.Errorf("auto_approve_requests = false on response; expected true")
|
||||
}
|
||||
|
||||
// Verify DB.
|
||||
var aa bool
|
||||
if err := pool.QueryRow(context.Background(),
|
||||
"SELECT auto_approve_requests FROM users WHERE id = $1", target.ID).Scan(&aa); err != nil {
|
||||
t.Fatalf("verify: %v", err)
|
||||
}
|
||||
if !aa {
|
||||
t.Errorf("DB row not updated")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,821 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"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/catalogue"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/wanted"
|
||||
)
|
||||
|
||||
// The wanted list's admin surface: wants, follows and
|
||||
// release-type profiles.
|
||||
|
||||
// wantView is one row of GET /api/admin/wanted.
|
||||
type wantView struct {
|
||||
ID string `json:"id"`
|
||||
ReleaseGroupMBID string `json:"release_group_mbid"`
|
||||
Title string `json:"title"`
|
||||
ArtistMBID string `json:"artist_mbid"`
|
||||
ArtistName string `json:"artist_name"`
|
||||
ArtistID string `json:"artist_id,omitempty"`
|
||||
PrimaryType string `json:"primary_type"`
|
||||
SecondaryTypes []string `json:"secondary_types"`
|
||||
Year string `json:"year"`
|
||||
Reason string `json:"reason"`
|
||||
RequestedBy string `json:"requested_by,omitempty"`
|
||||
AlbumID string `json:"album_id,omitempty"`
|
||||
WantedAt string `json:"wanted_at"`
|
||||
HeldAt *string `json:"held_at"`
|
||||
ImageURL string `json:"image_url"`
|
||||
// Upgrade: why a held album is wanted again, quality or rip, and
|
||||
// HeldQuality what the library's copy is.
|
||||
Upgrade string `json:"upgrade,omitempty"`
|
||||
HeldQuality string `json:"held_quality,omitempty"`
|
||||
// Search is the schedule's last look; Grab the download running.
|
||||
Search *wantSearchView `json:"search"`
|
||||
Grab *wantGrabView `json:"grab"`
|
||||
}
|
||||
|
||||
type wantSearchView struct {
|
||||
SearchedAt string `json:"searched_at"`
|
||||
Outcome string `json:"outcome"`
|
||||
Considered int32 `json:"considered"`
|
||||
BestRelease string `json:"best_release"`
|
||||
BestVerdict string `json:"best_verdict"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// wantGrabView is the want's latest download, running or ended, and what
|
||||
// its import made of it.
|
||||
type wantGrabView struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
GrabbedAt string `json:"grabbed_at"`
|
||||
Origin string `json:"origin"`
|
||||
Quality string `json:"quality"`
|
||||
Live bool `json:"live"`
|
||||
EndReason string `json:"end_reason"`
|
||||
Progress float32 `json:"progress"`
|
||||
ImportState string `json:"import_state"`
|
||||
ImportReason string `json:"import_reason"`
|
||||
EndDetail string `json:"end_detail"`
|
||||
ImportedAt *string `json:"imported_at"`
|
||||
ImportedFiles int32 `json:"imported_files"`
|
||||
}
|
||||
|
||||
// wantCounts sizes each tab of the Wanted page. Artists: how many artists
|
||||
// the list holds albums of, its main page.
|
||||
type wantCounts struct {
|
||||
Artists int64 `json:"artists"`
|
||||
// Unmatched: library albums waiting to be matched by hand.
|
||||
Unmatched int64 `json:"unmatched"`
|
||||
Wanted int64 `json:"wanted"`
|
||||
Missing int64 `json:"missing"`
|
||||
Held int64 `json:"held"`
|
||||
// Upgrades: held albums wanted for a better copy.
|
||||
Upgrades int64 `json:"upgrades"`
|
||||
Following int64 `json:"following"`
|
||||
// Activity: downloads running; Attention: of those, the ones waiting on
|
||||
// a person; Blocked: releases set aside.
|
||||
Activity int64 `json:"activity"`
|
||||
Attention int64 `json:"attention"`
|
||||
Blocked int64 `json:"blocked"`
|
||||
}
|
||||
|
||||
type wantsPage struct {
|
||||
Items []wantView `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
Counts wantCounts `json:"counts"`
|
||||
// Library is the one-time listing of the library's albums.
|
||||
Library libraryListingView `json:"library"`
|
||||
// Artist heads one artist's page, when the list is narrowed to them.
|
||||
Artist *wantArtistView `json:"artist,omitempty"`
|
||||
}
|
||||
|
||||
// wantArtistView is one artist on the Wanted view's main page: how
|
||||
// many of their albums the list holds, of how many.
|
||||
type wantArtistView struct {
|
||||
ArtistMBID string `json:"artist_mbid"`
|
||||
ArtistName string `json:"artist_name"`
|
||||
SortName string `json:"sort_name"`
|
||||
ArtistID string `json:"artist_id,omitempty"`
|
||||
ImageURL string `json:"image_url"`
|
||||
Albums int32 `json:"albums"`
|
||||
Held int32 `json:"held"`
|
||||
Wanted int32 `json:"wanted"`
|
||||
Missing int32 `json:"missing"`
|
||||
Downloading int32 `json:"downloading"`
|
||||
Following bool `json:"following"`
|
||||
}
|
||||
|
||||
type wantArtistsPage struct {
|
||||
Items []wantArtistView `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
Counts wantCounts `json:"counts"`
|
||||
Library libraryListingView `json:"library"`
|
||||
}
|
||||
|
||||
// libraryListingView: whether the library's albums are all on the list
|
||||
// yet, and how many could not be matched to MusicBrainz; those are
|
||||
// listed in the Collection's Unmatched section.
|
||||
type libraryListingView struct {
|
||||
ListedAt *string `json:"listed_at"`
|
||||
Unlisted int32 `json:"unlisted"`
|
||||
}
|
||||
|
||||
// unmatchedAlbumView is one album in the Collection's Unmatched section: why
|
||||
// no MusicBrainz album matched it, or that a person left it off.
|
||||
type unmatchedAlbumView struct {
|
||||
AlbumID string `json:"album_id"`
|
||||
Title string `json:"title"`
|
||||
Artist string `json:"artist"`
|
||||
Detail string `json:"detail"`
|
||||
Tracks int32 `json:"tracks"`
|
||||
LeftOff bool `json:"left_off"`
|
||||
DecidedAt string `json:"decided_at"`
|
||||
}
|
||||
|
||||
// unmatchedShown bounds the Unmatched section: a library a listing could
|
||||
// not match more of than this has a bigger problem than one page shows.
|
||||
const unmatchedShown = 500
|
||||
|
||||
const wantsPageSize = 50
|
||||
|
||||
// wantArtistsPageSize fills a few rows of the artist grid a page.
|
||||
const wantArtistsPageSize = 96
|
||||
|
||||
// wantsHeader is what every Collection page carries: each section's count,
|
||||
// and how the one-time library listing went.
|
||||
func (h *handlers) wantsHeader(r *http.Request, q *dbq.Queries) (wantCounts, libraryListingView, error) {
|
||||
counts, err := q.CountWants(r.Context())
|
||||
if err != nil {
|
||||
return wantCounts{}, libraryListingView{}, err
|
||||
}
|
||||
listing, err := q.GetLibraryListing(r.Context())
|
||||
if err != nil {
|
||||
return wantCounts{}, libraryListingView{}, err
|
||||
}
|
||||
lib := libraryListingView{Unlisted: listing.LibraryUnlisted}
|
||||
if listing.LibraryListedAt.Valid {
|
||||
at := formatTimestamp(listing.LibraryListedAt)
|
||||
lib.ListedAt = &at
|
||||
}
|
||||
return wantCounts{Artists: counts.Artists, Unmatched: counts.Unmatched, Wanted: counts.Wanted, Missing: counts.Missing, Held: counts.Held,
|
||||
Upgrades: counts.Upgrades, Following: counts.Following, Activity: counts.Activity, Attention: counts.Attention, Blocked: counts.Blocked}, lib, nil
|
||||
}
|
||||
|
||||
func offsetParam(r *http.Request) int {
|
||||
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||
return max(offset, 0)
|
||||
}
|
||||
|
||||
func wantArtistViewOf(row dbq.ListWantArtistsRow) wantArtistView {
|
||||
v := wantArtistView{
|
||||
ArtistMBID: row.ArtistMbid, ArtistName: row.ArtistName, SortName: row.SortName,
|
||||
ImageURL: artistArtURL(row.ArtistMbid, row.ArtistName),
|
||||
Albums: row.Albums, Held: row.Held, Wanted: row.Wanted, Missing: row.Missing,
|
||||
Downloading: row.Downloading, Following: row.Following,
|
||||
}
|
||||
if row.LibraryArtistID.Valid {
|
||||
v.ArtistID = uuidToString(row.LibraryArtistID)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// handleListWantArtists implements GET /api/admin/wanted/artists?q=&offset=:
|
||||
// the Wanted view's main page, every artist on the list A–Z.
|
||||
func (h *handlers) handleListWantArtists(w http.ResponseWriter, r *http.Request) {
|
||||
offset := offsetParam(r)
|
||||
q := dbq.New(h.pool)
|
||||
rows, err := q.ListWantArtists(r.Context(), dbq.ListWantArtistsParams{
|
||||
Q: strings.TrimSpace(r.URL.Query().Get("q")), Skip: int32(offset), MaxRows: wantArtistsPageSize})
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: artists", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
counts, lib, err := h.wantsHeader(r, q)
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: counts", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := wantArtistsPage{Items: make([]wantArtistView, 0, len(rows)), Limit: wantArtistsPageSize, Offset: offset,
|
||||
Counts: counts, Library: lib}
|
||||
for _, row := range rows {
|
||||
out.Total = row.Total
|
||||
out.Items = append(out.Items, wantArtistViewOf(row))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// handleListWants implements GET
|
||||
// /api/admin/wanted?state=wanted|missing|upgrade|held|all&artist=&q=&offset=.
|
||||
// wanted is everything open but missing files; upgrade the held albums wanted
|
||||
// for a better copy. Each list runs artist by artist, A–Z, like the library; q
|
||||
// narrows it to an artist or album, and artist to one artist's page, which it
|
||||
// then heads.
|
||||
func (h *handlers) handleListWants(w http.ResponseWriter, r *http.Request) {
|
||||
state := r.URL.Query().Get("state")
|
||||
if state == "" {
|
||||
state = "wanted"
|
||||
}
|
||||
if state != "wanted" && state != "missing" && state != "upgrade" && state != "held" && state != "all" {
|
||||
writeErr(w, apierror.BadRequest("bad_state", "state must be wanted, missing, upgrade, held or all"))
|
||||
return
|
||||
}
|
||||
offset := offsetParam(r)
|
||||
artist := strings.TrimSpace(r.URL.Query().Get("artist"))
|
||||
q := dbq.New(h.pool)
|
||||
rows, err := q.ListWants(r.Context(), dbq.ListWantsParams{State: state, ArtistMbid: artist,
|
||||
Q: strings.TrimSpace(r.URL.Query().Get("q")), Skip: int32(offset), MaxRows: wantsPageSize})
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: list", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
counts, lib, err := h.wantsHeader(r, q)
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: counts", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := wantsPage{Library: lib, Counts: counts,
|
||||
Items: make([]wantView, 0, len(rows)), Limit: wantsPageSize, Offset: offset}
|
||||
if artist != "" {
|
||||
heads, err := q.ListWantArtists(r.Context(), dbq.ListWantArtistsParams{ArtistMbid: artist, MaxRows: 1})
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: artist", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
if len(heads) == 0 {
|
||||
writeErr(w, apierror.NotFound("artist"))
|
||||
return
|
||||
}
|
||||
v := wantArtistViewOf(heads[0])
|
||||
out.Artist = &v
|
||||
}
|
||||
for _, row := range rows {
|
||||
out.Total = row.Total
|
||||
out.Items = append(out.Items, wantViewOf(row))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// wantViewOf is one ListWants row as the wanted list and the Missing page
|
||||
// send it.
|
||||
func wantViewOf(row dbq.ListWantsRow) wantView {
|
||||
v := wantView{
|
||||
ID: uuidToString(row.ID), ReleaseGroupMBID: row.ReleaseGroupMbid, Title: row.Title,
|
||||
ArtistMBID: row.ArtistMbid, ArtistName: row.ArtistName,
|
||||
PrimaryType: row.PrimaryType, SecondaryTypes: row.SecondaryTypes,
|
||||
Year: first4(row.FirstReleaseDate), Reason: row.Reason,
|
||||
WantedAt: formatTimestamp(row.WantedAt), Upgrade: row.Upgrade, HeldQuality: row.HeldQuality,
|
||||
ImageURL: groupArtURL(musicbrainz.ReleaseGroup{MBID: row.ReleaseGroupMbid, Title: row.Title, ArtistCredit: row.ArtistName}),
|
||||
}
|
||||
if row.LibraryArtistID.Valid {
|
||||
v.ArtistID = uuidToString(row.LibraryArtistID)
|
||||
}
|
||||
if row.AlbumID.Valid {
|
||||
v.AlbumID = uuidToString(row.AlbumID)
|
||||
}
|
||||
if row.RequestedBy != nil {
|
||||
v.RequestedBy = *row.RequestedBy
|
||||
}
|
||||
if row.FulfilledAt.Valid {
|
||||
held := formatTimestamp(row.FulfilledAt)
|
||||
v.HeldAt = &held
|
||||
}
|
||||
if v.SecondaryTypes == nil {
|
||||
v.SecondaryTypes = []string{}
|
||||
}
|
||||
if row.SearchedAt.Valid {
|
||||
v.Search = &wantSearchView{
|
||||
SearchedAt: formatTimestamp(row.SearchedAt), Outcome: row.SearchOutcome,
|
||||
Considered: row.SearchConsidered, BestRelease: row.BestRelease,
|
||||
BestVerdict: row.BestVerdict, Error: row.SearchError,
|
||||
}
|
||||
}
|
||||
if row.GrabName != nil {
|
||||
v.Grab = &wantGrabView{ID: uuidToString(row.GrabID), Name: *row.GrabName,
|
||||
GrabbedAt: formatTimestamp(row.GrabbedAt), Live: !row.GrabEndedAt.Valid,
|
||||
Origin: deref(row.GrabOrigin), Quality: deref(row.GrabQuality), EndReason: deref(row.GrabEndReason),
|
||||
ImportState: deref(row.GrabImportState), ImportReason: deref(row.GrabImportReason),
|
||||
EndDetail: deref(row.GrabEndDetail)}
|
||||
if row.GrabProgress != nil {
|
||||
v.Grab.Progress = *row.GrabProgress
|
||||
}
|
||||
if row.GrabImportedFiles != nil {
|
||||
v.Grab.ImportedFiles = *row.GrabImportedFiles
|
||||
}
|
||||
if row.GrabImportedAt.Valid {
|
||||
at := formatTimestamp(row.GrabImportedAt)
|
||||
v.Grab.ImportedAt = &at
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// wantTracksView is an album's track list for the Wanted view: the
|
||||
// library's own tracks for an album it holds or held, else MusicBrainz's
|
||||
// standard edition of what is wanted.
|
||||
type wantTracksView struct {
|
||||
// library, musicbrainz, or none when MusicBrainz lists no edition.
|
||||
Source string `json:"source"`
|
||||
// Edition names the MusicBrainz release the list is from.
|
||||
Edition string `json:"edition,omitempty"`
|
||||
Tracks []wantTrackView `json:"tracks"`
|
||||
}
|
||||
|
||||
type wantTrackView struct {
|
||||
Disc int32 `json:"disc"`
|
||||
Number int32 `json:"number"`
|
||||
Title string `json:"title"`
|
||||
LengthMs int32 `json:"length_ms"`
|
||||
// Missing: the library's file for it is gone.
|
||||
Missing bool `json:"missing"`
|
||||
}
|
||||
|
||||
// handleWantTracks implements GET /api/admin/wanted/{id}/tracks.
|
||||
func (h *handlers) handleWantTracks(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := dbq.New(h.pool)
|
||||
want, err := q.GetWantAlbum(r.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeErr(w, apierror.NotFound("want"))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: tracks", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := wantTracksView{Tracks: []wantTrackView{}}
|
||||
if want.AlbumID.Valid {
|
||||
rows, err := q.ListLibraryAlbumTracks(r.Context(), want.AlbumID)
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: library tracks", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out.Source = "library"
|
||||
for _, t := range rows {
|
||||
v := wantTrackView{Title: t.Title, LengthMs: t.DurationMs, Missing: t.Missing}
|
||||
if t.DiscNumber != nil {
|
||||
v.Disc = *t.DiscNumber
|
||||
}
|
||||
if t.TrackNumber != nil {
|
||||
v.Number = *t.TrackNumber
|
||||
}
|
||||
out.Tracks = append(out.Tracks, v)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
return
|
||||
}
|
||||
eds, err := h.catalogue.Releases(r.Context(), want.ReleaseGroupMbid)
|
||||
switch {
|
||||
case errors.Is(err, catalogue.ErrNotFound):
|
||||
out.Source = "none"
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
return
|
||||
case errors.Is(err, musicbrainz.ErrUnreachable), errors.Is(err, musicbrainz.ErrBadResponse):
|
||||
writeErr(w, &apierror.Error{Status: 503, Code: "musicbrainz_unreachable", Message: "MusicBrainz can't be reached", Cause: err})
|
||||
return
|
||||
case err != nil:
|
||||
writeErrWithLog(w, h.logger, "admin wanted: editions", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
e, ok := standardEdition(eds.Editions)
|
||||
if !ok {
|
||||
out.Source = "none"
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
return
|
||||
}
|
||||
out.Source = "musicbrainz"
|
||||
out.Edition = editionLabel(e.Release)
|
||||
for _, t := range e.Tracks {
|
||||
out.Tracks = append(out.Tracks, wantTrackView{Disc: t.MediumPosition, Number: t.Position, Title: t.Title, LengthMs: t.LengthMs})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// standardEdition is the edition a person would call the album: an official
|
||||
// one with the fewest tracks, else any with the fewest. The catalogue lists
|
||||
// official editions first by date, so a tie goes to the earliest.
|
||||
func standardEdition(eds []catalogue.Edition) (catalogue.Edition, bool) {
|
||||
best := -1
|
||||
for i, e := range eds {
|
||||
if len(e.Tracks) == 0 {
|
||||
continue
|
||||
}
|
||||
if best < 0 {
|
||||
best = i
|
||||
continue
|
||||
}
|
||||
b := eds[best]
|
||||
bo, eo := b.Release.Status == "Official", e.Release.Status == "Official"
|
||||
if (eo && !bo) || (eo == bo && len(e.Tracks) < len(b.Tracks)) {
|
||||
best = i
|
||||
}
|
||||
}
|
||||
if best < 0 {
|
||||
return catalogue.Edition{}, false
|
||||
}
|
||||
return eds[best], true
|
||||
}
|
||||
|
||||
// editionLabel names a release for a person: "2023 · CD · GB".
|
||||
func editionLabel(r dbq.MbRelease) string {
|
||||
var parts []string
|
||||
for _, p := range []string{first4(r.ReleaseDate), r.Formats, r.Country} {
|
||||
if p != "" {
|
||||
parts = append(parts, p)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, " · ")
|
||||
}
|
||||
|
||||
func first4(date string) string {
|
||||
if len(date) < 4 {
|
||||
return ""
|
||||
}
|
||||
return date[:4]
|
||||
}
|
||||
|
||||
// handleRemoveWant implements DELETE /api/admin/wanted/{id}.
|
||||
func (h *handlers) handleRemoveWant(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
removed, err := h.wanted.RemoveWant(r.Context(), id)
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: remove", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
if !removed {
|
||||
writeErr(w, apierror.NotFound("want"))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// followView is a followed artist.
|
||||
type followView struct {
|
||||
ArtistMBID string `json:"artist_mbid"`
|
||||
ArtistName string `json:"artist_name"`
|
||||
ArtistID string `json:"artist_id,omitempty"`
|
||||
ProfileID string `json:"profile_id"`
|
||||
ProfileName string `json:"profile_name"`
|
||||
FollowedAt string `json:"followed_at"`
|
||||
CheckedAt *string `json:"checked_at"`
|
||||
OpenWants int64 `json:"open_wants"`
|
||||
ImageURL string `json:"image_url"`
|
||||
}
|
||||
|
||||
// handleListFollows implements GET /api/admin/follows.
|
||||
func (h *handlers) handleListFollows(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := dbq.New(h.pool).ListFollows(r.Context())
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin follows: list", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := make([]followView, 0, len(rows))
|
||||
for _, f := range rows {
|
||||
v := followView{
|
||||
ArtistMBID: f.ArtistMbid, ArtistName: f.ArtistName,
|
||||
ProfileID: uuidToString(f.ProfileID), ProfileName: f.ProfileName,
|
||||
FollowedAt: formatTimestamp(f.FollowedAt), OpenWants: f.OpenWants,
|
||||
ImageURL: artistArtURL(f.ArtistMbid, f.ArtistName),
|
||||
}
|
||||
if f.ArtistID.Valid {
|
||||
v.ArtistID = uuidToString(f.ArtistID)
|
||||
}
|
||||
if f.CheckedAt.Valid {
|
||||
checked := formatTimestamp(f.CheckedAt)
|
||||
v.CheckedAt = &checked
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// followStateView answers whether one artist is followed, for the control on
|
||||
// an artist page.
|
||||
type followStateView struct {
|
||||
Following bool `json:"following"`
|
||||
ProfileID string `json:"profile_id,omitempty"`
|
||||
ProfileName string `json:"profile_name,omitempty"`
|
||||
}
|
||||
|
||||
// handleGetFollow implements GET /api/admin/follows/{mbid}.
|
||||
func (h *handlers) handleGetFollow(w http.ResponseWriter, r *http.Request) {
|
||||
f, err := dbq.New(h.pool).GetFollow(r.Context(), chi.URLParam(r, "mbid"))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSON(w, http.StatusOK, followStateView{})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin follows: get", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, followStateView{
|
||||
Following: true, ProfileID: uuidToString(f.ProfileID), ProfileName: f.ProfileName,
|
||||
})
|
||||
}
|
||||
|
||||
type putFollowBody struct {
|
||||
ArtistName string `json:"artist_name"`
|
||||
ProfileID string `json:"profile_id"`
|
||||
WantExisting bool `json:"want_existing"`
|
||||
}
|
||||
|
||||
// handlePutFollow implements PUT /api/admin/follows/{mbid}: follow an artist,
|
||||
// or change the profile it is followed on. want_existing also wants what the
|
||||
// artist has already released that the profile passes and isn't held.
|
||||
func (h *handlers) handlePutFollow(w http.ResponseWriter, r *http.Request) {
|
||||
admin, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body putFollowBody
|
||||
if !decodeBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
var profile pgtype.UUID
|
||||
if body.ProfileID != "" {
|
||||
if profile, ok = parseUUID(body.ProfileID); !ok {
|
||||
writeErr(w, apierror.BadRequest("bad_profile", "profile_id is not an id"))
|
||||
return
|
||||
}
|
||||
}
|
||||
mbid := chi.URLParam(r, "mbid")
|
||||
if _, err := h.wanted.Follow(r.Context(), wanted.FollowParams{
|
||||
ArtistMBID: mbid, ArtistName: body.ArtistName, ProfileID: profile,
|
||||
By: admin.ID, WantExisting: body.WantExisting,
|
||||
}); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, wanted.ErrNotFollowable):
|
||||
writeErr(w, apierror.BadRequest("not_followable", "Various Artists and MusicBrainz placeholders can't be followed"))
|
||||
case errors.Is(err, wanted.ErrProfileNotFound):
|
||||
writeErr(w, apierror.BadRequest("profile_not_found", "no such profile"))
|
||||
default:
|
||||
writeErrWithLog(w, h.logger, "admin follows: put", apierror.Internal(err))
|
||||
}
|
||||
return
|
||||
}
|
||||
h.handleGetFollow(w, r)
|
||||
}
|
||||
|
||||
// handleDeleteFollow implements DELETE /api/admin/follows/{mbid}. What the
|
||||
// follow already wanted stays on the list.
|
||||
func (h *handlers) handleDeleteFollow(w http.ResponseWriter, r *http.Request) {
|
||||
removed, err := h.wanted.Unfollow(r.Context(), chi.URLParam(r, "mbid"))
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin follows: delete", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
if !removed {
|
||||
writeErr(w, apierror.NotFound("follow"))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// releaseProfileView is a release-type profile.
|
||||
type releaseProfileView struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
PrimaryTypes []string `json:"primary_types"`
|
||||
SecondaryTypes []string `json:"secondary_types"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
FollowCount int64 `json:"follow_count"`
|
||||
}
|
||||
|
||||
// releaseProfilesResponse also carries MusicBrainz's types, so the editor
|
||||
// offers exactly what a profile may hold.
|
||||
type releaseProfilesResponse struct {
|
||||
Profiles []releaseProfileView `json:"profiles"`
|
||||
PrimaryTypes []string `json:"primary_types"`
|
||||
SecondaryTypes []string `json:"secondary_types"`
|
||||
}
|
||||
|
||||
// handleListReleaseProfiles implements GET /api/admin/release-profiles.
|
||||
func (h *handlers) handleListReleaseProfiles(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := dbq.New(h.pool).ListReleaseTypeProfiles(r.Context())
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin release profiles: list", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := releaseProfilesResponse{
|
||||
Profiles: make([]releaseProfileView, 0, len(rows)),
|
||||
PrimaryTypes: wanted.PrimaryTypes, SecondaryTypes: wanted.SecondaryTypes,
|
||||
}
|
||||
for _, p := range rows {
|
||||
out.Profiles = append(out.Profiles, releaseProfileView{
|
||||
ID: uuidToString(p.ID), Name: p.Name, PrimaryTypes: p.PrimaryTypes,
|
||||
SecondaryTypes: p.SecondaryTypes, IsDefault: p.IsDefault, FollowCount: p.FollowCount,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
type releaseProfileBody struct {
|
||||
Name string `json:"name"`
|
||||
PrimaryTypes []string `json:"primary_types"`
|
||||
SecondaryTypes []string `json:"secondary_types"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
}
|
||||
|
||||
func (b releaseProfileBody) input() wanted.ProfileInput {
|
||||
return wanted.ProfileInput{
|
||||
Name: b.Name, PrimaryTypes: b.PrimaryTypes, SecondaryTypes: b.SecondaryTypes, IsDefault: b.IsDefault,
|
||||
}
|
||||
}
|
||||
|
||||
// handleCreateReleaseProfile implements POST /api/admin/release-profiles.
|
||||
func (h *handlers) handleCreateReleaseProfile(w http.ResponseWriter, r *http.Request) {
|
||||
var body releaseProfileBody
|
||||
if !decodeBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
p, err := h.wanted.CreateProfile(r.Context(), body.input())
|
||||
if err != nil {
|
||||
h.writeProfileErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, releaseProfileView{
|
||||
ID: uuidToString(p.ID), Name: p.Name, PrimaryTypes: p.PrimaryTypes,
|
||||
SecondaryTypes: p.SecondaryTypes, IsDefault: p.IsDefault,
|
||||
})
|
||||
}
|
||||
|
||||
// handleUpdateReleaseProfile implements PUT /api/admin/release-profiles/{id}.
|
||||
// A follow on the profile judges new releases by the new types from its next
|
||||
// check; releases it has already judged are not judged again.
|
||||
func (h *handlers) handleUpdateReleaseProfile(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body releaseProfileBody
|
||||
if !decodeBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
p, err := h.wanted.UpdateProfile(r.Context(), id, body.input())
|
||||
if err != nil {
|
||||
h.writeProfileErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, releaseProfileView{
|
||||
ID: uuidToString(p.ID), Name: p.Name, PrimaryTypes: p.PrimaryTypes,
|
||||
SecondaryTypes: p.SecondaryTypes, IsDefault: p.IsDefault,
|
||||
})
|
||||
}
|
||||
|
||||
// handleDeleteReleaseProfile implements DELETE
|
||||
// /api/admin/release-profiles/{id}.
|
||||
func (h *handlers) handleDeleteReleaseProfile(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.wanted.DeleteProfile(r.Context(), id); err != nil {
|
||||
h.writeProfileErr(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *handlers) writeProfileErr(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, wanted.ErrProfileInvalid):
|
||||
writeErr(w, apierror.BadRequest("profile_invalid", err.Error()))
|
||||
case errors.Is(err, wanted.ErrProfileNotFound):
|
||||
writeErr(w, apierror.NotFound("profile"))
|
||||
case errors.Is(err, wanted.ErrProfileNameUsed):
|
||||
writeErr(w, apierror.Conflict("profile_name_taken", "a profile already has that name"))
|
||||
case errors.Is(err, wanted.ErrProfileInUse):
|
||||
writeErr(w, apierror.Conflict("profile_in_use", "artists are followed on this profile; move them first"))
|
||||
case errors.Is(err, wanted.ErrProfileDefault):
|
||||
writeErr(w, apierror.Conflict("profile_is_default", "the default profile can't be deleted"))
|
||||
default:
|
||||
writeErrWithLog(w, h.logger, "admin release profiles", apierror.Internal(err))
|
||||
}
|
||||
}
|
||||
|
||||
// deref is a nullable column's text, or "".
|
||||
func deref(s *string) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return *s
|
||||
}
|
||||
|
||||
// handleListUnmatched implements GET /api/admin/wanted/unmatched: the
|
||||
// Collection's Unmatched section, the albums no MusicBrainz album
|
||||
// matched and, after them, the ones a person left off.
|
||||
func (h *handlers) handleListUnmatched(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := dbq.New(h.pool).ListUnmatchedLibraryAlbums(r.Context(), unmatchedShown)
|
||||
if err != nil {
|
||||
writeErrWithLog(w, h.logger, "admin wanted: unmatched", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := struct {
|
||||
Items []unmatchedAlbumView `json:"items"`
|
||||
}{Items: make([]unmatchedAlbumView, 0, len(rows))}
|
||||
for _, u := range rows {
|
||||
out.Items = append(out.Items, unmatchedAlbumView{
|
||||
AlbumID: uuidToString(u.AlbumID), Title: u.Title, Artist: u.ArtistName, Detail: u.Detail,
|
||||
Tracks: u.Tracks, LeftOff: u.Outcome == "dismissed", DecidedAt: formatTimestamp(u.DecidedAt),
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
type manualMatchView struct {
|
||||
ReleaseGroupMBID string `json:"release_group_mbid"`
|
||||
Title string `json:"title"`
|
||||
Artist string `json:"artist"`
|
||||
Agree int `json:"agree"`
|
||||
Tracks int `json:"tracks"`
|
||||
}
|
||||
|
||||
// handleMatchUnmatched implements POST /api/admin/wanted/unmatched/{id}/match
|
||||
// {"ref": "<MusicBrainz link or id>"}: the album goes on the list as held,
|
||||
// as that MusicBrainz album.
|
||||
func (h *handlers) handleMatchUnmatched(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Ref string `json:"ref"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeErr(w, apierror.BadRequest("bad_body", "expected {\"ref\": \"…\"}"))
|
||||
return
|
||||
}
|
||||
m, err := h.wanted.MatchAlbumTo(r.Context(), id, body.Ref)
|
||||
switch {
|
||||
case errors.Is(err, wanted.ErrMatchRef):
|
||||
writeErr(w, apierror.BadRequest("bad_ref", "That isn't a MusicBrainz album link or id."))
|
||||
return
|
||||
case errors.Is(err, wanted.ErrMatchNoGroup):
|
||||
writeErr(w, &apierror.Error{Status: http.StatusUnprocessableEntity, Code: "no_such_album",
|
||||
Message: "MusicBrainz has no album at that link.", Cause: err})
|
||||
return
|
||||
case errors.Is(err, wanted.ErrAlbumNotUnmatched):
|
||||
writeErr(w, apierror.NotFound("unmatched album"))
|
||||
return
|
||||
case errors.Is(err, musicbrainz.ErrUnreachable), errors.Is(err, musicbrainz.ErrBadResponse):
|
||||
writeErr(w, &apierror.Error{Status: http.StatusServiceUnavailable, Code: "musicbrainz_unreachable",
|
||||
Message: "MusicBrainz can't be reached", Cause: err})
|
||||
return
|
||||
case err != nil:
|
||||
writeErrWithLog(w, h.logger, "admin wanted: match by hand", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, manualMatchView{ReleaseGroupMBID: m.Group, Title: m.Title, Artist: m.Artist,
|
||||
Agree: m.Agree, Tracks: m.Tracks})
|
||||
}
|
||||
|
||||
// handleLeaveUnmatchedOff implements POST
|
||||
// /api/admin/wanted/unmatched/{id}/leave-off, and handlePutUnmatchedBack its
|
||||
// undoing, POST …/{id}/put-back.
|
||||
func (h *handlers) handleLeaveUnmatchedOff(w http.ResponseWriter, r *http.Request) {
|
||||
h.setUnmatched(w, r, h.wanted.LeaveAlbumOff)
|
||||
}
|
||||
|
||||
func (h *handlers) handlePutUnmatchedBack(w http.ResponseWriter, r *http.Request) {
|
||||
h.setUnmatched(w, r, h.wanted.PutAlbumBack)
|
||||
}
|
||||
|
||||
func (h *handlers) setUnmatched(w http.ResponseWriter, r *http.Request, set func(context.Context, pgtype.UUID) error) {
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
err := set(r.Context(), id)
|
||||
switch {
|
||||
case errors.Is(err, wanted.ErrAlbumNotUnmatched):
|
||||
writeErr(w, apierror.NotFound("unmatched album"))
|
||||
case err != nil:
|
||||
writeErrWithLog(w, h.logger, "admin wanted: unmatched", apierror.Internal(err))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -1,371 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/catalogue"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/wanted"
|
||||
)
|
||||
|
||||
func doWantedReq(t *testing.T, h *handlers, path string, user dbq.User) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return doWanted(t, h, http.MethodGet, path, "", user)
|
||||
}
|
||||
|
||||
func doWanted(t *testing.T, h *handlers, method, path, body string, user dbq.User) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := chi.NewRouter()
|
||||
r.Route("/api/admin", func(admin chi.Router) {
|
||||
admin.Use(auth.RequireAdmin())
|
||||
admin.Get("/wanted", h.handleListWants)
|
||||
admin.Get("/wanted/artists", h.handleListWantArtists)
|
||||
admin.Get("/wanted/unmatched", h.handleListUnmatched)
|
||||
admin.Post("/wanted/unmatched/{id}/match", h.handleMatchUnmatched)
|
||||
admin.Post("/wanted/unmatched/{id}/leave-off", h.handleLeaveUnmatchedOff)
|
||||
admin.Post("/wanted/unmatched/{id}/put-back", h.handlePutUnmatchedBack)
|
||||
admin.Get("/wanted/{id}/tracks", h.handleWantTracks)
|
||||
})
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, withUser(httptest.NewRequest(method, path, strings.NewReader(body)), user))
|
||||
return w
|
||||
}
|
||||
|
||||
func seedWant(t *testing.T, h *handlers, group, artistMBID, artist, title, date string) dbq.Want {
|
||||
t.Helper()
|
||||
w, err := wanted.WantWith(context.Background(), dbq.New(h.pool), wanted.WantParams{
|
||||
GroupMBID: group, ArtistMBID: artistMBID, ArtistName: artist, Title: title,
|
||||
PrimaryType: "Album", FirstReleaseDate: date, Reason: wanted.ReasonFollow,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func listWanted(t *testing.T, h *handlers, user dbq.User, q string) wantsPage {
|
||||
t.Helper()
|
||||
w := doWantedReq(t, h, "/api/admin/wanted?"+url.Values{"q": {q}}.Encode(), user)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var page wantsPage
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
// The list runs like the library: artists A–Z by the library's sort
|
||||
// name where the library holds the artist, each artist's albums oldest
|
||||
// first; q narrows it to an artist or an album.
|
||||
func TestListWants_ArtistsAToZThenTheirAlbumsByDate(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
ctx := context.Background()
|
||||
beatles := "a0000000-0000-4000-8000-000000000002"
|
||||
if _, err := dbq.New(h.pool).UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "The Beatles", SortName: "Beatles, The", Mbid: &beatles}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedWant(t, h, "g0000000-0000-4000-8000-000000000001", "a0000000-0000-4000-8000-000000000003", "Zeds", "Zed Album", "2001")
|
||||
seedWant(t, h, "g0000000-0000-4000-8000-000000000002", beatles, "The Beatles", "Abbey Road", "1969-09-26")
|
||||
seedWant(t, h, "g0000000-0000-4000-8000-000000000003", beatles, "The Beatles", "Please Please Me", "1963-03-22")
|
||||
seedWant(t, h, "g0000000-0000-4000-8000-000000000004", "a0000000-0000-4000-8000-000000000001", "Camel", "Moonmadness", "1976")
|
||||
|
||||
page := listWanted(t, h, admin, "")
|
||||
var got []string
|
||||
for _, it := range page.Items {
|
||||
got = append(got, it.ArtistName+"/"+it.Title)
|
||||
}
|
||||
want := "[The Beatles/Please Please Me The Beatles/Abbey Road Camel/Moonmadness Zeds/Zed Album]"
|
||||
if fmt.Sprint(got) != want {
|
||||
t.Errorf("order = %v, want %s", got, want)
|
||||
}
|
||||
if page.Items[0].ArtistID == "" || page.Items[2].ArtistID != "" {
|
||||
t.Errorf("artist ids = %q, %q: only an artist the library holds has one", page.Items[0].ArtistID, page.Items[2].ArtistID)
|
||||
}
|
||||
|
||||
page = listWanted(t, h, admin, "BEATLES")
|
||||
if len(page.Items) != 2 || page.Total != 2 {
|
||||
t.Errorf("q=BEATLES: %d items, total %d; want the two Beatles albums", len(page.Items), page.Total)
|
||||
}
|
||||
page = listWanted(t, h, admin, "moon")
|
||||
if len(page.Items) != 1 || page.Items[0].Title != "Moonmadness" || page.Total != 1 {
|
||||
t.Errorf("q=moon: %+v, total %d", page.Items, page.Total)
|
||||
}
|
||||
if page = listWanted(t, h, admin, "nothing like it"); len(page.Items) != 0 || page.Total != 0 {
|
||||
t.Errorf("no match: %d items, total %d", len(page.Items), page.Total)
|
||||
}
|
||||
}
|
||||
|
||||
// The Collection's catalogue: every artist on the list A–Z, each
|
||||
// with how many of their albums are held; an artist's page lists every album
|
||||
// of theirs, held or not, under that artist.
|
||||
func TestListWantArtists_CatalogueAndAnArtistsPage(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
ctx := context.Background()
|
||||
q := dbq.New(h.pool)
|
||||
beatles := "a0000000-0000-4000-8000-000000000002"
|
||||
camel := "a0000000-0000-4000-8000-000000000001"
|
||||
if _, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "The Beatles", SortName: "Beatles, The", Mbid: &beatles}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedWant(t, h, "g0000000-0000-4000-8000-000000000002", beatles, "The Beatles", "Abbey Road", "1969")
|
||||
held := seedWant(t, h, "g0000000-0000-4000-8000-000000000003", beatles, "The Beatles", "Please Please Me", "1963")
|
||||
if _, err := h.pool.Exec(ctx, `UPDATE wants SET fulfilled_at = now() WHERE id = $1`, held.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedWant(t, h, "g0000000-0000-4000-8000-000000000004", camel, "Camel", "Moonmadness", "1976")
|
||||
if _, err := h.pool.Exec(ctx, `INSERT INTO follows (artist_mbid, artist_name, profile_id)
|
||||
SELECT $1, 'Camel', id FROM release_type_profiles WHERE is_default`, camel); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
w := doWantedReq(t, h, "/api/admin/wanted/artists", admin)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var page wantArtistsPage
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 2 || page.Total != 2 || page.Counts.Artists != 2 {
|
||||
t.Fatalf("catalogue = %+v, total %d, artists %d", page.Items, page.Total, page.Counts.Artists)
|
||||
}
|
||||
b, c := page.Items[0], page.Items[1]
|
||||
if b.ArtistName != "The Beatles" || b.SortName != "Beatles, The" || b.Albums != 2 || b.Held != 1 || b.Wanted != 1 ||
|
||||
b.ArtistID == "" || b.Following || b.ImageURL == "" {
|
||||
t.Errorf("Beatles = %+v", b)
|
||||
}
|
||||
if c.ArtistName != "Camel" || c.Albums != 1 || c.Held != 0 || !c.Following || c.ArtistID != "" {
|
||||
t.Errorf("Camel = %+v", c)
|
||||
}
|
||||
|
||||
// q finds an artist by an album's title.
|
||||
w = doWantedReq(t, h, "/api/admin/wanted/artists?q=moon", admin)
|
||||
page = wantArtistsPage{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 1 || page.Items[0].ArtistName != "Camel" {
|
||||
t.Errorf("q=moon: %+v", page.Items)
|
||||
}
|
||||
|
||||
// The Beatles' page: both albums, held or not, headed by the artist.
|
||||
w = doWantedReq(t, h, "/api/admin/wanted?state=all&artist="+beatles, admin)
|
||||
var albums wantsPage
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &albums); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(albums.Items) != 2 || albums.Items[0].Title != "Please Please Me" || albums.Items[0].HeldAt == nil ||
|
||||
albums.Artist == nil || albums.Artist.Held != 1 {
|
||||
t.Errorf("artist page = %+v, head %+v", albums.Items, albums.Artist)
|
||||
}
|
||||
if w := doWantedReq(t, h, "/api/admin/wanted?state=all&artist=nobody", admin); w.Code != http.StatusNotFound {
|
||||
t.Errorf("an artist with nothing on the list: status %d, want 404", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeEditions is a MusicBrainz holding one group with two editions, the
|
||||
// shorter official one the standard, or 503 when down is set.
|
||||
func fakeEditions(t *testing.T, group string, down bool) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if down {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.URL.Path == "/release-group/"+group:
|
||||
_, _ = fmt.Fprintf(w, `{"id": %q, "title": "Moonmadness", "primary-type": "Album", "first-release-date": "1976"}`, group)
|
||||
case r.URL.Path == "/release" && r.URL.Query().Get("release-group") == group:
|
||||
_, _ = fmt.Fprint(w, `{"release-count": 2, "releases": [
|
||||
{"id": "r-deluxe", "title": "Moonmadness", "status": "Official", "date": "2009", "country": "GB",
|
||||
"media": [{"position": 1, "format": "CD", "tracks": [
|
||||
{"position": 1, "number": "1", "title": "Aristillus", "length": 120000, "recording": {"id": "rec-1"}},
|
||||
{"position": 2, "number": "2", "title": "Song Within a Song", "length": 433000, "recording": {"id": "rec-2"}},
|
||||
{"position": 3, "number": "3", "title": "Bonus", "length": 200000, "recording": {"id": "rec-3"}}]}]},
|
||||
{"id": "r-orig", "title": "Moonmadness", "status": "Official", "date": "1976-03", "country": "GB",
|
||||
"media": [{"position": 1, "format": "12\" Vinyl", "tracks": [
|
||||
{"position": 1, "number": "A1", "title": "Aristillus", "length": 120000, "recording": {"id": "rec-1"}},
|
||||
{"position": 2, "number": "A2", "title": "Song Within a Song", "length": 433000, "recording": {"id": "rec-2"}}]}]}]}`)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func wantTracks(t *testing.T, h *handlers, user dbq.User, id string) (int, wantTracksView) {
|
||||
t.Helper()
|
||||
w := doWantedReq(t, h, "/api/admin/wanted/"+id+"/tracks", user)
|
||||
var out wantTracksView
|
||||
if w.Code == http.StatusOK {
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return w.Code, out
|
||||
}
|
||||
|
||||
// An album not yet held shows MusicBrainz's standard edition: the shortest
|
||||
// official one.
|
||||
func TestWantTracks_StandardEditionFromMusicBrainz(t *testing.T) {
|
||||
const group = "g0000000-0000-4000-8000-000000000010"
|
||||
for _, down := range []bool{false, true} {
|
||||
h, pool := testHandlers(t)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
h.catalogue = catalogue.New(pool, &musicbrainz.Client{BaseURL: fakeEditions(t, group, down).URL,
|
||||
Pace: &musicbrainz.Pacer{}, Retries: -1}, h.logger)
|
||||
w := seedWant(t, h, group, "a0000000-0000-4000-8000-000000000001", "Camel", "Moonmadness", "1976")
|
||||
|
||||
code, out := wantTracks(t, h, admin, uuidToString(w.ID))
|
||||
if down {
|
||||
if code != http.StatusServiceUnavailable {
|
||||
t.Errorf("MusicBrainz down: status %d, want 503", code)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if code != http.StatusOK || out.Source != "musicbrainz" || len(out.Tracks) != 2 {
|
||||
t.Fatalf("status %d, %+v: want the two-track original", code, out)
|
||||
}
|
||||
if out.Edition != "1976 · 12\" Vinyl · GB" {
|
||||
t.Errorf("edition = %q", out.Edition)
|
||||
}
|
||||
if tr := out.Tracks[1]; tr.Disc != 1 || tr.Number != 2 || tr.Title != "Song Within a Song" || tr.LengthMs != 433000 {
|
||||
t.Errorf("track 2 = %+v", tr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A held album shows the library's own tracks, a lost file marked.
|
||||
func TestWantTracks_HeldAlbumShowsTheLibrarysTracks(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
ctx := context.Background()
|
||||
q := dbq.New(h.pool)
|
||||
mbid := "a0000000-0000-4000-8000-000000000001"
|
||||
artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Camel", SortName: "Camel", Mbid: &mbid})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
album, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Moonmadness", SortTitle: "Moonmadness", ArtistID: artist.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, title := range []string{"Aristillus", "Song Within a Song"} {
|
||||
num := int32(i + 1)
|
||||
if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
|
||||
Title: title, AlbumID: album.ID, ArtistID: artist.ID, TrackNumber: &num, DurationMs: 120000,
|
||||
FilePath: fmt.Sprintf("/music/camel/%02d.flac", i+1), FileSize: 1, FileFormat: "flac",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := h.pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE title = 'Aristillus'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := seedWant(t, h, "g0000000-0000-4000-8000-000000000011", mbid, "Camel", "Moonmadness", "1976")
|
||||
if err := q.FulfillWant(ctx, dbq.FulfillWantParams{ID: w.ID, AlbumID: album.ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
code, out := wantTracks(t, h, admin, uuidToString(w.ID))
|
||||
if code != http.StatusOK || out.Source != "library" || len(out.Tracks) != 2 {
|
||||
t.Fatalf("status %d, %+v", code, out)
|
||||
}
|
||||
if !out.Tracks[0].Missing || out.Tracks[1].Missing || out.Tracks[1].Number != 2 {
|
||||
t.Errorf("tracks = %+v: the first is missing, the second on disk", out.Tracks)
|
||||
}
|
||||
}
|
||||
|
||||
// The Unmatched section: the albums matching could not place, a
|
||||
// local band's album left off and put back, and a link that names no
|
||||
// MusicBrainz album refused before MusicBrainz is asked.
|
||||
func TestUnmatched_ListLeaveOffPutBack(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
admin := seedUser(t, h.pool, "admin", "pw", true)
|
||||
ctx := context.Background()
|
||||
q := dbq.New(h.pool)
|
||||
artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Annadale", SortName: "Annadale"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
album, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Dial Tone", SortTitle: "Dial Tone", ArtistID: artist.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
|
||||
Title: "Intro", AlbumID: album.ID, ArtistID: artist.ID, DurationMs: 120000,
|
||||
FilePath: "/music/annadale/01.flac", FileSize: 1, FileFormat: "flac",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := q.RecordAlbumMatch(ctx, dbq.RecordAlbumMatchParams{
|
||||
AlbumID: album.ID, Outcome: "unmatched", Detail: "MusicBrainz has no album by that name", Matcher: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := uuidToString(album.ID)
|
||||
|
||||
list := func() []unmatchedAlbumView {
|
||||
t.Helper()
|
||||
w := doWantedReq(t, h, "/api/admin/wanted/unmatched", admin)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var out struct {
|
||||
Items []unmatchedAlbumView `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out.Items
|
||||
}
|
||||
if got := list(); len(got) != 1 || got[0].AlbumID != id || got[0].Artist != "Annadale" || got[0].Tracks != 1 ||
|
||||
got[0].LeftOff || got[0].Detail == "" || got[0].DecidedAt == "" {
|
||||
t.Fatalf("unmatched = %+v", got)
|
||||
}
|
||||
|
||||
for _, c := range []struct {
|
||||
path, body string
|
||||
code int
|
||||
}{
|
||||
{"/api/admin/wanted/unmatched/" + id + "/match", `{"ref":"Dial Tone"}`, http.StatusBadRequest},
|
||||
{"/api/admin/wanted/unmatched/" + id + "/match", `nope`, http.StatusBadRequest},
|
||||
{"/api/admin/wanted/unmatched/not-a-uuid/leave-off", "", http.StatusBadRequest},
|
||||
{"/api/admin/wanted/unmatched/" + id + "/put-back", "", http.StatusNotFound},
|
||||
{"/api/admin/wanted/unmatched/" + id + "/leave-off", "", http.StatusNoContent},
|
||||
{"/api/admin/wanted/unmatched/" + id + "/leave-off", "", http.StatusNotFound},
|
||||
} {
|
||||
if w := doWanted(t, h, http.MethodPost, c.path, c.body, admin); w.Code != c.code {
|
||||
t.Errorf("POST %s %s = %d, want %d; body = %s", c.path, c.body, w.Code, c.code, w.Body.String())
|
||||
}
|
||||
}
|
||||
if got := list(); len(got) != 1 || !got[0].LeftOff {
|
||||
t.Fatalf("left off = %+v", got)
|
||||
}
|
||||
if w := doWanted(t, h, http.MethodPost, "/api/admin/wanted/unmatched/"+id+"/put-back", "", admin); w.Code != http.StatusNoContent {
|
||||
t.Fatalf("put back = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
if got := list(); len(got) != 1 || got[0].LeftOff {
|
||||
t.Errorf("put back = %+v", got)
|
||||
}
|
||||
|
||||
user := seedUser(t, h.pool, "listener", "pw", false)
|
||||
if w := doWantedReq(t, h, "/api/admin/wanted/unmatched", user); w.Code != http.StatusForbidden {
|
||||
t.Errorf("a listener reads the unmatched section: %d", w.Code)
|
||||
}
|
||||
}
|
||||
+1
-136
@@ -13,35 +13,28 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/acquire"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/backup"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/catalogue"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/config"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/importer"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/lifecycle"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/netsettings"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/notifications"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/quarantine"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/reacquisition"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/recommendation"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/recsettings"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/requests"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/tags"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/tracks"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/wanted"
|
||||
)
|
||||
|
||||
// Mount attaches /api/* handlers to r. Public endpoints (login) are outside
|
||||
// RequireUser; everything else is gated by the middleware. The events writer
|
||||
// is shared with the Subsonic mount so /rest/scrobble feeds the same store.
|
||||
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, recSettings *recsettings.Service, requestSvc *requests.Service, quarantineSvc *quarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, tagSettings *tags.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler, streamSecret []byte, netSettings *netsettings.Service, reacqSettings *reacquisition.SettingsService, fpSettings *library.FingerprintSettingsService, loudSettings *library.LoudnessSettingsService, acoustIDLookup *library.AcoustIDLookupWorker, backups *backup.Service, restart func()) {
|
||||
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playevents.Writer, recCfg config.RecommendationConfig, recSettings *recsettings.Service, quarantineSvc *quarantine.Service, tracksSvc *tracks.Service, playlistsSvc *playlists.Service, coverEnricher *coverart.Enricher, coverSettings *coverart.SettingsService, tagSettings *tags.SettingsService, scanner *library.Scanner, scanCfg library.RunScanConfig, dataDir string, sender mailer.Sender, bus *eventbus.Bus, playlistScheduler *playlists.Scheduler, streamSecret []byte, netSettings *netsettings.Service, fpSettings *library.FingerprintSettingsService, loudSettings *library.LoudnessSettingsService, acoustIDLookup *library.AcoustIDLookupWorker, backups *backup.Service, restart func()) {
|
||||
rng := rand.New(rand.NewSource(rand.Int63()))
|
||||
setupToken, err := auth.NewSetupToken()
|
||||
if err != nil {
|
||||
@@ -50,12 +43,10 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
panic("api: mint setup token: " + err.Error())
|
||||
}
|
||||
logSetupTokenIfNeeded(pool, logger, setupToken)
|
||||
cat := catalogue.New(pool, nil, logger)
|
||||
h := &handlers{
|
||||
pool: pool, logger: logger, events: events, recCfg: recCfg,
|
||||
recSettings: recSettings,
|
||||
rng: rng.Float64,
|
||||
requests: requestSvc,
|
||||
quarantine: quarantineSvc,
|
||||
tracks: tracksSvc,
|
||||
playlists: playlistsSvc,
|
||||
@@ -71,20 +62,11 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
playlistScheduler: playlistScheduler,
|
||||
streamSecret: streamSecret,
|
||||
netSettings: netSettings,
|
||||
reacqSettings: reacqSettings,
|
||||
fingerprintSettings: fpSettings,
|
||||
loudnessSettings: loudSettings,
|
||||
acoustIDLookup: acoustIDLookup,
|
||||
backups: backups,
|
||||
restart: restart,
|
||||
acquisition: acquire.NewStore(pool),
|
||||
catalogue: cat,
|
||||
wanted: wanted.New(pool, cat, logger),
|
||||
searcher: wanted.NewSearcher(pool, cat, logger),
|
||||
importer: importer.New(pool, scanner, cat, nil, scannerRoots(scanner), logger),
|
||||
lifecycle: lifecycle.New(pool, logger),
|
||||
catalogueSearches: newSearchCache(),
|
||||
catalogueArt: catalogue.NewArt(dataDir, artSources(coverSettings)),
|
||||
leveled: newLeveledRenderer(dataDir, loudSettings, logger),
|
||||
librarySize: recommendation.NewLibrarySize(nil),
|
||||
loginGuard: auth.NewLoginGuard(),
|
||||
@@ -170,12 +152,6 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
// it can accept either a session or a signed token.
|
||||
authed.Get("/search", h.handleSearch)
|
||||
authed.Get("/radio", h.handleRadio)
|
||||
authed.Get("/discover/suggestions", h.handleListSuggestions)
|
||||
// Snooze = "not right now", time-boxed and self-expiring.
|
||||
// Not a dislike — see the migration for why.
|
||||
authed.Post("/discover/suggestions/{mbid}/snooze", h.handleSnoozeSuggestion)
|
||||
authed.Delete("/discover/suggestions/{mbid}/snooze", h.handleUnsnoozeSuggestion)
|
||||
authed.Get("/discover/snoozes", h.handleListSuggestionSnoozes)
|
||||
authed.Get("/home", h.handleGetHome)
|
||||
authed.Get("/home/index", h.handleGetHomeIndex)
|
||||
authed.Post("/events", h.handleEvents)
|
||||
@@ -194,17 +170,6 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
authed.Get("/likes/artists", h.handleListLikedArtists)
|
||||
authed.Get("/likes/ids", h.handleGetLikedIDs)
|
||||
|
||||
// The release catalogue: request search asks
|
||||
// MusicBrainz, and art for what isn't held comes through
|
||||
// Minstrel from the enabled cover-art sources.
|
||||
authed.Get("/catalogue/search", h.handleCatalogueSearch)
|
||||
authed.Get("/catalogue/art/{kind}/{mbid}", h.handleCatalogueArt)
|
||||
|
||||
authed.Post("/requests", h.handleCreateRequest)
|
||||
authed.Get("/requests", h.handleListRequests)
|
||||
authed.Get("/requests/{id}", h.handleGetRequest)
|
||||
authed.Delete("/requests/{id}", h.handleCancelRequest)
|
||||
|
||||
authed.Post("/quarantine", h.handleFlag)
|
||||
authed.Delete("/quarantine/{track_id}", h.handleUnflag)
|
||||
authed.Get("/quarantine/mine", h.handleListMyQuarantine)
|
||||
@@ -227,57 +192,10 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
|
||||
authed.Route("/admin", func(admin chi.Router) {
|
||||
admin.Use(auth.RequireAdmin())
|
||||
admin.Get("/acquisition/services", h.handleListAcquisitionServices)
|
||||
admin.Post("/acquisition/services", h.handleCreateAcquisitionService)
|
||||
admin.Put("/acquisition/services/{code}", h.handleUpdateAcquisitionService)
|
||||
admin.Delete("/acquisition/services/{code}", h.handleDeleteAcquisitionService)
|
||||
admin.Post("/acquisition/services/{code}/test", h.handleTestAcquisitionService)
|
||||
admin.Put("/acquisition/services/{code}/api-key", h.handleSetAcquisitionSecret("api_key"))
|
||||
admin.Delete("/acquisition/services/{code}/api-key", h.handleSetAcquisitionSecret("api_key"))
|
||||
admin.Put("/acquisition/services/{code}/password", h.handleSetAcquisitionSecret("password"))
|
||||
admin.Delete("/acquisition/services/{code}/password", h.handleSetAcquisitionSecret("password"))
|
||||
// The queues that wait on an admin, for the rail and the
|
||||
// Overview.
|
||||
admin.Get("/summary", h.handleGetAdminSummary)
|
||||
admin.Get("/status", h.handleGetAdminStatus)
|
||||
admin.Get("/requests", h.handleListAdminRequests)
|
||||
admin.Post("/requests/{id}/approve", h.handleApproveRequest)
|
||||
admin.Post("/requests/{id}/reject", h.handleRejectRequest)
|
||||
|
||||
// The wanted list: what Minstrel is looking
|
||||
// for, the artists it follows, and the release-type
|
||||
// profiles that decide which of their releases count.
|
||||
admin.Get("/wanted", h.handleListWants)
|
||||
admin.Get("/wanted/artists", h.handleListWantArtists)
|
||||
admin.Get("/wanted/unmatched", h.handleListUnmatched)
|
||||
admin.Post("/wanted/unmatched/{id}/match", h.handleMatchUnmatched)
|
||||
admin.Post("/wanted/unmatched/{id}/leave-off", h.handleLeaveUnmatchedOff)
|
||||
admin.Post("/wanted/unmatched/{id}/put-back", h.handlePutUnmatchedBack)
|
||||
admin.Delete("/wanted/{id}", h.handleRemoveWant)
|
||||
// Searching and grabbing.
|
||||
admin.Get("/acquisition/settings", h.handleGetSearchSettings)
|
||||
admin.Put("/acquisition/settings", h.handlePutSearchSettings)
|
||||
admin.Get("/wanted/{id}/candidates", h.handleListCandidates)
|
||||
admin.Get("/wanted/{id}/tracks", h.handleWantTracks)
|
||||
admin.Post("/wanted/{id}/search", h.handleSearchWant)
|
||||
admin.Post("/wanted/{id}/grab", h.handleGrabCandidate)
|
||||
admin.Post("/wanted/{id}/block", h.handleBlockCandidate)
|
||||
admin.Delete("/release-blocks/{hash}", h.handleUnblockRelease)
|
||||
admin.Get("/release-blocks", h.handleListReleaseBlocks)
|
||||
admin.Get("/downloads", h.handleListDownloads)
|
||||
admin.Post("/downloads/{id}/import", h.handleImportAnyway)
|
||||
admin.Post("/downloads/{id}/retry", h.handleRetryImport)
|
||||
admin.Post("/downloads/{id}/refuse", h.handleRefuseDownload)
|
||||
admin.Post("/downloads/{id}/abandon", h.handleAbandonDownload)
|
||||
admin.Get("/follows", h.handleListFollows)
|
||||
admin.Get("/follows/{mbid}", h.handleGetFollow)
|
||||
admin.Put("/follows/{mbid}", h.handlePutFollow)
|
||||
admin.Delete("/follows/{mbid}", h.handleDeleteFollow)
|
||||
admin.Get("/release-profiles", h.handleListReleaseProfiles)
|
||||
admin.Post("/release-profiles", h.handleCreateReleaseProfile)
|
||||
admin.Put("/release-profiles/{id}", h.handleUpdateReleaseProfile)
|
||||
admin.Delete("/release-profiles/{id}", h.handleDeleteReleaseProfile)
|
||||
|
||||
admin.Get("/quarantine", h.handleListAdminQuarantine)
|
||||
admin.Post("/quarantine/{track_id}/resolve", h.handleResolveQuarantine)
|
||||
|
||||
@@ -294,12 +212,6 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
admin.Get("/network-settings", h.handleGetNetworkSettings)
|
||||
admin.Put("/network-settings", h.handleUpdateNetworkSettings)
|
||||
|
||||
// Policy for wanting back an album whose files went missing
|
||||
// Sits beside the missing-files list it governs, because an
|
||||
// admin meets it on that surface.
|
||||
admin.Get("/library/reacquisition", h.handleGetReacquisitionSettings)
|
||||
admin.Put("/library/reacquisition", h.handleUpdateReacquisitionSettings)
|
||||
|
||||
// Where the library lives. A changed folder moves its
|
||||
// tracks rather than re-adding them.
|
||||
admin.Get("/library/folders", h.handleGetLibraryFolders)
|
||||
@@ -345,7 +257,6 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
|
||||
admin.Post("/users", h.handleAdminCreateUser)
|
||||
admin.Delete("/users/{id}", h.handleAdminDeleteUser)
|
||||
admin.Post("/users/{id}/reset-password", h.handleAdminResetPassword)
|
||||
admin.Put("/users/{id}/auto-approve", h.handleAdminAutoApproveToggle)
|
||||
admin.Put("/users/{id}/debug-mode", h.handleAdminDebugModeToggle)
|
||||
|
||||
// Device diagnostics timeline + device overview.
|
||||
@@ -408,7 +319,6 @@ type handlers struct {
|
||||
// Held here rather than counted per request: the count is a
|
||||
// full table scan, and library size only moves when a scan runs.
|
||||
librarySize *recommendation.LibrarySize
|
||||
requests *requests.Service
|
||||
quarantine *quarantine.Service
|
||||
tracks *tracks.Service
|
||||
playlists *playlists.Service
|
||||
@@ -424,10 +334,6 @@ type handlers struct {
|
||||
// notifier records nothing, which is what most handler tests want.
|
||||
notifier *notifications.Notifier
|
||||
playlistScheduler *playlists.Scheduler
|
||||
// reacqSettings is the DB-backed policy for auto re-acquisition of
|
||||
// missing files — grace window, backoff, attempt caps.
|
||||
// Cached in the service, so the admin card reads it without a query.
|
||||
reacqSettings *reacquisition.SettingsService
|
||||
// fingerprintSettings is the fingerprinting policy, the same
|
||||
// instance the scanner and the fingerprint workers read, so a save from the
|
||||
// admin card reaches them without a restart. Nil serves the defaults.
|
||||
@@ -443,26 +349,6 @@ type handlers struct {
|
||||
// restart stops the server and starts it again in place, so a restored
|
||||
// backup's settings are read at boot. Nil in tests.
|
||||
restart func()
|
||||
// acquisition is the configured indexers and download clients.
|
||||
acquisition *acquire.Store
|
||||
// catalogue is the release catalogue read from MusicBrainz, and
|
||||
// catalogueArt the images for what isn't held.
|
||||
catalogue *catalogue.Service
|
||||
catalogueArt *catalogue.Art
|
||||
// wanted is the wanted list: follows, release-type profiles and wants.
|
||||
// Its worker runs in main; the API reads and edits.
|
||||
wanted *wanted.Service
|
||||
// searcher searches for wants and grabs releases for them.
|
||||
searcher *wanted.Searcher
|
||||
// importer refuses a download at a person's word. The import
|
||||
// loop itself runs in main; this one only acts on a request.
|
||||
importer *importer.Importer
|
||||
// lifecycle gives up on a download at a person's word; its loop
|
||||
// runs in main.
|
||||
lifecycle *lifecycle.Service
|
||||
// catalogueSearches reuses recent MusicBrainz answers; nil asks every
|
||||
// time, which is what handler tests get.
|
||||
catalogueSearches *searchCache
|
||||
// leveled renders the leveled streams handed to Sonos/UPnP speakers. Nil
|
||||
// when its cache directory cannot be made: a level request then gets the
|
||||
// plain stream.
|
||||
@@ -502,24 +388,3 @@ func newLeveledRenderer(dataDir string, settings *library.LoudnessSettingsServic
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// artSources hands the art cache the cover-art settings, or nothing when
|
||||
// there are none: a nil *SettingsService inside the interface would not
|
||||
// compare equal to nil and would be called.
|
||||
func artSources(s *coverart.SettingsService) catalogue.ArtSources {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// scannerRoots reads the library folders, or none when the API runs without
|
||||
// a scanner (tests).
|
||||
func scannerRoots(s *library.Scanner) func() []string {
|
||||
return func() []string {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s.Roots()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/catalogue"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/config"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
@@ -30,9 +29,7 @@ import (
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/quarantine"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/recsettings"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/requests"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/tracks"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/wanted"
|
||||
)
|
||||
|
||||
// testHandlers spins up a handlers instance against MINSTREL_TEST_DATABASE_URL.
|
||||
@@ -65,13 +62,11 @@ func testHandlers(t *testing.T) (*handlers, *pgxpool.Pool) {
|
||||
if err != nil {
|
||||
t.Fatalf("recsettings: %v", err)
|
||||
}
|
||||
requestSvc := requests.NewService(pool)
|
||||
cat := catalogue.New(pool, nil, logger)
|
||||
quarantineSvc := quarantine.NewService(pool, "")
|
||||
dataDir := t.TempDir()
|
||||
tracksSvc := tracks.NewService(pool, logger, dataDir)
|
||||
playlistsSvc := playlists.NewService(pool, logger, dataDir)
|
||||
h := &handlers{pool: pool, logger: logger, events: w, recCfg: recCfg, recSettings: recSettings, rng: func() float64 { return 0.5 }, requests: requestSvc, catalogue: cat, wanted: wanted.New(pool, cat, logger), quarantine: quarantineSvc, tracks: tracksSvc, playlists: playlistsSvc, dataDir: dataDir, scanner: nil, scanCfg: library.RunScanConfig{}, mailer: &mailer.FakeSender{}, notifier: notifications.New(pool, nil, nil)}
|
||||
h := &handlers{pool: pool, logger: logger, events: w, recCfg: recCfg, recSettings: recSettings, rng: func() float64 { return 0.5 }, quarantine: quarantineSvc, tracks: tracksSvc, playlists: playlistsSvc, dataDir: dataDir, scanner: nil, scanCfg: library.RunScanConfig{}, mailer: &mailer.FakeSender{}, notifier: notifications.New(pool, nil, nil)}
|
||||
return h, pool
|
||||
}
|
||||
|
||||
@@ -223,6 +218,12 @@ func TestHandleLogin_MalformedBodyReturns400(t *testing.T) {
|
||||
|
||||
func userCtxKeyForTest() any { return auth.UserCtxKeyForTest() }
|
||||
|
||||
// withUser injects a user into the request context the same way RequireUser
|
||||
// does.
|
||||
func withUser(req *http.Request, user dbq.User) *http.Request {
|
||||
return req.WithContext(context.WithValue(req.Context(), userCtxKeyForTest(), user))
|
||||
}
|
||||
|
||||
func TestHandleLogout_DeletesSessionAndClearsCookie(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "hunter2", false)
|
||||
|
||||
@@ -1,284 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/catalogue"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz"
|
||||
)
|
||||
|
||||
// catalogueSearchLimit is how many results one search shows.
|
||||
const catalogueSearchLimit = 25
|
||||
|
||||
// catalogueSearchResult is one row of GET /api/catalogue/search, read by the
|
||||
// Discover page and request rows. artist_mbid and album_mbid are the parents a
|
||||
// request needs: empty on an artist, the artist on an album, both on a track.
|
||||
// An album is a MusicBrainz release group.
|
||||
type catalogueSearchResult struct {
|
||||
MBID string `json:"mbid"`
|
||||
Name string `json:"name"`
|
||||
SecondaryText string `json:"secondary_text"`
|
||||
ImageURL string `json:"image_url"`
|
||||
ArtistMBID string `json:"artist_mbid"`
|
||||
AlbumMBID string `json:"album_mbid"`
|
||||
InLibrary bool `json:"in_library"`
|
||||
Requested bool `json:"requested"`
|
||||
}
|
||||
|
||||
// handleCatalogueSearch implements GET
|
||||
// /api/catalogue/search?q=&kind=artist|album|track asking MusicBrainz directly.
|
||||
// An unreachable MusicBrainz is a 503 the page shows as such, not an empty
|
||||
// result.
|
||||
func (h *handlers) handleCatalogueSearch(w http.ResponseWriter, r *http.Request) {
|
||||
kind := strings.TrimSpace(r.URL.Query().Get("kind"))
|
||||
switch kind {
|
||||
case "artist", "album", "track":
|
||||
default:
|
||||
writeErr(w, apierror.BadRequest("bad_kind", "kind must be artist, album, or track"))
|
||||
return
|
||||
}
|
||||
q := strings.TrimSpace(r.URL.Query().Get("q"))
|
||||
if q == "" {
|
||||
writeErr(w, apierror.BadRequest("missing_query", "q is required"))
|
||||
return
|
||||
}
|
||||
|
||||
out, err := h.catalogueSearches.get(r.Context(), kind, q, h.searchCatalogue)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, musicbrainz.ErrUnreachable), errors.Is(err, musicbrainz.ErrBadResponse):
|
||||
writeErr(w, &apierror.Error{Status: 503, Code: "musicbrainz_unreachable", Message: "MusicBrainz can't be reached", Cause: err})
|
||||
case r.Context().Err() != nil:
|
||||
return
|
||||
default:
|
||||
h.logger.Error("api: catalogue search", "kind", kind, "err", err)
|
||||
writeErr(w, apierror.InternalMsg("search failed", err))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
dbQ := dbq.New(h.pool)
|
||||
for i := range out {
|
||||
inLib, err := h.catalogueInLibrary(r.Context(), kind, out[i].MBID)
|
||||
if err != nil {
|
||||
writeErr(w, apierror.InternalMsg("library check failed", err))
|
||||
return
|
||||
}
|
||||
requested, err := dbQ.HasNonTerminalRequestForMBID(r.Context(), out[i].MBID)
|
||||
if err != nil {
|
||||
writeErr(w, apierror.InternalMsg("request check failed", err))
|
||||
return
|
||||
}
|
||||
out[i].InLibrary, out[i].Requested = inLib, requested
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (h *handlers) searchCatalogue(ctx context.Context, kind, q string) ([]catalogueSearchResult, error) {
|
||||
mb := h.catalogue.MusicBrainz()
|
||||
out := []catalogueSearchResult{}
|
||||
switch kind {
|
||||
case "artist":
|
||||
artists, err := mb.SearchArtists(ctx, q, catalogueSearchLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, a := range artists {
|
||||
out = append(out, catalogueSearchResult{
|
||||
MBID: a.MBID, Name: a.Name, SecondaryText: artistLine(a),
|
||||
ImageURL: artistArtURL(a.MBID, a.Name),
|
||||
})
|
||||
}
|
||||
case "album":
|
||||
groups, err := mb.SearchReleaseGroups(ctx, q, catalogueSearchLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, g := range groups {
|
||||
out = append(out, catalogueSearchResult{
|
||||
MBID: g.MBID, Name: g.Title, SecondaryText: joinNonEmpty(g.ArtistCredit, g.Year(), groupType(g)),
|
||||
ImageURL: groupArtURL(g), ArtistMBID: first(g.ArtistMBIDs),
|
||||
})
|
||||
}
|
||||
case "track":
|
||||
recs, err := mb.SearchRecordings(ctx, q, catalogueSearchLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, rec := range recs {
|
||||
res := catalogueSearchResult{
|
||||
MBID: rec.MBID, Name: rec.Title,
|
||||
SecondaryText: joinNonEmpty(rec.ReleaseGroup.Title, rec.ArtistCredit),
|
||||
ArtistMBID: first(rec.ArtistMBIDs), AlbumMBID: rec.ReleaseGroup.MBID,
|
||||
}
|
||||
if rec.ReleaseGroup.MBID != "" {
|
||||
res.ImageURL = groupArtURL(rec.ReleaseGroup)
|
||||
}
|
||||
out = append(out, res)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// catalogueSearchTTL is how long a search's MusicBrainz answer is reused.
|
||||
// MusicBrainz allows a request a second, and Discover searches as the user
|
||||
// types, so the same words are often asked again within moments.
|
||||
const catalogueSearchTTL = 10 * time.Minute
|
||||
|
||||
// catalogueSearchCacheMax bounds the cache; past it, the cache starts over.
|
||||
const catalogueSearchCacheMax = 500
|
||||
|
||||
// searchCache keeps recent MusicBrainz answers by kind and query. A nil
|
||||
// cache asks every time. Whether a result is held or requested is not
|
||||
// cached: the handler works that out on every request.
|
||||
type searchCache struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]searchEntry
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type searchEntry struct {
|
||||
at time.Time
|
||||
results []catalogueSearchResult
|
||||
}
|
||||
|
||||
func newSearchCache() *searchCache {
|
||||
return &searchCache{entries: map[string]searchEntry{}, now: time.Now}
|
||||
}
|
||||
|
||||
func (c *searchCache) get(ctx context.Context, kind, q string,
|
||||
ask func(context.Context, string, string) ([]catalogueSearchResult, error),
|
||||
) ([]catalogueSearchResult, error) {
|
||||
if c == nil {
|
||||
return ask(ctx, kind, q)
|
||||
}
|
||||
key := kind + "\x00" + strings.ToLower(q)
|
||||
c.mu.Lock()
|
||||
e, ok := c.entries[key]
|
||||
c.mu.Unlock()
|
||||
if ok && c.now().Sub(e.at) < catalogueSearchTTL {
|
||||
return slices.Clone(e.results), nil
|
||||
}
|
||||
results, err := ask(ctx, kind, q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.mu.Lock()
|
||||
if len(c.entries) >= catalogueSearchCacheMax {
|
||||
c.entries = map[string]searchEntry{}
|
||||
}
|
||||
c.entries[key] = searchEntry{at: c.now(), results: slices.Clone(results)}
|
||||
c.mu.Unlock()
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// artistLine is what tells two artists of one name apart: MusicBrainz's own
|
||||
// disambiguation when it has one, else the kind of artist and the country.
|
||||
func artistLine(a musicbrainz.Artist) string {
|
||||
if a.Disambiguation != "" {
|
||||
return a.Disambiguation
|
||||
}
|
||||
return joinNonEmpty(a.Type, a.Country)
|
||||
}
|
||||
|
||||
// groupType names an album's kind the way people do: "Album", "EP",
|
||||
// "Album · Live", "Single · Remix".
|
||||
func groupType(g musicbrainz.ReleaseGroup) string {
|
||||
return joinNonEmpty(append([]string{g.PrimaryType}, g.SecondaryTypes...)...)
|
||||
}
|
||||
|
||||
func joinNonEmpty(parts ...string) string {
|
||||
kept := parts[:0:0]
|
||||
for _, p := range parts {
|
||||
if p != "" {
|
||||
kept = append(kept, p)
|
||||
}
|
||||
}
|
||||
return strings.Join(kept, " · ")
|
||||
}
|
||||
|
||||
func first(s []string) string {
|
||||
if len(s) == 0 {
|
||||
return ""
|
||||
}
|
||||
return s[0]
|
||||
}
|
||||
|
||||
// artistArtURL and groupArtURL point at Minstrel's own art endpoints. The
|
||||
// names ride along for the sources that look art up by name.
|
||||
func artistArtURL(mbid, name string) string {
|
||||
if mbid == "" {
|
||||
return ""
|
||||
}
|
||||
return "/api/catalogue/art/artist/" + mbid + "?" + url.Values{"name": {name}}.Encode()
|
||||
}
|
||||
|
||||
func groupArtURL(g musicbrainz.ReleaseGroup) string {
|
||||
return "/api/catalogue/art/release-group/" + g.MBID + "?" +
|
||||
url.Values{"artist": {g.ArtistCredit}, "title": {g.Title}}.Encode()
|
||||
}
|
||||
|
||||
// catalogueInLibrary reports whether a result is already held: an artist by
|
||||
// its MBID, an album by its release group (or a release id that happens to be
|
||||
// the same), a track by its recording.
|
||||
func (h *handlers) catalogueInLibrary(ctx context.Context, kind, mbid string) (bool, error) {
|
||||
var query string
|
||||
switch kind {
|
||||
case "artist":
|
||||
query = `SELECT EXISTS(SELECT 1 FROM artists WHERE mbid = $1)`
|
||||
case "album":
|
||||
query = `SELECT EXISTS(SELECT 1 FROM albums WHERE release_group_mbid = $1 OR mbid = $1)`
|
||||
case "track":
|
||||
query = `SELECT EXISTS(SELECT 1 FROM tracks WHERE mbid = $1)`
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
var exists bool
|
||||
err := h.pool.QueryRow(ctx, query, mbid).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
// handleCatalogueArt implements GET /api/catalogue/art/{kind}/{mbid} for an
|
||||
// artist or a release group Minstrel doesn't hold. The image comes from the
|
||||
// enabled cover-art sources and is kept on disk, so the browser
|
||||
// never fetches a third-party host. A 404 shows the placeholder.
|
||||
func (h *handlers) handleCatalogueArt(w http.ResponseWriter, r *http.Request) {
|
||||
kind, mbid := chi.URLParam(r, "kind"), chi.URLParam(r, "mbid")
|
||||
if !catalogue.ValidMBID(mbid) {
|
||||
writeErr(w, apierror.NotFound("art"))
|
||||
return
|
||||
}
|
||||
var (
|
||||
body []byte
|
||||
err error
|
||||
)
|
||||
switch kind {
|
||||
case "artist":
|
||||
body, err = h.catalogueArt.Artist(r.Context(), mbid, r.URL.Query().Get("name"))
|
||||
case "release-group":
|
||||
body, err = h.catalogueArt.ReleaseGroup(r.Context(), mbid, r.URL.Query().Get("artist"), r.URL.Query().Get("title"))
|
||||
default:
|
||||
writeErr(w, apierror.NotFound("art"))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
if r.Context().Err() == nil {
|
||||
writeErr(w, apierror.NotFound("art"))
|
||||
}
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", http.DetectContentType(body))
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400")
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/catalogue"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz"
|
||||
)
|
||||
|
||||
const (
|
||||
searchArtistMBID = "a74b1b7f-71a5-4011-9441-d0b5e4122711"
|
||||
searchGroupMBID = "b1392450-e666-3926-a536-22c65f834433"
|
||||
searchRecMBID = "c1a0e1b2-0000-4000-8000-000000000001"
|
||||
)
|
||||
|
||||
// fakeMusicBrainz answers the three searches with one Radiohead result each,
|
||||
// or 503 when down is set.
|
||||
func fakeMusicBrainz(t *testing.T, down bool) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if down {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
credit := `[{"name": "Radiohead", "artist": {"id": "` + searchArtistMBID + `"}}]`
|
||||
group := `{"id": "` + searchGroupMBID + `", "title": "OK Computer", "primary-type": "Album",
|
||||
"first-release-date": "1997-05-21", "artist-credit": ` + credit + `}`
|
||||
switch r.URL.Path {
|
||||
case "/artist":
|
||||
_, _ = w.Write([]byte(`{"artists": [{"id": "` + searchArtistMBID + `", "name": "Radiohead", "type": "Group", "country": "GB"}]}`))
|
||||
case "/release-group":
|
||||
_, _ = w.Write([]byte(`{"release-groups": [` + group + `]}`))
|
||||
case "/recording":
|
||||
_, _ = w.Write([]byte(`{"recordings": [{"id": "` + searchRecMBID + `", "title": "Karma Police",
|
||||
"artist-credit": ` + credit + `,
|
||||
"releases": [{"id": "r1", "status": "Official", "release-group": ` + group + `}]}]}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func catalogueHandlers(t *testing.T, down bool) *handlers {
|
||||
t.Helper()
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
mb := &musicbrainz.Client{BaseURL: fakeMusicBrainz(t, down).URL, Pace: &musicbrainz.Pacer{}, Retries: -1}
|
||||
h.catalogue = catalogue.New(pool, mb, h.logger)
|
||||
return h
|
||||
}
|
||||
|
||||
func doCatalogueSearch(t *testing.T, h *handlers, q, kind string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/catalogue/search?"+url.Values{"q": {q}, "kind": {kind}}.Encode(), nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.handleCatalogueSearch(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func decodeResults(t *testing.T, w *httptest.ResponseRecorder) []catalogueSearchResult {
|
||||
t.Helper()
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var out []catalogueSearchResult
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func errorCode(t *testing.T, w *httptest.ResponseRecorder) string {
|
||||
t.Helper()
|
||||
var resp struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
return resp.Error.Code
|
||||
}
|
||||
|
||||
func TestCatalogueSearch_RefusesABadKindOrNoQuery(t *testing.T) {
|
||||
h := catalogueHandlers(t, false)
|
||||
if w := doCatalogueSearch(t, h, "x", "playlist"); w.Code != http.StatusBadRequest || errorCode(t, w) != "bad_kind" {
|
||||
t.Errorf("bad kind: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w := doCatalogueSearch(t, h, " ", "artist"); w.Code != http.StatusBadRequest || errorCode(t, w) != "missing_query" {
|
||||
t.Errorf("no query: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogueSearch_EachKindAsksMusicBrainz(t *testing.T) {
|
||||
h := catalogueHandlers(t, false)
|
||||
|
||||
artists := decodeResults(t, doCatalogueSearch(t, h, "radiohead", "artist"))
|
||||
if len(artists) != 1 || artists[0].MBID != searchArtistMBID || artists[0].SecondaryText != "Group · GB" {
|
||||
t.Fatalf("artists = %+v", artists)
|
||||
}
|
||||
if artists[0].ImageURL != "/api/catalogue/art/artist/"+searchArtistMBID+"?name=Radiohead" {
|
||||
t.Errorf("artist art = %q: it must be Minstrel's own endpoint", artists[0].ImageURL)
|
||||
}
|
||||
|
||||
albums := decodeResults(t, doCatalogueSearch(t, h, "ok computer", "album"))
|
||||
if len(albums) != 1 || albums[0].MBID != searchGroupMBID || albums[0].ArtistMBID != searchArtistMBID ||
|
||||
albums[0].SecondaryText != "Radiohead · 1997 · Album" {
|
||||
t.Fatalf("albums = %+v", albums)
|
||||
}
|
||||
|
||||
tracks := decodeResults(t, doCatalogueSearch(t, h, "karma police", "track"))
|
||||
if len(tracks) != 1 || tracks[0].AlbumMBID != searchGroupMBID || tracks[0].ArtistMBID != searchArtistMBID ||
|
||||
tracks[0].SecondaryText != "OK Computer · Radiohead" {
|
||||
t.Fatalf("tracks = %+v", tracks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogueSearch_MarksWhatIsHeldAndWhatIsRequested(t *testing.T) {
|
||||
h := catalogueHandlers(t, false)
|
||||
ctx := context.Background()
|
||||
q := dbq.New(h.pool)
|
||||
|
||||
artistMBID := searchArtistMBID
|
||||
artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: dbtest.TestUserPrefix + "Radiohead", SortName: "Radiohead", Mbid: &artistMBID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The album is held under a release id; its release group is what matches.
|
||||
if _, err := h.pool.Exec(ctx,
|
||||
`INSERT INTO albums (title, sort_title, artist_id, mbid, release_group_mbid) VALUES ('OK Computer', 'OK Computer', $1, 'some-release-id', $2)`,
|
||||
artist.ID, searchGroupMBID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := decodeResults(t, doCatalogueSearch(t, h, "radiohead", "artist")); !got[0].InLibrary {
|
||||
t.Error("the artist is held")
|
||||
}
|
||||
if got := decodeResults(t, doCatalogueSearch(t, h, "ok computer", "album")); !got[0].InLibrary {
|
||||
t.Error("the album is held, matched by release group")
|
||||
}
|
||||
|
||||
user := seedUser(t, h.pool, "requester", "pw", false)
|
||||
track := searchRecMBID
|
||||
if _, err := q.CreateRequest(ctx, dbq.CreateRequestParams{
|
||||
UserID: user.ID, Kind: dbq.RequestKindTrack, ArtistMbid: searchArtistMBID,
|
||||
TrackMbid: &track, ArtistName: "Radiohead",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := decodeResults(t, doCatalogueSearch(t, h, "karma police", "track"))
|
||||
if got[0].InLibrary || !got[0].Requested {
|
||||
t.Errorf("track = %+v, want requested and not held", got[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogueSearch_UnreachableMusicBrainzIs503(t *testing.T) {
|
||||
h := catalogueHandlers(t, true)
|
||||
w := doCatalogueSearch(t, h, "radiohead", "artist")
|
||||
if w.Code != http.StatusServiceUnavailable || errorCode(t, w) != "musicbrainz_unreachable" {
|
||||
t.Fatalf("status %d, body %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// artSource is an artist-art source with one image.
|
||||
type artSource struct{ apiTestAlbumProvider }
|
||||
|
||||
func (artSource) FetchArtistArt(_ context.Context, _ coverart.ArtistRef) ([]byte, []byte, error) {
|
||||
return []byte("\x89PNG\r\n\x1a\nrest"), nil, nil
|
||||
}
|
||||
|
||||
type fakeArtSources struct{ artists []coverart.ArtistArtProvider }
|
||||
|
||||
func (s fakeArtSources) EnabledArtistProviders() []coverart.ArtistArtProvider { return s.artists }
|
||||
func (fakeArtSources) EnabledAlbumProviders() []coverart.AlbumCoverProvider { return nil }
|
||||
|
||||
func TestCatalogueArt_ServesTheImageOrAPlaceholder404(t *testing.T) {
|
||||
h := &handlers{catalogueArt: catalogue.NewArt(t.TempDir(), fakeArtSources{artists: []coverart.ArtistArtProvider{&artSource{}}})}
|
||||
r := chi.NewRouter()
|
||||
r.Get("/api/catalogue/art/{kind}/{mbid}", h.handleCatalogueArt)
|
||||
|
||||
get := func(path string) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
return w
|
||||
}
|
||||
if w := get("/api/catalogue/art/artist/" + searchArtistMBID + "?name=Radiohead"); w.Code != http.StatusOK || w.Header().Get("Content-Type") != "image/png" {
|
||||
t.Errorf("artist: %d %q", w.Code, w.Header().Get("Content-Type"))
|
||||
}
|
||||
// No album source is enabled: a 404, which the page shows as its
|
||||
// placeholder.
|
||||
if w := get("/api/catalogue/art/release-group/" + searchGroupMBID); w.Code != http.StatusNotFound {
|
||||
t.Errorf("release group with no source: %d", w.Code)
|
||||
}
|
||||
for _, bad := range []string{"/api/catalogue/art/artist/not-an-id", "/api/catalogue/art/label/" + searchArtistMBID} {
|
||||
if w := get(bad); w.Code != http.StatusNotFound {
|
||||
t.Errorf("%s: %d", bad, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuggestionArt_PointsAtMinstrelsOwnEndpoint(t *testing.T) {
|
||||
views := []suggestionView{{MBID: searchArtistMBID, Name: "Sigur Rós"}, {Name: "No MBID"}}
|
||||
resolveSuggestionArt(views)
|
||||
if views[0].ImageURL != "/api/catalogue/art/artist/"+searchArtistMBID+"?name=Sigur+R%C3%B3s" {
|
||||
t.Errorf("image_url = %q", views[0].ImageURL)
|
||||
}
|
||||
if views[1].ImageURL != "" {
|
||||
t.Errorf("no MBID, no image: %q", views[1].ImageURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchCache_ReusesAnAnswerButNotTheFlags(t *testing.T) {
|
||||
c := newSearchCache()
|
||||
now := time.Now()
|
||||
c.now = func() time.Time { return now }
|
||||
asks := 0
|
||||
ask := func(context.Context, string, string) ([]catalogueSearchResult, error) {
|
||||
asks++
|
||||
return []catalogueSearchResult{{MBID: "m"}}, nil
|
||||
}
|
||||
first, _ := c.get(context.Background(), "artist", "Radiohead", ask)
|
||||
first[0].InLibrary = true // the handler sets flags on what it is given
|
||||
again, _ := c.get(context.Background(), "artist", "radiohead", ask)
|
||||
if asks != 1 {
|
||||
t.Errorf("asks = %d: the same words in another case are the same search", asks)
|
||||
}
|
||||
if again[0].InLibrary {
|
||||
t.Error("a flag set on one answer leaked into the cache")
|
||||
}
|
||||
if _, _ = c.get(context.Background(), "album", "radiohead", ask); asks != 2 {
|
||||
t.Error("another kind is another search")
|
||||
}
|
||||
now = now.Add(catalogueSearchTTL + time.Second)
|
||||
if _, _ = c.get(context.Background(), "artist", "radiohead", ask); asks != 3 {
|
||||
t.Error("an old answer is asked again")
|
||||
}
|
||||
var none *searchCache
|
||||
if _, _ = none.get(context.Background(), "artist", "x", ask); asks != 4 {
|
||||
t.Error("a nil cache asks every time")
|
||||
}
|
||||
}
|
||||
@@ -194,3 +194,11 @@ func nonNilStrings(in []string) []string {
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
// deref is a nullable column's text, or "".
|
||||
func deref(s *string) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return *s
|
||||
}
|
||||
|
||||
@@ -280,13 +280,12 @@ func (h *handlers) handleAdminDebugModeToggle(w http.ResponseWriter, r *http.Req
|
||||
h.logger.Info("admin: debug mode toggled",
|
||||
"target_user", uuidToString(targetID), "enabled", req.Enabled)
|
||||
writeJSON(w, http.StatusOK, adminUserView{
|
||||
ID: uuidToString(updated.ID),
|
||||
Username: updated.Username,
|
||||
DisplayName: updated.DisplayName,
|
||||
IsAdmin: updated.IsAdmin,
|
||||
AutoApproveRequests: updated.AutoApproveRequests,
|
||||
DebugModeEnabled: updated.DebugModeEnabled,
|
||||
CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339),
|
||||
ID: uuidToString(updated.ID),
|
||||
Username: updated.Username,
|
||||
DisplayName: updated.DisplayName,
|
||||
IsAdmin: updated.IsAdmin,
|
||||
DebugModeEnabled: updated.DebugModeEnabled,
|
||||
CreatedAt: updated.CreatedAt.Time.UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
@@ -102,23 +101,3 @@ func (h *handlers) publishSystemRebuilt(userID pgtype.UUID) {
|
||||
Data: map[string]any{},
|
||||
})
|
||||
}
|
||||
|
||||
// publishRequestStatusChanged broadcasts a request status flip to
|
||||
// the request's original requester so their /requests page reflects the
|
||||
// new state without manual refresh. Admin actors (approve / reject) still
|
||||
// route to the requester's user_id, not the admin's — the original user
|
||||
// is who needs to see the update.
|
||||
func (h *handlers) publishRequestStatusChanged(row dbq.Request) {
|
||||
if h.eventbus == nil {
|
||||
return
|
||||
}
|
||||
h.eventbus.Publish(eventbus.Event{
|
||||
Kind: "request.status_changed",
|
||||
UserID: uuidToString(row.UserID),
|
||||
Data: map[string]any{
|
||||
"request_id": uuidToString(row.ID),
|
||||
"status": string(row.Status),
|
||||
"kind": string(row.Kind),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Live event stream — Server-Sent Events at GET /api/events/stream.
|
||||
//
|
||||
// The web app and the Android app subscribe to be notified of state changes
|
||||
// elsewhere in the system (likes, request status flips, quarantine
|
||||
// elsewhere in the system (likes, quarantine
|
||||
// resolutions, scan progress, playlist mutations) so static screens
|
||||
// can invalidate cached data without explicit user action.
|
||||
//
|
||||
|
||||
@@ -468,7 +468,7 @@ func TestRoutesRegisteredInMount(t *testing.T) {
|
||||
r := chi.NewRouter()
|
||||
w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
30*time.Minute, 0.5, 30000)
|
||||
Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.requests, h.quarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil, nil, nil, backup.NewService(h.pool, h.logger, "test"), nil)
|
||||
Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.quarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil, nil, backup.NewService(h.pool, h.logger, "test"), nil)
|
||||
|
||||
paths := []string{
|
||||
"/api/artists",
|
||||
@@ -486,7 +486,6 @@ func TestRoutesRegisteredInMount(t *testing.T) {
|
||||
// admin group, so reaching the auth check is what proves they are
|
||||
// wired.
|
||||
"/api/admin/library/missing",
|
||||
"/api/admin/library/reacquisition",
|
||||
"/api/admin/library/fingerprints",
|
||||
"/api/admin/library/fingerprint-settings",
|
||||
"/api/admin/library/duplicates",
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/notifications"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/requests"
|
||||
)
|
||||
|
||||
// Helpers for the handlers that produce notifications. Every call is
|
||||
@@ -23,25 +22,6 @@ func userLabel(u dbq.User) string {
|
||||
return u.Username
|
||||
}
|
||||
|
||||
func requestPayload(row dbq.Request) notifications.Payload {
|
||||
return notifications.Payload{
|
||||
RequestID: uuidToString(row.ID),
|
||||
RequestKind: string(row.Kind),
|
||||
Name: requests.DisplayName(row),
|
||||
}
|
||||
}
|
||||
|
||||
// notifyRequestDecided tells the requester an admin approved or declined
|
||||
// their request. An admin deciding their own request needs no notice.
|
||||
func (h *handlers) notifyRequestDecided(ctx context.Context, kind notifications.Kind, admin dbq.User, row dbq.Request, reason string) {
|
||||
if row.UserID == admin.ID {
|
||||
return
|
||||
}
|
||||
p := requestPayload(row)
|
||||
p.Reason = reason
|
||||
h.notifier.NotifyLogged(ctx, kind, notifications.ToUser(row.UserID), p.Map())
|
||||
}
|
||||
|
||||
// quarantineReasonLabel is a flag reason as the flag popover words it, in
|
||||
// lower case to sit inside a sentence ("flagged X: bad rip").
|
||||
func quarantineReasonLabel(reason string) string {
|
||||
|
||||
@@ -53,99 +53,6 @@ func wantInbox(t *testing.T, who string, got []inboxItem, kinds ...notifications
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotify_NewRequestReachesOtherAdminsOnce(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "np-alice", "pw", false)
|
||||
admin := seedUser(t, pool, "np-admin", "pw", true)
|
||||
selfAdmin := seedUser(t, pool, "np-self", "pw", true)
|
||||
|
||||
rv := createArtistRequest(t, h, alice, "np-mbid-1", "Pending Band")
|
||||
// The same request again dedups into the first and is not announced twice.
|
||||
createArtistRequest(t, h, alice, "np-mbid-1", "Pending Band")
|
||||
|
||||
got := inboxOf(t, pool, admin)
|
||||
wantInbox(t, "admin", got, notifications.KindRequestPending)
|
||||
if got[0].Payload.RequestID != uuidToString(rv.ID) || got[0].Payload.Name != "Pending Band" || got[0].Payload.Actor != alice.Username {
|
||||
t.Errorf("pending payload = %+v", got[0].Payload)
|
||||
}
|
||||
wantInbox(t, "requester", inboxOf(t, pool, alice))
|
||||
|
||||
// An admin's own request goes to the other admins, never back to them.
|
||||
createArtistRequest(t, h, selfAdmin, "np-mbid-2", "Own Band")
|
||||
wantInbox(t, "self-admin", inboxOf(t, pool, selfAdmin), notifications.KindRequestPending)
|
||||
if n := len(inboxOf(t, pool, admin)); n != 2 {
|
||||
t.Errorf("admin inbox = %d, want 2 (alice's and the self-admin's)", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotify_AutoApprovedRequestWaitsOnNobody(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, h.pool, "np-auto", "pw", false)
|
||||
admin := seedUser(t, h.pool, "np-auto-admin", "pw", true)
|
||||
if _, err := h.pool.Exec(context.Background(),
|
||||
"UPDATE users SET auto_approve_requests = true WHERE id = $1", alice.ID); err != nil {
|
||||
t.Fatalf("set auto_approve: %v", err)
|
||||
}
|
||||
alice, err := dbq.New(h.pool).GetUserByID(context.Background(), alice.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("reload user: %v", err)
|
||||
}
|
||||
|
||||
rv := createArtistRequest(t, h, alice, "np-auto-mbid", "Auto Band")
|
||||
if rv.Status != "approved" {
|
||||
t.Fatalf("status = %q, want approved — the stub should accept the add", rv.Status)
|
||||
}
|
||||
wantInbox(t, "admin", inboxOf(t, h.pool, admin))
|
||||
wantInbox(t, "requester", inboxOf(t, h.pool, alice))
|
||||
}
|
||||
|
||||
func TestNotify_DecisionsReachTheRequester(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, h.pool, "np-dec-alice", "pw", false)
|
||||
admin := seedUser(t, h.pool, "np-dec-admin", "pw", true)
|
||||
|
||||
approved := seedPendingArtistRequest(t, h, alice, "np-dec-1", "Yes Band")
|
||||
rejected := seedPendingArtistRequest(t, h, alice, "np-dec-2", "No Band")
|
||||
own := seedPendingArtistRequest(t, h, admin, "np-dec-3", "Own Band")
|
||||
|
||||
for _, c := range []struct {
|
||||
id string
|
||||
verb string
|
||||
body []byte
|
||||
}{
|
||||
{uuidToString(approved.ID), "approve", nil},
|
||||
{uuidToString(rejected.ID), "reject", []byte(`{"notes":"Only a live bootleg exists"}`)},
|
||||
{uuidToString(own.ID), "approve", nil},
|
||||
} {
|
||||
w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+c.id+"/"+c.verb, c.body, admin)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("%s %s: status = %d; body = %s", c.verb, c.id, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
got := inboxOf(t, h.pool, alice)
|
||||
wantInbox(t, "requester", got, notifications.KindRequestRejected, notifications.KindRequestApproved)
|
||||
if got[0].Payload.Name != "No Band" || got[0].Payload.Reason != "Only a live bootleg exists" {
|
||||
t.Errorf("rejected payload = %+v", got[0].Payload)
|
||||
}
|
||||
if got[1].Payload.Name != "Yes Band" || got[1].Payload.Reason != "" {
|
||||
t.Errorf("approved payload = %+v", got[1].Payload)
|
||||
}
|
||||
// The admin decided their own request: no notice. alice's two pending
|
||||
// notices are all the admin holds.
|
||||
for _, it := range inboxOf(t, h.pool, admin) {
|
||||
if it.Kind != string(notifications.KindRequestPending) {
|
||||
t.Errorf("admin inbox holds %q, want only request_pending", it.Kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotify_FlagReachesAdminsButNotTheFlagger(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
|
||||
@@ -1,264 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/notifications"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/requests"
|
||||
)
|
||||
|
||||
// requestView is the JSON shape returned by all /api/requests handlers.
|
||||
// Field names follow the lowercase snake_case convention for /api/* responses.
|
||||
type requestView struct {
|
||||
ID pgtype.UUID `json:"id"`
|
||||
UserID pgtype.UUID `json:"user_id"`
|
||||
// Username names the requester. Only the admin list fills it; a user's
|
||||
// own /requests page has no need to name them back to themselves.
|
||||
Username string `json:"username,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Kind string `json:"kind"`
|
||||
ArtistMBID string `json:"artist_mbid"`
|
||||
AlbumMBID *string `json:"album_mbid,omitempty"`
|
||||
TrackMBID *string `json:"track_mbid,omitempty"`
|
||||
ArtistName string `json:"artist_name"`
|
||||
AlbumTitle *string `json:"album_title,omitempty"`
|
||||
TrackTitle *string `json:"track_title,omitempty"`
|
||||
DecidedAt pgtype.Timestamptz `json:"decided_at,omitempty"`
|
||||
DecidedBy pgtype.UUID `json:"decided_by,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
CompletedAt pgtype.Timestamptz `json:"completed_at,omitempty"`
|
||||
MatchedTrackID pgtype.UUID `json:"matched_track_id,omitempty"`
|
||||
MatchedAlbumID pgtype.UUID `json:"matched_album_id,omitempty"`
|
||||
MatchedArtistID pgtype.UUID `json:"matched_artist_id,omitempty"`
|
||||
RequestedAt pgtype.Timestamptz `json:"requested_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
// Progress counters, computed at response time from the matched
|
||||
// entity's children. 0 when nothing has been ingested yet (or when
|
||||
// the request has no matched entity yet). For artist requests both
|
||||
// counters fill; for album/track requests only ImportedTrackCount.
|
||||
ImportedAlbumCount int `json:"imported_album_count"`
|
||||
ImportedTrackCount int `json:"imported_track_count"`
|
||||
}
|
||||
|
||||
func requestViewFrom(row dbq.Request) requestView {
|
||||
return requestView{
|
||||
ID: row.ID,
|
||||
UserID: row.UserID,
|
||||
Status: string(row.Status),
|
||||
Kind: string(row.Kind),
|
||||
ArtistMBID: row.ArtistMbid,
|
||||
AlbumMBID: row.AlbumMbid,
|
||||
TrackMBID: row.TrackMbid,
|
||||
ArtistName: row.ArtistName,
|
||||
AlbumTitle: row.AlbumTitle,
|
||||
TrackTitle: row.TrackTitle,
|
||||
DecidedAt: row.DecidedAt,
|
||||
DecidedBy: row.DecidedBy,
|
||||
Notes: row.Notes,
|
||||
CompletedAt: row.CompletedAt,
|
||||
MatchedTrackID: row.MatchedTrackID,
|
||||
MatchedAlbumID: row.MatchedAlbumID,
|
||||
MatchedArtistID: row.MatchedArtistID,
|
||||
RequestedAt: row.RequestedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// fillProgress fills ImportedAlbumCount + ImportedTrackCount on a view by
|
||||
// querying the count of children for the request's matched entity.
|
||||
//
|
||||
// kind=artist → counts all albums + tracks under the matched artist.
|
||||
// kind=album → counts tracks under the matched album.
|
||||
// kind=track → ImportedTrackCount = 1 once matched_track_id is set.
|
||||
//
|
||||
// N+1 against the request list: acceptable at admin scale (dozens of
|
||||
// in-flight requests at most). Errors are swallowed — progress is a
|
||||
// reporting nicety, not a correctness gate.
|
||||
func fillProgress(ctx context.Context, q *dbq.Queries, row dbq.Request, view *requestView) {
|
||||
switch row.Kind {
|
||||
case dbq.RequestKindArtist:
|
||||
if !row.MatchedArtistID.Valid {
|
||||
return
|
||||
}
|
||||
if n, err := q.CountAlbumsByArtist(ctx, row.MatchedArtistID); err == nil {
|
||||
view.ImportedAlbumCount = int(n)
|
||||
}
|
||||
if n, err := q.CountTracksByArtist(ctx, row.MatchedArtistID); err == nil {
|
||||
view.ImportedTrackCount = int(n)
|
||||
}
|
||||
case dbq.RequestKindAlbum:
|
||||
if !row.MatchedAlbumID.Valid {
|
||||
return
|
||||
}
|
||||
view.ImportedAlbumCount = 1
|
||||
if n, err := q.CountTracksByAlbum(ctx, row.MatchedAlbumID); err == nil {
|
||||
view.ImportedTrackCount = int(n)
|
||||
}
|
||||
case dbq.RequestKindTrack:
|
||||
if row.MatchedTrackID.Valid {
|
||||
view.ImportedTrackCount = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// createRequestBody is the decoded JSON for POST /api/requests. album_mbid
|
||||
// is the album's MusicBrainz release group, as catalogue search returns it.
|
||||
type createRequestBody struct {
|
||||
Kind string `json:"kind"`
|
||||
ArtistMBID string `json:"artist_mbid"`
|
||||
AlbumMBID string `json:"album_mbid"`
|
||||
TrackMBID string `json:"track_mbid"`
|
||||
ArtistName string `json:"artist_name"`
|
||||
AlbumTitle string `json:"album_title"`
|
||||
TrackTitle string `json:"track_title"`
|
||||
}
|
||||
|
||||
// handleCreateRequest implements POST /api/requests.
|
||||
func (h *handlers) handleCreateRequest(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var body createRequestBody
|
||||
if !decodeBody(w, r, &body) {
|
||||
return
|
||||
}
|
||||
|
||||
row, created, err := h.requests.CreateTracked(r.Context(), user.ID, requests.CreateParams{
|
||||
Kind: body.Kind,
|
||||
ArtistMBID: body.ArtistMBID,
|
||||
AlbumMBID: body.AlbumMBID,
|
||||
TrackMBID: body.TrackMBID,
|
||||
ArtistName: body.ArtistName,
|
||||
AlbumTitle: body.AlbumTitle,
|
||||
TrackTitle: body.TrackTitle,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, requests.ErrInvalidKindFields) {
|
||||
writeErr(w, apierror.BadRequest("mbid_required", err.Error()))
|
||||
return
|
||||
}
|
||||
h.logger.Error("api: create request", "err", err)
|
||||
writeErr(w, apierror.InternalMsg("create failed", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Auto-approve: when an admin has set the user's
|
||||
// auto_approve_requests flag, the new request goes straight onto the
|
||||
// wanted list as if approved. A failure leaves it pending for an admin,
|
||||
// the same as a manual approval hitting the same error. The approver is
|
||||
// the user themselves, acting under the privilege the admin granted; the
|
||||
// grant is in audit_log (ActionAutoApproveToggle).
|
||||
if user.AutoApproveRequests {
|
||||
approved, aerr := h.requests.Approve(r.Context(), row.ID, user.ID, pgtype.UUID{})
|
||||
if aerr == nil {
|
||||
row = approved
|
||||
} else {
|
||||
h.logger.Warn("api: auto-approve failed; request stays pending",
|
||||
"user_id", uuidToString(user.ID),
|
||||
"request_id", uuidToString(row.ID),
|
||||
"err", aerr)
|
||||
}
|
||||
}
|
||||
|
||||
// A new request still pending after any auto-approval waits on an admin.
|
||||
// One that deduped into a request already in flight was announced when it
|
||||
// was first made, and the requester, if they are an admin themselves,
|
||||
// needs no notice of their own request.
|
||||
if created && row.Status == dbq.RequestStatusPending {
|
||||
p := requestPayload(row)
|
||||
p.Actor = userLabel(user)
|
||||
h.notifier.NotifyLogged(r.Context(), notifications.KindRequestPending, notifications.ToAdmins(user.ID), p.Map())
|
||||
}
|
||||
|
||||
h.publishRequestStatusChanged(row)
|
||||
writeJSON(w, http.StatusCreated, requestViewFrom(row))
|
||||
}
|
||||
|
||||
// handleListRequests implements GET /api/requests — returns caller's own
|
||||
// requests.
|
||||
func (h *handlers) handleListRequests(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := h.requests.ListForUser(r.Context(), user.ID, 100)
|
||||
if err != nil {
|
||||
h.logger.Error("api: list requests", "err", err)
|
||||
writeErr(w, apierror.InternalMsg("list failed", err))
|
||||
return
|
||||
}
|
||||
|
||||
q := dbq.New(h.pool)
|
||||
out := make([]requestView, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
v := requestViewFrom(row)
|
||||
fillProgress(r.Context(), q, row, &v)
|
||||
out = append(out, v)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// handleGetRequest implements GET /api/requests/:id.
|
||||
// The caller must own the request, or be an admin.
|
||||
func (h *handlers) handleGetRequest(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
row, apiErr := resolveByID(r, "id", dbq.New(h.pool).GetRequestByID, "request")
|
||||
if apiErr != nil {
|
||||
writeErr(w, apiErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Allow if caller owns the request or is an admin.
|
||||
if row.UserID != user.ID && !user.IsAdmin {
|
||||
writeErr(w, apierror.NotFound("request"))
|
||||
return
|
||||
}
|
||||
|
||||
v := requestViewFrom(row)
|
||||
fillProgress(r.Context(), dbq.New(h.pool), row, &v)
|
||||
writeJSON(w, http.StatusOK, v)
|
||||
}
|
||||
|
||||
// handleCancelRequest implements DELETE /api/requests/:id.
|
||||
// Cancels the caller's own pending request.
|
||||
func (h *handlers) handleCancelRequest(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, ok := requireURLUUID(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
row, err := h.requests.Cancel(r.Context(), id, user.ID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, requests.ErrNotPending):
|
||||
writeErr(w, apierror.Conflict("request_not_pending", "request is not pending"))
|
||||
case errors.Is(err, requests.ErrNotFound):
|
||||
writeErr(w, apierror.NotFound("request"))
|
||||
default:
|
||||
h.logger.Error("api: cancel request", "err", err)
|
||||
writeErr(w, apierror.InternalMsg("cancel failed", err))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
h.publishRequestStatusChanged(row)
|
||||
writeJSON(w, http.StatusOK, requestViewFrom(row))
|
||||
}
|
||||
@@ -1,396 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// newRequestsRouter builds a test chi router wiring the /api/requests handlers
|
||||
// with chi URL params but without RequireUser middleware. Tests inject a user
|
||||
// into the context manually.
|
||||
func newRequestsRouter(h *handlers) chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Post("/api/requests", h.handleCreateRequest)
|
||||
r.Get("/api/requests", h.handleListRequests)
|
||||
r.Get("/api/requests/{id}", h.handleGetRequest)
|
||||
r.Delete("/api/requests/{id}", h.handleCancelRequest)
|
||||
return r
|
||||
}
|
||||
|
||||
// withUser injects a user into the request context the same way RequireUser
|
||||
// does.
|
||||
func withUser(req *http.Request, user dbq.User) *http.Request {
|
||||
return req.WithContext(context.WithValue(req.Context(), userCtxKeyForTest(), user))
|
||||
}
|
||||
|
||||
// doCreateRequest fires POST /api/requests with the given JSON body as the
|
||||
// given user.
|
||||
func doCreateRequest(h *handlers, user dbq.User, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/requests", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
newRequestsRouter(h).ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// doListRequests fires GET /api/requests as the given user.
|
||||
func doListRequests(h *handlers, user dbq.User) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/requests", nil)
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
newRequestsRouter(h).ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// doGetRequest fires GET /api/requests/:id as the given user.
|
||||
func doGetRequest(h *handlers, user dbq.User, id pgtype.UUID) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/requests/"+uuidToString(id), nil)
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
newRequestsRouter(h).ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// doCancelRequest fires DELETE /api/requests/:id as the given user.
|
||||
func doCancelRequest(h *handlers, user dbq.User, id pgtype.UUID) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/requests/"+uuidToString(id), nil)
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
newRequestsRouter(h).ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// createArtistRequest is a convenience wrapper that seeds a valid artist
|
||||
// request via the handler and returns the parsed response.
|
||||
func createArtistRequest(t *testing.T, h *handlers, user dbq.User, artistMBID, artistName string) requestView {
|
||||
t.Helper()
|
||||
body := fmt.Sprintf(`{"kind":"artist","artist_mbid":%q,"artist_name":%q}`, artistMBID, artistName)
|
||||
w := doCreateRequest(h, user, body)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("createArtistRequest: status = %d, want 201; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var rv requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &rv); err != nil {
|
||||
t.Fatalf("createArtistRequest: decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
// TestHandleCreateRequest_AutoApprove_GoesStraightOnTheWantedList verifies
|
||||
// that a user with auto_approve_requests=true gets their request approved on
|
||||
// creation: an artist request follows the artist at once.
|
||||
func TestHandleCreateRequest_AutoApprove_GoesStraightOnTheWantedList(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "alice", "pw", false)
|
||||
if _, err := pool.Exec(context.Background(),
|
||||
"UPDATE users SET auto_approve_requests = true WHERE id = $1", alice.ID); err != nil {
|
||||
t.Fatalf("set auto_approve: %v", err)
|
||||
}
|
||||
// Re-fetch so the User row carried into the request context has the flag.
|
||||
refreshed, err := dbq.New(pool).GetUserByID(context.Background(), alice.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("reload user: %v", err)
|
||||
}
|
||||
|
||||
body := `{"kind":"artist","artist_mbid":"auto-mbid-1","artist_name":"Autoband"}`
|
||||
w := doCreateRequest(h, refreshed, body)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, want 201; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var rv requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &rv); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if rv.Status != "approved" {
|
||||
t.Errorf("status = %q, want approved", rv.Status)
|
||||
}
|
||||
if _, err := dbq.New(pool).GetFollow(context.Background(), "auto-mbid-1"); err != nil {
|
||||
t.Errorf("the artist should be followed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCreateRequest_Artist_HappyPath verifies a valid artist request
|
||||
// returns 201 with kind=artist and status=pending.
|
||||
func TestHandleCreateRequest_Artist_HappyPath(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "alice", "pw", false)
|
||||
body := `{"kind":"artist","artist_mbid":"artist-mbid-1","artist_name":"The Beatles"}`
|
||||
w := doCreateRequest(h, alice, body)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, want 201; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var rv requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &rv); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if string(rv.Kind) != "artist" {
|
||||
t.Errorf("kind = %q, want artist", rv.Kind)
|
||||
}
|
||||
if rv.Status != "pending" {
|
||||
t.Errorf("status = %q, want pending", rv.Status)
|
||||
}
|
||||
if rv.ArtistMBID != "artist-mbid-1" {
|
||||
t.Errorf("artist_mbid = %q", rv.ArtistMBID)
|
||||
}
|
||||
if rv.ArtistName != "The Beatles" {
|
||||
t.Errorf("artist_name = %q", rv.ArtistName)
|
||||
}
|
||||
if !rv.ID.Valid {
|
||||
t.Error("id not set")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCreateRequest_AlbumWithoutAlbumMBID_400 verifies that sending
|
||||
// kind=album without album_mbid returns 400 with mbid_required.
|
||||
func TestHandleCreateRequest_AlbumWithoutAlbumMBID_400(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "alice", "pw", false)
|
||||
// Missing album_mbid and album_title.
|
||||
body := `{"kind":"album","artist_mbid":"artist-mbid-1","artist_name":"The Beatles"}`
|
||||
w := doCreateRequest(h, alice, body)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if resp.Error.Code != "mbid_required" {
|
||||
t.Errorf("error.code = %q, want mbid_required", resp.Error.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCreateRequest_TrackWithoutTrackFields_400 verifies that kind=track
|
||||
// with missing track_mbid/track_title returns 400 with mbid_required.
|
||||
func TestHandleCreateRequest_TrackWithoutTrackFields_400(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "alice", "pw", false)
|
||||
// Provides album fields but misses track_mbid and track_title.
|
||||
body := `{"kind":"track","artist_mbid":"artist-mbid-1","artist_name":"Beatles","album_mbid":"album-mbid-1","album_title":"Abbey Road"}`
|
||||
w := doCreateRequest(h, alice, body)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if resp.Error.Code != "mbid_required" {
|
||||
t.Errorf("error.code = %q, want mbid_required", resp.Error.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleListRequests_OnlyOwnRequests verifies alice sees only her own
|
||||
// requests, not bob's.
|
||||
func TestHandleListRequests_OnlyOwnRequests(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "alice", "pw", false)
|
||||
bob := seedUser(t, pool, "bob", "pw", false)
|
||||
|
||||
createArtistRequest(t, h, alice, "alice-mbid-1", "Alice Artist 1")
|
||||
createArtistRequest(t, h, alice, "alice-mbid-2", "Alice Artist 2")
|
||||
createArtistRequest(t, h, bob, "bob-mbid-1", "Bob Artist 1")
|
||||
|
||||
w := doListRequests(h, alice)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var results []requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if len(results) != 2 {
|
||||
t.Fatalf("len(results) = %d, want 2", len(results))
|
||||
}
|
||||
for _, rv := range results {
|
||||
if rv.UserID != alice.ID {
|
||||
t.Errorf("result belongs to wrong user: %v", rv.UserID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleGetRequest_OwnReturns200 verifies a caller can fetch their own
|
||||
// request.
|
||||
func TestHandleGetRequest_OwnReturns200(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "alice", "pw", false)
|
||||
rv := createArtistRequest(t, h, alice, "artist-mbid-get", "Get Artist")
|
||||
|
||||
w := doGetRequest(h, alice, rv.ID)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var got requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if got.ID != rv.ID {
|
||||
t.Errorf("id mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleGetRequest_OtherUserNotAdmin_404 verifies a non-admin caller
|
||||
// cannot see another user's request.
|
||||
func TestHandleGetRequest_OtherUserNotAdmin_404(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
bob := seedUser(t, pool, "bob", "pw", false)
|
||||
charlie := seedUser(t, pool, "charlie", "pw", false)
|
||||
|
||||
rv := createArtistRequest(t, h, bob, "bob-artist-mbid", "Bob's Artist")
|
||||
|
||||
// Charlie is not an admin, tries to fetch Bob's request.
|
||||
w := doGetRequest(h, charlie, rv.ID)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if resp.Error.Code != "request_not_found" {
|
||||
t.Errorf("error.code = %q, want request_not_found", resp.Error.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleGetRequest_OtherUserAsAdmin_200 verifies an admin can fetch any
|
||||
// user's request.
|
||||
func TestHandleGetRequest_OtherUserAsAdmin_200(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
bob := seedUser(t, pool, "bob", "pw", false)
|
||||
admin := seedUser(t, pool, "admin", "pw", true)
|
||||
|
||||
rv := createArtistRequest(t, h, bob, "bob-admin-mbid", "Bob's Artist For Admin")
|
||||
|
||||
// Admin fetches Bob's request — should succeed.
|
||||
w := doGetRequest(h, admin, rv.ID)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var got requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if got.ID != rv.ID {
|
||||
t.Errorf("id mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCancelRequest_PendingHappyPath verifies that cancelling a pending
|
||||
// request returns 200 with status=rejected.
|
||||
func TestHandleCancelRequest_PendingHappyPath(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "alice", "pw", false)
|
||||
rv := createArtistRequest(t, h, alice, "cancel-mbid-1", "Cancel Me")
|
||||
|
||||
w := doCancelRequest(h, alice, rv.ID)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var got requestView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if got.Status != "rejected" {
|
||||
t.Errorf("status = %q, want rejected", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCancelRequest_NonPending_409 verifies that cancelling an already
|
||||
// rejected request returns 409 with request_not_pending.
|
||||
func TestHandleCancelRequest_NonPending_409(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "alice", "pw", false)
|
||||
rv := createArtistRequest(t, h, alice, "cancel-mbid-2", "Cancel Twice")
|
||||
|
||||
// First cancel transitions to rejected.
|
||||
w1 := doCancelRequest(h, alice, rv.ID)
|
||||
if w1.Code != http.StatusOK {
|
||||
t.Fatalf("first cancel: status = %d, want 200; body = %s", w1.Code, w1.Body.String())
|
||||
}
|
||||
|
||||
// Second cancel on a now-rejected row → ErrNotPending → 409. The cancel SQL
|
||||
// checks user_id = $2 AND status = 'pending'; zero rows → ErrNotPending.
|
||||
// For this test we use dbq directly to reject via admin so Cancel returns
|
||||
// ErrNotPending rather than the ownership miss. We already did first cancel
|
||||
// so row is rejected.
|
||||
w2 := doCancelRequest(h, alice, rv.ID)
|
||||
if w2.Code != http.StatusConflict {
|
||||
t.Fatalf("second cancel: status = %d, want 409; body = %s", w2.Code, w2.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(w2.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w2.Body.String())
|
||||
}
|
||||
if resp.Error.Code != "request_not_pending" {
|
||||
t.Errorf("error.code = %q, want request_not_pending", resp.Error.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCancelRequest_WrongUser_409 verifies that attempting to cancel
|
||||
// another user's request returns 409 (not_pending from the ownership miss).
|
||||
func TestHandleCancelRequest_WrongUser_409(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
resetRequests(t, h)
|
||||
|
||||
alice := seedUser(t, pool, "alice-cancel-owner", "pw", false)
|
||||
bob := seedUser(t, pool, "bob-cancel-other", "pw", false)
|
||||
|
||||
rv := createArtistRequest(t, h, alice, "cancel-wrong-user-mbid", "Alice's Artist")
|
||||
|
||||
// Bob tries to cancel Alice's request: SQL WHERE user_id=bob AND
|
||||
// status=pending → 0 rows.
|
||||
w := doCancelRequest(h, bob, rv.ID)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want 409; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/recommendation"
|
||||
)
|
||||
|
||||
// suggestionView is the wire shape returned by GET /api/discover/suggestions.
|
||||
type suggestionView struct {
|
||||
MBID string `json:"mbid"`
|
||||
Name string `json:"name"`
|
||||
Score float64 `json:"score"`
|
||||
Attribution []seedContributionView `json:"attribution"`
|
||||
// MatchedTags are the candidate's tags that overlap the user's taste
|
||||
// profile, strongest first — the "matches: shoegaze, melancholic"
|
||||
// line. Omitted when empty, which is common: tag coverage for
|
||||
// out-of-library artists is permanently partial, and the card falls back
|
||||
// to the seed attribution.
|
||||
MatchedTags []string `json:"matched_tags,omitempty"`
|
||||
// ImageURL is Minstrel's catalogue art endpoint for the candidate
|
||||
// (out-of-library artists have no local art row). It
|
||||
// answers 404 when no enabled source has an image, and the client
|
||||
// falls back to a placeholder.
|
||||
ImageURL string `json:"image_url,omitempty"`
|
||||
}
|
||||
|
||||
type seedContributionView struct {
|
||||
ArtistID pgtype.UUID `json:"artist_id"`
|
||||
Name string `json:"name"`
|
||||
Contribution float64 `json:"contribution"`
|
||||
IsLiked bool `json:"is_liked"`
|
||||
PlayCount int64 `json:"play_count"`
|
||||
}
|
||||
|
||||
// handleListSuggestions implements GET /api/discover/suggestions.
|
||||
//
|
||||
// Query params:
|
||||
// - limit (default 12, capped at 50)
|
||||
// - half_life_days (default 30)
|
||||
//
|
||||
// Returns 200 with a JSON array (possibly empty). Read-only; no admin gate.
|
||||
func (h *handlers) handleListSuggestions(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit := 12
|
||||
if v := r.URL.Query().Get("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 {
|
||||
writeErr(w, apierror.BadRequest("bad_request", "invalid limit"))
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
halfLife := 30.0
|
||||
if v := r.URL.Query().Get("half_life_days"); v != "" {
|
||||
f, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil || f <= 0 {
|
||||
writeErr(w, apierror.BadRequest("bad_request", "invalid half_life_days"))
|
||||
return
|
||||
}
|
||||
halfLife = f
|
||||
}
|
||||
|
||||
// Read the tuned weight per request so an admin change takes effect on the
|
||||
// next refresh, no restart.
|
||||
tagWeight := h.recSettings.Discover().TagOverlapWeight
|
||||
suggestions, err := recommendation.SuggestArtists(
|
||||
r.Context(), h.pool, user.ID, halfLife, limit, tagWeight)
|
||||
if err != nil {
|
||||
h.logger.Error("api: list suggestions", "err", err)
|
||||
writeErr(w, apierror.InternalMsg("failed to load suggestions", err))
|
||||
return
|
||||
}
|
||||
|
||||
out := make([]suggestionView, 0, len(suggestions))
|
||||
for _, s := range suggestions {
|
||||
attr := make([]seedContributionView, 0, len(s.Attribution))
|
||||
for _, a := range s.Attribution {
|
||||
attr = append(attr, seedContributionView{
|
||||
ArtistID: a.ArtistID,
|
||||
Name: a.Name,
|
||||
Contribution: a.Contribution,
|
||||
IsLiked: a.IsLiked,
|
||||
PlayCount: a.PlayCount,
|
||||
})
|
||||
}
|
||||
out = append(out, suggestionView{
|
||||
MBID: s.MBID, Name: s.Name, Score: s.Score, Attribution: attr,
|
||||
MatchedTags: s.MatchedTags,
|
||||
})
|
||||
}
|
||||
resolveSuggestionArt(out)
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// maxSnoozeDays caps a client-supplied duration. The DEFAULT is not here: it's
|
||||
// a DB-backed knob on the admin tuning card, read per request via
|
||||
// recSettings.Discover().SnoozeDays.
|
||||
const maxSnoozeDays = 365.0
|
||||
|
||||
// snoozeRequest is the POST body. Both fields are optional in the JSON sense
|
||||
// (an absent body snoozes for the default), but Name is required in practice:
|
||||
// candidates are out-of-library, so the server has no artists row to resolve a
|
||||
// display name from and the un-snooze list would have nothing to show. The
|
||||
// client always has it — it just rendered the card.
|
||||
type snoozeRequest struct {
|
||||
Name string `json:"name"`
|
||||
Days float64 `json:"days"`
|
||||
}
|
||||
|
||||
// snoozeView is one row of GET /api/discover/snoozes.
|
||||
type snoozeView struct {
|
||||
MBID string `json:"mbid"`
|
||||
Name string `json:"name"`
|
||||
SnoozedUntil pgtype.Timestamptz `json:"snoozed_until"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
}
|
||||
|
||||
// handleSnoozeSuggestion implements
|
||||
// POST /api/discover/suggestions/{mbid}/snooze.
|
||||
//
|
||||
// Parks a candidate for `days` (default 90, capped at 365). Idempotent:
|
||||
// snoozing an already-snoozed candidate extends it rather than conflicting.
|
||||
//
|
||||
// This is NOT negative feedback. It records no verdict on the artist and is
|
||||
// never read by internal/taste — see 0049_suggestion_snoozes.up.sql for why.
|
||||
// Returns 204.
|
||||
func (h *handlers) handleSnoozeSuggestion(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
mbid := strings.TrimSpace(chi.URLParam(r, "mbid"))
|
||||
if mbid == "" {
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "missing mbid"))
|
||||
return
|
||||
}
|
||||
|
||||
// An empty body is a valid "snooze this for the default period", so EOF
|
||||
// is not an error here — decodeBody would reject it as a malformed body.
|
||||
var body snoozeRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil && !errors.Is(err, io.EOF) {
|
||||
writeErr(w, apierror.BadRequest("invalid_body", ""))
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(body.Name)
|
||||
if name == "" {
|
||||
writeErr(w, apierror.BadRequest("invalid_body", "name is required"))
|
||||
return
|
||||
}
|
||||
days := body.Days
|
||||
if days <= 0 {
|
||||
days = h.recSettings.Discover().SnoozeDays
|
||||
}
|
||||
if days > maxSnoozeDays {
|
||||
// Clamp rather than reject: a client asking for longer than we allow
|
||||
// still means "park this", and failing the write would leave the card
|
||||
// sitting there as if the tap did nothing.
|
||||
days = maxSnoozeDays
|
||||
}
|
||||
|
||||
q := dbq.New(h.pool)
|
||||
if err := q.SnoozeSuggestion(r.Context(), dbq.SnoozeSuggestionParams{
|
||||
UserID: user.ID,
|
||||
CandidateMbid: mbid,
|
||||
CandidateName: name,
|
||||
Column4: days,
|
||||
}); err != nil {
|
||||
h.logger.Error("api: snooze suggestion", "err", err)
|
||||
writeErr(w, apierror.InternalMsg("failed to snooze suggestion", err))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleUnsnoozeSuggestion implements
|
||||
// DELETE /api/discover/suggestions/{mbid}/snooze.
|
||||
//
|
||||
// Brings a parked candidate back immediately. 404s an MBID this user never
|
||||
// snoozed, so the client can tell "undone" from "there was nothing there".
|
||||
func (h *handlers) handleUnsnoozeSuggestion(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
mbid := strings.TrimSpace(chi.URLParam(r, "mbid"))
|
||||
if mbid == "" {
|
||||
writeErr(w, apierror.BadRequest("invalid_id", "missing mbid"))
|
||||
return
|
||||
}
|
||||
q := dbq.New(h.pool)
|
||||
rows, err := q.UnsnoozeSuggestion(r.Context(), dbq.UnsnoozeSuggestionParams{
|
||||
UserID: user.ID,
|
||||
CandidateMbid: mbid,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("api: unsnooze suggestion", "err", err)
|
||||
writeErr(w, apierror.InternalMsg("failed to unsnooze suggestion", err))
|
||||
return
|
||||
}
|
||||
if rows == 0 {
|
||||
writeErr(w, apierror.NotFound("snooze"))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleListSuggestionSnoozes implements GET /api/discover/snoozes.
|
||||
//
|
||||
// The un-snooze surface needs this: a parked candidate is by definition
|
||||
// absent from the suggestion deck, so without a list there is no way to
|
||||
// reach the DELETE above. Scoped to the caller. Expired rows are
|
||||
// already filtered by the query — the hourly gc sweep only reclaims space.
|
||||
func (h *handlers) handleListSuggestionSnoozes(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rows, err := dbq.New(h.pool).ListActiveSuggestionSnoozes(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
h.logger.Error("api: list suggestion snoozes", "err", err)
|
||||
writeErr(w, apierror.InternalMsg("failed to load snoozes", err))
|
||||
return
|
||||
}
|
||||
out := make([]snoozeView, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
out = append(out, snoozeView{
|
||||
MBID: row.CandidateMbid,
|
||||
Name: row.CandidateName,
|
||||
SnoozedUntil: row.SnoozedUntil,
|
||||
CreatedAt: row.CreatedAt,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// resolveSuggestionArt points each suggestion's ImageURL at Minstrel's
|
||||
// catalogue art endpoint. Nothing is fetched here: the image is
|
||||
// looked up from the enabled cover-art sources when the browser asks for it,
|
||||
// and kept, so listing suggestions makes no outbound call. A candidate with
|
||||
// no MBID keeps an empty ImageURL and the client renders its placeholder.
|
||||
func resolveSuggestionArt(views []suggestionView) {
|
||||
for i := range views {
|
||||
if views[i].MBID != "" {
|
||||
views[i].ImageURL = artistArtURL(views[i].MBID, views[i].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
func newSuggestionsRouter(h *handlers) chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Get("/api/discover/suggestions", h.handleListSuggestions)
|
||||
return r
|
||||
}
|
||||
|
||||
func doListSuggestions(h *handlers, user dbq.User, query string) *httptest.ResponseRecorder {
|
||||
url := "/api/discover/suggestions"
|
||||
if query != "" {
|
||||
url += "?" + query
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, url, nil)
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
newSuggestionsRouter(h).ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestSuggestions_HappyPath(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "pw", false)
|
||||
|
||||
q := dbq.New(pool)
|
||||
seed, err := q.UpsertArtist(context.Background(), dbq.UpsertArtistParams{
|
||||
Name: "Seed", SortName: "Seed",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("UpsertArtist: %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(context.Background(),
|
||||
`INSERT INTO general_likes_artists (user_id, artist_id) VALUES ($1, $2)`,
|
||||
user.ID, seed.ID,
|
||||
); err != nil {
|
||||
t.Fatalf("like artist: %v", err)
|
||||
}
|
||||
if err := q.UpsertArtistSimilarityUnmatched(context.Background(), dbq.UpsertArtistSimilarityUnmatchedParams{
|
||||
SeedArtistID: seed.ID,
|
||||
CandidateMbid: "out-mbid",
|
||||
CandidateName: "Outsider",
|
||||
Score: 0.9,
|
||||
Source: "listenbrainz",
|
||||
}); err != nil {
|
||||
t.Fatalf("UpsertArtistSimilarityUnmatched: %v", err)
|
||||
}
|
||||
|
||||
w := doListSuggestions(h, user, "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var got []suggestionView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("len = %d, want 1; body = %s", len(got), w.Body.String())
|
||||
}
|
||||
if got[0].MBID != "out-mbid" || got[0].Name != "Outsider" {
|
||||
t.Errorf("got = %+v", got[0])
|
||||
}
|
||||
if len(got[0].Attribution) != 1 || got[0].Attribution[0].Name != "Seed" {
|
||||
t.Errorf("attribution = %+v, want one entry named Seed", got[0].Attribution)
|
||||
}
|
||||
if !got[0].Attribution[0].IsLiked {
|
||||
t.Errorf("attribution.IsLiked = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuggestions_EmptyForNewUser(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "newbie", "pw", false)
|
||||
|
||||
w := doListSuggestions(h, user, "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
body := w.Body.String()
|
||||
if body != "[]" && body != "[]\n" {
|
||||
t.Errorf("body = %q, want []", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuggestions_BadLimit(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "pw", false)
|
||||
|
||||
w := doListSuggestions(h, user, "limit=not-a-number")
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user