Skip to content

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

Videos: no 100 % before the end, and the page's title instead of a hash (#344, #345) (#384)

Ahmed Nefzaoui0a5579c3abc9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed46fd98..7e88572e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- Video downloads: the progress no longer says 100 % while a video is still coming, when the site gives no total size, or between a video and its separate sound ([#344](https://github.com/anefzaoui/misterdownloadmanager/issues/344)). A video yt-dlp only knows by its address is named after the page, not a long hash ([#345](https://github.com/anefzaoui/misterdownloadmanager/issues/345)).
- **A YouTube playlist in Add URL** ([#338](https://github.com/anefzaoui/misterdownloadmanager/issues/338)) opens the video window with its videos, instead of saving the page as a file named "playlist".
- **Dailymotion's embedded player** ([#359](https://github.com/anefzaoui/misterdownloadmanager/issues/359)): its address is looked up as the video's own page, so the download button works on sites that embed one.
- 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.
diff --git a/ROADMAP.md b/ROADMAP.md
index 26ee0efe..4bc7baef 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -466,6 +466,9 @@ These ship in a later version, when they're ready.
### Bugs being looked into
+- πŸ”„ Video progress at 100 % while still downloading, and long encoded strings as file names
+ ([#344](https://github.com/anefzaoui/misterdownloadmanager/issues/344),
+ [#345](https://github.com/anefzaoui/misterdownloadmanager/issues/345)): fix in review
- πŸ”„ 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
diff --git a/crates/app/src/videodlg.rs b/crates/app/src/videodlg.rs
index 482969f1..4886d166 100644
--- a/crates/app/src/videodlg.rs
+++ b/crates/app/src/videodlg.rs
@@ -189,7 +189,15 @@ impl VideoDialog {
}
/// The choices for a looked-up video: merged qualities when ffmpeg is there.
- fn set_video(&mut self, v: Video) {
+ fn set_video(&mut self, mut v: Video) {
+ // No page reader for this site: the page's own title rather than a hash (#345).
+ if let Some(title) = self.context.video_title.as_deref().map(str::trim)
+ && !title.is_empty()
+ && self.page.trim() == self.from_browser
+ && mdm_tools::resolve::named_after_address(&v.title, &self.page)
+ {
+ v.title = title.to_owned();
+ }
let merge = self.tools.get_or_insert_with(tools).2.is_some();
let choices = mdm_tools::resolve::choices(&v, merge);
self.chosen = 0;
diff --git a/crates/ipc/src/lib.rs b/crates/ipc/src/lib.rs
index 56f0a135..202dd0a3 100644
--- a/crates/ipc/src/lib.rs
+++ b/crates/ipc/src/lib.rs
@@ -103,6 +103,9 @@ pub struct Command {
/// From the browser's download button over a video: open the Download video window for this
/// page (its address; an embedded player's own).
pub video_page: Option<String>,
+ /// The title of the page the button was clicked on: a video yt-dlp knows only by its address
+ /// is named by it.
+ pub video_title: Option<String>,
/// From that button's menu: never show it on this site (a host name) again.
pub panel_hide_site: Option<String>,
/// From the browser's right-click menu: the links of a page or a selection, offered in the
diff --git a/crates/nmhost/src/main.rs b/crates/nmhost/src/main.rs
index 0a545bfd..5b9046d5 100644
--- a/crates/nmhost/src/main.rs
+++ b/crates/nmhost/src/main.rs
@@ -104,6 +104,8 @@ struct Message {
/// the tab's media asked for it (#38).
video: bool,
src: Option<String>,
+ /// The page's title (`video`).
+ title: Option<String>,
/// The button's menu: keep it off this site (a host name).
hide_site: Option<String>,
/// The button's menu: open its settings in Options (`page`: the toolbar button's popup asks
@@ -424,6 +426,7 @@ fn video_command(
};
Ok(mdm_ipc::Command {
video_page: Some(src.unwrap_or_else(|| m.url.clone())),
+ video_title: m.title.clone().filter(|t| !t.trim().is_empty()),
referer,
cookies: m.cookies.clone().filter(|c| !c.is_empty()),
cookie_jar: m.cookie_jar.clone(),
diff --git a/crates/tools/src/resolve.rs b/crates/tools/src/resolve.rs
index 16d783e1..5eff71f3 100644
--- a/crates/tools/src/resolve.rs
+++ b/crates/tools/src/resolve.rs
@@ -112,6 +112,20 @@ struct RawFormat {
tbr: Option<f64>,
}
+/// Whether `title` is only the last part of `page`'s address, which is what yt-dlp calls a video
+/// on a site it has no page reader for (#345: on some servers that part is a long hash).
+pub fn named_after_address(title: &str, page: &str) -> bool {
+ let Some(last) = url::Url::parse(page).ok().and_then(|u| {
+ u.path_segments()
+ .and_then(|mut p| p.next_back().map(str::to_owned))
+ }) else {
+ return false;
+ };
+ let last = percent_encoding::percent_decode_str(&last).decode_utf8_lossy();
+ let stem = last.rsplit_once('.').map_or(last.as_ref(), |(s, _)| s);
+ !stem.is_empty() && title.trim() == stem
+}
+
/// Parse `yt-dlp -J` output.
pub fn parse(json: &[u8]) -> Option<Video> {
let raw: RawVideo = serde_json::from_slice(json).ok()?;
@@ -493,6 +507,19 @@ pub fn choices(v: &Video, can_merge: bool) -> Vec<Choice> {
#[cfg(test)]
mod tests {
+ #[test]
+ fn a_title_that_is_only_the_address() {
+ let hash = "SFp1NUcrZFRkRUVrUWlqM3paMitkakJIUW9JSFhOeEZkd0ZMNEc5UHpnZm5hRkY4Vis5MjlJU00xdDVqTk1vaw";
+ let page = format!("https://cdn.example/v/{hash}.mp4?sig=1");
+ assert!(named_after_address(hash, &page));
+ assert!(!named_after_address("A real title", &page));
+ assert!(!named_after_address("watch", "not an address"));
+ assert!(named_after_address(
+ "my clip",
+ "https://x.example/my%20clip.mp4"
+ ));
+ }
+
use super::*;
#[test]
diff --git a/crates/tools/src/video.rs b/crates/tools/src/video.rs
index c1b10bcd..840f7ece 100644
--- a/crates/tools/src/video.rs
+++ b/crates/tools/src/video.rs
@@ -415,11 +415,15 @@ fn supervise(
}
}
+/// The most the bar shows while yt-dlp still works.
+const MAX_WHILE_RUNNING: f64 = 0.999;
+
/// yt-dlp's progress lines (`MDMP <downloaded> <total> <estimate> <speed>`) made into one
/// steady figure. Each stream of a merged download (video, then audio) reports from 0 with its
/// own total, and a fragmented stream's total (HLS, DASH) is an estimate that moves with every
/// fragment: the streams are added up, the total never falls below the size the video window
-/// showed (`expected`, every stream), and the fraction done never goes back.
+/// showed (`expected`, every stream), and the fraction done goes back only when a stream's end
+/// had looked like the whole (no `expected`, the next stream starts).
struct Meter {
expected: Option<u64>,
/// The streams already finished, and the current one's last total and bytes.
@@ -454,34 +458,42 @@ impl Meter {
if got < self.last_got && self.last_got > 0 {
self.finished += self.last_total.max(self.last_got);
self.last_total = 0;
+ // Without the whole size from the start, the first stream's end looked like the
+ // whole download: the next stream's total pulls the bar back (#344).
+ if self.expected.is_none() {
+ self.frac = 0.0;
+ }
}
self.last_got = got;
if let Some(t) = total {
self.last_total = t;
}
let downloaded = self.finished + got;
+ p.downloaded = downloaded;
+ p.speed = f.get(3).copied().flatten().unwrap_or(0.0);
+ // Neither yt-dlp nor the video window knows how much is coming (a live stream, some
+ // HLS): no percentage rather than what came so far as the whole, 100 % (#344).
+ if self.last_total == 0 && self.expected.is_none() {
+ p.total = None;
+ return;
+ }
let mut whole = self.finished + self.last_total.max(got);
if let Some(e) = self.expected {
whole = whole.max(e);
}
- p.downloaded = downloaded;
- p.speed = f.get(3).copied().flatten().unwrap_or(0.0);
if whole == 0 {
p.total = None;
return;
}
- let frac = downloaded as f64 / whole as f64;
- if frac >= self.frac {
- self.frac = frac;
- p.total = Some(whole);
- } else {
- // The estimate grew: keep the bar where it was rather than move it back.
- p.total = Some(
- (downloaded as f64 / self.frac)
- .round()
- .max(downloaded as f64) as u64,
- );
- }
+ // 100 % is for the end (State::Done): another stream or the merge may still follow.
+ let frac = (downloaded as f64 / whole as f64).min(MAX_WHILE_RUNNING);
+ // When the estimate grew, the bar stays where it was rather than move back.
+ self.frac = self.frac.max(frac);
+ p.total = Some(
+ (downloaded as f64 / self.frac)
+ .round()
+ .max(whole.min(downloaded + 1) as f64) as u64,
+ );
}
}
@@ -1124,15 +1136,37 @@ mod tests {
"150 200 NA 5",
"200 200 NA 5",
];
- for expected in [None, Some(1800)] {
- let f = fractions(&run(expected, &lines));
- for w in f.windows(2) {
- assert!(w[1] >= w[0] - 1e-9, "went back: {f:?}");
- }
- let last = run(expected, &lines).pop().unwrap();
- assert_eq!(last.0, 1800);
- assert!((f[f.len() - 1] - 1.0).abs() < 1e-9, "{f:?}");
+ let f = fractions(&run(Some(1800), &lines));
+ for w in f.windows(2) {
+ assert!(w[1] >= w[0] - 1e-9, "went back: {f:?}");
}
+ let last = run(Some(1800), &lines).pop().unwrap();
+ assert_eq!(last.0, 1800);
+ assert!(f[f.len() - 1] > 0.99 && f[f.len() - 1] < 1.0, "{f:?}");
+ }
+
+ /// #344: with no size known from the start, the second stream brings the bar back from
+ /// where the first one's end had taken it, and it never says 100 % before the end.
+ #[test]
+ fn a_stream_ending_is_not_the_whole_download() {
+ let lines = [
+ "100 1000 NA 5",
+ "1000 1000 NA 5",
+ "50 500 NA 5",
+ "400 500 NA 5",
+ ];
+ let f = fractions(&run(None, &lines));
+ assert!(f.iter().all(|x| *x < 1.0), "100 % before the end: {f:?}");
+ assert!(f[2] < 0.75, "the first stream's 100 % stayed: {f:?}");
+ assert!(f[3] > f[2], "{f:?}");
+ }
+
+ /// #344: no total and no estimate for a stream, nothing said by the video window: no
+ /// percentage at all, and certainly not 100 %.
+ #[test]
+ fn nothing_known_is_no_percentage() {
+ let v = run(None, &["100 NA NA 5", "9000 NA NA 5"]);
+ assert_eq!(v, vec![(100, None), (9000, None)]);
}
/// The size the window showed counts both streams from the start: the first stream alone
diff --git a/docs/automation-api.schema.json b/docs/automation-api.schema.json
index 5ee544f6..45952750 100644
--- a/docs/automation-api.schema.json
+++ b/docs/automation-api.schema.json
@@ -561,6 +561,14 @@
"string",
"null"
]
+ },
+ "video_title": {
+ "default": null,
+ "description": "The title of the page the button was clicked on: a video yt-dlp knows only by its address\nis named by it.",
+ "type": [
+ "string",
+ "null"
+ ]
}
},
"required": [
diff --git a/extension/background.js b/extension/background.js
index 10380de4..3c849b39 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -907,6 +907,17 @@ async function mediaList(tabId) {
return out;
}
+// A file's name from the tab's title when its address ends in a long hash (#345), else none: the
+// app names it from the address, as for any download.
+function titledName(url, title) {
+ const last = pathOf(url).split("/").pop() || "";
+ const dot = last.lastIndexOf(".");
+ const stem = dot > 0 ? last.slice(0, dot) : last;
+ const name = String(title || "").replace(/[\\/:*?"<>|]/g, " ").trim().slice(0, 150);
+ const hash = stem.length >= 24 && /^[A-Za-z0-9=_-]+$/.test(stem) && (stem.match(/[-_]/g) || []).length <= 2;
+ return hash && name ? `${name}${dot > 0 ? last.slice(dot) : ""}` : "";
+}
+
// One of the tab's media, handed to the app as the popup asked: a stream to the Download video
// window (yt-dlp), a file as a download; with the page that played it (the referrer), the cookies
// its own server gets, and the browser's User-Agent (`native`). A protected one is never sent.
@@ -939,7 +950,7 @@ async function mediaDownload(tabId, url) {
...(ctx.incognito ? { private: true } : {}),
});
}
- return handOff({ url: it.url, referrer: page, size: it.size, mime: it.mime, explicit: true, ...ctx });
+ return handOff({ url: it.url, referrer: page, size: it.size, mime: it.mime, explicit: true, filename: titledName(it.url, tab.title), ...ctx });
}
// ---- the hand-off ------------------------------------------------------------------------
diff --git a/tools/extension/test.mjs b/tools/extension/test.mjs
index 3a6d85d2..bdd380a1 100644
--- a/tools/extension/test.mjs
+++ b/tools/extension/test.mjs
@@ -796,6 +796,13 @@ const MPD = (protect) => `<?xml version="1.0"?>
await popupAsk(listeners, { type: "media-download", tab: 9, url: "https://files.test/movie.mp4" });
const f = natives(calls).find((m) => m.url === "https://files.test/movie.mp4");
assert.deepEqual([f.explicit, f.referrer, f.size, f.mime, f.video], [true, "https://watch.test/v/1", 52428800, "video/mp4", undefined]);
+ assert.equal(f.filename, "", "a file with a name of its own is named by its address");
+ // #345: an address that ends in a long hash names nothing: the tab's title does.
+ const hashed = "https://files.test/SFp1NUcrZFRkRUVrUWlqM3paMitkakJIUW9JSFhOeEZkd0ZMNEc5UHpnZm5hRkY4Vis5MjlJU00xdDVqTk1vaw.mp4";
+ listeners.responseStarted({ tabId: 9, frameId: 0, type: "media", url: hashed, responseHeaders: [{ name: "Content-Type", value: "video/mp4" }, { name: "Content-Length", value: "52428800" }] });
+ await settle();
+ await popupAsk(listeners, { type: "media-download", tab: 9, url: hashed });
+ assert.equal(natives(calls).find((m) => m.url === hashed).filename, "A film.mp4");
const before = natives(calls).length;
assert.deepEqual(await popupAsk(listeners, { type: "media-download", tab: 9, url: "https://drm.test/p/manifest.mpd" }), { ok: false, why: "drm" });
assert.deepEqual(await popupAsk(listeners, { type: "media-download", tab: 9, url: "https://evil.test/x.mp4" }), { ok: false, why: "gone" });
@@ -805,7 +812,7 @@ const MPD = (protect) => `<?xml version="1.0"?>
// A move within the page keeps the list; another page clears it; so does closing the tab.
listeners.tabUpdated(9, { url: "https://watch.test/v/1#t=30" });
await settle();
- assert.equal((await popupAsk(listeners, { type: "media", tab: 9 })).media.length, 9);
+ assert.equal((await popupAsk(listeners, { type: "media", tab: 9 })).media.length, 10);
listeners.tabUpdated(9, { url: "https://watch.test/v/2" });
await settle();
assert.equal((await popupAsk(listeners, { type: "media", tab: 9 })).media.length, 0);