sidepanel.js 34 KB

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