sidepanel.js 135 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859
  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 updateSection = document.getElementById('update-section');
  13. const extensionUpdateStatus = document.getElementById('extension-update-status');
  14. const extensionVersionMeta = document.getElementById('extension-version-meta');
  15. const btnReleaseLog = document.getElementById('btn-release-log');
  16. const updateCardVersion = document.getElementById('update-card-version');
  17. const updateCardSummary = document.getElementById('update-card-summary');
  18. const updateReleaseList = document.getElementById('update-release-list');
  19. const btnOpenRelease = document.getElementById('btn-open-release');
  20. const settingsCard = document.getElementById('settings-card');
  21. const displayOauthUrl = document.getElementById('display-oauth-url');
  22. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  23. const displayStatus = document.getElementById('display-status');
  24. const statusBar = document.getElementById('status-bar');
  25. const inputEmail = document.getElementById('input-email');
  26. const inputPassword = document.getElementById('input-password');
  27. const btnToggleVpsUrl = document.getElementById('btn-toggle-vps-url');
  28. const btnToggleVpsPassword = document.getElementById('btn-toggle-vps-password');
  29. const btnFetchEmail = document.getElementById('btn-fetch-email');
  30. const btnTogglePassword = document.getElementById('btn-toggle-password');
  31. const btnSaveSettings = document.getElementById('btn-save-settings');
  32. const btnStop = document.getElementById('btn-stop');
  33. const btnReset = document.getElementById('btn-reset');
  34. const stepsProgress = document.getElementById('steps-progress');
  35. const btnAutoRun = document.getElementById('btn-auto-run');
  36. const btnAutoContinue = document.getElementById('btn-auto-continue');
  37. const autoContinueBar = document.getElementById('auto-continue-bar');
  38. const autoScheduleBar = document.getElementById('auto-schedule-bar');
  39. const autoScheduleTitle = document.getElementById('auto-schedule-title');
  40. const autoScheduleMeta = document.getElementById('auto-schedule-meta');
  41. const btnAutoRunNow = document.getElementById('btn-auto-run-now');
  42. const btnAutoCancelSchedule = document.getElementById('btn-auto-cancel-schedule');
  43. const btnClearLog = document.getElementById('btn-clear-log');
  44. const configMenuShell = document.getElementById('config-menu-shell');
  45. const btnConfigMenu = document.getElementById('btn-config-menu');
  46. const configMenu = document.getElementById('config-menu');
  47. const btnExportSettings = document.getElementById('btn-export-settings');
  48. const btnImportSettings = document.getElementById('btn-import-settings');
  49. const inputImportSettingsFile = document.getElementById('input-import-settings-file');
  50. const selectPanelMode = document.getElementById('select-panel-mode');
  51. const rowVpsUrl = document.getElementById('row-vps-url');
  52. const inputVpsUrl = document.getElementById('input-vps-url');
  53. const rowVpsPassword = document.getElementById('row-vps-password');
  54. const inputVpsPassword = document.getElementById('input-vps-password');
  55. const rowLocalCpaStep9Mode = document.getElementById('row-local-cpa-step9-mode');
  56. const localCpaStep9ModeButtons = Array.from(document.querySelectorAll('[data-local-cpa-step9-mode]'));
  57. const rowCpaCallbackMode = document.getElementById('row-cpa-callback-mode');
  58. const cpaCallbackModeButtons = Array.from(document.querySelectorAll('[data-cpa-callback-mode]'));
  59. const rowSub2ApiUrl = document.getElementById('row-sub2api-url');
  60. const inputSub2ApiUrl = document.getElementById('input-sub2api-url');
  61. const rowSub2ApiEmail = document.getElementById('row-sub2api-email');
  62. const inputSub2ApiEmail = document.getElementById('input-sub2api-email');
  63. const rowSub2ApiPassword = document.getElementById('row-sub2api-password');
  64. const inputSub2ApiPassword = document.getElementById('input-sub2api-password');
  65. const rowSub2ApiGroup = document.getElementById('row-sub2api-group');
  66. const inputSub2ApiGroup = document.getElementById('input-sub2api-group');
  67. const selectMailProvider = document.getElementById('select-mail-provider');
  68. const btnMailLogin = document.getElementById('btn-mail-login');
  69. const rowMail2925Mode = document.getElementById('row-mail-2925-mode');
  70. const mail2925ModeButtons = Array.from(document.querySelectorAll('[data-mail2925-mode]'));
  71. const rowEmailGenerator = document.getElementById('row-email-generator');
  72. const selectEmailGenerator = document.getElementById('select-email-generator');
  73. const rowTempEmailBaseUrl = document.getElementById('row-temp-email-base-url');
  74. const inputTempEmailBaseUrl = document.getElementById('input-temp-email-base-url');
  75. const rowTempEmailAdminAuth = document.getElementById('row-temp-email-admin-auth');
  76. const inputTempEmailAdminAuth = document.getElementById('input-temp-email-admin-auth');
  77. const rowTempEmailCustomAuth = document.getElementById('row-temp-email-custom-auth');
  78. const inputTempEmailCustomAuth = document.getElementById('input-temp-email-custom-auth');
  79. const rowTempEmailReceiveMailbox = document.getElementById('row-temp-email-receive-mailbox');
  80. const inputTempEmailReceiveMailbox = document.getElementById('input-temp-email-receive-mailbox');
  81. const rowTempEmailDomain = document.getElementById('row-temp-email-domain');
  82. const selectTempEmailDomain = document.getElementById('select-temp-email-domain');
  83. const inputTempEmailDomain = document.getElementById('input-temp-email-domain');
  84. const btnTempEmailDomainMode = document.getElementById('btn-temp-email-domain-mode');
  85. const hotmailSection = document.getElementById('hotmail-section');
  86. const luckmailSection = document.getElementById('luckmail-section');
  87. const icloudSection = document.getElementById('icloud-section');
  88. const icloudSummary = document.getElementById('icloud-summary');
  89. const icloudList = document.getElementById('icloud-list');
  90. const icloudLoginHelp = document.getElementById('icloud-login-help');
  91. const icloudLoginHelpTitle = document.getElementById('icloud-login-help-title');
  92. const icloudLoginHelpText = document.getElementById('icloud-login-help-text');
  93. const btnIcloudLoginDone = document.getElementById('btn-icloud-login-done');
  94. const btnIcloudRefresh = document.getElementById('btn-icloud-refresh');
  95. const btnIcloudDeleteUsed = document.getElementById('btn-icloud-delete-used');
  96. const selectIcloudHostPreference = document.getElementById('select-icloud-host-preference');
  97. const checkboxAutoDeleteIcloud = document.getElementById('checkbox-auto-delete-icloud');
  98. const inputIcloudSearch = document.getElementById('input-icloud-search');
  99. const selectIcloudFilter = document.getElementById('select-icloud-filter');
  100. const checkboxIcloudSelectAll = document.getElementById('checkbox-icloud-select-all');
  101. const icloudSelectionSummary = document.getElementById('icloud-selection-summary');
  102. const btnIcloudBulkUsed = document.getElementById('btn-icloud-bulk-used');
  103. const btnIcloudBulkUnused = document.getElementById('btn-icloud-bulk-unused');
  104. const btnIcloudBulkPreserve = document.getElementById('btn-icloud-bulk-preserve');
  105. const btnIcloudBulkUnpreserve = document.getElementById('btn-icloud-bulk-unpreserve');
  106. const btnIcloudBulkDelete = document.getElementById('btn-icloud-bulk-delete');
  107. const rowHotmailServiceMode = document.getElementById('row-hotmail-service-mode');
  108. const hotmailServiceModeButtons = Array.from(document.querySelectorAll('[data-hotmail-service-mode]'));
  109. const rowHotmailRemoteBaseUrl = document.getElementById('row-hotmail-remote-base-url');
  110. const inputHotmailRemoteBaseUrl = document.getElementById('input-hotmail-remote-base-url');
  111. const rowHotmailLocalBaseUrl = document.getElementById('row-hotmail-local-base-url');
  112. const inputHotmailLocalBaseUrl = document.getElementById('input-hotmail-local-base-url');
  113. const inputHotmailEmail = document.getElementById('input-hotmail-email');
  114. const inputHotmailClientId = document.getElementById('input-hotmail-client-id');
  115. const inputHotmailPassword = document.getElementById('input-hotmail-password');
  116. const inputHotmailRefreshToken = document.getElementById('input-hotmail-refresh-token');
  117. const inputHotmailImport = document.getElementById('input-hotmail-import');
  118. const btnAddHotmailAccount = document.getElementById('btn-add-hotmail-account');
  119. const btnImportHotmailAccounts = document.getElementById('btn-import-hotmail-accounts');
  120. const btnHotmailUsageGuide = document.getElementById('btn-hotmail-usage-guide');
  121. const btnClearUsedHotmailAccounts = document.getElementById('btn-clear-used-hotmail-accounts');
  122. const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotmail-accounts');
  123. const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list');
  124. const hotmailListShell = document.getElementById('hotmail-list-shell');
  125. const hotmailAccountsList = document.getElementById('hotmail-accounts-list');
  126. const inputLuckmailApiKey = document.getElementById('input-luckmail-api-key');
  127. const inputLuckmailBaseUrl = document.getElementById('input-luckmail-base-url');
  128. const selectLuckmailEmailType = document.getElementById('select-luckmail-email-type');
  129. const inputLuckmailDomain = document.getElementById('input-luckmail-domain');
  130. const btnLuckmailRefresh = document.getElementById('btn-luckmail-refresh');
  131. const btnLuckmailDisableUsed = document.getElementById('btn-luckmail-disable-used');
  132. const luckmailSummary = document.getElementById('luckmail-summary');
  133. const inputLuckmailSearch = document.getElementById('input-luckmail-search');
  134. const selectLuckmailFilter = document.getElementById('select-luckmail-filter');
  135. const checkboxLuckmailSelectAll = document.getElementById('checkbox-luckmail-select-all');
  136. const luckmailSelectionSummary = document.getElementById('luckmail-selection-summary');
  137. const btnLuckmailBulkUsed = document.getElementById('btn-luckmail-bulk-used');
  138. const btnLuckmailBulkUnused = document.getElementById('btn-luckmail-bulk-unused');
  139. const btnLuckmailBulkPreserve = document.getElementById('btn-luckmail-bulk-preserve');
  140. const btnLuckmailBulkUnpreserve = document.getElementById('btn-luckmail-bulk-unpreserve');
  141. const btnLuckmailBulkDisable = document.getElementById('btn-luckmail-bulk-disable');
  142. const btnLuckmailBulkEnable = document.getElementById('btn-luckmail-bulk-enable');
  143. const luckmailList = document.getElementById('luckmail-list');
  144. const rowEmailPrefix = document.getElementById('row-email-prefix');
  145. const labelEmailPrefix = document.getElementById('label-email-prefix');
  146. const inputEmailPrefix = document.getElementById('input-email-prefix');
  147. const rowInbucketHost = document.getElementById('row-inbucket-host');
  148. const inputInbucketHost = document.getElementById('input-inbucket-host');
  149. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  150. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  151. const rowCfDomain = document.getElementById('row-cf-domain');
  152. const selectCfDomain = document.getElementById('select-cf-domain');
  153. const inputCfDomain = document.getElementById('input-cf-domain');
  154. const btnCfDomainMode = document.getElementById('btn-cf-domain-mode');
  155. const inputRunCount = document.getElementById('input-run-count');
  156. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  157. const inputAutoSkipFailuresThreadIntervalMinutes = document.getElementById('input-auto-skip-failures-thread-interval-minutes');
  158. const inputAutoDelayEnabled = document.getElementById('input-auto-delay-enabled');
  159. const inputAutoDelayMinutes = document.getElementById('input-auto-delay-minutes');
  160. const inputAutoStepDelaySeconds = document.getElementById('input-auto-step-delay-seconds');
  161. const autoStartModal = document.getElementById('auto-start-modal');
  162. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  163. const autoStartMessage = document.getElementById('auto-start-message');
  164. const autoStartAlert = document.getElementById('auto-start-alert');
  165. const modalOptionRow = document.getElementById('modal-option-row');
  166. const modalOptionInput = document.getElementById('modal-option-input');
  167. const modalOptionText = document.getElementById('modal-option-text');
  168. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  169. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  170. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  171. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  172. const autoHintText = document.querySelector('.auto-hint');
  173. const STEP_DEFAULT_STATUSES = {
  174. 1: 'pending',
  175. 2: 'pending',
  176. 3: 'pending',
  177. 4: 'pending',
  178. 5: 'pending',
  179. 6: 'pending',
  180. 7: 'pending',
  181. 8: 'pending',
  182. 9: 'pending',
  183. };
  184. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  185. const AUTO_DELAY_MIN_MINUTES = 1;
  186. const AUTO_DELAY_MAX_MINUTES = 1440;
  187. const AUTO_DELAY_DEFAULT_MINUTES = 30;
  188. const AUTO_FALLBACK_THREAD_INTERVAL_MIN_MINUTES = 0;
  189. const AUTO_FALLBACK_THREAD_INTERVAL_MAX_MINUTES = 1440;
  190. const AUTO_FALLBACK_THREAD_INTERVAL_DEFAULT_MINUTES = 0;
  191. const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3;
  192. const AUTO_STEP_DELAY_MIN_SECONDS = 0;
  193. const AUTO_STEP_DELAY_MAX_SECONDS = 600;
  194. const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit';
  195. const DEFAULT_CPA_CALLBACK_MODE = 'step8';
  196. const MAIL_2925_MODE_PROVIDE = 'provide';
  197. const MAIL_2925_MODE_RECEIVE = 'receive';
  198. const DEFAULT_MAIL_2925_MODE = MAIL_2925_MODE_PROVIDE;
  199. const AUTO_SKIP_FAILURES_PROMPT_DISMISSED_STORAGE_KEY = 'multipage-auto-skip-failures-prompt-dismissed';
  200. const AUTO_RUN_FALLBACK_RISK_PROMPT_DISMISSED_STORAGE_KEY = 'multipage-auto-run-fallback-risk-prompt-dismissed';
  201. const AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS = 15;
  202. const AUTO_RUN_FALLBACK_RISK_RECOMMENDED_THREAD_INTERVAL_MINUTES = 5;
  203. const HOTMAIL_SERVICE_MODE_REMOTE = 'remote';
  204. const HOTMAIL_SERVICE_MODE_LOCAL = 'local';
  205. const ICLOUD_PROVIDER = 'icloud';
  206. const GMAIL_PROVIDER = 'gmail';
  207. const LUCKMAIL_PROVIDER = 'luckmail-api';
  208. const DEFAULT_LUCKMAIL_BASE_URL = 'https://mails.luckyous.com';
  209. const DEFAULT_LUCKMAIL_EMAIL_TYPE = 'ms_graph';
  210. const DISPLAY_TIMEZONE = 'Asia/Shanghai';
  211. let latestState = null;
  212. let currentAutoRun = {
  213. autoRunning: false,
  214. phase: 'idle',
  215. currentRun: 0,
  216. totalRuns: 1,
  217. attemptRun: 0,
  218. scheduledAt: null,
  219. countdownAt: null,
  220. countdownTitle: '',
  221. countdownNote: '',
  222. };
  223. let settingsDirty = false;
  224. let settingsSaveInFlight = false;
  225. let settingsAutoSaveTimer = null;
  226. let cloudflareDomainEditMode = false;
  227. let cloudflareTempEmailDomainEditMode = false;
  228. let modalChoiceResolver = null;
  229. let currentModalActions = [];
  230. let modalResultBuilder = null;
  231. let scheduledCountdownTimer = null;
  232. let configMenuOpen = false;
  233. let configActionInFlight = false;
  234. let currentReleaseSnapshot = null;
  235. 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>';
  236. 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>';
  237. 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>';
  238. const parseHotmailImportText = window.HotmailUtils?.parseHotmailImportText;
  239. const normalizeHotmailServiceModeFromUtils = window.HotmailUtils?.normalizeHotmailServiceMode;
  240. const shouldClearHotmailCurrentSelection = window.HotmailUtils?.shouldClearHotmailCurrentSelection;
  241. const upsertHotmailAccountInList = window.HotmailUtils?.upsertHotmailAccountInList;
  242. const filterHotmailAccountsByUsage = window.HotmailUtils?.filterHotmailAccountsByUsage;
  243. const getHotmailBulkActionLabel = window.HotmailUtils?.getHotmailBulkActionLabel;
  244. const getHotmailListToggleLabel = window.HotmailUtils?.getHotmailListToggleLabel;
  245. const normalizeLuckmailTimestampValue = window.LuckMailUtils?.normalizeTimestamp
  246. || ((value) => {
  247. const timestamp = Date.parse(String(value || ''));
  248. return Number.isFinite(timestamp) ? timestamp : 0;
  249. });
  250. const sidepanelUpdateService = window.SidepanelUpdateService;
  251. const DEFAULT_LUCKMAIL_PRESERVE_TAG_NAME = window.LuckMailUtils?.DEFAULT_LUCKMAIL_PRESERVE_TAG_NAME || '保留';
  252. const normalizeIcloudHost = window.IcloudUtils?.normalizeIcloudHost
  253. || ((value) => {
  254. const normalized = String(value || '').trim().toLowerCase();
  255. return normalized === 'icloud.com' || normalized === 'icloud.com.cn' ? normalized : '';
  256. });
  257. const getIcloudLoginUrlForHost = window.IcloudUtils?.getIcloudLoginUrlForHost
  258. || ((host) => host === 'icloud.com.cn' ? 'https://www.icloud.com.cn/' : (host === 'icloud.com' ? 'https://www.icloud.com/' : ''));
  259. btnAutoCancelSchedule?.remove();
  260. const MAIL_PROVIDER_LOGIN_CONFIGS = {
  261. [ICLOUD_PROVIDER]: {
  262. label: 'iCloud 邮箱',
  263. buttonLabel: '登录',
  264. },
  265. [GMAIL_PROVIDER]: {
  266. label: 'Gmail 邮箱',
  267. url: 'https://mail.google.com/mail/u/0/#inbox',
  268. buttonLabel: '登录',
  269. },
  270. '163': {
  271. label: '163 邮箱',
  272. url: 'https://mail.163.com/',
  273. buttonLabel: '登录',
  274. },
  275. '163-vip': {
  276. label: '163 VIP 邮箱',
  277. url: 'https://webmail.vip.163.com/',
  278. buttonLabel: '登录',
  279. },
  280. qq: {
  281. label: 'QQ 邮箱',
  282. url: 'https://wx.mail.qq.com/',
  283. buttonLabel: '登录',
  284. },
  285. 'cloudflare-temp-email': {
  286. label: 'Cloudflare Temp Email GitHub',
  287. url: 'https://github.com/dreamhunter2333/cloudflare_temp_email',
  288. buttonLabel: 'GitHub',
  289. },
  290. '2925': {
  291. label: '2925 邮箱',
  292. url: 'https://2925.com/#/mailList',
  293. },
  294. };
  295. // ============================================================
  296. // Toast Notifications
  297. // ============================================================
  298. const toastContainer = document.getElementById('toast-container');
  299. const TOAST_ICONS = {
  300. 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>',
  301. 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>',
  302. 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>',
  303. 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>',
  304. };
  305. const LOG_LEVEL_LABELS = {
  306. info: '信息',
  307. ok: '成功',
  308. warn: '警告',
  309. error: '错误',
  310. };
  311. function usesGeneratedAliasMailProvider(provider, mail2925Mode = getSelectedMail2925Mode()) {
  312. const normalizedProvider = String(provider || '').trim().toLowerCase();
  313. if (normalizedProvider === GMAIL_PROVIDER) {
  314. return true;
  315. }
  316. return normalizedProvider === '2925'
  317. && normalizeMail2925Mode(mail2925Mode) === MAIL_2925_MODE_PROVIDE;
  318. }
  319. function parseGmailBaseEmail(rawValue = '') {
  320. const value = String(rawValue || '').trim().toLowerCase();
  321. const match = value.match(/^([^@\s+]+)@((?:gmail|googlemail)\.com)$/i);
  322. if (!match) return null;
  323. return {
  324. localPart: match[1],
  325. domain: match[2].toLowerCase(),
  326. };
  327. }
  328. function isManagedGmailAlias(value, baseEmail) {
  329. const parsedBase = parseGmailBaseEmail(baseEmail);
  330. if (!parsedBase) return false;
  331. const match = String(value || '').trim().toLowerCase().match(/^([^@\s+]+)(?:\+[^@\s]+)?@((?:gmail|googlemail)\.com)$/i);
  332. if (!match) return false;
  333. return match[1] === parsedBase.localPart && match[2] === parsedBase.domain;
  334. }
  335. function showToast(message, type = 'error', duration = 4000) {
  336. const toast = document.createElement('div');
  337. toast.className = `toast toast-${type}`;
  338. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  339. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  340. toastContainer.appendChild(toast);
  341. if (duration > 0) {
  342. setTimeout(() => dismissToast(toast), duration);
  343. }
  344. }
  345. function dismissToast(toast) {
  346. if (!toast.parentNode) return;
  347. toast.classList.add('toast-exit');
  348. toast.addEventListener('animationend', () => toast.remove());
  349. }
  350. function resetActionModalOption() {
  351. if (!modalOptionRow || !modalOptionInput || !modalOptionText) {
  352. return;
  353. }
  354. modalOptionRow.hidden = true;
  355. modalOptionInput.checked = false;
  356. modalOptionInput.disabled = false;
  357. modalOptionText.textContent = '不再提示';
  358. }
  359. function resetActionModalAlert() {
  360. if (!autoStartAlert) {
  361. return;
  362. }
  363. autoStartAlert.hidden = true;
  364. autoStartAlert.textContent = '';
  365. autoStartAlert.className = 'modal-alert';
  366. }
  367. function resetActionModalButtons() {
  368. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  369. buttons.forEach((button) => {
  370. if (!button) return;
  371. button.hidden = true;
  372. button.disabled = false;
  373. button.onclick = null;
  374. });
  375. currentModalActions = [];
  376. }
  377. function configureActionModalButton(button, action) {
  378. if (!button) return;
  379. if (!action) {
  380. button.hidden = true;
  381. button.onclick = null;
  382. return;
  383. }
  384. button.hidden = false;
  385. button.disabled = false;
  386. button.textContent = action.label;
  387. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  388. button.onclick = () => resolveModalChoice(action.id);
  389. }
  390. function configureActionModalOption(option) {
  391. if (!modalOptionRow || !modalOptionInput || !modalOptionText) {
  392. return;
  393. }
  394. if (!option) {
  395. resetActionModalOption();
  396. return;
  397. }
  398. modalOptionRow.hidden = false;
  399. modalOptionInput.checked = Boolean(option.checked);
  400. modalOptionInput.disabled = Boolean(option.disabled);
  401. modalOptionText.textContent = option.label || '不再提示';
  402. }
  403. function configureActionModalAlert(alert) {
  404. if (!autoStartAlert) {
  405. return;
  406. }
  407. if (!alert?.text) {
  408. resetActionModalAlert();
  409. return;
  410. }
  411. autoStartAlert.hidden = false;
  412. autoStartAlert.textContent = alert.text;
  413. autoStartAlert.className = `modal-alert${alert.tone === 'danger' ? ' is-danger' : ''}`;
  414. }
  415. function resolveModalChoice(choice) {
  416. const optionChecked = Boolean(modalOptionInput?.checked);
  417. const result = typeof modalResultBuilder === 'function'
  418. ? modalResultBuilder(choice, { optionChecked })
  419. : choice;
  420. if (modalChoiceResolver) {
  421. modalChoiceResolver(result);
  422. modalChoiceResolver = null;
  423. }
  424. modalResultBuilder = null;
  425. resetActionModalButtons();
  426. resetActionModalAlert();
  427. resetActionModalOption();
  428. if (autoStartModal) {
  429. autoStartModal.hidden = true;
  430. }
  431. }
  432. function openActionModal({ title, message, actions, option, alert, buildResult }) {
  433. if (!autoStartModal) {
  434. return Promise.resolve(null);
  435. }
  436. if (modalChoiceResolver) {
  437. resolveModalChoice(null);
  438. }
  439. resetActionModalButtons();
  440. autoStartTitle.textContent = title;
  441. autoStartMessage.textContent = message;
  442. currentModalActions = actions || [];
  443. modalResultBuilder = typeof buildResult === 'function' ? buildResult : null;
  444. const buttonSlots = currentModalActions.length <= 2
  445. ? [btnAutoStartCancel, btnAutoStartContinue]
  446. : [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  447. buttonSlots.forEach((button, index) => {
  448. configureActionModalButton(button, currentModalActions[index]);
  449. });
  450. configureActionModalAlert(alert);
  451. configureActionModalOption(option);
  452. autoStartModal.hidden = false;
  453. return new Promise((resolve) => {
  454. modalChoiceResolver = resolve;
  455. });
  456. }
  457. function openAutoStartChoiceDialog(startStep, options = {}) {
  458. const runningStep = Number.isInteger(options.runningStep) ? options.runningStep : null;
  459. const continueMessage = runningStep
  460. ? `继续当前会先等待步骤 ${runningStep} 完成,再按最新进度自动执行。`
  461. : `继续当前会从步骤 ${startStep} 开始自动执行。`;
  462. return openActionModal({
  463. title: '启动自动',
  464. message: `检测到当前已有流程进度。${continueMessage}重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  465. actions: [
  466. { id: null, label: '取消', variant: 'btn-ghost' },
  467. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  468. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  469. ],
  470. });
  471. }
  472. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary', alert = null }) {
  473. const choice = await openActionModal({
  474. title,
  475. message,
  476. alert,
  477. actions: [
  478. { id: null, label: '取消', variant: 'btn-ghost' },
  479. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  480. ],
  481. });
  482. return choice === 'confirm';
  483. }
  484. async function openConfirmModalWithOption({
  485. title,
  486. message,
  487. confirmLabel = '确认',
  488. confirmVariant = 'btn-primary',
  489. alert = null,
  490. optionLabel = '不再提示',
  491. optionChecked = false,
  492. optionDisabled = false,
  493. }) {
  494. const result = await openActionModal({
  495. title,
  496. message,
  497. alert,
  498. actions: [
  499. { id: null, label: '取消', variant: 'btn-ghost' },
  500. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  501. ],
  502. option: {
  503. label: optionLabel,
  504. checked: optionChecked,
  505. disabled: optionDisabled,
  506. },
  507. buildResult: (choice, meta) => ({
  508. choice,
  509. optionChecked: Boolean(meta?.optionChecked),
  510. }),
  511. });
  512. return {
  513. confirmed: result?.choice === 'confirm',
  514. optionChecked: Boolean(result?.optionChecked),
  515. };
  516. }
  517. function isPromptDismissed(storageKey) {
  518. return localStorage.getItem(storageKey) === '1';
  519. }
  520. function setPromptDismissed(storageKey, dismissed) {
  521. if (dismissed) {
  522. localStorage.setItem(storageKey, '1');
  523. } else {
  524. localStorage.removeItem(storageKey);
  525. }
  526. }
  527. function isAutoSkipFailuresPromptDismissed() {
  528. return isPromptDismissed(AUTO_SKIP_FAILURES_PROMPT_DISMISSED_STORAGE_KEY);
  529. }
  530. function setAutoSkipFailuresPromptDismissed(dismissed) {
  531. setPromptDismissed(AUTO_SKIP_FAILURES_PROMPT_DISMISSED_STORAGE_KEY, dismissed);
  532. }
  533. function isAutoRunFallbackRiskPromptDismissed() {
  534. return isPromptDismissed(AUTO_RUN_FALLBACK_RISK_PROMPT_DISMISSED_STORAGE_KEY);
  535. }
  536. function setAutoRunFallbackRiskPromptDismissed(dismissed) {
  537. setPromptDismissed(AUTO_RUN_FALLBACK_RISK_PROMPT_DISMISSED_STORAGE_KEY, dismissed);
  538. }
  539. function shouldWarnAutoRunFallbackRisk(totalRuns, autoRunSkipFailures) {
  540. return totalRuns >= AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS;
  541. }
  542. async function openAutoSkipFailuresConfirmModal() {
  543. const result = await openConfirmModalWithOption({
  544. title: '自动重试说明',
  545. message: `开启后,自动模式在某一轮失败时,会先在当前轮自动重试;单轮最多重试 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次,仍失败则放弃当前轮并继续下一轮。线程间隔只在开启自动重试且总轮数大于 1 时生效。`,
  546. confirmLabel: '确认开启',
  547. });
  548. return {
  549. confirmed: result.confirmed,
  550. dismissPrompt: result.optionChecked,
  551. };
  552. }
  553. async function openAutoRunFallbackRiskConfirmModal(totalRuns, fallbackThreadIntervalMinutes) {
  554. const intervalLabel = Number.isFinite(fallbackThreadIntervalMinutes)
  555. ? `${fallbackThreadIntervalMinutes} 分钟`
  556. : '未设置';
  557. const result = await openConfirmModalWithOption({
  558. title: '自动运行风险提醒',
  559. message: `当前设置为 ${totalRuns} 轮自动化,已开启自动重试,线程间隔为 ${intervalLabel}。轮数过多时,可能会因为 IP 短时间注册过多而集中失败。建议控制在 ${AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS} 轮以下,并将线程间隔设置在 ${AUTO_RUN_FALLBACK_RISK_RECOMMENDED_THREAD_INTERVAL_MINUTES} 分钟以上。是否继续?`,
  560. confirmLabel: '继续',
  561. });
  562. return {
  563. confirmed: result.confirmed,
  564. dismissPrompt: result.optionChecked,
  565. };
  566. }
  567. function updateConfigMenuControls() {
  568. const disabled = configActionInFlight || settingsSaveInFlight;
  569. const importLocked = disabled
  570. || currentAutoRun.autoRunning
  571. || Object.values(getStepStatuses()).some((status) => status === 'running');
  572. if (btnConfigMenu) {
  573. btnConfigMenu.disabled = disabled;
  574. btnConfigMenu.setAttribute('aria-expanded', String(configMenuOpen));
  575. }
  576. if (configMenu) {
  577. configMenu.hidden = !configMenuOpen;
  578. }
  579. if (btnExportSettings) {
  580. btnExportSettings.disabled = disabled;
  581. }
  582. if (btnImportSettings) {
  583. btnImportSettings.disabled = importLocked;
  584. }
  585. }
  586. function closeConfigMenu() {
  587. configMenuOpen = false;
  588. updateConfigMenuControls();
  589. }
  590. function openConfigMenu() {
  591. configMenuOpen = true;
  592. updateConfigMenuControls();
  593. }
  594. function toggleConfigMenu() {
  595. configMenuOpen ? closeConfigMenu() : openConfigMenu();
  596. }
  597. async function waitForSettingsSaveIdle() {
  598. while (settingsSaveInFlight) {
  599. await new Promise((resolve) => setTimeout(resolve, 50));
  600. }
  601. }
  602. async function flushPendingSettingsBeforeExport() {
  603. clearTimeout(settingsAutoSaveTimer);
  604. await waitForSettingsSaveIdle();
  605. if (settingsDirty) {
  606. await saveSettings({ silent: true });
  607. }
  608. }
  609. async function settlePendingSettingsBeforeImport() {
  610. clearTimeout(settingsAutoSaveTimer);
  611. await waitForSettingsSaveIdle();
  612. }
  613. function downloadTextFile(content, fileName, mimeType = 'application/json;charset=utf-8') {
  614. const blob = new Blob([content], { type: mimeType });
  615. const objectUrl = URL.createObjectURL(blob);
  616. const anchor = document.createElement('a');
  617. anchor.href = objectUrl;
  618. anchor.download = fileName;
  619. document.body.appendChild(anchor);
  620. anchor.click();
  621. anchor.remove();
  622. setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
  623. }
  624. function isDoneStatus(status) {
  625. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  626. }
  627. function getStepStatuses(state = latestState) {
  628. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  629. }
  630. function getFirstUnfinishedStep(state = latestState) {
  631. const statuses = getStepStatuses(state);
  632. for (let step = 1; step <= 9; step++) {
  633. if (!isDoneStatus(statuses[step])) {
  634. return step;
  635. }
  636. }
  637. return null;
  638. }
  639. function getRunningSteps(state = latestState) {
  640. const statuses = getStepStatuses(state);
  641. return Object.entries(statuses)
  642. .filter(([, status]) => status === 'running')
  643. .map(([step]) => Number(step))
  644. .sort((a, b) => a - b);
  645. }
  646. function hasSavedProgress(state = latestState) {
  647. const statuses = getStepStatuses(state);
  648. return Object.values(statuses).some((status) => status !== 'pending');
  649. }
  650. function shouldOfferAutoModeChoice(state = latestState) {
  651. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  652. }
  653. function syncLatestState(nextState) {
  654. const mergedStepStatuses = nextState?.stepStatuses
  655. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  656. : getStepStatuses(latestState);
  657. latestState = {
  658. ...(latestState || {}),
  659. ...(nextState || {}),
  660. stepStatuses: mergedStepStatuses,
  661. };
  662. }
  663. function hasOwnStateValue(source, key) {
  664. return Object.prototype.hasOwnProperty.call(source, key);
  665. }
  666. function readAutoRunStateValue(source, keys, fallback) {
  667. for (const key of keys) {
  668. if (hasOwnStateValue(source, key)) {
  669. return source[key];
  670. }
  671. }
  672. return fallback;
  673. }
  674. function syncAutoRunState(source = {}) {
  675. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  676. const autoRunning = source.autoRunning !== undefined
  677. ? Boolean(source.autoRunning)
  678. : (source.autoRunPhase !== undefined || source.phase !== undefined
  679. ? ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying', 'waiting_interval'].includes(phase)
  680. : currentAutoRun.autoRunning);
  681. currentAutoRun = {
  682. autoRunning,
  683. phase,
  684. currentRun: readAutoRunStateValue(source, ['autoRunCurrentRun', 'currentRun'], currentAutoRun.currentRun),
  685. totalRuns: readAutoRunStateValue(source, ['autoRunTotalRuns', 'totalRuns'], currentAutoRun.totalRuns),
  686. attemptRun: readAutoRunStateValue(source, ['autoRunAttemptRun', 'attemptRun'], currentAutoRun.attemptRun),
  687. scheduledAt: readAutoRunStateValue(source, ['scheduledAutoRunAt', 'scheduledAt'], currentAutoRun.scheduledAt),
  688. countdownAt: readAutoRunStateValue(source, ['autoRunCountdownAt', 'countdownAt'], currentAutoRun.countdownAt),
  689. countdownTitle: readAutoRunStateValue(source, ['autoRunCountdownTitle', 'countdownTitle'], currentAutoRun.countdownTitle),
  690. countdownNote: readAutoRunStateValue(source, ['autoRunCountdownNote', 'countdownNote'], currentAutoRun.countdownNote),
  691. };
  692. }
  693. function isAutoRunLockedPhase() {
  694. return currentAutoRun.phase === 'running'
  695. || currentAutoRun.phase === 'waiting_step'
  696. || currentAutoRun.phase === 'retrying'
  697. || currentAutoRun.phase === 'waiting_interval';
  698. }
  699. function isAutoRunPausedPhase() {
  700. return currentAutoRun.phase === 'waiting_email';
  701. }
  702. function isAutoRunWaitingStepPhase() {
  703. return currentAutoRun.phase === 'waiting_step';
  704. }
  705. function isAutoRunScheduledPhase() {
  706. return currentAutoRun.phase === 'scheduled';
  707. }
  708. function getAutoRunLabel(payload = currentAutoRun) {
  709. if ((payload.phase ?? currentAutoRun.phase) === 'scheduled') {
  710. return (payload.totalRuns || 1) > 1 ? ` (${payload.totalRuns}轮)` : '';
  711. }
  712. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  713. if ((payload.totalRuns || 1) > 1) {
  714. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  715. }
  716. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  717. }
  718. function normalizeAutoDelayMinutes(value) {
  719. const numeric = Number(value);
  720. if (!Number.isFinite(numeric)) {
  721. return AUTO_DELAY_DEFAULT_MINUTES;
  722. }
  723. return Math.min(AUTO_DELAY_MAX_MINUTES, Math.max(AUTO_DELAY_MIN_MINUTES, Math.floor(numeric)));
  724. }
  725. function normalizeAutoRunThreadIntervalMinutes(value) {
  726. const rawValue = String(value ?? '').trim();
  727. if (!rawValue) {
  728. return AUTO_FALLBACK_THREAD_INTERVAL_DEFAULT_MINUTES;
  729. }
  730. const numeric = Number(rawValue);
  731. if (!Number.isFinite(numeric)) {
  732. return AUTO_FALLBACK_THREAD_INTERVAL_DEFAULT_MINUTES;
  733. }
  734. return Math.min(
  735. AUTO_FALLBACK_THREAD_INTERVAL_MAX_MINUTES,
  736. Math.max(AUTO_FALLBACK_THREAD_INTERVAL_MIN_MINUTES, Math.floor(numeric))
  737. );
  738. }
  739. function normalizeAutoStepDelaySeconds(value) {
  740. const rawValue = String(value ?? '').trim();
  741. if (!rawValue) {
  742. return null;
  743. }
  744. const numeric = Number(rawValue);
  745. if (!Number.isFinite(numeric)) {
  746. return null;
  747. }
  748. return Math.min(AUTO_STEP_DELAY_MAX_SECONDS, Math.max(AUTO_STEP_DELAY_MIN_SECONDS, Math.floor(numeric)));
  749. }
  750. function formatAutoStepDelayInputValue(value) {
  751. const normalized = normalizeAutoStepDelaySeconds(value);
  752. return normalized === null ? '' : String(normalized);
  753. }
  754. function getRunCountValue() {
  755. return Math.min(50, Math.max(1, parseInt(inputRunCount.value, 10) || 1));
  756. }
  757. function updateFallbackThreadIntervalInputState() {
  758. if (!inputAutoSkipFailuresThreadIntervalMinutes) {
  759. return;
  760. }
  761. inputAutoSkipFailuresThreadIntervalMinutes.disabled = Boolean(inputAutoSkipFailures.disabled);
  762. }
  763. function updateAutoDelayInputState() {
  764. const scheduled = isAutoRunScheduledPhase();
  765. inputAutoDelayEnabled.disabled = scheduled;
  766. inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked;
  767. }
  768. function formatCountdown(remainingMs) {
  769. const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
  770. const hours = Math.floor(totalSeconds / 3600);
  771. const minutes = Math.floor((totalSeconds % 3600) / 60);
  772. const seconds = totalSeconds % 60;
  773. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  774. }
  775. function formatScheduleTime(timestamp) {
  776. return new Date(timestamp).toLocaleString('zh-CN', {
  777. hour12: false,
  778. timeZone: DISPLAY_TIMEZONE,
  779. month: '2-digit',
  780. day: '2-digit',
  781. hour: '2-digit',
  782. minute: '2-digit',
  783. second: '2-digit',
  784. });
  785. }
  786. function stopScheduledCountdownTicker() {
  787. clearInterval(scheduledCountdownTimer);
  788. scheduledCountdownTimer = null;
  789. }
  790. function getActiveAutoRunCountdown() {
  791. if (isAutoRunScheduledPhase() && Number.isFinite(currentAutoRun.scheduledAt)) {
  792. return {
  793. at: currentAutoRun.scheduledAt,
  794. title: '已计划自动运行',
  795. note: `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始`,
  796. tone: 'scheduled',
  797. };
  798. }
  799. if (!Number.isFinite(currentAutoRun.countdownAt)) {
  800. return null;
  801. }
  802. return {
  803. at: currentAutoRun.countdownAt,
  804. title: currentAutoRun.countdownTitle || '等待中',
  805. note: currentAutoRun.countdownNote || '',
  806. tone: 'running',
  807. };
  808. }
  809. function renderScheduledAutoRunInfo() {
  810. if (!autoScheduleBar) {
  811. return;
  812. }
  813. const countdown = getActiveAutoRunCountdown();
  814. if (!countdown) {
  815. autoScheduleBar.style.display = 'none';
  816. return;
  817. }
  818. const remainingMs = countdown.at - Date.now();
  819. autoScheduleBar.style.display = 'flex';
  820. if (btnAutoRunNow) {
  821. btnAutoRunNow.hidden = false;
  822. btnAutoRunNow.textContent = currentAutoRun.phase === 'waiting_interval' ? '立即继续' : '立即开始';
  823. }
  824. if (btnAutoCancelSchedule) {
  825. btnAutoCancelSchedule.hidden = true;
  826. }
  827. autoScheduleTitle.textContent = countdown.title;
  828. autoScheduleMeta.textContent = remainingMs > 0
  829. ? `${countdown.note ? `${countdown.note},` : ''}剩余 ${formatCountdown(remainingMs)}`
  830. : '倒计时即将结束,正在准备继续...';
  831. return;
  832. }
  833. function syncScheduledCountdownTicker() {
  834. renderScheduledAutoRunInfo();
  835. if (getActiveAutoRunCountdown()) {
  836. if (scheduledCountdownTimer) {
  837. return;
  838. }
  839. scheduledCountdownTimer = setInterval(() => {
  840. renderScheduledAutoRunInfo();
  841. updateStatusDisplay(latestState);
  842. }, 1000);
  843. return;
  844. }
  845. stopScheduledCountdownTicker();
  846. return;
  847. }
  848. function setDefaultAutoRunButton() {
  849. btnAutoRun.disabled = false;
  850. inputRunCount.disabled = false;
  851. 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> 自动';
  852. }
  853. function normalizeCloudflareDomainValue(value = '') {
  854. let normalized = String(value || '').trim().toLowerCase();
  855. if (!normalized) return '';
  856. normalized = normalized.replace(/^@+/, '');
  857. normalized = normalized.replace(/^https?:\/\//, '');
  858. normalized = normalized.replace(/\/.*$/, '');
  859. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) {
  860. return '';
  861. }
  862. return normalized;
  863. }
  864. function normalizeCloudflareDomains(values = []) {
  865. const seen = new Set();
  866. const domains = [];
  867. for (const value of Array.isArray(values) ? values : []) {
  868. const normalized = normalizeCloudflareDomainValue(value);
  869. if (!normalized || seen.has(normalized)) continue;
  870. seen.add(normalized);
  871. domains.push(normalized);
  872. }
  873. return domains;
  874. }
  875. function normalizeCloudflareTempEmailBaseUrlValue(value = '') {
  876. const raw = String(value || '').trim();
  877. if (!raw) return '';
  878. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(raw) ? raw : `https://${raw}`;
  879. try {
  880. const parsed = new URL(candidate);
  881. parsed.hash = '';
  882. parsed.search = '';
  883. const pathname = parsed.pathname === '/' ? '' : parsed.pathname.replace(/\/+$/, '');
  884. return `${parsed.origin}${pathname}`;
  885. } catch {
  886. return '';
  887. }
  888. }
  889. function normalizeCloudflareTempEmailReceiveMailboxValue(value = '') {
  890. const normalized = String(value || '').trim().toLowerCase();
  891. if (!normalized) return '';
  892. return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalized) ? normalized : '';
  893. }
  894. function normalizeCloudflareTempEmailDomainValue(value = '') {
  895. return normalizeCloudflareDomainValue(value);
  896. }
  897. function normalizeCloudflareTempEmailDomains(values = []) {
  898. const seen = new Set();
  899. const domains = [];
  900. for (const value of Array.isArray(values) ? values : []) {
  901. const normalized = normalizeCloudflareTempEmailDomainValue(value);
  902. if (!normalized || seen.has(normalized)) continue;
  903. seen.add(normalized);
  904. domains.push(normalized);
  905. }
  906. return domains;
  907. }
  908. function getCloudflareDomainsFromState() {
  909. const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []);
  910. const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || '');
  911. if (activeDomain && !domains.includes(activeDomain)) {
  912. domains.unshift(activeDomain);
  913. }
  914. return { domains, activeDomain: activeDomain || domains[0] || '' };
  915. }
  916. function getCloudflareTempEmailDomainsFromState() {
  917. const domains = normalizeCloudflareTempEmailDomains(latestState?.cloudflareTempEmailDomains || []);
  918. const activeDomain = normalizeCloudflareTempEmailDomainValue(latestState?.cloudflareTempEmailDomain || '');
  919. if (activeDomain && !domains.includes(activeDomain)) {
  920. domains.unshift(activeDomain);
  921. }
  922. return { domains, activeDomain: activeDomain || domains[0] || '' };
  923. }
  924. function renderCloudflareDomainOptions(preferredDomain = '') {
  925. const preferred = normalizeCloudflareDomainValue(preferredDomain);
  926. const { domains, activeDomain } = getCloudflareDomainsFromState();
  927. const selected = preferred || activeDomain;
  928. selectCfDomain.innerHTML = '';
  929. if (domains.length === 0) {
  930. const option = document.createElement('option');
  931. option.value = '';
  932. option.textContent = '请先添加域名';
  933. selectCfDomain.appendChild(option);
  934. selectCfDomain.disabled = true;
  935. selectCfDomain.value = '';
  936. return;
  937. }
  938. for (const domain of domains) {
  939. const option = document.createElement('option');
  940. option.value = domain;
  941. option.textContent = domain;
  942. selectCfDomain.appendChild(option);
  943. }
  944. selectCfDomain.disabled = false;
  945. selectCfDomain.value = domains.includes(selected) ? selected : domains[0];
  946. }
  947. function renderCloudflareTempEmailDomainOptions(preferredDomain = '') {
  948. const preferred = normalizeCloudflareTempEmailDomainValue(preferredDomain);
  949. const { domains, activeDomain } = getCloudflareTempEmailDomainsFromState();
  950. const selected = preferred || activeDomain;
  951. selectTempEmailDomain.innerHTML = '';
  952. if (domains.length === 0) {
  953. const option = document.createElement('option');
  954. option.value = '';
  955. option.textContent = '请先添加域名';
  956. selectTempEmailDomain.appendChild(option);
  957. selectTempEmailDomain.disabled = true;
  958. selectTempEmailDomain.value = '';
  959. return;
  960. }
  961. for (const domain of domains) {
  962. const option = document.createElement('option');
  963. option.value = domain;
  964. option.textContent = domain;
  965. selectTempEmailDomain.appendChild(option);
  966. }
  967. selectTempEmailDomain.disabled = false;
  968. selectTempEmailDomain.value = domains.includes(selected) ? selected : domains[0];
  969. }
  970. function setCloudflareDomainEditMode(editing, options = {}) {
  971. const { clearInput = false } = options;
  972. cloudflareDomainEditMode = Boolean(editing);
  973. selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : '';
  974. inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none';
  975. btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加';
  976. if (cloudflareDomainEditMode) {
  977. if (clearInput) {
  978. inputCfDomain.value = '';
  979. }
  980. inputCfDomain.focus();
  981. } else if (clearInput) {
  982. inputCfDomain.value = '';
  983. }
  984. }
  985. function setCloudflareTempEmailDomainEditMode(editing, options = {}) {
  986. const { clearInput = false } = options;
  987. cloudflareTempEmailDomainEditMode = Boolean(editing);
  988. selectTempEmailDomain.style.display = cloudflareTempEmailDomainEditMode ? 'none' : '';
  989. inputTempEmailDomain.style.display = cloudflareTempEmailDomainEditMode ? '' : 'none';
  990. btnTempEmailDomainMode.textContent = cloudflareTempEmailDomainEditMode ? '保存' : '添加';
  991. if (cloudflareTempEmailDomainEditMode) {
  992. if (clearInput) {
  993. inputTempEmailDomain.value = '';
  994. }
  995. inputTempEmailDomain.focus();
  996. } else if (clearInput) {
  997. inputTempEmailDomain.value = '';
  998. }
  999. }
  1000. function collectSettingsPayload() {
  1001. const { domains, activeDomain } = getCloudflareDomainsFromState();
  1002. const selectedCloudflareDomain = normalizeCloudflareDomainValue(
  1003. !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain
  1004. ) || activeDomain;
  1005. const { domains: tempEmailDomains, activeDomain: tempEmailActiveDomain } = getCloudflareTempEmailDomainsFromState();
  1006. const selectedCloudflareTempEmailDomain = normalizeCloudflareTempEmailDomainValue(
  1007. !cloudflareTempEmailDomainEditMode ? selectTempEmailDomain.value : tempEmailActiveDomain
  1008. ) || tempEmailActiveDomain;
  1009. return {
  1010. panelMode: selectPanelMode.value,
  1011. vpsUrl: inputVpsUrl.value.trim(),
  1012. vpsPassword: inputVpsPassword.value,
  1013. localCpaStep9Mode: getSelectedLocalCpaStep9Mode(),
  1014. cpaCallbackMode: getSelectedCpaCallbackMode(),
  1015. sub2apiUrl: inputSub2ApiUrl.value.trim(),
  1016. sub2apiEmail: inputSub2ApiEmail.value.trim(),
  1017. sub2apiPassword: inputSub2ApiPassword.value,
  1018. sub2apiGroupName: inputSub2ApiGroup.value.trim(),
  1019. customPassword: inputPassword.value,
  1020. mailProvider: selectMailProvider.value,
  1021. mail2925Mode: getSelectedMail2925Mode(),
  1022. emailGenerator: selectEmailGenerator.value,
  1023. autoDeleteUsedIcloudAlias: checkboxAutoDeleteIcloud?.checked,
  1024. icloudHostPreference: selectIcloudHostPreference?.value || 'auto',
  1025. emailPrefix: inputEmailPrefix.value.trim(),
  1026. inbucketHost: inputInbucketHost.value.trim(),
  1027. inbucketMailbox: inputInbucketMailbox.value.trim(),
  1028. hotmailServiceMode: getSelectedHotmailServiceMode(),
  1029. hotmailRemoteBaseUrl: inputHotmailRemoteBaseUrl.value.trim(),
  1030. hotmailLocalBaseUrl: inputHotmailLocalBaseUrl.value.trim(),
  1031. luckmailApiKey: inputLuckmailApiKey.value,
  1032. luckmailBaseUrl: normalizeLuckmailBaseUrl(inputLuckmailBaseUrl.value),
  1033. luckmailEmailType: normalizeLuckmailEmailType(selectLuckmailEmailType.value),
  1034. luckmailDomain: inputLuckmailDomain.value.trim(),
  1035. cloudflareDomain: selectedCloudflareDomain,
  1036. cloudflareDomains: domains,
  1037. cloudflareTempEmailBaseUrl: normalizeCloudflareTempEmailBaseUrlValue(inputTempEmailBaseUrl.value),
  1038. cloudflareTempEmailAdminAuth: inputTempEmailAdminAuth.value,
  1039. cloudflareTempEmailCustomAuth: inputTempEmailCustomAuth.value,
  1040. cloudflareTempEmailReceiveMailbox: normalizeCloudflareTempEmailReceiveMailboxValue(inputTempEmailReceiveMailbox.value),
  1041. cloudflareTempEmailDomain: selectedCloudflareTempEmailDomain,
  1042. cloudflareTempEmailDomains: tempEmailDomains,
  1043. autoRunSkipFailures: inputAutoSkipFailures.checked,
  1044. autoRunFallbackThreadIntervalMinutes: normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value),
  1045. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  1046. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  1047. autoStepDelaySeconds: normalizeAutoStepDelaySeconds(inputAutoStepDelaySeconds.value),
  1048. };
  1049. }
  1050. function normalizeLocalCpaStep9Mode(value = '') {
  1051. return String(value || '').trim().toLowerCase() === 'bypass'
  1052. ? 'bypass'
  1053. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  1054. }
  1055. function normalizeCpaCallbackMode(value = '') {
  1056. return String(value || '').trim().toLowerCase() === 'step6'
  1057. ? 'step6'
  1058. : DEFAULT_CPA_CALLBACK_MODE;
  1059. }
  1060. function normalizeMail2925Mode(value = '') {
  1061. return String(value || '').trim().toLowerCase() === MAIL_2925_MODE_RECEIVE
  1062. ? MAIL_2925_MODE_RECEIVE
  1063. : DEFAULT_MAIL_2925_MODE;
  1064. }
  1065. function normalizeHotmailServiceMode(value = '') {
  1066. if (typeof normalizeHotmailServiceModeFromUtils === 'function') {
  1067. return normalizeHotmailServiceModeFromUtils(value);
  1068. }
  1069. return String(value || '').trim().toLowerCase() === HOTMAIL_SERVICE_MODE_REMOTE
  1070. ? HOTMAIL_SERVICE_MODE_REMOTE
  1071. : HOTMAIL_SERVICE_MODE_LOCAL;
  1072. }
  1073. function getSelectedLocalCpaStep9Mode() {
  1074. const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active'));
  1075. return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode);
  1076. }
  1077. function setLocalCpaStep9Mode(mode) {
  1078. const resolvedMode = normalizeLocalCpaStep9Mode(mode);
  1079. localCpaStep9ModeButtons.forEach((button) => {
  1080. const active = button.dataset.localCpaStep9Mode === resolvedMode;
  1081. button.classList.toggle('is-active', active);
  1082. button.setAttribute('aria-pressed', String(active));
  1083. });
  1084. }
  1085. function getSelectedCpaCallbackMode() {
  1086. const activeButton = cpaCallbackModeButtons.find((button) => button.classList.contains('is-active'));
  1087. return normalizeCpaCallbackMode(activeButton?.dataset.cpaCallbackMode);
  1088. }
  1089. function setCpaCallbackMode(mode) {
  1090. const resolvedMode = normalizeCpaCallbackMode(mode);
  1091. cpaCallbackModeButtons.forEach((button) => {
  1092. const active = button.dataset.cpaCallbackMode === resolvedMode;
  1093. button.classList.toggle('is-active', active);
  1094. button.setAttribute('aria-pressed', String(active));
  1095. });
  1096. }
  1097. function getSelectedMail2925Mode() {
  1098. const activeButton = mail2925ModeButtons.find((button) => button.classList.contains('is-active'));
  1099. return normalizeMail2925Mode(activeButton?.dataset.mail2925Mode);
  1100. }
  1101. function setMail2925Mode(mode) {
  1102. const resolvedMode = normalizeMail2925Mode(mode);
  1103. mail2925ModeButtons.forEach((button) => {
  1104. const active = button.dataset.mail2925Mode === resolvedMode;
  1105. button.classList.toggle('is-active', active);
  1106. button.setAttribute('aria-pressed', String(active));
  1107. });
  1108. }
  1109. function getSelectedHotmailServiceMode() {
  1110. const activeButton = hotmailServiceModeButtons.find((button) => button.classList.contains('is-active'));
  1111. return normalizeHotmailServiceMode(activeButton?.dataset.hotmailServiceMode);
  1112. }
  1113. function setHotmailServiceMode(mode) {
  1114. const resolvedMode = normalizeHotmailServiceMode(mode);
  1115. hotmailServiceModeButtons.forEach((button) => {
  1116. const active = button.dataset.hotmailServiceMode === resolvedMode;
  1117. button.disabled = false;
  1118. button.setAttribute('aria-disabled', 'false');
  1119. button.classList.toggle('is-active', active);
  1120. button.setAttribute('aria-pressed', String(active));
  1121. });
  1122. }
  1123. function setSettingsCardLocked(locked) {
  1124. if (!settingsCard) {
  1125. return;
  1126. }
  1127. settingsCard.classList.toggle('is-locked', locked);
  1128. settingsCard.toggleAttribute('inert', locked);
  1129. }
  1130. async function setRuntimeEmailState(email) {
  1131. const normalizedEmail = String(email || '').trim() || null;
  1132. const response = await chrome.runtime.sendMessage({
  1133. type: 'SET_EMAIL_STATE',
  1134. source: 'sidepanel',
  1135. payload: { email: normalizedEmail },
  1136. });
  1137. if (response?.error) {
  1138. throw new Error(response.error);
  1139. }
  1140. return normalizedEmail;
  1141. }
  1142. async function clearRegistrationEmail(options = {}) {
  1143. const { silent = false } = options;
  1144. if (!inputEmail.value.trim() && !latestState?.email) {
  1145. return;
  1146. }
  1147. inputEmail.value = '';
  1148. syncLatestState({ email: null });
  1149. try {
  1150. await setRuntimeEmailState(null);
  1151. } catch (err) {
  1152. if (!silent) {
  1153. showToast(`清空邮箱失败:${err.message}`, 'error');
  1154. }
  1155. throw err;
  1156. }
  1157. }
  1158. function markSettingsDirty(isDirty = true) {
  1159. settingsDirty = isDirty;
  1160. updateSaveButtonState();
  1161. }
  1162. function updateSaveButtonState() {
  1163. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  1164. updateConfigMenuControls();
  1165. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  1166. }
  1167. function scheduleSettingsAutoSave() {
  1168. clearTimeout(settingsAutoSaveTimer);
  1169. settingsAutoSaveTimer = setTimeout(() => {
  1170. saveSettings({ silent: true }).catch(() => { });
  1171. }, 500);
  1172. }
  1173. async function saveSettings(options = {}) {
  1174. const { silent = false } = options;
  1175. clearTimeout(settingsAutoSaveTimer);
  1176. if (!settingsDirty && !settingsSaveInFlight && silent) {
  1177. return;
  1178. }
  1179. const payload = collectSettingsPayload();
  1180. settingsSaveInFlight = true;
  1181. updateSaveButtonState();
  1182. try {
  1183. const response = await chrome.runtime.sendMessage({
  1184. type: 'SAVE_SETTING',
  1185. source: 'sidepanel',
  1186. payload,
  1187. });
  1188. if (response?.error) {
  1189. throw new Error(response.error);
  1190. }
  1191. if (response?.state) {
  1192. applySettingsState(response.state);
  1193. } else {
  1194. syncLatestState(payload);
  1195. markSettingsDirty(false);
  1196. updatePanelModeUI();
  1197. updateMailProviderUI();
  1198. updateButtonStates();
  1199. }
  1200. if (!silent) {
  1201. showToast('配置已保存', 'success', 1800);
  1202. }
  1203. } catch (err) {
  1204. markSettingsDirty(true);
  1205. if (!silent) {
  1206. showToast(`保存失败:${err.message}`, 'error');
  1207. }
  1208. throw err;
  1209. } finally {
  1210. settingsSaveInFlight = false;
  1211. updateSaveButtonState();
  1212. }
  1213. }
  1214. function applyAutoRunStatus(payload = currentAutoRun) {
  1215. syncAutoRunState(payload);
  1216. const runLabel = getAutoRunLabel(currentAutoRun);
  1217. const locked = isAutoRunLockedPhase();
  1218. const paused = isAutoRunPausedPhase();
  1219. const scheduled = isAutoRunScheduledPhase();
  1220. const settingsCardLocked = scheduled || locked;
  1221. setSettingsCardLocked(settingsCardLocked);
  1222. inputRunCount.disabled = currentAutoRun.autoRunning;
  1223. btnAutoRun.disabled = currentAutoRun.autoRunning;
  1224. btnFetchEmail.disabled = locked
  1225. || usesGeneratedAliasMailProvider(selectMailProvider.value)
  1226. || isCustomMailProvider();
  1227. inputEmail.disabled = locked;
  1228. inputAutoSkipFailures.disabled = scheduled;
  1229. if (currentAutoRun.totalRuns > 0) {
  1230. inputRunCount.value = String(currentAutoRun.totalRuns);
  1231. }
  1232. switch (currentAutoRun.phase) {
  1233. case 'scheduled':
  1234. autoContinueBar.style.display = 'none';
  1235. btnAutoRun.innerHTML = `已计划${runLabel}`;
  1236. break;
  1237. case 'waiting_step':
  1238. autoContinueBar.style.display = 'none';
  1239. btnAutoRun.innerHTML = `等待中${runLabel}`;
  1240. break;
  1241. case 'waiting_email':
  1242. autoContinueBar.style.display = 'flex';
  1243. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  1244. break;
  1245. case 'running':
  1246. autoContinueBar.style.display = 'none';
  1247. btnAutoRun.innerHTML = `运行中${runLabel}`;
  1248. break;
  1249. case 'retrying':
  1250. autoContinueBar.style.display = 'none';
  1251. btnAutoRun.innerHTML = `重试中${runLabel}`;
  1252. break;
  1253. case 'waiting_interval':
  1254. autoContinueBar.style.display = 'none';
  1255. btnAutoRun.innerHTML = `等待中${runLabel}`;
  1256. break;
  1257. default:
  1258. autoContinueBar.style.display = 'none';
  1259. setDefaultAutoRunButton();
  1260. inputEmail.disabled = false;
  1261. if (!locked) {
  1262. btnFetchEmail.disabled = usesGeneratedAliasMailProvider(selectMailProvider.value)
  1263. || isCustomMailProvider();
  1264. }
  1265. break;
  1266. }
  1267. updateAutoDelayInputState();
  1268. updateFallbackThreadIntervalInputState();
  1269. syncScheduledCountdownTicker();
  1270. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  1271. updateConfigMenuControls();
  1272. }
  1273. function initializeManualStepActions() {
  1274. document.querySelectorAll('.step-row').forEach((row) => {
  1275. const step = Number(row.dataset.step);
  1276. const statusEl = row.querySelector('.step-status');
  1277. if (!statusEl) return;
  1278. const actions = document.createElement('div');
  1279. actions.className = 'step-actions';
  1280. const manualBtn = document.createElement('button');
  1281. manualBtn.type = 'button';
  1282. manualBtn.className = 'step-manual-btn';
  1283. manualBtn.dataset.step = String(step);
  1284. manualBtn.title = '跳过此步';
  1285. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  1286. 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>';
  1287. manualBtn.addEventListener('click', async (event) => {
  1288. event.stopPropagation();
  1289. try {
  1290. await handleSkipStep(step);
  1291. } catch (err) {
  1292. showToast(err.message, 'error');
  1293. }
  1294. });
  1295. statusEl.parentNode.replaceChild(actions, statusEl);
  1296. actions.appendChild(manualBtn);
  1297. actions.appendChild(statusEl);
  1298. });
  1299. }
  1300. // ============================================================
  1301. // State Restore on load
  1302. // ============================================================
  1303. function applySettingsState(state) {
  1304. syncLatestState(state);
  1305. syncAutoRunState(state);
  1306. inputEmail.value = state?.email || '';
  1307. syncPasswordField(state || {});
  1308. inputVpsUrl.value = state?.vpsUrl || '';
  1309. inputVpsPassword.value = state?.vpsPassword || '';
  1310. setLocalCpaStep9Mode(state?.localCpaStep9Mode);
  1311. setCpaCallbackMode(state?.cpaCallbackMode);
  1312. selectPanelMode.value = state?.panelMode || 'cpa';
  1313. inputSub2ApiUrl.value = state?.sub2apiUrl || '';
  1314. inputSub2ApiEmail.value = state?.sub2apiEmail || '';
  1315. inputSub2ApiPassword.value = state?.sub2apiPassword || '';
  1316. inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
  1317. const restoredMailProvider = isCustomMailProvider(state?.mailProvider)
  1318. || [ICLOUD_PROVIDER, 'hotmail-api', GMAIL_PROVIDER, 'luckmail-api', '163', '163-vip', 'qq', 'inbucket', '2925', 'cloudflare-temp-email'].includes(String(state?.mailProvider || '').trim())
  1319. ? String(state?.mailProvider || '163').trim()
  1320. : (String(state?.emailGenerator || '').trim().toLowerCase() === 'custom'
  1321. || String(state?.emailGenerator || '').trim().toLowerCase() === 'manual'
  1322. ? 'custom'
  1323. : '163');
  1324. selectMailProvider.value = restoredMailProvider;
  1325. setMail2925Mode(state?.mail2925Mode);
  1326. {
  1327. const restoredEmailGenerator = String(state?.emailGenerator || '').trim().toLowerCase();
  1328. if (restoredEmailGenerator === 'icloud') {
  1329. selectEmailGenerator.value = 'icloud';
  1330. } else if (restoredEmailGenerator === 'cloudflare') {
  1331. selectEmailGenerator.value = 'cloudflare';
  1332. } else if (restoredEmailGenerator === 'cloudflare-temp-email') {
  1333. selectEmailGenerator.value = 'cloudflare-temp-email';
  1334. } else {
  1335. selectEmailGenerator.value = 'duck';
  1336. }
  1337. }
  1338. if (selectIcloudHostPreference) {
  1339. selectIcloudHostPreference.value = String(state?.icloudHostPreference || '').trim().toLowerCase() === 'icloud.com'
  1340. ? 'icloud.com'
  1341. : (String(state?.icloudHostPreference || '').trim().toLowerCase() === 'icloud.com.cn' ? 'icloud.com.cn' : 'auto');
  1342. }
  1343. if (checkboxAutoDeleteIcloud) {
  1344. checkboxAutoDeleteIcloud.checked = Boolean(state?.autoDeleteUsedIcloudAlias);
  1345. }
  1346. inputEmailPrefix.value = state?.emailPrefix || '';
  1347. inputInbucketHost.value = state?.inbucketHost || '';
  1348. inputInbucketMailbox.value = state?.inbucketMailbox || '';
  1349. setHotmailServiceMode(state?.hotmailServiceMode);
  1350. inputHotmailRemoteBaseUrl.value = state?.hotmailRemoteBaseUrl || '';
  1351. inputHotmailLocalBaseUrl.value = state?.hotmailLocalBaseUrl || '';
  1352. inputLuckmailApiKey.value = state?.luckmailApiKey || '';
  1353. inputLuckmailBaseUrl.value = normalizeLuckmailBaseUrl(state?.luckmailBaseUrl);
  1354. selectLuckmailEmailType.value = normalizeLuckmailEmailType(state?.luckmailEmailType);
  1355. inputLuckmailDomain.value = state?.luckmailDomain || '';
  1356. inputTempEmailBaseUrl.value = state?.cloudflareTempEmailBaseUrl || '';
  1357. inputTempEmailAdminAuth.value = state?.cloudflareTempEmailAdminAuth || '';
  1358. inputTempEmailCustomAuth.value = state?.cloudflareTempEmailCustomAuth || '';
  1359. inputTempEmailReceiveMailbox.value = state?.cloudflareTempEmailReceiveMailbox || '';
  1360. renderCloudflareDomainOptions(state?.cloudflareDomain || '');
  1361. setCloudflareDomainEditMode(false, { clearInput: true });
  1362. renderCloudflareTempEmailDomainOptions(state?.cloudflareTempEmailDomain || '');
  1363. setCloudflareTempEmailDomainEditMode(false, { clearInput: true });
  1364. inputAutoSkipFailures.checked = Boolean(state?.autoRunSkipFailures);
  1365. inputAutoSkipFailuresThreadIntervalMinutes.value = String(normalizeAutoRunThreadIntervalMinutes(state?.autoRunFallbackThreadIntervalMinutes));
  1366. inputAutoDelayEnabled.checked = Boolean(state?.autoRunDelayEnabled);
  1367. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state?.autoRunDelayMinutes));
  1368. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(state?.autoStepDelaySeconds);
  1369. if (state?.autoRunTotalRuns) {
  1370. inputRunCount.value = String(state.autoRunTotalRuns);
  1371. }
  1372. applyAutoRunStatus(state);
  1373. markSettingsDirty(false);
  1374. updateAutoDelayInputState();
  1375. updateFallbackThreadIntervalInputState();
  1376. updatePanelModeUI();
  1377. updateMailProviderUI();
  1378. if (isLuckmailProvider(state?.mailProvider)) {
  1379. queueLuckmailPurchaseRefresh();
  1380. }
  1381. updateButtonStates();
  1382. }
  1383. async function restoreState() {
  1384. try {
  1385. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  1386. applySettingsState(state);
  1387. if (getSelectedEmailGenerator() === 'icloud' && icloudSection?.style.display !== 'none') {
  1388. refreshIcloudAliases({ silent: true }).catch(() => { });
  1389. }
  1390. if (state.oauthUrl) {
  1391. displayOauthUrl.textContent = state.oauthUrl;
  1392. displayOauthUrl.classList.add('has-value');
  1393. }
  1394. if (state.localhostUrl) {
  1395. displayLocalhostUrl.textContent = state.localhostUrl;
  1396. displayLocalhostUrl.classList.add('has-value');
  1397. }
  1398. if (state.stepStatuses) {
  1399. for (const [step, status] of Object.entries(state.stepStatuses)) {
  1400. updateStepUI(Number(step), status);
  1401. }
  1402. }
  1403. if (state.logs) {
  1404. for (const entry of state.logs) {
  1405. appendLog(entry);
  1406. }
  1407. }
  1408. updateStatusDisplay(latestState);
  1409. updateProgressCounter();
  1410. } catch (err) {
  1411. console.error('Failed to restore state:', err);
  1412. }
  1413. }
  1414. function openExternalUrl(url) {
  1415. const targetUrl = String(url || '').trim();
  1416. if (!targetUrl) {
  1417. return;
  1418. }
  1419. if (chrome?.tabs?.create) {
  1420. chrome.tabs.create({ url: targetUrl, active: true }).catch(() => {
  1421. window.open(targetUrl, '_blank', 'noopener');
  1422. });
  1423. return;
  1424. }
  1425. window.open(targetUrl, '_blank', 'noopener');
  1426. }
  1427. function createUpdateNoteList(notes = []) {
  1428. if (!Array.isArray(notes) || notes.length === 0) {
  1429. const empty = document.createElement('p');
  1430. empty.className = 'update-release-empty';
  1431. empty.textContent = '该版本未提供可解析的更新说明,请查看完整更新日志。';
  1432. return empty;
  1433. }
  1434. const list = document.createElement('ul');
  1435. list.className = 'update-release-notes';
  1436. notes.forEach((note) => {
  1437. const item = document.createElement('li');
  1438. item.textContent = note;
  1439. list.appendChild(item);
  1440. });
  1441. return list;
  1442. }
  1443. function renderUpdateReleaseList(releases = []) {
  1444. if (!updateReleaseList) {
  1445. return;
  1446. }
  1447. updateReleaseList.innerHTML = '';
  1448. releases.forEach((release) => {
  1449. const item = document.createElement('article');
  1450. item.className = 'update-release-item';
  1451. const head = document.createElement('div');
  1452. head.className = 'update-release-head';
  1453. const titleRow = document.createElement('div');
  1454. titleRow.className = 'update-release-title-row';
  1455. const version = document.createElement('span');
  1456. version.className = 'update-release-version';
  1457. version.textContent = `v${release.version}`;
  1458. titleRow.appendChild(version);
  1459. if (release.title) {
  1460. const name = document.createElement('span');
  1461. name.className = 'update-release-name';
  1462. name.textContent = release.title;
  1463. titleRow.appendChild(name);
  1464. }
  1465. head.appendChild(titleRow);
  1466. const publishedAt = sidepanelUpdateService?.formatReleaseDate?.(release.publishedAt) || '';
  1467. if (publishedAt) {
  1468. const date = document.createElement('span');
  1469. date.className = 'update-release-date';
  1470. date.textContent = publishedAt;
  1471. head.appendChild(date);
  1472. }
  1473. item.appendChild(head);
  1474. item.appendChild(createUpdateNoteList(release.notes));
  1475. updateReleaseList.appendChild(item);
  1476. });
  1477. }
  1478. function resetUpdateCard() {
  1479. if (updateSection) {
  1480. updateSection.hidden = true;
  1481. }
  1482. if (updateCardVersion) {
  1483. updateCardVersion.textContent = '';
  1484. }
  1485. if (updateCardSummary) {
  1486. updateCardSummary.textContent = '';
  1487. }
  1488. if (updateReleaseList) {
  1489. updateReleaseList.innerHTML = '';
  1490. }
  1491. if (btnOpenRelease) {
  1492. btnOpenRelease.hidden = true;
  1493. btnOpenRelease.onclick = null;
  1494. }
  1495. }
  1496. function renderReleaseSnapshot(snapshot) {
  1497. currentReleaseSnapshot = snapshot;
  1498. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1499. return;
  1500. }
  1501. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed', 'is-version-label');
  1502. const localVersionText = snapshot?.localVersion ? `v${snapshot.localVersion}` : '';
  1503. const logUrl = snapshot?.logUrl || snapshot?.releasesPageUrl || sidepanelUpdateService?.releasesPageUrl || '';
  1504. if (btnReleaseLog) {
  1505. btnReleaseLog.onclick = () => openExternalUrl(logUrl);
  1506. btnReleaseLog.hidden = true;
  1507. }
  1508. extensionVersionMeta.hidden = true;
  1509. extensionVersionMeta.textContent = '';
  1510. switch (snapshot?.status) {
  1511. case 'update-available': {
  1512. extensionUpdateStatus.textContent = '有更新';
  1513. extensionUpdateStatus.classList.add('is-update-available');
  1514. if (btnReleaseLog) {
  1515. btnReleaseLog.hidden = false;
  1516. }
  1517. if (updateSection) {
  1518. updateSection.hidden = false;
  1519. }
  1520. if (updateCardVersion) {
  1521. updateCardVersion.textContent = `最新版本 v${snapshot.latestVersion}`;
  1522. }
  1523. if (updateCardSummary) {
  1524. const updateCount = Array.isArray(snapshot.newerReleases) ? snapshot.newerReleases.length : 0;
  1525. updateCardSummary.textContent = updateCount > 1
  1526. ? `当前 ${localVersionText},共有 ${updateCount} 个新版本可更新。`
  1527. : `当前 ${localVersionText},可更新到 v${snapshot.latestVersion}。`;
  1528. }
  1529. renderUpdateReleaseList(snapshot.newerReleases || []);
  1530. if (btnOpenRelease) {
  1531. btnOpenRelease.hidden = false;
  1532. btnOpenRelease.textContent = '前往更新';
  1533. btnOpenRelease.onclick = () => openExternalUrl(logUrl);
  1534. }
  1535. break;
  1536. }
  1537. case 'latest': {
  1538. extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
  1539. extensionUpdateStatus.classList.add('is-version-label');
  1540. resetUpdateCard();
  1541. break;
  1542. }
  1543. case 'empty': {
  1544. extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
  1545. extensionUpdateStatus.classList.add('is-version-label');
  1546. resetUpdateCard();
  1547. break;
  1548. }
  1549. case 'error':
  1550. default: {
  1551. extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
  1552. extensionUpdateStatus.classList.add('is-version-label', 'is-check-failed');
  1553. extensionVersionMeta.textContent = snapshot?.errorMessage || 'GitHub Releases 检查失败';
  1554. extensionVersionMeta.hidden = false;
  1555. resetUpdateCard();
  1556. break;
  1557. }
  1558. }
  1559. }
  1560. async function initializeReleaseInfo() {
  1561. const fallbackReleaseUrl = sidepanelUpdateService?.releasesPageUrl || 'https://github.com/QLHazyCoder/codex-oauth-automation-extension/releases';
  1562. if (btnReleaseLog) {
  1563. btnReleaseLog.onclick = () => openExternalUrl(currentReleaseSnapshot?.logUrl || fallbackReleaseUrl);
  1564. }
  1565. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1566. return;
  1567. }
  1568. const localVersion = sidepanelUpdateService?.stripVersionPrefix?.(chrome.runtime.getManifest()?.version || '') || '';
  1569. extensionUpdateStatus.textContent = localVersion ? `v${localVersion}` : 'v0.0.0';
  1570. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed');
  1571. extensionUpdateStatus.classList.add('is-version-label');
  1572. extensionVersionMeta.hidden = true;
  1573. extensionVersionMeta.textContent = '';
  1574. if (btnReleaseLog) {
  1575. btnReleaseLog.hidden = true;
  1576. }
  1577. resetUpdateCard();
  1578. if (!sidepanelUpdateService) {
  1579. extensionVersionMeta.textContent = '更新检查服务不可用';
  1580. extensionVersionMeta.hidden = false;
  1581. return;
  1582. }
  1583. const snapshot = await sidepanelUpdateService.getReleaseSnapshot();
  1584. renderReleaseSnapshot(snapshot);
  1585. }
  1586. function syncPasswordField(state) {
  1587. inputPassword.value = state.customPassword || state.password || '';
  1588. }
  1589. function isCustomMailProvider(provider = selectMailProvider.value) {
  1590. return String(provider || '').trim().toLowerCase() === 'custom';
  1591. }
  1592. function isLuckmailProvider(provider = selectMailProvider.value) {
  1593. return String(provider || '').trim().toLowerCase() === LUCKMAIL_PROVIDER;
  1594. }
  1595. function isIcloudMailProvider(provider = selectMailProvider.value) {
  1596. return String(provider || '').trim().toLowerCase() === ICLOUD_PROVIDER;
  1597. }
  1598. function normalizeLuckmailBaseUrl(value = '') {
  1599. const trimmed = String(value || '').trim();
  1600. if (!trimmed) {
  1601. return DEFAULT_LUCKMAIL_BASE_URL;
  1602. }
  1603. try {
  1604. const parsed = new URL(trimmed);
  1605. if (!['http:', 'https:'].includes(parsed.protocol)) {
  1606. return DEFAULT_LUCKMAIL_BASE_URL;
  1607. }
  1608. parsed.pathname = parsed.pathname.replace(/\/+$/, '');
  1609. parsed.search = '';
  1610. parsed.hash = '';
  1611. return parsed.toString().replace(/\/$/, '');
  1612. } catch {
  1613. return DEFAULT_LUCKMAIL_BASE_URL;
  1614. }
  1615. }
  1616. function normalizeLuckmailEmailType(value = '') {
  1617. const normalized = String(value || '').trim().toLowerCase();
  1618. return ['self_built', 'ms_imap', 'ms_graph', 'google_variant'].includes(normalized)
  1619. ? normalized
  1620. : DEFAULT_LUCKMAIL_EMAIL_TYPE;
  1621. }
  1622. function getSelectedEmailGenerator() {
  1623. const generator = String(selectEmailGenerator.value || '').trim().toLowerCase();
  1624. if (generator === 'custom' || generator === 'manual') {
  1625. return 'custom';
  1626. }
  1627. if (generator === 'icloud') {
  1628. return 'icloud';
  1629. }
  1630. if (generator === 'cloudflare') return 'cloudflare';
  1631. if (generator === 'cloudflare-temp-email') return 'cloudflare-temp-email';
  1632. return 'duck';
  1633. }
  1634. function getEmailGeneratorUiCopy() {
  1635. if (getSelectedEmailGenerator() === 'custom') {
  1636. return getCustomMailProviderUiCopy();
  1637. }
  1638. if (getSelectedEmailGenerator() === 'icloud') {
  1639. return {
  1640. buttonLabel: '获取',
  1641. placeholder: '点击获取 iCloud 隐私邮箱,或手动粘贴邮箱',
  1642. successVerb: '获取',
  1643. label: 'iCloud 隐私邮箱',
  1644. };
  1645. }
  1646. if (getSelectedEmailGenerator() === 'cloudflare') {
  1647. return {
  1648. buttonLabel: '生成',
  1649. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  1650. successVerb: '生成',
  1651. label: 'Cloudflare 邮箱',
  1652. };
  1653. }
  1654. if (getSelectedEmailGenerator() === 'cloudflare-temp-email') {
  1655. return {
  1656. buttonLabel: '生成 Temp',
  1657. placeholder: '点击生成 Cloudflare Temp Email,或手动粘贴邮箱',
  1658. successVerb: '生成',
  1659. label: 'Cloudflare Temp Email',
  1660. };
  1661. }
  1662. return {
  1663. buttonLabel: '获取',
  1664. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  1665. successVerb: '获取',
  1666. label: 'Duck 邮箱',
  1667. };
  1668. }
  1669. function getCustomMailProviderUiCopy() {
  1670. return {
  1671. buttonLabel: '自定义邮箱',
  1672. placeholder: '请填写本轮要使用的注册邮箱',
  1673. successVerb: '使用',
  1674. label: '自定义邮箱',
  1675. };
  1676. }
  1677. function getCustomVerificationPromptCopy(step) {
  1678. const verificationLabel = step === 4 ? '注册验证码' : '登录验证码';
  1679. return {
  1680. title: `手动处理${verificationLabel}`,
  1681. message: `当前邮箱服务为“自定义邮箱”。请先在页面中手动输入${verificationLabel},并确认已经进入下一页面后,再点击确认。`,
  1682. alert: {
  1683. text: `点击确认后会跳过步骤 ${step}。`,
  1684. tone: 'danger',
  1685. },
  1686. };
  1687. }
  1688. function getHotmailAccounts(state = latestState) {
  1689. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  1690. }
  1691. function getCurrentHotmailAccount(state = latestState) {
  1692. const currentId = state?.currentHotmailAccountId;
  1693. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  1694. }
  1695. function getCurrentHotmailEmail(state = latestState) {
  1696. return String(getCurrentHotmailAccount(state)?.email || '').trim();
  1697. }
  1698. function getCurrentLuckmailPurchase(state = latestState) {
  1699. return state?.currentLuckmailPurchase || null;
  1700. }
  1701. function getCurrentLuckmailEmail(state = latestState) {
  1702. return String(getCurrentLuckmailPurchase(state)?.email_address || '').trim();
  1703. }
  1704. function getLuckmailUsedPurchases(state = latestState) {
  1705. const rawValue = state?.luckmailUsedPurchases;
  1706. if (!rawValue || typeof rawValue !== 'object' || Array.isArray(rawValue)) {
  1707. return {};
  1708. }
  1709. return Object.entries(rawValue).reduce((result, [key, value]) => {
  1710. const numeric = Number(key);
  1711. if (!Number.isFinite(numeric) || numeric <= 0) {
  1712. return result;
  1713. }
  1714. result[String(Math.floor(numeric))] = Boolean(value);
  1715. return result;
  1716. }, {});
  1717. }
  1718. function normalizeLuckmailProjectName(value = '') {
  1719. return String(value || '').trim().toLowerCase();
  1720. }
  1721. function getLuckmailPreserveTagName(state = latestState) {
  1722. return String(state?.luckmailPreserveTagName || '').trim() || DEFAULT_LUCKMAIL_PRESERVE_TAG_NAME;
  1723. }
  1724. function formatLuckmailDateTime(value) {
  1725. const timestamp = normalizeLuckmailTimestampValue(value);
  1726. if (!timestamp) {
  1727. return String(value || '').trim() || '未知';
  1728. }
  1729. return new Date(timestamp).toLocaleString('zh-CN', {
  1730. hour12: false,
  1731. timeZone: DISPLAY_TIMEZONE,
  1732. });
  1733. }
  1734. function getMailProviderLoginConfig(provider = selectMailProvider.value) {
  1735. return MAIL_PROVIDER_LOGIN_CONFIGS[String(provider || '').trim()] || null;
  1736. }
  1737. function getSelectedIcloudHostPreference() {
  1738. return normalizeIcloudHost(selectIcloudHostPreference?.value || latestState?.icloudHostPreference || '')
  1739. || normalizeIcloudHost(latestState?.preferredIcloudHost)
  1740. || 'icloud.com';
  1741. }
  1742. function getMailProviderLoginUrl(provider = selectMailProvider.value) {
  1743. const config = getMailProviderLoginConfig(provider);
  1744. if (String(provider || '').trim() === ICLOUD_PROVIDER) {
  1745. return getIcloudLoginUrlForHost(getSelectedIcloudHostPreference());
  1746. }
  1747. const url = String(config?.url || '').trim();
  1748. return url ? url : '';
  1749. }
  1750. function isCurrentEmailManagedByHotmail(state = latestState) {
  1751. const hotmailEmail = getCurrentHotmailEmail(state);
  1752. if (!hotmailEmail) {
  1753. return false;
  1754. }
  1755. const inputEmailValue = String(inputEmail.value || '').trim();
  1756. const stateEmailValue = String(state?.email || '').trim();
  1757. return inputEmailValue === hotmailEmail || stateEmailValue === hotmailEmail;
  1758. }
  1759. function isCurrentEmailManagedByLuckmail(state = latestState) {
  1760. const luckmailEmail = getCurrentLuckmailEmail(state);
  1761. if (!luckmailEmail) {
  1762. return false;
  1763. }
  1764. const inputEmailValue = String(inputEmail.value || '').trim();
  1765. const stateEmailValue = String(state?.email || '').trim();
  1766. return inputEmailValue === luckmailEmail || stateEmailValue === luckmailEmail;
  1767. }
  1768. function isCurrentEmailManagedByGeneratedAlias(
  1769. provider = latestState?.mailProvider,
  1770. state = latestState,
  1771. mail2925Mode = latestState?.mail2925Mode
  1772. ) {
  1773. const normalizedProvider = String(provider || '').trim();
  1774. if (!usesGeneratedAliasMailProvider(normalizedProvider, mail2925Mode)) {
  1775. return false;
  1776. }
  1777. const inputEmailValue = String(inputEmail.value || '').trim().toLowerCase();
  1778. const stateEmailValue = String(state?.email || '').trim().toLowerCase();
  1779. if (normalizedProvider === GMAIL_PROVIDER) {
  1780. const baseEmail = String(state?.emailPrefix || inputEmailPrefix.value || '').trim();
  1781. return isManagedGmailAlias(inputEmailValue, baseEmail) || isManagedGmailAlias(stateEmailValue, baseEmail);
  1782. }
  1783. if (normalizedProvider === '2925') {
  1784. return inputEmailValue.endsWith('@2925.com') || stateEmailValue.endsWith('@2925.com');
  1785. }
  1786. return false;
  1787. }
  1788. async function maybeClearGeneratedAliasAfterEmailPrefixChange() {
  1789. const provider = selectMailProvider.value;
  1790. const mail2925Mode = latestState?.mail2925Mode;
  1791. if (!usesGeneratedAliasMailProvider(provider, mail2925Mode)) {
  1792. return;
  1793. }
  1794. const previousPrefix = String(latestState?.emailPrefix || '').trim();
  1795. const nextPrefix = inputEmailPrefix.value.trim();
  1796. if (previousPrefix === nextPrefix) {
  1797. return;
  1798. }
  1799. if (!isCurrentEmailManagedByGeneratedAlias(provider, latestState, mail2925Mode)) {
  1800. return;
  1801. }
  1802. await clearRegistrationEmail({ silent: true });
  1803. }
  1804. function updateMailLoginButtonState() {
  1805. if (!btnMailLogin) {
  1806. return;
  1807. }
  1808. const config = getMailProviderLoginConfig();
  1809. const loginUrl = getMailProviderLoginUrl();
  1810. btnMailLogin.disabled = !loginUrl;
  1811. btnMailLogin.textContent = config?.buttonLabel || '登录';
  1812. btnMailLogin.title = loginUrl ? `打开 ${config.label} 登录页` : '当前邮箱服务没有可跳转的登录页';
  1813. }
  1814. function updateMailProviderUI() {
  1815. const use2925 = selectMailProvider.value === '2925';
  1816. const useGmail = selectMailProvider.value === GMAIL_PROVIDER;
  1817. const mail2925Mode = getSelectedMail2925Mode();
  1818. const useGeneratedAlias = usesGeneratedAliasMailProvider(selectMailProvider.value, mail2925Mode);
  1819. const useInbucket = selectMailProvider.value === 'inbucket';
  1820. const useHotmail = selectMailProvider.value === 'hotmail-api';
  1821. const useLuckmail = isLuckmailProvider();
  1822. const useCustomEmail = isCustomMailProvider();
  1823. const useIcloudProvider = isIcloudMailProvider();
  1824. const useEmailGenerator = !useHotmail && !useLuckmail && !useGeneratedAlias && !useCustomEmail;
  1825. const useCloudflareTempEmailProvider = selectMailProvider.value === 'cloudflare-temp-email';
  1826. updateMailLoginButtonState();
  1827. if (rowMail2925Mode) {
  1828. rowMail2925Mode.style.display = use2925 ? '' : 'none';
  1829. }
  1830. rowEmailPrefix.style.display = useGeneratedAlias ? '' : 'none';
  1831. const hotmailServiceMode = getSelectedHotmailServiceMode();
  1832. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  1833. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  1834. const selectedGenerator = getSelectedEmailGenerator();
  1835. const useCloudflare = selectedGenerator === 'cloudflare';
  1836. const useIcloud = selectedGenerator === 'icloud';
  1837. const useCloudflareTempEmailGenerator = selectedGenerator === 'cloudflare-temp-email';
  1838. const showCloudflareDomain = useEmailGenerator && useCloudflare;
  1839. const showCloudflareTempEmailSettings = useCloudflareTempEmailProvider || (useEmailGenerator && useCloudflareTempEmailGenerator);
  1840. const showCloudflareTempEmailReceiveMailbox = useCloudflareTempEmailProvider && !useCloudflareTempEmailGenerator;
  1841. const showCloudflareTempEmailDomain = useEmailGenerator && useCloudflareTempEmailGenerator;
  1842. if (rowEmailGenerator) {
  1843. rowEmailGenerator.style.display = useEmailGenerator ? '' : 'none';
  1844. }
  1845. if (icloudSection) {
  1846. const showIcloudSection = (useEmailGenerator && useIcloud) || useIcloudProvider;
  1847. icloudSection.style.display = showIcloudSection ? '' : 'none';
  1848. if (showIcloudSection) {
  1849. queueIcloudAliasRefresh();
  1850. }
  1851. if (!showIcloudSection) {
  1852. hideIcloudLoginHelp();
  1853. }
  1854. }
  1855. rowCfDomain.style.display = showCloudflareDomain ? '' : 'none';
  1856. const { domains } = getCloudflareDomainsFromState();
  1857. if (showCloudflareDomain) {
  1858. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  1859. } else {
  1860. setCloudflareDomainEditMode(false, { clearInput: false });
  1861. }
  1862. rowTempEmailBaseUrl.style.display = showCloudflareTempEmailSettings ? '' : 'none';
  1863. rowTempEmailAdminAuth.style.display = showCloudflareTempEmailSettings ? '' : 'none';
  1864. rowTempEmailCustomAuth.style.display = showCloudflareTempEmailSettings ? '' : 'none';
  1865. rowTempEmailReceiveMailbox.style.display = showCloudflareTempEmailReceiveMailbox ? '' : 'none';
  1866. rowTempEmailDomain.style.display = showCloudflareTempEmailDomain ? '' : 'none';
  1867. const { domains: tempEmailDomains } = getCloudflareTempEmailDomainsFromState();
  1868. if (showCloudflareTempEmailDomain) {
  1869. setCloudflareTempEmailDomainEditMode(cloudflareTempEmailDomainEditMode || tempEmailDomains.length === 0, { clearInput: false });
  1870. } else {
  1871. setCloudflareTempEmailDomainEditMode(false, { clearInput: false });
  1872. }
  1873. if (hotmailSection) {
  1874. hotmailSection.style.display = useHotmail ? '' : 'none';
  1875. }
  1876. if (luckmailSection) {
  1877. luckmailSection.style.display = useLuckmail ? '' : 'none';
  1878. }
  1879. labelEmailPrefix.textContent = '邮箱前缀';
  1880. inputEmailPrefix.placeholder = '例如 abc';
  1881. selectEmailGenerator.disabled = useHotmail || useLuckmail || useGeneratedAlias || useCustomEmail;
  1882. if (useGmail) {
  1883. labelEmailPrefix.textContent = 'Gmail 原邮箱';
  1884. inputEmailPrefix.placeholder = '例如 yourname@gmail.com';
  1885. }
  1886. if (rowHotmailServiceMode) {
  1887. rowHotmailServiceMode.style.display = useHotmail ? '' : 'none';
  1888. }
  1889. if (rowHotmailRemoteBaseUrl) {
  1890. rowHotmailRemoteBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE ? '' : 'none';
  1891. }
  1892. if (rowHotmailLocalBaseUrl) {
  1893. rowHotmailLocalBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_LOCAL ? '' : 'none';
  1894. }
  1895. btnFetchEmail.hidden = useHotmail || useLuckmail || useCustomEmail;
  1896. inputEmail.readOnly = useHotmail || useLuckmail || useGeneratedAlias;
  1897. const uiCopy = useCustomEmail ? getCustomMailProviderUiCopy() : getEmailGeneratorUiCopy();
  1898. inputEmail.placeholder = useHotmail
  1899. ? '由 Hotmail 账号池自动分配'
  1900. : (useLuckmail
  1901. ? '步骤 3 自动购买 LuckMail 邮箱并回填'
  1902. : (useGeneratedAlias ? '步骤 3 自动生成 2925 邮箱并回填' : uiCopy.placeholder));
  1903. if (useGmail && useGeneratedAlias) {
  1904. inputEmail.placeholder = '步骤 3 自动生成 Gmail +tag 邮箱并回填';
  1905. }
  1906. btnFetchEmail.disabled = useGeneratedAlias || useLuckmail || useCustomEmail || isAutoRunLockedPhase();
  1907. if (!btnFetchEmail.disabled) {
  1908. btnFetchEmail.textContent = uiCopy.buttonLabel;
  1909. }
  1910. if (autoHintText) {
  1911. autoHintText.textContent = useHotmail
  1912. ? '请先校验并选择一个 Hotmail 账号'
  1913. : (useLuckmail
  1914. ? '步骤 3 会自动购买 LuckMail 邮箱并用于收码'
  1915. : (useGeneratedAlias
  1916. ? '步骤 3 会自动生成邮箱,无需手动获取'
  1917. : (useCustomEmail ? '请先填写自定义注册邮箱,成功一轮后会自动清空' : `先自动获取${uiCopy.label},或手动粘贴邮箱后再继续`)));
  1918. }
  1919. if (autoHintText && useGmail && useGeneratedAlias) {
  1920. autoHintText.textContent = '请先填写 Gmail 原邮箱,步骤 3 会自动生成 Gmail +tag 地址';
  1921. }
  1922. if (autoHintText && showCloudflareTempEmailReceiveMailbox) {
  1923. autoHintText.textContent = '若注册邮箱会转发到 Cloudflare Temp Email,请在“邮件接收”中填写实际接收转发邮件的邮箱。';
  1924. }
  1925. if (useHotmail) {
  1926. inputEmail.value = getCurrentHotmailEmail();
  1927. } else if (useLuckmail) {
  1928. inputEmail.value = getCurrentLuckmailEmail();
  1929. }
  1930. renderHotmailAccounts();
  1931. if (useLuckmail) {
  1932. renderLuckmailPurchases();
  1933. }
  1934. }
  1935. async function saveCloudflareDomainSettings(domains, activeDomain, options = {}) {
  1936. const { silent = false } = options;
  1937. const normalizedDomains = normalizeCloudflareDomains(domains);
  1938. const normalizedActiveDomain = normalizeCloudflareDomainValue(activeDomain) || normalizedDomains[0] || '';
  1939. const payload = {
  1940. cloudflareDomain: normalizedActiveDomain,
  1941. cloudflareDomains: normalizedDomains,
  1942. };
  1943. const response = await chrome.runtime.sendMessage({
  1944. type: 'SAVE_SETTING',
  1945. source: 'sidepanel',
  1946. payload,
  1947. });
  1948. if (response?.error) {
  1949. throw new Error(response.error);
  1950. }
  1951. syncLatestState({
  1952. ...payload,
  1953. });
  1954. renderCloudflareDomainOptions(normalizedActiveDomain);
  1955. setCloudflareDomainEditMode(false, { clearInput: true });
  1956. markSettingsDirty(false);
  1957. updateMailProviderUI();
  1958. if (!silent) {
  1959. showToast('Cloudflare 域名已保存', 'success', 1800);
  1960. }
  1961. }
  1962. async function saveCloudflareTempEmailDomainSettings(domains, activeDomain, options = {}) {
  1963. const { silent = false } = options;
  1964. const normalizedDomains = normalizeCloudflareTempEmailDomains(domains);
  1965. const normalizedActiveDomain = normalizeCloudflareTempEmailDomainValue(activeDomain) || normalizedDomains[0] || '';
  1966. const payload = {
  1967. cloudflareTempEmailDomain: normalizedActiveDomain,
  1968. cloudflareTempEmailDomains: normalizedDomains,
  1969. };
  1970. const response = await chrome.runtime.sendMessage({
  1971. type: 'SAVE_SETTING',
  1972. source: 'sidepanel',
  1973. payload,
  1974. });
  1975. if (response?.error) {
  1976. throw new Error(response.error);
  1977. }
  1978. syncLatestState({
  1979. ...payload,
  1980. });
  1981. renderCloudflareTempEmailDomainOptions(normalizedActiveDomain);
  1982. setCloudflareTempEmailDomainEditMode(false, { clearInput: true });
  1983. markSettingsDirty(false);
  1984. updateMailProviderUI();
  1985. if (!silent) {
  1986. showToast('Cloudflare Temp Email 域名已保存', 'success', 1800);
  1987. }
  1988. }
  1989. function updatePanelModeUI() {
  1990. const useSub2Api = selectPanelMode.value === 'sub2api';
  1991. rowVpsUrl.style.display = useSub2Api ? 'none' : '';
  1992. rowVpsPassword.style.display = useSub2Api ? 'none' : '';
  1993. rowLocalCpaStep9Mode.style.display = useSub2Api ? 'none' : '';
  1994. rowCpaCallbackMode.style.display = useSub2Api ? 'none' : '';
  1995. rowSub2ApiUrl.style.display = useSub2Api ? '' : 'none';
  1996. rowSub2ApiEmail.style.display = useSub2Api ? '' : 'none';
  1997. rowSub2ApiPassword.style.display = useSub2Api ? '' : 'none';
  1998. rowSub2ApiGroup.style.display = useSub2Api ? '' : 'none';
  1999. const step9Btn = document.querySelector('.step-btn[data-step="9"]');
  2000. if (step9Btn) {
  2001. step9Btn.textContent = useSub2Api ? 'SUB2API 回调验证' : 'CPA 回调验证';
  2002. }
  2003. }
  2004. // ============================================================
  2005. // UI Updates
  2006. // ============================================================
  2007. function updateStepUI(step, status) {
  2008. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  2009. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  2010. syncLatestState({
  2011. stepStatuses: {
  2012. ...getStepStatuses(),
  2013. [step]: status,
  2014. },
  2015. });
  2016. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  2017. if (row) {
  2018. row.className = `step-row ${status}`;
  2019. }
  2020. updateButtonStates();
  2021. updateProgressCounter();
  2022. updateConfigMenuControls();
  2023. }
  2024. function updateProgressCounter() {
  2025. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  2026. stepsProgress.textContent = `${completed} / 9`;
  2027. }
  2028. function updateButtonStates() {
  2029. const statuses = getStepStatuses();
  2030. const anyRunning = Object.values(statuses).some(s => s === 'running');
  2031. const autoLocked = isAutoRunLockedPhase();
  2032. const autoScheduled = isAutoRunScheduledPhase();
  2033. for (let step = 1; step <= 9; step++) {
  2034. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  2035. if (!btn) continue;
  2036. if (anyRunning || autoLocked || autoScheduled) {
  2037. btn.disabled = true;
  2038. } else if (step === 1) {
  2039. btn.disabled = false;
  2040. } else {
  2041. const prevStatus = statuses[step - 1];
  2042. const currentStatus = statuses[step];
  2043. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  2044. }
  2045. }
  2046. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  2047. const step = Number(btn.dataset.step);
  2048. const currentStatus = statuses[step];
  2049. const prevStatus = statuses[step - 1];
  2050. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  2051. btn.style.display = 'none';
  2052. btn.disabled = true;
  2053. btn.title = '当前不可跳过';
  2054. return;
  2055. }
  2056. if (step > 1 && !isDoneStatus(prevStatus)) {
  2057. btn.style.display = 'none';
  2058. btn.disabled = true;
  2059. btn.title = `请先完成步骤 ${step - 1}`;
  2060. return;
  2061. }
  2062. btn.style.display = '';
  2063. btn.disabled = false;
  2064. btn.title = `跳过步骤 ${step}`;
  2065. });
  2066. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  2067. const disableIcloudControls = anyRunning || autoScheduled || autoLocked;
  2068. if (btnIcloudRefresh) btnIcloudRefresh.disabled = disableIcloudControls;
  2069. if (btnIcloudDeleteUsed) btnIcloudDeleteUsed.disabled = disableIcloudControls || !hasDeletableUsedIcloudAliases();
  2070. if (selectIcloudHostPreference) selectIcloudHostPreference.disabled = disableIcloudControls;
  2071. if (checkboxAutoDeleteIcloud) checkboxAutoDeleteIcloud.disabled = disableIcloudControls;
  2072. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  2073. }
  2074. function updateStopButtonState(active) {
  2075. btnStop.disabled = !active;
  2076. }
  2077. function updateStatusDisplay(state) {
  2078. if (!state || !state.stepStatuses) return;
  2079. statusBar.className = 'status-bar';
  2080. const countdown = getActiveAutoRunCountdown();
  2081. if (countdown) {
  2082. const remainingMs = countdown.at - Date.now();
  2083. displayStatus.textContent = remainingMs > 0
  2084. ? `${countdown.title},剩余 ${formatCountdown(remainingMs)}`
  2085. : `${countdown.title},即将结束...`;
  2086. statusBar.classList.add(countdown.tone === 'scheduled' ? 'scheduled' : 'running');
  2087. return;
  2088. }
  2089. if (isAutoRunScheduledPhase()) {
  2090. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  2091. ? currentAutoRun.scheduledAt - Date.now()
  2092. : 0;
  2093. displayStatus.textContent = remainingMs > 0
  2094. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  2095. : '倒计时即将结束,正在准备启动...';
  2096. statusBar.classList.add('scheduled');
  2097. return;
  2098. }
  2099. if (isAutoRunPausedPhase()) {
  2100. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  2101. statusBar.classList.add('paused');
  2102. return;
  2103. }
  2104. if (isAutoRunWaitingStepPhase()) {
  2105. const runningSteps = getRunningSteps(state);
  2106. displayStatus.textContent = runningSteps.length
  2107. ? `自动等待步骤 ${runningSteps.join(', ')} 完成后继续${getAutoRunLabel()}`
  2108. : `自动正在按最新进度准备继续${getAutoRunLabel()}`;
  2109. statusBar.classList.add('running');
  2110. return;
  2111. }
  2112. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  2113. if (running) {
  2114. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  2115. statusBar.classList.add('running');
  2116. return;
  2117. }
  2118. if (isAutoRunLockedPhase()) {
  2119. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  2120. statusBar.classList.add('running');
  2121. return;
  2122. }
  2123. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  2124. if (failed) {
  2125. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  2126. statusBar.classList.add('failed');
  2127. return;
  2128. }
  2129. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  2130. if (stopped) {
  2131. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  2132. statusBar.classList.add('stopped');
  2133. return;
  2134. }
  2135. const lastCompleted = Object.entries(state.stepStatuses)
  2136. .filter(([, s]) => isDoneStatus(s))
  2137. .map(([k]) => Number(k))
  2138. .sort((a, b) => b - a)[0];
  2139. if (lastCompleted === 9) {
  2140. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  2141. statusBar.classList.add('completed');
  2142. } else if (lastCompleted) {
  2143. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  2144. ? `步骤 ${lastCompleted} 已跳过`
  2145. : `步骤 ${lastCompleted} 已完成`;
  2146. } else {
  2147. displayStatus.textContent = '就绪';
  2148. }
  2149. }
  2150. function appendLog(entry) {
  2151. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', {
  2152. hour12: false,
  2153. timeZone: DISPLAY_TIMEZONE,
  2154. });
  2155. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  2156. const line = document.createElement('div');
  2157. line.className = `log-line log-${entry.level}`;
  2158. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  2159. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  2160. let html = `<span class="log-time">${time}</span> `;
  2161. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  2162. if (stepNum) {
  2163. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  2164. }
  2165. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  2166. line.innerHTML = html;
  2167. logArea.appendChild(line);
  2168. logArea.scrollTop = logArea.scrollHeight;
  2169. }
  2170. function escapeHtml(text) {
  2171. const div = document.createElement('div');
  2172. div.textContent = text;
  2173. return div.innerHTML;
  2174. }
  2175. async function fetchGeneratedEmail(options = {}) {
  2176. const { showFailureToast = true } = options;
  2177. const uiCopy = getEmailGeneratorUiCopy();
  2178. if (isCustomMailProvider()) {
  2179. throw new Error('当前邮箱服务为自定义邮箱,请直接填写注册邮箱。');
  2180. }
  2181. const defaultLabel = uiCopy.buttonLabel;
  2182. btnFetchEmail.disabled = true;
  2183. btnFetchEmail.textContent = '...';
  2184. try {
  2185. const response = await chrome.runtime.sendMessage({
  2186. type: 'FETCH_GENERATED_EMAIL',
  2187. source: 'sidepanel',
  2188. payload: {
  2189. generateNew: true,
  2190. generator: selectEmailGenerator.value,
  2191. },
  2192. });
  2193. if (response?.error) {
  2194. throw new Error(response.error);
  2195. }
  2196. if (!response?.email) {
  2197. throw new Error('未返回可用邮箱。');
  2198. }
  2199. inputEmail.value = response.email;
  2200. if (getSelectedEmailGenerator() === 'icloud') {
  2201. queueIcloudAliasRefresh();
  2202. }
  2203. showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500);
  2204. return response.email;
  2205. } catch (err) {
  2206. if (showFailureToast) {
  2207. showToast(`${uiCopy.label}${uiCopy.successVerb}失败:${err.message}`, 'error');
  2208. }
  2209. throw err;
  2210. } finally {
  2211. btnFetchEmail.disabled = false;
  2212. btnFetchEmail.textContent = defaultLabel;
  2213. }
  2214. }
  2215. function syncToggleButtonLabel(button, input, labels) {
  2216. if (!button || !input) return;
  2217. const isHidden = input.type === 'password';
  2218. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  2219. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  2220. button.title = isHidden ? labels.show : labels.hide;
  2221. }
  2222. async function copyTextToClipboard(text) {
  2223. const value = String(text || '').trim();
  2224. if (!value) {
  2225. throw new Error('没有可复制的内容。');
  2226. }
  2227. if (!navigator.clipboard?.writeText) {
  2228. throw new Error('当前环境不支持剪贴板复制。');
  2229. }
  2230. await navigator.clipboard.writeText(value);
  2231. }
  2232. const hotmailManager = window.SidepanelHotmailManager?.createHotmailManager({
  2233. state: {
  2234. getLatestState: () => latestState,
  2235. syncLatestState,
  2236. },
  2237. dom: {
  2238. btnAddHotmailAccount,
  2239. btnClearUsedHotmailAccounts,
  2240. btnDeleteAllHotmailAccounts,
  2241. btnHotmailUsageGuide,
  2242. btnImportHotmailAccounts,
  2243. btnToggleHotmailList,
  2244. hotmailAccountsList,
  2245. hotmailListShell,
  2246. inputEmail,
  2247. inputHotmailClientId,
  2248. inputHotmailEmail,
  2249. inputHotmailImport,
  2250. inputHotmailPassword,
  2251. inputHotmailRefreshToken,
  2252. selectMailProvider,
  2253. },
  2254. helpers: {
  2255. copyTextToClipboard,
  2256. escapeHtml,
  2257. getCurrentHotmailEmail,
  2258. getHotmailAccounts,
  2259. openConfirmModal,
  2260. showToast,
  2261. },
  2262. runtime: {
  2263. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2264. },
  2265. constants: {
  2266. copyIcon: COPY_ICON,
  2267. displayTimeZone: DISPLAY_TIMEZONE,
  2268. expandedStorageKey: 'multipage-hotmail-list-expanded',
  2269. },
  2270. hotmailUtils: {
  2271. filterHotmailAccountsByUsage,
  2272. getHotmailBulkActionLabel,
  2273. getHotmailListToggleLabel,
  2274. parseHotmailImportText,
  2275. shouldClearHotmailCurrentSelection,
  2276. upsertHotmailAccountInList,
  2277. },
  2278. });
  2279. const initHotmailListExpandedState = hotmailManager?.initHotmailListExpandedState
  2280. || (() => { });
  2281. const renderHotmailAccounts = hotmailManager?.renderHotmailAccounts
  2282. || (() => { });
  2283. const bindHotmailEvents = hotmailManager?.bindHotmailEvents
  2284. || (() => { });
  2285. bindHotmailEvents();
  2286. const icloudManager = window.SidepanelIcloudManager?.createIcloudManager({
  2287. dom: {
  2288. btnIcloudBulkDelete,
  2289. btnIcloudBulkPreserve,
  2290. btnIcloudBulkUnpreserve,
  2291. btnIcloudBulkUnused,
  2292. btnIcloudBulkUsed,
  2293. btnIcloudDeleteUsed,
  2294. btnIcloudLoginDone,
  2295. btnIcloudRefresh,
  2296. checkboxIcloudSelectAll,
  2297. icloudList,
  2298. icloudLoginHelp,
  2299. icloudLoginHelpText,
  2300. icloudLoginHelpTitle,
  2301. icloudSection,
  2302. icloudSelectionSummary,
  2303. icloudSummary,
  2304. inputIcloudSearch,
  2305. selectIcloudFilter,
  2306. },
  2307. helpers: {
  2308. copyTextToClipboard,
  2309. escapeHtml,
  2310. openConfirmModal,
  2311. showToast,
  2312. },
  2313. runtime: {
  2314. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2315. },
  2316. });
  2317. const hideIcloudLoginHelp = icloudManager?.hideIcloudLoginHelp
  2318. || (() => { });
  2319. const hasDeletableUsedIcloudAliases = icloudManager?.hasDeletableUsedAliases
  2320. || (() => false);
  2321. const queueIcloudAliasRefresh = icloudManager?.queueIcloudAliasRefresh
  2322. || (() => { });
  2323. const refreshIcloudAliases = icloudManager?.refreshIcloudAliases
  2324. || (async () => { });
  2325. const renderIcloudAliases = icloudManager?.renderIcloudAliases
  2326. || (() => { });
  2327. const resetIcloudManager = icloudManager?.reset
  2328. || (() => { });
  2329. const showIcloudLoginHelp = icloudManager?.showIcloudLoginHelp
  2330. || (() => { });
  2331. const updateIcloudBulkUI = icloudManager?.updateIcloudBulkUI
  2332. || (() => { });
  2333. const bindIcloudEvents = icloudManager?.bindIcloudEvents
  2334. || (() => { });
  2335. bindIcloudEvents();
  2336. const luckmailManager = window.SidepanelLuckmailManager?.createLuckmailManager({
  2337. dom: {
  2338. btnLuckmailBulkDisable,
  2339. btnLuckmailBulkEnable,
  2340. btnLuckmailBulkPreserve,
  2341. btnLuckmailBulkUnpreserve,
  2342. btnLuckmailBulkUnused,
  2343. btnLuckmailBulkUsed,
  2344. btnLuckmailDisableUsed,
  2345. btnLuckmailRefresh,
  2346. checkboxLuckmailSelectAll,
  2347. inputEmail,
  2348. inputLuckmailSearch,
  2349. luckmailList,
  2350. luckmailSection,
  2351. luckmailSelectionSummary,
  2352. luckmailSummary,
  2353. selectLuckmailFilter,
  2354. },
  2355. helpers: {
  2356. copyTextToClipboard,
  2357. escapeHtml,
  2358. formatLuckmailDateTime,
  2359. getLuckmailPreserveTagName,
  2360. normalizeLuckmailProjectName,
  2361. openConfirmModal,
  2362. showToast,
  2363. },
  2364. runtime: {
  2365. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2366. },
  2367. constants: {
  2368. copyIcon: COPY_ICON,
  2369. },
  2370. });
  2371. const queueLuckmailPurchaseRefresh = luckmailManager?.queueLuckmailPurchaseRefresh
  2372. || (() => { });
  2373. const refreshLuckmailPurchases = luckmailManager?.refreshLuckmailPurchases
  2374. || (async () => { });
  2375. const renderLuckmailPurchases = luckmailManager?.renderLuckmailPurchases
  2376. || (() => { });
  2377. const resetLuckmailManager = luckmailManager?.reset
  2378. || (() => { });
  2379. const bindLuckmailEvents = luckmailManager?.bindLuckmailEvents
  2380. || (() => { });
  2381. bindLuckmailEvents();
  2382. async function exportSettingsFile() {
  2383. closeConfigMenu();
  2384. configActionInFlight = true;
  2385. updateConfigMenuControls();
  2386. try {
  2387. await flushPendingSettingsBeforeExport();
  2388. const response = await chrome.runtime.sendMessage({
  2389. type: 'EXPORT_SETTINGS',
  2390. source: 'sidepanel',
  2391. payload: {},
  2392. });
  2393. if (response?.error) {
  2394. throw new Error(response.error);
  2395. }
  2396. if (!response?.fileContent || !response?.fileName) {
  2397. throw new Error('\u672a\u751f\u6210\u53ef\u4e0b\u8f7d\u7684\u914d\u7f6e\u6587\u4ef6\u3002');
  2398. }
  2399. downloadTextFile(response.fileContent, response.fileName);
  2400. showToast('\u914d\u7f6e\u5df2\u5bfc\u51fa\uff1a' + response.fileName, 'success', 2200);
  2401. } catch (err) {
  2402. showToast('\u5bfc\u51fa\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  2403. } finally {
  2404. configActionInFlight = false;
  2405. updateConfigMenuControls();
  2406. }
  2407. }
  2408. async function importSettingsFromFile(file) {
  2409. if (!file) return;
  2410. configActionInFlight = true;
  2411. closeConfigMenu();
  2412. updateConfigMenuControls();
  2413. try {
  2414. await settlePendingSettingsBeforeImport();
  2415. const rawText = await file.text();
  2416. let parsedConfig = null;
  2417. try {
  2418. parsedConfig = JSON.parse(rawText);
  2419. } catch {
  2420. throw new Error('\u914d\u7f6e\u6587\u4ef6\u4e0d\u662f\u6709\u6548\u7684 JSON\u3002');
  2421. }
  2422. const confirmed = await openConfirmModal({
  2423. title: '\u5bfc\u5165\u914d\u7f6e',
  2424. message: '\u786e\u8ba4\u5bfc\u5165\u914d\u7f6e\u6587\u4ef6 "' + file.name + '" \u5417\uff1f\u5bfc\u5165\u540e\u4f1a\u8986\u76d6\u5f53\u524d\u914d\u7f6e\u3002',
  2425. confirmLabel: '\u786e\u8ba4\u8986\u76d6\u5bfc\u5165',
  2426. confirmVariant: 'btn-danger',
  2427. });
  2428. if (!confirmed) {
  2429. return;
  2430. }
  2431. const response = await chrome.runtime.sendMessage({
  2432. type: 'IMPORT_SETTINGS',
  2433. source: 'sidepanel',
  2434. payload: {
  2435. config: parsedConfig,
  2436. },
  2437. });
  2438. if (response?.error) {
  2439. throw new Error(response.error);
  2440. }
  2441. if (!response?.state) {
  2442. throw new Error('\u5bfc\u5165\u540e\u672a\u8fd4\u56de\u6700\u65b0\u914d\u7f6e\u72b6\u6001\u3002');
  2443. }
  2444. applySettingsState(response.state);
  2445. updateStatusDisplay(latestState);
  2446. showToast('\u914d\u7f6e\u5df2\u5bfc\u5165\uff0c\u5f53\u524d\u914d\u7f6e\u5df2\u8986\u76d6\u3002', 'success', 2200);
  2447. } catch (err) {
  2448. showToast('\u5bfc\u5165\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  2449. } finally {
  2450. configActionInFlight = false;
  2451. updateConfigMenuControls();
  2452. if (inputImportSettingsFile) {
  2453. inputImportSettingsFile.value = '';
  2454. }
  2455. }
  2456. }
  2457. function syncPasswordToggleLabel() {
  2458. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  2459. show: '显示密码',
  2460. hide: '隐藏密码',
  2461. });
  2462. }
  2463. function syncVpsUrlToggleLabel() {
  2464. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  2465. show: '显示 CPA 地址',
  2466. hide: '隐藏 CPA 地址',
  2467. });
  2468. }
  2469. function syncVpsPasswordToggleLabel() {
  2470. syncToggleButtonLabel(btnToggleVpsPassword, inputVpsPassword, {
  2471. show: '显示管理密钥',
  2472. hide: '隐藏管理密钥',
  2473. });
  2474. }
  2475. async function maybeTakeoverAutoRun(actionLabel) {
  2476. if (!isAutoRunPausedPhase()) {
  2477. return true;
  2478. }
  2479. const confirmed = await openConfirmModal({
  2480. title: '接管自动',
  2481. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  2482. confirmLabel: '确认接管',
  2483. confirmVariant: 'btn-primary',
  2484. });
  2485. if (!confirmed) {
  2486. return false;
  2487. }
  2488. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  2489. return true;
  2490. }
  2491. async function handleSkipStep(step) {
  2492. if (isAutoRunPausedPhase()) {
  2493. const takeoverResponse = await chrome.runtime.sendMessage({
  2494. type: 'TAKEOVER_AUTO_RUN',
  2495. source: 'sidepanel',
  2496. payload: {},
  2497. });
  2498. if (takeoverResponse?.error) {
  2499. throw new Error(takeoverResponse.error);
  2500. }
  2501. }
  2502. const response = await chrome.runtime.sendMessage({
  2503. type: 'SKIP_STEP',
  2504. source: 'sidepanel',
  2505. payload: { step },
  2506. });
  2507. if (response?.error) {
  2508. throw new Error(response.error);
  2509. }
  2510. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  2511. }
  2512. // ============================================================
  2513. // Button Handlers
  2514. // ============================================================
  2515. document.querySelectorAll('.step-btn').forEach(btn => {
  2516. btn.addEventListener('click', async () => {
  2517. try {
  2518. const step = Number(btn.dataset.step);
  2519. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  2520. return;
  2521. }
  2522. if (step === 3) {
  2523. if (inputPassword.value !== (latestState?.customPassword || '')) {
  2524. await chrome.runtime.sendMessage({
  2525. type: 'SAVE_SETTING',
  2526. source: 'sidepanel',
  2527. payload: { customPassword: inputPassword.value },
  2528. });
  2529. syncLatestState({ customPassword: inputPassword.value });
  2530. }
  2531. let email = inputEmail.value.trim();
  2532. if (selectMailProvider.value === 'hotmail-api' || isLuckmailProvider()) {
  2533. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  2534. if (response?.error) {
  2535. throw new Error(response.error);
  2536. }
  2537. } else if (usesGeneratedAliasMailProvider(selectMailProvider.value)) {
  2538. const emailPrefix = inputEmailPrefix.value.trim();
  2539. if (!emailPrefix) {
  2540. showToast(selectMailProvider.value === GMAIL_PROVIDER ? '请先填写 Gmail 原邮箱。' : '请先填写 2925 邮箱前缀。', 'warn');
  2541. return;
  2542. }
  2543. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, emailPrefix } });
  2544. if (response?.error) {
  2545. throw new Error(response.error);
  2546. }
  2547. } else {
  2548. let email = inputEmail.value.trim();
  2549. if (!email) {
  2550. if (isCustomMailProvider()) {
  2551. showToast('当前邮箱服务为自定义邮箱,请先填写注册邮箱后再执行第 3 步。', 'warn');
  2552. return;
  2553. }
  2554. try {
  2555. email = await fetchGeneratedEmail({ showFailureToast: false });
  2556. } catch (err) {
  2557. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  2558. return;
  2559. }
  2560. }
  2561. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  2562. if (response?.error) {
  2563. throw new Error(response.error);
  2564. }
  2565. }
  2566. } else {
  2567. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  2568. if (response?.error) {
  2569. throw new Error(response.error);
  2570. }
  2571. }
  2572. } catch (err) {
  2573. showToast(err.message, 'error');
  2574. }
  2575. });
  2576. });
  2577. btnFetchEmail.addEventListener('click', async () => {
  2578. if (selectMailProvider.value === 'hotmail-api' || isLuckmailProvider() || isCustomMailProvider()) {
  2579. return;
  2580. }
  2581. await fetchGeneratedEmail().catch(() => { });
  2582. });
  2583. btnTogglePassword.addEventListener('click', () => {
  2584. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  2585. syncPasswordToggleLabel();
  2586. });
  2587. btnToggleVpsUrl.addEventListener('click', () => {
  2588. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  2589. syncVpsUrlToggleLabel();
  2590. });
  2591. btnToggleVpsPassword.addEventListener('click', () => {
  2592. inputVpsPassword.type = inputVpsPassword.type === 'password' ? 'text' : 'password';
  2593. syncVpsPasswordToggleLabel();
  2594. });
  2595. btnMailLogin?.addEventListener('click', async () => {
  2596. const config = getMailProviderLoginConfig();
  2597. const loginUrl = getMailProviderLoginUrl();
  2598. if (!config || !loginUrl) {
  2599. return;
  2600. }
  2601. try {
  2602. await chrome.tabs.create({ url: loginUrl, active: true });
  2603. } catch (err) {
  2604. showToast(`打开${config.label}失败:${err.message}`, 'error');
  2605. }
  2606. });
  2607. localCpaStep9ModeButtons.forEach((button) => {
  2608. button.addEventListener('click', () => {
  2609. const nextMode = button.dataset.localCpaStep9Mode;
  2610. if (getSelectedLocalCpaStep9Mode() === normalizeLocalCpaStep9Mode(nextMode)) {
  2611. return;
  2612. }
  2613. setLocalCpaStep9Mode(nextMode);
  2614. markSettingsDirty(true);
  2615. saveSettings({ silent: true }).catch(() => { });
  2616. });
  2617. });
  2618. cpaCallbackModeButtons.forEach((button) => {
  2619. button.addEventListener('click', () => {
  2620. const nextMode = button.dataset.cpaCallbackMode;
  2621. if (getSelectedCpaCallbackMode() === normalizeCpaCallbackMode(nextMode)) {
  2622. return;
  2623. }
  2624. setCpaCallbackMode(nextMode);
  2625. markSettingsDirty(true);
  2626. saveSettings({ silent: true }).catch(() => { });
  2627. });
  2628. });
  2629. hotmailServiceModeButtons.forEach((button) => {
  2630. button.addEventListener('click', () => {
  2631. if (button.disabled) {
  2632. return;
  2633. }
  2634. const nextMode = button.dataset.hotmailServiceMode;
  2635. if (getSelectedHotmailServiceMode() === normalizeHotmailServiceMode(nextMode)) {
  2636. return;
  2637. }
  2638. setHotmailServiceMode(nextMode);
  2639. updateMailProviderUI();
  2640. markSettingsDirty(true);
  2641. saveSettings({ silent: true }).catch(() => { });
  2642. });
  2643. });
  2644. btnSaveSettings.addEventListener('click', async () => {
  2645. if (!settingsDirty) {
  2646. showToast('配置已是最新', 'info', 1400);
  2647. return;
  2648. }
  2649. await saveSettings({ silent: false }).catch(() => { });
  2650. });
  2651. btnStop.addEventListener('click', async () => {
  2652. btnStop.disabled = true;
  2653. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  2654. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  2655. });
  2656. btnConfigMenu?.addEventListener('click', (event) => {
  2657. event.stopPropagation();
  2658. toggleConfigMenu();
  2659. });
  2660. configMenu?.addEventListener('click', (event) => {
  2661. event.stopPropagation();
  2662. });
  2663. btnExportSettings?.addEventListener('click', async () => {
  2664. if (configActionInFlight || settingsSaveInFlight) {
  2665. return;
  2666. }
  2667. await exportSettingsFile();
  2668. });
  2669. btnImportSettings?.addEventListener('click', async () => {
  2670. if (configActionInFlight || settingsSaveInFlight) {
  2671. return;
  2672. }
  2673. closeConfigMenu();
  2674. if (inputImportSettingsFile) {
  2675. inputImportSettingsFile.value = '';
  2676. inputImportSettingsFile.click();
  2677. }
  2678. });
  2679. inputImportSettingsFile?.addEventListener('change', async () => {
  2680. const file = inputImportSettingsFile.files?.[0] || null;
  2681. await importSettingsFromFile(file);
  2682. });
  2683. autoStartModal?.addEventListener('click', (event) => {
  2684. if (event.target === autoStartModal) {
  2685. resolveModalChoice(null);
  2686. }
  2687. });
  2688. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  2689. // Auto Run
  2690. btnAutoRun.addEventListener('click', async () => {
  2691. try {
  2692. const totalRuns = getRunCountValue();
  2693. let mode = 'restart';
  2694. const autoRunSkipFailures = inputAutoSkipFailures.checked;
  2695. const fallbackThreadIntervalMinutes = normalizeAutoRunThreadIntervalMinutes(
  2696. inputAutoSkipFailuresThreadIntervalMinutes.value
  2697. );
  2698. inputAutoSkipFailuresThreadIntervalMinutes.value = String(fallbackThreadIntervalMinutes);
  2699. if (shouldOfferAutoModeChoice()) {
  2700. const startStep = getFirstUnfinishedStep();
  2701. const runningStep = getRunningSteps()[0] ?? null;
  2702. const choice = await openAutoStartChoiceDialog(startStep, { runningStep });
  2703. if (!choice) {
  2704. return;
  2705. }
  2706. mode = choice;
  2707. }
  2708. if (shouldWarnAutoRunFallbackRisk(totalRuns, autoRunSkipFailures)
  2709. && !isAutoRunFallbackRiskPromptDismissed()) {
  2710. const result = await openAutoRunFallbackRiskConfirmModal(totalRuns, fallbackThreadIntervalMinutes);
  2711. if (!result.confirmed) {
  2712. return;
  2713. }
  2714. if (result.dismissPrompt) {
  2715. setAutoRunFallbackRiskPromptDismissed(true);
  2716. }
  2717. }
  2718. btnAutoRun.disabled = true;
  2719. inputRunCount.disabled = true;
  2720. const delayEnabled = inputAutoDelayEnabled.checked;
  2721. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  2722. inputAutoDelayMinutes.value = String(delayMinutes);
  2723. btnAutoRun.innerHTML = delayEnabled
  2724. ? '<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> 计划中...'
  2725. : '<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> 运行中...';
  2726. const response = await chrome.runtime.sendMessage({
  2727. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  2728. source: 'sidepanel',
  2729. payload: {
  2730. totalRuns,
  2731. delayMinutes,
  2732. autoRunSkipFailures,
  2733. mode,
  2734. },
  2735. });
  2736. if (response?.error) {
  2737. throw new Error(response.error);
  2738. }
  2739. } catch (err) {
  2740. setDefaultAutoRunButton();
  2741. inputRunCount.disabled = false;
  2742. showToast(err.message, 'error');
  2743. }
  2744. });
  2745. btnAutoContinue.addEventListener('click', async () => {
  2746. const email = inputEmail.value.trim();
  2747. if (!email) {
  2748. showToast(
  2749. isCustomMailProvider() ? '请先填写自定义注册邮箱。' : '请先获取或粘贴邮箱。',
  2750. 'warn'
  2751. );
  2752. return;
  2753. }
  2754. autoContinueBar.style.display = 'none';
  2755. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  2756. });
  2757. btnAutoRunNow?.addEventListener('click', async () => {
  2758. try {
  2759. btnAutoRunNow.disabled = true;
  2760. const waitingInterval = currentAutoRun.phase === 'waiting_interval';
  2761. await chrome.runtime.sendMessage({
  2762. type: waitingInterval ? 'SKIP_AUTO_RUN_COUNTDOWN' : 'START_SCHEDULED_AUTO_RUN_NOW',
  2763. source: 'sidepanel',
  2764. payload: {},
  2765. });
  2766. if (waitingInterval) {
  2767. showToast('已跳过当前倒计时,自动流程将立即继续。', 'info', 1800);
  2768. }
  2769. } catch (err) {
  2770. showToast(err.message, 'error');
  2771. } finally {
  2772. btnAutoRunNow.disabled = false;
  2773. }
  2774. });
  2775. btnAutoCancelSchedule?.addEventListener('click', async () => {
  2776. try {
  2777. btnAutoCancelSchedule.disabled = true;
  2778. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  2779. showToast('已取消倒计时计划。', 'info', 1800);
  2780. } catch (err) {
  2781. showToast(err.message, 'error');
  2782. } finally {
  2783. btnAutoCancelSchedule.disabled = false;
  2784. }
  2785. });
  2786. // Reset
  2787. btnReset.addEventListener('click', async () => {
  2788. const confirmed = await openConfirmModal({
  2789. title: '重置流程',
  2790. message: '确认重置全部步骤和数据吗?',
  2791. confirmLabel: '确认重置',
  2792. confirmVariant: 'btn-danger',
  2793. });
  2794. if (!confirmed) {
  2795. return;
  2796. }
  2797. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  2798. syncLatestState({
  2799. stepStatuses: STEP_DEFAULT_STATUSES,
  2800. currentHotmailAccountId: null,
  2801. currentLuckmailPurchase: null,
  2802. currentLuckmailMailCursor: null,
  2803. email: null,
  2804. });
  2805. syncAutoRunState({
  2806. autoRunning: false,
  2807. autoRunPhase: 'idle',
  2808. autoRunCurrentRun: 0,
  2809. autoRunTotalRuns: 1,
  2810. autoRunAttemptRun: 0,
  2811. scheduledAutoRunAt: null,
  2812. autoRunCountdownAt: null,
  2813. autoRunCountdownTitle: '',
  2814. autoRunCountdownNote: '',
  2815. });
  2816. displayOauthUrl.textContent = '等待中...';
  2817. displayOauthUrl.classList.remove('has-value');
  2818. displayLocalhostUrl.textContent = '等待中...';
  2819. displayLocalhostUrl.classList.remove('has-value');
  2820. inputEmail.value = '';
  2821. displayStatus.textContent = '就绪';
  2822. statusBar.className = 'status-bar';
  2823. logArea.innerHTML = '';
  2824. resetIcloudManager();
  2825. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  2826. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  2827. setDefaultAutoRunButton();
  2828. applyAutoRunStatus(currentAutoRun);
  2829. markSettingsDirty(false);
  2830. updateStopButtonState(false);
  2831. updateButtonStates();
  2832. updateProgressCounter();
  2833. renderHotmailAccounts();
  2834. resetLuckmailManager();
  2835. if (isLuckmailProvider()) {
  2836. queueLuckmailPurchaseRefresh();
  2837. }
  2838. });
  2839. // Clear log
  2840. btnClearLog.addEventListener('click', () => {
  2841. logArea.innerHTML = '';
  2842. });
  2843. // Save settings on change
  2844. inputEmail.addEventListener('change', async () => {
  2845. if (selectMailProvider.value === 'hotmail-api' || isLuckmailProvider()) {
  2846. return;
  2847. }
  2848. const email = inputEmail.value.trim();
  2849. inputEmail.value = email;
  2850. try {
  2851. if (email) {
  2852. const response = await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  2853. if (response?.error) {
  2854. throw new Error(response.error);
  2855. }
  2856. } else {
  2857. await setRuntimeEmailState(null);
  2858. }
  2859. } catch (err) {
  2860. showToast(err.message, 'error');
  2861. }
  2862. });
  2863. inputEmail.addEventListener('input', updateButtonStates);
  2864. inputVpsUrl.addEventListener('input', () => {
  2865. markSettingsDirty(true);
  2866. scheduleSettingsAutoSave();
  2867. });
  2868. inputVpsUrl.addEventListener('blur', () => {
  2869. saveSettings({ silent: true }).catch(() => { });
  2870. });
  2871. inputVpsPassword.addEventListener('input', () => {
  2872. markSettingsDirty(true);
  2873. scheduleSettingsAutoSave();
  2874. });
  2875. inputVpsPassword.addEventListener('blur', () => {
  2876. saveSettings({ silent: true }).catch(() => { });
  2877. });
  2878. [inputHotmailRemoteBaseUrl, inputHotmailLocalBaseUrl].forEach((input) => {
  2879. input?.addEventListener('input', () => {
  2880. markSettingsDirty(true);
  2881. scheduleSettingsAutoSave();
  2882. });
  2883. input?.addEventListener('blur', () => {
  2884. saveSettings({ silent: true }).catch(() => { });
  2885. });
  2886. });
  2887. [inputLuckmailApiKey, inputLuckmailBaseUrl, inputLuckmailDomain].forEach((input) => {
  2888. input?.addEventListener('input', () => {
  2889. markSettingsDirty(true);
  2890. scheduleSettingsAutoSave();
  2891. });
  2892. input?.addEventListener('blur', () => {
  2893. saveSettings({ silent: true }).catch(() => { });
  2894. });
  2895. });
  2896. selectLuckmailEmailType?.addEventListener('change', () => {
  2897. markSettingsDirty(true);
  2898. saveSettings({ silent: true }).catch(() => { });
  2899. });
  2900. inputPassword.addEventListener('input', () => {
  2901. markSettingsDirty(true);
  2902. updateButtonStates();
  2903. scheduleSettingsAutoSave();
  2904. });
  2905. inputPassword.addEventListener('blur', () => {
  2906. saveSettings({ silent: true }).catch(() => { });
  2907. });
  2908. selectMailProvider.addEventListener('change', async () => {
  2909. const previousProvider = latestState?.mailProvider || '';
  2910. const previousMail2925Mode = latestState?.mail2925Mode;
  2911. const nextProvider = selectMailProvider.value;
  2912. updateMailProviderUI();
  2913. const leavingHotmail = previousProvider === 'hotmail-api'
  2914. && nextProvider !== 'hotmail-api'
  2915. && isCurrentEmailManagedByHotmail();
  2916. const leavingLuckmail = previousProvider === LUCKMAIL_PROVIDER
  2917. && nextProvider !== LUCKMAIL_PROVIDER
  2918. && isCurrentEmailManagedByLuckmail();
  2919. const leavingGeneratedAlias = (
  2920. previousProvider !== nextProvider
  2921. || (previousProvider === '2925' && normalizeMail2925Mode(previousMail2925Mode) !== getSelectedMail2925Mode())
  2922. ) && usesGeneratedAliasMailProvider(previousProvider, previousMail2925Mode)
  2923. && isCurrentEmailManagedByGeneratedAlias(previousProvider, latestState, previousMail2925Mode);
  2924. if (leavingHotmail || leavingLuckmail || leavingGeneratedAlias) {
  2925. await clearRegistrationEmail({ silent: true }).catch(() => { });
  2926. }
  2927. if (nextProvider === LUCKMAIL_PROVIDER) {
  2928. queueLuckmailPurchaseRefresh();
  2929. }
  2930. markSettingsDirty(true);
  2931. saveSettings({ silent: true }).catch(() => { });
  2932. });
  2933. mail2925ModeButtons.forEach((button) => {
  2934. button.addEventListener('click', async () => {
  2935. const nextMode = normalizeMail2925Mode(button.dataset.mail2925Mode);
  2936. const previousMode = normalizeMail2925Mode(latestState?.mail2925Mode);
  2937. if (nextMode === getSelectedMail2925Mode()) {
  2938. return;
  2939. }
  2940. setMail2925Mode(nextMode);
  2941. updateMailProviderUI();
  2942. const leavingGeneratedAlias = selectMailProvider.value === '2925'
  2943. && previousMode === MAIL_2925_MODE_PROVIDE
  2944. && nextMode !== MAIL_2925_MODE_PROVIDE
  2945. && isCurrentEmailManagedByGeneratedAlias('2925', latestState, previousMode);
  2946. if (leavingGeneratedAlias) {
  2947. await clearRegistrationEmail({ silent: true }).catch(() => { });
  2948. }
  2949. markSettingsDirty(true);
  2950. saveSettings({ silent: true }).catch(() => { });
  2951. });
  2952. });
  2953. selectEmailGenerator.addEventListener('change', () => {
  2954. updateMailProviderUI();
  2955. clearRegistrationEmail({ silent: true }).catch(() => { });
  2956. markSettingsDirty(true);
  2957. saveSettings({ silent: true }).catch(() => { });
  2958. });
  2959. selectIcloudHostPreference?.addEventListener('change', () => {
  2960. markSettingsDirty(true);
  2961. saveSettings({ silent: true }).catch(() => { });
  2962. if (getSelectedEmailGenerator() === 'icloud') {
  2963. queueIcloudAliasRefresh();
  2964. }
  2965. });
  2966. checkboxAutoDeleteIcloud?.addEventListener('change', () => {
  2967. markSettingsDirty(true);
  2968. saveSettings({ silent: true }).catch(() => { });
  2969. });
  2970. selectPanelMode.addEventListener('change', () => {
  2971. updatePanelModeUI();
  2972. markSettingsDirty(true);
  2973. saveSettings({ silent: true }).catch(() => { });
  2974. });
  2975. selectCfDomain.addEventListener('change', () => {
  2976. if (selectCfDomain.disabled) {
  2977. return;
  2978. }
  2979. markSettingsDirty(true);
  2980. saveSettings({ silent: true }).catch(() => { });
  2981. });
  2982. selectTempEmailDomain.addEventListener('change', () => {
  2983. if (selectTempEmailDomain.disabled) {
  2984. return;
  2985. }
  2986. markSettingsDirty(true);
  2987. saveSettings({ silent: true }).catch(() => { });
  2988. });
  2989. btnCfDomainMode.addEventListener('click', async () => {
  2990. try {
  2991. if (!cloudflareDomainEditMode) {
  2992. setCloudflareDomainEditMode(true, { clearInput: true });
  2993. return;
  2994. }
  2995. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  2996. if (!newDomain) {
  2997. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  2998. inputCfDomain.focus();
  2999. return;
  3000. }
  3001. const { domains } = getCloudflareDomainsFromState();
  3002. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  3003. } catch (err) {
  3004. showToast(err.message, 'error');
  3005. }
  3006. });
  3007. btnTempEmailDomainMode.addEventListener('click', async () => {
  3008. try {
  3009. if (!cloudflareTempEmailDomainEditMode) {
  3010. setCloudflareTempEmailDomainEditMode(true, { clearInput: true });
  3011. return;
  3012. }
  3013. const newDomain = normalizeCloudflareTempEmailDomainValue(inputTempEmailDomain.value);
  3014. if (!newDomain) {
  3015. showToast('请输入有效的 Cloudflare Temp Email 域名。', 'warn');
  3016. inputTempEmailDomain.focus();
  3017. return;
  3018. }
  3019. const { domains } = getCloudflareTempEmailDomainsFromState();
  3020. await saveCloudflareTempEmailDomainSettings([...domains, newDomain], newDomain);
  3021. } catch (err) {
  3022. showToast(err.message, 'error');
  3023. }
  3024. });
  3025. inputCfDomain.addEventListener('keydown', (event) => {
  3026. if (event.key === 'Enter') {
  3027. event.preventDefault();
  3028. btnCfDomainMode.click();
  3029. }
  3030. });
  3031. inputTempEmailDomain.addEventListener('keydown', (event) => {
  3032. if (event.key === 'Enter') {
  3033. event.preventDefault();
  3034. btnTempEmailDomainMode.click();
  3035. }
  3036. });
  3037. inputSub2ApiUrl.addEventListener('input', () => {
  3038. markSettingsDirty(true);
  3039. scheduleSettingsAutoSave();
  3040. });
  3041. inputSub2ApiUrl.addEventListener('blur', () => {
  3042. saveSettings({ silent: true }).catch(() => { });
  3043. });
  3044. inputSub2ApiEmail.addEventListener('input', () => {
  3045. markSettingsDirty(true);
  3046. scheduleSettingsAutoSave();
  3047. });
  3048. inputSub2ApiEmail.addEventListener('blur', () => {
  3049. saveSettings({ silent: true }).catch(() => { });
  3050. });
  3051. inputSub2ApiPassword.addEventListener('input', () => {
  3052. markSettingsDirty(true);
  3053. scheduleSettingsAutoSave();
  3054. });
  3055. inputSub2ApiPassword.addEventListener('blur', () => {
  3056. saveSettings({ silent: true }).catch(() => { });
  3057. });
  3058. inputSub2ApiGroup.addEventListener('input', () => {
  3059. markSettingsDirty(true);
  3060. scheduleSettingsAutoSave();
  3061. });
  3062. inputSub2ApiGroup.addEventListener('blur', () => {
  3063. saveSettings({ silent: true }).catch(() => { });
  3064. });
  3065. inputEmailPrefix.addEventListener('input', () => {
  3066. maybeClearGeneratedAliasAfterEmailPrefixChange().catch(() => { });
  3067. markSettingsDirty(true);
  3068. scheduleSettingsAutoSave();
  3069. });
  3070. inputEmailPrefix.addEventListener('blur', () => {
  3071. maybeClearGeneratedAliasAfterEmailPrefixChange().catch(() => {});
  3072. saveSettings({ silent: true }).catch(() => {});
  3073. });
  3074. inputInbucketMailbox.addEventListener('input', () => {
  3075. markSettingsDirty(true);
  3076. scheduleSettingsAutoSave();
  3077. });
  3078. inputInbucketMailbox.addEventListener('blur', () => {
  3079. saveSettings({ silent: true }).catch(() => { });
  3080. });
  3081. inputInbucketHost.addEventListener('input', () => {
  3082. markSettingsDirty(true);
  3083. scheduleSettingsAutoSave();
  3084. });
  3085. inputInbucketHost.addEventListener('blur', () => {
  3086. saveSettings({ silent: true }).catch(() => { });
  3087. });
  3088. inputRunCount.addEventListener('input', () => {
  3089. updateFallbackThreadIntervalInputState();
  3090. });
  3091. inputRunCount.addEventListener('blur', () => {
  3092. inputRunCount.value = String(getRunCountValue());
  3093. updateFallbackThreadIntervalInputState();
  3094. });
  3095. inputAutoSkipFailures.addEventListener('change', async () => {
  3096. if (inputAutoSkipFailures.checked && !isAutoSkipFailuresPromptDismissed()) {
  3097. const result = await openAutoSkipFailuresConfirmModal();
  3098. if (!result.confirmed) {
  3099. inputAutoSkipFailures.checked = false;
  3100. updateFallbackThreadIntervalInputState();
  3101. return;
  3102. }
  3103. if (result.dismissPrompt) {
  3104. setAutoSkipFailuresPromptDismissed(true);
  3105. }
  3106. }
  3107. updateFallbackThreadIntervalInputState();
  3108. markSettingsDirty(true);
  3109. saveSettings({ silent: true }).catch(() => { });
  3110. });
  3111. inputTempEmailBaseUrl.addEventListener('input', () => {
  3112. markSettingsDirty(true);
  3113. scheduleSettingsAutoSave();
  3114. });
  3115. inputTempEmailBaseUrl.addEventListener('blur', () => {
  3116. inputTempEmailBaseUrl.value = normalizeCloudflareTempEmailBaseUrlValue(inputTempEmailBaseUrl.value);
  3117. saveSettings({ silent: true }).catch(() => { });
  3118. });
  3119. inputTempEmailAdminAuth.addEventListener('input', () => {
  3120. markSettingsDirty(true);
  3121. scheduleSettingsAutoSave();
  3122. });
  3123. inputTempEmailAdminAuth.addEventListener('blur', () => {
  3124. saveSettings({ silent: true }).catch(() => { });
  3125. });
  3126. inputTempEmailCustomAuth.addEventListener('input', () => {
  3127. markSettingsDirty(true);
  3128. scheduleSettingsAutoSave();
  3129. });
  3130. inputTempEmailCustomAuth.addEventListener('blur', () => {
  3131. saveSettings({ silent: true }).catch(() => { });
  3132. });
  3133. inputTempEmailReceiveMailbox.addEventListener('input', () => {
  3134. markSettingsDirty(true);
  3135. scheduleSettingsAutoSave();
  3136. });
  3137. inputTempEmailReceiveMailbox.addEventListener('blur', () => {
  3138. inputTempEmailReceiveMailbox.value = normalizeCloudflareTempEmailReceiveMailboxValue(inputTempEmailReceiveMailbox.value);
  3139. saveSettings({ silent: true }).catch(() => { });
  3140. });
  3141. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('input', () => {
  3142. markSettingsDirty(true);
  3143. scheduleSettingsAutoSave();
  3144. });
  3145. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('blur', () => {
  3146. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  3147. normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value)
  3148. );
  3149. saveSettings({ silent: true }).catch(() => { });
  3150. });
  3151. inputAutoDelayEnabled.addEventListener('change', () => {
  3152. updateAutoDelayInputState();
  3153. markSettingsDirty(true);
  3154. saveSettings({ silent: true }).catch(() => { });
  3155. });
  3156. inputAutoDelayMinutes.addEventListener('input', () => {
  3157. markSettingsDirty(true);
  3158. scheduleSettingsAutoSave();
  3159. });
  3160. inputAutoDelayMinutes.addEventListener('blur', () => {
  3161. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  3162. saveSettings({ silent: true }).catch(() => { });
  3163. });
  3164. function syncAutoStepDelayInputs() {
  3165. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(inputAutoStepDelaySeconds.value);
  3166. }
  3167. inputAutoStepDelaySeconds.addEventListener('input', () => {
  3168. markSettingsDirty(true);
  3169. scheduleSettingsAutoSave();
  3170. });
  3171. inputAutoStepDelaySeconds.addEventListener('blur', () => {
  3172. syncAutoStepDelayInputs();
  3173. saveSettings({ silent: true }).catch(() => { });
  3174. });
  3175. // ============================================================
  3176. // Listen for Background broadcasts
  3177. // ============================================================
  3178. chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  3179. switch (message.type) {
  3180. case 'REQUEST_CUSTOM_VERIFICATION_BYPASS_CONFIRMATION': {
  3181. (async () => {
  3182. const step = Number(message.payload?.step);
  3183. const promptCopy = getCustomVerificationPromptCopy(step);
  3184. const confirmed = await openConfirmModal({
  3185. title: promptCopy.title,
  3186. message: promptCopy.message,
  3187. confirmLabel: '确认跳过',
  3188. confirmVariant: 'btn-danger',
  3189. alert: promptCopy.alert,
  3190. });
  3191. sendResponse({ confirmed });
  3192. })().catch((err) => {
  3193. sendResponse({ error: err.message });
  3194. });
  3195. return true;
  3196. }
  3197. case 'LOG_ENTRY':
  3198. appendLog(message.payload);
  3199. if (message.payload.level === 'error') {
  3200. showToast(message.payload.message, 'error');
  3201. }
  3202. break;
  3203. case 'STEP_STATUS_CHANGED': {
  3204. const { step, status } = message.payload;
  3205. updateStepUI(step, status);
  3206. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  3207. syncLatestState(state);
  3208. syncAutoRunState(state);
  3209. updateStatusDisplay(latestState);
  3210. updateButtonStates();
  3211. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  3212. syncPasswordField(state);
  3213. if (state.oauthUrl) {
  3214. displayOauthUrl.textContent = state.oauthUrl;
  3215. displayOauthUrl.classList.add('has-value');
  3216. }
  3217. if (state.localhostUrl) {
  3218. displayLocalhostUrl.textContent = state.localhostUrl;
  3219. displayLocalhostUrl.classList.add('has-value');
  3220. }
  3221. }
  3222. }
  3223. ).catch(() => { });
  3224. break;
  3225. }
  3226. case 'AUTO_RUN_RESET': {
  3227. // Full UI reset for next run
  3228. syncLatestState({
  3229. oauthUrl: null,
  3230. localhostUrl: null,
  3231. email: null,
  3232. password: null,
  3233. stepStatuses: STEP_DEFAULT_STATUSES,
  3234. logs: [],
  3235. scheduledAutoRunAt: null,
  3236. autoRunCountdownAt: null,
  3237. autoRunCountdownTitle: '',
  3238. autoRunCountdownNote: '',
  3239. });
  3240. displayOauthUrl.textContent = '等待中...';
  3241. displayOauthUrl.classList.remove('has-value');
  3242. displayLocalhostUrl.textContent = '等待中...';
  3243. displayLocalhostUrl.classList.remove('has-value');
  3244. inputEmail.value = '';
  3245. displayStatus.textContent = '就绪';
  3246. statusBar.className = 'status-bar';
  3247. logArea.innerHTML = '';
  3248. resetIcloudManager();
  3249. resetLuckmailManager();
  3250. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  3251. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  3252. syncAutoRunState({
  3253. autoRunning: false,
  3254. autoRunPhase: 'idle',
  3255. autoRunCurrentRun: 0,
  3256. autoRunTotalRuns: 1,
  3257. autoRunAttemptRun: 0,
  3258. scheduledAutoRunAt: null,
  3259. autoRunCountdownAt: null,
  3260. autoRunCountdownTitle: '',
  3261. autoRunCountdownNote: '',
  3262. });
  3263. applyAutoRunStatus(currentAutoRun);
  3264. updateProgressCounter();
  3265. updateButtonStates();
  3266. renderHotmailAccounts();
  3267. if (isLuckmailProvider()) {
  3268. queueLuckmailPurchaseRefresh();
  3269. }
  3270. break;
  3271. }
  3272. case 'DATA_UPDATED': {
  3273. syncLatestState(message.payload);
  3274. if (message.payload.email !== undefined) {
  3275. inputEmail.value = message.payload.email || '';
  3276. }
  3277. if (message.payload.password !== undefined) {
  3278. inputPassword.value = message.payload.password || '';
  3279. }
  3280. if (message.payload.localCpaStep9Mode !== undefined) {
  3281. setLocalCpaStep9Mode(message.payload.localCpaStep9Mode);
  3282. }
  3283. if (message.payload.cpaCallbackMode !== undefined) {
  3284. setCpaCallbackMode(message.payload.cpaCallbackMode);
  3285. }
  3286. if (message.payload.oauthUrl !== undefined) {
  3287. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  3288. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  3289. }
  3290. if (message.payload.localhostUrl !== undefined) {
  3291. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  3292. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  3293. }
  3294. if (message.payload.cloudflareTempEmailBaseUrl !== undefined) {
  3295. inputTempEmailBaseUrl.value = message.payload.cloudflareTempEmailBaseUrl || '';
  3296. }
  3297. if (message.payload.cloudflareTempEmailAdminAuth !== undefined) {
  3298. inputTempEmailAdminAuth.value = message.payload.cloudflareTempEmailAdminAuth || '';
  3299. }
  3300. if (message.payload.cloudflareTempEmailCustomAuth !== undefined) {
  3301. inputTempEmailCustomAuth.value = message.payload.cloudflareTempEmailCustomAuth || '';
  3302. }
  3303. if (message.payload.cloudflareTempEmailReceiveMailbox !== undefined) {
  3304. inputTempEmailReceiveMailbox.value = message.payload.cloudflareTempEmailReceiveMailbox || '';
  3305. }
  3306. if (message.payload.cloudflareTempEmailDomain !== undefined || message.payload.cloudflareTempEmailDomains !== undefined) {
  3307. renderCloudflareTempEmailDomainOptions(message.payload.cloudflareTempEmailDomain || latestState?.cloudflareTempEmailDomain || '');
  3308. }
  3309. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  3310. renderHotmailAccounts();
  3311. if (selectMailProvider.value === 'hotmail-api') {
  3312. inputEmail.value = getCurrentHotmailEmail();
  3313. }
  3314. }
  3315. if (message.payload.luckmailApiKey !== undefined) {
  3316. inputLuckmailApiKey.value = message.payload.luckmailApiKey || '';
  3317. }
  3318. if (message.payload.luckmailBaseUrl !== undefined) {
  3319. inputLuckmailBaseUrl.value = normalizeLuckmailBaseUrl(message.payload.luckmailBaseUrl);
  3320. }
  3321. if (message.payload.luckmailEmailType !== undefined) {
  3322. selectLuckmailEmailType.value = normalizeLuckmailEmailType(message.payload.luckmailEmailType);
  3323. }
  3324. if (message.payload.luckmailDomain !== undefined) {
  3325. inputLuckmailDomain.value = message.payload.luckmailDomain || '';
  3326. }
  3327. if (message.payload.luckmailUsedPurchases !== undefined && isLuckmailProvider()) {
  3328. queueLuckmailPurchaseRefresh();
  3329. }
  3330. if (message.payload.currentLuckmailPurchase !== undefined && isLuckmailProvider()) {
  3331. inputEmail.value = getCurrentLuckmailEmail();
  3332. queueLuckmailPurchaseRefresh();
  3333. }
  3334. if (message.payload.autoDeleteUsedIcloudAlias !== undefined && checkboxAutoDeleteIcloud) {
  3335. checkboxAutoDeleteIcloud.checked = Boolean(message.payload.autoDeleteUsedIcloudAlias);
  3336. }
  3337. if (message.payload.icloudHostPreference !== undefined && selectIcloudHostPreference) {
  3338. const hostPreference = String(message.payload.icloudHostPreference || '').trim().toLowerCase();
  3339. selectIcloudHostPreference.value = hostPreference === 'icloud.com'
  3340. ? 'icloud.com'
  3341. : (hostPreference === 'icloud.com.cn' ? 'icloud.com.cn' : 'auto');
  3342. }
  3343. if (message.payload.autoRunSkipFailures !== undefined) {
  3344. inputAutoSkipFailures.checked = Boolean(message.payload.autoRunSkipFailures);
  3345. updateFallbackThreadIntervalInputState();
  3346. }
  3347. if (message.payload.autoRunDelayEnabled !== undefined) {
  3348. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  3349. updateAutoDelayInputState();
  3350. }
  3351. if (message.payload.autoRunDelayMinutes !== undefined) {
  3352. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  3353. }
  3354. if (message.payload.autoRunFallbackThreadIntervalMinutes !== undefined) {
  3355. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  3356. normalizeAutoRunThreadIntervalMinutes(message.payload.autoRunFallbackThreadIntervalMinutes)
  3357. );
  3358. updateFallbackThreadIntervalInputState();
  3359. }
  3360. if (message.payload.autoStepDelaySeconds !== undefined) {
  3361. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(message.payload.autoStepDelaySeconds);
  3362. }
  3363. break;
  3364. }
  3365. case 'ICLOUD_LOGIN_REQUIRED': {
  3366. const loginMessage = '需要登录 iCloud,我已经为你打开登录页。';
  3367. showToast(loginMessage, 'warn', 5000);
  3368. if (icloudSummary) {
  3369. icloudSummary.textContent = loginMessage;
  3370. }
  3371. showIcloudLoginHelp(message.payload || {});
  3372. break;
  3373. }
  3374. case 'ICLOUD_ALIASES_CHANGED': {
  3375. queueIcloudAliasRefresh();
  3376. break;
  3377. }
  3378. case 'AUTO_RUN_STATUS': {
  3379. syncLatestState({
  3380. autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying', 'waiting_interval'].includes(message.payload.phase),
  3381. autoRunPhase: message.payload.phase,
  3382. autoRunCurrentRun: message.payload.currentRun,
  3383. autoRunTotalRuns: message.payload.totalRuns,
  3384. autoRunAttemptRun: message.payload.attemptRun,
  3385. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  3386. autoRunCountdownAt: message.payload.countdownAt ?? null,
  3387. autoRunCountdownTitle: message.payload.countdownTitle ?? '',
  3388. autoRunCountdownNote: message.payload.countdownNote ?? '',
  3389. });
  3390. applyAutoRunStatus(message.payload);
  3391. updateStatusDisplay(latestState);
  3392. updateButtonStates();
  3393. break;
  3394. }
  3395. }
  3396. });
  3397. // ============================================================
  3398. // Theme Toggle
  3399. // ============================================================
  3400. const btnTheme = document.getElementById('btn-theme');
  3401. function setTheme(theme) {
  3402. document.documentElement.setAttribute('data-theme', theme);
  3403. localStorage.setItem('multipage-theme', theme);
  3404. }
  3405. function initTheme() {
  3406. const saved = localStorage.getItem('multipage-theme');
  3407. if (saved) {
  3408. setTheme(saved);
  3409. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  3410. setTheme('dark');
  3411. }
  3412. }
  3413. btnTheme.addEventListener('click', () => {
  3414. const current = document.documentElement.getAttribute('data-theme');
  3415. setTheme(current === 'dark' ? 'light' : 'dark');
  3416. });
  3417. document.addEventListener('click', (event) => {
  3418. if (!configMenuOpen) {
  3419. return;
  3420. }
  3421. if (configMenuShell?.contains(event.target)) {
  3422. return;
  3423. }
  3424. closeConfigMenu();
  3425. });
  3426. document.addEventListener('keydown', (event) => {
  3427. if (event.key === 'Escape' && configMenuOpen) {
  3428. closeConfigMenu();
  3429. }
  3430. });
  3431. // ============================================================
  3432. // Init
  3433. // ============================================================
  3434. initializeManualStepActions();
  3435. initTheme();
  3436. initHotmailListExpandedState();
  3437. updateSaveButtonState();
  3438. updateConfigMenuControls();
  3439. setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
  3440. setCpaCallbackMode(DEFAULT_CPA_CALLBACK_MODE);
  3441. setMail2925Mode(DEFAULT_MAIL_2925_MODE);
  3442. initializeReleaseInfo().catch((err) => {
  3443. console.error('Failed to initialize release info:', err);
  3444. });
  3445. restoreState().then(() => {
  3446. syncPasswordToggleLabel();
  3447. syncVpsUrlToggleLabel();
  3448. syncVpsPasswordToggleLabel();
  3449. updatePanelModeUI();
  3450. updateButtonStates();
  3451. updateStatusDisplay(latestState);
  3452. });