WeComMessageDataJob.java 15 KB

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