sidepanel.js 148 KB

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