Prechádzať zdrojové kódy

拆分onlyoffice预览接口

陈长荣 2 mesiacov pred
rodič
commit
3270661043

+ 11 - 192
src/main/java/com/github/jfcloud/excel/editor/docdeal/controller/FileController.java

@@ -3,37 +3,24 @@ package com.github.jfcloud.excel.editor.docdeal.controller;
 import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.io.IoUtil;
 import cn.hutool.core.io.file.FileNameUtil;
-import cn.hutool.core.lang.Pair;
 import cn.hutool.core.net.URLEncodeUtil;
 import cn.hutool.core.util.IdUtil;
 import cn.hutool.core.util.StrUtil;
-import cn.hutool.http.HttpResponse;
-import cn.hutool.http.HttpUtil;
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONObject;
 import com.amazonaws.services.s3.model.S3Object;
-import com.github.jfcloud.excel.editor.docdeal.bean.*;
-import com.github.jfcloud.excel.editor.docdeal.constant.CommandEnum;
-import com.github.jfcloud.excel.editor.docdeal.constant.DocumentConstants;
-import com.github.jfcloud.excel.editor.docdeal.constant.DocumentStatus;
+import com.github.jfcloud.excel.editor.docdeal.bean.FileUpload;
 import com.github.jfcloud.excel.editor.docdeal.oss.OssProperties;
 import com.github.jfcloud.excel.editor.docdeal.oss.service.OssTemplate;
 import com.github.jfcloud.excel.editor.docdeal.service.FileUploadService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 
-import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.util.Date;
 import java.util.List;
-import java.util.stream.Collectors;
 
 @Slf4j
 @Controller
