sidepanel.js 116 KB

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