WeComMessageDataJob.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. package com.tzld.piaoquan.wecom.job;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.aliyun.odps.data.Record;
  5. import com.google.common.collect.Lists;
  6. import com.tzld.piaoquan.wecom.dao.mapper.*;
  7. import com.tzld.piaoquan.wecom.model.bo.PushMessage;
  8. import com.tzld.piaoquan.wecom.model.po.*;
  9. import com.tzld.piaoquan.wecom.service.MessageAttachmentService;
  10. import com.tzld.piaoquan.wecom.service.MessageService;
  11. import com.tzld.piaoquan.wecom.utils.DateUtil;
  12. import com.tzld.piaoquan.wecom.utils.MessageUtil;
  13. import com.tzld.piaoquan.wecom.utils.OdpsUtil;
  14. import com.tzld.piaoquan.wecom.utils.page.Page;
  15. import com.xxl.job.core.biz.model.ReturnT;
  16. import com.xxl.job.core.handler.annotation.XxlJob;
  17. import lombok.extern.log4j.Log4j2;
  18. import org.apache.commons.lang3.StringUtils;
  19. import org.springframework.beans.BeanUtils;
  20. import org.springframework.beans.factory.annotation.Autowired;
  21. import org.springframework.data.redis.core.RedisTemplate;
  22. import org.springframework.stereotype.Component;
  23. import org.springframework.util.CollectionUtils;
  24. import java.util.*;
  25. import java.util.stream.Collectors;
  26. import static com.tzld.piaoquan.wecom.common.constant.RedisConstant.GUARANTEED_MINIPROGRAM_KEY;
  27. import static com.tzld.piaoquan.wecom.common.constant.TimeConstant.MILLISECOND_DAY;
  28. @Log4j2
  29. @Component
  30. public class WeComMessageDataJob {
  31. @Autowired
  32. private UserMapper userMapper;
  33. @Autowired
  34. private MessageAttachmentMapper messageAttachmentMapper;
  35. @Autowired
  36. private RedisTemplate<String, Object> redisTemplate;
  37. @Autowired
  38. private MessageService messageService;
  39. @Autowired
  40. private MessageAttachmentService messageAttachmentService;
  41. @Autowired
  42. private StaffWithUserMapper staffWithUserMapper;
  43. @Autowired
  44. private StaffMapper staffMapper;
  45. @Autowired
  46. SendMessageMapper sendMessageMapper;
  47. private static final int MAX_VIDEO_NUM = 3;
  48. //历史优质视频可推送用户列表
  49. List<PushMessage> goodHistoryPushList = new ArrayList<>();
  50. //保底视频列表
  51. List<Long> guaranteedVideoIdList = new ArrayList<>();
  52. //从缓存中获取的保底视频数量
  53. int getGuaranteedVideoIdNum = 0;
  54. Map<String, String> pageMap = new HashMap<>();
  55. //初始化操作
  56. void init() {
  57. //历史优质视频获取
  58. String sql = String.format("SELECT * FROM loghubods.history_good_video_can_push_user_list where dt = %s;", DateUtil.getBeforeDayDateString());
  59. List<Record> recordList = OdpsUtil.getOdpsData(sql);
  60. if (CollectionUtils.isEmpty(recordList)) {
  61. return;
  62. }
  63. List<PushMessage> list = new ArrayList<>();
  64. for (Record record : recordList) {
  65. PushMessage pushMessage = new PushMessage();
  66. Long videoId = Long.parseLong((String) record.get(0));
  67. Set<Long> userIds = new HashSet<>(JSONObject.parseArray((String) record.get(1), Long.class));
  68. pushMessage.setVideoId(videoId);
  69. pushMessage.setUserIds(userIds);
  70. list.add(pushMessage);
  71. }
  72. goodHistoryPushList = list;
  73. getGuaranteedVideoIdNum = 0;
  74. //保底视频获取
  75. List<Long> videoIdList = Objects.requireNonNull(redisTemplate.opsForList().range(GUARANTEED_MINIPROGRAM_KEY, 0, -1))
  76. .stream().map(o -> (Integer) o).map(String::valueOf).map(Long::parseLong).collect(Collectors.toList());
  77. if (CollectionUtils.isEmpty(videoIdList)) {
  78. log.error("推送消息初始化失败,保底数据为空");
  79. throw new RuntimeException("保底数据为空");
  80. }
  81. List<Long> saveVideoIds = new ArrayList<>();
  82. for (Long videoId : videoIdList) {
  83. getGuaranteedVideoIdNum++;
  84. MessageAttachmentExample example = new MessageAttachmentExample();
  85. example.createCriteria().andMiniprogramVideoIdEqualTo(videoId);
  86. List<MessageAttachment> messageAttachmentList = messageAttachmentMapper.selectByExample(example);
  87. if (CollectionUtils.isEmpty(messageAttachmentList)) {
  88. continue;
  89. }
  90. MessageAttachment messageAttachment = messageAttachmentList.get(0);
  91. if (messageAttachment.getSendTime() != null
  92. && DateUtil.dateDifference(new Date(), messageAttachment.getSendTime()) < 180 * MILLISECOND_DAY) {
  93. continue;
  94. }
  95. saveVideoIds.add(videoId);
  96. if (saveVideoIds.size() >= MAX_VIDEO_NUM) {
  97. break;
  98. }
  99. }
  100. if (saveVideoIds.size() < MAX_VIDEO_NUM) {
  101. log.error("推送消息初始化失败,保底数据不足");
  102. throw new RuntimeException("保底数据不足");
  103. }
  104. guaranteedVideoIdList = saveVideoIds;
  105. }
  106. @XxlJob("assembleSendMessageJob")
  107. public ReturnT<String> assembleSendMessage(String param) {
  108. init();
  109. Long staffId = null;
  110. if (StringUtils.isNotEmpty(param)) {
  111. staffId = Long.parseLong(param);
  112. }
  113. UserExample example = new UserExample();
  114. example.createCriteria().andIsDeleteEqualTo(0);
  115. long count = userMapper.countByExample(example);
  116. int page = 1;
  117. int pageSize = 1000;
  118. long totalPageSize = count / pageSize + 1;
  119. for (; page <= totalPageSize; page++) {
  120. example.setPage(new Page<>(page, pageSize));
  121. List<User> userList = userMapper.selectByExample(example);
  122. if (CollectionUtils.isEmpty(userList)) {
  123. continue;
  124. }
  125. //落库逻辑
  126. List<SendMessage> allSeneMessageList = new ArrayList<>();
  127. for (User user : userList) {
  128. List<SendMessage> sendMessageList = getSendMessage(user, staffId);
  129. if (!CollectionUtils.isEmpty(sendMessageList)) {
  130. allSeneMessageList.addAll(sendMessageList);
  131. }
  132. }
  133. if (!CollectionUtils.isEmpty(allSeneMessageList)) {
  134. sendMessageMapper.insertList(allSeneMessageList);
  135. }
  136. }
  137. //组装好当天要发送的消息后 记录时间 删除保底数据
  138. saveGuaranteedVideoIdList(guaranteedVideoIdList);
  139. return ReturnT.SUCCESS;
  140. }
  141. public void saveGuaranteedVideoIdList(List<Long> videoIdList) {
  142. MessageAttachmentExample example = new MessageAttachmentExample();
  143. example.createCriteria().andMiniprogramVideoIdIn(videoIdList);
  144. List<MessageAttachment> messageAttachmentList = messageAttachmentMapper.selectByExample(example);
  145. for (MessageAttachment messageAttachment : messageAttachmentList) {
  146. MessageAttachment updateMessageAttachment = new MessageAttachment();
  147. updateMessageAttachment.setId(messageAttachment.getId());
  148. updateMessageAttachment.setSendTime(new Date());
  149. messageAttachmentMapper.updateByPrimaryKeySelective(updateMessageAttachment);
  150. }
  151. log.info("getGuaranteedVideoIdNum={}", getGuaranteedVideoIdNum);
  152. //移除从redis中获取的保底数据
  153. for (int i = 0; i < getGuaranteedVideoIdNum; i++) {
  154. redisTemplate.opsForList().leftPop(GUARANTEED_MINIPROGRAM_KEY);
  155. }
  156. }
  157. public List<SendMessage> getSendMessage(User user, Long staffId) {
  158. StaffWithUserExample example = new StaffWithUserExample();
  159. StaffWithUserExample.Criteria criteria = example.createCriteria();
  160. criteria.andUserIdEqualTo(user.getId());
  161. if (staffId != null) {
  162. criteria.andUserIdEqualTo(staffId);
  163. }
  164. List<StaffWithUser> staffWithUserList = staffWithUserMapper.selectByExample(example);
  165. if (CollectionUtils.isEmpty(staffWithUserList)) {
  166. return null;
  167. }
  168. int n = 0;
  169. List<SendMessage> sendMessageList = new ArrayList<>();
  170. SendMessage sendMessage = new SendMessage();
  171. for (PushMessage pushMessage : goodHistoryPushList) {
  172. if (pushMessage.getUserIds().contains(user.getId())) {
  173. if (n == 0) {
  174. sendMessage.setVideoId1(pushMessage.getVideoId());
  175. }
  176. if (n == 1) {
  177. sendMessage.setVideoId2(pushMessage.getVideoId());
  178. }
  179. if (n == 2) {
  180. sendMessage.setVideoId3(pushMessage.getVideoId());
  181. }
  182. n++;
  183. if (n >= MAX_VIDEO_NUM) {
  184. break;
  185. }
  186. }
  187. }
  188. //保底数据
  189. if (n < MAX_VIDEO_NUM) {
  190. for (Long videoId : guaranteedVideoIdList) {
  191. if (n == 0) {
  192. sendMessage.setVideoId1(videoId);
  193. }
  194. if (n == 1) {
  195. sendMessage.setVideoId2(videoId);
  196. }
  197. if (n == 2) {
  198. sendMessage.setVideoId3(videoId);
  199. }
  200. n++;
  201. if (n >= MAX_VIDEO_NUM) {
  202. break;
  203. }
  204. }
  205. }
  206. if (n < MAX_VIDEO_NUM) {
  207. log.error("组装数据失败 user={}", user);
  208. return null;
  209. }
  210. for (StaffWithUser staffWithUser : staffWithUserList) {
  211. SendMessage newSendMessage = new SendMessage();
  212. BeanUtils.copyProperties(sendMessage, newSendMessage);
  213. newSendMessage.setStaffId(staffWithUser.getStaffId());
  214. newSendMessage.setUserId(staffWithUser.getUserId());
  215. sendMessageList.add(newSendMessage);
  216. }
  217. return sendMessageList;
  218. }
  219. @XxlJob("pushSendMessageJob")
  220. public ReturnT<String> pushSendMessage(String param) {
  221. List<SendMessage> groupList = sendMessageMapper.getGroupList(DateUtil.getThatDayDate(), 0);
  222. if (StringUtils.isNotEmpty(param)) {
  223. groupList = groupList.stream().filter(e -> e.getStaffId() == Long.parseLong(param)).collect(Collectors.toList());
  224. }
  225. if (CollectionUtils.isEmpty(groupList)) {
  226. return ReturnT.SUCCESS;
  227. }
  228. for (SendMessage sendMessage : groupList) {
  229. sendMessage.setIsSend(0);
  230. sendMessage.setCreateTime(DateUtil.getThatDayDate());
  231. List<String> sendUserList = sendMessageMapper.selectExternalUserId3rdParty(sendMessage);
  232. boolean flag = pushMessage(sendUserList, sendMessage);
  233. if (flag) {
  234. SendMessage updateSendMessage = new SendMessage();
  235. updateSendMessage.setIsSend(1);
  236. SendMessageExample example = new SendMessageExample();
  237. example.createCriteria()
  238. .andVideoId1EqualTo(sendMessage.getVideoId1())
  239. .andVideoId2EqualTo(sendMessage.getVideoId2())
  240. .andVideoId3EqualTo(sendMessage.getVideoId3())
  241. .andStaffIdEqualTo(sendMessage.getStaffId())
  242. .andCreateTimeGreaterThan(DateUtil.getThatDayDate());
  243. sendMessageMapper.updateByExampleSelective(updateSendMessage, example);
  244. }
  245. }
  246. return ReturnT.SUCCESS;
  247. }
  248. public boolean pushMessage(List<String> sendUserList, SendMessage sendMessage) {
  249. List<JSONObject> pushList = new ArrayList<>();
  250. StaffExample staffExample = new StaffExample();
  251. staffExample.createCriteria().andIdEqualTo(sendMessage.getStaffId());
  252. List<Staff> staffList = staffMapper.selectByExample(staffExample);
  253. Staff staff = staffList.get(0);
  254. String text = messageService.getMessageText();
  255. String name = MessageUtil.getName(staff.getRemark());
  256. JSONObject jsonObject = new JSONObject();
  257. jsonObject.put("name", name);
  258. jsonObject.put("text", text);
  259. JSONArray attachments = new JSONArray();
  260. List<Long> videoIdList = new ArrayList<>();
  261. videoIdList.add(sendMessage.getVideoId1());
  262. videoIdList.add(sendMessage.getVideoId2());
  263. videoIdList.add(sendMessage.getVideoId3());
  264. for (Long videoId : videoIdList) {
  265. JSONObject attachment = new JSONObject();
  266. attachment.put("msgtype", "miniprogram");
  267. MessageAttachmentExample example = new MessageAttachmentExample();
  268. example.createCriteria().andMiniprogramVideoIdEqualTo(videoId);
  269. List<MessageAttachment> messageAttachmentList = messageAttachmentMapper.selectByExample(example);
  270. if (CollectionUtils.isEmpty(messageAttachmentList)) {
  271. throw new RuntimeException("附件信息查询异常");
  272. }
  273. MessageAttachment messageAttachment = messageAttachmentList.get(0);
  274. JSONObject miniprogram = new JSONObject();
  275. miniprogram.put("appid", messageAttachment.getAppid());
  276. miniprogram.put("title", messageAttachment.getTitle());
  277. miniprogram.put("cover", messageAttachment.getCover());
  278. String page = "";
  279. String key = staff.getStaffExtId() + "_" + videoId;
  280. if (pageMap.containsKey(key)) {
  281. page = pageMap.get(key);
  282. } else {
  283. page = messageAttachmentService.getPage(staff, videoId);
  284. pageMap.put(key, page);
  285. }
  286. if (StringUtils.isEmpty(page)) {
  287. throw new RuntimeException("获取page失败");
  288. }
  289. miniprogram.put("page", page);
  290. attachment.put("miniprogram", miniprogram);
  291. attachments.add(attachment);
  292. }
  293. jsonObject.put("attachments", attachments);
  294. List<List<String>> lists = Lists.partition(sendUserList, 10000);
  295. for (List<String> list : lists) {
  296. List<JSONObject> staffEuList = new ArrayList<>();
  297. JSONObject newJSONObject = new JSONObject();
  298. newJSONObject.putAll(jsonObject);
  299. JSONObject staff_eu = new JSONObject();
  300. staff_eu.put("staff_ext_id", staff.getStaffExtId());
  301. staff_eu.put("eu_ext_ids", list);
  302. staffEuList.add(staff_eu);
  303. newJSONObject.put("staff_eu_list", staffEuList);
  304. pushList.add(newJSONObject);
  305. }
  306. if (CollectionUtils.isEmpty(pushList)) {
  307. return false;
  308. }
  309. for (JSONObject pushJsonObject : pushList) {
  310. log.info("pushMessage pushJsonObject={}", pushJsonObject);
  311. boolean flag = messageService.pushMessage(pushJsonObject);
  312. if (!flag) {
  313. return flag;
  314. }
  315. }
  316. return true;
  317. }
  318. }