misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
A file numbered to avoid a clash shows and opens under its real name (#442) (#456)
Ahmed Nefzaouic0f5603c464e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7e959d04..dd535434 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- A download saved under a numbered name because another file already had its name (`master (1).mp4`) now shows that name in the list and opens its own file, instead of keeping the old name and opening the other file ([#442](https://github.com/anefzaoui/misterdownloadmanager/issues/442)). Two downloads waiting under one name no longer collide when they start: the later one takes the next free name, instead of failing with "already being downloaded" or continuing the other one's data.- A link sent from the browser no longer fails with 403 on sites whose bot check refuses a browser's User-Agent on a connection that isn't a browser's: MDM asks once more with its own, as Add URL does ([#372](https://github.com/anefzaoui/misterdownloadmanager/issues/372)).- The video download button moves to a free corner instead of covering a control of the page, such as a thumbnail's watch-later button ([#421](https://github.com/anefzaoui/misterdownloadmanager/issues/421)). Dragging it still puts it where you want it.- Crash reports: no report any more when one of the download engine's background tasks panics while MDM is already closing ([#422](https://github.com/anefzaoui/misterdownloadmanager/issues/422)).diff --git a/ROADMAP.md b/ROADMAP.mdindex 1b93fa5c..b59b4f33 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -504,6 +504,8 @@ These ship in a later version, when they're ready.### Bugs being looked into+- π A file renamed to avoid a clash still showing and opening under its old name+ ([#442](https://github.com/anefzaoui/misterdownloadmanager/issues/442)): fix in review- π RSS feeds: the rule boxes losing the keyboard after each key([#353](https://github.com/anefzaoui/misterdownloadmanager/issues/353)): fix in review- π Video progress at 100 % while still downloading, and long encoded strings as file namesdiff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex 6dee2d2e..9a0effd5 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -264,6 +264,50 @@ fn take_place(item: &mut Item, target: PathBuf) {item.dest = target;}+/// The place a download about to start takes instead of its own, when its own belongs to+/// another row (#442): two can wait under one name (nothing was on the disk when each was added,+/// and they can start in the same moment, before the engine has reserved anything). None: it+/// stays. A row with data of its own never moves, so a resume finds its pieces.+fn place_to_take(item: &Item, items: &[Item]) -> Option<PathBuf> {+ if item.downloaded > 0 || item.owns_resume_state() {+ return None;+ }+ let dir = item.dest.parent()?;+ let others = || {+ items+ .iter()+ .filter(|o| o.id != item.id && o.dest.parent() == Some(dir))+ };+ let lower = |p: &std::path::Path| p.to_string_lossy().to_lowercase();+ let stem = |o: &Item| {+ o.dest+ .file_stem()+ .map(|s| s.to_string_lossy().to_lowercase())+ };+ if item.video.is_some() {+ // yt-dlp takes any `<stem>.*` there as its own (#32): the stem has to be free.+ others()+ .any(|o| stem(o) == stem(item) && o.holds_place())+ .then(|| {+ mdm_engine::naming::stem_destination(dir, &item.file_name, |s| {+ let s = s.to_lowercase();+ others().any(|o| stem(o).as_ref() == Some(&s) && o.holds_place())+ })+ })+ } else {+ others()+ .any(|o| lower(&o.dest) == lower(&item.dest) && o.holds_place())+ .then(|| {+ let mut taken: std::collections::HashSet<PathBuf> = others()+ .filter(|o| o.holds_place())+ .map(|o| o.dest.clone())+ .collect();+ taken.insert(item.dest.clone());+ place_in(dir, &item.file_name, &mut taken)+ })+ }+}+/// The status strip's height, under the list and the Categories pane.const STRIP_H: f32 = 22.0;@@ -2386,6 +2430,22 @@ impl App {RequestParts { headers, opts }}+ /// Before a download starts: into a free place of its own if its own is another row's+ /// (`place_to_take`). The name stays the address's guess if it was one.+ fn claim_place(&mut self, id: u64) {+ let target = self+ .items+ .iter()+ .find(|i| i.id == id)+ .and_then(|i| place_to_take(i, &self.items));+ if let (Some(target), Some(item)) = (target, self.item(id)) {+ let guessed = item.name_from_url;+ take_place(item, target);+ item.name_from_url = guessed;+ self.dirty = true;+ }+ }+/// Start or resume a download; `show` opens its progress dialog (IDM's default).fn start(&mut self, id: u64, show: bool) {self.stopped_by_hand.remove(&id);@@ -2457,6 +2517,7 @@ impl App {// The file's own remembered limit, else the Speed Limiter's.opts.speed_limit = own_limit.or(self.settings.speed_limit());opts.checksum = checksum;+ self.claim_place(id);let Some(item) = self.item(id) else { return };let _guard = rt.enter();// Resume whenever there is something to resume. If that fails, say why and keep the@@ -3314,6 +3375,7 @@ impl App {/// Start a video item: yt-dlp (installed and verified) downloads it.fn start_video(&mut self, id: u64, show: bool) {+ self.claim_place(id);let tools = mdm_tools::tools_dir();let tool = tools.as_deref().and_then(mdm_tools::installed);let ffmpeg = tools.as_deref().and_then(mdm_tools::ffmpeg::installed);@@ -8699,6 +8761,93 @@ mod move_many_tests {}}+#[cfg(test)]+mod same_name_tests {+ use super::{Item, place_to_take};+ use crate::model::{Category, Status};+ use std::path::Path;++ fn row(id: u64, dest: &Path, status: Status, downloaded: u64) -> Item {+ let url = format!("http://files.test/{id}/master.mp4")+ .parse()+ .unwrap();+ let mut i = Item::new(id, url, dest.to_owned(), Category::Video);+ i.status = status;+ i.downloaded = downloaded;+ i+ }++ fn name(p: Option<std::path::PathBuf>) -> Option<String> {+ p.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())+ }++ /// #442: of two rows waiting under one name the first to start keeps it; the other goes to+ /// the next free one, not to the same file. A row with its own data never moves.+ #[test]+ fn a_row_leaves_a_name_another_row_holds() {+ let dir = tempfile::tempdir().unwrap();+ let at = dir.path().join("master.mp4");+ let waiting = |id| row(id, &at, Status::Queued, 0);+ let free = Some("master (1).mp4");++ // Both only waiting: nobody has it yet, the one starting stays.+ let items = [waiting(1), waiting(2)];+ assert_eq!(place_to_take(&items[0], &items), None);++ // The other is part-way (its pieces and resume state are at that name).+ let items = [row(1, &at, Status::Stopped, 500), waiting(2)];+ assert_eq!(name(place_to_take(&items[1], &items)).as_deref(), free);+ // And the part-way one resumes where it is, whoever else waits for the name.+ assert_eq!(place_to_take(&items[0], &items), None);++ // The other finished, its file there.+ std::fs::write(&at, b"x").unwrap();+ let items = [row(1, &at, Status::Complete, 1), waiting(2)];+ assert_eq!(name(place_to_take(&items[1], &items)).as_deref(), free);+ // Finished, but its file is gone: the name is free again.+ std::fs::remove_file(&at).unwrap();+ assert_eq!(place_to_take(&items[1], &items), None);++ // A crash left the list's count at nothing, but the resume state says whose the pieces+ // are: that row stays and resumes, the other leaves.+ let state = mdm_engine::state::state_path(&at);+ let mut items = [waiting(1), waiting(2)];+ let url = items[0].url.clone();+ mdm_engine::state::ResumeState::new(url.clone(), url, at.clone(), 9, Default::default())+ .write(&state)+ .unwrap();+ assert_eq!(place_to_take(&items[0], &items), None);+ assert_eq!(name(place_to_take(&items[1], &items)).as_deref(), free);+ items[0].status = Status::Stopped;+ assert_eq!(name(place_to_take(&items[1], &items)).as_deref(), free);+ std::fs::remove_file(&state).unwrap();++ // Another folder's row of that name is no clash.+ let other = tempfile::tempdir().unwrap();+ let there = other.path().join("master.mp4");+ let items = [row(1, &there, Status::Stopped, 5), waiting(2)];+ assert_eq!(place_to_take(&items[1], &items), None);+ }++ /// A video's stem has to be free whatever the extension: yt-dlp would take another file of+ /// that stem for its own and call the video downloaded.+ #[test]+ fn a_video_leaves_a_stem_another_row_holds() {+ let dir = tempfile::tempdir().unwrap();+ let d = dir.path();+ let mut video = row(2, &d.join("master.mp4"), Status::Queued, 0);+ video.video = Some(crate::model::VideoSpec {+ selector: "b".into(),+ subs: Default::default(),+ });+ let items = [row(1, &d.join("Master.webm"), Status::Stopped, 9), video];+ assert_eq!(+ name(place_to_take(&items[1], &items)).as_deref(),+ Some("master (1).mp4")+ );+ }+}+#[cfg(test)]mod at_login_tests {use super::{AtLogin, TRAY_GRACE, at_login};diff --git a/crates/app/src/model.rs b/crates/app/src/model.rsindex fac6d7e6..3e0dc8ae 100644--- a/crates/app/src/model.rs+++ b/crates/app/src/model.rs@@ -704,6 +704,25 @@ impl Item {notices: Vec::new(),}}+ /// This row's resume state is at its place. `downloaded` can't say: after a crash the list+ /// holds what it held at its last save, often nothing.+ pub fn owns_resume_state(&self) -> bool {+ let state = mdm_engine::state::state_path(&self.dest);+ mdm_engine::state::ResumeState::load(&state).is_ok_and(|s| s.url == self.url)+ }++ /// Whether this row has its place on the disk: running, part-way (its pieces and resume+ /// state are there), or finished with the file still there. A row not started yet holds+ /// nothing: several may wait under one name, and the first to start keeps it.+ pub fn holds_place(&self) -> bool {+ self.live.is_some()+ || if self.status == Status::Complete {+ self.dest.exists()+ } else {+ self.downloaded > 0 || self.owns_resume_state()+ }+ }+/// Pull the engine's snapshot into the row. Returns true when the download just ended.pub fn poll(&mut self) -> bool {let Some(live) = &mut self.live else {diff --git a/crates/app/src/store.rs b/crates/app/src/store.rsindex 95ad449f..085c2fb1 100644--- a/crates/app/src/store.rs+++ b/crates/app/src/store.rs@@ -134,6 +134,8 @@ fn load_from(p: &Path, empty: Loaded) -> Loaded {if i.status != Status::Complete&& i.video.is_none()&& let Ok(st) = ResumeState::load(&state_path(&i.dest))+ // A state under this name for another address is another row's (#442).+ && st.url == i.url{i.downloaded = st.downloaded();i.size = Some(st.size);@@ -546,6 +548,35 @@ mod tests {assert_eq!(load_from(&p, empty()).settings.auto_types, edited);}+ /// #442: two rows of one name, a resume state on the disk: only the row of its address+ /// takes the progress (the other would take the data for its own and resume it).+ #[test]+ fn a_resume_state_is_read_by_the_row_it_belongs_to() {+ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("downloads.json");+ let dest = dir.path().join("master.mp4");+ let url = "http://files.test/a/master.mp4";+ let row = |id: u64, url: &str| {+ serde_json::json!({+ "id": id, "url": url, "file_name": "master.mp4", "dest": dest, "size": 100,+ "downloaded": 0, "status": "Queued", "category": "Video", "description": "",+ "last_try": null, "error": null, "resumable": null,+ })+ };+ let list = serde_json::json!({+ "next_id": 3, "version": 2,+ "items": [row(1, url), row(2, "http://files.test/b/master.mp4")],+ });+ std::fs::write(&p, list.to_string()).unwrap();+ let (a, b): (url::Url, url::Url) = (url.parse().unwrap(), url.parse().unwrap());+ ResumeState::new(a, b, dest.clone(), 777, Default::default())+ .write(&state_path(&dest))+ .unwrap();+ let loaded = load_from(&p, empty());+ assert_eq!(loaded.items[0].size, Some(777));+ assert_eq!(loaded.items[1].size, Some(100));+ }+#[test]fn old_lists_get_four_files_at_once() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rsindex 385be0f1..7361d3ad 100644--- a/crates/engine/src/download.rs+++ b/crates/engine/src/download.rs@@ -1492,7 +1492,12 @@ async fn run(});let mut v = shared.view.lock().unwrap();v.state = match &result {- Ok(_) => State::Done,+ Ok(o) => {+ // Where it really is: `finish` numbers the name when another file took it meanwhile,+ // and whoever reads the view (the app's row) goes by this.+ v.file = Some(o.path.clone());+ State::Done+ }Err(Error::Cancelled) => State::Cancelled,Err(e) => {v.error = Some(e.to_string());diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rsindex 2267280b..51369be6 100644--- a/crates/engine/tests/e2e.rs+++ b/crates/engine/tests/e2e.rs@@ -770,6 +770,79 @@ fn on_disk(range: Option<&str>, saved: &mdm_engine::state::ResumeState) -> u64 {(to - from) - to_fetch}+/// Watch `dl` to its end: the file its view last named, and the path it reports. The view is what+/// the app's row follows.+async fn view_and_outcome(dl: Download) -> (Option<std::path::PathBuf>, std::path::PathBuf) {+ let until = std::time::Instant::now() + SETTLE;+ let file = loop {+ let v = dl.snapshot();+ if v.state == mdm_engine::download::State::Done {+ break v.file;+ }+ assert!(+ !matches!(+ v.state,+ mdm_engine::download::State::Failed | mdm_engine::download::State::Cancelled+ ),+ "{:?}",+ v.error+ );+ assert!(std::time::Instant::now() < until, "no end: {:?}", v.state);+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;+ };+ (file, dl.wait().await.unwrap().path)+}++/// #442: a file took the destination while the download ran, so it was saved under the next+/// number. The view says that name (the row used to keep the old one and open the other file).+#[tokio::test]+async fn the_view_names_the_file_when_its_place_was_taken_meanwhile() {+ // Several connections, and one connection on a server that refuses ranges.+ for query in ["seed=11&rate=4M", "seed=12&rate=4M&no_range=true"] {+ let s = server("").await;+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("master.mp4");+ let dl = Download::start(+ Request {+ url: s+ .url(&format!("/gen/2M/master.mp4?{query}"))+ .parse()+ .unwrap(),+ headers: Default::default(),+ dest: Destination::File(dest.clone()),+ },+ fast_opts(),+ );+ // Another program's file, once the download is under way.+ while dl.snapshot().file.is_none() {+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;+ }+ std::fs::write(&dest, b"someone else's").unwrap();+ let (file, path) = view_and_outcome(dl).await;+ assert_eq!(path, dir.path().join("master (1).mp4"), "{query}");+ assert_eq!(file.as_deref(), Some(path.as_path()), "{query}");+ assert_eq!(std::fs::read(&dest).unwrap(), b"someone else's");+ }+}++/// The same for a resumed download: the row follows, and the resume itself still works.+#[tokio::test]+async fn the_view_names_the_file_when_a_resume_finds_its_place_taken() {+ let s = server("rate=1M").await;+ let (dir, state) = paused(&s, "/gen/8M/master.mp4?seed=13").await;+ let dest = mdm_engine::state::ResumeState::load(&state).unwrap().dest;+ std::fs::write(&dest, b"someone else's").unwrap();+ s.set_faults(Faults::default());+ let dl = Download::resume(state.clone(), Default::default(), fast_opts()).unwrap();+ let (file, path) = view_and_outcome(dl).await;+ assert_eq!(path.parent(), Some(dir.path()));+ assert_ne!(path, dest);+ assert_eq!(file.as_deref(), Some(path.as_path()));+ assert_eq!(std::fs::metadata(&path).unwrap().len(), 8 << 20);+ assert!(!state.exists(), "state file removed on completion");+ assert_eq!(std::fs::read(&dest).unwrap(), b"someone else's");+}+#[tokio::test]async fn pause_and_resume_continues_where_it_stopped() {let s = server("rate=1M").await;