// sidepanel/sidepanel.js — Side Panel logic const STATUS_ICONS = { pending: '', running: '', completed: '\u2713', // ✓ failed: '\u2717', // ✗ stopped: '\u25A0', // ■ manual_completed: '跳', skipped: '跳', }; const logArea = document.getElementById('log-area'); const updateSection = document.getElementById('update-section'); const extensionUpdateStatus = document.getElementById('extension-update-status'); const extensionVersionMeta = document.getElementById('extension-version-meta'); const btnReleaseLog = document.getElementById('btn-release-log'); const updateCardVersion = document.getElementById('update-card-version'); const updateCardSummary = document.getElementById('update-card-summary'); const updateReleaseList = document.getElementById('update-release-list'); const btnOpenRelease = document.getElementById('btn-open-release'); const settingsCard = document.getElementById('settings-card'); const displayOauthUrl = document.getElementById('display-oauth-url'); const displayLocalhostUrl = document.getElementById('display-localhost-url'); const displayStatus = document.getElementById('display-status'); const statusBar = document.getElementById('status-bar'); const inputEmail = document.getElementById('input-email'); const inputPassword = document.getElementById('input-password'); const btnToggleVpsUrl = document.getElementById('btn-toggle-vps-url'); const btnToggleVpsPassword = document.getElementById('btn-toggle-vps-password'); const btnFetchEmail = document.getElementById('btn-fetch-email'); const btnTogglePassword = document.getElementById('btn-toggle-password'); const btnSaveSettings = document.getElementById('btn-save-settings'); const btnStop = document.getElementById('btn-stop'); const btnReset = document.getElementById('btn-reset'); const stepsProgress = document.getElementById('steps-progress'); const btnAutoRun = document.getElementById('btn-auto-run'); const btnAutoContinue = document.getElementById('btn-auto-continue'); const autoContinueBar = document.getElementById('auto-continue-bar'); const autoScheduleBar = document.getElementById('auto-schedule-bar'); const autoScheduleTitle = document.getElementById('auto-schedule-title'); const autoScheduleMeta = document.getElementById('auto-schedule-meta'); const btnAutoRunNow = document.getElementById('btn-auto-run-now'); const btnAutoCancelSchedule = document.getElementById('btn-auto-cancel-schedule'); const btnClearLog = document.getElementById('btn-clear-log'); const configMenuShell = document.getElementById('config-menu-shell'); const btnConfigMenu = document.getElementById('btn-config-menu'); const configMenu = document.getElementById('config-menu'); const btnExportSettings = document.getElementById('btn-export-settings'); const btnImportSettings = document.getElementById('btn-import-settings'); const inputImportSettingsFile = document.getElementById('input-import-settings-file'); const selectPanelMode = document.getElementById('select-panel-mode'); const rowVpsUrl = document.getElementById('row-vps-url'); const inputVpsUrl = document.getElementById('input-vps-url'); const rowVpsPassword = document.getElementById('row-vps-password'); const inputVpsPassword = document.getElementById('input-vps-password'); const rowLocalCpaStep9Mode = document.getElementById('row-local-cpa-step9-mode'); const localCpaStep9ModeButtons = Array.from(document.querySelectorAll('[data-local-cpa-step9-mode]')); const rowSub2ApiUrl = document.getElementById('row-sub2api-url'); const inputSub2ApiUrl = document.getElementById('input-sub2api-url'); const rowSub2ApiEmail = document.getElementById('row-sub2api-email'); const inputSub2ApiEmail = document.getElementById('input-sub2api-email'); const rowSub2ApiPassword = document.getElementById('row-sub2api-password'); const inputSub2ApiPassword = document.getElementById('input-sub2api-password'); const rowSub2ApiGroup = document.getElementById('row-sub2api-group'); const inputSub2ApiGroup = document.getElementById('input-sub2api-group'); const selectMailProvider = document.getElementById('select-mail-provider'); const btnMailLogin = document.getElementById('btn-mail-login'); const rowEmailGenerator = document.getElementById('row-email-generator'); const selectEmailGenerator = document.getElementById('select-email-generator'); const rowTempEmailBaseUrl = document.getElementById('row-temp-email-base-url'); const inputTempEmailBaseUrl = document.getElementById('input-temp-email-base-url'); const rowTempEmailAdminAuth = document.getElementById('row-temp-email-admin-auth'); const inputTempEmailAdminAuth = document.getElementById('input-temp-email-admin-auth'); const rowTempEmailCustomAuth = document.getElementById('row-temp-email-custom-auth'); const inputTempEmailCustomAuth = document.getElementById('input-temp-email-custom-auth'); const rowTempEmailDomain = document.getElementById('row-temp-email-domain'); const selectTempEmailDomain = document.getElementById('select-temp-email-domain'); const inputTempEmailDomain = document.getElementById('input-temp-email-domain'); const btnTempEmailDomainMode = document.getElementById('btn-temp-email-domain-mode'); const hotmailSection = document.getElementById('hotmail-section'); const rowHotmailServiceMode = document.getElementById('row-hotmail-service-mode'); const hotmailServiceModeButtons = Array.from(document.querySelectorAll('[data-hotmail-service-mode]')); const rowHotmailRemoteBaseUrl = document.getElementById('row-hotmail-remote-base-url'); const inputHotmailRemoteBaseUrl = document.getElementById('input-hotmail-remote-base-url'); const rowHotmailLocalBaseUrl = document.getElementById('row-hotmail-local-base-url'); const inputHotmailLocalBaseUrl = document.getElementById('input-hotmail-local-base-url'); const inputHotmailEmail = document.getElementById('input-hotmail-email'); const inputHotmailClientId = document.getElementById('input-hotmail-client-id'); const inputHotmailPassword = document.getElementById('input-hotmail-password'); const inputHotmailRefreshToken = document.getElementById('input-hotmail-refresh-token'); const inputHotmailImport = document.getElementById('input-hotmail-import'); const btnAddHotmailAccount = document.getElementById('btn-add-hotmail-account'); const btnImportHotmailAccounts = document.getElementById('btn-import-hotmail-accounts'); const btnHotmailUsageGuide = document.getElementById('btn-hotmail-usage-guide'); const btnClearUsedHotmailAccounts = document.getElementById('btn-clear-used-hotmail-accounts'); const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotmail-accounts'); const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list'); const hotmailListShell = document.getElementById('hotmail-list-shell'); const hotmailAccountsList = document.getElementById('hotmail-accounts-list'); const rowEmailPrefix = document.getElementById('row-email-prefix'); const labelEmailPrefix = document.getElementById('label-email-prefix'); const inputEmailPrefix = document.getElementById('input-email-prefix'); const rowInbucketHost = document.getElementById('row-inbucket-host'); const inputInbucketHost = document.getElementById('input-inbucket-host'); const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox'); const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox'); const rowCfDomain = document.getElementById('row-cf-domain'); const selectCfDomain = document.getElementById('select-cf-domain'); const inputCfDomain = document.getElementById('input-cf-domain'); const btnCfDomainMode = document.getElementById('btn-cf-domain-mode'); const inputRunCount = document.getElementById('input-run-count'); const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures'); const inputAutoSkipFailuresThreadIntervalMinutes = document.getElementById('input-auto-skip-failures-thread-interval-minutes'); const inputAutoDelayEnabled = document.getElementById('input-auto-delay-enabled'); const inputAutoDelayMinutes = document.getElementById('input-auto-delay-minutes'); const inputAutoStepDelaySeconds = document.getElementById('input-auto-step-delay-seconds'); const autoStartModal = document.getElementById('auto-start-modal'); const autoStartTitle = autoStartModal?.querySelector('.modal-title'); const autoStartMessage = document.getElementById('auto-start-message'); const autoStartAlert = document.getElementById('auto-start-alert'); const modalOptionRow = document.getElementById('modal-option-row'); const modalOptionInput = document.getElementById('modal-option-input'); const modalOptionText = document.getElementById('modal-option-text'); const btnAutoStartClose = document.getElementById('btn-auto-start-close'); const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel'); const btnAutoStartRestart = document.getElementById('btn-auto-start-restart'); const btnAutoStartContinue = document.getElementById('btn-auto-start-continue'); const autoHintText = document.querySelector('.auto-hint'); const STEP_DEFAULT_STATUSES = { 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending', 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending', }; const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]); const AUTO_DELAY_MIN_MINUTES = 1; const AUTO_DELAY_MAX_MINUTES = 1440; const AUTO_DELAY_DEFAULT_MINUTES = 30; const AUTO_FALLBACK_THREAD_INTERVAL_MIN_MINUTES = 0; const AUTO_FALLBACK_THREAD_INTERVAL_MAX_MINUTES = 1440; const AUTO_FALLBACK_THREAD_INTERVAL_DEFAULT_MINUTES = 0; const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3; const AUTO_STEP_DELAY_MIN_SECONDS = 0; const AUTO_STEP_DELAY_MAX_SECONDS = 600; const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit'; const AUTO_SKIP_FAILURES_PROMPT_DISMISSED_STORAGE_KEY = 'multipage-auto-skip-failures-prompt-dismissed'; const AUTO_RUN_FALLBACK_RISK_PROMPT_DISMISSED_STORAGE_KEY = 'multipage-auto-run-fallback-risk-prompt-dismissed'; const AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS = 15; const AUTO_RUN_FALLBACK_RISK_RECOMMENDED_THREAD_INTERVAL_MINUTES = 5; const HOTMAIL_SERVICE_MODE_REMOTE = 'remote'; const HOTMAIL_SERVICE_MODE_LOCAL = 'local'; const DISPLAY_TIMEZONE = 'Asia/Shanghai'; let latestState = null; let currentAutoRun = { autoRunning: false, phase: 'idle', currentRun: 0, totalRuns: 1, attemptRun: 0, scheduledAt: null, countdownAt: null, countdownTitle: '', countdownNote: '', }; let settingsDirty = false; let settingsSaveInFlight = false; let settingsAutoSaveTimer = null; let cloudflareDomainEditMode = false; let cloudflareTempEmailDomainEditMode = false; let modalChoiceResolver = null; let currentModalActions = []; let modalResultBuilder = null; let scheduledCountdownTimer = null; let hotmailActionInFlight = false; let hotmailListExpanded = false; let configMenuOpen = false; let configActionInFlight = false; let currentReleaseSnapshot = null; const EYE_OPEN_ICON = ''; const EYE_CLOSED_ICON = ''; const COPY_ICON = ''; const parseHotmailImportText = window.HotmailUtils?.parseHotmailImportText; const shouldClearHotmailCurrentSelection = window.HotmailUtils?.shouldClearHotmailCurrentSelection; const upsertHotmailAccountInList = window.HotmailUtils?.upsertHotmailAccountInList; const filterHotmailAccountsByUsage = window.HotmailUtils?.filterHotmailAccountsByUsage; const getHotmailBulkActionLabel = window.HotmailUtils?.getHotmailBulkActionLabel; const getHotmailListToggleLabel = window.HotmailUtils?.getHotmailListToggleLabel; const HOTMAIL_LIST_EXPANDED_STORAGE_KEY = 'multipage-hotmail-list-expanded'; const sidepanelUpdateService = window.SidepanelUpdateService; btnAutoCancelSchedule?.remove(); const MAIL_PROVIDER_LOGIN_CONFIGS = { '163': { label: '163 邮箱', url: 'https://mail.163.com/', buttonLabel: '登录', }, '163-vip': { label: '163 VIP 邮箱', url: 'https://webmail.vip.163.com/', buttonLabel: '登录', }, qq: { label: 'QQ 邮箱', url: 'https://wx.mail.qq.com/', buttonLabel: '登录', }, 'cloudflare-temp-email': { label: 'Cloudflare Temp Email GitHub', url: 'https://github.com/dreamhunter2333/cloudflare_temp_email', buttonLabel: 'GitHub', }, '2925': { label: '2925 邮箱', url: 'https://2925.com/#/mailList', }, }; // ============================================================ // Toast Notifications // ============================================================ const toastContainer = document.getElementById('toast-container'); const TOAST_ICONS = { error: '', warn: '', success: '', info: '', }; const LOG_LEVEL_LABELS = { info: '信息', ok: '成功', warn: '警告', error: '错误', }; function usesGeneratedAliasMailProvider(provider) { return provider === '2925'; } function showToast(message, type = 'error', duration = 4000) { const toast = document.createElement('div'); toast.className = `toast toast-${type}`; toast.innerHTML = `${TOAST_ICONS[type] || ''}${escapeHtml(message)}`; toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast)); toastContainer.appendChild(toast); if (duration > 0) { setTimeout(() => dismissToast(toast), duration); } } function dismissToast(toast) { if (!toast.parentNode) return; toast.classList.add('toast-exit'); toast.addEventListener('animationend', () => toast.remove()); } function resetActionModalOption() { if (!modalOptionRow || !modalOptionInput || !modalOptionText) { return; } modalOptionRow.hidden = true; modalOptionInput.checked = false; modalOptionInput.disabled = false; modalOptionText.textContent = '不再提示'; } function resetActionModalAlert() { if (!autoStartAlert) { return; } autoStartAlert.hidden = true; autoStartAlert.textContent = ''; autoStartAlert.className = 'modal-alert'; } function resetActionModalButtons() { const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue]; buttons.forEach((button) => { if (!button) return; button.hidden = true; button.disabled = false; button.onclick = null; }); currentModalActions = []; } function configureActionModalButton(button, action) { if (!button) return; if (!action) { button.hidden = true; button.onclick = null; return; } button.hidden = false; button.disabled = false; button.textContent = action.label; button.className = `btn ${action.variant || 'btn-outline'} btn-sm`; button.onclick = () => resolveModalChoice(action.id); } function configureActionModalOption(option) { if (!modalOptionRow || !modalOptionInput || !modalOptionText) { return; } if (!option) { resetActionModalOption(); return; } modalOptionRow.hidden = false; modalOptionInput.checked = Boolean(option.checked); modalOptionInput.disabled = Boolean(option.disabled); modalOptionText.textContent = option.label || '不再提示'; } function configureActionModalAlert(alert) { if (!autoStartAlert) { return; } if (!alert?.text) { resetActionModalAlert(); return; } autoStartAlert.hidden = false; autoStartAlert.textContent = alert.text; autoStartAlert.className = `modal-alert${alert.tone === 'danger' ? ' is-danger' : ''}`; } function resolveModalChoice(choice) { const optionChecked = Boolean(modalOptionInput?.checked); const result = typeof modalResultBuilder === 'function' ? modalResultBuilder(choice, { optionChecked }) : choice; if (modalChoiceResolver) { modalChoiceResolver(result); modalChoiceResolver = null; } modalResultBuilder = null; resetActionModalButtons(); resetActionModalAlert(); resetActionModalOption(); if (autoStartModal) { autoStartModal.hidden = true; } } function openActionModal({ title, message, actions, option, alert, buildResult }) { if (!autoStartModal) { return Promise.resolve(null); } if (modalChoiceResolver) { resolveModalChoice(null); } resetActionModalButtons(); autoStartTitle.textContent = title; autoStartMessage.textContent = message; currentModalActions = actions || []; modalResultBuilder = typeof buildResult === 'function' ? buildResult : null; const buttonSlots = currentModalActions.length <= 2 ? [btnAutoStartCancel, btnAutoStartContinue] : [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue]; buttonSlots.forEach((button, index) => { configureActionModalButton(button, currentModalActions[index]); }); configureActionModalAlert(alert); configureActionModalOption(option); autoStartModal.hidden = false; return new Promise((resolve) => { modalChoiceResolver = resolve; }); } function openAutoStartChoiceDialog(startStep, options = {}) { const runningStep = Number.isInteger(options.runningStep) ? options.runningStep : null; const continueMessage = runningStep ? `继续当前会先等待步骤 ${runningStep} 完成,再按最新进度自动执行。` : `继续当前会从步骤 ${startStep} 开始自动执行。`; return openActionModal({ title: '启动自动', message: `检测到当前已有流程进度。${continueMessage}重新开始会清空当前流程进度并从步骤 1 新开一轮。`, actions: [ { id: null, label: '取消', variant: 'btn-ghost' }, { id: 'restart', label: '重新开始', variant: 'btn-outline' }, { id: 'continue', label: '继续当前', variant: 'btn-primary' }, ], }); } async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary', alert = null }) { const choice = await openActionModal({ title, message, alert, actions: [ { id: null, label: '取消', variant: 'btn-ghost' }, { id: 'confirm', label: confirmLabel, variant: confirmVariant }, ], }); return choice === 'confirm'; } async function openConfirmModalWithOption({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary', alert = null, optionLabel = '不再提示', optionChecked = false, optionDisabled = false, }) { const result = await openActionModal({ title, message, alert, actions: [ { id: null, label: '取消', variant: 'btn-ghost' }, { id: 'confirm', label: confirmLabel, variant: confirmVariant }, ], option: { label: optionLabel, checked: optionChecked, disabled: optionDisabled, }, buildResult: (choice, meta) => ({ choice, optionChecked: Boolean(meta?.optionChecked), }), }); return { confirmed: result?.choice === 'confirm', optionChecked: Boolean(result?.optionChecked), }; } function isPromptDismissed(storageKey) { return localStorage.getItem(storageKey) === '1'; } function setPromptDismissed(storageKey, dismissed) { if (dismissed) { localStorage.setItem(storageKey, '1'); } else { localStorage.removeItem(storageKey); } } function isAutoSkipFailuresPromptDismissed() { return isPromptDismissed(AUTO_SKIP_FAILURES_PROMPT_DISMISSED_STORAGE_KEY); } function setAutoSkipFailuresPromptDismissed(dismissed) { setPromptDismissed(AUTO_SKIP_FAILURES_PROMPT_DISMISSED_STORAGE_KEY, dismissed); } function isAutoRunFallbackRiskPromptDismissed() { return isPromptDismissed(AUTO_RUN_FALLBACK_RISK_PROMPT_DISMISSED_STORAGE_KEY); } function setAutoRunFallbackRiskPromptDismissed(dismissed) { setPromptDismissed(AUTO_RUN_FALLBACK_RISK_PROMPT_DISMISSED_STORAGE_KEY, dismissed); } function shouldWarnAutoRunFallbackRisk(totalRuns, autoRunSkipFailures) { return totalRuns >= AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS; } async function openAutoSkipFailuresConfirmModal() { const result = await openConfirmModalWithOption({ title: '自动重试说明', message: `开启后,自动模式在某一轮失败时,会先在当前轮自动重试;单轮最多重试 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次,仍失败则放弃当前轮并继续下一轮。线程间隔只在开启自动重试且总轮数大于 1 时生效。`, confirmLabel: '确认开启', }); return { confirmed: result.confirmed, dismissPrompt: result.optionChecked, }; } async function openAutoRunFallbackRiskConfirmModal(totalRuns, fallbackThreadIntervalMinutes) { const intervalLabel = Number.isFinite(fallbackThreadIntervalMinutes) ? `${fallbackThreadIntervalMinutes} 分钟` : '未设置'; const result = await openConfirmModalWithOption({ title: '自动运行风险提醒', message: `当前设置为 ${totalRuns} 轮自动化,已开启自动重试,线程间隔为 ${intervalLabel}。轮数过多时,可能会因为 IP 短时间注册过多而集中失败。建议控制在 ${AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS} 轮以下,并将线程间隔设置在 ${AUTO_RUN_FALLBACK_RISK_RECOMMENDED_THREAD_INTERVAL_MINUTES} 分钟以上。是否继续?`, confirmLabel: '继续', }); return { confirmed: result.confirmed, dismissPrompt: result.optionChecked, }; } function updateConfigMenuControls() { const disabled = configActionInFlight || settingsSaveInFlight; const importLocked = disabled || currentAutoRun.autoRunning || Object.values(getStepStatuses()).some((status) => status === 'running'); if (btnConfigMenu) { btnConfigMenu.disabled = disabled; btnConfigMenu.setAttribute('aria-expanded', String(configMenuOpen)); } if (configMenu) { configMenu.hidden = !configMenuOpen; } if (btnExportSettings) { btnExportSettings.disabled = disabled; } if (btnImportSettings) { btnImportSettings.disabled = importLocked; } } function closeConfigMenu() { configMenuOpen = false; updateConfigMenuControls(); } function openConfigMenu() { configMenuOpen = true; updateConfigMenuControls(); } function toggleConfigMenu() { configMenuOpen ? closeConfigMenu() : openConfigMenu(); } async function waitForSettingsSaveIdle() { while (settingsSaveInFlight) { await new Promise((resolve) => setTimeout(resolve, 50)); } } async function flushPendingSettingsBeforeExport() { clearTimeout(settingsAutoSaveTimer); await waitForSettingsSaveIdle(); if (settingsDirty) { await saveSettings({ silent: true }); } } async function settlePendingSettingsBeforeImport() { clearTimeout(settingsAutoSaveTimer); await waitForSettingsSaveIdle(); } function downloadTextFile(content, fileName, mimeType = 'application/json;charset=utf-8') { const blob = new Blob([content], { type: mimeType }); const objectUrl = URL.createObjectURL(blob); const anchor = document.createElement('a'); anchor.href = objectUrl; anchor.download = fileName; document.body.appendChild(anchor); anchor.click(); anchor.remove(); setTimeout(() => URL.revokeObjectURL(objectUrl), 0); } function isDoneStatus(status) { return status === 'completed' || status === 'manual_completed' || status === 'skipped'; } function getStepStatuses(state = latestState) { return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) }; } function getFirstUnfinishedStep(state = latestState) { const statuses = getStepStatuses(state); for (let step = 1; step <= 9; step++) { if (!isDoneStatus(statuses[step])) { return step; } } return null; } function getRunningSteps(state = latestState) { const statuses = getStepStatuses(state); return Object.entries(statuses) .filter(([, status]) => status === 'running') .map(([step]) => Number(step)) .sort((a, b) => a - b); } function hasSavedProgress(state = latestState) { const statuses = getStepStatuses(state); return Object.values(statuses).some((status) => status !== 'pending'); } function shouldOfferAutoModeChoice(state = latestState) { return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null; } function syncLatestState(nextState) { const mergedStepStatuses = nextState?.stepStatuses ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses } : getStepStatuses(latestState); latestState = { ...(latestState || {}), ...(nextState || {}), stepStatuses: mergedStepStatuses, }; } function hasOwnStateValue(source, key) { return Object.prototype.hasOwnProperty.call(source, key); } function readAutoRunStateValue(source, keys, fallback) { for (const key of keys) { if (hasOwnStateValue(source, key)) { return source[key]; } } return fallback; } function syncAutoRunState(source = {}) { const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase; const autoRunning = source.autoRunning !== undefined ? Boolean(source.autoRunning) : (source.autoRunPhase !== undefined || source.phase !== undefined ? ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying', 'waiting_interval'].includes(phase) : currentAutoRun.autoRunning); currentAutoRun = { autoRunning, phase, currentRun: readAutoRunStateValue(source, ['autoRunCurrentRun', 'currentRun'], currentAutoRun.currentRun), totalRuns: readAutoRunStateValue(source, ['autoRunTotalRuns', 'totalRuns'], currentAutoRun.totalRuns), attemptRun: readAutoRunStateValue(source, ['autoRunAttemptRun', 'attemptRun'], currentAutoRun.attemptRun), scheduledAt: readAutoRunStateValue(source, ['scheduledAutoRunAt', 'scheduledAt'], currentAutoRun.scheduledAt), countdownAt: readAutoRunStateValue(source, ['autoRunCountdownAt', 'countdownAt'], currentAutoRun.countdownAt), countdownTitle: readAutoRunStateValue(source, ['autoRunCountdownTitle', 'countdownTitle'], currentAutoRun.countdownTitle), countdownNote: readAutoRunStateValue(source, ['autoRunCountdownNote', 'countdownNote'], currentAutoRun.countdownNote), }; } function isAutoRunLockedPhase() { return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'waiting_step' || currentAutoRun.phase === 'retrying' || currentAutoRun.phase === 'waiting_interval'; } function isAutoRunPausedPhase() { return currentAutoRun.phase === 'waiting_email'; } function isAutoRunWaitingStepPhase() { return currentAutoRun.phase === 'waiting_step'; } function isAutoRunScheduledPhase() { return currentAutoRun.phase === 'scheduled'; } function getAutoRunLabel(payload = currentAutoRun) { if ((payload.phase ?? currentAutoRun.phase) === 'scheduled') { return (payload.totalRuns || 1) > 1 ? ` (${payload.totalRuns}轮)` : ''; } const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : ''; if ((payload.totalRuns || 1) > 1) { return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`; } return attemptLabel ? ` (${attemptLabel.slice(3)})` : ''; } function normalizeAutoDelayMinutes(value) { const numeric = Number(value); if (!Number.isFinite(numeric)) { return AUTO_DELAY_DEFAULT_MINUTES; } return Math.min(AUTO_DELAY_MAX_MINUTES, Math.max(AUTO_DELAY_MIN_MINUTES, Math.floor(numeric))); } function normalizeAutoRunThreadIntervalMinutes(value) { const rawValue = String(value ?? '').trim(); if (!rawValue) { return AUTO_FALLBACK_THREAD_INTERVAL_DEFAULT_MINUTES; } const numeric = Number(rawValue); if (!Number.isFinite(numeric)) { return AUTO_FALLBACK_THREAD_INTERVAL_DEFAULT_MINUTES; } return Math.min( AUTO_FALLBACK_THREAD_INTERVAL_MAX_MINUTES, Math.max(AUTO_FALLBACK_THREAD_INTERVAL_MIN_MINUTES, Math.floor(numeric)) ); } function normalizeAutoStepDelaySeconds(value) { const rawValue = String(value ?? '').trim(); if (!rawValue) { return null; } const numeric = Number(rawValue); if (!Number.isFinite(numeric)) { return null; } return Math.min(AUTO_STEP_DELAY_MAX_SECONDS, Math.max(AUTO_STEP_DELAY_MIN_SECONDS, Math.floor(numeric))); } function formatAutoStepDelayInputValue(value) { const normalized = normalizeAutoStepDelaySeconds(value); return normalized === null ? '' : String(normalized); } function getRunCountValue() { return Math.min(50, Math.max(1, parseInt(inputRunCount.value, 10) || 1)); } function updateFallbackThreadIntervalInputState() { if (!inputAutoSkipFailuresThreadIntervalMinutes) { return; } inputAutoSkipFailuresThreadIntervalMinutes.disabled = Boolean(inputAutoSkipFailures.disabled); } function updateAutoDelayInputState() { const scheduled = isAutoRunScheduledPhase(); inputAutoDelayEnabled.disabled = scheduled; inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked; } function formatCountdown(remainingMs) { const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000)); const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const seconds = totalSeconds % 60; return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`; } function formatScheduleTime(timestamp) { return new Date(timestamp).toLocaleString('zh-CN', { hour12: false, timeZone: DISPLAY_TIMEZONE, month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', }); } function stopScheduledCountdownTicker() { clearInterval(scheduledCountdownTimer); scheduledCountdownTimer = null; } function getActiveAutoRunCountdown() { if (isAutoRunScheduledPhase() && Number.isFinite(currentAutoRun.scheduledAt)) { return { at: currentAutoRun.scheduledAt, title: '已计划自动运行', note: `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始`, tone: 'scheduled', }; } if (!Number.isFinite(currentAutoRun.countdownAt)) { return null; } return { at: currentAutoRun.countdownAt, title: currentAutoRun.countdownTitle || '等待中', note: currentAutoRun.countdownNote || '', tone: 'running', }; } function renderScheduledAutoRunInfo() { if (!autoScheduleBar) { return; } const countdown = getActiveAutoRunCountdown(); if (!countdown) { autoScheduleBar.style.display = 'none'; return; } const remainingMs = countdown.at - Date.now(); autoScheduleBar.style.display = 'flex'; if (btnAutoRunNow) { btnAutoRunNow.hidden = false; btnAutoRunNow.textContent = currentAutoRun.phase === 'waiting_interval' ? '立即继续' : '立即开始'; } if (btnAutoCancelSchedule) { btnAutoCancelSchedule.hidden = true; } autoScheduleTitle.textContent = countdown.title; autoScheduleMeta.textContent = remainingMs > 0 ? `${countdown.note ? `${countdown.note},` : ''}剩余 ${formatCountdown(remainingMs)}` : '倒计时即将结束,正在准备继续...'; return; } function syncScheduledCountdownTicker() { renderScheduledAutoRunInfo(); if (getActiveAutoRunCountdown()) { if (scheduledCountdownTimer) { return; } scheduledCountdownTimer = setInterval(() => { renderScheduledAutoRunInfo(); updateStatusDisplay(latestState); }, 1000); return; } stopScheduledCountdownTicker(); return; } function setDefaultAutoRunButton() { btnAutoRun.disabled = false; inputRunCount.disabled = false; btnAutoRun.innerHTML = ' 自动'; } function normalizeCloudflareDomainValue(value = '') { let normalized = String(value || '').trim().toLowerCase(); if (!normalized) return ''; normalized = normalized.replace(/^@+/, ''); normalized = normalized.replace(/^https?:\/\//, ''); normalized = normalized.replace(/\/.*$/, ''); if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) { return ''; } return normalized; } function normalizeCloudflareDomains(values = []) { const seen = new Set(); const domains = []; for (const value of Array.isArray(values) ? values : []) { const normalized = normalizeCloudflareDomainValue(value); if (!normalized || seen.has(normalized)) continue; seen.add(normalized); domains.push(normalized); } return domains; } function normalizeCloudflareTempEmailBaseUrlValue(value = '') { const raw = String(value || '').trim(); if (!raw) return ''; const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(raw) ? raw : `https://${raw}`; try { const parsed = new URL(candidate); parsed.hash = ''; parsed.search = ''; const pathname = parsed.pathname === '/' ? '' : parsed.pathname.replace(/\/+$/, ''); return `${parsed.origin}${pathname}`; } catch { return ''; } } function normalizeCloudflareTempEmailDomainValue(value = '') { return normalizeCloudflareDomainValue(value); } function normalizeCloudflareTempEmailDomains(values = []) { const seen = new Set(); const domains = []; for (const value of Array.isArray(values) ? values : []) { const normalized = normalizeCloudflareTempEmailDomainValue(value); if (!normalized || seen.has(normalized)) continue; seen.add(normalized); domains.push(normalized); } return domains; } function getCloudflareDomainsFromState() { const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []); const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || ''); if (activeDomain && !domains.includes(activeDomain)) { domains.unshift(activeDomain); } return { domains, activeDomain: activeDomain || domains[0] || '' }; } function getCloudflareTempEmailDomainsFromState() { const domains = normalizeCloudflareTempEmailDomains(latestState?.cloudflareTempEmailDomains || []); const activeDomain = normalizeCloudflareTempEmailDomainValue(latestState?.cloudflareTempEmailDomain || ''); if (activeDomain && !domains.includes(activeDomain)) { domains.unshift(activeDomain); } return { domains, activeDomain: activeDomain || domains[0] || '' }; } function renderCloudflareDomainOptions(preferredDomain = '') { const preferred = normalizeCloudflareDomainValue(preferredDomain); const { domains, activeDomain } = getCloudflareDomainsFromState(); const selected = preferred || activeDomain; selectCfDomain.innerHTML = ''; if (domains.length === 0) { const option = document.createElement('option'); option.value = ''; option.textContent = '请先添加域名'; selectCfDomain.appendChild(option); selectCfDomain.disabled = true; selectCfDomain.value = ''; return; } for (const domain of domains) { const option = document.createElement('option'); option.value = domain; option.textContent = domain; selectCfDomain.appendChild(option); } selectCfDomain.disabled = false; selectCfDomain.value = domains.includes(selected) ? selected : domains[0]; } function renderCloudflareTempEmailDomainOptions(preferredDomain = '') { const preferred = normalizeCloudflareTempEmailDomainValue(preferredDomain); const { domains, activeDomain } = getCloudflareTempEmailDomainsFromState(); const selected = preferred || activeDomain; selectTempEmailDomain.innerHTML = ''; if (domains.length === 0) { const option = document.createElement('option'); option.value = ''; option.textContent = '请先添加域名'; selectTempEmailDomain.appendChild(option); selectTempEmailDomain.disabled = true; selectTempEmailDomain.value = ''; return; } for (const domain of domains) { const option = document.createElement('option'); option.value = domain; option.textContent = domain; selectTempEmailDomain.appendChild(option); } selectTempEmailDomain.disabled = false; selectTempEmailDomain.value = domains.includes(selected) ? selected : domains[0]; } function setCloudflareDomainEditMode(editing, options = {}) { const { clearInput = false } = options; cloudflareDomainEditMode = Boolean(editing); selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : ''; inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none'; btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加'; if (cloudflareDomainEditMode) { if (clearInput) { inputCfDomain.value = ''; } inputCfDomain.focus(); } else if (clearInput) { inputCfDomain.value = ''; } } function setCloudflareTempEmailDomainEditMode(editing, options = {}) { const { clearInput = false } = options; cloudflareTempEmailDomainEditMode = Boolean(editing); selectTempEmailDomain.style.display = cloudflareTempEmailDomainEditMode ? 'none' : ''; inputTempEmailDomain.style.display = cloudflareTempEmailDomainEditMode ? '' : 'none'; btnTempEmailDomainMode.textContent = cloudflareTempEmailDomainEditMode ? '保存' : '添加'; if (cloudflareTempEmailDomainEditMode) { if (clearInput) { inputTempEmailDomain.value = ''; } inputTempEmailDomain.focus(); } else if (clearInput) { inputTempEmailDomain.value = ''; } } function collectSettingsPayload() { const { domains, activeDomain } = getCloudflareDomainsFromState(); const selectedCloudflareDomain = normalizeCloudflareDomainValue( !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain ) || activeDomain; const { domains: tempEmailDomains, activeDomain: tempEmailActiveDomain } = getCloudflareTempEmailDomainsFromState(); const selectedCloudflareTempEmailDomain = normalizeCloudflareTempEmailDomainValue( !cloudflareTempEmailDomainEditMode ? selectTempEmailDomain.value : tempEmailActiveDomain ) || tempEmailActiveDomain; return { panelMode: selectPanelMode.value, vpsUrl: inputVpsUrl.value.trim(), vpsPassword: inputVpsPassword.value, localCpaStep9Mode: getSelectedLocalCpaStep9Mode(), sub2apiUrl: inputSub2ApiUrl.value.trim(), sub2apiEmail: inputSub2ApiEmail.value.trim(), sub2apiPassword: inputSub2ApiPassword.value, sub2apiGroupName: inputSub2ApiGroup.value.trim(), customPassword: inputPassword.value, mailProvider: selectMailProvider.value, emailGenerator: selectEmailGenerator.value, emailPrefix: inputEmailPrefix.value.trim(), inbucketHost: inputInbucketHost.value.trim(), inbucketMailbox: inputInbucketMailbox.value.trim(), hotmailServiceMode: getSelectedHotmailServiceMode(), hotmailRemoteBaseUrl: inputHotmailRemoteBaseUrl.value.trim(), hotmailLocalBaseUrl: inputHotmailLocalBaseUrl.value.trim(), cloudflareDomain: selectedCloudflareDomain, cloudflareDomains: domains, cloudflareTempEmailBaseUrl: normalizeCloudflareTempEmailBaseUrlValue(inputTempEmailBaseUrl.value), cloudflareTempEmailAdminAuth: inputTempEmailAdminAuth.value, cloudflareTempEmailCustomAuth: inputTempEmailCustomAuth.value, cloudflareTempEmailDomain: selectedCloudflareTempEmailDomain, cloudflareTempEmailDomains: tempEmailDomains, autoRunSkipFailures: inputAutoSkipFailures.checked, autoRunFallbackThreadIntervalMinutes: normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value), autoRunDelayEnabled: inputAutoDelayEnabled.checked, autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value), autoStepDelaySeconds: normalizeAutoStepDelaySeconds(inputAutoStepDelaySeconds.value), }; } function normalizeLocalCpaStep9Mode(value = '') { return String(value || '').trim().toLowerCase() === 'bypass' ? 'bypass' : DEFAULT_LOCAL_CPA_STEP9_MODE; } function normalizeHotmailServiceMode(value = '') { return HOTMAIL_SERVICE_MODE_LOCAL; } function getSelectedLocalCpaStep9Mode() { const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active')); return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode); } function setLocalCpaStep9Mode(mode) { const resolvedMode = normalizeLocalCpaStep9Mode(mode); localCpaStep9ModeButtons.forEach((button) => { const active = button.dataset.localCpaStep9Mode === resolvedMode; button.classList.toggle('is-active', active); button.setAttribute('aria-pressed', String(active)); }); } function getSelectedHotmailServiceMode() { const activeButton = hotmailServiceModeButtons.find((button) => button.classList.contains('is-active')); return normalizeHotmailServiceMode(activeButton?.dataset.hotmailServiceMode); } function setHotmailServiceMode(mode) { const resolvedMode = normalizeHotmailServiceMode(mode); hotmailServiceModeButtons.forEach((button) => { const isRemoteMode = button.dataset.hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE; const active = button.dataset.hotmailServiceMode === resolvedMode; button.disabled = isRemoteMode; button.setAttribute('aria-disabled', String(isRemoteMode)); button.classList.toggle('is-active', active); button.setAttribute('aria-pressed', String(active)); }); } function setSettingsCardLocked(locked) { if (!settingsCard) { return; } settingsCard.classList.toggle('is-locked', locked); settingsCard.toggleAttribute('inert', locked); } async function setRuntimeEmailState(email) { const normalizedEmail = String(email || '').trim() || null; const response = await chrome.runtime.sendMessage({ type: 'SET_EMAIL_STATE', source: 'sidepanel', payload: { email: normalizedEmail }, }); if (response?.error) { throw new Error(response.error); } return normalizedEmail; } async function clearRegistrationEmail(options = {}) { const { silent = false } = options; if (!inputEmail.value.trim() && !latestState?.email) { return; } inputEmail.value = ''; syncLatestState({ email: null }); try { await setRuntimeEmailState(null); } catch (err) { if (!silent) { showToast(`清空邮箱失败:${err.message}`, 'error'); } throw err; } } function markSettingsDirty(isDirty = true) { settingsDirty = isDirty; updateSaveButtonState(); } function updateSaveButtonState() { btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty; updateConfigMenuControls(); btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存'; } function scheduleSettingsAutoSave() { clearTimeout(settingsAutoSaveTimer); settingsAutoSaveTimer = setTimeout(() => { saveSettings({ silent: true }).catch(() => { }); }, 500); } async function saveSettings(options = {}) { const { silent = false } = options; clearTimeout(settingsAutoSaveTimer); if (!settingsDirty && !settingsSaveInFlight && silent) { return; } const payload = collectSettingsPayload(); settingsSaveInFlight = true; updateSaveButtonState(); try { const response = await chrome.runtime.sendMessage({ type: 'SAVE_SETTING', source: 'sidepanel', payload, }); if (response?.error) { throw new Error(response.error); } if (response?.state) { applySettingsState(response.state); } else { syncLatestState(payload); markSettingsDirty(false); updatePanelModeUI(); updateMailProviderUI(); updateButtonStates(); } if (!silent) { showToast('配置已保存', 'success', 1800); } } catch (err) { markSettingsDirty(true); if (!silent) { showToast(`保存失败:${err.message}`, 'error'); } throw err; } finally { settingsSaveInFlight = false; updateSaveButtonState(); } } function applyAutoRunStatus(payload = currentAutoRun) { syncAutoRunState(payload); const runLabel = getAutoRunLabel(currentAutoRun); const locked = isAutoRunLockedPhase(); const paused = isAutoRunPausedPhase(); const scheduled = isAutoRunScheduledPhase(); const settingsCardLocked = scheduled || locked; setSettingsCardLocked(settingsCardLocked); inputRunCount.disabled = currentAutoRun.autoRunning; btnAutoRun.disabled = currentAutoRun.autoRunning; btnFetchEmail.disabled = locked || usesGeneratedAliasMailProvider(selectMailProvider.value) || isCustomMailProvider(); inputEmail.disabled = locked; inputAutoSkipFailures.disabled = scheduled; if (currentAutoRun.totalRuns > 0) { inputRunCount.value = String(currentAutoRun.totalRuns); } switch (currentAutoRun.phase) { case 'scheduled': autoContinueBar.style.display = 'none'; btnAutoRun.innerHTML = `已计划${runLabel}`; break; case 'waiting_step': autoContinueBar.style.display = 'none'; btnAutoRun.innerHTML = `等待中${runLabel}`; break; case 'waiting_email': autoContinueBar.style.display = 'flex'; btnAutoRun.innerHTML = `已暂停${runLabel}`; break; case 'running': autoContinueBar.style.display = 'none'; btnAutoRun.innerHTML = `运行中${runLabel}`; break; case 'retrying': autoContinueBar.style.display = 'none'; btnAutoRun.innerHTML = `重试中${runLabel}`; break; case 'waiting_interval': autoContinueBar.style.display = 'none'; btnAutoRun.innerHTML = `等待中${runLabel}`; break; default: autoContinueBar.style.display = 'none'; setDefaultAutoRunButton(); inputEmail.disabled = false; if (!locked) { btnFetchEmail.disabled = usesGeneratedAliasMailProvider(selectMailProvider.value) || isCustomMailProvider(); } break; } updateAutoDelayInputState(); updateFallbackThreadIntervalInputState(); syncScheduledCountdownTicker(); updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running')); updateConfigMenuControls(); } function initializeManualStepActions() { document.querySelectorAll('.step-row').forEach((row) => { const step = Number(row.dataset.step); const statusEl = row.querySelector('.step-status'); if (!statusEl) return; const actions = document.createElement('div'); actions.className = 'step-actions'; const manualBtn = document.createElement('button'); manualBtn.type = 'button'; manualBtn.className = 'step-manual-btn'; manualBtn.dataset.step = String(step); manualBtn.title = '跳过此步'; manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`); manualBtn.innerHTML = ''; manualBtn.addEventListener('click', async (event) => { event.stopPropagation(); try { await handleSkipStep(step); } catch (err) { showToast(err.message, 'error'); } }); statusEl.parentNode.replaceChild(actions, statusEl); actions.appendChild(manualBtn); actions.appendChild(statusEl); }); } // ============================================================ // State Restore on load // ============================================================ function applySettingsState(state) { syncLatestState(state); syncAutoRunState(state); inputEmail.value = state?.email || ''; syncPasswordField(state || {}); inputVpsUrl.value = state?.vpsUrl || ''; inputVpsPassword.value = state?.vpsPassword || ''; setLocalCpaStep9Mode(state?.localCpaStep9Mode); selectPanelMode.value = state?.panelMode || 'cpa'; inputSub2ApiUrl.value = state?.sub2apiUrl || ''; inputSub2ApiEmail.value = state?.sub2apiEmail || ''; inputSub2ApiPassword.value = state?.sub2apiPassword || ''; inputSub2ApiGroup.value = state?.sub2apiGroupName || ''; const restoredMailProvider = isCustomMailProvider(state?.mailProvider) || ['hotmail-api', '163', '163-vip', 'qq', 'inbucket', '2925', 'cloudflare-temp-email'].includes(String(state?.mailProvider || '').trim()) ? String(state?.mailProvider || '163').trim() : (String(state?.emailGenerator || '').trim().toLowerCase() === 'custom' || String(state?.emailGenerator || '').trim().toLowerCase() === 'manual' ? 'custom' : '163'); selectMailProvider.value = restoredMailProvider; const restoredEmailGenerator = String(state?.emailGenerator || '').trim().toLowerCase(); selectEmailGenerator.value = ['cloudflare', 'cloudflare-temp-email'].includes(restoredEmailGenerator) ? restoredEmailGenerator : 'duck'; inputEmailPrefix.value = state?.emailPrefix || ''; inputInbucketHost.value = state?.inbucketHost || ''; inputInbucketMailbox.value = state?.inbucketMailbox || ''; setHotmailServiceMode(state?.hotmailServiceMode); inputHotmailRemoteBaseUrl.value = state?.hotmailRemoteBaseUrl || ''; inputHotmailLocalBaseUrl.value = state?.hotmailLocalBaseUrl || ''; inputTempEmailBaseUrl.value = state?.cloudflareTempEmailBaseUrl || ''; inputTempEmailAdminAuth.value = state?.cloudflareTempEmailAdminAuth || ''; inputTempEmailCustomAuth.value = state?.cloudflareTempEmailCustomAuth || ''; renderCloudflareDomainOptions(state?.cloudflareDomain || ''); setCloudflareDomainEditMode(false, { clearInput: true }); renderCloudflareTempEmailDomainOptions(state?.cloudflareTempEmailDomain || ''); setCloudflareTempEmailDomainEditMode(false, { clearInput: true }); inputAutoSkipFailures.checked = Boolean(state?.autoRunSkipFailures); inputAutoSkipFailuresThreadIntervalMinutes.value = String(normalizeAutoRunThreadIntervalMinutes(state?.autoRunFallbackThreadIntervalMinutes)); inputAutoDelayEnabled.checked = Boolean(state?.autoRunDelayEnabled); inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state?.autoRunDelayMinutes)); inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(state?.autoStepDelaySeconds); if (state?.autoRunTotalRuns) { inputRunCount.value = String(state.autoRunTotalRuns); } applyAutoRunStatus(state); markSettingsDirty(false); updateAutoDelayInputState(); updateFallbackThreadIntervalInputState(); updatePanelModeUI(); updateMailProviderUI(); updateButtonStates(); } async function restoreState() { try { const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }); applySettingsState(state); if (state.oauthUrl) { displayOauthUrl.textContent = state.oauthUrl; displayOauthUrl.classList.add('has-value'); } if (state.localhostUrl) { displayLocalhostUrl.textContent = state.localhostUrl; displayLocalhostUrl.classList.add('has-value'); } if (state.stepStatuses) { for (const [step, status] of Object.entries(state.stepStatuses)) { updateStepUI(Number(step), status); } } if (state.logs) { for (const entry of state.logs) { appendLog(entry); } } updateStatusDisplay(latestState); updateProgressCounter(); } catch (err) { console.error('Failed to restore state:', err); } } function openExternalUrl(url) { const targetUrl = String(url || '').trim(); if (!targetUrl) { return; } if (chrome?.tabs?.create) { chrome.tabs.create({ url: targetUrl, active: true }).catch(() => { window.open(targetUrl, '_blank', 'noopener'); }); return; } window.open(targetUrl, '_blank', 'noopener'); } function createUpdateNoteList(notes = []) { if (!Array.isArray(notes) || notes.length === 0) { const empty = document.createElement('p'); empty.className = 'update-release-empty'; empty.textContent = '该版本未提供可解析的更新说明,请查看完整更新日志。'; return empty; } const list = document.createElement('ul'); list.className = 'update-release-notes'; notes.forEach((note) => { const item = document.createElement('li'); item.textContent = note; list.appendChild(item); }); return list; } function renderUpdateReleaseList(releases = []) { if (!updateReleaseList) { return; } updateReleaseList.innerHTML = ''; releases.forEach((release) => { const item = document.createElement('article'); item.className = 'update-release-item'; const head = document.createElement('div'); head.className = 'update-release-head'; const titleRow = document.createElement('div'); titleRow.className = 'update-release-title-row'; const version = document.createElement('span'); version.className = 'update-release-version'; version.textContent = `v${release.version}`; titleRow.appendChild(version); if (release.title) { const name = document.createElement('span'); name.className = 'update-release-name'; name.textContent = release.title; titleRow.appendChild(name); } head.appendChild(titleRow); const publishedAt = sidepanelUpdateService?.formatReleaseDate?.(release.publishedAt) || ''; if (publishedAt) { const date = document.createElement('span'); date.className = 'update-release-date'; date.textContent = publishedAt; head.appendChild(date); } item.appendChild(head); item.appendChild(createUpdateNoteList(release.notes)); updateReleaseList.appendChild(item); }); } function resetUpdateCard() { if (updateSection) { updateSection.hidden = true; } if (updateCardVersion) { updateCardVersion.textContent = ''; } if (updateCardSummary) { updateCardSummary.textContent = ''; } if (updateReleaseList) { updateReleaseList.innerHTML = ''; } if (btnOpenRelease) { btnOpenRelease.hidden = true; btnOpenRelease.onclick = null; } } function renderReleaseSnapshot(snapshot) { currentReleaseSnapshot = snapshot; if (!extensionUpdateStatus || !extensionVersionMeta) { return; } extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed', 'is-version-label'); const localVersionText = snapshot?.localVersion ? `v${snapshot.localVersion}` : ''; const logUrl = snapshot?.logUrl || snapshot?.releasesPageUrl || sidepanelUpdateService?.releasesPageUrl || ''; if (btnReleaseLog) { btnReleaseLog.onclick = () => openExternalUrl(logUrl); btnReleaseLog.hidden = true; } extensionVersionMeta.hidden = true; extensionVersionMeta.textContent = ''; switch (snapshot?.status) { case 'update-available': { extensionUpdateStatus.textContent = '有更新'; extensionUpdateStatus.classList.add('is-update-available'); if (btnReleaseLog) { btnReleaseLog.hidden = false; } if (updateSection) { updateSection.hidden = false; } if (updateCardVersion) { updateCardVersion.textContent = `最新版本 v${snapshot.latestVersion}`; } if (updateCardSummary) { const updateCount = Array.isArray(snapshot.newerReleases) ? snapshot.newerReleases.length : 0; updateCardSummary.textContent = updateCount > 1 ? `当前 ${localVersionText},共有 ${updateCount} 个新版本可更新。` : `当前 ${localVersionText},可更新到 v${snapshot.latestVersion}。`; } renderUpdateReleaseList(snapshot.newerReleases || []); if (btnOpenRelease) { btnOpenRelease.hidden = false; btnOpenRelease.textContent = '前往更新'; btnOpenRelease.onclick = () => openExternalUrl(logUrl); } break; } case 'latest': { extensionUpdateStatus.textContent = localVersionText || 'v0.0.0'; extensionUpdateStatus.classList.add('is-version-label'); resetUpdateCard(); break; } case 'empty': { extensionUpdateStatus.textContent = localVersionText || 'v0.0.0'; extensionUpdateStatus.classList.add('is-version-label'); resetUpdateCard(); break; } case 'error': default: { extensionUpdateStatus.textContent = localVersionText || 'v0.0.0'; extensionUpdateStatus.classList.add('is-version-label', 'is-check-failed'); extensionVersionMeta.textContent = snapshot?.errorMessage || 'GitHub Releases 检查失败'; extensionVersionMeta.hidden = false; resetUpdateCard(); break; } } } async function initializeReleaseInfo() { const fallbackReleaseUrl = sidepanelUpdateService?.releasesPageUrl || 'https://github.com/QLHazyCoder/codex-oauth-automation-extension/releases'; if (btnReleaseLog) { btnReleaseLog.onclick = () => openExternalUrl(currentReleaseSnapshot?.logUrl || fallbackReleaseUrl); } if (!extensionUpdateStatus || !extensionVersionMeta) { return; } const localVersion = sidepanelUpdateService?.stripVersionPrefix?.(chrome.runtime.getManifest()?.version || '') || ''; extensionUpdateStatus.textContent = localVersion ? `v${localVersion}` : 'v0.0.0'; extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed'); extensionUpdateStatus.classList.add('is-version-label'); extensionVersionMeta.hidden = true; extensionVersionMeta.textContent = ''; if (btnReleaseLog) { btnReleaseLog.hidden = true; } resetUpdateCard(); if (!sidepanelUpdateService) { extensionVersionMeta.textContent = '更新检查服务不可用'; extensionVersionMeta.hidden = false; return; } const snapshot = await sidepanelUpdateService.getReleaseSnapshot(); renderReleaseSnapshot(snapshot); } function syncPasswordField(state) { inputPassword.value = state.customPassword || state.password || ''; } function isCustomMailProvider(provider = selectMailProvider.value) { return String(provider || '').trim().toLowerCase() === 'custom'; } function getSelectedEmailGenerator() { const generator = String(selectEmailGenerator.value || '').trim().toLowerCase(); if (generator === 'custom' || generator === 'manual') { return 'custom'; } if (generator === 'cloudflare') return 'cloudflare'; if (generator === 'cloudflare-temp-email') return 'cloudflare-temp-email'; return 'duck'; } function getEmailGeneratorUiCopy() { if (getSelectedEmailGenerator() === 'custom') { return getCustomMailProviderUiCopy(); } if (getSelectedEmailGenerator() === 'cloudflare') { return { buttonLabel: '生成', placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱', successVerb: '生成', label: 'Cloudflare 邮箱', }; } if (getSelectedEmailGenerator() === 'cloudflare-temp-email') { return { buttonLabel: '生成 Temp', placeholder: '点击生成 Cloudflare Temp Email,或手动粘贴邮箱', successVerb: '生成', label: 'Cloudflare Temp Email', }; } return { buttonLabel: '获取', placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱', successVerb: '获取', label: 'Duck 邮箱', }; } function getCustomMailProviderUiCopy() { return { buttonLabel: '自定义邮箱', placeholder: '请填写本轮要使用的注册邮箱', successVerb: '使用', label: '自定义邮箱', }; } function getCustomVerificationPromptCopy(step) { const verificationLabel = step === 4 ? '注册验证码' : '登录验证码'; return { title: `手动处理${verificationLabel}`, message: `当前邮箱服务为“自定义邮箱”。请先在页面中手动输入${verificationLabel},并确认已经进入下一页面后,再点击确认。`, alert: { text: `点击确认后会跳过步骤 ${step}。`, tone: 'danger', }, }; } function getHotmailAccounts(state = latestState) { return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : []; } function getCurrentHotmailAccount(state = latestState) { const currentId = state?.currentHotmailAccountId; return getHotmailAccounts(state).find((account) => account.id === currentId) || null; } function getCurrentHotmailEmail(state = latestState) { return String(getCurrentHotmailAccount(state)?.email || '').trim(); } function getMailProviderLoginConfig(provider = selectMailProvider.value) { return MAIL_PROVIDER_LOGIN_CONFIGS[String(provider || '').trim()] || null; } function getMailProviderLoginUrl(provider = selectMailProvider.value) { const config = getMailProviderLoginConfig(provider); const url = String(config?.url || '').trim(); return url ? url : ''; } function isCurrentEmailManagedByHotmail(state = latestState) { const hotmailEmail = getCurrentHotmailEmail(state); if (!hotmailEmail) { return false; } const inputEmailValue = String(inputEmail.value || '').trim(); const stateEmailValue = String(state?.email || '').trim(); return inputEmailValue === hotmailEmail || stateEmailValue === hotmailEmail; } function isCurrentEmailManagedByGeneratedAlias(provider = latestState?.mailProvider, state = latestState) { const normalizedProvider = String(provider || '').trim(); if (!usesGeneratedAliasMailProvider(normalizedProvider)) { return false; } const inputEmailValue = String(inputEmail.value || '').trim().toLowerCase(); const stateEmailValue = String(state?.email || '').trim().toLowerCase(); if (normalizedProvider === '2925') { return inputEmailValue.endsWith('@2925.com') || stateEmailValue.endsWith('@2925.com'); } return false; } function updateMailLoginButtonState() { if (!btnMailLogin) { return; } const config = getMailProviderLoginConfig(); const loginUrl = getMailProviderLoginUrl(); btnMailLogin.disabled = !loginUrl; btnMailLogin.textContent = config?.buttonLabel || '登录'; btnMailLogin.title = loginUrl ? `打开 ${config.label} 登录页` : '当前邮箱服务没有可跳转的登录页'; } function getHotmailAccountsByUsage(mode = 'all', state = latestState) { const accounts = getHotmailAccounts(state); if (typeof filterHotmailAccountsByUsage === 'function') { return filterHotmailAccountsByUsage(accounts, mode); } if (mode === 'used') { return accounts.filter((account) => Boolean(account?.used)); } return accounts.slice(); } function getHotmailBulkActionText(mode, count) { if (typeof getHotmailBulkActionLabel === 'function') { return getHotmailBulkActionLabel(mode, count); } const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0; const prefix = mode === 'used' ? '清空已用' : '全部删除'; const suffix = normalizedCount > 0 ? `(${normalizedCount})` : ''; return `${prefix}${suffix}`; } function getHotmailListToggleText(expanded, count) { if (typeof getHotmailListToggleLabel === 'function') { return getHotmailListToggleLabel(expanded, count); } const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0; const suffix = normalizedCount > 0 ? `(${normalizedCount})` : ''; return `${expanded ? '收起列表' : '展开列表'}${suffix}`; } function updateHotmailListViewport() { const count = getHotmailAccounts().length; const usedCount = getHotmailAccountsByUsage('used').length; if (btnClearUsedHotmailAccounts) { btnClearUsedHotmailAccounts.textContent = getHotmailBulkActionText('used', usedCount); btnClearUsedHotmailAccounts.disabled = usedCount === 0; } if (btnDeleteAllHotmailAccounts) { btnDeleteAllHotmailAccounts.textContent = getHotmailBulkActionText('all', count); btnDeleteAllHotmailAccounts.disabled = count === 0; } if (btnToggleHotmailList) { btnToggleHotmailList.textContent = getHotmailListToggleText(hotmailListExpanded, count); btnToggleHotmailList.setAttribute('aria-expanded', String(hotmailListExpanded)); btnToggleHotmailList.disabled = count === 0; } if (hotmailListShell) { hotmailListShell.classList.toggle('is-expanded', hotmailListExpanded); hotmailListShell.classList.toggle('is-collapsed', !hotmailListExpanded); } } function setHotmailListExpanded(expanded, options = {}) { const { persist = true } = options; hotmailListExpanded = Boolean(expanded); updateHotmailListViewport(); if (persist) { localStorage.setItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY, hotmailListExpanded ? '1' : '0'); } } function initHotmailListExpandedState() { const saved = localStorage.getItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY); setHotmailListExpanded(saved === '1', { persist: false }); } function shouldClearCurrentHotmailSelectionLocally(account) { if (typeof shouldClearHotmailCurrentSelection === 'function') { return shouldClearHotmailCurrentSelection(account); } return Boolean(account) && account.used === true; } function upsertHotmailAccountListLocally(accounts, nextAccount) { if (typeof upsertHotmailAccountInList === 'function') { return upsertHotmailAccountInList(accounts, nextAccount); } const list = Array.isArray(accounts) ? accounts.slice() : []; if (!nextAccount?.id) return list; const existingIndex = list.findIndex((account) => account?.id === nextAccount.id); if (existingIndex === -1) { list.push(nextAccount); return list; } list[existingIndex] = nextAccount; return list; } function refreshHotmailSelectionUI() { renderHotmailAccounts(); if (selectMailProvider.value === 'hotmail-api') { inputEmail.value = getCurrentHotmailEmail(); } } function applyHotmailAccountMutation(account, options = {}) { if (!account?.id) return; const { preserveCurrentSelection = false } = options; const nextState = { hotmailAccounts: upsertHotmailAccountListLocally(getHotmailAccounts(), account), }; if (!preserveCurrentSelection && latestState?.currentHotmailAccountId === account.id && shouldClearCurrentHotmailSelectionLocally(account)) { nextState.currentHotmailAccountId = null; if (selectMailProvider.value === 'hotmail-api') { nextState.email = null; } } syncLatestState(nextState); refreshHotmailSelectionUI(); } function formatDateTime(timestamp) { const value = Number(timestamp); if (!Number.isFinite(value) || value <= 0) { return '未使用'; } return new Date(value).toLocaleString('zh-CN', { hour12: false, timeZone: DISPLAY_TIMEZONE, }); } function getHotmailAvailabilityLabel(account) { if (account.used) return '已用'; return '可分配'; } function getHotmailStatusLabel(account) { if (account.used) return '已用'; switch (account.status) { case 'authorized': return '可用'; case 'error': return '异常'; default: return '待校验'; } } function getHotmailStatusClass(account) { if (account.used) return 'status-used'; return `status-${account.status || 'pending'}`; } function clearHotmailForm() { inputHotmailEmail.value = ''; inputHotmailClientId.value = ''; inputHotmailPassword.value = ''; inputHotmailRefreshToken.value = ''; } function renderHotmailAccounts() { if (!hotmailAccountsList) return; const accounts = getHotmailAccounts(); const currentId = latestState?.currentHotmailAccountId || ''; if (!accounts.length) { hotmailAccountsList.innerHTML = '