main.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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.commandLine.appendSwitch('js-flags', '--max-old-space-size=512');
  275. app.commandLine.appendSwitch('renderer-process-limit', '2');
  276. app.whenReady().then(async () => {
  277. logMemory('AppReady');
  278. // 先创建窗口显示 splash screen
  279. createWindow();
  280. createTray();
  281. // 后台启动本地 Node 和 Python 服务,不阻塞窗口显示
  282. console.log('[Main] 正在后台启动本地服务...');
  283. startLocalServices().then(({ nodeOk, pythonOk }) => {
  284. console.log(`[Main] 本地服务状态: Node=${nodeOk ? '就绪' : '未就绪'}, Python=${pythonOk ? '就绪' : '未就绪'}`);
  285. // 通知渲染进程服务状态变化
  286. mainWindow?.webContents.send('services-status-changed', { nodeOk, pythonOk });
  287. });
  288. // 配置 webview session,允许第三方 cookies 和跨域请求
  289. setupWebviewSessions();
  290. setupCertificateBypass();
  291. setupCorsBypassForApiRequests();
  292. app.on('activate', () => {
  293. if (BrowserWindow.getAllWindows().length === 0) {
  294. createWindow();
  295. } else if (mainWindow) {
  296. mainWindow.show();
  297. }
  298. });
  299. });
  300. }
  301. // 配置 webview sessions
  302. function setupWebviewSessions() {
  303. // 监听新的 webContents 创建
  304. app.on('web-contents-created', (_event: unknown, contents: typeof webContents.prototype) => {
  305. // 为 webview 类型的 webContents 配置
  306. if (contents.getType() === 'webview') {
  307. // 设置 User-Agent(模拟 Chrome 浏览器)
  308. contents.setUserAgent(
  309. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  310. );
  311. // 拦截自定义协议链接(如 bitbrowser://)的导航
  312. contents.on('will-navigate', (event: Event, url: string) => {
  313. if (!isAllowedUrl(url)) {
  314. console.log('[WebView] 阻止导航到自定义协议:', url);
  315. event.preventDefault();
  316. }
  317. });
  318. // 拦截新窗口打开(包括自定义协议)
  319. contents.setWindowOpenHandler(({ url }: { url: string }) => {
  320. if (!isAllowedUrl(url)) {
  321. console.log('[WebView] 阻止打开自定义协议窗口:', url);
  322. return { action: 'deny' };
  323. }
  324. // 对于正常的 http/https 链接,在当前 webview 中打开
  325. console.log('[WebView] 拦截新窗口,在当前页面打开:', url);
  326. contents.loadURL(url);
  327. return { action: 'deny' };
  328. });
  329. // 允许所有的权限请求(如摄像头、地理位置等)
  330. contents.session.setPermissionRequestHandler((_webContents: unknown, permission: string, callback: (granted: boolean) => void) => {
  331. // 允许所有权限请求
  332. callback(true);
  333. });
  334. // 配置 webRequest 修改请求头,移除可能暴露 Electron 的特征
  335. contents.session.webRequest.onBeforeSendHeaders((details: { requestHeaders: Record<string, string> }, callback: (response: { requestHeaders: Record<string, string> }) => void) => {
  336. // 移除可能暴露 Electron 的请求头
  337. delete details.requestHeaders['X-DevTools-Emulate-Network-Conditions-Client-Id'];
  338. // 确保有正常的 Origin 和 Referer
  339. if (!details.requestHeaders['Origin'] && !details.requestHeaders['origin']) {
  340. // 不添加 Origin,让浏览器自动处理
  341. }
  342. callback({ requestHeaders: details.requestHeaders });
  343. });
  344. }
  345. });
  346. }
  347. // 检查 URL 是否是允许的协议
  348. function isAllowedUrl(url: string): boolean {
  349. if (!url) return false;
  350. const lowerUrl = url.toLowerCase();
  351. return lowerUrl.startsWith('http://') ||
  352. lowerUrl.startsWith('https://') ||
  353. lowerUrl.startsWith('about:') ||
  354. lowerUrl.startsWith('data:');
  355. }
  356. // 阻止默认的 window-all-closed 行为,保持托盘运行
  357. app.on('window-all-closed', () => {
  358. // 不退出应用,保持托盘运行
  359. // 只有在 isQuitting 为 true 时才真正退出
  360. });
  361. // 应用退出前清理托盘
  362. app.on('before-quit', () => {
  363. isQuitting = true;
  364. });
  365. app.on('quit', () => {
  366. stopLocalServices();
  367. if (tray) {
  368. tray.destroy();
  369. tray = null;
  370. }
  371. });
  372. ipcMain.handle('test-server-connection', async (_event: unknown, args: { url: string }) => {
  373. try {
  374. const baseUrl = normalizeBaseUrl(args?.url);
  375. if (!baseUrl) return { ok: false, error: '未填写服务器地址' };
  376. const result = await requestJson(`${baseUrl}/api/health`, 5000);
  377. if (!result.ok) return { ok: false, error: result.error || '连接失败' };
  378. if (result.data?.status === 'ok') return { ok: true };
  379. return { ok: false, error: '服务器响应异常' };
  380. } catch (e: any) {
  381. return { ok: false, error: e?.message || '连接失败' };
  382. }
  383. });
  384. // Python 服务测试连接(主进程发起,支持 HTTP/HTTPS,无跨域限制)
  385. ipcMain.handle('test-python-service-connection', async (_event: unknown, args: { url: string }) => {
  386. try {
  387. const baseUrl = normalizeBaseUrl(args?.url);
  388. if (!baseUrl) return { ok: false, error: '未填写 Python 服务地址' };
  389. const result = await requestJson(`${baseUrl}/health`, 5000);
  390. if (!result.ok) return { ok: false, error: result.error || '连接失败' };
  391. return { ok: true };
  392. } catch (e: any) {
  393. return { ok: false, error: e?.message || '连接失败' };
  394. }
  395. });
  396. // 本地服务状态查询
  397. ipcMain.handle('get-local-services-status', () => {
  398. return getServiceStatus();
  399. });
  400. ipcMain.handle('get-local-urls', () => {
  401. return { nodeUrl: LOCAL_NODE_URL, pythonUrl: LOCAL_PYTHON_URL };
  402. });
  403. ipcMain.handle('get-service-log', () => {
  404. try {
  405. const logPath = getLogPath();
  406. if (fs.existsSync(logPath)) {
  407. return { path: logPath, content: fs.readFileSync(logPath, 'utf-8') };
  408. }
  409. return { path: logPath, content: '(日志文件不存在)' };
  410. } catch (e: any) {
  411. return { path: '', content: `读取失败: ${e.message}` };
  412. }
  413. });
  414. ipcMain.handle('open-log-file', () => {
  415. try {
  416. const logPath = getLogPath();
  417. if (fs.existsSync(logPath)) {
  418. shell.showItemInFolder(logPath);
  419. }
  420. } catch { /* ignore */ }
  421. });
  422. // IPC 处理
  423. ipcMain.handle('get-app-version', () => {
  424. return app.getVersion();
  425. });
  426. ipcMain.handle('get-platform', () => {
  427. return process.platform;
  428. });
  429. // 窗口控制
  430. ipcMain.on('window-minimize', () => {
  431. mainWindow?.minimize();
  432. });
  433. ipcMain.on('window-maximize', () => {
  434. if (mainWindow?.isMaximized()) {
  435. mainWindow.unmaximize();
  436. } else {
  437. mainWindow?.maximize();
  438. }
  439. });
  440. // 关闭窗口(最小化到托盘)
  441. ipcMain.on('window-close', () => {
  442. mainWindow?.hide();
  443. });
  444. // 真正退出应用
  445. ipcMain.on('app-quit', () => {
  446. isQuitting = true;
  447. app.quit();
  448. });
  449. // 获取窗口最大化状态
  450. ipcMain.handle('window-is-maximized', () => {
  451. return mainWindow?.isMaximized() || false;
  452. });
  453. // 监听窗口最大化/还原事件,通知渲染进程
  454. function setupWindowEvents() {
  455. mainWindow?.on('maximize', () => {
  456. mainWindow?.webContents.send('window-maximized', true);
  457. });
  458. mainWindow?.on('unmaximize', () => {
  459. mainWindow?.webContents.send('window-maximized', false);
  460. });
  461. }
  462. // 弹窗打开平台后台(独立窗口,不嵌入;用于实验,可回归为嵌入)
  463. ipcMain.handle('open-backend-external', async (_event: unknown, payload: { url: string; cookieData?: string; title?: string }) => {
  464. const { url, cookieData, title } = payload || {};
  465. if (!url || typeof url !== 'string') return;
  466. const partition = 'persist:backend-popup-' + Date.now();
  467. const ses = session.fromPartition(partition);
  468. if (cookieData && typeof cookieData === 'string' && cookieData.trim()) {
  469. const raw = cookieData.trim();
  470. let cookiesToSet: Array<{ name: string; value: string; domain?: string; path?: string }> = [];
  471. try {
  472. if (raw.startsWith('[') || raw.startsWith('{')) {
  473. const parsed = JSON.parse(raw);
  474. const arr = Array.isArray(parsed) ? parsed : (parsed?.cookies || []);
  475. cookiesToSet = arr.map((c: { name?: string; value?: string; domain?: string; path?: string }) => ({
  476. name: String(c?.name ?? '').trim(),
  477. value: String(c?.value ?? '').trim(),
  478. domain: c?.domain ? String(c.domain) : undefined,
  479. path: c?.path ? String(c.path) : '/',
  480. })).filter((c: { name: string }) => c.name);
  481. } else {
  482. raw.split(';').forEach((p: string) => {
  483. const idx = p.indexOf('=');
  484. if (idx > 0) {
  485. const name = p.slice(0, idx).trim();
  486. const value = p.slice(idx + 1).trim();
  487. if (name) cookiesToSet.push({ name, value, path: '/' });
  488. }
  489. });
  490. }
  491. } catch (e) {
  492. console.warn('[open-backend-external] 解析 cookie 失败', e);
  493. }
  494. const origin = new URL(url).origin;
  495. const hostname = new URL(url).hostname;
  496. const defaultDomain = hostname.startsWith('www.') ? hostname.slice(4) : hostname;
  497. const domainWithDot = defaultDomain.includes('.') ? '.' + defaultDomain.split('.').slice(-2).join('.') : undefined;
  498. for (const c of cookiesToSet) {
  499. try {
  500. await ses.cookies.set({
  501. url: origin + '/',
  502. name: c.name,
  503. value: c.value,
  504. domain: c.domain || domainWithDot || hostname,
  505. path: c.path || '/',
  506. });
  507. } catch (err) {
  508. console.warn('[open-backend-external] 设置 cookie 失败', c.name, err);
  509. }
  510. }
  511. }
  512. const win = new BrowserWindow({
  513. width: 1280,
  514. height: 800,
  515. title: title || '平台后台',
  516. icon: getIconPath(),
  517. webPreferences: {
  518. session: ses,
  519. nodeIntegration: false,
  520. contextIsolation: true,
  521. },
  522. show: false,
  523. });
  524. win.once('ready-to-show', () => {
  525. win.show();
  526. });
  527. await win.loadURL(url);
  528. return { ok: true };
  529. });
  530. // 获取 webview 的 cookies
  531. ipcMain.handle('get-webview-cookies', async (_event: unknown, partition: string, url: string) => {
  532. try {
  533. const ses = session.fromPartition(partition);
  534. const cookies = await ses.cookies.get({ url });
  535. return cookies;
  536. } catch (error) {
  537. console.error('获取 cookies 失败:', error);
  538. return [];
  539. }
  540. });
  541. // 获取 webview 的全部 cookies(按 partition)
  542. ipcMain.handle('get-webview-all-cookies', async (_event: unknown, partition: string) => {
  543. try {
  544. const ses = session.fromPartition(partition);
  545. return await ses.cookies.get({});
  546. } catch (error) {
  547. console.error('获取全部 cookies 失败:', error);
  548. return [];
  549. }
  550. });
  551. // 清除 webview 的 cookies
  552. ipcMain.handle('clear-webview-cookies', async (_event: unknown, partition: string) => {
  553. try {
  554. const ses = session.fromPartition(partition);
  555. await ses.clearStorageData({ storages: ['cookies'] });
  556. return true;
  557. } catch (error) {
  558. console.error('清除 cookies 失败:', error);
  559. return false;
  560. }
  561. });
  562. // 设置 webview 的 cookies
  563. ipcMain.handle('set-webview-cookies', async (_event: unknown, partition: string, cookies: Electron.CookiesSetDetails[]) => {
  564. try {
  565. if (!Array.isArray(cookies) || cookies.length === 0) {
  566. console.warn(`[Main] set-webview-cookies: cookies 为空, partition=${partition}`);
  567. return false;
  568. }
  569. console.log(`[Main] 设置 webview cookies, partition=${partition}, count=${cookies.length}`);
  570. const ses = session.fromPartition(partition);
  571. // 逐个设置 cookie
  572. let successCount = 0;
  573. for (const cookie of cookies) {
  574. try {
  575. // 确保 Cookie 格式正确
  576. const cookieToSet: Electron.CookiesSetDetails = {
  577. url: cookie.url,
  578. name: cookie.name,
  579. value: cookie.value,
  580. domain: cookie.domain,
  581. path: cookie.path || '/',
  582. };
  583. // 可选字段
  584. if (typeof cookie.expirationDate === 'number' && Number.isFinite(cookie.expirationDate) && cookie.expirationDate > 0) {
  585. cookieToSet.expirationDate = cookie.expirationDate;
  586. }
  587. if (cookie.httpOnly !== undefined) {
  588. cookieToSet.httpOnly = cookie.httpOnly;
  589. }
  590. if (cookie.secure !== undefined) {
  591. cookieToSet.secure = cookie.secure;
  592. }
  593. if (cookie.sameSite) {
  594. cookieToSet.sameSite = cookie.sameSite as 'no_restriction' | 'lax' | 'strict';
  595. }
  596. await ses.cookies.set(cookieToSet);
  597. successCount++;
  598. // 记录关键 Cookie
  599. if (cookie.name === 'BDUSS' || cookie.name === 'STOKEN' || cookie.name === 'sessionid') {
  600. console.log(`[Main] 成功设置关键 Cookie: ${cookie.name}, domain: ${cookie.domain}`);
  601. }
  602. } catch (error) {
  603. console.error(`[Main] 设置 cookie 失败 (${cookie.name}):`, error);
  604. }
  605. }
  606. console.log(`[Main] 成功设置 ${successCount}/${cookies.length} 个 cookies`);
  607. // 验证 Cookie 是否真的设置成功
  608. try {
  609. const setCookies = await ses.cookies.get({ domain: '.baidu.com' });
  610. console.log(`[Main] 验证:当前 session 中有 ${setCookies.length} 个百度 Cookie`);
  611. const keyNames = setCookies.slice(0, 5).map(c => c.name).join(', ');
  612. console.log(`[Main] 关键 Cookie 名称: ${keyNames}`);
  613. } catch (verifyError) {
  614. console.error('[Main] 验证 Cookie 失败:', verifyError);
  615. }
  616. return successCount > 0;
  617. } catch (error) {
  618. console.error('[Main] 设置 cookies 失败:', error);
  619. return false;
  620. }
  621. });
  622. // 截取 webview 页面截图(用于 AI 分析)
  623. ipcMain.handle('capture-webview-page', async (_event: unknown, webContentsId: number) => {
  624. try {
  625. const wc = webContents.fromId(webContentsId);
  626. if (!wc) {
  627. console.error('找不到 webContents:', webContentsId);
  628. return null;
  629. }
  630. const image = await wc.capturePage();
  631. if (!image || image.isEmpty()) {
  632. console.warn('截图为空');
  633. return null;
  634. }
  635. // 转换为 JPEG 格式的 Base64
  636. const buffer = image.toJPEG(80);
  637. return buffer.toString('base64');
  638. } catch (error) {
  639. console.error('截图失败:', error);
  640. return null;
  641. }
  642. });
  643. // 向 webview 发送鼠标点击事件
  644. ipcMain.handle('webview-send-mouse-click', async (_event: unknown, webContentsId: number, x: number, y: number) => {
  645. try {
  646. const wc = webContents.fromId(webContentsId);
  647. if (!wc) {
  648. console.error('找不到 webContents:', webContentsId);
  649. return false;
  650. }
  651. // 发送鼠标移动事件
  652. wc.sendInputEvent({
  653. type: 'mouseMove',
  654. x: Math.round(x),
  655. y: Math.round(y),
  656. });
  657. // 短暂延迟后发送点击事件
  658. await new Promise(resolve => setTimeout(resolve, 50));
  659. // 发送鼠标按下事件
  660. wc.sendInputEvent({
  661. type: 'mouseDown',
  662. x: Math.round(x),
  663. y: Math.round(y),
  664. button: 'left',
  665. clickCount: 1,
  666. });
  667. // 短暂延迟后发送鼠标抬起事件
  668. await new Promise(resolve => setTimeout(resolve, 50));
  669. wc.sendInputEvent({
  670. type: 'mouseUp',
  671. x: Math.round(x),
  672. y: Math.round(y),
  673. button: 'left',
  674. clickCount: 1,
  675. });
  676. console.log(`[webview-send-mouse-click] Clicked at (${x}, ${y})`);
  677. return true;
  678. } catch (error) {
  679. console.error('发送点击事件失败:', error);
  680. return false;
  681. }
  682. });
  683. // 向 webview 发送键盘输入事件
  684. ipcMain.handle('webview-send-text-input', async (_event: unknown, webContentsId: number, text: string) => {
  685. try {
  686. const wc = webContents.fromId(webContentsId);
  687. if (!wc) {
  688. console.error('找不到 webContents:', webContentsId);
  689. return false;
  690. }
  691. // 逐字符输入
  692. for (const char of text) {
  693. wc.sendInputEvent({
  694. type: 'char',
  695. keyCode: char,
  696. });
  697. await new Promise(resolve => setTimeout(resolve, 30));
  698. }
  699. console.log(`[webview-send-text-input] Typed: ${text}`);
  700. return true;
  701. } catch (error) {
  702. console.error('发送输入事件失败:', error);
  703. return false;
  704. }
  705. });
  706. // 获取 webview 页面元素位置
  707. ipcMain.handle('webview-get-element-position', async (_event: unknown, webContentsId: number, selector: string) => {
  708. try {
  709. const wc = webContents.fromId(webContentsId);
  710. if (!wc) {
  711. console.error('找不到 webContents:', webContentsId);
  712. return null;
  713. }
  714. const result = await wc.executeJavaScript(`
  715. (function() {
  716. const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
  717. if (!el) return null;
  718. const rect = el.getBoundingClientRect();
  719. return {
  720. x: rect.left + rect.width / 2,
  721. y: rect.top + rect.height / 2,
  722. width: rect.width,
  723. height: rect.height
  724. };
  725. })()
  726. `);
  727. return result;
  728. } catch (error) {
  729. console.error('获取元素位置失败:', error);
  730. return null;
  731. }
  732. });
  733. // 通过文本内容查找并点击元素
  734. ipcMain.handle('webview-click-by-text', async (_event: unknown, webContentsId: number, text: string) => {
  735. try {
  736. const wc = webContents.fromId(webContentsId);
  737. if (!wc) {
  738. console.error('找不到 webContents:', webContentsId);
  739. return false;
  740. }
  741. // 查找包含指定文本的可点击元素的位置
  742. const position = await wc.executeJavaScript(`
  743. (function() {
  744. const searchText = '${text.replace(/'/g, "\\'")}';
  745. // 查找可点击元素
  746. const clickables = document.querySelectorAll('a, button, [role="button"], [onclick], input[type="submit"], input[type="button"]');
  747. for (const el of clickables) {
  748. if (el.textContent?.includes(searchText) || el.getAttribute('aria-label')?.includes(searchText) || el.getAttribute('title')?.includes(searchText)) {
  749. const rect = el.getBoundingClientRect();
  750. if (rect.width > 0 && rect.height > 0) {
  751. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  752. }
  753. }
  754. }
  755. // 查找所有包含文本的元素
  756. const allElements = document.querySelectorAll('*');
  757. for (const el of allElements) {
  758. const text = el.innerText?.trim();
  759. if (text && text.length < 100 && text.includes(searchText)) {
  760. const rect = el.getBoundingClientRect();
  761. if (rect.width > 0 && rect.height > 0 && rect.width < 500) {
  762. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  763. }
  764. }
  765. }
  766. return null;
  767. })()
  768. `);
  769. if (!position) {
  770. console.warn(`[webview-click-by-text] 未找到包含 "${text}" 的元素`);
  771. return false;
  772. }
  773. // 发送点击事件
  774. wc.sendInputEvent({ type: 'mouseMove', x: Math.round(position.x), y: Math.round(position.y) });
  775. await new Promise(resolve => setTimeout(resolve, 50));
  776. wc.sendInputEvent({ type: 'mouseDown', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  777. await new Promise(resolve => setTimeout(resolve, 50));
  778. wc.sendInputEvent({ type: 'mouseUp', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  779. console.log(`[webview-click-by-text] Clicked "${text}" at (${position.x}, ${position.y})`);
  780. return true;
  781. } catch (error) {
  782. console.error('通过文本点击失败:', error);
  783. return false;
  784. }
  785. });
  786. // ========== CDP 网络拦截功能 ==========
  787. // 存储每个 webContents 的网络拦截配置
  788. const networkInterceptors: Map<number, {
  789. patterns: Array<{ match: string, key: string }>;
  790. pendingRequests: Map<string, { url: string, timestamp: number }>;
  791. }> = new Map();
  792. // 清理已销毁的 webContents
  793. app.on('web-contents-destroyed', (_event: unknown, contents: typeof webContents.prototype) => {
  794. const webContentsId = contents.id;
  795. if (networkInterceptors.has(webContentsId)) {
  796. // 清理网络拦截器
  797. try {
  798. contents.debugger.detach();
  799. } catch (e) {
  800. // 忽略错误
  801. }
  802. networkInterceptors.delete(webContentsId);
  803. console.log(`[CDP] 已清理已销毁的 webContents 拦截器: ${webContentsId}`);
  804. }
  805. });
  806. // 启用 CDP 网络拦截
  807. ipcMain.handle('enable-network-intercept', async (_event: unknown, webContentsId: number, patterns: Array<{ match: string, key: string }>) => {
  808. try {
  809. const wc = webContents.fromId(webContentsId);
  810. if (!wc) {
  811. console.error('[CDP] 找不到 webContents:', webContentsId);
  812. return false;
  813. }
  814. // 如果已经有拦截器,先清理
  815. if (networkInterceptors.has(webContentsId)) {
  816. try {
  817. wc.debugger.detach();
  818. } catch (e) {
  819. // 忽略
  820. }
  821. }
  822. // 存储配置
  823. networkInterceptors.set(webContentsId, {
  824. patterns,
  825. pendingRequests: new Map()
  826. });
  827. // 附加调试器
  828. try {
  829. wc.debugger.attach('1.3');
  830. } catch (err: unknown) {
  831. const error = err as Error;
  832. if (!error.message?.includes('Already attached')) {
  833. throw err;
  834. }
  835. }
  836. // 启用网络监听
  837. await wc.debugger.sendCommand('Network.enable');
  838. // 监听网络响应
  839. wc.debugger.on('message', async (_e: unknown, method: string, params: {
  840. requestId?: string;
  841. response?: { url?: string; status?: number; mimeType?: string };
  842. encodedDataLength?: number;
  843. }) => {
  844. const config = networkInterceptors.get(webContentsId);
  845. if (!config) return;
  846. if (method === 'Network.responseReceived') {
  847. const { requestId, response } = params;
  848. if (!requestId || !response?.url) return;
  849. // 调试:打印百家号相关的所有 API 请求
  850. if (response.url.includes('baijiahao.baidu.com')) {
  851. if (response.url.includes('/pcui/') || response.url.includes('/article')) {
  852. console.log(`[CDP DEBUG] 百家号 API: ${response.url}`);
  853. }
  854. }
  855. // 检查是否匹配我们关注的 API
  856. for (const pattern of config.patterns) {
  857. if (response.url.includes(pattern.match)) {
  858. // 记录请求,等待响应完成
  859. config.pendingRequests.set(requestId, {
  860. url: response.url,
  861. timestamp: Date.now()
  862. });
  863. console.log(`[CDP] 匹配到 API: ${pattern.key} - ${response.url}`);
  864. break;
  865. }
  866. }
  867. }
  868. if (method === 'Network.loadingFinished') {
  869. const { requestId } = params;
  870. if (!requestId) return;
  871. const pending = config.pendingRequests.get(requestId);
  872. if (!pending) return;
  873. config.pendingRequests.delete(requestId);
  874. try {
  875. // 获取响应体
  876. const result = await wc.debugger.sendCommand('Network.getResponseBody', { requestId }) as { body: string; base64Encoded: boolean };
  877. let body = result.body;
  878. // 如果是 base64 编码,解码
  879. if (result.base64Encoded) {
  880. body = Buffer.from(body, 'base64').toString('utf8');
  881. }
  882. // 解析 JSON
  883. const data = JSON.parse(body);
  884. // 找到匹配的 key
  885. let matchedKey = '';
  886. for (const pattern of config.patterns) {
  887. if (pending.url.includes(pattern.match)) {
  888. matchedKey = pattern.key;
  889. break;
  890. }
  891. }
  892. if (matchedKey) {
  893. console.log(`[CDP] 获取到响应: ${matchedKey}`, JSON.stringify(data).substring(0, 200));
  894. // 发送到渲染进程
  895. mainWindow?.webContents.send('network-intercept-data', {
  896. webContentsId,
  897. key: matchedKey,
  898. url: pending.url,
  899. data
  900. });
  901. }
  902. } catch (err) {
  903. console.warn(`[CDP] 获取响应体失败:`, err);
  904. }
  905. }
  906. });
  907. console.log(`[CDP] 已启用网络拦截,webContentsId: ${webContentsId}, patterns:`, patterns.map(p => p.key));
  908. return true;
  909. } catch (error) {
  910. console.error('[CDP] 启用网络拦截失败:', error);
  911. return false;
  912. }
  913. });
  914. // 禁用 CDP 网络拦截
  915. ipcMain.handle('disable-network-intercept', async (_event: unknown, webContentsId: number) => {
  916. try {
  917. const wc = webContents.fromId(webContentsId);
  918. if (wc) {
  919. try {
  920. wc.debugger.detach();
  921. } catch (e) {
  922. // 忽略
  923. }
  924. }
  925. const config = networkInterceptors.get(webContentsId);
  926. if (config) {
  927. // 清理待处理请求的 Map
  928. config.pendingRequests.clear();
  929. }
  930. networkInterceptors.delete(webContentsId);
  931. console.log(`[CDP] 已禁用网络拦截,webContentsId: ${webContentsId}`);
  932. return true;
  933. } catch (error) {
  934. console.error('[CDP] 禁用网络拦截失败:', error);
  935. return false;
  936. }
  937. });
  938. // 更新网络拦截的 patterns
  939. ipcMain.handle('update-network-patterns', async (_event: unknown, webContentsId: number, patterns: Array<{ match: string, key: string }>) => {
  940. const config = networkInterceptors.get(webContentsId);
  941. if (config) {
  942. config.patterns = patterns;
  943. console.log(`[CDP] 已更新 patterns,webContentsId: ${webContentsId}`);
  944. return true;
  945. }
  946. return false;
  947. });