diff --git a/internal/api/admin_cover_sources.go b/internal/api/admin_cover_sources.go index 924eca90..a8183b0f 100644 --- a/internal/api/admin_cover_sources.go +++ b/internal/api/admin_cover_sources.go @@ -1,159 +1,23 @@ package api import ( - "encoding/json" - "errors" "net/http" - "time" - - "github.com/go-chi/chi/v5" - - "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" ) -// coverProviderResp is the wire shape for one provider in the -// GET /api/admin/cover-sources list. Mirrors coverart.ProviderInfo -// but uses snake_case JSON tags. -type coverProviderResp struct { - ID string `json:"id"` - DisplayName string `json:"display_name"` - RequiresAPIKey bool `json:"requires_api_key"` - Supports []string `json:"supports"` - Enabled bool `json:"enabled"` - APIKeySet bool `json:"api_key_set"` - DisplayOrder int32 `json:"display_order"` - Testable bool `json:"testable"` -} - -type coverProvidersListResp struct { - Providers []coverProviderResp `json:"providers"` - SourcesVersion int32 `json:"sources_version"` -} +// The cover-sources admin card: the shared provider-source handlers +// (admin_provider_sources.go) over the cover settings. // handleListCoverSources implements GET /api/admin/cover-sources. func (h *handlers) handleListCoverSources(w http.ResponseWriter, _ *http.Request) { - infos := h.coverSettings.ListProviderInfo() - out := coverProvidersListResp{ - Providers: make([]coverProviderResp, 0, len(infos)), - SourcesVersion: h.coverSettings.CurrentVersion(), - } - for _, info := range infos { - supports := info.Supports - if supports == nil { - supports = []string{} - } - out.Providers = append(out.Providers, coverProviderResp{ - ID: info.ID, - DisplayName: info.DisplayName, - RequiresAPIKey: info.RequiresAPIKey, - Supports: supports, - Enabled: info.Enabled, - APIKeySet: info.APIKeySet, - DisplayOrder: info.DisplayOrder, - Testable: info.Testable, - }) - } - writeJSON(w, http.StatusOK, out) + listProviderSources(w, h.coverSettings.Service) } -// updateCoverSourceReq is the PATCH body. nil pointers mean -// "leave unchanged"; non-nil means "set to this value (which may be -// empty string for api_key clearing)". -type updateCoverSourceReq struct { - Enabled *bool `json:"enabled,omitempty"` - APIKey *string `json:"api_key,omitempty"` -} - -type updateCoverSourceResp struct { - coverProviderResp - VersionBumped bool `json:"version_bumped"` -} - -// handleUpdateCoverSource implements PATCH -// /api/admin/cover-sources/{provider_id}. +// handleUpdateCoverSource implements PATCH /api/admin/cover-sources/{provider_id}. func (h *handlers) handleUpdateCoverSource(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "provider_id") - - var body updateCoverSourceReq - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - writeErr(w, apierror.BadRequest("bad_body", "invalid JSON")) - return - } - - bumped, err := h.coverSettings.UpdateProvider(r.Context(), id, coverart.ProviderUpdatePatch{ - Enabled: body.Enabled, - APIKey: body.APIKey, - }) - if err != nil { - if errors.Is(err, coverart.ErrProviderNotFound) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "no such provider"}) - return - } - h.logger.Error("admin: update cover source", "id", id, "err", err) - writeErr(w, apierror.InternalMsg("update failed", err)) - return - } - - // Re-fetch the provider info to return. - infos := h.coverSettings.ListProviderInfo() - var found coverProviderResp - for _, info := range infos { - if info.ID == id { - supports := info.Supports - if supports == nil { - supports = []string{} - } - found = coverProviderResp{ - ID: info.ID, - DisplayName: info.DisplayName, - RequiresAPIKey: info.RequiresAPIKey, - Supports: supports, - Enabled: info.Enabled, - APIKeySet: info.APIKeySet, - DisplayOrder: info.DisplayOrder, - Testable: info.Testable, - } - break - } - } - writeJSON(w, http.StatusOK, updateCoverSourceResp{ - coverProviderResp: found, - VersionBumped: bumped, - }) + h.updateProviderSource(w, r, h.coverSettings.Service) } -type testCoverSourceResp struct { - OK bool `json:"ok"` - DurationMs int64 `json:"duration_ms,omitempty"` - Error string `json:"error,omitempty"` -} - -// handleTestCoverSource implements POST -// /api/admin/cover-sources/{provider_id}/test. +// handleTestCoverSource implements POST /api/admin/cover-sources/{provider_id}/test. func (h *handlers) handleTestCoverSource(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "provider_id") - - start := time.Now() - err := h.coverSettings.TestProvider(r.Context(), id) - duration := time.Since(start).Milliseconds() - - if err == nil { - writeJSON(w, http.StatusOK, testCoverSourceResp{OK: true, DurationMs: duration}) - return - } - - if errors.Is(err, coverart.ErrProviderNotFound) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "no such provider"}) - return - } - - // Not testable, or test failed — both surface as ok=false. - // 200 status because the operation completed; the test result is - // data, not an error. - writeJSON(w, http.StatusOK, testCoverSourceResp{ - OK: false, - DurationMs: duration, - Error: err.Error(), - }) + testProviderSource(w, r, h.coverSettings.Service) } diff --git a/internal/api/admin_cover_sources_test.go b/internal/api/admin_cover_sources_test.go index 0da0d4f9..52930f8d 100644 --- a/internal/api/admin_cover_sources_test.go +++ b/internal/api/admin_cover_sources_test.go @@ -86,7 +86,7 @@ func TestAdminListCoverSources_ReturnsRegisteredProviders(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp coverProvidersListResp + var resp providerSourcesListResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -132,7 +132,7 @@ func TestAdminUpdateCoverSource_FlippingEnabledBumpsVersion(t *testing.T) { admin := seedUser(t, h.pool, "csflip", "pw", true) disabled := false - body, _ := json.Marshal(updateCoverSourceReq{Enabled: &disabled}) + body, _ := json.Marshal(updateProviderSourceReq{Enabled: &disabled}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/cover-sources/flip-prov", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -142,7 +142,7 @@ func TestAdminUpdateCoverSource_FlippingEnabledBumpsVersion(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp updateCoverSourceResp + var resp updateProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -164,7 +164,7 @@ func TestAdminUpdateCoverSource_KeyOnlyDoesNotBump(t *testing.T) { admin := seedUser(t, h.pool, "cskey", "pw", true) newKey := "newkey" - body, _ := json.Marshal(updateCoverSourceReq{APIKey: &newKey}) + body, _ := json.Marshal(updateProviderSourceReq{APIKey: &newKey}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/cover-sources/key-prov", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -174,7 +174,7 @@ func TestAdminUpdateCoverSource_KeyOnlyDoesNotBump(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp updateCoverSourceResp + var resp updateProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -197,7 +197,7 @@ func TestAdminUpdateCoverSource_UnknownProvider404(t *testing.T) { h, _ := testHandlersWithCoverSettings(t) admin := seedUser(t, h.pool, "cs404", "pw", true) - body, _ := json.Marshal(updateCoverSourceReq{}) + body, _ := json.Marshal(updateProviderSourceReq{}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/cover-sources/missing", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -252,7 +252,7 @@ func TestAdminTestCoverSource_NotTestableReturnsOkFalse(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp testCoverSourceResp + var resp testProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } diff --git a/internal/api/admin_provider_sources.go b/internal/api/admin_provider_sources.go new file mode 100644 index 00000000..474b281a --- /dev/null +++ b/internal/api/admin_provider_sources.go @@ -0,0 +1,132 @@ +package api + +import ( + "encoding/json" + "errors" + "net/http" + "time" + + "github.com/go-chi/chi/v5" + + "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" + "git.fabledsword.com/bvandeusen/minstrel/internal/providers" +) + +// The admin cards for outside sources, Cover sources and Tag sources, run +// on these. Each family's handlers pass their own providers.Service, so the +// two cards answer in one shape and share no rows. + +// providerSourceResp is one provider in a sources list. +type providerSourceResp struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + RequiresAPIKey bool `json:"requires_api_key"` + Supports []string `json:"supports"` + Enabled bool `json:"enabled"` + APIKeySet bool `json:"api_key_set"` + DisplayOrder int32 `json:"display_order"` + Testable bool `json:"testable"` +} + +func providerSourceRespFrom(info providers.Info) providerSourceResp { + supports := info.Supports + if supports == nil { + supports = []string{} + } + return providerSourceResp{ + ID: info.ID, + DisplayName: info.DisplayName, + RequiresAPIKey: info.RequiresAPIKey, + Supports: supports, + Enabled: info.Enabled, + APIKeySet: info.APIKeySet, + DisplayOrder: info.DisplayOrder, + Testable: info.Testable, + } +} + +type providerSourcesListResp struct { + Providers []providerSourceResp `json:"providers"` + SourcesVersion int32 `json:"sources_version"` +} + +// updateProviderSourceReq is the PATCH body. A nil field is left as it +// is; an empty api_key clears the key. +type updateProviderSourceReq struct { + Enabled *bool `json:"enabled,omitempty"` + APIKey *string `json:"api_key,omitempty"` +} + +type updateProviderSourceResp struct { + providerSourceResp + VersionBumped bool `json:"version_bumped"` +} + +// testProviderSourceResp is a Test-button result. It answers 200 whether +// or not the test passed: the result is data, not an error. +type testProviderSourceResp struct { + OK bool `json:"ok"` + DurationMs int64 `json:"duration_ms,omitempty"` + Error string `json:"error,omitempty"` +} + +var errNoSuchProvider = apierror.New(http.StatusNotFound, "not_found", "no such provider") + +// listProviderSources answers GET /api/admin/{family}-sources. +func listProviderSources(w http.ResponseWriter, svc *providers.Service) { + infos := svc.ListProviderInfo() + out := providerSourcesListResp{ + Providers: make([]providerSourceResp, 0, len(infos)), + SourcesVersion: svc.CurrentVersion(), + } + for _, info := range infos { + out.Providers = append(out.Providers, providerSourceRespFrom(info)) + } + writeJSON(w, http.StatusOK, out) +} + +// updateProviderSource answers PATCH /api/admin/{family}-sources/{provider_id} +// with the provider as it now stands. +func (h *handlers) updateProviderSource(w http.ResponseWriter, r *http.Request, svc *providers.Service) { + id := chi.URLParam(r, "provider_id") + var body updateProviderSourceReq + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeErr(w, apierror.BadRequest("bad_body", "invalid JSON")) + return + } + bumped, err := svc.UpdateProvider(r.Context(), id, providers.UpdatePatch{Enabled: body.Enabled, APIKey: body.APIKey}) + if err != nil { + if errors.Is(err, providers.ErrProviderNotFound) { + writeErr(w, errNoSuchProvider) + return + } + h.logger.Error("admin: update provider source", "id", id, "err", err) + writeErr(w, apierror.InternalMsg("update failed", err)) + return + } + var found providerSourceResp + for _, info := range svc.ListProviderInfo() { + if info.ID == id { + found = providerSourceRespFrom(info) + break + } + } + writeJSON(w, http.StatusOK, updateProviderSourceResp{providerSourceResp: found, VersionBumped: bumped}) +} + +// testProviderSource answers POST /api/admin/{family}-sources/{provider_id}/test. +func testProviderSource(w http.ResponseWriter, r *http.Request, svc *providers.Service) { + id := chi.URLParam(r, "provider_id") + start := time.Now() + err := svc.TestProvider(r.Context(), id) + duration := time.Since(start).Milliseconds() + switch { + case err == nil: + writeJSON(w, http.StatusOK, testProviderSourceResp{OK: true, DurationMs: duration}) + case errors.Is(err, providers.ErrProviderNotFound): + writeErr(w, errNoSuchProvider) + default: + // Not testable, or the test failed. + writeJSON(w, http.StatusOK, testProviderSourceResp{OK: false, DurationMs: duration, Error: err.Error()}) + } +} diff --git a/internal/api/admin_tag_sources.go b/internal/api/admin_tag_sources.go index 412a1a42..ca752bb0 100644 --- a/internal/api/admin_tag_sources.go +++ b/internal/api/admin_tag_sources.go @@ -1,139 +1,27 @@ package api import ( - "encoding/json" - "errors" "net/http" - "time" - - "github.com/go-chi/chi/v5" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" - "git.fabledsword.com/bvandeusen/minstrel/internal/tags" ) -// tagSourceResp is the wire shape for one tag-enrichment provider in the -// GET /api/admin/tag-sources list. Mirrors the cover-sources admin surface -// (admin_cover_sources.go) — a separate, independent settings card so a new -// tag source is added without touching art settings. -type tagSourceResp struct { - ID string `json:"id"` - DisplayName string `json:"display_name"` - RequiresAPIKey bool `json:"requires_api_key"` - Supports []string `json:"supports"` - Enabled bool `json:"enabled"` - APIKeySet bool `json:"api_key_set"` - DisplayOrder int32 `json:"display_order"` - Testable bool `json:"testable"` -} - -func tagSourceRespFrom(info tags.ProviderInfo) tagSourceResp { - supports := info.Supports - if supports == nil { - supports = []string{} - } - return tagSourceResp{ - ID: info.ID, - DisplayName: info.DisplayName, - RequiresAPIKey: info.RequiresAPIKey, - Supports: supports, - Enabled: info.Enabled, - APIKeySet: info.APIKeySet, - DisplayOrder: info.DisplayOrder, - Testable: info.Testable, - } -} - -type tagSourcesListResp struct { - Providers []tagSourceResp `json:"providers"` - SourcesVersion int32 `json:"sources_version"` -} +// The tag-sources admin card: the shared provider-source handlers +// (admin_provider_sources.go) over the tag settings. // handleListTagSources implements GET /api/admin/tag-sources. func (h *handlers) handleListTagSources(w http.ResponseWriter, _ *http.Request) { - infos := h.tagSettings.ListProviderInfo() - out := tagSourcesListResp{ - Providers: make([]tagSourceResp, 0, len(infos)), - SourcesVersion: h.tagSettings.CurrentVersion(), - } - for _, info := range infos { - out.Providers = append(out.Providers, tagSourceRespFrom(info)) - } - writeJSON(w, http.StatusOK, out) -} - -// updateTagSourceReq is the PATCH body. nil pointers mean "leave -// unchanged"; non-nil sets (empty api_key clears). -type updateTagSourceReq struct { - Enabled *bool `json:"enabled,omitempty"` - APIKey *string `json:"api_key,omitempty"` -} - -type updateTagSourceResp struct { - tagSourceResp - VersionBumped bool `json:"version_bumped"` + listProviderSources(w, h.tagSettings.Service) } // handleUpdateTagSource implements PATCH /api/admin/tag-sources/{provider_id}. func (h *handlers) handleUpdateTagSource(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "provider_id") - - var body updateTagSourceReq - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - writeErr(w, apierror.BadRequest("bad_body", "invalid JSON")) - return - } - - bumped, err := h.tagSettings.UpdateProvider(r.Context(), id, tags.ProviderUpdatePatch{ - Enabled: body.Enabled, - APIKey: body.APIKey, - }) - if err != nil { - if errors.Is(err, tags.ErrProviderNotFound) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "no such provider"}) - return - } - h.logger.Error("admin: update tag source", "id", id, "err", err) - writeErr(w, apierror.InternalMsg("update failed", err)) - return - } - - var found tagSourceResp - for _, info := range h.tagSettings.ListProviderInfo() { - if info.ID == id { - found = tagSourceRespFrom(info) - break - } - } - writeJSON(w, http.StatusOK, updateTagSourceResp{tagSourceResp: found, VersionBumped: bumped}) + h.updateProviderSource(w, r, h.tagSettings.Service) } -type testTagSourceResp struct { - OK bool `json:"ok"` - DurationMs int64 `json:"duration_ms,omitempty"` - Error string `json:"error,omitempty"` -} - -// handleTestTagSource implements POST -// /api/admin/tag-sources/{provider_id}/test. +// handleTestTagSource implements POST /api/admin/tag-sources/{provider_id}/test. func (h *handlers) handleTestTagSource(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "provider_id") - - start := time.Now() - err := h.tagSettings.TestProvider(r.Context(), id) - duration := time.Since(start).Milliseconds() - - if err == nil { - writeJSON(w, http.StatusOK, testTagSourceResp{OK: true, DurationMs: duration}) - return - } - if errors.Is(err, tags.ErrProviderNotFound) { - writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "no such provider"}) - return - } - // Not testable, or the test failed — both surface as ok=false with a - // 200 (the operation completed; the result is data, not an error). - writeJSON(w, http.StatusOK, testTagSourceResp{OK: false, DurationMs: duration, Error: err.Error()}) + testProviderSource(w, r, h.tagSettings.Service) } type researchTagsResp struct { diff --git a/internal/api/admin_tag_sources_test.go b/internal/api/admin_tag_sources_test.go index cb00a0a8..e3d8e440 100644 --- a/internal/api/admin_tag_sources_test.go +++ b/internal/api/admin_tag_sources_test.go @@ -82,7 +82,7 @@ func TestAdminListTagSources_ReturnsRegisteredProviders(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp tagSourcesListResp + var resp providerSourcesListResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -115,7 +115,7 @@ func TestAdminUpdateTagSource_FlippingEnabledBumpsVersion(t *testing.T) { admin := seedUser(t, h.pool, "tsflip", "pw", true) disabled := false - body, _ := json.Marshal(updateTagSourceReq{Enabled: &disabled}) + body, _ := json.Marshal(updateProviderSourceReq{Enabled: &disabled}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/tag-sources/flip-tag", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -125,7 +125,7 @@ func TestAdminUpdateTagSource_FlippingEnabledBumpsVersion(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp updateTagSourceResp + var resp updateProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -146,7 +146,7 @@ func TestAdminUpdateTagSource_KeyOnlyDoesNotBump(t *testing.T) { admin := seedUser(t, h.pool, "tskey", "pw", true) newKey := "newkey" - body, _ := json.Marshal(updateTagSourceReq{APIKey: &newKey}) + body, _ := json.Marshal(updateProviderSourceReq{APIKey: &newKey}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/tag-sources/key-tag", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -156,7 +156,7 @@ func TestAdminUpdateTagSource_KeyOnlyDoesNotBump(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp updateTagSourceResp + var resp updateProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) } @@ -178,7 +178,7 @@ func TestAdminUpdateTagSource_UnknownProvider404(t *testing.T) { h := testHandlersWithTagSettings(t) admin := seedUser(t, h.pool, "ts404", "pw", true) - body, _ := json.Marshal(updateTagSourceReq{}) + body, _ := json.Marshal(updateProviderSourceReq{}) req := httptest.NewRequest(http.MethodPatch, "/api/admin/tag-sources/missing", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req = withUser(req, admin) @@ -230,7 +230,7 @@ func TestAdminTestTagSource_NotTestableReturnsOkFalse(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } - var resp testTagSourceResp + var resp testProviderSourceResp if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode: %v", err) }