-
-
Notifications
You must be signed in to change notification settings - Fork 91
/
cli.py
677 lines (558 loc) · 22.7 KB
/
cli.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
# Why does this file exist, and why not put this in `__main__`?
#
# You might be tempted to import things from `__main__` later,
# but that will cause problems: the code will get executed twice:
#
# - When you run `python -m aria2p` python will execute
# `__main__.py` as a script. That means there won't be any
# `aria2p.__main__` in `sys.modules`.
# - When you import `__main__` it will get executed again (as a module) because
# there's no `aria2p.__main__` in `sys.modules`.
"""Module that contains the command line application."""
import argparse
import importlib.util
import json
import sys
from collections import namedtuple
from pathlib import Path
from typing import Any, List, Optional, Union
import requests
from loguru import logger
from aria2p import Download, enable_logger
from .api import API
from .client import DEFAULT_HOST, DEFAULT_PORT, DEFAULT_TIMEOUT, Client, ClientException
from .utils import get_version
try:
from .interface import Interface
except ImportError:
Interface = None
# ============ MAIN FUNCTION ============ #
def main(args: Optional[List[str]] = None) -> int:
"""The main function, which is executed when you type ``aria2p`` or ``python -m aria2p``."""
parser = get_parser()
args = parser.parse_args(args=args)
kwargs = args.__dict__
log_level = kwargs.pop("log_level")
log_path = kwargs.pop("log_path")
if log_path:
log_path = Path(log_path)
if log_path.is_dir():
log_path = log_path / "aria2p-{time}.log"
enable_logger(sink=log_path, level=log_level or "WARNING")
elif log_level:
enable_logger(sink=sys.stderr, level=log_level)
logger.debug("Checking arguments")
check_args(parser, args)
logger.debug("Instantiating API")
api = API(
Client(
host=kwargs.pop("host"),
port=kwargs.pop("port"),
secret=kwargs.pop("secret"),
timeout=kwargs.pop("client_timeout"),
)
)
logger.info(f"API instantiated: {api!r}")
# Warn if no aria2 daemon process seems to be running
logger.debug("Testing connection")
try:
api.client.get_version()
except requests.ConnectionError as error:
print(f"[ERROR] {error}", file=sys.stderr)
print(file=sys.stderr)
print("Please make sure that an instance of aria2c is running with RPC mode enabled,", file=sys.stderr)
print("and that you have provided the right host, port and secret token.", file=sys.stderr)
print("More information at https://aria2p.readthedocs.io/en/latest.", file=sys.stderr)
return 2
subcommands = {
None: subcommand_top,
"show": subcommand_show,
"top": subcommand_top,
"call": subcommand_call,
"add": subcommand_add,
"add-magnets": subcommand_add_magnets,
"add-torrents": subcommand_add_torrents,
"add-metalinks": subcommand_add_metalinks,
"pause": subcommand_pause,
"stop": subcommand_pause, # alias for pause
"resume": subcommand_resume,
"start": subcommand_resume, # alias for resume
"remove": subcommand_remove,
"rm": subcommand_remove, # alias for remove
"del": subcommand_remove, # alias for remove
"delete": subcommand_remove, # alias for remove
"autopurge": subcommand_autopurge,
"autoclear": subcommand_autopurge, # alias for autopurge
"listen": subcommand_listen,
}
subcommand = kwargs.pop("subcommand")
if subcommand:
logger.debug("Running subcommand " + subcommand)
try:
return subcommands.get(subcommand)(api, **kwargs)
except ClientException as error:
print(error.message, file=sys.stderr)
return error.code
def check_args(parser: argparse.ArgumentParser, args: namedtuple) -> None:
"""Additional checks for command line arguments."""
subparser = [action for action in parser._actions if isinstance(action, argparse._SubParsersAction)][0].choices
if args.subcommand in ("pause", "stop", "remove", "rm", "del", "delete", "resume", "start", "purge", "clear"):
if not args.do_all and not args.gids:
subparser[args.subcommand].error("the following arguments are required: gids or --all")
elif args.do_all and args.gids:
subparser[args.subcommand].error("argument -a/--all: not allowed with arguments gids")
elif args.subcommand in ("add", "add-magnet", "add-magnets"):
if not args.uris and not args.from_file:
subparser[args.subcommand].error("the following arguments are required: uris or -f FILE")
elif args.subcommand in ("add-torrent", "add-torrents"):
if not args.torrent_files and not args.from_file:
subparser[args.subcommand].error("the following arguments are required: torrent_files or -f FILE")
elif args.subcommand in ("add-metalink", "add-metalinks"):
if not args.metalink_files and not args.from_file:
subparser[args.subcommand].error("the following arguments are required: metalink_files or -f FILE")
def get_parser() -> argparse.ArgumentParser:
"""Return a parser for the command-line options and arguments."""
usage = "%(prog)s [GLOBAL_OPTS...] COMMAND [COMMAND_OPTS...]"
description = "Command-line tool and Python library to interact with an `aria2c` daemon process through JSON-RPC."
parser = argparse.ArgumentParser(add_help=False, usage=usage, description=description, prog="aria2p")
main_help = "Show this help message and exit. Commands also accept the -h/--help option."
subcommand_help = "Show this help message and exit."
global_options = parser.add_argument_group(title="Global options")
global_options.add_argument("-h", "--help", action="help", help=main_help)
global_options.add_argument(
"-p", "--port", dest="port", default=DEFAULT_PORT, type=int, help="Port to use to connect to the remote server."
)
global_options.add_argument(
"-H", "--host", dest="host", default=DEFAULT_HOST, help="Host address for the remote server."
)
global_options.add_argument(
"-s", "--secret", dest="secret", default="", help="Secret token to use to connect to the remote server."
)
global_options.add_argument(
"-L",
"--log-level",
dest="log_level",
default=None,
help="Log level to use",
choices=("TRACE", "DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL"),
type=str.upper,
)
global_options.add_argument(
"-P", "--log-path", dest="log_path", default=None, help="Log path to use. Can be a directory or a file."
)
global_options.add_argument(
"-T",
"--client-timeout",
dest="client_timeout",
default=DEFAULT_TIMEOUT,
type=float,
help=f"Timeout in seconds for requests to the remote server. Floats supported. Default: {DEFAULT_TIMEOUT}.",
)
# ========= SUBPARSERS ========= #
subparsers = parser.add_subparsers(dest="subcommand", title="Commands", metavar="", prog="aria2p")
def subparser(command: str, text: str, **kwargs) -> argparse.ArgumentParser:
sub = subparsers.add_parser(command, add_help=False, help=text, description=text, **kwargs)
sub.add_argument("-h", "--help", action="help", help=subcommand_help)
return sub
add_parser = subparser("add", "Add downloads with URIs/Magnets/torrents/Metalinks.")
add_magnets_parser = subparser("add-magnets", "Add downloads with Magnet URIs.", aliases=["add-magnet"])
add_metalinks_parser = subparser("add-metalinks", "Add downloads with Metalink files.", aliases=["add-metalink"])
add_torrents_parser = subparser("add-torrents", "Add downloads with torrent files.", aliases=["add-torrent"])
subparser("autopurge", "Automatically purge completed/removed/failed downloads.", aliases=["autoclear"])
call_parser = subparser("call", "Call a remote method through the JSON-RPC client.")
pause_parser = subparser("pause", "Pause downloads.", aliases=["stop"])
remove_parser = subparser("remove", "Remove downloads.", aliases=["rm", "del", "delete"])
resume_parser = subparser("resume", "Resume downloads.", aliases=["start"])
subparser("show", "Show the download progression.")
subparser("top", "Launch the top-like interactive interface.")
listen_parser = subparser("listen", "Listen to notifications.")
# ========= CALL PARSER ========= #
call_parser.add_argument(
"method",
help=(
"The method to call (case insensitive). "
"Dashes and underscores will be removed so you can use as many as you want, or none. "
"Prefixes like 'aria2.' or 'system.' are also optional."
),
)
call_parser_mxg = call_parser.add_mutually_exclusive_group()
call_parser_mxg.add_argument(
"-P", "--params-list", dest="params", nargs="+", help="Parameters as a list of strings."
)
call_parser_mxg.add_argument(
"-J",
"--json-params",
dest="params",
help="Parameters as a JSON string. You should always wrap it at least once in an array '[]'.",
)
# ========= ADD PARSER ========= #
add_parser.add_argument("uris", nargs="*", help="The URIs/file-paths to add.")
add_parser.add_argument("-f", "--from-file", dest="from_file", help="Load URIs from a file.")
# ========= ADD MAGNET PARSER ========= #
add_magnets_parser.add_argument("uris", nargs="*", help="The magnet URIs to add.")
add_magnets_parser.add_argument("-f", "--from-file", dest="from_file", help="Load URIs from a file.")
# ========= ADD TORRENT PARSER ========= #
add_torrents_parser.add_argument("torrent_files", nargs="*", help="The paths to the torrent files.")
add_torrents_parser.add_argument("-f", "--from-file", dest="from_file", help="Load file paths from a file.")
# ========= ADD METALINK PARSER ========= #
add_metalinks_parser.add_argument("metalink_files", nargs="*", help="The paths to the metalink files.")
add_metalinks_parser.add_argument("-f", "--from-file", dest="from_file", help="Load file paths from a file.")
# ========= PAUSE PARSER ========= #
pause_parser.add_argument("gids", nargs="*", help="The GIDs of the downloads to pause.")
pause_parser.add_argument("-a", "--all", action="store_true", dest="do_all", help="Pause all the downloads.")
pause_parser.add_argument(
"-f", "--force", dest="force", action="store_true", help="Pause without contacting servers first."
)
# ========= RESUME PARSER ========= #
resume_parser.add_argument("gids", nargs="*", help="The GIDs of the downloads to resume.")
resume_parser.add_argument("-a", "--all", action="store_true", dest="do_all", help="Resume all the downloads.")
# ========= REMOVE PARSER ========= #
remove_parser.add_argument("gids", nargs="*", help="The GIDs of the downloads to remove.")
remove_parser.add_argument("-a", "--all", action="store_true", dest="do_all", help="Remove all the downloads.")
remove_parser.add_argument(
"-f", "--force", dest="force", action="store_true", help="Remove without contacting servers first."
)
# ========= LISTEN PARSER ========= #
listen_parser.add_argument(
"-c",
"--callbacks-module",
dest="callbacks_module",
help="Path to the Python module defining your notifications callbacks.",
)
listen_parser.add_argument(
"event_types",
nargs="*",
help="The types of notifications to process: "
"start, pause, stop, error, complete or btcomplete. "
"Example: aria2p listen error btcomplete. "
"Useful if you want to spawn multiple specialized aria2p listener, "
"for example one for each type of notification, "
"but still want to use only one callback file.",
)
listen_parser.add_argument(
"-t",
"--timeout",
dest="timeout",
type=float,
default=5,
help="Timeout in seconds to use when waiting for data over the WebSocket at each iteration. "
"Use small values for faster reactivity when stopping to listen.",
)
return parser
# ============ SUBCOMMANDS ============ #
def subcommand_show(api: API) -> int:
"""
Show subcommand.
Parameters:
api: the API instance to use.
Returns:
int: always 0.
"""
downloads = api.get_downloads()
print(
f"{'GID':<17} "
f"{'STATUS':<9} "
f"{'PROGRESS':>8} "
f"{'DOWN_SPEED':>12} "
f"{'UP_SPEED':>12} "
f"{'ETA':>8} "
f"NAME"
)
for download in downloads:
print(
f"{download.gid:<17} "
f"{download.status:<9} "
f"{download.progress_string():>8} "
f"{download.download_speed_string():>12} "
f"{download.upload_speed_string():>12} "
f"{download.eta_string():>8} "
f"{download.name}"
)
return 0
def subcommand_top(api: API) -> int:
"""
Top subcommand.
Parameters:
api: the API instance to use.
Returns:
int: always 0.
"""
if Interface is None:
print(
"The top-interface dependencies are not installed. Try running `pip install aria2p[tui]` to install them.",
file=sys.stderr,
)
return 1
interface = Interface(api)
success = interface.run()
return 0 if success else 1
def subcommand_call(api: API, method: str, params: Union[str, List[str]]) -> int:
"""
Call subcommand.
Parameters:
api: the API instance to use.
method: name of the method to call.
params: parameters to use when calling method.
Returns:
int: always 0.
"""
real_method = get_method(method)
if real_method is None:
print(f"aria2p: call: Unknown method {method}.", file=sys.stderr)
print(" Run 'aria2p call listmethods' to list the available methods.", file=sys.stderr)
return 1
if isinstance(params, str):
params = json.loads(params)
elif params is None:
params = []
response = api.client.call(real_method, params)
print(json.dumps(response))
return 0
def get_method(name: str, default: Any = None) -> str:
"""Return the actual aria2 method name from a differently formatted name."""
methods = {}
for method in Client.METHODS:
methods[method.lower()] = method
methods[method.split(".")[1].lower()] = method
name = name.lower()
name = name.replace("-", "")
name = name.replace("_", "")
return methods.get(name, default)
def read_lines(path: str) -> List[str]:
with Path(path).open() as stream:
return stream.readlines()
def subcommand_add(api: API, uris: List[str] = None, from_file: str = None) -> int:
"""
Add magnet subcommand.
Parameters:
api: The API instance to use.
uris: The URIs or file-paths to add.
from_file: Path to the file to read uris from.
Deprecated: every URI that is a valid file-path
and is not a torrent or a metalink is now read as an input file.
Returns:
int: 0 if OK else 1.
"""
uris = uris or []
if from_file:
logger.warning(
"Deprecation warning: every URI that is a valid file-path "
"and is not a torrent or a metalink is now read as an input file."
)
new_downloads = []
for uri in uris:
new_downloads.extend(api.add(uri))
if new_downloads:
for new_download in new_downloads:
print(f"Created download {new_download.gid}")
return 0
print("No new download was created", file=sys.stderr)
return 1
def subcommand_add_magnets(api: API, uris: List[str] = None, from_file: str = None) -> int:
"""
Add magnet subcommand.
Parameters:
api: the API instance to use.
uris: the URIs of the magnets.
from_file: path to the file to read uris from.
Returns:
int: always 0.
"""
ok = True
if not uris:
uris = []
if from_file:
try:
uris.extend(read_lines(from_file))
except OSError:
print(f"Cannot open file: {from_file}", file=sys.stderr)
ok = False
for uri in uris:
new_download = api.add_magnet(uri)
print(f"Created download {new_download.gid}")
return 0 if ok else 1
def subcommand_add_torrents(api: API, torrent_files: List[str] = None, from_file: str = None) -> int:
"""
Add torrent subcommand.
Parameters:
api: the API instance to use.
torrent_files: the paths to the torrent files.
from_file: path to the file to read torrent files paths from.
Returns:
int: always 0.
"""
ok = True
if not torrent_files:
torrent_files = []
if from_file:
try:
torrent_files.extend(read_lines(from_file))
except OSError:
print(f"Cannot open file: {from_file}", file=sys.stderr)
ok = False
for torrent_file in torrent_files:
new_download = api.add_torrent(torrent_file)
print(f"Created download {new_download.gid}")
return 0 if ok else 1
def subcommand_add_metalinks(api: API, metalink_files: List[str] = None, from_file: str = None) -> int:
"""
Add metalink subcommand.
Parameters:
api: the API instance to use.
metalink_files: the paths to the metalink files.
from_file: path to the file to metalink files paths from.
Returns:
int: 0 if OK else 1.
"""
ok = True
if not metalink_files:
metalink_files = []
if from_file:
try:
metalink_files.extend(read_lines(from_file))
except OSError:
print(f"Cannot open file: {from_file}", file=sys.stderr)
ok = False
for metalink_file in metalink_files:
new_downloads = api.add_metalink(metalink_file)
for download in new_downloads:
print(f"Created download {download.gid}")
return 0 if ok else 1
def subcommand_pause(api: API, gids: List[str] = None, do_all: bool = False, force: bool = False) -> int:
"""
Pause subcommand.
Parameters:
api: the API instance to use.
gids: the GIDs of the downloads to pause.
do_all: pause all downloads if True.
force: force pause or not (see API.pause).
Returns:
int: 0 if all success, 1 if one failure.
"""
if do_all:
if api.pause_all(force=force):
return 0
return 1
# FIXME: could break if API.resume needs more info than just gid
# See how we do that in subcommand_remove
downloads = [Download(api, {"gid": gid}) for gid in gids]
result = api.pause(downloads, force=force)
if all(result):
return 0
for item in result:
if isinstance(item, ClientException):
print(item, file=sys.stderr)
return 1
def subcommand_resume(api: API, gids: List[str] = None, do_all: bool = False) -> int:
"""
Resume subcommand.
Parameters:
api: the API instance to use.
gids: the GIDs of the downloads to resume.
do_all: pause all downloads if True.
Returns:
int: 0 if all success, 1 if one failure.
"""
if do_all:
if api.resume_all():
return 0
return 1
# FIXME: could break if API.resume needs more info than just gid
# See how we do that in subcommand_remove
downloads = [Download(api, {"gid": gid}) for gid in gids]
result = api.resume(downloads)
if all(result):
return 0
for item in result:
if isinstance(item, ClientException):
print(item, file=sys.stderr)
return 1
def subcommand_remove(api: API, gids: List[str] = None, do_all: bool = False, force: bool = False) -> int:
"""
Remove subcommand.
Parameters:
api: the API instance to use.
gids: the GIDs of the downloads to remove.
do_all: pause all downloads if True.
force: force pause or not (see API.remove).
Returns:
int: 0 if all success, 1 if one failure.
"""
if do_all:
if api.remove_all():
return 0
return 1
ok = True
downloads = []
for gid in gids:
try:
downloads.append(api.get_download(gid))
except ClientException as error:
print(str(error), file=sys.stderr)
ok = False
result = api.remove(downloads, force=force)
if all(result):
return 0 if ok else 1
for item in result:
if isinstance(item, ClientException):
print(item, file=sys.stderr)
return 1
def subcommand_autopurge(api: API) -> int:
"""
Autopurge subcommand.
Parameters:
api: the API instance to use.
Returns:
int: 0 if all success, 1 if one failure.
"""
version = get_version()
if version.major == 0 and 9 > version.minor >= 7:
print(
"Future change warning: command 'autopurge' will be renamed 'purge' in version 0.9.0, "
"with an 'autoremove' alias.",
file=sys.stderr,
)
if api.autopurge():
return 0
return 1
def subcommand_listen(
api: API, callbacks_module: Union[str, Path] = None, event_types: List[str] = None, timeout: int = 5
) -> int:
"""
Listen subcommand.
Parameters:
api: the API instance to use.
callbacks_module: the path to the module to import, containing the callbacks as functions.
event_types: the event types to process.
timeout: the timeout to pass to the WebSocket connection, in seconds.
Returns:
int: always 0.
"""
if not callbacks_module:
print("aria2p: listen: Please provide the callback module file path with -c option", file=sys.stderr)
return 1
if isinstance(callbacks_module, Path):
callbacks_module = str(callbacks_module)
if not event_types:
event_types = ["start", "pause", "stop", "error", "complete", "btcomplete"]
spec = importlib.util.spec_from_file_location("aria2p_callbacks", callbacks_module)
callbacks = importlib.util.module_from_spec(spec)
if callbacks is None:
print(f"aria2p: Could not import module file {callbacks_module}", file=sys.stderr)
return 1
spec.loader.exec_module(callbacks)
callbacks_kwargs = {}
for callback_name in (
"on_download_start",
"on_download_pause",
"on_download_stop",
"on_download_error",
"on_download_complete",
"on_bt_download_complete",
):
if callback_name[3:].replace("download", "").replace("_", "") in event_types:
callback = getattr(callbacks, callback_name, None)
if callback:
callbacks_kwargs[callback_name] = callback
api.listen_to_notifications(timeout=timeout, handle_signals=True, threaded=False, **callbacks_kwargs)
return 0