send_msg.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. package crontask
  2. import (
  3. "encoding/json"
  4. "net/url"
  5. "path"
  6. "strings"
  7. "time"
  8. "wechat-api/ent"
  9. "wechat-api/ent/batchmsg"
  10. "wechat-api/ent/contact"
  11. "wechat-api/ent/custom_types"
  12. "wechat-api/ent/label"
  13. "wechat-api/ent/labelrelationship"
  14. "wechat-api/ent/msg"
  15. "wechat-api/ent/wx"
  16. "wechat-api/hook"
  17. )
  18. func (l *CronTask) sendMsg() {
  19. // 获取 BatchMsg 表中 start_time 小于当前时间并且 status 为 0 或 1 的数据
  20. batchlist, err := l.svcCtx.DB.BatchMsg.Query().Where(batchmsg.StartTimeLT(time.Now()), batchmsg.StatusIn(0, 1)).All(l.ctx)
  21. if err != nil {
  22. l.Logger.Errorf("batchlist err: %v", err)
  23. return
  24. }
  25. for _, batch := range batchlist {
  26. // 记录当前批次开始处理
  27. l.Logger.Info("batch start: ", batch.BatchNo)
  28. // 如果 批次 status 为 0,则先产生待发送消息
  29. if batch.Status == 0 {
  30. // 如果是设定了发送时间,且还没到则应该忽略该条内容
  31. if !batch.SendTime.IsZero() && time.Now().Before(batch.SendTime) {
  32. continue
  33. }
  34. userlist := make([]*ent.Contact, 0)
  35. if batch.Tag == "all" {
  36. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 的 type 为1或2的数据
  37. userlist, err = l.svcCtx.DB.Contact.Query().Where(contact.WxWxid(batch.Fromwxid), contact.TypeIn(1, 2)).All(l.ctx)
  38. if err != nil {
  39. l.Logger.Errorf("userlist err: %v", err)
  40. continue
  41. }
  42. } else {
  43. tags := strings.Split(batch.Tag, ",")
  44. // 获取 label 表中 name 为 tags的记录
  45. labids, err := l.svcCtx.DB.Label.Query().Where(label.NameIn(tags...)).IDs(l.ctx)
  46. if err != nil {
  47. l.Logger.Errorf("labids err: %v", err)
  48. continue
  49. }
  50. // 获取 label_relationship 表中,label_id 等于 labids 的 contact_id
  51. labelrelationships, err := l.svcCtx.DB.LabelRelationship.Query().Where(labelrelationship.LabelIDIn(labids...)).All(l.ctx)
  52. if err != nil {
  53. l.Logger.Errorf("labelrelationships err: %v", err)
  54. continue
  55. }
  56. contact_ids := make([]uint64, 0)
  57. for _, labelrelationship := range labelrelationships {
  58. contact_ids = append(contact_ids, labelrelationship.ContactID)
  59. }
  60. if len(contact_ids) > 0 {
  61. // 获取 contact 表中 wx_wxid 等于 req.Fromwxid 并且 id 等于 contact_ids 并且 type 为1或2 的数据
  62. userlist, err = l.svcCtx.DB.Contact.Query().Where(contact.WxWxid(batch.Fromwxid), contact.IDIn(contact_ids...), contact.TypeIn(1, 2)).All(l.ctx)
  63. if err != nil {
  64. l.Logger.Errorf("userlist err: %v", err)
  65. continue
  66. }
  67. }
  68. }
  69. // 这里是待插入到 msg 表的数据
  70. msgs := make([]*ent.MsgCreate, 0)
  71. // 这里是把 batch.Msg 转换为 json 数组
  72. msgArray := make([]custom_types.Action, 0)
  73. err := json.Unmarshal([]byte(batch.Msg), &msgArray)
  74. l.Logger.Infof("msgArray length= %v, err:%v", len(msgArray), err)
  75. if err != nil {
  76. // json 解析失败
  77. msgArray = make([]custom_types.Action, 0)
  78. }
  79. for _, user := range userlist {
  80. // 这里改动主要是 batch_msg 目前支持批量添加图文,导致 batch_msg 的 msg 字段为 json
  81. // msg 里包括文字和图片,msgtype=1 为文字, msgtype=2 为图片
  82. // 每一条文字或者图片 都是一条单独的消息
  83. if len(msgArray) > 0 {
  84. // 这里是新格式(msg内容为json),需要遍历数组
  85. for _, msgItem := range msgArray {
  86. msgRow := l.svcCtx.DB.Msg.Create().
  87. SetNotNilFromwxid(&batch.Fromwxid).
  88. SetNotNilToid(&user.Wxid).
  89. SetMsgtype(int32(msgItem.Type)).
  90. SetNotNilMsg(&msgItem.Content).
  91. SetStatus(0).
  92. SetNotNilBatchNo(&batch.BatchNo)
  93. msgs = append(msgs, msgRow)
  94. }
  95. }
  96. }
  97. if len(msgs) > 0 {
  98. _, err = l.svcCtx.DB.Msg.CreateBulk(msgs...).Save(l.ctx)
  99. if err != nil {
  100. l.Logger.Errorf("msg CreateBulk err: %v", err)
  101. continue
  102. }
  103. } else {
  104. // 如果没有消息,直接更新批次状态为已发送
  105. _, err = l.svcCtx.DB.BatchMsg.UpdateOneID(batch.ID).
  106. SetStatus(2).
  107. SetTotal(0).
  108. SetSuccess(0).
  109. SetFail(0).
  110. Save(l.ctx)
  111. if err != nil {
  112. l.Logger.Errorf("batchmsg update err: %v", err)
  113. }
  114. continue
  115. }
  116. _, err = l.svcCtx.DB.BatchMsg.UpdateOneID(batch.ID).Where(batchmsg.StatusNEQ(1)).SetStatus(1).Save(l.ctx)
  117. if err != nil {
  118. l.Logger.Errorf("batchmsg update err: %v", err)
  119. continue
  120. }
  121. }
  122. // 获取当前批次的所有待发送消息
  123. msglist, err := l.svcCtx.DB.Msg.Query().Where(msg.BatchNoEQ(batch.BatchNo), msg.StatusEQ(0)).All(l.ctx)
  124. if err != nil {
  125. l.Logger.Errorf("msglist err: %v", err)
  126. continue
  127. }
  128. wxInfo, err := l.svcCtx.DB.Wx.Query().Where(wx.Wxid(batch.Fromwxid)).Only(l.ctx)
  129. if err != nil {
  130. l.Logger.Errorf("wxInfo err: %v", err)
  131. continue
  132. }
  133. serverInfo, err := l.svcCtx.DB.Server.Get(l.ctx, wxInfo.ServerID)
  134. if err != nil {
  135. l.Logger.Errorf("serverInfo err: %v", err)
  136. continue
  137. }
  138. hookClient := hook.NewHook(serverInfo.PrivateIP, serverInfo.AdminPort, wxInfo.Port)
  139. //循环发送消息
  140. for _, msg := range msglist {
  141. // 这里之前只有文字消息(既 msgtype=1) 目前增加了图片 所以增加了msgtype=2
  142. // 所以增加了一个判断,判断发送的内容类型,如果是文字就调用SendTextMsg,如果是图片就调用SendPicMsg
  143. if msg.Msgtype == 1 {
  144. err = hookClient.SendTextMsg(msg.Toid, msg.Msg)
  145. } else if msg.Msgtype == 2 {
  146. diyfilename := getFileName(msg.Msg)
  147. err = hookClient.SendPicMsg(msg.Toid, msg.Msg, diyfilename)
  148. }
  149. // 每次发完暂停1秒
  150. time.Sleep(time.Second)
  151. if err != nil {
  152. l.Logger.Errorf("send msg err: %v", err)
  153. _, err = l.svcCtx.DB.Msg.UpdateOneID(msg.ID).SetStatus(2).Save(l.ctx)
  154. if err != nil {
  155. l.Logger.Errorf("msg update err: %v", err)
  156. continue
  157. }
  158. continue
  159. }
  160. _, err = l.svcCtx.DB.Msg.UpdateOneID(msg.ID).SetStatus(1).Save(l.ctx)
  161. if err != nil {
  162. l.Logger.Errorf("msg update err: %v", err)
  163. continue
  164. }
  165. }
  166. // 获取当前批次的所有发送的消息总数
  167. total, _ := l.svcCtx.DB.Msg.Query().Where(msg.BatchNoEQ(batch.BatchNo)).Count(l.ctx)
  168. // 获取当前批次的所有发送成功的消息总数
  169. success, _ := l.svcCtx.DB.Msg.Query().Where(msg.BatchNoEQ(batch.BatchNo), msg.StatusEQ(1)).Count(l.ctx)
  170. // 获取当前批次的所有发送失败的消息总数
  171. fail, _ := l.svcCtx.DB.Msg.Query().Where(msg.BatchNoEQ(batch.BatchNo), msg.StatusEQ(2)).Count(l.ctx)
  172. // 更新批次状态为已发送,同时更新发送总数、发送成功数量、失败数量、结束时间
  173. _, err = l.svcCtx.DB.BatchMsg.UpdateOneID(batch.ID).
  174. SetStatus(2).
  175. SetTotal(int32(total)).
  176. SetSuccess(int32(success)).
  177. SetFail(int32(fail)).
  178. SetStopTime(time.Now()).
  179. Save(l.ctx)
  180. if err != nil {
  181. l.Logger.Errorf("batchmsg update err: %v", err)
  182. continue
  183. }
  184. l.Logger.Info("batch stop: ", batch.BatchNo)
  185. }
  186. }
  187. // 根据URL获取图片名
  188. func getFileName(photoUrl string) string {
  189. u, err := url.Parse(photoUrl)
  190. if err != nil {
  191. return ""
  192. }
  193. return path.Base(u.Path)
  194. }