diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..549e00a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,33 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/
diff --git a/LICENSE b/LICENSE
index 261eeb9..9e32cde 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,201 +1,127 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
+ 木兰宽松许可证, 第2版
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+ 木兰宽松许可证, 第2版
+ 2020年1月 http://license.coscl.org.cn/MulanPSL2
- 1. Definitions.
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
+ 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第2版(“本许可证”)的如下条款的约束:
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
+ 0. 定义
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
+ “软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
+ “贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
+ “贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
+ “法人实体”是指提交贡献的机构及其“关联实体”。
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
+ “关联实体”是指,对“本许可证”下的行为方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
+ 1. 授予版权许可
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
+ 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
+ 2. 授予专利许可
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
+ 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
+ 3. 无商标许可
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
+ “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
+ 4. 分发限制
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
+ 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
+ 5. 免责声明与责任限制
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
+ “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
+ 6. 语言
+ “本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
+ 条款结束
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
+ 如何将木兰宽松许可证,第2版,应用到您的软件
+
+ 如果您希望将木兰宽松许可证,第2版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步:
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
+ 1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字;
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
+ 2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中;
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
+ 3, 请将如下声明文本放入每个源文件的头部注释中。
- END OF TERMS AND CONDITIONS
+ Copyright (c) [Year] [name of copyright holder]
+ [Software Name] is licensed under Mulan PSL v2.
+ You can use this software according to the terms and conditions of the Mulan PSL v2.
+ You may obtain a copy of Mulan PSL v2 at:
+ http://license.coscl.org.cn/MulanPSL2
+ THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
+ See the Mulan PSL v2 for more details.
- APPENDIX: How to apply the Apache License to your work.
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
+ Mulan Permissive Software License,Version 2
- Copyright [yyyy] [name of copyright owner]
+ Mulan Permissive Software License,Version 2 (Mulan PSL v2)
+ January 2020 http://license.coscl.org.cn/MulanPSL2
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
+ Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions:
+
+ 0. Definition
+
+ Software means the program and related documents which are licensed under this License and comprise all Contribution(s).
+
+ Contribution means the copyrightable work licensed by a particular Contributor under this License.
+
+ Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License.
+
+ Legal Entity means the entity making a Contribution and all its Affiliates.
+
+ Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity.
- http://www.apache.org/licenses/LICENSE-2.0
+ 1. Grant of Copyright License
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
+ Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not.
+
+ 2. Grant of Patent License
+
+ Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken.
+
+ 3. No Trademark License
+
+ No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4.
+
+ 4. Distribution Restriction
+
+ You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software.
+
+ 5. Disclaimer of Warranty and Limitation of Liability
+
+ THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT’S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+ 6. Language
+
+ THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL.
+
+ END OF THE TERMS AND CONDITIONS
+
+ How to Apply the Mulan Permissive Software License,Version 2 (Mulan PSL v2) to Your Software
+
+ To apply the Mulan PSL v2 to your work, for easy identification by recipients, you are suggested to complete following three steps:
+
+ i Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner;
+
+ ii Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package;
+
+ iii Attach the statement to the appropriate annotated syntax at the beginning of each source file.
+
+
+ Copyright (c) [Year] [name of copyright holder]
+ [Software Name] is licensed under Mulan PSL v2.
+ You can use this software according to the terms and conditions of the Mulan PSL v2.
+ You may obtain a copy of Mulan PSL v2 at:
+ http://license.coscl.org.cn/MulanPSL2
+ THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
+ See the Mulan PSL v2 for more details.
diff --git a/README.md b/README.md
index 337ee9a..c414865 100644
--- a/README.md
+++ b/README.md
@@ -1,247 +1,336 @@
-## Overview
-This example will help you integrate ONLYOFFICE Docs into your web application written in Java
-with Spring Boot.
-
-Spring Boot has a lot of functionality, but its most significant features are: dependency management,
-auto-configuration, and built-in servlet containers.
-
-**Please note**: It is intended for testing purposes and demonstrating functionality of the editors. Do NOT use this integration example on your own server without proper code modifications! In case you enabled the test example, disable it before going for production.
-
-## For Windows
-
-### Step 1. Install ONLYOFFICE Docs
-
-Download and install ONLYOFFICE Docs (packaged as Document Server).
-
-See the detailed guide to learn how to install Document Server [for Windows](https://helpcenter.onlyoffice.com/installation/docs-developer-install-windows.aspx).
-
-### Step 2. Download the Java code for the editors integration
-
-Download the [Java-Spring example](https://api.onlyoffice.com/editors/demopreview) from our site.
-
-To connect the editors to your website, specify the path to the editors installation, server port and the path to the storage folder in the *\src\main\resources\application.properties* file:
-
-```
- files.storage=
- server.port=port
- files.docservice.url.site=https://documentserver/
-```
-
-where the **documentserver** is the name of the server with the ONLYOFFICE Docs installed, **port** is any available port and **files.storage** is the path where files will be created and stored (in the project folder by default). You can set an absolute path. For example, *D:\\\\folder*. Please note that on Windows OS the double backslash must be used as a separator.
-
-If you want to experiment with the editor configuration, modify the [parameters](https://api.onlyoffice.com/editors/advanced) it the *\src\main\resources\editor.html* file.
-
-### Step 3. Install the prerequisites
-To run the Java example code, install the Java version 11 appropriate for your OS and framework **Apache Maven**:
-
-* Java (download from [the Oracle official website](https://www.oracle.com/ru/java/technologies/javase-jdk11-downloads.html));
-* Apache Maven (download from [the official website](https://maven.apache.org/download.cgi)).
-
-### Step 4. Set environment variables
-
-1. After you have installed Java on Windows, set the **JAVA_HOME** environment variable to point to the Java installation directory.
-
- Find out where Java is installed. If you didn't change the path during installation, it will be something like this:
-
- ```
- C:\Program Files\Java\jdk11
- ```
-
- In **Windows 7** right click **My Computer** and select **Properties**, then click **Advanced**.
-
- In **Windows 8** go to **Control Panel** -> **System** -> **Advanced System Settings**.
-
- Click the **Environment Variables** button.
-
- Under **System Variables**, click **New**.
-
- In the **Variable Name** field, enter **JAVA_HOME** if you installed the **JDK** (Java Development Kit) or **JRE_HOME** if you installed the **JRE** (Java Runtime Environment).
-
- In the **Variable Value** field, enter your **JDK** or **JRE** installation path, for example C:\Program Files\Java\jdk11.
-
- Check if the variable created successfully by **echo** command in the **Command Prompt**:
-
- ```
- echo %JAVA_HOME%
- ```
-
-2. Set the **MAVEN_HOME** environment variable:
-
- Unzip the downloaded archive with the maven to any directory, it will be something like this:
-
- ```
- C:\apache-maven-3.8.1
- ```
- In **Windows 7** right click **My Computer** and select **Properties**, then click **Advanced**.
-
- In **Windows 8** go to **Control Panel** -> **System** -> **Advanced System Settings**.
-
- Click the **Environment Variables** button.
-
- Under **System Variables**, click **New**.
-
- In the **Variable Name** field, enter **MAVEN_HOME**.
-
- In the **Variable Value** field, enter your **JDK** or **JRE** installation path, for example C:\apache-maven-3.8.1.
-
- Add C:\apache-maven-3.8.1\bin to the PATH system variable:
- In system variables, find PATH, clicks on the Edit... button. In “Edit environment variable” dialog, clicks on the New button and add this C:\apache-maven-3.8.1\bin
-
- Check if the variable created successfully by **echo** command in the **Command Prompt**:
-
- ```
- echo %MAVEN_HOME%
- ```
-
-
-### Step 5. Start application with Maven
-
-1. Open the console and go the java-spring folder using the **cd** command, for example:
- ```
- cd C:\Program Files\document-server-integration\web\documentserver-example\java-spring
- ```
-2. In the open console enter the following commands:
- ```
- mvn clean
- mvn package
- mvn spring-boot:run
- ```
-3. Open your browser using **server.address** and **server.port**:
-
- ```
- http://server.address:server.port/
- ```
-
-### Step 6. Check accessibility
-
- In case the example and Document Server are installed on different computers, make sure that your server with the example installed has access to the Document Server with the address which you specify instead of **documentserver** in the configuration files.
-
-Make sure that the Document Server has access to the server with the example installed with the address which you specify instead of **example.com** in the configuration files.
-
-## For Linux
-### Step 1. Install ONLYOFFICE Docs
-
-Download and install ONLYOFFICE Docs (packaged as Document Server).
-
-See the detailed guide to learn how to install Document Server [for Linux](https://helpcenter.onlyoffice.com/installation/docs-developer-install-ubuntu.aspx).
-
-### Step 2. Install the prerequisites and run the website with the editors
-
-1. Install **Java**:
-
- ```
- sudo add-apt-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java11-installer
- ```
-
-2. Download the archive with the Java-Spring example and unpack the archive or clone git repository:
-
- a) archive with Java-Spring:
-
- ```
- wget https://api.onlyoffice.com/app_data/editor/Java%20Spring%20Example.zip
- ```
-
- ```
- unzip Java\ Spring\ Example.zip
- ```
- b) git repository:
- ```
- git clone https://github.com/ONLYOFFICE/document-server-integration.git
- ```
-
-
-3. Change the current directory for the project directory:
-
- a) from archive
-
- ```
- cd Java\ Spring\ Example/
- ```
- b) from git repository
- ```
- cd document-server-integration/web/documentserver-example/java-spring
- ```
-4. Edit the *application.properties* configuration file. Specify the name of your local server with the ONLYOFFICE Document Server installed.
-
- ```
- nano src/main/resources/application.properties
- ```
-
- Edit the following lines:
-
- ```
- files.storage=
- server.port=port
- files.docservice.url.site=https://documentserver/
- ```
-
- where the **documentserver** is the name of the server with the ONLYOFFICE Docs installed, **port** is any available port and **files.storage** is the path where files will be created and stored (in the project folder by default). You can set an absolute path.
-
-
-5. Install **Maven**:
-
- ```
- sudo apt-get install maven
- ```
-
-6. Build:
-
- ```
- mvn package
- ```
-
- 7. Start Java-Spring example:
- ```
- ./mvnw spring-boot:run
- ```
- 8. Open your browser using **server.address** and **server.port**:
-
- ```
- http://server.address:server.port/
- ```
+# Spring-Boot-onlyOffice(集成onlyOffice服务)
+
+springboot集成onlyOffice的实现。在参考网络上的资料结合自身实际情况总结,让集成oo方便快捷。 封装了oo服务的API和统一了配置。
+- 在线编辑,查看,转换
+
+
+* onlyOffice.yml配置文件
+* 如果解决了你地方问题,请给个 **star**
+-----------------------------------
+# 对外使用的java类 —— OnlyServiceAPI
+## 核心方法
+
+
+
+
+ 方法名称
+ 参数
+ 参数说明
+ 返回值
+
+
+
+
+ openDocument()
+ Map<String,Object> map
+ 文件数据信息
+ {
+ 必填 fileId
+ 必填 fileName
+ 必填 fileType
+ 必填 fileSize
+ 可用携带其它值
+ }
+
+
+
+{
+"editorConfig": {
+ "mode": "edit",
+ "customization": {
+ "feedback": {
+ "visible": false
+ },
+ "help": false,
+ "goback": {
+ "blank": false
+ },
+ "macros": false,
+ "autosave": false,
+ "comments": false,
+ "review": {},
+ "hideRightMenu": true,
+ "anonymous": {
+ "request": false
+ },
+ "forcesave": true,
+ "logo": {},
+ "hideNotes": true
+ },
+ "plugins": {
+ "pluginsData": [],
+ "autostart": []
+ },
+ "callbackUrl": "http://172.31.240.1:9090/onlyOffice/save",
+ "lang": "zh-CN",
+ "user": {
+ "name": "TongHuic7bba5",
+ "id": "c7bba5"
+ }
+ },
+"docServiceApiUrl": "http://172.31.240.1:8886/web-apps/apps/api/documents/api.js",
+"documentType": "word",
+"document": {
+ "permissions": {
+ "edit": true,
+ "chat": false,
+ "review": false
+ },
+ "title": "fdfs.docx",
+ "fileType": "docx",
+ "key": "63f560ec03a94654b10cd4fdeebec05a",
+ "url": "http://172.31.240.1:9090/download/09cee8767dd3476280fa865bacfaf213",
+ "info": {
+ "sharingSettings": [{
+ "isLink": true,
+ "permissions": ["Full Access"],
+ "user": "TongHuic7bba5"
+ }],
+ "created": "2023-08-05 21:38:25"
+ }
+},
+"type": "desktop",
+"token": ""
+}
+
+
+
+ String mode
+ 打开方式 edit view
+
+
+ boolean collaborativeEditing
+ 是否协同编辑
+
+
+ handlerStatus()
+ JSONObject jsonObject
+ onlyOffice 回调传来的值。 https://api.onlyoffice.com/editors/callback
+
+
+
+ save():触发保存回调。
+ String key
+ 是openDocument()返回值中的key
+ String : 提示信息
+
+
+ String userId
+ 用户Id
+
+
+ converted()
+ String filetype
+ 文件类型
+ 转换后的文件下载地址
+
+
+ String fileId
+ 文件Id
+
+
+ String outputtype
+ 转化类型
+
+
+ String title
+ 转换后的文件名称
+
+
+ String password
+ 文档密码
+
+
+
+
+**注意:**
+ * 外部触发保存操作,save()方法。
+ * `autosave`/`forcesave` 参数为默认值时有效
+ * 修改文件后,没有执行回调方法。在点击保存后执行回调
+
+
+
+
+快速使用
+-----------------------------------
+
+- 必须的依赖
+
+``` pom
+
+ org.springframework.boot
+ spring-boot-starter-data-redis
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+ com.alibaba
+ fastjson
+ 2.0.25
+
+
+ cn.hutool
+ hutool-all
+ 5.8.16
+
+
+ com.inversoft
+ prime-jwt
+ 1.3.1
+
+
+ org.apache.commons
+ commons-pool2
+
+```
+
+- 定义关键接口(oo服务回调使用) `重要`
+ 1.保存接口
+ ```
+ 参考:demo/controller/IndexController.saveFile()
+ 对应配置文件参数:oo.call-back-url
+ 回调状态
+ 0 - 找不到具有密钥标识符的文档
+ 1 - 正在编辑文档(打开文件回调)
+ 2 - 文档已准备好保存
+ 3 - 发生文档保存错误
+ 4 - 不作任何更改就关闭文档(关闭回调)
+ 6 - 正在编辑文档,但保存当前文档状态(保存回调)
+ 7 - 强制保存文档时发生错误
+ ```
-### Step 3. Check accessibility
+ 2.下载文件地址
+ ```
+ 参考:demo/controller/IndexController.download()
+ 对应配置文件参数:oo.download-file
+ 对应openDocument()方法返回值中的 document.url
+ 打开文件后oo服务要下载对应的文件
+ ```
+- 实现SaveFileProcessor类
+ ```
+ 参考:demo.service.DemoService
+ ```
+
+
+
+ 方法名称
+ 方法说明
+ 参数
+ 参数说明
+ 返回值
+
+
+
+
+ saveBeforeInitialization()
+ 保存前置方法
+ Map<String, Object> map
+ 在openDocument()方法中传入的文件数据信息
+
+
+
+ byte[] bytes
+ 文件二进制数据
+
+
+ String fileExtension
+ 文件后缀
+
+
+ save()
+ 保存方法,实现自己的保存逻辑
+ Map<String, Object> map
+ 在openDocument()方法中传入的文件数据信息
+ Map<String, Object> 更新内存中的信息
+
+
+ byte[] bytes
+ 文件二进制数据
+
+
+ byte[] changes
+ 当前文件和保存之前文件的区别。changes.zip
+
+
+ String key
+ 是openDocument()返回值中的key
+
+
+ saveAfterInitialization()
+ 保存后置方法
+ Map<String, Object> map
+ 在openDocument()方法中传入的文件数据信息
+
+
+
+ byte[] bytes
+ 文件二进制数据
+
+
+ String fileExtension
+ 文件后缀
+
+
+
-In case the example and Document Server are installed on different computers, make sure that your server with the example installed has access to the Document Server with the address which you specify instead of **documentserver** in the configuration files.
-Make sure that the Document Server has access to the server with the example installed with the address which you specify instead of **example.com** in the configuration files.
+## 更新记录
+
+- [x] 修复关闭文件后快速再次打开该文件后,保存时报错的bug 2023/11/10
+- [x] 修复内存文件信息在保存后没有修改的bug 2023/10/23
+- [x] 实现和编辑器的数据通信 2023/9/9 (更新链接)
+ https://blog.xenosp.cn/posts/87468caf/
+- [x] 修复文件转pdf时只有第一页的bug 2023/8/13
+
+
+
+
+
+
+
+-----------------------------------
+
+
+# 页面集成
+### html
+```
+参考 onlyOffice.html
+style.js 中的openDocument()
+```
+### vue
+```
+参考 onlyOffice.vue
+```
+-----------------------------------
+
+
+### 编辑
+
+
+
+
+### 查看
+
+
+
+
+### 文件转换
+
+
+
-## For Docker
-1. Edit the *application.properties* configuration file. Specify the name of your local server with the ONLYOFFICE Document Server installed ([installation instructions](https://helpcenter.onlyoffice.com/installation/docs-developer-install-docker.aspx)).
- ```
- nano src/main/resources/application.properties
- ```
-
-2. Edit the following lines:
- ```
- files.storage=
- server.port=port
- files.docservice.url.site=https://documentserver/
- ```
- where the **documentserver** is the name of the server with the ONLYOFFICE Docs installed, **port** is any available port and **files.storage** is the path where files will be created and stored (in the project folder by default). You can set an absolute path.
-3. Run the next command in the java example directory:
- ```
- docker-compose up
- ```
-4. Open your browser using **server.address** and **server.port**:
- ```
- http://server.address:server.port/
- ```
-## Important security info
-Please keep in mind the following security aspects when you are using test examples:
-* There is no protection of the storage from unauthorized access since there is no need for authorization.
-* There are no checks against parameter substitution in links, since the parameters are generated by the code according to the pre-arranged scripts.
-* There are no data checks in requests of saving the file after editing, since each test example is intended for requests only from ONLYOFFICE Document Server.
-* There are no prohibitions on using test examples from other sites, since they are intended to interact with ONLYOFFICE Document Server from another domain.
\ No newline at end of file
diff --git a/file/8c969104e32f4efc9d83946ad5108ce2 b/file/8c969104e32f4efc9d83946ad5108ce2
new file mode 100644
index 0000000..e69de29
diff --git a/file/a0f59131619d430fb72a146ca2477ff6.docx b/file/a0f59131619d430fb72a146ca2477ff6.docx
new file mode 100644
index 0000000..4efa3ba
Binary files /dev/null and b/file/a0f59131619d430fb72a146ca2477ff6.docx differ
diff --git a/jpg/QQ截图20230805221213.jpg b/jpg/QQ截图20230805221213.jpg
new file mode 100644
index 0000000..ab2ec13
Binary files /dev/null and b/jpg/QQ截图20230805221213.jpg differ
diff --git a/jpg/docx-pdf.jpg b/jpg/docx-pdf.jpg
new file mode 100644
index 0000000..3927db4
Binary files /dev/null and b/jpg/docx-pdf.jpg differ
diff --git a/jpg/edit.jpg b/jpg/edit.jpg
new file mode 100644
index 0000000..b969a8b
Binary files /dev/null and b/jpg/edit.jpg differ
diff --git a/jpg/editppt.jpg b/jpg/editppt.jpg
new file mode 100644
index 0000000..79df123
Binary files /dev/null and b/jpg/editppt.jpg differ
diff --git a/jpg/editxlsx.jpg b/jpg/editxlsx.jpg
new file mode 100644
index 0000000..ea3fa88
Binary files /dev/null and b/jpg/editxlsx.jpg differ
diff --git a/jpg/f.jpg b/jpg/f.jpg
new file mode 100644
index 0000000..cefac1c
Binary files /dev/null and b/jpg/f.jpg differ
diff --git a/jpg/view.jpg b/jpg/view.jpg
new file mode 100644
index 0000000..237dbb5
Binary files /dev/null and b/jpg/view.jpg differ
diff --git a/jpg/viewppt.jpg b/jpg/viewppt.jpg
new file mode 100644
index 0000000..4f44484
Binary files /dev/null and b/jpg/viewppt.jpg differ
diff --git a/jpg/viewxls.jpg b/jpg/viewxls.jpg
new file mode 100644
index 0000000..fd9e82f
Binary files /dev/null and b/jpg/viewxls.jpg differ
diff --git a/jpg/xlsx2pdf.jpg b/jpg/xlsx2pdf.jpg
new file mode 100644
index 0000000..5007691
Binary files /dev/null and b/jpg/xlsx2pdf.jpg differ
diff --git a/plugins/externallistener/README.md b/plugins/externallistener/README.md
new file mode 100644
index 0000000..194ca7d
--- /dev/null
+++ b/plugins/externallistener/README.md
@@ -0,0 +1,3 @@
+## Overview
+
+(Linux服务器安装好)把当前文件夹放到路径: /var/www/onlyoffice/documentserver/sdkjs-plugins
\ No newline at end of file
diff --git a/plugins/externallistener/config.json b/plugins/externallistener/config.json
new file mode 100644
index 0000000..93d38c1
--- /dev/null
+++ b/plugins/externallistener/config.json
@@ -0,0 +1,25 @@
+{
+ "name" : "Listener",
+ "guid" : "asc.{A8705DEE-7544-4C33-B3D5-168406D92F72}",
+ "baseUrl" : "",
+ "variations" : [
+ {
+ "description" : "Listener",
+ "url" : "index.html",
+ "icons" : ["resources/img/icon.png", "resources/img/icon@2x.png"],
+ "isViewer" : false,
+ "EditorsSupport" : ["word", "cell", "slide"],
+ "isVisual" : false,
+ "isModal" : true,
+ "isInsideMode" : false,
+ "isSystem" : true,
+ "initDataType" : "none",
+ "initData" : "",
+ "isUpdateOleOnResize" : true,
+ "buttons" : [],
+ "events" : [
+ "onExternalPluginMessage"
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/plugins/externallistener/index.html b/plugins/externallistener/index.html
new file mode 100644
index 0000000..3d73063
--- /dev/null
+++ b/plugins/externallistener/index.html
@@ -0,0 +1,28 @@
+
+
+
+
+
+ Listener
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/plugins/externallistener/resources/img/icon.png b/plugins/externallistener/resources/img/icon.png
new file mode 100644
index 0000000..afd662c
Binary files /dev/null and b/plugins/externallistener/resources/img/icon.png differ
diff --git a/plugins/externallistener/resources/img/icon@2x.png b/plugins/externallistener/resources/img/icon@2x.png
new file mode 100644
index 0000000..75a16d8
Binary files /dev/null and b/plugins/externallistener/resources/img/icon@2x.png differ
diff --git a/plugins/externallistener/scripts/code.js b/plugins/externallistener/scripts/code.js
new file mode 100644
index 0000000..4472bc6
--- /dev/null
+++ b/plugins/externallistener/scripts/code.js
@@ -0,0 +1,103 @@
+/**
+ *
+ * (c) Copyright Ascensio System SIA 2020
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+(function(window, undefined){
+
+ window.Asc.plugin.init = function() {
+ console.log("插件初始化")
+
+ // none
+ window.parent.Common.Gateway.on('internalcommand', function(data){
+ console.log(data); // 接受到123参数console.log(data.data); // 接受到321参数
+ var data_ = data.data
+ switch (data.command){
+ case "insertText":
+ let text = "${"+data_.text+"}"
+ window.Asc.plugin.executeMethod ("PasteText", [text]);
+ if(window.Asc.plugin.info.editorType == 'cell'){
+ CorrectText('insertText')
+ }
+ break;
+ case 'getText':
+ CorrectText('getText')
+ break
+ }
+ });
+
+ var _info = window.Asc.plugin.info;
+ var userName =_info.userName
+ var userId = _info.userId
+
+ function CorrectText (command) {
+ let data = {
+ command:command,
+ text:""
+ }
+ switch (window.Asc.plugin.info.editorType) {
+ case 'word':
+ case 'slide': {
+ window.Asc.plugin.executeMethod ("GetSelectedText", [{"Numbering": false, "Math": false, "TableCellSeparator": '\n', "ParaSeparator": '\n', "TabSymbol": String.fromCharCode(9)}], function (e) {
+ let text = e.trim()
+ data.text = text
+ window.parent.parent.postMessage(JSON.stringify(data),'*');
+ });
+ break;
+ }
+ case 'cell': {
+ Asc.scope.command = command;
+ window.Asc.plugin.callCommand (function () {
+ var oWorksheet = Api.GetActiveSheet();
+ var oActiveCell = oWorksheet.GetActiveCell();
+ let str = oActiveCell.Text
+ if(str.indexOf("${") != -1){
+ str = str.substring(2,str.length-1)
+ }
+ let data = {
+ command:Asc.scope.command,
+ sheetName:oWorksheet.Name,
+ text:str,
+ x:oActiveCell.Row,
+ y:oActiveCell.Col
+ }
+
+ localStorage.setItem('dataInfo', JSON.stringify(data))
+ }, false,false,function(){
+ window.parent.parent.postMessage(localStorage.getItem('dataInfo'),'*');
+ localStorage.removeItem('dataInfo')
+ });
+ /* window.Asc.plugin.executeMethod ("GetSelectedText", [{"Numbering": false, "Math": false, "TableCellSeparator": '\n', "ParaSeparator": '\n', "TabSymbol": String.fromCharCode(9)}], function (e) {
+ let text = e.trim()
+ console.log(text)
+ data.text = text
+ if (text == '') {
+ text = text.replace (/\t/g, '\n');
+ window.parent.parent.postMessage(JSON.stringify(data),'*');
+ }
+ else {
+
+ }
+ });*/
+ break;
+ }
+ }
+ }
+ };
+
+ window.Asc.plugin.button = function(id) {
+ };
+
+})(window, undefined);
diff --git a/plugins/externallistener/translations/langs.json b/plugins/externallistener/translations/langs.json
new file mode 100644
index 0000000..82daa55
--- /dev/null
+++ b/plugins/externallistener/translations/langs.json
@@ -0,0 +1,3 @@
+[
+ "zh-CN"
+]
\ No newline at end of file
diff --git a/plugins/externallistener/translations/zh-CN.json b/plugins/externallistener/translations/zh-CN.json
new file mode 100644
index 0000000..0e0dcd2
--- /dev/null
+++ b/plugins/externallistener/translations/zh-CN.json
@@ -0,0 +1,3 @@
+{
+
+}
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index ba4ac4d..7d383c5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,112 +1,147 @@
- 4.0.0
-
- org.springframework.boot
- spring-boot-starter-parent
- 2.5.1
-
-
- com.onlyoffice
- integration
- 1.0
- Java Spring Integration Example
- ONLYOFFICE Java Spring Integration
-
- 11
-
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
- org.springframework.boot
- spring-boot-devtools
- true
-
-
- org.springframework.boot
- spring-boot-starter-thymeleaf
- 2.5.1
-
-
- org.springframework.boot
- spring-boot-starter-data-jpa
-
-
- com.h2database
- h2
- runtime
-
-
- com.googlecode.json-simple
- json-simple
- 1.1
-
-
- com.google.code.gson
- gson
- 2.8.9
-
-
- com.inversoft
- prime-jwt
- 1.3.1
-
-
- org.projectlombok
- lombok
- 1.18.20
- provided
-
-
- com.fasterxml.jackson.core
- jackson-core
- 2.13.4
-
-
- com.fasterxml.jackson.core
- jackson-databind
- 2.13.4.2
-
-
- org.modelmapper
- modelmapper
- 2.4.2
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
- org.apache.maven.plugins
- maven-checkstyle-plugin
- 3.2.0
-
-
- validate
- validate
-
- checkstyle.xml
- true
- true
- true
- warning
- true
- true
-
-
-
- check
-
-
-
-
-
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.6.6
+
+
+ com.oo
+ Spring-Boot-onlyOffice
+ 0.0.1-SNAPSHOT
+ Spring-Boot-onlyOffice
+ Demo project for Spring Boot
+
+ 1.8
+
+
+
+ org.springframework.boot
+ spring-boot-starter-thymeleaf
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ org.springframework.boot
+ spring-boot-devtools
+ true
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ com.baomidou
+ mybatis-plus-boot-starter
+ 3.5.1
+
+
+ com.baomidou
+ mybatis-plus-generator
+ 3.5.1
+
+
+ com.alibaba
+ druid-spring-boot-starter
+ 1.1.22
+
+
+ mysql
+ mysql-connector-java
+ 8.0.17
+
+
+ com.alibaba
+ fastjson
+ 2.0.25
+
+
+ cn.hutool
+ hutool-all
+ 5.8.16
+
+
+ com.inversoft
+ prime-jwt
+ 1.3.1
+
+
+ org.apache.commons
+ commons-pool2
+
+
+ org.springframework.boot
+ spring-boot-starter-data-redis
+
+
+ commons-fileupload
+ commons-fileupload
+ 1.4
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.projectlombok
+ lombok
+
+
+
+
+
+
+
+
+ spring-milestones
+ Spring Milestones
+ https://repo.spring.io/milestone
+
+ false
+
+
+
+ spring-snapshots
+ Spring Snapshots
+ https://repo.spring.io/snapshot
+
+ false
+
+
+
+
+
+ spring-milestones
+ Spring Milestones
+ https://repo.spring.io/milestone
+
+ false
+
+
+
+ spring-snapshots
+ Spring Snapshots
+ https://repo.spring.io/snapshot
+
+ false
+
+
+
+
diff --git a/src/main/java/com/onlyoffice/integration/ExampleData.java b/src/main/java/com/onlyoffice/integration/ExampleData.java
deleted file mode 100644
index 6fe3c3a..0000000
--- a/src/main/java/com/onlyoffice/integration/ExampleData.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration;
-
-import com.onlyoffice.integration.documentserver.serializers.FilterState;
-import com.onlyoffice.integration.services.UserServices;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-import java.util.ArrayList;
-import java.util.List;
-
-@Component
-public class ExampleData {
- @Autowired
- private UserServices userService;
- @PostConstruct
- public void init() {
- // the description for user 0
- List descriptionUserZero = List.of(
- "The name is requested when the editor is opened",
- "Doesn’t belong to any group",
- "Can review all the changes",
- "Can perform all actions with comments",
- "The file favorite state is undefined",
- "Can't mention others in comments",
- "Can't create new files from the editor",
- "Can’t see anyone’s information",
- "Can't rename files from the editor",
- "Can't view chat",
- "Can't protect file",
- "View file without collaboration"
- );
-
- // the description for user 1
- List descriptionUserFirst = List.of(
- "File author by default",
- "He doesn’t belong to any of the groups",
- "He can review all the changes",
- "He can do everything with the comments",
- "The file favorite state is undefined",
- "Can create a file from a template with data from the editor",
- "Can see the information about all users",
- "Can view chat"
- );
-
- // the description for user 2
- List descriptionUserSecond = List.of(
- "He belongs to Group2",
- "He can review only his own changes or the changes made by the users who don’t belong"
- + " to any of the groups",
- "He can view every comment, edit his comments and the comments left by the users "
- + "who don't belong to any of the groups and remove only his comments",
- "This file is favorite",
- "Can create a file from an editor",
- "Can see the information about users from Group2 and users who don’t belong to any group",
- "Can view chat"
- );
-
- // the description for user 3
- List descriptionUserThird = List.of(
- "He belongs to Group3",
- "He can review only the changes made by the users from Group2",
- "He can view the comments left by the users from Group2 and Group3 and edit the comments left by "
- + "the users from Group2",
- "This file isn’t favorite",
- "He can’t copy data from the file into the clipboard",
- "He can’t download the file",
- "He can’t print the file",
- "Can create a file from an editor",
- "Can see the information about Group2 users",
- "Can view chat"
- );
-
- // create user 1 with the specified parameters
- userService.createUser("John Smith", "smith@example.com", descriptionUserFirst,
- "", List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
- List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
- List.of(FilterState.NULL.toString()), null, true, true);
-
- // create user 2 with the specified parameters
- userService.createUser("Mark Pottato", "pottato@example.com", descriptionUserSecond,
- "group-2", List.of("", "group-2"), List.of(FilterState.NULL.toString()),
- List.of("group-2", ""), List.of("group-2"), List.of("group-2", ""), true, true,
- true);
-
- // create user 3 with the specified parameters
- userService.createUser("Hamish Mitchell", "mitchell@example.com", descriptionUserThird,
- "group-3", List.of("group-2"), List.of("group-2", "group-3"), List.of("group-2"),
- new ArrayList<>(), List.of("group-2"), false, true, true);
-
- // create user 0 with the specified parameters
- userService.createUser("Anonymous", null, descriptionUserZero, "",
- List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
- List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
- new ArrayList<>(), null, false, false);
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/IntegrationApplication.java b/src/main/java/com/onlyoffice/integration/IntegrationApplication.java
deleted file mode 100644
index 4a1a0cc..0000000
--- a/src/main/java/com/onlyoffice/integration/IntegrationApplication.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-
-@SpringBootApplication
-public class IntegrationApplication {
-
- // run the SpringApplication from the IntagrationApplication with the specified parameters
- public static void main(final String[] args) {
- SpringApplication.run(IntegrationApplication.class, args);
- }
-
-}
diff --git a/src/main/java/com/onlyoffice/integration/IntegrationConfiguration.java b/src/main/java/com/onlyoffice/integration/IntegrationConfiguration.java
deleted file mode 100644
index d9d7520..0000000
--- a/src/main/java/com/onlyoffice/integration/IntegrationConfiguration.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import org.json.simple.parser.JSONParser;
-import org.modelmapper.ModelMapper;
-import org.modelmapper.convention.MatchingStrategies;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-import javax.annotation.PostConstruct;
-
-import com.onlyoffice.integration.documentserver.util.SSLUtils;
-
-@Configuration
-public class IntegrationConfiguration {
-
- @Value("${files.storage}")
- private String storageAddress;
-
- @Value("${files.docservice.verify-peer-off}")
- private String verifyPerrOff;
-
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
-
- @Autowired
- private SSLUtils ssl;
-
- @Bean
- public ModelMapper mapper() { // create the model mapper
- ModelMapper mapper = new ModelMapper();
- mapper.getConfiguration() // get the mapper configuration and set new parameters to it
- .setMatchingStrategy(MatchingStrategies.STRICT) // specify the STRICT matching strategy
- .setFieldMatchingEnabled(true) // define if the field matching is enabled or not
- .setSkipNullEnabled(true) // define if null value will be skipped or not
- .setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); /* specify
- the PRIVATE field access level */
- return mapper;
- }
-
- @Bean
- public JSONParser jsonParser() { // create JSON parser
- return new JSONParser();
- }
-
- @PostConstruct
- public void init() { // initialize the storage path builder
- storagePathBuilder.configure(storageAddress.isBlank() ? null : storageAddress);
- if (!verifyPerrOff.isEmpty()) {
- try {
- if (verifyPerrOff.equals("true")) {
- ssl.turnOffSslChecking(); //the certificate will be ignored
- } else {
- ssl.turnOnSslChecking(); //the certificate will be verified
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
-
- @Bean
- public ObjectMapper objectMapper() { // create the object mapper
- return new ObjectMapper();
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/controllers/EditorController.java b/src/main/java/com/onlyoffice/integration/controllers/EditorController.java
deleted file mode 100644
index f9c24ad..0000000
--- a/src/main/java/com/onlyoffice/integration/controllers/EditorController.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.controllers;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.onlyoffice.integration.documentserver.managers.history.HistoryManager;
-import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
-import com.onlyoffice.integration.documentserver.models.enums.Action;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import com.onlyoffice.integration.entities.User;
-import com.onlyoffice.integration.dto.Mentions;
-import com.onlyoffice.integration.documentserver.models.enums.Type;
-import com.onlyoffice.integration.documentserver.models.filemodel.FileModel;
-import com.onlyoffice.integration.services.UserServices;
-import com.onlyoffice.integration.services.configurers.FileConfigurer;
-import com.onlyoffice.integration.services.configurers.wrappers.DefaultFileWrapper;
-import lombok.SneakyThrows;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.CookieValue;
-import org.springframework.web.bind.annotation.CrossOrigin;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Optional;
-
-import static com.onlyoffice.integration.documentserver.util.Constants.ANONYMOUS_USER_ID;
-
-@CrossOrigin("*")
-@Controller
-public class EditorController {
-
- @Value("${files.docservice.url.site}")
- private String docserviceSite;
-
- @Value("${files.docservice.url.api}")
- private String docserviceApiUrl;
-
- @Value("${files.docservice.languages}")
- private String langs;
-
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
-
- @Autowired
- private JwtManager jwtManager;
-
- @Autowired
- private UserServices userService;
-
- @Autowired
- private HistoryManager historyManager;
-
- @Autowired
- private ObjectMapper objectMapper;
-
- @Autowired
- private FileConfigurer fileConfigurer;
-
- @GetMapping(path = "${url.editor}")
- // process request to open the editor page
- public String index(@RequestParam("fileName") final String fileName,
- @RequestParam(value = "action", required = false) final String actionParam,
- @RequestParam(value = "type", required = false) final String typeParam,
- @RequestParam(value = "actionLink", required = false) final String actionLink,
- @RequestParam(value = "directUrl", required = false,
- defaultValue = "false") final Boolean directUrl,
- @CookieValue(value = "uid") final String uid,
- @CookieValue(value = "ulang") final String lang,
- final Model model) throws JsonProcessingException {
- Action action = Action.edit;
- Type type = Type.desktop;
- Locale locale = new Locale("en");
-
- if (actionParam != null) {
- action = Action.valueOf(actionParam);
- }
- if (typeParam != null) {
- type = Type.valueOf(typeParam);
- }
-
- List langsAndKeys = Arrays.asList(langs.split("\\|"));
- for (String langAndKey : langsAndKeys) {
- String[] couple = langAndKey.split(":");
- if (couple[0].equals(lang)) {
- String[] langAndCountry = couple[0].split("-");
- locale = new Locale(langAndCountry[0], langAndCountry.length > 1 ? langAndCountry[1] : "");
- }
- }
-
- Optional optionalUser = userService.findUserById(Integer.parseInt(uid));
-
- // if the user is not present, return the ONLYOFFICE start page
- if (!optionalUser.isPresent()) {
- return "index.html";
- }
-
- User user = optionalUser.get();
-
- // get file model with the default file parameters
- FileModel fileModel = fileConfigurer.getFileModel(
- DefaultFileWrapper
- .builder()
- .fileName(fileName)
- .type(type)
- .lang(locale.toLanguageTag())
- .action(action)
- .user(user)
- .actionData(actionLink)
- .isEnableDirectUrl(directUrl)
- .build()
- );
-
- // add attributes to the specified model
- // add file model with the default parameters to the original model
- model.addAttribute("model", fileModel);
-
- // get file history and add it to the model
- model.addAttribute("fileHistory", historyManager.getHistory(fileModel.getDocument()));
-
- // create the document service api URL and add it to the model
- model.addAttribute("docserviceApiUrl", docserviceSite + docserviceApiUrl);
-
- // get an image and add it to the model
- model.addAttribute("dataInsertImage", getInsertImage(directUrl));
-
- // get a document for comparison and add it to the model
- model.addAttribute("dataCompareFile", getCompareFile(directUrl));
-
- // get recipients data for mail merging and add it to the model
- model.addAttribute("dataMailMergeRecipients", getMailMerge(directUrl));
-
- // get user data for mentions and add it to the model
- model.addAttribute("usersForMentions", getUserMentions(uid));
- return "editor.html";
- }
-
- private List getUserMentions(final String uid) { // get user data for mentions
- List usersForMentions = new ArrayList<>();
- if (uid != null && !uid.equals("4")) {
- List list = userService.findAll();
- for (User u : list) {
- if (u.getId() != Integer.parseInt(uid) && u.getId() != ANONYMOUS_USER_ID) {
-
- // user data includes user names and emails
- usersForMentions.add(new Mentions(u.getName(), u.getEmail()));
- }
- }
- }
-
- return usersForMentions;
- }
-
- @SneakyThrows
- private String getInsertImage(final Boolean directUrl) { // get an image that will be inserted into the document
- Map dataInsertImage = new HashMap<>();
- dataInsertImage.put("fileType", "png");
- dataInsertImage.put("url", storagePathBuilder.getServerUrl(true) + "/css/img/logo.png");
- if (directUrl) {
- dataInsertImage.put("directUrl", storagePathBuilder
- .getServerUrl(false) + "/css/img/logo.png");
- }
-
- // check if the document token is enabled
- if (jwtManager.tokenEnabled()) {
-
- // create token from the dataInsertImage object
- dataInsertImage.put("token", jwtManager.createToken(dataInsertImage));
- }
-
- return objectMapper.writeValueAsString(dataInsertImage)
- .substring(1, objectMapper.writeValueAsString(dataInsertImage).length() - 1);
- }
-
- // get a document that will be compared with the current document
- @SneakyThrows
- private String getCompareFile(final Boolean directUrl) {
- Map dataCompareFile = new HashMap<>();
- dataCompareFile.put("fileType", "docx");
- dataCompareFile.put("url", storagePathBuilder.getServerUrl(true) + "/assets?name=sample.docx");
- if (directUrl) {
- dataCompareFile.put("directUrl", storagePathBuilder
- .getServerUrl(false) + "/assets?name=sample.docx");
- }
-
- // check if the document token is enabled
- if (jwtManager.tokenEnabled()) {
-
- // create token from the dataCompareFile object
- dataCompareFile.put("token", jwtManager.createToken(dataCompareFile));
- }
-
- return objectMapper.writeValueAsString(dataCompareFile);
- }
-
- @SneakyThrows
- private String getMailMerge(final Boolean directUrl) {
- Map dataMailMergeRecipients = new HashMap<>(); // get recipients data for mail merging
- dataMailMergeRecipients.put("fileType", "csv");
- dataMailMergeRecipients.put("url", storagePathBuilder.getServerUrl(true) + "/csv");
- if (directUrl) {
- dataMailMergeRecipients.put("directUrl", storagePathBuilder.getServerUrl(false) + "/csv");
- }
-
- // check if the document token is enabled
- if (jwtManager.tokenEnabled()) {
-
- // create token from the dataMailMergeRecipients object
- dataMailMergeRecipients.put("token", jwtManager.createToken(dataMailMergeRecipients));
- }
-
- return objectMapper.writeValueAsString(dataMailMergeRecipients);
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/controllers/FileController.java b/src/main/java/com/onlyoffice/integration/controllers/FileController.java
deleted file mode 100644
index c5259ea..0000000
--- a/src/main/java/com/onlyoffice/integration/controllers/FileController.java
+++ /dev/null
@@ -1,624 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.controllers;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.onlyoffice.integration.documentserver.callbacks.CallbackHandler;
-import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
-import com.onlyoffice.integration.documentserver.storage.FileStorageMutator;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import com.onlyoffice.integration.dto.Converter;
-import com.onlyoffice.integration.dto.ConvertedData;
-import com.onlyoffice.integration.dto.Track;
-import com.onlyoffice.integration.entities.User;
-import com.onlyoffice.integration.documentserver.models.enums.DocumentType;
-import com.onlyoffice.integration.services.UserServices;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import com.onlyoffice.integration.documentserver.util.service.ServiceConverter;
-import com.onlyoffice.integration.documentserver.managers.document.DocumentManager;
-import com.onlyoffice.integration.documentserver.managers.callback.CallbackManager;
-
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.core.io.Resource;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.CookieValue;
-import org.springframework.web.bind.annotation.CrossOrigin;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.PutMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.multipart.MultipartFile;
-
-import javax.servlet.http.HttpServletRequest;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Optional;
-
-@CrossOrigin("*")
-@Controller
-public class FileController {
-
- @Value("${files.docservice.header}")
- private String documentJwtHeader;
-
- @Value("${filesize-max}")
- private String filesizeMax;
-
- @Value("${files.docservice.url.site}")
- private String docserviceUrlSite;
-
- @Value("${files.docservice.url.command}")
- private String docserviceUrlCommand;
-
- @Autowired
- private FileUtility fileUtility;
- @Autowired
- private DocumentManager documentManager;
- @Autowired
- private JwtManager jwtManager;
- @Autowired
- private FileStorageMutator storageMutator;
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
- @Autowired
- private UserServices userService;
- @Autowired
- private CallbackHandler callbackHandler;
- @Autowired
- private ObjectMapper objectMapper;
- @Autowired
- private ServiceConverter serviceConverter;
- @Autowired
- private CallbackManager callbackManager;
-
- // create user metadata
- private String createUserMetadata(final String uid, final String fullFileName) {
- Optional optionalUser = userService.findUserById(Integer.parseInt(uid)); // find a user by their ID
- String documentType = fileUtility.getDocumentType(fullFileName).toString().toLowerCase(); // get document type
- if (optionalUser.isPresent()) {
- User user = optionalUser.get();
- storageMutator.createMeta(fullFileName, // create meta information with the user ID and name specified
- String.valueOf(user.getId()), user.getName());
- }
- return "{ \"filename\": \"" + fullFileName + "\", \"documentType\": \"" + documentType + "\" }";
- }
-
- // download data from the specified file
- private ResponseEntity downloadFile(final String fileName) {
- Resource resource = storageMutator.loadFileAsResource(fileName); // load the specified file as a resource
- String contentType = "application/octet-stream";
-
- // create a response with the content type, header and body with the file data
- return ResponseEntity.ok()
- .contentType(MediaType.parseMediaType(contentType))
- .header(HttpHeaders.CONTENT_DISPOSITION,
- "attachment; filename=\"" + resource.getFilename() + "\"")
- .body(resource);
- }
-
- // download data from the specified history file
- private ResponseEntity downloadFileHistory(final String fileName,
- final String version,
- final String file) {
-
- // load the specified file as a resource
- Resource resource = storageMutator.loadFileAsResourceHistory(fileName, version, file);
- String contentType = "application/octet-stream";
-
- // create a response with the content type, header and body with the file data
- return ResponseEntity.ok()
- .contentType(MediaType.parseMediaType(contentType))
- .header(HttpHeaders.CONTENT_DISPOSITION,
- "attachment; filename=\"" + resource.getFilename() + "\"")
- .body(resource);
- }
-
- @PostMapping("/upload")
- @ResponseBody
- public String upload(@RequestParam("file") final MultipartFile file, // upload a file
- @CookieValue("uid") final String uid) {
- try {
- String fullFileName = file.getOriginalFilename(); // get file name
- String fileExtension = fileUtility.getFileExtension(fullFileName); // get file extension
- long fileSize = file.getSize(); // get file size
- byte[] bytes = file.getBytes(); // get file in bytes
-
- // check if the file size exceeds the maximum file size or is less than 0
- if (fileUtility.getMaxFileSize() < fileSize || fileSize <= 0) {
- return "{ \"error\": \"File size is incorrect\"}"; // if so, write an error message to the response
- }
-
- // check if file extension is supported by the editor
- if (!fileUtility.getFileExts().contains(fileExtension)) {
-
- // if not, write an error message to the response
- return "{ \"error\": \"File type is not supported\"}";
- }
-
- String fileNamePath = storageMutator.updateFile(fullFileName, bytes); // update a file
- if (fileNamePath.isBlank()) {
- throw new IOException("Could not update a file"); // if the file cannot be updated, an error occurs
- }
-
- fullFileName = fileUtility.getFileNameWithoutExtension(fileNamePath) + fileExtension; // get full file name
-
- return createUserMetadata(uid, fullFileName); // create user metadata and return it
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- // if the operation of file uploading is unsuccessful, an error occurs
- return "{ \"error\": \"Something went wrong when uploading the file.\"}";
- }
-
- @PostMapping(path = "${url.converter}")
- @ResponseBody
- public String convert(@RequestBody final Converter body, // convert a file
- @CookieValue("uid") final String uid, @CookieValue("ulang") final String lang) {
- // get file name
- String fileName = body.getFileName();
-
- // get URL for downloading a file with the specified name
- String fileUri = documentManager.getDownloadUrl(fileName, true);
-
- // get file password if it exists
- String filePass = body.getFilePass() != null ? body.getFilePass() : null;
-
- // get file extension
- String fileExt = fileUtility.getFileExtension(fileName);
-
- // get document type (word, cell or slide)
- DocumentType type = fileUtility.getDocumentType(fileName);
-
- // convert to .ooxml
- String internalFileExt = "ooxml";
-
- try {
- // check if the file with such an extension can be converted
- if (fileUtility.getConvertExts().contains(fileExt)) {
- String key = serviceConverter.generateRevisionId(fileUri); // generate document key
- ConvertedData response = serviceConverter // get the URL to the converted file
- .getConvertedData(fileUri, fileExt, internalFileExt, key, filePass, true, lang);
-
- String newFileUri = response.getUri();
- String newFileType = "." + response.getFileType();
-
- if (newFileUri.isEmpty()) {
- return "{ \"step\" : \"0\", \"filename\" : \"" + fileName + "\"}";
- }
-
- /* get a file name of an internal file extension with an index if the file
- with such a name already exists */
- String nameWithInternalExt = fileUtility.getFileNameWithoutExtension(fileName) + newFileType;
- String correctedName = documentManager.getCorrectName(nameWithInternalExt);
-
- URL url = new URL(newFileUri);
- java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
- InputStream stream = connection.getInputStream(); // get input stream of the converted file
-
- if (stream == null) {
- connection.disconnect();
- throw new RuntimeException("Input stream is null");
- }
-
- // remove source file
- storageMutator.deleteFile(fileName);
-
- // create the converted file with input stream
- storageMutator.createFile(Path.of(storagePathBuilder.getFileLocation(correctedName)), stream);
- fileName = correctedName;
- }
-
- // create meta information about the converted file with the user ID and name specified
- return createUserMetadata(uid, fileName);
- } catch (Exception e) {
- e.printStackTrace();
- }
- // if the operation of file converting is unsuccessful, an error occurs
- return "{ \"error\": \"" + "The file can't be converted.\"}";
- }
-
- @PostMapping("/delete")
- @ResponseBody
- public String delete(@RequestBody final Converter body) { // delete a file
- try {
- String fullFileName = fileUtility.getFileName(body.getFileName()); // get full file name
-
- // delete a file from the storage and return the status of this operation (true or false)
- boolean fileSuccess = storageMutator.deleteFile(fullFileName);
-
- // delete file history and return the status of this operation (true or false)
- boolean historySuccess = storageMutator.deleteFileHistory(fullFileName);
-
- return "{ \"success\": \"" + (fileSuccess && historySuccess) + "\"}";
- } catch (Exception e) {
- // if the operation of file deleting is unsuccessful, an error occurs
- return "{ \"error\": \"" + e.getMessage() + "\"}";
- }
- }
-
- @GetMapping("/downloadhistory")
- public ResponseEntity downloadHistory(final HttpServletRequest request, // download a file
- @RequestParam("fileName") final String fileName,
- @RequestParam("ver") final String version,
- @RequestParam("file") final String file) { // history file
- try {
- // check if a token is enabled or not
- if (jwtManager.tokenEnabled() && jwtManager.tokenUseForRequest()) {
- String header = request.getHeader(documentJwtHeader == null // get the document JWT header
- || documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
- if (header != null && !header.isEmpty()) {
- String token = header
- .replace("Bearer ", ""); // token is the header without the Bearer prefix
- jwtManager.readToken(token); // read the token
- } else {
- return null;
- }
- }
- return downloadFileHistory(fileName, version, file); // download data from the specified file
- } catch (Exception e) {
- return null;
- }
- }
-
- @GetMapping(path = "${url.download}")
- public ResponseEntity download(final HttpServletRequest request, // download a file
- @RequestParam("fileName") final String fileName,
- @RequestParam(value = "userAddress", required = false)
- final String userAddress) {
- try {
- // check if a token is enabled or not
- if (jwtManager.tokenEnabled() && userAddress != null && jwtManager.tokenUseForRequest()) {
- String header = request.getHeader(documentJwtHeader == null // get the document JWT header
- || documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
- if (header != null && !header.isEmpty()) {
- String token = header
- .replace("Bearer ", ""); // token is the header without the Bearer prefix
- jwtManager.readToken(token); // read the token
- } else {
- return null;
- }
- }
- return downloadFile(fileName); // download data from the specified file
- } catch (Exception e) {
- return null;
- }
- }
-
- @GetMapping("/create")
- public String create(@RequestParam("fileExt")
- final String fileExt, // create a sample file of the specified extension
- @RequestParam(value = "sample", required = false) final Optional isSample,
- @CookieValue(value = "uid", required = false) final String uid,
- final Model model) {
- // specify if the sample data exists or not
- Boolean sampleData = (isSample.isPresent() && !isSample.isEmpty()) && isSample.get();
- if (fileExt != null) {
- try {
- Optional user = userService.findUserById(Integer.parseInt(uid)); // find a user by their ID
- if (!user.isPresent()) {
- // if the user with the specified ID doesn't exist, an error occurs
- throw new RuntimeException("Could not fine any user with id = " + uid);
- }
- String fileName = documentManager.createDemo(fileExt,
- sampleData,
- uid,
- user.get().getName()); // create a demo document with the sample data
- if (fileName.isBlank() || fileName == null) {
- throw new RuntimeException("You must have forgotten to add asset files");
- }
- return "redirect:editor?fileName=" + URLEncoder
- .encode(fileName, StandardCharsets.UTF_8); // redirect the request
- } catch (Exception ex) {
- model.addAttribute("error", ex.getMessage());
- return "error.html";
- }
- }
- return "redirect:/";
- }
-
- @GetMapping("/assets")
- public ResponseEntity assets(@RequestParam("name")
- final String name) { // get sample files from the assests
- String fileName = Path.of("assets", "document-templates", "sample", fileUtility.getFileName(name)).toString();
- return downloadFile(fileName);
- }
-
- @GetMapping("/csv")
- public ResponseEntity csv() { // download a csv file
- String fileName = Path.of("assets", "document-templates", "sample", "csv.csv").toString();
- return downloadFile(fileName);
- }
-
- @GetMapping("/files")
- @ResponseBody
- public ArrayList> files(@RequestParam(value = "fileId", required = false)
- final String fileId) { // get files information
- return fileId == null ? documentManager.getFilesInfo() : documentManager.getFilesInfo(fileId);
- }
-
- @PostMapping(path = "${url.track}")
- @ResponseBody
- public String track(final HttpServletRequest request, // track file changes
- @RequestParam("fileName") final String fileName,
- @RequestParam("userAddress") final String userAddress,
- @RequestBody final Track body) {
- Track track;
- try {
- String bodyString = objectMapper
- .writeValueAsString(body); // write the request body to the object mapper as a string
- String header = request.getHeader(documentJwtHeader == null // get the request header
- || documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
-
- if (bodyString.isEmpty()) { // if the request body is empty, an error occurs
- throw new RuntimeException("{\"error\":1,\"message\":\"Request payload is empty\"}");
- }
-
- JSONObject bodyCheck = jwtManager.parseBody(bodyString, header); // parse the request body
- track = objectMapper.readValue(bodyCheck.toJSONString(), Track.class); // read the request body
- } catch (Exception e) {
- e.printStackTrace();
- return e.getMessage();
- }
-
- int error = callbackHandler.handle(track, fileName);
-
- return "{\"error\":" + error + "}";
- }
-
- @PostMapping("/saveas")
- @ResponseBody
- public String saveAs(@RequestBody final JSONObject body, @CookieValue("uid") final String uid) {
- String title = (String) body.get("title");
- String saveAsFileUrl = (String) body.get("url");
-
- try {
- String fileName = documentManager.getCorrectName(title);
- String curExt = fileUtility.getFileExtension(fileName);
-
- if (!fileUtility.getFileExts().contains(curExt)) {
- return "{\"error\":\"File type is not supported\"}";
- }
-
- URL url = new URL(saveAsFileUrl);
- java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
- InputStream stream = connection.getInputStream();
-
- if (Integer.parseInt(filesizeMax) < stream.available() || stream.available() <= 0) {
- return "{\"error\":\"File size is incorrect\"}";
- }
- storageMutator.createFile(Path.of(storagePathBuilder.getFileLocation(fileName)), stream);
- createUserMetadata(uid, fileName);
-
- return "{\"file\": \"" + fileName + "\"}";
- } catch (IOException e) {
- e.printStackTrace();
- return "{ \"error\" : 1, \"message\" : \"" + e.getMessage() + "\"}";
- }
- }
-
- @PostMapping("/rename")
- @ResponseBody
- public String rename(@RequestBody final JSONObject body) {
- String newfilename = (String) body.get("newfilename");
- String dockey = (String) body.get("dockey");
- String origExt = "." + (String) body.get("ext");
- String curExt = newfilename;
-
- if (newfilename.indexOf(".") != -1) {
- curExt = (String) fileUtility.getFileExtension(newfilename);
- }
-
- if (origExt.compareTo(curExt) != 0) {
- newfilename += origExt;
- }
-
- HashMap meta = new HashMap<>();
- meta.put("title", newfilename);
-
- try {
- callbackManager.commandRequest("meta", dockey, meta);
- return "result ok";
- } catch (Exception e) {
- e.printStackTrace();
- return e.getMessage();
- }
- }
-
- @PostMapping("/reference")
- @ResponseBody
- public String reference(@RequestBody final JSONObject body) {
- try {
- JSONParser parser = new JSONParser();
- Gson gson = new GsonBuilder().disableHtmlEscaping().create();
-
- String userAddress = "";
- String fileName = "";
-
- if (body.containsKey("referenceData")) {
- LinkedHashMap referenceDataObj = (LinkedHashMap) body.get("referenceData");
- String instanceId = (String) referenceDataObj.get("instanceId");
-
- if (instanceId.equals(storagePathBuilder.getServerUrl(false))) {
- JSONObject fileKey = (JSONObject) parser.parse((String) referenceDataObj.get("fileKey"));
- userAddress = (String) fileKey.get("userAddress");
- if (userAddress.equals(InetAddress.getLocalHost().getHostAddress())) {
- fileName = (String) fileKey.get("fileName");
- }
- }
- }
-
-
- if (fileName.equals("")) {
- try {
- String path = (String) body.get("path");
- path = fileUtility.getFileName(path);
- File f = new File(storagePathBuilder.getFileLocation(path));
- if (f.exists()) {
- fileName = path;
- }
- } catch (Exception e) {
- return "{ \"error\" : 1, \"message\" : \"" + e.getMessage() + "\"}";
- }
- }
-
- if (fileName.equals("")) {
- return "{ \"error\": \"File not found\"}";
- }
-
- boolean directUrl = (boolean) body.get("directUrl");
-
- HashMap fileKey = new HashMap<>();
- fileKey.put("fileName", fileName);
- fileKey.put("userAddress", InetAddress.getLocalHost().getHostAddress());
-
- HashMap referenceData = new HashMap<>();
- referenceData.put("instanceId", storagePathBuilder.getServerUrl(true));
- referenceData.put("fileKey", gson.toJson(fileKey));
-
- HashMap data = new HashMap<>();
- data.put("fileType", fileUtility.getFileExtension(fileName).replace(".", ""));
- data.put("url", documentManager.getDownloadUrl(fileName, true));
- data.put("directUrl", directUrl ? documentManager.getDownloadUrl(fileName, false) : null);
- data.put("referenceData", referenceData);
- data.put("path", fileName);
-
- if (jwtManager.tokenEnabled()) {
- String token = jwtManager.createToken(data);
- data.put("token", token);
- }
- return gson.toJson(data);
- } catch (Exception e) {
- e.printStackTrace();
- return "{ \"error\" : 1, \"message\" : \"" + e.getMessage() + "\"}";
- }
- }
-
- @PutMapping("/restore")
- @ResponseBody
- public String restore(@RequestBody final JSONObject body) {
- try {
- String sourceBasename = (String) body.get("fileName");
- Integer version = (Integer) body.get("version");
- String userID = (String) body.get("userId");
-
- String sourceStringFile = storagePathBuilder.getFileLocation(sourceBasename);
- File sourceFile = new File(sourceStringFile);
- Path sourcePathFile = sourceFile.toPath();
- String historyDirectory = storagePathBuilder.getHistoryDir(sourcePathFile.toString());
-
- Integer bumpedVersion = storagePathBuilder.getFileVersion(historyDirectory, false);
- String bumpedVersionStringDirectory = documentManager.versionDir(historyDirectory, bumpedVersion, true);
- File bumpedVersionDirectory = new File(bumpedVersionStringDirectory);
- if (!bumpedVersionDirectory.exists()) {
- bumpedVersionDirectory.mkdir();
- }
-
- Path bumpedKeyPathFile = Paths.get(bumpedVersionStringDirectory, "key.txt");
- String bumpedKeyStringFile = bumpedKeyPathFile.toString();
- File bumpedKeyFile = new File(bumpedKeyStringFile);
- String bumpedKey = serviceConverter.generateRevisionId(
- storagePathBuilder.getStorageLocation()
- + "/"
- + sourceBasename
- + "/"
- + Long.toString(sourceFile.lastModified())
- );
- FileWriter bumpedKeyFileWriter = new FileWriter(bumpedKeyFile);
- bumpedKeyFileWriter.write(bumpedKey);
- bumpedKeyFileWriter.close();
-
- Integer userInnerID = Integer.parseInt(userID.replace("uid-", ""));
- User user = userService.findUserById(userInnerID).get();
-
- Path bumpedChangesPathFile = Paths.get(bumpedVersionStringDirectory, "changes.json");
- String bumpedChangesStringFile = bumpedChangesPathFile.toString();
- File bumpedChangesFile = new File(bumpedChangesStringFile);
- JSONObject bumpedChangesUser = new JSONObject();
- // Don't add the `uid-` prefix.
- // https://github.com/ONLYOFFICE/document-server-integration/issues/437#issuecomment-1663526562
- bumpedChangesUser.put("id", user.getId());
- bumpedChangesUser.put("name", user.getName());
- JSONObject bumpedChangesChangesItem = new JSONObject();
- bumpedChangesChangesItem.put("created", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
- bumpedChangesChangesItem.put("user", bumpedChangesUser);
- JSONArray bumpedChangesChanges = new JSONArray();
- bumpedChangesChanges.add(bumpedChangesChangesItem);
- JSONObject bumpedChanges = new JSONObject();
- bumpedChanges.put("serverVersion", null);
- bumpedChanges.put("changes", bumpedChangesChanges);
- String bumpedChangesContent = bumpedChanges.toJSONString();
- FileWriter bumpedChangesFileWriter = new FileWriter(bumpedChangesFile);
- bumpedChangesFileWriter.write(bumpedChangesContent);
- bumpedChangesFileWriter.close();
-
- String sourceExtension = fileUtility.getFileExtension(sourceBasename);
- String previousBasename = "prev" + sourceExtension;
-
- Path bumpedFile = Paths.get(bumpedVersionStringDirectory, previousBasename);
- Files.move(sourcePathFile, bumpedFile);
-
- String recoveryVersionStringDirectory = documentManager.versionDir(historyDirectory, version, true);
- Path recoveryPathFile = Paths.get(recoveryVersionStringDirectory, previousBasename);
- String recoveryStringFile = recoveryPathFile.toString();
- FileInputStream recoveryStream = new FileInputStream(recoveryStringFile);
- storageMutator.createFile(sourcePathFile, recoveryStream);
- recoveryStream.close();
-
- JSONObject responseBody = new JSONObject();
- responseBody.put("error", null);
- responseBody.put("success", true);
- return responseBody.toJSONString();
- } catch (Exception error) {
- error.printStackTrace();
- JSONObject responseBody = new JSONObject();
- responseBody.put("error", error.getMessage());
- responseBody.put("success", false);
- return responseBody.toJSONString();
- }
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/controllers/IndexController.java b/src/main/java/com/onlyoffice/integration/controllers/IndexController.java
deleted file mode 100644
index 1088ead..0000000
--- a/src/main/java/com/onlyoffice/integration/controllers/IndexController.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.controllers;
-
-import com.onlyoffice.integration.documentserver.storage.FileStorageMutator;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import com.onlyoffice.integration.documentserver.util.Misc;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import com.onlyoffice.integration.entities.User;
-import com.onlyoffice.integration.services.UserServices;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.CrossOrigin;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-@CrossOrigin("*")
-@Controller
-public class IndexController {
-
- @Autowired
- private FileStorageMutator storageMutator;
-
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
-
- @Autowired
- private FileUtility fileUtility;
-
- @Autowired
- private Misc mistUtility;
-
- @Autowired
- private UserServices userService;
-
- @Value("${files.docservice.url.site}")
- private String docserviceSite;
-
- @Value("${files.docservice.url.preloader}")
- private String docservicePreloader;
-
- @Value("${url.converter}")
- private String urlConverter;
-
- @Value("${url.editor}")
- private String urlEditor;
-
- @Value("${files.docservice.languages}")
- private String langs;
-
- @GetMapping("${url.index}")
- public String index(@RequestParam(value = "directUrl", required = false) final Boolean directUrl,
- final Model model) {
- java.io.File[] files = storageMutator.getStoredFiles(); // get all the stored files from the storage
- List docTypes = new ArrayList<>();
- List filesEditable = new ArrayList<>();
- List versions = new ArrayList<>();
- List isFillFormDoc = new ArrayList<>();
- List langsAndKeys = Arrays.asList(langs.split("\\|"));
-
- Map languages = new LinkedHashMap<>();
-
- langsAndKeys.forEach((str) -> {
- String[] couple = str.split(":");
- languages.put(couple[0], couple[1]);
- });
-
- List users = userService.findAll(); // get a list of all the users
-
- String tooltip = users.stream() // get the tooltip with the user descriptions
- .map(user -> mistUtility.convertUserDescriptions(user.getName(),
- user.getDescriptions())) // convert user descriptions to the specified format
- .collect(Collectors.joining());
-
- for (java.io.File file:files) { // run through all the files
- String fileName = file.getName(); // get file name
- docTypes.add(fileUtility
- .getDocumentType(fileName)
- .toString()
- .toLowerCase()); // add a document type of each file to the list
- filesEditable.add(fileUtility.getEditedExts()
- .contains(fileUtility.getFileExtension(fileName))); // specify if a file is editable or not
- versions.add(" [" + storagePathBuilder.
- getFileVersion(fileName, true) + "]"); // add a file version to the list
- isFillFormDoc.add(fileUtility.getFillExts().contains(fileUtility.getFileExtension(fileName)));
- }
-
- // add all the parameters to the model
- model.addAttribute("isFillFormDoc", isFillFormDoc);
- model.addAttribute("versions", versions);
- model.addAttribute("files", files);
- model.addAttribute("docTypes", docTypes);
- model.addAttribute("filesEditable", filesEditable);
- model.addAttribute("datadocs", docserviceSite + docservicePreloader);
- model.addAttribute("tooltip", tooltip);
- model.addAttribute("users", users);
- model.addAttribute("languages", languages);
- model.addAttribute("directUrl", directUrl);
-
- return "index.html";
- }
-
- @PostMapping("/config")
- @ResponseBody
- public HashMap configParameters() { // get configuration parameters
- HashMap configuration = new HashMap<>();
-
- configuration.put("FillExtList", String.join(",", fileUtility
- .getFillExts())); // put a list of the extensions that can be filled to config
- configuration.put("ConverExtList", String.join(",", fileUtility
- .getConvertExts())); // put a list of the extensions that can be converted to config
- configuration.put("EditedExtList", String.join(",", fileUtility
- .getEditedExts())); // put a list of the extensions that can be edited to config
- configuration.put("UrlConverter", urlConverter);
- configuration.put("UrlEditor", urlEditor);
-
- return configuration;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/Callback.java b/src/main/java/com/onlyoffice/integration/documentserver/callbacks/Callback.java
deleted file mode 100644
index 5e5743a..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/Callback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.callbacks;
-
-import com.onlyoffice.integration.dto.Track;
-import org.springframework.beans.factory.annotation.Autowired;
-
-// specify the callback handler functions
-public interface Callback {
- int handle(Track body, String fileName); // handle the callback
- int getStatus(); // get document status
- @Autowired
- default void selfRegistration(CallbackHandler callbackHandler) { // register a callback handler
- callbackHandler.register(getStatus(), this);
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/CallbackHandler.java b/src/main/java/com/onlyoffice/integration/documentserver/callbacks/CallbackHandler.java
deleted file mode 100644
index 3f643ce..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/CallbackHandler.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.callbacks;
-
-import com.onlyoffice.integration.dto.Track;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import java.util.HashMap;
-import java.util.Map;
-
-@Service
-public class CallbackHandler {
-
- private Logger logger = LoggerFactory.getLogger(CallbackHandler.class);
-
- private Map callbackHandlers = new HashMap<>();
-
- public void register(final int code, final Callback callback) { // register a callback handler
- callbackHandlers.put(code, callback);
- }
-
- public int handle(final Track body, final String fileName) { // handle a callback
- Callback callback = callbackHandlers.get(body.getStatus());
- if (callback == null) {
- logger.warn("Callback status " + body.getStatus() + " is not supported yet");
- return 0;
- }
-
- int result = callback.handle(body, fileName);
- return result;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/Status.java b/src/main/java/com/onlyoffice/integration/documentserver/callbacks/Status.java
deleted file mode 100644
index dfc27bb..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/Status.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.callbacks;
-
-// document status
-public enum Status {
- EDITING(1), // 1 - document is being edited
- SAVE(2), // 2 - document is ready for saving
- CORRUPTED(3), // 3 - document saving error has occurred
- MUST_FORCE_SAVE(6), // 6 - document is being edited, but the current document state is saved
- CORRUPTED_FORCE_SAVE(7); // 7 - error has occurred while force saving the document
- private int code;
- Status(final int codeParam) {
- this.code = codeParam;
- }
- public int getCode() { // get document status
- return this.code;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/implementations/EditCallback.java b/src/main/java/com/onlyoffice/integration/documentserver/callbacks/implementations/EditCallback.java
deleted file mode 100644
index 4f482c7..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/implementations/EditCallback.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.callbacks.implementations;
-
-import com.onlyoffice.integration.documentserver.callbacks.Callback;
-import com.onlyoffice.integration.documentserver.callbacks.Status;
-import com.onlyoffice.integration.documentserver.managers.callback.CallbackManager;
-import com.onlyoffice.integration.dto.Action;
-import com.onlyoffice.integration.dto.Track;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class EditCallback implements Callback {
- @Autowired
- private CallbackManager callbackManager;
- @Override
- public int handle(final Track body,
- final String fileName) { // handle the callback when the document is being edited
- int result = 0;
- Action action = body.getActions().get(0); // get the user ID who is editing the document
- if (action.getType().equals(com.onlyoffice.integration.documentserver.models.enums
- .Action.edit)) { // if this value is not equal to the user ID
- String user = action.getUserid(); // get user ID
- if (!body.getUsers().contains(user)) { // if this user is not specified in the body
- String key = body.getKey(); // get document key
- try {
- // create a command request to forcibly save the document being edited without closing it
- callbackManager.commandRequest("forcesave", key, null);
- } catch (Exception e) {
- e.printStackTrace();
- result = 1;
- }
- }
- }
- return result;
- }
-
- @Override
- public int getStatus() { // get document status
- return Status.EDITING.getCode(); // return status 1 - document is being edited
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/implementations/ForcesaveCallback.java b/src/main/java/com/onlyoffice/integration/documentserver/callbacks/implementations/ForcesaveCallback.java
deleted file mode 100644
index 0aa9c8e..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/implementations/ForcesaveCallback.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.callbacks.implementations;
-
-import com.onlyoffice.integration.documentserver.callbacks.Callback;
-import com.onlyoffice.integration.documentserver.callbacks.Status;
-import com.onlyoffice.integration.documentserver.managers.callback.CallbackManager;
-import com.onlyoffice.integration.dto.Track;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class ForcesaveCallback implements Callback {
- @Autowired
- private CallbackManager callbackManager;
- @Override
- public int handle(final Track body,
- final String fileName) { // handle the callback when the force saving request is performed
- int result = 0;
- try {
- callbackManager.processForceSave(body, fileName); // file force saving process
- } catch (Exception ex) {
- ex.printStackTrace();
- result = 1;
- }
- return result;
- }
-
- @Override
- public int getStatus() { // get document status
- // return status 6 - document is being edited, but the current document state is saved
- return Status.MUST_FORCE_SAVE.getCode();
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/implementations/SaveCallback.java b/src/main/java/com/onlyoffice/integration/documentserver/callbacks/implementations/SaveCallback.java
deleted file mode 100644
index d679761..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/callbacks/implementations/SaveCallback.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.callbacks.implementations;
-
-import com.onlyoffice.integration.documentserver.callbacks.Callback;
-import com.onlyoffice.integration.documentserver.callbacks.Status;
-import com.onlyoffice.integration.documentserver.managers.callback.CallbackManager;
-import com.onlyoffice.integration.dto.Track;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class SaveCallback implements Callback {
- @Autowired
- private CallbackManager callbackManager;
- @Override
- public int handle(final Track body,
- final String fileName) { // handle the callback when the saving request is performed
- int result = 0;
- try {
- callbackManager.processSave(body, fileName); // file saving process
- } catch (Exception ex) {
- ex.printStackTrace();
- result = 1;
- }
-
- return result;
- }
-
- @Override
- public int getStatus() { // get document status
- return Status.SAVE.getCode(); // return status 2 - document is ready for saving
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/callback/CallbackManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/callback/CallbackManager.java
deleted file mode 100644
index e0d3c5d..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/callback/CallbackManager.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.callback;
-
-import com.onlyoffice.integration.dto.Track;
-import java.util.HashMap;
-
-public interface CallbackManager { // specify the callback manager functions
- void processSave(Track body, String fileName); // file saving process
- void commandRequest(String method, String key, HashMap meta); // create a command request
- void processForceSave(Track body, String fileName); // file force saving process
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/callback/DefaultCallbackManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/callback/DefaultCallbackManager.java
deleted file mode 100644
index d1edc0b..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/callback/DefaultCallbackManager.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.callback;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.onlyoffice.integration.documentserver.managers.document.DocumentManager;
-import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
-import com.onlyoffice.integration.documentserver.storage.FileStorageMutator;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import com.onlyoffice.integration.dto.Action;
-import com.onlyoffice.integration.documentserver.util.service.ServiceConverter;
-import com.onlyoffice.integration.dto.Track;
-import lombok.SneakyThrows;
-import org.json.simple.JSONObject;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Primary;
-import org.springframework.http.HttpStatus;
-import org.springframework.stereotype.Component;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static com.onlyoffice.integration.documentserver.util.Constants.FILE_SAVE_TIMEOUT;
-
-// todo: Refactoring
-@Component
-@Primary
-public class DefaultCallbackManager implements CallbackManager {
-
- @Value("${files.docservice.url.site}")
- private String docserviceUrlSite;
- @Value("${files.docservice.url.command}")
- private String docserviceUrlCommand;
- @Value("${files.docservice.header}")
- private String documentJwtHeader;
-
- @Autowired
- private DocumentManager documentManager;
- @Autowired
- private JwtManager jwtManager;
- @Autowired
- private FileUtility fileUtility;
- @Autowired
- private FileStorageMutator storageMutator;
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
- @Autowired
- private ObjectMapper objectMapper;
- @Autowired
- private ServiceConverter serviceConverter;
-
- // download file from url
- @SneakyThrows
- private byte[] getDownloadFile(final String url) {
- if (url == null || url.isEmpty()) {
- throw new RuntimeException("Url argument is not specified"); // URL isn't specified
- }
-
- URL uri = new URL(url);
- java.net.HttpURLConnection connection = (java.net.HttpURLConnection) uri.openConnection();
- connection.setConnectTimeout(FILE_SAVE_TIMEOUT);
- InputStream stream = connection.getInputStream(); // get input stream of the file information from the URL
-
- int statusCode = connection.getResponseCode();
- if (statusCode != HttpStatus.OK.value()) { // checking status code
- connection.disconnect();
- throw new RuntimeException("Document editing service returned status: " + statusCode);
- }
-
- if (stream == null) {
- connection.disconnect();
- throw new RuntimeException("Input stream is null");
- }
-
- return stream.readAllBytes();
- }
-
- // file saving
- @SneakyThrows
- private void saveFile(final byte[] byteArray, final Path path) {
- if (path == null) {
- throw new RuntimeException("Path argument is not specified"); // file isn't specified
- }
- // update a file or create a new one
- storageMutator.createOrUpdateFile(path, new ByteArrayInputStream(byteArray));
- }
-
- @Override
- @SneakyThrows
- public void processSave(final Track body, final String fileName) { // file saving process
- String downloadUri = body.getUrl();
- String changesUri = body.getChangesurl();
- String key = body.getKey();
- String newFileName = fileName;
-
- String curExt = fileUtility.getFileExtension(fileName); // get current file extension
- String downloadExt = "." + body.getFiletype(); // get an extension of the downloaded file
-
- // todo: Refactoring
- // convert downloaded file to the file with the current extension if these extensions aren't equal
- if (!curExt.equals(downloadExt)) {
- try {
- String newFileUri = serviceConverter
- .getConvertedData(downloadUri, downloadExt, curExt,
- serviceConverter.generateRevisionId(downloadUri), null, false,
- null).getUri(); // convert a file and get URL to a new file
- if (newFileUri.isEmpty()) {
- newFileName = documentManager
- .getCorrectName(fileUtility.getFileNameWithoutExtension(fileName)
- + downloadExt); // get the correct file name if it already exists
- } else {
- downloadUri = newFileUri;
- }
- } catch (Exception e) {
- newFileName = documentManager
- .getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + downloadExt);
- }
- }
-
- byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
-
- String storagePath = storagePathBuilder.getFileLocation(newFileName); // get the path to a new file
- Path lastVersion = Paths.get(storagePathBuilder
- .getFileLocation(fileName)); // get the path to the last file version
-
- if (lastVersion.toFile().exists()) { // if the last file version exists
- Path histDir = Paths.get(storagePathBuilder.getHistoryDir(storagePath)); // get the history directory
- storageMutator.createDirectory(histDir); // and create it
-
- String versionDir = documentManager
- .versionDir(histDir.toAbsolutePath().toString(), // get the file version directory
- storagePathBuilder
- .getFileVersion(histDir.toAbsolutePath().toString(), false), true);
-
- Path ver = Paths.get(versionDir);
- Path toSave = Paths.get(storagePath);
-
- storageMutator.createDirectory(ver); // create the file version directory
-
- lastVersion.toFile().renameTo(new File(versionDir + File.separator + "prev" + curExt));
-
- saveFile(byteArrayFile, toSave); // save document file
-
- byte[] byteArrayChanges = getDownloadFile(changesUri); // download file changes
- saveFile(byteArrayChanges, Path
- .of(versionDir + File.separator + "diff.zip")); // save file changes to the diff.zip archive
-
- JSONObject jsonChanges = new JSONObject(); // create a json object for document changes
- jsonChanges.put("changes", body.getHistory().getChanges()); // put the changes to the json object
- jsonChanges.put("serverVersion", body.getHistory()
- .getServerVersion()); // put the server version to the json object
- String history = objectMapper.writeValueAsString(jsonChanges);
-
- if (history == null && body.getHistory() != null) {
- history = objectMapper.writeValueAsString(body.getHistory());
- }
-
- if (history != null && !history.isEmpty()) {
- // write the history changes to the changes.json file
- storageMutator.writeToFile(versionDir + File.separator + "changes.json", history);
- }
-
- // write the key value to the key.txt file
- storageMutator.writeToFile(versionDir + File.separator + "key.txt", key);
-
- // get the path to the forcesaved file version and remove it
- storageMutator.deleteFile(storagePathBuilder.getForcesavePath(newFileName, false));
- }
- }
-
- // todo: Replace (String method) with (Enum method)
- @SneakyThrows
- public void commandRequest(final String method,
- final String key,
- final HashMap meta) { // create a command request
- String documentCommandUrl = docserviceUrlSite + docserviceUrlCommand;
-
- URL url = new URL(documentCommandUrl);
- java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
-
- HashMap params = new HashMap();
- params.put("c", method);
- params.put("key", key);
-
- if (meta != null) {
- params.put("meta", meta);
- }
-
- String headerToken;
- // check if a secret key to generate token exists or not
- if (jwtManager.tokenEnabled() && jwtManager.tokenUseForRequest()) {
- Map payloadMap = new HashMap<>();
- payloadMap.put("payload", params);
- headerToken = jwtManager.createToken(payloadMap); // encode a payload object into a header token
-
- // add a header Authorization with a header token and Authorization prefix in it
- connection.setRequestProperty(documentJwtHeader.equals("")
- ? "Authorization" : documentJwtHeader, "Bearer " + headerToken);
-
- String token = jwtManager.createToken(params); // encode a payload object into a body token
- params.put("token", token);
- }
-
- String bodyString = objectMapper.writeValueAsString(params);
-
- byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);
-
- connection.setRequestMethod("POST"); // set the request method
- connection
- .setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // set the Content-Type header
- connection.setDoOutput(true); // set the doOutput field to true
- connection.connect();
-
- try (OutputStream os = connection.getOutputStream()) {
- os.write(bodyByte); // write bytes to the output stream
- }
-
- InputStream stream = connection.getInputStream(); // get input stream
-
- if (stream == null) {
- throw new RuntimeException("Could not get an answer");
- }
-
- String jsonString = serviceConverter.convertStreamToString(stream); // convert stream to json string
- connection.disconnect();
-
- JSONObject response = serviceConverter.convertStringToJSON(jsonString); // convert json string to json object
- // todo: Add errors ENUM
- String responseCode = response.get("error").toString();
- switch (responseCode) {
- case "0":
- case "4":
- break;
- default:
- throw new RuntimeException(response.toJSONString());
- }
- }
-
- @SneakyThrows
- public void processForceSave(final Track body, final String fileNameParam) { // file force saving process
-
- String downloadUri = body.getUrl();
- String fileName = fileNameParam;
-
- String curExt = fileUtility.getFileExtension(fileName); // get current file extension
- String downloadExt = "." + body.getFiletype(); // get an extension of the downloaded file
-
- Boolean newFileName = false;
-
- // convert downloaded file to the file with the current extension if these extensions aren't equal
- // todo: Extract function
- if (!curExt.equals(downloadExt)) {
- try {
- // convert file and get URL to a new file
- String newFileUri = serviceConverter
- .getConvertedData(downloadUri, downloadExt, curExt, serviceConverter
- .generateRevisionId(downloadUri), null, false, null).getUri();
- if (newFileUri.isEmpty()) {
- newFileName = true;
- } else {
- downloadUri = newFileUri;
- }
- } catch (Exception e) {
- newFileName = true;
- }
- }
-
- byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
- String forcesavePath = "";
-
- // todo: Use ENUMS
- // todo: Pointless toString conversion
- boolean isSubmitForm = body.getForcesavetype().toString().equals("3");
-
- // todo: Extract function
- if (isSubmitForm) { // if the form is submitted
- if (newFileName) {
- // get the correct file name if it already exists
- fileName = documentManager
- .getCorrectName(fileUtility
- .getFileNameWithoutExtension(fileName) + "-form" + downloadExt);
- } else {
- fileName = documentManager
- .getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + "-form" + curExt);
- }
- forcesavePath = storagePathBuilder.getFileLocation(fileName); // create forcesave path if it doesn't exist
- List actions = body.getActions();
- Action action = actions.get(0);
- String user = action.getUserid(); // get the user ID
- // create meta data for the forcesaved file
- storageMutator.createMeta(fileName, user, "Filling Form");
- } else {
- if (newFileName) {
- fileName = documentManager
- .getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + downloadExt);
- }
-
- forcesavePath = storagePathBuilder.getForcesavePath(fileName, false);
- if (forcesavePath.isEmpty()) {
- forcesavePath = storagePathBuilder.getForcesavePath(fileName, true);
- }
- }
-
- saveFile(byteArrayFile, Path.of(forcesavePath));
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/document/DefaultDocumentManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/document/DefaultDocumentManager.java
deleted file mode 100644
index 1baecb4..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/document/DefaultDocumentManager.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.document;
-
-import com.onlyoffice.integration.documentserver.storage.FileStorageMutator;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import com.onlyoffice.integration.documentserver.util.service.ServiceConverter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Component;
-
-import java.io.File;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.math.BigDecimal;
-import java.math.RoundingMode;
-import java.net.InetAddress;
-import java.net.URLEncoder;
-import java.net.UnknownHostException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import static com.onlyoffice.integration.documentserver.util.Constants.KILOBYTE_SIZE;
-
-@Component
-@Primary
-public class DefaultDocumentManager implements DocumentManager {
-
- @Value("${files.storage.folder}")
- private String storageFolder;
- @Value("${files.storage}")
- private String filesStorage;
- @Value("${url.track}")
- private String trackUrl;
- @Value("${url.download}")
- private String downloadUrl;
-
- @Autowired
- private FileStorageMutator storageMutator;
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
- @Autowired
- private FileUtility fileUtility;
- @Autowired
- private ServiceConverter serviceConverter;
-
- // get URL to the created file
- public String getCreateUrl(final String fileName, final Boolean sample) {
- String fileExt = fileUtility.getFileExtension(fileName).replace(".", "");
- String url = storagePathBuilder.getServerUrl(true)
- + "/create?fileExt=" + fileExt + "&sample=" + sample;
- return url;
- }
-
- // get a file name with an index if the file with such a name already exists
- public String getCorrectName(final String fileName) {
- String baseName = fileUtility.getFileNameWithoutExtension(fileName); // get file name without extension
- String ext = fileUtility.getFileExtension(fileName); // get file extension
- String name = baseName + ext; // create a full file name
-
- Path path = Paths.get(storagePathBuilder.getFileLocation(name));
-
- // run through all the files with such a name in the storage directory
- for (int i = 1; Files.exists(path); i++) {
- name = baseName + " (" + i + ")" + ext; // and add an index to the base name
- path = Paths.get(storagePathBuilder.getFileLocation(name));
- }
-
- return name;
- }
-
- // get file URL
- public String getFileUri(final String fileName, final Boolean forDocumentServer) {
- try {
- String serverPath = storagePathBuilder.getServerUrl(forDocumentServer); // get server URL
- String hostAddress = storagePathBuilder.getStorageLocation(); // get the storage directory
- String filePathDownload = !fileName.contains(InetAddress.getLocalHost().getHostAddress()) ? fileName
- : fileName.substring(fileName.indexOf(InetAddress.getLocalHost()
- .getHostAddress()) + InetAddress.getLocalHost().getHostAddress().length() + 1);
- if (!filesStorage.isEmpty() && filePathDownload.contains(filesStorage)) {
- filePathDownload = filePathDownload.substring(filesStorage.length() + 1);
- }
-
- String filePath = serverPath + "/download?fileName=" + URLEncoder
- .encode(filePathDownload, java.nio.charset.StandardCharsets.UTF_8.toString()) + "&userAddress"
- + URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString());
- return filePath;
- } catch (UnsupportedEncodingException | UnknownHostException e) {
- return "";
- }
- }
-
- // get file URL
- public String getHistoryFileUrl(final String fileName, final Integer version, final String file,
- final Boolean forDocumentServer) {
- try {
- String serverPath = storagePathBuilder.getServerUrl(forDocumentServer); // get server URL
- String hostAddress = storagePathBuilder.getStorageLocation(); // get the storage directory
- String filePathDownload = !fileName.contains(InetAddress.getLocalHost().getHostAddress()) ? fileName
- : fileName.substring(fileName.indexOf(InetAddress.getLocalHost().getHostAddress())
- + InetAddress.getLocalHost().getHostAddress().length() + 1);
- String userAddress = forDocumentServer ? "&userAddress" + URLEncoder
- .encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
- String filePath = serverPath + "/downloadhistory?fileName=" + URLEncoder
- .encode(filePathDownload, java.nio.charset.StandardCharsets.UTF_8.toString())
- + "&ver=" + version + "&file=" + file
- + userAddress;
- return filePath;
- } catch (UnsupportedEncodingException | UnknownHostException e) {
- return "";
- }
- }
-
- // get the callback URL
- public String getCallback(final String fileName) {
- String serverPath = storagePathBuilder.getServerUrl(true);
- String storageAddress = storagePathBuilder.getStorageLocation();
- try {
- String query = trackUrl + "?fileName="
- + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
- + "&userAddress=" + URLEncoder
- .encode(storageAddress, java.nio.charset.StandardCharsets.UTF_8.toString());
- return serverPath + query;
- } catch (UnsupportedEncodingException e) {
- return "";
- }
- }
-
- // get URL to download a file
- public String getDownloadUrl(final String fileName, final Boolean isServer) {
- String serverPath = storagePathBuilder.getServerUrl(isServer);
- String storageAddress = storagePathBuilder.getStorageLocation();
- try {
- String userAddress = isServer ? "&userAddress=" + URLEncoder
- .encode(storageAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
- String query = downloadUrl + "?fileName="
- + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
- + userAddress;
-
- return serverPath + query;
- } catch (UnsupportedEncodingException e) {
- return "";
- }
- }
-
- // get file information
- public ArrayList> getFilesInfo() {
- ArrayList> files = new ArrayList<>();
-
- // run through all the stored files
- for (File file : storageMutator.getStoredFiles()) {
- Map map = new LinkedHashMap<>(); // write all the parameters to the map
- map.put("version", storagePathBuilder.getFileVersion(file.getName(), false));
- map.put("id", serviceConverter
- .generateRevisionId(storagePathBuilder.getStorageLocation()
- + "/" + file.getName() + "/"
- + Paths.get(storagePathBuilder.getFileLocation(file.getName()))
- .toFile()
- .lastModified()));
- map.put("contentLength", new BigDecimal(String.valueOf((file.length() / Double.valueOf(KILOBYTE_SIZE))))
- .setScale(2, RoundingMode.HALF_UP) + " KB");
- map.put("pureContentLength", file.length());
- map.put("title", file.getName());
- map.put("updated", String.valueOf(new Date(file.lastModified())));
- files.add(map);
- }
-
- return files;
- }
-
- // get file information by its ID
- public ArrayList> getFilesInfo(final String fileId) {
- ArrayList> file = new ArrayList<>();
-
- for (Map map : getFilesInfo()) {
- if (map.get("id").equals(fileId)) {
- file.add(map);
- break;
- }
- }
-
- return file;
- }
-
- // get the path to the file version by the history path and file version
- public String versionDir(final String path, final Integer version, final boolean historyPath) {
- if (!historyPath) {
- return storagePathBuilder.getHistoryDir(storagePathBuilder.getFileLocation(path)) + version;
- }
- return path + File.separator + version;
- }
-
- // create demo document
- public String createDemo(final String fileExt, final Boolean sample, final String uid, final String uname) {
- String demoName = (sample ? "sample." : "new.")
- + fileExt; // create sample or new template file with the necessary extension
- String demoPath =
- "assets"
- + File.separator
- + "document-templates"
- + File.separator
- + (sample ? "sample" : "new")
- + File.separator
- + demoName;
-
- // get a file name with an index if the file with such a name already exists
- String fileName = getCorrectName(demoName);
-
- InputStream stream = Thread.currentThread()
- .getContextClassLoader()
- .getResourceAsStream(demoPath); // get the input file stream
-
- if (stream == null) {
- return null;
- }
-
- storageMutator.createFile(Path.of(storagePathBuilder
- .getFileLocation(fileName)), stream); // create a file in the specified directory
- storageMutator.createMeta(fileName, uid, uname); // create meta information of the demo file
-
- return fileName;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/document/DocumentManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/document/DocumentManager.java
deleted file mode 100644
index 6b8eb25..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/document/DocumentManager.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.document;
-
-import java.util.ArrayList;
-import java.util.Map;
-
-// specify the document manager functions
-public interface DocumentManager {
-
- // get a file name with an index if the file with such a name already exists
- String getCorrectName(String fileName);
- String getFileUri(String fileName, Boolean forDocumentServer); // get file URL
- String getHistoryFileUrl(String fileName, Integer version, String file, Boolean forDocumentServer); // get file URL
- String getCallback(String fileName); // get the callback URL
- String getDownloadUrl(String fileName, Boolean forDocumentServer); // get URL to download a file
- ArrayList> getFilesInfo(); // get file information
- ArrayList> getFilesInfo(String fileId); // get file information by its ID
-
- // get the path to the file version by the history path and file version
- String versionDir(String path, Integer version, boolean historyPath);
-
- // create demo document
- String createDemo(String fileExt, Boolean sample, String uid, String uname) throws Exception;
- String getCreateUrl(String fileName, Boolean sample); // get URL to the created file
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/history/DefaultHistoryManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/history/DefaultHistoryManager.java
deleted file mode 100644
index 2511246..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/history/DefaultHistoryManager.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.history;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.onlyoffice.integration.documentserver.managers.document.DocumentManager;
-import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
-import com.onlyoffice.integration.documentserver.models.filemodel.Document;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import lombok.SneakyThrows;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Scanner;
-
-// todo: Rebuild completely
-@Component
-public class DefaultHistoryManager implements HistoryManager {
-
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
-
- @Autowired
- private DocumentManager documentManager;
-
- @Autowired
- private JwtManager jwtManager;
-
- @Autowired
- private FileUtility fileUtility;
-
- @Autowired
- private JSONParser parser;
-
- @Autowired
- private ObjectMapper objectMapper;
-
- // todo: Refactoring
- @SneakyThrows
- public String[] getHistory(final Document document) { // get document history
-
- // get history directory
- String histDir = storagePathBuilder.getHistoryDir(storagePathBuilder.getFileLocation(document.getTitle()));
- Integer curVer = storagePathBuilder.getFileVersion(histDir, false); // get current file version
-
- if (curVer > 0) { // check if the current file version is greater than 0
- List hist = new ArrayList<>();
- Map histData = new HashMap<>();
-
- for (Integer i = 1; i <= curVer; i++) { // run through all the file versions
- Map obj = new HashMap();
- Map dataObj = new HashMap();
- String verDir = documentManager
- .versionDir(histDir, i, true); // get the path to the given file version
-
- String key = i == curVer ? document.getKey() : readFileToEnd(new File(verDir
- + File.separator + "key.txt")); // get document key
- obj.put("key", key);
- obj.put("version", i);
-
- if (i == 1) { // check if the version number is equal to 1
- String createdInfo = readFileToEnd(new File(histDir
- + File.separator + "createdInfo.json")); // get file with meta data
- JSONObject json = (JSONObject) parser.parse(createdInfo); // and turn it into json object
-
- // write meta information to the object (user information and creation date)
- obj.put("created", json.get("created"));
- Map user = new HashMap();
- user.put("id", json.get("id"));
- user.put("name", json.get("name"));
- obj.put("user", user);
- }
-
- dataObj.put("fileType", fileUtility
- .getFileExtension(document.getTitle()).replace(".", ""));
- dataObj.put("key", key);
- dataObj.put("url", i == curVer ? document.getUrl()
- : documentManager.getHistoryFileUrl(document.getTitle(), i, "prev" + fileUtility
- .getFileExtension(document.getTitle()), true));
- if (!document.getDirectUrl().equals("")) {
- dataObj.put("directUrl", i == curVer ? document.getDirectUrl()
- : documentManager.getHistoryFileUrl(document.getTitle(), i, "prev" + fileUtility
- .getFileExtension(document.getTitle()), false));
- }
- dataObj.put("version", i);
-
- if (i > 1) { //check if the version number is greater than 1
- // if so, get the path to the changes.json file
- JSONObject changes = (JSONObject) parser.parse(readFileToEnd(new File(documentManager
- .versionDir(histDir, i - 1, true) + File.separator + "changes.json")));
- JSONObject change = (JSONObject) ((JSONArray) changes.get("changes")).get(0);
-
- // write information about changes to the object
- obj.put("changes", changes.get("changes"));
- obj.put("serverVersion", changes.get("serverVersion"));
- obj.put("created", change.get("created"));
- obj.put("user", change.get("user"));
-
- // get the history data from the previous file version
- Map prev = (Map) histData.get(Integer.toString(i - 2));
- Map prevInfo = new HashMap();
- prevInfo.put("fileType", prev.get("fileType"));
- prevInfo.put("key", prev.get("key")); // write key and URL information about previous file version
- prevInfo.put("url", prev.get("url"));
- if (!document.getDirectUrl().equals("")) {
- prevInfo.put("directUrl", prev.get("directUrl"));
- }
-
- // write information about previous file version to the data object
- dataObj.put("previous", prevInfo);
- // write the path to the diff.zip archive with differences in this file version
- Integer verdiff = i - 1;
- dataObj.put("changesUrl", documentManager
- .getHistoryFileUrl(document.getTitle(), verdiff, "diff.zip", true));
- }
-
- if (jwtManager.tokenEnabled()) {
- dataObj.put("token", jwtManager.createToken(dataObj));
- }
-
- hist.add(obj);
- histData.put(Integer.toString(i - 1), dataObj);
- }
-
- // write history information about the current file version to the history object
- Map histObj = new HashMap();
- histObj.put("currentVersion", curVer);
- histObj.put("history", hist);
-
- try {
- return new String[]{objectMapper.writeValueAsString(histObj),
- objectMapper.writeValueAsString(histData)};
- } catch (JsonProcessingException e) {
- e.printStackTrace();
- }
- }
- return new String[]{"", ""};
- }
-
- // read a file
- private String readFileToEnd(final File file) {
- String output = "";
- try {
- try (FileInputStream is = new FileInputStream(file)) {
- Scanner scanner = new Scanner(is); // read data from the source
- scanner.useDelimiter("\\A");
- while (scanner.hasNext()) {
- output += scanner.next();
- }
- scanner.close();
- }
- } catch (Exception e) {
- }
- return output;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/history/HistoryManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/history/HistoryManager.java
deleted file mode 100644
index 2be05ff..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/history/HistoryManager.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.history;
-
-import com.onlyoffice.integration.documentserver.models.filemodel.Document;
-
-// specify the history manager functions
-public interface HistoryManager {
- String[] getHistory(Document document); // get document history
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/jwt/DefaultJwtManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/jwt/DefaultJwtManager.java
deleted file mode 100644
index a7161d7..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/jwt/DefaultJwtManager.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.jwt;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-import org.primeframework.jwt.Signer;
-import org.primeframework.jwt.Verifier;
-import org.primeframework.jwt.domain.JWT;
-import org.primeframework.jwt.hmac.HMACSigner;
-import org.primeframework.jwt.hmac.HMACVerifier;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Component;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-@Component
-public class DefaultJwtManager implements JwtManager {
- @Value("${files.docservice.secret}")
- private String tokenSecret;
- @Value("${files.docservice.token-use-for-request}")
- private String tokenUseForRequest;
- @Autowired
- private ObjectMapper objectMapper;
- @Autowired
- private JSONParser parser;
-
- // create document token
- @Override
- public String createToken(final Map payloadClaims) {
- try {
- // build a HMAC signer using a SHA-256 hash
- Signer signer = HMACSigner.newSHA256Signer(tokenSecret);
- JWT jwt = new JWT();
- for (String key : payloadClaims.keySet()) { // run through all the keys from the payload
- jwt.addClaim(key, payloadClaims.get(key)); // and write each claim to the jwt
- }
- return JWT.getEncoder().encode(jwt, signer); // sign and encode the JWT to a JSON string representation
- } catch (Exception e) {
- return "";
- }
- }
-
- // check if the token is enabled
- @Override
- public boolean tokenEnabled() {
- return tokenSecret != null && !tokenSecret.isEmpty();
- }
-
- @Override
- public boolean tokenUseForRequest() {
- return Boolean.parseBoolean(tokenUseForRequest) && !tokenUseForRequest.isEmpty();
- }
-
- // read document token
- @Override
- public JWT readToken(final String token) {
- try {
- // build a HMAC verifier using the token secret
- Verifier verifier = HMACVerifier.newVerifier(tokenSecret);
-
- // verify and decode the encoded string JWT to a rich object
- return JWT.getDecoder().decode(token, verifier);
- } catch (Exception exception) {
- return null;
- }
- }
-
- // parse the body
- @Override
- public JSONObject parseBody(final String payload, final String header) {
- JSONObject body;
- try {
- Object obj = parser.parse(payload); // get body parameters by parsing the payload
- body = (JSONObject) obj;
- } catch (Exception ex) {
- throw new RuntimeException("{\"error\":1,\"message\":\"JSON Parsing error\"}");
- }
- if (tokenEnabled() && tokenUseForRequest()) { // check if the token is enabled
- String token = (String) body.get("token"); // get token from the body
- if (token == null) { // if token is empty
- if (header != null && header.trim()!="") { // and the header is defined
-
- // get token from the header (it is placed after the Bearer prefix if it exists)
- token = header.startsWith("Bearer ") ? header.substring("Bearer ".length()) : header;
- }
- }
- if (token == null || token.trim()=="") {
- throw new RuntimeException("{\"error\":1,\"message\":\"JWT expected\"}");
- }
-
- JWT jwt = readToken(token); // read token
- if (jwt == null) {
- throw new RuntimeException("{\"error\":1,\"message\":\"JWT validation failed\"}");
- }
- if (jwt.getObject("payload") != null) { // get payload from the token and check if it is not empty
- try {
- @SuppressWarnings("unchecked") LinkedHashMap jwtPayload =
- (LinkedHashMap) jwt.getObject("payload");
-
- jwt.claims = jwtPayload;
- } catch (Exception ex) {
- throw new RuntimeException("{\"error\":1,\"message\":\"Wrong payload\"}");
- }
- }
- try {
- Object obj = parser.parse(objectMapper.writeValueAsString(jwt.claims));
- body = (JSONObject) obj;
- } catch (Exception ex) {
- throw new RuntimeException("{\"error\":1,\"message\":\"Parsing error\"}");
- }
- }
-
- return body;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/jwt/JwtManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/jwt/JwtManager.java
deleted file mode 100644
index 78b100d..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/jwt/JwtManager.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.jwt;
-
-import org.json.simple.JSONObject;
-import org.primeframework.jwt.domain.JWT;
-
-import java.util.Map;
-
-// specify the jwt manager functions
-public interface JwtManager {
- boolean tokenEnabled(); // check if the token is enabled
- boolean tokenUseForRequest(); // check if the token is enabled
- String createToken(Map payloadClaims); // create document token
- JWT readToken(String token); // read document token
- JSONObject parseBody(String payload, String header); // parse the body
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/template/SampleTemplateManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/template/SampleTemplateManager.java
deleted file mode 100644
index aaff9cb..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/template/SampleTemplateManager.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.template;
-
-import com.onlyoffice.integration.documentserver.models.enums.DocumentType;
-import com.onlyoffice.integration.documentserver.models.filemodel.Template;
-import com.onlyoffice.integration.documentserver.managers.document.DocumentManager;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.stereotype.Component;
-
-import java.util.List;
-
-@Component
-@Qualifier("sample")
-public class SampleTemplateManager implements TemplateManager {
- @Autowired
- private DocumentManager documentManager;
-
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
-
- @Autowired
- private FileUtility fileUtility;
-
- // create a template document with the specified name
- public List createTemplates(final String fileName) {
- List templates = List.of(
- new Template("", "Blank", documentManager
- .getCreateUrl(fileName, false)), // create a blank template
- new Template(getTemplateImageUrl(fileName), "With sample content", documentManager
- .getCreateUrl(fileName,
- true)) // create a template with sample content using the template image
- );
-
- return templates;
- }
-
- // get the template image URL for the specified file
- public String getTemplateImageUrl(final String fileName) {
- DocumentType fileType = fileUtility.getDocumentType(fileName); // get the file type
- String path = storagePathBuilder.getServerUrl(true); // get server URL
- if (fileType.equals(DocumentType.word)) { // get URL to the template image for the word document type
- return path + "/css/img/file_docx.svg";
- } else if (fileType.equals(DocumentType.slide)) { // get URL to the template image for the slide document type
- return path + "/css/img/file_pptx.svg";
- } else if (fileType.equals(DocumentType.cell)) { // get URL to the template image for the cell document type
- return path + "/css/img/file_xlsx.svg";
- }
- return path + "/css/img/file_docx.svg"; // get URL to the template image for the default document type (word)
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/managers/template/TemplateManager.java b/src/main/java/com/onlyoffice/integration/documentserver/managers/template/TemplateManager.java
deleted file mode 100644
index 322aa2e..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/managers/template/TemplateManager.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.managers.template;
-
-import com.onlyoffice.integration.documentserver.models.filemodel.Template;
-import java.util.List;
-
-// specify the template manager functions
-public interface TemplateManager {
- List createTemplates(String fileName); // create a template document with the specified name
- String getTemplateImageUrl(String fileName); // get the template image URL for the specified file
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/AbstractModel.java b/src/main/java/com/onlyoffice/integration/documentserver/models/AbstractModel.java
deleted file mode 100644
index fc5f91b..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/AbstractModel.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models;
-
-import java.io.Serializable;
-
-public abstract class AbstractModel implements Serializable {
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Customization.java b/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Customization.java
deleted file mode 100644
index 821b6df..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Customization.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.configurations;
-
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-@Component
-@Scope("prototype")
-@Getter
-@Setter
-/* The parameters which allow to customize the editor interface so that it looked like your
- other products (if there are any) and change the presence or absence of the additional buttons,
- links, change logos and editor owner details. */
-public class Customization {
- @Autowired
- private Logo logo; // the image file at the top left corner of the Editor header
- @Autowired
- private Goback goback; // the settings for the Open file location menu button and upper right corner button
- private Boolean autosave = true; // if the Autosave menu option is enabled or disabled
- private Boolean comments = true; // if the Comments menu button is displayed or hidden
- private Boolean compactHeader = false; /* if the additional action buttons are displayed
- in the upper part of the editor window header next to the logo (false) or in the toolbar (true) */
- private Boolean compactToolbar = false; // if the top toolbar type displayed is full (false) or compact (true)
- private Boolean compatibleFeatures = false; // the use of functionality only compatible with the OOXML format
- private Boolean forcesave = false; /* add the request for the forced file saving to the callback handler
- when saving the document within the document editing service */
- private Boolean help = true; // if the Help menu button is displayed or hidden
- private Boolean hideRightMenu = false; // if the right menu is displayed or hidden on first loading
- private Boolean hideRulers = false; // if the editor rulers are displayed or hidden
- private Boolean submitForm = false; // if the Submit form button is displayed or hidden
- private Boolean about = true;
- private Boolean feedback = true;
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Embedded.java b/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Embedded.java
deleted file mode 100644
index 33b3721..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Embedded.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.configurations;
-
-import com.onlyoffice.integration.documentserver.models.enums.ToolbarDocked;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-@Component
-@Scope("prototype")
-@Getter
-@Setter
-/* The parameters which allow to change the settings
- which define the behavior of the buttons in the embedded mode */
-public class Embedded {
- private String embedUrl; /* the absolute URL to the document serving as a source file for the document embedded
- into the web page */
- private String saveUrl; /* the absolute URL that will allow the document to be saved
- onto the user personal computer */
- private String shareUrl; // the absolute URL that will allow other users to share this document
- private ToolbarDocked toolbarDocked; // the place for the embedded viewer toolbar, can be either top or bottom
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Goback.java b/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Goback.java
deleted file mode 100644
index 4d85994..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Goback.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.configurations;
-
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import lombok.Getter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-
-@Component
-@Scope("prototype")
-public class Goback { // the settings for the Open file location menu button and upper right corner button
-
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
-
- @Value("${url.index}")
- private String indexMapping;
-
- @Getter
- private String url; /* the absolute URL to the website address which will be opened
- when clicking the Open file location menu button */
-
- @PostConstruct
- private void init() {
- this.url = storagePathBuilder.getServerUrl(false) + indexMapping;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Info.java b/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Info.java
deleted file mode 100644
index 53e891d..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Info.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.configurations;
-
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Locale;
-
-@Component
-@Scope("prototype")
-@Getter
-@Setter
-/* The additional parameters for the document (document owner, folder where the document is stored,
- uploading date, sharing settings) */
-public class Info {
- private String owner = "Me"; // the name of the document owner/creator
- private Boolean favorite = null; // the highlighting state of the Favorite icon
- private String uploaded = getDate(); // the document uploading date
-
- private String getDate() {
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
- return simpleDateFormat.format(new Date());
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Logo.java b/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Logo.java
deleted file mode 100644
index ba66376..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Logo.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.configurations;
-
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-@Component
-@Scope("prototype")
-@Getter
-@Setter
-public class Logo { // the image file at the top left corner of the Editor header
- @Value("${logo.image}")
- private String image; // the path to the image file used to show in common work mode
- @Value("${logo.imageEmbedded}")
- private String imageEmbedded; // the path to the image file used to show in the embedded mode
- @Value("${logo.url}")
- private String url; // the absolute URL which will be used when someone clicks the logo image
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/Action.java b/src/main/java/com/onlyoffice/integration/documentserver/models/enums/Action.java
deleted file mode 100644
index 4399a24..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/Action.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.enums;
-
-public enum Action {
- edit,
- review,
- view,
- embedded,
- filter,
- comment,
- chat,
- fillForms,
- blockcontent,
- protect
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/ConvertErrorType.java b/src/main/java/com/onlyoffice/integration/documentserver/models/enums/ConvertErrorType.java
deleted file mode 100644
index e070fd2..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/ConvertErrorType.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.enums;
-
-public enum ConvertErrorType {
- EMPTY_ERROR(0, ""),
- CONVERTATION_UNKNOWN(-1, "Error convertation unknown"),
- CONVERTATION_TIMEOUT(-2, "Error convertation timeout"),
- CONVERTATION_ERROR(-3, "Error convertation error"),
- DOWNLOAD_ERROR(-4, "Error download error"),
- UNEXPECTED_GUID_ERROR(-5, "Error unexpected guid"),
- DATABASE_ERROR(-6, "Error database"),
- DOCUMENT_REQUEST_ERROR(-7, "Error document request"),
- DOCUMENT_VKEY_ERROR(-8, "Error document VKey");
-
- private final int code;
- private final String label;
-
- ConvertErrorType(final int codeParam, final String labelParam) {
- this.code = codeParam;
- this.label = labelParam;
- }
-
- public static String labelOfCode(final int code) {
- for (ConvertErrorType convertErrorType : values()) {
- if (convertErrorType.code == code) {
- return convertErrorType.label;
- }
- }
- return "ErrorCode = " + code;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/DocumentType.java b/src/main/java/com/onlyoffice/integration/documentserver/models/enums/DocumentType.java
deleted file mode 100644
index 9b6e569..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/DocumentType.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.enums;
-
-public enum DocumentType {
- word,
- cell,
- slide
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/Mode.java b/src/main/java/com/onlyoffice/integration/documentserver/models/enums/Mode.java
deleted file mode 100644
index 1893b07..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/Mode.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.enums;
-
-public enum Mode {
- edit,
- view
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/ToolbarDocked.java b/src/main/java/com/onlyoffice/integration/documentserver/models/enums/ToolbarDocked.java
deleted file mode 100644
index 5b07598..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/ToolbarDocked.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.enums;
-
-public enum ToolbarDocked {
- top,
- bottom
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/Type.java b/src/main/java/com/onlyoffice/integration/documentserver/models/enums/Type.java
deleted file mode 100644
index 0036049..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/enums/Type.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.enums;
-
-public enum Type {
- desktop,
- mobile,
- embedded
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/CommentGroup.java b/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/CommentGroup.java
deleted file mode 100644
index 96848db..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/CommentGroup.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.filemodel;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.onlyoffice.integration.documentserver.serializers.SerializerFilter;
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-import org.springframework.stereotype.Component;
-
-import java.util.List;
-
-@Component
-@Data
-@NoArgsConstructor
-@AllArgsConstructor
-public class CommentGroup {
- @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = SerializerFilter.class)
- private List view; // define a list of groups whose comments the user can view
- @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = SerializerFilter.class)
- private List edit; // define a list of groups whose comments the user can edit
- @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = SerializerFilter.class)
- private List remove; // define a list of groups whose comments the user can remove
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/Document.java b/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/Document.java
deleted file mode 100644
index 56557cd..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/Document.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.filemodel;
-
-import com.onlyoffice.integration.documentserver.models.configurations.Info;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-import java.util.HashMap;
-
-@Component
-@Scope("prototype")
-@Getter
-@Setter
-public class Document { // the parameters pertaining to the document (title, url, file type, etc.)
- @Autowired
- private Info info; /* additional parameters for the document (document owner, folder where the document is stored,
- uploading date, sharing settings) */
- @Autowired
- private Permission permissions; // the permission for the document to be edited and downloaded or not
- private String fileType; // the file type for the source viewed or edited document
- private String key; // the unique document identifier used by the service to recognize the document
- private String urlUser; /* the absolute URL that will allow the document to be saved
- onto the user personal computer */
- private String title; /* the desired file name for the viewed or edited document which will also be used
- as file name when the document is downloaded */
- private String url; // the absolute URL where the source viewed or edited document is stored
- private String directUrl;
- private HashMap referenceData;
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/EditorConfig.java b/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/EditorConfig.java
deleted file mode 100644
index 2353de2..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/EditorConfig.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.filemodel;
-
-import com.onlyoffice.integration.documentserver.models.configurations.Customization;
-import com.onlyoffice.integration.documentserver.models.configurations.Embedded;
-import com.onlyoffice.integration.documentserver.models.enums.Mode;
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-import java.util.HashMap;
-import java.util.List;
-
-@Component
-@Scope("prototype")
-@Data
-@NoArgsConstructor
-@AllArgsConstructor
-public class EditorConfig { /* the parameters pertaining to the editor interface: opening mode (viewer or editor),
- interface language, additional buttons, etc. */
- private HashMap actionLink = null; /* the data which contains the information about the
- action in the document that will be scrolled to */
- private String callbackUrl; // the absolute URL to the document storage service
- private HashMap coEditing = null;
- private String createUrl; // the absolute URL of the document where it will be created and available after creation
- @Autowired
- private Customization customization; /* the parameters which allow to customize the editor interface
- so that it looked like your other products (if there are any) and change the presence or absence
- of the additional buttons, links, change logos and editor owner details */
- @Autowired
- private Embedded embedded; /* the parameters which allow to change the settings which define
- the behavior of the buttons in the embedded mode */
- private String lang; // the editor interface language
- private Mode mode; // the editor opening mode
- @Autowired
- private User user; // the user currently viewing or editing the document
- private List templates; /* the presence or absence
- of the templates in the Create New... menu option */
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/FileModel.java b/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/FileModel.java
deleted file mode 100644
index bbbf52d..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/FileModel.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.filemodel;
-
-import com.onlyoffice.integration.documentserver.models.enums.DocumentType;
-import com.onlyoffice.integration.documentserver.models.enums.Type;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-@Component
-@Scope("prototype")
-@Getter
-@Setter
-/* the file base parameters which include the platform type used,
- document display size (width and height) and type of the document opened */
-public class FileModel {
- @Autowired
- private Document document; // the parameters pertaining to the document (title, url, file type, etc.)
- private DocumentType documentType; // the document type to be opened
- @Autowired
- private EditorConfig editorConfig; /* the parameters pertaining to the
- editor interface: opening mode (viewer or editor), interface language, additional buttons, etc. */
- private String token; // the encrypted signature added to the Document Server config
- private Type type; // the platform type used to access the document
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/Permission.java b/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/Permission.java
deleted file mode 100644
index c6c1fd1..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/Permission.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.filemodel;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.onlyoffice.integration.documentserver.models.AbstractModel;
-import com.onlyoffice.integration.documentserver.serializers.SerializerFilter;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-import java.util.List;
-
-@Component
-@Scope("prototype")
-@Getter
-@Setter
-public class Permission extends AbstractModel { // the permission for the document to be edited and downloaded or not
- private Boolean comment = true; // if the document can be commented or not
- private Boolean copy = true; // if the content can be copied to the clipboard or not
- private Boolean download = true; // if the document can be downloaded or only viewed or edited online
- private Boolean edit = true; // if the document can be edited or only viewed
- private Boolean print = true; // if the document can be printed or not
- private Boolean fillForms = true; // if the forms can be filled
- private Boolean modifyFilter = true; /* if the filter can applied globally (true) affecting all the
- other users, or locally (false) */
- private Boolean modifyContentControl = true; // if the content control settings can be changed
- private Boolean review = true; // if the document can be reviewed or not
- private Boolean chat = true; // if a chat can be used
- @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = SerializerFilter.class)
- private List reviewGroups; // the groups whose changes the user can accept/reject
- @Autowired
- private CommentGroup commentGroups; // the groups whose comments the user can edit, remove and/or view
- @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = SerializerFilter.class)
- private List userInfoGroups;
- private Boolean protect = true;
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/ReferenceData.java b/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/ReferenceData.java
deleted file mode 100644
index 842be54..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/ReferenceData.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.filemodel;
-
-import java.util.HashMap;
-import java.util.Map;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import org.springframework.beans.factory.annotation.Autowired;
-
-public class ReferenceData {
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
- private final String instanceId;
- private final Map fileKey;
- public ReferenceData(final String fileName, final String curUserHostAddress, final User user) {
- instanceId = storagePathBuilder.getServerUrl(true);
- Map fileKeyList = new HashMap<>();
- if (!user.getId().equals("uid-0")) {
- fileKeyList.put("fileName", fileName);
- fileKeyList.put("userAddress", curUserHostAddress);
- } else {
- fileKeyList = null;
- }
- fileKey = fileKeyList;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/Template.java b/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/Template.java
deleted file mode 100644
index adbfe72..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/Template.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.filemodel;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.Setter;
-
-@Getter
-@Setter
-@AllArgsConstructor
-public class Template { // the document template parameters
- private String image; // the absolute URL to the image for template
- private String title; // the template title that will be displayed in the Create New... menu option
- private String url; // the absolute URL to the document where it will be created and available after creation
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/User.java b/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/User.java
deleted file mode 100644
index e7e9e6a..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/models/filemodel/User.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.models.filemodel;
-
-import com.onlyoffice.integration.documentserver.models.AbstractModel;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-@Component
-@Scope("prototype")
-@Getter
-@Setter
-public class User extends AbstractModel {
- private String id;
- private String name;
- private String group;
-
- // the user configuration parameters
- public void configure(final int idParam, final String nameParam, final String groupParam) {
- this.id = "uid-" + idParam; // the user id
- this.name = nameParam; // the user name
- this.group = groupParam; // the group the user belongs to
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/serializers/FilterState.java b/src/main/java/com/onlyoffice/integration/documentserver/serializers/FilterState.java
deleted file mode 100644
index dc1826e..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/serializers/FilterState.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.serializers;
-
-public enum FilterState {
- NULL
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/serializers/SerializerFilter.java b/src/main/java/com/onlyoffice/integration/documentserver/serializers/SerializerFilter.java
deleted file mode 100644
index 3f0918e..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/serializers/SerializerFilter.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.serializers;
-
-import java.util.List;
-
-public class SerializerFilter {
- @Override
- public boolean equals(final Object obj) {
- if (obj instanceof List) {
- if (((List>) obj).size() == 1 && ((List>) obj).get(0) == FilterState.NULL.toString()) {
- return true;
- }
- return false;
- }
- return false;
- }
- @Override
- public int hashCode() {
- return super.hashCode();
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/storage/FileStorageMutator.java b/src/main/java/com/onlyoffice/integration/documentserver/storage/FileStorageMutator.java
deleted file mode 100644
index efd10f4..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/storage/FileStorageMutator.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.storage;
-
-import org.springframework.core.io.Resource;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.nio.file.Path;
-
-// specify the file storage mutator functions
-public interface FileStorageMutator {
- void createDirectory(Path path); // create a new directory if it does not exist
- boolean createFile(Path path, InputStream stream); // create a new file if it does not exist
- boolean deleteFile(String fileName); // delete a file
- boolean deleteFileHistory(String fileName); // delete file history
- String updateFile(String fileName, byte[] bytes); // update a file
- boolean writeToFile(String pathName, String payload); // write the payload to the file
- boolean moveFile(Path source, Path destination); // move a file to the specified destination
- Resource loadFileAsResource(String fileName); // load file as a resource
- Resource loadFileAsResourceHistory(String fileName, String version, String file); // load file as a resource
- File[] getStoredFiles(); // get a collection of all the stored files
- void createMeta(String fileName, String uid, String uname); // create the file meta information
- boolean createOrUpdateFile(Path path, ByteArrayInputStream stream); // create or update a file
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/storage/FileStoragePathBuilder.java b/src/main/java/com/onlyoffice/integration/documentserver/storage/FileStoragePathBuilder.java
deleted file mode 100644
index 1c7f357..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/storage/FileStoragePathBuilder.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.storage;
-
-// specify the file storage path builder functions
-public interface FileStoragePathBuilder {
- void configure(String address); // create a new storage folder
- String getStorageLocation(); // get the storage directory
- String getFileLocation(String fileName); // get the directory of the specified file
- String getServerUrl(Boolean forDocumentServer); // get the server URL
- String getHistoryDir(String fileName); // get the history directory
- int getFileVersion(String historyPath, Boolean ifIndexPage); // get the file version
- String getForcesavePath(String fileName, Boolean create); /* get the path where all the
- forcely saved file versions are saved or create it */
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/storage/LocalFileStorage.java b/src/main/java/com/onlyoffice/integration/documentserver/storage/LocalFileStorage.java
deleted file mode 100644
index d9772c8..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/storage/LocalFileStorage.java
+++ /dev/null
@@ -1,392 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.storage;
-
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import lombok.Getter;
-import lombok.SneakyThrows;
-import org.json.simple.JSONObject;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Primary;
-import org.springframework.core.io.Resource;
-import org.springframework.core.io.UrlResource;
-import org.springframework.stereotype.Component;
-import org.springframework.util.FileSystemUtils;
-
-import javax.servlet.http.HttpServletRequest;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.URLDecoder;
-import java.net.UnknownHostException;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import static com.onlyoffice.integration.documentserver.util.Constants.KILOBYTE_SIZE;
-
-// todo: Refactoring
-@Component
-@Primary
-public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuilder {
-
- @Getter
- private String storageAddress;
-
- @Value("${files.storage.folder}")
- private String storageFolder;
-
- @Value("${files.docservice.url.example}")
- private String docserviceUrlExample;
-
- @Value("${files.docservice.history.postfix}")
- private String historyPostfix;
-
- @Autowired
- private FileUtility fileUtility;
-
- @Autowired
- private HttpServletRequest request;
-
- /*
- This Storage configuration method should be called whenever a new storage folder is required
- */
- public void configure(final String address) {
- this.storageAddress = address;
- if (this.storageAddress == null) {
- try {
- this.storageAddress = InetAddress.getLocalHost().getHostAddress();
- } catch (UnknownHostException e) {
- this.storageAddress = "unknown_storage";
- }
- }
- this.storageAddress.replaceAll("[^0-9a-zA-Z.=]", "_");
- createDirectory(Paths.get(getStorageLocation()));
- }
-
- // get the storage directory
- public String getStorageLocation() {
- String serverPath = System.getProperty("user.dir"); // get the path to the server
- String directory; // create the storage directory
- if (Paths.get(this.storageAddress).isAbsolute()) {
- directory = this.storageAddress + File.separator;
- } else {
- directory = serverPath
- + File.separator + storageFolder
- + File.separator + this.storageAddress
- + File.separator;
- }
- if (!Files.exists(Paths.get(directory))) {
- createDirectory(Paths.get(directory));
- }
-
- return directory;
- }
-
- // get the directory of the specified file
- public String getFileLocation(final String fileName) {
- if (fileName.contains(File.separator)) {
- return getStorageLocation() + fileName;
- }
- return getStorageLocation() + fileUtility.getFileName(fileName);
- }
-
- // create a new directory if it does not exist
- public void createDirectory(final Path path) {
- if (Files.exists(path)) {
- return;
- }
- try {
- Files.createDirectories(path);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- // create a new file if it does not exist
- public boolean createFile(final Path path, final InputStream stream) {
- if (Files.exists(path)) {
- return true;
- }
- try {
- File file = Files.createFile(path).toFile(); // create a new file in the specified path
- try (FileOutputStream out = new FileOutputStream(file)) {
- int read;
- final byte[] bytes = new byte[KILOBYTE_SIZE];
- while ((read = stream.read(bytes)) != -1) {
- out.write(bytes, 0, read); // write bytes to the output stream
- }
- out.flush(); // force write data to the output stream that can be cached in the current thread
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- }
-
- // delete a file
- public boolean deleteFile(final String fileNameParam) {
- String fileName = URLDecoder
- .decode(fileNameParam, StandardCharsets.UTF_8); // decode a x-www-form-urlencoded string
- if (fileName.isBlank()) {
- return false;
- }
-
- String filenameWithoutExt = fileUtility
- .getFileNameWithoutExtension(fileName); // get file name without extension
-
- Path filePath = fileName.contains(File.separator)
- ? Paths.get(fileName) : Paths.get(getFileLocation(fileName)); // get the path to the file
- Path filePathWithoutExt = fileName.contains(File.separator)
- ? Paths.get(filenameWithoutExt) : Paths
- .get(getStorageLocation() + filenameWithoutExt); // get the path to the file without extension
-
- // delete the specified file; for directories, recursively delete any nested directories or files as well
- boolean fileDeleted = FileSystemUtils.deleteRecursively(filePath.toFile());
- /* delete the specified file without extension; for directories,
- recursively delete any nested directories or files as well */
- boolean fileWithoutExtDeleted = FileSystemUtils.deleteRecursively(filePathWithoutExt.toFile());
-
- return fileDeleted && fileWithoutExtDeleted;
- }
-
- // delete file history
- public boolean deleteFileHistory(final String fileNameParam) {
- String fileName = URLDecoder
- .decode(fileNameParam, StandardCharsets.UTF_8); // decode a x-www-form-urlencoded string
- if (fileName.isBlank()) {
- return false;
- }
-
- Path fileHistoryPath = Paths
- .get(getStorageLocation() + getHistoryDir(fileName)); // get the path to the history file
- Path fileHistoryPathWithoutExt = Paths.get(getStorageLocation() + getHistoryDir(fileUtility
- .getFileNameWithoutExtension(fileName))); // get the path to the history file without extension
-
- /* delete the specified history file; for directories,
- recursively delete any nested directories or files as well */
- boolean historyDeleted = FileSystemUtils.deleteRecursively(fileHistoryPath.toFile());
-
- /* delete the specified history file without extension; for directories,
- recursively delete any nested directories or files as well */
- boolean historyWithoutExtDeleted = FileSystemUtils.deleteRecursively(fileHistoryPathWithoutExt.toFile());
-
- return historyDeleted || historyWithoutExtDeleted;
- }
-
- // update a file
- public String updateFile(final String fileName, final byte[] bytes) {
- Path path = fileUtility
- .generateFilepath(getStorageLocation(), fileName); // generate the path to the specified file
- try {
- Files.write(path, bytes); // write new information in the bytes format to the file
- return path.getFileName().toString();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "";
- }
-
- // move a file to the specified destination
- public boolean moveFile(final Path source, final Path destination) {
- try {
- Files.move(source, destination,
- new StandardCopyOption[]{StandardCopyOption.REPLACE_EXISTING});
- return true;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- }
-
- // write the payload to the file
- public boolean writeToFile(final String pathName, final String payload) {
- try (FileWriter fw = new FileWriter(pathName)) {
- fw.write(payload);
- return true;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- }
-
- // get the path where all the forcely saved file versions are saved or create it
- public String getForcesavePath(final String fileName, final Boolean create) {
- String directory = getStorageLocation();
-
- Path path = Paths.get(directory); // get the storage directory
- if (!Files.exists(path)) {
- return "";
- }
-
- directory = getFileLocation(fileName) + historyPostfix + File.separator;
-
- path = Paths.get(directory); // get the history file directory
- if (!create && !Files.exists(path)) {
- return "";
- }
-
- createDirectory(path); // create a new directory where all the forcely saved file versions will be saved
-
- directory = directory + fileName;
- path = Paths.get(directory);
- if (!create && !Files.exists(path)) {
- return "";
- }
-
- return directory;
- }
-
- // load file as a resource
- public Resource loadFileAsResource(final String fileName) {
- String fileLocation = getForcesavePath(fileName,
- false); // get the path where all the forcely saved file versions are saved
- if (fileLocation.isBlank()) { // if file location is empty
- fileLocation = getFileLocation(fileName); // get it by the file name
- }
- try {
- Path filePath = Paths.get(fileLocation); // get the path to the file location
- Resource resource = new UrlResource(filePath.toUri()); // convert the file path to URL
- if (resource.exists()) {
- return resource;
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- public Resource loadFileAsResourceHistory(final String fileName, final String version, final String file) {
-
- String fileLocation = getStorageLocation() + fileName + "-hist" + File.separator + version
- + File.separator + file; // get it by the file name
-
- try {
- Path filePath = Paths.get(fileLocation); // get the path to the file location
- Resource resource = new UrlResource(filePath.toUri()); // convert the file path to URL
- if (resource.exists()) {
- return resource;
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- // get a collection of all the stored files
- public File[] getStoredFiles() {
- File file = new File(getStorageLocation());
- return file.listFiles(pathname -> pathname.isFile());
- }
-
- @SneakyThrows
- public void createMeta(final String fileName,
- final String uid,
- final String uname) { // create the file meta information
- String histDir = getHistoryDir(getFileLocation(fileName)); // get the history directory
-
- Path path = Paths.get(histDir); // get the path to the history directory
- createDirectory(path); // create the history directory
-
- // create the json object with the file metadata
- JSONObject json = new JSONObject();
- json.put("created", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(new Date())); // put the file creation date to the json object
- json.put("id", uid); // put the user ID to the json object
- json.put("name", uname); // put the user name to the json object
-
- File meta = new File(histDir + File.separator
- + "createdInfo.json"); // create the createdInfo.json file with the file meta information
- try (FileWriter writer = new FileWriter(meta)) {
- json.writeJSONString(writer);
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
-
- // create or update a file
- public boolean createOrUpdateFile(final Path path, final ByteArrayInputStream stream) {
- if (!Files.exists(path)) { // if the specified file does not exist
- return createFile(path, stream); // create it in the specified directory
- } else {
- try {
- Files.write(path, stream
- .readAllBytes()); // otherwise, write new information in the bytes format to the file
- return true;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return false;
- }
-
- // get the server URL
- public String getServerUrl(final Boolean forDocumentServer) {
- if (forDocumentServer && !docserviceUrlExample.equals("")) {
- return docserviceUrlExample;
- } else {
- return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
- + request.getContextPath();
- }
- }
-
- // get the history directory
- public String getHistoryDir(final String path) {
- return path + historyPostfix;
- }
-
- // get the file version
- public int getFileVersion(final String historyPath, final Boolean ifIndexPage) {
- Path path;
- if (ifIndexPage) { // if the start page is opened
- path = Paths.get(getStorageLocation()
- + getHistoryDir(historyPath)); // get the storage directory and add the history directory to it
- } else {
- path = Paths.get(historyPath); // otherwise, get the path to the history directory
- if (!Files.exists(path)) {
- return 1; // if the history directory does not exist, then the file version is 1
- }
- }
-
- // run through all the files in the history directory
- try (Stream stream = Files.walk(path, 1)) {
- return stream
- .filter(file -> Files.isDirectory(file)) // take only directories from the history folder
- .map(Path::getFileName) // get file names
- .map(Path::toString) // and convert them into strings
- .collect(Collectors.toSet()).size(); /* convert stream into set
- and get its size which specifies the file version */
- } catch (IOException e) {
- e.printStackTrace();
- return 0;
- }
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/util/Constants.java b/src/main/java/com/onlyoffice/integration/documentserver/util/Constants.java
deleted file mode 100644
index 7f79df3..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/util/Constants.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.util;
-
-public final class Constants {
- public static final Integer MAX_FILE_SIZE = 5 * 1024 * 1024;
- public static final Integer CONVERT_TIMEOUT_MS = 120000;
- public static final String CONVERTATION_ERROR_MESSAGE_TEMPLATE = "Error occurred in the ConvertService: ";
- public static final Long FULL_LOADING_IN_PERCENT = 100L;
- public static final Integer FILE_SAVE_TIMEOUT = 5000;
- public static final Integer MAX_KEY_LENGTH = 20;
- public static final Integer ANONYMOUS_USER_ID = 4;
- public static final Integer KILOBYTE_SIZE = 1024;
-
- private Constants() { }
-}
-
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/util/Misc.java b/src/main/java/com/onlyoffice/integration/documentserver/util/Misc.java
deleted file mode 100644
index 662f7c9..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/util/Misc.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.util;
-
-import org.springframework.stereotype.Component;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-@Component
-public class Misc {
-
- // convert user descriptions to the specified format
- public String convertUserDescriptions(final String username, final List description) {
- String result = "" + username + " " + description.
- stream().map(text -> "" + text + " ")
- .collect(Collectors.joining()) + " ";
- return result;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/util/SSLUtils.java b/src/main/java/com/onlyoffice/integration/documentserver/util/SSLUtils.java
deleted file mode 100644
index 4f8e026..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/util/SSLUtils.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.util;
-
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-
-import org.springframework.stereotype.Component;
-/**
- * Disables and enables certificate and host-name checking in
- * HttpsURLConnection, the default JVM implementation of the HTTPS/TLS protocol.
- * Has no effect on implementations such as Apache Http Client, Ok Http.
-*/
-@Component
-public final class SSLUtils {
-
- private final HostnameVerifier jvmHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
-
- private final HostnameVerifier trivialHostnameVerifier = new HostnameVerifier() {
- public boolean verify(final String hostname, final SSLSession sslSession) {
- return true;
- }
- };
-
- private final TrustManager[] unquestioningTrustManager = new TrustManager[] {
- new X509TrustManager() {
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return null;
- }
-
- public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
- }
-
- public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
- }
- } };
-
- public void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
- HttpsURLConnection.setDefaultHostnameVerifier(trivialHostnameVerifier);
- // Install the all-trusting trust manager
- SSLContext sc = SSLContext.getInstance("SSL");
- sc.init(null, unquestioningTrustManager, null);
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
- }
-
- public void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
- HttpsURLConnection.setDefaultHostnameVerifier(jvmHostnameVerifier);
- // Return it to the initial state (discovered by reflection, now hardcoded)
- SSLContext sc = SSLContext.getInstance("SSL");
- sc.init(null, null, null);
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
- }
-
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/util/file/DefaultFileUtility.java b/src/main/java/com/onlyoffice/integration/documentserver/util/file/DefaultFileUtility.java
deleted file mode 100644
index 26c6a6f..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/util/file/DefaultFileUtility.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.util.file;
-
-import com.onlyoffice.integration.documentserver.models.enums.DocumentType;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Component;
-
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import static com.onlyoffice.integration.documentserver.util.Constants.MAX_FILE_SIZE;
-
-@Component
-@Qualifier("default")
-public class DefaultFileUtility implements FileUtility {
- @Value("${filesize-max}")
- private String filesizeMax;
-
- @Value("${files.docservice.viewed-docs}")
- private String docserviceViewedDocs;
-
- @Value("${files.docservice.edited-docs}")
- private String docserviceEditedDocs;
-
- @Value("${files.docservice.convert-docs}")
- private String docserviceConvertDocs;
-
- @Value("${files.docservice.fillforms-docs}")
- private String docserviceFillDocs;
-
- // document extensions
- private List extsDocument = Arrays.asList(
- ".doc", ".docx", ".docm",
- ".dot", ".dotx", ".dotm",
- ".odt", ".fodt", ".ott", ".rtf", ".txt",
- ".html", ".htm", ".mht", ".xml",
- ".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oform");
-
- // spreadsheet extensions
- private List extsSpreadsheet = Arrays.asList(
- ".xls", ".xlsx", ".xlsm", ".xlsb",
- ".xlt", ".xltx", ".xltm",
- ".ods", ".fods", ".ots", ".csv");
-
- // presentation extensions
- private List extsPresentation = Arrays.asList(
- ".pps", ".ppsx", ".ppsm",
- ".ppt", ".pptx", ".pptm",
- ".pot", ".potx", ".potm",
- ".odp", ".fodp", ".otp");
-
- // get the document type
- public DocumentType getDocumentType(final String fileName) {
- String ext = getFileExtension(fileName).toLowerCase(); // get file extension from its name
- // word type for document extensions
- if (extsDocument.contains(ext)) {
- return DocumentType.word;
- }
-
- // cell type for spreadsheet extensions
- if (extsSpreadsheet.contains(ext)) {
- return DocumentType.cell;
- }
-
- // slide type for presentation extensions
- if (extsPresentation.contains(ext)) {
- return DocumentType.slide;
- }
-
- // default file type is word
- return DocumentType.word;
- }
-
- // get file name from its URL
- public String getFileName(final String url) {
- if (url == null) {
- return "";
- }
-
- // get file name from the last part of URL
- String fileName = url.substring(url.lastIndexOf('/') + 1);
- fileName = fileName.split("\\?")[0];
- return fileName;
- }
-
- // get file name without extension
- public String getFileNameWithoutExtension(final String url) {
- String fileName = getFileName(url);
- if (fileName == null) {
- return null;
- }
- String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
- return fileNameWithoutExt;
- }
-
- // get file extension from URL
- public String getFileExtension(final String url) {
- String fileName = getFileName(url);
- if (fileName == null) {
- return null;
- }
- String fileExt = fileName.substring(fileName.lastIndexOf("."));
- return fileExt.toLowerCase();
- }
-
- // get an editor internal extension
- public String getInternalExtension(final DocumentType type) {
- // .docx for word file type
- if (type.equals(DocumentType.word)) {
- return ".docx";
- }
-
- // .xlsx for cell file type
- if (type.equals(DocumentType.cell)) {
- return ".xlsx";
- }
-
- // .pptx for slide file type
- if (type.equals(DocumentType.slide)) {
- return ".pptx";
- }
-
- // the default file type is .docx
- return ".docx";
- }
-
- public List getFillExts() {
- return Arrays.asList(docserviceFillDocs.split("\\|"));
- }
-
- // get file extensions that can be viewed
- public List getViewedExts() {
- return Arrays.asList(docserviceViewedDocs.split("\\|"));
- }
-
- // get file extensions that can be edited
- public List getEditedExts() {
- return Arrays.asList(docserviceEditedDocs.split("\\|"));
- }
-
- // get file extensions that can be converted
- public List getConvertExts() {
- return Arrays.asList(docserviceConvertDocs.split("\\|"));
- }
-
- // get all the supported file extensions
- public List getFileExts() {
- List res = new ArrayList<>();
-
- res.addAll(getViewedExts());
- res.addAll(getEditedExts());
- res.addAll(getConvertExts());
- res.addAll(getFillExts());
-
- return res;
- }
-
- // generate the file path from file directory and name
- public Path generateFilepath(final String directory, final String fullFileName) {
- String fileName = getFileNameWithoutExtension(fullFileName); // get file name without extension
- String fileExtension = getFileExtension(fullFileName); // get file extension
- Path path = Paths.get(directory + fullFileName); // get the path to the files with the specified name
-
- for (int i = 1; Files.exists(path); i++) { // run through all the files with the specified name
- // get a name of each file without extension and add an index to it
- fileName = getFileNameWithoutExtension(fullFileName) + "(" + i + ")";
-
- // create a new path for this file with the correct name and extension
- path = Paths.get(directory + fileName + fileExtension);
- }
-
- path = Paths.get(directory + fileName + fileExtension);
- return path;
- }
-
- // get maximum file size
- public long getMaxFileSize() {
- long size = Long.parseLong(filesizeMax);
- return size > 0 ? size : MAX_FILE_SIZE;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/util/file/FileUtility.java b/src/main/java/com/onlyoffice/integration/documentserver/util/file/FileUtility.java
deleted file mode 100644
index a4c6ead..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/util/file/FileUtility.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.util.file;
-
-import com.onlyoffice.integration.documentserver.models.enums.DocumentType;
-
-import java.nio.file.Path;
-import java.util.List;
-
-// specify the file utility functions
-public interface FileUtility {
- DocumentType getDocumentType(String fileName); // get the document type
- String getFileName(String url); // get file name from its URL
- String getFileNameWithoutExtension(String url); // get file name without extension
- String getFileExtension(String url); // get file extension from URL
- String getInternalExtension(DocumentType type); // get an editor internal extension
- List getFileExts(); // get all the supported file extensions
- List getFillExts(); // get file extensions that can be filled
- List getViewedExts(); // get file extensions that can be viewed
- List getEditedExts(); // get file extensions that can be edited
- List getConvertExts(); // get file extensions that can be converted
- Path generateFilepath(String directory, String fullFileName); /* generate the file path
- from file directory and name */
- long getMaxFileSize(); // get maximum file size
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/util/service/DefaultServiceConverter.java b/src/main/java/com/onlyoffice/integration/documentserver/util/service/DefaultServiceConverter.java
deleted file mode 100644
index 70cd176..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/util/service/DefaultServiceConverter.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.util.service;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
-import com.onlyoffice.integration.documentserver.models.enums.ConvertErrorType;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import com.onlyoffice.integration.dto.Convert;
-import com.onlyoffice.integration.dto.ConvertedData;
-import lombok.SneakyThrows;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.http.HttpStatus;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import static com.onlyoffice.integration.documentserver.util.Constants.CONVERTATION_ERROR_MESSAGE_TEMPLATE;
-import static com.onlyoffice.integration.documentserver.util.Constants.CONVERT_TIMEOUT_MS;
-import static com.onlyoffice.integration.documentserver.util.Constants.FULL_LOADING_IN_PERCENT;
-import static com.onlyoffice.integration.documentserver.util.Constants.MAX_KEY_LENGTH;
-
-// todo: Refactoring
-@Component
-public class DefaultServiceConverter implements ServiceConverter {
- @Value("${files.docservice.header}")
- private String documentJwtHeader;
- @Value("${files.docservice.url.site}")
- private String docServiceUrl;
- @Value("${files.docservice.url.converter}")
- private String docServiceUrlConverter;
- @Value("${files.docservice.timeout}")
- private String docserviceTimeout;
- private int convertTimeout;
-
- @Autowired
- private JwtManager jwtManager;
- @Autowired
- private FileUtility fileUtility;
- @Autowired
- private JSONParser parser;
- @Autowired
- private ObjectMapper objectMapper;
-
- @PostConstruct
- public void init() {
- int timeout = Integer.parseInt(docserviceTimeout); // parse the dcoument service timeout value
- convertTimeout = timeout > 0 ? timeout : CONVERT_TIMEOUT_MS;
- }
-
- @SneakyThrows
- private String postToServer(final Convert body, final String headerToken) { // send the POST request to the server
- String bodyString = objectMapper
- .writeValueAsString(body); // write the body request to the object mapper in the string format
- URL url = null;
- java.net.HttpURLConnection connection = null;
- InputStream response = null;
- String jsonString = null;
-
- byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8); // convert body string into bytes
- try {
- // set the request parameters
- url = new URL(docServiceUrl + docServiceUrlConverter);
- connection = (java.net.HttpURLConnection) url.openConnection();
- connection.setRequestMethod("POST");
- connection.setDoOutput(true);
- connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
- connection.setFixedLengthStreamingMode(bodyByte.length);
- connection.setRequestProperty("Accept", "application/json");
- connection.setConnectTimeout(convertTimeout);
-
- // check if the token is enabled
- if (jwtManager.tokenEnabled()) {
- // set the JWT header to the request
- connection.setRequestProperty(documentJwtHeader.isBlank()
- ? "Authorization" : documentJwtHeader, "Bearer " + headerToken);
- }
-
- connection.connect();
-
- try (OutputStream os = connection.getOutputStream()) {
- os.write(bodyByte); // write bytes to the output stream
- os.flush(); // force write data to the output stream that can be cached in the current thread
- }
-
- int statusCode = connection.getResponseCode();
- if (statusCode != HttpStatus.OK.value()) { // checking status code
- connection.disconnect();
- throw new RuntimeException("Convertation service returned status: " + statusCode);
- }
-
- response = connection.getInputStream(); // get the input stream
- jsonString = convertStreamToString(response); // convert the response stream into a string
- } finally {
- connection.disconnect();
- return jsonString;
- }
- }
-
- // get the URL to the converted file
- public ConvertedData getConvertedData(final String documentUri, final String fromExtension,
- final String toExtension, final String documentRevisionId,
- final String filePass, final Boolean isAsync, final String lang) {
- // check if the fromExtension parameter is defined; if not, get it from the document url
- String fromExt = fromExtension == null || fromExtension.isEmpty()
- ? fileUtility.getFileExtension(documentUri) : fromExtension;
-
- // check if the file name parameter is defined; if not, get random uuid for this file
- String title = fileUtility.getFileName(documentUri);
- title = title == null || title.isEmpty() ? UUID.randomUUID().toString() : title;
-
- String documentRevId = documentRevisionId == null || documentRevisionId.isEmpty()
- ? documentUri : documentRevisionId;
-
- documentRevId = generateRevisionId(documentRevId); // create document token
-
- // write all the necessary parameters to the body object
- Convert body = new Convert();
- body.setLang(lang);
- body.setUrl(documentUri);
- body.setOutputtype(toExtension.replace(".", ""));
- body.setFiletype(fromExt.replace(".", ""));
- body.setTitle(title);
- body.setKey(documentRevId);
- body.setFilePass(filePass);
- if (isAsync) {
- body.setAsync(true);
- }
-
- String headerToken = "";
- if (jwtManager.tokenEnabled() && jwtManager.tokenUseForRequest()) {
- HashMap map = new HashMap();
- map.put("region", lang);
- map.put("url", body.getUrl());
- map.put("outputtype", body.getOutputtype());
- map.put("filetype", body.getFiletype());
- map.put("title", body.getTitle());
- map.put("key", body.getKey());
- map.put("password", body.getFilePass());
- if (isAsync) {
- map.put("async", body.getAsync());
- }
-
- // add token to the body if it is enabled
- String token = jwtManager.createToken(map);
- body.setToken(token);
-
- Map payloadMap = new HashMap();
- payloadMap.put("payload", map); // create payload object
- headerToken = jwtManager.createToken(payloadMap); // create header token
- }
-
- String jsonString = postToServer(body, headerToken);
-
- return getResponseData(jsonString);
- }
-
- // generate document key
- public String generateRevisionId(final String expectedKey) {
- /* if the expected key length is greater than 20
- then he expected key is hashed and a fixed length value is stored in the string format */
- String formatKey = expectedKey.length() > MAX_KEY_LENGTH
- ? Integer.toString(expectedKey.hashCode()) : expectedKey;
- String key = formatKey.replace("[^0-9-.a-zA-Z_=]", "_");
-
- return key.substring(0, Math.min(key.length(), MAX_KEY_LENGTH)); // the resulting key length is 20 or less
- }
-
- // todo: Replace with a registry (callbacks package for reference)
- // create an error message for an error code
- private void processConvertServiceResponceError(final int errorCode) {
- String errorMessage = CONVERTATION_ERROR_MESSAGE_TEMPLATE + ConvertErrorType.labelOfCode(errorCode);
-
- throw new RuntimeException(errorMessage);
- }
-
- // get the response URL
- @SneakyThrows
- private ConvertedData getResponseData(final String jsonString) {
- JSONObject jsonObj = convertStringToJSON(jsonString);
-
- Object error = jsonObj.get("error");
- if (error != null) { // if an error occurs
- processConvertServiceResponceError(Math.toIntExact((long) error)); // then get an error message
- }
-
- // check if the conversion is completed and save the result to a variable
- Boolean isEndConvert = (Boolean) jsonObj.get("endConvert");
-
- Long resultPercent = 0L;
- String responseUri = null;
- String responseFileType = null;
- ConvertedData convertedData = new ConvertedData("", "");
-
- if (isEndConvert) { // if the conversion is completed
- resultPercent = FULL_LOADING_IN_PERCENT;
- responseUri = (String) jsonObj.get("fileUrl"); // get the file URL
- responseFileType = (String) jsonObj.get("fileType"); // get the file type
- convertedData.setUri(responseUri);
- convertedData.setFileType(responseFileType);
- } else { // if the conversion isn't completed
- resultPercent = (Long) jsonObj.get("percent");
-
- // get the percentage value of the conversion process
- resultPercent = resultPercent >= FULL_LOADING_IN_PERCENT ? FULL_LOADING_IN_PERCENT - 1 : resultPercent;
- }
-
- return convertedData;
- }
-
- // convert stream to string
- @SneakyThrows
- public String convertStreamToString(final InputStream stream) {
- InputStreamReader inputStreamReader = new InputStreamReader(stream); // create an object to get incoming stream
- StringBuilder stringBuilder = new StringBuilder(); // create a string builder object
-
- // create an object to read incoming streams
- BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
- String line = bufferedReader.readLine(); // get incoming streams by lines
-
- while (line != null) {
- stringBuilder.append(line); // concatenate strings using the string builder
- line = bufferedReader.readLine();
- }
-
- String result = stringBuilder.toString();
-
- return result;
- }
-
- // convert string to json
- @SneakyThrows
- public JSONObject convertStringToJSON(final String jsonString) {
- Object obj = parser.parse(jsonString); // parse json string
- JSONObject jsonObj = (JSONObject) obj; // and turn it into a json object
-
- return jsonObj;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/documentserver/util/service/ServiceConverter.java b/src/main/java/com/onlyoffice/integration/documentserver/util/service/ServiceConverter.java
deleted file mode 100644
index 5fcbe30..0000000
--- a/src/main/java/com/onlyoffice/integration/documentserver/util/service/ServiceConverter.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.documentserver.util.service;
-
-import com.onlyoffice.integration.dto.ConvertedData;
-import org.json.simple.JSONObject;
-import java.io.InputStream;
-
-
-// specify the converter service functions
-public interface ServiceConverter {
- ConvertedData getConvertedData(String documentUri, String fromExtension, // get the URL to the converted file
- String toExtension, String documentRevisionId,
- String filePass, Boolean isAsync, String lang);
- String generateRevisionId(String expectedKey); // generate document key
- String convertStreamToString(InputStream stream); // convert stream to string
- JSONObject convertStringToJSON(String jsonString); // convert string to json
-}
diff --git a/src/main/java/com/onlyoffice/integration/dto/Action.java b/src/main/java/com/onlyoffice/integration/dto/Action.java
deleted file mode 100644
index 864f40b..0000000
--- a/src/main/java/com/onlyoffice/integration/dto/Action.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.dto;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-@Getter
-@Setter
-@AllArgsConstructor
-@NoArgsConstructor
-public class Action {
- private String userid;
- private com.onlyoffice.integration.documentserver.models.enums.Action type;
-}
diff --git a/src/main/java/com/onlyoffice/integration/dto/ChangesHistory.java b/src/main/java/com/onlyoffice/integration/dto/ChangesHistory.java
deleted file mode 100644
index 4c82ef5..0000000
--- a/src/main/java/com/onlyoffice/integration/dto/ChangesHistory.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.dto;
-
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-
-@Data
-@AllArgsConstructor
-@NoArgsConstructor
-public class ChangesHistory {
- private String created;
- private ChangesUser user;
-}
diff --git a/src/main/java/com/onlyoffice/integration/dto/ChangesUser.java b/src/main/java/com/onlyoffice/integration/dto/ChangesUser.java
deleted file mode 100644
index 56deb70..0000000
--- a/src/main/java/com/onlyoffice/integration/dto/ChangesUser.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.dto;
-
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-
-@Data
-@AllArgsConstructor
-@NoArgsConstructor
-public class ChangesUser {
- private String id;
- private String name;
-}
diff --git a/src/main/java/com/onlyoffice/integration/dto/Convert.java b/src/main/java/com/onlyoffice/integration/dto/Convert.java
deleted file mode 100644
index 6fed7e4..0000000
--- a/src/main/java/com/onlyoffice/integration/dto/Convert.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.dto;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-@Getter
-@Setter
-@AllArgsConstructor
-@NoArgsConstructor
-public class Convert {
- private String url;
- private String outputtype;
- private String filetype;
- private String title;
- private String key;
- private String filePass;
- private Boolean async;
- private String token;
- private String lang;
-}
diff --git a/src/main/java/com/onlyoffice/integration/dto/ConvertedData.java b/src/main/java/com/onlyoffice/integration/dto/ConvertedData.java
deleted file mode 100644
index ea8b137..0000000
--- a/src/main/java/com/onlyoffice/integration/dto/ConvertedData.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.dto;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-@Getter
-@Setter
-@AllArgsConstructor
-@NoArgsConstructor
-public class ConvertedData {
- private String uri;
- private String fileType;
-}
diff --git a/src/main/java/com/onlyoffice/integration/dto/Converter.java b/src/main/java/com/onlyoffice/integration/dto/Converter.java
deleted file mode 100644
index edb67bc..0000000
--- a/src/main/java/com/onlyoffice/integration/dto/Converter.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.dto;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-@Getter
-@Setter
-@NoArgsConstructor
-public class Converter {
- @JsonProperty("filename")
- private String fileName;
- @JsonProperty("filePass")
- private String filePass;
- @JsonProperty("lang")
- private String lang;
-}
diff --git a/src/main/java/com/onlyoffice/integration/dto/History.java b/src/main/java/com/onlyoffice/integration/dto/History.java
deleted file mode 100644
index dabea9c..0000000
--- a/src/main/java/com/onlyoffice/integration/dto/History.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.dto;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.onlyoffice.integration.documentserver.models.filemodel.User;
-import lombok.AllArgsConstructor;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-
-import java.util.List;
-
-@Data
-@AllArgsConstructor
-@NoArgsConstructor
-public class History {
- @JsonProperty("serverVersion")
- private String serverVersion;
- private String key;
- private Integer version;
- private String created;
- private User user;
- private List changes;
-}
diff --git a/src/main/java/com/onlyoffice/integration/dto/Mentions.java b/src/main/java/com/onlyoffice/integration/dto/Mentions.java
deleted file mode 100644
index 162c83b..0000000
--- a/src/main/java/com/onlyoffice/integration/dto/Mentions.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.dto;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.Setter;
-
-@Getter
-@Setter
-@AllArgsConstructor
-public class Mentions {
- private String name;
- private String email;
-}
diff --git a/src/main/java/com/onlyoffice/integration/dto/Track.java b/src/main/java/com/onlyoffice/integration/dto/Track.java
deleted file mode 100644
index 23b7522..0000000
--- a/src/main/java/com/onlyoffice/integration/dto/Track.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.dto;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-import java.util.List;
-
-@Getter
-@Setter
-@AllArgsConstructor
-@NoArgsConstructor
-public class Track {
- private String filetype;
- private String url;
- private String key;
- private String changesurl;
- private History history;
- private String token;
- private Integer forcesavetype;
- private Integer status;
- private List users;
- private List actions;
- private String userdata;
- private String lastsave;
- private Boolean notmodified;
-}
diff --git a/src/main/java/com/onlyoffice/integration/entities/AbstractEntity.java b/src/main/java/com/onlyoffice/integration/entities/AbstractEntity.java
deleted file mode 100644
index 75a09dd..0000000
--- a/src/main/java/com/onlyoffice/integration/entities/AbstractEntity.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.entities;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.MappedSuperclass;
-import java.io.Serializable;
-
-@MappedSuperclass
-@NoArgsConstructor
-@AllArgsConstructor
-@Setter
-@Getter
-public abstract class AbstractEntity implements Serializable {
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private int id;
-}
diff --git a/src/main/java/com/onlyoffice/integration/entities/Group.java b/src/main/java/com/onlyoffice/integration/entities/Group.java
deleted file mode 100644
index b245510..0000000
--- a/src/main/java/com/onlyoffice/integration/entities/Group.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.entities;
-
-import lombok.Getter;
-import lombok.Setter;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
-import java.util.List;
-
-@Entity
-@Table(name = "`group`")
-@Getter
-@Setter
-public class Group extends AbstractEntity {
- @Column(unique = true)
- private String name;
- @OneToMany(mappedBy = "group")
- private List users;
-}
diff --git a/src/main/java/com/onlyoffice/integration/entities/Permission.java b/src/main/java/com/onlyoffice/integration/entities/Permission.java
deleted file mode 100644
index 96f3b30..0000000
--- a/src/main/java/com/onlyoffice/integration/entities/Permission.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.entities;
-
-import lombok.Getter;
-import lombok.Setter;
-
-import javax.persistence.Entity;
-import javax.persistence.ManyToMany;
-import javax.persistence.Table;
-import java.util.List;
-
-@Entity
-@Table(name = "`permission`")
-@Getter
-@Setter
-public class Permission extends AbstractEntity {
- private Boolean comment = true;
- private Boolean copy = true;
- private Boolean download = true;
- private Boolean edit = true;
- private Boolean print = true;
- private Boolean fillForms = true;
- private Boolean modifyFilter = true;
- private Boolean modifyContentControl = true;
- private Boolean review = true;
- private Boolean chat = true;
- private Boolean templates = true;
- @ManyToMany
- private List reviewGroups;
- @ManyToMany
- private List commentsViewGroups;
- @ManyToMany
- private List commentsEditGroups;
- @ManyToMany
- private List commentsRemoveGroups;
- @ManyToMany
- private List userInfoGroups;
- private Boolean protect = true;
-}
diff --git a/src/main/java/com/onlyoffice/integration/entities/User.java b/src/main/java/com/onlyoffice/integration/entities/User.java
deleted file mode 100644
index 94e6b11..0000000
--- a/src/main/java/com/onlyoffice/integration/entities/User.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.entities;
-
-import lombok.Getter;
-import lombok.Setter;
-
-import javax.persistence.CollectionTable;
-import javax.persistence.ElementCollection;
-import javax.persistence.Entity;
-import javax.persistence.ManyToOne;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
-import java.util.List;
-
-@Entity
-@Table(name = "`user`")
-@Getter
-@Setter
-public class User extends AbstractEntity {
- private String name;
- private String email;
- private Boolean favorite;
- @ManyToOne
- private Group group;
- @OneToOne
- private Permission permissions;
-// @Column(columnDefinition = "CLOB")
- @ElementCollection
- @CollectionTable(name = "user_descriptions")
- private List descriptions;
-}
diff --git a/src/main/java/com/onlyoffice/integration/mappers/AbstractMapper.java b/src/main/java/com/onlyoffice/integration/mappers/AbstractMapper.java
deleted file mode 100644
index 98fdb76..0000000
--- a/src/main/java/com/onlyoffice/integration/mappers/AbstractMapper.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.mappers;
-
-import com.onlyoffice.integration.entities.AbstractEntity;
-import com.onlyoffice.integration.documentserver.models.AbstractModel;
-import org.modelmapper.Converter;
-import org.modelmapper.ModelMapper;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.Objects;
-
-public abstract class AbstractMapper implements Mapper {
- @Autowired
- private ModelMapper mapper;
-
- private Class modelClass;
-
- AbstractMapper(final Class modelClassParam) {
- this.modelClass = modelClassParam;
- }
-
- @Override
- public M toModel(final E entity) { // convert the entity to the model
- return Objects.isNull(entity) // check if an entity is not empty
- ? null
- : mapper.map(entity, modelClass); // and add it to the model mapper
- }
-
- Converter modelConverter() { // specify the model converter
- return context -> {
- E source = context.getSource(); // get the source entity
- M destination = context.getDestination(); // get the destination model
- handleSpecificFields(source, destination); // map the entity to the model
- return context.getDestination();
- };
- }
-
-
- void handleSpecificFields(final E source, final M destination) {
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/mappers/Mapper.java b/src/main/java/com/onlyoffice/integration/mappers/Mapper.java
deleted file mode 100644
index a620172..0000000
--- a/src/main/java/com/onlyoffice/integration/mappers/Mapper.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.mappers;
-
-import com.onlyoffice.integration.entities.AbstractEntity;
-import com.onlyoffice.integration.documentserver.models.AbstractModel;
-
-// specify the model mapper functions
-public interface Mapper {
- M toModel(E entity); // convert the entity to the model
-}
diff --git a/src/main/java/com/onlyoffice/integration/mappers/PermissionsMapper.java b/src/main/java/com/onlyoffice/integration/mappers/PermissionsMapper.java
deleted file mode 100644
index 710defd..0000000
--- a/src/main/java/com/onlyoffice/integration/mappers/PermissionsMapper.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.mappers;
-
-import com.onlyoffice.integration.entities.Permission;
-import com.onlyoffice.integration.documentserver.models.filemodel.CommentGroup;
-import org.modelmapper.ModelMapper;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-import java.util.stream.Collectors;
-
-@Component
-@Primary
-public class PermissionsMapper extends AbstractMapper {
- @Autowired
- private ModelMapper mapper;
-
- public PermissionsMapper() {
- super(com.onlyoffice.integration.documentserver.models.filemodel.Permission.class);
- }
-
- @PostConstruct
- public void configure() { // configure the permission mapper
- mapper.createTypeMap(Permission.class, com.onlyoffice.integration.documentserver.models.filemodel
- .Permission.class) // create the type map
- .setPostConverter(modelConverter()); // and apply the post converter to it
- }
-
- @Override
- void handleSpecificFields(final Permission source,
- final com.onlyoffice.integration.documentserver.models.filemodel
- .Permission destination) { // handle specific permission fields
- destination.setReviewGroups(source.getReviewGroups().stream()
- .map(g -> g.getName())
- .collect(Collectors.toList())); // set the reviewGroups parameter
-
- // set the commentGroups parameter
- destination.setCommentGroups(
- new CommentGroup(
- source.getCommentsViewGroups().stream().map(g -> g.getName()).collect(Collectors.toList()),
- source.getCommentsEditGroups().stream().map(g -> g.getName()).collect(Collectors.toList()),
- source.getCommentsRemoveGroups().stream().map(g -> g.getName()).collect(Collectors.toList())
- )
- );
- destination.setUserInfoGroups(source.getUserInfoGroups().stream()
- .map(g -> g.getName())
- .collect(Collectors.toList()));
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/mappers/UsersMapper.java b/src/main/java/com/onlyoffice/integration/mappers/UsersMapper.java
deleted file mode 100644
index c60e941..0000000
--- a/src/main/java/com/onlyoffice/integration/mappers/UsersMapper.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.mappers;
-
-import com.onlyoffice.integration.entities.User;
-import org.modelmapper.ModelMapper;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-
-@Component
-@Primary
-public class UsersMapper extends AbstractMapper {
- @Autowired
- private ModelMapper mapper;
-
- public UsersMapper() {
- super(com.onlyoffice.integration.documentserver.models.filemodel.User.class);
- }
-
- @PostConstruct
- public void configure() { // configure the users mapper
- mapper.createTypeMap(User.class, com.onlyoffice.integration.documentserver.models.filemodel
- .User.class) // create the type map
- .setPostConverter(modelConverter()); // and apply the post converter to it
- }
-
- @Override
- public void handleSpecificFields(final User source,
- final com.onlyoffice.integration.documentserver.models.filemodel
- .User destination) { // handle specific users fields
- destination.setGroup(source.getGroup() != null
- ? source.getGroup().getName() : null); // set the Group parameter
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/repositories/GroupRepository.java b/src/main/java/com/onlyoffice/integration/repositories/GroupRepository.java
deleted file mode 100644
index 7fd4786..0000000
--- a/src/main/java/com/onlyoffice/integration/repositories/GroupRepository.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.repositories;
-
-import com.onlyoffice.integration.entities.Group;
-import org.springframework.data.jpa.repository.JpaRepository;
-
-import java.util.Optional;
-
-public interface GroupRepository extends JpaRepository {
- Optional findGroupByName(String name);
-}
diff --git a/src/main/java/com/onlyoffice/integration/repositories/PermissionRepository.java b/src/main/java/com/onlyoffice/integration/repositories/PermissionRepository.java
deleted file mode 100644
index dc5c0be..0000000
--- a/src/main/java/com/onlyoffice/integration/repositories/PermissionRepository.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.repositories;
-
-import com.onlyoffice.integration.entities.Permission;
-import org.springframework.data.jpa.repository.JpaRepository;
-
-public interface PermissionRepository extends JpaRepository {
-}
diff --git a/src/main/java/com/onlyoffice/integration/repositories/UserRepository.java b/src/main/java/com/onlyoffice/integration/repositories/UserRepository.java
deleted file mode 100644
index 9ae6e6d..0000000
--- a/src/main/java/com/onlyoffice/integration/repositories/UserRepository.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.repositories;
-
-import com.onlyoffice.integration.entities.User;
-import org.springframework.data.jpa.repository.JpaRepository;
-
-public interface UserRepository extends JpaRepository {
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/GroupServices.java b/src/main/java/com/onlyoffice/integration/services/GroupServices.java
deleted file mode 100644
index 996254d..0000000
--- a/src/main/java/com/onlyoffice/integration/services/GroupServices.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services;
-
-import com.onlyoffice.integration.entities.Group;
-import com.onlyoffice.integration.repositories.GroupRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-@Service
-public class GroupServices {
-
- @Autowired
- private GroupRepository groupRepository;
-
- // create a new group with the specified name
- public Group createGroup(final String name) {
- if (name == null) {
- return null; // check if a name is specified
- }
- Optional group = groupRepository
- .findGroupByName(name); // check if group with such a name already exists
- if (group.isPresent()) {
- return group.get(); // if it exists, return it
- }
- Group newGroup = new Group();
- newGroup.setName(name); // otherwise, create a new group with the specified name
-
- groupRepository.save(newGroup); // save a new group
-
- return newGroup;
- }
-
- // create a list of groups from the reviewGroups permission parameter
- public List createGroups(final List reviewGroups) {
- if (reviewGroups == null) {
- return null; // check if the reviewGroups permission exists
- }
- // convert this parameter to a list of groups whose changes the user can accept/reject
- return reviewGroups.stream()
- .map(group -> createGroup(group))
- .collect(Collectors.toList());
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/PermissionServices.java b/src/main/java/com/onlyoffice/integration/services/PermissionServices.java
deleted file mode 100644
index e630986..0000000
--- a/src/main/java/com/onlyoffice/integration/services/PermissionServices.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services;
-
-import com.onlyoffice.integration.entities.Group;
-import com.onlyoffice.integration.entities.Permission;
-import com.onlyoffice.integration.repositories.PermissionRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public class PermissionServices {
-
- @Autowired
- private PermissionRepository permissionRepository;
-
- // create permissions with the specified parameters
- public Permission createPermission(final List reviewGroups,
- final List commentViewGroups,
- final List commentEditGroups,
- final List commentRemoveGroups,
- final List userInfoGroups,
- final Boolean chat,
- final Boolean protect) {
-
- Permission permission = new Permission();
- permission.setReviewGroups(reviewGroups); // define the groups whose changes the user can accept/reject
- permission.setCommentsViewGroups(commentViewGroups); // defines the groups whose comments the user can view
- permission.setCommentsEditGroups(commentEditGroups); // defines the groups whose comments the user can edit
- permission.setCommentsRemoveGroups(commentRemoveGroups); /* defines the groups
- whose comments the user can remove */
- permission.setUserInfoGroups(userInfoGroups);
- permission.setChat(chat);
- permission.setProtect(protect);
-
- permissionRepository.save(permission); // save new permissions
-
- return permission;
- }
-
- // update permissions
- public Permission updatePermission(final Permission newPermission) {
- permissionRepository.save(newPermission); // save new permissions
-
- return newPermission;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/UserServices.java b/src/main/java/com/onlyoffice/integration/services/UserServices.java
deleted file mode 100644
index 53d0d5f..0000000
--- a/src/main/java/com/onlyoffice/integration/services/UserServices.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services;
-
-import com.onlyoffice.integration.entities.Group;
-import com.onlyoffice.integration.entities.Permission;
-import com.onlyoffice.integration.entities.User;
-import com.onlyoffice.integration.repositories.UserRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-import java.util.Optional;
-
-@Service
-public class UserServices {
- @Autowired
- private UserRepository userRepository;
-
- @Autowired
- private GroupServices groupServices;
-
- @Autowired
- private PermissionServices permissionService;
-
- // get a list of all users
- public List findAll() {
- return userRepository.findAll();
- }
-
- // get a user by their ID
- public Optional findUserById(final Integer id) {
- return userRepository.findById(id);
- }
-
- // create a user with the specified parameters
- public User createUser(final String name, final String email,
- final List description, final String group,
- final List reviewGroups,
- final List viewGroups,
- final List editGroups,
- final List removeGroups,
- final List userInfoGroups, final Boolean favoriteDoc,
- final Boolean chat,
- final Boolean protect) {
- User newUser = new User();
- newUser.setName(name); // set the user name
- newUser.setEmail(email); // set the user email
- newUser.setGroup(groupServices.createGroup(group)); // set the user group
- newUser.setDescriptions(description); // set the user description
- newUser.setFavorite(favoriteDoc); // specify if the user has the favorite documents or not
-
- List groupsReview = groupServices
- .createGroups(reviewGroups); // define the groups whose changes the user can accept/reject
- List commentGroupsView = groupServices
- .createGroups(viewGroups); // defines the groups whose comments the user can view
- List commentGroupsEdit = groupServices
- .createGroups(editGroups); // defines the groups whose comments the user can edit
- List commentGroupsRemove = groupServices
- .createGroups(removeGroups); // defines the groups whose comments the user can remove
- List usInfoGroups = groupServices.createGroups(userInfoGroups);
-
- Permission permission = permissionService
- .createPermission(groupsReview,
- commentGroupsView,
- commentGroupsEdit,
- commentGroupsRemove,
- usInfoGroups,
- chat,
- protect); // specify permissions for the current user
- newUser.setPermissions(permission);
-
- userRepository.save(newUser); // save a new user
-
- return newUser;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/Configurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/Configurer.java
deleted file mode 100644
index 41128b4..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/Configurer.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers;
-
-public interface Configurer {
- void configure(O instance, W wrapper);
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/CustomizationConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/CustomizationConfigurer.java
deleted file mode 100644
index 5b2d7de..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/CustomizationConfigurer.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers;
-
-import com.onlyoffice.integration.documentserver.models.configurations.Customization;
-
-public interface CustomizationConfigurer extends Configurer {
- void configure(Customization customization, W wrapper);
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/DocumentConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/DocumentConfigurer.java
deleted file mode 100644
index 42f7396..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/DocumentConfigurer.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers;
-
-import com.onlyoffice.integration.documentserver.models.filemodel.Document;
-
-public interface DocumentConfigurer extends Configurer {
- void configure(Document document, W wrapper);
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/EditorConfigConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/EditorConfigConfigurer.java
deleted file mode 100644
index 85c0bfb..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/EditorConfigConfigurer.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers;
-
-import com.onlyoffice.integration.documentserver.models.filemodel.EditorConfig;
-
-public interface EditorConfigConfigurer extends Configurer {
- void configure(EditorConfig editorConfig, W wrapper);
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/EmbeddedConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/EmbeddedConfigurer.java
deleted file mode 100644
index c81b023..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/EmbeddedConfigurer.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers;
-
-import com.onlyoffice.integration.documentserver.models.configurations.Embedded;
-
-public interface EmbeddedConfigurer extends Configurer {
- void configure(Embedded embedded, W wrapper);
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/FileConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/FileConfigurer.java
deleted file mode 100644
index 4aafab5..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/FileConfigurer.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers;
-
-import com.onlyoffice.integration.documentserver.models.filemodel.FileModel;
-
-public interface FileConfigurer extends Configurer {
- void configure(FileModel model, W wrapper);
- FileModel getFileModel(W wrapper);
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultCustomizationConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultCustomizationConfigurer.java
deleted file mode 100644
index 5af0568..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultCustomizationConfigurer.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers.implementations;
-
-import com.onlyoffice.integration.documentserver.models.enums.Action;
-import com.onlyoffice.integration.documentserver.models.configurations.Customization;
-import com.onlyoffice.integration.entities.User;
-import com.onlyoffice.integration.services.configurers.CustomizationConfigurer;
-import com.onlyoffice.integration.services.configurers.wrappers.DefaultCustomizationWrapper;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Service;
-
-@Service
-@Primary
-public class DefaultCustomizationConfigurer implements CustomizationConfigurer {
- @Override
- // define the customization configurer
- public void configure(final Customization customization, final DefaultCustomizationWrapper wrapper) {
- Action action = wrapper.getAction(); // get the action parameter from the customization wrapper
- User user = wrapper.getUser();
- customization.setSubmitForm(false); // set the submitForm parameter to the customization config
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultDocumentConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultDocumentConfigurer.java
deleted file mode 100644
index 1d616b9..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultDocumentConfigurer.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers.implementations;
-
-import com.google.gson.Gson;
-import com.onlyoffice.integration.documentserver.models.filemodel.Document;
-import com.onlyoffice.integration.documentserver.models.filemodel.Permission;
-import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
-import com.onlyoffice.integration.services.configurers.DocumentConfigurer;
-import com.onlyoffice.integration.services.configurers.wrappers.DefaultDocumentWrapper;
-import com.onlyoffice.integration.documentserver.managers.document.DocumentManager;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import com.onlyoffice.integration.documentserver.util.service.ServiceConverter;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Service;
-
-import java.io.File;
-import java.net.InetAddress;
-import java.util.HashMap;
-
-@Service
-@Primary
-public class DefaultDocumentConfigurer implements DocumentConfigurer {
-
- @Autowired
- private DocumentManager documentManager;
-
- @Autowired
- private FileStoragePathBuilder storagePathBuilder;
-
- @Autowired
- private FileUtility fileUtility;
-
- @Autowired
- private ServiceConverter serviceConverter;
-
- public void configure(final Document document,
- final DefaultDocumentWrapper wrapper) { // define the document configurer
- String fileName = wrapper.getFileName(); // get the fileName parameter from the document wrapper
- Permission permission = wrapper.getPermission(); // get the permission parameter from the document wrapper
-
- document.setTitle(fileName); // set the title to the document config
-
- // set the URL to download a file to the document config
- document.setUrl(documentManager.getDownloadUrl(fileName, true));
- document.setUrlUser(documentManager
- .getFileUri(fileName, false)); // set the file URL to the document config
- document.setDirectUrl(wrapper.getIsEnableDirectUrl() ? documentManager
- .getDownloadUrl(fileName, false) : "");
- document.setFileType(fileUtility.getFileExtension(fileName)
- .replace(".", "")); // set the file type to the document config
- document.getInfo().setFavorite(wrapper.getFavorite()); // set the favorite parameter to the document config
-
- // get the document key
- String key = serviceConverter
- .generateRevisionId(storagePathBuilder.getStorageLocation()
- + "/" + fileName + "/"
- + new File(storagePathBuilder.getFileLocation(fileName)).lastModified());
-
- Gson gson = new Gson();
- HashMap fileKey = new HashMap<>();
- fileKey.put("fileName", fileName);
- try {
- fileKey.put("userAddress", InetAddress.getLocalHost().getHostAddress());
- } catch (Exception e) {
- e.printStackTrace();
- }
- HashMap referenceData = new HashMap<>();
- referenceData.put("instanceId", storagePathBuilder.getServerUrl(true));
- referenceData.put("fileKey", gson.toJson(fileKey));
-
- document.setKey(key); // set the key to the document config
- document.setPermissions(permission); // set the permission parameters to the document config
- document.setReferenceData(referenceData);
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultEditorConfigConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultEditorConfigConfigurer.java
deleted file mode 100644
index 29d5d0e..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultEditorConfigConfigurer.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers.implementations;
-
-import com.fasterxml.jackson.databind.JavaType;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.gson.reflect.TypeToken;
-import com.onlyoffice.integration.documentserver.models.enums.Action;
-import com.onlyoffice.integration.documentserver.managers.template.TemplateManager;
-import com.onlyoffice.integration.entities.User;
-import com.onlyoffice.integration.mappers.Mapper;
-import com.onlyoffice.integration.documentserver.models.enums.Mode;
-import com.onlyoffice.integration.documentserver.models.filemodel.EditorConfig;
-import com.onlyoffice.integration.services.configurers.EditorConfigConfigurer;
-import com.onlyoffice.integration.services.configurers.wrappers.DefaultCustomizationWrapper;
-import com.onlyoffice.integration.services.configurers.wrappers.DefaultEmbeddedWrapper;
-import com.onlyoffice.integration.services.configurers.wrappers.DefaultFileWrapper;
-import com.onlyoffice.integration.documentserver.managers.document.DocumentManager;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import lombok.SneakyThrows;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Service;
-
-import java.util.HashMap;
-
-@Service
-@Primary
-public class DefaultEditorConfigConfigurer implements EditorConfigConfigurer {
-
- @Autowired
- private Mapper mapper;
-
- @Autowired
- private ObjectMapper objectMapper;
-
- @Autowired
- private DocumentManager documentManager;
-
- @Autowired
- @Qualifier("sample")
- private TemplateManager templateManager;
-
- @Autowired
- private DefaultCustomizationConfigurer defaultCustomizationConfigurer;
-
- @Autowired
- private DefaultEmbeddedConfigurer defaultEmbeddedConfigurer;
-
- @Autowired
- private FileUtility fileUtility;
-
- @SneakyThrows
- public void configure(final EditorConfig config,
- final DefaultFileWrapper wrapper) { // define the editorConfig configurer
- if (wrapper.getActionData() != null) { // check if the actionData is not empty in the editorConfig wrapper
-
- // set actionLink to the editorConfig
- config.setActionLink(objectMapper.readValue(wrapper.getActionData(),
- (JavaType) new TypeToken>() { }.getType()));
- }
- String fileName = wrapper.getFileName(); // set the fileName parameter from the editorConfig wrapper
- String fileExt = fileUtility.getFileExtension(fileName);
- boolean userIsAnon = wrapper.getUser()
- .getName().equals("Anonymous"); // check if the user from the editorConfig wrapper is anonymous or not
-
- // set a template to the editorConfig if the user is not anonymous
- config.setTemplates(userIsAnon ? null : templateManager.createTemplates(fileName));
- config.setCallbackUrl(documentManager.getCallback(fileName)); // set the callback URL to the editorConfig
-
- // set the document URL where it will be created to the editorConfig if the user is not anonymous
- config.setCreateUrl(userIsAnon ? null : documentManager.getCreateUrl(fileName, false));
- config.setLang(wrapper.getLang()); // set the language to the editorConfig
- Boolean canEdit = wrapper.getCanEdit(); // check if the file of the specified type can be edited or not
- Action action = wrapper.getAction(); // get the action parameter from the editorConfig wrapper
- config.setCoEditing(action.equals(Action.view) && userIsAnon ? new HashMap() {{
- put("mode", "strict");
- put("change", false);
- }} : null);
-
- defaultCustomizationConfigurer.configure(config.getCustomization(),
- DefaultCustomizationWrapper.builder() // define the customization configurer
- .action(action)
- .user(userIsAnon ? null : wrapper.getUser())
- .build());
- config.setMode(canEdit && !action.equals(Action.view) ? Mode.edit : Mode.view);
- config.setUser(mapper.toModel(wrapper.getUser()));
- defaultEmbeddedConfigurer.configure(config.getEmbedded(), DefaultEmbeddedWrapper.builder()
- .type(wrapper.getType())
- .fileName(fileName)
- .build());
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultEmbeddedConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultEmbeddedConfigurer.java
deleted file mode 100644
index a4deeb3..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultEmbeddedConfigurer.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers.implementations;
-
-import com.onlyoffice.integration.documentserver.models.configurations.Embedded;
-import com.onlyoffice.integration.documentserver.models.enums.ToolbarDocked;
-import com.onlyoffice.integration.documentserver.models.enums.Type;
-import com.onlyoffice.integration.services.configurers.EmbeddedConfigurer;
-import com.onlyoffice.integration.services.configurers.wrappers.DefaultEmbeddedWrapper;
-import com.onlyoffice.integration.documentserver.managers.document.DocumentManager;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Service;
-
-@Service
-@Primary
-public class DefaultEmbeddedConfigurer implements EmbeddedConfigurer {
-
- @Autowired
- private DocumentManager documentManager;
-
- public void configure(final Embedded embedded,
- final DefaultEmbeddedWrapper wrapper) { // define the embedded configurer
- if (wrapper.getType().equals(Type.embedded)) { // check if the type from the embedded wrapper is embedded
- String url = documentManager.getDownloadUrl(wrapper
- .getFileName(), false); // get file URL of the specified file
-
- /* set the embedURL parameter to the embedded config (the absolute URL to the document serving
- as a source file for the document embedded into the web page) */
- embedded.setEmbedUrl(url);
-
- /* set the saveURL parameter to the embedded config (the absolute URL that will allow
- the document to be saved onto the user personal computer) */
- embedded.setSaveUrl(url);
-
- /* set the shareURL parameter to the embedded config (the absolute URL
- that will allow other users to share this document) */
- embedded.setShareUrl(url);
-
- /* set the top toolbarDocked parameter to the embedded config (the place for the
- embedded viewer toolbar, can be either top or bottom) */
- embedded.setToolbarDocked(ToolbarDocked.top);
- }
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultFileConfigurer.java b/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultFileConfigurer.java
deleted file mode 100644
index 7f72833..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/implementations/DefaultFileConfigurer.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers.implementations;
-
-import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
-import com.onlyoffice.integration.documentserver.models.enums.Action;
-import com.onlyoffice.integration.documentserver.models.enums.DocumentType;
-import com.onlyoffice.integration.documentserver.models.filemodel.FileModel;
-import com.onlyoffice.integration.documentserver.models.filemodel.Permission;
-import com.onlyoffice.integration.documentserver.util.file.FileUtility;
-import com.onlyoffice.integration.mappers.Mapper;
-import com.onlyoffice.integration.services.configurers.FileConfigurer;
-import com.onlyoffice.integration.services.configurers.wrappers.DefaultDocumentWrapper;
-import com.onlyoffice.integration.services.configurers.wrappers.DefaultFileWrapper;
-import org.springframework.beans.factory.ObjectFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Primary;
-import org.springframework.stereotype.Service;
-
-import java.util.HashMap;
-import java.util.Map;
-
-@Service
-@Primary
-public class DefaultFileConfigurer implements FileConfigurer {
- @Autowired
- private ObjectFactory fileModelObjectFactory;
-
- @Autowired
- private FileUtility fileUtility;
-
- @Autowired
- private JwtManager jwtManager;
-
- @Autowired
- private Mapper mapper;
-
- @Autowired
- private DefaultDocumentConfigurer defaultDocumentConfigurer;
-
- @Autowired
- private DefaultEditorConfigConfigurer defaultEditorConfigConfigurer;
-
- public void configure(final FileModel fileModel, final DefaultFileWrapper wrapper) { // define the file configurer
- if (fileModel != null) { // check if the file model is specified
- String fileName = wrapper.getFileName(); // get the fileName parameter from the file wrapper
- Action action = wrapper.getAction(); // get the action parameter from the file wrapper
-
- DocumentType documentType = fileUtility
- .getDocumentType(fileName); // get the document type of the specified file
- fileModel.setDocumentType(documentType); // set the document type to the file model
- fileModel.setType(wrapper.getType()); // set the platform type to the file model
-
- Permission userPermissions = mapper.toModel(wrapper.getUser()
- .getPermissions()); // convert the permission entity to the model
-
- String fileExt = fileUtility.getFileExtension(wrapper.getFileName());
- Boolean canEdit = fileUtility.getEditedExts().contains(fileExt);
- if ((!canEdit && action.equals(Action.edit) || action.equals(Action.fillForms)) && fileUtility
- .getFillExts().contains(fileExt)) {
- canEdit = true;
- wrapper.setAction(Action.fillForms);
- }
- wrapper.setCanEdit(canEdit);
-
- DefaultDocumentWrapper documentWrapper = DefaultDocumentWrapper // define the document wrapper
- .builder()
- .fileName(fileName)
- .permission(updatePermissions(userPermissions, action, canEdit))
- .favorite(wrapper.getUser().getFavorite())
- .isEnableDirectUrl(wrapper.getIsEnableDirectUrl())
- .build();
-
- defaultDocumentConfigurer
- .configure(fileModel.getDocument(), documentWrapper); // define the document configurer
- defaultEditorConfigConfigurer
- .configure(fileModel.getEditorConfig(), wrapper); // define the editorConfig configurer
-
- Map map = new HashMap<>();
- map.put("type", fileModel.getType());
- map.put("documentType", documentType);
- map.put("document", fileModel.getDocument());
- map.put("editorConfig", fileModel.getEditorConfig());
-
- fileModel.setToken(jwtManager.createToken(map)); // create a token and set it to the file model
- }
- }
-
- @Override
- public FileModel getFileModel(final DefaultFileWrapper wrapper) { // get file model
- FileModel fileModel = fileModelObjectFactory.getObject();
- configure(fileModel, wrapper); // and configure it
- return fileModel;
- }
-
- private Permission updatePermissions(final Permission userPermissions, final Action action, final Boolean canEdit) {
- userPermissions.setComment(
- !action.equals(Action.view)
- && !action.equals(Action.fillForms)
- && !action.equals(Action.embedded)
- && !action.equals(Action.blockcontent)
- );
-
- userPermissions.setFillForms(
- !action.equals(Action.view)
- && !action.equals(Action.comment)
- && !action.equals(Action.embedded)
- && !action.equals(Action.blockcontent)
- );
-
- userPermissions.setReview(canEdit
- && (action.equals(Action.review) || action.equals(Action.edit)));
-
- userPermissions.setEdit(canEdit
- && (action.equals(Action.view)
- || action.equals(Action.edit)
- || action.equals(Action.filter)
- || action.equals(Action.blockcontent)));
-
- return userPermissions;
- }
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultCustomizationWrapper.java b/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultCustomizationWrapper.java
deleted file mode 100644
index 404fc1b..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultCustomizationWrapper.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers.wrappers;
-
-import com.onlyoffice.integration.documentserver.models.enums.Action;
-import com.onlyoffice.integration.entities.User;
-import lombok.Builder;
-import lombok.Getter;
-
-@Getter
-@Builder
-public class DefaultCustomizationWrapper {
- private Action action;
- private User user;
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultDocumentWrapper.java b/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultDocumentWrapper.java
deleted file mode 100644
index 1940a43..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultDocumentWrapper.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers.wrappers;
-
-import com.onlyoffice.integration.documentserver.models.filemodel.Permission;
-import com.onlyoffice.integration.documentserver.models.filemodel.ReferenceData;
-import lombok.Builder;
-import lombok.Getter;
-
-@Getter
-@Builder
-public class DefaultDocumentWrapper {
- private Permission permission;
- private String fileName;
- private Boolean favorite;
- private Boolean isEnableDirectUrl;
- private ReferenceData referenceData;
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultEmbeddedWrapper.java b/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultEmbeddedWrapper.java
deleted file mode 100644
index 47029c7..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultEmbeddedWrapper.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers.wrappers;
-
-import com.onlyoffice.integration.documentserver.models.enums.Type;
-import lombok.Builder;
-import lombok.Getter;
-
-@Getter
-@Builder
-public class DefaultEmbeddedWrapper {
- private Type type;
- private String fileName;
-}
diff --git a/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultFileWrapper.java b/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultFileWrapper.java
deleted file mode 100644
index 3351f72..0000000
--- a/src/main/java/com/onlyoffice/integration/services/configurers/wrappers/DefaultFileWrapper.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- *
- * (c) Copyright Ascensio System SIA 2023
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.onlyoffice.integration.services.configurers.wrappers;
-
-import com.onlyoffice.integration.documentserver.models.enums.Action;
-import com.onlyoffice.integration.entities.User;
-import com.onlyoffice.integration.documentserver.models.enums.Type;
-import lombok.Builder;
-import lombok.Getter;
-import lombok.Setter;
-
-@Getter
-@Builder
-@Setter
-public class DefaultFileWrapper {
- private String fileName;
- private Type type;
- private User user;
- private String lang;
- private Action action;
- private String actionData;
- private Boolean canEdit;
- private Boolean isEnableDirectUrl;
-}
diff --git a/src/main/java/com/oo/OnlyofficeDemoApplication.java b/src/main/java/com/oo/OnlyofficeDemoApplication.java
new file mode 100644
index 0000000..3b88eb2
--- /dev/null
+++ b/src/main/java/com/oo/OnlyofficeDemoApplication.java
@@ -0,0 +1,14 @@
+package com.oo;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration;
+
+@SpringBootApplication(exclude = {MultipartAutoConfiguration.class,})
+public class OnlyofficeDemoApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(OnlyofficeDemoApplication.class, args);
+ }
+
+}
diff --git a/src/main/java/com/oo/demo/config/CrossOriginConfig.java b/src/main/java/com/oo/demo/config/CrossOriginConfig.java
new file mode 100644
index 0000000..aba7bf2
--- /dev/null
+++ b/src/main/java/com/oo/demo/config/CrossOriginConfig.java
@@ -0,0 +1,21 @@
+package com.oo.demo.config;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * @Author: ymbgy
+ * @Date: 2022-06-13 13:31
+ */
+@Configuration
+public class CrossOriginConfig implements WebMvcConfigurer {
+ @Override
+ public void addCorsMappings(CorsRegistry registry) {
+ registry.addMapping("/**")
+ .allowedOrigins("*")
+ .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
+ .maxAge(3600)
+ .allowCredentials(false);
+ }
+}
diff --git a/src/main/java/com/oo/demo/config/MultipartResolverConfig.java b/src/main/java/com/oo/demo/config/MultipartResolverConfig.java
new file mode 100644
index 0000000..5b7994b
--- /dev/null
+++ b/src/main/java/com/oo/demo/config/MultipartResolverConfig.java
@@ -0,0 +1,27 @@
+package com.oo.demo.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.multipart.MultipartResolver;
+import org.springframework.web.multipart.commons.CommonsMultipartResolver;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.config
+ * @Author: TongHui
+ * @CreateTime: 2022-12-01 17:37
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Configuration
+public class MultipartResolverConfig {
+ @Bean(name="multipartResolver")
+ public MultipartResolver multipartResolver() {
+ CommonsMultipartResolver resolver = new CommonsMultipartResolver();
+ resolver.setDefaultEncoding("UTF-8");
+ resolver.setResolveLazily(true);
+ resolver.setMaxInMemorySize(102400000);
+ resolver.setMaxUploadSize(102400000);
+ return resolver;
+ }
+}
diff --git a/src/main/java/com/oo/demo/config/MybatisPlusConfig.java b/src/main/java/com/oo/demo/config/MybatisPlusConfig.java
new file mode 100644
index 0000000..0da81c5
--- /dev/null
+++ b/src/main/java/com/oo/demo/config/MybatisPlusConfig.java
@@ -0,0 +1,27 @@
+package com.oo.demo.config;
+
+import com.baomidou.mybatisplus.annotation.DbType;
+import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
+import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * MybatisPlusConfig.java
+ * @Description 配置分页插件
+ * @Date 2022/3/24 9:51
+ * @Version 1.0
+ */
+@Configuration
+public class MybatisPlusConfig {
+
+
+ @Bean
+ public MybatisPlusInterceptor mybatisPlusInterceptor() {
+ MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
+ interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
+ return interceptor;
+ }
+
+
+}
diff --git a/src/main/java/com/oo/demo/controller/OnlyOfficeController.java b/src/main/java/com/oo/demo/controller/OnlyOfficeController.java
new file mode 100644
index 0000000..bf6ca47
--- /dev/null
+++ b/src/main/java/com/oo/demo/controller/OnlyOfficeController.java
@@ -0,0 +1,301 @@
+package com.oo.demo.controller;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+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.service.FileService;
+import com.oo.demo.service.OnFileService;
+import com.oo.demo.service.TempUser;
+import com.oo.onlyoffice.api.OnlyServiceAPI;
+import com.oo.onlyoffice.dto.edit.FileUser;
+import com.oo.onlyoffice.tools.FileUtil;
+import com.oo.onlyoffice.tools.SecurityUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.commons.CommonsMultipartFile;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.controller
+ * @Author: TongHui
+ * @CreateTime: 2022-11-08 18:11
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Controller
+@Slf4j
+public class OnlyOfficeController {
+
+ private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ @Autowired
+ private OnFileService onFileService;
+ @Autowired
+ private FileService fileService;
+ @Autowired
+ private OnlyServiceAPI onlyServiceAPI;
+ @Value("${filepath}")
+ private String filepath;
+
+ @RequestMapping("/")
+ public String filesView(Model model) {
+ return "/index";
+ }
+
+
+ @RequestMapping("/file/all")
+ @ResponseBody
+ public Object file(@RequestParam Map parameter) {
+ int page = Integer.parseInt(parameter.get("page"));
+ int limit = Integer.parseInt(parameter.get("limit"));
+
+ QueryWrapper queryWrapper = new QueryWrapper();
+// queryWrapper.notLike("id","MD");
+ queryWrapper.orderByDesc("created_time");
+
+ Page p = new Page<>(page, limit);
+ p = onFileService.page(p, queryWrapper);
+ Map map = new HashMap<>();
+ map.put("code", 0);
+ map.put("msg", "SUCCESS");
+ map.put("count", p.getTotal());
+ map.put("data", p.getRecords());
+ return map;
+ }
+
+ @PostMapping("/files/upload")
+ @ResponseBody
+ public Object upload(@RequestParam("file") MultipartFile[] file) {
+ List result = new ArrayList<>();
+ int i = 0;
+ for (MultipartFile multipartFile : file) {
+ CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
+
+ String filename = multipartFile.getOriginalFilename();
+ // 获取文件后缀
+ String suffix = filename.substring(filename.lastIndexOf(".") + 1);
+ String fileId = "";
+ try {
+ fileId = onFileService.saveFile(commonsMultipartFile.getBytes(), suffix);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ OnFile onFile = new OnFile();
+ onFile.setFileId(fileId);
+ onFile.setFileName(filename);
+ onFile.setVersion("1.0.0");
+ onFile.setCreatedTime(sdf.format(new Date()));
+ onFile.setFileSize(commonsMultipartFile.getSize());
+ onFile.setFileType(suffix);
+ onFile.setFilePath(filepath + "/" + fileId + "." + suffix);
+ onFileService.save(onFile);
+ result.add(onFile);
+ i++;
+ }
+ if (file.length == i) {
+ log.info("文件上传成功");
+ return result;
+ }
+ return Result.error("文件上传失败");
+ }
+
+
+ /**
+ * 打开编辑
+ */
+ @RequestMapping("/onlyOfficeConfig/{mode}/{id}")
+ @ResponseBody
+ public Object openDocument(@PathVariable(required = false) String mode, @PathVariable(required = false) String id, Model model) {//@RequestParam("url") String url,
+ log.info("only office file:" + id);
+ OnFile onFile = onFileService.getById(id);
+ if (onFile == null) {
+ return Result.error("文件不存在");
+ }
+ /**
+ * 必要步骤
+ */
+ FileUser user = new FileUser();
+ user.setId(TempUser.getUserId());
+ user.setName(TempUser.getUserName());
+ SecurityUtils.setUserSession(user);
+ /**
+ * 必要步骤
+ */
+ Map map = new HashMap<>();
+ map.put("fileId", onFile.getFileId());
+ map.put("fileName", onFile.getFileName());
+ map.put("fileType", onFile.getFileType());
+ map.put("fileSize", onFile.getFileSize());
+ map.put("version", onFile.getVersion());
+
+ Map config = onlyServiceAPI.openDocument(map, mode, false);
+
+ SecurityUtils.removeUserSession();
+
+ String s = JSON.toJSONString(config);
+ log.info("only office config:" + s);
+ return s;
+ }
+// @RequestMapping("/onlyOffice/{mode}/{id}")
+// public ModelAndView openDocument(@PathVariable String mode,@PathVariable String id, Model model) {//@RequestParam("url") String url,
+// log.info("only office key:" + id);
+// OnFile onFile = onFileService.getById(id);
+//
+//
+// /**
+// * 必要步骤
+// */
+// FileUser user = new FileUser();
+// user.setId(TempUser.getUserId());
+// user.setName(TempUser.getUserName());
+// SecurityUtils.setUserSession(user);
+// /**
+// * 必要步骤
+// */
+// Map map = new HashMap<>();
+// map.put("fileId",onFile.getFileId());
+// map.put("fileName",onFile.getFileName());
+// map.put("fileType",onFile.getFileType());
+// map.put("fileSize",onFile.getFileSize());
+// map.put("version",onFile.getVersion());
+//
+// Map config = onlyServiceAPI.openDocument(map, mode, false);
+//
+// SecurityUtils.removeUserSession();
+//
+// String s = JSON.toJSONString(config);
+// log.info("only office config:" + s);
+// model.addAllAttributes(config);
+// return new ModelAndView("onlyOffice");
+// }
+
+ /**
+ * 文档编辑服务使用JavaScript API通知callbackUrl,向文档存储服务通知文档编辑的状态。
+ * 文档编辑服务使用具有正文中的信息的POST请求。
+ * https://api.onlyoffice.com/editors/callback
+ * 当我们关闭编辑窗口后,十秒钟左右only office会将它存储的我们的编辑后的文件
+ * 0 - 找不到具有密钥标识符的文档
+ * 1 - 正在编辑文档
+ * 2 - 文档已准备好保存
+ * 3 - 发生文档保存错误
+ * 4 - 不作任何更改就关闭文档
+ * 6 - 正在编辑文档,但保存当前文档状态
+ * 7 - 强制保存文档时发生错误
+ */
+ @RequestMapping("/onlyOffice/save")
+ @ResponseBody
+ public Object saveFile(HttpServletRequest request, HttpServletResponse response) {
+ PrintWriter writer = null;
+ try {
+ writer = response.getWriter();
+ // 获取传输的json数据
+ Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
+ String body = scanner.hasNext() ? scanner.next() : "";
+ JSONObject jsonObject = JSONObject.parseObject(body);
+ log.info("{}", jsonObject);
+
+ Object result = fileService.documentSave(jsonObject);
+ if (Objects.nonNull(writer)) {
+ writer.write("{\"error\":0}");
+ }
+ return result;
+ } catch (Exception e) {
+ e.printStackTrace();
+ writer.write("{\"error\":-1}");
+ return Result.error("保存出错");
+ }
+ /*
+ * status = 1,我们给onlyOffice的服务返回{"error":"0"}的信息。
+ * 这样onlyOffice会认为回调接口是没问题的,这样就可以在线编辑文档了,否则的话会弹出窗口说明
+ */
+// if (Objects.nonNull(writer)) {
+// writer.write("{\"error\":0}");
+// }
+ }
+
+ @PostMapping("/save/{id}")
+ @ResponseBody
+ public Object save(@PathVariable(required = false) String id) {
+ OnFile onFile = onFileService.getById(id);
+ if (onFile == null) {
+ return Result.error("文件不存在,保存失败");
+ }
+ /**
+ * 必要步骤
+ */
+ try {
+ FileUser user = new FileUser();
+ user.setId(TempUser.getUserId());
+ user.setName(TempUser.getUserName());
+ SecurityUtils.setUserSession(user);
+ String key = onlyServiceAPI.getKey(onFile.getFileId());
+ String msg = onlyServiceAPI.save(key, TempUser.getUserId());
+ SecurityUtils.removeUserSession();
+ OnFile fileInfo = new OnFile();
+ fileInfo.setFileId(id);
+ fileInfo.setFileName(onFile.getFileName());
+ fileInfo.setFileType(onFile.getFileType());
+ fileInfo.setFilePath(filepath + "/" + id + "." + onFile.getFileType());
+ return fileInfo;
+ } catch (Exception e) {
+ return Result.error("保存失败");
+ }
+
+ }
+
+
+ @RequestMapping("/converted")
+ public void converted(String id, String suffix, HttpServletResponse response) {
+ try {
+ OnFile onFile = onFileService.getById(id);
+ String title = onFile.getFileName().replace(onFile.getFileType(), suffix);
+ String path = onlyServiceAPI.converted(onFile.getFileType(), onFile.getFileId(), suffix, title, null);
+
+ FileUtil.downloadAttachment(path, title, response);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @PostMapping("/del")
+ @ResponseBody
+ public Object delFile(String id) {
+ try {
+ onFileService.removeFile(id);
+ return Result.OK("删除成功", "fileTable");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return Result.error("删除失败");
+ }
+
+ /**
+ * @param id
+ * @param isBrowser 用来判断是否是oo服务的回调下载 1.没有值 = oo服务回调下载。2.有值 = 页面手动下载
+ * @param response
+ */
+ @RequestMapping("/download/{id}")
+ public void download(@PathVariable String id, String isBrowser, HttpServletResponse response) {
+ try {
+ onFileService.download(id, isBrowser, response);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+}
diff --git a/src/main/java/com/oo/demo/dao/OnFileMapper.java b/src/main/java/com/oo/demo/dao/OnFileMapper.java
new file mode 100644
index 0000000..347772b
--- /dev/null
+++ b/src/main/java/com/oo/demo/dao/OnFileMapper.java
@@ -0,0 +1,18 @@
+package com.oo.demo.dao;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.oo.demo.entity.OnFile;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ *
+ * Mapper 接口
+ *
+ *
+ *
+ * @since 2022-03-10
+ */
+@Mapper
+public interface OnFileMapper extends BaseMapper {
+
+}
diff --git a/src/main/java/com/oo/demo/entity/OnFile.java b/src/main/java/com/oo/demo/entity/OnFile.java
new file mode 100644
index 0000000..64ef35a
--- /dev/null
+++ b/src/main/java/com/oo/demo/entity/OnFile.java
@@ -0,0 +1,37 @@
+package com.oo.demo.entity;
+
+import cn.hutool.core.date.DateUtil;
+import cn.hutool.core.util.IdUtil;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.*;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.entity
+ * @Author: TongHui
+ * @CreateTime: 2022-11-14 10:20
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Data
+@TableName("on_file")
+public class OnFile {
+ @TableId
+ private String fileId;
+ @TableField("`version`")
+ private String version;
+ private String createdTime;
+ private String userName;
+ private String userId;
+ private String fileName;
+ private String fileType;
+ private String filePath;
+ private Long fileSize;
+}
+
diff --git a/src/main/java/com/oo/demo/entity/Result.java b/src/main/java/com/oo/demo/entity/Result.java
new file mode 100644
index 0000000..1faa782
--- /dev/null
+++ b/src/main/java/com/oo/demo/entity/Result.java
@@ -0,0 +1,123 @@
+package com.oo.demo.entity;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * 接口返回数据格式
+ * @author scott
+ * @email jeecgos@163.com
+ * @date 2019年1月19日
+ */
+@Data
+public class Result implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * 成功标志
+ */
+ private boolean success = true;
+
+ /**
+ * 返回处理消息
+ */
+ private String message = "";
+
+ /**
+ * 返回代码
+ */
+ private Integer code = 200;
+
+ /**
+ * 返回数据对象 data
+ */
+ private T result;
+
+ /**
+ * 时间戳
+ */
+ private long timestamp = System.currentTimeMillis();
+
+ public Result() {
+ }
+
+ /**
+ * 兼容VUE3版token失效不跳转登录页面
+ * @param code
+ * @param message
+ */
+ public Result(Integer code, String message) {
+ this.code = code;
+ this.message = message;
+ }
+
+ public Result success(String message) {
+ this.message = message;
+ this.code = 200;
+ this.success = true;
+ return this;
+ }
+
+
+
+ public static Result OK() {
+ Result r = new Result();
+ r.setSuccess(true);
+ r.setCode(200);
+ return r;
+ }
+
+
+ public static Result OK(String msg) {
+ Result r = new Result();
+ r.setSuccess(true);
+ r.setCode(200);
+ r.setMessage(msg);
+ //Result OK(String msg)方法会造成兼容性问题 issues/I4IP3D
+ r.setResult((T) msg);
+ return r;
+ }
+
+ public static Result OK(T data) {
+ Result r = new Result();
+ r.setSuccess(true);
+ r.setCode(200);
+ r.setResult(data);
+ return r;
+ }
+
+ public static Result OK(String msg, T data) {
+ Result r = new Result();
+ r.setSuccess(true);
+ r.setCode(200);
+ r.setMessage(msg);
+ r.setResult(data);
+ return r;
+ }
+
+ public static Result error(String msg, T data) {
+ Result r = new Result();
+ r.setSuccess(false);
+ r.setCode(500);
+ r.setMessage(msg);
+ r.setResult(data);
+ return r;
+ }
+
+ public static Result error(String msg) {
+ return error(500, msg);
+ }
+
+
+ public static Result error(int code, String msg) {
+ Result r = new Result();
+ r.setCode(code);
+ r.setMessage(msg);
+ r.setSuccess(false);
+ return r;
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/main/java/com/oo/demo/service/DemoService.java b/src/main/java/com/oo/demo/service/DemoService.java
new file mode 100644
index 0000000..4bf48c9
--- /dev/null
+++ b/src/main/java/com/oo/demo/service/DemoService.java
@@ -0,0 +1,63 @@
+package com.oo.demo.service;
+
+import com.oo.demo.entity.OnFile;
+import com.oo.onlyoffice.config.OnlyProperties;
+import com.oo.onlyoffice.core.SaveFileProcessor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.Map;
+
+/**
+ * @BelongsProject: onlyoffice-demo
+ * @BelongsPackage: com.oo.demo.service
+ * @Author: TongHui
+ * @CreateTime: 2023-08-01 16:00
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Service
+public class DemoService implements SaveFileProcessor {
+
+ @Autowired
+ private OnlyProperties onlyProperties;
+ @Autowired
+ private OnFileService onFileService;
+
+
+ @Override
+ public void saveBeforeInitialization(Map map, byte[] bytes, String fileExtension) throws Exception {
+
+ }
+
+ @Override
+ public Map save(Map map, byte[] file, byte[] changes, String key){
+ String fileId = "";
+ try {
+ 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);
+
+ OnFile onFile = new OnFile();
+ onFile.setFileId(fileId);
+ onFile.setFileName(map.get("fileName").toString());
+ onFile.setVersion(version);
+ onFile.setFileSize((long) file.length);
+ onFile.setFileType(map.get("fileType").toString());
+ onFileService.save(onFile);
+
+ map.put("version", version);
+ return map;
+ }
+
+ @Override
+ public void saveAfterInitialization(Map map, byte[] bytes, String fileExtension) throws Exception {
+
+ }
+
+}
diff --git a/src/main/java/com/oo/demo/service/FileService.java b/src/main/java/com/oo/demo/service/FileService.java
new file mode 100644
index 0000000..1b0f2bb
--- /dev/null
+++ b/src/main/java/com/oo/demo/service/FileService.java
@@ -0,0 +1,116 @@
+package com.oo.demo.service;
+
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.oo.onlyoffice.api.OnlyServiceAPI;
+import com.oo.onlyoffice.dto.edit.FileUser;
+import com.oo.onlyoffice.tools.SecurityUtils;
+import com.oo.demo.entity.Result;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+//import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpServletResponse;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @BelongsProject: onlyoffice-demo
+ * @BelongsPackage: com.oo.demo.service
+ * @Author: TongHui
+ * @CreateTime: 2023-08-02 09:57
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Slf4j
+@Service
+public class FileService {
+
+ @Autowired
+ private OnlyServiceAPI onlyServiceAPI;
+ @Autowired
+ private DemoService demoService;
+
+
+ /**
+ * 文档服务器 保存文件回调
+ *
+ * @param jsonObject
+ */
+ @Transactional(rollbackFor = Exception.class)
+ public Object documentSave(JSONObject jsonObject) {
+ JSONObject result = new JSONObject();
+ String key = "";
+ try {
+ int status = jsonObject.getIntValue("status");
+ log.info("status[{}]", status);
+ if (6 == status) {
+ log.info("开始保存文件");
+
+ JSONArray jsonArray = jsonObject.getJSONObject("history").getJSONArray("changes");
+ JSONObject object = jsonArray.getJSONObject(0);
+ String userId = object.getJSONObject("user").getString("id");
+ FileUser fileUser = new FileUser();
+ fileUser.setId(userId);
+ SecurityUtils.setUserSession(fileUser);
+
+ key = jsonObject.getString("key");
+
+ //文件id
+ String id = onlyServiceAPI.getFileId(key);
+
+
+ //判断是否是最后一人进行保存
+ int users = onlyServiceAPI.getUserNum(key);
+ if (users > 1) {
+ return null;
+ }
+
+ //历史版本最大个数 获取当前文件的历史版本数量
+ Integer histNum = onlyServiceAPI.getHistNum();
+ /**
+ * 如果有需要保存历史记录 可以进行相关操作
+ */
+ if (null != histNum) {
+
+ }
+
+ //处理文件的保存
+ onlyServiceAPI.handlerStatus(jsonObject);
+
+
+ log.info("保存文件结束");
+ SecurityUtils.removeUserSession();
+ result.put("key", key);
+ result.put("fileId", id);
+ return result;
+ } else if (0 == status || 2 == status || 4 == status) {
+ onlyServiceAPI.close(jsonObject);
+ } else if (3 == status || 7 == status) {
+ //保存文档错误
+ onlyServiceAPI.close(jsonObject);
+ } else if (1 == status) {
+ //文件服务的回调 获取key判断当前文档有多少人在这使用
+ List actions = JSONObject.parseArray(jsonObject.getString("actions"), Map.class);
+ if ((Integer) actions.get(0).get("type") == 1) {
+ log.info("当前用户有[{}]", jsonObject.getString("users"));
+ List users = JSONObject.parseArray(jsonObject.getString("users"), String.class);
+ onlyServiceAPI.iskey(jsonObject.getString("key"), users.size());
+ }
+ if ((Integer) actions.get(0).get("type") == 0) {
+ onlyServiceAPI.iskey(jsonObject.getString("key"), null);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+ result.put("key", key);
+ return result;
+ }
+
+
+}
diff --git a/src/main/java/com/oo/demo/service/OnFileService.java b/src/main/java/com/oo/demo/service/OnFileService.java
new file mode 100644
index 0000000..fc1aba6
--- /dev/null
+++ b/src/main/java/com/oo/demo/service/OnFileService.java
@@ -0,0 +1,17 @@
+package com.oo.demo.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.oo.demo.entity.OnFile;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+
+
+public interface OnFileService extends IService {
+
+ String saveFile(byte[] bytes, String fileType) throws Exception;
+
+ void removeFile(String id);
+
+ void download(String id,String isBrowser, HttpServletResponse response);
+}
diff --git a/src/main/java/com/oo/demo/service/OnFileServiceImpl.java b/src/main/java/com/oo/demo/service/OnFileServiceImpl.java
new file mode 100644
index 0000000..3b55a27
--- /dev/null
+++ b/src/main/java/com/oo/demo/service/OnFileServiceImpl.java
@@ -0,0 +1,70 @@
+package com.oo.demo.service;
+
+import cn.hutool.core.util.IdUtil;
+import cn.hutool.core.util.StrUtil;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.oo.demo.dao.OnFileMapper;
+import com.oo.demo.entity.OnFile;
+import com.oo.onlyoffice.tools.FileUtil;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.nio.file.Files;
+
+
+/**
+ *
+ * 服务实现类
+ *
+ *
+ *
+ * @since 2022-03-10
+ */
+@Service
+public class OnFileServiceImpl extends ServiceImpl implements OnFileService {
+ @Value("${filepath}")
+ private String path;
+
+ @Override
+ public void download(String id, String isBrowser, HttpServletResponse response) {
+ OnFile byId = baseMapper.selectById(id);
+
+ //判断是否有值
+ if (StrUtil.isNotEmpty(isBrowser)) {
+ FileUtil.downloadAttachment(path + "/" + id + "." + byId.getFileType(), byId.getFileName(), response);
+ } else {
+ FileUtil.downloadInline(path + "/" + id + "." + byId.getFileType(), byId.getFileName(), response);
+ }
+ }
+
+ @Override
+ public void removeFile(String id) {
+ OnFile byId = baseMapper.selectById(id);
+ System.out.println(path);
+ File file = new File(path + "/" + id + "." + byId.getFileType());
+ System.out.println("删除文件");
+ FileUtils.deleteQuietly(file);
+
+ removeById(id);
+ }
+
+ public String saveFile(byte[] bytes, String fileType) throws Exception {
+
+ String fileId = IdUtil.simpleUUID();
+ File file = new File(path + "/" + fileId + "." + fileType);
+ File parentFile = file.getParentFile();
+ if (!parentFile.exists()) {
+ parentFile.mkdirs();
+ }
+ try (FileOutputStream out = new FileOutputStream(path + "/" + fileId + "." + fileType)) {
+ out.write(bytes);
+ out.flush();
+ }
+ return fileId;
+ }
+}
diff --git a/src/main/java/com/oo/demo/service/TempUser.java b/src/main/java/com/oo/demo/service/TempUser.java
new file mode 100644
index 0000000..443479a
--- /dev/null
+++ b/src/main/java/com/oo/demo/service/TempUser.java
@@ -0,0 +1,41 @@
+package com.oo.demo.service;
+
+import cn.hutool.core.util.IdUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.*;
+
+/**
+ * @BelongsProject: onlyoffice-demo
+ * @BelongsPackage: com.oo.demo.service
+ * @Author: TongHui
+ * @CreateTime: 2023-08-05 17:14
+ * @Description: TODO 用户信息
+ * @Version: 1.0
+ */
+public class TempUser {
+ private static Logger logger = LoggerFactory.getLogger(TempUser.class);
+ private static List> cache1 = new ArrayList<>();
+ private static Integer index;
+
+ static {
+ for (int i = 0; i < 1; i++) {
+ Map map = new HashMap<>();
+ map.put("userId", "1");
+ map.put("userName","OnlyOfficeUserName"+map.get("userId"));
+ cache1.add(map);
+ }
+ logger.info("用户初始完毕");
+ Random random = new Random();
+// index = random.nextInt(10);
+ index = 0;
+ logger.info("获取用户完毕"+index);
+ }
+ public static String getUserName(){
+ return cache1.get(index).get("userName");
+ }
+ public static String getUserId(){
+ return cache1.get(index).get("userId");
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/api/OnlyServiceAPI.java b/src/main/java/com/oo/onlyoffice/api/OnlyServiceAPI.java
new file mode 100644
index 0000000..60762f0
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/api/OnlyServiceAPI.java
@@ -0,0 +1,115 @@
+package com.oo.onlyoffice.api;
+
+import com.alibaba.fastjson.JSONObject;
+import com.oo.onlyoffice.core.context.FileMetadata;
+
+
+import java.util.Map;
+
+
+public interface OnlyServiceAPI {
+ /**
+ * 打开only office
+ *
+ * @param map 文件数据信息
+ * @param map{
+ * 必填 fileId
+ * 必填 fileName
+ * 必填 fileType
+ * 必填 fileSize
+ * 可用携带其它值
+ * }
+ * @param mode 打开方式 edit/view
+ * @param collaborativeEditing 是否协同编辑
+ * @return 配置信息
+ */
+ Map openDocument(Map map, String mode, boolean collaborativeEditing);
+
+
+
+
+ /**
+ * 处理保存结果
+ *
+ * @param jsonObject 信息
+ */
+ void handlerStatus(JSONObject jsonObject) throws Exception;
+
+
+ /**
+ * 删除临时文件
+ *
+ * @param jsonObject
+ */
+ void removeTempFile(JSONObject jsonObject);
+
+ /**
+ * 获取文件元数据
+ *
+ * @param key
+ * @return
+ */
+ FileMetadata getTempFile(String key);
+
+ /**
+ * 获取历史数量上限
+ *
+ * @return
+ */
+ Integer getHistNum();
+
+ /**
+ * 获取打开文档时的唯一key
+ *
+ * @param id
+ * @return
+ */
+ String getKey(String id);
+
+ /**
+ * 当文件没有人使用时,清空文件信息
+ */
+ void close(JSONObject jsonObject);
+
+ /**
+ * redis中存放文件使用人数
+ *
+ * @param key
+ * @param users
+ */
+ int iskey(String key, Integer users);
+
+ /**
+ * 获取文档是使用人数
+ * @return
+ */
+ int getUserNum(String key);
+
+ /**
+ * 获取文件id
+ * @return
+ */
+ String getFileId(String key);
+
+ String getCommandServiceUrl();
+
+ Integer getTimeout();
+
+ String downloadFileRequestPath();
+
+ /**
+ * 文件保存
+ */
+ String save(String key, String userId);
+
+ /**
+ * 文件转换
+ * @param filetype 文件类型
+ * @param fileId 文件id
+ * @param outputtype 转换类型
+ * @param title 转换后的名称
+ * @param password 文档密码
+ * @return 转换后的文件下载地址
+ */
+ String converted(String filetype, String fileId, String outputtype, String title,String password);
+}
diff --git a/src/main/java/com/oo/onlyoffice/api/impl/OnlyServiceAPIImpl.java b/src/main/java/com/oo/onlyoffice/api/impl/OnlyServiceAPIImpl.java
new file mode 100644
index 0000000..e95ea79
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/api/impl/OnlyServiceAPIImpl.java
@@ -0,0 +1,544 @@
+package com.oo.onlyoffice.api.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.oo.onlyoffice.api.OnlyServiceAPI;
+import com.oo.onlyoffice.config.OnlyProperties;
+import com.oo.onlyoffice.core.Cache;
+import com.oo.onlyoffice.core.SaveFileProcessor;
+import com.oo.onlyoffice.core.context.FileMetadata;
+import com.oo.onlyoffice.tools.DocumentKey;
+import com.oo.onlyoffice.tools.JWTUtil;
+import com.oo.onlyoffice.vo.FileConfig;
+import com.oo.onlyoffice.core.OnlyOfficeConfigFactory;
+import com.oo.onlyoffice.dto.convert.ConvertBody;
+import com.oo.onlyoffice.dto.edit.FileUser;
+import com.oo.onlyoffice.core.context.FileContext;
+import com.oo.onlyoffice.core.FileHandler;
+import com.oo.onlyoffice.tools.FileUtil;
+import com.oo.onlyoffice.tools.SecurityUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+
+/**
+ * only office 实现类
+ */
+@Service
+@Slf4j
+public class OnlyServiceAPIImpl implements OnlyServiceAPI {
+
+ @Autowired
+ private OnlyOfficeConfigFactory onlyOfficeConfigFactory;
+ @Autowired
+ private SaveFileProcessor saveFileProcessor;
+ @Autowired
+ private OnlyProperties onlyProperties;
+ @Autowired
+ private FileContext tempFileContext;
+ @Autowired
+ private FileHandler fileHandler;
+ @Autowired
+ private Cache cache;
+
+ private String EDIT = "edit";
+ private String VIEW = "view";
+
+
+ /**
+ * @param map 文件信息
+ * @param map{
+ * 必填 fileId
+ * 必填 fileName
+ * 必填 fileType
+ * 必填 fileSize
+ * 可用携带其它信息
+ * }
+ * @param mode 打开方式 edit/view
+ * @param collaborativeEditing 是否协同编辑
+ * @return
+ */
+ @Override
+ public Map openDocument(Map map, String mode, boolean collaborativeEditing) {
+ long fileSize = (long) map.get("fileSize");
+
+ if (fileSize > onlyProperties.getMaxSize()) {
+ // 添加操作日志
+ throw new RuntimeException("文件超过【"+onlyProperties.getMaxSize()/1024/1024+"MB】无法打开");
+ }
+
+ if (EDIT.equals(mode)) {
+ return documentEdit(map,collaborativeEditing);
+ }
+ if (VIEW.equals(mode)) {
+ return documentView(map);
+ }
+ return null;
+ }
+
+ private Map documentEdit(Map map,boolean collaborativeEditing) {
+ FileConfig fileConfigDTO = openEditConfig(map, "edit", collaborativeEditing);
+ String json = JSON.toJSONString(fileConfigDTO);
+
+ Map config = JSON.parseObject(json, Map.class);
+
+
+ return config;
+ }
+
+
+ private Map documentView(Map map) {
+ FileConfig fileConfigDTO = openEditConfig(map, "view", false);
+ String json = JSON.toJSONString(fileConfigDTO);
+ Map config = JSON.parseObject(json, Map.class);
+
+ return config;
+ }
+
+ private FileConfig openEditConfig(Map map, String mode, boolean collaborativeEditing) {
+ try {
+ map.put("mode", mode);
+ log.info("开始生成文件信息");
+ //在编辑模式 生成临时文件,保存原文件信息
+ FileMetadata tempFileInfo = fileHandler.handlerFile(map,collaborativeEditing) ;
+ //生成配置文件 TODO: 控制文件权限
+ log.info("开始生成编辑器配置信息");
+ FileConfig fileConfigDTO = onlyOfficeConfigFactory.buildInitConfig(tempFileInfo.getUrl(), mode, tempFileInfo.getKey(), tempFileInfo.getOldName());
+ log.info("生成编辑器配置信息结束");
+ // TODO: 添加更多详细的自定义信息
+ return fileConfigDTO;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+
+
+
+ /**
+ * 获取规定历史文件数量
+ *
+ * @return
+ */
+ @Override
+ public Integer getHistNum() {
+ return onlyProperties.getHistNum();
+ }
+
+
+ /**
+ * 保存文件地址
+ *
+ * @return
+ */
+ @Override
+ public String getCommandServiceUrl() {
+ return onlyProperties.getDocService() + onlyProperties.SAVE;
+ }
+
+ @Override
+ public Integer getTimeout() {
+ return onlyProperties.getTimeout();
+ }
+
+ @Override
+ public String downloadFileRequestPath() {
+ if (onlyProperties.getDownloadFile().endsWith("/")) {
+ return onlyProperties.getDownloadFile();
+ }
+ return onlyProperties.getDownloadFile() + "/";
+ }
+
+
+ @Override
+ public void handlerStatus(JSONObject jsonObject) throws Exception {
+ log.info("开始下载编辑器文件");
+ int status = jsonObject.getIntValue("status");
+ log.info("status[{}]:{}", status, jsonObject);
+ String key = (String) jsonObject.get("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);
+ // 下载前一个文化和修改后文件的区别
+ byte[] changes = FileUtil.getFileByte(changesurl);
+ log.info("下载编辑器文件成功");
+
+ log.info("保存文件前置处理");
+ try {
+ String fileExtension = FileUtil.getFileExtension(url);
+
+ Optional tempFile = tempFileHandler.getTempFile(key);
+
+ if (!tempFile.isPresent()){
+ throw new RuntimeException("文件元信息不存在");
+ }
+
+
+ saveFileProcessor.saveBeforeInitialization(tempFile.get().getFileInfo(),fileByte,fileExtension);
+
+ // 保存文件
+ Map map = saveFileProcessor.save(tempFile.get().getFileInfo(),fileByte,changes, key);
+
+ saveFileProcessor.saveAfterInitialization(tempFile.get().getFileInfo(),fileByte,fileExtension);
+ //更新内存文件信息
+ tempFileContext.updateCacheFileInfo(key,map);
+ } catch (Exception e) {
+ throw e;
+ }
+ }
+ }
+
+ public void removeTempFile(JSONObject jsonObject) {
+ String key = (String) jsonObject.get("key");
+ FileHandler tempFileHandler = tempFileContext.getHandlerByKey(key);
+ if (tempFileHandler != null) {
+ log.info("删除临时文件信息缓存" + key);
+ tempFileHandler.removeTempFile(key);
+ }
+ }
+
+ /**
+ * 临时文件信息
+ *
+ * @param key
+ * @return
+ */
+ public FileMetadata getTempFile(String key) {
+ FileMetadata tempFileInfo = tempFileContext.getFileInfo(key);
+ if (tempFileInfo != null) {
+ return tempFileInfo;
+ }
+ return null;
+ }
+
+ /**
+ * 获取打开文档时的唯一key
+ *
+ * @param id 文件id
+ * @return
+ */
+ public String getKey(String id) {
+ FileUser user = SecurityUtils.getUserSession();
+
+ if (cache.hasKey(user.getId() + "_" + id)) {
+ return (String) cache.get(user.getId() + "_" + id);
+ }
+
+ return (String) cache.get("collaborativeEditing_" + id);
+ }
+
+ public void close(JSONObject jsonObject) {
+ // 判断临时信息是否存在
+ FileMetadata tempFile = getTempFile(jsonObject.getString("key"));
+ if (tempFile == null){
+ return;
+ }
+
+ //判断 删除时间 是否大于 文件打开时间
+ //如果 删除时间 小于 文件打开时间 不执行删除
+ log.info("打开时间:"+tempFile.getOpenTime()+",回调时间:"+ new Date().getTime());
+ if (new Date().getTime() < tempFile.getOpenTime()){
+ return;
+ }
+ // 减少文档的使用人数
+ int i = iskey(jsonObject.getString("key"), null);
+ //如果没有人使用当前文档,清空临时信息
+ if (i <= 0) {
+ removeTempFile(jsonObject);
+ String id = (String) cache.get("getID_" + jsonObject.getString("key"));
+ cache.remove("getID_" + id);
+ cache.remove("collaborativeEditing_" + id);
+ cache.remove(id);
+ }
+ }
+
+ /**
+ * redis中存放文件使用人数
+ *
+ * @param key
+ * @param users
+ */
+ public int iskey(String key, Integer users) {
+ int i = 0;
+ if (users != null) {
+ cache.set(key, users);
+ i = users;
+ } else {
+ i = ((int)cache.get(key)) - 1;
+ cache.set(key, (i>=0 ? i : 0));
+ }
+ log.info("[" + key + "]文档使用人数:" + i);
+ return i;
+ }
+
+ @Override
+ public int getUserNum(String key) {
+ return (int)(cache.get(key));
+ }
+
+ @Override
+ public String getFileId(String key) {
+ return (String) cache.get("getID_" + key);
+ }
+
+ /**
+ * https://documentserver/coauthoring/CommandService.ashx
+ * {
+ * "c": "forcesave",
+ * "key": "Khirz6zTPdfd7",
+ * "userdata": "sample userdata"
+ * }
+ */
+ public String save(String key, String userId) {
+ Map map = new HashMap<>();
+ map.put("c", "forcesave");
+ map.put("key", key);
+ map.put("userdata", userId);
+ if (null != onlyProperties.getSecret()){
+ String token = JWTUtil.createToken(map,onlyProperties.getSecret());
+ map.put("token",token);
+ }
+ String bodyString = JSON.toJSONString(map);
+ log.info("forcesave:"+bodyString);
+ byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);
+ try {
+ URL url = new URL(onlyProperties.getDocService() + onlyProperties.SAVE);
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ connection.setRequestMethod("POST");
+ connection.setDoOutput(true);
+ connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
+ connection.setFixedLengthStreamingMode(bodyByte.length);
+ connection.setRequestProperty("Accept", "application/json");
+ connection.setConnectTimeout(onlyProperties.getTimeout());
+
+ connection.connect();
+
+ OutputStream os = connection.getOutputStream();
+ os.write(bodyByte);
+
+ InputStream stream = connection.getInputStream();
+
+ if (stream == null) {
+ throw new Exception("Could not get an answer");
+ }
+
+ /**将流转为字符串*/
+ String jsonString = FileUtil.ConvertStreamToString(stream);
+ connection.disconnect();
+ JSONObject jsonObj = JSONObject.parseObject(jsonString);
+ log.debug(jsonObj.toJSONString());
+ Object error = jsonObj.get("error");
+ String msg = "";
+ if (error != null) {
+ switch ((Integer) error) {
+ case 1:
+ msg = "缺少文档密钥或找不到具有此类密钥的文档";
+ break;
+ case 2:
+ msg = "回调网址不正确";
+ break;
+ case 3:
+ msg = "内部服务器错误";
+ break;
+ case 4:
+ msg = "在收到强制保存命令之前,未对文档应用任何更改";
+ break;
+ case 5:
+ msg = "命令不正确";
+ break;
+ case 6:
+ msg = "令牌无效";
+ break;
+ default:
+ msg = "保存成功";
+ }
+ }
+ return msg;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return "";
+ }
+ /**
+ * 文件转化 #简单请求参数示例:
+ * @param filetype 文件类型
+ * @param key 文件key
+ * @param outputtype 输出类型
+ * @param fileUrl 文件路径
+ * @param title 输出文件名称
+ * @param password 加密文档的密码
+ * @return 文件路径
+ */
+ /**
+ * //#请求参数示例 https://www.songbin.top/post_27457.html
+ * {
+ * "filetype": "xlsx",
+ * "key": "Khirz6zTPdfd7",
+ * "outputtype": "pdf",
+ * "region": "en-US",
+ * "spreadsheetLayout": {
+ * "ignorePrintArea": true,
+ * "orientation": "portrait",
+ * "fitToWidth": 0,
+ * "fitToHeight": 0,
+ * "scale": 100,
+ * "headings": false,
+ * "gridLines": false,
+ * "pageSize": {
+ * "width": "210mm",
+ * "height": "297mm"
+ * },
+ * "margins": {
+ * "left": "17.8mm",
+ * "right": "17.8mm",
+ * "top": "19.1mm",
+ * "bottom": "19.1mm"
+ * }
+ * },
+ * "title": "Example Document Title.pdf",
+ * "url": "https://example.com/url-to-example-spreadsheet.xlsx"
+ * }
+ */
+ @Override
+ public String converted(String filetype, String key, String outputtype, String title,String password) {
+ log.debug("文件开始转化{}->{}", filetype, outputtype);
+
+ String fileUrl = onlyProperties.getDownloadFile()+key;
+
+ ConvertBody body = new ConvertBody(filetype, DocumentKey.SnowflakeId(), outputtype, fileUrl, title,password);
+ String bodyString = JSON.toJSONString(body);
+
+ if (null != onlyProperties.getSecret()){
+ String token = JWTUtil.createToken(JSON.parseObject(bodyString,Map.class),onlyProperties.getSecret());
+ body.setToken(token);
+ bodyString = JSON.toJSONString(body);
+ }
+
+ log.debug(bodyString);
+ byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);
+ try {
+ URL url = new URL(onlyProperties.getDocService() + onlyProperties.CONVERTER);
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ connection.setRequestMethod("POST");
+ connection.setDoOutput(true);
+ connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
+ connection.setFixedLengthStreamingMode(bodyByte.length);
+ connection.setRequestProperty("Accept", "application/json");
+ connection.setConnectTimeout(onlyProperties.getTimeout());
+
+ connection.connect();
+
+ OutputStream os = connection.getOutputStream();
+ os.write(bodyByte);
+
+ InputStream stream = connection.getInputStream();
+
+ if (stream == null) {
+ throw new Exception("Could not get an answer");
+ }
+
+ /**将流转为字符串*/
+ String jsonString = FileUtil.ConvertStreamToString(stream);
+
+ connection.disconnect();
+
+ JSONObject jsonObj = JSONObject.parseObject(jsonString);
+ log.debug(jsonObj.toJSONString());
+ /**
+ * {
+ * "endConvert":true,//转换是否完成
+ * "fileUrl":“ https://documentserver/ResourceService.ashx?filename=output.doc”,//转换后的文件地址
+ * "percent":100//转换完成百分比 仅参数设置为异步时
+ * }
+ */
+ Object error = jsonObj.get("error");
+ if (error != null) {
+ ProcessConvertServiceResponceError((Integer) error);
+ }
+
+ /**检查转换是否完成,并将结果保存到一个变量中*/
+ Boolean isEndConvert = (Boolean) jsonObj.get("endConvert");
+ Long resultPercent = 0L;
+ String responseUri = null;
+
+ if (isEndConvert) {
+ resultPercent = 100L;
+ responseUri = (String) jsonObj.get("fileUrl");
+ log.debug("文件转化完成{}->{}", filetype, outputtype);
+ } else {
+ resultPercent = (Long) jsonObj.get("percent");
+ resultPercent = resultPercent >= 100l ? 99l : resultPercent;
+ }
+
+ return resultPercent >= 100L ? responseUri : "";
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+
+ /**
+ * 错误代码 描述
+ * -1 未知错误。
+ * -2 转换超时错误。
+ * -3 转换错误。
+ * -4 下载要转换的文档文件时出错。
+ * -5 密码不正确。
+ * -6 访问转换结果数据库时出错。
+ * -7 输入错误。
+ * -8 令牌无效。
+ */
+ private void ProcessConvertServiceResponceError(int errorCode) throws Exception {
+ String errorMessage = "";
+ String errorMessageTemplate = "Error occurred in the ConvertService: ";
+ switch (errorCode) {
+ case -8:
+ errorMessage = errorMessageTemplate + "令牌无效";
+ break;
+ case -7:
+ errorMessage = errorMessageTemplate + "输入错误";
+ break;
+ case -6:
+ errorMessage = errorMessageTemplate + "访问转换结果数据库时出错";
+ break;
+ case -5:
+ errorMessage = errorMessageTemplate + "密码不正确";
+ break;
+ case -4:
+ errorMessage = errorMessageTemplate + "下载要转换的文档文件时出错";
+ break;
+ case -3:
+ errorMessage = errorMessageTemplate + "转换错误";
+ break;
+ case -2:
+ errorMessage = errorMessageTemplate + "转换超时错误";
+ break;
+ case -1:
+ errorMessage = errorMessageTemplate + "未知错误";
+ break;
+ case 0:
+ break;
+ default:
+ errorMessage = "ErrorCode = " + errorCode;
+ break;
+ }
+ throw new Exception(errorMessage);
+ }
+}
+
+
diff --git a/src/main/java/com/oo/onlyoffice/config/CreateBean.java b/src/main/java/com/oo/onlyoffice/config/CreateBean.java
new file mode 100644
index 0000000..49516bd
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/config/CreateBean.java
@@ -0,0 +1,100 @@
+package com.oo.onlyoffice.config;
+
+import cn.hutool.json.JSONObject;
+import com.alibaba.fastjson.JSON;
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.oo.onlyoffice.core.Cache;
+import com.oo.onlyoffice.core.cache.InsideCache;
+import com.oo.onlyoffice.core.cache.RedisCache;
+import com.oo.onlyoffice.tools.LoadConfigUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.RedisSerializer;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+/**
+ * @BelongsProject: onlyoffice-demo
+ * @BelongsPackage: com.oo.onlyoffice.config
+ * @Author: TongHui
+ * @CreateTime: 2023-08-01 16:17
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Slf4j
+@Configuration
+public class CreateBean {
+ @Value("${serverhost}")
+ private String serverhost;
+
+ @Bean
+ public OnlyProperties getOnlyProperties() {
+ OnlyProperties onlyProperties = new OnlyProperties();
+ JSONObject map = LoadConfigUtil.getMap();
+ onlyProperties.setCallBackUrl(map.getStr("call-back-url"));
+ onlyProperties.setDocService(map.getStr("doc-service"));
+ onlyProperties.setDownloadFile(serverhost + map.getStr("download-file"));
+ onlyProperties.setHistNum(map.getInt("hist-num"));
+ onlyProperties.setSecret(map.getStr("secret"));
+ onlyProperties.setTimeout(map.getInt("timeout"));
+ onlyProperties.setLocalhostAddress(serverhost + map.getStr("localhost-address"));
+ onlyProperties.setMaxSize(map.getLong("max-size"));
+ log.info(JSON.toJSONString(onlyProperties));
+ return onlyProperties;
+ }
+
+ @Bean
+ public Cache getCache(RedisTemplate redisTemplate) {
+ JSONObject map = LoadConfigUtil.getMap();
+ String c = map.getStr("cache");
+ if (null != c && c.equals("redis")) {
+ return new RedisCache(redisTemplate);
+ }
+
+ return new InsideCache();
+ }
+
+ /**
+ * RedisTemplate配置
+ *
+ * @param lettuceConnectionFactory
+ * @return
+ */
+ @Bean
+ public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
+ log.info(" --- redis config init --- ");
+ Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = jacksonSerializer();
+ RedisTemplate redisTemplate = new RedisTemplate();
+ redisTemplate.setConnectionFactory(lettuceConnectionFactory);
+ RedisSerializer stringSerializer = new StringRedisSerializer();
+
+ // key序列化
+ redisTemplate.setKeySerializer(stringSerializer);
+ // value序列化
+ redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
+ // Hash key序列化
+ redisTemplate.setHashKeySerializer(stringSerializer);
+ // Hash value序列化
+ redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
+ redisTemplate.afterPropertiesSet();
+ return redisTemplate;
+ }
+
+ private Jackson2JsonRedisSerializer jacksonSerializer() {
+ Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+ objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+ jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
+ return jackson2JsonRedisSerializer;
+ }
+
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/config/OnlyProperties.java b/src/main/java/com/oo/onlyoffice/config/OnlyProperties.java
new file mode 100644
index 0000000..a4919f0
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/config/OnlyProperties.java
@@ -0,0 +1,72 @@
+package com.oo.onlyoffice.config;
+
+import lombok.Data;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+
+/**
+ * 配置信息
+ */
+@Data
+public class OnlyProperties {
+
+
+ private String localhostAddress;
+
+ /**
+ * 回调地址 不包含http表示本机地址
+ */
+
+ private String callBackUrl ;
+
+ /**
+ * only office服务路径
+ * 必须存在
+ */
+
+ private String docService ;
+ /**
+ * 下载文件请求接口
+ * */
+
+ private String downloadFile;
+
+ /**超时时间*/
+
+ private Integer timeout ;
+
+
+ /**
+ * 历史文件数量
+ */
+
+ private Integer histNum ;
+
+ /**
+ * JWT令牌
+ */
+
+ private String secret ;
+
+
+ /**
+ * 打开文件最大MB
+ * */
+ private Long maxSize;
+
+
+ public final String DOC_API_URL = "/web-apps/apps/api/documents/api.js";
+ public final String CONVERTER = "/ConvertService.ashx";
+ public final String SAVE = "/coauthoring/CommandService.ashx";
+
+
+ public void setMaxSize(Long maxSize) {
+ if (null == maxSize){
+ this.maxSize = Long.valueOf(20*1024*1024);
+ }else {
+ this.maxSize = maxSize*1024*1024;
+ }
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/Cache.java b/src/main/java/com/oo/onlyoffice/core/Cache.java
new file mode 100644
index 0000000..50c600b
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/Cache.java
@@ -0,0 +1,10 @@
+package com.oo.onlyoffice.core;
+
+public interface Cache {
+
+ Object get(String key);
+ void set(String key,Object value,long time);
+ void set(String key,Object value);
+ boolean hasKey(String key);
+ void remove(String key);
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/FileConfigFactory.java b/src/main/java/com/oo/onlyoffice/core/FileConfigFactory.java
new file mode 100644
index 0000000..11dbf5e
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/FileConfigFactory.java
@@ -0,0 +1,131 @@
+package com.oo.onlyoffice.core;
+
+import cn.hutool.core.date.DateUtil;
+import com.oo.onlyoffice.core.OnlyOfficeConfigFactory;
+import com.oo.onlyoffice.dto.DocumentConfig;
+import com.oo.onlyoffice.dto.EditorConfig;
+import com.oo.onlyoffice.dto.Plugins;
+import com.oo.onlyoffice.tools.*;
+import com.oo.onlyoffice.config.OnlyProperties;
+import com.oo.onlyoffice.dto.document.DocumentInfo;
+import com.oo.onlyoffice.dto.document.DocumentPermission;
+import com.oo.onlyoffice.dto.document.SharingSettings;
+import com.oo.onlyoffice.dto.edit.FileCustomization;
+import com.oo.onlyoffice.dto.edit.FileUser;
+import com.oo.onlyoffice.vo.FileConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.*;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.dto
+ * @Author: TongHui
+ * @CreateTime: 2022-11-16 17:00
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Component
+public class FileConfigFactory implements OnlyOfficeConfigFactory {
+
+ @Autowired
+ private OnlyProperties onlyProperties;
+
+ /**
+ * 初始化 only office 最基础的信息必要数据
+ *
+ * @param fileUrl 可访问的url路径
+ * @param mode 打开方式
+ * @param key 唯一标示符 20个字符以内
+ * @param fileName 文件名称
+ * @return 配置信息
+ */
+ @Override
+ public FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName) {
+
+ Map map = new HashMap<>();
+
+ FileConfig fileConfigDTO = new FileConfig();
+ // 1、文档类型
+ fileConfigDTO.setDocumentType(OnlyOfficeUtil.getDocumentType(fileName));
+ map.put("documentType", fileConfigDTO.getDocumentType());
+ map.put("type", fileConfigDTO.getType());
+ // 2、onlyoffice的 api位置
+ fileConfigDTO.setDocServiceApiUrl(onlyProperties.getDocService() + onlyProperties.getDOC_API_URL());
+
+ // ==========用户============
+ FileUser user = getUser();
+ // ========文档类型=============
+ String typePart = FileUtil.getFileExtension(fileName);
+ DocumentConfig fileDocument = DocumentConfig.builder()
+ // 文件名
+ .title(fileName)
+ // 扩展名
+ .fileType(typePart)
+ // 可访问的url
+ .url(fileUrl)
+ // 唯一有标示符
+ .key(key).info(getDocumentInfo(user)).permissions(buildPermission(mode)).build();
+ fileConfigDTO.setDocument(fileDocument);
+ map.put("document", fileDocument);
+ // ==========编辑配置===============
+ String callBackUrl = onlyProperties.getLocalhostAddress() + onlyProperties.getCallBackUrl();
+
+ EditorConfig editorConfig = new EditorConfig(callBackUrl, mode);
+ editorConfig.setFileCustomization(getFileCustomization(mode));
+ editorConfig.setFileUser(user);
+ editorConfig.setPlugins(getPlugins());
+
+
+ fileConfigDTO.setEditorConfig(editorConfig);
+ map.put("editorConfig", editorConfig);
+
+
+ if (null != onlyProperties.getSecret()) {
+ String token = JWTUtil.createToken(map, onlyProperties.getSecret());
+ fileConfigDTO.setToken(token);
+ }
+
+ return fileConfigDTO;
+ }
+
+
+ private DocumentInfo getDocumentInfo(FileUser user) {
+ SharingSettings sharingSettings = new SharingSettings();
+ sharingSettings.setPermissions(new String[]{"Full Access"});
+ sharingSettings.setUser(user.getName());
+ sharingSettings.setIsLink(true);
+ DocumentInfo info = DocumentInfo.builder().created(DateUtil.formatDateTime(new Date())).sharingSettings(Collections.singletonList(sharingSettings)).build();
+ return info;
+ }
+
+ private DocumentPermission buildPermission(String mode) {
+ if (mode.equals("view")) {
+ return LoadConfigUtil.getViewPermission();
+ }
+ return LoadConfigUtil.getEditPermission();
+ }
+
+ private FileCustomization getFileCustomization() {
+ return LoadConfigUtil.getCustomization();
+ }
+
+ private FileCustomization getFileCustomization(String mode) {
+ FileCustomization customization = LoadConfigUtil.getCustomization();
+ if (mode != null && !(mode.trim()).equals("") && mode.equals("edit")) {
+ customization.setAutosave(true);
+ }
+ return customization;
+ }
+
+ private Plugins getPlugins() {
+ return LoadConfigUtil.getPlugins();
+ }
+
+
+ private FileUser getUser() {
+ FileUser fileUser = SecurityUtils.getUserSession();
+ return fileUser;
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/FileHandler.java b/src/main/java/com/oo/onlyoffice/core/FileHandler.java
new file mode 100644
index 0000000..7749fc1
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/FileHandler.java
@@ -0,0 +1,50 @@
+package com.oo.onlyoffice.core;
+
+
+
+import com.oo.onlyoffice.core.context.FileMetadata;
+
+import java.util.Map;
+import java.util.Optional;
+
+
+public interface FileHandler {
+ /**
+ * 处理名称
+ *
+ * @return 名称
+ */
+ String getHandlerName();
+
+
+ /**
+ *
+ * @param map{
+ * 必填 fileId
+ * 必填 fileName
+ * 必填 fileType
+ * 必填 fileSize
+ * 可用携带其它值
+ * }
+ * @param collaborativeEditing
+ * @return
+ * @throws Exception
+ */
+ FileMetadata handlerFile(Map map, boolean collaborativeEditing) throws Exception;
+
+
+
+ /**
+ * 移除临时文件信息
+ *
+ * @param key key
+ */
+ void removeTempFile(String key);
+
+ /**
+ * 获取临时文件信息
+ *
+ * @param key key
+ */
+ Optional getTempFile(String key);
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/OnlyOfficeConfigFactory.java b/src/main/java/com/oo/onlyoffice/core/OnlyOfficeConfigFactory.java
new file mode 100644
index 0000000..8abca60
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/OnlyOfficeConfigFactory.java
@@ -0,0 +1,18 @@
+package com.oo.onlyoffice.core;
+
+
+import com.oo.onlyoffice.vo.FileConfig;
+
+public interface OnlyOfficeConfigFactory {
+
+
+ /**
+ * 文件初始化onlyOffice必须信息
+ *
+ * @param fileUrl 文件地址
+ * @param key 文件唯一标识
+ * @param fileName 文件名称
+ * @return onlyOffice必须信息
+ */
+ FileConfig buildInitConfig(String fileUrl, String mode, String key, String fileName);
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/SaveFileProcessor.java b/src/main/java/com/oo/onlyoffice/core/SaveFileProcessor.java
new file mode 100644
index 0000000..a39c2ca
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/SaveFileProcessor.java
@@ -0,0 +1,35 @@
+package com.oo.onlyoffice.core;
+
+import java.util.Map;
+
+/**
+ * 保存文件处理执行的方法
+ */
+public interface SaveFileProcessor {
+ /**
+ * 保存文件前进行自定义处理
+ * @param bytes
+ * @param fileExtension 文件后缀
+ * @return
+ * @throws Exception
+ */
+ void saveBeforeInitialization(Map map,byte[] bytes,String fileExtension) throws Exception;
+
+ /**
+ *
+ * @param map 文件元信息
+ * @param file 文件
+ * @param changes 文件变动信息
+ * @return 返回新的文件信息
+ */
+ Map save(Map map,byte[] file, byte[] changes,String key);
+
+ /**
+ * 保存文件后进行自定义处理
+ * @param bytes
+ * @param fileExtension 文件后缀
+ * @return
+ * @throws Exception
+ */
+ void saveAfterInitialization(Map map,byte[] bytes,String fileExtension) throws Exception;
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/cache/InsideCache.java b/src/main/java/com/oo/onlyoffice/core/cache/InsideCache.java
new file mode 100644
index 0000000..9dde328
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/cache/InsideCache.java
@@ -0,0 +1,64 @@
+package com.oo.onlyoffice.core.cache;
+
+import cn.hutool.cache.CacheUtil;
+import cn.hutool.cache.impl.TimedCache;
+import com.oo.onlyoffice.core.Cache;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * @BelongsProject: onlyoffice-demo
+ * @BelongsPackage: com.oo.onlyoffice.tools
+ * @Author: TongHui
+ * @CreateTime: 2023-07-30 17:11
+ * @Description: 内部缓存
+ * @Version: 1.0
+ */
+@Slf4j
+public class InsideCache implements Cache {
+
+ private long timeout = 60;
+
+ //时间单位 秒
+ private long timeUnit = 1000;
+
+ //创建缓存,默认 1分钟 过期
+ private TimedCache cache = CacheUtil.newTimedCache(timeout*timeUnit);
+
+
+ public InsideCache(){
+ cache.schedulePrune(timeout*timeUnit);
+ }
+
+ public Object get(String key){
+ return cache.get(key);
+ }
+
+ public boolean hasKey(String key){
+ return cache.get(key) == null ? false : true;
+ }
+
+ /**
+ *
+ * @param key
+ * @param value
+ * @param time 时间 单位是秒
+ */
+ public void set(String key,Object value,long time){
+ if (time < timeUnit){
+ time = timeout;
+ }
+ log.info("key:{},value:{},size:{}",key,value,cache.size());
+ cache.put(key, value, time*timeUnit);
+ }
+
+ @Override
+ public void set(String key, Object value) {
+ cache.put(key, value);
+ }
+
+ public void remove(String key){
+ cache.remove(key);
+ }
+
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/cache/RedisCache.java b/src/main/java/com/oo/onlyoffice/core/cache/RedisCache.java
new file mode 100644
index 0000000..c7f5bab
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/cache/RedisCache.java
@@ -0,0 +1,66 @@
+package com.oo.onlyoffice.core.cache;
+
+import com.oo.onlyoffice.core.Cache;
+import org.springframework.data.redis.core.RedisTemplate;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @BelongsProject: onlyoffice-demo
+ * @BelongsPackage: com.oo.onlyoffice.core.cache
+ * @Author: TongHui
+ * @CreateTime: 2023-08-01 18:06
+ * @Description: TODO
+ * @Version: 1.0
+ */
+
+public class RedisCache implements Cache {
+
+ private RedisTemplate redisTemplate;
+
+ public RedisCache(RedisTemplate redisTemplate){
+ this.redisTemplate = redisTemplate;
+ }
+
+ @Override
+ public Object get(String key) {
+ return key == null ? null : redisTemplate.opsForValue().get(key);
+ }
+
+ @Override
+ public void set(String key, Object value, long time) {
+ try {
+ if (time > 0) {
+ redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
+ } else {
+ set(key, value);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void set(String key, Object value) {
+ try {
+ redisTemplate.opsForValue().set(key, value);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public boolean hasKey(String key) {
+ try {
+ return redisTemplate.hasKey(key);
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
+ }
+
+ @Override
+ public void remove(String key) {
+ redisTemplate.delete(key);
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/context/FileContext.java b/src/main/java/com/oo/onlyoffice/core/context/FileContext.java
new file mode 100644
index 0000000..33f02ef
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/context/FileContext.java
@@ -0,0 +1,83 @@
+package com.oo.onlyoffice.core.context;
+
+import com.alibaba.fastjson.JSON;
+import com.oo.onlyoffice.core.FileHandler;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 存储文件信息
+ */
+@Component
+public class FileContext {
+
+ public final Map tempMaps = new ConcurrentHashMap<>();
+
+
+
+ public static Map keyUrlInfo = new HashMap<>();
+
+ @Autowired
+ public FileContext(Map tempMap) {
+ this.tempMaps.clear();
+ tempMap.forEach((k, v) -> this.tempMaps.put(v.getHandlerName(), v));
+ }
+
+ /**
+ * 获取对应的执行
+ *
+ * @param handler
+ * @return 结果
+ */
+ public FileHandler getHandler(String handler) {
+ return tempMaps.get(handler);
+ }
+
+ /**
+ * 获取对应的 处理方式
+ *
+ * @param key key
+ * @return 结果
+ */
+ public FileHandler getHandlerByKey(String key) {
+ for (FileHandler tempFileHandler : tempMaps.values()) {
+ FileMetadata tempFileInfo = keyUrlInfo.get(tempFileHandler.getHandlerName() + key);
+ if (Objects.nonNull(tempFileInfo)) {
+ return tempFileHandler;
+ }
+ }
+ return null;
+ }
+
+ public FileMetadata getFileInfo(String key) {
+ for (FileHandler fileHandler : tempMaps.values()) {
+ FileMetadata fileInfo = keyUrlInfo.get(fileHandler.getHandlerName() + key);
+ if (Objects.nonNull(fileInfo)) {
+ return fileInfo;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * 更新文件信息
+ * @param key
+ * @param map
+ */
+ public void updateCacheFileInfo(String key,Map map) {
+ FileHandler fileInfo = getHandlerByKey(key);
+ if (fileInfo != null){
+ System.out.println("更新内存文件信息:"+ JSON.toJSONString(map));
+ FileMetadata fileMetadata = keyUrlInfo.get(fileInfo.getHandlerName() + key);
+
+ fileMetadata.setFileInfo(map);
+ keyUrlInfo.put(fileInfo.getHandlerName() + key, fileMetadata);
+ }
+ }
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/context/FileMetadata.java b/src/main/java/com/oo/onlyoffice/core/context/FileMetadata.java
new file mode 100644
index 0000000..5ff751b
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/context/FileMetadata.java
@@ -0,0 +1,48 @@
+package com.oo.onlyoffice.core.context;
+
+import lombok.Builder;
+import lombok.Data;
+
+import java.util.Map;
+
+
+/**
+ * 文件元数据信息
+ */
+@Data
+@Builder(toBuilder = true)
+public class FileMetadata {
+ /**
+ * 文件可访问的url
+ */
+ private String url;
+ /**
+ * 文件标示符 最大长度为10位
+ */
+ private String key;
+ /**
+ * 文件名称 源文件名
+ */
+ private String oldName;
+
+ private String fileType;
+
+
+ /**
+ * 历史版本路径
+ */
+ private String histVerPath;
+
+
+ /**
+ * 文件信息
+ */
+ private Map fileInfo;
+
+ /**
+ * 打开时间
+ */
+
+ private long openTime;
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/core/enums/DocumentTypeEnum.java b/src/main/java/com/oo/onlyoffice/core/enums/DocumentTypeEnum.java
new file mode 100644
index 0000000..1a59f86
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/enums/DocumentTypeEnum.java
@@ -0,0 +1,10 @@
+package com.oo.onlyoffice.core.enums;
+
+/**
+ * 文件类型
+ */
+public enum DocumentTypeEnum {
+ Word,
+ Cell,
+ Slide
+}
\ No newline at end of file
diff --git a/src/main/java/com/oo/onlyoffice/core/handler/FileHandlerImpl.java b/src/main/java/com/oo/onlyoffice/core/handler/FileHandlerImpl.java
new file mode 100644
index 0000000..2df5dc8
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/core/handler/FileHandlerImpl.java
@@ -0,0 +1,149 @@
+package com.oo.onlyoffice.core.handler;
+
+import cn.hutool.core.util.IdUtil;
+import com.oo.onlyoffice.config.OnlyProperties;
+import com.oo.onlyoffice.core.Cache;
+import com.oo.onlyoffice.core.context.FileContext;
+import com.oo.onlyoffice.core.context.FileMetadata;
+import com.oo.onlyoffice.dto.edit.FileUser;
+import com.oo.onlyoffice.core.FileHandler;
+import com.oo.onlyoffice.tools.SecurityUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+
+import java.util.Date;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * 文件处理方式
+ *
+ * getID_+key 存储的文件id
+ * collaborativeEditing_+文件id 存储的 key 协同编辑使用同一个 key
+ * userID+文件id 存储的 key
+ */
+@Component
+@Slf4j
+public class FileHandlerImpl implements FileHandler {
+
+
+ @Autowired
+ private OnlyProperties onlyProperties;
+ @Autowired
+ private Cache cache;
+
+ private int time = 60*30;
+
+
+
+ @Override
+ public String getHandlerName() {
+ return "onlyOffice-";
+ }
+
+
+ /**
+ * @param map
+ * @param collaborativeEditing
+ * @return
+ * @throws Exception
+ */
+ public FileMetadata handlerFile(Map map, boolean collaborativeEditing) throws Exception {
+
+ try {
+ String id = (String) map.get("fileId");
+
+ log.info("源文件存储的ID" + id);
+ // 唯一标示符
+ /**
+ * 协同编辑时用的同一个key,判断是否协同,是:查找缓存中有无key,否:新生成key
+ * */
+ String key = "";
+ String mode = (String) map.get("mode");
+ if (mode.equals("edit")) { //编辑模式
+ if (collaborativeEditing) {
+ if (cache.get("collaborativeEditing_" + id) != null) {
+ key = (String) cache.get("collaborativeEditing_" + id);
+ } else {
+ key = IdUtil.simpleUUID();
+ cache.set("collaborativeEditing_" + id, key);
+ cache.set("getID_" + key, id);
+ }
+ } else {
+ key = IdUtil.simpleUUID();
+ FileUser user = SecurityUtils.getUserSession();
+ cache.set(user.getId() + "_" + id, key);
+ cache.set("getID_" + key, id);
+ }
+ } else {//查看模式
+ key = id;
+ }
+
+
+ Optional tempFileInfoOptional = this.getTempFile(key);
+ if (tempFileInfoOptional.isPresent()) {
+ return tempFileInfoOptional.get();
+ }
+
+ // 生成临时可访问文件的url
+ String tempUrl = getFileUri(id);
+
+ FileMetadata tempFileInfo = FileMetadata.builder()
+ // 可访问路径
+ .url(tempUrl)
+ // 原来的文件名
+ .oldName((String) map.get("fileName"))
+ .fileType((String) map.get("fileType"))
+ .fileInfo(map)
+ // 唯一标识
+ .key(key)
+ .openTime(new Date().getTime())
+ .build();
+ if (mode.equals("edit")) {
+ FileContext.keyUrlInfo.put(getHandlerName() + key, tempFileInfo);
+ }
+ return tempFileInfo;
+ } catch (Exception e) {
+ log.error("生成临时文件失败", e);
+ throw new Exception(e.getMessage());
+ }
+ }
+
+
+ @Override
+ public void removeTempFile(String key) {
+ Optional tempFileInfo = this.getTempFile(key);
+ if (tempFileInfo.isPresent()) {
+ FileContext.keyUrlInfo.remove(getHandlerName() + key);
+ }
+ }
+
+
+ /**
+ * 判断是否存在临时文件信息
+ *
+ * @param key
+ * @return
+ */
+ public Optional getTempFile(String key) {
+ FileMetadata tempFileInfo = FileContext.keyUrlInfo.get(getHandlerName() + key);
+ return Optional.ofNullable(tempFileInfo);
+ }
+
+
+
+ /**
+ * 获取文件可访问的地址
+ *
+ * @param id
+ * @return 地址
+ */
+ private String getFileUri(String id) {
+ if (onlyProperties.getDownloadFile().endsWith("/")) {
+ return onlyProperties.getDownloadFile() + id ;
+ }
+ return onlyProperties.getDownloadFile() + "/"+ id;
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/DocumentConfig.java b/src/main/java/com/oo/onlyoffice/dto/DocumentConfig.java
new file mode 100644
index 0000000..ba9d546
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/DocumentConfig.java
@@ -0,0 +1,49 @@
+package com.oo.onlyoffice.dto;
+
+import com.oo.onlyoffice.dto.document.DocumentInfo;
+import com.oo.onlyoffice.dto.document.DocumentPermission;
+import lombok.Builder;
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * file文档部分
+ */
+@Data
+@Builder(toBuilder = true)
+public class DocumentConfig implements Serializable {
+ /**
+ * 文件类型 如 docx
+ * 只需要文件的扩展名
+ */
+ private String fileType;
+
+ /**
+ * 文件名称
+ */
+ private String title;
+
+ /**
+ * 文件访问的url
+ */
+ private String url;
+
+ /**
+ * 定义用于服务的文档识别的唯一文档标识符。在发送已知密钥的情况下,文档将从高速缓存中取出。
+ * 每次编辑和保存文档时,必须重新生成密钥。
+ * 文档url可以用作键,但是没有特殊字符,长度限制为20个符号。
+ */
+ private String key;
+
+ /**
+ * 文件作者信息
+ */
+ private DocumentInfo info;
+
+ /**
+ * 权限
+ */
+ private DocumentPermission permissions;
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/EditorConfig.java b/src/main/java/com/oo/onlyoffice/dto/EditorConfig.java
new file mode 100644
index 0000000..5767905
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/EditorConfig.java
@@ -0,0 +1,98 @@
+package com.oo.onlyoffice.dto;
+
+import com.alibaba.fastjson.annotation.JSONField;
+import com.oo.onlyoffice.dto.edit.FileCustomization;
+import com.oo.onlyoffice.dto.edit.FileEmbedded;
+import com.oo.onlyoffice.dto.edit.FileRecent;
+import com.oo.onlyoffice.dto.edit.FileUser;
+import lombok.Data;
+import lombok.experimental.Accessors;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * 编辑配置
+ */
+@Data
+@Accessors(chain = true)
+public class EditorConfig implements Serializable {
+
+ /**
+ * 回调地址
+ * 指定文档存储服务的绝对URL(必须由在自己的服务器上使用ONLYOFFICE Document Server的软件集成器实现)。
+ * 必填*
+ */
+ private String callbackUrl;
+
+ /**
+ * 定义文档创建后的绝对URL,并在创建后可用。如果没有指定,将没有创建按钮
+ */
+ private String createUrl;
+
+
+ /**
+ * 语言
+ * 定义编辑器接口语言(如果存在除英语之外的其他语言)。
+ * 使用两个字母(DE、RU、IT等)或四个字母(EN美国、FR FR等)来设置语言代码。不填默认值是"EN US"。
+ */
+ private String lang = "zh-CN";
+
+
+ /**
+ * 定义编辑器打开模式。
+ * 可以是打开用于查看的文档的视图,也可以是在允许对文档数据应用更改的编辑模式下打开文档的编辑。
+ * 默认值是edit
+ * view 视图
+ * edit 编辑
+ */
+ private String mode;
+
+ /**
+ * 最近打开历史
+ */
+ private List recent;
+
+ /**
+ * 用户信息
+ */
+ private FileUser user;
+
+ /**
+ * 自定义信息
+ */
+ @JSONField(name = "customization")
+ private FileCustomization customization;
+
+ /**
+ *共同编辑
+ */
+ private Object coEditing;
+
+ @JSONField(name = "embedded")
+ private FileEmbedded embedded;
+
+ /**
+ * 请查看官方文档
+ * 自定义插件
+ * https://api.onlyoffice.com/editors/config/editor/plugins
+ */
+ private Plugins plugins;
+
+ public EditorConfig(String callbackUrl) {
+ this.callbackUrl = callbackUrl;
+ }
+ public EditorConfig(String callbackUrl,String mode) {
+ this.callbackUrl = callbackUrl;
+ this.mode = mode;
+ }
+
+ public void setFileCustomization(FileCustomization customization){
+ this.customization = customization;
+ }
+
+
+ public void setFileUser(FileUser user){
+ this.user = user;
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/Plugins.java b/src/main/java/com/oo/onlyoffice/dto/Plugins.java
new file mode 100644
index 0000000..4e5f170
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/Plugins.java
@@ -0,0 +1,24 @@
+package com.oo.onlyoffice.dto;
+
+import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * @BelongsProject: self-study
+ * @BelongsPackage: com.project.dto
+ * @Author: TongHui
+ * @CreateTime: 2022-12-23 16:23
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Slf4j
+@Data
+public class Plugins {
+
+ /** 插件的 guid asc.{4FF5B2DB-BDDA-CC2A-5A36-0087719EB455} */
+ private String[] autostart;
+ /** 插件地址 服务器地址+guid+/config.json 这的guid没有前缀 {4FF5B2DB-BDDA-CC2A-5A36-0087719EB455}*/
+ private String[] pluginsData;
+
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/convert/ConvertBody.java b/src/main/java/com/oo/onlyoffice/dto/convert/ConvertBody.java
new file mode 100644
index 0000000..38f6b4d
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/convert/ConvertBody.java
@@ -0,0 +1,146 @@
+package com.oo.onlyoffice.dto.convert;
+
+import cn.hutool.json.JSONObject;
+import com.oo.onlyoffice.dto.convert.document.DocumentLayout;
+import com.oo.onlyoffice.dto.convert.document.DocumentRenderer;
+import com.oo.onlyoffice.dto.convert.sheet.SpreadsheetLayout;
+import com.oo.onlyoffice.dto.convert.thumbnail.Thumbnail;
+import com.oo.onlyoffice.tools.LoadConfigUtil;
+import lombok.Data;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.dto.convert
+ * @Author: TongHui
+ * @CreateTime: 2022-11-23 09:41
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Data
+public class ConvertBody {
+ /**
+ * 定义转换请求类型:异步或非异步。
+ * 默认值为false。
+ */
+ private Boolean async;
+ /**
+ * 定义从csv或txt格式转换时的文件编码。
+ * 支持的主要值:
+ * 932- 日语 (移位 JIS),
+ * 950-繁体中文(大5),
+ * 1250- 中欧 (视窗),
+ * 1251-西里尔文(视窗),
+ * 65001- 统一码 (UTF-8)。
+ */
+ private Integer codePage;
+ /**
+ * 定义从csv格式转换时用于分隔值的分隔符。
+ * 0- 无分隔符,
+ * 1-标签,
+ * 2-分号,
+ * 3-冒号,
+ * 4-逗号,
+ * 5-空间。
+ */
+ private Integer delimiter;
+
+ /** 必填 文件类型*/
+ private String filetype;
+ /** 必填 文件key*/
+ private String key;
+ /** 必填 输出类型*/
+ private String outputtype;
+ /**密码*/
+ private String password;
+ /**地区 默认值为en-US*/
+ private String region;
+
+ /**定义转换后的文件名。*/
+ private String title;
+
+ /**必填 定义要转换的文档的绝对 URL。*/
+ private String url;
+
+ /**token*/
+ private String token;
+
+ /**文档布局*/
+ private DocumentLayout documentLayout;
+ /**文档渲染器*/
+ private DocumentRenderer documentRenderer;
+ /**表格布局*/
+ private SpreadsheetLayout spreadsheetLayout;
+
+ private Thumbnail thumbnail;
+
+ public ConvertBody(String filetype,String key,String outputtype,String url,String title,String password){
+ this.filetype =filetype;
+ this.key =key;
+ this.outputtype = outputtype;
+ this.password = password;
+ this.url = url;
+ this.title = title;
+ this.region = "zh-CN";
+
+ JSONObject convert = LoadConfigUtil.getConvert();
+ setAsync(convert.getBool("async"));
+ setCodePage(convert.getInt("codePage"));
+ setDelimiter(convert.getInt("delimiter"));
+ setRegion(convert.getStr("region"));
+
+ //判断以下属性是否启用
+ JSONObject documentLayout = convert.getJSONObject("documentLayout");
+ if (documentLayout.getBool("enabled")){
+ setDocumentLayout(convert.get("documentLayout", DocumentLayout.class));
+ }
+
+ JSONObject documentRenderer = convert.getJSONObject("documentRenderer");
+ if (documentRenderer.getBool("enabled")){
+ setDocumentRenderer(convert.get("documentRenderer", DocumentRenderer.class));
+ }
+
+ JSONObject spreadsheetLayout = convert.getJSONObject("spreadsheetLayout");
+ if (spreadsheetLayout.getBool("enabled")){
+ setSpreadsheetLayout(convert.get("spreadsheetLayout", SpreadsheetLayout.class));
+ }
+
+ JSONObject thumbnail = convert.getJSONObject("thumbnail");
+ if (thumbnail.getBool("enabled")){
+ setThumbnail(convert.get("thumbnail",Thumbnail.class));
+ }
+ }
+
+ public void setAsync(Boolean async) {
+ this.async = async;
+ }
+
+ public void setCodePage(Integer codePage) {
+ this.codePage = codePage;
+ }
+
+ public void setDelimiter(Integer delimiter) {
+ this.delimiter = delimiter;
+ }
+
+ public void setRegion(String region) {
+ if (null != region){
+ this.region = region;
+ }
+ }
+
+ public void setDocumentLayout(DocumentLayout documentLayout) {
+ this.documentLayout = documentLayout;
+ }
+
+ public void setDocumentRenderer(DocumentRenderer documentRenderer) {
+ this.documentRenderer = documentRenderer;
+ }
+
+ public void setSpreadsheetLayout(SpreadsheetLayout spreadsheetLayout) {
+ this.spreadsheetLayout = spreadsheetLayout;
+ }
+
+ public void setThumbnail(Thumbnail thumbnail) {
+ this.thumbnail = thumbnail;
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/convert/document/DocumentLayout.java b/src/main/java/com/oo/onlyoffice/dto/convert/document/DocumentLayout.java
new file mode 100644
index 0000000..84c6da5
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/convert/document/DocumentLayout.java
@@ -0,0 +1,27 @@
+package com.oo.onlyoffice.dto.convert.document;
+
+import lombok.Data;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.dto.convert
+ * @Author: TongHui
+ * @CreateTime: 2022-11-23 09:44
+ * @Description: 文档布局
+ * @Version: 1.0
+ */
+@Data
+public class DocumentLayout {
+ /**定义是否绘制占位符。*/
+ private Boolean drawPlaceHolders;
+ /**定义是否突出显示表单。*/
+ private Boolean drawFormHighlight;
+ /***
+ * 定义打印模式是打开还是关闭。
+ * 此参数仅用于将docx/docxf转换为pdf。
+ * 如果此参数等于true,则如上所述使用drawPlaceHolder和drawFormHighlight标志。
+ * 如果此参数为false,则drawFormHighlight标志不起作用,
+ * 并且drawPlaceHolder参数允许以pdf格式保存表单。 默认值为false。
+ */
+ private Boolean isPrint;
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/convert/document/DocumentRenderer.java b/src/main/java/com/oo/onlyoffice/dto/convert/document/DocumentRenderer.java
new file mode 100644
index 0000000..18cd409
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/convert/document/DocumentRenderer.java
@@ -0,0 +1,24 @@
+package com.oo.onlyoffice.dto.convert.document;
+
+import lombok.Data;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.dto.convert
+ * @Author: TongHui
+ * @CreateTime: 2022-11-23 09:46
+ * @Description: 文档渲染器
+ * @Version: 1.0
+ */
+@Data
+public class DocumentRenderer {
+ /***
+ * 定义可以具有以下值的呈现模式:
+ * 块字符(blockChar) - 所有文本都由单个字符转换。 每个字符都在自己的框架中(如文本框),
+ * blockLine- 所有文本都由单独的行转换。 每个文本行都位于其自己的框架中。行可以在同一块内组合,
+ * 纯行(plainLine) - 所有文本都转换为纯文本。 但每一行都是一个单独的段落,
+ * 纯段落(plainParagraph ) - 所有文本都转换为纯文本。 行合并为段落。
+ * 默认值为plainLine。
+ */
+ private String textAssociation;
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/convert/sheet/Margins.java b/src/main/java/com/oo/onlyoffice/dto/convert/sheet/Margins.java
new file mode 100644
index 0000000..175602d
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/convert/sheet/Margins.java
@@ -0,0 +1,25 @@
+package com.oo.onlyoffice.dto.convert.sheet;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.dto.convert.sheet
+ * @Author: TongHui
+ * @CreateTime: 2022-11-23 09:55
+ * @Description: 边距
+ * @Version: 1.0
+ */
+@Data
+@AllArgsConstructor
+public class Margins {
+ /**设置输出 PDF 文件的边距 默认 19.1mm */
+ private String bottom;
+ /** 默认 17.8mm */
+ private String left;
+ /** 默认 17.8mm */
+ private String right;
+ /** 默认 19.1mm */
+ private String top;
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/convert/sheet/PageSize.java b/src/main/java/com/oo/onlyoffice/dto/convert/sheet/PageSize.java
new file mode 100644
index 0000000..698afaf
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/convert/sheet/PageSize.java
@@ -0,0 +1,21 @@
+package com.oo.onlyoffice.dto.convert.sheet;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.dto.convert.sheet
+ * @Author: TongHui
+ * @CreateTime: 2022-11-23 09:58
+ * @Description: 页面大小
+ * @Version: 1.0
+ */
+@Data
+@AllArgsConstructor
+public class PageSize {
+ /** 设置输出 PDF 文件的页面高度。默认 297mm*/
+ private String height;
+ /** 设置输出 PDF 文件的页面宽度。默认 210mm*/
+ private String width;
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/convert/sheet/SpreadsheetLayout.java b/src/main/java/com/oo/onlyoffice/dto/convert/sheet/SpreadsheetLayout.java
new file mode 100644
index 0000000..187f4c8
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/convert/sheet/SpreadsheetLayout.java
@@ -0,0 +1,33 @@
+package com.oo.onlyoffice.dto.convert.sheet;
+
+import lombok.Data;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.dto.convert
+ * @Author: TongHui
+ * @CreateTime: 2022-11-23 09:50
+ * @Description: 电子表格布局
+ * @Version: 1.0
+ */
+@Data
+public class SpreadsheetLayout {
+ /**设置转换区域的高度(以页数为单位)。 默认值为0。*/
+ private Integer fitToHeight;
+ /**设置转换区域的宽度(以页数为单位)。 默认值为0。*/
+ private Integer fitToWidth;
+ /**允许是否在输出PDF文件中包含网格线。 默认值为false。*/
+ private Boolean gridLines;
+ /**允许是否包含输出PDF文件的标题。 默认值为false。*/
+ private Boolean headings;
+ /**确定是否忽略为电子表格文件选择的打印区域。 默认值为true。*/
+ private Boolean ignorePrintArea;
+
+ private Margins margins;
+ /**设置输出 PDF 文件的方向。 可能是landscape, portrait. 默认值为纵向(portrait)。*/
+ private String orientation;
+
+ private PageSize pageSize;
+ /**允许设置输出PDF文件的比例。 默认值为100。*/
+ private Integer scale;
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/convert/thumbnail/Thumbnail.java b/src/main/java/com/oo/onlyoffice/dto/convert/thumbnail/Thumbnail.java
new file mode 100644
index 0000000..720789e
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/convert/thumbnail/Thumbnail.java
@@ -0,0 +1,37 @@
+package com.oo.onlyoffice.dto.convert.thumbnail;
+
+import lombok.Data;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.dto.convert.thumbnail
+ * @Author: TongHui
+ * @CreateTime: 2022-11-23 10:18
+ * @Description: 缩略图 定义将图像格式(bmp,gif,jpg,png)指定为输出类型时缩略图的设置。
+ * @Version: 1.0
+ */
+@Data
+public class Thumbnail {
+ /**
+ * 定义使图像适合指定高度和宽度的模式。 支持的值:
+ * 0-拉伸文件以适合高度和宽度,
+ * 1-保留图像的纵横比,
+ * 2-在这种情况下,不使用宽度和高度设置。 取而代之的是,页面的度量大小将转换为具有 96dpi 的像素。 例如,A4(210x297mm)页面将是一张尺寸为794x1123像素的图片。
+ * 默认值为2。
+ */
+ private Integer aspect;
+ /**
+ * 定义是应仅为第一页生成缩略图,还是应为所有文档页面生成缩略图。
+ * 如果为 false,则将创建包含所有页面缩略图的 zip 存档。
+ * 默认值为true,
+ */
+ private Boolean first;
+ /**
+ * 定义缩略图高度(以像素为单位)。 默认值为100。
+ */
+ private Integer height;
+ /**
+ * 定义缩略图宽度(以像素为单位)。 默认值为100。
+ */
+ private Integer width;
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/document/DocumentInfo.java b/src/main/java/com/oo/onlyoffice/dto/document/DocumentInfo.java
new file mode 100644
index 0000000..6275549
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/document/DocumentInfo.java
@@ -0,0 +1,47 @@
+package com.oo.onlyoffice.dto.document;
+
+import lombok.Builder;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * file文档部分
+ */
+@Data
+@Builder(toBuilder = true)
+public class DocumentInfo implements Serializable {
+
+ /**
+ * 定义收藏夹图标的突出显示状态。 当用户单击该图标时,将调用onMetaChange事件
+ */
+ private String favorite;
+
+ /**
+ * 创建时间(格式化后数据)
+ */
+ private String owner;
+ /**
+ * 创建时间(格式化后数据)
+ */
+ private String created;
+
+ /**
+ * 存储文件夹可以为空
+ */
+ private String folder;
+
+ /**
+ * 分享
+ * Defines the settings which will allow to share the document with other users:
+ * permissions - the access rights for the user with the name above. Can be Full Access, Read Only or Deny Access
+ * type: string
+ * example: "Full Access"
+ * user - the name of the user the document will be shared with
+ * type: string
+ * example: "John Smith".
+ */
+ private List sharingSettings;
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/document/DocumentPermission.java b/src/main/java/com/oo/onlyoffice/dto/document/DocumentPermission.java
new file mode 100644
index 0000000..9cc1315
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/document/DocumentPermission.java
@@ -0,0 +1,116 @@
+package com.oo.onlyoffice.dto.document;
+
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.io.Serializable;
+
+/**
+ * file 权限
+ */
+@Data
+@NoArgsConstructor
+public class DocumentPermission implements Serializable {
+
+ /**
+ * 定义是否在文档中启用聊天功能。 如果聊天权限设置为true,将显示聊天菜单按钮。 默认值为true。
+ * */
+ private Boolean chat;
+
+ /**
+ * 定义文档是否可以被注释。
+ * 在注释权限设置为“true”的情况下,文档侧栏将包含“注释”菜单选项;
+ * 如果该模式参数设置为“编辑”,则文档注释仅可用于文档编辑器。
+ * 默认值与编辑参数的值一致。
+ * 默认为true
+ */
+ private Boolean comment;
+ /***
+ "edit": ["Group2", ""],
+ "remove": [""],
+ "view": "" ,
+ 定义用户可以编辑、删除和/或查看其注释的组。 该对象具有以下参数:
+ 编辑 - 用户可以编辑其他用户的评论,类型:列表,例如:[“Group2”,“”];
+ 删除 - 用户可以删除其他用户的评论,类型:列表,
+ 示例:[];
+ 查看 - 用户可以查看其他用户的评论,类型:列表,
+ [“”]值表示用户可以编辑/删除/查看不属于这些组的人员所做的评论(例如,如果在第三方编辑器中审阅文档)。
+ 如果值为 [],则用户无法编辑/删除/查看任何组所做的注释。
+ 如果编辑、删除和查看参数为“”或未指定,则用户可以查看/编辑/删除任何用户所做的评论。
+ */
+ private Object commentGroups;
+
+ /**
+ * 定义是否可以将内容复制到剪贴板。
+ * 如果参数设置为false,则粘贴内容将仅在当前文档编辑器中可用。 默认值为true。
+ */
+ private Boolean copy;
+
+ /**
+ * 定义用户是否只能删除其注释。 默认值为false。
+ */
+ private Boolean deleteCommentAuthorOnly;
+ /**
+ * 是否允许下载 默认为true
+ */
+ private Boolean download;
+ /**
+ * 是否允许编辑 默认true
+ */
+ private Boolean edit;
+
+ /**
+ * 定义用户是否只能编辑其注释。 默认值为false。
+ */
+ private Boolean editCommentAuthorOnly;
+
+ /**
+ * 是否可以填写表单 默认true
+ * 如果编辑设置为“true”或审阅设置为“true”,则不考虑fillForms值,并且可以填写表单。
+ * 如果编辑设置为“false”,审阅设置为“false”,并且fillForms也设置为“true”,则用户只能在文档中填写表单。
+ * 如果编辑设置为“false”并且审阅设置为“false”并且fillForms设置为“true”则不考虑注释值,并且注释不可用。
+ * 仅表单填写模式目前仅适用于文档编辑器。
+ */
+ private Boolean fillForms;
+ /**
+ * 定义是否可以更改内容控件设置。 仅当mode参数设置为编辑时,内容控件修改才可用于文档编辑器。 默认值为true。
+ */
+ private Boolean modifyContentControl;
+ /**
+ * 定义筛选器是可以全局应用(true)影响所有其他用户,还是本地应用(false),即仅适用于当前用户。
+ * 仅当模式参数设置为编辑时,过滤器修改才可用于电子表格编辑器。 默认值为true。
+ */
+ private Boolean modifyFilter;
+ /**
+ * 定义文档是否可以打印。 如果打印权限设置为“false”打印菜单选项将不在“文件”菜单中。 默认值为true。
+ */
+ private Boolean print;
+ /**
+ * 定义是显示工具栏上的“保护”选项卡和左侧菜单中的“保护”按钮(真)还是隐藏(假)。 默认值为true。
+ */
+ private Boolean protect;
+ /**
+ * 定义文档是否可以被审核。
+ * 如果审阅权限设置为“true”,则文档状态栏将包含审阅菜单选项;
+ * 如果模式参数设置为编辑,则文档审阅将仅对文档编辑器可用。
+ * 默认值与编辑参数的值一致。
+ * 如果编辑设置为“true”并且审阅也设置为“true”,则用户将能够编辑文档,接受/拒绝所做的更改并自己切换到审阅模式。
+ * 如果编辑设置为“true”并且审阅设置为“false”,则用户将只能进行编辑。 如果编辑设置为“false”并且审阅设置为“true”,则文档将仅在审阅模式下可用。
+ * 默认:true
+ */
+ private Boolean review;
+ /**
+ * 定义用户可以接受/拒绝其更改的组。 [“”]值表示用户可以审阅不属于这些组的人员所做的更改(例如,如果在第三方编辑器中审阅文档)。
+ * 如果值为 [],则用户无法查看任何组所做的更改。 如果值为“”或未指定,则用户可以查看任何用户所做的更改。
+ */
+ private String[] reviewGroups;
+ /**
+ * 定义其信息显示在编辑器中的用户组:
+ * 用户名显示在编辑器标题的编辑用户列表中,
+ * 键入文本时,将显示用户光标和工具提示及其名称,
+ * 在严格协同编辑模式下锁定对象时,将显示用户名。
+ * [“组 1”, “”] 表示显示有关组 1 中的用户和不属于任何组的用户的信息。 [] 表示根本不显示任何用户信息。 未定义的或 “” 值表示显示有关所有用户的信息。
+ */
+ private String[] userInfoGroups;
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/document/SharingSettings.java b/src/main/java/com/oo/onlyoffice/dto/document/SharingSettings.java
new file mode 100644
index 0000000..fb4a36e
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/document/SharingSettings.java
@@ -0,0 +1,20 @@
+package com.oo.onlyoffice.dto.document;
+
+import lombok.Data;
+
+/**
+ * @BelongsProject: leaf-onlyoffice
+ * @BelongsPackage: com.ideayp.leaf.onlyoffice.dto.document
+ * @Author: TongHui
+ * @CreateTime: 2022-11-09 13:53
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Data
+public class SharingSettings {
+
+ private Boolean isLink; //将用户图标更改为链接图标
+ private String[] permissions; //完全访问,只读或拒绝访问 Full Access, Read Only , Deny Access
+ private String user; //共享文档的用户的名称
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/edit/FileCustomer.java b/src/main/java/com/oo/onlyoffice/dto/edit/FileCustomer.java
new file mode 100644
index 0000000..a3991d9
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/edit/FileCustomer.java
@@ -0,0 +1,50 @@
+package com.oo.onlyoffice.dto.edit;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+*
+*
+*@Date 2022/11/16
+*@ClassName FileCustomer
+*@Version 1.0
+*/
+@Data
+public class FileCustomer implements Serializable {
+
+ /**
+ * 地址
+ */
+ private String address;
+
+ /**
+ * 介绍信息
+ */
+ private String info;
+
+ /**
+ * logo地址
+ * 将显示在“关于”页上的图像标志的路径(该文件没有特别推荐,但如果是具有透明背景的.png格式会更好)。
+ * 图像必须具有以下尺寸:432×70
+ */
+ private String logo;
+
+ /**
+ * 联系邮箱
+ */
+ private String mail;
+
+ /**
+ * 名称
+ */
+ private String name;
+
+ /**
+ * 网址
+ */
+ private String www;
+
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/edit/FileCustomization.java b/src/main/java/com/oo/onlyoffice/dto/edit/FileCustomization.java
new file mode 100644
index 0000000..06ae79c
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/edit/FileCustomization.java
@@ -0,0 +1,208 @@
+package com.oo.onlyoffice.dto.edit;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+*
+*
+*@Date 2022/11/16
+*@ClassName FileCustomization
+*@Version 1.0
+*/
+@Data
+public class FileCustomization implements Serializable {
+
+ /**
+ * {
+ * "request": true,
+ * "label": "Guest"
+ * },
+ * 添加对匿名名称的请求:
+ * 请求 - 定义请求是否发送。 默认值为 true,类型:布尔值,
+ * 标签 - 添加到用户名的后缀。 默认值为来宾,类型:字符串,
+ */
+ private Object anonymous;
+
+ /**
+ * 定义是否启用或禁用“自动保存”菜单选项。
+ * 如果设置为false,则只能选择Strict协同编辑模式,因为Fast在没有自动保存的情况下无法工作。
+ * 请注意,如果您在菜单中更改此选项,它将保存到您的浏览器localStorage。默认值为true
+ */
+ private Boolean autosave;
+
+ /**
+ 定义是显示还是隐藏“注释”菜单按钮。
+ 请注意,如果您隐藏了“评论”按钮,则相应的评论功能将仅供查看,添加和编辑评论将不可用。 默认值为true。
+ */
+ private Boolean comments;
+ /**
+ * 定义其他操作按钮是显示在编辑器窗口标题的上部徽标旁边 (false) 还是显示在工具栏 (true) 中,从而使标题更紧凑。 默认值为false。
+ */
+ private Boolean compactHeader;
+ /**
+ * 定义显示的顶部工具栏类型是完整 (假) 还是紧凑 (真)。 默认值为false。
+ */
+ private Boolean compactToolbar;
+ /**
+ * 定义仅与 OOXML 格式兼容的功能的使用。 例如,不要对整个文档使用注释。 默认值为false。
+ */
+ private Boolean compatibleFeatures;
+ /**
+ * "address": "My City, 123a-45",有权访问编辑或编辑作者的公司或个人的邮政地址
+ * "info": "Some additional information",有关您希望其他人认识的公司或个人的一些其他信息,
+ * "logo": "https://example.com/logo-big.png",图片徽标的路径
+ * "logoDark": "https://example.com/dark-logo-big.png",深色主题的图像徽标的路径
+ * "mail": "john@example.com",有权访问编辑者或编辑者的公司或个人的电子邮件地址
+ * "name": "John Smith and Co.",名称
+ * "phone": "123456789",电话
+ * "www": "example.com"以上公司或个人的家庭网站地址
+ */
+ private Object customer;
+ /**
+ * {"spellcheck": true}
+ * 定义用户可以禁用或自定义的参数(如果可能):
+ * 拼写检查 - 定义在加载编辑器时是自动打开还是关闭拼写检查器。 如果此参数是布尔值,则将其设置为初始拼写检查器值,并且不会隐藏拼写检查器设置。
+ * 默认值为 true,类型:对象或布尔值,
+ * {"spellcheck": {"mode": true}}
+ * 拼写检查模式 - 定义在加载编辑器时拼写检查器是自动打开还是关闭。
+ * 此参数仅适用于文档编辑器和演示文稿编辑器,类型:布尔值,
+ * 示例:true;
+ */
+ private Object features;
+ /**
+ * {"url": "https://example.com",
+ * "visible": true}
+ * 定义“反馈和支持”菜单按钮的设置。
+ * 可以是布尔值(仅显示或隐藏“反馈和支持”菜单按钮)或对象。
+ */
+ private Object feedback;
+ /**在文档编辑服务中保存文档时(例如,单击“保存”按钮等),
+ * 将文件强制保存的请求添加到回调处理程序中。 默认值为false。*/
+ private Boolean forcesave;
+
+ /**
+ * {
+ * "blank": true,
+ * "requestClose": false,
+ * "text": "Open file location",
+ * "url": "https://example.com"
+ * }
+ * 定义“打开文件位置”菜单按钮和右上角按钮的设置。 该对象具有以下参数:
+ * 空白 - 单击“打开文件位置”按钮时,在新的浏览器选项卡/窗口中打开网站(如果值设置为true)或当前选项卡(如果值设置为false)。
+ * 默认值为 true,类型:布尔值,
+
+ * requestClose- 定义如果单击“打开文件位置”按钮,则会调用 events.onRequestClose事件,而不是打开浏览器选项卡或窗口。
+ * 默认值为假,类型:布尔值,
+ *
+
+ * text-将为“打开文件位置”菜单按钮和右上角按钮(即而不是“转到文档”)显示的文本,键入:字符串,
+
+ * url-单击“打开文件位置”菜单按钮时将打开的网站地址的绝对URL,键入:字符串,
+ *
+ */
+ private Object goback;
+ /**
+ * 定义是显示还是隐藏“帮助”菜单按钮。 默认值为true。
+ */
+ private Boolean help;
+ /**
+ * 定义在首次加载时是显示还是隐藏注释面板。 默认值为false。此参数仅适用于演示文稿编辑器ppt。
+ */
+ private Boolean hideNotes;
+ /**
+ * 定义首次加载时是显示还是隐藏右侧菜单。 默认值为false。
+ */
+ private Boolean hideRightMenu;
+ /**
+ * 定义是显示还是隐藏编辑器标尺。 此参数可用于文档和演示文稿编辑器。文档编辑器的默认值为false,演示文稿的默认值为true。
+ */
+ private Boolean hideRulers;
+
+ /**
+ * 定义将编辑器嵌入网页的模式。 嵌入值在加载编辑器框架时禁用滚动到编辑器框架,因为未捕获焦点。
+ */
+ private String integrationMode;
+
+ /**
+ * "image": "https://example.com/logo.png",
+ * "imageDark": "https://example.com/dark-logo.png",
+ * "url": "https://www.onlyoffice.com"
+ * 更改编辑器标题左上角的图像文件。 建议的图像高度为 20 像素。 该对象具有以下参数:
+ * image- 用于在通用工作模式(即所有编辑器的查看和编辑模式下)或嵌入模式下显示的图像文件的路径(请参阅配置部分以了解如何定义嵌入式文档类型)。
+ * 图像必须具有以下大小:172x40,类型:字符串,
+ *
+ * imageDark - 用于深色主题的图像文件的路径。 图像必须具有以下大小:172x40,类型:字符串,
+ *
+ * url - 当有人点击徽标图像时将使用的绝对URL(可用于访问您的网站等)。
+ * 保留为空字符串或null以使徽标不可点击,键入:字符串,
+ */
+ private Object logo;
+
+ /**
+ * 定义在编辑器打开时是否自动运行文档宏。 默认值为true。false值对用户隐藏宏设置。
+ */
+ private Boolean macros;
+ /**
+ * disable
+ * enable
+ * warn 默认
+ */
+ private String macrosMode;
+ /**
+ *定义在注释中提及后描述事件的提示。
+ * 如果为 true,则提示指示用户将收到通知并访问文档。
+ * 如果为 false,则提示指示用户将仅收到提及通知。 默认值为true。
+ * 请注意,只有在设置了onRequestSendNotify事件的情况下,它才可用于注释。
+ */
+ private Boolean mentionShare;
+ /**
+ * 定义插件是否启动并可用。 默认值为true。
+ */
+ private Boolean plugins;
+
+ /**
+ * "hideReviewDisplay": false, 定义在“协作”选项卡上显示还是隐藏“显示模式”按钮。 默认值为假,类型:布尔值,
+ * "hoverMode": false 定义审阅显示模式:通过悬停更改在工具提示中显示审阅 (true) 或通过单击更改(假)在气球中。 默认值为false。
+ */
+ private Object review;
+
+ /**
+ * 定义文档标题是在顶部工具栏上可见 (假) 还是隐藏 (真)。 默认值为false。
+ */
+ private Boolean toolbarHideFileName;
+
+ /**
+ * 定义顶部工具栏选项卡是清晰显示 (false) 还是仅突出显示以查看选择了哪个选项卡 (true)。 默认值为false。
+ */
+ private Boolean toolbarNoTabs;
+
+ /**
+ *定义编辑器主题设置。 可以通过两种方式进行设置:
+ * 主题 ID - 用户通过其 ID 设置主题参数(主题-浅色、主题-经典-浅色、主题-深色、主题-对比度-深),
+ * 默认主题 - 将设置默认的深色或浅色主题值(默认深色,默认浅色)。 默认浅色主题为主题经典浅色。
+ * 第一个选项具有更高的优先级。除了可用的编辑器主题外,用户还可以为应用程序界面自定义自己的颜色主题。
+ * 颜色可以以十六进制或 RGBA 格式呈现。
+ */
+ private String uiTheme;
+
+ /**
+ * 定义标尺和对话框中使用的度量单位。 可以采用以下值:
+ * 厘米,
+ * pt-点,
+ * 英寸 - 英寸。
+ * 默认值为厘米 (cm)。
+ */
+ private String unit;
+
+ /**
+ * 定义以百分比度量的文档显示缩放值。 可以采用大于0 的值。
+ * 对于文本文档和演示文稿,可以将此参数设置为 -1(使文档适合页面选项)或 to-2(使文档页面宽度适合编辑器页面)。
+ * 默认值为100。
+ */
+ private Integer zoom;
+
+
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/edit/FileEmbedded.java b/src/main/java/com/oo/onlyoffice/dto/edit/FileEmbedded.java
new file mode 100644
index 0000000..8d79d9a
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/edit/FileEmbedded.java
@@ -0,0 +1,41 @@
+package com.oo.onlyoffice.dto.edit;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * 当type =embedded 生效
+ */
+@Data
+public class FileEmbedded implements Serializable {
+
+ /**
+ * 文件url
+ * "https://example.com/embedded?doc=exampledocument1.docx"
+ */
+ private String embedUrl="https://example.com/embedded?doc=exampledocument1.docx";
+
+ /**
+ * "https://example.com/embedded?doc=exampledocument1.docx#fullscreen"
+ */
+ private String fullscreenUrl="https://example.com/embedded?doc=exampledocument1.docx";
+
+ /**
+ * 保存的url
+ * "https://example.com/download?doc=exampledocument1.docx"
+ */
+ private String saveUrl;
+
+ /**
+ * "https://example.com/view?doc=exampledocument1.docx"
+ */
+ private String shareUrl;
+
+ /**
+ * 定义嵌入式浏览器工具栏的位置,可以是顶部或底部
+ * 默认top
+ * bottom/top
+ */
+ private String toolbarDocked;
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/edit/FileRecent.java b/src/main/java/com/oo/onlyoffice/dto/edit/FileRecent.java
new file mode 100644
index 0000000..4833c32
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/edit/FileRecent.java
@@ -0,0 +1,28 @@
+package com.oo.onlyoffice.dto.edit;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * 最近打开
+ */
+@Data
+public class FileRecent implements Serializable {
+
+ /**
+ * 文件夹
+ */
+ private String folder;
+
+ /**
+ * 名称
+ */
+ private String title;
+
+ /**
+ * url 绝对路径
+ */
+ private String url;
+
+}
diff --git a/src/main/java/com/oo/onlyoffice/dto/edit/FileUser.java b/src/main/java/com/oo/onlyoffice/dto/edit/FileUser.java
new file mode 100644
index 0000000..7eb0a38
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/dto/edit/FileUser.java
@@ -0,0 +1,27 @@
+package com.oo.onlyoffice.dto.edit;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * 使用文件的用户信息
+ */
+@Data
+public class FileUser implements Serializable {
+
+ /**
+ * 用户唯一标识
+ */
+ private String id;
+
+ /**
+ * 用户 全称
+ */
+ private String name;
+
+ /**
+ * 组
+ */
+ private String[] group;
+}
diff --git a/src/main/java/com/oo/onlyoffice/tools/DocumentKey.java b/src/main/java/com/oo/onlyoffice/tools/DocumentKey.java
new file mode 100644
index 0000000..74c86f8
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/tools/DocumentKey.java
@@ -0,0 +1,60 @@
+package com.oo.onlyoffice.tools;
+
+import cn.hutool.core.lang.Snowflake;
+import cn.hutool.core.net.NetUtil;
+import cn.hutool.core.util.IdUtil;
+
+import java.util.Calendar;
+import java.util.Random;
+
+/**
+ * @BelongsProject: office-demo
+ * @BelongsPackage: com.doc.utils
+ * @Author: TongHui
+ * @CreateTime: 2022-11-04 18:25
+ * @Description: 生成ID
+ * @Version: 1.0
+ */
+
+public class DocumentKey {
+
+ private static Snowflake snowflake;
+
+ static {
+ // 0 ~ 31 位,可以采用配置的方式使用
+ long workerId;
+ try {
+ workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
+ } catch (Exception e) {
+ workerId = NetUtil.getLocalhostStr().hashCode();
+ }
+
+ workerId = workerId >> 16 & 31;
+
+ long dataCenterId = 1L;
+ snowflake = IdUtil.createSnowflake(workerId,dataCenterId);
+ }
+
+ public static String SnowflakeId() {
+ return String.valueOf(snowflake.nextId());
+ }
+
+ public static String ShortCode() {
+ Calendar calendar = Calendar.getInstance();
+ int year = calendar.get(Calendar.YEAR);
+ int week = calendar.get(Calendar.WEEK_OF_YEAR);
+ int day = calendar.get(Calendar.DAY_OF_WEEK);
+ int hour = calendar.get(Calendar.HOUR_OF_DAY);
+
+ // 打乱排序:2020年为准 + 小时 + 周期 + 日 + 三位随机数
+ StringBuilder idStr = new StringBuilder();
+ idStr.append(year-2020);
+ idStr.append(hour);
+ //(“%04d”, 99) 0099
+ idStr.append(String.format("%02d",week));
+ idStr.append(day);
+ idStr.append(String.format("%03d",new Random().nextInt(1000)));
+
+ return idStr.toString();
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/tools/FileUtil.java b/src/main/java/com/oo/onlyoffice/tools/FileUtil.java
new file mode 100644
index 0000000..ea7f7e6
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/tools/FileUtil.java
@@ -0,0 +1,388 @@
+package com.oo.onlyoffice.tools;
+
+
+import cn.hutool.core.io.IoUtil;
+import cn.hutool.core.io.file.FileNameUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URL;
+import java.net.URLEncoder;
+
+
+/**
+ * @BelongsProject: onlyoffice-demo
+ * @BelongsPackage: com.oo.onlyoffice.tools
+ * @Author: TongHui
+ * @CreateTime: 2023-07-30 17:26
+ * @Description: 文件操作
+ * @Version: 1.0
+ */
+@Slf4j
+public class FileUtil {
+
+ private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
+
+ static String COMMA = ".";
+
+ /**
+ * 获取文件后缀 不带.
+ * @param name
+ * @return
+ */
+ public static String getFileExtension(String name){
+ return FileNameUtil.extName(name);
+ }
+
+ /**
+ * 读取远程文件
+ * @param url
+ * @return
+ */
+ public static byte[] getFileByte(String url){
+ try (InputStream in = new URL(url).openConnection().getInputStream()){
+ return IoUtil.readBytes(in);
+ }catch (IOException e){
+ log.error("读取失败:" + e.getMessage());
+ }
+ return new byte[0];
+ }
+
+ /**
+ * 流 转字符串
+ * @param stream
+ * @return
+ * @throws IOException
+ */
+ public static String ConvertStreamToString(InputStream stream) throws IOException {
+ InputStreamReader inputStreamReader = new InputStreamReader(stream);
+ StringBuilder stringBuilder = new StringBuilder();
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
+ String line = bufferedReader.readLine();
+
+ while (line != null) {
+ stringBuilder.append(line);
+ line = bufferedReader.readLine();
+ }
+
+ String result = stringBuilder.toString();
+
+ return result;
+ }
+
+ public static InputStream openInputStream(File file){
+ return IoUtil.toStream(file);
+ }
+
+ // 一般oo服务回调下载
+ public static void downloadInline(File file,String name,HttpServletResponse response){
+ try {
+ byte[] buffer = null;
+ // 将文件写入输入流
+ FileInputStream fileInputStream = new FileInputStream(file);
+ InputStream fis = new BufferedInputStream(fileInputStream);
+ buffer = new byte[fis.available()];
+ fis.read(buffer);
+ fis.close();
+ dowInline(buffer, name, response);
+ }catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+ public static void downloadInline(String path,String name,HttpServletResponse response){
+ logger.info("文件下载:"+path);
+ byte[] buffer = null;
+ try {
+ if (path.startsWith("http")){
+ buffer = getFileByte(path);
+ dowInline(buffer,name,response);
+ }else {
+ // path是指想要下载的文件的路径
+ File file = new File(path);
+
+ downloadInline(file,name,response);
+ }
+ }catch (Exception e){
+ e.printStackTrace();
+ }
+
+ }
+ public static void downloadInline(byte[] bytes,String name,HttpServletResponse response){
+ logger.info("文件下载:"+name);
+ dowInline(bytes,name,response);
+ }
+
+
+ //以附件形式下载 浏览器下载使用
+ public static void downloadAttachment(File file,String name,HttpServletResponse response){
+ try {
+ byte[] buffer = null;
+ // 将文件写入输入流
+ FileInputStream fileInputStream = new FileInputStream(file);
+ InputStream fis = new BufferedInputStream(fileInputStream);
+ buffer = new byte[fis.available()];
+ fis.read(buffer);
+ fis.close();
+ attachment(buffer, name, response);
+ }catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+ public static void downloadAttachment(String path,String name,HttpServletResponse response){
+ logger.info("文件下载:"+path);
+ byte[] buffer = null;
+ try {
+ if (path.startsWith("http")){
+ buffer = getFileByte(path);
+ downloadAttachment(buffer,name,response);
+ }else {
+ // path是指想要下载的文件的路径
+ File file = new File(path);
+
+ downloadAttachment(file,name,response);
+ }
+ }catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+ public static void downloadAttachment(byte[] bytes,String name,HttpServletResponse response){
+ attachment(bytes,name,response);
+ }
+
+ private static void attachment(byte[] bytes,String name, HttpServletResponse response){
+ try {
+ // 清空response
+ response.reset();
+ // 设置response的Header
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType(getContentType(name));
+ //Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
+ //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
+ // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
+ response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
+ // 告知浏览器文件的大小
+ response.addHeader("Content-Length", "" + bytes.length);
+ OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
+ outputStream.write(bytes);
+ outputStream.flush();
+ outputStream.close();
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+ }
+ private static void dowInline(byte[] bytes,String name, HttpServletResponse response){
+ try {
+ // 清空response
+ response.reset();
+ // 设置response的Header
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType(getContentType(name));
+ //Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
+ //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
+ // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
+ response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(name, "UTF-8"));
+ // 告知浏览器文件的大小
+ response.addHeader("Content-Length", "" + bytes.length);
+ OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
+ outputStream.write(bytes);
+ outputStream.flush();
+ outputStream.close();
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ /**
+ * 根据“文件名的后缀”获取文件内容类型(而非根据File.getContentType()读取的文件类型)
+ *
+ * @param returnFileName 带验证的文件名
+ * @return 返回文件类型
+ */
+ public static String getContentType(String returnFileName) {
+ String contentType = "application/octet-stream";
+ if (returnFileName.lastIndexOf(COMMA) < 0) {
+ return contentType;
+ }
+ returnFileName = returnFileName.toLowerCase();
+ returnFileName = returnFileName.substring(returnFileName.lastIndexOf(".") + 1);
+ switch (returnFileName) {
+ case "html":
+ case "htm":
+ case "shtml":
+ contentType = "text/html";
+ break;
+ case "apk":
+ contentType = "application/vnd.android.package-archive";
+ break;
+ case "sis":
+ contentType = "application/vnd.symbian.install";
+ break;
+ case "sisx":
+ contentType = "application/vnd.symbian.install";
+ break;
+ case "exe":
+ contentType = "application/x-msdownload";
+ break;
+ case "msi":
+ contentType = "application/x-msdownload";
+ break;
+ case "css":
+ contentType = "text/css";
+ break;
+ case "xml":
+ contentType = "text/xml";
+ break;
+ case "gif":
+ contentType = "image/gif";
+ break;
+ case "jpeg":
+ case "jpg":
+ contentType = "image/jpeg";
+ break;
+ case "js":
+ contentType = "application/x-javascript";
+ break;
+ case "atom":
+ contentType = "application/atom+xml";
+ break;
+ case "rss":
+ contentType = "application/rss+xml";
+ break;
+ case "mml":
+ contentType = "text/mathml";
+ break;
+ case "txt":
+ contentType = "text/plain";
+ break;
+ case "jad":
+ contentType = "text/vnd.sun.j2me.app-descriptor";
+ break;
+ case "wml":
+ contentType = "text/vnd.wap.wml";
+ break;
+ case "htc":
+ contentType = "text/x-component";
+ break;
+ case "png":
+ contentType = "image/png";
+ break;
+ case "tif":
+ case "tiff":
+ contentType = "image/tiff";
+ break;
+ case "wbmp":
+ contentType = "image/vnd.wap.wbmp";
+ break;
+ case "ico":
+ contentType = "image/x-icon";
+ break;
+ case "jng":
+ contentType = "image/x-jng";
+ break;
+ case "bmp":
+ contentType = "image/x-ms-bmp";
+ break;
+ case "svg":
+ contentType = "image/svg+xml";
+ break;
+ case "jar":
+ case "var":
+ case "ear":
+ contentType = "application/java-archive";
+ break;
+ case "doc":
+ contentType = "application/msword";
+ break;
+ case "pdf":
+ contentType = "application/pdf";
+ break;
+ case "rtf":
+ contentType = "application/rtf";
+ break;
+ case "xls":
+ contentType = "application/vnd.ms-excel";
+ break;
+ case "ppt":
+ contentType = "application/vnd.ms-powerpoint";
+ break;
+ case "7z":
+ contentType = "application/x-7z-compressed";
+ break;
+ case "rar":
+ contentType = "application/x-rar-compressed";
+ break;
+ case "swf":
+ contentType = "application/x-shockwave-flash";
+ break;
+ case "rpm":
+ contentType = "application/x-redhat-package-manager";
+ break;
+ case "der":
+ case "pem":
+ case "crt":
+ contentType = "application/x-x509-ca-cert";
+ break;
+ case "xhtml":
+ contentType = "application/xhtml+xml";
+ break;
+ case "zip":
+ contentType = "application/zip";
+ break;
+ case "mid":
+ case "midi":
+ case "kar":
+ contentType = "audio/midi";
+ break;
+ case "mp3":
+ contentType = "audio/mpeg";
+ break;
+ case "ogg":
+ contentType = "audio/ogg";
+ break;
+ case "m4a":
+ contentType = "audio/x-m4a";
+ break;
+ case "ra":
+ contentType = "audio/x-realaudio";
+ break;
+ case "3gpp":
+ case "3gp":
+ contentType = "video/3gpp";
+ break;
+ case "mp4":
+ contentType = "video/mp4";
+ break;
+ case "mpeg":
+ case "mpg":
+ contentType = "video/mpeg";
+ break;
+ case "mov":
+ contentType = "video/quicktime";
+ break;
+ case "flv":
+ contentType = "video/x-flv";
+ break;
+ case "m4v":
+ contentType = "video/x-m4v";
+ break;
+ case "mng":
+ contentType = "video/x-mng";
+ break;
+ case "asx":
+ case "asf":
+ contentType = "video/x-ms-asf";
+ break;
+ case "wmv":
+ contentType = "video/x-ms-wmv";
+ break;
+ case "avi":
+ contentType = "video/x-msvideo";
+ break;
+ default:
+ }
+ return contentType;
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/tools/JWTUtil.java b/src/main/java/com/oo/onlyoffice/tools/JWTUtil.java
new file mode 100644
index 0000000..24caa8c
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/tools/JWTUtil.java
@@ -0,0 +1,32 @@
+package com.oo.onlyoffice.tools;
+
+import org.primeframework.jwt.Signer;
+import org.primeframework.jwt.domain.JWT;
+import org.primeframework.jwt.hmac.HMACSigner;
+
+import java.util.Map;
+
+
+/**
+ * @BelongsProject: onlyoffice-demo
+ * @BelongsPackage: com.oo.onlyoffice.tools
+ * @Author: TongHui
+ * @CreateTime: 2023-07-30 18:39
+ * @Description: TODO
+ * @Version: 1.0
+ */
+public class JWTUtil {
+
+ public static String createToken(Map map,String secret){
+ try {
+ Signer signer = HMACSigner.newSHA256Signer(secret);
+ JWT jwt = new JWT();
+ for (String key : map.keySet()) {
+ jwt.addClaim(key, map.get(key));
+ }
+ return JWT.getEncoder().encode(jwt, signer);
+ } catch (Exception e) {
+ return "";
+ }
+ }
+}
diff --git a/src/main/java/com/oo/onlyoffice/tools/LoadConfigUtil.java b/src/main/java/com/oo/onlyoffice/tools/LoadConfigUtil.java
new file mode 100644
index 0000000..956d954
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/tools/LoadConfigUtil.java
@@ -0,0 +1,111 @@
+package com.oo.onlyoffice.tools;
+
+import cn.hutool.json.JSONObject;
+import cn.hutool.json.JSONUtil;
+import com.oo.onlyoffice.dto.Plugins;
+import com.oo.onlyoffice.dto.document.DocumentPermission;
+import com.oo.onlyoffice.dto.edit.FileCustomization;
+import com.oo.onlyoffice.dto.edit.FileEmbedded;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.yaml.snakeyaml.Yaml;
+
+import javax.annotation.PostConstruct;
+import java.io.InputStream;
+import java.util.Iterator;
+
+/**
+ * @BelongsProject: onlyoffice-demo
+ * @BelongsPackage: com.oo.onlyoffice.tools
+ * @Author: TongHui
+ * @CreateTime: 2023-07-30 18:30
+ * @Description: TODO
+ * @Version: 1.0
+ */
+@Slf4j
+public class LoadConfigUtil {
+ private static JSONObject map = new JSONObject();
+ private static DocumentPermission viewPermission = new DocumentPermission();
+ private static DocumentPermission editPermission = new DocumentPermission();
+ private static FileCustomization customization = new FileCustomization();
+ private static FileEmbedded embedded = new FileEmbedded();
+ private static Plugins plugins = new Plugins();
+
+ private static String YML_NAME = "onlyOffice.yml";
+
+ static {
+ loadYml();
+ }
+ private static void loadYml() {
+ log.info("--------加载【onlyOffice.yml】配置文件-------");
+ InputStream inputStream = LoadConfigUtil.class.getClassLoader().getResourceAsStream(YML_NAME);
+ //解析配置文件
+ map = new Yaml().loadAs(inputStream, JSONObject.class);
+ JSONObject oo = map.getJSONObject("oo");
+ JSONObject document = oo.getJSONObject("document");
+ if (null != document || null != document.getJSONObject("permissions")) {
+ JSONObject permissions = document.getJSONObject("permissions");
+ if (null != permissions.getJSONObject("edit")) {
+ editPermission = JSONUtil.toBean(permissions.getJSONObject("edit").toString(), DocumentPermission.class);
+ editPermission.setEdit(true);
+ }
+ if (null != permissions.getJSONObject("view")) {
+ viewPermission = JSONUtil.toBean(permissions.getJSONObject("view").toString(), DocumentPermission.class);
+ viewPermission.setEdit(false);
+ }
+ }
+ JSONObject editor = oo.getJSONObject("editor");
+ if (null != editor) {
+ customization = JSONUtil.toBean(editor.getJSONObject("customization").toString(), FileCustomization.class);
+ }
+
+ JSONObject embeddedJson = editor.getJSONObject("embedded");
+ if (null != embeddedJson) {
+ embedded = JSONUtil.toBean(embeddedJson.toString(), FileEmbedded.class);
+ }
+
+ JSONObject pluginsJson = editor.getJSONObject("plugins");
+ if (null != pluginsJson) {
+ plugins = JSONUtil.toBean(pluginsJson.toString(), Plugins.class);
+ }
+ log.info("--------【onlyOffice.yml】配置文件加载完成-------");
+ }
+
+ public static DocumentPermission getEditPermission() {
+ return editPermission;
+ }
+
+ public static DocumentPermission getViewPermission() {
+ return viewPermission;
+ }
+
+ public static FileCustomization getCustomization() {
+ return customization;
+ }
+
+ public static FileEmbedded getEmbedded() {
+ return embedded;
+ }
+
+ public static Plugins getPlugins() {
+ return plugins;
+ }
+
+ public static JSONObject getConvert() {
+ JSONObject oo = map.getJSONObject("oo");
+ JSONObject convert = oo.getJSONObject("convert");
+ return convert;
+ }
+
+ public static JSONObject getMap() {
+ return map.getJSONObject("oo");
+ }
+
+
+// public static void main(String[] args) {
+//
+// JSONObject convert = LoadConfigUtil.getConvert();
+// System.out.println(convert.toString());
+// }
+}
diff --git a/src/main/java/com/oo/onlyoffice/tools/OnlyOfficeUtil.java b/src/main/java/com/oo/onlyoffice/tools/OnlyOfficeUtil.java
new file mode 100644
index 0000000..de809cc
--- /dev/null
+++ b/src/main/java/com/oo/onlyoffice/tools/OnlyOfficeUtil.java
@@ -0,0 +1,50 @@
+package com.oo.onlyoffice.tools;
+
+
+import com.oo.onlyoffice.core.enums.DocumentTypeEnum;
+import lombok.extern.slf4j.Slf4j;
+
+import java.util.Arrays;
+import java.util.List;
+
+@Slf4j
+public class OnlyOfficeUtil {
+
+
+ /**
+ * 通过文件名获取文件类型
+ *
+ * @param fileName 文件名
+ * @return 结果
+ */
+ public static String getDocumentType(String fileName) {
+ // 获取文件的扩展名
+ String ext = "." + FileUtil.getFileExtension(fileName);
+ if (ExtsDocument.contains(ext)) {
+ return DocumentTypeEnum.Word.toString().toLowerCase();
+ } else if (ExtsSpreadsheet.contains(ext)) {
+ return DocumentTypeEnum.Cell.toString().toLowerCase();
+ } else if (ExtsPresentation.contains(ext)) {
+ return DocumentTypeEnum.Slide.toString().toLowerCase();
+ }
+ return DocumentTypeEnum.Word.toString().toLowerCase();
+ }
+
+ private static List ExtsDocument = Arrays.asList(
+ ".doc", ".docx", ".docm",
+ ".dot", ".dotx", ".dotm",
+ ".odt", ".fodt", ".ott", ".rtf", ".txt",
+ ".html", ".htm", ".mht",
+ ".pdf", ".djvu", ".fb2", ".epub", ".xps");
+
+ private static List ExtsSpreadsheet = Arrays.asList(
+ ".xls", ".xlsx", ".xlsm",
+ ".xlt", ".xltx", ".xltm",
+ ".ods", ".fods", ".ots", ".csv");
+
+ private static List