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
Add torrent: a magnet handed over while it is open waits its turn (#507) (#528)
Ahmed Nefzaouibe90912b9fdd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 26e7dfbb..055ceffb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see- Windows: video and gallery look-ups no longer fail with "[WinError 448] The path cannot be traversed because it contains an untrusted mount point" when a folder on PATH goes through a junction Windows won't let yt-dlp cross (one an app installed for itself, Codex's for example): yt-dlp, gallery-dl and the ffmpeg they start get that folder's real place instead, and no folder that can't be opened ([#508](https://github.com/anefzaoui/misterdownloadmanager/issues/508)).- **Download video** from Dailymotion's player embedded in another site: the look-up no longer sends that site as the Referer, which Dailymotion refused with 403, so its formats are found as with the video's own address ([#359](https://github.com/anefzaoui/misterdownloadmanager/issues/359)).- The video button fades again after a click on the player, in fullscreen too, and stays while you use the keyboard ([#480](https://github.com/anefzaoui/misterdownloadmanager/issues/480)).+- A magnet link or a .torrent handed to MDM while **Add torrent** is already open is no longer dropped without a word: it waits, and Add torrent opens again for it when you close the first ([#507](https://github.com/anefzaoui/misterdownloadmanager/issues/507)).- The window no longer freezes when a video or a gallery finishes: marking its files as downloaded from the web, which can wait on the disk and the antivirus for a while with a big video, now happens beside the window ([#510](https://github.com/anefzaoui/misterdownloadmanager/issues/510)).- Linux: **View → Dark Mode support** turns dark on window managers such as Hyprland and sway when only GNOME's setting says so (`gsettings set org.gnome.desktop.interface color-scheme prefer-dark`), as it did when a desktop portal answered ([#324](https://github.com/anefzaoui/misterdownloadmanager/issues/324)).- Dark mode no longer draws a bright white line under the menu bar, across the whole window, in the Classic and Native themes ([#379](https://github.com/anefzaoui/misterdownloadmanager/issues/379)).diff --git a/ROADMAP.md b/ROADMAP.mdindex 24a6eafb..eafbffc3 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -535,6 +535,8 @@ These ship in a later version, when they're ready.- 🔄 Dailymotion's embedded player from the browser's button: no formats, the embedding site'sReferer refused ([#359](https://github.com/anefzaoui/misterdownloadmanager/issues/359)): fix in review- 🔄 The video button staying on screen after a click on the player, in fullscreen too\n ([#480](https://github.com/anefzaoui/misterdownloadmanager/issues/480)): fix in review+- 🔄 A magnet link handed over while Add torrent is already open being dropped without a word+ ([#507](https://github.com/anefzaoui/misterdownloadmanager/issues/507)): fix in review- 🔄 A freeze when a video finishes, while its file is marked as downloaded from the web([#510](https://github.com/anefzaoui/misterdownloadmanager/issues/510)): fix in review- 🔄 Linux: Dark Mode support on window managers such as Hyprland and sway, which often have nodiff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex 1659a811..5f098715 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -508,6 +508,11 @@ pub struct App {/// Download a gallery (#58).gallery_dlg: Option<crate::gallerydlg::GalleryDialog>,torrent_dlg: Option<crate::torrentdlg::TorrentDialog>,+ /// Magnet links and .torrents handed over while Add torrent was open (#507), oldest first:+ /// each opens in Add torrent when the one before it closes.+ torrent_waiting: std::collections::VecDeque<(String, Option<crate::torrents::Remote>)>,+ /// Add torrent closed this frame: the next waiting one opens after a frame without it.+ torrent_closed: bool,torrent_settings: Option<crate::torrentdlg::TorrentSettings>,/// Right-click → Torrent → Add trackers… (#39).add_trackers: Option<crate::torrentdlg::AddTrackers>,@@ -1118,6 +1123,8 @@ impl App {video_dlg: None,gallery_dlg: None,torrent_dlg: None,+ torrent_waiting: Default::default(),+ torrent_closed: false,torrent_settings: None,add_trackers: None,torrent_files: None,@@ -3700,7 +3707,19 @@ impl App {self.show_window(ctx);return;}- if self.torrent_dlg.is_some() {+ if let Some(open) = &self.torrent_dlg {+ // One Add torrent at a time: a torrent handed over meanwhile waits its turn (#507).+ // Add torrent… from the menu with it open (no source) has nothing to wait for.+ if let Some(source) = source+ && open.source() != source+ && !self.torrent_waiting.iter().any(|(s, _)| *s == source)+ {+ tracing::info!(+ "Add torrent is open: a torrent waits ({} waiting)",+ self.torrent_waiting.len() + 1+ );+ self.torrent_waiting.push_back((source, remote));+ }return;}self.torrent_dlg = Some(crate::torrentdlg::TorrentDialog::new(@@ -8390,14 +8409,36 @@ impl App {if let Some((id, (files, all, size))) = torrent_files_selection {self.choose_files(id, files, all, size);}+ // The next torrent handed over while Add torrent was open (#507), a frame after it+ // closed: that frame without it closes its window, and the next one opens as a window+ // of its own (opened in the same frame, the closed window would only change its+ // contents). One that goes to the debrid account opens nothing, and the one after it+ // is next.+ if self.torrent_dlg.is_none() && !self.torrent_waiting.is_empty() {+ if std::mem::take(&mut self.torrent_closed) {+ ctx.request_repaint();+ } else {+ while self.torrent_dlg.is_none()+ && let Some((source, remote)) = self.torrent_waiting.pop_front()+ {+ self.open_torrent_dialog_with(Some(source), remote, ctx);+ }+ }+ }if let Some(t) = &mut self.torrent_dlg {- match t.show(ctx, &self.rt) {- Outcome::Open => {}- Outcome::Closed => self.torrent_dlg = None,+ let closed = match t.show(ctx, &self.rt) {+ Outcome::Open => false,+ Outcome::Closed => true,Outcome::Done(add) => {self.torrent_dlg = None;self.add_torrent(add);+ true}+ };+ if closed {+ self.torrent_dlg = None;+ self.torrent_closed = true;+ ctx.request_repaint();}}if let Some(g) = &mut self.gallery_dlg {diff --git a/crates/app/src/torrentdlg.rs b/crates/app/src/torrentdlg.rsindex 589d9ea8..b17316dc 100644--- a/crates/app/src/torrentdlg.rs+++ b/crates/app/src/torrentdlg.rs@@ -199,6 +199,11 @@ fn lookup_lines(s: &LookupStatus, secs: u64) -> (String, String, Option<&'static}impl TorrentDialog {+ /// The magnet link, .torrent path or address in its box.+ pub fn source(&self) -> &str {+ &self.source+ }+/// `source`: a magnet link, a .torrent path or a .torrent's web address (`remote`: how to/// ask for it) to look up at once, or None (the clipboard's magnet, if any, is offered and/// looked up).diff --git a/crates/app/tests/magnet_while_open.rs b/crates/app/tests/magnet_while_open.rsnew file mode 100644index 00000000..d0e526fb--- /dev/null+++ b/crates/app/tests/magnet_while_open.rs@@ -0,0 +1,165 @@+//! Issue #507: a magnet link handed to MDM while Add torrent was already open was dropped+//! without a word (the channel answered ok, nothing happened). It now waits its turn: Add torrent+//! opens again for it once the first one closes. The real app, off the screens (MDM_OFFSCREEN),+//! with a data folder of its own: two magnet links handed over as Windows starts the program for+//! one, the first Add torrent closed as its title bar's × does (WM_CLOSE), then the second one+//! must open.+//!+//! It opens windows, which needs OpenGL or Direct3D, so it runs on request:+//! `cargo test -p mdm-app --test magnet_while_open -- --ignored`.+//!+//! Windows only: the window is closed with `PostMessage(WM_CLOSE)` through PowerShell; the+//! queue itself is the same code on every system (app.rs `torrent_waiting`).+#![cfg(windows)]++use std::path::Path;+use std::process::{Child, Command};+use std::time::{Duration, Instant};++const APP: &str = env!("CARGO_BIN_EXE_misterdownloadmanager");++/// The app's log so far (every file of `logs/`).+fn log(data: &Path) -> String {+ let mut all = String::new();+ if let Ok(dir) = std::fs::read_dir(data.join("logs")) {+ for f in dir.flatten() {+ all += &std::fs::read_to_string(f.path()).unwrap_or_default();+ }+ }+ all+}++/// Wait until the log has `line` `times` times, failing if the app quits first or `wait` passes.+fn wait_for(app: &mut Child, data: &Path, line: &str, times: usize, wait: Duration) {+ let until = Instant::now() + wait;+ loop {+ let text = log(data);+ assert!(!text.contains("panic"), "the app panicked:\n{text}");+ if text.matches(line).count() >= times {+ return;+ }+ if let Some(status) = app.try_wait().unwrap() {+ panic!("the app closed ({status}) before '{line}' x{times}:\n{text}");+ }+ assert!(+ Instant::now() < until,+ "no '{line}' x{times} after {wait:?}:\n{text}"+ );+ std::thread::sleep(Duration::from_millis(200));+ }+}++/// A second launch with `args`: it hands them to the running app and quits.+fn second_launch(data: &Path, args: &[&str]) {+ let status = Command::new(APP)+ .args(args)+ .env("MDM_DATA_DIR", data)+ .env("MDM_OFFSCREEN", "1")+ .status()+ .unwrap();+ assert!(status.success(), "second launch {args:?}: {status}");+}++/// `WM_CLOSE` to `pid`'s visible window titled `title`, as its title bar's × sends.+fn close_window(pid: u32, title: &str) {+ let script = format!(+ r#"Add-Type @"+using System; using System.Text; using System.Runtime.InteropServices;+public static class W {{+ public delegate bool P(IntPtr h, IntPtr l);+ [DllImport("user32.dll")] static extern bool EnumWindows(P f, IntPtr l);+ [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint p);+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int GetWindowText(IntPtr h, StringBuilder s, int n);+ [DllImport("user32.dll")] static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l);+ public static int Close(uint pid, string title) {{+ int n = 0;+ EnumWindows((h, l) => {{ uint p; GetWindowThreadProcessId(h, out p);+ if (p == pid && IsWindowVisible(h)) {{ var sb = new StringBuilder(256); GetWindowText(h, sb, 256);+ if (sb.ToString() == title) {{ PostMessage(h, 0x10, IntPtr.Zero, IntPtr.Zero); n++; }} }}+ return true; }}, IntPtr.Zero);+ return n;+ }}+}}+"@+[W]::Close({pid}, '{title}')"#+ );+ let out = Command::new("powershell")+ .args(["-NoProfile", "-NonInteractive", "-Command", &script])+ .output()+ .unwrap();+ let closed = String::from_utf8_lossy(&out.stdout).trim().to_owned();+ assert_eq!(closed, "1", "windows closed: {closed} ({:?})", out.stderr);+}++#[test]+#[ignore = "opens the app's windows (off-screen): needs OpenGL or Direct3D; run with --ignored"]+fn a_magnet_handed_over_while_add_torrent_is_open_opens_after_it() {+ let dir = tempfile::tempdir().unwrap();+ let data = dir.path();+ // No update check, no first-start questions, English titles; the torrent engine stays on+ // this computer (the magnets name no tracker, so their look-ups just wait).+ let settings = serde_json::json!({+ "update_check": false, "helpers_asked": true, "language_asked": true, "language": "en",+ "extension_never_ask": true,+ "torrent_dht": false, "torrent_lsd": false, "torrent_upnp": false,+ "torrent_incoming": false,+ });+ std::fs::write(+ data.join("downloads.json"),+ serde_json::json!({ "next_id": 1, "items": [], "version": 2, "settings": settings })+ .to_string(),+ )+ .unwrap();+ let mut app = Command::new(APP)+ .env("MDM_DATA_DIR", data)+ .env("MDM_OFFSCREEN", "1")+ .spawn()+ .unwrap();+ let wait = Duration::from_secs(60);+ let opened = "window opened: add-torrent";+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ wait_for(&mut app, data, "window opened: main", 1, wait);+ let first =+ "magnet:?xt=urn:btih:5b4f0c3a9e1d27f86c0b3a4e9d1f2a7c6e8b0d14&dn=MDM%20test%201";+ let second =+ "magnet:?xt=urn:btih:7c1e9a2b4d6f8e0a1c3b5d7f9e2a4c6b8d0f1e23&dn=MDM%20test%202";+ second_launch(data, &[first]);+ wait_for(&mut app, data, opened, 1, wait);+ // Its first frames drawn (a close asked before then isn't seen by the window yet).+ std::thread::sleep(Duration::from_secs(2));+ // Handed over while it is open: it waits (the second launch returns once the app took+ // it).+ second_launch(data, &[second]);+ std::thread::sleep(Duration::from_millis(1500));+ assert_eq!(+ log(data).matches(opened).count(),+ 1,+ "one Add torrent at a time"+ );+ // The first closed: Add torrent opens again, for the second.+ close_window(app.id(), "Add torrent");+ wait_for(&mut app, data, "window closed: add-torrent", 1, wait);+ wait_for(&mut app, data, opened, 2, wait);+ assert!(log(data).contains("Add torrent is open: a torrent waits (1 waiting)"));+ // Closed too: nothing more was waiting.+ close_window(app.id(), "Add torrent");+ wait_for(&mut app, data, "window closed: add-torrent", 2, wait);+ std::thread::sleep(Duration::from_secs(2));+ assert_eq!(log(data).matches(opened).count(), 2, "nothing else waited");+ }));+ let _ = Command::new(APP)+ .arg("/exit")+ .env("MDM_DATA_DIR", data)+ .env("MDM_OFFSCREEN", "1")+ .status();+ let until = Instant::now() + Duration::from_secs(15);+ while app.try_wait().unwrap().is_none() && Instant::now() < until {+ std::thread::sleep(Duration::from_millis(200));+ }+ let _ = app.kill();+ let _ = app.wait();+ if let Err(e) = result {+ std::panic::resume_unwind(e);+ }+}