forked from lnguyen/go-transmission
-
Notifications
You must be signed in to change notification settings - Fork 7
/
client.go
87 lines (77 loc) · 1.8 KB
/
client.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
package transmission
import (
"io/ioutil"
"net/http"
"strings"
)
type ApiClient struct {
url string
username string
password string
token string
client http.Client
}
func NewClient(url string,
username string, password string) ApiClient {
ac := ApiClient{url: url + "/transmission/rpc", username: username, password: password}
return ac
}
func (ac *ApiClient) CreateClient(apiToken string) {
ac.client = http.Client{}
}
func (ac *ApiClient) Post(body string) ([]byte, error) {
authRequest, err := ac.authRequest("POST", body)
if err != nil {
return make([]byte, 0), err
}
res, err := ac.client.Do(authRequest)
if err != nil {
return make([]byte, 0), err
}
defer res.Body.Close()
if res.StatusCode == 409 {
ac.getToken()
authRequest, err := ac.authRequest("POST", body)
if err != nil {
return make([]byte, 0), err
}
res, err = ac.client.Do(authRequest)
if err != nil {
return make([]byte, 0), err
}
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return make([]byte, 0), err
}
return resBody, nil
}
func (ac *ApiClient) getToken() error {
req, err := http.NewRequest("POST", ac.url, strings.NewReader(""))
if err != nil {
return err
}
req.SetBasicAuth(ac.username, ac.password)
res, err := ac.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
ac.token = res.Header.Get("X-Transmission-Session-Id")
return nil
}
func (ac *ApiClient) authRequest(method string, body string) (*http.Request, error) {
if ac.token == "" {
err := ac.getToken()
if err != nil {
return &http.Request{}, err
}
}
req, err := http.NewRequest(method, ac.url, strings.NewReader(body))
if err != nil {
return &http.Request{}, err
}
req.Header.Add("X-Transmission-Session-Id", ac.token)
req.SetBasicAuth(ac.username, ac.password)
return req, nil
}