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 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 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 getOssConfig() { // 这里手动缓存,不然在当前方法内调用缓存无效 List all = null;//(List) CacheUtils.get(Cache.CONFIG, "all"); if (all == null) { all = new ArrayList<>(); List configs = baseDao.selectList(new QueryWrapper() .eq(Constant.TableColumn.IS_DELETE, Constant.Bool.NO).lambda().orderByAsc(SysOssConfig::getSort)); if (configs.size() > 0) { Map busiMap = new HashMap<>(); Map 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 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 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 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 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 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 busiIdList, OssDto dto) { List 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 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 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 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().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 selectList(String busiType) { return baseDao.selectList(new QueryWrapper().eq(Constant.TableColumn.IS_DELETE, Constant.Bool.NO).lambda() .eq(SysOssConfig::getBusiType, busiType)); } public void downloadFilesByosList(HttpServletRequest request, HttpServletResponse response, List 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(); // 或者记录日志 } } }