sonda/internal/api/http/handlers_providers.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +01:00

208 lines
7 KiB
Go

package httpapi
import (
"context"
"errors"
"net/http"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/providers"
"git.kmalloc.org/squid/sonda/internal/providers/lidarr"
)
// providersHandlers are the admin-only routes that set up the external
// providers. The API key can be written here but is never returned.
type providersHandlers struct {
svc providerService
lidarr lidarrOptionsService
}
type providerJSON struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
NeedsAPIKey bool `json:"needs_api_key"`
NeedsURL bool `json:"needs_url"`
HasAPIKey bool `json:"has_api_key"`
Contact string `json:"contact"`
URL string `json:"url"`
Sends string `json:"sends"`
Notes string `json:"notes"`
UpdatedAt *string `json:"updated_at"`
// Lidarr is only there for the provider that has these options.
Lidarr *lidarrOptionsJSON `json:"lidarr,omitempty"`
}
type lidarrOptionsJSON struct {
QualityProfileID int `json:"quality_profile_id"`
MetadataProfileID int `json:"metadata_profile_id"`
RootFolderPath string `json:"root_folder_path"`
Monitor string `json:"monitor"`
SearchMissing bool `json:"search_missing"`
}
func toProviderJSON(in providers.Info) providerJSON {
out := providerJSON{
Name: in.Name, Enabled: in.Enabled, NeedsAPIKey: in.NeedsAPIKey, NeedsURL: in.NeedsURL, HasAPIKey: in.HasAPIKey,
Contact: in.Contact, URL: in.URL, Sends: in.Sends, Notes: in.Notes,
}
if in.NeedsURL {
out.Lidarr = &lidarrOptionsJSON{
QualityProfileID: in.Lidarr.QualityProfileID, MetadataProfileID: in.Lidarr.MetadataProfileID,
RootFolderPath: in.Lidarr.RootFolderPath, Monitor: in.Lidarr.Monitor, SearchMissing: in.Lidarr.SearchMissing,
}
}
if !in.UpdatedAt.IsZero() {
out.UpdatedAt = rfc3339(in.UpdatedAt)
}
return out
}
func writeProviderError(c *gin.Context, err error) {
switch {
case errors.Is(err, providers.ErrUnknownProvider):
writeError(c, http.StatusNotFound, "provider_not_found", "no such provider")
case errors.Is(err, providers.ErrNoTest):
writeError(c, http.StatusBadRequest, "invalid_input", "this provider has no test")
case errors.Is(err, providers.ErrInvalidSettings):
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
}
func (h *providersHandlers) list(c *gin.Context) {
infos, err := h.svc.List(c.Request.Context())
if err != nil {
writeProviderError(c, err)
return
}
out := make([]providerJSON, len(infos))
for i, in := range infos {
out[i] = toProviderJSON(in)
}
c.JSON(http.StatusOK, gin.H{"providers": out})
}
type updateProviderRequest struct {
Enabled *bool `json:"enabled"` // pointers: an absent field is left alone
APIKey *string `json:"api_key"`
Contact *string `json:"contact"`
URL *string `json:"url"`
// Lidarr replaces all the options at once; what it does not say is the default.
Lidarr *struct {
QualityProfileID int `json:"quality_profile_id"`
MetadataProfileID int `json:"metadata_profile_id"`
RootFolderPath string `json:"root_folder_path"`
Monitor string `json:"monitor"`
SearchMissing *bool `json:"search_missing"`
} `json:"lidarr"`
}
func (h *providersHandlers) update(c *gin.Context) {
var req updateProviderRequest
if !bindJSON(c, &req) {
return
}
patch := providers.Patch{Enabled: req.Enabled, APIKey: req.APIKey, Contact: req.Contact, URL: req.URL}
if l := req.Lidarr; l != nil {
o := providers.LidarrOptions{
QualityProfileID: l.QualityProfileID, MetadataProfileID: l.MetadataProfileID,
RootFolderPath: l.RootFolderPath, Monitor: l.Monitor, SearchMissing: true,
}
if o.Monitor == "" {
o.Monitor = "all"
}
if l.SearchMissing != nil {
o.SearchMissing = *l.SearchMissing
}
patch.Lidarr = &o
}
info, err := h.svc.Update(c.Request.Context(), c.Param("name"), patch)
if err != nil {
writeProviderError(c, err)
return
}
c.JSON(http.StatusOK, toProviderJSON(info))
}
func (h *providersHandlers) test(c *gin.Context) {
res, err := h.svc.Test(c.Request.Context(), c.Param("name"))
if err != nil {
writeProviderError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"ok": res.OK, "status": res.Status})
}
func (h *providersHandlers) purge(c *gin.Context) {
res, err := h.svc.Purge(c.Request.Context(), c.Param("name"))
if err != nil {
writeProviderError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"similar_artists": res.SimilarArtists, "tags": res.Tags, "descriptions": res.Descriptions, "images": res.Images, "artists": res.Artists})
}
type lidarrOptionsService interface {
Options(ctx context.Context) (lidarr.Options, error)
}
// writeLidarrError says what went wrong asking Lidarr, which is the admin's own server: not being
// set up is a conflict with the state of the settings, anything else is a bad gateway.
func writeLidarrError(c *gin.Context, err error) {
switch {
case errors.Is(err, lidarr.ErrNotConfigured):
writeError(c, http.StatusConflict, "lidarr_not_configured", "Lidarr has no address or no API key set")
case errors.Is(err, lidarr.ErrKeyRefused):
writeError(c, http.StatusBadGateway, "lidarr_key_refused", "Lidarr refused the API key")
case errors.Is(err, context.Canceled):
writeError(c, 499, "canceled", "request canceled")
case errors.Is(err, lidarr.ErrUnreachable), errors.Is(err, lidarr.ErrBadResponse), errors.Is(err, context.DeadlineExceeded):
_ = c.Error(err)
writeError(c, http.StatusBadGateway, "lidarr_unavailable", "Lidarr could not be asked")
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
}
type lidarrProfileJSON struct {
ID int `json:"id"`
Name string `json:"name"`
}
type lidarrFolderJSON struct {
Path string `json:"path"`
Accessible bool `json:"accessible"`
}
// lidarrOptions lists what Lidarr offers, for an admin to choose from. It works whether Lidarr is
// switched on or not, like a test of the key: the admin needs it to finish setting it up.
func (h *providersHandlers) lidarrOptions(c *gin.Context) {
o, err := h.lidarr.Options(c.Request.Context())
if err != nil {
writeLidarrError(c, err)
return
}
out := gin.H{
"quality_profiles": make([]lidarrProfileJSON, 0, len(o.QualityProfiles)),
"metadata_profiles": make([]lidarrProfileJSON, 0, len(o.MetadataProfiles)),
"root_folders": make([]lidarrFolderJSON, 0, len(o.RootFolders)),
}
q := out["quality_profiles"].([]lidarrProfileJSON)
for _, p := range o.QualityProfiles {
q = append(q, lidarrProfileJSON{ID: p.ID, Name: p.Name})
}
m := out["metadata_profiles"].([]lidarrProfileJSON)
for _, p := range o.MetadataProfiles {
m = append(m, lidarrProfileJSON{ID: p.ID, Name: p.Name})
}
f := out["root_folders"].([]lidarrFolderJSON)
for _, r := range o.RootFolders {
f = append(f, lidarrFolderJSON{Path: r.Path, Accessible: r.Accessible})
}
out["quality_profiles"], out["metadata_profiles"], out["root_folders"] = q, m, f
c.JSON(http.StatusOK, out)
}