sidepanel.js 89 KB

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