sidepanel.js 110 KB

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