sidepanel.js 93 KB

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