jinlin
2024-02-20 935a19db72dadce80fdc6feeb9888233019d7b3c
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
package com.zt.life.sys.service;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.ObjectIdGenerator;
import com.zt.common.constant.Constant;
import com.zt.common.db.query.QueryFilter;
import com.zt.common.service.BaseService;
import com.zt.common.utils.CacheUtils;
import com.zt.common.utils.UUIDUtil;
import com.zt.core.oss.service.ISysOssConfigService;
import com.zt.core.oss.service.ISysOssService;
import com.zt.life.core.constant.Cache;
import com.zt.life.export.service.DownloadService;
import com.zt.life.oss.OssEncryptService;
import com.zt.life.sys.dao.SysOssConfigDao;
import com.zt.life.sys.dto.OssDto;
import com.zt.life.sys.mapstruct.OssExMapper;
import com.zt.life.sys.model.SysOssConfig;
import com.zt.life.util.ZipCipherUtil;
import com.zt.modules.oss.model.SysOss;
import com.zt.modules.oss.service.SysOssService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * SYS_OSS_CONFIG
 *
 * @author zt generator
 * @since 1.0.0 2020-08-25
 */
@Service
public class SysOssConfigService extends BaseService<SysOssConfigDao, SysOssConfig> implements ISysOssConfigService {
 
    @Autowired
    private OssExMapper ossExMapper;
    @Autowired
    private ISysOssService sysOssService;
 
    @Autowired
    private SysOssService sysOssServices;
 
    @Value("${zt.oss.local-path}")
    private String localPath;
 
    @Value("${data.key}")
    private String key;
 
    @Autowired
    private OssEncryptService ossEncryptService;
 
    /**
     * 分页查询
     *
     * @param queryFilter
     * @return
     */
    public List<SysOssConfig> page(QueryFilter queryFilter) {
        return queryFilter.getPageList(baseDao.getList(queryFilter.getQueryParams()));
    }
 
    @Override
    @CacheEvict(value = Cache.CONFIG, allEntries = true)
    public void insert(SysOssConfig entity) {
        super.insert(entity);
    }
 
    @Override
    @CacheEvict(value = Cache.CONFIG, allEntries = true)
    public void update(SysOssConfig entity) {
        super.update(entity);
    }
 
    /**
     * 删除
     *
     * @param ids
     */
    @CacheEvict(value = Cache.CONFIG, allEntries = true)
    public void delete(Long[] ids) {
        super.deleteLogic(ids);
    }
 
    public List<OssDto> getOssConfig() {
        // 这里手动缓存,不然在当前方法内调用缓存无效
        List<OssDto> all = null;//(List<OssDto>) CacheUtils.get(Cache.CONFIG, "all");
        if (all == null) {
            all = new ArrayList<>();
            List<SysOssConfig> configs = baseDao.selectList(new QueryWrapper<SysOssConfig>()
                    .eq(Constant.TableColumn.IS_DELETE, Constant.Bool.NO).lambda().orderByAsc(SysOssConfig::getSort));
            if (configs.size() > 0) {
                Map<String, OssDto> busiMap = new HashMap<>();
                Map<String, OssDto.OssFieldGroupDto> groupMap = new HashMap<>();
 
                for (SysOssConfig config : configs) {
                    OssDto dto = busiMap.get(config.getBusiType());
                    if (dto == null) {
                        dto = new OssDto(config.getBusiType(), config.getBusiTypeName());
                        busiMap.put(config.getBusiType(), dto);
                        all.add(dto);
                    }
 
                    String group = config.getBusiFieldGroup();
                    OssDto.OssFieldGroupDto groupDto = groupMap.get(group);
                    if (groupDto == null) {
                        groupDto = new OssDto.OssFieldGroupDto(group);
                        dto.getGroups().add(groupDto);
                        groupMap.put(group, groupDto);
                    }
                    groupDto.getFields().add(ossExMapper.toDto(config));
                }
            }
            CacheUtils.put(Cache.CONFIG, "all", all);
        }
        return all.stream().map(ossDto -> {
            try {
                return ossDto.clone();
            } catch (CloneNotSupportedException e) {
            }
            return null;
        }).collect(Collectors.toList());
    }
 
