main.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. import { app, BrowserWindow, session, ipcMain } from 'electron';
  2. import { fileURLToPath } from 'url';
  3. import path from 'path';
  4. import { exec } from 'child_process';
  5. import { promisify } from 'util';
  6. import { existsSync, readFileSync } from 'fs';
  7. const execAsync = promisify(exec);
  8. const __filename = fileURLToPath(import.meta.url);
  9. const __dirname = path.dirname(__filename);
  10. const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged;
  11. // 读取配置文件
  12. function loadConfig() {
  13. try {
  14. const configPath = path.join(__dirname, 'config.js');
  15. if (existsSync(configPath)) {
  16. const configContent = readFileSync(configPath, 'utf-8');
  17. // 解析 JSON(移除可能的注释和尾随逗号)
  18. const jsonContent = configContent.replace(/\/\/.*$/gm, '').replace(/,(\s*[}\]])/g, '$1');
  19. return JSON.parse(jsonContent);
  20. }
  21. } catch (error) {
  22. console.warn('Failed to load config.js:', error.message);
  23. }
  24. return null;
  25. }
  26. // 查找 ADB 可执行文件路径
  27. function getAdbPath() {
  28. // 首先尝试从配置文件读取
  29. const config = loadConfig();
  30. if (config && config['adb-path']) {
  31. const configAdbPath = path.join(config['adb-path'], 'adb.exe');
  32. if (existsSync(configAdbPath)) {
  33. console.log('Using ADB path from config.js:', configAdbPath);
  34. return configAdbPath;
  35. }
  36. // 如果配置的路径不存在,尝试直接使用配置的路径(可能已经是完整路径)
  37. if (existsSync(config['adb-path'])) {
  38. console.log('Using ADB path from config.js:', config['adb-path']);
  39. return config['adb-path'];
  40. }
  41. }
  42. // 如果配置文件没有或路径不存在,使用常见 ADB 安装位置(按优先级排序)
  43. const possiblePaths = [
  44. path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk', 'platform-tools', 'adb.exe'),
  45. path.join(process.env.USERPROFILE || '', 'AppData', 'Local', 'Android', 'Sdk', 'platform-tools', 'adb.exe'),
  46. path.join(process.env.ProgramFiles || '', 'Android', 'android-sdk', 'platform-tools', 'adb.exe'),
  47. path.join(process.env['ProgramFiles(x86)'] || '', 'Android', 'android-sdk', 'platform-tools', 'adb.exe'),
  48. ];
  49. // 检查常见位置
  50. for (const adbPath of possiblePaths) {
  51. if (existsSync(adbPath)) {
  52. return adbPath;
  53. }
  54. }
  55. // 如果都找不到,尝试使用 PATH 中的 adb
  56. return 'adb';
  57. }
  58. // 缓存 ADB 路径
  59. let adbPathCache = null;
  60. function getCachedAdbPath() {
  61. if (!adbPathCache) {
  62. adbPathCache = getAdbPath();
  63. }
  64. return adbPathCache;
  65. }
  66. // 设置内容安全策略(CSP),防止 XSS 攻击
  67. function setContentSecurityPolicy() {
  68. session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
  69. const csp = isDev
  70. ? "default-src 'self'; script-src 'self' 'unsafe-inline' http://localhost:*; style-src 'self' 'unsafe-inline'; connect-src 'self' http://localhost:* ws://localhost:*; img-src 'self' data: https: blob:; font-src 'self' data:; worker-src 'self' blob:;"
  71. : "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: https:; font-src 'self' data:;";
  72. const responseHeaders = Object.assign({}, details.responseHeaders);
  73. responseHeaders['Content-Security-Policy'] = [csp];
  74. callback({ responseHeaders });
  75. });
  76. }
  77. // 全局主窗口引用,用于发送实时事件
  78. let mainWindow = null;
  79. // 创建主窗口,根据环境加载不同内容源
  80. function createWindow() {
  81. mainWindow = new BrowserWindow({
  82. width: 1200,
  83. height: 800,
  84. webPreferences: {
  85. preload: path.join(__dirname, 'preload.cjs'),
  86. nodeIntegration: false,
  87. contextIsolation: true
  88. }
  89. });
  90. // 禁用窗口关闭确认对话框,直接关闭
  91. mainWindow.on('close', (event) => {
  92. // 不阻止关闭事件,直接关闭窗口
  93. // 如果需要清理资源,可以在这里添加
  94. });
  95. // 禁用 webContents 的 beforeunload 确认对话框
  96. mainWindow.webContents.on('will-prevent-unload', (event) => {
  97. // 不阻止卸载,直接关闭
  98. // 注意:这里不需要调用 event.preventDefault(),因为我们要允许关闭
  99. });
  100. // 禁用 beforeunload 事件(前端页面可能触发的确认对话框)
  101. mainWindow.webContents.setWindowOpenHandler(() => {
  102. return { action: 'allow' };
  103. });
  104. // 禁用所有可能阻止关闭的事件
  105. mainWindow.webContents.on('beforeunload', (event) => {
  106. // 不阻止卸载
  107. });
  108. if (isDev) {
  109. mainWindow.loadURL('http://localhost:5173');
  110. mainWindow.webContents.openDevTools();
  111. } else {
  112. mainWindow.loadFile(path.join(__dirname, 'dist/index.html'));
  113. }
  114. }
  115. // 获取已连接的 ADB 设备列表
  116. async function getADBDevices() {
  117. try {
  118. const adbPath = getCachedAdbPath();
  119. const { stdout } = await execAsync(`${adbPath} devices`);
  120. const lines = stdout.split('\n').slice(1);
  121. const devices = [];
  122. for (const line of lines) {
  123. const parts = line.trim().split(/\s+/);
  124. if (parts.length >= 2 && parts[0] && parts[1] === 'device') {
  125. devices.push({
  126. id: parts[0],
  127. status: parts[1]
  128. });
  129. }
  130. }
  131. return devices;
  132. } catch (error) {
  133. console.error('获取设备列表失败:', error);
  134. return [];
  135. }
  136. }
  137. // 网络扫描:从 192.168.0.1 开始扫描网段,尝试连接设备(实时推送结果)
  138. async function scanNetworkDevices(event) {
  139. const adbPath = getCachedAdbPath();
  140. const baseIP = '192.168.0';
  141. const port = 5555;
  142. const maxConcurrent = 20; // 限制并发数,避免过载
  143. const connectTimeout = 1500; // 连接超时时间(毫秒)
  144. // 生成 IP 地址列表
  145. const ipList = [];
  146. for (let i = 1; i <= 255; i++) {
  147. ipList.push(`${baseIP}.${i}`);
  148. }
  149. const foundDevices = new Set(); // 使用 Set 避免重复
  150. // 分批并发扫描
  151. for (let i = 0; i < ipList.length; i += maxConcurrent) {
  152. const batch = ipList.slice(i, i + maxConcurrent);
  153. const promises = batch.map(async (ip) => {
  154. const ipPort = `${ip}:${port}`;
  155. try {
  156. // 先尝试连接设备
  157. await execAsync(`${adbPath} connect ${ipPort}`, {
  158. timeout: connectTimeout,
  159. maxBuffer: 1024 * 1024
  160. });
  161. // 连接后稍等片刻,让设备注册到 ADB 服务器
  162. await new Promise(resolve => setTimeout(resolve, 500));
  163. } catch (error) {
  164. // 连接失败是正常的,继续检查设备列表
  165. }
  166. // 直接使用 adb -s IP:PORT devices 命令检查该设备是否在列表中
  167. try {
  168. const { stdout } = await execAsync(`${adbPath} -s ${ipPort} devices`, {
  169. timeout: 2000,
  170. maxBuffer: 1024 * 1024
  171. });
  172. // 检查输出中是否包含 IP:PORT,如果有则说明设备存在
  173. if (stdout.includes(ipPort)) {
  174. // 发现设备,实时推送
  175. if (!foundDevices.has(ipPort)) {
  176. foundDevices.add(ipPort);
  177. const device = {
  178. id: ipPort,
  179. status: 'device'
  180. };
  181. // 实时发送发现的设备
  182. if (event && event.sender) {
  183. event.sender.send('device-found', device);
  184. } else if (mainWindow) {
  185. mainWindow.webContents.send('device-found', device);
  186. }
  187. console.log('发现设备:', ipPort);
  188. }
  189. return ipPort;
  190. }
  191. } catch (checkError) {
  192. // 检查失败,忽略
  193. }
  194. return null;
  195. });
  196. await Promise.all(promises);
  197. }
  198. // 返回所有发现的设备
  199. return Array.from(foundDevices).map(ipPort => ({
  200. id: ipPort,
  201. status: 'device'
  202. }));
  203. }
  204. // IPC 处理程序:获取 ADB 路径配置
  205. ipcMain.handle('get-adb-path-config', async () => {
  206. const config = loadConfig();
  207. return config ? config['adb-path'] : null;
  208. });
  209. // IPC 处理程序:获取 ADB 设备列表
  210. ipcMain.handle('get-adb-devices', async () => {
  211. return await getADBDevices();
  212. });
  213. // IPC 处理程序:扫描网络设备(支持实时推送)
  214. ipcMain.handle('scan-adb-devices', async (event) => {
  215. try {
  216. const devices = await scanNetworkDevices(event);
  217. return devices;
  218. } catch (error) {
  219. console.error('网络扫描失败:', error);
  220. return [];
  221. }
  222. });
  223. // IPC 处理程序:连接 ADB 设备
  224. ipcMain.handle('connect-adb-device', async (event, ipPort) => {
  225. try {
  226. const adbPath = getCachedAdbPath();
  227. await execAsync(`${adbPath} connect ${ipPort}`);
  228. return { success: true };
  229. } catch (error) {
  230. console.error('连接设备失败:', error);
  231. return { success: false, error: error.message };
  232. }
  233. });
  234. // IPC 处理程序:获取设备分辨率
  235. ipcMain.handle('get-device-resolution', async (event, ipPort) => {
  236. if (!ipPort) {
  237. return { success: false, error: '缺少设备 ID' };
  238. }
  239. try {
  240. // 使用 wm size 命令获取设备分辨率
  241. const adbPath = getCachedAdbPath();
  242. const { stdout } = await execAsync(`${adbPath} -s ${ipPort} shell wm size`);
  243. // 输出格式通常是: "Physical size: 1080x2400" 或 "1080x2400"
  244. const match = stdout.match(/(\d+)x(\d+)/);
  245. if (match) {
  246. return {
  247. success: true,
  248. width: parseInt(match[1], 10),
  249. height: parseInt(match[2], 10)
  250. };
  251. }
  252. // 如果解析失败,返回默认值
  253. return { success: true, width: 1280, height: 2400 };
  254. } catch (error) {
  255. console.error('获取设备分辨率失败:', error);
  256. // 返回默认值
  257. return { success: true, width: 1280, height: 2400 };
  258. }
  259. });
  260. // IPC 处理程序:抓取设备截屏(返回 base64 PNG/JPEG)
  261. ipcMain.handle('capture-screenshot', async (event, ipPort, options = {}) => {
  262. if (!ipPort) {
  263. return { success: false, error: '缺少设备 ID' };
  264. }
  265. try {
  266. const adbPath = getCachedAdbPath();
  267. // 从选项或默认值获取参数
  268. const format = options.format || 'png'; // 'png' 或 'jpeg'
  269. const quality = options.quality || 80; // JPEG 质量 1-100
  270. const scale = options.scale || 1.0; // 缩放比例 0.1-1.0
  271. // 构建 screencap 命令
  272. let command = `${adbPath} -s ${ipPort} exec-out screencap`;
  273. // 根据格式选择参数
  274. if (format === 'jpeg') {
  275. // JPEG 格式(更小,延迟更低)
  276. command += ` -j ${quality}`;
  277. } else {
  278. // PNG 格式(默认)
  279. command += ' -p';
  280. }
  281. // 如果缩放比例不是 1.0,需要通过 shell 命令处理
  282. // 注意:screencap 本身不支持缩放,需要通过其他方式实现
  283. // 这里先实现基本功能,缩放可以在后续优化
  284. const { stdout } = await execAsync(command, {
  285. encoding: 'buffer',
  286. maxBuffer: 25 * 1024 * 1024,
  287. });
  288. return { success: true, data: stdout.toString('base64') };
  289. } catch (error) {
  290. console.error('截屏失败:', error);
  291. return { success: false, error: error.message };
  292. }
  293. });
  294. // IPC 处理程序:发送 tap 事件到设备
  295. ipcMain.handle('send-tap', async (event, ipPort, x, y) => {
  296. if (!ipPort) {
  297. return { success: false, error: '缺少设备 ID' };
  298. }
  299. if (typeof x !== 'number' || typeof y !== 'number') {
  300. return { success: false, error: '坐标必须是数字' };
  301. }
  302. try {
  303. const adbPath = getCachedAdbPath();
  304. const command = `${adbPath} -s ${ipPort} shell input tap ${x} ${y}`;
  305. await execAsync(command, {
  306. timeout: 5000,
  307. maxBuffer: 1024 * 1024
  308. });
  309. return { success: true };
  310. } catch (error) {
  311. console.error('Tap 失败:', error.message);
  312. return { success: false, error: error.message };
  313. }
  314. });
  315. // IPC 处理程序:发送 swipe 事件到设备
  316. ipcMain.handle('send-swipe', async (event, ipPort, x1, y1, x2, y2, duration = 300) => {
  317. if (!ipPort) {
  318. return { success: false, error: '缺少设备 ID' };
  319. }
  320. if (typeof x1 !== 'number' || typeof y1 !== 'number' || typeof x2 !== 'number' || typeof y2 !== 'number') {
  321. return { success: false, error: '坐标必须是数字' };
  322. }
  323. try {
  324. const adbPath = getCachedAdbPath();
  325. const command = `${adbPath} -s ${ipPort} shell input swipe ${x1} ${y1} ${x2} ${y2} ${duration}`;
  326. await execAsync(command, {
  327. timeout: 5000,
  328. maxBuffer: 1024 * 1024
  329. });
  330. return { success: true };
  331. } catch (error) {
  332. console.error('Swipe 失败:', error.message);
  333. return { success: false, error: error.message };
  334. }
  335. });
  336. // IPC 处理程序:发送文字到设备
  337. ipcMain.handle('send-text', async (event, ipPort, text) => {
  338. if (!ipPort) {
  339. return { success: false, error: '缺少设备 ID' };
  340. }
  341. if (typeof text !== 'string') {
  342. return { success: false, error: '文字必须是字符串' };
  343. }
  344. try {
  345. const adbPath = getCachedAdbPath();
  346. // ADB input text 需要转义特殊字符
  347. // 使用单引号包裹,并转义单引号
  348. const escapedText = text
  349. .replace(/\\/g, '\\\\') // 先转义反斜杠
  350. .replace(/'/g, "'\\''") // 转义单引号
  351. .replace(/ /g, '%s') // 空格转换为 %s
  352. .replace(/&/g, '\\&') // 转义 &
  353. .replace(/</g, '\\<') // 转义 <
  354. .replace(/>/g, '\\>') // 转义 >
  355. .replace(/\(/g, '\\(') // 转义 (
  356. .replace(/\)/g, '\\)') // 转义 )
  357. .replace(/;/g, '\\;') // 转义 ;
  358. .replace(/\|/g, '\\|') // 转义 |
  359. .replace(/\*/g, '\\*') // 转义 *
  360. .replace(/\?/g, '\\?') // 转义 ?
  361. .replace(/`/g, '\\`') // 转义 `
  362. .replace(/\$/g, '\\$') // 转义 $
  363. .replace(/"/g, '\\"'); // 转义 "
  364. // 对于换行,使用 KEYCODE_ENTER
  365. if (text.includes('\n')) {
  366. // 如果有换行,分段发送
  367. const lines = text.split('\n');
  368. for (let i = 0; i < lines.length; i++) {
  369. if (lines[i]) {
  370. const escapedLine = lines[i]
  371. .replace(/\\/g, '\\\\')
  372. .replace(/'/g, "'\\''")
  373. .replace(/ /g, '%s')
  374. .replace(/&/g, '\\&')
  375. .replace(/</g, '\\<')
  376. .replace(/>/g, '\\>')
  377. .replace(/\(/g, '\\(')
  378. .replace(/\)/g, '\\)')
  379. .replace(/;/g, '\\;')
  380. .replace(/\|/g, '\\|')
  381. .replace(/\*/g, '\\*')
  382. .replace(/\?/g, '\\?')
  383. .replace(/`/g, '\\`')
  384. .replace(/\$/g, '\\$')
  385. .replace(/"/g, '\\"');
  386. await execAsync(`${adbPath} -s ${ipPort} shell input text "${escapedLine}"`, {
  387. timeout: 5000,
  388. maxBuffer: 1024 * 1024
  389. });
  390. }
  391. // 发送换行(除了最后一行)
  392. if (i < lines.length - 1) {
  393. await execAsync(`${adbPath} -s ${ipPort} shell input keyevent KEYCODE_ENTER`, {
  394. timeout: 5000,
  395. maxBuffer: 1024 * 1024
  396. });
  397. }
  398. }
  399. } else {
  400. // 没有换行,直接发送
  401. const command = `${adbPath} -s ${ipPort} shell input text "${escapedText}"`;
  402. await execAsync(command, {
  403. timeout: 5000,
  404. maxBuffer: 1024 * 1024
  405. });
  406. }
  407. return { success: true };
  408. } catch (error) {
  409. console.error('发送文字失败:', error.message);
  410. return { success: false, error: error.message };
  411. }
  412. });
  413. // IPC 处理程序:发送按键事件到设备
  414. ipcMain.handle('send-key-event', async (event, ipPort, keyCode) => {
  415. if (!ipPort) {
  416. return { success: false, error: '缺少设备 ID' };
  417. }
  418. if (typeof keyCode !== 'string') {
  419. return { success: false, error: '按键代码必须是字符串' };
  420. }
  421. try {
  422. const adbPath = getCachedAdbPath();
  423. const command = `${adbPath} -s ${ipPort} shell input keyevent ${keyCode}`;
  424. await execAsync(command, {
  425. timeout: 5000,
  426. maxBuffer: 1024 * 1024
  427. });
  428. return { success: true };
  429. } catch (error) {
  430. console.error('发送按键失败:', error.message);
  431. return { success: false, error: error.message };
  432. }
  433. });
  434. // 应用启动逻辑:设置 CSP、创建窗口、监听激活事件
  435. app.whenReady().then(() => {
  436. setContentSecurityPolicy();
  437. createWindow();
  438. app.on('activate', () => {
  439. if (BrowserWindow.getAllWindows().length === 0) {
  440. createWindow();
  441. }
  442. });
  443. // 禁用 before-quit 事件的确认对话框
  444. app.on('before-quit', (event) => {
  445. // 不阻止退出,直接退出应用
  446. // 如果需要清理资源,可以在这里添加
  447. });
  448. });
  449. // 应用关闭逻辑:macOS 保持运行,其他平台退出
  450. app.on('window-all-closed', () => {
  451. if (process.platform !== 'darwin') {
  452. // 直接退出,不询问
  453. app.exit(0);
  454. }
  455. });