package org.jeecg.modules.doc.controller; import cn.hutool.core.util.IdUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.toolkit.ClassUtils; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.apache.shiro.SecurityUtils; import org.jeecg.common.api.vo.Result; import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.util.DateUtils; import org.jeecg.common.util.MD5Util; import org.jeecg.modules.doc.api.JeecgSystemClient; import org.jeecg.modules.doc.component.Copier; import org.jeecg.modules.doc.component.DocFileDealComp; import org.jeecg.modules.doc.component.LocalStorageCopier; import org.jeecg.modules.doc.component.LocalStorageDownloader; import org.jeecg.modules.doc.constant.Constant; import org.jeecg.modules.doc.dto.CreateOfficeFileDTO; import org.jeecg.modules.doc.dto.EditOfficeFileDTO; import org.jeecg.modules.doc.dto.PreviewOfficeFileDTO; import org.jeecg.modules.doc.entity.DocFile; import org.jeecg.modules.doc.entity.DocFilePath; import org.jeecg.modules.doc.entity.FileModel; import org.jeecg.modules.doc.exception.NotLoginException; import org.jeecg.modules.doc.service.IDocFilePathService; import org.jeecg.modules.doc.service.IDocFileService; import org.jeecg.modules.doc.service.IDocOperationHisService; import org.jeecg.modules.doc.util.ConfigManager; import org.jeecg.modules.doc.vo.CopyFile; import org.jeecg.modules.doc.vo.DownloadFile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.List; import java.util.Scanner; import java.util.UUID; @ApiOperation(value = "office", notes = "该接口为Onlyoffice文件操作接口,主要用来做一些文档的编辑,浏览等。") @RestController @Slf4j @RequestMapping({"/office"}) public class OfficeController { public static final String CURRENT_MODULE = "Onlyoffice文件操作接口"; @Resource JeecgSystemClient jeecgSystemClient; @Resource DocFileDealComp fileDealComp; @Value("${deployment.host}") private String deploymentHost; @Value("${deployment.port}") private String port; @Value("${ufop.storage-type}") private Integer storageType; @Resource IDocFileService fileService; @Resource IDocFilePathService userFileService; @Autowired private IDocOperationHisService operationHisService; @ApiOperation(value = "创建office文件", notes = "创建office文件", tags = {"office"}) @ResponseBody @RequestMapping(value = "/createofficefile", method = RequestMethod.POST) public Result createOfficeFile(@RequestBody CreateOfficeFileDTO createOfficeFileDTO) { LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); Result result = new Result<>(); try{ String fileName = createOfficeFileDTO.getFileName(); String filePath = createOfficeFileDTO.getFilePath(); String extendName = createOfficeFileDTO.getExtendName(); List userFiles = userFileService.selectSameUserFile(fileName, filePath, extendName); if (userFiles != null && !userFiles.isEmpty()) { return Result.error("同名文件已存在"); } String uuid = UUID.randomUUID().toString().replaceAll("-",""); String templateFilePath = ""; if ("docx".equals(extendName)) { templateFilePath = "template/Word.docx"; } else if ("xlsx".equals(extendName)) { templateFilePath = "template/Excel.xlsx"; } else if ("pptx".equals(extendName)) { templateFilePath = "template/PowerPoint.pptx"; } // String url2 = ClassUtils.getDefaultClassLoader().getResource("static/" + templateFilePath).getPath(); // url2 = URLDecoder.decode(url2, "UTF-8"); InputStream fileInputStream = ClassUtils.getDefaultClassLoader().getResourceAsStream("static/" + templateFilePath); Copier copier = new LocalStorageCopier(); CopyFile copyFile = new CopyFile(); copyFile.setExtendName(extendName); String fileUrl = copier.copy(fileInputStream, copyFile); DocFile fileBean = new DocFile(); fileBean.setFileId(IdUtil.getSnowflakeNextIdStr()); fileBean.setFileSize(0L); fileBean.setFileUrl(fileUrl); fileBean.setStorageType(storageType); fileBean.setIdentifier(uuid); fileBean.setCreateTime(DateUtils.getDate()); fileBean.setFileStatus(1); boolean saveFlag = fileService.save(fileBean); DocFilePath userFile = new DocFilePath(); if(saveFlag) { userFile.setPathId(IdUtil.getSnowflakeNextIdStr()); userFile.setFileName(fileName); userFile.setFilePath(filePath); userFile.setDeleteFlag(0); userFile.setIsDir(0); userFile.setExtendName(extendName); userFile.setFileId(fileBean.getFileId()); DocFilePath parent = fileDealComp.getParent(userFile.getFilePath()); if (parent!=null) { userFile.setParentId(parent.getPathId()); } userFileService.save(userFile); } operationHisService.saveHis(loginUser,userFile,Constant.OPERATION_CREATE); return Result.OK("文件创建成功"); } catch (Exception e) { log.error(e.getMessage()); return Result.error(e.getMessage()); } } @ApiOperation(value = "预览office文件", notes = "预览office文件", tags = {"office"}) @RequestMapping(value = "/previewofficefile", method = RequestMethod.POST) @ResponseBody public Result previewOfficeFile(HttpServletRequest request, @RequestBody PreviewOfficeFileDTO previewOfficeFileDTO, @RequestHeader("X-Access-Token") String token) { Result result = new Result<>(); try { LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); DocFilePath userFile = userFileService.getById(previewOfficeFileDTO.getUserFileId()); String baseUrl = "http"+"://"+ deploymentHost + ":" + port + request.getContextPath(); String query = "?type=show&X-Access-Token="+token; String callbackUrl = baseUrl + "/office/IndexServlet" + query; FileModel file = new FileModel(userFile.getPathId(), userFile.getFileName() + "." + userFile.getExtendName(), previewOfficeFileDTO.getPreviewUrl(), DateUtils.date2Str(userFile.getCreateTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")), loginUser.getId(), loginUser.getUsername(), callbackUrl, "view"); JSONObject jsonObject = new JSONObject(); jsonObject.put("file",file); jsonObject.put("docserviceApiUrl", ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.api")); jsonObject.put("reportName",userFile.getFileName()); result.setResult(jsonObject); result.setCode(200); result.setMessage("获取报告成功!"); } catch (Exception e) { log.error(e.getMessage()); result.setCode(500); result.setMessage("服务器错误!"); } return result; } @ApiOperation(value = "编辑office文件", notes = "编辑office文件", tags = {"office"}) @ResponseBody @RequestMapping(value = "/editofficefile", method = RequestMethod.POST) public Result editOfficeFile(HttpServletRequest request, @RequestBody EditOfficeFileDTO editOfficeFileDTO, @RequestHeader("X-Access-Token") String token) { Result result = new Result<>(); log.info("editOfficeFile"); try { LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); DocFilePath userFile = userFileService.getById(editOfficeFileDTO.getUserFileId()); String baseUrl = "http"+"://"+ deploymentHost + ":" + port + request.getContextPath(); log.info("回调地址baseUrl:" + baseUrl); String query = "?type=edit&userFileId="+userFile.getPathId()+"&X-Access-Token="+token; String callbackUrl = baseUrl + "/office/IndexServlet" + query; FileModel file = new FileModel(userFile.getPathId(), userFile.getFileName() + "." + userFile.getExtendName(), editOfficeFileDTO.getPreviewUrl(), DateUtils.date2Str(userFile.getCreateTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")), String.valueOf(loginUser.getId()), loginUser.getUsername(), callbackUrl, "edit"); JSONObject jsonObject = new JSONObject(); jsonObject.put("file",file); jsonObject.put("docserviceApiUrl",ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.api")); jsonObject.put("reportName",userFile.getFileName()); result.setResult(jsonObject); result.setCode(200); result.setMessage("编辑报告成功!"); } catch (Exception e) { log.error(e.getMessage()); result.setCode(500); result.setMessage("服务器错误!"); } return result; } @RequestMapping(value = "/IndexServlet", method = RequestMethod.POST) @ResponseBody public void IndexServlet(HttpServletResponse response, HttpServletRequest request) throws IOException { String token = request.getParameter("X-Access-Token"); String userId = jeecgSystemClient.getUserSectionInfoByToken(token).getResult().get("sysUserId"); if (userId == null) { throw new NotLoginException(); } String username = jeecgSystemClient.getUserSectionInfoByToken(token).getResult().get("sysUserCode"); LoginUser user = new LoginUser(); user.setId(userId); user.setUsername(username); PrintWriter writer = response.getWriter(); Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A"); String body = scanner.hasNext() ? scanner.next() : ""; JSONObject jsonObj = JSON.parseObject(body); log.info("===saveeditedfile:" + jsonObj.get("status")); ; String status = jsonObj != null ? jsonObj.get("status").toString() : ""; if ("2".equals(status) || "6".equals(status)) { String type = request.getParameter("type"); String downloadUri = (String) jsonObj.get("url"); if("edit".equals(type)){//修改报告 String userFileId = request.getParameter("userFileId"); DocFilePath userFile = userFileService.getById(userFileId); DocFile fileBean = fileService.getById(userFile.getFileId()); Long pointCount = fileService.getFilePointCount(userFile.getFileId()); String fileUrl = fileBean.getFileUrl(); if (pointCount > 1) { fileUrl = fileDealComp.copyFile(fileBean, userFile); } URL url = new URL(downloadUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { InputStream stream = connection.getInputStream(); fileDealComp.saveFileInputStream(fileUrl, stream); } catch (Exception e) { log.error(e.getMessage(),e); } finally { int fileLength = connection.getContentLength(); log.info("当前修改文件大小为:" + Long.valueOf(fileLength)); DownloadFile downloadFile = new DownloadFile(); downloadFile.setFileUrl(fileBean.getFileUrl()); InputStream inputStream = new LocalStorageDownloader().getInputStream(downloadFile); String md5Str = DigestUtils.md5Hex(inputStream); fileService.updateFileDetail(userFile.getPathId(), md5Str, fileLength, userId); connection.disconnect(); } operationHisService.saveHis(user, userFile, Constant.OPERATION_UPDATE); } } if("3".equals(status)||"7".equals(status)) {//不强制手动保存时为6,"6".equals(status) log.debug("====保存失败:"); writer.write("{\"error\":1}"); }else { log.debug("状态为:0") ; writer.write("{\"error\":" + "0" + "}"); } } }