sidepanel.js 151 KB

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