use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{RwLock, mpsc};
use tokio_util::sync::CancellationToken;
use super::json_rpc::{JsonRpcRequest, JsonRpcResponse};
use super::server::{AuthConfig, CorsConfig, RpcAuthMiddleware};
use super::types::{GlobalOptions, PeerInfo, StatusInfo, TaskOptions};
use super::websocket::EventPublisher;
use aria2_core::TorrentFileEntry;
use aria2_core::config::OptionRegistry;
use aria2_core::engine::command::Command;
use aria2_core::request::request_group_man::RequestGroupMan;
pub struct RpcEngine {
pub(crate) tasks: Arc<RwLock<HashMap<String, TaskState>>>,
pub(crate) global_opts: GlobalOptions,
pub(crate) task_opts: TaskOptions,
pub(crate) stopped_tasks: Arc<RwLock<Vec<StatusInfo>>>,
pub(crate) event_publisher: Arc<EventPublisher>,
pub(crate) auth_middleware: RpcAuthMiddleware,
pub(crate) group_man: Option<Arc<RwLock<RequestGroupMan>>>,
pub(crate) cmd_tx: Option<mpsc::UnboundedSender<Box<dyn Command>>>,
}
pub(crate) struct TaskState {
pub(crate) status: StatusInfo,
#[allow(dead_code)] pub(crate) options: HashMap<String, serde_json::Value>,
#[allow(dead_code)] pub(crate) uris: Vec<String>,
pub(crate) torrent_files: Option<Vec<TorrentFileEntry>>,
pub(crate) total_length: u64,
pub(crate) completed_length: u64,
pub(crate) upload_length: u64,
pub(crate) download_speed: u64,
pub(crate) upload_speed: u64,
pub(crate) connections: u16,
pub(crate) peers: Vec<PeerInfo>,
pub(crate) cancel_token: Option<CancellationToken>,
}
impl TaskState {
pub(crate) fn new(
status: StatusInfo,
options: HashMap<String, serde_json::Value>,
uris: Vec<String>,
) -> Self {
Self {
status,
options,
uris,
torrent_files: None,
total_length: 0,
completed_length: 0,
upload_length: 0,
download_speed: 0,
upload_speed: 0,
connections: 0,
peers: vec![],
cancel_token: Some(CancellationToken::new()),
}
}
pub(crate) fn update_status_info(&mut self) {
let mut status = StatusInfo::new(&self.status.gid)
.with_status(self.status.status.clone())
.with_total_length(self.total_length)
.with_completed_length(self.completed_length)
.with_upload_length(self.upload_length)
.with_download_speed(self.download_speed)
.with_upload_speed(self.upload_speed)
.with_connections(self.connections)
.with_dir(self.status.dir.clone().unwrap_or_default())
.with_files(self.status.files.clone().unwrap_or_default());
if let Some(ref tf) = self.torrent_files {
status = status.with_torrent_files(tf.clone());
}
self.status = status;
}
pub fn update_progress(
&mut self,
total: u64,
completed: u64,
uploaded: u64,
dl_speed: u64,
ul_speed: u64,
connections: u16,
) {
self.total_length = total;
self.completed_length = completed;
self.upload_length = uploaded;
self.download_speed = dl_speed;
self.upload_speed = ul_speed;
self.connections = connections;
}
}
impl RpcEngine {
pub fn new() -> Self {
let registry = OptionRegistry::new();
let mut defaults = HashMap::new();
for (name, def) in registry.all() {
if def.deprecated || def.hidden {
continue;
}
let json_val: serde_json::Value = serde_json::Value::from(def.default_value());
if !json_val.is_null() {
defaults.insert(name.clone(), json_val);
}
}
Self {
tasks: Arc::new(RwLock::new(HashMap::new())),
global_opts: Arc::new(RwLock::new(defaults)),
task_opts: Arc::new(RwLock::new(HashMap::new())),
stopped_tasks: Arc::new(RwLock::new(Vec::new())),
event_publisher: Arc::new(EventPublisher::default()),
auth_middleware: RpcAuthMiddleware::default(),
group_man: None,
cmd_tx: None,
}
}
pub fn with_auth(mut self, auth: AuthConfig) -> Self {
if let Some(token) = &auth.token {
self.auth_middleware = RpcAuthMiddleware::new(token);
}
self
}
pub fn with_auth_middleware(mut self, middleware: RpcAuthMiddleware) -> Self {
self.auth_middleware = middleware;
self
}
pub fn with_cors(self, cors: CorsConfig) -> Self {
let _ = cors;
self
}
pub fn with_group_man(mut self, man: Arc<RwLock<RequestGroupMan>>) -> Self {
self.group_man = Some(man);
self
}
pub fn with_cmd_tx(mut self, tx: mpsc::UnboundedSender<Box<dyn Command>>) -> Self {
self.cmd_tx = Some(tx);
self
}
pub fn with_global_opts(self, user_opts: HashMap<String, serde_json::Value>) -> Self {
{
let mut defaults = self
.global_opts
.try_write()
.expect("no contention on fresh engine");
for (k, v) in user_opts {
if !v.is_null() {
defaults.insert(k, v);
}
}
}
self
}
pub fn publisher(&self) -> &EventPublisher {
&self.event_publisher
}
pub async fn task_count(&self) -> usize {
self.tasks.read().await.len()
}
#[allow(clippy::too_many_arguments)]
pub async fn update_task_progress(
&self,
gid: &str,
total: u64,
completed: u64,
uploaded: u64,
dl_speed: u64,
ul_speed: u64,
connections: u16,
) -> bool {
let mut tasks = self.tasks.write().await;
if let Some(state) = tasks.get_mut(gid) {
state.update_progress(total, completed, uploaded, dl_speed, ul_speed, connections);
true
} else {
false
}
}
pub async fn set_task_torrent_files(&self, gid: &str, files: Vec<TorrentFileEntry>) -> bool {
let mut tasks = self.tasks.write().await;
if let Some(state) = tasks.get_mut(gid) {
state.torrent_files = Some(files);
true
} else {
false
}
}
pub async fn set_task_peers(&self, gid: &str, peers: Vec<PeerInfo>) -> bool {
let mut tasks = self.tasks.write().await;
if let Some(state) = tasks.get_mut(gid) {
state.peers = peers;
true
} else {
false
}
}
pub async fn handle_request(&self, req: &JsonRpcRequest) -> JsonRpcResponse {
let id = req.id.clone().unwrap_or(serde_json::Value::Null);
let token = req.params.get("token").and_then(|v| v.as_str());
if let Err(auth_err) = self.auth_middleware.validate(token) {
return auth_err.into_response(req.id.clone());
}
match req.method.as_str() {
"aria2.addUri" => self
.handle_add_uri(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.addTorrent" => self
.handle_add_torrent(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.addMetalink" => self
.handle_add_metalink(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.remove" => self
.handle_remove(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.pause" => self
.handle_pause(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.forcePause" => self
.handle_force_pause(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.unpause" | "aria2.forceUnpause" => self
.handle_unpause(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.tellStatus" => self
.handle_tell_status(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.tellActive" => self
.handle_tell_active(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.tellWaiting" => self
.handle_tell_waiting(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.tellStopped" => self
.handle_tell_stopped(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.getGlobalStat" => self.handle_global_stat().await,
"aria2.getUris" => self
.handle_get_uris(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.getFiles" => self
.handle_get_files(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.getServers" => self
.handle_get_servers(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.purgeDownloadResult" => self
.handle_purge_download_result(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.removeDownloadResult" => self
.handle_remove_download_result(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.getGlobalOption" => self.handle_get_global_option().await,
"aria2.changeGlobalOption" => self
.handle_change_global_option(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.getOption" => self
.handle_get_option(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.changeOption" => self
.handle_change_option(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.getPeers" => self
.handle_get_peers(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.pauseAll" => self.handle_pause_all().await,
"aria2.forcePauseAll" => self.handle_force_pause_all().await,
"aria2.unpauseAll" => self.handle_unpause_all().await,
"aria2.changeUri" => self
.handle_change_uri(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.saveSession" => self
.handle_save_session(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.changePosition" => self
.handle_change_position(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.forceRemove" => self
.handle_force_remove(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.shutdown" => self
.handle_shutdown(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.forceShutdown" => self
.handle_force_shutdown(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"aria2.getVersion" => self.handle_version(req),
"aria2.getSessionInfo" => self.handle_session_info(req),
"system.multicall" => self
.handle_multicall(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"system.listMethods" => self
.handle_list_methods(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
"system.listNotifications" => self
.handle_list_notifications(req)
.await
.unwrap_or_else(|e| e.into_response(req.id.clone())),
_ => JsonRpcResponse::error(id, -32601, format!("Method not found: {}", req.method)),
}
}
}
impl Default for RpcEngine {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_engine_creation() {
let engine = RpcEngine::new();
assert_eq!(engine.task_count().await, 0);
}
#[tokio::test]
async fn test_handle_unknown_method() {
let engine = RpcEngine::new();
let req = JsonRpcRequest::new("aria2.nonExistent", serde_json::json!([])).with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_error());
assert_eq!(resp.error.unwrap().code, -32601);
}
#[tokio::test]
async fn test_handle_version() {
let engine = RpcEngine::new();
let req = JsonRpcRequest::new("aria2.getVersion", serde_json::json!([])).with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_success());
}
#[tokio::test]
async fn test_handle_session_info() {
let engine = RpcEngine::new();
let req = JsonRpcRequest::new("aria2.getSessionInfo", serde_json::json!([])).with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_success());
}
#[tokio::test]
async fn test_handle_add_uri() {
let engine = RpcEngine::new();
let req = JsonRpcRequest::new(
"aria2.addUri",
serde_json::json!(["http://example.com/file.iso"]),
)
.with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_success());
let gid: String = serde_json::from_value(resp.result.unwrap()).unwrap();
assert_eq!(gid.len(), 16);
}
#[tokio::test]
async fn test_handle_remove_nonexistent() {
let engine = RpcEngine::new();
let req =
JsonRpcRequest::new("aria2.remove", serde_json::json!(["nonexistent-gid"])).with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_error());
}
#[tokio::test]
async fn test_handle_pause_and_unpause() {
let engine = RpcEngine::new();
let add_req =
JsonRpcRequest::new("aria2.addUri", serde_json::json!(["http://x.com/f"])).with_id(1);
let add_resp = engine.handle_request(&add_req).await;
let gid: String = serde_json::from_value(add_resp.result.unwrap()).unwrap();
let pause_req = JsonRpcRequest::new("aria2.pause", serde_json::json!([gid])).with_id(2);
let pause_resp = engine.handle_request(&pause_req).await;
assert!(pause_resp.is_success());
let unpause_req = JsonRpcRequest::new("aria2.unpause", serde_json::json!([gid])).with_id(3);
let unpause_resp = engine.handle_request(&unpause_req).await;
assert!(unpause_resp.is_success());
}
#[tokio::test]
async fn test_handle_tell_status() {
let engine = RpcEngine::new();
let add_req =
JsonRpcRequest::new("aria2.addUri", serde_json::json!(["http://x.com/f"])).with_id(1);
let add_resp = engine.handle_request(&add_req).await;
let gid: String = serde_json::from_value(add_resp.result.unwrap()).unwrap();
let tell_req = JsonRpcRequest::new("aria2.tellStatus", serde_json::json!([gid])).with_id(2);
let tell_resp = engine.handle_request(&tell_req).await;
assert!(tell_resp.is_success());
}
#[tokio::test]
async fn test_handle_tell_active() {
let engine = RpcEngine::new();
let req = JsonRpcRequest::new("aria2.tellActive", serde_json::json!([])).with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_success());
}
#[tokio::test]
async fn test_handle_global_stat() {
let engine = RpcEngine::new();
let req = JsonRpcRequest::new("aria2.getGlobalStat", serde_json::json!([])).with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_success());
}
#[tokio::test]
async fn test_handle_purge_download_result() {
let engine = RpcEngine::new();
let req =
JsonRpcRequest::new("aria2.purgeDownloadResult", serde_json::json!([])).with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_success());
}
#[tokio::test]
async fn test_handle_get_set_global_option() {
let engine = RpcEngine::new();
let get_req =
JsonRpcRequest::new("aria2.getGlobalOption", serde_json::json!([])).with_id(1);
let get_resp = engine.handle_request(&get_req).await;
assert!(get_resp.is_success());
let set_req = JsonRpcRequest::new(
"aria2.changeGlobalOption",
serde_json::json!([{"max-concurrent-downloads": 5}]),
)
.with_id(2);
let set_resp = engine.handle_request(&set_req).await;
assert!(set_resp.is_success());
}
#[tokio::test]
async fn test_engine_auth_default_accepts_all() {
let engine = RpcEngine::new();
let req = JsonRpcRequest::new("aria2.getVersion", serde_json::json!([])).with_id(1);
let resp = engine.handle_request(&req).await;
assert!(
resp.is_success(),
"Default engine should accept requests without token"
);
}
#[tokio::test]
async fn test_engine_auth_valid_token_passes() {
let engine = RpcEngine::new().with_auth_middleware(RpcAuthMiddleware::new("my-secret"));
let req = JsonRpcRequest::new(
"aria2.getVersion",
serde_json::json!({"token": "my-secret"}),
)
.with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_success(), "Valid token should be accepted");
}
#[tokio::test]
async fn test_engine_auth_wrong_token_rejected() {
let engine = RpcEngine::new().with_auth_middleware(RpcAuthMiddleware::new("my-secret"));
let req = JsonRpcRequest::new(
"aria2.getVersion",
serde_json::json!({"token": "wrong-token"}),
)
.with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_error(), "Wrong token should be rejected");
assert_eq!(
resp.error.unwrap().code,
-32001,
"Should return Unauthorized error code"
);
}
#[tokio::test]
async fn test_engine_auth_missing_token_rejected() {
let engine = RpcEngine::new().with_auth_middleware(RpcAuthMiddleware::new("my-secret"));
let req = JsonRpcRequest::new("aria2.getVersion", serde_json::json!([])).with_id(1);
let resp = engine.handle_request(&req).await;
assert!(
resp.is_error(),
"Missing token should be rejected when auth is enabled"
);
assert_eq!(resp.error.unwrap().code, -32001);
}
#[tokio::test]
async fn test_engine_auth_via_config_token() {
let engine = RpcEngine::new().with_auth(AuthConfig::default().with_token("config-secret"));
let req = JsonRpcRequest::new(
"aria2.getVersion",
serde_json::json!({"token": "config-secret"}),
)
.with_id(1);
let resp = engine.handle_request(&req).await;
assert!(resp.is_success(), "Token from AuthConfig should work");
}
}