sidepanel.js 29 KB

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