mirror of
https://github.com/FJurmanovic/sugarr.git
synced 2026-11-11 07:41:08 +00:00
init
This commit is contained in:
59
internal/controller/request.go
Normal file
59
internal/controller/request.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/fjurmanovic/sugarr/internal/service"
|
||||
"github.com/fjurmanovic/sugarr/internal/utl/configs"
|
||||
"github.com/fjurmanovic/sugarr/internal/utl/httputil"
|
||||
)
|
||||
|
||||
type RequestController struct {
|
||||
cfg *configs.Config
|
||||
rec *service.Recommender
|
||||
}
|
||||
|
||||
func NewRequestController(mux *http.ServeMux, cfg *configs.Config, rec *service.Recommender) *RequestController {
|
||||
c := &RequestController{cfg: cfg, rec: rec}
|
||||
mux.HandleFunc("POST /recommendations/request", c.handle)
|
||||
return c
|
||||
}
|
||||
|
||||
// handle adds a movie to Radarr by TMDb ID.
|
||||
// Body: {"tmdb_id": 12345}
|
||||
func (c *RequestController) handle(w http.ResponseWriter, r *http.Request) {
|
||||
if !c.cfg.RadarrEnabled || c.rec.Radarr() == nil {
|
||||
httputil.WriteError(w, http.StatusBadRequest, "Radarr is not enabled")
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
TMDbID int `json:"tmdb_id"`
|
||||
}
|
||||
if err := decodeJSON(r, &body); err != nil || body.TMDbID == 0 {
|
||||
httputil.WriteError(w, http.StatusBadRequest, "body must be {\"tmdb_id\": 12345}")
|
||||
return
|
||||
}
|
||||
|
||||
movie, err := c.rec.Radarr().Lookup(body.TMDbID)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("radarr lookup failed: %s", err))
|
||||
return
|
||||
}
|
||||
if err := c.rec.Radarr().AddMovie(*movie); err != nil {
|
||||
httputil.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("radarr add failed: %s", err))
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, http.StatusOK, map[string]any{"requested": true, "title": movie.Title})
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, v any) error {
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(body, v)
|
||||
}
|
||||
Reference in New Issue
Block a user