Skip to content

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

Streams without .m3u8/.mpd, served as plain text, found when asked (#171) (#188)

Ahmed Nefzaouiefb0a2e92132
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 394c5372..4b237110 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -350,6 +350,13 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- **Streams served as plain text, from addresses without .m3u8 or .mpd**
+ ([#171](https://github.com/anefzaoui/misterdownloadmanager/issues/171)): some players load
+ their stream from such an address, and the extension didn't know it as one. The button over the
+ video, the right-click menu and **Media on this page** then sent the page alone, which yt-dlp
+ answered "Unsupported URL". Now, when one of them is used and no stream is known, the extension
+ reads the start of what the player fetched (a few kilobytes, never on sight) and recognises an
+ HLS playlist or a DASH manifest.
- **A minimized MDM keeps working**: with the main window minimized (not to the notification
area), queues didn't start their next file, the Scheduler's starts and stops didn't fire,
download limits, the network adapter's kill switch, the clipboard monitor, the update check, the
diff --git a/ROADMAP.md b/ROADMAP.md
index 42d1bf92..73dcf717 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -13,6 +13,9 @@ Everything below ships together, in one release.
### Done
+- ✅ Streams whose address doesn't end in .m3u8 or .mpd, served as plain text, are found too: by
+ the button over the video, the right-click menu and the media list, read only when asked
+ ([#171](https://github.com/anefzaoui/misterdownloadmanager/issues/171))
- ✅ The extension in the [Chrome Web Store](https://chromewebstore.google.com/detail/mister-download-manager/ejoleppdfgjdndddcjoehopknmlglojp): **Add to Chrome** beside **Add to Firefox**
on the website, in the help, the FAQ and the README; MDM's **Add Mister Download Manager to
your browser** window opens the store in Chrome, Edge, Brave, Opera and Vivaldi, with the
@@ -174,8 +177,6 @@ Everything below ships together, in one release.
MDM; no address is sent anywhere ([#140](https://github.com/anefzaoui/misterdownloadmanager/issues/140))
- 🔄 Torrents: download in order, to watch a video while it downloads; the other torrents rarest
first ([#39](https://github.com/anefzaoui/misterdownloadmanager/issues/39))
-- 🔄 A stream whose address doesn't end in `.m3u8` or `.mpd` is still recognised by its contents
- ([#171](https://github.com/anefzaoui/misterdownloadmanager/issues/171))
- 🔄 Firefox: reading the browser's proxy or VPN extension becomes a switch in the add-on, so the
update asks for no new permission ([#42](https://github.com/anefzaoui/misterdownloadmanager/issues/42))
- 🔄 MDM's browser window: the check mark before **Connected** shows in every language (an empty
diff --git a/crates/labserver/assets/stream.js b/crates/labserver/assets/stream.js
index 3928d383..b59182de 100644
--- a/crates/labserver/assets/stream.js
+++ b/crates/labserver/assets/stream.js
@@ -60,8 +60,12 @@
video.src = URL.createObjectURL(new MediaSource());
} catch {}
}
- const run = manifest.pathname.endsWith(".mpd") ? dash : hls;
- run(manifest).then(
+ // HLS or DASH: data-kind, else the address's ending (#171's have none).
+ const kind = script.dataset.kind || (manifest.pathname.endsWith(".mpd") ? "dash" : "hls");
+ const run = kind === "dash" ? dash : hls;
+ // A player's other text first (data-decoy): no manifest, never to be listed.
+ const decoy = script.dataset.decoy ? fetch(new URL(script.dataset.decoy, location.href)).then((r) => r.text()) : Promise.resolve();
+ decoy.then(() => run(manifest)).then(
() => {
const done = Number(document.body.dataset.streamsDone || 0) + 1;
document.body.dataset.streamsDone = String(done);
diff --git a/crates/labserver/src/pages.rs b/crates/labserver/src/pages.rs
index c1e3680c..19898c3c 100644
--- a/crates/labserver/src/pages.rs
+++ b/crates/labserver/src/pages.rs
@@ -58,7 +58,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&
-/// hls=1&dash=1&drm=1&csp=strict`: a web page with what the browser extension acts on (see
+/// 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 {
let pairs = pairs(q);
@@ -73,14 +73,15 @@ pub(crate) async fn page(RawQuery(q): RawQuery) -> Response {
let several = num("several", 0).min(16);
let csp = m.get("csp") == Some(&"strict");
// A player for each stream asked for, in this order.
- let streams: Vec<&str> = [
+ let streams: Vec<(&str, &str)> = [
("hls", "/hls/master.m3u8"),
("dash", "/dash/manifest.mpd"),
("drm", "/dash/protected.mpd"),
+ ("hls2", "/hls2/playlist?id=lab"),
+ ("dash2", "/dash2/manifest?id=lab"),
]
.into_iter()
.filter(|(k, _)| flag(k))
- .map(|(_, m)| m)
.collect();
// `link` may come again: one link each, in order.
let links: Vec<&str> = pairs
@@ -157,15 +158,22 @@ pub(crate) async fn page(RawQuery(q): RawQuery) -> Response {
if let Some(src) = audio {
body += &format!("<audio id=audio src=\"{}\" controls></audio>", esc(src));
}
- for (k, manifest) in streams.iter().enumerate() {
+ for (k, (kind, manifest)) in streams.iter().enumerate() {
let id = if k == 0 {
"player".to_owned()
} else {
format!("player{}", k + 1)
};
+ // #171's have no .m3u8 or .mpd to tell: their kind, and a text answer first that is no
+ // manifest (a player's settings).
+ let more = match *kind {
+ "hls2" => " data-kind=hls data-decoy=\"/hls2/config?id=lab\"",
+ "dash2" => " data-kind=dash data-decoy=\"/hls2/config?id=lab\"",
+ _ => "",
+ };
body += &format!(
"<video id={id} width={} height={} controls></video>\
- <script src=/assets/stream.js data-manifest=\"{manifest}\" data-player={id}>\
+ <script src=/assets/stream.js data-manifest=\"{manifest}\" data-player={id}{more}>\
</script>",
size.0, size.1
);
diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rs
index b44b4c2f..9343b188 100644
--- a/crates/labserver/src/server.rs
+++ b/crates/labserver/src/server.rs
@@ -13,7 +13,8 @@
//! - `GET /hop?to=URL&how=meta|header[&wait=S][&cookie=N=V]` — a page that sends the browser on to
//! `URL` itself (`<meta http-equiv="refresh">` or a `Refresh` header), as download sites' waiting pages do
//! - `GET /page`, `/formpage`, `/cookie`, `/assets/*` — web pages for the browser tests (`pages`)
-//! - `GET /hls/*`, `/dash/*` — adaptive streams (`streams`)
+//! - `GET /hls/*`, `/dash/*` — adaptive streams (`streams`); `/hls2/*`, `/dash2/*` the same with
+//! no `.m3u8`/`.mpd` in their addresses, served as text/plain or octet-stream (#171)
//! - Google Drive's addresses on its own host names (`drive`): links, the virus-scan and quota
//! pages, Docs exports, the sign-in page
//! - `GET /_log` — the request log as JSON; `DELETE /_log` clears it
@@ -315,6 +316,11 @@ impl LabServer {
.route("/dash/manifest.mpd", get(streams::dash_manifest))
.route("/dash/protected.mpd", get(streams::dash_protected))
.route("/dash/{rep}/{file}", get(streams::dash_file))
+ .route("/hls2/playlist", get(streams::hls2_playlist))
+ .route("/hls2/seg", get(streams::hls2_segment))
+ .route("/hls2/config", get(streams::hls2_config))
+ .route("/dash2/manifest", get(streams::dash2_manifest))
+ .route("/dash2/{rep}/{file}", get(streams::dash_file))
.route_layer(axum::middleware::from_fn_with_state(
shared.clone(),
log_simple,
@@ -482,6 +488,9 @@ GET /page?<any of>
#player3), which fetches /hls/master.m3u8, /dash/manifest.mpd or
/dash/protected.mpd, the first variant's and the audio's playlists and every
segment, then sets <body data-stream=done> once all are (or error)
+ hls2=1, dash2=1 the same for /hls2/playlist?id=lab and /dash2/manifest?id=lab (no .m3u8 or
+ .mpd, text/plain and octet-stream, #171); each player first fetches
+ /hls2/config?id=lab, a text/plain answer that is no manifest
csp=strict Content-Security-Policy: default-src 'none'; style-src 'self'; img-src 'self';
media-src 'self'; script-src 'self' (+ frame-src 'self' with iframe,
+ connect-src 'self' and media-src blob: with hls or dash)
@@ -501,6 +510,12 @@ GET /dash/manifest.mpd (application/dash+xml) the same tracks as Representation
SegmentTemplate: /dash/{720p,360p,audio}/init.mp4 and seg1..3.m4s (video/mp4, audio/mp4)
GET /dash/protected.mpd the same, each AdaptationSet marked encrypted (CENC, Widevine's
ContentProtection), as a DRM-protected stream's manifest is
+GET /hls2/playlist?id=ID the HLS stream again with no .m3u8 anywhere, all text/plain (#171):
+ variants playlist?id=ID&track={720p,360p,audio}, segments seg?id=ID&track=T&i=0..2
+ (application/octet-stream)
+GET /dash2/manifest?id=ID the DASH manifest as application/octet-stream, no .mpd; segments
+ /dash2/{720p,360p,audio}/init.mp4 and seg1..3.m4s
+GET /hls2/config?id=ID {"autoplay":false,"volume":0.8} as text/plain: not a manifest
GOOGLE DRIVE a fake one for the engine's tests, on Google's host names (resolve
drive.google.com, drive.usercontent.google.com, docs.google.com, accounts.google.com and
diff --git a/crates/labserver/src/streams.rs b/crates/labserver/src/streams.rs
index 3a3f1fcc..46032e61 100644
--- a/crates/labserver/src/streams.rs
+++ b/crates/labserver/src/streams.rs
@@ -5,9 +5,12 @@
//! 188-byte packet with the 0x47 sync byte, DASH init segments with an `ftyp` box), enough for a
//! client that lists, fetches or joins segments, not for one that decodes them.
-use axum::extract::Path;
+use std::collections::HashMap;
+
+use axum::extract::{Path, Query};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
+use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use crate::content;
@@ -185,6 +188,73 @@ fn mpd(protected: bool) -> String {
s
}
+/// #171: the same HLS stream with no `.m3u8` in any address and served as `text/plain`, as some
+/// CDNs and players do: `/hls2/playlist?id=ID` (the master), `/hls2/playlist?id=ID&track=T` (a
+/// media playlist) and `/hls2/seg?id=ID&track=T&i=N` (`application/octet-stream`).
+pub(crate) async fn hls2_playlist(Query(q): Query<HashMap<String, String>>) -> Response {
+ let id = utf8_percent_encode(q.get("id").map_or("lab", String::as_str), NON_ALPHANUMERIC)
+ .to_string();
+ let Some(name) = q.get("track") else {
+ let mut s = format!(
+ "#EXTM3U\n#EXT-X-VERSION:3\n\
+ #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"aud\",NAME=\"English\",LANGUAGE=\"en\",\
+ DEFAULT=YES,AUTOSELECT=YES,URI=\"playlist?id={id}&track=audio\"\n"
+ );
+ for t in &TRACKS {
+ if let Some((w, h)) = t.video {
+ s += &format!(
+ "#EXT-X-STREAM-INF:BANDWIDTH={},RESOLUTION={w}x{h},\
+ CODECS=\"avc1.4d401f,mp4a.40.2\",AUDIO=\"aud\"\nplaylist?id={id}&track={}\n",
+ t.bandwidth, t.name
+ );
+ }
+ }
+ return text(PLAIN, s);
+ };
+ if track(name).is_none() {
+ return StatusCode::NOT_FOUND.into_response();
+ }
+ let mut s = format!(
+ "#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:{SEGMENT_SECS}\n\
+ #EXT-X-MEDIA-SEQUENCE:0\n#EXT-X-PLAYLIST-TYPE:VOD\n"
+ );
+ for i in 0..SEGMENTS {
+ s += &format!("#EXTINF:{SEGMENT_SECS}.000,\nseg?id={id}&track={name}&i={i}\n");
+ }
+ s += "#EXT-X-ENDLIST\n";
+ text(PLAIN, s)
+}
+
+const PLAIN: &str = "text/plain; charset=utf-8";
+
+/// `/hls2/seg?track=T&i=N`: segment N of track T, as `application/octet-stream`.
+pub(crate) async fn hls2_segment(Query(q): Query<HashMap<String, String>>) -> Response {
+ let found = q.get("track").and_then(|n| track(n));
+ let i = q.get("i").and_then(|i| i.parse::<u32>().ok());
+ match (found, i) {
+ (Some((ti, t)), Some(i)) if i < SEGMENTS => {
+ let mut buf = segment(ti, i, t.segment_len);
+ for packet in buf.chunks_mut(TS_PACKET) {
+ packet[0] = 0x47;
+ }
+ bytes("application/octet-stream", buf)
+ }
+ _ => StatusCode::NOT_FOUND.into_response(),
+ }
+}
+
+/// `/dash2/manifest?id=ID`: the DASH manifest with no `.mpd` in its address, served as
+/// `application/octet-stream`; its segments are `/dash2/{rep}/init.mp4` and `seg{n}.m4s`.
+pub(crate) async fn dash2_manifest() -> Response {
+ text("application/octet-stream", mpd(false))
+}
+
+/// `/hls2/config?id=ID`: a player's settings as `text/plain`, not a manifest (the pages' decoy:
+/// the extension may read it and must never list it).
+pub(crate) async fn hls2_config() -> Response {
+ text(PLAIN, "{\"autoplay\":false,\"volume\":0.8}\n".to_owned())
+}
+
/// `/dash/{rep}/init.mp4` and `/dash/{rep}/seg{n}.m4s` (n from 1).
pub(crate) async fn dash_file(Path((name, file)): Path<(String, String)>) -> Response {
let Some((ti, t)) = track(&name) else {
diff --git a/crates/labserver/tests/http.rs b/crates/labserver/tests/http.rs
index 07e62f14..facc5dc6 100644
--- a/crates/labserver/tests/http.rs
+++ b/crates/labserver/tests/http.rs
@@ -616,6 +616,70 @@ async fn hls_and_dash() {
assert_eq!(r.status(), 404);
}
+/// #171: the same streams with no .m3u8 or .mpd in any address, as text/plain and octet-stream,
+/// and the pages that play them (a decoy text answer first).
+#[tokio::test]
+async fn hls_and_dash_without_their_endings_or_types() {
+ let s = server("").await;
+ let (h, master) = text(&s, "/hls2/playlist?id=x%201").await;
+ assert_eq!(h["content-type"], "text/plain; charset=utf-8");
+ assert!(master.starts_with("#EXTM3U\n") && master.contains("RESOLUTION=1280x720"));
+ assert!(master.contains("URI=\"playlist?id=x%201&track=audio\""));
+ let variants: Vec<&str> = master.lines().filter(|l| !l.starts_with('#')).collect();
+ assert_eq!(
+ variants,
+ [
+ "playlist?id=x%201&track=720p",
+ "playlist?id=x%201&track=360p"
+ ]
+ );
+ assert!(!master.contains(".m3u8"));
+ for (track, len) in [("720p", 48128), ("audio", 6016)] {
+ let (h, media) = text(&s, &format!("/hls2/playlist?id=x%201&track={track}")).await;
+ assert_eq!(h["content-type"], "text/plain; charset=utf-8");
+ assert!(media.contains("#EXT-X-ENDLIST"));
+ let segs: Vec<&str> = media.lines().filter(|l| !l.starts_with('#')).collect();
+ assert_eq!(segs.len(), 3);
+ assert_eq!(segs[0], format!("seg?id=x%201&track={track}&i=0"));
+ let r = reqwest::get(s.url(&format!("/hls2/{}", segs[2])))
+ .await
+ .unwrap();
+ assert_eq!(r.headers()["content-type"], "application/octet-stream");
+ let b = r.bytes().await.unwrap();
+ assert_eq!(b.len(), len);
+ assert!(b.iter().step_by(188).all(|x| *x == 0x47));
+ }
+ for missing in [
+ "/hls2/playlist?id=a&track=1080p",
+ "/hls2/seg?track=720p&i=3",
+ "/hls2/seg?track=720p",
+ ] {
+ let r = reqwest::get(s.url(missing)).await.unwrap();
+ assert_eq!(r.status(), 404, "{missing}");
+ }
+ let (h, mpd) = text(&s, "/dash2/manifest?id=lab").await;
+ assert_eq!(h["content-type"], "application/octet-stream");
+ assert!(mpd.contains("<MPD ") && mpd.contains("<Representation id=\"360p\""));
+ let r = reqwest::get(s.url("/dash2/720p/init.mp4")).await.unwrap();
+ assert_eq!(&r.bytes().await.unwrap()[4..8], b"ftyp");
+ let (h, config) = text(&s, "/hls2/config?id=lab").await;
+ assert_eq!(h["content-type"], "text/plain; charset=utf-8");
+ assert!(config.starts_with('{') && !config.contains("#EXTM3U"));
+
+ let (_, page) = text(&s, "/page?hls2=1&dash2=1").await;
+ assert!(page.contains(
+ "data-manifest=\"/hls2/playlist?id=lab\" data-player=player data-kind=hls \
+ data-decoy=\"/hls2/config?id=lab\">"
+ ));
+ assert!(
+ page.contains(
+ "data-manifest=\"/dash2/manifest?id=lab\" data-player=player2 data-kind=dash"
+ )
+ );
+ let (_, js) = text(&s, "/assets/stream.js").await;
+ assert!(js.contains("dataset.kind") && js.contains("dataset.decoy"));
+}
+
#[tokio::test]
async fn help_lists_the_routes() {
let s = server("").await;
@@ -645,6 +709,10 @@ async fn help_lists_the_routes() {
"/dash/manifest.mpd",
"/dash/protected.mpd",
"drm=1",
+ "hls2=1",
+ "/hls2/playlist?id=",
+ "/dash2/manifest?id=",
+ "/hls2/config?id=",
"req_body_sha256",
"referer",
] {
diff --git a/docs/browser-integration.md b/docs/browser-integration.md
index 15cf58b2..b1b8ee3d 100644
--- a/docs/browser-integration.md
+++ b/docs/browser-integration.md
@@ -82,7 +82,10 @@ too. The toolbar button lists what the page has loaded, so you can still save it
- **Streams**: HLS (`.m3u8`) and DASH (`.mpd`), the way most sites play long videos. Each stream
is listed once, however many qualities its player switched between, with its qualities (`1080p ·
- 720p`) and its length when the extension can read them.
+ 720p`) and its length when the extension can read them. A stream whose address doesn't end in
+ `.m3u8` or `.mpd`, served as plain text, is found too: when you open the list (or press the
+ download button over its player) and the player plays a stream, the extension reads the first
+ few kilobytes of what that player fetched to recognise it. Nothing is read until you ask.
- **Video and sound files** the page played (MP4, WebM, MP3 and the like), with their size and,
for a video, its picture size.
diff --git a/extension/background.js b/extension/background.js
index a58331b0..f9cdfd82 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -337,6 +337,11 @@ const SEGMENT_TYPE = /^(video\/mp2t|video\/iso\.segment|audio\/iso\.segment)$/;
const SEGMENT_EXT = /\.(ts|m4s|m4f|cmfv|cmfa|cmft)$/;
const MEDIA_EXT = /\.(mp4|m4v|webm|mkv|mov|avi|wmv|flv|3gp|ogv|mp3|m4a|aac|ogg|oga|opus|flac|wav|wma)$/;
const AUDIO_EXT = /^(mp3|m4a|aac|oga|ogg|opus|flac|wav|wma)$/;
+// The types a manifest is sometimes served as, besides its own (#171): plain text, no type, a
+// file's, XML. Such an answer is only noted (`maybe`, MAYBE_MAX a tab), never listed unread.
+const MAYBE_TYPE = /^(text\/plain|(application|binary)\/octet-stream|(application|text)\/xml|)$/;
+const MAYBE_MAX = 20;
+const MANIFEST_MAX = 2 << 20;
const pathOf = (url) => url.split(/[?#]/)[0];
const headerOf = (d, name) => ((d.responseHeaders || []).find((h) => h.name.toLowerCase() === name) || {}).value || "";
@@ -352,6 +357,12 @@ function mediaKind(d) {
if (/\.mpd$/.test(path) || /dash\+xml/.test(mime)) return { kind: "dash", mime, size: 0 };
if (SEGMENT_TYPE.test(mime) || SEGMENT_EXT.test(path)) return null;
const ext = (MEDIA_EXT.exec(path) || [])[1] || "";
+ // Maybe a manifest whose address and type don't say so (#171): a player's own small text or
+ // untyped answer, read only when a stream is asked for and none is known (`sniffTab`).
+ if (d.type !== "media" && !ext && MAYBE_TYPE.test(mime) && d.statusCode !== 206 && !headerOf(d, "content-range")) {
+ const len = Number(headerOf(d, "content-length"));
+ return len > MANIFEST_MAX ? null : { kind: "maybe", mime, size: 0 };
+ }
const typed = /^(video|audio)\//.test(mime) || mime === "application/ogg";
const untyped = !mime || /^(application|binary)\/octet-stream$/.test(mime);
if (!typed && !(ext && untyped)) return null;
@@ -408,11 +419,88 @@ function noteMedia(d, found) {
keepMedia();
}
+// A response that may be a manifest (#171), noted apart: the newest MAYBE_MAX of the tab.
+function noteMaybe(d, found) {
+ const tab = media.get(d.tabId) || { page: null, items: [] };
+ if (tab.items.some((it) => it.url === d.url)) return;
+ tab.maybe = (tab.maybe || []).filter((m) => m.url !== d.url);
+ tab.maybe.push({ url: d.url, frameId: d.frameId || 0, mime: found.mime });
+ if (tab.maybe.length > MAYBE_MAX) tab.maybe.splice(0, tab.maybe.length - MAYBE_MAX);
+ if (!media.has(d.tabId)) {
+ media.set(d.tabId, tab);
+ for (const id of media.keys()) {
+ if (media.size <= MEDIA_TABS) break;
+ media.delete(id);
+ }
+ }
+ keepMedia();
+}
+
+// What a text starts as: an HLS playlist ("hls"), a DASH manifest ("dash"), or neither ("").
+function manifestKind(text) {
+ const t = String(text).replace(/^/, "").trimStart();
+ if (t.startsWith("#EXTM3U")) return "hls";
+ // An XML declaration, comments, then the MPD element (with a namespace prefix or not).
+ if (/^(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<(?:[\w-]+:)?MPD[\s>/]/.test(t)) return "dash";
+ return "";
+}
+
+// The start of a response (SNIFF_BYTES), fetched again with the site's cookies as `probe` does:
+// what it is (`manifestKind`), or "" (not a manifest, refused, too slow).
+const SNIFF_BYTES = 4096;
+async function sniff(url) {
+ let reader = null;
+ try {
+ const r = await withTimeout(fetch(url, { credentials: "include" }), 5000);
+ if (!r.ok) return "";
+ if (!r.body || !r.body.getReader) return manifestKind((await withTimeout(r.text(), 5000)).slice(0, SNIFF_BYTES));
+ reader = r.body.getReader();
+ const dec = new TextDecoder();
+ let text = "";
+ while (text.length < SNIFF_BYTES) {
+ const { done, value } = await withTimeout(reader.read(), 5000);
+ if (done) break;
+ text += dec.decode(value, { stream: true });
+ }
+ return manifestKind(text);
+ } catch {
+ return "";
+ } finally {
+ // The rest is never read.
+ if (reader) reader.cancel().catch(() => {});
+ }
+}
+
+// The tab's possible manifests read, those of `frames` only (a Set of frame ids, or null: all),
+// each once: the ones that are become its streams, in the order they were loaded. One reading at
+// a time per tab: a second ask waits for the first.
+const sniffing = new Map();
+function sniffTab(tabId, frames) {
+ const run = async () => {
+ const tab = media.get(tabId);
+ if (!tab || !tab.maybe || !tab.maybe.length) return;
+ const asked = tab.maybe.filter((m) => !frames || frames.has(m.frameId));
+ if (!asked.length) return;
+ tab.maybe = tab.maybe.filter((m) => !asked.includes(m));
+ const kinds = await Promise.all(asked.map((m) => sniff(m.url)));
+ // The tab went to another page meanwhile: its old page's answers don't count.
+ if (media.get(tabId) !== tab) return;
+ asked.forEach((m, i) => {
+ if (kinds[i]) noteMedia({ tabId, url: m.url, frameId: m.frameId }, { kind: kinds[i], mime: m.mime, size: 0 });
+ });
+ keepMedia();
+ };
+ const next = (sniffing.get(tabId) || Promise.resolve()).then(run, run);
+ sniffing.set(tabId, next);
+ next.finally(() => sniffing.get(tabId) === next && sniffing.delete(tabId)).catch(() => {});
+ return next;
+}
+
if (ext.webRequest && ext.webRequest.onResponseStarted) {
ext.webRequest.onResponseStarted.addListener(
(d) => {
const found = mediaKind(d);
- if (found) mediaBack.then(() => noteMedia(d, found));
+ if (found) mediaBack.then(() => (found.kind === "maybe" ? noteMaybe(d, found) : noteMedia(d, found)));
},
{ urls: ["<all_urls>"], types: ["xmlhttprequest", "media", "other"] },
["responseHeaders"],
@@ -450,7 +538,8 @@ const mediaBack = session
for (const [id, kept] of v.media || []) {
const now = media.get(id);
const fresh = ((now && now.items) || []).filter((s) => !kept.items.some((o) => o.url === s.url));
- media.set(id, { ...kept, page: (now && now.page) || kept.page, items: [...kept.items, ...fresh].slice(-MEDIA_MAX) });
+ const maybe = [...(kept.maybe || []), ...((now && now.maybe) || [])].filter((m, i, all) => all.findIndex((o) => o.url === m.url) === i);
+ media.set(id, { ...kept, page: (now && now.page) || kept.page, items: [...kept.items, ...fresh].slice(-MEDIA_MAX), maybe: maybe.slice(-MAYBE_MAX) });
}
})
.catch(() => {})
@@ -463,6 +552,19 @@ function streamOf(sender) {
return (mine || list[0] || {}).url || "";
}
+// The same for a player that plays from a blob: (asked by the button over it or the right-click
+// menu), reading the tab's possible manifests when no stream is known (#171): the frame's own
+// first, then the tab's other frames'.
+async function streamFor(sender) {
+ const tabId = sender.tab && sender.tab.id;
+ if (tabId === undefined || tabId === null) return streamOf(sender);
+ const frameId = sender.frameId || 0;
+ const own = () => ((media.get(tabId) || { items: [] }).items.some((it) => isStream(it) && it.frameId === frameId));
+ if (!own()) await sniffTab(tabId, new Set([frameId]));
+ if (!own() && !streamOf(sender)) await sniffTab(tabId, null);
+ return streamOf(sender);
+}
+
// ---- a stream's manifest: its qualities, length, and whether it is protected -------------------
// An HLS tag's attributes (KEY=value,KEY="value").
@@ -547,7 +649,6 @@ function parseDash(text) {
// A manifest, fetched again by the extension (the player's copy can't be read): its details, or
// {failed: true}: a site that refuses the extension's request (it checks the page that asks) is
// listed without them.
-const MANIFEST_MAX = 2 << 20;
async function probe(item) {
try {
const r = await withTimeout(fetch(item.url, { credentials: "include" }), 5000);
@@ -577,9 +678,7 @@ function mediaElements() {
// (qualities, length, size, protected). Manifests are read once.
async function mediaList(tabId) {
await mediaBack;
- const tab = media.get(tabId);
- if (!tab) return [];
- await Promise.all(tab.items.filter((it) => isStream(it) && !it.info).map(async (it) => (it.info = await probe(it))));
+ if (!media.get(tabId)) return [];
const frames = {};
try {
const found = await withTimeout(ext.scripting.executeScript({ target: { tabId, allFrames: true }, func: mediaElements }), 3000);
@@ -587,6 +686,14 @@ async function mediaList(tabId) {
} catch {
// A page extensions may not read: listed without its players' details.
}
+ // #171: the possible manifests of frames whose player plays from a blob: (a MediaSource), read.
+ const fed = Object.entries(frames)
+ .filter(([, f]) => f.players.some((v) => /^blob:/i.test(v.src)))
+ .map(([id]) => Number(id));
+ if (fed.length) await sniffTab(tabId, new Set(fed));
+ const tab = media.get(tabId);
+ if (!tab) return [];
+ 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();
const out = [];
@@ -1139,7 +1246,7 @@ ext.contextMenus.onClicked.addListener(async (info, tab) => {
if ((url && /^(blob|mediastream):/i.test(url)) || (player && !url)) {
const page = info.frameUrl || info.pageUrl;
await mediaBack;
- const src = streamOf({ tab, frameId: info.frameId || 0 });
+ const src = await streamFor({ tab, frameId: info.frameId || 0 });
const reply = await native({
video: true,
explicit: true,
@@ -1257,7 +1364,7 @@ async function pageMessage(m, sender) {
}
if (m.type === "video" && page) {
await mediaBack;
- const src = typeof m.src === "string" && /^https?:/i.test(m.src) ? m.src : streamOf(sender);
+ const src = typeof m.src === "string" && /^https?:/i.test(m.src) ? m.src : await streamFor(sender);
const reply = await native({
video: true,
url: page,
diff --git a/tools/extension/e2e.mjs b/tools/extension/e2e.mjs
index 4bd9c66e..9914e591 100644
--- a/tools/extension/e2e.mjs
+++ b/tools/extension/e2e.mjs
@@ -13,7 +13,9 @@
// forwarded), names (Content-Disposition), redirect, form (POST, 303), alt (Alt+click leaves it
// to the browser), opened (a PDF or MP3 the browser would show or play), csp (the video button
// under a strict CSP), hls (the stream a player loaded), streams (HLS and DASH players handed over
-// by the button, the right-click menu and the media list, and read by yt-dlp; #155), media (the
+// by the button, the right-click menu and the media list, and read by yt-dlp; #155; also with no
+// .m3u8 or .mpd, served as text/plain or octet-stream, #171), sniffed (#171 without yt-dlp: such
+// streams found only when asked, by the button and the media list, a text decoy never), media (the
// toolbar button's list of the media a tab loaded: streams, files, a protected stream; #38), video (shown, clicked, dragged,
// kept; "never on the site" in the last browser), start (MDM not running: the host starts it).
//
@@ -717,8 +719,10 @@ async function streamLookedUp(trigger, manifest, page, cookie) {
appWindows(pid, VIDEO_WINDOW);
}
const got = await asked();
- const first = got.find((x) => x.path === manifest);
- if (!first) throw new Error(`yt-dlp didn't ask for ${manifest}: ${got.map((x) => x.path).join(", ")}`);
+ // The address with its query: #171's master and variants share one path.
+ const full = (x) => `${x.path}${x.query ? `?${x.query}` : ""}`;
+ const first = got.find((x) => full(x) === manifest);
+ if (!first) throw new Error(`yt-dlp didn't ask for ${manifest}: ${got.map(full).join(", ")}`);
if (got.some((x) => x.path === "/page")) throw new Error("yt-dlp was given the page too");
if (!(first.cookie || "").includes(cookie)) throw new Error(`${manifest} without the cookie ${cookie}: ${first.cookie}`);
return `${address.replace(LAB, "")} read by yt-dlp${ready ? "" : "?"} (cookie, referrer)`;
@@ -1096,7 +1100,15 @@ const CASES = {
throw e;
}
};
- for (const [kind, manifest] of [["hls", "/hls/master.m3u8"], ["dash", "/dash/manifest.mpd"]]) {
+ // #171: the same with no .m3u8 or .mpd and served as text/plain or octet-stream, after a
+ // text answer that is no manifest (the player's settings, never sent).
+ const kinds = [
+ ["hls", "/hls/master.m3u8"],
+ ["dash", "/dash/manifest.mpd"],
+ ["hls2", "/hls2/playlist?id=lab"],
+ ["dash2", "/dash2/manifest?id=lab"],
+ ];
+ for (const [kind, manifest] of kinds) {
await t.session.navigate(`${LAB}/page?${kind}=1`);
const state = await until("the stream player", 15000, () => t.session.evaluate("document.body.dataset.stream || ''"));
if (state !== "done") throw new Error(`the page's ${kind} player: ${state}`);
@@ -1119,7 +1131,7 @@ const CASES = {
// The toolbar button's media list.
const popup = await t.session.tab(`${t.session.base}popup.html?page=${encodeURIComponent(page)}`);
try {
- const name = manifest.split("/").pop();
+ const name = manifest.split("?")[0].split("/").pop();
await until("the popup's media list", 15000, () =>
popup.evaluate(`[...document.querySelectorAll("#media-list li")].some((li) => li.querySelector(".name").textContent === ${JSON.stringify(name)} && li.querySelector("button"))`),
);
@@ -1137,6 +1149,60 @@ const CASES = {
return done.join("; ");
},
+ // #171: a page whose players load streams with no .m3u8 or .mpd in any address, served as
+ // text/plain (HLS) and application/octet-stream (DASH), each after a text answer that is no
+ // manifest. Nothing is read while the page plays; the button over the player sends the HLS
+ // master; the media list shows the two streams with their qualities, and nothing else.
+ async sniffed(t) {
+ const play = async (q) => {
+ await clearLog();
+ await t.session.navigate(`${LAB}/page?${q}`);
+ const state = await until("the stream players", 20000, () => t.session.evaluate("document.body.dataset.stream || ''"));
+ if (state !== "done") throw new Error(`the page's players: ${state}`);
+ return t.session.evaluate("location.href");
+ };
+ const masters = async () => (await (await fetch(`${LAB}/_log`)).json()).filter((x) => x.path === "/hls2/playlist" && x.query === "id=lab");
+ // The HLS player alone (two players race: either manifest could come first).
+ await play("hls2=1");
+ await sleep(500);
+ const before = (await masters()).length;
+ if (before !== 1) throw new Error(`the master was asked for ${before} times while the page played (the player's once)`);
+ // The button over the HLS player: no stream known, the frame's possible manifests are read.
+ const v = await rect(t.session, "#player");
+ const b = await hover(t.session, v);
+ if (!b) throw new Error("no button over the stream's player");
+ const address = await clickButton(t.session, b);
+ const want = `${LAB}/hls2/playlist?id=lab`;
+ if (address !== want) throw new Error(`the video window got ${address}, not ${want}`);
+ const read = (await masters()).length - before;
+ // The media list, on the page played again (nothing known yet).
+ const page = await play("hls2=1&dash2=1");
+ const popup = await t.session.tab(`${t.session.base}popup.html?page=${encodeURIComponent(page)}`);
+ try {
+ const rows = () =>
+ popup.evaluate(`[...document.querySelectorAll("#media-list li")].map((li) => ({
+ tag: li.querySelector(".tag").textContent, name: li.querySelector(".name").textContent,
+ meta: li.querySelector(".meta").textContent, get: Boolean(li.querySelector("button")) }))`);
+ await until("the popup's media list", 15000, async () => (await rows().catch(() => [])).length >= 2);
+ await sleep(500);
+ const all = await rows();
+ const want = [
+ ["HLS", "playlist", "720p · 360p"],
+ ["DASH", "manifest", "720p · 360p · 0:12"],
+ ];
+ for (const [tag, name, meta] of want) {
+ const r = all.find((x) => x.tag === tag && x.name === name);
+ if (!r) throw new Error(`not listed: ${tag} ${name} (the list: ${JSON.stringify(all)})`);
+ if (!r.meta.startsWith(meta) || !r.get) throw new Error(`${name}: ${JSON.stringify(r)}, not "${meta}" with a Download button`);
+ }
+ if (all.length !== want.length) throw new Error(`${all.length} rows, not ${want.length}: ${JSON.stringify(all)}`);
+ await keptNothing(t.dl);
+ return `nothing read while playing; the button sent ${address.replace(LAB, "")} (then the master was asked for ${read} more times, the extension's read among them); listed ${all.map((r) => `${r.tag} ${r.name} (${r.meta})`).join(", ")}, not the settings`;
+ } finally {
+ await popup.close();
+ }
+ },
+
// #38: the toolbar button's list of what the tab loaded. A page plays a video file (behind a
// cookie and hotlink protection), a sound, an HLS stream, a DASH stream and a DRM-protected
// one; the popup (its page, in a tab of its own) lists the five, each stream once with its
diff --git a/tools/extension/test.mjs b/tools/extension/test.mjs
index 5f686bc6..22c25c3c 100644
--- a/tools/extension/test.mjs
+++ b/tools/extension/test.mjs
@@ -139,7 +139,17 @@ async function fakeFetch(url, opts) {
fetched.push([String(url), opts && opts.credentials]);
const r = served[url];
if (!r) throw new TypeError("Failed to fetch");
- return { ok: (r.status || 200) < 300, status: r.status || 200, headers: { get: () => null }, text: async () => r.body };
+ // Its body as a stream too, 1 KB a chunk: `r.read` counts what was pulled (#171 reads 4 KB).
+ const bytes = new TextEncoder().encode(r.body);
+ r.read = 0;
+ const body = new ReadableStream({
+ pull(c) {
+ if (r.read >= bytes.length) return c.close();
+ c.enqueue(bytes.slice(r.read, r.read + 1024));
+ r.read += 1024;
+ },
+ });
+ return { ok: (r.status || 200) < 300, status: r.status || 200, headers: { get: () => null }, body, text: async () => r.body };
}
function load(api, firefox) {
@@ -740,6 +750,124 @@ const MPD = (protect) => `<?xml version="1.0"?>
ok("media list: kept across the script's restarts; the popup in a tab");
}
+// #171: a manifest whose address and type don't say so (text/plain, octet-stream, no .m3u8 or
+// .mpd) is noted, never read on sight, and read (its first 4 KB) only when a stream is asked
+// for: the popup's list for a frame whose player plays from a blob:, the button, the menu.
+{
+ const PL = "https://cdn.test/p/playlist?id=7";
+ const PL_720 = "https://cdn.test/p/playlist?id=7&v=720";
+ const DASH = "https://cdn.test/q/manifest?id=7";
+ const CONFIG = "https://cdn.test/p/config?id=7";
+ const FEED = "https://cdn.test/p/feed";
+ const LONG = "https://cdn.test/p/log";
+ served = {
+ [PL]: { body: "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1280000,RESOLUTION=1280x720\nplaylist?id=7&v=720\n" },
+ [PL_720]: { body: "#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXTINF:4.0,\nseg?i=0\n#EXT-X-ENDLIST\n" },
+ // With a byte order mark and a comment before the MPD.
+ [DASH]: { body: `<?xml version="1.0"?>\n<!-- made by a packager -->\n${MPD(false).replace(/^<\?xml[^>]*\?>\n/, "")}` },
+ [CONFIG]: { body: '{"autoplay":true}' },
+ [FEED]: { body: '<?xml version="1.0"?><rss><channel><title>MPD news</title></channel></rss>' },
+ // Text going on and on: only its start is read.
+ [LONG]: { body: "x".repeat(200_000) },
+ };
+ const blob = { 0: { href: "https://watch.test/v/3", players: [{ src: "blob:https://watch.test/a", w: 0, h: 0, duration: 0, drm: false }] } };
+ const tabs = { 9: { id: 9, url: "https://watch.test/v/3", title: "Clip", incognito: false } };
+ const { api, calls, listeners } = fakeApi({ firefox: false, frames: blob, tabs });
+ load(api, false);
+ listeners.tabUpdated(9, { url: "https://watch.test/v/3" });
+ await settle();
+ fetched.length = 0;
+ for (const d of [
+ res(PL, "xmlhttprequest", H("text/plain; charset=utf-8")),
+ res(PL_720, "xmlhttprequest", H("text/plain")),
+ res("https://cdn.test/p/seg?i=0", "xmlhttprequest", H("video/mp2t")),
+ res(DASH, "xmlhttprequest", H("application/octet-stream")),
+ res(CONFIG, "xmlhttprequest", H("text/plain")),
+ res(FEED, "other", H("application/xml")),
+ res(LONG, "xmlhttprequest", []),
+ // Not possible manifests: too large, a piece, a media element's own file, a page, JSON.
+ res("https://cdn.test/p/huge", "xmlhttprequest", H("text/plain", { "Content-Length": String(3 << 20) })),
+ res("https://cdn.test/p/part", "xmlhttprequest", H("application/octet-stream", { "Content-Range": "bytes 0-9/99" }), { statusCode: 206 }),
+ res("https://cdn.test/p/el", "media", H("text/plain")),
+ res("https://cdn.test/p/page", "xmlhttprequest", H("text/html")),
+ res("https://cdn.test/p/api", "xmlhttprequest", H("application/json")),
+ ]) {
+ listeners.responseStarted(d);
+ }
+ await settle();
+ assert.equal(fetched.length, 0, "nothing read on sight");
+ const { media } = await popupAsk(listeners, { type: "media", tab: 9 });
+ assert.deepEqual(
+ media.map((m) => [m.kind, m.url]),
+ [
+ ["hls", PL],
+ ["dash", DASH],
+ ],
+ "the manifests become streams (the variant inside its master); the rest stays unlisted",
+ );
+ assert.deepEqual(media[0].heights, [720]);
+ assert.deepEqual([media[1].heights, media[1].duration], [[1080, 480], 90]);
+ const sniffed = new Set(fetched.map(([u]) => u));
+ for (const u of [PL, PL_720, DASH, CONFIG, FEED, LONG]) assert.ok(sniffed.has(u), `read: ${u}`);
+ for (const u of ["https://cdn.test/p/huge", "https://cdn.test/p/part", "https://cdn.test/p/el", "https://cdn.test/p/page", "https://cdn.test/p/api"]) {
+ assert.ok(!sniffed.has(u), `never read: ${u}`);
+ }
+ // 4 KB, and the stream's own read-ahead of a chunk or two.
+ assert.ok(served[LONG].read <= 6 * 1024, `only the start read (${served[LONG].read} of 200000 bytes)`);
+ assert.ok(fetched.every(([, c]) => c === "include"), "read with the site's cookies");
+ const reads = fetched.length;
+ await popupAsk(listeners, { type: "media", tab: 9 });
+ assert.equal(fetched.length, reads, "each read once");
+ ok("#171: manifests without .m3u8/.mpd or their type: noted, read only when asked, listed");
+}
+{
+ // The popup reads nothing for a frame whose players have files of their own (no MediaSource).
+ served = { "https://cdn.test/p/playlist?id=8": { body: "#EXTM3U\n#EXT-X-ENDLIST\n" } };
+ const files = { 0: { href: "https://watch.test/v/4", players: [{ src: "https://files.test/movie.mp4", w: 0, h: 0, duration: 0, drm: false }] } };
+ const { api, listeners } = fakeApi({ firefox: false, frames: files, tabs: { 9: { id: 9, url: "https://watch.test/v/4" } } });
+ load(api, false);
+ listeners.tabUpdated(9, { url: "https://watch.test/v/4" });
+ await settle();
+ fetched.length = 0;
+ listeners.responseStarted(res("https://cdn.test/p/playlist?id=8", "xmlhttprequest", H("text/plain")));
+ await settle();
+ assert.deepEqual((await popupAsk(listeners, { type: "media", tab: 9 })).media, []);
+ assert.equal(fetched.length, 0, "no player fed by a MediaSource: nothing read");
+ ok("#171: nothing read where no player plays from a blob:");
+}
+{
+ // The button over a player playing from a blob: and the right-click menu: no stream known, the
+ // frame's possible manifests are read and the one that is goes; a frame of its own first.
+ const PL = "https://emb.test/e/playlist?id=9";
+ served = {
+ [PL]: { body: "#EXTM3U\n#EXT-X-STREAM-INF:RESOLUTION=640x360\nplaylist?id=9&v=360\n" },
+ "https://emb.test/e/settings": { body: "volume=1" },
+ "https://blog.test/ads/list": { body: "#EXTM3U\n#EXTINF:5,\nad.ts\n" },
+ };
+ const { api, calls, listeners } = fakeApi({ firefox: false });
+ load(api, false);
+ // The page's own frame loaded another playlist (an ad's); the player's frame (2) its stream.
+ listeners.responseStarted({ tabId: 7, frameId: 0, url: "https://blog.test/ads/list", type: "xmlhttprequest", statusCode: 200, responseHeaders: H("text/plain") });
+ listeners.responseStarted({ tabId: 7, frameId: 2, url: "https://emb.test/e/settings", type: "xmlhttprequest", statusCode: 200, responseHeaders: H("text/plain") });
+ listeners.responseStarted({ tabId: 7, frameId: 2, url: PL, type: "xmlhttprequest", statusCode: 200, responseHeaders: H("application/octet-stream") });
+ await settle();
+ fetched.length = 0;
+ await listeners.menu(
+ { menuItemId: "mdm-link", srcUrl: "blob:https://emb.test/1", frameId: 2, frameUrl: "https://emb.test/player", pageUrl: "https://blog.test/post" },
+ { id: 7, incognito: false },
+ );
+ await settle();
+ const m = natives(calls).find((x) => x.video);
+ assert.deepEqual([m.url, m.src], ["https://emb.test/player", PL], "the menu: the frame's sniffed stream");
+ assert.ok(!fetched.some(([u]) => u === "https://blog.test/ads/list"), "the frame's own found: the page's frame isn't read");
+ assert.ok(calls.some((c) => c[0] === "cookies" && c[1].url === PL), "the stream's cookies");
+ // The button in the page's frame (0): none of its own known yet; its frame's read, it goes.
+ const sender = { id: "ours", url: "https://blog.test/post", frameId: 0, tab: { id: 7, url: "https://blog.test/post" } };
+ await new Promise((r) => listeners.message({ type: "video", src: "" }, sender, r));
+ assert.equal(natives(calls).filter((x) => x.video).pop().src, "https://blog.test/ads/list", "the button: its own frame's");
+ ok("#171: the button and the menu read the frame's possible manifests when no stream is known");
+}
+
// The button's logo is the extension's own icon, kept in video.js as data.
{
const video = readFileSync(new URL("../../extension/video.js", import.meta.url), "utf8");