DiskFilesController.java 15.9 KB
Newer Older
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
package cn.timer.api.controller.disk;

import cn.timer.api.bean.disk.DiskCatalogue;
import cn.timer.api.bean.disk.DiskCatalogueFiles;
import cn.timer.api.bean.disk.DiskFiles;
import cn.timer.api.bean.disk.DiskFilesLog;
import cn.timer.api.bean.qyzx.QyzxEmpLogin;
import cn.timer.api.config.annotation.CurrentUser;
import cn.timer.api.config.annotation.UserBean;
import cn.timer.api.config.enuminterface.JxglEnumInterface;
import cn.timer.api.config.exception.CustomException;
import cn.timer.api.config.sftp.SftpConfiguration;
import cn.timer.api.controller.disk.sevice.DiskFilesService;
import cn.timer.api.dto.disk.*;
import cn.timer.api.service.FtpService;
import cn.timer.api.service.OSSService;
import cn.timer.api.utils.FileUtils;
import cn.timer.api.utils.Result;
import cn.timer.api.utils.ResultUtil;
import cn.timer.api.utils.UserIp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 云盘-资源上传文件表
 *
 * @author wuqingjun
 * @email 284718418@qq.com
 * @date 2021-12-27 10:05:49
 */
@Api(tags = "云盘")
@Transactional(rollbackOn = Exception.class)
@RestController
@RequestMapping("/disk")
public class DiskFilesController {

    @Autowired
    private FtpService ftpService;
    @Autowired
    private DiskFilesService diskFilesService;

    @Autowired
    private SftpConfiguration config;

66 67 68 69 70 71 72 73
    @Value("${sftp.client.targetPath}")
    private String targetPath;

    @Value("${sftp.client.reservedName}")
    private boolean reservedName;

