Skip to content

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

Downloads a page starts by script: the file's address, not the page's (#374) (#383)

Ahmed Nefzaouib82758e83c89
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 56df3058..fe365fcb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- A download that a page starts by script (a thank-you page going to the installer, as obsproject.com's does) gets the file's address, not the page's, so MDM no longer saves that page under the installer's name ([#374](https://github.com/anefzaoui/misterdownloadmanager/issues/374)). A finished download also shows what really came down when the server gives no size.
- **Stop** on a download in a running queue stays stopped, instead of the queue starting it again a moment later; **Stop All** too ([#341](https://github.com/anefzaoui/misterdownloadmanager/issues/341)).
- Removing the last feed in the RSS feeds window no longer crashes the app ([#321](https://github.com/anefzaoui/misterdownloadmanager/issues/321)).
- **YouTube formats with Node.js or Bun installed** ([#360](https://github.com/anefzaoui/misterdownloadmanager/issues/360)): yt-dlp needs a JavaScript runtime for them and looks for Deno alone, so MDM now tells it about Node.js (nvm's too) or Bun when there is no Deno.
diff --git a/ROADMAP.md b/ROADMAP.md
index 9bd17337..2a8ab147 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -463,6 +463,8 @@ These ship in a later version, when they're ready.
### Bugs being looked into
+- πŸ”„ A page that starts a download by script being saved instead of the file
+ ([#374](https://github.com/anefzaoui/misterdownloadmanager/issues/374)): fix in review
- πŸ” A site's bot check refusing MDM's request (testfile.org, a Cloudflare challenge): the\n message now says so ([#376](https://github.com/anefzaoui/misterdownloadmanager/issues/376)); a way to hand the download back to the browser is still to decide
- πŸ”„ A download starting again by itself after Stop, when it is in a running queue\n ([#341](https://github.com/anefzaoui/misterdownloadmanager/issues/341)): fix in review
- πŸ”„ A crash when removing the last feed in the RSS feeds window
diff --git a/crates/app/src/model.rs b/crates/app/src/model.rs
index 20e36d51..eea14c23 100644
--- a/crates/app/src/model.rs
+++ b/crates/app/src/model.rs
@@ -621,6 +621,21 @@ fn push_log(log: &mut Vec<(i64, String)>, at: i64, text: String) {
log.push((at, text));
}
+/// The size a row shows after a snapshot: the server's when it said one, else what was known. A
+/// download that ended without one is as long as what came down, not what the browser announced
+/// for the file it was going to fetch (#374).
+fn size_after(
+ state: State,
+ server: Option<u64>,
+ downloaded: u64,
+ known: Option<u64>,
+) -> Option<u64> {
+ match server {
+ None if state == State::Done => Some(downloaded),
+ server => server.or(known),
+ }
+}
+
impl Item {
/// Add an app-side event (added, started, stopped …) to the log.
pub fn note(&mut self, text: impl Into<String>) {
@@ -704,7 +719,7 @@ impl Item {
self.server = Some(crate::whereis::Seen::from(server));
}
self.downloaded = s.downloaded;
- self.size = s.size.or(self.size);
+ self.size = size_after(s.state, s.size, s.downloaded, self.size);
self.resumable = s.resumable.or(self.resumable);
if let Some(f) = &s.file {
// Named now: a later start from scratch keeps this name.
@@ -1049,6 +1064,25 @@ pub fn time(secs: f64) -> String {
}
}
+#[cfg(test)]
+mod size_tests {
+ use super::*;
+
+ #[test]
+ fn a_finished_download_is_as_long_as_what_came_down() {
+ // The browser announced 178 MB; the server sent a 15 KB page and no size.
+ assert_eq!(
+ size_after(State::Done, None, 14473, Some(186662440)),
+ Some(14473)
+ );
+ assert_eq!(
+ size_after(State::Downloading, None, 14473, Some(186662440)),
+ Some(186662440)
+ );
+ assert_eq!(size_after(State::Done, Some(100), 100, None), Some(100));
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/labserver/src/pages.rs b/crates/labserver/src/pages.rs
index 19898c3c..7c755d2b 100644
--- a/crates/labserver/src/pages.rs
+++ b/crates/labserver/src/pages.rs
@@ -203,6 +203,21 @@ pub(crate) async fn page(RawQuery(q): RawQuery) -> Response {
resp
}
+/// `/leadon?to=PATH`: a page that goes to `to` by script as it loads, as a download site's
+/// thank-you page does (#374).
+pub(crate) async fn leadon(RawQuery(q): RawQuery) -> Response {
+ let pairs = pairs(q);
+ let to = pairs
+ .iter()
+ .find(|(k, _)| k == "to")
+ .map_or("/", |(_, v)| v.as_str());
+ let to = to.replace('\\', "\\\\").replace('"', "\\\"");
+ html(format!(
+ "{}Thank you<script>location.href = \"{to}\";</script>",
+ head("Thank you")
+ ))
+}
+
/// `/formpage?size=1M&name=report.zip&token=abc&with=QUERY`: three forms that post to `/form`
/// (urlencoded, multipart, and urlencoded answered with 303).
pub(crate) async fn formpage(RawQuery(q): RawQuery) -> Response {
diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rs
index 59483621..bca7c891 100644
--- a/crates/labserver/src/server.rs
+++ b/crates/labserver/src/server.rs
@@ -333,6 +333,7 @@ impl LabServer {
// Routes answered from memory, logged by `log_simple`.
let simple = Router::new()
.route("/page", get(pages::page))
+ .route("/leadon", get(pages::leadon))
.route("/formpage", get(pages::formpage))
.route("/cookie", get(pages::cookie))
.route("/assets/{file}", get(pages::asset))
diff --git a/extension/background.js b/extension/background.js
index c8bdbc46..c3bcd6a3 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -455,10 +455,18 @@ if (ext.webRequest && ext.webRequest.onBeforeRedirect) {
);
}
+// Pages the browser loaded in a tab or frame (two minutes), by address (the listener below).
+const loadedPages = new Map();
+
// The address a download was first asked for: the browser's own (Chromium), else the start of
-// the redirects that led to it.
+// the redirects that led to it. Chromium also counts the page a script or a meta refresh left
+// from as a download's start (#374: a thank-you page setting location.href to the installer);
+// that page isn't the file, and asking it again would save the page under the file's name.
function firstUrl(item) {
- if (item.finalUrl && item.finalUrl !== item.url) return item.url;
+ if (item.finalUrl && item.finalUrl !== item.url) {
+ const page = loadedPages.get(item.url);
+ return page && Date.now() - page.at < 120000 ? item.finalUrl : item.url;
+ }
const r = redirected.get(item.url);
return r && Date.now() - r.at < 120000 ? r.from : item.url;
}
@@ -655,10 +663,18 @@ function sniffTab(tabId, frames) {
if (ext.webRequest && ext.webRequest.onResponseStarted) {
ext.webRequest.onResponseStarted.addListener(
(d) => {
+ if (d.type === "main_frame" || d.type === "sub_frame") {
+ const type = (d.responseHeaders || []).find((h) => h.name.toLowerCase() === "content-type");
+ if (d.statusCode === 200 && type && /^\s*(text\/html|application\/xhtml)/i.test(type.value || "")) {
+ forget(loadedPages, 120000);
+ loadedPages.set(d.url, { at: Date.now() });
+ }
+ return;
+ }
const found = mediaKind(d);
if (found) mediaBack.then(() => (found.kind === "maybe" ? noteMaybe(d, found) : noteMedia(d, found)));
},
- { urls: ["<all_urls>"], types: ["xmlhttprequest", "media", "other"] },
+ { urls: ["<all_urls>"], types: ["main_frame", "sub_frame", "xmlhttprequest", "media", "other"] },
["responseHeaders"],
);
}
diff --git a/tools/extension/e2e.mjs b/tools/extension/e2e.mjs
index ca5dae1c..9e77479c 100644
--- a/tools/extension/e2e.mjs
+++ b/tools/extension/e2e.mjs
@@ -15,7 +15,7 @@
//
// The cases (per browser): 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, form (POST, 303), alt (Alt+click leaves it
+// 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), csp (the video button
// under a strict CSP), hls (the stream a player loaded), streams (HLS and DASH players handed over
// by the button, the right-click menu and the media list, and read by yt-dlp; #155; also with no
@@ -1440,6 +1440,19 @@ const CASES = {
return "the address clicked kept, the file from its target";
},
+ // A page that goes to the file by script (#374): MDM gets the file's address, not the page's.
+ async leadon(t) {
+ const file = `e2e-leadon-${t.name}.zip`;
+ const page = `/leadon?to=${encodeURIComponent(`/gen/2M/${file}`)}`;
+ await t.session.navigate(`${LAB}${page}`);
+ const item = await arrived(file, 2 << 20);
+ if (item.url !== `${LAB}/gen/2M/${file}`) throw new Error(`MDM's address is ${item.url}, not the file's`);
+ const asked = await requests(page.split("?")[0]);
+ if (asked.length !== 1) throw new Error(`the page was asked ${asked.length} times (only the browser's expected)`);
+ await keptNothing(t.dl);
+ return "the file's address, the page asked by the browser only";
+ },
+
// A form's download: MDM posts it again with the form's body; one answered 303 too.
async form(t) {
const name = `e2e-form-${t.name}.zip`;
diff --git a/tools/extension/test.mjs b/tools/extension/test.mjs
index ab50166b..3a6d85d2 100644
--- a/tools/extension/test.mjs
+++ b/tools/extension/test.mjs
@@ -346,6 +346,20 @@ const ok = (what) => {
ok("Chrome: taken at its name, incognito cookies, both addresses");
}
+// Chrome: a page that left for the file by script (Chromium counts it as the download's start,
+// #374) isn't the address of the file.
+{
+ const { api, calls, listeners } = fakeApi({ firefox: false });
+ load(api, false);
+ const page = "https://site.test/welcome";
+ listeners.responseStarted({ type: "main_frame", tabId: 1, frameId: 0, statusCode: 200, url: page, responseHeaders: [{ name: "Content-Type", value: "text/html; charset=UTF-8" }] });
+ listeners.determining({ id: 7, url: page, finalUrl: "https://cdn.test/x.exe", filename: "x.exe" }, () => {});
+ await settle();
+ const [m] = natives(calls);
+ assert.deepEqual([m.url, m.finalUrl], ["https://cdn.test/x.exe", ""], "the file's address, not the page's");
+ ok("Chrome: a page that went to the file by script isn't the file's address");
+}
+
// Chrome: one the app doesn't take goes on as the browser's own (its name confirmed).
{
const { api, calls, listeners } = fakeApi({ firefox: false, reply: { ok: false } });