sidepanel.js 115 KB

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