Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
414 lines (392 loc) · 9.71 KB
/
Copy pathmain.go
File metadata and controls
414 lines (392 loc) · 9.71 KB
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
package main
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"path"
"strconv"
"strings"
rpc "github.com/hekmon/transmissionrpc"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
ClientKey = "rpcClient"
)
func getClient(vp *viper.Viper) *rpc.Client {
return vp.Get(ClientKey).(*rpc.Client)
}
func printTorrent(t *rpc.Torrent) {
fmt.Println(torrentToString(t))
}
func torrentToString(t *rpc.Torrent) string {
var id string
if t.ID != nil {
id = strconv.FormatInt(*t.ID, 10)
} else {
id = "-"
}
var progress string
if t.PercentDone != nil {
value := int(100 * *t.PercentDone)
if value == 100 {
progress = "OK!"
} else {
progress = fmt.Sprintf("%2d%%", value)
}
} else {
progress = "---"
}
var available string = "---"
if t.HaveValid != nil && t.HaveUnchecked != nil && t.DesiredAvailable != nil && t.LeftUntilDone != nil {
have := *t.HaveValid + *t.HaveUnchecked
avail := have + *t.DesiredAvailable
all := have + *t.LeftUntilDone
if av := 100 * avail / all; av == 100 {
available = "OK!"
} else {
available = fmt.Sprintf("%2d%%", av)
}
}
var status string
if t.Status != nil {
switch *t.Status {
case rpc.TorrentStatusStopped:
status = "||"
case rpc.TorrentStatusDownload, rpc.TorrentStatusDownloadWait,
rpc.TorrentStatusCheck, rpc.TorrentStatusCheckWait:
status = ">>"
case rpc.TorrentStatusSeed, rpc.TorrentStatusSeedWait:
status = "<<"
}
} else {
status = "--"
}
var name string
if t.Name != nil {
name = *t.Name
} else {
name = "-"
}
return fmt.Sprintf("[ %4s ][ %s ][ %s ][ %s ] %s", id, available, progress, status, name)
}
func argsToIDs(args []string) ([]int64, error) {
var ids []int64
for _, arg := range args {
id, err := strconv.ParseInt(arg, 10, 64)
if err != nil {
return nil, fmt.Errorf("fail to parse id=%s err=%w", arg, err)
}
ids = append(ids, id)
}
return ids, nil
}
func getLocation(vp *viper.Viper) (string, error) {
location := vp.GetString("location")
if len(location) == 0 {
return "", nil
}
if location[0] == '@' {
name := location[1:]
locations := vp.GetStringMapString("alias")
if len(locations) == 0 {
return "", errors.New("no alias information")
}
if alias, ok := locations[name]; ok {
return alias, nil
} else {
return "", fmt.Errorf("unknown location alias %s", name)
}
}
return location, nil
}
func NewAddCommand(vp *viper.Viper) *cobra.Command {
var detail bool
cmd := &cobra.Command{
Use: "add [FILE or URLS]",
Short: "Add torrent file or magnet link",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client := getClient(vp)
deleteTorrent := vp.GetBool("delete")
location, err := getLocation(vp)
if err != nil {
return err
}
for _, arg := range args {
var torrent *rpc.Torrent
var err error
if strings.HasPrefix(arg, "http") {
var pLocation *string
if len(location) > 0 {
pLocation = &location
}
torrent, err = client.TorrentAdd(&rpc.TorrentAddPayload{
Filename: &arg,
DownloadDir: pLocation,
})
} else {
if len(location) > 0 {
torrent, err = client.TorrentAddFileDownloadDir(arg, location)
} else {
torrent, err = client.TorrentAddFile(arg)
}
if err == nil && deleteTorrent {
if err := os.Remove(arg); err != nil {
return fmt.Errorf("fail to remove torrent file=%s err=%w", arg, err)
}
}
}
if err != nil {
return fmt.Errorf("fail to add torrent arg=%q err=%w", arg, err)
}
if detail {
printTorrent(torrent)
} else {
fmt.Println(*torrent.ID)
}
}
return nil
},
}
flags := cmd.Flags()
flags.BoolVar(&detail, "detail", false, "Show details of added torrent")
flags.Bool("delete", false, "Delete torrent file on successful addition")
vp.BindPFlag("delete", flags.Lookup("delete"))
return cmd
}
func NewListCommand(vp *viper.Viper) *cobra.Command {
var showJSON bool
cmd := &cobra.Command{
Use: "ls",
Short: "List current torrents",
RunE: func(cmd *cobra.Command, args []string) error {
client := getClient(vp)
ids, err := argsToIDs(args)
if err != nil {
return err
}
torrents, err := client.TorrentGetAllFor(ids)
if err != nil {
return fmt.Errorf("fail to get torrents err=%w", err)
}
if showJSON {
je := json.NewEncoder(os.Stdout)
je.SetIndent("", " ")
je.Encode(torrents)
} else {
for _, torrent := range torrents {
printTorrent(torrent)
}
}
return nil
},
}
flags := cmd.Flags()
flags.BoolVar(&showJSON, "json", false, "JSON Output")
return cmd
}
func NewStopCommand(vp *viper.Viper) *cobra.Command {
cmd := &cobra.Command{
Use: "stop",
Short: "Stop the torrents",
RunE: func(cmd *cobra.Command, args []string) error {
client := getClient(vp)
ids, err := argsToIDs(args)
if err != nil {
return err
}
return client.TorrentStopIDs(ids)
},
}
return cmd
}
func NewStartCommand(vp *viper.Viper) *cobra.Command {
cmd := &cobra.Command{
Use: "start",
Short: "Start the torrents",
RunE: func(cmd *cobra.Command, args []string) error {
client := getClient(vp)
ids, err := argsToIDs(args)
if err != nil {
return err
}
return client.TorrentStartIDs(ids)
},
}
return cmd
}
func NewMoveCommand(vp *viper.Viper) *cobra.Command {
cmd := &cobra.Command{
Use: "move",
Short: "Move download location to specified location",
RunE: func(cmd *cobra.Command, args []string) error {
client := getClient(vp)
ids, err := argsToIDs(args)
if err != nil {
return err
}
location, err := getLocation(vp)
if err != nil {
return err
}
for _, id := range ids {
err = client.TorrentSetLocation(id, location, true)
if err != nil {
return err
}
}
return nil
},
}
return cmd
}
func isDone(t *rpc.Torrent) bool {
if t.Status != nil && *t.Status == rpc.TorrentStatusStopped {
if t.LeftUntilDone != nil && *t.LeftUntilDone == 0 {
return true
}
}
return false
}
func NewRemoveCommand(vp *viper.Viper) *cobra.Command {
var delete bool
cmd := &cobra.Command{
Use: "remove [TORRENT IDs]",
Short: "Remove specified torrents or already finished and stopped torrents",
RunE: func(cmd *cobra.Command, args []string) error {
client := getClient(vp)
ids, err := argsToIDs(args)
if err != nil {
return err
}
if len(ids) == 0 {
torrents, err := client.TorrentGetAllFor(nil)
if err != nil {
return fmt.Errorf("fail to get torrents err=%w", err)
}
for _, t := range torrents {
if isDone(t) {
ids = append(ids, *t.ID)
}
}
}
if len(ids) > 0 {
if err := client.TorrentRemove(&rpc.TorrentRemovePayload{
IDs: ids,
DeleteLocalData: delete,
}); err != nil {
return err
}
}
for _, id := range ids {
fmt.Println(id)
}
return nil
},
}
flags := cmd.Flags()
flags.BoolVar(&delete, "delete", false, "Delete downloaded files")
return cmd
}
func main() {
vp := viper.New()
vp.SetEnvPrefix("TRANSMISSION")
vp.AutomaticEnv()
vp.SetConfigName("config")
vp.SetConfigType("yaml")
vp.AddConfigPath(os.ExpandEnv("$HOME/.tmc"))
root := &cobra.Command{
Use: os.Args[0],
Short: "Transmission Client (CUI)",
SilenceUsage: true,
}
flags := root.PersistentFlags()
flags.StringP("host", "s", "localhost", "Transmission server host")
flags.IntP("port", "p", 0, "Transmission server port")
flags.String("url", "", "Transmission RPC URL (optional)")
flags.StringP("user", "u", "", "Transmission user name")
flags.StringP("password", "w", "", "Transmission password")
flags.BoolP("https", "t", false, "Use TLS for connection")
flags.String("useragent", "TorrentCLI", "UserAgent name for HTTP Client")
flags.StringP("location", "l", "", "Location to put downloaded")
root.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
var config rpc.AdvancedConfig
host := vp.GetString("host")
user := vp.GetString("user")
pass := vp.GetString("password")
config.HTTPS = vp.GetBool("https")
config.Port = vp.GetUint16("port")
config.UserAgent = vp.GetString("useragent")
rpcUrl := vp.GetString("url")
if len(rpcUrl) > 0 {
urlObj, err := url.Parse(rpcUrl)
if err != nil {
return err
}
host = urlObj.Host
if info := urlObj.User; info != nil {
user = info.Username()
if p, ok := info.Password(); ok {
pass = p
}
}
config.HTTPS = urlObj.Scheme == "https"
if s := urlObj.Port(); len(s) > 0 {
v, err := strconv.ParseUint(s, 10, 16)
if err != nil {
return err
}
config.Port = uint16(v)
}
if uri := urlObj.RequestURI(); len(uri) > 0 {
config.RPCURI = uri
}
}
if config.HTTPS && config.Port == 0 {
config.Port = 443
}
if len(user) > 0 && len(pass) == 0 {
prompt := promptui.Prompt{
Label: "Password",
Mask: '*',
}
if result, err := prompt.Run(); err != nil {
return err
} else {
pass = result
}
}
client, err := rpc.New(host, user, pass, &config)
if err != nil {
return err
}
vp.Set(ClientKey, client)
return err
}
vp.MergeInConfig()
vp.BindPFlags(flags)
root.AddCommand(NewAddCommand(vp))
root.AddCommand(NewListCommand(vp))
root.AddCommand(NewStopCommand(vp))
root.AddCommand(NewStartCommand(vp))
root.AddCommand(NewMoveCommand(vp))
root.AddCommand(NewRemoveCommand(vp))
root.AddCommand(&cobra.Command{
Use: "save",
Short: "Save current configuration",
RunE: func(cmd *cobra.Command, args []string) error {
file := os.ExpandEnv("$HOME/.tmc/config.yml")
dir := path.Dir(file)
if err := os.MkdirAll(dir, 0700); err != nil {
return err
}
fmt.Fprintln(os.Stderr, "Save configuration to", file)
return vp.WriteConfigAs(file)
},
})
root.Execute()
}