options.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import { DEFAULT_SELECTORS } from './parser.js';
  2. const $ = id => document.getElementById(id);
  3. const automationFields = { intervalSeconds: 'automation-interval', dwellSeconds: 'automation-dwell', maxChats: 'automation-max', listScrollPasses: 'automation-list-scroll', historyScrollPasses: 'automation-history-scroll' };
  4. const automationSelectors = { chatItemSelector: 'chat-item-selector', chatListSelector: 'chat-list-selector', messageListSelector: 'message-list-selector' };
  5. const phases = { disabled: '已停止', idle: '等待页面', discovering: '发现聊天', opening: '打开聊天', settling: '等待加载', capturing: '保存消息', history: '加载历史', waiting: '等待下一轮', paused: '已暂停', error: '遇到错误' };
  6. const feedback = (text, error = false) => { $('feedback').textContent = text; $('feedback').className = error ? 'error' : 'success'; };
  7. function showConnection(connection, enabled, prefix = '') {
  8. const description = !connection.teamsTabCount ? '尚未打开 Teams 页面。请打开 Teams 并进入聊天或日历。' : connection.error ? connection.error : `页面脚本已就绪(${connection.readyTabCount}/${connection.teamsTabCount}),${enabled ? '正在等待页面心跳。' : '采集已暂停。'}`;
  9. $('connection').textContent = description;
  10. if (prefix) feedback(`${prefix}${description}`, Boolean(connection.error));
  11. }
  12. async function call(type, extra = {}) {
  13. const result = await chrome.runtime.sendMessage({ type, ...extra });
  14. if (!result?.ok) throw new Error(result?.error || '扩展未响应,请重新打开设置页');
  15. return result;
  16. }
  17. function draft() {
  18. return { accountId: $('account').value, token: $('token').value, port: Number($('port').value), enabled: $('enabled').checked, includeActivity: $('activity').checked, selectors: Object.fromEntries(['message', 'event', 'activity'].map(kind => [kind, $(`${kind}-selector`).value])), automation: { enabled: $('automation-enabled').checked, ...Object.fromEntries(Object.entries(automationFields).map(([key, id]) => [key, Number($(id).value)])), ...Object.fromEntries(Object.entries(automationSelectors).map(([key, id]) => [key, $(id).value])) } };
  19. }
  20. function showAutomation(config, status = {}) {
  21. const state = status.automation || {};
  22. const next = state.nextRunAt ? `;下轮 ${new Date(state.nextRunAt).toLocaleTimeString('zh-CN')}` : '';
  23. $('automation-status').textContent = `${config.automation.enabled ? phases[state.phase] || '准备启动' : '自动采集已停止'} · 本轮 ${state.visited || 0}/${state.discovered || 0} 个聊天${next}${state.coverage ? `。${state.coverage}` : ''}${state.error ? `。${state.error}` : ''}`;
  24. $('automation-status').className = state.error ? 'error' : '';
  25. }
  26. function validateDraft(config) {
  27. validateSelectors(config.selectors);
  28. validateSelectors(Object.fromEntries(Object.keys(automationSelectors).map(key => [key, config.automation[key]])));
  29. }
  30. function validateSelectors(selectors) {
  31. for (const [kind, selector] of Object.entries(selectors)) {
  32. if (!selector.trim()) continue;
  33. try { document.querySelector(selector); }
  34. catch { throw new Error(`${kind} CSS 选择器无效,请修正或留空`); }
  35. }
  36. }
  37. async function action(run) {
  38. try { await run(); } catch (error) { feedback(error.message, true); }
  39. }
  40. $('settings-form').addEventListener('submit', event => {
  41. event.preventDefault();
  42. void action(async () => {
  43. const config = draft(); validateDraft(config);
  44. const result = await call('SAVE_CONFIG', { config });
  45. const { connection } = result;
  46. $('automation-enabled').checked = result.config.automation.enabled;
  47. showAutomation(result.config, result.status);
  48. showConnection(connection, config.enabled, config.enabled ? '设置已保存并开启。' : '设置已保存。');
  49. });
  50. });
  51. $('ping').addEventListener('click', () => { void action(async () => { feedback('正在连接…'); await call('PING', { config: draft() }); feedback('连接成功。请保存设置以应用配置。'); }); });
  52. $('login').addEventListener('click', () => { void action(() => call('OPEN_LOGIN')); });
  53. $('dashboard').addEventListener('click', () => { void action(() => call('OPEN_DASHBOARD')); });
  54. $('automation-start').addEventListener('click', () => { void action(async () => {
  55. const config = draft(); validateDraft(config);
  56. config.automation.enabled = false;
  57. await call('SAVE_CONFIG', { config });
  58. const result = await call('START_AUTOMATION');
  59. $('automation-enabled').checked = result.config.automation.enabled;
  60. showAutomation(result.config, result.status);
  61. feedback('自动采集已启动。请保持新建的采集标签和本地服务运行。');
  62. }); });
  63. $('automation-stop').addEventListener('click', () => { void action(async () => {
  64. const result = await call('STOP_AUTOMATION');
  65. $('automation-enabled').checked = false;
  66. showAutomation(result.config, result.status);
  67. feedback('自动采集已停止;采集标签和待发队列保留,重新启动后继续。');
  68. }); });
  69. $('preview-chats').addEventListener('click', () => { void action(async () => {
  70. const config = draft(); validateDraft(config);
  71. $('chat-preview-result').textContent = '正在检查聊天列表…';
  72. const result = await call('PREVIEW_CHATS', { config });
  73. const preview = result.preview || result;
  74. $('chat-preview-result').textContent = JSON.stringify({ 能发现的聊天数: preview.count, 聊天名称样本: preview.labels, 提示: preview.errors }, null, 2);
  75. }); });
  76. $('reconnect').addEventListener('click', () => { void action(async () => {
  77. $('connection').textContent = '正在重新连接 Teams 页面…';
  78. const { config, connection } = await call('RECONNECT');
  79. showConnection(connection, config.enabled, '重新连接检查完成。');
  80. }); });
  81. $('preview').addEventListener('click', () => {
  82. void action(async () => {
  83. $('preview-result').textContent = '正在读取 Teams 页面…';
  84. const config = draft(); validateSelectors(config.selectors);
  85. const result = await call('PREVIEW', { config });
  86. $('preview-result').textContent = JSON.stringify({ 可见条目: result.counts, 提示: result.errors, 页面: result.page, 样本: result.sample }, null, 2);
  87. });
  88. });
  89. void action(async () => {
  90. const { config, connection, status } = await call('GET_STATE');
  91. $('account').value = config.accountId; $('token').value = config.token; $('port').value = config.port;
  92. $('enabled').checked = config.enabled; $('activity').checked = config.includeActivity;
  93. $('automation-enabled').checked = config.automation.enabled;
  94. for (const [key, id] of Object.entries(automationFields)) $(id).value = config.automation[key];
  95. for (const [key, id] of Object.entries(automationSelectors)) $(id).value = config.automation[key];
  96. for (const kind of ['message', 'event', 'activity']) { $(`${kind}-selector`).value = config.selectors[kind] || ''; $(`${kind}-selector`).placeholder = DEFAULT_SELECTORS[kind]; }
  97. showConnection(connection, config.enabled);
  98. showAutomation(config, status);
  99. if (status.lastError || status.runtimeError || status.diagnosticsError) feedback(status.runtimeError || status.lastError || status.diagnosticsError, true);
  100. });
  101. chrome.storage.onChanged.addListener((changes, area) => {
  102. if (area !== 'local') return;
  103. if (changes.config?.newValue) $('automation-enabled').checked = changes.config.newValue.automation?.enabled === true;
  104. if (changes.status) showAutomation({ automation: { enabled: $('automation-enabled').checked } }, changes.status.newValue || {});
  105. });