const $ = id => document.getElementById(id); const state = { token: '', kind: 'message', offset: 0, limit: 30, total: 0, loading: false, refreshPromise: null, rendered: '', accounts: '', graph: {}, network: {}, networkAvailable: false, networkPending: '', networkActionError: '', instances: null, instanceId: 'default', instanceSignature: '', instanceSettingsId: '', instanceDirty: false, instanceBusy: false, deletePreview: null, localAccounts: [], localBusy: false, localDeletePreview: null }; const sourceNames = { browser: '浏览器', graph: 'Graph', 'web-api': '网页 API', demo: '示例数据' }; const kindNames = { message: '聊天消息', chat: '聊天', event: '日历', activity: '活动' }; function notice(text, error = false) { $('notice').textContent = text; $('notice').hidden = !text; $('notice').classList.toggle('error', error); } async function api(url, body) { const res = await fetch(url, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Local-Token': state.token }, body: JSON.stringify(body) }); const localRecords = url.startsWith('/api/local-records/'); let data; try { data = await res.json(); } catch { throw new Error(localRecords ? '当前服务未返回有效的本地记录管理结果,请重启至 0.5.1 或更新版本后重试。' : '服务未返回有效数据,请重试。'); } if (!res.ok) throw new Error(localRecords && res.status === 404 ? '当前服务不支持示例 / 浏览器记录管理,请重启至 0.5.1 或更新版本。' : data.error || '请求失败'); return data; } const formatTime = value => value && Number.isFinite(Date.parse(value)) ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '日期未识别'; function params() { const query = new URLSearchParams({ kind: state.kind, source: $('source').value, accountId: $('account').value, q: $('search').value, limit: String(state.limit), offset: String(state.offset) }); if ($('instanceFilter').value) query.set('instanceId', $('instanceFilter').value); for (const [id, key] of [['dateFrom', 'from'], ['dateTo', 'to']]) if ($(id).value) { const value = new Date($(id).value); if (!Number.isFinite(value.getTime())) throw new Error('请输入有效的时间。'); query.set(key, value.toISOString()); } if (query.get('from') && query.get('to') && query.get('from') >= query.get('to')) throw new Error('开始时间须早于结束时间。'); return query; } function element(tag, text, className) { const e = document.createElement(tag); if (text !== undefined) e.textContent = text; if (className) e.className = className; return e; } const count = value => Number.isSafeInteger(value) && value >= 0 ? value : 0; const plain = value => typeof value === 'string' ? value : ''; const senderLabel = record => record.kind === 'message' ? plain(record.senderName || record.raw?.author || record.raw?.from?.user?.displayName || record.raw?.from?.application?.displayName).trim() : ''; const selectedInstance = () => state.instances?.find(instance => instance.id === state.instanceId); let exportQuery = null; function disableExport() { $('export').removeAttribute('href'); $('export').setAttribute('aria-disabled', 'true'); exportQuery = null; } const instancePath = (operation, id = state.instanceId) => `/api/instances/${encodeURIComponent(id)}/${operation}`; function localRecordButtons() { $('localRecordAccount').disabled = state.localBusy || !state.token; $('loadLocalRecordAccounts').disabled = state.localBusy || !state.token; $('previewLocalRecordDeletion').disabled = state.localBusy || !state.token || !$('localRecordAccount').value; $('localDeleteConfirm').disabled = state.localBusy; $('cancelLocalRecordDeletion').disabled = state.localBusy; $('confirmLocalRecordDeletion').disabled = state.localBusy || !state.token || !$('localDeleteConfirm').checked || !state.localDeletePreview; } function localRecordScope(value) { return value && ['demo', 'browser'].includes(value.source) && typeof value.accountId === 'string' && value.accountId.length > 0; } function validateLocalPreview(result, scope, deleted = false) { if (!result || result.source !== scope.source || result.accountId !== scope.accountId || !result.counts || !['records', 'versions', 'changes', 'liveObservations', 'webhookDeliveries'].every(key => Number.isSafeInteger(result.counts[key]) && result.counts[key] >= 0) || (deleted && result.deleted !== true)) throw new Error('服务未确认所选来源和账号的删除范围,请重启至 0.5.1 或更新版本后重试。'); return result.counts; } async function fetchLocalRecordAccounts() { const result = await api('/api/local-records/accounts'); if (!Array.isArray(result?.items) || result.items.some(item => !localRecordScope(item) || !Number.isSafeInteger(item.records) || item.records <= 0)) throw new Error('服务未返回有效的示例 / 浏览器账号列表,请重启至 0.5.1 或更新版本后重试。'); const previous = $('localRecordAccount').value; state.localAccounts = result.items; $('localRecordAccount').replaceChildren(element('option', '请选择来源和账号')); $('localRecordAccount').firstChild.value = ''; for (const item of state.localAccounts) { const option = element('option', `${sourceNames[item.source]} (${item.source}) · ${item.accountId} · ${item.records} 条记录`); option.value = JSON.stringify({ source: item.source, accountId: item.accountId }); $('localRecordAccount').append(option); } $('localRecordAccount').value = previous; $('localRecordStatus').textContent = state.localAccounts.length ? `共 ${state.localAccounts.length} 个来源与账号组合。请选择账号并预览全部删除范围。` : '当前没有示例或浏览器记录。'; } async function localRecordAction(fn) { if (state.localBusy || !state.token) return; state.localBusy = true; localRecordButtons(); try { await fn(); } catch (error) { notice(error.message, true); $('localRecordStatus').textContent = error.message; if ($('localDeleteDialog').open) { $('localDeleteError').textContent = error.message; $('localDeleteConfirm').checked = false; } } finally { state.localBusy = false; localRecordButtons(); } } function loadLocalRecordAccounts() { return localRecordAction(async () => { state.localAccounts = []; $('localRecordAccount').replaceChildren(element('option', '正在加载来源和账号…')); $('localRecordAccount').firstChild.value = ''; try { await fetchLocalRecordAccounts(); } catch (error) { $('localRecordAccount').replaceChildren(element('option', '无法加载,请刷新账号列表')); $('localRecordAccount').firstChild.value = ''; throw error; } }); } function instanceButtons() { const busy = state.instanceBusy || Boolean(state.networkPending), available = Boolean(state.token && state.instances); for (const id of ['instanceSelect', 'instanceCreate', 'instanceSave', 'instanceImportPresence']) $(id).disabled = busy || !available; for (const id of ['instanceName', 'instanceKeepOnline', 'newInstanceName', 'presenceCaptureName', 'deleteAccount']) $(id).disabled = busy || !available; $('previewAccountDeletion').disabled = busy || !available || !$('deleteAccount').value; const images = state.media?.instances?.find(value => value.instanceId === state.instanceId); $('instanceImageBackfill').disabled = busy || !available || !images; $('instanceImageRetry').disabled = busy || !available || !images || !images.retryableFailed; } function instanceStatus(instances) { state.instances = Array.isArray(instances) ? instances : null; $('instanceControls').hidden = !state.instances; $('instanceFilter').disabled = !state.instances; if (!state.instances) return; if (!selectedInstance()) state.instanceId = state.instances[0]?.id || 'default'; const signature = JSON.stringify(state.instances.map(({ id, name }) => ({ id, name }))); if (signature !== state.instanceSignature) { const filterId = $('instanceFilter').value; $('instanceSelect').replaceChildren(); $('instanceFilter').replaceChildren(element('option', '所有实例')); $('instanceFilter').firstChild.value = ''; for (const instance of state.instances) for (const id of ['instanceSelect', 'instanceFilter']) { const option = element('option', instance.name); option.value = instance.id; $(id).append(option); } $('instanceFilter').value = filterId; state.instanceSignature = signature; } $('instanceSelect').value = state.instanceId; const current = selectedInstance(); if (!current) { instanceButtons(); return; } if (state.instanceSettingsId !== current.id || !state.instanceDirty) { $('instanceName').value = current.name; $('instanceKeepOnline').checked = current.keepOnline === true; state.instanceSettingsId = current.id; } const runtime = current.runtime || {}, presence = runtime.presence || {}; const runningCount = state.instances.filter(instance => instance.runtime?.running === true).length; $('instanceSummary').textContent = `${runningCount} / ${state.instances.length} 个实例正在采集`; $('instancePresence').textContent = !current.keepOnline ? '在线维持:已关闭。' : !runtime.running ? '在线维持:已启用设置,待启动该实例采集。' : `在线维持:${plain(presence.message) || '正在检查状态接口。'}${presence.lastRenewedAt ? ` 最近续期 ${formatTime(presence.lastRenewedAt)}。` : ''}`; const images = state.media?.instances?.find(value => value.instanceId === current.id); $('instanceImageBackfill').textContent = images?.enabled ? '暂停补下载' : '开启补下载'; if (images) { const mode = !images.enabled ? '历史图片自动补下载已关闭' : !runtime.running ? '已开启,等待此实例启动采集' : images.waitingReason === 'session_expired' || images.waitingReason === 'session_unavailable' ? '已开启,等待此实例恢复登录会话' : images.waitingReason ? '已开启,等待接口冷却' : images.remaining ? '正在后台补下载' : '已开启,已处理完当前已发现图片'; $('instanceImageProgress').textContent = `${mode}。已保存 ${count(images.counts?.saved)} / ${count(images.total)} 张,待处理 ${count(images.remaining)} 张,失败 ${count(images.counts?.failed)} 张。${images.nextAttemptAt ? ` 下次重试 ${formatTime(images.nextAttemptAt)}。` : ''}关闭页面后仍会继续,停止实例会暂停下载。`; } else $('instanceImageProgress').textContent = '图片补下载状态不可用,请检查后台服务版本。'; const accountSignature = JSON.stringify(current.accounts || []); if ($('deleteAccount').dataset.signature !== accountSignature) { const previous = $('deleteAccount').value; $('deleteAccount').replaceChildren(element('option', '选择要删除记录的账号')); $('deleteAccount').firstChild.value = ''; for (const account of current.accounts || []) { const option = element('option', `${sourceNames[account.source] || account.source} · ${account.accountId}`); option.value = JSON.stringify(account); $('deleteAccount').append(option); } $('deleteAccount').value = previous; $('deleteAccount').dataset.signature = accountSignature; } instanceButtons(); } function networkButtons() { const n = state.network, login = n.login?.state || 'idle'; const busy = Boolean(state.networkPending) || state.instanceBusy || !state.networkAvailable || !state.token; const loginActive = !n.login?.silent && ['opening', 'waiting', 'verifying', 'finishing'].includes(login); $('networkLogin').disabled = busy || loginActive; $('networkLogin').textContent = state.networkPending === 'networkLogin' ? '正在打开登录窗口…' : n.sessionAvailable ? '重新登录 Microsoft' : '从工具登录'; $('networkFinish').hidden = !loginActive; $('networkFinish').disabled = busy || login !== 'waiting'; $('networkFinish').textContent = state.networkPending === 'networkFinish' || ['verifying', 'finishing'].includes(login) ? '正在验证会话并关闭窗口…' : '完成登录并关闭窗口'; $('networkCancel').hidden = !loginActive; $('networkCancel').disabled = busy || ['verifying', 'finishing'].includes(login); $('networkStart').disabled = busy || !n.sessionAvailable || n.running === true || loginActive; $('networkStart').textContent = state.networkPending === 'networkStart' ? '正在启动…' : '启动后台采集'; $('networkStop').disabled = busy || n.running !== true; $('networkStop').textContent = state.networkPending === 'networkStop' ? '正在停止…' : '停止后台采集'; $('network').setAttribute('aria-busy', String(Boolean(state.networkPending))); instanceButtons(); } function networkStatus(data) { state.networkAvailable = Boolean(data && typeof data === 'object'); const n = state.network = data || {}, login = n.login || {}, sync = n.sync || {}, history = n.history || {}, historyCoverage = history.coverage || {}; const loginActive = !login.silent && ['opening', 'waiting', 'verifying', 'finishing'].includes(login.state); const renewal = n.renewal || {}; const running = n.running === true; const renewing = running && renewal.available && !renewal.interactionRequired && (login.silent && ['opening', 'waiting', 'verifying', 'finishing'].includes(login.state) || ['renewing', 'browser_required'].includes(renewal.state)); const retrying = running && renewal.available && !renewal.interactionRequired && !renewing && renewal.state === 'retrying'; const needsLogin = !renewing && !retrying && (renewal.interactionRequired === true || sync.authRequired === true || history.authRequired === true || count(historyCoverage.authRequired) > 0); const label = !state.networkAvailable ? '需要重启服务' : loginActive ? '正在登录' : renewing ? '正在自动续期' : retrying ? '续期等待重试' : needsLogin ? '需要重新登录' : running ? '后台运行中' : n.sessionAvailable ? '已停止' : '未启动'; $('networkState').textContent = label; $('networkState').dataset.state = needsLogin ? 'error' : running ? 'running' : 'idle'; $('networkMetric').textContent = label; $('networkMetricDetail').textContent = !state.networkAvailable ? '当前服务尚未支持后台 API' : retrying ? renewal.nextAttemptAt ? `下次续期 ${formatTime(renewal.nextAttemptAt)}` : '等待下次自动续期尝试' : needsLogin ? '完成微软验证后可继续采集' : renewing ? '正在更新此实例的访问凭证' : running ? '每 30 秒轮询 · 无需打开 Teams' : n.sessionAvailable ? '已保存本地会话,可启动采集' : '登录后每 30 秒轮询'; const loginLabels = { opening: '正在打开登录窗口', waiting: '等待你完成微软登录', verifying: '正在验证登录会话', finishing: '正在保存登录会话', error: '本次登录未完成' }; $('networkLoginState').textContent = !state.networkAvailable ? '等待新版服务' : login.silent && renewing ? '正在恢复此实例的会话' : retrying ? '会话等待自动恢复' : loginLabels[login.state] || (needsLogin ? '会话失效或授权被拒绝' : n.sessionAvailable ? count(sync.successful) > 0 ? '登录会话可用' : '本地会话已保存' : '尚未登录'); $('networkLastSync').textContent = sync.at ? formatTime(sync.at) : '尚未同步'; $('networkSaved').textContent = sync.at ? `${count(sync.records)} 条记录 · ${count(sync.changed)} 项变化` : '尚无结果'; $('networkRenewal').textContent = `自动续期:${plain(renewal.message) || '等待实例状态。'}${renewal.expiresAt ? ` 当前最早到期 ${formatTime(renewal.expiresAt)}。` : ''}${renewal.lastSuccessAt ? ` 最近成功 ${formatTime(renewal.lastSuccessAt)}。` : ''}${renewal.nextAttemptAt && renewal.state === 'retrying' ? ` 下次尝试 ${formatTime(renewal.nextAttemptAt)}。` : ''}`; const defaults = { opening: '正在打开临时窗口,请稍候。', waiting: '请在临时窗口完成微软登录,再按已捕获接口的提示完成登录。', verifying: '正在验证采集接口并保存当前会话,完成后会关闭临时窗口。', finishing: '正在保存当前会话并关闭临时窗口。', complete: '登录窗口已关闭;启动后台采集后,Teams 网页无需常驻。', cancelled: '已取消本次登录,可重新打开临时登录窗口。', error: '登录未完成,请查看提示后重新登录。' }; const loginMessage = plain(login.message); const legacyLoginGuide = '请在微软页面完成登录或 MFA,然后打开一次聊天;日历可选。准备好后点击完成登录。'; $('networkLoginMessage').textContent = login.silent ? plain(renewal.message) || '此实例使用已保存的会话自动续期。' : login.state === 'waiting' && loginMessage === legacyLoginGuide ? defaults.waiting : loginMessage || defaults[login.state] || '登录窗口仅在设置或重新登录时打开。'; const captured = login.counts || {}, capturedTotal = count(captured.messages) + count(captured.chats) + count(captured.calendar) + count(captured.presence); $('networkCaptureCounts').hidden = !loginActive && !capturedTotal; $('networkPresenceGuide').hidden = !loginActive; $('networkCaptureCounts').textContent = `已捕获接口:聊天列表 ${count(captured.chats)} · 消息 ${count(captured.messages)} · 日历 ${count(captured.calendar)} · 在线状态 ${count(captured.presence)}`; $('networkLoginNextStep').hidden = !loginActive || login.state !== 'waiting'; const messageGuide = !count(captured.messages) ? '尚未捕获消息接口。完成微软登录后,先等待页面加载;消息数仍为 0 时打开任意聊天,无需指定某个聊天。' : login.canFinish === false ? '已捕获消息接口,等待登录状态更新后即可尝试完成。' : '已捕获消息接口,可直接点击「完成登录并关闭窗口」进行验证,无需再打开指定聊天。'; const calendarGuide = count(captured.calendar) ? '日历接口已捕获,无需再打开日历。' : '日历尚未捕获;若需要日历采集,请在关闭窗口前打开日历,取得日历读取凭证。仅采集聊天可跳过。'; $('networkLoginNextStep').textContent = login.state === 'waiting' ? `${messageGuide} ${calendarGuide}` : ''; const chatMetadata = sync.chatMetadata; $('networkChatMetadata').hidden = !chatMetadata; $('networkChatMetadata').textContent = chatMetadata ? `会话名称:本轮读取 ${count(chatMetadata.successful)} 个,更新 ${count(chatMetadata.changed)} 项,待处理 ${count(chatMetadata.pending)} 个。${(Array.isArray(chatMetadata.errors) ? chatMetadata.errors.slice(0, 2).map(item => plain(item.reason)).filter(Boolean).join(' ') : '')}` : ''; const chats = count(historyCoverage.conversations), completed = count(historyCoverage.complete), pages = count(historyCoverage.pages), remaining = count(historyCoverage.pending), truncated = count(historyCoverage.truncated); const historyKnown = ['conversations', 'complete', 'pages', 'pending'].some(key => Number.isSafeInteger(historyCoverage[key])); const historyInitializationFailed = history.initializationFailed === true; const historyComplete = chats > 0 && history.complete === true && remaining === 0 && truncated === 0; $('networkHistoryState').textContent = historyInitializationFailed ? '历史补录暂不可用' : !historyKnown ? '历史补录尚未开始' : !chats ? '尚未发现可补录的聊天' : history.authRequired || count(historyCoverage.authRequired) ? '历史补录需要重新登录' : historyComplete ? '已发现聊天的历史补录已完成' : truncated && !remaining ? '历史补录结束 · 部分范围受限' : running ? '历史补录进行中' : '历史补录已暂停'; $('networkHistoryCount').textContent = chats ? `${completed} / ${chats} 个聊天` : ''; $('networkHistoryProgress').hidden = !chats; $('networkHistoryProgress').max = Math.max(1, chats); $('networkHistoryProgress').value = Math.min(completed, chats); $('networkHistoryDetail').textContent = historyInitializationFailed ? plain(historyCoverage.limitation) || '历史补录初始化未完成;实时聊天和日历采集仍可继续。' : historyKnown ? `累计读取 ${pages} 页、记录 ${count(historyCoverage.records)} 条 · 剩余 ${remaining} 个聊天${truncated ? ` · ${truncated} 个范围受限` : ''}${count(historyCoverage.errors) ? ` · ${count(historyCoverage.errors)} 个错误` : ''}。本轮新增或更新 ${count(history.changed)} 条。${plain(historyCoverage.limitation) || '进度仅包含已发现且可读取的历史范围。'}` : '启动后可在这里查看历史补录进度。'; const pace = history.pacing; const paceKnown = Number.isFinite(pace?.minDelayMs) && Number.isFinite(pace?.maxDelayMs) && pace.minDelayMs >= 0 && pace.maxDelayMs >= pace.minDelayMs; $('networkHistoryPacing').hidden = !paceKnown; $('networkHistoryPacing').textContent = paceKnown ? `历史请求间隔:随机 ${pace.minDelayMs / 1000}–${pace.maxDelayMs / 1000} 秒。${running && pace.waiting ? '正在等待下一次历史请求。' : running && count(pace.coolingDownOrigins) ? '历史请求因限流暂缓,实时采集继续。' : ''}` : ''; const errors = [!state.networkAvailable ? '当前服务版本不支持后台 API,请重启本地服务或打开新版控制台。' : '', state.networkActionError, plain(n.error), login.state === 'error' ? plain(login.message) : '', ...(Array.isArray(sync.errors) ? sync.errors.slice(0, 3).map(error => plain(error?.reason)) : []), ...(Array.isArray(history.errors) ? history.errors.slice(0, 3).map(error => plain(error?.reason) ? `历史补录:${error.reason}` : '') : [])].filter(Boolean); $('networkError').textContent = [...new Set(errors)].join('\n'); $('networkError').hidden = !errors.length; const coverage = sync.coverage || {}; const totals = Number.isSafeInteger(coverage.messages) || Number.isSafeInteger(coverage.calendarRequests) ? `当前发现 ${count(coverage.messages)} 个聊天、${count(coverage.calendarRequests)} 个日历查询。` : ''; $('networkCoverage').textContent = totals + (plain(coverage.limitation) || '覆盖范围以实际捕获的接口、发现的聊天和日历查询窗口为准;不代表完整历史。可续期会话自动恢复,需要交互时会显示提示。'); networkButtons(); } async function status() { const data = await api('/api/status'); state.token = data.localToken; state.media = data.media || null; localRecordButtons(); if (typeof data.version === 'string') document.querySelector('.version').textContent = data.version; $('pairingToken').value = data.pairingToken; $('endpoint').textContent = `http://127.0.0.1:${location.port}`; $('dbPath').textContent = `${data.dataDir}/teams.sqlite`; $('mcpStatus').textContent = data.mcp?.available ? 'MCP 已就绪:支持通用客户端的 stdio 和 Streamable HTTP。' : '当前服务未启用 MCP;升级后需重启本地服务。'; $('mcpEndpoint').textContent = data.mcp?.endpoint || `http://127.0.0.1:${location.port}/mcp`; $('webhookStatus').textContent = data.webhooks ? `已配置 ${count(data.webhooks.subscriptions)} 个提醒,启用 ${count(data.webhooks.enabled)} 个。` : '尚未配置消息提醒。'; for (const kind of ['message', 'event']) $(kind + 'Count').textContent = data.stats.groups.filter(g => g.kind === kind && g.source !== 'demo').reduce((n, g) => n + g.count, 0).toLocaleString(); $('versionCount').textContent = data.stats.versions.toLocaleString(); instanceStatus(data.instances); networkStatus(state.instances ? selectedInstance()?.runtime : data.network); const browser = data.browser, fresh = browser && Date.now() - Date.parse(browser.at) < 90000; const extension = data.extension, paired = data.pairing; const extensionFresh = extension && Date.now() - Date.parse(extension.at) < 90000; const accountMatches = !extension?.accountId || browser?.accountId === `browser:${extension.accountId}`; const newerDiagnostic = extensionFresh && (!browser || Date.parse(extension.at) >= Date.parse(browser.at)); if (extensionFresh && !extension.enabled) { $('connection').textContent = '已配对 · 采集暂停'; $('browserDetail').textContent = '本地配对已成功;请在扩展中开启采集并保存。'; } else if (newerDiagnostic && (extension.error || !extension.readyTabCount)) { $('connection').textContent = extension.error ? '页面连接异常' : '等待页面连接'; $('browserDetail').textContent = extension.error || `已配对,但 ${extension.teamsTabCount} 个 Teams 标签页中尚无采集脚本就绪。请点击扩展中的「重新连接页面」。`; } else if (fresh && accountMatches) { $('connection').textContent = browser.signedIn === false ? '等待 Teams 登录' : '页面已连接'; $('browserDetail').textContent = browser.signedIn === false ? '已收到页面心跳,请在 Teams 中完成登录。' : `页面已连接。最近一批 ${browser.received} 条记录,${browser.changed} 条发生变化。零条表示页面连接正常但当前没有新识别内容,可在扩展设置中预览。`; } else if (extensionFresh) { $('connection').textContent = !extension.enabled ? '已配对 · 采集暂停' : extension.error ? '页面连接异常' : !extension.readyTabCount ? '等待页面连接' : '等待页面心跳'; $('browserDetail').textContent = !extension.enabled ? '本地配对已成功;请在扩展中开启采集并保存。' : extension.error || `本地服务已连接,检测到 ${extension.teamsTabCount} 个 Teams 标签页,${extension.readyTabCount} 个页面脚本就绪。请打开聊天或日历;仍无心跳时点击扩展中的「重新连接页面」。`; } else if (paired || extension) { $('connection').textContent = '已配对 · 等待页面'; $('browserDetail').textContent = '配对只验证扩展能访问本地服务。请打开 Teams 标签页,并在扩展中点击「重新连接页面」;更新扩展后需先在扩展管理页点击重新加载。'; } else { $('connection').textContent = browser ? '等待页面响应' : '等待配对'; $('browserDetail').textContent = browser ? '页面心跳已过期,请检查 Teams 页面和扩展,或点击扩展中的「重新连接页面」。' : '尚未检测到扩展连接。在扩展设置中保存并开启采集。'; } $('heartbeat').textContent = browser && accountMatches ? `最近页面心跳 ${formatTime(browser.at)}` : extension || paired ? `最近扩展连接 ${formatTime(extension?.at || paired.at)}` : '尚未收到页面数据'; if (state.kind !== 'activity') { if (browser && accountMatches) $('coverage').textContent = `浏览器账号:${browser.accountId.replace(/^browser:/, '')} · ${browser.coverage || '仅已加载的页面内容'}${!fresh ? ' · 连接已暂停,检查扩展和 Teams 标签页。' : ''}`; else if (extension?.accountId) $('coverage').textContent = `当前配置账号:${extension.accountId} · 等待此账号的页面心跳。`; if (data.network && (!$('source').value || $('source').value === 'web-api')) $('coverage').textContent = `网页 API 记录由本机后台采集。${$('networkCoverage').textContent}`; } const accountSignature = JSON.stringify(data.stats.accounts); if (accountSignature !== state.accounts) { const selectedAccount = $('account').value; $('account').replaceChildren(element('option', '所有账号')); $('account').firstChild.value = ''; for (const a of data.stats.accounts) { const o = element('option', a.accountId); o.value = a.accountId; $('account').append(o); } $('account').value = selectedAccount; state.accounts = accountSignature; } const g = data.graph; state.graph = g; $('graphState').textContent = g.syncing ? '同步中' : g.authenticated ? '已登录' : g.configured ? '等待登录' : '未配置'; $('graphDetail').textContent = g.lastError?.message || (g.authenticated ? `已连接 ${g.account?.username || g.account?.name || ''};上次成功同步:${formatTime(g.lastSuccessAt)}。聊天 ${g.coverage?.chats?.completed || 0}/${g.coverage?.chats?.discovered || 0} 已完成;日历${g.coverage?.calendar?.completed ? '已完成' : '待同步或未完成'}。` : g.configurationMessage || '在 .env 配置 MS_CLIENT_ID,再重启服务。申请 User.Read、Chat.Read、Calendars.Read 委派权限。'); graphButtons(); const logs = await api('/api/logs'); const logText = logs.length ? logs.map(log => `${formatTime(log.at)} [${log.level}] ${log.message}`).join('\n') : '暂无运行日志'; if ($('logs').textContent !== logText) $('logs').textContent = logText; } function graphButtons() { const g = state.graph; $('graphLogin').disabled = !g.configured; $('sync').disabled = !g.authenticated || g.syncing; $('logout').disabled = !g.authenticated && !g.loginPending; } async function showDetail(id) { const r = await api(`/api/records/${id}`); $('detailTitle').textContent = r.displayTitle || r.title || kindNames[r.kind]; $('detailMeta').textContent = `${sourceNames[r.source]} · ${r.accountId} · 首次采集 ${formatTime(r.firstSeenAt)} · ${r.versions.length} 个版本`; const sender = senderLabel(r); $('detailSender').hidden = !sender; $('detailSender').textContent = sender ? `发送者:${sender}` : ''; $('detailBody').textContent = r.text || '无正文'; state.detailId = id; state.imageSignature = ''; renderDetailImages(id, r.images || []); $('detailRaw').textContent = JSON.stringify({ raw: r.raw, versions: r.versions }, null, 2); $('detail').showModal(); } function renderDetailImages(recordId, images) { if (state.detailId !== recordId || !Array.isArray(images)) return; const signature = JSON.stringify(images); if (state.imageSignature === signature) return; state.imageSignature = signature; $('detailImages').hidden = images.length === 0; $('detailImageList').replaceChildren(); const labels = { available: '历史图片,尚未下载', pending: '等待自动下载', downloading: '正在下载', retrying: '等待自动重试', failed: '下载失败', missing: '本地文件已不存在', saved: '已保存到本地' }; const errors = { session_unavailable: '此实例暂无可用会话', session_expired: '等待此实例续期或重新登录', access_denied: '凭证或图片权限不足', image_unavailable: '原图已不可用', rate_limited: '接口限流,稍后重试', redirect_blocked: '图片跳转地址暂不支持', unsupported_image: '图片类型暂不支持', image_too_large: '图片超过 25 MiB', invalid_image: '响应不是有效图片', download_failed: '网络或保存失败', download_interrupted: '下载中断' }; for (const item of images) { if (!/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(item.id)) continue; const card = document.createElement('article'); card.className = 'message-image'; const label = document.createElement('p'); label.textContent = `${item.label || '图片'}${item.fromEarlierVersion ? '(历史版本)' : ''} · ${labels[item.status] || '等待处理'}${item.bytes ? ` · ${(item.bytes / 1024).toFixed(1)} KiB` : ''}${item.errorCode ? ` · ${errors[item.errorCode] || '请重试'}` : ''}`; card.append(label); if (item.status === 'saved') { const path = `/api/images/${item.id}/content`; const preview = document.createElement('img'); preview.src = path; preview.alt = item.label || '聊天图片'; preview.loading = 'lazy'; const link = document.createElement('a'); link.href = `${path}?download=1`; link.textContent = '下载图片'; card.append(preview, link); } else { const button = document.createElement('button'); button.textContent = ['failed', 'retrying', 'missing'].includes(item.status) ? '重试下载' : '立即下载'; button.disabled = item.status === 'downloading'; button.addEventListener('click', async () => { button.disabled = true; button.textContent = '正在下载…'; try { await api(`/api/images/${item.id}/download`, {}); const updated = await api(`/api/records/${recordId}`); state.imageSignature = ''; renderDetailImages(recordId, updated.images || []); } catch (error) { button.disabled = false; button.textContent = '重试下载'; notice(error.message, true); } }); card.append(button); } $('detailImageList').append(card); } } async function records() { const query = params().toString(); const data = await api(`/api/records?${query}`); if (query !== params().toString()) return; $('export').href = `/api/export?${query}`; $('export').setAttribute('aria-disabled', 'false'); exportQuery = query; const signature = JSON.stringify([query, data.total, data.items.map(({ lastSeenAt, ...r }) => r)]); if (state.rendered === signature) return; state.rendered = signature; state.total = data.total; $('resultCount').textContent = String(data.total); $('records').replaceChildren(); if (!data.items.length) { const empty = element('div', undefined, 'empty'); empty.append(element('span', '⌑', 'empty-symbol'), element('strong', '这里还没有保存的记录'), element('p', '在「后台 API 采集」完成微软登录并启动采集;你也可以在「存储与诊断」添加示例。')); $('records').append(empty); } for (const r of data.items) { const row = element('article', undefined, 'record'), body = element('div'); const title = element('button', `${r.removedFromView ? '[从同步视图移除] ' : r.deleted ? '[已删除] ' : ''}${r.displayTitle || r.title || r.text?.slice(0, 80) || kindNames[r.kind]}`, 'record-title'); title.addEventListener('click', () => showDetail(r.id).catch(e => notice(e.message, true))); const meta = element('div', undefined, 'record-meta'); meta.append(element('span', sourceNames[r.source] || r.source, `source-label ${r.source}`), element('span', r.instanceName || r.accountId), element('span', kindNames[r.kind])); const sender = senderLabel(r); if (sender) meta.append(element('span', `发送者:${sender}`)); if (r.raw?.derived) meta.append(element('span', '本地派生变更记录')); if (!r.occurredAt) meta.append(element('span', '原始日期未识别 · 右侧为采集时间')); body.append(title, element('p', r.text || '打开详情查看原始字段'), meta); row.append(element('span', r.kind === 'event' ? '▦' : r.kind === 'activity' ? '↗' : '≡', 'record-icon'), body, element('time', formatTime(r.occurredAt || r.firstSeenAt))); $('records').append(row); } $('pageLabel').textContent = data.total ? `${state.offset + 1}–${Math.min(state.offset + state.limit, data.total)} / ${data.total} 条` : '0 条记录'; $('prev').disabled = !state.offset; $('next').disabled = state.offset + state.limit >= data.total; } async function refresh() { if (state.loading) return state.refreshPromise; state.loading = true; state.refreshPromise = (async () => { try { await status(); await records(); } catch (e) { notice(`无法连接本地服务:${e.message}`, true); } finally { state.loading = false; } })(); return state.refreshPromise; } function networkAction(id, path, message) { $(id).addEventListener('click', async () => { if (state.networkPending || $(id).disabled) return; state.networkPending = id; state.networkActionError = ''; networkButtons(); try { await api(state.instances ? instancePath(path.replace('/api/network/', '')) : path, {}); notice(message); if (state.loading) await state.refreshPromise; await refresh(); } catch (error) { state.networkActionError = error.message; notice(error.message, true); $('networkError').textContent = error.message; $('networkError').hidden = false; } finally { state.networkPending = ''; networkButtons(); } }); } networkAction('networkLogin', '/api/network/login', '请在临时窗口中完成微软登录。'); networkAction('networkFinish', '/api/network/login/finish', '已请求保存登录会话并关闭窗口,请查看登录状态。'); networkAction('networkCancel', '/api/network/login/cancel', '已取消本次登录。'); networkAction('networkStart', '/api/network/start', '后台采集已启动,无需保持 Teams 网页打开。'); networkAction('networkStop', '/api/network/stop', '后台采集已停止,已保存的数据继续保留。'); async function instanceAction(fn) { if (state.instanceBusy || state.networkPending) return; state.instanceBusy = true; networkButtons(); try { const result = await fn(); if (state.loading) await state.refreshPromise; await refresh(); if (result?.selectInstanceId && state.instances?.some(instance => instance.id === result.selectInstanceId)) { state.instanceId = result.selectInstanceId; state.instanceDirty = false; instanceStatus(state.instances); networkStatus(selectedInstance()?.runtime); } } catch (error) { notice(error.message, true); if ($('deleteDialog').open) $('deleteError').textContent = error.message; } finally { state.instanceBusy = false; networkButtons(); $('confirmAccountDeletion').disabled = !$('deleteConfirm').checked || !state.deletePreview; } } $('instanceSelect').addEventListener('change', () => { state.instanceId = $('instanceSelect').value; state.instanceDirty = false; state.networkActionError = ''; state.deletePreview = null; if ($('deleteDialog').open) $('deleteDialog').close(); instanceStatus(state.instances); networkStatus(selectedInstance()?.runtime); }); for (const id of ['instanceName', 'instanceKeepOnline']) $(id).addEventListener('input', () => { state.instanceDirty = true; }); $('instanceCreate').addEventListener('click', () => instanceAction(async () => { const name = $('newInstanceName').value.trim(); if (!name) throw new Error('请填写新实例名称。'); const created = await api('/api/instances', { name }); state.instanceDirty = false; $('newInstanceName').value = ''; notice('实例已创建。请选择该实例并完成登录,其他实例继续运行。'); return { selectInstanceId: created.id }; })); $('instanceSave').addEventListener('click', () => instanceAction(async () => { await api(instancePath('settings'), { name: $('instanceName').value.trim(), keepOnline: $('instanceKeepOnline').checked }); state.instanceDirty = false; notice('当前实例设置已保存。在线状态请查看下方实际结果。'); })); $('instanceImageBackfill').addEventListener('click', () => instanceAction(async () => { const imageStatus = state.media?.instances?.find(value => value.instanceId === state.instanceId); if (!imageStatus) throw new Error('请刷新图片补下载状态后重试。'); const enabled = !imageStatus.enabled; await api(instancePath('images/backfill'), { enabled }); notice(enabled ? '当前实例已开启历史图片自动补下载;重启后会继续,并自动处理以后补录发现的图片。' : '当前实例已暂停历史图片补下载,正在下载的这一张完成后暂停。'); })); $('instanceImageRetry').addEventListener('click', () => instanceAction(async () => { await api(instancePath('images/backfill'), { enabled: true, retryFailed: true }); notice('当前实例的暂时失败图片已重新排队;已保存图片不会重复下载,接口冷却时间继续生效。'); })); $('instanceImportPresence').addEventListener('click', () => instanceAction(async () => { const fileName = $('presenceCaptureName').value.trim(); if (!fileName) throw new Error('请填写本机 data/captures 中的 HAR 文件名。'); await api(instancePath('presence/import'), { fileName }); $('presenceCaptureName').value = ''; notice('状态模板已导入当前实例。该实例保持停止,请手动启动并查看在线维持结果。'); })); $('deleteAccount').addEventListener('change', instanceButtons); $('previewAccountDeletion').addEventListener('click', () => instanceAction(async () => { const scope = JSON.parse($('deleteAccount').value), current = selectedInstance(); const preview = await api(instancePath('records/preview', current.id), scope); state.deletePreview = { instanceId: current.id, ...scope }; $('deleteScope').textContent = `${current.name} · ${scope.accountId}`; const counts = preview.counts || {}; $('deleteCounts').textContent = `将删除 ${count(counts.records)} 条记录、${count(counts.versions)} 个历史版本、${count(counts.changes)} 项变更、${count(counts.images)} 张图片和 ${count(counts.webhookDeliveries)} 项提醒投递记录。`; $('deleteConfirm').checked = false; $('confirmAccountDeletion').disabled = true; $('deleteError').textContent = ''; $('deleteDialog').showModal(); })); $('deleteConfirm').addEventListener('change', () => { $('confirmAccountDeletion').disabled = state.instanceBusy || !$('deleteConfirm').checked || !state.deletePreview; }); $('cancelAccountDeletion').addEventListener('click', () => { if (!state.instanceBusy) { state.deletePreview = null; $('deleteDialog').close(); } }); $('deleteDialog').addEventListener('cancel', event => { if (state.instanceBusy) event.preventDefault(); else state.deletePreview = null; }); $('confirmAccountDeletion').addEventListener('click', () => { if (!$('deleteConfirm').checked || !state.deletePreview || $('confirmAccountDeletion').disabled) return; const preview = { ...state.deletePreview }; $('confirmAccountDeletion').disabled = true; void instanceAction(async () => { await api(instancePath('records/delete', preview.instanceId), { source: preview.source, accountId: preview.accountId, confirmation: preview.accountId }); state.deletePreview = null; $('deleteDialog').close(); state.rendered = ''; state.offset = 0; notice('指定账号的本地记录已删除,该实例已停止。再次启动可能重新补回历史。'); }); }); $('localRecordControls').addEventListener('toggle', () => { if ($('localRecordControls').open) void loadLocalRecordAccounts(); }); $('loadLocalRecordAccounts').addEventListener('click', () => { void loadLocalRecordAccounts(); }); $('localRecordAccount').addEventListener('change', localRecordButtons); $('previewLocalRecordDeletion').addEventListener('click', () => { if ($('previewLocalRecordDeletion').disabled) return; void localRecordAction(async () => { const scope = JSON.parse($('localRecordAccount').value); if (!localRecordScope(scope) || !state.localAccounts.some(item => item.source === scope.source && item.accountId === scope.accountId)) throw new Error('请先刷新并选择实际有记录的来源和账号。'); state.localDeletePreview = null; $('localDeleteConfirm').checked = false; const preview = await api('/api/local-records/preview', scope), counts = validateLocalPreview(preview, scope); state.localDeletePreview = Object.freeze({ source: scope.source, accountId: scope.accountId }); $('localDeleteScope').textContent = `来源:${sourceNames[scope.source]} (${scope.source}) · 账号:${scope.accountId}`; $('localDeleteCounts').textContent = `将删除 ${counts.records} 条记录(全部类型)、${counts.versions} 个历史版本、${counts.changes} 项变更、${counts.liveObservations} 项实时观察和 ${counts.webhookDeliveries} 项提醒投递记录。`; $('localDeleteError').textContent = ''; $('localDeleteDialog').showModal(); }); }); $('localDeleteConfirm').addEventListener('change', localRecordButtons); $('cancelLocalRecordDeletion').addEventListener('click', () => { if (!state.localBusy) { state.localDeletePreview = null; $('localDeleteDialog').close(); localRecordButtons(); } }); $('localDeleteDialog').addEventListener('cancel', event => { if (state.localBusy) event.preventDefault(); else { state.localDeletePreview = null; localRecordButtons(); } }); $('confirmLocalRecordDeletion').addEventListener('click', () => { if ($('confirmLocalRecordDeletion').disabled || !$('localDeleteConfirm').checked || !state.localDeletePreview) return; const scope = { ...state.localDeletePreview }; void localRecordAction(async () => { const result = await api('/api/local-records/delete', { ...scope, confirmation: scope.accountId }); validateLocalPreview(result, scope, true); state.localDeletePreview = null; $('localDeleteDialog').close(); state.rendered = ''; state.offset = 0; disableExport(); notice('指定来源和账号的本地记录已删除,其他实例继续运行。浏览器扩展仍开启时可能再次上传,请先暂停扩展采集。'); if (state.loading) await state.refreshPromise; await refresh(); try { await fetchLocalRecordAccounts(); } catch (error) { state.localAccounts = []; $('localRecordAccount').replaceChildren(element('option', '请刷新账号列表')); $('localRecordAccount').firstChild.value = ''; $('localRecordStatus').textContent = `本地记录已删除;账号列表刷新失败:${error.message}`; } }); }); function action(id, fn) { $(id).addEventListener('click', async () => { $(id).disabled = true; try { await fn(); await refresh(); } catch (e) { notice(e.message, true); } finally { $(id).disabled = false; graphButtons(); } }); } action('copyToken', async () => { await navigator.clipboard.writeText($('pairingToken').value); notice('已复制配对密钥,请粘贴到扩展设置。'); }); action('rotateToken', async () => { await api('/api/pairing/rotate', {}); notice('配对密钥已更新,请在扩展设置中粘贴新密钥。'); }); action('demo', async () => { await api('/api/demo', {}); notice('已添加示例记录;示例有独立来源标签,不计入真实消息与日程数量。'); }); action('graphLogin', async () => { const { url } = await api('/api/graph/login', {}); location.assign(url); }); action('sync', async () => { await api('/api/sync', {}); notice('同步请求已完成,请查看 Graph 连接状态。'); }); action('logout', async () => { await api('/api/graph/logout', {}); notice('本地 Graph 授权缓存已清除;已保存的记录继续保留。'); }); action('refresh', refresh); $('closeDetail').addEventListener('click', () => $('detail').close()); document.querySelectorAll('[data-kind]').forEach(button => button.addEventListener('click', async () => { state.kind = button.dataset.kind; state.offset = 0; disableExport(); document.querySelectorAll('[data-kind]').forEach(b => b.setAttribute('aria-selected', String(b === button))); $('coverage').textContent = state.kind === 'activity' ? '活动为实验性页面观察;Graph 来源的活动是本地派生变更记录,并非完整 Teams 通知。' : '网页 API 记录由本机后台采集;日期无法识别时保留原文。'; await refresh(); })); let searchTimer; $('search').addEventListener('input', () => { disableExport(); clearTimeout(searchTimer); searchTimer = setTimeout(() => { state.offset = 0; refresh(); }, 250); }); for (const id of ['source', 'account', 'instanceFilter', 'dateFrom', 'dateTo']) $(id).addEventListener('change', () => { disableExport(); state.offset = 0; refresh(); }); $('clearTime').addEventListener('click', () => { disableExport(); $('dateFrom').value = ''; $('dateTo').value = ''; state.offset = 0; refresh(); }); $('prev').addEventListener('click', () => { disableExport(); state.offset = Math.max(0, state.offset - state.limit); refresh(); }); $('next').addEventListener('click', () => { disableExport(); state.offset += state.limit; refresh(); }); $('export').addEventListener('click', event => { try { if ($('export').getAttribute('aria-disabled') === 'true' || exportQuery !== params().toString()) { event.preventDefault(); disableExport(); } } catch { event.preventDefault(); disableExport(); } }); disableExport(); localRecordButtons(); const login = new URLSearchParams(location.search).get('login'); if (login) { notice(login === 'success' ? 'Microsoft 登录成功,后台同步已启动。' : 'Microsoft 登录未完成,请重新登录并检查应用回调地址与权限。', login !== 'success'); history.replaceState(null, '', '/'); } await refresh(); setInterval(() => { if (document.hidden) return; refresh(); if ($('detail').open && state.detailId) { const id = state.detailId; void api(`/api/records/${id}`).then(record => renderDetailImages(id, record.images || [])).catch(() => {}); } }, 5000);