Skip to content

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

fix(aria2): 网页投递按 aria2 原始行为兼容 #769

XiaoYouChRee5c738756e5
diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.py
index 14d75d02..fae41a42 100644
--- a/Ghost-Downloader-3.py
+++ b/Ghost-Downloader-3.py
@@ -86,11 +86,13 @@ def startApp(application, isSilent=False):
MainWindow.refreshThemeColor()
- featureService, taskService, browserService, aria2RpcServer, updateService, runtimeStatusService = createServices(
+ featureService, taskService, browserService, updateService, runtimeStatusService = createServices(
coroutineRunner, categoryService, speedMeter,
)
loadPacks(featureService, coroutineRunner, speedMeter)
+ from app.services.aria2_rpc import Aria2RpcServer
+ from app.services.loopback_server import LoopbackServer
from app.services.plan import Plan
plan = Plan(allCompleted=lambda: taskService.runningCount() == 0)
taskService.tasksAllCompleted.connect(plan.trigger)
@@ -201,17 +203,10 @@ def startApp(application, isSilent=False):
cfg.browserExtensionPort.valueChanged.connect(onBrowserPortChanged)
- aria2RpcServer.taskDraftRequested.connect(onBrowserDraft)
- if cfg.isAria2RpcEnabled.value:
- aria2RpcServer.start()
- cfg.isAria2RpcEnabled.valueChanged.connect(aria2RpcServer.setEnabled)
-
- def onAria2PortChanged(_port):
- if cfg.isAria2RpcEnabled.value:
- aria2RpcServer.stop()
- aria2RpcServer.start()
-
- cfg.aria2RpcPort.valueChanged.connect(onAria2PortChanged)
+ aria2RpcServer = Aria2RpcServer(coroutineRunner, featureService.parse, taskService.add, requestDraft=onBrowserDraft)
+ aria2Server = LoopbackServer(coroutineRunner, aria2RpcServer.handle,
+ isEnabled=cfg.isAria2RpcEnabled, port=cfg.aria2RpcPort)
+ aria2Server.start()
application.clipboardListener.urlsDetected.connect(lambda urls: show().addUrls(urls))
@@ -263,7 +258,7 @@ def startApp(application, isSilent=False):
updateService.changed.connect(onUpdateChanged)
checkUpdateAtStartup(updateService)
- application.aboutToQuit.connect(lambda: stopEngine(taskService, browserService, aria2RpcServer, featureService, coroutineRunner, speedMeter, updateService))
+ application.aboutToQuit.connect(lambda: stopEngine(taskService, browserService, aria2Server, featureService, coroutineRunner, speedMeter, updateService))
if __name__ == "__main__":
diff --git a/app/services/aria2_rpc.py b/app/services/aria2_rpc.py
index 924ee34d..0a46b4af 100644
--- a/app/services/aria2_rpc.py
+++ b/app/services/aria2_rpc.py
@@ -2,275 +2,227 @@ from __future__ import annotations
import asyncio
import json
-import socket
-from functools import partial
+from dataclasses import dataclass
+from http import HTTPStatus
from pathlib import Path
from secrets import token_hex
from typing import TYPE_CHECKING, Any
-from app.signal import Signal
from loguru import logger
from app.config.cfg import cfg
from app.config.constants import VERSION
+from app.models.task import TaskOptions
+from app.services.websocket_stream import acceptWebSocket, readHead
if TYPE_CHECKING:
from app.models.task import Task
JSONRPC_PARSE_ERROR = -32700
JSONRPC_INVALID_REQUEST = -32600
-JSONRPC_METHOD_NOT_FOUND = -32601
+JSONRPC_INVALID_PARAMS = -32602
+ARIA2_ERROR = 1
+MAX_REQUEST_SIZE = 2 * 1024 * 1024
+UNAUTHORIZED_DELAY = 1
+
+
+class RpcError(Exception):
+ pass
+
+
+@dataclass(frozen=True)
+class HttpRequest:
+ method: str
+ path: str
+ headers: dict[str, str]
+
+
+def parseHead(head: bytes) -> HttpRequest | None:
+ lines = head.decode("latin-1").split("\r\n")
+ parts = lines[0].split(" ")
+ if len(parts) != 3:
+ return None
+ headers = {}
+ for line in lines[1:]:
+ name, sep, value = line.partition(":")
+ if sep:
+ headers[name.strip().lower()] = value.strip()
+ return HttpRequest(parts[0], parts[1].split("?")[0].split("#")[0], headers)
+
+
+def buildHttpResponse(status: int, body: bytes = b"", headers: dict[str, str] | None = None) -> bytes:
+ lines = [
+ f"HTTP/1.1 {status} {HTTPStatus(status).phrase}",
+ "Access-Control-Allow-Origin: *",
+ f"Content-Length: {len(body)}",
+ "Connection: close",
+ *(f"{name}: {value}" for name, value in (headers or {}).items()),
+ ]
+ return ("\r\n".join(lines) + "\r\n\r\n").encode("latin-1") + body
+
+
+def buildPreflightHeaders(request: HttpRequest) -> dict[str, str]:
+ if "origin" not in request.headers or "access-control-request-method" not in request.headers:
+ return {}
+ return {
+ "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
+ "Access-Control-Allow-Headers": request.headers.get("access-control-request-headers", ""),
+ "Access-Control-Max-Age": "1728000",
+ }
+
+
+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:
+ return 200
+ return 400 if response["error"]["code"] in (ARIA2_ERROR, JSONRPC_INVALID_REQUEST) else 500
+
+
+def toText(options: dict, key: str) -> str:
+ value = options.get(key)
+ return value if isinstance(value, str) else ""
+
+
+def toHeaders(options: dict) -> dict[str, str]:
+ raw = options.get("header")
+ lines = [raw] if isinstance(raw, str) else [h for h in raw if isinstance(h, str)] if isinstance(raw, list) else []
+ headers: dict[str, str] = {}
+ for line in lines:
+ name, sep, value = line.partition(":")
+ if sep:
+ headers[name.strip()] = value.strip()
+
+ names = {name.lower() for name in headers}
+ if (userAgent := toText(options, "user-agent")) and "user-agent" not in names:
+ headers["User-Agent"] = userAgent
+ if (referer := toText(options, "referer")) and "referer" not in names:
+ headers["Referer"] = referer
+ return headers
class Aria2RpcServer:
- taskDraftRequested = Signal(list)
+ """aria2 JSON-RPC 的最小兼容:getVersion 与 addUri,HTTP POST 与 WebSocket 共用 /jsonrpc。
+
+ handle 在 loop 线程运行;解析完成的 Task 在 dispatcher 线程交给 addTask 或 requestDraft。
+ """
- def __init__(self, coroutineRunner, parse, addTask) -> None:
+ def __init__(self, coroutineRunner, parse, addTask, requestDraft) -> None:
self._coroutineRunner = coroutineRunner
self._parse = parse
self._addTask = addTask
- self._serveWorkId: str | None = None
+ self._requestDraft = requestDraft
- @property
- def isRunning(self) -> bool:
- return self._serveWorkId is not None
-
- def start(self) -> None:
- if self._serveWorkId is not None:
+ async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ head = await readHead(reader)
+ request = parseHead(head) if head else None
+ if request is None:
return
- port = cfg.aria2RpcPort.value
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- try:
- sock.bind(('127.0.0.1', port))
- sock.listen()
- except OSError as e:
- logger.error("Aria2 RPC compat server failed to start on port {}: {}", port, e)
- sock.close()
- return
- sock.setblocking(False)
- self._serveWorkId = self._coroutineRunner.submit(
- self._run(sock), failed=self._onServeFailed)
- logger.info("Aria2 RPC compat server started on port {}", port)
- def stop(self) -> None:
- if self._serveWorkId is None:
+ if request.method == "OPTIONS":
+ writer.write(buildHttpResponse(200, headers=buildPreflightHeaders(request)))
+ elif request.path != "/jsonrpc":
+ writer.write(buildHttpResponse(404))
+ elif request.method == "GET" and request.headers.get("upgrade", "").lower() == "websocket":
+ await self._runWebSocket(reader, writer, head)
return
- self._coroutineRunner.cancel(self._serveWorkId)
- self._serveWorkId = None
-
- def _onServeFailed(self, error) -> None:
- self._serveWorkId = None
- logger.error("Aria2 RPC compat server crashed: {}", error)
-
- def setEnabled(self, enabled: bool) -> None:
- if enabled:
- self.start()
+ elif request.method == "POST":
+ await self._runHttp(reader, writer, request)
else:
- self.stop()
+ writer.write(buildHttpResponse(404))
+ await writer.drain()
- async def _run(self, sock: socket.socket) -> None:
- try:
- server = await asyncio.start_server(self._onConnection, sock=sock)
- except Exception:
- sock.close()
- raise
- async with server:
- await server.serve_forever()
-
- async def _onConnection(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ async def _runHttp(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, request: HttpRequest) -> None:
try:
- await reader.readline()
-
- headers = {}
- while True:
- line = await reader.readline()
- if line == b"\r\n":
- break
- if b":" in line:
- k, v = line.split(b":", 1)
- headers[k.decode().strip().lower()] = v.strip().decode()
-
- if headers.get("upgrade", "").lower() == "websocket":
- await self._onWebSocketConnection(reader, writer, headers)
- return
-
- await self._onHttpRequest(reader, writer, headers)
- except Exception as e:
- logger.warning("Aria2 RPC connection failed: {}", e)
- writer.close()
- await writer.wait_closed()
-
- async def _onHttpRequest(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, headers: dict[str, str]) -> None:
+ length = 0 if "transfer-encoding" in request.headers else int(request.headers.get("content-length", "0"))
+ except ValueError:
+ return
+ if length > MAX_REQUEST_SIZE:
+ return
try:
- contentLength = int(headers.get("content-length", "0"))
- body = await reader.readexactly(contentLength) if contentLength else b""
- response = self._dispatchRpc(body)
- payload = json.dumps(response, ensure_ascii=False).encode("utf-8")
-
- httpHeader = (
- f"HTTP/1.1 200 OK\r\n"
- f"Content-Type: application/json\r\n"
- f"Content-Length: {len(payload)}\r\n"
- f"Connection: close\r\n"
- f"\r\n"
- ).encode("utf-8")
- writer.write(httpHeader + payload)
- await writer.drain()
- except (asyncio.IncompleteReadError, asyncio.LimitOverrunError, ValueError):
- pass
- finally:
- writer.close()
- await writer.wait_closed()
-
- async def _onWebSocketConnection(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, headers: dict[str, str]) -> None:
- import base64
- import hashlib
-
- key = headers.get("sec-websocket-key", "")
- acceptKey = base64.b64encode(
- hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest()
- ).decode()
-
- handshake = (
- f"HTTP/1.1 101 Switching Protocols\r\n"
- f"Upgrade: websocket\r\n"
- f"Connection: Upgrade\r\n"
- f"Sec-WebSocket-Accept: {acceptKey}\r\n"
- f"\r\n"
- ).encode()
- writer.write(handshake)
- await writer.drain()
+ body = await reader.readexactly(length)
+ except asyncio.IncompleteReadError:
+ return
+ response = await self._run(body)
+ payload = json.dumps(response, ensure_ascii=False).encode("utf-8")
+ writer.write(buildHttpResponse(toHttpStatus(response), payload, {"Content-Type": "application/json-rpc"}))
- try:
- while True:
- firstByte = await reader.readexactly(1)
- opcode = firstByte[0] & 0x0F
- if opcode == 0x08:
- break
-
- secondByte = (await reader.readexactly(1))[0]
- isMasked = (secondByte & 0x80) != 0
- payloadLen = secondByte & 0x7F
-
- if payloadLen == 126:
- payloadLen = int.from_bytes(await reader.readexactly(2), "big")
- elif payloadLen == 127:
- payloadLen = int.from_bytes(await reader.readexactly(8), "big")
-
- maskingKey = await reader.readexactly(4) if isMasked else None
- payload = await reader.readexactly(payloadLen)
-
- if isMasked and maskingKey:
- payload = bytes(b ^ maskingKey[i % 4] for i, b in enumerate(payload))
-
- response = self._dispatchRpc(payload)
- responseData = json.dumps(response, ensure_ascii=False).encode("utf-8")
-
- frame = bytearray([0x81])
- if len(responseData) <= 125:
- frame.append(len(responseData))
- elif len(responseData) <= 65535:
- frame.append(126)
- frame.extend(len(responseData).to_bytes(2, "big"))
- else:
- frame.append(127)
- frame.extend(len(responseData).to_bytes(8, "big"))
- frame.extend(responseData)
-
- writer.write(bytes(frame))
- await writer.drain()
- except (asyncio.IncompleteReadError, ConnectionResetError):
- pass
- finally:
- writer.close()
- await writer.wait_closed()
-
- def _dispatchRpc(self, body: bytes) -> dict:
+ async def _runWebSocket(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, head: bytes) -> None:
+ stream = await acceptWebSocket(reader, writer, head, maxSize=MAX_REQUEST_SIZE)
+ if stream is None:
+ return
+ 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:
try:
data = json.loads(body)
- except Exception:
- return {"jsonrpc": "2.0", "id": None, "error": {"code": JSONRPC_PARSE_ERROR, "message": "Parse error"}}
-
+ except ValueError:
+ return buildError(None, JSONRPC_PARSE_ERROR, "Parse error.")
if not isinstance(data, dict):
- return {"jsonrpc": "2.0", "id": None, "error": {"code": JSONRPC_INVALID_REQUEST, "message": "Invalid Request"}}
-
+ return buildError(None, JSONRPC_INVALID_REQUEST, "Invalid Request.")
rpcId = data.get("id")
- method = data.get("method", "")
+ method = data.get("method")
params = data.get("params", [])
-
+ if "id" not in data or not isinstance(method, str):
+ return buildError(rpcId, JSONRPC_INVALID_REQUEST, "Invalid Request.")
if not isinstance(params, list):
- return {"jsonrpc": "2.0", "id": rpcId, "error": {"code": JSONRPC_INVALID_REQUEST, "message": "params must be array"}}
-
- token = cfg.aria2RpcToken.value
- if token:
- if params and isinstance(params[0], str) and params[0].startswith("token:"):
- if params[0] != f"token:{token}":
- return {"jsonrpc": "2.0", "id": rpcId, "error": {"code": 1, "message": "Unauthorized"}}
- params = params[1:]
- else:
- return {"jsonrpc": "2.0", "id": rpcId, "error": {"code": 1, "message": "Unauthorized"}}
- elif params and isinstance(params[0], str) and params[0].startswith("token:"):
- params = params[1:]
-
- if method == "aria2.addUri":
- return self._addUri(rpcId, params)
- if method == "aria2.getVersion":
- return {"jsonrpc": "2.0", "id": rpcId, "result": {"version": VERSION, "enabledFeatures": ["HTTPS"]}}
- return {"jsonrpc": "2.0", "id": rpcId, "error": {"code": JSONRPC_METHOD_NOT_FOUND, "message": "Method not found"}}
-
- def _addUri(self, rpcId: Any, params: list) -> dict:
- uris = params[0] if params and isinstance(params[0], list) else []
- options = params[1] if len(params) > 1 and isinstance(params[1], dict) else {}
+ return buildError(rpcId, JSONRPC_INVALID_PARAMS, "Invalid params.")
+
+ 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.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}
+
+ def _addUri(self, params: list) -> str:
+ if not params:
+ raise RpcError("The parameter at 0 is required but missing.")
+ if not isinstance(params[0], list):
+ raise RpcError("The parameter at 0 has wrong type.")
+ uris = [uri for uri in params[0] if isinstance(uri, str)]
if not uris:
- return {"jsonrpc": "2.0", "id": rpcId, "error": {"code": 1, "message": "No URI provided"}}
-
- url = uris[0]
- filename = options.get("out", "")
- directory = options.get("dir", "")
- rawHeaders = options.get("header", [])
-
- headers: dict[str, str] = {}
- if isinstance(rawHeaders, str):
- rawHeaders = [rawHeaders]
- for h in rawHeaders:
- if isinstance(h, str) and ":" in h:
- k, v = h.split(":", 1)
- headers[k.strip()] = v.strip()
-
- if ua := options.get("user-agent"):
- headers.setdefault("User-Agent", ua)
- if referer := options.get("referer"):
- headers.setdefault("Referer", referer)
-
- from app.models.task import TaskOptions
-
- outputFolder = Path(directory) if directory else Path(cfg.downloadFolder.value)
- clientProfile = "" if cfg.aria2RpcEmulateFingerprint.value else "raw"
+ raise RpcError("URI is not provided.")
+ options = params[1] if len(params) > 1 else {}
+ if not isinstance(options, dict):
+ raise RpcError("The parameter at 1 has wrong type.")
+
+ directory = toText(options, "dir")
taskOptions = TaskOptions(
- url=url,
- headers=headers,
- outputFolder=outputFolder,
- clientProfile=clientProfile,
+ url=uris[0],
+ headers=toHeaders(options),
+ outputFolder=Path(directory or cfg.downloadFolder.value),
+ clientProfile="" if cfg.aria2RpcEmulateFingerprint.value else "raw",
)
self._coroutineRunner.submit(
self._parse(taskOptions),
- done=partial(self._onTaskParsed, filename=filename),
- failed=self._onTaskParseFailed,
+ done=self._onTaskParsed, failed=self._onTaskParseFailed,
+ name=toText(options, "out"),
)
+ return token_hex(8)
- return {"jsonrpc": "2.0", "id": rpcId, "result": token_hex(8)}
-
- def _onTaskParsed(self, task: Task, filename: str = "") -> None:
- if filename:
- task.setName(filename)
-
+ def _onTaskParsed(self, task: Task, name: str) -> None:
+ if name:
+ task.setName(name)
if cfg.shouldDraftTakenDownload.value:
- self.taskDraftRequested.emit([task])
+ self._requestDraft([task])
return
-
self._addTask(task)
- def _onTaskParseFailed(self, error: str) -> None:
+ def _onTaskParseFailed(self, error, **_) -> None:
logger.warning("Aria2 RPC task parse failed: {}", error)
diff --git a/app/startup.py b/app/startup.py
index 7d161218..fe65cd75 100644
--- a/app/startup.py
+++ b/app/startup.py
@@ -53,7 +53,6 @@ def loadEngine(application):
def createServices(coroutineRunner, categoryService, speedMeter):
from PySide6.QtCore import QFileSystemWatcher
- from app.services.aria2_rpc import Aria2RpcServer
from app.services.browser_service import BrowserService
from app.services.feature_service import FeatureService
from app.services.runtime_status import RuntimeStatusService
@@ -69,10 +68,9 @@ def createServices(coroutineRunner, categoryService, speedMeter):
return bytes(QResource(":/res/chrome_extension.crx").data())
browserService = BrowserService(coroutineRunner, taskService, parse=featureService.parse, loadCrx=loadCrx)
- aria2RpcServer = Aria2RpcServer(coroutineRunner, parse=featureService.parse, addTask=taskService.add)
updateService = UpdateService(coroutineRunner)
- return featureService, taskService, browserService, aria2RpcServer, updateService, runtimeStatusService
+ return featureService, taskService, browserService, updateService, runtimeStatusService
def loadPacks(featureService, coroutineRunner, speedMeter):
@@ -111,12 +109,12 @@ def checkUpdateAtStartup(updateService):
updateService.check()
-def stopEngine(taskService, browserService, aria2RpcServer, featureService, coroutineRunner, speedMeter, updateService=None):
+def stopEngine(taskService, browserService, aria2Server, featureService, coroutineRunner, speedMeter, updateService=None):
taskService.stop()
taskService.flush()
speedMeter.stop()
browserService.stop()
- aria2RpcServer.stop()
+ aria2Server.stop()
featureService.deactivate()
taskService.flush()
if updateService is not None:
diff --git a/tests/test_aria2_rpc.py b/tests/test_aria2_rpc.py
index d9bf3ffe..5e82c554 100644
--- a/tests/test_aria2_rpc.py
+++ b/tests/test_aria2_rpc.py
@@ -2,132 +2,258 @@ from __future__ import annotations
import asyncio
import json
-from unittest.mock import Mock
+import time
+from dataclasses import dataclass
+from pathlib import Path
import pytest
import websockets
+from websockets.exceptions import InvalidStatus
+from app.config.cfg import cfg
+from app.config.constants import VERSION
from app.services.aria2_rpc import Aria2RpcServer
+from app.services.coroutine_runner import CoroutineRunner
+from app.services.loopback_server import ListenStatus, LoopbackServer
+from tests.test_loopback_server import FakeItem, findFreePort, waitFor
+pytestmark = pytest.mark.asyncio(loop_factories=["asyncio", "uvloop"])
-def mockCoroutineRunner():
- runner = Mock()
- runner.submit = lambda coro, **kwargs: asyncio.create_task(coro)
- return runner
+@dataclass
+class FakeTask:
+ options: object
+ name: str = ""
-def mockParse():
- async def parse(taskOptions):
- from app.models.task import Task
- task = Task()
- task.url = taskOptions.url
- return task
- return parse
+ def setName(self, name: str) -> None:
+ self.name = name
-def mockAddTask():
- tasks = []
- def add(task):
- tasks.append(task)
- add.tasks = tasks
- return add
+@dataclass
+class Response:
+ status: int
+ headers: dict[str, str]
+ body: bytes
+ def json(self) -> dict:
+ return json.loads(self.body)
-async def aria2Server(mockCoroutineRunner, mockParse, mockAddTask):
- import socket
- server = Aria2RpcServer(mockCoroutineRunner, mockParse, mockAddTask)
+class Aria2Client:
+ def __init__(self, port: int, added: list, drafted: list):
+ self.port = port
+ self.added = added
+ self.drafted = drafted
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- sock.bind(('127.0.0.1', 0))
- sock.listen()
- sock.setblocking(False)
- port = sock.getsockname()[1]
+ async def send(self, raw: bytes) -> Response | None:
+ reader, writer = await asyncio.open_connection("127.0.0.1", self.port)
+ writer.write(raw)
+ data = await asyncio.wait_for(reader.read(), 3)
+ writer.close()
+ if not data:
+ return None
+ head, _, body = data.partition(b"\r\n\r\n")
+ lines = head.decode().split("\r\n")
+ headers = {k.strip().lower(): v.strip() for k, v in (line.split(":", 1) for line in lines[1:])}
+ return Response(int(lines[0].split()[1]), headers, body)
+
+ async def post(self, payload, path: str = "/jsonrpc") -> Response:
+ body = payload if isinstance(payload, bytes) else json.dumps(payload).encode()
+ return await self.send(
+ f"POST {path} HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n"
+ f"Content-Length: {len(body)}\r\n\r\n".encode() + body
+ )
- task = asyncio.create_task(server._run(sock))
- await asyncio.sleep(0.1)
+ async def call(self, method: str, params: list) -> dict:
+ return (await self.post({"jsonrpc": "2.0", "id": "t", "method": method, "params": params})).json()
- yield f"127.0.0.1:{port}", server, mockAddTask
+ def connect(self, path: str = "/jsonrpc"):
+ return websockets.connect(f"ws://127.0.0.1:{self.port}{path}")
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
+async def aria2(monkeypatch, tmp_path):
+ monkeypatch.setattr(cfg.aria2RpcToken, "value", "")
+ monkeypatch.setattr(cfg.shouldDraftTakenDownload, "value", False)
+ monkeypatch.setattr(cfg.downloadFolder, "value", str(tmp_path))
+ loop = asyncio.get_running_loop()
+ runner = CoroutineRunner(loop.call_soon, loop=loop)
+ added, drafted = [], []
-class TestAria2RpcHttp:
- async def test_getVersion_returns_version_and_features(self, aria2Server):
- addr, _, _ = aria2Server
+ async def parse(options):
+ return FakeTask(options)
- request = json.dumps({
- "jsonrpc": "2.0",
- "id": "test1",
- "method": "aria2.getVersion",
- "params": []
- }).encode()
+ rpc = Aria2RpcServer(runner, parse=parse, addTask=added.append, requestDraft=drafted.extend)
+ server = LoopbackServer(runner, rpc.handle, isEnabled=FakeItem(True), port=FakeItem(findFreePort()))
+ server.start()
+ await waitFor(lambda: server.state.status == ListenStatus.LISTENING)
- host, port = addr.split(":")
- reader, writer = await asyncio.open_connection(host, int(port))
+ yield Aria2Client(server.state.port, added, drafted)
- writer.write(
- b"POST /jsonrpc HTTP/1.1\r\n"
- b"Content-Type: application/json\r\n"
- b"Content-Length: " + str(len(request)).encode() + b"\r\n"
- b"\r\n" + request
- )
- await writer.drain()
+ server.stop()
+ await asyncio.sleep(0.05)
- response = b""
- while b"\r\n\r\n" not in response:
- response += await reader.read(1024)
- headers = response[:response.index(b"\r\n\r\n")].decode()
- contentLength = next(
- int(line.split(":", 1)[1].strip())
- for line in headers.split("\r\n")
- if line.lower().startswith("content-length:")
- )
+def isGid(value) -> bool:
+ return isinstance(value, str) and len(value) == 16 and all(c in "0123456789abcdef" for c in value)
- body = response[response.index(b"\r\n\r\n") + 4:]
- while len(body) < contentLength:
- body += await reader.read(1024)
- data = json.loads(body)
+class TestTransport:
+ async def test_getVersion_over_http(self, aria2):
+ response = await aria2.post({"jsonrpc": "2.0", "id": "a", "method": "aria2.getVersion", "params": []})
- assert data["jsonrpc"] == "2.0"
- assert data["id"] == "test1"
- assert "version" in data["result"]
- assert "enabledFeatures" in data["result"]
+ assert response.status == 200
+ assert response.headers["content-type"] == "application/json-rpc"
+ assert response.headers["access-control-allow-origin"] == "*"
+ assert response.json() == {"jsonrpc": "2.0", "id": "a",
+ "result": {"version": VERSION, "enabledFeatures": ["HTTPS"]}}
- writer.close()
- await writer.wait_closed()
+ async def test_getVersion_over_websocket(self, aria2):
+ async with aria2.connect() as ws:
+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": "w", "method": "aria2.getVersion", "params": []}))
+ assert json.loads(await ws.recv())["result"]["version"] == VERSION
+ async def test_preflight_is_answered_without_token(self, aria2, monkeypatch):
+ monkeypatch.setattr(cfg.aria2RpcToken, "value", "secret")
+ response = await aria2.send(
+ b"OPTIONS /jsonrpc HTTP/1.1\r\nHost: x\r\nOrigin: https://pdpb.cn\r\n"
+ b"Access-Control-Request-Method: POST\r\nAccess-Control-Request-Headers: content-type\r\n\r\n"
+ )
-class TestAria2RpcWebSocket:
- async def test_websocket_handshake_succeeds(self, aria2Server):
- addr, _, _ = aria2Server
- async with websockets.connect(f"ws://{addr}/jsonrpc") as ws:
- assert ws.protocol.state.name == "OPEN"
+ assert response.status == 200
+ assert response.body == b""
+ assert response.headers["access-control-allow-origin"] == "*"
+ assert response.headers["access-control-allow-methods"] == "POST, GET, OPTIONS"
+ assert response.headers["access-control-allow-headers"] == "content-type"
- async def test_getVersion_over_websocket(self, aria2Server):
- addr, _, _ = aria2Server
+ async def test_other_path_is_not_found(self, aria2):
+ assert (await aria2.post(b"{}", path="/rpc")).status == 404
- async with websockets.connect(f"ws://{addr}/jsonrpc") as ws:
- await ws.send(json.dumps({
- "jsonrpc": "2.0",
- "id": "ws1",
- "method": "aria2.getVersion",
- "params": []
- }))
+ async def test_websocket_on_other_path_is_not_found(self, aria2):
+ with pytest.raises(InvalidStatus) as error:
+ async with aria2.connect("/other"):
+ pass
+ assert error.value.response.status_code == 404
+
+ async def test_client_leaving_mid_head_does_not_stall_server(self, aria2):
+ _, writer = await asyncio.open_connection("127.0.0.1", aria2.port)
+ writer.write(b"POST /jsonrpc HTTP/1.1\r\nHost: x\r\n")
+ writer.close()
+
+ result = await asyncio.wait_for(aria2.call("aria2.getVersion", []), 1)
+ assert result["result"]["version"] == VERSION
+
+ async def test_body_over_2m_is_dropped_without_response(self, aria2):
+ response = await aria2.send(
+ b"POST /jsonrpc HTTP/1.1\r\nHost: x\r\nContent-Length: 3000000\r\n\r\n{}"
+ )
+ assert response is None
- data = json.loads(await ws.recv())
- assert data["jsonrpc"] == "2.0"
- assert data["id"] == "ws1"
- assert "version" in data["result"]
+class TestRequestErrors:
+ @pytest.mark.parametrize("body, status, code", [
+ (b"{not json", 500, -32700),
+ (b"[]", 400, -32600),
+ (b'{"jsonrpc":"2.0","method":"aria2.getVersion"}', 400, -32600),
+ (b'{"jsonrpc":"2.0","id":"x","method":"aria2.getVersion","params":{}}', 500, -32602),
+ ])
+ async def test_malformed_request(self, aria2, body, status, code):
+ response = await aria2.post(body)
+
+ assert response.status == status
+ assert response.json()["error"]["code"] == code
+
+ async def test_unknown_method(self, aria2):
+ response = await aria2.post({"jsonrpc": "2.0", "id": "x", "method": "aria2.tellStatus", "params": ["g"]})
+
+ assert response.status == 400
+ assert response.json()["error"] == {"code": 1, "message": "No such method: aria2.tellStatus"}
+
+
+class TestToken:
+ async def test_missing_token_is_unauthorized_after_a_second(self, aria2, monkeypatch):
+ monkeypatch.setattr(cfg.aria2RpcToken, "value", "secret")
+ started = time.monotonic()
+ response = await aria2.post({"jsonrpc": "2.0", "id": "x", "method": "aria2.addUri", "params": [[]]})
+
+ assert time.monotonic() - started >= 1
+ assert response.status == 400
+ assert response.json()["error"] == {"code": 1, "message": "Unauthorized"}
+
+ async def test_wrong_token_is_unauthorized(self, aria2, monkeypatch):
+ monkeypatch.setattr(cfg.aria2RpcToken, "value", "secret")
+ result = await aria2.call("aria2.getVersion", ["token:guess"])
+
+ assert result["error"]["message"] == "Unauthorized"
+
+ async def test_right_token_is_accepted(self, aria2, monkeypatch):
+ monkeypatch.setattr(cfg.aria2RpcToken, "value", "secret")
+ result = await aria2.call("aria2.getVersion", ["token:secret"])
+
+ assert result["result"]["version"] == VERSION
+
+ async def test_token_param_is_stripped_when_no_token_is_set(self, aria2):
+ result = await aria2.call("aria2.addUri", ["token:", ["https://a.test/f.zip"]])
+
+ assert isGid(result["result"])
+
+
+class TestAddUri:
+ async def test_task_is_created_from_aria2_options(self, aria2, tmp_path):
+ result = await aria2.call("aria2.addUri", [
+ ["https://a.test/f.zip", "https://mirror.test/f.zip"],
+ {"dir": str(tmp_path / "sub"), "out": "renamed.zip",
+ "header": ["Cookie: a=b", "User-Agent: from-header"],
+ "user-agent": "from-option", "referer": "https://a.test/"},
+ ])
+ await waitFor(lambda: aria2.added)
+
+ assert isGid(result["result"])
+ task = aria2.added[0]
+ assert task.options.url == "https://a.test/f.zip"
+ assert task.options.outputFolder == tmp_path / "sub"
+ assert task.options.headers == {"Cookie": "a=b", "User-Agent": "from-header", "Referer": "https://a.test/"}
+ assert task.name == "renamed.zip"
+
+ async def test_header_may_be_a_single_string(self, aria2):
+ await aria2.call("aria2.addUri", [["https://a.test/f"], {"header": "Cookie: a=b"}])
+ await waitFor(lambda: aria2.added)
+
+ assert aria2.added[0].options.headers == {"Cookie": "a=b"}
+
+ async def test_wrongly_typed_options_are_ignored(self, aria2, tmp_path):
+ async with aria2.connect() as ws:
+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "aria2.addUri", "params": [
+ ["https://a.test/f"], {"dir": 123, "out": ["x"], "header": 5, "user-agent": None}]}))
+ assert isGid(json.loads(await ws.recv())["result"])
+
+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "aria2.addUri", "params": [
+ ["https://a.test/g"], {"dir": None}]}))
+ assert isGid(json.loads(await ws.recv())["result"])
+
+ await waitFor(lambda: len(aria2.added) == 2)
+ assert aria2.added[0].options.outputFolder == Path(tmp_path)
+ assert aria2.added[0].options.headers == {}
+ assert aria2.added[0].name == ""
+
+ @pytest.mark.parametrize("params, message", [
+ ([], "The parameter at 0 is required but missing."),
+ (["https://a.test/f"], "The parameter at 0 has wrong type."),
+ ([[]], "URI is not provided."),
+ ([[1, None]], "URI is not provided."),
+ ([["https://a.test/f"], "dir"], "The parameter at 1 has wrong type."),
+ ])
+ async def test_invalid_uris_or_options(self, aria2, params, message):
+ response = await aria2.post({"jsonrpc": "2.0", "id": "x", "method": "aria2.addUri", "params": params})
+
+ assert response.status == 400
+ assert response.json()["error"] == {"code": 1, "message": message}
+ assert aria2.added == []
+
+ async def test_task_goes_to_draft_when_drafting_is_on(self, aria2, monkeypatch):
+ monkeypatch.setattr(cfg.shouldDraftTakenDownload, "value", True)
+ await aria2.call("aria2.addUri", [["https://a.test/f"]])
+ await waitFor(lambda: aria2.drafted)
+
+ assert aria2.added == []
+ assert aria2.drafted[0].options.url == "https://a.test/f"