use std::sync::Arc;
use async_trait::async_trait;
use crate::engine::command::Command;
use crate::engine::protocol_adapter::{
ProtocolCommandAdapter, ProtocolCommandRequest, ProtocolServices,
};
use crate::error::Result;
use crate::util::rwlock_ext::RwLockRecover;
pub(crate) struct MetalinkCommandAdapter {
ftp_connection_pool: Arc<crate::ftp::connection_pool::FtpConnectionPool>,
#[cfg(feature = "bittorrent")]
bittorrent: crate::engine::bittorrent::command_adapter::BtCommandServices,
}
impl MetalinkCommandAdapter {
pub(crate) fn new(
ftp_connection_pool: Arc<crate::ftp::connection_pool::FtpConnectionPool>,
#[cfg(feature = "bittorrent")]
bittorrent: crate::engine::bittorrent::command_adapter::BtCommandServices,
) -> Self {
Self {
ftp_connection_pool,
#[cfg(feature = "bittorrent")]
bittorrent,
}
}
}
#[async_trait]
impl ProtocolCommandAdapter for MetalinkCommandAdapter {
fn supports(&self, request: &ProtocolCommandRequest) -> bool {
request.group.recover().has_metalink_source()
}
async fn create(
&self,
request: ProtocolCommandRequest,
services: &ProtocolServices,
) -> Result<Box<dyn Command>> {
let parsed_file = request.group.recover().take_parsed_metalink_file();
let mut command = if let Some(file) = parsed_file {
crate::engine::metalink::download_command::MetalinkDownloadCommand::new_with_group_file(
Arc::clone(&request.group),
file.as_ref(),
&request.options,
&services.outbound_network_policy,
)?
} else {
let (metalink_data, file_index) = request
.group
.recover()
.metalink_source()
.expect("the registry calls this adapter only for Metalink groups");
let base_uri = request.group.recover().metalink_base_uri();
crate::engine::metalink::download_command::MetalinkDownloadCommand::new_with_group_source(
request.group,
&metalink_data,
file_index,
&request.options,
base_uri.as_deref(),
&services.outbound_network_policy,
)?
};
if let Some(limiter) = services.global_limiter.clone() {
command.set_global_limiter(limiter);
}
command.set_protocol_runtime(
crate::engine::protocol_adapter::ProtocolAdapterRegistry::source_protocols(Arc::clone(
&self.ftp_connection_pool,
)),
services.clone(),
);
#[cfg(feature = "bittorrent")]
{
command.set_public_tracker_catalog(Arc::clone(&self.bittorrent.public_tracker_catalog));
command.set_bt_registry(Arc::clone(&self.bittorrent.bt_registry));
command.set_bt_listener(Arc::clone(&self.bittorrent.bt_listener));
command.set_lpd_manager(Arc::clone(&self.bittorrent.lpd_manager));
command.set_open_file_budget(Arc::clone(&self.bittorrent.open_file_budget));
}
Ok(Box::new(command))
}
}