sidepanel.js 113 KB

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