sidepanel.js 151 KB

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