昨天完成了onlyoffice 在线编辑集成,在此基础上实现查看编辑历史记录,效果如下:
直接上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文档编辑</title>
<script src="http://192.168.0.12:8001/web-apps/apps/api/documents/api.js"></script>
</head>
<body style="margin:0px;padding:0px;">
<div id="placeholder" class = "nav" style="width:100%;height:100%;min-height:900px;"></div>
</body>
<script>
window.onmessage = function (event) {
var data = event.data;
//var data = JSON.parse(event.data);
//console.log(data)
if (data.event == "onDocumentStateChange" && data.data == false) {
console.log("保存成功");
}
}
var fileInfo = ${fileInfo};
var fileid = "${fileid}";
var uuid = "${uuid}";
var currentVersion = "${currentVersion}";
var names = "${names}";
var suffix,fileName;
if(fileInfo) {
suffix = fileInfo.suffix;
fileName = fileInfo.fileName;
}
function handleDocType(fileType) {
var docType = '';
var fileTypesDoc = [
'doc', 'docm', 'docx', 'dot', 'dotm', 'dotx', 'epub', 'fodt', 'htm', 'html', 'mht', 'odt', 'ott', 'pdf', 'rtf', 'txt', 'djvu', 'xps'
];
var fileTypesCsv = [
'csv', 'fods', 'ods', 'ots', 'xls', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx'
];
var fileTypesPPt = [
'fodp', 'odp', 'otp', 'pot', 'potm', 'potx', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx'
];
if (fileTypesDoc.includes(fileType)) {
docType = 'word'
}
if (fileTypesCsv.includes(fileType)) {
docType = 'cell'
}
if (fileTypesPPt.includes(fileType)) {
docType = 'slide'
}
return docType;
}
var origin = window.location.origin;
var loglist = ${loglist};
var historys = [];
var logjson = {};
for(var i in loglist) {
var log = loglist[i];
//console.log(log)
historys.push({
"created": log.lastsave,
"key": log.key,
"user": {
"id": log.userid,
"name": log.names
},
"version": log.version
});
logjson[log.version] = {
"changesUrl": origin+"/sysfile/download2?id="+log.changesurlFileId,
"fileType": log.fileType,
"key": log.key,
"previous": {
"fileType": log.fileType,
"key": log.prekey,
"url": origin+"/sysfile/download2?id="+log.preurlFileId,
},
"token": "",
"url": origin+"/sysfile/download2?id="+log.urlFileId,
"version": log.version
}
}
//console.log(logjson)
var onRequestHistory = function () {
docEditor.refreshHistory({
"currentVersion": currentVersion,
"history": historys
});
};
var onRequestHistoryClose = function () {
document.location.reload();
};
var onRequestHistoryData = function (event) {
//console.log(event)
var version = event.data;
docEditor.setHistoryData(logjson[version])
};
var docEditor = new DocsAPI.DocEditor("placeholder", {
"document": {
"fileType": suffix, //文件类型
"key": uuid, //文件key,确保唯一就行
"title": fileName, //文件名称
"url": origin+"/sysfile/download2?id="+fileid,
"permissions": {
"edit": true,
"comment": true,
"download": false,
"fillForms": true,
"print": true,
"review": true
},
},
"documentType": handleDocType(suffix), //word:docx,xlsx:cell
"type": "desktop",
"events": {
"onRequestHistory": onRequestHistory,
"onRequestHistoryClose": onRequestHistoryClose,
"onRequestHistoryData": onRequestHistoryData
},
"width": "100%",
"height": "900px",
"editorConfig": {
"callbackUrl": origin+"/admin/onlyoffice/save?fileid="+fileid+"&names="+names,
"lang":"zh-CN",
"customization":{
"forcesave":"true",
"download": "false"
//,"trackChanges": true,//true为对自己启动,false为对自己关闭。
//"review": {
// "hoverMode": true, //定义检查显示模式:通过悬停更改(true)在工具提示中显示检查,或者通过单击更改(false)在气泡中显示检查。默认值为false。
//}
},
"mode":""//view
},
"token":""
});
</script>
</html>
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@Table(name = "officelog")
@Entity
public class Officelog{
private static final long serialVersionUID = 6841210424356828509L;
private Long fileid; //文件id
private String filetype;//docx
private String lastsave;
@Column(name = "changesurl", length = 500)
private String changesurl;
private String forcesavetype;
private String key;
@Column(name = "url", length = 500)
private String url;
private String status;
private String serverVersion;
private Integer version;//版本
private String prekey;//上一版本key
private String preurl;//上一版本url
private String userid;
private String names;
private Long urlFileId;
private Long preurlFileId;
private Long changesurlFileId;
}
@Controller
@RequestMapping("/admin")
public class OnlyofficeController {
@Value("${file.uploadPath}")
private String uploadPath;
@Autowired
private FilePreviewService filePreviewService;
@Autowired
private OfficelogDao officelogDao;
@Resource
private CommonService commonService;
@Resource
private SysFileDao sysFileDao;
@GetMapping("/onlyoffice/edit")
public String edit(Model model,HttpServletRequest request) {
Long fileid = StrUtils.parseLong(request.getParameter("fileid"));
SysFileEntity fileInfo = filePreviewService.getFileListByid(fileid);
request.setAttribute("fileid", fileid+"");
request.setAttribute("uuid", UUID.fastUUID());
request.setAttribute("fileInfo",JSONObject.toJSONString(fileInfo));
List<Officelog> loglist = officelogDao.getOfficeloglist(fileid);
request.setAttribute("loglist",JSONArray.toJSON(loglist).toString());
Integer currentVersion = 1;
if(loglist.size()>0) {
currentVersion = loglist.get(loglist.size()-1).getVersion();
}
request.setAttribute("currentVersion",currentVersion);
SysUserEntity user = commonService.getCurrentUser();
request.setAttribute("names",user.getName());
return "document";
}
@PostMapping(value = "/onlyoffice/save")
@Transactional
@ResponseBody
public String onlyOfficeCallBack(HttpServletRequest request, HttpServletResponse response) {
System.out.println("RemoteAddr----"+request.getRemoteAddr());//client's IP address from the remote host
System.out.println("User-Agent----"+request.getHeader("User-Agent"));
Long fileid = StrUtils.parseLong(request.getParameter("fileid"));
String names = StrUtils.getString(request.getParameter("names"));
Scanner scanner;
try {
scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
String body = scanner.hasNext() ? scanner.next() : "";
JSONObject jsonObject = JSONObject.parseObject(body);
Integer status = jsonObject.getInteger("status");
System.out.println("status----->"+status);
if (status == 2 || status == 3 || status == 6) {//6=强制保存
String downloadUri = jsonObject.getString("url");
URL url = new URL(downloadUri);
HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
InputStream stream = connection.getInputStream();
//查询附件信息,以获取附件存储路径
SysFileEntity fileInfo = filePreviewService.getFileListByid(fileid);
String path = fileInfo.getPath();
if (!path.startsWith("/")) {
path = uploadPath + "/" + path;
} else {
path = uploadPath + path;
}
System.out.println("保存文件-->"+path);
File savedFile = new File(path);
if (!savedFile.exists()) {
return "{\"error\":-1}";
}
try (FileOutputStream out = new FileOutputStream(savedFile)) {
int read;
final byte[] bytes = new byte[1024];
while ((read = stream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
}
connection.disconnect();
//保存版本信息
if(status!=6) {
String officeCache = uploadPath+"/officeCache/";
File folder = new File(officeCache);
if(!folder.exists()) {
folder.mkdirs();
}
Officelog log = newLog(fileid,jsonObject);
log.setNames(names);
String historyUrl = log.getKey()+"_"+log.getVersion()+"."+log.getFiletype();
String historyzip = log.getKey()+"_"+log.getVersion()+".zip";
FileUtil.copy(path, officeCache+historyUrl, true);
URL zipurl = new URL(log.getChangesurl());
HttpURLConnection connectionzip = (java.net.HttpURLConnection) zipurl.openConnection();
InputStream zipstream = connectionzip.getInputStream();
try (FileOutputStream out2 = new FileOutputStream(officeCache+historyzip)) {
int read;
final byte[] bytes = new byte[1024];
while ((read = zipstream.read(bytes)) != -1) {
out2.write(bytes, 0, read);
}
out2.flush();
}
connectionzip.disconnect();
SysFileEntity urlfile = new SysFileEntity();
BeanUtil.copyProperties(fileInfo, urlfile);
urlfile.setId(null);
urlfile.setExt1(fileInfo.getId().toString());
urlfile.setPath("officeCache/"+historyUrl);
urlfile.setSize(new BigDecimal(FileUtil.size(new File(officeCache+historyUrl))));
sysFileDao.save(urlfile);
SysFileEntity changesurlFile = new SysFileEntity();;
BeanUtil.copyProperties(fileInfo, changesurlFile);
changesurlFile.setId(null);
changesurlFile.setExt1(fileInfo.getId().toString());
changesurlFile.setFileName(historyzip);
changesurlFile.setPath("officeCache/"+historyzip);
changesurlFile.setSuffix("zip");
changesurlFile.setSize(new BigDecimal(FileUtil.size(new File(officeCache+historyzip))));
sysFileDao.save(changesurlFile);
log.setUrlFileId(urlfile.getId());
log.setChangesurlFileId(changesurlFile.getId());
officelogDao.save(log);
}
}
return "{\"error\":0}";
} catch (IOException e) {
return "{\"error\":-1}";
}
}
private String formatTime(String str) {
Instant instant = Instant.parse(str);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
ZoneId zoneId = ZoneId.of("UTC");
String formatterTime = formatter.format(instant.atZone(zoneId));
return formatterTime;
}
private Officelog newLog (Long fileid,JSONObject jsonObject) {
Officelog prelog = officelogDao.getprelog(fileid);
Integer version = 1;
String prekey ="";//上一版本key
String preurl ="";//上一版本url
Long preurlFileId = null;
if(prelog!=null) {
version = prelog.getVersion()+1;
prekey = prelog.getKey();
preurl = prelog.getUrl();
preurlFileId = prelog.getUrlFileId();
}
String filetype = jsonObject.getString("filetype");
String lastsave = jsonObject.getString("lastsave");
String formatterTime = formatTime(lastsave);
String changesurl = jsonObject.getString("changesurl");
String key = jsonObject.getString("key");
String url = jsonObject.getString("url");
String status = jsonObject.getString("status");
JSONArray actions = jsonObject.getJSONArray("actions");
JSONObject action = actions.getJSONObject(0);
String userid = action.getString("userid");
JSONObject historys = jsonObject.getJSONObject("history");
String serverVersion = historys.getString("serverVersion");
String forcesavetype = jsonObject.getString("forcesavetype");
Officelog log = new Officelog();
log.setFileid(fileid);
log.setVersion(version);
log.setPrekey(prekey);
log.setPreurl(preurl);
log.setPreurlFileId(preurlFileId);
log.setFiletype(filetype);
log.setLastsave(formatterTime);
log.setChangesurl(changesurl);
log.setKey(key);
log.setUrl(url);
log.setStatus(status);
log.setUserid(userid);
log.setServerVersion(serverVersion);
log.setForcesavetype(forcesavetype);
return log;
}
}