WorkWechatMediaManager.java
16 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
package cn.com.glsx.wechatbuild.manager;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.scrm.wechat.dto.workwechat.media.response.GetWorkWechatMediaResponseDTO;
import cn.com.glsx.scrm.wechat.enums.WorkWechatMediaTypeEnum;
import cn.com.glsx.wechatbuild.Constants.oa.WorkWechatMediaConstants;
import cn.com.glsx.wechatbuild.config.WechatApiUrlConfig;
import cn.com.glsx.wechatbuild.model.WechatErrorEnum;
import cn.com.glsx.wechatbuild.model.request.oa.*;
import cn.com.glsx.wechatbuild.model.response.oa.*;
import cn.com.glsx.wechatbuild.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.oreframework.util.json.JacksonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.Objects;
import java.util.UUID;
/**
* @author chizw
* @version ver.1.0.0
* @Description
* @create 2025/2/13 16:32
*/
@Component
@Slf4j
public class WorkWechatMediaManager {
@Autowired
private TokenManager tokenManager;
@Autowired
private FileUploadService fileUploadService;
private static final int BUFFER_SIZE = 1024 * 1024;
/**
* @Description 上传临时素材
* @author chizw
* @create 2025/2/17 16:10
* @version ver.1.0.0
*/
public UploadWorkWechatMediaResponseDTO uploadMedia(UploadWorkWechatMediaRequestDTO request) {
try {
String url = WechatApiUrlConfig.getApi(WorkWechatMediaConstants.MEDIA_UPLOAD_PATH,
tokenManager.getAccessToken(request), request.getMediaType().getValue());
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
File file = null;
long l = System.currentTimeMillis();
if (WorkWechatMediaTypeEnum.FILE.equals(request.getMediaType())) {
// file = byteArrayToFileNew(request.getData(), request.getFileName().substring(request.getFileName().indexOf("-") + 1));
file = streamToFile(request.getData(), request.getFileName().substring(request.getFileName().indexOf("-") + 1));
}else {
file = bytesToFile(request.getData(), request.getFileName().substring(request.getFileName().indexOf(".") + 1));
}
log.info("文件转换处理时长:{}", System.currentTimeMillis() - l);
FileSystemResource fileSystemResource = new FileSystemResource(file);
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("file", fileSystemResource);
form.add("filename", request.getFileName());
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
log.info("work wechat uploadMedia request url:{},files:{}", url, files);
String response = restTemplate.postForObject(url, files, String.class);
log.info("work wechat uploadMedia response:{}", response);
return JacksonUtils.jsonCastBean(response, UploadWorkWechatMediaResponseDTO.class);
} catch (RpcServiceException e) {
throw new RpcServiceException(e.getErrId(), e.getMessage());
} catch (Exception e) {
log.error("work wechat uploadMedia error:{}", e.getMessage(), e);
throw new RpcServiceException(WechatErrorEnum.SERVER_ERROR, e.getMessage());
}
}
/**
* 获取附件地址(文件oss地址)
*
* @param request
* @return
*/
public GetWorkWechatMediaResponseDTO getMediaUrl(cn.com.glsx.scrm.wechat.dto.workwechat.media.request.GetWorkWechatMediaRequestDTO request){
GetWorkWechatMediaRequestDTO qwFileDataRequest = new GetWorkWechatMediaRequestDTO();
BeanUtils.copyProperties(request, qwFileDataRequest);
GetWorkWechatMediaResponseDTO media = this.getMedia(qwFileDataRequest);
if (Objects.isNull(media) || !media.isSuccess()) {
log.error("获取附件mediaId:{} 异常", qwFileDataRequest.getMediaId());
throw new RpcServiceException(cn.com.glsx.scrm.wechat.enums.WechatErrorEnum.GET_WORK_WECHAT_MEDIA_FAILED, "获取附件失败 mediaId:" + qwFileDataRequest.getMediaId());
}
String fileSizeStr = cn.com.glsx.wechatbuild.util.FileUtils.formatFileSize(media.getFileData());
media.setFileSizeStr(fileSizeStr);
String fileUrl = uploadMediaToOSS(media, request);
media.setFileUrl(fileUrl);
media.setFileData(null);
return media;
}
/**
* 上传附件到oss
*
* @param media
* @param request
* @return
*/
public String uploadMediaToOSS(GetWorkWechatMediaResponseDTO media, cn.com.glsx.scrm.wechat.dto.workwechat.media.request.GetWorkWechatMediaRequestDTO request) {
String fileName = media.getFileName();
byte[] fileData = media.getFileData();
InputStream inputStream = new ByteArrayInputStream(fileData);
String objectName = UUID.randomUUID().toString() + "_" + fileName;
String objectNameCustom = request.getObjectName();
if (StringUtils.isNotBlank(objectNameCustom)) {
objectName = objectNameCustom;
}
return fileUploadService.uploadFileInputStreamToOss(inputStream, objectName, request.getEndpoint(), request.getBucketName(), request.getAccessKeyId(), request.getAccessKeySecret());
}
public GetWorkWechatMediaResponseDTO getMedia(GetWorkWechatMediaRequestDTO request){
try{
String url = WechatApiUrlConfig.getApi(WorkWechatMediaConstants.MEDIA_GET_PATH,
tokenManager.getAccessToken(request), request.getMediaId());
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
log.info("get media url:{}", url);
ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
byte[] body = entity.getBody();
log.info("get media response:{}", entity);
if(HttpStatus.OK.equals(entity.getStatusCode()) && !entity.getHeaders().containsKey("error-code")){
GetWorkWechatMediaResponseDTO response = new GetWorkWechatMediaResponseDTO();
response.setFileData(body);
String contentDispositionHeader = entity.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
log.info("contentDispositionHeader:{}", contentDispositionHeader);
String fileName = extractFileName(contentDispositionHeader);
log.info("fileName:{}", fileName);
response.setFileName(fileName);
response.setFileSize(entity.getHeaders().getContentLength());
response.setMediaType(WorkWechatMediaTypeEnum.get(entity.getHeaders().getContentType().getType()));
return response;
}else{
return JacksonUtils.jsonCastBean(new String(body), GetWorkWechatMediaResponseDTO.class);
}
}catch(Exception e){
log.error("get media error:{}", e.getMessage(), e);
throw new RpcServiceException(cn.com.glsx.scrm.wechat.enums.WechatErrorEnum.UPLOAD_WORK_WECHAT_MEDIA_FAILED, e);
}
}
private String extractFileName(String contentDispositionHeader) {
if (StringUtils.isBlank(contentDispositionHeader)) return null;
String contentDispositionField = null;
String[] split = contentDispositionHeader.split(";");
for (String field : split) {
if (field.contains("filename*=")) {
contentDispositionField = field.trim();
}
}
if (StringUtils.isBlank(contentDispositionField)) {
for (String field : split) {
if (field.contains("filename=")) {
contentDispositionField = field.trim();
}
}
}
if (StringUtils.isBlank(contentDispositionField)) return null;
try {
// 优先 filename*= 形式
if (contentDispositionField.contains("filename*=")) {
String encoded = contentDispositionField.split("filename\\*=")[1].trim();
if (encoded.contains("''")) {
encoded = encoded.substring(encoded.indexOf("''") + 2);
return URLDecoder.decode(encoded, StandardCharsets.UTF_8.name());
}
} else if (contentDispositionField.contains("filename=")) {
String filename = contentDispositionField.split("filename=")[1].trim();
return filename.replaceAll("\"", "");
}
} catch (Exception e) {
log.error("extractFileName error:{}", e.getMessage(), e);
}
return null;
}
/**
* 按文件名生成文件(后期如果企微支持会话中展示自定义fileName时候,可不用这个方法)
* @param bytes
* @param fileName
* @return
* @throws IOException
*/
public static File byteArrayToFile(byte[] bytes, String fileName) throws IOException {
File tempFile = Files.createTempDirectory("tempFile").toFile();
String filePath = tempFile.getPath() + "/" + UUID.randomUUID().toString();
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
file = new File(filePath + "/" + fileName);
//虚拟机结束后删除临时文件
file.deleteOnExit();
if (!file.getParentFile().exists()){
//文件夹不存在 生成
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
private File createTmpFile(InputStream inputStream, String name, String ext, File tmpDirFile) throws IOException {
File resultFile = File.createTempFile(name, '.' + ext, tmpDirFile);
resultFile.deleteOnExit();
FileUtils.copyInputStreamToFile(inputStream, resultFile);
return resultFile;
}
private File bytesToFile(byte[] bytes, String fileType) throws IOException {
return createTmpFile(new ByteArrayInputStream(bytes),
UUID.randomUUID().toString(),
fileType,
Files.createTempDirectory("tempFile").toFile());
}
public static void main(String[] args) throws IOException {
String filePath = "D:\\360MoveData\\Users\\chizw\\Desktop\\【业财一体化】V1.3.0-待付清单(付款单)&OA审批节点&退款回单&账户余额&到账伴侣通知功能-0610-PRD.docx";
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
byteArrayToFile(bytes, "test.txt");
long l = System.currentTimeMillis();
File file = byteArrayToFile(bytes, "test.txt");
long l1 = System.currentTimeMillis();
System.out.println(l1 - l);
File file2 = byteArrayToFileNew(bytes, "test.txt");
long l2 = System.currentTimeMillis();
System.out.println(l2 - l1);
File file3 = streamToFile(bytes, "test.txt");
System.out.println(System.currentTimeMillis() - l2);
}
public static File byteArrayToFileNew(byte[] bytes, String fileName) throws IOException {
if (fileName == null || fileName.trim().isEmpty()) {
throw new IllegalArgumentException("File name cannot be null or empty.");
}
Path tempDirPath = Files.createTempDirectory("tempFile");
File tempDir = tempDirPath.toFile();
File uniqueDir = new File(tempDir, "dir-" + UUID.randomUUID());
if (!uniqueDir.exists() && !uniqueDir.mkdirs()) {
throw new IOException("Failed to create directory: " + uniqueDir.getAbsolutePath());
}
if (!uniqueDir.exists() || !uniqueDir.isDirectory() || !uniqueDir.canWrite()) {
throw new IOException("Unique directory is not accessible for writing.");
}
File file = new File(uniqueDir, fileName);
try {
Files.write(file.toPath(), bytes);
} catch (IOException e) {
boolean deleted = file.delete();
if (!deleted) {
log.warn("Failed to delete corrupted file: {}", file.getAbsolutePath());
}
throw e;
}
file.deleteOnExit();
return file;
}
public static File streamToFile(byte[] bytes, String fileName) {
try (InputStream inputStream = new ByteArrayInputStream(bytes)){
if (fileName == null || fileName.trim().isEmpty()) {
throw new IllegalArgumentException("File name cannot be null or empty.");
}
Path tempDirPath = Files.createTempDirectory("tempFile");
File tempDir = tempDirPath.toFile();
File uniqueDir = new File(tempDir, "dir-" + UUID.randomUUID());
if (!uniqueDir.exists() && !uniqueDir.mkdirs()) {
deleteDirectoryRecursively(tempDir);
throw new IOException("Failed to create directory: " + uniqueDir.getAbsolutePath());
}
File file = new File(uniqueDir, fileName);
try (OutputStream fos = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
boolean deleted = file.delete();
if (!deleted) {
log.warn("Failed to delete corrupted file: {}", file.getAbsolutePath());
}
deleteDirectoryRecursively(tempDir);
throw e;
}
addShutdownHookToDelete(tempDir);
return file;
} catch (Exception e) {
log.error("Failed to create file: {}", fileName, e);
throw new RuntimeException(e);
}
}
/**
* 添加 JVM 钩子,在程序退出时尝试删除临时目录
*/
private static void addShutdownHookToDelete(File dir) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
deleteDirectoryRecursively(dir);
} catch (IOException e) {
log.warn("Failed to delete temporary directory during shutdown: {}", dir.getAbsolutePath(), e);
}
}));
}
/**
* 递归删除目录及其所有内容
*/
private static void deleteDirectoryRecursively(File dir) throws IOException {
if (dir == null || !dir.exists()) return;
Files.walk(dir.toPath())
.sorted(Comparator.reverseOrder())
.forEach(path -> {
try {
Files.deleteIfExists(path);
} catch (IOException ignored) {
// 忽略删除失败的情况
}
});
}
}