sidepanel.js 153 KB

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