misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
fix(extension): the video button sends the video's own page, not the page playing it (#313)
mayankmohan19922991a4b186d4
diff --git a/extension/background.js b/extension/background.jsindex 69788513..043c3e32 100644--- a/extension/background.js+++ b/extension/background.js@@ -1758,15 +1758,22 @@ 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 : await streamFor(sender);+ // The video's own page when the content script names one of its site's (extension/video.js:+ // a watch page in a playlist is the list in the address bar, but the video is one video);+ // the tab's otherwise.+ const own =+ typeof m.url === "string" && /^https?:/i.test(m.url) && siteOf(m.url) === siteOf(page)+ ? m.url+ : page;const reply = await native({video: true,- url: page,+ url: own,...(src ? { src } : {}),title: typeof m.title === "string" ? m.title.slice(0, 300) : "",- referrer: tab.url && tab.url !== page ? tab.url : "",+ referrer: tab.url && tab.url !== own ? tab.url : "",// The cookies of what yt-dlp is given (the app files them under its host): the stream's// own server may not be the page's, and the page's cookies are not for it.- ...(await videoCookies(src || page, { incognito: tab.incognito, storeId: tab.cookieStoreId })),+ ...(await videoCookies(src || own, { incognito: tab.incognito, storeId: tab.cookieStoreId })),...(tab.incognito ? { private: true } : {}),});return { ok: Boolean(reply.ok), why: reply.why };diff --git a/extension/video.js b/extension/video.jsindex 1a1b8e77..70c59031 100644--- a/extension/video.js+++ b/extension/video.js@@ -52,6 +52,76 @@}};const host = location.hostname;+ // The address the app looks the video up by — the video's, not the page's. Most pages that play+ // a video are not the video's page: YouTube's home, a search, a channel or a playlist carries a+ // list in its address ("recommended", the results, the channel's videos), and yt-dlp reads such+ // an address as the list, so the app offered the whole feed instead of the video the button was+ // on. A watch page opened from a mix or a playlist has the same problem one level down+ // (…&list=…&index=…): its own page is watch?v=<id>, and nothing else.+ //+ // Null when the page plays a video but doesn't name it: YouTube's channel masthead player has no+ // video-id attribute, no link to the video inside the player and a blob: source, so there is+ // nothing to read (its id lives in the page's own JavaScript, out of reach of a content script,+ // and YouTube's Trusted Types rules out a script of ours reading it). The button stays away+ // there rather than send the page, which is a whole channel to yt-dlp.+ function videoPage(v) {+ const watch = (id) =>+ /^[\w-]+$/.test(id || "") ? `https://www.youtube.com/watch?v=${id}` : null;+ try {+ const url = new URL(location.href);+ const name = url.hostname.replace(/^(www|m|music)\./, "");+ if (name === "youtu.be") {+ const id = url.pathname.split("/")[1];+ if (watch(id)) return `https://youtu.be/${id}`;+ }+ if (name === "youtube.com" || name === "youtube-nocookie.com") {+ // An embed's own page is the video's (…/embed/<id>).+ if (url.pathname.startsWith("/embed/")) {+ const id = watch(url.pathname.split("/")[2]);+ if (id) return id;+ }+ // The page is this video's own: a watch page, with or without a list on it.+ const own = watch(url.searchParams.get("v"));+ if (own && url.pathname.startsWith("/watch")) return own;+ const shown = watch(document.querySelector("ytd-watch-flexy")?.getAttribute("video-id"));+ if (shown && url.pathname.startsWith("/watch")) return shown;+ const player = watch(document.querySelector("#movie_player")?.getAttribute("video-id"));+ if (player) return player;+ // A player inside the card it belongs to (a feed, a search, a playlist): the card links to+ // the video. Only a container that names exactly one video counts — walking on into the+ // page's column would find some other card's link and send the wrong video, which is worse+ // than sending none.+ for (let node = v, i = 0; node && i < 12; i += 1, node = node.parentElement) {+ const ids = new Set();+ for (const a of node.querySelectorAll?.('a[href*="/watch?"], a[href*="youtu.be/"]') || []) {+ const link = new URL(a.href, location.href);+ const id = link.hostname.endsWith("youtu.be")+ ? link.pathname.split("/")[1]+ : link.searchParams.get("v");+ if (watch(id)) ids.add(id);+ }+ if (ids.size === 1) return watch([...ids][0]);+ if (ids.size > 1) break;+ }+ // A page that plays a video and names none: not the video's page, so not the app's.+ return null;+ }+ } catch {+ // Not an address this page can reason about: its own follows.+ }+ return location.href;+ }++ // `videoPage` once per video element and address: it walks the DOM, and the pointer asks on+ // every move. A page that navigates in place (YouTube) gives a different answer.+ const namedAt = new WeakMap();+ function videoPageOf(v) {+ const seen = namedAt.get(v);+ if (seen && seen.at === location.href) return seen.page;+ const page = videoPage(v);+ namedAt.set(v, { at: location.href, page });+ return page;+ }const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;// "Hide on this video": the video's address (players reuse one element for the next video),@@ -218,6 +288,9 @@ button:focus-visible { outline: 2px solid #2a78d6; outline-offset: -2px; }if (audio ? !v.controls || r.width < MIN_W || r.height < MIN_AUDIO_H : r.width < MIN_W || r.height < MIN_H) {return false;}+ // A video the page doesn't name (a player of its own with nothing around it to link to it):+ // there is no address to hand the app, and the page's own would be a list.+ if (videoPageOf(v) === null) return false;// A short muted loop without controls: a moving picture, not something to save.if (v.muted && v.loop && !v.controls && !(v.duration > CLIP_S)) return false;const s = getComputedStyle(v);@@ -383,7 +456,11 @@ button:focus-visible { outline: 2px solid #2a78d6; outline-offset: -2px; }if (video.mediaKeys) return flash("err", t("video_drm"));const src = /^https?:/i.test(video.currentSrc || "") ? video.currentSrc : "";const title = (document.querySelector('meta[property="og:title"]')?.content || document.title || "").trim();- const r = await send({ type: "video", src, title });+ const page = videoPageOf(video);+ // The button stays away from a video the page doesn't name (`eligible`), so this is the+ // guard: nothing is sent rather than the page, which is a list to yt-dlp.+ if (!page) return;+ const r = await send({ type: "video", src, title, url: page });if (r.gone) return;flash(r.ok ? "ok" : "err", t(r.ok ? "video_sent" : r.why === "options" ? "video_off" : "video_failed"));} finally {diff --git a/tools/extension/test.mjs b/tools/extension/test.mjsindex 9ac8fbd2..028a1abc 100644--- a/tools/extension/test.mjs+++ b/tools/extension/test.mjs@@ -566,6 +566,21 @@ const ok = (what) => {assert.deepEqual(await ask({ type: "panel" }, "https://tube.test/embed/3"), { on: false }, "off at once");assert.deepEqual(await ask({ type: "panel" }, "https://tube.test:8443/embed/4"), { on: false }, "whatever the port");assert.deepEqual(await ask({ type: "video" }, "javascript:alert(1)"), { ok: false });+ // The video's own address, when the content script names one of its site's: a watch page opened+ // from a mix or a playlist is the list in the address bar, but the video the button is on is one+ // video. The tab stays the referrer, and its cookies are read for that address.+ assert.equal((await ask({ type: "video", url: "https://tube.test/watch?v=abc123" })).ok, true);+ const own = natives(calls).filter((m) => m.video).at(-1);+ assert.equal(own.url, "https://tube.test/watch?v=abc123", "the video's own page");+ assert.equal(own.referrer, "https://blog.test/post");+ assert.equal(own.cookies, "sid=1");+ // Another site's address is not the page's: ignored, as any message content was before.+ assert.equal((await ask({ type: "video", url: "https://evil.test/watch?v=abc123" })).ok, true);+ assert.equal(+ natives(calls).filter((m) => m.video).at(-1).url,+ "https://tube.test/embed/1",+ "another site's address is ignored",+ );assert.equal(await ask({ type: "panel" }, "https://x.test/", { id: "someone-else", url: "https://x.test/", tab: {} }), undefined);}// A player playing a stream (HLS) from a blob: the button sends the manifest its frame loaded@@ -956,6 +971,63 @@ const MPD = (protect) => `<?xml version="1.0"?>ok("video button logo");}+// The address the button hands the app (video.js's videoPage): the video's own page, not the page+// that plays it. YouTube's home, a search, a channel or a playlist is a list to yt-dlp, and a watch+// page opened from a mix carries the list in its address: the button sent either, and the app+// offered the whole feed (~50 videos) instead of the one playing. #311.+{+ const source = readFileSync(new URL("../../extension/video.js", import.meta.url), "utf8");+ const start = source.indexOf("function videoPage(v) {");+ assert.ok(start > 0, "video.js has videoPage");+ // The function's own braces, so a test never runs a half of it.+ let depth = 0;+ let end = start;+ for (let i = source.indexOf("{", start); i < source.length; i += 1) {+ if (source[i] === "{") depth += 1;+ if (source[i] === "}") {+ depth -= 1;+ if (depth === 0) {+ end = i + 1;+ break;+ }+ }+ }+ // A page: its address, an optional ytd-watch-flexy video-id, and the cards a player can sit in+ // (each level on the way up from the video element names the video links it contains).+ const at = (href, { flexy = null, cards = [] } = {}) => {+ const element = (links) => ({+ parentElement: null,+ querySelectorAll: () => (links || []).map((href) => ({ href })),+ });+ const chain = cards.map(element);+ for (let i = 0; i < chain.length; i += 1) chain[i].parentElement = chain[i + 1] || null;+ const document = { querySelector: (sel) => (sel === "ytd-watch-flexy" && flexy ? { getAttribute: () => flexy } : null) };+ const fn = new Function("location", "document", `${source.slice(start, end)}; return videoPage;`)({ href }, document);+ return fn(chain[0] || element([]));+ };+ // A watch page from a mix or a playlist: the video's own address, without the list.+ assert.equal(at("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=RDdQw4w9WgXcQ&start_radio=1"), "https://www.youtube.com/watch?v=dQw4w9WgXcQ");+ assert.equal(at("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PL1234567890abcdef&index=12"), "https://www.youtube.com/watch?v=dQw4w9WgXcQ");+ // A player that isn't the page's own: the card it sits in links to the video it is playing.+ assert.equal(at("https://www.youtube.com/", { cards: [[], ["https://www.youtube.com/watch?v=abc123XYZ_-&t=5s"]] }), "https://www.youtube.com/watch?v=abc123XYZ_-");+ // The card links to it twice (thumbnail and title): one video, still.+ assert.equal(at("https://www.youtube.com/results?search_query=rick+astley", { cards: [[], ["https://www.youtube.com/watch?v=abc123XYZ_-", "https://www.youtube.com/watch?v=abc123XYZ_-&pp=1"]] }), "https://www.youtube.com/watch?v=abc123XYZ_-");+ assert.equal(at("https://www.youtube.com/@someone", { cards: [[], [], ["https://www.youtube.com/watch?v=abc123XYZ_-"]] }), "https://www.youtube.com/watch?v=abc123XYZ_-");+ // A page that plays a video and names none: no address at all, so no button and nothing sent+ // (the page's own address — a channel's videos — would be a list of ~50 to yt-dlp).+ assert.equal(at("https://www.youtube.com/@someone/videos"), null);+ assert.equal(at("https://www.youtube.com/@someone/videos", { flexy: "feat12345" }), null);+ assert.equal(at("https://www.youtube.com/"), null);+ // A container naming two videos is the page's column, not a card: nothing is sent, rather than+ // some other card's video.+ assert.equal(at("https://www.youtube.com/@someone/videos", { cards: [[], ["https://www.youtube.com/watch?v=aaa", "https://www.youtube.com/watch?v=bbb"]] }), null);+ // Short links, embeds, and a site that isn't YouTube's (untouched).+ assert.equal(at("https://youtu.be/dQw4w9WgXcQ?t=10&list=PL999"), "https://youtu.be/dQw4w9WgXcQ");+ assert.equal(at("https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ?start=5"), "https://www.youtube.com/watch?v=dQw4w9WgXcQ");+ assert.equal(at("https://vimeo.com/123456789?list=abc"), "https://vimeo.com/123456789?list=abc");+ ok("#311: the button sends the video's own page, not the page playing it");+}+// No other download manager's name in what ships (the clean-room rule, CLAUDE.md).{for (const file of readdirSync(new URL("../../extension/", import.meta.url))) {