visualagent-daemon.sh 8.2 KB
#!/data/data/com.termux/files/usr/bin/bash
# VisualAgent 后台服务脚本
# 监控 /sdcard/VisualAgent/commands/ 目录并执行命令
#
# 用法:
#   bash visualagent-daemon.sh start    # 启动后台监控服务
#   bash visualagent-daemon.sh stop     # 停止后台监控服务
#   bash visualagent-daemon.sh once     # 单次执行(适合 cron)
#   bash visualagent-daemon.sh file <路径>  # 处理单个文件
#
# 命令文件格式 (JSON):
#   {"command": "screenshot", "filename": "test.png"}
#   {"command": "tap", "x": 500, "y": 500}
#   {"command": "swipe", "x1": 500, "y1": 1000, "x2": 500, "y2": 200, "duration": 500}
#   {"command": "input", "text": "Hello World"}
#   {"command": "start_app", "package": "com.google.android.calculator"}
#
# 也支持 "type" 字段替代 "command"

COMMANDS_DIR="/sdcard/VisualAgent/commands/"
RESULTS_DIR="/sdcard/VisualAgent/results/"
PROCESSED_DIR="/sdcard/VisualAgent/processed/"
PROCESSED_FILES="/sdcard/VisualAgent/.processed_files"
LOG_FILE="/sdcard/VisualAgent/daemon.log"

# 初始化目录
init_dirs() {
    su -c "mkdir -p $COMMANDS_DIR $RESULTS_DIR $PROCESSED_DIR"
    su -c "touch $PROCESSED_FILES"
}

# 日志函数
log() {
    local msg="[$(date '+%Y-%m-%d %H:%M:%S')] $1"
    echo "$msg"
    su -c "echo '$msg' >> $LOG_FILE"
}

# 检查是否已处理
is_processed() {
    local filename="$1"
    local filepath="$2"
    
    # 先检查是否在 processed 目录中
    if su -c "test -f '$PROCESSED_DIR$filename'"; then
        return 0
    fi
    
    # 再检查 processed_files 记录
    su -c "grep -Fx '$filename' $PROCESSED_FILES" > /dev/null 2>&1
    return $?
}

# 标记为已处理
mark_processed() {
    local filepath="$1"
    local filename="$2"
    su -c "mv '$filepath' $PROCESSED_DIR$filename"
    su -c "echo '$filename' >> $PROCESSED_FILES"
}

