This repository was archived by the owner on Sep 21, 2023. It is now read-only.
forked from pyed/transmission-telegram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
1492 lines (1244 loc) · 40.9 KB
/
main.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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"flag"
"fmt"
"log"
"os"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/dustin/go-humanize"
"github.com/pyed/tailer"
"github.com/pyed/transmission"
"gopkg.in/telegram-bot-api.v4"
)
const (
VERSION = "v1.4.1"
HELP = `
*list* or *li* or *ls*
Lists all the torrents, takes an optional argument which is a query to list only torrents that has a tracker matches the query, or some of it.
*head* or *he*
Lists the first n number of torrents, n defaults to 5 if no argument is provided.
*tail* or *ta*
Lists the last n number of torrents, n defaults to 5 if no argument is provided.
*down* or *dl*
Lists torrents with the status of _Downloading_ or in the queue to download.
*seeding* or *sd*
Lists torrents with the status of _Seeding_ or in the queue to seed.
*paused* or *pa*
Lists _Paused_ torrents.
*checking* or *ch*
Lists torrents with the status of _Verifying_ or in the queue to verify.
*active* or *ac*
Lists torrents that are actively uploading or downloading.
*errors* or *er*
Lists torrents with with errors along with the error message.
*sort* or *so*
Manipulate the sorting of the aforementioned commands. Call it without arguments for more.
*trackers* or *tr*
Lists all the trackers along with the number of torrents.
*add* or *ad*
Takes one or many URLs or magnets to add them. You can send a ".torrent" file via Telegram to add it.
*search* or *se*
Takes a query and lists torrents with matching names.
*latest* or *la*
Lists the newest n torrents, n defaults to 5 if no argument is provided.
*info* or *in*
Takes one or more torrent's IDs to list more info about them.
*stop* or *sp*
Takes one or more torrent's IDs to stop them, or _all_ to stop all torrents.
*start* or *st*
Takes one or more torrent's IDs to start them, or _all_ to start all torrents.
*check* or *ck*
Takes one or more torrent's IDs to verify them, or _all_ to verify all torrents.
*del* or *rm*
Takes one or more torrent's IDs to delete them.
*deldata*
Takes one or more torrent's IDs to delete them and their data.
*stats* or *sa*
Shows Transmission's stats.
*speed* or *ss*
Shows the upload and download speeds.
*count* or *co*
Shows the torrents counts per status.
*help*
Shows this help message.
*version* or *ver*
Shows version numbers.
- Prefix commands with '/' if you want to talk to your bot in a group.
- report any issues [here](https://github.com/pyed/transmission-telegram)
`
)
var (
// flags
BotToken string
Masters masterSlice
RPCURL string
Username string
Password string
LogFile string
TransLogFile string // Transmission log file
NoLive bool
// transmission
Client *transmission.TransmissionClient
// telegram
Bot *tgbotapi.BotAPI
Updates <-chan tgbotapi.Update
// chatID will be used to keep track of which chat to send completion notifictions.
chatID int64
// logging
logger = log.New(os.Stdout, "", log.LstdFlags)
// interval in seconds for live updates, affects: "active", "info", "speed", "head", "tail"
interval time.Duration = 5
// duration controls how many intervals will happen
duration = 10
// since telegram's markdown can't be escaped, we have to replace some chars
// affects only markdown users: info, active, head, tail
mdReplacer = strings.NewReplacer("*", "•",
"[", "(",
"]", ")",
"_", "-",
"`", "'")
)
// we need a type for masters for the flag package to parse them as a slice
type masterSlice []string
// String is mandatory functions for the flag package
func (masters *masterSlice) String() string {
return fmt.Sprintf("%s", *masters)
}
// Set is mandatory functions for the flag package
func (masters *masterSlice) Set(master string) error {
*masters = append(*masters, strings.ToLower(master))
return nil
}
// Contains takes a string and return true of masterSlice has it
func (masters masterSlice) Contains(master string) bool {
master = strings.ToLower(master)
for i := range masters {
if masters[i] == master {
return true
}
}
return false
}
// init flags
func init() {
// define arguments and parse them.
flag.StringVar(&BotToken, "token", "", "Telegram bot token, Can be passed via environment variable 'TT_BOTT'")
flag.Var(&Masters, "master", "Your telegram handler, So the bot will only respond to you. Can specify more than one")
flag.StringVar(&RPCURL, "url", "http://localhost:9091/transmission/rpc", "Transmission RPC URL")
flag.StringVar(&Username, "username", "", "Transmission username")
flag.StringVar(&Password, "password", "", "Transmission password")
flag.StringVar(&LogFile, "logfile", "", "Send logs to a file")
flag.StringVar(&TransLogFile, "transmission-logfile", "", "Open transmission logfile to monitor torrents completion")
flag.BoolVar(&NoLive, "no-live", false, "Don't edit and update info after sending")
// set the usage message
flag.Usage = func() {
fmt.Fprint(os.Stderr, "Usage: transmission-telegram <-token=TOKEN> <-master=@tuser> [-master=@yuser2] [-url=http://] [-username=user] [-password=pass]\n\n")
flag.PrintDefaults()
}
flag.Parse()
// if we don't have BotToken passed, check the environment variable "TT_BOTT"
if BotToken == "" {
if token := os.Getenv("TT_BOTT"); len(token) > 1 {
BotToken = token
}
}
// make sure that we have the two madatory arguments: telegram token & master's handler.
if BotToken == "" ||
len(Masters) < 1 {
fmt.Fprintf(os.Stderr, "Error: Mandatory argument missing! (-token or -master)\n\n")
flag.Usage()
os.Exit(1)
}
// make sure that the handler doesn't contain @
for i := range Masters {
Masters[i] = strings.Replace(Masters[i], "@", "", -1)
}
// if we got a log file, log to it
if LogFile != "" {
logf, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
logger.SetOutput(logf)
}
// if we got a transmission log file, monitor it for torrents completion to notify upon them.
if TransLogFile != "" {
go func() {
ft := tailer.RunFileTailer(TransLogFile, false, nil)
// [2017-02-22 21:00:00.898] File-Name State changed from "Incomplete" to "Complete" (torrent.c:2218)
const (
substring = `"Incomplete" to "Complete"`
start = len(`[2017-02-22 21:00:00.898] `)
end = len(` State changed from "Incomplete" to "Complete" (torrent.c:2218)`)
)
for {
select {
case line := <-ft.Lines():
if strings.Contains(line, substring) {
// if we don't have a chatID continue
if chatID == 0 {
continue
}
msg := fmt.Sprintf("Completed: %s", line[start:len(line)-end])
send(msg, chatID, false)
}
case err := <-ft.Errors():
logger.Printf("[ERROR] tailing transmission log: %s", err)
return
}
}
}()
}
// if the `-username` flag isn't set, look into the environment variable 'TR_AUTH'
if Username == "" {
if values := strings.Split(os.Getenv("TR_AUTH"), ":"); len(values) > 1 {
Username, Password = values[0], values[1]
}
}
// log the flags
logger.Printf("[INFO] Token=%s\n\t\tMasters=%s\n\t\tURL=%s\n\t\tUSER=%s\n\t\tPASS=%s",
BotToken, Masters, RPCURL, Username, Password)
}
// init transmission
func init() {
var err error
Client, err = transmission.New(RPCURL, Username, Password)
if err != nil {
fmt.Fprintf(os.Stderr, "[ERROR] Transmission: Make sure you have the right URL, Username and Password\n")
os.Exit(1)
}
}
// init telegram
func init() {
// authorize using the token
var err error
Bot, err = tgbotapi.NewBotAPI(BotToken)
if err != nil {
fmt.Fprintf(os.Stderr, "[ERROR] Telegram: %s\n", err)
os.Exit(1)
}
logger.Printf("[INFO] Authorized: %s", Bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
Updates, err = Bot.GetUpdatesChan(u)
if err != nil {
fmt.Fprintf(os.Stderr, "[ERROR] Telegram: %s\n", err)
os.Exit(1)
}
}
func main() {
for update := range Updates {
// ignore edited messages
if update.Message == nil {
continue
}
// ignore non masters
if !Masters.Contains(update.Message.From.UserName) {
logger.Printf("[INFO] Ignored a message from: %s", update.Message.From.String())
continue
}
// update chatID for complete notification
if TransLogFile != "" && chatID != update.Message.Chat.ID {
chatID = update.Message.Chat.ID
}
// tokenize the update
tokens := strings.Split(update.Message.Text, " ")
// preprocess message based on URL schema
// in case those were added from the mobile via "Share..." option
// when it is not possible to easily prepend it with "add" command
if strings.HasPrefix(tokens[0], "magnet") || strings.HasPrefix(tokens[0], "http") {
tokens = append([]string{"add"}, tokens...)
}
command := strings.ToLower(tokens[0])
switch command {
case "list", "/list", "li", "/li", "/ls", "ls":
go list(update, tokens[1:])
case "head", "/head", "he", "/he":
go head(update, tokens[1:])
case "tail", "/tail", "ta", "/ta":
go tail(update, tokens[1:])
case "downs", "/downs", "dl", "/dl":
go downs(update)
case "seeding", "/seeding", "sd", "/sd":
go seeding(update)
case "paused", "/paused", "pa", "/pa":
go paused(update)
case "checking", "/checking", "ch", "/ch":
go checking(update)
case "active", "/active", "ac", "/ac":
go active(update)
case "errors", "/errors", "er", "/er":
go errors(update)
case "sort", "/sort", "so", "/so":
go sort(update, tokens[1:])
case "trackers", "/trackers", "tr", "/tr":
go trackers(update)
case "add", "/add", "ad", "/ad":
go add(update, tokens[1:])
case "search", "/search", "se", "/se":
go search(update, tokens[1:])
case "latest", "/latest", "la", "/la":
go latest(update, tokens[1:])
case "info", "/info", "in", "/in":
go info(update, tokens[1:])
case "stop", "/stop", "sp", "/sp":
go stop(update, tokens[1:])
case "start", "/start", "st", "/st":
go start(update, tokens[1:])
case "check", "/check", "ck", "/ck":
go check(update, tokens[1:])
case "stats", "/stats", "sa", "/sa":
go stats(update)
case "speed", "/speed", "ss", "/ss":
go speed(update)
case "count", "/count", "co", "/co":
go count(update)
case "del", "/del", "rm", "/rm":
go del(update, tokens[1:])
case "deldata", "/deldata":
go deldata(update, tokens[1:])
case "help", "/help":
go send(HELP, update.Message.Chat.ID, true)
case "version", "/version", "ver", "/ver":
go getVersion(update)
case "":
// might be a file received
go receiveTorrent(update)
default:
// no such command, try help
go send("No such command, try /help", update.Message.Chat.ID, false)
}
}
}
// list will form and send a list of all the torrents
// takes an optional argument which is a query to match against trackers
// to list only torrents that has a tracker that matchs.
func list(ud tgbotapi.Update, tokens []string) {
torrents, err := Client.GetTorrents()
if err != nil {
send("*list:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
buf := new(bytes.Buffer)
// if it gets a query, it will list torrents that has trackers that match the query
if len(tokens) != 0 {
// (?i) for case insensitivity
regx, err := regexp.Compile("(?i)" + tokens[0])
if err != nil {
send("*list:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
for i := range torrents {
if regx.MatchString(torrents[i].GetTrackers()) {
buf.WriteString(fmt.Sprintf("<%d> %s\n", torrents[i].ID, torrents[i].Name))
}
}
} else { // if we did not get a query, list all torrents
for i := range torrents {
buf.WriteString(fmt.Sprintf("<%d> %s\n", torrents[i].ID, torrents[i].Name))
}
}
if buf.Len() == 0 {
// if we got a tracker query show different message
if len(tokens) != 0 {
send(fmt.Sprintf("*list:* No tracker matches: *%s*", tokens[0]), ud.Message.Chat.ID, true)
return
}
send("*list:* no torrents", ud.Message.Chat.ID, false)
return
}
send(buf.String(), ud.Message.Chat.ID, false)
}
// head will list the first 5 or n torrents
func head(ud tgbotapi.Update, tokens []string) {
var (
n = 5 // default to 5
err error
)
if len(tokens) > 0 {
n, err = strconv.Atoi(tokens[0])
if err != nil {
send("*head:* argument must be a number", ud.Message.Chat.ID, false)
return
}
}
torrents, err := Client.GetTorrents()
if err != nil {
send("*head:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
// make sure that we stay in the boundaries
if n <= 0 || n > len(torrents) {
n = len(torrents)
}
buf := new(bytes.Buffer)
for i := range torrents[:n] {
torrentName := mdReplacer.Replace(torrents[i].Name) // escape markdown
buf.WriteString(fmt.Sprintf("`<%d>` *%s*\n%s *%s* of *%s* (*%.1f%%*) ↓ *%s* ↑ *%s* R: *%s*\n\n",
torrents[i].ID, torrentName, torrents[i].TorrentStatus(), humanize.Bytes(torrents[i].Have()),
humanize.Bytes(torrents[i].SizeWhenDone), torrents[i].PercentDone*100, humanize.Bytes(torrents[i].RateDownload),
humanize.Bytes(torrents[i].RateUpload), torrents[i].Ratio()))
}
if buf.Len() == 0 {
send("*head:* no torrents", ud.Message.Chat.ID, false)
return
}
msgID := send(buf.String(), ud.Message.Chat.ID, true)
if NoLive {
return
}
// keep the info live
for i := 0; i < duration; i++ {
time.Sleep(time.Second * interval)
buf.Reset()
torrents, err = Client.GetTorrents()
if err != nil {
continue // try again if some error heppened
}
if len(torrents) < 1 {
continue
}
// make sure that we stay in the boundaries
if n <= 0 || n > len(torrents) {
n = len(torrents)
}
for _, torrent := range torrents[:n] {
torrentName := mdReplacer.Replace(torrent.Name) // escape markdown
buf.WriteString(fmt.Sprintf("`<%d>` *%s*\n%s *%s* of *%s* (*%.1f%%*) ↓ *%s* ↑ *%s* R: *%s*\n\n",
torrent.ID, torrentName, torrent.TorrentStatus(), humanize.Bytes(torrent.Have()),
humanize.Bytes(torrent.SizeWhenDone), torrent.PercentDone*100, humanize.Bytes(torrent.RateDownload),
humanize.Bytes(torrent.RateUpload), torrent.Ratio()))
}
// no need to check if it is empty, as if the buffer is empty telegram won't change the message
editConf := tgbotapi.NewEditMessageText(ud.Message.Chat.ID, msgID, buf.String())
editConf.ParseMode = tgbotapi.ModeMarkdown
Bot.Send(editConf)
}
}
// tail lists the last 5 or n torrents
func tail(ud tgbotapi.Update, tokens []string) {
var (
n = 5 // default to 5
err error
)
if len(tokens) > 0 {
n, err = strconv.Atoi(tokens[0])
if err != nil {
send("*tail:* argument must be a number", ud.Message.Chat.ID, false)
return
}
}
torrents, err := Client.GetTorrents()
if err != nil {
send("*tail:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
// make sure that we stay in the boundaries
if n <= 0 || n > len(torrents) {
n = len(torrents)
}
buf := new(bytes.Buffer)
for _, torrent := range torrents[len(torrents)-n:] {
torrentName := mdReplacer.Replace(torrent.Name) // escape markdown
buf.WriteString(fmt.Sprintf("`<%d>` *%s*\n%s *%s* of *%s* (*%.1f%%*) ↓ *%s* ↑ *%s* R: *%s*\n\n",
torrent.ID, torrentName, torrent.TorrentStatus(), humanize.Bytes(torrent.Have()),
humanize.Bytes(torrent.SizeWhenDone), torrent.PercentDone*100, humanize.Bytes(torrent.RateDownload),
humanize.Bytes(torrent.RateUpload), torrent.Ratio()))
}
if buf.Len() == 0 {
send("*tail:* no torrents", ud.Message.Chat.ID, false)
return
}
msgID := send(buf.String(), ud.Message.Chat.ID, true)
if NoLive {
return
}
// keep the info live
for i := 0; i < duration; i++ {
time.Sleep(time.Second * interval)
buf.Reset()
torrents, err = Client.GetTorrents()
if err != nil {
continue // try again if some error heppened
}
if len(torrents) < 1 {
continue
}
// make sure that we stay in the boundaries
if n <= 0 || n > len(torrents) {
n = len(torrents)
}
for _, torrent := range torrents[len(torrents)-n:] {
torrentName := mdReplacer.Replace(torrent.Name) // escape markdown
buf.WriteString(fmt.Sprintf("`<%d>` *%s*\n%s *%s* of *%s* (*%.1f%%*) ↓ *%s* ↑ *%s* R: *%s*\n\n",
torrent.ID, torrentName, torrent.TorrentStatus(), humanize.Bytes(torrent.Have()),
humanize.Bytes(torrent.SizeWhenDone), torrent.PercentDone*100, humanize.Bytes(torrent.RateDownload),
humanize.Bytes(torrent.RateUpload), torrent.Ratio()))
}
// no need to check if it is empty, as if the buffer is empty telegram won't change the message
editConf := tgbotapi.NewEditMessageText(ud.Message.Chat.ID, msgID, buf.String())
editConf.ParseMode = tgbotapi.ModeMarkdown
Bot.Send(editConf)
}
}
// downs will send the names of torrents with status 'Downloading' or in queue to
func downs(ud tgbotapi.Update) {
torrents, err := Client.GetTorrents()
if err != nil {
send("*downs:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
buf := new(bytes.Buffer)
for i := range torrents {
// Downloading or in queue to download
if torrents[i].Status == transmission.StatusDownloading ||
torrents[i].Status == transmission.StatusDownloadPending {
buf.WriteString(fmt.Sprintf("<%d> %s\n", torrents[i].ID, torrents[i].Name))
}
}
if buf.Len() == 0 {
send("No downloads", ud.Message.Chat.ID, false)
return
}
send(buf.String(), ud.Message.Chat.ID, false)
}
// seeding will send the names of the torrents with the status 'Seeding' or in the queue to
func seeding(ud tgbotapi.Update) {
torrents, err := Client.GetTorrents()
if err != nil {
send("*seeding:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
buf := new(bytes.Buffer)
for i := range torrents {
if torrents[i].Status == transmission.StatusSeeding ||
torrents[i].Status == transmission.StatusSeedPending {
buf.WriteString(fmt.Sprintf("<%d> %s\n", torrents[i].ID, torrents[i].Name))
}
}
if buf.Len() == 0 {
send("No torrents seeding", ud.Message.Chat.ID, false)
return
}
send(buf.String(), ud.Message.Chat.ID, false)
}
// paused will send the names of the torrents with status 'Paused'
func paused(ud tgbotapi.Update) {
torrents, err := Client.GetTorrents()
if err != nil {
send("*paused:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
buf := new(bytes.Buffer)
for i := range torrents {
if torrents[i].Status == transmission.StatusStopped {
buf.WriteString(fmt.Sprintf("<%d> %s\n%s (%.1f%%) DL: %s UL: %s R: %s\n\n",
torrents[i].ID, torrents[i].Name, torrents[i].TorrentStatus(),
torrents[i].PercentDone*100, humanize.Bytes(torrents[i].DownloadedEver),
humanize.Bytes(torrents[i].UploadedEver), torrents[i].Ratio()))
}
}
if buf.Len() == 0 {
send("No paused torrents", ud.Message.Chat.ID, false)
return
}
send(buf.String(), ud.Message.Chat.ID, false)
}
// checking will send the names of torrents with the status 'verifying' or in the queue to
func checking(ud tgbotapi.Update) {
torrents, err := Client.GetTorrents()
if err != nil {
send("*checking:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
buf := new(bytes.Buffer)
for i := range torrents {
if torrents[i].Status == transmission.StatusChecking ||
torrents[i].Status == transmission.StatusCheckPending {
buf.WriteString(fmt.Sprintf("<%d> %s\n%s (%.1f%%)\n\n",
torrents[i].ID, torrents[i].Name, torrents[i].TorrentStatus(),
torrents[i].PercentDone*100))
}
}
if buf.Len() == 0 {
send("No torrents verifying", ud.Message.Chat.ID, false)
return
}
send(buf.String(), ud.Message.Chat.ID, false)
}
// active will send torrents that are actively downloading or uploading
func active(ud tgbotapi.Update) {
torrents, err := Client.GetTorrents()
if err != nil {
send("*active:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
buf := new(bytes.Buffer)
for i := range torrents {
if torrents[i].RateDownload > 0 ||
torrents[i].RateUpload > 0 {
// escape markdown
torrentName := mdReplacer.Replace(torrents[i].Name)
buf.WriteString(fmt.Sprintf("`<%d>` *%s*\n%s *%s* of *%s* (*%.1f%%*) ↓ *%s* ↑ *%s* R: *%s*\n\n",
torrents[i].ID, torrentName, torrents[i].TorrentStatus(), humanize.Bytes(torrents[i].Have()),
humanize.Bytes(torrents[i].SizeWhenDone), torrents[i].PercentDone*100, humanize.Bytes(torrents[i].RateDownload),
humanize.Bytes(torrents[i].RateUpload), torrents[i].Ratio()))
}
}
if buf.Len() == 0 {
send("No active torrents", ud.Message.Chat.ID, false)
return
}
msgID := send(buf.String(), ud.Message.Chat.ID, true)
if NoLive {
return
}
// keep the active list live for 'duration * interval'
for i := 0; i < duration; i++ {
time.Sleep(time.Second * interval)
// reset the buffer to reuse it
buf.Reset()
// update torrents
torrents, err = Client.GetTorrents()
if err != nil {
continue // if there was error getting torrents, skip to the next iteration
}
// do the same loop again
for i := range torrents {
if torrents[i].RateDownload > 0 ||
torrents[i].RateUpload > 0 {
torrentName := mdReplacer.Replace(torrents[i].Name) // replace markdown chars
buf.WriteString(fmt.Sprintf("`<%d>` *%s*\n%s *%s* of *%s* (*%.1f%%*) ↓ *%s* ↑ *%s* R: *%s*\n\n",
torrents[i].ID, torrentName, torrents[i].TorrentStatus(), humanize.Bytes(torrents[i].Have()),
humanize.Bytes(torrents[i].SizeWhenDone), torrents[i].PercentDone*100, humanize.Bytes(torrents[i].RateDownload),
humanize.Bytes(torrents[i].RateUpload), torrents[i].Ratio()))
}
}
// no need to check if it is empty, as if the buffer is empty telegram won't change the message
editConf := tgbotapi.NewEditMessageText(ud.Message.Chat.ID, msgID, buf.String())
editConf.ParseMode = tgbotapi.ModeMarkdown
Bot.Send(editConf)
}
// sleep one more time before putting the dashes
time.Sleep(time.Second * interval)
// replace the speed with dashes to indicate that we are done being live
buf.Reset()
for i := range torrents {
if torrents[i].RateDownload > 0 ||
torrents[i].RateUpload > 0 {
// escape markdown
torrentName := mdReplacer.Replace(torrents[i].Name)
buf.WriteString(fmt.Sprintf("`<%d>` *%s*\n%s *%s* of *%s* (*%.1f%%*) ↓ *-* ↑ *-* R: *%s*\n\n",
torrents[i].ID, torrentName, torrents[i].TorrentStatus(), humanize.Bytes(torrents[i].Have()),
humanize.Bytes(torrents[i].SizeWhenDone), torrents[i].PercentDone*100, torrents[i].Ratio()))
}
}
editConf := tgbotapi.NewEditMessageText(ud.Message.Chat.ID, msgID, buf.String())
editConf.ParseMode = tgbotapi.ModeMarkdown
Bot.Send(editConf)
}
// errors will send torrents with errors
func errors(ud tgbotapi.Update) {
torrents, err := Client.GetTorrents()
if err != nil {
send("*errors:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
buf := new(bytes.Buffer)
for i := range torrents {
if torrents[i].Error != 0 {
buf.WriteString(fmt.Sprintf("<%d> %s\n%s\n",
torrents[i].ID, torrents[i].Name, torrents[i].ErrorString))
}
}
if buf.Len() == 0 {
send("No errors", ud.Message.Chat.ID, false)
return
}
send(buf.String(), ud.Message.Chat.ID, false)
}
// sort changes torrents sorting
func sort(ud tgbotapi.Update, tokens []string) {
if len(tokens) == 0 {
send(`*sort* takes one of:
(*id, name, age, size, progress, downspeed, upspeed, download, upload, ratio*)
optionally start with (*rev*) for reversed order
e.g. "*sort rev size*" to get biggest torrents first.`, ud.Message.Chat.ID, true)
return
}
var reversed bool
if strings.ToLower(tokens[0]) == "rev" {
reversed = true
tokens = tokens[1:]
}
switch strings.ToLower(tokens[0]) {
case "id":
if reversed {
Client.SetSort(transmission.SortRevID)
break
}
Client.SetSort(transmission.SortID)
case "name":
if reversed {
Client.SetSort(transmission.SortRevName)
break
}
Client.SetSort(transmission.SortName)
case "age":
if reversed {
Client.SetSort(transmission.SortRevAge)
break
}
Client.SetSort(transmission.SortAge)
case "size":
if reversed {
Client.SetSort(transmission.SortRevSize)
break
}
Client.SetSort(transmission.SortSize)
case "progress":
if reversed {
Client.SetSort(transmission.SortRevProgress)
break
}
Client.SetSort(transmission.SortProgress)
case "downspeed":
if reversed {
Client.SetSort(transmission.SortRevDownSpeed)
break
}
Client.SetSort(transmission.SortDownSpeed)
case "upspeed":
if reversed {
Client.SetSort(transmission.SortRevUpSpeed)
break
}
Client.SetSort(transmission.SortUpSpeed)
case "download":
if reversed {
Client.SetSort(transmission.SortRevDownloaded)
break
}
Client.SetSort(transmission.SortDownloaded)
case "upload":
if reversed {
Client.SetSort(transmission.SortRevUploaded)
break
}
Client.SetSort(transmission.SortUploaded)
case "ratio":
if reversed {
Client.SetSort(transmission.SortRevRatio)
break
}
Client.SetSort(transmission.SortRatio)
default:
send("unkown sorting method", ud.Message.Chat.ID, false)
return
}
if reversed {
send("*sort:* reversed "+tokens[0], ud.Message.Chat.ID, false)
return
}
send("*sort:* "+tokens[0], ud.Message.Chat.ID, false)
}
var trackerRegex = regexp.MustCompile(`[https?|udp]://([^:/]*)`)
// trackers will send a list of trackers and how many torrents each one has
func trackers(ud tgbotapi.Update) {
torrents, err := Client.GetTorrents()
if err != nil {
send("*trackers:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
trackers := make(map[string]int)
for i := range torrents {
for _, tracker := range torrents[i].Trackers {
sm := trackerRegex.FindSubmatch([]byte(tracker.Announce))
if len(sm) > 1 {
currentTracker := string(sm[1])
n, ok := trackers[currentTracker]
if !ok {
trackers[currentTracker] = 1
continue
}
trackers[currentTracker] = n + 1
}
}
}
buf := new(bytes.Buffer)
for k, v := range trackers {
buf.WriteString(fmt.Sprintf("%d - %s\n", v, k))
}
if buf.Len() == 0 {
send("No trackers!", ud.Message.Chat.ID, false)
return
}
send(buf.String(), ud.Message.Chat.ID, false)
}
// add takes an URL to a .torrent file to add it to transmission
func add(ud tgbotapi.Update, tokens []string) {
if len(tokens) == 0 {
send("*add:* needs at least one URL", ud.Message.Chat.ID, false)
return
}
// loop over the URL/s and add them
for _, url := range tokens {
cmd := transmission.NewAddCmdByURL(url)
torrent, err := Client.ExecuteAddCommand(cmd)
if err != nil {
send("*add:* "+err.Error(), ud.Message.Chat.ID, false)
continue
}
// check if torrent.Name is empty, then an error happened
if torrent.Name == "" {
send("*add:* error adding "+url, ud.Message.Chat.ID, false)
continue
}
send(fmt.Sprintf("*Added:* <%d> %s", torrent.ID, torrent.Name), ud.Message.Chat.ID, false)
}
}
// receiveTorrent gets an update that potentially has a .torrent file to add
func receiveTorrent(ud tgbotapi.Update) {
if ud.Message.Document == nil {
return // has no document
}
// get the file ID and make the config
fconfig := tgbotapi.FileConfig{
FileID: ud.Message.Document.FileID,
}
file, err := Bot.GetFile(fconfig)
if err != nil {
send("*receiver:* "+err.Error(), ud.Message.Chat.ID, false)
return
}
// add by file URL
add(ud, []string{file.Link(BotToken)})
}
// search takes a query and returns torrents with match
func search(ud tgbotapi.Update, tokens []string) {