341 lines
12 KiB
Rust
341 lines
12 KiB
Rust
//! An in-memory qBittorrent for the daemon's tests.
|
|
//!
|
|
//! Shared rather than per-module because every lane that grabs needs the same
|
|
//! two behaviours to be right, and both are easy to fake wrongly: `torrents/add`
|
|
//! answers `Ok.` with no hash, so the fake has to derive the same infohash the
|
|
//! client did, and adding the same source twice has to collapse to one torrent
|
|
//! or the restart and re-grab tests prove nothing.
|
|
|
|
#![allow(clippy::unwrap_used, dead_code)]
|
|
|
|
use std::collections::HashMap;
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use arr_dl::TorrentSource;
|
|
use serde_json::{json, Value};
|
|
use wiremock::matchers::any;
|
|
use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub(crate) struct FakeTorrent {
|
|
pub hash: String,
|
|
pub name: String,
|
|
/// The magnet URI, or `<inline .torrent>` for a torrent sent as bytes.
|
|
pub source: String,
|
|
/// The bytes of a torrent sent inline, so a test can prove arr forwarded
|
|
/// the file rather than the indexer link.
|
|
pub metainfo: Option<Vec<u8>>,
|
|
pub labels: Vec<String>,
|
|
pub save_path: String,
|
|
pub progress: f64,
|
|
pub state: String,
|
|
pub ratio_limit: f64,
|
|
pub idle_limit_minutes: i64,
|
|
/// `(path, size)`, relative to `save_path`.
|
|
pub files: Vec<(String, u64)>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default)]
|
|
pub(crate) struct FakeQbit {
|
|
pub torrents: Arc<Mutex<Vec<FakeTorrent>>>,
|
|
/// Every source ever added, in order, kept across removals.
|
|
pub added: Arc<Mutex<Vec<String>>>,
|
|
}
|
|
|
|
impl FakeQbit {
|
|
/// Start a mock server backed by a fresh fake.
|
|
pub(crate) async fn start() -> (MockServer, Self) {
|
|
let server = MockServer::start().await;
|
|
let fake = Self::default();
|
|
Mock::given(any())
|
|
.respond_with(fake.clone())
|
|
.mount(&server)
|
|
.await;
|
|
(server, fake)
|
|
}
|
|
|
|
pub(crate) fn torrents(&self) -> Vec<FakeTorrent> {
|
|
self.torrents.lock().unwrap().clone()
|
|
}
|
|
|
|
pub(crate) fn complete_all(&self) {
|
|
for torrent in self.torrents.lock().unwrap().iter_mut() {
|
|
torrent.progress = 1.0;
|
|
torrent.state = "uploading".into();
|
|
}
|
|
}
|
|
|
|
/// Give every torrent the same file list and download directory, for the
|
|
/// import lane.
|
|
pub(crate) fn set_contents(&self, save_path: &str, files: &[(&str, u64)]) {
|
|
for torrent in self.torrents.lock().unwrap().iter_mut() {
|
|
torrent.save_path = save_path.to_owned();
|
|
torrent.files = files
|
|
.iter()
|
|
.map(|(path, size)| ((*path).to_owned(), *size))
|
|
.collect();
|
|
}
|
|
}
|
|
|
|
fn add(&self, request: &Request) -> ResponseTemplate {
|
|
let parts = multipart(request);
|
|
let (source, name, metainfo) = if let Some(urls) = parts.get("urls") {
|
|
let uri = String::from_utf8_lossy(urls).trim().to_owned();
|
|
let name = uri.split_once("dn=").map_or_else(
|
|
|| uri.clone(),
|
|
|(_, rest)| rest.split('&').next().unwrap_or_default().to_owned(),
|
|
);
|
|
(TorrentSource::Magnet(uri), name, None)
|
|
} else {
|
|
let bytes = parts.get("torrents").cloned().unwrap_or_default();
|
|
(
|
|
TorrentSource::Metainfo(bytes.clone()),
|
|
"<inline .torrent>".to_owned(),
|
|
Some(bytes),
|
|
)
|
|
};
|
|
let Ok(hash) = arr_dl::infohash(&source) else {
|
|
// The real client refuses these before the call, so reaching here
|
|
// means the fixture is malformed.
|
|
return ResponseTemplate::new(415).set_body_string("invalid torrent");
|
|
};
|
|
let display = match &source {
|
|
TorrentSource::Magnet(uri) => uri.clone(),
|
|
TorrentSource::Metainfo(_) => "<inline .torrent>".to_owned(),
|
|
};
|
|
|
|
self.added.lock().unwrap().push(display.clone());
|
|
let mut torrents = self.torrents.lock().unwrap();
|
|
if !torrents.iter().any(|torrent| torrent.hash == hash) {
|
|
torrents.push(FakeTorrent {
|
|
hash,
|
|
name,
|
|
source: display,
|
|
metainfo,
|
|
labels: text(&parts, "tags")
|
|
.split(',')
|
|
.filter(|tag| !tag.is_empty())
|
|
.map(ToOwned::to_owned)
|
|
.collect(),
|
|
save_path: text(&parts, "savepath"),
|
|
progress: 0.0,
|
|
state: "downloading".into(),
|
|
ratio_limit: -1.0,
|
|
idle_limit_minutes: -1,
|
|
files: Vec::new(),
|
|
});
|
|
}
|
|
ResponseTemplate::new(200).set_body_string("Ok.")
|
|
}
|
|
|
|
fn info(&self, request: &Request) -> ResponseTemplate {
|
|
let wanted = query(request, "hashes");
|
|
let torrents: Vec<Value> = self
|
|
.torrents()
|
|
.into_iter()
|
|
.filter(|torrent| {
|
|
wanted
|
|
.as_ref()
|
|
.is_none_or(|hash| torrent.hash.eq_ignore_ascii_case(hash))
|
|
})
|
|
.map(|torrent| {
|
|
json!({
|
|
"hash": torrent.hash,
|
|
"name": torrent.name,
|
|
"state": torrent.state,
|
|
"progress": torrent.progress,
|
|
"dlspeed": 0,
|
|
"save_path": torrent.save_path,
|
|
"tags": torrent.labels.join(","),
|
|
"ratio": 0.0,
|
|
"ratio_limit": torrent.ratio_limit,
|
|
"seeding_time": 0,
|
|
"seeding_time_limit": -1,
|
|
"inactive_seeding_time_limit": torrent.idle_limit_minutes,
|
|
"last_activity": 0
|
|
})
|
|
})
|
|
.collect();
|
|
ResponseTemplate::new(200).set_body_json(torrents)
|
|
}
|
|
|
|
fn files(&self, request: &Request) -> ResponseTemplate {
|
|
let hash = query(request, "hash").unwrap_or_default();
|
|
let files: Vec<Value> = self
|
|
.torrents()
|
|
.into_iter()
|
|
.find(|torrent| torrent.hash.eq_ignore_ascii_case(&hash))
|
|
.map_or_default(|torrent| {
|
|
torrent
|
|
.files
|
|
.into_iter()
|
|
.map(|(path, size)| json!({"name": path, "size": size}))
|
|
.collect()
|
|
});
|
|
ResponseTemplate::new(200).set_body_json(files)
|
|
}
|
|
|
|
fn mutate(&self, path: &str, request: &Request) -> ResponseTemplate {
|
|
let form = urlencoded(request);
|
|
let hashes = form.get("hashes").cloned().unwrap_or_default();
|
|
for torrent in self.torrents.lock().unwrap().iter_mut() {
|
|
if !hashes
|
|
.split('|')
|
|
.any(|hash| hash.eq_ignore_ascii_case(&torrent.hash))
|
|
{
|
|
continue;
|
|
}
|
|
match path {
|
|
"addTags" => {
|
|
for tag in form.get("tags").cloned().unwrap_or_default().split(',') {
|
|
if !tag.is_empty() && !torrent.labels.iter().any(|held| held == tag) {
|
|
torrent.labels.push(tag.to_owned());
|
|
}
|
|
}
|
|
}
|
|
"setLocation" => {
|
|
torrent.save_path = form.get("location").cloned().unwrap_or_default();
|
|
}
|
|
"setShareLimits" => {
|
|
torrent.ratio_limit = form
|
|
.get("ratioLimit")
|
|
.and_then(|value| value.parse().ok())
|
|
.unwrap_or(-1.0);
|
|
torrent.idle_limit_minutes = form
|
|
.get("inactiveSeedingTimeLimit")
|
|
.and_then(|value| value.parse().ok())
|
|
.unwrap_or(-1);
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
ResponseTemplate::new(200).set_body_string("")
|
|
}
|
|
|
|
fn delete(&self, request: &Request) -> ResponseTemplate {
|
|
let form = urlencoded(request);
|
|
let hashes = form.get("hashes").cloned().unwrap_or_default();
|
|
self.torrents.lock().unwrap().retain(|torrent| {
|
|
!hashes
|
|
.split('|')
|
|
.any(|hash| hash.eq_ignore_ascii_case(&torrent.hash))
|
|
});
|
|
ResponseTemplate::new(200).set_body_string("")
|
|
}
|
|
}
|
|
|
|
impl Respond for FakeQbit {
|
|
fn respond(&self, request: &Request) -> ResponseTemplate {
|
|
let path = request.url.path().to_owned();
|
|
match path.rsplit('/').next().unwrap_or_default() {
|
|
"add" => self.add(request),
|
|
"info" => self.info(request),
|
|
"files" => self.files(request),
|
|
"delete" => self.delete(request),
|
|
endpoint @ ("addTags" | "setLocation" | "setShareLimits") => {
|
|
self.mutate(endpoint, request)
|
|
}
|
|
_ => ResponseTemplate::new(200).set_body_string("Ok."),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn query(request: &Request, key: &str) -> Option<String> {
|
|
request
|
|
.url
|
|
.query_pairs()
|
|
.find(|(name, _)| name == key)
|
|
.map(|(_, value)| value.into_owned())
|
|
}
|
|
|
|
fn urlencoded(request: &Request) -> HashMap<String, String> {
|
|
String::from_utf8_lossy(&request.body)
|
|
.split('&')
|
|
.filter_map(|pair| pair.split_once('='))
|
|
.map(|(key, value)| (decode(key), decode(value)))
|
|
.collect()
|
|
}
|
|
|
|
fn decode(input: &str) -> String {
|
|
let bytes = input.replace('+', " ").into_bytes();
|
|
let mut out = Vec::with_capacity(bytes.len());
|
|
let mut at = 0;
|
|
while at < bytes.len() {
|
|
if bytes[at] == b'%' && at + 2 < bytes.len() {
|
|
if let Some(byte) = std::str::from_utf8(&bytes[at + 1..at + 3])
|
|
.ok()
|
|
.and_then(|pair| u8::from_str_radix(pair, 16).ok())
|
|
{
|
|
out.push(byte);
|
|
at += 3;
|
|
continue;
|
|
}
|
|
}
|
|
out.push(bytes[at]);
|
|
at += 1;
|
|
}
|
|
String::from_utf8_lossy(&out).into_owned()
|
|
}
|
|
|
|
fn text(parts: &HashMap<String, Vec<u8>>, key: &str) -> String {
|
|
parts
|
|
.get(key)
|
|
.map_or_default(|bytes| String::from_utf8_lossy(bytes).into_owned())
|
|
}
|
|
|
|
/// The named parts of a `multipart/form-data` body.
|
|
fn multipart(request: &Request) -> HashMap<String, Vec<u8>> {
|
|
let Some(boundary) = request
|
|
.headers
|
|
.get("content-type")
|
|
.and_then(|value| value.to_str().ok())
|
|
.and_then(|value| value.split("boundary=").nth(1))
|
|
.map(|value| format!("--{}", value.trim_matches('"')))
|
|
else {
|
|
return HashMap::new();
|
|
};
|
|
|
|
let mut parts = HashMap::new();
|
|
for section in split(&request.body, boundary.as_bytes()).skip(1) {
|
|
let Some(header_end) = find(section, b"\r\n\r\n") else {
|
|
continue;
|
|
};
|
|
let headers = String::from_utf8_lossy(§ion[..header_end]);
|
|
let Some(name) = headers
|
|
.split("name=\"")
|
|
.nth(1)
|
|
.and_then(|rest| rest.split('"').next())
|
|
else {
|
|
continue;
|
|
};
|
|
let body = §ion[header_end + 4..];
|
|
let body = body.strip_suffix(b"\r\n").unwrap_or(body);
|
|
parts.insert(name.to_owned(), body.to_vec());
|
|
}
|
|
parts
|
|
}
|
|
|
|
fn split<'a>(haystack: &'a [u8], needle: &'a [u8]) -> impl Iterator<Item = &'a [u8]> {
|
|
let mut rest = haystack;
|
|
std::iter::from_fn(move || {
|
|
if rest.is_empty() {
|
|
return None;
|
|
}
|
|
if let Some(at) = find(rest, needle) {
|
|
let (section, tail) = rest.split_at(at);
|
|
rest = &tail[needle.len()..];
|
|
Some(section)
|
|
} else {
|
|
let section = rest;
|
|
rest = &[];
|
|
Some(section)
|
|
}
|
|
})
|
|
}
|
|
|
|
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
|
|
haystack
|
|
.windows(needle.len())
|
|
.position(|window| window == needle)
|
|
}
|