WeiXinEventConsumer.java 11.1 KB
package com.topdraw.mq.consumer;


import com.alibaba.fastjson.JSONObject;
import com.topdraw.config.RabbitMqConfig;
import com.topdraw.mq.domain.SubscribeBean;
import com.topdraw.resttemplate.RestTemplateClient;
import com.topdraw.utils.RedisUtils;
import com.topdraw.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 微信事件
 */
@Component
@Slf4j
public class WeiXinEventConsumer {


    @Autowired
    private RestTemplateClient restTemplateClient;

    private static final String QR_CODE_URL = "QR_CODE_URL_";

    /**
     * @description 删除用户收藏记录
     * @param content 消息内容
     */
    /*@RabbitHandler
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = RabbitMqConfig.COLLECTION_DELETE_QUEUE),
                    exchange = @Exchange(value = ExchangeTypes.DIRECT))},
            containerFactory = "managementRabbitListenerContainerFactory")*/
    public void deleteCollection(String content) {
        try {
            log.info("receive UserCollection delete message, content {}", content);
            this.restTemplateClient.deleteCollection(content);
        } catch (Exception e) {
            log.error("CollectionDeleteConsumer || UserCollection delete error || {}", e.toString(), e);
        }
    }

    /**
     * @description 删除全部收藏记录
     * @param content 消息内容
     */
    /*@RabbitHandler
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = RabbitMqConfig.COLLECTION_DELETE_ALL_QUEUE),
                    exchange = @Exchange(value = ExchangeTypes.DIRECT))},
            containerFactory = "managementRabbitListenerContainerFactory")*/
    @Transactional
    public void deleteAllCollection(String content) {
        try {
            log.info("receive UserCollection delete all message, content {}", content);
            this.restTemplateClient.deleteAllCollection(content);
        } catch (Exception e) {
            log.error("CollectionDeleteConsumer || UserCollection delete all error || {}", e.toString(), e);
        }
    }

    /**
     * 处理带参的二维码事件
     * @param content 消息内容
     * @description 获取公众号带参二维码
     */
    /*@RabbitHandler
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = RabbitMqConfig.GET_QR_CODE_QUEUE),
                    exchange = @Exchange(value = ExchangeTypes.DIRECT))},
            containerFactory = "managementRabbitListenerContainerFactory")*/
    public void getQrCode(String content) {
        try {
            log.info("receive get qrCode message, content {}", content);
            JSONObject jsonObject = JSONObject.parseObject(content);
            /*String appid = jsonObject.getString("appid");
            String IPTVappid = jsonObject.getString("IPTVappid");
            String platformAccount = jsonObject.getString("platformAccount");
            String sessionId = jsonObject.getString("sessionId");
            String key = QR_CODE_URL + appid + "_" + platformAccount + "_" + sessionId;
            String url = (String) redisUtils.get(key);
            if (StringUtils.isBlank(url)) {
                Map<String, String> wxInfo = WeixinUtil.getWeixinInfoByAppid(appid);
                var appType = wxInfo.get("appType");
                // 订阅号不支持带参二维码,直接返回
                if (StrUtil.isNotEmpty(appType) && ObjectUtil.equals(appType, WeChatConstants.WX_SUBSCRIPTION)) {
                    log.error("订阅号不支持带参二维码 || {} || {}", appid, content);
                    return;
                }
                QrCode qrCode = new QrCode();
                qrCode.setActionName(WeChatConstants.QR_STR_SCENE);
                if (StringUtils.isNotBlank(wxInfo.get("qrCodeExpireSeconds"))) {
                    qrCode.setExpireSeconds(Integer.valueOf(wxInfo.get("qrCodeExpireSeconds")));
                }
                ActionInfo actionInfo = new ActionInfo();
                Scene scene = new Scene();
                scene.setSceneStr(content);
                actionInfo.setScene(scene);
                qrCode.setActionInfo(actionInfo);
                JSONObject jsonQrCode = weixinRequestUtil.getQrCode(wxInfo, qrCode);
                url = jsonQrCode.getString("url");
                Integer expireSeconds = jsonQrCode.getInteger("expire_seconds");
                redisUtils.set(key, url, expireSeconds, TimeUnit.SECONDS);
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("sessionId", sessionId);
            map.put("url", url);
            map.put("appid", appid);
            map.put("IPTVappid", IPTVappid);
            map.put("platformAccount", platformAccount);
            map.put("extraInfo", content);*/
            restTemplateClient.sendQrCodeMessage(content);
        } catch (Exception e) {
            log.error("GetQrCodeConsumer || get qrCode error || {}", e.toString(), e);
        }
    }