    /**
     * 查询附件
     *
     * @param busiId
     * @param busiType
     * @return
     */
    public OssDto getOssByBusiType(Long busiId, String busiType) {
        List<OssDto> dtos = this.getOssConfig().stream().filter(config -> config.getBusiType().equals(busiType))
                .collect(Collectors.toList());
 
        if (dtos.size() > 0) {
            OssDto dto = dtos.get(0);
            if (busiId != null && busiId > 0) {
                for (OssDto.OssFieldGroupDto groupDto : dto.getGroups()) {
                    for (OssDto.OssFieldDto fieldDto : groupDto.getFields()) {
                        fieldDto.getFiles().addAll(sysOssService.getOsses(busiId, busiType, fieldDto.getBusiField()));
                    }
                }
            }
            return dto;
        }
        return null;
    }
 
 
    /**
     * 修改附件http
     *
     * @param busiId
     * @param dto
     */
    public void updateOss(Long busiId, OssDto dto) {
        if (dto != null) {
            for (OssDto.OssFieldGroupDto groupDto : dto.getGroups()) {
                for (OssDto.OssFieldDto fieldDto : groupDto.getFields()) {
                    if (CollectionUtil.isNotEmpty(fieldDto.getFiles())) {
                        List<Long> ids = fieldDto.getFiles().stream().map(file -> file.getId())
                                .collect(Collectors.toList());
                        sysOssService.updateBusiInfo(busiId, dto.getBusiType(), dto.getBusiTypeName(),
                                fieldDto.getBusiField(), fieldDto.getBusiFieldName(), ids, true);
                    } else {// 没有附件了
                        sysOssService.deleteBusiInfo(busiId, dto.getBusiType(), fieldDto.getBusiField());
                    }
                }
            }
        }
    }
 
    public void updateOssBatch(String[] bizIds, OssDto dto) {
        if (dto != null) {
        for (OssDto.OssFieldGroupDto groupDto : dto.getGroups()) {
            for (OssDto.OssFieldDto fieldDto : groupDto.getFields()) {
                if (CollectionUtil.isNotEmpty(fieldDto.getFiles())) {
                    List<Long> ids = fieldDto.getFiles().stream().map(file -> file.getId())
                            .collect(Collectors.toList());
                    SysOss sysOss = sysOssServices.get(ids.get(0));
                    for (String bizId : bizIds) {
                        Long uuId = UUIDUtil.generateId();
                        sysOss.setId(uuId);
                        sysOssServices.insert(sysOss);
                        List<Long> ids2 = new ArrayList<>();
                        ids2.add(uuId);
                        sysOssServices.updateBusiInfo(Long.parseLong(bizId), dto.getBusiType(), dto.getBusiTypeName(),
                                fieldDto.getBusiField(), fieldDto.getBusiFieldName(), ids2, true);
                    }
 
                } else {// 没有附件了
                    //sysOssService.deleteBusiInfo(busiId, dto.getBusiType(), fieldDto.getBusiField());
                }
            }
        }
    }
}
 
