sidepanel.js 92 KB

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