forked from twistedfall/utorrentctl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utorrentctl.py
executable file
·1894 lines (1636 loc) · 65.3 KB
/
utorrentctl.py
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
#!/usr/bin/env python3
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser 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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
"""
utorrentctl - uTorrent cli remote control utility and library
"""
from hashlib import sha1
from collections import OrderedDict
import base64
import datetime
import email.generator
import errno
import http.client
import http.cookiejar
import json
import ntpath
import os.path
import posixpath
import re
import socket
import string
import time
import urllib.parse
import urllib.request
def url_quote( string ):
return urllib.parse.quote( string, "" )
def bdecode( data, str_encoding = "utf8" ):
if not hasattr( data, "__next__" ):
data = iter( data )
out = None
t = chr( next( data ) )
if t == "e": # end of list/dict
return None
elif t == "i": # integer
out = ""
c = chr( next( data ) )
while c != "e":
out += c
c = chr( next( data ) )
out = int( out )
elif t == "l": # list
out = []
while True:
e = bdecode( data )
if e == None:
break
out.append( e )
elif t == "d": # dictionary
out = {}
while True:
k = bdecode( data )
if k == None:
break
out[k] = bdecode( data )
elif t.isdigit(): # string
out = ""
l = t
c = chr( next( data ) )
while c != ":":
l += c
c = chr( next( data ) )
bout = bytearray()
for i in range( int( l ) ):
bout.append( next( data ) )
try:
out = bout.decode( str_encoding )
except UnicodeDecodeError:
out = bout
return out
def bencode( obj, str_encoding = "utf8" ):
out = bytearray()
t = type( obj )
if t == int:
out.extend( "i{}e".format( obj ).encode( str_encoding ) )
elif t == dict:
out.extend( b"d" )
for k in sorted( obj.keys() ):
out.extend( bencode( k ) )
out.extend( bencode( obj[k] ) )
out.extend( b"e" )
elif t in ( bytes, bytearray ):
out.extend( str( len( obj ) ).encode( str_encoding ) )
out.extend( b":" )
out.extend( obj )
elif is_list_type( obj ):
out.extend( b"l" )
for e in map( bencode, obj ):
out.extend( e )
out.extend( b"e" )
else:
obj = str( obj ).encode( str_encoding )
out.extend( str( len( obj ) ).encode( str_encoding ) )
out.extend( b":" )
out.extend( obj )
return bytes( out )
def _get_external_attrs( cls ):
return [ i for i in dir( cls ) if not re.search( "^_|_h$", i ) and not hasattr( getattr( cls, i ), "__call__" ) ]
def is_list_type( obj ):
return hasattr( obj, "__iter__" ) and not isinstance( obj, ( str, bytes ) );
class uTorrentError( Exception ):
pass
class Version:
product = ""
major = 0
middle = 0
minor = 0
build = 0
engine = 0
ui = 0
date = None
user_agent = ""
peer_id = ""
device_id = ""
@staticmethod
def detect_from_settings( settings ):
out = Version( settings )
falcon = False
for setting in settings["settings"]:
if setting[0] == "webui.uconnect_enable": # only Falcon has this setting
falcon = True
out.major = 3
out.middle = 0
out.minor = 0
break
if not falcon:
out.major = 2
out.middle = 2
out.minor = 0
out.user_agent = "BTWebClient/{}{}{}0({})".format( out.major, out.middle, out.minor, out.build )
out.peer_id = "UT{}{}{}0".format( out.major, out.middle, out.minor )
return out
def __init__( self, res ):
if "version" in res: # server returns full data
self.product = res["version"]["product_code"]
self.major = res["version"]["major_version"]
self.middle = 0
self.minor = res["version"]["minor_version"]
self.build = res["build"]
self.engine = res["version"]["engine_version"]
self.ui = res["version"]["ui_version"]
date = res["version"]["version_date"].split( " " )
self.date = datetime.datetime( *map( int, date[0].split( "-" ) + date[1].split( ":" ) ) )
self.user_agent = res["version"]["user_agent"]
self.peer_id = res["version"]["peer_id"]
self.device_id = res["version"]["device_id"]
elif "build" in res:
# fill some partially made up values as desktop client doesn't provide full info, only build
self.product = "desktop"
self.build = self.engine = self.ui = res["build"]
else:
raise uTorrentError( "Cannot detect version from the supplied server response" )
def __str__( self ):
return self.user_agent
def verbose_str( self ):
return "{} {}/{} {} v{}.{}.{}.{}, engine v{}, ui v{}".format(
self.user_agent, self.device_id, self.peer_id, self.product,
self.major, self.middle, self.minor, self.build, self.engine, self.ui
)
class TorrentStatus:
_progress = 0
_value = 0
started = False
checking = False
start_after_check = False
checked = False
error = False
paused = False
queued = False # queued == False means forced
loaded = False
def __init__( self, status, percent_loaded = 0 ):
self._value = status
self._progress = percent_loaded
self.started = bool( status & 1 )
self.checking = bool( status & 2 )
self.start_after_check = bool( status & 4 )
self.checked = bool( status & 8 )
self.error = bool( status & 16 )
self.paused = bool( status & 32 )
self.queued = bool( status & 64 )
self.loaded = bool( status & 128 )
# http://forum.utorrent.com/viewtopic.php?pid=381527#p381527
def __str__( self ):
if not self.loaded:
return "Not loaded"
if self.error:
return "Error"
if self.checking:
return "Checked {:.1f}%".format( self._progress )
if self.paused:
if self.queued:
return "Paused"
else:
return "[F] Paused"
if self._progress == 100:
if self.queued:
if self.started:
return "Seeding"
else:
return "Queued Seed"
else:
if self.started:
return "[F] Seeding"
else:
return "Finished"
else: # self._progress < 100
if self.queued:
if self.started:
return "Downloading"
else:
return "Queued"
else:
if self.started:
return "[F] Downloading"
# else:
# return "Stopped"
return "Stopped"
def __lt__( self, other ):
return self._value < other._value
class Torrent:
_utorrent = None
hash = ""
status = None
name = ""
size = 0
size_h = ""
progress = 0. # in percent
downloaded = 0
downloaded_h = ""
uploaded = 0
uploaded_h = ""
ratio = 0.
ul_speed = 0
ul_speed_h = ""
dl_speed = 0
dl_speed_h = ""
eta = 0
eta_h = ""
label = ""
peers_connected = 0
peers_total = 0
seeds_connected = 0
seeds_total = 0
availability = 0
availability_h = ""
queue_order = 0
dl_remain = 0
dl_remain_h = ""
_default_format = "{hash} {status} {progress}% {size} {dl_speed} {ul_speed} {ratio} {peer_info} eta: {eta} {name} {label}"
_default_format_specs = {
"status" : "{status: <15}",
"name" : "{name: <60}",
"size" : "{size_h: >9}",
"progress" : "{progress: >5.1f}",
"downloaded" : "{downloaded_h: >9}",
"uploaded" : "{uploaded_h: >9}",
"ratio" : "{ratio: <6.2f}",
"dl_speed" : "{dl_speed_h: >12}",
"ul_speed" : "{ul_speed_h: >12}",
"eta" : "{eta_h: <7}",
"label" : "{label}",
"peers_connected" : "{peers_connected: <4}",
"peers_total" : "{peers_total: <5}",
"seeds_connected" : "{seeds_connected: <4}",
"seeds_total" : "{seeds_total: <5}",
"peer_info" : "{peer_info: <7}",
"availability" : "{availability_h: >5.2}",
"dl_remain" : "{dl_remain_h: >9}",
}
def __init__( self, utorrent, torrent = None ):
self._utorrent = utorrent
if torrent:
self.fill( torrent )
def __str__( self ):
return "{} {}".format( self.hash, self.name )
def _process_format( self, format_string ):
out = []
args = dict( self.__dict__ )
args["peer_info"] = ( "{peers_connected}/{peers_total}" if args["progress"] == 100 else "{seeds_connected}/{seeds_total}" ).format( **args )
args["label"] = "({label})".format( **args ) if args["label"] != "" else ""
if args["dl_speed"] < 1024:
args["dl_speed_h"] = ""
if args["ul_speed"] < 1024:
args["ul_speed_h"] = ""
if args["dl_remain"] == 0:
args["dl_remain_h"] = ""
formatter = string.Formatter()
for literal_text, field_name, format_spec, conversion in formatter.parse( format_string ):
elem = { "before" : literal_text, "value" : "" }
if field_name != None:
def_field_name, def_format_spec, def_conversion = None, " <20", None
if field_name in self._default_format_specs:
def_field_name, def_format_spec, def_conversion = next( formatter.parse( self._default_format_specs[field_name] ) )[1:4]
val = formatter.get_field( field_name if def_field_name == None else def_field_name, None, args )[0]
val = formatter.convert_field( val, conversion if conversion != None else def_conversion )
val = formatter.format_field( val, format_spec if format_spec != "" else def_format_spec )
elem["value"] = val
out.append( elem )
return out
def _format_to_str( self, format_res ):
out = ""
for i in format_res:
out += i["before"] + i["value"]
return out.strip()
def verbose_str( self, format_string = None ):
return self._format_to_str( self._process_format( self._default_format if format_string == None else format_string ) )
def fill( self, torrent ):
self.hash, status, self.name, self.size, progress, self.downloaded, \
self.uploaded, ratio, self.ul_speed, self.dl_speed, self.eta, self.label, \
self.peers_connected, self.peers_total, self.seeds_connected, self.seeds_total, \
self.availability, self.queue_order, self.dl_remain = torrent
self._utorrent.check_hash( self.hash )
self.progress = progress / 10.
self.ratio = ratio / 1000.
self.status = TorrentStatus( status, self.progress )
self.size_h = uTorrent.human_size( self.size )
self.uploaded_h = uTorrent.human_size( self.uploaded )
self.downloaded_h = uTorrent.human_size( self.downloaded )
self.ul_speed_h = uTorrent.human_size( self.ul_speed ) + "/s"
self.dl_speed_h = uTorrent.human_size( self.dl_speed ) + "/s"
self.eta_h = uTorrent.human_time_delta( self.eta )
self.availability_h = self.availability / 65535.
self.dl_remain_h = uTorrent.human_size( self.dl_remain )
@classmethod
def get_readonly_attrs( cls ):
return tuple( set( _get_external_attrs( cls ) ) - set( ( "label", ) ) )
@classmethod
def get_public_attrs( cls ):
return tuple( set( _get_external_attrs( cls ) ) - set( cls.get_readonly_attrs() ) )
def info( self ):
return self._utorrent.torrent_info( self )
def file_list( self ):
return self._utorrent.file_list( self )
def start( self, force = False ):
return self._utorrent.torrent_start( self, force )
def stop( self ):
return self._utorrent.torrent_stop( self )
def pause( self ):
return self._utorrent.torrent_pause( self )
def resume( self ):
return self._utorrent.torrent_resume( self )
def recheck( self ):
return self._utorrent.torrent_recheck( self )
def remove( self, with_data = False ):
return self._utorrent.torrent_remove( self, with_data )
class Torrent_API2( Torrent ):
url = ""
rss_url = ""
status_message = ""
_unk_hash = ""
added_on = 0
completed_on = 0
_unk_str = 0
download_dir = ""
def __init__( self, utorrent, torrent = None ):
Torrent.__init__( self, utorrent, torrent )
self._default_format_specs["status"] = "{status_message: <15}"
self._default_format_specs["completed_on"] = "{completed_on!s}"
self._default_format_specs["added_on"] = "{added_on!s}"
def fill( self, torrent ):
Torrent.fill( self, torrent[0:19] )
self.url, self.rss_url, self.status_message, self._unk_hash, self.added_on, \
self.completed_on, self._unk_str, self.download_dir = torrent[19:27]
self.added_on = datetime.datetime.fromtimestamp( self.added_on )
self.completed_on = datetime.datetime.fromtimestamp( int( self.completed_on ) )
def remove( self, with_data = False, with_torrent = False ):
return self._utorrent.torrent_remove( self, with_data, with_torrent )
class Label:
name = ""
torrent_count = 0
def __init__( self, label ):
self.name, self.torrent_count = label
def __str__( self ):
return "{} ({})".format( self.name, self.torrent_count )
class Priority:
value = 0
def __init__( self, priority ):
priority = int( priority )
if priority in range( 4 ):
self.value = priority
else:
self.value = 2
def __str__( self ):
if self.value == 0:
return "don't download"
elif self.value == 1:
return "low priority"
elif self.value == 2:
return "normal priority"
elif self.value == 3:
return "high priority"
else:
return "unknown priority"
class File:
_utorrent = None
_parent_hash = ""
index = 0
hash = ""
name = ""
size = 0
size_h = ""
downloaded = 0
downloaded_h = ""
priority = None
progress = 0.
def __init__( self, utorrent, parent_hash, index, file = None ):
self._utorrent = utorrent
self._utorrent.check_hash( parent_hash )
self._parent_hash = parent_hash
self.index = index
self.hash = "{}.{}".format( self._parent_hash, self.index )
if file:
self.fill( file )
def __str__( self ):
return "{} {}".format( self.hash, self.name )
def verbose_str( self ):
return "{: <44} [{: <15}] {: >5}% ({: >9} / {: >9}) {}".format( self.hash, self.priority, self.progress, \
self.downloaded_h, self.size_h, self.name )
def fill( self, file ):
self.name, self.size, self.downloaded, priority = file[:4]
self.priority = Priority( priority )
if self.size == 0:
self.progress = 100
else:
self.progress = round( float( self.downloaded ) / self.size * 100, 1 )
self.size_h = uTorrent.human_size( self.size )
self.downloaded_h = uTorrent.human_size( self.downloaded )
def set_priority( self, priority ):
self._utorrent.file_set_priority( { self.hash : priority } )
class File_API2( File ):
def fill( self, file ):
File.fill( self, file[:4] )
class JobInfo:
_utorrent = None
hash = ""
trackers = []
ulrate = 0
ulrate_h = ""
dlrate = 0
dlrate_h = ""
superseed = 0
dht = 0
pex = 0
seed_override = 0
seed_ratio = 0
seed_time = 0
def __init__( self, utorrent, hash = None, jobinfo = None ):
self._utorrent = utorrent
self.hash = hash
if jobinfo:
self.fill( jobinfo )
def __str__( self ):
return "Limits D:{} U:{}".format( self.dlrate, self.ulrate )
def verbose_str( self ):
return str( self ) + " Superseed:{} DHT:{} PEX:{} Queuing override:{} Seed ratio:{} Seed time:{}".format(
self._tribool_status_str( self.superseed ), self._tribool_status_str( self.dht ),
self._tribool_status_str( self.pex ), self._tribool_status_str( self.seed_override ), self.seed_ratio,
uTorrent.human_time_delta( self.seed_time )
)
def fill( self, jobinfo ):
self.hash = jobinfo["hash"]
self.trackers = jobinfo["trackers"].strip().split( "\r\n\r\n" )
self.ulrate = jobinfo["ulrate"]
self.ulrate_h = uTorrent.human_size( self.ulrate ) + "/s"
self.dlrate = jobinfo["dlrate"]
self.dlrate_h = uTorrent.human_size( self.dlrate ) + "/s"
self.superseed = jobinfo["superseed"]
self.dht = jobinfo["dht"]
self.pex = jobinfo["pex"]
self.seed_override = jobinfo["seed_override"]
self.seed_ratio = jobinfo["seed_ratio"]
self.seed_time = jobinfo["seed_time"]
@classmethod
def get_public_attrs( cls ):
return _get_external_attrs( cls )
def _tribool_status_str( self, status ):
return "not allowed" if status == -1 else ( "disabled" if status == 0 else "enabled" )
class RssFeedEntry:
name = ""
name_full = ""
url = ""
quality = 0
codec = 0
timestamp = 0
season = 0
episode = 0
episode_to = 0
feed_id = 0
repack = False
in_history = False
def __init__( self, entry ):
self.fill( entry )
def __str__( self ):
return "{}".format( self.name )
def verbose_str( self ):
return "{} {}".format( '*' if self.in_history else ' ', self.name_full )
def fill( self, entry ):
self.name, self.name_full, self.url, self.quality, self.codec, self.timestamp, self.season, self.episode, \
self.episode_to, self.feed_id, self.repack, self.in_history = entry
try:
self.timestamp = datetime.datetime.fromtimestamp( self.timestamp )
except ValueError: # utorrent 2.2 sometimes gives too large timestamp
pass
class RssFeed:
id = 0
enabled = False
use_feed_title = False
user_selected = False
programmed = False
download_state = 0
url = ""
next_update = 0
entries = None
def __init__( self, feed ):
self.fill( feed )
def __str__( self ):
return "{: <3} {: <3} {}".format( self.id, "on" if self.enabled else "off", self.url )
def verbose_str( self ):
return "{} ({}/{}) update: {}".format(
str( self ), len( [ x for x in self.entries if x.in_history ] ), len( self.entries ), self.next_update
)
def fill( self, feed ):
self.id, self.enabled, self.use_feed_title, self.user_selected, self.programmed, \
self.download_state, self.url, self.next_update = feed[0:8]
self.next_update = datetime.datetime.fromtimestamp( self.next_update )
self.entries = []
for e in feed[8]:
self.entries.append( RssFeedEntry( e ) )
@classmethod
def get_readonly_attrs( cls ):
return ( "id", "use_feed_title", "user_selected", "programmed", "download_state", "next_update", "entries" )
@classmethod
def get_writeonly_attrs( cls ):
return ( "download_dir", "alias", "subscribe", "smart_filter" )
@classmethod
def get_public_attrs( cls ):
return tuple( set( _get_external_attrs( cls ) ) - set( cls.get_readonly_attrs() ) )
class RssFilter:
id = 0
flags = 0
name = ""
filter = None
not_filter = None
save_in = ""
feed_id = 0
quality = 0
label = ""
postpone_mode = False
last_match = 0
smart_ep_filter = 0
repack_ep_filter = 0
episode = ""
episode_filter = False
resolving_candidate = False
def __init__( self, filter_props ):
self.fill( filter_props )
def __str__( self ):
return "{: <3} {: <3} {}".format( self.id, "on" if self.enabled else "off", self.name )
def verbose_str( self ):
return "{} {} -> {}: +{}-{}".format( str( self ), self.filter, self.save_in, self.filter, \
self.not_filter )
def fill( self, filter_props ):
self.id, self.flags, self.name, self.filter, self.not_filter, self.save_in, self.feed_id, \
self.quality, self.label, self.postpone_mode, self.last_match, self.smart_ep_filter, \
self.repack_ep_filter, self.episode, self.episode_filter, self.resolving_candidate = filter_props
self.postpone_mode = bool( self.postpone_mode )
@classmethod
def get_readonly_attrs( cls ):
return ( "id", "flags", "last_match", "resolving_candidate", "enabled" )
@classmethod
def get_writeonly_attrs( cls ):
return ( "prio", "add_stopped" )
@classmethod
def get_public_attrs( cls ):
return tuple( set( _get_external_attrs( cls ) ) - set( cls.get_readonly_attrs() ) )
@property
def enabled( self ):
return bool( self.flags & 1 )
class uTorrentConnection( http.client.HTTPConnection ):
_host = ""
_login = ""
_password = ""
_request = None
_cookies = http.cookiejar.CookieJar()
_token = ""
_retry_max = 3
_utorrent = None
@property
def request_obj( self ):
return self._request
def __init__( self, host, login, password ):
self._host = host
self._login = login
self._password = password
self._url = "http://{}/".format( self._host )
self._request = urllib.request.Request( self._url )
self._request.add_header( "Authorization", "Basic " + base64.b64encode( "{}:{}".format( self._login, self._password ).encode( "latin1" ) ).decode( "ascii" ) )
http.client.HTTPConnection.__init__( self, self._request.host, timeout = 10 )
self._fetch_token()
def _make_request( self, loc, headers, data = None, retry = True ):
last_e = None
utserver_retry = False
retries = 0
max_retries = self._retry_max if retry else 1
try:
while retries < max_retries or utserver_retry:
try:
self._request.add_data( data )
self.request( self._request.get_method(), self._request.get_selector() + loc, self._request.get_data(), headers )
resp = self.getresponse()
if resp.status == 400:
last_e = uTorrentError( resp.read().decode( "utf8" ).strip() )
# if uTorrent server alpha is bound to the same port as WebUI then it will respond with "invalid request" to the first request in the connection
# apparently this is no longer the case, TODO: remove this hack
if ( not self._utorrent or type( self._utorrent ) == uTorrentLinuxServer ) and not utserver_retry:
utserver_retry = True
continue
raise last_e
elif resp.status == 404 or resp.status == 401:
raise uTorrentError( "Request {}: {}".format( loc, resp.reason ) )
elif resp.status != 200:
raise uTorrentError( "{}: {}".format( resp.reason, resp.status ) )
self._cookies.extract_cookies( resp, self._request )
if len( self._cookies ) > 0:
self._request.add_header( "Cookie", "; ".join( [ "{}={}".format( url_quote( c.name ), url_quote( c.value ) ) for c in self._cookies ] ) )
return resp
# retry when utorrent returns bad data
except ( http.client.CannotSendRequest, http.client.BadStatusLine ) as e:
last_e = e
self.close()
# socket errors
except socket.error as e:
# retry on timeout
if str( e ) == "timed out": # some peculiar handling for timeout error
last_e = uTorrentError( "Timeout after {} tries".format( max_retries ) )
self.close()
# retry after pause on specific windows errors
elif e.errno == 10053 or e.errno == 10054:
# Windows specific socket errors:
# 10053 - An established connection was aborted by the software in your host machine
# 10054 - An existing connection was forcibly closed by the remote host
last_e = e
self.close()
time.sleep( 2 )
elif e.errno == errno.ECONNREFUSED or e.errno == errno.ECONNRESET:
raise uTorrentError( e.strerror )
else:
raise e
# name resolution failed
except socket.gaierror as e:
raise uTorrentError( e.strerror )
retries += 1
if last_e:
raise last_e
except Exception as e:
self.close()
raise e
return None
def _get_data( self, loc, data = None, retry = True, save_buffer = None, progress_cb = None ):
headers = { k : v for k, v in self._request.header_items() }
if data:
bnd = email.generator._make_boundary( data )
headers["Content-Type"] = "multipart/form-data; boundary={}".format( bnd )
data = data.replace( "{{BOUNDARY}}", bnd )
resp = self._make_request( loc, headers, data, retry )
if save_buffer:
read = 0
resp_len = resp.length
while True:
buf = resp.read( 10240 )
read += len( buf )
if progress_cb:
progress_cb( read, resp_len )
if len( buf ) == 0:
break
save_buffer.write( buf )
self.close()
return None
out = resp.read().decode( "utf8" )
self.close()
return out
def _fetch_token( self ):
data = self._get_data( "gui/token.html" )
match = re.search( "<div .*?id='token'.*?>(.+?)</div>", data )
if match == None:
raise uTorrentError( "Can't fetch security token" )
self._token = match.group( 1 )
def _action_val( self, val ):
if isinstance( val, bool ):
val = int( val )
return str( val )
def _action( self, action, params = None, params_str = None ):
args = []
if params:
for k, v in params.items():
if is_list_type( v ):
for i in v:
args.append( "{}={}".format( url_quote( str( k ) ), url_quote( self._action_val( i ) ) ) )
else:
args.append( "{}={}".format( url_quote( str( k ) ), url_quote( self._action_val( v ) ) ) )
if params_str:
params_str = "&" + params_str
else:
params_str = ""
if action == "list":
args.insert( 0, "token=" + self._token )
args.insert( 1, "list=1" )
section = "gui/"
elif action == "proxy":
section = "proxy"
else:
args.insert( 0, "token=" + self._token )
args.insert( 1, "action=" + url_quote( str( action ) ) )
section = "gui/"
return section + "?" + "&".join( args ) + params_str
def do_action( self, action, params = None, params_str = None, data = None, retry = True, save_buffer = None, progress_cb = None ):
# uTorrent can send incorrect overlapping array objects, this will fix them, converting them to list
def obj_hook( obj ):
out = {}
for k, v in obj:
if k in out:
out[k].extend( v )
else:
out[k] = v
return out
res = self._get_data( self._action( action, params, params_str ), data = data, retry = retry, save_buffer = save_buffer, progress_cb = progress_cb )
if res:
return json.loads( res, object_pairs_hook = obj_hook )
else:
return ""
def utorrent( self, api = None ):
if api == "linux":
return uTorrentLinuxServer( self )
elif api == "desktop":
return uTorrent( self )
elif api == "falcon":
return uTorrentFalcon( self )
else: # auto-detect
try:
ver = Version( self.do_action( "getversion", retry = False ) )
except uTorrentError as e:
if e.args[0] == "invalid request": # windows desktop uTorrent client
ver = Version.detect_from_settings( self.do_action( "getsettings" ) )
else:
raise e
if ver.product == "server":
return uTorrentLinuxServer( self, ver )
elif ver.product == "desktop":
if ver.major == 3:
return uTorrentFalcon( self, ver )
else:
return uTorrent( self, ver )
else:
raise uTorrentError( "Unsupported WebUI API" )
class uTorrent:
_url = ""
_connection = None
_version = None
_TorrentClass = Torrent
_JobInfoClass = JobInfo
_FileClass = File
_pathmodule = ntpath
_list_cache_id = 0
_torrent_cache = None
_rssfeed_cache = None
_rssfilter_cache = None
api_version = 1 # http://user.utorrent.com/community/developers/webapi
@property
def TorrentClass( self ):
return self._TorrentClass
@property
def JobInfoClass( self ):
return self._JobInfoClass
@property
def pathmodule( self ):
return self._pathmodule
def __init__( self, connection, version = None ):
self._connection = connection
self._connection._utorrent = self
self._version = version
@staticmethod
def _setting_val( value_type, value ):
# Falcon incorrectly sends type 0 and empty string for some fields (e.g. boss_pw and boss_key_salt)
if value_type == 0 and value != '': # int
return int( value )
elif value_type == 1 and value != '': # bool
return value == "true"
else:
return value
@staticmethod
def human_size( size, suffixes = ( "B", "kiB", "MiB", "GiB", "TiB" ) ):
for s in suffixes:
if size < 1024:
if s == suffixes[0]:
return "{}{}".format( round( size, 0 ), s )
else:
return "{:.2f}{}".format( round( size, 2 ), s )
if s != suffixes[-1]:
size /= 1024.
return "{:.2f}{}".format( round( size, 2 ), suffixes[-1] )
@staticmethod
def human_time_delta( seconds, max_elems = 2 ):
if seconds == -1:
return "inf"
out = []
reducer = ( ( 60 * 60 * 24 * 7, "w" ), ( 60 * 60 * 24, "d" ), ( 60 * 60, "h" ), ( 60, "m" ), ( 1, "s" ) )
for d, c in reducer:
v = int( seconds / d )
seconds -= d * v
if v or len( out ) > 0:
out.append( "{}{}".format( v, c ) )
if len( out ) == max_elems:
break
if len( out ) == 0:
out.append( "0{}".format( reducer[-1][1] ) )
return " ".join( out )
@staticmethod
def is_hash( torrent_hash ):
return re.match( "[0-9A-F]{40}$", torrent_hash, re.IGNORECASE )
@staticmethod
def get_info_hash( torrent_data ):
return sha1( bencode( bdecode( torrent_data )["info"] ) ).hexdigest().upper()
@classmethod
def check_hash( cls, torrent_hash ):
if not cls.is_hash( torrent_hash ):
raise uTorrentError( "Incorrect hash: {}".format( torrent_hash ) )
@classmethod
def parse_hash_prop( cls, hash_prop ):
if isinstance( hash_prop, ( File, Torrent, JobInfo ) ):
hash_prop = hash_prop.hash
try:
parent_hash, prop = hash_prop.split( ".", 1 )
except ValueError:
parent_hash, prop = hash_prop, None
parent_hash = parent_hash.upper()
cls.check_hash( parent_hash )
return parent_hash, prop
def resolve_torrent_hashes( self, hashes, torrent_list = None ):
out = []