sidepanel.js 151 KB

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