zhuguifei
2025-04-28 442928123f63ee497d766f9a7a14f0a6ee067e25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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<Object> createOfficeFile(@RequestBody CreateOfficeFileDTO createOfficeFileDTO) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Result<Object> result = new Result<>();
        try{
 
            String fileName = createOfficeFileDTO.getFileName();
            String filePath = createOfficeFileDTO.getFilePath();
            String extendName = createOfficeFileDTO.getExtendName();
            List<DocFilePath> 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<Object> previewOfficeFile(HttpServletRequest request, @RequestBody PreviewOfficeFileDTO previewOfficeFileDTO, @RequestHeader("X-Access-Token") String token) {
        Result<Object> 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<Object> editOfficeFile(HttpServletRequest request, @RequestBody EditOfficeFileDTO editOfficeFileDTO, @RequestHeader("X-Access-Token") String token) {
        Result<Object> 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" + "}");
        }
    }
 
}