package com.qianwen.smartman.modules.sync.service.impl; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; 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.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.dingtalk.api.DefaultDingTalkClient; import com.dingtalk.api.request.OapiAuthScopesRequest; 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.response.OapiAuthScopesResponse; 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 java.lang.invoke.SerializedLambda; import java.util.ArrayList; import java.util.Collection; 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 com.qianwen.smartman.common.cache.RegionCache; 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.core.log.exception.ServiceException; import com.qianwen.core.tool.utils.Func; import com.qianwen.core.tool.utils.StringUtil; 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 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; @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; private static /* synthetic */ Object $deserializeLambda$(SerializedLambda lambda) { String implMethodName = lambda.getImplMethodName(); boolean z = true; switch (implMethodName.hashCode()) { case -75080655: if (implMethodName.equals("getUuid")) { z = true; break; } break; case 98245393: if (implMethodName.equals("getId")) { z = true; break; } break; case 242925765: if (implMethodName.equals("getAppType")) { z = true; break; } break; case 799509265: if (implMethodName.equals("getSource")) { z = false; break; } break; case 859984188: if (implMethodName.equals("getUserId")) { z = true; break; } break; case 1722789684: if (implMethodName.equals("getLastSyncTime")) { z = true; break; } break; } switch (z) { case false: if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/String;")) { return (v0) -> { return v0.getSource(); }; } if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/String;")) { return (v0) -> { return v0.getSource(); }; } break; case true: if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/String;")) { return (v0) -> { return v0.getUuid(); }; } break; case true: if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/core/mp/base/BaseEntity") && lambda.getImplMethodSignature().equals("()Ljava/lang/Long;")) { return (v0) -> { return v0.getId(); }; } break; case true: if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/sync/entity/OuterAppConfig") && lambda.getImplMethodSignature().equals("()Ljava/util/Date;")) { return (v0) -> { return v0.getLastSyncTime(); }; } break; case true: if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/Long;")) { return (v0) -> { return v0.getUserId(); }; } if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/Long;")) { return (v0) -> { return v0.getUserId(); }; } if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/Long;")) { return (v0) -> { return v0.getUserId(); }; } break; case RegionCache.VILLAGE_LEVEL /* 5 */: if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/sync/entity/OuterAppConfig") && lambda.getImplMethodSignature().equals("()Ljava/lang/Integer;")) { return (v0) -> { return v0.getAppType(); }; } break; } throw new IllegalArgumentException("Invalid lambda deserialization"); } 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() { List posts; List oriGroups; List oriUsers; List permissionGroups; OuterAppConfig dingAppConfig = this.outerAppConfigService.getAppConfig(OuterAppConfigConstant.DING); String appKey = dingAppConfig.getDingAppKey(); String appSecret = dingAppConfig.getDingAppSecret(); DefaultTransactionDefinition transDefinition = new DefaultTransactionDefinition(); TransactionStatus transStatus = this.dataSourceTransactionManager.getTransaction(transDefinition); SyncResultVO syncResultVO = new SyncResultVO(); try { try { posts = new ArrayList<>(); oriGroups = new ArrayList<>(); oriUsers = new ArrayList<>(); getRoles(appKey, appSecret, posts, syncResultVO); 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); } } catch (Exception e) { log.error("同步钉钉通讯录异常,异常信息为:", e); this.dataSourceTransactionManager.rollback(transStatus); this.userPostRelationMap.clear(); } 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), (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((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 (Throwable th) { this.userPostRelationMap.clear(); throw th; } } 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 = (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 = (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((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 = (Map) 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()); }); } } /* JADX WARN: Code restructure failed: missing block: B:20:0x0161, code lost: r10.setPostResult(false); r10.setPostReason("同步钉钉角色异常,结果为:" + r0 + "---------参数为:" + r0); */ /* Code decompiled incorrectly, please refer to instructions dump. To view partially-correct code enable 'Show inconsistent code' option in preferences */ private void getRoles(java.lang.String r7, java.lang.String r8, java.util.List r9, org.springblade.modules.sync.vo.SyncResultVO r10) { /* Method dump skipped, instructions count: 448 To view this dump change 'Code comments level' option to 'DEBUG' */ throw new UnsupportedOperationException("Method not decompiled: org.springblade.modules.sync.service.impl.DingSyncServiceImpl.getRoles(java.lang.String, java.lang.String, java.util.List, org.springblade.modules.sync.vo.SyncResultVO):void"); } 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()); } } /* JADX WARN: Code restructure failed: missing block: B:15:0x00cb, code lost: r11.setUserResult(false); r11.setUserReason("同步钉钉用户异常,结果为:" + r0 + "---------参数为:" + r0); */ /* Code decompiled incorrectly, please refer to instructions dump. To view partially-correct code enable 'Show inconsistent code' option in preferences */ private void SyncEmployee(java.lang.Long r7, java.lang.String r8, java.lang.String r9, java.util.List r10, org.springblade.modules.sync.vo.SyncResultVO r11) { /* Method dump skipped, instructions count: 298 To view this dump change 'Code comments level' option to 'DEBUG' */ throw new UnsupportedOperationException("Method not decompiled: org.springblade.modules.sync.service.impl.DingSyncServiceImpl.SyncEmployee(java.lang.Long, java.lang.String, java.lang.String, java.util.List, org.springblade.modules.sync.vo.SyncResultVO):void"); } 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; } }