-
Notifications
You must be signed in to change notification settings - Fork 0
/
delugeclient.go
311 lines (273 loc) · 7.53 KB
/
delugeclient.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package delugeclient
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"golang.org/x/net/publicsuffix"
"log"
"net/http"
"net/http/cookiejar"
"os"
"reflect"
)
type Deluge struct {
ServiceUrl string
Password string
Index int
HttpClient http.Client
}
type RpcError struct {
Message string `json:"message"`
Code int `json:"code"`
}
type RpcResponse struct {
Id int `json:"id"`
Result bool `json:"result"`
Error RpcError `json:"error"`
}
type RpcResponseComplex struct {
Id int `json:"id"`
Result [][]interface{} `json:"result"`
Error RpcError `json:"error"`
}
type ResponseEntry struct {
HasValue bool
Value string
}
func (r RpcResponseComplex) result(index int) ResponseEntry {
return ResponseEntry{
HasValue: reflect.ValueOf(r.Result[index][0]).Bool(),
Value: reflect.ValueOf(r.Result[index][1]).String(),
}
}
func (r RpcResponse) String() string {
return fmt.Sprintf("id: '%d' result: '%v' error: {%s}", r.Id, r.Result, r.Error)
}
func (e RpcError) String() string {
return fmt.Sprintf("code: '%d' message: '%s'", e.Code, e.Message)
}
type Torrent struct {
Id string
Name string
Progress float64
ShareRatio float64
Files []string
}
func (t *Torrent) String() string {
return fmt.Sprintf("id=%s name=%s ratio=%f files=%s", t.Id, t.Name, t.ShareRatio, t.Files)
}
type TorrentEntry struct {
Message string `json:"message"`
Progress float64 `json:"progress"`
Ratio float64 `json:"ratio"`
Name string `json:"name"`
}
type TorrentSet struct {
Map map[string]TorrentEntry `json:"torrents"`
}
type AllResponse struct {
Index int `json:"id"`
Torrents TorrentSet `json:"result"`
Error RpcError `json:"error"`
}
// NewDeluge initializes the client
func NewDeluge(serverUrl, password string) *Deluge {
if len(serverUrl) == 0 {
panic("serverUrl cannot be empty")
}
if len(password) == 0 {
panic("password cannot be empty")
}
log.SetOutput(os.Stdout)
options := cookiejar.Options{
PublicSuffixList: publicsuffix.List,
}
cookieJar, err := cookiejar.New(&options)
if err != nil {
log.Fatal(err)
}
config := &tls.Config{InsecureSkipVerify: true}
tr := &http.Transport{TLSClientConfig: config}
return &Deluge{
ServiceUrl: serverUrl + "/json",
Password: password,
Index: 1,
HttpClient: http.Client{Jar: cookieJar, Transport: tr},
}
}
// Connect establishes a connection to the server
func (d *Deluge) Connect() error {
var payload = fmt.Sprintf(
`{"id":%d, "method":"auth.login", "params":["%s"]}`,
d.Index, d.Password)
var rr RpcResponse
err := sendRequest(d.HttpClient, d.ServiceUrl, payload, &rr)
if err != nil {
return err
}
if !rr.Result {
return fmt.Errorf("error code %d! %s", rr.Error.Code, rr.Error.Message)
}
d.Index++
return nil
}
// AddMagnet adds a magnet/torrent link
func (d *Deluge) AddMagnet(magnet string) error {
var payload = fmt.Sprintf(
`{"id":%d, "method":"web.add_torrents", "params":[[{"path":"%s", "options":""}]]}`,
d.Index, magnet)
var rr RpcResponseComplex
err := sendRequest(d.HttpClient, d.ServiceUrl, payload, &rr)
if err != nil {
return err
}
if rr.Error.Code > 0 {
log.Println(rr)
return fmt.Errorf("error code %d! %s", rr.Error.Code, rr.Error.Message)
}
d.Index++
return nil
}
// MoveToQueueTop moves a torrent to the queue top
func (d *Deluge) MoveToQueueTop(torrentId string) error {
var payload = fmt.Sprintf(
`{"id":%d, "method":"core.queue_top", "params":[["%s"]]}`,
d.Index, torrentId)
var rr RpcResponse
err := sendRequest(d.HttpClient, d.ServiceUrl, payload, &rr)
if err != nil {
return err
}
if rr.Error.Code > 0 {
log.Println(rr)
return fmt.Errorf("error code %d! %s", rr.Error.Code, rr.Error.Message)
}
d.Index++
return nil
}
type TorrentResult struct {
Type string `json:"type"`
Contents map[string]TorrentDetail `json:"contents"`
}
type TorrentContent struct {
Index int `json:"id"`
TorrentResult TorrentResult `json:"result"`
Error RpcError `json:"error"`
}
type TorrentDetail struct {
Priority int64 `json:"priority"`
Path string `json:"path"`
Type string `json:"type"`
ShareRatio float64 `json:"ratio"`
Progress float64 `json:"progress"`
TorrentEntryMap map[string]TorrentDetail `json:"contents"`
}
type Detail struct {
Path string `json:"path"`
}
// Get the link details about a single link given its hash id (torrentId)
func (d *Deluge) Get(torrentId string) (*Torrent, error) {
var payload = fmt.Sprintf(
`{"id":%d, "method":"web.get_torrent_files", "params":["%s"]}`,
d.Index, torrentId)
var rr TorrentContent
err := sendRequest(d.HttpClient, d.ServiceUrl, payload, &rr)
if err != nil {
return nil, err
}
if rr.Error.Code > 0 {
return nil, fmt.Errorf("error code %d! %s", rr.Error.Code, rr.Error.Message)
}
if rr.TorrentResult.Type != "dir" {
return nil, nil
}
if len(rr.TorrentResult.Contents) == 0 {
return &Torrent{
Id: torrentId,
Files: make([]string, 0),
ShareRatio: 0,
}, nil
}
for k, v := range rr.TorrentResult.Contents {
contents := rr.TorrentResult.Contents[k]
if len(contents.TorrentEntryMap) == 0 {
files := make([]string, 0, 1)
return &Torrent{
Id: torrentId,
Name: contents.Path,
Files: append(files, contents.Path),
ShareRatio: contents.ShareRatio,
}, nil
}
files := make([]string, 0, len(contents.TorrentEntryMap))
for x, y := range contents.TorrentEntryMap {
if y.Type == "file" {
//fmt.Println("type: ", y.Type, " key: ", x)
files = append(files, x)
}
}
d.Index++
return &Torrent{
Id: torrentId,
Name: v.Path,
Files: files,
ShareRatio: v.ShareRatio,
Progress: v.Progress,
}, nil
}
return nil, nil
}
// GetAll gets the link details off all entries
func (d *Deluge) GetAll() ([]Torrent, error) {
var payload = fmt.Sprintf(
`{"id":%d, "method":"web.update_ui", "params":[["name", "ratio", "message", "progress"],{}]}`,
d.Index)
var rr AllResponse
err := sendRequest(d.HttpClient, d.ServiceUrl, payload, &rr)
if err != nil {
return nil, err
}
if rr.Error.Code > 0 {
log.Println(rr)
return nil, fmt.Errorf("error code %d! %s", rr.Error.Code, rr.Error.Message)
}
torrents := make([]Torrent, 0, len(rr.Torrents.Map))
for k, v := range rr.Torrents.Map {
torrents = append(torrents, Torrent{Id: k, Name: v.Name, ShareRatio: v.Ratio, Progress: v.Progress})
}
d.Index++
return torrents, nil
}
// Remove removes a link given its hash id (torrentId)
func (d *Deluge) Remove(torrentId string) error {
var payload = fmt.Sprintf(
`{"id":%d, "method":"core.remove_torrent", "params":["%s",true]}`,
d.Index, torrentId)
var rr RpcResponse
err := sendRequest(d.HttpClient, d.ServiceUrl, payload, &rr)
if err != nil {
return err
}
if rr.Error.Code > 0 {
log.Println(rr)
return fmt.Errorf("error code %d! %s", rr.Error.Code, rr.Error.Message)
}
d.Index++
return nil
}
func sendRequest(httpClient http.Client, url, payload string, decoder interface{}) error {
response, err := httpClient.Post(url, "application/json", bytes.NewBufferString(payload))
if err != nil {
return fmt.Errorf("connection error. %s", err)
}
defer response.Body.Close()
if response.StatusCode != 200 {
return fmt.Errorf("server error response: %s", response.Status)
}
if err := json.NewDecoder(response.Body).Decode(&decoder); err != nil {
return errors.New("unable to parse response body")
}
return nil
}