sidepanel.js 119 KB

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