S008: continue from a new link, matcher and adopting partial files
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
49f6e5d0e3
commit
4f1435e72f
19 changed files with 1833 additions and 36 deletions
|
|
@ -67,6 +67,19 @@
|
|||
"log.file_unknown": "File {name}, of unknown size",
|
||||
"log.failed": "Failed: {why}",
|
||||
"log.moved": "Moved to {folder}",
|
||||
"log.continued": "Continues from {url}",
|
||||
"log.adopted": "Took over the unfinished file {path}",
|
||||
"manager.different": "The new link leads to another file, so this download can't continue from it.",
|
||||
"manager.partial": "Nothing in that file can be used: {why}",
|
||||
"relink.version": "Same file. The server's version and the bytes compared are the same.",
|
||||
"relink.samples": "Probably the same file. The bytes compared are the same, but the server doesn't tell versions apart.",
|
||||
"relink.size": "Different file. The new one has {new} bytes, this one has {old}.",
|
||||
"relink.bytes": "Different file. Some of its bytes are not the ones already here.",
|
||||
"relink.other_version": "Different file. The server has a newer version of it.",
|
||||
"relink.page": "Different file. The link leads to a web page.",
|
||||
"relink.nothing": "Nothing is here yet, so the download starts with the new link.",
|
||||
"relink.too_little": "Too little is here to tell whether it is the same file.",
|
||||
"relink.no_ranges": "The server of the new link can't continue downloads, so it must start over. The unfinished file stays until the new one is complete.",
|
||||
"log.renamed": "Renamed to {name}",
|
||||
|
||||
"error.dns": "Server not found",
|
||||
|
|
@ -89,6 +102,8 @@
|
|||
"error.login.why": "{server} wants a user name and password.",
|
||||
"error.forbidden": "Access denied",
|
||||
"error.forbidden.why": "{server} refused to give out the file (status {code}). The link may need the page it came from.",
|
||||
"error.link": "Waiting for a new link",
|
||||
"error.link.why": "Start the download again on the page it came from. Medlar continues this one with the new link.",
|
||||
"error.expired": "Link expired",
|
||||
"error.expired.why": "{server} gave out the file before but refuses now (status {code}). A new link for the same file continues the download.",
|
||||
"error.not_found": "File not found",
|
||||
|
|
|
|||
339
crates/core/src/adopt.rs
Normal file
339
crates/core/src/adopt.rs
Normal file
|
|
@ -0,0 +1,339 @@
|
|||
//! Taking over a file that another program left unfinished.
|
||||
//!
|
||||
//! `look` reads what is there, `check` compares it with a link, `Command::Adopt` copies it. The file itself is never touched.
|
||||
//! Browsers fill a file from the start; aria2 keeps a list of its pieces next to it. Of anything else only the start counts,
|
||||
//! as far as it stands the comparison with the server.
|
||||
|
||||
use crate::http::{Client, Error, Link, Result, Source, Stop, same_bytes};
|
||||
use crate::model::{Part, Task};
|
||||
use crate::relink::{Checked, NewLink, Reason, probed, read, runs, samples, total};
|
||||
use crate::{disk, http};
|
||||
use std::fs::File;
|
||||
use std::io::{self, ErrorKind, Read};
|
||||
use std::ops::Range;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Looked at in one piece for being empty.
|
||||
const BLOCK: u64 = 4096;
|
||||
/// Empty stretches the server is asked about.
|
||||
const DOUBTS: usize = 64;
|
||||
/// Endings of unfinished files, and where the name comes before them.
|
||||
const ENDINGS: &[&str] = &[".part", ".crdownload", ".opdownload", ".partial", ".download", disk::ENDING];
|
||||
const ARIA2: &str = ".aria2";
|
||||
/// Blocks inside aria2's unfinished pieces.
|
||||
const ARIA2_BLOCK: u64 = 16 * 1024;
|
||||
/// More than any control file of a sensible download.
|
||||
const ARIA2_MAX: u64 = 64 << 20;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Partial {
|
||||
pub path: PathBuf,
|
||||
/// As far as the file's own name tells.
|
||||
pub name: Option<String>,
|
||||
/// What seems to be finished.
|
||||
pub runs: Vec<Range<u64>>,
|
||||
pub total: Option<u64>,
|
||||
/// `runs` come from the other program's own list.
|
||||
pub listed: bool,
|
||||
}
|
||||
|
||||
impl Partial {
|
||||
pub fn bytes(&self) -> u64 {
|
||||
total(&self.runs)
|
||||
}
|
||||
}
|
||||
|
||||
/// An unfinished file and the link it can go on from. `partial.runs` holds only what stood the comparison.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Found {
|
||||
pub partial: Partial,
|
||||
pub checked: Checked,
|
||||
}
|
||||
|
||||
impl Found {
|
||||
pub(crate) fn parts(&self) -> Vec<Part> {
|
||||
parts(&self.partial.runs, self.checked.size.unwrap_or(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks. Takes the file or its list.
|
||||
pub fn look(path: &Path) -> io::Result<Partial> {
|
||||
let text = path.to_string_lossy();
|
||||
if let Some(data) = text.strip_suffix(ARIA2)
|
||||
&& path.with_file_name(Path::new(data).file_name().unwrap_or_default()).is_file()
|
||||
{
|
||||
return look(Path::new(data));
|
||||
}
|
||||
let meta = path.symlink_metadata()?;
|
||||
if !meta.is_file() {
|
||||
return Err(ErrorKind::InvalidInput.into());
|
||||
}
|
||||
let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||
// Chrome's, before it knows the name.
|
||||
let stem = ENDINGS.iter().find_map(|e| name.strip_suffix(e)).unwrap_or(&name);
|
||||
let known = Some(stem).filter(|s| !s.starts_with("Unconfirmed ")).and_then(http::safe_name);
|
||||
let start = std::iter::once(0..meta.len()).collect();
|
||||
let mut partial = Partial { path: path.into(), name: known, runs: start, total: None, listed: false };
|
||||
let mut list = path.as_os_str().to_os_string();
|
||||
list.push(ARIA2);
|
||||
if let Some((runs, total)) = aria2(Path::new(&list)) {
|
||||
let len = meta.len();
|
||||
partial.runs = runs.into_iter().map(|r| r.start.min(len)..r.end.min(len)).collect();
|
||||
(partial.total, partial.listed) = (Some(total), true);
|
||||
}
|
||||
partial.runs.retain(|r| !r.is_empty());
|
||||
Ok(partial)
|
||||
}
|
||||
|
||||
/// The finished ranges and the size in aria2's control file, as its manual describes it ("Control file (*.aria2) format").
|
||||
/// None for anything else, such as a torrent's.
|
||||
fn aria2(path: &Path) -> Option<(Vec<Range<u64>>, u64)> {
|
||||
let mut file = File::open(path).ok()?;
|
||||
if file.metadata().ok()?.len() > ARIA2_MAX {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = vec![];
|
||||
file.read_to_end(&mut bytes).ok()?;
|
||||
let mut rest = &bytes[..];
|
||||
let mut take = |n: usize| -> Option<&[u8]> {
|
||||
let (now, later) = rest.split_at_checked(n)?;
|
||||
rest = later;
|
||||
Some(now)
|
||||
};
|
||||
let int = |b: &[u8]| b.iter().fold(0u64, |n, b| n << 8 | u64::from(*b));
|
||||
let (version, _extension, hash) = (int(take(2)?), take(4)?, int(take(4)?));
|
||||
if version != 1 || hash != 0 {
|
||||
return None;
|
||||
}
|
||||
let (piece, total, _upload, field) = (int(take(4)?), int(take(8)?), take(8)?, int(take(4)?));
|
||||
if piece == 0 || total == 0 || field != total.div_ceil(piece).div_ceil(8) {
|
||||
return None;
|
||||
}
|
||||
// The first bit is the highest one.
|
||||
let set = |bits: &[u8], i: u64| bits.get((i / 8) as usize).is_some_and(|b| b & (0x80 >> (i % 8)) != 0);
|
||||
let bits = take(field as usize)?;
|
||||
let mut done: Vec<Range<u64>> =
|
||||
(0..total.div_ceil(piece)).filter(|i| set(bits, *i)).map(|i| i * piece..((i + 1) * piece).min(total)).collect();
|
||||
for _ in 0..int(take(4)?) {
|
||||
let (index, len, field) = (int(take(4)?), int(take(4)?), int(take(4)?));
|
||||
let start = index.checked_mul(piece).filter(|s| s + len <= total)?;
|
||||
let bits = take(field as usize)?;
|
||||
let blocks = (0..len.div_ceil(ARIA2_BLOCK)).filter(|i| set(bits, *i));
|
||||
done.extend(blocks.map(|i| start + i * ARIA2_BLOCK..start + ((i + 1) * ARIA2_BLOCK).min(len)));
|
||||
}
|
||||
let done: Vec<Part> = done.iter().map(|r| Part { start: r.start, end: Some(r.end), done: r.end - r.start }).collect();
|
||||
Some((runs(&done), total))
|
||||
}
|
||||
|
||||
/// Compares the file with what the link leads to. Reads only.
|
||||
pub async fn check(client: &Client, partial: Partial, link: NewLink, source: Source, stop: &mut Stop) -> Result<Found> {
|
||||
let task = Task { size: partial.total, name: partial.name.clone().unwrap_or_default(), url: link.url.clone(), ..Task::default() };
|
||||
let (checked, opened) = probed(client, &task, link, source, partial.bytes(), stop).await?;
|
||||
let mut found = Found { partial, checked };
|
||||
let Some((server, _body)) = opened else { return Ok(found) };
|
||||
let Some(size) = server.version.size.filter(|_| server.ranges) else {
|
||||
found.checked.reason = Reason::NoRanges;
|
||||
return Ok(found);
|
||||
};
|
||||
let Some(last) = found.partial.runs.last().map(|r| r.end) else {
|
||||
found.checked.reason = Reason::Nothing;
|
||||
return Ok(found);
|
||||
};
|
||||
if last > size {
|
||||
found.checked.reason = Reason::Size { old: last, new: size };
|
||||
return Ok(found);
|
||||
}
|
||||
let file = crate::relink::open(&found.partial.path).await?;
|
||||
let mut eye = Eye { server: &server, file: &file, compared: 0, stop };
|
||||
let result = if found.partial.listed { eye.listed(&found.partial.runs).await } else { eye.start(last).await };
|
||||
found.checked.compared = eye.compared;
|
||||
let ok = match result {
|
||||
Ok(Some(runs)) => {
|
||||
found.partial.runs = runs;
|
||||
true
|
||||
}
|
||||
Ok(None) => false,
|
||||
Err(Error::Changed) => {
|
||||
found.checked.reason = Reason::OtherVersion;
|
||||
return Ok(found);
|
||||
}
|
||||
Err(Error::RangeIgnored) => {
|
||||
(found.checked.reason, found.checked.ranges) = (Reason::NoRanges, false);
|
||||
return Ok(found);
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
found.checked.here = found.partial.bytes();
|
||||
found.checked.reason = match ok {
|
||||
false => Reason::Bytes,
|
||||
true if found.checked.compared < BLOCK => Reason::TooLittle,
|
||||
true => Reason::Samples,
|
||||
};
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
struct Eye<'a> {
|
||||
server: &'a Link,
|
||||
file: &'a Arc<File>,
|
||||
compared: u64,
|
||||
stop: &'a mut Stop,
|
||||
}
|
||||
|
||||
impl Eye<'_> {
|
||||
async fn same(&mut self, range: Range<u64>) -> Result<bool> {
|
||||
let known = read(self.file, range.clone()).await?;
|
||||
self.compared += known.len() as u64;
|
||||
same_bytes(self.server, &known, range.start, self.stop).await
|
||||
}
|
||||
|
||||
/// All or nothing.
|
||||
async fn listed(&mut self, runs: &[Range<u64>]) -> Result<Option<Vec<Range<u64>>>> {
|
||||
for sample in samples(runs) {
|
||||
if !self.same(sample).await? {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(Some(runs.to_vec()))
|
||||
}
|
||||
|
||||
/// How far the start of the file is the server's. The space may have been taken before it was filled.
|
||||
async fn start(&mut self, len: u64) -> Result<Option<Vec<Range<u64>>>> {
|
||||
let first = 0..len.min(BLOCK);
|
||||
if !self.same(first.clone()).await? {
|
||||
return Ok(None);
|
||||
}
|
||||
let file = self.file.clone();
|
||||
let empty = disk::blocking(move || empty(&file, len)).await.map_err(disk::Error::Io)?;
|
||||
let mut end = len;
|
||||
for (i, hole) in empty.into_iter().enumerate() {
|
||||
let ends = [hole.start..hole.start + BLOCK.min(hole.end - hole.start), hole.end.saturating_sub(BLOCK).max(hole.start)..hole.end];
|
||||
if i >= DOUBTS || !self.same(ends[0].clone()).await? || !self.same(ends[1].clone()).await? {
|
||||
end = hole.start;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Cut where the first of them differs, back to one that doesn't.
|
||||
let mut good = first.end.min(end);
|
||||
let mut looks = samples(std::slice::from_ref(&(0..end)));
|
||||
looks.sort_by_key(|s| s.start);
|
||||
for look in looks.into_iter().filter(|l| !l.is_empty()) {
|
||||
if !self.same(look.clone()).await? {
|
||||
end = good;
|
||||
break;
|
||||
}
|
||||
good = look.end;
|
||||
}
|
||||
Ok((end > 0).then(|| std::iter::once(0..end).collect()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Stretches of nothing but zeros, as whole blocks.
|
||||
fn empty(file: &File, len: u64) -> io::Result<Vec<Range<u64>>> {
|
||||
use std::os::unix::fs::FileExt;
|
||||
let mut buf = vec![0; 1 << 20];
|
||||
let (mut at, mut out) = (0, Vec::<Range<u64>>::new());
|
||||
while at < len {
|
||||
let n = (len - at).min(buf.len() as u64) as usize;
|
||||
file.read_exact_at(&mut buf[..n], at)?;
|
||||
for block in buf[..n].chunks(BLOCK as usize) {
|
||||
let next = at + block.len() as u64;
|
||||
if block.iter().all(|b| *b == 0) {
|
||||
match out.last_mut() {
|
||||
Some(last) if last.end == at => last.end = next,
|
||||
_ => out.push(at..next),
|
||||
}
|
||||
}
|
||||
at = next;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The whole file as parts: each finished range with the gap after it.
|
||||
fn parts(runs: &[Range<u64>], size: u64) -> Vec<Part> {
|
||||
let mut out = vec![];
|
||||
if let Some(first) = runs.first().filter(|r| r.start > 0) {
|
||||
out.push(Part { start: 0, end: Some(first.start), done: 0 });
|
||||
}
|
||||
for (i, r) in runs.iter().enumerate() {
|
||||
let end = runs.get(i + 1).map_or(size, |next| next.start);
|
||||
out.push(Part { start: r.start, end: Some(end), done: r.end - r.start });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 10 pieces of 64 KiB, the last one short; pieces 0, 1 and 9 done, and two blocks of piece 4.
|
||||
pub fn control(total: u64) -> Vec<u8> {
|
||||
let mut b = vec![0, 1, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
b.extend(65536u32.to_be_bytes());
|
||||
b.extend(total.to_be_bytes());
|
||||
b.extend(0u64.to_be_bytes());
|
||||
b.extend(2u32.to_be_bytes());
|
||||
b.extend([0b1100_0000, 0b0100_0000]);
|
||||
b.extend(1u32.to_be_bytes());
|
||||
b.extend(4u32.to_be_bytes());
|
||||
b.extend(65536u32.to_be_bytes());
|
||||
b.extend(1u32.to_be_bytes());
|
||||
b.push(0b1010_0000);
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_list_of_aria2() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (file, list) = (dir.path().join("a.zip"), dir.path().join("a.zip.aria2"));
|
||||
let total = 9 * 65536 + 100;
|
||||
std::fs::write(&file, vec![1; total as usize]).unwrap();
|
||||
std::fs::write(&list, control(total)).unwrap();
|
||||
let found = look(&list).unwrap();
|
||||
assert_eq!(found, look(&file).unwrap());
|
||||
let k = 16384;
|
||||
assert_eq!(found.runs, [0..8 * k, 16 * k..17 * k, 18 * k..19 * k, 36 * k..36 * k + 100]);
|
||||
assert_eq!((found.total, found.listed, found.name.as_deref()), (Some(total), true, Some("a.zip")));
|
||||
let parts = parts(&found.runs, total);
|
||||
assert_eq!(parts.first(), Some(&Part { start: 0, end: Some(16 * k), done: 8 * k }));
|
||||
assert!(parts.windows(2).all(|w| w[0].end == Some(w[1].start)) && parts.last().unwrap().end == Some(total));
|
||||
// Broken ones count for nothing.
|
||||
for cut in 0..control(total).len() {
|
||||
std::fs::write(&list, &control(total)[..cut]).unwrap();
|
||||
assert!(!look(&file).unwrap().listed, "{cut}");
|
||||
}
|
||||
for i in 0..control(total).len() {
|
||||
let mut bad = control(total);
|
||||
bad[i] ^= 0xff;
|
||||
std::fs::write(&list, bad).unwrap();
|
||||
let found = look(&file).unwrap();
|
||||
assert!(found.runs.iter().all(|r| r.end <= total));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_of_unfinished_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (file, name) in [
|
||||
("a.zip.part", Some("a.zip")),
|
||||
("b.iso.crdownload", Some("b.iso")),
|
||||
("Unconfirmed 1234.crdownload", None),
|
||||
("c.tar.gz", Some("c.tar.gz")),
|
||||
("d.bin.medlar", Some("d.bin")),
|
||||
] {
|
||||
let path = dir.path().join(file);
|
||||
std::fs::write(&path, "xy").unwrap();
|
||||
let found = look(&path).unwrap();
|
||||
assert_eq!((found.name.as_deref(), &found.runs[..]), (name, std::slice::from_ref(&(0..2))), "{file}");
|
||||
}
|
||||
assert!(look(dir.path()).is_err() && look(&dir.path().join("none")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_begin_with_the_gap() {
|
||||
let p = |start, end, done| Part { start, end: Some(end), done };
|
||||
assert_eq!(parts(&[5..7, 9..10], 12), [p(0, 5, 0), p(5, 9, 2), p(9, 12, 1)]);
|
||||
assert_eq!(parts(std::slice::from_ref(&(0..4)), 4), [p(0, 4, 4)]);
|
||||
}
|
||||
}
|
||||
|
|
@ -95,7 +95,7 @@ impl ErrorKind {
|
|||
ReadOnly | FolderGone | DriveGone | Denied => (Blocked, Retry::Disk, Fix::ChangeFolder),
|
||||
FileGone => (Blocked, Retry::Disk, Fix::Restart),
|
||||
Login => (Blocked, Retry::Never, Fix::SignIn),
|
||||
Forbidden | Expired | WrongContent => (Blocked, Retry::Never, Fix::NewLink),
|
||||
Forbidden | Expired | WrongContent | Link => (Blocked, Retry::Never, Fix::NewLink),
|
||||
NotFound | Rejected | BadLink => (Blocked, Retry::Never, Fix::EditLink),
|
||||
Changed | NoResume => (Blocked, Retry::Never, Fix::Choose),
|
||||
Killed => (Passing, Retry::Never, Fix::Resume),
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt
|
|||
}
|
||||
|
||||
/// The server sent a web page, and the task is for something else.
|
||||
fn is_page(task: &Task, source: &Source, probe: &Probe) -> bool {
|
||||
pub(crate) fn is_page(task: &Task, source: &Source, probe: &Probe) -> bool {
|
||||
let mime = probe.mime.as_deref();
|
||||
let names = [Some(task.name.clone()).filter(|n| !n.is_empty()), name::from_url(&source.url)];
|
||||
let was_page = task.mime.as_deref().is_some_and(|m| page(Some(m)));
|
||||
|
|
|
|||
|
|
@ -163,15 +163,31 @@ async fn whole(link: &Link, part: &LivePart, body: Option<Response>, stop: &mut
|
|||
/// Compares `len` finished bytes at `at` with the server's.
|
||||
pub async fn compare(link: &Link, file: &PartialFile, at: u64, len: u64, stop: &mut Stop) -> Result<()> {
|
||||
let known = file.read_at(len as usize, at).await?;
|
||||
let mut response = send_range(link, at, Some(at + len), stop).await?;
|
||||
let mut seen = vec![];
|
||||
while seen.len() < known.len() {
|
||||
if same_bytes(link, &known, at, stop).await? { Ok(()) } else { Err(Error::Changed) }
|
||||
}
|
||||
|
||||
/// Whether the server has `known` at `at`.
|
||||
pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) -> Result<bool> {
|
||||
let len = known.len() as u64;
|
||||
same_body(send_range(link, at, Some(at + len), stop).await?, known, stop).await
|
||||
}
|
||||
|
||||
/// Whether the body begins with `known`.
|
||||
pub(crate) async fn same_body(mut response: Response, known: &[u8], stop: &mut Stop) -> Result<bool> {
|
||||
let mut rest = known;
|
||||
while !rest.is_empty() {
|
||||
let chunk = tokio::select! {
|
||||
_ = stopped(stop) => return Err(Error::Stopped),
|
||||
chunk = response.chunk() => chunk?,
|
||||
};
|
||||
let Some(chunk) = chunk else { return Err(Error::Cut { got: seen.len() as u64, expected: Some(len) }) };
|
||||
seen.extend_from_slice(&chunk);
|
||||
let Some(chunk) = chunk else {
|
||||
return Err(Error::Cut { got: (known.len() - rest.len()) as u64, expected: Some(known.len() as u64) });
|
||||
};
|
||||
let (now, later) = rest.split_at(chunk.len().min(rest.len()));
|
||||
if !chunk.starts_with(now) {
|
||||
return Ok(false);
|
||||
}
|
||||
rest = later;
|
||||
}
|
||||
if seen == known { Ok(()) } else { Err(Error::Changed) }
|
||||
Ok(true)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,14 +8,17 @@ mod parts;
|
|||
mod probe;
|
||||
|
||||
pub use download::{Options, Shared, download};
|
||||
pub use fetch::{Link, OVERLAP, compare, fetch};
|
||||
pub(crate) use download::is_page;
|
||||
pub(crate) use fetch::same_body;
|
||||
pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes};
|
||||
pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot};
|
||||
pub use name::safe as safe_name;
|
||||
pub use probe::{Probe, probe};
|
||||
|
||||
use crate::{disk, store};
|
||||
use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue};
|
||||
use reqwest::{Certificate, Client, Response, StatusCode, redirect};
|
||||
pub(crate) use reqwest::{Client, Response};
|
||||
use reqwest::{Certificate, StatusCode, redirect};
|
||||
use std::sync::Once;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::watch;
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ fn extension_of(mime: &str) -> Option<&'static str> {
|
|||
}
|
||||
|
||||
/// The extension stands for a kind of file that Medlar knows.
|
||||
pub(super) fn is_file_type(ext: &str) -> bool {
|
||||
pub(crate) fn is_file_type(ext: &str) -> bool {
|
||||
let ext = ext.to_lowercase();
|
||||
let more = ["appimage", "bin", "dmg", "exe", "img", "jar", "msi", "torrent"];
|
||||
TYPES.iter().any(|(_, e)| *e == ext) || more.contains(&ext.as_str())
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
//! Medlar's engine, limits, queues, store and settings. No UI code.
|
||||
|
||||
pub mod adapt;
|
||||
pub mod adopt;
|
||||
pub mod disk;
|
||||
pub mod error;
|
||||
pub mod events;
|
||||
|
|
@ -14,6 +15,7 @@ pub mod part;
|
|||
pub mod paths;
|
||||
pub mod recover;
|
||||
pub mod redact;
|
||||
pub mod relink;
|
||||
pub mod segment;
|
||||
pub mod settings;
|
||||
pub mod snapshot;
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
use super::bin::Binned;
|
||||
use super::pick::{Candidate, pick};
|
||||
use super::{Answer, Command, Config, Error, Files, Msg, Result, files};
|
||||
use crate::adopt::Found;
|
||||
use crate::error::{Failure, Place, Retry};
|
||||
use crate::events::Event;
|
||||
use crate::http::{self, Monitor, PartState, PartView, Source, download, safe_name};
|
||||
|
|
@ -13,14 +14,15 @@ use crate::model::*;
|
|||
use crate::net_state::{self, Network};
|
||||
use crate::recover::sleep::{self, Sleep};
|
||||
use crate::recover::{Breakers, DiskNeed, Gate};
|
||||
use crate::relink::{self, Checked, NewLink, Verdict};
|
||||
use crate::settings::Limits;
|
||||
use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals};
|
||||
use crate::speed::{History, Meter};
|
||||
use crate::store::{self, Store};
|
||||
use crate::{host, redact, strings, tr};
|
||||
use crate::{adopt, disk, host, redact, strings, tr};
|
||||
use arc_swap::ArcSwap;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
|
@ -46,6 +48,11 @@ pub enum Why {
|
|||
pub enum Worked {
|
||||
Plain,
|
||||
Binned(Option<Binned>),
|
||||
Continued,
|
||||
/// Out of the way of this one.
|
||||
Aside(Box<Task>),
|
||||
/// With the state it should be in. Nothing is left of it if it failed.
|
||||
Adopted(Result<State>),
|
||||
}
|
||||
|
||||
enum Work {
|
||||
|
|
@ -73,6 +80,7 @@ enum Hold {
|
|||
/// For a look at its folder; None while one is under way.
|
||||
Disk(Option<Instant>),
|
||||
Wake,
|
||||
Link,
|
||||
}
|
||||
|
||||
/// What waits for a task's work to end.
|
||||
|
|
@ -282,10 +290,11 @@ impl Actor {
|
|||
actor.store.delete_task(task.id)?;
|
||||
continue;
|
||||
}
|
||||
let awaits = task.state == State::Waiting && task.error.as_ref().is_some_and(|e| e.kind == Some(ErrorKind::Link));
|
||||
// The program ended in the middle of it.
|
||||
let cut = matches!(task.state, State::Running | State::Checking | State::Finishing);
|
||||
// It waited for a retry, the network or a disk: that is found out anew.
|
||||
if cut || (task.state == State::Waiting && task.error.as_ref().is_some_and(|e| e.kind.is_some())) {
|
||||
if cut || (task.state == State::Waiting && !awaits && task.error.as_ref().is_some_and(|e| e.kind.is_some())) {
|
||||
actor.store.set_state(task.id, State::Queued, None)?;
|
||||
(task.state, task.error) = (State::Queued, None);
|
||||
if !actor.config.recovery.auto_resume {
|
||||
|
|
@ -301,6 +310,10 @@ impl Actor {
|
|||
if unfinished {
|
||||
entry.took(Some(actor.store.parts(id)?));
|
||||
}
|
||||
if awaits {
|
||||
entry.hold = Some(Hold::Link);
|
||||
actor.held.insert(id);
|
||||
}
|
||||
actor.entries.insert(id, entry);
|
||||
actor.dirty.insert(id);
|
||||
}
|
||||
|
|
@ -356,6 +369,8 @@ impl Actor {
|
|||
fn take(&mut self, msg: Msg) {
|
||||
match msg {
|
||||
Msg::Command(command, answer) => self.command(command, answer),
|
||||
Msg::Check(id, link, answer) => self.check(id, link, answer),
|
||||
Msg::CheckPartial(path, link, answer) => self.check_partial(path, link, answer),
|
||||
Msg::Limits(limits) => self.set_limits(limits),
|
||||
Msg::OnChange(call) => self.on_change.push(call),
|
||||
Msg::Ended(id, result) => self.ended(id, result),
|
||||
|
|
@ -433,9 +448,14 @@ impl Actor {
|
|||
|
||||
fn command(&mut self, command: Command, answer: Option<Answer>) {
|
||||
let Some(id) = command.id() else {
|
||||
let Command::Add(task) = command else { unreachable!("only it has no id") };
|
||||
let result = self.add(*task);
|
||||
return self.answer(answer, result);
|
||||
return match command {
|
||||
Command::Add(task) => {
|
||||
let result = self.add(*task);
|
||||
self.answer(answer, result);
|
||||
}
|
||||
Command::Adopt { task, found } => self.adopt(*task, *found, answer),
|
||||
_ => unreachable!("they have an id"),
|
||||
};
|
||||
};
|
||||
let Some(e) = self.entries.get(&id) else {
|
||||
let removed = matches!(command, Command::Remove { .. });
|
||||
|
|
@ -443,7 +463,7 @@ impl Actor {
|
|||
};
|
||||
match command {
|
||||
Command::KeepBoth(_) if !e.removed() => {
|
||||
let again = Task { state: State::Queued, size: None, etag: None, last_modified: None, mime: None, position: 0.0, ..(*e.task).clone() };
|
||||
let again = Task { state: State::Queued, size: None, etag: None, last_modified: None, mime: None, position: 0.0, replaces: None, ..(*e.task).clone() };
|
||||
let result = self.add(again);
|
||||
self.answer(answer, result);
|
||||
}
|
||||
|
|
@ -465,6 +485,7 @@ impl Actor {
|
|||
}
|
||||
match command {
|
||||
Command::Restore(_) => (!e.removed()).then_some(Ok(())),
|
||||
Command::Continue { checked, .. } if checked.verdict() == Verdict::Different => Some(Err(Error::Different)),
|
||||
_ if e.removed() => Some(Err(store::Error::NotFound.into())),
|
||||
Command::Move { folder, .. } if !folder.is_absolute() => Some(Err(Error::Folder)),
|
||||
Command::Move { folder, .. } => (*folder == e.task.folder).then_some(Ok(())),
|
||||
|
|
@ -479,7 +500,7 @@ impl Actor {
|
|||
fn must_wait(&self, id: TaskId, command: &Command) -> bool {
|
||||
use Command::*;
|
||||
let e = &self.entries[&id];
|
||||
let alone = matches!(command, Move { .. } | Rename { .. } | Redownload(_) | Restore(_));
|
||||
let alone = matches!(command, Move { .. } | Rename { .. } | Redownload(_) | Restore(_) | Continue { .. });
|
||||
!e.todo.is_empty()
|
||||
|| match e.work {
|
||||
None => false,
|
||||
|
|
@ -574,8 +595,10 @@ impl Actor {
|
|||
None => result = Err(Error::Name),
|
||||
},
|
||||
Command::Edit { edit, .. } => result = self.change(id, edit),
|
||||
Command::AwaitLink(_) => result = self.await_link(id),
|
||||
Command::Continue { checked, .. } => return self.go_on(id, *checked, answer),
|
||||
Command::Remove { .. } | Command::KeepBoth(_) => {}
|
||||
Command::Add(_) => unreachable!("has no id"),
|
||||
Command::Add(_) | Command::Adopt { .. } => unreachable!("have no id"),
|
||||
}
|
||||
self.answer(answer, result.map(|()| id));
|
||||
}
|
||||
|
|
@ -603,6 +626,111 @@ impl Actor {
|
|||
Ok(id)
|
||||
}
|
||||
|
||||
// New links.
|
||||
|
||||
/// Off this thread, until it is done or nobody waits for it any more.
|
||||
fn look<T: Send + 'static>(&self, mut answer: oneshot::Sender<Result<T>>, server: Arc<str>, work: impl Future<Output = http::Result<T>> + Send + 'static) {
|
||||
self.runtime().spawn(async move {
|
||||
let result = tokio::select! {
|
||||
_ = answer.closed() => return,
|
||||
result = work => result,
|
||||
};
|
||||
let place = Place { server: &server, folder: Path::new("/"), begun: false };
|
||||
let _ = answer.send(result.map_err(|e| Error::Link(Box::new(Failure::of(&e, place)))));
|
||||
});
|
||||
}
|
||||
|
||||
fn check(&self, id: TaskId, link: NewLink, answer: oneshot::Sender<Result<Checked>>) {
|
||||
let Some(e) = self.entries.get(&id).filter(|e| !e.removed()) else {
|
||||
let _ = answer.send(Err(store::Error::NotFound.into()));
|
||||
return;
|
||||
};
|
||||
let (task, shared) = (e.task.clone(), self.config.shared.clone());
|
||||
self.look(answer, host_of(&link.url), async move {
|
||||
let (_keep, mut stop) = watch::channel(false);
|
||||
let store = shared.store.clone();
|
||||
let parts = disk::blocking(move || store.parts(id)).await?;
|
||||
let source = Source::new(&link.url)?.with_headers(&link.headers);
|
||||
relink::check(&shared.client, &task, &parts, link, source, &mut stop).await
|
||||
});
|
||||
}
|
||||
|
||||
fn check_partial(&self, path: PathBuf, link: NewLink, answer: oneshot::Sender<Result<Found>>) {
|
||||
let shared = self.config.shared.clone();
|
||||
self.look(answer, host_of(&link.url), async move {
|
||||
let (_keep, mut stop) = watch::channel(false);
|
||||
let partial = disk::blocking(move || adopt::look(&path)).await.map_err(disk::Error::Io)?;
|
||||
let source = Source::new(&link.url)?.with_headers(&link.headers);
|
||||
adopt::check(&shared.client, partial, link, source, &mut stop).await
|
||||
});
|
||||
}
|
||||
|
||||
fn await_link(&mut self, id: TaskId) -> Result<()> {
|
||||
if matches!(self.entries[&id].task.state, State::Checking | State::Finishing | State::Done | State::Gone) {
|
||||
return Ok(());
|
||||
}
|
||||
self.hold(id)?;
|
||||
self.held.remove(&id);
|
||||
let error = Failure::new(ErrorKind::Link, self.place(id)).error();
|
||||
self.set_state(id, State::Waiting, Some(error))?;
|
||||
self.held.insert(id);
|
||||
self.entry(id).hold = Some(Hold::Link);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn go_on(&mut self, id: TaskId, checked: Checked, answer: Option<Answer>) {
|
||||
let e = &self.entries[&id];
|
||||
if matches!(e.task.state, State::Checking | State::Finishing | State::Done | State::Gone) {
|
||||
return self.answer(answer, Ok(id));
|
||||
}
|
||||
if checked.ranges || e.downloaded == 0 {
|
||||
return self.work(id, answer, move |store, _| files::relink(store, id, checked).map(|()| Worked::Continued));
|
||||
}
|
||||
let mut again = (*e.task).clone();
|
||||
again.replaces = Some(id);
|
||||
(again.state, again.position) = (State::Queued, e.task.position);
|
||||
checked.put_in(&mut again);
|
||||
(again.size, again.etag, again.last_modified, again.mime) = (None, None, None, None);
|
||||
if let Err(e) = self.hold(id) {
|
||||
return self.answer(answer, Err(e));
|
||||
}
|
||||
self.work(id, answer, move |store, cancel| files::step_aside(store, id, cancel).map(|()| Worked::Aside(Box::new(again))));
|
||||
}
|
||||
|
||||
fn adopt(&mut self, mut task: Task, found: Found, answer: Option<Answer>) {
|
||||
let checked = &found.checked;
|
||||
let refused = match checked.verdict() {
|
||||
Verdict::Different => Some(Error::Different),
|
||||
_ if !checked.ranges || found.partial.runs.is_empty() => Some(Error::Partial(checked.text())),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(refused) = refused {
|
||||
return self.answer(answer, Err(refused));
|
||||
}
|
||||
// It must not begin before the file is there.
|
||||
let wanted = std::mem::replace(&mut task.state, State::Paused);
|
||||
checked.link.put_in(&mut task);
|
||||
match self.add(task) {
|
||||
Ok(id) => {
|
||||
let path = redact::text(&found.partial.path.display().to_string());
|
||||
self.entry(id).log(&tr!("log.adopted", path = path));
|
||||
self.work(id, answer, move |store, cancel| Ok(Worked::Adopted(files::adopt(store, id, &found, cancel).map(|()| wanted))));
|
||||
}
|
||||
Err(e) => self.answer(answer, Err(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The new one is whole: those it started over for may go.
|
||||
fn replace(&mut self, id: TaskId) {
|
||||
let mut old = self.entries[&id].task.replaces;
|
||||
while let Some((id, e)) = old.and_then(|id| Some((id, self.entries.get(&id)?))) {
|
||||
old = e.task.replaces;
|
||||
if !e.removed() && !matches!(e.task.state, State::Done | State::Gone) {
|
||||
self.command(Command::Remove { id, files: Files::Bin }, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resume(&mut self, id: TaskId) -> Result<()> {
|
||||
match self.entries[&id].task.state {
|
||||
State::Paused | State::Waiting | State::Failed => {
|
||||
|
|
@ -881,6 +1009,7 @@ impl Actor {
|
|||
e.counters.finished += 1;
|
||||
(e.forced, e.fails) = (0, 0);
|
||||
e.took(None);
|
||||
self.replace(id);
|
||||
}
|
||||
|
||||
fn failed(&mut self, id: TaskId, why: &Why) {
|
||||
|
|
@ -1062,10 +1191,30 @@ impl Actor {
|
|||
let Some(Work::Files { answer, .. }) = self.entry(id).work.take() else { return };
|
||||
let was = self.entries[&id].task.clone();
|
||||
let result = result.and_then(|worked| self.reload(id, true).map(|()| worked));
|
||||
let mut answers = id;
|
||||
let result = match result {
|
||||
Ok(Worked::Continued) => {
|
||||
let e = self.entry(id);
|
||||
let url = e.task.url.clone();
|
||||
e.log(&tr!("log.continued", url = url));
|
||||
self.resume(id).map(|()| Worked::Plain)
|
||||
}
|
||||
Ok(Worked::Aside(task)) => self.add(*task).map(|new| {
|
||||
answers = new;
|
||||
Worked::Plain
|
||||
}),
|
||||
Ok(Worked::Adopted(Ok(State::Queued))) => self.resume(id).map(|()| Worked::Plain),
|
||||
Ok(Worked::Adopted(Ok(_))) => Ok(Worked::Plain),
|
||||
Ok(Worked::Adopted(Err(e))) => {
|
||||
self.remove(id, Files::Keep, None);
|
||||
Err(e)
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
let e = self.entry(id);
|
||||
match &result {
|
||||
Ok(Worked::Binned(binned)) => e.binned = binned.clone(),
|
||||
Ok(Worked::Plain) => {
|
||||
Ok(_) => {
|
||||
if was.folder != e.task.folder {
|
||||
e.log(&tr!("log.moved", folder = e.task.folder.display()));
|
||||
}
|
||||
|
|
@ -1080,7 +1229,7 @@ impl Actor {
|
|||
self.removed.remove(&id);
|
||||
self.happened.push(Event::Restored(id));
|
||||
}
|
||||
self.answer(answer, result.map(|_| id));
|
||||
self.answer(answer, result.map(|_| answers));
|
||||
self.next(id);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,12 +2,15 @@
|
|||
|
||||
use super::bin::{Bin, Binned};
|
||||
use super::{Error, Result};
|
||||
use crate::adopt::Found;
|
||||
use crate::disk::{self, PartialFile, exists, partial_path, rename_new, variants};
|
||||
use crate::http::safe_name;
|
||||
use crate::model::{Part, State, Task, TaskId};
|
||||
use crate::relink::Checked;
|
||||
use crate::store::Store;
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::io::{self, Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
|
|
@ -184,6 +187,73 @@ pub fn discard(store: &Store, id: TaskId) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Copies the finished ranges of another program's file. Nothing is left behind when it fails.
|
||||
pub fn adopt(store: &Store, id: TaskId, found: &Found, cancel: &AtomicBool) -> Result<()> {
|
||||
let task = store.task(id)?;
|
||||
let disk_error = |e| match e {
|
||||
disk::Error::Io(e) => Error::File(e),
|
||||
disk::Error::NoSpace { .. } => Error::File(io::ErrorKind::StorageFull.into()),
|
||||
disk::Error::Busy => Error::File(io::ErrorKind::ResourceBusy.into()),
|
||||
};
|
||||
let wanted = safe_name(&task.name).unwrap_or(found.checked.name.clone());
|
||||
let (file, checked) = {
|
||||
let _names = disk::names();
|
||||
let (file, name) = PartialFile::create(&task.folder, &wanted, &store.used_names(&task.folder, id)?).map_err(disk_error)?;
|
||||
let checked = found.checked.clone();
|
||||
store.edit_task(id, move |t| t.name = name)?;
|
||||
(file, checked)
|
||||
};
|
||||
let work = || -> Result<()> {
|
||||
if let Some(size) = checked.size {
|
||||
file.reserve(size).map_err(disk_error)?;
|
||||
}
|
||||
let mut from = File::open(&found.partial.path).map_err(Error::File)?;
|
||||
let mut to = OpenOptions::new().write(true).open(file.path()).map_err(Error::File)?;
|
||||
for run in &found.partial.runs {
|
||||
from.seek(SeekFrom::Start(run.start)).map_err(Error::File)?;
|
||||
to.seek(SeekFrom::Start(run.start)).map_err(Error::File)?;
|
||||
let mut left = run.end - run.start;
|
||||
while left > 0 {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err(Error::File(io::ErrorKind::Interrupted.into()));
|
||||
}
|
||||
let n = left.min(64 << 20);
|
||||
// Shorter than it was.
|
||||
if io::copy(&mut (&from).take(n), &mut to).map_err(Error::File)? != n {
|
||||
return Err(Error::File(io::ErrorKind::UnexpectedEof.into()));
|
||||
}
|
||||
left -= n;
|
||||
}
|
||||
}
|
||||
file.sync().map_err(disk_error)?;
|
||||
// The data goes first, so that the record never claims more than there is.
|
||||
store.save_parts(id, found.parts())?;
|
||||
store.edit_task(id, move |t| checked.put_in(t))?;
|
||||
Ok(())
|
||||
};
|
||||
work().inspect_err(|_| {
|
||||
let _ = fs::remove_file(file.path());
|
||||
let _ = store.save_parts(id, vec![]);
|
||||
})
|
||||
}
|
||||
|
||||
/// Takes a new link. What is here stays.
|
||||
pub fn relink(store: &Store, id: TaskId, checked: Checked) -> Result<()> {
|
||||
// Nothing to keep; its parts may not fit the new size.
|
||||
if store.task(id)?.downloaded == 0 {
|
||||
discard(store, id)?;
|
||||
}
|
||||
store.edit_task(id, move |t| checked.put_in(t))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Leaves the task's name to another.
|
||||
pub fn step_aside(store: &Store, id: TaskId, cancel: &AtomicBool) -> Result<()> {
|
||||
let name = store.task(id)?.name;
|
||||
let other = variants(&name).nth(1).expect("variants never end");
|
||||
relocate(store, id, None, Some(&other), cancel)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
|||
|
|
@ -9,12 +9,15 @@ mod pick;
|
|||
|
||||
pub use bin::Bin;
|
||||
|
||||
use crate::adopt::Found;
|
||||
use crate::error::Failure;
|
||||
use crate::events::Event;
|
||||
use crate::http::{Options, Shared};
|
||||
use crate::model::{Task, TaskId};
|
||||
use crate::net_state::Network;
|
||||
use crate::recover::Recovery;
|
||||
use crate::recover::sleep::Sleep;
|
||||
use crate::relink::{Checked, NewLink};
|
||||
use crate::settings::Limits;
|
||||
use crate::snapshot::Snapshot;
|
||||
use crate::{store, tr};
|
||||
|
|
@ -39,6 +42,12 @@ pub enum Error {
|
|||
Folder,
|
||||
File(io::Error),
|
||||
Bin(io::Error),
|
||||
/// The link leads to another file.
|
||||
Different,
|
||||
/// Nothing can be taken over; `Checked::text` says why.
|
||||
Partial(String),
|
||||
/// The link could not be checked.
|
||||
Link(Box<Failure>),
|
||||
/// Medlar is closing.
|
||||
Closed,
|
||||
}
|
||||
|
|
@ -59,6 +68,9 @@ impl fmt::Display for Error {
|
|||
Error::Folder => tr!("manager.folder"),
|
||||
Error::File(e) => tr!("manager.file", why = e),
|
||||
Error::Bin(e) => tr!("manager.bin", why = e),
|
||||
Error::Different => tr!("manager.different"),
|
||||
Error::Partial(why) => tr!("manager.partial", why = why),
|
||||
Error::Link(failure) => failure.text.clone(),
|
||||
Error::Closed => tr!("manager.closed"),
|
||||
})
|
||||
}
|
||||
|
|
@ -101,15 +113,24 @@ pub enum Command {
|
|||
/// Changes what the user decides: link, mirrors, queue, position, priority, limits, headers, notes and the like.
|
||||
/// Changes of other fields are dropped.
|
||||
Edit { id: TaskId, edit: Box<dyn FnOnce(&mut Task) + Send> },
|
||||
/// Waits for a link from the source page; `relink::find` puts it first. Pause and Resume end the wait.
|
||||
AwaitLink(TaskId),
|
||||
/// Goes on from a link that `Manager::check` looked at, with that link's headers and login instead of the old ones. Refused
|
||||
/// when it is another file. If the server can't continue, a new download starts over and answers; the old one keeps what it
|
||||
/// has and is binned when the new one is whole.
|
||||
Continue { id: TaskId, checked: Box<Checked> },
|
||||
/// Adds a download that goes on from a file `Manager::check_partial` looked at. The link and what the server said come from
|
||||
/// there, the rest from the task.
|
||||
Adopt { task: Box<Task>, found: Box<Found> },
|
||||
}
|
||||
|
||||
impl Command {
|
||||
fn id(&self) -> Option<TaskId> {
|
||||
use Command::*;
|
||||
match self {
|
||||
Add(_) => None,
|
||||
Start(id) | Pause(id) | Resume(id) | Stop(id) | Restore(id) | Redownload(id) | KeepBoth(id) => Some(*id),
|
||||
Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } => Some(*id),
|
||||
Add(_) | Adopt { .. } => None,
|
||||
Start(id) | Pause(id) | Resume(id) | Stop(id) | Restore(id) | Redownload(id) | KeepBoth(id) | AwaitLink(id) => Some(*id),
|
||||
Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } | Continue { id, .. } => Some(*id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -117,11 +138,11 @@ impl Command {
|
|||
/// The answer to a command, when the snapshot shows what it did. Needn't be looked at.
|
||||
#[derive(Debug)]
|
||||
#[must_use = "errors come only this way; drop it to ignore them"]
|
||||
pub struct Reply(oneshot::Receiver<Result<TaskId>>);
|
||||
pub struct Reply<T = TaskId>(oneshot::Receiver<Result<T>>);
|
||||
|
||||
impl Reply {
|
||||
impl<T> Reply<T> {
|
||||
/// None while there is no answer. Never waits; ask no more after the answer.
|
||||
pub fn try_get(&mut self) -> Option<Result<TaskId>> {
|
||||
pub fn try_get(&mut self) -> Option<Result<T>> {
|
||||
match self.0.try_recv() {
|
||||
Ok(result) => Some(result),
|
||||
Err(oneshot::error::TryRecvError::Empty) => None,
|
||||
|
|
@ -130,13 +151,13 @@ impl Reply {
|
|||
}
|
||||
|
||||
/// Not for the thread of the window, nor inside async code.
|
||||
pub fn wait(self) -> Result<TaskId> {
|
||||
pub fn wait(self) -> Result<T> {
|
||||
self.0.blocking_recv().unwrap_or(Err(Error::Closed))
|
||||
}
|
||||
}
|
||||
|
||||
impl Future for Reply {
|
||||
type Output = Result<TaskId>;
|
||||
impl<T> Future for Reply<T> {
|
||||
type Output = Result<T>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
|
||||
Poll::Ready(ready!(Pin::new(&mut self.0).poll(cx)).unwrap_or(Err(Error::Closed)))
|
||||
|
|
@ -173,6 +194,8 @@ type Answer = oneshot::Sender<Result<TaskId>>;
|
|||
|
||||
enum Msg {
|
||||
Command(Command, Option<Answer>),
|
||||
Check(TaskId, NewLink, oneshot::Sender<Result<Checked>>),
|
||||
CheckPartial(PathBuf, NewLink, oneshot::Sender<Result<Found>>),
|
||||
Limits(Limits),
|
||||
OnChange(Box<dyn Fn() + Send>),
|
||||
/// A download ended.
|
||||
|
|
@ -214,6 +237,20 @@ impl Manager {
|
|||
Reply(reply)
|
||||
}
|
||||
|
||||
/// Compares what a download has with what a new link leads to; nothing changes. Dropping the reply ends it.
|
||||
pub fn check(&self, id: TaskId, link: NewLink) -> Reply<Checked> {
|
||||
let (answer, reply) = oneshot::channel();
|
||||
let _ = self.to.send(Msg::Check(id, link, answer));
|
||||
Reply(reply)
|
||||
}
|
||||
|
||||
/// The same for an unfinished file of another program.
|
||||
pub fn check_partial(&self, path: PathBuf, link: NewLink) -> Reply<Found> {
|
||||
let (answer, reply) = oneshot::channel();
|
||||
let _ = self.to.send(Msg::CheckPartial(path, link, answer));
|
||||
Reply(reply)
|
||||
}
|
||||
|
||||
/// Takes effect at once, also on running downloads. 0 is no limit. The speed is not its business.
|
||||
pub fn set_limits(&self, limits: Limits) {
|
||||
let _ = self.to.send(Msg::Limits(limits));
|
||||
|
|
|
|||
|
|
@ -126,6 +126,8 @@ named_enum!(
|
|||
List = "list",
|
||||
Sleep = "sleep",
|
||||
Killed = "killed",
|
||||
/// Waits for a link from its page.
|
||||
Link = "link",
|
||||
Crashed = "crashed",
|
||||
}
|
||||
);
|
||||
|
|
@ -174,6 +176,8 @@ pub struct Task {
|
|||
/// Keyring item with the cookies and login.
|
||||
pub secret: Option<String>,
|
||||
pub after: Option<TaskId>,
|
||||
/// The unfinished one this starts over. Removed when this is done.
|
||||
pub replaces: Option<TaskId>,
|
||||
pub start_at: Option<Time>,
|
||||
pub added_at: Time,
|
||||
pub finished_at: Option<Time>,
|
||||
|
|
@ -210,6 +214,7 @@ impl Default for Task {
|
|||
proxy: None,
|
||||
secret: None,
|
||||
after: None,
|
||||
replaces: None,
|
||||
start_at: None,
|
||||
added_at: now(),
|
||||
finished_at: None,
|
||||
|
|
|
|||
336
crates/core/src/relink/matching.rs
Normal file
336
crates/core/src/relink/matching.rs
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
//! Which downloads an incoming link may continue. Only a guess: `check` proves it.
|
||||
|
||||
use crate::http::name;
|
||||
use crate::model::{ErrorKind, State, Task, TaskId};
|
||||
use percent_encoding::percent_decode_str;
|
||||
use std::collections::BTreeSet;
|
||||
use url::Url;
|
||||
|
||||
/// A link from the browser or the clipboard, and what is known about it.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Incoming {
|
||||
pub url: String,
|
||||
pub name: Option<String>,
|
||||
pub size: Option<u64>,
|
||||
/// The page it is on.
|
||||
pub page: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Strength {
|
||||
Maybe,
|
||||
Likely,
|
||||
/// The same link but for its signature, or the same name and size.
|
||||
Strong,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Match {
|
||||
pub id: TaskId,
|
||||
pub strength: Strength,
|
||||
/// It waits for a new link.
|
||||
pub awaited: bool,
|
||||
score: u32,
|
||||
}
|
||||
|
||||
/// Best first: the one that waits for a link, then by how much speaks for it, then the latest.
|
||||
pub fn find<'a>(link: &Incoming, tasks: impl IntoIterator<Item = &'a Task>) -> Vec<Match> {
|
||||
let Some(new) = Clues::of(&link.url, link.name.as_deref()) else { return vec![] };
|
||||
let mut out: Vec<Match> = tasks
|
||||
.into_iter()
|
||||
.filter(|t| t.removed_at.is_none() && matches!(t.state, State::Paused | State::Failed | State::Waiting | State::Queued))
|
||||
.filter_map(|t| {
|
||||
let score = score(link, &new, t)?;
|
||||
let strength = match score {
|
||||
100.. => Strength::Strong,
|
||||
80.. => Strength::Likely,
|
||||
60.. => Strength::Maybe,
|
||||
_ => return None,
|
||||
};
|
||||
Some(Match { id: t.id, strength, awaited: awaited(t), score })
|
||||
})
|
||||
.collect();
|
||||
out.sort_by_key(|m| std::cmp::Reverse((m.awaited, m.score, m.id)));
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn awaited(t: &Task) -> bool {
|
||||
t.state == State::Waiting && t.error.as_ref().is_some_and(|e| e.kind == Some(ErrorKind::Link))
|
||||
}
|
||||
|
||||
/// None when it can't be the same file. A name, a size or a page alone proves too little.
|
||||
fn score(link: &Incoming, new: &Clues, task: &Task) -> Option<u32> {
|
||||
let old = Clues::of(&task.url, Some(&task.name).filter(|n| !n.is_empty()).map(|n| n.as_str()))?;
|
||||
let same_size = match (link.size, task.size) {
|
||||
(Some(a), Some(b)) if a != b => return None,
|
||||
(Some(_), Some(_)) => true,
|
||||
_ => false,
|
||||
};
|
||||
let mut score = 0u32;
|
||||
let same_site = new.site == old.site;
|
||||
if new.path == old.path && new.query == old.query && new.tells() {
|
||||
score += if new.host == old.host { 100 } else if same_site { 90 } else { 60 };
|
||||
} else if new.loose_path == old.loose_path && new.query == old.query && same_site && new.named() {
|
||||
// Tokens in the path may tell files apart.
|
||||
score += 45;
|
||||
}
|
||||
if let (Some(a), Some(b)) = (&new.name, &old.name) {
|
||||
if a == b {
|
||||
score += if generic(a) { 5 } else { 45 };
|
||||
} else if link.name.is_some() && !task.name.is_empty() && !generic(a) && !generic(b) {
|
||||
// Both were named, differently. The name may have been changed by the user.
|
||||
score = score.saturating_sub(40);
|
||||
}
|
||||
}
|
||||
if same_size {
|
||||
score += 55;
|
||||
}
|
||||
if let (Some(a), Some(b)) = (&link.page, &task.source_page)
|
||||
&& let (Some(a), Some(b)) = (page(a), page(b))
|
||||
{
|
||||
score += if a == b { 45 } else { 0 };
|
||||
}
|
||||
if awaited(task) && same_site && score > 0 {
|
||||
score += 15;
|
||||
}
|
||||
Some(score)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Clues {
|
||||
host: String,
|
||||
/// The last two labels of the host: good enough to group the servers of a site.
|
||||
site: String,
|
||||
path: Vec<String>,
|
||||
/// Without tokens.
|
||||
loose_path: Vec<String>,
|
||||
query: BTreeSet<(String, String)>,
|
||||
/// In small letters, without ` (1)`.
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
impl Clues {
|
||||
fn of(url: &str, name: Option<&str>) -> Option<Clues> {
|
||||
let url = Url::parse(url).ok()?;
|
||||
let host = url.host_str()?.trim_start_matches("www.").to_string();
|
||||
let path: Vec<String> =
|
||||
url.path().split('/').filter(|s| !s.is_empty()).map(|s| percent_decode_str(s).decode_utf8_lossy().into_owned()).collect();
|
||||
let query = url.query_pairs().filter(|(k, v)| !noise(&k.to_ascii_lowercase(), v)).map(|(k, v)| (k.into(), v.into())).collect();
|
||||
let named = path.last().filter(|n| name::split(n).1.is_some_and(name::is_file_type)).map(String::as_str);
|
||||
Some(Clues {
|
||||
site: site(&host),
|
||||
host,
|
||||
loose_path: path.iter().filter(|s| !token(s)).cloned().collect(),
|
||||
query,
|
||||
name: name.or(named).map(plain_name),
|
||||
path,
|
||||
})
|
||||
}
|
||||
|
||||
/// More than the front page of a site.
|
||||
fn tells(&self) -> bool {
|
||||
!self.path.is_empty() || !self.query.is_empty()
|
||||
}
|
||||
|
||||
fn named(&self) -> bool {
|
||||
self.name.as_ref().is_some_and(|n| !generic(n))
|
||||
}
|
||||
}
|
||||
|
||||
fn site(host: &str) -> String {
|
||||
if host.parse::<std::net::Ipv4Addr>().is_ok() || host.starts_with('[') {
|
||||
return host.into();
|
||||
}
|
||||
let labels: Vec<&str> = host.split('.').collect();
|
||||
// `co.uk` and the like.
|
||||
let short = labels.len() > 2 && labels[labels.len() - 2].len() <= 3 && labels[labels.len() - 1].len() == 2;
|
||||
labels[labels.len().saturating_sub(if short { 3 } else { 2 })..].join(".")
|
||||
}
|
||||
|
||||
/// Without a number in brackets before the ending, which browsers and Medlar add to names that are taken.
|
||||
fn plain_name(name: &str) -> String {
|
||||
let name = name.to_lowercase();
|
||||
let (stem, ext) = name::split(&name);
|
||||
let mut stem = stem.trim_end();
|
||||
if let Some((before, number)) = stem.strip_suffix(')').and_then(|s| s.rsplit_once('('))
|
||||
&& !before.trim().is_empty()
|
||||
&& (1..=3).contains(&number.len())
|
||||
&& number.bytes().all(|b| b.is_ascii_digit())
|
||||
{
|
||||
stem = before.trim_end();
|
||||
}
|
||||
match ext {
|
||||
Some(ext) => format!("{stem}.{ext}"),
|
||||
None => stem.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Names that many files have.
|
||||
fn generic(name: &str) -> bool {
|
||||
matches!(
|
||||
name::split(name).0,
|
||||
"download" | "file" | "index" | "videoplayback" | "video" | "audio" | "image" | "get" | "dl" | "stream" | "media" | "main" | "master"
|
||||
| "latest" | "setup" | "installer" | "default" | "untitled" | "data" | "source" | "archive" | "unknown" | "playlist"
|
||||
)
|
||||
}
|
||||
|
||||
/// The page without what only moves inside it.
|
||||
fn page(url: &str) -> Option<String> {
|
||||
let mut url = Url::parse(url).ok()?;
|
||||
// A site's front page links everything.
|
||||
if url.path().len() <= 1 && url.query().is_none() {
|
||||
return None;
|
||||
}
|
||||
url.set_fragment(None);
|
||||
Some(url.as_str().trim_end_matches('/').to_string())
|
||||
}
|
||||
|
||||
/// A query field that changes with each visit and says nothing about the file.
|
||||
fn noise(key: &str, value: &str) -> bool {
|
||||
const PREFIXES: &[&str] = &["x-amz-", "x-goog-", "x-oss-", "x-cos-", "x-bce-", "utm_", "hdn", "__hdn", "__gda", "ak_"];
|
||||
const FIELDS: &[&str] = &[
|
||||
// CloudFront, S3, Google, Azure, Alibaba and the like.
|
||||
"awsaccesskeyid", "googleaccessid", "ossaccesskeyid", "key-pair-id", "policy", "signature", "sig", "sign", "lsig", "expires", "expire",
|
||||
"exp", "expiry", "expiration", "se", "sp", "sv", "sr", "st", "spr", "skoid", "sktid", "skt", "ske", "sks", "skv", "rscd", "rsct",
|
||||
"response-content-disposition", "response-content-type", "response-cache-control",
|
||||
// Tokens, sessions, times and visitors.
|
||||
"token", "access_token", "auth", "auth_key", "authkey", "jwt", "hmac", "verify", "nonce", "ticket", "session", "sessionid", "sid",
|
||||
"jsessionid", "phpsessid", "time", "timestamp", "ts", "t", "ttl", "e", "ip", "ipbits", "uid", "userid", "user", "ref", "referer",
|
||||
"referrer", "source", "from", "fbclid", "gclid", "rnd", "rand", "random", "r", "_", "cb", "cachebuster", "md5", "hash", "h", "s", "k",
|
||||
"download_token", "confirm", "uuid", "at", "wsiphost", "wstime", "wssecret", "txtime", "txsecret", "cdn_hash", "srcid", "ei", "cpn",
|
||||
"mh", "mm", "mn", "ms", "mv", "mvi", "pl", "rms", "redirect_counter", "cm2rm", "req_id", "cms_redirect", "met", "initcwndbps", "spc",
|
||||
"vprv", "svpuc", "fvip", "sparams", "lsparams", "n", "pot", "c",
|
||||
];
|
||||
// These name a file even when they look random.
|
||||
const NAMES: &[&str] = &["id", "file", "fileid", "file_id", "f", "name", "filename", "path", "v", "itag", "key", "item", "oid", "fid", "docid"];
|
||||
if NAMES.contains(&key) {
|
||||
return false;
|
||||
}
|
||||
PREFIXES.iter().any(|p| key.starts_with(p)) || FIELDS.contains(&key) || random(value)
|
||||
}
|
||||
|
||||
/// Long, and mixed as no word or number is.
|
||||
fn random(s: &str) -> bool {
|
||||
let code = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'=' | b'+' | b'/' | b'~' | b'%');
|
||||
s.len() >= 20 && s.bytes().all(code) && s.bytes().filter(u8::is_ascii_digit).count() >= 3 && s.bytes().any(|b| b.is_ascii_alphabetic())
|
||||
}
|
||||
|
||||
/// A path step that is a token or a time.
|
||||
fn token(s: &str) -> bool {
|
||||
let time = matches!(s.len(), 10 | 13) && s.starts_with('1') && s.bytes().all(|b| b.is_ascii_digit());
|
||||
time || (random(s) && name::split(s).1.is_none())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::TaskError;
|
||||
|
||||
fn task(id: TaskId, url: &str, name: &str, size: Option<u64>, page: Option<&str>) -> Task {
|
||||
Task { id, url: url.into(), name: name.into(), size, source_page: page.map(String::from), state: State::Failed, ..Task::default() }
|
||||
}
|
||||
|
||||
fn one(url: &str) -> Vec<Task> {
|
||||
let name = Url::parse(url).unwrap().path_segments().unwrap().next_back().unwrap().to_string();
|
||||
vec![task(1, url, &name, None, None)]
|
||||
}
|
||||
|
||||
fn best(link: &str, tasks: &[Task]) -> Option<(TaskId, Strength)> {
|
||||
best_of(&Incoming { url: link.into(), ..Incoming::default() }, tasks)
|
||||
}
|
||||
|
||||
fn best_of(link: &Incoming, tasks: &[Task]) -> Option<(TaskId, Strength)> {
|
||||
find(link, tasks).first().map(|m| (m.id, m.strength))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signatures_are_ignored() {
|
||||
for (old, new) in [
|
||||
// S3
|
||||
(
|
||||
"https://b.s3.eu-west-1.amazonaws.com/rel/app-2.1.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=A%2F1%2Fs3&X-Amz-Date=20261120T100000Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=8f1c0e",
|
||||
"https://b.s3.eu-west-1.amazonaws.com/rel/app-2.1.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=A%2F2%2Fs3&X-Amz-Date=20261125T100000Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=11aa22",
|
||||
),
|
||||
// GitHub's release files
|
||||
(
|
||||
"https://release-assets.githubusercontent.com/github-production-release-asset/123/0a1b-2c?sp=r&sv=2018-11-09&sr=b&spr=https&se=2026-11-20T10%3A00%3A00Z&rscd=attachment%3B+filename%3Da.zip&rsct=application%2Foctet-stream&skoid=96c2&sig=abc%3D&jwt=eyJhbGciOiJIUzI1NiJ9",
|
||||
"https://release-assets.githubusercontent.com/github-production-release-asset/123/0a1b-2c?sp=r&sv=2018-11-09&sr=b&spr=https&se=2026-11-25T10%3A00%3A00Z&rscd=attachment%3B+filename%3Da.zip&rsct=application%2Foctet-stream&skoid=96c2&sig=def%3D&jwt=eyJ0eXAiOiJKV1QiLCJh",
|
||||
),
|
||||
// CloudFront
|
||||
(
|
||||
"https://d1.cloudfront.net/movies/film.mkv?Expires=1763650000&Signature=Ab~c-&Key-Pair-Id=K2",
|
||||
"https://d1.cloudfront.net/movies/film.mkv?Expires=1764090000&Signature=Xy~z-&Key-Pair-Id=K2",
|
||||
),
|
||||
// nginx secure_link, Akamai
|
||||
("https://cdn.example.org/f/disc.iso?md5=Zg8x&expires=1763650000", "https://cdn.example.org/f/disc.iso?md5=qqP1&expires=1764090000"),
|
||||
("https://a.example.net/v/x.mp4?hdnea=st=1~exp=2~acl=/*~hmac=ab", "https://a.example.net/v/x.mp4?hdnea=st=8~exp=9~acl=/*~hmac=cd"),
|
||||
// An unknown signature.
|
||||
("https://h.example.com/a.zip?zq=9f86d081884c7d659a2feaa0c55ad015", "https://h.example.com/a.zip?zq=60303ae22b998861bce3b28f33eec1be"),
|
||||
("https://www.example.com/a.zip", "https://example.com/a.zip"),
|
||||
] {
|
||||
assert_eq!(best(new, &one(old)), Some((1, Strength::Strong)), "{new}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_in_paths_and_other_servers() {
|
||||
let old = one("https://s3.files.example/dl/9f86d081884c7d659a2feaa0c55ad015/1763650000/Big.Archive.rar");
|
||||
let new = "https://s7.files.example/dl/60303ae22b998861bce3b28f33eec1be/1764090000/Big.Archive.rar";
|
||||
assert_eq!(best(new, &old), Some((1, Strength::Likely)));
|
||||
// Another file in the same place.
|
||||
assert_eq!(best("https://s7.files.example/dl/60303ae22b998861bce3b28f33eec1be/1764090000/Other.rar", &old), None);
|
||||
// A mirror.
|
||||
assert_eq!(best("https://mirror.other.net/pub/Big.Archive.rar", &old), None, "a name alone");
|
||||
let mut sized = old.clone();
|
||||
sized[0].size = Some(7_340_032);
|
||||
let link = |size| Incoming { url: "https://mirror.other.net/pub/Big.Archive.rar".into(), size: Some(size), ..Incoming::default() };
|
||||
assert_eq!(best_of(&link(7_340_032), &sized), Some((1, Strength::Strong)));
|
||||
assert_eq!(best_of(&link(7_340_033), &sized), None);
|
||||
// Another node of a video site.
|
||||
let video = |host, expire| {
|
||||
format!("https://{host}.googlevideo.com/videoplayback?expire={expire}&ei=x{expire}&id=o-AHk&itag=137&mime=video%2Fmp4&clen=1000&sig=A{expire}&mn=sn-{host}")
|
||||
};
|
||||
let tasks = [task(4, &video("rr3---sn-aa", "1763650000"), "Talk.mp4", Some(1000), None)];
|
||||
assert_eq!(best(&video("rr1---sn-bb", "1764090000"), &tasks), Some((4, Strength::Likely)));
|
||||
assert_eq!(best(&video("rr1---sn-bb", "1764090000").replace("itag=137", "itag=140"), &tasks), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_names_a_file_counts() {
|
||||
let old = vec![task(1, "https://h.example/download.php?id=1", "report.pdf", None, None)];
|
||||
assert_eq!(best("https://h.example/download.php?id=2", &old), None);
|
||||
assert_eq!(best("https://h.example/download.php?id=1&token=abc", &old), Some((1, Strength::Strong)));
|
||||
let drive = one("https://drive.example/uc?export=download&id=1AbCdEfGhIjKlMnOpQrStUvWxYz012345");
|
||||
assert_eq!(best("https://drive.example/uc?export=download&id=1ZZCdEfGhIjKlMnOpQrStUvWxYz012345", &drive), None);
|
||||
assert_eq!(best("https://h.example/", &[task(1, "https://h.example/", "", None, None)]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_and_pages() {
|
||||
let page = Some("https://h.example/film/7#top");
|
||||
let tasks = [task(1, "https://a.cdn/x1", "Film (1).mkv", None, page), task(2, "https://a.cdn/x2", "Other.mkv", None, page)];
|
||||
let link = |name: &str, page: &str| Incoming {
|
||||
url: "https://b.cdn/y9".into(),
|
||||
name: Some(name.into()),
|
||||
page: Some(page.into()),
|
||||
..Incoming::default()
|
||||
};
|
||||
assert_eq!(best_of(&link("film.mkv", "https://h.example/film/7"), &tasks), Some((1, Strength::Likely)));
|
||||
assert_eq!(best_of(&link("film.mkv", "https://h.example/"), &tasks), None);
|
||||
assert_eq!(best_of(&link("third.mkv", "https://h.example/film/7"), &tasks), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiting_ones_first_and_finished_ones_never() {
|
||||
let url = "https://h.example/a.zip";
|
||||
let mut tasks: Vec<Task> = (1..=5).map(|id| task(id, url, "a.zip", None, None)).collect();
|
||||
tasks[0].state = State::Waiting;
|
||||
tasks[0].error = Some(TaskError { kind: Some(ErrorKind::Link), detail: String::new() });
|
||||
tasks[1].state = State::Done;
|
||||
tasks[2].removed_at = Some(1);
|
||||
tasks[3].state = State::Running;
|
||||
let found = find(&Incoming { url: url.into(), ..Incoming::default() }, &tasks);
|
||||
assert_eq!(found.iter().map(|m| (m.id, m.awaited)).collect::<Vec<_>>(), [(1, true), (5, false)]);
|
||||
assert_eq!(best("not a link", &tasks), None);
|
||||
}
|
||||
}
|
||||
383
crates/core/src/relink/mod.rs
Normal file
383
crates/core/src/relink/mod.rs
Normal file
|
|
@ -0,0 +1,383 @@
|
|||
//! Continuing a download from another link to the same file.
|
||||
//!
|
||||
//! `check` compares what is here with what the new link leads to; nothing changes. `Command::Continue` then takes the link.
|
||||
//! `find` tells which downloads an incoming link may be meant for.
|
||||
|
||||
mod matching;
|
||||
|
||||
pub use matching::{Incoming, Match, Strength, find};
|
||||
|
||||
use crate::http::{self, Client, Error, Link, OVERLAP, Result, Source, Stop, Validators, is_page, probe, same_body, same_bytes};
|
||||
use crate::model::{Part, Task};
|
||||
use crate::{disk, tr};
|
||||
use std::fs::File;
|
||||
use std::hash::{BuildHasher, RandomState};
|
||||
use std::io;
|
||||
use std::ops::Range;
|
||||
use std::os::unix::fs::FileExt;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Bytes looked at in one place.
|
||||
const SAMPLE: u64 = OVERLAP;
|
||||
/// Places inside the finished ranges, besides their ends.
|
||||
const INNER: u64 = 8;
|
||||
/// Ends of finished ranges looked at.
|
||||
const ENDS: usize = 32;
|
||||
/// So little is compared whole.
|
||||
const ALL: u64 = 16 * SAMPLE;
|
||||
|
||||
/// A link and what is sent along. Takes the place of all the old one had.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct NewLink {
|
||||
pub url: String,
|
||||
/// Without cookies and logins.
|
||||
pub headers: Vec<(String, String)>,
|
||||
/// Keyring item with the cookies and login.
|
||||
pub secret: Option<String>,
|
||||
/// None keeps the page known so far.
|
||||
pub source_page: Option<String>,
|
||||
}
|
||||
|
||||
impl NewLink {
|
||||
/// The task as it would be with this link.
|
||||
pub fn put_in(&self, task: &mut Task) {
|
||||
task.url = self.url.clone();
|
||||
task.headers = self.headers.clone();
|
||||
task.secret = self.secret.clone();
|
||||
if self.source_page.is_some() {
|
||||
task.source_page = self.source_page.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Same,
|
||||
/// What was compared is equal, but the server tells no versions apart.
|
||||
ProbablySame,
|
||||
/// Never continued.
|
||||
Different,
|
||||
CannotTell,
|
||||
}
|
||||
|
||||
/// What a verdict rests on.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Reason {
|
||||
/// Size, version and samples agree.
|
||||
Version,
|
||||
/// Samples agree.
|
||||
Samples,
|
||||
Size { old: u64, new: u64 },
|
||||
/// Some bytes differ.
|
||||
Bytes,
|
||||
/// The same server calls it another version.
|
||||
OtherVersion,
|
||||
/// A web page instead of the file.
|
||||
Page,
|
||||
/// Nothing is here yet, so nothing can be lost.
|
||||
Nothing,
|
||||
/// Too few bytes are here.
|
||||
TooLittle,
|
||||
/// The server can't continue. It starts over, and what is here stays until the new one is whole.
|
||||
NoRanges,
|
||||
}
|
||||
|
||||
impl Reason {
|
||||
pub fn verdict(self) -> Verdict {
|
||||
use Reason::*;
|
||||
match self {
|
||||
Version => Verdict::Same,
|
||||
Samples => Verdict::ProbablySame,
|
||||
Size { .. } | Bytes | OtherVersion | Page => Verdict::Different,
|
||||
Nothing | TooLittle | NoRanges => Verdict::CannotTell,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a link leads to, compared with what is here.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Checked {
|
||||
pub link: NewLink,
|
||||
pub reason: Reason,
|
||||
/// Bytes that are here.
|
||||
pub here: u64,
|
||||
/// Bytes compared.
|
||||
pub compared: u64,
|
||||
/// The server can continue.
|
||||
pub ranges: bool,
|
||||
pub size: Option<u64>,
|
||||
/// The name the server gives.
|
||||
pub name: String,
|
||||
pub(crate) version: Validators,
|
||||
pub(crate) mime: Option<String>,
|
||||
}
|
||||
|
||||
impl Checked {
|
||||
pub fn verdict(&self) -> Verdict {
|
||||
self.reason.verdict()
|
||||
}
|
||||
|
||||
/// What is here can't be used.
|
||||
pub fn starts_over(&self) -> bool {
|
||||
!self.ranges && self.here > 0
|
||||
}
|
||||
|
||||
/// For the user.
|
||||
pub fn text(&self) -> String {
|
||||
match self.reason {
|
||||
Reason::Version => tr!("relink.version"),
|
||||
Reason::Samples => tr!("relink.samples"),
|
||||
Reason::Size { old, new } => tr!("relink.size", old = old, new = new),
|
||||
Reason::Bytes => tr!("relink.bytes"),
|
||||
Reason::OtherVersion => tr!("relink.other_version"),
|
||||
Reason::Page => tr!("relink.page"),
|
||||
Reason::Nothing => tr!("relink.nothing"),
|
||||
Reason::TooLittle => tr!("relink.too_little"),
|
||||
Reason::NoRanges => tr!("relink.no_ranges"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Records what the server said.
|
||||
pub(crate) fn put_in(&self, task: &mut Task) {
|
||||
self.link.put_in(task);
|
||||
task.size = self.size.or(task.size);
|
||||
(task.etag, task.last_modified) = (self.version.etag.clone(), self.version.last_modified.clone());
|
||||
task.mime = self.mime.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares the task's finished bytes with the new link's. Reads the file only; the task may even be running.
|
||||
pub async fn check(client: &Client, task: &Task, parts: &[Part], link: NewLink, source: Source, stop: &mut Stop) -> Result<Checked> {
|
||||
let path = disk::partial_path(&task.folder, &task.name);
|
||||
let whole = runs(parts);
|
||||
let file = if whole.is_empty() { None } else { Some(open(&path).await?) };
|
||||
let (mut checked, opened) = probed(client, task, link, source, total(&whole), stop).await?;
|
||||
let Some((server, body)) = opened else { return Ok(checked) };
|
||||
let Some(file) = file else {
|
||||
checked.reason = Reason::Nothing;
|
||||
return Ok(checked);
|
||||
};
|
||||
let old = Validators { size: task.size, etag: task.etag.clone(), last_modified: task.last_modified.clone() };
|
||||
// Both at the same server, as far as is known.
|
||||
let same_server = url::Url::parse(&task.url).is_ok_and(|u| u.origin() == server.source.url.origin());
|
||||
let opinion = versions(&old, &server.version, same_server);
|
||||
if opinion == Opinion::Other {
|
||||
checked.reason = Reason::OtherVersion;
|
||||
return Ok(checked);
|
||||
}
|
||||
// More is here than it has.
|
||||
if let (Some(size), Some(last)) = (server.version.size, whole.last())
|
||||
&& last.end > size
|
||||
{
|
||||
checked.reason = Reason::Size { old: last.end, new: size };
|
||||
return Ok(checked);
|
||||
}
|
||||
if !server.ranges {
|
||||
let head = whole.first().filter(|r| r.start == 0).map(|r| r.end.min(ALL)).unwrap_or(0);
|
||||
let known = read(&file, 0..head).await?;
|
||||
let same = match body {
|
||||
Some(body) => same_body(body, &known, stop).await?,
|
||||
None => true,
|
||||
};
|
||||
checked.compared = head;
|
||||
checked.reason = if same { Reason::NoRanges } else { Reason::Bytes };
|
||||
return Ok(checked);
|
||||
}
|
||||
drop(body);
|
||||
for sample in samples(&whole) {
|
||||
let known = read(&file, sample.clone()).await?;
|
||||
checked.reason = match same_bytes(&server, &known, sample.start, stop).await {
|
||||
Ok(true) => {
|
||||
checked.compared += known.len() as u64;
|
||||
continue;
|
||||
}
|
||||
Ok(false) => Reason::Bytes,
|
||||
Err(Error::Changed) => Reason::OtherVersion,
|
||||
Err(Error::Page) => Reason::Page,
|
||||
Err(Error::RangeIgnored) => {
|
||||
checked.ranges = false;
|
||||
Reason::NoRanges
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
return Ok(checked);
|
||||
}
|
||||
checked.reason = match opinion {
|
||||
Opinion::Same => Reason::Version,
|
||||
_ if checked.compared < SAMPLE => Reason::TooLittle,
|
||||
_ => Reason::Samples,
|
||||
};
|
||||
Ok(checked)
|
||||
}
|
||||
|
||||
/// What the link leads to. Nothing to compare comes along when the verdict is clear already.
|
||||
pub(crate) async fn probed(
|
||||
client: &Client,
|
||||
task: &Task,
|
||||
link: NewLink,
|
||||
source: Source,
|
||||
here: u64,
|
||||
stop: &mut Stop,
|
||||
) -> Result<(Checked, Option<(Link, Option<http::Response>)>)> {
|
||||
let mut probe = probe(client, &source, stop).await?;
|
||||
let body = probe.body.take();
|
||||
let mut checked = Checked {
|
||||
link,
|
||||
reason: Reason::Nothing,
|
||||
here,
|
||||
compared: 0,
|
||||
ranges: probe.ranges,
|
||||
size: probe.version.size,
|
||||
name: probe.name.clone(),
|
||||
version: probe.version.clone(),
|
||||
mime: probe.mime.clone(),
|
||||
};
|
||||
let sizes = task.size.zip(probe.version.size).filter(|(old, new)| old != new && here > 0);
|
||||
if is_page(task, &source, &probe) {
|
||||
checked.reason = Reason::Page;
|
||||
return Ok((checked, None));
|
||||
}
|
||||
if let Some((old, new)) = sizes {
|
||||
checked.reason = Reason::Size { old, new };
|
||||
return Ok((checked, None));
|
||||
}
|
||||
let server = Link { client: client.clone(), source: source.at(&probe.url), ranges: probe.ranges, version: probe.version };
|
||||
Ok((checked, Some((server, body))))
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Opinion {
|
||||
Same,
|
||||
Other,
|
||||
None,
|
||||
}
|
||||
|
||||
/// What the servers' own versions say. Two servers may call the same file differently, one server does so only for a reason:
|
||||
/// but copies behind one name may have tags of their own, while their dates agree.
|
||||
fn versions(old: &Validators, new: &Validators, same_server: bool) -> Opinion {
|
||||
let tag = |v: &Validators| v.etag.as_ref().map(|t| t.trim_start_matches("W/").to_string());
|
||||
let tags = tag(old).zip(tag(new)).map(|(a, b)| a == b);
|
||||
let dates = old.last_modified.as_ref().zip(new.last_modified.as_ref()).map(|(a, b)| a == b);
|
||||
let sizes = old.size.is_some() && old.size == new.size;
|
||||
match (tags, dates) {
|
||||
(Some(true), _) | (None, Some(true)) if sizes => Opinion::Same,
|
||||
(Some(false), Some(true)) | (Some(true), _) => Opinion::None,
|
||||
(Some(false), _) | (None, Some(false)) if same_server => Opinion::Other,
|
||||
_ => Opinion::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The finished ranges, joined, in order.
|
||||
pub(crate) fn runs(parts: &[Part]) -> Vec<Range<u64>> {
|
||||
let mut all: Vec<_> = parts.iter().filter(|p| p.done > 0).map(|p| p.start..p.start + p.done).collect();
|
||||
all.sort_by_key(|r| r.start);
|
||||
let mut out: Vec<Range<u64>> = vec![];
|
||||
for r in all {
|
||||
match out.last_mut() {
|
||||
Some(last) if last.end >= r.start => last.end = last.end.max(r.end),
|
||||
_ => out.push(r),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn total(runs: &[Range<u64>]) -> u64 {
|
||||
runs.iter().map(|r| r.end - r.start).sum()
|
||||
}
|
||||
|
||||
/// Where to look: the last bytes of the finished ranges, the first ones of the file, and places in between.
|
||||
pub(crate) fn samples(runs: &[Range<u64>]) -> Vec<Range<u64>> {
|
||||
let total = total(runs);
|
||||
if total <= ALL {
|
||||
return runs.to_vec();
|
||||
}
|
||||
let mut out: Vec<_> = runs.iter().rev().take(ENDS).map(|r| r.end.saturating_sub(SAMPLE).max(r.start)..r.end).collect();
|
||||
out.extend(runs.first().map(|r| r.start..r.end.min(r.start + SAMPLE)));
|
||||
for i in 0..INNER {
|
||||
let step = total / INNER;
|
||||
let mut at = i * step + RandomState::new().hash_one(i) % step;
|
||||
for r in runs {
|
||||
let len = r.end - r.start;
|
||||
if at < len {
|
||||
let start = r.start + at;
|
||||
out.push(start..r.end.min(start + SAMPLE));
|
||||
break;
|
||||
}
|
||||
at -= len;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) async fn open(path: &Path) -> Result<Arc<File>> {
|
||||
let path = path.to_path_buf();
|
||||
let opened = disk::blocking(move || File::open(path)).await;
|
||||
opened.map(Arc::new).map_err(|e| if e.kind() == io::ErrorKind::NotFound { Error::Missing } else { disk::Error::Io(e).into() })
|
||||
}
|
||||
|
||||
pub(crate) async fn read(file: &Arc<File>, range: Range<u64>) -> Result<Vec<u8>> {
|
||||
let file = file.clone();
|
||||
let read = disk::blocking(move || {
|
||||
let mut buf = vec![0; (range.end - range.start) as usize];
|
||||
file.read_exact_at(&mut buf, range.start)?;
|
||||
Ok::<_, io::Error>(buf)
|
||||
});
|
||||
// Shorter than its record.
|
||||
read.await.map_err(|e| if e.kind() == io::ErrorKind::UnexpectedEof { Error::Missing } else { disk::Error::Io(e).into() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn part(start: u64, end: u64, done: u64) -> Part {
|
||||
Part { start, end: Some(end), done }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_are_joined() {
|
||||
assert_eq!(runs(&[part(50, 90, 10), part(0, 20, 20), part(20, 50, 5), part(90, 99, 0)]), [0..25, 50..60]);
|
||||
assert_eq!(runs(&[]), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn samples_hold_every_end_and_stay_inside() {
|
||||
for _ in 0..200 {
|
||||
let mut runs = vec![];
|
||||
let mut at = fastrand::u64(0..1000);
|
||||
for _ in 0..fastrand::usize(1..20) {
|
||||
let end = at + fastrand::u64(1..1_000_000);
|
||||
runs.push(at..end);
|
||||
at = end + fastrand::u64(1..1_000_000);
|
||||
}
|
||||
let samples = samples(&runs);
|
||||
assert!(samples.iter().all(|s| s.start < s.end && runs.iter().any(|r| r.start <= s.start && s.end <= r.end)));
|
||||
for r in &runs {
|
||||
assert!(samples.iter().any(|s| s.end == r.end && s.start <= r.end.saturating_sub(SAMPLE).max(r.start)), "{r:?}");
|
||||
}
|
||||
assert!(total(&samples) <= ALL + SAMPLE * (runs.len() as u64 + INNER));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_versions_say() {
|
||||
let v = |size, tag: &str, date: &str| {
|
||||
let text = |s: &str| Some(s.to_string()).filter(|s| !s.is_empty());
|
||||
Validators { size: Some(size), etag: text(tag), last_modified: text(date) }
|
||||
};
|
||||
let old = v(5, "\"a\"", "d");
|
||||
for (new, here, there) in [
|
||||
(v(5, "W/\"a\"", "x"), Opinion::Same, Opinion::Same),
|
||||
(v(5, "", "d"), Opinion::Same, Opinion::Same),
|
||||
(v(5, "\"b\"", "d"), Opinion::None, Opinion::None),
|
||||
(v(5, "\"b\"", ""), Opinion::Other, Opinion::None),
|
||||
(v(5, "\"b\"", "x"), Opinion::Other, Opinion::None),
|
||||
(v(5, "", "x"), Opinion::Other, Opinion::None),
|
||||
(v(5, "", ""), Opinion::None, Opinion::None),
|
||||
] {
|
||||
assert_eq!(versions(&old, &new, true), here, "{new:?}");
|
||||
assert_eq!(versions(&old, &new, false), there, "{new:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
1
crates/core/src/store/003.sql
Normal file
1
crates/core/src/store/003.sql
Normal file
|
|
@ -0,0 +1 @@
|
|||
ALTER TABLE tasks ADD COLUMN replaces INTEGER;
|
||||
|
|
@ -16,7 +16,7 @@ use std::thread::JoinHandle;
|
|||
use std::time::Duration;
|
||||
|
||||
/// Never edit one that shipped; add the next number.
|
||||
const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql")];
|
||||
const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql")];
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result<usize> {
|
|||
":checksum": t.checksum, ":max_parts": t.max_parts, ":speed_limit": t.speed_limit, ":headers": headers,
|
||||
":proxy": t.proxy, ":secret": t.secret, ":after": t.after, ":start_at": t.start_at, ":added_at": t.added_at,
|
||||
":finished_at": t.finished_at, ":removed_at": t.removed_at, ":notes": t.notes, ":tries": t.tries,
|
||||
":replaces": t.replaces,
|
||||
};
|
||||
Ok(c.execute(sql, columns)?)
|
||||
}
|
||||
|
|
@ -45,10 +46,10 @@ pub fn insert_task(c: &Connection, t: &Task) -> Result<TaskId> {
|
|||
c,
|
||||
"INSERT INTO tasks (url, mirrors, source_page, name, folder, state, queue, position, priority, size, downloaded, mime,
|
||||
etag, last_modified, checksum, max_parts, speed_limit, headers, proxy, secret, after, start_at, added_at,
|
||||
finished_at, removed_at, notes, tries)
|
||||
finished_at, removed_at, notes, tries, replaces)
|
||||
VALUES (:url, :mirrors, :source_page, :name, :folder, 'queued', :queue, :position, :priority, :size, :downloaded, :mime,
|
||||
:etag, :last_modified, :checksum, :max_parts, :speed_limit, :headers, :proxy, :secret, :after, :start_at, :added_at,
|
||||
:finished_at, :removed_at, :notes, :tries)",
|
||||
:finished_at, :removed_at, :notes, :tries, :replaces)",
|
||||
t,
|
||||
)?;
|
||||
let id = c.last_insert_rowid();
|
||||
|
|
@ -67,7 +68,7 @@ pub fn update_task(c: &Connection, t: &Task) -> Result<usize> {
|
|||
etag = :etag, last_modified = :last_modified, checksum = :checksum, max_parts = :max_parts,
|
||||
speed_limit = :speed_limit, headers = :headers, proxy = :proxy, secret = :secret, after = :after,
|
||||
start_at = :start_at, added_at = :added_at, finished_at = :finished_at, removed_at = :removed_at, notes = :notes,
|
||||
tries = :tries
|
||||
tries = :tries, replaces = :replaces
|
||||
WHERE id = {}",
|
||||
t.id
|
||||
);
|
||||
|
|
@ -126,6 +127,7 @@ fn task(r: &Row) -> Result<Task> {
|
|||
proxy: r.get("proxy")?,
|
||||
secret: r.get("secret")?,
|
||||
after: r.get("after")?,
|
||||
replaces: r.get("replaces")?,
|
||||
start_at: r.get("start_at")?,
|
||||
added_at: r.get("added_at")?,
|
||||
finished_at: r.get("finished_at")?,
|
||||
|
|
|
|||
438
crates/core/tests/relink.rs
Normal file
438
crates/core/tests/relink.rs
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
//! Downloads that go on from another link, and files that other programs left unfinished.
|
||||
|
||||
use medlar_core::adapt::Timing;
|
||||
use medlar_core::host::{Caps, Hosts};
|
||||
use medlar_core::http::{ClientOptions, Options, Shared, client};
|
||||
use medlar_core::manager::{Bin, Command, Config, Error, Manager};
|
||||
use medlar_core::model::*;
|
||||
use medlar_core::relink::{Checked, Incoming, NewLink, Reason, Strength, Verdict, find};
|
||||
use medlar_core::segment::Rules;
|
||||
use medlar_core::settings::Limits;
|
||||
use medlar_core::snapshot::TaskView;
|
||||
use medlar_core::store::Store;
|
||||
use medlar_testserver::{Faults, TestServer, expected};
|
||||
use std::os::unix::fs::FileExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::time::sleep;
|
||||
|
||||
const LIMITS: Limits = Limits { speed: 0, max_active: 8, max_connections: 32, parts_per_download: 4, connections_per_host: 16 };
|
||||
const LEN: usize = 2 << 20;
|
||||
|
||||
fn ms(n: u64) -> Duration {
|
||||
Duration::from_millis(n)
|
||||
}
|
||||
|
||||
fn open(dir: &Path) -> Manager {
|
||||
let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap());
|
||||
let client = client(&ClientOptions { idle_timeout: ms(2000), ..ClientOptions::default() }).unwrap();
|
||||
let hosts = Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() });
|
||||
let mut config = Config::new(Shared { client, store, hosts }, LIMITS);
|
||||
config.options = Options {
|
||||
rules: Rules { min: 64 * 1024, align: 4096, min_time: ms(50) },
|
||||
timing: Timing { settle: ms(100), window: ms(200), hold: ms(2000), refused: ms(60_000) },
|
||||
tick: ms(25),
|
||||
tries: 2,
|
||||
backoff: ms(20),
|
||||
checkpoint: ms(50),
|
||||
..Options::default()
|
||||
};
|
||||
(config.bin, config.tick) = (Bin::at(dir.join("Trash")), ms(20));
|
||||
Manager::open(config).unwrap()
|
||||
}
|
||||
|
||||
struct Bench {
|
||||
server: TestServer,
|
||||
dir: tempfile::TempDir,
|
||||
manager: Manager,
|
||||
files: PathBuf,
|
||||
}
|
||||
|
||||
impl Bench {
|
||||
async fn new() -> Bench {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
Bench { server: TestServer::start().await, files: dir.path().join("files"), manager: open(dir.path()), dir }
|
||||
}
|
||||
|
||||
fn restart(self) -> Bench {
|
||||
drop(self.manager);
|
||||
Bench { manager: open(self.dir.path()), ..self }
|
||||
}
|
||||
|
||||
fn view(&self, id: TaskId) -> Arc<TaskView> {
|
||||
self.manager.snapshot().get(id).unwrap_or_else(|| panic!("{id} is not in the list")).clone()
|
||||
}
|
||||
|
||||
async fn run(&self, command: Command) -> TaskId {
|
||||
self.manager.send(command).await.unwrap()
|
||||
}
|
||||
|
||||
async fn until(&self, id: TaskId, what: &str, is: impl Fn(&TaskView) -> bool) -> Arc<TaskView> {
|
||||
let end = Instant::now() + Duration::from_secs(40);
|
||||
loop {
|
||||
let view = self.view(id);
|
||||
if is(&view) {
|
||||
return view;
|
||||
}
|
||||
assert!(Instant::now() < end, "never {what}: {:?} {:?} {:#?}", view.state(), view.task.error, view.log);
|
||||
sleep(ms(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// About half of it is here, in several parts, and paused.
|
||||
async fn half(&self, path: &str) -> TaskId {
|
||||
let faults = path.split('?').next().unwrap();
|
||||
self.server.set_faults(faults, Faults { throttle_total: Some(1_500_000), ..Faults::default() });
|
||||
let task = Task {
|
||||
url: self.server.url(path),
|
||||
folder: self.files.clone(),
|
||||
headers: vec![("Referer".into(), "https://old.example/".into()), ("X-Old".into(), "1".into())],
|
||||
..Task::default()
|
||||
};
|
||||
let id = self.run(Command::Add(Box::new(task))).await;
|
||||
self.until(id, "half", |v| v.downloaded >= LEN as u64 / 2).await;
|
||||
self.run(Command::Pause(id)).await;
|
||||
self.until(id, "stopped", |v| v.connections == 0).await;
|
||||
self.server.clear_all_faults();
|
||||
self.server.clear_log();
|
||||
id
|
||||
}
|
||||
|
||||
async fn check(&self, id: TaskId, path: &str) -> Checked {
|
||||
self.manager.check(id, self.link(path)).await.unwrap()
|
||||
}
|
||||
|
||||
fn link(&self, path: &str) -> NewLink {
|
||||
NewLink { url: self.server.url(path), ..NewLink::default() }
|
||||
}
|
||||
|
||||
async fn go_on(&self, id: TaskId, checked: Checked) -> TaskId {
|
||||
self.run(Command::Continue { id, checked: Box::new(checked) }).await
|
||||
}
|
||||
|
||||
async fn done(&self, id: TaskId, seed: u64) {
|
||||
let view = self.until(id, "done", |v| v.state() == State::Done).await;
|
||||
let is = std::fs::read(view.task.folder.join(&view.task.name)).unwrap();
|
||||
assert!(is == expected(seed, 0, LEN), "{:#?}", view.log);
|
||||
}
|
||||
|
||||
/// Bytes of the body that a path gave.
|
||||
fn sent(&self, path: &str) -> u64 {
|
||||
self.server.requests_for(path).iter().map(|r| r.sent).sum()
|
||||
}
|
||||
|
||||
fn partial(&self, id: TaskId) -> PathBuf {
|
||||
let task = &self.view(id).task;
|
||||
task.folder.join(format!("{}.medlar", task.name))
|
||||
}
|
||||
}
|
||||
|
||||
fn path(seed: u64, name: &str) -> String {
|
||||
format!("/data/{seed}/{LEN}/{name}")
|
||||
}
|
||||
|
||||
/// Nobody tells versions apart.
|
||||
fn bare(path: String) -> String {
|
||||
path + "?etag=0&lm=0"
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_expired_link_waits_for_a_new_one_and_keeps_its_parts() {
|
||||
let b = Bench::new().await;
|
||||
let id = b.half(&path(1, "a.bin")).await;
|
||||
let had = b.view(id).downloaded;
|
||||
b.server.set_faults(&path(1, "a.bin"), Faults { expire_requests: Some(0), ..Faults::default() });
|
||||
b.run(Command::Resume(id)).await;
|
||||
let view = b.until(id, "expired", |v| v.state() == State::Failed).await;
|
||||
assert_eq!(view.task.error.as_ref().unwrap().kind, Some(ErrorKind::Expired));
|
||||
|
||||
b.run(Command::AwaitLink(id)).await;
|
||||
let b = b.restart();
|
||||
sleep(ms(300)).await;
|
||||
let view = b.view(id);
|
||||
assert_eq!((view.state(), view.task.error.as_ref().unwrap().kind), (State::Waiting, Some(ErrorKind::Link)));
|
||||
assert_eq!(view.downloaded, had);
|
||||
|
||||
let new = path(1, "a.bin") + "?token=new";
|
||||
let incoming = Incoming { url: b.server.url(&new), ..Incoming::default() };
|
||||
let shot = b.manager.snapshot();
|
||||
let found = find(&incoming, shot.iter().map(|v| &*v.task));
|
||||
assert_eq!((found.len(), found[0].id, found[0].strength, found[0].awaited), (1, id, Strength::Strong, true));
|
||||
|
||||
b.server.clear_all_faults();
|
||||
b.server.clear_log();
|
||||
let mut link = b.link(&new);
|
||||
link.headers = vec![("Referer".into(), "https://new.example/".into())];
|
||||
link.source_page = Some("https://new.example/page".into());
|
||||
let checked = b.manager.check(id, link).await.unwrap();
|
||||
assert_eq!((checked.verdict(), checked.reason, checked.here), (Verdict::Same, Reason::Version, had));
|
||||
assert!(checked.compared < 200_000 && !checked.text().is_empty());
|
||||
assert_eq!(b.view(id).task.url, b.server.url(&path(1, "a.bin")), "looking changes nothing");
|
||||
assert_eq!(b.go_on(id, checked).await, id);
|
||||
b.done(id, 1).await;
|
||||
let left = LEN as u64 - had;
|
||||
assert!(b.sent(&path(1, "a.bin")) < left + 600_000, "{} of {left}", b.sent(&path(1, "a.bin")));
|
||||
let task = b.view(id).task.clone();
|
||||
assert_eq!(task.source_page.as_deref(), Some("https://new.example/page"));
|
||||
assert_eq!(task.headers, [("Referer".to_string(), "https://new.example/".to_string())]);
|
||||
for r in b.server.log() {
|
||||
assert_eq!((r.header("referer"), r.header("x-old")), (Some("https://new.example/"), None));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_wait_for_a_link_ends_with_pause_and_resume() {
|
||||
let b = Bench::new().await;
|
||||
let id = b.half(&path(1, "a.bin")).await;
|
||||
b.run(Command::AwaitLink(id)).await;
|
||||
b.run(Command::Pause(id)).await;
|
||||
assert_eq!((b.view(id).state(), &b.view(id).task.error), (State::Paused, &None));
|
||||
b.run(Command::Resume(id)).await;
|
||||
b.until(id, "running", |v| v.connections > 0 || v.state() == State::Done).await;
|
||||
b.run(Command::AwaitLink(id)).await;
|
||||
if b.view(id).state() != State::Done {
|
||||
sleep(ms(200)).await;
|
||||
assert_eq!(b.view(id).state(), State::Waiting);
|
||||
b.run(Command::Resume(id)).await;
|
||||
}
|
||||
b.done(id, 1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn another_file_is_never_taken() {
|
||||
let b = Bench::new().await;
|
||||
let id = b.half(&bare(path(1, "a.bin"))).await;
|
||||
let before = b.view(id).task.clone();
|
||||
let other = TestServer::data_path(1, LEN as u64 + 1);
|
||||
for (path, reason) in [
|
||||
// The same size, other bytes.
|
||||
(bare(path(2, "a.bin")), Reason::Bytes),
|
||||
(path(2, "a.bin"), Reason::Bytes),
|
||||
(other, Reason::Size { old: LEN as u64, new: LEN as u64 + 1 }),
|
||||
("/site/".into(), Reason::Page),
|
||||
] {
|
||||
let checked = b.check(id, &path).await;
|
||||
assert_eq!((checked.verdict(), checked.reason), (Verdict::Different, reason), "{path}");
|
||||
let refused = b.manager.send(Command::Continue { id, checked: Box::new(checked) }).await;
|
||||
assert!(matches!(refused, Err(Error::Different)));
|
||||
let after = b.view(id).task.clone();
|
||||
assert_eq!((&after.url, after.downloaded, after.state), (&before.url, before.downloaded, State::Paused));
|
||||
}
|
||||
b.run(Command::Resume(id)).await;
|
||||
b.done(id, 1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn swapped_on_the_same_server() {
|
||||
let b = Bench::new().await;
|
||||
let id = b.half(&path(1, "a.bin")).await;
|
||||
b.server.set_faults(&path(1, "a.bin"), Faults { version_after_requests: Some(0), ..Faults::default() });
|
||||
let checked = b.check(id, &(path(1, "a.bin") + "?token=2")).await;
|
||||
assert_eq!((checked.verdict(), checked.reason), (Verdict::Different, Reason::OtherVersion));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn without_versions_the_bytes_decide() {
|
||||
let b = Bench::new().await;
|
||||
let id = b.half(&bare(path(1, "a.bin"))).await;
|
||||
let checked = b.check(id, &bare(path(1, "b.bin"))).await;
|
||||
assert_eq!((checked.verdict(), checked.reason), (Verdict::ProbablySame, Reason::Samples));
|
||||
b.go_on(id, checked).await;
|
||||
b.done(id, 1).await;
|
||||
assert_eq!(b.view(id).task.name, "a.bin");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_last_finished_byte_counts() {
|
||||
let b = Bench::new().await;
|
||||
let id = b.half(&bare(path(1, "a.bin"))).await;
|
||||
for part in b.view(id).parts.iter().filter(|p| p.done > 0) {
|
||||
let file = std::fs::OpenOptions::new().read(true).write(true).open(b.partial(id)).unwrap();
|
||||
let (at, mut byte) = (part.start + part.done - 1, [0]);
|
||||
file.read_exact_at(&mut byte, at).unwrap();
|
||||
file.write_all_at(&[!byte[0]], at).unwrap();
|
||||
// Ends that another finished range goes on from are inside of one.
|
||||
let end = !b.view(id).parts.iter().any(|p| p.done > 0 && p.start == at + 1);
|
||||
if end {
|
||||
assert_eq!(b.check(id, &bare(path(1, "b.bin"))).await.reason, Reason::Bytes);
|
||||
}
|
||||
file.write_all_at(&byte, at).unwrap();
|
||||
}
|
||||
assert_eq!(b.check(id, &bare(path(1, "b.bin"))).await.reason, Reason::Samples);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn without_ranges_it_starts_over_and_keeps_the_old_one_until_then() {
|
||||
let b = Bench::new().await;
|
||||
let id = b.half(&path(1, "a.bin")).await;
|
||||
let had = b.view(id).downloaded;
|
||||
let whole = Faults { ignore_range: true, ..Faults::default() };
|
||||
b.server.set_faults(&path(2, "n.bin"), whole.clone());
|
||||
assert_eq!(b.check(id, &path(2, "n.bin")).await.reason, Reason::Bytes);
|
||||
b.server.set_faults(&path(1, "n.bin"), Faults { throttle_conn: Some(3_000_000), ..whole });
|
||||
let checked = b.check(id, &path(1, "n.bin")).await;
|
||||
assert_eq!((checked.verdict(), checked.reason, checked.starts_over()), (Verdict::CannotTell, Reason::NoRanges, true));
|
||||
let new = b.go_on(id, checked).await;
|
||||
assert_ne!(new, id);
|
||||
b.until(new, "under way", |v| v.downloaded > 0 && v.state() == State::Running).await;
|
||||
let old = b.view(id);
|
||||
assert_eq!((old.downloaded, old.state()), (had, State::Paused));
|
||||
assert!(b.partial(id).exists());
|
||||
assert_eq!(b.view(new).task.name, "a.bin");
|
||||
let b = b.restart();
|
||||
b.done(new, 1).await;
|
||||
let end = Instant::now() + Duration::from_secs(10);
|
||||
while b.manager.snapshot().get(id).is_some() {
|
||||
assert!(Instant::now() < end);
|
||||
sleep(ms(5)).await;
|
||||
}
|
||||
sleep(ms(300)).await;
|
||||
let names: Vec<_> = std::fs::read_dir(&b.files).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert_eq!(names, ["a.bin"]);
|
||||
b.run(Command::Restore(id)).await;
|
||||
assert!(b.partial(id).exists(), "it went to the bin");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn links_that_fail_and_downloads_with_nothing_yet() {
|
||||
let b = Bench::new().await;
|
||||
let id = b.half(&path(1, "a.bin")).await;
|
||||
b.server.set_faults(&path(1, "b.bin"), Faults::status(404));
|
||||
for (link, kind) in [(b.link(&path(1, "b.bin")), ErrorKind::NotFound), (NewLink { url: "no link".into(), ..NewLink::default() }, ErrorKind::BadLink)] {
|
||||
let Err(Error::Link(failure)) = b.manager.check(id, link).await else { panic!("{kind:?}") };
|
||||
assert_eq!(failure.kind, kind);
|
||||
}
|
||||
std::fs::remove_file(b.partial(id)).unwrap();
|
||||
let Err(Error::Link(failure)) = b.manager.check(id, b.link(&path(1, "c.bin"))).await else { panic!() };
|
||||
assert_eq!(failure.kind, ErrorKind::FileGone);
|
||||
|
||||
// Nothing here: whatever it is now, it is what the user wants.
|
||||
b.server.set_faults(&path(3, "x.bin"), Faults::status(404));
|
||||
let task = Task { url: b.server.url(&path(3, "x.bin")), folder: b.files.clone(), ..Task::default() };
|
||||
let id = b.run(Command::Add(Box::new(task))).await;
|
||||
b.until(id, "failed", |v| v.state() == State::Failed).await;
|
||||
let checked = b.check(id, &path(2, "x.bin")).await;
|
||||
assert_eq!((checked.verdict(), checked.starts_over()), (Verdict::CannotTell, false));
|
||||
b.go_on(id, checked).await;
|
||||
b.done(id, 2).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_running_one_changes_over() {
|
||||
let b = Bench::new().await;
|
||||
let id = b.half(&path(1, "a.bin")).await;
|
||||
b.server.set_faults(&path(1, "a.bin"), Faults { throttle_total: Some(100_000), ..Faults::default() });
|
||||
b.run(Command::Resume(id)).await;
|
||||
b.until(id, "running", |v| v.connections > 0).await;
|
||||
let checked = b.check(id, &path(1, "b.bin")).await;
|
||||
assert_eq!(checked.verdict(), Verdict::Same);
|
||||
b.go_on(id, checked).await;
|
||||
b.done(id, 1).await;
|
||||
assert!(b.sent(&path(1, "b.bin")) > 500_000);
|
||||
}
|
||||
|
||||
// Files of other programs.
|
||||
|
||||
impl Bench {
|
||||
fn left(&self, name: &str, bytes: &[u8]) -> PathBuf {
|
||||
let path = self.dir.path().join(name);
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
async fn adopt(&self, file: &Path, link: &str) -> (Reason, u64, Result<TaskId, Error>) {
|
||||
let found = self.manager.check_partial(file.into(), self.link(link)).await.unwrap();
|
||||
let (reason, bytes) = (found.checked.reason, found.partial.bytes());
|
||||
let name = found.partial.name.clone().unwrap_or_default();
|
||||
let task = Task { name, folder: self.files.clone(), ..Task::default() };
|
||||
(reason, bytes, self.manager.send(Command::Adopt { task: Box::new(task), found: Box::new(found) }).await)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn goes_on_from_a_browsers_file() {
|
||||
let b = Bench::new().await;
|
||||
let data = expected(1, 0, LEN);
|
||||
let half = LEN / 2 + 123;
|
||||
for (i, file) in ["a.bin.part", "a.bin.crdownload"].into_iter().enumerate() {
|
||||
let left = b.left(file, &data[..half]);
|
||||
let path = path(1, &format!("{i}.bin"));
|
||||
let (reason, bytes, id) = b.adopt(&left, &path).await;
|
||||
assert_eq!((reason, bytes), (Reason::Samples, half as u64));
|
||||
let id = id.unwrap();
|
||||
b.done(id, 1).await;
|
||||
assert!(b.sent(&path) < (LEN - half) as u64 + 600_000);
|
||||
assert_eq!(std::fs::read(&left).unwrap(), data[..half], "the browser's file stays");
|
||||
assert_eq!(b.view(id).task.name, ["a.bin", "a (1).bin"][i]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn space_taken_beforehand_is_no_data() {
|
||||
let b = Bench::new().await;
|
||||
let mut data = expected(1, 0, LEN);
|
||||
data[LEN / 2..].fill(0);
|
||||
let (reason, bytes, id) = b.adopt(&b.left("a.bin", &data), &path(1, "a.bin")).await;
|
||||
assert!(reason == Reason::Samples && bytes <= LEN as u64 / 2 && bytes > LEN as u64 / 2 - 4096, "{reason:?} {bytes}");
|
||||
b.done(id.unwrap(), 1).await;
|
||||
|
||||
// Filled with something else.
|
||||
data[LEN / 2..].fill(7);
|
||||
let (reason, bytes, id) = b.adopt(&b.left("b.bin", &data), &path(1, "b.bin")).await;
|
||||
assert!(reason == Reason::Samples && bytes <= LEN as u64 / 2, "{reason:?} {bytes}");
|
||||
b.done(id.unwrap(), 1).await;
|
||||
|
||||
// A hole in the middle, as a program with several parts leaves it.
|
||||
let mut data = expected(1, 0, LEN);
|
||||
data[400_000..600_000].fill(0);
|
||||
let (_, bytes, id) = b.adopt(&b.left("c.bin", &data), &path(1, "c.bin")).await;
|
||||
assert!(bytes <= 404_096, "{bytes}");
|
||||
b.done(id.unwrap(), 1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn goes_on_from_aria2s_list() {
|
||||
let b = Bench::new().await;
|
||||
let mut data = expected(1, 0, LEN);
|
||||
let piece = 1 << 18;
|
||||
// Pieces 0, 3 and 4 of 8.
|
||||
for p in [1, 2, 5, 6, 7] {
|
||||
data[p * piece..(p + 1) * piece].fill(0);
|
||||
}
|
||||
let file = b.left("a.bin", &data);
|
||||
let mut list = vec![0, 1, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
list.extend((piece as u32).to_be_bytes());
|
||||
list.extend((LEN as u64).to_be_bytes());
|
||||
list.extend([0; 8]);
|
||||
list.extend([0, 0, 0, 1, 0b1001_1000, 0, 0, 0, 0]);
|
||||
b.left("a.bin.aria2", &list);
|
||||
let (reason, bytes, id) = b.adopt(&file, &path(1, "a.bin")).await;
|
||||
assert_eq!((reason, bytes), (Reason::Samples, 3 * piece as u64));
|
||||
b.done(id.unwrap(), 1).await;
|
||||
// The list is not true.
|
||||
data[4 * piece..5 * piece].fill(1);
|
||||
let file = b.left("a.bin", &data);
|
||||
let (reason, _, id) = b.adopt(&file, &path(1, "b.bin")).await;
|
||||
assert!(reason == Reason::Bytes && matches!(id, Err(Error::Different)));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn what_can_not_be_taken_over() {
|
||||
let b = Bench::new().await;
|
||||
let file = b.left("a.bin.part", &expected(1, 0, LEN / 2));
|
||||
let (reason, _, id) = b.adopt(&file, &path(2, "a.bin")).await;
|
||||
assert!(reason == Reason::Bytes && matches!(id, Err(Error::Different)));
|
||||
b.server.set_faults(&path(1, "n.bin"), Faults { ignore_range: true, ..Faults::default() });
|
||||
let (reason, _, id) = b.adopt(&file, &path(1, "n.bin")).await;
|
||||
assert!(reason == Reason::NoRanges && matches!(id, Err(Error::Partial(_))));
|
||||
let (reason, _, id) = b.adopt(&file, "/data/1/1000/a.bin").await;
|
||||
assert!(matches!(reason, Reason::Size { .. }) && matches!(id, Err(Error::Different)));
|
||||
let found = b.manager.check_partial(file.clone(), b.link(&path(1, "a.bin"))).await.unwrap();
|
||||
// It shrinks in the meantime.
|
||||
std::fs::write(&file, "x").unwrap();
|
||||
let task = Task { folder: b.files.clone(), ..Task::default() };
|
||||
assert!(b.manager.send(Command::Adopt { task: Box::new(task), found: Box::new(found) }).await.is_err());
|
||||
assert_eq!(b.manager.snapshot().iter().count(), 0);
|
||||
assert_eq!(std::fs::read_dir(&b.files).unwrap().count(), 0);
|
||||
}
|
||||
|
|
@ -29,6 +29,7 @@ Title and text: `error.<kind>` and `error.<kind>.why` in the catalogue; button:
|
|||
| `login` | Login needed | blocked | no | Sign in (`sign_in`) |
|
||||
| `forbidden` | Access denied | blocked | no | Get new link (`new_link`) |
|
||||
| `expired` | Link expired | blocked | no | Get new link (`new_link`) |
|
||||
| `link` | Waiting for a new link | blocked | no | Get new link (`new_link`) |
|
||||
| `wrong_content` | Not the file | blocked | no | Get new link (`new_link`) |
|
||||
| `not_found` | File not found | blocked | no | Edit link (`edit_link`) |
|
||||
| `rejected` | Request rejected | blocked | no | Edit link (`edit_link`) |
|
||||
|
|
|
|||
Loading…
Reference in a new issue