background-runtime.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import { DEFAULT_CONFIG, validateConfig, publicConfig, isTeamsUrl, isTrustedPage, isTeamsSender, validateCapture, deliverWithRetry } from './config.js';
  2. export function createBackgroundRuntime({ chrome, fetch, sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)) }) {
  3. const ready = chrome.storage.local.setAccessLevel({ accessLevel: 'TRUSTED_CONTEXTS' });
  4. const busyTabs = new Set();
  5. const connectingTabs = new Map();
  6. let statusTail = Promise.resolve();
  7. let automationTail = Promise.resolve();
  8. let owner = null;
  9. const session = chrome.storage.session;
  10. const ownerReady = ready.then(async () => {
  11. if (session) {
  12. await session.setAccessLevel?.({ accessLevel: 'TRUSTED_CONTEXTS' });
  13. const saved = (await session.get('automationOwner')).automationOwner;
  14. if (Number.isInteger(saved?.tabId) && typeof saved.accountId === 'string') owner = { tabId: saved.tabId, accountId: saved.accountId, assigned: saved.assigned === true };
  15. }
  16. });
  17. let started = false;
  18. // Serialize tab creation and configuration writes across popup/startup/tab events.
  19. function automate(task) {
  20. const result = automationTail.catch(() => {}).then(async () => { await ownerReady; return task(); });
  21. automationTail = result;
  22. return result;
  23. }
  24. async function saveOwner(next) {
  25. owner = next;
  26. if (session) await session.set({ automationOwner: next });
  27. }
  28. function cleanAutomation(input = {}) {
  29. if (!input || typeof input !== 'object' || Array.isArray(input)) input = {};
  30. const text = (value, max) => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, max) : '';
  31. const count = value => typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.min(1000000, Math.floor(value))) : 0;
  32. const phases = ['disabled', 'idle', 'discovering', 'opening', 'settling', 'capturing', 'history', 'waiting', 'paused', 'error'];
  33. const timestamp = typeof input.nextRunAt === 'number' || typeof input.nextRunAt === 'string' ? new Date(input.nextRunAt).getTime() : NaN;
  34. return { running: input.running === true, phase: phases.includes(input.phase) ? input.phase : 'idle', visited: count(input.visited), discovered: count(input.discovered), pass: count(input.pass), nextRunAt: Number.isFinite(timestamp) && timestamp > 0 ? new Date(timestamp).toISOString() : null, error: text(input.error, 300), coverage: text(input.coverage, 500) };
  35. }
  36. async function notifyOwner(tabId = owner?.tabId) {
  37. if (!Number.isInteger(tabId)) return;
  38. let timeout;
  39. try {
  40. await Promise.race([chrome.tabs.sendMessage(tabId, { type: 'CONFIG_CHANGED' }, { frameId: 0 }), new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error('页面响应超时')), 3000); })]);
  41. } catch { /* Navigation may have already removed the old content script. */ }
  42. finally { clearTimeout(timeout); }
  43. }
  44. async function stopAutomation(settings, reason = '', { forget = false } = {}) {
  45. const tabId = owner?.tabId;
  46. await saveOwner(forget ? null : owner ? { ...owner, assigned: false } : null);
  47. const next = { ...settings, automation: { ...settings.automation, enabled: false } };
  48. await chrome.storage.local.set({ config: next });
  49. await updateStatus({ automation: cleanAutomation({ phase: 'disabled', coverage: reason }) });
  50. await notifyOwner(tabId);
  51. return next;
  52. }
  53. async function reconcileAutomation(settings, { allowCreate = false } = {}) {
  54. if (!settings.enabled || !settings.automation.enabled) {
  55. if (owner?.assigned || settings.automation.enabled) return stopAutomation(settings, '自动采集已停止');
  56. return settings;
  57. }
  58. if (owner && owner.accountId !== settings.accountId) return stopAutomation(settings, '账号标签已改变,请重新启动自动采集', { forget: true });
  59. if (owner) {
  60. let current;
  61. try { current = await chrome.tabs.get(owner.tabId); } catch { /* User closed the tab during service worker suspension. */ }
  62. if (!current || !isTeamsUrl(current.url)) return stopAutomation(settings, '采集标签已关闭或离开 Teams,请重新启动自动采集', { forget: true });
  63. if (!owner.assigned) await saveOwner({ ...owner, assigned: true });
  64. return settings;
  65. }
  66. if (!allowCreate) return settings;
  67. const tabs = await teamsTabs();
  68. const origin = tabs.length ? new URL(tabs[0].url).origin : 'https://teams.cloud.microsoft';
  69. const created = await chrome.tabs.create({ url: `${origin}/`, active: false });
  70. if (!Number.isInteger(created?.id)) throw new Error('无法创建自动采集标签页');
  71. await saveOwner({ tabId: created.id, accountId: settings.accountId, assigned: true });
  72. await updateStatus({ automation: cleanAutomation({ phase: 'idle', coverage: '采集标签已创建,等待 Teams 加载' }) });
  73. return settings;
  74. }
  75. async function isAssigned(sender, settings) {
  76. await ownerReady;
  77. if (!settings.enabled || !settings.automation.enabled || !owner?.assigned || owner.tabId !== sender.tab.id || owner.accountId !== settings.accountId) return false;
  78. const candidate = owner;
  79. try { const tab = await chrome.tabs.get(candidate.tabId); return owner === candidate && owner.assigned && isTeamsUrl(tab.url); } catch { return false; }
  80. }
  81. async function config() {
  82. await ready;
  83. const saved = (await chrome.storage.local.get('config')).config;
  84. return validateConfig({ ...DEFAULT_CONFIG, ...saved });
  85. }
  86. function updateStatus(patch, delivered = 0, guard = () => true) {
  87. statusTail = statusTail.catch(() => {}).then(async () => {
  88. const current = (await chrome.storage.local.get('status')).status || {};
  89. if (!guard()) return false;
  90. await chrome.storage.local.set({ status: { ...current, ...patch, delivered: (current.delivered || 0) + delivered } });
  91. return true;
  92. });
  93. return statusTail;
  94. }
  95. async function post(path, settings, body) {
  96. let response;
  97. try {
  98. response = await fetch(`http://127.0.0.1:${settings.port}${path}`, {
  99. method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${settings.token}` },
  100. body, signal: AbortSignal.timeout(5000), redirect: 'error', credentials: 'omit', cache: 'no-store'
  101. });
  102. } catch { throw new Error('无法连接本地服务,请确认服务已启动、端口正确且浏览器允许本地连接'); }
  103. if (!response.ok) {
  104. const error = new Error(response.status === 401 || response.status === 403 ? '配对验证失败,请从本地控制台复制最新令牌' : `本地服务返回 HTTP ${response.status}`);
  105. error.permanent = response.status >= 400 && response.status < 500 && response.status !== 429;
  106. throw error;
  107. }
  108. return { ok: true };
  109. }
  110. async function teamsTabs() {
  111. return (await chrome.tabs.query({})).filter(tab => Number.isInteger(tab.id) && isTeamsUrl(tab.url));
  112. }
  113. async function publishStatus(settings) {
  114. if (!settings.accountId || !settings.token) return;
  115. const status = (await chrome.storage.local.get('status')).status || {};
  116. const body = JSON.stringify({ accountId: settings.accountId, version: chrome.runtime.getManifest().version, enabled: settings.enabled,
  117. teamsTabCount: status.teamsTabCount || 0, readyTabCount: status.readyTabCount || 0,
  118. error: status.connectionError || status.runtimeError || status.lastError || '',
  119. ...(status.automation ? { automation: cleanAutomation(status.automation) } : {}) });
  120. try {
  121. await post('/api/extension/status', settings, body);
  122. await updateStatus({ diagnosticsError: '' });
  123. } catch (error) {
  124. await updateStatus({ diagnosticsError: error.message });
  125. }
  126. }
  127. async function probe(tabId) {
  128. const response = await chrome.tabs.sendMessage(tabId, { type: 'PROBE' }, { frameId: 0 });
  129. if (!response?.ok || response.ready !== true) throw new Error(response?.error || '采集脚本尚未就绪');
  130. return response;
  131. }
  132. function ensureContentScript(tab) {
  133. if (!Number.isInteger(tab.id) || !isTeamsUrl(tab.url)) return Promise.reject(new Error('只允许连接 Teams 顶层页面'));
  134. if (connectingTabs.has(tab.id)) return connectingTabs.get(tab.id);
  135. const task = (async () => {
  136. try { return await probe(tab.id); } catch { /* Existing tabs may predate extension installation. */ }
  137. const current = await chrome.tabs.get(tab.id);
  138. if (!isTeamsUrl(current.url)) throw new Error('Teams 标签页已跳转,请重新打开 Teams');
  139. try {
  140. await chrome.scripting.executeScript({ target: { tabId: tab.id, frameIds: [0] }, files: ['content.js'] });
  141. } catch { throw new Error('无法启动 Teams 采集脚本,请检查扩展的网站访问权限,然后重新连接页面'); }
  142. let failure;
  143. for (let attempt = 0; attempt < 3; attempt++) {
  144. try { return await probe(tab.id); }
  145. catch (error) { failure = error; if (attempt < 2) await sleep(100); }
  146. }
  147. throw new Error(failure?.message || '采集脚本启动失败,请刷新 Teams 页面后重新连接');
  148. })().finally(() => connectingTabs.delete(tab.id));
  149. connectingTabs.set(tab.id, task);
  150. return task;
  151. }
  152. async function connectPages(settings, { notifyConfig = false, resumeAutomation = false } = {}) {
  153. const tabs = await teamsTabs();
  154. const results = await Promise.allSettled(tabs.map(async tab => {
  155. const pageState = await ensureContentScript(tab);
  156. if (notifyConfig) {
  157. const reply = await chrome.tabs.sendMessage(tab.id, { type: 'CONFIG_CHANGED', ...(resumeAutomation ? { resumeAutomation: true } : {}) }, { frameId: 0 });
  158. if (!reply?.ok) throw new Error(reply?.error || 'Teams 页面未能应用采集配置');
  159. }
  160. return pageState;
  161. }));
  162. const errors = results.flatMap((result, index) => result.status === 'rejected' ? [`Teams 标签 ${tabs[index].id}:${String(result.reason?.message || '连接失败').slice(0, 240)}`] : []);
  163. const connection = { teamsTabCount: tabs.length, readyTabCount: results.filter(result => result.status === 'fulfilled').length, error: errors.join(';').slice(0, 500) };
  164. const pageReports = results.filter(result => result.status === 'fulfilled' && typeof result.value?.runtimeError === 'string');
  165. const runtimeErrors = pageReports.map(result => result.value.runtimeError).filter(Boolean);
  166. const currentStatus = (await chrome.storage.local.get('status')).status || {};
  167. const recovered = !connection.error && notifyConfig && ['SAVE_CONFIG', 'GET_CONFIG', 'GET_STATE', 'RECONNECT'].includes(currentStatus.lastErrorSource);
  168. await updateStatus({ teamsTabCount: connection.teamsTabCount, readyTabCount: connection.readyTabCount, connectionError: connection.error, connectionCheckedAt: new Date().toISOString(),
  169. ...(pageReports.length ? { runtimeError: runtimeErrors.join(';').slice(0, 300) } : {}),
  170. ...(recovered ? { lastError: '', lastErrorSource: '' } : {}),
  171. ...(!connection.readyTabCount ? { signedIn: null, view: 'unknown', visibleCounts: {}, pending: 0 } : {}) });
  172. await publishStatus(settings);
  173. return connection;
  174. }
  175. async function dispatchInternal(message, sender) {
  176. if (!message || typeof message.type !== 'string') throw new Error('消息格式无效');
  177. const trusted = isTrustedPage(sender, chrome.runtime.id, chrome.runtime.getURL(''));
  178. const teams = isTeamsSender(sender, chrome.runtime.id);
  179. if (!trusted && !teams) throw new Error('来源不受信任');
  180. if (message.type === 'SAVE_CONFIG' && trusted) {
  181. let next = validateConfig(message.config);
  182. next = await automate(async () => {
  183. const previous = await config();
  184. await chrome.storage.local.set({ config: next });
  185. if (next.accountId !== previous.accountId) {
  186. await chrome.storage.local.set({ status: {} });
  187. if (owner || previous.automation.enabled) return stopAutomation(next, '账号标签已改变,请重新启动自动采集', { forget: true });
  188. }
  189. return reconcileAutomation(next, { allowCreate: true });
  190. });
  191. const connection = await connectPages(next, { notifyConfig: true, resumeAutomation: true });
  192. return { ok: true, config: next, connection, status: (await chrome.storage.local.get('status')).status || {} };
  193. }
  194. const settings = await config();
  195. if (message.type === 'GET_CONFIG' && teams) {
  196. const assigned = await isAssigned(sender, settings);
  197. return { ok: true, config: { ...publicConfig(settings), automation: { ...settings.automation, assigned, collectorTab: owner?.tabId === sender.tab.id } } };
  198. }
  199. if (message.type === 'REPORT_AUTOMATION' && teams) {
  200. if (message.accountId !== settings.accountId || !await isAssigned(sender, settings)) throw new Error('仅指定采集标签页可以报告此账号的自动采集状态');
  201. const candidate = owner;
  202. const accepted = await updateStatus({ automation: cleanAutomation(message.status) }, 0, () => owner === candidate && candidate.assigned && candidate.accountId === message.accountId);
  203. if (!accepted) throw new Error('自动采集已停止或账号配置已变更');
  204. await publishStatus(settings);
  205. return { ok: true };
  206. }
  207. if (message.type === 'CAPTURE' && teams) {
  208. if (busyTabs.has(sender.tab.id)) throw new Error('上一批仍在发送,将自动重试');
  209. const json = validateCapture(message, settings);
  210. const sourceUrl = new URL(sender.url);
  211. if (message.page.url !== `${sourceUrl.origin}${sourceUrl.pathname}`) throw new Error('来源页面不匹配');
  212. busyTabs.add(sender.tab.id);
  213. try {
  214. await deliverWithRetry(() => post('/api/extension/events', settings, json), { sleep });
  215. await updateStatus({ lastSuccess: new Date().toISOString(), lastError: '', lastErrorSource: '', runtimeError: '', signedIn: typeof message.page.signedIn === 'boolean' ? message.page.signedIn : null, view: message.page.view, accountId: settings.accountId, lastBatch: message.records.length, tabId: sender.tab.id }, message.records.length);
  216. return { ok: true, accepted: message.records.length };
  217. } finally { busyTabs.delete(sender.tab.id); }
  218. }
  219. if (message.type === 'REPORT_STATUS' && teams) {
  220. await updateStatus({ runtimeError: typeof message.runtimeError === 'string' ? message.runtimeError.slice(0, 300) : '', parserErrors: (Array.isArray(message.errors) ? message.errors : []).slice(0, 5).map(item => String(item).slice(0, 200)), pending: Math.max(0, Math.min(Number(message.pending) || 0, 1000)), visibleCounts: message.counts, overflow: message.overflow === true });
  221. await publishStatus(settings);
  222. return { ok: true };
  223. }
  224. if (!trusted) throw new Error('此操作只允许从扩展设置页或弹窗执行');
  225. if (message.type === 'START_AUTOMATION' || message.type === 'STOP_AUTOMATION') {
  226. const next = await automate(async () => {
  227. const current = await config();
  228. if (message.type === 'STOP_AUTOMATION') return stopAutomation(current, '自动采集已停止');
  229. if (!current.enabled) throw new Error('请先保存配对设置并开启页面采集');
  230. const enabled = { ...current, automation: { ...current.automation, enabled: true } };
  231. await chrome.storage.local.set({ config: enabled });
  232. return reconcileAutomation(enabled, { allowCreate: true });
  233. });
  234. const connection = await connectPages(next, { notifyConfig: true, resumeAutomation: message.type === 'START_AUTOMATION' });
  235. return { ok: true, config: next, connection, status: (await chrome.storage.local.get('status')).status || {} };
  236. }
  237. if (message.type === 'GET_STATE' || message.type === 'RECONNECT') {
  238. const connection = await connectPages(settings, { notifyConfig: message.type === 'RECONNECT', resumeAutomation: message.type === 'RECONNECT' });
  239. await ownerReady;
  240. return { ok: true, config: settings, status: (await chrome.storage.local.get('status')).status || {}, automation: { tabId: owner?.tabId ?? null, assigned: Boolean(owner?.assigned && settings.enabled && settings.automation.enabled && owner.accountId === settings.accountId) }, ...connection, connection };
  241. }
  242. if (message.type === 'PING') {
  243. const draft = validateConfig(message.config || settings);
  244. if (!draft.token) throw new Error('请填写配对令牌');
  245. return post('/api/extension/ping', draft, JSON.stringify({ accountId: draft.accountId }));
  246. }
  247. if (message.type === 'OPEN_LOGIN') {
  248. await chrome.tabs.create({ url: 'https://teams.microsoft.com/v2/' });
  249. return { ok: true };
  250. }
  251. if (message.type === 'OPEN_DASHBOARD') {
  252. await chrome.tabs.create({ url: `http://127.0.0.1:${settings.port}/` });
  253. return { ok: true };
  254. }
  255. if (message.type === 'PREVIEW' || message.type === 'PREVIEW_CHATS') {
  256. const tabs = (await teamsTabs()).sort((a, b) => Number(b.active) - Number(a.active) || (b.lastAccessed || 0) - (a.lastAccessed || 0));
  257. if (!tabs.length) throw new Error('请先打开 Teams 网页并进入聊天或日历');
  258. const draft = validateConfig(message.config || settings);
  259. await connectPages(settings);
  260. await ownerReady;
  261. const target = message.type === 'PREVIEW_CHATS' ? tabs.find(tab => tab.id === owner?.tabId) || tabs[0] : tabs[0];
  262. await ensureContentScript(target);
  263. const result = await chrome.tabs.sendMessage(target.id, { type: message.type, config: publicConfig(draft) }, { frameId: 0 });
  264. if (!result?.ok) throw new Error(result?.error || '页面预览失败');
  265. return result;
  266. }
  267. throw new Error('不支持的操作');
  268. }
  269. async function dispatch(message, sender) {
  270. try { return await dispatchInternal(message, sender); }
  271. catch (error) {
  272. const trusted = isTrustedPage(sender || {}, chrome.runtime.id, chrome.runtime.getURL('')) || isTeamsSender(sender || {}, chrome.runtime.id);
  273. if (trusted) {
  274. await updateStatus({ lastError: String(error.message || '操作失败').slice(0, 300), lastErrorSource: message?.type || '', lastFailure: new Date().toISOString() });
  275. try { await publishStatus(await config()); } catch { /* Invalid saved configuration is returned to the caller. */ }
  276. }
  277. throw error;
  278. }
  279. }
  280. function start() {
  281. if (started) return;
  282. started = true;
  283. chrome.runtime.onMessage.addListener((message, sender, respond) => {
  284. dispatch(message, sender).then(respond).catch(error => respond({ ok: false, error: String(error.message || '操作失败').slice(0, 300) }));
  285. return true;
  286. });
  287. const reconnect = () => { void automate(async () => reconcileAutomation(await config(), { allowCreate: true })).then(settings => connectPages(settings, { notifyConfig: Boolean(owner?.assigned) })).catch(error => updateStatus({ lastError: String(error.message || '扩展初始化失败').slice(0, 300) })); };
  288. chrome.runtime.onInstalled.addListener(reconnect);
  289. chrome.runtime.onStartup?.addListener(reconnect);
  290. chrome.tabs.onRemoved?.addListener(tabId => { void automate(async () => {
  291. if (owner?.tabId === tabId) await stopAutomation(await config(), '采集标签已关闭,自动采集已停止', { forget: true });
  292. }).catch(() => {}); });
  293. chrome.tabs.onUpdated?.addListener((tabId, change) => { void automate(async () => {
  294. if (owner?.tabId !== tabId) return;
  295. if (change.url && !isTeamsUrl(change.url)) { await stopAutomation(await config(), '采集标签已离开 Teams,自动采集已停止', { forget: true }); return; }
  296. if (change.status === 'complete' && owner.assigned) await notifyOwner(tabId);
  297. }).catch(() => {}); });
  298. reconnect();
  299. }
  300. return { start, dispatch, ensureContentScript, connectPages };
  301. }