diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2ba409b..984f4ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,16 @@ note on what to update.
## [Unreleased]
+### Added
+
+- **Streaming sites without the immersion profile.** "Count streaming sites" in the dashboard settings turns on
+ Netflix, Crunchyroll, Prime Video and Disney+ (the last two experimental), each one apart, asking for access
+ to that site's pages only. Inputly reads which audio track the player plays and counts the episode or film
+ only when it is in your language; ads are left out where the player shows them. The popup and the day's list
+ name the episode. In the immersion profile every title of a site turned on counts. See
+ [docs/streaming.md](docs/streaming.md).
+- The popup shows the title of the video it is counting, on YouTube too.
+
## [0.1.1] - 2026-11-23
Fixes that make the count more honest: ads, a failed player and crashes no longer add or lose time.
diff --git a/PRIVACY.md b/PRIVACY.md
index 936b2ff..f48d9c0 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -35,7 +35,7 @@ It stores on your computer (in `chrome.storage.local`):
Mosaik" on, it goes to your Mosaik: [see below](#what-happens-when-you-turn-on-send-to-mosaik));
- the **corrections** you make to a day (a number of seconds, and when you made it);
- your **daily goal** and your settings (the language you learn, light or dark, the range of the chart, the
- immersion profile);
+ immersion profile, the streaming sites you turned on);
- the **ids of the videos you marked** as in the language you learn or not, for each language, so the
decision is remembered;
- only if you turn on "Send to Mosaik": its settings (with the device token, if your Mosaik is on a
@@ -69,6 +69,24 @@ its language. When you turn it on in the dashboard settings, your browser asks y
Turning it off stops the script. The permissions stay granted until you remove them in `chrome://extensions`.
+## Streaming sites
+
+Counting Netflix, Crunchyroll, Prime Video and Disney+ is **optional and off by default**, for each site apart.
+When you turn a site on in the dashboard settings ("Count streaming sites"), your browser asks you for
+`scripting` and access to that site's pages only (for Crunchyroll also `static.crunchyroll.com`, where its
+player is; for Prime Video also the Amazon stores where it plays: amazon.com, .co.uk, .de and .co.jp). Then,
+in the pages of that site, Inputly reads **in your browser**:
+
+- whether the video is playing, and whether the player shows an ad (ads are not counted);
+- from the player, the id and the title of the episode or film, the language of the audio track it plays and
+ of the subtitles shown, only to decide whether it is in the language you learn.
+
+It keeps the address, the title and the seconds of each episode or film in your language in the list of the
+day above, and your decisions about which ones are in your language. It does not read your account, your
+profile, your watch history, your lists or your recommendations, and makes no request to those sites or to
+anyone else. Turning a site off stops its scripts; the access stays granted until you remove it in
+`chrome://extensions`.
+
## Reading counted by hand
The popup has a button to count reading with no video (a comic, for example). While it runs, Inputly counts the
@@ -118,6 +136,7 @@ dashboard (the squares button). Then:
## Your choices
- **Turn off the immersion profile** in the dashboard settings: no more pages are looked at.
+- **Turn off a streaming site** in the dashboard settings: its pages are no longer looked at.
- **Turn off "Send to Mosaik"** in the dashboard: nothing more is sent, and what was waiting is deleted.
- **Uninstall** the extension to delete everything it kept on that computer.
diff --git a/README.md b/README.md
index b60f356..2a22ac3 100644
--- a/README.md
+++ b/README.md
@@ -27,6 +27,10 @@ days, weeks and months, so you can see how much input you really get.
- **A day you can explain and correct.** Click a day in the dashboard to see which videos made it up
(for the last 60 days), take out the ones that were not in your language, or say how many minutes you really
watched.
+- **Netflix and Crunchyroll, if you want.** Turn a site on in the settings of the dashboard ("Count
+ streaming sites") and Inputly counts what plays there in your language, from the audio track the player
+ says it plays; ads are left out. Prime Video and Disney+ are there too, as experimental. Each site asks
+ for access to its own pages only. See [docs/streaming.md](docs/streaming.md).
- **An immersion profile.** In a Chrome profile you use only for the language you learn, turn it on in the settings of the
dashboard and every video that plays with sound counts, on any site, with no guessing. So does any tab
that plays sound for 30 seconds or more, like a podcast; a word a dictionary says does not.
diff --git a/docs/plan.md b/docs/plan.md
index c45b3e5..cb3598b 100644
--- a/docs/plan.md
+++ b/docs/plan.md
@@ -84,9 +84,12 @@ data stays German.
Worth doing before or soon after
the first release; each is its own task.
-- [ ] **2.7 Streaming sites without the immersion profile.** Count Netflix, Prime Video, Crunchyroll and
+- [x] **2.7 Streaming sites without the immersion profile.** Count Netflix, Prime Video, Crunchyroll and
Disney+ in the target language, from the audio or subtitle track the player says is playing.
Investigate each player first; the store review needs a reason for each new host permission.
+ Done in [streaming.md](streaming.md): all four ship, off by default, each asked for from the settings
+ as an optional host inside ``; Prime Video and Disney+ marked experimental. What is left is a
+ check by hand with real accounts (see the note of 2.7).
- [x] **2.8 Leave out ads** on YouTube (and on the sites of 2.7): time an ad plays is not input.
- [x] **2.9 Recover after a crash.** Time counted while the browser or the service worker dies is not
lost.
@@ -311,3 +314,21 @@ Sessions add here what the next one needs to know: decisions taken, dead ends, f
instead) and the sleep path of the sound, both covered by unit tests. Follow-up: after an extension update
or reload, a tab opened before it keeps a content script that cannot reach the extension any more and
counts nothing until the page is reloaded; re-injecting the scripts on update needs `scripting` for YouTube.
+- 2026-11-23, task 2.7: the streaming sites are registered at runtime (`scheduleStreaming` in `background.js`)
+ from a per-site switch in the settings, which asks for `scripting` and that site's origins only
+ (`sites.js`). Both are inside the optional `scripting` and `` the manifest already had, so the
+ manifest only gained a `web_accessible_resources` entry and 0.2.0 shows no new warning at install; static
+ content scripts would have warned every user and disabled the extension until accepted. A page script
+ (`streaming-bridge.js`, world `MAIN`) copies plain values from each player and `streaming.js` reads them;
+ the audio track decides, subtitles never do, and a site whose player cannot be read counts nothing (fails
+ closed). Stored: a new key `streamingSites` (`{ netflix: true }`) and web items `web:` of
+ `https://www.netflix.com/watch/` and the like, so no stored shape changed and `STORAGE_VERSION` stays;
+ `override` messages and "take out of the day" now accept web item ids too. What was seen: Crunchyroll's
+ store (`content.media.byId[watch.id].audioLocale`) on the real site, logged out (every episode was premium
+ only, so nothing played; no free tier with ads seen); counting was then checked in Chrome 157 with that
+ store shape served at a Crunchyroll address, in the page and in a `static.crunchyroll.com` frame, because
+ the real site shows a bot check to a browser driven through CDP. Netflix comes from published probe output
+ (LingoFlix); Prime Video and Disney+ from one open-source tool each, hence "experimental". Not checked: any
+ real playback, ads on any of the four, Firefox. Follow-ups: the maintainer's check by hand
+ ([streaming.md](streaming.md#checking-by-hand)); a Crunchyroll ad rule if a free tier with ads shows up; more
+ Amazon stores for Prime Video if someone asks.
diff --git a/docs/store-listing.md b/docs/store-listing.md
index 9a154e6..5ecbc05 100644
--- a/docs/store-listing.md
+++ b/docs/store-listing.md
@@ -47,8 +47,9 @@ WHAT MAKES INPUTLY DIFFERENT
HOW IT COUNTS
• It counts the real seconds a video in your language plays. Pausing, rewinding and looping are handled,
and at 2x a minute is still a minute. Two tabs playing at once count once.
-• By itself it counts YouTube. Other sites (streaming sites, Twitch, podcasts) count only with the
- immersion profile on.
+• By itself it counts YouTube. Netflix and Crunchyroll count too once you turn them on in the settings (Prime
+ Video and Disney+ as experimental): Inputly reads which audio track the player plays and counts it only in
+ your language. Other sites (Twitch, podcasts) count with the immersion profile on.
• Pick your language when you install it, and change it any time in the settings. The popup says it:
"Counting Japanese", "Not Japanese, not counted".
@@ -62,8 +63,9 @@ WHAT YOU SEE
OPEN SOURCE
The extension is open source (MIT): https://github.com/joaquinmuzzi/inputly
-Inputly is an independent project. It is not affiliated with, endorsed by or sponsored by YouTube or
-Google. YouTube is a trademark of Google LLC.
+Inputly is an independent project. It is not affiliated with, endorsed by or sponsored by YouTube, Google,
+Netflix, Crunchyroll, Amazon or Disney. YouTube is a trademark of Google LLC; the other names are trademarks
+of their owners.
```
**Images** (1280 × 800 JPEG, from the real extension pages with the invented history of someone who learns
@@ -91,27 +93,36 @@ They are made with `node scripts/screenshots/capture.mjs` (see task 2.2 in the [
**Single purpose:**
-> Track how much time the user spends on input in the language they learn (videos on YouTube, any video or
-> sound in a Chrome profile the user sets for that language, and reading they count by hand), and show their
-> progress toward a daily goal.
+> Track how much time the user spends on input in the language they learn (videos on YouTube, the streaming
+> sites the user turns on, any video or sound in a Chrome profile the user sets for that language, and reading
+> they count by hand), and show their progress toward a daily goal.
**Permission justifications** (one field per permission in the form; paste the text of its row):
-| Permission | Why |
-| ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `storage` | Keeps, in the browser of the user, the seconds counted per day, the videos and readings of the last 60 days with their title, address and seconds, the corrections the user made to a day, the daily goal, the settings (the language the user learns among them) and the decisions of the user about which videos are in that language. Nothing is synced or sent by this permission. |
-| `alarms` | A service worker cannot keep a timer, so a one-minute alarm does the periodic work: it adds up the reading the user started by hand, the sound of tabs while the immersion profile is on, and, only while the user has "Send to Mosaik" on, sends to their Mosaik. No alarm runs while none of these is in use. |
-| `idle` | Stops the reading counted by hand when nobody has used the computer for 15 minutes, so that time away is not counted. It says only whether the computer is in use. |
-| `activeTab` | The popup works on the tab the user has open when they click the toolbar button: "Count reading" reads the address and the title of that one tab to name what is being read, and the popup asks that tab whether its video is in the language the user learns. |
-| Optional permission `scripting` | Not granted at install. Asked for only when the user turns on the immersion profile in the settings: it registers the small script that finds the videos of other sites and whether they play. Turning the profile off unregisters it. |
-| Optional host permissions `http://127.0.0.1/*` and `http://localhost/*` | Not granted at install. Asked for only when the user turns on "Send to Mosaik" in the dashboard with the address of Mosaik on their own computer: it sends the counted time to that app of the user. Nothing goes to another computer. |
-| Optional host permission `` | Not granted at install. Asked for whole only when the user turns on the immersion profile, meant for a Chrome profile they use only for the language they learn: every video that plays with sound counts, on any site, and so does a tab that plays sound. The script only looks for videos and whether they play; only the address, the title and the seconds of a page where something played are kept, in the browser, never sent unless "Send to Mosaik" is on. It also covers "Send to Mosaik" with the address of the user's own Mosaik server: then the extension asks for that one host only (`https:///*`), never for the whole pattern, because the address is typed by the user and cannot be known in advance. The server takes the data only with a device token the user made in it. |
-| Content scripts on `https://www.youtube.com/*` | Read, in the page of the video, whether it is playing, which audio track plays and the language of its captions, title and description, to count only the time of videos in the language the user learns. One small script runs in the page itself because the player data is not visible to the isolated content script; it only reads it and never writes to the page. Only the id and the title of the video counted are kept. |
-
-`web_accessible_resources` lists two scripts (`src/tracker.js`, `src/watcher.js`) for ``. It is not
-a permission: it lets the immersion script, which runs only where the user granted ``, load the
+| Permission | Why |
+| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `storage` | Keeps, in the browser of the user, the seconds counted per day, the videos and readings of the last 60 days with their title, address and seconds, the corrections the user made to a day, the daily goal, the settings (the language the user learns among them) and the decisions of the user about which videos are in that language. Nothing is synced or sent by this permission. |
+| `alarms` | A service worker cannot keep a timer, so a one-minute alarm does the periodic work: it adds up the reading the user started by hand, the sound of tabs while the immersion profile is on, and, only while the user has "Send to Mosaik" on, sends to their Mosaik. No alarm runs while none of these is in use. |
+| `idle` | Stops the reading counted by hand when nobody has used the computer for 15 minutes, so that time away is not counted. It says only whether the computer is in use. |
+| `activeTab` | The popup works on the tab the user has open when they click the toolbar button: "Count reading" reads the address and the title of that one tab to name what is being read, and the popup asks that tab whether its video is in the language the user learns. |
+| Optional permission `scripting` | Not granted at install. Asked for only when the user turns on the immersion profile, or a streaming site (Netflix, Crunchyroll, Prime Video, Disney+), in the settings: it registers the small scripts that find the videos of those sites and whether they play. Turning the profile or the site off unregisters them. |
+| Optional host permissions `http://127.0.0.1/*` and `http://localhost/*` | Not granted at install. Asked for only when the user turns on "Send to Mosaik" in the dashboard with the address of Mosaik on their own computer: it sends the counted time to that app of the user. Nothing goes to another computer. |
+| Optional host permission `` | Not granted at install. Asked for whole only when the user turns on the immersion profile, meant for a Chrome profile they use only for the language they learn: every video that plays with sound counts, on any site, and so does a tab that plays sound. The script only looks for videos and whether they play; only the address, the title and the seconds of a page where something played are kept, in the browser, never sent unless "Send to Mosaik" is on. It also covers "Send to Mosaik" with the address of the user's own Mosaik server: then the extension asks for that one host only (`https:///*`), never for the whole pattern, because the address is typed by the user and cannot be known in advance. The server takes the data only with a device token the user made in it. It also covers the streaming sites: when the user turns one on in the settings, the extension asks for that site's pages only (`https://www.netflix.com/*`; `https://www.crunchyroll.com/*` and `https://static.crunchyroll.com/*`, where its player is; `https://www.primevideo.com/*` and the Amazon stores where Prime Video plays, `https://www.amazon.com/*`, `.co.uk`, `.de`, `.co.jp`; `https://www.disneyplus.com/*`), never for the whole pattern. There a script reads which episode plays, which audio language the player says it plays and whether an ad plays, to count the episode only when it is in the language the user learns. |
+| Content scripts on `https://www.youtube.com/*` | Read, in the page of the video, whether it is playing, which audio track plays and the language of its captions, title and description, to count only the time of videos in the language the user learns. One small script runs in the page itself because the player data is not visible to the isolated content script; it only reads it and never writes to the page. Only the id and the title of the video counted are kept. |
+
+`web_accessible_resources` lists three scripts (`src/tracker.js`, `src/watcher.js`, `src/delivery.js`) for
+``, and the counting modules for the streaming sites' pages. It is not a permission: it lets the
+immersion script and the streaming sites' script, which run only where the user granted access, load the
extension's own counting code. The reviewer may ask; the answer is this.
+**Why the streaming sites are optional, one by one** (task 2.7, see [streaming.md](streaming.md)): they could
+have been content scripts in the manifest, like YouTube, but a new host in `host_permissions` or in a content
+script's `matches` shows a new warning to every user at the update ("Read and change your data on
+www.netflix.com…") and disables the extension until they accept it. Asked for at runtime, inside the optional
+`` the manifest already declares, nothing changes for whoever does not use those sites, the update
+needs no new approval, and each person grants only the sites they turn on. Each request names one site's own
+pages, which is also the easiest reason for a reviewer to accept.
+
**Remote code:** No, I am not using remote code. All the code is in the package; the extension loads
nothing from the internet and evaluates no strings as code.
diff --git a/docs/streaming.md b/docs/streaming.md
new file mode 100644
index 0000000..ec5c4ee
--- /dev/null
+++ b/docs/streaming.md
@@ -0,0 +1,172 @@
+# Streaming sites
+
+How Inputly counts Netflix, Crunchyroll, Prime Video and Disney+ without the immersion profile (task 2.7 of the
+[plan](plan.md)): what each player says, where it was read, what was checked and what is only inferred. Read
+this before changing `extension/src/streaming.js` (the readers), `extension/src/streaming-bridge.js` (the page
+script), `extension/src/streaming-content.js` (the glue) or `extension/src/sites.js` (the list of sites).
+
+## How it works
+
+- **Off until the person turns a site on.** The dashboard settings have "Count streaming sites", one switch per
+ site. Turning one on asks the browser, from that click, for `scripting` and that site's own pages
+ (`sitePermissions` in `sites.js`). Both are inside what the manifest already declares as optional
+ (`scripting` and ``, used by the immersion profile), so an update shows no new warning at install,
+ and nothing about these sites is granted until the person asks for it.
+- **Two scripts per site, registered by the background script** while the site is on and its access granted
+ (`scheduleStreaming` in `background.js`): `streaming-bridge.js` in the page itself (world `MAIN`), because
+ the players' state is not visible from a content script's isolated world, and `streaming-content.js`, which
+ counts. Both start at `document_start`.
+- **The bridge copies a few plain values** when asked (`inputly:streaming-request`, once a second): ids, the
+ title, the playing audio and subtitle tracks, whether an ad plays. It never calls a player method that
+ changes anything, never writes to the page and makes no request. Nothing is intercepted: no `fetch` or
+ `JSON.parse` hook, no network manifest.
+- **The readers** (`readNetflix`, `readCrunchyroll`, `readPrimeVideo`, `readDisneyPlus` in `streaming.js`) turn
+ that copy into `{ key, title, audioLanguage, subtitleLanguages, ad }`. They are pure and tested
+ (`tests/streaming.test.js`).
+- **The audio track decides**, as on YouTube: `audioLanguage` matched against the target language
+ (`streamingVerdict`). Subtitles never decide (they are often translations); they are read for the record
+ only. While the player has not said which audio plays, the time waits, as on YouTube, and is dropped if it
+ never says. During an ad the verdict stays the title's (the player's tracks may be the ad's) and nothing
+ counts (`Watcher.setAd`).
+- **The time goes to the episode or film**, as a web item (`web:` of `key`, an address such as
+ `https://www.netflix.com/watch/82028220`), with its title, in the day's list and in the popup. The popup's
+ "Not Japanese?" button works as on YouTube, remembered per item.
+- **In the immersion profile** every title of a site turned on counts, as every YouTube video does. The
+ immersion profile's own script (`generic.js`) leaves a page alone when `streaming-content.js` runs there
+ (`globalThis.inputlyStreaming`, set before anything waits), so a title is not counted under two names.
+- **Frames:** Crunchyroll's player (Vilos) is an iframe on `static.crunchyroll.com`. There the script only tells
+ the page, by `postMessage`, whether its video plays; the page checks the message's origin against the site's
+ `frames` and counts.
+
+## Per site
+
+| Site | Shipped | Audio language from | Checked |
+| ----------- | -------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------- |
+| Netflix | Yes | The player API, `getAudioTrack().bcp47` | Shape from two published probes; no Netflix account here |
+| Crunchyroll | Yes | The web app's store, `content.media.byId[watch.id].audioLocale` | The store read on the real site, logged out; counting through a fixture |
+| Prime Video | Yes, marked "experimental" | The player's React context, `audioStream` active stream | Shape from one open-source tool; no account here |
+| Disney+ | Yes, marked "experimental" | `mediaPlayer.audio.selectedTrack.language` on the player element | Shape from one open-source extension; no account here |
+
+Every site fails closed: when the bridge reads nothing (the player changed, a property moved), `audioLanguage` is
+`null` and nothing counts; the popup says "Detecting the language…". A wrong reader can make Inputly count
+nothing on a site, but not count the wrong language.
+
+### Netflix
+
+- **Player:** `netflix.appContext.state.playerApp.getAPI().videoPlayer`; `getAllPlayerSessionIds()` (the one
+ that starts with `watch`), then `getVideoPlayerBySessionId(id)`.
+- **Audio:** `getAudioTrack()` → `{ trackId, bcp47, displayName, isNative, … }`, e.g. `{ bcp47: "en",
+displayName: "English [Original]", isNative: true }`. A dub has its own `bcp47`.
+- **Subtitles:** `getTimedTextTrack()` → `{ bcp47, isNoneTrack, isForcedNarrative, rawTrackType, … }`.
+- **Id:** `getMovieId()`, the episode or film (`/watch/` in the address; the query changes, the path not).
+- **Title:** `playerApp.getState().videoPlayer.videoMetadata[movieId]._metadataObject.video` → the show's
+ `title`, `type` (`show` or `movie`), and its `seasons[].episodes[]` (`id`, `seq`, `title`). Fallback: the
+ player's title line `[data-uia="video-title"]` (`h4` show, `span` episode number, `span` episode title).
+ `document.title` is just "Netflix".
+- **Ads** (plans with ads): the lead-in before a title is a separate segment; LingoFlix saw `getSegmentTime()`
+ stay at 0 while `getCurrentTime()` ran through a 7007 ms lead-in, so `segmentTime === 0 && currentTime > 0` is
+ read as an ad. During any ad the player shows its "Ad" label; jp343 looks for `[data-uia="ads-info-container"]`
+ and `[data-uia="ads-info-text"]`, read here as `[data-uia*="ads-info"]`. Inferred: neither was seen here.
+- **Navigation:** a single page app; the bridge is asked every second, a new `movieId` is a new item, and no
+ player session (back to browsing) ends the item.
+- **Sources:** [LingoFlix's Netflix internals](https://github.com/jaycho1214/lingoflix/blob/main/docs/netflix-internals.md)
+ (verified probe output, Chrome 154, 2026-10-10, with an ad plan; the test data comes from it);
+ [Read Frog's Netflix player bridge](https://github.com/mengxi-ream/read-frog/blob/main/src/entrypoints/netflix-interceptor.content/player.ts)
+ (the same API path and `getAudioTrack()?.bcp47`); jp343's Netflix content script for the ad selectors.
+
+### Crunchyroll
+
+- **Checked on the real site** on 2026-11-23, logged out, in Argentina, in a browser pane: the watch page of One
+ Piece episode 1 (`/watch/GR3VWXP96`, Japanese) and its Latin American dub (`/watch/GE00010122ES419`). The
+ stream itself was blocked ("Emisión restringida"): every episode seen was `availabilityStatus: "premium_only"`,
+ so nothing played.
+- **Store:** the web app is React with a Redux store, reached through the props of its root (`store.getState()`);
+ `watch.id` is the episode of the page, and `content.media.byId[id]` holds `audioLocale` (`"ja-JP"`,
+ `"es-419"`), `title`, `parentTitle`, `episode`, `type`, `subtitleLanguages`, `audioLanguages` and `dubVersions`
+ (`{ guid, audioLocale, original }` for each dub). A dub is a separate episode with its own id, so the episode
+ of the page is the audio that plays. `watch.premiumDubSelectedVersion` (null here) is read as a dub picked
+ inside the player; inferred from its name.
+- **Title:** `parentTitle`, `episode` and `title` ("One Piece E1 - …"); `document.title` and the page's JSON-LD
+ (`TVEpisode`) also name it.
+- **Player:** `__APP_CONFIG__.vilosConfig.vilosPlayerUrl` is `https://static.crunchyroll.com/vilos-v2/web/vilos/player.html`,
+ and jp343 runs in all frames of `*.crunchyroll.com` with code for the player's iframe, so the video is taken to
+ play in that frame (asked for as `https://static.crunchyroll.com/*`). Inferred: no stream played here. The
+ script also counts a `
+
+
diff --git a/extension/dashboard/dashboard.js b/extension/dashboard/dashboard.js
index 01bc046..967452f 100644
--- a/extension/dashboard/dashboard.js
+++ b/extension/dashboard/dashboard.js
@@ -4,6 +4,7 @@ import { IMMERSION_PERMISSIONS, immersionOf } from "../src/immersion.js";
import { itemUrl } from "../src/items.js";
import { formatClock, migrate, shownLog } from "../src/log.js";
import { dayItems, hasOthers, withOtherDevices } from "../src/mosaik-days.js";
+import { SITES_KEY, STREAMING_SITES, enabledSites, sitePermissions } from "../src/sites.js";
import { DEFAULT_RANGE, RANGES, dashboardData, timeline } from "../src/stats.js";
import { TARGET_HASH, TARGET_KEY, targetName, targetOf, targetOptions } from "../src/target.js";
import { setUpTheme } from "../src/theme.js";
@@ -263,6 +264,7 @@ function renderTargets() {
/** The immersion note names the language picked, even before it is saved. */
const renderImmersionLanguage = () => {
byId("immersionLanguage").textContent = targetName(targetSelect.value);
+ byId("streamingLanguage").textContent = targetName(targetSelect.value);
};
targetSelect.addEventListener("change", renderImmersionLanguage);
@@ -319,6 +321,45 @@ immersionBox.addEventListener("change", () => {
});
});
+// The streaming sites: each one asks for access to its own pages, from the click that turns it on
+const streamingError = byId("streamingError");
+const siteBoxes = new Map(
+ STREAMING_SITES.map((site) => {
+ const box = document.createElement("input");
+ box.type = "checkbox";
+ box.id = `site-${site.id}`;
+ const label = document.createElement("label");
+ label.className = "switch-row";
+ label.append(box, ` ${site.name}${site.experimental ? " (experimental)" : ""}`);
+ byId("streamingSites").append(label);
+ box.addEventListener("change", () => setSite(site, box));
+ return [site.id, box];
+ }),
+);
+
+/** Turns a site on (if the person grants its access) or off, and keeps what the boxes say. */
+async function setSite(site, box) {
+ streamingError.textContent = "";
+ const want = box.checked;
+ // Asked for first, from the click itself, as the browser wants
+ const granted = want ? await chrome.permissions.request(sitePermissions(site)).catch(() => false) : true;
+ if (!granted) {
+ box.checked = false;
+ streamingError.textContent = `Without access to ${site.name}, Inputly cannot see what its player plays.`;
+ return;
+ }
+ const saved = (await chrome.storage.local.get(SITES_KEY))[SITES_KEY];
+ await chrome.storage.local.set({ [SITES_KEY]: { ...saved, [site.id]: want } });
+ await chrome.runtime.sendMessage({ type: "streaming:refresh" }).catch(() => {});
+}
+
+const renderSites = (saved) => {
+ const on = enabledSites(saved);
+ for (const [id, box] of siteBoxes) {
+ box.checked = on.includes(id);
+ }
+};
+
byId("ranges").addEventListener("change", (event) => {
range = Number(event.target.value);
chrome.storage.local.set({ range });
@@ -335,6 +376,7 @@ const stored = await chrome.storage.local.get([
"range",
"videos",
"immersion",
+ SITES_KEY,
TARGET_KEY,
]);
log = stored.log;
@@ -342,6 +384,7 @@ mosaikDays = stored.mosaikDays;
mosaikOn = stored.mosaikSettings?.enabled === true;
videos = stored.videos;
immersionBox.checked = immersionOf(stored.immersion);
+renderSites(stored[SITES_KEY]);
goalMinutes = goalMinutesOf(stored.goalMinutes);
target = targetOf(stored[TARGET_KEY]);
renderTargets();
@@ -371,6 +414,9 @@ chrome.storage.onChanged.addListener((changes) => {
if (changes.immersion) {
immersionBox.checked = immersionOf(changes.immersion.newValue);
}
+ if (changes[SITES_KEY]) {
+ renderSites(changes[SITES_KEY].newValue);
+ }
if (changes.videos) {
videos = changes.videos.newValue;
}
diff --git a/extension/manifest.json b/extension/manifest.json
index 5aa35e7..a4fb88e 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -57,6 +57,30 @@
{
"resources": ["src/tracker.js", "src/watcher.js", "src/delivery.js"],
"matches": [""]
+ },
+ {
+ "resources": [
+ "src/sites.js",
+ "src/streaming.js",
+ "src/items.js",
+ "src/overrides.js",
+ "src/target.js",
+ "src/immersion.js",
+ "src/watcher.js",
+ "src/tracker.js",
+ "src/delivery.js"
+ ],
+ "matches": [
+ "https://www.netflix.com/*",
+ "https://www.crunchyroll.com/*",
+ "https://static.crunchyroll.com/*",
+ "https://www.primevideo.com/*",
+ "https://www.amazon.com/*",
+ "https://www.amazon.co.uk/*",
+ "https://www.amazon.de/*",
+ "https://www.amazon.co.jp/*",
+ "https://www.disneyplus.com/*"
+ ]
}
]
}
diff --git a/extension/popup/popup.css b/extension/popup/popup.css
index 6f31ed1..cb6dab0 100644
--- a/extension/popup/popup.css
+++ b/extension/popup/popup.css
@@ -58,6 +58,15 @@ header {
background: var(--strong);
}
+.live-title {
+ overflow: hidden;
+ margin: -8px 0 12px 16px;
+ color: var(--muted);
+ font-size: 12px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
.quiet {
margin-left: auto;
padding: 4px 0;
diff --git a/extension/popup/popup.html b/extension/popup/popup.html
index 758fa42..47b4a69 100644
--- a/extension/popup/popup.html
+++ b/extension/popup/popup.html
@@ -21,6 +21,7 @@
Inputly
No video here
+
diff --git a/extension/popup/popup.js b/extension/popup/popup.js
index 17f2c0d..13e2004 100644
--- a/extension/popup/popup.js
+++ b/extension/popup/popup.js
@@ -71,9 +71,12 @@ async function renderStatus() {
!reply && tab
? (await chrome.runtime.sendMessage({ type: "audio:status", tabId: tab.id }).catch(() => null))?.sound
: null;
- const { kind, text, action } = describeStatus(reply, sound, language);
+ const { kind, text, action, title } = describeStatus(reply, sound, language);
byId("status").dataset.kind = kind;
byId("statusText").textContent = text;
+ byId("statusTitle").hidden = !title;
+ byId("statusTitle").textContent = title ?? "";
+ byId("statusTitle").title = title ?? "";
const button = byId("override");
button.hidden = !action;
if (action) {
diff --git a/extension/src/background.js b/extension/src/background.js
index e5594dc..03e5741 100644
--- a/extension/src/background.js
+++ b/extension/src/background.js
@@ -25,8 +25,16 @@ import { addSeconds, dayKey, migrate, shownLog } from "./log.js";
import { IDLE_SECONDS, MANUAL_ALARM, flushManual, manualItem, readManual, startManual } from "./manual.js";
import { othersOn } from "./mosaik-days.js";
import { createMosaikRunner, queueRemoval, queueWatched } from "./mosaik-runner.js";
-import { isVideoId, overridesKey, withOverride } from "./overrides.js";
+import { overridesKey, withOverride } from "./overrides.js";
import { forgetTab, knowPage, pageTitle, splitByPage, trackPage } from "./pages.js";
+import {
+ SITES_KEY,
+ STREAMING_SITES,
+ enabledSites,
+ sitePermissions,
+ siteScriptIds,
+ siteScripts,
+} from "./sites.js";
import { TARGET_HASH, TARGET_KEY } from "./target.js";
import { addVideoSeconds, cleanVideo, removeVideo } from "./videos.js";
@@ -123,7 +131,8 @@ async function removeFromDay(day, id) {
videos: removeVideo(stored.videos, day, id),
...(mosaikOutbox ? { mosaikOutbox } : {}),
});
- if (isVideoId(id)) {
+ // A YouTube video or a streaming title will not count again; for other pages the decision is harmless
+ if (isItemId(id)) {
await saveOverride(id, false);
}
await correct(day, Math.max(0, Math.round(total - seconds)));
@@ -241,6 +250,35 @@ async function scheduleImmersion() {
}
}
+// The streaming sites (see sites.js)
+
+/**
+ * Makes the scripts of each streaming site match the setting: there while the site is on and its access is
+ * granted, gone otherwise (the person can take the access back from the browser's own pages).
+ */
+async function scheduleStreaming() {
+ if (!chrome.scripting) {
+ return;
+ }
+ const on = new Set(enabledSites((await chrome.storage.local.get(SITES_KEY))[SITES_KEY]));
+ const registered = new Set(
+ (await chrome.scripting.getRegisteredContentScripts()).map((script) => script.id),
+ );
+ for (const site of STREAMING_SITES) {
+ const wanted = on.has(site.id) && (await chrome.permissions.contains(sitePermissions(site)));
+ const ids = siteScriptIds(site);
+ const there = ids.filter((id) => registered.has(id));
+ if (wanted && there.length < ids.length) {
+ if (there.length > 0) {
+ await chrome.scripting.unregisterContentScripts({ ids: there });
+ }
+ await chrome.scripting.registerContentScripts(siteScripts(site));
+ } else if (!wanted && there.length > 0) {
+ await chrome.scripting.unregisterContentScripts({ ids: there });
+ }
+ }
+}
+
// Sound in the immersion profile (see audio.js)
async function immersionOn() {
@@ -363,6 +401,7 @@ chrome.runtime.onInstalled.addListener(({ reason }) => {
// there (and that there is none while it is off); the same for the script of the immersion profile
mosaik.schedule().catch(() => {});
scheduleImmersion().catch(() => {});
+scheduleStreaming().catch(() => {});
stepAudio().catch(() => {});
// In the single writer, so that a session the browser start ends (below) is not shown again after it
enqueue(async () => {
@@ -397,9 +436,13 @@ chrome.storage.onChanged.addListener((changes, area) => {
scheduleImmersion().catch(() => {});
stepAudio().catch(() => {});
}
+ if (area === "local" && changes[SITES_KEY]) {
+ scheduleStreaming().catch(() => {});
+ }
});
chrome.permissions.onRemoved.addListener(() => {
scheduleImmersion().catch(() => {});
+ scheduleStreaming().catch(() => {});
stepAudio().catch(() => {});
});
@@ -415,6 +458,7 @@ const CONTROLS = {
? enqueue(() => removeFromDay(message.day, message.videoId)).then(() => ({}))
: Promise.resolve({ error: "invalid" }),
"immersion:refresh": () => scheduleImmersion().then(() => ({})),
+ "streaming:refresh": () => scheduleStreaming().then(() => ({})),
"audio:status": async (message) => {
const sound = readSound((await chrome.storage.session.get("sound")).sound);
if (!Object.hasOwn(sound.open, String(message.tabId))) {
@@ -468,7 +512,7 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
return true;
} else if (
message?.type === "override" &&
- isVideoId(message.videoId) &&
+ isItemId(message.videoId) &&
typeof message.inTarget === "boolean"
) {
queue = queue.then(() => saveOverride(message.videoId, message.inTarget)).catch(() => {});
diff --git a/extension/src/content.js b/extension/src/content.js
index 5565ec4..fbad570 100644
--- a/extension/src/content.js
+++ b/extension/src/content.js
@@ -199,7 +199,7 @@
return;
}
if (message?.type === "status") {
- sendResponse({ ...watcher.status, immersion });
+ sendResponse({ ...watcher.status, immersion, title: currentVideo?.title ?? "" });
} else if (message?.type === "setInTarget" && typeof message.inTarget === "boolean" && currentVideoId) {
decided = message.inTarget;
setVerdict(message.inTarget);
diff --git a/extension/src/generic.js b/extension/src/generic.js
index eddb33c..461887e 100644
--- a/extension/src/generic.js
+++ b/extension/src/generic.js
@@ -12,6 +12,11 @@
if (location.hostname === "www.youtube.com" && window === window.top) {
return;
}
+ // Nor do the streaming sites the person turned on (streaming-content.js, which starts before this script
+ // and says so): there the time goes to the episode, under its own name
+ if (globalThis.inputlyStreaming) {
+ return;
+ }
const [{ Watcher }, { createSender }] = await Promise.all([
import(chrome.runtime.getURL("src/watcher.js")),
diff --git a/extension/src/sites.js b/extension/src/sites.js
new file mode 100644
index 0000000..f6dc4c5
--- /dev/null
+++ b/extension/src/sites.js
@@ -0,0 +1,103 @@
+/**
+ * The streaming sites Inputly can count without the immersion profile: Netflix, Crunchyroll, Prime Video and
+ * Disney+. Each one is off until the person turns it on in the settings, which asks the browser for access
+ * to that site alone (see docs/streaming.md). The setting is kept as `streamingSites: { "": true }`.
+ *
+ * Nothing here touches the browser: the background script registers the scripts this file describes, and
+ * the dashboard asks for the permissions it names.
+ */
+
+export const SITES_KEY = "streamingSites";
+
+/**
+ * `origins` are what is asked for when the site is turned on. They are all inside the optional ``
+ * the manifest declares, so turning a site on adds no warning at install and asks for that site only.
+ * `frames` is set where the video plays in a frame of another origin than the page.
+ * `experimental` sites were built from other extensions' notes and could not be tried in a real player.
+ */
+export const STREAMING_SITES = [
+ {
+ id: "netflix",
+ name: "Netflix",
+ origins: ["https://www.netflix.com/*"],
+ },
+ {
+ id: "crunchyroll",
+ name: "Crunchyroll",
+ // The page is on www; its player (Vilos) has been an iframe on static.crunchyroll.com
+ origins: ["https://www.crunchyroll.com/*", "https://static.crunchyroll.com/*"],
+ frames: ["https://static.crunchyroll.com"],
+ },
+ {
+ id: "primevideo",
+ name: "Prime Video",
+ // Prime Video has its own site, and plays inside the Amazon store of the countries that have one: the
+ // largest ones are asked for; elsewhere Amazon sends the person to primevideo.com
+ origins: [
+ "https://www.primevideo.com/*",
+ "https://www.amazon.com/*",
+ "https://www.amazon.co.uk/*",
+ "https://www.amazon.de/*",
+ "https://www.amazon.co.jp/*",
+ ],
+ experimental: true,
+ },
+ {
+ id: "disneyplus",
+ name: "Disney+",
+ origins: ["https://www.disneyplus.com/*"],
+ experimental: true,
+ },
+];
+
+/** The site with this id, or `null`. */
+export const siteById = (id) => STREAMING_SITES.find((site) => site.id === id) ?? null;
+
+/** The ids of the sites turned on, as they were saved; anything else is left out. */
+export function enabledSites(saved) {
+ if (!saved || typeof saved !== "object") {
+ return [];
+ }
+ return STREAMING_SITES.filter((site) => saved[site.id] === true).map((site) => site.id);
+}
+
+/** What is asked for when a site is turned on: registering its scripts, and access to its pages only. */
+export const sitePermissions = (site) => ({ permissions: ["scripting"], origins: [...site.origins] });
+
+/** The ids of the scripts of a site, so that they can be found and taken away again. */
+export const siteScriptIds = (site) => [`inputly-${site.id}-bridge`, `inputly-${site.id}`];
+
+/**
+ * The two scripts of a site, for `chrome.scripting.registerContentScripts`: one in the page itself (world
+ * "MAIN"), which reads what the player says, and the one that counts (`streaming-content.js`). They start
+ * before the page so that the immersion profile's script, which runs later in the same pages, sees that the
+ * page is counted already.
+ */
+export function siteScripts(site) {
+ const [bridgeId, contentId] = siteScriptIds(site);
+ const common = {
+ matches: [...site.origins],
+ runAt: "document_start",
+ allFrames: Boolean(site.frames),
+ persistAcrossSessions: true,
+ };
+ return [
+ { id: bridgeId, js: ["src/streaming-bridge.js"], world: "MAIN", ...common },
+ { id: contentId, js: ["src/streaming-content.js"], ...common },
+ ];
+}
+
+/** Whether a page address belongs to a site: compared with its origins, as the browser matches them. */
+export function siteOfUrl(text) {
+ let url;
+ try {
+ url = new URL(text);
+ } catch {
+ return null;
+ }
+ return (
+ STREAMING_SITES.find((site) =>
+ site.origins.some((origin) => new URL(origin.replace("/*", "/")).origin === url.origin),
+ ) ?? null
+ );
+}
diff --git a/extension/src/status.js b/extension/src/status.js
index 21e0f9a..91b5944 100644
--- a/extension/src/status.js
+++ b/extension/src/status.js
@@ -13,10 +13,19 @@ import { DEFAULT_TARGET, languageName } from "./target.js";
*
* `reply.ad` is true while an ad plays in the player: it is not counted, whatever the video's language.
*
+ * `reply.title` is the title of what plays (a YouTube video, an episode on a streaming site): `title` says
+ * it under the status, so that the person sees what the verdict is about.
+ *
* `action` is the link to correct a wrong guess about the language: `inTarget` is what pressing it
* decides. There is none while the language is not known, or when there is no video.
*/
export function describeStatus(reply, sound = null, language = languageName(DEFAULT_TARGET)) {
+ const status = statusOf(reply, sound, language);
+ const title = typeof reply?.title === "string" ? reply.title.trim() : "";
+ return title && !reply.ad ? { ...status, title } : status;
+}
+
+function statusOf(reply, sound, language) {
if (!reply) {
if (sound === "counting") {
return { kind: "counting", text: "Counting sound (immersion profile)" };
diff --git a/extension/src/streaming-bridge.js b/extension/src/streaming-bridge.js
new file mode 100644
index 0000000..591dd30
--- /dev/null
+++ b/extension/src/streaming-bridge.js
@@ -0,0 +1,196 @@
+// Runs in the page itself (world "MAIN") on the streaming sites the person turned on (see sites.js), because
+// what the player knows is not visible from the isolated world of a content script. It answers
+// `inputly:streaming-request` with a copy of a few plain values (the ids, the title, the playing audio and
+// subtitle tracks, whether an ad plays), which streaming.js turns into what counts. It never writes to the
+// page, never calls the player, and makes no request. What each value is, and where it was seen, is in
+// docs/streaming.md.
+(() => {
+ if (window.inputlyStreamingBridge) {
+ return;
+ }
+ window.inputlyStreamingBridge = true;
+
+ const MAX_TEXT = 300;
+ const str = (value) => (typeof value === "string" ? value.slice(0, MAX_TEXT) : null);
+ const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
+ const attempt = (read) => {
+ try {
+ return read();
+ } catch {
+ return null;
+ }
+ };
+ const visibleText = (selector) => {
+ const element = document.querySelector(selector);
+ return element ? str(element.textContent) : null;
+ };
+
+ /** The props of the React components above an element, nearest first, until `found` says one is it. */
+ function reactProps(element, found) {
+ const key = element && Object.keys(element).find((name) => name.startsWith("__reactFiber"));
+ let fiber = key ? element[key] : null;
+ for (let depth = 0; fiber && depth < 60; depth += 1, fiber = fiber.return) {
+ const value = found(fiber.memoizedProps);
+ if (value) {
+ return value;
+ }
+ }
+ return null;
+ }
+
+ function netflix() {
+ const api = window.netflix?.appContext?.state?.playerApp?.getAPI?.()?.videoPlayer;
+ const ids = api?.getAllPlayerSessionIds?.() ?? [];
+ const session = ids.find((id) => String(id).startsWith("watch")) ?? ids[0];
+ const player = session ? api.getVideoPlayerBySessionId(session) : null;
+ if (!player) {
+ return null;
+ }
+ const movieId = attempt(() => player.getMovieId());
+ const audio = attempt(() => player.getAudioTrack());
+ const shown = attempt(() => player.getTimedTextTrack());
+ const metadata = attempt(
+ () =>
+ window.netflix.appContext.state.playerApp.getState().videoPlayer.videoMetadata[movieId]
+ ._metadataObject.video,
+ );
+ const seasons = Array.isArray(metadata?.seasons) ? metadata.seasons.slice(0, 50) : [];
+ return {
+ movieId: num(movieId),
+ audioTrack: audio && { bcp47: str(audio.bcp47), displayName: str(audio.displayName) },
+ timedTextTrack: shown && {
+ bcp47: str(shown.bcp47),
+ isNoneTrack: shown.isNoneTrack === true,
+ isForcedNarrative: shown.isForcedNarrative === true,
+ },
+ video: metadata && {
+ title: str(metadata.title),
+ type: str(metadata.type),
+ seasons: seasons.map((season) => ({
+ seq: num(season?.seq),
+ episodes: (Array.isArray(season?.episodes) ? season.episodes.slice(0, 200) : []).map((episode) => ({
+ id: num(episode?.id),
+ seq: num(episode?.seq),
+ title: str(episode?.title),
+ })),
+ })),
+ },
+ currentTime: num(attempt(() => player.getCurrentTime())),
+ segmentTime: num(attempt(() => player.getSegmentTime())),
+ adLabel: document.querySelector('[data-uia*="ads-info"]') !== null,
+ domTitle: visibleText('[data-uia="video-title"]'),
+ };
+ }
+
+ // The store of Crunchyroll's web app, found once through the props of its React root
+ let crunchyrollStore = null;
+ function crunchyroll() {
+ if (window !== window.top) {
+ return null;
+ }
+ if (!crunchyrollStore) {
+ for (const element of document.querySelectorAll("body > div, body > div > div")) {
+ crunchyrollStore = reactProps(element, (props) =>
+ typeof props?.store?.getState === "function" ? props.store : null,
+ );
+ if (crunchyrollStore) {
+ break;
+ }
+ }
+ }
+ const state = crunchyrollStore?.getState?.();
+ const watchId = str(state?.watch?.id);
+ const media = watchId ? state.content?.media?.byId?.[watchId] : null;
+ if (!media) {
+ return null;
+ }
+ return {
+ watchId,
+ premiumDubSelectedVersion: str(state.watch.premiumDubSelectedVersion),
+ media: {
+ id: str(media.id),
+ type: str(media.type),
+ title: str(media.title),
+ parentTitle: str(media.parentTitle),
+ episode: str(media.episode),
+ audioLocale: str(media.audioLocale),
+ subtitleLanguages: (Array.isArray(media.subtitleLanguages) ? media.subtitleLanguages : [])
+ .slice(0, 50)
+ .map(str),
+ dubVersions: (Array.isArray(media.dubVersions) ? media.dubVersions : [])
+ .slice(0, 50)
+ .map((version) => ({
+ guid: str(version?.guid),
+ audioLocale: str(version?.audioLocale),
+ })),
+ },
+ };
+ }
+
+ // The context Prime Video's player gives its components, found through the player's container
+ let primeContext = { element: null, value: null };
+ function primevideo() {
+ const element = document.querySelector("#dv-web-player .atvwebplayersdk-player-container");
+ if (!element) {
+ return null;
+ }
+ if (primeContext.element !== element) {
+ const value = reactProps(element, (props) =>
+ [props?.context, props?.value].find((each) => each?.audioStream && each?.title && each?.player),
+ );
+ primeContext = { element, value };
+ }
+ const context = primeContext.value;
+ if (!context || !context.player.isPlayerOpen || context.player.isPlayerDestroyed) {
+ return null;
+ }
+ const info = attempt(() => context.title.getTitleInfo());
+ const audio = attempt(() => context.audioStream.getAudioStreamInfo().activeStream);
+ const subtitle = attempt(() => context.captions.getCurrentCaptionsStream());
+ const items = attempt(() => context.player.timeline.items);
+ const index = attempt(() => context.player.currentTime.currentTimelineItemIndex);
+ const item = Array.isArray(items) && Number.isInteger(index) ? items[index] : null;
+ return {
+ titleInfo: info && { titleId: str(info.titleId), title: str(info.title) },
+ audio: audio && { id: str(audio.id), language: str(audio.language) },
+ subtitle: subtitle && { id: str(subtitle.id), language: str(subtitle.language) },
+ // An ad plays when the ad player says so, or the timeline item is not the title's (`..._main`)
+ adPlaying:
+ Boolean(attempt(() => context.adPlayback.getAdPlaybackInfo())) ||
+ (typeof item?.contentId === "string" && !item.contentId.endsWith("_main")),
+ adTimer: document.querySelector(".atvwebplayersdk-ad-timer") !== null,
+ domTitle: visibleText(".atvwebplayersdk-title-text"),
+ domSubtitle: visibleText(".atvwebplayersdk-subtitle-text"),
+ };
+ }
+
+ function disneyplus() {
+ const element = document.querySelector("disney-web-player");
+ const own = (target, key) => (target && Object.hasOwn(target, key) ? target[key] : undefined);
+ const audio = attempt(() => own(element, "mediaPlayer")?.audio?.selectedTrack);
+ const badge = document.querySelector("ad-badge-overlay");
+ return {
+ path: str(location.pathname),
+ title: str(document.title),
+ audio: audio && { language: str(audio.language) },
+ adBadge: badge ? str((badge.shadowRoot ?? badge).textContent) : null,
+ };
+ }
+
+ const READERS = { netflix, crunchyroll, primevideo, disneyplus };
+
+ window.addEventListener("message", (event) => {
+ const site = event.data?.site;
+ if (
+ event.source !== window ||
+ event.data?.type !== "inputly:streaming-request" ||
+ !Object.hasOwn(READERS, site)
+ ) {
+ return;
+ }
+ window.postMessage(
+ { type: "inputly:streaming", site, raw: attempt(READERS[site]) },
+ window.location.origin,
+ );
+ });
+})();
diff --git a/extension/src/streaming-content.js b/extension/src/streaming-content.js
new file mode 100644
index 0000000..563eeb0
--- /dev/null
+++ b/extension/src/streaming-content.js
@@ -0,0 +1,220 @@
+// Runs on the streaming sites the person turned on in the settings (see sites.js), added by the background
+// script. It asks the page script (streaming-bridge.js) what the player plays, lets streaming.js turn that
+// into an episode, its audio language and whether an ad plays, and counts the seconds the video element
+// plays in the target language, as content.js does on YouTube. In the immersion profile every title counts.
+(async () => {
+ // Added again when the page runs it twice (an extension update)
+ if (globalThis.inputlyStreaming) {
+ return;
+ }
+ // Set before anything waits: the immersion profile's script (generic.js), which runs later in the same
+ // pages, leaves a page this script counts alone, or the time would be counted under two names
+ globalThis.inputlyStreaming = true;
+
+ const { siteOfUrl } = await import(chrome.runtime.getURL("src/sites.js"));
+ const site = siteOfUrl(location.href);
+ if (!site) {
+ return;
+ }
+
+ const FLUSH_EVERY_MS = 2_000;
+ const ASK_EVERY_MS = 1_000;
+ // A frame that stopped telling counts as stopped after this long (it says every flush period)
+ const FRAME_SILENCE_MS = 6_000;
+ const videoPlays = (video) => video.isConnected && !video.paused && !video.ended;
+
+ // The player of some sites (Crunchyroll's Vilos) is a frame of another origin than the page: there this
+ // script only tells the page whether its video plays, and the page counts it
+ if (window !== window.top) {
+ if (!(site.frames ?? []).includes(location.origin)) {
+ globalThis.inputlyStreaming = false;
+ return;
+ }
+ const tell = () =>
+ window.top.postMessage(
+ { type: "inputly:frame-video", playing: [...document.querySelectorAll("video")].some(videoPlays) },
+ "*",
+ );
+ for (const type of ["playing", "pause", "waiting", "ended", "emptied", "error"]) {
+ document.addEventListener(type, tell, true);
+ }
+ setInterval(tell, FLUSH_EVERY_MS);
+ return;
+ }
+
+ const [
+ { Watcher },
+ { readStreaming, streamingItem, streamingVerdict },
+ { overridesKey, verdict },
+ { immersionOf },
+ { TARGET_KEY, targetOf },
+ { createSender },
+ { SITES_KEY, enabledSites },
+ ] = await Promise.all([
+ import(chrome.runtime.getURL("src/watcher.js")),
+ import(chrome.runtime.getURL("src/streaming.js")),
+ import(chrome.runtime.getURL("src/overrides.js")),
+ import(chrome.runtime.getURL("src/immersion.js")),
+ import(chrome.runtime.getURL("src/target.js")),
+ import(chrome.runtime.getURL("src/delivery.js")),
+ import(chrome.runtime.getURL("src/sites.js")),
+ ]);
+ const saved = await chrome.storage.local.get(["immersion", TARGET_KEY]);
+ let immersion = immersionOf(saved.immersion);
+ let target = targetOf(saved[TARGET_KEY]);
+ let stopped = false;
+
+ const now = () => Date.now() / 1000;
+ // The episode or film that plays: `{ id, title, url }`, named in the day's list and in the popup
+ let item = null;
+ let key = null;
+ let decided = null;
+ const sender = createSender((message) => chrome.runtime.sendMessage(message));
+ const watcher = new Watcher({
+ send: (intervals) => sender.send({ type: "watched", intervals, video: item }),
+ });
+ const announce = (inTarget) => chrome.runtime.sendMessage({ type: "language", inTarget }).catch(() => {});
+
+ // Whether a video plays: an element of this page, or the frame of the player
+ const videos = new Set();
+ let frameSaid = { playing: false, at: 0 };
+ const playsNow = () =>
+ !stopped &&
+ ([...videos].some(videoPlays) || (frameSaid.playing && Date.now() - frameSaid.at < FRAME_SILENCE_MS));
+ let playing = false;
+ let ad = false;
+
+ function update() {
+ const plays = playsNow();
+ watcher.setAd(now(), ad, plays);
+ if (plays && !playing) {
+ watcher.play(now());
+ } else if (!plays && playing) {
+ watcher.pause(now());
+ }
+ playing = plays;
+ }
+
+ function attach(video) {
+ if (videos.has(video)) {
+ return;
+ }
+ videos.add(video);
+ for (const type of ["playing", "pause", "waiting", "ended", "emptied", "error"]) {
+ video.addEventListener(type, update);
+ }
+ update();
+ }
+ const lookForVideos = () => document.querySelectorAll("video").forEach(attach);
+
+ window.addEventListener("message", (event) => {
+ if (event.data?.type === "inputly:frame-video" && (site.frames ?? []).includes(event.origin)) {
+ frameSaid = { playing: event.data.playing === true, at: Date.now() };
+ update();
+ }
+ });
+
+ const ask = () =>
+ window.postMessage({ type: "inputly:streaming-request", site: site.id }, window.location.origin);
+
+ function forget() {
+ watcher.newVideo(now());
+ item = null;
+ key = null;
+ decided = null;
+ announce(null);
+ }
+
+ window.addEventListener("message", async (event) => {
+ if (event.source !== window || event.data?.type !== "inputly:streaming" || event.data.site !== site.id) {
+ return;
+ }
+ const info = readStreaming(site.id, event.data.raw);
+ if (!info) {
+ // The player closed, or the page went back to browsing: what was counted is settled
+ if (key !== null) {
+ forget();
+ }
+ return;
+ }
+ if (info.key !== key) {
+ forget();
+ key = info.key;
+ }
+ item = streamingItem(info, site.name);
+ if (info.ad !== ad) {
+ ad = info.ad;
+ update();
+ }
+ // What the person decided about this title, for this target language, wins over the player's answer
+ const asked = target;
+ const storageKey = overridesKey(asked);
+ const { [storageKey]: overrides } = await chrome.storage.local.get(storageKey);
+ if (info.key !== key || asked !== target || ad) {
+ // During an ad the tracks are the ad's: the verdict stays the title's
+ return;
+ }
+ const guess = immersion ? true : streamingVerdict(info, asked);
+ const inTarget = verdict(overrides, item.id, guess);
+ if (typeof inTarget === "boolean" && inTarget !== decided) {
+ decided = inTarget;
+ watcher.setInTarget(now(), inTarget);
+ announce(inTarget);
+ }
+ });
+
+ chrome.storage.onChanged.addListener((changes, area) => {
+ if (area !== "local") {
+ return;
+ }
+ if (changes.immersion) {
+ immersion = immersionOf(changes.immersion.newValue);
+ }
+ if (changes[TARGET_KEY]) {
+ target = targetOf(changes[TARGET_KEY].newValue);
+ }
+ // Turned off: nothing more counts here, even before the page is opened again
+ if (changes[SITES_KEY] && !enabledSites(changes[SITES_KEY].newValue).includes(site.id)) {
+ stopped = true;
+ update();
+ watcher.flush(now());
+ }
+ if (changes[overridesKey(target)] || changes.immersion || changes[TARGET_KEY]) {
+ decided = null;
+ ask();
+ }
+ });
+
+ // The popup asks what the tab plays, and can correct the answer about its language
+ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
+ if (sender.id !== chrome.runtime.id || stopped || !item) {
+ return;
+ }
+ if (message?.type === "status") {
+ sendResponse({ ...watcher.status, immersion, title: item.title });
+ } else if (message?.type === "setInTarget" && typeof message.inTarget === "boolean") {
+ decided = message.inTarget;
+ watcher.setInTarget(now(), message.inTarget);
+ announce(message.inTarget);
+ chrome.runtime
+ .sendMessage({ type: "override", videoId: item.id, inTarget: message.inTarget })
+ .catch(() => {});
+ }
+ });
+
+ new MutationObserver(lookForVideos).observe(document.documentElement, { childList: true, subtree: true });
+ // These sites change page without loading one, and switch tracks while playing: the player is asked
+ // every second, which costs a few property reads
+ setInterval(ask, ASK_EVERY_MS);
+ setInterval(() => {
+ update();
+ watcher.sync(now(), playsNow());
+ watcher.flush(now());
+ sender.retry(now());
+ }, FLUSH_EVERY_MS);
+ document.addEventListener("visibilitychange", () => document.hidden && watcher.flush(now()));
+ window.addEventListener("pagehide", () => watcher.flush(now()));
+
+ lookForVideos();
+ ask();
+})();
diff --git a/extension/src/streaming.js b/extension/src/streaming.js
new file mode 100644
index 0000000..e73a41f
--- /dev/null
+++ b/extension/src/streaming.js
@@ -0,0 +1,205 @@
+/**
+ * What a streaming player says it is playing, turned into the same few facts for every site:
+ * `{ key, title, audioLanguage, subtitleLanguages, ad }`.
+ *
+ * - `key` names the episode or film: the same one is the same item in the day's list, whatever the address
+ * of the page says (an item id is made from it, see `streamingItem`).
+ * - `audioLanguage` is the language of the audio track the player says is playing (a BCP 47 tag, or `null`
+ * when it does not say). It decides, as it does on YouTube: what is heard is what counts. A dub in the
+ * target language counts, an original in the target language with the person's dub picked does not.
+ * - `subtitleLanguages` are the subtitle tracks shown (or offered, where the player says no more), kept for
+ * the record: subtitles are often translations, so they never decide.
+ * - `ad` is true while the player shows an ad instead of the title.
+ *
+ * Each `read` takes what `streaming-bridge.js` copied from the page (plain data, never the player's
+ * objects) and returns those facts, or `null` when nothing is playing. They are pure so that they can be
+ * tested with data captured from the real players (see tests/streaming.test.js and docs/streaming.md).
+ */
+import { webItemId } from "./items.js";
+import { isTarget, normalizeLanguage } from "./target.js";
+
+const text = (value) => (typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "");
+
+/** A language tag as the player gives it (`"ja"`, `"ja-JP"`, `"es-419"`, `"en_US"`), or `null`. */
+const tag = (value) => (normalizeLanguage(typeof value === "string" ? value : null) ? value.trim() : null);
+
+const tags = (values) => [...new Set((Array.isArray(values) ? values : []).map(tag).filter(Boolean))];
+
+const idText = (value) =>
+ (typeof value === "number" && Number.isSafeInteger(value)) || (typeof value === "string" && value.trim())
+ ? String(value).trim()
+ : null;
+
+// Netflix
+
+/**
+ * Netflix's player (Cadmium), read through `netflix.appContext.state.playerApp.getAPI().videoPlayer`:
+ * `movieId` is the episode or film, `audioTrack` the playing track (`bcp47`), `timedTextTrack` the shown
+ * subtitles, `video` the title's metadata (`_metadataObject.video`: the show, its seasons and episodes).
+ *
+ * Ads (the plan with ads): before the title the player plays a lead-in in its own segment, and the player
+ * clock (`currentTime`) runs while the title's clock (`segmentTime`) stays at 0; during any ad the player
+ * shows its "Ad" label (`adLabel`, from `[data-uia*="ads-info"]`).
+ */
+export function readNetflix(raw) {
+ const movieId = idText(raw?.movieId);
+ if (!movieId) {
+ return null;
+ }
+ const audio = raw.audioTrack ?? {};
+ const shown = raw.timedTextTrack;
+ const subtitles = shown && !shown.isNoneTrack && !shown.isForcedNarrative ? [shown.bcp47] : [];
+ const leadIn = raw.segmentTime === 0 && raw.currentTime > 0;
+ return {
+ key: `https://www.netflix.com/watch/${movieId}`,
+ title: netflixTitle(raw.video, movieId) || text(raw.domTitle),
+ audioLanguage: tag(audio.bcp47),
+ subtitleLanguages: tags(subtitles),
+ ad: raw.adLabel === true || leadIn,
+ };
+}
+
+/** "Show S1:E2 Episode" for an episode, the title alone for a film. */
+function netflixTitle(video, movieId) {
+ const show = text(video?.title);
+ if (!show || video.type !== "show") {
+ return show;
+ }
+ for (const season of Array.isArray(video.seasons) ? video.seasons : []) {
+ const episode = (Array.isArray(season?.episodes) ? season.episodes : []).find(
+ (each) => idText(each?.id) === movieId,
+ );
+ if (episode) {
+ const name = text(episode.title);
+ return `${show} S${season.seq}:E${episode.seq}${name ? ` ${name}` : ""}`;
+ }
+ }
+ return show;
+}
+
+// Crunchyroll
+
+/**
+ * Crunchyroll's web app keeps the episode of the watch page in its store: `watch.id`, and
+ * `content.media.byId[id]` with its `audioLocale`. Each dub is a separate episode with its own id
+ * (`dubVersions`), so the episode of the page is the audio that plays; a dub picked inside the player
+ * (`premiumDubSelectedVersion`) wins over it.
+ *
+ * Ads: none is detected. Every episode seen was `premium_only` (no free tier with ads, checked logged out on
+ * 2026-11-23), and a premium account plays none.
+ */
+export function readCrunchyroll(raw) {
+ const media = raw?.media;
+ const pageId = idText(raw?.watchId);
+ if (!media || !pageId || idText(media.id) !== pageId) {
+ return null;
+ }
+ const versions = Array.isArray(media.dubVersions) ? media.dubVersions : [];
+ const picked = versions.find((version) => version?.guid && version.guid === raw.premiumDubSelectedVersion);
+ const id = idText(picked?.guid) ?? pageId;
+ const audio = tag(picked?.audioLocale) ?? tag(media.audioLocale);
+ const series = text(media.parentTitle);
+ const name = text(media.title);
+ const episode = text(media.episode);
+ const title =
+ media.type === "episode" && series
+ ? `${series}${episode ? ` E${episode}` : ""}${name ? ` - ${name}` : ""}`
+ : name || series;
+ return {
+ key: `https://www.crunchyroll.com/watch/${id}`,
+ title,
+ audioLanguage: audio,
+ subtitleLanguages: tags(media.subtitleLanguages),
+ ad: false,
+ };
+}
+
+// Prime Video
+
+/**
+ * Prime Video's web player (the "atvwebplayersdk"), read from the context its React tree gives the player:
+ * `title.getTitleInfo()` (`titleId`, `title`), `audioStream.getAudioStreamInfo().activeStream` (`language`,
+ * or an id that starts with it), `captions.getCurrentCaptionsStream()`. During an ad
+ * `adPlayback.getAdPlaybackInfo()` says so (`adPlaying`), and the player shows an ad timer (`adTimer`).
+ */
+export function readPrimeVideo(raw) {
+ const titleId = idText(raw?.titleInfo?.titleId);
+ if (!titleId) {
+ return null;
+ }
+ const streamLanguage = (stream) =>
+ stream && stream.id !== "off"
+ ? (tag(stream.language) ?? tag(typeof stream.id === "string" ? stream.id.split("_")[0] : null))
+ : null;
+ const title = text(raw.titleInfo.title) || text(raw.domTitle);
+ const episode = text(raw.domSubtitle);
+ return {
+ key: `https://www.primevideo.com/detail/${encodeURIComponent(titleId)}`,
+ title: episode && title && !title.includes(episode) ? `${title} - ${episode}` : title,
+ audioLanguage: streamLanguage(raw.audio),
+ subtitleLanguages: tags([streamLanguage(raw.subtitle)]),
+ ad: raw.adPlaying === true || raw.adTimer === true,
+ };
+}
+
+// Disney+
+
+/** "Disney+" alone, or a page that is not the player, says nothing of the title. */
+const DISNEY_SUFFIX = /\s*[|–—-]\s*Disney\+\s*$/i;
+const GENERIC_DISNEY = /^(disney\+?|home|watch|search)$/i;
+
+/**
+ * Disney+'s player (`disney-web-player`) keeps its audio on the element (`mediaPlayer.audio.selectedTrack`,
+ * whose `language` is a tag). The id is the one of the play page (`/play/`). The title is the page's,
+ * without " | Disney+". During an ad the player draws `ad-badge-overlay` with the time left ("0:15").
+ */
+export function readDisneyPlus(raw) {
+ const id = /\/play\/([\w-]+)/.exec(typeof raw?.path === "string" ? raw.path : "")?.[1];
+ if (!id) {
+ return null;
+ }
+ const title = text(raw.title)
+ .replace(DISNEY_SUFFIX, "")
+ .replace(/^watch\s+/i, "");
+ return {
+ key: `https://www.disneyplus.com/play/${id}`,
+ title: GENERIC_DISNEY.test(title) ? "" : title,
+ audioLanguage: tag(raw.audio?.language),
+ subtitleLanguages: tags([raw.subtitle?.language]),
+ ad: /\d+:\d{2}/.test(text(raw.adBadge)),
+ };
+}
+
+const READERS = {
+ netflix: readNetflix,
+ crunchyroll: readCrunchyroll,
+ primevideo: readPrimeVideo,
+ disneyplus: readDisneyPlus,
+};
+
+/** What a site's player is playing, from what the bridge copied of it; `null` if nothing (or not known). */
+export function readStreaming(siteId, raw) {
+ const read = Object.hasOwn(READERS, siteId) ? READERS[siteId] : null;
+ try {
+ return read && raw && typeof raw === "object" ? read(raw) : null;
+ } catch {
+ // A player that changed shape reads as nothing: nothing is counted, rather than a wrong guess
+ return null;
+ }
+}
+
+/**
+ * Whether what plays is in the target language: `null` while the player has not said which audio plays
+ * (the time waits, and is dropped if it never says), and during an ad, whose tracks are the ad's.
+ */
+export function streamingVerdict(info, target) {
+ if (!info || info.ad || !info.audioLanguage) {
+ return null;
+ }
+ return isTarget(info.audioLanguage, target);
+}
+
+/** The item the time of an episode or film is kept under, for the day's list: `{ id, title, url }`. */
+export function streamingItem(info, siteName) {
+ return { id: webItemId(info.key), title: info.title || siteName, url: info.key };
+}
diff --git a/tests/sites.test.js b/tests/sites.test.js
new file mode 100644
index 0000000..e6b0d67
--- /dev/null
+++ b/tests/sites.test.js
@@ -0,0 +1,118 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+
+import {
+ STREAMING_SITES,
+ enabledSites,
+ siteById,
+ siteOfUrl,
+ sitePermissions,
+ siteScriptIds,
+ siteScripts,
+} from "../extension/src/sites.js";
+
+const EXTENSION = resolve(dirname(fileURLToPath(import.meta.url)), "..", "extension");
+const manifest = JSON.parse(readFileSync(resolve(EXTENSION, "manifest.json"), "utf8"));
+const read = (file) => readFileSync(resolve(EXTENSION, file), "utf8");
+
+test("the four sites, Netflix and Crunchyroll first", () => {
+ assert.deepEqual(
+ STREAMING_SITES.map((site) => site.id),
+ ["netflix", "crunchyroll", "primevideo", "disneyplus"],
+ );
+ assert.equal(siteById("crunchyroll").name, "Crunchyroll");
+ assert.equal(siteById("hulu"), null);
+});
+
+test("only the sites saved as on are on", () => {
+ assert.deepEqual(enabledSites(undefined), []);
+ assert.deepEqual(enabledSites({ netflix: true, crunchyroll: false, hulu: true, disneyplus: "yes" }), [
+ "netflix",
+ ]);
+});
+
+test("each site asks for its own pages only, inside what the manifest declares as optional", () => {
+ for (const site of STREAMING_SITES) {
+ const asked = sitePermissions(site);
+ assert.deepEqual(asked.permissions, ["scripting"]);
+ assert.ok(manifest.optional_permissions.includes("scripting"));
+ for (const origin of asked.origins) {
+ assert.match(origin, /^https:\/\/[a-z0-9.-]+\/\*$/, origin);
+ // Granted at runtime as a part of : no new host in the manifest, no warning at install
+ assert.ok(manifest.optional_host_permissions.includes(""));
+ assert.ok(!(manifest.host_permissions ?? []).includes(origin));
+ }
+ }
+});
+
+test("each site registers its page script and the script that counts, on its pages", () => {
+ for (const site of STREAMING_SITES) {
+ const [bridge, content] = siteScripts(site);
+ assert.deepEqual([bridge.id, content.id], siteScriptIds(site));
+ assert.equal(bridge.world, "MAIN");
+ assert.deepEqual(bridge.js, ["src/streaming-bridge.js"]);
+ assert.deepEqual(content.js, ["src/streaming-content.js"]);
+ assert.equal(content.world, undefined);
+ for (const script of [bridge, content]) {
+ assert.deepEqual(script.matches, site.origins);
+ // Before the immersion profile's script, which then leaves the page alone
+ assert.equal(script.runAt, "document_start");
+ assert.equal(script.allFrames, Boolean(site.frames));
+ }
+ }
+ // Crunchyroll's player is a frame of static.crunchyroll.com, which it asks for too
+ const crunchyroll = siteById("crunchyroll");
+ assert.equal(siteScripts(crunchyroll)[1].allFrames, true);
+ for (const frame of crunchyroll.frames) {
+ assert.ok(crunchyroll.origins.includes(`${frame}/*`));
+ }
+});
+
+test("a page address finds its site by origin", () => {
+ assert.equal(siteOfUrl("https://www.netflix.com/watch/82028220?trackId=1").id, "netflix");
+ assert.equal(siteOfUrl("https://static.crunchyroll.com/vilos-v2/web/vilos/player.html").id, "crunchyroll");
+ assert.equal(siteOfUrl("https://www.amazon.de/gp/video/detail/B0").id, "primevideo");
+ assert.equal(siteOfUrl("https://www.disneyplus.com/play/x").id, "disneyplus");
+ assert.equal(siteOfUrl("https://netflix.com.evil.example/watch/1"), null);
+ assert.equal(siteOfUrl("not an address"), null);
+});
+
+test("what the counting script imports can be reached from every page it runs on, and nothing more", () => {
+ const imported = (file) => [...read(file).matchAll(/getURL\("([^"]+)"\)/g)].map((match) => match[1]);
+ // The modules it imports, and the ones they import in turn
+ const needed = new Set();
+ const visit = (file) => {
+ for (const next of [
+ ...imported(file),
+ ...[...read(file).matchAll(/from "\.\/([^"]+)"/g)].map((match) => `src/${match[1]}`),
+ ]) {
+ if (!needed.has(next)) {
+ needed.add(next);
+ visit(next);
+ }
+ }
+ };
+ visit("src/streaming-content.js");
+ const origins = STREAMING_SITES.flatMap((site) => site.origins);
+ for (const origin of origins) {
+ const reachable = manifest.web_accessible_resources
+ .filter((entry) => entry.matches.includes(origin) || entry.matches.includes(""))
+ .flatMap((entry) => entry.resources);
+ for (const file of needed) {
+ assert.ok(reachable.includes(file), `${file} on ${origin}`);
+ }
+ }
+ const entry = manifest.web_accessible_resources.find((each) => each.resources.includes("src/streaming.js"));
+ assert.deepEqual([...entry.resources].sort(), [...needed].sort());
+ assert.deepEqual([...entry.matches].sort(), [...origins].sort());
+});
+
+test("the page script makes no request and never writes to the page", () => {
+ const bridge = read("src/streaming-bridge.js");
+ for (const call of ["fetch(", "XMLHttpRequest", "sendBeacon", "JSON.parse =", "innerHTML", ".click()"]) {
+ assert.ok(!bridge.includes(call), call);
+ }
+});
diff --git a/tests/status.test.js b/tests/status.test.js
index f40a159..823dfa2 100644
--- a/tests/status.test.js
+++ b/tests/status.test.js
@@ -100,3 +100,12 @@ test("marking a video as not German stops what is counted, and marking it back r
watcher.pause(8);
assert.deepEqual(sent.at(-1), [{ from: 6, to: 8 }]);
});
+
+test("the title of what plays goes under the status, but not during an ad", () => {
+ const reply = { inTarget: true, playing: true, title: " One Piece E1 - ¡Soy Luffy! " };
+ assert.equal(describeStatus(reply, null, "Japanese").title, "One Piece E1 - ¡Soy Luffy!");
+ assert.equal(describeStatus(reply, null, "Japanese").text, "Counting Japanese");
+ assert.equal(describeStatus({ ...reply, ad: true }).title, undefined);
+ assert.equal(describeStatus({ ...reply, title: "" }).title, undefined);
+ assert.equal(describeStatus(undefined).title, undefined);
+});
diff --git a/tests/streaming.test.js b/tests/streaming.test.js
new file mode 100644
index 0000000..e019cbc
--- /dev/null
+++ b/tests/streaming.test.js
@@ -0,0 +1,259 @@
+// The streaming sites' readers, fed with what the bridge copies from each player. Where the data comes from
+// is said for each site, and in docs/streaming.md: Crunchyroll's was captured from its real page, Netflix's
+// is the probe output another extension published, Prime Video's and Disney+'s follow the shapes other
+// extensions read (no account was at hand to capture them).
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { isWebItemId } from "../extension/src/items.js";
+import {
+ readCrunchyroll,
+ readDisneyPlus,
+ readNetflix,
+ readPrimeVideo,
+ readStreaming,
+ streamingItem,
+ streamingVerdict,
+} from "../extension/src/streaming.js";
+
+// Crunchyroll, captured logged out on 2026-11-23 from www.crunchyroll.com/es/watch/ (the bridge's copy of
+// the store: `watch.id` and `content.media.byId[id]`). One Piece episode 1, original and Latin American dub.
+const crunchyrollDubs = [
+ { guid: "GR3VWXP96", audioLocale: "ja-JP" },
+ { guid: "GE00010122ES419", audioLocale: "es-419" },
+ { guid: "GE00010122PTBR", audioLocale: "pt-BR" },
+];
+const crunchyrollOriginal = {
+ watchId: "GR3VWXP96",
+ premiumDubSelectedVersion: null,
+ media: {
+ id: "GR3VWXP96",
+ type: "episode",
+ title: "¡Soy Luffy! ¡El hombre que se convertirá en el Rey de los Piratas!",
+ parentTitle: "One Piece",
+ episode: "1",
+ audioLocale: "ja-JP",
+ subtitleLanguages: ["en-US", "es-419", "es-ES", "pt-BR"],
+ dubVersions: crunchyrollDubs,
+ },
+};
+const crunchyrollDub = {
+ watchId: "GE00010122ES419",
+ premiumDubSelectedVersion: null,
+ media: {
+ ...crunchyrollOriginal.media,
+ id: "GE00010122ES419",
+ audioLocale: "es-419",
+ subtitleLanguages: ["en-US", "es-419", "es-ES", "pt-BR", "es-419"],
+ },
+};
+
+test("Crunchyroll: the episode of the page is the audio that plays", () => {
+ const info = readCrunchyroll(crunchyrollOriginal);
+ assert.deepEqual(info, {
+ key: "https://www.crunchyroll.com/watch/GR3VWXP96",
+ title: "One Piece E1 - ¡Soy Luffy! ¡El hombre que se convertirá en el Rey de los Piratas!",
+ audioLanguage: "ja-JP",
+ subtitleLanguages: ["en-US", "es-419", "es-ES", "pt-BR"],
+ ad: false,
+ });
+ assert.equal(streamingVerdict(info, "ja"), true);
+ assert.equal(streamingVerdict(info, "es"), false);
+});
+
+test("Crunchyroll: a dub is another episode, in the language of the dub", () => {
+ const info = readCrunchyroll(crunchyrollDub);
+ assert.equal(info.key, "https://www.crunchyroll.com/watch/GE00010122ES419");
+ assert.equal(info.audioLanguage, "es-419");
+ // The subtitle list repeats a language: kept once
+ assert.deepEqual(info.subtitleLanguages, ["en-US", "es-419", "es-ES", "pt-BR"]);
+ assert.equal(streamingVerdict(info, "ja"), false);
+ assert.equal(streamingVerdict(info, "es"), true);
+});
+
+test("Crunchyroll: a dub picked inside the player wins over the page's episode", () => {
+ const info = readCrunchyroll({ ...crunchyrollOriginal, premiumDubSelectedVersion: "GE00010122PTBR" });
+ assert.equal(info.key, "https://www.crunchyroll.com/watch/GE00010122PTBR");
+ assert.equal(info.audioLanguage, "pt-BR");
+});
+
+test("Crunchyroll: a store that does not hold the page's episode yet says nothing", () => {
+ assert.equal(readCrunchyroll({ watchId: "GR3VWXP96", media: null }), null);
+ assert.equal(readCrunchyroll({ ...crunchyrollOriginal, watchId: "GY2P59DJY" }), null);
+ assert.equal(readCrunchyroll({}), null);
+});
+
+test("Crunchyroll: a film is named by its title", () => {
+ const info = readCrunchyroll({
+ watchId: "G2XU0Z1P7",
+ media: { id: "G2XU0Z1P7", type: "movie", title: "Suzume", parentTitle: "Suzume", audioLocale: "ja-JP" },
+ });
+ assert.equal(info.title, "Suzume");
+});
+
+// Netflix: the values of the probe LingoFlix published for "A Different World" E1 (/watch/82028220), Chrome 154,
+// 2026-10-10 (docs/netflix-internals.md of jaycho1214/lingoflix), in the shape the bridge copies.
+const netflixEpisode = {
+ movieId: 82028220,
+ audioTrack: { bcp47: "en", displayName: "English [Original]" },
+ timedTextTrack: { bcp47: "en", isNoneTrack: false, isForcedNarrative: false },
+ video: {
+ title: "A Different World",
+ type: "show",
+ seasons: [
+ {
+ seq: 1,
+ episodes: [
+ { id: 82028220, seq: 1, title: "Irreconcilable Differences" },
+ { id: 82028221, seq: 2, title: "O Captain! My Captain!" },
+ ],
+ },
+ ],
+ },
+ currentTime: 691009,
+ segmentTime: 691009,
+ adLabel: false,
+ domTitle: "A Different WorldE1Irreconcilable Differences",
+};
+
+test("Netflix: the audio track the player plays, and the episode's name from its metadata", () => {
+ const info = readNetflix(netflixEpisode);
+ assert.deepEqual(info, {
+ key: "https://www.netflix.com/watch/82028220",
+ title: "A Different World S1:E1 Irreconcilable Differences",
+ audioLanguage: "en",
+ subtitleLanguages: ["en"],
+ ad: false,
+ });
+ assert.equal(streamingVerdict(info, "en"), true);
+ assert.equal(streamingVerdict(info, "de"), false);
+});
+
+test("Netflix: a dub plays in its own language, whatever the original was", () => {
+ const info = readNetflix({ ...netflixEpisode, audioTrack: { bcp47: "ja", displayName: "Japanese" } });
+ assert.equal(streamingVerdict(info, "ja"), true);
+ assert.equal(streamingVerdict(info, "en"), false);
+});
+
+test("Netflix: the lead-in ad before the title, and the ad label, are ads", () => {
+ // LingoFlix saw getSegmentTime() stay 0 while getCurrentTime() ran through a 7007 ms lead-in
+ const leadIn = readNetflix({ ...netflixEpisode, currentTime: 3500, segmentTime: 0 });
+ assert.equal(leadIn.ad, true);
+ // During an ad the verdict is not taken from the tracks, which may be the ad's
+ assert.equal(streamingVerdict(leadIn, "en"), null);
+ assert.equal(readNetflix({ ...netflixEpisode, adLabel: true }).ad, true);
+ // The very start of the title, before anything played, is not an ad
+ assert.equal(readNetflix({ ...netflixEpisode, currentTime: 0, segmentTime: 0 }).ad, false);
+});
+
+test("Netflix: subtitles turned off or forced narrative are not shown subtitles", () => {
+ const off = readNetflix({ ...netflixEpisode, timedTextTrack: { bcp47: "en", isNoneTrack: true } });
+ assert.deepEqual(off.subtitleLanguages, []);
+ const forced = readNetflix({
+ ...netflixEpisode,
+ timedTextTrack: { bcp47: "en", isNoneTrack: false, isForcedNarrative: true },
+ });
+ assert.deepEqual(forced.subtitleLanguages, []);
+});
+
+test("Netflix: a film is its title; without metadata the player's title line names it", () => {
+ assert.equal(readNetflix({ ...netflixEpisode, video: { title: "Roma", type: "movie" } }).title, "Roma");
+ assert.equal(readNetflix({ ...netflixEpisode, video: null, domTitle: " Roma " }).title, "Roma");
+});
+
+test("Netflix: no player session, or no audio said yet, decides nothing", () => {
+ assert.equal(readNetflix({ movieId: null }), null);
+ const loading = readNetflix({ ...netflixEpisode, audioTrack: null });
+ assert.equal(loading.audioLanguage, null);
+ assert.equal(streamingVerdict(loading, "en"), null);
+});
+
+// Prime Video: the shape tvctl (yusukeshib/tvctl, plugins/primevideo/chrome.js) reads from the player's context;
+// the values are made up, in that shape.
+const primeEpisode = {
+ titleInfo: { titleId: "amzn1.dv.gti.0000aaaa-bbbb-cccc-dddd-eeeeffff0000", title: "The Boys" },
+ audio: { id: "de_dialog_0", language: "de-de" },
+ subtitle: { id: "off", language: null },
+ adPlaying: false,
+ adTimer: false,
+ domTitle: "The Boys",
+ domSubtitle: "Season 1, Ep. 1 The Name of the Game",
+};
+
+test("Prime Video: the active audio stream decides, and the episode line names it", () => {
+ const info = readPrimeVideo(primeEpisode);
+ assert.equal(info.title, "The Boys - Season 1, Ep. 1 The Name of the Game");
+ assert.equal(info.audioLanguage, "de-de");
+ assert.deepEqual(info.subtitleLanguages, []);
+ assert.equal(
+ info.key,
+ "https://www.primevideo.com/detail/amzn1.dv.gti.0000aaaa-bbbb-cccc-dddd-eeeeffff0000",
+ );
+ assert.equal(streamingVerdict(info, "de"), true);
+});
+
+test("Prime Video: a stream with no language says it in its id", () => {
+ const info = readPrimeVideo({ ...primeEpisode, audio: { id: "ja-jp_dialog_0" } });
+ assert.equal(info.audioLanguage, "ja-jp");
+ assert.equal(streamingVerdict(info, "ja"), true);
+});
+
+test("Prime Video: an ad, said by the ad player or by its timer, is an ad", () => {
+ assert.equal(readPrimeVideo({ ...primeEpisode, adPlaying: true }).ad, true);
+ assert.equal(readPrimeVideo({ ...primeEpisode, adTimer: true }).ad, true);
+ assert.equal(readPrimeVideo({ titleInfo: null }), null);
+});
+
+// Disney+: the audio track as Theater Mode Everywhere (TomaszJanusz/Theater-Mode-Everywhere,
+// src/providers/disney/audio-main.ts) reads it, the ad badge as jp343 reads it; values made up in that shape.
+const disneyFilm = {
+ path: "/play/3c2a6e2e-7f61-4f1e-9c8c-2b8f1a0d9e11",
+ title: "Encanto | Disney+",
+ audio: { language: "es-419" },
+ adBadge: null,
+};
+
+test("Disney+: the selected audio track decides, and the page title names it", () => {
+ const info = readDisneyPlus(disneyFilm);
+ assert.deepEqual(info, {
+ key: "https://www.disneyplus.com/play/3c2a6e2e-7f61-4f1e-9c8c-2b8f1a0d9e11",
+ title: "Encanto",
+ audioLanguage: "es-419",
+ subtitleLanguages: [],
+ ad: false,
+ });
+ assert.equal(streamingVerdict(info, "es"), true);
+});
+
+test("Disney+: the ad badge with time left is an ad; a page that is not the player is nothing", () => {
+ assert.equal(readDisneyPlus({ ...disneyFilm, adBadge: "Ad 0:15" }).ad, true);
+ assert.equal(readDisneyPlus({ ...disneyFilm, adBadge: "" }).ad, false);
+ assert.equal(readDisneyPlus({ ...disneyFilm, path: "/browse/entity-123" }), null);
+ assert.equal(readDisneyPlus({ ...disneyFilm, title: "Disney+" }).title, "");
+});
+
+test("an unknown site, missing data or a player that changed shape reads as nothing", () => {
+ assert.equal(readStreaming("hulu", { movieId: 1 }), null);
+ assert.equal(readStreaming("netflix", null), null);
+ assert.equal(
+ readStreaming("netflix", {
+ movieId: 1,
+ get audioTrack() {
+ throw new Error("gone");
+ },
+ }),
+ null,
+ );
+ assert.equal(readStreaming("toString", {}), null);
+});
+
+test("a title is kept as a web item, named after the site when the player gives no name", () => {
+ const info = readCrunchyroll(crunchyrollOriginal);
+ const item = streamingItem(info, "Crunchyroll");
+ assert.ok(isWebItemId(item.id));
+ assert.equal(item.url, "https://www.crunchyroll.com/watch/GR3VWXP96");
+ // The same episode from another page address is the same item
+ assert.equal(streamingItem(readCrunchyroll(crunchyrollOriginal), "Crunchyroll").id, item.id);
+ assert.notEqual(streamingItem(readCrunchyroll(crunchyrollDub), "Crunchyroll").id, item.id);
+ assert.equal(streamingItem({ ...info, title: "" }, "Crunchyroll").title, "Crunchyroll");
+});