main.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. if (isDev) {
  96. mainWindow.loadURL('http://localhost:5173');
  97. mainWindow.webContents.openDevTools();
  98. } else {
  99. mainWindow.loadFile(path.join(__dirname, 'dist/index.html'));
  100. }
  101. }
  102. // 获取已连接的 ADB 设备列表
  103. async function getADBDevices() {
  104. try {
  105. const adbPath = getCachedAdbPath();
  106. const { stdout } = await execAsync(`${adbPath} devices`);
  107. const lines = stdout.split('\n').slice(1);
  108. const devices = [];
  109. for (const line of lines) {
  110. const parts = line.trim().split(/\s+/);
  111. if (parts.length >= 2 && parts[0] && parts[1] === 'device') {
  112. devices.push({
  113. id: parts[0],
  114. status: parts[1]
  115. });
  116. }
  117. }
  118. return devices;
  119. } catch (error) {
  120. console.error('获取设备列表失败:', error);
  121. return [];
  122. }
  123. }
  124. // 网络扫描:从 192.168.0.1 开始扫描网段,尝试连接设备(实时推送结果)
  125. async function scanNetworkDevices(event) {
  126. const adbPath = getCachedAdbPath();
  127. const baseIP = '192.168.0';
  128. const port = 5555;
  129. const maxConcurrent = 20; // 限制并发数,避免过载
  130. const connectTimeout = 1500; // 连接超时时间(毫秒)
  131. // 生成 IP 地址列表
  132. const ipList = [];
  133. for (let i = 1; i <= 255; i++) {
  134. ipList.push(`${baseIP}.${i}`);
  135. }
  136. const foundDevices = new Set(); // 使用 Set 避免重复
  137. // 分批并发扫描
  138. for (let i = 0; i < ipList.length; i += maxConcurrent) {
  139. const batch = ipList.slice(i, i + maxConcurrent);
  140. const promises = batch.map(async (ip) => {
  141. const ipPort = `${ip}:${port}`;
  142. try {
  143. // 先尝试连接设备
  144. await execAsync(`${adbPath} connect ${ipPort}`, {
  145. timeout: connectTimeout,
  146. maxBuffer: 1024 * 1024
  147. });
  148. // 连接后稍等片刻,让设备注册到 ADB 服务器
  149. await new Promise(resolve => setTimeout(resolve, 500));
  150. } catch (error) {
  151. // 连接失败是正常的,继续检查设备列表
  152. }
  153. // 直接使用 adb -s IP:PORT devices 命令检查该设备是否在列表中
  154. try {
  155. const { stdout } = await execAsync(`${adbPath} -s ${ipPort} devices`, {
  156. timeout: 2000,
  157. maxBuffer: 1024 * 1024
  158. });
  159. // 检查输出中是否包含 IP:PORT,如果有则说明设备存在
  160. if (stdout.includes(ipPort)) {
  161. // 发现设备,实时推送
  162. if (!foundDevices.has(ipPort)) {
  163. foundDevices.add(ipPort);
  164. const device = {
  165. id: ipPort,
  166. status: 'device'
  167. };
  168. // 实时发送发现的设备
  169. if (event && event.sender) {
  170. event.sender.send('device-found', device);
  171. } else if (mainWindow) {
  172. mainWindow.webContents.send('device-found', device);
  173. }
  174. console.log('发现设备:', ipPort);
  175. }
  176. return ipPort;
  177. }
  178. } catch (checkError) {
  179. // 检查失败,忽略
  180. }
  181. return null;
  182. });
  183. await Promise.all(promises);
  184. }
  185. // 返回所有发现的设备
  186. return Array.from(foundDevices).map(ipPort => ({
  187. id: ipPort,
  188. status: 'device'
  189. }));
  190. }
  191. // IPC 处理程序:获取 ADB 路径配置
  192. ipcMain.handle('get-adb-path-config', async () => {
  193. const config = loadConfig();
  194. return config ? config['adb-path'] : null;
  195. });
  196. // IPC 处理程序:获取 ADB 设备列表
  197. ipcMain.handle('get-adb-devices', async () => {
  198. return await getADBDevices();
  199. });
  200. // IPC 处理程序:扫描网络设备(支持实时推送)
  201. ipcMain.handle('scan-adb-devices', async (event) => {
  202. try {
  203. const devices = await scanNetworkDevices(event);
  204. return devices;
  205. } catch (error) {
  206. console.error('网络扫描失败:', error);
  207. return [];
  208. }
  209. });
  210. // IPC 处理程序:连接 ADB 设备
  211. ipcMain.handle('connect-adb-device', async (event, ipPort) => {
  212. try {
  213. const adbPath = getCachedAdbPath();
  214. await execAsync(`${adbPath} connect ${ipPort}`);
  215. return { success: true };
  216. } catch (error) {
  217. console.error('连接设备失败:', error);
  218. return { success: false, error: error.message };
  219. }
  220. });
  221. // IPC 处理程序:获取设备分辨率
  222. ipcMain.handle('get-device-resolution', async (event, ipPort) => {
  223. if (!ipPort) {
  224. return { success: false, error: '缺少设备 ID' };
  225. }
  226. try {
  227. // 使用 wm size 命令获取设备分辨率
  228. const adbPath = getCachedAdbPath();
  229. const { stdout } = await execAsync(`${adbPath} -s ${ipPort} shell wm size`);
  230. // 输出格式通常是: "Physical size: 1080x2400" 或 "1080x2400"
  231. const match = stdout.match(/(\d+)x(\d+)/);
  232. if (match) {
  233. return {
  234. success: true,
  235. width: parseInt(match[1], 10),
  236. height: parseInt(match[2], 10)
  237. };
  238. }
  239. // 如果解析失败,返回默认值
  240. return { success: true, width: 1280, height: 2400 };
  241. } catch (error) {
  242. console.error('获取设备分辨率失败:', error);
  243. // 返回默认值
  244. return { success: true, width: 1280, height: 2400 };
  245. }
  246. });
  247. // IPC 处理程序:抓取设备截屏(返回 base64 PNG/JPEG)
  248. ipcMain.handle('capture-screenshot', async (event, ipPort, options = {}) => {
  249. if (!ipPort) {
  250. return { success: false, error: '缺少设备 ID' };
  251. }
  252. try {
  253. const adbPath = getCachedAdbPath();
  254. // 从选项或默认值获取参数
  255. const format = options.format || 'png'; // 'png' 或 'jpeg'
  256. const quality = options.quality || 80; // JPEG 质量 1-100
  257. const scale = options.scale || 1.0; // 缩放比例 0.1-1.0
  258. // 构建 screencap 命令
  259. let command = `${adbPath} -s ${ipPort} exec-out screencap`;
  260. // 根据格式选择参数
  261. if (format === 'jpeg') {
  262. // JPEG 格式(更小,延迟更低)
  263. command += ` -j ${quality}`;
  264. } else {
  265. // PNG 格式(默认)
  266. command += ' -p';
  267. }
  268. // 如果缩放比例不是 1.0,需要通过 shell 命令处理
  269. // 注意:screencap 本身不支持缩放,需要通过其他方式实现
  270. // 这里先实现基本功能,缩放可以在后续优化
  271. const { stdout } = await execAsync(command, {
  272. encoding: 'buffer',
  273. maxBuffer: 25 * 1024 * 1024,
  274. });
  275. return { success: true, data: stdout.toString('base64') };
  276. } catch (error) {
  277. console.error('截屏失败:', error);
  278. return { success: false, error: error.message };
  279. }
  280. });
  281. // IPC 处理程序:发送 tap 事件到设备
  282. ipcMain.handle('send-tap', async (event, ipPort, x, y) => {
  283. if (!ipPort) {
  284. return { success: false, error: '缺少设备 ID' };
  285. }
  286. if (typeof x !== 'number' || typeof y !== 'number') {
  287. return { success: false, error: '坐标必须是数字' };
  288. }
  289. try {
  290. const adbPath = getCachedAdbPath();
  291. const command = `${adbPath} -s ${ipPort} shell input tap ${x} ${y}`;
  292. await execAsync(command, {
  293. timeout: 5000,
  294. maxBuffer: 1024 * 1024
  295. });
  296. return { success: true };
  297. } catch (error) {
  298. console.error('Tap 失败:', error.message);
  299. return { success: false, error: error.message };
  300. }
  301. });
  302. // IPC 处理程序:发送 swipe 事件到设备
  303. ipcMain.handle('send-swipe', async (event, ipPort, x1, y1, x2, y2, duration = 300) => {
  304. if (!ipPort) {
  305. return { success: false, error: '缺少设备 ID' };
  306. }
  307. if (typeof x1 !== 'number' || typeof y1 !== 'number' || typeof x2 !== 'number' || typeof y2 !== 'number') {
  308. return { success: false, error: '坐标必须是数字' };
  309. }
  310. try {
  311. const adbPath = getCachedAdbPath();
  312. const command = `${adbPath} -s ${ipPort} shell input swipe ${x1} ${y1} ${x2} ${y2} ${duration}`;
  313. await execAsync(command, {
  314. timeout: 5000,
  315. maxBuffer: 1024 * 1024
  316. });
  317. return { success: true };
  318. } catch (error) {
  319. console.error('Swipe 失败:', error.message);
  320. return { success: false, error: error.message };
  321. }
  322. });
  323. // IPC 处理程序:发送文字到设备
  324. ipcMain.handle('send-text', async (event, ipPort, text) => {
  325. if (!ipPort) {
  326. return { success: false, error: '缺少设备 ID' };
  327. }
  328. if (typeof text !== 'string') {
  329. return { success: false, error: '文字必须是字符串' };
  330. }
  331. try {
  332. const adbPath = getCachedAdbPath();
  333. // ADB input text 需要转义特殊字符
  334. // 使用单引号包裹,并转义单引号
  335. const escapedText = text
  336. .replace(/\\/g, '\\\\') // 先转义反斜杠
  337. .replace(/'/g, "'\\''") // 转义单引号
  338. .replace(/ /g, '%s') // 空格转换为 %s
  339. .replace(/&/g, '\\&') // 转义 &
  340. .replace(/</g, '\\<') // 转义 <
  341. .replace(/>/g, '\\>') // 转义 >
  342. .replace(/\(/g, '\\(') // 转义 (
  343. .replace(/\)/g, '\\)') // 转义 )
  344. .replace(/;/g, '\\;') // 转义 ;
  345. .replace(/\|/g, '\\|') // 转义 |
  346. .replace(/\*/g, '\\*') // 转义 *
  347. .replace(/\?/g, '\\?') // 转义 ?
  348. .replace(/`/g, '\\`') // 转义 `
  349. .replace(/\$/g, '\\$') // 转义 $
  350. .replace(/"/g, '\\"'); // 转义 "
  351. // 对于换行,使用 KEYCODE_ENTER
  352. if (text.includes('\n')) {
  353. // 如果有换行,分段发送
  354. const lines = text.split('\n');
  355. for (let i = 0; i < lines.length; i++) {
  356. if (lines[i]) {
  357. const escapedLine = lines[i]
  358. .replace(/\\/g, '\\\\')
  359. .replace(/'/g, "'\\''")
  360. .replace(/ /g, '%s')
  361. .replace(/&/g, '\\&')
  362. .replace(/</g, '\\<')
  363. .replace(/>/g, '\\>')
  364. .replace(/\(/g, '\\(')
  365. .replace(/\)/g, '\\)')
  366. .replace(/;/g, '\\;')
  367. .replace(/\|/g, '\\|')
  368. .replace(/\*/g, '\\*')
  369. .replace(/\?/g, '\\?')
  370. .replace(/`/g, '\\`')
  371. .replace(/\$/g, '\\$')
  372. .replace(/"/g, '\\"');
  373. await execAsync(`${adbPath} -s ${ipPort} shell input text "${escapedLine}"`, {
  374. timeout: 5000,
  375. maxBuffer: 1024 * 1024
  376. });
  377. }
  378. // 发送换行(除了最后一行)
  379. if (i < lines.length - 1) {
  380. await execAsync(`${adbPath} -s ${ipPort} shell input keyevent KEYCODE_ENTER`, {
  381. timeout: 5000,
  382. maxBuffer: 1024 * 1024
  383. });
  384. }
  385. }
  386. } else {
  387. // 没有换行,直接发送
  388. const command = `${adbPath} -s ${ipPort} shell input text "${escapedText}"`;
  389. await execAsync(command, {
  390. timeout: 5000,
  391. maxBuffer: 1024 * 1024
  392. });
  393. }
  394. return { success: true };
  395. } catch (error) {
  396. console.error('发送文字失败:', error.message);
  397. return { success: false, error: error.message };
  398. }
  399. });
  400. // IPC 处理程序:发送按键事件到设备
  401. ipcMain.handle('send-key-event', async (event, ipPort, keyCode) => {
  402. if (!ipPort) {
  403. return { success: false, error: '缺少设备 ID' };
  404. }
  405. if (typeof keyCode !== 'string') {
  406. return { success: false, error: '按键代码必须是字符串' };
  407. }
  408. try {
  409. const adbPath = getCachedAdbPath();
  410. const command = `${adbPath} -s ${ipPort} shell input keyevent ${keyCode}`;
  411. await execAsync(command, {
  412. timeout: 5000,
  413. maxBuffer: 1024 * 1024
  414. });
  415. return { success: true };
  416. } catch (error) {
  417. console.error('发送按键失败:', error.message);
  418. return { success: false, error: error.message };
  419. }
  420. });
  421. // 应用启动逻辑:设置 CSP、创建窗口、监听激活事件
  422. app.whenReady().then(() => {
  423. setContentSecurityPolicy();
  424. createWindow();
  425. app.on('activate', () => {
  426. if (BrowserWindow.getAllWindows().length === 0) {
  427. createWindow();
  428. }
  429. });
  430. });
  431. // 应用关闭逻辑:macOS 保持运行,其他平台退出
  432. app.on('window-all-closed', () => {
  433. if (process.platform !== 'darwin') {
  434. app.quit();
  435. }
  436. });