sidepanel.js 152 KB

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