main.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. // 获取 webview 的 cookies
  266. ipcMain.handle('get-webview-cookies', async (_event: unknown, partition: string, url: string) => {
  267. try {
  268. const ses = session.fromPartition(partition);
  269. const cookies = await ses.cookies.get({ url });
  270. return cookies;
  271. } catch (error) {
  272. console.error('获取 cookies 失败:', error);
  273. return [];
  274. }
  275. });
  276. // 清除 webview 的 cookies
  277. ipcMain.handle('clear-webview-cookies', async (_event: unknown, partition: string) => {
  278. try {
  279. const ses = session.fromPartition(partition);
  280. await ses.clearStorageData({ storages: ['cookies'] });
  281. return true;
  282. } catch (error) {
  283. console.error('清除 cookies 失败:', error);
  284. return false;
  285. }
  286. });
  287. // 设置 webview 的 cookies
  288. ipcMain.handle('set-webview-cookies', async (_event: unknown, partition: string, cookies: Electron.CookiesSetDetails[]) => {
  289. try {
  290. const ses = session.fromPartition(partition);
  291. // 逐个设置 cookie
  292. for (const cookie of cookies) {
  293. await ses.cookies.set(cookie);
  294. }
  295. return true;
  296. } catch (error) {
  297. console.error('设置 cookies 失败:', error);
  298. return false;
  299. }
  300. });
  301. // 截取 webview 页面截图(用于 AI 分析)
  302. ipcMain.handle('capture-webview-page', async (_event: unknown, webContentsId: number) => {
  303. try {
  304. const wc = webContents.fromId(webContentsId);
  305. if (!wc) {
  306. console.error('找不到 webContents:', webContentsId);
  307. return null;
  308. }
  309. const image = await wc.capturePage();
  310. if (!image || image.isEmpty()) {
  311. console.warn('截图为空');
  312. return null;
  313. }
  314. // 转换为 JPEG 格式的 Base64
  315. const buffer = image.toJPEG(80);
  316. return buffer.toString('base64');
  317. } catch (error) {
  318. console.error('截图失败:', error);
  319. return null;
  320. }
  321. });
  322. // 向 webview 发送鼠标点击事件
  323. ipcMain.handle('webview-send-mouse-click', async (_event: unknown, webContentsId: number, x: number, y: number) => {
  324. try {
  325. const wc = webContents.fromId(webContentsId);
  326. if (!wc) {
  327. console.error('找不到 webContents:', webContentsId);
  328. return false;
  329. }
  330. // 发送鼠标移动事件
  331. wc.sendInputEvent({
  332. type: 'mouseMove',
  333. x: Math.round(x),
  334. y: Math.round(y),
  335. });
  336. // 短暂延迟后发送点击事件
  337. await new Promise(resolve => setTimeout(resolve, 50));
  338. // 发送鼠标按下事件
  339. wc.sendInputEvent({
  340. type: 'mouseDown',
  341. x: Math.round(x),
  342. y: Math.round(y),
  343. button: 'left',
  344. clickCount: 1,
  345. });
  346. // 短暂延迟后发送鼠标抬起事件
  347. await new Promise(resolve => setTimeout(resolve, 50));
  348. wc.sendInputEvent({
  349. type: 'mouseUp',
  350. x: Math.round(x),
  351. y: Math.round(y),
  352. button: 'left',
  353. clickCount: 1,
  354. });
  355. console.log(`[webview-send-mouse-click] Clicked at (${x}, ${y})`);
  356. return true;
  357. } catch (error) {
  358. console.error('发送点击事件失败:', error);
  359. return false;
  360. }
  361. });
  362. // 向 webview 发送键盘输入事件
  363. ipcMain.handle('webview-send-text-input', async (_event: unknown, webContentsId: number, text: string) => {
  364. try {
  365. const wc = webContents.fromId(webContentsId);
  366. if (!wc) {
  367. console.error('找不到 webContents:', webContentsId);
  368. return false;
  369. }
  370. // 逐字符输入
  371. for (const char of text) {
  372. wc.sendInputEvent({
  373. type: 'char',
  374. keyCode: char,
  375. });
  376. await new Promise(resolve => setTimeout(resolve, 30));
  377. }
  378. console.log(`[webview-send-text-input] Typed: ${text}`);
  379. return true;
  380. } catch (error) {
  381. console.error('发送输入事件失败:', error);
  382. return false;
  383. }
  384. });
  385. // 获取 webview 页面元素位置
  386. ipcMain.handle('webview-get-element-position', async (_event: unknown, webContentsId: number, selector: string) => {
  387. try {
  388. const wc = webContents.fromId(webContentsId);
  389. if (!wc) {
  390. console.error('找不到 webContents:', webContentsId);
  391. return null;
  392. }
  393. const result = await wc.executeJavaScript(`
  394. (function() {
  395. const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
  396. if (!el) return null;
  397. const rect = el.getBoundingClientRect();
  398. return {
  399. x: rect.left + rect.width / 2,
  400. y: rect.top + rect.height / 2,
  401. width: rect.width,
  402. height: rect.height
  403. };
  404. })()
  405. `);
  406. return result;
  407. } catch (error) {
  408. console.error('获取元素位置失败:', error);
  409. return null;
  410. }
  411. });
  412. // 通过文本内容查找并点击元素
  413. ipcMain.handle('webview-click-by-text', async (_event: unknown, webContentsId: number, text: string) => {
  414. try {
  415. const wc = webContents.fromId(webContentsId);
  416. if (!wc) {
  417. console.error('找不到 webContents:', webContentsId);
  418. return false;
  419. }
  420. // 查找包含指定文本的可点击元素的位置
  421. const position = await wc.executeJavaScript(`
  422. (function() {
  423. const searchText = '${text.replace(/'/g, "\\'")}';
  424. // 查找可点击元素
  425. const clickables = document.querySelectorAll('a, button, [role="button"], [onclick], input[type="submit"], input[type="button"]');
  426. for (const el of clickables) {
  427. if (el.textContent?.includes(searchText) || el.getAttribute('aria-label')?.includes(searchText) || el.getAttribute('title')?.includes(searchText)) {
  428. const rect = el.getBoundingClientRect();
  429. if (rect.width > 0 && rect.height > 0) {
  430. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  431. }
  432. }
  433. }
  434. // 查找所有包含文本的元素
  435. const allElements = document.querySelectorAll('*');
  436. for (const el of allElements) {
  437. const text = el.innerText?.trim();
  438. if (text && text.length < 100 && text.includes(searchText)) {
  439. const rect = el.getBoundingClientRect();
  440. if (rect.width > 0 && rect.height > 0 && rect.width < 500) {
  441. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  442. }
  443. }
  444. }
  445. return null;
  446. })()
  447. `);
  448. if (!position) {
  449. console.warn(`[webview-click-by-text] 未找到包含 "${text}" 的元素`);
  450. return false;
  451. }
  452. // 发送点击事件
  453. wc.sendInputEvent({ type: 'mouseMove', x: Math.round(position.x), y: Math.round(position.y) });
  454. await new Promise(resolve => setTimeout(resolve, 50));
  455. wc.sendInputEvent({ type: 'mouseDown', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  456. await new Promise(resolve => setTimeout(resolve, 50));
  457. wc.sendInputEvent({ type: 'mouseUp', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  458. console.log(`[webview-click-by-text] Clicked "${text}" at (${position.x}, ${position.y})`);
  459. return true;
  460. } catch (error) {
  461. console.error('通过文本点击失败:', error);
  462. return false;
  463. }
  464. });
  465. // ========== CDP 网络拦截功能 ==========
  466. // 存储每个 webContents 的网络拦截配置
  467. const networkInterceptors: Map<number, {
  468. patterns: Array<{match: string, key: string}>;
  469. pendingRequests: Map<string, {url: string, timestamp: number}>;
  470. }> = new Map();
  471. // 启用 CDP 网络拦截
  472. ipcMain.handle('enable-network-intercept', async (_event: unknown, webContentsId: number, patterns: Array<{match: string, key: string}>) => {
  473. try {
  474. const wc = webContents.fromId(webContentsId);
  475. if (!wc) {
  476. console.error('[CDP] 找不到 webContents:', webContentsId);
  477. return false;
  478. }
  479. // 如果已经有拦截器,先清理
  480. if (networkInterceptors.has(webContentsId)) {
  481. try {
  482. wc.debugger.detach();
  483. } catch (e) {
  484. // 忽略
  485. }
  486. }
  487. // 存储配置
  488. networkInterceptors.set(webContentsId, {
  489. patterns,
  490. pendingRequests: new Map()
  491. });
  492. // 附加调试器
  493. try {
  494. wc.debugger.attach('1.3');
  495. } catch (err: unknown) {
  496. const error = err as Error;
  497. if (!error.message?.includes('Already attached')) {
  498. throw err;
  499. }
  500. }
  501. // 启用网络监听
  502. await wc.debugger.sendCommand('Network.enable');
  503. // 监听网络响应
  504. wc.debugger.on('message', async (_e: unknown, method: string, params: {
  505. requestId?: string;
  506. response?: { url?: string; status?: number; mimeType?: string };
  507. encodedDataLength?: number;
  508. }) => {
  509. const config = networkInterceptors.get(webContentsId);
  510. if (!config) return;
  511. if (method === 'Network.responseReceived') {
  512. const { requestId, response } = params;
  513. if (!requestId || !response?.url) return;
  514. // 调试:打印百家号相关的所有 API 请求
  515. if (response.url.includes('baijiahao.baidu.com')) {
  516. if (response.url.includes('/pcui/') || response.url.includes('/article')) {
  517. console.log(`[CDP DEBUG] 百家号 API: ${response.url}`);
  518. }
  519. }
  520. // 检查是否匹配我们关注的 API
  521. for (const pattern of config.patterns) {
  522. if (response.url.includes(pattern.match)) {
  523. // 记录请求,等待响应完成
  524. config.pendingRequests.set(requestId, {
  525. url: response.url,
  526. timestamp: Date.now()
  527. });
  528. console.log(`[CDP] 匹配到 API: ${pattern.key} - ${response.url}`);
  529. break;
  530. }
  531. }
  532. }
  533. if (method === 'Network.loadingFinished') {
  534. const { requestId } = params;
  535. if (!requestId) return;
  536. const pending = config.pendingRequests.get(requestId);
  537. if (!pending) return;
  538. config.pendingRequests.delete(requestId);
  539. try {
  540. // 获取响应体
  541. const result = await wc.debugger.sendCommand('Network.getResponseBody', { requestId }) as { body: string; base64Encoded: boolean };
  542. let body = result.body;
  543. // 如果是 base64 编码,解码
  544. if (result.base64Encoded) {
  545. body = Buffer.from(body, 'base64').toString('utf8');
  546. }
  547. // 解析 JSON
  548. const data = JSON.parse(body);
  549. // 找到匹配的 key
  550. let matchedKey = '';
  551. for (const pattern of config.patterns) {
  552. if (pending.url.includes(pattern.match)) {
  553. matchedKey = pattern.key;
  554. break;
  555. }
  556. }
  557. if (matchedKey) {
  558. console.log(`[CDP] 获取到响应: ${matchedKey}`, JSON.stringify(data).substring(0, 200));
  559. // 发送到渲染进程
  560. mainWindow?.webContents.send('network-intercept-data', {
  561. webContentsId,
  562. key: matchedKey,
  563. url: pending.url,
  564. data
  565. });
  566. }
  567. } catch (err) {
  568. console.warn(`[CDP] 获取响应体失败:`, err);
  569. }
  570. }
  571. });
  572. console.log(`[CDP] 已启用网络拦截,webContentsId: ${webContentsId}, patterns:`, patterns.map(p => p.key));
  573. return true;
  574. } catch (error) {
  575. console.error('[CDP] 启用网络拦截失败:', error);
  576. return false;
  577. }
  578. });
  579. // 禁用 CDP 网络拦截
  580. ipcMain.handle('disable-network-intercept', async (_event: unknown, webContentsId: number) => {
  581. try {
  582. const wc = webContents.fromId(webContentsId);
  583. if (wc) {
  584. try {
  585. wc.debugger.detach();
  586. } catch (e) {
  587. // 忽略
  588. }
  589. }
  590. networkInterceptors.delete(webContentsId);
  591. console.log(`[CDP] 已禁用网络拦截,webContentsId: ${webContentsId}`);
  592. return true;
  593. } catch (error) {
  594. console.error('[CDP] 禁用网络拦截失败:', error);
  595. return false;
  596. }
  597. });
  598. // 更新网络拦截的 patterns
  599. ipcMain.handle('update-network-patterns', async (_event: unknown, webContentsId: number, patterns: Array<{match: string, key: string}>) => {
  600. const config = networkInterceptors.get(webContentsId);
  601. if (config) {
  602. config.patterns = patterns;
  603. console.log(`[CDP] 已更新 patterns,webContentsId: ${webContentsId}`);
  604. return true;
  605. }
  606. return false;
  607. });