Feature: Radarr (#13)

* feat(web): add and update radarr

* feat: add radarr download client

* feat: add tests
This commit is contained in:
Ludvig Lundgren 2021-08-21 23:36:06 +02:00 committed by GitHub
parent 0c4aaa29b0
commit 455284a94b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
35 changed files with 2898 additions and 3348 deletions

82
pkg/radarr/client.go Normal file
View file

@ -0,0 +1,82 @@
package radarr
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/rs/zerolog/log"
)
func (c *client) get(endpoint string) (*http.Response, error) {
reqUrl := fmt.Sprintf("%v/api/v3/%v", c.config.Hostname, endpoint)
req, err := http.NewRequest(http.MethodGet, reqUrl, http.NoBody)
if err != nil {
log.Error().Err(err).Msgf("radarr client request error : %v", reqUrl)
return nil, err
}
if c.config.BasicAuth {
req.SetBasicAuth(c.config.Username, c.config.Password)
}
req.Header.Add("X-Api-Key", c.config.APIKey)
req.Header.Set("User-Agent", "autobrr")
res, err := c.http.Do(req)
if err != nil {
log.Error().Err(err).Msgf("radarr client request error : %v", reqUrl)
return nil, err
}
if res.StatusCode == http.StatusUnauthorized {
return nil, errors.New("unauthorized: bad credentials")
}
return res, nil
}
func (c *client) post(endpoint string, data interface{}) (*http.Response, error) {
reqUrl := fmt.Sprintf("%v/api/v3/%v", c.config.Hostname, endpoint)
jsonData, err := json.Marshal(data)
if err != nil {
log.Error().Err(err).Msgf("radarr client could not marshal data: %v", reqUrl)
return nil, err
}
req, err := http.NewRequest(http.MethodPost, reqUrl, bytes.NewBuffer(jsonData))
if err != nil {
log.Error().Err(err).Msgf("radarr client request error: %v", reqUrl)
return nil, err
}
if c.config.BasicAuth {
req.SetBasicAuth(c.config.Username, c.config.Password)
}
req.Header.Add("X-Api-Key", c.config.APIKey)
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
req.Header.Set("User-Agent", "autobrr")
res, err := c.http.Do(req)
if err != nil {
log.Error().Err(err).Msgf("radarr client request error: %v", reqUrl)
return nil, err
}
// validate response
if res.StatusCode == http.StatusUnauthorized {
log.Error().Err(err).Msgf("radarr client bad request: %v", reqUrl)
return nil, errors.New("unauthorized: bad credentials")
} else if res.StatusCode != http.StatusOK {
log.Error().Err(err).Msgf("radarr client request error: %v", reqUrl)
return nil, nil
}
// return raw response and let the caller handle json unmarshal of body
return res, nil
}

130
pkg/radarr/radarr.go Normal file
View file

@ -0,0 +1,130 @@
package radarr
import (
"encoding/json"
"errors"
"fmt"
"io"
"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) error
}
type client struct {
config Config
http *http.Client
}
func New(config Config) Client {
httpClient := &http.Client{
Timeout: time.Second * 10,
}
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) {
res, err := c.get("system/status")
if err != nil {
log.Error().Err(err).Msg("radarr client get error")
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
log.Error().Err(err).Msg("radarr client error reading body")
return nil, err
}
response := SystemStatusResponse{}
err = json.Unmarshal(body, &response)
if err != nil {
log.Error().Err(err).Msg("radarr client error json unmarshal")
return nil, err
}
log.Trace().Msgf("radarr system/status response: %+v", response)
return &response, nil
}
func (c *client) Push(release Release) error {
res, err := c.post("release/push", release)
if err != nil {
log.Error().Err(err).Msg("radarr client post error")
return err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
log.Error().Err(err).Msg("radarr client error reading body")
return err
}
pushResponse := make([]PushResponse, 0)
err = json.Unmarshal(body, &pushResponse)
if err != nil {
log.Error().Err(err).Msg("radarr client error json unmarshal")
return err
}
log.Trace().Msgf("radarr release/push response body: %+v", string(body))
// log and return if rejected
if pushResponse[0].Rejected {
rejections := strings.Join(pushResponse[0].Rejections, ", ")
log.Trace().Msgf("radarr push rejected: %s - reasons: %q", release.Title, rejections)
return errors.New(fmt.Errorf("radarr push rejected %v", rejections).Error())
}
return nil
}

183
pkg/radarr/radarr_test.go Normal file
View file

