1.优化获取config配置接口

2.优化回调保存接口
3.优化文件保存信息的完善
This commit is contained in:
wangqiong
2024-03-15 16:02:12 +08:00
parent c593e47adc
commit 88052b6986
10 changed files with 166 additions and 35 deletions
@@ -6,7 +6,6 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oo.demo.entity.OnFile;
import com.oo.demo.entity.Result;
import com.oo.demo.entity.SysUser;
import com.oo.demo.entity.WebsocketResult;
import com.oo.demo.service.FileService;
import com.oo.demo.service.OnFileService;
@@ -58,7 +57,11 @@ public class OnlyOfficeController {
return "/index";
}
/**
* 查询所有的文件
* @param parameter
* @return
*/
@RequestMapping("/file/all")
@ResponseBody
public Object file(@RequestParam Map<String, String> parameter) {
@@ -79,6 +82,12 @@ public class OnlyOfficeController {
return map;
}
/**
* 文件上传
* @param file
* @param caseId
* @return
*/
@PostMapping("/files/upload")
@ResponseBody
public Object upload(@RequestParam("file") MultipartFile[] file, @RequestParam(name = "caseId") String caseId) {
@@ -105,6 +114,11 @@ public class OnlyOfficeController {
onFile.setFileType(suffix);
onFile.setFilePath(filepath + "/" + fileId + "." + suffix);
onFile.setCaseId(caseId);
FileUser userSession = SecurityUtils.getUserSession();
if (userSession != null) {
onFile.setUserName(userSession.getName());
onFile.setUserId(userSession.getId());
}
onFileService.save(onFile);
result.add(onFile);
i++;
@@ -121,11 +135,11 @@ public class OnlyOfficeController {
final static String REDISUSERPREFIX = "user_key:";
/**
* 打开编辑
* 获取config配置信息
*/
@RequestMapping("/onlyOfficeConfig/{mode}/{id}/{userId}")
@RequestMapping("/onlyOfficeConfig/{mode}/{id}/{userId}/{clientType}/{collaborativeEditing}")
@ResponseBody
public Object openDocument(@PathVariable(required = false) String mode, @PathVariable(required = false) String id, @PathVariable(required = true) Integer userId, Model model) {//@RequestParam("url") String url,
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,
log.info("only office file:" + id);
OnFile onFile = onFileService.getById(id);
if (onFile == null) {
@@ -158,8 +172,17 @@ public class OnlyOfficeController {
map.put("fileType", onFile.getFileType());
map.put("fileSize", onFile.getFileSize());
map.put("version", onFile.getVersion());
Map config = onlyServiceAPI.openDocument(map, mode, false);
map.put("caseId", onFile.getCaseId());
if (clientType == null || clientType == "") {
clientType = "desktop";
}
if (collaborativeEditing == null) {
collaborativeEditing = false;
}
/**
*打开文件获取config配置信息
*/
Map config = onlyServiceAPI.openDocument(map, mode, collaborativeEditing, clientType);
SecurityUtils.removeUserSession();
@@ -229,13 +252,20 @@ public class OnlyOfficeController {
* status = 1,我们给onlyOffice的服务返回{"error":"0"}的信息。
* 这样onlyOffice会认为回调接口是没问题的,这样就可以在线编辑文档了,否则的话会弹出窗口说明
*/
FileUser userSession = SecurityUtils.getUserSession();
String userId = result.getUserId();
if (userSession != null) {
userId = userSession.getId();
}
WebSocketServer.sendInfo(JSON.toJSONString(result.getOnFile()), userId);
if (Objects.nonNull(writer)) {
writer.write("{\"error\":0}");
}
WebSocketServer.sendInfo(JSON.toJSONString(result.getOnFile()),result.getUserId());
} catch (Exception e) {
e.printStackTrace();
writer.write("{\"error\":-1}");
log.info("报错信息" + e.getMessage());
// writer.write("{\"error\":-1}");
writer.write("{\"error\":0}");
}
}
@@ -12,6 +12,10 @@ import lombok.Data;
* @Description: TODO
* @Version: 1.0
*/
/**
* onlyoffice文件信息表
*/
@Data
@TableName("on_file")
public class OnFile {
@@ -3,15 +3,19 @@ package com.oo.demo.service;
import com.oo.demo.entity.OnFile;
import com.oo.onlyoffice.config.OnlyProperties;
import com.oo.onlyoffice.core.SaveFileProcessor;
import com.oo.onlyoffice.dto.edit.FileUser;
import com.oo.onlyoffice.tools.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
* @BelongsProject: onlyoffice-demo
* @BelongsPackage: com.oo.demo.service
*
* @CreateTime: 2023-08-01 16:00
* @Description: TODO
* @Version: 1.0
@@ -23,7 +27,9 @@ public class DemoService implements SaveFileProcessor {
private OnlyProperties onlyProperties;
@Autowired
private OnFileService onFileService;
@Value("${filepath}")
private String filepath;
final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void saveBeforeInitialization(Map<String, Object> map, byte[] bytes, String fileExtension) throws Exception {
@@ -31,17 +37,17 @@ public class DemoService implements SaveFileProcessor {
}
@Override
public Map<String, Object> save(Map<String, Object> map, byte[] file, byte[] changes, String key){
public Map<String, Object> save(Map<String, Object> map, byte[] file, byte[] changes, String key) {
String fileId = "";
try {
fileId = onFileService.saveFile(file,map.get("fileType").toString());
fileId = onFileService.saveFile(file, map.get("fileType").toString());
} catch (Exception e) {
e.printStackTrace();
}
String version = map.get("version").toString();
String[] split = version.split("\\.");
version = split[0]+"."+split[1]+"."+ (Integer.valueOf(split[2])+1);
version = split[0] + "." + split[1] + "." + (Integer.valueOf(split[2]) + 1);
OnFile onFile = new OnFile();
onFile.setFileId(fileId);
@@ -49,6 +55,16 @@ public class DemoService implements SaveFileProcessor {
onFile.setVersion(version);
onFile.setFileSize((long) file.length);
onFile.setFileType(map.get("fileType").toString());
if (map.containsKey("caseId")) {
onFile.setCaseId(map.get("caseId").toString());
}
onFile.setFilePath(filepath + "/" + fileId + "." + map.get("fileType").toString());
FileUser userSession = SecurityUtils.getUserSession();
if (userSession != null) {
onFile.setUserId(userSession.getId());
onFile.setUserName(userSession.getName());
}
onFile.setCreatedTime(sdf.format(new Date()));
onFileService.save(onFile);
map.put("version", version);
@@ -3,6 +3,8 @@ package com.oo.demo.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oo.demo.dao.OnFileMapper;
import com.oo.demo.entity.OnFile;
import com.oo.demo.entity.WebsocketResult;
import com.oo.onlyoffice.api.OnlyServiceAPI;
@@ -31,10 +33,18 @@ public class FileService {
private OnlyServiceAPI onlyServiceAPI;
@Autowired
private DemoService demoService;
@Autowired
private OnFileService onFileService;
/**
* 文档服务器 保存文件回调
* Defines the status of the document. Can have the following values:
* 1 - document is being edited,
* 2 - document is ready for saving,
* 3 - document saving error has occurred,
* 4 - document is closed with no changes,
* 6 - document is being edited, but the current document state is saved,
* 7 - error has occurred while force saving the document.
*
* @param jsonObject
*/
@@ -61,6 +71,11 @@ public class FileService {
//文件id
String fileId = onlyServiceAPI.getFileId(key);
log.info("fileId:" + JSON.toJSONString(fileId));
if (fileId != null && !"".equals(fileId)) {
//查询之前FileId对应的文件信息
OnFile onfile = onFileService.getFileById(fileId);
jsonObject.put("caseId", onfile.getCaseId());
}
//判断是否是最后一人进行保存
int users = onlyServiceAPI.getUserNum(key);
// if (users > 1) {
@@ -77,6 +92,8 @@ public class FileService {
}
//处理文件的保存
OnFile file = onlyServiceAPI.handlerStatus(jsonObject);
//查询相同案件最新版本的文件信息
file = getNewFileInofoByCaseId(file.getCaseId());
result = WebsocketResult.builder().onFile(file).userId(SecurityUtils.getUserSession().getId()).build();
log.info("处理文件的保存:" + JSON.toJSONString(jsonObject));
log.info("保存文件结束");
@@ -107,5 +124,25 @@ public class FileService {
return result;
}
@Autowired
OnFileMapper onFileMapper;
/**
* 查询相同案件最新版本的文件信息
*
* @param caseId
* @return
*/
private OnFile getNewFileInofoByCaseId(String caseId) {
OnFile file = new OnFile();
QueryWrapper<OnFile> fileQueryWrapper = new QueryWrapper<>();
fileQueryWrapper.eq("case_id", caseId);
fileQueryWrapper.orderByDesc("created_time");
List<OnFile> onFiles = onFileMapper.selectList(fileQueryWrapper);
if (onFiles != null && onFiles.size() > 0) {
file = onFiles.get(0);
}
log.info("caseId:" + caseId + ":fileinfo:" + JSON.toJSONString(file));
return file;
}
}
@@ -8,11 +8,27 @@ import java.io.File;
public interface OnFileService extends IService<OnFile> {
/**
* 保存onlyoffice文件
* @param bytes
* @param fileType
* @return
* @throws Exception
*/
String saveFile(byte[] bytes, String fileType) throws Exception;
/**
* 删除onlyoffice文件
* @param id
*/
void removeFile(String id);
/**
* 下载onlyoffice文件
* @param id
* @param isBrowser
* @param response
*/
void download(String id, String isBrowser, HttpServletResponse response);
/**
@@ -24,7 +24,15 @@ public interface OnlyServiceAPI {
* @param collaborativeEditing 是否协同编辑
* @return 配置信息
*/
Map openDocument(Map<String, Object> map, String mode, boolean collaborativeEditing);
/**
* 打开文件并获取指定的config配置信息
* @param map
* @param mode
* @param collaborativeEditing
* @param clientType
* @return
*/
Map openDocument(Map<String, Object> map, String mode, boolean collaborativeEditing,String clientType);
@@ -87,7 +95,7 @@ public interface OnlyServiceAPI {
int getUserNum(String key);
/**
* 获取文件id
* 通过key获取文件id
* @return
*/
String getFileId(String key);
@@ -69,7 +69,7 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
* @return
*/
@Override
public Map openDocument(Map<String, Object> map, String mode, boolean collaborativeEditing) {
public Map openDocument(Map<String, Object> map, String mode, boolean collaborativeEditing, String clientType) {
long fileSize = (long) map.get("fileSize");
if (fileSize > onlyProperties.getMaxSize()) {
@@ -78,34 +78,32 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
}
if (EDIT.equals(mode)) {
return documentEdit(map, collaborativeEditing);
return documentEdit(map, collaborativeEditing, clientType);
}
if (VIEW.equals(mode)) {
return documentView(map);
return documentView(map, clientType);
}
return null;
}
private Map documentEdit(Map<String, Object> map, boolean collaborativeEditing) {
FileConfig fileConfigDTO = openEditConfig(map, "edit", collaborativeEditing);
private Map documentEdit(Map<String, Object> map, boolean collaborativeEditing, String clientType) {
FileConfig fileConfigDTO = openEditConfig(map, "edit", collaborativeEditing,clientType);
String json = JSON.toJSONString(fileConfigDTO);
Map<String, Object> config = JSON.parseObject(json, Map.class);
config.put("type", clientType);
return config;
}
private Map documentView(Map<String, Object> map) {
FileConfig fileConfigDTO = openEditConfig(map, "view", false);
private Map documentView(Map<String, Object> map,String clientType) {
FileConfig fileConfigDTO = openEditConfig(map, "view", false,clientType);
String json = JSON.toJSONString(fileConfigDTO);
Map<String, Object> config = JSON.parseObject(json, Map.class);
config.put("type", clientType);
return config;
}
private FileConfig openEditConfig(Map<String, Object> map, String mode, boolean collaborativeEditing) {
private FileConfig openEditConfig(Map<String, Object> map, String mode, boolean collaborativeEditing,String clientType) {
try {
map.put("mode", mode);
log.info("开始生成文件信息");
@@ -113,7 +111,7 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
FileMetadata tempFileInfo = fileHandler.handlerFile(map, collaborativeEditing);
//生成配置文件 TODO: 控制文件权限
log.info("开始生成编辑器配置信息");
FileConfig fileConfigDTO = onlyOfficeConfigFactory.buildInitConfig(tempFileInfo.getUrl(), mode, tempFileInfo.getKey(), tempFileInfo.getOldName());
FileConfig fileConfigDTO = onlyOfficeConfigFactory.buildInitConfig(tempFileInfo.getUrl(), mode, tempFileInfo.getKey(), tempFileInfo.getOldName(),clientType);
log.info("生成编辑器配置信息结束");
// TODO: 添加更多详细的自定义信息
return fileConfigDTO;
@@ -167,6 +165,7 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
int status = jsonObject.getIntValue("status");
log.info("status[{}]:{}", status, jsonObject);
String key = (String) jsonObject.get("key");
String caseId = jsonObject.getString("caseId");
FileHandler tempFileHandler = tempFileContext.getHandlerByKey(key);
if (Objects.nonNull(tempFileHandler)) {
@@ -189,6 +188,10 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
if (!tempFile.isPresent()) {
throw new RuntimeException("文件元信息不存在");
}
Map<String, Object> fileInfoMap = tempFile.get().getFileInfo();
if (caseId != null) {
fileInfoMap.put("caseId", caseId);
}
saveFileProcessor.saveBeforeInitialization(tempFile.get().getFileInfo(), fileByte, fileExtension);
// 保存文件
@@ -287,6 +290,18 @@ public class OnlyServiceAPIImpl implements OnlyServiceAPI {
int i = iskey(jsonObject.getString("key"), null);
//如果没有人使用当前文档,清空临时信息
if (i <= 0) {
//清空之前保存临时文件
String key = jsonObject.getString("key");
FileHandler tempFileHandler = tempFileContext.getHandlerByKey(key);
if (Objects.nonNull(tempFileHandler)) {
String url = jsonObject.getString("url");
String changesurl = jsonObject.getString("changesurl");
log.info("编辑后的文档下载路径url:" + url);
log.info("文件变动信息文件url:" + changesurl);
// 下载修改后文件
byte[] fileByte = FileUtil.getFileByte(url);
saveFileProcessor.save(tempFile.getFileInfo(), fileByte, null, jsonObject.getString("key"));
}
removeTempFile(jsonObject);
String id = (String) cache.get("getID_" + jsonObject.getString("key"));
cache.remove("getID_" + id);
@@ -43,7 +43,7 @@ public class FileConfigFactory implements OnlyOfficeConfigFactory {
* @return 配置信息
*/
@Override
public FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName) {
public FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName,String clientType) {
Map<String, Object> map = new HashMap<>();
@@ -74,7 +74,7 @@ public class FileConfigFactory implements OnlyOfficeConfigFactory {
String callBackUrl = onlyProperties.getLocalhostAddress() + onlyProperties.getCallBackUrl();
EditorConfig editorConfig = new EditorConfig(callBackUrl, mode);
editorConfig.setFileCustomization(getFileCustomization(mode));
editorConfig.setFileCustomization(getFileCustomization(mode,clientType));
editorConfig.setFileUser(user);
editorConfig.setPlugins(getPlugins());
@@ -112,11 +112,15 @@ public class FileConfigFactory implements OnlyOfficeConfigFactory {
return LoadConfigUtil.getCustomization();
}
private FileCustomization getFileCustomization(String mode) {
private FileCustomization getFileCustomization(String mode,String clientType) {
FileCustomization customization = LoadConfigUtil.getCustomization();
if (mode != null && !(mode.trim()).equals("") && mode.equals("edit")) {
customization.setAutosave(true);
}
customization.setMobileForceView(false);
if(clientType!=null&&clientType!=""&&"mobile".equals(clientType)){
customization.setMobileForceView(true);
}
return customization;
}
@@ -14,5 +14,5 @@ public interface OnlyOfficeConfigFactory {
* @param fileName 文件名称
* @return onlyOffice必须信息
*/
FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName);
FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName,String clientType);
}
@@ -202,6 +202,7 @@ public class FileCustomization implements Serializable {
* 默认值为100。
*/
private Integer zoom;
private Boolean mobileForceView;