Files
teams-whisper/app/ext/popup.js
T

72 lines
4.2 KiB
JavaScript

// Popup controller: Start/Stop button, status line and transcript view; talks to the offscreen recorder.
// Shorthand for getElementById.
const byId = elementId => document.getElementById(elementId);
// Forward a command to the offscreen document (addressed with to:"off").
const sendToOffscreen = message => chrome.runtime.sendMessage({ to: "off", ...message });
// Format milliseconds as m:ss.
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 recorderState = { state: "idle" }, lastError = "";
// Refresh the button and status line from state recorderState.
function render() {
const goButton = byId("go"), statusLine = byId("st");
document.body.dataset.state = recorderState.state;
// Pipeline busy after stop: no new start until it finishes.
goButton.disabled = recorderState.state === "transcribing";
// Button doubles as Stop while recording.
goButton.textContent = recorderState.state === "recording" ? "Stop + transcribe" : "Start";
// Status line text per recorder state.
statusLine.textContent = {
idle: "idle - open a Teams tab and press Start",
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)",
}[recorderState.state];
// Show the transcript/result text when there is one.
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()) recorderState = (await sendToOffscreen({ cmd: "status" })) || recorderState; else recorderState = lastError ? { state: "error", text: lastError } : { state: "idle" };
render();
}
// Start / Stop click handler.
byId("go").onclick = async () => {
// Stop path: first ask teams.js to stop its scanners.
if (recorderState.state === "recording") {
// Tell the Teams content script to stop (errors ignored: the tab may be gone).
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(resolve => setTimeout(resolve, 300));
await sendToOffscreen({ cmd: "stop" }); return poll();
}
// Clear the previous error before a new attempt.
lastError = "";
try {
// Tab the user is looking at when the button is pressed.
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
// The popup itself is an extension page; it can't be recorded.
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 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 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(activeTab.id, { cmd: "cap-start" }).catch(() => {});
// Any failure is shown in the status line.
} catch (error) { lastError = String(error); chrome.runtime.sendMessage({ to: "bg", state: "error" }); }
render(); poll();
};
// Keep status fresh while the popup is open.
poll(); setInterval(poll, 1000);