sidepanel.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. // sidepanel/sidepanel.js — Side Panel logic
  2. const STATUS_ICONS = {
  3. pending: '',
  4. running: '',
  5. completed: '\u2713', // ✓
  6. failed: '\u2717', // ✗
  7. stopped: '\u25A0', // ■
  8. manual_completed: '跳',
  9. skipped: '跳',
  10. };
  11. const logArea = document.getElementById('log-area');
  12. const displayOauthUrl = document.getElementById('display-oauth-url');
  13. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  14. const displayStatus = document.getElementById('display-status');
  15. const statusBar = document.getElementById('status-bar');
  16. const inputEmail = document.getElementById('input-email');
  17. const inputPassword = document.getElementById('input-password');
  18. const btnFetchEmail = document.getElementById('btn-fetch-email');
  19. const btnTogglePassword = document.getElementById('btn-toggle-password');
  20. const btnSaveSettings = document.getElementById('btn-save-settings');
  21. const btnStop = document.getElementById('btn-stop');
  22. const btnReset = document.getElementById('btn-reset');
  23. const stepsProgress = document.getElementById('steps-progress');
  24. const btnAutoRun = document.getElementById('btn-auto-run');
  25. const btnAutoContinue = document.getElementById('btn-auto-continue');
  26. const autoContinueBar = document.getElementById('auto-continue-bar');
  27. const btnClearLog = document.getElementById('btn-clear-log');
  28. const inputVpsUrl = document.getElementById('input-vps-url');
  29. const inputVpsPassword = document.getElementById('input-vps-password');
  30. const selectMailProvider = document.getElementById('select-mail-provider');
  31. const rowInbucketHost = document.getElementById('row-inbucket-host');
  32. const inputInbucketHost = document.getElementById('input-inbucket-host');
  33. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  34. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  35. const inputRunCount = document.getElementById('input-run-count');
  36. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  37. const STEP_DEFAULT_STATUSES = {
  38. 1: 'pending',
  39. 2: 'pending',
  40. 3: 'pending',
  41. 4: 'pending',
  42. 5: 'pending',
  43. 6: 'pending',
  44. 7: 'pending',
  45. 8: 'pending',
  46. 9: 'pending',
  47. };
  48. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  49. let latestState = null;
  50. let currentAutoRun = {
  51. autoRunning: false,
  52. phase: 'idle',
  53. currentRun: 0,
  54. totalRuns: 1,
  55. attemptRun: 0,
  56. };
  57. let settingsDirty = false;
  58. let settingsSaveInFlight = false;
  59. let settingsAutoSaveTimer = null;
  60. const EYE_OPEN_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>';
  61. const EYE_CLOSED_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 19C5 19 1 12 1 12a21.77 21.77 0 0 1 5.06-6.94"/><path d="M9.9 4.24A10.94 10.94 0 0 1 12 5c7 0 11 7 11 7a21.86 21.86 0 0 1-2.16 3.19"/><path d="M1 1l22 22"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/></svg>';
  62. // ============================================================
  63. // Toast Notifications
  64. // ============================================================
  65. const toastContainer = document.getElementById('toast-container');
  66. const TOAST_ICONS = {
  67. error: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
  68. warn: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
  69. success: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
  70. info: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
  71. };
  72. const LOG_LEVEL_LABELS = {
  73. info: '信息',
  74. ok: '成功',
  75. warn: '警告',
  76. error: '错误',
  77. };
  78. function showToast(message, type = 'error', duration = 4000) {
  79. const toast = document.createElement('div');
  80. toast.className = `toast toast-${type}`;
  81. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  82. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  83. toastContainer.appendChild(toast);
  84. if (duration > 0) {
  85. setTimeout(() => dismissToast(toast), duration);
  86. }
  87. }
  88. function dismissToast(toast) {
  89. if (!toast.parentNode) return;
  90. toast.classList.add('toast-exit');
  91. toast.addEventListener('animationend', () => toast.remove());
  92. }
  93. function isDoneStatus(status) {
  94. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  95. }
  96. function getStepStatuses(state = latestState) {
  97. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  98. }
  99. function syncLatestState(nextState) {
  100. const mergedStepStatuses = nextState?.stepStatuses
  101. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  102. : getStepStatuses(latestState);
  103. latestState = {
  104. ...(latestState || {}),
  105. ...(nextState || {}),
  106. stepStatuses: mergedStepStatuses,
  107. };
  108. }
  109. function syncAutoRunState(source = {}) {
  110. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  111. const autoRunning = source.autoRunning !== undefined
  112. ? Boolean(source.autoRunning)
  113. : (source.autoRunPhase !== undefined || source.phase !== undefined
  114. ? ['running', 'waiting_email', 'retrying'].includes(phase)
  115. : currentAutoRun.autoRunning);
  116. currentAutoRun = {
  117. autoRunning,
  118. phase,
  119. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  120. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  121. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  122. };
  123. }
  124. function isAutoRunLockedPhase() {
  125. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'retrying';
  126. }
  127. function isAutoRunPausedPhase() {
  128. return currentAutoRun.phase === 'waiting_email';
  129. }
  130. function getAutoRunLabel(payload = currentAutoRun) {
  131. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  132. if ((payload.totalRuns || 1) > 1) {
  133. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  134. }
  135. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  136. }
  137. function setDefaultAutoRunButton() {
  138. btnAutoRun.disabled = false;
  139. inputRunCount.disabled = false;
  140. btnAutoRun.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg> 自动';
  141. }
  142. function collectSettingsPayload() {
  143. return {
  144. vpsUrl: inputVpsUrl.value.trim(),
  145. vpsPassword: inputVpsPassword.value,
  146. customPassword: inputPassword.value,
  147. mailProvider: selectMailProvider.value,
  148. inbucketHost: inputInbucketHost.value.trim(),
  149. inbucketMailbox: inputInbucketMailbox.value.trim(),
  150. autoRunSkipFailures: inputAutoSkipFailures.checked,
  151. };
  152. }
  153. function markSettingsDirty(isDirty = true) {
  154. settingsDirty = isDirty;
  155. updateSaveButtonState();
  156. }
  157. function updateSaveButtonState() {
  158. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  159. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  160. }
  161. function scheduleSettingsAutoSave() {
  162. clearTimeout(settingsAutoSaveTimer);
  163. settingsAutoSaveTimer = setTimeout(() => {
  164. saveSettings({ silent: true }).catch(() => {});
  165. }, 500);
  166. }
  167. async function saveSettings(options = {}) {
  168. const { silent = false } = options;
  169. clearTimeout(settingsAutoSaveTimer);
  170. if (!settingsDirty && !settingsSaveInFlight && silent) {
  171. return;
  172. }
  173. const payload = collectSettingsPayload();
  174. settingsSaveInFlight = true;
  175. updateSaveButtonState();
  176. try {
  177. const response = await chrome.runtime.sendMessage({
  178. type: 'SAVE_SETTING',
  179. source: 'sidepanel',
  180. payload,
  181. });
  182. if (response?.error) {
  183. throw new Error(response.error);
  184. }
  185. syncLatestState(payload);
  186. markSettingsDirty(false);
  187. updateMailProviderUI();
  188. updateButtonStates();
  189. if (!silent) {
  190. showToast('配置已保存', 'success', 1800);
  191. }
  192. } catch (err) {
  193. markSettingsDirty(true);
  194. if (!silent) {
  195. showToast(`保存失败:${err.message}`, 'error');
  196. }
  197. throw err;
  198. } finally {
  199. settingsSaveInFlight = false;
  200. updateSaveButtonState();
  201. }
  202. }
  203. function applyAutoRunStatus(payload = currentAutoRun) {
  204. syncAutoRunState(payload);
  205. const runLabel = getAutoRunLabel(currentAutoRun);
  206. const locked = isAutoRunLockedPhase();
  207. const paused = isAutoRunPausedPhase();
  208. inputRunCount.disabled = currentAutoRun.autoRunning;
  209. btnAutoRun.disabled = currentAutoRun.autoRunning;
  210. btnFetchEmail.disabled = locked;
  211. inputEmail.disabled = locked;
  212. switch (currentAutoRun.phase) {
  213. case 'waiting_email':
  214. autoContinueBar.style.display = 'flex';
  215. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  216. break;
  217. case 'running':
  218. autoContinueBar.style.display = 'none';
  219. btnAutoRun.innerHTML = `运行中${runLabel}`;
  220. break;
  221. case 'retrying':
  222. autoContinueBar.style.display = 'none';
  223. btnAutoRun.innerHTML = `重试中${runLabel}`;
  224. break;
  225. default:
  226. autoContinueBar.style.display = 'none';
  227. setDefaultAutoRunButton();
  228. inputEmail.disabled = false;
  229. if (!locked) {
  230. btnFetchEmail.disabled = false;
  231. }
  232. break;
  233. }
  234. updateStopButtonState(paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  235. }
  236. function initializeManualStepActions() {
  237. document.querySelectorAll('.step-row').forEach((row) => {
  238. const step = Number(row.dataset.step);
  239. const statusEl = row.querySelector('.step-status');
  240. if (!statusEl) return;
  241. const actions = document.createElement('div');
  242. actions.className = 'step-actions';
  243. const manualBtn = document.createElement('button');
  244. manualBtn.type = 'button';
  245. manualBtn.className = 'step-manual-btn';
  246. manualBtn.dataset.step = String(step);
  247. manualBtn.title = '跳过此步';
  248. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  249. manualBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="13 17 18 12 13 7"/><polyline points="6 17 11 12 6 7"/></svg>';
  250. manualBtn.addEventListener('click', async (event) => {
  251. event.stopPropagation();
  252. try {
  253. await handleSkipStep(step);
  254. } catch (err) {
  255. showToast(err.message, 'error');
  256. }
  257. });
  258. statusEl.parentNode.replaceChild(actions, statusEl);
  259. actions.appendChild(manualBtn);
  260. actions.appendChild(statusEl);
  261. });
  262. }
  263. // ============================================================
  264. // State Restore on load
  265. // ============================================================
  266. async function restoreState() {
  267. try {
  268. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  269. syncLatestState(state);
  270. syncAutoRunState(state);
  271. if (state.oauthUrl) {
  272. displayOauthUrl.textContent = state.oauthUrl;
  273. displayOauthUrl.classList.add('has-value');
  274. }
  275. if (state.localhostUrl) {
  276. displayLocalhostUrl.textContent = state.localhostUrl;
  277. displayLocalhostUrl.classList.add('has-value');
  278. }
  279. if (state.email) {
  280. inputEmail.value = state.email;
  281. }
  282. syncPasswordField(state);
  283. if (state.vpsUrl) {
  284. inputVpsUrl.value = state.vpsUrl;
  285. }
  286. if (state.vpsPassword) {
  287. inputVpsPassword.value = state.vpsPassword;
  288. }
  289. if (state.mailProvider) {
  290. selectMailProvider.value = state.mailProvider;
  291. }
  292. if (state.inbucketHost) {
  293. inputInbucketHost.value = state.inbucketHost;
  294. }
  295. if (state.inbucketMailbox) {
  296. inputInbucketMailbox.value = state.inbucketMailbox;
  297. }
  298. inputAutoSkipFailures.checked = Boolean(state.autoRunSkipFailures);
  299. if (state.stepStatuses) {
  300. for (const [step, status] of Object.entries(state.stepStatuses)) {
  301. updateStepUI(Number(step), status);
  302. }
  303. }
  304. if (state.logs) {
  305. for (const entry of state.logs) {
  306. appendLog(entry);
  307. }
  308. }
  309. applyAutoRunStatus(state);
  310. markSettingsDirty(false);
  311. updateStatusDisplay(latestState);
  312. updateProgressCounter();
  313. updateMailProviderUI();
  314. updateButtonStates();
  315. } catch (err) {
  316. console.error('Failed to restore state:', err);
  317. }
  318. }
  319. function syncPasswordField(state) {
  320. inputPassword.value = state.customPassword || state.password || '';
  321. }
  322. function updateMailProviderUI() {
  323. const useInbucket = selectMailProvider.value === 'inbucket';
  324. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  325. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  326. }
  327. // ============================================================
  328. // UI Updates
  329. // ============================================================
  330. function updateStepUI(step, status) {
  331. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  332. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  333. syncLatestState({
  334. stepStatuses: {
  335. ...getStepStatuses(),
  336. [step]: status,
  337. },
  338. });
  339. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  340. if (row) {
  341. row.className = `step-row ${status}`;
  342. }
  343. updateButtonStates();
  344. updateProgressCounter();
  345. }
  346. function updateProgressCounter() {
  347. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  348. stepsProgress.textContent = `${completed} / 9`;
  349. }
  350. function updateButtonStates() {
  351. const statuses = getStepStatuses();
  352. const anyRunning = Object.values(statuses).some(s => s === 'running');
  353. const autoLocked = isAutoRunLockedPhase();
  354. for (let step = 1; step <= 9; step++) {
  355. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  356. if (!btn) continue;
  357. if (anyRunning || autoLocked) {
  358. btn.disabled = true;
  359. } else if (step === 1) {
  360. btn.disabled = false;
  361. } else {
  362. const prevStatus = statuses[step - 1];
  363. const currentStatus = statuses[step];
  364. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  365. }
  366. }
  367. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  368. const step = Number(btn.dataset.step);
  369. const currentStatus = statuses[step];
  370. const prevStatus = statuses[step - 1];
  371. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  372. btn.style.display = 'none';
  373. btn.disabled = true;
  374. btn.title = '当前不可跳过';
  375. return;
  376. }
  377. if (step > 1 && !isDoneStatus(prevStatus)) {
  378. btn.style.display = 'none';
  379. btn.disabled = true;
  380. btn.title = `请先完成步骤 ${step - 1}`;
  381. return;
  382. }
  383. btn.style.display = '';
  384. btn.disabled = false;
  385. btn.title = `跳过步骤 ${step}`;
  386. });
  387. updateStopButtonState(anyRunning || isAutoRunPausedPhase() || autoLocked);
  388. }
  389. function updateStopButtonState(active) {
  390. btnStop.disabled = !active;
  391. }
  392. function updateStatusDisplay(state) {
  393. if (!state || !state.stepStatuses) return;
  394. statusBar.className = 'status-bar';
  395. if (isAutoRunPausedPhase()) {
  396. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  397. statusBar.classList.add('paused');
  398. return;
  399. }
  400. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  401. if (running) {
  402. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  403. statusBar.classList.add('running');
  404. return;
  405. }
  406. if (isAutoRunLockedPhase()) {
  407. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  408. statusBar.classList.add('running');
  409. return;
  410. }
  411. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  412. if (failed) {
  413. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  414. statusBar.classList.add('failed');
  415. return;
  416. }
  417. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  418. if (stopped) {
  419. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  420. statusBar.classList.add('stopped');
  421. return;
  422. }
  423. const lastCompleted = Object.entries(state.stepStatuses)
  424. .filter(([, s]) => isDoneStatus(s))
  425. .map(([k]) => Number(k))
  426. .sort((a, b) => b - a)[0];
  427. if (lastCompleted === 9) {
  428. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  429. statusBar.classList.add('completed');
  430. } else if (lastCompleted) {
  431. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  432. ? `步骤 ${lastCompleted} 已跳过`
  433. : `步骤 ${lastCompleted} 已完成`;
  434. } else {
  435. displayStatus.textContent = '就绪';
  436. }
  437. }
  438. function appendLog(entry) {
  439. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  440. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  441. const line = document.createElement('div');
  442. line.className = `log-line log-${entry.level}`;
  443. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  444. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  445. let html = `<span class="log-time">${time}</span> `;
  446. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  447. if (stepNum) {
  448. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  449. }
  450. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  451. line.innerHTML = html;
  452. logArea.appendChild(line);
  453. logArea.scrollTop = logArea.scrollHeight;
  454. }
  455. function escapeHtml(text) {
  456. const div = document.createElement('div');
  457. div.textContent = text;
  458. return div.innerHTML;
  459. }
  460. async function fetchDuckEmail(options = {}) {
  461. const { showFailureToast = true } = options;
  462. const defaultLabel = '获取';
  463. btnFetchEmail.disabled = true;
  464. btnFetchEmail.textContent = '...';
  465. try {
  466. const response = await chrome.runtime.sendMessage({
  467. type: 'FETCH_DUCK_EMAIL',
  468. source: 'sidepanel',
  469. payload: { generateNew: true },
  470. });
  471. if (response?.error) {
  472. throw new Error(response.error);
  473. }
  474. if (!response?.email) {
  475. throw new Error('未返回 Duck 邮箱。');
  476. }
  477. inputEmail.value = response.email;
  478. showToast(`已获取 ${response.email}`, 'success', 2500);
  479. return response.email;
  480. } catch (err) {
  481. if (showFailureToast) {
  482. showToast(`自动获取失败:${err.message}`, 'error');
  483. }
  484. throw err;
  485. } finally {
  486. btnFetchEmail.disabled = false;
  487. btnFetchEmail.textContent = defaultLabel;
  488. }
  489. }
  490. function syncPasswordToggleLabel() {
  491. const isHidden = inputPassword.type === 'password';
  492. btnTogglePassword.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  493. btnTogglePassword.setAttribute('aria-label', isHidden ? '显示密码' : '隐藏密码');
  494. btnTogglePassword.title = isHidden ? '显示密码' : '隐藏密码';
  495. }
  496. async function maybeTakeoverAutoRun(actionLabel) {
  497. if (!isAutoRunPausedPhase()) {
  498. return true;
  499. }
  500. const confirmed = confirm(`当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`);
  501. if (!confirmed) {
  502. return false;
  503. }
  504. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  505. return true;
  506. }
  507. async function handleSkipStep(step) {
  508. if (!(await maybeTakeoverAutoRun(`跳过步骤 ${step}`))) {
  509. return;
  510. }
  511. const confirmed = confirm(`这不会真正执行步骤 ${step},只会直接跳过该步骤并放行后续步骤。是否继续?`);
  512. if (!confirmed) {
  513. return;
  514. }
  515. const response = await chrome.runtime.sendMessage({
  516. type: 'SKIP_STEP',
  517. source: 'sidepanel',
  518. payload: { step },
  519. });
  520. if (response?.error) {
  521. throw new Error(response.error);
  522. }
  523. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  524. }
  525. // ============================================================
  526. // Button Handlers
  527. // ============================================================
  528. document.querySelectorAll('.step-btn').forEach(btn => {
  529. btn.addEventListener('click', async () => {
  530. try {
  531. const step = Number(btn.dataset.step);
  532. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  533. return;
  534. }
  535. if (step === 3) {
  536. if (inputPassword.value !== (latestState?.customPassword || '')) {
  537. await chrome.runtime.sendMessage({
  538. type: 'SAVE_SETTING',
  539. source: 'sidepanel',
  540. payload: { customPassword: inputPassword.value },
  541. });
  542. syncLatestState({ customPassword: inputPassword.value });
  543. }
  544. let email = inputEmail.value.trim();
  545. if (!email) {
  546. try {
  547. email = await fetchDuckEmail({ showFailureToast: false });
  548. } catch (err) {
  549. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  550. return;
  551. }
  552. }
  553. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  554. if (response?.error) {
  555. throw new Error(response.error);
  556. }
  557. } else {
  558. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  559. if (response?.error) {
  560. throw new Error(response.error);
  561. }
  562. }
  563. } catch (err) {
  564. showToast(err.message, 'error');
  565. }
  566. });
  567. });
  568. btnFetchEmail.addEventListener('click', async () => {
  569. await fetchDuckEmail().catch(() => {});
  570. });
  571. btnTogglePassword.addEventListener('click', () => {
  572. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  573. syncPasswordToggleLabel();
  574. });
  575. btnSaveSettings.addEventListener('click', async () => {
  576. if (!settingsDirty) {
  577. showToast('配置已是最新', 'info', 1400);
  578. return;
  579. }
  580. await saveSettings({ silent: false }).catch(() => {});
  581. });
  582. btnStop.addEventListener('click', async () => {
  583. btnStop.disabled = true;
  584. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  585. showToast('正在停止当前流程...', 'warn', 2000);
  586. });
  587. // Auto Run
  588. btnAutoRun.addEventListener('click', async () => {
  589. const totalRuns = parseInt(inputRunCount.value) || 1;
  590. btnAutoRun.disabled = true;
  591. inputRunCount.disabled = true;
  592. btnAutoRun.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 运行中...';
  593. await chrome.runtime.sendMessage({
  594. type: 'AUTO_RUN',
  595. source: 'sidepanel',
  596. payload: {
  597. totalRuns,
  598. autoRunSkipFailures: inputAutoSkipFailures.checked,
  599. },
  600. });
  601. });
  602. btnAutoContinue.addEventListener('click', async () => {
  603. const email = inputEmail.value.trim();
  604. if (!email) {
  605. showToast('请先获取或粘贴 DuckDuckGo 邮箱。', 'warn');
  606. return;
  607. }
  608. autoContinueBar.style.display = 'none';
  609. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  610. });
  611. // Reset
  612. btnReset.addEventListener('click', async () => {
  613. if (confirm('确认重置全部步骤和数据吗?')) {
  614. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  615. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES });
  616. syncAutoRunState({ autoRunning: false, autoRunPhase: 'idle', autoRunCurrentRun: 0, autoRunTotalRuns: 1, autoRunAttemptRun: 0 });
  617. displayOauthUrl.textContent = '等待中...';
  618. displayOauthUrl.classList.remove('has-value');
  619. displayLocalhostUrl.textContent = '等待中...';
  620. displayLocalhostUrl.classList.remove('has-value');
  621. inputEmail.value = '';
  622. displayStatus.textContent = '就绪';
  623. statusBar.className = 'status-bar';
  624. logArea.innerHTML = '';
  625. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  626. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  627. setDefaultAutoRunButton();
  628. applyAutoRunStatus(currentAutoRun);
  629. markSettingsDirty(false);
  630. updateStopButtonState(false);
  631. updateButtonStates();
  632. updateProgressCounter();
  633. }
  634. });
  635. // Clear log
  636. btnClearLog.addEventListener('click', () => {
  637. logArea.innerHTML = '';
  638. });
  639. // Save settings on change
  640. inputEmail.addEventListener('change', async () => {
  641. const email = inputEmail.value.trim();
  642. if (email) {
  643. await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  644. }
  645. });
  646. inputEmail.addEventListener('input', updateButtonStates);
  647. inputVpsUrl.addEventListener('input', () => {
  648. markSettingsDirty(true);
  649. scheduleSettingsAutoSave();
  650. });
  651. inputVpsUrl.addEventListener('blur', () => {
  652. saveSettings({ silent: true }).catch(() => {});
  653. });
  654. inputVpsPassword.addEventListener('input', () => {
  655. markSettingsDirty(true);
  656. scheduleSettingsAutoSave();
  657. });
  658. inputVpsPassword.addEventListener('blur', () => {
  659. saveSettings({ silent: true }).catch(() => {});
  660. });
  661. inputPassword.addEventListener('input', () => {
  662. markSettingsDirty(true);
  663. updateButtonStates();
  664. scheduleSettingsAutoSave();
  665. });
  666. inputPassword.addEventListener('blur', () => {
  667. saveSettings({ silent: true }).catch(() => {});
  668. });
  669. selectMailProvider.addEventListener('change', () => {
  670. updateMailProviderUI();
  671. markSettingsDirty(true);
  672. saveSettings({ silent: true }).catch(() => {});
  673. });
  674. inputInbucketMailbox.addEventListener('input', () => {
  675. markSettingsDirty(true);
  676. scheduleSettingsAutoSave();
  677. });
  678. inputInbucketMailbox.addEventListener('blur', () => {
  679. saveSettings({ silent: true }).catch(() => {});
  680. });
  681. inputInbucketHost.addEventListener('input', () => {
  682. markSettingsDirty(true);
  683. scheduleSettingsAutoSave();
  684. });
  685. inputInbucketHost.addEventListener('blur', () => {
  686. saveSettings({ silent: true }).catch(() => {});
  687. });
  688. inputAutoSkipFailures.addEventListener('change', () => {
  689. markSettingsDirty(true);
  690. saveSettings({ silent: true }).catch(() => {});
  691. });
  692. // ============================================================
  693. // Listen for Background broadcasts
  694. // ============================================================
  695. chrome.runtime.onMessage.addListener((message) => {
  696. switch (message.type) {
  697. case 'LOG_ENTRY':
  698. appendLog(message.payload);
  699. if (message.payload.level === 'error') {
  700. showToast(message.payload.message, 'error');
  701. }
  702. break;
  703. case 'STEP_STATUS_CHANGED': {
  704. const { step, status } = message.payload;
  705. updateStepUI(step, status);
  706. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  707. syncLatestState(state);
  708. syncAutoRunState(state);
  709. updateStatusDisplay(latestState);
  710. updateButtonStates();
  711. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  712. syncPasswordField(state);
  713. if (state.oauthUrl) {
  714. displayOauthUrl.textContent = state.oauthUrl;
  715. displayOauthUrl.classList.add('has-value');
  716. }
  717. if (state.localhostUrl) {
  718. displayLocalhostUrl.textContent = state.localhostUrl;
  719. displayLocalhostUrl.classList.add('has-value');
  720. }
  721. }
  722. }
  723. ).catch(() => {});
  724. break;
  725. }
  726. case 'AUTO_RUN_RESET': {
  727. // Full UI reset for next run
  728. syncLatestState({
  729. oauthUrl: null,
  730. localhostUrl: null,
  731. email: null,
  732. password: null,
  733. stepStatuses: STEP_DEFAULT_STATUSES,
  734. logs: [],
  735. });
  736. displayOauthUrl.textContent = '等待中...';
  737. displayOauthUrl.classList.remove('has-value');
  738. displayLocalhostUrl.textContent = '等待中...';
  739. displayLocalhostUrl.classList.remove('has-value');
  740. inputEmail.value = '';
  741. displayStatus.textContent = '就绪';
  742. statusBar.className = 'status-bar';
  743. logArea.innerHTML = '';
  744. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  745. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  746. applyAutoRunStatus(currentAutoRun);
  747. updateProgressCounter();
  748. updateButtonStates();
  749. break;
  750. }
  751. case 'DATA_UPDATED': {
  752. syncLatestState(message.payload);
  753. if (message.payload.email) {
  754. inputEmail.value = message.payload.email;
  755. }
  756. if (message.payload.password !== undefined) {
  757. inputPassword.value = message.payload.password || '';
  758. }
  759. if (message.payload.oauthUrl) {
  760. displayOauthUrl.textContent = message.payload.oauthUrl;
  761. displayOauthUrl.classList.add('has-value');
  762. }
  763. if (message.payload.localhostUrl) {
  764. displayLocalhostUrl.textContent = message.payload.localhostUrl;
  765. displayLocalhostUrl.classList.add('has-value');
  766. }
  767. break;
  768. }
  769. case 'AUTO_RUN_STATUS': {
  770. syncLatestState({
  771. autoRunning: ['running', 'waiting_email', 'retrying'].includes(message.payload.phase),
  772. autoRunPhase: message.payload.phase,
  773. autoRunCurrentRun: message.payload.currentRun,
  774. autoRunTotalRuns: message.payload.totalRuns,
  775. autoRunAttemptRun: message.payload.attemptRun,
  776. });
  777. applyAutoRunStatus(message.payload);
  778. updateStatusDisplay(latestState);
  779. updateButtonStates();
  780. break;
  781. }
  782. }
  783. });
  784. // ============================================================
  785. // Theme Toggle
  786. // ============================================================
  787. const btnTheme = document.getElementById('btn-theme');
  788. function setTheme(theme) {
  789. document.documentElement.setAttribute('data-theme', theme);
  790. localStorage.setItem('multipage-theme', theme);
  791. }
  792. function initTheme() {
  793. const saved = localStorage.getItem('multipage-theme');
  794. if (saved) {
  795. setTheme(saved);
  796. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  797. setTheme('dark');
  798. }
  799. }
  800. btnTheme.addEventListener('click', () => {
  801. const current = document.documentElement.getAttribute('data-theme');
  802. setTheme(current === 'dark' ? 'light' : 'dark');
  803. });
  804. // ============================================================
  805. // Init
  806. // ============================================================
  807. initializeManualStepActions();
  808. initTheme();
  809. updateSaveButtonState();
  810. restoreState().then(() => {
  811. syncPasswordToggleLabel();
  812. updateButtonStates();
  813. updateStatusDisplay(latestState);
  814. });