@@ -42,12 +29,6 @@ public class FileController {
     OssTemplate ossTemplate;
     @Autowired
     OssProperties ossProperties;
-    @Value("${files.docservice.url.site}")
-    private String officeUrl;
-    @Value("${files.docservice.url.command}")
-    private String officeCommand;
-    @Value("${document.server.url}")
-    private String serverUrl;
 
     @Autowired
     private FileUploadService uploadService;
@@ -80,16 +61,6 @@ public class FileController {
         return upload;
     }
 
-    /**
-     * 查询所有上传文档信息接口
-     *
-     * @return
-     */
-    @GetMapping("/filelist")
-    @ResponseBody
-    public List<FileUpload> listFile() {
-        return uploadService.lambdaQuery().orderByDesc(FileUpload::getUploadDate).list();
-    }
 
     /**
      * 下载文档接口
@@ -100,7 +71,13 @@ public class FileController {
     @GetMapping("/download")
     public void download(@RequestParam String name,
                          @RequestParam(required = false) String bucket,
+                         @RequestParam(required = false) String url,
                          HttpServletResponse response) {
+        if (StrUtil.isNotBlank(url)) {
+            name = url.substring(url.lastIndexOf('/') + 1);
+            bucket = url.replace("/admin/sys-file/", "");
+            bucket = bucket.substring(0, bucket.indexOf('/'));
+        }
         if (StrUtil.isBlank(bucket)) {
             bucket = ossProperties.getBucketName();
         }
@@ -124,173 +101,15 @@ public class FileController {
         }
     }
 
-    @GetMapping("/reviewExcel")
-    public String reviewExcel(PreviewVo vo, Model model) {
-        return reviewDocFile(vo, model);
-    }
-
-    @GetMapping("/review")
-    public String reviewDocFile(PreviewVo vo, Model model) {
-        vo.setEdit(false);
-        log.info("==> 查看文档 vo: {}", vo);
-        if (!ossTemplate.exist(vo.getBucket(), vo.getName())) {
-            model.addAttribute("name", vo.getName());
-            return "/notFound";
-        }
-
-        Pair<Document, DocumentEditParam> pair = docInfo(vo);
-        model.addAttribute("document", pair.getKey());
-        model.addAttribute("documentEditParam", pair.getValue());
-
-        String suffix = FileNameUtil.getSuffix(vo.getName());
-        if (suffix.equals("xls") || suffix.equals("xlsx")) {
-            return "/viewerExcel";
-        }
-        return "/viewer";
-    }
-
-    @GetMapping("/edit")
-    public String editDocFile(PreviewVo vo, Model model) {
-        vo.setEdit(true);
-        log.info("==> 编辑文档 vo: {}", vo);
-        if (!ossTemplate.exist(vo.getBucket(), vo.getName())) {
-            model.addAttribute("name", vo.getName());
-            return "/notFound";
-        }
-        Pair<Document, DocumentEditParam> pair = docInfo(vo);
-        model.addAttribute("document", pair.getKey());
-        model.addAttribute("documentEditParam", pair.getValue());
-        return "/editor";
-    }
-
-    private Pair<Document, DocumentEditParam> docInfo(PreviewVo vo) {
-        String title = StrUtil.blankToDefault(vo.getTitle(), vo.getName());
-        String bucket = StrUtil.blankToDefault(vo.getBucket(), ossProperties.getBucketName());
-        String downloadUrl = String.format(DocumentConstants.OFFICE_API_DOC_FILE_BUCKET, serverUrl, vo.getName(), bucket) + "&_t=" + System.currentTimeMillis();
-
-        Document document = Document.builder()
-                .key(IdUtil.fastSimpleUUID())
-                .title(title)
-                .fileType(FileNameUtil.getSuffix(vo.getName()))
-                .url(downloadUrl)
-                .storage(bucket)
-                .len(ossTemplate.getSize(bucket, vo.getName()))
-                .permissions(new JSONObject()
-                        .fluentPut("chat", true)
-                        .fluentPut("comment", true)
-                        .fluentPut("copy", true)
-                        .fluentPut("download", true)
-                        .fluentPut("edit", vo.isEdit())
-                        .fluentPut("fillForms", false)
-                        .fluentPut("modifyContentControl", true)
-                        .fluentPut("modifyFilter", true)
-                        .fluentPut("print", true)
-                        .fluentPut("review", false)
-                        .fluentPut("reviewGroups", null)
-                        .fluentPut("commentGroups", null)
-                        .fluentPut("userInfoGroups", null))
-                .build();
-        log.info("document: {}", JSON.toJSONString(document));
-
-        //回调接口回传文档名称和存储桶
-        DocumentEditParam param = DocumentEditParam.builder()
-                .callbackUrl(String.format(DocumentConstants.OFFICE_API_CALLBACK_BUCKET, serverUrl, vo.getName(), bucket))
-                .user(new DocumentEditParam.UserBean(vo.getUserId(), vo.getUserName()))
-                .build();
-        log.info("param: {}", JSON.toJSONString(param));
-
-        return Pair.of(document, param);
-    }
-
-    /**
-     * Only Office 回调接口
-     * <a href="https://api.onlyoffice.com/zh-CN/docs/docs-api/usage-api/callback-handler/">回调参数</a>
-     */
-    @RequestMapping("/callback")
-    @ResponseBody
-    public DocumentEditCallbackResponse callback(@RequestBody DocumentEditCallback param, HttpServletRequest request) {
-        String name = request.getParameter("name");
-        String bucket = request.getParameter("bucket");
-        log.info("==> onlyoffice 回调 name={}, bucket={}, body={}", name, bucket, JSON.toJSONString(param));
-
-        String userIds = param.getActions()
-                .stream()
-                .map(DocumentEditCallback.ActionsBean::getUserid)
-                .collect(Collectors.joining(", "));
-        String msg = String.format("bucket=%s name=%s user=%s", bucket, name, userIds);
-
-        try {
-            switch (param.getStatus()) {
-                case 0:
-                    log.info("找不到具有对应key的文档 {}", msg);
-                    break;
-                case 1:
-                    log.info("文档正在被编辑 {}", msg);
-                    break;
-                case 2:
-                case 6:
-                    if (param.getStatus() == 2) {
-                        log.info("文档已准备好保存 {}", msg);
-                    } else {
-                        log.info("正在进行强制保存请求 {}", msg);
-                    }
-
-                    //更新oss文件
-                    byte[] bytes = HttpUtil.downloadBytes(param.getUrl());
-                    ossTemplate.putObject(bucket, name, new ByteArrayInputStream(bytes));
-                    log.info("文档已保存 {}", msg);
-                    break;
-                case 3:
-                    log.warn("文档保存时发生错误 {}", msg);
-                    break;
-                case 4:
-                    log.info("文档关闭时没有更改 {}", msg);
-                    break;
-                case 7:
-                    log.error("强制保存文档时发生错误 {}", msg);
-                    break;
-                default:
-                    log.warn("未知状态 {}", msg);
-            }
-        } catch (Exception ex) {
-            log.error("文档保存时发生错误 {} msg={}", msg, ex.getMessage());
-            return DocumentEditCallbackResponse.fail();
-        }
-        return DocumentEditCallbackResponse.success();
-    }
-
     /**
-     * 获取文档编辑状态
+     * 查询所有上传文档信息接口
      *
-     * @param name
      * @return
      */
-    @GetMapping("/editStatus")
+    @GetMapping("/filelist")
     @ResponseBody
-    public JSONObject getDoucmentEditStatus(@RequestParam String name, @RequestParam(required = false) String command) {
-        log.info("查询文档编辑状态 name={}", name);
-
-        command = StrUtil.isBlank(command) ? CommandEnum.FORCE_SAVE.getCommand() : command;
-        JSONObject params = new JSONObject()
-                .fluentPut("c", command)
-                .fluentPut("key", name);
-
-        try (HttpResponse response = HttpUtil.createPost( officeUrl + officeCommand)
-                .body(params.toJSONString())
-                .header("Content-Type", "application/json")
-                .execute()) {
-
-            JSONObject responseObj = JSON.parseObject(response.body());
-            if (CommandEnum.INFO.getCommand().equals(command)) {
-                DocumentStatus documentStatus = DocumentStatus.getDocumentStatus(responseObj.getInteger("error"));
-                if (documentStatus != null) {
-                    responseObj.put("msg", documentStatus.getMsg());
-                }
-            }
-
-            log.info("文档({})编辑状态 {}", name, responseObj);
-            return responseObj;
-        }
+    public List<FileUpload> listFile() {
+        return uploadService.lambdaQuery().orderByDesc(FileUpload::getUploadDate).list();
     }
 
 }

+ 211 - 0
src/main/java/com/github/jfcloud/excel/editor/docdeal/controller/PreviewController.java

@@ -0,0 +1,211 @@
+package com.github.jfcloud.excel.editor.docdeal.controller;
+
+import cn.hutool.core.io.file.FileNameUtil;
+import cn.hutool.core.lang.Pair;
+import cn.hutool.core.util.IdUtil;
+import cn.hutool.core.util.StrUtil;
+import cn.hutool.http.HttpResponse;
+import cn.hutool.http.HttpUtil;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.github.jfcloud.excel.editor.docdeal.bean.*;
+import com.github.jfcloud.excel.editor.docdeal.constant.CommandEnum;
+import com.github.jfcloud.excel.editor.docdeal.constant.DocumentConstants;
+import com.github.jfcloud.excel.editor.docdeal.constant.DocumentStatus;
+import com.github.jfcloud.excel.editor.docdeal.oss.OssProperties;
+import com.github.jfcloud.excel.editor.docdeal.oss.service.OssTemplate;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.ByteArrayInputStream;
+import java.util.stream.Collectors;
+
+@Slf4j
+@Controller
+public class PreviewController {
+    @Autowired
+    OssTemplate ossTemplate;
+    @Autowired
+    OssProperties ossProperties;
+    @Value("${files.docservice.url.site}")
+    private String officeUrl;
+    @Value("${files.docservice.url.command}")
+    private String officeCommand;
+    @Value("${document.server.url}")
+    private String serverUrl;
+
+    @GetMapping("/reviewExcel")
+    public String reviewExcel(PreviewVo vo, Model model) {
+        return reviewDocFile(vo, model);
+    }
+
+    @GetMapping("/review")
+    public String reviewDocFile(PreviewVo vo, Model model) {
+        vo.setEdit(false);
+        log.info("==> 查看文档 vo: {}", vo);
+        if (!ossTemplate.exist(vo.getBucket(), vo.getName())) {
+            model.addAttribute("name", vo.getName());
+            return "/notFound";
+        }
+
+        Pair<Document, DocumentEditParam> pair = docInfo(vo);
+        model.addAttribute("document", pair.getKey());
+        model.addAttribute("documentEditParam", pair.getValue());
+
+        String suffix = FileNameUtil.getSuffix(vo.getName());
+        if (suffix.equals("xls") || suffix.equals("xlsx")) {
+            return "/viewerExcel";
+        }
+        return "/viewer";
+    }
+
+    @GetMapping("/edit")
+    public String editDocFile(PreviewVo vo, Model model) {
+        vo.setEdit(true);
+        log.info("==> 编辑文档 vo: {}", vo);
+        if (!ossTemplate.exist(vo.getBucket(), vo.getName())) {
+            model.addAttribute("name", vo.getName());
+            return "/notFound";
+        }
+        Pair<Document, DocumentEditParam> pair = docInfo(vo);
+        model.addAttribute("document", pair.getKey());
+        model.addAttribute("documentEditParam", pair.getValue());
+        return "/editor";
+    }
+
+    private Pair<Document, DocumentEditParam> docInfo(PreviewVo vo) {
+        String title = StrUtil.blankToDefault(vo.getTitle(), vo.getName());
+        String bucket = StrUtil.blankToDefault(vo.getBucket(), ossProperties.getBucketName());
+        String downloadUrl = String.format(DocumentConstants.OFFICE_API_DOC_FILE_BUCKET, serverUrl, vo.getName(), bucket) + "&_t=" + System.currentTimeMillis();
+
+        Document document = Document.builder()
+                .key(IdUtil.fastSimpleUUID())
+                .title(title)
+                .fileType(FileNameUtil.getSuffix(vo.getName()))
+                .url(downloadUrl)
+                .storage(bucket)
+                .len(ossTemplate.getSize(bucket, vo.getName()))
+                .permissions(new JSONObject()
+                        .fluentPut("chat", true)
+                        .fluentPut("comment", true)
+                        .fluentPut("copy", true)
+                        .fluentPut("download", true)
+                        .fluentPut("edit", vo.isEdit())
+                        .fluentPut("fillForms", false)
+                        .fluentPut("modifyContentControl", true)
+                        .fluentPut("modifyFilter", true)
+                        .fluentPut("print", true)
+                        .fluentPut("review", false)
+                        .fluentPut("reviewGroups", null)
+                        .fluentPut("commentGroups", null)
+                        .fluentPut("userInfoGroups", null))
+                .build();
+        log.info("document: {}", JSON.toJSONString(document));
+
+        //回调接口回传文档名称和存储桶
+        DocumentEditParam param = DocumentEditParam.builder()
+                .callbackUrl(String.format(DocumentConstants.OFFICE_API_CALLBACK_BUCKET, serverUrl, vo.getName(), bucket))
+                .user(new DocumentEditParam.UserBean(vo.getUserId(), vo.getUserName()))
+                .build();
+        log.info("param: {}", JSON.toJSONString(param));
+
+        return Pair.of(document, param);
+    }
+
+    /**
+     * Only Office 回调接口
+     * <a href="https://api.onlyoffice.com/zh-CN/docs/docs-api/usage-api/callback-handler/">回调参数</a>
+     */
+    @RequestMapping("/callback")
+    @ResponseBody
+    public DocumentEditCallbackResponse callback(@RequestBody DocumentEditCallback param, HttpServletRequest request) {
+        String name = request.getParameter("name");
+        String bucket = request.getParameter("bucket");
+        log.info("==> onlyoffice 回调 name={}, bucket={}, body={}", name, bucket, JSON.toJSONString(param));
+
+        String userIds = param.getActions()
+                .stream()
+                .map(DocumentEditCallback.ActionsBean::getUserid)
+                .collect(Collectors.joining(", "));
+        String msg = String.format("bucket=%s name=%s user=%s", bucket, name, userIds);
+
+        try {
+            switch (param.getStatus()) {
+                case 0:
+                    log.info("找不到具有对应key的文档 {}", msg);
+                    break;
+                case 1:
+                    log.info("文档正在被编辑 {}", msg);
+                    break;
+                case 2:
+                case 6:
+                    if (param.getStatus() == 2) {
+                        log.info("文档已准备好保存 {}", msg);
+                    } else {
+                        log.info("正在进行强制保存请求 {}", msg);
+                    }
+
+                    //更新oss文件
+                    byte[] bytes = HttpUtil.downloadBytes(param.getUrl());
+                    ossTemplate.putObject(bucket, name, new ByteArrayInputStream(bytes));
+                    log.info("文档已保存 {}", msg);
+                    break;
+                case 3:
+                    log.warn("文档保存时发生错误 {}", msg);
+                    break;
+                case 4:
+                    log.info("文档关闭时没有更改 {}", msg);
+                    break;
+                case 7:
+                    log.error("强制保存文档时发生错误 {}", msg);
+                    break;
+                default:
+                    log.warn("未知状态 {}", msg);
+            }
+        } catch (Exception ex) {
+            log.error("文档保存时发生错误 {} msg={}", msg, ex.getMessage());
+            return DocumentEditCallbackResponse.fail();
+        }
+        return DocumentEditCallbackResponse.success();
+    }
+
+    /**
+     * 获取文档编辑状态
+     *
+     * @param name
+     * @return
+     */
+    @GetMapping("/editStatus")
+    @ResponseBody
+    public JSONObject getDoucmentEditStatus(@RequestParam String name, @RequestParam(required = false) String command) {
+        log.info("查询文档编辑状态 name={}", name);
+
+        command = StrUtil.isBlank(command) ? CommandEnum.FORCE_SAVE.getCommand() : command;
+        JSONObject params = new JSONObject()
+                .fluentPut("c", command)
+                .fluentPut("key", name);
+
+        try (HttpResponse response = HttpUtil.createPost(officeUrl + officeCommand)
+                .body(params.toJSONString())
+                .header("Content-Type", "application/json")
+                .execute()) {
+
+            JSONObject responseObj = JSON.parseObject(response.body());
+            if (CommandEnum.INFO.getCommand().equals(command)) {
+                DocumentStatus documentStatus = DocumentStatus.getDocumentStatus(responseObj.getInteger("error"));
+                if (documentStatus != null) {
+                    responseObj.put("msg", documentStatus.getMsg());
+                }
+            }
+
+            log.info("文档({})编辑状态 {}", name, responseObj);
+            return responseObj;
+        }
+    }
+
+}

+ 1 - 1
src/main/resources/mapper/FileUploadMapper.xml

@@ -1,6 +1,6 @@
 <?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="com.lc.docdeal.mapper">
+<mapper namespace="com.github.jfcloud.excel.editor.docdeal.mapper.FileUploadMapper">
 
 
 </mapper>