main.js 14 KB

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