sidepanel.js 149 KB

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