package com.qianwen.smartman.modules.sync.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Service; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.DefaultTransactionDefinition; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.aliyun.dingtalkcontact_1_0.models.GetUserHeaders; import com.aliyun.dingtalkcontact_1_0.models.GetUserResponseBody; import com.aliyun.dingtalkoauth2_1_0.Client; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.dingtalk.api.DefaultDingTalkClient; import com.dingtalk.api.request.OapiAuthScopesRequest; import com.dingtalk.api.request.OapiRoleListRequest; import com.dingtalk.api.request.OapiRoleSimplelistRequest; import com.dingtalk.api.request.OapiSnsGetuserinfoBycodeRequest; import com.dingtalk.api.request.OapiUserGetbyunionidRequest; import com.dingtalk.api.request.OapiV2DepartmentGetRequest; import com.dingtalk.api.request.OapiV2DepartmentListsubRequest; import com.dingtalk.api.request.OapiV2UserGetRequest; import com.dingtalk.api.request.OapiV2UserListRequest; import com.dingtalk.api.response.OapiAuthScopesResponse; import com.dingtalk.api.response.OapiRoleListResponse; import com.dingtalk.api.response.OapiRoleSimplelistResponse; import com.dingtalk.api.response.OapiSnsGetuserinfoBycodeResponse; import com.dingtalk.api.response.OapiUserGetbyunionidResponse; import com.dingtalk.api.response.OapiV2DepartmentGetResponse; import com.dingtalk.api.response.OapiV2DepartmentListsubResponse; import com.dingtalk.api.response.OapiV2UserGetResponse; import com.dingtalk.api.response.OapiV2UserListResponse; import com.qianwen.core.log.exception.ServiceException; import com.qianwen.core.tool.utils.Func; import com.qianwen.core.tool.utils.StringUtil; import com.qianwen.smartman.common.constant.CommonConstant; import com.qianwen.smartman.common.constant.CommonGroupConstant; import com.qianwen.smartman.common.enums.CommonGroupTypeEnum; import com.qianwen.smartman.common.utils.MessageUtils; import com.qianwen.smartman.modules.cps.entity.CommonGroup; import com.qianwen.smartman.modules.cps.entity.CommonGroupOfItem; import com.qianwen.smartman.modules.cps.entity.Employee; import com.qianwen.smartman.modules.cps.entity.EmployeePost; import com.qianwen.smartman.modules.cps.mapper.CommonGroupMapper; import com.qianwen.smartman.modules.cps.service.ICommonGroupOfItemService; import com.qianwen.smartman.modules.cps.service.ICommonGroupService; import com.qianwen.smartman.modules.cps.service.IEmployeePostService; import com.qianwen.smartman.modules.cps.service.IEmployeeService; import com.qianwen.smartman.modules.sync.constant.DingConstant; import com.qianwen.smartman.modules.sync.constant.OuterAppConfigConstant; import com.qianwen.smartman.modules.sync.constant.QyWechatConstant; import com.qianwen.smartman.modules.sync.entity.DingOriDept; import com.qianwen.smartman.modules.sync.entity.DingOriUser; import com.qianwen.smartman.modules.sync.entity.OuterAppConfig; import com.qianwen.smartman.modules.sync.service.IDingEventService; import com.qianwen.smartman.modules.sync.service.IDingSyncService; import com.qianwen.smartman.modules.sync.service.IOuterAppConfigService; import com.qianwen.smartman.modules.sync.vo.SyncResultVO; import com.qianwen.smartman.modules.system.entity.Post; import com.qianwen.smartman.modules.system.entity.UserOauth; import com.qianwen.smartman.modules.system.mapper.PostMapper; import com.qianwen.smartman.modules.system.service.IParamService; import com.qianwen.smartman.modules.system.service.IPostService; import com.qianwen.smartman.modules.system.service.IUserOauthService; import com.taobao.api.TaobaoRequest; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; @Service /* loaded from: blade-api.jar:BOOT-INF/classes/org/springblade/modules/sync/service/impl/DingSyncServiceImpl.class */ public class DingSyncServiceImpl implements IDingSyncService { private static final Logger log = LoggerFactory.getLogger(DingSyncServiceImpl.class); private final IUserOauthService userOauthService; private final IEmployeeService employeeService; private final IPostService postService; private final ICommonGroupService groupService; private final CommonGroupMapper commonGroupMapper; private final IDingEventService dingEventService; private final ICommonGroupOfItemService commonGroupOfItemService; private Map> userPostRelationMap; private final DataSourceTransactionManager dataSourceTransactionManager; private final PostMapper postMapper; private final IOuterAppConfigService outerAppConfigService; private final IParamService paramService; private final IEmployeePostService employeePostService; public DingSyncServiceImpl(final IUserOauthService userOauthService, final IEmployeeService employeeService, final IPostService postService, final ICommonGroupService groupService, final CommonGroupMapper commonGroupMapper, final IDingEventService dingEventService, final ICommonGroupOfItemService commonGroupOfItemService, final Map> userPostRelationMap, final DataSourceTransactionManager dataSourceTransactionManager, final PostMapper postMapper, final IOuterAppConfigService outerAppConfigService, final IParamService paramService, final IEmployeePostService employeePostService) { this.userOauthService = userOauthService; this.employeeService = employeeService; this.postService = postService; this.groupService = groupService; this.commonGroupMapper = commonGroupMapper; this.dingEventService = dingEventService; this.commonGroupOfItemService = commonGroupOfItemService; this.userPostRelationMap = userPostRelationMap; this.dataSourceTransactionManager = dataSourceTransactionManager; this.postMapper = postMapper; this.outerAppConfigService = outerAppConfigService; this.paramService = paramService; this.employeePostService = employeePostService; } @Override // org.springblade.modules.sync.service.IDingSyncService public SyncResultVO syncImmediately() { OuterAppConfig dingAppConfig = this.outerAppConfigService.getAppConfig(OuterAppConfigConstant.DING); String appKey = dingAppConfig.getDingAppKey(); String appSecret = dingAppConfig.getDingAppSecret(); DefaultTransactionDefinition transDefinition = new DefaultTransactionDefinition(); List posts = new ArrayList<>(); List oriGroups = new ArrayList<>(); List oriUsers = new ArrayList<>(); TransactionStatus transStatus = this.dataSourceTransactionManager.getTransaction(transDefinition); SyncResultVO syncResultVO = new SyncResultVO(); try { getRoles(appKey, appSecret, posts, syncResultVO); List permissionGroups = getPermissionGroup(appKey, appSecret, syncResultVO); if (Func.isEmpty(permissionGroups)) { syncResultVO.setGroupResult(false); syncResultVO.setUserReason("未获取到权限范围内的组织机构!"); } for (Long permissionGroup : permissionGroups) { SyncEmployee(permissionGroup, appKey, appSecret, oriUsers, syncResultVO); recursionGetGroup(permissionGroup, appKey, appSecret, oriGroups, oriUsers, syncResultVO, permissionGroups); } if (!syncResultVO.getGroupResult().booleanValue() || !syncResultVO.getPostResult().booleanValue() || !syncResultVO.getUserResult().booleanValue()) { this.userPostRelationMap.clear(); return syncResultVO; } List employees = new ArrayList<>(); List employeePosts = new ArrayList<>(); List userOauths = new ArrayList<>(); List commonGroupOfItems = new ArrayList<>(); List updateEmployees = new ArrayList<>(); Boolean flag = true; try { this.postMapper.removePost(); this.postService.saveBatch(posts); } catch (Exception e2) { flag = false; syncResultVO.setPostResult(false); syncResultVO.setPostReason("同步钉钉角色数据库部分报错:" + e2.toString()); } try { this.commonGroupMapper.removeOrg(); insertGroups(permissionGroups, oriGroups, appKey, appSecret); } catch (Exception e3) { flag = false; syncResultVO.setGroupResult(false); syncResultVO.setGroupReason("同步钉钉部门数据库部分报错:" + e3.toString()); } try { this.userOauthService.remove(Wrappers.lambdaQuery()); this.commonGroupMapper.removeOrgContact(); this.employeePostService.remove(Wrappers.lambdaQuery()); handleAuthAndEmployee(oriUsers, employees, userOauths, commonGroupOfItems, employeePosts, updateEmployees); this.employeeService.remove(Wrappers.lambdaQuery().notIn(Func.isNotEmpty(updateEmployees), Employee::getId, updateEmployees.stream().map(Employee::getId).collect(Collectors.toList()))); /* this.employeeService.remove(Wrappers.lambdaQuery().notIn(Func.isNotEmpty(updateEmployees), (v0) -> { return v0.getId(); }, (Collection) updateEmployees.stream().map((v0) -> { return v0.getId(); }).collect(Collectors.toList())));*/ this.employeeService.saveBatch(employees); this.employeeService.updateBatchById(updateEmployees); this.userOauthService.saveOrUpdateBatch(userOauths); this.commonGroupOfItemService.saveBatch(commonGroupOfItems); if (Func.isNotEmpty(employeePosts)) { this.employeePostService.saveBatch(employeePosts); } } catch (Exception e4) { flag = false; syncResultVO.setUserResult(false); syncResultVO.setUserReason("同步钉钉员工数据库部分报错:" + e4.toString()); } if (syncResultVO.getGroupResult().booleanValue() && syncResultVO.getPostResult().booleanValue() && syncResultVO.getUserResult().booleanValue()) { this.outerAppConfigService.update(Wrappers.lambdaUpdate().eq(OuterAppConfig::getAppType, OuterAppConfigConstant.DING) .set(OuterAppConfig::getLastSyncTime, new Date())); /* this.outerAppConfigService.update((Wrapper) ((LambdaUpdateWrapper) Wrappers.lambdaUpdate().eq((v0) -> { return v0.getAppType(); }, OuterAppConfigConstant.DING)).set((v0) -> { return v0.getLastSyncTime(); }, new Date()));*/ } if (flag.booleanValue()) { this.dataSourceTransactionManager.commit(transStatus); } else { this.dataSourceTransactionManager.rollback(transStatus); } this.userPostRelationMap.clear(); return syncResultVO; } catch (Exception th) { log.error("同步钉钉通讯录异常,异常信息为:", th); this.dataSourceTransactionManager.rollback(transStatus); //throw th; }finally { this.userPostRelationMap.clear(); } return syncResultVO; } private List getPermissionGroup(String appKey, String appSecret, SyncResultVO syncResultVO) { try { DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/auth/scopes"); OapiAuthScopesRequest req = new OapiAuthScopesRequest(); req.setHttpMethod("GET"); OapiAuthScopesResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret)); JSONObject jsonObject = JSONObject.parseObject(rsp.getBody()); if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) { JSONObject authInfo = jsonObject.getJSONObject("auth_org_scopes"); JSONArray deptArray = authInfo.getJSONArray("authed_dept"); return deptArray.toJavaList(Long.class); } syncResultVO.setUserResult(false); syncResultVO.setUserReason("获取权限下部门报错,结果为:" + jsonObject + "---------参数为:" + req); return null; } catch (Exception e) { syncResultVO.setGroupResult(false); syncResultVO.setUserReason("获取权限下部门报错:" + e.toString()); return null; } } @Override // org.springblade.modules.sync.service.IDingSyncService @Transactional public Boolean scanCodeBind(String code, String state) { OuterAppConfig outerAppConfig = this.outerAppConfigService.getAppConfig(OuterAppConfigConstant.DING); String appKey = outerAppConfig.getDingAppKey(); String appSecret = outerAppConfig.getDingAppSecret(); JSONObject userObject = null; try { String userId = getUserIdByCode(code, appKey, appSecret); if (Func.isNotEmpty(userId)) { userObject = getDetailByUserId(userId, appKey, appSecret); } if (Func.isNotEmpty(userId) && Func.isNotEmpty(userObject)) { UserOauth userOauth = this.userOauthService.getOne(Wrappers.lambdaQuery().eq(UserOauth::getUuid, userId), false); /* UserOauth userOauth = (UserOauth) this.userOauthService.getOne((Wrapper) Wrappers.lambdaQuery().eq((v0) -> { return v0.getUuid(); }, userId), false);*/ if (Func.isEmpty(userOauth)) { throw new ServiceException(MessageUtils.message("sys.outer.user.not.exist", new Object[0])); } if (Func.isEmpty(userOauth.getUserId())) { relationScanUser(userObject, userOauth, state); this.userOauthService.updateById(userOauth); return true; } throw new ServiceException(MessageUtils.message("cps.employee.already.bind", new Object[0])); } throw new ServiceException(MessageUtils.message("sys.outer.user.not.exist", new Object[0])); } catch (Exception e) { log.error("扫码绑定员工异常,异常信息为:", e); return false; } } @Override // org.springblade.modules.sync.service.IDingSyncService public Boolean unbind(Long id, String source) { UserOauth userOauth = this.userOauthService.getOne(Wrappers.lambdaQuery().eq(UserOauth::getUserId, id).eq(UserOauth::getSource, source)); /* UserOauth userOauth = (UserOauth) this.userOauthService.getOne((Wrapper) ((LambdaQueryWrapper) Wrappers.lambdaQuery().eq((v0) -> { return v0.getUserId(); }, id)).eq((v0) -> { return v0.getSource(); }, source));*/ if (Func.isEmpty(userOauth)) { throw new ServiceException(MessageUtils.message("cps.employee.not.band", new Object[0])); } return Boolean.valueOf(this.userOauthService.update(Wrappers.lambdaUpdate() .set(UserOauth::getUserId, null).eq(UserOauth::getUserId, id).eq(UserOauth::getSource, source))); /* return Boolean.valueOf(this.userOauthService.update((Wrapper) ((LambdaUpdateWrapper) ((LambdaUpdateWrapper) Wrappers.lambdaUpdate().set((v0) -> { return v0.getUserId(); }, (Object) null)).eq((v0) -> { return v0.getUserId(); }, id)).eq((v0) -> { return v0.getSource(); }, source)));*/ } @Override // org.springblade.modules.sync.service.IDingSyncService public String getDingUserId(String code) { try { OuterAppConfig outerAppConfig = this.outerAppConfigService.getAppConfig(OuterAppConfigConstant.DING); String appKey = outerAppConfig.getDingAppKey(); String appSecret = outerAppConfig.getDingAppSecret(); String userId = getUserIdByCode(code, appKey, appSecret); return userId; } catch (Exception e) { log.error("获取钉钉userId异常,异常信息为:", e); return null; } } private String getUserIdByCode(String code, String appKey, String appSecret) throws Exception { DefaultDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode"); OapiSnsGetuserinfoBycodeRequest reqBycodeRequest = new OapiSnsGetuserinfoBycodeRequest(); reqBycodeRequest.setTmpAuthCode(code); OapiSnsGetuserinfoBycodeResponse bycodeResponse = client2.execute(reqBycodeRequest, appKey, appSecret); if (Func.isEmpty(bycodeResponse) || Func.isEmpty(bycodeResponse.getUserInfo())) { return null; } String unionid = bycodeResponse.getUserInfo().getUnionid(); DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); OapiUserGetbyunionidRequest reqGetbyunionidRequest = new OapiUserGetbyunionidRequest(); reqGetbyunionidRequest.setUnionid(unionid); OapiUserGetbyunionidResponse oapiUserGetbyunionidResponse = defaultDingTalkClient.execute(reqGetbyunionidRequest, this.dingEventService.getDingAccessToken(appKey, appSecret)); if (Func.isEmpty(oapiUserGetbyunionidResponse) || Func.isEmpty(oapiUserGetbyunionidResponse.getResult()) || Func.isEmpty(oapiUserGetbyunionidResponse.getResult().getUserid())) { return null; } String userid = oapiUserGetbyunionidResponse.getResult().getUserid(); return userid; } private void relationScanUser(JSONObject userObject, UserOauth userOauth, String state) { Employee employee = (Employee) this.employeeService.getById(state); if (Func.isNotEmpty(employee)) { if (!employee.getTel().equals(userObject.getString("mobile"))) { throw new ServiceException(MessageUtils.message("cps.employee.not.current.scan.user", new Object[0])); } userOauth.setUserId(employee.getId()); return; } throw new ServiceException(MessageUtils.message("cps.employee.not.exist.by.mobile", new Object[0])); } private JSONObject getDetailByUserId(String userId, String appKey, String appSecret) throws Exception { DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get"); OapiV2UserGetRequest reqDetail = new OapiV2UserGetRequest(); reqDetail.setUserid(userId); OapiV2UserGetResponse rspDetail = defaultDingTalkClient.execute(reqDetail, this.dingEventService.getDingAccessToken(appKey, appSecret)); JSONObject jsonObject = JSONObject.parseObject(rspDetail.getBody()); if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) { return jsonObject.getJSONObject("result"); } return null; } private String getUserIdByUnionId(GetUserResponseBody userBody, String appKey, String appSecret) throws Exception { DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); OapiUserGetbyunionidRequest req = new OapiUserGetbyunionidRequest(); req.setUnionid(userBody.getUnionId()); OapiUserGetbyunionidResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret)); if (Func.isEmpty(rsp) || Func.isEmpty(rsp.getBody())) { return null; } JSONObject userObject = JSONObject.parseObject(rsp.getBody()).getJSONObject("result"); if (Func.isEmpty(userObject)) { return null; } return userObject.getString("userid"); } private void handleAuthAndEmployee(List oriUsers, List employees, List userOauths, List commonGroupOfItems, List employeePosts, List updateEmployees) { if (Func.isNotEmpty(oriUsers)) { String pinValue = this.paramService.getValue("employee.default.pin"); List dbEmployees = this.employeeService.list(); Map employeeMap = dbEmployees.parallelStream().filter(o -> { return Func.isNotEmpty(o.getTel()); }).collect(Collectors.toMap((v0) -> { return v0.getTel(); }, e -> { return e; }, (k1, k2) -> { return k1; })); Snowflake snowflake = IdUtil.createSnowflake(1L, 1L); Set distinctUser = new HashSet<>(); oriUsers.forEach(oriUser -> { if (!distinctUser.contains(oriUser.getUserid())) { distinctUser.add(oriUser.getUserid()); Employee employee = handleEmployee(oriUser, employees, commonGroupOfItems, employeePosts, snowflake, pinValue, employeeMap, updateEmployees); UserOauth userOauth = packageUserOauth(employee, oriUser); userOauths.add(userOauth); } }); } } @NotNull private Employee handleEmployee(DingOriUser oriUser, List employees, List commonGroupOfItems, List employeePosts, Snowflake snowflake, String pin, Map employeeMap, List updateEmployees) { Employee employee = packageEmployee(oriUser, snowflake, pin, employeeMap); if (Func.isEmpty(employee.getTenantId())) { employees.add(employee); } else { updateEmployees.add(employee); } packageRelation(oriUser, employee, commonGroupOfItems, employeePosts); return employee; } private void packageRelation(DingOriUser oriUser, Employee employee, List commonGroupOfItems, List employeePosts) { if (this.userPostRelationMap.containsKey(oriUser.getUserid())) { employee.setPostId(StringUtil.join(this.userPostRelationMap.get(oriUser.getUserid()), ",")); for (String postId : this.userPostRelationMap.get(oriUser.getUserid())) { EmployeePost employeePost = new EmployeePost(); employeePost.setEmployeeId(employee.getId()); employeePost.setPostId(Long.valueOf(postId)); employeePosts.add(employeePost); } } commonGroupOfItems.add(CommonGroupOfItem.builder().groupId(Long.valueOf(oriUser.getDept_id_list().get(0).equals(1L) ? 3L : Long.valueOf(String.valueOf(oriUser.getDept_id_list().get(0))).longValue())).itemId(employee.getId()).groupType(CommonGroupTypeEnum.ORGANIZATION.getName()).groupCategory(CommonGroupConstant.DEFAULT_CATEGORY).build()); } @NotNull private UserOauth packageUserOauth(Employee employee, DingOriUser dingOriUser) { UserOauth userOauth = new UserOauth(); userOauth.setEmail(employee.getEmail()); userOauth.setUserId(employee.getId()); userOauth.setUsername(employee.getName()); userOauth.setSource(DingConstant.DING_AUTH_KEY); userOauth.setUuid(dingOriUser.getUserid()); userOauth.setAvatar(employee.getAvatar()); return userOauth; } @NotNull private Employee packageEmployee(DingOriUser oriUser, Snowflake snowflake, String pin, Map employeeMap) { Employee employee = new Employee(); employee.setName(oriUser.getName()); employee.setPinCode(pin); employee.setTel(oriUser.getMobile()); if (Func.isNotEmpty(oriUser.getEmail())) { employee.setEmail(oriUser.getEmail()); } if (Func.isNotEmpty(oriUser.getHired_date())) { employee.setHireDate(new Date(oriUser.getHired_date().longValue())); } if (Func.isNotEmpty(oriUser.getJob_number())) { employee.setJobNumber(oriUser.getJob_number()); } if (Func.isNotEmpty(oriUser.getAvatar())) { employee.setAvatar(oriUser.getAvatar()); } employee.setStatus(CommonConstant.ENABLE); employee.setOrganizationId(oriUser.getDept_id_list().get(0).equals(1L) ? "3" : String.valueOf(oriUser.getDept_id_list().get(0))); if (employeeMap.containsKey(oriUser.getMobile())) { Employee oriEmp = employeeMap.get(oriUser.getMobile()); employee.setPinCode(oriEmp.getPinCode()); employee.setUserId(oriEmp.getUserId()); employee.setJobNumber(oriEmp.getJobNumber()); employee.setId(oriEmp.getId()); employee.setTenantId(oriEmp.getTenantId()); employee.setCreateUser(oriEmp.getCreateUser()); employee.setCreateDept(oriEmp.getCreateDept()); } else { employee.setId(Long.valueOf(snowflake.nextId())); } return employee; } private void insertGroups(List permissionGroups, List oriGroups, String appKey, String appSecret) throws Exception { for (Long permissionGroup : permissionGroups) { DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get"); OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest(); req.setDeptId(permissionGroup); OapiV2DepartmentGetResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret)); JSONObject jsonObject = JSONObject.parseObject(rsp.getBody()); if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) { JSONObject resultMap = jsonObject.getJSONObject("result"); this.groupService.insert(CommonGroup.builder().groupCategory(1).groupType(DingConstant.GROUPTYPE).parentId(Long.valueOf(permissionGroup.equals(1L) ? 0L : Long.valueOf(String.valueOf(resultMap.get("parent_id"))).longValue())).name(String.valueOf(resultMap.get("name"))).status(1).id(Long.valueOf(permissionGroup.equals(1L) ? 3L : permissionGroup.longValue())).build()); } } if (Func.isNotEmpty(oriGroups)) { oriGroups.forEach(oriGroup -> { this.groupService.insert(CommonGroup.builder().groupCategory(1).groupType(DingConstant.GROUPTYPE).parentId(Long.valueOf(oriGroup.getParent_id().equals(1L) ? 3L : oriGroup.getParent_id().longValue())).name(oriGroup.getName()).status(1).id(oriGroup.getDept_id()).build()); }); } } private void getRoles(String appKey, String appSecret, List postList, SyncResultVO syncResultVO) { try { DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/role/list"); OapiRoleListRequest req = new OapiRoleListRequest(); req.setSize(DingConstant.ROLE_SIZE); req.setOffset(DingConstant.START_OFFSET); while (true) { OapiRoleListResponse rsp = (OapiRoleListResponse)defaultDingTalkClient.execute((TaobaoRequest)req, this.dingEventService.getDingAccessToken(appKey, appSecret)); JSONObject jsonObject = JSONObject.parseObject(rsp.getBody()); if (jsonObject.getInteger("errcode").equals(DingConstant.SUCCESS)) { Map resultMap = (Map)jsonObject.get("result"); List> resultList = (List>)resultMap.get("list"); if (Func.isNotEmpty(resultList)) for (Map roleGroupMap : resultList) { List> roleList = (List>)roleGroupMap.get("roles"); if (Func.isNotEmpty(roleList)) for (Map role : roleList) { Post post = new Post(); post.setPostCode(String.valueOf(role.get("id"))); post.setId(Long.valueOf(String.valueOf(role.get("id")))); post.setPostName(String.valueOf(role.get("name"))); post.setStatus(CommonConstant.ENABLE); postList.add(post); getRoleContainsUser(post.getPostCode(), appKey, appSecret); } } if (((Boolean)resultMap.get("hasMore")).booleanValue()) { req.setOffset(Long.valueOf(req.getOffset().longValue() + DingConstant.ROLE_SIZE.longValue())); continue; } break; } syncResultVO.setPostResult(Boolean.valueOf(false)); syncResultVO.setPostReason("同步钉钉角色异常,结果为:" + jsonObject + "---------参数为:" + req); break; } } catch (Exception e) { syncResultVO.setPostResult(Boolean.valueOf(false)); syncResultVO.setPostReason("同步钉钉角色报错:" + e.toString()); } } private void getRoleContainsUser(String postCode, String appKey, String appSecret) throws Exception { DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/role/simplelist"); OapiRoleSimplelistRequest req = new OapiRoleSimplelistRequest(); req.setRoleId(Long.valueOf(postCode)); req.setOffset(DingConstant.START_OFFSET); req.setSize(DingConstant.SIZE); while (true) { OapiRoleSimplelistResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret)); JSONObject jsonObject = JSONObject.parseObject(rsp.getBody()); if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) { Map resultMap = (Map) jsonObject.get("result"); List> resultList = (List) resultMap.get("list"); if (Func.isNotEmpty(resultList)) { resultList.forEach(userMap -> { if (this.userPostRelationMap.containsKey(String.valueOf(userMap.get("userid")))) { Set userRoleList = this.userPostRelationMap.get(String.valueOf(userMap.get("userid"))); userRoleList.add(postCode); this.userPostRelationMap.put(String.valueOf(userMap.get("userid")), userRoleList); return; } Set userRoleList2 = new HashSet<>(); userRoleList2.add(postCode); this.userPostRelationMap.put(String.valueOf(userMap.get("userid")), userRoleList2); }); } if (((Boolean) resultMap.get("hasMore")).booleanValue()) { req.setOffset(Long.valueOf(req.getOffset().longValue() + DingConstant.SIZE.longValue())); } else { return; } } else { log.error("同步钉钉用户异常,结果为:" + jsonObject + "---------参数为:" + req.toString()); return; } } } private void recursionGetGroup(Long deptId, String appKey, String appSecret, List oriGroups, List oriUsers, SyncResultVO syncResultVO, List permissionGroups) { try { DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub"); OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest(); req.setDeptId(Long.valueOf(deptId.equals(3L) ? 1L : deptId.longValue())); OapiV2DepartmentListsubResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret)); JSONObject jsonObject = JSONObject.parseObject(rsp.getBody()); if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) { List resultList = jsonObject.getJSONArray("result").toJavaList(DingOriDept.class); if (Func.isNotEmpty(resultList)) { resultList.forEach(dept -> { Long childDeptId = dept.getDept_id(); if (!permissionGroups.contains(childDeptId)) { try { oriGroups.add(dept); } catch (Exception e) { log.error("同步钉钉部门入库时异常,部门为:" + dept); } SyncEmployee(childDeptId, appKey, appSecret, oriUsers, syncResultVO); recursionGetGroup(childDeptId, appKey, appSecret, oriGroups, oriUsers, syncResultVO, permissionGroups); } }); } } else { syncResultVO.setGroupResult(false); syncResultVO.setGroupReason("同步钉钉部门异常,结果为:" + jsonObject + "---------参数为:" + req.toString()); } } catch (Exception e) { syncResultVO.setGroupResult(false); syncResultVO.setGroupReason("同步钉钉部门报错:" + e.toString()); } } private void SyncEmployee(Long deptId, String appKey, String appSecret, List oriUsers, SyncResultVO syncResultVO) { try { DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list"); OapiV2UserListRequest req = new OapiV2UserListRequest(); req.setSize(DingConstant.SIZE); req.setDeptId(Long.valueOf(deptId.equals(Long.valueOf(3L)) ? 1L : deptId.longValue())); req.setCursor(DingConstant.START_OFFSET); while (true) { OapiV2UserListResponse rsp = (OapiV2UserListResponse)defaultDingTalkClient.execute((TaobaoRequest)req, this.dingEventService.getDingAccessToken(appKey, appSecret)); JSONObject jsonObject = JSONObject.parseObject(rsp.getBody()); if (jsonObject.getInteger("errcode").equals(DingConstant.SUCCESS)) { JSONObject resultMap = jsonObject.getJSONObject("result"); List resultList = resultMap.getJSONArray("list").toJavaList(DingOriUser.class); if (Func.isNotEmpty(resultList)) resultList.forEach(userMap -> oriUsers.add(userMap)); if (((Boolean)resultMap.get("has_more")).booleanValue()) { req.setCursor(Long.valueOf(String.valueOf(resultMap.get("next_cursor")))); continue; } break; } syncResultVO.setUserResult(Boolean.valueOf(false)); syncResultVO.setUserReason("同步钉钉用户异常,结果为:" + jsonObject + "---------参数为:" + req); break; } } catch (Exception e) { syncResultVO.setUserResult(Boolean.valueOf(false)); syncResultVO.setUserReason("同步钉钉用户报错:" + e.toString()); } } public static Client authClient() throws Exception { Config config = new Config(); config.protocol = "https"; config.regionId = "central"; return new Client(config); } public static com.aliyun.dingtalkcontact_1_0.Client contactClient() throws Exception { Config config = new Config(); config.protocol = "https"; config.regionId = "central"; return new com.aliyun.dingtalkcontact_1_0.Client(config); } public GetUserResponseBody getUserinfo(String accessToken) throws Exception { com.aliyun.dingtalkcontact_1_0.Client client = contactClient(); GetUserHeaders getUserHeaders = new GetUserHeaders(); getUserHeaders.xAcsDingtalkAccessToken = accessToken; GetUserResponseBody responseBody = client.getUserWithOptions("me", getUserHeaders, new RuntimeOptions()).getBody(); return responseBody; } }