Skip to content

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

Videos a site's program sends, named by what they are: the page's title or file= name and the real type, not stream.php (#695, #800) (#840)

Ahmed Nefzaouied0cf8d183b4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a0ad86ff..5674862e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- A video a site sends through a program's address (`stream.php?file=lecture.mp4`, `remote_control.php`, many lecture and video sites do) is named by what it is, not by the program: MDM took the name and the type from the address's last part, so the file was saved as `stream.php`, the browser's media list showed **remote_control.php · PHP**, and the Download video window offered **PHP** and then failed ("The extracted extension (php) is unusual and will be skipped for safety reasons"). Now a name whose ending is a program's (`.php`, `.asp`, `.aspx`, `.jsp`, `.cgi` and the like), a page's or none at all takes its type from the address's `file=` name, else from what the server says it sends (video/mp4 is `.mp4`), else from the file's first bytes; a video from the browser whose address names nothing (a program, a bare number, `videoplayback`) is named by its page's title, with the **Prefix media file names with the page title** switch on or off; and a name the server gives (Content-Disposition) still wins. The media list shows that name and type (**Lecture 1.mp4 · MP4**), the button over a video says MP4 instead of PHP, and the Download video window saves such a video as an MP4. Only media, picture, document and archive types are taken this way, never a program's ([#695](https://github.com/anefzaoui/misterdownloadmanager/issues/695), [#800](https://github.com/anefzaoui/misterdownloadmanager/issues/800)).
- Copying several links at once no longer opens **Download File Info** with all of them run together as one address (with **Offer to download links copied to the clipboard** on): a copied text with spaces or line breaks in it is not one link, and is left for **Add batch download from clipboard** ([#709](https://github.com/anefzaoui/misterdownloadmanager/issues/709)).
- Windows: MDM follows the Group Policy **Do not preserve zone information in file attachments**, as browsers do: with it on, for the computer or for you, downloads no longer get the mark that says they came from the internet (the Mark of the Web). MDM added it to every download whatever the policy said. A new option, **Options → Save to → Mark downloaded files as coming from the internet** (on by default), turns the mark off for MDM alone, on every system: Windows' Mark of the Web, macOS' quarantine and Linux's origin attributes ([#813](https://github.com/anefzaoui/misterdownloadmanager/issues/813)).
- **Tasks → Import** no longer freezes the window on a large file, or on one that isn't a list of addresses (a video, an archive, another program's backup picked by mistake): MDM read the whole file and looked through it for web addresses on the window's own thread, so a backup of several gigabytes kept the window frozen. The file is now read and searched beside the window, the status strip says **Reading** and the file's name meanwhile, and a file over 64 MB, far more than any list of links holds, is refused at once with a message that says so. Link grabber also takes a long list without a pause: it compared each new link with every link already in it, so 10,000 links made 50 million comparisons on the window's thread ([#805](https://github.com/anefzaoui/misterdownloadmanager/issues/805)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 0c943931..c611b839 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -556,6 +556,12 @@ Bug fixes from the first days of 0.5.0, a Safari extension, and more file types.
These ship in the next version.
+- ✅ A video a site sends through a program's address (`stream.php?file=…`,
+ `remote_control.php`) is named by what it is: the page's title (or the address's `file=` name)
+ and its real type, `Lecture.mp4`, not `stream.php`; the browser's media list shows that name
+ and type, and the Download video window saves it instead of failing on its `.php`
+ ([#695](https://github.com/anefzaoui/misterdownloadmanager/issues/695),
+ [#800](https://github.com/anefzaoui/misterdownloadmanager/issues/800))
- ✅ **Add batch download from clipboard** reads every link copied (a list, a forum post): http,
ftp and magnet links, each once, ticked in Link grabber, started or queued together with one
summary at the end; a copied address with a number in it (`…/ep01.mp4`) opens Batch download
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 805adc1b..b9addec0 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -2811,6 +2811,8 @@ impl App {
if let Some(file) = drive_file_behind_player(&cmd) {
cmd.video_page = None;
cmd.url = Some(file);
+ // Drive names its file itself; its page's title ("… - Google Drive") doesn't.
+ cmd.video_title = None;
}
// The button over a video that plays a plain file (#703): downloaded as any file, at
// once and without a window (its page the referrer), as Download File Info's Start would.
@@ -2932,7 +2934,7 @@ impl App {
let name = cmd
.name
.clone()
- .unwrap_or_else(|| mdm_engine::naming::file_name(None, &url));
+ .unwrap_or_else(|| crate::model::browser_guess(&url, &cmd));
let name = mdm_engine::naming::sanitize(&name);
// The automation API's `category` (by its key) and `queue` (by name), when given.
let category = cmd
@@ -3041,6 +3043,9 @@ impl App {
on_file_created: Some(mark_hook(url, context.referer.as_deref())),
// The browser's own download's type: a web page instead is an error (#533).
expected_type: context.mime.clone(),
+ // The page a media file was played on (#800): a file whose address names nothing
+ // (a script, a bare id) is named by its title when the engine names it.
+ page_title: context.video_title.clone(),
..Options::default()
};
RequestParts { headers, opts }
@@ -10685,7 +10690,7 @@ impl App {
let name = context
.name
.clone()
- .unwrap_or_else(|| mdm_engine::naming::file_name(None, &url));
+ .unwrap_or_else(|| crate::model::browser_guess(&url, &context));
let name = mdm_engine::naming::sanitize(&name);
let category = Category::of(&name);
let dir = self.settings.category_dir(category, &self.downloads);
diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rs
index 01b8df8b..d7adfa89 100644
--- a/crates/app/src/dialogs.rs
+++ b/crates/app/src/dialogs.rs
@@ -1089,7 +1089,7 @@ impl FileInfo {
.filter(|n| !n.is_empty());
let name = from_browser
.clone()
- .unwrap_or_else(|| mdm_engine::naming::file_name(None, &new.url));
+ .unwrap_or_else(|| crate::model::browser_guess(&new.url, &context));
let category = Category::of(&name);
let folder = crate::model::category_folder(category, &downloads, &dirs);
let mut place = SaveAsPlace::new(Some(ctx));
diff --git a/crates/app/src/model.rs b/crates/app/src/model.rs
index cd6049b3..5bdcf237 100644
--- a/crates/app/src/model.rs
+++ b/crates/app/src/model.rs
@@ -325,6 +325,21 @@ pub fn default_downloads<'a>(
.unwrap_or(std::borrow::Cow::Borrowed(downloads))
}
+/// The name a download from `context` has before its server answers, when nobody named it: the
+/// address's ([`mdm_engine::naming::answer_name`]), typed by the browser's own type for it and,
+/// for a page's media whose address names nothing (a script, a bare id), its page's title
+/// (#695, #800). The engine names it again from the server's answer as it starts.
+pub fn browser_guess(url: &url::Url, context: &mdm_ipc::Command) -> String {
+ mdm_engine::naming::answer_name(
+ url,
+ &mdm_engine::naming::Answer {
+ content_type: context.mime.as_deref(),
+ title: context.video_title.as_deref(),
+ ..Default::default()
+ },
+ )
+}
+
/// The category's folder: the one chosen in Options → Save to (or remembered from Download
/// File Info), else the default under [`default_downloads`] (#556).
pub fn category_folder(cat: Category, downloads: &Path, dirs: &[(String, String)]) -> PathBuf {
diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rs
index eb052c73..0f775afa 100644
--- a/crates/engine/src/download.rs
+++ b/crates/engine/src/download.rs
@@ -171,6 +171,10 @@ pub struct Options {
/// type is the server refusing MDM (a firewall's "The requested URL was rejected"), an error
/// and never saved as the file (#533, `expects_other_file`).
pub expected_type: Option<String>,
+ /// From the browser: the title of the page a media file was played on (#800). A download
+ /// the engine names ([`Destination::Dir`]) whose address names nothing (a script, a bare id,
+ /// `videoplayback`) is named by it ([`naming::answer_name`]).
+ pub page_title: Option<String>,
/// The most one request asks for (bytes): every request, the first one too, is a range of
/// at most this many, the next one following on the same connection. For servers that slow
/// a long answer down (YouTube's media servers serve 10 MB ranges at full speed and a whole
@@ -258,6 +262,7 @@ impl Default for Options {
post: None,
on_file_created: None,
expected_type: None,
+ page_title: None,
request_cap: None,
slow_disk: None,
}
@@ -936,8 +941,14 @@ pub async fn probe_kept(
StatusCode::OK => (head.len, true),
_ => (head.len, false),
};
- let cd = header_text(&head.headers, header::CONTENT_DISPOSITION);
- let file_name = name_for(cd.as_deref(), &final_url, unlocked.as_ref());
+ // A name its address and the server leave untyped: the bytes' type, when they are the
+ // file's first (#800).
+ let (body, sniffed) = if from_zero && names_by_bytes(&head, unlocked.as_ref()) {
+ sniff_body(body, &CancellationToken::new()).await?
+ } else {
+ (body, None)
+ };
+ let file_name = name_for(&head, sniffed, unlocked.as_ref(), opts);
let info = ProbeInfo {
final_url,
size: size.or(unlocked.as_ref().and_then(|u| u.size)),
@@ -976,12 +987,63 @@ pub fn hop_client(opts: &Options, url: &Url) -> Result<Client, Error> {
}
/// The file's name: the server's (Content-Disposition), else the service's (#44), else the
-/// address's.
-fn name_for(cd: Option<&str>, url: &Url, unlocked: Option<&crate::unlock::Unlocked>) -> String {
- match (cd, unlocked.and_then(|u| u.file_name.as_deref())) {
+/// address's, typed by the server's `Content-Type` or the bytes' own type (`sniffed`), and named
+/// by the page's title when the address names nothing (#695, #800: [`naming::answer_name`]).
+fn name_for(
+ head: &Head,
+ sniffed: Option<&str>,
+ unlocked: Option<&crate::unlock::Unlocked>,
+ opts: &Options,
+) -> String {
+ let cd = header_text(&head.headers, header::CONTENT_DISPOSITION);
+ match (&cd, unlocked.and_then(|u| u.file_name.as_deref())) {
(None, Some(name)) if !name.trim().is_empty() => naming::sanitize(name),
- _ => naming::file_name(cd, url),
+ _ => naming::answer_name(
+ &head.url,
+ &naming::Answer {
+ disposition: cd.as_deref(),
+ content_type: header_str(&head.headers, header::CONTENT_TYPE),
+ sniffed,
+ title: opts.page_title.as_deref(),
+ },
+ ),
+ }
+}
+
+/// Whether the answer's first bytes are needed for its name (`name_for`): it is named by its
+/// address, whose name doesn't say the file's type, and neither does the server (#800).
+fn names_by_bytes(head: &Head, unlocked: Option<&crate::unlock::Unlocked>) -> bool {
+ let cd = header_text(&head.headers, header::CONTENT_DISPOSITION);
+ let service = unlocked
+ .and_then(|u| u.file_name.as_deref())
+ .is_some_and(|n| !n.trim().is_empty());
+ !(cd.is_none() && service)
+ && naming::needs_sniff(
+ &head.url,
+ cd.as_deref(),
+ header_str(&head.headers, header::CONTENT_TYPE),
+ )
+}
+
+/// The type `body`'s first bytes show ([`naming::sniff`]), and the body that still gives them:
+/// read up to [`naming::SNIFF_BYTES`] (less at its end).
+async fn sniff_body(
+ mut body: Body,
+ cancel: &CancellationToken,
+) -> Result<(Body, Option<&'static str>), Error> {
+ let mut seen: Vec<u8> = Vec::new();
+ while seen.len() < naming::SNIFF_BYTES {
+ let next = tokio::select! {
+ _ = cancel.cancelled() => return Err(Error::Cancelled),
+ n = body.chunk() => n?,
+ };
+ match next {
+ Some(c) => seen.extend_from_slice(&c),
+ None => break,
+ }
}
+ let ext = naming::sniff(&seen);
+ Ok((Body::Prefixed(Some(Bytes::from(seen)), Box::new(body)), ext))
}
/// `opts.unlocker`'s direct link for `url` (#44), noted in the event log (never the link
@@ -1331,6 +1393,9 @@ pub(crate) enum Body {
/// An answer to the browser-like connection (#668, `crate::browserlike`).
#[cfg_attr(not(feature = "browser-connection"), allow(dead_code))]
Browser(crate::browserlike::Stream),
+ /// A body whose first bytes were read already (to know the file's type, #800): they come
+ /// first, then the rest.
+ Prefixed(Option<bytes::Bytes>, Box<Body>),
}
impl Body {
@@ -1340,6 +1405,10 @@ impl Body {
Body::Http(r) => Ok(r.chunk().await?),
Body::Ftp(t) => t.chunk().await,
Body::Browser(b) => b.chunk().await,
+ Body::Prefixed(first, rest) => match first.take().filter(|b| !b.is_empty()) {
+ Some(b) => Ok(Some(b)),
+ None => Box::pin(rest.chunk()).await,
+ },
}
}
@@ -1349,6 +1418,7 @@ impl Body {
Body::Http(r) => r.content_length(),
Body::Ftp(t) => t.expected(),
Body::Browser(b) => b.len(),
+ Body::Prefixed(_, rest) => rest.len(),
}
}
@@ -1364,6 +1434,7 @@ impl Body {
Body::Ftp(t) => t.done(at_end).await,
// Its connection isn't pooled for another request: there is only the one.
Body::Browser(_) => {}
+ Body::Prefixed(_, rest) => Box::pin(rest.done(at_end)).await,
}
}
}
@@ -1868,9 +1939,16 @@ async fn run_fresh(
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
+ // A file the engine names whose address and server leave its type unsaid: its first bytes
+ // say it (#800), and still come first to the file.
+ let (body, sniffed) =
+ if matches!(req.dest, Destination::Dir(_)) && names_by_bytes(&head, unlocked.as_ref()) {
+ sniff_body(body, cancel).await?
+ } else {
+ (body, None)
+ };
let (dest, _reservation, file) = open_destination(&req.dest, size, &opts, || {
- let cd = header_text(&head.headers, header::CONTENT_DISPOSITION);
- name_for(cd.as_deref(), &final_url, unlocked.as_ref())
+ name_for(&head, sniffed, unlocked.as_ref(), &opts)
})
.await?;
downloading(shared, &dest, size, ranges);
diff --git a/crates/engine/src/naming.rs b/crates/engine/src/naming.rs
index 332c2de7..e7bba55e 100644
--- a/crates/engine/src/naming.rs
+++ b/crates/engine/src/naming.rs
@@ -7,21 +7,316 @@ use std::sync::{Mutex, OnceLock};
use percent_encoding::percent_decode_str;
use url::Url;
-/// File name from `Content-Disposition`, else the last URL path segment, else `download`.
-/// Always safe to use as a single path component on Windows and Unix.
+/// File name from `Content-Disposition`, else the address's ([`address_name`]), else
+/// `download`. Always safe to use as a single path component on Windows and Unix.
pub fn file_name(content_disposition: Option<&str>, url: &Url) -> String {
- let from_url = || {
- url.path_segments()
- .and_then(|mut s| s.next_back())
- .map(|s| percent_decode_str(s).decode_utf8_lossy().into_owned())
+ answer_name(
+ url,
+ &Answer {
+ disposition: content_disposition,
+ ..Answer::default()
+ },
+ )
+}
+
+/// What is known of a file besides its address, for its name: the server's answer
+/// (`Content-Disposition`, `Content-Type`), the type its first bytes show (`sniffed`, an
+/// extension from [`sniff`]), and the title of the page it was played on, when the browser sent
+/// one with a page's media (#695, #800).
+#[derive(Clone, Copy, Debug, Default)]
+pub struct Answer<'a> {
+ pub disposition: Option<&'a str>,
+ pub content_type: Option<&'a str>,
+ pub sniffed: Option<&'a str>,
+ pub title: Option<&'a str>,
+}
+
+/// The file's name from all that is known of it (#695, #800), safe as one path component:
+///
+/// 1. the server's `Content-Disposition` name, as it gives it: it wins over everything;
+/// 2. else the address's name ([`address_name`]: a script's `file=` value, else its last part);
+/// 3. a name whose extension doesn't say its type (a script's, `stream.php`; a page's; none, a
+/// bare id) takes the type's: the server's `Content-Type`, else its bytes' (`sniffed`). Only
+/// the media, picture, document and archive types of [`TYPES`], never one that runs;
+/// 4. a name that means nothing ([`means_nothing`]: a script's, a bare id, `videoplayback`, a
+/// long hash) gives way to the page's `title` when there is one, with that extension.
+///
+/// A real file name (`clip.mp4`, `setup.zip`, a script's `file=` value) is never changed by the
+/// type or the title.
+pub fn answer_name(url: &Url, a: &Answer) -> String {
+ if let Some(name) = a.disposition.and_then(disposition_name) {
+ // A header may carry a path; keep only its last component.
+ return sanitize(last_component(&name));
+ }
+ let last = last_segment(url);
+ let given = query_file_name(url).filter(|_| names_nothing(&last));
+ let named = given.is_some();
+ let name = given.unwrap_or(last);
+ let typed = if untyped(&name) {
+ a.content_type
+ .and_then(type_extension)
+ .or_else(|| a.sniffed.filter(|e| is_typed_extension(e)))
+ } else {
+ None
};
- let name = content_disposition
- .and_then(disposition_name)
- .or_else(from_url)
- .unwrap_or_default();
- // A header may carry a path; keep only its last component.
- let name = name.rsplit(['/', '\\']).next().unwrap_or_default();
- sanitize(name)
+ let title = a
+ .title
+ .map(clean_title)
+ .filter(|t| !t.is_empty() && !named && means_nothing(&name));
+ let (stem, ext) = split_extension(&name);
+ let stem = match title.as_deref() {
+ Some(t) => t,
+ None if stem.trim().is_empty() => "download",
+ None => stem,
+ };
+ let name = match typed.or(ext) {
+ Some(e) => format!("{stem}.{e}"),
+ None => stem.to_owned(),
+ };
+ sanitize(&name)
+}
+
+/// The address's last path part, percent-decoded (empty for a folder's address).
+fn last_segment(url: &Url) -> String {
+ url.path_segments()
+ .and_then(|mut s| s.next_back())
+ .map(|s| percent_decode_str(s).decode_utf8_lossy().into_owned())
+ .unwrap_or_default()
+}
+
+/// A path's last component (`a/b\c.zip` → `c.zip`).
+fn last_component(name: &str) -> &str {
+ name.rsplit(['/', '\\']).next().unwrap_or_default()
+}
+
+/// The address's own name for its file, not sanitized: a script's `file=` or `filename=` value
+/// when it names a file of a known type (`stream.php?file=FL262-1E01-4.mp4` →
+/// `FL262-1E01-4.mp4`, #695), else its last path part.
+pub fn address_name(url: &Url) -> String {
+ let last = last_segment(url);
+ query_file_name(url)
+ .filter(|_| names_nothing(&last))
+ .unwrap_or(last)
+}
+
+/// The address's `file=` / `filename=` value (its last component) when its extension is a known
+/// type's ([`TYPES`]): a value naming a program, or anything else, is never taken.
+fn query_file_name(url: &Url) -> Option<String> {
+ url.query_pairs()
+ .filter(|(k, _)| k.eq_ignore_ascii_case("file") || k.eq_ignore_ascii_case("filename"))
+ .map(|(_, v)| last_component(v.trim()).trim().to_owned())
+ .find(|v| match split_extension(v) {
+ (stem, Some(ext)) => {
+ !stem.trim().is_empty() && is_typed_extension(&ext.to_ascii_lowercase())
+ }
+ _ => false,
+ })
+}
+
+/// `name`'s stem and extension (`clip.mp4` → `clip`, `mp4`). `.profile`, `clip` and `Mr. Smith`
+/// have none.
+fn split_extension(name: &str) -> (&str, Option<&str>) {
+ match name.rsplit_once('.') {
+ Some((stem, ext))
+ if !stem.is_empty() && !ext.is_empty() && !ext.contains(char::is_whitespace) =>
+ {
+ (stem, Some(ext))
+ }
+ _ => (name, None),
+ }
+}
+
+/// The extensions of programs that answer on a web server: an address ending in one names the
+/// program, not the file it sends (`stream.php`, `remote_control.php`, `download.aspx`).
+pub const SCRIPT_EXTENSIONS: &[&str] = &[
+ "php", "php3", "php4", "php5", "phtml", "asp", "aspx", "ashx", "axd", "jsp", "jspx", "do",
+ "action", "cgi", "pl", "cfm", "py", "rb",
+];
+
+/// A web page's extensions: a file of another type served at such an address takes its type's.
+pub const PAGE_EXTENSIONS: &[&str] = &["htm", "html", "xhtml", "shtml", "dhtml"];
+
+/// Whether `name`'s extension is a web server's program's ([`SCRIPT_EXTENSIONS`]).
+pub fn is_script_name(name: &str) -> bool {
+ split_extension(name)
+ .1
+ .is_some_and(|e| SCRIPT_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
+}
+
+/// A name whose extension doesn't say what the file is: a script's, a page's, or none.
+fn untyped(name: &str) -> bool {
+ match split_extension(name).1 {
+ None => true,
+ Some(e) => {
+ let e = e.to_ascii_lowercase();
+ SCRIPT_EXTENSIONS.contains(&e.as_str()) || PAGE_EXTENSIONS.contains(&e.as_str())
+ }
+ }
+}
+
+/// An address's last part that names no file, so its `file=` value does: a script's, or one
+/// without an extension.
+fn names_nothing(last: &str) -> bool {
+ split_extension(last).1.is_none() || is_script_name(last)
+}
+
+/// A name that says nothing of what the file is, for a page's title to replace (#345, #800): a
+/// script's (`remote_control.php`), none, one without an extension (a bare id, `videoplayback`),
+/// or a long hash (`a3f9…e1.mp4`). The browser extension's `meansNothing` is the same test.
+pub fn means_nothing(name: &str) -> bool {
+ let (stem, ext) = split_extension(name);
+ let hash = stem.chars().count() >= 24
+ && stem
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '=' | '_' | '-'))
+ && stem.chars().filter(|c| matches!(c, '-' | '_')).count() <= 2;
+ ext.is_none() || is_script_name(name) || hash
+}
+
+/// A page's title as a file's stem: what a file name can't hold becomes a space, spaces are
+/// collapsed, at most 150 characters, no trailing dot (the browser extension's `cleanTitle`).
+pub fn clean_title(title: &str) -> String {
+ let spaced: String = title
+ .chars()
+ .filter(|c| !is_format_char(*c))
+ .map(|c| {
+ if c.is_control() || r#"<>:"/\|?*"#.contains(c) {
+ ' '
+ } else {
+ c
+ }
+ })
+ .collect();
+ let words = spaced.split_whitespace().collect::<Vec<_>>().join(" ");
+ let cut: String = words.chars().take(150).collect();
+ cut.trim_end_matches(['.', ' ']).to_owned()
+}
+
+/// The types a file's extension is taken from, with that extension (the browser extension's
+/// `TYPE_EXTENSIONS` holds the same, which `tools/extension/test.mjs` checks). Media, pictures,
+/// documents and archives only: a type that runs (a program, a script, a page) never names a
+/// file's extension.
+pub const TYPES: &[(&str, &str)] = &[
+ ("video/mp4", "mp4"),
+ ("video/x-m4v", "m4v"),
+ ("video/webm", "webm"),
+ ("video/x-matroska", "mkv"),
+ ("video/quicktime", "mov"),
+ ("video/x-msvideo", "avi"),
+ ("video/avi", "avi"),
+ ("video/x-ms-wmv", "wmv"),
+ ("video/x-flv", "flv"),
+ ("video/mpeg", "mpg"),
+ ("video/mp2t", "ts"),
+ ("video/3gpp", "3gp"),
+ ("video/3gpp2", "3g2"),
+ ("video/ogg", "ogv"),
+ ("audio/mpeg", "mp3"),
+ ("audio/mp3", "mp3"),
+ ("audio/mp4", "m4a"),
+ ("audio/x-m4a", "m4a"),
+ ("audio/aac", "aac"),
+ ("audio/aacp", "aac"),
+ ("audio/webm", "weba"),
+ ("audio/ogg", "ogg"),
+ ("audio/opus", "opus"),
+ ("audio/flac", "flac"),
+ ("audio/x-flac", "flac"),
+ ("audio/wav", "wav"),
+ ("audio/x-wav", "wav"),
+ ("audio/wave", "wav"),
+ ("audio/x-ms-wma", "wma"),
+ ("application/ogg", "ogg"),
+ ("image/jpeg", "jpg"),
+ ("image/png", "png"),
+ ("image/gif", "gif"),
+ ("image/webp", "webp"),
+ ("image/avif", "avif"),
+ ("application/pdf", "pdf"),
+ ("application/epub+zip", "epub"),
+ ("application/zip", "zip"),
+ ("application/x-zip-compressed", "zip"),
+ ("application/x-7z-compressed", "7z"),
+ ("application/vnd.rar", "rar"),
+ ("application/x-rar-compressed", "rar"),
+ ("application/gzip", "gz"),
+ ("application/x-gzip", "gz"),
+];
+
+/// The extension a `Content-Type` value names (`video/mp4; codecs=…` → `mp4`), if [`TYPES`] has
+/// it.
+pub fn type_extension(content_type: &str) -> Option<&'static str> {
+ let mime = content_type.split(';').next()?.trim();
+ TYPES
+ .iter()
+ .find(|(t, _)| t.eq_ignore_ascii_case(mime))
+ .map(|(_, e)| *e)
+}
+
+/// Whether `ext` is one of [`TYPES`]' extensions (every one [`sniff`] gives is), in any case.
+pub fn is_typed_extension(ext: &str) -> bool {
+ TYPES.iter().any(|(_, e)| e.eq_ignore_ascii_case(ext))
+}
+
+/// How many first bytes [`sniff`] reads.
+pub const SNIFF_BYTES: usize = 64;
+
+/// The media type a file's first bytes show, as its extension: the MP4 family's (`ftyp`),
+/// Matroska or WebM (EBML), Ogg, FLAC, MP3 (an ID3 tag or a Layer III frame), AAC (ADTS), WAVE,
+/// AVI, FLV. None for anything else: a file is never named a program by its bytes.
+pub fn sniff(head: &[u8]) -> Option<&'static str> {
+ let at = |i: usize, sig: &[u8]| head.get(i..i + sig.len()) == Some(sig);
+ if at(4, b"ftyp") {
+ return Some(match head.get(8..12).unwrap_or_default() {
+ b"M4A " | b"M4B " => "m4a",
+ b"qt " => "mov",
+ b if b.starts_with(b"3g") => "3gp",
+ _ => "mp4",
+ });
+ }
+ if at(0, &[0x1A, 0x45, 0xDF, 0xA3]) {
+ let webm = head.windows(4).any(|w| w == b"webm");
+ return Some(if webm { "webm" } else { "mkv" });
+ }
+ if at(0, b"OggS") {
+ return Some("ogg");
+ }
+ if at(0, b"fLaC") {
+ return Some("flac");
+ }
+ if at(0, b"ID3") {
+ return Some("mp3");
+ }
+ if at(0, b"RIFF") && at(8, b"WAVE") {
+ return Some("wav");
+ }
+ if at(0, b"RIFF") && at(8, b"AVI ") {
+ return Some("avi");
+ }
+ if at(0, b"FLV\x01") {
+ return Some("flv");
+ }
+ if let [0xFF, b, c, ..] = *head {
+ // ADTS: a 12-bit sync and layer 00.
+ if b & 0xF6 == 0xF0 {
+ return Some("aac");
+ }
+ // An MPEG audio frame: an 11-bit sync, a version that isn't reserved, Layer III, and a
+ // bitrate and sample rate that aren't either (a UTF-16 text's FF FE isn't one).
+ let (version, layer) = ((b >> 3) & 3, (b >> 1) & 3);
+ if b & 0xE0 == 0xE0 && version != 1 && layer == 1 && c >> 4 != 0xF && (c >> 2) & 3 != 3 {
+ return Some("mp3");
+ }
+ }
+ None
+}
+
+/// Whether the file's bytes must be looked at for its name ([`sniff`]): it is named by its
+/// address, whose name doesn't say its type, and the server's `Content-Type` doesn't either.
+pub fn needs_sniff(url: &Url, disposition: Option<&str>, content_type: Option<&str>) -> bool {
+ disposition.and_then(disposition_name).is_none()
+ && untyped(&address_name(url))
+ && content_type.and_then(type_extension).is_none()
}
/// The file name a `Content-Disposition` value suggests (RFC 6266), read as browsers do:
@@ -713,6 +1008,267 @@ mod tests {
assert_eq!(sanitize("تقرير-été-日本.zip"), "تقرير-été-日本.zip");
}
+ fn named(u: &str, a: Answer) -> String {
+ answer_name(&url(u), &a)
+ }
+
+ fn typed(content_type: &str) -> Answer<'_> {
+ Answer {
+ content_type: Some(content_type),
+ ..Answer::default()
+ }
+ }
+
+ /// #695, #800: a video a script sends is named by its type, not the script's extension.
+ #[test]
+ fn a_scripts_answer_takes_its_types_extension() {
+ let mp4 = typed("video/mp4");
+ assert_eq!(named("http://x/stream.php?id=7", mp4), "stream.mp4");
+ assert_eq!(
+ named(
+ "http://x/v/remote_control.php?a=1",
+ typed("video/mp4; codecs=avc1")
+ ),
+ "remote_control.mp4"
+ );
+ assert_eq!(named("http://x/get.aspx", typed("audio/mpeg")), "get.mp3");
+ assert_eq!(named("http://x/dl.cgi", typed("application/pdf")), "dl.pdf");
+ assert_eq!(named("http://x/watch.html", mp4), "watch.mp4");
+ // A bare id and Google's `videoplayback` have no extension: the type gives one.
+ assert_eq!(named("http://x/media/123456", mp4), "123456.mp4");
+ assert_eq!(
+ named("http://x/videoplayback?itag=18", mp4),
+ "videoplayback.mp4"
+ );
+ assert_eq!(named("http://x/", mp4), "download.mp4");
+ // A type that isn't a file's (a page, nothing said) leaves the name as it is.
+ assert_eq!(
+ named("http://x/stream.php", typed("text/html")),
+ "stream.php"
+ );
+ assert_eq!(
+ named("http://x/stream.php", typed("application/octet-stream")),
+ "stream.php"
+ );
+ assert_eq!(
+ named("http://x/stream.php", Answer::default()),
+ "stream.php"
+ );
+ }
+
+ /// #695: the script's `file=` (or `filename=`) value names it, before and after the answer.
+ #[test]
+ fn a_scripts_file_value_names_it() {
+ let u = "http://x/baigiang/stream.php?file=FL262-1E01-4.mp4&token=abc";
+ assert_eq!(file_name(None, &url(u)), "FL262-1E01-4.mp4");
+ assert_eq!(named(u, typed("video/mp4")), "FL262-1E01-4.mp4");
+ assert_eq!(
+ file_name(None, &url("http://x/get.php?filename=a%2Fb%2Fclip.webm")),
+ "clip.webm"
+ );
+ // No type known from the value: the script's name stays.
+ assert_eq!(
+ file_name(None, &url("http://x/get.php?file=notes")),
+ "get.php"
+ );
+ // A real name in the path is the file's: the query doesn't change it.
+ assert_eq!(
+ file_name(None, &url("http://x/files/movie.mkv?file=other.mp4")),
+ "movie.mkv"
+ );
+ // The page's title doesn't replace a real name.
+ let titled = Answer {
+ title: Some("Lecture one"),
+ ..typed("video/mp4")
+ };
+ assert_eq!(named(u, titled), "FL262-1E01-4.mp4");
+ }
+
+ /// Content-Disposition still wins over the type, the `file=` value and the title.
+ #[test]
+ fn the_servers_name_wins_over_type_and_title() {
+ let a = Answer {
+ disposition: Some("attachment; filename=\"Lecture 1.mp4\""),
+ content_type: Some("video/webm"),
+ sniffed: Some("mkv"),
+ title: Some("A page"),
+ };
+ assert_eq!(
+ named("http://x/stream.php?file=other.mp4", a),
+ "Lecture 1.mp4"
+ );
+ }
+
+ /// A real file name is never changed by the type, the bytes or a title.
+ #[test]
+ fn real_names_are_left_alone() {
+ let a = Answer {
+ content_type: Some("video/webm"),
+ sniffed: Some("mkv"),
+ title: Some("A page"),
+ ..Answer::default()
+ };
+ assert_eq!(named("http://x/clip.mp4", a), "clip.mp4");
+ assert_eq!(named("http://x/setup.zip", typed("video/mp4")), "setup.zip");
+ assert_eq!(named("http://x/my%20file.iso", a), "my file.iso");
+ }
+
+ /// The type's extension is only ever a media, picture, document or archive one: a script
+ /// serving a program, a script or a page keeps its own name, and a `file=` naming a program
+ /// is not taken.
+ #[test]
+ fn a_dangerous_extension_is_never_introduced() {
+ for t in [
+ "application/x-msdownload",
+ "application/x-msdos-program",
+ "application/x-sh",
+ "application/javascript",
+ "application/hta",
+ "application/x-ms-shortcut",
+ "text/html",
+ ] {
+ assert_eq!(named("http://x/get.php", typed(t)), "get.php", "{t}");
+ assert_eq!(named("http://x/123", typed(t)), "123", "{t}");
+ }
+ for v in [
+ "setup.exe",
+ "run.bat",
+ "x.scr",
+ "a.lnk",
+ "b.ps1",
+ "c.js",
+ "d.hta",
+ "e.msi",
+ ] {
+ assert_eq!(
+ file_name(None, &url(&format!("http://x/get.php?file={v}"))),
+ "get.php"
+ );
+ }
+ let runs = [
+ "exe", "bat", "cmd", "com", "scr", "msi", "lnk", "ps1", "js", "vbs", "hta",
+ ];
+ for (_, e) in TYPES {
+ assert!(!runs.contains(e), "{e}");
+ }
+ assert_eq!(
+ named(
+ "http://x/v.php",
+ Answer {
+ sniffed: Some("exe"),
+ ..Answer::default()
+ }
+ ),
+ "v.php"
+ );
+ }
+
+ /// #800: a page's media with a name that means nothing takes the page's title.
+ #[test]
+ fn a_meaningless_name_takes_the_pages_title() {
+ let t = |title| Answer {
+ title: Some(title),
+ ..typed("video/mp4")
+ };
+ assert_eq!(
+ named("http://x/remote_control.php?id=9", t("A clip: part 1/2")),
+ "A clip part 1 2.mp4"
+ );
+ assert_eq!(named("http://x/videoplayback", t("Talk")), "Talk.mp4");
+ assert_eq!(
+ named("http://x/v/aGVsbG8gd29ybGQgdGhpcyBpcyBh.mp4", t("Talk")),
+ "Talk.mp4"
+ );
+ // A real name keeps its own; a blank title is none.
+ assert_eq!(named("http://x/clip.mp4", t("Talk")), "clip.mp4");
+ assert_eq!(named("http://x/stream.php", t(" ")), "stream.mp4");
+ // Its type unknown: the title, and the script's extension (nothing says it is another).
+ let untyped = Answer {
+ title: Some("Talk"),
+ ..Answer::default()
+ };
+ assert_eq!(named("http://x/stream.php", untyped), "Talk.php");
+ assert_eq!(named("http://x/12345", untyped), "Talk");
+ // Its bytes said: that type.
+ let sniffed = Answer {
+ sniffed: Some("webm"),
+ ..untyped
+ };
+ assert_eq!(named("http://x/stream.php", sniffed), "Talk.webm");
+ }
+
+ /// The names the browser extension gives a page's media (background.js' `mediaName`) are
+ /// the engine's: both check the same cases (`tools/extension/test.mjs`).
+ #[test]
+ fn the_extension_names_media_as_the_engine_does() {
+ let cases: serde_json::Value =
+ serde_json::from_str(include_str!("../tests/data/media-names.json")).unwrap();
+ for c in cases["cases"].as_array().unwrap() {
+ let text = |i: usize| c[i].as_str().unwrap();
+ let (mime, title) = (text(1).to_owned(), text(2).to_owned());
+ let a = Answer {
+ content_type: Some(mime.as_str()).filter(|s| !s.is_empty()),
+ title: Some(title.as_str()).filter(|s| !s.is_empty()),
+ ..Answer::default()
+ };
+ assert_eq!(named(text(0), a), text(3), "{c}");
+ }
+ }
+
+ #[test]
+ fn titles_are_cleaned() {
+ assert_eq!(clean_title(" a b\t c "), "a b c");
+ assert_eq!(clean_title("Who? Me: <yes>|no*"), "Who Me yes no");
+ assert_eq!(clean_title("End..."), "End");
+ assert_eq!(clean_title("x\u{202E}y"), "xy");
+ assert_eq!(clean_title(&"é".repeat(200)).chars().count(), 150);
+ }
+
+ #[test]
+ fn bytes_say_their_type() {
+ let mut mp4 = vec![0, 0, 0, 0x20];
+ mp4.extend_from_slice(b"ftypisom\0\0\x02\0");
+ assert_eq!(sniff(&mp4), Some("mp4"));
+ assert_eq!(sniff(b"\0\0\0\x20ftypM4A \0\0"), Some("m4a"));
+ assert_eq!(sniff(b"\0\0\0\x14ftypqt "), Some("mov"));
+ assert_eq!(
+ sniff(b"\x1A\x45\xDF\xA3\x9F\x42\x86\x81\x01\x42\x82\x84webm"),
+ Some("webm")
+ );
+ assert_eq!(sniff(b"\x1A\x45\xDF\xA3\x42\x82\x88matroska"), Some("mkv"));
+ assert_eq!(sniff(b"OggS\0\x02"), Some("ogg"));
+ assert_eq!(sniff(b"fLaC\0\0\0\x22"), Some("flac"));
+ assert_eq!(sniff(b"ID3\x04\0\0"), Some("mp3"));
+ assert_eq!(sniff(&[0xFF, 0xFB, 0x90, 0x64]), Some("mp3"));
+ assert_eq!(sniff(&[0xFF, 0xF1, 0x50, 0x80]), Some("aac"));
+ assert_eq!(sniff(b"RIFF\0\0\0\0WAVEfmt "), Some("wav"));
+ assert_eq!(sniff(b"RIFF\0\0\0\0AVI LIST"), Some("avi"));
+ assert_eq!(sniff(b"FLV\x01\x05"), Some("flv"));
+ // Not media: a page, a program, UTF-16 text, nothing.
+ assert_eq!(sniff(b"<!doctype html>"), None);
+ assert_eq!(sniff(b"MZ\x90\0\x03\0"), None);
+ assert_eq!(sniff(&[0xFF, 0xFE, 0x3C, 0x00]), None);
+ assert_eq!(sniff(b""), None);
+ // Every type the bytes give is one a name may take.
+ for e in [
+ "mp4", "m4a", "mov", "3gp", "webm", "mkv", "ogg", "flac", "mp3", "aac", "wav",
+ ] {
+ assert!(is_typed_extension(e), "{e}");
+ }
+ assert!(is_typed_extension("avi") && is_typed_extension("flv"));
+ }
+
+ #[test]
+ fn bytes_are_looked_at_only_when_nothing_else_says() {
+ let u = url("http://x/stream.php?id=1");
+ assert!(needs_sniff(&u, None, None));
+ assert!(needs_sniff(&u, None, Some("application/octet-stream")));
+ assert!(!needs_sniff(&u, None, Some("video/mp4")));
+ assert!(!needs_sniff(&u, Some("attachment; filename=a.bin"), None));
+ assert!(!needs_sniff(&url("http://x/a.zip"), None, None));
+ assert!(!needs_sniff(&url("http://x/s.php?file=c.mp4"), None, None));
+ }
+
#[test]
fn url_fallbacks() {
assert_eq!(
diff --git a/crates/engine/tests/data/media-names.json b/crates/engine/tests/data/media-names.json
new file mode 100644
index 00000000..4b261572
--- /dev/null
+++ b/crates/engine/tests/data/media-names.json
@@ -0,0 +1,21 @@
+{
+ "about": "A page's media file's name (#345, #695, #800): the address, the type its server said and the tab's title, and the name both the engine (naming.rs, answer_name) and the browser extension (background.js, mediaName with the switch off) give it. Checked by both: cargo test -p mdm-engine and node tools/extension/test.mjs.",
+ "cases": [
+ ["https://v.test/remote_control.php?id=7&t=1", "video/mp4", "Movie: the title", "Movie the title.mp4"],
+ ["https://v.test/remote_control.php?id=7", "video/mp4", "", "remote_control.mp4"],
+ ["https://v.test/baigiang/stream.php?file=FL262-1E01-4.mp4&token=x", "video/mp4", "Lecture", "FL262-1E01-4.mp4"],
+ ["https://v.test/get.php?filename=talks%2Fclip.webm", "", "Lecture", "clip.webm"],
+ ["https://v.test/get.php?file=setup.exe", "video/mp4", "", "get.mp4"],
+ ["https://v.test/videoplayback?id=3", "video/webm", "A talk", "A talk.webm"],
+ ["https://v.test/media/123456", "audio/mpeg", "", "123456.mp3"],
+ ["https://v.test/watch.html", "video/mp4", "A talk", "watch.mp4"],
+ ["https://v.test/v/SFp1NUcrZFRkRUVrUWlqM3paMitkakJIUW9J.mp4", "video/mp4", "A film", "A film.mp4"],
+ ["https://v.test/a/movie.mp4", "video/webm", "A film", "movie.mp4"],
+ ["https://v.test/a/setup.zip", "video/mp4", "A film", "setup.zip"],
+ ["https://v.test/stream.php", "application/octet-stream", "A talk", "A talk.php"],
+ ["https://v.test/stream.php", "application/x-msdownload", "", "stream.php"],
+ ["https://v.test/stream.php", "text/html", "", "stream.php"],
+ ["https://v.test/s.aspx?id=1", "video/mp4; codecs=\"avc1\"", "Talk...", "Talk.mp4"],
+ ["https://v.test/a%20b/my%20clip.ogg", "audio/ogg", "x", "my clip.ogg"]
+ ]
+}
diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs
index 86ffb7e1..189fc965 100644
--- a/crates/engine/tests/e2e.rs
+++ b/crates/engine/tests/e2e.rs
@@ -2211,3 +2211,126 @@ async fn a_capped_download_resumes_within_the_cap() {
"{spans:?}"
);
}
+
+/// Download `path` from `s` into a fresh folder the engine names it in; its name and its bytes
+/// (the generated file `seed`, with `head` over its first bytes).
+async fn named_download(
+ s: &LabServer,
+ path: &str,
+ seed: u64,
+ head: &[u8],
+ opts: Options,
+) -> String {
+ let dir = tempfile::tempdir().unwrap();
+ let req = Request {
+ url: s.url(path).parse().unwrap(),
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ };
+ let out = Download::start(req, opts)
+ .wait()
+ .await
+ .expect("download succeeds");
+ let data = std::fs::read(&out.path).unwrap();
+ let mut want = vec![0; data.len()];
+ content::fill_with_head(seed, 0, &mut want, head);
+ assert!(data == want, "{path}: content mismatch");
+ assert_eq!(data.len() as u64, 1 << 20, "{path}");
+ out.path.file_name().unwrap().to_string_lossy().into_owned()
+}
+
+/// #695, #800: a video a server's program sends (`/stream.php?id=…` as video/mp4) is named by
+/// its type, its `file=` value, its bytes and the page's title, never the script's extension;
+/// the server's own name still wins; segmented as any download.
+#[tokio::test]
+async fn a_scripts_video_is_named_by_what_it_is() {
+ let s = server("").await;
+ let titled = || Options {
+ page_title: Some("Lecture: one".into()),
+ ..fast_opts()
+ };
+ let mp4 = content::media_head("mp4").unwrap();
+ // Its type: video/mp4.
+ assert_eq!(
+ named_download(&s, "/stream.php?id=7", 0, &[], fast_opts()).await,
+ "stream.mp4"
+ );
+ // Its `file=` value, before the page's title.
+ assert_eq!(
+ named_download(&s, "/stream.php?file=clip.mp4&token=x", 0, &[], titled()).await,
+ "clip.mp4"
+ );
+ // The page's title for a name that means nothing.
+ assert_eq!(
+ named_download(&s, "/remote_control.php?id=9&seed=4", 4, &[], titled()).await,
+ "Lecture one.mp4"
+ );
+ // No type said (none, or octet-stream): its first bytes say it, and are saved as sent.
+ assert_eq!(
+ named_download(
+ &s,
+ "/remote_control.php?id=9&type=none&magic=mp4&seed=5",
+ 5,
+ mp4,
+ titled()
+ )
+ .await,
+ "Lecture one.mp4"
+ );
+ assert_eq!(
+ named_download(
+ &s,
+ "/stream.php?id=3&type=application/octet-stream&magic=webm&seed=6",
+ 6,
+ content::media_head("webm").unwrap(),
+ fast_opts()
+ )
+ .await,
+ "stream.webm"
+ );
+ // Nothing says what it is: the script's name stays (nothing is guessed).
+ assert_eq!(
+ named_download(&s, "/stream.php?id=3&type=none&seed=8", 8, &[], fast_opts()).await,
+ "stream.php"
+ );
+ // The server's own name (Content-Disposition) wins over all of it.
+ assert_eq!(
+ named_download(
+ &s,
+ "/stream.php?file=clip.mp4&inline=0&cd=Lecture%201.webm",
+ 0,
+ &[],
+ titled()
+ )
+ .await,
+ "Lecture 1.webm"
+ );
+ // Download File Info's look-up gives the same name, its bytes kept for the download.
+ let opts = titled();
+ let url: url::Url = s
+ .url("/remote_control.php?id=9&type=none&magic=mp4&seed=5")
+ .parse()
+ .unwrap();
+ let (info, kept) = mdm_engine::probe_kept(url.clone(), Default::default(), &opts)
+ .await
+ .unwrap();
+ assert_eq!(info.file_name, "Lecture one.mp4");
+ let dir = tempfile::tempdir().unwrap();
+ let out = Download::start_with(
+ Request {
+ url,
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ },
+ opts,
+ kept,
+ )
+ .wait()
+ .await
+ .expect("download succeeds");
+ let data = std::fs::read(&out.path).unwrap();
+ let mut want = vec![0; data.len()];
+ content::fill_with_head(5, 0, &mut want, mp4);
+ assert!(data == want, "the kept answer's first bytes are the file's");
+ assert_eq!(out.path.file_name().unwrap(), "Lecture one.mp4");
+}
diff --git a/crates/labserver/src/content.rs b/crates/labserver/src/content.rs
index b7c8edf9..74867638 100644
--- a/crates/labserver/src/content.rs
+++ b/crates/labserver/src/content.rs
@@ -15,6 +15,28 @@ pub fn fill(seed: u64, offset: u64, buf: &mut [u8]) {
}
}
+/// The first bytes of a media file of `kind` (`mp4`, `webm`, `mp3`), which a client that looks
+/// at a file's bytes for its type reads (#800): a generated file with `magic=` starts with them.
+pub fn media_head(kind: &str) -> Option<&'static [u8]> {
+ Some(match kind {
+ "mp4" => &b"\0\0\0\x20ftypisom\0\0\x02\0isomiso2avc1mp41"[..],
+ "webm" => &b"\x1A\x45\xDF\xA3\x9F\x42\x86\x81\x01\x42\xF7\x81\x01\x42\x82\x84webm"[..],
+ "mp3" => &b"ID3\x04\0\0\0\0\0\0"[..],
+ _ => return None,
+ })
+}
+
+/// [`fill`], with `head` over the file's first bytes.
+pub fn fill_with_head(seed: u64, offset: u64, buf: &mut [u8], head: &[u8]) {
+ fill(seed, offset, buf);
+ let Some(rest) = usize::try_from(offset).ok().and_then(|o| head.get(o..)) else {
+ return;
+ };
+ for (b, h) in buf.iter_mut().zip(rest) {
+ *b = *h;
+ }
+}
+
fn splitmix64(x: u64) -> u64 {
let mut z = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
@@ -49,6 +71,24 @@ mod tests {
}
}
+ #[test]
+ fn a_media_head_covers_the_first_bytes_only() {
+ let head = media_head("mp4").unwrap();
+ let mut whole = vec![0u8; 100];
+ fill_with_head(3, 0, &mut whole, head);
+ assert_eq!(&whole[..head.len()], head);
+ let mut plain = vec![0u8; 100];
+ fill(3, 0, &mut plain);
+ assert_eq!(whole[head.len()..], plain[head.len()..]);
+ // From any offset: the same bytes.
+ for off in [1usize, 7, 31, 32, 60] {
+ let mut part = vec![0u8; 100 - off];
+ fill_with_head(3, off as u64, &mut part, head);
+ assert_eq!(part, whole[off..]);
+ }
+ assert!(media_head("exe").is_none());
+ }
+
#[test]
fn seeds_differ() {
let (mut a, mut b) = ([0u8; 64], [0u8; 64]);
diff --git a/crates/labserver/src/pages.rs b/crates/labserver/src/pages.rs
index 7c755d2b..ce19fdec 100644
--- a/crates/labserver/src/pages.rs
+++ b/crates/labserver/src/pages.rs
@@ -57,7 +57,7 @@ fn video_tag(id: &str, src: &str, (w, h): (u32, u32), muted_loop: bool) -> Strin
)
}
-/// `/page?link=PATH&video=PATH|1&w=&h=&muted_loop=1&iframe=1&shadow=1&several=N&audio=PATH|1&
+/// `/page?title=TEXT&link=PATH&video=PATH|1&w=&h=&muted_loop=1&iframe=1&shadow=1&several=N&audio=PATH|1&
/// hls=1&dash=1&drm=1&hls2=1&dash2=1&csp=strict`: a web page with what the browser extension acts on (see
/// `HELP`).
pub(crate) async fn page(RawQuery(q): RawQuery) -> Response {
@@ -111,7 +111,7 @@ pub(crate) async fn page(RawQuery(q): RawQuery) -> Response {
None => None,
};
- let mut body = head("labserver page");
+ let mut body = head(m.get("title").copied().unwrap_or("labserver page"));
for (k, link) in links.iter().enumerate() {
let id = if k == 0 {
"link".to_owned()
diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rs
index acc8d8d7..6c22f876 100644
--- a/crates/labserver/src/server.rs
+++ b/crates/labserver/src/server.rs
@@ -7,6 +7,8 @@
//! for a form post that carries `FIELD=VALUE`
//! - `GET /files/{name}` — a real file from `--files DIR` (Range too; 404 without it): archives
//! for the link grabber's tests
+//! - `GET /stream.php`, `/remote_control.php` — a generated file a server's program sends, typed
+//! by `type` and named by nothing but a `file=` value (#695, #800)
//! - `GET /redirect?to=URL[&ttl_ms=N][&uses=N][&code=3xx]` — a redirect (302 unless `code` says)
//! to `URL` (cross-host redirects, credential scoping); with `ttl_ms` the target gets
//! `expires=<unix ms>` and answers 403 after it (signed CDN links); with `uses` it is a link of
@@ -386,6 +388,9 @@ impl LabServer {
.route("/form/{size}", any(form))
.route("/form/{size}/{*name}", any(form))
.route("/files/{*name}", get(files))
+ // A file a server's program sends (#695, #800).
+ .route("/stream.php", get(script))
+ .route("/remote_control.php", get(script))
.route("/redirect", get(redirect))
.route("/hop", get(hop))
.route("/_log", get(get_log).delete(clear_log))
@@ -645,6 +650,9 @@ POST /form/{size}[/{name}]?need=FIELD=VALUE&see_other=1&<as /gen>
(default need=token=abc): 405 to other methods, 403 to a form without it;
see_other=1: 303 to /gen/{size}/{name}?<the rest of the query> instead
GET /files/{name} a real file from --files DIR (Range too; 404 without --files)
+GET /stream.php, /remote_control.php?id=N|file=NAME&size=1M&type=MIME|none&magic=mp4|webm|mp3&<as /gen>
+ a generated file a server's program sends (#695, #800): no Content-Disposition, Content-Type
+ video/mp4 (type= another, none for none at all), magic= its first bytes a media type's
GET /redirect?to=URL[&ttl_ms=N][&uses=N][&code=3xx] 302 (or code) to URL (not logged); ttl_ms: a signed link expiring after N ms; uses: a new link each time, expiring after N requests
/rd/rest/1.0/{user,hosts/domains,unrestrict/link,disable_access_token}, /rd/oauth/v2/{device/code,device/credentials,token}
a fake Real-Debrid (#44): tokens good (premium), free; links http://hoster.test/file/SIZE/NAME[?gone=1&down=1&chunks=N&ttl_ms=N&rate=SIZE]
@@ -666,6 +674,7 @@ GET /page?<any of>
video=PATH|1 <video id=video controls> 640x360 (1: /gen/1M/clip.mp4?inline=1, also shown
when nothing else is asked for, or with muted_loop, iframe or shadow)
w=PX h=PX the videos' size
+ title=TEXT the page's title (default "labserver page")
muted_loop=1 the video muted, looping and autoplaying, without controls
iframe=1 the video inside <iframe id=frame> (a /page of its own)
shadow=1 the video inside the open shadow root of <div id=host> (declarative)
@@ -928,6 +937,42 @@ async fn generated(
serve(shared, entry, &method, &size, name.as_deref(), &query).await
}
+/// `GET /stream.php` and `/remote_control.php` (#695, #800): a generated file a server's program
+/// sends, with no Content-Disposition (as such sites do): `size` (1M by default), `type` its
+/// Content-Type (video/mp4 by default; `none` for no Content-Type at all), `magic` its first bytes
+/// a media type's (`mp4`, `webm`, `mp3`). `id`, `file`, `filename` and `token` are the page's own
+/// (a `file=` value names the file). Every generated file's key works too.
+async fn script(
+ State(shared): State<Arc<Shared>>,
+ ConnectInfo(peer): ConnectInfo<SocketAddr>,
+ method: Method,
+ uri: axum::http::Uri,
+ RawQuery(query): RawQuery,
+ headers: HeaderMap,
+) -> Response {
+ let entry = shared.begin(
+ peer,
+ &method,
+ uri.path().to_owned(),
+ query.clone(),
+ &headers,
+ &[],
+ );
+ let mut pairs: Vec<(String, String)> =
+ serde_urlencoded::from_str(query.as_deref().unwrap_or_default()).unwrap_or_default();
+ let size = pairs
+ .iter()
+ .position(|(k, _)| k == "size")
+ .map_or_else(|| "1M".to_owned(), |i| pairs.remove(i).1);
+ for (k, v) in [("type", "video/mp4"), ("inline", "bare")] {
+ if !pairs.iter().any(|(key, _)| key == k) {
+ pairs.push((k.into(), v.into()));
+ }
+ }
+ let query = serde_urlencoded::to_string(pairs).unwrap_or_default();
+ serve(shared, entry, &method, &size, None, &query).await
+}
+
/// `GET /files/{name}`: a real file from `Config::files` (404 without one, or for a name that
/// leaves that folder), whole or one range of it.
async fn files(
@@ -1114,6 +1159,10 @@ struct FileQuery {
cd: Option<String>,
cdstar: Option<String>,
disposition: Disposition,
+ /// `type`: the Content-Type sent instead of the name's (`none`: none at all).
+ content_type: Option<String>,
+ /// `magic`: the file starts as a media type's ([`content::media_head`]).
+ magic: Option<&'static [u8]>,
faults: Faults,
}
@@ -1344,13 +1393,17 @@ pub(crate) async fn serve(
entry.body_len = end - start;
let file_name = q.cdstar.as_deref().or(q.cd.as_deref()).or(name);
- let content_type = match q.disposition {
- Disposition::Attachment => "application/octet-stream",
- _ => mime_type(file_name.unwrap_or("")),
+ let content_type = match (q.content_type.as_deref(), q.disposition) {
+ (Some("none"), _) => None,
+ (Some(t), _) => Some(t),
+ (None, Disposition::Attachment) => Some("application/octet-stream"),
+ (None, _) => Some(mime_type(file_name.unwrap_or(""))),
};
- let mut builder = Response::builder()
- .status(status)
- .header(header::CONTENT_TYPE, content_type)
+ let mut builder = Response::builder().status(status);
+ if let Some(t) = content_type {
+ builder = builder.header(header::CONTENT_TYPE, t);
+ }
+ let mut builder = builder
.header(header::CONTENT_LENGTH, end - start)
.header(header::LAST_MODIFIED, &last_modified);
if f.no_range != Some(true) {
@@ -1394,6 +1447,7 @@ pub(crate) async fn serve(
shared: shared.clone(),
entry: Some(entry),
seed,
+ magic: q.magic,
pos: start,
end,
rate,
@@ -1489,6 +1543,8 @@ fn split_query(q: &str) -> Result<FileQuery, String> {
cd: None,
cdstar: None,
disposition: Disposition::Attachment,
+ content_type: None,
+ magic: None,
faults: Faults::default(),
};
let name = |k: &str, v: String| {
@@ -1506,7 +1562,13 @@ fn split_query(q: &str) -> Result<FileQuery, String> {
out.expires = Some(v.parse().map_err(|_| format!("invalid expires `{v}`\n"))?)
}
"uses" => out.uses = Some(v.parse().map_err(|_| format!("invalid uses `{v}`\n"))?),
- "link" => {}
+ // A page's own keys for a server's program (`script`): they change nothing here.
+ "link" | "id" | "file" | "filename" | "token" => {}
+ "type" => out.content_type = name(&k, v)?,
+ "magic" => {
+ out.magic =
+ Some(content::media_head(&v).ok_or_else(|| format!("invalid magic `{v}`\n"))?)
+ }
"cd" => out.cd = name(&k, v)?,
"cdstar" => out.cdstar = name(&k, v)?,
"inline" => {
@@ -1531,6 +1593,8 @@ struct Transfer {
shared: Arc<Shared>,
entry: Option<LogEntry>,
seed: u64,
+ /// The file's first bytes, over the generated ones (`magic`).
+ magic: Option<&'static [u8]>,
pos: u64,
end: u64,
rate: Option<u64>,
@@ -1589,7 +1653,7 @@ impl Transfer {
n = n.min(d - t.sent);
}
let mut buf = vec![0u8; n as usize];
- content::fill(t.seed, t.pos, &mut buf);
+ content::fill_with_head(t.seed, t.pos, &mut buf, t.magic.unwrap_or_default());
t.pos += n;
t.sent += n;
if let Some(slot) = &t.slot {
diff --git a/crates/nmhost/src/main.rs b/crates/nmhost/src/main.rs
index 1fb8d265..5e243951 100644
--- a/crates/nmhost/src/main.rs
+++ b/crates/nmhost/src/main.rs
@@ -522,6 +522,8 @@ fn video_command(
let direct = m.direct && src.is_some();
Ok(mdm_ipc::Command {
video_direct: direct,
+ // The type the plain file's server said when the tab loaded it (#800).
+ mime: m.mime.clone().filter(|t| direct && !t.trim().is_empty()),
video_page: Some(src.unwrap_or_else(|| m.url.clone())),
video_title: m.title.clone().filter(|t| !t.trim().is_empty()),
referer,
@@ -840,6 +842,14 @@ fn to_command(m: Message) -> mdm_ipc::Command {
user_agent: m.user_agent,
size: m.size.filter(|s| *s > 0),
mime: some(m.mime),
+ // A page's media from the toolbar button's list (#800): its page's title names a file
+ // whose address names nothing.
+ video_title: m
+ .title
+ .as_deref()
+ .map(str::trim)
+ .filter(|t| !t.is_empty())
+ .map(|t| t.chars().take(TITLE_MAX).collect()),
post_type: m.post.as_ref().and(some(m.post_type)),
post: m.post,
private: m.private,
@@ -1636,6 +1646,17 @@ mod tests {
assert!(cmd.video_direct);
assert_eq!(cmd.video_page.as_deref(), Some("https://cdn.test/a.mp4"));
assert_eq!(cmd.referer.as_deref(), Some("https://videos.test/p"));
+ assert_eq!(cmd.mime, None);
+ // #800: with the type its server said, which names a script's answer at once.
+ let m: Message = serde_json::from_str(&format!(
+ r#"{{"video":true,"url":"https://videos.test/p","src":"https://cdn.test/stream.php?id=1","direct":true,"mime":"video/mp4","title":"Talk","userAgent":"{ua}"}}"#
+ ))
+ .unwrap();
+ let cmd = video_command(&m, &rules, browser(&m)).unwrap();
+ assert_eq!(
+ (cmd.mime.as_deref(), cmd.video_title.as_deref()),
+ (Some("video/mp4"), Some("Talk"))
+ );
// `direct` without a file of its own is the page, as before.
let m: Message = serde_json::from_str(&format!(
r#"{{"video":true,"url":"https://videos.test/p","direct":true,"userAgent":"{ua}"}}"#
@@ -2290,6 +2311,25 @@ mod tests {
);
assert!(!c.later && !c.silent);
assert_eq!((c.proxy, c.proxy_pac, c.proxy_login), (None, None, false));
+ assert_eq!(c.video_title, None);
+ }
+
+ /// #800: a page's media from the toolbar button's list goes with its page's title (for a
+ /// file whose address names nothing), trimmed and cut; a blank one is none.
+ #[test]
+ fn a_media_files_page_title_goes_with_it() {
+ let m: Message = serde_json::from_str(
+ r#"{"url":"https://x/remote_control.php?id=1","mime":"video/mp4","title":" A talk "}"#,
+ )
+ .unwrap();
+ let c = to_command(m);
+ assert_eq!(c.video_title.as_deref(), Some("A talk"));
+ assert_eq!(c.mime.as_deref(), Some("video/mp4"));
+ let long = format!(r#"{{"url":"https://x/a","title":"{}"}}"#, "t".repeat(400));
+ let c = to_command(serde_json::from_str(&long).unwrap());
+ assert_eq!(c.video_title.unwrap().len(), TITLE_MAX);
+ let blank: Message = serde_json::from_str(r#"{"url":"https://x/a","title":" "}"#).unwrap();
+ assert_eq!(to_command(blank).video_title, None);
}
#[test]
diff --git a/crates/tools/src/proc.rs b/crates/tools/src/proc.rs
index a19f7630..05e4c5ed 100644
--- a/crates/tools/src/proc.rs
+++ b/crates/tools/src/proc.rs
@@ -190,7 +190,10 @@ pub fn look_up(
url: &str,
timeout: Duration,
) -> Result<LookedUp, ProcError> {
- let run = |args: &[String]| output(ytdlp(exe, &[], args, url)?, "yt-dlp", timeout);
+ // A plain file a server's program sends gets its real type (#695).
+ let run = |args: &[String]| {
+ output(ytdlp(exe, &[], args, url)?, "yt-dlp", timeout).map(crate::resolve::typed_scripts)
+ };
match run(ours) {
Ok(json) => Ok(LookedUp {
json,
diff --git a/crates/tools/src/resolve.rs b/crates/tools/src/resolve.rs
index e5836d5e..b23a9944 100644
--- a/crates/tools/src/resolve.rs
+++ b/crates/tools/src/resolve.rs
@@ -224,6 +224,79 @@ pub fn named_after_address(title: &str, page: &str) -> bool {
!stem.is_empty() && title.trim() == stem
}
+/// yt-dlp's `-J` answer with the real type of a file a server's program sends (#695): yt-dlp
+/// takes a plain file's extension from its address (`stream.php?file=x.mp4` → `php`), lists it
+/// so ("PHP") and then refuses to save it ("The extracted extension (php) is unusual and will
+/// be skipped for safety reasons"). Such a format's extension is the one MDM names the file with
+/// (`mdm_engine::naming`): its address's `file=` value's, else the server's type, which yt-dlp
+/// gives a plain file as its format id (`video/mp4` → `mp4`). The answer is given as it came
+/// when nothing in it is such a format, or it isn't JSON.
+pub fn typed_scripts(json: Vec<u8>) -> Vec<u8> {
+ let Ok(mut v) = serde_json::from_slice::<serde_json::Value>(&json) else {
+ return json;
+ };
+ let mut changed = retype(&mut v);
+ for list in ["formats", "requested_formats"] {
+ if let Some(fs) = v.get_mut(list).and_then(serde_json::Value::as_array_mut) {
+ for f in fs {
+ changed |= retype(f);
+ }
+ }
+ }
+ match changed {
+ true => serde_json::to_vec(&v).unwrap_or(json),
+ false => json,
+ }
+}
+
+/// [`typed_scripts`] for one format (or the chosen one's fields at the top): true when its
+/// extension, a program's or a page's, became its file's type's.
+fn retype(f: &mut serde_json::Value) -> bool {
+ use mdm_engine::naming;
+ let Some(ext) = f.get("ext").and_then(serde_json::Value::as_str) else {
+ return false;
+ };
+ let ext = ext.to_ascii_lowercase();
+ if !naming::SCRIPT_EXTENSIONS.contains(&ext.as_str())
+ && !naming::PAGE_EXTENSIONS.contains(&ext.as_str())
+ {
+ return false;
+ }
+ let text = |k: &str| f.get(k).and_then(serde_json::Value::as_str).unwrap_or("");
+ // The `file=` value's own extension, when the address has one.
+ let from_address = url::Url::parse(text("url")).ok().and_then(|u| {
+ let name = naming::address_name(&u);
+ let (_, e) = name.rsplit_once('.')?;
+ (!naming::is_script_name(&name) && naming::is_typed_extension(e))
+ .then(|| e.to_ascii_lowercase())
+ });
+ // A plain file's format id is its type's subtype, as is or after an `f` (yt-dlp 2026.10:
+ // `fmp4` for video/mp4; `webm`, `mpeg`): sound first when it has no picture.
+ let id = text("format_id").to_ascii_lowercase();
+ let families = match text("vcodec") {
+ "none" => ["audio", "video"],
+ _ => ["video", "audio"],
+ };
+ let from_type = || {
+ [Some(id.as_str()), id.strip_prefix('f')]
+ .into_iter()
+ .flatten()
+ .find_map(|subtype| {
+ families
+ .iter()
+ .find_map(|k| naming::type_extension(&format!("{k}/{subtype}")))
+ })
+ .map(str::to_owned)
+ };
+ match from_address.or_else(from_type) {
+ Some(e) => {
+ f["ext"] = serde_json::Value::String(e);
+ true
+ }
+ None => false,
+ }
+}
+
/// Parse `yt-dlp -J` output.
pub fn parse(json: &[u8]) -> Option<Video> {
let raw: RawVideo = serde_json::from_slice(json).ok()?;
@@ -1367,6 +1440,65 @@ mod tests {
assert!(!heights.is_empty(), "no video in {:?}", v.title);
}
+ /// #695: a plain file a server's program sends (`stream.php`), as yt-dlp's generic reader
+ /// answers for it: the format id is the type's subtype, the extension the address's. It gets
+ /// its file's type: the `file=` value's, else the type's; a real one stays.
+ #[test]
+ fn a_scripts_file_gets_its_real_type() {
+ let answer = |url: &str, id: &str, vcodec: &str| {
+ format!(
+ r#"{{"title": "stream", "direct": true, "ext": "php", "url": "{url}",
+ "format_id": "{id}", "vcodec": {vcodec}, "formats": [{{"format_id": "{id}",
+ "ext": "php", "url": "{url}", "vcodec": {vcodec}, "protocol": "https"}}]}}"#
+ )
+ };
+ let ext = |json: &[u8]| {
+ let v: serde_json::Value = serde_json::from_slice(json).unwrap();
+ (
+ v["ext"].as_str().unwrap().to_owned(),
+ v["formats"][0]["ext"].as_str().unwrap().to_owned(),
+ )
+ };
+ let fixed = typed_scripts(
+ answer(
+ "https://u.test/stream.php?file=FL262-1E01-4.mp4&t=1",
+ "mp4",
+ "null",
+ )
+ .into_bytes(),
+ );
+ assert_eq!(ext(&fixed), ("mp4".into(), "mp4".into()));
+ assert_eq!(parse(&fixed).unwrap().formats[0].ext, "mp4");
+ // No file name in the address: the server's type, read as a sound's when it has no
+ // picture (audio/mpeg is an MP3, video/mpeg an MPG).
+ let fixed = typed_scripts(
+ answer("https://u.test/remote_control.php?id=3", "webm", "null").into_bytes(),
+ );
+ assert_eq!(ext(&fixed), ("webm".into(), "webm".into()));
+ let fixed = typed_scripts(answer("https://u.test/a.php", "mpeg", r#""none""#).into_bytes());
+ assert_eq!(ext(&fixed).1, "mp3");
+ // yt-dlp 2026.10 names it `f` and the subtype (its answer for the lab's /stream.php).
+ let fixed =
+ typed_scripts(answer("https://u.test/stream.php?id=1", "fmp4", "null").into_bytes());
+ assert_eq!(ext(&fixed), ("mp4".into(), "mp4".into()));
+ let fixed = typed_scripts(answer("https://u.test/a.php", "flac", r#""none""#).into_bytes());
+ assert_eq!(ext(&fixed).1, "flac");
+ // Nothing says what it is: as it came. A real extension is never touched.
+ let unknown = answer("https://u.test/a.php", "x-unknown", "null").into_bytes();
+ assert_eq!(typed_scripts(unknown.clone()), unknown);
+ let real = br#"{"title": "t", "ext": "mp4", "formats": [{"format_id": "18", "ext": "mp4", "url": "https://u.test/v.php"}]}"#.to_vec();
+ assert_eq!(typed_scripts(real.clone()), real);
+ assert_eq!(typed_scripts(b"not json".to_vec()), b"not json".to_vec());
+ // A program's type is never one: application/x-msdownload stays as it came.
+ let program = answer(
+ "https://u.test/a.php?file=setup.exe",
+ "x-msdownload",
+ "null",
+ )
+ .into_bytes();
+ assert_eq!(typed_scripts(program.clone()), program);
+ }
+
/// #320: yt-dlp's answer for a plain file (real output, 2026.10.26) says `direct` and no size.
#[test]
fn a_direct_file_takes_the_size_the_server_said() {
diff --git a/docs/browser-integration.md b/docs/browser-integration.md
index 4945cd06..7e50b99d 100644
--- a/docs/browser-integration.md
+++ b/docs/browser-integration.md
@@ -151,8 +151,12 @@ too. The toolbar button lists what the page has loaded, so you can still save it
for a video, its picture size.
Start the video first: the list fills as the page loads things, and it's emptied when the tab goes
-to another page. With **Prefix media file names with the page title** on, a file from the list is
-named after the page, then its own name (`The page - clip.mp4`). Click **Download** beside one: a stream opens MDM's **Download video from a page**
+to another page. Each file is listed under the name it will be saved with. A file the site sends
+through a program's address (`stream.php`, `remote_control.php`, `videoplayback`, a bare number)
+has no name of its own: it's named after the page (`The page.mp4`), or after the `file=` name in
+its address when there is one, with the type its server says it is (MP4, not PHP). With **Prefix
+media file names with the page title** on, a file with a name of its own is named after the page,
+then that name (`The page - clip.mp4`). Click **Download** beside one: a stream opens MDM's **Download video from a page**
window, which reads its qualities (yt-dlp does the work); a file goes to MDM's list like any other
download. Your cookies for its server, the page as the referrer and your browser's User-Agent go
with it, as they do for a link you click.
diff --git a/extension/background.js b/extension/background.js
index 04ae6f19..4d5aeb86 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -901,6 +901,14 @@ async function mediaList(tabId) {
await Promise.all(tab.items.filter((it) => isStream(it) && !it.info).map(async (it) => (it.info = await probe(it))));
tab.frames = Object.fromEntries(Object.entries(frames).map(([id, f]) => [id, f.href]));
keepMedia();
+ // A file's name as it will be saved (#800): the tab's title and the popup's switch name it too.
+ const { mediaTitleName } = await ext.storage.local.get({ mediaTitleName: false });
+ let title = "";
+ try {
+ title = (await ext.tabs.get(tabId)).title || "";
+ } catch {
+ // The tab is gone: names without its title.
+ }
const out = [];
const shown = [];
for (const it of tab.items) {
@@ -914,10 +922,13 @@ async function mediaList(tabId) {
const frame = frames[it.frameId] || { players: [] };
const player = frame.players.find((v) => v.src === it.url);
const info = it.info && !it.info.failed ? it.info : null;
+ // A stream is named in the Download video window; a file here, with its type (#800).
+ const named = isStream(it) ? null : mediaName(it.url, it.mime, title, mediaTitleName).name;
out.push({
url: it.url,
kind: it.kind,
mime: it.mime,
+ ...(named ? { name: named, ext: splitExtension(named)[1].toLowerCase() } : {}),
size: it.size || 0,
heights: info ? [...new Set(info.heights)].sort((a, b) => b - a) : player && player.h ? [player.h] : [],
width: (!info && player && player.w) || 0,
@@ -930,21 +941,127 @@ async function mediaList(tabId) {
return out;
}
-// A file's name from the tab's title when its address ends in a long hash (#345) or is on a
-// server whose names are all random ids (#493: X's video.twimg.com, too short for the hash test);
-// else, with the popup's switch on (`includeOriginal`), the title before the address's own name;
-// else none: the app names it from the address, as for any download.
-function titledName(url, title, includeOriginal = false) {
- 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);
+// ---- a page's media file's name (#345, #493, #695, #800): as the app's engine names it
+// (crates/engine/src/naming.rs, answer_name; tools/extension/test.mjs checks they agree) ---------
+
+// The types a file's extension is taken from (naming.rs' TYPES): media, pictures, documents and
+// archives, never a type that runs.
+const TYPE_EXTENSIONS = {
+ "video/mp4": "mp4",
+ "video/x-m4v": "m4v",
+ "video/webm": "webm",
+ "video/x-matroska": "mkv",
+ "video/quicktime": "mov",
+ "video/x-msvideo": "avi",
+ "video/avi": "avi",
+ "video/x-ms-wmv": "wmv",
+ "video/x-flv": "flv",
+ "video/mpeg": "mpg",
+ "video/mp2t": "ts",
+ "video/3gpp": "3gp",
+ "video/3gpp2": "3g2",
+ "video/ogg": "ogv",
+ "audio/mpeg": "mp3",
+ "audio/mp3": "mp3",
+ "audio/mp4": "m4a",
+ "audio/x-m4a": "m4a",
+ "audio/aac": "aac",
+ "audio/aacp": "aac",
+ "audio/webm": "weba",
+ "audio/ogg": "ogg",
+ "audio/opus": "opus",
+ "audio/flac": "flac",
+ "audio/x-flac": "flac",
+ "audio/wav": "wav",
+ "audio/x-wav": "wav",
+ "audio/wave": "wav",
+ "audio/x-ms-wma": "wma",
+ "application/ogg": "ogg",
+ "image/jpeg": "jpg",
+ "image/png": "png",
+ "image/gif": "gif",
+ "image/webp": "webp",
+ "image/avif": "avif",
+ "application/pdf": "pdf",
+ "application/epub+zip": "epub",
+ "application/zip": "zip",
+ "application/x-zip-compressed": "zip",
+ "application/x-7z-compressed": "7z",
+ "application/vnd.rar": "rar",
+ "application/x-rar-compressed": "rar",
+ "application/gzip": "gz",
+ "application/x-gzip": "gz",
+};
+const TYPED = new Set(Object.values(TYPE_EXTENSIONS));
+// A web server's programs (naming.rs' SCRIPT_EXTENSIONS) and a page's: such an address names the
+// program that answers, not the file it sends.
+const SCRIPT_EXTENSIONS = ["php", "php3", "php4", "php5", "phtml", "asp", "aspx", "ashx", "axd", "jsp", "jspx", "do", "action", "cgi", "pl", "cfm", "py", "rb"];
+const PAGE_EXTENSIONS = ["htm", "html", "xhtml", "shtml", "dhtml"];
+
+// A name's stem and extension ("clip.mp4": "clip", "mp4"); ".profile", "clip", "Mr. Smith" have none.
+function splitExtension(name) {
+ const dot = name.lastIndexOf(".");
+ const ext = dot > 0 ? name.slice(dot + 1) : "";
+ return ext && !/\s/.test(ext) ? [name.slice(0, dot), ext] : [name, ""];
+}
+const typeExtension = (mime) => TYPE_EXTENSIONS[String(mime || "").split(";")[0].trim().toLowerCase()] || "";
+const isScriptName = (name) => SCRIPT_EXTENSIONS.includes(splitExtension(name)[1].toLowerCase());
+// Its extension doesn't say what the file is: a script's, a page's, or none.
+function untyped(name) {
+ const ext = splitExtension(name)[1].toLowerCase();
+ return !ext || SCRIPT_EXTENSIONS.includes(ext) || PAGE_EXTENSIONS.includes(ext);
+}
+// A name that says nothing of the file, for the tab's title to replace: a script's, none (a bare
+// id, `videoplayback`), or a long hash (#345).
+function meansNothing(name) {
+ const [stem, ext] = splitExtension(name);
const hash = stem.length >= 24 && /^[A-Za-z0-9=_-]+$/.test(stem) && (stem.match(/[-_]/g) || []).length <= 2;
+ return !ext || isScriptName(name) || hash;
+}
+// The tab's title as a file's stem: what a file name can't hold becomes a space, at most 150 characters.
+function cleanTitle(title) {
+ const spaced = String(title || "")
+ .replace(/[\u00AD\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF]/g, "")
+ .replace(/[\x00-\x1f\x7f-\x9f<>:"/\\|?*]/g, " ");
+ return [...spaced.split(/\s+/).filter(Boolean).join(" ")].slice(0, 150).join("").replace(/[. ]+$/, "");
+}
+// The address's own name (naming.rs' address_name): a script's `file=` or `filename=` value naming
+// a file of a known type (#695), else its last part.
+function addressFileName(url) {
+ const last = addressName(url);
+ if (splitExtension(last)[1] && !isScriptName(last)) return last;
+ try {
+ for (const [k, v] of new URL(url).searchParams) {
+ if (!/^(file|filename)$/i.test(k)) continue;
+ const name = v.trim().split(/[\\/]/).pop().trim();
+ const [stem, ext] = splitExtension(name);
+ if (stem.trim() && TYPED.has(ext.toLowerCase())) return name;
+ }
+ } catch {
+ // Not an address: its last part.
+ }
+ return last;
+}
+
+// A page's media file's name as the app saves it ({name, own}): its address's (a script's `file=`
+// value), typed by the type its server said (`mime`) when its own extension doesn't say it
+// (stream.php: stream.mp4), and the tab's title instead of a name that means nothing (a script's,
+// a bare id, a hash; any on a server whose names are all random ids, #493: X's video.twimg.com).
+// With the popup's switch on (`includeOriginal`), the title before a real name ("Title -
+// clip.mp4"). `own`: the address names the file as the app would name it with no name sent, so
+// none is (a server's Content-Disposition then still wins).
+function mediaName(url, mime, title, includeOriginal = false) {
+ const given = addressFileName(url);
+ const typed = untyped(given) ? typeExtension(mime) : "";
+ const [stem, ext] = splitExtension(given);
+ const name = cleanTitle(title);
const randomServer = siteOf(url).toLowerCase() === "video.twimg.com";
- if ((hash || randomServer) && name) return `${name}${dot > 0 ? last.slice(dot) : ""}`;
- if (!includeOriginal || !name) return "";
- const original = addressName(url).replace(/[\\/:*?"<>|\x00-\x1f]/g, " ").trim();
- return original && original !== "." && original !== ".." ? `${name} - ${original}` : "";
+ const bare = given === addressName(url) && (meansNothing(given) || randomServer);
+ const dotted = typed || ext ? `.${typed || ext}` : "";
+ if (bare && name) return { name: `${name}${dotted}`, own: false };
+ const own = typed ? `${stem || "download"}.${typed}` : given;
+ if (includeOriginal && name && own) return { name: `${name} - ${own}`, own: false };
+ return { name: own, own: !typed };
}
// One of the tab's media, handed to the app as the popup asked: a stream to the Download video
@@ -980,7 +1097,12 @@ async function mediaDownload(tabId, url) {
});
}
const { mediaTitleName } = await ext.storage.local.get({ mediaTitleName: false });
- return handOff({ url: it.url, referrer: page, size: it.size, mime: it.mime, explicit: true, filename: titledName(it.url, tab.title, mediaTitleName), ...ctx });
+ const named = mediaName(it.url, it.mime, tab.title, mediaTitleName);
+ // The name the list shows; none when the address names the file as the app would (a server's
+ // Content-Disposition may still name it). The title goes too: a file whose address names nothing
+ // and whose type only the server or its bytes say is named by it in the app (#800).
+ const title = String(tab.title || "").slice(0, 300);
+ return handOff({ url: it.url, referrer: page, size: it.size, mime: it.mime, explicit: true, filename: named.own ? "" : named.name, ...(title ? { title } : {}), ...ctx });
}
// ---- the hand-off ------------------------------------------------------------------------
@@ -1284,6 +1406,8 @@ async function handOff(d) {
...(d.post ? { post: d.post.body, postType: d.post.type || "" } : {}),
...(d.incognito ? { private: true } : {}),
...(d.explicit ? { explicit: true } : {}),
+ // A page's media from the popup's list (#800): its page's title, for a name the address lacks.
+ ...(d.title ? { title: d.title } : {}),
// Through the browser's proxy too (#42): the one its own request for the file took.
...(await browserProxy(d.finalUrl || d.url, d.incognito)),
};
@@ -2156,13 +2280,16 @@ async function pageMessage(m, sender) {
if (m.type === "video" && page) {
const v = await videoTarget(m, page, sender);
if (!v) return { ok: false, why: isYouTube(page) ? "unnamed" : "feed" };
- // The video's own plain file (#703): downloaded as a file, no window.
+ // The video's own plain file (#703): downloaded as a file, no window; with the type its
+ // server said when the tab loaded it, which names a script's answer at once (#800).
const direct = Boolean(m.direct) && Boolean(v.file) && v.file === v.src;
+ const loaded = direct && ((media.get(tab.id) || {}).items || []).find((it) => it.url === v.src);
const reply = await native({
video: true,
url: v.own,
...(v.src ? { src: v.src } : {}),
...(direct ? { direct: true } : {}),
+ ...(loaded && loaded.mime ? { mime: loaded.mime } : {}),
title: v.title,
referrer: v.referrer,
cookies: v.cookies,
diff --git a/extension/popup.js b/extension/popup.js
index 56dec806..1f3bfb44 100644
--- a/extension/popup.js
+++ b/extension/popup.js
@@ -111,16 +111,19 @@ const TYPES = {
"audio/wav": "WAV",
};
-// Its type as a short tag: HLS, DASH, else the file's extension or its type's.
+// Its type as a short tag: HLS, DASH, else its file's extension as it will be saved (a script's
+// answer: its type's, #800), else its type's.
function tagOf(m) {
if (m.kind === "hls") return "HLS";
if (m.kind === "dash") return "DASH";
- const ext = (/\.([a-z0-9]{2,4})$/i.exec(m.url.split(/[?#]/)[0]) || [])[1];
+ const ext = typeof m.name === "string" ? m.ext : (/\.([a-z0-9]{2,4})$/i.exec(m.url.split(/[?#]/)[0]) || [])[1];
return (ext || TYPES[m.mime] || (m.kind === "audio" ? "AUDIO" : "VIDEO")).toUpperCase();
}
-// The address's last part, readable.
-function nameOf(url) {
+// Its name: a file's as it will be saved (#800), else the address's last part, readable.
+function nameOf(m) {
+ if (typeof m.name === "string" && m.name) return m.name;
+ const url = m.url;
const last = url.split(/[?#]/)[0].split("/").filter(Boolean).pop() || url;
try {
return decodeURIComponent(last);
@@ -187,7 +190,7 @@ async function showMedia(tab, connected) {
what.className = "what";
const name = document.createElement("span");
name.className = "name";
- name.textContent = nameOf(m.url);
+ name.textContent = nameOf(m);
name.title = m.url;
const meta = document.createElement("span");
meta.className = "meta";
@@ -223,8 +226,9 @@ const mediaTitleName = $("media-title-name");
ext.storage.local.get({ mediaTitleName: false })
.then((v) => (mediaTitleName.checked = Boolean(v.mediaTitleName)))
.catch(() => {});
+// The list's names follow it at once.
mediaTitleName.addEventListener("change", () =>
- ext.storage.local.set({ mediaTitleName: mediaTitleName.checked }).catch(() => {}));
+ ext.storage.local.set({ mediaTitleName: mediaTitleName.checked }).then(show, () => {}));
// #42: reading the browser's proxy (a VPN or proxy extension's) is an opt-in, this switch, off as
// installed. Firefox: the optional "proxy" permission, asked for on it. Chromium can't make that
diff --git a/extension/video.js b/extension/video.js
index 3748a20b..ad430e12 100644
--- a/extension/video.js
+++ b/extension/video.js
@@ -1070,6 +1070,26 @@ button:focus-visible { outline: none; }
let lookTimer = 0;
// A stream's manifest the page plays as its file (Safari's way, Chrome's own HLS): looked up.
const STREAM = /\.(m3u8|mpd)(?:[?#]|$)/i;
+ // A web server's programs and a page (background.js' SCRIPT_EXTENSIONS and PAGE_EXTENSIONS):
+ // a file such an address sends is of another type, which only its server says (#695, #800).
+ const SCRIPT_EXTENSIONS = ["php", "php3", "php4", "php5", "phtml", "asp", "aspx", "ashx", "axd", "jsp", "jspx", "do", "action", "cgi", "pl", "cfm", "py", "rb", "htm", "html", "xhtml", "shtml", "dhtml"];
+ // A plain file's type as its address says it: its extension, or a script's `file=` value's
+ // (stream.php?file=x.mp4: MP4); none for a script's alone (not "PHP": the file isn't one).
+ function fileType(src) {
+ let u;
+ try {
+ u = new URL(src);
+ } catch {
+ return "";
+ }
+ const ext = ((/\.([a-z0-9]{2,5})$/i.exec(u.pathname) || [])[1] || "").toLowerCase();
+ if (!SCRIPT_EXTENSIONS.includes(ext) && ext) return ext;
+ for (const [k, v] of u.searchParams) {
+ const given = /^(file|filename)$/i.test(k) && /\.(mp4|m4v|webm|mkv|mov|avi|wmv|flv|3gp|ogv|mp3|m4a|aac|ogg|oga|opus|flac|wav|wma)$/i.exec(v.trim());
+ if (given) return given[1].toLowerCase();
+ }
+ return "";
+ }
// What the button sends for a video, and its look-up's key (none when nothing names the video).
const lookKey = (d) => (d.url === null ? null : `${d.url} ${d.src}`);
// What download sends for the video now ({v, d, key}), kept a moment (the DOM walk is not free).
@@ -1085,15 +1105,7 @@ button:focus-visible { outline: none; }
// one asked, or null.
function lookOf(c) {
if (!c || c.d.drm) return null;
- if (c.d.src && !STREAM.test(c.d.src)) {
- let ext = "";
- try {
- ext = (/\.([a-z0-9]{2,5})$/i.exec(new URL(c.d.src).pathname) || [])[1] || "";
- } catch {
- // No type to say.
- }
- return { file: true, height: c.v.videoHeight || 0, ext: ext.toLowerCase() };
- }
+ if (c.d.src && !STREAM.test(c.d.src)) return { file: true, height: c.v.videoHeight || 0, ext: fileType(c.d.src) };
return (c.key && looks.get(c.key)) || null;
}
// A look-up worth keeping: one under way, or one that found the video (and wasn't picked from:
diff --git a/tools/extension/e2e.mjs b/tools/extension/e2e.mjs
index a539a1f1..eb43c2c1 100644
--- a/tools/extension/e2e.mjs
+++ b/tools/extension/e2e.mjs
@@ -28,6 +28,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),
+// scripted (a video a server's program sends, named after its page with its real type: the list,
+// the button, the Download video window; #695, #800),
// qualities (the button's menu: a stream's qualities looked up by MDM, with their sizes; the one
// picked downloads with its progress window only, MDM's main window hidden), page (the menu on a
// real video page, E2E_VIDEO_PAGE, and the line E2E_VIDEO_PICK downloaded: off by default), video (shown,
@@ -42,7 +44,8 @@
// Screenshots for a pull request (Chromium only): E2E_LANG=de (or ar, ...) starts the browser in that
// language, so the extension shows its _locales text of it; with E2E_SHOTS=<folder> the `qualities`
// case saves <lang>-looking.png, <lang>-video-tab.png and <lang>-audio-tab.png there (the player and
-// the menu), before the pick. Neither changes anything when unset.
+// the menu), before the pick, and the `scripted` case <lang>-media-list.png (the popup's list) and
+// <lang>-video-window.png. Neither changes anything when unset.
//
// Windows: the host is registered for the current user while it runs (nmhost --register, as the
// installer does) and unregistered at the end. Every registry key that touches (the browsers'
@@ -445,7 +448,21 @@ async function chromium(bin, profile, dl, page, ready) {
if (r.exceptionDetails) throw new Error(`evaluate: ${r.exceptionDetails.text} ${expression}`);
return r.result.value;
};
- return { evaluate: ev, close: () => cdp.send("Target.closeTarget", { targetId: tid }).catch(() => {}) };
+ // A picture of its page, cut to the body (the popup's 300 px), for a PR's body; in
+ // E2E_COLOR_SCHEME's colours (light or dark) when set, else the system's.
+ const shot = async (file) => {
+ const scheme = process.env.E2E_COLOR_SCHEME;
+ if (scheme) {
+ await cdp.send("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: scheme }] }, s);
+ await sleep(300);
+ }
+ const r = JSON.parse(await ev("JSON.stringify(document.body.getBoundingClientRect())"));
+ // Its margin as much on each side as above it (a right-to-left page's body is at the right).
+ const clip = { x: Math.max(0, r.left - r.top), y: 0, width: Math.ceil(r.width + 2 * r.top), height: Math.ceil(r.bottom + r.top), scale: 2 };
+ const { data } = await cdp.send("Page.captureScreenshot", { format: "png", clip }, s);
+ fs.writeFileSync(file, Buffer.from(data, "base64"));
+ };
+ return { evaluate: ev, shot, close: () => cdp.send("Target.closeTarget", { targetId: tid }).catch(() => {}) };
};
// The tab's requests to `hosts` (http and https) answered here, never by the network:
// `respond(url)` gives { status, type, body }, or null for the network's own answer.
@@ -1018,6 +1035,28 @@ foreach ($w in $A::RootElement.FindAll([System.Windows.Automation.TreeScope]::Ch
const VIDEO_WINDOW = "Download video from a page";
+// The Download video window's "Download Now", pressed through UI Automation (its Invoke, as a
+// screen reader does: no pointer, nothing on the screen). Whether it was there to press.
+function videoDownloadNow(pid) {
+ if (!WIN) throw new Skip(NO_UIA);
+ const script = `
+Add-Type -AssemblyName UIAutomationClient; Add-Type -AssemblyName UIAutomationTypes
+$A = [System.Windows.Automation.AutomationElement]
+$pid_ = New-Object System.Windows.Automation.PropertyCondition($A::ProcessIdProperty, ${pid})
+$now = New-Object System.Windows.Automation.AndCondition(
+ (New-Object System.Windows.Automation.PropertyCondition($A::ControlTypeProperty, [System.Windows.Automation.ControlType]::Button)),
+ (New-Object System.Windows.Automation.PropertyCondition($A::NameProperty, 'Download Now')))
+$edit = New-Object System.Windows.Automation.AndCondition(
+ (New-Object System.Windows.Automation.PropertyCondition($A::ControlTypeProperty, [System.Windows.Automation.ControlType]::Edit)),
+ (New-Object System.Windows.Automation.PropertyCondition($A::NameProperty, 'Page address')))
+foreach ($w in $A::RootElement.FindAll([System.Windows.Automation.TreeScope]::Children, $pid_)) {
+ if (-not $w.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $edit)) { continue }
+ $b = $w.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $now)
+ if ($b -and $b.Current.IsEnabled) { $b.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke(); 'PRESSED'; break }
+}`;
+ return /PRESSED/.test(spawnSync("powershell", ["-NoProfile", "-Command", script], { encoding: "utf8" }).stdout);
+}
+
// Whether the Download video window's "Download Now" is enabled: yt-dlp looked the address up
// and offered something to download (#155). null while the window isn't open.
function videoReady(pid) {
@@ -1235,7 +1274,8 @@ const mainPart = async (session, b) => {
// The button's menu, then "All qualities and subtitles…" in it (openInMdm): the app's Download
// video window opens; the address it shows.
// `shot`: a picture of that window first (PrintWindow: off the screens too), for a PR's body.
-async function clickButton(session, b, shot = "") {
+// `open`: the window is left open (closed otherwise).
+async function clickButton(session, b, shot = "", open = false) {
const pid = appPid();
appWindows(pid, VIDEO_WINDOW);
await until("the Download video window closed", 5000, () => !appWindows(pid).includes(VIDEO_WINDOW));
@@ -1246,7 +1286,7 @@ async function clickButton(session, b, shot = "") {
await sleep(1500);
spawnSync("powershell", ["-NoProfile", "-File", path.join(root, "tools", "lab", "cap-own.ps1"), "-ProcessId", String(pid), "-Title", VIDEO_WINDOW, "-Out", shot]);
}
- appWindows(pid, VIDEO_WINDOW);
+ if (!open) appWindows(pid, VIDEO_WINDOW);
return address;
}
@@ -2488,6 +2528,80 @@ const CASES = {
}
},
+ // #695, #800: a video a server's program sends (/remote_control.php, /stream.php as video/mp4,
+ // no Content-Disposition), on a page titled "Lab lecture: week N". The toolbar button's list
+ // names it after the page with its type ("Lab lecture week 1.mp4 · MP4", never
+ // "remote_control.php · PHP"), and MDM saves it so from there; the button over its player (a
+ // plain file) saves "Lab lecture week 2.mp4"; with yt-dlp, the Download video window lists a
+ // `stream.php?file=` video as MP4 and saves an .mp4 (yt-dlp refused a .php). E2E_SHOTS:
+ // <lang>-media-list.png (the popup's list) and <lang>-video-window.png (that window, Windows).
+ async scripted(t) {
+ const shots = process.env.E2E_SHOTS ? path.resolve(process.env.E2E_SHOTS) : "";
+ const lang = process.env.E2E_LANG || "en";
+ const page = (week, src) => `${LAB}/page?title=${encodeURIComponent(`Lab lecture: week ${week}`)}&video=${encodeURIComponent(src)}`;
+ const said = [];
+ // An earlier browser's files of the same names off the list and the disk: they'd be numbered.
+ const earlier = (await mdmList()).filter((d) => /^Lab lecture/.test(d.file)).map((d) => d.id);
+ if (earlier.length) await ipc({ action: "delete", ids: earlier });
+ // The list: named after the page, typed by its server.
+ await t.session.navigate(page(1, `/remote_control.php?id=${t.name}&seed=11`));
+ const at = await t.session.evaluate("location.href");
+ const popup = await t.session.tab(`${t.session.base}popup.html?page=${encodeURIComponent(at)}`);
+ const first = "Lab lecture week 1.mp4";
+ try {
+ const rows = () =>
+ popup.evaluate(`[...document.querySelectorAll("#media-list li")].map((li) => ({
+ tag: li.querySelector(".tag").textContent, name: li.querySelector(".name").textContent }))`);
+ const listed = await until("the popup's media list", 15000, async () => {
+ const r = await rows().catch(() => []);
+ return r.length >= 1 && r;
+ });
+ await sleep(500);
+ if (shots && popup.shot) await popup.shot(path.join(shots, `${lang}-media-list.png`));
+ if (listed.length !== 1 || listed[0].tag !== "MP4" || listed[0].name !== first) {
+ throw new Error(`the list shows ${JSON.stringify(listed)}, not MP4 ${first}`);
+ }
+ await popup.evaluate(`(() => { document.querySelector("#media-list li button").click(); return true; })()`);
+ await arrived(first, 1 << 20, "Video");
+ said.push(`list: MP4 ${first}, saved as it`);
+ } finally {
+ await popup.close();
+ }
+ // The button over its player: the file at once, named the same way.
+ await t.session.navigate(page(2, `/stream.php?id=${t.name}&seed=12`));
+ const v = await rect(t.session, "#video");
+ const b = await hover(t.session, v);
+ if (!b) throw new Error("no button over the video");
+ await t.session.mouse(await mainPart(t.session, b), (b.t + b.b) / 2, "click");
+ await arrived("Lab lecture week 2.mp4", 1 << 20, "Video");
+ said.push("button: Lab lecture week 2.mp4");
+ // The Download video window (#695): yt-dlp's look-up of a `file=` address, typed MP4.
+ if (!WIN || !ytdlp) return `${said.join("; ")} (no Download video window: ${WIN ? "no yt-dlp" : NO_UIA})`;
+ const file = `/stream.php?file=e2e-${t.name}.mp4&token=x&seed=13`;
+ await t.session.navigate(page(3, file));
+ const v3 = await rect(t.session, "#video");
+ const b3 = await hover(t.session, v3);
+ if (!b3) throw new Error("no button over the third video");
+ const address = await clickButton(t.session, b3, "", true);
+ if (address !== `${LAB}${file}`) throw new Error(`the video window got ${address}`);
+ const pid = appPid();
+ await until("yt-dlp's lookup (Download Now enabled)", 60000, () => videoReady(pid));
+ await sleep(1000);
+ if (shots) spawnSync("powershell", ["-NoProfile", "-File", path.join(root, "tools", "lab", "cap-own.ps1"), "-ProcessId", String(pid), "-Title", VIDEO_WINDOW, "-Out", path.join(shots, `${lang}-video-window.png`)]);
+ const before = new Set((await mdmList()).map((d) => d.id));
+ if (!videoDownloadNow(pid)) throw new Error("no Download Now to press");
+ const done = await until("the Download video window's download", 60000, async () => {
+ const d = (await mdmList()).find((x) => !before.has(x.id));
+ if (d && d.status === "Error") throw new Error(`it failed: ${d.error}`);
+ return d && d.status === "Complete" ? d : null;
+ });
+ if (!/\.mp4$/.test(done.file) || path.dirname(path.resolve(done.path)) !== path.join(downloads, "Video")) {
+ throw new Error(`the window saved ${done.path}`);
+ }
+ said.push(`window: ${done.file}`);
+ return said.join("; ");
+ },
+
// A page that moves in place (history.pushState, as YouTube does between videos): the button
// hands the app the address it is at now, not the one the document loaded at.
async inplace(t) {
diff --git a/tools/extension/test.mjs b/tools/extension/test.mjs
index 66f24b46..f866bf7a 100644
--- a/tools/extension/test.mjs
+++ b/tools/extension/test.mjs
@@ -938,7 +938,14 @@ const ok = (what) => {
const r = await ask(listeners, { type: "video", src: "https://cdn.test/v/clip.mp4", url: "https://news.test/story", direct: true, title: "" }, from);
assert.deepEqual(r, { ok: true, show: "https://cdn.test/v/clip.mp4" });
const v = natives(calls).filter((x) => x.video).at(-1);
- assert.deepEqual([v.direct, v.src], [true, "https://cdn.test/v/clip.mp4"]);
+ assert.deepEqual([v.direct, v.src, v.mime], [true, "https://cdn.test/v/clip.mp4", undefined]);
+ // #800: a file the tab loaded goes with the type its server said (a script's answer is named
+ // by it at once), and the page's title.
+ listeners.responseStarted({ tabId: 5, frameId: 0, type: "media", url: "https://cdn.test/remote_control.php?id=4", statusCode: 200, responseHeaders: [{ name: "Content-Type", value: "video/mp4" }, { name: "Content-Length", value: "9000000" }] });
+ await settle();
+ await ask(listeners, { type: "video", src: "https://cdn.test/remote_control.php?id=4", url: "https://news.test/story", direct: true, title: "A talk" }, from);
+ const s = natives(calls).filter((x) => x.video).at(-1);
+ assert.deepEqual([s.direct, s.mime, s.title], [true, "video/mp4", "A talk"]);
// `direct` without a file of its own: the page, as before.
await ask(listeners, { type: "video", url: "https://news.test/story", direct: true, src: "blob:https://news.test/x" }, from);
assert.equal(natives(calls).filter((x) => x.video).at(-1).direct, undefined);
@@ -1105,6 +1112,98 @@ const MPD = (protect) => `<?xml version="1.0"?>
assert.equal((await popupAsk(listeners, { type: "media", tab: 9 })).media.length, 0);
ok("media list: cleared on another page, kept within one");
}
+{
+ // #695, #800: a video a server's program sends (`remote_control.php`, `stream.php?file=…`) is
+ // listed and saved as the app's engine names it: the tab's title (or the `file=` value) and the
+ // type its server said, never "remote_control.php · PHP". The popup's switch puts the title
+ // before a real name.
+ const tabs = { 9: { id: 9, url: "https://watch.test/v/2", title: "Movie: the title", incognito: false } };
+ const { api, calls, listeners } = fakeApi({ firefox: false, frames: { 0: { href: "https://watch.test/v/2", players: [] } }, tabs });
+ load(api, false);
+ listeners.tabUpdated(9, { url: "https://watch.test/v/2" });
+ await settle();
+ const big = (type) => H(type, { "Content-Length": "176900000" });
+ const script = "https://files.test/remote_control.php?id=7&t=1";
+ const given = "https://files.test/baigiang/stream.php?file=FL262-1E01-4.mp4&token=x";
+ const bare = "https://files.test/videoplayback?id=3";
+ const real = "https://files.test/a/movie.mp4";
+ for (const [u, type] of [[script, "video/mp4"], [given, "video/mp4"], [bare, "video/webm"], [real, "video/mp4"]]) {
+ listeners.responseStarted(res(u, "media", big(type)));
+ }
+ await settle();
+ const list = async () => (await popupAsk(listeners, { type: "media", tab: 9 })).media.map((m) => [m.name, m.ext]);
+ assert.deepEqual(await list(), [
+ ["Movie the title.mp4", "mp4"],
+ ["FL262-1E01-4.mp4", "mp4"],
+ ["Movie the title.webm", "webm"],
+ ["movie.mp4", "mp4"],
+ ]);
+ const saved = async (u) => {
+ await popupAsk(listeners, { type: "media-download", tab: 9, url: u });
+ const m = natives(calls).filter((x) => x.url === u).at(-1);
+ return [m.filename, m.title, m.mime];
+ };
+ assert.deepEqual(await saved(script), ["Movie the title.mp4", "Movie: the title", "video/mp4"]);
+ // A name the app gives itself (the `file=` value, a real one) isn't sent: a server's own name
+ // (Content-Disposition) still wins there.
+ assert.deepEqual(await saved(given), ["", "Movie: the title", "video/mp4"]);
+ assert.deepEqual(await saved(real), ["", "Movie: the title", "video/mp4"]);
+ await api.storage.local.set({ mediaTitleName: true });
+ assert.deepEqual(await list(), [
+ ["Movie the title.mp4", "mp4"],
+ ["Movie the title - FL262-1E01-4.mp4", "mp4"],
+ ["Movie the title.webm", "webm"],
+ ["Movie the title - movie.mp4", "mp4"],
+ ]);
+ assert.equal((await saved(given))[0], "Movie the title - FL262-1E01-4.mp4");
+ assert.equal((await saved(bare))[0], "Movie the title.webm");
+ // The popup's tag is the saved file's type (popup.js tagOf), its name the saved one (nameOf).
+ const popup = readFileSync(new URL("../../extension/popup.js", import.meta.url), "utf8");
+ const part = (name) => popup.slice(popup.indexOf(`function ${name}(`), popup.indexOf("\n}\n", popup.indexOf(`function ${name}(`)) + 2);
+ const shown = new Function(`const TYPES = {}; ${part("tagOf")}\n${part("nameOf")}\nreturn [tagOf, nameOf];`)();
+ const [tagOf, nameOf] = shown;
+ const listed = (await popupAsk(listeners, { type: "media", tab: 9 })).media;
+ assert.deepEqual(listed.map((m) => `${nameOf(m)} · ${tagOf(m)}`), [
+ "Movie the title.mp4 · MP4",
+ "Movie the title - FL262-1E01-4.mp4 · MP4",
+ "Movie the title.webm · WEBM",
+ "Movie the title - movie.mp4 · MP4",
+ ]);
+ ok("media list: a script's video named by the title or its file= value, typed by its server (#695, #800)");
+}
+{
+ // The names the extension gives a page's media are the app's engine's (crates/engine/src/naming.rs):
+ // the same cases (crates/engine/tests/data/media-names.json), the same types, the same scripts.
+ const ctx = { URL, URLSearchParams, console: quietConsole, setTimeout, clearTimeout, Promise, TextDecoder, fetch: fakeFetch, navigator: { userAgent: "UA" } };
+ ctx.chrome = fakeApi({ firefox: false }).api;
+ vm.runInNewContext(code, ctx);
+ const cases = JSON.parse(readFileSync(new URL("../../crates/engine/tests/data/media-names.json", import.meta.url), "utf8")).cases;
+ for (const [u, mime, title, want] of cases) assert.equal(ctx.mediaName(u, mime, title, false).name, want, u);
+ const naming = readFileSync(new URL("../../crates/engine/src/naming.rs", import.meta.url), "utf8");
+ const table = naming.slice(naming.indexOf("pub const TYPES"), naming.indexOf("];", naming.indexOf("pub const TYPES")));
+ const rustTypes = Object.fromEntries([...table.matchAll(/\("([^"]+)", "([^"]+)"\)/g)].map((m) => [m[1], m[2]]));
+ assert.ok(Object.keys(rustTypes).length > 30);
+ const types = vm.runInNewContext("TYPE_EXTENSIONS", ctx);
+ assert.deepEqual({ ...types }, rustTypes, "background.js' TYPE_EXTENSIONS is naming.rs' TYPES");
+ const list = (name) => {
+ const at = naming.indexOf(`pub const ${name}`);
+ return [...naming.slice(at, naming.indexOf("];", at)).matchAll(/"([^"]+)"/g)].map((m) => m[1]);
+ };
+ assert.deepEqual([...vm.runInNewContext("SCRIPT_EXTENSIONS", ctx)], list("SCRIPT_EXTENSIONS"));
+ assert.deepEqual([...vm.runInNewContext("PAGE_EXTENSIONS", ctx)], list("PAGE_EXTENSIONS"));
+ const video = readFileSync(new URL("../../extension/video.js", import.meta.url), "utf8");
+ const scripts = JSON.parse(/const SCRIPT_EXTENSIONS = (\[[^\]]+\]);/.exec(video)[1]);
+ assert.deepEqual(scripts, [...list("SCRIPT_EXTENSIONS"), ...list("PAGE_EXTENSIONS")], "video.js knows the same scripts and pages");
+ // The button over a plain file says its type as the address says it: a script's file= value's,
+ // none for a script alone (not "PHP").
+ const at = video.indexOf(" function fileType(");
+ const fileType = new Function(`const SCRIPT_EXTENSIONS = ${JSON.stringify(scripts)};\n${video.slice(at, video.indexOf("\n }\n", at) + 4)}\nreturn fileType;`)();
+ assert.equal(fileType("https://u.test/stream.php?file=FL262-1E01-4.mp4&token=x"), "mp4");
+ assert.equal(fileType("https://u.test/remote_control.php?id=1"), "");
+ assert.equal(fileType("https://u.test/v/clip.webm?x=1"), "webm");
+ assert.equal(fileType("https://u.test/stream.php?file=setup.exe"), "");
+ ok("media names: the extension's are the engine's (types, scripts, cases)");
+}
{
// Bounded: a page loading file after file keeps at most 60 per tab, its first stream (the one
// the button sends) included; at most 50 tabs.