| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321 |
- import { DEFAULT_CONFIG, validateConfig, publicConfig, isTeamsUrl, isTrustedPage, isTeamsSender, validateCapture, deliverWithRetry } from './config.js';
- export function createBackgroundRuntime({ chrome, fetch, sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)) }) {
- const ready = chrome.storage.local.setAccessLevel({ accessLevel: 'TRUSTED_CONTEXTS' });
- const busyTabs = new Set();
- const connectingTabs = new Map();
- let statusTail = Promise.resolve();
- let automationTail = Promise.resolve();
- let owner = null;
- const session = chrome.storage.session;
- const ownerReady = ready.then(async () => {
- if (session) {
- await session.setAccessLevel?.({ accessLevel: 'TRUSTED_CONTEXTS' });
- const saved = (await session.get('automationOwner')).automationOwner;
- if (Number.isInteger(saved?.tabId) && typeof saved.accountId === 'string') owner = { tabId: saved.tabId, accountId: saved.accountId, assigned: saved.assigned === true };
- }
- });
- let started = false;
- // Serialize tab creation and configuration writes across popup/startup/tab events.
- function automate(task) {
- const result = automationTail.catch(() => {}).then(async () => { await ownerReady; return task(); });
- automationTail = result;
- return result;
- }
- async function saveOwner(next) {
- owner = next;
- if (session) await session.set({ automationOwner: next });
- }
- function cleanAutomation(input = {}) {
- if (!input || typeof input !== 'object' || Array.isArray(input)) input = {};
- const text = (value, max) => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, max) : '';
- const count = value => typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.min(1000000, Math.floor(value))) : 0;
- const phases = ['disabled', 'idle', 'discovering', 'opening', 'settling', 'capturing', 'history', 'waiting', 'paused', 'error'];
- const timestamp = typeof input.nextRunAt === 'number' || typeof input.nextRunAt === 'string' ? new Date(input.nextRunAt).getTime() : NaN;
- 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) };
- }
- async function notifyOwner(tabId = owner?.tabId) {
- if (!Number.isInteger(tabId)) return;
- let timeout;
- try {
- await Promise.race([chrome.tabs.sendMessage(tabId, { type: 'CONFIG_CHANGED' }, { frameId: 0 }), new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error('页面响应超时')), 3000); })]);
- } catch { /* Navigation may have already removed the old content script. */ }
- finally { clearTimeout(timeout); }
- }
- async function stopAutomation(settings, reason = '', { forget = false } = {}) {
- const tabId = owner?.tabId;
- await saveOwner(forget ? null : owner ? { ...owner, assigned: false } : null);
- const next = { ...settings, automation: { ...settings.automation, enabled: false } };
- await chrome.storage.local.set({ config: next });
- await updateStatus({ automation: cleanAutomation({ phase: 'disabled', coverage: reason }) });
- await notifyOwner(tabId);
- return next;
- }
- async function reconcileAutomation(settings, { allowCreate = false } = {}) {
- if (!settings.enabled || !settings.automation.enabled) {
- if (owner?.assigned || settings.automation.enabled) return stopAutomation(settings, '自动采集已停止');
- return settings;
- }
- if (owner && owner.accountId !== settings.accountId) return stopAutomation(settings, '账号标签已改变,请重新启动自动采集', { forget: true });
- if (owner) {
- let current;
- try { current = await chrome.tabs.get(owner.tabId); } catch { /* User closed the tab during service worker suspension. */ }
- if (!current || !isTeamsUrl(current.url)) return stopAutomation(settings, '采集标签已关闭或离开 Teams,请重新启动自动采集', { forget: true });
- if (!owner.assigned) await saveOwner({ ...owner, assigned: true });
- return settings;
- }
- if (!allowCreate) return settings;
- const tabs = await teamsTabs();
- const origin = tabs.length ? new URL(tabs[0].url).origin : 'https://teams.cloud.microsoft';
- const created = await chrome.tabs.create({ url: `${origin}/`, active: false });
- if (!Number.isInteger(created?.id)) throw new Error('无法创建自动采集标签页');
- await saveOwner({ tabId: created.id, accountId: settings.accountId, assigned: true });
- await updateStatus({ automation: cleanAutomation({ phase: 'idle', coverage: '采集标签已创建,等待 Teams 加载' }) });
- return settings;
- }
- async function isAssigned(sender, settings) {
- await ownerReady;
- if (!settings.enabled || !settings.automation.enabled || !owner?.assigned || owner.tabId !== sender.tab.id || owner.accountId !== settings.accountId) return false;
- const candidate = owner;
- try { const tab = await chrome.tabs.get(candidate.tabId); return owner === candidate && owner.assigned && isTeamsUrl(tab.url); } catch { return false; }
- }
- async function config() {
- await ready;
- const saved = (await chrome.storage.local.get('config')).config;
- return validateConfig({ ...DEFAULT_CONFIG, ...saved });
- }
- function updateStatus(patch, delivered = 0, guard = () => true) {
- statusTail = statusTail.catch(() => {}).then(async () => {
- const current = (await chrome.storage.local.get('status')).status || {};
- if (!guard()) return false;
- await chrome.storage.local.set({ status: { ...current, ...patch, delivered: (current.delivered || 0) + delivered } });
- return true;
- });
- return statusTail;
- }
- async function post(path, settings, body) {
- let response;
- try {
- response = await fetch(`http://127.0.0.1:${settings.port}${path}`, {
- method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${settings.token}` },
- body, signal: AbortSignal.timeout(5000), redirect: 'error', credentials: 'omit', cache: 'no-store'
- });
- } catch { throw new Error('无法连接本地服务,请确认服务已启动、端口正确且浏览器允许本地连接'); }
- if (!response.ok) {
- const error = new Error(response.status === 401 || response.status === 403 ? '配对验证失败,请从本地控制台复制最新令牌' : `本地服务返回 HTTP ${response.status}`);
- error.permanent = response.status >= 400 && response.status < 500 && response.status !== 429;
- throw error;
- }
- return { ok: true };
- }
- async function teamsTabs() {
- return (await chrome.tabs.query({})).filter(tab => Number.isInteger(tab.id) && isTeamsUrl(tab.url));
- }
- async function publishStatus(settings) {
- if (!settings.accountId || !settings.token) return;
- const status = (await chrome.storage.local.get('status')).status || {};
- const body = JSON.stringify({ accountId: settings.accountId, version: chrome.runtime.getManifest().version, enabled: settings.enabled,
- teamsTabCount: status.teamsTabCount || 0, readyTabCount: status.readyTabCount || 0,
- error: status.connectionError || status.runtimeError || status.lastError || '',
- ...(status.automation ? { automation: cleanAutomation(status.automation) } : {}) });
- try {
- await post('/api/extension/status', settings, body);
- await updateStatus({ diagnosticsError: '' });
- } catch (error) {
- await updateStatus({ diagnosticsError: error.message });
- }
- }
- async function probe(tabId) {
- const response = await chrome.tabs.sendMessage(tabId, { type: 'PROBE' }, { frameId: 0 });
- if (!response?.ok || response.ready !== true) throw new Error(response?.error || '采集脚本尚未就绪');
- return response;
- }
- function ensureContentScript(tab) {
- if (!Number.isInteger(tab.id) || !isTeamsUrl(tab.url)) return Promise.reject(new Error('只允许连接 Teams 顶层页面'));
- if (connectingTabs.has(tab.id)) return connectingTabs.get(tab.id);
- const task = (async () => {
- try { return await probe(tab.id); } catch { /* Existing tabs may predate extension installation. */ }
- const current = await chrome.tabs.get(tab.id);
- if (!isTeamsUrl(current.url)) throw new Error('Teams 标签页已跳转,请重新打开 Teams');
- try {
- await chrome.scripting.executeScript({ target: { tabId: tab.id, frameIds: [0] }, files: ['content.js'] });
- } catch { throw new Error('无法启动 Teams 采集脚本,请检查扩展的网站访问权限,然后重新连接页面'); }
- let failure;
- for (let attempt = 0; attempt < 3; attempt++) {
- try { return await probe(tab.id); }
- catch (error) { failure = error; if (attempt < 2) await sleep(100); }
- }
- throw new Error(failure?.message || '采集脚本启动失败,请刷新 Teams 页面后重新连接');
- })().finally(() => connectingTabs.delete(tab.id));
- connectingTabs.set(tab.id, task);
- return task;
- }
- async function connectPages(settings, { notifyConfig = false, resumeAutomation = false } = {}) {
- const tabs = await teamsTabs();
- const results = await Promise.allSettled(tabs.map(async tab => {
- const pageState = await ensureContentScript(tab);
- if (notifyConfig) {
- const reply = await chrome.tabs.sendMessage(tab.id, { type: 'CONFIG_CHANGED', ...(resumeAutomation ? { resumeAutomation: true } : {}) }, { frameId: 0 });
- if (!reply?.ok) throw new Error(reply?.error || 'Teams 页面未能应用采集配置');
- }
- return pageState;
- }));
- const errors = results.flatMap((result, index) => result.status === 'rejected' ? [`Teams 标签 ${tabs[index].id}:${String(result.reason?.message || '连接失败').slice(0, 240)}`] : []);
- const connection = { teamsTabCount: tabs.length, readyTabCount: results.filter(result => result.status === 'fulfilled').length, error: errors.join(';').slice(0, 500) };
- const pageReports = results.filter(result => result.status === 'fulfilled' && typeof result.value?.runtimeError === 'string');
- const runtimeErrors = pageReports.map(result => result.value.runtimeError).filter(Boolean);
- const currentStatus = (await chrome.storage.local.get('status')).status || {};
- const recovered = !connection.error && notifyConfig && ['SAVE_CONFIG', 'GET_CONFIG', 'GET_STATE', 'RECONNECT'].includes(currentStatus.lastErrorSource);
- await updateStatus({ teamsTabCount: connection.teamsTabCount, readyTabCount: connection.readyTabCount, connectionError: connection.error, connectionCheckedAt: new Date().toISOString(),
- ...(pageReports.length ? { runtimeError: runtimeErrors.join(';').slice(0, 300) } : {}),
- ...(recovered ? { lastError: '', lastErrorSource: '' } : {}),
- ...(!connection.readyTabCount ? { signedIn: null, view: 'unknown', visibleCounts: {}, pending: 0 } : {}) });
- await publishStatus(settings);
- return connection;
- }
- async function dispatchInternal(message, sender) {
- if (!message || typeof message.type !== 'string') throw new Error('消息格式无效');
- const trusted = isTrustedPage(sender, chrome.runtime.id, chrome.runtime.getURL(''));
- const teams = isTeamsSender(sender, chrome.runtime.id);
- if (!trusted && !teams) throw new Error('来源不受信任');
- if (message.type === 'SAVE_CONFIG' && trusted) {
- let next = validateConfig(message.config);
- next = await automate(async () => {
- const previous = await config();
- await chrome.storage.local.set({ config: next });
- if (next.accountId !== previous.accountId) {
- await chrome.storage.local.set({ status: {} });
- if (owner || previous.automation.enabled) return stopAutomation(next, '账号标签已改变,请重新启动自动采集', { forget: true });
- }
- return reconcileAutomation(next, { allowCreate: true });
- });
- const connection = await connectPages(next, { notifyConfig: true, resumeAutomation: true });
- return { ok: true, config: next, connection, status: (await chrome.storage.local.get('status')).status || {} };
- }
- const settings = await config();
- if (message.type === 'GET_CONFIG' && teams) {
- const assigned = await isAssigned(sender, settings);
- return { ok: true, config: { ...publicConfig(settings), automation: { ...settings.automation, assigned, collectorTab: owner?.tabId === sender.tab.id } } };
- }
- if (message.type === 'REPORT_AUTOMATION' && teams) {
- if (message.accountId !== settings.accountId || !await isAssigned(sender, settings)) throw new Error('仅指定采集标签页可以报告此账号的自动采集状态');
- const candidate = owner;
- const accepted = await updateStatus({ automation: cleanAutomation(message.status) }, 0, () => owner === candidate && candidate.assigned && candidate.accountId === message.accountId);
- if (!accepted) throw new Error('自动采集已停止或账号配置已变更');
- await publishStatus(settings);
- return { ok: true };
- }
- if (message.type === 'CAPTURE' && teams) {
- if (busyTabs.has(sender.tab.id)) throw new Error('上一批仍在发送,将自动重试');
- const json = validateCapture(message, settings);
- const sourceUrl = new URL(sender.url);
- if (message.page.url !== `${sourceUrl.origin}${sourceUrl.pathname}`) throw new Error('来源页面不匹配');
- busyTabs.add(sender.tab.id);
- try {
- await deliverWithRetry(() => post('/api/extension/events', settings, json), { sleep });
- 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);
- return { ok: true, accepted: message.records.length };
- } finally { busyTabs.delete(sender.tab.id); }
- }
- if (message.type === 'REPORT_STATUS' && teams) {
- 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 });
- await publishStatus(settings);
- return { ok: true };
- }
- if (!trusted) throw new Error('此操作只允许从扩展设置页或弹窗执行');
- if (message.type === 'START_AUTOMATION' || message.type === 'STOP_AUTOMATION') {
- const next = await automate(async () => {
- const current = await config();
- if (message.type === 'STOP_AUTOMATION') return stopAutomation(current, '自动采集已停止');
- if (!current.enabled) throw new Error('请先保存配对设置并开启页面采集');
- const enabled = { ...current, automation: { ...current.automation, enabled: true } };
- await chrome.storage.local.set({ config: enabled });
- return reconcileAutomation(enabled, { allowCreate: true });
- });
- const connection = await connectPages(next, { notifyConfig: true, resumeAutomation: message.type === 'START_AUTOMATION' });
- return { ok: true, config: next, connection, status: (await chrome.storage.local.get('status')).status || {} };
- }
- if (message.type === 'GET_STATE' || message.type === 'RECONNECT') {
- const connection = await connectPages(settings, { notifyConfig: message.type === 'RECONNECT', resumeAutomation: message.type === 'RECONNECT' });
- await ownerReady;
- 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 };
- }
- if (message.type === 'PING') {
- const draft = validateConfig(message.config || settings);
- if (!draft.token) throw new Error('请填写配对令牌');
- return post('/api/extension/ping', draft, JSON.stringify({ accountId: draft.accountId }));
- }
- if (message.type === 'OPEN_LOGIN') {
- await chrome.tabs.create({ url: 'https://teams.microsoft.com/v2/' });
- return { ok: true };
- }
- if (message.type === 'OPEN_DASHBOARD') {
- await chrome.tabs.create({ url: `http://127.0.0.1:${settings.port}/` });
- return { ok: true };
- }
- if (message.type === 'PREVIEW' || message.type === 'PREVIEW_CHATS') {
- const tabs = (await teamsTabs()).sort((a, b) => Number(b.active) - Number(a.active) || (b.lastAccessed || 0) - (a.lastAccessed || 0));
- if (!tabs.length) throw new Error('请先打开 Teams 网页并进入聊天或日历');
- const draft = validateConfig(message.config || settings);
- await connectPages(settings);
- await ownerReady;
- const target = message.type === 'PREVIEW_CHATS' ? tabs.find(tab => tab.id === owner?.tabId) || tabs[0] : tabs[0];
- await ensureContentScript(target);
- const result = await chrome.tabs.sendMessage(target.id, { type: message.type, config: publicConfig(draft) }, { frameId: 0 });
- if (!result?.ok) throw new Error(result?.error || '页面预览失败');
- return result;
- }
- throw new Error('不支持的操作');
- }
- async function dispatch(message, sender) {
- try { return await dispatchInternal(message, sender); }
- catch (error) {
- const trusted = isTrustedPage(sender || {}, chrome.runtime.id, chrome.runtime.getURL('')) || isTeamsSender(sender || {}, chrome.runtime.id);
- if (trusted) {
- await updateStatus({ lastError: String(error.message || '操作失败').slice(0, 300), lastErrorSource: message?.type || '', lastFailure: new Date().toISOString() });
- try { await publishStatus(await config()); } catch { /* Invalid saved configuration is returned to the caller. */ }
- }
- throw error;
- }
- }
- function start() {
- if (started) return;
- started = true;
- chrome.runtime.onMessage.addListener((message, sender, respond) => {
- dispatch(message, sender).then(respond).catch(error => respond({ ok: false, error: String(error.message || '操作失败').slice(0, 300) }));
- return true;
- });
- 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) })); };
- chrome.runtime.onInstalled.addListener(reconnect);
- chrome.runtime.onStartup?.addListener(reconnect);
- chrome.tabs.onRemoved?.addListener(tabId => { void automate(async () => {
- if (owner?.tabId === tabId) await stopAutomation(await config(), '采集标签已关闭,自动采集已停止', { forget: true });
- }).catch(() => {}); });
- chrome.tabs.onUpdated?.addListener((tabId, change) => { void automate(async () => {
- if (owner?.tabId !== tabId) return;
- if (change.url && !isTeamsUrl(change.url)) { await stopAutomation(await config(), '采集标签已离开 Teams,自动采集已停止', { forget: true }); return; }
- if (change.status === 'complete' && owner.assigned) await notifyOwner(tabId);
- }).catch(() => {}); });
- reconnect();
- }
- return { start, dispatch, ensureContentScript, connectPages };
- }
|