inleft
2022-02-15 d734432a8bbbf863dc3de305f56e831c56ac767a
commit | author | age
9bcb19 1 /*
I 2 Copyright [2020] [https://www.xiaonuo.vip]
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8   http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15
16 Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
17
18 1.请不要删除和修改根目录下的LICENSE文件。
19 2.请不要删除和修改Snowy源码头部的版权声明。
20 3.请保留源码和相关描述文件的项目出处,作者声明等。
21 4.分发源码时候,请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
22 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
23 6.若您的项目无法满足以上几点,可申请商业授权,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip
24  */
25 package vip.xiaonuo.sys.modular.file.util;
26
27 import cn.hutool.core.io.FileUtil;
28 import cn.hutool.core.lang.Dict;
29 import cn.hutool.extra.spring.SpringUtil;
30 import cn.hutool.json.JSONUtil;
31 import com.alibaba.fastjson.JSONArray;
32 import com.alibaba.fastjson.JSONObject;
33 import com.google.gson.Gson;
34 import vip.xiaonuo.core.consts.SymbolConstant;
35 import vip.xiaonuo.core.file.FileOperator;
36 import vip.xiaonuo.core.file.modular.local.LocalFileOperator;
37 import vip.xiaonuo.sys.config.FileConfig;
38 import vip.xiaonuo.sys.modular.file.result.SysOnlineFileInfoResult;
39
40 import java.io.File;
41 import java.io.FileFilter;
42 import java.io.FileInputStream;
43 import java.io.UnsupportedEncodingException;
44 import java.net.URLEncoder;
45 import java.util.*;
46
47 /**
48  * 在线文档相关工具类
49  *
50  * @author xuyuxiang
51  * @date 2021/3/24 16:12
52  */
53 public class OnlineDocumentUtil {
54
55     private static final String VIEWED_SUFFIX = ".pdf|.djvu|.xps";
56     private static final String EDITED_SUFFIX = ".docx|.xlsx|.csv|.pptx|.txt";
57     private static final String CONVERT_SUFFIX = ".docm|.dotx|.dotm|.dot|.doc|.odt|.fodt|.ott|.xlsm|.xltx|.xltm|.xlt|.xls|.ods|.fods|.ots|.pptm|.ppt|.ppsx|.ppsm|.pps|.potx|.potm|.pot|.odp|.fodp|.otp|.rtf|.mht|.html|.htm|.epub";
58
59     public static final List<String> DOCUMENT_SUFFIX = Arrays.asList(".doc", ".docx", ".docm", ".dot", ".dotx", ".dotm", ".odt", ".fodt", ".ott", ".rtf", ".txt", ".html", ".htm",
60             ".mht", ".pdf", ".djvu", ".fb2", ".epub", ".xps");
61
62     public static final List<String> SPREADSHEET_SUFFIX = Arrays.asList(".xls", ".xlsx", ".xlsm", ".xlt", ".xltx", ".xltm", ".ods", ".fods", ".ots", ".csv");
63
64     public static final List<String> Presentation_SUFFIX = Arrays.asList(".pps", ".ppsx", ".ppsm",".ppt", ".pptx", ".pptm", ".pot", ".potx", ".potm", ".odp", ".fodp", ".otp");
65
66
67     public static List<String> getFileSuffix() {
68         List<String> res = new ArrayList<>();
69         res.addAll(getViewedSuffix());
70         res.addAll(getEditedSuffix());
71         res.addAll(getConvertSuffix());
72         return res;
73     }
74
75     public static List<String> getViewedSuffix() {
76         return Arrays.asList(VIEWED_SUFFIX.split("\\|"));
77     }
78
79     public static List<String> getEditedSuffix() {
80         return Arrays.asList(EDITED_SUFFIX.split("\\|"));
81     }
82
83     public static List<String> getConvertSuffix() {
84         return Arrays.asList(CONVERT_SUFFIX.split("\\|"));
85     }
86
87     public static String getFileType(String fileOriginName) {
88         String suffix = SymbolConstant.PERIOD + FileUtil.getSuffix(fileOriginName);
89         if (DOCUMENT_SUFFIX.contains(suffix)) return "Text";
90         if (SPREADSHEET_SUFFIX.contains(suffix)) return "Spreadsheet";
91         if (Presentation_SUFFIX.contains(suffix)) return "Presentation";
92         return "Text";
93     }
94
95     public static String getFileUri(String fileId, String fileName) {
96         try {
97             String filePath = "sysFileInfo/download?id="+ fileId +"&name=" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString()).replace("+", "%20");
98
99             return filePath;
100         } catch (UnsupportedEncodingException e) {
101             return "";
102         }
103     }
104
105     public static String getCallback(String fileId, String fileSuffix) {
106         return "sysFileInfo/track?fileObjectName=" + fileId + SymbolConstant.PERIOD + fileSuffix + "&id=" + fileId;
107     }
108
109     public static String getStoragePath(String fileIdOrObjectName) {
110         String directory = FilesRootPath();
111         return directory + File.separator + FileConfig.DEFAULT_BUCKET + File.separator + fileIdOrObjectName;
112     }
113
114     public static String FilesRootPath() {
115         LocalFileOperator localFileOperator = (LocalFileOperator) SpringUtil.getBean(FileOperator.class);
116         Dict localClientDict = (Dict) localFileOperator.getClient();
117         String currentSavePath = localClientDict.getStr("currentSavePath");
118         File file = new File(currentSavePath);
119
120         if (!file.exists()) {
121             file.mkdirs();
122         }
123         return currentSavePath;
124     }
125
126     public static String[] getHistory(SysOnlineFileInfoResult sysOnlineFileInfoResult) {
127         String histDir = OnlineDocumentUtil.getHistoryDir(OnlineDocumentUtil.getStoragePath(sysOnlineFileInfoResult.getFileId()));
128         if (getFileVersion(histDir) > 0) {
129             Integer curVer = getFileVersion(histDir);
130
131             Set<Object> hist = new HashSet<Object>();
132             Map<String, Object> histData = new HashMap<String, Object>();
133
134             for (Integer i = 0; i <= curVer; i++) {
135                 Map<String, Object> obj = new HashMap<String, Object>();
136                 Map<String, Object> dataObj = new HashMap<String, Object>();
137                 String verDir = getVersionDir(histDir, i + 1);
138
139                 try {
140                     String key = null;
141
142                     key = i == curVer ? sysOnlineFileInfoResult.document.key : readFileToEnd(new File(verDir + File.separator + "key.txt"));
143
144                     obj.put("key", key);
145                     obj.put("version", i);
146
147                     if (i == 0) {
148                         String createdInfo = readFileToEnd(new File(histDir + File.separator + "createdInfo.json"));
149                         JSONObject json = (JSONObject) JSONUtil.parse(createdInfo);
150
151                         obj.put("created", json.get("created"));
152                         Map<String, Object> user = new HashMap<String, Object>();
153                         user.put("id", json.get("id"));
154                         user.put("name", json.get("name"));
155                         obj.put("user", user);
156                     }
157
158                     dataObj.put("key", key);
159                     dataObj.put("url", i == curVer ? sysOnlineFileInfoResult.document.url : getStoragePath(verDir + File.separator + "prev" + FileUtil.getSuffix(sysOnlineFileInfoResult.getDocument().title)));
160                     dataObj.put("version", i);
161
162                     if (i > 0) {
163                         JSONObject changes = (JSONObject) JSONUtil.parse(readFileToEnd(new File(getVersionDir(histDir, i) + File.separator + "changes.json")));
164                         JSONObject change = (JSONObject) ((JSONArray) changes.get("changes")).get(0);
165
166                         obj.put("changes", changes.get("changes"));
167                         obj.put("serverVersion", changes.get("serverVersion"));
168                         obj.put("created", change.get("created"));
169                         obj.put("user", change.get("user"));
170
171                         Map<String, Object> prev = (Map<String, Object>) histData.get(Integer.toString(i - 1));
172                         Map<String, Object> prevInfo = new HashMap<String, Object>();
173                         prevInfo.put("key", prev.get("key"));
174                         prevInfo.put("url", prev.get("url"));
175                         dataObj.put("previous", prevInfo);
176                         dataObj.put("changesUrl", getStoragePath(getVersionDir(histDir, i) + File.separator + "diff.zip"));
177                     }
178
179                     hist.add(obj);
180                     histData.put(Integer.toString(i), dataObj);
181
182                 } catch (Exception ex) {
183                 }
184             }
185
186             Map<String, Object> histObj = new HashMap<String, Object>();
187             histObj.put("currentVersion", curVer);
188             histObj.put("history", hist);
189
190             Gson gson = new Gson();
191             return new String[]{gson.toJson(histObj), gson.toJson(histData)};
192         }
193         return new String[]{"", ""};
194     }
195
196     public static String getHistoryDir(String storagePath) {
197         return storagePath += "-hist";
198     }
199
200     public static String getVersionDir(String histPath, Integer version) {
201         return histPath + File.separator + Integer.toString(version);
202     }
203
204     public static Integer getFileVersion(String historyPath) {
205         File dir = new File(historyPath);
206
207         if (!dir.exists()) return 0;
208
209         File[] dirs = dir.listFiles(new FileFilter() {
210             @Override
211             public boolean accept(File pathname) {
212                 return pathname.isDirectory();
213             }
214         });
215
216         return dirs.length;
217     }
218
219     private static String readFileToEnd(File file) {
220         String output = "";
221         try {
222             try(FileInputStream is = new FileInputStream(file))
223             {
224                 Scanner scanner = new Scanner(is);
225                 scanner.useDelimiter("\\A");
226                 while (scanner.hasNext()) {
227                     output += scanner.next();
228                 }
229                 scanner.close();
230             }
231         } catch (Exception e) { }
232         return output;
233     }
234
235     public static void deleteFileHistory(String fileId) {
236         // 判断文件存在不存在
237         String histDir = OnlineDocumentUtil.getHistoryDir(OnlineDocumentUtil.getStoragePath(fileId));
238         File hisDirFile = FileUtil.file(histDir);
239         if (!FileUtil.exist(hisDirFile)) {
240             return;
241         }
242
243         // 删除文件
244         FileUtil.del(hisDirFile);
245     }
246 }