get_wx_list_logic.go 6.7 KB

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