sidepanel.js 152 KB

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