autobrr/pkg/lidarr/lidarr.go
Ludvig Lundgren 3d018404a9
feat(download-clients): improve errors for starr apps (#250)
* feat(actions): improve errors for starr apps

* fix: tests expected error

* feat: radarr improve logging

* feat: sonarr improve logging and errors

* feat: lidarr improve logging and errors
2022-04-18 15:33:32 +02:00

117 lines
2.6 KiB
Go

package lidarr
import (
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"github.com/rs/zerolog/log"
)
type Config struct {
Hostname string
APIKey string
// basic auth username and password
BasicAuth bool
Username string
Password string
}
type Client interface {
Test() (*SystemStatusResponse, error)
Push(release Release) ([]string, error)
}
type client struct {
config Config
http *http.Client
}
// New create new lidarr client
func New(config Config) Client {
httpClient := &http.Client{
Timeout: time.Second * 30,
}
c := &client{
config: config,
http: httpClient,
}
return c
}
type Release struct {
Title string `json:"title"`
DownloadUrl string `json:"downloadUrl"`
Size int64 `json:"size"`
Indexer string `json:"indexer"`
DownloadProtocol string `json:"downloadProtocol"`
Protocol string `json:"protocol"`
PublishDate string `json:"publishDate"`
}
type PushResponse struct {
Approved bool `json:"approved"`
Rejected bool `json:"rejected"`
TempRejected bool `json:"temporarilyRejected"`
Rejections []string `json:"rejections"`
}
type SystemStatusResponse struct {
Version string `json:"version"`
}
func (c *client) Test() (*SystemStatusResponse, error) {
status, res, err := c.get("system/status")
if err != nil {
log.Error().Stack().Err(err).Msg("lidarr client get error")
return nil, err
}
if status == http.StatusUnauthorized {
return nil, errors.New("unauthorized: bad credentials")
}
log.Trace().Msgf("lidarr system/status response status: %v body: %v", status, string(res))
response := SystemStatusResponse{}
err = json.Unmarshal(res, &response)
if err != nil {
log.Error().Stack().Err(err).Msg("lidarr client error json unmarshal")
return nil, err
}
return &response, nil
}
func (c *client) Push(release Release) ([]string, error) {
status, res, err := c.postBody("release/push", release)
if err != nil {
log.Error().Stack().Err(err).Msg("lidarr client post error")
return nil, err
}
log.Trace().Msgf("lidarr release/push response status: %v body: %v", status, string(res))
pushResponse := PushResponse{}
err = json.Unmarshal(res, &pushResponse)
if err != nil {
log.Error().Stack().Err(err).Msg("lidarr client error json unmarshal")
return nil, err
}
// log and return if rejected
if pushResponse.Rejected {
rejections := strings.Join(pushResponse.Rejections, ", ")
log.Trace().Msgf("lidarr push rejected: %s - reasons: %q", release.Title, rejections)
return pushResponse.Rejections, nil
}
return nil, nil
}