sidepanel.js 142 KB

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