-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
235 lines (190 loc) · 5.73 KB
/
Copy pathbackground.js
File metadata and controls
235 lines (190 loc) · 5.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"use strict";
const OFFSCREEN_DOCUMENT_PATH = "offscreen.html";
let latestVoiceTabId = null;
let audioRunning = false;
const DEFAULT_BACKEND_URL = "http://127.0.0.1:8787";
async function safeStorageSet(values) {
try {
await chrome.storage.local.set(values);
} catch (err) {
// Storage can fail because of quota or transient extension-context issues.
}
}
async function getActiveVoiceTab() {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tab = tabs?.[0];
if (!tab?.id || !tab?.url?.startsWith("https://voice.google.com/")) {
throw new Error("Open https://voice.google.com/ and keep that tab active first.");
}
latestVoiceTabId = tab.id;
return tab;
}
async function ensureOffscreenDocument() {
const offscreenUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH);
if (chrome.runtime.getContexts) {
const existingContexts = await chrome.runtime.getContexts({
contextTypes: ["OFFSCREEN_DOCUMENT"],
documentUrls: [offscreenUrl]
});
if (existingContexts.length > 0) return;
}
await chrome.offscreen.createDocument({
url: OFFSCREEN_DOCUMENT_PATH,
reasons: ["USER_MEDIA"],
justification: "Analyze Google Voice tab audio locally without recording or saving audio."
});
}
async function startTabAudioAnalysis() {
const tab = await getActiveVoiceTab();
await ensureOffscreenDocument();
const streamId = await chrome.tabCapture.getMediaStreamId({
targetTabId: tab.id
});
const started = await chrome.runtime.sendMessage({
target: "offscreen",
type: "START_TAB_AUDIO",
streamId,
tabId: tab.id
});
if (!started?.ok) {
throw new Error(started?.error || "Offscreen audio analysis failed to start.");
}
audioRunning = true;
await safeStorageSet({
gvDetectorAudioRunning: true,
gvDetectorLastError: null
});
await sendToContent(tab.id, {
type: "GV_AUDIO_CONTROL",
status: "started"
});
return { ok: true, tabId: tab.id };
}
async function stopTabAudioAnalysis() {
await chrome.runtime.sendMessage({
target: "offscreen",
type: "STOP_TAB_AUDIO"
}).catch(() => {});
audioRunning = false;
await safeStorageSet({
gvDetectorAudioRunning: false
});
if (latestVoiceTabId) {
await sendToContent(latestVoiceTabId, {
type: "GV_AUDIO_CONTROL",
status: "stopped"
}).catch(() => {});
}
return { ok: true };
}
async function sendToContent(tabId, message) {
if (!tabId) return;
try {
await chrome.tabs.sendMessage(tabId, message);
} catch (err) {
// The content script may not be ready or the tab may have navigated.
}
}
async function getBackendUrl() {
const data = await chrome.storage.local.get(["gvDetectorSettings"]);
return data.gvDetectorSettings?.backendUrl || DEFAULT_BACKEND_URL;
}
async function checkBackendHealth() {
const backendUrl = (await getBackendUrl()).replace(/\/$/, "");
try {
const response = await fetch(`${backendUrl}/health`, { cache: "no-store" });
const health = await response.json();
return {
ok: response.ok,
backendUrl,
health,
status: response.status
};
} catch (err) {
return {
ok: false,
backendUrl,
error: err?.message || String(err)
};
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
(async () => {
try {
if (message?.type === "START_AUDIO_FROM_POPUP" || message?.type === "START_AUDIO_FROM_OVERLAY") {
sendResponse(await startTabAudioAnalysis());
return;
}
if (message?.type === "STOP_AUDIO_FROM_POPUP" || message?.type === "STOP_AUDIO_FROM_OVERLAY") {
sendResponse(await stopTabAudioAnalysis());
return;
}
if (message?.type === "GET_STATUS") {
const storage = await chrome.storage.local.get([
"gvDetectorAudioRunning",
"gvDetectorLatestState",
"gvDetectorLatestAudio",
"gvDetectorLastError"
]);
sendResponse({
ok: true,
audioRunning,
storage
});
return;
}
if (message?.type === "CHECK_BACKEND_HEALTH") {
sendResponse(await checkBackendHealth());
return;
}
if (message?.target === "background" && message?.type === "AUDIO_STATE_UPDATE") {
const payload = {
type: "GV_AUDIO_STATE_UPDATE",
audio: message.audio,
ts: Date.now()
};
if (latestVoiceTabId) {
await sendToContent(latestVoiceTabId, payload);
}
await safeStorageSet({
gvDetectorLatestAudio: payload
});
sendResponse({ ok: true });
return;
}
if (message?.target === "background" && message?.type === "BACKEND_AMD_UPDATE") {
const payload = {
type: "GV_BACKEND_AMD_UPDATE",
backend: message.backend,
ts: Date.now()
};
if (latestVoiceTabId) {
await sendToContent(latestVoiceTabId, payload);
}
await safeStorageSet({
gvDetectorLatestBackend: payload
});
sendResponse({ ok: true });
return;
}
sendResponse({ ok: false, error: "Unknown message type." });
} catch (err) {
const error = err?.message || String(err);
await safeStorageSet({ gvDetectorLastError: error });
sendResponse({ ok: false, error });
}
})();
return true;
});
chrome.tabCapture?.onStatusChanged?.addListener(async (info) => {
if (info.status !== "stopped" && info.status !== "error") return;
audioRunning = false;
await safeStorageSet({ gvDetectorAudioRunning: false });
if (latestVoiceTabId) {
await sendToContent(latestVoiceTabId, {
type: "GV_AUDIO_CONTROL",
status: "stopped",
captureInfo: info
});
}
});