/
Aria2JsonRpc.py
948 lines (673 loc) · 20.1 KB
/
Aria2JsonRpc.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
#!/usr/bin/env python3
# -*- coding: utf8 -*-
# Copyright (C) 2012-2014 Xyne
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# (version 2) as published by the Free Software Foundation.
#
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import base64
import http.client
import json
import urllib.parse
import urllib.request
import ssl
################################## Constants ###################################
DEFAULT_PORT = 6800
SERVER_URI_FORMAT = '{}://{}:{:d}/jsonrpc'
############################ Convenience Functions #############################
def to_json_list(obj):
'''
Wrap strings in lists. Other iterables are converted to lists directly.
'''
if isinstance(objs, str):
return [objs]
elif not isinstance(objs, list):
return list(objs)
else:
return objs
def add_options_and_position(params, options=None, position=None):
'''
Convenience method for adding options and position to parameters.
'''
if options:
params.append(options)
if position:
if not isinstance(position, int):
try:
position = int(position)
except ValueError:
position = -1
if position >= 0:
params.append(position)
return params
################## From python3-aur's ThreadedServers.common ###################
def format_bytes(size):
"""Format bytes for inferior humans."""
if size < 0x400:
return '{:d} B'.format(size)
else:
size = float(size) / 0x400
for prefix in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB'):
if size < 0x400:
return '{:0.02f} {}'.format(size, prefix)
else:
size /= 0x400
return '{:0.02f} YiB'.format(size)
def format_seconds(s):
'''Format seconds for inferior humans.'''
string = ''
for base, char in (
(60, 's'),
(60, 'm'),
(24, 'h')
):
s, r = divmod(s, base)
if s == 0:
return '{:d}{}{}'.format(r, char, string)
elif r != 0:
string = '{:02d}{}{}'.format(r, char, string)
else:
return '{:d}d{}'.format(s, string)
############################## Aria2JsonRpc Class ##############################
class Aria2JsonRpc(object):
# TODO: certificate options, etc.
def __init__(
self, ID, uri,
mode='normal',
token=None,
http_user=None, http_passwd=None,
server_cert=None, client_cert=None, client_cert_password=None,
ssl_protocol=None
):
'''
ID: the ID to send to the RPC interface
uri: the URI of the RPC interface
mode:
normal - process requests immediately
batch - queue requests (run with "process_queue")
format - return RPC request objects
token: RPC method-level authorization token (set using `--rpc-secret`)
http_user, http_password: HTTP Basic authentication credentials (deprecated)
server_cert: server certificate for HTTPS connections
client_cert: client certificate for HTTPS connections
client_cert_password: prompt for client certificate password
ssl_protocol: SSL protocol from the ssl module
'''
self.id = ID
self.uri = uri
self.mode = mode
self.queue = []
self.handlers = dict()
self.token = token
if None not in (http_user, http_passwd):
self.add_HTTPBasicAuthHandler(http_user, http_passwd)
if server_cert or client_cert:
self.add_HTTPSHandler(
server_cert=server_cert,
client_cert=client_cert,
client_cert_password=client_cert_password,
protocol=ssl_protocol
)
self.update_opener()
def log(self, message):
'''
Print log messages to STDOUT. Override this if necessary.
'''
print(message)
def log_info(self, message):
self.log(message)
def log_error(self, message):
self.log('error: ' + message)
def iter_handlers(self):
'''
Iterate over handlers.
'''
for name in ('HTTPS', 'HTTPBasicAuth'):
try:
yield self.handlers[name]
except KeyError:
pass
def update_opener(self):
'''
Build an opener from the current handlers.
'''
self.opener = urllib.request.build_opener(*self.iter_handlers())
def remove_handler(self, name):
'''
Remove a handler.
'''
try:
del self.handlers[name]
except KeyError:
pass
def add_HTTPBasicAuthHandler(self, user, passwd):
'''
Add a handler for HTTP Basic authentication.
If either user or passwd are None, the handler is removed.
'''
handler = urllib.request.HTTPBasicAuthHandler()
handler.add_password(
realm='aria2',
uri=self.uri,
user=user,
passwd=passwd,
)
self.handlers['HTTPBasicAuth'] = handler
def remove_HTTPBasicAuthHandler(self):
self.remove_handler('HTTPBasicAuth')
def add_HTTPSHandler(
self,
server_cert=None,
client_cert=None,
client_cert_password=None,
protocol=None,
):
'''
Add a handler for HTTPS connections with optional server and client
certificates.
'''
if not protocol:
protocol = ssl.PROTOCOL_TLSv1
# protocol = ssl.PROTOCOL_TLSv1_1 # openssl 1.0.1+
# protocol = ssl.PROTOCOL_TLSv1_2 # Python 3.4+
context = ssl.SSLContext(protocol)
if server_cert:
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(cafile=server_cert)
else:
context.verify_mode = ssl.CERT_OPTIONAL
if client_cert:
context.load_cert_chain(client_cert, password=client_cert_password)
self.handlers['HTTPS'] = urllib.request.HTTPSHandler(
context=context,
check_hostname=False
)
def remove_HTTPSHandler(self):
self.remove_handler('HTTPS')
def send_request(self, req_obj):
'''
Send the request and return the response.
'''
req = json.dumps(req_obj).encode('UTF-8')
try:
with self.opener.open(self.uri, req) as f:
obj = json.loads(f.read().decode())
try:
return obj['result']
except KeyError:
self.log_error('unexpected result: {}'.format(obj))
return None
except urllib.error.URLError as e:
self.log_error(str(e))
return None
except http.client.BadStatusLine as e:
self.log_error('BadStatusLine: {} (HTTPS error?)'.format(e))
return None
def jsonrpc(self, method, params=None, prefix='aria2.'):
'''
POST a request to the RPC interface.
'''
if not params:
params = []
if self.token is not None:
params.insert(0, 'token:{}'.format(self.token))
req_obj = {
'jsonrpc' : '2.0',
'id' : self.id,
'method' : prefix + method,
'params' : params,
}
if self.mode == 'batch':
self.queue.append(req_obj)
return None
elif self.mode == 'format':
return req_obj
else:
return self.send_request(req_obj)
def process_queue(self):
'''
Processed queued requests.
'''
req_obj = self.queue
self.queue = []
return self.send_request(req_obj)
############################### Standard Methods ###############################
def addUri(self, uris, options=None, position=None):
'''
aria2.addUri method
uris: list of URIs
options: dictionary of additional options
position: position in queue
'''
params = [uris]
params = add_options_and_position(params, options, position)
return self.jsonrpc('addUri', params)
def addTorrent(self, torrent, uris=None, options=None, position=None):
'''
aria2.addTorrent method
torrent: base64-encoded torrent file
uris: list of webseed URIs
options: dictionary of additional options
position: position in queue
'''
params = [torrent]
if uris:
params.append(uris)
params = add_options_and_position(params, options, position)
return self.jsonrpc('addTorrent', params)
def addMetalink(self, metalink, options=None, position=None):
'''
aria2.addMetalink method
metalink: base64-encoded torrent file
options: dictionary of additional options
position: position in queue
'''
params = [metalink]
params = add_options_and_position(params, options, position)
return self.jsonrpc('addTorrent', params)
def remove(self, gid):
'''
aria2.remove method
gid: GID to remove
'''
params = [gid]
return self.jsonrpc('remove', params)
def forceRemove(self, gid):
'''
aria2.forceRemove method
gid: GID to remove
'''
params = [gid]
return self.jsonrpc('forceRemove', params)
def pause(self, gid):
'''
aria2.pause method
gid: GID to pause
'''
params = [gid]
return self.jsonrpc('pause', params)
def pauseAll(self):
'''
aria2.pauseAll method
'''
return self.jsonrpc('pauseAll')
def forcePause(self, gid):
'''
aria2.forcePause method
gid: GID to pause
'''
params = [gid]
return self.jsonrpc('forcePause', params)
def forcePauseAll(self):
'''
aria2.forcePauseAll method
'''
return self.jsonrpc('forcePauseAll')
def unpause(self, gid):
'''
aria2.unpause method
gid: GID to unpause
'''
params = [gid]
return self.jsonrpc('unpause', params)
def unpauseAll(self):
'''
aria2.unpauseAll method
'''
return self.jsonrpc('unpauseAll')
def tellStatus(self, gid, keys=None):
'''
aria2.tellStatus method
gid: GID to query
keys: subset of status keys to return (all keys are returned otherwise)
Returns a dictionary.
'''
params = [gid]
if keys:
params.append(keys)
return self.jsonrpc('tellStatus', params)
def getUris(self, gid):
'''
aria2.getUris method
gid: GID to query
Returns a list of dictionaries.
'''
params = [gid]
return self.jsonrpc('getUris', params)
def getFiles(self, gid):
'''
aria2.getFiles method
gid: GID to query
Returns a list of dictionaries.
'''
params = [gid]
return self.jsonrpc('getFiles', params)
def getPeers(self, gid):
'''
aria2.getPeers method
gid: GID to query
Returns a list of dictionaries.
'''
params = [gid]
return self.jsonrpc('getPeers', params)
def getServers(self, gid):
'''
aria2.getServers method
gid: GID to query
Returns a list of dictionaries.
'''
params = [gid]
return self.jsonrpc('getServers', params)
def tellActive(self, keys=None):
'''
aria2.tellActive method
keys: same as tellStatus
Returns a list of dictionaries. The dictionaries are the same as those
returned by tellStatus.
'''
if keys:
params = [keys]
else:
params = None
return self.jsonrpc('tellActive', params)
def tellWaiting(self, offset, num, keys=None):
'''
aria2.tellWaiting method
offset: offset from start of waiting download queue
(negative values are counted from the end of the queue)
num: number of downloads to return
keys: same as tellStatus
Returns a list of dictionaries. The dictionaries are the same as those
returned by tellStatus.
'''
params = [offset, num]
if keys:
params.append(keys)
return self.jsonrpc('tellWaiting', params)
def tellStopped(self, offset, num, keys=None):
'''
aria2.tellStopped method
offset: offset from oldest download (same semantics as tellWaiting)
num: same as tellWaiting
keys: same as tellStatus
Returns a list of dictionaries. The dictionaries are the same as those
returned by tellStatus.
'''
params = [offset, num]
if keys:
params.append(keys)
return self.jsonrpc('tellStopped', params)
def changePosition(self, gid, pos, how):
'''
aria2.changePosition method
gid: GID to change
pos: the position
how: "POS_SET", "POS_CUR" or "POS_END"
'''
params = [gid, pos, how]
return self.jsonrpc('changePosition', params)
def changeUri(self, gid, fileIndex, delUris, addUris, position=None):
'''
aria2.changePosition method
gid: GID to change
fileIndex: file to affect (1-based)
delUris: URIs to remove
addUris: URIs to add
position: where URIs are inserted, after URIs have been removed
'''
params = [gid, fileIndex, delUris, addUris]
if position:
params.append(position)
return self.jsonrpc('changePosition', params)
def getOption(self, gid):
'''
aria2.getOption method
gid: GID to query
Returns a dictionary of options.
'''
params = [gid]
return self.jsonrpc('getOption', params)
def changeOption(self, gid, options):
'''
aria2.changeOption method
gid: GID to change
options: dictionary of new options
(not all options can be changed for active downloads)
'''
params = [gid, options]
return self.jsonrpc('changeOption', params)
def getGlobalOption(self):
'''
aria2.getGlobalOption method
Returns a dictionary.
'''
return self.jsonrpc('getGlobalOption')
def changeGlobalOption(self, options):
'''
aria2.changeGlobalOption method
options: dictionary of new options
'''
params = [options]
return self.jsonrpc('changeGlobalOption', params)
def getGlobalStat(self):
'''
aria2.getGlobalStat method
Returns a dictionary.
'''
return self.jsonrpc('getGlobalStat')
def purgeDownloadResult(self):
'''
aria2.purgeDownloadResult method
'''
self.jsonrpc('purgeDownloadResult')
def removeDownloadResult(self, gid):
'''
aria2.removeDownloadResult method
gid: GID to remove
'''
params = [gid]
return self.jsonrpc('removeDownloadResult', params)
def getVersion(self):
'''
aria2.getVersion method
Returns a dictionary.
'''
return self.jsonrpc('getVersion')
def getSessionInfo(self):
'''
aria2.getSessionInfo method
Returns a dictionary.
'''
return self.jsonrpc('getSessionInfo')
def shutdown(self):
'''
aria2.shutdown method
'''
return self.jsonrpc('shutdown')
def forceShutdown(self):
'''
aria2.forceShutdown method
'''
return self.jsonrpc('forceShutdown')
def multicall(self, methods):
'''
aria2.multicall method
methods: list of dictionaries (keys: methodName, params)
The method names must be those used by Aria2c, e.g. "aria2.tellStatus".
'''
params = [methods]
return self.jsonrpc('multicall', params, prefix='system.')
############################# Convenience Methods ##############################
def add_torrent(self, path, uris=None, options=None, position=None):
'''
A wrapper around addTorrent for loading files.
'''
with open(path, 'r') as f:
torrent = base64.encode(f.read())
return self.addTorrent(torrent, uris, options, position)
def add_metalink(self, path, uris=None, options=None, position=None):
'''
A wrapper around addMetalink for loading files.
'''
with open(path, 'r') as f:
metalink = base64.encode(f.read())
return self.addMetalink(metalink, uris, options, position)
def get_status(self, gids):
'''
Get the status of multiple GIDs.
'''
methods = [
{
'methodName' : 'aria2.tellStatus',
'params' : [gid, ['gid', 'status']]
}
for gid in gids
]
stati = dict()
response = self.multicall(methods)
if response:
for result in response['result']:
result = result[0]
gid = result['gid']
status = result['status']
stati[gid] = status
return stati
def print_status(self):
status = self.getGlobalStat()
if status:
numWaiting = int(status['numWaiting'])
numStopped = int(status['numStopped'])
keys = ['totalLength', 'completedLength']
total = self.tellActive(keys)
waiting = self.tellWaiting(0, numWaiting, keys)
if waiting:
total += waiting
stopped = self.tellStopped(0, numStopped, keys)
if stopped:
total += stopped
downloadSpeed = int(status['downloadSpeed'])
uploadSpeed = int(status['uploadSpeed'])
totalLength = sum(int(x['totalLength']) for x in total)
completedLength = sum(int(x['completedLength']) for x in total)
remaining = totalLength - completedLength
status['downloadSpeed'] = format_bytes(downloadSpeed) + '/s'
status['uploadSpeed'] = format_bytes(uploadSpeed) + '/s'
preordered = ('downloadSpeed', 'uploadSpeed')
rows = list()
for k in sorted(status):
if k in preordered:
continue
rows.append((k, status[k]))
rows.extend((x, status[x]) for x in preordered)
if totalLength > 0:
rows.append(('total', format(format_bytes(totalLength))))
rows.append(('completed', format(format_bytes(completedLength))))
rows.append(('remaining', format(format_bytes(remaining))))
if completedLength == totalLength:
eta = 'finished'
else:
try:
eta = format_seconds(remaining // downloadSpeed)
except ZeroDivisionError:
eta = 'never'
rows.append(('ETA', eta))
l = max(len(r[0]) for r in rows)
r = max(len(r[1]) for r in rows)
r = max(r, len(self.uri) - (l + 2))
fmt = '{:<' + str(l) + 's} {:>' + str(r) + 's}'
print(self.uri)
for k, v in rows:
print(fmt.format(k, v))
def queue_uris(self, uris, options, interval=None):
gid = self.addUri(uris, options)
print("GID:", gid)
if gid and interval is not None:
blanker = ''
while True:
response = self.tellStatus(gid, ['status'])
if response:
try:
status = response['status']
except KeyError:
print("error: no status returned from server")
print("{}\rstatus: {}".format(blanker, status), end='')
blanker = ' ' * len(status)
if status == 'active':
time.sleep(interval)
else:
break
else:
print("error: no response from server")
break
################################### argparse ###################################
def add_server_arguments(parser):
"""
Common command-line arguments for the server.
Accepts an argparse ArgumentParser or group.
"""
parser.add_argument(
'-a', '--address', default='localhost',
help='The server host. Default: %(default)s.'
)
parser.add_argument(
'-p', '--port', type=int, default=DEFAULT_PORT,
help='The server port. Default: %(default)s.'
)
parser.add_argument(
'-s', '--scheme', default='http',
help='The server scheme. Default: %(default)s.'
)
# parser.add_argument(
# '--auth', nargs=2,
# help='HTTP Basic authentication user and password.'
# )
parser.add_argument(
'--token',
help='Secret RPC token.'
)
parser.add_argument(
'--server-cert',
help='HTTPS server certificate file, in PEM format.'
)
parser.add_argument(
'--client-cert',
help='HTTPS client certificate file, in PEM format.'
)
parser.add_argument(
'--client-cert-password',
help='Prompt for a client certificate password.'
)
def a2jr_from_args(identity, args):
"""
Return a new Aria2JsonRpc object using the provided arguments.
See `add_server_arguments`.
"""
uri = SERVER_URI_FORMAT.format(args.scheme, args.address, args.port)
# if args.auth:
# http_user, http_passwd = args.auth
# else:
# http_user = None
# http_passwd = None
token = args.token
if args.client_cert and args.client_cert_password:
client_cert_password = getpass.getpass('password for {}: '.format(args.client_cert))
else:
client_cert_password = None
return Aria2JsonRpc(
identity, uri,
token=token,
# http_user=http_user, http_passwd=http_passwd,
server_cert=args.server_cert,
client_cert=args.client_cert,
client_cert_password=client_cert_password,
)