| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- #!/usr/bin/env node
- /**
- * 通过 ADB 将本地图片推送到手机并加入相册(1+ 等 Android 通用)
- * 用法: node send-img-to-device.js <本地图片路径> [deviceId]
- * 或 require 后调用: sendImageToDevice(localPath, deviceId) => { success, error }
- */
- const { spawnSync } = require('child_process')
- const path = require('path')
- const fs = require('fs')
- const configPath = process.env.STATIC_ROOT
- ? path.join(path.dirname(process.env.STATIC_ROOT), 'configs', 'config.js')
- : path.join(__dirname, '..', '..', 'configs', 'config.js')
- const projectRoot = path.dirname(path.dirname(path.resolve(configPath)))
- const config = fs.existsSync(configPath) ? require(configPath) : {}
- const adbPath = config.adbPath?.path
- ? (path.isAbsolute(config.adbPath.path) ? config.adbPath.path : path.resolve(projectRoot, config.adbPath.path))
- : path.join(projectRoot, 'lib', 'scrcpy-adb', process.platform === 'win32' ? 'adb.exe' : 'adb')
- /** 设备 DCIM 目录,相册会扫描此处 */
- const DEVICE_DCIM = '/sdcard/DCIM/'
- /**
- * 将本地图片推送到设备相册
- * @param {string} localPath - 本地图片绝对或相对路径
- * @param {string} [deviceId] - 设备 ID,如 192.168.42.129 或 192.168.42.129:5555
- * @returns {{ success: boolean, error?: string, devicePath?: string }}
- */
- function sendImageToDevice(localPath, deviceId = '') {
- const resolved = path.resolve(localPath)
- if (!fs.existsSync(resolved)) {
- return { success: false, error: `本地文件不存在: ${resolved}` }
- }
- const basename = path.basename(resolved)
- const deviceFile = DEVICE_DCIM + basename
- const args = deviceId ? ['-s', deviceId, 'push', resolved, deviceFile] : ['push', resolved, deviceFile]
- const push = spawnSync(adbPath, args, { encoding: 'utf-8', timeout: 30000 })
- if (push.status !== 0) {
- const err = (push.stderr || push.stdout || '').trim() || `adb push 退出码 ${push.status}`
- return { success: false, error: err }
- }
- const scanArgs = deviceId ? ['-s', deviceId, 'shell', 'am', 'broadcast', '-a', 'android.intent.action.MEDIA_SCANNER_SCAN_FILE', '-d', `file://${deviceFile}`] : ['shell', 'am', 'broadcast', '-a', 'android.intent.action.MEDIA_SCANNER_SCAN_FILE', '-d', `file://${deviceFile}`]
- spawnSync(adbPath, scanArgs, { encoding: 'utf-8', timeout: 5000 })
- return { success: true, devicePath: deviceFile }
- }
- if (require.main === module) {
- const localPath = process.argv[2]
- const deviceId = process.argv[3] || ''
- if (!localPath) {
- console.error('用法: node send-img-to-device.js <本地图片路径> [deviceId]')
- process.exit(1)
- }
- const result = sendImageToDevice(localPath, deviceId)
- if (result.success) {
- console.log(result.devicePath || 'ok')
- } else {
- console.error(result.error)
- process.exit(1)
- }
- }
- module.exports = { sendImageToDevice }
|