sidepanel.js 36 KB

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