onlyoffice版本历史功能开发划重点(前后端分离的springboot vue项目)

wylc123 1年前 ⋅ 1263 阅读
  1. 前端重点

点击编辑时获取历史版本数据,并跳转页面传参:

import request from '@/utils/request'

export function getMessage (id) {
  return request({
    url: '/test/editor/' + id,
    method: 'get'
  })
}
editor (row) {
      console.log(row)
      getMessage(row.id).then(res => {
        debugger
        const option = {
          url: row.url,
          callbackUrl: res.data.callbackUrl + row.fileId,
          history: res.data.history,
          histData: res.data.histData
        }
        this.$router.push({
          path: '/edit',
          query: {
            option: option
          }
        })
      })
    },

根据后台数据返回判断是否存在历史版本,如果存在加载3个事件>

if (option.history) {
        config.events = {
          onRequestHistory () {
            docEditor.refreshHistory(option.history)
          },
          onRequestHistoryData (event) {
            var ver = event.data
            docEditor.setHistoryData(option.histData[ver])
          },
          onRequestHistoryClose () {
            document.location.reload()
          }
        }
      }

注:

1)onRequestHistory事件用于触发打开版本历史记录列表的处理程序。当onRequestHistory事件被调用时,refreshHistory方法必须被执行。如果每个版本都存在历史参数,则此方法包含每个文档版本的文档历史记录。

option.history格式类似:

{
        "currentVersion": 2,
        "history": [
            {
                "created": "2010-07-06 10:13 AM",
                "key": "af86C7e71Ca8",
                "user": {
                    "id": "F89d8069ba2b",
                    "name": "Kate Cage"
                },
                "version": 1
            },
            {
                "created": "2010-07-07 3:46 PM",
                "key": "Khirz6zTPdfd7",
                "user": {
                    "id": "78e1e841",
                    "name": "John Smith"
                },
                "version": 2
            },
            ...
        ]
    }

2)onRequestHistoryData事件用于触发点击对应版本打开对应版本内容的处理程序。当onRequestHistoryData事件被调用时,必须执行setHistoryData方法。此方法包含对应版本文件的绝对 URL。

option.histData[ver]格式类似:

{
     "changesUrl" : "https://example.com/url-to-changes.zip" ,
     "key" : "Khirz6zTPdfd7" ,
     "previous" : {
         "key" : "af86C7e71Ca8" ,
         "url " : "https://example.com/url-to-the-previous-version-of-the-document.docx" 
    }, "url" : "https://example.com/url-to-example- document.docx" ,
     "version" : 2 
}

3)onRequestHistoryClose事件用于关闭历史版本时,重新加载最新版本文档。

2.  后端重点

重点是要在新建文档,保存文档调用回调函数时将传给回调函数的历史版本信息保存到数据库中,并在打开文件时提供历史版本信息列表数据option.history

1)新建一个数据库表用于存储历史版本数据:

CREATE TABLE `tb_hist_data` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `file_id` varchar(255) DEFAULT NULL,
  `file_key` varchar(255) DEFAULT NULL,
  `pre_key` varchar(255) DEFAULT NULL,
  `version` int(255) DEFAULT NULL,
  `changes_url` varchar(255) DEFAULT NULL,
  `pre_url` varchar(255) DEFAULT NULL,
  `created` date DEFAULT NULL,
  `update_id` int(11) DEFAULT NULL,
  `del_flag` int(255) DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;

2. 在调回调函数时存储历史数据

