Jelajahi Sumber

试玩模块创建和开发

zhaoxian 4 tahun lalu
induk
melakukan
ad177b2dba

+ 3 - 0
jeecg-boot-module-system/src/main/resources/application-dev.yml

@@ -226,3 +226,6 @@ oss:
     replace-old-value: oss-cn-beijing
     download: D:\mnt\file\video
 
+zip:
+  local:
+    download-path: /data/unzip/

+ 4 - 0
jeecg-boot-module-system/src/main/resources/application-prod.yml

@@ -196,3 +196,7 @@ oss:
     replace-value: oss-cn-beijing
     replace-old-value: oss-cn-beijing
     download: /data/file/video/
+
+zip:
+  local:
+    download-path: /data/unzip/

+ 4 - 0
jeecg-boot-module-system/src/main/resources/application-prod2.yml

@@ -188,3 +188,7 @@ oss:
     replace-value: oss-cn-beijing
     replace-old-value: oss-cn-beijing
     download: /data/file/video/
+
+zip:
+  local:
+    download-path: /data/unzip/

+ 6 - 2
jeecg-boot-module-system/src/main/resources/application-test.yml

@@ -125,8 +125,8 @@ mybatis-plus:
       id-type: 4
       # 默认数据库表下划线命名
       table-underline: true
-#  configuration:
-#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
+  #  configuration:
+  #    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
   #  map-underscore-to-camel-case: false
   #分页pageHelper
 pagehelper:
@@ -187,3 +187,7 @@ oss:
     replace-value: oss-cn-beijing
     replace-old-value: oss-cn-beijing
     download: /mnt/file/video/
+
+zip:
+  local:
+    download-path: /data/unzip/

+ 35 - 18
jeecg-boot-module-system/src/test/java/org/jeecg/SampleTest.java

@@ -7,11 +7,16 @@ import cn.com.ctop.common.module.entity.BindAccountLogin;
 import cn.com.ctop.common.module.entity.CtopOauthToken;
 import cn.com.ctop.common.module.entity.UserAllocation;
 import cn.com.ctop.common.module.message.handle.impl.EmailSendMsgHandle;
-import cn.com.ctop.common.module.service.*;
+import cn.com.ctop.common.module.service.IBindAccountLoginService;
+import cn.com.ctop.common.module.service.ICtopOauthTokenService;
+import cn.com.ctop.common.module.service.IUReportExportService;
+import cn.com.ctop.common.module.service.IUReportService;
+import cn.com.ctop.common.module.service.IUserAllocationService;
 import cn.com.ctop.common.module.utils.CtopAdConstant;
 import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouHistoryReportTaskService;
 import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouWebInterfaceService;
 import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportDailyAgentService;
+import cn.com.ctop.shiwan.modules.service.IShiwanFileUploadService;
 import cn.com.ctop.toutiao.modules.material.service.IByteDanceAdvertiserDataService;
 import cn.com.ctop.toutiao.modules.report.service.IByteDanceVideoReportDailyService;
 import cn.com.ctop.toutiao.modules.report.service.IBytedanceReportService;
@@ -27,6 +32,7 @@ import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.test.context.ActiveProfiles;
 import org.springframework.test.context.junit4.SpringRunner;
 
+import java.io.IOException;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
@@ -130,10 +136,10 @@ public class SampleTest {
         List<UserAllocation> allocations = allocationService.getByParams(633L, null, 0);
         for (UserAllocation allocation : allocations) {
 //            for (int i = 2; i < 10; i++) {
-                CtopOauthToken token = oauthTokenService.getTokenByAccountId(allocation.getAccountId());
-                Date getDate = DateUtils.addDay(new Date(), 0);
+            CtopOauthToken token = oauthTokenService.getTokenByAccountId(allocation.getAccountId());
+            Date getDate = DateUtils.addDay(new Date(), 0);
 //                reportService.getAdvertiserReport(token, getDate, getDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
-                reportService.getAdvertiserReport(token, getDate, getDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY);
+            reportService.getAdvertiserReport(token, getDate, getDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_HOURLY);
 //            }
         }
     }
