main.ts 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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. const http = require('http');
  6. const https = require('https');
  7. const os = require('os');
  8. import { startLocalServices, stopLocalServices, getServiceStatus, LOCAL_NODE_URL, LOCAL_PYTHON_URL, getLogPath } from './local-services';
  9. let mainWindow: typeof BrowserWindow.prototype | null = null;
  10. // ========== 内存监控 ==========
  11. const MEMORY_THRESHOLD_MB = 512; // 超过 512MB 触发警告 / 清理
  12. let lastMemoryReport = 0;
  13. function getMemoryUsageMB(): number {
  14. const used = process.memoryUsage();
  15. return Math.round(used.heapUsed / 1024 / 1024);
  16. }
  17. function logMemory(prefix: string): void {
  18. const used = getMemoryUsageMB();
  19. const total = Math.round(os.totalmem() / 1024 / 1024);
  20. const free = Math.round(os.freemem() / 1024 / 1024);
  21. const usagePct = Math.round((used / total) * 100);
  22. console.log(`[MEM] ${prefix} heap=${used}MB total=${total}MB free=${free}MB usage=${usagePct}%`);
  23. }
  24. function monitorMemory(): void {
  25. const used = getMemoryUsageMB();
  26. const now = Date.now();
  27. // 每 60 秒报告一次
  28. if (now - lastMemoryReport > 60000) {
  29. logMemory('Electron');
  30. lastMemoryReport = now;
  31. }
  32. // 超过阈值,触发 GC 并报告
  33. if (used > MEMORY_THRESHOLD_MB) {
  34. console.warn(`[MEM] Memory high (${used}MB), triggering GC...`);
  35. if (global.gc) {
  36. global.gc();
  37. }
  38. // 关闭多余的 webContents
  39. if (mainWindow?.webContents) {
  40. const wc = mainWindow.webContents;
  41. // 尝试清理 devtools extension
  42. try {
  43. session.defaultSession?.webContents.forEach(w => {
  44. if (w !== wc && !w.isDestroyed()) {
  45. console.warn('[MEM] Closing idle webContents');
  46. w.close();
  47. }
  48. });
  49. } catch {}
  50. }
  51. }
  52. }
  53. // 启动内存监控
  54. setInterval(monitorMemory, 30000);
  55. let tray: typeof Tray.prototype | null = null;
  56. let isQuitting = false;
  57. const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL;
  58. function setupCertificateBypass() {
  59. app.on('certificate-error', (event: Event, _webContents: typeof webContents.prototype, _url: string, _error: string, _certificate: unknown, callback: (isTrusted: boolean) => void) => {
  60. event.preventDefault();
  61. callback(true);
  62. });
  63. }
  64. function setupCorsBypassForApiRequests() {
  65. const ses = session.defaultSession;
  66. if (!ses) return;
  67. ses.webRequest.onHeadersReceived((details: { url: string; responseHeaders?: Record<string, string[] | string> }, callback: (response: { responseHeaders: Record<string, string[] | string> }) => void) => {
  68. const url = String(details.url || '');
  69. const isHttp = url.startsWith('http://') || url.startsWith('https://');
  70. const isApiLike = url.includes('/api/') || url.includes('/uploads/');
  71. if (!isHttp || !isApiLike) {
  72. callback({ responseHeaders: details.responseHeaders || {} });
  73. return;
  74. }
  75. const responseHeaders = { ...(details.responseHeaders || {}) };
  76. // 移除服务端已有的 CORS 头,避免与下面设置的值合并成 "origin1, *" 导致违规
  77. const corsKeys = ['access-control-allow-origin', 'Access-Control-Allow-Origin'];
  78. corsKeys.forEach((k) => delete responseHeaders[k]);
  79. responseHeaders['access-control-allow-origin'] = ['*'];
  80. responseHeaders['access-control-allow-methods'] = ['GET,POST,PUT,PATCH,DELETE,OPTIONS'];
  81. responseHeaders['access-control-allow-headers'] = ['Authorization,Content-Type,X-Requested-With'];
  82. responseHeaders['access-control-expose-headers'] = ['Content-Disposition,Content-Type'];
  83. callback({ responseHeaders });
  84. });
  85. }
  86. function normalizeBaseUrl(url: string): string {
  87. const raw = String(url || '').trim();
  88. if (!raw) return '';
  89. try {
  90. const u = new URL(raw);
  91. return `${u.protocol}//${u.host}`.replace(/\/$/, '');
  92. } catch {
  93. return raw.replace(/\/$/, '');
  94. }
  95. }
  96. function requestJson(url: string, timeoutMs: number): Promise<{ ok: boolean; status?: number; data?: any; error?: string }> {
  97. return new Promise((resolve) => {
  98. const u = new URL(url);
  99. const isHttps = u.protocol === 'https:';
  100. const lib = isHttps ? https : http;
  101. // Windows 上 localhost 常被解析为 ::1,而后端仅监听 127.0.0.1,导致 ECONNREFUSED
  102. const hostname = (u.hostname === 'localhost' || u.hostname === '::1') ? '127.0.0.1' : u.hostname;
  103. const req = lib.request({
  104. method: 'GET',
  105. protocol: u.protocol,
  106. hostname,
  107. port: u.port || (isHttps ? 443 : 80),
  108. path: `${u.pathname}${u.search}`,
  109. headers: {
  110. Accept: 'application/json',
  111. },
  112. timeout: timeoutMs,
  113. rejectUnauthorized: false,
  114. }, (res: any) => {
  115. const chunks: Buffer[] = [];
  116. res.on('data', (c: Buffer) => chunks.push(c));
  117. res.on('end', () => {
  118. const status = Number(res.statusCode || 0);
  119. const rawText = Buffer.concat(chunks).toString('utf-8');
  120. if (status < 200 || status >= 300) {
  121. resolve({ ok: false, status, error: `HTTP ${status}` });
  122. return;
  123. }
  124. try {
  125. const json = rawText ? JSON.parse(rawText) : null;
  126. resolve({ ok: true, status, data: json });
  127. } catch {
  128. resolve({ ok: false, status, error: '响应不是 JSON' });
  129. }
  130. });
  131. });
  132. req.on('timeout', () => {
  133. req.destroy(new Error('timeout'));
  134. });
  135. req.on('error', (err: any) => {
  136. resolve({ ok: false, error: err?.message || '网络错误' });
  137. });
  138. req.end();
  139. });
  140. }
  141. // 获取图标路径
  142. function getIconPath() {
  143. return VITE_DEV_SERVER_URL
  144. ? join(__dirname, '../public/icons/icon-256.png')
  145. : join(__dirname, '../dist/icons/icon-256.png');
  146. }
  147. // 获取托盘图标路径
  148. function getTrayIconPath() {
  149. return VITE_DEV_SERVER_URL
  150. ? join(__dirname, '../public/icons/tray-icon.png')
  151. : join(__dirname, '../dist/icons/tray-icon.png');
  152. }
  153. // 创建托盘图标
  154. function createTrayIcon(): typeof nativeImage.prototype {
  155. const trayIconPath = getTrayIconPath();
  156. return nativeImage.createFromPath(trayIconPath);
  157. }
  158. // 创建系统托盘
  159. function createTray() {
  160. const trayIcon = createTrayIcon();
  161. tray = new Tray(trayIcon);
  162. const contextMenu = Menu.buildFromTemplate([
  163. {
  164. label: '显示主窗口',
  165. click: () => {
  166. if (mainWindow) {
  167. mainWindow.show();
  168. mainWindow.focus();
  169. }
  170. }
  171. },
  172. {
  173. label: '最小化到托盘',
  174. click: () => {
  175. mainWindow?.hide();
  176. }
  177. },
  178. { type: 'separator' },
  179. {
  180. label: '退出',
  181. click: () => {
  182. isQuitting = true;
  183. app.quit();
  184. }
  185. }
  186. ]);
  187. tray.setToolTip('智媒通');
  188. tray.setContextMenu(contextMenu);
  189. // 点击托盘图标显示窗口
  190. tray.on('click', () => {
  191. if (mainWindow) {
  192. if (mainWindow.isVisible()) {
  193. mainWindow.focus();
  194. } else {
  195. mainWindow.show();
  196. mainWindow.focus();
  197. }
  198. }
  199. });
  200. // 双击托盘图标显示窗口
  201. tray.on('double-click', () => {
  202. if (mainWindow) {
  203. mainWindow.show();
  204. mainWindow.focus();
  205. }
  206. });
  207. }
  208. function createWindow() {
  209. // 隐藏默认菜单栏
  210. Menu.setApplicationMenu(null);
  211. const iconPath = getIconPath();
  212. mainWindow = new BrowserWindow({
  213. width: 1400,
  214. height: 900,
  215. minWidth: 1200,
  216. minHeight: 700,
  217. icon: iconPath,
  218. webPreferences: {
  219. preload: join(__dirname, 'preload.js'),
  220. nodeIntegration: false,
  221. contextIsolation: true,
  222. webviewTag: true, // 启用 webview 标签
  223. },
  224. frame: false, // 无边框窗口,自定义标题栏
  225. transparent: false,
  226. backgroundColor: '#f0f2f5',
  227. show: false,
  228. });
  229. // 窗口准备好后再显示,避免白屏
  230. mainWindow.once('ready-to-show', () => {
  231. mainWindow?.show();
  232. setupWindowEvents();
  233. });
  234. // 加载页面
  235. if (VITE_DEV_SERVER_URL) {
  236. mainWindow.loadURL(VITE_DEV_SERVER_URL);
  237. mainWindow.webContents.openDevTools();
  238. } else {
  239. mainWindow.loadFile(join(__dirname, '../dist/index.html'));
  240. }
  241. // 处理外部链接
  242. mainWindow.webContents.setWindowOpenHandler(({ url }: { url: string }) => {
  243. shell.openExternal(url);
  244. return { action: 'deny' };
  245. });
  246. // 关闭按钮默认最小化到托盘
  247. mainWindow.on('close', (event: Event) => {
  248. if (!isQuitting) {
  249. event.preventDefault();
  250. mainWindow?.hide();
  251. // 显示托盘通知(仅首次)
  252. if (tray && !app.isPackaged) {
  253. // 开发模式下可以显示通知
  254. }
  255. }
  256. });
  257. mainWindow.on('closed', () => {
  258. mainWindow = null;
  259. });
  260. }
  261. // 单实例锁定
  262. const gotTheLock = app.requestSingleInstanceLock();
  263. if (!gotTheLock) {
  264. app.quit();
  265. } else {
  266. app.on('second-instance', () => {
  267. if (mainWindow) {
  268. mainWindow.show();
  269. if (mainWindow.isMinimized()) mainWindow.restore();
  270. mainWindow.focus();
  271. }
  272. });
  273. // ========== 降低 Electron 内存占用(必须在 app.whenReady 之前) ==========
  274. app.disableHardwareAcceleration();
  275. app.commandLine.appendSwitch('js-flags', '--max-old-space-size=512');
  276. app.commandLine.appendSwitch('disable-gpu');
  277. app.commandLine.appendSwitch('disable-software-rasterizer');
  278. app.commandLine.appendSwitch('renderer-process-limit', '2');
  279. app.commandLine.appendSwitch('disable-backgrounding-occluded-windows');
  280. app.commandLine.appendSwitch('disable-renderer-backgrounding');
  281. app.whenReady().then(async () => {
  282. logMemory('AppReady');
  283. // 先创建窗口显示 splash screen
  284. createWindow();
  285. createTray();
  286. // 后台启动本地 Node 和 Python 服务,不阻塞窗口显示
  287. console.log('[Main] 正在后台启动本地服务...');
  288. startLocalServices().then(({ nodeOk, pythonOk }) => {
  289. console.log(`[Main] 本地服务状态: Node=${nodeOk ? '就绪' : '未就绪'}, Python=${pythonOk ? '就绪' : '未就绪'}`);
  290. // 通知渲染进程服务状态变化
  291. mainWindow?.webContents.send('services-status-changed', { nodeOk, pythonOk });
  292. });
  293. // 配置 webview session,允许第三方 cookies 和跨域请求
  294. setupWebviewSessions();
  295. setupCertificateBypass();
  296. setupCorsBypassForApiRequests();
  297. app.on('activate', () => {
  298. if (BrowserWindow.getAllWindows().length === 0) {
  299. createWindow();
  300. } else if (mainWindow) {
  301. mainWindow.show();
  302. }
  303. });
  304. });
  305. }
  306. // 配置 webview sessions
  307. function setupWebviewSessions() {
  308. // 监听新的 webContents 创建
  309. app.on('web-contents-created', (_event: unknown, contents: typeof webContents.prototype) => {
  310. // 为 webview 类型的 webContents 配置
  311. if (contents.getType() === 'webview') {
  312. // 设置 User-Agent(模拟 Chrome 浏览器)
  313. contents.setUserAgent(
  314. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  315. );
  316. // 拦截自定义协议链接(如 bitbrowser://)的导航
  317. contents.on('will-navigate', (event: Event, url: string) => {
  318. if (!isAllowedUrl(url)) {
  319. console.log('[WebView] 阻止导航到自定义协议:', url);
  320. event.preventDefault();
  321. }
  322. });
  323. // 拦截新窗口打开(包括自定义协议)
  324. contents.setWindowOpenHandler(({ url }: { url: string }) => {
  325. if (!isAllowedUrl(url)) {
  326. console.log('[WebView] 阻止打开自定义协议窗口:', url);
  327. return { action: 'deny' };
  328. }
  329. // 对于正常的 http/https 链接,在当前 webview 中打开
  330. console.log('[WebView] 拦截新窗口,在当前页面打开:', url);
  331. contents.loadURL(url);
  332. return { action: 'deny' };
  333. });
  334. // 允许所有的权限请求(如摄像头、地理位置等)
  335. contents.session.setPermissionRequestHandler((_webContents: unknown, permission: string, callback: (granted: boolean) => void) => {
  336. // 允许所有权限请求
  337. callback(true);
  338. });
  339. // 配置 webRequest 修改请求头,移除可能暴露 Electron 的特征
  340. contents.session.webRequest.onBeforeSendHeaders((details: { requestHeaders: Record<string, string> }, callback: (response: { requestHeaders: Record<string, string> }) => void) => {
  341. // 移除可能暴露 Electron 的请求头
  342. delete details.requestHeaders['X-DevTools-Emulate-Network-Conditions-Client-Id'];
  343. // 确保有正常的 Origin 和 Referer
  344. if (!details.requestHeaders['Origin'] && !details.requestHeaders['origin']) {
  345. // 不添加 Origin,让浏览器自动处理
  346. }
  347. callback({ requestHeaders: details.requestHeaders });
  348. });
  349. }
  350. });
  351. }
  352. // 检查 URL 是否是允许的协议
  353. function isAllowedUrl(url: string): boolean {
  354. if (!url) return false;
  355. const lowerUrl = url.toLowerCase();
  356. return lowerUrl.startsWith('http://') ||
  357. lowerUrl.startsWith('https://') ||
  358. lowerUrl.startsWith('about:') ||
  359. lowerUrl.startsWith('data:');
  360. }
  361. // 阻止默认的 window-all-closed 行为,保持托盘运行
  362. app.on('window-all-closed', () => {
  363. // 不退出应用,保持托盘运行
  364. // 只有在 isQuitting 为 true 时才真正退出
  365. });
  366. // 应用退出前清理托盘
  367. app.on('before-quit', () => {
  368. isQuitting = true;
  369. });
  370. app.on('quit', () => {
  371. stopLocalServices();
  372. if (tray) {
  373. tray.destroy();
  374. tray = null;
  375. }
  376. });
  377. ipcMain.handle('test-server-connection', async (_event: unknown, args: { url: string }) => {
  378. try {
  379. const baseUrl = normalizeBaseUrl(args?.url);
  380. if (!baseUrl) return { ok: false, error: '未填写服务器地址' };
  381. const result = await requestJson(`${baseUrl}/api/health`, 5000);
  382. if (!result.ok) return { ok: false, error: result.error || '连接失败' };
  383. if (result.data?.status === 'ok') return { ok: true };
  384. return { ok: false, error: '服务器响应异常' };
  385. } catch (e: any) {
  386. return { ok: false, error: e?.message || '连接失败' };
  387. }
  388. });
  389. // Python 服务测试连接(主进程发起,支持 HTTP/HTTPS,无跨域限制)
  390. ipcMain.handle('test-python-service-connection', async (_event: unknown, args: { url: string }) => {
  391. try {
  392. const baseUrl = normalizeBaseUrl(args?.url);
  393. if (!baseUrl) return { ok: false, error: '未填写 Python 服务地址' };
  394. const result = await requestJson(`${baseUrl}/health`, 5000);
  395. if (!result.ok) return { ok: false, error: result.error || '连接失败' };
  396. return { ok: true };
  397. } catch (e: any) {
  398. return { ok: false, error: e?.message || '连接失败' };
  399. }
  400. });
  401. // 本地服务状态查询
  402. ipcMain.handle('get-local-services-status', () => {
  403. return getServiceStatus();
  404. });
  405. ipcMain.handle('get-local-urls', () => {
  406. return { nodeUrl: LOCAL_NODE_URL, pythonUrl: LOCAL_PYTHON_URL };
  407. });
  408. ipcMain.handle('get-service-log', () => {
  409. try {
  410. const logPath = getLogPath();
  411. if (fs.existsSync(logPath)) {
  412. return { path: logPath, content: fs.readFileSync(logPath, 'utf-8') };
  413. }
  414. return { path: logPath, content: '(日志文件不存在)' };
  415. } catch (e: any) {
  416. return { path: '', content: `读取失败: ${e.message}` };
  417. }
  418. });
  419. ipcMain.handle('open-log-file', () => {
  420. try {
  421. const logPath = getLogPath();
  422. if (fs.existsSync(logPath)) {
  423. shell.showItemInFolder(logPath);
  424. }
  425. } catch { /* ignore */ }
  426. });
  427. // IPC 处理
  428. ipcMain.handle('get-app-version', () => {
  429. return app.getVersion();
  430. });
  431. ipcMain.handle('get-platform', () => {
  432. return process.platform;
  433. });
  434. // 窗口控制
  435. ipcMain.on('window-minimize', () => {
  436. mainWindow?.minimize();
  437. });
  438. ipcMain.on('window-maximize', () => {
  439. if (mainWindow?.isMaximized()) {
  440. mainWindow.unmaximize();
  441. } else {
  442. mainWindow?.maximize();
  443. }
  444. });
  445. // 关闭窗口(最小化到托盘)
  446. ipcMain.on('window-close', () => {
  447. mainWindow?.hide();
  448. });
  449. // 真正退出应用
  450. ipcMain.on('app-quit', () => {
  451. isQuitting = true;
  452. app.quit();
  453. });
  454. // 获取窗口最大化状态
  455. ipcMain.handle('window-is-maximized', () => {
  456. return mainWindow?.isMaximized() || false;
  457. });
  458. // 监听窗口最大化/还原事件,通知渲染进程
  459. function setupWindowEvents() {
  460. mainWindow?.on('maximize', () => {
  461. mainWindow?.webContents.send('window-maximized', true);
  462. });
  463. mainWindow?.on('unmaximize', () => {
  464. mainWindow?.webContents.send('window-maximized', false);
  465. });
  466. }
  467. // 弹窗打开平台后台(独立窗口,不嵌入;用于实验,可回归为嵌入)
  468. ipcMain.handle('open-backend-external', async (_event: unknown, payload: { url: string; cookieData?: string; title?: string }) => {
  469. const { url, cookieData, title } = payload || {};
  470. if (!url || typeof url !== 'string') return;
  471. const partition = 'persist:backend-popup-' + Date.now();
  472. const ses = session.fromPartition(partition);
  473. if (cookieData && typeof cookieData === 'string' && cookieData.trim()) {
  474. const raw = cookieData.trim();
  475. let cookiesToSet: Array<{ name: string; value: string; domain?: string; path?: string }> = [];
  476. try {
  477. if (raw.startsWith('[') || raw.startsWith('{')) {
  478. const parsed = JSON.parse(raw);
  479. const arr = Array.isArray(parsed) ? parsed : (parsed?.cookies || []);
  480. cookiesToSet = arr.map((c: { name?: string; value?: string; domain?: string; path?: string }) => ({
  481. name: String(c?.name ?? '').trim(),
  482. value: String(c?.value ?? '').trim(),
  483. domain: c?.domain ? String(c.domain) : undefined,
  484. path: c?.path ? String(c.path) : '/',
  485. })).filter((c: { name: string }) => c.name);
  486. } else {
  487. raw.split(';').forEach((p: string) => {
  488. const idx = p.indexOf('=');
  489. if (idx > 0) {
  490. const name = p.slice(0, idx).trim();
  491. const value = p.slice(idx + 1).trim();
  492. if (name) cookiesToSet.push({ name, value, path: '/' });
  493. }
  494. });
  495. }
  496. } catch (e) {
  497. console.warn('[open-backend-external] 解析 cookie 失败', e);
  498. }
  499. const origin = new URL(url).origin;
  500. const hostname = new URL(url).hostname;
  501. const defaultDomain = hostname.startsWith('www.') ? hostname.slice(4) : hostname;
  502. const domainWithDot = defaultDomain.includes('.') ? '.' + defaultDomain.split('.').slice(-2).join('.') : undefined;
  503. for (const c of cookiesToSet) {
  504. try {
  505. await ses.cookies.set({
  506. url: origin + '/',
  507. name: c.name,
  508. value: c.value,
  509. domain: c.domain || domainWithDot || hostname,
  510. path: c.path || '/',
  511. });
  512. } catch (err) {
  513. console.warn('[open-backend-external] 设置 cookie 失败', c.name, err);
  514. }
  515. }
  516. }
  517. const win = new BrowserWindow({
  518. width: 1280,
  519. height: 800,
  520. title: title || '平台后台',
  521. icon: getIconPath(),
  522. webPreferences: {
  523. session: ses,
  524. nodeIntegration: false,
  525. contextIsolation: true,
  526. },
  527. show: false,
  528. });
  529. win.once('ready-to-show', () => {
  530. win.show();
  531. });
  532. await win.loadURL(url);
  533. return { ok: true };
  534. });
  535. // 获取 webview 的 cookies
  536. ipcMain.handle('get-webview-cookies', async (_event: unknown, partition: string, url: string) => {
  537. try {
  538. const ses = session.fromPartition(partition);
  539. const cookies = await ses.cookies.get({ url });
  540. return cookies;
  541. } catch (error) {
  542. console.error('获取 cookies 失败:', error);
  543. return [];
  544. }
  545. });
  546. // 获取 webview 的全部 cookies(按 partition)
  547. ipcMain.handle('get-webview-all-cookies', async (_event: unknown, partition: string) => {
  548. try {
  549. const ses = session.fromPartition(partition);
  550. return await ses.cookies.get({});
  551. } catch (error) {
  552. console.error('获取全部 cookies 失败:', error);
  553. return [];
  554. }
  555. });
  556. // 清除 webview 的 cookies
  557. ipcMain.handle('clear-webview-cookies', async (_event: unknown, partition: string) => {
  558. try {
  559. const ses = session.fromPartition(partition);
  560. await ses.clearStorageData({ storages: ['cookies'] });
  561. return true;
  562. } catch (error) {
  563. console.error('清除 cookies 失败:', error);
  564. return false;
  565. }
  566. });
  567. // 设置 webview 的 cookies
  568. ipcMain.handle('set-webview-cookies', async (_event: unknown, partition: string, cookies: Electron.CookiesSetDetails[]) => {
  569. try {
  570. if (!Array.isArray(cookies) || cookies.length === 0) {
  571. console.warn(`[Main] set-webview-cookies: cookies 为空, partition=${partition}`);
  572. return false;
  573. }
  574. console.log(`[Main] 设置 webview cookies, partition=${partition}, count=${cookies.length}`);
  575. const ses = session.fromPartition(partition);
  576. // 逐个设置 cookie
  577. let successCount = 0;
  578. for (const cookie of cookies) {
  579. try {
  580. // 确保 Cookie 格式正确
  581. const cookieToSet: Electron.CookiesSetDetails = {
  582. url: cookie.url,
  583. name: cookie.name,
  584. value: cookie.value,
  585. domain: cookie.domain,
  586. path: cookie.path || '/',
  587. };
  588. // 可选字段
  589. if (typeof cookie.expirationDate === 'number' && Number.isFinite(cookie.expirationDate) && cookie.expirationDate > 0) {
  590. cookieToSet.expirationDate = cookie.expirationDate;
  591. }
  592. if (cookie.httpOnly !== undefined) {
  593. cookieToSet.httpOnly = cookie.httpOnly;
  594. }
  595. if (cookie.secure !== undefined) {
  596. cookieToSet.secure = cookie.secure;
  597. }
  598. if (cookie.sameSite) {
  599. cookieToSet.sameSite = cookie.sameSite as 'no_restriction' | 'lax' | 'strict';
  600. }
  601. await ses.cookies.set(cookieToSet);
  602. successCount++;
  603. // 记录关键 Cookie
  604. if (cookie.name === 'BDUSS' || cookie.name === 'STOKEN' || cookie.name === 'sessionid') {
  605. console.log(`[Main] 成功设置关键 Cookie: ${cookie.name}, domain: ${cookie.domain}`);
  606. }
  607. } catch (error) {
  608. console.error(`[Main] 设置 cookie 失败 (${cookie.name}):`, error);
  609. }
  610. }
  611. console.log(`[Main] 成功设置 ${successCount}/${cookies.length} 个 cookies`);
  612. // 验证 Cookie 是否真的设置成功
  613. try {
  614. const setCookies = await ses.cookies.get({ domain: '.baidu.com' });
  615. console.log(`[Main] 验证:当前 session 中有 ${setCookies.length} 个百度 Cookie`);
  616. const keyNames = setCookies.slice(0, 5).map(c => c.name).join(', ');
  617. console.log(`[Main] 关键 Cookie 名称: ${keyNames}`);
  618. } catch (verifyError) {
  619. console.error('[Main] 验证 Cookie 失败:', verifyError);
  620. }
  621. return successCount > 0;
  622. } catch (error) {
  623. console.error('[Main] 设置 cookies 失败:', error);
  624. return false;
  625. }
  626. });
  627. // 截取 webview 页面截图(用于 AI 分析)
  628. ipcMain.handle('capture-webview-page', async (_event: unknown, webContentsId: number) => {
  629. try {
  630. const wc = webContents.fromId(webContentsId);
  631. if (!wc) {
  632. console.error('找不到 webContents:', webContentsId);
  633. return null;
  634. }
  635. const image = await wc.capturePage();
  636. if (!image || image.isEmpty()) {
  637. console.warn('截图为空');
  638. return null;
  639. }
  640. // 转换为 JPEG 格式的 Base64
  641. const buffer = image.toJPEG(80);
  642. return buffer.toString('base64');
  643. } catch (error) {
  644. console.error('截图失败:', error);
  645. return null;
  646. }
  647. });
  648. // 向 webview 发送鼠标点击事件
  649. ipcMain.handle('webview-send-mouse-click', async (_event: unknown, webContentsId: number, x: number, y: number) => {
  650. try {
  651. const wc = webContents.fromId(webContentsId);
  652. if (!wc) {
  653. console.error('找不到 webContents:', webContentsId);
  654. return false;
  655. }
  656. // 发送鼠标移动事件
  657. wc.sendInputEvent({
  658. type: 'mouseMove',
  659. x: Math.round(x),
  660. y: Math.round(y),
  661. });
  662. // 短暂延迟后发送点击事件
  663. await new Promise(resolve => setTimeout(resolve, 50));
  664. // 发送鼠标按下事件
  665. wc.sendInputEvent({
  666. type: 'mouseDown',
  667. x: Math.round(x),
  668. y: Math.round(y),
  669. button: 'left',
  670. clickCount: 1,
  671. });
  672. // 短暂延迟后发送鼠标抬起事件
  673. await new Promise(resolve => setTimeout(resolve, 50));
  674. wc.sendInputEvent({
  675. type: 'mouseUp',
  676. x: Math.round(x),
  677. y: Math.round(y),
  678. button: 'left',
  679. clickCount: 1,
  680. });
  681. console.log(`[webview-send-mouse-click] Clicked at (${x}, ${y})`);
  682. return true;
  683. } catch (error) {
  684. console.error('发送点击事件失败:', error);
  685. return false;
  686. }
  687. });
  688. // 向 webview 发送键盘输入事件
  689. ipcMain.handle('webview-send-text-input', async (_event: unknown, webContentsId: number, text: string) => {
  690. try {
  691. const wc = webContents.fromId(webContentsId);
  692. if (!wc) {
  693. console.error('找不到 webContents:', webContentsId);
  694. return false;
  695. }
  696. // 逐字符输入
  697. for (const char of text) {
  698. wc.sendInputEvent({
  699. type: 'char',
  700. keyCode: char,
  701. });
  702. await new Promise(resolve => setTimeout(resolve, 30));
  703. }
  704. console.log(`[webview-send-text-input] Typed: ${text}`);
  705. return true;
  706. } catch (error) {
  707. console.error('发送输入事件失败:', error);
  708. return false;
  709. }
  710. });
  711. // 获取 webview 页面元素位置
  712. ipcMain.handle('webview-get-element-position', async (_event: unknown, webContentsId: number, selector: string) => {
  713. try {
  714. const wc = webContents.fromId(webContentsId);
  715. if (!wc) {
  716. console.error('找不到 webContents:', webContentsId);
  717. return null;
  718. }
  719. const result = await wc.executeJavaScript(`
  720. (function() {
  721. const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
  722. if (!el) return null;
  723. const rect = el.getBoundingClientRect();
  724. return {
  725. x: rect.left + rect.width / 2,
  726. y: rect.top + rect.height / 2,
  727. width: rect.width,
  728. height: rect.height
  729. };
  730. })()
  731. `);
  732. return result;
  733. } catch (error) {
  734. console.error('获取元素位置失败:', error);
  735. return null;
  736. }
  737. });
  738. // 通过文本内容查找并点击元素
  739. ipcMain.handle('webview-click-by-text', async (_event: unknown, webContentsId: number, text: string) => {
  740. try {
  741. const wc = webContents.fromId(webContentsId);
  742. if (!wc) {
  743. console.error('找不到 webContents:', webContentsId);
  744. return false;
  745. }
  746. // 查找包含指定文本的可点击元素的位置
  747. const position = await wc.executeJavaScript(`
  748. (function() {
  749. const searchText = '${text.replace(/'/g, "\\'")}';
  750. // 查找可点击元素
  751. const clickables = document.querySelectorAll('a, button, [role="button"], [onclick], input[type="submit"], input[type="button"]');
  752. for (const el of clickables) {
  753. if (el.textContent?.includes(searchText) || el.getAttribute('aria-label')?.includes(searchText) || el.getAttribute('title')?.includes(searchText)) {
  754. const rect = el.getBoundingClientRect();
  755. if (rect.width > 0 && rect.height > 0) {
  756. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  757. }
  758. }
  759. }
  760. // 查找所有包含文本的元素
  761. const allElements = document.querySelectorAll('*');
  762. for (const el of allElements) {
  763. const text = el.innerText?.trim();
  764. if (text && text.length < 100 && text.includes(searchText)) {
  765. const rect = el.getBoundingClientRect();
  766. if (rect.width > 0 && rect.height > 0 && rect.width < 500) {
  767. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  768. }
  769. }
  770. }
  771. return null;
  772. })()
  773. `);
  774. if (!position) {
  775. console.warn(`[webview-click-by-text] 未找到包含 "${text}" 的元素`);
  776. return false;
  777. }
  778. // 发送点击事件
  779. wc.sendInputEvent({ type: 'mouseMove', x: Math.round(position.x), y: Math.round(position.y) });
  780. await new Promise(resolve => setTimeout(resolve, 50));
  781. wc.sendInputEvent({ type: 'mouseDown', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  782. await new Promise(resolve => setTimeout(resolve, 50));
  783. wc.sendInputEvent({ type: 'mouseUp', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  784. console.log(`[webview-click-by-text] Clicked "${text}" at (${position.x}, ${position.y})`);
  785. return true;
  786. } catch (error) {
  787. console.error('通过文本点击失败:', error);
  788. return false;
  789. }
  790. });
  791. // ========== CDP 网络拦截功能 ==========
  792. // 存储每个 webContents 的网络拦截配置
  793. const networkInterceptors: Map<number, {
  794. patterns: Array<{ match: string, key: string }>;
  795. pendingRequests: Map<string, { url: string, timestamp: number }>;
  796. }> = new Map();
  797. // 清理已销毁的 webContents
  798. app.on('web-contents-destroyed', (_event: unknown, contents: typeof webContents.prototype) => {
  799. const webContentsId = contents.id;
  800. if (networkInterceptors.has(webContentsId)) {
  801. // 清理网络拦截器
  802. try {
  803. contents.debugger.detach();
  804. } catch (e) {
  805. // 忽略错误
  806. }
  807. networkInterceptors.delete(webContentsId);
  808. console.log(`[CDP] 已清理已销毁的 webContents 拦截器: ${webContentsId}`);
  809. }
  810. });
  811. // 启用 CDP 网络拦截
  812. ipcMain.handle('enable-network-intercept', async (_event: unknown, webContentsId: number, patterns: Array<{ match: string, key: string }>) => {
  813. try {
  814. const wc = webContents.fromId(webContentsId);
  815. if (!wc) {
  816. console.error('[CDP] 找不到 webContents:', webContentsId);
  817. return false;
  818. }
  819. // 如果已经有拦截器,先清理
  820. if (networkInterceptors.has(webContentsId)) {
  821. try {
  822. wc.debugger.detach();
  823. } catch (e) {
  824. // 忽略
  825. }
  826. }
  827. // 存储配置
  828. networkInterceptors.set(webContentsId, {
  829. patterns,
  830. pendingRequests: new Map()
  831. });
  832. // 附加调试器
  833. try {
  834. wc.debugger.attach('1.3');
  835. } catch (err: unknown) {
  836. const error = err as Error;
  837. if (!error.message?.includes('Already attached')) {
  838. throw err;
  839. }
  840. }
  841. // 启用网络监听
  842. await wc.debugger.sendCommand('Network.enable');
  843. // 监听网络响应
  844. wc.debugger.on('message', async (_e: unknown, method: string, params: {
  845. requestId?: string;
  846. response?: { url?: string; status?: number; mimeType?: string };
  847. encodedDataLength?: number;
  848. }) => {
  849. const config = networkInterceptors.get(webContentsId);
  850. if (!config) return;
  851. if (method === 'Network.responseReceived') {
  852. const { requestId, response } = params;
  853. if (!requestId || !response?.url) return;
  854. // 调试:打印百家号相关的所有 API 请求
  855. if (response.url.includes('baijiahao.baidu.com')) {
  856. if (response.url.includes('/pcui/') || response.url.includes('/article')) {
  857. console.log(`[CDP DEBUG] 百家号 API: ${response.url}`);
  858. }
  859. }
  860. // 检查是否匹配我们关注的 API
  861. for (const pattern of config.patterns) {
  862. if (response.url.includes(pattern.match)) {
  863. // 记录请求,等待响应完成
  864. config.pendingRequests.set(requestId, {
  865. url: response.url,
  866. timestamp: Date.now()
  867. });
  868. console.log(`[CDP] 匹配到 API: ${pattern.key} - ${response.url}`);
  869. break;
  870. }
  871. }
  872. }
  873. if (method === 'Network.loadingFinished') {
  874. const { requestId } = params;
  875. if (!requestId) return;
  876. const pending = config.pendingRequests.get(requestId);
  877. if (!pending) return;
  878. config.pendingRequests.delete(requestId);
  879. try {
  880. // 获取响应体
  881. const result = await wc.debugger.sendCommand('Network.getResponseBody', { requestId }) as { body: string; base64Encoded: boolean };
  882. let body = result.body;
  883. // 如果是 base64 编码,解码
  884. if (result.base64Encoded) {
  885. body = Buffer.from(body, 'base64').toString('utf8');
  886. }
  887. // 解析 JSON
  888. const data = JSON.parse(body);
  889. // 找到匹配的 key
  890. let matchedKey = '';
  891. for (const pattern of config.patterns) {
  892. if (pending.url.includes(pattern.match)) {
  893. matchedKey = pattern.key;
  894. break;
  895. }
  896. }
  897. if (matchedKey) {
  898. console.log(`[CDP] 获取到响应: ${matchedKey}`, JSON.stringify(data).substring(0, 200));
  899. // 发送到渲染进程
  900. mainWindow?.webContents.send('network-intercept-data', {
  901. webContentsId,
  902. key: matchedKey,
  903. url: pending.url,
  904. data
  905. });
  906. }
  907. } catch (err) {
  908. console.warn(`[CDP] 获取响应体失败:`, err);
  909. }
  910. }
  911. });
  912. console.log(`[CDP] 已启用网络拦截,webContentsId: ${webContentsId}, patterns:`, patterns.map(p => p.key));
  913. return true;
  914. } catch (error) {
  915. console.error('[CDP] 启用网络拦截失败:', error);
  916. return false;
  917. }
  918. });
  919. // 禁用 CDP 网络拦截
  920. ipcMain.handle('disable-network-intercept', async (_event: unknown, webContentsId: number) => {
  921. try {
  922. const wc = webContents.fromId(webContentsId);
  923. if (wc) {
  924. try {
  925. wc.debugger.detach();
  926. } catch (e) {
  927. // 忽略
  928. }
  929. }
  930. const config = networkInterceptors.get(webContentsId);
  931. if (config) {
  932. // 清理待处理请求的 Map
  933. config.pendingRequests.clear();
  934. }
  935. networkInterceptors.delete(webContentsId);
  936. console.log(`[CDP] 已禁用网络拦截,webContentsId: ${webContentsId}`);
  937. return true;
  938. } catch (error) {
  939. console.error('[CDP] 禁用网络拦截失败:', error);
  940. return false;
  941. }
  942. });
  943. // 更新网络拦截的 patterns
  944. ipcMain.handle('update-network-patterns', async (_event: unknown, webContentsId: number, patterns: Array<{ match: string, key: string }>) => {
  945. const config = networkInterceptors.get(webContentsId);
  946. if (config) {
  947. config.patterns = patterns;
  948. console.log(`[CDP] 已更新 patterns,webContentsId: ${webContentsId}`);
  949. return true;
  950. }
  951. return false;
  952. });