Apply ruff lint and rename cryptic identifiers to readable names

This commit is contained in:
Stefano Zini
2026-11-05 09:09:20 +01:00
parent 19de4654ff
commit ead33657c7
24 changed files with 4459 additions and 1856 deletions
+6 -6
View File
@@ -1,13 +1,13 @@
// Make Teams see Edge instead of Opera: rewrite UA + client-hint request headers.
// Edge UA built from the browser's own UA: the Opera OPR/ token is removed and an Edg/ token is added.
const ua = navigator.userAgent;
const userAgent = navigator.userAgent;
// Chrome major version taken from the UA; falls back to 130 if the UA has no Chrome token.
const v = (ua.match(/Chrome\/(\d+)/) || [])[1] || "130";
const edgeUA = ua.replace(/ OPR\/[\d.]+/, "") + ` Edg/${v}.0.0.0`;
const chromeMajor = (userAgent.match(/Chrome\/(\d+)/) || [])[1] || "130";
const edgeUA = userAgent.replace(/ OPR\/[\d.]+/, "") + ` Edg/${chromeMajor}.0.0.0`;
// Sec-CH-UA brand list matching the Edge UA; "Not_A Brand" is a GREASE placeholder brand.
const brands = `"Microsoft Edge";v="${v}", "Chromium";v="${v}", "Not_A Brand";v="24"`;
const brands = `"Microsoft Edge";v="${chromeMajor}", "Chromium";v="${chromeMajor}", "Not_A Brand";v="24"`;
// Helper: builds one declarativeNetRequest header operation.
const set = (header, value) => ({ header, operation: "set", value });
const headerSet = (header, value) => ({ header, operation: "set", value });
// Dynamic rules persist across service-worker restarts, so id 1 is replaced on every start.
chrome.declarativeNetRequest.updateDynamicRules({
@@ -19,7 +19,7 @@ chrome.declarativeNetRequest.updateDynamicRules({
// Rewrite the outgoing request headers.
action: {
type: "modifyHeaders",
requestHeaders: [set("User-Agent", edgeUA), set("Sec-CH-UA", brands)],
requestHeaders: [headerSet("User-Agent", edgeUA), headerSet("Sec-CH-UA", brands)],
},
condition: {
// Only Teams hosts: teams.microsoft.com and teams.cloud.microsoft.
+2 -2
View File
@@ -1,6 +1,6 @@
// Run in mic.html (a normal tab): asks for mic permission once so offscreen.js can use it later without a prompt.
navigator.mediaDevices.getUserMedia({ audio: true })
// Stop the probe tracks at once: only the permission grant was needed, not the audio.
.then(s => { s.getTracks().forEach(t => t.stop()); document.body.append(" granted."); })
.then(stream => { stream.getTracks().forEach(track => track.stop()); document.body.append(" granted."); })
// Show the outcome in the page (the error text if the user denied or the call failed).
.catch(e => document.body.append(" " + e));
.catch(error => document.body.append(" " + error));
+45 -45
View File
@@ -1,79 +1,79 @@
// Offscreen document: records the Teams tab (tabCapture) and uploads 10 s WebM chunks to the local server.
// Local server endpoint (server.py); must match start.js port 18765.
const API = "http://127.0.0.1:18765";
let rec, ctx, tab, mic, q = Promise.resolve(), name;
let recorder, audioContext, tabStream, micStream, uploadQueue = Promise.resolve(), recordingName;
// state: idle | recording | transcribing | done | error ; popup polls it
const S = { state: "idle", name: "", t0: 0, t1: 0, chunks: 0, mic: false, text: "" };
const recorderState = { state: "idle", name: "", t0: 0, t1: 0, chunks: 0, mic: false, text: "" };
// Messages from popup.js / teams.js are addressed with to:"off"; other messages are ignored.
chrome.runtime.onMessage.addListener((m, _s, send) => {
if (m.to !== "off") return;
if (m.cmd === "status") send(S);
// start is async: reply with ok, or with the error text (also stored in S for the popup).
if (m.cmd === "start") start(m.id, m.tabId).then(() => send({ ok: true }), e => { S.state = "error"; S.text = String(e); send({ err: String(e) }); });
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message.to !== "off") return;
if (message.cmd === "status") sendResponse(recorderState);
// start is async: reply with ok, or with the error text (also stored in recorderState for the popup).
if (message.cmd === "start") start(message.id, message.tabId).then(() => sendResponse({ ok: true }), error => { recorderState.state = "error"; recorderState.text = String(error); sendResponse({ err: String(error) }); });
// teams.js events are re-based to seconds since recording start; events from before start are dropped.
if (m.cmd === "events") { for (const e of m.events) if (e.ts >= S.t0) S.ev.push({ t: (e.ts - S.t0) / 1000, kind: e.kind, who_key: e.who_key, who: e.who, text: e.text }); }
if (message.cmd === "events") { for (const event of message.events) if (event.ts >= recorderState.t0) recorderState.ev.push({ t: (event.ts - recorderState.t0) / 1000, kind: event.kind, who_key: event.who_key, who: event.who, text: event.text }); }
// Stop: MediaRecorder.onstop handles the finalisation.
if (m.cmd === "stop") { rec.stop(); send({ ok: true }); }
if (message.cmd === "stop") { recorder.stop(); sendResponse({ ok: true }); }
// Keep the message channel open for the async replies above.
return true;
});
// Send buffered Teams events to the server; on failure count it so the popup can warn.
async function flushEv() {
if (!S.ev.length) return;
const b = S.ev.splice(0);
if (!recorderState.ev.length) return;
const batch = recorderState.ev.splice(0);
try {
const r = await fetch(`${API}/events?name=${name}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) });
if (!r.ok) throw 0;
S.evSent += b.length;
} catch { S.failed++; }
const response = await fetch(`${API}/events?name=${recordingName}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(batch) });
if (!response.ok) throw 0;
recorderState.evSent += batch.length;
} catch { recorderState.failed++; }
}
// Start recording the given tab (id from tabCapture.getMediaStreamId).
async function start(id, tabId) {
name = "teams_" + new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
async function start(streamId, tabId) {
recordingName = "teams_" + new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
// Tab capture stream: the chromeMediaSource constraint is the only way to get tab audio/video in an extension.
const src = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: id } };
tab = await navigator.mediaDevices.getUserMedia({ audio: src, video: src });
const captureConstraint = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: streamId } };
tabStream = await navigator.mediaDevices.getUserMedia({ audio: captureConstraint, video: captureConstraint });
// Mixer: tab audio + optional mic are mixed into one destination track.
ctx = new AudioContext();
const dest = ctx.createMediaStreamDestination();
const t = ctx.createMediaStreamSource(tab);
t.connect(dest);
t.connect(ctx.destination); // tabCapture mutes the tab; play it back
audioContext = new AudioContext();
const dest = audioContext.createMediaStreamDestination();
const tabSource = audioContext.createMediaStreamSource(tabStream);
tabSource.connect(dest);
tabSource.connect(audioContext.destination); // tabCapture mutes the tab; play it back
// Mic is optional: needs the one-time grant from mic.html; without it the recording is tab-only.
try { // needs one-time grant via mic.html
mic = await navigator.mediaDevices.getUserMedia({ audio: true });
ctx.createMediaStreamSource(mic).connect(dest);
} catch { mic = null; }
micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
audioContext.createMediaStreamSource(micStream).connect(dest);
} catch { micStream = null; }
// Output stream: tab video + mixed audio.
const out = new MediaStream([...tab.getVideoTracks(), ...dest.stream.getAudioTracks()]);
const outStream = new MediaStream([...tabStream.getVideoTracks(), ...dest.stream.getAudioTracks()]);
// VP8 video + Opus audio at 1 Mbps video, a format the server's ffmpeg pipeline accepts.
rec = new MediaRecorder(out, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 1e6 });
// Each 10 s chunk is uploaded in order through the q promise chain.
rec.ondataavailable = e => {
// Chain the upload on q so chunks reach the server in order; count success or failure, then flush events.
q = q.then(() => fetch(`${API}/chunk?name=${name}`, { method: "POST", body: e.data })).then(() => S.chunks++, () => S.failed++).then(flushEv);
recorder = new MediaRecorder(outStream, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 1e6 });
// Each 10 s chunk is uploaded in order through the uploadQueue promise chain.
recorder.ondataavailable = event => {
// Chain the upload on uploadQueue so chunks reach the server in order; count success or failure, then flush events.
uploadQueue = uploadQueue.then(() => fetch(`${API}/chunk?name=${recordingName}`, { method: "POST", body: event.data })).then(() => recorderState.chunks++, () => recorderState.failed++).then(flushEv);
};
// Stop path: wait for uploads, release the capture, then ask the server to transcribe.
rec.onstop = async () => {
S.state = "transcribing"; S.t1 = Date.now();
recorder.onstop = async () => {
recorderState.state = "transcribing"; recorderState.t1 = Date.now();
try {
// Wait for all queued chunk uploads to finish before asking for transcription.
await q;
await uploadQueue;
await flushEv();
// Release tab/mic capture devices and the audio context.
[tab, mic].forEach(s => s && s.getTracks().forEach(t => t.stop()));
ctx.close();
[tabStream, micStream].forEach(stream => stream && stream.getTracks().forEach(track => track.stop()));
audioContext.close();
// Server concatenates the uploaded chunks and runs the transcription pipeline; body is the result text.
const r = await fetch(`${API}/stop?name=${name}`, { method: "POST" });
S.text = await r.text(); S.state = r.ok ? "done" : "error";
} catch (e) { S.text = "server down or failed: " + e; S.state = "error"; }
rec = null;
const response = await fetch(`${API}/stop?name=${recordingName}`, { method: "POST" });
recorderState.text = await response.text(); recorderState.state = response.ok ? "done" : "error";
} catch (error) { recorderState.text = "server down or failed: " + error; recorderState.state = "error"; }
recorder = null;
};
// Reset per-session state and record the start time; events are kept in S.ev until sent.
Object.assign(S, { state: "recording", name, t0: Date.now(), chunks: 0, failed: 0, mic: !!mic, text: "", ev: [], evSent: 0, tabId });
// Reset per-session state and record the start time; events are kept in recorderState.ev until sent.
Object.assign(recorderState, { state: "recording", name: recordingName, t0: Date.now(), chunks: 0, failed: 0, mic: !!micStream, text: "", ev: [], evSent: 0, tabId });
// 10 s timeslice: MediaRecorder emits a chunk every 10 s.
rec.start(10000);
recorder.start(10000);
}
+26 -26
View File
@@ -1,67 +1,67 @@
// Popup controller: Start/Stop button, status line and transcript view; talks to the offscreen recorder.
// Shorthand for getElementById.
const $ = id => document.getElementById(id);
const byId = elementId => document.getElementById(elementId);
// Forward a command to the offscreen document (addressed with to:"off").
const off = msg => chrome.runtime.sendMessage({ to: "off", ...msg });
const sendToOffscreen = message => chrome.runtime.sendMessage({ to: "off", ...message });
// Format milliseconds as m:ss.
const mmss = ms => { const s = Math.floor(ms / 1000); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; };
const formatElapsed = milliseconds => { const totalSeconds = Math.floor(milliseconds / 1000); return `${Math.floor(totalSeconds / 60)}:${String(totalSeconds % 60).padStart(2, "0")}`; };
// Last error shown when there is no offscreen document to report it.
let S = { state: "idle" }, lastErr = "";
let recorderState = { state: "idle" }, lastError = "";
// Refresh the button and status line from state S.
// Refresh the button and status line from state recorderState.
function render() {
const go = $("go"), st = $("st");
const goButton = byId("go"), statusLine = byId("st");
// Pipeline busy after stop: no new start until it finishes.
go.disabled = S.state === "transcribing";
goButton.disabled = recorderState.state === "transcribing";
// Button doubles as Stop while recording.
go.textContent = S.state === "recording" ? "Stop + transcribe" : "Start";
goButton.textContent = recorderState.state === "recording" ? "Stop + transcribe" : "Start";
// Status line text per recorder state.
st.textContent = {
statusLine.textContent = {
idle: "idle - open a Teams tab and press Start",
recording: `REC ${mmss(Date.now() - S.t0)} | ${S.chunks} chunks uploaded${S.failed ? ` | ${S.failed} FAILED (server down?)` : ""} | mic ${S.mic ? "on" : "OFF (grant it)"} | eventi call: ${S.evSent || 0}`,
recording: `REC ${formatElapsed(Date.now() - recorderState.t0)} | ${recorderState.chunks} chunks uploaded${recorderState.failed ? ` | ${recorderState.failed} FAILED (server down?)` : ""} | mic ${recorderState.mic ? "on" : "OFF (grant it)"} | eventi call: ${recorderState.evSent || 0}`,
transcribing: `invio alla pipeline...`,
done: `inviato alla pipeline — stato e report su http://127.0.0.1:18765/`,
error: "ERROR (see below)",
}[S.state];
}[recorderState.state];
// Show the transcript/result text when there is one.
if (S.text) $("txt").textContent = S.text;
if (recorderState.text) byId("txt").textContent = recorderState.text;
}
// Poll the recorder state every second.
async function poll() {
// Offscreen doc exists: ask it for its state. Otherwise show the last error, or idle.
if (await chrome.offscreen.hasDocument()) S = (await off({ cmd: "status" })) || S; else S = lastErr ? { state: "error", text: lastErr } : { state: "idle" };
if (await chrome.offscreen.hasDocument()) recorderState = (await sendToOffscreen({ cmd: "status" })) || recorderState; else recorderState = lastError ? { state: "error", text: lastError } : { state: "idle" };
render();
}
// Start / Stop click handler.
$("go").onclick = async () => {
byId("go").onclick = async () => {
// Stop path: first ask teams.js to stop its scanners.
if (S.state === "recording") {
if (recorderState.state === "recording") {
// Tell the Teams content script to stop (errors ignored: the tab may be gone).
if (S.tabId != null) await chrome.tabs.sendMessage(S.tabId, { cmd: "cap-stop" }).catch(() => {});
if (recorderState.tabId != null) await chrome.tabs.sendMessage(recorderState.tabId, { cmd: "cap-stop" }).catch(() => {});
// Give teams.js's final event batch time to reach the offscreen doc before the recorder stops.
await new Promise(r => setTimeout(r, 300));
await off({ cmd: "stop" }); return poll();
await new Promise(resolve => setTimeout(resolve, 300));
await sendToOffscreen({ cmd: "stop" }); return poll();
}
// Clear the previous error before a new attempt.
lastErr = "";
lastError = "";
try {
// Tab the user is looking at when the button is pressed.
const [t] = await chrome.tabs.query({ active: true, currentWindow: true });
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
// The popup itself is an extension page; it can't be recorded.
if (t.url?.startsWith("chrome-extension:")) throw new Error("This is the extension's own page. Switch to the Teams tab, then click the icon.");
if (activeTab.url?.startsWith("chrome-extension:")) throw new Error("This is the extension's own page. Switch to the Teams tab, then click the icon.");
// Stream id that the offscreen document later passes to getUserMedia.
const id = await chrome.tabCapture.getMediaStreamId({ targetTabId: t.id });
const streamId = await chrome.tabCapture.getMediaStreamId({ targetTabId: activeTab.id });
// Create the offscreen document once; it stays alive while recording.
if (!(await chrome.offscreen.hasDocument()))
await chrome.offscreen.createDocument({ url: "offscreen.html", reasons: ["USER_MEDIA"], justification: "record tab" });
const r = await off({ cmd: "start", id, tabId: t.id });
if (r?.err) throw new Error(r.err);
const response = await sendToOffscreen({ cmd: "start", id: streamId, tabId: activeTab.id });
if (response?.err) throw new Error(response.err);
// Tell teams.js to start its scanners; ignored if the content script is not on this tab.
chrome.tabs.sendMessage(t.id, { cmd: "cap-start" }).catch(() => {});
chrome.tabs.sendMessage(activeTab.id, { cmd: "cap-start" }).catch(() => {});
// Any failure is shown in the status line.
} catch (e) { lastErr = String(e); }
} catch (error) { lastError = String(error); }
render(); poll();
};
+21 -21
View File
@@ -1,44 +1,44 @@
// MAIN world, document_start: navigator.* reports Edge instead of Opera.
(() => {
// Original UA string from the page (Opera).
const ua = navigator.userAgent;
const originalUA = navigator.userAgent;
// Only patch Opera; other browsers are left as-is.
if (!/OPR\//.test(ua)) return;
if (!/OPR\//.test(originalUA)) return;
// Chrome major version, same logic as background.js.
const v = (ua.match(/Chrome\/(\d+)/) || [])[1] || "130";
const chromeMajor = (originalUA.match(/Chrome\/(\d+)/) || [])[1] || "130";
// Same UA rewrite as background.js: drop OPR/, add Edg/.
const edgeUA = ua.replace(/ OPR\/[\d.]+/, "") + ` Edg/${v}.0.0.0`;
const edgeUA = originalUA.replace(/ OPR\/[\d.]+/, "") + ` Edg/${chromeMajor}.0.0.0`;
// Replace any Opera brand entry with Microsoft Edge, keeping its version.
const fix = (b) => b.map((x) => (/opera/i.test(x.brand) ? { brand: "Microsoft Edge", version: x.version } : x));
const fixBrands = brandList => brandList.map(entry => (/opera/i.test(entry.brand) ? { brand: "Microsoft Edge", version: entry.version } : entry));
// Getter-only property definer; configurable so it can be redefined.
const def = (o, k, g) => Object.defineProperty(o, k, { get: g, configurable: true });
const defineGetter = (object, key, getter) => Object.defineProperty(object, key, { get: getter, configurable: true });
// Override on Navigator.prototype so page scripts reading navigator.userAgent see Edge.
def(Navigator.prototype, "userAgent", () => edgeUA);
defineGetter(Navigator.prototype, "userAgent", () => edgeUA);
// appVersion is the UA without the leading "Mozilla/".
def(Navigator.prototype, "appVersion", () => edgeUA.replace(/^Mozilla\//, ""));
defineGetter(Navigator.prototype, "appVersion", () => edgeUA.replace(/^Mozilla\//, ""));
// userAgentData (Client Hints) exists only in Chromium-based browsers.
const d = navigator.userAgentData;
const uaData = navigator.userAgentData;
// Older builds without UA-CH: nothing more to patch.
if (!d) return;
if (!uaData) return;
// Brand list with Opera replaced by Edge.
const brands = fix(d.brands);
const brands = fixBrands(uaData.brands);
// Keep the original function bound to the real object.
const hev = d.getHighEntropyValues.bind(d);
const originalHighEntropy = uaData.getHighEntropyValues.bind(uaData);
// Replacement userAgentData object exposing the same fields as the original.
const patched = {
brands,
mobile: d.mobile,
platform: d.platform,
mobile: uaData.mobile,
platform: uaData.platform,
// High-entropy values also carry brands and fullVersionList: patch them too.
getHighEntropyValues: async (h) => {
const r = await hev(h);
if (r.brands) r.brands = fix(r.brands);
if (r.fullVersionList) r.fullVersionList = fix(r.fullVersionList);
return r;
getHighEntropyValues: async hints => {
const result = await originalHighEntropy(hints);
if (result.brands) result.brands = fixBrands(result.brands);
if (result.fullVersionList) result.fullVersionList = fixBrands(result.fullVersionList);
return result;
},
// toJSON is used when the object is serialised; must match the patched fields.
toJSON: () => ({ brands, mobile: d.mobile, platform: d.platform }),
toJSON: () => ({ brands, mobile: uaData.mobile, platform: uaData.platform }),
};
// Installed on the prototype, same as userAgent above.
def(Navigator.prototype, "userAgentData", () => patched);
defineGetter(Navigator.prototype, "userAgentData", () => patched);
})();
+32 -32
View File
@@ -28,26 +28,26 @@ let buf = [], timers = [], seenCap = new WeakMap(), capAuthor = "", seenChat = n
const norm = raw => {
raw = (raw || "").trim();
// Matches "Last, First" with an optional "(...)" suffix; anything else is returned trimmed.
const m = raw.match(/^([^,]+),\s*([^(]+?)\s*(\(.*)?$/);
if (!m) return raw;
const match = raw.match(/^([^,]+),\s*([^(]+?)\s*(\(.*)?$/);
if (!match) return raw;
// Reorder to "First Last" and title-case words that are fully uppercase.
return `${m[2]} ${m[1]}`.split(/\s+/).map(w => (w.length > 1 && w === w.toUpperCase() ? w[0] + w.slice(1).toLowerCase() : w)).join(" ");
return `${match[2]} ${match[1]}`.split(/\s+/).map(word => (word.length > 1 && word === word.toUpperCase() ? word[0] + word.slice(1).toLowerCase() : word)).join(" ");
};
// Walk up from an element to the participant tile (the ancestor containing a name tag).
const tileOf = el => { while (el && !el.querySelector(SEL.nametag)) el = el.parentElement; return el; };
const tileOf = element => { while (element && !element.querySelector(SEL.nametag)) element = element.parentElement; return element; };
// Stable participant key: the nearest ancestor data-tid containing "@" (an id), else the name text.
const keyOf = tile => {
for (let e = tile; e; e = e.parentElement) if ((e.dataset?.tid || "").includes("@")) return e.dataset.tid;
for (let node = tile; node; node = node.parentElement) if ((node.dataset?.tid || "").includes("@")) return node.dataset.tid;
return tile.querySelector(SEL.nametag)?.textContent.trim() || "";
};
// Display name from a tile's name tag.
const nameOf = tile => norm(tile.querySelector(SEL.nametag)?.textContent);
// Name of the local user, read from the self-video tile.
const selfName = () => { const s = document.querySelector(SEL.self); return s ? nameOf(s) : ""; };
const selfName = () => { const selfTile = document.querySelector(SEL.self); return selfTile ? nameOf(selfTile) : ""; };
// Queue an event with a wall-clock timestamp; sent later by send().
const emit = (kind, who_key = "", who = "", text = "") => buf.push({ ts: Date.now(), kind, who_key, who, text });
// Wrap timer callbacks so one exception does not kill the interval.
const guard = f => () => { try { f(); } catch (e) { console.error("[teams-whisper]", e); } };
const guard = callback => () => { try { callback(); } catch (error) { console.error("[teams-whisper]", error); } };
// Send queued events to the offscreen document; errors ignored (the recorder may be closed).
const send = () => { if (buf.length) chrome.runtime.sendMessage({ to: "off", cmd: "events", events: buf.splice(0) }).catch(() => { }); };
// All participant tiles currently in the DOM.
@@ -68,18 +68,18 @@ function present() {
// Dedupe by key (a participant can have more than one tile).
const seen = new Map();
// The self tile's name comes from the self-video element.
for (const t of tiles()) seen.set(keyOf(t), { key: keyOf(t), who: t.closest(SEL.self) ? selfName() : nameOf(t) });
for (const tile of tiles()) seen.set(keyOf(tile), { key: keyOf(tile), who: tile.closest(SEL.self) ? selfName() : nameOf(tile) });
// Roster snapshot payload.
emit("present", "", "", JSON.stringify([...seen.values()]));
}
// Emit one "active" event for each participant whose speaking outline is on.
function active() {
// Speaking outlines in the DOM.
for (const el of document.querySelectorAll(SEL.speaking)) {
const t = tileOf(el); if (!t) continue;
for (const element of document.querySelectorAll(SEL.speaking)) {
const tile = tileOf(element); if (!tile) continue;
// The local user speaking is recorded under the key "self".
if (t.closest(SEL.self) || t.matches(SEL.self)) emit("active", "self", selfName());
else emit("active", keyOf(t), nameOf(t));
if (tile.closest(SEL.self) || tile.matches(SEL.self)) emit("active", "self", selfName());
else emit("active", keyOf(tile), nameOf(tile));
}
}
// Screen share: detect the sharer from the banner aria-label and emit start/stop on change.
@@ -88,10 +88,10 @@ function share() {
const names = tiles().map(nameOf);
let cur = "";
// Scan all aria-labels for the share banner.
for (const el of document.querySelectorAll("[aria-label]")) {
const m = el.getAttribute("aria-label").match(SEL.shareAria);
for (const element of document.querySelectorAll("[aria-label]")) {
const match = element.getAttribute("aria-label").match(SEL.shareAria);
// Prefer a roster name the banner text starts with (labels can be truncated); else use the raw text.
if (m) { cur = names.find(n => n && m[2].startsWith(n)) || m[2]; break; }
if (match) { cur = names.find(name => name && match[2].startsWith(name)) || match[2]; break; }
}
// No change since last check.
if (cur === lastShare) return;
@@ -102,33 +102,33 @@ function share() {
}
// Captions, chat and raised hands, each emitted once.
function messages() {
if (SEL.caption) for (const el of document.querySelectorAll(SEL.caption)) {
if (SEL.caption) for (const element of document.querySelectorAll(SEL.caption)) {
// Author row sets the speaker for the text rows that follow it.
if (el.getAttribute("data-tid") === "author") { capAuthor = norm(el.textContent); continue; }
if (element.getAttribute("data-tid") === "author") { capAuthor = norm(element.textContent); continue; }
// caption text grows while spoken: emit once it was unchanged for a full tick
// Caption text of this row.
const text = el.textContent.trim(), s = seenCap.get(el) || {};
const text = element.textContent.trim(), seenState = seenCap.get(element) || {};
// Already emitted this row.
if (s.done) continue;
if (seenState.done) continue;
// Unchanged since last tick: treat as final and emit once.
if (text && s.text === text) { s.done = true; emit("caption", "", capAuthor, text); }
s.text = text; seenCap.set(el, s);
if (text && seenState.text === text) { seenState.done = true; emit("caption", "", capAuthor, text); }
seenState.text = text; seenCap.set(element, seenState);
}
// Chat messages (inactive while SEL.chatMsg is null); each element is counted once.
if (SEL.chatMsg) for (const el of document.querySelectorAll(SEL.chatMsg)) {
if (seenChat.has(el)) continue; seenChat.add(el);
const text = el.querySelector(SEL.chatText)?.textContent.trim();
if (text) emit("chat", "", norm(el.querySelector(SEL.chatAuthor)?.textContent), text);
if (SEL.chatMsg) for (const element of document.querySelectorAll(SEL.chatMsg)) {
if (seenChat.has(element)) continue; seenChat.add(element);
const text = element.querySelector(SEL.chatText)?.textContent.trim();
if (text) emit("chat", "", norm(element.querySelector(SEL.chatAuthor)?.textContent), text);
}
// Hand raises (inactive while SEL.hand is null); emit only new raises.
if (SEL.hand) {
// Hands raised this tick.
const now = new Set();
for (const el of document.querySelectorAll(SEL.hand)) {
const t = tileOf(el); if (!t) continue;
const k = keyOf(t); now.add(k);
for (const element of document.querySelectorAll(SEL.hand)) {
const tile = tileOf(element); if (!tile) continue;
const participantKey = keyOf(tile); now.add(participantKey);
// New raise since the last tick.
if (!raised.has(k)) emit("hand", k, nameOf(t));
if (!raised.has(participantKey)) emit("hand", participantKey, nameOf(tile));
}
// Keep only hands still up.
raised = now;
@@ -160,7 +160,7 @@ function start() {
}
// Start/stop commands sent by popup.js directly to this tab.
chrome.runtime.onMessage.addListener(m => {
if (m.cmd === "cap-start") start();
if (m.cmd === "cap-stop") stop();
chrome.runtime.onMessage.addListener(message => {
if (message.cmd === "cap-start") start();
if (message.cmd === "cap-stop") stop();
});