@@ -174,11 +180,11 @@ public class SampleTest {
     public void loadAccountData() {
 //        List<UserAllocation> allocations = allocationService.getByParams(776L,null,0);
 //        for (UserAllocation allocation:allocations) {
-            CtopOauthToken token = tokenService.getTokenByAccountId(93238965516L);
-            for(int i=92;i<100;i++){
-                Date getDate = DateUtils.addDay(new Date(),-i);
-                reportService.getAdvertiserReport(token, getDate, getDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
-            }
+        CtopOauthToken token = tokenService.getTokenByAccountId(93238965516L);
+        for (int i = 92; i < 100; i++) {
+            Date getDate = DateUtils.addDay(new Date(), -i);
+            reportService.getAdvertiserReport(token, getDate, getDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
+        }
 //        }
     }
 
@@ -190,20 +196,20 @@ public class SampleTest {
     IUReportService uReportService;
 
     @Test
-    public void loadBytedanceData(){
-        List<UserAllocation>allocations = allocationService.getByParams(633L,null,0);
-        for (int i=0;i<allocations.size();i++) {
+    public void loadBytedanceData() {
+        List<UserAllocation> allocations = allocationService.getByParams(633L, null, 0);
+        for (int i = 0; i < allocations.size(); i++) {
             CtopOauthToken token = tokenService.getTokenByAccountId(allocations.get(i).getAccountId());
-            for(int j=10;j<110;j++){
+            for (int j = 10; j < 110; j++) {
                 Date getDate = DateUtils.addDay(new Date(), -j);
-                reportService.getAdvertiserReport(token, getDate, getDate,CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
+                reportService.getAdvertiserReport(token, getDate, getDate, CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
             }
         }
     }
 
     @Test
-    public void loaddata(){
-        for(int i=0;i<30;i++){
+    public void loaddata() {
+        for (int i = 0; i < 30; i++) {
             Date getDate = DateUtils.addDay(new Date(), -i);
             String date = DateUtils.formatDate(getDate);
             videoReportDailyService.videoInfoList(date, date);
@@ -215,9 +221,10 @@ public class SampleTest {
 
     @Autowired
     private IByteDanceVideoReportDailyService videoReportDailyService;
+
     @Test
-    public void loadMatData(){
-        List<UserAllocation> allocations = allocationService.getByParams(320L,null,0);
+    public void loadMatData() {
+        List<UserAllocation> allocations = allocationService.getByParams(320L, null, 0);
         countDownLatch = new CountDownLatch(allocations.size());
         executorService = Executors.newFixedThreadPool(2);
         allocations.forEach(allocation -> {
@@ -243,4 +250,14 @@ public class SampleTest {
         }
         XxlJobLogger.log("物料数据同步完成");
     }
+
+    @Autowired
+    private IShiwanFileUploadService shiwanFileUploadService;
+
+    @Test
+    public void fileUpload() throws IOException {
+        shiwanFileUploadService.createNewZipFile(null, "6",null,null,null,null);
+    }
+
+
 }

+ 287 - 0
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/FileUtil.java

@@ -0,0 +1,287 @@
+package cn.com.ctop.shiwan.modules;
+
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileItemFactory;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.commons.CommonsMultipartFile;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URL;
+import java.util.Date;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+/**
+ * TODO
+ *
+ * @ClassName ZipUtil
+ * @Author ZHAOXA
+ * @date 2020-10-23 10:05
+ */
+@Slf4j
+public class FileUtil {
+
+    /**
+     * 转MultipartFile格式文件
+     *
+     * @param
+     * @return org.springframework.web.multipart.MultipartFile
+     * @throws
+     * @author ZHAOXA
+     */
+    public static MultipartFile getMulFileByPath(String picPath) {
+        FileItem fileItem = createFileItem(picPath);
+        MultipartFile mfile = new CommonsMultipartFile(fileItem);
+        return mfile;
+    }
+
+    private static FileItem createFileItem(String filePath) {
+        FileItemFactory factory = new DiskFileItemFactory(16, null);
+        String textFieldName = "textField";
+        int num = filePath.lastIndexOf("/");
+        String fileName = filePath.substring(num);
+        FileItem item = factory.createItem(textFieldName, "text/plain", true,
+                fileName);
+        File newfile = new File(filePath);
+        int bytesRead = 0;
+        byte[] buffer = new byte[8192];
+        try {
+            FileInputStream fis = new FileInputStream(newfile);
+            OutputStream os = item.getOutputStream();
+            while ((bytesRead = fis.read(buffer, 0, 8192))
+                    != -1) {
+                os.write(buffer, 0, bytesRead);
+            }
+            os.close();
+            fis.close();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return item;
+    }
+
+
+    /**
+     * 下载文件到本地
+     *
+     * @param locationPath 本地路径
+     * @param fileUrl      文件下载路径
+     * @param fileName     下载后的名称含后缀
+     * @return java.lang.String
+     * @throws
+     * @author ZHAOXA
+     */
+    public static String writeFiles(String locationPath, String fileUrl, String fileName) {
+        InputStream is = null;
+        OutputStream os = null;
+        Date date = new Date();
+        String realPath = null;
+        try {
+            URL url = new URL(fileUrl);
+            is = url.openStream();
+            File file = new File(locationPath);
+            if (!file.exists()) {
+                boolean mkdirFlag = file.mkdirs();
+                if (!mkdirFlag) {
+                    log.error("[ ========== 下载,创建临时文件夹失败 ========== ]");
+                    return null;
+                }
+            }
+            realPath = locationPath.concat("/").concat(fileName);
+            os = new FileOutputStream(realPath);
+            int bytesRead = 0;
+            byte[] buffer = new byte[8192];
+            while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
+                os.write(buffer, 0, bytesRead);
+                os.flush();
+            }
+        } catch (Exception e) {
+            log.error(" ========== 文件下载到本地异常:", e);
+            return null;
+        } finally {
+            try {
+                if (os != null) {
+                    os.close();
+                }
+            } catch (IOException e) {
+                log.error("Close OutputStream error", e);
+            }
+            try {
+                if (is != null) {
+                    is.close();
+                }
+            } catch (IOException e) {
+                log.error("Close InputStream error", e);
+            }
+        }
+        return realPath;
+    }
+
+
+    /**
+     * //创建zip方法,其中的参数ZipFileName是压缩后文件,inputFile要压缩的文件。
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    public static void zip(String ZipFileName, File inputFile) throws IOException {
+        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ZipFileName));//创建了输出流,这里ZipOutputStream()的参数是FileOutPutStream的原因是因为ZIP压缩的对象是文件。
+        zip(out, inputFile, "");//调用zip方法,实现了zip的重载。这次的参数是本方法中定义过的输出流out,要压缩的文件:inputFile以及文件最后的存储目录base
+        log.info("压缩中....");
+        out.close();
+        log.info("压缩完成!");
+    }
+
+    public static void zip(ZipOutputStream out, File f, String base) throws IOException {//方法重载
+        if (f.isDirectory()) {//判断要压缩的文件是否是文件夹
+            File[] fl = f.listFiles();//如果是文件夹就对把该文件夹中的文件的路径以文件数组的形式获得
+            if (base.length() != 0) {//判断最后要存储的路径是否已存在
+                out.putNextEntry(new ZipEntry(base + "/"));//如果已经存在,写入此目录的entry
+            }
+            for (int i = 0; i < fl.length; i++) {//遍历文件数组
+                zip(out, fl[i], base + fl[i]);//将文件数组中的文件添加到已经创建的ZIP中。
+            }
+        } else {
+            out.putNextEntry(new ZipEntry(base));//如果base为空。那么就创建新的进入点
+            //创建FileInputStream对象
+            FileInputStream in = new FileInputStream(f);//创建该输入流的原因是为了后边判断该流是否到达尾部
+            int b;
+            System.out.println(base);
+            while ((b = in.read()) != -1) {
+                out.write(b);//在没有到达尾部的情况下向已经创建的ZIP中添加
+            }
+            in.close();//关闭流
+        }
+    }
+
+    /**
+     * 文件压缩方法
+     *
+     * @param list
+     * @param zipfilename
+     * @param basePath
+     * @param vid
+     * @throws
+     * @Title: listToZip
+     * @date 2020年1月20日
+     */
+    public static String listToZip(List<String> list, String localPath, String zipfilename) {
+        FileInputStream is = null;
+        ZipOutputStream zos = null;
+        String realPath = localPath + "/newFiles/" + zipfilename;
+        try {
+            if (list != null && list.size() > 0) {
+                File f = new File(localPath, "newFiles");
+                if (!f.exists()) {
+                    boolean mkdirFlag = f.mkdirs();
+                    if (!mkdirFlag) {
+                        log.error(" ==========压缩, 创建临时文件夹失败 ========== ");
+                        return null;
+                    }
+                }
+                // 创建zip文件输出流
+                zos = new ZipOutputStream(new FileOutputStream(new File(realPath)));
+                File file = null;
+                String path = "";
+                for (int i = 0; i < list.size(); i++) {
+                    path = list.get(i);
+                    // file 拿到待压缩文件
+                    file = new File(path);
+                    if (file.exists()) {
+                        // 创建源文件输入流
+                        is = new FileInputStream(file);
+                        zos.putNextEntry(new ZipEntry(file.getName()));
+                        byte[] buf = new byte[2048];
+                        int length = -1;
+                        while ((length = is.read(buf)) != -1) {
+                            zos.write(buf, 0, length);
+                            zos.flush();
+                        }
+                        zos.closeEntry();
+                        is.close();
+                      /*  if (file.delete()) {
+                            // 删除图片
+                            log.debug("[ ===== File deleted successfully ===== ]");
+                        }*/
+                    } else {
+                        log.warn("[ ======= {} 源文件不存在 ======= ]", path);
+                        return null;
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.error("[ ==========压缩文件异常 ========== ]", e);
+            return null;
+        } finally {
+            try {
+                if (is != null) {
+                    is.close();
+                }
+                if (zos != null) {
+                    zos.close();
+                }
+            } catch (IOException e) {
+                log.error("[ ==========关闭IO流失败========== ]", e);
+            }
+        }
+        return realPath;
+    }
+
+
+    /**
+     * 通过MultipartFile获取本地下载路径
+     *
+     * @param
+     * @return java.lang.String
+     * @throws
+     * @author ZHAOXA
+     */
+    public static String approvalFile(MultipartFile filecontent, String path) {
+        OutputStream os = null;
+        InputStream inputStream = null;
+        String fileName = filecontent.getOriginalFilename();
+        try {
+            inputStream = filecontent.getInputStream();
+        } catch (IOException e) {
+            log.error("获取文件流异常");
+        }
+        try {
+            byte[] bs = new byte[1024];
+            // 读取到的数据长度
+            int len;
+            // 输出的文件流保存到本地文件
+            File tempFile = new File(path);
+            if (!tempFile.exists()) {
+                tempFile.mkdirs();
+            }
+            os = new FileOutputStream(tempFile.getPath() + "/" + File.separator + fileName);
+            // 开始读取
+            while ((len = inputStream.read(bs)) != -1) {
+                os.write(bs, 0, len);
+            }
+        } catch (Exception e) {
+            log.error("获取文件的本地路径失败", e);
+        } finally {
+            // 完毕,关闭所有链接
+            try {
+                os.close();
+                inputStream.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return path + fileName;
+    }
+
+}

+ 57 - 11
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/controller/ShiwanFileUploadController.java

@@ -1,12 +1,14 @@
 package cn.com.ctop.shiwan.modules.controller;
 
 import cn.com.ctop.common.module.annotation.AutoLog;
+import cn.com.ctop.common.module.utils.Check;
 import cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload;
 import cn.com.ctop.shiwan.modules.service.IShiwanFileUploadService;
 import com.alibaba.fastjson.JSON;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.xxl.job.core.enums.NoEn;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.extern.slf4j.Slf4j;
@@ -19,11 +21,9 @@ import org.jeecgframework.poi.excel.entity.ExportParams;
 import org.jeecgframework.poi.excel.entity.ImportParams;
 import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.DeleteMapping;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.PutMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
@@ -74,6 +74,10 @@ public class ShiwanFileUploadController {
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
         Result<IPage<ShiwanFileUpload>> result = new Result<>();
+        //父级为0,是zip文件,其他为zip内部文件
+        shiwanFileUpload.setParentId((long) 0);
+        //状态为1,文件有效未被删除
+        shiwanFileUpload.setFileStatus(NoEn.NO1.valueStr());
         QueryWrapper<ShiwanFileUpload> queryWrapper = QueryGenerator.initQueryWrapper(shiwanFileUpload, req.getParameterMap());
         Page<ShiwanFileUpload> page = new Page<ShiwanFileUpload>(pageNo, pageSize);
         IPage<ShiwanFileUpload> pageList = shiwanFileUploadService.page(page, queryWrapper);
@@ -82,17 +86,59 @@ public class ShiwanFileUploadController {
         return result;
     }
 
+    @PostMapping("/saveOrUpdateFile")
+    public Result<Object> saveOrUpdateFile(@RequestBody MultipartFile file, String userId, Long accountId, String fileType, HttpServletRequest request) {
+        Result<Object> result = new Result<>();
+        try {
+            ShiwanFileUpload entity = shiwanFileUploadService.saveOrUpdateFile(file, userId, accountId, fileType, null, null);
+            if (Check.isNull(entity)) {
+                result = Result.error("上传失败");
+            }
+            Object obj = entity;
+            result = Result.ok(obj);
+        } catch (Exception e) {
+            log.error("试玩素材上传COS异常", e);
+            result = Result.error(-1, "上传失败");
+        }
+        return result;
+    }
 
 
-    @PostMapping("/fileSave")
-    public Result<String> fileSave(@RequestBody MultipartFile file, String _w_userid, HttpServletRequest request){
-        Result<String> result = new Result<>();
-        log.info("上传文件新版本");
-        String fileId = request.getHeader("x-weboffice-file-id");
-        String data = shiwanFileUploadService.fileSave(file,_w_userid,fileId);
-        result.setResult(data);
+    @PostMapping("/createNewZipFile")
+    public Result<Object> createNewZipFile(@RequestBody MultipartFile file, String id, String updateName, String userId, Long accountId, String fileType) {
+        Result<Object> result = new Result<>();
+        try {
+            ShiwanFileUpload entity = shiwanFileUploadService.createNewZipFile(file, id, updateName, userId, accountId, fileType);
+            if (Check.isNull(entity)) {
+                result = Result.error("上传失败");
+            }
+            Object obj = entity;
+            result = Result.ok(obj);
+        } catch (Exception e) {
+            log.error("生成新的试玩素材ZIP包异常", e);
+            result = Result.error(-1, "上传失败");
+        }
         return result;
     }
+
+    @GetMapping("/selectListByParentId")
+    public Result<List<ShiwanFileUpload>> selectListByParentId(String id) {
+        Result<List<ShiwanFileUpload>> result = new Result<List<ShiwanFileUpload>>();
+        ShiwanFileUpload shiwanFileUploadEntity = shiwanFileUploadService.getById(id);
+        if (shiwanFileUploadEntity == null) {
+            result.error500("未找到对应实体");
+        } else {
+            List<ShiwanFileUpload> list = shiwanFileUploadService.selectListByParentId(id);
+            if (!Check.isNull(list)) {
+                result.success("查询成功!");
+                result.setResult(list);
+            } else {
+                result.error(-1, "查询失败");
+            }
+        }
+        return result;
+    }
+
     /**
      * 添加
      *
@@ -122,7 +168,7 @@ public class ShiwanFileUploadController {
      */
     @AutoLog(value = "试玩平台,文件信息-编辑")
     @ApiOperation(value = "试玩平台,文件信息-编辑", notes = "试玩平台,文件信息-编辑")
-    @PutMapping(value = "/edit")
+    @PostMapping(value = "/edit")
     public Result<ShiwanFileUpload> edit(@RequestBody ShiwanFileUpload shiwanFileUpload) {
         Result<ShiwanFileUpload> result = new Result<ShiwanFileUpload>();
         ShiwanFileUpload shiwanFileUploadEntity = shiwanFileUploadService.getById(shiwanFileUpload.getId());
@@ -146,7 +192,7 @@ public class ShiwanFileUploadController {
      */
     @AutoLog(value = "试玩平台,文件信息-通过id删除")
     @ApiOperation(value = "试玩平台,文件信息-通过id删除", notes = "试玩平台,文件信息-通过id删除")
-    @DeleteMapping(value = "/delete")
+    @GetMapping(value = "/delete")
     public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
         try {
             shiwanFileUploadService.removeById(id);

+ 15 - 3
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/entity/ShiwanFileUpload.java

@@ -78,6 +78,10 @@ public class ShiwanFileUpload {
     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     @ApiModelProperty(value = "上传时间")
     private Date uploadTime;
+
+    private Date createTime;
+
+    private Date updateTime;
     /**
      * 操作人
      */
@@ -90,10 +94,18 @@ public class ShiwanFileUpload {
     @Excel(name = "remake", width = 15)
     @ApiModelProperty(value = "remake")
     private String remake;
-
-    private String functionType;
-
+    /**
+     * 文件后缀
+     */
     private String fileSuffix;
 
     private String cfileName;
+    /**
+     * MD5签名
+     */
+    private String signature;
+
+    private Long accountId;
+
+    private Long parentId;
 }

+ 8 - 0
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/mapper/xml/ShiwanFileUploadMapper.java

@@ -1,8 +1,11 @@
 package cn.com.ctop.shiwan.modules.mapper;
 
 import cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 
+import java.util.List;
+
 /**
  * 试玩平台,文件信息
  *
@@ -12,4 +15,9 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  */
 public interface ShiwanFileUploadMapper extends BaseMapper<ShiwanFileUpload> {
 
+    ShiwanFileUpload selectEntity(JSONObject job);
+
+    void deleteByParentId(Long id);
+
+    List<ShiwanFileUpload> selectListByParentId(String id);
 }

+ 36 - 1
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/mapper/xml/ShiwanFileUploadMapper.xml

@@ -1,5 +1,40 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-<mapper namespace="cn.com.ctop.shiwan.mapper.ShiwanFileUploadMapper">
+<mapper namespace="cn.com.ctop.shiwan.modules.mapper.ShiwanFileUploadMapper">
+
+    <select id="selectEntity" resultType="cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload">
+        SELECT
+        *
+        FROM ctop_shiwan_file_upload
+        WHERE
+        file_status = 1
+        <if test="fileName != null and fileName != '' ">
+            and file_name = #{fileName}
+        </if>
+        <if test="fileType != null and fileType != '' ">
+            and file_type = #{fileType}
+        </if>
+        <if test="accountId != null and accountId != '' ">
+            and account_id = #{accountId}
+        </if>
+        <if test="userId != null and userId != '' ">
+            and user_id = #{userId}
+        </if>
+        <if test="parentId != null and parentId != '' ">
+            and parent_id = #{parentId}
+        </if>
+    </select>
+    <select id="selectListByParentId" resultType="cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload">
+        SELECT
+        *
+        FROM ctop_shiwan_file_upload
+        WHERE file_status = 1
+        AND parent_id=#{id}
+    </select>
+
+    <delete id="deleteByParentId" parameterType="java.lang.Long">
+        delete from ctop_shiwan_file_upload
+    where parent_id = #{parentId}
+    </delete>
 
 </mapper>

+ 343 - 0
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/service/ShiwanFileUploadServiceImpl.java

@@ -0,0 +1,343 @@
+package cn.com.ctop.shiwan.modules.service;
+
+import cn.com.ctop.common.module.utils.Check;
+import cn.com.ctop.common.module.utils.CosUtils;
+import cn.com.ctop.common.module.utils.LoadFileUtil;
+import cn.com.ctop.common.module.vo.ResFileDTO;
+import cn.com.ctop.shiwan.modules.FileUtil;
+import cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload;
+import cn.com.ctop.shiwan.modules.mapper.ShiwanFileUploadMapper;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.xxl.job.core.enums.NoEn;
+import lombok.extern.slf4j.Slf4j;
+import org.jeecg.common.util.DateUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.UUID;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * 试玩平台,文件信息
+ * try-play
+ *
+ * @author jeecg-boot
+ * @version V1.0
+ * @date 2020-10-21
+ */
+@Slf4j
+@Service
+public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMapper, ShiwanFileUpload> implements cn.com.ctop.shiwan.modules.service.IShiwanFileUploadService {
+
+    @Autowired
+    private ShiwanFileUploadMapper shiwanFileUploadMapper;
+    @Value("${zip.local.download-path}")
+    private String downloadPath;
+
+    @Override
+    public ShiwanFileUpload saveOrUpdateFile(MultipartFile file, String userId, Long accountId, String fileType, Long parentId, String uuid) {
+        ShiwanFileUpload existFiles = getExistFiles(userId, accountId, file.getOriginalFilename(), fileType, parentId);
+        StringBuffer path = new StringBuffer();
+        String uuids = UUID.randomUUID().toString();
+        path.append(downloadPath).append(DateUtils.getNowDate(DateUtils.WEB_FORMAT)).append("/").append(uuids).append("/");
+        log.info("----------服务器下载地址:{}", path.toString());
+        ShiwanFileUpload shiwanFileUpload = null;
+        String newUrl = FileUtil.approvalFile(file, path.toString());
+        String md5 = null;
+        try {
+            md5 = LoadFileUtil.getMD5(newUrl);
+        } catch (IOException e) {
+            log.error("获取MD5签名失败", e);
+        }
+        if (!Check.isNull(existFiles)) {
+            existFiles.setSignature(md5);
+            shiwanFileUpload = updateFile(file, existFiles);
+            if (!Check.isNull(shiwanFileUpload)) {
+                List<String> urlList = unzipFiles(shiwanFileUpload, path.toString());
+                saveInnerFiles(shiwanFileUpload, urlList);
+            }
+        } else {
+            ShiwanFileUpload fileUpload = new ShiwanFileUpload();
+            fileUpload.setSignature(md5);
+            fileUpload.setUserId(userId);
+            fileUpload.setAccountId(accountId);
+            fileUpload.setFileType(fileType);
+            fileUpload.setParentId(parentId);
+            shiwanFileUpload = saveFile(file, fileUpload, uuid);
+            if (!Check.isNull(shiwanFileUpload)) {
+                List<String> urlList = unzipFiles(shiwanFileUpload, path.toString());
+                saveInnerFiles(shiwanFileUpload, urlList);
+            }
+        }
+        return shiwanFileUpload;
+    }
+
+    /**
+     * 更新数据并上传文件到COS
+     *
+     * @param
+     * @return cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload
+     * @throws
+     * @author ZHAOXA
+     */
+    private ShiwanFileUpload updateFile(MultipartFile file, ShiwanFileUpload existFiles) {
+        ResFileDTO resultFile = null;
+        String url = "";
+        ShiwanFileUpload fileUpload = new ShiwanFileUpload();
+        if (existFiles.getParentId() != 0) {
+            url = "try-play/inner-file/";
+        } else {
+            url = "try-play/zip/";
+        }
+        try {
+            resultFile = CosUtils.uploadDetailInputStreamV2(file.getInputStream(), existFiles.getCfileName(), existFiles.getFileSuffix(), file.getSize(), url);
+        } catch (IOException e) {
+            log.error("更新文件,上传COS失败", e);
+        }
+        QueryWrapper<ShiwanFileUpload> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("id", existFiles.getId());
+        existFiles.setFileSize(resultFile.getFileSize() + "b");
+        existFiles.setUploadTime(new Date());
+        shiwanFileUploadMapper.update(existFiles, queryWrapper);
+        shiwanFileUploadMapper.deleteByParentId(existFiles.getId());
+        return existFiles;
+    }
+
+    /**
+     * 存储数据并上传文件到COS
+     *
+     * @param
+     * @return cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload
+     * @throws
+     * @author ZHAOXA
+     */
+    private ShiwanFileUpload saveFile(MultipartFile file, ShiwanFileUpload fileUpload, String uuid) {
+        String filename = file.getOriginalFilename();
+        ResFileDTO resultFile = null;
+        String url = "";
+        if (Check.isNull(fileUpload.getParentId())) {
+            url = "try-play/zip/";
+            fileUpload.setParentId((long) NoEn.NO0.valueInt());
+        } else {
+            url = "try-play/inner-file/".concat(uuid).concat("/");
+        }
+        String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
+        try {
+            resultFile = CosUtils.uploadDetailInputStream(file.getInputStream(), filename, fileSuffix, file.getSize(), url);
+        } catch (IOException e) {
+            log.error("上传COS异常", e);
+        }
+        if (!Check.isNull(resultFile)) {
+            fileUpload.setCfileName(resultFile.getCFileName());
+            fileUpload.setFileName(filename);
+            fileUpload.setFileSuffix(fileSuffix);
+            if ("zip".equals(fileSuffix)) {
+                fileUpload.setFileLevel(NoEn.NO0.valueInt());
+            } else {
+                fileUpload.setFileLevel(NoEn.NO1.valueInt());
+            }
+            fileUpload.setFileStatus(NoEn.NO1.valueStr());
+            fileUpload.setFileSize(resultFile.getFileSize() + "b");
+            fileUpload.setFileUrl(resultFile.getFileUrl());
+            fileUpload.setUploadTime(new Date());
+            shiwanFileUploadMapper.insert(fileUpload);
+        }
+        return shiwanFileUploadMapper.selectById(fileUpload.getId());
+    }
+
+
+    @Override
+    public ShiwanFileUpload createNewZipFile(MultipartFile file, String id, String updateName, String userId, Long accountId, String fileType) throws IOException {
+        ShiwanFileUpload fileUpload = shiwanFileUploadMapper.selectById(id);
+        StringBuffer path = new StringBuffer();
+        String uuid = UUID.randomUUID().toString();
+        path.append(downloadPath).append(DateUtils.getNowDate(DateUtils.WEB_FORMAT)).append("/").append(uuid).append("/");
+        log.info("----------服务器下载地址:{}", path.toString());
+        //解压zip文件
+        List<String> urlList = unzipFiles(fileUpload, path.toString());
+        if (null != urlList && urlList.size() > 0) {
+            Iterator it = urlList.iterator();
+            while (it.hasNext()) {
+                String url = it.next().toString();
+                String fileName = url.substring(url.lastIndexOf("/") + 1);
+                if (updateName.equals(fileName)) {
+                    //移除被替换的对象
+                    it.remove();
+                }
+            }
+        }
+        //添加上新的对象
+        String newUrl = FileUtil.approvalFile(file, path.toString());
+        urlList.add(newUrl);
+        //压缩zip文件
+        String newFileName = DateUtils.getNowDate(DateUtils.LONG_FORMAT).concat("_COPYFROM_").concat(fileUpload.getFileName());
+        return createNewZipFiles(urlList, path.toString(), newFileName, updateName, userId, accountId, fileType);
+    }
+
+    @Override
+    public List<ShiwanFileUpload> selectListByParentId(String id) {
+        return shiwanFileUploadMapper.selectListByParentId(id);
+    }
+
+    /**
+     * 解压文件
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    private List<String> unzipFiles(ShiwanFileUpload fileUpload, String path) {
+        List<String> urlList = new ArrayList<>();
+        try {
+            //下载到本地服务器
+            String innerZipPath = FileUtil.writeFiles(path.concat("oldZip/"), fileUpload.getFileUrl(), fileUpload.getCfileName());
+            log.info("----------zip包解压地址:{}", innerZipPath);
+            ZipFile zipFile = new ZipFile(innerZipPath, Charset.forName("GBK"));
+            Enumeration<?> enumeration = zipFile.entries();
+            ZipEntry zipEntry = null;
+            path.concat("innerFile/");
+            while (enumeration.hasMoreElements()) {
+                zipEntry = (ZipEntry) enumeration.nextElement();
+                // 如果是文件夹,就创建个文件夹
+                if (zipEntry.isDirectory()) {
+                    String dirPath = path + zipEntry.getName();
+                    File dir = new File(dirPath);
+                    dir.mkdirs();
+                } else {
+                    String url = path + zipEntry.getName();
+                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
+                    File targetFile = new File(url);
+                    // 保证这个文件的父文件夹必须要存在
+                    if (!targetFile.getParentFile().exists()) {
+                        targetFile.getParentFile().mkdirs();
+                    }
+                    targetFile.createNewFile();
+                    // 将压缩文件内容写入到这个文件中
+                    InputStream is = zipFile.getInputStream(zipEntry);
+                    FileOutputStream fos = new FileOutputStream(targetFile);
+                    int len;
+                    byte[] buf = new byte[8192];
+                    while ((len = is.read(buf)) != -1) {
+                        fos.write(buf, 0, len);
+                    }
+                    urlList.add(url);
+                    // 关流顺序,先打开的后关闭
+                    fos.close();
+                    is.close();
+                }
+            }
+            deletelocalFiles(path.concat("oldZip/").concat(fileUpload.getCfileName()));
+        } catch (IOException e) {
+            log.error("解压原zip失败 ", e);
+        }
+        return urlList;
+    }
+
+    /**
+     * 压缩ZIP文件,并存储数据到本地
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    private ShiwanFileUpload createNewZipFiles(List<String> list, String innerFilePath, String zipfilename, String updateName, String userId, Long accountId, String fileType) throws IOException {
+        String zipUrl = FileUtil.listToZip(list, innerFilePath, zipfilename);
+        ShiwanFileUpload shiwanFileUpload = new ShiwanFileUpload();
+        shiwanFileUpload.setUserId(userId);
+        shiwanFileUpload.setAccountId(accountId);
+        shiwanFileUpload.setFileType(fileType);
+        try {
+            shiwanFileUpload.setSignature(LoadFileUtil.getMD5(zipUrl));
+        } catch (IOException e) {
+            log.error("获取MD5签名失败", e);
+        }
+        //存储新ZIP包
+        ShiwanFileUpload newZipEntity = saveFile(FileUtil.getMulFileByPath(zipUrl), shiwanFileUpload, null);
+        deletelocalFiles(zipUrl);
+        if (!Check.isNull(newZipEntity)) {
+            saveInnerFiles(newZipEntity, list);
+        }
+        return newZipEntity;
+    }
+
+    /**
+     * 存储zip内部文件
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    private void saveInnerFiles(ShiwanFileUpload newZipEntity, List<String> list) {
+        MultipartFile mulFileByPath = null;
+        for (String url : list) {
+            ShiwanFileUpload shiwanFileUpload = new ShiwanFileUpload();
+            shiwanFileUpload.setUserId(newZipEntity.getUserId());
+            shiwanFileUpload.setAccountId(newZipEntity.getAccountId());
+            shiwanFileUpload.setFileType(newZipEntity.getFileType());
+            shiwanFileUpload.setParentId(newZipEntity.getId());
+            try {
+                shiwanFileUpload.setSignature(LoadFileUtil.getMD5(url));
+            } catch (IOException e) {
+                log.error("获取MD5签名失败", e);
+            }
+            mulFileByPath = FileUtil.getMulFileByPath(url);
+            saveFile(mulFileByPath, shiwanFileUpload, newZipEntity.getCfileName());
+            deletelocalFiles(url);
+        }
+    }
+
+    /**
+     * 删除本地文件
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    private void deletelocalFiles(String filePath) {
+        File file = new File(filePath);
+        if (file.exists()) {
+            file.delete();
+        }
+    }
+
+    /**
+     * 查询现有的文件
+     *
+     * @param
+     * @return cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload
+     * @throws
+     * @author ZHAOXA
+     */
+    private ShiwanFileUpload getExistFiles(String userId, Long accountId, String fileName, String fileType, Long parentId) {
+        JSONObject job = new JSONObject();
+        job.put("useId", userId);
+        job.put("accountId", accountId);
+        job.put("fileName", fileName);
+        job.put("fileType", fileType);
+        job.put("parentId", parentId);
+        ShiwanFileUpload fileEntity = shiwanFileUploadMapper.selectEntity(job);
+        if (Check.isNull(fileEntity)) {
+            return null;
+        }
+        return fileEntity;
+    }
+}

+ 25 - 2
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/service/impl/IShiwanFileUploadService.java

@@ -4,13 +4,36 @@ import cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload;
 import com.baomidou.mybatisplus.extension.service.IService;
 import org.springframework.web.multipart.MultipartFile;
 
+import java.io.IOException;
+import java.util.List;
+
 /**
  * @Description: 试玩平台,文件信息
  * @Author: jeecg-boot
- * @Date:   2020-10-21
+ * @Date: 2020-10-21
  * @Version: V1.0
  */
 public interface IShiwanFileUploadService extends IService<ShiwanFileUpload> {
 
-    String fileSave(MultipartFile file, String w_userid, String fileId);
+    /**
+     * 上传或更新文件(同名同账户同操作人同类型的文件会被新文件更新覆盖)
+     *
+     * @param
+     * @return java.lang.String
+     * @throws
+     * @author ZHAOXA
+     */
+    ShiwanFileUpload saveOrUpdateFile(MultipartFile file, String userId, Long accountId, String fileType, Long parentId, String uuid);
+
+    /**
+     * 创建新的zip文件
+     *
+     * @param
+     * @return java.lang.String
+     * @throws
+     * @author ZHAOXA
+     */
+    ShiwanFileUpload createNewZipFile(MultipartFile file, String id, String updateName, String userId, Long accountId, String fileType) throws IOException;
+
+    List<ShiwanFileUpload> selectListByParentId(String id);
 }

+ 0 - 62
module-shiwan/src/main/java/cn/com/ctop/shiwan/modules/service/impl/ShiwanFileUploadServiceImpl.java

@@ -1,62 +0,0 @@
-package cn.com.ctop.shiwan.modules.service.impl;
-
-import cn.com.ctop.common.module.utils.Check;
-import cn.com.ctop.common.module.utils.CosUtils;
-import cn.com.ctop.common.module.vo.ResFileDTO;
-import cn.com.ctop.shiwan.modules.entity.ShiwanFileUpload;
-import cn.com.ctop.shiwan.modules.mapper.ShiwanFileUploadMapper;
-import cn.com.ctop.shiwan.modules.service.IShiwanFileUploadService;
-import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
-import com.xxl.job.core.enums.NoEn;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.web.multipart.MultipartFile;
-
-import java.util.Date;
-
-/**
- * 试玩平台,文件信息
- * try-play
- *
- * @author jeecg-boot
- * @version V1.0
- * @date 2020-10-21
- */
-@Service
-public class ShiwanFileUploadServiceImpl extends ServiceImpl<ShiwanFileUploadMapper, ShiwanFileUpload> implements IShiwanFileUploadService {
-
-    @Autowired
-    private ShiwanFileUploadMapper shiwanFileUploadMapper;
-
-
-    @Override
-    public String fileSave(MultipartFile file, String w_userid, String fileId) {
-        ResFileDTO resultFile = CosUtils.uploadMultipartFile(file, "try-play/zip/");
-        if (Check.isNull(resultFile)) {
-            return null;
-        }
-        ShiwanFileUpload fileUpload = new ShiwanFileUpload();
-        fileUpload.setCfileName(resultFile.getCFileName());
-        String filename = file.getOriginalFilename();
-        fileUpload.setFileName(filename);
-        String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
-        fileUpload.setFileSuffix(fileSuffix);
-        fileUpload.setFileName(file.getOriginalFilename());
-        if ("zip".equals(fileSuffix)) {
-            fileUpload.setFileLevel(NoEn.NO0.valueInt());
-        } else {
-            fileUpload.setFileLevel(NoEn.NO1.valueInt());
-        }
-        fileUpload.setFileStatus(NoEn.NO1.valueStr());
-
-        fileUpload.setFileSize(Math.random() + "kb");
-        fileUpload.setFileUrl(resultFile.getFileUrl());
-        fileUpload.setUploadTime(new Date());
-        //TODO
-        fileUpload.setUserId(null);
-        fileUpload.setFileType(null);
-        fileUpload.setFunctionType(null);
-        shiwanFileUploadMapper.insert(fileUpload);
-        return resultFile.getFileUrl();
-    }
-}