Commit 883311e7 by xinlaa

Merge branch 'master' of https://gitee.com/LinkWeChat/link-wechat into master

2 parents 0b550c74 ac1e1caf
Showing 20 changed files with 419 additions and 180 deletions
...@@ -53,4 +53,16 @@ public class WeConversationArchiveController extends BaseController { ...@@ -53,4 +53,16 @@ public class WeConversationArchiveController extends BaseController {
} }
/**
* 获取全局会话数据接口
*
* @param query 入参
* @return
*/
@PreAuthorize("@ss.hasPermi('conversationArchive:chatAllContact:list')")
@GetMapping("/getChatAllList")
public TableDataInfo getChatAllList(ConversationArchiveQuery query) {
return getDataTable(weConversationArchiveService.getChatAllList(query));
}
} }
...@@ -7,10 +7,10 @@ import com.linkwechat.common.core.domain.AjaxResult; ...@@ -7,10 +7,10 @@ import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.common.core.page.TableDataInfo; import com.linkwechat.common.core.page.TableDataInfo;
import com.linkwechat.common.enums.BusinessType; import com.linkwechat.common.enums.BusinessType;
import com.linkwechat.wecom.domain.WeSensitive; import com.linkwechat.wecom.domain.WeSensitive;
import com.linkwechat.wecom.domain.query.WeSensitiveHitQuery;
import com.linkwechat.wecom.service.IWeSensitiveService; import com.linkwechat.wecom.service.IWeSensitiveService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.validation.Valid; import javax.validation.Valid;
...@@ -19,7 +19,7 @@ import java.util.List; ...@@ -19,7 +19,7 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* 敏感词设置Controller * 敏感词Controller
* *
* @author ruoyi * @author ruoyi
* @date 2020-12-29 * @date 2020-12-29
...@@ -87,4 +87,13 @@ public class WeSensitiveController extends BaseController { ...@@ -87,4 +87,13 @@ public class WeSensitiveController extends BaseController {
Arrays.stream(id).map(Long::parseLong).collect(Collectors.toList()).toArray(idArray); Arrays.stream(id).map(Long::parseLong).collect(Collectors.toList()).toArray(idArray);
return toAjax(weSensitiveService.destroyWeSensitiveByIds(idArray)); return toAjax(weSensitiveService.destroyWeSensitiveByIds(idArray));
} }
/**
* 敏感词命中查询
*/
@PreAuthorize("@ss.hasPermi('wecom:sensitivehit:list')")
@GetMapping("/hit/list")
public TableDataInfo hitList(WeSensitiveHitQuery query) {
return getDataTable(weSensitiveService.getHitSensitiveList(query));
}
} }
package com.linkwechat.common.constant; package com.linkwechat.common.constant;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -149,7 +148,7 @@ public class WeConstans { ...@@ -149,7 +148,7 @@ public class WeConstans {
/** /**
* 批量生成的单人码 活动场景 * 批量生成的单人码 活动场景
*/ */
public static final String ONE_PERSON_CODE_GENERATED_BATCH="批量生成的单人码"; public static final String ONE_PERSON_CODE_GENERATED_BATCH = "批量生成的单人码";
/** /**
* 微信接口相应端错误字段 * 微信接口相应端错误字段
...@@ -222,6 +221,11 @@ public class WeConstans { ...@@ -222,6 +221,11 @@ public class WeConstans {
public static final Integer ID_TYPE_MACHINE = 2; public static final Integer ID_TYPE_MACHINE = 2;
/** /**
* 一次拉取的消息条数,最大值1000条,超过1000条会返回错误
*/
public static final long LIMIT = 1_000L;
/**
* 企微回调事件类型路由 * 企微回调事件类型路由
*/ */
public final static Map<String, String> eventRoute = new HashMap<String, String>() { public final static Map<String, String> eventRoute = new HashMap<String, String>() {
...@@ -285,6 +289,10 @@ public class WeConstans { ...@@ -285,6 +289,10 @@ public class WeConstans {
public static final String WECOM_FINANCE_INDEX = "finance"; public static final String WECOM_FINANCE_INDEX = "finance";
/** 开启会话存档成员列表 **/ public static final String WECOM_SENSITIVE_HIT_INDEX = "sensitive";
/**
* 开启会话存档成员列表
**/
public static final String weMsgAuditKey = "wecom_msg_audit:user:ids"; public static final String weMsgAuditKey = "wecom_msg_audit:user:ids";
} }
package com.linkwechat.common.core.domain; package com.linkwechat.common.core.domain;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data; import lombok.Data;
/** /**
...@@ -13,12 +12,21 @@ public class ConversationArchiveQuery extends BaseEntity { ...@@ -13,12 +12,21 @@ public class ConversationArchiveQuery extends BaseEntity {
/** 发送人Id */ /** 发送人Id */
private String fromId; private String fromId;
/** 成员名称 */
private String userName;
/** 接收人Id */ /** 接收人Id */
private String receiveId; private String receiveId;
/** 客户姓名 */
private String customerName;
/** 群聊Id */ /** 群聊Id */
private String roomId; private String roomId;
/** 类型 */ /** 类型 */
private String msgType; private String msgType;
/** 关键词 **/
private String keyWord;
} }
package com.linkwechat.common.core.elasticsearch; package com.linkwechat.common.core.elasticsearch;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper; import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import com.linkwechat.common.core.domain.elastic.ElasticSearchEntity; import com.linkwechat.common.core.domain.elastic.ElasticSearchEntity;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteRequest;
...@@ -18,6 +20,7 @@ import org.elasticsearch.client.indices.CreateIndexRequest; ...@@ -18,6 +20,7 @@ import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
...@@ -25,16 +28,16 @@ import org.elasticsearch.index.query.QueryBuilder; ...@@ -25,16 +28,16 @@ import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest; import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/** /**
* @author sxw * @author sxw
...@@ -99,7 +102,7 @@ public class ElasticSearch { ...@@ -99,7 +102,7 @@ public class ElasticSearch {
// request.settings() 手工指定Setting // request.settings() 手工指定Setting
CreateIndexResponse res = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT); CreateIndexResponse res = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
if (!res.isAcknowledged()) { if (!res.isAcknowledged()) {
throw new RuntimeException("初始化失败"); log.info("初始化失败");
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -169,7 +172,7 @@ public class ElasticSearch { ...@@ -169,7 +172,7 @@ public class ElasticSearch {
*/ */
public void insertOrUpdateOne(String idxName, ElasticSearchEntity entity) { public void insertOrUpdateOne(String idxName, ElasticSearchEntity entity) {
IndexRequest request = new IndexRequest(idxName, "_doc"); IndexRequest request = new IndexRequest(idxName, "_doc");
log.error("Data : id={},entity={}", entity.getId(), JSON.toJSONString(entity.getData())); log.info("Data : id={},entity={}", entity.getId(), JSON.toJSONString(entity.getData()));
request.id(entity.getId()); request.id(entity.getId());
request.source(entity.getData(), XContentType.JSON); request.source(entity.getData(), XContentType.JSON);
// request.source(JSON.toJSONString(entity.getData()), XContentType.JSON); // request.source(JSON.toJSONString(entity.getData()), XContentType.JSON);
...@@ -205,6 +208,24 @@ public class ElasticSearch { ...@@ -205,6 +208,24 @@ public class ElasticSearch {
} }
/** /**
* 异步批量插入,并执行回调方法
*
* @param idxName
* @param list
* @param consumers
*/
public void insertBatchAsync(String idxName, List<JSONObject> list, List<Consumer<List<JSONObject>>> consumers) {
BulkRequest request = new BulkRequest();
list.forEach(item -> request.add(new IndexRequest(idxName, "_doc").id(item.getString("msgid"))
.source(item, XContentType.JSON)));
try {
restHighLevelClient.bulkAsync(request, RequestOptions.DEFAULT, getActionListener(list, consumers));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 批量删除 * 批量删除
* *
* @param idxName index * @param idxName index
...@@ -259,15 +280,28 @@ public class ElasticSearch { ...@@ -259,15 +280,28 @@ public class ElasticSearch {
request.source(builder); request.source(builder);
try { try {
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT); SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
int totalHits =(int) response.getHits().getTotalHits().value; int totalHits = (int) response.getHits().getTotalHits().value;
SearchHit[] hits = response.getHits().getHits(); SearchHit[] hits = response.getHits().getHits();
List<T> res = new ArrayList<>(hits.length); List<T> res = new ArrayList<>(hits.length);
for (SearchHit hit : hits) { for (SearchHit hit : hits) {
res.add(JSON.parseObject(hit.getSourceAsString(), c)); //解析高亮字段
//获取当前命中的对象的高亮的字段
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField hghlightContent = highlightFields.get("text.content");
String newName = "";
if (hghlightContent != null) {
//获取该高亮字段的高亮信息
Text[] fragments = hghlightContent.getFragments();
//将前缀、关键词、后缀进行拼接
for (Text fragment : fragments) {
newName += fragment;
}
}
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
sourceAsMap.put("content", newName);
res.add(JSON.parseObject(JSONObject.toJSONString(sourceAsMap), c));
} }
// 封装分页 // 封装分页
PageHelper.startPage(1,2);
PageInfo<T> page = new PageInfo<>(); PageInfo<T> page = new PageInfo<>();
page.setList(res); page.setList(res);
page.setPageNum(pageNum); page.setPageNum(pageNum);
...@@ -328,6 +362,20 @@ public class ElasticSearch { ...@@ -328,6 +362,20 @@ public class ElasticSearch {
} }
} }
public ActionListener getActionListener(List<JSONObject> list, List<Consumer<List<JSONObject>>> consumers) {
return new ActionListener() {
@Override
public void onResponse(Object o) {
consumers.forEach(consumer -> consumer.accept(list));
}
@Override
public void onFailure(Exception e) {
log.warn("work with es failed, exception={}", ExceptionUtils.getStackTrace(e));
}
};
}
public XContentBuilder getFinanceMapping() throws IOException { public XContentBuilder getFinanceMapping() throws IOException {
// 创建 会话文本Mapping // 创建 会话文本Mapping
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder() XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
...@@ -358,4 +406,4 @@ public class ElasticSearch { ...@@ -358,4 +406,4 @@ public class ElasticSearch {
.endObject(); .endObject();
return xContentBuilder; return xContentBuilder;
} }
} }
\ No newline at end of file \ No newline at end of file
...@@ -4,7 +4,8 @@ import cn.hutool.core.collection.CollectionUtil; ...@@ -4,7 +4,8 @@ import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.linkwechat.common.config.RuoYiConfig; import com.linkwechat.common.config.RuoYiConfig;
import com.linkwechat.common.core.domain.elastic.ElasticSearchEntity; import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.utils.DateUtils; import com.linkwechat.common.utils.DateUtils;
import com.linkwechat.common.utils.StringUtils; import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.common.utils.uuid.IdUtils; import com.linkwechat.common.utils.uuid.IdUtils;
...@@ -17,6 +18,7 @@ import java.security.PrivateKey; ...@@ -17,6 +18,7 @@ import java.security.PrivateKey;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
/** /**
* @author sxw * @author sxw
...@@ -33,10 +35,6 @@ public class FinanceUtils { ...@@ -33,10 +35,6 @@ public class FinanceUtils {
* 超时时间,单位秒 * 超时时间,单位秒
*/ */
private final static long timeout = 5 * 60; private final static long timeout = 5 * 60;
/**
* 一次拉取的消息条数,最大值1000条,超过1000条会返回错误
*/
private final static long LIMIT = 1000;
private static String downloadWeWorkPath = RuoYiConfig.getDownloadWeWorkPath(); private static String downloadWeWorkPath = RuoYiConfig.getDownloadWeWorkPath();
...@@ -62,10 +60,10 @@ public class FinanceUtils { ...@@ -62,10 +60,10 @@ public class FinanceUtils {
* @param proxy 代理 * @param proxy 代理
* @param passwd 密码 * @param passwd 密码
*/ */
public static List<ElasticSearchEntity> getChatData(long seq, String proxy, String passwd) { public static List<JSONObject> getChatData(long seq, String proxy, String passwd, RedisCache redisCache) {
List<ElasticSearchEntity> resList = new ArrayList<>(); List<JSONObject> resList = new ArrayList<>();
long slice = Finance.NewSlice(); long slice = Finance.NewSlice();
int ret = Finance.GetChatData(sdk, seq, LIMIT, proxy, passwd, timeout, slice); int ret = Finance.GetChatData(sdk, seq, WeConstans.LIMIT, proxy, passwd, timeout, slice);
if (ret != 0) { if (ret != 0) {
log.info("getChatData ret " + ret); log.info("getChatData ret " + ret);
return null; return null;
...@@ -73,20 +71,18 @@ public class FinanceUtils { ...@@ -73,20 +71,18 @@ public class FinanceUtils {
String content = Finance.GetContentFromSlice(slice); String content = Finance.GetContentFromSlice(slice);
JSONArray chatdataArr = JSONObject.parseObject(content).getJSONArray("chatdata"); JSONArray chatdataArr = JSONObject.parseObject(content).getJSONArray("chatdata");
log.info("开始执行数据解析:------------"); log.info("开始执行数据解析:------------");
AtomicLong LocalSEQ = new AtomicLong();
if (CollectionUtil.isNotEmpty(chatdataArr)) { if (CollectionUtil.isNotEmpty(chatdataArr)) {
chatdataArr.stream().map(data -> (JSONObject) data).forEach(data -> { chatdataArr.stream().map(data -> (JSONObject) data).forEach(data -> {
try { try {
ElasticSearchEntity elasticSearchEntity = new ElasticSearchEntity(); LocalSEQ.set(data.getLong("seq"));
long LocalSEQ = data.getLong("seq");
JSONObject jsonObject = decryptChatRecord(sdk, data.getString("encrypt_random_key"), JSONObject jsonObject = decryptChatRecord(sdk, data.getString("encrypt_random_key"),
data.getString("encrypt_chat_msg"), privateKey); data.getString("encrypt_chat_msg"), privateKey);
if (jsonObject ==null){ if (jsonObject == null) {
return; return;
} }
jsonObject.put("seq", LocalSEQ); jsonObject.put("seq", LocalSEQ.get());
elasticSearchEntity.setData(jsonObject); resList.add(jsonObject);
elasticSearchEntity.setId(jsonObject.getString("msgid"));
resList.add(elasticSearchEntity);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -94,6 +90,7 @@ public class FinanceUtils { ...@@ -94,6 +90,7 @@ public class FinanceUtils {
log.info("数据解析完成:------------"); log.info("数据解析完成:------------");
} }
Finance.FreeSlice(slice); Finance.FreeSlice(slice);
redisCache.setCacheObject(WeConstans.CONTACT_SEQ_KEY, LocalSEQ.get());
return resList; return resList;
} }
...@@ -122,7 +119,7 @@ public class FinanceUtils { ...@@ -122,7 +119,7 @@ public class FinanceUtils {
if (StringUtils.isNotEmpty(msgType)) { if (StringUtils.isNotEmpty(msgType)) {
getSwitchType(realJsonData, msgType); getSwitchType(realJsonData, msgType);
} }
log.info("数据解析:------------"+ realJsonData.toJSONString()); log.info("数据解析:------------" + realJsonData.toJSONString());
return realJsonData; return realJsonData;
} catch (Exception e) { } catch (Exception e) {
log.error("解析密文失败"); log.error("解析密文失败");
...@@ -277,5 +274,4 @@ public class FinanceUtils { ...@@ -277,5 +274,4 @@ public class FinanceUtils {
} }
} }
} }
} }
...@@ -2,12 +2,14 @@ package com.linkwechat.quartz.task; ...@@ -2,12 +2,14 @@ package com.linkwechat.quartz.task;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
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.domain.elastic.ElasticSearchEntity;
import com.linkwechat.common.core.elasticsearch.ElasticSearch; import com.linkwechat.common.core.elasticsearch.ElasticSearch;
import com.linkwechat.common.core.redis.RedisCache; import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.utils.StringUtils; import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.service.IWeChatContactMappingService; import com.linkwechat.wecom.service.IWeChatContactMappingService;
import com.linkwechat.wecom.service.IWeSensitiveService;
import com.tencent.wework.FinanceUtils; import com.tencent.wework.FinanceUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T; import org.apache.poi.ss.formula.functions.T;
...@@ -38,6 +40,8 @@ public class RyTask { ...@@ -38,6 +40,8 @@ public class RyTask {
private RedisCache redisCache; private RedisCache redisCache;
@Autowired @Autowired
private IWeChatContactMappingService weChatContactMappingService; private IWeChatContactMappingService weChatContactMappingService;
@Autowired
private IWeSensitiveService weSensitiveService;
public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) { public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i)); System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i));
...@@ -67,18 +71,18 @@ public class RyTask { ...@@ -67,18 +71,18 @@ public class RyTask {
log.info(">>>>>>>seq:{}",index.get()); log.info(">>>>>>>seq:{}",index.get());
FinanceUtils.initSDK(corpId, secret); FinanceUtils.initSDK(corpId, secret);
List<ElasticSearchEntity> chatDataList = FinanceUtils.getChatData(index.get(), List<JSONObject> chatDataList = FinanceUtils.getChatData(index.get(),
"", "",
""); "", redisCache);
if (CollectionUtil.isNotEmpty(chatDataList)){ if (CollectionUtil.isNotEmpty(chatDataList)){
try { try {
elasticSearch.insertBatch(WeConstans.WECOM_FINANCE_INDEX, chatDataList); List<Consumer<List<JSONObject>>> consumerList = Lists.newArrayList();
weChatContactMappingService.saveWeChatContactMapping(chatDataList); consumerList.add(weChatContactMappingService::saveWeChatContactMapping);
consumerList.add(weSensitiveService::hitSensitive);
elasticSearch.insertBatchAsync(WeConstans.WECOM_FINANCE_INDEX, chatDataList, consumerList);
} catch (Exception e) { } catch (Exception e) {
log.error("消息处理异常:ex:{}", e); log.error("消息处理异常:ex:{}", e);
e.printStackTrace(); e.printStackTrace();
}finally {
setRedisCacheSeqValue(index);
} }
} }
} }
......
...@@ -3,7 +3,6 @@ package com.linkwechat.wecom.domain; ...@@ -3,7 +3,6 @@ package com.linkwechat.wecom.domain;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.linkwechat.common.annotation.Excel; import com.linkwechat.common.annotation.Excel;
import com.linkwechat.wecom.domain.dto.msgaudit.GroupChatVo;
import lombok.Data; import lombok.Data;
...@@ -80,7 +79,7 @@ public class WeChatContactMapping { ...@@ -80,7 +79,7 @@ public class WeChatContactMapping {
* 群信息 * 群信息
*/ */
@TableField(exist = false) @TableField(exist = false)
private GroupChatVo roomInfo; private WeGroup roomInfo;
/** /**
* 最后一条聊天数据 * 最后一条聊天数据
......
...@@ -14,7 +14,6 @@ import org.apache.commons.lang3.builder.ToStringStyle; ...@@ -14,7 +14,6 @@ import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List; import java.util.List;
/** /**
...@@ -66,8 +65,8 @@ public class WeSensitive extends BaseEntity { ...@@ -66,8 +65,8 @@ public class WeSensitive extends BaseEntity {
*/ */
@TableField(value = "audit_user_id") @TableField(value = "audit_user_id")
@ApiModelProperty(value = "审计人id") @ApiModelProperty(value = "审计人id")
@NotNull(message = "审计人id不能为空") @NotBlank(message = "审计人id不能为空")
private Long auditUserId; private String auditUserId;
/** /**
* 审计人姓名 * 审计人姓名
......
...@@ -42,7 +42,7 @@ public class WeSensitiveAuditScope implements Serializable { ...@@ -42,7 +42,7 @@ public class WeSensitiveAuditScope implements Serializable {
*/ */
@TableField(value = "audit_scope_id") @TableField(value = "audit_scope_id")
@ApiModelProperty(value = "审计对象id") @ApiModelProperty(value = "审计对象id")
private Long auditScopeId; private String auditScopeId;
/** /**
* 审计对象名称 * 审计对象名称
......
package com.linkwechat.wecom.domain.dto.msgaudit;
import lombok.Data;
/**
* @author sxw
* @description
* @date 2020/12/30 23:41
**/
@Data
public class GroupChatVo {
/**客户群ID*/
private String chat_id;
/**群名*/
private String name;
/**群主ID*/
private String owner;
/**群的创建时间*/
private long create_time;
/**群公告*/
private String notice;
}
package com.linkwechat.wecom.domain.query;
import com.linkwechat.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author leejoker <1056650571@qq.com>
* @version 1.0
* @date 2021/1/4 21:56
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class WeSensitiveHitQuery extends BaseEntity {
/**
* 1:组织机构id,2:成员id
*/
@ApiModelProperty(value = "审计范围类型, 1 组织机构 2 成员")
private Integer scopeType;
/**
* 审计对象id
*/
@ApiModelProperty(value = "审计范围id")
private String auditScopeId;
/**
* 关键词
*/
@ApiModelProperty(value = "关键词")
private String keyword;
}
package com.linkwechat.wecom.service; package com.linkwechat.wecom.service;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import com.linkwechat.common.core.domain.elastic.ElasticSearchEntity; import com.linkwechat.common.core.domain.elastic.ElasticSearchEntity;
...@@ -69,7 +70,7 @@ public interface IWeChatContactMappingService extends IService<WeChatContactMapp ...@@ -69,7 +70,7 @@ public interface IWeChatContactMappingService extends IService<WeChatContactMapp
* *
* @param query * @param query
*/ */
public void saveWeChatContactMapping(List<ElasticSearchEntity> query); public List<ElasticSearchEntity> saveWeChatContactMapping(List<JSONObject> query);
/** /**
* 按客户查询关系映射列表 * 按客户查询关系映射列表
......
...@@ -38,5 +38,13 @@ public interface IWeConversationArchiveService { ...@@ -38,5 +38,13 @@ public interface IWeConversationArchiveService {
* @return * @return
*/ */
JSONObject getFinalChatRoomContactInfo(String fromId, String roomId); JSONObject getFinalChatRoomContactInfo(String fromId, String roomId);
/**
* 获取全局会话数据接口
*
* @param query 参
* @return
*/
PageInfo<JSONObject> getChatAllList(ConversationArchiveQuery query);
} }
package com.linkwechat.wecom.service; package com.linkwechat.wecom.service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.linkwechat.wecom.domain.WeSensitive; import com.linkwechat.wecom.domain.WeSensitive;
import com.linkwechat.wecom.domain.query.WeSensitiveHitQuery;
import java.util.List; import java.util.List;
...@@ -58,4 +61,13 @@ public interface IWeSensitiveService { ...@@ -58,4 +61,13 @@ public interface IWeSensitiveService {
* @return 结果 * @return 结果
*/ */
public int destroyWeSensitiveByIds(Long[] ids); public int destroyWeSensitiveByIds(Long[] ids);
/**
* 敏感词命中
*
* @param entityList
*/
public void hitSensitive(List<JSONObject> entityList);
public PageInfo<JSONObject> getHitSensitiveList(WeSensitiveHitQuery weSensitiveHitQuery);
} }
...@@ -9,7 +9,6 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; ...@@ -9,7 +9,6 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
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.domain.elastic.ElasticSearchEntity;
import com.linkwechat.common.core.page.TableDataInfo;
import com.linkwechat.common.utils.StringUtils; import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.client.WeCustomerClient; import com.linkwechat.wecom.client.WeCustomerClient;
import com.linkwechat.wecom.client.WeCustomerGroupClient; import com.linkwechat.wecom.client.WeCustomerGroupClient;
...@@ -17,14 +16,15 @@ import com.linkwechat.wecom.client.WeMsgAuditClient; ...@@ -17,14 +16,15 @@ import com.linkwechat.wecom.client.WeMsgAuditClient;
import com.linkwechat.wecom.client.WeUserClient; import com.linkwechat.wecom.client.WeUserClient;
import com.linkwechat.wecom.domain.WeChatContactMapping; import com.linkwechat.wecom.domain.WeChatContactMapping;
import com.linkwechat.wecom.domain.WeCustomer; import com.linkwechat.wecom.domain.WeCustomer;
import com.linkwechat.wecom.domain.WeGroup;
import com.linkwechat.wecom.domain.WeUser; import com.linkwechat.wecom.domain.WeUser;
import com.linkwechat.wecom.domain.dto.customer.CustomerGroupDetail; import com.linkwechat.wecom.domain.dto.customer.CustomerGroupDetail;
import com.linkwechat.wecom.domain.dto.msgaudit.GroupChatVo;
import com.linkwechat.wecom.mapper.WeChatContactMappingMapper; import com.linkwechat.wecom.mapper.WeChatContactMappingMapper;
import com.linkwechat.wecom.mapper.WeCustomerMapper; import com.linkwechat.wecom.mapper.WeCustomerMapper;
import com.linkwechat.wecom.mapper.WeUserMapper; import com.linkwechat.wecom.mapper.WeUserMapper;
import com.linkwechat.wecom.service.IWeChatContactMappingService; import com.linkwechat.wecom.service.IWeChatContactMappingService;
import com.linkwechat.wecom.service.IWeConversationArchiveService; import com.linkwechat.wecom.service.IWeConversationArchiveService;
import com.linkwechat.wecom.service.IWeGroupService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -59,6 +59,8 @@ public class WeChatContactMappingServiceImpl extends ServiceImpl<WeChatContactMa ...@@ -59,6 +59,8 @@ public class WeChatContactMappingServiceImpl extends ServiceImpl<WeChatContactMa
private WeMsgAuditClient weMsgAuditClient; private WeMsgAuditClient weMsgAuditClient;
@Autowired @Autowired
private IWeConversationArchiveService weConversationArchiveService; private IWeConversationArchiveService weConversationArchiveService;
@Autowired
private IWeGroupService weGroupService;
/** /**
* 查询聊天关系映射 * 查询聊天关系映射
...@@ -95,10 +97,8 @@ public class WeChatContactMappingServiceImpl extends ServiceImpl<WeChatContactMa ...@@ -95,10 +97,8 @@ public class WeChatContactMappingServiceImpl extends ServiceImpl<WeChatContactMa
item.setFinalChatContext(weConversationArchiveService.getFinalChatContactInfo(item.getFromId(), item.getReceiveId())); item.setFinalChatContext(weConversationArchiveService.getFinalChatContactInfo(item.getFromId(), item.getReceiveId()));
} else if (StringUtils.isNotEmpty(item.getRoomId())) { } else if (StringUtils.isNotEmpty(item.getRoomId())) {
//获取群信息 //获取群信息
CustomerGroupDetail customerGroupDetail = weCustomerGroupClient.groupChatDetail(new CustomerGroupDetail().new Params(item.getRoomId())); WeGroup weGroup = weGroupService.getOne(new LambdaQueryWrapper<WeGroup>().eq(WeGroup::getChatId, item.getRoomId()));
GroupChatVo groupChatVo = new GroupChatVo(); item.setRoomInfo(weGroup);
BeanUtil.copyProperties(customerGroupDetail.getGroup_chat().get(0), groupChatVo);
item.setRoomInfo(groupChatVo);
item.setFinalChatContext(weConversationArchiveService.getFinalChatRoomContactInfo(item.getFromId(), item.getRoomId())); item.setFinalChatContext(weConversationArchiveService.getFinalChatRoomContactInfo(item.getFromId(), item.getRoomId()));
} }
}); });
...@@ -160,33 +160,59 @@ public class WeChatContactMappingServiceImpl extends ServiceImpl<WeChatContactMa ...@@ -160,33 +160,59 @@ public class WeChatContactMappingServiceImpl extends ServiceImpl<WeChatContactMa
* @param query * @param query
*/ */
@Override @Override
public void saveWeChatContactMapping(List<ElasticSearchEntity> query) { public List<ElasticSearchEntity> saveWeChatContactMapping(List<JSONObject> query) {
query.stream().forEach(elasticSearchEntity -> { List<ElasticSearchEntity> resultList = new ArrayList<>();
query.stream().filter(chatData -> StringUtils.isNotEmpty(chatData.getString("from"))).forEach(chatData -> {
ElasticSearchEntity elasticSearchEntity = new ElasticSearchEntity();
elasticSearchEntity.setId(chatData.getString("msgid"));
//发送人映射数据 //发送人映射数据
WeChatContactMapping fromWeChatContactMapping = new WeChatContactMapping(); WeChatContactMapping fromWeChatContactMapping = new WeChatContactMapping();
JSONObject chatData = JSONObject.parseObject(JSONObject.toJSONString(elasticSearchEntity.getData()));
String fromId = chatData.getString("from"); String fromId = chatData.getString("from");
//发送人类型
int fromType = StringUtils.weCustomTypeJudgment(fromId); int fromType = StringUtils.weCustomTypeJudgment(fromId);
fromWeChatContactMapping.setFromId(fromId); fromWeChatContactMapping.setFromId(fromId);
getUserOrCustomerInfo(chatData, fromId, fromType, "fromInfo");
JSONArray tolist = chatData.getJSONArray("tolist"); JSONArray tolist = chatData.getJSONArray("tolist");
if (CollectionUtil.isNotEmpty(tolist)) { if (CollectionUtil.isNotEmpty(tolist)) {
//如果是单聊,tolist唯一,只有一个接收人,并判断接收人的类型 //如果是单聊,tolist唯一,只有一个接收人,并判断接收人的类型
if (StringUtils.isEmpty(chatData.getString("roomid"))) { if (StringUtils.isEmpty(chatData.getString("roomid"))) {
String idStr = String.valueOf(tolist.get(0)); String idStr = String.valueOf(tolist.get(0));
//接收人类型
int reveiceType = StringUtils.weCustomTypeJudgment(idStr); int reveiceType = StringUtils.weCustomTypeJudgment(idStr);
fromWeChatContactMapping.setReceiveId(idStr); fromWeChatContactMapping.setReceiveId(idStr);
//获取接收人信息
getUserOrCustomerInfo(chatData, idStr, reveiceType, "toListInfo");
fromWeChatContactMapping.setIsCustom(reveiceType); fromWeChatContactMapping.setIsCustom(reveiceType);
} else { } else {
fromWeChatContactMapping.setRoomId(chatData.getString("roomid")); fromWeChatContactMapping.setRoomId(chatData.getString("roomid"));
WeGroup weGroup = weGroupService.getOne(new LambdaQueryWrapper<WeGroup>().eq(WeGroup::getChatId, chatData.getString("roomid")));
chatData.put("roomInfo",JSONObject.parse(JSONObject.toJSONString(weGroup)));
} }
} }
//接收人映射数据 //接收人映射数据
WeChatContactMapping reveiceWeChatContactMapping = from2ReveiceData(fromType, fromWeChatContactMapping); WeChatContactMapping reveiceWeChatContactMapping = from2ReveiceData(fromType, fromWeChatContactMapping);
insertWeChatContactMapping(fromWeChatContactMapping); insertWeChatContactMapping(fromWeChatContactMapping);
insertWeChatContactMapping(reveiceWeChatContactMapping); insertWeChatContactMapping(reveiceWeChatContactMapping);
elasticSearchEntity.setData(chatData);
resultList.add(elasticSearchEntity);
}); });
return resultList;
}
private void getUserOrCustomerInfo(JSONObject chatData, String fromId, int fromType, String key) {
//获取发送人信息
if (WeConstans.ID_TYPE_USER.equals(fromType)) {
//成员信息
WeUser weUser = weUserMapper.selectOne(new LambdaQueryWrapper<WeUser>().eq(WeUser::getUserId, fromId));
chatData.put(key, JSONObject.parse(JSONObject.toJSONString(weUser)));
} else if (WeConstans.ID_TYPE_EX.equals(fromType)) {
//获取外部联系人信息
WeCustomer weCustomer = weCustomerMapper.selectWeCustomerById(fromId);
chatData.put(key,JSONObject.parse(JSONObject.toJSONString(weCustomer)));
} else if (WeConstans.ID_TYPE_MACHINE.equals(fromType)) {
//拉去机器人信息暂不处理
}
} }
@Override @Override
......
...@@ -15,6 +15,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -15,6 +15,7 @@ import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -160,4 +161,45 @@ public class WeConversationArchiveServiceImpl implements IWeConversationArchiveS ...@@ -160,4 +161,45 @@ public class WeConversationArchiveServiceImpl implements IWeConversationArchiveS
return null; return null;
} }
} }
@Override
public PageInfo<JSONObject> getChatAllList(ConversationArchiveQuery query) {
PageDomain pageDomain = TableSupport.buildPageRequest();
Integer pageNum = pageDomain.getPageNum() == null ? 1 : pageDomain.getPageNum();
Integer pageSize = pageDomain.getPageSize() == null ? 10 : pageDomain.getPageSize();
SearchSourceBuilder builder = new SearchSourceBuilder();
int from = (pageNum - 1) * pageSize;
builder.size(pageSize);
builder.from(from);
builder.sort("msgtime", SortOrder.DESC);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//成员姓名查询
if(StringUtils.isNotEmpty(query.getUserName())){
boolQueryBuilder.must(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("fromInfo.name",query.getUserName()))
.mustNot(QueryBuilders.existsQuery("fromInfo.externalUserid")));
}
//客户姓名查询
if(StringUtils.isNotEmpty(query.getCustomerName())){
boolQueryBuilder.must(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("fromInfo.name",query.getCustomerName()))
.must(QueryBuilders.existsQuery("fromInfo.externalUserid")));
}
//关键词查询并高亮显示
if (StringUtils.isNotEmpty(query.getKeyWord())){
boolQueryBuilder.must(QueryBuilders.multiMatchQuery(query.getKeyWord(),"text.content"));
builder.highlighter(new HighlightBuilder().field("text.content"));
}
//时间范围查询
if (StringUtils.isNotEmpty(query.getBeginTime()) && StringUtils.isNotEmpty(query.getEndTime())) {
Date beginTime = DateUtils.dateTime(query.getBeginTime(), DateUtils.YYYY_MM_DD);
Date endTime = DateUtils.dateTime(query.getEndTime(), DateUtils.YYYY_MM_DD);
boolQueryBuilder.filter(QueryBuilders.rangeQuery("msgtime").gte(beginTime).lte(endTime));
}
builder.query(boolQueryBuilder);
PageInfo<JSONObject> pageInfo = elasticSearch.searchPage(WeConstans.WECOM_FINANCE_INDEX, builder, pageNum, pageSize, JSONObject.class);
return pageInfo;
}
} }
package com.linkwechat.wecom.service.impl; package com.linkwechat.wecom.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
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.page.PageDomain;
import com.linkwechat.common.core.page.TableSupport;
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.wecom.domain.WeSensitive; import com.linkwechat.wecom.domain.WeSensitive;
import com.linkwechat.wecom.domain.WeSensitiveAuditScope;
import com.linkwechat.wecom.domain.WeUser;
import com.linkwechat.wecom.domain.query.WeSensitiveHitQuery;
import com.linkwechat.wecom.mapper.WeSensitiveMapper; import com.linkwechat.wecom.mapper.WeSensitiveMapper;
import com.linkwechat.wecom.service.IWeSensitiveAuditScopeService; import com.linkwechat.wecom.service.IWeSensitiveAuditScopeService;
import com.linkwechat.wecom.service.IWeSensitiveService; import com.linkwechat.wecom.service.IWeSensitiveService;
import com.linkwechat.wecom.service.IWeUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/** /**
* 敏感词设置Service业务层处理 * 敏感词设置Service业务层处理
...@@ -20,6 +43,7 @@ import java.util.List; ...@@ -20,6 +43,7 @@ import java.util.List;
* @date 2020-12-29 * @date 2020-12-29
*/ */
@Service @Service
@Slf4j
public class WeSensitiveServiceImpl implements IWeSensitiveService { public class WeSensitiveServiceImpl implements IWeSensitiveService {
@Autowired @Autowired
private WeSensitiveMapper weSensitiveMapper; private WeSensitiveMapper weSensitiveMapper;
...@@ -27,6 +51,12 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService { ...@@ -27,6 +51,12 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService {
@Autowired @Autowired
private IWeSensitiveAuditScopeService sensitiveAuditScopeService; private IWeSensitiveAuditScopeService sensitiveAuditScopeService;
@Autowired
private ElasticSearch elasticSearch;
@Autowired
private IWeUserService weUserService;
/** /**
* 查询敏感词设置 * 查询敏感词设置
* *
...@@ -132,4 +162,112 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService { ...@@ -132,4 +162,112 @@ public class WeSensitiveServiceImpl implements IWeSensitiveService {
} }
return deleteResult; return deleteResult;
} }
@Override
public void hitSensitive(List<JSONObject> entityList) {
//获取所有的敏感词规则
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());
jsonList.addAll(hitSensitiveInES(patternWords, users));
//将命中结果插入es
try {
addHitSensitiveList(jsonList, weSensitive);
} catch (IOException e) {
log.warn("添加敏感词命中信息失败, jsonList={}, auditUserId={}, exception={}",
jsonList, weSensitive.getAuditUserId(), ExceptionUtils.getStackTrace(e));
}
});
}
}
@Override
public PageInfo<JSONObject> getHitSensitiveList(WeSensitiveHitQuery weSensitiveHitQuery) {
List<String> userIds = Lists.newArrayList();
if (weSensitiveHitQuery.getScopeType().equals(WeConstans.USE_SCOP_BUSINESSID_TYPE_USER)) {
userIds.add(weSensitiveHitQuery.getAuditScopeId());
} else {
List<String> userIdList = weUserService.selectWeUserList(WeUser.builder().department(new String[]{weSensitiveHitQuery.getAuditScopeId()}).build())
.stream().filter(Objects::nonNull).map(WeUser::getUserId).collect(Collectors.toList());
userIds.addAll(userIdList);
}
PageDomain pageDomain = TableSupport.buildPageRequest();
Integer pageNum = pageDomain.getPageNum() == null ? 1 : pageDomain.getPageNum();
Integer pageSize = pageDomain.getPageSize() == null ? 10 : pageDomain.getPageSize();
SearchSourceBuilder builder = new SearchSourceBuilder();
int from = (pageNum - 1) * pageSize;
builder.size(pageSize);
builder.from(from);
builder.sort("msgtime", SortOrder.DESC);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
BoolQueryBuilder userBuilder = QueryBuilders.boolQuery();
userIds.forEach(user -> {
userBuilder.should(QueryBuilders.termQuery("from.keyword", user));
});
userBuilder.minimumShouldMatch(1);
boolQueryBuilder.must(userBuilder);
if (StringUtils.isNotBlank(weSensitiveHitQuery.getKeyword())) {
BoolQueryBuilder keywordBuilder = QueryBuilders.boolQuery().should(QueryBuilders.matchPhraseQuery("text.content", weSensitiveHitQuery.getKeyword()));
boolQueryBuilder.must(keywordBuilder);
}
builder.query(boolQueryBuilder);
return elasticSearch.searchPage(WeConstans.WECOM_SENSITIVE_HIT_INDEX, builder, pageNum, pageSize, JSONObject.class);
}
private void addHitSensitiveList(List<JSONObject> json, WeSensitive weSensitive) throws IOException {
//创建索引
elasticSearch.createIndex2(WeConstans.WECOM_SENSITIVE_HIT_INDEX, elasticSearch.getFinanceMapping());
if (weSensitive.getAlertFlag().equals(1)) {
//针对每一条命中信息发送消息通知给相应的审计人 TODO
}
//批量提交插入记录
if (CollectionUtils.isNotEmpty(json)) {
List<ElasticSearchEntity> list = json.stream().filter(Objects::nonNull).map(j -> {
ElasticSearchEntity ese = new ElasticSearchEntity();
ese.setData(j);
ese.setId(j.getString("msgid"));
return ese;
}).collect(Collectors.toList());
elasticSearch.insertBatch(WeConstans.WECOM_SENSITIVE_HIT_INDEX, list);
}
}
private List<String> getScopeUsers(List<WeSensitiveAuditScope> scopeList) {
List<String> users = Lists.newArrayList();
scopeList.forEach(scope -> {
if (scope.getScopeType().equals(WeConstans.USE_SCOP_BUSINESSID_TYPE_USER)) {
users.add(scope.getAuditScopeId());
} else {
List<String> userIdList = weUserService.selectWeUserList(WeUser.builder().department(new String[]{scope.getAuditScopeId()}).build())
.stream().filter(Objects::nonNull).map(WeUser::getUserId).collect(Collectors.toList());
users.addAll(userIdList);
}
});
return users;
}
private List<JSONObject> hitSensitiveInES(List<String> patternWords, List<String> users) {
//TODO user过大时进行分组处理
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.sort("msgtime", SortOrder.DESC);
BoolQueryBuilder patterWordsBuilder = QueryBuilders.boolQuery();
patternWords.forEach(word -> {
patterWordsBuilder.should(QueryBuilders.matchPhraseQuery("text.content", word));
});
patterWordsBuilder.minimumShouldMatch(1);
BoolQueryBuilder userBuilder = QueryBuilders.boolQuery();
users.forEach(user -> {
userBuilder.should(QueryBuilders.termQuery("from.keyword", user));
});
userBuilder.minimumShouldMatch(1);
BoolQueryBuilder searchBuilder = QueryBuilders.boolQuery().must(patterWordsBuilder).must(userBuilder);
builder.query(searchBuilder);
return elasticSearch.search(WeConstans.WECOM_FINANCE_INDEX, builder, JSONObject.class);
}
} }
...@@ -42,11 +42,12 @@ ...@@ -42,11 +42,12 @@
<if test="patternWords != null and patternWords != ''">and a.pattern_words like concat('%', <if test="patternWords != null and patternWords != ''">and a.pattern_words like concat('%',
#{patternWords}, '%') #{patternWords}, '%')
</if> </if>
<if test="auditUserId != null ">and a.audit_user_id = #{auditUserId}</if> <if test="auditUserId != null and auditUserId != ''">and a.audit_user_id = #{auditUserId}</if>
<if test="auditUserName != null and auditUserName != ''">and a.audit_user_name like concat('%', <if test="auditUserName != null and auditUserName != ''">and a.audit_user_name like concat('%',
#{auditUserName}, '%') #{auditUserName}, '%')
</if> </if>
</where> </where>
order by a.update_time desc, a.create_time desc
</select> </select>
<select id="selectWeSensitiveById" parameterType="Long" resultMap="WeSensitiveResult"> <select id="selectWeSensitiveById" parameterType="Long" resultMap="WeSensitiveResult">
...@@ -60,6 +61,7 @@ ...@@ -60,6 +61,7 @@
<foreach item="id" collection="array" open="(" separator="," close=")"> <foreach item="id" collection="array" open="(" separator="," close=")">
#{id} #{id}
</foreach> </foreach>
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="WeSensitive" useGeneratedKeys="true" keyProperty="id">
...@@ -67,7 +69,7 @@ ...@@ -67,7 +69,7 @@
<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>
<if test="patternWords != null and patternWords != ''">pattern_words,</if> <if test="patternWords != null and patternWords != ''">pattern_words,</if>
<if test="auditUserId != null">audit_user_id,</if> <if test="auditUserId != null and auditUserId != ''">audit_user_id,</if>
<if test="auditUserName != null and auditUserName != ''">audit_user_name,</if> <if test="auditUserName != null and auditUserName != ''">audit_user_name,</if>
<if test="alertFlag != null">alert_flag,</if> <if test="alertFlag != null">alert_flag,</if>
<if test="delFlag != null">del_flag,</if> <if test="delFlag != null">del_flag,</if>
...@@ -79,7 +81,7 @@ ...@@ -79,7 +81,7 @@
<trim prefix="values (" suffix=")" suffixOverrides=","> <trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="strategyName != null and strategyName != ''">#{strategyName},</if> <if test="strategyName != null and strategyName != ''">#{strategyName},</if>
<if test="patternWords != null and patternWords != ''">#{patternWords},</if> <if test="patternWords != null and patternWords != ''">#{patternWords},</if>
<if test="auditUserId != null">#{auditUserId},</if> <if test="auditUserId != null and auditUserId != ''">#{auditUserId},</if>
<if test="auditUserName != null and auditUserName != ''">#{auditUserName},</if> <if test="auditUserName != null and auditUserName != ''">#{auditUserName},</if>
<if test="alertFlag != null">#{alertFlag},</if> <if test="alertFlag != null">#{alertFlag},</if>
<if test="delFlag != null">#{delFlag},</if> <if test="delFlag != null">#{delFlag},</if>
...@@ -95,7 +97,7 @@ ...@@ -95,7 +97,7 @@
<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>
<if test="patternWords != null and patternWords != ''">pattern_words = #{patternWords},</if> <if test="patternWords != null and patternWords != ''">pattern_words = #{patternWords},</if>
<if test="auditUserId != null">audit_user_id = #{auditUserId},</if> <if test="auditUserId != null and auditUserId != ''">audit_user_id = #{auditUserId},</if>
<if test="auditUserName != null">audit_user_name = #{auditUserName},</if> <if test="auditUserName != null">audit_user_name = #{auditUserName},</if>
<if test="alertFlag != null">alert_flag = #{alertFlag},</if> <if test="alertFlag != null">alert_flag = #{alertFlag},</if>
<if test="delFlag != null">del_flag = #{delFlag},</if> <if test="delFlag != null">del_flag = #{delFlag},</if>
...@@ -126,7 +128,7 @@ ...@@ -126,7 +128,7 @@
</trim> </trim>
<trim prefix="audit_user_id = case" suffix="end,"> <trim prefix="audit_user_id = case" suffix="end,">
<foreach collection="list" item="item" index="index"> <foreach collection="list" item="item" index="index">
<if test="item.auditUserId != null"> <if test="item.auditUserId != null and auditUserId != ''">
when id = #{item.id} then #{item.auditUserId} when id = #{item.id} then #{item.auditUserId}
</if> </if>
</foreach> </foreach>
......
...@@ -10,7 +10,7 @@ Target Server Type : MYSQL ...@@ -10,7 +10,7 @@ Target Server Type : MYSQL
Target Server Version : 50718 Target Server Version : 50718
File Encoding : 65001 File Encoding : 65001
Date: 2020-12-30 10:16:02 Date: 2021-01-04 10:23:38
*/ */
SET FOREIGN_KEY_CHECKS=0; SET FOREIGN_KEY_CHECKS=0;
...@@ -5762,50 +5762,6 @@ CREATE TABLE `we_customer` ( ...@@ -5762,50 +5762,6 @@ CREATE TABLE `we_customer` (
-- ---------------------------- -- ----------------------------
-- ---------------------------- -- ----------------------------
-- Table structure for we_customer_imageMessage
-- ----------------------------
DROP TABLE IF EXISTS `we_customer_imageMessage`;
CREATE TABLE `we_customer_imageMessage` (
`image_message_id` bigint(64) NOT NULL,
`message_id` bigint(64) DEFAULT NULL COMMENT '微信消息表id',
`media_id` varchar(100) DEFAULT NULL COMMENT '图片的media_id,可以通过 <a href="https://work.weixin.qq.com/api/doc/90000/90135/90253">素材管理接口</a>获得',
`pic_url` varchar(100) DEFAULT NULL COMMENT '图片的链接,仅可使用<a href="https://work.weixin.qq.com/api/doc/90000/90135/90256">上传图片接口</a>得到的链接',
`create_by` varchar(64) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_by` varchar(255) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`del_flag` int(1) DEFAULT '0',
PRIMARY KEY (`image_message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='群发消息 图片消息';
-- ----------------------------
-- Records of we_customer_imageMessage
-- ----------------------------
-- ----------------------------
-- Table structure for we_customer_linkMessage
-- ----------------------------
DROP TABLE IF EXISTS `we_customer_linkMessage`;
CREATE TABLE `we_customer_linkMessage` (
`link_message_id` bigint(64) NOT NULL,
`message_id` bigint(64) DEFAULT NULL COMMENT '微信消息表id',
`title` varchar(100) DEFAULT NULL COMMENT '图文消息标题',
`picurl` varchar(255) DEFAULT NULL COMMENT '图文消息封面的url',
`desc` varchar(1000) DEFAULT NULL COMMENT '图文消息的描述,最多512个字节',
`url` varchar(1000) DEFAULT NULL COMMENT '图文消息的链接',
`create_by` varchar(64) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_by` varchar(64) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`del_flag` int(1) DEFAULT '0',
PRIMARY KEY (`link_message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='群发消息 链接消息表';
-- ----------------------------
-- Records of we_customer_linkMessage
-- ----------------------------
-- ----------------------------
-- Table structure for we_customer_message -- Table structure for we_customer_message
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `we_customer_message`; DROP TABLE IF EXISTS `we_customer_message`;
...@@ -5818,12 +5774,15 @@ CREATE TABLE `we_customer_message` ( ...@@ -5818,12 +5774,15 @@ CREATE TABLE `we_customer_message` (
`check_status` varchar(2) DEFAULT NULL COMMENT '消息发送状态 0 未发送 1 已发送', `check_status` varchar(2) DEFAULT NULL COMMENT '消息发送状态 0 未发送 1 已发送',
`msgid` varchar(100) DEFAULT NULL COMMENT '企业群发消息的id,可用于<a href="https://work.weixin.qq.com/api/doc/90000/90135/92136">获取群发消息发送结果</a>', `msgid` varchar(100) DEFAULT NULL COMMENT '企业群发消息的id,可用于<a href="https://work.weixin.qq.com/api/doc/90000/90135/92136">获取群发消息发送结果</a>',
`content` text COMMENT '消息内容', `content` text COMMENT '消息内容',
`send_info` varchar(255) DEFAULT NULL COMMENT '发送情况 ps:显示样式 1)定时任务 发送时间:2020-12-25 10:00:00 2) 预计发送3190人,已成功发送0人 3)预计发送2个群,已成功发送0个群 ',
`create_by` varchar(64) DEFAULT NULL, `create_by` varchar(64) DEFAULT NULL,
`create_time` datetime DEFAULT NULL, `create_time` datetime DEFAULT NULL,
`update_by` varchar(64) DEFAULT NULL, `update_by` varchar(64) DEFAULT NULL,
`update_time` datetime DEFAULT NULL, `update_time` datetime DEFAULT NULL,
`del_flag` int(11) DEFAULT NULL, `del_flag` int(11) DEFAULT NULL,
`setting_time` varchar(255) DEFAULT NULL COMMENT '发送时间',
`expect_send` int(11) DEFAULT '0' COMMENT '预计发送消息数(客户对应多少人 客户群对应多个群)',
`actual_send` int(11) DEFAULT '0' COMMENT '实际发送消息数(客户对应多少人 客户群对应多个群)',
`timed_task` int(1) DEFAULT '0' COMMENT '是否定时任务 0 常规 1 定时发送',
PRIMARY KEY (`message_id`) PRIMARY KEY (`message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='群发消息 微信消息表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='群发消息 微信消息表';
...@@ -5886,29 +5845,6 @@ CREATE TABLE `we_customer_messgaeResult` ( ...@@ -5886,29 +5845,6 @@ CREATE TABLE `we_customer_messgaeResult` (
-- ---------------------------- -- ----------------------------
-- ---------------------------- -- ----------------------------
-- Table structure for we_customer_miniprogramMessage
-- ----------------------------
DROP TABLE IF EXISTS `we_customer_miniprogramMessage`;
CREATE TABLE `we_customer_miniprogramMessage` (
`miniprogram_message_id` bigint(64) NOT NULL,
`message_id` bigint(64) DEFAULT NULL COMMENT '微信消息表id',
`title` varchar(255) DEFAULT NULL COMMENT '小程序消息标题,最多64个字节',
`pic_media_id` varchar(100) DEFAULT NULL COMMENT '小程序消息封面的mediaid,封面图建议尺寸为520*416',
`appid` varchar(100) DEFAULT NULL COMMENT '小程序appid,必须是关联到企业的小程序应用',
`page` varchar(255) DEFAULT NULL COMMENT '小程序page路径',
`create_by` varchar(64) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_by` varchar(64) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`del_flag` int(2) DEFAULT '0',
PRIMARY KEY (`miniprogram_message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='群发消息 小程序消息';
-- ----------------------------
-- Records of we_customer_miniprogramMessage
-- ----------------------------
-- ----------------------------
-- Table structure for we_customer_seedMessage -- Table structure for we_customer_seedMessage
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `we_customer_seedMessage`; DROP TABLE IF EXISTS `we_customer_seedMessage`;
...@@ -5940,26 +5876,6 @@ CREATE TABLE `we_customer_seedMessage` ( ...@@ -5940,26 +5876,6 @@ CREATE TABLE `we_customer_seedMessage` (
-- ---------------------------- -- ----------------------------
-- ---------------------------- -- ----------------------------
-- Table structure for we_customer_textMessage
-- ----------------------------
DROP TABLE IF EXISTS `we_customer_textMessage`;
CREATE TABLE `we_customer_textMessage` (
`text_message_id` bigint(64) NOT NULL,
`message_id` bigint(64) DEFAULT NULL COMMENT '微信消息表id',
`content` text COMMENT '消息文本内容,最多4000个字节',
`create_by` varchar(64) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_by` varchar(64) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`del_flag` int(2) DEFAULT '0',
PRIMARY KEY (`text_message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of we_customer_textMessage
-- ----------------------------
-- ----------------------------
-- Table structure for we_department -- Table structure for we_department
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `we_department`; DROP TABLE IF EXISTS `we_department`;
...@@ -6316,6 +6232,10 @@ CREATE TABLE `we_poster_subassembly` ( ...@@ -6316,6 +6232,10 @@ CREATE TABLE `we_poster_subassembly` (
`vertical_type` tinyint(255) DEFAULT NULL COMMENT '垂直对齐方式', `vertical_type` tinyint(255) DEFAULT NULL COMMENT '垂直对齐方式',
`word_space` int(255) DEFAULT NULL COMMENT '字间距', `word_space` int(255) DEFAULT NULL COMMENT '字间距',
`line_space` int(255) DEFAULT NULL COMMENT '行间距', `line_space` int(255) DEFAULT NULL COMMENT '行间距',
`alpha` int(255) DEFAULT NULL COMMENT '透明度[0,255]',
`rotate` int(255) DEFAULT NULL COMMENT '旋转角度(顺时针)',
`font_style` tinyint(255) DEFAULT NULL COMMENT '字体类型 0 通常 1 粗体 2 斜体',
`order` int(255) DEFAULT NULL COMMENT '排序 顺序',
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
...@@ -6400,7 +6320,7 @@ CREATE TABLE `we_sensitive` ( ...@@ -6400,7 +6320,7 @@ CREATE TABLE `we_sensitive` (
id BIGINT auto_increment NOT NULL COMMENT '主键', id BIGINT auto_increment NOT NULL COMMENT '主键',
strategy_name varchar(100) NOT NULL COMMENT '策略名称', strategy_name varchar(100) NOT NULL COMMENT '策略名称',
pattern_words TEXT NOT NULL COMMENT '匹配词', pattern_words TEXT NOT NULL COMMENT '匹配词',
audit_user_id BIGINT NOT NULL COMMENT '审计人id', audit_user_id varchar(64) NOT NULL COMMENT '审计人id',
audit_user_name varchar(30) NOT NULL COMMENT '审计人', audit_user_name varchar(30) NOT NULL COMMENT '审计人',
alert_flag TINYINT DEFAULT 1 NOT NULL COMMENT '消息通知,1 开启 0 关闭', alert_flag TINYINT DEFAULT 1 NOT NULL COMMENT '消息通知,1 开启 0 关闭',
del_flag TINYINT DEFAULT 0 NOT NULL COMMENT '删除标识,1 已删除 0 未删除', del_flag TINYINT DEFAULT 0 NOT NULL COMMENT '删除标识,1 已删除 0 未删除',
...@@ -6419,7 +6339,7 @@ CREATE TABLE `we_sensitive_audit_scope` ( ...@@ -6419,7 +6339,7 @@ CREATE TABLE `we_sensitive_audit_scope` (
id BIGINT auto_increment NOT NULL COMMENT '主键', id BIGINT auto_increment NOT NULL COMMENT '主键',
sensitive_id BIGINT NOT NULL COMMENT '敏感词表主键', sensitive_id BIGINT NOT NULL COMMENT '敏感词表主键',
scope_type TINYINT NOT NULL COMMENT '审计范围类型, 1 组织机构 2 成员', scope_type TINYINT NOT NULL COMMENT '审计范围类型, 1 组织机构 2 成员',
audit_scope_id BIGINT NOT NULL COMMENT '审计对象id', audit_scope_id varchar(64) NOT NULL COMMENT '审计对象id',
audit_scope_name varchar(64) NOT NULL COMMENT '审计对象名称', audit_scope_name varchar(64) NOT NULL COMMENT '审计对象名称',
CONSTRAINT we_sensitive_audit_scope_pk PRIMARY KEY (id) CONSTRAINT we_sensitive_audit_scope_pk PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='敏感词审计范围'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='敏感词审计范围';
\ No newline at end of file \ 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!