Add explanatory comments across codebase

This commit is contained in:
Stefano Zini
2026-11-04 14:23:18 +01:00
parent b8aa5548a2
commit 82b72b6c28
34 changed files with 934 additions and 0 deletions
+54
View File
@@ -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();