    public void updateOssBatch2(String bizIds, OssDto dto) {
        if (dto != null) {
            SysOss sysOss = null;
            for (OssDto.OssFieldGroupDto groupDto : dto.getGroups()) {
                for (OssDto.OssFieldDto fieldDto : groupDto.getFields()) {
                    if (CollectionUtil.isNotEmpty(fieldDto.getFiles())) {
                        List<Long> ids = fieldDto.getFiles().stream().map(file -> file.getId())
                                .collect(Collectors.toList());
                        sysOss = sysOssServices.get(ids.get(0));
                    }
                }
            }
            if (sysOss != null) {
                for (String bizId : bizIds.split(",")) {
                    sysOss.setBusiId(Convert.toLong(bizId));
                    Long uuId = UUIDUtil.generateId();
                    sysOss.setId(uuId);
                    sysOssServices.insert(sysOss);
                }
            }
        }
    }
    /**
     * 批量上传
     *
     * @param dto
     */
    public void uploadingOss(List<Long> busiIdList, OssDto dto) {
        List<SysOss> all = new ArrayList<>();
        String busiType = "";
        String busiTypeName = "";
        String busiField = "";
        String busiFieldName = "";
        for (OssDto.OssFieldGroupDto groupDto : dto.getGroups()) {
            for (OssDto.OssFieldDto fieldDto : groupDto.getFields()) {
                if (CollectionUtil.isNotEmpty(fieldDto.getFiles())) {
                    List<Long> ids = fieldDto.getFiles().stream().map(file -> file.getId()).collect(Collectors.toList());
                    if (ids.size() > 0) {
                        all = sysOssServices.getBySysOss(ids);
                    }
                }
            }
        }
 
        for (Long busiId : busiIdList) {
            for (OssDto.OssFieldGroupDto groupDto : dto.getGroups()) {
                for (OssDto.OssFieldDto fieldDto : groupDto.getFields()) {
                    if (CollectionUtil.isNotEmpty(fieldDto.getFiles())) {
                        List<Long> ids = fieldDto.getFiles().stream().map(file -> file.getId()).collect(Collectors.toList());
                        busiType = dto.getBusiType();
                        busiTypeName = dto.getBusiTypeName();
                        busiField = fieldDto.getBusiField();
                        busiFieldName = fieldDto.getBusiFieldName();
                        sysOssService.updateBusiInfo(busiId, busiType, busiTypeName, busiField, busiFieldName, ids, false);
                    }
//                    else {// 没有附件了
//                        sysOssService.deleteBusiInfo(busiId, dto.getBusiType(), fieldDto.getBusiField());
//                    }
                }
            }
        }
        List<com.zt.core.oss.dto.OssDto> ossDtoList = new ArrayList<>();
        if (all != null && all.size() > 0 && busiIdList.size() > 1) {
            for (int i = 0; i < busiIdList.size() - 1; i++) {
                for (int j = 0; j < all.size(); j++) {
                    Long uuid = generateId();
                    SysOss sysOss = all.get(j);
                    sysOss.setId(uuid);
                    String urlOssIdStr = sysOss.getUrl().substring(sysOss.getUrl().indexOf("_zt_oss_id="));
                    String newUrlOssIdStr = "_zt_oss_id=" + uuid;
                    sysOss.setUrl(sysOss.getUrl().replace(urlOssIdStr, newUrlOssIdStr));
                    sysOss.setBusiId(busiIdList.get(i + 1));
                    sysOss.setBusiType(busiType);
                    sysOss.setBusiTypeName(busiTypeName);
                    sysOss.setBusiField(busiField);
                    sysOss.setBusiFieldName(busiFieldName);
                    sysOssServices.insert(sysOss);
                    ossDtoList.add(JSONObject.toJavaObject(JSONObject.parseObject(JSONObject.toJSONString(sysOss)), com.zt.core.oss.dto.OssDto.class));
                }
            }
        }
    }
 
 
    public static Long generateId() {
        String code = String.valueOf(new Date().getTime());
        float fl = new Random().nextFloat();
        fl = fl < 0.1 ? (float) (fl + 0.1) : fl;
        Integer ran = Integer.parseInt((fl * 1000000 + "").split("\\.")[0]);
        char[] temp = code.substring(code.length() - 6, code.length()).toCharArray();
        for (char c : temp) {
            int i = new Random().nextInt(6);
            ran += Integer.parseInt(((Integer.parseInt(c + "") * Math.pow(10, i)) + "").split("\\.")[0]);
        }
        code = code.substring(0, code.length() - 6) + ran;
        String buwei = "";
        int codel = code.length();
        if (codel < 17) {
            double f = Math.pow(10, 17 - codel);
            fl = new Random().nextFloat();
            fl = fl < 0.1 ? (float) (fl + 0.1) : fl;
            String a1 = fl * f + "";
            buwei = a1.split("\\.")[0];
        }
        Random runnable = new Random();
        int num = runnable.nextInt(90) + 10;
        return Long.parseLong(code + buwei + num);
    }
 
