sidepanel.js 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219
  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. inputAutoSkipFailuresThreadIntervalMinutes.disabled = !(inputAutoSkipFailures.checked && getRunCountValue() > 1);
  599. }
  600. function updateAutoDelayInputState() {
  601. const scheduled = isAutoRunScheduledPhase();
  602. inputAutoDelayEnabled.disabled = scheduled;
  603. inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked;
  604. }
  605. function formatCountdown(remainingMs) {
  606. const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
  607. const hours = Math.floor(totalSeconds / 3600);
  608. const minutes = Math.floor((totalSeconds % 3600) / 60);
  609. const seconds = totalSeconds % 60;
  610. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  611. }
  612. function formatScheduleTime(timestamp) {
  613. return new Date(timestamp).toLocaleString('zh-CN', {
  614. hour12: false,
  615. month: '2-digit',
  616. day: '2-digit',
  617. hour: '2-digit',
  618. minute: '2-digit',
  619. second: '2-digit',
  620. });
  621. }
  622. function stopScheduledCountdownTicker() {
  623. clearInterval(scheduledCountdownTimer);
  624. scheduledCountdownTimer = null;
  625. }
  626. function renderScheduledAutoRunInfo() {
  627. if (!autoScheduleBar) {
  628. return;
  629. }
  630. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  631. autoScheduleBar.style.display = 'none';
  632. return;
  633. }
  634. const remainingMs = currentAutoRun.scheduledAt - Date.now();
  635. autoScheduleBar.style.display = 'flex';
  636. autoScheduleTitle.textContent = '已计划自动运行';
  637. autoScheduleMeta.textContent = remainingMs > 0
  638. ? `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始,剩余 ${formatCountdown(remainingMs)}`
  639. : '倒计时即将结束,正在准备启动...';
  640. }
  641. function syncScheduledCountdownTicker() {
  642. renderScheduledAutoRunInfo();
  643. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  644. stopScheduledCountdownTicker();
  645. return;
  646. }
  647. if (scheduledCountdownTimer) {
  648. return;
  649. }
  650. scheduledCountdownTimer = setInterval(() => {
  651. renderScheduledAutoRunInfo();
  652. updateStatusDisplay(latestState);
  653. }, 1000);
  654. }
  655. function setDefaultAutoRunButton() {
  656. btnAutoRun.disabled = false;
  657. inputRunCount.disabled = false;
  658. 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> 自动';
  659. }
  660. function normalizeCloudflareDomainValue(value = '') {
  661. let normalized = String(value || '').trim().toLowerCase();
  662. if (!normalized) return '';
  663. normalized = normalized.replace(/^@+/, '');
  664. normalized = normalized.replace(/^https?:\/\//, '');
  665. normalized = normalized.replace(/\/.*$/, '');
  666. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) {
  667. return '';
  668. }
  669. return normalized;
  670. }
  671. function normalizeCloudflareDomains(values = []) {
  672. const seen = new Set();
  673. const domains = [];
  674. for (const value of Array.isArray(values) ? values : []) {
  675. const normalized = normalizeCloudflareDomainValue(value);
  676. if (!normalized || seen.has(normalized)) continue;
  677. seen.add(normalized);
  678. domains.push(normalized);
  679. }
  680. return domains;
  681. }
  682. function getCloudflareDomainsFromState() {
  683. const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []);
  684. const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || '');
  685. if (activeDomain && !domains.includes(activeDomain)) {
  686. domains.unshift(activeDomain);
  687. }
  688. return { domains, activeDomain: activeDomain || domains[0] || '' };
  689. }
  690. function renderCloudflareDomainOptions(preferredDomain = '') {
  691. const preferred = normalizeCloudflareDomainValue(preferredDomain);
  692. const { domains, activeDomain } = getCloudflareDomainsFromState();
  693. const selected = preferred || activeDomain;
  694. selectCfDomain.innerHTML = '';
  695. if (domains.length === 0) {
  696. const option = document.createElement('option');
  697. option.value = '';
  698. option.textContent = '请先添加域名';
  699. selectCfDomain.appendChild(option);
  700. selectCfDomain.disabled = true;
  701. selectCfDomain.value = '';
  702. return;
  703. }
  704. for (const domain of domains) {
  705. const option = document.createElement('option');
  706. option.value = domain;
  707. option.textContent = domain;
  708. selectCfDomain.appendChild(option);
  709. }
  710. selectCfDomain.disabled = false;
  711. selectCfDomain.value = domains.includes(selected) ? selected : domains[0];
  712. }
  713. function setCloudflareDomainEditMode(editing, options = {}) {
  714. const { clearInput = false } = options;
  715. cloudflareDomainEditMode = Boolean(editing);
  716. selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : '';
  717. inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none';
  718. btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加';
  719. if (cloudflareDomainEditMode) {
  720. if (clearInput) {
  721. inputCfDomain.value = '';
  722. }
  723. inputCfDomain.focus();
  724. } else if (clearInput) {
  725. inputCfDomain.value = '';
  726. }
  727. }
  728. function collectSettingsPayload() {
  729. const { domains, activeDomain } = getCloudflareDomainsFromState();
  730. const selectedCloudflareDomain = normalizeCloudflareDomainValue(
  731. !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain
  732. ) || activeDomain;
  733. return {
  734. panelMode: selectPanelMode.value,
  735. vpsUrl: inputVpsUrl.value.trim(),
  736. vpsPassword: inputVpsPassword.value,
  737. localCpaStep9Mode: getSelectedLocalCpaStep9Mode(),
  738. sub2apiUrl: inputSub2ApiUrl.value.trim(),
  739. sub2apiEmail: inputSub2ApiEmail.value.trim(),
  740. sub2apiPassword: inputSub2ApiPassword.value,
  741. sub2apiGroupName: inputSub2ApiGroup.value.trim(),
  742. customPassword: inputPassword.value,
  743. mailProvider: selectMailProvider.value,
  744. emailGenerator: selectEmailGenerator.value,
  745. emailPrefix: inputEmailPrefix.value.trim(),
  746. inbucketHost: inputInbucketHost.value.trim(),
  747. inbucketMailbox: inputInbucketMailbox.value.trim(),
  748. hotmailServiceMode: getSelectedHotmailServiceMode(),
  749. hotmailRemoteBaseUrl: inputHotmailRemoteBaseUrl.value.trim(),
  750. hotmailLocalBaseUrl: inputHotmailLocalBaseUrl.value.trim(),
  751. cloudflareDomain: selectedCloudflareDomain,
  752. cloudflareDomains: domains,
  753. autoRunSkipFailures: true,
  754. autoRunFallbackThreadIntervalMinutes: normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value),
  755. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  756. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  757. autoStepDelaySeconds: normalizeAutoStepDelaySeconds(inputAutoStepDelaySeconds.value),
  758. };
  759. }
  760. function normalizeLocalCpaStep9Mode(value = '') {
  761. return String(value || '').trim().toLowerCase() === 'bypass'
  762. ? 'bypass'
  763. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  764. }
  765. function normalizeHotmailServiceMode(value = '') {
  766. return HOTMAIL_SERVICE_MODE_LOCAL;
  767. }
  768. function getSelectedLocalCpaStep9Mode() {
  769. const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active'));
  770. return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode);
  771. }
  772. function setLocalCpaStep9Mode(mode) {
  773. const resolvedMode = normalizeLocalCpaStep9Mode(mode);
  774. localCpaStep9ModeButtons.forEach((button) => {
  775. const active = button.dataset.localCpaStep9Mode === resolvedMode;
  776. button.classList.toggle('is-active', active);
  777. button.setAttribute('aria-pressed', String(active));
  778. });
  779. }
  780. function getSelectedHotmailServiceMode() {
  781. const activeButton = hotmailServiceModeButtons.find((button) => button.classList.contains('is-active'));
  782. return normalizeHotmailServiceMode(activeButton?.dataset.hotmailServiceMode);
  783. }
  784. function setHotmailServiceMode(mode) {
  785. const resolvedMode = normalizeHotmailServiceMode(mode);
  786. hotmailServiceModeButtons.forEach((button) => {
  787. const isRemoteMode = button.dataset.hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE;
  788. const active = button.dataset.hotmailServiceMode === resolvedMode;
  789. button.disabled = isRemoteMode;
  790. button.setAttribute('aria-disabled', String(isRemoteMode));
  791. button.classList.toggle('is-active', active);
  792. button.setAttribute('aria-pressed', String(active));
  793. });
  794. }
  795. function setSettingsCardLocked(locked) {
  796. if (!settingsCard) {
  797. return;
  798. }
  799. settingsCard.classList.toggle('is-locked', locked);
  800. settingsCard.toggleAttribute('inert', locked);
  801. }
  802. async function setRuntimeEmailState(email) {
  803. const normalizedEmail = String(email || '').trim() || null;
  804. const response = await chrome.runtime.sendMessage({
  805. type: 'SET_EMAIL_STATE',
  806. source: 'sidepanel',
  807. payload: { email: normalizedEmail },
  808. });
  809. if (response?.error) {
  810. throw new Error(response.error);
  811. }
  812. return normalizedEmail;
  813. }
  814. async function clearRegistrationEmail(options = {}) {
  815. const { silent = false } = options;
  816. if (!inputEmail.value.trim() && !latestState?.email) {
  817. return;
  818. }
  819. inputEmail.value = '';
  820. syncLatestState({ email: null });
  821. try {
  822. await setRuntimeEmailState(null);
  823. } catch (err) {
  824. if (!silent) {
  825. showToast(`清空邮箱失败:${err.message}`, 'error');
  826. }
  827. throw err;
  828. }
  829. }
  830. function markSettingsDirty(isDirty = true) {
  831. settingsDirty = isDirty;
  832. updateSaveButtonState();
  833. }
  834. function updateSaveButtonState() {
  835. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  836. updateConfigMenuControls();
  837. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  838. }
  839. function scheduleSettingsAutoSave() {
  840. clearTimeout(settingsAutoSaveTimer);
  841. settingsAutoSaveTimer = setTimeout(() => {
  842. saveSettings({ silent: true }).catch(() => { });
  843. }, 500);
  844. }
  845. async function saveSettings(options = {}) {
  846. const { silent = false } = options;
  847. clearTimeout(settingsAutoSaveTimer);
  848. if (!settingsDirty && !settingsSaveInFlight && silent) {
  849. return;
  850. }
  851. const payload = collectSettingsPayload();
  852. settingsSaveInFlight = true;
  853. updateSaveButtonState();
  854. try {
  855. const response = await chrome.runtime.sendMessage({
  856. type: 'SAVE_SETTING',
  857. source: 'sidepanel',
  858. payload,
  859. });
  860. if (response?.error) {
  861. throw new Error(response.error);
  862. }
  863. if (response?.state) {
  864. applySettingsState(response.state);
  865. } else {
  866. syncLatestState(payload);
  867. markSettingsDirty(false);
  868. updatePanelModeUI();
  869. updateMailProviderUI();
  870. updateButtonStates();
  871. }
  872. if (!silent) {
  873. showToast('配置已保存', 'success', 1800);
  874. }
  875. } catch (err) {
  876. markSettingsDirty(true);
  877. if (!silent) {
  878. showToast(`保存失败:${err.message}`, 'error');
  879. }
  880. throw err;
  881. } finally {
  882. settingsSaveInFlight = false;
  883. updateSaveButtonState();
  884. }
  885. }
  886. function applyAutoRunStatus(payload = currentAutoRun) {
  887. syncAutoRunState(payload);
  888. const runLabel = getAutoRunLabel(currentAutoRun);
  889. const locked = isAutoRunLockedPhase();
  890. const paused = isAutoRunPausedPhase();
  891. const scheduled = isAutoRunScheduledPhase();
  892. const settingsCardLocked = scheduled || locked;
  893. setSettingsCardLocked(settingsCardLocked);
  894. inputRunCount.disabled = currentAutoRun.autoRunning;
  895. btnAutoRun.disabled = currentAutoRun.autoRunning;
  896. btnFetchEmail.disabled = locked
  897. || usesGeneratedAliasMailProvider(selectMailProvider.value)
  898. || isCustomEmailGeneratorSelected();
  899. inputEmail.disabled = locked;
  900. inputAutoSkipFailures.disabled = true;
  901. if (currentAutoRun.totalRuns > 0) {
  902. inputRunCount.value = String(currentAutoRun.totalRuns);
  903. }
  904. switch (currentAutoRun.phase) {
  905. case 'scheduled':
  906. autoContinueBar.style.display = 'none';
  907. btnAutoRun.innerHTML = `已计划${runLabel}`;
  908. break;
  909. case 'waiting_step':
  910. autoContinueBar.style.display = 'none';
  911. btnAutoRun.innerHTML = `等待中${runLabel}`;
  912. break;
  913. case 'waiting_email':
  914. autoContinueBar.style.display = 'flex';
  915. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  916. break;
  917. case 'running':
  918. autoContinueBar.style.display = 'none';
  919. btnAutoRun.innerHTML = `运行中${runLabel}`;
  920. break;
  921. case 'retrying':
  922. autoContinueBar.style.display = 'none';
  923. btnAutoRun.innerHTML = `重试中${runLabel}`;
  924. break;
  925. default:
  926. autoContinueBar.style.display = 'none';
  927. setDefaultAutoRunButton();
  928. inputEmail.disabled = false;
  929. if (!locked) {
  930. btnFetchEmail.disabled = usesGeneratedAliasMailProvider(selectMailProvider.value)
  931. || isCustomEmailGeneratorSelected();
  932. }
  933. break;
  934. }
  935. updateAutoDelayInputState();
  936. updateFallbackThreadIntervalInputState();
  937. syncScheduledCountdownTicker();
  938. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  939. updateConfigMenuControls();
  940. }
  941. function initializeManualStepActions() {
  942. document.querySelectorAll('.step-row').forEach((row) => {
  943. const step = Number(row.dataset.step);
  944. const statusEl = row.querySelector('.step-status');
  945. if (!statusEl) return;
  946. const actions = document.createElement('div');
  947. actions.className = 'step-actions';
  948. const manualBtn = document.createElement('button');
  949. manualBtn.type = 'button';
  950. manualBtn.className = 'step-manual-btn';
  951. manualBtn.dataset.step = String(step);
  952. manualBtn.title = '跳过此步';
  953. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  954. 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>';
  955. manualBtn.addEventListener('click', async (event) => {
  956. event.stopPropagation();
  957. try {
  958. await handleSkipStep(step);
  959. } catch (err) {
  960. showToast(err.message, 'error');
  961. }
  962. });
  963. statusEl.parentNode.replaceChild(actions, statusEl);
  964. actions.appendChild(manualBtn);
  965. actions.appendChild(statusEl);
  966. });
  967. }
  968. // ============================================================
  969. // State Restore on load
  970. // ============================================================
  971. function applySettingsState(state) {
  972. syncLatestState(state);
  973. syncAutoRunState(state);
  974. inputEmail.value = state?.email || '';
  975. syncPasswordField(state || {});
  976. inputVpsUrl.value = state?.vpsUrl || '';
  977. inputVpsPassword.value = state?.vpsPassword || '';
  978. setLocalCpaStep9Mode(state?.localCpaStep9Mode);
  979. selectPanelMode.value = state?.panelMode || 'cpa';
  980. inputSub2ApiUrl.value = state?.sub2apiUrl || '';
  981. inputSub2ApiEmail.value = state?.sub2apiEmail || '';
  982. inputSub2ApiPassword.value = state?.sub2apiPassword || '';
  983. inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
  984. selectMailProvider.value = state?.mailProvider || '163';
  985. selectEmailGenerator.value = state?.emailGenerator || 'duck';
  986. inputEmailPrefix.value = state?.emailPrefix || '';
  987. inputInbucketHost.value = state?.inbucketHost || '';
  988. inputInbucketMailbox.value = state?.inbucketMailbox || '';
  989. setHotmailServiceMode(state?.hotmailServiceMode);
  990. inputHotmailRemoteBaseUrl.value = state?.hotmailRemoteBaseUrl || '';
  991. inputHotmailLocalBaseUrl.value = state?.hotmailLocalBaseUrl || '';
  992. renderCloudflareDomainOptions(state?.cloudflareDomain || '');
  993. setCloudflareDomainEditMode(false, { clearInput: true });
  994. inputAutoSkipFailures.checked = true;
  995. inputAutoSkipFailuresThreadIntervalMinutes.value = String(normalizeAutoRunThreadIntervalMinutes(state?.autoRunFallbackThreadIntervalMinutes));
  996. inputAutoDelayEnabled.checked = Boolean(state?.autoRunDelayEnabled);
  997. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state?.autoRunDelayMinutes));
  998. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(state?.autoStepDelaySeconds);
  999. if (state?.autoRunTotalRuns) {
  1000. inputRunCount.value = String(state.autoRunTotalRuns);
  1001. }
  1002. applyAutoRunStatus(state);
  1003. markSettingsDirty(false);
  1004. updateAutoDelayInputState();
  1005. updateFallbackThreadIntervalInputState();
  1006. updatePanelModeUI();
  1007. updateMailProviderUI();
  1008. updateButtonStates();
  1009. }
  1010. async function restoreState() {
  1011. try {
  1012. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  1013. applySettingsState(state);
  1014. if (state.oauthUrl) {
  1015. displayOauthUrl.textContent = state.oauthUrl;
  1016. displayOauthUrl.classList.add('has-value');
  1017. }
  1018. if (state.localhostUrl) {
  1019. displayLocalhostUrl.textContent = state.localhostUrl;
  1020. displayLocalhostUrl.classList.add('has-value');
  1021. }
  1022. if (state.stepStatuses) {
  1023. for (const [step, status] of Object.entries(state.stepStatuses)) {
  1024. updateStepUI(Number(step), status);
  1025. }
  1026. }
  1027. if (state.logs) {
  1028. for (const entry of state.logs) {
  1029. appendLog(entry);
  1030. }
  1031. }
  1032. updateStatusDisplay(latestState);
  1033. updateProgressCounter();
  1034. } catch (err) {
  1035. console.error('Failed to restore state:', err);
  1036. }
  1037. }
  1038. function openExternalUrl(url) {
  1039. const targetUrl = String(url || '').trim();
  1040. if (!targetUrl) {
  1041. return;
  1042. }
  1043. if (chrome?.tabs?.create) {
  1044. chrome.tabs.create({ url: targetUrl, active: true }).catch(() => {
  1045. window.open(targetUrl, '_blank', 'noopener');
  1046. });
  1047. return;
  1048. }
  1049. window.open(targetUrl, '_blank', 'noopener');
  1050. }
  1051. function createUpdateNoteList(notes = []) {
  1052. if (!Array.isArray(notes) || notes.length === 0) {
  1053. const empty = document.createElement('p');
  1054. empty.className = 'update-release-empty';
  1055. empty.textContent = '该版本未提供可解析的更新说明,请查看完整更新日志。';
  1056. return empty;
  1057. }
  1058. const list = document.createElement('ul');
  1059. list.className = 'update-release-notes';
  1060. notes.forEach((note) => {
  1061. const item = document.createElement('li');
  1062. item.textContent = note;
  1063. list.appendChild(item);
  1064. });
  1065. return list;
  1066. }
  1067. function renderUpdateReleaseList(releases = []) {
  1068. if (!updateReleaseList) {
  1069. return;
  1070. }
  1071. updateReleaseList.innerHTML = '';
  1072. releases.forEach((release) => {
  1073. const item = document.createElement('article');
  1074. item.className = 'update-release-item';
  1075. const head = document.createElement('div');
  1076. head.className = 'update-release-head';
  1077. const titleRow = document.createElement('div');
  1078. titleRow.className = 'update-release-title-row';
  1079. const version = document.createElement('span');
  1080. version.className = 'update-release-version';
  1081. version.textContent = `v${release.version}`;
  1082. titleRow.appendChild(version);
  1083. if (release.title) {
  1084. const name = document.createElement('span');
  1085. name.className = 'update-release-name';
  1086. name.textContent = release.title;
  1087. titleRow.appendChild(name);
  1088. }
  1089. head.appendChild(titleRow);
  1090. const publishedAt = sidepanelUpdateService?.formatReleaseDate?.(release.publishedAt) || '';
  1091. if (publishedAt) {
  1092. const date = document.createElement('span');
  1093. date.className = 'update-release-date';
  1094. date.textContent = publishedAt;
  1095. head.appendChild(date);
  1096. }
  1097. item.appendChild(head);
  1098. item.appendChild(createUpdateNoteList(release.notes));
  1099. updateReleaseList.appendChild(item);
  1100. });
  1101. }
  1102. function resetUpdateCard() {
  1103. if (updateSection) {
  1104. updateSection.hidden = true;
  1105. }
  1106. if (updateCardVersion) {
  1107. updateCardVersion.textContent = '';
  1108. }
  1109. if (updateCardSummary) {
  1110. updateCardSummary.textContent = '';
  1111. }
  1112. if (updateReleaseList) {
  1113. updateReleaseList.innerHTML = '';
  1114. }
  1115. if (btnOpenRelease) {
  1116. btnOpenRelease.hidden = true;
  1117. btnOpenRelease.onclick = null;
  1118. }
  1119. }
  1120. function renderReleaseSnapshot(snapshot) {
  1121. currentReleaseSnapshot = snapshot;
  1122. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1123. return;
  1124. }
  1125. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed', 'is-version-label');
  1126. const localVersionText = snapshot?.localVersion ? `v${snapshot.localVersion}` : '';
  1127. const logUrl = snapshot?.logUrl || snapshot?.releasesPageUrl || sidepanelUpdateService?.releasesPageUrl || '';
  1128. if (btnReleaseLog) {
  1129. btnReleaseLog.onclick = () => openExternalUrl(logUrl);
  1130. btnReleaseLog.hidden = true;
  1131. }
  1132. extensionVersionMeta.hidden = true;
  1133. extensionVersionMeta.textContent = '';
  1134. switch (snapshot?.status) {
  1135. case 'update-available': {
  1136. extensionUpdateStatus.textContent = '有更新';
  1137. extensionUpdateStatus.classList.add('is-update-available');
  1138. if (btnReleaseLog) {
  1139. btnReleaseLog.hidden = false;
  1140. }
  1141. if (updateSection) {
  1142. updateSection.hidden = false;
  1143. }
  1144. if (updateCardVersion) {
  1145. updateCardVersion.textContent = `最新版本 v${snapshot.latestVersion}`;
  1146. }
  1147. if (updateCardSummary) {
  1148. const updateCount = Array.isArray(snapshot.newerReleases) ? snapshot.newerReleases.length : 0;
  1149. updateCardSummary.textContent = updateCount > 1
  1150. ? `当前 ${localVersionText},共有 ${updateCount} 个新版本可更新。`
  1151. : `当前 ${localVersionText},可更新到 v${snapshot.latestVersion}。`;
  1152. }
  1153. renderUpdateReleaseList(snapshot.newerReleases || []);
  1154. if (btnOpenRelease) {
  1155. btnOpenRelease.hidden = false;
  1156. btnOpenRelease.textContent = '前往更新';
  1157. btnOpenRelease.onclick = () => openExternalUrl(logUrl);
  1158. }
  1159. break;
  1160. }
  1161. case 'latest': {
  1162. extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
  1163. extensionUpdateStatus.classList.add('is-version-label');
  1164. resetUpdateCard();
  1165. break;
  1166. }
  1167. case 'empty': {
  1168. extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
  1169. extensionUpdateStatus.classList.add('is-version-label');
  1170. resetUpdateCard();
  1171. break;
  1172. }
  1173. case 'error':
  1174. default: {
  1175. extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
  1176. extensionUpdateStatus.classList.add('is-version-label', 'is-check-failed');
  1177. extensionVersionMeta.textContent = snapshot?.errorMessage || 'GitHub Releases 检查失败';
  1178. extensionVersionMeta.hidden = false;
  1179. resetUpdateCard();
  1180. break;
  1181. }
  1182. }
  1183. }
  1184. async function initializeReleaseInfo() {
  1185. const fallbackReleaseUrl = sidepanelUpdateService?.releasesPageUrl || 'https://github.com/QLHazyCoder/codex-oauth-automation-extension/releases';
  1186. if (btnReleaseLog) {
  1187. btnReleaseLog.onclick = () => openExternalUrl(currentReleaseSnapshot?.logUrl || fallbackReleaseUrl);
  1188. }
  1189. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1190. return;
  1191. }
  1192. const localVersion = sidepanelUpdateService?.stripVersionPrefix?.(chrome.runtime.getManifest()?.version || '') || '';
  1193. extensionUpdateStatus.textContent = localVersion ? `v${localVersion}` : 'v0.0.0';
  1194. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed');
  1195. extensionUpdateStatus.classList.add('is-version-label');
  1196. extensionVersionMeta.hidden = true;
  1197. extensionVersionMeta.textContent = '';
  1198. if (btnReleaseLog) {
  1199. btnReleaseLog.hidden = true;
  1200. }
  1201. resetUpdateCard();
  1202. if (!sidepanelUpdateService) {
  1203. extensionVersionMeta.textContent = '更新检查服务不可用';
  1204. extensionVersionMeta.hidden = false;
  1205. return;
  1206. }
  1207. const snapshot = await sidepanelUpdateService.getReleaseSnapshot();
  1208. renderReleaseSnapshot(snapshot);
  1209. }
  1210. function syncPasswordField(state) {
  1211. inputPassword.value = state.customPassword || state.password || '';
  1212. }
  1213. function getSelectedEmailGenerator() {
  1214. const generator = String(selectEmailGenerator.value || '').trim().toLowerCase();
  1215. if (generator === 'custom' || generator === 'manual') {
  1216. return 'custom';
  1217. }
  1218. if (generator === 'cloudflare') {
  1219. return 'cloudflare';
  1220. }
  1221. return 'duck';
  1222. }
  1223. function getEmailGeneratorUiCopy() {
  1224. if (getSelectedEmailGenerator() === 'custom') {
  1225. return {
  1226. buttonLabel: '自定义邮箱',
  1227. placeholder: '请填写本轮要使用的注册邮箱',
  1228. successVerb: '使用',
  1229. label: '自定义邮箱',
  1230. };
  1231. }
  1232. if (getSelectedEmailGenerator() === 'cloudflare') {
  1233. return {
  1234. buttonLabel: '生成',
  1235. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  1236. successVerb: '生成',
  1237. label: 'Cloudflare 邮箱',
  1238. };
  1239. }
  1240. return {
  1241. buttonLabel: '获取',
  1242. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  1243. successVerb: '获取',
  1244. label: 'Duck 邮箱',
  1245. };
  1246. }
  1247. function isCustomEmailGeneratorSelected() {
  1248. return getSelectedEmailGenerator() === 'custom';
  1249. }
  1250. function getHotmailAccounts(state = latestState) {
  1251. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  1252. }
  1253. function getCurrentHotmailAccount(state = latestState) {
  1254. const currentId = state?.currentHotmailAccountId;
  1255. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  1256. }
  1257. function getCurrentHotmailEmail(state = latestState) {
  1258. return String(getCurrentHotmailAccount(state)?.email || '').trim();
  1259. }
  1260. function getMailProviderLoginConfig(provider = selectMailProvider.value) {
  1261. return MAIL_PROVIDER_LOGIN_CONFIGS[String(provider || '').trim()] || null;
  1262. }
  1263. function isCurrentEmailManagedByHotmail(state = latestState) {
  1264. const hotmailEmail = getCurrentHotmailEmail(state);
  1265. if (!hotmailEmail) {
  1266. return false;
  1267. }
  1268. const inputEmailValue = String(inputEmail.value || '').trim();
  1269. const stateEmailValue = String(state?.email || '').trim();
  1270. return inputEmailValue === hotmailEmail || stateEmailValue === hotmailEmail;
  1271. }
  1272. function isCurrentEmailManagedByGeneratedAlias(provider = latestState?.mailProvider, state = latestState) {
  1273. const normalizedProvider = String(provider || '').trim();
  1274. if (!usesGeneratedAliasMailProvider(normalizedProvider)) {
  1275. return false;
  1276. }
  1277. const inputEmailValue = String(inputEmail.value || '').trim().toLowerCase();
  1278. const stateEmailValue = String(state?.email || '').trim().toLowerCase();
  1279. if (normalizedProvider === '2925') {
  1280. return inputEmailValue.endsWith('@2925.com') || stateEmailValue.endsWith('@2925.com');
  1281. }
  1282. return false;
  1283. }
  1284. function updateMailLoginButtonState() {
  1285. if (!btnMailLogin) {
  1286. return;
  1287. }
  1288. const config = getMailProviderLoginConfig();
  1289. btnMailLogin.disabled = !config;
  1290. btnMailLogin.title = config ? `打开 ${config.label} 登录页` : '当前邮箱服务无需网页登录';
  1291. }
  1292. function getHotmailAccountsByUsage(mode = 'all', state = latestState) {
  1293. const accounts = getHotmailAccounts(state);
  1294. if (typeof filterHotmailAccountsByUsage === 'function') {
  1295. return filterHotmailAccountsByUsage(accounts, mode);
  1296. }
  1297. if (mode === 'used') {
  1298. return accounts.filter((account) => Boolean(account?.used));
  1299. }
  1300. return accounts.slice();
  1301. }
  1302. function getHotmailBulkActionText(mode, count) {
  1303. if (typeof getHotmailBulkActionLabel === 'function') {
  1304. return getHotmailBulkActionLabel(mode, count);
  1305. }
  1306. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  1307. const prefix = mode === 'used' ? '清空已用' : '全部删除';
  1308. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  1309. return `${prefix}${suffix}`;
  1310. }
  1311. function getHotmailListToggleText(expanded, count) {
  1312. if (typeof getHotmailListToggleLabel === 'function') {
  1313. return getHotmailListToggleLabel(expanded, count);
  1314. }
  1315. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  1316. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  1317. return `${expanded ? '收起列表' : '展开列表'}${suffix}`;
  1318. }
  1319. function updateHotmailListViewport() {
  1320. const count = getHotmailAccounts().length;
  1321. const usedCount = getHotmailAccountsByUsage('used').length;
  1322. if (btnClearUsedHotmailAccounts) {
  1323. btnClearUsedHotmailAccounts.textContent = getHotmailBulkActionText('used', usedCount);
  1324. btnClearUsedHotmailAccounts.disabled = usedCount === 0;
  1325. }
  1326. if (btnDeleteAllHotmailAccounts) {
  1327. btnDeleteAllHotmailAccounts.textContent = getHotmailBulkActionText('all', count);
  1328. btnDeleteAllHotmailAccounts.disabled = count === 0;
  1329. }
  1330. if (btnToggleHotmailList) {
  1331. btnToggleHotmailList.textContent = getHotmailListToggleText(hotmailListExpanded, count);
  1332. btnToggleHotmailList.setAttribute('aria-expanded', String(hotmailListExpanded));
  1333. btnToggleHotmailList.disabled = count === 0;
  1334. }
  1335. if (hotmailListShell) {
  1336. hotmailListShell.classList.toggle('is-expanded', hotmailListExpanded);
  1337. hotmailListShell.classList.toggle('is-collapsed', !hotmailListExpanded);
  1338. }
  1339. }
  1340. function setHotmailListExpanded(expanded, options = {}) {
  1341. const { persist = true } = options;
  1342. hotmailListExpanded = Boolean(expanded);
  1343. updateHotmailListViewport();
  1344. if (persist) {
  1345. localStorage.setItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY, hotmailListExpanded ? '1' : '0');
  1346. }
  1347. }
  1348. function initHotmailListExpandedState() {
  1349. const saved = localStorage.getItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY);
  1350. setHotmailListExpanded(saved === '1', { persist: false });
  1351. }
  1352. function shouldClearCurrentHotmailSelectionLocally(account) {
  1353. if (typeof shouldClearHotmailCurrentSelection === 'function') {
  1354. return shouldClearHotmailCurrentSelection(account);
  1355. }
  1356. return Boolean(account) && account.used === true;
  1357. }
  1358. function upsertHotmailAccountListLocally(accounts, nextAccount) {
  1359. if (typeof upsertHotmailAccountInList === 'function') {
  1360. return upsertHotmailAccountInList(accounts, nextAccount);
  1361. }
  1362. const list = Array.isArray(accounts) ? accounts.slice() : [];
  1363. if (!nextAccount?.id) return list;
  1364. const existingIndex = list.findIndex((account) => account?.id === nextAccount.id);
  1365. if (existingIndex === -1) {
  1366. list.push(nextAccount);
  1367. return list;
  1368. }
  1369. list[existingIndex] = nextAccount;
  1370. return list;
  1371. }
  1372. function refreshHotmailSelectionUI() {
  1373. renderHotmailAccounts();
  1374. if (selectMailProvider.value === 'hotmail-api') {
  1375. inputEmail.value = getCurrentHotmailEmail();
  1376. }
  1377. }
  1378. function applyHotmailAccountMutation(account, options = {}) {
  1379. if (!account?.id) return;
  1380. const { preserveCurrentSelection = false } = options;
  1381. const nextState = {
  1382. hotmailAccounts: upsertHotmailAccountListLocally(getHotmailAccounts(), account),
  1383. };
  1384. if (!preserveCurrentSelection
  1385. && latestState?.currentHotmailAccountId === account.id
  1386. && shouldClearCurrentHotmailSelectionLocally(account)) {
  1387. nextState.currentHotmailAccountId = null;
  1388. if (selectMailProvider.value === 'hotmail-api') {
  1389. nextState.email = null;
  1390. }
  1391. }
  1392. syncLatestState(nextState);
  1393. refreshHotmailSelectionUI();
  1394. }
  1395. function formatDateTime(timestamp) {
  1396. const value = Number(timestamp);
  1397. if (!Number.isFinite(value) || value <= 0) {
  1398. return '未使用';
  1399. }
  1400. return new Date(value).toLocaleString('zh-CN', { hour12: false });
  1401. }
  1402. function getHotmailAvailabilityLabel(account) {
  1403. if (account.used) return '已用';
  1404. return '可分配';
  1405. }
  1406. function getHotmailStatusLabel(account) {
  1407. if (account.used) return '已用';
  1408. switch (account.status) {
  1409. case 'authorized':
  1410. return '可用';
  1411. case 'error':
  1412. return '异常';
  1413. default:
  1414. return '待校验';
  1415. }
  1416. }
  1417. function getHotmailStatusClass(account) {
  1418. if (account.used) return 'status-used';
  1419. return `status-${account.status || 'pending'}`;
  1420. }
  1421. function clearHotmailForm() {
  1422. inputHotmailEmail.value = '';
  1423. inputHotmailClientId.value = '';
  1424. inputHotmailPassword.value = '';
  1425. inputHotmailRefreshToken.value = '';
  1426. }
  1427. function renderHotmailAccounts() {
  1428. if (!hotmailAccountsList) return;
  1429. const accounts = getHotmailAccounts();
  1430. const currentId = latestState?.currentHotmailAccountId || '';
  1431. if (!accounts.length) {
  1432. hotmailAccountsList.innerHTML = '<div class="hotmail-empty">还没有 Hotmail 账号,先添加一条再校验。</div>';
  1433. updateHotmailListViewport();
  1434. return;
  1435. }
  1436. hotmailAccountsList.innerHTML = accounts.map((account) => `
  1437. <div class="hotmail-account-item${account.id === currentId ? ' is-current' : ''}">
  1438. <div class="hotmail-account-top">
  1439. <div class="hotmail-account-title-row">
  1440. <div class="hotmail-account-email">${escapeHtml(account.email || '(未命名账号)')}</div>
  1441. <button
  1442. class="hotmail-copy-btn"
  1443. type="button"
  1444. data-account-action="copy-email"
  1445. data-account-id="${escapeHtml(account.id)}"
  1446. title="复制邮箱"
  1447. aria-label="复制邮箱 ${escapeHtml(account.email || '')}"
  1448. >${COPY_ICON}</button>
  1449. </div>
  1450. <span class="hotmail-status-chip ${escapeHtml(getHotmailStatusClass(account))}">${escapeHtml(getHotmailStatusLabel(account))}</span>
  1451. </div>
  1452. <div class="hotmail-account-meta">
  1453. <span>客户端 ID:${escapeHtml(account.clientId ? `${account.clientId.slice(0, 10)}...` : '未填写')}</span>
  1454. <span>刷新令牌:${account.refreshToken ? '已保存' : '未保存'}</span>
  1455. <span>分配状态: ${escapeHtml(getHotmailAvailabilityLabel(account))}</span>
  1456. <span>上次校验: ${escapeHtml(formatDateTime(account.lastAuthAt))}</span>
  1457. <span>上次使用: ${escapeHtml(formatDateTime(account.lastUsedAt))}</span>
  1458. </div>
  1459. ${account.lastError ? `<div class="hotmail-account-error">${escapeHtml(account.lastError)}</div>` : ''}
  1460. <div class="hotmail-account-actions">
  1461. <button class="btn btn-outline btn-sm" type="button" data-account-action="select" data-account-id="${escapeHtml(account.id)}">使用此账号</button>
  1462. <button class="btn btn-outline btn-sm" type="button" data-account-action="toggle-used" data-account-id="${escapeHtml(account.id)}">${account.used ? '标记未用' : '标记已用'}</button>
  1463. <button class="btn btn-primary btn-sm" type="button" data-account-action="verify" data-account-id="${escapeHtml(account.id)}">校验</button>
  1464. <button class="btn btn-outline btn-sm" type="button" data-account-action="test" data-account-id="${escapeHtml(account.id)}">复制最新验证码</button>
  1465. <button class="btn btn-ghost btn-sm" type="button" data-account-action="delete" data-account-id="${escapeHtml(account.id)}">删除</button>
  1466. </div>
  1467. </div>
  1468. `).join('');
  1469. updateHotmailListViewport();
  1470. }
  1471. function updateMailProviderUI() {
  1472. const use2925 = selectMailProvider.value === '2925';
  1473. const useGeneratedAlias = usesGeneratedAliasMailProvider(selectMailProvider.value);
  1474. const useInbucket = selectMailProvider.value === 'inbucket';
  1475. const useHotmail = selectMailProvider.value === 'hotmail-api';
  1476. const useCustomEmail = !useGeneratedAlias && !useHotmail && isCustomEmailGeneratorSelected();
  1477. const useEmailGenerator = !useHotmail && !useGeneratedAlias;
  1478. updateMailLoginButtonState();
  1479. rowEmailPrefix.style.display = useGeneratedAlias ? '' : 'none';
  1480. const hotmailServiceMode = getSelectedHotmailServiceMode();
  1481. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  1482. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  1483. const useCloudflare = selectEmailGenerator.value === 'cloudflare';
  1484. const showCloudflareDomain = useEmailGenerator && useCloudflare;
  1485. if (rowEmailGenerator) {
  1486. rowEmailGenerator.style.display = useEmailGenerator ? '' : 'none';
  1487. }
  1488. rowCfDomain.style.display = showCloudflareDomain ? '' : 'none';
  1489. const { domains } = getCloudflareDomainsFromState();
  1490. if (showCloudflareDomain) {
  1491. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  1492. } else {
  1493. setCloudflareDomainEditMode(false, { clearInput: false });
  1494. }
  1495. if (hotmailSection) {
  1496. hotmailSection.style.display = useHotmail ? '' : 'none';
  1497. }
  1498. labelEmailPrefix.textContent = '邮箱前缀';
  1499. inputEmailPrefix.placeholder = '例如 abc';
  1500. selectEmailGenerator.disabled = useHotmail || useGeneratedAlias;
  1501. if (rowHotmailServiceMode) {
  1502. rowHotmailServiceMode.style.display = useHotmail ? '' : 'none';
  1503. }
  1504. if (rowHotmailRemoteBaseUrl) {
  1505. rowHotmailRemoteBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE ? '' : 'none';
  1506. }
  1507. if (rowHotmailLocalBaseUrl) {
  1508. rowHotmailLocalBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_LOCAL ? '' : 'none';
  1509. }
  1510. btnFetchEmail.hidden = useHotmail || useCustomEmail;
  1511. inputEmail.readOnly = useHotmail || useGeneratedAlias;
  1512. const uiCopy = getEmailGeneratorUiCopy();
  1513. inputEmail.placeholder = useHotmail
  1514. ? '由 Hotmail 账号池自动分配'
  1515. : (use2925 ? '步骤 3 自动生成 2925 邮箱并回填' : uiCopy.placeholder);
  1516. btnFetchEmail.disabled = useGeneratedAlias || useCustomEmail || isAutoRunLockedPhase();
  1517. if (!btnFetchEmail.disabled) {
  1518. btnFetchEmail.textContent = uiCopy.buttonLabel;
  1519. }
  1520. if (autoHintText) {
  1521. autoHintText.textContent = useHotmail
  1522. ? '请先校验并选择一个 Hotmail 账号'
  1523. : (useGeneratedAlias
  1524. ? '步骤 3 会自动生成邮箱,无需手动获取'
  1525. : (useCustomEmail ? '请先填写自定义注册邮箱,成功一轮后会自动清空' : '先自动获取邮箱,或手动粘贴邮箱后再继续'));
  1526. }
  1527. if (useHotmail) {
  1528. inputEmail.value = getCurrentHotmailEmail();
  1529. }
  1530. renderHotmailAccounts();
  1531. }
  1532. async function saveCloudflareDomainSettings(domains, activeDomain, options = {}) {
  1533. const { silent = false } = options;
  1534. const normalizedDomains = normalizeCloudflareDomains(domains);
  1535. const normalizedActiveDomain = normalizeCloudflareDomainValue(activeDomain) || normalizedDomains[0] || '';
  1536. const payload = {
  1537. cloudflareDomain: normalizedActiveDomain,
  1538. cloudflareDomains: normalizedDomains,
  1539. };
  1540. const response = await chrome.runtime.sendMessage({
  1541. type: 'SAVE_SETTING',
  1542. source: 'sidepanel',
  1543. payload,
  1544. });
  1545. if (response?.error) {
  1546. throw new Error(response.error);
  1547. }
  1548. syncLatestState({
  1549. ...payload,
  1550. });
  1551. renderCloudflareDomainOptions(normalizedActiveDomain);
  1552. setCloudflareDomainEditMode(false, { clearInput: true });
  1553. markSettingsDirty(false);
  1554. updateMailProviderUI();
  1555. if (!silent) {
  1556. showToast('Cloudflare 域名已保存', 'success', 1800);
  1557. }
  1558. }
  1559. function updatePanelModeUI() {
  1560. const useSub2Api = selectPanelMode.value === 'sub2api';
  1561. rowVpsUrl.style.display = useSub2Api ? 'none' : '';
  1562. rowVpsPassword.style.display = useSub2Api ? 'none' : '';
  1563. rowLocalCpaStep9Mode.style.display = useSub2Api ? 'none' : '';
  1564. rowSub2ApiUrl.style.display = useSub2Api ? '' : 'none';
  1565. rowSub2ApiEmail.style.display = useSub2Api ? '' : 'none';
  1566. rowSub2ApiPassword.style.display = useSub2Api ? '' : 'none';
  1567. rowSub2ApiGroup.style.display = useSub2Api ? '' : 'none';
  1568. const step9Btn = document.querySelector('.step-btn[data-step="9"]');
  1569. if (step9Btn) {
  1570. step9Btn.textContent = useSub2Api ? 'SUB2API 回调验证' : 'CPA 回调验证';
  1571. }
  1572. }
  1573. // ============================================================
  1574. // UI Updates
  1575. // ============================================================
  1576. function updateStepUI(step, status) {
  1577. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  1578. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  1579. syncLatestState({
  1580. stepStatuses: {
  1581. ...getStepStatuses(),
  1582. [step]: status,
  1583. },
  1584. });
  1585. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  1586. if (row) {
  1587. row.className = `step-row ${status}`;
  1588. }
  1589. updateButtonStates();
  1590. updateProgressCounter();
  1591. updateConfigMenuControls();
  1592. }
  1593. function updateProgressCounter() {
  1594. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  1595. stepsProgress.textContent = `${completed} / 9`;
  1596. }
  1597. function updateButtonStates() {
  1598. const statuses = getStepStatuses();
  1599. const anyRunning = Object.values(statuses).some(s => s === 'running');
  1600. const autoLocked = isAutoRunLockedPhase();
  1601. const autoScheduled = isAutoRunScheduledPhase();
  1602. for (let step = 1; step <= 9; step++) {
  1603. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  1604. if (!btn) continue;
  1605. if (anyRunning || autoLocked || autoScheduled) {
  1606. btn.disabled = true;
  1607. } else if (step === 1) {
  1608. btn.disabled = false;
  1609. } else {
  1610. const prevStatus = statuses[step - 1];
  1611. const currentStatus = statuses[step];
  1612. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  1613. }
  1614. }
  1615. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  1616. const step = Number(btn.dataset.step);
  1617. const currentStatus = statuses[step];
  1618. const prevStatus = statuses[step - 1];
  1619. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  1620. btn.style.display = 'none';
  1621. btn.disabled = true;
  1622. btn.title = '当前不可跳过';
  1623. return;
  1624. }
  1625. if (step > 1 && !isDoneStatus(prevStatus)) {
  1626. btn.style.display = 'none';
  1627. btn.disabled = true;
  1628. btn.title = `请先完成步骤 ${step - 1}`;
  1629. return;
  1630. }
  1631. btn.style.display = '';
  1632. btn.disabled = false;
  1633. btn.title = `跳过步骤 ${step}`;
  1634. });
  1635. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  1636. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  1637. }
  1638. function updateStopButtonState(active) {
  1639. btnStop.disabled = !active;
  1640. }
  1641. function updateStatusDisplay(state) {
  1642. if (!state || !state.stepStatuses) return;
  1643. statusBar.className = 'status-bar';
  1644. if (isAutoRunScheduledPhase()) {
  1645. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  1646. ? currentAutoRun.scheduledAt - Date.now()
  1647. : 0;
  1648. displayStatus.textContent = remainingMs > 0
  1649. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  1650. : '倒计时即将结束,正在准备启动...';
  1651. statusBar.classList.add('scheduled');
  1652. return;
  1653. }
  1654. if (isAutoRunPausedPhase()) {
  1655. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  1656. statusBar.classList.add('paused');
  1657. return;
  1658. }
  1659. if (isAutoRunWaitingStepPhase()) {
  1660. const runningSteps = getRunningSteps(state);
  1661. displayStatus.textContent = runningSteps.length
  1662. ? `自动等待步骤 ${runningSteps.join(', ')} 完成后继续${getAutoRunLabel()}`
  1663. : `自动正在按最新进度准备继续${getAutoRunLabel()}`;
  1664. statusBar.classList.add('running');
  1665. return;
  1666. }
  1667. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  1668. if (running) {
  1669. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  1670. statusBar.classList.add('running');
  1671. return;
  1672. }
  1673. if (isAutoRunLockedPhase()) {
  1674. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  1675. statusBar.classList.add('running');
  1676. return;
  1677. }
  1678. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  1679. if (failed) {
  1680. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  1681. statusBar.classList.add('failed');
  1682. return;
  1683. }
  1684. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  1685. if (stopped) {
  1686. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  1687. statusBar.classList.add('stopped');
  1688. return;
  1689. }
  1690. const lastCompleted = Object.entries(state.stepStatuses)
  1691. .filter(([, s]) => isDoneStatus(s))
  1692. .map(([k]) => Number(k))
  1693. .sort((a, b) => b - a)[0];
  1694. if (lastCompleted === 9) {
  1695. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  1696. statusBar.classList.add('completed');
  1697. } else if (lastCompleted) {
  1698. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  1699. ? `步骤 ${lastCompleted} 已跳过`
  1700. : `步骤 ${lastCompleted} 已完成`;
  1701. } else {
  1702. displayStatus.textContent = '就绪';
  1703. }
  1704. }
  1705. function appendLog(entry) {
  1706. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  1707. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  1708. const line = document.createElement('div');
  1709. line.className = `log-line log-${entry.level}`;
  1710. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  1711. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  1712. let html = `<span class="log-time">${time}</span> `;
  1713. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  1714. if (stepNum) {
  1715. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  1716. }
  1717. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  1718. line.innerHTML = html;
  1719. logArea.appendChild(line);
  1720. logArea.scrollTop = logArea.scrollHeight;
  1721. }
  1722. function escapeHtml(text) {
  1723. const div = document.createElement('div');
  1724. div.textContent = text;
  1725. return div.innerHTML;
  1726. }
  1727. async function fetchGeneratedEmail(options = {}) {
  1728. const { showFailureToast = true } = options;
  1729. const uiCopy = getEmailGeneratorUiCopy();
  1730. if (isCustomEmailGeneratorSelected()) {
  1731. throw new Error('当前邮箱生成方式为自定义邮箱,请直接填写注册邮箱。');
  1732. }
  1733. const defaultLabel = uiCopy.buttonLabel;
  1734. btnFetchEmail.disabled = true;
  1735. btnFetchEmail.textContent = '...';
  1736. try {
  1737. const response = await chrome.runtime.sendMessage({
  1738. type: 'FETCH_GENERATED_EMAIL',
  1739. source: 'sidepanel',
  1740. payload: {
  1741. generateNew: true,
  1742. generator: selectEmailGenerator.value,
  1743. },
  1744. });
  1745. if (response?.error) {
  1746. throw new Error(response.error);
  1747. }
  1748. if (!response?.email) {
  1749. throw new Error('未返回可用邮箱。');
  1750. }
  1751. inputEmail.value = response.email;
  1752. showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500);
  1753. return response.email;
  1754. } catch (err) {
  1755. if (showFailureToast) {
  1756. showToast(`${uiCopy.label}${uiCopy.successVerb}失败:${err.message}`, 'error');
  1757. }
  1758. throw err;
  1759. } finally {
  1760. btnFetchEmail.disabled = false;
  1761. btnFetchEmail.textContent = defaultLabel;
  1762. }
  1763. }
  1764. function syncToggleButtonLabel(button, input, labels) {
  1765. if (!button || !input) return;
  1766. const isHidden = input.type === 'password';
  1767. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  1768. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  1769. button.title = isHidden ? labels.show : labels.hide;
  1770. }
  1771. async function copyTextToClipboard(text) {
  1772. const value = String(text || '').trim();
  1773. if (!value) {
  1774. throw new Error('没有可复制的内容。');
  1775. }
  1776. if (!navigator.clipboard?.writeText) {
  1777. throw new Error('当前环境不支持剪贴板复制。');
  1778. }
  1779. await navigator.clipboard.writeText(value);
  1780. }
  1781. async function exportSettingsFile() {
  1782. closeConfigMenu();
  1783. configActionInFlight = true;
  1784. updateConfigMenuControls();
  1785. try {
  1786. await flushPendingSettingsBeforeExport();
  1787. const response = await chrome.runtime.sendMessage({
  1788. type: 'EXPORT_SETTINGS',
  1789. source: 'sidepanel',
  1790. payload: {},
  1791. });
  1792. if (response?.error) {
  1793. throw new Error(response.error);
  1794. }
  1795. if (!response?.fileContent || !response?.fileName) {
  1796. throw new Error('\u672a\u751f\u6210\u53ef\u4e0b\u8f7d\u7684\u914d\u7f6e\u6587\u4ef6\u3002');
  1797. }
  1798. downloadTextFile(response.fileContent, response.fileName);
  1799. showToast('\u914d\u7f6e\u5df2\u5bfc\u51fa\uff1a' + response.fileName, 'success', 2200);
  1800. } catch (err) {
  1801. showToast('\u5bfc\u51fa\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  1802. } finally {
  1803. configActionInFlight = false;
  1804. updateConfigMenuControls();
  1805. }
  1806. }
  1807. async function importSettingsFromFile(file) {
  1808. if (!file) return;
  1809. configActionInFlight = true;
  1810. closeConfigMenu();
  1811. updateConfigMenuControls();
  1812. try {
  1813. await settlePendingSettingsBeforeImport();
  1814. const rawText = await file.text();
  1815. let parsedConfig = null;
  1816. try {
  1817. parsedConfig = JSON.parse(rawText);
  1818. } catch {
  1819. throw new Error('\u914d\u7f6e\u6587\u4ef6\u4e0d\u662f\u6709\u6548\u7684 JSON\u3002');
  1820. }
  1821. const confirmed = await openConfirmModal({
  1822. title: '\u5bfc\u5165\u914d\u7f6e',
  1823. message: '\u786e\u8ba4\u5bfc\u5165\u914d\u7f6e\u6587\u4ef6 "' + file.name + '" \u5417\uff1f\u5bfc\u5165\u540e\u4f1a\u8986\u76d6\u5f53\u524d\u914d\u7f6e\u3002',
  1824. confirmLabel: '\u786e\u8ba4\u8986\u76d6\u5bfc\u5165',
  1825. confirmVariant: 'btn-danger',
  1826. });
  1827. if (!confirmed) {
  1828. return;
  1829. }
  1830. const response = await chrome.runtime.sendMessage({
  1831. type: 'IMPORT_SETTINGS',
  1832. source: 'sidepanel',
  1833. payload: {
  1834. config: parsedConfig,
  1835. },
  1836. });
  1837. if (response?.error) {
  1838. throw new Error(response.error);
  1839. }
  1840. if (!response?.state) {
  1841. throw new Error('\u5bfc\u5165\u540e\u672a\u8fd4\u56de\u6700\u65b0\u914d\u7f6e\u72b6\u6001\u3002');
  1842. }
  1843. applySettingsState(response.state);
  1844. updateStatusDisplay(latestState);
  1845. showToast('\u914d\u7f6e\u5df2\u5bfc\u5165\uff0c\u5f53\u524d\u914d\u7f6e\u5df2\u8986\u76d6\u3002', 'success', 2200);
  1846. } catch (err) {
  1847. showToast('\u5bfc\u5165\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  1848. } finally {
  1849. configActionInFlight = false;
  1850. updateConfigMenuControls();
  1851. if (inputImportSettingsFile) {
  1852. inputImportSettingsFile.value = '';
  1853. }
  1854. }
  1855. }
  1856. async function deleteHotmailAccountsByMode(mode) {
  1857. const isUsedMode = mode === 'used';
  1858. const targetAccounts = getHotmailAccountsByUsage(isUsedMode ? 'used' : 'all');
  1859. if (!targetAccounts.length) {
  1860. showToast(isUsedMode ? '没有已用账号可清空。' : '没有可删除的 Hotmail 账号。', 'warn');
  1861. return;
  1862. }
  1863. const confirmed = await openConfirmModal({
  1864. title: isUsedMode ? '清空已用账号' : '全部删除账号',
  1865. message: isUsedMode
  1866. ? `确认删除当前 ${targetAccounts.length} 个已用 Hotmail 账号吗?`
  1867. : `确认删除全部 ${targetAccounts.length} 个 Hotmail 账号吗?`,
  1868. confirmLabel: isUsedMode ? '确认清空已用' : '确认全部删除',
  1869. confirmVariant: isUsedMode ? 'btn-outline' : 'btn-danger',
  1870. });
  1871. if (!confirmed) {
  1872. return;
  1873. }
  1874. const response = await chrome.runtime.sendMessage({
  1875. type: 'DELETE_HOTMAIL_ACCOUNTS',
  1876. source: 'sidepanel',
  1877. payload: { mode: isUsedMode ? 'used' : 'all' },
  1878. });
  1879. if (response?.error) {
  1880. throw new Error(response.error);
  1881. }
  1882. const targetIds = new Set(targetAccounts.map((account) => account.id));
  1883. const nextAccounts = isUsedMode
  1884. ? getHotmailAccounts().filter((account) => !targetIds.has(account.id))
  1885. : [];
  1886. const nextState = { hotmailAccounts: nextAccounts };
  1887. if (latestState?.currentHotmailAccountId && targetIds.has(latestState.currentHotmailAccountId)) {
  1888. nextState.currentHotmailAccountId = null;
  1889. if (selectMailProvider.value === 'hotmail-api') {
  1890. nextState.email = null;
  1891. }
  1892. }
  1893. syncLatestState(nextState);
  1894. refreshHotmailSelectionUI();
  1895. showToast(
  1896. isUsedMode
  1897. ? `已清空 ${response.deletedCount || 0} 个已用 Hotmail 账号`
  1898. : `已删除全部 ${response.deletedCount || 0} 个 Hotmail 账号`,
  1899. 'success',
  1900. 2200
  1901. );
  1902. }
  1903. function syncPasswordToggleLabel() {
  1904. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  1905. show: '显示密码',
  1906. hide: '隐藏密码',
  1907. });
  1908. }
  1909. function syncVpsUrlToggleLabel() {
  1910. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  1911. show: '显示 CPA 地址',
  1912. hide: '隐藏 CPA 地址',
  1913. });
  1914. }
  1915. function syncVpsPasswordToggleLabel() {
  1916. syncToggleButtonLabel(btnToggleVpsPassword, inputVpsPassword, {
  1917. show: '显示管理密钥',
  1918. hide: '隐藏管理密钥',
  1919. });
  1920. }
  1921. async function maybeTakeoverAutoRun(actionLabel) {
  1922. if (!isAutoRunPausedPhase()) {
  1923. return true;
  1924. }
  1925. const confirmed = await openConfirmModal({
  1926. title: '接管自动',
  1927. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  1928. confirmLabel: '确认接管',
  1929. confirmVariant: 'btn-primary',
  1930. });
  1931. if (!confirmed) {
  1932. return false;
  1933. }
  1934. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  1935. return true;
  1936. }
  1937. async function handleSkipStep(step) {
  1938. if (isAutoRunPausedPhase()) {
  1939. const takeoverResponse = await chrome.runtime.sendMessage({
  1940. type: 'TAKEOVER_AUTO_RUN',
  1941. source: 'sidepanel',
  1942. payload: {},
  1943. });
  1944. if (takeoverResponse?.error) {
  1945. throw new Error(takeoverResponse.error);
  1946. }
  1947. }
  1948. const response = await chrome.runtime.sendMessage({
  1949. type: 'SKIP_STEP',
  1950. source: 'sidepanel',
  1951. payload: { step },
  1952. });
  1953. if (response?.error) {
  1954. throw new Error(response.error);
  1955. }
  1956. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  1957. }
  1958. // ============================================================
  1959. // Button Handlers
  1960. // ============================================================
  1961. document.querySelectorAll('.step-btn').forEach(btn => {
  1962. btn.addEventListener('click', async () => {
  1963. try {
  1964. const step = Number(btn.dataset.step);
  1965. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  1966. return;
  1967. }
  1968. if (step === 3) {
  1969. if (inputPassword.value !== (latestState?.customPassword || '')) {
  1970. await chrome.runtime.sendMessage({
  1971. type: 'SAVE_SETTING',
  1972. source: 'sidepanel',
  1973. payload: { customPassword: inputPassword.value },
  1974. });
  1975. syncLatestState({ customPassword: inputPassword.value });
  1976. }
  1977. let email = inputEmail.value.trim();
  1978. if (selectMailProvider.value === 'hotmail-api') {
  1979. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  1980. if (response?.error) {
  1981. throw new Error(response.error);
  1982. }
  1983. } else if (usesGeneratedAliasMailProvider(selectMailProvider.value)) {
  1984. const emailPrefix = inputEmailPrefix.value.trim();
  1985. if (!emailPrefix) {
  1986. showToast('请先填写 2925 邮箱前缀。', 'warn');
  1987. return;
  1988. }
  1989. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, emailPrefix } });
  1990. if (response?.error) {
  1991. throw new Error(response.error);
  1992. }
  1993. } else {
  1994. let email = inputEmail.value.trim();
  1995. if (!email) {
  1996. if (isCustomEmailGeneratorSelected()) {
  1997. showToast('当前邮箱生成方式为自定义邮箱,请先填写注册邮箱后再执行第 3 步。', 'warn');
  1998. return;
  1999. }
  2000. try {
  2001. email = await fetchGeneratedEmail({ showFailureToast: false });
  2002. } catch (err) {
  2003. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  2004. return;
  2005. }
  2006. }
  2007. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  2008. if (response?.error) {
  2009. throw new Error(response.error);
  2010. }
  2011. }
  2012. } else {
  2013. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  2014. if (response?.error) {
  2015. throw new Error(response.error);
  2016. }
  2017. }
  2018. } catch (err) {
  2019. showToast(err.message, 'error');
  2020. }
  2021. });
  2022. });
  2023. btnFetchEmail.addEventListener('click', async () => {
  2024. if (selectMailProvider.value === 'hotmail-api' || isCustomEmailGeneratorSelected()) {
  2025. return;
  2026. }
  2027. await fetchGeneratedEmail().catch(() => { });
  2028. });
  2029. btnToggleHotmailList?.addEventListener('click', () => {
  2030. setHotmailListExpanded(!hotmailListExpanded);
  2031. });
  2032. btnHotmailUsageGuide?.addEventListener('click', async () => {
  2033. await openConfirmModal({
  2034. title: '使用教程',
  2035. message: '由于第三方服务接口结构不同,所以暂时无法使用,如果您的token可以直连微软,请测试本地功能,详细功能请看项目根目录的readme文件',
  2036. confirmLabel: '确定',
  2037. confirmVariant: 'btn-primary',
  2038. });
  2039. });
  2040. btnClearUsedHotmailAccounts?.addEventListener('click', async () => {
  2041. if (hotmailActionInFlight) return;
  2042. hotmailActionInFlight = true;
  2043. btnClearUsedHotmailAccounts.disabled = true;
  2044. try {
  2045. await deleteHotmailAccountsByMode('used');
  2046. } catch (err) {
  2047. showToast(err.message, 'error');
  2048. } finally {
  2049. hotmailActionInFlight = false;
  2050. updateHotmailListViewport();
  2051. }
  2052. });
  2053. btnDeleteAllHotmailAccounts?.addEventListener('click', async () => {
  2054. if (hotmailActionInFlight) return;
  2055. hotmailActionInFlight = true;
  2056. btnDeleteAllHotmailAccounts.disabled = true;
  2057. try {
  2058. await deleteHotmailAccountsByMode('all');
  2059. } catch (err) {
  2060. showToast(err.message, 'error');
  2061. } finally {
  2062. hotmailActionInFlight = false;
  2063. updateHotmailListViewport();
  2064. }
  2065. });
  2066. btnAddHotmailAccount?.addEventListener('click', async () => {
  2067. if (hotmailActionInFlight) return;
  2068. const email = inputHotmailEmail.value.trim();
  2069. const clientId = inputHotmailClientId.value.trim();
  2070. const refreshToken = inputHotmailRefreshToken.value.trim();
  2071. if (!email) {
  2072. showToast('请先填写 Hotmail 邮箱。', 'warn');
  2073. return;
  2074. }
  2075. if (!clientId) {
  2076. showToast('请先填写微软应用客户端 ID。', 'warn');
  2077. return;
  2078. }
  2079. if (!refreshToken) {
  2080. showToast('请先填写刷新令牌(refresh token)。', 'warn');
  2081. return;
  2082. }
  2083. hotmailActionInFlight = true;
  2084. btnAddHotmailAccount.disabled = true;
  2085. try {
  2086. const response = await chrome.runtime.sendMessage({
  2087. type: 'UPSERT_HOTMAIL_ACCOUNT',
  2088. source: 'sidepanel',
  2089. payload: {
  2090. email,
  2091. clientId,
  2092. password: inputHotmailPassword.value,
  2093. refreshToken,
  2094. },
  2095. });
  2096. if (response?.error) {
  2097. throw new Error(response.error);
  2098. }
  2099. showToast(`已保存 Hotmail 账号 ${email}`, 'success', 1800);
  2100. clearHotmailForm();
  2101. } catch (err) {
  2102. showToast(`保存 Hotmail 账号失败:${err.message}`, 'error');
  2103. } finally {
  2104. hotmailActionInFlight = false;
  2105. btnAddHotmailAccount.disabled = false;
  2106. }
  2107. });
  2108. btnImportHotmailAccounts?.addEventListener('click', async () => {
  2109. if (hotmailActionInFlight) return;
  2110. if (typeof parseHotmailImportText !== 'function') {
  2111. showToast('导入解析器未加载,请刷新扩展后重试。', 'error');
  2112. return;
  2113. }
  2114. const rawText = inputHotmailImport.value.trim();
  2115. if (!rawText) {
  2116. showToast('请先粘贴账号导入内容。', 'warn');
  2117. return;
  2118. }
  2119. const parsedAccounts = parseHotmailImportText(rawText);
  2120. if (!parsedAccounts.length) {
  2121. showToast('没有解析到有效账号,请检查格式是否为 账号----密码----ID----Token。', 'error');
  2122. return;
  2123. }
  2124. hotmailActionInFlight = true;
  2125. btnImportHotmailAccounts.disabled = true;
  2126. try {
  2127. for (const account of parsedAccounts) {
  2128. const response = await chrome.runtime.sendMessage({
  2129. type: 'UPSERT_HOTMAIL_ACCOUNT',
  2130. source: 'sidepanel',
  2131. payload: account,
  2132. });
  2133. if (response?.error) {
  2134. throw new Error(response.error);
  2135. }
  2136. }
  2137. inputHotmailImport.value = '';
  2138. showToast(`已导入 ${parsedAccounts.length} 条 Hotmail 账号`, 'success', 2200);
  2139. } catch (err) {
  2140. showToast(`批量导入失败:${err.message}`, 'error');
  2141. } finally {
  2142. hotmailActionInFlight = false;
  2143. btnImportHotmailAccounts.disabled = false;
  2144. }
  2145. });
  2146. hotmailAccountsList?.addEventListener('click', async (event) => {
  2147. const actionButton = event.target.closest('[data-account-action]');
  2148. if (!actionButton || hotmailActionInFlight) {
  2149. return;
  2150. }
  2151. const accountId = actionButton.dataset.accountId;
  2152. const action = actionButton.dataset.accountAction;
  2153. if (!accountId || !action) {
  2154. return;
  2155. }
  2156. const targetAccount = getHotmailAccounts().find((account) => account.id === accountId) || null;
  2157. hotmailActionInFlight = true;
  2158. actionButton.disabled = true;
  2159. try {
  2160. if (action === 'copy-email') {
  2161. if (!targetAccount?.email) throw new Error('未找到可复制的邮箱地址。');
  2162. await copyTextToClipboard(targetAccount.email);
  2163. showToast(`已复制 ${targetAccount.email}`, 'success', 1800);
  2164. } else if (action === 'select') {
  2165. const response = await chrome.runtime.sendMessage({
  2166. type: 'SELECT_HOTMAIL_ACCOUNT',
  2167. source: 'sidepanel',
  2168. payload: { accountId },
  2169. });
  2170. if (response?.error) throw new Error(response.error);
  2171. syncLatestState({ currentHotmailAccountId: response.account.id });
  2172. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  2173. showToast(`已切换当前 Hotmail 账号为 ${response.account.email}`, 'success', 1800);
  2174. } else if (action === 'toggle-used') {
  2175. if (!targetAccount) throw new Error('未找到目标 Hotmail 账号。');
  2176. const response = await chrome.runtime.sendMessage({
  2177. type: 'PATCH_HOTMAIL_ACCOUNT',
  2178. source: 'sidepanel',
  2179. payload: {
  2180. accountId,
  2181. updates: { used: !targetAccount.used },
  2182. },
  2183. });
  2184. if (response?.error) throw new Error(response.error);
  2185. applyHotmailAccountMutation(response.account);
  2186. showToast(`账号 ${response.account.email} 已${response.account.used ? '标记为已用' : '恢复为未用'}`, 'success', 2200);
  2187. } else if (action === 'verify') {
  2188. const response = await chrome.runtime.sendMessage({
  2189. type: 'VERIFY_HOTMAIL_ACCOUNT',
  2190. source: 'sidepanel',
  2191. payload: { accountId },
  2192. });
  2193. if (response?.error) throw new Error(response.error);
  2194. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  2195. showToast(`账号 ${response.account.email} 校验通过`, 'success', 2200);
  2196. } else if (action === 'test') {
  2197. const response = await chrome.runtime.sendMessage({
  2198. type: 'TEST_HOTMAIL_ACCOUNT',
  2199. source: 'sidepanel',
  2200. payload: { accountId },
  2201. });
  2202. if (response?.error) throw new Error(response.error);
  2203. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  2204. if (response.latestCode) {
  2205. await copyTextToClipboard(response.latestCode);
  2206. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  2207. showToast(`已复制最新验证码 ${response.latestCode}${mailbox}`, 'success', 2600);
  2208. } else if (response.latestSubject) {
  2209. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  2210. showToast(`最新邮件${mailbox}没有验证码:${response.latestSubject}`, 'warn', 3200);
  2211. } else {
  2212. showToast('当前没有可读取的最新邮件。', 'warn', 2600);
  2213. }
  2214. } else if (action === 'delete') {
  2215. const confirmed = await openConfirmModal({
  2216. title: '删除账号',
  2217. message: '确认删除这个 Hotmail 账号吗?对应 token 也会一起移除。',
  2218. confirmLabel: '确认删除',
  2219. confirmVariant: 'btn-danger',
  2220. });
  2221. if (!confirmed) {
  2222. return;
  2223. }
  2224. const response = await chrome.runtime.sendMessage({
  2225. type: 'DELETE_HOTMAIL_ACCOUNT',
  2226. source: 'sidepanel',
  2227. payload: { accountId },
  2228. });
  2229. if (response?.error) throw new Error(response.error);
  2230. showToast('Hotmail 账号已删除', 'success', 1800);
  2231. }
  2232. } catch (err) {
  2233. showToast(err.message, 'error');
  2234. } finally {
  2235. hotmailActionInFlight = false;
  2236. actionButton.disabled = false;
  2237. }
  2238. });
  2239. btnTogglePassword.addEventListener('click', () => {
  2240. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  2241. syncPasswordToggleLabel();
  2242. });
  2243. btnToggleVpsUrl.addEventListener('click', () => {
  2244. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  2245. syncVpsUrlToggleLabel();
  2246. });
  2247. btnToggleVpsPassword.addEventListener('click', () => {
  2248. inputVpsPassword.type = inputVpsPassword.type === 'password' ? 'text' : 'password';
  2249. syncVpsPasswordToggleLabel();
  2250. });
  2251. btnMailLogin?.addEventListener('click', async () => {
  2252. const config = getMailProviderLoginConfig();
  2253. if (!config) {
  2254. return;
  2255. }
  2256. try {
  2257. await chrome.tabs.create({ url: config.url, active: true });
  2258. } catch (err) {
  2259. showToast(`打开${config.label}失败:${err.message}`, 'error');
  2260. }
  2261. });
  2262. localCpaStep9ModeButtons.forEach((button) => {
  2263. button.addEventListener('click', () => {
  2264. const nextMode = button.dataset.localCpaStep9Mode;
  2265. if (getSelectedLocalCpaStep9Mode() === normalizeLocalCpaStep9Mode(nextMode)) {
  2266. return;
  2267. }
  2268. setLocalCpaStep9Mode(nextMode);
  2269. markSettingsDirty(true);
  2270. saveSettings({ silent: true }).catch(() => { });
  2271. });
  2272. });
  2273. hotmailServiceModeButtons.forEach((button) => {
  2274. button.addEventListener('click', () => {
  2275. if (button.disabled) {
  2276. return;
  2277. }
  2278. const nextMode = button.dataset.hotmailServiceMode;
  2279. if (getSelectedHotmailServiceMode() === normalizeHotmailServiceMode(nextMode)) {
  2280. return;
  2281. }
  2282. setHotmailServiceMode(nextMode);
  2283. updateMailProviderUI();
  2284. markSettingsDirty(true);
  2285. saveSettings({ silent: true }).catch(() => { });
  2286. });
  2287. });
  2288. btnSaveSettings.addEventListener('click', async () => {
  2289. if (!settingsDirty) {
  2290. showToast('配置已是最新', 'info', 1400);
  2291. return;
  2292. }
  2293. await saveSettings({ silent: false }).catch(() => { });
  2294. });
  2295. btnStop.addEventListener('click', async () => {
  2296. btnStop.disabled = true;
  2297. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  2298. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  2299. });
  2300. btnConfigMenu?.addEventListener('click', (event) => {
  2301. event.stopPropagation();
  2302. toggleConfigMenu();
  2303. });
  2304. configMenu?.addEventListener('click', (event) => {
  2305. event.stopPropagation();
  2306. });
  2307. btnExportSettings?.addEventListener('click', async () => {
  2308. if (configActionInFlight || settingsSaveInFlight) {
  2309. return;
  2310. }
  2311. await exportSettingsFile();
  2312. });
  2313. btnImportSettings?.addEventListener('click', async () => {
  2314. if (configActionInFlight || settingsSaveInFlight) {
  2315. return;
  2316. }
  2317. closeConfigMenu();
  2318. if (inputImportSettingsFile) {
  2319. inputImportSettingsFile.value = '';
  2320. inputImportSettingsFile.click();
  2321. }
  2322. });
  2323. inputImportSettingsFile?.addEventListener('change', async () => {
  2324. const file = inputImportSettingsFile.files?.[0] || null;
  2325. await importSettingsFromFile(file);
  2326. });
  2327. autoStartModal?.addEventListener('click', (event) => {
  2328. if (event.target === autoStartModal) {
  2329. resolveModalChoice(null);
  2330. }
  2331. });
  2332. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  2333. // Auto Run
  2334. btnAutoRun.addEventListener('click', async () => {
  2335. try {
  2336. const totalRuns = getRunCountValue();
  2337. let mode = 'restart';
  2338. if (shouldOfferAutoModeChoice()) {
  2339. const startStep = getFirstUnfinishedStep();
  2340. const runningStep = getRunningSteps()[0] ?? null;
  2341. const choice = await openAutoStartChoiceDialog(startStep, { runningStep });
  2342. if (!choice) {
  2343. return;
  2344. }
  2345. mode = choice;
  2346. }
  2347. btnAutoRun.disabled = true;
  2348. inputRunCount.disabled = true;
  2349. const delayEnabled = inputAutoDelayEnabled.checked;
  2350. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  2351. inputAutoDelayMinutes.value = String(delayMinutes);
  2352. btnAutoRun.innerHTML = delayEnabled
  2353. ? '<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> 计划中...'
  2354. : '<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> 运行中...';
  2355. const response = await chrome.runtime.sendMessage({
  2356. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  2357. source: 'sidepanel',
  2358. payload: {
  2359. totalRuns,
  2360. delayMinutes,
  2361. autoRunSkipFailures: true,
  2362. mode,
  2363. },
  2364. });
  2365. if (response?.error) {
  2366. throw new Error(response.error);
  2367. }
  2368. } catch (err) {
  2369. setDefaultAutoRunButton();
  2370. inputRunCount.disabled = false;
  2371. showToast(err.message, 'error');
  2372. }
  2373. });
  2374. btnAutoContinue.addEventListener('click', async () => {
  2375. const email = inputEmail.value.trim();
  2376. if (!email) {
  2377. showToast(
  2378. isCustomEmailGeneratorSelected() ? '请先填写自定义注册邮箱。' : '请先获取或粘贴邮箱。',
  2379. 'warn'
  2380. );
  2381. return;
  2382. }
  2383. autoContinueBar.style.display = 'none';
  2384. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  2385. });
  2386. btnAutoRunNow?.addEventListener('click', async () => {
  2387. try {
  2388. btnAutoRunNow.disabled = true;
  2389. await chrome.runtime.sendMessage({ type: 'START_SCHEDULED_AUTO_RUN_NOW', source: 'sidepanel', payload: {} });
  2390. } catch (err) {
  2391. showToast(err.message, 'error');
  2392. } finally {
  2393. btnAutoRunNow.disabled = false;
  2394. }
  2395. });
  2396. btnAutoCancelSchedule?.addEventListener('click', async () => {
  2397. try {
  2398. btnAutoCancelSchedule.disabled = true;
  2399. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  2400. showToast('已取消倒计时计划。', 'info', 1800);
  2401. } catch (err) {
  2402. showToast(err.message, 'error');
  2403. } finally {
  2404. btnAutoCancelSchedule.disabled = false;
  2405. }
  2406. });
  2407. // Reset
  2408. btnReset.addEventListener('click', async () => {
  2409. const confirmed = await openConfirmModal({
  2410. title: '重置流程',
  2411. message: '确认重置全部步骤和数据吗?',
  2412. confirmLabel: '确认重置',
  2413. confirmVariant: 'btn-danger',
  2414. });
  2415. if (!confirmed) {
  2416. return;
  2417. }
  2418. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  2419. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES, currentHotmailAccountId: null, email: null });
  2420. syncAutoRunState({
  2421. autoRunning: false,
  2422. autoRunPhase: 'idle',
  2423. autoRunCurrentRun: 0,
  2424. autoRunTotalRuns: 1,
  2425. autoRunAttemptRun: 0,
  2426. scheduledAutoRunAt: null,
  2427. });
  2428. displayOauthUrl.textContent = '等待中...';
  2429. displayOauthUrl.classList.remove('has-value');
  2430. displayLocalhostUrl.textContent = '等待中...';
  2431. displayLocalhostUrl.classList.remove('has-value');
  2432. inputEmail.value = '';
  2433. displayStatus.textContent = '就绪';
  2434. statusBar.className = 'status-bar';
  2435. logArea.innerHTML = '';
  2436. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  2437. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  2438. setDefaultAutoRunButton();
  2439. applyAutoRunStatus(currentAutoRun);
  2440. markSettingsDirty(false);
  2441. updateStopButtonState(false);
  2442. updateButtonStates();
  2443. updateProgressCounter();
  2444. renderHotmailAccounts();
  2445. });
  2446. // Clear log
  2447. btnClearLog.addEventListener('click', () => {
  2448. logArea.innerHTML = '';
  2449. });
  2450. // Save settings on change
  2451. inputEmail.addEventListener('change', async () => {
  2452. if (selectMailProvider.value === 'hotmail-api') {
  2453. return;
  2454. }
  2455. const email = inputEmail.value.trim();
  2456. inputEmail.value = email;
  2457. try {
  2458. if (email) {
  2459. const response = await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  2460. if (response?.error) {
  2461. throw new Error(response.error);
  2462. }
  2463. } else {
  2464. await setRuntimeEmailState(null);
  2465. }
  2466. } catch (err) {
  2467. showToast(err.message, 'error');
  2468. }
  2469. });
  2470. inputEmail.addEventListener('input', updateButtonStates);
  2471. inputVpsUrl.addEventListener('input', () => {
  2472. markSettingsDirty(true);
  2473. scheduleSettingsAutoSave();
  2474. });
  2475. inputVpsUrl.addEventListener('blur', () => {
  2476. saveSettings({ silent: true }).catch(() => { });
  2477. });
  2478. inputVpsPassword.addEventListener('input', () => {
  2479. markSettingsDirty(true);
  2480. scheduleSettingsAutoSave();
  2481. });
  2482. inputVpsPassword.addEventListener('blur', () => {
  2483. saveSettings({ silent: true }).catch(() => { });
  2484. });
  2485. [inputHotmailRemoteBaseUrl, inputHotmailLocalBaseUrl].forEach((input) => {
  2486. input?.addEventListener('input', () => {
  2487. markSettingsDirty(true);
  2488. scheduleSettingsAutoSave();
  2489. });
  2490. input?.addEventListener('blur', () => {
  2491. saveSettings({ silent: true }).catch(() => { });
  2492. });
  2493. });
  2494. inputPassword.addEventListener('input', () => {
  2495. markSettingsDirty(true);
  2496. updateButtonStates();
  2497. scheduleSettingsAutoSave();
  2498. });
  2499. inputPassword.addEventListener('blur', () => {
  2500. saveSettings({ silent: true }).catch(() => { });
  2501. });
  2502. selectMailProvider.addEventListener('change', async () => {
  2503. const previousProvider = latestState?.mailProvider || '';
  2504. const nextProvider = selectMailProvider.value;
  2505. updateMailProviderUI();
  2506. const leavingHotmail = previousProvider === 'hotmail-api'
  2507. && nextProvider !== 'hotmail-api'
  2508. && isCurrentEmailManagedByHotmail();
  2509. const leavingGeneratedAlias = previousProvider !== nextProvider
  2510. && usesGeneratedAliasMailProvider(previousProvider)
  2511. && isCurrentEmailManagedByGeneratedAlias(previousProvider);
  2512. if (leavingHotmail || leavingGeneratedAlias) {
  2513. await clearRegistrationEmail({ silent: true }).catch(() => { });
  2514. }
  2515. markSettingsDirty(true);
  2516. saveSettings({ silent: true }).catch(() => { });
  2517. });
  2518. selectEmailGenerator.addEventListener('change', () => {
  2519. updateMailProviderUI();
  2520. clearRegistrationEmail({ silent: true }).catch(() => { });
  2521. markSettingsDirty(true);
  2522. saveSettings({ silent: true }).catch(() => { });
  2523. });
  2524. selectPanelMode.addEventListener('change', () => {
  2525. updatePanelModeUI();
  2526. markSettingsDirty(true);
  2527. saveSettings({ silent: true }).catch(() => { });
  2528. });
  2529. selectCfDomain.addEventListener('change', () => {
  2530. if (selectCfDomain.disabled) {
  2531. return;
  2532. }
  2533. markSettingsDirty(true);
  2534. saveSettings({ silent: true }).catch(() => { });
  2535. });
  2536. btnCfDomainMode.addEventListener('click', async () => {
  2537. try {
  2538. if (!cloudflareDomainEditMode) {
  2539. setCloudflareDomainEditMode(true, { clearInput: true });
  2540. return;
  2541. }
  2542. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  2543. if (!newDomain) {
  2544. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  2545. inputCfDomain.focus();
  2546. return;
  2547. }
  2548. const { domains } = getCloudflareDomainsFromState();
  2549. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  2550. } catch (err) {
  2551. showToast(err.message, 'error');
  2552. }
  2553. });
  2554. inputCfDomain.addEventListener('keydown', (event) => {
  2555. if (event.key === 'Enter') {
  2556. event.preventDefault();
  2557. btnCfDomainMode.click();
  2558. }
  2559. });
  2560. inputSub2ApiUrl.addEventListener('input', () => {
  2561. markSettingsDirty(true);
  2562. scheduleSettingsAutoSave();
  2563. });
  2564. inputSub2ApiUrl.addEventListener('blur', () => {
  2565. saveSettings({ silent: true }).catch(() => { });
  2566. });
  2567. inputSub2ApiEmail.addEventListener('input', () => {
  2568. markSettingsDirty(true);
  2569. scheduleSettingsAutoSave();
  2570. });
  2571. inputSub2ApiEmail.addEventListener('blur', () => {
  2572. saveSettings({ silent: true }).catch(() => { });
  2573. });
  2574. inputSub2ApiPassword.addEventListener('input', () => {
  2575. markSettingsDirty(true);
  2576. scheduleSettingsAutoSave();
  2577. });
  2578. inputSub2ApiPassword.addEventListener('blur', () => {
  2579. saveSettings({ silent: true }).catch(() => { });
  2580. });
  2581. inputSub2ApiGroup.addEventListener('input', () => {
  2582. markSettingsDirty(true);
  2583. scheduleSettingsAutoSave();
  2584. });
  2585. inputSub2ApiGroup.addEventListener('blur', () => {
  2586. saveSettings({ silent: true }).catch(() => { });
  2587. });
  2588. inputEmailPrefix.addEventListener('input', () => {
  2589. markSettingsDirty(true);
  2590. scheduleSettingsAutoSave();
  2591. });
  2592. inputEmailPrefix.addEventListener('blur', () => {
  2593. saveSettings({ silent: true }).catch(() => {});
  2594. });
  2595. inputInbucketMailbox.addEventListener('input', () => {
  2596. markSettingsDirty(true);
  2597. scheduleSettingsAutoSave();
  2598. });
  2599. inputInbucketMailbox.addEventListener('blur', () => {
  2600. saveSettings({ silent: true }).catch(() => { });
  2601. });
  2602. inputInbucketHost.addEventListener('input', () => {
  2603. markSettingsDirty(true);
  2604. scheduleSettingsAutoSave();
  2605. });
  2606. inputInbucketHost.addEventListener('blur', () => {
  2607. saveSettings({ silent: true }).catch(() => { });
  2608. });
  2609. inputRunCount.addEventListener('input', () => {
  2610. updateFallbackThreadIntervalInputState();
  2611. });
  2612. inputRunCount.addEventListener('blur', () => {
  2613. inputRunCount.value = String(getRunCountValue());
  2614. updateFallbackThreadIntervalInputState();
  2615. });
  2616. inputAutoSkipFailures.addEventListener('change', async () => {
  2617. if (inputAutoSkipFailures.checked && !isAutoSkipFailuresPromptDismissed()) {
  2618. const result = await openAutoSkipFailuresConfirmModal();
  2619. if (!result.confirmed) {
  2620. inputAutoSkipFailures.checked = false;
  2621. updateFallbackThreadIntervalInputState();
  2622. return;
  2623. }
  2624. if (result.dismissPrompt) {
  2625. setAutoSkipFailuresPromptDismissed(true);
  2626. }
  2627. }
  2628. updateFallbackThreadIntervalInputState();
  2629. markSettingsDirty(true);
  2630. saveSettings({ silent: true }).catch(() => { });
  2631. });
  2632. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('input', () => {
  2633. markSettingsDirty(true);
  2634. scheduleSettingsAutoSave();
  2635. });
  2636. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('blur', () => {
  2637. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  2638. normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value)
  2639. );
  2640. saveSettings({ silent: true }).catch(() => { });
  2641. });
  2642. inputAutoDelayEnabled.addEventListener('change', () => {
  2643. updateAutoDelayInputState();
  2644. markSettingsDirty(true);
  2645. saveSettings({ silent: true }).catch(() => { });
  2646. });
  2647. inputAutoDelayMinutes.addEventListener('input', () => {
  2648. markSettingsDirty(true);
  2649. scheduleSettingsAutoSave();
  2650. });
  2651. inputAutoDelayMinutes.addEventListener('blur', () => {
  2652. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  2653. saveSettings({ silent: true }).catch(() => { });
  2654. });
  2655. function syncAutoStepDelayInputs() {
  2656. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(inputAutoStepDelaySeconds.value);
  2657. }
  2658. inputAutoStepDelaySeconds.addEventListener('input', () => {
  2659. markSettingsDirty(true);
  2660. scheduleSettingsAutoSave();
  2661. });
  2662. inputAutoStepDelaySeconds.addEventListener('blur', () => {
  2663. syncAutoStepDelayInputs();
  2664. saveSettings({ silent: true }).catch(() => { });
  2665. });
  2666. // ============================================================
  2667. // Listen for Background broadcasts
  2668. // ============================================================
  2669. chrome.runtime.onMessage.addListener((message) => {
  2670. switch (message.type) {
  2671. case 'LOG_ENTRY':
  2672. appendLog(message.payload);
  2673. if (message.payload.level === 'error') {
  2674. showToast(message.payload.message, 'error');
  2675. }
  2676. break;
  2677. case 'STEP_STATUS_CHANGED': {
  2678. const { step, status } = message.payload;
  2679. updateStepUI(step, status);
  2680. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  2681. syncLatestState(state);
  2682. syncAutoRunState(state);
  2683. updateStatusDisplay(latestState);
  2684. updateButtonStates();
  2685. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  2686. syncPasswordField(state);
  2687. if (state.oauthUrl) {
  2688. displayOauthUrl.textContent = state.oauthUrl;
  2689. displayOauthUrl.classList.add('has-value');
  2690. }
  2691. if (state.localhostUrl) {
  2692. displayLocalhostUrl.textContent = state.localhostUrl;
  2693. displayLocalhostUrl.classList.add('has-value');
  2694. }
  2695. }
  2696. }
  2697. ).catch(() => { });
  2698. break;
  2699. }
  2700. case 'AUTO_RUN_RESET': {
  2701. // Full UI reset for next run
  2702. syncLatestState({
  2703. oauthUrl: null,
  2704. localhostUrl: null,
  2705. email: null,
  2706. password: null,
  2707. stepStatuses: STEP_DEFAULT_STATUSES,
  2708. logs: [],
  2709. scheduledAutoRunAt: null,
  2710. });
  2711. displayOauthUrl.textContent = '等待中...';
  2712. displayOauthUrl.classList.remove('has-value');
  2713. displayLocalhostUrl.textContent = '等待中...';
  2714. displayLocalhostUrl.classList.remove('has-value');
  2715. inputEmail.value = '';
  2716. displayStatus.textContent = '就绪';
  2717. statusBar.className = 'status-bar';
  2718. logArea.innerHTML = '';
  2719. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  2720. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  2721. applyAutoRunStatus(currentAutoRun);
  2722. updateProgressCounter();
  2723. updateButtonStates();
  2724. renderHotmailAccounts();
  2725. break;
  2726. }
  2727. case 'DATA_UPDATED': {
  2728. syncLatestState(message.payload);
  2729. if (message.payload.email !== undefined) {
  2730. inputEmail.value = message.payload.email || '';
  2731. }
  2732. if (message.payload.password !== undefined) {
  2733. inputPassword.value = message.payload.password || '';
  2734. }
  2735. if (message.payload.localCpaStep9Mode !== undefined) {
  2736. setLocalCpaStep9Mode(message.payload.localCpaStep9Mode);
  2737. }
  2738. if (message.payload.oauthUrl !== undefined) {
  2739. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  2740. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  2741. }
  2742. if (message.payload.localhostUrl !== undefined) {
  2743. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  2744. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  2745. }
  2746. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  2747. renderHotmailAccounts();
  2748. if (selectMailProvider.value === 'hotmail-api') {
  2749. inputEmail.value = getCurrentHotmailEmail();
  2750. }
  2751. }
  2752. if (message.payload.autoRunSkipFailures !== undefined) {
  2753. inputAutoSkipFailures.checked = true;
  2754. updateFallbackThreadIntervalInputState();
  2755. }
  2756. if (message.payload.autoRunDelayEnabled !== undefined) {
  2757. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  2758. updateAutoDelayInputState();
  2759. }
  2760. if (message.payload.autoRunDelayMinutes !== undefined) {
  2761. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  2762. }
  2763. if (message.payload.autoRunFallbackThreadIntervalMinutes !== undefined) {
  2764. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  2765. normalizeAutoRunThreadIntervalMinutes(message.payload.autoRunFallbackThreadIntervalMinutes)
  2766. );
  2767. updateFallbackThreadIntervalInputState();
  2768. }
  2769. if (message.payload.autoStepDelaySeconds !== undefined) {
  2770. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(message.payload.autoStepDelaySeconds);
  2771. }
  2772. break;
  2773. }
  2774. case 'AUTO_RUN_STATUS': {
  2775. syncLatestState({
  2776. autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying'].includes(message.payload.phase),
  2777. autoRunPhase: message.payload.phase,
  2778. autoRunCurrentRun: message.payload.currentRun,
  2779. autoRunTotalRuns: message.payload.totalRuns,
  2780. autoRunAttemptRun: message.payload.attemptRun,
  2781. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  2782. });
  2783. applyAutoRunStatus(message.payload);
  2784. updateStatusDisplay(latestState);
  2785. updateButtonStates();
  2786. break;
  2787. }
  2788. }
  2789. });
  2790. // ============================================================
  2791. // Theme Toggle
  2792. // ============================================================
  2793. const btnTheme = document.getElementById('btn-theme');
  2794. function setTheme(theme) {
  2795. document.documentElement.setAttribute('data-theme', theme);
  2796. localStorage.setItem('multipage-theme', theme);
  2797. }
  2798. function initTheme() {
  2799. const saved = localStorage.getItem('multipage-theme');
  2800. if (saved) {
  2801. setTheme(saved);
  2802. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  2803. setTheme('dark');
  2804. }
  2805. }
  2806. btnTheme.addEventListener('click', () => {
  2807. const current = document.documentElement.getAttribute('data-theme');
  2808. setTheme(current === 'dark' ? 'light' : 'dark');
  2809. });
  2810. document.addEventListener('click', (event) => {
  2811. if (!configMenuOpen) {
  2812. return;
  2813. }
  2814. if (configMenuShell?.contains(event.target)) {
  2815. return;
  2816. }
  2817. closeConfigMenu();
  2818. });
  2819. document.addEventListener('keydown', (event) => {
  2820. if (event.key === 'Escape' && configMenuOpen) {
  2821. closeConfigMenu();
  2822. }
  2823. });
  2824. // ============================================================
  2825. // Init
  2826. // ============================================================
  2827. initializeManualStepActions();
  2828. initTheme();
  2829. initHotmailListExpandedState();
  2830. updateSaveButtonState();
  2831. updateConfigMenuControls();
  2832. setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
  2833. initializeReleaseInfo().catch((err) => {
  2834. console.error('Failed to initialize release info:', err);
  2835. });
  2836. restoreState().then(() => {
  2837. syncPasswordToggleLabel();
  2838. syncVpsUrlToggleLabel();
  2839. syncVpsPasswordToggleLabel();
  2840. updatePanelModeUI();
  2841. updateButtonStates();
  2842. updateStatusDisplay(latestState);
  2843. });