sidepanel.js 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222
  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 (currentAutoRun.phase !== 'waiting_interval') {
  951. return null;
  952. }
  953. if (!Number.isFinite(currentAutoRun.countdownAt)) {
  954. return null;
  955. }
  956. return {
  957. at: currentAutoRun.countdownAt,
  958. title: currentAutoRun.countdownTitle || '等待中',
  959. note: currentAutoRun.countdownNote || '',
  960. tone: 'running',
  961. };
  962. }
  963. function renderScheduledAutoRunInfo() {
  964. if (!autoScheduleBar) {
  965. return;
  966. }
  967. const countdown = getActiveAutoRunCountdown();
  968. if (!countdown) {
  969. autoScheduleBar.style.display = 'none';
  970. return;
  971. }
  972. const remainingMs = countdown.at - Date.now();
  973. autoScheduleBar.style.display = 'flex';
  974. if (btnAutoRunNow) {
  975. btnAutoRunNow.hidden = false;
  976. btnAutoRunNow.textContent = currentAutoRun.phase === 'waiting_interval' ? '立即继续' : '立即开始';
  977. }
  978. if (btnAutoCancelSchedule) {
  979. btnAutoCancelSchedule.hidden = true;
  980. }
  981. autoScheduleTitle.textContent = countdown.title;
  982. autoScheduleMeta.textContent = remainingMs > 0
  983. ? `${countdown.note ? `${countdown.note},` : ''}剩余 ${formatCountdown(remainingMs)}`
  984. : '倒计时即将结束,正在准备继续...';
  985. return;
  986. }
  987. function syncScheduledCountdownTicker() {
  988. renderScheduledAutoRunInfo();
  989. if (getActiveAutoRunCountdown()) {
  990. if (scheduledCountdownTimer) {
  991. return;
  992. }
  993. scheduledCountdownTimer = setInterval(() => {
  994. renderScheduledAutoRunInfo();
  995. updateStatusDisplay(latestState);
  996. }, 1000);
  997. return;
  998. }
  999. stopScheduledCountdownTicker();
  1000. return;
  1001. }
  1002. function setDefaultAutoRunButton() {
  1003. btnAutoRun.disabled = false;
  1004. inputRunCount.disabled = false;
  1005. 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> 自动';
  1006. }
  1007. function normalizeCloudflareDomainValue(value = '') {
  1008. let normalized = String(value || '').trim().toLowerCase();
  1009. if (!normalized) return '';
  1010. normalized = normalized.replace(/^@+/, '');
  1011. normalized = normalized.replace(/^https?:\/\//, '');
  1012. normalized = normalized.replace(/\/.*$/, '');
  1013. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) {
  1014. return '';
  1015. }
  1016. return normalized;
  1017. }
  1018. function normalizeCloudflareDomains(values = []) {
  1019. const seen = new Set();
  1020. const domains = [];
  1021. for (const value of Array.isArray(values) ? values : []) {
  1022. const normalized = normalizeCloudflareDomainValue(value);
  1023. if (!normalized || seen.has(normalized)) continue;
  1024. seen.add(normalized);
  1025. domains.push(normalized);
  1026. }
  1027. return domains;
  1028. }
  1029. function normalizeCloudflareTempEmailBaseUrlValue(value = '') {
  1030. const raw = String(value || '').trim();
  1031. if (!raw) return '';
  1032. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(raw) ? raw : `https://${raw}`;
  1033. try {
  1034. const parsed = new URL(candidate);
  1035. parsed.hash = '';
  1036. parsed.search = '';
  1037. const pathname = parsed.pathname === '/' ? '' : parsed.pathname.replace(/\/+$/, '');
  1038. return `${parsed.origin}${pathname}`;
  1039. } catch {
  1040. return '';
  1041. }
  1042. }
  1043. function normalizeCloudflareTempEmailReceiveMailboxValue(value = '') {
  1044. const normalized = String(value || '').trim().toLowerCase();
  1045. if (!normalized) return '';
  1046. return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalized) ? normalized : '';
  1047. }
  1048. function normalizeCloudflareTempEmailDomainValue(value = '') {
  1049. return normalizeCloudflareDomainValue(value);
  1050. }
  1051. function normalizeCloudflareTempEmailDomains(values = []) {
  1052. const seen = new Set();
  1053. const domains = [];
  1054. for (const value of Array.isArray(values) ? values : []) {
  1055. const normalized = normalizeCloudflareTempEmailDomainValue(value);
  1056. if (!normalized || seen.has(normalized)) continue;
  1057. seen.add(normalized);
  1058. domains.push(normalized);
  1059. }
  1060. return domains;
  1061. }
  1062. function getCloudflareDomainsFromState() {
  1063. const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []);
  1064. const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || '');
  1065. if (activeDomain && !domains.includes(activeDomain)) {
  1066. domains.unshift(activeDomain);
  1067. }
  1068. return { domains, activeDomain: activeDomain || domains[0] || '' };
  1069. }
  1070. function getCloudflareTempEmailDomainsFromState() {
  1071. const domains = normalizeCloudflareTempEmailDomains(latestState?.cloudflareTempEmailDomains || []);
  1072. const activeDomain = normalizeCloudflareTempEmailDomainValue(latestState?.cloudflareTempEmailDomain || '');
  1073. if (activeDomain && !domains.includes(activeDomain)) {
  1074. domains.unshift(activeDomain);
  1075. }
  1076. return { domains, activeDomain: activeDomain || domains[0] || '' };
  1077. }
  1078. function renderCloudflareDomainOptions(preferredDomain = '') {
  1079. const preferred = normalizeCloudflareDomainValue(preferredDomain);
  1080. const { domains, activeDomain } = getCloudflareDomainsFromState();
  1081. const selected = preferred || activeDomain;
  1082. selectCfDomain.innerHTML = '';
  1083. if (domains.length === 0) {
  1084. const option = document.createElement('option');
  1085. option.value = '';
  1086. option.textContent = '请先添加域名';
  1087. selectCfDomain.appendChild(option);
  1088. selectCfDomain.disabled = true;
  1089. selectCfDomain.value = '';
  1090. return;
  1091. }
  1092. for (const domain of domains) {
  1093. const option = document.createElement('option');
  1094. option.value = domain;
  1095. option.textContent = domain;
  1096. selectCfDomain.appendChild(option);
  1097. }
  1098. selectCfDomain.disabled = false;
  1099. selectCfDomain.value = domains.includes(selected) ? selected : domains[0];
  1100. }
  1101. function renderCloudflareTempEmailDomainOptions(preferredDomain = '') {
  1102. const preferred = normalizeCloudflareTempEmailDomainValue(preferredDomain);
  1103. const { domains, activeDomain } = getCloudflareTempEmailDomainsFromState();
  1104. const selected = preferred || activeDomain;
  1105. selectTempEmailDomain.innerHTML = '';
  1106. if (domains.length === 0) {
  1107. const option = document.createElement('option');
  1108. option.value = '';
  1109. option.textContent = '请先添加域名';
  1110. selectTempEmailDomain.appendChild(option);
  1111. selectTempEmailDomain.disabled = true;
  1112. selectTempEmailDomain.value = '';
  1113. return;
  1114. }
  1115. for (const domain of domains) {
  1116. const option = document.createElement('option');
  1117. option.value = domain;
  1118. option.textContent = domain;
  1119. selectTempEmailDomain.appendChild(option);
  1120. }
  1121. selectTempEmailDomain.disabled = false;
  1122. selectTempEmailDomain.value = domains.includes(selected) ? selected : domains[0];
  1123. }
  1124. function setCloudflareDomainEditMode(editing, options = {}) {
  1125. const { clearInput = false } = options;
  1126. cloudflareDomainEditMode = Boolean(editing);
  1127. selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : '';
  1128. inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none';
  1129. btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加';
  1130. if (cloudflareDomainEditMode) {
  1131. if (clearInput) {
  1132. inputCfDomain.value = '';
  1133. }
  1134. inputCfDomain.focus();
  1135. } else if (clearInput) {
  1136. inputCfDomain.value = '';
  1137. }
  1138. }
  1139. function setCloudflareTempEmailDomainEditMode(editing, options = {}) {
  1140. const { clearInput = false } = options;
  1141. cloudflareTempEmailDomainEditMode = Boolean(editing);
  1142. selectTempEmailDomain.style.display = cloudflareTempEmailDomainEditMode ? 'none' : '';
  1143. inputTempEmailDomain.style.display = cloudflareTempEmailDomainEditMode ? '' : 'none';
  1144. btnTempEmailDomainMode.textContent = cloudflareTempEmailDomainEditMode ? '保存' : '添加';
  1145. if (cloudflareTempEmailDomainEditMode) {
  1146. if (clearInput) {
  1147. inputTempEmailDomain.value = '';
  1148. }
  1149. inputTempEmailDomain.focus();
  1150. } else if (clearInput) {
  1151. inputTempEmailDomain.value = '';
  1152. }
  1153. }
  1154. function collectSettingsPayload() {
  1155. const { domains, activeDomain } = getCloudflareDomainsFromState();
  1156. const selectedCloudflareDomain = normalizeCloudflareDomainValue(
  1157. !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain
  1158. ) || activeDomain;
  1159. const { domains: tempEmailDomains, activeDomain: tempEmailActiveDomain } = getCloudflareTempEmailDomainsFromState();
  1160. const selectedCloudflareTempEmailDomain = normalizeCloudflareTempEmailDomainValue(
  1161. !cloudflareTempEmailDomainEditMode ? selectTempEmailDomain.value : tempEmailActiveDomain
  1162. ) || tempEmailActiveDomain;
  1163. return {
  1164. panelMode: selectPanelMode.value,
  1165. vpsUrl: inputVpsUrl.value.trim(),
  1166. vpsPassword: inputVpsPassword.value,
  1167. localCpaStep9Mode: getSelectedLocalCpaStep9Mode(),
  1168. cpaCallbackMode: getSelectedCpaCallbackMode(),
  1169. sub2apiUrl: inputSub2ApiUrl.value.trim(),
  1170. sub2apiEmail: inputSub2ApiEmail.value.trim(),
  1171. sub2apiPassword: inputSub2ApiPassword.value,
  1172. sub2apiGroupName: inputSub2ApiGroup.value.trim(),
  1173. customPassword: inputPassword.value,
  1174. mailProvider: selectMailProvider.value,
  1175. mail2925Mode: getSelectedMail2925Mode(),
  1176. emailGenerator: selectEmailGenerator.value,
  1177. autoDeleteUsedIcloudAlias: checkboxAutoDeleteIcloud?.checked,
  1178. icloudHostPreference: selectIcloudHostPreference?.value || 'auto',
  1179. accountRunHistoryTextEnabled: Boolean(inputAccountRunHistoryTextEnabled?.checked),
  1180. accountRunHistoryHelperBaseUrl: normalizeAccountRunHistoryHelperBaseUrlValue(inputAccountRunHistoryHelperBaseUrl?.value),
  1181. ...buildManagedAliasBaseEmailPayload(),
  1182. inbucketHost: inputInbucketHost.value.trim(),
  1183. inbucketMailbox: inputInbucketMailbox.value.trim(),
  1184. hotmailServiceMode: getSelectedHotmailServiceMode(),
  1185. hotmailRemoteBaseUrl: inputHotmailRemoteBaseUrl.value.trim(),
  1186. hotmailLocalBaseUrl: inputHotmailLocalBaseUrl.value.trim(),
  1187. luckmailApiKey: inputLuckmailApiKey.value,
  1188. luckmailBaseUrl: normalizeLuckmailBaseUrl(inputLuckmailBaseUrl.value),
  1189. luckmailEmailType: normalizeLuckmailEmailType(selectLuckmailEmailType.value),
  1190. luckmailDomain: inputLuckmailDomain.value.trim(),
  1191. cloudflareDomain: selectedCloudflareDomain,
  1192. cloudflareDomains: domains,
  1193. cloudflareTempEmailBaseUrl: normalizeCloudflareTempEmailBaseUrlValue(inputTempEmailBaseUrl.value),
  1194. cloudflareTempEmailAdminAuth: inputTempEmailAdminAuth.value,
  1195. cloudflareTempEmailCustomAuth: inputTempEmailCustomAuth.value,
  1196. cloudflareTempEmailReceiveMailbox: normalizeCloudflareTempEmailReceiveMailboxValue(inputTempEmailReceiveMailbox.value),
  1197. cloudflareTempEmailDomain: selectedCloudflareTempEmailDomain,
  1198. cloudflareTempEmailDomains: tempEmailDomains,
  1199. autoRunSkipFailures: inputAutoSkipFailures.checked,
  1200. autoRunFallbackThreadIntervalMinutes: normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value),
  1201. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  1202. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  1203. autoStepDelaySeconds: normalizeAutoStepDelaySeconds(inputAutoStepDelaySeconds.value),
  1204. verificationResendCount: normalizeVerificationResendCount(
  1205. inputVerificationResendCount?.value,
  1206. DEFAULT_VERIFICATION_RESEND_COUNT
  1207. ),
  1208. };
  1209. }
  1210. function normalizeLocalCpaStep9Mode(value = '') {
  1211. return String(value || '').trim().toLowerCase() === 'bypass'
  1212. ? 'bypass'
  1213. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  1214. }
  1215. function normalizeCpaCallbackMode(value = '') {
  1216. const normalized = String(value || '').trim().toLowerCase();
  1217. if (normalized === 'step7' || normalized === 'step6') {
  1218. return 'step7';
  1219. }
  1220. if (normalized === 'step9' || normalized === 'step8') {
  1221. return 'step9';
  1222. }
  1223. return DEFAULT_CPA_CALLBACK_MODE;
  1224. }
  1225. function normalizeMail2925Mode(value = '') {
  1226. return String(value || '').trim().toLowerCase() === MAIL_2925_MODE_RECEIVE
  1227. ? MAIL_2925_MODE_RECEIVE
  1228. : DEFAULT_MAIL_2925_MODE;
  1229. }
  1230. function normalizeHotmailServiceMode(value = '') {
  1231. if (typeof normalizeHotmailServiceModeFromUtils === 'function') {
  1232. return normalizeHotmailServiceModeFromUtils(value);
  1233. }
  1234. return String(value || '').trim().toLowerCase() === HOTMAIL_SERVICE_MODE_REMOTE
  1235. ? HOTMAIL_SERVICE_MODE_REMOTE
  1236. : HOTMAIL_SERVICE_MODE_LOCAL;
  1237. }
  1238. function normalizeAccountRunHistoryHelperBaseUrlValue(value = '') {
  1239. const trimmed = String(value || '').trim();
  1240. if (!trimmed) {
  1241. return DEFAULT_ACCOUNT_RUN_HISTORY_HELPER_BASE_URL;
  1242. }
  1243. try {
  1244. const parsed = new URL(trimmed);
  1245. if (!['http:', 'https:'].includes(parsed.protocol)) {
  1246. return DEFAULT_ACCOUNT_RUN_HISTORY_HELPER_BASE_URL;
  1247. }
  1248. if (parsed.pathname === '/append-account-log' || parsed.pathname === '/sync-account-run-records') {
  1249. parsed.pathname = '';
  1250. parsed.search = '';
  1251. parsed.hash = '';
  1252. }
  1253. return parsed.toString().replace(/\/$/, '');
  1254. } catch {
  1255. return DEFAULT_ACCOUNT_RUN_HISTORY_HELPER_BASE_URL;
  1256. }
  1257. }
  1258. function getSelectedLocalCpaStep9Mode() {
  1259. const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active'));
  1260. return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode);
  1261. }
  1262. function setLocalCpaStep9Mode(mode) {
  1263. const resolvedMode = normalizeLocalCpaStep9Mode(mode);
  1264. localCpaStep9ModeButtons.forEach((button) => {
  1265. const active = button.dataset.localCpaStep9Mode === resolvedMode;
  1266. button.classList.toggle('is-active', active);
  1267. button.setAttribute('aria-pressed', String(active));
  1268. });
  1269. }
  1270. function getSelectedCpaCallbackMode() {
  1271. const activeButton = cpaCallbackModeButtons.find((button) => button.classList.contains('is-active'));
  1272. return normalizeCpaCallbackMode(activeButton?.dataset.cpaCallbackMode);
  1273. }
  1274. function setCpaCallbackMode(mode) {
  1275. const resolvedMode = normalizeCpaCallbackMode(mode);
  1276. cpaCallbackModeButtons.forEach((button) => {
  1277. const active = button.dataset.cpaCallbackMode === resolvedMode;
  1278. button.classList.toggle('is-active', active);
  1279. button.setAttribute('aria-pressed', String(active));
  1280. });
  1281. }
  1282. function getSelectedMail2925Mode() {
  1283. const activeButton = mail2925ModeButtons.find((button) => button.classList.contains('is-active'));
  1284. return normalizeMail2925Mode(activeButton?.dataset.mail2925Mode);
  1285. }
  1286. function setMail2925Mode(mode) {
  1287. const resolvedMode = normalizeMail2925Mode(mode);
  1288. mail2925ModeButtons.forEach((button) => {
  1289. const active = button.dataset.mail2925Mode === resolvedMode;
  1290. button.classList.toggle('is-active', active);
  1291. button.setAttribute('aria-pressed', String(active));
  1292. });
  1293. }
  1294. function getSelectedHotmailServiceMode() {
  1295. const activeButton = hotmailServiceModeButtons.find((button) => button.classList.contains('is-active'));
  1296. return normalizeHotmailServiceMode(activeButton?.dataset.hotmailServiceMode);
  1297. }
  1298. function setHotmailServiceMode(mode) {
  1299. const resolvedMode = normalizeHotmailServiceMode(mode);
  1300. hotmailServiceModeButtons.forEach((button) => {
  1301. const active = button.dataset.hotmailServiceMode === resolvedMode;
  1302. button.disabled = false;
  1303. button.setAttribute('aria-disabled', 'false');
  1304. button.classList.toggle('is-active', active);
  1305. button.setAttribute('aria-pressed', String(active));
  1306. });
  1307. }
  1308. function updateAccountRunHistorySettingsUI() {
  1309. if (!rowAccountRunHistoryHelperBaseUrl || !inputAccountRunHistoryTextEnabled) {
  1310. return;
  1311. }
  1312. rowAccountRunHistoryHelperBaseUrl.style.display = inputAccountRunHistoryTextEnabled.checked ? '' : 'none';
  1313. }
  1314. function setSettingsCardLocked(locked) {
  1315. if (!settingsCard) {
  1316. return;
  1317. }
  1318. settingsCard.classList.toggle('is-locked', locked);
  1319. settingsCard.toggleAttribute('inert', locked);
  1320. }
  1321. async function setRuntimeEmailState(email) {
  1322. const normalizedEmail = String(email || '').trim() || null;
  1323. const response = await chrome.runtime.sendMessage({
  1324. type: 'SET_EMAIL_STATE',
  1325. source: 'sidepanel',
  1326. payload: { email: normalizedEmail },
  1327. });
  1328. if (response?.error) {
  1329. throw new Error(response.error);
  1330. }
  1331. return normalizedEmail;
  1332. }
  1333. async function clearRegistrationEmail(options = {}) {
  1334. const { silent = false } = options;
  1335. if (!inputEmail.value.trim() && !latestState?.email) {
  1336. return;
  1337. }
  1338. inputEmail.value = '';
  1339. syncLatestState({ email: null });
  1340. try {
  1341. await setRuntimeEmailState(null);
  1342. } catch (err) {
  1343. if (!silent) {
  1344. showToast(`清空邮箱失败:${err.message}`, 'error');
  1345. }
  1346. throw err;
  1347. }
  1348. }
  1349. function markSettingsDirty(isDirty = true) {
  1350. settingsDirty = isDirty;
  1351. updateSaveButtonState();
  1352. }
  1353. function updateSaveButtonState() {
  1354. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  1355. updateConfigMenuControls();
  1356. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  1357. }
  1358. function scheduleSettingsAutoSave() {
  1359. clearTimeout(settingsAutoSaveTimer);
  1360. settingsAutoSaveTimer = setTimeout(() => {
  1361. saveSettings({ silent: true }).catch(() => { });
  1362. }, 500);
  1363. }
  1364. async function saveSettings(options = {}) {
  1365. const { silent = false } = options;
  1366. clearTimeout(settingsAutoSaveTimer);
  1367. if (!settingsDirty && !settingsSaveInFlight && silent) {
  1368. return;
  1369. }
  1370. const payload = collectSettingsPayload();
  1371. settingsSaveInFlight = true;
  1372. updateSaveButtonState();
  1373. try {
  1374. const response = await chrome.runtime.sendMessage({
  1375. type: 'SAVE_SETTING',
  1376. source: 'sidepanel',
  1377. payload,
  1378. });
  1379. if (response?.error) {
  1380. throw new Error(response.error);
  1381. }
  1382. if (response?.state) {
  1383. applySettingsState(response.state);
  1384. } else {
  1385. syncLatestState(payload);
  1386. markSettingsDirty(false);
  1387. updatePanelModeUI();
  1388. updateMailProviderUI();
  1389. updateButtonStates();
  1390. }
  1391. if (!silent) {
  1392. showToast('配置已保存', 'success', 1800);
  1393. }
  1394. } catch (err) {
  1395. markSettingsDirty(true);
  1396. if (!silent) {
  1397. showToast(`保存失败:${err.message}`, 'error');
  1398. }
  1399. throw err;
  1400. } finally {
  1401. settingsSaveInFlight = false;
  1402. updateSaveButtonState();
  1403. }
  1404. }
  1405. function applyAutoRunStatus(payload = currentAutoRun) {
  1406. syncAutoRunState(payload);
  1407. const runLabel = getAutoRunLabel(currentAutoRun);
  1408. const locked = isAutoRunLockedPhase();
  1409. const paused = isAutoRunPausedPhase();
  1410. const scheduled = isAutoRunScheduledPhase();
  1411. const settingsCardLocked = scheduled || locked;
  1412. setSettingsCardLocked(settingsCardLocked);
  1413. inputRunCount.disabled = currentAutoRun.autoRunning;
  1414. btnAutoRun.disabled = currentAutoRun.autoRunning;
  1415. btnFetchEmail.disabled = locked
  1416. || isCustomMailProvider();
  1417. inputEmail.disabled = locked;
  1418. inputAutoSkipFailures.disabled = scheduled;
  1419. if (currentAutoRun.totalRuns > 0) {
  1420. inputRunCount.value = String(currentAutoRun.totalRuns);
  1421. }
  1422. switch (currentAutoRun.phase) {
  1423. case 'scheduled':
  1424. autoContinueBar.style.display = 'none';
  1425. btnAutoRun.innerHTML = `已计划${runLabel}`;
  1426. break;
  1427. case 'waiting_step':
  1428. autoContinueBar.style.display = 'none';
  1429. btnAutoRun.innerHTML = `等待中${runLabel}`;
  1430. break;
  1431. case 'waiting_email':
  1432. autoContinueBar.style.display = 'flex';
  1433. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  1434. break;
  1435. case 'running':
  1436. autoContinueBar.style.display = 'none';
  1437. btnAutoRun.innerHTML = `运行中${runLabel}`;
  1438. break;
  1439. case 'retrying':
  1440. autoContinueBar.style.display = 'none';
  1441. btnAutoRun.innerHTML = `重试中${runLabel}`;
  1442. break;
  1443. case 'waiting_interval':
  1444. autoContinueBar.style.display = 'none';
  1445. btnAutoRun.innerHTML = `等待中${runLabel}`;
  1446. break;
  1447. default:
  1448. autoContinueBar.style.display = 'none';
  1449. setDefaultAutoRunButton();
  1450. inputEmail.disabled = false;
  1451. if (!locked) {
  1452. btnFetchEmail.disabled = isCustomMailProvider();
  1453. }
  1454. break;
  1455. }
  1456. updateAutoDelayInputState();
  1457. updateFallbackThreadIntervalInputState();
  1458. syncScheduledCountdownTicker();
  1459. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  1460. updateConfigMenuControls();
  1461. }
  1462. function initializeManualStepActions() {
  1463. document.querySelectorAll('.step-row').forEach((row) => {
  1464. const step = Number(row.dataset.step);
  1465. const statusEl = row.querySelector('.step-status');
  1466. if (!statusEl) return;
  1467. const actions = document.createElement('div');
  1468. actions.className = 'step-actions';
  1469. const manualBtn = document.createElement('button');
  1470. manualBtn.type = 'button';
  1471. manualBtn.className = 'step-manual-btn';
  1472. manualBtn.dataset.step = String(step);
  1473. manualBtn.title = '跳过此步';
  1474. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  1475. 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>';
  1476. manualBtn.addEventListener('click', async (event) => {
  1477. event.stopPropagation();
  1478. try {
  1479. await handleSkipStep(step);
  1480. } catch (err) {
  1481. showToast(err.message, 'error');
  1482. }
  1483. });
  1484. statusEl.parentNode.replaceChild(actions, statusEl);
  1485. actions.appendChild(manualBtn);
  1486. actions.appendChild(statusEl);
  1487. });
  1488. }
  1489. function renderStepsList() {
  1490. if (!stepsList) return;
  1491. stepsList.innerHTML = stepDefinitions.map((step) => `
  1492. <div class="step-row" data-step="${step.id}" data-step-key="${escapeHtml(step.key)}">
  1493. <div class="step-indicator" data-step="${step.id}"><span class="step-num">${step.id}</span></div>
  1494. <button class="step-btn" data-step="${step.id}" data-step-key="${escapeHtml(step.key)}">${escapeHtml(step.title)}</button>
  1495. <span class="step-status" data-step="${step.id}"></span>
  1496. </div>
  1497. `).join('');
  1498. if (stepsProgress) {
  1499. stepsProgress.textContent = `0 / ${STEP_IDS.length}`;
  1500. }
  1501. }
  1502. // ============================================================
  1503. // State Restore on load
  1504. // ============================================================
  1505. function applySettingsState(state) {
  1506. syncLatestState(state);
  1507. syncAutoRunState(state);
  1508. inputEmail.value = state?.email || '';
  1509. syncPasswordField(state || {});
  1510. inputVpsUrl.value = state?.vpsUrl || '';
  1511. inputVpsPassword.value = state?.vpsPassword || '';
  1512. setLocalCpaStep9Mode(state?.localCpaStep9Mode);
  1513. setCpaCallbackMode(state?.cpaCallbackMode);
  1514. selectPanelMode.value = state?.panelMode || 'cpa';
  1515. inputSub2ApiUrl.value = state?.sub2apiUrl || '';
  1516. inputSub2ApiEmail.value = state?.sub2apiEmail || '';
  1517. inputSub2ApiPassword.value = state?.sub2apiPassword || '';
  1518. inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
  1519. const restoredMailProvider = isCustomMailProvider(state?.mailProvider)
  1520. || [ICLOUD_PROVIDER, 'hotmail-api', GMAIL_PROVIDER, 'luckmail-api', '163', '163-vip', 'qq', 'inbucket', '2925', 'cloudflare-temp-email'].includes(String(state?.mailProvider || '').trim())
  1521. ? String(state?.mailProvider || '163').trim()
  1522. : (String(state?.emailGenerator || '').trim().toLowerCase() === 'custom'
  1523. || String(state?.emailGenerator || '').trim().toLowerCase() === 'manual'
  1524. ? 'custom'
  1525. : '163');
  1526. selectMailProvider.value = restoredMailProvider;
  1527. setMail2925Mode(state?.mail2925Mode);
  1528. {
  1529. const restoredEmailGenerator = String(state?.emailGenerator || '').trim().toLowerCase();
  1530. if (restoredEmailGenerator === 'icloud') {
  1531. selectEmailGenerator.value = 'icloud';
  1532. } else if (restoredEmailGenerator === 'cloudflare') {
  1533. selectEmailGenerator.value = 'cloudflare';
  1534. } else if (restoredEmailGenerator === 'cloudflare-temp-email') {
  1535. selectEmailGenerator.value = 'cloudflare-temp-email';
  1536. } else {
  1537. selectEmailGenerator.value = 'duck';
  1538. }
  1539. }
  1540. if (selectIcloudHostPreference) {
  1541. selectIcloudHostPreference.value = String(state?.icloudHostPreference || '').trim().toLowerCase() === 'icloud.com'
  1542. ? 'icloud.com'
  1543. : (String(state?.icloudHostPreference || '').trim().toLowerCase() === 'icloud.com.cn' ? 'icloud.com.cn' : 'auto');
  1544. }
  1545. if (checkboxAutoDeleteIcloud) {
  1546. checkboxAutoDeleteIcloud.checked = Boolean(state?.autoDeleteUsedIcloudAlias);
  1547. }
  1548. if (inputAccountRunHistoryTextEnabled) {
  1549. inputAccountRunHistoryTextEnabled.checked = Boolean(state?.accountRunHistoryTextEnabled);
  1550. }
  1551. if (inputAccountRunHistoryHelperBaseUrl) {
  1552. inputAccountRunHistoryHelperBaseUrl.value = normalizeAccountRunHistoryHelperBaseUrlValue(state?.accountRunHistoryHelperBaseUrl);
  1553. }
  1554. setManagedAliasBaseEmailInputForProvider(restoredMailProvider, state);
  1555. inputInbucketHost.value = state?.inbucketHost || '';
  1556. inputInbucketMailbox.value = state?.inbucketMailbox || '';
  1557. setHotmailServiceMode(state?.hotmailServiceMode);
  1558. inputHotmailRemoteBaseUrl.value = state?.hotmailRemoteBaseUrl || '';
  1559. inputHotmailLocalBaseUrl.value = state?.hotmailLocalBaseUrl || '';
  1560. inputLuckmailApiKey.value = state?.luckmailApiKey || '';
  1561. inputLuckmailBaseUrl.value = normalizeLuckmailBaseUrl(state?.luckmailBaseUrl);
  1562. selectLuckmailEmailType.value = normalizeLuckmailEmailType(state?.luckmailEmailType);
  1563. inputLuckmailDomain.value = state?.luckmailDomain || '';
  1564. inputTempEmailBaseUrl.value = state?.cloudflareTempEmailBaseUrl || '';
  1565. inputTempEmailAdminAuth.value = state?.cloudflareTempEmailAdminAuth || '';
  1566. inputTempEmailCustomAuth.value = state?.cloudflareTempEmailCustomAuth || '';
  1567. inputTempEmailReceiveMailbox.value = state?.cloudflareTempEmailReceiveMailbox || '';
  1568. renderCloudflareDomainOptions(state?.cloudflareDomain || '');
  1569. setCloudflareDomainEditMode(false, { clearInput: true });
  1570. renderCloudflareTempEmailDomainOptions(state?.cloudflareTempEmailDomain || '');
  1571. setCloudflareTempEmailDomainEditMode(false, { clearInput: true });
  1572. inputAutoSkipFailures.checked = Boolean(state?.autoRunSkipFailures);
  1573. inputAutoSkipFailuresThreadIntervalMinutes.value = String(normalizeAutoRunThreadIntervalMinutes(state?.autoRunFallbackThreadIntervalMinutes));
  1574. inputAutoDelayEnabled.checked = Boolean(state?.autoRunDelayEnabled);
  1575. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state?.autoRunDelayMinutes));
  1576. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(state?.autoStepDelaySeconds);
  1577. if (inputVerificationResendCount) {
  1578. const restoredVerificationResendCount = state?.verificationResendCount !== undefined
  1579. ? state.verificationResendCount
  1580. : (state?.signupVerificationResendCount ?? state?.loginVerificationResendCount);
  1581. inputVerificationResendCount.value = String(
  1582. normalizeVerificationResendCount(restoredVerificationResendCount, DEFAULT_VERIFICATION_RESEND_COUNT)
  1583. );
  1584. }
  1585. if (state?.autoRunTotalRuns) {
  1586. inputRunCount.value = String(state.autoRunTotalRuns);
  1587. }
  1588. applyAutoRunStatus(state);
  1589. markSettingsDirty(false);
  1590. updateAutoDelayInputState();
  1591. updateFallbackThreadIntervalInputState();
  1592. updateAccountRunHistorySettingsUI();
  1593. updatePanelModeUI();
  1594. updateMailProviderUI();
  1595. if (isLuckmailProvider(state?.mailProvider)) {
  1596. queueLuckmailPurchaseRefresh();
  1597. }
  1598. updateButtonStates();
  1599. }
  1600. async function restoreState() {
  1601. try {
  1602. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  1603. applySettingsState(state);
  1604. if (getSelectedEmailGenerator() === 'icloud' && icloudSection?.style.display !== 'none') {
  1605. refreshIcloudAliases({ silent: true }).catch(() => { });
  1606. }
  1607. if (state.oauthUrl) {
  1608. displayOauthUrl.textContent = state.oauthUrl;
  1609. displayOauthUrl.classList.add('has-value');
  1610. }
  1611. if (state.localhostUrl) {
  1612. displayLocalhostUrl.textContent = state.localhostUrl;
  1613. displayLocalhostUrl.classList.add('has-value');
  1614. }
  1615. if (state.stepStatuses) {
  1616. for (const [step, status] of Object.entries(state.stepStatuses)) {
  1617. updateStepUI(Number(step), status);
  1618. }
  1619. }
  1620. if (state.logs) {
  1621. for (const entry of state.logs) {
  1622. appendLog(entry);
  1623. }
  1624. }
  1625. updateStatusDisplay(latestState);
  1626. updateProgressCounter();
  1627. } catch (err) {
  1628. console.error('Failed to restore state:', err);
  1629. }
  1630. }
  1631. function openExternalUrl(url) {
  1632. const targetUrl = String(url || '').trim();
  1633. if (!targetUrl) {
  1634. return;
  1635. }
  1636. if (chrome?.tabs?.create) {
  1637. chrome.tabs.create({ url: targetUrl, active: true }).catch(() => {
  1638. window.open(targetUrl, '_blank', 'noopener');
  1639. });
  1640. return;
  1641. }
  1642. window.open(targetUrl, '_blank', 'noopener');
  1643. }
  1644. function createUpdateNoteList(notes = []) {
  1645. if (!Array.isArray(notes) || notes.length === 0) {
  1646. const empty = document.createElement('p');
  1647. empty.className = 'update-release-empty';
  1648. empty.textContent = '该版本未提供可解析的更新说明,请查看完整更新日志。';
  1649. return empty;
  1650. }
  1651. const list = document.createElement('ul');
  1652. list.className = 'update-release-notes';
  1653. notes.forEach((note) => {
  1654. const item = document.createElement('li');
  1655. item.textContent = note;
  1656. list.appendChild(item);
  1657. });
  1658. return list;
  1659. }
  1660. function renderUpdateReleaseList(releases = []) {
  1661. if (!updateReleaseList) {
  1662. return;
  1663. }
  1664. updateReleaseList.innerHTML = '';
  1665. releases.forEach((release) => {
  1666. const item = document.createElement('article');
  1667. item.className = 'update-release-item';
  1668. const head = document.createElement('div');
  1669. head.className = 'update-release-head';
  1670. const titleRow = document.createElement('div');
  1671. titleRow.className = 'update-release-title-row';
  1672. const version = document.createElement('span');
  1673. version.className = 'update-release-version';
  1674. version.textContent = release.displayVersion || `Pro${release.version}`;
  1675. titleRow.appendChild(version);
  1676. if (release.title) {
  1677. const name = document.createElement('span');
  1678. name.className = 'update-release-name';
  1679. name.textContent = release.title;
  1680. titleRow.appendChild(name);
  1681. }
  1682. head.appendChild(titleRow);
  1683. const publishedAt = sidepanelUpdateService?.formatReleaseDate?.(release.publishedAt) || '';
  1684. if (publishedAt) {
  1685. const date = document.createElement('span');
  1686. date.className = 'update-release-date';
  1687. date.textContent = publishedAt;
  1688. head.appendChild(date);
  1689. }
  1690. item.appendChild(head);
  1691. item.appendChild(createUpdateNoteList(release.notes));
  1692. updateReleaseList.appendChild(item);
  1693. });
  1694. }
  1695. function resetUpdateCard() {
  1696. if (updateSection) {
  1697. updateSection.hidden = true;
  1698. }
  1699. if (updateCardVersion) {
  1700. updateCardVersion.textContent = '';
  1701. }
  1702. if (updateCardSummary) {
  1703. updateCardSummary.textContent = '';
  1704. }
  1705. if (updateReleaseList) {
  1706. updateReleaseList.innerHTML = '';
  1707. }
  1708. if (btnOpenRelease) {
  1709. btnOpenRelease.hidden = true;
  1710. btnOpenRelease.onclick = null;
  1711. }
  1712. }
  1713. function renderReleaseSnapshot(snapshot) {
  1714. currentReleaseSnapshot = snapshot;
  1715. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1716. return;
  1717. }
  1718. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed', 'is-version-label');
  1719. const localVersionText = snapshot?.localVersion || '';
  1720. const logUrl = snapshot?.logUrl || snapshot?.releasesPageUrl || sidepanelUpdateService?.releasesPageUrl || '';
  1721. if (btnReleaseLog) {
  1722. btnReleaseLog.onclick = () => openExternalUrl(logUrl);
  1723. btnReleaseLog.hidden = true;
  1724. }
  1725. extensionVersionMeta.hidden = true;
  1726. extensionVersionMeta.textContent = '';
  1727. switch (snapshot?.status) {
  1728. case 'update-available': {
  1729. extensionUpdateStatus.textContent = '有更新';
  1730. extensionUpdateStatus.classList.add('is-update-available');
  1731. if (btnReleaseLog) {
  1732. btnReleaseLog.hidden = false;
  1733. }
  1734. if (updateSection) {
  1735. updateSection.hidden = false;
  1736. }
  1737. if (updateCardVersion) {
  1738. updateCardVersion.textContent = `最新版本 ${snapshot.latestVersion}`;
  1739. }
  1740. if (updateCardSummary) {
  1741. const updateCount = Array.isArray(snapshot.newerReleases) ? snapshot.newerReleases.length : 0;
  1742. updateCardSummary.textContent = updateCount > 1
  1743. ? `当前 ${localVersionText},共有 ${updateCount} 个新版本可更新。`
  1744. : `当前 ${localVersionText},可更新到 ${snapshot.latestVersion}。`;
  1745. }
  1746. renderUpdateReleaseList(snapshot.newerReleases || []);
  1747. if (btnOpenRelease) {
  1748. btnOpenRelease.hidden = false;
  1749. btnOpenRelease.textContent = '前往更新';
  1750. btnOpenRelease.onclick = () => openExternalUrl(logUrl);
  1751. }
  1752. break;
  1753. }
  1754. case 'latest': {
  1755. extensionUpdateStatus.textContent = localVersionText || 'Pro0.0';
  1756. extensionUpdateStatus.classList.add('is-version-label');
  1757. resetUpdateCard();
  1758. break;
  1759. }
  1760. case 'empty': {
  1761. extensionUpdateStatus.textContent = localVersionText || 'Pro0.0';
  1762. extensionUpdateStatus.classList.add('is-version-label');
  1763. resetUpdateCard();
  1764. break;
  1765. }
  1766. case 'error':
  1767. default: {
  1768. extensionUpdateStatus.textContent = localVersionText || 'Pro0.0';
  1769. extensionUpdateStatus.classList.add('is-version-label', 'is-check-failed');
  1770. extensionVersionMeta.textContent = snapshot?.errorMessage || 'GitHub Releases 检查失败';
  1771. extensionVersionMeta.hidden = false;
  1772. resetUpdateCard();
  1773. break;
  1774. }
  1775. }
  1776. }
  1777. async function initializeReleaseInfo() {
  1778. const fallbackReleaseUrl = sidepanelUpdateService?.releasesPageUrl || 'https://github.com/QLHazyCoder/codex-oauth-automation-extension/releases';
  1779. if (btnReleaseLog) {
  1780. btnReleaseLog.onclick = () => openExternalUrl(currentReleaseSnapshot?.logUrl || fallbackReleaseUrl);
  1781. }
  1782. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1783. return;
  1784. }
  1785. const localVersion = sidepanelUpdateService?.getLocalVersionLabel?.(chrome.runtime.getManifest())
  1786. || chrome.runtime.getManifest()?.version_name
  1787. || (chrome.runtime.getManifest()?.version ? `v${chrome.runtime.getManifest().version}` : '');
  1788. extensionUpdateStatus.textContent = localVersion || 'Pro0.0';
  1789. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed');
  1790. extensionUpdateStatus.classList.add('is-version-label');
  1791. extensionVersionMeta.hidden = true;
  1792. extensionVersionMeta.textContent = '';
  1793. if (btnReleaseLog) {
  1794. btnReleaseLog.hidden = true;
  1795. }
  1796. resetUpdateCard();
  1797. if (!sidepanelUpdateService) {
  1798. extensionVersionMeta.textContent = '更新检查服务不可用';
  1799. extensionVersionMeta.hidden = false;
  1800. return;
  1801. }
  1802. const snapshot = await sidepanelUpdateService.getReleaseSnapshot();
  1803. renderReleaseSnapshot(snapshot);
  1804. }
  1805. function syncPasswordField(state) {
  1806. inputPassword.value = state.customPassword || state.password || '';
  1807. }
  1808. function isCustomMailProvider(provider = selectMailProvider.value) {
  1809. return String(provider || '').trim().toLowerCase() === 'custom';
  1810. }
  1811. function isLuckmailProvider(provider = selectMailProvider.value) {
  1812. return String(provider || '').trim().toLowerCase() === LUCKMAIL_PROVIDER;
  1813. }
  1814. function isIcloudMailProvider(provider = selectMailProvider.value) {
  1815. return String(provider || '').trim().toLowerCase() === ICLOUD_PROVIDER;
  1816. }
  1817. function normalizeLuckmailBaseUrl(value = '') {
  1818. const trimmed = String(value || '').trim();
  1819. if (!trimmed) {
  1820. return DEFAULT_LUCKMAIL_BASE_URL;
  1821. }
  1822. try {
  1823. const parsed = new URL(trimmed);
  1824. if (!['http:', 'https:'].includes(parsed.protocol)) {
  1825. return DEFAULT_LUCKMAIL_BASE_URL;
  1826. }
  1827. parsed.pathname = parsed.pathname.replace(/\/+$/, '');
  1828. parsed.search = '';
  1829. parsed.hash = '';
  1830. return parsed.toString().replace(/\/$/, '');
  1831. } catch {
  1832. return DEFAULT_LUCKMAIL_BASE_URL;
  1833. }
  1834. }
  1835. function normalizeLuckmailEmailType(value = '') {
  1836. const normalized = String(value || '').trim().toLowerCase();
  1837. return ['self_built', 'ms_imap', 'ms_graph', 'google_variant'].includes(normalized)
  1838. ? normalized
  1839. : DEFAULT_LUCKMAIL_EMAIL_TYPE;
  1840. }
  1841. function getSelectedEmailGenerator() {
  1842. const generator = String(selectEmailGenerator.value || '').trim().toLowerCase();
  1843. if (generator === 'custom' || generator === 'manual') {
  1844. return 'custom';
  1845. }
  1846. if (generator === 'icloud') {
  1847. return 'icloud';
  1848. }
  1849. if (generator === 'cloudflare') return 'cloudflare';
  1850. if (generator === 'cloudflare-temp-email') return 'cloudflare-temp-email';
  1851. return 'duck';
  1852. }
  1853. function getEmailGeneratorUiCopy() {
  1854. if (getSelectedEmailGenerator() === 'custom') {
  1855. return getCustomMailProviderUiCopy();
  1856. }
  1857. if (getSelectedEmailGenerator() === 'icloud') {
  1858. return {
  1859. buttonLabel: '获取',
  1860. placeholder: '点击获取 iCloud 隐私邮箱,或手动粘贴邮箱',
  1861. successVerb: '获取',
  1862. label: 'iCloud 隐私邮箱',
  1863. };
  1864. }
  1865. if (getSelectedEmailGenerator() === 'cloudflare') {
  1866. return {
  1867. buttonLabel: '生成',
  1868. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  1869. successVerb: '生成',
  1870. label: 'Cloudflare 邮箱',
  1871. };
  1872. }
  1873. if (getSelectedEmailGenerator() === 'cloudflare-temp-email') {
  1874. return {
  1875. buttonLabel: '生成 Temp',
  1876. placeholder: '点击生成 Cloudflare Temp Email,或手动粘贴邮箱',
  1877. successVerb: '生成',
  1878. label: 'Cloudflare Temp Email',
  1879. };
  1880. }
  1881. return {
  1882. buttonLabel: '获取',
  1883. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  1884. successVerb: '获取',
  1885. label: 'Duck 邮箱',
  1886. };
  1887. }
  1888. function getCustomMailProviderUiCopy() {
  1889. return {
  1890. buttonLabel: '自定义邮箱',
  1891. placeholder: '请填写本轮要使用的注册邮箱',
  1892. successVerb: '使用',
  1893. label: '自定义邮箱',
  1894. };
  1895. }
  1896. function getCustomVerificationPromptCopy(step) {
  1897. const verificationLabel = step === 4 ? '注册验证码' : '登录验证码';
  1898. return {
  1899. title: `手动处理${verificationLabel}`,
  1900. message: `当前邮箱服务为“自定义邮箱”。请先在页面中手动输入${verificationLabel},并确认已经进入下一页面后,再点击确认。`,
  1901. alert: {
  1902. text: `点击确认后会跳过步骤 ${step}。`,
  1903. tone: 'danger',
  1904. },
  1905. };
  1906. }
  1907. function getHotmailAccounts(state = latestState) {
  1908. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  1909. }
  1910. function getCurrentHotmailAccount(state = latestState) {
  1911. const currentId = state?.currentHotmailAccountId;
  1912. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  1913. }
  1914. function getCurrentHotmailEmail(state = latestState) {
  1915. return String(getCurrentHotmailAccount(state)?.email || '').trim();
  1916. }
  1917. function getCurrentLuckmailPurchase(state = latestState) {
  1918. return state?.currentLuckmailPurchase || null;
  1919. }
  1920. function getCurrentLuckmailEmail(state = latestState) {
  1921. return String(getCurrentLuckmailPurchase(state)?.email_address || '').trim();
  1922. }
  1923. function getLuckmailUsedPurchases(state = latestState) {
  1924. const rawValue = state?.luckmailUsedPurchases;
  1925. if (!rawValue || typeof rawValue !== 'object' || Array.isArray(rawValue)) {
  1926. return {};
  1927. }
  1928. return Object.entries(rawValue).reduce((result, [key, value]) => {
  1929. const numeric = Number(key);
  1930. if (!Number.isFinite(numeric) || numeric <= 0) {
  1931. return result;
  1932. }
  1933. result[String(Math.floor(numeric))] = Boolean(value);
  1934. return result;
  1935. }, {});
  1936. }
  1937. function normalizeLuckmailProjectName(value = '') {
  1938. return String(value || '').trim().toLowerCase();
  1939. }
  1940. function getLuckmailPreserveTagName(state = latestState) {
  1941. return String(state?.luckmailPreserveTagName || '').trim() || DEFAULT_LUCKMAIL_PRESERVE_TAG_NAME;
  1942. }
  1943. function formatLuckmailDateTime(value) {
  1944. const timestamp = normalizeLuckmailTimestampValue(value);
  1945. if (!timestamp) {
  1946. return String(value || '').trim() || '未知';
  1947. }
  1948. return new Date(timestamp).toLocaleString('zh-CN', {
  1949. hour12: false,
  1950. timeZone: DISPLAY_TIMEZONE,
  1951. });
  1952. }
  1953. function getMailProviderLoginConfig(provider = selectMailProvider.value) {
  1954. return MAIL_PROVIDER_LOGIN_CONFIGS[String(provider || '').trim()] || null;
  1955. }
  1956. function getSelectedIcloudHostPreference() {
  1957. return normalizeIcloudHost(selectIcloudHostPreference?.value || latestState?.icloudHostPreference || '')
  1958. || normalizeIcloudHost(latestState?.preferredIcloudHost)
  1959. || 'icloud.com';
  1960. }
  1961. function getMailProviderLoginUrl(provider = selectMailProvider.value) {
  1962. const config = getMailProviderLoginConfig(provider);
  1963. if (String(provider || '').trim() === ICLOUD_PROVIDER) {
  1964. return getIcloudLoginUrlForHost(getSelectedIcloudHostPreference());
  1965. }
  1966. const url = String(config?.url || '').trim();
  1967. return url ? url : '';
  1968. }
  1969. function isCurrentEmailManagedByHotmail(state = latestState) {
  1970. const hotmailEmail = getCurrentHotmailEmail(state);
  1971. if (!hotmailEmail) {
  1972. return false;
  1973. }
  1974. const inputEmailValue = String(inputEmail.value || '').trim();
  1975. const stateEmailValue = String(state?.email || '').trim();
  1976. return inputEmailValue === hotmailEmail || stateEmailValue === hotmailEmail;
  1977. }
  1978. function isCurrentEmailManagedByLuckmail(state = latestState) {
  1979. const luckmailEmail = getCurrentLuckmailEmail(state);
  1980. if (!luckmailEmail) {
  1981. return false;
  1982. }
  1983. const inputEmailValue = String(inputEmail.value || '').trim();
  1984. const stateEmailValue = String(state?.email || '').trim();
  1985. return inputEmailValue === luckmailEmail || stateEmailValue === luckmailEmail;
  1986. }
  1987. function isCurrentEmailManagedByGeneratedAlias(
  1988. provider = latestState?.mailProvider,
  1989. state = latestState,
  1990. mail2925Mode = latestState?.mail2925Mode
  1991. ) {
  1992. const normalizedProvider = String(provider || '').trim();
  1993. if (!usesGeneratedAliasMailProvider(normalizedProvider, mail2925Mode)) {
  1994. return false;
  1995. }
  1996. const inputEmailValue = String(inputEmail.value || '').trim().toLowerCase();
  1997. const stateEmailValue = String(state?.email || '').trim().toLowerCase();
  1998. const baseEmail = getManagedAliasBaseEmailForProvider(normalizedProvider, state);
  1999. return isManagedAliasEmail(inputEmailValue, baseEmail, normalizedProvider)
  2000. || isManagedAliasEmail(stateEmailValue, baseEmail, normalizedProvider);
  2001. }
  2002. async function maybeClearGeneratedAliasAfterEmailPrefixChange() {
  2003. const provider = selectMailProvider.value;
  2004. if (!usesGeneratedAliasMailProvider(provider, latestState?.mail2925Mode)) {
  2005. return;
  2006. }
  2007. const previousPrefix = getManagedAliasBaseEmailForProvider(provider, latestState);
  2008. const nextPrefix = inputEmailPrefix.value.trim();
  2009. if (previousPrefix === nextPrefix) {
  2010. return;
  2011. }
  2012. if (!previousPrefix) {
  2013. return;
  2014. }
  2015. if (!isCurrentEmailManagedByGeneratedAlias(provider, latestState, latestState?.mail2925Mode)) {
  2016. return;
  2017. }
  2018. await clearRegistrationEmail({ silent: true });
  2019. }
  2020. function updateMailLoginButtonState() {
  2021. if (!btnMailLogin) {
  2022. return;
  2023. }
  2024. const config = getMailProviderLoginConfig();
  2025. const loginUrl = getMailProviderLoginUrl();
  2026. btnMailLogin.disabled = !loginUrl;
  2027. btnMailLogin.textContent = config?.buttonLabel || '登录';
  2028. btnMailLogin.title = loginUrl ? `打开 ${config.label} 登录页` : '当前邮箱服务没有可跳转的登录页';
  2029. }
  2030. function updateMailProviderUI() {
  2031. const use2925 = selectMailProvider.value === '2925';
  2032. const useGmail = selectMailProvider.value === GMAIL_PROVIDER;
  2033. const mail2925Mode = getSelectedMail2925Mode();
  2034. const useGeneratedAlias = usesGeneratedAliasMailProvider(selectMailProvider.value, mail2925Mode);
  2035. const useInbucket = selectMailProvider.value === 'inbucket';
  2036. const useHotmail = selectMailProvider.value === 'hotmail-api';
  2037. const useLuckmail = isLuckmailProvider();
  2038. const useCustomEmail = isCustomMailProvider();
  2039. const useIcloudProvider = isIcloudMailProvider();
  2040. const useEmailGenerator = !useHotmail && !useLuckmail && !useGeneratedAlias && !useCustomEmail;
  2041. const useCloudflareTempEmailProvider = selectMailProvider.value === 'cloudflare-temp-email';
  2042. const aliasUiCopy = useGeneratedAlias ? getManagedAliasProviderUiCopy(selectMailProvider.value) : null;
  2043. const uiCopy = getCurrentRegistrationEmailUiCopy();
  2044. updateMailLoginButtonState();
  2045. if (rowMail2925Mode) {
  2046. rowMail2925Mode.style.display = 'none';
  2047. }
  2048. rowEmailPrefix.style.display = useGeneratedAlias ? '' : 'none';
  2049. const hotmailServiceMode = getSelectedHotmailServiceMode();
  2050. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  2051. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  2052. const selectedGenerator = getSelectedEmailGenerator();
  2053. const useCloudflare = selectedGenerator === 'cloudflare';
  2054. const useIcloud = selectedGenerator === 'icloud';
  2055. const useCloudflareTempEmailGenerator = selectedGenerator === 'cloudflare-temp-email';
  2056. const showCloudflareDomain = useEmailGenerator && useCloudflare;
  2057. const showCloudflareTempEmailSettings = useCloudflareTempEmailProvider || (useEmailGenerator && useCloudflareTempEmailGenerator);
  2058. const showCloudflareTempEmailReceiveMailbox = useCloudflareTempEmailProvider && !useCloudflareTempEmailGenerator;
  2059. const showCloudflareTempEmailDomain = useEmailGenerator && useCloudflareTempEmailGenerator;
  2060. if (rowEmailGenerator) {
  2061. rowEmailGenerator.style.display = useEmailGenerator ? '' : 'none';
  2062. }
  2063. if (icloudSection) {
  2064. const showIcloudSection = (useEmailGenerator && useIcloud) || useIcloudProvider;
  2065. icloudSection.style.display = showIcloudSection ? '' : 'none';
  2066. if (showIcloudSection) {
  2067. queueIcloudAliasRefresh();
  2068. }
  2069. if (!showIcloudSection) {
  2070. hideIcloudLoginHelp();
  2071. }
  2072. }
  2073. rowCfDomain.style.display = showCloudflareDomain ? '' : 'none';
  2074. const { domains } = getCloudflareDomainsFromState();
  2075. if (showCloudflareDomain) {
  2076. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  2077. } else {
  2078. setCloudflareDomainEditMode(false, { clearInput: false });
  2079. }
  2080. rowTempEmailBaseUrl.style.display = showCloudflareTempEmailSettings ? '' : 'none';
  2081. rowTempEmailAdminAuth.style.display = showCloudflareTempEmailSettings ? '' : 'none';
  2082. rowTempEmailCustomAuth.style.display = showCloudflareTempEmailSettings ? '' : 'none';
  2083. rowTempEmailReceiveMailbox.style.display = showCloudflareTempEmailReceiveMailbox ? '' : 'none';
  2084. rowTempEmailDomain.style.display = showCloudflareTempEmailDomain ? '' : 'none';
  2085. const { domains: tempEmailDomains } = getCloudflareTempEmailDomainsFromState();
  2086. if (showCloudflareTempEmailDomain) {
  2087. setCloudflareTempEmailDomainEditMode(cloudflareTempEmailDomainEditMode || tempEmailDomains.length === 0, { clearInput: false });
  2088. } else {
  2089. setCloudflareTempEmailDomainEditMode(false, { clearInput: false });
  2090. }
  2091. if (hotmailSection) {
  2092. hotmailSection.style.display = useHotmail ? '' : 'none';
  2093. }
  2094. if (luckmailSection) {
  2095. luckmailSection.style.display = useLuckmail ? '' : 'none';
  2096. }
  2097. labelEmailPrefix.textContent = '邮箱前缀';
  2098. inputEmailPrefix.placeholder = '例如 abc';
  2099. selectEmailGenerator.disabled = useHotmail || useLuckmail || useGeneratedAlias || useCustomEmail;
  2100. if (useGmail) {
  2101. labelEmailPrefix.textContent = 'Gmail 原邮箱';
  2102. inputEmailPrefix.placeholder = '例如 yourname@gmail.com';
  2103. }
  2104. labelEmailPrefix.textContent = aliasUiCopy?.baseLabel || labelEmailPrefix.textContent;
  2105. inputEmailPrefix.placeholder = aliasUiCopy?.basePlaceholder || inputEmailPrefix.placeholder;
  2106. if (rowHotmailServiceMode) {
  2107. rowHotmailServiceMode.style.display = useHotmail ? '' : 'none';
  2108. }
  2109. if (rowHotmailRemoteBaseUrl) {
  2110. rowHotmailRemoteBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE ? '' : 'none';
  2111. }
  2112. if (rowHotmailLocalBaseUrl) {
  2113. rowHotmailLocalBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_LOCAL ? '' : 'none';
  2114. }
  2115. btnFetchEmail.hidden = useHotmail || useLuckmail || useCustomEmail;
  2116. inputEmail.readOnly = useHotmail || useLuckmail;
  2117. inputEmail.placeholder = useHotmail
  2118. ? '由 Hotmail 账号池自动分配'
  2119. : (useLuckmail
  2120. ? '步骤 3 自动购买 LuckMail 邮箱并回填'
  2121. : (useGeneratedAlias ? '步骤 3 自动生成 2925 邮箱并回填' : uiCopy.placeholder));
  2122. if (useGmail && useGeneratedAlias) {
  2123. inputEmail.placeholder = '步骤 3 自动生成 Gmail +tag 邮箱并回填';
  2124. }
  2125. if (!useHotmail && !useLuckmail) {
  2126. inputEmail.placeholder = uiCopy.placeholder;
  2127. }
  2128. btnFetchEmail.disabled = useLuckmail || useCustomEmail || isAutoRunLockedPhase();
  2129. if (!btnFetchEmail.disabled) {
  2130. btnFetchEmail.textContent = uiCopy.buttonLabel;
  2131. }
  2132. if (autoHintText) {
  2133. autoHintText.textContent = useHotmail
  2134. ? '请先校验并选择一个 Hotmail 账号'
  2135. : (useLuckmail
  2136. ? '步骤 3 会自动购买 LuckMail 邮箱并用于收码'
  2137. : (useGeneratedAlias
  2138. ? '步骤 3 会自动生成邮箱,无需手动获取'
  2139. : (useCustomEmail ? '请先填写自定义注册邮箱,成功一轮后会自动清空' : `先自动获取${uiCopy.label},或手动粘贴邮箱后再继续`)));
  2140. }
  2141. if (autoHintText && useGmail && useGeneratedAlias) {
  2142. autoHintText.textContent = '请先填写 Gmail 原邮箱,步骤 3 会自动生成 Gmail +tag 地址';
  2143. }
  2144. if (autoHintText && useGeneratedAlias && aliasUiCopy?.hint) {
  2145. autoHintText.textContent = aliasUiCopy.hint;
  2146. }
  2147. if (autoHintText && showCloudflareTempEmailReceiveMailbox) {
  2148. autoHintText.textContent = '若注册邮箱会转发到 Cloudflare Temp Email,请在“邮件接收”中填写实际接收转发邮件的邮箱。';
  2149. }
  2150. if (useHotmail) {
  2151. inputEmail.value = getCurrentHotmailEmail();
  2152. } else if (useLuckmail) {
  2153. inputEmail.value = getCurrentLuckmailEmail();
  2154. }
  2155. renderHotmailAccounts();
  2156. if (useLuckmail) {
  2157. renderLuckmailPurchases();
  2158. }
  2159. }
  2160. async function saveCloudflareDomainSettings(domains, activeDomain, options = {}) {
  2161. const { silent = false } = options;
  2162. const normalizedDomains = normalizeCloudflareDomains(domains);
  2163. const normalizedActiveDomain = normalizeCloudflareDomainValue(activeDomain) || normalizedDomains[0] || '';
  2164. const payload = {
  2165. cloudflareDomain: normalizedActiveDomain,
  2166. cloudflareDomains: normalizedDomains,
  2167. };
  2168. const response = await chrome.runtime.sendMessage({
  2169. type: 'SAVE_SETTING',
  2170. source: 'sidepanel',
  2171. payload,
  2172. });
  2173. if (response?.error) {
  2174. throw new Error(response.error);
  2175. }
  2176. syncLatestState({
  2177. ...payload,
  2178. });
  2179. renderCloudflareDomainOptions(normalizedActiveDomain);
  2180. setCloudflareDomainEditMode(false, { clearInput: true });
  2181. markSettingsDirty(false);
  2182. updateMailProviderUI();
  2183. if (!silent) {
  2184. showToast('Cloudflare 域名已保存', 'success', 1800);
  2185. }
  2186. }
  2187. async function saveCloudflareTempEmailDomainSettings(domains, activeDomain, options = {}) {
  2188. const { silent = false } = options;
  2189. const normalizedDomains = normalizeCloudflareTempEmailDomains(domains);
  2190. const normalizedActiveDomain = normalizeCloudflareTempEmailDomainValue(activeDomain) || normalizedDomains[0] || '';
  2191. const payload = {
  2192. cloudflareTempEmailDomain: normalizedActiveDomain,
  2193. cloudflareTempEmailDomains: normalizedDomains,
  2194. };
  2195. const response = await chrome.runtime.sendMessage({
  2196. type: 'SAVE_SETTING',
  2197. source: 'sidepanel',
  2198. payload,
  2199. });
  2200. if (response?.error) {
  2201. throw new Error(response.error);
  2202. }
  2203. syncLatestState({
  2204. ...payload,
  2205. });
  2206. renderCloudflareTempEmailDomainOptions(normalizedActiveDomain);
  2207. setCloudflareTempEmailDomainEditMode(false, { clearInput: true });
  2208. markSettingsDirty(false);
  2209. updateMailProviderUI();
  2210. if (!silent) {
  2211. showToast('Cloudflare Temp Email 域名已保存', 'success', 1800);
  2212. }
  2213. }
  2214. function updatePanelModeUI() {
  2215. const useSub2Api = selectPanelMode.value === 'sub2api';
  2216. rowVpsUrl.style.display = useSub2Api ? 'none' : '';
  2217. rowVpsPassword.style.display = useSub2Api ? 'none' : '';
  2218. rowLocalCpaStep9Mode.style.display = useSub2Api ? 'none' : '';
  2219. rowCpaCallbackMode.style.display = useSub2Api ? 'none' : '';
  2220. rowSub2ApiUrl.style.display = useSub2Api ? '' : 'none';
  2221. rowSub2ApiEmail.style.display = useSub2Api ? '' : 'none';
  2222. rowSub2ApiPassword.style.display = useSub2Api ? '' : 'none';
  2223. rowSub2ApiGroup.style.display = useSub2Api ? '' : 'none';
  2224. const step9Btn = document.querySelector('.step-btn[data-step-key="platform-verify"]');
  2225. if (step9Btn) {
  2226. step9Btn.textContent = useSub2Api ? 'SUB2API 回调验证' : 'CPA 回调验证';
  2227. }
  2228. }
  2229. // ============================================================
  2230. // UI Updates
  2231. // ============================================================
  2232. function updateStepUI(step, status) {
  2233. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  2234. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  2235. syncLatestState({
  2236. stepStatuses: {
  2237. ...getStepStatuses(),
  2238. [step]: status,
  2239. },
  2240. });
  2241. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  2242. if (row) {
  2243. row.className = `step-row ${status}`;
  2244. }
  2245. updateButtonStates();
  2246. updateProgressCounter();
  2247. updateConfigMenuControls();
  2248. }
  2249. function updateProgressCounter() {
  2250. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  2251. stepsProgress.textContent = `${completed} / ${STEP_IDS.length}`;
  2252. }
  2253. function updateButtonStates() {
  2254. const statuses = getStepStatuses();
  2255. const anyRunning = Object.values(statuses).some(s => s === 'running');
  2256. const autoLocked = isAutoRunLockedPhase();
  2257. const autoScheduled = isAutoRunScheduledPhase();
  2258. for (const step of STEP_IDS) {
  2259. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  2260. if (!btn) continue;
  2261. if (anyRunning || autoLocked || autoScheduled) {
  2262. btn.disabled = true;
  2263. } else if (step === 1) {
  2264. btn.disabled = false;
  2265. } else {
  2266. const currentIndex = STEP_IDS.indexOf(step);
  2267. const prevStep = currentIndex > 0 ? STEP_IDS[currentIndex - 1] : null;
  2268. const prevStatus = prevStep === null ? 'completed' : statuses[prevStep];
  2269. const currentStatus = statuses[step];
  2270. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  2271. }
  2272. }
  2273. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  2274. const step = Number(btn.dataset.step);
  2275. const currentStatus = statuses[step];
  2276. const currentIndex = STEP_IDS.indexOf(step);
  2277. const prevStep = currentIndex > 0 ? STEP_IDS[currentIndex - 1] : null;
  2278. const prevStatus = prevStep === null ? 'completed' : statuses[prevStep];
  2279. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  2280. btn.style.display = 'none';
  2281. btn.disabled = true;
  2282. btn.title = '当前不可跳过';
  2283. return;
  2284. }
  2285. if (prevStep !== null && !isDoneStatus(prevStatus)) {
  2286. btn.style.display = 'none';
  2287. btn.disabled = true;
  2288. btn.title = `请先完成步骤 ${prevStep}`;
  2289. return;
  2290. }
  2291. btn.style.display = '';
  2292. btn.disabled = false;
  2293. btn.title = `跳过步骤 ${step}`;
  2294. });
  2295. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  2296. const disableIcloudControls = anyRunning || autoScheduled || autoLocked;
  2297. if (btnIcloudRefresh) btnIcloudRefresh.disabled = disableIcloudControls;
  2298. if (btnIcloudDeleteUsed) btnIcloudDeleteUsed.disabled = disableIcloudControls || !hasDeletableUsedIcloudAliases();
  2299. if (selectIcloudHostPreference) selectIcloudHostPreference.disabled = disableIcloudControls;
  2300. if (checkboxAutoDeleteIcloud) checkboxAutoDeleteIcloud.disabled = disableIcloudControls;
  2301. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  2302. }
  2303. function updateStopButtonState(active) {
  2304. btnStop.disabled = !active;
  2305. }
  2306. function updateStatusDisplay(state) {
  2307. if (!state || !state.stepStatuses) return;
  2308. statusBar.className = 'status-bar';
  2309. const countdown = getActiveAutoRunCountdown();
  2310. if (countdown) {
  2311. const remainingMs = countdown.at - Date.now();
  2312. displayStatus.textContent = remainingMs > 0
  2313. ? `${countdown.title},剩余 ${formatCountdown(remainingMs)}`
  2314. : `${countdown.title},即将结束...`;
  2315. statusBar.classList.add(countdown.tone === 'scheduled' ? 'scheduled' : 'running');
  2316. return;
  2317. }
  2318. if (isAutoRunScheduledPhase()) {
  2319. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  2320. ? currentAutoRun.scheduledAt - Date.now()
  2321. : 0;
  2322. displayStatus.textContent = remainingMs > 0
  2323. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  2324. : '倒计时即将结束,正在准备启动...';
  2325. statusBar.classList.add('scheduled');
  2326. return;
  2327. }
  2328. if (isAutoRunPausedPhase()) {
  2329. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  2330. statusBar.classList.add('paused');
  2331. return;
  2332. }
  2333. if (isAutoRunWaitingStepPhase()) {
  2334. const runningSteps = getRunningSteps(state);
  2335. displayStatus.textContent = runningSteps.length
  2336. ? `自动等待步骤 ${runningSteps.join(', ')} 完成后继续${getAutoRunLabel()}`
  2337. : `自动正在按最新进度准备继续${getAutoRunLabel()}`;
  2338. statusBar.classList.add('running');
  2339. return;
  2340. }
  2341. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  2342. if (running) {
  2343. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  2344. statusBar.classList.add('running');
  2345. return;
  2346. }
  2347. if (isAutoRunLockedPhase()) {
  2348. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  2349. statusBar.classList.add('running');
  2350. return;
  2351. }
  2352. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  2353. if (failed) {
  2354. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  2355. statusBar.classList.add('failed');
  2356. return;
  2357. }
  2358. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  2359. if (stopped) {
  2360. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  2361. statusBar.classList.add('stopped');
  2362. return;
  2363. }
  2364. const lastCompleted = Object.entries(state.stepStatuses)
  2365. .filter(([, s]) => isDoneStatus(s))
  2366. .map(([k]) => Number(k))
  2367. .sort((a, b) => b - a)[0];
  2368. if (lastCompleted === STEP_IDS[STEP_IDS.length - 1]) {
  2369. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  2370. statusBar.classList.add('completed');
  2371. } else if (lastCompleted) {
  2372. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  2373. ? `步骤 ${lastCompleted} 已跳过`
  2374. : `步骤 ${lastCompleted} 已完成`;
  2375. } else {
  2376. displayStatus.textContent = '就绪';
  2377. }
  2378. }
  2379. function appendLog(entry) {
  2380. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', {
  2381. hour12: false,
  2382. timeZone: DISPLAY_TIMEZONE,
  2383. });
  2384. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  2385. const line = document.createElement('div');
  2386. line.className = `log-line log-${entry.level}`;
  2387. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  2388. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  2389. let html = `<span class="log-time">${time}</span> `;
  2390. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  2391. if (stepNum) {
  2392. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  2393. }
  2394. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  2395. line.innerHTML = html;
  2396. logArea.appendChild(line);
  2397. logArea.scrollTop = logArea.scrollHeight;
  2398. }
  2399. function escapeHtml(text) {
  2400. const div = document.createElement('div');
  2401. div.textContent = text;
  2402. return div.innerHTML;
  2403. }
  2404. async function fetchGeneratedEmail(options = {}) {
  2405. const { showFailureToast = true } = options;
  2406. const uiCopy = getCurrentRegistrationEmailUiCopy();
  2407. if (isCustomMailProvider()) {
  2408. throw new Error('当前邮箱服务为自定义邮箱,请直接填写注册邮箱。');
  2409. }
  2410. const defaultLabel = uiCopy.buttonLabel;
  2411. btnFetchEmail.disabled = true;
  2412. btnFetchEmail.textContent = '...';
  2413. try {
  2414. const response = await chrome.runtime.sendMessage({
  2415. type: 'FETCH_GENERATED_EMAIL',
  2416. source: 'sidepanel',
  2417. payload: {
  2418. generateNew: true,
  2419. generator: selectEmailGenerator.value,
  2420. mailProvider: selectMailProvider.value,
  2421. ...buildManagedAliasBaseEmailPayload(),
  2422. },
  2423. });
  2424. if (response?.error) {
  2425. throw new Error(response.error);
  2426. }
  2427. if (!response?.email) {
  2428. throw new Error('未返回可用邮箱。');
  2429. }
  2430. inputEmail.value = response.email;
  2431. if (getSelectedEmailGenerator() === 'icloud') {
  2432. queueIcloudAliasRefresh();
  2433. }
  2434. showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500);
  2435. return response.email;
  2436. } catch (err) {
  2437. if (showFailureToast) {
  2438. showToast(`${uiCopy.label}${uiCopy.successVerb}失败:${err.message}`, 'error');
  2439. }
  2440. throw err;
  2441. } finally {
  2442. btnFetchEmail.disabled = false;
  2443. btnFetchEmail.textContent = defaultLabel;
  2444. }
  2445. }
  2446. function syncToggleButtonLabel(button, input, labels) {
  2447. if (!button || !input) return;
  2448. const isHidden = input.type === 'password';
  2449. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  2450. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  2451. button.title = isHidden ? labels.show : labels.hide;
  2452. }
  2453. async function copyTextToClipboard(text) {
  2454. const value = String(text || '').trim();
  2455. if (!value) {
  2456. throw new Error('没有可复制的内容。');
  2457. }
  2458. if (!navigator.clipboard?.writeText) {
  2459. throw new Error('当前环境不支持剪贴板复制。');
  2460. }
  2461. await navigator.clipboard.writeText(value);
  2462. }
  2463. const hotmailManager = window.SidepanelHotmailManager?.createHotmailManager({
  2464. state: {
  2465. getLatestState: () => latestState,
  2466. syncLatestState,
  2467. },
  2468. dom: {
  2469. btnAddHotmailAccount,
  2470. btnClearUsedHotmailAccounts,
  2471. btnDeleteAllHotmailAccounts,
  2472. btnHotmailUsageGuide,
  2473. btnImportHotmailAccounts,
  2474. btnToggleHotmailList,
  2475. hotmailAccountsList,
  2476. hotmailListShell,
  2477. inputEmail,
  2478. inputHotmailClientId,
  2479. inputHotmailEmail,
  2480. inputHotmailImport,
  2481. inputHotmailPassword,
  2482. inputHotmailRefreshToken,
  2483. selectMailProvider,
  2484. },
  2485. helpers: {
  2486. copyTextToClipboard,
  2487. escapeHtml,
  2488. getCurrentHotmailEmail,
  2489. getHotmailAccounts,
  2490. openConfirmModal,
  2491. showToast,
  2492. },
  2493. runtime: {
  2494. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2495. },
  2496. constants: {
  2497. copyIcon: COPY_ICON,
  2498. displayTimeZone: DISPLAY_TIMEZONE,
  2499. expandedStorageKey: 'multipage-hotmail-list-expanded',
  2500. },
  2501. hotmailUtils: {
  2502. filterHotmailAccountsByUsage,
  2503. getHotmailBulkActionLabel,
  2504. getHotmailListToggleLabel,
  2505. parseHotmailImportText,
  2506. shouldClearHotmailCurrentSelection,
  2507. upsertHotmailAccountInList,
  2508. },
  2509. });
  2510. const initHotmailListExpandedState = hotmailManager?.initHotmailListExpandedState
  2511. || (() => { });
  2512. const renderHotmailAccounts = hotmailManager?.renderHotmailAccounts
  2513. || (() => { });
  2514. const bindHotmailEvents = hotmailManager?.bindHotmailEvents
  2515. || (() => { });
  2516. bindHotmailEvents();
  2517. const icloudManager = window.SidepanelIcloudManager?.createIcloudManager({
  2518. dom: {
  2519. btnIcloudBulkDelete,
  2520. btnIcloudBulkPreserve,
  2521. btnIcloudBulkUnpreserve,
  2522. btnIcloudBulkUnused,
  2523. btnIcloudBulkUsed,
  2524. btnIcloudDeleteUsed,
  2525. btnIcloudLoginDone,
  2526. btnIcloudRefresh,
  2527. checkboxIcloudSelectAll,
  2528. icloudList,
  2529. icloudLoginHelp,
  2530. icloudLoginHelpText,
  2531. icloudLoginHelpTitle,
  2532. icloudSection,
  2533. icloudSelectionSummary,
  2534. icloudSummary,
  2535. inputIcloudSearch,
  2536. selectIcloudFilter,
  2537. },
  2538. helpers: {
  2539. copyTextToClipboard,
  2540. escapeHtml,
  2541. openConfirmModal,
  2542. showToast,
  2543. },
  2544. runtime: {
  2545. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2546. },
  2547. });
  2548. const hideIcloudLoginHelp = icloudManager?.hideIcloudLoginHelp
  2549. || (() => { });
  2550. const hasDeletableUsedIcloudAliases = icloudManager?.hasDeletableUsedAliases
  2551. || (() => false);
  2552. const queueIcloudAliasRefresh = icloudManager?.queueIcloudAliasRefresh
  2553. || (() => { });
  2554. const refreshIcloudAliases = icloudManager?.refreshIcloudAliases
  2555. || (async () => { });
  2556. const renderIcloudAliases = icloudManager?.renderIcloudAliases
  2557. || (() => { });
  2558. const resetIcloudManager = icloudManager?.reset
  2559. || (() => { });
  2560. const showIcloudLoginHelp = icloudManager?.showIcloudLoginHelp
  2561. || (() => { });
  2562. const updateIcloudBulkUI = icloudManager?.updateIcloudBulkUI
  2563. || (() => { });
  2564. const bindIcloudEvents = icloudManager?.bindIcloudEvents
  2565. || (() => { });
  2566. bindIcloudEvents();
  2567. const luckmailManager = window.SidepanelLuckmailManager?.createLuckmailManager({
  2568. dom: {
  2569. btnLuckmailBulkDisable,
  2570. btnLuckmailBulkEnable,
  2571. btnLuckmailBulkPreserve,
  2572. btnLuckmailBulkUnpreserve,
  2573. btnLuckmailBulkUnused,
  2574. btnLuckmailBulkUsed,
  2575. btnLuckmailDisableUsed,
  2576. btnLuckmailRefresh,
  2577. checkboxLuckmailSelectAll,
  2578. inputEmail,
  2579. inputLuckmailSearch,
  2580. luckmailList,
  2581. luckmailSection,
  2582. luckmailSelectionSummary,
  2583. luckmailSummary,
  2584. selectLuckmailFilter,
  2585. },
  2586. helpers: {
  2587. copyTextToClipboard,
  2588. escapeHtml,
  2589. formatLuckmailDateTime,
  2590. getLuckmailPreserveTagName,
  2591. normalizeLuckmailProjectName,
  2592. openConfirmModal,
  2593. showToast,
  2594. },
  2595. runtime: {
  2596. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2597. },
  2598. constants: {
  2599. copyIcon: COPY_ICON,
  2600. },
  2601. });
  2602. const queueLuckmailPurchaseRefresh = luckmailManager?.queueLuckmailPurchaseRefresh
  2603. || (() => { });
  2604. const refreshLuckmailPurchases = luckmailManager?.refreshLuckmailPurchases
  2605. || (async () => { });
  2606. const renderLuckmailPurchases = luckmailManager?.renderLuckmailPurchases
  2607. || (() => { });
  2608. const resetLuckmailManager = luckmailManager?.reset
  2609. || (() => { });
  2610. const bindLuckmailEvents = luckmailManager?.bindLuckmailEvents
  2611. || (() => { });
  2612. bindLuckmailEvents();
  2613. const accountRecordsManager = window.SidepanelAccountRecordsManager?.createAccountRecordsManager({
  2614. state: {
  2615. getLatestState: () => latestState,
  2616. syncLatestState,
  2617. },
  2618. dom: {
  2619. accountRecordsList,
  2620. accountRecordsMeta,
  2621. accountRecordsOverlay,
  2622. accountRecordsPageLabel,
  2623. accountRecordsStats,
  2624. btnAccountRecordsNext,
  2625. btnAccountRecordsPrev,
  2626. btnClearAccountRecords,
  2627. btnCloseAccountRecords,
  2628. btnOpenAccountRecords,
  2629. },
  2630. helpers: {
  2631. escapeHtml,
  2632. openConfirmModal,
  2633. showToast,
  2634. },
  2635. runtime: {
  2636. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2637. },
  2638. constants: {
  2639. displayTimeZone: DISPLAY_TIMEZONE,
  2640. pageSize: 10,
  2641. },
  2642. });
  2643. const renderAccountRecords = accountRecordsManager?.render
  2644. || (() => { });
  2645. const bindAccountRecordEvents = accountRecordsManager?.bindEvents
  2646. || (() => { });
  2647. bindAccountRecordEvents();
  2648. renderStepsList();
  2649. async function exportSettingsFile() {
  2650. closeConfigMenu();
  2651. configActionInFlight = true;
  2652. updateConfigMenuControls();
  2653. try {
  2654. await flushPendingSettingsBeforeExport();
  2655. const response = await chrome.runtime.sendMessage({
  2656. type: 'EXPORT_SETTINGS',
  2657. source: 'sidepanel',
  2658. payload: {},
  2659. });
  2660. if (response?.error) {
  2661. throw new Error(response.error);
  2662. }
  2663. if (!response?.fileContent || !response?.fileName) {
  2664. throw new Error('\u672a\u751f\u6210\u53ef\u4e0b\u8f7d\u7684\u914d\u7f6e\u6587\u4ef6\u3002');
  2665. }
  2666. downloadTextFile(response.fileContent, response.fileName);
  2667. showToast('\u914d\u7f6e\u5df2\u5bfc\u51fa\uff1a' + response.fileName, 'success', 2200);
  2668. } catch (err) {
  2669. showToast('\u5bfc\u51fa\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  2670. } finally {
  2671. configActionInFlight = false;
  2672. updateConfigMenuControls();
  2673. }
  2674. }
  2675. async function importSettingsFromFile(file) {
  2676. if (!file) return;
  2677. configActionInFlight = true;
  2678. closeConfigMenu();
  2679. updateConfigMenuControls();
  2680. try {
  2681. await settlePendingSettingsBeforeImport();
  2682. const rawText = await file.text();
  2683. let parsedConfig = null;
  2684. try {
  2685. parsedConfig = JSON.parse(rawText);
  2686. } catch {
  2687. throw new Error('\u914d\u7f6e\u6587\u4ef6\u4e0d\u662f\u6709\u6548\u7684 JSON\u3002');
  2688. }
  2689. const confirmed = await openConfirmModal({
  2690. title: '\u5bfc\u5165\u914d\u7f6e',
  2691. message: '\u786e\u8ba4\u5bfc\u5165\u914d\u7f6e\u6587\u4ef6 "' + file.name + '" \u5417\uff1f\u5bfc\u5165\u540e\u4f1a\u8986\u76d6\u5f53\u524d\u914d\u7f6e\u3002',
  2692. confirmLabel: '\u786e\u8ba4\u8986\u76d6\u5bfc\u5165',
  2693. confirmVariant: 'btn-danger',
  2694. });
  2695. if (!confirmed) {
  2696. return;
  2697. }
  2698. const response = await chrome.runtime.sendMessage({
  2699. type: 'IMPORT_SETTINGS',
  2700. source: 'sidepanel',
  2701. payload: {
  2702. config: parsedConfig,
  2703. },
  2704. });
  2705. if (response?.error) {
  2706. throw new Error(response.error);
  2707. }
  2708. if (!response?.state) {
  2709. throw new Error('\u5bfc\u5165\u540e\u672a\u8fd4\u56de\u6700\u65b0\u914d\u7f6e\u72b6\u6001\u3002');
  2710. }
  2711. applySettingsState(response.state);
  2712. updateStatusDisplay(latestState);
  2713. showToast('\u914d\u7f6e\u5df2\u5bfc\u5165\uff0c\u5f53\u524d\u914d\u7f6e\u5df2\u8986\u76d6\u3002', 'success', 2200);
  2714. } catch (err) {
  2715. showToast('\u5bfc\u5165\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  2716. } finally {
  2717. configActionInFlight = false;
  2718. updateConfigMenuControls();
  2719. if (inputImportSettingsFile) {
  2720. inputImportSettingsFile.value = '';
  2721. }
  2722. }
  2723. }
  2724. function syncPasswordToggleLabel() {
  2725. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  2726. show: '显示密码',
  2727. hide: '隐藏密码',
  2728. });
  2729. }
  2730. function syncVpsUrlToggleLabel() {
  2731. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  2732. show: '显示 CPA 地址',
  2733. hide: '隐藏 CPA 地址',
  2734. });
  2735. }
  2736. function syncVpsPasswordToggleLabel() {
  2737. syncToggleButtonLabel(btnToggleVpsPassword, inputVpsPassword, {
  2738. show: '显示管理密钥',
  2739. hide: '隐藏管理密钥',
  2740. });
  2741. }
  2742. async function maybeTakeoverAutoRun(actionLabel) {
  2743. if (!isAutoRunPausedPhase()) {
  2744. return true;
  2745. }
  2746. const confirmed = await openConfirmModal({
  2747. title: '接管自动',
  2748. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  2749. confirmLabel: '确认接管',
  2750. confirmVariant: 'btn-primary',
  2751. });
  2752. if (!confirmed) {
  2753. return false;
  2754. }
  2755. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  2756. return true;
  2757. }
  2758. async function handleSkipStep(step) {
  2759. if (isAutoRunPausedPhase()) {
  2760. const takeoverResponse = await chrome.runtime.sendMessage({
  2761. type: 'TAKEOVER_AUTO_RUN',
  2762. source: 'sidepanel',
  2763. payload: {},
  2764. });
  2765. if (takeoverResponse?.error) {
  2766. throw new Error(takeoverResponse.error);
  2767. }
  2768. }
  2769. const response = await chrome.runtime.sendMessage({
  2770. type: 'SKIP_STEP',
  2771. source: 'sidepanel',
  2772. payload: { step },
  2773. });
  2774. if (response?.error) {
  2775. throw new Error(response.error);
  2776. }
  2777. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  2778. }
  2779. // ============================================================
  2780. // Button Handlers
  2781. // ============================================================
  2782. stepsList?.addEventListener('click', async (event) => {
  2783. const btn = event.target.closest('.step-btn');
  2784. if (!btn) {
  2785. return;
  2786. }
  2787. try {
  2788. const step = Number(btn.dataset.step);
  2789. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  2790. return;
  2791. }
  2792. if (step === 3) {
  2793. if (inputPassword.value !== (latestState?.customPassword || '')) {
  2794. await chrome.runtime.sendMessage({
  2795. type: 'SAVE_SETTING',
  2796. source: 'sidepanel',
  2797. payload: { customPassword: inputPassword.value },
  2798. });
  2799. syncLatestState({ customPassword: inputPassword.value });
  2800. }
  2801. let email = inputEmail.value.trim();
  2802. if (selectMailProvider.value === 'hotmail-api' || isLuckmailProvider()) {
  2803. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  2804. if (response?.error) {
  2805. throw new Error(response.error);
  2806. }
  2807. } else if (false && usesGeneratedAliasMailProvider(selectMailProvider.value)) {
  2808. const emailPrefix = inputEmailPrefix.value.trim();
  2809. if (!emailPrefix) {
  2810. showToast(selectMailProvider.value === GMAIL_PROVIDER ? '请先填写 Gmail 原邮箱。' : '请先填写 2925 邮箱前缀。', 'warn');
  2811. return;
  2812. }
  2813. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, emailPrefix } });
  2814. if (response?.error) {
  2815. throw new Error(response.error);
  2816. }
  2817. } else {
  2818. let email = inputEmail.value.trim();
  2819. if (!email) {
  2820. if (isCustomMailProvider()) {
  2821. showToast('当前邮箱服务为自定义邮箱,请先填写注册邮箱后再执行第 3 步。', 'warn');
  2822. return;
  2823. }
  2824. try {
  2825. email = await fetchGeneratedEmail({ showFailureToast: false });
  2826. } catch (err) {
  2827. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  2828. return;
  2829. }
  2830. }
  2831. if (!validateCurrentRegistrationEmail(email, { showToastOnFailure: true })) {
  2832. return;
  2833. }
  2834. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  2835. if (response?.error) {
  2836. throw new Error(response.error);
  2837. }
  2838. }
  2839. } else {
  2840. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  2841. if (response?.error) {
  2842. throw new Error(response.error);
  2843. }
  2844. }
  2845. } catch (err) {
  2846. showToast(err.message, 'error');
  2847. }
  2848. });
  2849. btnFetchEmail.addEventListener('click', async () => {
  2850. if (selectMailProvider.value === 'hotmail-api' || isLuckmailProvider() || isCustomMailProvider()) {
  2851. return;
  2852. }
  2853. await fetchGeneratedEmail().catch(() => { });
  2854. });
  2855. btnTogglePassword.addEventListener('click', () => {
  2856. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  2857. syncPasswordToggleLabel();
  2858. });
  2859. btnToggleVpsUrl.addEventListener('click', () => {
  2860. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  2861. syncVpsUrlToggleLabel();
  2862. });
  2863. btnToggleVpsPassword.addEventListener('click', () => {
  2864. inputVpsPassword.type = inputVpsPassword.type === 'password' ? 'text' : 'password';
  2865. syncVpsPasswordToggleLabel();
  2866. });
  2867. btnMailLogin?.addEventListener('click', async () => {
  2868. const config = getMailProviderLoginConfig();
  2869. const loginUrl = getMailProviderLoginUrl();
  2870. if (!config || !loginUrl) {
  2871. return;
  2872. }
  2873. try {
  2874. await chrome.tabs.create({ url: loginUrl, active: true });
  2875. } catch (err) {
  2876. showToast(`打开${config.label}失败:${err.message}`, 'error');
  2877. }
  2878. });
  2879. localCpaStep9ModeButtons.forEach((button) => {
  2880. button.addEventListener('click', () => {
  2881. const nextMode = button.dataset.localCpaStep9Mode;
  2882. if (getSelectedLocalCpaStep9Mode() === normalizeLocalCpaStep9Mode(nextMode)) {
  2883. return;
  2884. }
  2885. setLocalCpaStep9Mode(nextMode);
  2886. markSettingsDirty(true);
  2887. saveSettings({ silent: true }).catch(() => { });
  2888. });
  2889. });
  2890. cpaCallbackModeButtons.forEach((button) => {
  2891. button.addEventListener('click', () => {
  2892. const nextMode = button.dataset.cpaCallbackMode;
  2893. if (getSelectedCpaCallbackMode() === normalizeCpaCallbackMode(nextMode)) {
  2894. return;
  2895. }
  2896. setCpaCallbackMode(nextMode);
  2897. markSettingsDirty(true);
  2898. saveSettings({ silent: true }).catch(() => { });
  2899. });
  2900. });
  2901. hotmailServiceModeButtons.forEach((button) => {
  2902. button.addEventListener('click', () => {
  2903. if (button.disabled) {
  2904. return;
  2905. }
  2906. const nextMode = button.dataset.hotmailServiceMode;
  2907. if (getSelectedHotmailServiceMode() === normalizeHotmailServiceMode(nextMode)) {
  2908. return;
  2909. }
  2910. setHotmailServiceMode(nextMode);
  2911. updateMailProviderUI();
  2912. markSettingsDirty(true);
  2913. saveSettings({ silent: true }).catch(() => { });
  2914. });
  2915. });
  2916. btnSaveSettings.addEventListener('click', async () => {
  2917. if (!settingsDirty) {
  2918. showToast('配置已是最新', 'info', 1400);
  2919. return;
  2920. }
  2921. await saveSettings({ silent: false }).catch(() => { });
  2922. });
  2923. btnStop.addEventListener('click', async () => {
  2924. btnStop.disabled = true;
  2925. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  2926. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  2927. });
  2928. btnConfigMenu?.addEventListener('click', (event) => {
  2929. event.stopPropagation();
  2930. toggleConfigMenu();
  2931. });
  2932. configMenu?.addEventListener('click', (event) => {
  2933. event.stopPropagation();
  2934. });
  2935. btnExportSettings?.addEventListener('click', async () => {
  2936. if (configActionInFlight || settingsSaveInFlight) {
  2937. return;
  2938. }
  2939. await exportSettingsFile();
  2940. });
  2941. btnImportSettings?.addEventListener('click', async () => {
  2942. if (configActionInFlight || settingsSaveInFlight) {
  2943. return;
  2944. }
  2945. closeConfigMenu();
  2946. if (inputImportSettingsFile) {
  2947. inputImportSettingsFile.value = '';
  2948. inputImportSettingsFile.click();
  2949. }
  2950. });
  2951. inputImportSettingsFile?.addEventListener('change', async () => {
  2952. const file = inputImportSettingsFile.files?.[0] || null;
  2953. await importSettingsFromFile(file);
  2954. });
  2955. autoStartModal?.addEventListener('click', (event) => {
  2956. if (event.target === autoStartModal) {
  2957. resolveModalChoice(null);
  2958. }
  2959. });
  2960. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  2961. // Auto Run
  2962. btnAutoRun.addEventListener('click', async () => {
  2963. try {
  2964. const totalRuns = getRunCountValue();
  2965. let mode = 'restart';
  2966. const autoRunSkipFailures = inputAutoSkipFailures.checked;
  2967. const fallbackThreadIntervalMinutes = normalizeAutoRunThreadIntervalMinutes(
  2968. inputAutoSkipFailuresThreadIntervalMinutes.value
  2969. );
  2970. inputAutoSkipFailuresThreadIntervalMinutes.value = String(fallbackThreadIntervalMinutes);
  2971. if (shouldOfferAutoModeChoice()) {
  2972. const startStep = getFirstUnfinishedStep();
  2973. const runningStep = getRunningSteps()[0] ?? null;
  2974. const choice = await openAutoStartChoiceDialog(startStep, { runningStep });
  2975. if (!choice) {
  2976. return;
  2977. }
  2978. mode = choice;
  2979. }
  2980. if (shouldWarnAutoRunFallbackRisk(totalRuns, autoRunSkipFailures)
  2981. && !isAutoRunFallbackRiskPromptDismissed()) {
  2982. const result = await openAutoRunFallbackRiskConfirmModal(totalRuns, fallbackThreadIntervalMinutes);
  2983. if (!result.confirmed) {
  2984. return;
  2985. }
  2986. if (result.dismissPrompt) {
  2987. setAutoRunFallbackRiskPromptDismissed(true);
  2988. }
  2989. }
  2990. btnAutoRun.disabled = true;
  2991. inputRunCount.disabled = true;
  2992. const delayEnabled = inputAutoDelayEnabled.checked;
  2993. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  2994. inputAutoDelayMinutes.value = String(delayMinutes);
  2995. btnAutoRun.innerHTML = delayEnabled
  2996. ? '<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> 计划中...'
  2997. : '<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> 运行中...';
  2998. const response = await chrome.runtime.sendMessage({
  2999. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  3000. source: 'sidepanel',
  3001. payload: {
  3002. totalRuns,
  3003. delayMinutes,
  3004. autoRunSkipFailures,
  3005. mode,
  3006. },
  3007. });
  3008. if (response?.error) {
  3009. throw new Error(response.error);
  3010. }
  3011. } catch (err) {
  3012. setDefaultAutoRunButton();
  3013. inputRunCount.disabled = false;
  3014. showToast(err.message, 'error');
  3015. }
  3016. });
  3017. btnAutoContinue.addEventListener('click', async () => {
  3018. const email = inputEmail.value.trim();
  3019. if (!email) {
  3020. showToast(
  3021. isCustomMailProvider() ? '请先填写自定义注册邮箱。' : '请先获取或粘贴邮箱。',
  3022. 'warn'
  3023. );
  3024. return;
  3025. }
  3026. autoContinueBar.style.display = 'none';
  3027. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  3028. });
  3029. btnAutoRunNow?.addEventListener('click', async () => {
  3030. try {
  3031. btnAutoRunNow.disabled = true;
  3032. const waitingInterval = currentAutoRun.phase === 'waiting_interval';
  3033. await chrome.runtime.sendMessage({
  3034. type: waitingInterval ? 'SKIP_AUTO_RUN_COUNTDOWN' : 'START_SCHEDULED_AUTO_RUN_NOW',
  3035. source: 'sidepanel',
  3036. payload: {},
  3037. });
  3038. if (waitingInterval) {
  3039. showToast('已跳过当前倒计时,自动流程将立即继续。', 'info', 1800);
  3040. }
  3041. } catch (err) {
  3042. showToast(err.message, 'error');
  3043. } finally {
  3044. btnAutoRunNow.disabled = false;
  3045. }
  3046. });
  3047. btnAutoCancelSchedule?.addEventListener('click', async () => {
  3048. try {
  3049. btnAutoCancelSchedule.disabled = true;
  3050. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  3051. showToast('已取消倒计时计划。', 'info', 1800);
  3052. } catch (err) {
  3053. showToast(err.message, 'error');
  3054. } finally {
  3055. btnAutoCancelSchedule.disabled = false;
  3056. }
  3057. });
  3058. // Reset
  3059. btnReset.addEventListener('click', async () => {
  3060. const confirmed = await openConfirmModal({
  3061. title: '重置流程',
  3062. message: '确认重置全部步骤和数据吗?',
  3063. confirmLabel: '确认重置',
  3064. confirmVariant: 'btn-danger',
  3065. });
  3066. if (!confirmed) {
  3067. return;
  3068. }
  3069. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  3070. syncLatestState({
  3071. stepStatuses: STEP_DEFAULT_STATUSES,
  3072. currentHotmailAccountId: null,
  3073. currentLuckmailPurchase: null,
  3074. currentLuckmailMailCursor: null,
  3075. email: null,
  3076. });
  3077. syncAutoRunState({
  3078. autoRunning: false,
  3079. autoRunPhase: 'idle',
  3080. autoRunCurrentRun: 0,
  3081. autoRunTotalRuns: 1,
  3082. autoRunAttemptRun: 0,
  3083. scheduledAutoRunAt: null,
  3084. autoRunCountdownAt: null,
  3085. autoRunCountdownTitle: '',
  3086. autoRunCountdownNote: '',
  3087. });
  3088. displayOauthUrl.textContent = '等待中...';
  3089. displayOauthUrl.classList.remove('has-value');
  3090. displayLocalhostUrl.textContent = '等待中...';
  3091. displayLocalhostUrl.classList.remove('has-value');
  3092. inputEmail.value = '';
  3093. displayStatus.textContent = '就绪';
  3094. statusBar.className = 'status-bar';
  3095. logArea.innerHTML = '';
  3096. resetIcloudManager();
  3097. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  3098. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  3099. setDefaultAutoRunButton();
  3100. applyAutoRunStatus(currentAutoRun);
  3101. markSettingsDirty(false);
  3102. updateStopButtonState(false);
  3103. updateButtonStates();
  3104. updateProgressCounter();
  3105. renderHotmailAccounts();
  3106. resetLuckmailManager();
  3107. if (isLuckmailProvider()) {
  3108. queueLuckmailPurchaseRefresh();
  3109. }
  3110. });
  3111. // Clear log
  3112. btnClearLog.addEventListener('click', () => {
  3113. logArea.innerHTML = '';
  3114. });
  3115. // Save settings on change
  3116. inputEmail.addEventListener('change', async () => {
  3117. if (selectMailProvider.value === 'hotmail-api' || isLuckmailProvider()) {
  3118. return;
  3119. }
  3120. const email = inputEmail.value.trim();
  3121. inputEmail.value = email;
  3122. try {
  3123. if (email) {
  3124. if (!validateCurrentRegistrationEmail(email, { showToastOnFailure: true })) {
  3125. return;
  3126. }
  3127. const response = await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  3128. if (response?.error) {
  3129. throw new Error(response.error);
  3130. }
  3131. } else {
  3132. await setRuntimeEmailState(null);
  3133. }
  3134. } catch (err) {
  3135. showToast(err.message, 'error');
  3136. }
  3137. });
  3138. inputEmail.addEventListener('input', updateButtonStates);
  3139. inputVpsUrl.addEventListener('input', () => {
  3140. markSettingsDirty(true);
  3141. scheduleSettingsAutoSave();
  3142. });
  3143. inputVpsUrl.addEventListener('blur', () => {
  3144. saveSettings({ silent: true }).catch(() => { });
  3145. });
  3146. inputVpsPassword.addEventListener('input', () => {
  3147. markSettingsDirty(true);
  3148. scheduleSettingsAutoSave();
  3149. });
  3150. inputVpsPassword.addEventListener('blur', () => {
  3151. saveSettings({ silent: true }).catch(() => { });
  3152. });
  3153. [inputHotmailRemoteBaseUrl, inputHotmailLocalBaseUrl].forEach((input) => {
  3154. input?.addEventListener('input', () => {
  3155. markSettingsDirty(true);
  3156. scheduleSettingsAutoSave();
  3157. });
  3158. input?.addEventListener('blur', () => {
  3159. saveSettings({ silent: true }).catch(() => { });
  3160. });
  3161. });
  3162. [inputLuckmailApiKey, inputLuckmailBaseUrl, inputLuckmailDomain].forEach((input) => {
  3163. input?.addEventListener('input', () => {
  3164. markSettingsDirty(true);
  3165. scheduleSettingsAutoSave();
  3166. });
  3167. input?.addEventListener('blur', () => {
  3168. saveSettings({ silent: true }).catch(() => { });
  3169. });
  3170. });
  3171. selectLuckmailEmailType?.addEventListener('change', () => {
  3172. markSettingsDirty(true);
  3173. saveSettings({ silent: true }).catch(() => { });
  3174. });
  3175. inputPassword.addEventListener('input', () => {
  3176. markSettingsDirty(true);
  3177. updateButtonStates();
  3178. scheduleSettingsAutoSave();
  3179. });
  3180. inputPassword.addEventListener('blur', () => {
  3181. saveSettings({ silent: true }).catch(() => { });
  3182. });
  3183. selectMailProvider.addEventListener('change', async () => {
  3184. const previousProvider = latestState?.mailProvider || '';
  3185. const previousMail2925Mode = latestState?.mail2925Mode;
  3186. const nextProvider = selectMailProvider.value;
  3187. syncManagedAliasBaseEmailDraftFromInput(previousProvider);
  3188. setManagedAliasBaseEmailInputForProvider(nextProvider, latestState);
  3189. updateMailProviderUI();
  3190. const leavingHotmail = previousProvider === 'hotmail-api'
  3191. && nextProvider !== 'hotmail-api'
  3192. && isCurrentEmailManagedByHotmail();
  3193. const leavingLuckmail = previousProvider === LUCKMAIL_PROVIDER
  3194. && nextProvider !== LUCKMAIL_PROVIDER
  3195. && isCurrentEmailManagedByLuckmail();
  3196. const leavingGeneratedAlias = (
  3197. previousProvider !== nextProvider
  3198. || (previousProvider === '2925' && normalizeMail2925Mode(previousMail2925Mode) !== getSelectedMail2925Mode())
  3199. ) && usesGeneratedAliasMailProvider(previousProvider, previousMail2925Mode)
  3200. && isCurrentEmailManagedByGeneratedAlias(previousProvider, latestState, previousMail2925Mode);
  3201. if (leavingHotmail || leavingLuckmail || leavingGeneratedAlias) {
  3202. await clearRegistrationEmail({ silent: true }).catch(() => { });
  3203. }
  3204. if (nextProvider === LUCKMAIL_PROVIDER) {
  3205. queueLuckmailPurchaseRefresh();
  3206. }
  3207. markSettingsDirty(true);
  3208. saveSettings({ silent: true }).catch(() => { });
  3209. });
  3210. mail2925ModeButtons.forEach((button) => {
  3211. button.addEventListener('click', async () => {
  3212. const nextMode = normalizeMail2925Mode(button.dataset.mail2925Mode);
  3213. const previousMode = normalizeMail2925Mode(latestState?.mail2925Mode);
  3214. if (nextMode === getSelectedMail2925Mode()) {
  3215. return;
  3216. }
  3217. setMail2925Mode(nextMode);
  3218. updateMailProviderUI();
  3219. const leavingGeneratedAlias = selectMailProvider.value === '2925'
  3220. && previousMode === MAIL_2925_MODE_PROVIDE
  3221. && nextMode !== MAIL_2925_MODE_PROVIDE
  3222. && isCurrentEmailManagedByGeneratedAlias('2925', latestState, previousMode);
  3223. if (leavingGeneratedAlias) {
  3224. await clearRegistrationEmail({ silent: true }).catch(() => { });
  3225. }
  3226. markSettingsDirty(true);
  3227. saveSettings({ silent: true }).catch(() => { });
  3228. });
  3229. });
  3230. selectEmailGenerator.addEventListener('change', () => {
  3231. updateMailProviderUI();
  3232. clearRegistrationEmail({ silent: true }).catch(() => { });
  3233. markSettingsDirty(true);
  3234. saveSettings({ silent: true }).catch(() => { });
  3235. });
  3236. selectIcloudHostPreference?.addEventListener('change', () => {
  3237. markSettingsDirty(true);
  3238. saveSettings({ silent: true }).catch(() => { });
  3239. if (getSelectedEmailGenerator() === 'icloud') {
  3240. queueIcloudAliasRefresh();
  3241. }
  3242. });
  3243. checkboxAutoDeleteIcloud?.addEventListener('change', () => {
  3244. markSettingsDirty(true);
  3245. saveSettings({ silent: true }).catch(() => { });
  3246. });
  3247. selectPanelMode.addEventListener('change', () => {
  3248. updatePanelModeUI();
  3249. markSettingsDirty(true);
  3250. saveSettings({ silent: true }).catch(() => { });
  3251. });
  3252. selectCfDomain.addEventListener('change', () => {
  3253. if (selectCfDomain.disabled) {
  3254. return;
  3255. }
  3256. markSettingsDirty(true);
  3257. saveSettings({ silent: true }).catch(() => { });
  3258. });
  3259. selectTempEmailDomain.addEventListener('change', () => {
  3260. if (selectTempEmailDomain.disabled) {
  3261. return;
  3262. }
  3263. markSettingsDirty(true);
  3264. saveSettings({ silent: true }).catch(() => { });
  3265. });
  3266. btnCfDomainMode.addEventListener('click', async () => {
  3267. try {
  3268. if (!cloudflareDomainEditMode) {
  3269. setCloudflareDomainEditMode(true, { clearInput: true });
  3270. return;
  3271. }
  3272. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  3273. if (!newDomain) {
  3274. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  3275. inputCfDomain.focus();
  3276. return;
  3277. }
  3278. const { domains } = getCloudflareDomainsFromState();
  3279. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  3280. } catch (err) {
  3281. showToast(err.message, 'error');
  3282. }
  3283. });
  3284. btnTempEmailDomainMode.addEventListener('click', async () => {
  3285. try {
  3286. if (!cloudflareTempEmailDomainEditMode) {
  3287. setCloudflareTempEmailDomainEditMode(true, { clearInput: true });
  3288. return;
  3289. }
  3290. const newDomain = normalizeCloudflareTempEmailDomainValue(inputTempEmailDomain.value);
  3291. if (!newDomain) {
  3292. showToast('请输入有效的 Cloudflare Temp Email 域名。', 'warn');
  3293. inputTempEmailDomain.focus();
  3294. return;
  3295. }
  3296. const { domains } = getCloudflareTempEmailDomainsFromState();
  3297. await saveCloudflareTempEmailDomainSettings([...domains, newDomain], newDomain);
  3298. } catch (err) {
  3299. showToast(err.message, 'error');
  3300. }
  3301. });
  3302. inputCfDomain.addEventListener('keydown', (event) => {
  3303. if (event.key === 'Enter') {
  3304. event.preventDefault();
  3305. btnCfDomainMode.click();
  3306. }
  3307. });
  3308. inputTempEmailDomain.addEventListener('keydown', (event) => {
  3309. if (event.key === 'Enter') {
  3310. event.preventDefault();
  3311. btnTempEmailDomainMode.click();
  3312. }
  3313. });
  3314. inputSub2ApiUrl.addEventListener('input', () => {
  3315. markSettingsDirty(true);
  3316. scheduleSettingsAutoSave();
  3317. });
  3318. inputSub2ApiUrl.addEventListener('blur', () => {
  3319. saveSettings({ silent: true }).catch(() => { });
  3320. });
  3321. inputSub2ApiEmail.addEventListener('input', () => {
  3322. markSettingsDirty(true);
  3323. scheduleSettingsAutoSave();
  3324. });
  3325. inputSub2ApiEmail.addEventListener('blur', () => {
  3326. saveSettings({ silent: true }).catch(() => { });
  3327. });
  3328. inputSub2ApiPassword.addEventListener('input', () => {
  3329. markSettingsDirty(true);
  3330. scheduleSettingsAutoSave();
  3331. });
  3332. inputSub2ApiPassword.addEventListener('blur', () => {
  3333. saveSettings({ silent: true }).catch(() => { });
  3334. });
  3335. inputSub2ApiGroup.addEventListener('input', () => {
  3336. markSettingsDirty(true);
  3337. scheduleSettingsAutoSave();
  3338. });
  3339. inputSub2ApiGroup.addEventListener('blur', () => {
  3340. saveSettings({ silent: true }).catch(() => { });
  3341. });
  3342. inputEmailPrefix.addEventListener('input', () => {
  3343. maybeClearGeneratedAliasAfterEmailPrefixChange().catch(() => { });
  3344. syncManagedAliasBaseEmailDraftFromInput();
  3345. markSettingsDirty(true);
  3346. scheduleSettingsAutoSave();
  3347. });
  3348. inputEmailPrefix.addEventListener('blur', () => {
  3349. maybeClearGeneratedAliasAfterEmailPrefixChange().catch(() => {});
  3350. syncManagedAliasBaseEmailDraftFromInput();
  3351. saveSettings({ silent: true }).catch(() => {});
  3352. });
  3353. inputInbucketMailbox.addEventListener('input', () => {
  3354. markSettingsDirty(true);
  3355. scheduleSettingsAutoSave();
  3356. });
  3357. inputInbucketMailbox.addEventListener('blur', () => {
  3358. saveSettings({ silent: true }).catch(() => { });
  3359. });
  3360. inputInbucketHost.addEventListener('input', () => {
  3361. markSettingsDirty(true);
  3362. scheduleSettingsAutoSave();
  3363. });
  3364. inputInbucketHost.addEventListener('blur', () => {
  3365. saveSettings({ silent: true }).catch(() => { });
  3366. });
  3367. inputRunCount.addEventListener('input', () => {
  3368. updateFallbackThreadIntervalInputState();
  3369. });
  3370. inputRunCount.addEventListener('blur', () => {
  3371. inputRunCount.value = String(getRunCountValue());
  3372. updateFallbackThreadIntervalInputState();
  3373. });
  3374. inputAutoSkipFailures.addEventListener('change', async () => {
  3375. if (inputAutoSkipFailures.checked && !isAutoSkipFailuresPromptDismissed()) {
  3376. const result = await openAutoSkipFailuresConfirmModal();
  3377. if (!result.confirmed) {
  3378. inputAutoSkipFailures.checked = false;
  3379. updateFallbackThreadIntervalInputState();
  3380. return;
  3381. }
  3382. if (result.dismissPrompt) {
  3383. setAutoSkipFailuresPromptDismissed(true);
  3384. }
  3385. }
  3386. updateFallbackThreadIntervalInputState();
  3387. markSettingsDirty(true);
  3388. saveSettings({ silent: true }).catch(() => { });
  3389. });
  3390. inputTempEmailBaseUrl.addEventListener('input', () => {
  3391. markSettingsDirty(true);
  3392. scheduleSettingsAutoSave();
  3393. });
  3394. inputTempEmailBaseUrl.addEventListener('blur', () => {
  3395. inputTempEmailBaseUrl.value = normalizeCloudflareTempEmailBaseUrlValue(inputTempEmailBaseUrl.value);
  3396. saveSettings({ silent: true }).catch(() => { });
  3397. });
  3398. inputTempEmailAdminAuth.addEventListener('input', () => {
  3399. markSettingsDirty(true);
  3400. scheduleSettingsAutoSave();
  3401. });
  3402. inputTempEmailAdminAuth.addEventListener('blur', () => {
  3403. saveSettings({ silent: true }).catch(() => { });
  3404. });
  3405. inputTempEmailCustomAuth.addEventListener('input', () => {
  3406. markSettingsDirty(true);
  3407. scheduleSettingsAutoSave();
  3408. });
  3409. inputTempEmailCustomAuth.addEventListener('blur', () => {
  3410. saveSettings({ silent: true }).catch(() => { });
  3411. });
  3412. inputTempEmailReceiveMailbox.addEventListener('input', () => {
  3413. markSettingsDirty(true);
  3414. scheduleSettingsAutoSave();
  3415. });
  3416. inputTempEmailReceiveMailbox.addEventListener('blur', () => {
  3417. inputTempEmailReceiveMailbox.value = normalizeCloudflareTempEmailReceiveMailboxValue(inputTempEmailReceiveMailbox.value);
  3418. saveSettings({ silent: true }).catch(() => { });
  3419. });
  3420. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('input', () => {
  3421. markSettingsDirty(true);
  3422. scheduleSettingsAutoSave();
  3423. });
  3424. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('blur', () => {
  3425. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  3426. normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value)
  3427. );
  3428. saveSettings({ silent: true }).catch(() => { });
  3429. });
  3430. inputAutoDelayEnabled.addEventListener('change', () => {
  3431. updateAutoDelayInputState();
  3432. markSettingsDirty(true);
  3433. saveSettings({ silent: true }).catch(() => { });
  3434. });
  3435. inputAutoDelayMinutes.addEventListener('input', () => {
  3436. markSettingsDirty(true);
  3437. scheduleSettingsAutoSave();
  3438. });
  3439. inputAutoDelayMinutes.addEventListener('blur', () => {
  3440. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  3441. saveSettings({ silent: true }).catch(() => { });
  3442. });
  3443. inputAccountRunHistoryTextEnabled?.addEventListener('change', () => {
  3444. updateAccountRunHistorySettingsUI();
  3445. markSettingsDirty(true);
  3446. saveSettings({ silent: true }).catch(() => { });
  3447. });
  3448. inputAccountRunHistoryHelperBaseUrl?.addEventListener('input', () => {
  3449. markSettingsDirty(true);
  3450. scheduleSettingsAutoSave();
  3451. });
  3452. inputAccountRunHistoryHelperBaseUrl?.addEventListener('blur', () => {
  3453. inputAccountRunHistoryHelperBaseUrl.value = normalizeAccountRunHistoryHelperBaseUrlValue(inputAccountRunHistoryHelperBaseUrl.value);
  3454. saveSettings({ silent: true }).catch(() => { });
  3455. });
  3456. function syncAutoStepDelayInputs() {
  3457. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(inputAutoStepDelaySeconds.value);
  3458. }
  3459. inputAutoStepDelaySeconds.addEventListener('input', () => {
  3460. markSettingsDirty(true);
  3461. scheduleSettingsAutoSave();
  3462. });
  3463. inputAutoStepDelaySeconds.addEventListener('blur', () => {
  3464. syncAutoStepDelayInputs();
  3465. saveSettings({ silent: true }).catch(() => { });
  3466. });
  3467. inputVerificationResendCount?.addEventListener('input', () => {
  3468. markSettingsDirty(true);
  3469. scheduleSettingsAutoSave();
  3470. });
  3471. inputVerificationResendCount?.addEventListener('blur', () => {
  3472. inputVerificationResendCount.value = String(
  3473. normalizeVerificationResendCount(
  3474. inputVerificationResendCount.value,
  3475. DEFAULT_VERIFICATION_RESEND_COUNT
  3476. )
  3477. );
  3478. saveSettings({ silent: true }).catch(() => { });
  3479. });
  3480. // ============================================================
  3481. // Listen for Background broadcasts
  3482. // ============================================================
  3483. chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  3484. switch (message.type) {
  3485. case 'REQUEST_CUSTOM_VERIFICATION_BYPASS_CONFIRMATION': {
  3486. (async () => {
  3487. const step = Number(message.payload?.step);
  3488. const promptCopy = getCustomVerificationPromptCopy(step);
  3489. const confirmed = await openConfirmModal({
  3490. title: promptCopy.title,
  3491. message: promptCopy.message,
  3492. confirmLabel: '确认跳过',
  3493. confirmVariant: 'btn-danger',
  3494. alert: promptCopy.alert,
  3495. });
  3496. sendResponse({ confirmed });
  3497. })().catch((err) => {
  3498. sendResponse({ error: err.message });
  3499. });
  3500. return true;
  3501. }
  3502. case 'LOG_ENTRY':
  3503. appendLog(message.payload);
  3504. if (message.payload.level === 'error') {
  3505. showToast(message.payload.message, 'error');
  3506. }
  3507. break;
  3508. case 'STEP_STATUS_CHANGED': {
  3509. const { step, status } = message.payload;
  3510. updateStepUI(step, status);
  3511. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  3512. syncLatestState(state);
  3513. syncAutoRunState(state);
  3514. updateStatusDisplay(latestState);
  3515. updateButtonStates();
  3516. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  3517. syncPasswordField(state);
  3518. if (state.oauthUrl) {
  3519. displayOauthUrl.textContent = state.oauthUrl;
  3520. displayOauthUrl.classList.add('has-value');
  3521. }
  3522. if (state.localhostUrl) {
  3523. displayLocalhostUrl.textContent = state.localhostUrl;
  3524. displayLocalhostUrl.classList.add('has-value');
  3525. }
  3526. }
  3527. }
  3528. ).catch(() => { });
  3529. break;
  3530. }
  3531. case 'AUTO_RUN_RESET': {
  3532. // Full UI reset for next run
  3533. syncLatestState({
  3534. oauthUrl: null,
  3535. localhostUrl: null,
  3536. email: null,
  3537. password: null,
  3538. stepStatuses: STEP_DEFAULT_STATUSES,
  3539. logs: [],
  3540. scheduledAutoRunAt: null,
  3541. autoRunCountdownAt: null,
  3542. autoRunCountdownTitle: '',
  3543. autoRunCountdownNote: '',
  3544. });
  3545. displayOauthUrl.textContent = '等待中...';
  3546. displayOauthUrl.classList.remove('has-value');
  3547. displayLocalhostUrl.textContent = '等待中...';
  3548. displayLocalhostUrl.classList.remove('has-value');
  3549. inputEmail.value = '';
  3550. displayStatus.textContent = '就绪';
  3551. statusBar.className = 'status-bar';
  3552. logArea.innerHTML = '';
  3553. resetIcloudManager();
  3554. resetLuckmailManager();
  3555. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  3556. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  3557. syncAutoRunState({
  3558. autoRunning: false,
  3559. autoRunPhase: 'idle',
  3560. autoRunCurrentRun: 0,
  3561. autoRunTotalRuns: 1,
  3562. autoRunAttemptRun: 0,
  3563. scheduledAutoRunAt: null,
  3564. autoRunCountdownAt: null,
  3565. autoRunCountdownTitle: '',
  3566. autoRunCountdownNote: '',
  3567. });
  3568. applyAutoRunStatus(currentAutoRun);
  3569. updateProgressCounter();
  3570. updateButtonStates();
  3571. renderHotmailAccounts();
  3572. if (isLuckmailProvider()) {
  3573. queueLuckmailPurchaseRefresh();
  3574. }
  3575. break;
  3576. }
  3577. case 'DATA_UPDATED': {
  3578. syncLatestState(message.payload);
  3579. if (message.payload.email !== undefined) {
  3580. inputEmail.value = message.payload.email || '';
  3581. }
  3582. if (message.payload.password !== undefined) {
  3583. inputPassword.value = message.payload.password || '';
  3584. }
  3585. if (message.payload.localCpaStep9Mode !== undefined) {
  3586. setLocalCpaStep9Mode(message.payload.localCpaStep9Mode);
  3587. }
  3588. if (message.payload.cpaCallbackMode !== undefined) {
  3589. setCpaCallbackMode(message.payload.cpaCallbackMode);
  3590. }
  3591. if (message.payload.oauthUrl !== undefined) {
  3592. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  3593. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  3594. }
  3595. if (message.payload.localhostUrl !== undefined) {
  3596. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  3597. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  3598. }
  3599. if (message.payload.cloudflareTempEmailBaseUrl !== undefined) {
  3600. inputTempEmailBaseUrl.value = message.payload.cloudflareTempEmailBaseUrl || '';
  3601. }
  3602. if (message.payload.cloudflareTempEmailAdminAuth !== undefined) {
  3603. inputTempEmailAdminAuth.value = message.payload.cloudflareTempEmailAdminAuth || '';
  3604. }
  3605. if (message.payload.cloudflareTempEmailCustomAuth !== undefined) {
  3606. inputTempEmailCustomAuth.value = message.payload.cloudflareTempEmailCustomAuth || '';
  3607. }
  3608. if (message.payload.cloudflareTempEmailReceiveMailbox !== undefined) {
  3609. inputTempEmailReceiveMailbox.value = message.payload.cloudflareTempEmailReceiveMailbox || '';
  3610. }
  3611. if (message.payload.cloudflareTempEmailDomain !== undefined || message.payload.cloudflareTempEmailDomains !== undefined) {
  3612. renderCloudflareTempEmailDomainOptions(message.payload.cloudflareTempEmailDomain || latestState?.cloudflareTempEmailDomain || '');
  3613. }
  3614. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  3615. renderHotmailAccounts();
  3616. if (selectMailProvider.value === 'hotmail-api') {
  3617. inputEmail.value = getCurrentHotmailEmail();
  3618. }
  3619. }
  3620. if (message.payload.luckmailApiKey !== undefined) {
  3621. inputLuckmailApiKey.value = message.payload.luckmailApiKey || '';
  3622. }
  3623. if (message.payload.luckmailBaseUrl !== undefined) {
  3624. inputLuckmailBaseUrl.value = normalizeLuckmailBaseUrl(message.payload.luckmailBaseUrl);
  3625. }
  3626. if (message.payload.luckmailEmailType !== undefined) {
  3627. selectLuckmailEmailType.value = normalizeLuckmailEmailType(message.payload.luckmailEmailType);
  3628. }
  3629. if (message.payload.luckmailDomain !== undefined) {
  3630. inputLuckmailDomain.value = message.payload.luckmailDomain || '';
  3631. }
  3632. if (message.payload.luckmailUsedPurchases !== undefined && isLuckmailProvider()) {
  3633. queueLuckmailPurchaseRefresh();
  3634. }
  3635. if (message.payload.currentLuckmailPurchase !== undefined && isLuckmailProvider()) {
  3636. inputEmail.value = getCurrentLuckmailEmail();
  3637. queueLuckmailPurchaseRefresh();
  3638. }
  3639. if (message.payload.autoDeleteUsedIcloudAlias !== undefined && checkboxAutoDeleteIcloud) {
  3640. checkboxAutoDeleteIcloud.checked = Boolean(message.payload.autoDeleteUsedIcloudAlias);
  3641. }
  3642. if (message.payload.accountRunHistoryTextEnabled !== undefined && inputAccountRunHistoryTextEnabled) {
  3643. inputAccountRunHistoryTextEnabled.checked = Boolean(message.payload.accountRunHistoryTextEnabled);
  3644. updateAccountRunHistorySettingsUI();
  3645. }
  3646. if (message.payload.accountRunHistoryHelperBaseUrl !== undefined && inputAccountRunHistoryHelperBaseUrl) {
  3647. inputAccountRunHistoryHelperBaseUrl.value = normalizeAccountRunHistoryHelperBaseUrlValue(message.payload.accountRunHistoryHelperBaseUrl);
  3648. }
  3649. if (message.payload.icloudHostPreference !== undefined && selectIcloudHostPreference) {
  3650. const hostPreference = String(message.payload.icloudHostPreference || '').trim().toLowerCase();
  3651. selectIcloudHostPreference.value = hostPreference === 'icloud.com'
  3652. ? 'icloud.com'
  3653. : (hostPreference === 'icloud.com.cn' ? 'icloud.com.cn' : 'auto');
  3654. }
  3655. if (message.payload.autoRunSkipFailures !== undefined) {
  3656. inputAutoSkipFailures.checked = Boolean(message.payload.autoRunSkipFailures);
  3657. updateFallbackThreadIntervalInputState();
  3658. }
  3659. if (message.payload.autoRunDelayEnabled !== undefined) {
  3660. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  3661. updateAutoDelayInputState();
  3662. }
  3663. if (message.payload.autoRunDelayMinutes !== undefined) {
  3664. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  3665. }
  3666. if (message.payload.autoRunFallbackThreadIntervalMinutes !== undefined) {
  3667. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  3668. normalizeAutoRunThreadIntervalMinutes(message.payload.autoRunFallbackThreadIntervalMinutes)
  3669. );
  3670. updateFallbackThreadIntervalInputState();
  3671. }
  3672. if (message.payload.autoStepDelaySeconds !== undefined) {
  3673. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(message.payload.autoStepDelaySeconds);
  3674. }
  3675. if (
  3676. (
  3677. message.payload.verificationResendCount !== undefined
  3678. || message.payload.signupVerificationResendCount !== undefined
  3679. || message.payload.loginVerificationResendCount !== undefined
  3680. )
  3681. && inputVerificationResendCount
  3682. ) {
  3683. const nextVerificationResendCount = message.payload.verificationResendCount !== undefined
  3684. ? message.payload.verificationResendCount
  3685. : (message.payload.signupVerificationResendCount ?? message.payload.loginVerificationResendCount);
  3686. inputVerificationResendCount.value = String(
  3687. normalizeVerificationResendCount(
  3688. nextVerificationResendCount,
  3689. DEFAULT_VERIFICATION_RESEND_COUNT
  3690. )
  3691. );
  3692. }
  3693. break;
  3694. }
  3695. case 'ICLOUD_LOGIN_REQUIRED': {
  3696. const loginMessage = '需要登录 iCloud,我已经为你打开登录页。';
  3697. showToast(loginMessage, 'warn', 5000);
  3698. if (icloudSummary) {
  3699. icloudSummary.textContent = loginMessage;
  3700. }
  3701. showIcloudLoginHelp(message.payload || {});
  3702. break;
  3703. }
  3704. case 'ICLOUD_ALIASES_CHANGED': {
  3705. queueIcloudAliasRefresh();
  3706. break;
  3707. }
  3708. case 'AUTO_RUN_STATUS': {
  3709. syncLatestState({
  3710. autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying', 'waiting_interval'].includes(message.payload.phase),
  3711. autoRunPhase: message.payload.phase,
  3712. autoRunCurrentRun: message.payload.currentRun,
  3713. autoRunTotalRuns: message.payload.totalRuns,
  3714. autoRunAttemptRun: message.payload.attemptRun,
  3715. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  3716. autoRunCountdownAt: message.payload.countdownAt ?? null,
  3717. autoRunCountdownTitle: message.payload.countdownTitle ?? '',
  3718. autoRunCountdownNote: message.payload.countdownNote ?? '',
  3719. });
  3720. applyAutoRunStatus(message.payload);
  3721. updateStatusDisplay(latestState);
  3722. updateButtonStates();
  3723. break;
  3724. }
  3725. }
  3726. });
  3727. // ============================================================
  3728. // Theme Toggle
  3729. // ============================================================
  3730. const btnTheme = document.getElementById('btn-theme');
  3731. function setTheme(theme) {
  3732. document.documentElement.setAttribute('data-theme', theme);
  3733. localStorage.setItem('multipage-theme', theme);
  3734. }
  3735. function initTheme() {
  3736. const saved = localStorage.getItem('multipage-theme');
  3737. if (saved) {
  3738. setTheme(saved);
  3739. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  3740. setTheme('dark');
  3741. }
  3742. }
  3743. btnTheme.addEventListener('click', () => {
  3744. const current = document.documentElement.getAttribute('data-theme');
  3745. setTheme(current === 'dark' ? 'light' : 'dark');
  3746. });
  3747. document.addEventListener('click', (event) => {
  3748. if (!configMenuOpen) {
  3749. return;
  3750. }
  3751. if (configMenuShell?.contains(event.target)) {
  3752. return;
  3753. }
  3754. closeConfigMenu();
  3755. });
  3756. document.addEventListener('keydown', (event) => {
  3757. if (event.key === 'Escape' && configMenuOpen) {
  3758. closeConfigMenu();
  3759. }
  3760. });
  3761. // ============================================================
  3762. // Init
  3763. // ============================================================
  3764. initializeManualStepActions();
  3765. initTheme();
  3766. initHotmailListExpandedState();
  3767. updateSaveButtonState();
  3768. updateConfigMenuControls();
  3769. setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
  3770. setCpaCallbackMode(DEFAULT_CPA_CALLBACK_MODE);
  3771. setMail2925Mode(DEFAULT_MAIL_2925_MODE);
  3772. initializeReleaseInfo().catch((err) => {
  3773. console.error('Failed to initialize release info:', err);
  3774. });
  3775. restoreState().then(() => {
  3776. syncPasswordToggleLabel();
  3777. syncVpsUrlToggleLabel();
  3778. syncVpsPasswordToggleLabel();
  3779. updatePanelModeUI();
  3780. updateButtonStates();
  3781. updateStatusDisplay(latestState);
  3782. });