runtime-api.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * 运行时 API:设备操作(adb)、日志、桩函数
  3. */
  4. const path = require('path')
  5. const fs = require('fs')
  6. const { spawnSync } = require('child_process')
  7. const config = require('./compiler-config.js')
  8. const { sendSystemButton } = require(path.join(config.projectRoot, 'nodejs', 'adb', 'adb-sys-btn.js'))
  9. function runAdb(action, args = [], deviceId = '') {
  10. const r = spawnSync('node', [config.adbInteractPath, action, ...args, deviceId], { encoding: 'utf-8', timeout: 10000 })
  11. return { success: r.status === 0, error: r.stderr }
  12. }
  13. const sendTap = (device, x, y) => runAdb('tap', [String(x), String(y)], device)
  14. const sendSwipe = (device, x1, y1, x2, y2, duration) =>
  15. runAdb('swipe-coords', [String(x1), String(y1), String(x2), String(y2), String(duration || 300)], device)
  16. const sendKeyEvent = (device, keyCode) => runAdb('keyevent', [String(keyCode)], device)
  17. const sendText = (device, text) => runAdb('text', [String(text)], device)
  18. function appendLog(folderPath, message) {
  19. if (!folderPath || typeof folderPath !== 'string') return Promise.resolve()
  20. const logDir = path.resolve(folderPath)
  21. const logFile = path.join(logDir, 'log.txt')
  22. fs.mkdirSync(logDir, { recursive: true })
  23. fs.appendFileSync(logFile, message + '\n')
  24. return Promise.resolve()
  25. }
  26. const _stub = (name) => ({ success: false, error: `${name} 需在主进程实现` })
  27. function createElectronAPI(overrides = {}) {
  28. return {
  29. sendTap,
  30. sendSwipe,
  31. sendKeyEvent,
  32. sendText,
  33. sendSystemKey: (device, keyCode) => sendSystemButton(String(keyCode), device),
  34. matchImageAndGetCoordinate: null,
  35. findTextAndGetCoordinate: () => _stub('findTextAndGetCoordinate'),
  36. appendLog,
  37. readTextFile: null,
  38. writeTextFile: null,
  39. saveChatHistory: () => _stub('saveChatHistory'),
  40. readChatHistory: () => _stub('readChatHistory'),
  41. readAllChatHistory: () => _stub('readAllChatHistory'),
  42. saveChatHistorySummary: () => _stub('saveChatHistorySummary'),
  43. getChatHistorySummary: () => _stub('getChatHistorySummary'),
  44. saveChatHistoryTxt: () => _stub('saveChatHistoryTxt'),
  45. extractChatHistory: () => _stub('extractChatHistory'),
  46. readLastMessage: () => _stub('readLastMessage'),
  47. ocrLastMessage: () => _stub('ocrLastMessage'),
  48. getCachedScreenshot: () => _stub('getCachedScreenshot'),
  49. captureScreenshot: () => _stub('captureScreenshot'),
  50. sendScroll: () => _stub('sendScroll'),
  51. matchImageRegionLocation: () => _stub('matchImageRegionLocation'),
  52. ...overrides,
  53. }
  54. }
  55. module.exports = {
  56. runAdb,
  57. sendTap,
  58. sendSwipe,
  59. sendKeyEvent,
  60. sendText,
  61. appendLog,
  62. createElectronAPI,
  63. }