sidepanel.js 147 KB

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