Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

Extension: downloads it leaves keep another extension's name and folder (#578) (#584)

Ahmed Nefzaouia5a758037188
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9f1bf34a..3b5c4bdb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
- 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)).
- Windows: a download's progress window with a title of 256 characters or more (a torrent with a long name, or a file name kept whole in a folder too deep to shorten it) has MDM's own title bar again, instead of the system's drawn above it (part of [#540](https://github.com/anefzaoui/misterdownloadmanager/issues/540)).
- Windows: closing the window hides MDM in the notification area again when Windows keeps its icon among the hidden icons (behind ^), where a new icon goes. MDM took the icon for missing there and left the window in the taskbar instead; it now does that only when Windows has no icon of MDM's at all ([#545](https://github.com/anefzaoui/misterdownloadmanager/issues/545), [#534](https://github.com/anefzaoui/misterdownloadmanager/issues/534), [#527](https://github.com/anefzaoui/misterdownloadmanager/issues/527)).
+- Chrome, Edge, Brave and the other Chromium browsers: a download the extension leaves to the browser keeps the name and folder another extension gives it (Save In's folders, or any extension's own download into a folder). The extension's answer for it counted as a name of its own, an empty one, and when the extension was the newest installed it won: the file landed in the Downloads folder, and the browser could warn of a conflict between the two extensions ([#578](https://github.com/anefzaoui/misterdownloadmanager/issues/578)).
### Added
- Options → General → **Customize MDM Download panels in browsers**: Export... and Import... for the sites the download button stays off, a plain text file with one site a line ([#424](https://github.com/anefzaoui/misterdownloadmanager/issues/424)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 7568bf1b..e4396d84 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -535,6 +535,9 @@ These ship in a later version, when they're ready.
### Bugs being looked into
+- 🔄 Chromium browsers: another extension's file names and folders (Save In's) lost while MDM's
+ extension was on, for downloads it left to the browser
+ ([#578](https://github.com/anefzaoui/misterdownloadmanager/issues/578)): fix in review
- 🔄 Without ffmpeg, YouTube's sound alone saved as `.mp4` though it was raw AAC from HLS pieces,
which no player opened ([#569](https://github.com/anefzaoui/misterdownloadmanager/issues/569)): fix in review
- 🔄 A progress window's title bar buttons not answering
diff --git a/extension/background.js b/extension/background.js
index f7275b6d..83fc458c 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -1409,6 +1409,19 @@ async function drop(item) {
closeLeftTab([firstUrl(item), item.url, item.finalUrl].filter(Boolean)).catch(() => {});
}
+// A download left to the browser keeps the name it has, or the one another extension gives it
+// (Save In's folders, #578; a `downloads.download` with a `filename`). Chromium counts every
+// listener's answer as a name of its own, an empty one too: `suggest()` without a suggestion
+// reaches it as an empty name with no conflict action, and when the most recently installed
+// extension answers so, its empty name wins and the others' are dropped (the download lands in
+// the Downloads folder, and the browser may warn of a conflict). Only an answer with
+// "uniquify" and no name is no suggestion at all (downloads_api.cc, DeterminerCallback), and
+// the binding lets no empty name through: a name the browser refuses, which it empties after
+// counting the answer, is how a listener gives one ("Invalid filename" is logged once).
+function noName(suggest) {
+ suggest({ filename: "..", conflictAction: "uniquify" });
+}
+
if (SAFARI) {
// Nothing to listen to: see `link`.
} else if (!FIREFOX) {
@@ -1423,10 +1436,10 @@ if (SAFARI) {
const taken = Boolean(c && c.name && !c.left) && (await offer(item, url, c.name));
if (taken) return drop(item);
// The browser goes on first; why is said after.
- suggest();
+ noName(suggest);
leftAlone(c, item, url);
})
- .catch(() => suggest());
+ .catch(() => noName(suggest));
return true; // suggest() comes later
});
} else {
diff --git a/tools/extension/e2e.mjs b/tools/extension/e2e.mjs
index 3fa4edde..24632e30 100644
--- a/tools/extension/e2e.mjs
+++ b/tools/extension/e2e.mjs
@@ -13,7 +13,8 @@
// place). E2E_FIREFOX_ASK=1: Firefox's family asks what to do with each new type in every case
// (Waterfox's default), not only in the ask case.
//
-// The cases (per browser): link (a .zip link, throttled and not), ask (Firefox set to ask what to
+// The cases (per browser): folders (another extension's download in a folder of its own keeps
+// it, #578), link (a .zip link, throttled and not), ask (Firefox set to ask what to
// do with each new type, as Waterfox is: caught before its dialog, #208), cookie (cookies and referrer
// forwarded), names (Content-Disposition), redirect, leadon (a page going to the file by script, #374), form (POST, 303), alt (Alt+click leaves it
// to the browser), opened (a PDF or MP3 the browser would show or play), spot (the video button
@@ -386,10 +387,10 @@ async function chromium(bin, profile, dl, page, ready) {
// that tab's `evaluate` and `close` (the proxy case's stand-in VPN extension sets the
// browser's proxy there, as one does). A page, not its service worker: the browser may
// stop an idle worker, a page keeps its extension API while open.
- loadExtension: async (dir, page) => {
+ loadExtension: async (dir, page, api = "proxy") => {
const { id: other } = await cdp.send("Extensions.loadUnpacked", { path: dir });
const t = await tab(`chrome-extension://${other}/${page}`);
- await until("the other extension's page", 10000, () => t.evaluate("document.readyState === 'complete' && typeof chrome === 'object' && Boolean(chrome.proxy)").catch(() => false));
+ await until("the other extension's page", 10000, () => t.evaluate(`document.readyState === 'complete' && typeof chrome === 'object' && Boolean(chrome.${api})`).catch(() => false));
return t;
},
close: () => {
@@ -1253,6 +1254,19 @@ function vpnExtension() {
return dir;
}
+// #578's stand-in for an extension that saves files in folders of its own (Save In): it starts
+// a download with `downloads.download` and a `filename` in a folder. Its page, driven over DevTools.
+function folderExtension() {
+ const dir = path.join(work, "folder-extension");
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, "manifest.json"),
+ JSON.stringify({ manifest_version: 3, name: "MDM e2e stand-in Save In", version: "1.0", permissions: ["downloads"], host_permissions: ["<all_urls>"] }),
+ );
+ fs.writeFileSync(path.join(dir, "page.html"), "<!doctype html><title>stand-in Save In</title>");
+ return dir;
+}
+
// Firefox's stand-in VPN add-on: it sends the lab's host (lab.mdm.test) through the test proxy
// per request (proxy.onRequest), leaving the browser's proxy settings alone.
function firefoxVpnExtension() {
@@ -1371,6 +1385,38 @@ async function proxyInChromium(t) {
}
const CASES = {
+ // #578: a download another extension starts in a folder of its own, of a type MDM doesn't
+ // take, lands in that folder. Chromium only (Firefox has no onDeterminingFilename): MDM's
+ // listener answers for every download, and an answer that names nothing must not empty the
+ // other extension's name.
+ async folders(t) {
+ if (t.kind !== "chromium") throw new Skip("Chromium's onDeterminingFilename only");
+ const page = await t.session.loadExtension(folderExtension(), "page.html", "downloads");
+ try {
+ const file = `e2e-folders-${t.name}.png`;
+ const sub = path.join("Pic", "OthersW");
+ const id = await page.evaluate(`chrome.downloads.download({ url: ${JSON.stringify(`${LAB}/gen/64K/${file}`)}, filename: ${JSON.stringify(`Pic/OthersW/${file}`)} })`);
+ const want = path.join(t.dl, sub, file);
+ const where = () => {
+ const found = [];
+ const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).forEach((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : found.push(path.relative(t.dl, path.join(d, e.name)))));
+ walk(t.dl);
+ return found;
+ };
+ try {
+ await until(`${file} in the stand-in's folder`, 20000, () => fs.existsSync(want) && fs.statSync(want).size === 64 << 10);
+ } catch {
+ throw new Error(`the browser saved it as ${JSON.stringify(where())} (want ${path.join(sub, file)})`);
+ }
+ const mdm = (await mdmList().catch(() => [])).filter((d) => d.file === file);
+ if (mdm.length) throw new Error(`MDM took it too: ${JSON.stringify(mdm)}`);
+ const got = (await requests(`/gen/64K/${file}`)).map(brief);
+ for (const f of fs.readdirSync(t.dl)) fs.rmSync(path.join(t.dl, f), { force: true, recursive: true });
+ return `download ${id} saved in ${path.join(sub, file)}, MDM left it (the lab's log: ${got.join("; ")})`;
+ } finally {
+ await page.close();
+ }
+ },
// #42: the browser behind a proxy (a VPN or proxy extension's). The file's host (lab.mdm.test) is
// known to that proxy only, so MDM can download it only through the same proxy, which the
// extension hands over with the download, once the user switched that on: the popup's switch
diff --git a/tools/extension/test.mjs b/tools/extension/test.mjs
index 5ead24b7..9dbba94f 100644
--- a/tools/extension/test.mjs
+++ b/tools/extension/test.mjs
@@ -374,6 +374,52 @@ const ok = (what) => {
ok("Chrome: declined, the browser's own");
}
+// Chrome, #578: a download left to the browser keeps another extension's name. What Chromium
+// does with each listener's answer (downloads_custom_bindings.js, then downloads_api.cc
+// DetermineFilename and DeterminerCallback): no valid suggestion goes as an empty name with no
+// conflict action, which counts as a name; a name the browser refuses is emptied after the
+// answer is counted, and only an empty name with "uniquify" is no name at all. The newest
+// extension's name wins (here MDM's, updated after Save In was installed).
+{
+ const answer = (s) => {
+ const valid = s && typeof s === "object" && typeof s.filename === "string" && s.filename.length > 0;
+ const [name, action] = valid ? [s.filename, s.conflictAction || ""] : ["", ""];
+ const safe = name && !name.split(/[\/]/).some((p) => p === "" || p === "." || p === "..") && !/^[a-z]:|^[\/]/i.test(name);
+ const filename = safe ? name : "";
+ return filename || action !== "uniquify" ? { filename } : null; // null: no suggestion
+ };
+ // The determination of one download: `answers` in install order, oldest first.
+ const determined = (creator, answers) => {
+ let name = creator;
+ let by = -1;
+ answers.forEach((a, i) => {
+ const s = answer(a);
+ if (s && i >= by) [name, by] = [s.filename, i];
+ });
+ return name;
+ };
+ for (const [what, item, creator] of [
+ ["its own listener's folder (Save In)", { id: 70, url: "https://img.test/cat.jpg", filename: "cat.jpg", byExtensionId: "savein" }, ""],
+ ["a downloads.download filename", { id: 71, url: "https://img.test/dog.jpg", filename: "dog.jpg", byExtensionId: "savein" }, "Pic/OthersW/dog.jpg"],
+ ["a page's download", { id: 72, url: "https://x/page.html", filename: "page.html" }, ""],
+ ]) {
+ const { api, listeners } = fakeApi({ firefox: false });
+ load(api, false);
+ const other = item.byExtensionId && !creator ? { filename: `Pic/OthersW/${item.filename}` } : undefined;
+ let mdm = "none";
+ listeners.determining(item, (s) => (mdm = s));
+ await settle();
+ assert.notEqual(mdm, "none", `${what}: answered, the download doesn't wait`);
+ const want = other ? other.filename : creator;
+ assert.equal(determined(creator, other ? [other, mdm] : [mdm]), want, `${what}: MDM's answer gives no name of its own`);
+ }
+ // The model, checked: Chromium's own cases.
+ assert.equal(determined("Pic/a.jpg", [undefined]), "", "suggest() empties the creator's name");
+ assert.equal(determined("", [{ filename: "Pic/b.jpg" }, undefined]), "", "and the older extension's");
+ assert.equal(determined("", [undefined, { filename: "Pic/b.jpg" }]), "Pic/b.jpg", "an older suggest() loses");
+ ok("Chrome: a download left alone keeps another extension's name and folder (#578)");
+}
+
// Firefox: a small file finished before it could be stopped: the browser's copy is removed.
{
const { api, calls, listeners } = fakeApi({ firefox: true, finished: true });