    /**
     * 关注和取关事件
     * eg:
     * {
     * "appIdMap": "{\"mpId\":\"234\"}",
     * "allFieldsMap":"{\"FromUserName\":\"4343\",\"MsgType\":\"event\",\"Event\":\"unsubscribe\"}"
     * }
     * @param content
     */
    /*@RabbitHandler
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = RabbitMqConfig.WEIXIN_SUBORUNSUB_QUEUE),
                    exchange = @Exchange(value = ExchangeTypes.DIRECT))},
            containerFactory = "managementRabbitListenerContainerFactory")*/
    @Transactional
    public void subOrUnSubEvent(String content) {
        try {
            log.info("receive wxu subOrUnSub message, content {}", content);
            JSONObject jsonObject = JSONObject.parseObject(content);

            JSONObject map = jsonObject.getJSONObject("appIdMap");
            JSONObject wechatMsg = jsonObject.getJSONObject("allFieldsMap");
            String appid = map.getString("mpId");
            String unionid = map.getString("unionid");
//            Map<String, String> wxInfoMap = WeixinUtil.getWeixinInfoByAppid(appid);

            String openid = wechatMsg.getString("FromUserName");
            String msgType = wechatMsg.getString("MsgType");
            if ("event".equals(msgType)) {
                String event = wechatMsg.getString("Event");
                log.info("event ===>> [{}]",event);
                String eventKey = wechatMsg.getString("EventKey");

                SubscribeBean subscribeBean = new SubscribeBean();
                subscribeBean.setAppId(appid);
                subscribeBean.setOpenId(openid);
                subscribeBean.setUnionid(unionid);
                subscribeBean.setEventKey(eventKey);

                if (event.equals("subscribe"))
                    this.restTemplateClient.subscribe(subscribeBean);

                if (event.equals("unsubscribe"))
                    this.restTemplateClient.unsubscribe(subscribeBean);

            }

        } catch (Exception e) {
            log.error("WXSubscribeConsumer || subOrUnSub msg error || {} || {}", content, e.getMessage());
        }
    }

    /**
     * @description 添加收藏记录
     * @param content 消息内容
     */
   /* @RabbitHandler
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = RabbitMqConfig.COLLECTION_ADD_QUEUE),
                    exchange = @Exchange(value = ExchangeTypes.DIRECT))},
            containerFactory = "managementRabbitListenerContainerFactory")*/
    @Transactional
    public void addCollection(String content) {
        try {
            log.info("receive UserCollection add message, content {}", content);
            JSONObject jsonObject = JSONObject.parseObject(content);
            String platformAccount = jsonObject.getString("platformAccount");
            String data = jsonObject.getString("data");
            if (StringUtils.isBlank(data) || !data.startsWith("[")) {
//                return;
            }
            /*Optional<TvUser> userOptional = tvUserRepository.findByPlatformAccount(platformAccount);
            if (!userOptional.isPresent()) {
                return;
            }
            Long tvUserId = userOptional.get().getId();
            List<UserCollectionMq> userCollectionMqList = JSONObject.parseArray(data, UserCollectionMq.class);
            if (userCollectionMqList == null || userCollectionMqList.isEmpty()) {
                return;
            }
            Map<Long, List<UserCollectionMq>> collect = userCollectionMqList.stream().collect(Collectors.groupingBy(UserCollectionMq::getUserCollectionId));
            for (Map.Entry<Long, List<UserCollectionMq>> entry : collect.entrySet()) {
                List<UserCollectionMq> value = entry.getValue();
                UserCollectionMq userCollectionMq = value.get(0);
                if (StringUtils.isBlank(userCollectionMq.getName())) {
                    userCollectionMq.setName("DEFAULT");
                }
                UserCollection userCollection = userCollectionRepository
                        .findFirstByUserIdAndTypeAndName(tvUserId, userCollectionMq.getType(), userCollectionMq.getName()).orElseGet(UserCollection::new);
                userCollection.setAppId(userCollectionMq.getAppId())
                        .setUserId(tvUserId)
                        .setName(userCollectionMq.getName())
                        .setType(userCollectionMq.getType())
                        .setCount(userCollection.getCount() == null ? value.size() : userCollection.getCount() + value.size());
                UserCollection userCollectionSave = userCollectionRepository.save(userCollection);
                for (UserCollectionMq collectionMq : value) {
                    UserCollectionDetail userCollectionDetail = collectionMq2DetailMapper.toEntity(collectionMq);
                    Optional<UserCollectionDetail> userCollectionDetailOptional = userCollectionDetailRepository
                            .findByDetailIdAndDetailTypeAndUserCollectionId(userCollectionDetail.getDetailId(), userCollectionDetail.getDetailType(), userCollectionSave.getId());
                    //观影记录同一天只存一条记录
                    if (userCollectionDetailOptional.isPresent() &&
                            DateUtil.isSameDay(new Date(userCollectionDetailOptional.get().getCreateTime().getTime()), new Date())) {
                        userCollectionDetail.setId(userCollectionDetailOptional.get().getId());
                    } else {
                        userCollectionDetail.setId(null)
                                .setUserCollectionId(userCollectionSave.getId());
                    }
                    userCollectionDetailRepository.save(userCollectionDetail);
                }
            }*/

            this.restTemplateClient.addCollection(content);
        } catch (Exception e) {
            log.error("CollectionAddConsumer || UserCollection add error || {}", e.toString(), e);
        }
    }

}