Search in sources :

Example 1 with FileBean

use of com.qiwenshare.file.domain.FileBean in project qiwen-file by qiwenshare.

the class AsyncTaskComp method deleteUserFile.

public Future<String> deleteUserFile(Long userFileId) {
    long begin = System.currentTimeMillis();
    UserFile userFile = userFileService.getById(userFileId);
    if (userFile.getIsDir() == 1) {
        LambdaQueryWrapper<UserFile> userFileLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userFileLambdaQueryWrapper.eq(UserFile::getDeleteBatchNum, userFile.getDeleteBatchNum());
        List<UserFile> list = userFileService.list(userFileLambdaQueryWrapper);
        recoveryFileService.deleteUserFileByDeleteBatchNum(userFile.getDeleteBatchNum());
        for (UserFile userFileItem : list) {
            Long filePointCount = getFilePointCount(userFileItem.getFileId());
            if (filePointCount != null && filePointCount == 0 && userFileItem.getIsDir() == 0) {
                FileBean fileBean = fileMapper.selectById(userFileItem.getFileId());
                try {
                    filetransferService.deleteFile(fileBean);
                    fileMapper.deleteById(fileBean.getFileId());
                } catch (Exception e) {
                    log.error("删除本地文件失败:" + JSON.toJSONString(fileBean));
                }
            }
        }
    } else {
        recoveryFileService.deleteUserFileByDeleteBatchNum(userFile.getDeleteBatchNum());
        Long filePointCount = getFilePointCount(userFile.getFileId());
        if (filePointCount != null && filePointCount == 0 && userFile.getIsDir() == 0) {
            FileBean fileBean = fileMapper.selectById(userFile.getFileId());
            try {
                filetransferService.deleteFile(fileBean);
                fileMapper.deleteById(fileBean.getFileId());
            } catch (Exception e) {
                log.error("删除本地文件失败:" + JSON.toJSONString(fileBean));
            }
        }
    }
    long end = System.currentTimeMillis();
    System.out.println("任务 deleteUserFile 耗时=" + (end - begin));
    return new AsyncResult<String>("deleteUserFile");
}
Also used : UserFile(com.qiwenshare.file.domain.UserFile) FileBean(com.qiwenshare.file.domain.FileBean) AsyncResult(org.springframework.scheduling.annotation.AsyncResult) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper)

Example 2 with FileBean

use of com.qiwenshare.file.domain.FileBean in project qiwen-file by qiwenshare.

the class AsyncTaskComp method saveUnzipFile.

