send_text_msg_logic.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package chat
  2. import (
  3. "context"
  4. "errors"
  5. "wechat-api/ent"
  6. "wechat-api/ent/predicate"
  7. "wechat-api/ent/wx"
  8. "wechat-api/hook"
  9. "wechat-api/internal/svc"
  10. "wechat-api/internal/types"
  11. "wechat-api/internal/utils/contextkey"
  12. "github.com/suyuan32/simple-admin-common/enum/errorcode"
  13. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  14. "github.com/zeromicro/go-zero/core/logx"
  15. )
  16. type SendTextMsgLogic struct {
  17. logx.Logger
  18. ctx context.Context
  19. svcCtx *svc.ServiceContext
  20. }
  21. func NewSendTextMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendTextMsgLogic {
  22. return &SendTextMsgLogic{
  23. Logger: logx.WithContext(ctx),
  24. ctx: ctx,
  25. svcCtx: svcCtx}
  26. }
  27. func (l *SendTextMsgLogic) SendTextMsg(req *types.SendTextMsgReq) (resp *types.BaseMsgResp, err error) {
  28. // todo: add your logic here and delete this line
  29. var (
  30. apiKeyObj *ent.ApiKey
  31. ok bool
  32. )
  33. //从上下文中获取鉴权中间件埋下的apiAuthInfo
  34. apiKeyObj, ok = contextkey.AuthTokenInfoKey.GetValue(l.ctx)
  35. if !ok {
  36. return nil, errors.New("content get auth info err")
  37. }
  38. //根据wx实体的wxid查询
  39. var predicates []predicate.Wx
  40. if req.WxWxid != nil {
  41. predicates = append(predicates, wx.WxidContains(*req.WxWxid))
  42. }
  43. wxInfo, err := l.svcCtx.DB.Wx.Query().Where(predicates...).Only(l.ctx)
  44. //根据wx实体的主键ID查询
  45. //wxInfo, err := l.svcCtx.DB.Wx.Get(l.ctx, *req.AgentWxId)
  46. l.Infof("wxInfo = %v", wxInfo)
  47. if err != nil {
  48. l.Error("查询微信信息失败", err)
  49. return
  50. }
  51. if wxInfo.OrganizationID != apiKeyObj.OrganizationID {
  52. return nil, errors.New("OID不一致")
  53. }
  54. privateIP := ""
  55. adminPort := ""
  56. port := ""
  57. if wxInfo.ServerID != 0 {
  58. serverInfo, err := l.svcCtx.DB.Server.Get(l.ctx, wxInfo.ServerID)
  59. if err != nil {
  60. l.Error("查询服务器信息失败", err)
  61. return nil, err
  62. }
  63. privateIP = serverInfo.PrivateIP
  64. adminPort = serverInfo.AdminPort
  65. port = wxInfo.Port
  66. }
  67. var ctype uint64
  68. if req.Ctype != nil && *req.Ctype != 0 {
  69. ctype = *req.Ctype
  70. }
  71. var hookClient *hook.Hook
  72. if ctype == 3 {
  73. hookClient = hook.NewWecomHook("", adminPort, port)
  74. } else {
  75. hookClient = hook.NewHook(privateIP, adminPort, port)
  76. }
  77. err = hookClient.SendTextMsg(*req.Wxid, *req.Msg, wxInfo.Wxid)
  78. if err != nil {
  79. l.Errorf("发送微信文本消息失败:%v\n", err)
  80. return nil, err
  81. }
  82. resp = &types.BaseMsgResp{
  83. Msg: errormsg.Success,
  84. Code: errorcode.OK,
  85. }
  86. return resp, nil
  87. }