You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
2.8 KiB
Go

package device
import (
"autogo/controllers"
"autogo/dbsql"
"autogo/models"
"net/http"
"os/exec"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"github.com/spf13/cast"
)
// @Tags 设备相关 /api/device/v1/
// @Summary 安装应用
// @Description 传入安装包链接并指定设备安装
// @accept x-www-form-urlencoded
// @Param udid formData string true "设备udid"
// @Param pf formData string true "安装平台"
// @Param pkg_url formData string true "安装包下载链接"
// @Success 200 {object} models.Response "返回结果"
// @Router /api/device/v1/opt/install [post]
func InstallApp(c *gin.Context) {
rsp := controllers.NewResponse()
udid := c.PostForm("udid") // 获取 udid 参数
pf := c.PostForm("pf") // 获取 pf 参数
pkg_url := c.PostForm("pkg_url") // 获取 pkg_url 参数
if udid == "" {
rsp.Error("参数udid错误:" + udid)
c.JSON(http.StatusOK, rsp)
return
}
if pf == "" {
rsp.Error("参数pf错误:" + pf)
c.JSON(http.StatusOK, rsp)
return
}
if pkg_url == "" {
rsp.Error("参数pkgUrl错误:" + pkg_url)
c.JSON(http.StatusOK, rsp)
return
}
db, err := dbsql.GetConn(dbsql.DSN)
if err != nil {
rsp.Error(err.Error())
c.JSON(http.StatusOK, rsp)
}
defer dbsql.Close(db)
var device models.Device
db.Model(models.Device{}).Where("udid = ?", udid).Find(&device)
if device.ID < 1 {
rsp.Error("找不到该设备:" + udid)
c.JSON(http.StatusOK, rsp)
return
}
if device.Status == "offline" {
rsp.Error("设备不在线:" + udid)
c.JSON(http.StatusOK, rsp)
return
}
if device.Status == "busy" {
rsp.Error("设备正在被占用,无法执行安装操作")
c.JSON(http.StatusOK, rsp)
return
}
if pf == "adr" {
// 下载app到服务器
go DownloadAndInstallApp(udid, pkg_url)
} else {
rsp.Error("未支持的平台:" + pf)
c.JSON(http.StatusOK, rsp)
return
}
rsp.Success()
rsp.Data = "已执行"
c.JSON(http.StatusOK, rsp)
}
func DownloadAndInstallApp(udid, pkg_url string) error {
pkg_path := "/home/tmp/pkg/" + cast.ToString(time.Now().Unix()) + ".apk"
log.Debug("正在下载:", pkg_url)
err := exec.Command("wget", pkg_url, "-O", pkg_path).Run()
if err != nil {
log.Error(err)
return err
}
log.Debug("下载完毕,路径:", pkg_path)
err = AdbInstall(udid, pkg_path)
if err != nil {
log.Error(err)
return err
}
return nil
}
func AdbInstall(udid, filepath string) error {
// 通过 adb 安装 APK
cmd := exec.Command("adb", "-s", udid, "install", "-r", filepath)
output, err := cmd.CombinedOutput()
if err != nil {
log.Error("安装失败:", err)
return err
}
log.Debug("安装成功:", string(output))
return nil
}