sidepanel.js 109 KB

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