get_wx_list_logic.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. package Wx
  2. import (
  3. "context"
  4. "fmt"
  5. reqv3 "github.com/imroc/req/v3"
  6. "github.com/suyuan32/simple-admin-core/rpc/types/core"
  7. "strings"
  8. "wechat-api/ent"
  9. "wechat-api/ent/predicate"
  10. "wechat-api/ent/usagetotal"
  11. "wechat-api/ent/wx"
  12. "wechat-api/hook"
  13. "wechat-api/internal/svc"
  14. "wechat-api/internal/types"
  15. "wechat-api/internal/utils/dberrorhandler"
  16. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  17. "github.com/suyuan32/simple-admin-common/utils/pointy"
  18. "github.com/zeromicro/go-zero/core/logx"
  19. )
  20. type GetWxListLogic struct {
  21. ctx context.Context
  22. svcCtx *svc.ServiceContext
  23. logx.Logger
  24. }
  25. func NewGetWxListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWxListLogic {
  26. return &GetWxListLogic{
  27. ctx: ctx,
  28. svcCtx: svcCtx,
  29. Logger: logx.WithContext(ctx),
  30. }
  31. }
  32. func (l *GetWxListLogic) GetWxList(req *types.WxListReq) (*types.WxListResp, error) {
  33. organizationId := l.ctx.Value("organizationId").(uint64)
  34. isAdmin := l.ctx.Value("isAdmin").(bool)
  35. servers, err := l.svcCtx.DB.Server.Query().All(l.ctx)
  36. serverSet := make(map[uint64]*ent.Server, len(servers))
  37. serverSet[0] = &ent.Server{
  38. ID: 0,
  39. Name: "工作手机",
  40. Status: 1,
  41. }
  42. for _, s := range servers {
  43. serverSet[s.ID] = s
  44. }
  45. var predicates []predicate.Wx
  46. if !isAdmin {
  47. predicates = append(predicates, wx.OrganizationIDEQ(organizationId))
  48. } else {
  49. if req.OrganizationId != nil {
  50. predicates = append(predicates, wx.OrganizationIDEQ(*req.OrganizationId))
  51. }
  52. if req.OrganizationName != nil {
  53. departmentList, _ := l.svcCtx.CoreRpc.GetDepartmentList(l.ctx, &core.DepartmentListReq{Name: req.OrganizationName})
  54. organizationIds := make([]uint64, 0)
  55. for _, department := range departmentList.Data {
  56. organizationIds = append(organizationIds, *department.Id)
  57. }
  58. predicates = append(predicates, wx.OrganizationIDIn(organizationIds...))
  59. }
  60. }
  61. if req.ServerId != nil {
  62. predicates = append(predicates, wx.ServerIDEQ(*req.ServerId))
  63. }
  64. if req.Port != nil {
  65. predicates = append(predicates, wx.PortContains(*req.Port))
  66. }
  67. if req.ProcessId != nil {
  68. predicates = append(predicates, wx.ProcessIDContains(*req.ProcessId))
  69. }
  70. if req.Callback != nil {
  71. predicates = append(predicates, wx.CallbackContains(*req.Callback))
  72. }
  73. data, err := l.svcCtx.DB.Wx.Query().Where(predicates...).Order(ent.Desc(wx.FieldOrganizationID)).WithAgent().WithServer().Page(l.ctx, req.Page, req.PageSize)
  74. if err != nil {
  75. return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
  76. }
  77. resp := &types.WxListResp{}
  78. resp.Msg = errormsg.Success
  79. resp.Data.Total = data.PageDetails.Total
  80. var result types.WorkPhoneGetWeChatsResp
  81. res, err := reqv3.C().DevMode().R().SetSuccessResult(&result).Post("http://chat.gkscrm.com:13086/pc/GetWeChatsReq?id=13")
  82. if err != nil {
  83. return nil, err
  84. }
  85. if !res.IsSuccessState() {
  86. err = fmt.Errorf("GetWeChats failed with status code %d", res.StatusCode)
  87. return nil, err
  88. }
  89. workphoneWxList := make(map[string]types.WorkPhoneWeChat, len(result.Data))
  90. for _, v := range result.Data {
  91. workphoneWxList[v.Wechatid] = v
  92. }
  93. for _, v := range data.List {
  94. // 创建 hookClient 客户端
  95. serverInfo := serverSet[v.ServerID]
  96. serverName := serverInfo.Name
  97. if strings.HasPrefix(strings.ToUpper(v.Port), "PC-") {
  98. serverName = "本地版"
  99. }
  100. var loginStatus uint8 = 0
  101. hookClient := hook.NewHook(serverInfo.PrivateIP, serverInfo.AdminPort, v.Port)
  102. if v.ServerID > 0 {
  103. if serverInfo.Status == 1 {
  104. // 获取登录状态
  105. loginInfo, err := hookClient.IsLoginStatus()
  106. if err != nil {
  107. l.Error("退出登录失败", err)
  108. } else {
  109. if loginInfo.Onlinestatus == "3" {
  110. loginStatus = 1
  111. }
  112. }
  113. }
  114. } else {
  115. workphoneWx, exists := workphoneWxList[v.Wxid]
  116. if exists && workphoneWx.Isonline == 0 {
  117. loginStatus = 1
  118. } else {
  119. loginStatus = 0
  120. }
  121. }
  122. processID := v.ProcessID
  123. wxid := v.Wxid
  124. account := v.Account
  125. nickname := v.Nickname
  126. tel := v.Tel
  127. headBig := v.HeadBig
  128. departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: v.OrganizationID})
  129. if err != nil {
  130. l.Error("获取部门信息失败", err)
  131. }
  132. if v.ServerID > 0 {
  133. if loginStatus == 1 {
  134. // 如果处于登录状态,获取登录信息
  135. wxInfo, _ := hookClient.GetSelfLoginInfo()
  136. if err != nil {
  137. l.Error("获取登录信息失败", err)
  138. } else {
  139. if wxid != wxInfo.Wxid {
  140. l.svcCtx.Rds.HDel(l.ctx, "wx_info", wxid)
  141. l.svcCtx.Rds.HDel(l.ctx, "wx_info", wxInfo.Wxid)
  142. l.svcCtx.Rds.HDel(l.ctx, "crontask_wx_server_info", wxid)
  143. l.svcCtx.Rds.HDel(l.ctx, "crontask_wx_server_info", wxInfo.Wxid)
  144. }
  145. processID = wxInfo.ProcessID
  146. wxid = wxInfo.Wxid
  147. account = wxInfo.Account
  148. nickname = wxInfo.Nickname
  149. tel = wxInfo.Tel
  150. headBig = wxInfo.HeadBig
  151. _ = l.svcCtx.DB.Wx.UpdateOneID(v.ID).
  152. SetNotNilStatus(&loginStatus).
  153. SetNotNilProcessID(&wxInfo.ProcessID).
  154. SetNotNilWxid(&wxInfo.Wxid).
  155. SetNotNilAccount(&wxInfo.Account).
  156. SetNotNilNickname(&wxInfo.Nickname).
  157. SetNotNilTel(&wxInfo.Tel).
  158. SetNotNilHeadBig(&wxInfo.HeadBig).
  159. Exec(l.ctx)
  160. }
  161. } else {
  162. if loginStatus != v.Status {
  163. _ = l.svcCtx.DB.Wx.UpdateOneID(v.ID).
  164. SetNotNilStatus(&loginStatus).
  165. Exec(l.ctx)
  166. }
  167. }
  168. }
  169. totalTokens := uint64(0)
  170. usageTotalInfo, _ := l.svcCtx.DB.UsageTotal.Query().
  171. Where(
  172. usagetotal.BotID(wxid),
  173. ).
  174. Only(l.ctx)
  175. if usageTotalInfo != nil {
  176. totalTokens = usageTotalInfo.TotalTokens
  177. }
  178. var agent types.AgentInfo
  179. if v.Edges.Agent != nil {
  180. agent = types.AgentInfo{
  181. BaseIDInfo: types.BaseIDInfo{
  182. Id: &v.AgentID,
  183. CreatedAt: pointy.GetPointer(v.Edges.Agent.CreatedAt.UnixMilli()),
  184. UpdatedAt: pointy.GetPointer(v.Edges.Agent.UpdatedAt.UnixMilli()),
  185. },
  186. Name: &v.Edges.Agent.Name,
  187. Role: &v.Edges.Agent.Role,
  188. Status: &v.Edges.Agent.Status,
  189. Background: &v.Edges.Agent.Background,
  190. Examples: &v.Edges.Agent.Examples,
  191. }
  192. }
  193. resp.Data.Data = append(resp.Data.Data,
  194. types.WxInfo{
  195. BaseIDInfo: types.BaseIDInfo{
  196. Id: &v.ID,
  197. CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
  198. UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
  199. },
  200. Status: &loginStatus,
  201. ServerId: &v.ServerID,
  202. ServerName: &serverName,
  203. Port: &v.Port,
  204. ProcessId: &processID,
  205. Callback: &v.Callback,
  206. Wxid: &wxid,
  207. Account: &account,
  208. Nickname: &nickname,
  209. Tel: &tel,
  210. HeadBig: &headBig,
  211. OrganizationId: &v.OrganizationID,
  212. OrganizationName: departmentInfo.Name,
  213. AgentId: &v.AgentID,
  214. AgentInfo: &agent,
  215. ApiBase: &v.APIBase,
  216. ApiKey: &v.APIKey,
  217. TotalTokens: &totalTokens,
  218. })
  219. }
  220. return resp, nil
  221. }