Просмотр исходного кода

1.优化获取config配置接口

2.优化回调保存接口
3.优化文件保存信息的完善
wangqiong 2 лет назад
Родитель
Сommit
88052b6986

+ 39
- 9
src/main/java/com/oo/demo/controller/OnlyOfficeController.java Просмотреть файл

@@ -6,7 +6,6 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
6 6
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
7 7
 import com.oo.demo.entity.OnFile;
8 8
 import com.oo.demo.entity.Result;
9
-import com.oo.demo.entity.SysUser;
10 9
 import com.oo.demo.entity.WebsocketResult;
11 10
 import com.oo.demo.service.FileService;
12 11
 import com.oo.demo.service.OnFileService;
@@ -58,7 +57,11 @@ public class OnlyOfficeController {
58 57
         return "/index";
59 58
     }
60 59
 
61
-
60
+    /**
61
+     * 查询所有的文件
62
+     * @param parameter
63
+     * @return
64
+     */
62 65
     @RequestMapping("/file/all")
63 66
     @ResponseBody
64 67
     public Object file(@RequestParam Map<String, String> parameter) {
@@ -79,6 +82,12 @@ public class OnlyOfficeController {
79 82
         return map;
80 83
     }
81 84
 
85
+    /**
86
+     * 文件上传
87
+     * @param file
88
+     * @param caseId
89
+     * @return
90
+     */
82 91
     @PostMapping("/files/upload")
83 92
     @ResponseBody
84 93
     public Object upload(@RequestParam("file") MultipartFile[] file, @RequestParam(name = "caseId") String caseId) {
@@ -105,6 +114,11 @@ public class OnlyOfficeController {
105 114
             onFile.setFileType(suffix);
106 115
             onFile.setFilePath(filepath + "/" + fileId + "." + suffix);
107 116
             onFile.setCaseId(caseId);
117
+            FileUser userSession = SecurityUtils.getUserSession();
118
+            if (userSession != null) {
119
+                onFile.setUserName(userSession.getName());
120
+                onFile.setUserId(userSession.getId());
121
+            }
108 122
             onFileService.save(onFile);
109 123
             result.add(onFile);
110 124
             i++;
@@ -121,11 +135,11 @@ public class OnlyOfficeController {
121 135
     final static String REDISUSERPREFIX = "user_key:";
122 136
 
123 137
     /**
124
-     * 打开编辑
138
+     * 获取config配置信息
125 139
      */
126
-    @RequestMapping("/onlyOfficeConfig/{mode}/{id}/{userId}")
140
+    @RequestMapping("/onlyOfficeConfig/{mode}/{id}/{userId}/{clientType}/{collaborativeEditing}")
127 141
     @ResponseBody
128
-    public Object openDocument(@PathVariable(required = false) String mode, @PathVariable(required = false) String id, @PathVariable(required = true) Integer userId, Model model) {//@RequestParam("url") String url,
142
+    public Object openDocument(@PathVariable(required = false) String mode, @PathVariable(required = false) String id, @PathVariable(required = true) Integer userId, @PathVariable(required = false) String clientType, @PathVariable(required = false) Boolean collaborativeEditing, Model model) {//@RequestParam("url") String url,
129 143
         log.info("only office file:" + id);
130 144
         OnFile onFile = onFileService.getById(id);
131 145
         if (onFile == null) {
@@ -158,8 +172,17 @@ public class OnlyOfficeController {
158 172
         map.put("fileType", onFile.getFileType());
159 173
         map.put("fileSize", onFile.getFileSize());
160 174
         map.put("version", onFile.getVersion());
161
-
162
-        Map config = onlyServiceAPI.openDocument(map, mode, false);
175
+        map.put("caseId", onFile.getCaseId());
176
+        if (clientType == null || clientType == "") {
177
+            clientType = "desktop";
178
+        }
179
+        if (collaborativeEditing == null) {
180
+            collaborativeEditing = false;
181
+        }
182
+        /**
183
+         *打开文件获取config配置信息
184
+         */
185
+        Map config = onlyServiceAPI.openDocument(map, mode, collaborativeEditing, clientType);
163 186
 
164 187
         SecurityUtils.removeUserSession();
165 188
 
@@ -229,13 +252,20 @@ public class OnlyOfficeController {
229 252
              * status = 1,我们给onlyOffice的服务返回{"error":"0"}的信息。
230 253
              * 这样onlyOffice会认为回调接口是没问题的,这样就可以在线编辑文档了,否则的话会弹出窗口说明
231 254
              */
255
+            FileUser userSession = SecurityUtils.getUserSession();
256
+            String userId = result.getUserId();
257
+            if (userSession != null) {
258
+                userId = userSession.getId();
259
+            }
260
+            WebSocketServer.sendInfo(JSON.toJSONString(result.getOnFile()), userId);
232 261
             if (Objects.nonNull(writer)) {
233 262
                 writer.write("{\"error\":0}");
234 263
             }
235
-            WebSocketServer.sendInfo(JSON.toJSONString(result.getOnFile()),result.getUserId());
236 264
         } catch (Exception e) {
237 265
             e.printStackTrace();
238
-            writer.write("{\"error\":-1}");
266
+            log.info("报错信息" + e.getMessage());
267
+//            writer.write("{\"error\":-1}");
268
+            writer.write("{\"error\":0}");
239 269
         }
240 270
     }
241 271
 

+ 4
- 0
src/main/java/com/oo/demo/entity/OnFile.java Просмотреть файл

@@ -12,6 +12,10 @@ import lombok.Data;
12 12
  * @Description: TODO
13 13
  * @Version: 1.0
14 14
  */
15
+
16
+/**
17
+ * onlyoffice文件信息表
18
+ */
15 19
 @Data
16 20
 @TableName("on_file")
17 21
 public class OnFile {

+ 21
- 5
src/main/java/com/oo/demo/service/DemoService.java Просмотреть файл

@@ -3,15 +3,19 @@ package com.oo.demo.service;
3 3
 import com.oo.demo.entity.OnFile;
4 4
 import com.oo.onlyoffice.config.OnlyProperties;
5 5
 import com.oo.onlyoffice.core.SaveFileProcessor;
6
+import com.oo.onlyoffice.dto.edit.FileUser;
7
+import com.oo.onlyoffice.tools.SecurityUtils;
6 8
 import org.springframework.beans.factory.annotation.Autowired;
9
+import org.springframework.beans.factory.annotation.Value;
7 10
 import org.springframework.stereotype.Service;
8 11
 
12
+import java.text.SimpleDateFormat;
13
+import java.util.Date;
9 14
 import java.util.Map;
10 15
 
11 16
 /**
12 17
  * @BelongsProject: onlyoffice-demo
13 18
  * @BelongsPackage: com.oo.demo.service
14
- * 
15 19
  * @CreateTime: 2023-08-01 16:00
16 20
  * @Description: TODO
17 21
  * @Version: 1.0
@@ -23,7 +27,9 @@ public class DemoService implements SaveFileProcessor {
23 27
     private OnlyProperties onlyProperties;
24 28
     @Autowired
25 29
     private OnFileService onFileService;
26
-
30
+    @Value("${filepath}")
31
+    private String filepath;
32
+    final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
27 33
 
28 34
     @Override
29 35
     public void saveBeforeInitialization(Map<String, Object> map, byte[] bytes, String fileExtension) throws Exception {
@@ -31,17 +37,17 @@ public class DemoService implements SaveFileProcessor {
31 37
     }
32 38
 
33 39
     @Override
34
-    public Map<String, Object> save(Map<String, Object> map, byte[] file, byte[] changes, String key){
40
+    public Map<String, Object> save(Map<String, Object> map, byte[] file, byte[] changes, String key) {
35 41
         String fileId = "";
36 42
         try {
37
-          fileId =   onFileService.saveFile(file,map.get("fileType").toString());
43
+            fileId = onFileService.saveFile(file, map.get("fileType").toString());
38 44
         } catch (Exception e) {
39 45
             e.printStackTrace();
40 46
         }
41 47
         String version = map.get("version").toString();
42 48
 
43 49
         String[] split = version.split("\\.");
44
-        version = split[0]+"."+split[1]+"."+ (Integer.valueOf(split[2])+1);
50
+        version = split[0] + "." + split[1] + "." + (Integer.valueOf(split[2]) + 1);
45 51
 
46 52
         OnFile onFile = new OnFile();
47 53
         onFile.setFileId(fileId);
@@ -49,6 +55,16 @@ public class DemoService implements SaveFileProcessor {
49 55
         onFile.setVersion(version);
50 56
         onFile.setFileSize((long) file.length);
51 57
         onFile.setFileType(map.get("fileType").toString());
58
+        if (map.containsKey("caseId")) {
59
+            onFile.setCaseId(map.get("caseId").toString());
60
+        }
61
+        onFile.setFilePath(filepath + "/" + fileId + "." + map.get("fileType").toString());
62
+        FileUser userSession = SecurityUtils.getUserSession();
63
+        if (userSession != null) {
64
+            onFile.setUserId(userSession.getId());
65
+            onFile.setUserName(userSession.getName());
66
+        }
67
+        onFile.setCreatedTime(sdf.format(new Date()));
52 68
         onFileService.save(onFile);
53 69
 
54 70
         map.put("version", version);

+ 38
- 1
src/main/java/com/oo/demo/service/FileService.java Просмотреть файл

@@ -3,6 +3,8 @@ package com.oo.demo.service;
3 3
 import com.alibaba.fastjson.JSON;
4 4
 import com.alibaba.fastjson.JSONArray;
5 5
 import com.alibaba.fastjson.JSONObject;
6
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
7
+import com.oo.demo.dao.OnFileMapper;
6 8
 import com.oo.demo.entity.OnFile;
7 9
 import com.oo.demo.entity.WebsocketResult;
8 10
 import com.oo.onlyoffice.api.OnlyServiceAPI;
@@ -31,10 +33,18 @@ public class FileService {
31 33
     private OnlyServiceAPI onlyServiceAPI;
32 34
     @Autowired
33 35
     private DemoService demoService;
34
-
36
+    @Autowired
37
+    private OnFileService onFileService;
35 38
 
36 39
     /**
37 40
      * 文档服务器 保存文件回调
41
+     * Defines the status of the document. Can have the following values:
42
+     * 1 - document is being edited,
43
+     * 2 - document is ready for saving,
44
+     * 3 - document saving error has occurred,
45
+     * 4 - document is closed with no changes,
46
+     * 6 - document is being edited, but the current document state is saved,
47
+     * 7 - error has occurred while force saving the document.
38 48
      *
39 49
      * @param jsonObject
40 50
      */
@@ -61,6 +71,11 @@ public class FileService {
61 71
                 //文件id
62 72
                 String fileId = onlyServiceAPI.getFileId(key);
63 73
                 log.info("fileId:" + JSON.toJSONString(fileId));
74
+                if (fileId != null && !"".equals(fileId)) {
75
+                    //查询之前FileId对应的文件信息
76
+                    OnFile onfile = onFileService.getFileById(fileId);
77
+                    jsonObject.put("caseId", onfile.getCaseId());
78
+                }
64 79
                 //判断是否是最后一人进行保存
65 80
                 int users = onlyServiceAPI.getUserNum(key);
66 81
 //                if (users > 1) {
@@ -77,6 +92,8 @@ public class FileService {
77 92
                 }
78 93
                 //处理文件的保存
79 94
                 OnFile file = onlyServiceAPI.handlerStatus(jsonObject);
95
+                //查询相同案件最新版本的文件信息
96
+                file = getNewFileInofoByCaseId(file.getCaseId());
80 97
                 result = WebsocketResult.builder().onFile(file).userId(SecurityUtils.getUserSession().getId()).build();
81 98
                 log.info("处理文件的保存:" + JSON.toJSONString(jsonObject));
82 99
                 log.info("保存文件结束");
@@ -107,5 +124,25 @@ public class FileService {
107 124
         return result;
108 125
     }
109 126
 
127
+    @Autowired
128
+    OnFileMapper onFileMapper;
110 129
 
130
+    /**
131
+     * 查询相同案件最新版本的文件信息
132
+     *
133
+     * @param caseId
134
+     * @return
135
+     */
136
+    private OnFile getNewFileInofoByCaseId(String caseId) {
137
+        OnFile file = new OnFile();
138
+        QueryWrapper<OnFile> fileQueryWrapper = new QueryWrapper<>();
139
+        fileQueryWrapper.eq("case_id", caseId);
140
+        fileQueryWrapper.orderByDesc("created_time");
141
+        List<OnFile> onFiles = onFileMapper.selectList(fileQueryWrapper);
142
+        if (onFiles != null && onFiles.size() > 0) {
143
+            file = onFiles.get(0);
144
+        }
145
+        log.info("caseId:" + caseId + ":fileinfo:" + JSON.toJSONString(file));
146
+        return file;
147
+    }
111 148
 }

+ 17
- 1
src/main/java/com/oo/demo/service/OnFileService.java Просмотреть файл

@@ -8,11 +8,27 @@ import java.io.File;
8 8
 
9 9
 
10 10
 public interface OnFileService extends IService<OnFile> {
11
-
11
+    /**
12
+     * 保存onlyoffice文件
13
+     * @param bytes
14
+     * @param fileType
15
+     * @return
16
+     * @throws Exception
17
+     */
12 18
     String saveFile(byte[] bytes, String fileType) throws Exception;
13 19
 
20
+    /**
21
+     * 删除onlyoffice文件
22
+     * @param id
23
+     */
14 24
     void removeFile(String id);
15 25
 
26
+    /**
27
+     * 下载onlyoffice文件
28
+     * @param id
29
+     * @param isBrowser
30
+     * @param response
31
+     */
16 32
     void download(String id, String isBrowser, HttpServletResponse response);
17 33
 
18 34
     /**

+ 10
- 2
src/main/java/com/oo/onlyoffice/api/OnlyServiceAPI.java Просмотреть файл

@@ -24,7 +24,15 @@ public interface OnlyServiceAPI {
24 24
      * @param collaborativeEditing 是否协同编辑
25 25
      * @return 配置信息
26 26
      */
27
-    Map openDocument(Map<String, Object> map, String mode, boolean collaborativeEditing);
27
+    /**
28
+     * 打开文件并获取指定的config配置信息
29
+     * @param map
30
+     * @param mode
31
+     * @param collaborativeEditing
32
+     * @param clientType
33
+     * @return
34
+     */
35
+    Map openDocument(Map<String, Object> map, String mode, boolean collaborativeEditing,String clientType);
28 36
 
29 37
 
30 38
 
@@ -87,7 +95,7 @@ public interface OnlyServiceAPI {
87 95
     int getUserNum(String key);
88 96
 
89 97
     /**
90
-     * 获取文件id
98
+     * 通过key获取文件id
91 99
      * @return
92 100
      */
93 101
     String getFileId(String key);

+ 28
- 13
src/main/java/com/oo/onlyoffice/api/impl/OnlyServiceAPIImpl.java Просмотреть файл

@@ -69,7 +69,7 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
69 69
      * @return
70 70
      */
71 71
     @Override
72
-    public Map openDocument(Map<String, Object> map, String mode, boolean collaborativeEditing) {
72
+    public Map openDocument(Map<String, Object> map, String mode, boolean collaborativeEditing, String clientType) {
73 73
         long fileSize = (long) map.get("fileSize");
74 74
 
75 75
         if (fileSize > onlyProperties.getMaxSize()) {
@@ -78,34 +78,32 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
78 78
         }
79 79
 
80 80
         if (EDIT.equals(mode)) {
81
-            return documentEdit(map, collaborativeEditing);
81
+            return documentEdit(map, collaborativeEditing, clientType);
82 82
         }
83 83
         if (VIEW.equals(mode)) {
84
-            return documentView(map);
84
+            return documentView(map, clientType);
85 85
         }
86 86
         return null;
87 87
     }
88 88
 
89
-    private Map documentEdit(Map<String, Object> map, boolean collaborativeEditing) {
90
-        FileConfig fileConfigDTO = openEditConfig(map, "edit", collaborativeEditing);
89
+    private Map documentEdit(Map<String, Object> map, boolean collaborativeEditing, String clientType) {
90
+        FileConfig fileConfigDTO = openEditConfig(map, "edit", collaborativeEditing,clientType);
91 91
         String json = JSON.toJSONString(fileConfigDTO);
92
-
93 92
         Map<String, Object> config = JSON.parseObject(json, Map.class);
94
-
95
-
93
+        config.put("type", clientType);
96 94
         return config;
97 95
     }
98 96
 
99 97
 
100
-    private Map documentView(Map<String, Object> map) {
101
-        FileConfig fileConfigDTO = openEditConfig(map, "view", false);
98
+    private Map documentView(Map<String, Object> map,String clientType) {
99
+        FileConfig fileConfigDTO = openEditConfig(map, "view", false,clientType);
102 100
         String json = JSON.toJSONString(fileConfigDTO);
103 101
         Map<String, Object> config = JSON.parseObject(json, Map.class);
104
-
102
+        config.put("type", clientType);
105 103
         return config;
106 104
     }
107 105
 
108
-    private FileConfig openEditConfig(Map<String, Object> map, String mode, boolean collaborativeEditing) {
106
+    private FileConfig openEditConfig(Map<String, Object> map, String mode, boolean collaborativeEditing,String clientType) {
109 107
         try {
110 108
             map.put("mode", mode);
111 109
             log.info("开始生成文件信息");
@@ -113,7 +111,7 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
113 111
             FileMetadata tempFileInfo = fileHandler.handlerFile(map, collaborativeEditing);
114 112
             //生成配置文件 TODO: 控制文件权限
115 113
             log.info("开始生成编辑器配置信息");
116
-            FileConfig fileConfigDTO = onlyOfficeConfigFactory.buildInitConfig(tempFileInfo.getUrl(), mode, tempFileInfo.getKey(), tempFileInfo.getOldName());
114
+            FileConfig fileConfigDTO = onlyOfficeConfigFactory.buildInitConfig(tempFileInfo.getUrl(), mode, tempFileInfo.getKey(), tempFileInfo.getOldName(),clientType);
117 115
             log.info("生成编辑器配置信息结束");
118 116
             // TODO: 添加更多详细的自定义信息
119 117
             return fileConfigDTO;
@@ -167,6 +165,7 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
167 165
         int status = jsonObject.getIntValue("status");
168 166
         log.info("status[{}]:{}", status, jsonObject);
169 167
         String key = (String) jsonObject.get("key");
168
+        String caseId = jsonObject.getString("caseId");
170 169
 
171 170
         FileHandler tempFileHandler = tempFileContext.getHandlerByKey(key);
172 171
         if (Objects.nonNull(tempFileHandler)) {
@@ -189,6 +188,10 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
189 188
                 if (!tempFile.isPresent()) {
190 189
                     throw new RuntimeException("文件元信息不存在");
191 190
                 }
191
+                Map<String, Object> fileInfoMap = tempFile.get().getFileInfo();
192
+                if (caseId != null) {
193
+                    fileInfoMap.put("caseId", caseId);
194
+                }
192 195
                 saveFileProcessor.saveBeforeInitialization(tempFile.get().getFileInfo(), fileByte, fileExtension);
193 196
 
194 197
                 // 保存文件
@@ -287,6 +290,18 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
287 290
         int i = iskey(jsonObject.getString("key"), null);
288 291
         //如果没有人使用当前文档,清空临时信息
289 292
         if (i <= 0) {
293
+            //清空之前保存临时文件
294
+            String key = jsonObject.getString("key");
295
+            FileHandler tempFileHandler = tempFileContext.getHandlerByKey(key);
296
+            if (Objects.nonNull(tempFileHandler)) {
297
+                String url = jsonObject.getString("url");
298
+                String changesurl = jsonObject.getString("changesurl");
299
+                log.info("编辑后的文档下载路径url:" + url);
300
+                log.info("文件变动信息文件url:" + changesurl);
301
+                // 下载修改后文件
302
+                byte[] fileByte = FileUtil.getFileByte(url);
303
+                saveFileProcessor.save(tempFile.getFileInfo(), fileByte, null, jsonObject.getString("key"));
304
+            }
290 305
             removeTempFile(jsonObject);
291 306
             String id = (String) cache.get("getID_" + jsonObject.getString("key"));
292 307
             cache.remove("getID_" + id);

+ 7
- 3
src/main/java/com/oo/onlyoffice/core/FileConfigFactory.java Просмотреть файл

@@ -43,7 +43,7 @@ public class FileConfigFactory implements OnlyOfficeConfigFactory {
43 43
      * @return 配置信息
44 44
      */
45 45
     @Override
46
-    public FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName) {
46
+    public FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName,String clientType) {
47 47
 
48 48
         Map<String, Object> map = new HashMap<>();
49 49
 
@@ -74,7 +74,7 @@ public class FileConfigFactory implements OnlyOfficeConfigFactory {
74 74
         String callBackUrl = onlyProperties.getLocalhostAddress() + onlyProperties.getCallBackUrl();
75 75
 
76 76
         EditorConfig editorConfig = new EditorConfig(callBackUrl, mode);
77
-        editorConfig.setFileCustomization(getFileCustomization(mode));
77
+        editorConfig.setFileCustomization(getFileCustomization(mode,clientType));
78 78
         editorConfig.setFileUser(user);
79 79
         editorConfig.setPlugins(getPlugins());
80 80
 
@@ -112,11 +112,15 @@ public class FileConfigFactory implements OnlyOfficeConfigFactory {
112 112
         return LoadConfigUtil.getCustomization();
113 113
     }
114 114
 
115
-    private FileCustomization getFileCustomization(String mode) {
115
+    private FileCustomization getFileCustomization(String mode,String clientType) {
116 116
         FileCustomization customization = LoadConfigUtil.getCustomization();
117 117
         if (mode != null && !(mode.trim()).equals("") && mode.equals("edit")) {
118 118
             customization.setAutosave(true);
119 119
         }
120
+        customization.setMobileForceView(false);
121
+        if(clientType!=null&&clientType!=""&&"mobile".equals(clientType)){
122
+            customization.setMobileForceView(true);
123
+        }
120 124
         return customization;
121 125
     }
122 126
 

+ 1
- 1
src/main/java/com/oo/onlyoffice/core/OnlyOfficeConfigFactory.java Просмотреть файл

@@ -14,5 +14,5 @@ public interface OnlyOfficeConfigFactory {
14 14
      * @param fileName 文件名称
15 15
      * @return onlyOffice必须信息
16 16
      */
17
-    FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName);
17
+    FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName,String clientType);
18 18
 }

+ 1
- 0
src/main/java/com/oo/onlyoffice/dto/edit/FileCustomization.java Просмотреть файл

@@ -202,6 +202,7 @@ public class FileCustomization implements Serializable {
202 202
      * 默认值为100。
203 203
      */
204 204
     private Integer zoom;
205
+    private Boolean mobileForceView;
205 206
 
206 207
 
207 208