main.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. // 使用 CommonJS 格式
  2. const { app, BrowserWindow, ipcMain, shell, session, Menu, Tray, nativeImage, webContents } = require('electron');
  3. const { join } = require('path');
  4. const fs = require('fs');
  5. let mainWindow: typeof BrowserWindow.prototype | null = null;
  6. let tray: typeof Tray.prototype | null = null;
  7. let isQuitting = false;
  8. const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL;
  9. // 获取图标路径
  10. function getIconPath() {
  11. return VITE_DEV_SERVER_URL
  12. ? join(__dirname, '../public/icons/icon-256.png')
  13. : join(__dirname, '../dist/icons/icon-256.png');
  14. }
  15. // 获取托盘图标路径
  16. function getTrayIconPath() {
  17. return VITE_DEV_SERVER_URL
  18. ? join(__dirname, '../public/icons/tray-icon.png')
  19. : join(__dirname, '../dist/icons/tray-icon.png');
  20. }
  21. // 创建托盘图标
  22. function createTrayIcon(): typeof nativeImage.prototype {
  23. const trayIconPath = getTrayIconPath();
  24. return nativeImage.createFromPath(trayIconPath);
  25. }
  26. // 创建系统托盘
  27. function createTray() {
  28. const trayIcon = createTrayIcon();
  29. tray = new Tray(trayIcon);
  30. const contextMenu = Menu.buildFromTemplate([
  31. {
  32. label: '显示主窗口',
  33. click: () => {
  34. if (mainWindow) {
  35. mainWindow.show();
  36. mainWindow.focus();
  37. }
  38. }
  39. },
  40. {
  41. label: '最小化到托盘',
  42. click: () => {
  43. mainWindow?.hide();
  44. }
  45. },
  46. { type: 'separator' },
  47. {
  48. label: '退出',
  49. click: () => {
  50. isQuitting = true;
  51. app.quit();
  52. }
  53. }
  54. ]);
  55. tray.setToolTip('多平台媒体管理系统');
  56. tray.setContextMenu(contextMenu);
  57. // 点击托盘图标显示窗口
  58. tray.on('click', () => {
  59. if (mainWindow) {
  60. if (mainWindow.isVisible()) {
  61. mainWindow.focus();
  62. } else {
  63. mainWindow.show();
  64. mainWindow.focus();
  65. }
  66. }
  67. });
  68. // 双击托盘图标显示窗口
  69. tray.on('double-click', () => {
  70. if (mainWindow) {
  71. mainWindow.show();
  72. mainWindow.focus();
  73. }
  74. });
  75. }
  76. function createWindow() {
  77. // 隐藏默认菜单栏
  78. Menu.setApplicationMenu(null);
  79. const iconPath = getIconPath();
  80. mainWindow = new BrowserWindow({
  81. width: 1400,
  82. height: 900,
  83. minWidth: 1200,
  84. minHeight: 700,
  85. icon: iconPath,
  86. webPreferences: {
  87. preload: join(__dirname, 'preload.js'),
  88. nodeIntegration: false,
  89. contextIsolation: true,
  90. webviewTag: true, // 启用 webview 标签
  91. },
  92. frame: false, // 无边框窗口,自定义标题栏
  93. transparent: false,
  94. backgroundColor: '#f0f2f5',
  95. show: false,
  96. });
  97. // 窗口准备好后再显示,避免白屏
  98. mainWindow.once('ready-to-show', () => {
  99. mainWindow?.show();
  100. setupWindowEvents();
  101. });
  102. // 加载页面
  103. if (VITE_DEV_SERVER_URL) {
  104. mainWindow.loadURL(VITE_DEV_SERVER_URL);
  105. mainWindow.webContents.openDevTools();
  106. } else {
  107. mainWindow.loadFile(join(__dirname, '../dist/index.html'));
  108. }
  109. // 处理外部链接
  110. mainWindow.webContents.setWindowOpenHandler(({ url }: { url: string }) => {
  111. shell.openExternal(url);
  112. return { action: 'deny' };
  113. });
  114. // 关闭按钮默认最小化到托盘
  115. mainWindow.on('close', (event: Event) => {
  116. if (!isQuitting) {
  117. event.preventDefault();
  118. mainWindow?.hide();
  119. // 显示托盘通知(仅首次)
  120. if (tray && !app.isPackaged) {
  121. // 开发模式下可以显示通知
  122. }
  123. }
  124. });
  125. mainWindow.on('closed', () => {
  126. mainWindow = null;
  127. });
  128. }
  129. // 单实例锁定
  130. const gotTheLock = app.requestSingleInstanceLock();
  131. if (!gotTheLock) {
  132. app.quit();
  133. } else {
  134. app.on('second-instance', () => {
  135. if (mainWindow) {
  136. mainWindow.show();
  137. if (mainWindow.isMinimized()) mainWindow.restore();
  138. mainWindow.focus();
  139. }
  140. });
  141. app.whenReady().then(() => {
  142. createTray();
  143. createWindow();
  144. // 配置 webview session,允许第三方 cookies 和跨域请求
  145. setupWebviewSessions();
  146. app.on('activate', () => {
  147. if (BrowserWindow.getAllWindows().length === 0) {
  148. createWindow();
  149. } else if (mainWindow) {
  150. mainWindow.show();
  151. }
  152. });
  153. });
  154. }
  155. // 配置 webview sessions
  156. function setupWebviewSessions() {
  157. // 监听新的 webContents 创建
  158. app.on('web-contents-created', (_event: unknown, contents: typeof webContents.prototype) => {
  159. // 为 webview 类型的 webContents 配置
  160. if (contents.getType() === 'webview') {
  161. // 设置 User-Agent(模拟 Chrome 浏览器)
  162. contents.setUserAgent(
  163. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  164. );
  165. // 拦截自定义协议链接(如 bitbrowser://)的导航
  166. contents.on('will-navigate', (event: Event, url: string) => {
  167. if (!isAllowedUrl(url)) {
  168. console.log('[WebView] 阻止导航到自定义协议:', url);
  169. event.preventDefault();
  170. }
  171. });
  172. // 拦截新窗口打开(包括自定义协议)
  173. contents.setWindowOpenHandler(({ url }: { url: string }) => {
  174. if (!isAllowedUrl(url)) {
  175. console.log('[WebView] 阻止打开自定义协议窗口:', url);
  176. return { action: 'deny' };
  177. }
  178. // 对于正常的 http/https 链接,在当前 webview 中打开
  179. console.log('[WebView] 拦截新窗口,在当前页面打开:', url);
  180. contents.loadURL(url);
  181. return { action: 'deny' };
  182. });
  183. // 允许所有的权限请求(如摄像头、地理位置等)
  184. contents.session.setPermissionRequestHandler((_webContents: unknown, permission: string, callback: (granted: boolean) => void) => {
  185. // 允许所有权限请求
  186. callback(true);
  187. });
  188. // 配置 webRequest 修改请求头,移除可能暴露 Electron 的特征
  189. contents.session.webRequest.onBeforeSendHeaders((details: { requestHeaders: Record<string, string> }, callback: (response: { requestHeaders: Record<string, string> }) => void) => {
  190. // 移除可能暴露 Electron 的请求头
  191. delete details.requestHeaders['X-DevTools-Emulate-Network-Conditions-Client-Id'];
  192. // 确保有正常的 Origin 和 Referer
  193. if (!details.requestHeaders['Origin'] && !details.requestHeaders['origin']) {
  194. // 不添加 Origin,让浏览器自动处理
  195. }
  196. callback({ requestHeaders: details.requestHeaders });
  197. });
  198. }
  199. });
  200. }
  201. // 检查 URL 是否是允许的协议
  202. function isAllowedUrl(url: string): boolean {
  203. if (!url) return false;
  204. const lowerUrl = url.toLowerCase();
  205. return lowerUrl.startsWith('http://') ||
  206. lowerUrl.startsWith('https://') ||
  207. lowerUrl.startsWith('about:') ||
  208. lowerUrl.startsWith('data:');
  209. }
  210. // 阻止默认的 window-all-closed 行为,保持托盘运行
  211. app.on('window-all-closed', () => {
  212. // 不退出应用,保持托盘运行
  213. // 只有在 isQuitting 为 true 时才真正退出
  214. });
  215. // 应用退出前清理托盘
  216. app.on('before-quit', () => {
  217. isQuitting = true;
  218. });
  219. app.on('quit', () => {
  220. if (tray) {
  221. tray.destroy();
  222. tray = null;
  223. }
  224. });
  225. // IPC 处理
  226. ipcMain.handle('get-app-version', () => {
  227. return app.getVersion();
  228. });
  229. ipcMain.handle('get-platform', () => {
  230. return process.platform;
  231. });
  232. // 窗口控制
  233. ipcMain.on('window-minimize', () => {
  234. mainWindow?.minimize();
  235. });
  236. ipcMain.on('window-maximize', () => {
  237. if (mainWindow?.isMaximized()) {
  238. mainWindow.unmaximize();
  239. } else {
  240. mainWindow?.maximize();
  241. }
  242. });
  243. // 关闭窗口(最小化到托盘)
  244. ipcMain.on('window-close', () => {
  245. mainWindow?.hide();
  246. });
  247. // 真正退出应用
  248. ipcMain.on('app-quit', () => {
  249. isQuitting = true;
  250. app.quit();
  251. });
  252. // 获取窗口最大化状态
  253. ipcMain.handle('window-is-maximized', () => {
  254. return mainWindow?.isMaximized() || false;
  255. });
  256. // 监听窗口最大化/还原事件,通知渲染进程
  257. function setupWindowEvents() {
  258. mainWindow?.on('maximize', () => {
  259. mainWindow?.webContents.send('window-maximized', true);
  260. });
  261. mainWindow?.on('unmaximize', () => {
  262. mainWindow?.webContents.send('window-maximized', false);
  263. });
  264. }
  265. // 弹窗打开平台后台(独立窗口,不嵌入;用于实验,可回归为嵌入)
  266. ipcMain.handle('open-backend-external', async (_event: unknown, payload: { url: string; cookieData?: string; title?: string }) => {
  267. const { url, cookieData, title } = payload || {};
  268. if (!url || typeof url !== 'string') return;
  269. const partition = 'persist:backend-popup-' + Date.now();
  270. const ses = session.fromPartition(partition);
  271. if (cookieData && typeof cookieData === 'string' && cookieData.trim()) {
  272. const raw = cookieData.trim();
  273. let cookiesToSet: Array<{ name: string; value: string; domain?: string; path?: string }> = [];
  274. try {
  275. if (raw.startsWith('[') || raw.startsWith('{')) {
  276. const parsed = JSON.parse(raw);
  277. const arr = Array.isArray(parsed) ? parsed : (parsed?.cookies || []);
  278. cookiesToSet = arr.map((c: { name?: string; value?: string; domain?: string; path?: string }) => ({
  279. name: String(c?.name ?? '').trim(),
  280. value: String(c?.value ?? '').trim(),
  281. domain: c?.domain ? String(c.domain) : undefined,
  282. path: c?.path ? String(c.path) : '/',
  283. })).filter((c: { name: string }) => c.name);
  284. } else {
  285. raw.split(';').forEach((p: string) => {
  286. const idx = p.indexOf('=');
  287. if (idx > 0) {
  288. const name = p.slice(0, idx).trim();
  289. const value = p.slice(idx + 1).trim();
  290. if (name) cookiesToSet.push({ name, value, path: '/' });
  291. }
  292. });
  293. }
  294. } catch (e) {
  295. console.warn('[open-backend-external] 解析 cookie 失败', e);
  296. }
  297. const origin = new URL(url).origin;
  298. const hostname = new URL(url).hostname;
  299. const defaultDomain = hostname.startsWith('www.') ? hostname.slice(4) : hostname;
  300. const domainWithDot = defaultDomain.includes('.') ? '.' + defaultDomain.split('.').slice(-2).join('.') : undefined;
  301. for (const c of cookiesToSet) {
  302. try {
  303. await ses.cookies.set({
  304. url: origin + '/',
  305. name: c.name,
  306. value: c.value,
  307. domain: c.domain || domainWithDot || hostname,
  308. path: c.path || '/',
  309. });
  310. } catch (err) {
  311. console.warn('[open-backend-external] 设置 cookie 失败', c.name, err);
  312. }
  313. }
  314. }
  315. const win = new BrowserWindow({
  316. width: 1280,
  317. height: 800,
  318. title: title || '平台后台',
  319. icon: getIconPath(),
  320. webPreferences: {
  321. session: ses,
  322. nodeIntegration: false,
  323. contextIsolation: true,
  324. },
  325. show: false,
  326. });
  327. win.once('ready-to-show', () => {
  328. win.show();
  329. });
  330. await win.loadURL(url);
  331. return { ok: true };
  332. });
  333. // 获取 webview 的 cookies
  334. ipcMain.handle('get-webview-cookies', async (_event: unknown, partition: string, url: string) => {
  335. try {
  336. const ses = session.fromPartition(partition);
  337. const cookies = await ses.cookies.get({ url });
  338. return cookies;
  339. } catch (error) {
  340. console.error('获取 cookies 失败:', error);
  341. return [];
  342. }
  343. });
  344. // 清除 webview 的 cookies
  345. ipcMain.handle('clear-webview-cookies', async (_event: unknown, partition: string) => {
  346. try {
  347. const ses = session.fromPartition(partition);
  348. await ses.clearStorageData({ storages: ['cookies'] });
  349. return true;
  350. } catch (error) {
  351. console.error('清除 cookies 失败:', error);
  352. return false;
  353. }
  354. });
  355. // 设置 webview 的 cookies
  356. ipcMain.handle('set-webview-cookies', async (_event: unknown, partition: string, cookies: Electron.CookiesSetDetails[]) => {
  357. try {
  358. console.log(`[Main] 设置 webview cookies, partition=${partition}, count=${cookies.length}`);
  359. const ses = session.fromPartition(partition);
  360. // 逐个设置 cookie
  361. let successCount = 0;
  362. for (const cookie of cookies) {
  363. try {
  364. // 确保 Cookie 格式正确
  365. const cookieToSet: Electron.CookiesSetDetails = {
  366. url: cookie.url,
  367. name: cookie.name,
  368. value: cookie.value,
  369. domain: cookie.domain,
  370. path: cookie.path || '/',
  371. };
  372. // 可选字段
  373. if (cookie.expirationDate) {
  374. cookieToSet.expirationDate = cookie.expirationDate;
  375. }
  376. if (cookie.httpOnly !== undefined) {
  377. cookieToSet.httpOnly = cookie.httpOnly;
  378. }
  379. if (cookie.secure !== undefined) {
  380. cookieToSet.secure = cookie.secure;
  381. }
  382. if (cookie.sameSite) {
  383. cookieToSet.sameSite = cookie.sameSite as 'no_restriction' | 'lax' | 'strict';
  384. }
  385. await ses.cookies.set(cookieToSet);
  386. successCount++;
  387. // 记录关键 Cookie
  388. if (cookie.name === 'BDUSS' || cookie.name === 'STOKEN' || cookie.name === 'sessionid') {
  389. console.log(`[Main] 成功设置关键 Cookie: ${cookie.name}, domain: ${cookie.domain}`);
  390. }
  391. } catch (error) {
  392. console.error(`[Main] 设置 cookie 失败 (${cookie.name}):`, error);
  393. }
  394. }
  395. console.log(`[Main] 成功设置 ${successCount}/${cookies.length} 个 cookies`);
  396. // 验证 Cookie 是否真的设置成功
  397. try {
  398. const setCookies = await ses.cookies.get({ domain: '.baidu.com' });
  399. console.log(`[Main] 验证:当前 session 中有 ${setCookies.length} 个百度 Cookie`);
  400. const keyNames = setCookies.slice(0, 5).map(c => c.name).join(', ');
  401. console.log(`[Main] 关键 Cookie 名称: ${keyNames}`);
  402. } catch (verifyError) {
  403. console.error('[Main] 验证 Cookie 失败:', verifyError);
  404. }
  405. return true;
  406. } catch (error) {
  407. console.error('[Main] 设置 cookies 失败:', error);
  408. return false;
  409. }
  410. });
  411. // 截取 webview 页面截图(用于 AI 分析)
  412. ipcMain.handle('capture-webview-page', async (_event: unknown, webContentsId: number) => {
  413. try {
  414. const wc = webContents.fromId(webContentsId);
  415. if (!wc) {
  416. console.error('找不到 webContents:', webContentsId);
  417. return null;
  418. }
  419. const image = await wc.capturePage();
  420. if (!image || image.isEmpty()) {
  421. console.warn('截图为空');
  422. return null;
  423. }
  424. // 转换为 JPEG 格式的 Base64
  425. const buffer = image.toJPEG(80);
  426. return buffer.toString('base64');
  427. } catch (error) {
  428. console.error('截图失败:', error);
  429. return null;
  430. }
  431. });
  432. // 向 webview 发送鼠标点击事件
  433. ipcMain.handle('webview-send-mouse-click', async (_event: unknown, webContentsId: number, x: number, y: number) => {
  434. try {
  435. const wc = webContents.fromId(webContentsId);
  436. if (!wc) {
  437. console.error('找不到 webContents:', webContentsId);
  438. return false;
  439. }
  440. // 发送鼠标移动事件
  441. wc.sendInputEvent({
  442. type: 'mouseMove',
  443. x: Math.round(x),
  444. y: Math.round(y),
  445. });
  446. // 短暂延迟后发送点击事件
  447. await new Promise(resolve => setTimeout(resolve, 50));
  448. // 发送鼠标按下事件
  449. wc.sendInputEvent({
  450. type: 'mouseDown',
  451. x: Math.round(x),
  452. y: Math.round(y),
  453. button: 'left',
  454. clickCount: 1,
  455. });
  456. // 短暂延迟后发送鼠标抬起事件
  457. await new Promise(resolve => setTimeout(resolve, 50));
  458. wc.sendInputEvent({
  459. type: 'mouseUp',
  460. x: Math.round(x),
  461. y: Math.round(y),
  462. button: 'left',
  463. clickCount: 1,
  464. });
  465. console.log(`[webview-send-mouse-click] Clicked at (${x}, ${y})`);
  466. return true;
  467. } catch (error) {
  468. console.error('发送点击事件失败:', error);
  469. return false;
  470. }
  471. });
  472. // 向 webview 发送键盘输入事件
  473. ipcMain.handle('webview-send-text-input', async (_event: unknown, webContentsId: number, text: string) => {
  474. try {
  475. const wc = webContents.fromId(webContentsId);
  476. if (!wc) {
  477. console.error('找不到 webContents:', webContentsId);
  478. return false;
  479. }
  480. // 逐字符输入
  481. for (const char of text) {
  482. wc.sendInputEvent({
  483. type: 'char',
  484. keyCode: char,
  485. });
  486. await new Promise(resolve => setTimeout(resolve, 30));
  487. }
  488. console.log(`[webview-send-text-input] Typed: ${text}`);
  489. return true;
  490. } catch (error) {
  491. console.error('发送输入事件失败:', error);
  492. return false;
  493. }
  494. });
  495. // 获取 webview 页面元素位置
  496. ipcMain.handle('webview-get-element-position', async (_event: unknown, webContentsId: number, selector: string) => {
  497. try {
  498. const wc = webContents.fromId(webContentsId);
  499. if (!wc) {
  500. console.error('找不到 webContents:', webContentsId);
  501. return null;
  502. }
  503. const result = await wc.executeJavaScript(`
  504. (function() {
  505. const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
  506. if (!el) return null;
  507. const rect = el.getBoundingClientRect();
  508. return {
  509. x: rect.left + rect.width / 2,
  510. y: rect.top + rect.height / 2,
  511. width: rect.width,
  512. height: rect.height
  513. };
  514. })()
  515. `);
  516. return result;
  517. } catch (error) {
  518. console.error('获取元素位置失败:', error);
  519. return null;
  520. }
  521. });
  522. // 通过文本内容查找并点击元素
  523. ipcMain.handle('webview-click-by-text', async (_event: unknown, webContentsId: number, text: string) => {
  524. try {
  525. const wc = webContents.fromId(webContentsId);
  526. if (!wc) {
  527. console.error('找不到 webContents:', webContentsId);
  528. return false;
  529. }
  530. // 查找包含指定文本的可点击元素的位置
  531. const position = await wc.executeJavaScript(`
  532. (function() {
  533. const searchText = '${text.replace(/'/g, "\\'")}';
  534. // 查找可点击元素
  535. const clickables = document.querySelectorAll('a, button, [role="button"], [onclick], input[type="submit"], input[type="button"]');
  536. for (const el of clickables) {
  537. if (el.textContent?.includes(searchText) || el.getAttribute('aria-label')?.includes(searchText) || el.getAttribute('title')?.includes(searchText)) {
  538. const rect = el.getBoundingClientRect();
  539. if (rect.width > 0 && rect.height > 0) {
  540. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  541. }
  542. }
  543. }
  544. // 查找所有包含文本的元素
  545. const allElements = document.querySelectorAll('*');
  546. for (const el of allElements) {
  547. const text = el.innerText?.trim();
  548. if (text && text.length < 100 && text.includes(searchText)) {
  549. const rect = el.getBoundingClientRect();
  550. if (rect.width > 0 && rect.height > 0 && rect.width < 500) {
  551. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  552. }
  553. }
  554. }
  555. return null;
  556. })()
  557. `);
  558. if (!position) {
  559. console.warn(`[webview-click-by-text] 未找到包含 "${text}" 的元素`);
  560. return false;
  561. }
  562. // 发送点击事件
  563. wc.sendInputEvent({ type: 'mouseMove', x: Math.round(position.x), y: Math.round(position.y) });
  564. await new Promise(resolve => setTimeout(resolve, 50));
  565. wc.sendInputEvent({ type: 'mouseDown', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  566. await new Promise(resolve => setTimeout(resolve, 50));
  567. wc.sendInputEvent({ type: 'mouseUp', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  568. console.log(`[webview-click-by-text] Clicked "${text}" at (${position.x}, ${position.y})`);
  569. return true;
  570. } catch (error) {
  571. console.error('通过文本点击失败:', error);
  572. return false;
  573. }
  574. });
  575. // ========== CDP 网络拦截功能 ==========
  576. // 存储每个 webContents 的网络拦截配置
  577. const networkInterceptors: Map<number, {
  578. patterns: Array<{match: string, key: string}>;
  579. pendingRequests: Map<string, {url: string, timestamp: number}>;
  580. }> = new Map();
  581. // 启用 CDP 网络拦截
  582. ipcMain.handle('enable-network-intercept', async (_event: unknown, webContentsId: number, patterns: Array<{match: string, key: string}>) => {
  583. try {
  584. const wc = webContents.fromId(webContentsId);
  585. if (!wc) {
  586. console.error('[CDP] 找不到 webContents:', webContentsId);
  587. return false;
  588. }
  589. // 如果已经有拦截器,先清理
  590. if (networkInterceptors.has(webContentsId)) {
  591. try {
  592. wc.debugger.detach();
  593. } catch (e) {
  594. // 忽略
  595. }
  596. }
  597. // 存储配置
  598. networkInterceptors.set(webContentsId, {
  599. patterns,
  600. pendingRequests: new Map()
  601. });
  602. // 附加调试器
  603. try {
  604. wc.debugger.attach('1.3');
  605. } catch (err: unknown) {
  606. const error = err as Error;
  607. if (!error.message?.includes('Already attached')) {
  608. throw err;
  609. }
  610. }
  611. // 启用网络监听
  612. await wc.debugger.sendCommand('Network.enable');
  613. // 监听网络响应
  614. wc.debugger.on('message', async (_e: unknown, method: string, params: {
  615. requestId?: string;
  616. response?: { url?: string; status?: number; mimeType?: string };
  617. encodedDataLength?: number;
  618. }) => {
  619. const config = networkInterceptors.get(webContentsId);
  620. if (!config) return;
  621. if (method === 'Network.responseReceived') {
  622. const { requestId, response } = params;
  623. if (!requestId || !response?.url) return;
  624. // 调试:打印百家号相关的所有 API 请求
  625. if (response.url.includes('baijiahao.baidu.com')) {
  626. if (response.url.includes('/pcui/') || response.url.includes('/article')) {
  627. console.log(`[CDP DEBUG] 百家号 API: ${response.url}`);
  628. }
  629. }
  630. // 检查是否匹配我们关注的 API
  631. for (const pattern of config.patterns) {
  632. if (response.url.includes(pattern.match)) {
  633. // 记录请求,等待响应完成
  634. config.pendingRequests.set(requestId, {
  635. url: response.url,
  636. timestamp: Date.now()
  637. });
  638. console.log(`[CDP] 匹配到 API: ${pattern.key} - ${response.url}`);
  639. break;
  640. }
  641. }
  642. }
  643. if (method === 'Network.loadingFinished') {
  644. const { requestId } = params;
  645. if (!requestId) return;
  646. const pending = config.pendingRequests.get(requestId);
  647. if (!pending) return;
  648. config.pendingRequests.delete(requestId);
  649. try {
  650. // 获取响应体
  651. const result = await wc.debugger.sendCommand('Network.getResponseBody', { requestId }) as { body: string; base64Encoded: boolean };
  652. let body = result.body;
  653. // 如果是 base64 编码,解码
  654. if (result.base64Encoded) {
  655. body = Buffer.from(body, 'base64').toString('utf8');
  656. }
  657. // 解析 JSON
  658. const data = JSON.parse(body);
  659. // 找到匹配的 key
  660. let matchedKey = '';
  661. for (const pattern of config.patterns) {
  662. if (pending.url.includes(pattern.match)) {
  663. matchedKey = pattern.key;
  664. break;
  665. }
  666. }
  667. if (matchedKey) {
  668. console.log(`[CDP] 获取到响应: ${matchedKey}`, JSON.stringify(data).substring(0, 200));
  669. // 发送到渲染进程
  670. mainWindow?.webContents.send('network-intercept-data', {
  671. webContentsId,
  672. key: matchedKey,
  673. url: pending.url,
  674. data
  675. });
  676. }
  677. } catch (err) {
  678. console.warn(`[CDP] 获取响应体失败:`, err);
  679. }
  680. }
  681. });
  682. console.log(`[CDP] 已启用网络拦截,webContentsId: ${webContentsId}, patterns:`, patterns.map(p => p.key));
  683. return true;
  684. } catch (error) {
  685. console.error('[CDP] 启用网络拦截失败:', error);
  686. return false;
  687. }
  688. });
  689. // 禁用 CDP 网络拦截
  690. ipcMain.handle('disable-network-intercept', async (_event: unknown, webContentsId: number) => {
  691. try {
  692. const wc = webContents.fromId(webContentsId);
  693. if (wc) {
  694. try {
  695. wc.debugger.detach();
  696. } catch (e) {
  697. // 忽略
  698. }
  699. }
  700. networkInterceptors.delete(webContentsId);
  701. console.log(`[CDP] 已禁用网络拦截,webContentsId: ${webContentsId}`);
  702. return true;
  703. } catch (error) {
  704. console.error('[CDP] 禁用网络拦截失败:', error);
  705. return false;
  706. }
  707. });
  708. // 更新网络拦截的 patterns
  709. ipcMain.handle('update-network-patterns', async (_event: unknown, webContentsId: number, patterns: Array<{match: string, key: string}>) => {
  710. const config = networkInterceptors.get(webContentsId);
  711. if (config) {
  712. config.patterns = patterns;
  713. console.log(`[CDP] 已更新 patterns,webContentsId: ${webContentsId}`);
  714. return true;
  715. }
  716. return false;
  717. });