forked from twistedfall/utorrentctl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utorrentctl.py
executable file
·1648 lines (1409 loc) · 54.8 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
"""
import urllib.request, http.client, http.cookiejar, urllib.parse, socket
import base64, posixpath, ntpath, email.generator, os.path, datetime, errno
from hashlib import sha1
import re, json
def url_quote( string ):
return urllib.parse.quote( string, "" )
try:
from config import utorrentcfg
except ImportError:
utorrentcfg = { "host" : None, "login" : None, "password" : None }
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 = ""
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"]
else:
# 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"]
build_versions = ( ( 23217, 3, 0, 0 ), ( 23071, 2, 2, 0 ), ( 0, 2, 0, 4 ) )
for version in build_versions:
if self.build >= version[0]:
self.major, self.middle, self.minor = version[1:]
break
self.user_agent = "BTWebClient/{}{}{}0({})".format( self.major, self.middle, self.minor, self.build )
self.peer_id = "UT{}{}{}0".format( self.major, self.middle, self.minor )
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
queue_order = 0
dl_remain = 0
def __init__( self, utorrent, torrent = None ):
self._utorrent = utorrent
if torrent:
self.fill( torrent )
def __str__( self ):
return "{} {}".format( self.hash, self.name )
def verbose_str( self ):
return "{} {: <15} {: >5.1f}% {: >9} D:{: >14} U:{: >14} {: <8.3f} {: <9} eta: {: <7} {}{}".format(
self.hash, self.status, self.progress, self.size_h,
self.dl_speed_h if self.dl_speed > 0 else "", self.ul_speed_h if self.ul_speed > 0 else "",
self.ratio, "{}({})/{}".format( self.seeds_connected, self.seeds_total, self.peers_connected ),
self.eta_h, self.name, " ({})".format( self.label ) if self.label else ""
)
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 )
@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
_unk_num = 0
_unk_str = 0
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._unk_num, self._unk_str = torrent[19:]
self.added_on = datetime.datetime.fromtimestamp( self.added_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
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
dlrate = 0
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.dlrate = jobinfo["dlrate"]
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 ):
self.fill( filter )
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 ):
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
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 _get_data( self, loc, data = None, retry = True, save_buffer = None, progress_cb = None ):
last_e = None
utserver_retries = 0
retries = 0
max_retries = self._retry_max if retry else 1
while retries < max_retries or utserver_retries == 1:
try:
headers = { k : v for k, v in self._request.header_items() }
if data:
bnd = email.generator._make_boundary()
headers["Content-Type"] = "multipart/form-data; boundary={}".format( bnd )
data = data.replace( "{{BOUNDARY}}", bnd )
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 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 )
return None
out = resp.read().decode( "utf8" )
if resp.status == 400:
last_e = uTorrentError( out.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
if ( not self._utorrent or type( self._utorrent ) == uTorrentLinuxServer ) and utserver_retries == 0:
utserver_retries += 1
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 out
except socket.gaierror as e:
raise uTorrentError( e.args[1] )
except socket.error as e:
e = e.args[0]
if str( e ) == "timed out":
last_e = uTorrentError( "Timeout" )
elif e.args[0] == errno.ECONNREFUSED:
self.close()
raise uTorrentError( e.args[1] )
except ( http.client.CannotSendRequest, http.client.BadStatusLine ) as e:
self.close()
raise e
retries += 1
if last_e:
self.close()
raise last_e
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=" + url_quote( self._token ) )
args.insert( 1, "list=1" )
section = "gui/"
elif action == "proxy":
section = "proxy"
else:
args.insert( 0, "token=" + url_quote( 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 ):
try:
ver = Version( self.do_action( "getversion", retry = False ) )
except http.client.BadStatusLine:
return uTorrent( self )
except uTorrentError as e:
if e.args[0] == "invalid request":
return uTorrentFalcon( self )
if ver.product == "server":
return uTorrentLinuxServer( self, ver )
else:
raise uTorrentError( "Unsupported WebAPI" )
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://forum.utorrent.com/viewtopic.php?id=25661
@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( type, value ):
# Falcon incorrectly sends type 0 and empty string for some fields (e.g. boss_pw and boss_key_salt)
if type == 0 and value != '': # int
return int( value )
elif 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:
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( hash ):
return re.match( "[0-9A-F]{40}$", hash, re.IGNORECASE )
@staticmethod
def get_info_hash( torrent_data ):
return sha1( bencode( bdecode( torrent_data )["info"] ) ).hexdigest().upper()
@classmethod
def check_hash( cls, hash ):
if not cls.is_hash( hash ):
raise uTorrentError( "Incorrect hash: {}".format( 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 = []
if torrent_list == None:
torrent_list = self.torrent_list()
for h in hashes:
if h in torrent_list:
out.append( torrent_list[h].name )
return out
def resolve_feed_ids( self, ids, rss_list = None ):
out = []
if rss_list == None:
rss_list = utorrent.rss_list()
for id in ids:
if int( id ) in rss_list:
out.append( rss_list[int( id )].url )
return out
def resolve_filter_ids( self, ids, filter_list = None ):
out = []
if filter_list == None:
filter_list = utorrent.rssfilter_list()
for id in ids:
if int( id ) in filter_list:
out.append( filter_list[int( id )].name )
return out
def _create_torrent_upload( self, torrent_data, torrent_filename ):
out = "\r\n".join( (
"--{{BOUNDARY}}",
'Content-Disposition: form-data; name="torrent_file"; filename="{}"'.format( url_quote( torrent_filename ) ),
"Content-Type: application/x-bittorrent",
"",
torrent_data.decode( "latin1" ),
"--{{BOUNDARY}}",
"",
) )
return out
def _get_hashes( self, torrents ):
if not is_list_type( torrents ):
torrents = ( torrents, )
out = []
for t in torrents:
if isinstance( t, self._TorrentClass ):
hash = t.hash
elif isinstance( t, str ):
hash = t
else:
raise uTorrentError( "Hash designation only supported via Torrent class or string" )
self.check_hash( hash )
out.append( hash )
return out
def _handle_download_dir( self, download_dir ):
out = None
if download_dir:
out = self.settings_get()["dir_active_download"]
if not self._pathmodule.isabs( download_dir ):
download_dir = out + self._pathmodule.sep + download_dir
self.settings_set( { "dir_active_download" : download_dir } )
return out
def _handle_prev_dir( self, prev_dir ):
if prev_dir:
self.settings_set( { "dir_active_download" : prev_dir } )
def do_action( self, action, params = None, params_str = None, data = None, retry = True, save_buffer = None, progress_cb = None ):
return self._connection.do_action( action = action, params = params, params_str = params_str, data = data, retry = retry, save_buffer = save_buffer, progress_cb = progress_cb )
def version( self ):
if not self._version:
self._version = Version( self.do_action( "start" ) )
return self._version
def _fetch_torrent_list( self ):
if self._list_cache_id:
out = self.do_action( "list", { "cid" : self._list_cache_id } )
# torrents
for t in out["torrentm"]:
del self._torrent_cache[t]
for t in out["torrentp"]:
self._torrent_cache[t[0]] = t
# feeds
for r in out["rssfeedm"]:
del self._rssfeed_cache[r]
for r in out["rssfeedp"]:
self._rssfeed_cache[r[0]] = r
# filters
for f in out["rssfilterm"]:
del self._rssfilter_cache[f]
for f in out["rssfilterp"]:
self._rssfilter_cache[f[0]] = f
else:
out = self.do_action( "list" )
self._torrent_cache = { hash : torrent for hash, torrent in [ ( t[0], t ) for t in out["torrents"] ] }
self._rssfeed_cache = { id : feed for id, feed in [ ( r[0], r ) for r in out["rssfeeds"] ] }
self._rssfilter_cache = { id : filter for id, filter in [ ( f[0], f ) for f in out["rssfilters"] ] }
self._list_cache_id = out["torrentc"]
return out
def torrent_list( self, labels = None, rss_feeds = None, rss_filters = None ):
res = self._fetch_torrent_list()
out = { h : self._TorrentClass( self, t ) for h, t in self._torrent_cache.items() }
if labels != None:
labels.extend( [ Label( i ) for i in res["label"] ] )
if rss_feeds != None:
for id, feed in self._rssfeed_cache.items():
rss_feeds[id] = RssFeed( feed )
if rss_filters != None:
for id, filter in self._rssfilter_cache.items():
rss_filters[id] = RssFilter( filter )
return out
def torrent_info( self, torrents ):
res = self.do_action( "getprops", { "hash" : self._get_hashes( torrents ) } )
if not "props" in res:
return {}
return { hash : info for hash, info in [ ( i["hash"], self._JobInfoClass( self, jobinfo = i ) ) for i in res["props"] ] }
def torrent_add_url( self, url, download_dir = None ):
prev_dir = self._handle_download_dir( download_dir )
res = self.do_action( "add-url", { "s" : url } );
self._handle_prev_dir( prev_dir )
if "error" in res:
raise uTorrentError( res["error"] )
if url[0:7] == "magnet:":
m = re.search( "urn:btih:([0-9A-F]{40})", url, re.IGNORECASE )
if m: