sidepanel.js 32 KB

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