forked from Tubbebubbe/transmission
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtransmission.go
548 lines (467 loc) · 13.4 KB
/
transmission.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package transmission
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"time"
)
const (
StatusStopped = iota
StatusCheckPending
StatusChecking
StatusDownloadPending
StatusDownloading
StatusSeedPending
StatusSeeding
)
// TransmissionClient to talk to transmission
type TransmissionClient struct {
apiclient *ApiClient
}
type Command struct {
Method string `json:"method,omitempty"`
Arguments arguments `json:"arguments,omitempty"`
Result string `json:"result,omitempty"`
}
type arguments struct {
Fields []string `json:"fields,omitempty"`
Torrents Torrents `json:"torrents,omitempty"`
Ids []int `json:"ids,omitempty"`
DeleteData bool `json:"delete-local-data,omitempty"`
DownloadDir string `json:"download-dir,omitempty"`
MetaInfo string `json:"metainfo,omitempty"`
Filename string `json:"filename,omitempty"`
TorrentAdded TorrentAdded `json:"torrent-added"`
SpeedLimitDown uint `json:"speed-limit-down,omitempty"`
SpeedLimitUp uint `json:"speed-limit-up,omitempty"`
// Stats
ActiveTorrentCount int `json:"activeTorrentCount"`
CumulativeStats cumulativeStats `json:"cumulative-stats"`
CurrentStats currentStats `json:"current-stats"`
DownloadSpeed uint64 `json:"downloadSpeed"`
PausedTorrentCount int `json:"pausedTorrentCount"`
TorrentCount int `json:"torrentCount"`
UploadSpeed uint64 `json:"uploadSpeed"`
Version string `json:"version"`
}
type tracker struct {
Announce string `json:"announce"`
Id int `json:"id"`
Scrape string `json:"scrape"`
Tire int `json:"tire"`
}
// TorrentAdded data returning
type TorrentAdded struct {
HashString string `json:"hashString"`
ID int `json:"id"`
Name string `json:"name"`
}
// session-stats
type Stats struct {
ActiveTorrentCount int
CumulativeStats cumulativeStats
CurrentStats currentStats
DownloadSpeed uint64
PausedTorrentCount int
TorrentCount int
UploadSpeed uint64
}
type cumulativeStats struct {
DownloadedBytes uint64 `json:"downloadedBytes"`
FilesAdded int `json:"filesAdded"`
SecondsActive time.Duration `json:"secondsActive"`
SessionCount int `json:"sessionCount"`
UploadedBytes uint64 `json:"uploadedBytes"`
}
type currentStats struct {
DownloadedBytes uint64 `json:"downloadedBytes"`
FilesAdded int `json:"filesAdded"`
SecondsActive time.Duration `json:"secondsActive"`
SessionCount int `json:"sessionCount"`
UploadedBytes uint64 `json:"uploadedBytes"`
}
func (s *Stats) CurrentActiveTime() string {
return (time.Second * s.CurrentStats.SecondsActive).String()
}
func (s *Stats) CumulativeActiveTime() string {
return (time.Second * s.CumulativeStats.SecondsActive).String()
}
// Torrent struct for torrents
type Torrent struct {
ID int `json:"id"`
Name string `json:"name"`
Status int `json:"status"`
AddedDate int64 `json:"addedDate"`
LeftUntilDone uint64 `json:"leftUntilDone"`
SizeWhenDone uint64 `json:"sizeWhenDone"`
Eta time.Duration `json:"eta"`
UploadRatio float64 `json:"uploadRatio"`
RateDownload uint64 `json:"rateDownload"`
RateUpload uint64 `json:"rateUpload"`
DownloadDir string `json:"downloadDir"`
DownloadedEver uint64 `json:"downloadedEver"`
UploadedEver uint64 `json:"uploadedEver"`
HashString string `json:"hashString"`
HaveUnchecked uint64 `json:"haveUnchecked"`
HaveValid uint64 `json:"haveValid"`
IsFinished bool `json:"isFinished"`
PercentDone float64 `json:"percentDone"`
SeedRatioMode int `json:"seedRatioMode"`
Trackers []tracker `json:"trackers"`
Error int `json:"error"`
ErrorString string `json:"errorString"`
}
// Status translates the status of the torrent
func (t *Torrent) TorrentStatus() string {
switch t.Status {
case StatusStopped:
return "Stopped"
case StatusCheckPending:
return "Check waiting"
case StatusChecking:
return "Checking"
case StatusDownloadPending:
return "Download waiting"
case StatusDownloading:
return "Downloading"
case StatusSeedPending:
return "Seed waiting"
case StatusSeeding:
return "Seeding"
default:
return "unknown"
}
}
// Ratio returns the upload ratio of the torrent
func (t *Torrent) Ratio() string {
if t.UploadRatio < 0 {
return "∞"
}
return fmt.Sprintf("%.3f", t.UploadRatio)
}
// ETA returns the time left for the download to finish
func (t *Torrent) ETA() string {
if t.Eta < 0 {
return "∞"
}
return (time.Second * t.Eta).String()
}
// GetTrackers combines the torrent's trackers in one string
func (t *Torrent) GetTrackers() string {
buf := new(bytes.Buffer)
for i := range t.Trackers {
buf.WriteString(fmt.Sprintf("%s\n", t.Trackers[i].Announce))
}
return buf.String()
}
// Have returns haveValid + haveUnchecked
func (t *Torrent) Have() uint64 {
return t.HaveValid + t.HaveUnchecked
}
// Torrents represent []Torrent
type Torrents []*Torrent
// GetIDs returns []int of all the ids
func (t Torrents) GetIDs() []int {
ids := make([]int, 0, len(t))
for i := range t {
ids = append(ids, t[i].ID)
}
return ids
}
// sortType keeps track of which sorting we are using
var sortType = SortID // SortID is transmission's default
// SetSort takes a 'Sorting' to set 'sortType'
func (ac *TransmissionClient) SetSort(st Sorting) {
sortType = st
}
// New create new transmission torrent
func New(url string, username string, password string) (*TransmissionClient, error) {
apiclient := NewClient(url, username, password)
client := &TransmissionClient{apiclient: apiclient}
// test that we have a working client
cmd := Command{Method: "session-get"}
_, err := client.sendCommand(cmd)
if err != nil {
return client, err
}
return client, nil
}
// GetTorrents get a list of torrents
func (ac *TransmissionClient) GetTorrents() (Torrents, error) {
cmd := NewGetTorrentsCmd()
out, err := ac.ExecuteCommand(cmd)
if err != nil {
return nil, err
}
torrents := out.Arguments.Torrents
// sorting
switch sortType {
case SortID:
return torrents, nil // already sorted by ID
case SortRevID:
torrents.SortID(true)
case SortName:
torrents.SortName(false)
case SortRevName:
torrents.SortName(true)
case SortAge:
torrents.SortAge(false)
case SortRevAge:
torrents.SortAge(true)
case SortSize:
torrents.SortSize(false)
case SortRevSize:
torrents.SortSize(true)
case SortProgress:
torrents.SortProgress(false)
case SortRevProgress:
torrents.SortProgress(true)
case SortDownSpeed:
torrents.SortDownSpeed(false)
case SortRevDownSpeed:
torrents.SortDownSpeed(true)
case SortUpSpeed:
torrents.SortUpSpeed(false)
case SortRevUpSpeed:
torrents.SortUpSpeed(true)
case SortDownloaded:
torrents.SortDownloaded(false)
case SortRevDownloaded:
torrents.SortDownloaded(true)
case SortUploaded:
torrents.SortUploaded(false)
case SortRevUploaded:
torrents.SortUploaded(true)
case SortRatio:
torrents.SortRatio(false)
case SortRevRatio:
torrents.SortRatio(true)
}
return torrents, nil
}
// GetTorrent takes an id and returns *Torrent
func (ac *TransmissionClient) GetTorrent(id int) (*Torrent, error) {
cmd := NewGetTorrentsCmd()
cmd.Arguments.Ids = append(cmd.Arguments.Ids, id)
out, err := ac.ExecuteCommand(cmd)
if err != nil {
return &Torrent{}, err
}
if len(out.Arguments.Torrents) > 0 {
return out.Arguments.Torrents[0], nil
}
return &Torrent{}, errors.New("No torrent with that id")
}
// Delete takes a bool, if true it will delete with data;
// returns the name of the deleted torrent if it succeed
func (ac *TransmissionClient) DeleteTorrent(id int, wd bool) (string, error) {
torrent, err := ac.GetTorrent(id)
if err != nil {
return "", err
}
cmd := newDelCmd(id, wd)
_, err = ac.ExecuteCommand(cmd)
if err != nil {
return "", err
}
return torrent.Name, nil
}
// GetStats returns "session-stats"
func (ac *TransmissionClient) GetStats() (*Stats, error) {
cmd := &Command{
Method: "session-stats",
}
out, err := ac.ExecuteCommand(cmd)
if err != nil {
return nil, err
}
return &Stats{
ActiveTorrentCount: out.Arguments.ActiveTorrentCount,
CumulativeStats: out.Arguments.CumulativeStats,
CurrentStats: out.Arguments.CurrentStats,
DownloadSpeed: out.Arguments.DownloadSpeed,
PausedTorrentCount: out.Arguments.PausedTorrentCount,
TorrentCount: out.Arguments.TorrentCount,
UploadSpeed: out.Arguments.UploadSpeed,
}, nil
}
// StartTorrent start the torrent
func (ac *TransmissionClient) StartTorrent(id int) (string, error) {
return ac.sendSimpleCommand("torrent-start", id)
}
// StopTorrent start the torrent
func (ac *TransmissionClient) StopTorrent(id int) (string, error) {
return ac.sendSimpleCommand("torrent-stop", id)
}
// VerifyTorrent verifies a torrent
func (ac *TransmissionClient) VerifyTorrent(id int) (string, error) {
return ac.sendSimpleCommand("torrent-verify", id)
}
// StartAll starts all the torrents
func (ac *TransmissionClient) StartAll() error {
cmd := Command{Method: "torrent-start"}
torrents, err := ac.GetTorrents()
if err != nil {
return err
}
cmd.Arguments.Ids = torrents.GetIDs()
if _, err := ac.sendCommand(cmd); err != nil {
return err
}
return nil
}
// StopAll stops all torrents
func (ac *TransmissionClient) StopAll() error {
cmd := Command{Method: "torrent-stop"}
torrents, err := ac.GetTorrents()
if err != nil {
return err
}
cmd.Arguments.Ids = torrents.GetIDs()
if _, err := ac.sendCommand(cmd); err != nil {
return err
}
return nil
}
// VerifyAll verfies all torrents
func (ac *TransmissionClient) VerifyAll() error {
cmd := Command{Method: "torrent-verify"}
torrents, err := ac.GetTorrents()
if err != nil {
return err
}
cmd.Arguments.Ids = torrents.GetIDs()
if _, err := ac.sendCommand(cmd); err != nil {
return err
}
return nil
}
func NewGetTorrentsCmd() *Command {
cmd := &Command{}
cmd.Method = "torrent-get"
cmd.Arguments.Fields = []string{"id", "name",
"status", "addedDate", "leftUntilDone", "sizeWhenDone", "eta", "uploadRatio", "uploadedEver",
"rateDownload", "rateUpload", "downloadDir", "hashString", "haveValid", "haveUnchecked", "isFinished", "downloadedEver",
"percentDone", "seedRatioMode", "error", "errorString", "trackers"}
return cmd
}
func NewAddCmd() *Command {
cmd := &Command{}
cmd.Method = "torrent-add"
return cmd
}
// URL or magnet
func NewAddCmdByURL(url string) *Command {
cmd := NewAddCmd()
cmd.Arguments.Filename = url
return cmd
}
func NewAddCmdByFilename(filename string) *Command {
cmd := NewAddCmd()
cmd.Arguments.Filename = filename
return cmd
}
func NewAddCmdByFile(file string) (*Command, error) {
cmd := NewAddCmd()
fileData, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
cmd.Arguments.MetaInfo = base64.StdEncoding.EncodeToString(fileData)
return cmd, nil
}
func NewSessionSetCommand() *Command {
cmd := &Command{}
cmd.Method = "session-set"
return cmd
}
func (cmd *Command) SetDownloadDir(dir string) {
cmd.Arguments.DownloadDir = dir
}
type SpeedLimitType string
const (
DownloadLimitType = "downloadlimit"
UploadLimitType = "uploadlimit"
)
// newSpeedLimitCommand creates a new command that mutates either a download or upload limit.
func NewSpeedLimitCommand(limitType SpeedLimitType, limit uint) *Command {
cmd := &Command{}
cmd.Method = "session-set"
switch limitType {
case DownloadLimitType:
cmd.Arguments.SpeedLimitDown = limit
case UploadLimitType:
cmd.Arguments.SpeedLimitUp = limit
default:
return nil
}
return cmd
}
func newDelCmd(id int, removeFile bool) *Command {
cmd := &Command{}
cmd.Method = "torrent-remove"
cmd.Arguments.Ids = []int{id}
cmd.Arguments.DeleteData = removeFile
return cmd
}
func (ac *TransmissionClient) ExecuteCommand(cmd *Command) (*Command, error) {
out := &Command{}
body, err := json.Marshal(cmd)
if err != nil {
return out, err
}
output, err := ac.apiclient.Post(string(body))
if err != nil {
return out, err
}
err = json.Unmarshal(output, &out)
if err != nil {
return out, err
}
return out, nil
}
func (ac *TransmissionClient) ExecuteAddCommand(addCmd *Command) (TorrentAdded, error) {
outCmd, err := ac.ExecuteCommand(addCmd)
if err != nil {
return TorrentAdded{}, err
}
return outCmd.Arguments.TorrentAdded, nil
}
func encodeFile(file string) (string, error) {
fileData, err := ioutil.ReadFile(file)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(fileData), nil
}
// Version returns transmission's version
func (ac *TransmissionClient) Version() string {
cmd := Command{Method: "session-get"}
resp, _ := ac.sendCommand(cmd)
return resp.Arguments.Version
}
func (ac *TransmissionClient) sendSimpleCommand(method string, id int) (result string, err error) {
cmd := Command{Method: method}
cmd.Arguments.Ids = []int{id}
resp, err := ac.sendCommand(cmd)
return resp.Result, err
}
func (ac *TransmissionClient) sendCommand(cmd Command) (response Command, err error) {
var body, output []byte
body, err = json.Marshal(cmd)
if err != nil {
return
}
output, err = ac.apiclient.Post(string(body))
if err != nil {
return
}
err = json.Unmarshal(output, &response)
if err != nil {
return
}
return response, nil
}