@RequestMapping("save")
    public void saveFile(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter writer = null;
        System.out.println("===========保存文件=============");
        String fileId = request.getParameter("fileId");
        System.out.println(fileId);
        try {
            writer = response.getWriter();
            Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\n");
            String body = scanner.hasNext() ? scanner.next() : "";
            JSONObject jsonObject = (JSONObject) new JSONParser().parse(body);
            System.out.println("===saveEditedFile:" + jsonObject.get("status"));

            /*
                0 - no document with the key identifier could be found,
                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.
             **/
            long status = (long) jsonObject.get("status");
            if (status == 2 || status ==3) {
                String downloadUri = (String) jsonObject.get("url");
                String fileName = downloadUri.substring(downloadUri.lastIndexOf("/") + 1);
                // 更改之后的文件保存
                String saveUrl = FileUtils.downloadToFile(downloadUri,"out.dock");
                // diff文件
                String changesUrl = (String) jsonObject.get("changesurl");
                String diffUrl = FileUtils.downloadToFile(changesUrl, "diff.zip");

                // history
                String changeshistory = (String) jsonObject.get("changeshistory");
                System.out.println("changeshistory========>"+changeshistory);
                JSONObject history = (JSONObject) jsonObject.get("history");
                System.out.println("history=====>"+history);
                // key
                String key = (String) jsonObject.get("key");
                System.out.println(key);
                File preFile = this.fileService.getOne(new QueryWrapper<File>().eq("file_id", fileId));

                UpdateWrapper<File> wrapper = new UpdateWrapper<>();
                wrapper.eq("file_id",fileId)
                        .set("file_key",key)
                        .set("hist_status",0)
                        .set("url",saveUrl);
                this.fileService.update(wrapper);
                List<HistData> histList = this.histDataService.list(new QueryWrapper<HistData>().eq("file_id", fileId));
                if (histList.size()==0) {
                    int version = 0;
                    HistData v0 = new HistData();
                    v0.setFileId(fileId);
                    v0.setVersion(version);
                    v0.setFileKey(preFile.getFileKey());
                    v0.setDelFlag(1);
                    HistData v1 = new HistData();
                    v1.setVersion(version+1);
                    v1.setFileId(fileId);
                    v1.setFileKey(key);
                    v1.setChangesUrl(diffUrl);
                    v1.setPreKey(preFile.getFileKey());
                    v1.setPreUrl(preFile.getUrl());
                    v1.setDelFlag(1);
                    List<HistData> list = Arrays.asList(v0, v1);
                    this.histDataService.saveBatch(list);
                } else {
                    Integer max = histList.stream().map(HistData::getVersion).max(Integer::compareTo).orElse(1);
                    HistData data = new HistData();
                    data.setVersion(max+1);
                    data.setFileId(fileId);
                    data.setFileKey(key);
                    data.setChangesUrl(diffUrl);
                    data.setPreKey(preFile.getFileKey());
                    data.setPreUrl(preFile.getUrl());
                    data.setDelFlag(1);
                    this.histDataService.save(data);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        writer.write("{\"error\":0}");
    }

3. 在打开文件时向前端提供历史版本数据

controller:

@RequestMapping("editor/{id}")
    public String editorFile(@PathVariable Long id) {
        return ResultMsg.success(this.editorService.getEditMsg(id));
    }

service:

@Service("editorService")
public class EditorService {
    @Resource
    private FileMapper fileMapper;

    @Resource
    private HistDataMapper histDataMapper;

    public HandleEditModel getEditMsg(Long id) {
        HandleEditModel model = new HandleEditModel();
        model.setCallbackUrl("http://192.168.20.150:9520/test/save?fileId=");
        File file = this.fileMapper.selectById(id);
        if (file.getHistStatus() == 0) {
            List<HistData> histList = this.histDataMapper.selectList(new QueryWrapper<HistData>().eq("file_id", file.getFileId()));
            Map<String, HistDataDto> dtos = handleHistData(histList, file);
            HistoryDto historyDto = handleHistory(histList);
            model.setHistData(dtos);
            model.setHistory(historyDto);
        }
        return model;
    }

    private Map<String, HistDataDto> handleHistData(List<HistData> histData, File file) {
        Map<Integer, HistData> map = new HashMap<>();
        for (HistData data : histData) {
            map.put(data.getVersion(), data);
        }
        Map<String, HistDataDto> result = new HashMap<>();
        for (int i = 0; i < histData.size() - 1; i++) {
            HistData data = histData.get(i);
            HistDataDto dto = new HistDataDto();
            dto.setChangesUrl(data.getChangesUrl());
            dto.setVersion(data.getVersion());
            dto.setKey(histData.get(i + 1).getPreKey());
            dto.setUrl(histData.get(i + 1).getPreUrl());
            HistDataDto previous = new HistDataDto();
            previous.setUrl(data.getPreUrl());
            previous.setKey(data.getPreKey());
            dto.setPrevious(previous);
            result.put(String.valueOf(i), dto);
        }
        Integer max = histData.stream().map(HistData::getVersion).max(Integer::compareTo).orElse(1);
        HistDataDto dataDto = new HistDataDto();
        dataDto.setVersion(max);
        HistDataDto previous = new HistDataDto();
        previous.setKey(map.get(max).getPreKey());
        previous.setUrl(map.get(max).getPreUrl());
        dataDto.setPrevious(previous);
        dataDto.setKey(file.getFileKey());
        dataDto.setChangesUrl(map.get(max).getChangesUrl());
        dataDto.setUrl(file.getUrl());
        result.put(String.valueOf(max),dataDto);
        return result;
    }

    private HistoryDto handleHistory(List<HistData> histData) {
        HistoryDto result = new HistoryDto();
        List<VersionDto> history = new ArrayList<>();
        for (HistData data : histData) {
            VersionDto dto = new VersionDto();
            dto.setCreated("");
            dto.setVersion(data.getVersion());
            dto.setKey(data.getFileKey());
            dto.setServerVersion("6.1.0");
            // TODO: 2021/1/20 查询修改人的信息
            List<VersionDto> list = new ArrayList<>();
            VersionDto versionDto = new VersionDto();
            User user = new User();
            versionDto.setUser(user);
            versionDto.setCreated("");
            list.add(versionDto);
            dto.setChanges(list);
            history.add(dto);
        }
        Integer max = histData.stream().map(HistData::getVersion).max(Integer::compareTo).orElse(1);
        result.setHistory(history);
        result.setCurrentVersion(max);
        return result;
    }
}

完成!

有需要可以加群交流:点击链接加入群聊【onlyoffice交流群】:https://jq.qq.com/?_wv=1027&k=ozgBiZts

1群将满可加2群【onlyoffice交流群2】:https://jq.qq.com/?_wv=1027&k=2uSJJPfr

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: