Commit 86cf9aed by 孙喜旺

会话存档优化,暂时弃用elasticsearch搜索引擎

1 parent d213e95d
Showing 20 changed files with 750 additions and 156 deletions
package com.linkwechat.web.controller.wecom;
import com.linkwechat.common.annotation.Log;
import com.linkwechat.common.core.controller.BaseController;
import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.common.core.page.TableDataInfo;
import com.linkwechat.common.enums.BusinessType;
import com.linkwechat.common.utils.poi.ExcelUtil;
import com.linkwechat.wecom.domain.WeChatContactMsg;
import com.linkwechat.wecom.domain.vo.WeChatContactMsgVo;
import com.linkwechat.wecom.service.IWeChatContactMsgService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
/**
* 会话消息Controller
*
* @author ruoyi
* @date 2021-07-28
*/
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/linkwechat/msg" )
public class WeChatContactMsgController extends BaseController {
private final IWeChatContactMsgService iWeChatContactMsgService;
/**
* 查询会话消息列表
*/
@PreAuthorize("@ss.hasPermi('linkwechat:msg:list')")
@GetMapping("/list")
public TableDataInfo list(WeChatContactMsg weChatContactMsg) {
startPage();
List<WeChatContactMsg> list = iWeChatContactMsgService.queryList(weChatContactMsg);
return getDataTable(list);
}
/**
* 导出会话消息列表
*/
@PreAuthorize("@ss.hasPermi('linkwechat:msg:export')" )
@Log(title = "会话消息" , businessType = BusinessType.EXPORT)
@GetMapping("/export" )
public AjaxResult export(WeChatContactMsg weChatContactMsg) {
List<WeChatContactMsg> list = iWeChatContactMsgService.queryList(weChatContactMsg);
ExcelUtil<WeChatContactMsg> util = new ExcelUtil<WeChatContactMsg>(WeChatContactMsg.class);
return util.exportExcel(list, "msg" );
}
/**
* 获取会话消息详细信息
*/
@PreAuthorize("@ss.hasPermi('linkwechat:msg:query')" )
@GetMapping(value = "/{id}" )
public AjaxResult getInfo(@PathVariable("id" ) Long id) {
return AjaxResult.success(iWeChatContactMsgService.getById(id));
}
/**
* 新增会话消息
*/
@PreAuthorize("@ss.hasPermi('linkwechat:msg:add')" )
@Log(title = "会话消息" , businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody WeChatContactMsg weChatContactMsg) {
return toAjax(iWeChatContactMsgService.save(weChatContactMsg) ? 1 : 0);
}
/**
* 修改会话消息
*/
@PreAuthorize("@ss.hasPermi('linkwechat:msg:edit')" )
@Log(title = "会话消息" , businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody WeChatContactMsg weChatContactMsg) {
return toAjax(iWeChatContactMsgService.updateById(weChatContactMsg) ? 1 : 0);
}
/**
* 删除会话消息
*/
@PreAuthorize("@ss.hasPermi('linkwechat:msg:remove')" )
@Log(title = "会话消息" , businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}" )
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(iWeChatContactMsgService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
}
/**
* 外部联系人/单聊 会话列表
*/
@Log(title = "外部联系人/单聊 会话列表" , businessType = BusinessType.OTHER)
@GetMapping("selectExternalChatList/{fromId}" )
public AjaxResult<List<WeChatContactMsgVo>> selectExternalChatList(@PathVariable("fromId") String fromId) {
return AjaxResult.success(iWeChatContactMsgService.selectExternalChatList(fromId));
}
/**
* 内部联系人 会话列表
*/
@Log(title = "内部联系人 会话列表" , businessType = BusinessType.OTHER)
@GetMapping("selectInternalChatList/{fromId}" )
public AjaxResult<List<WeChatContactMsgVo>> selectInternalChatList(@PathVariable("fromId") String fromId) {
return AjaxResult.success(iWeChatContactMsgService.selectInternalChatList(fromId));
}
/**
* 群聊 会话列表
*/
@Log(title = "群聊 会话列表" , businessType = BusinessType.OTHER)
@GetMapping("selectGroupChatList/{fromId}" )
public AjaxResult<List<WeChatContactMsgVo>> selectGroupChatList(@PathVariable("fromId") String fromId) {
return AjaxResult.success(iWeChatContactMsgService.selectGroupChatList(fromId));
}
}
......@@ -81,7 +81,6 @@ logging:
level:
com.ruoyi: debug
org.springframework: warn
path: ./logs
path:
log: ./logs
......@@ -245,16 +244,16 @@ xss:
urlPatterns: /system/*,/monitor/*,/tool/*
# elasticsearch配置
elasticsearch:
schema: http
address:
userName: ""
password: ""
connectTimeout: 10000
socketTimeout: 10000
connectionRequestTimeout: 10000
maxConnectNum: 100
maxConnectPerRoute: 100
#elasticsearch:
# schema: http
# address:
# userName: ""
# password: ""
# connectTimeout: 10000
# socketTimeout: 10000
# connectionRequestTimeout: 10000
# maxConnectNum: 100
# maxConnectPerRoute: 100
# forest配置
forest:
......
/*
package com.linkwechat.common.config;
import org.apache.http.HttpHost;
......@@ -14,23 +15,29 @@ import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
*/
/**
* @author danmo
* @description ElasticSearch 配置
* @date 2020/12/4 9:59
**/
**//*
@Configuration
public class ElasticSearchConfig {
/**
*/
/**
* 协议
*/
*//*
@Value("${elasticsearch.schema:http}")
private String schema;
/**
*/
/**
* 集群地址,如果有多个用“,”隔开
*/
*//*
@Value("${elasticsearch.address}")
private String address;
......@@ -39,33 +46,43 @@ public class ElasticSearchConfig {
@Value("${elasticsearch.password}")
private String password;
/**
*/
/**
* 连接超时时间
*/
*//*
@Value("${elasticsearch.connectTimeout:5000}")
private int connectTimeout;
/**
*/
/**
* Socket 连接超时时间
*/
*//*
@Value("${elasticsearch.socketTimeout:10000}")
private int socketTimeout;
/**
*/
/**
* 获取连接的超时时间
*/
*//*
@Value("${elasticsearch.connectionRequestTimeout:5000}")
private int connectionRequestTimeout;
/**
*/
/**
* 最大连接数
*/
*//*
@Value("${elasticsearch.maxConnectNum:100}")
private int maxConnectNum;
/**
*/
/**
* 最大路由连接数
*/
*//*
@Value("${elasticsearch.maxConnectPerRoute:100}")
private int maxConnectPerRoute;
......@@ -102,4 +119,4 @@ public class ElasticSearchConfig {
return new RestHighLevelClient(builder);
}
}
\ No newline at end of file
}*/
......@@ -39,7 +39,4 @@ public class WeComeConfig {
/**多租户相关表*/
private String[] needTenant=new String[]{};
/**ES索引KEY**/
private String chatKey;
}
......@@ -404,4 +404,8 @@ public class WeConstans {
*/
public static final String SEND_MESSAGE_CUSTOMER_PART = "1";
/**
* 会话消息订阅的频道
*/
public static final String CONVERSATION_MSG_CHANNEL = "CONVERSATION_MSG_CHANNEL";
}
......@@ -82,6 +82,8 @@ public class WeCorpAccount extends BaseEntity
@ApiModelProperty("客户流失通知开关 0:关闭 1:开启")
private String customerChurnNoticeSwitch = Constants.NORMAL_CODE;
@ApiModelProperty("会话存档私钥")
private String financePrivateKey;
@ApiModelProperty("企业管理员账号")
private String corpAccount;
......
......@@ -5,11 +5,14 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* spring redis 工具类
......@@ -224,4 +227,16 @@ public class RedisCache
{
return redisTemplate.keys(pattern);
}
/**
* 将给定的消息发布到给定的频道
*
* @param channel 要发布到的频道
* @param message 消息内容
*/
public void convertAndSend(String channel, Object message)
{
redisTemplate.convertAndSend(channel,message);
}
}
package com.linkwechat.common.utils.wecom;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
......@@ -21,6 +22,13 @@ import java.util.Base64;
* @date 2020/12/7 23:37
**/
public class RSAUtil {
static{
try{
Security.addProvider(new BouncyCastleProvider());
}catch(Exception e){
e.printStackTrace();
}
}
/**
* RSA pkcs1 2048bit 解密工具,
* 获取私钥PrivateKey
......
package com.linkwechat.framework.config;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.framework.listener.ChatMsgCheckListener;
import com.linkwechat.framework.listener.ChatMsgListener;
import com.linkwechat.framework.listener.EmpleCodeExpiredListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
......@@ -53,14 +59,30 @@ public class RedisConfig extends CachingConfigurerSupport
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
public RedisMessageListenerContainer redisMessageListenerContainer(MessageListenerAdapter chatMsgAdapter,
MessageListenerAdapter chatMsgCheckAdapter) {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
//定义监听渠道
Topic msgChannel = new ChannelTopic(WeConstans.CONVERSATION_MSG_CHANNEL);
//定义监听器监听的Redis的消息
redisMessageListenerContainer.addMessageListener(chatMsgAdapter,msgChannel);
redisMessageListenerContainer.addMessageListener(chatMsgCheckAdapter,msgChannel);
return redisMessageListenerContainer;
}
@Bean
public EmpleCodeExpiredListener codeExpiredListener() {
return new EmpleCodeExpiredListener(this.redisMessageListenerContainer());
return new EmpleCodeExpiredListener(this.redisMessageListenerContainer(null,null));
}
@Bean
MessageListenerAdapter chatMsgAdapter(ChatMsgListener receiver){
return new MessageListenerAdapter(receiver);
}
@Bean
MessageListenerAdapter chatMsgCheckAdapter(ChatMsgCheckListener receiver){
return new MessageListenerAdapter(receiver);
}
}
package com.linkwechat.framework.listener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
/**
* @author danmo
* @description 会话存档会话审核订阅者
* @date 2021/7/27 23:11
**/
@Slf4j
@Component
public class ChatMsgCheckListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
log.info(">> 订阅消息,会话审核订阅者:{}", message);
String body = new String(message.getBody());
//渠道名称
String topic = new String(pattern);
System.out.println(body);
System.out.println(topic);
}
}
package com.linkwechat.framework.listener;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.common.utils.Threads;
import com.linkwechat.wecom.domain.WeChatContactMsg;
import com.linkwechat.wecom.service.IWeChatContactMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.concurrent.Future;
/**
* @author danmo
* @description 会话存档订阅者
* @date 2021/7/27 23:11
**/
@Slf4j
@Component
public class ChatMsgListener implements MessageListener {
@Autowired
private IWeChatContactMsgService weChatContactMsgService;
@Override
public void onMessage(Message message, byte[] pattern) {
JSONObject jsonObject = JSONObject.parseObject(new String(message.getBody()));
log.info(">> 订阅消息,会话存档消息:{}", jsonObject.toJSONString());
Threads.SINGLE_THREAD_POOL.submit(() -> msgContextHandle(jsonObject));
}
private void msgContextHandle(JSONObject jsonObject){
WeChatContactMsg weChatContactMsg = new WeChatContactMsg();
weChatContactMsg.setMsgId(jsonObject.getString("msgid"));
weChatContactMsg.setFromId(jsonObject.getString("from"));
weChatContactMsg.setToList(CollectionUtil.join(jsonObject.getJSONArray("tolist"), ","));
weChatContactMsg.setAction(jsonObject.getString("action"));
weChatContactMsg.setRoomId(jsonObject.getString("roomid"));
weChatContactMsg.setMsgType(jsonObject.getString("msgtype"));
weChatContactMsg.setMsgTime(new Date(jsonObject.getLong("msgtime")));
weChatContactMsg.setSeq(jsonObject.getLong("seq"));
String objectString = jsonObject.getString(jsonObject.getString("msgtype"));
if(StringUtils.isNotEmpty(objectString)){
weChatContactMsg.setContact(objectString);
}else if("external_redpacket".equals(weChatContactMsg.getMsgType())){
weChatContactMsg.setContact(jsonObject.getString("redpacket"));
}else if("docmsg".equals(weChatContactMsg.getMsgType())){
weChatContactMsg.setContact(jsonObject.getString("doc"));
}else if("markdown".equals(weChatContactMsg.getMsgType())
|| "news".equals(weChatContactMsg.getMsgType())){
weChatContactMsg.setContact(jsonObject.getString("info"));
}
if(!weChatContactMsg.getMsgId().contains("external")){
weChatContactMsg.setIsExternal(1);
}
LambdaQueryWrapper<WeChatContactMsg> wrapper = new LambdaQueryWrapper<WeChatContactMsg>()
.eq(WeChatContactMsg::getMsgId, weChatContactMsg.getMsgId())
.eq(WeChatContactMsg::getFromId, weChatContactMsg.getFromId());
if(!weChatContactMsgService.update(weChatContactMsg,wrapper)){
weChatContactMsgService.save(weChatContactMsg);
}
}
}
package com.linkwechat.quartz.task;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.domain.WeChatContactMsg;
import com.linkwechat.wecom.service.IWeChatContactMsgService;
import com.linkwechat.wecom.service.IWeCorpAccountService;
import com.tencent.wework.FinanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author danmo
* @description 会话存档定时任务
* @date 2021/7/26 15:50
**/
@Slf4j
@Component("conversationArchiveTask")
public class ConversationArchiveTask {
@Autowired
private RedisCache redisCache;
@Autowired
private IWeCorpAccountService weCorpAccountService;
@Autowired
private IWeChatContactMsgService weChatContactMsgService;
public void FinanceTask(String corpId, String secret, String privateKey){
log.info("执行有参方法: params:{},{}", corpId, secret);
Long seqLong = 0L;
log.info(">>>>>>>seq:{}", seqLong);
if(StringUtils.isEmpty(privateKey)){
WeCorpAccount validWeCorpAccount = weCorpAccountService.findValidWeCorpAccount();
privateKey = validWeCorpAccount.getFinancePrivateKey();
}
LambdaQueryWrapper<WeChatContactMsg> wrapper = new LambdaQueryWrapper<WeChatContactMsg>().orderByDesc(WeChatContactMsg::getSeq).last("limit 1");
WeChatContactMsg weChatContactMsg = weChatContactMsgService.getOne(wrapper);
if(weChatContactMsg != null){
seqLong = weChatContactMsg.getSeq();
}
FinanceService financeService = new FinanceService(corpId,secret,privateKey);
financeService.getChatData(seqLong,(data) -> redisCache.convertAndSend(WeConstans.CONVERSATION_MSG_CHANNEL,data));
}
}
package com.linkwechat.quartz.task;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.linkwechat.common.config.WeComeConfig;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.elasticsearch.ElasticSearch;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.domain.WeCustomer;
import com.linkwechat.wecom.domain.WeCustomerMessageTimeTask;
import com.linkwechat.wecom.mapper.WeCustomerMessageTimeTaskMapper;
import com.linkwechat.wecom.service.*;
import com.tencent.wework.FinanceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicLong;
/**
* 定时任务调度测试
*
......@@ -38,32 +12,6 @@ import java.util.concurrent.atomic.AtomicLong;
@Slf4j
@Component("ryTask")
public class RyTask {
@Autowired
private ElasticSearch elasticSearch;
@Autowired
private RedisCache redisCache;
@Autowired
private IWeChatContactMappingService weChatContactMappingService;
@Autowired
private IWeSensitiveService weSensitiveService;
@Autowired
private IWeSensitiveActHitService weSensitiveActHitService;
@Autowired
private WeComeConfig weComeConfig;
@PostConstruct
public void init() {
try{
//初始化es索引
elasticSearch.createIndex2(weComeConfig.getChatKey(), elasticSearch.getFinanceMapping());
}catch (Exception e){
log.error(e.getMessage());
}
}
public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i));
......@@ -76,76 +24,5 @@ public class RyTask {
public void ryNoParams() {
System.out.println("执行无参方法");
}
public void FinanceTask(String corpId, String secret) throws IOException {
log.info("执行有参方法: params:{},{}", corpId, secret);
//创建索引
elasticSearch.createIndex2(weComeConfig.getChatKey(), elasticSearch.getFinanceMapping());
//从缓存中获取消息标识
Object seqObject = Optional.ofNullable(redisCache.getCacheObject(WeConstans.CONTACT_SEQ_KEY)).orElse(0L);
Long seqLong = Long.valueOf(String.valueOf(seqObject));
AtomicLong index = new AtomicLong(seqLong);
if (index.get() == 0) {
setRedisCacheSeqValue(index);
}
log.info(">>>>>>>seq:{}", index.get());
FinanceUtils.initSDK(corpId, secret);
List<JSONObject> chatDataList = FinanceUtils.getChatData(index.get(),
"",
"", redisCache);
if (CollectionUtil.isNotEmpty(chatDataList)) {
try {
List<JSONObject> elasticSearchEntities = weChatContactMappingService.saveWeChatContactMapping(chatDataList);
//获取敏感行为命中信息
weSensitiveActHitService.hitWeSensitiveAct(chatDataList);
elasticSearch.insertBatchAsync(weComeConfig.getChatKey(), elasticSearchEntities, weSensitiveService::hitSensitive);
} catch (Exception e) {
log.error("消息处理异常:ex:{}", e);
e.printStackTrace();
}
}
}
// public void WeCustomers() {
// //查询系统所有客户
// List<WeCustomer> cacheList = redisCache.getCacheList(WeConstans.WECUSTOMERS_KEY);
// if (CollectionUtils.isEmpty(cacheList)) {
// List<WeCustomer> customers = weCustomerService.selectWeCustomerList(null);
// redisCache.setCacheList(WeConstans.WECUSTOMERS_KEY, customers);
// } else {
// List<WeCustomer> customers = weCustomerService.selectWeCustomerList(null);
// List<WeCustomer> weCustomers = redisCache.getCacheList(WeConstans.WECUSTOMERS_KEY);
// if (CollectionUtils.isNotEmpty(weCustomers) && weCustomers.size() < customers.size()) {
// redisCache.setCacheList(WeConstans.WECUSTOMERS_KEY, customers);
// }
// }
// }
private void setRedisCacheSeqValue(AtomicLong index) {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
SortBuilder<?> sortBuilderPrice = SortBuilders.fieldSort(WeConstans.CONTACT_SEQ_KEY).order(SortOrder.DESC);
searchSourceBuilder.sort(sortBuilderPrice);
searchSourceBuilder.size(1);
List<JSONObject> searchResultList = elasticSearch.search(weComeConfig.getChatKey(), searchSourceBuilder, JSONObject.class);
if(CollectionUtil.isNotEmpty(searchResultList)){
searchResultList.stream().findFirst().ifPresent(result -> {
index.set(result.getLong(WeConstans.CONTACT_SEQ_KEY) + 1);
});
redisCache.setCacheObject(WeConstans.CONTACT_SEQ_KEY, index);
}
}
/**
* @param corpId 企业id
* @param secret 会话密钥
*/
public void getPermitUserList(String corpId, String secret) {
log.info("执行有参方法: params:{},{}", corpId, secret);
}
}
package com.linkwechat.wecom.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.linkwechat.common.annotation.Excel;
import com.linkwechat.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* 会话消息对象 we_chat_contact_msg
*
* @author ruoyi
* @date 2021-07-28
*/
@ApiModel
@Data
@NoArgsConstructor
@Accessors(chain = true)
@TableName("we_chat_contact_msg")
public class WeChatContactMsg extends BaseEntity implements Serializable {
private static final long serialVersionUID=1L;
/** 主键id */
@TableId(value = "id",type = IdType.AUTO)
@ApiModelProperty("主键id")
private Long id;
/** 消息id */
@Excel(name = "消息id")
@ApiModelProperty("消息id")
private String msgId;
/** 消息记录seq值 */
@ApiModelProperty("消息记录seq值")
private Long seq;
/** 发送人id */
@Excel(name = "发送人id")
@ApiModelProperty("发送人id")
private String fromId;
/** 接收人id(列表) */
@Excel(name = "接收人id" , readConverterExp = "列=表")
@ApiModelProperty("接收人id")
private String toList;
/** 群聊id */
@Excel(name = "群聊id")
@ApiModelProperty("群聊id")
private String roomId;
/** 消息类型 */
@Excel(name = "消息类型")
@ApiModelProperty("消息类型")
private String action;
/** 消息类型(如:文本,图片) */
@Excel(name = "消息类型(如:文本,图片)")
@ApiModelProperty("消息类型(如:文本,图片)")
private String msgType;
/** 发送时间 */
@Excel(name = "发送时间")
@ApiModelProperty("发送时间")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date msgTime;
/** 消息内容 */
@Excel(name = "消息内容")
@ApiModelProperty("消息内容")
private String contact;
/** 是否为外部聊天 0 外部 1 内部 */
@ApiModelProperty("是否为外部聊天 0 外部 1 内部")
private Integer isExternal;
}
package com.linkwechat.wecom.domain.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* @author danmo
* @description 会话信息
* @date 2021/7/29 0:21
**/
@ApiModel
@Data
public class WeChatContactMsgVo {
@ApiModelProperty("接收人id")
private String receiver;
@ApiModelProperty("名称")
private String name;
@ApiModelProperty("头像")
private String avatar;
@ApiModelProperty("消息发送时间")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date msgTime;
@ApiModelProperty("消息类型(如:文本,图片)")
private String msgType;
@ApiModelProperty("消息类型(send(发送消息)/recall(撤回消息)/switch(切换企业日志))")
private String action;
@ApiModelProperty("消息内容")
private String contact;
}
package com.linkwechat.wecom.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkwechat.wecom.domain.WeChatContactMsg;
import com.linkwechat.wecom.domain.vo.WeChatContactMsgVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 会话消息Mapper接口
*
* @author ruoyi
* @date 2021-07-28
*/
public interface WeChatContactMsgMapper extends BaseMapper<WeChatContactMsg> {
/**
* 外部联系人/单聊 会话列表
* @param fromId 消息发送人id
* @return 会话列表
*/
List<WeChatContactMsgVo> selectExternalChatList(@Param("fromId") String fromId);
/**
* 内部联系人 会话列表
* @param fromId 消息发送人id
* @return 会话列表
*/
List<WeChatContactMsgVo> selectInternalChatList(@Param("fromId") String fromId);
/**
* 群聊 会话列表
* @param fromId 消息发送人id
* @return 会话列表
*/
List<WeChatContactMsgVo> selectGroupChatList(@Param("fromId") String fromId);
}
package com.linkwechat.wecom.service;
import com.linkwechat.wecom.domain.WeChatContactMsg;
import com.baomidou.mybatisplus.extension.service.IService;
import com.linkwechat.wecom.domain.vo.WeChatContactMsgVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 会话消息Service接口
*
* @author ruoyi
* @date 2021-07-28
*/
public interface IWeChatContactMsgService extends IService<WeChatContactMsg> {
/**
* 查询列表
*/
List<WeChatContactMsg> queryList(WeChatContactMsg weChatContactMsg);
/**
* 外部联系人/单聊 会话列表
* @param fromId 消息发送人id
* @return 会话列表
*/
List<WeChatContactMsgVo> selectExternalChatList(String fromId);
/**
* 内部联系人 会话列表
* @param fromId 消息发送人id
* @return 会话列表
*/
List<WeChatContactMsgVo> selectInternalChatList(String fromId);
/**
* 群聊 会话列表
* @param fromId 消息发送人id
* @return 会话列表
*/
List<WeChatContactMsgVo> selectGroupChatList(String fromId);
}
package com.linkwechat.wecom.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.linkwechat.wecom.domain.dto.WeGroupMemberDto;
import com.linkwechat.wecom.domain.vo.WeChatContactMsgVo;
import com.linkwechat.wecom.service.IWeGroupMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import com.linkwechat.wecom.mapper.WeChatContactMsgMapper;
import com.linkwechat.wecom.domain.WeChatContactMsg;
import com.linkwechat.wecom.service.IWeChatContactMsgService;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 会话消息Service业务层处理
*
* @author ruoyi
* @date 2021-07-28
*/
@Service
public class WeChatContactMsgServiceImpl extends ServiceImpl<WeChatContactMsgMapper, WeChatContactMsg> implements IWeChatContactMsgService {
@Autowired
private IWeGroupMemberService weGroupMemberService;
@Override
public List<WeChatContactMsg> queryList(WeChatContactMsg weChatContactMsg) {
LambdaQueryWrapper<WeChatContactMsg> lqw = Wrappers.lambdaQuery();
if (StringUtils.isNotBlank(weChatContactMsg.getMsgId())){
lqw.eq(WeChatContactMsg::getMsgId ,weChatContactMsg.getMsgId());
}
if (StringUtils.isNotBlank(weChatContactMsg.getFromId())){
lqw.eq(WeChatContactMsg::getFromId ,weChatContactMsg.getFromId());
}
if (StringUtils.isNotBlank(weChatContactMsg.getToList())){
lqw.eq(WeChatContactMsg::getToList ,weChatContactMsg.getToList());
}
if (StringUtils.isNotBlank(weChatContactMsg.getRoomId())){
lqw.eq(WeChatContactMsg::getRoomId ,weChatContactMsg.getRoomId());
}
if (StringUtils.isNotBlank(weChatContactMsg.getAction())){
lqw.eq(WeChatContactMsg::getAction ,weChatContactMsg.getAction());
}
if (StringUtils.isNotBlank(weChatContactMsg.getMsgType())){
lqw.eq(WeChatContactMsg::getMsgType ,weChatContactMsg.getMsgType());
}
if (weChatContactMsg.getMsgTime() != null){
lqw.eq(WeChatContactMsg::getMsgTime ,weChatContactMsg.getMsgTime());
}
if (StringUtils.isNotBlank(weChatContactMsg.getContact())){
lqw.eq(WeChatContactMsg::getContact ,weChatContactMsg.getContact());
}
return this.list(lqw);
}
@Override
public List<WeChatContactMsgVo> selectExternalChatList(String fromId) {
return this.baseMapper.selectExternalChatList(fromId);
}
@Override
public List<WeChatContactMsgVo> selectInternalChatList(String fromId) {
return this.baseMapper.selectInternalChatList(fromId);
}
@Override
public List<WeChatContactMsgVo> selectGroupChatList(String fromId) {
List<WeChatContactMsgVo> weChatContactMsgVos = this.baseMapper.selectGroupChatList(fromId);
if(CollectionUtil.isNotEmpty(weChatContactMsgVos)){
weChatContactMsgVos.forEach(msg ->{
List<WeGroupMemberDto> weGroupMemberDtos = weGroupMemberService.selectWeGroupMemberListByChatId(msg.getReceiver());
if(CollectionUtil.isNotEmpty(weGroupMemberDtos)){
if(StringUtils.isEmpty(msg.getName())){
String names = weGroupMemberDtos.stream().map(WeGroupMemberDto::getMemberName)
.filter(StringUtils::isNotEmpty).collect(Collectors.joining(","));
msg.setName(names);
}
String avatars = weGroupMemberDtos.stream().map(WeGroupMemberDto::getMemberAvatar)
.filter(StringUtils::isNotEmpty).collect(Collectors.joining(","));
msg.setAvatar(avatars);
}
});
}
return this.baseMapper.selectGroupChatList(fromId);
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.linkwechat.wecom.mapper.WeChatContactMsgMapper">
<resultMap type="WeChatContactMsg" id="WeChatContactMsgResult">
<result property="id" column="id"/>
<result property="msgId" column="msg_id"/>
<result property="fromId" column="from_id"/>
<result property="toList" column="to_list"/>
<result property="roomId" column="room_id"/>
<result property="action" column="action"/>
<result property="msgType" column="msg_type"/>
<result property="msgTime" column="msg_time"/>
<result property="contact" column="contact"/>
<result property="createBy" column="create_by"/>
<result property="createTime" column="create_time"/>
<result property="updateBy" column="update_by"/>
<result property="updateTime" column="update_time"/>
</resultMap>
<select id="selectExternalChatList" resultType="com.linkwechat.wecom.domain.vo.WeChatContactMsgVo">
select t.*, wc.name, wc.avatar from
(
select receiver, msg_time,`action`, msg_type, contact
from
(
select to_list as receiver, `action` , msg_time, msg_type, contact
from we_chat_contact_msg
where from_id = ${fromId} and is_external = 0 and room_id = ''
union
select from_id as receiver, `action`, msg_time, msg_type, contact
from we_chat_contact_msg
where FIND_IN_SET(${fromId}, to_list) and is_external = 0 and room_id = ''
order by msg_time desc
) as msg group by receiver order by msg.msg_time desc) t
inner join we_customer wc on t.receiver = wc.external_userid;
</select>
<select id="selectInternalChatList" resultType="com.linkwechat.wecom.domain.vo.WeChatContactMsgVo">
select t.*, wu.user_name as name , wu.head_image_url as avatar from
(
select receiver, msg_time,`action`, msg_type, contact
from
(
select to_list as receiver, `action` , msg_time, msg_type, contact
from we_chat_contact_msg
where from_id = ${fromId} and is_external = 1 and room_id = ''
union
select from_id as receiver, `action`, msg_time, msg_type, contact
from we_chat_contact_msg
where FIND_IN_SET(${fromId}, to_list) and is_external = 1 and room_id = ''
order by msg_time desc
) as msg group by receiver order by msg.msg_time desc) t
inner join we_user wu on t.receiver = wu.user_id;
</select>
<select id="selectGroupChatList" resultType="com.linkwechat.wecom.domain.vo.WeChatContactMsgVo">
select t.*, wg.group_name as name , '' as avatar from
(
select receiver, msg_time,`action`, msg_type, contact
from
(
select to_list as receiver, `action` , msg_time, msg_type, contact
from we_chat_contact_msg
where from_id = ${fromId} and <![CDATA[ room_id <> '' ]]>
union
select from_id as receiver, `action`, msg_time, msg_type, contact
from we_chat_contact_msg
where FIND_IN_SET(${fromId}, to_list) and <![CDATA[ room_id <> '' ]]>
order by msg_time desc
) as msg group by receiver order by msg.msg_time desc) t
inner join we_group wg on t.receiver = wg.chat_id;
</select>
</mapper>
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!