sidepanel.js 149 KB

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