Files
RemoteCompilation/server/adb.go
T
tongtong b46ebd1070 feat: 支持安装前后ADB命令与安装后启动应用
按工程保存前后置命令和自动启动选项,全程绑定选中设备,区分安装与后续动作失败。通过实际APK及目标设备解析Launcher入口,兼容activity-alias;增加模拟进程回归测试及0.8.0三套服务部署记录。
2026-11-27 16:26:03 +08:00

209 lines
5.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"bytes"
"context"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
type adbDevice struct {
Serial string `json:"serial"`
State string `json:"state"`
Model string `json:"model"`
}
var adbInstallLock sync.Mutex
func parseADBDevices(output string) []adbDevice {
devices := []adbDevice{}
for _, line := range strings.Split(output, "\n") {
fields := strings.Fields(line)
if len(fields) < 2 || (fields[1] != "device" && fields[1] != "offline" && fields[1] != "unauthorized") {
continue
}
d := adbDevice{Serial: fields[0], State: fields[1]}
for _, field := range fields[2:] {
if strings.HasPrefix(field, "model:") {
d.Model = strings.ReplaceAll(strings.TrimPrefix(field, "model:"), "_", " ")
}
}
devices = append(devices, d)
}
return devices
}
type adbOutput struct{ bytes.Buffer }
func (b *adbOutput) Write(p []byte) (int, error) {
n := len(p)
left := 64*1024 - b.Len()
if left > 0 {
if left > n {
left = n
}
_, _ = b.Buffer.Write(p[:left])
}
return n, nil
}
func (s *Server) adbCommand(ctx context.Context, args ...string) (string, error) {
cfg, e := s.buildEnvironment()
if e != nil {
return "", e
}
binary := cfg.Adb
if binary == "" {
name := "adb"
if runtime.GOOS == "windows" {
name += ".exe"
}
if cfg.AndroidHome != "" {
candidate := filepath.Join(cfg.AndroidHome, "platform-tools", name)
if st, e := os.Stat(candidate); e == nil && !st.IsDir() {
binary = candidate
}
}
if binary == "" {
binary, e = exec.LookPath(name)
if e != nil {
return "", fmt.Errorf("服务账户找不到adb:请安装SDK platform-tools,或在build-environment.json的adb字段配置可执行文件绝对路径")
}
}
}
cmd := exec.CommandContext(ctx, binary, args...)
var output adbOutput
cmd.Stdout = &output
cmd.Stderr = &output
e = cmd.Run()
if ctx.Err() != nil {
return output.String(), fmt.Errorf("服务端adb超时或请求取消;安装结果尚未确认,请检查设备")
}
if e != nil {
return output.String(), fmt.Errorf("服务端adb失败:%w;%s", e, output.String())
}
return output.String(), nil
}
func (s *Server) serveADB(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/v1/adb/devices" && r.Method == "GET" {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
out, e := s.adbCommand(ctx, "devices", "-l")
if e != nil {
http.Error(w, e.Error(), 400)
return
}
jsonOut(w, map[string]any{"devices": parseADBDevices(out)})
return
}
if r.URL.Path != "/api/v1/adb/install" || r.Method != "POST" {
http.NotFound(w, r)
return
}
var req struct {
BuildID string `json:"buildId"`
Artifact string `json:"artifact"`
Serial string `json:"serial"`
BeforeCommands string `json:"beforeCommands"`
AfterCommands string `json:"afterCommands"`
LaunchAfter bool `json:"launchAfter"`
}
if e := decode(w, r, &req); e != nil {
http.Error(w, e.Error(), 400)
return
}
before, err := parseInstallCommands(req.BeforeCommands)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
after, err := parseInstallCommands(req.AfterCommands)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
if req.Serial == "" || strings.HasPrefix(req.Serial, "-") || strings.ContainsAny(req.Serial, " \t\r\n\x00") {
http.Error(w, "请选择服务端在线且已授权的设备", 400)
return
}
s.mu.Lock()
b := s.builds[req.BuildID]
var chosen *Artifact
if b != nil && b.Status == "success" {
for _, a := range b.Artifacts {
if a.Name == req.Artifact && strings.HasSuffix(strings.ToLower(a.Name), ".apk") {
v := a
chosen = &v
break
}
}
}
s.mu.Unlock()
if chosen == nil {
http.Error(w, "只能安装成功构建中已保存的APK,请选择正确的构建及产物", 400)
return
}
if !adbInstallLock.TryLock() {
http.Error(w, "服务端正在安装,请稍后重试", 409)
return
}
defer adbInstallLock.Unlock()
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Minute)
defer cancel()
out, e := s.adbCommand(ctx, "devices", "-l")
if e != nil {
http.Error(w, e.Error(), 400)
return
}
online := false
for _, d := range parseADBDevices(out) {
if d.Serial == req.Serial && d.State == "device" {
online = true
}
}
if !online {
http.Error(w, "所选服务端设备已离线或未授权,请刷新设备列表;不会自动安装到其他设备", 409)
return
}
path := filepath.Join(s.root, "artifacts", req.BuildID, chosen.Name)
data, e := os.ReadFile(path)
if e != nil || int64(len(data)) != chosen.Size || digest(data) != chosen.Hash {
http.Error(w, "服务端APK缺失或摘要校验失败,请重新构建", 409)
return
}
var log strings.Builder
if e = s.runInstallCommands(ctx, req.Serial, "安装前", before, &log); e != nil {
http.Error(w, log.String()+"\n"+e.Error(), 400)
return
}
log.WriteString("[安装APK] adb -s " + req.Serial + " install -r\n")
installCtx, installCancel := context.WithTimeout(ctx, 2*time.Minute)
out, e = s.adbCommand(installCtx, "-s", req.Serial, "install", "-r", path)
installCancel()
log.WriteString(out)
if e != nil {
http.Error(w, log.String()+"\n"+e.Error(), 400)
return
}
if !strings.Contains(out, "Success") {
http.Error(w, "ADB未确认安装成功:"+out, 400)
return
}
postError := s.runInstallCommands(ctx, req.Serial, "安装后", after, &log)
if postError == nil && req.LaunchAfter {
postError = s.launchInstalledAPK(ctx, req.Serial, path, &log)
}
if postError != nil {
log.WriteString("\n安装已成功,后续操作未完成:" + postError.Error())
}
jsonOut(w, map[string]any{"success": true, "serial": req.Serial, "output": log.String(), "postActionsSuccess": postError == nil})
}