forked from tremc/tremc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tremc
executable file
·5147 lines (4576 loc) · 229 KB
/
tremc
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
863
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################################################################
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details: #
# http://www.gnu.org/licenses/gpl-3.0.txt #
########################################################################
import json
import time
import datetime
import re
import base64
import socket
import argparse
import sys
import os
import signal
import unicodedata
import locale
import curses
import curses.ascii
from textwrap import wrap
from subprocess import call, Popen
import netrc
import operator
import urllib.request
import urllib.error
import urllib.parse
import configparser
import enum
try:
import IPy
except ImportError:
pass
try:
import pyperclip
except ImportError:
pass
locale.setlocale(locale.LC_ALL, '')
PROG = 'tremc'
# Global constants and constant configuration
class GConfig:
VERSION = '0.9.2'
TRNSM_VERSION_MIN = '1.90'
TRNSM_VERSION_MAX = '3.0.0'
RPC_VERSION_MIN = 8
RPC_VERSION_MAX = 16
STARTTIME = time.time()
DEBUG = False
ENCODING = locale.getpreferredencoding() or 'UTF-8'
# error codes
class errors(enum.IntEnum):
CONNECTION_ERROR = 1
JSON_ERROR = 2
CONFIGFILE_ERROR = 3
FILTERS_WITH_PARAM = ['tracker', 'regex', 'location', 'label']
def __init__(self):
default_config_path = xdg_config_home(PROG '/settings.cfg')
parser = argparse.ArgumentParser(description="%(prog)s " self.VERSION,
usage="(prog)s [options] [torrent] -- transmission-remote-args ...",
epilog="Positional arguments are passed to transmission-remote. Use -- to separate from %(prog)s arguments")
parser.add_argument("-v", "--version", action="version", version="%(prog)s " self.VERSION,
help="Show version number and supported Transmission versions.")
parser.add_argument("-c", "--connect", action="store", dest="connection", default="",
help="Point to the server using pattern [username:password@]host[:port]/[path]")
parser.add_argument("-s", "--ssl", action="store_true", dest="ssl", default=False,
help="Connect to Transmission using SSL.")
parser.add_argument("-f", "--config", action="store", dest="configfile", default=default_config_path,
help="Path to configuration file.")
parser.add_argument("--create-config", action="store_true", default=False,
help="Create configuration file CONFIGFILE with default values.")
parser.add_argument("-l", "--list-actions", action="store_true", dest='listactions', default=False,
help="List available actions for key mapping.")
parser.add_argument("-k", "--list-keys", action="store_true", dest='listkeys', default=False,
help="List available key names for key mapping.")
parser.add_argument("-n", "--netrc", action="store_true", dest="use_netrc", default=False,
help="Get authentication info from your ~/.netrc file.")
parser.add_argument("-X", "--skip-version-check", "--permissive", action="store_true", dest="PERMISSIVE", default=False,
help="Proceed even if the running transmission daemon seems incompatible, or the terminal is too small.")
parser.add_argument("-p", "--profile", action="store", dest="profile",
help="Select profile to use.")
parser.add_argument("-r", "--reverse-dns", action="store_true", dest="rdns", default=False,
help="Toggle reverse DNS peers addresses.")
parser.add_argument("-d", "--debug", action="store", dest="DEBUG", nargs='?', default=False,
help="Enable debugging messages.")
parser.add_argument('transmissionremote_args', nargs='*', metavar='A',
help="Torrent files to add using transmission-remote")
cmd_args = parser.parse_args()
for i in vars(cmd_args).keys():
setattr(self, i, vars(cmd_args)[i])
if self.DEBUG is None:
self.DEBUG = True
self.debug_file = sys.stderr
elif isinstance(self.DEBUG, str):
try:
self.debug_file = open(self.DEBUG, "a", buffering=1)
except OSError:
pass
if not self.create_config and not os.path.isfile(self.configfile) and '/' not in self.configfile:
if os.path.isfile(xdg_config_home(PROG '/' self.configfile)):
self.configfile = xdg_config_home(PROG '/' self.configfile)
elif os.path.isfile(xdg_config_home(PROG '/' self.configfile '.cfg')):
self.configfile = xdg_config_home(PROG '/' self.configfile '.cfg')
self.configfile = self.configfile
config.read(self.configfile)
self.history_file = ''
if PROG in os.path.dirname(self.configfile):
self.history_file = os.path.join(os.path.dirname(self.configfile), 'history.json')
elif PROG in os.path.basename(self.configfile):
self.history_file = self.configfile.rsplit(PROG, 1)[0] PROG '-history.json'
self.geoip2_database = config.get('Misc', 'geoip2_database', fallback='')
self.rdns = self.rdns ^ config.getboolean('Misc', 'rdns', fallback=False)
# Handle connection details
self.host = config.get('Connection', 'host', fallback='localhost')
self.port = config.getint('Connection', 'port', fallback=9091)
self.path = config.get('Connection', 'path', fallback='/transmission/rpc')
self.username = config.get('Connection', 'username', fallback='')
self.password = config.get('Connection', 'password', fallback='')
un_pw = os.environ.get("TR_AUTH")
if un_pw:
self.username = un_pw.split(":")[0]
self.password = ":".join(un_pw.split(":")[1:])
if self.use_netrc:
self.username, self.password = read_netrc(hostname=self.host)
if self.connection:
try:
if self.connection.count('@') == 1:
auth, self.connection = self.connection.split('@')
if auth.count(':') == 1:
self.username, self.password = auth.split(':')
if self.connection.count(':') == 1:
self.host, port = self.connection.split(':')
if port.count('/') >= 1:
port, self.path = port.split('/', 1)
self.port = int(port)
else:
self.host = self.connection
self.ssl = False # Don't use ssl from config file if given connection info on command line.
except ValueError:
exit_prog("Wrong connection pattern: %s\n" % self.connection)
self.ssl = self.ssl | config.getboolean('Connection', 'ssl', fallback=False)
url = '%s:%d/%s' % (self.host, self.port, self.path)
url = url.replace('//', '/') # double-/ doesn't work for some reason
self.url = 'https://%s' % url if self.ssl else 'http://%s' % url
if self.create_config:
config.set('Connection', 'host', self.host)
config.set('Connection', 'port', str(self.port))
config.set('Connection', 'path', self.path)
config.set('Connection', 'username', self.username)
config.set('Connection', 'password', self.password)
create_config(self.configfile, self.connection)
try:
self.ipy = True # extract ipv4 from ipv6 addresses
self.IPV6_RANGE_6TO4 = IPy.IP('2002::/16')
self.IPV6_RANGE_TEREDO = IPy.IP('2001::/32')
self.IPV4_ONES = 0xffffffff
except NameError:
self.ipy = False
self.clipboard = 'pyperclip' in sys.modules
self.sort_options = [
('name', '_Name'), ('addedDate', '_Age'), ('percentDone', '_Progress'),
('seeders', '_Seeds'), ('leechers', 'Lee_ches'), ('sizeWhenDone', 'Si_ze'),
('status', 'S_tatus'), ('uploadedEver', 'Up_loaded'),
('rateUpload', '_Upload Speed'), ('rateDownload', '_Download Speed'),
('uploadRatio', '_Ratio'), ('peersConnected', 'P_eers'),
('downloadDir', 'L_ocation'), ('mainTrackerDomain', 'Trac_ker'),
('queuePosition', '_Queue Position'), ('reverse', 'Re_verse') ]
self.file_sort_options = [
('name', '_Name'), ('progress', '_Progress'),
('length', 'Si_ze'), ('bytesCompleted', '_Downloaded'),
('none', '_Torrent order'),
('reverse', 'Re_verse')
]
self.filters = [[{}]]
self.filters[0][0]['name'] = config.get('Filtering', 'filter', fallback='')
self.filters[0][0]['inverse'] = config.getboolean('Filtering', 'invert', fallback=False)
self.sort_orders = parse_sort_str(config.get('Sorting', 'order', fallback=''), [x[0] for x in self.sort_options])
self.file_sort_key = 'name'
self.file_sort_reverse = False
self.filters[0][0]['regex'] = ''
self.filters[0][0]['tracker'] = ''
self.filters[0][0]['location'] = ''
self.histories = load_history(self.history_file)
self.tlist_item_height = config.getint('Misc', 'lines_per_torrent')
self.torrentname_is_progressbar = config.getboolean('Misc', 'torrentname_is_progressbar')
self.file_viewer = config.get('Misc', 'file_viewer')
self.file_open_in_terminal = config.getboolean('Misc', 'file_open_in_terminal')
self.view_selected = config.getboolean('Misc', 'view_selected', fallback=False)
self.torrent_numbers = config.getboolean('Misc', 'torrent_numbers', fallback=False)
self.profiles = parse_config_profiles(config, [x[0] for x in self.sort_options])
try:
self.selected_file_attr = curses.A_BOLD curses.A_ITALIC
except AttributeError:
self.selected_file_attr = curses.A_BOLD
self.actions = {
# First in list: 0=all 1=list 2=details 3=files 4=tracker 16=movement
# 256 for RPC>=14, 512 for RPC>=16
'list_key_bindings': [0, ['F1', '?'], 'List key bindings'],
'quit_now': [0, ['^w'], 'Quit immediately'],
'quit': [1, ['q'], 'Quit'],
'leave_details': [2, ['BACKSPACE', 'q'], 'Back to torrent list'],
'go_back_or_unfocus': [2, ['ESC', 'BREAK'], 'Unfocus or back to torrent list'],
'daemon_quit': [0, ['X'], 'Ask daemon to quit'],
'options_dialog': [0, ['O'], PROG ' options menu'],
'server_options_dialog': [1, ['o'], 'Server options menu'],
'toggle_compact_torrentlist': [1, ['C'], 'Cycle torrent line height'],
'toggle_torrent_numbers': [1, [], 'Toggle torrent number in list'],
'turtle_mode': [1, ['t'], 'Toggle turtle mode'],
'unmapped_actions': [0, '`', 'Show actions not mapped to keys'],
'global_upload': [0, ['u'], 'Set global upload'],
'global_download': [0, ['d'], 'Set global download limit'],
'torrent_upload': [0, ['U'], 'Set torrent maximum upload rate'],
'torrent_download': [0, ['D'], 'Set torrent maximum download rate'],
'seed_ratio': [0, ['L'], 'Set seed ratio limit for focused torrent'],
'bandwidth_priority_inc': [0, [' '], 'Increase torrent bandwidth priority'],
'bandwidth_priority_dec': [0, ['-'], 'Decrease torrent bandwidth priority'],
'honors_limits': [0, ['*'], 'Toggle torrent honors session limits'],
'pause_unpause_torrent': [0, ['p'], 'Pause/Unpause torrent'],
'pause_unpause_all_torrent': [0, ['P'], 'Pause/Unpause all torrents'],
'start_now_torrent': [0, ['N'], 'Start torrent now'],
'verify_torrent': [0, ['v', 'y'], 'Verify torrent'],
'move_torrent': [0, ['m'], 'Move torrent'],
'rename_torrent_selected_file': [0, ['F'], 'Rename torrent/file'],
'reannounce_torrent': [0, ['n'], 'Reannounce torrent'],
'show_stats': [0, ['S'], 'Show upload/download stats'],
'remove': [1, ['DC', 'r'], 'Remove selected/focused torrents, keeping content'],
'remove_focused': [1, [], 'Remove focused torrent keeping content'],
'remove_selected': [1, ['^r'], 'Remove selected torrents'],
'remove_data': [0, [], 'Remove selected/focused torrents and content'],
'remove_focused_data': [0, ['SDC', 'R'], 'Remove torrent and content'],
'remove_selected_data': [1, [], 'Remove selected torrents and content'],
'copy_magnet_link': [0, ['M'], 'Copy Magnet Link to the System Clipboard'],
'remove_labels': [256, ['^l'], 'Remove labels'],
'add_label': [256, ['b'], 'Add label'],
'set_labels': [256, ['B'], 'Set labels'],
'move_queue_down': [513, ['J'], 'Move torrent down in queue'],
'move_queue_up': [513, ['K'], 'Move torrent up in queue'],
'profile_menu': [1, ['e'], 'Profile menu'],
'save_profile': [1, ['E'], 'Save profile'],
'search_torrent': [1, ['/'], 'Find torrent'],
'search_torrent_regex': [1, ['.'], 'Find torrents matching regular expression'],
'search_torrent_fulltext': [1, [], 'Find torrent (full text)'],
'search_torrent_regex_fulltext': [1, [], 'Find torrents matching regular expression (full text)'],
'set_filter': [1, ['f'], 'Set filter'],
'add_filter': [1, ['T'], 'Add filter'],
'edit_filters': [1, ['I'], 'Edit list of filters'],
'invert_filters_action': [1, ['~'], 'Reverse filters'],
'show_torrent_sort_order_menu': [1, ['s'], 'Sort torrent list'],
'select_unselect_torrent': [1, ['SPACE'], 'Select/unselect torrent'],
'select_unselect_torrents': [1, ['A'], 'Select/Deselect all torrents'],
'invert_selection_torrents': [1, ['i'], 'Invert torrent selection'],
'select_search_torrent': [1, [','], 'Select torrents matching pattern'],
'select_search_torrent_regex': [1, ['<'], 'Select torrents matching regex'],
'select_search_torrent_fulltext': [1, [], 'Select torrents matching pattern (full text)'],
'select_search_torrent_regex_fulltext': [1, [], 'Select torrents matching regex (full text)'],
'enter_details': [1, ['ENTER', 'RIGHT', 'l'], 'Enter torrent details view'],
'add_torrent': [1, ['a'], 'Add torrent'],
'add_torrent_paused': [1, ['^a'], 'Add torrent paused'],
'unfocus_torrent': [1, ['ESC', 'BREAK'], 'Unfocus torrent'],
'tab_overview': [2, ['o'], 'Jump to overview'],
'tab_files': [2, ['f'], 'Jump to file list'],
'tab_peers': [2, ['e'], 'Jump to peer list'],
'tab_trackers': [2, ['t'], 'Jump to tracker list'],
'tab_chunks': [2, ['c'], 'Jump to chunck list'],
'next_details': [2, ['TAB'], 'Next details tab'],
'prev_details': [2, ['BTAB'], 'Previous details tab'],
'file_priority_or_switch_details_next': [2, ['RIGHT', 'l'], 'Raise file priority or Previous tab'],
'file_priority_or_switch_details_prev': [2, ['LEFT', 'h'], 'Lower file priority or Previous tab'],
'add_tracker_or_select_all_files': [2, ['a'], 'Select/Deselect all files or add torrent'],
'view_file': [3, ['ENTER'], 'View file'],
'view_file_command': [3, ['|'], 'Run command on file'],
'move_to_next_directory': [3, ['J'], 'Next diectory'],
'move_to_previous_directory': [3, ['K'], 'Previous directory'],
'show_file_sort_order_menu': [3, ['s'], 'Sort file list'],
'visual_select_files': [3, ['V'], 'Visually select files'],
'select_search_file': [3, [','], 'Select files matching pattern'],
'select_files_dir': [3, ['A'], 'Select/Deselect directory'],
'search_file': [3, ['/'], 'Search file list'],
'rename_dir': [3, ['C'], 'Rename directory inside torrent'],
'select_search_file_regex': [3, ['<'], 'Select files matching regex'],
'search_file_regex': [3, ['.'], 'Find files matching regex'],
'invert_selection_files': [3, ['i'], 'Invert selection'],
'select_file': [3, ['SPACE'], 'Select/unselect file'],
'file_info': [3, ['x'], 'Show file info'],
'remove_tracker': [4, ['DC', 'r'], 'Remove tracker'],
'page_up': [16, ['PPAGE', '^b'], 'Page Up'],
'page_down': [16, ['NPAGE', '^f'], 'Page Down'],
'line_up': [16, ['UP', 'k', '^p'], 'Up'],
'line_down': [16, ['DOWN', 'j', '^n'], 'Down'],
'go_home': [16, ['HOME', 'g'], 'Home'],
'go_end': [16, ['END', 'G'], 'End'],
}
self.keys = [x for x in dir(K) if x[0] != '_'] \
[x[4:] for x in dir(curses) if x[:4] == 'KEY_']
exit = False
if self.listactions:
list_actions(self.actions)
exit = True
if self.listkeys:
list_keys()
exit = True
if exit:
sys.exit(0)
class Keys:
TAB = 9
LF = 10
CR = 13
ESC = 27
SPACE = 32
EXCLAMATION = 33
QUOT = 34
HASH = 35
DOLLAR = 36
PERCENT = 37
AMPERSAND = 38
APOSTROPHE = 39
LPAREN = 40
RPAREN = 41
STAR = 42
PLUS = 43
COMMA = 44
MINUS = 45
DOT = 46
SLASH = 47
COLON = 58
SEMICOLON = 59
LT = 60
EQUAL = 61
GT = 62
QUES = 63
AT = 64
LBRACKET = 91
BACKSLASH = 92
RBRACKET = 93
CARET = 94
UL = 95
BACKTICK = 96
LBRACE = 123
PIPE = 124
RBRACE = 125
TILDE = 126
DEL = 127
def __init__(self):
for i in range(1, 27):
setattr(self, chr(64 i), 64 i)
setattr(self, chr(64 i) '_', i)
setattr(self, chr(96 i), 96 i)
for i in range(0, 10):
setattr(self, 'n' str(i), ord('0') i)
K = Keys()
def country_code_by_addr_vany(geo_ip, geo_ip6, addr):
if gconfig.geoip2:
try:
return geo_ip.country(addr).country.iso_code
except Exception:
return '?'
if '.' in addr:
return geo_ip.country_code_by_addr(addr)
if ':' not in addr:
return '?'
if gconfig.ipy:
ip = IPy.IP(addr)
if ip in gconfig.IPV6_RANGE_6TO4:
addr = str(IPy.IP(ip.int() >> 80 & gconfig.IPV4_ONES))
return geo_ip.country_code_by_addr(addr)
if ip in gconfig.IPV6_RANGE_TEREDO:
addr = str(IPy.IP(ip.int() & gconfig.IPV4_ONES ^ gconfig.IPV4_ONES))
return geo_ip.country_code_by_addr(addr)
if hasattr(geo_ip6, 'country_code_by_addr_v6'):
return geo_ip6.country_code_by_addr_v6(addr)
return '?'
def pdebug(*argv):
if gconfig.DEBUG:
print(time.time() - gconfig.STARTTIME, ": ", *argv, file=gconfig.debug_file, flush=True)
# define config defaults
config = configparser.ConfigParser()
config.optionxform = lambda option: option
config.add_section('Connection')
config.add_section('Sorting')
config.set('Sorting', 'order', 'name')
config.add_section('Filtering')
config.set('Filtering', 'filter', '')
config.set('Filtering', 'invert', 'False')
config.add_section('Misc')
config.set('Misc', 'lines_per_torrent', '2')
config.set('Misc', 'torrentname_is_progressbar', 'True')
config.set('Misc', 'file_viewer', 'xdg-open %%s')
config.set('Misc', 'file_open_in_terminal', 'True')
config.add_section('Colors')
config.set('Colors', 'header', 'bg:default,fg:default')
config.set('Colors', 'footer', 'bg:default,fg:default')
config.set('Colors', 'title_seed', 'bg:green,fg:black')
config.set('Colors', 'title_download', 'bg:blue,fg:black')
config.set('Colors', 'title_idle', 'bg:cyan,fg:black')
config.set('Colors', 'title_incomplete', 'bg:default,fg:default')
config.set('Colors', 'title_verify', 'bg:magenta,fg:black')
config.set('Colors', 'title_paused', 'bg:default,fg:default')
config.set('Colors', 'title_error', 'bg:red,fg:default')
config.set('Colors', 'download_rate', 'bg:default,fg:blue')
config.set('Colors', 'upload_rate', 'bg:black,fg:red')
config.set('Colors', 'eta ratio', 'bg:default,fg:default')
config.set('Colors', 'filter_status', 'bg:red,fg:black')
config.set('Colors', 'multi_filter_status', 'bg:blue,fg:black')
config.set('Colors', 'window', 'bg:default,fg:default')
config.set('Colors', 'dialog', 'bg:default,fg:default')
config.set('Colors', 'dialog_important', 'bg:default,fg:red')
config.set('Colors', 'file_prio_high', 'fg:red,bg:default')
config.set('Colors', 'file_prio_normal', 'fg:default,bg:default')
config.set('Colors', 'file_prio_low', 'fg:yellow,bg:default')
config.set('Colors', 'file_prio_off', 'fg:blue,bg:default')
class ColorManager:
def __init__(self, config):
self.config = dict()
self.term_has_colors = curses.has_colors()
curses.start_color()
if self.term_has_colors:
curses.use_default_colors()
for name in list(config.keys()):
self.config[name] = self._parse_color_pair(config[name])
if self.term_has_colors:
curses.init_pair(self.config[name]['ind'],
self.config[name]['fg'],
self.config[name]['bg'])
def _parse_color_pair(self, pair):
bg_name = [x for x in pair.split(',') if x[:3] == 'bg:'][0].split(':')[1].upper() if 'bg:' in pair else 'DEFAULT'
fg_name = [x for x in pair.split(',') if x[:3] == 'fg:'][0].split(':')[1].upper() if 'fg:' in pair else 'DEFAULT'
color_pair = {'ind': len(list(self.config.keys())) 1}
try:
if bg_name == 'DEFAULT':
color_pair['bg'] = -1
else:
color_pair['bg'] = getattr(curses, 'COLOR_' bg_name)
except AttributeError:
color_pair['bg'] = -1
try:
if fg_name == 'DEFAULT':
color_pair['fg'] = -1
else:
color_pair['fg'] = getattr(curses, 'COLOR_' fg_name)
if fg_name == 'WHITE':
color_pair['fg'] = -1
except AttributeError:
color_pair['fg'] = -1
return color_pair
def ind(self, name):
return self.config[name]['ind']
class Normalizer:
def __init__(self):
self.values = {}
def add(self, key, value, max_len):
if key not in list(self.values.keys()):
self.values[key] = [float(value)]
else:
if len(self.values[key]) >= max_len:
self.values[key].pop(0)
self.values[key].append(float(value))
return self.get(key)
def get(self, key):
if key not in list(self.values.keys()):
return 0.0
return sum(self.values[key]) / len(self.values[key])
class TransmissionRequest:
"""Handle communication with Transmission server."""
def __init__(self, url, method=None, tag=None, arguments=None, server=None):
"""server is not really optional"""
self.url = url
self.open_request = None
self.last_update = 0
self.server = server
if method and tag:
self.set_request_data(method, tag, arguments)
def set_request_data(self, method, tag, arguments=None):
request_data = {'method': method, 'tag': tag}
if arguments:
request_data['arguments'] = arguments
self.http_request = urllib.request.Request(self.url, bytes(json.dumps(request_data), gconfig.ENCODING))
def send_request(self):
"""Ask for information from server OR submit command."""
try:
if self.server.session_id:
self.http_request.add_header('X-Transmission-Session-Id', self.server.session_id)
self.open_request = urllib.request.urlopen(self.http_request)
except AttributeError:
# request data (http_request) isn't specified yet -- data will be available on next call
pass
# authentication
except urllib.error.HTTPError as e:
try:
msg = html2text(str(e.read()))
except Exception:
msg = str(e)
# extract session id and send request again
m = re.search(r'X-Transmission-Session-Id:\s*(\w )', msg)
try:
self.server.session_id = m.group(1)
self.send_request()
except AttributeError:
exit_prog(str(msg) "\n", gconfig.errors.CONNECTION_ERROR)
except urllib.error.URLError as msg:
exit_prog("Cannot connect to %s: %s" % (self.http_request.host, msg.reason), gconfig.errors.CONNECTION_ERROR)
def get_response(self):
"""Get response to previously sent request."""
if self.open_request is None:
return {'result': 'no open request'}
response = b''
while True:
try:
chunk = self.open_request.read()
except ConnectionResetError:
return {'result': 'connection reset by peer'}
if not chunk:
break
response = chunk
try:
data = json.loads(response.decode("utf-8"))
except ValueError:
exit_prog("Cannot parse response: %s\n" % response, gconfig.errors.JSON_ERROR)
self.open_request = None
return data
# End of Class TransmissionRequest
class Transmission:
"""Higher level of data exchange"""
STATUS_STOPPED = 0 # Torrent is stopped
STATUS_CHECK_WAIT = 1 # Queued to check files
STATUS_CHECK = 2 # Checking files
STATUS_DOWNLOAD_WAIT = 3 # Queued to download
STATUS_DOWNLOAD = 4 # Downloading
STATUS_SEED_WAIT = 5 # Queued to seed
STATUS_SEED = 6 # Seeding
TAG_TORRENT_LIST = 7
TAG_TORRENT_DETAILS = 77
TAG_SESSION_STATS = 21
TAG_SESSION_GET = 22
TAG_SESSION_CLOSE = 23
LIST_FIELDS = ['id', 'name', 'downloadDir', 'status', 'trackerStats', 'desiredAvailable',
'rateDownload', 'rateUpload', 'eta', 'uploadRatio',
'sizeWhenDone', 'haveValid', 'haveUnchecked', 'addedDate',
'uploadedEver', 'errorString', 'recheckProgress',
'peersConnected', 'uploadLimit', 'downloadLimit',
'uploadLimited', 'downloadLimited', 'bandwidthPriority',
'peersSendingToUs', 'peersGettingFromUs',
'seedRatioLimit', 'seedRatioMode', 'isPrivate', 'magnetLink',
'honorsSessionLimits', 'metadataPercentComplete',
]
DETAIL_FIELDS = ['files', 'priorities', 'wanted', 'peers', 'trackers',
'activityDate', 'dateCreated', 'startDate', 'doneDate',
'totalSize', 'leftUntilDone', 'comment', 'creator',
'hashString', 'pieceCount', 'pieceSize', 'pieces',
'downloadedEver', 'corruptEver', 'peersFrom'] LIST_FIELDS
def __init__(self, url, username, password):
self.url = url
self.session_id = 0
if username and password:
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, url, username, password)
authhandler = urllib.request.HTTPBasicAuthHandler(password_mgr)
opener = urllib.request.build_opener(authhandler)
urllib.request.install_opener(opener)
# check rpc version
request = TransmissionRequest(url, 'session-get', self.TAG_SESSION_GET, server=self)
request.send_request()
response = request.get_response()
self.rpc_version = response['arguments']['rpc-version']
self.version = response['arguments']['version'].split()[0]
# rpc version too old?
version_error = "Unsupported Transmission version: " str(response['arguments']['version']) \
" -- RPC protocol version: " str(response['arguments']['rpc-version']) "\n"
skip_msg = "Proceeding anyway because of --skip-version-check.\n"
min_msg = "Please install Transmission version " gconfig.TRNSM_VERSION_MIN " or higher.\n"
try:
if response['arguments']['rpc-version'] < gconfig.RPC_VERSION_MIN:
if gconfig.PERMISSIVE:
pdebug(version_error skip_msg)
else:
exit_prog(version_error min_msg)
except KeyError:
exit_prog(version_error min_msg)
# rpc version too new?
if response['arguments']['rpc-version'] > gconfig.RPC_VERSION_MAX:
if gconfig.PERMISSIVE:
pdebug(version_error skip_msg)
else:
exit_prog(version_error "Please install Transmission version " gconfig.TRNSM_VERSION_MAX " or lower.\n")
# setup compatibility to Transmission <2.40
if self.rpc_version < 14:
Transmission.STATUS_CHECK_WAIT = 1 << 0
Transmission.STATUS_CHECK = 1 << 1
Transmission.STATUS_DOWNLOAD_WAIT = 1 << 2
Transmission.STATUS_DOWNLOAD = 1 << 2
Transmission.STATUS_SEED_WAIT = 1 << 3
Transmission.STATUS_SEED = 1 << 3
Transmission.STATUS_STOPPED = 1 << 4
# Queue was implemented in Transmission v2.4
if self.rpc_version >= 14:
self.LIST_FIELDS.append('queuePosition')
self.DETAIL_FIELDS.append('queuePosition')
if self.rpc_version >= 16:
self.LIST_FIELDS.append('labels')
self.DETAIL_FIELDS.append('labels')
# set up request list
self.requests = {'torrent-list':
TransmissionRequest(url, 'torrent-get', self.TAG_TORRENT_LIST, {'fields': self.LIST_FIELDS}, server=self),
'session-stats':
TransmissionRequest(url, 'session-stats', self.TAG_SESSION_STATS, 21, server=self),
'session-get':
TransmissionRequest(url, 'session-get', self.TAG_SESSION_GET, server=self),
'torrent-details':
TransmissionRequest(url, server=self)}
self.torrent_cache = []
self.trackers = set()
self.locations = set()
self.labels = set()
self.status_cache = dict()
self.torrent_details_cache = dict()
self.peer_progress_cache = dict()
self.hosts_cache = dict()
self.geo_ips_cache = dict()
if gconfig.geoip1:
self.geo_ip = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
try:
self.geo_ip6 = GeoIP.open_type(GeoIP.GEOIP_COUNTRY_EDITION_V6, GeoIP.GEOIP_MEMORY_CACHE)
except AttributeError:
self.geo_ip6 = None
except GeoIP.error:
self.geo_ip6 = None
elif gconfig.geoip2:
self.geo_ip6 = None
try:
self.geo_ip = geoip2.database.Reader(gconfig.geoip2_database)
except Exception:
gconfig.geoip = False
# make sure there are no undefined values
self.wait_for_torrentlist_update()
self.requests['torrent-details'] = TransmissionRequest(self.url, server=self)
def update(self, delay, tag_waiting_for=0):
"""Maintain up-to-date data."""
tag_waiting_for_occurred = False
for request in list(self.requests.values()):
if time.time() - request.last_update >= delay:
request.last_update = time.time()
response = request.get_response()
if response['result'] == 'no open request':
request.send_request()
elif response['result'] == 'success':
tag = self.parse_response(response)
if tag == tag_waiting_for:
tag_waiting_for_occurred = True
return tag_waiting_for_occurred if tag_waiting_for else None
def parse_response(self, response):
def get_main_tracker_domain(torrent):
if torrent['trackerStats']:
trackers = sorted(torrent['trackerStats'],
key=operator.itemgetter('tier', 'id'))
return urllib.parse.urlparse(trackers[0]['announce']).hostname
# Trackerless torrents
return None
# response is a reply to torrent-get
if response['tag'] == self.TAG_TORRENT_LIST or response['tag'] == self.TAG_TORRENT_DETAILS:
for t in response['arguments']['torrents']:
t['uploadRatio'] = round(float(t['uploadRatio']), 2)
t['percentDone'] = percent(float(t['sizeWhenDone']),
float(t['haveValid'] t['haveUnchecked']))
t['available'] = t['desiredAvailable'] t['haveValid'] t['haveUnchecked']
if t['downloadDir'][-1] != '/':
t['downloadDir'] = '/'
try:
t['seeders'] = max([x['seederCount'] for x in t['trackerStats']])
t['leechers'] = max([x['leecherCount'] for x in t['trackerStats']])
except ValueError:
t['seeders'] = t['leechers'] = -1
t['isIsolated'] = not self.can_has_peers(t)
t['mainTrackerDomain'] = get_main_tracker_domain(t)
if t['mainTrackerDomain']:
self.trackers.add(t['mainTrackerDomain'])
self.locations.add(homedir2tilde(t['downloadDir']))
if self.rpc_version >= 16:
for l in t['labels']:
self.labels.add(l)
if response['tag'] == self.TAG_TORRENT_LIST:
self.torrent_cache = response['arguments']['torrents']
elif response['tag'] == self.TAG_TORRENT_DETAILS:
# torrent list may be empty sometimes after deleting
# torrents. no idea why and why the server sends us
# TAG_TORRENT_DETAILS, but just passing seems to help.(?)
try:
if len(response['arguments']['torrents']) > 1:
self.torrent_details_cache = response['arguments']['torrents']
else:
torrent_details = response['arguments']['torrents'][0]
torrent_details['pieces'] = base64.decodebytes(bytes(torrent_details['pieces'], gconfig.ENCODING))
self.torrent_details_cache = torrent_details
self.upgrade_peerlist()
except IndexError:
pass
elif response['tag'] == self.TAG_SESSION_STATS:
self.status_cache.update(response['arguments'])
elif response['tag'] == self.TAG_SESSION_GET:
self.status_cache.update(response['arguments'])
return response['tag']
def upgrade_peerlist(self):
for index, peer in enumerate(self.torrent_details_cache['peers']):
ip = peer['address']
peerid = ip self.torrent_details_cache['hashString']
# make sure peer cache exists
if peerid not in self.peer_progress_cache:
self.peer_progress_cache[peerid] = {
'last_progress': peer['progress'],
'last_update': time.time(),
'download_speed': 0,
'time_left': 0
}
this_peer = self.peer_progress_cache[peerid]
this_torrent = self.torrent_details_cache
# estimate how fast a peer is downloading
if peer['progress'] < 1:
this_time = time.time()
time_diff = this_time - this_peer['last_update']
progress_diff = peer['progress'] - this_peer['last_progress']
if this_peer['last_progress'] and progress_diff > 0 and time_diff > 5:
download_left = this_torrent['totalSize'] - \
(this_torrent['totalSize'] * peer['progress'])
downloaded = this_torrent['totalSize'] * progress_diff
this_peer['download_speed'] = \
norm.add(peerid ':download_speed', downloaded / time_diff, 10)
this_peer['time_left'] = download_left / this_peer['download_speed']
this_peer['last_update'] = this_time
# infrequent progress updates lead to increasingly inaccurate
# estimates, so we go back to <guessing>
elif time_diff > 60:
this_peer['download_speed'] = 0
this_peer['time_left'] = 0
this_peer['last_update'] = time.time()
this_peer['last_progress'] = peer['progress'] # remember progress
this_torrent['peers'][index].update(this_peer)
# resolve and locate peer's ip
if gconfig.rdns and ip not in self.hosts_cache:
threading.Thread(target=reverse_dns, args=(self.hosts_cache, ip), daemon=True).start()
if gconfig.geoip and ip not in self.geo_ips_cache:
self.geo_ips_cache[ip] = country_code_by_addr_vany(self.geo_ip, self.geo_ip6, ip)
def get_rpc_version(self):
return self.rpc_version
def get_global_stats(self):
return self.status_cache
def get_torrent_list(self, sort_orders):
def sort_value(value):
# Always return a string, so everything is comparable
if isinstance(value, (int, float)):
# 20 digits should be quite enough for anything (for now)
return "7.6f" % value
elif isinstance(value, str):
return value.lower()
else:
return str(value)
try:
for sort_order in sort_orders:
self.torrent_cache.sort(key=lambda x: sort_value(x[sort_order['name']]),
reverse=sort_order['reverse'])
except IndexError:
return []
return self.torrent_cache
def get_torrent_by_id(self, t_id):
i = 0
while self.torrent_cache[i]['id'] != t_id:
i = 1
return self.torrent_cache[i] if self.torrent_cache[i]['id'] == t_id else None
def get_torrent_details(self):
return self.torrent_details_cache
def set_torrent_details_id(self, t_id):
if isinstance(t_id, int) and t_id < 0:
self.requests['torrent-details'] = TransmissionRequest(self.url, server=self)
else:
self.requests['torrent-details'].set_request_data('torrent-get', self.TAG_TORRENT_DETAILS,
{'ids': t_id, 'fields': self.DETAIL_FIELDS})
def get_hosts(self):
return self.hosts_cache
def get_geo_ips(self):
return self.geo_ips_cache
def get_free_space(self):
request = TransmissionRequest(self.url, 'session-get', self.TAG_SESSION_GET, server=self)
request.send_request()
response = request.get_response()
path = response['arguments']['download-dir']
request = TransmissionRequest(self.url, 'free-space', 1, {'path': path}, server=self)
request.send_request()
response = request.get_response()
if 'size-bytes' in response['arguments']:
free = response['arguments']['size-bytes']
else:
free = 0
return free # free space in bytes
def set_option(self, option_name, option_value):
request = TransmissionRequest(self.url, 'session-set', 1, {option_name: option_value}, server=self)
request.send_request()
self.wait_for_status_update()
# torrent_id is -1 for global or a non-empty list of ids
def set_rate_limit(self, direction, new_limit, torrent_id=-1):
data = dict()
if new_limit <= -1:
new_limit = None
limit_enabled = False
else:
limit_enabled = True
if torrent_id == -1:
request_type = 'session-set'
data['speed-limit-' direction] = new_limit
data['speed-limit-' direction '-enabled'] = limit_enabled
else:
request_type = 'torrent-set'
data['ids'] = torrent_id
data[direction 'loadLimit'] = new_limit
data[direction 'loadLimited'] = limit_enabled
request = TransmissionRequest(self.url, request_type, 1, data, server=self)
request.send_request()
self.wait_for_torrentlist_update()
def set_seed_ratio(self, ratio, ids=-1):
data = dict()
if ratio == -1:
ratio = None
mode = 0 # Use global settings
elif ratio == 0:
ratio = None
mode = 2 # Seed regardless of ratio
elif ratio >= 0:
mode = 1 # Stop seeding at seedRatioLimit
else:
return
data['ids'] = ids
data['seedRatioLimit'] = ratio
data['seedRatioMode'] = mode
request = TransmissionRequest(self.url, 'torrent-set', 1, data, server=self)
request.send_request()
self.wait_for_torrentlist_update()
def toggle_honors_session_limits(self, torrent_ids):
if torrent_ids:
new_honors = not all([self.get_torrent_by_id(t)['honorsSessionLimits'] for t in torrent_ids])
request = TransmissionRequest(self.url, 'torrent-set', 1,
{'ids': torrent_ids, 'honorsSessionLimits': new_honors}, server=self)
request.send_request()
self.wait_for_torrentlist_update()
def increase_bandwidth_priority(self, torrent_ids):
if torrent_ids:
current = min([self.get_torrent_by_id(t)['bandwidthPriority'] for t in torrent_ids])
if current < 1:
request = TransmissionRequest(self.url, 'torrent-set', 1,
{'ids': torrent_ids, 'bandwidthPriority': current 1}, server=self)
request.send_request()
self.wait_for_torrentlist_update()
def decrease_bandwidth_priority(self, torrent_ids):
if torrent_ids:
current = max([self.get_torrent_by_id(t)['bandwidthPriority'] for t in torrent_ids])
if current > -1:
request = TransmissionRequest(self.url, 'torrent-set', 1,
{'ids': torrent_ids, 'bandwidthPriority': current - 1}, server=self)
request.send_request()
self.wait_for_torrentlist_update()
def move_queue(self, torrent_id, new_position):
args = {'ids': [torrent_id]}
if new_position in ('up', 'down', 'top', 'bottom'):
method_name = 'queue-move-' new_position
elif isinstance(new_position, int):
method_name = 'torrent-set'
args['queuePosition'] = min(max(new_position, 0), len(self.torrent_cache) - 1)
else:
raise ValueError("Is not up/down/top/bottom/<number>: %s" % new_position)
request = TransmissionRequest(self.url, method_name, 1, args, server=self)
request.send_request()
self.wait_for_torrentlist_update()
def toggle_turtle_mode(self):
self.set_option('alt-speed-enabled', not self.status_cache['alt-speed-enabled'])
def add_torrent(self, location, paused=False):
args = {'paused': paused}
try:
with open(location, 'rb') as fp:
args['metainfo'] = base64.b64encode(fp.read()).decode()
# If the file doesnt exist or we cant open it, then it is either a url or needs to
# be open by the server
except IOError:
args['filename'] = location
request = TransmissionRequest(self.url, 'torrent-add', 1, args, server=self)
request.send_request()
response = request.get_response()