sidepanel.js 108 KB

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