autobrr/pkg/lidarr/client.go
Ludvig Lundgren e6cfc77e85
Feature: Lidarr (#15)
* feat(web): add lidarr download client

* feat: add lidarr download client
2021-08-22 02:17:13 +02:00

82 lines
2.1 KiB
Go

package lidarr
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/v1/%v", c.config.Hostname, endpoint)
req, err := http.NewRequest(http.MethodGet, reqUrl, http.NoBody)
if err != nil {
log.Error().Err(err).Msgf("lidarr 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("lidarr 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/v1/%v", c.config.Hostname, endpoint)
jsonData, err := json.Marshal(data)
if err != nil {
log.Error().Err(err).Msgf("lidarr 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("lidarr 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("lidarr client request error: %v", reqUrl)
return nil, err
}
// validate response
if res.StatusCode == http.StatusUnauthorized {
log.Error().Err(err).Msgf("lidarr client bad request: %v", reqUrl)
return nil, errors.New("unauthorized: bad credentials")
} else if res.StatusCode != http.StatusOK {
log.Error().Err(err).Msgf("lidarr client request error: %v", reqUrl)
return nil, nil
}
// return raw response and let the caller handle json unmarshal of body
return res, nil
}