17808
2023-09-14 f4e77cdf431974fff8165e67378f1ca0fecdf4f1
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
package com.ycl.controller.dingding;
 
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.GetClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.ycl.api.CommonResult;
import com.ycl.bo.AdminUserDetails;
import com.ycl.common.dingding.DingCommon;
import com.ycl.config.DingConfig;
import com.ycl.controller.BaseController;
import com.ycl.entity.dingding.DingUserInfo;
import com.ycl.service.auth.AuthService;
import com.ycl.service.ding.BookRemarkService;
import com.ycl.service.ding.DingService;
import com.ycl.utils.ConstantPropertiesUtils;
import com.ycl.vo.AddressBookVO;
import com.ycl.vo.NewAddressBookVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import static com.ycl.common.constant.DingConst.*;
 
@RestController
@RequestMapping("/ding")
@Api(tags = "钉钉")
@Slf4j
public class DingController extends BaseController {
 
    @Autowired
    private DingCommon dingCommon;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    /**
     * DING 免登
     * 根据临时授权码和access_token获取用户信息
     *
     * @author cjx
     */
 
    @Autowired
    private AuthService authService;
 
    @Autowired
    private DingService dingService;
 
    @Autowired
    private BookRemarkService bookRemarkService;
 
    @Resource
    private ExecutableClient executableClient;
 
    @Resource
    private DingConfig dingConfig;
 
 
 
 
    @ApiOperation(value = "根据钉钉授权码获取token")
    @GetMapping("/dingLogin")
    public CommonResult<Map> dingLogin(@RequestParam String code) {
        HashMap<String, Object> map = new HashMap<>();
        //获取用户信息
        DingUserInfo dingUser = dingCommon.getDingUserInfo(code);
        //按ding登录
        String token = authService.dingLogin(dingUser);
        map.put("token", token);
        map.put("tokenHead", tokenHead);
        map.put("accountId", dingUser.getAccountId());
        return CommonResult.success(map);
    }
 
    @ApiOperation(value = "根据钉钉授权码获取jsapiToken")
    @GetMapping("/dingTicker")
    public CommonResult<Map> dingTicker() {
        String accessToken = getToken();
        String ticket = getTiker(accessToken);
        HashMap<String, Object> map = new HashMap<>();
 
        map.put("accessToken", accessToken);
 
        map.put("ticket", ticket);
        return CommonResult.success(map);
    }
 
    private String getToken() {
        //调用API
        GetClient getTokenClient = executableClient.newGetClient(GET_TOKEN);
        //设置参数
        getTokenClient.addParameter("appkey", dingConfig.getAppKey());
        getTokenClient.addParameter("appsecret", dingConfig.getAppSecret());
        String apiResult = getTokenClient.get();
        return parsingResult(apiResult);
    }
 
    private String getTiker(String accToken) {
        //调用API
        PostClient postClient = executableClient.newPostClient(GET_TIKER);
        //设置参数
        if (ObjectUtil.isNotNull(accToken)) {
            postClient.addParameter("accessToken", accToken);
            postClient.addParameter("appkey", dingConfig.getAppKey());
            postClient.addParameter("appsecret", dingConfig.getAppSecret());
            String apiResult = postClient.post();
            return parsingResult(apiResult);
        }
        return null;
    }
 
    private String parsingResult(String apiResult) {
        if (ObjectUtil.isNotNull(apiResult)) {
            JSONObject resJson = JSONObject.parseObject(apiResult);
            if (resJson.getBoolean("success")) {
                JSONObject content = resJson.getJSONObject("content");
                if (content.getBoolean("success")) {
                    JSONObject dataObj = content.getJSONObject("data");
                    String accessToken = dataObj.getString("accessToken");
                    return accessToken;
                }
            } else {
                log.error(resJson.toJSONString());
            }
        }
        return null;
    }
 
    @ApiOperation(value = "通讯录")
    @GetMapping("/addressBook")
    public CommonResult<List<AddressBookVO>> getAddressBook() {
        AdminUserDetails user = (AdminUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return CommonResult.success(dingService.getAddressBook(user.getUserId()));
    }
 
 
    @ApiOperation(value = "通讯录递归")
    @GetMapping("/addressBookById")
    public CommonResult<List<AddressBookVO>> getAddressBook(@RequestParam("id") Long id) {
        AdminUserDetails user = (AdminUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return CommonResult.success(dingService.getAddressBookByParentId(id, user.getUserId()));
    }
 
 
    @ApiOperation(value = "通讯录递归")
    @GetMapping("/getDddressBook")
    public CommonResult<NewAddressBookVO> getNewAddressBook(@RequestParam("id") Long id) {
        AdminUserDetails user = (AdminUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return CommonResult.success(dingService.getAddressBookById(id, user.getUserId()));
    }
 
 
    @ApiOperation(value = "修改通讯录备注")
    @PutMapping("/remark")
    public CommonResult updateRemark(@RequestParam("userId") Long userId, @RequestParam("remark") String remark) {
        AdminUserDetails user = (AdminUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return CommonResult.success(bookRemarkService.updateRemark(user, userId, remark));
    }
 
    private String getVideo(String MediaId,MultipartFile file) {
        CloseableHttpResponse response = null;
        //调用API
        GetClient getClient = executableClient.newGetClient(GET_VIDEO);
        String token =getToken();
        //设置参数
        try {
            if (ObjectUtil.isNotNull(MediaId)) {
            getClient.addParameter("accessToken", token);
            getClient.addParameter("mediaId", MediaId);
//            String result = getClient.get();
//            return parsingResult(result);
            response = getClient.getB();
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            File voice = new File("/Users/video/log1.xlsx");
            OutputStream fos = new FileOutputStream(voice);
            int cache = 10 * 1024;
            byte[] buffer = new byte[cache];
            int ch = 0;
                while ((ch = is.read(buffer)) != -1) {
                fos.write(buffer, 0, ch);
                }
            is.close();
            fos.flush();
            fos.close();
            }
            if (file == null) {
                return "上传视频为空";
            }
            String endpoint = ConstantPropertiesUtils.END_POINT;
            String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
            String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
            String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
 
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 获取文件的名称
            String fileName = "sczf/" + file.getOriginalFilename();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            // 调用oss的方法实现长传
            // 第一个参数 bucketName
            // 第二个参数 上传到oss的文件路径和文件名称
            ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes()), objectMetadata);
            // 关闭OSSClient。
            ossClient.shutdown();
            // 把上传的文件路径返回 (手动拼接)
            // 这里设置图片有效时间 我设置了30年
            Date expiration = new Date(System.currentTimeMillis() + (long) 946080000 * 1000);
            String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();
 
            return url;
            }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (response != null) {
                try {
                    //特别提醒:需要调用response的close方法关闭网络连接!!!
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".mp4")||FilenameExtension.equalsIgnoreCase(".mov")) {
            return "video/mp4";
        }
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }
 
 
 
}