sidepanel.js 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295
  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. autoRunTotalRuns: getRunCountValue(),
  1235. autoRunSkipFailures: inputAutoSkipFailures.checked,
  1236. autoRunFallbackThreadIntervalMinutes: normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value),
  1237. autoRunAddPhonePauseMinutes: normalizeAddPhonePauseMinutes(inputAutoAddPhonePauseMinutes?.value),
  1238. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  1239. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  1240. autoStepDelaySeconds: normalizeAutoStepDelaySeconds(inputAutoStepDelaySeconds.value),
  1241. verificationResendCount: normalizeVerificationResendCount(
  1242. inputVerificationResendCount?.value,
  1243. DEFAULT_VERIFICATION_RESEND_COUNT
  1244. ),
  1245. };
  1246. }
  1247. function normalizeLocalCpaStep9Mode(value = '') {
  1248. return String(value || '').trim().toLowerCase() === 'bypass'
  1249. ? 'bypass'
  1250. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  1251. }
  1252. function normalizeMail2925Mode(value = '') {
  1253. return String(value || '').trim().toLowerCase() === MAIL_2925_MODE_RECEIVE
  1254. ? MAIL_2925_MODE_RECEIVE
  1255. : DEFAULT_MAIL_2925_MODE;
  1256. }
  1257. function normalizeHotmailServiceMode(value = '') {
  1258. if (typeof normalizeHotmailServiceModeFromUtils === 'function') {
  1259. return normalizeHotmailServiceModeFromUtils(value);
  1260. }
  1261. return String(value || '').trim().toLowerCase() === HOTMAIL_SERVICE_MODE_REMOTE
  1262. ? HOTMAIL_SERVICE_MODE_REMOTE
  1263. : HOTMAIL_SERVICE_MODE_LOCAL;
  1264. }
  1265. function normalizeAccountRunHistoryHelperBaseUrlValue(value = '') {
  1266. const trimmed = String(value || '').trim();
  1267. if (!trimmed) {
  1268. return DEFAULT_ACCOUNT_RUN_HISTORY_HELPER_BASE_URL;
  1269. }
  1270. try {
  1271. const parsed = new URL(trimmed);
  1272. if (!['http:', 'https:'].includes(parsed.protocol)) {
  1273. return DEFAULT_ACCOUNT_RUN_HISTORY_HELPER_BASE_URL;
  1274. }
  1275. if (parsed.pathname === '/append-account-log' || parsed.pathname === '/sync-account-run-records') {
  1276. parsed.pathname = '';
  1277. parsed.search = '';
  1278. parsed.hash = '';
  1279. }
  1280. return parsed.toString().replace(/\/$/, '');
  1281. } catch {
  1282. return DEFAULT_ACCOUNT_RUN_HISTORY_HELPER_BASE_URL;
  1283. }
  1284. }
  1285. function getSelectedLocalCpaStep9Mode() {
  1286. const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active'));
  1287. return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode);
  1288. }
  1289. function setLocalCpaStep9Mode(mode) {
  1290. const resolvedMode = normalizeLocalCpaStep9Mode(mode);
  1291. localCpaStep9ModeButtons.forEach((button) => {
  1292. const active = button.dataset.localCpaStep9Mode === resolvedMode;
  1293. button.classList.toggle('is-active', active);
  1294. button.setAttribute('aria-pressed', String(active));
  1295. });
  1296. }
  1297. function getSelectedMail2925Mode() {
  1298. const activeButton = mail2925ModeButtons.find((button) => button.classList.contains('is-active'));
  1299. return normalizeMail2925Mode(activeButton?.dataset.mail2925Mode);
  1300. }
  1301. function setMail2925Mode(mode) {
  1302. const resolvedMode = normalizeMail2925Mode(mode);
  1303. mail2925ModeButtons.forEach((button) => {
  1304. const active = button.dataset.mail2925Mode === resolvedMode;
  1305. button.classList.toggle('is-active', active);
  1306. button.setAttribute('aria-pressed', String(active));
  1307. });
  1308. }
  1309. function getSelectedHotmailServiceMode() {
  1310. const activeButton = hotmailServiceModeButtons.find((button) => button.classList.contains('is-active'));
  1311. return normalizeHotmailServiceMode(activeButton?.dataset.hotmailServiceMode);
  1312. }
  1313. function setHotmailServiceMode(mode) {
  1314. const resolvedMode = normalizeHotmailServiceMode(mode);
  1315. hotmailServiceModeButtons.forEach((button) => {
  1316. const active = button.dataset.hotmailServiceMode === resolvedMode;
  1317. button.disabled = false;
  1318. button.setAttribute('aria-disabled', 'false');
  1319. button.classList.toggle('is-active', active);
  1320. button.setAttribute('aria-pressed', String(active));
  1321. });
  1322. }
  1323. function updateAccountRunHistorySettingsUI() {
  1324. if (!rowAccountRunHistoryHelperBaseUrl || !inputAccountRunHistoryTextEnabled) {
  1325. return;
  1326. }
  1327. rowAccountRunHistoryHelperBaseUrl.style.display = inputAccountRunHistoryTextEnabled.checked ? '' : 'none';
  1328. }
  1329. function setSettingsCardLocked(locked) {
  1330. if (!settingsCard) {
  1331. return;
  1332. }
  1333. settingsCard.classList.toggle('is-locked', locked);
  1334. settingsCard.toggleAttribute('inert', locked);
  1335. }
  1336. async function setRuntimeEmailState(email) {
  1337. const normalizedEmail = String(email || '').trim() || null;
  1338. const response = await chrome.runtime.sendMessage({
  1339. type: 'SET_EMAIL_STATE',
  1340. source: 'sidepanel',
  1341. payload: { email: normalizedEmail },
  1342. });
  1343. if (response?.error) {
  1344. throw new Error(response.error);
  1345. }
  1346. return normalizedEmail;
  1347. }
  1348. async function clearRegistrationEmail(options = {}) {
  1349. const { silent = false } = options;
  1350. if (!inputEmail.value.trim() && !latestState?.email) {
  1351. return;
  1352. }
  1353. inputEmail.value = '';
  1354. syncLatestState({ email: null });
  1355. try {
  1356. await setRuntimeEmailState(null);
  1357. } catch (err) {
  1358. if (!silent) {
  1359. showToast(`清空邮箱失败:${err.message}`, 'error');
  1360. }
  1361. throw err;
  1362. }
  1363. }
  1364. function markSettingsDirty(isDirty = true) {
  1365. settingsDirty = isDirty;
  1366. updateSaveButtonState();
  1367. }
  1368. function updateSaveButtonState() {
  1369. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  1370. updateConfigMenuControls();
  1371. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  1372. }
  1373. function scheduleSettingsAutoSave() {
  1374. clearTimeout(settingsAutoSaveTimer);
  1375. settingsAutoSaveTimer = setTimeout(() => {
  1376. saveSettings({ silent: true }).catch(() => { });
  1377. }, 500);
  1378. }
  1379. async function saveSettings(options = {}) {
  1380. const { silent = false } = options;
  1381. clearTimeout(settingsAutoSaveTimer);
  1382. if (!settingsDirty && !settingsSaveInFlight && silent) {
  1383. return;
  1384. }
  1385. const payload = collectSettingsPayload();
  1386. settingsSaveInFlight = true;
  1387. updateSaveButtonState();
  1388. try {
  1389. const response = await chrome.runtime.sendMessage({
  1390. type: 'SAVE_SETTING',
  1391. source: 'sidepanel',
  1392. payload,
  1393. });
  1394. if (response?.error) {
  1395. throw new Error(response.error);
  1396. }
  1397. if (response?.state) {
  1398. applySettingsState(response.state);
  1399. } else {
  1400. syncLatestState(payload);
  1401. markSettingsDirty(false);
  1402. updatePanelModeUI();
  1403. updateMailProviderUI();
  1404. updateButtonStates();
  1405. }
  1406. if (!silent) {
  1407. showToast('配置已保存', 'success', 1800);
  1408. }
  1409. } catch (err) {
  1410. markSettingsDirty(true);
  1411. if (!silent) {
  1412. showToast(`保存失败:${err.message}`, 'error');
  1413. }
  1414. throw err;
  1415. } finally {
  1416. settingsSaveInFlight = false;
  1417. updateSaveButtonState();
  1418. }
  1419. }
  1420. function applyAutoRunStatus(payload = currentAutoRun) {
  1421. syncAutoRunState(payload);
  1422. const runLabel = getAutoRunLabel(currentAutoRun);
  1423. const locked = isAutoRunLockedPhase();
  1424. const paused = isAutoRunPausedPhase();
  1425. const scheduled = isAutoRunScheduledPhase();
  1426. const settingsCardLocked = scheduled || locked;
  1427. setSettingsCardLocked(settingsCardLocked);
  1428. inputRunCount.disabled = currentAutoRun.autoRunning;
  1429. btnAutoRun.disabled = currentAutoRun.autoRunning;
  1430. btnFetchEmail.disabled = locked
  1431. || isCustomMailProvider();
  1432. inputEmail.disabled = locked;
  1433. inputAutoSkipFailures.disabled = scheduled;
  1434. if (currentAutoRun.totalRuns > 0) {
  1435. inputRunCount.value = String(currentAutoRun.totalRuns);
  1436. }
  1437. switch (currentAutoRun.phase) {
  1438. case 'scheduled':
  1439. autoContinueBar.style.display = 'none';
  1440. btnAutoRun.innerHTML = `已计划${runLabel}`;
  1441. break;
  1442. case 'waiting_step':
  1443. autoContinueBar.style.display = 'none';
  1444. btnAutoRun.innerHTML = `等待中${runLabel}`;
  1445. break;
  1446. case 'waiting_email':
  1447. autoContinueBar.style.display = 'flex';
  1448. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  1449. break;
  1450. case 'running':
  1451. autoContinueBar.style.display = 'none';
  1452. btnAutoRun.innerHTML = `运行中${runLabel}`;
  1453. break;
  1454. case 'retrying':
  1455. autoContinueBar.style.display = 'none';
  1456. btnAutoRun.innerHTML = `重试中${runLabel}`;
  1457. break;
  1458. case 'waiting_interval':
  1459. autoContinueBar.style.display = 'none';
  1460. btnAutoRun.innerHTML = `等待中${runLabel}`;
  1461. break;
  1462. default:
  1463. autoContinueBar.style.display = 'none';
  1464. setDefaultAutoRunButton();
  1465. inputEmail.disabled = false;
  1466. if (!locked) {
  1467. btnFetchEmail.disabled = isCustomMailProvider();
  1468. }
  1469. break;
  1470. }
  1471. updateAutoDelayInputState();
  1472. updateFallbackThreadIntervalInputState();
  1473. syncScheduledCountdownTicker();
  1474. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  1475. updateConfigMenuControls();
  1476. }
  1477. function initializeManualStepActions() {
  1478. document.querySelectorAll('.step-row').forEach((row) => {
  1479. const step = Number(row.dataset.step);
  1480. const statusEl = row.querySelector('.step-status');
  1481. if (!statusEl) return;
  1482. const actions = document.createElement('div');
  1483. actions.className = 'step-actions';
  1484. const manualBtn = document.createElement('button');
  1485. manualBtn.type = 'button';
  1486. manualBtn.className = 'step-manual-btn';
  1487. manualBtn.dataset.step = String(step);
  1488. manualBtn.title = '跳过此步';
  1489. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  1490. 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>';
  1491. manualBtn.addEventListener('click', async (event) => {
  1492. event.stopPropagation();
  1493. try {
  1494. await handleSkipStep(step);
  1495. } catch (err) {
  1496. showToast(err.message, 'error');
  1497. }
  1498. });
  1499. statusEl.parentNode.replaceChild(actions, statusEl);
  1500. actions.appendChild(manualBtn);
  1501. actions.appendChild(statusEl);
  1502. });
  1503. }
  1504. function renderStepsList() {
  1505. if (!stepsList) return;
  1506. stepsList.innerHTML = stepDefinitions.map((step) => `
  1507. <div class="step-row" data-step="${step.id}" data-step-key="${escapeHtml(step.key)}">
  1508. <div class="step-indicator" data-step="${step.id}"><span class="step-num">${step.id}</span></div>
  1509. <button class="step-btn" data-step="${step.id}" data-step-key="${escapeHtml(step.key)}">${escapeHtml(step.title)}</button>
  1510. <span class="step-status" data-step="${step.id}"></span>
  1511. </div>
  1512. `).join('');
  1513. if (stepsProgress) {
  1514. stepsProgress.textContent = `0 / ${STEP_IDS.length}`;
  1515. }
  1516. }
  1517. // ============================================================
  1518. // State Restore on load
  1519. // ============================================================
  1520. function applySettingsState(state) {
  1521. syncLatestState(state);
  1522. syncAutoRunState(state);
  1523. inputEmail.value = state?.email || '';
  1524. syncPasswordField(state || {});
  1525. inputVpsUrl.value = state?.vpsUrl || '';
  1526. inputVpsPassword.value = state?.vpsPassword || '';
  1527. setLocalCpaStep9Mode(state?.localCpaStep9Mode);
  1528. selectPanelMode.value = state?.panelMode || 'cpa';
  1529. inputSub2ApiUrl.value = state?.sub2apiUrl || '';
  1530. inputSub2ApiEmail.value = state?.sub2apiEmail || '';
  1531. inputSub2ApiPassword.value = state?.sub2apiPassword || '';
  1532. inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
  1533. inputSub2ApiDefaultProxy.value = state?.sub2apiDefaultProxyName || DEFAULT_SUB2API_PROXY_NAME;
  1534. const restoredMailProvider = isCustomMailProvider(state?.mailProvider)
  1535. || [ICLOUD_PROVIDER, 'hotmail-api', GMAIL_PROVIDER, A4SKY_PROVIDER, 'luckmail-api', '163', '163-vip', 'qq', 'inbucket', '2925', 'cloudflare-temp-email'].includes(String(state?.mailProvider || '').trim())
  1536. ? String(state?.mailProvider || '163').trim()
  1537. : (String(state?.emailGenerator || '').trim().toLowerCase() === 'custom'
  1538. || String(state?.emailGenerator || '').trim().toLowerCase() === 'manual'
  1539. ? 'custom'
  1540. : '163');
  1541. selectMailProvider.value = restoredMailProvider;
  1542. setMail2925Mode(state?.mail2925Mode);
  1543. {
  1544. const restoredEmailGenerator = String(state?.emailGenerator || '').trim().toLowerCase();
  1545. if (restoredEmailGenerator === 'icloud') {
  1546. selectEmailGenerator.value = 'icloud';
  1547. } else if (restoredEmailGenerator === 'cloudflare') {
  1548. selectEmailGenerator.value = 'cloudflare';
  1549. } else if (restoredEmailGenerator === 'cloudflare-temp-email') {
  1550. selectEmailGenerator.value = 'cloudflare-temp-email';
  1551. } else {
  1552. selectEmailGenerator.value = 'duck';
  1553. }
  1554. }
  1555. if (selectIcloudHostPreference) {
  1556. selectIcloudHostPreference.value = String(state?.icloudHostPreference || '').trim().toLowerCase() === 'icloud.com'
  1557. ? 'icloud.com'
  1558. : (String(state?.icloudHostPreference || '').trim().toLowerCase() === 'icloud.com.cn' ? 'icloud.com.cn' : 'auto');
  1559. }
  1560. if (checkboxAutoDeleteIcloud) {
  1561. checkboxAutoDeleteIcloud.checked = Boolean(state?.autoDeleteUsedIcloudAlias);
  1562. }
  1563. if (inputAccountRunHistoryTextEnabled) {
  1564. inputAccountRunHistoryTextEnabled.checked = Boolean(state?.accountRunHistoryTextEnabled);
  1565. }
  1566. if (inputAccountRunHistoryHelperBaseUrl) {
  1567. inputAccountRunHistoryHelperBaseUrl.value = normalizeAccountRunHistoryHelperBaseUrlValue(state?.accountRunHistoryHelperBaseUrl);
  1568. }
  1569. setManagedAliasBaseEmailInputForProvider(restoredMailProvider, state);
  1570. inputInbucketHost.value = state?.inbucketHost || '';
  1571. inputInbucketMailbox.value = state?.inbucketMailbox || '';
  1572. setHotmailServiceMode(state?.hotmailServiceMode);
  1573. inputHotmailRemoteBaseUrl.value = state?.hotmailRemoteBaseUrl || '';
  1574. inputHotmailLocalBaseUrl.value = state?.hotmailLocalBaseUrl || '';
  1575. inputLuckmailApiKey.value = state?.luckmailApiKey || '';
  1576. inputLuckmailBaseUrl.value = normalizeLuckmailBaseUrl(state?.luckmailBaseUrl);
  1577. selectLuckmailEmailType.value = normalizeLuckmailEmailType(state?.luckmailEmailType);
  1578. inputLuckmailDomain.value = state?.luckmailDomain || '';
  1579. inputTempEmailBaseUrl.value = state?.cloudflareTempEmailBaseUrl || '';
  1580. inputTempEmailAdminAuth.value = state?.cloudflareTempEmailAdminAuth || '';
  1581. inputTempEmailCustomAuth.value = state?.cloudflareTempEmailCustomAuth || '';
  1582. inputTempEmailReceiveMailbox.value = state?.cloudflareTempEmailReceiveMailbox || '';
  1583. renderCloudflareDomainOptions(state?.cloudflareDomain || '');
  1584. setCloudflareDomainEditMode(false, { clearInput: true });
  1585. renderCloudflareTempEmailDomainOptions(state?.cloudflareTempEmailDomain || '');
  1586. setCloudflareTempEmailDomainEditMode(false, { clearInput: true });
  1587. inputAutoSkipFailures.checked = Boolean(state?.autoRunSkipFailures);
  1588. inputAutoSkipFailuresThreadIntervalMinutes.value = String(normalizeAutoRunThreadIntervalMinutes(state?.autoRunFallbackThreadIntervalMinutes));
  1589. if (inputAutoAddPhonePauseMinutes) {
  1590. inputAutoAddPhonePauseMinutes.value = String(normalizeAddPhonePauseMinutes(state?.autoRunAddPhonePauseMinutes));
  1591. }
  1592. inputAutoDelayEnabled.checked = Boolean(state?.autoRunDelayEnabled);
  1593. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state?.autoRunDelayMinutes));
  1594. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(state?.autoStepDelaySeconds);
  1595. if (inputVerificationResendCount) {
  1596. const restoredVerificationResendCount = state?.verificationResendCount !== undefined
  1597. ? state.verificationResendCount
  1598. : (state?.signupVerificationResendCount ?? state?.loginVerificationResendCount);
  1599. inputVerificationResendCount.value = String(
  1600. normalizeVerificationResendCount(restoredVerificationResendCount, DEFAULT_VERIFICATION_RESEND_COUNT)
  1601. );
  1602. }
  1603. if (state?.autoRunTotalRuns) {
  1604. inputRunCount.value = String(state.autoRunTotalRuns);
  1605. }
  1606. applyAutoRunStatus(state);
  1607. markSettingsDirty(false);
  1608. updateAutoDelayInputState();
  1609. updateFallbackThreadIntervalInputState();
  1610. updateAccountRunHistorySettingsUI();
  1611. updatePanelModeUI();
  1612. updateMailProviderUI();
  1613. if (isLuckmailProvider(state?.mailProvider)) {
  1614. queueLuckmailPurchaseRefresh();
  1615. }
  1616. updateButtonStates();
  1617. }
  1618. async function restoreState() {
  1619. try {
  1620. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  1621. applySettingsState(state);
  1622. if (getSelectedEmailGenerator() === 'icloud' && icloudSection?.style.display !== 'none') {
  1623. refreshIcloudAliases({ silent: true }).catch(() => { });
  1624. }
  1625. if (state.oauthUrl) {
  1626. displayOauthUrl.textContent = state.oauthUrl;
  1627. displayOauthUrl.classList.add('has-value');
  1628. }
  1629. if (state.localhostUrl) {
  1630. displayLocalhostUrl.textContent = state.localhostUrl;
  1631. displayLocalhostUrl.classList.add('has-value');
  1632. }
  1633. if (state.stepStatuses) {
  1634. for (const [step, status] of Object.entries(state.stepStatuses)) {
  1635. updateStepUI(Number(step), status);
  1636. }
  1637. }
  1638. if (state.logs) {
  1639. for (const entry of state.logs) {
  1640. appendLog(entry);
  1641. }
  1642. }
  1643. updateStatusDisplay(latestState);
  1644. updateProgressCounter();
  1645. } catch (err) {
  1646. console.error('Failed to restore state:', err);
  1647. }
  1648. }
  1649. function openExternalUrl(url) {
  1650. const targetUrl = String(url || '').trim();
  1651. if (!targetUrl) {
  1652. return;
  1653. }
  1654. if (chrome?.tabs?.create) {
  1655. chrome.tabs.create({ url: targetUrl, active: true }).catch(() => {
  1656. window.open(targetUrl, '_blank', 'noopener');
  1657. });
  1658. return;
  1659. }
  1660. window.open(targetUrl, '_blank', 'noopener');
  1661. }
  1662. function createUpdateNoteList(notes = []) {
  1663. if (!Array.isArray(notes) || notes.length === 0) {
  1664. const empty = document.createElement('p');
  1665. empty.className = 'update-release-empty';
  1666. empty.textContent = '该版本未提供可解析的更新说明,请查看完整更新日志。';
  1667. return empty;
  1668. }
  1669. const list = document.createElement('ul');
  1670. list.className = 'update-release-notes';
  1671. notes.forEach((note) => {
  1672. const item = document.createElement('li');
  1673. item.textContent = note;
  1674. list.appendChild(item);
  1675. });
  1676. return list;
  1677. }
  1678. function renderUpdateReleaseList(releases = []) {
  1679. if (!updateReleaseList) {
  1680. return;
  1681. }
  1682. updateReleaseList.innerHTML = '';
  1683. releases.forEach((release) => {
  1684. const item = document.createElement('article');
  1685. item.className = 'update-release-item';
  1686. const head = document.createElement('div');
  1687. head.className = 'update-release-head';
  1688. const titleRow = document.createElement('div');
  1689. titleRow.className = 'update-release-title-row';
  1690. const version = document.createElement('span');
  1691. version.className = 'update-release-version';
  1692. version.textContent = release.displayVersion || `Pro${release.version}`;
  1693. titleRow.appendChild(version);
  1694. if (release.title) {
  1695. const name = document.createElement('span');
  1696. name.className = 'update-release-name';
  1697. name.textContent = release.title;
  1698. titleRow.appendChild(name);
  1699. }
  1700. head.appendChild(titleRow);
  1701. const publishedAt = sidepanelUpdateService?.formatReleaseDate?.(release.publishedAt) || '';
  1702. if (publishedAt) {
  1703. const date = document.createElement('span');
  1704. date.className = 'update-release-date';
  1705. date.textContent = publishedAt;
  1706. head.appendChild(date);
  1707. }
  1708. item.appendChild(head);
  1709. item.appendChild(createUpdateNoteList(release.notes));
  1710. updateReleaseList.appendChild(item);
  1711. });
  1712. }
  1713. function resetUpdateCard() {
  1714. if (updateSection) {
  1715. updateSection.hidden = true;
  1716. }
  1717. if (updateCardVersion) {
  1718. updateCardVersion.textContent = '';
  1719. }
  1720. if (updateCardSummary) {
  1721. updateCardSummary.textContent = '';
  1722. }
  1723. if (updateReleaseList) {
  1724. updateReleaseList.innerHTML = '';
  1725. }
  1726. if (btnOpenRelease) {
  1727. btnOpenRelease.hidden = true;
  1728. btnOpenRelease.onclick = null;
  1729. }
  1730. }
  1731. function renderReleaseSnapshot(snapshot) {
  1732. currentReleaseSnapshot = snapshot;
  1733. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1734. return;
  1735. }
  1736. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed', 'is-version-label');
  1737. const localVersionText = snapshot?.localVersion || '';
  1738. const logUrl = snapshot?.logUrl || snapshot?.releasesPageUrl || sidepanelUpdateService?.releasesPageUrl || '';
  1739. if (btnReleaseLog) {
  1740. btnReleaseLog.onclick = () => openExternalUrl(logUrl);
  1741. btnReleaseLog.hidden = true;
  1742. }
  1743. extensionVersionMeta.hidden = true;
  1744. extensionVersionMeta.textContent = '';
  1745. switch (snapshot?.status) {
  1746. case 'update-available': {
  1747. extensionUpdateStatus.textContent = '有更新';
  1748. extensionUpdateStatus.classList.add('is-update-available');
  1749. if (btnReleaseLog) {
  1750. btnReleaseLog.hidden = false;
  1751. }
  1752. if (updateSection) {
  1753. updateSection.hidden = false;
  1754. }
  1755. if (updateCardVersion) {
  1756. updateCardVersion.textContent = `最新版本 ${snapshot.latestVersion}`;
  1757. }
  1758. if (updateCardSummary) {
  1759. const updateCount = Array.isArray(snapshot.newerReleases) ? snapshot.newerReleases.length : 0;
  1760. updateCardSummary.textContent = updateCount > 1
  1761. ? `当前 ${localVersionText},共有 ${updateCount} 个新版本可更新。`
  1762. : `当前 ${localVersionText},可更新到 ${snapshot.latestVersion}。`;
  1763. }
  1764. renderUpdateReleaseList(snapshot.newerReleases || []);
  1765. if (btnOpenRelease) {
  1766. btnOpenRelease.hidden = false;
  1767. btnOpenRelease.textContent = '前往更新';
  1768. btnOpenRelease.onclick = () => openExternalUrl(logUrl);
  1769. }
  1770. break;
  1771. }
  1772. case 'latest': {
  1773. extensionUpdateStatus.textContent = localVersionText || 'Pro0.0';
  1774. extensionUpdateStatus.classList.add('is-version-label');
  1775. resetUpdateCard();
  1776. break;
  1777. }
  1778. case 'empty': {
  1779. extensionUpdateStatus.textContent = localVersionText || 'Pro0.0';
  1780. extensionUpdateStatus.classList.add('is-version-label');
  1781. resetUpdateCard();
  1782. break;
  1783. }
  1784. case 'error':
  1785. default: {
  1786. extensionUpdateStatus.textContent = localVersionText || 'Pro0.0';
  1787. extensionUpdateStatus.classList.add('is-version-label', 'is-check-failed');
  1788. extensionVersionMeta.textContent = snapshot?.errorMessage || 'GitHub Releases 检查失败';
  1789. extensionVersionMeta.hidden = false;
  1790. resetUpdateCard();
  1791. break;
  1792. }
  1793. }
  1794. }
  1795. async function initializeReleaseInfo() {
  1796. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1797. return;
  1798. }
  1799. const localVersion = sidepanelUpdateService?.getLocalVersionLabel?.(chrome.runtime.getManifest())
  1800. || chrome.runtime.getManifest()?.version_name
  1801. || (chrome.runtime.getManifest()?.version ? `v${chrome.runtime.getManifest().version}` : '');
  1802. currentReleaseSnapshot = null;
  1803. extensionUpdateStatus.textContent = localVersion || 'Pro0.0';
  1804. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed');
  1805. extensionUpdateStatus.classList.add('is-version-label');
  1806. extensionVersionMeta.hidden = true;
  1807. extensionVersionMeta.textContent = '';
  1808. if (btnReleaseLog) {
  1809. btnReleaseLog.hidden = true;
  1810. btnReleaseLog.onclick = null;
  1811. }
  1812. resetUpdateCard();
  1813. return;
  1814. }
  1815. function syncPasswordField(state) {
  1816. inputPassword.value = state.customPassword || state.password || '';
  1817. }
  1818. function isCustomMailProvider(provider = selectMailProvider.value) {
  1819. return String(provider || '').trim().toLowerCase() === 'custom';
  1820. }
  1821. function isLuckmailProvider(provider = selectMailProvider.value) {
  1822. return String(provider || '').trim().toLowerCase() === LUCKMAIL_PROVIDER;
  1823. }
  1824. function isA4skyProvider(provider = selectMailProvider.value) {
  1825. return String(provider || '').trim().toLowerCase() === A4SKY_PROVIDER;
  1826. }
  1827. function isIcloudMailProvider(provider = selectMailProvider.value) {
  1828. return String(provider || '').trim().toLowerCase() === ICLOUD_PROVIDER;
  1829. }
  1830. function normalizeLuckmailBaseUrl(value = '') {
  1831. const trimmed = String(value || '').trim();
  1832. if (!trimmed) {
  1833. return DEFAULT_LUCKMAIL_BASE_URL;
  1834. }
  1835. try {
  1836. const parsed = new URL(trimmed);
  1837. if (!['http:', 'https:'].includes(parsed.protocol)) {
  1838. return DEFAULT_LUCKMAIL_BASE_URL;
  1839. }
  1840. parsed.pathname = parsed.pathname.replace(/\/+$/, '');
  1841. parsed.search = '';
  1842. parsed.hash = '';
  1843. return parsed.toString().replace(/\/$/, '');
  1844. } catch {
  1845. return DEFAULT_LUCKMAIL_BASE_URL;
  1846. }
  1847. }
  1848. function normalizeLuckmailEmailType(value = '') {
  1849. const normalized = String(value || '').trim().toLowerCase();
  1850. return ['self_built', 'ms_imap', 'ms_graph', 'google_variant'].includes(normalized)
  1851. ? normalized
  1852. : DEFAULT_LUCKMAIL_EMAIL_TYPE;
  1853. }
  1854. function getSelectedEmailGenerator() {
  1855. const generator = String(selectEmailGenerator.value || '').trim().toLowerCase();
  1856. if (generator === 'custom' || generator === 'manual') {
  1857. return 'custom';
  1858. }
  1859. if (generator === 'icloud') {
  1860. return 'icloud';
  1861. }
  1862. if (generator === 'cloudflare') return 'cloudflare';
  1863. if (generator === 'cloudflare-temp-email') return 'cloudflare-temp-email';
  1864. return 'duck';
  1865. }
  1866. function getEmailGeneratorUiCopy() {
  1867. if (getSelectedEmailGenerator() === 'custom') {
  1868. return getCustomMailProviderUiCopy();
  1869. }
  1870. if (getSelectedEmailGenerator() === 'icloud') {
  1871. return {
  1872. buttonLabel: '获取',
  1873. placeholder: '点击获取 iCloud 隐私邮箱,或手动粘贴邮箱',
  1874. successVerb: '获取',
  1875. label: 'iCloud 隐私邮箱',
  1876. };
  1877. }
  1878. if (getSelectedEmailGenerator() === 'cloudflare') {
  1879. return {
  1880. buttonLabel: '生成',
  1881. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  1882. successVerb: '生成',
  1883. label: 'Cloudflare 邮箱',
  1884. };
  1885. }
  1886. if (getSelectedEmailGenerator() === 'cloudflare-temp-email') {
  1887. return {
  1888. buttonLabel: '生成 Temp',
  1889. placeholder: '点击生成 Cloudflare Temp Email,或手动粘贴邮箱',
  1890. successVerb: '生成',
  1891. label: 'Cloudflare Temp Email',
  1892. };
  1893. }
  1894. return {
  1895. buttonLabel: '获取',
  1896. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  1897. successVerb: '获取',
  1898. label: 'Duck 邮箱',
  1899. };
  1900. }
  1901. function getCustomMailProviderUiCopy() {
  1902. return {
  1903. buttonLabel: '自定义邮箱',
  1904. placeholder: '请填写本轮要使用的注册邮箱',
  1905. successVerb: '使用',
  1906. label: '自定义邮箱',
  1907. };
  1908. }
  1909. function getCustomVerificationPromptCopy(step) {
  1910. const verificationLabel = step === 4 ? '注册验证码' : '登录验证码';
  1911. return {
  1912. title: `手动处理${verificationLabel}`,
  1913. message: `当前邮箱服务为“自定义邮箱”。请先在页面中手动输入${verificationLabel},并确认已经进入下一页面后,再点击确认。`,
  1914. alert: {
  1915. text: `点击确认后会跳过步骤 ${step}。`,
  1916. tone: 'danger',
  1917. },
  1918. };
  1919. }
  1920. function getHotmailAccounts(state = latestState) {
  1921. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  1922. }
  1923. function getCurrentHotmailAccount(state = latestState) {
  1924. const currentId = state?.currentHotmailAccountId;
  1925. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  1926. }
  1927. function getCurrentHotmailEmail(state = latestState) {
  1928. return String(getCurrentHotmailAccount(state)?.email || '').trim();
  1929. }
  1930. function getCurrentLuckmailPurchase(state = latestState) {
  1931. return state?.currentLuckmailPurchase || null;
  1932. }
  1933. function getCurrentLuckmailEmail(state = latestState) {
  1934. return String(getCurrentLuckmailPurchase(state)?.email_address || '').trim();
  1935. }
  1936. function getLuckmailUsedPurchases(state = latestState) {
  1937. const rawValue = state?.luckmailUsedPurchases;
  1938. if (!rawValue || typeof rawValue !== 'object' || Array.isArray(rawValue)) {
  1939. return {};
  1940. }
  1941. return Object.entries(rawValue).reduce((result, [key, value]) => {
  1942. const numeric = Number(key);
  1943. if (!Number.isFinite(numeric) || numeric <= 0) {
  1944. return result;
  1945. }
  1946. result[String(Math.floor(numeric))] = Boolean(value);
  1947. return result;
  1948. }, {});
  1949. }
  1950. function normalizeLuckmailProjectName(value = '') {
  1951. return String(value || '').trim().toLowerCase();
  1952. }
  1953. function getLuckmailPreserveTagName(state = latestState) {
  1954. return String(state?.luckmailPreserveTagName || '').trim() || DEFAULT_LUCKMAIL_PRESERVE_TAG_NAME;
  1955. }
  1956. function formatLuckmailDateTime(value) {
  1957. const timestamp = normalizeLuckmailTimestampValue(value);
  1958. if (!timestamp) {
  1959. return String(value || '').trim() || '未知';
  1960. }
  1961. return new Date(timestamp).toLocaleString('zh-CN', {
  1962. hour12: false,
  1963. timeZone: DISPLAY_TIMEZONE,
  1964. });
  1965. }
  1966. function getMailProviderLoginConfig(provider = selectMailProvider.value) {
  1967. return MAIL_PROVIDER_LOGIN_CONFIGS[String(provider || '').trim()] || null;
  1968. }
  1969. function getSelectedIcloudHostPreference() {
  1970. return normalizeIcloudHost(selectIcloudHostPreference?.value || latestState?.icloudHostPreference || '')
  1971. || normalizeIcloudHost(latestState?.preferredIcloudHost)
  1972. || 'icloud.com';
  1973. }
  1974. function getMailProviderLoginUrl(provider = selectMailProvider.value) {
  1975. const config = getMailProviderLoginConfig(provider);
  1976. if (String(provider || '').trim() === ICLOUD_PROVIDER) {
  1977. return getIcloudLoginUrlForHost(getSelectedIcloudHostPreference());
  1978. }
  1979. const url = String(config?.url || '').trim();
  1980. return url ? url : '';
  1981. }
  1982. function isCurrentEmailManagedByHotmail(state = latestState) {
  1983. const hotmailEmail = getCurrentHotmailEmail(state);
  1984. if (!hotmailEmail) {
  1985. return false;
  1986. }
  1987. const inputEmailValue = String(inputEmail.value || '').trim();
  1988. const stateEmailValue = String(state?.email || '').trim();
  1989. return inputEmailValue === hotmailEmail || stateEmailValue === hotmailEmail;
  1990. }
  1991. function isCurrentEmailManagedByLuckmail(state = latestState) {
  1992. const luckmailEmail = getCurrentLuckmailEmail(state);
  1993. if (!luckmailEmail) {
  1994. return false;
  1995. }
  1996. const inputEmailValue = String(inputEmail.value || '').trim();
  1997. const stateEmailValue = String(state?.email || '').trim();
  1998. return inputEmailValue === luckmailEmail || stateEmailValue === luckmailEmail;
  1999. }
  2000. function isCurrentEmailManagedByGeneratedAlias(
  2001. provider = latestState?.mailProvider,
  2002. state = latestState,
  2003. mail2925Mode = latestState?.mail2925Mode
  2004. ) {
  2005. const normalizedProvider = String(provider || '').trim();
  2006. if (!usesGeneratedAliasMailProvider(normalizedProvider, mail2925Mode)) {
  2007. return false;
  2008. }
  2009. const inputEmailValue = String(inputEmail.value || '').trim().toLowerCase();
  2010. const stateEmailValue = String(state?.email || '').trim().toLowerCase();
  2011. const baseEmail = getManagedAliasBaseEmailForProvider(normalizedProvider, state);
  2012. return isManagedAliasEmail(inputEmailValue, baseEmail, normalizedProvider)
  2013. || isManagedAliasEmail(stateEmailValue, baseEmail, normalizedProvider);
  2014. }
  2015. async function maybeClearGeneratedAliasAfterEmailPrefixChange() {
  2016. const provider = selectMailProvider.value;
  2017. if (!usesGeneratedAliasMailProvider(provider, latestState?.mail2925Mode)) {
  2018. return;
  2019. }
  2020. const previousPrefix = getManagedAliasBaseEmailForProvider(provider, latestState);
  2021. const nextPrefix = inputEmailPrefix.value.trim();
  2022. if (previousPrefix === nextPrefix) {
  2023. return;
  2024. }
  2025. if (!previousPrefix) {
  2026. return;
  2027. }
  2028. if (!isCurrentEmailManagedByGeneratedAlias(provider, latestState, latestState?.mail2925Mode)) {
  2029. return;
  2030. }
  2031. await clearRegistrationEmail({ silent: true });
  2032. }
  2033. function updateMailLoginButtonState() {
  2034. if (!btnMailLogin) {
  2035. return;
  2036. }
  2037. const config = getMailProviderLoginConfig();
  2038. const loginUrl = getMailProviderLoginUrl();
  2039. btnMailLogin.disabled = !loginUrl;
  2040. btnMailLogin.textContent = config?.buttonLabel || '登录';
  2041. btnMailLogin.title = loginUrl ? `打开 ${config.label} 登录页` : '当前邮箱服务没有可跳转的登录页';
  2042. }
  2043. function updateMailProviderUI() {
  2044. const use2925 = selectMailProvider.value === '2925';
  2045. const useGmail = selectMailProvider.value === GMAIL_PROVIDER;
  2046. const useA4sky = isA4skyProvider();
  2047. const mail2925Mode = getSelectedMail2925Mode();
  2048. const useGeneratedAlias = usesGeneratedAliasMailProvider(selectMailProvider.value, mail2925Mode);
  2049. const useInbucket = selectMailProvider.value === 'inbucket';
  2050. const useHotmail = selectMailProvider.value === 'hotmail-api';
  2051. const useLuckmail = isLuckmailProvider();
  2052. const useCustomEmail = isCustomMailProvider();
  2053. const useIcloudProvider = isIcloudMailProvider();
  2054. const useEmailGenerator = !useHotmail && !useLuckmail && !useGeneratedAlias && !useCustomEmail && !useA4sky;
  2055. const useCloudflareTempEmailProvider = selectMailProvider.value === 'cloudflare-temp-email';
  2056. const aliasUiCopy = useGeneratedAlias ? getManagedAliasProviderUiCopy(selectMailProvider.value) : null;
  2057. const uiCopy = getCurrentRegistrationEmailUiCopy();
  2058. updateMailLoginButtonState();
  2059. if (rowMail2925Mode) {
  2060. rowMail2925Mode.style.display = 'none';
  2061. }
  2062. rowEmailPrefix.style.display = useGeneratedAlias ? '' : 'none';
  2063. const hotmailServiceMode = getSelectedHotmailServiceMode();
  2064. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  2065. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  2066. const selectedGenerator = getSelectedEmailGenerator();
  2067. const useCloudflare = selectedGenerator === 'cloudflare';
  2068. const useIcloud = selectedGenerator === 'icloud';
  2069. const useCloudflareTempEmailGenerator = selectedGenerator === 'cloudflare-temp-email';
  2070. const showCloudflareDomain = useEmailGenerator && useCloudflare;
  2071. const showCloudflareTempEmailSettings = useCloudflareTempEmailProvider || (useEmailGenerator && useCloudflareTempEmailGenerator);
  2072. const showCloudflareTempEmailReceiveMailbox = useCloudflareTempEmailProvider && !useCloudflareTempEmailGenerator;
  2073. const showCloudflareTempEmailDomain = useEmailGenerator && useCloudflareTempEmailGenerator;
  2074. if (rowEmailGenerator) {
  2075. rowEmailGenerator.style.display = useEmailGenerator ? '' : 'none';
  2076. }
  2077. if (icloudSection) {
  2078. const showIcloudSection = (useEmailGenerator && useIcloud) || useIcloudProvider;
  2079. icloudSection.style.display = showIcloudSection ? '' : 'none';
  2080. if (showIcloudSection) {
  2081. queueIcloudAliasRefresh();
  2082. }
  2083. if (!showIcloudSection) {
  2084. hideIcloudLoginHelp();
  2085. }
  2086. }
  2087. rowCfDomain.style.display = showCloudflareDomain ? '' : 'none';
  2088. const { domains } = getCloudflareDomainsFromState();
  2089. if (showCloudflareDomain) {
  2090. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  2091. } else {
  2092. setCloudflareDomainEditMode(false, { clearInput: false });
  2093. }
  2094. rowTempEmailBaseUrl.style.display = showCloudflareTempEmailSettings ? '' : 'none';
  2095. rowTempEmailAdminAuth.style.display = showCloudflareTempEmailSettings ? '' : 'none';
  2096. rowTempEmailCustomAuth.style.display = showCloudflareTempEmailSettings ? '' : 'none';
  2097. rowTempEmailReceiveMailbox.style.display = showCloudflareTempEmailReceiveMailbox ? '' : 'none';
  2098. rowTempEmailDomain.style.display = showCloudflareTempEmailDomain ? '' : 'none';
  2099. const { domains: tempEmailDomains } = getCloudflareTempEmailDomainsFromState();
  2100. if (showCloudflareTempEmailDomain) {
  2101. setCloudflareTempEmailDomainEditMode(cloudflareTempEmailDomainEditMode || tempEmailDomains.length === 0, { clearInput: false });
  2102. } else {
  2103. setCloudflareTempEmailDomainEditMode(false, { clearInput: false });
  2104. }
  2105. if (hotmailSection) {
  2106. hotmailSection.style.display = useHotmail || useA4sky ? '' : 'none';
  2107. }
  2108. if (hotmailSectionLabel) {
  2109. hotmailSectionLabel.textContent = useA4sky ? 'A4Sky IMAP 助手' : 'Hotmail 账号池';
  2110. }
  2111. if (labelHotmailLocalBaseUrl) {
  2112. labelHotmailLocalBaseUrl.textContent = useA4sky ? '助手地址' : '本地助手';
  2113. }
  2114. if (inputHotmailLocalBaseUrl) {
  2115. inputHotmailLocalBaseUrl.placeholder = useA4sky
  2116. ? '例如 http://ali.97admin.com:17373'
  2117. : 'http://127.0.0.1:17373';
  2118. }
  2119. if (btnHotmailUsageGuide) {
  2120. btnHotmailUsageGuide.style.display = useHotmail ? '' : 'none';
  2121. }
  2122. if (btnClearUsedHotmailAccounts) {
  2123. btnClearUsedHotmailAccounts.style.display = useHotmail ? '' : 'none';
  2124. }
  2125. if (btnDeleteAllHotmailAccounts) {
  2126. btnDeleteAllHotmailAccounts.style.display = useHotmail ? '' : 'none';
  2127. }
  2128. if (btnToggleHotmailList) {
  2129. btnToggleHotmailList.style.display = useHotmail ? '' : 'none';
  2130. }
  2131. if (hotmailListShell) {
  2132. hotmailListShell.style.display = useHotmail ? '' : 'none';
  2133. }
  2134. if (luckmailSection) {
  2135. luckmailSection.style.display = useLuckmail ? '' : 'none';
  2136. }
  2137. labelEmailPrefix.textContent = '邮箱前缀';
  2138. inputEmailPrefix.placeholder = '例如 abc';
  2139. selectEmailGenerator.disabled = useHotmail || useLuckmail || useGeneratedAlias || useCustomEmail || useA4sky;
  2140. if (useGmail) {
  2141. labelEmailPrefix.textContent = 'Gmail 原邮箱';
  2142. inputEmailPrefix.placeholder = '例如 yourname@gmail.com';
  2143. }
  2144. labelEmailPrefix.textContent = aliasUiCopy?.baseLabel || labelEmailPrefix.textContent;
  2145. inputEmailPrefix.placeholder = aliasUiCopy?.basePlaceholder || inputEmailPrefix.placeholder;
  2146. if (rowHotmailServiceMode) {
  2147. rowHotmailServiceMode.style.display = useHotmail ? '' : 'none';
  2148. }
  2149. if (rowHotmailRemoteBaseUrl) {
  2150. rowHotmailRemoteBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE ? '' : 'none';
  2151. }
  2152. if (rowHotmailLocalBaseUrl) {
  2153. rowHotmailLocalBaseUrl.style.display = (useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_LOCAL) || useA4sky ? '' : 'none';
  2154. }
  2155. if (inputHotmailEmail?.closest('.data-row')) {
  2156. inputHotmailEmail.closest('.data-row').style.display = useHotmail ? '' : 'none';
  2157. }
  2158. if (inputHotmailClientId?.closest('.data-row')) {
  2159. inputHotmailClientId.closest('.data-row').style.display = useHotmail ? '' : 'none';
  2160. }
  2161. if (inputHotmailPassword?.closest('.data-row')) {
  2162. inputHotmailPassword.closest('.data-row').style.display = useHotmail ? '' : 'none';
  2163. }
  2164. if (inputHotmailRefreshToken?.closest('.data-row')) {
  2165. inputHotmailRefreshToken.closest('.data-row').style.display = useHotmail ? '' : 'none';
  2166. }
  2167. if (btnAddHotmailAccount?.closest('.data-row')) {
  2168. btnAddHotmailAccount.closest('.data-row').style.display = useHotmail ? '' : 'none';
  2169. }
  2170. if (inputHotmailImport?.closest('.data-row')) {
  2171. inputHotmailImport.closest('.data-row').style.display = useHotmail ? '' : 'none';
  2172. }
  2173. btnFetchEmail.hidden = useHotmail || useLuckmail || useCustomEmail;
  2174. inputEmail.readOnly = useHotmail || useLuckmail;
  2175. inputEmail.placeholder = useHotmail
  2176. ? '由 Hotmail 账号池自动分配'
  2177. : (useLuckmail
  2178. ? '步骤 3 自动购买 LuckMail 邮箱并回填'
  2179. : (useGeneratedAlias ? '步骤 3 自动生成 2925 邮箱并回填' : uiCopy.placeholder));
  2180. if (useGmail && useGeneratedAlias) {
  2181. inputEmail.placeholder = '步骤 3 自动生成 Gmail +tag 邮箱并回填';
  2182. }
  2183. if (!useHotmail && !useLuckmail) {
  2184. inputEmail.placeholder = uiCopy.placeholder;
  2185. }
  2186. btnFetchEmail.disabled = useLuckmail || useCustomEmail || isAutoRunLockedPhase();
  2187. if (!btnFetchEmail.disabled) {
  2188. btnFetchEmail.textContent = uiCopy.buttonLabel;
  2189. }
  2190. if (autoHintText) {
  2191. autoHintText.textContent = useHotmail
  2192. ? '请先校验并选择一个 Hotmail 账号'
  2193. : (useLuckmail
  2194. ? '步骤 3 会自动购买 LuckMail 邮箱并用于收码'
  2195. : (useA4sky
  2196. ? '点击“生成”得到 n{Ymdhis}@a4sky.com;步骤 4/8 会通过下方 IMAP 助手地址直接取码'
  2197. : (useGeneratedAlias
  2198. ? '步骤 3 会自动生成邮箱,无需手动获取'
  2199. : (useCustomEmail ? '请先填写自定义注册邮箱,成功一轮后会自动清空' : `先自动获取${uiCopy.label},或手动粘贴邮箱后再继续`))));
  2200. }
  2201. if (autoHintText && useGmail && useGeneratedAlias) {
  2202. autoHintText.textContent = '请先填写 Gmail 原邮箱,步骤 3 会自动生成 Gmail +tag 地址';
  2203. }
  2204. if (autoHintText && useGeneratedAlias && aliasUiCopy?.hint) {
  2205. autoHintText.textContent = aliasUiCopy.hint;
  2206. }
  2207. if (autoHintText && showCloudflareTempEmailReceiveMailbox) {
  2208. autoHintText.textContent = '若注册邮箱会转发到 Cloudflare Temp Email,请在“邮件接收”中填写实际接收转发邮件的邮箱。';
  2209. }
  2210. if (useHotmail) {
  2211. inputEmail.value = getCurrentHotmailEmail();
  2212. } else if (useLuckmail) {
  2213. inputEmail.value = getCurrentLuckmailEmail();
  2214. }
  2215. renderHotmailAccounts();
  2216. if (useLuckmail) {
  2217. renderLuckmailPurchases();
  2218. }
  2219. }
  2220. async function saveCloudflareDomainSettings(domains, activeDomain, options = {}) {
  2221. const { silent = false } = options;
  2222. const normalizedDomains = normalizeCloudflareDomains(domains);
  2223. const normalizedActiveDomain = normalizeCloudflareDomainValue(activeDomain) || normalizedDomains[0] || '';
  2224. const payload = {
  2225. cloudflareDomain: normalizedActiveDomain,
  2226. cloudflareDomains: normalizedDomains,
  2227. };
  2228. const response = await chrome.runtime.sendMessage({
  2229. type: 'SAVE_SETTING',
  2230. source: 'sidepanel',
  2231. payload,
  2232. });
  2233. if (response?.error) {
  2234. throw new Error(response.error);
  2235. }
  2236. syncLatestState({
  2237. ...payload,
  2238. });
  2239. renderCloudflareDomainOptions(normalizedActiveDomain);
  2240. setCloudflareDomainEditMode(false, { clearInput: true });
  2241. markSettingsDirty(false);
  2242. updateMailProviderUI();
  2243. if (!silent) {
  2244. showToast('Cloudflare 域名已保存', 'success', 1800);
  2245. }
  2246. }
  2247. async function saveCloudflareTempEmailDomainSettings(domains, activeDomain, options = {}) {
  2248. const { silent = false } = options;
  2249. const normalizedDomains = normalizeCloudflareTempEmailDomains(domains);
  2250. const normalizedActiveDomain = normalizeCloudflareTempEmailDomainValue(activeDomain) || normalizedDomains[0] || '';
  2251. const payload = {
  2252. cloudflareTempEmailDomain: normalizedActiveDomain,
  2253. cloudflareTempEmailDomains: normalizedDomains,
  2254. };
  2255. const response = await chrome.runtime.sendMessage({
  2256. type: 'SAVE_SETTING',
  2257. source: 'sidepanel',
  2258. payload,
  2259. });
  2260. if (response?.error) {
  2261. throw new Error(response.error);
  2262. }
  2263. syncLatestState({
  2264. ...payload,
  2265. });
  2266. renderCloudflareTempEmailDomainOptions(normalizedActiveDomain);
  2267. setCloudflareTempEmailDomainEditMode(false, { clearInput: true });
  2268. markSettingsDirty(false);
  2269. updateMailProviderUI();
  2270. if (!silent) {
  2271. showToast('Cloudflare Temp Email 域名已保存', 'success', 1800);
  2272. }
  2273. }
  2274. function updatePanelModeUI() {
  2275. const useSub2Api = selectPanelMode.value === 'sub2api';
  2276. rowVpsUrl.style.display = useSub2Api ? 'none' : '';
  2277. rowVpsPassword.style.display = useSub2Api ? 'none' : '';
  2278. rowLocalCpaStep9Mode.style.display = useSub2Api ? 'none' : '';
  2279. rowSub2ApiUrl.style.display = useSub2Api ? '' : 'none';
  2280. rowSub2ApiEmail.style.display = useSub2Api ? '' : 'none';
  2281. rowSub2ApiPassword.style.display = useSub2Api ? '' : 'none';
  2282. rowSub2ApiGroup.style.display = useSub2Api ? '' : 'none';
  2283. rowSub2ApiDefaultProxy.style.display = useSub2Api ? '' : 'none';
  2284. const step9Btn = document.querySelector('.step-btn[data-step-key="platform-verify"]');
  2285. if (step9Btn) {
  2286. step9Btn.textContent = useSub2Api ? 'SUB2API 回调验证' : 'CPA 回调验证';
  2287. }
  2288. }
  2289. // ============================================================
  2290. // UI Updates
  2291. // ============================================================
  2292. function updateStepUI(step, status) {
  2293. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  2294. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  2295. syncLatestState({
  2296. stepStatuses: {
  2297. ...getStepStatuses(),
  2298. [step]: status,
  2299. },
  2300. });
  2301. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  2302. if (row) {
  2303. row.className = `step-row ${status}`;
  2304. }
  2305. updateButtonStates();
  2306. updateProgressCounter();
  2307. updateConfigMenuControls();
  2308. }
  2309. function updateProgressCounter() {
  2310. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  2311. stepsProgress.textContent = `${completed} / ${STEP_IDS.length}`;
  2312. }
  2313. function updateButtonStates() {
  2314. const statuses = getStepStatuses();
  2315. const anyRunning = Object.values(statuses).some(s => s === 'running');
  2316. const autoLocked = isAutoRunLockedPhase();
  2317. const autoScheduled = isAutoRunScheduledPhase();
  2318. for (const step of STEP_IDS) {
  2319. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  2320. if (!btn) continue;
  2321. if (anyRunning || autoLocked || autoScheduled) {
  2322. btn.disabled = true;
  2323. } else if (step === 1) {
  2324. btn.disabled = false;
  2325. } else {
  2326. const currentIndex = STEP_IDS.indexOf(step);
  2327. const prevStep = currentIndex > 0 ? STEP_IDS[currentIndex - 1] : null;
  2328. const prevStatus = prevStep === null ? 'completed' : statuses[prevStep];
  2329. const currentStatus = statuses[step];
  2330. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  2331. }
  2332. }
  2333. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  2334. const step = Number(btn.dataset.step);
  2335. const currentStatus = statuses[step];
  2336. const currentIndex = STEP_IDS.indexOf(step);
  2337. const prevStep = currentIndex > 0 ? STEP_IDS[currentIndex - 1] : null;
  2338. const prevStatus = prevStep === null ? 'completed' : statuses[prevStep];
  2339. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  2340. btn.style.display = 'none';
  2341. btn.disabled = true;
  2342. btn.title = '当前不可跳过';
  2343. return;
  2344. }
  2345. if (prevStep !== null && !isDoneStatus(prevStatus)) {
  2346. btn.style.display = 'none';
  2347. btn.disabled = true;
  2348. btn.title = `请先完成步骤 ${prevStep}`;
  2349. return;
  2350. }
  2351. btn.style.display = '';
  2352. btn.disabled = false;
  2353. btn.title = `跳过步骤 ${step}`;
  2354. });
  2355. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  2356. const disableIcloudControls = anyRunning || autoScheduled || autoLocked;
  2357. if (btnIcloudRefresh) btnIcloudRefresh.disabled = disableIcloudControls;
  2358. if (btnIcloudDeleteUsed) btnIcloudDeleteUsed.disabled = disableIcloudControls || !hasDeletableUsedIcloudAliases();
  2359. if (selectIcloudHostPreference) selectIcloudHostPreference.disabled = disableIcloudControls;
  2360. if (checkboxAutoDeleteIcloud) checkboxAutoDeleteIcloud.disabled = disableIcloudControls;
  2361. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  2362. }
  2363. function updateStopButtonState(active) {
  2364. btnStop.disabled = !active;
  2365. }
  2366. function updateStatusDisplay(state) {
  2367. if (!state || !state.stepStatuses) return;
  2368. statusBar.className = 'status-bar';
  2369. const countdown = getActiveAutoRunCountdown();
  2370. if (countdown) {
  2371. const remainingMs = countdown.at - Date.now();
  2372. displayStatus.textContent = remainingMs > 0
  2373. ? `${countdown.title},剩余 ${formatCountdown(remainingMs)}`
  2374. : `${countdown.title},即将结束...`;
  2375. statusBar.classList.add(countdown.tone === 'scheduled' ? 'scheduled' : 'running');
  2376. return;
  2377. }
  2378. if (isAutoRunScheduledPhase()) {
  2379. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  2380. ? currentAutoRun.scheduledAt - Date.now()
  2381. : 0;
  2382. displayStatus.textContent = remainingMs > 0
  2383. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  2384. : '倒计时即将结束,正在准备启动...';
  2385. statusBar.classList.add('scheduled');
  2386. return;
  2387. }
  2388. if (isAutoRunPausedPhase()) {
  2389. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  2390. statusBar.classList.add('paused');
  2391. return;
  2392. }
  2393. if (isAutoRunWaitingStepPhase()) {
  2394. const runningSteps = getRunningSteps(state);
  2395. displayStatus.textContent = runningSteps.length
  2396. ? `自动等待步骤 ${runningSteps.join(', ')} 完成后继续${getAutoRunLabel()}`
  2397. : `自动正在按最新进度准备继续${getAutoRunLabel()}`;
  2398. statusBar.classList.add('running');
  2399. return;
  2400. }
  2401. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  2402. if (running) {
  2403. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  2404. statusBar.classList.add('running');
  2405. return;
  2406. }
  2407. if (isAutoRunLockedPhase()) {
  2408. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  2409. statusBar.classList.add('running');
  2410. return;
  2411. }
  2412. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  2413. if (failed) {
  2414. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  2415. statusBar.classList.add('failed');
  2416. return;
  2417. }
  2418. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  2419. if (stopped) {
  2420. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  2421. statusBar.classList.add('stopped');
  2422. return;
  2423. }
  2424. const lastCompleted = Object.entries(state.stepStatuses)
  2425. .filter(([, s]) => isDoneStatus(s))
  2426. .map(([k]) => Number(k))
  2427. .sort((a, b) => b - a)[0];
  2428. if (lastCompleted === STEP_IDS[STEP_IDS.length - 1]) {
  2429. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  2430. statusBar.classList.add('completed');
  2431. } else if (lastCompleted) {
  2432. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  2433. ? `步骤 ${lastCompleted} 已跳过`
  2434. : `步骤 ${lastCompleted} 已完成`;
  2435. } else {
  2436. displayStatus.textContent = '就绪';
  2437. }
  2438. }
  2439. function appendLog(entry) {
  2440. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', {
  2441. hour12: false,
  2442. timeZone: DISPLAY_TIMEZONE,
  2443. });
  2444. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  2445. const line = document.createElement('div');
  2446. line.className = `log-line log-${entry.level}`;
  2447. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  2448. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  2449. let html = `<span class="log-time">${time}</span> `;
  2450. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  2451. if (stepNum) {
  2452. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  2453. }
  2454. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  2455. line.innerHTML = html;
  2456. logArea.appendChild(line);
  2457. logArea.scrollTop = logArea.scrollHeight;
  2458. }
  2459. function escapeHtml(text) {
  2460. const div = document.createElement('div');
  2461. div.textContent = text;
  2462. return div.innerHTML;
  2463. }
  2464. async function fetchGeneratedEmail(options = {}) {
  2465. const { showFailureToast = true } = options;
  2466. const uiCopy = getCurrentRegistrationEmailUiCopy();
  2467. if (isCustomMailProvider()) {
  2468. throw new Error('当前邮箱服务为自定义邮箱,请直接填写注册邮箱。');
  2469. }
  2470. const defaultLabel = uiCopy.buttonLabel;
  2471. btnFetchEmail.disabled = true;
  2472. btnFetchEmail.textContent = '...';
  2473. try {
  2474. const response = await chrome.runtime.sendMessage({
  2475. type: 'FETCH_GENERATED_EMAIL',
  2476. source: 'sidepanel',
  2477. payload: {
  2478. generateNew: true,
  2479. generator: selectEmailGenerator.value,
  2480. mailProvider: selectMailProvider.value,
  2481. ...buildManagedAliasBaseEmailPayload(),
  2482. },
  2483. });
  2484. if (response?.error) {
  2485. throw new Error(response.error);
  2486. }
  2487. if (!response?.email) {
  2488. throw new Error('未返回可用邮箱。');
  2489. }
  2490. inputEmail.value = response.email;
  2491. if (getSelectedEmailGenerator() === 'icloud') {
  2492. queueIcloudAliasRefresh();
  2493. }
  2494. showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500);
  2495. return response.email;
  2496. } catch (err) {
  2497. if (showFailureToast) {
  2498. showToast(`${uiCopy.label}${uiCopy.successVerb}失败:${err.message}`, 'error');
  2499. }
  2500. throw err;
  2501. } finally {
  2502. btnFetchEmail.disabled = false;
  2503. btnFetchEmail.textContent = defaultLabel;
  2504. }
  2505. }
  2506. function syncToggleButtonLabel(button, input, labels) {
  2507. if (!button || !input) return;
  2508. const isHidden = input.type === 'password';
  2509. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  2510. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  2511. button.title = isHidden ? labels.show : labels.hide;
  2512. }
  2513. async function copyTextToClipboard(text) {
  2514. const value = String(text || '').trim();
  2515. if (!value) {
  2516. throw new Error('没有可复制的内容。');
  2517. }
  2518. if (!navigator.clipboard?.writeText) {
  2519. throw new Error('当前环境不支持剪贴板复制。');
  2520. }
  2521. await navigator.clipboard.writeText(value);
  2522. }
  2523. const hotmailManager = window.SidepanelHotmailManager?.createHotmailManager({
  2524. state: {
  2525. getLatestState: () => latestState,
  2526. syncLatestState,
  2527. },
  2528. dom: {
  2529. btnAddHotmailAccount,
  2530. btnClearUsedHotmailAccounts,
  2531. btnDeleteAllHotmailAccounts,
  2532. btnHotmailUsageGuide,
  2533. btnImportHotmailAccounts,
  2534. btnToggleHotmailList,
  2535. hotmailAccountsList,
  2536. hotmailListShell,
  2537. inputEmail,
  2538. inputHotmailClientId,
  2539. inputHotmailEmail,
  2540. inputHotmailImport,
  2541. inputHotmailPassword,
  2542. inputHotmailRefreshToken,
  2543. selectMailProvider,
  2544. },
  2545. helpers: {
  2546. copyTextToClipboard,
  2547. escapeHtml,
  2548. getCurrentHotmailEmail,
  2549. getHotmailAccounts,
  2550. openConfirmModal,
  2551. showToast,
  2552. },
  2553. runtime: {
  2554. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2555. },
  2556. constants: {
  2557. copyIcon: COPY_ICON,
  2558. displayTimeZone: DISPLAY_TIMEZONE,
  2559. expandedStorageKey: 'multipage-hotmail-list-expanded',
  2560. },
  2561. hotmailUtils: {
  2562. filterHotmailAccountsByUsage,
  2563. getHotmailBulkActionLabel,
  2564. getHotmailListToggleLabel,
  2565. parseHotmailImportText,
  2566. shouldClearHotmailCurrentSelection,
  2567. upsertHotmailAccountInList,
  2568. },
  2569. });
  2570. const initHotmailListExpandedState = hotmailManager?.initHotmailListExpandedState
  2571. || (() => { });
  2572. const renderHotmailAccounts = hotmailManager?.renderHotmailAccounts
  2573. || (() => { });
  2574. const bindHotmailEvents = hotmailManager?.bindHotmailEvents
  2575. || (() => { });
  2576. bindHotmailEvents();
  2577. const icloudManager = window.SidepanelIcloudManager?.createIcloudManager({
  2578. dom: {
  2579. btnIcloudBulkDelete,
  2580. btnIcloudBulkPreserve,
  2581. btnIcloudBulkUnpreserve,
  2582. btnIcloudBulkUnused,
  2583. btnIcloudBulkUsed,
  2584. btnIcloudDeleteUsed,
  2585. btnIcloudLoginDone,
  2586. btnIcloudRefresh,
  2587. checkboxIcloudSelectAll,
  2588. icloudList,
  2589. icloudLoginHelp,
  2590. icloudLoginHelpText,
  2591. icloudLoginHelpTitle,
  2592. icloudSection,
  2593. icloudSelectionSummary,
  2594. icloudSummary,
  2595. inputIcloudSearch,
  2596. selectIcloudFilter,
  2597. },
  2598. helpers: {
  2599. copyTextToClipboard,
  2600. escapeHtml,
  2601. openConfirmModal,
  2602. showToast,
  2603. },
  2604. runtime: {
  2605. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2606. },
  2607. });
  2608. const hideIcloudLoginHelp = icloudManager?.hideIcloudLoginHelp
  2609. || (() => { });
  2610. const hasDeletableUsedIcloudAliases = icloudManager?.hasDeletableUsedAliases
  2611. || (() => false);
  2612. const queueIcloudAliasRefresh = icloudManager?.queueIcloudAliasRefresh
  2613. || (() => { });
  2614. const refreshIcloudAliases = icloudManager?.refreshIcloudAliases
  2615. || (async () => { });
  2616. const renderIcloudAliases = icloudManager?.renderIcloudAliases
  2617. || (() => { });
  2618. const resetIcloudManager = icloudManager?.reset
  2619. || (() => { });
  2620. const showIcloudLoginHelp = icloudManager?.showIcloudLoginHelp
  2621. || (() => { });
  2622. const updateIcloudBulkUI = icloudManager?.updateIcloudBulkUI
  2623. || (() => { });
  2624. const bindIcloudEvents = icloudManager?.bindIcloudEvents
  2625. || (() => { });
  2626. bindIcloudEvents();
  2627. const luckmailManager = window.SidepanelLuckmailManager?.createLuckmailManager({
  2628. dom: {
  2629. btnLuckmailBulkDisable,
  2630. btnLuckmailBulkEnable,
  2631. btnLuckmailBulkPreserve,
  2632. btnLuckmailBulkUnpreserve,
  2633. btnLuckmailBulkUnused,
  2634. btnLuckmailBulkUsed,
  2635. btnLuckmailDisableUsed,
  2636. btnLuckmailRefresh,
  2637. checkboxLuckmailSelectAll,
  2638. inputEmail,
  2639. inputLuckmailSearch,
  2640. luckmailList,
  2641. luckmailSection,
  2642. luckmailSelectionSummary,
  2643. luckmailSummary,
  2644. selectLuckmailFilter,
  2645. },
  2646. helpers: {
  2647. copyTextToClipboard,
  2648. escapeHtml,
  2649. formatLuckmailDateTime,
  2650. getLuckmailPreserveTagName,
  2651. normalizeLuckmailProjectName,
  2652. openConfirmModal,
  2653. showToast,
  2654. },
  2655. runtime: {
  2656. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2657. },
  2658. constants: {
  2659. copyIcon: COPY_ICON,
  2660. },
  2661. });
  2662. const queueLuckmailPurchaseRefresh = luckmailManager?.queueLuckmailPurchaseRefresh
  2663. || (() => { });
  2664. const refreshLuckmailPurchases = luckmailManager?.refreshLuckmailPurchases
  2665. || (async () => { });
  2666. const renderLuckmailPurchases = luckmailManager?.renderLuckmailPurchases
  2667. || (() => { });
  2668. const resetLuckmailManager = luckmailManager?.reset
  2669. || (() => { });
  2670. const bindLuckmailEvents = luckmailManager?.bindLuckmailEvents
  2671. || (() => { });
  2672. bindLuckmailEvents();
  2673. const accountRecordsManager = window.SidepanelAccountRecordsManager?.createAccountRecordsManager({
  2674. state: {
  2675. getLatestState: () => latestState,
  2676. syncLatestState,
  2677. },
  2678. dom: {
  2679. accountRecordsList,
  2680. accountRecordsMeta,
  2681. accountRecordsOverlay,
  2682. accountRecordsPageLabel,
  2683. accountRecordsStats,
  2684. btnAccountRecordsNext,
  2685. btnAccountRecordsPrev,
  2686. btnClearAccountRecords,
  2687. btnCloseAccountRecords,
  2688. btnOpenAccountRecords,
  2689. },
  2690. helpers: {
  2691. escapeHtml,
  2692. openConfirmModal,
  2693. showToast,
  2694. },
  2695. runtime: {
  2696. sendMessage: (message) => chrome.runtime.sendMessage(message),
  2697. },
  2698. constants: {
  2699. displayTimeZone: DISPLAY_TIMEZONE,
  2700. pageSize: 10,
  2701. },
  2702. });
  2703. const renderAccountRecords = accountRecordsManager?.render
  2704. || (() => { });
  2705. const bindAccountRecordEvents = accountRecordsManager?.bindEvents
  2706. || (() => { });
  2707. bindAccountRecordEvents();
  2708. renderStepsList();
  2709. async function exportSettingsFile() {
  2710. closeConfigMenu();
  2711. configActionInFlight = true;
  2712. updateConfigMenuControls();
  2713. try {
  2714. await flushPendingSettingsBeforeExport();
  2715. const response = await chrome.runtime.sendMessage({
  2716. type: 'EXPORT_SETTINGS',
  2717. source: 'sidepanel',
  2718. payload: {},
  2719. });
  2720. if (response?.error) {
  2721. throw new Error(response.error);
  2722. }
  2723. if (!response?.fileContent || !response?.fileName) {
  2724. throw new Error('\u672a\u751f\u6210\u53ef\u4e0b\u8f7d\u7684\u914d\u7f6e\u6587\u4ef6\u3002');
  2725. }
  2726. downloadTextFile(response.fileContent, response.fileName);
  2727. showToast('\u914d\u7f6e\u5df2\u5bfc\u51fa\uff1a' + response.fileName, 'success', 2200);
  2728. } catch (err) {
  2729. showToast('\u5bfc\u51fa\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  2730. } finally {
  2731. configActionInFlight = false;
  2732. updateConfigMenuControls();
  2733. }
  2734. }
  2735. async function importSettingsFromFile(file) {
  2736. if (!file) return;
  2737. configActionInFlight = true;
  2738. closeConfigMenu();
  2739. updateConfigMenuControls();
  2740. try {
  2741. await settlePendingSettingsBeforeImport();
  2742. const rawText = await file.text();
  2743. let parsedConfig = null;
  2744. try {
  2745. parsedConfig = JSON.parse(rawText);
  2746. } catch {
  2747. throw new Error('\u914d\u7f6e\u6587\u4ef6\u4e0d\u662f\u6709\u6548\u7684 JSON\u3002');
  2748. }
  2749. const confirmed = await openConfirmModal({
  2750. title: '\u5bfc\u5165\u914d\u7f6e',
  2751. message: '\u786e\u8ba4\u5bfc\u5165\u914d\u7f6e\u6587\u4ef6 "' + file.name + '" \u5417\uff1f\u5bfc\u5165\u540e\u4f1a\u8986\u76d6\u5f53\u524d\u914d\u7f6e\u3002',
  2752. confirmLabel: '\u786e\u8ba4\u8986\u76d6\u5bfc\u5165',
  2753. confirmVariant: 'btn-danger',
  2754. });
  2755. if (!confirmed) {
  2756. return;
  2757. }
  2758. const response = await chrome.runtime.sendMessage({
  2759. type: 'IMPORT_SETTINGS',
  2760. source: 'sidepanel',
  2761. payload: {
  2762. config: parsedConfig,
  2763. },
  2764. });
  2765. if (response?.error) {
  2766. throw new Error(response.error);
  2767. }
  2768. if (!response?.state) {
  2769. throw new Error('\u5bfc\u5165\u540e\u672a\u8fd4\u56de\u6700\u65b0\u914d\u7f6e\u72b6\u6001\u3002');
  2770. }
  2771. applySettingsState(response.state);
  2772. updateStatusDisplay(latestState);
  2773. showToast('\u914d\u7f6e\u5df2\u5bfc\u5165\uff0c\u5f53\u524d\u914d\u7f6e\u5df2\u8986\u76d6\u3002', 'success', 2200);
  2774. } catch (err) {
  2775. showToast('\u5bfc\u5165\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  2776. } finally {
  2777. configActionInFlight = false;
  2778. updateConfigMenuControls();
  2779. if (inputImportSettingsFile) {
  2780. inputImportSettingsFile.value = '';
  2781. }
  2782. }
  2783. }
  2784. function syncPasswordToggleLabel() {
  2785. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  2786. show: '显示密码',
  2787. hide: '隐藏密码',
  2788. });
  2789. }
  2790. function syncVpsUrlToggleLabel() {
  2791. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  2792. show: '显示 CPA 地址',
  2793. hide: '隐藏 CPA 地址',
  2794. });
  2795. }
  2796. function syncVpsPasswordToggleLabel() {
  2797. syncToggleButtonLabel(btnToggleVpsPassword, inputVpsPassword, {
  2798. show: '显示管理密钥',
  2799. hide: '隐藏管理密钥',
  2800. });
  2801. }
  2802. async function maybeTakeoverAutoRun(actionLabel) {
  2803. if (!isAutoRunPausedPhase()) {
  2804. return true;
  2805. }
  2806. const confirmed = await openConfirmModal({
  2807. title: '接管自动',
  2808. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  2809. confirmLabel: '确认接管',
  2810. confirmVariant: 'btn-primary',
  2811. });
  2812. if (!confirmed) {
  2813. return false;
  2814. }
  2815. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  2816. return true;
  2817. }
  2818. async function handleSkipStep(step) {
  2819. if (isAutoRunPausedPhase()) {
  2820. const takeoverResponse = await chrome.runtime.sendMessage({
  2821. type: 'TAKEOVER_AUTO_RUN',
  2822. source: 'sidepanel',
  2823. payload: {},
  2824. });
  2825. if (takeoverResponse?.error) {
  2826. throw new Error(takeoverResponse.error);
  2827. }
  2828. }
  2829. const response = await chrome.runtime.sendMessage({
  2830. type: 'SKIP_STEP',
  2831. source: 'sidepanel',
  2832. payload: { step },
  2833. });
  2834. if (response?.error) {
  2835. throw new Error(response.error);
  2836. }
  2837. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  2838. }
  2839. // ============================================================
  2840. // Button Handlers
  2841. // ============================================================
  2842. stepsList?.addEventListener('click', async (event) => {
  2843. const btn = event.target.closest('.step-btn');
  2844. if (!btn) {
  2845. return;
  2846. }
  2847. try {
  2848. const step = Number(btn.dataset.step);
  2849. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  2850. return;
  2851. }
  2852. if (step === 3) {
  2853. if (inputPassword.value !== (latestState?.customPassword || '')) {
  2854. await chrome.runtime.sendMessage({
  2855. type: 'SAVE_SETTING',
  2856. source: 'sidepanel',
  2857. payload: { customPassword: inputPassword.value },
  2858. });
  2859. syncLatestState({ customPassword: inputPassword.value });
  2860. }
  2861. let email = inputEmail.value.trim();
  2862. if (selectMailProvider.value === 'hotmail-api' || isLuckmailProvider()) {
  2863. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  2864. if (response?.error) {
  2865. throw new Error(response.error);
  2866. }
  2867. } else if (false && usesGeneratedAliasMailProvider(selectMailProvider.value)) {
  2868. const emailPrefix = inputEmailPrefix.value.trim();
  2869. if (!emailPrefix) {
  2870. showToast(selectMailProvider.value === GMAIL_PROVIDER ? '请先填写 Gmail 原邮箱。' : '请先填写 2925 邮箱前缀。', 'warn');
  2871. return;
  2872. }
  2873. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, emailPrefix } });
  2874. if (response?.error) {
  2875. throw new Error(response.error);
  2876. }
  2877. } else {
  2878. let email = inputEmail.value.trim();
  2879. if (!email) {
  2880. if (isCustomMailProvider()) {
  2881. showToast('当前邮箱服务为自定义邮箱,请先填写注册邮箱后再执行第 3 步。', 'warn');
  2882. return;
  2883. }
  2884. try {
  2885. email = await fetchGeneratedEmail({ showFailureToast: false });
  2886. } catch (err) {
  2887. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  2888. return;
  2889. }
  2890. }
  2891. if (!validateCurrentRegistrationEmail(email, { showToastOnFailure: true })) {
  2892. return;
  2893. }
  2894. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  2895. if (response?.error) {
  2896. throw new Error(response.error);
  2897. }
  2898. }
  2899. } else {
  2900. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  2901. if (response?.error) {
  2902. throw new Error(response.error);
  2903. }
  2904. }
  2905. } catch (err) {
  2906. showToast(err.message, 'error');
  2907. }
  2908. });
  2909. btnFetchEmail.addEventListener('click', async () => {
  2910. if (selectMailProvider.value === 'hotmail-api' || isLuckmailProvider() || isCustomMailProvider()) {
  2911. return;
  2912. }
  2913. await fetchGeneratedEmail().catch(() => { });
  2914. });
  2915. btnTogglePassword.addEventListener('click', () => {
  2916. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  2917. syncPasswordToggleLabel();
  2918. });
  2919. btnToggleVpsUrl.addEventListener('click', () => {
  2920. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  2921. syncVpsUrlToggleLabel();
  2922. });
  2923. btnToggleVpsPassword.addEventListener('click', () => {
  2924. inputVpsPassword.type = inputVpsPassword.type === 'password' ? 'text' : 'password';
  2925. syncVpsPasswordToggleLabel();
  2926. });
  2927. btnMailLogin?.addEventListener('click', async () => {
  2928. const config = getMailProviderLoginConfig();
  2929. const loginUrl = getMailProviderLoginUrl();
  2930. if (!config || !loginUrl) {
  2931. return;
  2932. }
  2933. try {
  2934. await chrome.tabs.create({ url: loginUrl, active: true });
  2935. } catch (err) {
  2936. showToast(`打开${config.label}失败:${err.message}`, 'error');
  2937. }
  2938. });
  2939. localCpaStep9ModeButtons.forEach((button) => {
  2940. button.addEventListener('click', () => {
  2941. const nextMode = button.dataset.localCpaStep9Mode;
  2942. if (getSelectedLocalCpaStep9Mode() === normalizeLocalCpaStep9Mode(nextMode)) {
  2943. return;
  2944. }
  2945. setLocalCpaStep9Mode(nextMode);
  2946. markSettingsDirty(true);
  2947. saveSettings({ silent: true }).catch(() => { });
  2948. });
  2949. });
  2950. hotmailServiceModeButtons.forEach((button) => {
  2951. button.addEventListener('click', () => {
  2952. if (button.disabled) {
  2953. return;
  2954. }
  2955. const nextMode = button.dataset.hotmailServiceMode;
  2956. if (getSelectedHotmailServiceMode() === normalizeHotmailServiceMode(nextMode)) {
  2957. return;
  2958. }
  2959. setHotmailServiceMode(nextMode);
  2960. updateMailProviderUI();
  2961. markSettingsDirty(true);
  2962. saveSettings({ silent: true }).catch(() => { });
  2963. });
  2964. });
  2965. btnSaveSettings.addEventListener('click', async () => {
  2966. if (!settingsDirty) {
  2967. showToast('配置已是最新', 'info', 1400);
  2968. return;
  2969. }
  2970. await saveSettings({ silent: false }).catch(() => { });
  2971. });
  2972. btnStop.addEventListener('click', async () => {
  2973. btnStop.disabled = true;
  2974. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  2975. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  2976. });
  2977. btnConfigMenu?.addEventListener('click', (event) => {
  2978. event.stopPropagation();
  2979. toggleConfigMenu();
  2980. });
  2981. configMenu?.addEventListener('click', (event) => {
  2982. event.stopPropagation();
  2983. });
  2984. btnExportSettings?.addEventListener('click', async () => {
  2985. if (configActionInFlight || settingsSaveInFlight) {
  2986. return;
  2987. }
  2988. await exportSettingsFile();
  2989. });
  2990. btnImportSettings?.addEventListener('click', async () => {
  2991. if (configActionInFlight || settingsSaveInFlight) {
  2992. return;
  2993. }
  2994. closeConfigMenu();
  2995. if (inputImportSettingsFile) {
  2996. inputImportSettingsFile.value = '';
  2997. inputImportSettingsFile.click();
  2998. }
  2999. });
  3000. inputImportSettingsFile?.addEventListener('change', async () => {
  3001. const file = inputImportSettingsFile.files?.[0] || null;
  3002. await importSettingsFromFile(file);
  3003. });
  3004. autoStartModal?.addEventListener('click', (event) => {
  3005. if (event.target === autoStartModal) {
  3006. resolveModalChoice(null);
  3007. }
  3008. });
  3009. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  3010. // Auto Run
  3011. btnAutoRun.addEventListener('click', async () => {
  3012. try {
  3013. const totalRuns = getRunCountValue();
  3014. let mode = 'restart';
  3015. const autoRunSkipFailures = inputAutoSkipFailures.checked;
  3016. const fallbackThreadIntervalMinutes = normalizeAutoRunThreadIntervalMinutes(
  3017. inputAutoSkipFailuresThreadIntervalMinutes.value
  3018. );
  3019. inputAutoSkipFailuresThreadIntervalMinutes.value = String(fallbackThreadIntervalMinutes);
  3020. if (shouldOfferAutoModeChoice()) {
  3021. const startStep = getFirstUnfinishedStep();
  3022. const runningStep = getRunningSteps()[0] ?? null;
  3023. const choice = await openAutoStartChoiceDialog(startStep, { runningStep });
  3024. if (!choice) {
  3025. return;
  3026. }
  3027. mode = choice;
  3028. }
  3029. if (shouldWarnAutoRunFallbackRisk(totalRuns, autoRunSkipFailures)
  3030. && !isAutoRunFallbackRiskPromptDismissed()) {
  3031. const result = await openAutoRunFallbackRiskConfirmModal(totalRuns, fallbackThreadIntervalMinutes);
  3032. if (!result.confirmed) {
  3033. return;
  3034. }
  3035. if (result.dismissPrompt) {
  3036. setAutoRunFallbackRiskPromptDismissed(true);
  3037. }
  3038. }
  3039. btnAutoRun.disabled = true;
  3040. inputRunCount.disabled = true;
  3041. const delayEnabled = inputAutoDelayEnabled.checked;
  3042. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  3043. inputAutoDelayMinutes.value = String(delayMinutes);
  3044. btnAutoRun.innerHTML = delayEnabled
  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. : '<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> 运行中...';
  3047. const response = await chrome.runtime.sendMessage({
  3048. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  3049. source: 'sidepanel',
  3050. payload: {
  3051. totalRuns,
  3052. delayMinutes,
  3053. autoRunSkipFailures,
  3054. mode,
  3055. },
  3056. });
  3057. if (response?.error) {
  3058. throw new Error(response.error);
  3059. }
  3060. } catch (err) {
  3061. setDefaultAutoRunButton();
  3062. inputRunCount.disabled = false;
  3063. showToast(err.message, 'error');
  3064. }
  3065. });
  3066. btnAutoContinue.addEventListener('click', async () => {
  3067. const email = inputEmail.value.trim();
  3068. if (!email) {
  3069. showToast(
  3070. isCustomMailProvider() ? '请先填写自定义注册邮箱。' : '请先获取或粘贴邮箱。',
  3071. 'warn'
  3072. );
  3073. return;
  3074. }
  3075. autoContinueBar.style.display = 'none';
  3076. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  3077. });
  3078. btnAutoRunNow?.addEventListener('click', async () => {
  3079. try {
  3080. btnAutoRunNow.disabled = true;
  3081. const waitingInterval = currentAutoRun.phase === 'waiting_interval';
  3082. await chrome.runtime.sendMessage({
  3083. type: waitingInterval ? 'SKIP_AUTO_RUN_COUNTDOWN' : 'START_SCHEDULED_AUTO_RUN_NOW',
  3084. source: 'sidepanel',
  3085. payload: {},
  3086. });
  3087. if (waitingInterval) {
  3088. showToast('已跳过当前倒计时,自动流程将立即继续。', 'info', 1800);
  3089. }
  3090. } catch (err) {
  3091. showToast(err.message, 'error');
  3092. } finally {
  3093. btnAutoRunNow.disabled = false;
  3094. }
  3095. });
  3096. btnAutoCancelSchedule?.addEventListener('click', async () => {
  3097. try {
  3098. btnAutoCancelSchedule.disabled = true;
  3099. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  3100. showToast('已取消倒计时计划。', 'info', 1800);
  3101. } catch (err) {
  3102. showToast(err.message, 'error');
  3103. } finally {
  3104. btnAutoCancelSchedule.disabled = false;
  3105. }
  3106. });
  3107. // Reset
  3108. btnReset.addEventListener('click', async () => {
  3109. const confirmed = await openConfirmModal({
  3110. title: '重置流程',
  3111. message: '确认重置全部步骤和数据吗?',
  3112. confirmLabel: '确认重置',
  3113. confirmVariant: 'btn-danger',
  3114. });
  3115. if (!confirmed) {
  3116. return;
  3117. }
  3118. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  3119. syncLatestState({
  3120. stepStatuses: STEP_DEFAULT_STATUSES,
  3121. currentHotmailAccountId: null,
  3122. currentLuckmailPurchase: null,
  3123. currentLuckmailMailCursor: null,
  3124. email: null,
  3125. });
  3126. syncAutoRunState({
  3127. autoRunning: false,
  3128. autoRunPhase: 'idle',
  3129. autoRunCurrentRun: 0,
  3130. autoRunTotalRuns: 1,
  3131. autoRunAttemptRun: 0,
  3132. scheduledAutoRunAt: null,
  3133. autoRunCountdownAt: null,
  3134. autoRunCountdownTitle: '',
  3135. autoRunCountdownNote: '',
  3136. });
  3137. displayOauthUrl.textContent = '等待中...';
  3138. displayOauthUrl.classList.remove('has-value');
  3139. displayLocalhostUrl.textContent = '等待中...';
  3140. displayLocalhostUrl.classList.remove('has-value');
  3141. inputEmail.value = '';
  3142. displayStatus.textContent = '就绪';
  3143. statusBar.className = 'status-bar';
  3144. logArea.innerHTML = '';
  3145. resetIcloudManager();
  3146. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  3147. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  3148. setDefaultAutoRunButton();
  3149. applyAutoRunStatus(currentAutoRun);
  3150. markSettingsDirty(false);
  3151. updateStopButtonState(false);
  3152. updateButtonStates();
  3153. updateProgressCounter();
  3154. renderHotmailAccounts();
  3155. resetLuckmailManager();
  3156. if (isLuckmailProvider()) {
  3157. queueLuckmailPurchaseRefresh();
  3158. }
  3159. });
  3160. // Clear log
  3161. btnClearLog.addEventListener('click', () => {
  3162. logArea.innerHTML = '';
  3163. });
  3164. // Save settings on change
  3165. inputEmail.addEventListener('change', async () => {
  3166. if (selectMailProvider.value === 'hotmail-api' || isLuckmailProvider()) {
  3167. return;
  3168. }
  3169. const email = inputEmail.value.trim();
  3170. inputEmail.value = email;
  3171. try {
  3172. if (email) {
  3173. if (!validateCurrentRegistrationEmail(email, { showToastOnFailure: true })) {
  3174. return;
  3175. }
  3176. const response = await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  3177. if (response?.error) {
  3178. throw new Error(response.error);
  3179. }
  3180. } else {
  3181. await setRuntimeEmailState(null);
  3182. }
  3183. } catch (err) {
  3184. showToast(err.message, 'error');
  3185. }
  3186. });
  3187. inputEmail.addEventListener('input', updateButtonStates);
  3188. inputVpsUrl.addEventListener('input', () => {
  3189. markSettingsDirty(true);
  3190. scheduleSettingsAutoSave();
  3191. });
  3192. inputVpsUrl.addEventListener('blur', () => {
  3193. saveSettings({ silent: true }).catch(() => { });
  3194. });
  3195. inputVpsPassword.addEventListener('input', () => {
  3196. markSettingsDirty(true);
  3197. scheduleSettingsAutoSave();
  3198. });
  3199. inputVpsPassword.addEventListener('blur', () => {
  3200. saveSettings({ silent: true }).catch(() => { });
  3201. });
  3202. [inputHotmailRemoteBaseUrl, inputHotmailLocalBaseUrl].forEach((input) => {
  3203. input?.addEventListener('input', () => {
  3204. markSettingsDirty(true);
  3205. scheduleSettingsAutoSave();
  3206. });
  3207. input?.addEventListener('blur', () => {
  3208. saveSettings({ silent: true }).catch(() => { });
  3209. });
  3210. });
  3211. [inputLuckmailApiKey, inputLuckmailBaseUrl, inputLuckmailDomain].forEach((input) => {
  3212. input?.addEventListener('input', () => {
  3213. markSettingsDirty(true);
  3214. scheduleSettingsAutoSave();
  3215. });
  3216. input?.addEventListener('blur', () => {
  3217. saveSettings({ silent: true }).catch(() => { });
  3218. });
  3219. });
  3220. selectLuckmailEmailType?.addEventListener('change', () => {
  3221. markSettingsDirty(true);
  3222. saveSettings({ silent: true }).catch(() => { });
  3223. });
  3224. inputPassword.addEventListener('input', () => {
  3225. markSettingsDirty(true);
  3226. updateButtonStates();
  3227. scheduleSettingsAutoSave();
  3228. });
  3229. inputPassword.addEventListener('blur', () => {
  3230. saveSettings({ silent: true }).catch(() => { });
  3231. });
  3232. selectMailProvider.addEventListener('change', async () => {
  3233. const previousProvider = latestState?.mailProvider || '';
  3234. const previousMail2925Mode = latestState?.mail2925Mode;
  3235. const nextProvider = selectMailProvider.value;
  3236. syncManagedAliasBaseEmailDraftFromInput(previousProvider);
  3237. setManagedAliasBaseEmailInputForProvider(nextProvider, latestState);
  3238. updateMailProviderUI();
  3239. const leavingHotmail = previousProvider === 'hotmail-api'
  3240. && nextProvider !== 'hotmail-api'
  3241. && isCurrentEmailManagedByHotmail();
  3242. const leavingLuckmail = previousProvider === LUCKMAIL_PROVIDER
  3243. && nextProvider !== LUCKMAIL_PROVIDER
  3244. && isCurrentEmailManagedByLuckmail();
  3245. const leavingA4sky = previousProvider === A4SKY_PROVIDER
  3246. && nextProvider !== A4SKY_PROVIDER
  3247. && /^n\d{14}@a4sky\.com$/i.test(String(inputEmail.value || latestState?.email || '').trim());
  3248. const leavingGeneratedAlias = (
  3249. previousProvider !== nextProvider
  3250. || (previousProvider === '2925' && normalizeMail2925Mode(previousMail2925Mode) !== getSelectedMail2925Mode())
  3251. ) && usesGeneratedAliasMailProvider(previousProvider, previousMail2925Mode)
  3252. && isCurrentEmailManagedByGeneratedAlias(previousProvider, latestState, previousMail2925Mode);
  3253. if (leavingHotmail || leavingLuckmail || leavingA4sky || leavingGeneratedAlias) {
  3254. await clearRegistrationEmail({ silent: true }).catch(() => { });
  3255. }
  3256. if (nextProvider === LUCKMAIL_PROVIDER) {
  3257. queueLuckmailPurchaseRefresh();
  3258. }
  3259. markSettingsDirty(true);
  3260. saveSettings({ silent: true }).catch(() => { });
  3261. });
  3262. mail2925ModeButtons.forEach((button) => {
  3263. button.addEventListener('click', async () => {
  3264. const nextMode = normalizeMail2925Mode(button.dataset.mail2925Mode);
  3265. const previousMode = normalizeMail2925Mode(latestState?.mail2925Mode);
  3266. if (nextMode === getSelectedMail2925Mode()) {
  3267. return;
  3268. }
  3269. setMail2925Mode(nextMode);
  3270. updateMailProviderUI();
  3271. const leavingGeneratedAlias = selectMailProvider.value === '2925'
  3272. && previousMode === MAIL_2925_MODE_PROVIDE
  3273. && nextMode !== MAIL_2925_MODE_PROVIDE
  3274. && isCurrentEmailManagedByGeneratedAlias('2925', latestState, previousMode);
  3275. if (leavingGeneratedAlias) {
  3276. await clearRegistrationEmail({ silent: true }).catch(() => { });
  3277. }
  3278. markSettingsDirty(true);
  3279. saveSettings({ silent: true }).catch(() => { });
  3280. });
  3281. });
  3282. selectEmailGenerator.addEventListener('change', () => {
  3283. updateMailProviderUI();
  3284. clearRegistrationEmail({ silent: true }).catch(() => { });
  3285. markSettingsDirty(true);
  3286. saveSettings({ silent: true }).catch(() => { });
  3287. });
  3288. selectIcloudHostPreference?.addEventListener('change', () => {
  3289. markSettingsDirty(true);
  3290. saveSettings({ silent: true }).catch(() => { });
  3291. if (getSelectedEmailGenerator() === 'icloud') {
  3292. queueIcloudAliasRefresh();
  3293. }
  3294. });
  3295. checkboxAutoDeleteIcloud?.addEventListener('change', () => {
  3296. markSettingsDirty(true);
  3297. saveSettings({ silent: true }).catch(() => { });
  3298. });
  3299. selectPanelMode.addEventListener('change', () => {
  3300. updatePanelModeUI();
  3301. markSettingsDirty(true);
  3302. saveSettings({ silent: true }).catch(() => { });
  3303. });
  3304. selectCfDomain.addEventListener('change', () => {
  3305. if (selectCfDomain.disabled) {
  3306. return;
  3307. }
  3308. markSettingsDirty(true);
  3309. saveSettings({ silent: true }).catch(() => { });
  3310. });
  3311. selectTempEmailDomain.addEventListener('change', () => {
  3312. if (selectTempEmailDomain.disabled) {
  3313. return;
  3314. }
  3315. markSettingsDirty(true);
  3316. saveSettings({ silent: true }).catch(() => { });
  3317. });
  3318. btnCfDomainMode.addEventListener('click', async () => {
  3319. try {
  3320. if (!cloudflareDomainEditMode) {
  3321. setCloudflareDomainEditMode(true, { clearInput: true });
  3322. return;
  3323. }
  3324. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  3325. if (!newDomain) {
  3326. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  3327. inputCfDomain.focus();
  3328. return;
  3329. }
  3330. const { domains } = getCloudflareDomainsFromState();
  3331. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  3332. } catch (err) {
  3333. showToast(err.message, 'error');
  3334. }
  3335. });
  3336. btnTempEmailDomainMode.addEventListener('click', async () => {
  3337. try {
  3338. if (!cloudflareTempEmailDomainEditMode) {
  3339. setCloudflareTempEmailDomainEditMode(true, { clearInput: true });
  3340. return;
  3341. }
  3342. const newDomain = normalizeCloudflareTempEmailDomainValue(inputTempEmailDomain.value);
  3343. if (!newDomain) {
  3344. showToast('请输入有效的 Cloudflare Temp Email 域名。', 'warn');
  3345. inputTempEmailDomain.focus();
  3346. return;
  3347. }
  3348. const { domains } = getCloudflareTempEmailDomainsFromState();
  3349. await saveCloudflareTempEmailDomainSettings([...domains, newDomain], newDomain);
  3350. } catch (err) {
  3351. showToast(err.message, 'error');
  3352. }
  3353. });
  3354. inputCfDomain.addEventListener('keydown', (event) => {
  3355. if (event.key === 'Enter') {
  3356. event.preventDefault();
  3357. btnCfDomainMode.click();
  3358. }
  3359. });
  3360. inputTempEmailDomain.addEventListener('keydown', (event) => {
  3361. if (event.key === 'Enter') {
  3362. event.preventDefault();
  3363. btnTempEmailDomainMode.click();
  3364. }
  3365. });
  3366. inputSub2ApiUrl.addEventListener('input', () => {
  3367. markSettingsDirty(true);
  3368. scheduleSettingsAutoSave();
  3369. });
  3370. inputSub2ApiUrl.addEventListener('blur', () => {
  3371. saveSettings({ silent: true }).catch(() => { });
  3372. });
  3373. inputSub2ApiEmail.addEventListener('input', () => {
  3374. markSettingsDirty(true);
  3375. scheduleSettingsAutoSave();
  3376. });
  3377. inputSub2ApiEmail.addEventListener('blur', () => {
  3378. saveSettings({ silent: true }).catch(() => { });
  3379. });
  3380. inputSub2ApiPassword.addEventListener('input', () => {
  3381. markSettingsDirty(true);
  3382. scheduleSettingsAutoSave();
  3383. });
  3384. inputSub2ApiPassword.addEventListener('blur', () => {
  3385. saveSettings({ silent: true }).catch(() => { });
  3386. });
  3387. inputSub2ApiGroup.addEventListener('input', () => {
  3388. markSettingsDirty(true);
  3389. scheduleSettingsAutoSave();
  3390. });
  3391. inputSub2ApiGroup.addEventListener('blur', () => {
  3392. saveSettings({ silent: true }).catch(() => { });
  3393. });
  3394. inputSub2ApiDefaultProxy.addEventListener('input', () => {
  3395. markSettingsDirty(true);
  3396. scheduleSettingsAutoSave();
  3397. });
  3398. inputSub2ApiDefaultProxy.addEventListener('blur', () => {
  3399. saveSettings({ silent: true }).catch(() => { });
  3400. });
  3401. inputEmailPrefix.addEventListener('input', () => {
  3402. maybeClearGeneratedAliasAfterEmailPrefixChange().catch(() => { });
  3403. syncManagedAliasBaseEmailDraftFromInput();
  3404. markSettingsDirty(true);
  3405. scheduleSettingsAutoSave();
  3406. });
  3407. inputEmailPrefix.addEventListener('blur', () => {
  3408. maybeClearGeneratedAliasAfterEmailPrefixChange().catch(() => {});
  3409. syncManagedAliasBaseEmailDraftFromInput();
  3410. saveSettings({ silent: true }).catch(() => {});
  3411. });
  3412. inputInbucketMailbox.addEventListener('input', () => {
  3413. markSettingsDirty(true);
  3414. scheduleSettingsAutoSave();
  3415. });
  3416. inputInbucketMailbox.addEventListener('blur', () => {
  3417. saveSettings({ silent: true }).catch(() => { });
  3418. });
  3419. inputInbucketHost.addEventListener('input', () => {
  3420. markSettingsDirty(true);
  3421. scheduleSettingsAutoSave();
  3422. });
  3423. inputInbucketHost.addEventListener('blur', () => {
  3424. saveSettings({ silent: true }).catch(() => { });
  3425. });
  3426. inputRunCount.addEventListener('input', () => {
  3427. inputRunCount.value = inputRunCount.value.replace(/[^\d]/g, '');
  3428. markSettingsDirty(true);
  3429. updateFallbackThreadIntervalInputState();
  3430. scheduleSettingsAutoSave();
  3431. });
  3432. inputRunCount.addEventListener('blur', () => {
  3433. inputRunCount.value = String(getRunCountValue());
  3434. markSettingsDirty(true);
  3435. updateFallbackThreadIntervalInputState();
  3436. saveSettings({ silent: true }).catch(() => { });
  3437. });
  3438. inputAutoSkipFailures.addEventListener('change', async () => {
  3439. if (inputAutoSkipFailures.checked && !isAutoSkipFailuresPromptDismissed()) {
  3440. const result = await openAutoSkipFailuresConfirmModal();
  3441. if (!result.confirmed) {
  3442. inputAutoSkipFailures.checked = false;
  3443. updateFallbackThreadIntervalInputState();
  3444. return;
  3445. }
  3446. if (result.dismissPrompt) {
  3447. setAutoSkipFailuresPromptDismissed(true);
  3448. }
  3449. }
  3450. updateFallbackThreadIntervalInputState();
  3451. markSettingsDirty(true);
  3452. saveSettings({ silent: true }).catch(() => { });
  3453. });
  3454. inputTempEmailBaseUrl.addEventListener('input', () => {
  3455. markSettingsDirty(true);
  3456. scheduleSettingsAutoSave();
  3457. });
  3458. inputTempEmailBaseUrl.addEventListener('blur', () => {
  3459. inputTempEmailBaseUrl.value = normalizeCloudflareTempEmailBaseUrlValue(inputTempEmailBaseUrl.value);
  3460. saveSettings({ silent: true }).catch(() => { });
  3461. });
  3462. inputTempEmailAdminAuth.addEventListener('input', () => {
  3463. markSettingsDirty(true);
  3464. scheduleSettingsAutoSave();
  3465. });
  3466. inputTempEmailAdminAuth.addEventListener('blur', () => {
  3467. saveSettings({ silent: true }).catch(() => { });
  3468. });
  3469. inputTempEmailCustomAuth.addEventListener('input', () => {
  3470. markSettingsDirty(true);
  3471. scheduleSettingsAutoSave();
  3472. });
  3473. inputTempEmailCustomAuth.addEventListener('blur', () => {
  3474. saveSettings({ silent: true }).catch(() => { });
  3475. });
  3476. inputTempEmailReceiveMailbox.addEventListener('input', () => {
  3477. markSettingsDirty(true);
  3478. scheduleSettingsAutoSave();
  3479. });
  3480. inputTempEmailReceiveMailbox.addEventListener('blur', () => {
  3481. inputTempEmailReceiveMailbox.value = normalizeCloudflareTempEmailReceiveMailboxValue(inputTempEmailReceiveMailbox.value);
  3482. saveSettings({ silent: true }).catch(() => { });
  3483. });
  3484. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('input', () => {
  3485. markSettingsDirty(true);
  3486. scheduleSettingsAutoSave();
  3487. });
  3488. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('blur', () => {
  3489. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  3490. normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value)
  3491. );
  3492. saveSettings({ silent: true }).catch(() => { });
  3493. });
  3494. inputAutoAddPhonePauseMinutes?.addEventListener('input', () => {
  3495. markSettingsDirty(true);
  3496. scheduleSettingsAutoSave();
  3497. });
  3498. inputAutoAddPhonePauseMinutes?.addEventListener('blur', () => {
  3499. inputAutoAddPhonePauseMinutes.value = String(
  3500. normalizeAddPhonePauseMinutes(inputAutoAddPhonePauseMinutes.value)
  3501. );
  3502. saveSettings({ silent: true }).catch(() => { });
  3503. });
  3504. inputAutoDelayEnabled.addEventListener('change', () => {
  3505. updateAutoDelayInputState();
  3506. markSettingsDirty(true);
  3507. saveSettings({ silent: true }).catch(() => { });
  3508. });
  3509. inputAutoDelayMinutes.addEventListener('input', () => {
  3510. markSettingsDirty(true);
  3511. scheduleSettingsAutoSave();
  3512. });
  3513. inputAutoDelayMinutes.addEventListener('blur', () => {
  3514. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  3515. saveSettings({ silent: true }).catch(() => { });
  3516. });
  3517. inputAccountRunHistoryTextEnabled?.addEventListener('change', () => {
  3518. updateAccountRunHistorySettingsUI();
  3519. markSettingsDirty(true);
  3520. saveSettings({ silent: true }).catch(() => { });
  3521. });
  3522. inputAccountRunHistoryHelperBaseUrl?.addEventListener('input', () => {
  3523. markSettingsDirty(true);
  3524. scheduleSettingsAutoSave();
  3525. });
  3526. inputAccountRunHistoryHelperBaseUrl?.addEventListener('blur', () => {
  3527. inputAccountRunHistoryHelperBaseUrl.value = normalizeAccountRunHistoryHelperBaseUrlValue(inputAccountRunHistoryHelperBaseUrl.value);
  3528. saveSettings({ silent: true }).catch(() => { });
  3529. });
  3530. function syncAutoStepDelayInputs() {
  3531. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(inputAutoStepDelaySeconds.value);
  3532. }
  3533. inputAutoStepDelaySeconds.addEventListener('input', () => {
  3534. markSettingsDirty(true);
  3535. scheduleSettingsAutoSave();
  3536. });
  3537. inputAutoStepDelaySeconds.addEventListener('blur', () => {
  3538. syncAutoStepDelayInputs();
  3539. saveSettings({ silent: true }).catch(() => { });
  3540. });
  3541. inputVerificationResendCount?.addEventListener('input', () => {
  3542. markSettingsDirty(true);
  3543. scheduleSettingsAutoSave();
  3544. });
  3545. inputVerificationResendCount?.addEventListener('blur', () => {
  3546. inputVerificationResendCount.value = String(
  3547. normalizeVerificationResendCount(
  3548. inputVerificationResendCount.value,
  3549. DEFAULT_VERIFICATION_RESEND_COUNT
  3550. )
  3551. );
  3552. saveSettings({ silent: true }).catch(() => { });
  3553. });
  3554. // ============================================================
  3555. // Listen for Background broadcasts
  3556. // ============================================================
  3557. chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  3558. switch (message.type) {
  3559. case 'REQUEST_CUSTOM_VERIFICATION_BYPASS_CONFIRMATION': {
  3560. (async () => {
  3561. const step = Number(message.payload?.step);
  3562. const promptCopy = getCustomVerificationPromptCopy(step);
  3563. const confirmed = await openConfirmModal({
  3564. title: promptCopy.title,
  3565. message: promptCopy.message,
  3566. confirmLabel: '确认跳过',
  3567. confirmVariant: 'btn-danger',
  3568. alert: promptCopy.alert,
  3569. });
  3570. sendResponse({ confirmed });
  3571. })().catch((err) => {
  3572. sendResponse({ error: err.message });
  3573. });
  3574. return true;
  3575. }
  3576. case 'LOG_ENTRY':
  3577. appendLog(message.payload);
  3578. if (message.payload.level === 'error') {
  3579. showToast(message.payload.message, 'error');
  3580. }
  3581. break;
  3582. case 'STEP_STATUS_CHANGED': {
  3583. const { step, status } = message.payload;
  3584. updateStepUI(step, status);
  3585. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  3586. syncLatestState(state);
  3587. syncAutoRunState(state);
  3588. updateStatusDisplay(latestState);
  3589. updateButtonStates();
  3590. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  3591. syncPasswordField(state);
  3592. if (state.oauthUrl) {
  3593. displayOauthUrl.textContent = state.oauthUrl;
  3594. displayOauthUrl.classList.add('has-value');
  3595. }
  3596. if (state.localhostUrl) {
  3597. displayLocalhostUrl.textContent = state.localhostUrl;
  3598. displayLocalhostUrl.classList.add('has-value');
  3599. }
  3600. }
  3601. }
  3602. ).catch(() => { });
  3603. break;
  3604. }
  3605. case 'AUTO_RUN_RESET': {
  3606. // Full UI reset for next run
  3607. syncLatestState({
  3608. oauthUrl: null,
  3609. localhostUrl: null,
  3610. email: null,
  3611. password: null,
  3612. stepStatuses: STEP_DEFAULT_STATUSES,
  3613. logs: [],
  3614. scheduledAutoRunAt: null,
  3615. autoRunCountdownAt: null,
  3616. autoRunCountdownTitle: '',
  3617. autoRunCountdownNote: '',
  3618. });
  3619. displayOauthUrl.textContent = '等待中...';
  3620. displayOauthUrl.classList.remove('has-value');
  3621. displayLocalhostUrl.textContent = '等待中...';
  3622. displayLocalhostUrl.classList.remove('has-value');
  3623. inputEmail.value = '';
  3624. displayStatus.textContent = '就绪';
  3625. statusBar.className = 'status-bar';
  3626. logArea.innerHTML = '';
  3627. resetIcloudManager();
  3628. resetLuckmailManager();
  3629. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  3630. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  3631. syncAutoRunState({
  3632. autoRunning: false,
  3633. autoRunPhase: 'idle',
  3634. autoRunCurrentRun: 0,
  3635. autoRunTotalRuns: 1,
  3636. autoRunAttemptRun: 0,
  3637. scheduledAutoRunAt: null,
  3638. autoRunCountdownAt: null,
  3639. autoRunCountdownTitle: '',
  3640. autoRunCountdownNote: '',
  3641. });
  3642. applyAutoRunStatus(currentAutoRun);
  3643. updateProgressCounter();
  3644. updateButtonStates();
  3645. renderHotmailAccounts();
  3646. if (isLuckmailProvider()) {
  3647. queueLuckmailPurchaseRefresh();
  3648. }
  3649. break;
  3650. }
  3651. case 'DATA_UPDATED': {
  3652. syncLatestState(message.payload);
  3653. if (message.payload.email !== undefined) {
  3654. inputEmail.value = message.payload.email || '';
  3655. }
  3656. if (message.payload.password !== undefined) {
  3657. inputPassword.value = message.payload.password || '';
  3658. }
  3659. if (message.payload.localCpaStep9Mode !== undefined) {
  3660. setLocalCpaStep9Mode(message.payload.localCpaStep9Mode);
  3661. }
  3662. if (message.payload.oauthUrl !== undefined) {
  3663. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  3664. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  3665. }
  3666. if (message.payload.localhostUrl !== undefined) {
  3667. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  3668. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  3669. }
  3670. if (message.payload.cloudflareTempEmailBaseUrl !== undefined) {
  3671. inputTempEmailBaseUrl.value = message.payload.cloudflareTempEmailBaseUrl || '';
  3672. }
  3673. if (message.payload.cloudflareTempEmailAdminAuth !== undefined) {
  3674. inputTempEmailAdminAuth.value = message.payload.cloudflareTempEmailAdminAuth || '';
  3675. }
  3676. if (message.payload.cloudflareTempEmailCustomAuth !== undefined) {
  3677. inputTempEmailCustomAuth.value = message.payload.cloudflareTempEmailCustomAuth || '';
  3678. }
  3679. if (message.payload.cloudflareTempEmailReceiveMailbox !== undefined) {
  3680. inputTempEmailReceiveMailbox.value = message.payload.cloudflareTempEmailReceiveMailbox || '';
  3681. }
  3682. if (message.payload.cloudflareTempEmailDomain !== undefined || message.payload.cloudflareTempEmailDomains !== undefined) {
  3683. renderCloudflareTempEmailDomainOptions(message.payload.cloudflareTempEmailDomain || latestState?.cloudflareTempEmailDomain || '');
  3684. }
  3685. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  3686. renderHotmailAccounts();
  3687. if (selectMailProvider.value === 'hotmail-api') {
  3688. inputEmail.value = getCurrentHotmailEmail();
  3689. }
  3690. }
  3691. if (message.payload.luckmailApiKey !== undefined) {
  3692. inputLuckmailApiKey.value = message.payload.luckmailApiKey || '';
  3693. }
  3694. if (message.payload.luckmailBaseUrl !== undefined) {
  3695. inputLuckmailBaseUrl.value = normalizeLuckmailBaseUrl(message.payload.luckmailBaseUrl);
  3696. }
  3697. if (message.payload.luckmailEmailType !== undefined) {
  3698. selectLuckmailEmailType.value = normalizeLuckmailEmailType(message.payload.luckmailEmailType);
  3699. }
  3700. if (message.payload.luckmailDomain !== undefined) {
  3701. inputLuckmailDomain.value = message.payload.luckmailDomain || '';
  3702. }
  3703. if (message.payload.luckmailUsedPurchases !== undefined && isLuckmailProvider()) {
  3704. queueLuckmailPurchaseRefresh();
  3705. }
  3706. if (message.payload.currentLuckmailPurchase !== undefined && isLuckmailProvider()) {
  3707. inputEmail.value = getCurrentLuckmailEmail();
  3708. queueLuckmailPurchaseRefresh();
  3709. }
  3710. if (message.payload.autoDeleteUsedIcloudAlias !== undefined && checkboxAutoDeleteIcloud) {
  3711. checkboxAutoDeleteIcloud.checked = Boolean(message.payload.autoDeleteUsedIcloudAlias);
  3712. }
  3713. if (message.payload.accountRunHistoryTextEnabled !== undefined && inputAccountRunHistoryTextEnabled) {
  3714. inputAccountRunHistoryTextEnabled.checked = Boolean(message.payload.accountRunHistoryTextEnabled);
  3715. updateAccountRunHistorySettingsUI();
  3716. }
  3717. if (message.payload.accountRunHistoryHelperBaseUrl !== undefined && inputAccountRunHistoryHelperBaseUrl) {
  3718. inputAccountRunHistoryHelperBaseUrl.value = normalizeAccountRunHistoryHelperBaseUrlValue(message.payload.accountRunHistoryHelperBaseUrl);
  3719. }
  3720. if (message.payload.icloudHostPreference !== undefined && selectIcloudHostPreference) {
  3721. const hostPreference = String(message.payload.icloudHostPreference || '').trim().toLowerCase();
  3722. selectIcloudHostPreference.value = hostPreference === 'icloud.com'
  3723. ? 'icloud.com'
  3724. : (hostPreference === 'icloud.com.cn' ? 'icloud.com.cn' : 'auto');
  3725. }
  3726. if (message.payload.autoRunSkipFailures !== undefined) {
  3727. inputAutoSkipFailures.checked = Boolean(message.payload.autoRunSkipFailures);
  3728. updateFallbackThreadIntervalInputState();
  3729. }
  3730. if (message.payload.autoRunDelayEnabled !== undefined) {
  3731. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  3732. updateAutoDelayInputState();
  3733. }
  3734. if (message.payload.autoRunDelayMinutes !== undefined) {
  3735. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  3736. }
  3737. if (message.payload.autoRunFallbackThreadIntervalMinutes !== undefined) {
  3738. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  3739. normalizeAutoRunThreadIntervalMinutes(message.payload.autoRunFallbackThreadIntervalMinutes)
  3740. );
  3741. updateFallbackThreadIntervalInputState();
  3742. }
  3743. if (message.payload.autoRunAddPhonePauseMinutes !== undefined && inputAutoAddPhonePauseMinutes) {
  3744. inputAutoAddPhonePauseMinutes.value = String(
  3745. normalizeAddPhonePauseMinutes(message.payload.autoRunAddPhonePauseMinutes)
  3746. );
  3747. }
  3748. if (message.payload.autoStepDelaySeconds !== undefined) {
  3749. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(message.payload.autoStepDelaySeconds);
  3750. }
  3751. if (
  3752. (
  3753. message.payload.verificationResendCount !== undefined
  3754. || message.payload.signupVerificationResendCount !== undefined
  3755. || message.payload.loginVerificationResendCount !== undefined
  3756. )
  3757. && inputVerificationResendCount
  3758. ) {
  3759. const nextVerificationResendCount = message.payload.verificationResendCount !== undefined
  3760. ? message.payload.verificationResendCount
  3761. : (message.payload.signupVerificationResendCount ?? message.payload.loginVerificationResendCount);
  3762. inputVerificationResendCount.value = String(
  3763. normalizeVerificationResendCount(
  3764. nextVerificationResendCount,
  3765. DEFAULT_VERIFICATION_RESEND_COUNT
  3766. )
  3767. );
  3768. }
  3769. break;
  3770. }
  3771. case 'ICLOUD_LOGIN_REQUIRED': {
  3772. const loginMessage = '需要登录 iCloud,我已经为你打开登录页。';
  3773. showToast(loginMessage, 'warn', 5000);
  3774. if (icloudSummary) {
  3775. icloudSummary.textContent = loginMessage;
  3776. }
  3777. showIcloudLoginHelp(message.payload || {});
  3778. break;
  3779. }
  3780. case 'ICLOUD_ALIASES_CHANGED': {
  3781. queueIcloudAliasRefresh();
  3782. break;
  3783. }
  3784. case 'AUTO_RUN_STATUS': {
  3785. syncLatestState({
  3786. autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying', 'waiting_interval'].includes(message.payload.phase),
  3787. autoRunPhase: message.payload.phase,
  3788. autoRunCurrentRun: message.payload.currentRun,
  3789. autoRunTotalRuns: message.payload.totalRuns,
  3790. autoRunAttemptRun: message.payload.attemptRun,
  3791. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  3792. autoRunCountdownAt: message.payload.countdownAt ?? null,
  3793. autoRunCountdownTitle: message.payload.countdownTitle ?? '',
  3794. autoRunCountdownNote: message.payload.countdownNote ?? '',
  3795. });
  3796. applyAutoRunStatus(message.payload);
  3797. updateStatusDisplay(latestState);
  3798. updateButtonStates();
  3799. break;
  3800. }
  3801. }
  3802. });
  3803. // ============================================================
  3804. // Theme Toggle
  3805. // ============================================================
  3806. const btnTheme = document.getElementById('btn-theme');
  3807. function setTheme(theme) {
  3808. document.documentElement.setAttribute('data-theme', theme);
  3809. localStorage.setItem('multipage-theme', theme);
  3810. }
  3811. function initTheme() {
  3812. const saved = localStorage.getItem('multipage-theme');
  3813. if (saved) {
  3814. setTheme(saved);
  3815. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  3816. setTheme('dark');
  3817. }
  3818. }
  3819. btnTheme.addEventListener('click', () => {
  3820. const current = document.documentElement.getAttribute('data-theme');
  3821. setTheme(current === 'dark' ? 'light' : 'dark');
  3822. });
  3823. document.addEventListener('click', (event) => {
  3824. if (!configMenuOpen) {
  3825. return;
  3826. }
  3827. if (configMenuShell?.contains(event.target)) {
  3828. return;
  3829. }
  3830. closeConfigMenu();
  3831. });
  3832. document.addEventListener('keydown', (event) => {
  3833. if (event.key === 'Escape' && configMenuOpen) {
  3834. closeConfigMenu();
  3835. }
  3836. });
  3837. // ============================================================
  3838. // Init
  3839. // ============================================================
  3840. initializeManualStepActions();
  3841. initTheme();
  3842. initHotmailListExpandedState();
  3843. updateSaveButtonState();
  3844. updateConfigMenuControls();
  3845. setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
  3846. setMail2925Mode(DEFAULT_MAIL_2925_MODE);
  3847. initializeReleaseInfo().catch((err) => {
  3848. console.error('Failed to initialize release info:', err);
  3849. });
  3850. restoreState().then(() => {
  3851. syncPasswordToggleLabel();
  3852. syncVpsUrlToggleLabel();
  3853. syncVpsPasswordToggleLabel();
  3854. updatePanelModeUI();
  3855. updateButtonStates();
  3856. updateStatusDisplay(latestState);
  3857. });