Procházet zdrojové kódy

1.把视频和文件格式转换进行优化,彻底完成功能

jasonk5949 před 8 měsíci
rodič
revize
03eb5f4488

+ 16 - 16
snowy-plugin/snowy-plugin-disk/snowy-plugin-disk-func/src/main/java/vip/xiaonuo/disk/controller/FiletransferController.java

@@ -101,15 +101,15 @@ public class FiletransferController {
     @MyLog(operation = "下载文件", module = CURRENT_MODULE)
     @RequestMapping(value = "/downloadfile", method = RequestMethod.GET)
     public void downloadFile(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, DownloadFileDTO downloadFileDTO) {
-        Cookie[] cookieArr = httpServletRequest.getCookies();
+//        Cookie[] cookieArr = httpServletRequest.getCookies();
         String token = "";
-        if (cookieArr != null) {
-            for (Cookie cookie : cookieArr) {
-                if ("token".equals(cookie.getName())) {
-                    token = cookie.getValue();
-                }
-            }
-        }
+//        if (cookieArr != null) {
+//            for (Cookie cookie : cookieArr) {
+//                if ("token".equals(cookie.getName())) {
+//                    token = cookie.getValue();
+//                }
+//            }
+//        }
         boolean authResult = fileDealComp.checkAuthDownloadAndPreview(downloadFileDTO.getShareBatchNum(),
                 downloadFileDTO.getExtractionCode(),
                 token,
@@ -143,15 +143,15 @@ public class FiletransferController {
     @MyLog(operation = "批量下载文件", module = CURRENT_MODULE)
     @ResponseBody
     public void batchDownloadFile(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BatchDownloadFileDTO batchDownloadFileDTO) {
-        Cookie[] cookieArr = httpServletRequest.getCookies();
+//        Cookie[] cookieArr = httpServletRequest.getCookies();
         String token = "";
-        if (cookieArr != null) {
-            for (Cookie cookie : cookieArr) {
-                if ("token".equals(cookie.getName())) {
-                    token = cookie.getValue();
-                }
-            }
-        }
+//        if (cookieArr != null) {
+//            for (Cookie cookie : cookieArr) {
+//                if ("token".equals(cookie.getName())) {
+//                    token = cookie.getValue();
+//                }
+//            }
+//        }
         boolean authResult = fileDealComp.checkAuthDownloadAndPreview(batchDownloadFileDTO.getShareBatchNum(),
                 batchDownloadFileDTO.getExtractionCode(),
                 token,

+ 0 - 1
snowy-plugin/snowy-plugin-disk/snowy-plugin-disk-func/src/main/java/vip/xiaonuo/disk/service/impl/FiletransferService.java

@@ -149,7 +149,6 @@ public class FiletransferService implements IFiletransferService {
     }
 
     @Override
-    @Transactional(rollbackFor = Exception.class)
     public void uploadFile(HttpServletRequest request, UploadFileDTO uploadFileDto, String userId) {
 
         UploadFile uploadFile = new UploadFile();

+ 48 - 8
snowy-plugin/snowy-plugin-disk/snowy-plugin-disk-func/src/main/java/vip/xiaonuo/disk/service/impl/TranscodingServiceImpl.java

@@ -13,14 +13,12 @@ import vip.xiaonuo.disk.dto.file.TranscodingReqDTO;
 import vip.xiaonuo.disk.mapper.FileMapper;
 import vip.xiaonuo.disk.mapper.UserFileMapper;
 import vip.xiaonuo.disk.service.TranscodingService;
+import vip.xiaonuo.disk.util.OfficeConverter;
+import vip.xiaonuo.disk.util.PdfUtils;
 import vip.xiaonuo.disk.util.VideoConverter;
 
 import javax.annotation.Resource;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
 import java.util.ArrayList;
-import java.util.List;
 
 /**
  * 资源转码 service
@@ -39,6 +37,12 @@ public class TranscodingServiceImpl implements TranscodingService {
     @Resource
     private UserFileMapper userFileMapper;
 
+    @Resource
+    private PdfUtils pdfUtils;
+
+    @Resource
+    private OfficeConverter officeConverter;
+
     @Override
     public CommonResult<String> transcodingVideo(TranscodingReqDTO transcodingReqDTO) {
         // 校验目标文件是否存在,是否是本人的
@@ -65,9 +69,9 @@ public class TranscodingServiceImpl implements TranscodingService {
                 // 转换后把文件信息新增到数据库
                 FileBean newFile = new FileBean();
                 newFile.setFileId(IdUtil.simpleUUID());
-                newFile.setFileUrl(fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
+                newFile.setFileUrl("converted/" + fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
                 newFile.setCreateUserId(userId);
-                newFile.setFileSize(videoConverter.getConverterFileSize(fileBean.getFileId() + "." + transcodingReqDTO.getFormat()));
+                newFile.setFileSize(videoConverter.getConverterFileSize("converted/" + fileBean.getFileId() + "." + transcodingReqDTO.getFormat()));
                 newFile.setFileStatus(1);
                 newFile.setIdentifier(fileBean.getIdentifier());
                 newFile.setStorageType(3);
@@ -93,8 +97,44 @@ public class TranscodingServiceImpl implements TranscodingService {
             // 转码文档
             // pdf doc docx ppt pptx xls xlsx
             // doc转docx,ppt转pptx,xls转xlsx 所有均转pdf
-
-
+            // 判断目标格式
+            if ("pdf".equals(transcodingReqDTO.getFormat())) {
+                try {
+                    pdfUtils.convertToPdf(fileBean.getFileUrl(), fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
+                } catch (Exception ex) {
+                    log.error("PDF格式转换:"+ex.getMessage());
+                }
+            } else {
+                try {
+                    officeConverter.convertAndUpload(fileBean.getFileUrl(), fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
+                } catch (Exception ex) {
+                    log.error("非PDF格式转换:"+ex.getMessage());
+                }
+            }
+            // 转换后把文件信息新增到数据库
+            FileBean newFile = new FileBean();
+            newFile.setFileId(IdUtil.simpleUUID());
+            newFile.setFileUrl("converted/" + fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
+            newFile.setCreateUserId(userId);
+            newFile.setFileSize(videoConverter.getConverterFileSize("converted/" + fileBean.getFileId() + "." + transcodingReqDTO.getFormat()));
+            newFile.setFileStatus(1);
+            newFile.setIdentifier(fileBean.getIdentifier());
+            newFile.setStorageType(3);
+            newFile.setCreateTime(DateUtil.getCurrentTime());
+            fileMapper.insert(newFile);
+            UserFile newUserFile = new UserFile();
+            newUserFile.setUserFileId(IdUtil.simpleUUID());
+            newUserFile.setCreateUserId(userId);
+            newUserFile.setDeleteFlag(0);
+            newUserFile.setExtendName(transcodingReqDTO.getFormat());
+            newUserFile.setFileId(newFile.getFileId());
+            newUserFile.setFileName(userFile.getFileName());
+            newUserFile.setFilePath(userFile.getFilePath());
+            newUserFile.setIsDir(userFile.getIsDir());
+            newUserFile.setUserId(userId);
+            newUserFile.setCreateTime(DateUtil.getCurrentTime());
+            newUserFile.setUploadTime(DateUtil.getCurrentTime());
+            userFileMapper.insert(newUserFile);
         }
         return null;
     }

+ 48 - 31
snowy-plugin/snowy-plugin-disk/snowy-plugin-disk-func/src/main/java/vip/xiaonuo/disk/util/OfficeConverter.java

@@ -1,6 +1,8 @@
 package vip.xiaonuo.disk.util;
 
 import io.minio.*;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
 import java.io.*;
@@ -13,28 +15,34 @@ import java.util.concurrent.TimeUnit;
 public class OfficeConverter {
 
 
-//    @Value("${ufop.minio.endpoint}")
-//    private String minioEndpoint;
-//
-//    @Value("${ufop.minio.access-key}")
-//    private String accessKey;
-//
-//    @Value("${ufop.minio.secret-key}")
-//    private String secretKey;
-//
-//    @Value("${ufop.minio.bucket-name}")
-//    private String bucketName;
-
-    private static final MinioClient minioClient = MinioClient.builder()
-            .endpoint("http:47.93.185.192:10005")
-            .credentials("admin", "Aa123456")
-            .build();
+    private final String minioEndpoint;
+    private final String accessKey;
+    private final String secretKey;
+    private final String bucketName;
+    private final MinioClient minioClient;
+
+    @Autowired
+    public OfficeConverter(
+            @Value("${ufop.minio.endpoint}") String minioEndpoint,
+            @Value("${ufop.minio.access-key}") String accessKey,
+            @Value("${ufop.minio.secret-key}") String secretKey,
+            @Value("${ufop.minio.bucket-name}") String bucketName
+    ) {
+        this.minioEndpoint = minioEndpoint;
+        this.accessKey = accessKey;
+        this.secretKey = secretKey;
+        this.bucketName = bucketName;
+        this.minioClient = MinioClient.builder()
+                .endpoint(minioEndpoint)
+                .credentials(accessKey, secretKey)
+                .build();
+    }
 
     private static final String LIBRE_OFFICE_PATH = "soffice"; // Linux路径
 
-    public static void main(String[] args) {
+    public void main(String[] args) {
         try {
-            convertAndUpload("netdisk", "upload/20241010/fba210e119de04088439e64b062665da.doc", "netdisk", "665da.docx");
+            convertAndUpload("upload/20241010/fba210e119de04088439e64b062665da.doc", "665da.docx");
 //            convertAndUpload("netdisk", "upload/20240705/7faa77badef7a854e3bf664a2ddb1a4f.ppt", "netdisk", "b1a4f.pptx");
 //            convertAndUpload("netdisk", "upload/20250611/答辩会议室号.xls", "netdisk", "室号.xlsx");
         } catch (Exception e) {
@@ -42,22 +50,21 @@ public class OfficeConverter {
         }
     }
 
-    public static void convertAndUpload(String inputBucket, String inputFile,
-                                        String outputBucket, String outputFile) throws Exception {
+    public void convertAndUpload(String inputFile, String outputFile) throws Exception {
         // 1. 从MinIO下载文件
-        File tempInput = downloadFromMinio(inputBucket, inputFile);
+        File tempInput = downloadFromMinio(bucketName, inputFile);
 
         // 2. 执行LibreOffice转换
         File tempOutput = convertWithLibreOffice(tempInput, getOutputFormat(outputFile));
 
         // 3. 上传到MinIO
-        uploadToMinio(outputBucket, outputFile, tempOutput);
+        uploadToMinio(bucketName, outputFile, tempOutput);
 
         // 4. 清理临时文件
         deleteFiles(tempInput, tempOutput);
     }
 
-    private static File downloadFromMinio(String bucket, String objectName) throws Exception {
+    private File downloadFromMinio(String bucket, String objectName) throws Exception {
         // 使用UUID确保唯一性
         String uniqueId = UUID.randomUUID().toString();
         Path tempDir = Files.createTempDirectory("minio-download-");
@@ -66,7 +73,7 @@ public class OfficeConverter {
         try {
             minioClient.downloadObject(
                     DownloadObjectArgs.builder()
-                            .bucket(bucket)
+                            .bucket(bucketName)
                             .object(objectName)
                             .filename(tempPath.toString())
                             .build());
@@ -79,7 +86,7 @@ public class OfficeConverter {
         }
     }
 
-    private static File convertWithLibreOffice(File inputFile, String outputFormat) throws Exception {
+    private File convertWithLibreOffice(File inputFile, String outputFormat) throws Exception {
         File outputFile = File.createTempFile("converted-", "." + outputFormat);
 
         ProcessBuilder pb = new ProcessBuilder(
@@ -112,17 +119,27 @@ public class OfficeConverter {
         return convertedFile;
     }
 
-    private static void uploadToMinio(String bucket, String objectName, File file) throws Exception {
+//    private void uploadToMinio(String bucket, String objectName, File file) throws Exception {
+//        minioClient.uploadObject(
+//                UploadObjectArgs.builder()
+//                        .bucket(bucketName)
+//                        .object(objectName)
+//                        .filename("/convert")
+//                        .contentType(getMimeType(objectName))
+//                        .build());
+//    }
+
+    private void uploadToMinio(String bucket, String objectName, File file) throws Exception {
         minioClient.uploadObject(
                 UploadObjectArgs.builder()
-                        .bucket(bucket)
-                        .object(objectName)
+                        .bucket(bucketName)
+                        .object("converted/"+objectName)
                         .filename(file.getAbsolutePath())
                         .contentType(getMimeType(objectName))
                         .build());
     }
 
-    private static void deleteFiles(File... files) {
+    private  void deleteFiles(File... files) {
         for (File f : files) {
             if (f != null && f.exists()) {
                 f.delete();
@@ -130,7 +147,7 @@ public class OfficeConverter {
         }
     }
 
-    private static String getOutputFormat(String outputFile) {
+    private  String getOutputFormat(String outputFile) {
         if (outputFile.endsWith(".docx")) {
             return "docx";
         }
@@ -143,7 +160,7 @@ public class OfficeConverter {
         throw new IllegalArgumentException("不支持的输出格式: " + outputFile);
     }
 
-    private static String getMimeType(String fileName) {
+    private String getMimeType(String fileName) {
         return switch (fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase()) {
             case "docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
             case "pptx" -> "application/vnd.openxmlformats-officedocument.presentationml.presentation";

+ 26 - 33
snowy-plugin/snowy-plugin-disk/snowy-plugin-disk-func/src/main/java/vip/xiaonuo/disk/util/PdfUtils.java

@@ -3,6 +3,8 @@ package vip.xiaonuo.disk.util;
 import io.minio.DownloadObjectArgs;
 import io.minio.MinioClient;
 import io.minio.UploadObjectArgs;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Component;
 
@@ -15,31 +17,25 @@ import java.util.UUID;
 @Component
 public class PdfUtils {
 
-//    @Value("${ufop.minio.endpoint}")
-//    private String minioEndpoint;
-//
-//    @Value("${ufop.minio.access-key}")
-//    private String accessKey;
-//
-//    @Value("${ufop.minio.secret-key}")
-//    private String secretKey;
-//
-//    @Value("${ufop.minio.bucket-name}")
-//    private String bucketName;
-
-    private String minioEndpoint = "http:47.93.185.192:10005";
-
-    private String accessKey = "admin";
-
-    private String secretKey = "Aa123456";
-
-    private String bucketName = "netdisk";
-
-
+    private final String minioEndpoint;
+    private final String accessKey;
+    private final String secretKey;
+    private final String bucketName;
     private final MinioClient minioClient;
     private final String tempDir = System.getProperty("java.io.tmpdir") + "/minio-converter/";
 
-    public PdfUtils() {
+    // 使用构造函数注入@Value属性
+    @Autowired
+    public PdfUtils(
+            @Value("${ufop.minio.endpoint}") String minioEndpoint,
+            @Value("${ufop.minio.access-key}") String accessKey,
+            @Value("${ufop.minio.secret-key}") String secretKey,
+            @Value("${ufop.minio.bucket-name}") String bucketName
+    ) {
+        this.minioEndpoint = minioEndpoint;
+        this.accessKey = accessKey;
+        this.secretKey = secretKey;
+        this.bucketName = bucketName;
         this.minioClient = MinioClient.builder()
                 .endpoint(minioEndpoint)
                 .credentials(accessKey, secretKey)
@@ -55,13 +51,12 @@ public class PdfUtils {
     }
 
 
-    public static void main(String[] args) throws Exception {
-        PdfUtils pdfUtils = new PdfUtils();
-        pdfUtils.convertToPdf("upload/20250611/答辩会议室号.xls","室号.pdf");
+    public void main(String[] args) throws Exception {
+        convertToPdf("upload/20250611/答辩会议室号.xls","室号.pdf");
     }
 
-    @Async
-    public void convertToPdf(String objectName, String targetFolder) throws Exception {
+//    @Async
+    public void convertToPdf(String objectName, String fileId) throws Exception {
         long start = System.currentTimeMillis();
         File tempFile = null;
 
@@ -70,10 +65,10 @@ public class PdfUtils {
             tempFile = downloadFile(objectName);
 
             // 2. 执行转换
-            String outputPath = convertToPdfLocal(tempFile.getAbsolutePath(), targetFolder);
+            String outputPath = convertToPdfLocal(tempFile.getAbsolutePath(), "convert");
 
             // 3. 上传转换结果
-            uploadToMinio(outputPath, targetFolder);
+            uploadToMinio(outputPath, fileId);
 
         } finally {
             if (tempFile != null && tempFile.exists()) {
@@ -152,15 +147,13 @@ public class PdfUtils {
         }
     }
 
-    private void uploadToMinio(String filePath, String targetFolder) throws Exception {
+    private void uploadToMinio(String filePath, String fileId) throws Exception {
         String fileName = new File(filePath).getName();
-        String objectName = targetFolder.endsWith("/") ?
-                targetFolder + fileName : targetFolder + "/" + fileName;
 
         minioClient.uploadObject(
                 UploadObjectArgs.builder()
                         .bucket(bucketName)
-                        .object(objectName)
+                        .object("converted/"+fileId)
                         .filename(filePath)
                         .build());
     }

+ 1 - 1
snowy-plugin/snowy-plugin-disk/snowy-plugin-disk-func/src/main/java/vip/xiaonuo/disk/util/VideoConverter.java

@@ -151,7 +151,7 @@ public class VideoConverter {
         client.uploadObject(
                 UploadObjectArgs.builder()
                         .bucket(bucket)
-                        .object(object)
+                        .object("convert/" + object)
                         .filename(file.getAbsolutePath())
                         .contentType(getMimeType(object))
                         .build()