李寻欢 fa8bf764db
All checks were successful
BuildImage / build-image (push) Successful in 1m54s
:refactor: 更新登录逻辑,使用用户ID查询机器人并记录首次登录时间
2025-04-28 11:51:28 +08:00

111 lines
2.6 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 handler
import (
"encoding/json"
"errors"
"gitee.ltd/lxh/wechat-robot/internal/config"
"gitee.ltd/lxh/wechat-robot/internal/tasks"
"gitee.ltd/lxh/xybot"
"github.com/gofiber/fiber/v2/log"
"strconv"
"time"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
"gitee.ltd/lxh/wechat-robot/internal/model"
)
// CheckQRCodeStatus 检查二维码状态
func CheckQRCodeStatus(c *fiber.Ctx) error {
id, err := strconv.Atoi(c.Params("id"))
if err != nil {
return c.JSON(fiber.Map{
"success": false,
"message": "无效的机器人ID",
})
}
uuid := c.Query("uuid")
if uuid == "" {
return c.JSON(fiber.Map{
"success": false,
"message": "UUID参数缺失",
})
}
// 获取机器人实例
db := model.GetDB()
var robot model.Robot
if err = db.Where("user_id = ?", c.Locals("userId")).First(&robot, id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return c.JSON(fiber.Map{
"success": false,
"message": "机器人不存在",
})
}
return c.JSON(fiber.Map{
"success": false,
"message": "查询数据库失败",
})
}
// 调用CheckUuid API检查二维码状态传递容器访问地址
robotCli, err := xybot.NewClient(robot.WechatID, robot.ContainerHost, false)
if err != nil {
return c.JSON(fiber.Map{
"success": false,
"message": "创建微信客户端失败: " + err.Error(),
})
}
response, err := robotCli.Login.CheckUuid(uuid)
if err != nil {
return c.JSON(fiber.Map{
"success": false,
"message": "检查二维码状态失败: " + err.Error(),
})
}
if config.Scd.Server.Env == "development" {
bs, _ := json.Marshal(response)
log.Debugf("扫码返回结果: %s", bs)
}
// 如果返回status=1表示已扫码暂存一下昵称和头像
if response.Status == 1 {
robot.Nickname = response.NickName
robot.Avatar = response.HeadImgUrl
db.Save(&robot)
}
// 如果检测到已登录,更新机器人状态
if response.AcctSectResp.Username != "" {
response.Status = 99
robot.WechatID = response.AcctSectResp.Username
// 开启自动心跳,传递容器访问地址
if robot.WechatID != "" {
_ = robotCli.Login.AutoHeartbeatStart()
}
// 更新机器人状态
robot.Status = model.RobotStatusOnline
now := time.Now()
robot.LastLoginAt = &now
if robot.FirstLoginAt == nil {
robot.FirstLoginAt = &now // 只有在为空的时候才记录首次登录时间
}
db.Save(&robot)
// 添加定时任务
tasks.AddJob(robot)
}
return c.JSON(fiber.Map{
"success": true,
"status": response.Status,
"message": "success",
"userInfo": response.AcctSectResp,
})
}