public Future<String> saveUnzipFile(UserFile userFile, FileBean fileBean, int unzipMode, String entryName, String filePath) {
    String unzipUrl = UFOPUtils.getTempFile(fileBean.getFileUrl()).getAbsolutePath().replace("." + userFile.getExtendName(), "");
    String totalFileUrl = unzipUrl + entryName;
    File currentFile = new File(totalFileUrl);
    UserFile saveUserFile = new UserFile();
    saveUserFile.setUploadTime(DateUtil.getCurrentTime());
    saveUserFile.setUserId(userFile.getUserId());
    saveUserFile.setFilePath(UFOPUtils.pathSplitFormat(userFile.getFilePath() + entryName.replace(currentFile.getName(), "")).replace("\\", "/"));
    if (currentFile.isDirectory()) {
        saveUserFile.setIsDir(1);
        saveUserFile.setFileName(currentFile.getName());
    } else {
        FileInputStream fis = null;
        String md5Str = UUID.randomUUID().toString();
        try {
            fis = new FileInputStream(currentFile);
            md5Str = DigestUtils.md5Hex(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
        FileInputStream fileInputStream = null;
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("identifier", md5Str);
            List<FileBean> list = fileMapper.selectByMap(param);
            if (list != null && !list.isEmpty()) {
                // 文件已存在
                saveUserFile.setFileId(list.get(0).getFileId());
            } else {
                // 文件不存在
                fileInputStream = new FileInputStream(currentFile);
                CopyFile createFile = new CopyFile();
                createFile.setExtendName(UFOPUtils.getFileExtendName(totalFileUrl));
                String saveFileUrl = ufopFactory.getCopier().copy(fileInputStream, createFile);
                FileBean tempFileBean = new FileBean(saveFileUrl, currentFile.length(), storageType, md5Str, userFile.getUserId());
                ;
                fileMapper.insert(tempFileBean);
                saveUserFile.setFileId(tempFileBean.getFileId());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fileInputStream);
            System.gc();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            currentFile.delete();
        }
        saveUserFile.setIsDir(0);
        saveUserFile.setExtendName(UFOPUtils.getFileExtendName(totalFileUrl));
        saveUserFile.setFileName(UFOPUtils.getFileNameNotExtend(currentFile.getName()));
    }
    saveUserFile.setDeleteFlag(0);
    if (unzipMode == 1) {
        saveUserFile.setFilePath(UFOPUtils.pathSplitFormat(userFile.getFilePath() + userFile.getFileName() + "/" + entryName.replace(currentFile.getName(), "")).replace("\\", "/"));
    } else if (unzipMode == 2) {
        saveUserFile.setFilePath(UFOPUtils.pathSplitFormat(filePath + entryName.replace(currentFile.getName(), "")).replace("\\", "/"));
    }
    String fileName = fileDealComp.getRepeatFileName(saveUserFile, saveUserFile.getFilePath());
    if (saveUserFile.getIsDir() == 1 && !fileName.equals(saveUserFile.getFileName())) {
    // 如果是目录,而且重复,什么也不做
    } else {
        saveUserFile.setFileName(fileName);
        userFileMapper.insert(saveUserFile);
    }
    return new AsyncResult<String>("saveUnzipFile");
}
Also used : HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) UserFile(com.qiwenshare.file.domain.UserFile) FileBean(com.qiwenshare.file.domain.FileBean) CopyFile(com.qiwenshare.ufop.operation.copy.domain.CopyFile) CopyFile(com.qiwenshare.ufop.operation.copy.domain.CopyFile) UserFile(com.qiwenshare.file.domain.UserFile) File(java.io.File) AsyncResult(org.springframework.scheduling.annotation.AsyncResult)

Example 3 with FileBean

use of com.qiwenshare.file.domain.FileBean in project qiwen-file by qiwenshare.

the class FileController method updateFile.

@Operation(summary = "修改文件", description = "支持普通文本类文件的修改", tags = { "file" })
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ResponseBody
public RestResult<String> updateFile(@RequestBody UpdateFileDTO updateFileDTO) {
    JwtUser sessionUserBean = SessionUtil.getSession();
    UserFile userFile = userFileService.getById(updateFileDTO.getUserFileId());
    FileBean fileBean = fileService.getById(userFile.getFileId());
    Long pointCount = fileService.getFilePointCount(userFile.getFileId());
    if (pointCount > 1) {
        return RestResult.fail().message("暂不支持修改");
    }
    String content = updateFileDTO.getFileContent();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getBytes());
    try {
        Writer writer1 = ufopFactory.getWriter(fileBean.getStorageType());
        WriteFile writeFile = new WriteFile();
        writeFile.setFileUrl(fileBean.getFileUrl());
        int fileSize = byteArrayInputStream.available();
        writeFile.setFileSize(fileSize);
        writer1.write(byteArrayInputStream, writeFile);
        DownloadFile downloadFile = new DownloadFile();
        downloadFile.setFileUrl(fileBean.getFileUrl());
        InputStream inputStream = ufopFactory.getDownloader(fileBean.getStorageType()).getInputStream(downloadFile);
        String md5Str = DigestUtils.md5Hex(inputStream);
        fileBean.setIdentifier(md5Str);
        fileBean.setModifyTime(DateUtil.getCurrentTime());
        fileBean.setModifyUserId(sessionUserBean.getUserId());
        fileBean.setFileSize((long) fileSize);
        fileService.updateById(fileBean);
    } catch (Exception e) {
        throw new QiwenException(999999, "修改文件异常");
    } finally {
        try {
            byteArrayInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return RestResult.success().message("修改文件成功");
}
Also used : WriteFile(com.qiwenshare.ufop.operation.write.domain.WriteFile) DownloadFile(com.qiwenshare.ufop.operation.download.domain.DownloadFile) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) QiwenException(com.qiwenshare.common.exception.QiwenException) IOException(java.io.IOException) QiwenException(com.qiwenshare.common.exception.QiwenException) ByteArrayInputStream(java.io.ByteArrayInputStream) UserFile(com.qiwenshare.file.domain.UserFile) FileBean(com.qiwenshare.file.domain.FileBean) JwtUser(com.qiwenshare.common.util.security.JwtUser) Writer(com.qiwenshare.ufop.operation.write.Writer) Operation(io.swagger.v3.oas.annotations.Operation)

