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
Video button: follows Options in pages already open (#532) (#537)
Ahmed Nefzaoui67241b4b1f84
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6e010d9b..ca698138 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- The video button follows **Options → General → Customize MDM Download panels in browsers** in the pages already open: switched off, or its site listed, it goes within a few seconds, without reloading the page (it stayed until a reload, and on YouTube, which never reloads, for good). A site listed as `example.com` now takes `www.example.com` and its other subdomains too, and a player embedded from another site follows the site in the address bar ([#532](https://github.com/anefzaoui/misterdownloadmanager/issues/532)).- macOS: file names in Persian, Arabic, Urdu, Hebrew or Armenian show their letters in the download list and windows instead of boxes, whatever the interface language: these scripts now get the font for them that comes with macOS (Arial Unicode), the first time one is needed ([#533](https://github.com/anefzaoui/misterdownloadmanager/issues/533)).- A download's progress is saved from its first seconds again: since 0.5.2, when the disk was slow to write the resume state as the download started (no data had arrived yet), the first save of its progress waited nine times as long, up to a minute, so a short download cut off by a crash or a power cut in that time started over from the beginning (part of [#518](https://github.com/anefzaoui/misterdownloadmanager/issues/518)).- macOS: **Download File Info** opens in front of the browser that asked for it ([#484](https://github.com/anefzaoui/misterdownloadmanager/issues/484)).diff --git a/ROADMAP.md b/ROADMAP.mdindex 510038bd..8cabb368 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -522,6 +522,8 @@ These ship in a later version, when they're ready.### Bugs being looked into+- 🔄 The video button still showing after it was switched off, or its site listed, in Options+ ([#532](https://github.com/anefzaoui/misterdownloadmanager/issues/532)): fix in review- 🔄 macOS: Persian and other Arabic-script file names drawn as boxes in the download list([#533](https://github.com/anefzaoui/misterdownloadmanager/issues/533)): fix in review, toconfirm on a Macdiff --git a/crates/ipc/src/capture.rs b/crates/ipc/src/capture.rsindex 87f183f2..4878f665 100644--- a/crates/ipc/src/capture.rs+++ b/crates/ipc/src/capture.rs@@ -222,16 +222,22 @@ impl CaptureRules {impl CaptureRules {/// May the download button show over videos on `page` (its address) in `browser`?/// Integration on, that browser captured, the button on and the site not one it stays off.- pub fn panel_on(&self, page: &str, browser: &str) -> bool {- self.captures(browser) && self.video_panel && !self.panel_hidden_on(page)+ /// `top`: the tab's address when `page` is a frame of another page's (a player embedded from+ /// another site): the site in the address bar is the one a person lists (#532).+ pub fn panel_on(&self, page: &str, top: Option<&str>, browser: &str) -> bool {+ self.captures(browser)+ && self.video_panel+ && !self.panel_hidden_on(page)+ && !top.is_some_and(|t| !t.is_empty() && self.panel_hidden_on(t))}- /// Is `page` (an address) on a site the button stays off?+ /// Is `page` (an address) on a site the button stays off? A name without `*.` takes its+ /// subdomains too (#532: `youtube.com` listed, the button still showed on www.youtube.com).pub fn panel_hidden_on(&self, page: &str) -> bool {let host = host_of(page);self.video_panel_sites.split_whitespace()- .any(|p| host_matches(&host, p))+ .any(|p| host_matches(&host, p) || host_matches(&host, &format!("*.{p}")))}}@@ -487,27 +493,45 @@ mod tests {video_panel_sites: "*.example.com tube.test".into(),..CaptureRules::default()};- assert!(r.panel_on("https://videos.site/watch?v=1", CHROME));+ assert!(r.panel_on("https://videos.site/watch?v=1", None, CHROME));assert!(- !r.panel_on("https://www.example.com/v", CHROME),+ !r.panel_on("https://www.example.com/v", None, CHROME),"a listed site");assert!(- !r.panel_on("https://example.com/v", CHROME),+ !r.panel_on("https://example.com/v", None, CHROME),"*. takes the domain too");- assert!(!r.panel_on("https://TUBE.test/v", FIREFOX));+ assert!(!r.panel_on("https://TUBE.test/v", None, FIREFOX));r.browsers = vec![("Mozilla Firefox".into(), false)];assert!(- !r.panel_on("https://videos.site/", FIREFOX),+ !r.panel_on("https://videos.site/", None, FIREFOX),"a browser not captured");- assert!(r.panel_on("https://videos.site/", CHROME));+ assert!(r.panel_on("https://videos.site/", None, CHROME));r.video_panel = false;- assert!(!r.panel_on("https://videos.site/", CHROME));+ assert!(!r.panel_on("https://videos.site/", None, CHROME));+ // #532: a name without `*.` takes its subdomains (www. above all); a player embedded+ // from another site follows the tab's site.+ r.video_panel = true;+ r.video_panel_sites = "quiet.test".into();+ assert!(!r.panel_on("https://www.quiet.test/v", None, CHROME));+ assert!(!r.panel_on("https://quiet.test/v", None, CHROME));+ assert!(r.panel_on("https://notquiet.test/v", None, CHROME));+ assert!(!r.panel_on(+ "https://videos.site/embed/1",+ Some("https://www.quiet.test/post"),+ CHROME+ ));+ assert!(r.panel_on(+ "https://videos.site/embed/1",+ Some("https://blog.site/"),+ CHROME+ ));+ assert!(r.panel_on("https://videos.site/embed/1", Some(""), CHROME));r.video_panel = true;r.advanced_integration = false;- assert!(!r.panel_on("https://videos.site/", CHROME));+ assert!(!r.panel_on("https://videos.site/", None, CHROME));}#[test]diff --git a/crates/nmhost/src/main.rs b/crates/nmhost/src/main.rsindex 5b9046d5..1a93021c 100644--- a/crates/nmhost/src/main.rs+++ b/crates/nmhost/src/main.rs@@ -96,7 +96,8 @@ struct Message {/// The user asked for this download (right-click → Download with Mister Download Manager):/// Options' automatic-capture rules don't apply, as IDM's "Download with IDM" takes any link.explicit: bool,- /// May the download button show over videos on page `url`?+ /// May the download button show over videos on page `url`? With `referrer`: the tab's+ /// address, when `url` is a frame embedded from another page (its site counts too, #532).panel: bool,/// The download button was clicked: `url` is the video's page, `src` the video's own/// address when the page plays a plain file (not a stream assembled in the page), or the@@ -242,7 +243,7 @@ fn answer(m: Message, rules: &mdm_ipc::capture::CaptureRules) -> Reply {// if need be), which opens its window or keeps the setting.if m.panel {return Reply {- ok: rules.panel_on(&m.url, browser),+ ok: rules.panel_on(&m.url, m.referrer.as_deref(), browser),..Default::default()};}@@ -411,7 +412,7 @@ fn video_command(}// The toolbar button's list of the tab's media (#38) asks for one explicitly: whether the// button over videos shows on this site doesn't matter then.- if !m.explicit && !rules.panel_on(&m.url, browser) {+ if !m.explicit && !rules.panel_on(&m.url, m.referrer.as_deref(), browser) {return Err(("options", "the video button is off here"));}// The video clicked, not the page's first one (a feed plays many): its own file when there@@ -1195,6 +1196,12 @@ mod tests {};assert!(answer(ask("https://videos.test/watch"), &rules).ok);assert!(!answer(ask("https://www.quiet.test/watch"), &rules).ok);+ // #532: a player embedded from another site, in a tab on a listed site.+ let embedded = Message {+ referrer: Some("https://www.quiet.test/post".into()),+ ..ask("https://videos.test/embed/1")+ };+ assert!(!answer(embedded, &rules).ok);rules.video_panel = false;assert!(!answer(ask("https://videos.test/watch"), &rules).ok);// Clicked where it's off (the page was open before the change): refused, nothing sent.diff --git a/extension/background.js b/extension/background.jsindex e51bcf77..f7275b6d 100644--- a/extension/background.js+++ b/extension/background.js@@ -1866,17 +1866,25 @@ async function injectOpenTabs() {// ---- messages from the page (video.js, page.js) and the popup (popup.js) -------------------// The download button over videos asks: may it show on this page, the button was clicked, its-// menu. The app decides through the native host; its answer for a site is kept a minute (one-// question per page load at most). A failure to reach it isn't kept.+// menu. The app decides through the native host, from Options as saved now; its answer for a+// site is kept a few seconds (the page's frames ask together, and each page asks again when its+// answer is older: video.js ASK_MS), so a change in Options reaches the pages already open+// (#532: it was kept a minute, and by the page for good). A failure to reach it isn't kept.+// `top`: the tab's address, when the frame asking is another page's (a player embedded from+// another site): the button stays off there too when the tab's site is listed.+const PANEL_KEEP_MS = 5000;const panelCache = new Map();-async function panelOn(page) {+async function panelOn(page, top) {// The host name without a port: as video.js names the site, and as the app matches sites.const site = new URL(page).hostname;- forget(panelCache, 60000);- const kept = panelCache.get(site);+ const tabSite = top ? new URL(top).hostname : "";+ const key = tabSite && tabSite !== site ? `${site} ${tabSite}` : site;+ forget(panelCache, PANEL_KEEP_MS);+ if (panelCache.get(site)?.hidden) return false;+ const kept = panelCache.get(key);if (kept) return kept.on;- const reply = await native({ panel: true, url: page });- if (reply.ok || !reply.why) panelCache.set(site, { on: Boolean(reply.ok), at: Date.now() });+ const reply = await native({ panel: true, url: page, ...(key !== site ? { referrer: top } : {}) });+ if (reply.ok || !reply.why) panelCache.set(key, { on: Boolean(reply.ok), at: Date.now() });return Boolean(reply.ok);}@@ -1949,7 +1957,10 @@ async function videoAddress(m, page, sender) {async function pageMessage(m, sender) {const page = senderPage(sender);const tab = sender.tab || {};- if (m.type === "panel") return { on: page ? await panelOn(page) : false };+ if (m.type === "panel") {+ const top = tab.url && /^https?:/i.test(tab.url) ? tab.url : "";+ return { on: page ? await panelOn(page, top) : false };+ }if (m.type === "link" && typeof m.url === "string") {const name = typeof m.name === "string" ? m.name.split(/[\\/]/).pop().slice(0, 255) : "";return link(m.url, page || "", Boolean(tab.incognito), name);@@ -1989,7 +2000,8 @@ async function pageMessage(m, sender) {}if (m.type === "hide-site" && page) {const host = new URL(page).hostname;- panelCache.set(host, { on: false, at: Date.now() });+ // Off at once on this site, whatever the tab around it, while the app saves it.+ panelCache.set(host, { on: false, hidden: true, at: Date.now() });const reply = await native({ hideSite: host });return { ok: Boolean(reply.ok) };}diff --git a/extension/video.js b/extension/video.jsindex 89d69030..3d914464 100644--- a/extension/video.js+++ b/extension/video.js@@ -130,7 +130,17 @@const dismissed = new WeakSet();const dismissedSrc = new Set();const isDismissed = (v) => dismissed.has(v) || (v.currentSrc && dismissedSrc.has(v.currentSrc));- let allowed = null; // asked once per page: may it show here?+ // May it show here? The app's answer (Options: the button on, the site not listed), asked+ // again when older than ASK_MS, so a change in Options reaches a page already open (#532: one+ // that never reloads, as YouTube's, kept the button for good). `never`: this page's own+ // "Never on this site".+ let allowed = null;+ let askedAt = 0;+ let asking = null;+ let never = false;+ let placed = false;+ const ASK_MS = 5000;+ const answered = () => allowed !== null && Date.now() - askedAt < ASK_MS;let place = { x: 1, y: 0 }; // where on the edge: fractions of the room, top right by defaultlet chosen = false; // the user put it where it is (dragged it, on this site): theirs, never moved for a page's controllet auto = { v: null, at: null, t: 0 }; // the spot found for this video, kept for a moment@@ -517,29 +527,42 @@ button:focus-visible { outline: 2px solid #2a78d6; outline-offset: -2px; }function look() {scan = 0;- if (dragging || allowed === false) return;+ if (dragging || never || (allowed === false && answered())) return;const v = videoAt(pointer.x, pointer.y);if (!v) return;- if (allowed === null) return void ask().then(() => allowed && look());+ if (!answered()) return void ask().then(() => allowed && look());show(v);}- async function ask() {- if (allowed !== null) return;- allowed = false; // until answered: one question per page- const r = await send({ type: "panel" });- allowed = Boolean(r && r.on);- if (allowed) {- try {- const { positions } = await ext.storage.local.get({ positions: {} });- if (positions[host]) {- place = snap(positions[host]);- chosen = true;+ // One question at a time; while it is out, the button waits for its answer.+ function ask() {+ if (never) {+ allowed = false;+ return Promise.resolve();+ }+ if (answered()) return Promise.resolve();+ asking = asking || send({ type: "panel" }).then(async (r) => {+ allowed = !never && Boolean(r && r.on);+ askedAt = Date.now();+ // Switched off meanwhile: gone now, unless the menu or a drag has it in hand.+ if (!allowed && video && !menuOpen && !dragging) {+ video = null;+ hide(true);+ }+ if (allowed && !placed) {+ placed = true;+ try {+ const { positions } = await ext.storage.local.get({ positions: {} });+ if (positions[host]) {+ place = snap(positions[host]);+ chosen = true;+ }+ } catch {+ // Default spot.}- } catch {- // Default spot.}- }+ }).finally(() => (asking = null));+ return asking;}// ---- acting ---------------------------------------------------------------------------------@@ -612,6 +635,7 @@ button:focus-visible { outline: 2px solid #2a78d6; outline-offset: -2px; }return hide(true);}if (act === "never") {+ never = true;allowed = false;video = null;hide(true);@@ -729,6 +753,7 @@ button:focus-visible { outline: 2px solid #2a78d6; outline-offset: -2px; }removeEventListener("pointermove", onMove, true);removeEventListener("keydown", onTab, true);root.remove();+ never = true;allowed = false;video = null;}diff --git a/tools/extension/e2e.mjs b/tools/extension/e2e.mjsindex 1a79598c..3fa4edde 100644--- a/tools/extension/e2e.mjs+++ b/tools/extension/e2e.mjs@@ -24,7 +24,8 @@// .m3u8 or .mpd, served as text/plain or octet-stream, #171), sniffed (#171 without yt-dlp: such// streams found only when asked, by the button and the media list, a text decoy never), media (the// toolbar button's list of the media a tab loaded: streams, files, a protected stream; #38), video (shown, clicked, dragged,-// kept; "never on the site" in the last browser), videoFocus (mouse idle/fullscreen and keyboard+// kept; "never on the site" in the last browser), panelOptions (the button follows Options in+// an open tab: off, on, the site listed; #532), videoFocus (mouse idle/fullscreen and keyboard// focus, #480), start (MDM not running: the host starts it),// remote (Send downloads to → Another MDM, #157: paired from the popup, a link downloaded by a// headless MDM; E2E_REMOTE_URL for one running elsewhere, such as the Docker image: remoteServer).@@ -1102,6 +1103,58 @@ async function videoButton(session, never) {return "shown, clicked (the video's file), dragged, kept, never on the site";}+// How long the page and the extension keep the app's "may it show here" (video.js ASK_MS,+// background.js PANEL_KEEP_MS), with room for the question.+const PANEL_KEPT_MS = 5000 + 1500;++// Options → General → Download panels, changed as its OK does: the settings saved in+// downloads.json, which the host reads at each question. Changed with the app stopped, so its own+// next save doesn't put them back.+async function panelSettings(change) {+ await stopApp();+ const file = path.join(data, "downloads.json");+ const saved = JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));+ Object.assign(saved.settings, change);+ fs.writeFileSync(file, JSON.stringify(saved));+ await startApp();+}++// #532: the button follows Options in a tab already open (no reload: YouTube never reloads),+// switched off, on again, and off on the site; and after a reload.+async function videoButtonFollowsOptions(session) {+ const page = `${LAB}/page?video=${encodeURIComponent("/gen/1M/clip.mp4")}`;+ await session.navigate(page);+ const v = await rect(session, "#video");+ const away = async () => {+ await session.mouse(5, 5);+ await sleep(PANEL_KEPT_MS);+ };+ const done = [];+ try {+ if (!(await hover(session, v))) throw new Error("no button over the video");+ await panelSettings({ video_panel: false });+ await away();+ if (await hover(session, v)) throw new Error("switched off in Options: the button still shows in the open tab");+ done.push("off: gone in the open tab");+ await session.mouse(5, 5);+ await session.navigate(page);+ if (await hover(session, v)) throw new Error("switched off in Options: the button shows after a reload");+ done.push("and after a reload");+ await panelSettings({ video_panel: true });+ await away();+ if (!(await hover(session, v))) throw new Error("switched on again: no button in the open tab");+ done.push("on again: back in the open tab");+ await panelSettings({ video_panel_sites: "127.0.0.1" });+ await away();+ if (await hover(session, v)) throw new Error("the site listed in Options: the button still shows in the open tab");+ done.push("the site listed: gone in the open tab");+ } finally {+ await session.mouse(5, 5);+ await panelSettings({ video_panel: true, video_panel_sites: "" });+ }+ return done.join("; ");+}+// ---- the cases ---------------------------------------------------------------------------------class Skip extends Error {}@@ -1944,6 +1997,11 @@ const CASES = {return `sent ${address.replace(LAB, "")}`;},+ // Before `video`, which ends with "Never on this site" for the lab in the last browser.+ async panelOptions(t) {+ return videoButtonFollowsOptions(t.session);+ },+// Before `video`: its last step turns the button off for the lab's site in the last browser.async videoFocus(t) {// Headless Firefox refuses the player's fullscreen request and Tab's focus on it here.diff --git a/tools/extension/test.mjs b/tools/extension/test.mjsindex 76a33fea..5ead24b7 100644--- a/tools/extension/test.mjs+++ b/tools/extension/test.mjs@@ -134,8 +134,8 @@ function fakeApi({return { ok: true, version: "0.2.5", types, capture: true, excludedSites: "*.update.microsoft.com", excludedAddresses: [], opened: true, ...rules };}calls.push(["native", name, m]);- // The video button: "may it show" follows `panelOn`.- if (m.panel) return { ok: panelOn !== false };+ // The video button: "may it show" follows `panelOn` (a function: the app's answer now).+ if (m.panel) return { ok: typeof panelOn === "function" ? panelOn(m) : panelOn !== false };// A notice of a download left alone (#208): an older host, which knows none, takes it// for an address it can't download (`noticeReply`).if (m.declined) return noticeReply || { ok: true };@@ -231,7 +231,8 @@ async function fakeFetch(url, opts) {const complaints = [];const quietConsole = { ...console, error: (...a) => complaints.push(["error", ...a]), warn: (...a) => complaints.push(["warn", ...a]) };-function load(api, firefox) {+// `extra`: more of the script's globals (a `Date` whose clock the test moves).+function load(api, firefox, extra = {}) {const ctx = {fetch: fakeFetch,navigator: { userAgent: "UA", userAgentData: { brands: [{ brand: "Chromium" }, { brand: "Brave" }] } },@@ -245,6 +246,7 @@ function load(api, firefox) {};if (firefox) ctx.browser = api;else ctx.chrome = api;+ Object.assign(ctx, extra);vm.runInNewContext(code, ctx);}@@ -676,6 +678,44 @@ const ok = (what) => {assert.ok(calls.some((c) => c[0] === "cookies" && c[1].url === "https://other.test/x/main.mpd"), "the button: the stream's cookies");ok("#155: the right-click menu on a stream's player sends its manifest; cookies of the stream");}+// #532: Options changed while a page with a video is open: the app's answer is kept a few+// seconds, not a minute, so the button follows (the page asks again: video.js ASK_MS). An+// embedded player asks with its tab's address, so the site in the address bar counts too.+{+ const clock = { t: Date.now() };+ class FakeDate extends Date {+ static now() {+ return clock.t;+ }+ }+ let appSays = true;+ const { api, calls, listeners } = fakeApi({ firefox: false, panelOn: () => appSays });+ load(api, false, { Date: FakeDate });+ const embed = { id: "ours", url: "https://tube.test/embed/1", frameId: 3, tab: { url: "https://blog.test/post" } };+ const top = { id: "ours", url: "https://tube.test/watch", frameId: 0, tab: { url: "https://tube.test/watch" } };+ const ask = (sender) =>+ new Promise((r) => listeners.message({ type: "panel" }, sender, (v) => r(JSON.parse(JSON.stringify(v)))));+ assert.deepEqual(await ask(embed), { on: true });+ const asked = () => natives(calls).filter((m) => m.panel);+ assert.equal(asked()[0].referrer, "https://blog.test/post", "the tab's address with an embedded player's question");+ assert.deepEqual(await ask(top), { on: true });+ assert.equal(asked()[1].referrer, undefined, "none for the tab's own page");+ appSays = false;+ clock.t += 1000;+ assert.deepEqual(await ask(top), { on: true }, "kept a moment (the page's frames ask together)");+ assert.equal(asked().length, 2);+ clock.t += 5000;+ assert.deepEqual(await ask(top), { on: false }, "switched off in Options: the next question has it");+ assert.deepEqual(await ask(embed), { on: false });+ appSays = true;+ clock.t += 6000;+ assert.deepEqual(await ask(embed), { on: true }, "and on again");+ // "Never on this site" from the embed: off at once, in its tab and in any other.+ await new Promise((r) => listeners.message({ type: "hide-site" }, embed, r));+ assert.deepEqual(await ask(embed), { on: false });+ assert.deepEqual(await ask({ ...embed, tab: { url: "https://news.test/" } }), { on: false }, "whatever the tab");+ ok("#532: the video button follows Options within seconds; an embed asks with its tab's address");+}{const { api, listeners } = fakeApi({ firefox: true, panelOn: false });load(api, true);