sidepanel.js 129 KB

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