Skip to content

The only downloader you need. 下载器的集大成者。

feat(aria2): 支持 system.multicall 与 JSON-RPC Batch

XiaoYouChRc20f6e622625
diff --git a/app/services/aria2_rpc.py b/app/services/aria2_rpc.py
index 1c2a46aa..7f76b622 100644
--- a/app/services/aria2_rpc.py
+++ b/app/services/aria2_rpc.py
@@ -76,8 +76,8 @@ def buildError(rpcId: Any, code: int, message: str) -> dict:
return {"jsonrpc": "2.0", "id": rpcId, "error": {"code": code, "message": message}}
-def toHttpStatus(response: dict) -> int:
- if "error" not in response:
+def toHttpStatus(response: dict | list) -> int:
+ if isinstance(response, list) or "error" not in response:
return 200
return 400 if response["error"]["code"] in (ARIA2_ERROR, JSONRPC_INVALID_REQUEST) else 500
@@ -154,41 +154,65 @@ class Aria2RpcService:
async for message in stream.messages():
await stream.send(json.dumps(await self._run(message), ensure_ascii=False))
- async def _run(self, body: bytes) -> dict:
+ async def _run(self, message: bytes) -> dict | list:
try:
- data = json.loads(body)
+ data = json.loads(message)
except ValueError:
return buildError(None, JSONRPC_PARSE_ERROR, "Parse error.")
+ if isinstance(data, list):
+ return [await self._runRequest(request) for request in data if isinstance(request, dict)]
if not isinstance(data, dict):
return buildError(None, JSONRPC_INVALID_REQUEST, "Invalid Request.")
- rpcId = data.get("id")
- method = data.get("method")
- params = data.get("params", [])
- if "id" not in data or not isinstance(method, str):
+ return await self._runRequest(data)
+
+ async def _runRequest(self, request: dict) -> dict:
+ rpcId = request.get("id")
+ method = request.get("method")
+ params = request.get("params", [])
+ if "id" not in request or not isinstance(method, str):
return buildError(rpcId, JSONRPC_INVALID_REQUEST, "Invalid Request.")
if not isinstance(params, list):
return buildError(rpcId, JSONRPC_INVALID_PARAMS, "Invalid params.")
+ try:
+ if method == "system.multicall":
+ result = await self._runMulticall(params)
+ else:
+ result = await self._runMethod(method, params)
+ except RpcError as e:
+ return buildError(rpcId, ARIA2_ERROR, str(e))
+ return {"jsonrpc": "2.0", "id": rpcId, "result": result}
+
+ async def _runMulticall(self, params: list) -> list:
+ if not params or not isinstance(params[0], list):
+ raise RpcError("The parameter at 0 has wrong type.")
+ results = []
+ for call in params[0]:
+ call = call if isinstance(call, dict) else {}
+ callParams = call.get("params")
+ try:
+ results.append([await self._runMethod(call.get("methodName"), callParams if isinstance(callParams, list) else [])])
+ except RpcError as e:
+ results.append({"code": ARIA2_ERROR, "message": str(e)})
+ return results
+
+ async def _runMethod(self, method: Any, params: list) -> Any:
token = ""
if params and isinstance(params[0], str) and params[0].startswith("token:"):
token, params = params[0].removeprefix("token:"), params[1:]
if (secret := cfg.aria2RpcToken.value) and token != secret:
await asyncio.sleep(UNAUTHORIZED_DELAY)
- return buildError(rpcId, ARIA2_ERROR, "Unauthorized")
-
- try:
- match method:
- case "aria2.getVersion":
- result = {"version": VERSION, "enabledFeatures": ["HTTPS"]}
- case "aria2.getGlobalOption":
- result = {"dir": cfg.downloadFolder.value}
- case "aria2.addUri":
- result = self._addUri(params)
- case _:
- raise RpcError(f"No such method: {method}")
- except RpcError as e:
- return buildError(rpcId, ARIA2_ERROR, str(e))
- return {"jsonrpc": "2.0", "id": rpcId, "result": result}
+ raise RpcError("Unauthorized")
+
+ match method:
+ case "aria2.getVersion":
+ return {"version": VERSION, "enabledFeatures": ["HTTPS"]}
+ case "aria2.getGlobalOption":
+ return {"dir": cfg.downloadFolder.value}
+ case "aria2.addUri":
+ return self._addUri(params)
+ case _:
+ raise RpcError(f"No such method: {method}")
def _addUri(self, params: list) -> str:
if not params:
diff --git a/tests/test_aria2_rpc.py b/tests/test_aria2_rpc.py
index 7d76fa48..db1acfd6 100644
--- a/tests/test_aria2_rpc.py
+++ b/tests/test_aria2_rpc.py
@@ -168,7 +168,7 @@ class TestTransport:
class TestRequestErrors:
@pytest.mark.parametrize("body, status, code", [
(b"{not json", 500, -32700),
- (b"[]", 400, -32600),
+ (b'"x"', 400, -32600),
(b'{"jsonrpc":"2.0","method":"aria2.getVersion"}', 400, -32600),
(b'{"jsonrpc":"2.0","id":"x","method":"aria2.getVersion","params":{}}', 500, -32602),
])
@@ -283,3 +283,58 @@ class TestAddUri:
assert url == "https://fail.test/f"
assert isinstance(error, TaskError)
assert (error.message, error.params) == ("发生了意外错误:{detail}", {"detail": "unreachable"})
+
+
+class TestMulticall:
+ async def test_each_call_returns_its_result_in_a_list(self, aria2):
+ result = await aria2.call("system.multicall", [[
+ {"methodName": "aria2.addUri", "params": [["https://a.test/1.zip"]]},
+ {"methodName": "aria2.addUri", "params": [["https://a.test/2.zip"]]},
+ ]])
+
+ [[first], [second]] = result["result"]
+ assert isGid(first) and isGid(second)
+ await waitFor(lambda: len(aria2.added) == 2)
+
+ async def test_token_is_checked_per_call(self, aria2, monkeypatch):
+ monkeypatch.setattr(cfg.aria2RpcToken, "value", "secret")
+ response = await aria2.post({"jsonrpc": "2.0", "id": "x", "method": "system.multicall", "params": [[
+ {"methodName": "aria2.getVersion", "params": ["token:secret"]},
+ {"methodName": "aria2.getVersion", "params": []},
+ ]]})
+
+ assert response.status == 200
+ [[version], fault] = response.json()["result"]
+ assert version["version"] == VERSION
+ assert fault == {"code": 1, "message": "Unauthorized"}
+
+ async def test_nested_multicall_is_a_fault(self, aria2):
+ result = await aria2.call("system.multicall", [[{"methodName": "system.multicall", "params": [[]]}]])
+
+ assert result["result"] == [{"code": 1, "message": "No such method: system.multicall"}]
+
+
+class TestBatch:
+ async def test_each_request_gets_its_own_response(self, aria2):
+ response = await aria2.post([
+ {"jsonrpc": "2.0", "id": "a", "method": "aria2.getVersion"},
+ {"jsonrpc": "2.0", "id": "b", "method": "aria2.tellStatus", "params": ["g"]},
+ ])
+
+ assert response.status == 200
+ version, error = response.json()
+ assert (version["id"], version["result"]["version"]) == ("a", VERSION)
+ assert (error["id"], error["error"]) == ("b", {"code": 1, "message": "No such method: aria2.tellStatus"})
+
+ @pytest.mark.parametrize("batch, expected", [([], []), ([1, "x"], [])])
+ async def test_non_object_items_are_skipped(self, aria2, batch, expected):
+ response = await aria2.post(batch)
+
+ assert (response.status, response.json()) == (200, expected)
+
+ async def test_batch_over_websocket(self, aria2):
+ async with aria2.connect() as ws:
+ await ws.send(json.dumps([{"jsonrpc": "2.0", "id": "a", "method": "aria2.getVersion"}]))
+ [response] = json.loads(await ws.recv())
+
+ assert response["result"]["version"] == VERSION