sidepanel.js 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195
  1. // sidepanel/sidepanel.js — Side Panel logic
  2. const STATUS_ICONS = {
  3. pending: '',
  4. running: '',
  5. completed: '\u2713', // ✓
  6. failed: '\u2717', // ✗
  7. stopped: '\u25A0', // ■
  8. manual_completed: '跳',
  9. skipped: '跳',
  10. };
  11. const logArea = document.getElementById('log-area');
  12. const displayOauthUrl = document.getElementById('display-oauth-url');
  13. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  14. const displayStatus = document.getElementById('display-status');
  15. const statusBar = document.getElementById('status-bar');
  16. const inputEmail = document.getElementById('input-email');
  17. const inputPassword = document.getElementById('input-password');
  18. const btnToggleVpsUrl = document.getElementById('btn-toggle-vps-url');
  19. const btnFetchEmail = document.getElementById('btn-fetch-email');
  20. const btnTogglePassword = document.getElementById('btn-toggle-password');
  21. const btnSaveSettings = document.getElementById('btn-save-settings');
  22. const btnStop = document.getElementById('btn-stop');
  23. const btnReset = document.getElementById('btn-reset');
  24. const stepsProgress = document.getElementById('steps-progress');
  25. const btnAutoRun = document.getElementById('btn-auto-run');
  26. const btnAutoContinue = document.getElementById('btn-auto-continue');
  27. const autoContinueBar = document.getElementById('auto-continue-bar');
  28. const autoScheduleBar = document.getElementById('auto-schedule-bar');
  29. const autoScheduleTitle = document.getElementById('auto-schedule-title');
  30. const autoScheduleMeta = document.getElementById('auto-schedule-meta');
  31. const btnAutoRunNow = document.getElementById('btn-auto-run-now');
  32. const btnAutoCancelSchedule = document.getElementById('btn-auto-cancel-schedule');
  33. const btnClearLog = document.getElementById('btn-clear-log');
  34. const selectPanelMode = document.getElementById('select-panel-mode');
  35. const rowVpsUrl = document.getElementById('row-vps-url');
  36. const inputVpsUrl = document.getElementById('input-vps-url');
  37. const rowVpsPassword = document.getElementById('row-vps-password');
  38. const inputVpsPassword = document.getElementById('input-vps-password');
  39. const rowLocalCpaStep9Mode = document.getElementById('row-local-cpa-step9-mode');
  40. const localCpaStep9ModeButtons = Array.from(document.querySelectorAll('[data-local-cpa-step9-mode]'));
  41. const rowSub2ApiUrl = document.getElementById('row-sub2api-url');
  42. const inputSub2ApiUrl = document.getElementById('input-sub2api-url');
  43. const rowSub2ApiEmail = document.getElementById('row-sub2api-email');
  44. const inputSub2ApiEmail = document.getElementById('input-sub2api-email');
  45. const rowSub2ApiPassword = document.getElementById('row-sub2api-password');
  46. const inputSub2ApiPassword = document.getElementById('input-sub2api-password');
  47. const rowSub2ApiGroup = document.getElementById('row-sub2api-group');
  48. const inputSub2ApiGroup = document.getElementById('input-sub2api-group');
  49. const selectMailProvider = document.getElementById('select-mail-provider');
  50. const selectEmailGenerator = document.getElementById('select-email-generator');
  51. const hotmailSection = document.getElementById('hotmail-section');
  52. const inputHotmailEmail = document.getElementById('input-hotmail-email');
  53. const inputHotmailClientId = document.getElementById('input-hotmail-client-id');
  54. const inputHotmailPassword = document.getElementById('input-hotmail-password');
  55. const inputHotmailRefreshToken = document.getElementById('input-hotmail-refresh-token');
  56. const inputHotmailImport = document.getElementById('input-hotmail-import');
  57. const btnAddHotmailAccount = document.getElementById('btn-add-hotmail-account');
  58. const btnImportHotmailAccounts = document.getElementById('btn-import-hotmail-accounts');
  59. const btnClearUsedHotmailAccounts = document.getElementById('btn-clear-used-hotmail-accounts');
  60. const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotmail-accounts');
  61. const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list');
  62. const hotmailListShell = document.getElementById('hotmail-list-shell');
  63. const hotmailAccountsList = document.getElementById('hotmail-accounts-list');
  64. const rowInbucketHost = document.getElementById('row-inbucket-host');
  65. const inputInbucketHost = document.getElementById('input-inbucket-host');
  66. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  67. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  68. const rowCfDomain = document.getElementById('row-cf-domain');
  69. const selectCfDomain = document.getElementById('select-cf-domain');
  70. const inputCfDomain = document.getElementById('input-cf-domain');
  71. const btnCfDomainMode = document.getElementById('btn-cf-domain-mode');
  72. const inputRunCount = document.getElementById('input-run-count');
  73. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  74. const inputAutoDelayEnabled = document.getElementById('input-auto-delay-enabled');
  75. const inputAutoDelayMinutes = document.getElementById('input-auto-delay-minutes');
  76. const autoStartModal = document.getElementById('auto-start-modal');
  77. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  78. const autoStartMessage = document.getElementById('auto-start-message');
  79. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  80. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  81. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  82. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  83. const autoHintText = document.querySelector('.auto-hint');
  84. const STEP_DEFAULT_STATUSES = {
  85. 1: 'pending',
  86. 2: 'pending',
  87. 3: 'pending',
  88. 4: 'pending',
  89. 5: 'pending',
  90. 6: 'pending',
  91. 7: 'pending',
  92. 8: 'pending',
  93. 9: 'pending',
  94. };
  95. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  96. const AUTO_DELAY_MIN_MINUTES = 1;
  97. const AUTO_DELAY_MAX_MINUTES = 1440;
  98. const AUTO_DELAY_DEFAULT_MINUTES = 30;
  99. const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit';
  100. let latestState = null;
  101. let currentAutoRun = {
  102. autoRunning: false,
  103. phase: 'idle',
  104. currentRun: 0,
  105. totalRuns: 1,
  106. attemptRun: 0,
  107. scheduledAt: null,
  108. };
  109. let settingsDirty = false;
  110. let settingsSaveInFlight = false;
  111. let settingsAutoSaveTimer = null;
  112. let cloudflareDomainEditMode = false;
  113. let modalChoiceResolver = null;
  114. let currentModalActions = [];
  115. let scheduledCountdownTimer = null;
  116. let hotmailActionInFlight = false;
  117. let hotmailListExpanded = false;
  118. 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>';
  119. 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>';
  120. 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>';
  121. const parseHotmailImportText = window.HotmailUtils?.parseHotmailImportText;
  122. const shouldClearHotmailCurrentSelection = window.HotmailUtils?.shouldClearHotmailCurrentSelection;
  123. const upsertHotmailAccountInList = window.HotmailUtils?.upsertHotmailAccountInList;
  124. const filterHotmailAccountsByUsage = window.HotmailUtils?.filterHotmailAccountsByUsage;
  125. const getHotmailBulkActionLabel = window.HotmailUtils?.getHotmailBulkActionLabel;
  126. const getHotmailListToggleLabel = window.HotmailUtils?.getHotmailListToggleLabel;
  127. const HOTMAIL_LIST_EXPANDED_STORAGE_KEY = 'multipage-hotmail-list-expanded';
  128. // ============================================================
  129. // Toast Notifications
  130. // ============================================================
  131. const toastContainer = document.getElementById('toast-container');
  132. const TOAST_ICONS = {
  133. 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>',
  134. 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>',
  135. 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>',
  136. 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>',
  137. };
  138. const LOG_LEVEL_LABELS = {
  139. info: '信息',
  140. ok: '成功',
  141. warn: '警告',
  142. error: '错误',
  143. };
  144. function showToast(message, type = 'error', duration = 4000) {
  145. const toast = document.createElement('div');
  146. toast.className = `toast toast-${type}`;
  147. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  148. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  149. toastContainer.appendChild(toast);
  150. if (duration > 0) {
  151. setTimeout(() => dismissToast(toast), duration);
  152. }
  153. }
  154. function dismissToast(toast) {
  155. if (!toast.parentNode) return;
  156. toast.classList.add('toast-exit');
  157. toast.addEventListener('animationend', () => toast.remove());
  158. }
  159. function resetActionModalButtons() {
  160. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  161. buttons.forEach((button) => {
  162. if (!button) return;
  163. button.hidden = true;
  164. button.disabled = false;
  165. button.onclick = null;
  166. });
  167. currentModalActions = [];
  168. }
  169. function configureActionModalButton(button, action) {
  170. if (!button) return;
  171. if (!action) {
  172. button.hidden = true;
  173. button.onclick = null;
  174. return;
  175. }
  176. button.hidden = false;
  177. button.disabled = false;
  178. button.textContent = action.label;
  179. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  180. button.onclick = () => resolveModalChoice(action.id);
  181. }
  182. function resolveModalChoice(choice) {
  183. if (modalChoiceResolver) {
  184. modalChoiceResolver(choice);
  185. modalChoiceResolver = null;
  186. }
  187. resetActionModalButtons();
  188. if (autoStartModal) {
  189. autoStartModal.hidden = true;
  190. }
  191. }
  192. function openActionModal({ title, message, actions }) {
  193. if (!autoStartModal) {
  194. return Promise.resolve(null);
  195. }
  196. if (modalChoiceResolver) {
  197. resolveModalChoice(null);
  198. }
  199. autoStartTitle.textContent = title;
  200. autoStartMessage.textContent = message;
  201. currentModalActions = actions || [];
  202. configureActionModalButton(btnAutoStartCancel, currentModalActions[0]);
  203. configureActionModalButton(btnAutoStartRestart, currentModalActions[1]);
  204. configureActionModalButton(btnAutoStartContinue, currentModalActions[2]);
  205. autoStartModal.hidden = false;
  206. return new Promise((resolve) => {
  207. modalChoiceResolver = resolve;
  208. });
  209. }
  210. function openAutoStartChoiceDialog(startStep) {
  211. return openActionModal({
  212. title: '启动自动',
  213. message: `检测到当前已有流程进度。继续当前会从步骤 ${startStep} 开始自动执行,重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  214. actions: [
  215. { id: null, label: '取消', variant: 'btn-ghost' },
  216. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  217. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  218. ],
  219. });
  220. }
  221. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary' }) {
  222. const choice = await openActionModal({
  223. title,
  224. message,
  225. actions: [
  226. { id: null, label: '取消', variant: 'btn-ghost' },
  227. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  228. ],
  229. });
  230. return choice === 'confirm';
  231. }
  232. function isDoneStatus(status) {
  233. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  234. }
  235. function getStepStatuses(state = latestState) {
  236. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  237. }
  238. function getFirstUnfinishedStep(state = latestState) {
  239. const statuses = getStepStatuses(state);
  240. for (let step = 1; step <= 9; step++) {
  241. if (!isDoneStatus(statuses[step])) {
  242. return step;
  243. }
  244. }
  245. return null;
  246. }
  247. function hasSavedProgress(state = latestState) {
  248. const statuses = getStepStatuses(state);
  249. return Object.values(statuses).some((status) => status !== 'pending');
  250. }
  251. function shouldOfferAutoModeChoice(state = latestState) {
  252. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  253. }
  254. function syncLatestState(nextState) {
  255. const mergedStepStatuses = nextState?.stepStatuses
  256. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  257. : getStepStatuses(latestState);
  258. latestState = {
  259. ...(latestState || {}),
  260. ...(nextState || {}),
  261. stepStatuses: mergedStepStatuses,
  262. };
  263. }
  264. function syncAutoRunState(source = {}) {
  265. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  266. const autoRunning = source.autoRunning !== undefined
  267. ? Boolean(source.autoRunning)
  268. : (source.autoRunPhase !== undefined || source.phase !== undefined
  269. ? ['scheduled', 'running', 'waiting_email', 'retrying'].includes(phase)
  270. : currentAutoRun.autoRunning);
  271. currentAutoRun = {
  272. autoRunning,
  273. phase,
  274. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  275. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  276. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  277. scheduledAt: source.scheduledAutoRunAt ?? source.scheduledAt ?? currentAutoRun.scheduledAt,
  278. };
  279. }
  280. function isAutoRunLockedPhase() {
  281. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'retrying';
  282. }
  283. function isAutoRunPausedPhase() {
  284. return currentAutoRun.phase === 'waiting_email';
  285. }
  286. function isAutoRunScheduledPhase() {
  287. return currentAutoRun.phase === 'scheduled';
  288. }
  289. function getAutoRunLabel(payload = currentAutoRun) {
  290. if ((payload.phase ?? currentAutoRun.phase) === 'scheduled') {
  291. return (payload.totalRuns || 1) > 1 ? ` (${payload.totalRuns}轮)` : '';
  292. }
  293. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  294. if ((payload.totalRuns || 1) > 1) {
  295. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  296. }
  297. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  298. }
  299. function normalizeAutoDelayMinutes(value) {
  300. const numeric = Number(value);
  301. if (!Number.isFinite(numeric)) {
  302. return AUTO_DELAY_DEFAULT_MINUTES;
  303. }
  304. return Math.min(AUTO_DELAY_MAX_MINUTES, Math.max(AUTO_DELAY_MIN_MINUTES, Math.floor(numeric)));
  305. }
  306. function updateAutoDelayInputState() {
  307. const scheduled = isAutoRunScheduledPhase();
  308. inputAutoDelayEnabled.disabled = scheduled;
  309. inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked;
  310. }
  311. function formatCountdown(remainingMs) {
  312. const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
  313. const hours = Math.floor(totalSeconds / 3600);
  314. const minutes = Math.floor((totalSeconds % 3600) / 60);
  315. const seconds = totalSeconds % 60;
  316. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  317. }
  318. function formatScheduleTime(timestamp) {
  319. return new Date(timestamp).toLocaleString('zh-CN', {
  320. hour12: false,
  321. month: '2-digit',
  322. day: '2-digit',
  323. hour: '2-digit',
  324. minute: '2-digit',
  325. second: '2-digit',
  326. });
  327. }
  328. function stopScheduledCountdownTicker() {
  329. clearInterval(scheduledCountdownTimer);
  330. scheduledCountdownTimer = null;
  331. }
  332. function renderScheduledAutoRunInfo() {
  333. if (!autoScheduleBar) {
  334. return;
  335. }
  336. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  337. autoScheduleBar.style.display = 'none';
  338. return;
  339. }
  340. const remainingMs = currentAutoRun.scheduledAt - Date.now();
  341. autoScheduleBar.style.display = 'flex';
  342. autoScheduleTitle.textContent = '已计划自动运行';
  343. autoScheduleMeta.textContent = remainingMs > 0
  344. ? `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始,剩余 ${formatCountdown(remainingMs)}`
  345. : '倒计时即将结束,正在准备启动...';
  346. }
  347. function syncScheduledCountdownTicker() {
  348. renderScheduledAutoRunInfo();
  349. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  350. stopScheduledCountdownTicker();
  351. return;
  352. }
  353. if (scheduledCountdownTimer) {
  354. return;
  355. }
  356. scheduledCountdownTimer = setInterval(() => {
  357. renderScheduledAutoRunInfo();
  358. updateStatusDisplay(latestState);
  359. }, 1000);
  360. }
  361. function setDefaultAutoRunButton() {
  362. btnAutoRun.disabled = false;
  363. inputRunCount.disabled = false;
  364. 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> 自动';
  365. }
  366. function normalizeCloudflareDomainValue(value = '') {
  367. let normalized = String(value || '').trim().toLowerCase();
  368. if (!normalized) return '';
  369. normalized = normalized.replace(/^@+/, '');
  370. normalized = normalized.replace(/^https?:\/\//, '');
  371. normalized = normalized.replace(/\/.*$/, '');
  372. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) {
  373. return '';
  374. }
  375. return normalized;
  376. }
  377. function normalizeCloudflareDomains(values = []) {
  378. const seen = new Set();
  379. const domains = [];
  380. for (const value of Array.isArray(values) ? values : []) {
  381. const normalized = normalizeCloudflareDomainValue(value);
  382. if (!normalized || seen.has(normalized)) continue;
  383. seen.add(normalized);
  384. domains.push(normalized);
  385. }
  386. return domains;
  387. }
  388. function getCloudflareDomainsFromState() {
  389. const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []);
  390. const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || '');
  391. if (activeDomain && !domains.includes(activeDomain)) {
  392. domains.unshift(activeDomain);
  393. }
  394. return { domains, activeDomain: activeDomain || domains[0] || '' };
  395. }
  396. function renderCloudflareDomainOptions(preferredDomain = '') {
  397. const preferred = normalizeCloudflareDomainValue(preferredDomain);
  398. const { domains, activeDomain } = getCloudflareDomainsFromState();
  399. const selected = preferred || activeDomain;
  400. selectCfDomain.innerHTML = '';
  401. if (domains.length === 0) {
  402. const option = document.createElement('option');
  403. option.value = '';
  404. option.textContent = '请先添加域名';
  405. selectCfDomain.appendChild(option);
  406. selectCfDomain.disabled = true;
  407. selectCfDomain.value = '';
  408. return;
  409. }
  410. for (const domain of domains) {
  411. const option = document.createElement('option');
  412. option.value = domain;
  413. option.textContent = domain;
  414. selectCfDomain.appendChild(option);
  415. }
  416. selectCfDomain.disabled = false;
  417. selectCfDomain.value = domains.includes(selected) ? selected : domains[0];
  418. }
  419. function setCloudflareDomainEditMode(editing, options = {}) {
  420. const { clearInput = false } = options;
  421. cloudflareDomainEditMode = Boolean(editing);
  422. selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : '';
  423. inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none';
  424. btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加';
  425. if (cloudflareDomainEditMode) {
  426. if (clearInput) {
  427. inputCfDomain.value = '';
  428. }
  429. inputCfDomain.focus();
  430. } else if (clearInput) {
  431. inputCfDomain.value = '';
  432. }
  433. }
  434. function collectSettingsPayload() {
  435. const { domains, activeDomain } = getCloudflareDomainsFromState();
  436. const selectedCloudflareDomain = normalizeCloudflareDomainValue(
  437. !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain
  438. ) || activeDomain;
  439. return {
  440. panelMode: selectPanelMode.value,
  441. vpsUrl: inputVpsUrl.value.trim(),
  442. vpsPassword: inputVpsPassword.value,
  443. localCpaStep9Mode: getSelectedLocalCpaStep9Mode(),
  444. sub2apiUrl: inputSub2ApiUrl.value.trim(),
  445. sub2apiEmail: inputSub2ApiEmail.value.trim(),
  446. sub2apiPassword: inputSub2ApiPassword.value,
  447. sub2apiGroupName: inputSub2ApiGroup.value.trim(),
  448. customPassword: inputPassword.value,
  449. mailProvider: selectMailProvider.value,
  450. emailGenerator: selectEmailGenerator.value,
  451. inbucketHost: inputInbucketHost.value.trim(),
  452. inbucketMailbox: inputInbucketMailbox.value.trim(),
  453. cloudflareDomain: selectedCloudflareDomain,
  454. cloudflareDomains: domains,
  455. autoRunSkipFailures: inputAutoSkipFailures.checked,
  456. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  457. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  458. };
  459. }
  460. function normalizeLocalCpaStep9Mode(value = '') {
  461. return String(value || '').trim().toLowerCase() === 'bypass'
  462. ? 'bypass'
  463. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  464. }
  465. function getSelectedLocalCpaStep9Mode() {
  466. const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active'));
  467. return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode);
  468. }
  469. function setLocalCpaStep9Mode(mode) {
  470. const resolvedMode = normalizeLocalCpaStep9Mode(mode);
  471. localCpaStep9ModeButtons.forEach((button) => {
  472. const active = button.dataset.localCpaStep9Mode === resolvedMode;
  473. button.classList.toggle('is-active', active);
  474. button.setAttribute('aria-pressed', String(active));
  475. });
  476. }
  477. function markSettingsDirty(isDirty = true) {
  478. settingsDirty = isDirty;
  479. updateSaveButtonState();
  480. }
  481. function updateSaveButtonState() {
  482. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  483. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  484. }
  485. function scheduleSettingsAutoSave() {
  486. clearTimeout(settingsAutoSaveTimer);
  487. settingsAutoSaveTimer = setTimeout(() => {
  488. saveSettings({ silent: true }).catch(() => { });
  489. }, 500);
  490. }
  491. async function saveSettings(options = {}) {
  492. const { silent = false } = options;
  493. clearTimeout(settingsAutoSaveTimer);
  494. if (!settingsDirty && !settingsSaveInFlight && silent) {
  495. return;
  496. }
  497. const payload = collectSettingsPayload();
  498. settingsSaveInFlight = true;
  499. updateSaveButtonState();
  500. try {
  501. const response = await chrome.runtime.sendMessage({
  502. type: 'SAVE_SETTING',
  503. source: 'sidepanel',
  504. payload,
  505. });
  506. if (response?.error) {
  507. throw new Error(response.error);
  508. }
  509. syncLatestState(payload);
  510. markSettingsDirty(false);
  511. updatePanelModeUI();
  512. updateMailProviderUI();
  513. updateButtonStates();
  514. if (!silent) {
  515. showToast('配置已保存', 'success', 1800);
  516. }
  517. } catch (err) {
  518. markSettingsDirty(true);
  519. if (!silent) {
  520. showToast(`保存失败:${err.message}`, 'error');
  521. }
  522. throw err;
  523. } finally {
  524. settingsSaveInFlight = false;
  525. updateSaveButtonState();
  526. }
  527. }
  528. function applyAutoRunStatus(payload = currentAutoRun) {
  529. syncAutoRunState(payload);
  530. const runLabel = getAutoRunLabel(currentAutoRun);
  531. const locked = isAutoRunLockedPhase();
  532. const paused = isAutoRunPausedPhase();
  533. const scheduled = isAutoRunScheduledPhase();
  534. inputRunCount.disabled = currentAutoRun.autoRunning;
  535. btnAutoRun.disabled = currentAutoRun.autoRunning;
  536. btnFetchEmail.disabled = locked;
  537. inputEmail.disabled = locked;
  538. inputAutoSkipFailures.disabled = scheduled;
  539. if (currentAutoRun.totalRuns > 0) {
  540. inputRunCount.value = String(currentAutoRun.totalRuns);
  541. }
  542. switch (currentAutoRun.phase) {
  543. case 'scheduled':
  544. autoContinueBar.style.display = 'none';
  545. btnAutoRun.innerHTML = `已计划${runLabel}`;
  546. break;
  547. case 'waiting_email':
  548. autoContinueBar.style.display = 'flex';
  549. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  550. break;
  551. case 'running':
  552. autoContinueBar.style.display = 'none';
  553. btnAutoRun.innerHTML = `运行中${runLabel}`;
  554. break;
  555. case 'retrying':
  556. autoContinueBar.style.display = 'none';
  557. btnAutoRun.innerHTML = `重试中${runLabel}`;
  558. break;
  559. default:
  560. autoContinueBar.style.display = 'none';
  561. setDefaultAutoRunButton();
  562. inputEmail.disabled = false;
  563. if (!locked) {
  564. btnFetchEmail.disabled = false;
  565. }
  566. break;
  567. }
  568. updateAutoDelayInputState();
  569. syncScheduledCountdownTicker();
  570. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  571. }
  572. function initializeManualStepActions() {
  573. document.querySelectorAll('.step-row').forEach((row) => {
  574. const step = Number(row.dataset.step);
  575. const statusEl = row.querySelector('.step-status');
  576. if (!statusEl) return;
  577. const actions = document.createElement('div');
  578. actions.className = 'step-actions';
  579. const manualBtn = document.createElement('button');
  580. manualBtn.type = 'button';
  581. manualBtn.className = 'step-manual-btn';
  582. manualBtn.dataset.step = String(step);
  583. manualBtn.title = '跳过此步';
  584. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  585. 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>';
  586. manualBtn.addEventListener('click', async (event) => {
  587. event.stopPropagation();
  588. try {
  589. await handleSkipStep(step);
  590. } catch (err) {
  591. showToast(err.message, 'error');
  592. }
  593. });
  594. statusEl.parentNode.replaceChild(actions, statusEl);
  595. actions.appendChild(manualBtn);
  596. actions.appendChild(statusEl);
  597. });
  598. }
  599. // ============================================================
  600. // State Restore on load
  601. // ============================================================
  602. async function restoreState() {
  603. try {
  604. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  605. syncLatestState(state);
  606. syncAutoRunState(state);
  607. if (state.oauthUrl) {
  608. displayOauthUrl.textContent = state.oauthUrl;
  609. displayOauthUrl.classList.add('has-value');
  610. }
  611. if (state.localhostUrl) {
  612. displayLocalhostUrl.textContent = state.localhostUrl;
  613. displayLocalhostUrl.classList.add('has-value');
  614. }
  615. if (state.email) {
  616. inputEmail.value = state.email;
  617. }
  618. syncPasswordField(state);
  619. if (state.vpsUrl) {
  620. inputVpsUrl.value = state.vpsUrl;
  621. }
  622. if (state.vpsPassword) {
  623. inputVpsPassword.value = state.vpsPassword;
  624. }
  625. setLocalCpaStep9Mode(state.localCpaStep9Mode);
  626. if (state.panelMode) {
  627. selectPanelMode.value = state.panelMode;
  628. }
  629. if (state.sub2apiUrl) {
  630. inputSub2ApiUrl.value = state.sub2apiUrl;
  631. }
  632. if (state.sub2apiEmail) {
  633. inputSub2ApiEmail.value = state.sub2apiEmail;
  634. }
  635. if (state.sub2apiPassword) {
  636. inputSub2ApiPassword.value = state.sub2apiPassword;
  637. }
  638. if (state.sub2apiGroupName) {
  639. inputSub2ApiGroup.value = state.sub2apiGroupName;
  640. }
  641. if (state.mailProvider) {
  642. selectMailProvider.value = state.mailProvider;
  643. }
  644. if (state.emailGenerator) {
  645. selectEmailGenerator.value = state.emailGenerator;
  646. }
  647. if (state.inbucketHost) {
  648. inputInbucketHost.value = state.inbucketHost;
  649. }
  650. if (state.inbucketMailbox) {
  651. inputInbucketMailbox.value = state.inbucketMailbox;
  652. }
  653. renderCloudflareDomainOptions(state.cloudflareDomain || '');
  654. setCloudflareDomainEditMode(false, { clearInput: true });
  655. inputAutoSkipFailures.checked = Boolean(state.autoRunSkipFailures);
  656. inputAutoDelayEnabled.checked = Boolean(state.autoRunDelayEnabled);
  657. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state.autoRunDelayMinutes));
  658. if (state.autoRunTotalRuns) {
  659. inputRunCount.value = String(state.autoRunTotalRuns);
  660. }
  661. if (state.stepStatuses) {
  662. for (const [step, status] of Object.entries(state.stepStatuses)) {
  663. updateStepUI(Number(step), status);
  664. }
  665. }
  666. if (state.logs) {
  667. for (const entry of state.logs) {
  668. appendLog(entry);
  669. }
  670. }
  671. applyAutoRunStatus(state);
  672. markSettingsDirty(false);
  673. updateAutoDelayInputState();
  674. updateStatusDisplay(latestState);
  675. updateProgressCounter();
  676. updatePanelModeUI();
  677. updateMailProviderUI();
  678. updateButtonStates();
  679. } catch (err) {
  680. console.error('Failed to restore state:', err);
  681. }
  682. }
  683. function syncPasswordField(state) {
  684. inputPassword.value = state.customPassword || state.password || '';
  685. }
  686. function getSelectedEmailGenerator() {
  687. return selectEmailGenerator.value === 'cloudflare' ? 'cloudflare' : 'duck';
  688. }
  689. function getEmailGeneratorUiCopy() {
  690. if (getSelectedEmailGenerator() === 'cloudflare') {
  691. return {
  692. buttonLabel: '生成 Cloudflare',
  693. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  694. successVerb: '生成',
  695. label: 'Cloudflare 邮箱',
  696. };
  697. }
  698. return {
  699. buttonLabel: '获取 Duck',
  700. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  701. successVerb: '获取',
  702. label: 'Duck 邮箱',
  703. };
  704. }
  705. function getHotmailAccounts(state = latestState) {
  706. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  707. }
  708. function getCurrentHotmailAccount(state = latestState) {
  709. const currentId = state?.currentHotmailAccountId;
  710. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  711. }
  712. function getHotmailAccountsByUsage(mode = 'all', state = latestState) {
  713. const accounts = getHotmailAccounts(state);
  714. if (typeof filterHotmailAccountsByUsage === 'function') {
  715. return filterHotmailAccountsByUsage(accounts, mode);
  716. }
  717. if (mode === 'used') {
  718. return accounts.filter((account) => Boolean(account?.used));
  719. }
  720. return accounts.slice();
  721. }
  722. function getHotmailBulkActionText(mode, count) {
  723. if (typeof getHotmailBulkActionLabel === 'function') {
  724. return getHotmailBulkActionLabel(mode, count);
  725. }
  726. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  727. const prefix = mode === 'used' ? '清空已用' : '全部删除';
  728. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  729. return `${prefix}${suffix}`;
  730. }
  731. function getHotmailListToggleText(expanded, count) {
  732. if (typeof getHotmailListToggleLabel === 'function') {
  733. return getHotmailListToggleLabel(expanded, count);
  734. }
  735. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  736. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  737. return `${expanded ? '收起列表' : '展开列表'}${suffix}`;
  738. }
  739. function updateHotmailListViewport() {
  740. const count = getHotmailAccounts().length;
  741. const usedCount = getHotmailAccountsByUsage('used').length;
  742. if (btnClearUsedHotmailAccounts) {
  743. btnClearUsedHotmailAccounts.textContent = getHotmailBulkActionText('used', usedCount);
  744. btnClearUsedHotmailAccounts.disabled = usedCount === 0;
  745. }
  746. if (btnDeleteAllHotmailAccounts) {
  747. btnDeleteAllHotmailAccounts.textContent = getHotmailBulkActionText('all', count);
  748. btnDeleteAllHotmailAccounts.disabled = count === 0;
  749. }
  750. if (btnToggleHotmailList) {
  751. btnToggleHotmailList.textContent = getHotmailListToggleText(hotmailListExpanded, count);
  752. btnToggleHotmailList.setAttribute('aria-expanded', String(hotmailListExpanded));
  753. btnToggleHotmailList.disabled = count === 0;
  754. }
  755. if (hotmailListShell) {
  756. hotmailListShell.classList.toggle('is-expanded', hotmailListExpanded);
  757. hotmailListShell.classList.toggle('is-collapsed', !hotmailListExpanded);
  758. }
  759. }
  760. function setHotmailListExpanded(expanded, options = {}) {
  761. const { persist = true } = options;
  762. hotmailListExpanded = Boolean(expanded);
  763. updateHotmailListViewport();
  764. if (persist) {
  765. localStorage.setItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY, hotmailListExpanded ? '1' : '0');
  766. }
  767. }
  768. function initHotmailListExpandedState() {
  769. const saved = localStorage.getItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY);
  770. setHotmailListExpanded(saved === '1', { persist: false });
  771. }
  772. function shouldClearCurrentHotmailSelectionLocally(account) {
  773. if (typeof shouldClearHotmailCurrentSelection === 'function') {
  774. return shouldClearHotmailCurrentSelection(account);
  775. }
  776. return Boolean(account) && account.used === true;
  777. }
  778. function upsertHotmailAccountListLocally(accounts, nextAccount) {
  779. if (typeof upsertHotmailAccountInList === 'function') {
  780. return upsertHotmailAccountInList(accounts, nextAccount);
  781. }
  782. const list = Array.isArray(accounts) ? accounts.slice() : [];
  783. if (!nextAccount?.id) return list;
  784. const existingIndex = list.findIndex((account) => account?.id === nextAccount.id);
  785. if (existingIndex === -1) {
  786. list.push(nextAccount);
  787. return list;
  788. }
  789. list[existingIndex] = nextAccount;
  790. return list;
  791. }
  792. function refreshHotmailSelectionUI() {
  793. renderHotmailAccounts();
  794. if (selectMailProvider.value === 'hotmail-api') {
  795. const currentAccount = getCurrentHotmailAccount();
  796. inputEmail.value = currentAccount?.email || latestState?.email || '';
  797. }
  798. }
  799. function applyHotmailAccountMutation(account, options = {}) {
  800. if (!account?.id) return;
  801. const { preserveCurrentSelection = false } = options;
  802. const nextState = {
  803. hotmailAccounts: upsertHotmailAccountListLocally(getHotmailAccounts(), account),
  804. };
  805. if (!preserveCurrentSelection
  806. && latestState?.currentHotmailAccountId === account.id
  807. && shouldClearCurrentHotmailSelectionLocally(account)) {
  808. nextState.currentHotmailAccountId = null;
  809. if (selectMailProvider.value === 'hotmail-api') {
  810. nextState.email = null;
  811. }
  812. }
  813. syncLatestState(nextState);
  814. refreshHotmailSelectionUI();
  815. }
  816. function formatDateTime(timestamp) {
  817. const value = Number(timestamp);
  818. if (!Number.isFinite(value) || value <= 0) {
  819. return '未使用';
  820. }
  821. return new Date(value).toLocaleString('zh-CN', { hour12: false });
  822. }
  823. function getHotmailAvailabilityLabel(account) {
  824. if (account.used) return '已用';
  825. return '可分配';
  826. }
  827. function getHotmailStatusLabel(account) {
  828. if (account.used) return '已用';
  829. switch (account.status) {
  830. case 'authorized':
  831. return '可用';
  832. case 'error':
  833. return '异常';
  834. default:
  835. return '待校验';
  836. }
  837. }
  838. function getHotmailStatusClass(account) {
  839. if (account.used) return 'status-used';
  840. return `status-${account.status || 'pending'}`;
  841. }
  842. function clearHotmailForm() {
  843. inputHotmailEmail.value = '';
  844. inputHotmailClientId.value = '';
  845. inputHotmailPassword.value = '';
  846. inputHotmailRefreshToken.value = '';
  847. }
  848. function renderHotmailAccounts() {
  849. if (!hotmailAccountsList) return;
  850. const accounts = getHotmailAccounts();
  851. const currentId = latestState?.currentHotmailAccountId || '';
  852. if (!accounts.length) {
  853. hotmailAccountsList.innerHTML = '<div class="hotmail-empty">还没有 Hotmail 账号,先添加一条再校验。</div>';
  854. updateHotmailListViewport();
  855. return;
  856. }
  857. hotmailAccountsList.innerHTML = accounts.map((account) => `
  858. <div class="hotmail-account-item${account.id === currentId ? ' is-current' : ''}">
  859. <div class="hotmail-account-top">
  860. <div class="hotmail-account-title-row">
  861. <div class="hotmail-account-email">${escapeHtml(account.email || '(未命名账号)')}</div>
  862. <button
  863. class="hotmail-copy-btn"
  864. type="button"
  865. data-account-action="copy-email"
  866. data-account-id="${escapeHtml(account.id)}"
  867. title="复制邮箱"
  868. aria-label="复制邮箱 ${escapeHtml(account.email || '')}"
  869. >${COPY_ICON}</button>
  870. </div>
  871. <span class="hotmail-status-chip ${escapeHtml(getHotmailStatusClass(account))}">${escapeHtml(getHotmailStatusLabel(account))}</span>
  872. </div>
  873. <div class="hotmail-account-meta">
  874. <span>客户端 ID:${escapeHtml(account.clientId ? `${account.clientId.slice(0, 10)}...` : '未填写')}</span>
  875. <span>刷新令牌:${account.refreshToken ? '已保存' : '未保存'}</span>
  876. <span>分配状态: ${escapeHtml(getHotmailAvailabilityLabel(account))}</span>
  877. <span>上次校验: ${escapeHtml(formatDateTime(account.lastAuthAt))}</span>
  878. <span>上次使用: ${escapeHtml(formatDateTime(account.lastUsedAt))}</span>
  879. </div>
  880. ${account.lastError ? `<div class="hotmail-account-error">${escapeHtml(account.lastError)}</div>` : ''}
  881. <div class="hotmail-account-actions">
  882. <button class="btn btn-outline btn-sm" type="button" data-account-action="select" data-account-id="${escapeHtml(account.id)}">使用此账号</button>
  883. <button class="btn btn-outline btn-sm" type="button" data-account-action="toggle-used" data-account-id="${escapeHtml(account.id)}">${account.used ? '标记未用' : '标记已用'}</button>
  884. <button class="btn btn-primary btn-sm" type="button" data-account-action="verify" data-account-id="${escapeHtml(account.id)}">校验</button>
  885. <button class="btn btn-outline btn-sm" type="button" data-account-action="test" data-account-id="${escapeHtml(account.id)}">复制最新验证码</button>
  886. <button class="btn btn-ghost btn-sm" type="button" data-account-action="delete" data-account-id="${escapeHtml(account.id)}">删除</button>
  887. </div>
  888. </div>
  889. `).join('');
  890. updateHotmailListViewport();
  891. }
  892. function updateMailProviderUI() {
  893. const useInbucket = selectMailProvider.value === 'inbucket';
  894. const useHotmail = selectMailProvider.value === 'hotmail-api';
  895. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  896. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  897. const useCloudflare = selectEmailGenerator.value === 'cloudflare';
  898. rowCfDomain.style.display = !useHotmail && useCloudflare ? '' : 'none';
  899. const { domains } = getCloudflareDomainsFromState();
  900. if (useCloudflare) {
  901. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  902. } else {
  903. setCloudflareDomainEditMode(false, { clearInput: false });
  904. }
  905. if (hotmailSection) {
  906. hotmailSection.style.display = useHotmail ? '' : 'none';
  907. }
  908. selectEmailGenerator.disabled = useHotmail;
  909. btnFetchEmail.hidden = useHotmail;
  910. inputEmail.readOnly = useHotmail;
  911. const uiCopy = getEmailGeneratorUiCopy();
  912. inputEmail.placeholder = useHotmail ? '由 Hotmail 账号池自动分配' : uiCopy.placeholder;
  913. if (!btnFetchEmail.disabled) {
  914. btnFetchEmail.textContent = uiCopy.buttonLabel;
  915. }
  916. if (autoHintText) {
  917. autoHintText.textContent = useHotmail
  918. ? '请先校验并选择一个 Hotmail 账号'
  919. : '先自动获取邮箱,或手动粘贴邮箱后再继续';
  920. }
  921. if (useHotmail) {
  922. const currentAccount = getCurrentHotmailAccount();
  923. inputEmail.value = currentAccount?.email || latestState?.email || '';
  924. }
  925. renderHotmailAccounts();
  926. }
  927. async function saveCloudflareDomainSettings(domains, activeDomain, options = {}) {
  928. const { silent = false } = options;
  929. const normalizedDomains = normalizeCloudflareDomains(domains);
  930. const normalizedActiveDomain = normalizeCloudflareDomainValue(activeDomain) || normalizedDomains[0] || '';
  931. const payload = {
  932. cloudflareDomain: normalizedActiveDomain,
  933. cloudflareDomains: normalizedDomains,
  934. };
  935. const response = await chrome.runtime.sendMessage({
  936. type: 'SAVE_SETTING',
  937. source: 'sidepanel',
  938. payload,
  939. });
  940. if (response?.error) {
  941. throw new Error(response.error);
  942. }
  943. syncLatestState({
  944. ...payload,
  945. });
  946. renderCloudflareDomainOptions(normalizedActiveDomain);
  947. setCloudflareDomainEditMode(false, { clearInput: true });
  948. markSettingsDirty(false);
  949. updateMailProviderUI();
  950. if (!silent) {
  951. showToast('Cloudflare 域名已保存', 'success', 1800);
  952. }
  953. }
  954. function updatePanelModeUI() {
  955. const useSub2Api = selectPanelMode.value === 'sub2api';
  956. rowVpsUrl.style.display = useSub2Api ? 'none' : '';
  957. rowVpsPassword.style.display = useSub2Api ? 'none' : '';
  958. rowLocalCpaStep9Mode.style.display = useSub2Api ? 'none' : '';
  959. rowSub2ApiUrl.style.display = useSub2Api ? '' : 'none';
  960. rowSub2ApiEmail.style.display = useSub2Api ? '' : 'none';
  961. rowSub2ApiPassword.style.display = useSub2Api ? '' : 'none';
  962. rowSub2ApiGroup.style.display = useSub2Api ? '' : 'none';
  963. const step9Btn = document.querySelector('.step-btn[data-step="9"]');
  964. if (step9Btn) {
  965. step9Btn.textContent = useSub2Api ? 'SUB2API 回调验证' : 'CPA 回调验证';
  966. }
  967. }
  968. // ============================================================
  969. // UI Updates
  970. // ============================================================
  971. function updateStepUI(step, status) {
  972. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  973. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  974. syncLatestState({
  975. stepStatuses: {
  976. ...getStepStatuses(),
  977. [step]: status,
  978. },
  979. });
  980. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  981. if (row) {
  982. row.className = `step-row ${status}`;
  983. }
  984. updateButtonStates();
  985. updateProgressCounter();
  986. }
  987. function updateProgressCounter() {
  988. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  989. stepsProgress.textContent = `${completed} / 9`;
  990. }
  991. function updateButtonStates() {
  992. const statuses = getStepStatuses();
  993. const anyRunning = Object.values(statuses).some(s => s === 'running');
  994. const autoLocked = isAutoRunLockedPhase();
  995. const autoScheduled = isAutoRunScheduledPhase();
  996. for (let step = 1; step <= 9; step++) {
  997. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  998. if (!btn) continue;
  999. if (anyRunning || autoLocked || autoScheduled) {
  1000. btn.disabled = true;
  1001. } else if (step === 1) {
  1002. btn.disabled = false;
  1003. } else {
  1004. const prevStatus = statuses[step - 1];
  1005. const currentStatus = statuses[step];
  1006. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  1007. }
  1008. }
  1009. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  1010. const step = Number(btn.dataset.step);
  1011. const currentStatus = statuses[step];
  1012. const prevStatus = statuses[step - 1];
  1013. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  1014. btn.style.display = 'none';
  1015. btn.disabled = true;
  1016. btn.title = '当前不可跳过';
  1017. return;
  1018. }
  1019. if (step > 1 && !isDoneStatus(prevStatus)) {
  1020. btn.style.display = 'none';
  1021. btn.disabled = true;
  1022. btn.title = `请先完成步骤 ${step - 1}`;
  1023. return;
  1024. }
  1025. btn.style.display = '';
  1026. btn.disabled = false;
  1027. btn.title = `跳过步骤 ${step}`;
  1028. });
  1029. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  1030. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  1031. }
  1032. function updateStopButtonState(active) {
  1033. btnStop.disabled = !active;
  1034. }
  1035. function updateStatusDisplay(state) {
  1036. if (!state || !state.stepStatuses) return;
  1037. statusBar.className = 'status-bar';
  1038. if (isAutoRunScheduledPhase()) {
  1039. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  1040. ? currentAutoRun.scheduledAt - Date.now()
  1041. : 0;
  1042. displayStatus.textContent = remainingMs > 0
  1043. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  1044. : '倒计时即将结束,正在准备启动...';
  1045. statusBar.classList.add('scheduled');
  1046. return;
  1047. }
  1048. if (isAutoRunPausedPhase()) {
  1049. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  1050. statusBar.classList.add('paused');
  1051. return;
  1052. }
  1053. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  1054. if (running) {
  1055. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  1056. statusBar.classList.add('running');
  1057. return;
  1058. }
  1059. if (isAutoRunLockedPhase()) {
  1060. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  1061. statusBar.classList.add('running');
  1062. return;
  1063. }
  1064. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  1065. if (failed) {
  1066. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  1067. statusBar.classList.add('failed');
  1068. return;
  1069. }
  1070. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  1071. if (stopped) {
  1072. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  1073. statusBar.classList.add('stopped');
  1074. return;
  1075. }
  1076. const lastCompleted = Object.entries(state.stepStatuses)
  1077. .filter(([, s]) => isDoneStatus(s))
  1078. .map(([k]) => Number(k))
  1079. .sort((a, b) => b - a)[0];
  1080. if (lastCompleted === 9) {
  1081. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  1082. statusBar.classList.add('completed');
  1083. } else if (lastCompleted) {
  1084. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  1085. ? `步骤 ${lastCompleted} 已跳过`
  1086. : `步骤 ${lastCompleted} 已完成`;
  1087. } else {
  1088. displayStatus.textContent = '就绪';
  1089. }
  1090. }
  1091. function appendLog(entry) {
  1092. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  1093. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  1094. const line = document.createElement('div');
  1095. line.className = `log-line log-${entry.level}`;
  1096. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  1097. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  1098. let html = `<span class="log-time">${time}</span> `;
  1099. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  1100. if (stepNum) {
  1101. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  1102. }
  1103. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  1104. line.innerHTML = html;
  1105. logArea.appendChild(line);
  1106. logArea.scrollTop = logArea.scrollHeight;
  1107. }
  1108. function escapeHtml(text) {
  1109. const div = document.createElement('div');
  1110. div.textContent = text;
  1111. return div.innerHTML;
  1112. }
  1113. async function fetchGeneratedEmail(options = {}) {
  1114. const { showFailureToast = true } = options;
  1115. const uiCopy = getEmailGeneratorUiCopy();
  1116. const defaultLabel = uiCopy.buttonLabel;
  1117. btnFetchEmail.disabled = true;
  1118. btnFetchEmail.textContent = '...';
  1119. try {
  1120. const response = await chrome.runtime.sendMessage({
  1121. type: 'FETCH_GENERATED_EMAIL',
  1122. source: 'sidepanel',
  1123. payload: {
  1124. generateNew: true,
  1125. generator: selectEmailGenerator.value,
  1126. },
  1127. });
  1128. if (response?.error) {
  1129. throw new Error(response.error);
  1130. }
  1131. if (!response?.email) {
  1132. throw new Error('未返回可用邮箱。');
  1133. }
  1134. inputEmail.value = response.email;
  1135. showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500);
  1136. return response.email;
  1137. } catch (err) {
  1138. if (showFailureToast) {
  1139. showToast(`${uiCopy.label}${uiCopy.successVerb}失败:${err.message}`, 'error');
  1140. }
  1141. throw err;
  1142. } finally {
  1143. btnFetchEmail.disabled = false;
  1144. btnFetchEmail.textContent = defaultLabel;
  1145. }
  1146. }
  1147. function syncToggleButtonLabel(button, input, labels) {
  1148. if (!button || !input) return;
  1149. const isHidden = input.type === 'password';
  1150. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  1151. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  1152. button.title = isHidden ? labels.show : labels.hide;
  1153. }
  1154. async function copyTextToClipboard(text) {
  1155. const value = String(text || '').trim();
  1156. if (!value) {
  1157. throw new Error('没有可复制的内容。');
  1158. }
  1159. if (!navigator.clipboard?.writeText) {
  1160. throw new Error('当前环境不支持剪贴板复制。');
  1161. }
  1162. await navigator.clipboard.writeText(value);
  1163. }
  1164. async function deleteHotmailAccountsByMode(mode) {
  1165. const isUsedMode = mode === 'used';
  1166. const targetAccounts = getHotmailAccountsByUsage(isUsedMode ? 'used' : 'all');
  1167. if (!targetAccounts.length) {
  1168. showToast(isUsedMode ? '没有已用账号可清空。' : '没有可删除的 Hotmail 账号。', 'warn');
  1169. return;
  1170. }
  1171. const confirmed = await openConfirmModal({
  1172. title: isUsedMode ? '清空已用账号' : '全部删除账号',
  1173. message: isUsedMode
  1174. ? `确认删除当前 ${targetAccounts.length} 个已用 Hotmail 账号吗?`
  1175. : `确认删除全部 ${targetAccounts.length} 个 Hotmail 账号吗?`,
  1176. confirmLabel: isUsedMode ? '确认清空已用' : '确认全部删除',
  1177. confirmVariant: isUsedMode ? 'btn-outline' : 'btn-danger',
  1178. });
  1179. if (!confirmed) {
  1180. return;
  1181. }
  1182. const response = await chrome.runtime.sendMessage({
  1183. type: 'DELETE_HOTMAIL_ACCOUNTS',
  1184. source: 'sidepanel',
  1185. payload: { mode: isUsedMode ? 'used' : 'all' },
  1186. });
  1187. if (response?.error) {
  1188. throw new Error(response.error);
  1189. }
  1190. const targetIds = new Set(targetAccounts.map((account) => account.id));
  1191. const nextAccounts = isUsedMode
  1192. ? getHotmailAccounts().filter((account) => !targetIds.has(account.id))
  1193. : [];
  1194. const nextState = { hotmailAccounts: nextAccounts };
  1195. if (latestState?.currentHotmailAccountId && targetIds.has(latestState.currentHotmailAccountId)) {
  1196. nextState.currentHotmailAccountId = null;
  1197. if (selectMailProvider.value === 'hotmail-api') {
  1198. nextState.email = null;
  1199. }
  1200. }
  1201. syncLatestState(nextState);
  1202. refreshHotmailSelectionUI();
  1203. showToast(
  1204. isUsedMode
  1205. ? `已清空 ${response.deletedCount || 0} 个已用 Hotmail 账号`
  1206. : `已删除全部 ${response.deletedCount || 0} 个 Hotmail 账号`,
  1207. 'success',
  1208. 2200
  1209. );
  1210. }
  1211. function syncPasswordToggleLabel() {
  1212. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  1213. show: '显示密码',
  1214. hide: '隐藏密码',
  1215. });
  1216. }
  1217. function syncVpsUrlToggleLabel() {
  1218. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  1219. show: '显示 CPA 地址',
  1220. hide: '隐藏 CPA 地址',
  1221. });
  1222. }
  1223. async function maybeTakeoverAutoRun(actionLabel) {
  1224. if (!isAutoRunPausedPhase()) {
  1225. return true;
  1226. }
  1227. const confirmed = await openConfirmModal({
  1228. title: '接管自动',
  1229. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  1230. confirmLabel: '确认接管',
  1231. confirmVariant: 'btn-primary',
  1232. });
  1233. if (!confirmed) {
  1234. return false;
  1235. }
  1236. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  1237. return true;
  1238. }
  1239. async function handleSkipStep(step) {
  1240. if (isAutoRunPausedPhase()) {
  1241. const takeoverResponse = await chrome.runtime.sendMessage({
  1242. type: 'TAKEOVER_AUTO_RUN',
  1243. source: 'sidepanel',
  1244. payload: {},
  1245. });
  1246. if (takeoverResponse?.error) {
  1247. throw new Error(takeoverResponse.error);
  1248. }
  1249. }
  1250. const response = await chrome.runtime.sendMessage({
  1251. type: 'SKIP_STEP',
  1252. source: 'sidepanel',
  1253. payload: { step },
  1254. });
  1255. if (response?.error) {
  1256. throw new Error(response.error);
  1257. }
  1258. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  1259. }
  1260. // ============================================================
  1261. // Button Handlers
  1262. // ============================================================
  1263. document.querySelectorAll('.step-btn').forEach(btn => {
  1264. btn.addEventListener('click', async () => {
  1265. try {
  1266. const step = Number(btn.dataset.step);
  1267. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  1268. return;
  1269. }
  1270. if (step === 3) {
  1271. if (inputPassword.value !== (latestState?.customPassword || '')) {
  1272. await chrome.runtime.sendMessage({
  1273. type: 'SAVE_SETTING',
  1274. source: 'sidepanel',
  1275. payload: { customPassword: inputPassword.value },
  1276. });
  1277. syncLatestState({ customPassword: inputPassword.value });
  1278. }
  1279. let email = inputEmail.value.trim();
  1280. if (selectMailProvider.value === 'hotmail-api') {
  1281. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  1282. if (response?.error) {
  1283. throw new Error(response.error);
  1284. }
  1285. } else {
  1286. let email = inputEmail.value.trim();
  1287. if (!email) {
  1288. try {
  1289. email = await fetchGeneratedEmail({ showFailureToast: false });
  1290. } catch (err) {
  1291. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  1292. return;
  1293. }
  1294. }
  1295. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  1296. if (response?.error) {
  1297. throw new Error(response.error);
  1298. }
  1299. }
  1300. } else {
  1301. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  1302. if (response?.error) {
  1303. throw new Error(response.error);
  1304. }
  1305. }
  1306. } catch (err) {
  1307. showToast(err.message, 'error');
  1308. }
  1309. });
  1310. });
  1311. btnFetchEmail.addEventListener('click', async () => {
  1312. if (selectMailProvider.value === 'hotmail-api') {
  1313. return;
  1314. }
  1315. await fetchGeneratedEmail().catch(() => { });
  1316. });
  1317. btnToggleHotmailList?.addEventListener('click', () => {
  1318. setHotmailListExpanded(!hotmailListExpanded);
  1319. });
  1320. btnClearUsedHotmailAccounts?.addEventListener('click', async () => {
  1321. if (hotmailActionInFlight) return;
  1322. hotmailActionInFlight = true;
  1323. btnClearUsedHotmailAccounts.disabled = true;
  1324. try {
  1325. await deleteHotmailAccountsByMode('used');
  1326. } catch (err) {
  1327. showToast(err.message, 'error');
  1328. } finally {
  1329. hotmailActionInFlight = false;
  1330. updateHotmailListViewport();
  1331. }
  1332. });
  1333. btnDeleteAllHotmailAccounts?.addEventListener('click', async () => {
  1334. if (hotmailActionInFlight) return;
  1335. hotmailActionInFlight = true;
  1336. btnDeleteAllHotmailAccounts.disabled = true;
  1337. try {
  1338. await deleteHotmailAccountsByMode('all');
  1339. } catch (err) {
  1340. showToast(err.message, 'error');
  1341. } finally {
  1342. hotmailActionInFlight = false;
  1343. updateHotmailListViewport();
  1344. }
  1345. });
  1346. btnAddHotmailAccount?.addEventListener('click', async () => {
  1347. if (hotmailActionInFlight) return;
  1348. const email = inputHotmailEmail.value.trim();
  1349. const clientId = inputHotmailClientId.value.trim();
  1350. const refreshToken = inputHotmailRefreshToken.value.trim();
  1351. if (!email) {
  1352. showToast('请先填写 Hotmail 邮箱。', 'warn');
  1353. return;
  1354. }
  1355. if (!clientId) {
  1356. showToast('请先填写微软应用客户端 ID。', 'warn');
  1357. return;
  1358. }
  1359. if (!refreshToken) {
  1360. showToast('请先填写刷新令牌(refresh token)。', 'warn');
  1361. return;
  1362. }
  1363. hotmailActionInFlight = true;
  1364. btnAddHotmailAccount.disabled = true;
  1365. try {
  1366. const response = await chrome.runtime.sendMessage({
  1367. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1368. source: 'sidepanel',
  1369. payload: {
  1370. email,
  1371. clientId,
  1372. password: inputHotmailPassword.value,
  1373. refreshToken,
  1374. },
  1375. });
  1376. if (response?.error) {
  1377. throw new Error(response.error);
  1378. }
  1379. showToast(`已保存 Hotmail 账号 ${email}`, 'success', 1800);
  1380. clearHotmailForm();
  1381. } catch (err) {
  1382. showToast(`保存 Hotmail 账号失败:${err.message}`, 'error');
  1383. } finally {
  1384. hotmailActionInFlight = false;
  1385. btnAddHotmailAccount.disabled = false;
  1386. }
  1387. });
  1388. btnImportHotmailAccounts?.addEventListener('click', async () => {
  1389. if (hotmailActionInFlight) return;
  1390. if (typeof parseHotmailImportText !== 'function') {
  1391. showToast('导入解析器未加载,请刷新扩展后重试。', 'error');
  1392. return;
  1393. }
  1394. const rawText = inputHotmailImport.value.trim();
  1395. if (!rawText) {
  1396. showToast('请先粘贴账号导入内容。', 'warn');
  1397. return;
  1398. }
  1399. const parsedAccounts = parseHotmailImportText(rawText);
  1400. if (!parsedAccounts.length) {
  1401. showToast('没有解析到有效账号,请检查格式是否为 账号----密码----ID----Token。', 'error');
  1402. return;
  1403. }
  1404. hotmailActionInFlight = true;
  1405. btnImportHotmailAccounts.disabled = true;
  1406. try {
  1407. for (const account of parsedAccounts) {
  1408. const response = await chrome.runtime.sendMessage({
  1409. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1410. source: 'sidepanel',
  1411. payload: account,
  1412. });
  1413. if (response?.error) {
  1414. throw new Error(response.error);
  1415. }
  1416. }
  1417. inputHotmailImport.value = '';
  1418. showToast(`已导入 ${parsedAccounts.length} 条 Hotmail 账号`, 'success', 2200);
  1419. } catch (err) {
  1420. showToast(`批量导入失败:${err.message}`, 'error');
  1421. } finally {
  1422. hotmailActionInFlight = false;
  1423. btnImportHotmailAccounts.disabled = false;
  1424. }
  1425. });
  1426. hotmailAccountsList?.addEventListener('click', async (event) => {
  1427. const actionButton = event.target.closest('[data-account-action]');
  1428. if (!actionButton || hotmailActionInFlight) {
  1429. return;
  1430. }
  1431. const accountId = actionButton.dataset.accountId;
  1432. const action = actionButton.dataset.accountAction;
  1433. if (!accountId || !action) {
  1434. return;
  1435. }
  1436. const targetAccount = getHotmailAccounts().find((account) => account.id === accountId) || null;
  1437. hotmailActionInFlight = true;
  1438. actionButton.disabled = true;
  1439. try {
  1440. if (action === 'copy-email') {
  1441. if (!targetAccount?.email) throw new Error('未找到可复制的邮箱地址。');
  1442. await copyTextToClipboard(targetAccount.email);
  1443. showToast(`已复制 ${targetAccount.email}`, 'success', 1800);
  1444. } else if (action === 'select') {
  1445. const response = await chrome.runtime.sendMessage({
  1446. type: 'SELECT_HOTMAIL_ACCOUNT',
  1447. source: 'sidepanel',
  1448. payload: { accountId },
  1449. });
  1450. if (response?.error) throw new Error(response.error);
  1451. syncLatestState({ currentHotmailAccountId: response.account.id });
  1452. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1453. showToast(`已切换当前 Hotmail 账号为 ${response.account.email}`, 'success', 1800);
  1454. } else if (action === 'toggle-used') {
  1455. if (!targetAccount) throw new Error('未找到目标 Hotmail 账号。');
  1456. const response = await chrome.runtime.sendMessage({
  1457. type: 'PATCH_HOTMAIL_ACCOUNT',
  1458. source: 'sidepanel',
  1459. payload: {
  1460. accountId,
  1461. updates: { used: !targetAccount.used },
  1462. },
  1463. });
  1464. if (response?.error) throw new Error(response.error);
  1465. applyHotmailAccountMutation(response.account);
  1466. showToast(`账号 ${response.account.email} 已${response.account.used ? '标记为已用' : '恢复为未用'}`, 'success', 2200);
  1467. } else if (action === 'verify') {
  1468. const response = await chrome.runtime.sendMessage({
  1469. type: 'VERIFY_HOTMAIL_ACCOUNT',
  1470. source: 'sidepanel',
  1471. payload: { accountId },
  1472. });
  1473. if (response?.error) throw new Error(response.error);
  1474. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1475. showToast(`账号 ${response.account.email} 校验通过`, 'success', 2200);
  1476. } else if (action === 'test') {
  1477. const response = await chrome.runtime.sendMessage({
  1478. type: 'TEST_HOTMAIL_ACCOUNT',
  1479. source: 'sidepanel',
  1480. payload: { accountId },
  1481. });
  1482. if (response?.error) throw new Error(response.error);
  1483. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1484. if (response.latestCode) {
  1485. await copyTextToClipboard(response.latestCode);
  1486. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1487. showToast(`已复制最新验证码 ${response.latestCode}${mailbox}`, 'success', 2600);
  1488. } else if (response.latestSubject) {
  1489. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1490. showToast(`最新邮件${mailbox}没有验证码:${response.latestSubject}`, 'warn', 3200);
  1491. } else {
  1492. showToast('当前没有可读取的最新邮件。', 'warn', 2600);
  1493. }
  1494. } else if (action === 'delete') {
  1495. const confirmed = await openConfirmModal({
  1496. title: '删除账号',
  1497. message: '确认删除这个 Hotmail 账号吗?对应 token 也会一起移除。',
  1498. confirmLabel: '确认删除',
  1499. confirmVariant: 'btn-danger',
  1500. });
  1501. if (!confirmed) {
  1502. return;
  1503. }
  1504. const response = await chrome.runtime.sendMessage({
  1505. type: 'DELETE_HOTMAIL_ACCOUNT',
  1506. source: 'sidepanel',
  1507. payload: { accountId },
  1508. });
  1509. if (response?.error) throw new Error(response.error);
  1510. showToast('Hotmail 账号已删除', 'success', 1800);
  1511. }
  1512. } catch (err) {
  1513. showToast(err.message, 'error');
  1514. } finally {
  1515. hotmailActionInFlight = false;
  1516. actionButton.disabled = false;
  1517. }
  1518. });
  1519. btnTogglePassword.addEventListener('click', () => {
  1520. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  1521. syncPasswordToggleLabel();
  1522. });
  1523. btnToggleVpsUrl.addEventListener('click', () => {
  1524. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  1525. syncVpsUrlToggleLabel();
  1526. });
  1527. localCpaStep9ModeButtons.forEach((button) => {
  1528. button.addEventListener('click', () => {
  1529. const nextMode = button.dataset.localCpaStep9Mode;
  1530. if (getSelectedLocalCpaStep9Mode() === normalizeLocalCpaStep9Mode(nextMode)) {
  1531. return;
  1532. }
  1533. setLocalCpaStep9Mode(nextMode);
  1534. markSettingsDirty(true);
  1535. saveSettings({ silent: true }).catch(() => { });
  1536. });
  1537. });
  1538. btnSaveSettings.addEventListener('click', async () => {
  1539. if (!settingsDirty) {
  1540. showToast('配置已是最新', 'info', 1400);
  1541. return;
  1542. }
  1543. await saveSettings({ silent: false }).catch(() => { });
  1544. });
  1545. btnStop.addEventListener('click', async () => {
  1546. btnStop.disabled = true;
  1547. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  1548. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  1549. });
  1550. autoStartModal?.addEventListener('click', (event) => {
  1551. if (event.target === autoStartModal) {
  1552. resolveModalChoice(null);
  1553. }
  1554. });
  1555. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  1556. // Auto Run
  1557. btnAutoRun.addEventListener('click', async () => {
  1558. try {
  1559. const totalRuns = Math.min(50, Math.max(1, parseInt(inputRunCount.value, 10) || 1));
  1560. let mode = 'restart';
  1561. if (shouldOfferAutoModeChoice()) {
  1562. const startStep = getFirstUnfinishedStep();
  1563. const choice = await openAutoStartChoiceDialog(startStep);
  1564. if (!choice) {
  1565. return;
  1566. }
  1567. mode = choice;
  1568. }
  1569. btnAutoRun.disabled = true;
  1570. inputRunCount.disabled = true;
  1571. const delayEnabled = inputAutoDelayEnabled.checked;
  1572. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  1573. inputAutoDelayMinutes.value = String(delayMinutes);
  1574. btnAutoRun.innerHTML = delayEnabled
  1575. ? '<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> 计划中...'
  1576. : '<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> 运行中...';
  1577. const response = await chrome.runtime.sendMessage({
  1578. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  1579. source: 'sidepanel',
  1580. payload: {
  1581. totalRuns,
  1582. delayMinutes,
  1583. autoRunSkipFailures: inputAutoSkipFailures.checked,
  1584. mode,
  1585. },
  1586. });
  1587. if (response?.error) {
  1588. throw new Error(response.error);
  1589. }
  1590. } catch (err) {
  1591. setDefaultAutoRunButton();
  1592. inputRunCount.disabled = false;
  1593. showToast(err.message, 'error');
  1594. }
  1595. });
  1596. btnAutoContinue.addEventListener('click', async () => {
  1597. const email = inputEmail.value.trim();
  1598. if (!email) {
  1599. showToast('请先获取或粘贴邮箱。', 'warn');
  1600. return;
  1601. }
  1602. autoContinueBar.style.display = 'none';
  1603. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  1604. });
  1605. btnAutoRunNow?.addEventListener('click', async () => {
  1606. try {
  1607. btnAutoRunNow.disabled = true;
  1608. await chrome.runtime.sendMessage({ type: 'START_SCHEDULED_AUTO_RUN_NOW', source: 'sidepanel', payload: {} });
  1609. } catch (err) {
  1610. showToast(err.message, 'error');
  1611. } finally {
  1612. btnAutoRunNow.disabled = false;
  1613. }
  1614. });
  1615. btnAutoCancelSchedule?.addEventListener('click', async () => {
  1616. try {
  1617. btnAutoCancelSchedule.disabled = true;
  1618. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  1619. showToast('已取消倒计时计划。', 'info', 1800);
  1620. } catch (err) {
  1621. showToast(err.message, 'error');
  1622. } finally {
  1623. btnAutoCancelSchedule.disabled = false;
  1624. }
  1625. });
  1626. // Reset
  1627. btnReset.addEventListener('click', async () => {
  1628. const confirmed = await openConfirmModal({
  1629. title: '重置流程',
  1630. message: '确认重置全部步骤和数据吗?',
  1631. confirmLabel: '确认重置',
  1632. confirmVariant: 'btn-danger',
  1633. });
  1634. if (!confirmed) {
  1635. return;
  1636. }
  1637. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  1638. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES, currentHotmailAccountId: null, email: null });
  1639. syncAutoRunState({
  1640. autoRunning: false,
  1641. autoRunPhase: 'idle',
  1642. autoRunCurrentRun: 0,
  1643. autoRunTotalRuns: 1,
  1644. autoRunAttemptRun: 0,
  1645. scheduledAutoRunAt: null,
  1646. });
  1647. displayOauthUrl.textContent = '等待中...';
  1648. displayOauthUrl.classList.remove('has-value');
  1649. displayLocalhostUrl.textContent = '等待中...';
  1650. displayLocalhostUrl.classList.remove('has-value');
  1651. inputEmail.value = '';
  1652. displayStatus.textContent = '就绪';
  1653. statusBar.className = 'status-bar';
  1654. logArea.innerHTML = '';
  1655. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1656. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1657. setDefaultAutoRunButton();
  1658. applyAutoRunStatus(currentAutoRun);
  1659. markSettingsDirty(false);
  1660. updateStopButtonState(false);
  1661. updateButtonStates();
  1662. updateProgressCounter();
  1663. renderHotmailAccounts();
  1664. });
  1665. // Clear log
  1666. btnClearLog.addEventListener('click', () => {
  1667. logArea.innerHTML = '';
  1668. });
  1669. // Save settings on change
  1670. inputEmail.addEventListener('change', async () => {
  1671. if (selectMailProvider.value === 'hotmail-api') {
  1672. return;
  1673. }
  1674. const email = inputEmail.value.trim();
  1675. if (email) {
  1676. await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  1677. }
  1678. });
  1679. inputEmail.addEventListener('input', updateButtonStates);
  1680. inputVpsUrl.addEventListener('input', () => {
  1681. markSettingsDirty(true);
  1682. scheduleSettingsAutoSave();
  1683. });
  1684. inputVpsUrl.addEventListener('blur', () => {
  1685. saveSettings({ silent: true }).catch(() => { });
  1686. });
  1687. inputVpsPassword.addEventListener('input', () => {
  1688. markSettingsDirty(true);
  1689. scheduleSettingsAutoSave();
  1690. });
  1691. inputVpsPassword.addEventListener('blur', () => {
  1692. saveSettings({ silent: true }).catch(() => { });
  1693. });
  1694. inputPassword.addEventListener('input', () => {
  1695. markSettingsDirty(true);
  1696. updateButtonStates();
  1697. scheduleSettingsAutoSave();
  1698. });
  1699. inputPassword.addEventListener('blur', () => {
  1700. saveSettings({ silent: true }).catch(() => { });
  1701. });
  1702. selectMailProvider.addEventListener('change', () => {
  1703. updateMailProviderUI();
  1704. markSettingsDirty(true);
  1705. saveSettings({ silent: true }).catch(() => { });
  1706. });
  1707. selectEmailGenerator.addEventListener('change', () => {
  1708. updateMailProviderUI();
  1709. markSettingsDirty(true);
  1710. saveSettings({ silent: true }).catch(() => { });
  1711. });
  1712. selectPanelMode.addEventListener('change', () => {
  1713. updatePanelModeUI();
  1714. markSettingsDirty(true);
  1715. saveSettings({ silent: true }).catch(() => { });
  1716. });
  1717. selectCfDomain.addEventListener('change', () => {
  1718. if (selectCfDomain.disabled) {
  1719. return;
  1720. }
  1721. markSettingsDirty(true);
  1722. saveSettings({ silent: true }).catch(() => { });
  1723. });
  1724. btnCfDomainMode.addEventListener('click', async () => {
  1725. try {
  1726. if (!cloudflareDomainEditMode) {
  1727. setCloudflareDomainEditMode(true, { clearInput: true });
  1728. return;
  1729. }
  1730. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  1731. if (!newDomain) {
  1732. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  1733. inputCfDomain.focus();
  1734. return;
  1735. }
  1736. const { domains } = getCloudflareDomainsFromState();
  1737. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  1738. } catch (err) {
  1739. showToast(err.message, 'error');
  1740. }
  1741. });
  1742. inputCfDomain.addEventListener('keydown', (event) => {
  1743. if (event.key === 'Enter') {
  1744. event.preventDefault();
  1745. btnCfDomainMode.click();
  1746. }
  1747. });
  1748. inputSub2ApiUrl.addEventListener('input', () => {
  1749. markSettingsDirty(true);
  1750. scheduleSettingsAutoSave();
  1751. });
  1752. inputSub2ApiUrl.addEventListener('blur', () => {
  1753. saveSettings({ silent: true }).catch(() => { });
  1754. });
  1755. inputSub2ApiEmail.addEventListener('input', () => {
  1756. markSettingsDirty(true);
  1757. scheduleSettingsAutoSave();
  1758. });
  1759. inputSub2ApiEmail.addEventListener('blur', () => {
  1760. saveSettings({ silent: true }).catch(() => { });
  1761. });
  1762. inputSub2ApiPassword.addEventListener('input', () => {
  1763. markSettingsDirty(true);
  1764. scheduleSettingsAutoSave();
  1765. });
  1766. inputSub2ApiPassword.addEventListener('blur', () => {
  1767. saveSettings({ silent: true }).catch(() => { });
  1768. });
  1769. inputSub2ApiGroup.addEventListener('input', () => {
  1770. markSettingsDirty(true);
  1771. scheduleSettingsAutoSave();
  1772. });
  1773. inputSub2ApiGroup.addEventListener('blur', () => {
  1774. saveSettings({ silent: true }).catch(() => { });
  1775. });
  1776. inputInbucketMailbox.addEventListener('input', () => {
  1777. markSettingsDirty(true);
  1778. scheduleSettingsAutoSave();
  1779. });
  1780. inputInbucketMailbox.addEventListener('blur', () => {
  1781. saveSettings({ silent: true }).catch(() => { });
  1782. });
  1783. inputInbucketHost.addEventListener('input', () => {
  1784. markSettingsDirty(true);
  1785. scheduleSettingsAutoSave();
  1786. });
  1787. inputInbucketHost.addEventListener('blur', () => {
  1788. saveSettings({ silent: true }).catch(() => { });
  1789. });
  1790. inputAutoSkipFailures.addEventListener('change', () => {
  1791. markSettingsDirty(true);
  1792. saveSettings({ silent: true }).catch(() => { });
  1793. });
  1794. inputAutoDelayEnabled.addEventListener('change', () => {
  1795. updateAutoDelayInputState();
  1796. markSettingsDirty(true);
  1797. saveSettings({ silent: true }).catch(() => { });
  1798. });
  1799. inputAutoDelayMinutes.addEventListener('input', () => {
  1800. markSettingsDirty(true);
  1801. scheduleSettingsAutoSave();
  1802. });
  1803. inputAutoDelayMinutes.addEventListener('blur', () => {
  1804. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  1805. saveSettings({ silent: true }).catch(() => { });
  1806. });
  1807. // ============================================================
  1808. // Listen for Background broadcasts
  1809. // ============================================================
  1810. chrome.runtime.onMessage.addListener((message) => {
  1811. switch (message.type) {
  1812. case 'LOG_ENTRY':
  1813. appendLog(message.payload);
  1814. if (message.payload.level === 'error') {
  1815. showToast(message.payload.message, 'error');
  1816. }
  1817. break;
  1818. case 'STEP_STATUS_CHANGED': {
  1819. const { step, status } = message.payload;
  1820. updateStepUI(step, status);
  1821. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  1822. syncLatestState(state);
  1823. syncAutoRunState(state);
  1824. updateStatusDisplay(latestState);
  1825. updateButtonStates();
  1826. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  1827. syncPasswordField(state);
  1828. if (state.oauthUrl) {
  1829. displayOauthUrl.textContent = state.oauthUrl;
  1830. displayOauthUrl.classList.add('has-value');
  1831. }
  1832. if (state.localhostUrl) {
  1833. displayLocalhostUrl.textContent = state.localhostUrl;
  1834. displayLocalhostUrl.classList.add('has-value');
  1835. }
  1836. }
  1837. }
  1838. ).catch(() => { });
  1839. break;
  1840. }
  1841. case 'AUTO_RUN_RESET': {
  1842. // Full UI reset for next run
  1843. syncLatestState({
  1844. oauthUrl: null,
  1845. localhostUrl: null,
  1846. email: null,
  1847. password: null,
  1848. stepStatuses: STEP_DEFAULT_STATUSES,
  1849. logs: [],
  1850. scheduledAutoRunAt: null,
  1851. });
  1852. displayOauthUrl.textContent = '等待中...';
  1853. displayOauthUrl.classList.remove('has-value');
  1854. displayLocalhostUrl.textContent = '等待中...';
  1855. displayLocalhostUrl.classList.remove('has-value');
  1856. inputEmail.value = '';
  1857. displayStatus.textContent = '就绪';
  1858. statusBar.className = 'status-bar';
  1859. logArea.innerHTML = '';
  1860. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1861. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1862. applyAutoRunStatus(currentAutoRun);
  1863. updateProgressCounter();
  1864. updateButtonStates();
  1865. renderHotmailAccounts();
  1866. break;
  1867. }
  1868. case 'DATA_UPDATED': {
  1869. syncLatestState(message.payload);
  1870. if (message.payload.email !== undefined) {
  1871. inputEmail.value = message.payload.email || '';
  1872. }
  1873. if (message.payload.password !== undefined) {
  1874. inputPassword.value = message.payload.password || '';
  1875. }
  1876. if (message.payload.oauthUrl !== undefined) {
  1877. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  1878. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  1879. }
  1880. if (message.payload.localhostUrl !== undefined) {
  1881. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  1882. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  1883. }
  1884. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  1885. renderHotmailAccounts();
  1886. if (selectMailProvider.value === 'hotmail-api') {
  1887. const currentAccount = getCurrentHotmailAccount();
  1888. inputEmail.value = currentAccount?.email || latestState?.email || '';
  1889. }
  1890. }
  1891. if (message.payload.autoRunDelayEnabled !== undefined) {
  1892. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  1893. updateAutoDelayInputState();
  1894. }
  1895. if (message.payload.autoRunDelayMinutes !== undefined) {
  1896. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  1897. }
  1898. break;
  1899. }
  1900. case 'AUTO_RUN_STATUS': {
  1901. syncLatestState({
  1902. autoRunning: ['scheduled', 'running', 'waiting_email', 'retrying'].includes(message.payload.phase),
  1903. autoRunPhase: message.payload.phase,
  1904. autoRunCurrentRun: message.payload.currentRun,
  1905. autoRunTotalRuns: message.payload.totalRuns,
  1906. autoRunAttemptRun: message.payload.attemptRun,
  1907. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  1908. });
  1909. applyAutoRunStatus(message.payload);
  1910. updateStatusDisplay(latestState);
  1911. updateButtonStates();
  1912. break;
  1913. }
  1914. }
  1915. });
  1916. // ============================================================
  1917. // Theme Toggle
  1918. // ============================================================
  1919. const btnTheme = document.getElementById('btn-theme');
  1920. function setTheme(theme) {
  1921. document.documentElement.setAttribute('data-theme', theme);
  1922. localStorage.setItem('multipage-theme', theme);
  1923. }
  1924. function initTheme() {
  1925. const saved = localStorage.getItem('multipage-theme');
  1926. if (saved) {
  1927. setTheme(saved);
  1928. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  1929. setTheme('dark');
  1930. }
  1931. }
  1932. btnTheme.addEventListener('click', () => {
  1933. const current = document.documentElement.getAttribute('data-theme');
  1934. setTheme(current === 'dark' ? 'light' : 'dark');
  1935. });
  1936. // ============================================================
  1937. // Init
  1938. // ============================================================
  1939. initializeManualStepActions();
  1940. initTheme();
  1941. initHotmailListExpandedState();
  1942. updateSaveButtonState();
  1943. setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
  1944. restoreState().then(() => {
  1945. syncPasswordToggleLabel();
  1946. syncVpsUrlToggleLabel();
  1947. updatePanelModeUI();
  1948. updateButtonStates();
  1949. updateStatusDisplay(latestState);
  1950. });