sidepanel.js 150 KB

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