钉钉通讯录事件监听,保存到mdm

2024年8月29日 15:58:19
This commit is contained in:
xiang2lin 2024-08-29 15:58:25 +08:00
parent 0727770457
commit 2eb9960f23
4 changed files with 276 additions and 54 deletions

View File

@ -1,16 +1,22 @@
package com.hzya.frame.plugin.kjs.listener;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.open.app.api.GenericEventListener;
import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;
import com.dingtalk.open.app.api.message.GenericOpenDingTalkEvent;
import com.dingtalk.open.app.api.security.AuthClientCredential;
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus;
import com.hzya.frame.dingtalk.service.IDingTalkExtService;
import com.hzya.frame.plugin.kjs.service.GenericEventConsumer;
import com.hzya.frame.plugin.kjs.util.GenericEventThreadPool;
import com.hzya.frame.sysnew.application.dao.ISysApplicationDao;
import com.hzya.frame.sysnew.application.entity.SysApplicationEntity;
import com.hzya.frame.sysnew.application.service.ISysApplicationService;
import com.hzya.frame.sysnew.application.service.impl.ApplicationCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@ -21,23 +27,38 @@ import javax.annotation.Resource;
* @Date 2024/8/27 14:43
**/
@Component
@Order(9999)
public class GenericEventSubscribe {
Logger logger = LoggerFactory.getLogger(getClass());
//线程池
GenericEventThreadPool threadPool = new GenericEventThreadPool();
@Resource
private GenericEventConsumer genericEventConsumer;
@Value("${dingtalk.appKey:}")
private String appKey;
@Value("${dingtalk.appSecret:}")
private String appSecret;
@Resource
private TaskExecutor taskExecutor;
@Resource
private ApplicationCache applicationCache;
@Resource
private IDingTalkExtService dingTalkExtService;
@Resource
private ISysApplicationDao sysApplicationDao;
@PostConstruct
public void init() {
//查询钉钉配置的参数
SysApplicationEntity sysApp = new SysApplicationEntity();
sysApp.setAppId(800005);
sysApp = sysApplicationDao.queryOne(sysApp);
if (null != sysApp){
JSONObject dingTalkConfig = dingTalkExtService.getDingTalkConfig(sysApp);
if (null != dingTalkConfig){
String appKey = dingTalkConfig.getString("appKey");
String appSecret = dingTalkConfig.getString("appSecret");
subscribe(appKey,appSecret);
}
}
}
/**
* 通讯录事件订阅
*/
@PostConstruct
public void subscribe(){
public void subscribe(String appKey,String appSecret){
try {
logger.info("通讯录事件订阅");
OpenDingTalkStreamClientBuilder
@ -49,14 +70,11 @@ public class GenericEventSubscribe {
try {
try {
//处理事件
threadPool.executeTask(() ->{
taskExecutor.execute(()->{
genericEventConsumer.consume(event);
});
threadPool.close();
}catch (Exception e){
logger.error("GenericEventThreadPool错误{}",e);
}finally {
threadPool.close();
}
//消费成功
return EventAckStatus.SUCCESS;

View File

@ -3,12 +3,15 @@ package com.hzya.frame.plugin.kjs.service;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.dingtalk.api.response.OapiV2DepartmentGetResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.open.app.api.message.GenericOpenDingTalkEvent;
import com.hzya.frame.dingtalk.enums.OrgEventEnum;
import com.hzya.frame.dingtalk.service.IDingTalkService;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@ -16,6 +19,7 @@ import shade.com.alibaba.fastjson2.JSONArray;
import shade.com.alibaba.fastjson2.JSONObject;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@ -26,8 +30,31 @@ import java.util.Map;
**/
public class GenericEventConsumer {
Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private IDingTalkService dingtalkService;
//中台应用
private static final String APPCODE = "800004";
private static final String URL = "http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterface";
//中台 publicKey
private static final String PUBLICKEY = "ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj";
//中台secretKey
private static final String SECRETKEY = "fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=";
//mdm通用新增接口编码
private static final String MDMADDCODE = "8000040022";
//mdm通用删除接口编码
private static final String MDMREMOVECODE = "8000040024";
//主数据人员钉钉档案编码
private static final String DDUSERMDMCODE = "10015";
//主数据钉钉部门档案编码
private static final String DDDEPTMDMCODE = "10016";
//钉钉应用编码
private static final String DDAPPCODE = "800005";
//钉钉 publicKey
private static final String DDPUBLICKEY = "ZJYAn/EBWEhLUMezDLU4iZ1vTO9kc6pM6XrYLajnqnK60Q9Ce7eDIk+3zDUT+v578prj";
//钉钉secretKey
private static final String DDSECRETKEY = "ctMIYyauwoKSFeU4tg5gH1aWC/3OJK6HsKJrSR0oyDmdmdvRNgdoTzX0C1OQ+whrj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=";
//获取钉钉用户详情接口编码
private static final String GETUSERAPPCODE="8000050001";
//获取钉钉部门详情接口编码
private static final String GETDETPAPPCODE="8000050002";
/**
* 消费通讯录事件订阅消息
*
@ -44,42 +71,102 @@ public class GenericEventConsumer {
JSONObject bizData = event.getData();
logger.info("事件唯一id{},事件类型:{},参数:{}",eventId,eventType,JSONObject.toJSONString(bizData));
OrgEventEnum orgEventEnum = OrgEventEnum.getByCode(eventType);
String apiCode = "";
String type = "";
String apiCode = MDMADDCODE;
String type = "user";
boolean flag = false;
switch (orgEventEnum){
//新增到主数据
case USER_ADD_ORG:
type = "user";
apiCode = "8000040022";
break;
case USER_MODIFY_ORG:
case USER_LEAVE_ORG:
type = "user";
apiCode = "8000040023";
case USER_MODIFY_ORG:
flag = true;
break;
case ORG_DEPT_CREATE:
type = "dept";
apiCode = "8000040022";
break;
case ORG_DEPT_MODIFY:
type = "dept";
apiCode = "8000040023";
flag = true;
break;
case ORG_DEPT_REMOVE:
type = "dept";
apiCode = "8000040024";
apiCode = MDMREMOVECODE;
flag = true;
break;
}
if ("user".equals(type)){
//解析报文
JSONArray userIds = bizData.getJSONArray("userId");
for (int i=0; i<userIds.size();i++){
OapiV2UserGetResponse.UserGetResponse userInfo = dingtalkService.getUserById(userIds.getString(i));
if (flag){
if ("user".equals(type)){
JSONArray userIds = bizData.getJSONArray("userId");
//调用钉钉查询用户详情接口
for (int i=0; i<userIds.size();i++){
//获取用户详情
String userRes = getUserById(String.valueOf(userIds.get(i)));
//保存钉钉用户到mdm
String userMdmRes = createUser(userRes);
}
}else if ("dept".equals(type)){
JSONArray deptIdArr = bizData.getJSONArray("deptId");
for (int i=0; i<deptIdArr.size(); i++){
//查询部门详情
String deptRes = getDeptById(deptIdArr.getLong(i));
//保存部门到mdm
String deptMdmRes = createDept(deptRes,apiCode);
}
}
}
}
/**
* 查询钉钉用户详情
* @param userid
* @return
*/
private static String getUserById(String userid) {
Map<String, String> userHeaderMap = MapBuilder.<String, String>create(true)
.put("apiCode", GETUSERAPPCODE)//钉钉接口
.put("publicKey",PUBLICKEY)//中台应用
.put("secretKey",SECRETKEY)//中台应用
.put("appId",DDAPPCODE)//钉钉接口
.build();
Map<String,Object> userParam = new HashMap<>();
userParam.put("userid", userid);
userParam.put("language","zh_CN");
String userRes = HttpRequest.post(URL).addHeaders(userHeaderMap).body(com.alibaba.fastjson.JSONObject.toJSONString(userParam)).timeout(60000).execute().body();
return userRes;
}
/**
* 查询钉钉部门详情
* @param deptId
* @return
*/
private String getDeptById(Long deptId) {
Map<String, String> userHeaderMap = MapBuilder.<String, String>create(true)
.put("apiCode", GETDETPAPPCODE)//钉钉接口
.put("publicKey",PUBLICKEY)//中台应用
.put("secretKey",SECRETKEY)//中台应用
.put("appId",DDAPPCODE)//钉钉接口
.build();
Map<String,Object> deptParam = new LinkedHashMap<>();
deptParam.put("dept_id",deptId);
deptParam.put("language","zh_CN");
String deptRes = HttpRequest.post(URL).addHeaders(userHeaderMap).body(com.alibaba.fastjson.JSONObject.toJSONString(deptParam)).timeout(60000).execute().body();
return deptRes;
}
//保存用户到mdm
private static String createUser(String userRes) {
JsonResultEntity jsonResult = JSONObject.parseObject(userRes,JsonResultEntity.class);
if (jsonResult.isFlag()){
shade.com.alibaba.fastjson2.JSONObject attribute = (shade.com.alibaba.fastjson2.JSONObject) jsonResult.getAttribute();
String attrStr = attribute.toString();
OapiV2UserGetResponse rsp = JSONObject.parseObject(attrStr, OapiV2UserGetResponse.class);
if (rsp.isSuccess()){
OapiV2UserGetResponse.UserGetResponse userInfo = rsp.getResult();
//OapiV2UserGetResponse.UserGetResponse userInfo = dingtalkService.getUserById(userIds.getString(i));
Map<String,Object> mdmMap = new LinkedHashMap<>();
mdmMap.put("mdmCode","10031");
mdmMap.put("mdmCode",DDUSERMDMCODE);
mdmMap.put("optionName","系统管理员");
Map<String,Object> userMap = new LinkedHashMap<>();
userMap.put("data_id", IdUtil.fastUUID());
userMap.put("data_id", userInfo.getUserid());
userMap.put("unionid",userInfo.getUnionid());
userMap.put("userid",userInfo.getUserid());
userMap.put("name",userInfo.getName());
@ -94,36 +181,53 @@ public class GenericEventConsumer {
mdmMap.put("mdm_dd_user",userMap);
//保存到人员主数据
Map<String, String> headerMap = MapBuilder.<String, String>create(true)
.put("apiCode", apiCode)//中台接口
.put("publicKey","ZJYAn/EBWEhLUMezDLU4iZ1vTO9kc6pM6XrYLajnqnK60Q9Ce7eDIk+3zDUT+v578prj")//钉钉应用
.put("secretKey","ctMIYyauwoKSFeU4tg5gH1aWC/3OJK6HsKJrSR0oyDmdmdvRNgdoTzX0C1OQ+whrj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=")//钉钉应用
.put("appId","800004")//中台应用
.put("apiCode", MDMADDCODE)//中台接口
.put("publicKey",DDPUBLICKEY)//钉钉应用
.put("secretKey",DDSECRETKEY)//钉钉应用
.put("appId",APPCODE)//中台应用
.build();
String body = HttpRequest.post("http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterface").addHeaders(headerMap).body(com.alibaba.fastjson.JSONObject.toJSONString(mdmMap)).timeout(60000).execute().body();
System.out.println(body);
String body = HttpRequest.post(URL).addHeaders(headerMap).body(com.alibaba.fastjson.JSONObject.toJSONString(mdmMap)).timeout(60000).execute().body();
return body;
}
}else if ("dept".equals(type)){
JSONArray deptIdArr = bizData.getJSONArray("deptId");
for (int i=0; i<deptIdArr.size(); i++){
OapiV2DepartmentGetResponse.DeptGetResponse deptInfo = dingtalkService.getDeptById(deptIdArr.getLong(i));
}
return null;
}
/**
* 保存部门到mdm
* @param deptRes
* @return
*/
private String createDept(String deptRes,String apiCode) {
if (StrUtil.isNotEmpty(deptRes) && StrUtil.isNotEmpty(apiCode)){
JsonResultEntity jsonResult = JSONObject.parseObject(deptRes,JsonResultEntity.class);
if (jsonResult.isFlag()){
shade.com.alibaba.fastjson2.JSONObject attribute = (shade.com.alibaba.fastjson2.JSONObject) jsonResult.getAttribute();
String attrStr = attribute.toString();
OapiV2DepartmentGetResponse rsp = JSONObject.parseObject(attrStr,OapiV2DepartmentGetResponse.class);
String result = attribute.getString("result");
OapiV2DepartmentGetResponse.DeptGetResponse deptInfo = com.alibaba.fastjson.JSONObject.parseObject(result,OapiV2DepartmentGetResponse.DeptGetResponse.class);
//OapiV2DepartmentGetResponse.DeptGetResponse deptInfo = dingtalkService.getDeptById(deptIdArr.getLong(i));
Map<String,Object> mdmMap = new LinkedHashMap<>();
mdmMap.put("mdmCode","10033");
mdmMap.put("mdmCode",DDDEPTMDMCODE);
mdmMap.put("optionName","系统管理员");
Map<String,Object> deptMap = new LinkedHashMap<>();
deptMap.put("dept_id",deptInfo.getDeptId());
deptMap.put("data_id",deptInfo.getDeptId());
deptMap.put("name",deptInfo.getName());
deptMap.put("parent_id",deptInfo.getParentId());
mdmMap.put("mdm_dd_dept",deptMap);
//保存部门到主数据
Map<String, String> headerMap = MapBuilder.<String, String>create(true)
.put("apiCode", apiCode)//中台接口
.put("publicKey","ZJYAn/EBWEhLUMezDLU4iZ1vTO9kc6pM6XrYLajnqnK60Q9Ce7eDIk+3zDUT+v578prj")//钉钉应用
.put("secretKey","ctMIYyauwoKSFeU4tg5gH1aWC/3OJK6HsKJrSR0oyDmdmdvRNgdoTzX0C1OQ+whrj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=")//钉钉应用
.put("appId","800004")//中台应用
.put("publicKey",DDPUBLICKEY)//钉钉应用
.put("secretKey",DDSECRETKEY)//钉钉应用
.put("appId",APPCODE)//中台应用
.build();
String body = HttpRequest.post("http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterface").addHeaders(headerMap).body(com.alibaba.fastjson.JSONObject.toJSONString(mdmMap)).timeout(60000).execute().body();
System.out.println(body);
String body = HttpRequest.post(URL).addHeaders(headerMap).body(com.alibaba.fastjson.JSONObject.toJSONString(mdmMap)).timeout(60000).execute().body();
return body;
}
}
return null;
}
}

View File

@ -0,0 +1,100 @@
package com.hzya.frame.dingtalk.service.impl;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.dingtalk.service.IDingTalkExtService;
import com.hzya.frame.dingtalk.util.DingTalkAccessToken;
import com.hzya.frame.sysnew.application.api.entity.SysApplicationApiEntity;
import com.hzya.frame.sysnew.application.apiPara.dao.ISysApplicationApiParaDao;
import com.hzya.frame.sysnew.application.apiPara.entity.SysApplicationApiParaEntity;
import com.hzya.frame.sysnew.application.apiPara.service.ISysApplicationApiParaService;
import com.hzya.frame.sysnew.application.entity.SysApplicationEntity;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Description 钉钉集成扩展类
* @Author xiangerlin
* @Date 2024/8/28 14:25
**/
@Service
public class DingTalkExtServiceImpl implements IDingTalkExtService {
@Resource
private ISysApplicationApiParaDao sysApplicationApiParaDao;
private final ConcurrentHashMap<String, JSONObject> dingTalkMap = new ConcurrentHashMap<>();
/**
* 调用这个方法初始化钉钉参数
*
* @param entity
* @return
*/
@Override
public SysExtensionApiEntity init(SysExtensionApiEntity entity) {
Map<String, String> headers = entity.getHeaders();
if (null == headers){
headers = new HashMap<>();
}
SysApplicationEntity receiveApp = entity.getReceiveApp();
//查询应用上配置的参数
JSONObject dingTalkConfig = getDingTalkConfig(receiveApp);
//给token赋值
entity.setQuerys("access_token="+DingTalkAccessToken.getAccessToken(dingTalkConfig.getString("appKey"),dingTalkConfig.getString("appSecret")));
return entity;
}
/**
* 查询配置在应用上的钉钉参数
*
* @param sysApplication
* @return
*/
@Override
public JSONObject getDingTalkConfig(SysApplicationEntity sysApplication) {
if (null != sysApplication && StrUtil.isNotEmpty(sysApplication.getId()) && null != sysApplication.getAppId()){
JSONObject jsonObject = new JSONObject();
String key = sysApplication.getAppId()+"dingTalk";
if (null != dingTalkMap.get(key)){
return dingTalkMap.get(key);
}else {
//查询应用上配置的参数
SysApplicationApiParaEntity paraEntity = new SysApplicationApiParaEntity();
paraEntity.setAppId(sysApplication.getId());
List<SysApplicationApiParaEntity> paraList = sysApplicationApiParaDao.query(paraEntity);
if (CollectionUtils.isNotEmpty(paraList)) {
List<SysApplicationApiParaEntity> appKeyList = paraList.stream().filter(p -> p.getInterfaceKey().equals("appKey")).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(appKeyList)) {
jsonObject.put("appKey", appKeyList.get(0).getInterfaceValue());
}
List<SysApplicationApiParaEntity> appSecretList = paraList.stream().filter(p -> p.getInterfaceKey().equals("appSecret")).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(appSecretList)) {
jsonObject.put("appSecret", appSecretList.get(0).getInterfaceValue());
}
dingTalkMap.put(key,jsonObject);
return dingTalkMap.get(key);
}
}
}
return null;
}
/**
* 清空配置缓存
*/
@Override
public void clearDingTalkConfigCatch() {
dingTalkMap.clear();
}
}

View File

@ -19,7 +19,7 @@ import org.springframework.stereotype.Service;
* @Author xiangerlin
* @Date 2024/8/27 16:17
**/
@Service()
@Service
public class DingTalkServiceImpl implements IDingTalkService {
Logger logger = LoggerFactory.getLogger(getClass());
@Value("${dingtalk.appKey:}")