Example 4 with FileBean

use of com.qiwenshare.file.domain.FileBean in project qiwen-file by qiwenshare.

the class FiletransferController method preview.

@Operation(summary = "预览文件", description = "用于文件预览", tags = { "filetransfer" })
@GetMapping("/preview")
public void preview(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, PreviewDTO previewDTO) {
    if (previewDTO.getPlatform() != null && previewDTO.getPlatform() == 2) {
        filetransferService.previewPictureFile(httpServletResponse, previewDTO);
        return;
    }
    String token = "";
    if (StringUtils.isNotEmpty(previewDTO.getToken())) {
        token = previewDTO.getToken();
    } else {
        Cookie[] cookieArr = httpServletRequest.getCookies();
        for (Cookie cookie : cookieArr) {
            if ("token".equals(cookie.getName())) {
                token = cookie.getValue();
            }
        }
    }
    UserFile userFile = userFileService.getById(previewDTO.getUserFileId());
    boolean authResult = fileDealComp.checkAuthDownloadAndPreview(previewDTO.getShareBatchNum(), previewDTO.getExtractionCode(), token, previewDTO.getUserFileId(), previewDTO.getPlatform());
    if (!authResult) {
        log.error("没有权限预览!!!");
        return;
    }
    FileBean fileBean = fileService.getById(userFile.getFileId());
    String mime = MimeUtils.getMime(userFile.getExtendName());
    httpServletResponse.setHeader("Content-Type", mime);
    // 如果是video标签发起的请求就不会为null
    String rangeString = httpServletRequest.getHeader("Range");
    if (StringUtils.isNotEmpty(rangeString)) {
        long range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
        httpServletResponse.setContentLength(Math.toIntExact(fileBean.getFileSize()));
        httpServletResponse.setHeader("Content-Range", String.valueOf(range + (Math.toIntExact(fileBean.getFileSize()) - 1)));
    }
    httpServletResponse.setHeader("Accept-Ranges", "bytes");
    String fileName = userFile.getFileName() + "." + userFile.getExtendName();
    try {
        fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    // 设置文件名
    httpServletResponse.addHeader("Content-Disposition", "fileName=" + fileName);
    filetransferService.previewFile(httpServletResponse, previewDTO);
}
Also used : Cookie(javax.servlet.http.Cookie) UserFile(com.qiwenshare.file.domain.UserFile) FileBean(com.qiwenshare.file.domain.FileBean) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Operation(io.swagger.v3.oas.annotations.Operation)

Example 5 with FileBean

use of com.qiwenshare.file.domain.FileBean in project qiwen-file by qiwenshare.

the class OfficeController method createOfficeFile.

@Operation(summary = "创建office文件", description = "创建office文件", tags = { "office" })
@ResponseBody
@RequestMapping(value = "/createofficefile", method = RequestMethod.POST)
public RestResult<Object> createOfficeFile(@RequestBody CreateOfficeFileDTO createOfficeFileDTO) {
    RestResult<Object> result = new RestResult<>();
    try {
        JwtUser loginUser = SessionUtil.getSession();
        String fileName = createOfficeFileDTO.getFileName();
        String filePath = createOfficeFileDTO.getFilePath();
        String extendName = createOfficeFileDTO.getExtendName();
        List<UserFile> userFiles = userFileService.selectSameUserFile(fileName, filePath, extendName, loginUser.getUserId());
        if (userFiles != null && !userFiles.isEmpty()) {
            return RestResult.fail().message("同名文件已存在");
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String templateFilePath = "";
        if ("docx".equals(extendName)) {
            templateFilePath = "template/Word.docx";
        } else if ("xlsx".equals(extendName)) {
            templateFilePath = "template/Excel.xlsx";
        } else if ("pptx".equals(extendName)) {
            templateFilePath = "template/PowerPoint.pptx";
        }
        String url2 = ClassUtils.getDefaultClassLoader().getResource("static/" + templateFilePath).getPath();
        FileInputStream fileInputStream = new FileInputStream(url2);
        Copier copier = ufopFactory.getCopier();
        CopyFile copyFile = new CopyFile();
        copyFile.setExtendName(extendName);
        String fileUrl = copier.copy(fileInputStream, copyFile);
        FileBean fileBean = new FileBean();
        fileBean.setFileSize(0L);
        fileBean.setFileUrl(fileUrl);
        fileBean.setStorageType(storageType);
        fileBean.setIdentifier(uuid);
        fileBean.setCreateTime(DateUtil.getCurrentTime());
        fileBean.setCreateUserId(loginUser.getUserId());
        fileBean.setFileStatus(1);
        boolean saveFlag = fileService.save(fileBean);
        UserFile userFile = new UserFile();
        if (saveFlag) {
            userFile.setUserId(loginUser.getUserId());
            userFile.setFileName(fileName);
            userFile.setFilePath(filePath);
            userFile.setDeleteFlag(0);
            userFile.setIsDir(0);
            userFile.setExtendName(extendName);
            userFile.setUploadTime(DateUtil.getCurrentTime());
            userFile.setFileId(fileBean.getFileId());
            userFileService.save(userFile);
        }
        return RestResult.success().message("文件创建成功");
    } catch (Exception e) {
        log.error(e.getMessage());
        return RestResult.fail().message(e.getMessage());
    }
}
Also used : RestResult(com.qiwenshare.common.result.RestResult) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) NotLoginException(com.qiwenshare.common.exception.NotLoginException) UserFile(com.qiwenshare.file.domain.UserFile) FileBean(com.qiwenshare.file.domain.FileBean) Copier(com.qiwenshare.ufop.operation.copy.Copier) JSONObject(com.alibaba.fastjson.JSONObject) JwtUser(com.qiwenshare.common.util.security.JwtUser) CopyFile(com.qiwenshare.ufop.operation.copy.domain.CopyFile) Operation(io.swagger.v3.oas.annotations.Operation)

Aggregations

FileBean (com.qiwenshare.file.domain.FileBean)7 UserFile (com.qiwenshare.file.domain.UserFile)7 IOException (java.io.IOException)6 DownloadFile (com.qiwenshare.ufop.operation.download.domain.DownloadFile)3 Operation (io.swagger.v3.oas.annotations.Operation)3 FileInputStream (java.io.FileInputStream)3 InputStream (java.io.InputStream)3 JSONObject (com.alibaba.fastjson.JSONObject)2 NotLoginException (com.qiwenshare.common.exception.NotLoginException)2 QiwenException (com.qiwenshare.common.exception.QiwenException)2 JwtUser (com.qiwenshare.common.util.security.JwtUser)2 CopyFile (com.qiwenshare.ufop.operation.copy.domain.CopyFile)2 Writer (com.qiwenshare.ufop.operation.write.Writer)2 WriteFile (com.qiwenshare.ufop.operation.write.domain.WriteFile)2 File (java.io.File)2 FileNotFoundException (java.io.FileNotFoundException)2 AsyncResult (org.springframework.scheduling.annotation.AsyncResult)2 LambdaQueryWrapper (com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper)1 LambdaUpdateWrapper (com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper)1 RestResult (com.qiwenshare.common.result.RestResult)1