main.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. // 允许所有的权限请求(如摄像头、地理位置等)
  166. contents.session.setPermissionRequestHandler((_webContents: unknown, permission: string, callback: (granted: boolean) => void) => {
  167. // 允许所有权限请求
  168. callback(true);
  169. });
  170. // 配置 webRequest 修改请求头,移除可能暴露 Electron 的特征
  171. contents.session.webRequest.onBeforeSendHeaders((details: { requestHeaders: Record<string, string> }, callback: (response: { requestHeaders: Record<string, string> }) => void) => {
  172. // 移除可能暴露 Electron 的请求头
  173. delete details.requestHeaders['X-DevTools-Emulate-Network-Conditions-Client-Id'];
  174. // 确保有正常的 Origin 和 Referer
  175. if (!details.requestHeaders['Origin'] && !details.requestHeaders['origin']) {
  176. // 不添加 Origin,让浏览器自动处理
  177. }
  178. callback({ requestHeaders: details.requestHeaders });
  179. });
  180. }
  181. });
  182. }
  183. // 阻止默认的 window-all-closed 行为,保持托盘运行
  184. app.on('window-all-closed', () => {
  185. // 不退出应用,保持托盘运行
  186. // 只有在 isQuitting 为 true 时才真正退出
  187. });
  188. // 应用退出前清理托盘
  189. app.on('before-quit', () => {
  190. isQuitting = true;
  191. });
  192. app.on('quit', () => {
  193. if (tray) {
  194. tray.destroy();
  195. tray = null;
  196. }
  197. });
  198. // IPC 处理
  199. ipcMain.handle('get-app-version', () => {
  200. return app.getVersion();
  201. });
  202. ipcMain.handle('get-platform', () => {
  203. return process.platform;
  204. });
  205. // 窗口控制
  206. ipcMain.on('window-minimize', () => {
  207. mainWindow?.minimize();
  208. });
  209. ipcMain.on('window-maximize', () => {
  210. if (mainWindow?.isMaximized()) {
  211. mainWindow.unmaximize();
  212. } else {
  213. mainWindow?.maximize();
  214. }
  215. });
  216. // 关闭窗口(最小化到托盘)
  217. ipcMain.on('window-close', () => {
  218. mainWindow?.hide();
  219. });
  220. // 真正退出应用
  221. ipcMain.on('app-quit', () => {
  222. isQuitting = true;
  223. app.quit();
  224. });
  225. // 获取窗口最大化状态
  226. ipcMain.handle('window-is-maximized', () => {
  227. return mainWindow?.isMaximized() || false;
  228. });
  229. // 监听窗口最大化/还原事件,通知渲染进程
  230. function setupWindowEvents() {
  231. mainWindow?.on('maximize', () => {
  232. mainWindow?.webContents.send('window-maximized', true);
  233. });
  234. mainWindow?.on('unmaximize', () => {
  235. mainWindow?.webContents.send('window-maximized', false);
  236. });
  237. }
  238. // 获取 webview 的 cookies
  239. ipcMain.handle('get-webview-cookies', async (_event: unknown, partition: string, url: string) => {
  240. try {
  241. const ses = session.fromPartition(partition);
  242. const cookies = await ses.cookies.get({ url });
  243. return cookies;
  244. } catch (error) {
  245. console.error('获取 cookies 失败:', error);
  246. return [];
  247. }
  248. });
  249. // 清除 webview 的 cookies
  250. ipcMain.handle('clear-webview-cookies', async (_event: unknown, partition: string) => {
  251. try {
  252. const ses = session.fromPartition(partition);
  253. await ses.clearStorageData({ storages: ['cookies'] });
  254. return true;
  255. } catch (error) {
  256. console.error('清除 cookies 失败:', error);
  257. return false;
  258. }
  259. });
  260. // 设置 webview 的 cookies
  261. ipcMain.handle('set-webview-cookies', async (_event: unknown, partition: string, cookies: Electron.CookiesSetDetails[]) => {
  262. try {
  263. const ses = session.fromPartition(partition);
  264. // 逐个设置 cookie
  265. for (const cookie of cookies) {
  266. await ses.cookies.set(cookie);
  267. }
  268. return true;
  269. } catch (error) {
  270. console.error('设置 cookies 失败:', error);
  271. return false;
  272. }
  273. });
  274. // 截取 webview 页面截图(用于 AI 分析)
  275. ipcMain.handle('capture-webview-page', async (_event: unknown, webContentsId: number) => {
  276. try {
  277. const wc = webContents.fromId(webContentsId);
  278. if (!wc) {
  279. console.error('找不到 webContents:', webContentsId);
  280. return null;
  281. }
  282. const image = await wc.capturePage();
  283. if (!image || image.isEmpty()) {
  284. console.warn('截图为空');
  285. return null;
  286. }
  287. // 转换为 JPEG 格式的 Base64
  288. const buffer = image.toJPEG(80);
  289. return buffer.toString('base64');
  290. } catch (error) {
  291. console.error('截图失败:', error);
  292. return null;
  293. }
  294. });
  295. // 向 webview 发送鼠标点击事件
  296. ipcMain.handle('webview-send-mouse-click', async (_event: unknown, webContentsId: number, x: number, y: number) => {
  297. try {
  298. const wc = webContents.fromId(webContentsId);
  299. if (!wc) {
  300. console.error('找不到 webContents:', webContentsId);
  301. return false;
  302. }
  303. // 发送鼠标移动事件
  304. wc.sendInputEvent({
  305. type: 'mouseMove',
  306. x: Math.round(x),
  307. y: Math.round(y),
  308. });
  309. // 短暂延迟后发送点击事件
  310. await new Promise(resolve => setTimeout(resolve, 50));
  311. // 发送鼠标按下事件
  312. wc.sendInputEvent({
  313. type: 'mouseDown',
  314. x: Math.round(x),
  315. y: Math.round(y),
  316. button: 'left',
  317. clickCount: 1,
  318. });
  319. // 短暂延迟后发送鼠标抬起事件
  320. await new Promise(resolve => setTimeout(resolve, 50));
  321. wc.sendInputEvent({
  322. type: 'mouseUp',
  323. x: Math.round(x),
  324. y: Math.round(y),
  325. button: 'left',
  326. clickCount: 1,
  327. });
  328. console.log(`[webview-send-mouse-click] Clicked at (${x}, ${y})`);
  329. return true;
  330. } catch (error) {
  331. console.error('发送点击事件失败:', error);
  332. return false;
  333. }
  334. });
  335. // 向 webview 发送键盘输入事件
  336. ipcMain.handle('webview-send-text-input', async (_event: unknown, webContentsId: number, text: string) => {
  337. try {
  338. const wc = webContents.fromId(webContentsId);
  339. if (!wc) {
  340. console.error('找不到 webContents:', webContentsId);
  341. return false;
  342. }
  343. // 逐字符输入
  344. for (const char of text) {
  345. wc.sendInputEvent({
  346. type: 'char',
  347. keyCode: char,
  348. });
  349. await new Promise(resolve => setTimeout(resolve, 30));
  350. }
  351. console.log(`[webview-send-text-input] Typed: ${text}`);
  352. return true;
  353. } catch (error) {
  354. console.error('发送输入事件失败:', error);
  355. return false;
  356. }
  357. });
  358. // 获取 webview 页面元素位置
  359. ipcMain.handle('webview-get-element-position', async (_event: unknown, webContentsId: number, selector: string) => {
  360. try {
  361. const wc = webContents.fromId(webContentsId);
  362. if (!wc) {
  363. console.error('找不到 webContents:', webContentsId);
  364. return null;
  365. }
  366. const result = await wc.executeJavaScript(`
  367. (function() {
  368. const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
  369. if (!el) return null;
  370. const rect = el.getBoundingClientRect();
  371. return {
  372. x: rect.left + rect.width / 2,
  373. y: rect.top + rect.height / 2,
  374. width: rect.width,
  375. height: rect.height
  376. };
  377. })()
  378. `);
  379. return result;
  380. } catch (error) {
  381. console.error('获取元素位置失败:', error);
  382. return null;
  383. }
  384. });
  385. // 通过文本内容查找并点击元素
  386. ipcMain.handle('webview-click-by-text', async (_event: unknown, webContentsId: number, text: string) => {
  387. try {
  388. const wc = webContents.fromId(webContentsId);
  389. if (!wc) {
  390. console.error('找不到 webContents:', webContentsId);
  391. return false;
  392. }
  393. // 查找包含指定文本的可点击元素的位置
  394. const position = await wc.executeJavaScript(`
  395. (function() {
  396. const searchText = '${text.replace(/'/g, "\\'")}';
  397. // 查找可点击元素
  398. const clickables = document.querySelectorAll('a, button, [role="button"], [onclick], input[type="submit"], input[type="button"]');
  399. for (const el of clickables) {
  400. if (el.textContent?.includes(searchText) || el.getAttribute('aria-label')?.includes(searchText) || el.getAttribute('title')?.includes(searchText)) {
  401. const rect = el.getBoundingClientRect();
  402. if (rect.width > 0 && rect.height > 0) {
  403. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  404. }
  405. }
  406. }
  407. // 查找所有包含文本的元素
  408. const allElements = document.querySelectorAll('*');
  409. for (const el of allElements) {
  410. const text = el.innerText?.trim();
  411. if (text && text.length < 100 && text.includes(searchText)) {
  412. const rect = el.getBoundingClientRect();
  413. if (rect.width > 0 && rect.height > 0 && rect.width < 500) {
  414. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  415. }
  416. }
  417. }
  418. return null;
  419. })()
  420. `);
  421. if (!position) {
  422. console.warn(`[webview-click-by-text] 未找到包含 "${text}" 的元素`);
  423. return false;
  424. }
  425. // 发送点击事件
  426. wc.sendInputEvent({ type: 'mouseMove', x: Math.round(position.x), y: Math.round(position.y) });
  427. await new Promise(resolve => setTimeout(resolve, 50));
  428. wc.sendInputEvent({ type: 'mouseDown', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  429. await new Promise(resolve => setTimeout(resolve, 50));
  430. wc.sendInputEvent({ type: 'mouseUp', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  431. console.log(`[webview-click-by-text] Clicked "${text}" at (${position.x}, ${position.y})`);
  432. return true;
  433. } catch (error) {
  434. console.error('通过文本点击失败:', error);
  435. return false;
  436. }
  437. });