# 执行命令
execute_command() {
    local cmd_file="$1"
    local filename="$2"
    
    # 读取 JSON
    local content
    content=$(su -c "cat '$cmd_file'")
    
    if [ -z "$content" ]; then
        log "ERROR: 无法读取文件 $filename"
        return 1
    fi
    
    # 解析命令类型(支持 command 和 type 两种字段)
    local cmd_type
    cmd_type=$(echo "$content" | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    print(d.get('command', d.get('type', 'unknown')))
except:
    print('unknown')
" 2>/dev/null)
    
    if [ -z "$cmd_type" ] || [ "$cmd_type" = "unknown" ]; then
        log "ERROR: 无法解析命令类型: $filename"
        return 1
    fi
    
    log "执行命令: $cmd_type (文件: $filename)"
    
    local result="{}"
    local timestamp
    timestamp=$(date +%s)
    
    case "$cmd_type" in
        screenshot)
            local screenshot_file="/sdcard/VisualAgent/results/screenshot_${timestamp}.png"
            if su -c "screencap -p '$screenshot_file'"; then
                result="{\"success\":true,\"type\":\"screenshot\",\"path\":\"$screenshot_file\",\"timestamp\":$timestamp}"
            else
                result="{\"success\":false,\"type\":\"screenshot\",\"error\":\"截图失败\",\"timestamp\":$timestamp}"
            fi
            ;;
        
        tap)
            local x y
            x=$(echo "$content" | python3 -c "import sys,json; print(json.load(sys.stdin).get('x', 0))")
            y=$(echo "$content" | python3 -c "import sys,json; print(json.load(sys.stdin).get('y', 0))")
            if su -c "input tap $x $y"; then
                result="{\"success\":true,\"type\":\"tap\",\"x\":$x,\"y\":$y,\"timestamp\":$timestamp}"
            else
                result="{\"success\":false,\"type\":\"tap\",\"error\":\"点击失败\",\"timestamp\":$timestamp}"
            fi
            ;;
        
        swipe)
            local x1 y1 x2 y2 duration
            x1=$(echo "$content" | python3 -c "import sys,json; print(json.load(sys.stdin).get('x1', 0))")
            y1=$(echo "$content" | python3 -c "import sys,json; print(json.load(sys.stdin).get('y1', 0))")
            x2=$(echo "$content" | python3 -c "import sys,json; print(json.load(sys.stdin).get('x2', 0))")
            y2=$(echo "$content" | python3 -c "import sys,json; print(json.load(sys.stdin).get('y2', 0))")
            duration=$(echo "$content" | python3 -c "import sys,json; print(json.load(sys.stdin).get('duration', 300))")
            if su -c "input swipe $x1 $y1 $x2 $y2 $duration"; then
                result="{\"success\":true,\"type\":\"swipe\",\"x1\":$x1,\"y1\":$y1,\"x2\":$x2,\"y2\":$y2,\"duration\":$duration,\"timestamp\":$timestamp}"
            else
                result="{\"success\":false,\"type\":\"swipe\",\"error\":\"滑动失败\",\"timestamp\":$timestamp}"
            fi
            ;;
        
        input)
            local text
            text=$(echo "$content" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('text', d.get('input', '')))")
            # 转义单引号
            local safe_text
            safe_text=$(echo "$text" | sed "s/'/'\\''/g")
            if su -c "input text '$safe_text'"; then
                result="{\"success\":true,\"type\":\"input\",\"text\":\"$text\",\"timestamp\":$timestamp}"
            else
                result="{\"success\":false,\"type\":\"input\",\"error\":\"输入失败\",\"timestamp\":$timestamp}"
            fi
            ;;
        
        start_app)
            local package
            package=$(echo "$content" | python3 -c "import sys,json; print(json.load(sys.stdin).get('package', ''))")
            if su -c "monkey -p $package -c android.intent.category.LAUNCHER 1"; then
                result="{\"success\":true,\"type\":\"start_app\",\"package\":\"$package\",\"timestamp\":$timestamp}"
            else
                result="{\"success\":false,\"type\":\"start_app\",\"error\":\"启动应用失败\",\"timestamp\":$timestamp}"
            fi
            ;;
        
        *)
            result="{\"success\":false,\"type\":\"unknown\",\"error\":\"未知命令: $cmd_type\",\"timestamp\":$timestamp}"
            ;;
    esac
    
    # 保存结果
    local result_file="/sdcard/VisualAgent/results/result_${filename}"
    su -c "echo '$result' > '$result_file'"
    log "结果已保存: $result_file"
    
    return 0
}

# 单次执行函数
run_once() {
    init_dirs
    log "单次执行模式"
    
    # 使用 find 查找 JSON 文件(更可靠,避免 glob 扩展问题)
    local files
    files=$(su -c "find $COMMANDS_DIR -maxdepth 1 -name '*.json' -type f 2>/dev/null")
    if [ -n "$files" ]; then
        for filepath in $files; do
            local filename
            filename=$(basename "$filepath")
            if ! is_processed "$filename" "$filepath"; then
                execute_command "$filepath" "$filename"
                mark_processed "$filepath" "$filename"
            fi
        done
    else
        log "没有新的命令文件"
    fi
}

# 直接处理单个文件(用于 cron 直接传入文件路径)
process_single_file() {
    local filepath="$1"
    local filename
    filename=$(basename "$filepath")
    
    if ! is_processed "$filename" "$filepath"; then
        execute_command "$filepath" "$filename"
        mark_processed "$filepath" "$filename"
    fi
}

# 主循环
main_loop() {
    init_dirs
    log "VisualAgent 服务启动"
    
    while true; do
        run_once
        # 等待 5 秒
        sleep 5
    done
}

# 启动
case "${1:-}" in
    start)
        main_loop &
        echo $! > /sdcard/VisualAgent/daemon.pid
        log "后台进程已启动 (PID: $!)"
        ;;
    stop)
        if [ -f /sdcard/VisualAgent/daemon.pid ]; then
            kill "$(cat /sdcard/VisualAgent/daemon.pid)" 2>/dev/null
            rm -f /sdcard/VisualAgent/daemon.pid
            log "服务已停止"
        fi
        ;;
    once)
        # 单次执行模式(用于 cron)
        run_once
        ;;
    file)
        # 处理单个文件
        if [ -n "${2:-}" ]; then
            process_single_file "$2"
        else
            echo "用法: $0 file <文件路径>"
        fi
        ;;
    *)
        echo "用法: $0 {start|stop|once|file}"
        echo "  start - 启动后台监控服务"
        echo "  stop  - 停止后台监控服务"
        echo "  once  - 单次执行(适合 cron)"
        echo "  file  - 处理单个文件: $0 file <文件路径>"
        ;;
esac