    public Integer existsSameTypeAndFiledGroup(String busiType, String busiFieldGroup, Long id) {
        return baseDao.existsSameTypeAndFiledGroup(busiType, busiFieldGroup, id);
    }
 
    public Integer existsSameGroupById(String busiFiledGroup, Long id) {
        return baseDao.existsSameGroupById(busiFiledGroup, id);
    }
 
    public SysOssConfig getByBusiTypeAndBusiFiledGroup(String busiType, String busiFiledGroup) {
        return baseDao.selectOne(new QueryWrapper<SysOssConfig>().eq("busi_type", busiType).eq("busi_field_group", busiFiledGroup));
    }
 
    public void deleteByBusiTypes(Long[] busiTypes) {
        for (Long busiType : busiTypes) {
           baseDao.updateByBusiType(String.valueOf(busiType));
        }
    }
 
    public List<SysOssConfig> selectList(String busiType) {
        return baseDao.selectList(new QueryWrapper<SysOssConfig>().eq(Constant.TableColumn.IS_DELETE, Constant.Bool.NO).lambda()
                .eq(SysOssConfig::getBusiType, busiType));
    }
 
    public void downloadFilesByosList(HttpServletRequest request, HttpServletResponse response, List<SysOss> list, String projectName) {
        try {
            String uuid = UUIDUtil.getUUID();
            String remoteFileFullPath = Paths.get(localPath, "temp", uuid).toString();
            Files.createDirectories(Paths.get(remoteFileFullPath));
 
            for (SysOss so : list) {
                try {
                    String localFileFullPath = Paths.get(localPath, so.getPath()).toString();
                    File localFile = new File(localFileFullPath);
                    if (localFile.exists()) {
                        try (InputStream in = ossEncryptService.decrypt(localFile);
                             BufferedInputStream bis = new BufferedInputStream(in);
                             BufferedOutputStream bos = new BufferedOutputStream(
                                     new FileOutputStream(remoteFileFullPath + File.separator + so.getName()))) {
 
                            byte[] buffer = new byte[1024];
                            int len;
                            while ((len = bis.read(buffer)) != -1) {
                                bos.write(buffer, 0, len);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace(); // 或者记录日志
                }
            }
 
            String fileNameZip = Paths.get(localPath, "temp", uuid + ".zip").toString();
            new ZipCipherUtil().encryptZip(remoteFileFullPath, fileNameZip, key);
 
            File zipFile = new File(fileNameZip);
            response.reset();
            response.setContentLength((int) zipFile.length());
            response.setContentType("application/octet-stream;charset=UTF-8");
            String encodedFilename = DownloadService.getNameEncoder(request, projectName + ".zip");
            response.addHeader("Content-Disposition", "attachment;filename=" + encodedFilename);
 
            try (FileInputStream fileInputStream = new FileInputStream(zipFile);
                 ServletOutputStream outputStream = response.getOutputStream()) {
 
                byte[] buffers = new byte[1024];
                int length;
                while ((length = fileInputStream.read(buffers)) > 0) {
                    outputStream.write(buffers, 0, length);
                }
 
            } catch (IOException e) {
                e.printStackTrace(); // 或者记录日志
            } finally {
                FileUtils.deleteQuietly(new File(remoteFileFullPath));
                FileUtils.deleteQuietly(new File(fileNameZip));// 删除临时文件夹及其内容
            }
        } catch (Exception ex) {
            ex.printStackTrace(); // 或者记录日志
        }
    }
}