DingMod.java 20.7 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
package vion.third;

import cn.dev33.satoken.stp.StpUtil;
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.dromara.hutool.json.JSONArray;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
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.vo.RoleVO;
import vion.vo.UserVO;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HlQ
 * @date 2023/11/13
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DingMod {

    @Value("${appkey:}")
    private String appKey;
    @Value("${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(() -> {
                    String res = oDingRestClient.get()
                            .uri("/gettoken?appkey=" + appKey + "&appsecret=" + appSecret)
                            .retrieve()
                            .body(String.class);
                    JSONObject jsonObj = JSONUtil.parseObj(res);
                    if (jsonObj.containsKey("access_token")) {
                        String accessToken = jsonObj.getStr("access_token");
                        redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.ACCESS_TOKEN.getVal()).set(accessToken, Duration.ofSeconds(7000));
                        return accessToken;
                    }
                    return "";
                });
    }

    /**
     * 获取钉钉员工列表
     */
    public void getDingUserList() {
        String accessToken = getToken();

        List<String> userIdList = new ArrayList<>();
        Long offset = 0L;
        boolean flag = true;
        while (flag) {
            // 2:试用期 3:正式 5:待离职 -1:无状态
            JSONObject paramJson = JSONUtil.ofObj()
                    .set("status_list", "2,3,5,-1")
                    .set("size", 50)
                    .set("offset", offset);
            var jsonObject = oDingRestClient.post()
                    .uri("/topapi/smartwork/hrm/employee/queryonjob?access_token=" + accessToken)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(paramJson.toString())
                    .retrieve()
                    .body(JSONObject.class);
            if (jsonObject.getBool("success", false)) {
                JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("data_list");
                List<String> list = jsonArray.toList(String.class);
                userIdList.addAll(list);

                Long nextCursor = jsonObject.getJSONObject("result").getLong("next_cursor");
                if (ObjUtil.isNotNull(nextCursor)) {
                    offset = nextCursor;
                } else {
                    flag = false;
                }
            }
        }

        if (CollUtil.isEmpty(userIdList)) {
            log.error("获取钉钉用户id列表为空");
            return;
        }

        List<List<String>> userIdListSplit = ListUtil.partition(userIdList, 90);
        userIdListSplit.forEach(tmpList -> {
            JSONObject paramJson = JSONUtil.ofObj()
                    .set("agentid", 2358374016L)
                    .set("userid_list", String.join(",", tmpList))
                    .set("field_filter_list", "sys00-name,sys00-mobile,sys00-mainDeptId,sys00-mainDept,sys01-employeeStatus");

            var jsonObject = oDingRestClient.post()
                    .uri("/topapi/smartwork/hrm/employee/v2/list?access_token=" + accessToken)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(paramJson.toString())
                    .retrieve()
                    .body(JSONObject.class);
            if (jsonObject.getBool("success", false)) {
                JSONArray resArr = jsonObject.getJSONArray("result");
                for (Object o : resArr) {
                    User user = new User();
                    JSONObject jsonObj = JSONUtil.parseObj(o);
                    String userid = jsonObj.getStr("userid");
                    user.setUserid(userid);

                    JSONArray dataArr = jsonObj.getJSONArray("field_data_list");
                    for (Object o1 : dataArr) {
                        JSONObject tmpObj = JSONUtil.parseObj(o1);
                        if (StrUtil.equals("sys00-name", tmpObj.getStr("field_code"))) {
                            user.setUsername(tmpObj.getJSONArray("field_value_list").getByPath("[0].value", String.class));
                        } else if (StrUtil.equals("sys00-mobile", tmpObj.getStr("field_code"))) {
                            user.setPhone(Opt.ofNullable((String) tmpObj.getJSONArray("field_value_list").getByPath("[0].value", String.class)).orElse(""));
                        } else if (StrUtil.equals("sys00-mainDeptId", tmpObj.getStr("field_code"))) {
                            user.setDeptId(tmpObj.getJSONArray("field_value_list").getByPath("[0].value", Long.class));
                        } else if (StrUtil.equals("sys01-employeeStatus", tmpObj.getStr("field_code"))) {
                            user.setEmployeeStatus(tmpObj.getJSONArray("field_value_list").getByPath("[0].value", Integer.class));
                        }
                    }
                    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 jsonObject = oDingRestClient.post()
                    .uri("/topapi/v2/department/listsub?access_token=" + accessToken)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(JSONUtil.ofObj().set("dept_id", value).toString())
                    .retrieve()
                    .body(JSONObject.class);
            if (StrUtil.equals("ok", jsonObject.getStr("errmsg"))) {
                JSONArray resArr = jsonObject.getJSONArray("result");
                if (CollUtil.isNotEmpty(resArr)) {
                    for (Object o : resArr) {
                        Dept dept = new Dept();
                        JSONObject jsonObj = JSONUtil.parseObj(o);
                        Long deptId = jsonObj.getLong("dept_id");
                        dept.setDeptId(deptId);
                        dept.setParentId(jsonObj.getLong("parent_id"));
                        dept.setDeptName(jsonObj.getStr("name"));
                        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(JSONObject msg) {
        String token = getToken();
        var res = oDingRestClient.post()
                .uri("/topapi/message/corpconversation/asyncsend_v2?access_token=" + token)
                .contentType(MediaType.APPLICATION_JSON)
                .body(msg.toString())
                .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")) {
            JSONObject jsonObject = JSONUtil.ofObj()
                    .set("clientId", appKey)
                    .set("clientSecret", appSecret)
                    .set("code", dto.getAuthCode())
                    .set("grantType", "authorization_code");
            var tokenObj = dingRestClient.post()
                    .uri("/v1.0/oauth2/userAccessToken")
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(jsonObject.toString())
                    .retrieve()
                    .body(JSONObject.class);
            if (!tokenObj.containsKey("accessToken")) {
                log.error("钉钉回调接口获取accessToken失败:{}", tokenObj);
                return tokenObj;
            }
            String accessToken = tokenObj.getStr("accessToken");
            var userInfoObj = 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(JSONObject.class);
            String unionId = userInfoObj.getStr("unionId");
            var useridObj = oDingRestClient.post()
                    .uri("/topapi/user/getbyunionid?access_token=" + getToken())
                    .body(JSONUtil.ofObj().set("unionid", unionId).toString())
                    .retrieve()
                    .body(JSONObject.class);
            if (!useridObj.containsKey("result")) {
                log.error("钉钉回调接口获取userid失败:{}", useridObj);
                return useridObj;
            }
            String userid = useridObj.getJSONObject("result").getStr("userid");
            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 userInfoObj = oDingRestClient.post()
                    .uri(buildSignUrl())
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(JSONUtil.ofObj().set("tmp_auth_code", dto.getCode()).toString())
                    .retrieve()
                    .body(JSONObject.class);
            if (!userInfoObj.containsKey("user_info")) {
                log.error("钉钉回调接口获取unionid失败:{}", userInfoObj);
                return userInfoObj;
            }
            String unionId = userInfoObj.getJSONObject("user_info").getStr("unionid");

            JSONObject useridObj = oDingRestClient.post()
                    .uri("/topapi/user/getbyunionid?access_token=" + getToken())
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(JSONUtil.ofObj().set("unionid", unionId).toString())
                    .retrieve()
                    .body(JSONObject.class);
            if (!useridObj.containsKey("result")) {
                log.error("钉钉回调接口获取userid失败:{}", useridObj);
                return useridObj;
            }
            String userid = useridObj.getJSONObject("result").getStr("userid");
            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 accessTokenStr = oDingRestClient.get()
                .uri(StrUtil.format("/gettoken?appkey={}&appsecret={}", appKey, appSecret))
                .retrieve()
                .body(String.class);
        if (!StrUtil.contains(accessTokenStr, "access_token")) {
            log.error("获取钉钉access_token失败:{}", accessTokenStr);
            return "获取钉钉access_token失败";
        }
        var accessToken = JSONUtil.parseObj(accessTokenStr).getStr("access_token");

        var userInfoStr = oDingRestClient.post()
                .uri("/topapi/v2/user/getuserinfo?access_token=" + accessToken)
                .contentType(MediaType.APPLICATION_JSON)
                .body(JSONUtil.ofObj().set("code", authCode).toString())
                .retrieve()
                .body(String.class);
        if (!StrUtil.contains(userInfoStr, "\"errmsg\":\"ok\"")) {
            log.error("获取钉钉用户信息失败:{}", userInfoStr);
            return "获取钉钉用户信息失败";
        }
        var userid = JSONUtil.parseObj(userInfoStr).getJSONObject("result").getStr("userid");
        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);
        return StrUtil.format("/sns/getuserinfo_bycode?accessKey=dingkrzwks0jpi2di3uo&timestamp={}&signature={}", timestamp, sign);
    }

    public String robotPush(String accessToken, String body) {
        var res = oDingRestClient.post()
                .uri("/robot/send?access_token=" + accessToken)
                .contentType(MediaType.APPLICATION_JSON)
                .body(body)
                .retrieve()
                .body(String.class);
        log.info("钉钉机器人消息推送:{}", res);
        return res;
    }
}