@ -0,0 +1,183 @@
package radarr
import (
"errors"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/rs/zerolog"
)
func Test_client_Push(t *testing.T) {
// disable logger
zerolog.SetGlobalLevel(zerolog.Disabled)
mux := http.NewServeMux()
ts := httptest.NewServer(mux)
defer ts.Close()
key := "mock-key"
mux.HandleFunc("/api/v3/release/push", func(w http.ResponseWriter, r *http.Request) {
// request validation logic
apiKey := r.Header.Get("X-Api-Key")
if apiKey != "" {
if apiKey != key {
w.WriteHeader(http.StatusUnauthorized)
w.Write(nil)
return
}
}
// read json response
jsonPayload, _ := ioutil.ReadFile("testdata/release_push_response.json")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonPayload)
})
type fields struct {
config Config
}
type args struct {
release Release
}
tests := []struct {
name string
fields fields
args args
err error
wantErr bool
}{
{
name: "push",
fields: fields{
config: Config{
Hostname: ts.URL,
APIKey: "",
BasicAuth: false,
Username: "",
Password: "",
},
},
args: args{release: Release{
Title: "Some.Old.Movie.1996.Remastered.1080p.BluRay.REMUX.AVC.MULTI.TrueHD.Atmos.7.1-NOGROUP",
DownloadUrl: "https://www.test.org/rss/download/0000001/00000000000000000000/Some.Old.Movie.1996.Remastered.1080p.BluRay.REMUX.AVC.MULTI.TrueHD.Atmos.7.1-NOGROUP.torrent",
Size: 0,
Indexer: "test",
DownloadProtocol: "torrent",
Protocol: "torrent",
PublishDate: "2021-08-21T15:36:00Z",
}},
err: errors.New("radarr push rejected Could not find Some Old Movie"),
wantErr: true,
},
{
name: "push_error",
fields: fields{
config: Config{
Hostname: ts.URL,
APIKey: key,
BasicAuth: false,
Username: "",
Password: "",
},
},
args: args{release: Release{
Title: "Some.Old.Movie.1996.Remastered.1080p.BluRay.REMUX.AVC.MULTI.TrueHD.Atmos.7.1-NOGROUP",
DownloadUrl: "https://www.test.org/rss/download/0000001/00000000000000000000/Some.Old.Movie.1996.Remastered.1080p.BluRay.REMUX.AVC.MULTI.TrueHD.Atmos.7.1-NOGROUP.torrent",
Size: 0,
Indexer: "test",
DownloadProtocol: "torrent",
Protocol: "torrent",
PublishDate: "2021-08-21T15:36:00Z",
}},
err: errors.New("radarr push rejected Could not find Some Old Movie"),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := New(tt.fields.config)
err := c.Push(tt.args.release)
if tt.wantErr && assert.Error(t, err) {
assert.Equal(t, tt.err, err)
}
})
}
}
func Test_client_Test(t *testing.T) {
// disable logger
zerolog.SetGlobalLevel(zerolog.Disabled)
key := "mock-key"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
apiKey := r.Header.Get("X-Api-Key")
if apiKey != "" {
if apiKey != key {
w.WriteHeader(http.StatusUnauthorized)
w.Write(nil)
return
}
}
jsonPayload, _ := ioutil.ReadFile("testdata/system_status_response.json")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonPayload)
}))
defer srv.Close()
tests := []struct {
name string
cfg Config
want *SystemStatusResponse
err error
wantErr bool
}{
{
name: "fetch",
cfg: Config{
Hostname: srv.URL,
APIKey: key,
BasicAuth: false,
Username: "",
Password: "",
},
want: &SystemStatusResponse{Version: "3.2.2.5080"},
err: nil,
wantErr: false,
},
{
name: "fetch_unauthorized",
cfg: Config{
Hostname: srv.URL,
APIKey: "bad-mock-key",
BasicAuth: false,
Username: "",
Password: "",
},
want: nil,
wantErr: true,
err: errors.New("unauthorized: bad credentials"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := New(tt.cfg)
got, err := c.Test()
if tt.wantErr && assert.Error(t, err) {
assert.Equal(t, tt.err, err)
}
assert.Equal(t, tt.want, got)
})
}
}

View file

@ -0,0 +1,54 @@
[
{
"guid": "PUSH-https://www.test.org/rss/download/0000001/00000000000000000000/Some.Old.Movie.1996.Remastered.1080p.BluRay.REMUX.AVC.MULTI.TrueHD.Atmos.7.1-NOGROUP.torrent",
"quality": {
"quality": {
"id": 30,
"name": "Remux-1080p",
"source": "bluray",
"resolution": 1080,
"modifier": "remux"
},
"revision": {
"version": 1,
"real": 0,
"isRepack": false
}
},
"customFormats": [],
"customFormatScore": 0,
"qualityWeight": 1901,
"age": 0,
"ageHours": 0.028290299305555554,
"ageMinutes": 1.69741874,
"size": 0,
"indexerId": 0,
"indexer": "test",
"releaseGroup": "NOGROUP",
"releaseHash": "",
"title": "Some.Old.Movie.1996.Remastered.1080p.BluRay.REMUX.AVC.MULTI.TrueHD.Atmos.7.1-NOGROUP",
"sceneSource": false,
"movieTitle": "Twister",
"languages": [
{
"id": 1,
"name": "English"
}
],
"approved": false,
"temporarilyRejected": false,
"rejected": true,
"tmdbId": 0,
"imdbId": 0,
"rejections": [
"Could not find Some Old Movie"
],
"publishDate": "2021-08-21T15:36:00Z",
"downloadUrl": "https://www.test.org/rss/download/0000001/00000000000000000000/Some.Old.Movie.1996.Remastered.1080p.BluRay.REMUX.AVC.MULTI.TrueHD.Atmos.7.1-NOGROUP.torrent",
"downloadAllowed": false,
"releaseWeight": 0,
"indexerFlags": [],
"edition": "Remastered",
"protocol": "torrent"
}
]

View file

@ -0,0 +1,28 @@
{
"version": "3.2.2.5080",
"buildTime": "2021-06-03T11:51:33Z",
"isDebug": false,
"isProduction": true,
"isAdmin": false,
"isUserInteractive": true,
"startupPath": "/opt/Radarr",
"appData": "/home/test/.config/Radarr",
"osName": "debian",
"osVersion": "10",
"isNetCore": true,
"isMono": false,
"isLinux": true,
"isOsx": false,
"isWindows": false,
"isDocker": false,
"mode": "console",
"branch": "master",
"authentication": "none",
"sqliteVersion": "3.27.2",
"migrationVersion": 195,
"urlBase": "/radarr",
"runtimeVersion": "5.0.5",
"runtimeName": "netCore",
"startTime": "2021-08-20T20:49:42Z",
"packageUpdateMechanism": "builtIn"
}