├── aioaria2 ├── py.typed ├── exceptions.py ├── typing.py ├── __init__.py ├── server.py ├── utils.py ├── parser.py └── client.py ├── MANIFEST.in ├── tests ├── __init__.py ├── test_server.py ├── test_parser.py ├── test_websocket.py └── test.py ├── requirements.txt ├── .gitignore ├── pyproject.toml ├── example ├── read_aria2files.py ├── demo.py └── demo2.py ├── .github └── workflows │ └── upload.yml ├── setup.cfg ├── setup.py ├── README_zh.markdown ├── README.markdown └── LICENSE /aioaria2/py.typed: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include aioaria2/py.typed -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp 2 | aiofiles 3 | typing-extensions -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /dist/ 2 | /build/ 3 | /.idea/ 4 | /.mypy_cache/ 5 | *.pyd 6 | *.pyc 7 | *.pyo 8 | *.so 9 | *.dll 10 | *.exe 11 | *.bat -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=42", 4 | "wheel" 5 | ] 6 | build-backend = "setuptools.build_meta" -------------------------------------------------------------------------------- /example/read_aria2files.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright (c) 2008-2023 synodriver 3 | """ 4 | 5 | from io import BytesIO 6 | 7 | from aioaria2 import ControlFile, DHTFile 8 | 9 | data = ControlFile.from_file("180P_225K_242958531.webm.aria2") 10 | print(data) 11 | # do something with .aria2 file 12 | data.save(BytesIO()) 13 | 14 | dht = DHTFile.from_file("dht.dat") # or dht6.dat 15 | print(dht) 16 | # do something with dht file 17 | dht.save(BytesIO()) 18 | -------------------------------------------------------------------------------- /aioaria2/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | 本模块存放异常 4 | """ 5 | from typing import Optional 6 | 7 | 8 | class Aria2rpcException(Exception): 9 | """ 10 | Base exception raised by this module. 11 | """ 12 | 13 | def __init__(self, msg: str, connection_error: Optional[bool] = False): 14 | super().__init__(msg) 15 | self.msg = msg 16 | self.connection_error = connection_error 17 | 18 | def __str__(self): 19 | return f"{self.__class__.__name__}: {self.msg}" 20 | -------------------------------------------------------------------------------- /aioaria2/typing.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | 支持类型注释 4 | """ 5 | from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, TypeVar, Union 6 | 7 | Aria2WebsocketClient = TypeVar("Aria2WebsocketClient", bound="Aria2WebsocketClient") 8 | 9 | if TYPE_CHECKING: 10 | from aioaria2 import Aria2WebsocketClient 11 | 12 | """ 13 | Websocket事件的回调函数 14 | """ 15 | CallBack = Callable[ 16 | [Aria2WebsocketClient, Dict[str, Any]], Union[Awaitable[Any], Awaitable[None]] 17 | ] 18 | 19 | """ 20 | 产生随机id的工厂函数 如果一定要参数可以用functools.partial 21 | """ 22 | IdFactory = Callable[[], Union[int, Awaitable[int]]] 23 | -------------------------------------------------------------------------------- /tests/test_server.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import asyncio 3 | import sys 4 | 5 | import aioaria2 6 | 7 | 8 | async def main(): 9 | server = aioaria2.AsyncAria2Server( 10 | r"128aria2c.exe", r"--conf-path=aria2.conf", "--rpc-secret=admin", daemon=True 11 | ) 12 | await server.start() 13 | await server.wait() 14 | print("不等他") 15 | 16 | 17 | if __name__ == "__main__": 18 | # if sys.platform == "win32": 19 | # # 想不到吧,官方文档说要在windows使用asyncio.create_subprocess_shell,只说了修改event_loop_policy, 20 | # # 没想到还要修改默认的事件循环,哈哈 21 | # # windows就是矫情 22 | # asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) 23 | # asyncio.set_event_loop(asyncio.ProactorEventLoop()) 24 | # asyncio.run(main()) 25 | # main() 26 | def a(c=1, d=2): 27 | print(c, d) 28 | 29 | a(None) 30 | -------------------------------------------------------------------------------- /.github/workflows/upload.yml: -------------------------------------------------------------------------------- 1 | name: upload 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | jobs: 7 | build: 8 | 9 | runs-on: ${{ matrix.os }} 10 | strategy: 11 | matrix: 12 | python-version: ["3.9"] 13 | os: [ubuntu-latest] 14 | fail-fast: false 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v2 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | - name: Install dependencies 23 | run: | 24 | python -m pip install --upgrade pip 25 | python -m pip install --upgrade setuptools 26 | python -m pip install --upgrade wheel 27 | pip install flake8 pytest 28 | pip install twine 29 | pip install -r requirements.txt 30 | - name: build_whl 31 | run: | 32 | python setup.py sdist bdist_wheel 33 | - name: Publish package 34 | run: | 35 | twine upload dist/* -u ${{ secrets.PYPI_USER }} -p ${{ secrets.PYPI_PASSWORD }} -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | # replace with your username: 3 | name = aioaria2 4 | version = 1.3.5rc3 5 | keywords = 6 | asyncio 7 | Aria2 8 | author = synodriver 9 | author_email = diguohuangjiajinweijun@gmail.com 10 | description = Support Aria2 rpc client and manage server with async/await 11 | long_description = file: README.markdown 12 | long_description_content_type = text/markdown 13 | url = https://github.com/synodriver/aioaria2 14 | project_urls = 15 | Bug Tracker = https://github.com/synodriver/aioaria2/issues 16 | classifiers = 17 | Development Status :: 3 - Alpha 18 | Framework :: AsyncIO 19 | Operating System :: OS Independent 20 | License :: OSI Approved :: GNU General Public License v3 (GPLv3) 21 | Programming Language :: Python 22 | Programming Language :: Python :: 3.7 23 | Programming Language :: Python :: 3.8 24 | Programming Language :: Python :: 3.9 25 | Programming Language :: Python :: Implementation :: CPython 26 | install_requires = 27 | aiohttp 28 | aiofiles 29 | typing-extensions 30 | 31 | [options] 32 | include_package_data = True 33 | packages = find: 34 | python_requires = >=3.7 -------------------------------------------------------------------------------- /tests/test_parser.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from io import BytesIO 3 | from os.path import dirname, join 4 | from unittest import TestCase 5 | 6 | from aioaria2 import ControlFile, DHTFile 7 | 8 | 9 | class Testarser(TestCase): 10 | def test_ControlFile(self): 11 | s = BytesIO() 12 | data = ControlFile.from_file("180P_225K_242958531.webm.aria2") 13 | data.save(s) 14 | self.assertEqual( 15 | s.getvalue(), open("180P_225K_242958531.webm.aria2", "rb").read() 16 | ) 17 | 18 | def test_DHTFile(self): 19 | s = BytesIO() 20 | data = DHTFile.from_file(join(dirname(__file__), "dht.dat")) 21 | data.save(s) 22 | self.assertEqual( 23 | len(s.getvalue()), 24 | len(open(join(dirname(__file__), "dht.dat"), "rb").read()), 25 | ) 26 | 27 | def test_DHTFilev6(self): 28 | s = BytesIO() 29 | data = DHTFile.from_file(join(dirname(__file__), "dht6.dat")) 30 | data.save(s) 31 | self.assertEqual( 32 | len(s.getvalue()), 33 | len(open(join(dirname(__file__), "dht6.dat"), "rb").read()), 34 | ) 35 | -------------------------------------------------------------------------------- /example/demo.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # infinite retry 3 | import asyncio 4 | from pprint import pprint 5 | 6 | import ujson 7 | 8 | import aioaria2 9 | 10 | HOST = "http://127.0.0.1:6800/jsonrpc" 11 | 12 | 13 | async def on_download_error(trigger: aioaria2.Aria2WebsocketClient, data: dict): 14 | print("Oops! It seems sth wrong with your network! Never mind, try again") 15 | gid: str = data["params"][0]["gid"] 16 | uri: str = (await trigger.getFiles(gid))[0]["uris"][0]["uri"] 17 | await trigger.addUri([uri]) 18 | 19 | 20 | async def on_download_complete(trigger: aioaria2.Aria2WebsocketClient, data: dict): 21 | print("Congratulations! You have successfully across the great wall") 22 | 23 | 24 | async def main(): 25 | client: aioaria2.Aria2WebsocketClient = await aioaria2.Aria2WebsocketClient.new( 26 | "http://127.0.0.1:6800/jsonrpc", 27 | token="token", 28 | loads=ujson.loads, 29 | dumps=ujson.dumps, 30 | ) 31 | client.onDownloadError(on_download_error) 32 | client.onDownloadComplete(on_download_complete) 33 | pprint(await client.addUri(["http://www.google.com"])) # 34 | 35 | 36 | loop = asyncio.get_event_loop() 37 | loop.create_task(main()) 38 | loop.run_forever() 39 | -------------------------------------------------------------------------------- /example/demo2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 示例下载豆瓣top250 movie的封面 3 | import asyncio 4 | 5 | import aiohttp 6 | from bs4 import BeautifulSoup 7 | 8 | import aioaria2 9 | 10 | start_url = "https://movie.douban.com/top250?start={0}&filter=" 11 | 12 | header = { 13 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 14 | } 15 | 16 | HOST = "http://127.0.0.1:6800/jsonrpc" 17 | SEC = "token" 18 | 19 | 20 | def parse(html: str): 21 | soup = BeautifulSoup(html, "lxml") 22 | return [ 23 | tag.attrs["src"] for tag in soup.find_all(name="img", attrs={"width": "100"}) 24 | ] 25 | 26 | 27 | async def fetch( 28 | session: aiohttp.ClientSession, url: str, client: aioaria2.Aria2HttpClient 29 | ): 30 | async with session.get(url, headers=header) as resp: 31 | pic_urls = parse(await resp.text()) 32 | for url in pic_urls: 33 | await client.addUri([url]) 34 | 35 | 36 | async def get_client(): 37 | async with aioaria2.Aria2HttpClient( 38 | HOST, token=SEC 39 | ) as client, aiohttp.ClientSession() as session: 40 | urls = [start_url.format(i * 25) for i in range(10)] # 每个页面 41 | tasks = [asyncio.create_task(fetch(session, url, client)) for url in urls] 42 | await asyncio.wait(tasks) 43 | 44 | 45 | if __name__ == "__main__": 46 | asyncio.run(get_client()) 47 | -------------------------------------------------------------------------------- /aioaria2/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | 本模块提供aria2 json rpc的异步io交互接口 和aria2进程的管理器 4 | """ 5 | from aioaria2.client import Aria2HttpClient, Aria2WebsocketClient, Aria2WebsocketTrigger 6 | from aioaria2.exceptions import Aria2rpcException 7 | from aioaria2.parser import ControlFile, DHTFile 8 | from aioaria2.server import Aria2Server, AsyncAria2Server 9 | from aioaria2.utils import add_async_callback, run_sync 10 | 11 | __version__ = "1.3.6" 12 | 13 | __author__ = "synodriver" 14 | __all__ = [ 15 | "Aria2Server", 16 | "AsyncAria2Server", 17 | "Aria2WebsocketTrigger", 18 | "Aria2HttpClient", 19 | "Aria2WebsocketClient", 20 | "Aria2rpcException", 21 | "ControlFile", 22 | "DHTFile", 23 | "run_sync", 24 | "add_async_callback", 25 | ] 26 | 27 | # 28 | # class Aria2Client: 29 | # def __init__(self, identity: str, url: str, token=None): 30 | # self._queue = asyncio.Queue() 31 | # self.req_generator = Aria2HttpClient(identity, url, "batch", token, self._queue) 32 | # # self.trigger=Aria2WebsocketTrigger() 33 | # 34 | # @classmethod 35 | # async def create(cls, identity: str, url: str, token=None, queue=None): 36 | # self = cls(identity, url, token, queue) 37 | # self.trigger = await Aria2WebsocketTrigger.create(identity, url, "batch", token, self._queue) 38 | # return self 39 | # 40 | # async def getVersion(self): 41 | # await self.req_generator.getVersion() 42 | # 43 | # def register(self, func, type): 44 | # """ 45 | # :return: 46 | # """ 47 | # self.trigger.functions[type] = func 48 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import re 4 | 5 | from setuptools import find_packages, setup 6 | 7 | 8 | def get_version() -> str: 9 | path = os.path.join( 10 | os.path.abspath(os.path.dirname(__file__)), "aioaria2", "__init__.py" 11 | ) 12 | with open(path, "r", encoding="utf-8") as f: 13 | data = f.read() 14 | result = re.findall(r"(?<=__version__ = \")\S+(?=\")", data) 15 | return result[0] 16 | 17 | 18 | def get_dis(): 19 | with open("README.markdown", "r", encoding="utf-8") as f: 20 | return f.read() 21 | 22 | 23 | packages = find_packages(exclude=("test", "tests.*", "test*")) 24 | 25 | 26 | def main(): 27 | version: str = get_version() 28 | 29 | dis = get_dis() 30 | setup( 31 | name="aioaria2", 32 | version=version, 33 | url="https://github.com/synodriver/aioaria2", 34 | packages=packages, 35 | keywords=["asyncio", "Aria2"], 36 | description="Support Aria2 rpc client and manage server with async/await", 37 | long_description_content_type="text/markdown", 38 | long_description=dis, 39 | author="synodriver", 40 | author_email="diguohuangjiajinweijun@gmail.com", 41 | maintainer="v-vinson", 42 | python_requires=">=3.6", 43 | install_requires=["aiohttp", "aiofiles", "typing-extensions"], 44 | license="GPLv3", 45 | classifiers=[ 46 | "Development Status :: 3 - Alpha", 47 | "Framework :: AsyncIO", 48 | "Operating System :: OS Independent", 49 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 50 | "Programming Language :: Python", 51 | "Programming Language :: Python :: 3.8", 52 | "Programming Language :: Python :: 3.9", 53 | "Programming Language :: Python :: 3.10", 54 | "Programming Language :: Python :: 3.11", 55 | "Programming Language :: Python :: 3.12", 56 | "Programming Language :: Python :: 3.13", 57 | "Programming Language :: Python :: Implementation :: CPython", 58 | ], 59 | include_package_data=True, 60 | ) 61 | 62 | 63 | if __name__ == "__main__": 64 | main() 65 | -------------------------------------------------------------------------------- /tests/test_websocket.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import asyncio 3 | import time 4 | from pprint import pprint 5 | 6 | import ujson 7 | 8 | import aioaria2 9 | 10 | HOST = "http://aria.blackjoe.art:2082/jsonrpc" 11 | 12 | 13 | async def callback(trigger, data): 14 | print("下载开始{0}".format(data)) 15 | 16 | 17 | async def callback2(trigger: aioaria2.Aria2WebsocketTrigger, data): 18 | print("下载完成{0}".format(data)) 19 | 20 | 21 | async def callback3(trigger: aioaria2.Aria2WebsocketTrigger, future): 22 | print("下载中断") 23 | data = future.result() 24 | gid = data["params"][0]["gid"] 25 | trigger.identity = "getFiles" 26 | await trigger.getFiles(gid) 27 | trigger.identity = "id" 28 | 29 | 30 | async def onresult(trigger, data): 31 | print("结果") 32 | if data["id"] == "getFiles": 33 | # 如同http一样的返回 getFiles调用 34 | url = data["result"][0]["uris"][0]["uri"] 35 | trigger.identity = "addUri" 36 | await trigger.addUri([url]) 37 | trigger.identity = "id" 38 | elif data["id"] == "addUri": 39 | print("重新入队成功:{0}".format(data["result"])) 40 | 41 | 42 | async def get_client(): 43 | async with aioaria2.Aria2HttpClient( 44 | HOST, token="a489451594cda0792df1", loads=ujson.loads, dumps=ujson.dumps 45 | ) as client: 46 | # pprint(await client.addUri(["http://odrive.aptx.xin/%E5%8A%A8%E7%94%BB/2004/200445.zip"])) 47 | pprint(await client.getVersion()) 48 | 49 | 50 | async def get_trigger(): 51 | try: 52 | client = await aioaria2.Aria2WebsocketTrigger.new( 53 | "https://127.0.0.1:443", token="a489451594cda0792df1" 54 | ) 55 | # client=aioaria2.Aria2WebsocketTrigger("id", HOST,token="adman",) 56 | client.onDownloadStart(callback) 57 | client.onDownloadComplete(callback2) 58 | await client.addUri(["https://www.baidu.com"]) 59 | except aioaria2.Aria2rpcException as e: 60 | print("can't connect ") 61 | 62 | 63 | def main(): 64 | loop = asyncio.get_event_loop() 65 | # loop.call_soon_threadsafe() 66 | # asyncio.run_coroutine_threadsafe() 67 | # tasks = [loop.create_task(get_trigger()),loop.create_task(get_client())] # , loop.create_task(get_client())] 68 | tasks = [loop.create_task(get_trigger()), asyncio.sleep(100)] 69 | loop.run_until_complete(asyncio.wait(tasks)) 70 | 71 | 72 | if __name__ == "__main__": 73 | loop = asyncio.get_event_loop() 74 | loop.create_task(get_trigger()) 75 | try: 76 | loop.run_forever() 77 | finally: 78 | loop.close() 79 | # main() 80 | -------------------------------------------------------------------------------- /aioaria2/server.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | 本模块负责管理aria2进程 4 | """ 5 | 6 | import asyncio 7 | import os 8 | import subprocess 9 | import threading 10 | 11 | # --------------------------# 12 | 13 | ENCODING = "gbk" 14 | 15 | 16 | # --------------------------# 17 | # 18 | # cache: Dict[str, object] = {} 19 | 20 | 21 | # def single_instance(cls: type): 22 | # """ 23 | # 单例模式装饰器,如果两个aria2进程一同开启必定端口冲突 24 | # :param cls: 要装饰的类 25 | # :return: 26 | # """ 27 | # 28 | # @wraps(cls) 29 | # def inner(*args, **kw): 30 | # class_name = cls.__name__ 31 | # if class_name in cache: 32 | # return cache[class_name] 33 | # else: 34 | # instance = cls(*args, **kw) 35 | # cache[class_name] = instance 36 | # return instance 37 | # return inner 38 | 39 | 40 | class SingletonType(type): 41 | _instance_lock = threading.Lock() 42 | 43 | def __call__(cls, *args, **kwargs): 44 | if not hasattr(cls, "_instance"): 45 | with cls._instance_lock: # 加锁 46 | cls._instance = super().__call__(*args, **kwargs) 47 | return cls._instance 48 | 49 | 50 | class Aria2Server(metaclass=SingletonType): 51 | """ 52 | aria2进程对象 53 | """ 54 | 55 | def __init__(self, *args: str, daemon=False): 56 | """ 57 | :param args: 启动aria2的命令行参数 58 | :param daemon: True:aria2随python解释器同生共死 59 | """ 60 | self.cmd = list(args) if args else [] 61 | if daemon: 62 | self.cmd.append("--stop-with-process={:d}".format(os.getpid())) 63 | self.process: subprocess.Popen = None # type: ignore 64 | self._is_running = False 65 | 66 | def start(self) -> None: 67 | self.process = subprocess.Popen(self.cmd) 68 | self._is_running = True 69 | 70 | def wait(self) -> int: 71 | """ 72 | 等待进程结束 73 | :return: ret code 74 | """ 75 | code = self.process.wait() 76 | self._is_running = False 77 | return code 78 | 79 | def terminate(self) -> int: 80 | """ 81 | 结束进程 82 | :return: ret code 83 | """ 84 | self.process.terminate() 85 | return self.wait() 86 | 87 | def kill(self) -> int: 88 | self.process.kill() 89 | return self.wait() 90 | 91 | @property 92 | def pid(self) -> int: 93 | return self.process.pid 94 | 95 | @property 96 | def returncode(self) -> int: 97 | return self.process.returncode 98 | 99 | def __enter__(self) -> "Aria2Server": 100 | self.start() 101 | return self 102 | 103 | def __exit__(self, exc_type, exc_val, exc_tb) -> None: 104 | if self._is_running: 105 | self.terminate() 106 | 107 | 108 | class AsyncAria2Server(Aria2Server): 109 | """ 110 | aria2进程对象 111 | 异步io 112 | """ 113 | 114 | def __init__(self, *args: str, daemon=False): 115 | super().__init__(*args, daemon=daemon) 116 | 117 | async def start(self) -> None: # type: ignore 118 | program, *args = self.cmd 119 | self.process = await asyncio.create_subprocess_exec(program, *args) # type: ignore 120 | self._is_running = True 121 | 122 | async def wait(self) -> int: # type: ignore 123 | code = await self.process.wait() # type: ignore 124 | self._is_running = False 125 | return code 126 | 127 | async def terminate(self) -> int: # type: ignore 128 | self.process.terminate() 129 | return await self.wait() 130 | 131 | async def kill(self) -> int: # type: ignore 132 | self.process.kill() 133 | return await self.wait() 134 | 135 | async def __aenter__(self) -> "AsyncAria2Server": 136 | await self.start() 137 | return self 138 | 139 | async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: 140 | if self._is_running: 141 | await self.terminate() 142 | 143 | 144 | pass 145 | -------------------------------------------------------------------------------- /aioaria2/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | 本模块存放工具函数 4 | """ 5 | import asyncio 6 | import base64 7 | import contextvars 8 | import json 9 | import sys 10 | from functools import partial, wraps 11 | from typing import Any, Awaitable, Callable, Dict, Generator, Optional 12 | 13 | import aiofiles 14 | 15 | from aioaria2.exceptions import Aria2rpcException 16 | 17 | JSON_ENCODING = "utf-8" 18 | DEFAULT_JSON_DECODER = json.loads 19 | DEFAULT_JSON_ENCODER = json.dumps 20 | 21 | 22 | def __init__(): 23 | pass 24 | 25 | 26 | class ResultStore: 27 | """ 28 | websocket 结果缓存类 29 | """ 30 | 31 | _id = 1 # jsonrpc的id 32 | _futures: Dict[int, asyncio.Future] = {} # 暂存id对应的未来对象 33 | 34 | @classmethod 35 | def get_id(cls) -> int: 36 | """ 37 | jsonrpc的自增id 默认的id生成工厂函数 38 | :return: 39 | """ 40 | s = cls._id 41 | cls._id = (cls._id + 1) % sys.maxsize 42 | return s 43 | 44 | @classmethod 45 | def add_result(cls, result: Dict[str, Any]) -> None: 46 | """ 47 | 收到websocket消息的时候,用这个类存储结果 表示一次特定的请求返回了 48 | :param result: jsonrpc的回复格式 {'id':int,'jsonrpc','2.0','result':xxx} 49 | :return: 50 | """ 51 | if isinstance(result, dict): 52 | future = cls._futures.get(result["id"]) 53 | if not future or future.done(): 54 | # 没有这个future fetch没有被调用 future=None 55 | future = asyncio.get_running_loop().create_future() 56 | cls._futures[result["id"]] = future 57 | future.set_result(result) 58 | 59 | @classmethod 60 | async def fetch( 61 | cls, identity: int, timeout: Optional[float] = None 62 | ) -> Dict[str, Any]: 63 | """ 64 | 返回暂存在本类中的结果 65 | :param identity: jsonrpc返回的id 66 | :param timeout: 等待结果超时 67 | :return: 返回完整的jsonrpc 返回数据而不是仅仅有result字段 判断在后续来处理 68 | """ 69 | if cls._futures.get(identity): # 已经存在这个id的future了 不用创建了 70 | future = cls._futures[identity] 71 | else: 72 | future = ( 73 | asyncio.get_running_loop().create_future() 74 | ) # todo 可能会导致Future泄漏吗? 75 | cls._futures[identity] = future 76 | try: 77 | return await asyncio.wait_for(future, timeout) 78 | except asyncio.TimeoutError: 79 | raise Aria2rpcException("jsonrpc over websocket call timeout") from None 80 | finally: 81 | del cls._futures[identity] 82 | 83 | 84 | def run_sync(func: Callable[..., Any]) -> Callable[..., Awaitable[Any]]: 85 | """ 86 | 一个用于包装 sync function 为 async function 的装饰器 87 | :param func: 88 | :return: 89 | """ 90 | 91 | @wraps(func) 92 | async def _wrapper(*args: Any, **kwargs: Any) -> Any: 93 | loop = asyncio.get_running_loop() 94 | pfunc = partial(func, *args, **kwargs) 95 | context = contextvars.copy_context() 96 | context_run = context.run 97 | result = await loop.run_in_executor(None, context_run, pfunc) 98 | return result 99 | 100 | return _wrapper 101 | 102 | 103 | async def add_async_callback(task: asyncio.Task, callback) -> asyncio.Task: 104 | assert asyncio.iscoroutinefunction(callback), "callback must be a coroutinefunction" 105 | result = await task 106 | await callback(task) 107 | return result 108 | 109 | 110 | def add_options_and_position(params: list, options=None, position=None) -> list: 111 | """ 112 | Convenience method for adding options and position to parameters. 113 | """ 114 | if options: 115 | params.append(options) 116 | if position: 117 | if not isinstance(position, int): 118 | try: 119 | position = int(position) 120 | except ValueError: 121 | position = -1 122 | if position >= 0: 123 | params.append(position) 124 | return params 125 | 126 | 127 | async def b64encode_file(path: str) -> str: 128 | """ 129 | 读取文件,转换b64编码 130 | """ 131 | async with aiofiles.open(path, "rb") as handle: 132 | return str(base64.b64encode(await handle.read()), JSON_ENCODING) 133 | 134 | 135 | def get_status(response: Dict) -> Any: 136 | """ 137 | Process a status response. 138 | """ 139 | if not response: 140 | return "error" 141 | try: 142 | return response["status"] 143 | except KeyError: 144 | return "error" 145 | 146 | 147 | def read_configfile(path: str, prefix: str = "--") -> Generator[str, None, None]: 148 | """ 149 | 从配置文件中读取可用配置 150 | :param path: aria2配置文件路径 151 | :param prefix: yield之前的前缀 152 | :return: 153 | """ 154 | with open(path, "r") as f: 155 | for line in f.readlines(): 156 | line = line.strip() 157 | if line and not line.startswith("#"): 158 | yield prefix + line 159 | 160 | 161 | pass 162 | -------------------------------------------------------------------------------- /tests/test.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import unittest 3 | from pprint import pprint 4 | 5 | import ujson 6 | 7 | import aioaria2 8 | 9 | 10 | class TestHTTP(unittest.IsolatedAsyncioTestCase): 11 | async def asyncSetUp(self) -> None: 12 | self.client = aioaria2.Aria2HttpClient( 13 | "http://aria.blackjoe.art:2082/jsonrpc", token="a489451594cda0792df1" 14 | ) 15 | 16 | async def test_addUri(self): 17 | gid = await self.client.addUri(["https://www.google.com"]) 18 | self.assertTrue(isinstance(gid, str)) 19 | 20 | async def test_getVersion(self): 21 | data = await self.client.getVersion() 22 | self.assertTrue(isinstance(data, dict)) 23 | 24 | async def asyncTearDown(self) -> None: 25 | await self.client.close() 26 | 27 | 28 | class TestWebsocket(unittest.IsolatedAsyncioTestCase): 29 | onDownloadStart1 = None 30 | onDownloadStart2 = None 31 | onDownloadComplete1 = None 32 | onDownloadComplete2 = None 33 | 34 | async def asyncSetUp(self) -> None: 35 | # self.client = aioaria2.Aria2HttpClient("test", "http://aria.blackjoe.art:2082/jsonrpc", 36 | # token="a489451594cda0792df1") 37 | self.trigger = await aioaria2.Aria2WebsocketTrigger.new( 38 | "http://aria.blackjoe.art:2082/jsonrpc", 39 | token="a489451594cda0792df1", 40 | loads=ujson.loads, 41 | dumps=ujson.dumps, 42 | ) 43 | 44 | # asyncio.get_running_loop().create_task(self.trigger.listen()) 45 | @self.trigger.onDownloadStart 46 | async def handeler1(trigger, data): 47 | print("我是1号回调,我收到了消息") 48 | self.__class__.onDownloadStart1 = data 49 | 50 | @self.trigger.onDownloadStart 51 | @aioaria2.run_sync 52 | def handeler2(trigger, data): 53 | print("我是2号回调,我收到了消息") 54 | self.__class__.onDownloadStart2 = data 55 | 56 | @self.trigger.onDownloadComplete 57 | async def handeler3(trigger, data): 58 | print("我是3号回调,我收到了消息") 59 | self.__class__.onDownloadComplete1 = data 60 | 61 | @self.trigger.onDownloadComplete 62 | @aioaria2.run_sync 63 | def handeler4(trigger, data): 64 | print("我是4号回调,我收到了消息") 65 | self.__class__.onDownloadComplete2 = data 66 | 67 | await asyncio.sleep(10) 68 | 69 | async def test_connect(self): 70 | data = await self.trigger.getVersion() 71 | pprint(data) 72 | print(self.trigger.functions) 73 | 74 | self.assertTrue(isinstance(data, dict)) 75 | self.assertTrue( 76 | len(self.trigger.functions["aria2.onDownloadStart"]) == 2, 77 | len(self.trigger.functions["aria2.onDownloadStart"]), 78 | ) 79 | self.assertTrue( 80 | len(self.trigger.functions["aria2.onDownloadComplete"]) == 2, 81 | len(self.trigger.functions["aria2.onDownloadComplete"]), 82 | ) 83 | 84 | async def test_onDownloadStart_and_Stop(self): 85 | data = await self.trigger.addUri(["https://www.baidu.com"]) 86 | pprint(data) 87 | self.assertTrue(isinstance(data, str), data) 88 | while True: 89 | if self.onDownloadComplete1 is not None: 90 | self.assertEqual( 91 | self.onDownloadStart1["method"], 92 | "aria2.onDownloadStart", 93 | "回调断言失败,期待{0} 接收到了{1}".format( 94 | "aria2.onDownloadStart", self.onDownloadStart1["method"] 95 | ), 96 | ) 97 | self.assertEqual( 98 | self.onDownloadStart2["method"], 99 | "aria2.onDownloadStart", 100 | "回调断言失败,期待{0} 接收到了{1}".format( 101 | "aria2.onDownloadStart", self.onDownloadStart1["method"] 102 | ), 103 | ) 104 | break 105 | await asyncio.sleep(1) 106 | while True: 107 | if self.onDownloadComplete1 is not None: 108 | self.assertEqual( 109 | self.onDownloadComplete1["method"], 110 | "aria2.onDownloadComplete", 111 | "回调断言失败,期待{0} 接收到了{1}".format( 112 | "aria2.onDownloadComplete", self.onDownloadComplete1["method"] 113 | ), 114 | ) 115 | self.assertEqual( 116 | self.onDownloadComplete2["method"], 117 | "aria2.onDownloadComplete", 118 | "回调断言失败,期待{0} 接收到了{1}".format( 119 | "aria2.onDownloadComplete", self.onDownloadComplete2["method"] 120 | ), 121 | ) 122 | break 123 | await asyncio.sleep(1) 124 | 125 | async def asyncTearDown(self) -> None: 126 | await self.trigger.close() 127 | 128 | 129 | if __name__ == "__main__": 130 | unittest.main() 131 | -------------------------------------------------------------------------------- /README_zh.markdown: -------------------------------------------------------------------------------- 1 | # aioaria2 2 | 3 | 提供aria2异步客户端通信 4 | 5 | [![pypi](https://img.shields.io/pypi/v/aioaria2.svg)](https://pypi.org/project/aioaria2/) 6 | ![python](https://img.shields.io/pypi/pyversions/aioaria2) 7 | ![implementation](https://img.shields.io/pypi/implementation/aioaria2) 8 | ![wheel](https://img.shields.io/pypi/wheel/aioaria2) 9 | ![license](https://img.shields.io/github/license/synodriver/aioaria2.svg) 10 | 11 | ## 提供与aria2异步通信的客户端与管理aria2进程的服务端 12 | 13 | ## 使用方法: 14 | 15 | ### 示例 16 | 17 | ```python 18 | import asyncio 19 | from pprint import pprint 20 | 21 | import aioaria2 22 | 23 | 24 | async def main(): 25 | async with aioaria2.Aria2HttpClient("http://117.0.0.1:6800/jsonrpc", 26 | token="token") as client: 27 | pprint(await client.getVersion()) 28 | 29 | 30 | asyncio.run(main()) 31 | ``` 32 | 33 | ### 相关ip地址应该换成自己的 34 | 35 | ### client对象的相关方法见aria2手册 36 | 37 | ```python 38 | # 示例http协议 39 | import asyncio 40 | from pprint import pprint 41 | 42 | import aioaria2 43 | import ujson 44 | 45 | 46 | async def main(): 47 | async with aioaria2.Aria2HttpClient("http://127.0.0.1:6800/jsonrpc", 48 | token="token", 49 | loads=ujson.loads, 50 | dumps=ujson.dumps) as client: 51 | pprint(await client.addUri(["http://www.demo.com"])) # 即可下载 52 | 53 | 54 | asyncio.run(main()) 55 | ``` 56 | 57 | ```python 58 | # 示例websocket协议 59 | import asyncio 60 | from pprint import pprint 61 | 62 | import aioaria2 63 | import ujson 64 | 65 | 66 | @aioaria2.run_sync 67 | def on_download_complete(trigger, data): 68 | print(f"downlaod complete {data}") 69 | 70 | 71 | async def main(): 72 | client: aioaria2.Aria2WebsocketClient = await aioaria2.Aria2WebsocketClient.new("http://127.0.0.1:6800/jsonrpc", 73 | token="token", 74 | loads=ujson.loads, 75 | dumps=ujson.dumps) 76 | client.onDownloadComplete(on_download_complete) 77 | pprint(await client.addUri(["http://www.demo.com"])) # 即可下载 78 | 79 | 80 | loop = asyncio.get_event_loop() 81 | loop.create_task(main()) 82 | loop.run_forever() 83 | ``` 84 | 85 | - 运行该协程函数即可,方法对应aria2jsonrpc的方法。对于服务端,每一个实例对应一个aria2进程 86 | 87 | ```python 88 | import aioaria2 89 | import asyncio 90 | 91 | 92 | async def main(): 93 | server = aioaria2.AsyncAria2Server(r"aria2c.exe", 94 | r"--conf-path=aria2.conf", "--rpc-secret=admin", daemon=True) 95 | await server.start() 96 | await server.wait() 97 | 98 | 99 | asyncio.run(main()) 100 | ``` 101 | 102 | #### 即可启动一个aria2进程 103 | 104 | [参考选项及设置](http://aria2.github.io/manual/en/html/) 105 | 106 | ### todolist 107 | 108 | - [x] 异步http通信 109 | - [x] 异步websocket通信 110 | - [x] 修复server类的bug 111 | - [x] 单元测试 112 | 113 | 本模块在[aria2jsonrpc](https://xyne.archlinux.ca/projects/python3-aria2jsonrpc) 114 | 之上构建,提供了异步支持,以级websocket支持 115 | 116 | ### windows用户应该加上以下设置 117 | 118 | ``` 119 | # 为了启动异步子进程管理 120 | asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) 121 | asyncio.set_event_loop(asyncio.ProactorEventLoop()) 122 | ``` 123 | 124 | python3.8以后默认是ProactorEventLoop,因此可以不用修改 125 | 126 | #### v1.2.0更新 127 | 128 | 新增Aria2WebsocketTrigger类,可以监听websocket消息, 使用on*方法注册自定义回调函数,既可以是同步也可以是异步的 129 | 130 | 如下 131 | 132 | ``` 133 | @trigger.onDownloadStart 134 | async def onDownloadStart(trigger, future): 135 | print("下载开始{0}".format(future.result())) 136 | ``` 137 | 138 | #### v1.2.3更新 139 | 140 | 可以给一个事件注册多个回调,现在只能是协程函数,同步函数需要自行从utils.run_sync包装 141 | 142 | ``` 143 | @trigger.onDownloadStart 144 | async def callback1(trigger, future): 145 | print("第一个回调{0}".format(future.result())) 146 | 147 | @trigger.onDownloadStart 148 | @run_sync 149 | def callback2(trigger, future): 150 | print("第二个回调{0}".format(future.result())) 151 | ``` 152 | 153 | #### v1.3.0更新 154 | 155 | *本版本大量修改了```Aria2WebsocketTrigger```类的方法,```Aria2HttpClient```保持不变* 156 | 157 | * 回调直接接受```dict```参数而不再是```asyncio.Future``` 158 | * ```Aria2WebsocketTrigger```的相应方法获得了返回值,等效于http协议 159 | * id现在需要传入一个可以调用的id工厂函数作为uuid使用,否则将使用默认的uuid生成器 160 | 161 | 162 | ``` 163 | @trigger.onDownloadStart 164 | async def callback1(trigger, data:dict): 165 | print("第一个回调{0}".format(data)) 166 | 167 | @trigger.onDownloadStart 168 | @run_sync 169 | def callback2(trigger, data:dict): 170 | print("第二个回调{0}".format(data)) 171 | ``` 172 | 173 | ### v1.3.1更新 174 | 175 | * 可以使用自定义的json序列化函数,使用关键字参数```loads=``` ```dumps=```传入构造方法 176 | 177 | ### v1.3.2更新 178 | 179 | * 修复了ws_connect中,如果抛异常则连接不会关闭的问题 180 | * ```Aria2WebsocketTrigger``` 有了一个别名 ```Aria2WebsocketClient``` 181 | 182 | ### v1.3.3 183 | 184 | * 修改了笔误造成的问题 185 | 186 | ### v1.3.4rc1 187 | 188 | * 简单处理websocket掉线 189 | * 修复ping aria2时造成的aria2不讲武德不回复pong的问题 190 | 191 | ### v1.3.4 192 | 193 | * 异步id工厂函数 194 | * 取消websocketclient注册的回调 ```unregister``` 195 | * ```run_sync``` 加入contextvars支持 196 | 197 | ### v1.3.5rc1 198 | 199 | * 更好的关闭 200 | 201 | ### v1.3.5rc2 202 | 203 | * aria2二进制文件解析器 204 | 205 | ```python 206 | from pprint import pprint 207 | from aioaria2 import DHTFile 208 | 209 | pprint(DHTFile.from_file2("dht.dat")) 210 | ``` 211 | 212 | ### v1.3.5rc3 213 | 214 | * 对没完成的task使用强引用以防止被gc 215 | 216 | ### v1.3.6 217 | 218 | * 更新aiohttp最新版,解决不兼容问题 219 | 220 | ![title](https://konachan.com/sample/c7f565c0cd96e58908bc852dd754f61a/Konachan.com%20-%20302356%20sample.jpg) -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | # aioaria2 2 | 3 | 4 | [![pypi](https://img.shields.io/pypi/v/aioaria2.svg)](https://pypi.org/project/aioaria2/) 5 | ![python](https://img.shields.io/pypi/pyversions/aioaria2) 6 | ![implementation](https://img.shields.io/pypi/implementation/aioaria2) 7 | ![wheel](https://img.shields.io/pypi/wheel/aioaria2) 8 | ![license](https://img.shields.io/github/license/synodriver/aioaria2.svg) 9 | 10 | ## Support async rpc call with aria2 and process management 11 | 12 | ## Usage: 13 | 14 | ### example 15 | 16 | ```python 17 | import asyncio 18 | from pprint import pprint 19 | 20 | import aioaria2 21 | 22 | 23 | async def main(): 24 | async with aioaria2.Aria2HttpClient("http://117.0.0.1:6800/jsonrpc", 25 | token="token") as client: 26 | pprint(await client.getVersion()) 27 | 28 | 29 | asyncio.run(main()) 30 | ``` 31 | 32 | ### The ip address should be replaced with your own 33 | 34 | ### See [aria2 manual](http://aria2.github.io/manual/en/html/) for more detail about client methods 35 | 36 | ```python 37 | # exampe of http 38 | import asyncio 39 | from pprint import pprint 40 | 41 | import aioaria2 42 | import ujson 43 | 44 | 45 | async def main(): 46 | async with aioaria2.Aria2HttpClient("http://127.0.0.1:6800/jsonrpc", 47 | token="token", 48 | loads=ujson.loads, 49 | dumps=ujson.dumps) as client: 50 | pprint(await client.addUri(["http://www.demo.com"])) # that would start downloading 51 | 52 | 53 | asyncio.run(main()) 54 | ``` 55 | 56 | ```python 57 | # exampe of websocket 58 | import asyncio 59 | from pprint import pprint 60 | 61 | import aioaria2 62 | import ujson 63 | 64 | 65 | @aioaria2.run_sync 66 | def on_download_complete(trigger, data): 67 | print(f"downlaod complete {data}") 68 | 69 | 70 | async def main(): 71 | client: aioaria2.Aria2WebsocketClient = await aioaria2.Aria2WebsocketClient.new("http://127.0.0.1:6800/jsonrpc", 72 | token="token", 73 | loads=ujson.loads, 74 | dumps=ujson.dumps) 75 | client.onDownloadComplete(on_download_complete) 76 | pprint(await client.addUri(["http://www.demo.com"])) 77 | 78 | 79 | loop = asyncio.get_event_loop() 80 | loop.create_task(main()) 81 | loop.run_forever() 82 | ``` 83 | 84 | - Run that coroutine function and each method represent an aria2-rpc call. As for server, each instance represent an aria2 process. 85 | 86 | ```python 87 | import aioaria2 88 | import asyncio 89 | 90 | 91 | async def main(): 92 | server = aioaria2.AsyncAria2Server(r"aria2c.exe", 93 | r"--conf-path=aria2.conf", "--rpc-secret=admin", daemon=True) 94 | await server.start() 95 | await server.wait() 96 | 97 | 98 | asyncio.run(main()) 99 | ``` 100 | 101 | #### this start an aria2 process 102 | 103 | [Aria2 Manual](http://aria2.github.io/manual/en/html/) 104 | 105 | ### todolist 106 | 107 | - [x] async http 108 | - [x] async websocket 109 | - [x] async process management 110 | - [x] unitest 111 | 112 | This module is built on top of [aria2jsonrpc](https://xyne.archlinux.ca/projects/python3-aria2jsonrpc) 113 | with async and websocket support. 114 | 115 | ### For windows users, you should 116 | 117 | ``` 118 | # for start async aria2 process 119 | asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) 120 | asyncio.set_event_loop(asyncio.ProactorEventLoop()) 121 | ``` 122 | 123 | For python version greater than 3.8, asyncio uses ProactorEventLoop by default, so there is no need to modify 124 | 125 | #### v1.2.0 126 | 127 | new Aria2WebsocketTrigger class for websocket events, use on* methods to add callbacks 128 | 129 | Like 130 | 131 | ``` 132 | @trigger.onDownloadStart 133 | async def onDownloadStart(trigger, future): 134 | print("下载开始{0}".format(future.result())) 135 | ``` 136 | 137 | #### v1.2.3 138 | 139 | Now you can add multiple callbacks for one event ,must be coroutine function or an async callable, use ```aioaria2.run_sync``` to wrap a sync function 140 | 141 | ``` 142 | @trigger.onDownloadStart 143 | async def callback1(trigger, future): 144 | print("第一个回调{0}".format(future.result())) 145 | 146 | @trigger.onDownloadStart 147 | @run_sync 148 | def callback2(trigger, future): 149 | print("第二个回调{0}".format(future.result())) 150 | ``` 151 | 152 | #### v1.3.0 153 | 154 | * Big changes for class```Aria2WebsocketTrigger``` 155 | 156 | * Callbacks now accept```dict```as second parameter instead of```asyncio.Future``` 157 | * methods of class```Aria2WebsocketTrigger``` now have same return value as ```Aria2HttpClient``` 158 | * ```id``` parameter now accept a callable as idfactory to generate uuid, otherwise default uuid factory is used. 159 | 160 | 161 | ``` 162 | @trigger.onDownloadStart 163 | async def callback1(trigger, data:dict): 164 | print("第一个回调{0}".format(data)) 165 | 166 | @trigger.onDownloadStart 167 | @run_sync 168 | def callback2(trigger, data:dict): 169 | print("第二个回调{0}".format(data)) 170 | ``` 171 | 172 | ### v1.3.1 173 | 174 | * custom json library with keyword arguments ```loads``` ```dumps``` 175 | 176 | ### v1.3.2 177 | 178 | * fix unclosed client_session when exception occurs during ws_connect 179 | * alias for ```Aria2WebsocketTrigger```,named ```Aria2WebsocketClient``` 180 | 181 | ### v1.3.3 182 | 183 | * fix method problems in client 184 | 185 | ### v1.3.4rc1 186 | 187 | * handle reconnect simply 188 | * handle InvalidstateError while trying to ping aria2 189 | 190 | ### v1.3.4 191 | 192 | * add async id factory support 193 | * allow unregister callbacks in websocketclient 194 | * add contextvars support in ```run_sync``` 195 | 196 | ### v1.3.5rc1 197 | 198 | * graceful shutdown 199 | 200 | ### v1.3.5rc2 201 | 202 | * add parser for aria2 files 203 | 204 | ```python 205 | from pprint import pprint 206 | from aioaria2 import DHTFile 207 | 208 | pprint(DHTFile.from_file2("dht.dat")) 209 | ``` 210 | 211 | ### v1.3.5rc3 212 | 213 | * add strong ref to pending tasks 214 | 215 | ### v1.3.6 216 | 217 | * update latest aiohttp version -------------------------------------------------------------------------------- /aioaria2/parser.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | See https://aria2.github.io/manual/en/html/technical-notes.html 4 | """ 5 | from dataclasses import dataclass 6 | from ipaddress import IPv4Address, IPv6Address 7 | from pathlib import Path 8 | from typing import IO, List, Union 9 | 10 | 11 | @dataclass 12 | class InFlightPiece: 13 | index: int 14 | length: int 15 | piece_bitfield_length: int 16 | piece_bitfield: bytes 17 | 18 | @classmethod 19 | def from_file(cls, file: IO[bytes], version: int) -> "InFlightPiece": 20 | index = int.from_bytes(file.read(4), "big" if version == 1 else "little") 21 | length = int.from_bytes(file.read(4), "big" if version == 1 else "little") 22 | piece_bitfield_length = int.from_bytes( 23 | file.read(4), "big" if version == 1 else "little" 24 | ) 25 | piece_bitfield = file.read(piece_bitfield_length) 26 | return cls( 27 | index=index, 28 | length=length, 29 | piece_bitfield_length=piece_bitfield_length, 30 | piece_bitfield=piece_bitfield, 31 | ) 32 | 33 | def save(self, file: IO[bytes], version: int) -> None: 34 | file.write(self.index.to_bytes(4, "big" if version == 1 else "little")) 35 | file.write(self.length.to_bytes(4, "big" if version == 1 else "little")) 36 | file.write( 37 | len(self.piece_bitfield).to_bytes(4, "big" if version == 1 else "little") 38 | ) 39 | file.write(self.piece_bitfield) 40 | 41 | 42 | @dataclass 43 | class ControlFile: 44 | """ 45 | Parse .aria2 files 46 | """ 47 | 48 | version: int 49 | ext: bytes 50 | info_hash_length: int 51 | info_hash: bytes 52 | piece_length: int 53 | total_length: int 54 | upload_length: int 55 | bitfield_length: int 56 | bitfield: bytes 57 | num_inflight_piece: int 58 | inflight_pieces: List[InFlightPiece] 59 | 60 | @classmethod 61 | def from_file(cls, file: Union[str, Path, IO[bytes]]) -> "ControlFile": 62 | should_close: bool = False 63 | try: 64 | if isinstance(file, (str, Path)): 65 | file_ = open(file, "rb") 66 | should_close = True 67 | else: 68 | file_ = file # type: ignore 69 | version = int.from_bytes(file_.read(2), "big") 70 | ext = file_.read(4) 71 | info_hash_length = int.from_bytes( 72 | file_.read(4), "big" if version == 1 else "little" 73 | ) 74 | if info_hash_length == 0 and ext[3] & 1 == 1: 75 | raise ValueError( 76 | '"infoHashCheck" extension is enabled but info hash length is 0' 77 | ) 78 | info_hash = file_.read(info_hash_length) 79 | piece_length = int.from_bytes( 80 | file_.read(4), "big" if version == 1 else "little" 81 | ) 82 | total_length = int.from_bytes( 83 | file_.read(8), "big" if version == 1 else "little" 84 | ) 85 | upload_length = int.from_bytes( 86 | file_.read(8), "big" if version == 1 else "little" 87 | ) 88 | bitfield_length = int.from_bytes( 89 | file_.read(4), "big" if version == 1 else "little" 90 | ) 91 | bitfield = file_.read(bitfield_length) 92 | num_inflight_piece = int.from_bytes( 93 | file_.read(4), "big" if version == 1 else "little" 94 | ) 95 | inflight_pieces = [ 96 | InFlightPiece.from_file(file_, version) 97 | for _ in range(num_inflight_piece) 98 | ] 99 | 100 | return cls( 101 | version=version, 102 | ext=ext, 103 | info_hash_length=info_hash_length, 104 | info_hash=info_hash, 105 | piece_length=piece_length, 106 | total_length=total_length, 107 | upload_length=upload_length, 108 | bitfield_length=bitfield_length, 109 | bitfield=bitfield, 110 | num_inflight_piece=num_inflight_piece, 111 | inflight_pieces=inflight_pieces, 112 | ) 113 | finally: 114 | if should_close: 115 | try: 116 | file_.close() 117 | except: 118 | pass 119 | 120 | def save(self, file: IO[bytes]) -> None: 121 | file.write(self.version.to_bytes(2, "big" if self.version == 1 else "little")) 122 | file.write(self.ext) 123 | file.write( 124 | len(self.info_hash).to_bytes(4, "big" if self.version == 1 else "little") 125 | ) 126 | file.write(self.info_hash) 127 | file.write( 128 | self.piece_length.to_bytes(4, "big" if self.version == 1 else "little") 129 | ) 130 | file.write( 131 | self.total_length.to_bytes(8, "big" if self.version == 1 else "little") 132 | ) 133 | file.write( 134 | self.upload_length.to_bytes(8, "big" if self.version == 1 else "little") 135 | ) 136 | file.write( 137 | len(self.bitfield).to_bytes(4, "big" if self.version == 1 else "little") 138 | ) 139 | file.write(self.bitfield) 140 | file.write( 141 | len(self.inflight_pieces).to_bytes( 142 | 4, "big" if self.version == 1 else "little" 143 | ) 144 | ) 145 | for piece in self.inflight_pieces: 146 | piece.save(file, self.version) 147 | 148 | 149 | @dataclass 150 | class NodeInfo: 151 | plen: int 152 | compact_peer_info: tuple 153 | node_id: bytes 154 | 155 | @classmethod 156 | def from_file(cls, file: IO[bytes]) -> "NodeInfo": 157 | plen = int.from_bytes(file.read(1), "big") 158 | file.read(7) 159 | class_ = IPv4Address if plen == 6 else IPv6Address 160 | temp = file.read(plen) 161 | compact_peer_info = (class_(temp[:-2]), int.from_bytes(temp[-2:], "big")) 162 | file.read(24 - plen) 163 | node_id = file.read(20) 164 | file.read(4) 165 | return cls(plen=plen, compact_peer_info=compact_peer_info, node_id=node_id) 166 | 167 | def save(self, file: IO[bytes]) -> None: 168 | file.write(self.plen.to_bytes(1, "big")) 169 | file.write(b"\x00" * 7) 170 | 171 | file.write(self.compact_peer_info[0].packed) 172 | file.write(self.compact_peer_info[1].to_bytes(2, "big")) 173 | 174 | file.write(b"\x00" * (24 - self.plen)) 175 | file.write(self.node_id) 176 | file.write(b"\x00" * 4) 177 | 178 | 179 | @dataclass 180 | class DHTFile: 181 | """ 182 | Parse dht.dat/dht6.dat files 183 | """ 184 | 185 | mgc: bytes 186 | fmt: bytes 187 | ver: bytes 188 | mtime: int 189 | localnode_id: bytes 190 | num_node: int 191 | nodes: List[NodeInfo] 192 | 193 | @classmethod 194 | def from_file(cls, file: Union[str, Path, IO[bytes]]) -> "DHTFile": 195 | should_close: bool = False 196 | try: 197 | if isinstance(file, (str, Path)): 198 | file_ = open(file, "rb") 199 | should_close = True 200 | else: 201 | file_ = file # type: ignore 202 | mgc = file_.read(2) 203 | assert mgc == b"\xa1\xa2", "wrong magic number" 204 | fmt = file_.read(1) 205 | assert fmt == b"\x02", "wrong format idr" 206 | ver = file_.read(2) 207 | # assert ver == b'\x00\x03', "wrong version number" 208 | file_.read(3) 209 | mtime = int.from_bytes(file_.read(8), "big") 210 | file_.read(8) 211 | localnode_id = file_.read(20) 212 | file_.read(4) 213 | num_node = int.from_bytes(file_.read(4), "big") 214 | file_.read(4) 215 | nodes = [NodeInfo.from_file(file_) for _ in range(num_node)] 216 | return cls( 217 | mgc=mgc, 218 | fmt=fmt, 219 | ver=ver, 220 | mtime=mtime, 221 | localnode_id=localnode_id, 222 | num_node=num_node, 223 | nodes=nodes, 224 | ) 225 | finally: 226 | if should_close: 227 | try: 228 | file_.close() 229 | except: 230 | pass 231 | 232 | def save(self, file: IO[bytes]) -> None: 233 | file.write(self.mgc) 234 | file.write(self.fmt) 235 | file.write(self.ver) 236 | file.write(b"\x00" * 3) 237 | file.write(self.mtime.to_bytes(8, "big")) 238 | file.write(b"\x00" * 8) 239 | file.write(self.localnode_id) 240 | file.write(b"\x00" * 4) 241 | file.write(len(self.nodes).to_bytes(4, "big")) 242 | file.write(b"\x00" * 4) 243 | for node in self.nodes: 244 | node.save(file) 245 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /aioaria2/client.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | 本模块负责与aria2 json rpc通信 4 | 5 | 参数参考 http://aria2.github.io/manual/en/html/aria2c.html#rpc-interface 6 | """ 7 | import asyncio 8 | import warnings 9 | from collections import defaultdict 10 | from inspect import stack 11 | from typing import ( 12 | Any, 13 | AsyncGenerator, 14 | DefaultDict, 15 | Dict, 16 | Iterable, 17 | List, 18 | NoReturn, 19 | Optional, 20 | Union, 21 | ) 22 | 23 | import aiohttp 24 | from typing_extensions import Literal 25 | 26 | from aioaria2.exceptions import Aria2rpcException 27 | from aioaria2.typing import CallBack, IdFactory 28 | from aioaria2.utils import ( 29 | DEFAULT_JSON_DECODER, 30 | DEFAULT_JSON_ENCODER, 31 | ResultStore, 32 | add_options_and_position, 33 | b64encode_file, 34 | get_status, 35 | ) 36 | 37 | 38 | class _Aria2BaseClient: 39 | """ 40 | 与jsonrpc通信的接口 41 | """ 42 | 43 | def __init__( 44 | self, 45 | url: str, 46 | identity: Optional[IdFactory] = None, 47 | mode: Literal["normal", "batch", "format"] = "normal", 48 | token: str = None, 49 | queue: asyncio.Queue = None, 50 | ): 51 | """ 52 | :param identity: 操作rpc接口的id 生成他的工厂函数 53 | :param url: rpc服务器地址 54 | :param mode: 55 | normal - 立即处理请求 56 | batch - 请求加入队列,由process_queue方法处理 57 | format - 返回rpc请求json结构 58 | :param token: rpc服务器密码 (用 `--rpc-secret`设置) 59 | """ 60 | self.queue = asyncio.Queue() if queue is None else queue 61 | self.identity = identity or ResultStore.get_id 62 | self.url = url 63 | self.mode = mode 64 | self.token = token 65 | 66 | async def jsonrpc( 67 | self, method: str, params: Optional[List[Any]] = None, prefix: str = "aria2." 68 | ) -> Union[Dict[str, Any], List[Any], str, None]: 69 | """ 70 | 组装json数据 71 | :param method: 请求方法 72 | :param params: 参数 73 | :param prefix: 请求的头部 74 | :return: 响应结果 75 | """ 76 | if not params: 77 | params = [] 78 | 79 | if self.token is not None: 80 | token_str = f"token:{self.token}" 81 | if method == "multicall": 82 | for param in params[0]: 83 | try: 84 | param["params"].insert(0, token_str) 85 | except KeyError: 86 | param["params"] = [token_str] 87 | else: 88 | params.insert(0, token_str) 89 | 90 | identity = self.identity() 91 | if asyncio.iscoroutine(identity): 92 | identity = await identity 93 | req_obj = { 94 | "jsonrpc": "2.0", 95 | "id": identity, 96 | "method": prefix + method, 97 | "params": params, 98 | } 99 | if self.mode == "batch": 100 | await self.queue.put(req_obj) 101 | return None 102 | if self.mode == "format": 103 | return req_obj 104 | return await self.send_request(req_obj) 105 | 106 | async def send_request(self, req_obj: Dict[str, Any]) -> Union[Dict[str, Any], Any]: 107 | raise NotImplementedError 108 | 109 | async def process_queue(self) -> List: 110 | """ 111 | 处理队列请求 112 | """ 113 | # req_obj = self.queue 114 | # self.queue = [] 115 | # return await self.send_request(req_obj) 116 | req_objs = [] 117 | while not self.queue.empty(): 118 | req_objs.append(await self.queue.get()) 119 | 120 | results = await asyncio.gather(*map(self.send_request, req_objs)) 121 | return results 122 | 123 | async def addUri( 124 | self, uris: List[str], options: Dict[str, Any] = None, position: int = None 125 | ) -> str: 126 | """ 127 | 添加新的任务到下载队列 128 | :param uris: 要添加的链接 务必是list HTTP/FTP/SFTP/BitTorrent URIs (strings) 129 | :param options:附加参数 130 | :param position:在下载队列中的位置 131 | :return:包含结果的json 132 | {"result":"2089b05ecca3d829"} 133 | """ 134 | params = [uris] 135 | params = add_options_and_position(params, options, position) 136 | return await self.jsonrpc("addUri", params) # type: ignore 137 | 138 | async def addTorrent( 139 | self, 140 | torrent: str, 141 | uris: List[str] = None, 142 | options: Dict[str, Any] = None, 143 | position: int = None, 144 | ) -> Union[Dict[str, Any], Any]: 145 | """ 146 | 下载种子 147 | :param torrent: base64编码的种子文件 base64.b64encode(open("xxx.torrent","rb").read()) 148 | :param uris: uri用于播种 对于单个文件,URI可以是指向资源的完整URI;如果URI以/结尾,则添加到torrent文件。 149 | 对于多文件的torrent,则会在torrent文件中添加名称和路径以生成每个文件的URI。 150 | :param options:参数字典 151 | :param position:在下载队列中的位置 152 | :return:包含结果的json 153 | {"result":"2089b05ecca3d829"} 154 | """ 155 | params = [torrent] 156 | if not uris: 157 | uris = [] 158 | params.append(uris) # type: ignore 159 | params = add_options_and_position(params, options, position) 160 | return await self.jsonrpc("addTorrent", params) 161 | 162 | async def addMetalink( 163 | self, metalink: List, options: Dict[str, Any] = None, position: int = None 164 | ) -> Union[Dict[str, Any], Any]: 165 | """ 166 | 此方法通过上载一个来添加一个Metalink下载 metalink是一个用base64编码的字符串,其中包含“.metalink”文件。 167 | :param metalink: base64编码的字符串 base64.b64encode(open('file.meta4',"rb").read()) 168 | :param options:参数字典 169 | :param position:在下载队列中的位置 170 | :return:包含结果的json 171 | {"result":"2089b05ecca3d829"} 172 | """ 173 | params = [metalink] 174 | params = add_options_and_position(params, options, position) 175 | return await self.jsonrpc("addMetalink", params) 176 | 177 | async def remove(self, gid: str) -> Union[Dict[str, Any], Any]: 178 | """ 179 | 正在下载的停止下载 停止的删除状态 180 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 181 | :return:包含结果的json 182 | {"result":"2089b05ecca3d829"} 183 | """ 184 | params = [gid] 185 | return await self.jsonrpc("remove", params) 186 | 187 | async def forceRemove(self, gid: str) -> Union[Dict[str, Any], Any]: 188 | """ 189 | 此方法删除由gid表示的下载。这个方法的行为就像aria2.remove(),但是会立即生效,而不执行任何需要时间的操作, 190 | 例如联系BitTorrent跟踪器先取消下载。 191 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 192 | :return:包含结果的json 193 | """ 194 | params = [gid] 195 | return await self.jsonrpc("forceRemove", params) 196 | 197 | async def pause(self, gid: str) -> Union[Dict[str, Any], Any]: 198 | """ 199 | 此方法暂停由gid(字符串)表示的下载。暂停下载的状态变为暂停。如果下载是活动的,下载将放在等待队列的前面。 200 | 当状态暂停时,下载不会启动。要将状态更改为等待,请使用aria2.unpause()方法 201 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 202 | :return:包含结果的json 203 | """ 204 | params = [gid] 205 | return await self.jsonrpc("pause", params) 206 | 207 | async def pauseAll(self) -> Union[Dict[str, Any], Any]: 208 | """ 209 | 这个方法相当于为每个活动/等待的下载调用aria2.pause()。这个方法返回OK。 210 | :return:包含结果的json 211 | """ 212 | return await self.jsonrpc("pauseAll") 213 | 214 | async def forcePause(self, gid) -> Union[Dict[str, Any], Any]: 215 | """ 216 | 此方法暂停由gid表示的下载。这个方法的行为就像aria2.pause(),只是这个方法暂停下载,不执行任何需要时间的操作, 217 | 比如联系BitTorrent tracker先取消下载。 218 | :param gid:GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 219 | :return:包含结果的json 220 | """ 221 | params = [gid] 222 | return await self.jsonrpc("forcePause", params) 223 | 224 | async def forcePauseAll(self) -> Union[Dict[str, Any], Any]: 225 | """ 226 | 这个方法相当于对每个活动/等待的下载调用aria2.forcePause()。这个方法返回OK 227 | :return:包含结果的json 228 | """ 229 | return await self.jsonrpc("forcePauseAll") 230 | 231 | async def unpause(self, gid: str) -> Union[Dict[str, Any], Any]: 232 | """ 233 | 此方法将由gid (string)表示的下载状态从暂停更改为等待,从而使下载符合重新启动的条件。此方法返回未暂停下载的GID。 234 | :param gid:GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 235 | :return:包含结果的json 236 | """ 237 | params = [gid] 238 | return await self.jsonrpc("unpause", params) 239 | 240 | async def unpauseAll(self) -> Union[Dict[str, Any], Any]: 241 | """ 242 | 这个方法相当于对每个暂停的下载调用aria2.unpause()。这个方法返回OK 243 | :return:包含结果的json 244 | """ 245 | return await self.jsonrpc("unpauseAll") 246 | 247 | async def tellStatus( 248 | self, gid: str, keys: List[str] = None 249 | ) -> Union[Dict[str, Any], Any]: 250 | """ 251 | 此方法返回由gid(字符串)表示的下载进度 252 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 253 | :param keys:如果指定,则返回结果只包含keys数组中的键。如果键keys空或省略,则返回结果包含所有键。 254 | status: 255 | active: 当前下载/做种 256 | waiting: 等待队列 257 | paused: 当前暂停的下载 258 | error: 出错的下载 259 | complete: 停止和完成的下载 260 | removed: 用户移除的下载 261 | totalLength: 文件总长度(字节) 262 | completedLength: 已经下载的长度(字节) 263 | uploadLength: 已经上传的长度(字节) 264 | bitfield:下载进度的十六进制表示。最高位对应于下标0处的块。任何为1的位表示已加载的块,而为0位表示尚未加载和/或缺失的块。 265 | 任何最后的溢出位都被置为0。当下载尚未启动时,此key将不包含在响应中。 266 | downloadSpeed: 下载速度 单位bytes/sec 267 | uploadSpeed: 上传速度 单位bytes/sec 268 | infoHash: hash值 仅针对bt下载 269 | numSeeders: 连接的peer数,仅针对bt下载 270 | seeder: 如果本机在做种true 否则false 仅针对bt下载 271 | pieceLength: 分片长度 单位byte 272 | numPieces: 分片数量 273 | connections: aria2连接的种子/服务器数量 274 | errorCode: 错误代码 仅针对停止/完成的下载 275 | errorMessage: 与errorCode关联的错误信息 276 | followedBy: 下载结果的gid列表 277 | following: 此结果在followedBy中,是他的反向连接 278 | belongsTo: 父下载的GID。有些下载是另一个下载的一部分。例如,如果一个文件在一个Metalink有BitTorrent资源, 279 | 下载的“.torrent“文件是父文件的一部分。如果此下载没有父节点,则此键将不会包含在响应中。 280 | dir: 保存文件的路径 281 | files: 返回文件列表。这个列表的元素与aria2.getFiles()方法中使用的结构相同 282 | bittorrent: 从种子文件检索到的信息结构,仅针对bt 包含以下 283 | announceList: 匿名uri的列表。如果种子文件包含announcement而没有announcer -list, announcement将被转换成announcer -list格式 284 | comment: 种子的评论 如果可以将使用utf-8 285 | creationDate: 创造时间轴。该值是自元年以来的整数,以秒为单位。 286 | mode: 文件模式。不是single就是multi 287 | info: 包含json数据的信息 包括以下key 288 | name: 字典的名字。如果可以将使用utf-8 289 | verifiedLength: 文件被哈希检查时已验证的字节数。此键仅在对下载任务进行散列检查时存在。 290 | verifyIntegrityPending: 如果此下载任务正在队列中等待hash检查,则为true。此key仅在下载文件在队列中时存在。 291 | 292 | :return: json格式的结果 293 | {'bitfield': '0000000000', 294 | 'completedLength': '901120', 295 | 'connections': '1', 296 | 'dir': '/downloads', 297 | 'downloadSpeed': '15158', 298 | 'files': [{'index': '1', 299 | 'length': '34896138', 300 | 'completedLength': '34896138', 301 | 'path': '/downloads/file', 302 | 'selected': 'true', 303 | 'uris': [{'status': 'used', 304 | 'uri': 'http://example.org/file'}]}], 305 | 'gid': '2089b05ecca3d829', 306 | 'numPieces': '34', 307 | 'pieceLength': '1048576', 308 | 'status': 'active', 309 | 'totalLength': '34896138', 310 | 'uploadLength': '0', 311 | 'uploadSpeed': '0'} 312 | 313 | :example: await client.tellStatus(xxxxx,["status","downloadSpeed"]) 314 | """ 315 | params = [gid] 316 | if keys: 317 | params.append(keys) # type: ignore 318 | return await self.jsonrpc("tellStatus", params) 319 | 320 | async def getUris(self, gid: str) -> Union[Dict[str, Any], Any]: 321 | """ 322 | 此方法返回由gid(字符串)表示的下载中使用的uri。响应是一个json,它包含以下键。值是字符串 323 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 324 | :return:json格式的结果 325 | [{'status': 'used', 如果url已经使用就是used ,还在队列中就是waiting 326 | 'uri': 'http://example.org/file'},...] 327 | """ 328 | params = [gid] 329 | return await self.jsonrpc("getUris", params) 330 | 331 | async def getFiles(self, gid: str) -> Union[Dict[str, Any], Any]: 332 | """ 333 | 返回下载文件列表 334 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 335 | :return: 336 | [{'index': '1', 件的索引,从1开始,与文件在多文件中出现的顺序相同 337 | 'length': '34896138', 文件大小 byte 338 | 'completedLength': '34896138', 此文件的完整长度(以字节为单位)。请注意, 339 | completedLength的和可能小于aria2.tellStatus()方法返回的completedLength。 340 | 这是因为在aria2.getFiles()中completedLength只包含完成的片段。 341 | 另一方面,在aria2.tellStatus()中完成的长度也包括部分完成的片段。 342 | 'path': '/downloads/file', 路径 343 | 'selected': 'true', 如果此文件是由——select-file选项选择的,则为true。 344 | 如果——select-file没有指定,或者这是单文件的torrent文件,或者根本不是torrent下载,那么这个值总是为真。否则错误。 345 | 'uris': [{'status': 'used', 返回此文件的uri列表。元素类型与aria2.getUris()方法中使用的结构相同。 346 | 'uri': 'http://example.org/file'}]}] 347 | """ 348 | params = [gid] 349 | return await self.jsonrpc("getFiles", params) 350 | 351 | async def getPeers(self, gid: str) -> Union[Dict[str, Any], Any]: 352 | """ 353 | 返回下载对象,仅适用于bt 354 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 355 | :return: 356 | [{'amChoking': 'true', 357 | 'bitfield': 'ffffffffffffffffffffffffffffffffffffffff', 358 | 'downloadSpeed': '10602', 359 | 'ip': '10.0.0.9', 360 | 'peerChoking': 'false', 361 | 'peerId': 'aria2%2F1%2E10%2E5%2D%87%2A%EDz%2F%F7%E6', 362 | 'port': '6881', 363 | 'seeder': 'true', 364 | 'uploadSpeed': '0'}, 365 | {'amChoking': 'false', 366 | 'bitfield': 'ffffeff0fffffffbfffffff9fffffcfff7f4ffff', 367 | 'downloadSpeed': '8654', 368 | 'ip': '10.0.0.30', 369 | 'peerChoking': 'false', 370 | 'peerId': 'bittorrent client758', 371 | 'port': '37842', 372 | 'seeder': 'false', 373 | 'uploadSpeed': '6890'}] 374 | """ 375 | params = [gid] 376 | return await self.jsonrpc("getPeers", params) 377 | 378 | async def getServers(self, gid: str) -> Union[Dict[str, Any], Any]: 379 | """ 380 | 此方法返回当前连接的HTTP(S)/FTP/SFTP服务器的下载,用gid(字符串)表示。响应是一个结构数组,包含以下key。值是字符串。 381 | :param gid:GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 382 | :return: 383 | [{'index': '1', 384 | 'servers': [{'currentUri': 'http://example.org/file', # 正在使用的 385 | 'downloadSpeed': '10467', # 下载速度(byte/sec) 386 | 'uri': 'http://example.org/file'}]}]} #原url 387 | """ 388 | params = [gid] 389 | return await self.jsonrpc("getServers", params) 390 | 391 | async def tellActive( 392 | self, keys: Optional[List[str]] = None 393 | ) -> Union[Dict[str, Any], Any]: 394 | """ 395 | 此方法返回活动下载列表。响应是一个与aria2.tellStatus()方法返回的结构相同的数组。关于keys参数,请参考aria2.tellStatus()方法。 396 | :param keys: 如果指定,则返回结果只包含keys数组中的键。如果键keys空或省略,则返回结果包含所有键。 397 | :return: 398 | json格式的结果 399 | {'bitfield': '0000000000', 400 | 'completedLength': '901120', 401 | 'connections': '1', 402 | 'dir': '/downloads', 403 | 'downloadSpeed': '15158', 404 | 'files': [{'index': '1', 405 | 'length': '34896138', 406 | 'completedLength': '34896138', 407 | 'path': '/downloads/file', 408 | 'selected': 'true', 409 | 'uris': [{'status': 'used', 410 | 'uri': 'http://example.org/file'}]}], 411 | 'gid': '2089b05ecca3d829', 412 | 'numPieces': '34', 413 | 'pieceLength': '1048576', 414 | 'status': 'active', 415 | 'totalLength': '34896138', 416 | 'uploadLength': '0', 417 | 'uploadSpeed': '0'} 418 | 419 | :example: await client.tellActive(xxxxx,["status","downloadSpeed"]) 420 | """ 421 | params = [keys] if keys else None 422 | return await self.jsonrpc("tellActive", params) 423 | 424 | async def tellWaiting( 425 | self, offset: int, num: int, keys: List[str] = None 426 | ) -> Union[Dict[str, Any], Any]: 427 | """ 428 | 此方法返回等待下载的列表,包括暂停的下载。偏移量是一个整数,它指定等待在前面的下载的偏移量。 429 | num是一个整数,指定最大值。要返回的下载数量。关于keys参数,请参考aria2.tellStatus()方法。 430 | :param offset: 起始索引 431 | :param num: 数量 432 | :param keys: 同上 433 | :return: 同上 434 | """ 435 | params = [offset, num] 436 | if keys: 437 | params.append(keys) # type: ignore 438 | return await self.jsonrpc("tellWaiting", params) 439 | 440 | async def tellStopped( 441 | self, offset: int, num: int, keys: List[str] = None 442 | ) -> Union[Dict[str, Any], Any]: 443 | """ 444 | 此方法返回停止下载的列表 关于keys参数,请参考aria2.tellStatus()方法。 445 | :param offset: 起始索引 446 | :param num: 数量 447 | :param keys: 同上 448 | :return: 同上 449 | """ 450 | params = [offset, num] 451 | if keys: 452 | params.append(keys) # type: ignore 453 | return await self.jsonrpc("tellStopped", params) 454 | 455 | async def changePosition( 456 | self, gid: str, pos: int, how: str 457 | ) -> Union[Dict[str, Any], Any]: 458 | """ 459 | 此方法更改队列中由gid表示的下载位置。pos是一个整数。how是一个字符串。 460 | 如果how是POS_SET,它将下载移动到相对于队列开头的位置。 461 | 如果how是POS_CUR,它将下载移动到相对于当前位置的位置。 462 | 如果how是POS_END,它将下载移动到相对于队列末尾的位置。 463 | 如果目标位置小于0或超过队列的末尾,则将下载分别移动到队列的开头或末尾。响应是一个表示结果位置的整数。 464 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 465 | :param pos: 偏移量 466 | :param how: 方法 467 | :return:位置 int 468 | """ 469 | params = [gid, pos, how] 470 | return await self.jsonrpc("changePosition", params) 471 | 472 | async def changeUri( 473 | self, 474 | gid: str, 475 | fileIndex: int, 476 | delUris: List[str], 477 | addUris: List[str], 478 | position: int = None, 479 | ) -> Union[Dict[str, Any], Any]: 480 | """ 481 | 此方法从delUris中删除uri,并将addUris中的uri附加到以gid表示的下载中。 482 | delUris和addUris是字符串列表。下载可以包含多个文件,每个文件都附加了uri。 483 | fileIndex用于选择要删除/附加哪个文件。fileIndex从0开始。 484 | 485 | 当位置被省略时,uri被附加到列表的后面。这个方法首先执行删除,然后执行添加。 486 | position是删除uri后的位置,而不是调用此方法时的位置。在删除URI时,如果下载中存在相同的URI, 487 | 则对于deluri中的每个URI只删除一个URI。换句话说,如果有三个uri http://example.org/aria2,并且您希望将它们全部删除, 488 | 则必须在delUris中指定(至少)3个http://example.org/aria2。这个方法返回一个包含两个整数的列表。第一个整数是删除uri的数目。 489 | 第二个整数是添加的uri的数量。 490 | 491 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 492 | :param fileIndex:用于选择要删除/附加哪个文件。fileIndex从0开始。 493 | :param delUris: 要删除的 494 | :param addUris: 要添加的 495 | :param position: position用于指定在现有的等待URI列表中插入URI的位置 0开始 496 | :return: 497 | [0, 1] 498 | """ 499 | params = [gid, fileIndex, delUris, addUris] 500 | if position: 501 | params.append(position) 502 | return await self.jsonrpc("changeUri", params) 503 | 504 | async def getOption(self, gid: str) -> Union[Dict[str, Any], Any]: 505 | """ 506 | 此方法返回由gid表示的下载选项。 507 | 注意,此方法不会返回没有默认值,也没有在配置文件或RPC方法的命令行上设置这些的选项 508 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 509 | :return: 510 | {'allow-overwrite': 'false', 511 | 'allow-piece-length-change': 'false', 512 | 'always-resume': 'true', 513 | 'async-dns': 'true', 514 | """ 515 | params = [gid] 516 | return await self.jsonrpc("getOption", params) 517 | 518 | async def changeOption(self, gid: str, options: Dict[str, Any]) -> Literal["OK"]: 519 | """ 520 | 此方法动态地更改由gid (string)表示的下载选项。options是一个字典。输入文件小节中列出的选项是可用的,但以下选项除外: 521 | dry-run 522 | metalink-base-uri 523 | parameterized-uri 524 | pause 525 | piece-length 526 | rpc-save-upload-metadata 527 | 除了以下选项外,更改活动下载的其他选项将使其重新启动(重新启动本身由aria2管理,不需要用户干预): 528 | bt-max-peers 529 | bt-request-peer-speed-limit 530 | bt-remove-unselected-file 531 | force-save 532 | max-download-limit 533 | max-upload-limit 534 | 此方法返回OK表示成功。 535 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值。 536 | :param options: 537 | :return: 538 | "OK" 539 | """ 540 | params = [gid, options] 541 | return await self.jsonrpc("changeOption", params) # type: ignore 542 | 543 | async def getGlobalOption(self) -> Union[Dict[str, Any], Any]: 544 | """ 545 | 此方法返回全局选项。响应是一个结构体。它的键是选项的名称。值是字符串。 546 | 注意,此方法不会返回没有默认值的选项,也不会在配置文件或RPC方法的命令行上设置这些选项。 547 | 因为全局选项用作新添加下载选项的模板,所以响应包含aria2.getOption()方法返回的键。 548 | :return: 549 | """ 550 | return await self.jsonrpc("getGlobalOption") 551 | 552 | async def changeGlobalOption( 553 | self, options: Dict[str, Any] 554 | ) -> Union[Dict[str, Any], Any]: 555 | """ 556 | 此方法动态更改全局选项。options是一个字典。以下是可供选择的方案: 557 | bt-max-open-files 558 | download-result 559 | keep-unfinished-download-result 560 | log 561 | log-level 562 | max-concurrent-downloads 563 | max-download-result 564 | max-overall-download-limit 565 | max-overall-upload-limit 566 | optimize-concurrent-downloads 567 | save-cookies 568 | save-session 569 | server-stat-of 570 | :param options: 参数字典 571 | :return: "OK" 572 | """ 573 | params = [options] 574 | return await self.jsonrpc("changeGlobalOption", params) 575 | 576 | async def getGlobalStat(self) -> Dict[str, str]: 577 | """ 578 | 此方法返回全局统计信息,如总下载和上传速度。响应是一个字典,包含以下键。值是字符串 579 | :return: 580 | {'downloadSpeed': '21846', 581 | 'numActive': '2', #活动下载数 582 | 'numStopped': '0', # 当前会话中停止的下载数量。以 --max-download-result 选项为上限 583 | 'numWaiting': '0', # 等待下载数 584 | 'uploadSpeed': '0'} 585 | """ 586 | return await self.jsonrpc("getGlobalStat") # type: ignore 587 | 588 | async def purgeDownloadResult(self) -> Literal["OK"]: 589 | """ 590 | 此方法将已完成/错误/删除的下载清除到空闲内存。这个方法返回OK。 591 | :return: "OK" 592 | """ 593 | return await self.jsonrpc("purgeDownloadResult") # type: ignore 594 | 595 | async def removeDownloadResult(self, gid: str) -> Literal["OK"]: 596 | """ 597 | 此方法从内存中删除由gid表示的已完成/错误/已删除的下载。此方法返回OK表示成功。 598 | :param gid: GID(或GID)是管理每个下载的密钥。每个下载将被分配一个唯一的GID。GID在aria2中存储为64位二进制值 599 | :return: "OK" 600 | """ 601 | params = [gid] 602 | return await self.jsonrpc("removeDownloadResult", params) # type: ignore 603 | 604 | async def getVersion(self) -> Dict[str, str]: 605 | """ 606 | 此方法返回aria2的版本和启用的特性列表 607 | :return:一个字典,包含以下键 608 | version: aria2的版本 609 | enabledFeatures: 启用功能的列表。每个特性都以字符串的形式给出 610 | """ 611 | return await self.jsonrpc("getVersion") # type: ignore 612 | 613 | async def getSessionInfo(self) -> Dict[str, str]: 614 | """ 615 | 返回会话信息 616 | :return:字典,包含以下键 617 | sessionId: 每次调用aria2时生成的会话id 618 | """ 619 | return await self.jsonrpc("getSessionInfo") # type: ignore 620 | 621 | async def shutdown(self) -> Literal["OK"]: 622 | """ 623 | 关闭aria2 624 | :return: "OK" 625 | """ 626 | return await self.jsonrpc("shutdown") # type: ignore 627 | 628 | async def forceShutdown(self) -> Literal["OK"]: 629 | """ 630 | 该方法关闭了aria2()。该方法的行为像aria2.shutdown而没有执行任何需要时间的操作,比如联系BitTorrent跟踪器先注销下载。 631 | :return:"OK" 632 | """ 633 | return await self.jsonrpc("forceShutdown") # type: ignore 634 | 635 | async def saveSession(self) -> Literal["OK"]: 636 | """ 637 | 此方法将当前会话保存到由——save-session选项指定的文件中。 638 | :return:"OK" 639 | """ 640 | return await self.jsonrpc("saveSession") # type: ignore 641 | 642 | async def multicall(self, methods: List[Dict[str, Any]]) -> List[Any]: 643 | """ 644 | 此方法将多个方法调用封装在单个请求中 645 | :param methods: 字典数组。结构包含两个键:methodName和params。methodName是要调用的方法名,params是包含方法调用参数的数组。 646 | 此方法返回一个响应数组。元素要么是一个包含方法调用返回值的单条目数组,要么是一个封装的方法调用失败时的fault元素结构。 647 | example: [{'methodName':'aria2.addUri', 648 | 'params':[['http://example.org']]}, 649 | {'methodName':'aria2.addTorrent', 650 | 'params':[base64.b64encode(open('file.torrent').read())]}] 651 | :return: 652 | """ 653 | return await self.jsonrpc("multicall", [methods], prefix="system.") # type: ignore 654 | 655 | async def listMethods(self) -> List[str]: 656 | """ 657 | 此方法在字符串数组中返回所有可用的RPC方法。与其他方法不同,此方法不需要秘密令牌。这是安全的,因为这个方法只返回可用的方法名。 658 | :return: 659 | """ 660 | return await self.jsonrpc("listMethods", prefix="system.") # type: ignore 661 | 662 | async def listNotifications(self) -> List[str]: 663 | """ 664 | 此方法以字符串数组的形式返回所有可用的RPC通知。与其他方法不同,此方法不需要秘密令牌。 665 | 这是安全的,因为这个方法只返回可用的通知名称。 666 | :return: 667 | """ 668 | return await self.jsonrpc("listNotifications", prefix="system.") # type: ignore 669 | 670 | # ----------------------以下是进一步抽象的高级方法---------------------------- 671 | 672 | async def add_torrent( 673 | self, 674 | path: str, 675 | uris: List[str] = None, 676 | options: Dict[str, Any] = None, 677 | position: int = None, 678 | ) -> Union[Dict[str, Any], Any]: 679 | """ 680 | 直接添加种子路径 681 | :param path: 文件路径 682 | :param uris: 参考addTorrent方法 683 | :param options: 参考addTorrent方法 684 | :param position: 参考addTorrent方法 685 | :return:包含结果的json gid 686 | """ 687 | torrent = await b64encode_file(path) 688 | return await self.addTorrent(torrent, uris, options, position) 689 | 690 | async def add_metalink( 691 | self, path, options: Dict[str, Any] = None, position: int = None 692 | ) -> Union[Dict[str, Any], Any]: 693 | """ 694 | 直接添加metalink路径 695 | :param path: 文件路径 696 | :param options: 参考addMetalink方法 697 | :param position: 参考addMetalink方法 698 | :return: 699 | """ 700 | metalink = await b64encode_file(path) 701 | return await self.addMetalink(metalink, options, position) # type: ignore 702 | 703 | async def get_status(self, gid: str) -> Dict[str, str]: 704 | """ 705 | 取一个gid的状态 706 | :param gid: 707 | :return: 708 | """ 709 | response = await self.tellStatus(gid, ["status"]) 710 | return get_status(response) 711 | 712 | async def get_statuses(self, gids: Iterable) -> AsyncGenerator[ 713 | Literal["active", "waiting", "paused", "error", "complete", "removed", "error"], 714 | None, 715 | ]: 716 | """ 717 | 取得每个gid的状态 是一个异步生成器 718 | :param gids: 719 | :return: 720 | """ 721 | methods = [ 722 | {"methodName": "aria2.tellStatus", "params": [gid, ["gid", "status"]]} 723 | for gid in gids 724 | ] 725 | results = await self.multicall(methods) 726 | if results: 727 | status = {r[0]["gid"]: r[0]["status"] for r in results} 728 | for gid in gids: 729 | try: 730 | yield status[gid] 731 | except KeyError: 732 | yield "error" 733 | else: 734 | for gid in gids: 735 | yield "error" 736 | 737 | async def close(self) -> None: 738 | await self.client_session.close() # type: ignore 739 | 740 | 741 | class Aria2HttpClient(_Aria2BaseClient): 742 | def __init__( 743 | self, 744 | url: str, 745 | identity: IdFactory = None, 746 | mode: Literal["normal", "batch", "format"] = "normal", 747 | token: str = None, 748 | queue=None, 749 | client_session: aiohttp.ClientSession = None, 750 | **kw, 751 | ): 752 | """ 753 | :param identity: 操作rpc接口的id 754 | :param url: rpc服务器地址 755 | :param mode: 756 | normal - 立即处理请求 757 | batch - 请求加入队列,由process_queue方法处理 758 | format - 返回rpc请求json结构 759 | :param token: rpc服务器密码 (用 `--rpc-secret`设置) 760 | :param queue: 请求队列 761 | :param client_session: aiohttp的session 762 | :param kw: aiohttp.session.post的相关参数 763 | new in v1.3.1 loads: DEFAULT_JSON_DECODER json.loads 764 | dumps json.dumps 765 | """ 766 | super().__init__(url, identity, mode, token, queue) 767 | self.kw = kw 768 | self.loads = ( 769 | self.kw.pop("loads") if "loads" in self.kw else DEFAULT_JSON_DECODER 770 | ) # json serialize 771 | self.dumps = ( 772 | self.kw.pop("dumps") if "dumps" in self.kw else DEFAULT_JSON_ENCODER 773 | ) 774 | self.client_session = client_session or aiohttp.ClientSession( 775 | json_serialize=self.dumps 776 | ) # aiohttp的会话 777 | 778 | async def send_request(self, req_obj: Dict[str, Any]) -> Union[Dict[str, Any], Any]: 779 | try: 780 | async with self.client_session.post( 781 | self.url, json=req_obj, **self.kw 782 | ) as response: 783 | try: 784 | data = self.loads(await response.text()) 785 | return data["result"] 786 | except KeyError: 787 | raise Aria2rpcException(f"unexpected result: {data}") 788 | except aiohttp.ClientConnectionError as err: 789 | raise Aria2rpcException( 790 | str(err), connection_error=("Cannot connect" in str(err)) 791 | ) from err 792 | 793 | async def __aenter__(self): 794 | return self 795 | 796 | async def __aexit__(self, exc_type, exc_val, exc_tb): 797 | await self.close() 798 | 799 | 800 | class Aria2WebsocketClient(_Aria2BaseClient): 801 | def __init__( 802 | self, 803 | url: str, 804 | identity: IdFactory = None, 805 | mode: Literal["normal", "batch", "format"] = "normal", 806 | token=None, 807 | queue: asyncio.Queue = None, 808 | client_session: aiohttp.ClientSession = None, 809 | reconnect_interval: int = 1, 810 | **kw, 811 | ): 812 | """ 813 | :param identity: 操作rpc接口的id 工厂函数 814 | :param url: rpc服务器地址 815 | :param mode: 816 | normal - 立即处理请求 817 | batch - 请求加入队列,由process_queue方法处理 818 | format - 返回rpc请求json结构 819 | :param token: rpc服务器密码 (用 `--rpc-secret`设置) 820 | :param queue: 请求队列 821 | :param kw: ws_connect()的相关参数 822 | new in v1.3.1 loads: DEFAULT_JSON_DECODER json.loads 823 | dumps json.dumps 824 | """ 825 | if (stack()[1].function) not in ("new", "eval_in_context"): 826 | warnings.warn( 827 | "do not init directly,use {0} instead".format( 828 | f"await {self.__class__.__name__}.new" 829 | ) 830 | ) 831 | 832 | super().__init__(url, identity, mode, token, queue) 833 | self.kw = kw 834 | self.loads = ( 835 | self.kw.pop("loads") if "loads" in self.kw else DEFAULT_JSON_DECODER 836 | ) # json serialize 837 | self.dumps = ( 838 | self.kw.pop("dumps") if "dumps" in self.kw else DEFAULT_JSON_ENCODER 839 | ) 840 | self._client_session = client_session or aiohttp.ClientSession( 841 | json_serialize=self.dumps 842 | ) # type: aiohttp.ClientSession 843 | self.reconnect_interval = reconnect_interval 844 | self.functions: DefaultDict[str, List[CallBack]] = defaultdict( 845 | list 846 | ) # 存放各个notice的回调 847 | self._listen_task = None # type: asyncio.Task 848 | self._pending_tasks = set() 849 | 850 | @classmethod 851 | async def new( 852 | cls, 853 | url: str, 854 | identity: IdFactory = None, 855 | mode: Literal["normal", "batch", "format"] = "normal", 856 | token: str = None, 857 | queue: asyncio.Queue = None, 858 | client_session: aiohttp.ClientSession = None, 859 | reconnect_interval: int = 1, 860 | **kw, 861 | ) -> "Aria2WebsocketClient": 862 | """ 863 | 真正创建实例 864 | :param queue: 继承下来的任务队列 865 | :param identity: 操作rpc接口的id 866 | :param url: rpc服务器地址 867 | :param mode: 同上 868 | :param token: rpc服务器密码 (用 `--rpc-secret`设置) 869 | :param kw: ws_connect()的相关参数 870 | :return: 真正的实例 871 | """ 872 | try: 873 | self = cls( 874 | url, 875 | identity, 876 | mode, 877 | token, 878 | queue, 879 | client_session, 880 | reconnect_interval, 881 | **kw, 882 | ) 883 | self.client_session = await self._client_session.ws_connect( 884 | self.url, **self.kw 885 | ) 886 | self._listen_task = asyncio.create_task(self.listen()) 887 | return self 888 | except aiohttp.ClientError as err: 889 | await self._client_session.close() 890 | raise Aria2rpcException( 891 | str(err), connection_error=("Cannot connect" in str(err)) 892 | ) from err 893 | 894 | async def send_request(self, req_obj: Dict[str, Any]) -> Union[Dict[str, Any], str, NoReturn]: # type: ignore 895 | try: 896 | await self.client_session.send_json(req_obj, dumps=self.dumps) 897 | data = await ResultStore.fetch( 898 | req_obj["id"], self.kw.get("timeout", None) or 10.0 899 | ) 900 | return data["result"] 901 | except KeyError: # 'error':xxx 902 | raise Aria2rpcException(f"unexpected result: {data}") 903 | except Aria2rpcException as err: 904 | if not self.closed and "timeout" in err.msg: 905 | await asyncio.sleep(self.reconnect_interval) 906 | return await self.send_request(req_obj) 907 | except Exception as err: 908 | raise Aria2rpcException( 909 | str(err), connection_error=("Cannot connect" in str(err)) 910 | ) from err 911 | 912 | @property 913 | def closed(self) -> bool: 914 | return self.client_session.closed 915 | 916 | async def close(self) -> None: 917 | if self._listen_task and not self._listen_task.cancelled(): 918 | self._listen_task.cancel() 919 | try: 920 | await self._listen_task 921 | except asyncio.CancelledError: 922 | pass 923 | await super().close() 924 | await self._client_session.close() 925 | 926 | async def listen(self) -> None: 927 | """ 928 | 轮询返回数据 929 | """ 930 | try: 931 | while not self.closed: 932 | try: 933 | data = await self.client_session.receive_json(loads=self.loads) 934 | except TypeError: # aria2抽了 935 | continue 936 | if not data or not isinstance(data, dict): 937 | continue 938 | task = asyncio.create_task(self.handle_event(data)) 939 | self._pending_tasks.add(task) # add a strong ref 940 | task.add_done_callback(self._pending_tasks.discard) 941 | except asyncio.CancelledError: 942 | pass 943 | 944 | async def handle_event(self, data: dict) -> None: 945 | """ 946 | 基础回调函数 当websocket服务器向客户端发送数据时候 此方法会自动调用 947 | :param data: receive_json包装对象 显然,与http不同,你得自己过滤出result字段,因为这个是完整的jsonrpc响应 948 | :return: 949 | """ 950 | # 1.2.3更新:回调只能是异步函数了,同一种可以注册多个方法,同步的需要用run_sync包装 951 | if "result" in data or "error" in data: 952 | # 等效于post数据的结果 953 | ResultStore.add_result(data) 954 | # if "result" in self.functions: 955 | # await asyncio.gather(*map(lambda x: x(self, future), self.functions["result"])) 956 | if "method" in data: 957 | # 来自aria2的notice信息 958 | method = data["method"] 959 | if method in self.functions: # TODO 有鬼 960 | await asyncio.gather( 961 | *map(lambda x: x(self, data), self.functions[method]) 962 | ) 963 | 964 | def register(self, func: CallBack, type_: str) -> None: 965 | """ 966 | 注册响应websocket的事件 967 | :return: 968 | """ 969 | self.functions[type_].append(func) 970 | 971 | def unregister(self, func: CallBack, type_: str) -> None: 972 | """ 973 | 取消注册响应websocket的事件 974 | :return: 975 | """ 976 | try: 977 | self.functions[type_].remove(func) 978 | except ValueError: 979 | pass 980 | 981 | # ----------以下这些推荐作为装饰器使用--------------------- 982 | 983 | def onDownloadStart(self, func: CallBack) -> CallBack: 984 | """ 985 | 注册回调事件 986 | func的第二个参数的task.result()型如{'jsonrpc': '2.0', 'method': 'aria2.onDownloadStart', 'params': [{'gid': '5de52dc4eba048ca'}]} 987 | :param func: 988 | :return: 989 | """ 990 | self.register(func, "aria2.onDownloadStart") 991 | return func 992 | 993 | def onDownloadPause(self, func: CallBack) -> CallBack: 994 | """ 995 | 注册回调事件 996 | :param func: 997 | :return: 998 | """ 999 | self.register(func, "aria2.onDownloadPause") 1000 | return func 1001 | 1002 | def onDownloadStop(self, func: CallBack) -> CallBack: 1003 | """ 1004 | 注册回调事件 1005 | :param func: 1006 | :return: 1007 | """ 1008 | self.register(func, "aria2.onDownloadStop") 1009 | return func 1010 | 1011 | def onDownloadComplete(self, func: CallBack) -> CallBack: 1012 | """ 1013 | 注册回调事件 1014 | :param func: 1015 | :return: 1016 | """ 1017 | self.register(func, "aria2.onDownloadComplete") 1018 | return func 1019 | 1020 | def onDownloadError(self, func: CallBack) -> CallBack: 1021 | """ 1022 | 注册回调事件 1023 | :param func: 1024 | :return: 1025 | """ 1026 | self.register(func, "aria2.onDownloadError") 1027 | return func 1028 | 1029 | def onBtDownloadComplete(self, func: CallBack) -> CallBack: 1030 | """ 1031 | 注册回调事件 1032 | :param func: 1033 | :return: 1034 | """ 1035 | self.register(func, "aria2.onBtDownloadComplete") 1036 | return func 1037 | 1038 | async def __aenter__(self): 1039 | if not hasattr(self, "client_session"): 1040 | self.client_session: aiohttp.ClientWebSocketResponse = ( 1041 | await self._client_session.ws_connect(self.url, **self.kw) 1042 | ) 1043 | self._listen_task = asyncio.create_task(self.listen()) 1044 | return self 1045 | return self 1046 | 1047 | async def __aexit__(self, exc_type, exc_val, exc_tb): 1048 | await self.close() 1049 | 1050 | 1051 | Aria2WebsocketTrigger = Aria2WebsocketClient 1052 | --------------------------------------------------------------------------------