Add explanatory comments across codebase
This commit is contained in:
@@ -1,21 +1,30 @@
|
||||
// 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;
|
||||
// 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`;
|
||||
// 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"`;
|
||||
// Helper: builds one declarativeNetRequest header operation.
|
||||
const set = (header, value) => ({ header, operation: "set", value });
|
||||
|
||||
// Dynamic rules persist across service-worker restarts, so id 1 is replaced on every start.
|
||||
chrome.declarativeNetRequest.updateDynamicRules({
|
||||
removeRuleIds: [1],
|
||||
addRules: [{
|
||||
id: 1,
|
||||
// Higher than default so this rule wins over other extensions' header rules.
|
||||
priority: 1,
|
||||
// Rewrite the outgoing request headers.
|
||||
action: {
|
||||
type: "modifyHeaders",
|
||||
requestHeaders: [set("User-Agent", edgeUA), set("Sec-CH-UA", brands)],
|
||||
},
|
||||
condition: {
|
||||
// Only Teams hosts: teams.microsoft.com and teams.cloud.microsoft.
|
||||
regexFilter: "^https://teams\\.(cloud\\.)?microsoft(\\.com)?/",
|
||||
// Every request type Teams uses, including websocket handshakes.
|
||||
resourceTypes: ["main_frame", "sub_frame", "xmlhttprequest", "script", "stylesheet", "image", "font", "websocket", "other"],
|
||||
},
|
||||
}],
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
<!-- Opened as a normal tab so Chrome can show the mic permission prompt; close it after granting. -->
|
||||
<body>Allow the microphone, then close this tab.
|
||||
<!-- mic.js requests the permission. -->
|
||||
<script src="mic.js"></script>
|
||||
|
||||
@@ -1,3 +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."); })
|
||||
// Show the outcome in the page (the error text if the user denied or the call failed).
|
||||
.catch(e => document.body.append(" " + e));
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
<!-- Hidden offscreen document created by popup.js to hold the recorder; not shown to the user. -->
|
||||
<script src="offscreen.js"></script>
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
// 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;
|
||||
// state: idle | recording | transcribing | done | error ; popup polls it
|
||||
const S = { 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) }); });
|
||||
// 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 }); }
|
||||
// Stop: MediaRecorder.onstop handles the finalisation.
|
||||
if (m.cmd === "stop") { rec.stop(); send({ 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);
|
||||
@@ -22,36 +30,50 @@ async function flushEv() {
|
||||
} catch { S.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);
|
||||
// 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 });
|
||||
// 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
|
||||
// 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; }
|
||||
// Output stream: tab video + mixed audio.
|
||||
const out = new MediaStream([...tab.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);
|
||||
};
|
||||
// Stop path: wait for uploads, release the capture, then ask the server to transcribe.
|
||||
rec.onstop = async () => {
|
||||
S.state = "transcribing"; S.t1 = Date.now();
|
||||
try {
|
||||
// Wait for all queued chunk uploads to finish before asking for transcription.
|
||||
await q;
|
||||
await flushEv();
|
||||
// Release tab/mic capture devices and the audio context.
|
||||
[tab, mic].forEach(s => s && s.getTracks().forEach(t => t.stop()));
|
||||
ctx.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;
|
||||
};
|
||||
// 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 });
|
||||
// 10 s timeslice: MediaRecorder emits a chunk every 10 s.
|
||||
rec.start(10000);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
<!-- Extension popup: Start/Stop button, mic-grant link, status line and transcript view. -->
|
||||
<body style="width:380px;font:13px sans-serif">
|
||||
<!-- mic.html opens in a new tab so the permission prompt can appear; needed once. -->
|
||||
<button id="go">Start</button> <a href="mic.html" target="_blank">grant mic (once)</a>
|
||||
<!-- Status line, filled by popup.js. -->
|
||||
<div id="st"></div>
|
||||
<!-- Transcript/result text returned by the recorder. -->
|
||||
<pre id="txt" style="white-space:pre-wrap;max-height:300px;overflow:auto"></pre>
|
||||
<!-- popup.js drives the UI. -->
|
||||
<script src="popup.js"></script>
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
// Popup controller: Start/Stop button, status line and transcript view; talks to the offscreen recorder.
|
||||
// Shorthand for getElementById.
|
||||
const $ = id => document.getElementById(id);
|
||||
// Forward a command to the offscreen document (addressed with to:"off").
|
||||
const off = msg => chrome.runtime.sendMessage({ to: "off", ...msg });
|
||||
// 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")}`; };
|
||||
// Last error shown when there is no offscreen document to report it.
|
||||
let S = { state: "idle" }, lastErr = "";
|
||||
|
||||
// Refresh the button and status line from state S.
|
||||
function render() {
|
||||
const go = $("go"), st = $("st");
|
||||
// Pipeline busy after stop: no new start until it finishes.
|
||||
go.disabled = S.state === "transcribing";
|
||||
// Button doubles as Stop while recording.
|
||||
go.textContent = S.state === "recording" ? "Stop + transcribe" : "Start";
|
||||
// Status line text per recorder state.
|
||||
st.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}`,
|
||||
@@ -14,33 +23,48 @@ function render() {
|
||||
done: `inviato alla pipeline — stato e report su http://127.0.0.1:18765/`,
|
||||
error: "ERROR (see below)",
|
||||
}[S.state];
|
||||
// Show the transcript/result text when there is one.
|
||||
if (S.text) $("txt").textContent = S.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" };
|
||||
render();
|
||||
}
|
||||
|
||||
// Start / Stop click handler.
|
||||
$("go").onclick = async () => {
|
||||
// Stop path: first ask teams.js to stop its scanners.
|
||||
if (S.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(() => {});
|
||||
// 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();
|
||||
}
|
||||
// Clear the previous error before a new attempt.
|
||||
lastErr = "";
|
||||
try {
|
||||
// Tab the user is looking at when the button is pressed.
|
||||
const [t] = 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.");
|
||||
// Stream id that the offscreen document later passes to getUserMedia.
|
||||
const id = await chrome.tabCapture.getMediaStreamId({ targetTabId: t.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);
|
||||
// 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(() => {});
|
||||
// Any failure is shown in the status line.
|
||||
} catch (e) { lastErr = String(e); }
|
||||
render(); poll();
|
||||
};
|
||||
|
||||
|
||||
// Keep status fresh while the popup is open.
|
||||
poll(); setInterval(poll, 1000);
|
||||
|
||||
@@ -1,28 +1,44 @@
|
||||
// MAIN world, document_start: navigator.* reports Edge instead of Opera.
|
||||
(() => {
|
||||
// Original UA string from the page (Opera).
|
||||
const ua = navigator.userAgent;
|
||||
// Only patch Opera; other browsers are left as-is.
|
||||
if (!/OPR\//.test(ua)) return;
|
||||
// Chrome major version, same logic as background.js.
|
||||
const v = (ua.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`;
|
||||
// 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));
|
||||
// Getter-only property definer; configurable so it can be redefined.
|
||||
const def = (o, k, g) => Object.defineProperty(o, k, { get: g, configurable: true });
|
||||
// Override on Navigator.prototype so page scripts reading navigator.userAgent see Edge.
|
||||
def(Navigator.prototype, "userAgent", () => edgeUA);
|
||||
// appVersion is the UA without the leading "Mozilla/".
|
||||
def(Navigator.prototype, "appVersion", () => edgeUA.replace(/^Mozilla\//, ""));
|
||||
// userAgentData (Client Hints) exists only in Chromium-based browsers.
|
||||
const d = navigator.userAgentData;
|
||||
// Older builds without UA-CH: nothing more to patch.
|
||||
if (!d) return;
|
||||
// Brand list with Opera replaced by Edge.
|
||||
const brands = fix(d.brands);
|
||||
// Keep the original function bound to the real object.
|
||||
const hev = d.getHighEntropyValues.bind(d);
|
||||
// Replacement userAgentData object exposing the same fields as the original.
|
||||
const patched = {
|
||||
brands,
|
||||
mobile: d.mobile,
|
||||
platform: d.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;
|
||||
},
|
||||
// toJSON is used when the object is serialised; must match the patched fields.
|
||||
toJSON: () => ({ brands, mobile: d.mobile, platform: d.platform }),
|
||||
};
|
||||
// Installed on the prototype, same as userAgent above.
|
||||
def(Navigator.prototype, "userAgentData", () => patched);
|
||||
})();
|
||||
|
||||
@@ -1,102 +1,155 @@
|
||||
// Content script on Teams web: logs active speaker, shares, captions, chat, hands, presence while recording.
|
||||
// Events go via the offscreen document (it has host_permissions for 127.0.0.1). Never clicks or types in the call.
|
||||
// DOM selectors for the Teams web client. The data-tid attributes are Teams' internal test ids and can change with Teams releases.
|
||||
const SEL = {
|
||||
// Call elapsed-time element.
|
||||
duration: '[data-tid="call-duration"]',
|
||||
// Name label inside each participant tile.
|
||||
nametag: '[data-tid="participant-info-nametag"]',
|
||||
// Participant info container.
|
||||
info: '[data-tid="participant-info"]',
|
||||
// Speaking outline: data-is-speaking="true" while the participant talks.
|
||||
speaking: '[data-tid="voice-level-stream-outline"][data-is-speaking="true"]',
|
||||
// The local user's own video tile.
|
||||
self: '[data-tid="myself-video"]',
|
||||
// Screen-share banner aria-label (English and Italian UI); group 2 is the sharer's name.
|
||||
shareAria: /^(Contenuto condiviso da|Content shared by) (.+)$/,
|
||||
caption: '[data-tid="author"],[data-tid="closed-caption-text"]', // DOM order; author only on first row of a speaker's run
|
||||
// Chat selectors not found yet (null): chat capture is disabled.
|
||||
chatMsg: null, chatAuthor: null, chatText: null, // discovery step
|
||||
// Raised-hand selector not found yet (null): hand capture is disabled.
|
||||
hand: null, // discovery step
|
||||
};
|
||||
|
||||
// State: buf = queued events; timers = intervals; seenCap = caption rows already emitted; capAuthor = last caption speaker; seenChat; lastShare = current sharer; raised = hands up; lastTitle = last title sent.
|
||||
let buf = [], timers = [], seenCap = new WeakMap(), capAuthor = "", seenChat = new WeakSet(), lastShare = "", raised = new Set(), lastTitle = null;
|
||||
|
||||
// Normalise a Teams display name: "LAST, First (Org)" -> "First Last"; ALL-CAPS words are title-cased.
|
||||
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;
|
||||
// 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(" ");
|
||||
};
|
||||
// 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; };
|
||||
// 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;
|
||||
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) : ""; };
|
||||
// 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); } };
|
||||
// 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.
|
||||
const tiles = () => [...document.querySelectorAll(SEL.nametag)].map(tileOf).filter(Boolean);
|
||||
|
||||
// Emit the meeting title and call elapsed time, but only when the title changes.
|
||||
function meta() {
|
||||
// Page title looks like "Meeting | Name | Microsoft Teams": drop the leading segment and the trailing suffix.
|
||||
const title = document.title.replace(/^[^|]*\|\s*/, "").replace(/\s*\|\s*Microsoft Teams$/, "");
|
||||
// Nothing new since last time.
|
||||
if (title === lastTitle) return;
|
||||
lastTitle = title;
|
||||
// Payload is JSON in the text field.
|
||||
emit("meta", "", "", JSON.stringify({ title, call_elapsed: document.querySelector(SEL.duration)?.textContent.trim() || "", url: location.href }));
|
||||
}
|
||||
// Roster snapshot: one entry per participant key.
|
||||
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) });
|
||||
// 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;
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
// Screen share: detect the sharer from the banner aria-label and emit start/stop on change.
|
||||
function share() {
|
||||
// Roster names to match the banner text against.
|
||||
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);
|
||||
// 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; }
|
||||
}
|
||||
// No change since last check.
|
||||
if (cur === lastShare) return;
|
||||
// Previous sharer stopped.
|
||||
if (lastShare) emit("share_stop", "", lastShare);
|
||||
if (cur) emit("share_start", "", cur);
|
||||
lastShare = cur;
|
||||
}
|
||||
// Captions, chat and raised hands, each emitted once.
|
||||
function messages() {
|
||||
if (SEL.caption) for (const el 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; }
|
||||
// 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) || {};
|
||||
// Already emitted this row.
|
||||
if (s.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);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
// 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);
|
||||
// New raise since the last tick.
|
||||
if (!raised.has(k)) emit("hand", k, nameOf(t));
|
||||
}
|
||||
// Keep only hands still up.
|
||||
raised = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Stop: clear timers, flush pending events, and close any open share.
|
||||
function stop() {
|
||||
timers.forEach(clearInterval); timers = [];
|
||||
send();
|
||||
if (lastShare) { emit("share_stop", "", lastShare); lastShare = ""; }
|
||||
send();
|
||||
}
|
||||
// Start a fresh recording: stop old timers, then reset per-recording state.
|
||||
function start() {
|
||||
stop();
|
||||
// Reset per-recording state.
|
||||
buf = []; seenCap = new WeakMap(); capAuthor = ""; seenChat = new WeakSet(); raised = new Set(); lastTitle = null; lastShare = "";
|
||||
// Emit the initial snapshot right away.
|
||||
meta(); present();
|
||||
// Periodic scans: speaker 500 ms, share and captions 1 s, roster 30 s, flush 5 s.
|
||||
timers = [
|
||||
setInterval(guard(() => { meta(); active(); }), 500),
|
||||
setInterval(guard(share), 1000),
|
||||
@@ -106,6 +159,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();
|
||||
|
||||
Reference in New Issue
Block a user