get_wx_list_logic.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. l.Infof("----------------strings.ToUpper(v.Port)--------------: %+v", strings.ToUpper(v.Port))
  98. l.Infof("----------------HasPrefix--------------: %+v", strings.HasPrefix(strings.ToUpper(v.Port), "PC-"))
  99. if strings.HasPrefix(strings.ToUpper(v.Port), "PC-") {
  100. serverName = "本地版"
  101. }
  102. var loginStatus uint8 = 0
  103. hookClient := hook.NewHook(serverInfo.PrivateIP, serverInfo.AdminPort, v.Port)
  104. if v.ServerID > 0 {
  105. if serverInfo.Status == 1 {
  106. // 获取登录状态
  107. loginInfo, err := hookClient.IsLoginStatus()
  108. if err != nil {
  109. l.Error("退出登录失败", err)
  110. } else {
  111. if loginInfo.Onlinestatus == "3" {
  112. loginStatus = 1
  113. }
  114. }
  115. }
  116. } else {
  117. workphoneWx, exists := workphoneWxList[v.Wxid]
  118. if exists && workphoneWx.Isonline == 0 {
  119. loginStatus = 1
  120. } else {
  121. loginStatus = 0
  122. }
  123. }
  124. processID := v.ProcessID
  125. wxid := v.Wxid
  126. account := v.Account
  127. nickname := v.Nickname
  128. tel := v.Tel
  129. headBig := v.HeadBig
  130. departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: v.OrganizationID})
  131. if err != nil {
  132. l.Error("获取部门信息失败", err)
  133. }
  134. if v.ServerID > 0 {
  135. if loginStatus == 1 {
  136. // 如果处于登录状态,获取登录信息
  137. wxInfo, _ := hookClient.GetSelfLoginInfo()
  138. if err != nil {
  139. l.Error("获取登录信息失败", err)
  140. } else {
  141. if wxid != wxInfo.Wxid {
  142. l.svcCtx.Rds.HDel(l.ctx, "wx_info", wxid)
  143. l.svcCtx.Rds.HDel(l.ctx, "wx_info", wxInfo.Wxid)
  144. l.svcCtx.Rds.HDel(l.ctx, "crontask_wx_server_info", wxid)
  145. l.svcCtx.Rds.HDel(l.ctx, "crontask_wx_server_info", wxInfo.Wxid)
  146. }
  147. processID = wxInfo.ProcessID
  148. wxid = wxInfo.Wxid
  149. account = wxInfo.Account
  150. nickname = wxInfo.Nickname
  151. tel = wxInfo.Tel
  152. headBig = wxInfo.HeadBig
  153. _ = l.svcCtx.DB.Wx.UpdateOneID(v.ID).
  154. SetNotNilStatus(&loginStatus).
  155. SetNotNilProcessID(&wxInfo.ProcessID).
  156. SetNotNilWxid(&wxInfo.Wxid).
  157. SetNotNilAccount(&wxInfo.Account).
  158. SetNotNilNickname(&wxInfo.Nickname).
  159. SetNotNilTel(&wxInfo.Tel).
  160. SetNotNilHeadBig(&wxInfo.HeadBig).
  161. Exec(l.ctx)
  162. }
  163. } else {
  164. if loginStatus != v.Status {
  165. _ = l.svcCtx.DB.Wx.UpdateOneID(v.ID).
  166. SetNotNilStatus(&loginStatus).
  167. Exec(l.ctx)
  168. }
  169. }
  170. }
  171. totalTokens := uint64(0)
  172. usageTotalInfo, _ := l.svcCtx.DB.UsageTotal.Query().
  173. Where(
  174. usagetotal.BotID(wxid),
  175. ).
  176. Only(l.ctx)
  177. if usageTotalInfo != nil {
  178. totalTokens = usageTotalInfo.TotalTokens
  179. }
  180. var agent types.AgentInfo
  181. if v.Edges.Agent != nil {
  182. agent = types.AgentInfo{
  183. BaseIDInfo: types.BaseIDInfo{
  184. Id: &v.AgentID,
  185. CreatedAt: pointy.GetPointer(v.Edges.Agent.CreatedAt.UnixMilli()),
  186. UpdatedAt: pointy.GetPointer(v.Edges.Agent.UpdatedAt.UnixMilli()),
  187. },
  188. Name: &v.Edges.Agent.Name,
  189. Role: &v.Edges.Agent.Role,
  190. Status: &v.Edges.Agent.Status,
  191. Background: &v.Edges.Agent.Background,
  192. Examples: &v.Edges.Agent.Examples,
  193. }
  194. }
  195. resp.Data.Data = append(resp.Data.Data,
  196. types.WxInfo{
  197. BaseIDInfo: types.BaseIDInfo{
  198. Id: &v.ID,
  199. CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
  200. UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
  201. },
  202. Status: &loginStatus,
  203. ServerId: &v.ServerID,
  204. ServerName: &serverName,
  205. Port: &v.Port,
  206. ProcessId: &processID,
  207. Callback: &v.Callback,
  208. Wxid: &wxid,
  209. Account: &account,
  210. Nickname: &nickname,
  211. Tel: &tel,
  212. HeadBig: &headBig,
  213. OrganizationId: &v.OrganizationID,
  214. OrganizationName: departmentInfo.Name,
  215. AgentId: &v.AgentID,
  216. AgentInfo: &agent,
  217. ApiBase: &v.APIBase,
  218. ApiKey: &v.APIKey,
  219. TotalTokens: &totalTokens,
  220. })
  221. }
  222. return resp, nil
  223. }