sidepanel.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  1. // sidepanel/sidepanel.js — Side Panel logic
  2. const STATUS_ICONS = {
  3. pending: '',
  4. running: '',
  5. completed: '\u2713', // ✓
  6. failed: '\u2717', // ✗
  7. stopped: '\u25A0', // ■
  8. manual_completed: '跳',
  9. skipped: '跳',
  10. };
  11. const logArea = document.getElementById('log-area');
  12. const displayOauthUrl = document.getElementById('display-oauth-url');
  13. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  14. const displayStatus = document.getElementById('display-status');
  15. const statusBar = document.getElementById('status-bar');
  16. const inputEmail = document.getElementById('input-email');
  17. const inputPassword = document.getElementById('input-password');
  18. const btnFetchEmail = document.getElementById('btn-fetch-email');
  19. const btnTogglePassword = document.getElementById('btn-toggle-password');
  20. const btnSaveSettings = document.getElementById('btn-save-settings');
  21. const btnStop = document.getElementById('btn-stop');
  22. const btnReset = document.getElementById('btn-reset');
  23. const stepsProgress = document.getElementById('steps-progress');
  24. const btnAutoRun = document.getElementById('btn-auto-run');
  25. const btnAutoContinue = document.getElementById('btn-auto-continue');
  26. const autoContinueBar = document.getElementById('auto-continue-bar');
  27. const btnClearLog = document.getElementById('btn-clear-log');
  28. const inputVpsUrl = document.getElementById('input-vps-url');
  29. const inputVpsPassword = document.getElementById('input-vps-password');
  30. const selectMailProvider = document.getElementById('select-mail-provider');
  31. const hotmailSection = document.getElementById('hotmail-section');
  32. const inputHotmailEmail = document.getElementById('input-hotmail-email');
  33. const inputHotmailClientId = document.getElementById('input-hotmail-client-id');
  34. const inputHotmailPassword = document.getElementById('input-hotmail-password');
  35. const inputHotmailRefreshToken = document.getElementById('input-hotmail-refresh-token');
  36. const inputHotmailImport = document.getElementById('input-hotmail-import');
  37. const btnAddHotmailAccount = document.getElementById('btn-add-hotmail-account');
  38. const btnImportHotmailAccounts = document.getElementById('btn-import-hotmail-accounts');
  39. const btnClearUsedHotmailAccounts = document.getElementById('btn-clear-used-hotmail-accounts');
  40. const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotmail-accounts');
  41. const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list');
  42. const hotmailListShell = document.getElementById('hotmail-list-shell');
  43. const hotmailAccountsList = document.getElementById('hotmail-accounts-list');
  44. const rowInbucketHost = document.getElementById('row-inbucket-host');
  45. const inputInbucketHost = document.getElementById('input-inbucket-host');
  46. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  47. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  48. const inputRunCount = document.getElementById('input-run-count');
  49. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  50. const autoStartModal = document.getElementById('auto-start-modal');
  51. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  52. const autoStartMessage = document.getElementById('auto-start-message');
  53. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  54. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  55. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  56. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  57. const autoHintText = document.querySelector('.auto-hint');
  58. const STEP_DEFAULT_STATUSES = {
  59. 1: 'pending',
  60. 2: 'pending',
  61. 3: 'pending',
  62. 4: 'pending',
  63. 5: 'pending',
  64. 6: 'pending',
  65. 7: 'pending',
  66. 8: 'pending',
  67. 9: 'pending',
  68. };
  69. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  70. let latestState = null;
  71. let currentAutoRun = {
  72. autoRunning: false,
  73. phase: 'idle',
  74. currentRun: 0,
  75. totalRuns: 1,
  76. attemptRun: 0,
  77. };
  78. let settingsDirty = false;
  79. let settingsSaveInFlight = false;
  80. let settingsAutoSaveTimer = null;
  81. let modalChoiceResolver = null;
  82. let currentModalActions = [];
  83. let hotmailActionInFlight = false;
  84. let hotmailListExpanded = false;
  85. 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>';
  86. 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>';
  87. const COPY_ICON = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
  88. const parseHotmailImportText = window.HotmailUtils?.parseHotmailImportText;
  89. const shouldClearHotmailCurrentSelection = window.HotmailUtils?.shouldClearHotmailCurrentSelection;
  90. const upsertHotmailAccountInList = window.HotmailUtils?.upsertHotmailAccountInList;
  91. const filterHotmailAccountsByUsage = window.HotmailUtils?.filterHotmailAccountsByUsage;
  92. const getHotmailBulkActionLabel = window.HotmailUtils?.getHotmailBulkActionLabel;
  93. const getHotmailListToggleLabel = window.HotmailUtils?.getHotmailListToggleLabel;
  94. const HOTMAIL_LIST_EXPANDED_STORAGE_KEY = 'multipage-hotmail-list-expanded';
  95. // ============================================================
  96. // Toast Notifications
  97. // ============================================================
  98. const toastContainer = document.getElementById('toast-container');
  99. const TOAST_ICONS = {
  100. 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>',
  101. 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>',
  102. 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>',
  103. 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>',
  104. };
  105. const LOG_LEVEL_LABELS = {
  106. info: '信息',
  107. ok: '成功',
  108. warn: '警告',
  109. error: '错误',
  110. };
  111. function showToast(message, type = 'error', duration = 4000) {
  112. const toast = document.createElement('div');
  113. toast.className = `toast toast-${type}`;
  114. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  115. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  116. toastContainer.appendChild(toast);
  117. if (duration > 0) {
  118. setTimeout(() => dismissToast(toast), duration);
  119. }
  120. }
  121. function dismissToast(toast) {
  122. if (!toast.parentNode) return;
  123. toast.classList.add('toast-exit');
  124. toast.addEventListener('animationend', () => toast.remove());
  125. }
  126. function resetActionModalButtons() {
  127. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  128. buttons.forEach((button) => {
  129. if (!button) return;
  130. button.hidden = true;
  131. button.disabled = false;
  132. button.onclick = null;
  133. });
  134. currentModalActions = [];
  135. }
  136. function configureActionModalButton(button, action) {
  137. if (!button) return;
  138. if (!action) {
  139. button.hidden = true;
  140. button.onclick = null;
  141. return;
  142. }
  143. button.hidden = false;
  144. button.disabled = false;
  145. button.textContent = action.label;
  146. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  147. button.onclick = () => resolveModalChoice(action.id);
  148. }
  149. function resolveModalChoice(choice) {
  150. if (modalChoiceResolver) {
  151. modalChoiceResolver(choice);
  152. modalChoiceResolver = null;
  153. }
  154. resetActionModalButtons();
  155. if (autoStartModal) {
  156. autoStartModal.hidden = true;
  157. }
  158. }
  159. function openActionModal({ title, message, actions }) {
  160. if (!autoStartModal) {
  161. return Promise.resolve(null);
  162. }
  163. if (modalChoiceResolver) {
  164. resolveModalChoice(null);
  165. }
  166. autoStartTitle.textContent = title;
  167. autoStartMessage.textContent = message;
  168. currentModalActions = actions || [];
  169. configureActionModalButton(btnAutoStartCancel, currentModalActions[0]);
  170. configureActionModalButton(btnAutoStartRestart, currentModalActions[1]);
  171. configureActionModalButton(btnAutoStartContinue, currentModalActions[2]);
  172. autoStartModal.hidden = false;
  173. return new Promise((resolve) => {
  174. modalChoiceResolver = resolve;
  175. });
  176. }
  177. function openAutoStartChoiceDialog(startStep) {
  178. return openActionModal({
  179. title: '启动自动',
  180. message: `检测到当前已有流程进度。继续当前会从步骤 ${startStep} 开始自动执行,重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  181. actions: [
  182. { id: null, label: '取消', variant: 'btn-ghost' },
  183. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  184. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  185. ],
  186. });
  187. }
  188. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary' }) {
  189. const choice = await openActionModal({
  190. title,
  191. message,
  192. actions: [
  193. { id: null, label: '取消', variant: 'btn-ghost' },
  194. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  195. ],
  196. });
  197. return choice === 'confirm';
  198. }
  199. function isDoneStatus(status) {
  200. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  201. }
  202. function getStepStatuses(state = latestState) {
  203. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  204. }
  205. function getFirstUnfinishedStep(state = latestState) {
  206. const statuses = getStepStatuses(state);
  207. for (let step = 1; step <= 9; step++) {
  208. if (!isDoneStatus(statuses[step])) {
  209. return step;
  210. }
  211. }
  212. return null;
  213. }
  214. function hasSavedProgress(state = latestState) {
  215. const statuses = getStepStatuses(state);
  216. return Object.values(statuses).some((status) => status !== 'pending');
  217. }
  218. function shouldOfferAutoModeChoice(state = latestState) {
  219. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  220. }
  221. function syncLatestState(nextState) {
  222. const mergedStepStatuses = nextState?.stepStatuses
  223. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  224. : getStepStatuses(latestState);
  225. latestState = {
  226. ...(latestState || {}),
  227. ...(nextState || {}),
  228. stepStatuses: mergedStepStatuses,
  229. };
  230. }
  231. function syncAutoRunState(source = {}) {
  232. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  233. const autoRunning = source.autoRunning !== undefined
  234. ? Boolean(source.autoRunning)
  235. : (source.autoRunPhase !== undefined || source.phase !== undefined
  236. ? ['running', 'waiting_email', 'retrying'].includes(phase)
  237. : currentAutoRun.autoRunning);
  238. currentAutoRun = {
  239. autoRunning,
  240. phase,
  241. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  242. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  243. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  244. };
  245. }
  246. function isAutoRunLockedPhase() {
  247. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'retrying';
  248. }
  249. function isAutoRunPausedPhase() {
  250. return currentAutoRun.phase === 'waiting_email';
  251. }
  252. function getAutoRunLabel(payload = currentAutoRun) {
  253. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  254. if ((payload.totalRuns || 1) > 1) {
  255. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  256. }
  257. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  258. }
  259. function setDefaultAutoRunButton() {
  260. btnAutoRun.disabled = false;
  261. inputRunCount.disabled = false;
  262. 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> 自动';
  263. }
  264. function collectSettingsPayload() {
  265. return {
  266. vpsUrl: inputVpsUrl.value.trim(),
  267. vpsPassword: inputVpsPassword.value,
  268. customPassword: inputPassword.value,
  269. mailProvider: selectMailProvider.value,
  270. inbucketHost: inputInbucketHost.value.trim(),
  271. inbucketMailbox: inputInbucketMailbox.value.trim(),
  272. autoRunSkipFailures: inputAutoSkipFailures.checked,
  273. };
  274. }
  275. function markSettingsDirty(isDirty = true) {
  276. settingsDirty = isDirty;
  277. updateSaveButtonState();
  278. }
  279. function updateSaveButtonState() {
  280. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  281. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  282. }
  283. function scheduleSettingsAutoSave() {
  284. clearTimeout(settingsAutoSaveTimer);
  285. settingsAutoSaveTimer = setTimeout(() => {
  286. saveSettings({ silent: true }).catch(() => {});
  287. }, 500);
  288. }
  289. async function saveSettings(options = {}) {
  290. const { silent = false } = options;
  291. clearTimeout(settingsAutoSaveTimer);
  292. if (!settingsDirty && !settingsSaveInFlight && silent) {
  293. return;
  294. }
  295. const payload = collectSettingsPayload();
  296. settingsSaveInFlight = true;
  297. updateSaveButtonState();
  298. try {
  299. const response = await chrome.runtime.sendMessage({
  300. type: 'SAVE_SETTING',
  301. source: 'sidepanel',
  302. payload,
  303. });
  304. if (response?.error) {
  305. throw new Error(response.error);
  306. }
  307. syncLatestState(payload);
  308. markSettingsDirty(false);
  309. updateMailProviderUI();
  310. updateButtonStates();
  311. if (!silent) {
  312. showToast('配置已保存', 'success', 1800);
  313. }
  314. } catch (err) {
  315. markSettingsDirty(true);
  316. if (!silent) {
  317. showToast(`保存失败:${err.message}`, 'error');
  318. }
  319. throw err;
  320. } finally {
  321. settingsSaveInFlight = false;
  322. updateSaveButtonState();
  323. }
  324. }
  325. function applyAutoRunStatus(payload = currentAutoRun) {
  326. syncAutoRunState(payload);
  327. const runLabel = getAutoRunLabel(currentAutoRun);
  328. const locked = isAutoRunLockedPhase();
  329. const paused = isAutoRunPausedPhase();
  330. inputRunCount.disabled = currentAutoRun.autoRunning;
  331. btnAutoRun.disabled = currentAutoRun.autoRunning;
  332. btnFetchEmail.disabled = locked;
  333. inputEmail.disabled = locked;
  334. switch (currentAutoRun.phase) {
  335. case 'waiting_email':
  336. autoContinueBar.style.display = 'flex';
  337. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  338. break;
  339. case 'running':
  340. autoContinueBar.style.display = 'none';
  341. btnAutoRun.innerHTML = `运行中${runLabel}`;
  342. break;
  343. case 'retrying':
  344. autoContinueBar.style.display = 'none';
  345. btnAutoRun.innerHTML = `重试中${runLabel}`;
  346. break;
  347. default:
  348. autoContinueBar.style.display = 'none';
  349. setDefaultAutoRunButton();
  350. inputEmail.disabled = false;
  351. if (!locked) {
  352. btnFetchEmail.disabled = false;
  353. }
  354. break;
  355. }
  356. updateStopButtonState(paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  357. }
  358. function initializeManualStepActions() {
  359. document.querySelectorAll('.step-row').forEach((row) => {
  360. const step = Number(row.dataset.step);
  361. const statusEl = row.querySelector('.step-status');
  362. if (!statusEl) return;
  363. const actions = document.createElement('div');
  364. actions.className = 'step-actions';
  365. const manualBtn = document.createElement('button');
  366. manualBtn.type = 'button';
  367. manualBtn.className = 'step-manual-btn';
  368. manualBtn.dataset.step = String(step);
  369. manualBtn.title = '跳过此步';
  370. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  371. 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>';
  372. manualBtn.addEventListener('click', async (event) => {
  373. event.stopPropagation();
  374. try {
  375. await handleSkipStep(step);
  376. } catch (err) {
  377. showToast(err.message, 'error');
  378. }
  379. });
  380. statusEl.parentNode.replaceChild(actions, statusEl);
  381. actions.appendChild(manualBtn);
  382. actions.appendChild(statusEl);
  383. });
  384. }
  385. // ============================================================
  386. // State Restore on load
  387. // ============================================================
  388. async function restoreState() {
  389. try {
  390. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  391. syncLatestState(state);
  392. syncAutoRunState(state);
  393. if (state.oauthUrl) {
  394. displayOauthUrl.textContent = state.oauthUrl;
  395. displayOauthUrl.classList.add('has-value');
  396. }
  397. if (state.localhostUrl) {
  398. displayLocalhostUrl.textContent = state.localhostUrl;
  399. displayLocalhostUrl.classList.add('has-value');
  400. }
  401. if (state.email) {
  402. inputEmail.value = state.email;
  403. }
  404. syncPasswordField(state);
  405. if (state.vpsUrl) {
  406. inputVpsUrl.value = state.vpsUrl;
  407. }
  408. if (state.vpsPassword) {
  409. inputVpsPassword.value = state.vpsPassword;
  410. }
  411. if (state.mailProvider) {
  412. selectMailProvider.value = state.mailProvider;
  413. }
  414. if (state.inbucketHost) {
  415. inputInbucketHost.value = state.inbucketHost;
  416. }
  417. if (state.inbucketMailbox) {
  418. inputInbucketMailbox.value = state.inbucketMailbox;
  419. }
  420. inputAutoSkipFailures.checked = Boolean(state.autoRunSkipFailures);
  421. if (state.stepStatuses) {
  422. for (const [step, status] of Object.entries(state.stepStatuses)) {
  423. updateStepUI(Number(step), status);
  424. }
  425. }
  426. if (state.logs) {
  427. for (const entry of state.logs) {
  428. appendLog(entry);
  429. }
  430. }
  431. applyAutoRunStatus(state);
  432. markSettingsDirty(false);
  433. updateStatusDisplay(latestState);
  434. updateProgressCounter();
  435. updateMailProviderUI();
  436. updateButtonStates();
  437. } catch (err) {
  438. console.error('Failed to restore state:', err);
  439. }
  440. }
  441. function syncPasswordField(state) {
  442. inputPassword.value = state.customPassword || state.password || '';
  443. }
  444. function getHotmailAccounts(state = latestState) {
  445. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  446. }
  447. function getCurrentHotmailAccount(state = latestState) {
  448. const currentId = state?.currentHotmailAccountId;
  449. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  450. }
  451. function getHotmailAccountsByUsage(mode = 'all', state = latestState) {
  452. const accounts = getHotmailAccounts(state);
  453. if (typeof filterHotmailAccountsByUsage === 'function') {
  454. return filterHotmailAccountsByUsage(accounts, mode);
  455. }
  456. if (mode === 'used') {
  457. return accounts.filter((account) => Boolean(account?.used));
  458. }
  459. return accounts.slice();
  460. }
  461. function getHotmailBulkActionText(mode, count) {
  462. if (typeof getHotmailBulkActionLabel === 'function') {
  463. return getHotmailBulkActionLabel(mode, count);
  464. }
  465. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  466. const prefix = mode === 'used' ? '清空已用' : '全部删除';
  467. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  468. return `${prefix}${suffix}`;
  469. }
  470. function getHotmailListToggleText(expanded, count) {
  471. if (typeof getHotmailListToggleLabel === 'function') {
  472. return getHotmailListToggleLabel(expanded, count);
  473. }
  474. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  475. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  476. return `${expanded ? '收起列表' : '展开列表'}${suffix}`;
  477. }
  478. function updateHotmailListViewport() {
  479. const count = getHotmailAccounts().length;
  480. const usedCount = getHotmailAccountsByUsage('used').length;
  481. if (btnClearUsedHotmailAccounts) {
  482. btnClearUsedHotmailAccounts.textContent = getHotmailBulkActionText('used', usedCount);
  483. btnClearUsedHotmailAccounts.disabled = usedCount === 0;
  484. }
  485. if (btnDeleteAllHotmailAccounts) {
  486. btnDeleteAllHotmailAccounts.textContent = getHotmailBulkActionText('all', count);
  487. btnDeleteAllHotmailAccounts.disabled = count === 0;
  488. }
  489. if (btnToggleHotmailList) {
  490. btnToggleHotmailList.textContent = getHotmailListToggleText(hotmailListExpanded, count);
  491. btnToggleHotmailList.setAttribute('aria-expanded', String(hotmailListExpanded));
  492. btnToggleHotmailList.disabled = count === 0;
  493. }
  494. if (hotmailListShell) {
  495. hotmailListShell.classList.toggle('is-expanded', hotmailListExpanded);
  496. hotmailListShell.classList.toggle('is-collapsed', !hotmailListExpanded);
  497. }
  498. }
  499. function setHotmailListExpanded(expanded, options = {}) {
  500. const { persist = true } = options;
  501. hotmailListExpanded = Boolean(expanded);
  502. updateHotmailListViewport();
  503. if (persist) {
  504. localStorage.setItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY, hotmailListExpanded ? '1' : '0');
  505. }
  506. }
  507. function initHotmailListExpandedState() {
  508. const saved = localStorage.getItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY);
  509. setHotmailListExpanded(saved === '1', { persist: false });
  510. }
  511. function shouldClearCurrentHotmailSelectionLocally(account) {
  512. if (typeof shouldClearHotmailCurrentSelection === 'function') {
  513. return shouldClearHotmailCurrentSelection(account);
  514. }
  515. return Boolean(account) && account.used === true;
  516. }
  517. function upsertHotmailAccountListLocally(accounts, nextAccount) {
  518. if (typeof upsertHotmailAccountInList === 'function') {
  519. return upsertHotmailAccountInList(accounts, nextAccount);
  520. }
  521. const list = Array.isArray(accounts) ? accounts.slice() : [];
  522. if (!nextAccount?.id) return list;
  523. const existingIndex = list.findIndex((account) => account?.id === nextAccount.id);
  524. if (existingIndex === -1) {
  525. list.push(nextAccount);
  526. return list;
  527. }
  528. list[existingIndex] = nextAccount;
  529. return list;
  530. }
  531. function refreshHotmailSelectionUI() {
  532. renderHotmailAccounts();
  533. if (selectMailProvider.value === 'hotmail-api') {
  534. const currentAccount = getCurrentHotmailAccount();
  535. inputEmail.value = currentAccount?.email || latestState?.email || '';
  536. }
  537. }
  538. function applyHotmailAccountMutation(account, options = {}) {
  539. if (!account?.id) return;
  540. const { preserveCurrentSelection = false } = options;
  541. const nextState = {
  542. hotmailAccounts: upsertHotmailAccountListLocally(getHotmailAccounts(), account),
  543. };
  544. if (!preserveCurrentSelection
  545. && latestState?.currentHotmailAccountId === account.id
  546. && shouldClearCurrentHotmailSelectionLocally(account)) {
  547. nextState.currentHotmailAccountId = null;
  548. if (selectMailProvider.value === 'hotmail-api') {
  549. nextState.email = null;
  550. }
  551. }
  552. syncLatestState(nextState);
  553. refreshHotmailSelectionUI();
  554. }
  555. function formatDateTime(timestamp) {
  556. const value = Number(timestamp);
  557. if (!Number.isFinite(value) || value <= 0) {
  558. return '未使用';
  559. }
  560. return new Date(value).toLocaleString('zh-CN', { hour12: false });
  561. }
  562. function getHotmailAvailabilityLabel(account) {
  563. if (account.used) return '已用';
  564. return '可分配';
  565. }
  566. function getHotmailStatusLabel(account) {
  567. if (account.used) return '已用';
  568. switch (account.status) {
  569. case 'authorized':
  570. return '可用';
  571. case 'error':
  572. return '异常';
  573. default:
  574. return '待校验';
  575. }
  576. }
  577. function getHotmailStatusClass(account) {
  578. if (account.used) return 'status-used';
  579. return `status-${account.status || 'pending'}`;
  580. }
  581. function clearHotmailForm() {
  582. inputHotmailEmail.value = '';
  583. inputHotmailClientId.value = '';
  584. inputHotmailPassword.value = '';
  585. inputHotmailRefreshToken.value = '';
  586. }
  587. function renderHotmailAccounts() {
  588. if (!hotmailAccountsList) return;
  589. const accounts = getHotmailAccounts();
  590. const currentId = latestState?.currentHotmailAccountId || '';
  591. if (!accounts.length) {
  592. hotmailAccountsList.innerHTML = '<div class="hotmail-empty">还没有 Hotmail 账号,先添加一条再校验。</div>';
  593. updateHotmailListViewport();
  594. return;
  595. }
  596. hotmailAccountsList.innerHTML = accounts.map((account) => `
  597. <div class="hotmail-account-item${account.id === currentId ? ' is-current' : ''}">
  598. <div class="hotmail-account-top">
  599. <div class="hotmail-account-title-row">
  600. <div class="hotmail-account-email">${escapeHtml(account.email || '(未命名账号)')}</div>
  601. <button
  602. class="hotmail-copy-btn"
  603. type="button"
  604. data-account-action="copy-email"
  605. data-account-id="${escapeHtml(account.id)}"
  606. title="复制邮箱"
  607. aria-label="复制邮箱 ${escapeHtml(account.email || '')}"
  608. >${COPY_ICON}</button>
  609. </div>
  610. <span class="hotmail-status-chip ${escapeHtml(getHotmailStatusClass(account))}">${escapeHtml(getHotmailStatusLabel(account))}</span>
  611. </div>
  612. <div class="hotmail-account-meta">
  613. <span>Client ID: ${escapeHtml(account.clientId ? `${account.clientId.slice(0, 10)}...` : '未填写')}</span>
  614. <span>Refresh: ${account.refreshToken ? '已保存' : '未保存'}</span>
  615. <span>分配状态: ${escapeHtml(getHotmailAvailabilityLabel(account))}</span>
  616. <span>上次校验: ${escapeHtml(formatDateTime(account.lastAuthAt))}</span>
  617. <span>上次使用: ${escapeHtml(formatDateTime(account.lastUsedAt))}</span>
  618. </div>
  619. ${account.lastError ? `<div class="hotmail-account-error">${escapeHtml(account.lastError)}</div>` : ''}
  620. <div class="hotmail-account-actions">
  621. <button class="btn btn-outline btn-sm" type="button" data-account-action="select" data-account-id="${escapeHtml(account.id)}">使用此账号</button>
  622. <button class="btn btn-outline btn-sm" type="button" data-account-action="toggle-used" data-account-id="${escapeHtml(account.id)}">${account.used ? '标记未用' : '标记已用'}</button>
  623. <button class="btn btn-primary btn-sm" type="button" data-account-action="verify" data-account-id="${escapeHtml(account.id)}">校验</button>
  624. <button class="btn btn-outline btn-sm" type="button" data-account-action="test" data-account-id="${escapeHtml(account.id)}">复制最新验证码</button>
  625. <button class="btn btn-ghost btn-sm" type="button" data-account-action="delete" data-account-id="${escapeHtml(account.id)}">删除</button>
  626. </div>
  627. </div>
  628. `).join('');
  629. updateHotmailListViewport();
  630. }
  631. function updateMailProviderUI() {
  632. const useInbucket = selectMailProvider.value === 'inbucket';
  633. const useHotmail = selectMailProvider.value === 'hotmail-api';
  634. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  635. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  636. if (hotmailSection) {
  637. hotmailSection.style.display = useHotmail ? '' : 'none';
  638. }
  639. btnFetchEmail.hidden = useHotmail;
  640. inputEmail.readOnly = useHotmail;
  641. inputEmail.placeholder = useHotmail ? '由 Hotmail 账号池自动分配' : '粘贴 DuckDuckGo 邮箱';
  642. if (autoHintText) {
  643. autoHintText.textContent = useHotmail
  644. ? '请先校验并选择一个 Hotmail 账号'
  645. : '先自动获取 Duck 邮箱,或手动粘贴邮箱后再继续';
  646. }
  647. if (useHotmail) {
  648. const currentAccount = getCurrentHotmailAccount();
  649. inputEmail.value = currentAccount?.email || latestState?.email || '';
  650. }
  651. renderHotmailAccounts();
  652. }
  653. // ============================================================
  654. // UI Updates
  655. // ============================================================
  656. function updateStepUI(step, status) {
  657. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  658. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  659. syncLatestState({
  660. stepStatuses: {
  661. ...getStepStatuses(),
  662. [step]: status,
  663. },
  664. });
  665. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  666. if (row) {
  667. row.className = `step-row ${status}`;
  668. }
  669. updateButtonStates();
  670. updateProgressCounter();
  671. }
  672. function updateProgressCounter() {
  673. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  674. stepsProgress.textContent = `${completed} / 9`;
  675. }
  676. function updateButtonStates() {
  677. const statuses = getStepStatuses();
  678. const anyRunning = Object.values(statuses).some(s => s === 'running');
  679. const autoLocked = isAutoRunLockedPhase();
  680. for (let step = 1; step <= 9; step++) {
  681. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  682. if (!btn) continue;
  683. if (anyRunning || autoLocked) {
  684. btn.disabled = true;
  685. } else if (step === 1) {
  686. btn.disabled = false;
  687. } else {
  688. const prevStatus = statuses[step - 1];
  689. const currentStatus = statuses[step];
  690. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  691. }
  692. }
  693. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  694. const step = Number(btn.dataset.step);
  695. const currentStatus = statuses[step];
  696. const prevStatus = statuses[step - 1];
  697. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  698. btn.style.display = 'none';
  699. btn.disabled = true;
  700. btn.title = '当前不可跳过';
  701. return;
  702. }
  703. if (step > 1 && !isDoneStatus(prevStatus)) {
  704. btn.style.display = 'none';
  705. btn.disabled = true;
  706. btn.title = `请先完成步骤 ${step - 1}`;
  707. return;
  708. }
  709. btn.style.display = '';
  710. btn.disabled = false;
  711. btn.title = `跳过步骤 ${step}`;
  712. });
  713. updateStopButtonState(anyRunning || isAutoRunPausedPhase() || autoLocked);
  714. }
  715. function updateStopButtonState(active) {
  716. btnStop.disabled = !active;
  717. }
  718. function updateStatusDisplay(state) {
  719. if (!state || !state.stepStatuses) return;
  720. statusBar.className = 'status-bar';
  721. if (isAutoRunPausedPhase()) {
  722. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  723. statusBar.classList.add('paused');
  724. return;
  725. }
  726. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  727. if (running) {
  728. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  729. statusBar.classList.add('running');
  730. return;
  731. }
  732. if (isAutoRunLockedPhase()) {
  733. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  734. statusBar.classList.add('running');
  735. return;
  736. }
  737. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  738. if (failed) {
  739. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  740. statusBar.classList.add('failed');
  741. return;
  742. }
  743. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  744. if (stopped) {
  745. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  746. statusBar.classList.add('stopped');
  747. return;
  748. }
  749. const lastCompleted = Object.entries(state.stepStatuses)
  750. .filter(([, s]) => isDoneStatus(s))
  751. .map(([k]) => Number(k))
  752. .sort((a, b) => b - a)[0];
  753. if (lastCompleted === 9) {
  754. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  755. statusBar.classList.add('completed');
  756. } else if (lastCompleted) {
  757. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  758. ? `步骤 ${lastCompleted} 已跳过`
  759. : `步骤 ${lastCompleted} 已完成`;
  760. } else {
  761. displayStatus.textContent = '就绪';
  762. }
  763. }
  764. function appendLog(entry) {
  765. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  766. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  767. const line = document.createElement('div');
  768. line.className = `log-line log-${entry.level}`;
  769. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  770. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  771. let html = `<span class="log-time">${time}</span> `;
  772. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  773. if (stepNum) {
  774. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  775. }
  776. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  777. line.innerHTML = html;
  778. logArea.appendChild(line);
  779. logArea.scrollTop = logArea.scrollHeight;
  780. }
  781. function escapeHtml(text) {
  782. const div = document.createElement('div');
  783. div.textContent = text;
  784. return div.innerHTML;
  785. }
  786. async function fetchDuckEmail(options = {}) {
  787. const { showFailureToast = true } = options;
  788. const defaultLabel = '获取';
  789. btnFetchEmail.disabled = true;
  790. btnFetchEmail.textContent = '...';
  791. try {
  792. const response = await chrome.runtime.sendMessage({
  793. type: 'FETCH_DUCK_EMAIL',
  794. source: 'sidepanel',
  795. payload: { generateNew: true },
  796. });
  797. if (response?.error) {
  798. throw new Error(response.error);
  799. }
  800. if (!response?.email) {
  801. throw new Error('未返回 Duck 邮箱。');
  802. }
  803. inputEmail.value = response.email;
  804. showToast(`已获取 ${response.email}`, 'success', 2500);
  805. return response.email;
  806. } catch (err) {
  807. if (showFailureToast) {
  808. showToast(`自动获取失败:${err.message}`, 'error');
  809. }
  810. throw err;
  811. } finally {
  812. btnFetchEmail.disabled = false;
  813. btnFetchEmail.textContent = defaultLabel;
  814. }
  815. }
  816. async function copyTextToClipboard(text) {
  817. const value = String(text || '').trim();
  818. if (!value) {
  819. throw new Error('没有可复制的内容。');
  820. }
  821. if (!navigator.clipboard?.writeText) {
  822. throw new Error('当前环境不支持剪贴板复制。');
  823. }
  824. await navigator.clipboard.writeText(value);
  825. }
  826. async function deleteHotmailAccountsByMode(mode) {
  827. const isUsedMode = mode === 'used';
  828. const targetAccounts = getHotmailAccountsByUsage(isUsedMode ? 'used' : 'all');
  829. if (!targetAccounts.length) {
  830. showToast(isUsedMode ? '没有已用账号可清空。' : '没有可删除的 Hotmail 账号。', 'warn');
  831. return;
  832. }
  833. const confirmed = await openConfirmModal({
  834. title: isUsedMode ? '清空已用账号' : '全部删除账号',
  835. message: isUsedMode
  836. ? `确认删除当前 ${targetAccounts.length} 个已用 Hotmail 账号吗?`
  837. : `确认删除全部 ${targetAccounts.length} 个 Hotmail 账号吗?`,
  838. confirmLabel: isUsedMode ? '确认清空已用' : '确认全部删除',
  839. confirmVariant: isUsedMode ? 'btn-outline' : 'btn-danger',
  840. });
  841. if (!confirmed) {
  842. return;
  843. }
  844. const response = await chrome.runtime.sendMessage({
  845. type: 'DELETE_HOTMAIL_ACCOUNTS',
  846. source: 'sidepanel',
  847. payload: { mode: isUsedMode ? 'used' : 'all' },
  848. });
  849. if (response?.error) {
  850. throw new Error(response.error);
  851. }
  852. const targetIds = new Set(targetAccounts.map((account) => account.id));
  853. const nextAccounts = isUsedMode
  854. ? getHotmailAccounts().filter((account) => !targetIds.has(account.id))
  855. : [];
  856. const nextState = { hotmailAccounts: nextAccounts };
  857. if (latestState?.currentHotmailAccountId && targetIds.has(latestState.currentHotmailAccountId)) {
  858. nextState.currentHotmailAccountId = null;
  859. if (selectMailProvider.value === 'hotmail-api') {
  860. nextState.email = null;
  861. }
  862. }
  863. syncLatestState(nextState);
  864. refreshHotmailSelectionUI();
  865. showToast(
  866. isUsedMode
  867. ? `已清空 ${response.deletedCount || 0} 个已用 Hotmail 账号`
  868. : `已删除全部 ${response.deletedCount || 0} 个 Hotmail 账号`,
  869. 'success',
  870. 2200
  871. );
  872. }
  873. function syncPasswordToggleLabel() {
  874. const isHidden = inputPassword.type === 'password';
  875. btnTogglePassword.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  876. btnTogglePassword.setAttribute('aria-label', isHidden ? '显示密码' : '隐藏密码');
  877. btnTogglePassword.title = isHidden ? '显示密码' : '隐藏密码';
  878. }
  879. async function maybeTakeoverAutoRun(actionLabel) {
  880. if (!isAutoRunPausedPhase()) {
  881. return true;
  882. }
  883. const confirmed = await openConfirmModal({
  884. title: '接管自动',
  885. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  886. confirmLabel: '确认接管',
  887. confirmVariant: 'btn-primary',
  888. });
  889. if (!confirmed) {
  890. return false;
  891. }
  892. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  893. return true;
  894. }
  895. async function handleSkipStep(step) {
  896. if (!(await maybeTakeoverAutoRun(`跳过步骤 ${step}`))) {
  897. return;
  898. }
  899. const confirmed = await openConfirmModal({
  900. title: '跳过步骤',
  901. message: `这不会真正执行步骤 ${step},只会直接跳过该步骤并放行后续步骤。是否继续?`,
  902. confirmLabel: `跳过步骤 ${step}`,
  903. confirmVariant: 'btn-primary',
  904. });
  905. if (!confirmed) {
  906. return;
  907. }
  908. const response = await chrome.runtime.sendMessage({
  909. type: 'SKIP_STEP',
  910. source: 'sidepanel',
  911. payload: { step },
  912. });
  913. if (response?.error) {
  914. throw new Error(response.error);
  915. }
  916. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  917. }
  918. // ============================================================
  919. // Button Handlers
  920. // ============================================================
  921. document.querySelectorAll('.step-btn').forEach(btn => {
  922. btn.addEventListener('click', async () => {
  923. try {
  924. const step = Number(btn.dataset.step);
  925. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  926. return;
  927. }
  928. if (step === 3) {
  929. if (inputPassword.value !== (latestState?.customPassword || '')) {
  930. await chrome.runtime.sendMessage({
  931. type: 'SAVE_SETTING',
  932. source: 'sidepanel',
  933. payload: { customPassword: inputPassword.value },
  934. });
  935. syncLatestState({ customPassword: inputPassword.value });
  936. }
  937. if (selectMailProvider.value === 'hotmail-api') {
  938. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  939. if (response?.error) {
  940. throw new Error(response.error);
  941. }
  942. } else {
  943. let email = inputEmail.value.trim();
  944. if (!email) {
  945. try {
  946. email = await fetchDuckEmail({ showFailureToast: false });
  947. } catch (err) {
  948. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  949. return;
  950. }
  951. }
  952. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  953. if (response?.error) {
  954. throw new Error(response.error);
  955. }
  956. }
  957. } else {
  958. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  959. if (response?.error) {
  960. throw new Error(response.error);
  961. }
  962. }
  963. } catch (err) {
  964. showToast(err.message, 'error');
  965. }
  966. });
  967. });
  968. btnFetchEmail.addEventListener('click', async () => {
  969. if (selectMailProvider.value === 'hotmail-api') {
  970. return;
  971. }
  972. await fetchDuckEmail().catch(() => {});
  973. });
  974. btnToggleHotmailList?.addEventListener('click', () => {
  975. setHotmailListExpanded(!hotmailListExpanded);
  976. });
  977. btnClearUsedHotmailAccounts?.addEventListener('click', async () => {
  978. if (hotmailActionInFlight) return;
  979. hotmailActionInFlight = true;
  980. btnClearUsedHotmailAccounts.disabled = true;
  981. try {
  982. await deleteHotmailAccountsByMode('used');
  983. } catch (err) {
  984. showToast(err.message, 'error');
  985. } finally {
  986. hotmailActionInFlight = false;
  987. updateHotmailListViewport();
  988. }
  989. });
  990. btnDeleteAllHotmailAccounts?.addEventListener('click', async () => {
  991. if (hotmailActionInFlight) return;
  992. hotmailActionInFlight = true;
  993. btnDeleteAllHotmailAccounts.disabled = true;
  994. try {
  995. await deleteHotmailAccountsByMode('all');
  996. } catch (err) {
  997. showToast(err.message, 'error');
  998. } finally {
  999. hotmailActionInFlight = false;
  1000. updateHotmailListViewport();
  1001. }
  1002. });
  1003. btnAddHotmailAccount?.addEventListener('click', async () => {
  1004. if (hotmailActionInFlight) return;
  1005. const email = inputHotmailEmail.value.trim();
  1006. const clientId = inputHotmailClientId.value.trim();
  1007. const refreshToken = inputHotmailRefreshToken.value.trim();
  1008. if (!email) {
  1009. showToast('请先填写 Hotmail 邮箱。', 'warn');
  1010. return;
  1011. }
  1012. if (!clientId) {
  1013. showToast('请先填写 Microsoft client ID。', 'warn');
  1014. return;
  1015. }
  1016. if (!refreshToken) {
  1017. showToast('请先填写 refresh token。', 'warn');
  1018. return;
  1019. }
  1020. hotmailActionInFlight = true;
  1021. btnAddHotmailAccount.disabled = true;
  1022. try {
  1023. const response = await chrome.runtime.sendMessage({
  1024. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1025. source: 'sidepanel',
  1026. payload: {
  1027. email,
  1028. clientId,
  1029. password: inputHotmailPassword.value,
  1030. refreshToken,
  1031. },
  1032. });
  1033. if (response?.error) {
  1034. throw new Error(response.error);
  1035. }
  1036. showToast(`已保存 Hotmail 账号 ${email}`, 'success', 1800);
  1037. clearHotmailForm();
  1038. } catch (err) {
  1039. showToast(`保存 Hotmail 账号失败:${err.message}`, 'error');
  1040. } finally {
  1041. hotmailActionInFlight = false;
  1042. btnAddHotmailAccount.disabled = false;
  1043. }
  1044. });
  1045. btnImportHotmailAccounts?.addEventListener('click', async () => {
  1046. if (hotmailActionInFlight) return;
  1047. if (typeof parseHotmailImportText !== 'function') {
  1048. showToast('导入解析器未加载,请刷新扩展后重试。', 'error');
  1049. return;
  1050. }
  1051. const rawText = inputHotmailImport.value.trim();
  1052. if (!rawText) {
  1053. showToast('请先粘贴账号导入内容。', 'warn');
  1054. return;
  1055. }
  1056. const parsedAccounts = parseHotmailImportText(rawText);
  1057. if (!parsedAccounts.length) {
  1058. showToast('没有解析到有效账号,请检查格式是否为 账号----密码----ID----Token。', 'error');
  1059. return;
  1060. }
  1061. hotmailActionInFlight = true;
  1062. btnImportHotmailAccounts.disabled = true;
  1063. try {
  1064. for (const account of parsedAccounts) {
  1065. const response = await chrome.runtime.sendMessage({
  1066. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1067. source: 'sidepanel',
  1068. payload: account,
  1069. });
  1070. if (response?.error) {
  1071. throw new Error(response.error);
  1072. }
  1073. }
  1074. inputHotmailImport.value = '';
  1075. showToast(`已导入 ${parsedAccounts.length} 条 Hotmail 账号`, 'success', 2200);
  1076. } catch (err) {
  1077. showToast(`批量导入失败:${err.message}`, 'error');
  1078. } finally {
  1079. hotmailActionInFlight = false;
  1080. btnImportHotmailAccounts.disabled = false;
  1081. }
  1082. });
  1083. hotmailAccountsList?.addEventListener('click', async (event) => {
  1084. const actionButton = event.target.closest('[data-account-action]');
  1085. if (!actionButton || hotmailActionInFlight) {
  1086. return;
  1087. }
  1088. const accountId = actionButton.dataset.accountId;
  1089. const action = actionButton.dataset.accountAction;
  1090. if (!accountId || !action) {
  1091. return;
  1092. }
  1093. const targetAccount = getHotmailAccounts().find((account) => account.id === accountId) || null;
  1094. hotmailActionInFlight = true;
  1095. actionButton.disabled = true;
  1096. try {
  1097. if (action === 'copy-email') {
  1098. if (!targetAccount?.email) throw new Error('未找到可复制的邮箱地址。');
  1099. await copyTextToClipboard(targetAccount.email);
  1100. showToast(`已复制 ${targetAccount.email}`, 'success', 1800);
  1101. } else if (action === 'select') {
  1102. const response = await chrome.runtime.sendMessage({
  1103. type: 'SELECT_HOTMAIL_ACCOUNT',
  1104. source: 'sidepanel',
  1105. payload: { accountId },
  1106. });
  1107. if (response?.error) throw new Error(response.error);
  1108. syncLatestState({ currentHotmailAccountId: response.account.id });
  1109. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1110. showToast(`已切换当前 Hotmail 账号为 ${response.account.email}`, 'success', 1800);
  1111. } else if (action === 'toggle-used') {
  1112. if (!targetAccount) throw new Error('未找到目标 Hotmail 账号。');
  1113. const response = await chrome.runtime.sendMessage({
  1114. type: 'PATCH_HOTMAIL_ACCOUNT',
  1115. source: 'sidepanel',
  1116. payload: {
  1117. accountId,
  1118. updates: { used: !targetAccount.used },
  1119. },
  1120. });
  1121. if (response?.error) throw new Error(response.error);
  1122. applyHotmailAccountMutation(response.account);
  1123. showToast(`账号 ${response.account.email} 已${response.account.used ? '标记为已用' : '恢复为未用'}`, 'success', 2200);
  1124. } else if (action === 'verify') {
  1125. const response = await chrome.runtime.sendMessage({
  1126. type: 'VERIFY_HOTMAIL_ACCOUNT',
  1127. source: 'sidepanel',
  1128. payload: { accountId },
  1129. });
  1130. if (response?.error) throw new Error(response.error);
  1131. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1132. showToast(`账号 ${response.account.email} 校验通过`, 'success', 2200);
  1133. } else if (action === 'test') {
  1134. const response = await chrome.runtime.sendMessage({
  1135. type: 'TEST_HOTMAIL_ACCOUNT',
  1136. source: 'sidepanel',
  1137. payload: { accountId },
  1138. });
  1139. if (response?.error) throw new Error(response.error);
  1140. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1141. if (response.latestCode) {
  1142. await copyTextToClipboard(response.latestCode);
  1143. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1144. showToast(`已复制最新验证码 ${response.latestCode}${mailbox}`, 'success', 2600);
  1145. } else if (response.latestSubject) {
  1146. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1147. showToast(`最新邮件${mailbox}没有验证码:${response.latestSubject}`, 'warn', 3200);
  1148. } else {
  1149. showToast('当前没有可读取的最新邮件。', 'warn', 2600);
  1150. }
  1151. } else if (action === 'delete') {
  1152. const confirmed = await openConfirmModal({
  1153. title: '删除账号',
  1154. message: '确认删除这个 Hotmail 账号吗?对应 token 也会一起移除。',
  1155. confirmLabel: '确认删除',
  1156. confirmVariant: 'btn-danger',
  1157. });
  1158. if (!confirmed) {
  1159. return;
  1160. }
  1161. const response = await chrome.runtime.sendMessage({
  1162. type: 'DELETE_HOTMAIL_ACCOUNT',
  1163. source: 'sidepanel',
  1164. payload: { accountId },
  1165. });
  1166. if (response?.error) throw new Error(response.error);
  1167. showToast('Hotmail 账号已删除', 'success', 1800);
  1168. }
  1169. } catch (err) {
  1170. showToast(err.message, 'error');
  1171. } finally {
  1172. hotmailActionInFlight = false;
  1173. actionButton.disabled = false;
  1174. }
  1175. });
  1176. btnTogglePassword.addEventListener('click', () => {
  1177. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  1178. syncPasswordToggleLabel();
  1179. });
  1180. btnSaveSettings.addEventListener('click', async () => {
  1181. if (!settingsDirty) {
  1182. showToast('配置已是最新', 'info', 1400);
  1183. return;
  1184. }
  1185. await saveSettings({ silent: false }).catch(() => {});
  1186. });
  1187. btnStop.addEventListener('click', async () => {
  1188. btnStop.disabled = true;
  1189. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  1190. showToast('正在停止当前流程...', 'warn', 2000);
  1191. });
  1192. autoStartModal?.addEventListener('click', (event) => {
  1193. if (event.target === autoStartModal) {
  1194. resolveModalChoice(null);
  1195. }
  1196. });
  1197. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  1198. // Auto Run
  1199. btnAutoRun.addEventListener('click', async () => {
  1200. try {
  1201. const totalRuns = parseInt(inputRunCount.value) || 1;
  1202. let mode = 'restart';
  1203. if (shouldOfferAutoModeChoice()) {
  1204. const startStep = getFirstUnfinishedStep();
  1205. const choice = await openAutoStartChoiceDialog(startStep);
  1206. if (!choice) {
  1207. return;
  1208. }
  1209. mode = choice;
  1210. }
  1211. btnAutoRun.disabled = true;
  1212. inputRunCount.disabled = true;
  1213. 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> 运行中...';
  1214. const response = await chrome.runtime.sendMessage({
  1215. type: 'AUTO_RUN',
  1216. source: 'sidepanel',
  1217. payload: {
  1218. totalRuns,
  1219. autoRunSkipFailures: inputAutoSkipFailures.checked,
  1220. mode,
  1221. },
  1222. });
  1223. if (response?.error) {
  1224. throw new Error(response.error);
  1225. }
  1226. } catch (err) {
  1227. setDefaultAutoRunButton();
  1228. inputRunCount.disabled = false;
  1229. showToast(err.message, 'error');
  1230. }
  1231. });
  1232. btnAutoContinue.addEventListener('click', async () => {
  1233. const email = inputEmail.value.trim();
  1234. if (!email) {
  1235. showToast('请先获取或粘贴 DuckDuckGo 邮箱。', 'warn');
  1236. return;
  1237. }
  1238. autoContinueBar.style.display = 'none';
  1239. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  1240. });
  1241. // Reset
  1242. btnReset.addEventListener('click', async () => {
  1243. const confirmed = await openConfirmModal({
  1244. title: '重置流程',
  1245. message: '确认重置全部步骤和数据吗?',
  1246. confirmLabel: '确认重置',
  1247. confirmVariant: 'btn-danger',
  1248. });
  1249. if (!confirmed) {
  1250. return;
  1251. }
  1252. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  1253. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES, currentHotmailAccountId: null, email: null });
  1254. syncAutoRunState({ autoRunning: false, autoRunPhase: 'idle', autoRunCurrentRun: 0, autoRunTotalRuns: 1, autoRunAttemptRun: 0 });
  1255. displayOauthUrl.textContent = '等待中...';
  1256. displayOauthUrl.classList.remove('has-value');
  1257. displayLocalhostUrl.textContent = '等待中...';
  1258. displayLocalhostUrl.classList.remove('has-value');
  1259. inputEmail.value = '';
  1260. displayStatus.textContent = '就绪';
  1261. statusBar.className = 'status-bar';
  1262. logArea.innerHTML = '';
  1263. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1264. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1265. setDefaultAutoRunButton();
  1266. applyAutoRunStatus(currentAutoRun);
  1267. markSettingsDirty(false);
  1268. updateStopButtonState(false);
  1269. updateButtonStates();
  1270. updateProgressCounter();
  1271. renderHotmailAccounts();
  1272. });
  1273. // Clear log
  1274. btnClearLog.addEventListener('click', () => {
  1275. logArea.innerHTML = '';
  1276. });
  1277. // Save settings on change
  1278. inputEmail.addEventListener('change', async () => {
  1279. if (selectMailProvider.value === 'hotmail-api') {
  1280. return;
  1281. }
  1282. const email = inputEmail.value.trim();
  1283. if (email) {
  1284. await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  1285. }
  1286. });
  1287. inputEmail.addEventListener('input', updateButtonStates);
  1288. inputVpsUrl.addEventListener('input', () => {
  1289. markSettingsDirty(true);
  1290. scheduleSettingsAutoSave();
  1291. });
  1292. inputVpsUrl.addEventListener('blur', () => {
  1293. saveSettings({ silent: true }).catch(() => {});
  1294. });
  1295. inputVpsPassword.addEventListener('input', () => {
  1296. markSettingsDirty(true);
  1297. scheduleSettingsAutoSave();
  1298. });
  1299. inputVpsPassword.addEventListener('blur', () => {
  1300. saveSettings({ silent: true }).catch(() => {});
  1301. });
  1302. inputPassword.addEventListener('input', () => {
  1303. markSettingsDirty(true);
  1304. updateButtonStates();
  1305. scheduleSettingsAutoSave();
  1306. });
  1307. inputPassword.addEventListener('blur', () => {
  1308. saveSettings({ silent: true }).catch(() => {});
  1309. });
  1310. selectMailProvider.addEventListener('change', () => {
  1311. updateMailProviderUI();
  1312. markSettingsDirty(true);
  1313. saveSettings({ silent: true }).catch(() => {});
  1314. });
  1315. inputInbucketMailbox.addEventListener('input', () => {
  1316. markSettingsDirty(true);
  1317. scheduleSettingsAutoSave();
  1318. });
  1319. inputInbucketMailbox.addEventListener('blur', () => {
  1320. saveSettings({ silent: true }).catch(() => {});
  1321. });
  1322. inputInbucketHost.addEventListener('input', () => {
  1323. markSettingsDirty(true);
  1324. scheduleSettingsAutoSave();
  1325. });
  1326. inputInbucketHost.addEventListener('blur', () => {
  1327. saveSettings({ silent: true }).catch(() => {});
  1328. });
  1329. inputAutoSkipFailures.addEventListener('change', () => {
  1330. markSettingsDirty(true);
  1331. saveSettings({ silent: true }).catch(() => {});
  1332. });
  1333. // ============================================================
  1334. // Listen for Background broadcasts
  1335. // ============================================================
  1336. chrome.runtime.onMessage.addListener((message) => {
  1337. switch (message.type) {
  1338. case 'LOG_ENTRY':
  1339. appendLog(message.payload);
  1340. if (message.payload.level === 'error') {
  1341. showToast(message.payload.message, 'error');
  1342. }
  1343. break;
  1344. case 'STEP_STATUS_CHANGED': {
  1345. const { step, status } = message.payload;
  1346. updateStepUI(step, status);
  1347. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  1348. syncLatestState(state);
  1349. syncAutoRunState(state);
  1350. updateStatusDisplay(latestState);
  1351. updateButtonStates();
  1352. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  1353. syncPasswordField(state);
  1354. if (state.oauthUrl) {
  1355. displayOauthUrl.textContent = state.oauthUrl;
  1356. displayOauthUrl.classList.add('has-value');
  1357. }
  1358. if (state.localhostUrl) {
  1359. displayLocalhostUrl.textContent = state.localhostUrl;
  1360. displayLocalhostUrl.classList.add('has-value');
  1361. }
  1362. }
  1363. }
  1364. ).catch(() => {});
  1365. break;
  1366. }
  1367. case 'AUTO_RUN_RESET': {
  1368. // Full UI reset for next run
  1369. syncLatestState({
  1370. oauthUrl: null,
  1371. localhostUrl: null,
  1372. email: null,
  1373. password: null,
  1374. stepStatuses: STEP_DEFAULT_STATUSES,
  1375. logs: [],
  1376. });
  1377. displayOauthUrl.textContent = '等待中...';
  1378. displayOauthUrl.classList.remove('has-value');
  1379. displayLocalhostUrl.textContent = '等待中...';
  1380. displayLocalhostUrl.classList.remove('has-value');
  1381. inputEmail.value = '';
  1382. displayStatus.textContent = '就绪';
  1383. statusBar.className = 'status-bar';
  1384. logArea.innerHTML = '';
  1385. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1386. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1387. applyAutoRunStatus(currentAutoRun);
  1388. updateProgressCounter();
  1389. updateButtonStates();
  1390. renderHotmailAccounts();
  1391. break;
  1392. }
  1393. case 'DATA_UPDATED': {
  1394. syncLatestState(message.payload);
  1395. if (message.payload.email !== undefined) {
  1396. inputEmail.value = message.payload.email || '';
  1397. }
  1398. if (message.payload.password !== undefined) {
  1399. inputPassword.value = message.payload.password || '';
  1400. }
  1401. if (message.payload.oauthUrl !== undefined) {
  1402. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  1403. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  1404. }
  1405. if (message.payload.localhostUrl !== undefined) {
  1406. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  1407. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  1408. }
  1409. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  1410. renderHotmailAccounts();
  1411. if (selectMailProvider.value === 'hotmail-api') {
  1412. const currentAccount = getCurrentHotmailAccount();
  1413. inputEmail.value = currentAccount?.email || latestState?.email || '';
  1414. }
  1415. }
  1416. break;
  1417. }
  1418. case 'AUTO_RUN_STATUS': {
  1419. syncLatestState({
  1420. autoRunning: ['running', 'waiting_email', 'retrying'].includes(message.payload.phase),
  1421. autoRunPhase: message.payload.phase,
  1422. autoRunCurrentRun: message.payload.currentRun,
  1423. autoRunTotalRuns: message.payload.totalRuns,
  1424. autoRunAttemptRun: message.payload.attemptRun,
  1425. });
  1426. applyAutoRunStatus(message.payload);
  1427. updateStatusDisplay(latestState);
  1428. updateButtonStates();
  1429. break;
  1430. }
  1431. }
  1432. });
  1433. // ============================================================
  1434. // Theme Toggle
  1435. // ============================================================
  1436. const btnTheme = document.getElementById('btn-theme');
  1437. function setTheme(theme) {
  1438. document.documentElement.setAttribute('data-theme', theme);
  1439. localStorage.setItem('multipage-theme', theme);
  1440. }
  1441. function initTheme() {
  1442. const saved = localStorage.getItem('multipage-theme');
  1443. if (saved) {
  1444. setTheme(saved);
  1445. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  1446. setTheme('dark');
  1447. }
  1448. }
  1449. btnTheme.addEventListener('click', () => {
  1450. const current = document.documentElement.getAttribute('data-theme');
  1451. setTheme(current === 'dark' ? 'light' : 'dark');
  1452. });
  1453. // ============================================================
  1454. // Init
  1455. // ============================================================
  1456. initializeManualStepActions();
  1457. initTheme();
  1458. initHotmailListExpandedState();
  1459. updateSaveButtonState();
  1460. restoreState().then(() => {
  1461. syncPasswordToggleLabel();
  1462. updateButtonStates();
  1463. updateStatusDisplay(latestState);
  1464. });