DingMod.java
21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package vion.third;
import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.linpeilie.Converter;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.codec.binary.Base64;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.lang.Opt;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.crypto.digest.mac.HMac;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import vion.constant.RedisKeyEnum;
import vion.dto.DingDTO;
import vion.model.*;
import vion.service.*;
import vion.utils.JsonUtil;
import vion.vo.RoleVO;
import vion.vo.UserVO;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author vion
* @date 2023/11/13
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class DingMod {
@Value("${ding.appkey:}")
private String appKey;
@Value("${ding.appsecret:}")
private String appSecret;
private final IUserService userService;
private final IRoleService roleService;
private final IResourceService resourceService;
private final IRUserRoleService userRoleService;
private final IRRoleResourceService roleResourceService;
private final IDeptService deptService;
private final Converter converter;
private final RedissonClient redissonClient;
private final RestClient oDingRestClient;
private final RestClient dingRestClient;
/**
* 获取钉钉token
*
* @return java.lang.String
*/
public String getToken() {
return (String) Opt.ofNullable(redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.ACCESS_TOKEN.getVal()).get())
.orElseGet(() -> {
JsonNode tokenJson = oDingRestClient.get()
.uri("/gettoken?appkey={appKey}&appsecret={appSecret}", appKey, appSecret)
.retrieve()
.body(JsonNode.class);
return Opt.ofNullable(tokenJson)
.map(jsonNode -> {
String accessToken = jsonNode.path("access_token").asText();
redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.ACCESS_TOKEN.getVal())
.set(accessToken, Duration.ofSeconds(7000));
return accessToken;
})
.orElse("");
});
}
/**
* 获取钉钉员工列表
*/
public void getDingUserList() {
String accessToken = getToken();
List<String> userIdList = new ArrayList<>();
Long offset = 0L;
boolean flag = true;
while (flag) {
// 2:试用期 3:正式 5:待离职 -1:无状态
var paramJson = JsonUtil.createObj()
.put("status_list", "2,3,5,-1")
.put("size", 50)
.put("offset", offset);
var jsonNode = oDingRestClient.post()
.uri("/topapi/smartwork/hrm/employee/queryonjob?access_token={accessToken}", accessToken)
.contentType(MediaType.APPLICATION_JSON)
.body(paramJson.toString())
.retrieve()
.body(JsonNode.class);
if (ObjUtil.isNotNull(jsonNode) && jsonNode.path("success").asBoolean(false)) {
jsonNode.path("result").withArray("data_list")
.forEach(v -> userIdList.add(v.asText()));
long nextCursor = jsonNode.path("result").path("next_cursor").asLong(-1L);
if (nextCursor > 0) {
offset = nextCursor;
} else {
flag = false;
}
}
}
if (CollUtil.isEmpty(userIdList)) {
log.error("获取钉钉用户id列表为空");
return;
}
List<List<String>> userIdListSplit = ListUtil.partition(userIdList, 90);
userIdListSplit.forEach(tmpList -> {
var paramJson = JsonUtil.createObj()
.put("agentid", 2358374016L)
.put("userid_list", String.join(",", tmpList))
.put("field_filter_list", "sys00-name,sys00-mobile,sys00-mainDeptId,sys00-mainDept,sys01-employeeStatus");
var jsonNode = oDingRestClient.post()
.uri("/topapi/smartwork/hrm/employee/v2/list?access_token={accessToken}", accessToken)
.contentType(MediaType.APPLICATION_JSON)
.body(paramJson.toString())
.retrieve()
.body(JsonNode.class);
var success = ObjUtil.isNotNull(jsonNode) && jsonNode.path("success").asBoolean(false);
if (!success) {
log.error("获取用户列表失败:{}", jsonNode);
return;
}
var resArr = jsonNode.withArray("result");
for (JsonNode o : resArr) {
User user = new User();
String userid = o.path("userid").asText();
user.setUserid(userid);
var dataArr = o.withArray("field_data_list");
for (JsonNode o1 : dataArr) {
if (StrUtil.equals("sys00-name", o1.path("field_code").asText())) {
user.setUsername(o1.withArray("field_value_list").path(0).path("value").asText());
} else if (StrUtil.equals("sys00-mobile", o1.path("field_code").asText())) {
user.setPhone(o1.withArray("field_value_list").path(0).path("value").asText(""));
} else if (StrUtil.equals("sys00-mainDeptId", o1.path("field_code").asText())) {
user.setDeptId(o1.withArray("field_value_list").path(0).path("value").asLong());
} else if (StrUtil.equals("sys01-employeeStatus", o1.path("field_code").asText())) {
user.setEmployeeStatus(o1.withArray("field_value_list").path(0).path("value").asInt());
}
}
userService.lambdaQuery()
.eq(User::getUserid, userid)
.oneOpt()
.ifPresentOrElse(u -> {
user.setId(u.getId());
userService.updateById(user);
}, () -> userService.save(user));
User one = userService.lambdaQuery().eq(User::getUserid, userid).one();
redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_ID.getVal() + one.getId()).set(user);
redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_NAME.getVal() + one.getUsername()).set(user);
}
});
}
/**
* 获取钉钉部门列表
*/
public void getDeptList() {
String accessToken = getToken();
List<Long> deptIdList = ListUtil.of(1L);
int idx = 0;
while (idx < deptIdList.size()) {
// 2:试用期 3:正式 5:待离职 -1:无状态
Long value = deptIdList.get(idx++);
var jsonNode = oDingRestClient.post()
.uri("/topapi/v2/department/listsub?access_token={accessToken}", accessToken)
.contentType(MediaType.APPLICATION_JSON)
.body(JsonUtil.createObj().put("dept_id", value).toString())
.retrieve()
.body(JsonNode.class);
var success = ObjUtil.isNotNull(jsonNode) && StrUtil.equals("ok", jsonNode.path("errmsg").asText());
if (!success) {
log.error("获取部门列表失败:{}", jsonNode);
return;
}
var resArr = jsonNode.withArray("result");
if (CollUtil.isNotEmpty(resArr)) {
for (JsonNode o : resArr) {
Dept dept = new Dept();
var deptId = o.path("dept_id").asLong();
dept.setDeptId(deptId);
dept.setParentId(o.path("parent_id").asLong());
dept.setDeptName(o.path("name").asText());
deptService.lambdaQuery()
.eq(Dept::getDeptId, deptId)
.oneOpt()
.ifPresentOrElse(d -> {
dept.setId(d.getId());
deptService.updateById(dept);
}, () -> deptService.save(dept));
deptIdList.add(deptId);
}
}
}
}
/**
* 钉钉工作消息推送
*/
public String workMsg(String msg) {
String token = getToken();
var res = oDingRestClient.post()
.uri("/topapi/message/corpconversation/asyncsend_v2?access_token={accessToken}", token)
.contentType(MediaType.APPLICATION_JSON)
.body(msg)
.retrieve()
.body(String.class);
log.info("钉钉工作通知消息推送:{}", res);
return res;
}
/**
* 钉钉回调接口
*
* @param target login,inside 区分是钉钉扫码登录还是钉钉内打开链接
* @param dto dto
* @param res httpServletResponse
* @return java.lang.Object
*/
public Object dingCallback(String target, DingDTO dto, HttpServletResponse res) {
if (StrUtil.equals(target, "login")) {
var objNode = JsonUtil.createObj()
.put("clientId", appKey)
.put("clientSecret", appSecret)
.put("code", dto.getAuthCode())
.put("grantType", "authorization_code");
var tokenNode = dingRestClient.post()
.uri("/v1.0/oauth2/userAccessToken")
.contentType(MediaType.APPLICATION_JSON)
.body(objNode.toString())
.retrieve()
.body(JsonNode.class);
if (ObjUtil.isNull(tokenNode) || !tokenNode.hasNonNull("accessToken")) {
log.error("钉钉回调接口获取accessToken失败:{}", tokenNode);
return tokenNode;
}
var accessToken = tokenNode.path("accessToken").asText();
var userInfoNode = dingRestClient.get()
.uri("/v1.0/contact/users/me")
.header("x-acs-dingtalk-access-token", accessToken)
.retrieve()
.onStatus(httpStatusCode -> !httpStatusCode.is2xxSuccessful(), (request, response) -> {
throw new RuntimeException("钉钉回调接口获取unionid失败:" + response.getBody());
})
.body(JsonNode.class);
var unionId = userInfoNode.path("unionId").asText();
var useridNode = oDingRestClient.post()
.uri("/topapi/user/getbyunionid?access_token={1}", getToken())
.body(JsonUtil.createObj().put("unionid", unionId).toString())
.retrieve()
.body(JsonNode.class);
if (ObjUtil.isNull(useridNode) || !useridNode.hasNonNull("result")) {
log.error("钉钉回调接口获取userid失败:{}", useridNode);
return useridNode;
}
String userid = useridNode.path("result").path("userid").asText();
User user = userService.lambdaQuery()
.select(User::getId, User::getUserid, User::getUsername, User::getPhone, User::getStatus, User::getEmployeeStatus)
.eq(User::getUserid, userid).one();
UserVO userVO = converter.convert(user, UserVO.class);
// 禁用用户或离职用户禁止登录系统
if (userVO.getStatus() == 1 || userVO.getEmployeeStatus() == 5) {
return "用户已禁用禁止登录系统,请联系管理员!";
}
Long id = userVO.getId();
setRolesAndPerms(id, userVO);
if (CollUtil.isEmpty(userVO.getRoleVOList())) {
return "用户未分配角色,请联系管理员!";
}
StpUtil.login(id);
String token = StpUtil.getTokenValue();
userVO.setToken(token);
StpUtil.getTokenSession().set("curLoginUser", userVO);
return userVO;
} else if (StrUtil.equals(target, "inside")) {
var userInfoNode = oDingRestClient.post()
.uri(buildSignUrl())
.contentType(MediaType.APPLICATION_JSON)
.body(JsonUtil.createObj().put("tmp_auth_code", dto.getCode()).toString())
.retrieve()
.body(JsonNode.class);
if (ObjUtil.isNull(userInfoNode) || !userInfoNode.hasNonNull("user_info")) {
log.error("钉钉回调接口获取unionid失败:{}", userInfoNode);
return userInfoNode;
}
var unionId = userInfoNode.path("user_info").path("unionid").asText();
var useridNode = oDingRestClient.post()
.uri("/topapi/user/getbyunionid?access_token={1}", getToken())
.contentType(MediaType.APPLICATION_JSON)
.body(JsonUtil.createObj().put("unionid", unionId).toString())
.retrieve()
.body(JsonNode.class);
if (ObjUtil.isNull(useridNode) || !useridNode.hasNonNull("result")) {
log.error("钉钉回调接口获取userid失败:{}", useridNode);
return useridNode;
}
var userid = useridNode.path("result").path("userid").asText();
User user = userService.lambdaQuery().select(User::getId, User::getUserid, User::getUsername, User::getPhone, User::getStatus).eq(User::getUserid, userid).one();
UserVO userVO = converter.convert(user, UserVO.class);
Long id = userVO.getId();
setRolesAndPerms(id, userVO);
if (CollUtil.isEmpty(userVO.getRoleVOList())) {
return "用户未分配角色,请联系管理员!";
}
StpUtil.login(id);
String token = StpUtil.getTokenValue();
userVO.setToken(token);
StpUtil.getTokenSession().set("curLoginUser", userVO);
try {
if (ArrayUtil.isAllNotEmpty(dto.getStoreId(), dto.getTaskId())) {
res.sendRedirect("https://yunwei.vionyun.com:8443/wap/workflow-process?token=" + token + "&storeId=" + dto.getStoreId() + "&taskId=" + dto.getTaskId());
} else if (ObjUtil.isNotEmpty(dto.getTaskTempId())) {
res.sendRedirect("https://yunwei.vionyun.com:8443/wap/workflow-assign?token=" + token + "&id=" + dto.getTaskTempId());
} else if (ObjUtil.isNotEmpty(dto.getUserId())) {
res.sendRedirect("https://yunwei.vionyun.com:8443/wap/workflow-list?token=" + token + "&activeUser=" + dto.getUserId());
} else if (ObjUtil.isNotEmpty(dto.getDeliveryId())) {
res.sendRedirect("https://yunwei.vionyun.com:8443/wap/delivery-invoice?token=" + token + "&id=" + dto.getDeliveryId());
} else if (ObjUtil.isNotEmpty(dto.getTaskUuid())) {
res.sendRedirect("https://yunwei.vionyun.com:8443/wap/workflow-process-view?token=" + token + "&taskUuid=" + dto.getTaskUuid());
}
} catch (IOException e) {
log.error("钉钉回调接口重定向失败!", e);
return "钉钉回调接口重定向失败,请联系相关人员";
}
return "success";
}
return "钉钉回调异常,请联系相关人员";
}
/**
* 钉钉工作台应用获取应用程序token
*
* @param authCode 授权码
* @return java.lang.Object
*/
public Object getPlatformToken(String authCode) {
var accessTokenNode = oDingRestClient.get()
.uri("/gettoken?appkey={appKey}&appsecret={appSecret}", appKey, appSecret)
.retrieve()
.body(JsonNode.class);
if (ObjUtil.isNull(accessTokenNode) || !accessTokenNode.hasNonNull("access_token")) {
log.error("获取钉钉access_token失败:{}", accessTokenNode);
return "获取钉钉access_token失败";
}
var accessToken = accessTokenNode.path("access_token").asText();
var userInfoNode = oDingRestClient.post()
.uri("/topapi/v2/user/getuserinfo?access_token={accessToken}", accessToken)
.contentType(MediaType.APPLICATION_JSON)
.body(JsonUtil.createObj().put("code", authCode).toString())
.retrieve()
.body(JsonNode.class);
if (ObjUtil.isNull(userInfoNode) || !StrUtil.equalsIgnoreCase(userInfoNode.path("errmsg").asText(), "ok")) {
log.error("获取钉钉用户信息失败:{}", userInfoNode);
return "获取钉钉用户信息失败";
}
var userid = userInfoNode.path("result").path("userid").asText();
User user = userService.lambdaQuery()
.select(User::getId, User::getUserid, User::getUsername, User::getPhone, User::getStatus, User::getEmployeeStatus)
.eq(User::getUserid, userid).one();
if (ObjUtil.isNull(user)) {
return "该用户不存在,请联系管理员!";
}
UserVO userVO = converter.convert(user, UserVO.class);
// 禁用用户或离职用户禁止登录系统
if (userVO.getStatus() == 1 || userVO.getEmployeeStatus() == 5) {
return "用户已禁用禁止登录系统,请联系管理员!";
}
Long id = userVO.getId();
setRolesAndPerms(id, userVO);
if (CollUtil.isEmpty(userVO.getRoleVOList())) {
return "用户未分配角色,请联系管理员!";
}
StpUtil.login(id);
String token = StpUtil.getTokenValue();
userVO.setToken(token);
StpUtil.getTokenSession().set("curLoginUser", userVO);
return userVO;
}
private void setRolesAndPerms(Long id, UserVO userVO) {
List<RUserRole> userRoleList = userRoleService.lambdaQuery().eq(RUserRole::getUserId, id).list();
List<RRoleResource> roleResourceList = Opt.ofEmptyAble(userRoleList)
.map(urList -> urList.stream().map(RUserRole::getRoleId).collect(Collectors.toList()))
.map(roleIdList -> {
// 获取用户关联的角色
List<Role> roles = roleService.listByIds(roleIdList);
List<RoleVO> roleVOS = converter.convert(roles, RoleVO.class);
userVO.setRoleVOList(roleVOS);
return roleResourceService.lambdaQuery().select(RRoleResource::getResourceId).in(RRoleResource::getRoleId, roleIdList).list();
}).orElse(ListUtil.empty());
// 获取角色关联的资源
Opt.ofEmptyAble(roleResourceList)
.map(rrList -> rrList.stream().map(RRoleResource::getResourceId).collect(Collectors.toList()))
.ifPresent(resourceIdList -> {
List<Resource> resourceList = resourceService.listByIds(resourceIdList);
userVO.setResourceList(resourceList);
});
}
/**
* 构建获取用户信息url
*/
String buildSignUrl() {
String appSecret = "Ul5UTZqIost_kEAdfZXidvLoZhzvraYurm_g7PCHg-IrDMLHT7mdSgRS1iCHrDPt";
String timestamp = String.valueOf(System.currentTimeMillis());
HMac hMac = SecureUtil.hmacSha256(appSecret);
byte[] signBytes = hMac.digest(timestamp);
String sign = Base64.encode(signBytes);
String encode = URLEncoder.encode(sign, StandardCharsets.UTF_8);
String encodeSign = encode.replace("+", "%20").replace("*", "%2A").replace("~", "%7E").replace("/", "%2F");
return StrUtil.format("/sns/getuserinfo_bycode?accessKey=dingkrzwks0jpi2di3uo×tamp={}&signature={}", timestamp, encodeSign);
}
public String robotPush(String accessToken, String body) {
var res = oDingRestClient.post()
.uri("/robot/send?access_token={accessToken}", accessToken)
.contentType(MediaType.APPLICATION_JSON)
.body(body)
.retrieve()
.body(String.class);
log.info("钉钉机器人消息推送:{}", res);
return res;
}
}