fix(文件编辑): 文件编辑代码优化

This commit is contained in:
MAC 2022-05-15 16:50:46 +08:00
parent 9c78b30143
commit 7b69ca71be
7 changed files with 229 additions and 193 deletions

View File

@ -1,5 +1,6 @@
package com.qiwenshare.file.component; package com.qiwenshare.file.component;
import com.alibaba.fastjson.JSON;
import com.qiwenshare.common.util.math.CalculatorUtils; import com.qiwenshare.common.util.math.CalculatorUtils;
import com.qiwenshare.file.config.jwt.JwtProperties; import com.qiwenshare.file.config.jwt.JwtProperties;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
@ -14,6 +15,7 @@ import javax.annotation.Resource;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import java.util.Date; import java.util.Date;
import java.util.Map;
@Component @Component
public class JwtComp { public class JwtComp {
@ -32,8 +34,8 @@ public class JwtComp {
} }
// 创建jwt // 创建jwt
public String createJWT(String subject) throws Exception { public String createJWT(Map<String, Object> param) {
String subject = JSON.toJSONString(param);
// 生成JWT的时间 // 生成JWT的时间
long nowTime = System.currentTimeMillis(); long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime); Date nowDate = new Date(nowTime);

View File

@ -147,16 +147,17 @@ public class OfficeController {
UserFile userFile = userFileService.getById(previewOfficeFileDTO.getUserFileId()); UserFile userFile = userFileService.getById(previewOfficeFileDTO.getUserFileId());
String baseUrl = request.getScheme()+"://"+ deploymentHost + ":" + port + request.getContextPath(); String baseUrl = request.getScheme()+"://"+ deploymentHost + ":" + port + request.getContextPath();
String query = "?type=show&token="+token;
FileModel file = new FileModel(userFile.getFileName() + "." + userFile.getExtendName(), String callbackUrl = baseUrl + "/office/IndexServlet" + query;
FileModel file = new FileModel(userFile.getUserFileId(),
userFile.getFileName() + "." + userFile.getExtendName(),
previewOfficeFileDTO.getPreviewUrl(), previewOfficeFileDTO.getPreviewUrl(),
userFile.getUploadTime(), userFile.getUploadTime(),
String.valueOf(loginUser.getUserId()), String.valueOf(loginUser.getUserId()),
loginUser.getUsername(), loginUser.getUsername(),
callbackUrl,
"view"); "view");
String query = "?type=show&token="+token;
file.editorConfig.callbackUrl= baseUrl + "/office/IndexServlet" + query;
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("file",file); jsonObject.put("file",file);
jsonObject.put("docserviceApiUrl", ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.api")); jsonObject.put("docserviceApiUrl", ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.api"));
@ -185,17 +186,17 @@ public class OfficeController {
String baseUrl = request.getScheme()+"://"+ deploymentHost + ":" + port + request.getContextPath(); String baseUrl = request.getScheme()+"://"+ deploymentHost + ":" + port + request.getContextPath();
log.info("回调地址baseUrl" + baseUrl); log.info("回调地址baseUrl" + baseUrl);
String query = "?type=edit&userFileId="+userFile.getUserFileId()+"&token="+token;
String callbackUrl = baseUrl + "/office/IndexServlet" + query;
FileModel file = new FileModel(userFile.getFileName() + "." + userFile.getExtendName(), FileModel file = new FileModel(userFile.getUserFileId(),
userFile.getFileName() + "." + userFile.getExtendName(),
editOfficeFileDTO.getPreviewUrl(), editOfficeFileDTO.getPreviewUrl(),
userFile.getUploadTime(), userFile.getUploadTime(),
String.valueOf(loginUser.getUserId()), String.valueOf(loginUser.getUserId()),
loginUser.getUsername(), loginUser.getUsername(),
callbackUrl,
"edit"); "edit");
file.changeType(request.getParameter("mode"), "edit");
String query = "?type=edit&userFileId="+userFile.getUserFileId()+"&token="+token;
file.editorConfig.callbackUrl= baseUrl + "/office/IndexServlet" + query;
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("file",file); jsonObject.put("file",file);

View File

@ -19,6 +19,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -68,7 +69,11 @@ public class UserController {
@Parameter(description = "登录密码") String password){ @Parameter(description = "登录密码") String password){
RestResult<UserLoginVo> restResult = new RestResult<UserLoginVo>(); RestResult<UserLoginVo> restResult = new RestResult<UserLoginVo>();
String salt = userService.getSaltByTelephone(telephone); String salt = userService.getSaltByTelephone(telephone);
String hashPassword = new SimpleHash("MD5", password, salt, 1024).toHex(); // String hashPassword = new SimpleHash("MD5", password, salt, 1024).toHex();
String hashPassword = password + salt;
for (int i = 0; i < 1024; i++) {
hashPassword = DigestUtils.md5Hex(hashPassword);
}
UserBean result = userService.selectUserByTelephoneAndPassword(telephone, hashPassword); UserBean result = userService.selectUserByTelephoneAndPassword(telephone, hashPassword);
if (result == null) { if (result == null) {
@ -79,7 +84,7 @@ public class UserController {
param.put("userId", result.getUserId()); param.put("userId", result.getUserId());
String token = ""; String token = "";
try { try {
token = jwtComp.createJWT(JSON.toJSONString(param)); token = jwtComp.createJWT(param);
} catch (Exception e) { } catch (Exception e) {
log.info("登录失败:{}", e); log.info("登录失败:{}", e);
return RestResult.fail().message("创建token失败"); return RestResult.fail().message("创建token失败");
@ -98,7 +103,6 @@ public class UserController {
} }
@Operation(summary = "检查用户登录信息", description = "验证token的有效性", tags = {"user"}) @Operation(summary = "检查用户登录信息", description = "验证token的有效性", tags = {"user"})
@GetMapping("/checkuserlogininfo") @GetMapping("/checkuserlogininfo")
@ResponseBody @ResponseBody

View File

@ -19,15 +19,12 @@
package com.qiwenshare.file.helper; package com.qiwenshare.file.helper;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwenshare.file.constant.FileType; import com.qiwenshare.file.component.JwtComp;
import org.primeframework.jwt.Signer; import com.qiwenshare.file.service.OfficeConverterService;
import org.primeframework.jwt.Verifier; import org.springframework.stereotype.Component;
import org.primeframework.jwt.domain.JWT;
import org.primeframework.jwt.hmac.HMACSigner;
import org.primeframework.jwt.hmac.HMACVerifier;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.io.*;
@ -38,8 +35,13 @@ import java.net.URLEncoder;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
@Component
public class DocumentManager public class DocumentManager
{ {
@Resource
private JwtComp jwtComp;
@Resource
private OfficeConverterService officeConverterService;
private static HttpServletRequest request; private static HttpServletRequest request;
public static void Init(HttpServletRequest req, HttpServletResponse resp) public static void Init(HttpServletRequest req, HttpServletResponse resp)
@ -290,13 +292,13 @@ public class DocumentManager
} }
} }
public static ArrayList<Map<String, Object>> GetFilesInfo(){ public ArrayList<Map<String, Object>> GetFilesInfo(){
ArrayList<Map<String, Object>> files = new ArrayList<>(); ArrayList<Map<String, Object>> files = new ArrayList<>();
for(File file : GetStoredFiles(null)){ for(File file : GetStoredFiles(null)){
Map<String, Object> map = new LinkedHashMap<>(); Map<String, Object> map = new LinkedHashMap<>();
map.put("version", GetFileVersion(file.getName(), null)); map.put("version", GetFileVersion(file.getName(), null));
map.put("id", ServiceConverter.GenerateRevisionId(CurUserHostAddress(null) + "/" + file.getName() + "/" + Long.toString(new File(StoragePath(file.getName(), null)).lastModified()))); map.put("id", officeConverterService.GenerateRevisionId(CurUserHostAddress(null) + "/" + file.getName() + "/" + Long.toString(new File(StoragePath(file.getName(), null)).lastModified())));
map.put("contentLength", new BigDecimal(String.valueOf((file.length()/1024.0))).setScale(2, RoundingMode.HALF_UP) + " KB"); map.put("contentLength", new BigDecimal(String.valueOf((file.length()/1024.0))).setScale(2, RoundingMode.HALF_UP) + " KB");
map.put("pureContentLength", file.length()); map.put("pureContentLength", file.length());
map.put("title", file.getName()); map.put("title", file.getName());
@ -307,7 +309,7 @@ public class DocumentManager
return files; return files;
} }
public static ArrayList<Map<String, Object>> GetFilesInfo(String fileId){ public ArrayList<Map<String, Object>> GetFilesInfo(String fileId){
ArrayList<Map<String, Object>> file = new ArrayList<>(); ArrayList<Map<String, Object>> file = new ArrayList<>();
for (Map<String, Object> map : GetFilesInfo()){ for (Map<String, Object> map : GetFilesInfo()){
@ -356,50 +358,52 @@ public class DocumentManager
} }
} }
public static String GetInternalExtension(FileType fileType) // public static String GetInternalExtension(FileType fileType)
{ // {
if (fileType.equals(FileType.Word)) // if (fileType.equals(FileType.Word))
return ".docx"; // return ".docx";
//
// if (fileType.equals(FileType.Cell))
// return ".xlsx";
//
// if (fileType.equals(FileType.Slide))
// return ".pptx";
//
// return ".docx";
// }
if (fileType.equals(FileType.Cell)) // public static String CreateToken(Map<String, Object> payloadClaims)
return ".xlsx"; // {
// jwtComp.createJWT(payloadClaims);
if (fileType.equals(FileType.Slide)) //
return ".pptx"; // try
// {
return ".docx"; // Signer signer = HMACSigner.newSHA256Signer(GetTokenSecret());
} // JWT jwt = new JWT();
// for (String key : payloadClaims.keySet())
public static String CreateToken(Map<String, Object> payloadClaims) // {
{ // jwt.addClaim(key, payloadClaims.get(key));
try // }
{ // return JWT.getEncoder().encode(jwt, signer);
Signer signer = HMACSigner.newSHA256Signer(GetTokenSecret()); // }
JWT jwt = new JWT(); // catch (Exception e)
for (String key : payloadClaims.keySet()) // {
{ // return "";
jwt.addClaim(key, payloadClaims.get(key)); // }
} // }
return JWT.getEncoder().encode(jwt, signer); //
} // public static JWT ReadToken(String token)
catch (Exception e) // {
{ // try
return ""; // {
} // Verifier verifier = HMACVerifier.newVerifier(GetTokenSecret());
} // return JWT.getDecoder().decode(token, verifier);
// }
public static JWT ReadToken(String token) // catch (Exception exception)
{ // {
try // return null;
{ // }
Verifier verifier = HMACVerifier.newVerifier(GetTokenSecret()); // }
return JWT.getDecoder().decode(token, verifier);
}
catch (Exception exception)
{
return null;
}
}
public static Boolean TokenEnabled() public static Boolean TokenEnabled()
{ {

View File

@ -18,24 +18,33 @@
package com.qiwenshare.file.helper; package com.qiwenshare.file.helper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson; import com.google.gson.Gson;
import org.primeframework.jwt.domain.JWT; import com.qiwenshare.file.component.JwtComp;
import com.qiwenshare.file.service.OfficeConverterService;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.*; import java.io.*;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Scanner; import java.util.Scanner;
@Component
public class TrackManager { public class TrackManager {
@Resource
private JwtComp jwtComp;
@Resource
private OfficeConverterService officeConverterService;
private static final String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header"); private static final String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header");
public static JSONObject readBody(HttpServletRequest request, PrintWriter writer) throws Exception { public JSONObject readBody(HttpServletRequest request, PrintWriter writer) throws Exception {
String bodyString = ""; String bodyString = "";
try { try {
@ -78,37 +87,45 @@ public class TrackManager {
throw new Exception("{\"error\":1,\"message\":\"JWT expected\"}"); throw new Exception("{\"error\":1,\"message\":\"JWT expected\"}");
} }
JWT jwt = DocumentManager.ReadToken(token); Claims claims = jwtComp.parseJWT(token);
if (jwt == null) {
writer.write("{\"error\":1,\"message\":\"JWT validation failed\"}");
throw new Exception("{\"error\":1,\"message\":\"JWT validation failed\"}");
}
if (jwt.getObject("payload") != null) {
try {
@SuppressWarnings("unchecked") LinkedHashMap<String, Object> payload =
(LinkedHashMap<String, Object>)jwt.getObject("payload");
jwt.claims = payload;
} catch (Exception ex) {
writer.write("{\"error\":1,\"message\":\"Wrong payload\"}");
throw ex;
}
}
try { try {
Gson gson = new Gson(); body = JSONObject.parseObject(JSON.toJSONString(claims));
body = JSONObject.parseObject(gson.toJson(jwt.claims));
} catch (Exception ex) { } catch (Exception ex) {
writer.write("JSONParser.parse error:" + ex.getMessage()); writer.write("JSONParser.parse error:" + ex.getMessage());
throw ex; throw ex;
} }
if (body == null) {
writer.write("{\"error\":1,\"message\":\"JWT validation failed\"}");
throw new Exception("{\"error\":1,\"message\":\"JWT validation failed\"}");
}
// if (jwt.getObject("payload") != null) {
// try {
// @SuppressWarnings("unchecked") LinkedHashMap<String, Object> payload =
// (LinkedHashMap<String, Object>)jwt.getObject("payload");
//
// jwt.claims = payload;
// } catch (Exception ex) {
// writer.write("{\"error\":1,\"message\":\"Wrong payload\"}");
// throw ex;
// }
// }
//
// try {
// Gson gson = new Gson();
// body = JSONObject.parseObject(gson.toJson(jwt.claims));
// } catch (Exception ex) {
// writer.write("JSONParser.parse error:" + ex.getMessage());
// throw ex;
// }
} }
return body; return body;
} }
public static void processSave(JSONObject body, String fileName, String userAddress) throws Exception { public void processSave(JSONObject body, String fileName, String userAddress) throws Exception {
String downloadUri = (String) body.get("url"); String downloadUri = (String) body.get("url");
String changesUri = (String) body.get("changesurl"); String changesUri = (String) body.get("changesurl");
String key = (String) body.get("key"); String key = (String) body.get("key");
@ -119,7 +136,7 @@ public class TrackManager {
if (!curExt.equals(downloadExt)) { if (!curExt.equals(downloadExt)) {
try { try {
String newFileUri = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), null, false); String newFileUri = officeConverterService.GetConvertedUri(downloadUri, downloadExt, curExt, officeConverterService.GenerateRevisionId(downloadUri), null, false);
if (newFileUri.isEmpty()) { if (newFileUri.isEmpty()) {
newFileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress); newFileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
} else { } else {
@ -167,7 +184,7 @@ public class TrackManager {
} }
} }
public static void processForceSave(JSONObject body, String fileName, String userAddress) throws Exception { public void processForceSave(JSONObject body, String fileName, String userAddress) throws Exception {
String downloadUri = (String) body.get("url"); String downloadUri = (String) body.get("url");
@ -177,7 +194,7 @@ public class TrackManager {
if (!curExt.equals(downloadExt)) { if (!curExt.equals(downloadExt)) {
try { try {
String newFileUri = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), null, false); String newFileUri = officeConverterService.GetConvertedUri(downloadUri, downloadExt, curExt, officeConverterService.GenerateRevisionId(downloadUri), null, false);
if (newFileUri.isEmpty()) { if (newFileUri.isEmpty()) {
newFileName = true; newFileName = true;
} else { } else {
@ -249,7 +266,7 @@ public class TrackManager {
connection.disconnect(); connection.disconnect();
} }
public static void commandRequest(String method, String key) throws Exception { public void commandRequest(String method, String key) throws Exception {
String DocumentCommandUrl = ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.command"); String DocumentCommandUrl = ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.command");
URL url = new URL(DocumentCommandUrl); URL url = new URL(DocumentCommandUrl);
@ -264,11 +281,11 @@ public class TrackManager {
{ {
Map<String, Object> payloadMap = new HashMap<String, Object>(); Map<String, Object> payloadMap = new HashMap<String, Object>();
payloadMap.put("payload", params); payloadMap.put("payload", params);
headerToken = DocumentManager.CreateToken(payloadMap); headerToken = jwtComp.createJWT(payloadMap);
connection.setRequestProperty(DocumentJwtHeader.equals("") ? "Authorization" : DocumentJwtHeader, "Bearer " + headerToken); connection.setRequestProperty(DocumentJwtHeader.equals("") ? "Authorization" : DocumentJwtHeader, "Bearer " + headerToken);
String token = DocumentManager.CreateToken(params); String token = jwtComp.createJWT(params);
params.put("token", token); params.put("token", token);
} }
@ -290,10 +307,10 @@ public class TrackManager {
if (stream == null) if (stream == null)
throw new Exception("Could not get an answer"); throw new Exception("Could not get an answer");
String jsonString = ServiceConverter.ConvertStreamToString(stream); String jsonString = officeConverterService.ConvertStreamToString(stream);
connection.disconnect(); connection.disconnect();
JSONObject response = ServiceConverter.ConvertStringToJSON(jsonString); JSONObject response = officeConverterService.ConvertStringToJSON(jsonString);
if (!response.get("error").toString().equals("0")){ if (!response.get("error").toString().equals("0")){
throw new Exception(response.toJSONString()); throw new Exception(response.toJSONString());
} }

View File

@ -16,10 +16,17 @@
* *
*/ */
package com.qiwenshare.file.helper; package com.qiwenshare.file.service;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.qiwenshare.file.component.JwtComp;
import com.qiwenshare.file.helper.ConfigManager;
import com.qiwenshare.file.helper.DocumentManager;
import com.qiwenshare.file.helper.FileUtility;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.*; import java.io.*;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -28,8 +35,11 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
public class ServiceConverter @Component
public class OfficeConverterService
{ {
@Resource
private JwtComp jwtComp;
private static int ConvertTimeout = 120000; private static int ConvertTimeout = 120000;
private static final String DocumentConverterUrl = ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.converter"); private static final String DocumentConverterUrl = ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.converter");
private static final String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header"); private static final String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header");
@ -61,7 +71,7 @@ public class ServiceConverter
} }
} }
public static String GetConvertedUri(String documentUri, String fromExtension, String toExtension, String documentRevisionId, String filePass, Boolean isAsync) throws Exception public String GetConvertedUri(String documentUri, String fromExtension, String toExtension, String documentRevisionId, String filePass, Boolean isAsync) throws Exception
{ {
fromExtension = fromExtension == null || fromExtension.isEmpty() ? FileUtility.GetFileExtension(documentUri) : fromExtension; fromExtension = fromExtension == null || fromExtension.isEmpty() ? FileUtility.GetFileExtension(documentUri) : fromExtension;
@ -95,12 +105,12 @@ public class ServiceConverter
if (isAsync) if (isAsync)
map.put("async", body.async); map.put("async", body.async);
String token = DocumentManager.CreateToken(map); String token = jwtComp.createJWT(map);
body.token = token; body.token = token;
Map<String, Object> payloadMap = new HashMap<String, Object>(); Map<String, Object> payloadMap = new HashMap<String, Object>();
payloadMap.put("payload", map); payloadMap.put("payload", map);
headerToken = DocumentManager.CreateToken(payloadMap); headerToken = jwtComp.createJWT(payloadMap);
} }
Gson gson = new Gson(); Gson gson = new Gson();

View File

@ -18,17 +18,15 @@
package com.qiwenshare.file.util; package com.qiwenshare.file.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.qiwenshare.file.helper.DocumentManager; import com.qiwenshare.file.helper.DocumentManager;
import com.qiwenshare.file.helper.FileUtility; import com.qiwenshare.file.helper.FileUtility;
import com.qiwenshare.file.helper.ServiceConverter;
import lombok.Data; import lombok.Data;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
@Data @Data
@ -41,7 +39,7 @@ public class FileModel
public EditorConfig editorConfig; public EditorConfig editorConfig;
public String token; public String token;
public FileModel(String fileName, String fileUrl, String fileModifyTime, String uid, String uname, String mode) public FileModel(String userFileId, String fileName, String fileUrl, String fileModifyTime, String uid, String uname, String callbackUrl, String mode)
{ {
if (fileName == null) fileName = ""; if (fileName == null) fileName = "";
fileName = fileName.trim(); fileName = fileName.trim();
@ -53,12 +51,12 @@ public class FileModel
document.url = fileUrl; document.url = fileUrl;
// document.urlUser = DocumentManager.GetFileUri(fileName, false); // document.urlUser = DocumentManager.GetFileUri(fileName, false);
document.fileType = FileUtility.GetFileExtension(fileName).replace(".", ""); document.fileType = FileUtility.GetFileExtension(fileName).replace(".", "");
document.key = ServiceConverter.GenerateRevisionId(DocumentManager.CurUserHostAddress(null) + "/" + fileName + "/" + fileModifyTime); document.key = Base64.getEncoder().encodeToString((userFileId + "_" + fileModifyTime).getBytes(StandardCharsets.UTF_8));
document.info = new Info(); document.info = new Info();
document.info.favorite = uid != null && !uid.isEmpty() ? uid.equals("uid-2") : null; document.info.favorite = uid != null && !uid.isEmpty() ? uid.equals("uid-2") : null;
editorConfig = new EditorConfig(null); editorConfig = new EditorConfig(null);
// editorConfig.callbackUrl = DocumentManager.GetCallback(fileName); editorConfig.callbackUrl = callbackUrl;
// editorConfig.lang = null; // editorConfig.lang = null;
if (uid != null) editorConfig.user.id = uid; if (uid != null) editorConfig.user.id = uid;
@ -90,90 +88,90 @@ public class FileModel
editorConfig.InitDesktop(document.urlUser); editorConfig.InitDesktop(document.urlUser);
} }
public void BuildToken() // public void BuildToken()
{ // {
Map<String, Object> map = new HashMap<>(); // Map<String, Object> map = new HashMap<>();
map.put("type", type); // map.put("type", type);
map.put("documentType", documentType); // map.put("documentType", documentType);
map.put("document", document); // map.put("document", document);
map.put("editorConfig", editorConfig); // map.put("editorConfig", editorConfig);
//
// token = jwtComp.createJWT(map);
// }
token = DocumentManager.CreateToken(map); // public String[] GetHistory()
} // {
// String histDir = DocumentManager.HistoryDir(DocumentManager.StoragePath(document.title, null));
public String[] GetHistory() // if (DocumentManager.GetFileVersion(histDir) > 0) {
{ // Integer curVer = DocumentManager.GetFileVersion(histDir);
String histDir = DocumentManager.HistoryDir(DocumentManager.StoragePath(document.title, null)); //
if (DocumentManager.GetFileVersion(histDir) > 0) { // List<Object> hist = new ArrayList<>();
Integer curVer = DocumentManager.GetFileVersion(histDir); // Map<String, Object> histData = new HashMap<String, Object>();
//
List<Object> hist = new ArrayList<>(); // for (Integer i = 1; i <= curVer; i++) {
Map<String, Object> histData = new HashMap<String, Object>(); // Map<String, Object> obj = new HashMap<String, Object>();
// Map<String, Object> dataObj = new HashMap<String, Object>();
for (Integer i = 1; i <= curVer; i++) { // String verDir = DocumentManager.VersionDir(histDir, i);
Map<String, Object> obj = new HashMap<String, Object>(); //
Map<String, Object> dataObj = new HashMap<String, Object>(); // try {
String verDir = DocumentManager.VersionDir(histDir, i); // String key = null;
//
try { // key = i == curVer ? document.key : readFileToEnd(new File(verDir + File.separator + "key.txt"));
String key = null; //
// obj.put("key", key);
key = i == curVer ? document.key : readFileToEnd(new File(verDir + File.separator + "key.txt")); // obj.put("version", i);
//
obj.put("key", key); // if (i == 1) {
obj.put("version", i); // String createdInfo = readFileToEnd(new File(histDir + File.separator + "createdInfo.json"));
// JSONObject json = JSONObject.parseObject(createdInfo);
if (i == 1) { // obj.put("created", json.get("created"));
String createdInfo = readFileToEnd(new File(histDir + File.separator + "createdInfo.json")); // Map<String, Object> user = new HashMap<String, Object>();
JSONObject json = JSONObject.parseObject(createdInfo); // user.put("id", json.get("id"));
obj.put("created", json.get("created")); // user.put("name", json.get("name"));
Map<String, Object> user = new HashMap<String, Object>(); // obj.put("user", user);
user.put("id", json.get("id")); // }
user.put("name", json.get("name")); //
obj.put("user", user); // dataObj.put("key", key);
} // dataObj.put("url", i == curVer ? document.url : DocumentManager.GetPathUri(verDir + File.separator + "prev" + FileUtility.GetFileExtension(document.title)));
// dataObj.put("version", i);
dataObj.put("key", key); //
dataObj.put("url", i == curVer ? document.url : DocumentManager.GetPathUri(verDir + File.separator + "prev" + FileUtility.GetFileExtension(document.title))); // if (i > 1) {
dataObj.put("version", i); // JSONObject changes = JSONObject.parseObject(readFileToEnd(new File(DocumentManager.VersionDir(histDir, i - 1) + File.separator + "changes.json")));
// JSONObject change = (JSONObject) ((JSONArray) changes.get("changes")).get(0);
if (i > 1) { //
JSONObject changes = JSONObject.parseObject(readFileToEnd(new File(DocumentManager.VersionDir(histDir, i - 1) + File.separator + "changes.json"))); // obj.put("changes", changes.get("changes"));
JSONObject change = (JSONObject) ((JSONArray) changes.get("changes")).get(0); // obj.put("serverVersion", changes.get("serverVersion"));
// obj.put("created", change.get("created"));
obj.put("changes", changes.get("changes")); // obj.put("user", change.get("user"));
obj.put("serverVersion", changes.get("serverVersion")); //
obj.put("created", change.get("created")); // Map<String, Object> prev = (Map<String, Object>) histData.get(Integer.toString(i - 2));
obj.put("user", change.get("user")); // Map<String, Object> prevInfo = new HashMap<String, Object>();
// prevInfo.put("key", prev.get("key"));
Map<String, Object> prev = (Map<String, Object>) histData.get(Integer.toString(i - 2)); // prevInfo.put("url", prev.get("url"));
Map<String, Object> prevInfo = new HashMap<String, Object>(); // dataObj.put("previous", prevInfo);
prevInfo.put("key", prev.get("key")); // dataObj.put("changesUrl", DocumentManager.GetPathUri(DocumentManager.VersionDir(histDir, i - 1) + File.separator + "diff.zip"));
prevInfo.put("url", prev.get("url")); // }
dataObj.put("previous", prevInfo); //
dataObj.put("changesUrl", DocumentManager.GetPathUri(DocumentManager.VersionDir(histDir, i - 1) + File.separator + "diff.zip")); // if (DocumentManager.TokenEnabled())
} // {
// dataObj.put("token", jwtComp.createJWT(dataObj));
if (DocumentManager.TokenEnabled()) // }
{ //
dataObj.put("token", DocumentManager.CreateToken(dataObj)); // hist.add(obj);
} // histData.put(Integer.toString(i - 1), dataObj);
//
hist.add(obj); // } catch (Exception ex) { }
histData.put(Integer.toString(i - 1), dataObj); // }
//
} catch (Exception ex) { } // Map<String, Object> histObj = new HashMap<String, Object>();
} // histObj.put("currentVersion", curVer);
// histObj.put("history", hist);
Map<String, Object> histObj = new HashMap<String, Object>(); //
histObj.put("currentVersion", curVer); // Gson gson = new Gson();
histObj.put("history", hist); // return new String[] { gson.toJson(histObj), gson.toJson(histData) };
// }
Gson gson = new Gson(); // return new String[] { "", "" };
return new String[] { gson.toJson(histObj), gson.toJson(histData) }; // }
}
return new String[] { "", "" };
}
private String readFileToEnd(File file) { private String readFileToEnd(File file) {
String output = ""; String output = "";