    @Value("${sftp.client.serverUrl}")
    private String serverUrl;
74 75 76
    @Autowired
    private OSSService ossService;

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
    @ResponseBody
    @PostMapping("/upload")
    @ApiOperation(value = "上传普通文件", httpMethod = "POST", notes = "接口发布说明")
    public Result<Object> upload(@CurrentUser UserBean userBean, @RequestParam(required = true) MultipartFile[] file,
                                 @ApiParam("文件文件夹或共享空间ID") @RequestParam(required = false) Integer catalogueId,HttpServletRequest request) {
        if(catalogueId<=0){
            DiskCatalogue diskCatalogue = DiskCatalogue.builder().build().selectOne(new QueryWrapper<DiskCatalogue>().select("id")
                    .eq("org_id", userBean.getOrgCode())
                    .eq("delete_flag",0)
                    .eq("create_user_id",userBean.getEmpNum()).orderByAsc("create_time")
            );
            if(StringUtils.isEmpty(diskCatalogue)){
                diskCatalogue = new DiskCatalogue();
                diskCatalogue.setCreateUserId(userBean.getEmpNum());
                diskCatalogue.setOrgId(userBean.getOrgCode());
                diskCatalogue.setParentIds("");
                diskCatalogue.setName("我的文件夹");
                diskCatalogue.setUserName(userBean.getUserInfo().getName());
                diskCatalogue.setType(JxglEnumInterface.DiskCatalogueType.DISK_FILE.getType());
                diskCatalogue.insert();
            }
            catalogueId = diskCatalogue.getId();

            //return ResultUtil.error("上传失败,请选择文件夹");
        }
        if (file == null || file.length == 0) {
            return ResultUtil.error("上传失败,请选择上传文件");
        }
        DiskFiles diskFiles = new DiskFiles();
        diskFiles.setOrgId(userBean.getOrgCode());
        diskFiles.setCreateUserId(userBean.getEmpNum());
        diskFiles.setUploadIp(UserIp.getIpAddr(request));
        diskFiles.setUserName(userBean.getQyzxEmpLogin().getUsername());
        DiskCatalogueFiles diskCatalogueFiles = new DiskCatalogueFiles();
        DiskFilesLog diskFilesLog = new DiskFilesLog();
        diskFilesLog.setUserId(userBean.getEmpNum());
        diskFilesLog.setUserName(userBean.getQyzxEmpLogin().getUsername());
        List<FileInfoDto> imageUrls;
        try {
            //上传文件到服务器
            imageUrls = ftpService.uploadFile(userBean.getOrgCode(),file);
            for (FileInfoDto dto : imageUrls) {
                //新增资源上传文件
                diskFiles.setFileType(dto.getFileSuffix());
                //"/home/disk/123456.jpg"
                diskFiles.setDiskPath(dto.getFileName());
                diskFiles.setUrlPath(dto.getUrlPath());
                diskFiles.setTitle(dto.getResourceFileName());
                diskFiles.setFileSize(dto.getFileSize());
                // 显示大小:10KB,5M,2G
                diskFiles.setShowSize(FileUtils.getSize(dto.getFileSize()));
                diskFiles.insert();

                //新增中间关系
                diskCatalogueFiles.setCatalogueId(catalogueId);
                diskCatalogueFiles.setFilesId(diskFiles.getId());
                diskCatalogueFiles.insert();

                //新增 文件浏览记录
                diskFilesLog.setFilePath(dto.getUrlPath());
                diskFilesLog.setFilesId(diskFiles.getId());
                diskFilesLog.setFileSize(dto.getFileSize() + "B");
                diskFilesLog.setTitle(dto.getResourceFileName());
                diskFilesLog.setType(JxglEnumInterface.DiskFilesLogType.CREATE_LOG.getType());
                diskFilesLog.insert();

            }
            return ResultUtil.data(diskFiles);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error("上传文件失败");
    }
    /*@ResponseBody
    @GetMapping("/download")
    @ApiOperation(value = "下载普通文件", httpMethod = "POST", notes = "接口发布说明")
    public Result<Object> download(@CurrentUser UserBean userBean,
                                 @ApiParam("文件ID") @RequestParam(required = true) Integer fileId,
                                   @ApiParam("本地保存目录") @RequestParam(required = true) String localPath) {
        if (fileId == null || fileId <= 0) {
            return ResultUtil.error("下载失败,请选择文件下载");
        }
        DiskFiles diskFiles = DiskFiles.builder().id(fileId).build().selectById();
        if(StringUtils.isEmpty(diskFiles)){
            return ResultUtil.error("下载失败,文件不存在");
        }
        try {
            boolean count = ftpService.downloadFile(diskFiles.getDiskPath());
            if(count){
                DiskFilesLog diskFilesLog = new DiskFilesLog();
                //新增 文件浏览记录
                diskFilesLog.setFilePath(diskFiles.getUrlPath());
                diskFilesLog.setFilesId(diskFiles.getId());
                diskFilesLog.setFileSize(diskFiles.getFileSize() + "B");
                diskFilesLog.setTitle(diskFiles.getTitle());
                diskFilesLog.setType(JxglEnumInterface.DiskFilesLogType.DOWN_LOAD_LOG.getType());
                diskFilesLog.setUserId(userBean.getEmpNum());
                diskFilesLog.setUserName(userBean.getQyzxEmpLogin().getUsername());
                diskFilesLog.insert();
                return ResultUtil.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("下载文件异常,请联系管理员");
        }
        return ResultUtil.error("下载文件失败");
    }*/
    /**
     * 云盘-文件重命名
     *
     * @param userBean
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/file_name")
    @ApiOperation(value = "文件重命名", httpMethod = "POST", notes = "文件重命名")
    public Result<Object> updateFileName(@CurrentUser UserBean userBean, @Validated @RequestBody DiskFilesParam diskFilesParam) {
        try{
            DiskFiles entity = new DiskFiles();
            DiskFiles diskFiles = DiskFiles.builder().id(diskFilesParam.getId()).build().selectById();
            /*if (StringUtils.isEmpty(diskFiles) || !diskFiles.getCreateUserId().equals(userBean.getEmpNum())) {
                return ResultUtil.error("无权限,操作失败!");
            }*/
            entity.setId(diskFiles.getId());
            entity.setTitle(diskFilesParam.getName());
            entity.setUpdateUserId(userBean.getEmpNum());
            entity.setUserName(userBean.getQyzxEmpLogin().getUsername());
            DiskFilesLog diskFilesLog = new DiskFilesLog();
            diskFilesLog.setType(JxglEnumInterface.DiskFilesLogType.UPDATE_LOG.getType());
            if(!StringUtils.isEmpty(diskFilesParam.getDeleteFlag())){
                entity.setDeleteFlag(1);
                diskFilesLog.setType(JxglEnumInterface.DiskFilesLogType.DELETE_LOG.getType());
            }
            Boolean count = entity.updateById();
            if (count) {
                //新增 文件浏览记录
                diskFilesLog.setFilePath(diskFiles.getUrlPath());
                diskFilesLog.setFilesId(diskFiles.getId());
                diskFilesLog.setFileSize(diskFiles.getFileSize() + "B");
                diskFilesLog.setTitle(diskFiles.getTitle());
                diskFilesLog.setUserId(userBean.getEmpNum());
                diskFilesLog.setUserName(userBean.getQyzxEmpLogin().getUsername());
                diskFilesLog.insert();
                return ResultUtil.data(StringUtils.isEmpty(diskFilesParam.getDeleteFlag())?"文件重命名成功":"删除文件成功");
            } else {
                return ResultUtil.error(StringUtils.isEmpty(diskFilesParam.getDeleteFlag())?"文件重命名失败":"删除文件失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException(StringUtils.isEmpty(diskFilesParam.getDeleteFlag())?"文件重命名异常":"删除文件异常");
        }
    }

    /**
     * 云盘-我的文件空间大小
     *
     * @param userBean
     * @return
     */
    @GetMapping(value = "/mycatalogue/{type}")
    @ApiOperation(value = "我的文件空间大小", httpMethod = "GET", notes = "我的文件空间大小")
    public Result<Object> myCatalogue(@PathVariable("type")Integer type,@CurrentUser UserBean userBean) {
        try {
            DiskFileCatalogueDto diskFileCatalogueDto = diskFilesService.getFileCount(userBean,type);
            return ResultUtil.data(diskFileCatalogueDto);
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException("获取我的文件空间大小异常");
        }
    }

    @GetMapping(value = "/exportContract")
    public void exportContract(@CurrentUser UserBean userBean, @ApiParam("文件ID") @RequestParam(required = true) Integer fileId,
                               @ApiParam("下载通道默认不传:我收到的列表下载传type=1") @RequestParam(required = false) Integer type, HttpServletResponse resp) {
        DiskFiles diskFiles = DiskFiles.builder().id(fileId).build().selectById();
        /*if (fileId == null || fileId <= 0) {
            throw new CustomException("下载失败,请选择文件下载");
        }

        if(StringUtils.isEmpty(diskFiles)){
            throw new CustomException("下载失败,文件不存在");
        }
        if(diskFiles.getDeleteFlag() == 1 && StringUtils.isEmpty(type)){
            throw new CustomException("下载失败,该文件已删除");
        }*/
        InputStream fis = null;
        BufferedInputStream bis = null;
        OutputStream os;
        File filePath = null;
        try {
            String name = diskFiles.getTitle()+diskFiles.getFileType();
            resp.setContentType("application/octet-stream");
            resp.setHeader("content-disposition", "attachment; filename=" + new String(name.getBytes("UTF8"), "ISO-8859-1"));
            resp.setCharacterEncoding("UTF-8");
//            filePath = new File(diskFiles.getDiskPath());
            byte[] buffer = new byte[1024];
//            fis = new FileInputStream(filePath);
            fis = ftpService.downloadFile(diskFiles);
            bis = new BufferedInputStream(fis);
            os = resp.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            os.flush();
            DiskFilesLog diskFilesLog = DiskFilesLog.builder().build();
            //新增 文件浏览记录
            diskFilesLog.setFilePath(diskFiles.getUrlPath());
            diskFilesLog.setFilesId(diskFiles.getId());
            diskFilesLog.setFileSize(diskFiles.getFileSize() + "B");
            diskFilesLog.setTitle(diskFiles.getTitle());
            diskFilesLog.setType(JxglEnumInterface.DiskFilesLogType.DOWN_LOAD_LOG.getType());
            diskFilesLog.setUserId(userBean.getEmpNum());
            diskFilesLog.setUserName(userBean.getQyzxEmpLogin().getUsername());
            diskFilesLog.insert();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @ApiOperation(value = "新增文件查看记录", httpMethod = "GET", notes = "新增文件查看记录")
    @GetMapping(value = "/add_look_log")
    public Result<Object> lookLog(@CurrentUser UserBean userBean,@ApiParam("文件ID") @RequestParam(required = true) Integer fileId,
                                  @ApiParam("默认不传,我收到的列表查看传type=1") @RequestParam(required = false) Integer type){
        DiskFiles diskFiles = DiskFiles.builder().id(fileId).build().selectById();
        DiskFilesLog diskFilesLog = DiskFilesLog.builder().build();
        if(StringUtils.isEmpty(diskFiles)){
            throw new CustomException("查看失败,文件不存在");
        }
        if(diskFiles.getDeleteFlag() == 1 && StringUtils.isEmpty(type)){
            throw new CustomException("查看失败,该文件已删除");
        }
        //新增 文件浏览记录
        diskFilesLog.setFilePath(diskFiles.getUrlPath());
        diskFilesLog.setFilesId(diskFiles.getId());
        diskFilesLog.setFileSize(diskFiles.getFileSize() + "B");
        diskFilesLog.setTitle(diskFiles.getTitle());
        diskFilesLog.setType(JxglEnumInterface.DiskFilesLogType.LOOK_LOG.getType());
        diskFilesLog.setUserId(userBean.getEmpNum());
        diskFilesLog.setUserName(userBean.getQyzxEmpLogin().getUsername());
        diskFilesLog.insert();
        return ResultUtil.success();
    }

    @ApiOperation(value = "查询文件是否存在", httpMethod = "GET", notes = "查询文件是否存在")
    @GetMapping(value = "/query_file_isExist")
    public Result<Object> queryFileIsExist(@CurrentUser UserBean userBean,@ApiParam("文件ID") @RequestParam(required = true) Integer fileId,
338
                                           @ApiParam("默认不传,我收到的列表查询传type=1") @RequestParam(required = false) Integer type){
339 340 341 342 343 344 345 346 347 348 349 350
        DiskFiles diskFiles = DiskFiles.builder().id(fileId).build().selectById();
        DiskFilesLog diskFilesLog = DiskFilesLog.builder().build();
        if(StringUtils.isEmpty(diskFiles)){
            throw new CustomException("文件不存在");
        }
        if(diskFiles.getDeleteFlag() == 1 && StringUtils.isEmpty(type)){
            throw new CustomException("该文件已删除");
        }
        return ResultUtil.success();
    }

}