change: server

This commit is contained in:
lilong.129 2025-02-18 20:22:07 +08:00
parent 5d91b69603
commit 7183eae486
10 changed files with 570 additions and 465 deletions

View File

@ -1 +1 @@
v5.0.0+2502181933
v5.0.0+2502182022

View File

@ -1,112 +1,121 @@
package server
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/httprunner/httprunner/v5/code"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v5/pkg/uixt"
)
func foregroundAppHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
driver, err := GetDriver(c)
if err != nil {
return
}
appInfo, err := driver.ForegroundInfo()
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, appInfo)
}
appInfo, err := dExt.ForegroundInfo()
if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to unlick screen", c.HandlerName()))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
func appInfoHandler(c *gin.Context) {
var appInfoReq AppInfoRequest
if err := c.ShouldBindQuery(&appInfoReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
device, err := GetDevice(c)
if err != nil {
return
}
if androidDevice, ok := device.(*uixt.AndroidDevice); ok {
appInfo, err := androidDevice.GetAppInfo(appInfoReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, appInfo)
return
} else if iOSDevice, ok := device.(*uixt.IOSDevice); ok {
appInfo, err := iOSDevice.GetAppInfo(appInfoReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, appInfo)
return
}
c.JSON(http.StatusOK, HttpResponse{Result: appInfo})
}
func clearAppHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
if err != nil {
return
}
var appClearReq AppClearRequest
if err := c.ShouldBindJSON(&appClearReq); err != nil {
handlerValidateRequestFailedContext(c, err)
RenderErrorValidateRequest(c, err)
return
}
err = dExt.AppClear(appClearReq.PackageName)
driver, err := GetDriver(c)
if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to unlick screen", c.HandlerName()))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
err = driver.IDriver.(*uixt.ADBDriver).AppClear(appClearReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
func launchAppHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
if err != nil {
return
}
var appLaunchReq AppLaunchRequest
if err := c.ShouldBindJSON(&appLaunchReq); err != nil {
handlerValidateRequestFailedContext(c, err)
RenderErrorValidateRequest(c, err)
return
}
err = dExt.AppLaunch(appLaunchReq.PackageName)
driver, err := GetDriver(c)
if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to launch app %s", c.HandlerName(), appLaunchReq.PackageName))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
err = driver.AppLaunch(appLaunchReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
func terminalAppHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
var appTerminalReq AppTerminalRequest
if err := c.ShouldBindJSON(&appTerminalReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
if err != nil {
return
}
var appTerminalReq AppTerminalRequest
if err := c.ShouldBindJSON(&appTerminalReq); err != nil {
handlerValidateRequestFailedContext(c, err)
_, err = driver.AppTerminate(appTerminalReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
success, err := dExt.AppTerminate(appTerminalReq.PackageName)
if !success {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to launch app %s", c.HandlerName(), appTerminalReq.PackageName))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
RenderSuccess(c, true)
}
func uninstallAppHandler(c *gin.Context) {
var appUninstallReq AppUninstallRequest
if err := c.ShouldBindJSON(&appUninstallReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
if err != nil {
return
}
err = driver.GetDevice().Uninstall(appUninstallReq.PackageName)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}

View File

@ -14,99 +14,101 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
)
var uiClients = make(map[string]*uixt.XTDriver) // UI automation clients for iOS and Android, key is udid/serial
func (r *Router) HandleDeviceContext() gin.HandlerFunc {
return func(c *gin.Context) {
platform := c.Param("platform")
serial := c.Param("serial")
if serial == "" {
log.Error().Str("platform", platform).Msg(fmt.Sprintf("[%s]: serial is empty", c.HandlerName()))
c.JSON(http.StatusBadRequest, HttpResponse{
Code: code.GetErrorCode(code.InvalidParamError),
Message: "serial is empty",
})
c.Abort()
return
}
// get cached driver
if driver, ok := uiClients[serial]; ok {
c.Set("driver", driver)
c.Next()
return
}
switch strings.ToLower(platform) {
case "android":
device, err := uixt.NewAndroidDevice(
option.WithSerialNumber(serial))
if err != nil {
log.Error().Err(err).Str("platform", platform).Str("serial", serial).
Msg("device not found")
c.JSON(http.StatusBadRequest,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
driver, err := device.NewDriver()
if err != nil {
log.Error().Err(err).Str("platform", platform).Str("serial", serial).
Msg("failed to init driver")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
driverExt := uixt.NewXTDriver(driver,
ai.WithCVService(ai.CVServiceTypeVEDEM))
c.Set("driver", driverExt)
// cache driver
uiClients[serial] = driverExt
default:
c.JSON(http.StatusBadRequest, HttpResponse{
Code: code.GetErrorCode(code.InvalidParamError),
Message: fmt.Sprintf("unsupported platform %s", platform),
})
c.Abort()
return
}
c.Next()
}
}
func GetContextDriver(c *gin.Context) (*uixt.XTDriver, error) {
driverObj, exists := c.Get("driver")
func GetDriver(c *gin.Context) (driverExt *uixt.XTDriver, err error) {
deviceObj, exists := c.Get("device")
var device uixt.IDevice
var driver uixt.IDriver
if !exists {
handlerInitDeviceDriverFailedContext(c)
return nil, fmt.Errorf("driver not found")
device, err = GetDevice(c)
if err != nil {
return nil, err
}
} else {
device = deviceObj.(uixt.IDevice)
}
dExt := driverObj.(*uixt.XTDriver)
return dExt, nil
driver, err = device.NewDriver()
if err != nil {
RenderErrorInitDriver(c, err)
return
}
c.Set("driver", driver)
driverExt = uixt.NewXTDriver(driver,
ai.WithCVService(ai.CVServiceTypeVEDEM))
return driverExt, nil
}
func handlerInitDeviceDriverFailedContext(c *gin.Context) {
log.Error().Msg("init device driver failed")
func GetDevice(c *gin.Context) (device uixt.IDevice, err error) {
platform := c.Param("platform")
serial := c.Param("serial")
if serial == "" {
RenderErrorInitDriver(c, err)
return
}
switch strings.ToLower(platform) {
case "android":
device, err = uixt.NewAndroidDevice(
option.WithSerialNumber(serial))
if err != nil {
RenderErrorInitDriver(c, err)
return
}
_ = device.Setup()
case "ios":
device, err = uixt.NewIOSDevice(
option.WithUDID(serial),
option.WithWDAPort(8700),
option.WithWDAMjpegPort(8800),
option.WithResetHomeOnStartup(false),
)
if err != nil {
RenderErrorInitDriver(c, err)
return
}
default:
err = fmt.Errorf("[%s]: invalid platform", c.HandlerName())
return
}
c.Set("device", device)
return device, nil
}
func RenderSuccess(c *gin.Context, result interface{}) {
c.JSON(http.StatusOK, HttpResponse{
Code: code.Success,
Message: "success",
Result: result,
})
}
func RenderError(c *gin.Context, err error) {
log.Error().Err(err).Msgf("failed to %s", c.HandlerName())
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(code.MobileUIDriverError),
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
}
func RenderErrorInitDriver(c *gin.Context, err error) {
log.Error().Err(err).Msg("init device driver failed")
errCode := code.GetErrorCode(err)
if errCode == code.GeneralFail {
errCode = code.GetErrorCode(code.MobileUIDriverError)
}
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: errCode,
Message: "init driver failed",
},
)
c.Abort()
}
func handlerValidateRequestFailedContext(c *gin.Context, err error) {
func RenderErrorValidateRequest(c *gin.Context, err error) {
log.Error().Err(err).Msg("validate request failed")
c.JSON(http.StatusBadRequest, HttpResponse{
Code: code.GetErrorCode(code.InvalidParamError),

View File

@ -1,93 +1,140 @@
package server
import (
"fmt"
"net/http"
"strings"
"os"
"path"
"github.com/Masterminds/semver"
"github.com/danielpaulus/go-ios/ios"
"github.com/gin-gonic/gin"
"github.com/httprunner/httprunner/v5/code"
"github.com/httprunner/httprunner/v5/internal/builtin"
"github.com/httprunner/httprunner/v5/pkg/gadb"
"github.com/httprunner/httprunner/v5/pkg/uixt"
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
"github.com/rs/zerolog/log"
)
func listDeviceHandler(c *gin.Context) {
platform := c.Param("platform")
switch strings.ToLower(platform) {
case "android":
{
client, err := gadb.NewClient()
if err != nil {
log.Err(err).Msg("failed to init adb client")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
devices, err := client.DeviceList()
if err != nil && strings.Contains(err.Error(), "no android device found") {
c.JSON(http.StatusOK, HttpResponse{Result: nil})
return
} else if err != nil {
log.Err(err).Msg("failed to list devices")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
var deviceList []interface{}
for _, device := range devices {
var deviceList []interface{}
client, err := gadb.NewClient()
if err == nil {
androidDevices, err := client.DeviceList()
if err == nil {
for _, device := range androidDevices {
brand, err := device.Brand()
if err != nil {
log.Err(err).Msg("failed to get device brand")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
RenderError(c, err)
return
}
model, err := device.Model()
if err != nil {
log.Err(err).Msg("failed to get device model")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
RenderError(c, err)
return
}
version, err := device.SdkVersion()
if err != nil {
RenderError(c, err)
return
}
deviceInfo := map[string]interface{}{
"serial": device.Serial(),
"brand": brand,
"model": model,
"version": version,
"platform": "android",
}
deviceList = append(deviceList, deviceInfo)
}
c.JSON(http.StatusOK, HttpResponse{Result: deviceList})
return
}
default:
{
c.JSON(http.StatusBadRequest, HttpResponse{
Code: code.GetErrorCode(code.InvalidParamError),
Message: fmt.Sprintf("unsupported platform %s", platform),
})
c.Abort()
return
}
}
iosDevices, err := ios.ListDevices()
if err == nil {
for _, dev := range iosDevices.DeviceList {
device, err := uixt.NewIOSDevice(
option.WithUDID(dev.Properties.SerialNumber))
if err != nil {
continue
}
properties := device.Properties
err = ios.Pair(dev)
if err != nil {
log.Error().Err(err).Msg("failed to pair device")
continue
}
version, err := ios.GetProductVersion(dev)
if err != nil {
continue
}
if version.LessThan(semver.MustParse("17.4.0")) &&
version.GreaterThan(ios.IOS17()) {
log.Warn().Msg("not support ios 17.0-17.3")
continue
}
plist, err := ios.GetValuesPlist(dev)
if err != nil {
log.Error().Err(err).Msg("failed to get device info")
continue
}
deviceInfo := map[string]interface{}{
"udid": properties.SerialNumber,
"platform": "ios",
"brand": "apple",
"model": plist["ProductType"],
"version": plist["ProductVersion"],
}
deviceList = append(deviceList, deviceInfo)
}
}
RenderSuccess(c, deviceList)
}
func pushImageHandler(c *gin.Context) {
var pushMediaReq PushMediaRequest
if err := c.ShouldBindJSON(&pushMediaReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
if err != nil {
return
}
imagePath, err := builtin.DownloadFileByUrl(pushMediaReq.ImageUrl)
if path.Ext(imagePath) == "" {
err = os.Rename(imagePath, imagePath+".png")
if err != nil {
RenderError(c, err)
return
}
imagePath = imagePath + ".png"
}
if err != nil {
RenderError(c, err)
return
}
defer func() {
_ = os.Remove(imagePath)
}()
err = driver.PushImage(imagePath)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
func clearImageHandler(c *gin.Context) {
driver, err := GetDriver(c)
if err != nil {
return
}
err = driver.ClearImages()
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
func videoHandler(c *gin.Context) {
RenderSuccess(c, "")
}

View File

@ -1,53 +1,74 @@
package server
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v5/code"
"github.com/httprunner/httprunner/v5/pkg/uixt"
)
func unlockHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
driver, err := GetDriver(c)
if err != nil {
return
}
err = dExt.Unlock()
err = driver.Unlock()
if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to unlick screen", c.HandlerName()))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
RenderError(c, err)
return
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
RenderSuccess(c, true)
}
func homeHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
driver, err := GetDriver(c)
if err != nil {
return
}
err = dExt.Home()
err = driver.Home()
if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to enter homescreen", c.HandlerName()))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
RenderError(c, err)
return
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
RenderSuccess(c, true)
}
func backspaceHandler(c *gin.Context) {
var deleteReq DeleteRequest
if err := c.ShouldBindJSON(&deleteReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
if deleteReq.Count == 0 {
deleteReq.Count = 20
}
driver, err := GetDriver(c)
if err != nil {
return
}
err = driver.Backspace(deleteReq.Count)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
func keycodeHandler(c *gin.Context) {
var keycodeReq KeycodeRequest
if err := c.ShouldBindJSON(&keycodeReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
if err != nil {
return
}
// TODO FIXME
err = driver.IDriver.(*uixt.ADBDriver).
PressKeyCode(uixt.KeyCode(keycodeReq.Keycode), uixt.KMEmpty)
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}

View File

@ -2,7 +2,9 @@ package server
import (
"fmt"
"net/http"
"time"
"github.com/httprunner/httprunner/v5/pkg/uixt"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
@ -20,31 +22,45 @@ type Router struct {
func (r *Router) Init() {
r.Engine = gin.Default()
r.Engine.Use(teardown())
r.Engine.GET("/ping", pingHandler)
r.Engine.GET("/", pingHandler)
r.Engine.POST("/", pingHandler)
r.Engine.GET("/api/v1/devices", listDeviceHandler)
apiV1Platform := r.Engine.Group("/api/v1").Group("/:platform")
apiV1Platform.GET("/devices", listDeviceHandler)
apiV1PlatformSerial := r.Group("/api/v1").Group("/:platform").Group("/:serial")
apiV1PlatformSerial := apiV1Platform.Group("/:serial")
// UI operations
apiV1PlatformSerial.POST("/ui/tap", r.HandleDeviceContext(), tapHandler)
apiV1PlatformSerial.POST("/ui/drag", r.HandleDeviceContext(), dragHandler)
apiV1PlatformSerial.POST("/ui/input", r.HandleDeviceContext(), inputHandler)
apiV1PlatformSerial.POST("/ui/tap", tapHandler)
apiV1PlatformSerial.POST("/ui/double_tap", doubleTapHandler)
apiV1PlatformSerial.POST("/ui/drag", dragHandler)
apiV1PlatformSerial.POST("/ui/input", inputHandler)
apiV1PlatformSerial.POST("/ui/home", homeHandler)
// Key operations
apiV1PlatformSerial.POST("/key/unlock", r.HandleDeviceContext(), unlockHandler)
apiV1PlatformSerial.POST("/key/home", r.HandleDeviceContext(), homeHandler)
// App operations
apiV1PlatformSerial.GET("/app/foreground", r.HandleDeviceContext(), foregroundAppHandler)
apiV1PlatformSerial.POST("/app/clear", r.HandleDeviceContext(), clearAppHandler)
apiV1PlatformSerial.POST("/app/launch", r.HandleDeviceContext(), launchAppHandler)
apiV1PlatformSerial.POST("/app/terminal", r.HandleDeviceContext(), terminalAppHandler)
// get screen info
apiV1PlatformSerial.GET("/screenshot", r.HandleDeviceContext(), screenshotHandler)
apiV1PlatformSerial.POST("/screenresult", r.HandleDeviceContext(), screenResultHandler)
apiV1PlatformSerial.GET("/adb/source", r.HandleDeviceContext(), adbSourceHandler)
// run uixt actions
apiV1PlatformSerial.POST("/uixt/action", r.HandleDeviceContext(), uixtActionHandler)
apiV1PlatformSerial.POST("/uixt/actions", r.HandleDeviceContext(), uixtActionsHandler)
apiV1PlatformSerial.POST("/key/unlock", unlockHandler)
apiV1PlatformSerial.POST("/key/home", homeHandler)
apiV1PlatformSerial.POST("/key/backspace", backspaceHandler)
apiV1PlatformSerial.POST("/key", keycodeHandler)
// APP operations
apiV1PlatformSerial.GET("/app/foreground", foregroundAppHandler)
apiV1PlatformSerial.GET("/app/appInfo", appInfoHandler)
apiV1PlatformSerial.POST("/app/clear", clearAppHandler)
apiV1PlatformSerial.POST("/app/launch", launchAppHandler)
apiV1PlatformSerial.POST("/app/terminal", terminalAppHandler)
apiV1PlatformSerial.POST("/app/uninstall", uninstallAppHandler)
// Device operations
apiV1PlatformSerial.GET("/screenshot", screenshotHandler)
apiV1PlatformSerial.GET("/video", videoHandler)
apiV1PlatformSerial.POST("/device/push_image", pushImageHandler)
apiV1PlatformSerial.POST("/device/clear_image", clearImageHandler)
apiV1PlatformSerial.GET("/adb/source", adbSourceHandler)
// uixt operations
apiV1PlatformSerial.POST("/uixt/action", uixtActionHandler)
apiV1PlatformSerial.POST("/uixt/actions", uixtActionsHandler)
}
func (r *Router) Run(port int) error {
@ -57,5 +73,56 @@ func (r *Router) Run(port int) error {
}
func pingHandler(c *gin.Context) {
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
RenderSuccess(c, true)
}
func teardown() gin.HandlerFunc {
return func(c *gin.Context) {
logID := c.Request.Header.Get("x-tt-logid")
startTime := time.Now()
// 结束处理后打印日志
fmt.Printf("[GIN] %s | %s | %-7s \"%s\"\n",
startTime.Format("2006/01/02 - 15:04:05"),
logID,
c.Request.Method,
c.Request.URL.Path,
)
// 执行请求处理器
c.Next()
driverObj, exists := c.Get("driver")
if exists {
if driver, ok := driverObj.(*uixt.XTDriver); ok {
_ = driver.TearDown()
}
}
deviceObj, exists := c.Get("device")
if exists {
if device, ok := deviceObj.(*uixt.IOSDevice); ok {
err := device.Teardown()
if err != nil {
log.Error().Err(err)
}
}
}
// 处理请求后获取结束时间
endTime := time.Now()
latency := endTime.Sub(startTime)
// 获取请求的状态码、客户端IP等信息
statusCode := c.Writer.Status()
// 结束处理后打印日志
fmt.Printf("[GIN] %s | %d | %v | %s | %-7s \"%s\"\n",
endTime.Format("2006/01/02 - 15:04:05"),
statusCode,
latency,
logID,
c.Request.Method,
c.Request.URL.Path,
)
c.Writer.Flush()
}
}

View File

@ -4,50 +4,98 @@ import (
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
)
type TapRequest struct {
X float64 `json:"x" binding:"required"`
Y float64 `json:"y" binding:"required"`
Duration float64 `json:"duration"`
Options *option.ActionOptions `json:"options,omitempty"`
}
type DragRequest struct {
FromX float64 `json:"from_x" binding:"required"`
FromY float64 `json:"from_y" binding:"required"`
ToX float64 `json:"to_x" binding:"required"`
ToY float64 `json:"to_y" binding:"required"`
Duration float64 `json:"duration"`
PressDuration float64 `json:"press_duration"`
Options *option.ActionOptions `json:"options,omitempty"`
}
type InputRequest struct {
Text string `json:"text" binding:"required"`
Frequency int `json:"frequency"` // only iOS
}
type DeleteRequest struct {
Count int `json:"count" binding:"required"`
}
type KeycodeRequest struct {
Keycode int `json:"keycode" binding:"required"`
}
type AppClearRequest struct {
PackageName string `json:"packageName" binding:"required"`
}
type AppLaunchRequest struct {
PackageName string `json:"packageName" binding:"required"`
}
type AppTerminalRequest struct {
PackageName string `json:"packageName" binding:"required"`
}
type AppInstallRequest struct {
AppUrl string `json:"appUrl" binding:"required"`
MappingUrl string `json:"mappingUrl"`
ResourceMappingUrl string `json:"resourceMappingUrl"`
PackageName string `json:"packageName"`
}
type AppInfoRequest struct {
PackageName string `form:"packageName" binding:"required"`
}
type AppUninstallRequest struct {
PackageName string `json:"packageName" binding:"required"`
}
type PushMediaRequest struct {
ImageUrl string `json:"imageUrl" binding:"required_without=VideoUrl"`
VideoUrl string `json:"videoUrl" binding:"required_without=ImageUrl"`
}
type OperateRequest struct {
StepText string `json:"stepText" binding:"required"`
}
type HttpResponse struct {
Code int `json:"code"`
Message string `json:"msg"`
Result interface{} `json:"result,omitempty"`
}
type TapRequest struct {
X float64 `json:"x"`
Y float64 `json:"y"`
Text string `json:"text"`
Options *option.ActionOptions `json:"options,omitempty"`
}
type DragRequest struct {
FromX float64 `json:"from_x"`
FromY float64 `json:"from_y"`
ToX float64 `json:"to_x"`
ToY float64 `json:"to_y"`
Options *option.ActionOptions `json:"options,omitempty"`
}
type InputRequest struct {
Text string `json:"text"`
Frequency int `json:"frequency"` // only iOS
}
type ScreenRequest struct {
Options *option.ScreenOptions `json:"options,omitempty"`
}
type KeycodeRequest struct {
Keycode int `json:"keycode"`
type UploadRequest struct {
X float64 `json:"x"`
Y float64 `json:"y"`
FileUrl string `json:"file_url"`
FileFormat string `json:"file_format"`
}
type AppClearRequest struct {
PackageName string `json:"packageName"`
type HoverRequest struct {
X float64 `json:"x"`
Y float64 `json:"y"`
}
type AppLaunchRequest struct {
PackageName string `json:"packageName"`
type ScrollRequest struct {
Delta int `json:"delta"`
}
type AppTerminalRequest struct {
PackageName string `json:"packageName"`
type CreateBrowserRequest struct {
Timeout int `json:"timeout"`
}

View File

@ -2,7 +2,6 @@ package server
import (
"encoding/base64"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
@ -13,42 +12,28 @@ import (
)
func screenshotHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
driver, err := GetDriver(c)
if err != nil {
return
}
raw, err := dExt.ScreenShot()
raw, err := driver.ScreenShot()
if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to get screenshot", c.HandlerName()))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
RenderError(c, err)
return
}
c.JSON(http.StatusOK,
HttpResponse{
Code: code.Success,
Message: "success",
Result: base64.StdEncoding.EncodeToString(raw.Bytes()),
},
)
RenderSuccess(c, base64.StdEncoding.EncodeToString(raw.Bytes()))
}
func screenResultHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
dExt, err := GetDriver(c)
if err != nil {
return
}
var screenReq ScreenRequest
if err := c.ShouldBindJSON(&screenReq); err != nil {
handlerValidateRequestFailedContext(c, err)
RenderErrorValidateRequest(c, err)
return
}
@ -69,32 +54,19 @@ func screenResultHandler(c *gin.Context) {
c.Abort()
return
}
c.JSON(http.StatusOK,
HttpResponse{
Code: code.Success,
Message: "success",
Result: screenResult,
},
)
RenderSuccess(c, screenResult)
}
func adbSourceHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
dExt, err := GetDriver(c)
if err != nil {
return
}
source, err := dExt.Source()
if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to get adb source", c.HandlerName()))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
RenderError(c, err)
return
}
c.JSON(http.StatusOK, HttpResponse{Result: source})
RenderSuccess(c, source)
}

View File

@ -1,157 +1,98 @@
package server
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v5/code"
"github.com/httprunner/httprunner/v5/pkg/uixt/option"
)
func tapHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
var tapReq TapRequest
if err := c.ShouldBindJSON(&tapReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
if err != nil {
return
}
if tapReq.Duration > 0 {
err = driver.Drag(tapReq.X, tapReq.Y, tapReq.X, tapReq.Y,
option.WithDuration(tapReq.Duration),
option.WithAbsoluteCoordinate(true))
} else {
err = driver.TapAbsXY(tapReq.X, tapReq.Y)
}
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}
func doubleTapHandler(c *gin.Context) {
var tapReq TapRequest
if err := c.ShouldBindJSON(&tapReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
driver, err := GetDriver(c)
if err != nil {
return
}
var tapReq TapRequest
if err := c.ShouldBindJSON(&tapReq); err != nil {
handlerValidateRequestFailedContext(c, err)
if tapReq.X < 1 && tapReq.Y < 1 {
err = driver.DoubleTapXY(tapReq.X, tapReq.Y)
} else {
err = driver.DoubleTapXY(tapReq.X, tapReq.Y,
option.WithAbsoluteCoordinate(true))
}
if err != nil {
RenderError(c, err)
return
}
var actionOptions []option.ActionOption
if tapReq.Options != nil {
actionOptions = tapReq.Options.Options()
}
if tapReq.Text != "" {
err := dExt.TapByOCR(tapReq.Text, actionOptions...)
if err != nil {
log.Err(err).Str("text", tapReq.Text).Msg("tap text failed")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
} else if tapReq.X < 1 && tapReq.Y < 1 {
err := dExt.TapXY(tapReq.X, tapReq.Y, actionOptions...)
if err != nil {
log.Err(err).Float64("x", tapReq.X).Float64("y", tapReq.Y).Msg("tap relative xy failed")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
} else {
err := dExt.TapAbsXY(tapReq.X, tapReq.Y, actionOptions...)
if err != nil {
log.Err(err).Float64("x", tapReq.X).Float64("y", tapReq.Y).Msg("tap abs xy failed")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
RenderSuccess(c, true)
}
func dragHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
var dragReq DragRequest
if err := c.ShouldBindJSON(&dragReq); err != nil {
RenderErrorValidateRequest(c, err)
return
}
if dragReq.Duration == 0 {
dragReq.Duration = 1
}
driver, err := GetDriver(c)
if err != nil {
return
}
var dragReq DragRequest
if err := c.ShouldBindJSON(&dragReq); err != nil {
handlerValidateRequestFailedContext(c, err)
err = driver.Drag(dragReq.FromX, dragReq.FromY, dragReq.ToX, dragReq.ToY,
option.WithDuration(dragReq.Duration), option.WithPressDuration(dragReq.PressDuration),
option.WithAbsoluteCoordinate(true))
if err != nil {
RenderError(c, err)
return
}
var actionOptions []option.ActionOption
if dragReq.Options != nil {
actionOptions = dragReq.Options.Options()
}
if dragReq.FromX < 1 && dragReq.FromY < 1 && dragReq.ToX < 1 && dragReq.ToY < 1 {
err := dExt.Swipe(
dragReq.FromX, dragReq.FromY, dragReq.ToX, dragReq.ToY,
actionOptions...)
if err != nil {
log.Err(err).
Float64("from_x", dragReq.FromX).Float64("from_y", dragReq.FromY).
Float64("to_x", dragReq.ToX).Float64("to_y", dragReq.ToY).
Msg("swipe relative failed")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
} else {
err := dExt.Swipe(
dragReq.FromX, dragReq.FromY, dragReq.ToX, dragReq.ToY,
actionOptions...)
if err != nil {
log.Err(err).
Float64("from_x", dragReq.FromX).Float64("from_y", dragReq.FromY).
Float64("to_x", dragReq.ToX).Float64("to_y", dragReq.ToY).
Msg("swipe absolute failed")
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
RenderSuccess(c, true)
}
func inputHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
if err != nil {
return
}
var inputReq InputRequest
if err := c.ShouldBindJSON(&inputReq); err != nil {
handlerValidateRequestFailedContext(c, err)
RenderErrorValidateRequest(c, err)
return
}
err = dExt.Input(inputReq.Text,
option.WithFrequency(inputReq.Frequency))
driver, err := GetDriver(c)
if err != nil {
log.Err(err).Msg(fmt.Sprintf("[%s]: failed to input text %s", c.HandlerName(), inputReq.Text))
c.JSON(http.StatusInternalServerError,
HttpResponse{
Code: code.GetErrorCode(err),
Message: err.Error(),
},
)
c.Abort()
return
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
err = driver.Input(inputReq.Text, option.WithFrequency(inputReq.Frequency))
if err != nil {
RenderError(c, err)
return
}
RenderSuccess(c, true)
}

View File

@ -11,14 +11,14 @@ import (
// exec a single uixt action
func uixtActionHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
dExt, err := GetDriver(c)
if err != nil {
return
}
var req uixt.MobileAction
if err := c.ShouldBindJSON(&req); err != nil {
handlerValidateRequestFailedContext(c, err)
RenderErrorValidateRequest(c, err)
return
}
@ -34,20 +34,19 @@ func uixtActionHandler(c *gin.Context) {
c.Abort()
return
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
RenderSuccess(c, true)
}
// exec multiple uixt actions
func uixtActionsHandler(c *gin.Context) {
dExt, err := GetContextDriver(c)
dExt, err := GetDriver(c)
if err != nil {
return
}
var actions []uixt.MobileAction
if err := c.ShouldBindJSON(&actions); err != nil {
handlerValidateRequestFailedContext(c, err)
RenderErrorValidateRequest(c, err)
return
}
@ -65,6 +64,5 @@ func uixtActionsHandler(c *gin.Context) {
return
}
}
c.JSON(http.StatusOK, HttpResponse{Code: 0, Message: "success"})
RenderSuccess(c, true)
}