Commit b2ce6511 by leejoker

增加敏感词过滤回调处理

1 parent ac4ae6f4
package com.linkwechat.framework.listener; package com.linkwechat.framework.listener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.enums.MessageType;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.common.utils.Threads;
import com.linkwechat.wecom.client.WeMessagePushClient;
import com.linkwechat.wecom.domain.WeChatContactMsg;
import com.linkwechat.wecom.domain.WeChatContactSensitiveMsg;
import com.linkwechat.wecom.domain.WeSensitive;
import com.linkwechat.wecom.domain.dto.WeMessagePushDto;
import com.linkwechat.wecom.domain.dto.message.TextMessageDto;
import com.linkwechat.wecom.mapper.WeChatContactSensitiveMsgMapper;
import com.linkwechat.wecom.mapper.WeSensitiveMapper;
import com.linkwechat.wecom.service.IWeChatContactMsgService;
import com.linkwechat.wecom.service.IWeCorpAccountService;
import com.linkwechat.wecom.service.IWeSensitiveService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener; import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/** /**
* @author danmo * @author danmo
* @description 会话存档会话审核订阅者 * @description 会话存档会话审核订阅者
...@@ -14,14 +37,102 @@ import org.springframework.stereotype.Component; ...@@ -14,14 +37,102 @@ import org.springframework.stereotype.Component;
@Component @Component
public class ChatMsgCheckListener implements MessageListener { public class ChatMsgCheckListener implements MessageListener {
@Autowired
private IWeSensitiveService weSensitiveService;
@Autowired
private WeSensitiveMapper weSensitiveMapper;
@Autowired
private IWeChatContactMsgService weChatContactMsgService;
@Autowired
private WeChatContactSensitiveMsgMapper weChatContactSensitiveMsgMapper;
@Autowired
private IWeCorpAccountService weCorpAccountService;
@Autowired
private WeMessagePushClient weMessagePushClient;
@Override @Override
public void onMessage(Message message, byte[] pattern) { public void onMessage(Message message, byte[] pattern) {
log.info(">> 订阅消息,会话审核订阅者:{}", message); log.info(">> 订阅消息,会话审核订阅者:{}, topic: {}", message, new String(pattern));
String body = new String(message.getBody()); JSONObject jsonObject = JSONObject.parseObject(new String(message.getBody()));
//渠道名称 log.info(">> 订阅消息,会话存档消息:{}", jsonObject.toJSONString());
String topic = new String(pattern);
System.out.println(body); Threads.SINGLE_THREAD_POOL.submit(() -> msgContextHandle(jsonObject));
System.out.println(topic); }
private void msgContextHandle(JSONObject jsonObject) {
String from = jsonObject.getString("from");
String msgId = jsonObject.getString("msgid");
String roomId = jsonObject.getString("roomid");
String msgType = jsonObject.getString("msgtype");
String content = null;
String objectString = jsonObject.getString(jsonObject.getString("msgtype"));
if (StringUtils.isNotEmpty(objectString)) {
content = objectString;
} else if ("external_redpacket".equals(msgType)) {
content = jsonObject.getString("redpacket");
} else if ("docmsg".equals(msgType)) {
content = jsonObject.getString("doc");
} else if ("markdown".equals(msgType)
|| "news".equals(msgType)) {
content = jsonObject.getString("info");
}
log.info("执行敏感词命中过滤,time=[{}]", System.currentTimeMillis());
//获取所有的敏感词规则
List<WeSensitive> allSensitiveRules = weSensitiveMapper.selectWeSensitiveList(new WeSensitive());
//根据规则过滤命中
if (CollectionUtils.isNotEmpty(allSensitiveRules) && StringUtils.isBlank(roomId)) {
String finalContent = content;
allSensitiveRules.parallelStream().forEach(weSensitive -> {
List<String> patternWords = Arrays.asList(weSensitive.getPatternWords().split(","));
List<String> users = weSensitiveService.getScopeUsers(weSensitive.getAuditUserScope());
if (StringUtils.isNotBlank(finalContent)
&& !CollectionUtils.isEmpty(users)
&& users.stream().anyMatch(from::equals)) {
WeChatContactSensitiveMsg wccsm = hitSensitive(patternWords, from, finalContent);
if (wccsm != null) {
LambdaQueryWrapper<WeChatContactMsg> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(WeChatContactMsg::getMsgId, msgId);
WeChatContactMsg ccm = weChatContactMsgService.getOne(wrapper);
wccsm.setWeChatContactId(ccm.getId());
int result = weChatContactSensitiveMsgMapper.insert(wccsm);
if (result > 0) {
sendMessage(wccsm, weSensitive);
}
}
}
});
}
}
private WeChatContactSensitiveMsg hitSensitive(List<String> patternWords, String user, String content) {
WeChatContactSensitiveMsg weChatContactSensitiveMsg = new WeChatContactSensitiveMsg();
patternWords = patternWords.stream().filter(content::contains).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(patternWords)) {
weChatContactSensitiveMsg.setContent(content);
weChatContactSensitiveMsg.setSendStatus(0);
weChatContactSensitiveMsg.setPatternWords(String.join(", ", patternWords));
return weChatContactSensitiveMsg;
}
return null;
}
private void sendMessage(WeChatContactSensitiveMsg wccsm, Object weSensitiveObj) {
WeSensitive weSensitive = (WeSensitive) weSensitiveObj;
if (weSensitive.getAlertFlag().equals(1)) {
//发送消息通知给相应的审计人
WeCorpAccount weCorpAccount = weCorpAccountService.findValidWeCorpAccount();
String auditUserId = weSensitive.getAuditUserId();
String content = "有消息触发敏感词,请登录系统及时处理!";
TextMessageDto textMessageDto = new TextMessageDto();
textMessageDto.setContent(content);
WeMessagePushDto pushDto = new WeMessagePushDto();
pushDto.setTouser(auditUserId);
pushDto.setMsgtype(MessageType.TEXT.getMessageType());
pushDto.setText(textMessageDto);
weMessagePushClient.sendMessageToUser(pushDto, weCorpAccount.getAgentId());
wccsm.setSendStatus(1);
weChatContactSensitiveMsgMapper.updateById(wccsm);
}
} }
} }
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.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;
/**
* @author leejoker <1056650571@qq.com>
* @version 1.0
* @date 2021/8/13 22:35
*/
@ApiModel
@Data
@NoArgsConstructor
@Accessors(chain = true)
@TableName("we_chat_contact_sensitive_msg")
public class WeChatContactSensitiveMsg extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1909244243128889376L;
/**
* 主键id
*/
@TableId(value = "id", type = IdType.AUTO)
@ApiModelProperty("主键id")
private Long id;
/**
* 主键id
*/
@Excel(name = "消息表关联id")
@ApiModelProperty("消息表关联id")
private Long weChatContactId;
@Excel(name = "通知发送状态")
@ApiModelProperty("通知发送状态, 0 未发送 1 已发送")
private Integer sendStatus;
@Excel(name = "匹配词")
@ApiModelProperty("匹配词")
private String patternWords;
@Excel(name = "匹配的内容")
@ApiModelProperty("匹配的内容")
private String content;
}
package com.linkwechat.wecom.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkwechat.wecom.domain.WeChatContactSensitiveMsg;
/**
* @author leejoker <1056650571@qq.com>
* @version 1.0
* @date 2021/8/13 23:14
*/
public interface WeChatContactSensitiveMsgMapper extends BaseMapper<WeChatContactSensitiveMsg> {
}
...@@ -2,7 +2,9 @@ package com.linkwechat.wecom.service; ...@@ -2,7 +2,9 @@ package com.linkwechat.wecom.service;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import com.linkwechat.wecom.domain.WeChatContactSensitiveMsg;
import com.linkwechat.wecom.domain.WeSensitive; import com.linkwechat.wecom.domain.WeSensitive;
import com.linkwechat.wecom.domain.WeSensitiveAuditScope;
import com.linkwechat.wecom.domain.query.WeSensitiveHitQuery; import com.linkwechat.wecom.domain.query.WeSensitiveHitQuery;
import java.util.List; import java.util.List;
...@@ -62,12 +64,7 @@ public interface IWeSensitiveService { ...@@ -62,12 +64,7 @@ public interface IWeSensitiveService {
*/ */
public int destroyWeSensitiveByIds(Long[] ids); public int destroyWeSensitiveByIds(Long[] ids);
/**
* 敏感词命中
*
* @param entityList
*/
public void hitSensitive(List<JSONObject> entityList);
public PageInfo<JSONObject> getHitSensitiveList(WeSensitiveHitQuery weSensitiveHitQuery); public PageInfo<JSONObject> getHitSensitiveList(WeSensitiveHitQuery weSensitiveHitQuery);
List<String> getScopeUsers(List<WeSensitiveAuditScope> auditUserScope);
} }
...@@ -4,21 +4,16 @@ import com.alibaba.fastjson.JSONObject; ...@@ -4,21 +4,16 @@ import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.linkwechat.common.constant.WeConstans; import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.domain.elastic.ElasticSearchEntity;
import com.linkwechat.common.core.elasticsearch.ElasticSearch; import com.linkwechat.common.core.elasticsearch.ElasticSearch;
import com.linkwechat.common.core.page.PageDomain; import com.linkwechat.common.core.page.PageDomain;
import com.linkwechat.common.core.page.TableSupport; import com.linkwechat.common.core.page.TableSupport;
import com.linkwechat.common.enums.MessageType;
import com.linkwechat.common.utils.DateUtils; import com.linkwechat.common.utils.DateUtils;
import com.linkwechat.common.utils.SecurityUtils; import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.StringUtils; import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.client.WeMessagePushClient; import com.linkwechat.wecom.client.WeMessagePushClient;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.wecom.domain.WeSensitive; import com.linkwechat.wecom.domain.WeSensitive;
import com.linkwechat.wecom.domain.WeSensitiveAuditScope; import com.linkwechat.wecom.domain.WeSensitiveAuditScope;
import com.linkwechat.wecom.domain.WeUser; import com.linkwechat.wecom.domain.WeUser;
import com.linkwechat.wecom.domain.dto.WeMessagePushDto;
import com.linkwechat.wecom.domain.dto.message.TextMessageDto;
import com.linkwechat.wecom.domain.query.WeSensitiveHitQuery; import com.linkwechat.wecom.domain.query.WeSensitiveHitQuery;
import com.linkwechat.wecom.mapper.WeSensitiveMapper; import com.linkwechat.wecom.mapper.WeSensitiveMapper;
import com.linkwechat.wecom.service.IWeCorpAccountService; import com.linkwechat.wecom.service.IWeCorpAccountService;
...@@ -39,9 +34,7 @@ import org.springframework.beans.factory.annotation.Value; ...@@ -39,9 +34,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -182,26 +175,6 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService { ...@@ -182,26 +175,6 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService {
} }
@Override @Override
public void hitSensitive(List<JSONObject> entityList) {
log.info("执行敏感词命中过滤,time=[{}]", System.currentTimeMillis());
//获取所有的敏感词规则
List<WeSensitive> allSensitiveRules = weSensitiveMapper.selectWeSensitiveList(new WeSensitive());
//根据规则过滤命中
if (CollectionUtils.isNotEmpty(allSensitiveRules)) {
allSensitiveRules.parallelStream().forEach(weSensitive -> {
List<JSONObject> jsonList = Lists.newArrayList();
List<String> patternWords = Arrays.asList(weSensitive.getPatternWords().split(","));
List<String> users = getScopeUsers(weSensitive.getAuditUserScope());
patternWords.forEach(patternWord -> {
jsonList.addAll(hitSensitiveInES(patternWord, users));
});
//将命中结果插入es
addHitSensitiveList(jsonList, weSensitive);
});
}
}
@Override
public PageInfo<JSONObject> getHitSensitiveList(WeSensitiveHitQuery weSensitiveHitQuery) { public PageInfo<JSONObject> getHitSensitiveList(WeSensitiveHitQuery weSensitiveHitQuery) {
elasticSearch.createIndex2(WeConstans.WECOM_SENSITIVE_HIT_INDEX, getSensitiveHitMapping()); elasticSearch.createIndex2(WeConstans.WECOM_SENSITIVE_HIT_INDEX, getSensitiveHitMapping());
List<String> userIds = Lists.newArrayList(); List<String> userIds = Lists.newArrayList();
...@@ -259,47 +232,7 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService { ...@@ -259,47 +232,7 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService {
return pageInfo; return pageInfo;
} }
private void addHitSensitiveList(List<JSONObject> json, WeSensitive weSensitive) { public List<String> getScopeUsers(List<WeSensitiveAuditScope> scopeList) {
elasticSearch.createIndex2(WeConstans.WECOM_SENSITIVE_HIT_INDEX, getSensitiveHitMapping());
//批量提交插入记录
if (CollectionUtils.isNotEmpty(json)) {
List<ElasticSearchEntity> list = json.stream().filter(Objects::nonNull).map(j -> {
ElasticSearchEntity ese = new ElasticSearchEntity();
j.put("status", "0");
ese.setData(j);
ese.setId(j.getString("msgid"));
return ese;
}).collect(Collectors.toList());
elasticSearch.insertBatchAsync(WeConstans.WECOM_SENSITIVE_HIT_INDEX, list, this::sendMessage, weSensitive);
}
}
private void sendMessage(Object listObj, Object weSensitiveObj) {
WeSensitive weSensitive = (WeSensitive) weSensitiveObj;
List<ElasticSearchEntity> list = (List<ElasticSearchEntity>) listObj;
if (weSensitive.getAlertFlag().equals(1) && CollectionUtils.isNotEmpty(list)) {
//发送消息通知给相应的审计人
WeCorpAccount weCorpAccount = weCorpAccountService.findValidWeCorpAccount();
String auditUserId = weSensitive.getAuditUserId();
String content = "有消息触发敏感词,请登录系统及时处理!";
TextMessageDto textMessageDto = new TextMessageDto();
textMessageDto.setContent(content);
WeMessagePushDto pushDto = new WeMessagePushDto();
pushDto.setTouser(auditUserId);
pushDto.setMsgtype(MessageType.TEXT.getMessageType());
pushDto.setText(textMessageDto);
weMessagePushClient.sendMessageToUser(pushDto, weCorpAccount.getAgentId());
//批量更新
list = list.stream().peek(entity -> {
Map map = entity.getData();
map.put("status", "1");
entity.setData(map);
}).collect(Collectors.toList());
elasticSearch.updateBatch(WeConstans.WECOM_SENSITIVE_HIT_INDEX, list);
}
}
private List<String> getScopeUsers(List<WeSensitiveAuditScope> scopeList) {
List<String> users = Lists.newArrayList(); List<String> users = Lists.newArrayList();
scopeList.forEach(scope -> { scopeList.forEach(scope -> {
if (scope.getScopeType().equals(WeConstans.USE_SCOP_BUSINESSID_TYPE_USER)) { if (scope.getScopeType().equals(WeConstans.USE_SCOP_BUSINESSID_TYPE_USER)) {
...@@ -313,39 +246,6 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService { ...@@ -313,39 +246,6 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService {
return users; return users;
} }
private List<JSONObject> hitSensitiveInES(String patternWord, List<String> users) {
int pieceSize = userPiecesCount(users);
if (pieceSize != -1) {
List<JSONObject> resultList = Lists.newArrayList();
for (int i = 0; i < pieceSize; i++) {
List<String> subUsers = users.subList(i + i * pieceSize, i + pieceSize - 1);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.sort("msgtime", SortOrder.DESC);
BoolQueryBuilder userBuilder = QueryBuilders.boolQuery();
subUsers.parallelStream().forEach(user -> userBuilder.should(QueryBuilders.termQuery("from", user)));
userBuilder.minimumShouldMatch(1);
BoolQueryBuilder searchBuilder = QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery("content", patternWord)).must(userBuilder);
builder.query(searchBuilder);
List<JSONObject> list = elasticSearch.search(chartKey, builder, JSONObject.class);
list.parallelStream().forEach(j -> j.put("pattern_words", patternWord));
resultList.addAll(list);
}
return resultList;
}
return Lists.newArrayList();
}
private int userPiecesCount(List<String> users) {
if (CollectionUtils.isNotEmpty(users)) {
if (users.size() % WeConstans.SENSITIVE_USER_PIECE != 0) {
return users.size() / WeConstans.SENSITIVE_USER_PIECE + 1;
} else {
return users.size() / WeConstans.SENSITIVE_USER_PIECE;
}
}
return -1;
}
private XContentBuilder getSensitiveHitMapping() { private XContentBuilder getSensitiveHitMapping() {
try { try {
//创建索引 //创建索引
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.linkwechat.wecom.mapper.WeSensitiveMapper"> <mapper namespace="com.linkwechat.wecom.mapper.WeSensitiveMapper">
<resultMap type="WeSensitive" id="WeSensitiveResult"> <resultMap type="com.linkwechat.wecom.domain.WeSensitive" id="WeSensitiveResult">
<result property="id" column="id"/> <result property="id" column="id"/>
<result property="strategyName" column="strategy_name"/> <result property="strategyName" column="strategy_name"/>
<result property="patternWords" column="pattern_words"/> <result property="patternWords" column="pattern_words"/>
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
= b.sensitive_id = b.sensitive_id
</sql> </sql>
<select id="selectWeSensitiveList" parameterType="WeSensitive" resultMap="WeSensitiveResult"> <select id="selectWeSensitiveList" parameterType="com.linkwechat.wecom.domain.WeSensitive" resultMap="WeSensitiveResult">
<include refid="selectWeSensitiveList"/> <include refid="selectWeSensitiveList"/>
<where> <where>
<if test="strategyName != null and strategyName != ''">and a.strategy_name like concat('%', <if test="strategyName != null and strategyName != ''">and a.strategy_name like concat('%',
...@@ -64,7 +64,7 @@ ...@@ -64,7 +64,7 @@
order by a.update_time desc, a.create_time desc order by a.update_time desc, a.create_time desc
</select> </select>
<insert id="insertWeSensitive" parameterType="WeSensitive" useGeneratedKeys="true" keyProperty="id"> <insert id="insertWeSensitive" parameterType="com.linkwechat.wecom.domain.WeSensitive" useGeneratedKeys="true" keyProperty="id">
insert into we_sensitive insert into we_sensitive
<trim prefix="(" suffix=")" suffixOverrides=","> <trim prefix="(" suffix=")" suffixOverrides=",">
<if test="strategyName != null and strategyName != ''">strategy_name,</if> <if test="strategyName != null and strategyName != ''">strategy_name,</if>
...@@ -92,7 +92,7 @@ ...@@ -92,7 +92,7 @@
</trim> </trim>
</insert> </insert>
<update id="updateWeSensitive" parameterType="WeSensitive"> <update id="updateWeSensitive" parameterType="com.linkwechat.wecom.domain.WeSensitive">
update we_sensitive update we_sensitive
<trim prefix="SET" suffixOverrides=","> <trim prefix="SET" suffixOverrides=",">
<if test="strategyName != null and strategyName != ''">strategy_name = #{strategyName},</if> <if test="strategyName != null and strategyName != ''">strategy_name = #{strategyName},</if>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!