sidepanel.js 154 KB

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