-
Notifications
You must be signed in to change notification settings - Fork 1
/
nzbget.go
93 lines (77 loc) · 2.23 KB
/
nzbget.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package nzbget
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"net/http"
"strings"
"time"
"github.com/gorilla/rpc/json"
)
// Package defaults.
const (
DefaultTimeout = 1 * time.Minute
)
// Config is the input data needed to return a NZBGet struct.
// This is setup to allow you to easily pass this data in from a config file.
type Config struct {
URL string `json:"url" toml:"url" xml:"url" yaml:"url"`
User string `json:"user" toml:"user" xml:"user" yaml:"user"`
Pass string `json:"pass" toml:"pass" xml:"pass" yaml:"pass"`
Client *http.Client `json:"-" toml:"-" xml:"-" yaml:"-"` // optional.
}
// NZBGet is what you get in return for passing in a valid Config to New().
type NZBGet struct {
client *client
url string
}
type client struct {
Auth string
*http.Client
}
func New(config *Config) *NZBGet {
// Set username and password if one's configured.
auth := config.User + ":" + config.Pass
if auth != ":" {
auth = "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
} else {
auth = ""
}
httpClient := config.Client
if httpClient == nil {
httpClient = &http.Client{}
}
return &NZBGet{
url: strings.TrimSuffix(strings.TrimSuffix(config.URL, "/"), "/jsonrpc") + "/jsonrpc",
client: &client{
Auth: auth,
Client: httpClient,
},
}
}
// GetInto is a helper method to make a JSON-RPC request and turn the response into structured data.
func (n *NZBGet) GetInto(ctx context.Context, method string, output interface{}, args ...interface{}) error {
message, err := json.EncodeClientRequest(method, args)
if err != nil {
return fmt.Errorf("encoding request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.url, bytes.NewBuffer(message))
if err != nil {
return fmt.Errorf("creating request: %w", err)
}
if n.client.Auth != "" {
req.Header.Set("Authorization", n.client.Auth)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
resp, err := n.client.Do(req)
if err != nil {
return fmt.Errorf("making request: %w", err)
}
defer resp.Body.Close()
if err := json.DecodeClientResponse(resp.Body, &output); err != nil {
return fmt.Errorf("parsing response: %w: %s", err, resp.Status)
}
return nil
}