Compare commits

...

144 Commits

Author SHA1 Message Date
8ae1fd1c55 remove old 2023-06-23 13:54:18 +04:00
b472709542 fix restore changes 2023-06-23 13:00:45 +04:00
38c439c817 ruby-raw: history prelatest 2023-06-22 10:21:44 +04:00
a172afc904 ruby-raw: history restore 2023-06-20 18:15:05 +04:00
0b5692f085 ruby-raw: history next 2023-06-20 17:21:34 +04:00
87cdf95c17 ruby-raw: history done+- 2023-06-20 13:59:41 +04:00
060cc1f0cc ruby-raw: history 2023-06-16 19:59:28 +04:00
321e48bad2 ruby-raw: history 2023-06-15 18:37:52 +04:00
30aaaa2b67 ruby-raw: history, storage 2023-06-14 18:52:15 +04:00
43368fd9fa ruby-raw: restore endpoint 2023-06-14 09:55:07 +04:00
1c5b64bba7 ruby: add receipt stages to build and up containers 2023-06-13 15:23:03 +04:00
df93bbda77 ruby: add containerization 2023-06-13 15:21:03 +04:00
3754bb6b03 ruby: add receipt stages to generate bin files 2023-06-13 14:40:48 +04:00
a51fad84e9 ruby: delete files that should be ignored 2023-06-13 14:39:28 +04:00
1469ce6c0f ruby: move example-specific ignored files to the root of the example 2023-06-13 14:36:23 +04:00
c534989cb3 ruby: remove sqlite3 dependency as it's not used 2023-06-13 14:32:45 +04:00
f57292a3ae ruby: add a recipe to start the server in the Makefile 2023-06-13 14:30:12 +04:00
4961da4c11 ruby: simplify server configuration 2023-06-13 14:29:42 +04:00
c21f87bdb0 ruby: standardize the format of the URIs in the configuration 2023-06-13 10:42:55 +04:00
bd98cd4e54 ruby: support for private network communication 2023-06-11 23:28:24 +04:00
9429e080b2 ruby: support for configuration via environment variables 2023-06-11 23:14:20 +04:00
26a9de9250 ruby: add lint recipe to Makefile 2023-06-09 21:31:27 +04:00
874f551318 ruby: add install recipe to Makefile 2023-06-09 21:31:08 +04:00
5e50db62f2 ruby: add help recipe to Makefile 2023-06-09 21:30:47 +04:00
64fdfe62d9 ruby: add sorbet as a type-checker dependency 2023-06-09 21:30:15 +04:00
036b1e50d4 ruby: add rubocop as a lint dependency 2023-06-09 12:17:30 +04:00
517b130db6 ruby: pin ruby version 2023-06-09 12:13:40 +04:00
0ff435b9bd ruby: pin dependency versions and add support for the arm64 platform 2023-06-09 12:13:14 +04:00
56bc372140 Merge remote-tracking branch 'remotes/origin/release/v7.4.0' into develop
# Conflicts:
#	web/documentserver-example/nodejs/helpers/docManager.js
2023-06-07 18:57:00 +05:00
4679804774 Merge pull request #386 from ONLYOFFICE/hotfix/fix-php-readme
php: composer installation added to readme
2023-06-07 16:30:48 +05:00
d03f74087c php: composer installation added to readme 2023-06-07 16:29:57 +05:00
f3cb5adb22 nodejs: fix (668df46ec3) 2023-06-02 11:00:30 +03:00
668df46ec3 nodejs: fix(dd3255779f) 2023-06-01 15:53:07 +03:00
d6a4984b84 Merge pull request #382 from ONLYOFFICE/feature/restore-version
Feature/restore version
2023-05-22 15:45:19 +05:00
f1dae06746 changelog: restore file 2023-05-22 15:44:45 +05:00
3cf3bcf2c8 Merge remote-tracking branch 'remotes/origin/develop' into feature/restore-version 2023-05-22 15:44:11 +05:00
aa6e19ebaa Merge pull request #372 from ONLYOFFICE/dependabot/bundler/web/documentserver-example/ruby/nokogiri-1.14.3
build(deps): bump nokogiri from 1.13.9 to 1.14.3 in /web/documentserver-example/ruby
2023-05-22 14:01:04 +05:00
d7034c72c9 Merge pull request #379 from ONLYOFFICE/feature/remove-row-without-reload
nodejs: remove row without reload
2023-05-18 18:12:46 +05:00
c0437b152f remove row to changelog 2023-05-18 18:10:44 +05:00
b72b2c6619 Merge branch 'develop' into feature/remove-row-without-reload
# Conflicts:
#	web/documentserver-example/nodejs/public/javascripts/jscript.js
2023-05-18 13:34:34 +03:00
c516631360 nodejs: fix remove for IE 2023-05-18 13:31:50 +03:00
5cc8d7c094 Merge pull request #380 from ONLYOFFICE/feature/get-history-by-request
nodejs: get history data by request
2023-05-18 11:23:10 +05:00
5f4764060c changelog: history request 2023-05-18 11:22:17 +05:00
44832008a8 nodejs: reload the page if deleted line is the last one 2023-05-17 13:24:28 +03:00
d86e737493 nodejs: fix properties for IE, historyObject used in requestRestore 2023-05-17 12:59:55 +03:00
07a1e3101b Merge branch 'feature/get-history-by-request' into feature/restore-version 2023-05-17 12:55:51 +03:00
1ebfe49916 nodejs: fix properties for IE 2023-05-17 12:54:15 +03:00
b1d6f8d652 Merge branch 'feature/get-history-by-request' into feature/restore-version 2023-05-17 12:46:15 +03:00
8f0edf90e6 nodejs: request in onRequestHistory only 2023-05-17 12:43:33 +03:00
7c77389550 build(deps): bump nokogiri in /web/documentserver-example/ruby
Bumps [nokogiri](https://github.com/sparklemotion/nokogiri) from 1.13.9 to 1.14.3.
- [Release notes](https://github.com/sparklemotion/nokogiri/releases)
- [Changelog](https://github.com/sparklemotion/nokogiri/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sparklemotion/nokogiri/compare/v1.13.9...v1.14.3)

---
updated-dependencies:
- dependency-name: nokogiri
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-17 12:42:09 +05:00
637731a4d7 Merge pull request #373 from ONLYOFFICE/refactor/collect-params-for-url
Refactor/collect params for url
2023-05-17 12:34:35 +05:00
6fc98a025b Merge branch 'feature/get-history-by-request' into feature/restore-version
# Conflicts:
#	web/documentserver-example/nodejs/app.js
2023-05-12 13:03:31 +03:00
f123cbcce3 nodejs: handler for restore file version 2023-05-12 13:00:48 +03:00
11f166525e nodejs: onRequestRestore method on front 2023-05-12 12:56:24 +03:00
68db498dfd nodejs: get history data by request 2023-05-12 11:12:32 +03:00
f914afcc53 nodejs: remove row without reload 2023-05-11 15:14:07 +03:00
8dcf75f3fb nodejs: get history data by request 2023-05-11 14:06:48 +03:00
3d9e091882 Merge pull request #378 from ONLYOFFICE/hotfix/disable-rule-for-old-nodejs
nodejs: hasOwnProperty() used instead of hasOwn() for NodeJS v.14
2023-05-10 17:36:27 +05:00
a9ca4b3272 Merge remote-tracking branch 'remotes/origin/release/v7.4.0' into develop 2023-05-10 17:32:40 +05:00
35798a7916 nodejs: hasOwnProperty() used instead of hasOwn() for NodeJS v.14 2023-05-10 11:30:26 +03:00
f7000b51a7 Merge branch 'release/v7.4.0' into develop
# Conflicts:
#	web/documentserver-example/nodejs/app.js
#	web/documentserver-example/nodejs/helpers/users.js
2023-05-10 10:55:24 +05:00
66faaab294 Merge branch 'develop' into refactor/collect-params-for-url
# Conflicts:
#	web/documentserver-example/nodejs/views/index.ejs
#	web/documentserver-example/nodejs/views/wopiIndex.ejs
2023-04-28 11:20:25 +03:00
7be2a5a507 nodejs: remove serverUrl 2023-04-27 16:45:22 +03:00
8cf26de5e2 Merge remote-tracking branch 'remotes/origin/release/v7.4.0' into develop 2023-04-27 15:15:15 +03:00
f2a11a5894 nodejs: WOPI-page fix 2023-04-27 14:54:36 +03:00
b543392c62 nodejs: server url to link in logo 2023-04-26 09:22:39 +03:00
adf52c756e nodejs: fix url-params + IE fix 2023-04-21 12:55:02 +03:00
693cc5a951 Merge pull request #369 from ONLYOFFICE/refactor/format-by-linter-nodejs
Refactor/format by linter nodejs
2023-04-21 09:40:20 +05:00
ff9ba7fbf1 Merge pull request #371 from ONLYOFFICE/hotfix/editor-warning-fix
php: editor warnings fix
2023-04-20 17:06:59 +05:00
c2b87959a2 nodejs: collectParams() instead of reload() + input text added 2023-04-19 11:14:45 +03:00
18ee7776ef nodejs: radio elements + "name" attribute instead of "data-param" 2023-04-19 10:06:29 +03:00
c99efda67a nodejs: open window in new tab 2023-04-19 09:25:49 +03:00
d65f970255 nodejs: collectParams() method added 2023-04-18 14:45:31 +03:00
f5442a8a89 nodejs: url params for collectable elements 2023-04-18 14:44:04 +03:00
e347ea36ce nodejs: "params" in links deleted, added class for actions 2023-04-18 11:50:54 +03:00
f0651dabf0 php: editor warnings fix 2023-04-10 12:31:04 +03:00
ccf85c1c0f nodejs: "no-plusplus" - rule excluded for loops 2023-04-05 15:16:33 +03:00
6ea35bf55c Merge branch 'refactor/format-by-linter-nodejs' of https://github.com/ONLYOFFICE/document-server-integration into refactor/format-by-linter-nodejs 2023-04-05 15:05:05 +03:00
f6afde346a nodejs: await in loops excluded from check 2023-04-05 15:04:50 +03:00
ce4074bcce nodejs: change order 2023-04-05 11:46:06 +05:00
5697b58aa2 nodejs: radix parameters for parseInt() 2023-04-04 12:57:32 +03:00
d5e6301211 nodejs: no restricted syntax 2023-04-04 12:50:45 +03:00
9048082cb7 nodejs: no shadow vars 2023-04-04 11:05:29 +03:00
56e46466b2 nodejs: useless rules deleted, autofixed spaces before parenthesis, arrow functions syntax, and comma after arguments added 2023-04-03 17:05:26 +03:00
fa9731ab57 nodejs: no unnamed functions 2023-04-03 16:44:48 +03:00
c2ba46ce85 nodejs: no await in loops 2023-04-03 15:25:43 +03:00
4c5780f1d6 nodejs: default param last 2023-04-03 15:20:26 +03:00
0419611a62 nodejs: no prototype builtins 2023-04-03 15:17:57 +03:00
bcc1011ddd nodejs: no constant condition 2023-04-03 15:04:57 +03:00
91a4fe1e52 nodejs: no throw literal 2023-04-03 12:51:30 +03:00
21fed8a81e nodejs: off unused airbnb-base rules 2023-03-31 14:29:59 +03:00
f2fc63c24f nodejs: default cases required 2023-03-31 14:03:14 +03:00
521608fa15 nodejs: no unused else blocks 2023-03-31 13:55:35 +03:00
e16ad4e53d nodejs: define vars is required 2023-03-31 13:48:11 +03:00
7205e383c8 nodejs: no new RegExp() 2023-03-31 13:40:47 +03:00
9bf317b3e0 nodejs: camelCase used 2023-03-31 13:38:38 +03:00
ac668a41c5 nodejs: declaration of methods before use 2023-03-31 13:32:20 +03:00
606f4255dc nodejs: no useless return statements + ';' in the end 2023-03-31 13:03:15 +03:00
22a64dd932 nodejs: no mixed tabs 2023-03-31 12:34:05 +03:00
dd3255779f nodejs: required the use of === and !== 2023-03-31 12:30:04 +03:00
89c7e63ab8 nodejs: object curly spacing 2023-03-31 11:04:35 +03:00
447c604fe9 nodejs: no multiple empty lines 2023-03-31 10:54:40 +03:00
dff9602852 nodejs: require correct order 2023-03-31 10:00:32 +03:00
f4d7915dd6 nodejs: 'use strict' is unnecessary inside of modules 2023-03-31 09:35:57 +03:00
01204d544e nodejs: const declarations for variables that are never reassigned after declared 2023-03-30 17:03:40 +03:00
a06aa8c8b3 nodejs: max-length of lines - 120 2023-03-30 16:31:39 +03:00
7977427038 nodejs: no unused variables 2023-03-30 13:47:33 +03:00
0b8d0ed10a nodejs: disallowed spacing around embedded expressions of template strings 2023-03-30 12:33:52 +03:00
efec141039 nodejs: disallowed padding within blocks 2023-03-30 12:29:39 +03:00
6736555ff3 nodejs: constructor names to begin with a capital letter 2023-03-30 12:20:50 +03:00
d94fe30a3e nodejs: fix no nested ternary expressions 2023-03-30 12:12:04 +03:00
3079320534 nodejs: no multi spaces 2023-03-30 10:57:00 +03:00
4f3af51e54 nodejs: newline after each call in a method chain 2023-03-30 10:52:48 +03:00
d19c81c944 nodejs: EOL last 2023-03-30 10:48:34 +03:00
bc3cbbbb82 nodejs: spacing around infix operators 2023-03-30 10:47:14 +03:00
8ee3ddc925 nodejs: space before the opening parenthesis in control statements 2023-03-30 10:44:00 +03:00
173c05dbf3 nodejs: consistent indentation (2 spaces) 2023-03-30 10:41:27 +03:00
b13c548c4d nodejs: 1 space before comment text 2023-03-30 10:30:18 +03:00
ef8237adfd nodejs: disallowed else blocks after return statements in if statements 2023-03-30 10:24:06 +03:00
c80379da31 nodejs: braces for multi-line blocks with if and else 2023-03-30 10:22:04 +03:00
a54c43c0c2 nodejs: braces with all multi-line blocks 2023-03-30 10:19:25 +03:00
5e524aa148 nodejs: disallow bitwise operators 2023-03-30 10:12:41 +03:00
e84ee9e01b nodejs: no unneeded ternary operators 2023-03-30 09:32:01 +03:00
27ceb1e6c6 nodejs: no nested ternary expressions 2023-03-29 17:23:50 +03:00
508b0d913c nodejs: disallow the unary operators ++ and -- 2023-03-29 16:35:32 +03:00
5999b070dc nodejs: dot notation whenever possible 2023-03-29 15:43:55 +03:00
3ed13f3975 nodejs: braces around arrow function bodies 2023-03-29 13:33:51 +03:00
1789f7c9fd nodejs: parentheses around arrow function arguments 2023-03-29 13:31:33 +03:00
a05ea11dd7 nodejs: spacing before and after the arrow in arrow functions 2023-03-29 13:29:34 +03:00
c6dd46a004 nodejs: linebreaks inside function parentheses if any of the parameters/arguments have a line break between them 2023-03-29 13:27:07 +03:00
bf04979c31 nodejs: reassigning function parameters disallowed 2023-03-29 13:20:33 +03:00
e9274b7303 nodejs: spacing before blocks 2023-03-29 12:52:36 +03:00
03022c5b45 nodejs: spacing before function definition opening parenthesis 2023-03-29 12:50:35 +03:00
ce4ccdd5b0 nodejs: rest parameters instead of arguments 2023-03-29 12:32:28 +03:00
07eba65458 nodejs: used named function expressions instead of function declarations 2023-03-29 10:56:17 +03:00
072b082240 nodejs: require using arrow functions for callbacks 2023-03-29 09:49:21 +03:00
c664bc4ee9 nodejs: template literals instead of string concatenation 2023-03-28 17:38:41 +03:00
f113d7eeb1 nodejs: require destructuring from arrays and objects 2023-03-28 16:52:27 +03:00
9409bf0785 nodejs: quote only properties that are invalid identifiers 2023-03-28 15:41:02 +03:00
d51e724130 nodejs: method and property shorthand syntax for object literals 2023-03-28 15:35:27 +03:00
9489b4dcde nodejs: variables with block scope used 2023-03-28 14:46:09 +03:00
d9c139a42b nodejs: const declarations for variables that are never reassigned after declared 2023-03-28 14:08:15 +03:00
534f1d8284 nodejs: single quotes used 2023-03-28 14:02:31 +03:00
f177af8791 nodejs: added max-length (120) to ruleset 2023-03-28 13:57:52 +03:00
80 changed files with 4851 additions and 3334 deletions

5
.gitignore vendored
View File

@ -22,8 +22,3 @@
/web/documentserver-example/csharp/packages
/web/documentserver-example/csharp-mvc/packages
/web/documentserver-example/java-spring/documents/
/web/documentserver-example/ruby/.bundle
/web/documentserver-example/ruby/db/*.sqlite3
/web/documentserver-example/ruby/db/*.sqlite3-journal
/web/documentserver-example/ruby/log/*
/web/documentserver-example/ruby/tmp

View File

@ -1,5 +1,8 @@
# Change Log
- nodejs: delete file without reloading the page
- nodejs: getting history by a separate request
- nodejs: restore from history
- nodejs: setUsers for region protection
- si skin languages
- fix "no" skin languages

View File

@ -11,5 +11,11 @@ module.exports = {
ecmaVersion: 'latest',
},
rules: {
'max-len': ['error', { code: 120 }],
'no-console': 'off',
'no-continue': 'off',
'no-extend-native': ['error', { exceptions: ['String'] }],
'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
'no-prototype-builtins': 'off',
},
};

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
/**
/**
*
* (c) Copyright Ascensio System SIA 2023
*
@ -16,42 +16,43 @@
*
*/
var cache = {};
let cache = {};
// write the key value and its creation time to the cache
exports.put = function (key, value) {
cache[key] = { value:value, time: new Date().getTime()};
}
exports.put = function put(key, value) {
cache[key] = { value, time: new Date().getTime() };
};
// check if the given key is in the cache
exports.containsKey = function (key) {
if (typeof cache[key] == "undefined"){
return false;
}
exports.containsKey = function containsKey(key) {
if (typeof cache[key] === 'undefined') {
return false;
}
var secondsCache = 30;
const secondsCache = 30;
var t1 = new Date(cache[key].time + (1000 * secondsCache)); // get the creation time of the given key and add 30 seconds to it
var t2 = new Date(); // get the current time
if (t1 < t2 ){ // if the current time is greater
delete cache[key]; // delete the given key from the cache
return false;
}
// get the creation time of the given key and add 30 seconds to it
const t1 = new Date(cache[key].time + (1000 * secondsCache));
const t2 = new Date(); // get the current time
if (t1 < t2) { // if the current time is greater
delete cache[key]; // delete the given key from the cache
return false;
}
return true;
}
return true;
};
// get the given key from the cache
exports.get = function (key) {
return cache[key];
}
exports.get = function get(key) {
return cache[key];
};
// delete the given key from the cache
exports.delete = function (key) {
delete cache[key];
}
exports.delete = function deleteKey(key) {
delete cache[key];
};
// clear the cache
exports.clear = function () {
cache = {};
}
exports.clear = function clear() {
cache = {};
};

View File

@ -1,4 +1,3 @@
"use strict";
/**
*
* (c) Copyright Ascensio System SIA 2023
@ -17,488 +16,596 @@
*
*/
const path = require("path");
const fileSystem = require("fs");
const fileUtility = require("./fileUtility");
const documentService = require("./documentService");
const path = require('path');
const fileSystem = require('fs');
const configServer = require('config').get('server');
const storageConfigFolder = configServer.get("storageFolder");
const fileUtility = require('./fileUtility');
const documentService = require('./documentService');
function docManager(req, res) {
this.req = req;
this.res = res;
}
const storageConfigFolder = configServer.get('storageFolder');
const DocManager = function DocManager(req, res) {
this.req = req;
this.res = res;
};
// check if the path exists or not
docManager.prototype.existsSync = function(path) {
let res = true;
try {
fileSystem.accessSync(path, fileSystem.F_OK); // synchronously test the user's permissions for the directory specified by path; the directory is visible to the calling process
} catch (e) { // the response is set to false, if an error occurs
res = false;
}
return res;
DocManager.prototype.existsSync = function existsSync(directory) {
let res = true;
try {
// synchronously test the user's permissions for the directory specified by path;
// the directory is visible to the calling process
fileSystem.accessSync(directory, fileSystem.F_OK);
} catch (e) { // the response is set to false, if an error occurs
res = false;
}
return res;
};
// create a new directory if it doesn't exist
docManager.prototype.createDirectory = function(path) {
if (!this.existsSync(path)) {
fileSystem.mkdirSync(path);
}
DocManager.prototype.createDirectory = function createDirectory(directory) {
if (!this.existsSync(directory)) {
fileSystem.mkdirSync(directory);
}
};
// get the language from the request
docManager.prototype.getLang = function () {
if (new RegExp("^[a-z]{2}(-[A-Z]{2})?$", "i").test(this.req.query.lang)) {
return this.req.query.lang;
} else { // the default language value is English
return "en"
}
DocManager.prototype.getLang = function getLang() {
if (/^[a-z]{2}(-[A-Z]{2})?$/i.test(this.req.query.lang)) {
return this.req.query.lang;
} // the default language value is English
return 'en';
};
// get customization parameters
docManager.prototype.getCustomParams = function () {
let params = "";
DocManager.prototype.getCustomParams = function getCustomParams() {
let params = '';
const userid = this.req.query.userid; // user id
params += (userid ? "&userid=" + userid : "");
const { userid } = this.req.query; // user id
params += (userid ? `&userid=${userid}` : '');
const lang = this.req.query.lang; // language
params += (lang ? "&lang=" + this.getLang() : "");
const { lang } = this.req.query; // language
params += (lang ? `&lang=${this.getLang()}` : '');
const directUrl = this.req.query.directUrl; // directUrl
params += (directUrl ? "&directUrl=" + (directUrl == "true") : "");
const { directUrl } = this.req.query; // directUrl
params += (directUrl ? `&directUrl=${directUrl === 'true'}` : '');
const fileName = this.req.query.fileName; // file name
params += (fileName ? "&fileName=" + fileName : "");
const { fileName } = this.req.query; // file name
params += (fileName ? `&fileName=${fileName}` : '');
const mode = this.req.query.mode; // mode: view/edit/review/comment/fillForms/embedded
params += (mode ? "&mode=" + mode : "");
const { mode } = this.req.query; // mode: view/edit/review/comment/fillForms/embedded
params += (mode ? `&mode=${mode}` : '');
const type = this.req.query.type; // type: embedded/mobile/desktop
params += (type ? "&type=" + type : "");
const { type } = this.req.query; // type: embedded/mobile/desktop
params += (type ? `&type=${type}` : '');
return params;
return params;
};
// get the correct file name if such a name already exists
docManager.prototype.getCorrectName = function (fileName, userAddress) {
const baseName = fileUtility.getFileName(fileName, true); // get file name from the url without extension
const ext = fileUtility.getFileExtension(fileName); // get file extension from the url
let name = baseName + ext; // get full file name
let index = 1;
DocManager.prototype.getCorrectName = function getCorrectName(fileName, userAddress) {
const baseName = fileUtility.getFileName(fileName, true); // get file name from the url without extension
const ext = fileUtility.getFileExtension(fileName); // get file extension from the url
let name = baseName + ext; // get full file name
let index = 1;
while (this.existsSync(this.storagePath(name, userAddress))) { // if the file with such a name already exists in this directory
name = baseName + " (" + index + ")" + ext; // add an index after its base name
index++;
}
// if the file with such a name already exists in this directory
while (this.existsSync(this.storagePath(name, userAddress))) {
name = `${baseName} (${index})${ext}`; // add an index after its base name
index += 1;
}
return name;
return name;
};
// processes a request editnew
docManager.prototype.RequestEditnew = function (req, fileName, user) {
if (req.params['id'] != fileName){ // processes a repeated request editnew
this.fileRemove(req.params['id']);
fileName = this.getCorrectName(req.params['id']);
}
this.fileSizeZero(fileName);
this.saveFileData(fileName, user.id, user.name);
DocManager.prototype.requestEditnew = function requestEditnew(req, fileName, user) {
let correctName = fileName;
if (req.params.id !== fileName) { // processes a repeated request editnew
this.fileRemove(req.params.id);
correctName = this.getCorrectName(req.params.id);
}
this.fileSizeZero(correctName);
this.saveFileData(correctName, user.id, user.name);
return fileName;
}
return correctName;
};
// delete a file with its history
docManager.prototype.fileRemove = function (fileName) {
const filePath = this.storagePath(fileName); // get the path to this file
fileSystem.unlinkSync(filePath); // and delete it
DocManager.prototype.fileRemove = function fileRemove(fileName) {
const filePath = this.storagePath(fileName); // get the path to this file
fileSystem.unlinkSync(filePath); // and delete it
const userAddress = this.curUserHostAddress();
const historyPath = this.historyPath(fileName, userAddress, true);
this.cleanFolderRecursive(historyPath, true); // clean all the files from the history folder
}
const userAddress = this.curUserHostAddress();
const historyPath = this.historyPath(fileName, userAddress, true);
this.cleanFolderRecursive(historyPath, true); // clean all the files from the history folder
};
// create a zero-size file
docManager.prototype.fileSizeZero = function (fileName) {
var path = this.storagePath(fileName);
var fh = fileSystem.openSync(path, 'w');
fileSystem.closeSync(fh);
}
DocManager.prototype.fileSizeZero = function fileSizeZero(fileName) {
const storagePath = this.storagePath(fileName);
const fh = fileSystem.openSync(storagePath, 'w');
fileSystem.closeSync(fh);
};
// create demo document
docManager.prototype.createDemo = function (isSample, fileExt, userid, username, wopi) {
// eslint-disable-next-line no-unused-vars
DocManager.prototype.createDemo = function createDemo(isSample, fileExt, userid, username, wopi) {
const demoName = `${isSample ? 'sample' : 'new'}.${fileExt}`;
const fileName = this.getCorrectName(demoName); // get the correct file name if such a name already exists
const demoName = (isSample ? "sample" : "new") + "." + fileExt;
const fileName = this.getCorrectName(demoName); // get the correct file name if such a name already exists
// copy sample document of a necessary extension to the storage path
this.copyFile(path.join(__dirname, '..', 'public', 'assets', isSample
? 'sample' : 'new', demoName), this.storagePath(fileName));
this.copyFile(path.join(__dirname, "..","public", "assets", isSample ? "sample" : "new", demoName), this.storagePath(fileName)); // copy sample document of a necessary extension to the storage path
this.saveFileData(fileName, userid, username); // save file data to the file
this.saveFileData(fileName, userid, username); // save file data to the file
return fileName;
return fileName;
};
// save file data to the file
docManager.prototype.saveFileData = function (fileName, userid, username, userAddress) {
if (!userAddress) {
userAddress = this.curUserHostAddress(); // get current user host address
}
// get full creation date of the document
const date_create = fileSystem.statSync(this.storagePath(fileName, userAddress)).mtime;
const minutes = (date_create.getMinutes() < 10 ? '0' : '') + date_create.getMinutes().toString();
const month = (date_create.getMonth() < 10 ? '0' : '') + (parseInt(date_create.getMonth().toString()) + 1);
const sec = (date_create.getSeconds() < 10 ? '0' : '') + date_create.getSeconds().toString();
const date_format = date_create.getFullYear() + "-" + month + "-" + date_create.getDate() + " " + date_create.getHours() + ":" + minutes + ":" + sec;
DocManager.prototype.saveFileData = function saveFileData(fileName, userid, username, userAddress) {
let address = userAddress;
if (!address) {
address = this.curUserHostAddress(); // get current user host address
}
// get full creation date of the document
const dateCreate = fileSystem.statSync(this.storagePath(fileName, address)).mtime;
const minutes = (dateCreate.getMinutes() < 10 ? '0' : '') + dateCreate.getMinutes().toString();
const month = (dateCreate.getMonth() < 10 ? '0' : '') + (parseInt(dateCreate.getMonth().toString(), 10) + 1);
const sec = (dateCreate.getSeconds() < 10 ? '0' : '') + dateCreate.getSeconds().toString();
const dateFormat = `${dateCreate.getFullYear()}-${month}-${dateCreate.getDate()}`
+ `${dateCreate.getHours()}:${minutes}:${sec}`;
const file_info = this.historyPath(fileName, userAddress, true); // get file history information
this.createDirectory(file_info); // create a new history directory if it doesn't exist
const fileInfo = this.historyPath(fileName, address, true); // get file history information
this.createDirectory(fileInfo); // create a new history directory if it doesn't exist
fileSystem.writeFileSync(path.join(file_info, fileName + ".txt"), date_format + "," + userid + "," + username); // write all the file information to a new txt file
// write all the file information to a new txt file
fileSystem.writeFileSync(path.join(fileInfo, `${fileName}.txt`), `${dateFormat},${userid},${username}`);
};
// get file data
docManager.prototype.getFileData = function (fileName, userAddress) {
const history = path.join(this.historyPath(fileName, userAddress, true), fileName + ".txt"); // get the path to the file with file information
if (!this.existsSync(history)) { // if such a file doesn't exist
return ["2017-01-01", "uid-1", "John Smith"]; // return default information
}
DocManager.prototype.getFileData = function getFileData(fileName, userAddress) {
// get the path to the file with file information
const history = path.join(this.historyPath(fileName, userAddress, true), `${fileName}.txt`);
if (!this.existsSync(history)) { // if such a file doesn't exist
return ['2017-01-01', 'uid-1', 'John Smith']; // return default information
}
return ((fileSystem.readFileSync(history)).toString()).split(",");
return ((fileSystem.readFileSync(history)).toString())
.split(',');
};
// get server url
docManager.prototype.getServerUrl = function (forDocumentServer) {
return (forDocumentServer && !!configServer.get("exampleUrl")) ? configServer.get("exampleUrl") : this.getServerPath();
DocManager.prototype.getServerUrl = function getServerUrl(forDocumentServer) {
return (forDocumentServer && !!configServer.get('exampleUrl'))
? configServer.get('exampleUrl') : this.getServerPath();
};
// get server address from the request
docManager.prototype.getServerPath = function () {
return this.getServerHost() + (this.req.headers["x-forwarded-path"] || this.req.baseUrl);
DocManager.prototype.getServerPath = function getServerPath() {
return this.getServerHost() + (this.req.headers['x-forwarded-path'] || this.req.baseUrl);
};
// get host address from the request
docManager.prototype.getServerHost = function () {
return this.getProtocol() + "://" + (this.req.headers["x-forwarded-host"] || this.req.headers["host"]) + (this.req.headers["x-forwarded-prefix"] || "");
DocManager.prototype.getServerHost = function getServerHost() {
return `${this.getProtocol()}://${this.req.headers['x-forwarded-host'] || this.req.headers.host}`
+ `${this.req.headers['x-forwarded-prefix'] || ''}`;
};
// get protocol from the request
docManager.prototype.getProtocol = function () {
return this.req.headers["x-forwarded-proto"] || this.req.protocol;
DocManager.prototype.getProtocol = function getProtocol() {
return this.req.headers['x-forwarded-proto'] || this.req.protocol;
};
// get callback url
docManager.prototype.getCallback = function (fileName) {
const server = this.getServerUrl(true);
const hostAddress = this.curUserHostAddress();
const handler = "/track?filename=" + encodeURIComponent(fileName) + "&useraddress=" + encodeURIComponent(hostAddress); // get callback handler
DocManager.prototype.getCallback = function getCallback(fileName) {
const server = this.getServerUrl(true);
const hostAddress = this.curUserHostAddress();
// get callback handler
const handler = `/track?filename=${encodeURIComponent(fileName)}&useraddress=${encodeURIComponent(hostAddress)}`;
return server + handler;
return server + handler;
};
// get url to the created file
docManager.prototype.getCreateUrl = function (docType, userid, type, lang) {
const server = this.getServerUrl();
var ext = this.getInternalExtension(docType).replace(".", "");
const handler = "/editor?fileExt=" + ext + "&userid=" + userid + "&type=" + type + "&lang=" + lang;
DocManager.prototype.getCreateUrl = function getCreateUrl(docType, userid, type, lang) {
const server = this.getServerUrl();
const ext = this.getInternalExtension(docType).replace('.', '');
const handler = `/editor?fileExt=${ext}&userid=${userid}&type=${type}&lang=${lang}`;
return server + handler;
}
// get url to download a file
docManager.prototype.getDownloadUrl = function (fileName, forDocumentServer) {
const server = this.getServerUrl(forDocumentServer);
var handler = "/download?fileName=" + encodeURIComponent(fileName);
if (forDocumentServer) {
const hostAddress = this.curUserHostAddress();
handler += "&useraddress=" + encodeURIComponent(hostAddress);
}
return server + handler;
return server + handler;
};
docManager.prototype.storageRootPath = function (userAddress) {
return path.join(storageConfigFolder, this.curUserHostAddress(userAddress)); // get the path to the directory for the host address
}
// get url to download a file
DocManager.prototype.getDownloadUrl = function getDownloadUrl(fileName, forDocumentServer) {
const server = this.getServerUrl(forDocumentServer);
let handler = `/download?fileName=${encodeURIComponent(fileName)}`;
if (forDocumentServer) {
const hostAddress = this.curUserHostAddress();
handler += `&useraddress=${encodeURIComponent(hostAddress)}`;
}
return server + handler;
};
DocManager.prototype.storageRootPath = function storageRootPath(userAddress) {
// get the path to the directory for the host address
return path.join(storageConfigFolder, this.curUserHostAddress(userAddress));
};
// get the storage path of the given file
docManager.prototype.storagePath = function (fileName, userAddress) {
fileName = fileUtility.getFileName(fileName); // get the file name with extension
const directory = this.storageRootPath(userAddress);
this.createDirectory(directory); // create a new directory if it doesn't exist
return path.join(directory, fileName); // put the given file to this directory
DocManager.prototype.storagePath = function storagePath(fileName, userAddress) {
const fileNameExt = fileUtility.getFileName(fileName); // get the file name with extension
const directory = this.storageRootPath(userAddress);
this.createDirectory(directory); // create a new directory if it doesn't exist
return path.join(directory, fileNameExt); // put the given file to this directory
};
// get the path to the forcesaved file version
docManager.prototype.forcesavePath = function (fileName, userAddress, create) {
let directory = this.storageRootPath(userAddress);
if (!this.existsSync(directory)) { // the directory with host address doesn't exist
return "";
}
directory = path.join(directory, fileName + "-history"); // get the path to the history of the given file
if (!create && !this.existsSync(directory)) { // the history directory doesn't exist and we are not supposed to create it
return "";
}
this.createDirectory(directory); // create history directory if it doesn't exist
directory = path.join(directory, fileName); // and get the path to the given file
if (!create && !this.existsSync(directory)) {
return "";
}
return directory;
DocManager.prototype.forcesavePath = function forcesavePath(fileName, userAddress, create) {
let directory = this.storageRootPath(userAddress);
if (!this.existsSync(directory)) { // the directory with host address doesn't exist
return '';
}
directory = path.join(directory, `${fileName}-history`); // get the path to the history of the given file
// the history directory doesn't exist and we are not supposed to create it
if (!create && !this.existsSync(directory)) {
return '';
}
this.createDirectory(directory); // create history directory if it doesn't exist
directory = path.join(directory, fileName); // and get the path to the given file
if (!create && !this.existsSync(directory)) {
return '';
}
return directory;
};
// create the path to the file history
docManager.prototype.historyPath = function (fileName, userAddress, create) {
let directory = this.storageRootPath(userAddress);
if (!this.existsSync(directory)) {
return "";
}
directory = path.join(directory, fileName + "-history");
if (!create && !this.existsSync(path.join(directory, "1"))) {
return "";
}
return directory;
DocManager.prototype.historyPath = function historyPath(fileName, userAddress, create) {
let directory = this.storageRootPath(userAddress);
if (!this.existsSync(directory)) {
return '';
}
directory = path.join(directory, `${fileName}-history`);
if (!create && !this.existsSync(path.join(directory, '1'))) {
return '';
}
return directory;
};
// get the path to the specified file version
docManager.prototype.versionPath = function (fileName, userAddress, version) {
const historyPath = this.historyPath(fileName, userAddress, true); // get the path to the history of a given file or create it if it doesn't exist
return path.join(historyPath, "" + version);
DocManager.prototype.versionPath = function versionPath(fileName, userAddress, version) {
// get the path to the history of a given file or create it if it doesn't exist
const historyPath = this.historyPath(fileName, userAddress, true);
return path.join(historyPath, `${version}`);
};
// get the path to the previous file version
docManager.prototype.prevFilePath = function (fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), "prev" + fileUtility.getFileExtension(fileName));
DocManager.prototype.prevFilePath = function prevFilePath(fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), `prev${fileUtility.getFileExtension(fileName)}`);
};
// get the path to the file with document versions differences
docManager.prototype.diffPath = function (fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), "diff.zip");
DocManager.prototype.diffPath = function diffPath(fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), 'diff.zip');
};
// get the path to the file with document changes
docManager.prototype.changesPath = function (fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), "changes.txt");
DocManager.prototype.changesPath = function changesPath(fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), 'changes.txt');
};
// get the path to the file with key value in it
docManager.prototype.keyPath = function (fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), "key.txt");
DocManager.prototype.keyPath = function keyPath(fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), 'key.txt');
};
// get the path to the file with the user information
docManager.prototype.changesUser = function (fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), "user.txt");
DocManager.prototype.changesUser = function changesUser(fileName, userAddress, version) {
return path.join(this.versionPath(fileName, userAddress, version), 'user.txt');
};
// get all the stored files
docManager.prototype.getStoredFiles = function () {
const userAddress = this.curUserHostAddress();
const directory = this.storageRootPath(userAddress);
this.createDirectory(directory);
const result = [];
const storedFiles = fileSystem.readdirSync(directory); // read the user host directory contents
for (let i = 0; i < storedFiles.length; i++) { // run through all the elements from the folder
const stats = fileSystem.lstatSync(path.join(directory, storedFiles[i])); // save element parameters
DocManager.prototype.getStoredFiles = function getStoredFiles() {
const userAddress = this.curUserHostAddress();
const directory = this.storageRootPath(userAddress);
this.createDirectory(directory);
const result = [];
const storedFiles = fileSystem.readdirSync(directory); // read the user host directory contents
for (let i = 0; i < storedFiles.length; i++) { // run through all the elements from the folder
const stats = fileSystem.lstatSync(path.join(directory, storedFiles[i])); // save element parameters
if (!stats.isDirectory()) { // if the element isn't a directory
let historyPath = this.historyPath(storedFiles[i], userAddress); // get the path to the file history
let version = 0;
if (historyPath != "") { // if the history path exists
version = this.countVersion(historyPath); // get the last file version
}
if (!stats.isDirectory()) { // if the element isn't a directory
const historyPath = this.historyPath(storedFiles[i], userAddress); // get the path to the file history
let version = 0;
if (historyPath !== '') { // if the history path exists
version = this.countVersion(historyPath); // get the last file version
}
const time = stats.mtime.getTime(); // get the time of element modification
const item = { // create an object with element data
time: time,
name: storedFiles[i],
documentType: fileUtility.getFileType(storedFiles[i]),
canEdit: configServer.get("editedDocs").indexOf(fileUtility.getFileExtension(storedFiles[i])) != -1,
version: version+1
};
const time = stats.mtime.getTime(); // get the time of element modification
const item = { // create an object with element data
time,
name: storedFiles[i],
documentType: fileUtility.getFileType(storedFiles[i]),
canEdit: configServer.get('editedDocs').indexOf(fileUtility.getFileExtension(storedFiles[i])) !== -1,
version: version + 1,
};
if (!result.length) { // if the result array is empty
result.push(item); // push the item object to it
} else {
let j = 0;
for (; j < result.length; j++) {
if (time > result[j].time) { // otherwise, run through all the objects from the result array
break;
}
}
result.splice(j, 0, item); // and add new object in ascending order of time
}
if (!result.length) { // if the result array is empty
result.push(item); // push the item object to it
} else {
let j = 0;
for (; j < result.length; j++) {
if (time > result[j].time) { // otherwise, run through all the objects from the result array
break;
}
}
result.splice(j, 0, item); // and add new object in ascending order of time
}
}
return result;
}
return result;
};
// get current user host address
docManager.prototype.curUserHostAddress = function (userAddress) {
if (!userAddress) // if user address isn't passed to the function
userAddress = this.req.headers["x-forwarded-for"] || this.req.connection.remoteAddress; // take it from the header or use the remote address
DocManager.prototype.curUserHostAddress = function curUserHostAddress(userAddress) {
let address = userAddress;
if (!address) { // if user address isn't passed to the function
// take it from the header or use the remote address
address = this.req.headers['x-forwarded-for'] || this.req.connection.remoteAddress;
}
return userAddress.replace(new RegExp("[^0-9a-zA-Z.=]", "g"), "_");
return address.replace(/[^0-9a-zA-Z.=]/g, '_');
};
// copy file
docManager.prototype.copyFile = function (exist, target) {
fileSystem.writeFileSync(target, fileSystem.readFileSync(exist));
DocManager.prototype.copyFile = function copyFile(exist, target) {
fileSystem.writeFileSync(target, fileSystem.readFileSync(exist));
};
// get an internal extension
docManager.prototype.getInternalExtension = function (fileType) {
if (fileType == fileUtility.fileType.word) // .docx for word type
return ".docx";
DocManager.prototype.getInternalExtension = function getInternalExtension(fileType) {
if (fileType === fileUtility.fileType.word) { // .docx for word type
return '.docx';
}
if (fileType == fileUtility.fileType.cell) // .xlsx for cell type
return ".xlsx";
if (fileType === fileUtility.fileType.cell) { // .xlsx for cell type
return '.xlsx';
}
if (fileType == fileUtility.fileType.slide) // .pptx for slide type
return ".pptx";
if (fileType === fileUtility.fileType.slide) { // .pptx for slide type
return '.pptx';
}
return ".docx"; // the default value is .docx
return '.docx'; // the default value is .docx
};
// get the template image url
docManager.prototype.getTemplateImageUrl = function (fileType) {
let path = this.getServerUrl(true);
if (fileType == fileUtility.fileType.word) // for word type
return path + "/images/file_docx.svg";
DocManager.prototype.getTemplateImageUrl = function getTemplateImageUrl(fileType) {
const serverUrl = this.getServerUrl(true);
if (fileType === fileUtility.fileType.word) { // for word type
return `${serverUrl}/images/file_docx.svg`;
}
if (fileType == fileUtility.fileType.cell) // for cell type
return path + "/images/file_xlsx.svg";
if (fileType === fileUtility.fileType.cell) { // for cell type
return `${path}/images/file_xlsx.svg`;
}
if (fileType == fileUtility.fileType.slide) // for slide type
return path + "/images/file_pptx.svg";
if (fileType === fileUtility.fileType.slide) { // for slide type
return `${path}/images/file_pptx.svg`;
}
return path + "/images/file_docx.svg"; // the default value
}
return `${path}/images/file_docx.svg`; // the default value
};
// get document key
docManager.prototype.getKey = function (fileName, userAddress) {
userAddress = userAddress || this.curUserHostAddress();
let key = userAddress + fileName; // get document key by adding local file url to the current user host address
DocManager.prototype.getKey = function getKey(fileName, userAddress) {
const address = userAddress || this.curUserHostAddress();
let key = address + fileName; // get document key by adding local file url to the current user host address
let historyPath = this.historyPath(fileName, userAddress); // get the path to the file history
if (historyPath != ""){ // if the path to the file history exists
key += this.countVersion(historyPath); // add file version number to the document key
}
const historyPath = this.historyPath(fileName, address); // get the path to the file history
if (historyPath !== '') { // if the path to the file history exists
key += this.countVersion(historyPath); // add file version number to the document key
}
let storagePath = this.storagePath(fileName, userAddress); // get the storage path to the given file
const stat = fileSystem.statSync(storagePath); // get file information
key += stat.mtime.getTime(); // and add creation time to the document key
const storagePath = this.storagePath(fileName, address); // get the storage path to the given file
const stat = fileSystem.statSync(storagePath); // get file information
key += stat.mtime.getTime(); // and add creation time to the document key
return documentService.generateRevisionId(key); // generate the document key value
return documentService.generateRevisionId(key); // generate the document key value
};
// get current date
docManager.prototype.getDate = function (date) {
const minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes().toString();
return date.getMonth() + "/" + date.getDate() + "/" + date.getFullYear() + " " + date.getHours() + ":" + minutes;
DocManager.prototype.getDate = function getDate(date) {
const minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes().toString();
return `${date.getMonth()}/${date.getDate()}/${date.getFullYear()} ${date.getHours()}:${minutes}`;
};
// get changes made in the file
docManager.prototype.getChanges = function (fileName) {
if (this.existsSync(fileName)) { // if the directory with such a file exists
return JSON.parse(fileSystem.readFileSync(fileName)); // read this file and parse it
}
return null;
DocManager.prototype.getChanges = function getChanges(fileName) {
if (this.existsSync(fileName)) { // if the directory with such a file exists
return JSON.parse(fileSystem.readFileSync(fileName)); // read this file and parse it
}
return null;
};
// get the last file version
docManager.prototype.countVersion = function(directory) {
let i = 0;
while (this.existsSync(path.join(directory, '' + (i + 1)))) { // run through all the file versions
i++; // and count them
}
return i;
DocManager.prototype.countVersion = function countVersion(directory) {
let i = 0;
while (this.existsSync(path.join(directory, `${i + 1}`))) { // run through all the file versions
i += 1; // and count them
}
return i;
};
// get file history information
docManager.prototype.getHistory = function (fileName, content, keyVersion, version) {
let oldVersion = false;
let contentJson = null;
if (content) { // if content is defined
if (content.changes && content.changes.length) { // and there are some modifications in the content
contentJson = content.changes[0]; // write these modifications to the json content
} else if (content.length){
contentJson = content[0]; // otherwise, write original content to the json content
oldVersion = true; // and note that this is an old version
} else {
content = false;
}
DocManager.prototype.getHistoryObject = function getHistoryObject(fileName, userAddr = null, userDirectUrl = null) {
const userAddress = userAddr || this.curUserHostAddress();
const historyPath = this.historyPath(fileName, userAddress);
const key = this.getKey(fileName);
const directUrl = this.getDownloadUrl(fileName);
const fileExt = fileUtility.getFileExtension(fileName);
const url = this.getDownloadUrl(fileName, true);
const history = [];
const historyData = [];
let countVersion = 1;
let changes = null;
let keyVersion = key;
if (historyPath !== '') {
countVersion = this.countVersion(historyPath) + 1; // get the number of file versions
for (let i = 1; i <= countVersion; i++) { // get keys to all the file versions
if (i < countVersion) {
const keyPath = this.keyPath(fileName, userAddress, i);
if (!fileSystem.existsSync(keyPath)) continue;
keyVersion = `${fileSystem.readFileSync(keyPath)}`;
} else {
keyVersion = key;
}
// write all the file history information
history.push(this.getHistory(fileName, changes, keyVersion, i));
const userUrl = i === countVersion ? directUrl : (`${this.getServerUrl(false)}/history?fileName=`
+ `${encodeURIComponent(fileName)}&file=prev${fileExt}&ver=${i}`);
const historyD = {
fileType: fileExt.slice(1),
version: i,
key: keyVersion,
url: i === countVersion ? url : (`${this.getServerUrl(true)}/history?fileName=`
+ `${encodeURIComponent(fileName)}&file=prev${fileExt}&ver=${i}&useraddress=${userAddress}`),
directUrl: !userDirectUrl ? null : userUrl,
};
// check if the path to the file with document versions differences exists
if (i > 1 && this.existsSync(this.diffPath(fileName, userAddress, i - 1))) {
historyD.previous = { // write information about previous file version
fileType: historyData[i - 2].fileType,
key: historyData[i - 2].key,
url: historyData[i - 2].url,
directUrl: !userDirectUrl ? null : historyData[i - 2].directUrl,
};
const changesUrl = `${this.getServerUrl(true)}/history?fileName=`
+ `${encodeURIComponent(fileName)}&file=diff.zip&ver=${i - 1}&useraddress=${userAddress}`;
historyD.changesUrl = changesUrl; // get the path to the diff.zip file and write it to the history object
}
historyData.push(historyD);
if (i < countVersion) {
// get the path to the file with document changes
const changesFile = this.changesPath(fileName, userAddress, i);
changes = this.getChanges(changesFile); // get changes made in the file
}
}
} else { // if history path is empty
// write the history information about the last file version
history.push(this.getHistory(fileName, changes, keyVersion, countVersion));
historyData.push({
fileType: fileExt.slice(1),
version: countVersion,
key,
url,
directUrl: !userDirectUrl ? null : directUrl,
});
}
const userAddress = this.curUserHostAddress();
const username = content ? (oldVersion ? contentJson.username : contentJson.user.name) : (this.getFileData(fileName, userAddress))[2];
const userid = content ? (oldVersion ? contentJson.userid : contentJson.user.id) : (this.getFileData(fileName, userAddress))[1];
const created = content ? (oldVersion ? contentJson.date : contentJson.created) : (this.getFileData(fileName, userAddress))[0];
const res = (content && !oldVersion) ? content : {changes: content};
res.key = keyVersion; // write the information about the user, creation time, key and version to the result object
res.version = version;
res.created = created;
res.user = {
id: userid,
name: username != "null" ? username : null
};
return { history, historyData, countVersion };
};
// get file history information
DocManager.prototype.getHistory = function getHistory(fileName, content, keyVersion, version) {
let oldVersion = false;
let contentJson = null;
let fileContent = content;
let userNameFromJson = null;
let userIdFromJson = null;
let createdFromJson = null;
if (fileContent) { // if content is defined
if (fileContent.changes && fileContent.changes.length) { // and there are some modifications in the content
[contentJson] = fileContent.changes; // write these modifications to the json content
} else if (fileContent.length) {
[contentJson] = fileContent; // otherwise, write original content to the json content
oldVersion = true; // and note that this is an old version
} else {
fileContent = false;
}
}
return res;
const userAddress = this.curUserHostAddress();
if (content && contentJson) {
userNameFromJson = oldVersion ? contentJson.username : contentJson.user.name;
userIdFromJson = oldVersion ? contentJson.userid : contentJson.user.userid;
createdFromJson = oldVersion ? contentJson.date : contentJson.created;
}
const username = userNameFromJson || (this.getFileData(fileName, userAddress))[2];
const userid = userIdFromJson || (this.getFileData(fileName, userAddress))[1];
const created = createdFromJson || (this.getFileData(fileName, userAddress))[0];
const res = (fileContent && !oldVersion) ? fileContent : { changes: fileContent };
res.key = keyVersion; // write the information about the user, creation time, key and version to the result object
res.version = version;
res.created = created;
res.user = {
id: userid,
name: username !== 'null' ? username : null,
};
return res;
};
// clean folder
docManager.prototype.cleanFolderRecursive = function (folder, me) {
if (fileSystem.existsSync(folder)) { // if the given folder exists
const files = fileSystem.readdirSync(folder);
files.forEach((file) => { // for each file from the folder
const curPath = path.join(folder, file); // get its current path
if (fileSystem.lstatSync(curPath).isDirectory()) {
this.cleanFolderRecursive(curPath, true); // for each folder included in this one repeat the same procedure
} else {
fileSystem.unlinkSync(curPath); // remove the file
}
});
if (me) {
fileSystem.rmdirSync(folder);
}
DocManager.prototype.cleanFolderRecursive = function cleanFolderRecursive(folder, me) {
if (fileSystem.existsSync(folder)) { // if the given folder exists
const files = fileSystem.readdirSync(folder);
files.forEach((file) => { // for each file from the folder
const curPath = path.join(folder, file); // get its current path
if (fileSystem.lstatSync(curPath).isDirectory()) {
this.cleanFolderRecursive(curPath, true); // for each folder included in this one repeat the same procedure
} else {
fileSystem.unlinkSync(curPath); // remove the file
}
});
if (me) {
fileSystem.rmdirSync(folder);
}
}
};
// get files information
docManager.prototype.getFilesInfo = function (fileId) {
const userAddress = this.curUserHostAddress();
const directory = this.storageRootPath(userAddress);
const filesInDirectory = this.getStoredFiles(); // get all the stored files from the folder
let responseArray = [];
let responseObject;
for (let currentFile = 0; currentFile < filesInDirectory.length; currentFile++) { // run through all the files from the directory
const file = filesInDirectory[currentFile];
const stats = fileSystem.lstatSync(path.join(directory, file.name)); // get file information
const fileObject = { // write file parameters to the file object
version: file.version,
id: this.getKey(file.name),
contentLength: `${(stats.size/1024).toFixed(2)} KB`,
pureContentLength: stats.size,
title: file.name,
updated: stats.mtime
};
if (fileId !== undefined) { // if file id is defined
if (this.getKey(file.name) == fileId) { // and it is equal to the document key value
responseObject = fileObject; // response object will be equal to the file object
break;
}
}
else responseArray.push(fileObject); // otherwise, push file object to the response array
DocManager.prototype.getFilesInfo = function getFilesInfo(fileId) {
const userAddress = this.curUserHostAddress();
const directory = this.storageRootPath(userAddress);
const filesInDirectory = this.getStoredFiles(); // get all the stored files from the folder
const responseArray = [];
let responseObject;
// run through all the files from the directory
for (let currentFile = 0; currentFile < filesInDirectory.length; currentFile++) {
const file = filesInDirectory[currentFile];
const stats = fileSystem.lstatSync(path.join(directory, file.name)); // get file information
const fileObject = { // write file parameters to the file object
version: file.version,
id: this.getKey(file.name),
contentLength: `${(stats.size / 1024).toFixed(2)} KB`,
pureContentLength: stats.size,
title: file.name,
updated: stats.mtime,
};
if (fileId !== undefined) {
if (responseObject !== undefined) return responseObject;
else return "File not found";
}
else return responseArray;
if (fileId !== undefined) { // if file id is defined
if (this.getKey(file.name) === fileId) { // and it is equal to the document key value
responseObject = fileObject; // response object will be equal to the file object
break;
}
} else responseArray.push(fileObject); // otherwise, push file object to the response array
}
if (fileId !== undefined) {
if (responseObject !== undefined) return responseObject;
return 'File not found';
} return responseArray;
};
docManager.prototype.getInstanceId = function () {
return this.getServerUrl();
DocManager.prototype.getInstanceId = function getInstanceId() {
return this.getServerUrl();
};
// save all the functions to the docManager module to export it later in other files
module.exports = docManager;
// save all the functions to the DocManager module to export it later in other files
module.exports = DocManager;

View File

@ -1,4 +1,4 @@
/**
/**
*
* (c) Copyright Ascensio System SIA 2023
*
@ -17,229 +17,261 @@
*/
// get all the necessary values and modules
var urlModule = require("url");
var urllib = require("urllib");
var jwt = require("jsonwebtoken");
var fileUtility = require("./fileUtility");
var guidManager = require("./guidManager");
var configServer = require('config').get('server');
var siteUrl = configServer.get('siteUrl'); // the path to the editors installation
var cfgSignatureEnable = configServer.get('token.enable');
var cfgSignatureUseForRequest = configServer.get('token.useforrequest');
var cfgSignatureAuthorizationHeader = configServer.get('token.authorizationHeader');
var cfgSignatureAuthorizationHeaderPrefix = configServer.get('token.authorizationHeaderPrefix');
var cfgSignatureSecretExpiresIn = configServer.get('token.expiresIn');
var cfgSignatureSecret = configServer.get('token.secret');
var cfgSignatureSecretAlgorithmRequest = configServer.get('token.algorithmRequest');
const urlModule = require('url');
const urllib = require('urllib');
const jwt = require('jsonwebtoken');
const configServer = require('config').get('server');
const fileUtility = require('./fileUtility');
const guidManager = require('./guidManager');
var documentService = {};
const siteUrl = configServer.get('siteUrl'); // the path to the editors installation
const cfgSignatureEnable = configServer.get('token.enable');
const cfgSignatureUseForRequest = configServer.get('token.useforrequest');
const cfgSignatureAuthorizationHeader = configServer.get('token.authorizationHeader');
const cfgSignatureAuthorizationHeaderPrefix = configServer.get('token.authorizationHeaderPrefix');
const cfgSignatureSecretExpiresIn = configServer.get('token.expiresIn');
const cfgSignatureSecret = configServer.get('token.secret');
const cfgSignatureSecretAlgorithmRequest = configServer.get('token.algorithmRequest');
const documentService = {};
documentService.userIp = null;
// get the url of the converted file (synchronous)
documentService.getConvertedUriSync = function (documentUri, fromExtension, toExtension, documentRevisionId, callback) {
documentService.getConvertedUri(documentUri, fromExtension, toExtension, documentRevisionId, false, function (err, data) {
callback(err, data);
});
documentService.getConvertedUriSync = function getConvertedUriSync(
documentUri,
fromExtension,
toExtension,
documentRevisionId,
callback,
) {
documentService.getConvertedUri(documentUri, fromExtension, toExtension, documentRevisionId, false, (err, data) => {
callback(err, data);
});
};
// get the url of the converted file
documentService.getConvertedUri = function (documentUri, fromExtension, toExtension, documentRevisionId, async, callback, filePass = null, lang = null) {
fromExtension = fromExtension || fileUtility.getFileExtension(documentUri); // get the current document extension
documentService.getConvertedUri = function getConvertedUri(
documentUri,
fromExtension,
toExtension,
documentRevisionId,
async,
callback,
filePass = null,
lang = null,
) {
const fromExt = fromExtension || fileUtility.getFileExtension(documentUri); // get the current document extension
var title = fileUtility.getFileName(documentUri) || guidManager.newGuid(); // get the current document name or uuid
const title = fileUtility.getFileName(documentUri) || guidManager.newGuid(); // get the current document name or uuid
documentRevisionId = documentService.generateRevisionId(documentRevisionId || documentUri); // generate the document key value
// generate the document key value
const revisionId = documentService.generateRevisionId(documentRevisionId || documentUri);
var params = { // write all the conversion parameters to the params dictionary
async: async,
url: documentUri,
outputtype: toExtension.replace(".", ""),
filetype: fromExtension.replace(".", ""),
title: title,
key: documentRevisionId,
password: filePass,
region: lang,
};
const params = { // write all the conversion parameters to the params dictionary
async,
url: documentUri,
outputtype: toExtension.replace('.', ''),
filetype: fromExt.replace('.', ''),
title,
key: revisionId,
password: filePass,
region: lang,
};
var uri = siteUrl + configServer.get('converterUrl'); // get the absolute converter url
var headers = {
'Content-Type': 'application/json',
"Accept": "application/json"
};
const uri = siteUrl + configServer.get('converterUrl'); // get the absolute converter url
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
if (cfgSignatureEnable && cfgSignatureUseForRequest) { // if the signature is enabled and it can be used for request
headers[cfgSignatureAuthorizationHeader] = cfgSignatureAuthorizationHeaderPrefix + this.fillJwtByUrl(uri, params); // write signature authorization header
params.token = documentService.getToken(params); // get token and save it to the parameters
}
if (cfgSignatureEnable && cfgSignatureUseForRequest) { // if the signature is enabled and it can be used for request
// write signature authorization header
headers[cfgSignatureAuthorizationHeader] = cfgSignatureAuthorizationHeaderPrefix + this.fillJwtByUrl(uri, params);
params.token = documentService.getToken(params); // get token and save it to the parameters
}
//parse url to allow request by relative url after https://github.com/node-modules/urllib/pull/321/commits/514de1924bf17a38a6c2db2a22a6bc3494c0a959
urllib.request(urlModule.parse(uri),
{
method: "POST",
headers: headers,
data: params
},
callback);
// parse url to allow request by relative url after
// https://github.com/node-modules/urllib/pull/321/commits/514de1924bf17a38a6c2db2a22a6bc3494c0a959
urllib.request(
urlModule.parse(uri),
{
method: 'POST',
headers,
data: params,
},
callback,
);
};
// generate the document key value
documentService.generateRevisionId = function (expectedKey) {
let maxKeyLength = 128; // the max key length is 128
if (expectedKey.length > maxKeyLength) { // if the expected key length is greater than the max key length
expectedKey = expectedKey.hashCode().toString(); // the expected key is hashed and a fixed length value is stored in the string format
}
documentService.generateRevisionId = function generateRevisionId(expectedKey) {
const maxKeyLength = 128; // the max key length is 128
let expKey = expectedKey;
if (expKey.length > maxKeyLength) { // if the expected key length is greater than the max key length
// the expected key is hashed and a fixed length value is stored in the string format
expKey = expKey.hashCode().toString();
}
var key = expectedKey.replace(new RegExp("[^0-9-.a-zA-Z_=]", "g"), "_");
const key = expKey.replace(/[^0-9-.a-zA-Z_=]/g, '_');
return key.substring(0, Math.min(key.length, maxKeyLength)); // the resulting key is of the max key length or less
return key.substring(0, Math.min(key.length, maxKeyLength)); // the resulting key is of the max key length or less
};
// create an error message for the error code
documentService.processConvertServiceResponceError = function (errorCode) {
var errorMessage = "";
var errorMessageTemplate = "Error occurred in the ConvertService: ";
documentService.processConvertServiceResponceError = function processConvertServiceResponceError(errorCode) {
let errorMessage = '';
const errorMessageTemplate = 'Error occurred in the ConvertService: ';
// add the error message to the error message template depending on the error code
switch (errorCode) {
case -20:
errorMessage = errorMessageTemplate + "Error encrypt signature";
break;
case -8:
errorMessage = errorMessageTemplate + "Error document signature";
break;
case -7:
errorMessage = errorMessageTemplate + "Error document request";
break;
case -6:
errorMessage = errorMessageTemplate + "Error database";
break;
case -5:
errorMessage = errorMessageTemplate + "Incorrect password";
break;
case -4:
errorMessage = errorMessageTemplate + "Error download error";
break;
case -3:
errorMessage = errorMessageTemplate + "Error convertation error";
break;
case -2:
errorMessage = errorMessageTemplate + "Error convertation timeout";
break;
case -1:
errorMessage = errorMessageTemplate + "Error convertation unknown";
break;
case 0: // if the error code is equal to 0, the error message is empty
break;
default:
errorMessage = "ErrorCode = " + errorCode; // default value for the error message
break;
}
// add the error message to the error message template depending on the error code
switch (errorCode) {
case -20:
errorMessage = `${errorMessageTemplate}Error encrypt signature`;
break;
case -8:
errorMessage = `${errorMessageTemplate}Error document signature`;
break;
case -7:
errorMessage = `${errorMessageTemplate}Error document request`;
break;
case -6:
errorMessage = `${errorMessageTemplate}Error database`;
break;
case -5:
errorMessage = `${errorMessageTemplate}Incorrect password`;
break;
case -4:
errorMessage = `${errorMessageTemplate}Error download error`;
break;
case -3:
errorMessage = `${errorMessageTemplate}Error convertation error`;
break;
case -2:
errorMessage = `${errorMessageTemplate}Error convertation timeout`;
break;
case -1:
errorMessage = `${errorMessageTemplate}Error convertation unknown`;
break;
case 0: // if the error code is equal to 0, the error message is empty
break;
default:
errorMessage = `ErrorCode = ${errorCode}`; // default value for the error message
break;
}
throw { message: errorMessage };
throw new Error(errorMessage);
};
// get the response url
documentService.getResponseUri = function (json) {
var fileResult = JSON.parse(json);
documentService.getResponseUri = function getResponseUri(json) {
const fileResult = JSON.parse(json);
if (fileResult.error) // if an error occurs
documentService.processConvertServiceResponceError(parseInt(fileResult.error)); // get an error message
if (fileResult.error) { // if an error occurs
documentService.processConvertServiceResponceError(parseInt(fileResult.error, 10)); // get an error message
}
var isEndConvert = fileResult.endConvert // check if the conversion is completed
const isEndConvert = fileResult.endConvert; // check if the conversion is completed
var percent = parseInt(fileResult.percent); // get the conversion percentage
var uri = null;
var fileType = null;
let percent = parseInt(fileResult.percent, 10); // get the conversion percentage
let uri = null;
let fileType = null;
if (isEndConvert) { // if the conversion is completed
if (!fileResult.fileUrl) // and the file url doesn't exist
throw { message: "FileUrl is null" }; // the file url is null
uri = fileResult.fileUrl; // otherwise, get the file url
fileType = fileResult.fileType; // get the file type
percent = 100;
} else { // if the conversion isn't completed
percent = percent >= 100 ? 99 : percent; // get the percentage value
if (isEndConvert) { // if the conversion is completed
if (!fileResult.fileUrl) { // and the file url doesn't exist
throw new Error('FileUrl is null'); // the file url is null
}
return {
percent : percent,
uri : uri,
fileType : fileType
};
uri = fileResult.fileUrl; // otherwise, get the file url
({ fileType } = fileResult); // get the file type
percent = 100;
} else { // if the conversion isn't completed
percent = percent >= 100 ? 99 : percent; // get the percentage value
}
return {
percent,
uri,
fileType,
};
};
// create a command request
documentService.commandRequest = function (method, documentRevisionId, meta = null, callback) {
documentService.commandRequest = function commandRequest(method, documentRevisionId, callback, meta = null) {
const revisionId = documentService.generateRevisionId(documentRevisionId); // generate the document key value
const params = { // create a parameter object with command method and the document key value in it
c: method,
key: revisionId,
};
documentRevisionId = documentService.generateRevisionId(documentRevisionId); // generate the document key value
params = { // create a parameter object with command method and the document key value in it
c: method,
key: documentRevisionId
};
if (meta) {
params.meta = meta;
}
if (meta) {
params.meta = meta;
}
const uri = siteUrl + configServer.get('commandUrl'); // get the absolute command url
const headers = { // create a headers object
'Content-Type': 'application/json',
};
if (cfgSignatureEnable && cfgSignatureUseForRequest) {
headers[cfgSignatureAuthorizationHeader] = cfgSignatureAuthorizationHeaderPrefix + this.fillJwtByUrl(uri, params);
params.token = documentService.getToken(params);
}
var uri = siteUrl + configServer.get('commandUrl'); // get the absolute command url
var headers = { // create a headers object
'Content-Type': 'application/json'
};
if (cfgSignatureEnable && cfgSignatureUseForRequest) {
headers[cfgSignatureAuthorizationHeader] = cfgSignatureAuthorizationHeaderPrefix + this.fillJwtByUrl(uri, params);
params.token = documentService.getToken(params);
}
//parse url to allow request by relative url after https://github.com/node-modules/urllib/pull/321/commits/514de1924bf17a38a6c2db2a22a6bc3494c0a959
urllib.request(urlModule.parse(uri),
{
method: "POST",
headers: headers,
data: params
},
callback);
// parse url to allow request by relative url after
// https://github.com/node-modules/urllib/pull/321/commits/514de1924bf17a38a6c2db2a22a6bc3494c0a959
urllib.request(
urlModule.parse(uri),
{
method: 'POST',
headers,
data: params,
},
callback,
);
};
// check jwt token headers
documentService.checkJwtHeader = function (req) {
var decoded = null;
var authorization = req.get(cfgSignatureAuthorizationHeader); // get signature authorization header from the request
if (authorization && authorization.startsWith(cfgSignatureAuthorizationHeaderPrefix)) { // if authorization header exists and it starts with the authorization header prefix
var token = authorization.substring(cfgSignatureAuthorizationHeaderPrefix.length); // the resulting token starts after the authorization header prefix
documentService.checkJwtHeader = function checkJwtHeader(req) {
let decoded = null;
const authorization = req.get(cfgSignatureAuthorizationHeader); // get signature authorization header from the request
// if authorization header exists and it starts with the authorization header prefix
if (authorization && authorization.startsWith(cfgSignatureAuthorizationHeaderPrefix)) {
// the resulting token starts after the authorization header prefix
const token = authorization.substring(cfgSignatureAuthorizationHeaderPrefix.length);
try {
decoded = jwt.verify(token, cfgSignatureSecret); // verify signature on jwt token using signature secret
decoded = jwt.verify(token, cfgSignatureSecret); // verify signature on jwt token using signature secret
} catch (err) {
console.log('checkJwtHeader error: name = ' + err.name + ' message = ' + err.message + ' token = ' + token) // print debug information to the console
// print debug information to the console
console.log(`checkJwtHeader error: name = ${err.name} message = ${err.message} token = ${token}`);
}
}
return decoded;
}
};
// get jwt token using url information
documentService.fillJwtByUrl = function (uri, opt_dataObject) {
var parseObject = urlModule.parse(uri, true); // get parse object from the url
var payload = {query: parseObject.query, payload: opt_dataObject}; // create payload object
documentService.fillJwtByUrl = function fillJwtByUrl(uri, optDataObject) {
const parseObject = urlModule.parse(uri, true); // get parse object from the url
const payload = { query: parseObject.query, payload: optDataObject }; // create payload object
var options = {algorithm: cfgSignatureSecretAlgorithmRequest, expiresIn: cfgSignatureSecretExpiresIn};
return jwt.sign(payload, cfgSignatureSecret, options); // sign token with given data using signature secret and options parameters
}
const options = { algorithm: cfgSignatureSecretAlgorithmRequest, expiresIn: cfgSignatureSecretExpiresIn };
// sign token with given data using signature secret and options parameters
return jwt.sign(payload, cfgSignatureSecret, options);
};
// get token
documentService.getToken = function (data) {
var options = {algorithm: cfgSignatureSecretAlgorithmRequest, expiresIn: cfgSignatureSecretExpiresIn};
return jwt.sign(data, cfgSignatureSecret, options); // sign token with given data using signature secret and options parameters
documentService.getToken = function getToken(data) {
const options = { algorithm: cfgSignatureSecretAlgorithmRequest, expiresIn: cfgSignatureSecretExpiresIn };
// sign token with given data using signature secret and options parameters
return jwt.sign(data, cfgSignatureSecret, options);
};
// read and verify token
documentService.readToken = function (token) {
try {
return jwt.verify(token, cfgSignatureSecret); // verify signature on jwt token using signature secret
} catch (err) {
console.log('checkJwtHeader error: name = ' + err.name + ' message = ' + err.message + ' token = ' + token)
}
return null;
documentService.readToken = function readToken(token) {
try {
return jwt.verify(token, cfgSignatureSecret); // verify signature on jwt token using signature secret
} catch (err) {
console.log(`checkJwtHeader error: name = ${err.name} message = ${err.message} token = ${token}`);
}
return null;
};
// save all the functions to the documentService module to export it later in other files

View File

@ -1,4 +1,4 @@
/**
/**
*
* (c) Copyright Ascensio System SIA 2023
*
@ -16,79 +16,86 @@
*
*/
var fileUtility = {};
const fileUtility = {};
// get file name from the given url
fileUtility.getFileName = function (url, withoutExtension) {
if (!url) return "";
fileUtility.getFileName = function getFileName(url, withoutExtension) {
if (!url) return '';
var parts = url.split("\\");
parts = parts.pop();
parts = parts.split("/");
var fileName = parts.pop(); // get the file name from the last part of the url
fileName = fileName.split("?")[0];
let parts = url.split('\\');
parts = parts.pop();
parts = parts.split('/');
let fileName = parts.pop(); // get the file name from the last part of the url
[fileName] = fileName.split('?');
// get file name without extension
if (withoutExtension) {
return fileName.substring(0, fileName.lastIndexOf("."));
}
// get file name without extension
if (withoutExtension) {
return fileName.substring(0, fileName.lastIndexOf('.'));
}
return fileName;
return fileName;
};
// get file extension from the given url
fileUtility.getFileExtension = function (url, withoutDot) {
if (!url) return null;
fileUtility.getFileExtension = function getFileExtension(url, withoutDot) {
if (!url) return null;
var fileName = fileUtility.getFileName(url); // get file name from the given url
const fileName = fileUtility.getFileName(url); // get file name from the given url
var parts = fileName.toLowerCase().split(".");
const parts = fileName.toLowerCase().split('.');
return withoutDot ? parts.pop() : "." + parts.pop(); // get the extension from the file name with or without dot
return withoutDot ? parts.pop() : `.${parts.pop()}`; // get the extension from the file name with or without dot
};
// get file type from the given url
fileUtility.getFileType = function (url) {
var ext = fileUtility.getFileExtension(url); // get the file extension from the given url
fileUtility.getFileType = function getFileType(url) {
const ext = fileUtility.getFileExtension(url); // get the file extension from the given url
if (fileUtility.documentExts.indexOf(ext) != -1) return fileUtility.fileType.word; // word type for document extensions
if (fileUtility.spreadsheetExts.indexOf(ext) != -1) return fileUtility.fileType.cell; // cell type for spreadsheet extensions
if (fileUtility.presentationExts.indexOf(ext) != -1) return fileUtility.fileType.slide; // slide type for presentation extensions
// word type for document extensions
if (fileUtility.documentExts.indexOf(ext) !== -1) return fileUtility.fileType.word;
// cell type for spreadsheet extensions
if (fileUtility.spreadsheetExts.indexOf(ext) !== -1) return fileUtility.fileType.cell;
// slide type for presentation extensions
if (fileUtility.presentationExts.indexOf(ext) !== -1) return fileUtility.fileType.slide;
return fileUtility.fileType.word; // the default file type is word
}
return fileUtility.fileType.word; // the default file type is word
};
fileUtility.fileType = {
word: "word",
cell: "cell",
slide: "slide"
}
word: 'word',
cell: 'cell',
slide: 'slide',
};
// the document extension list
fileUtility.documentExts = [".doc", ".docx", ".oform", ".docm", ".dot", ".dotx", ".dotm", ".odt", ".fodt", ".ott", ".rtf", ".txt", ".html", ".htm", ".mht", ".xml", ".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oxps"];
fileUtility.documentExts = ['.doc', '.docx', '.oform', '.docm', '.dot', '.dotx', '.dotm', '.odt',
'.fodt', '.ott', '.rtf', '.txt', '.html', '.htm', '.mht', '.xml', '.pdf', '.djvu', '.fb2', '.epub', '.xps', '.oxps'];
// the spreadsheet extension list
fileUtility.spreadsheetExts = [".xls", ".xlsx", ".xlsm", ".xlsb", ".xlt", ".xltx", ".xltm", ".ods", ".fods", ".ots", ".csv"];
fileUtility.spreadsheetExts = ['.xls', '.xlsx', '.xlsm', '.xlsb', '.xlt',
'.xltx', '.xltm', '.ods', '.fods', '.ots', '.csv'];
// the presentation extension list
fileUtility.presentationExts = [".pps", ".ppsx", ".ppsm", ".ppt", ".pptx", ".pptm", ".pot", ".potx", ".potm", ".odp", ".fodp", ".otp"];
fileUtility.presentationExts = ['.pps', '.ppsx', '.ppsm', '.ppt', '.pptx', '.pptm', '.pot',
'.potx', '.potm', '.odp', '.fodp', '.otp'];
// get url parameters
function getUrlParams(url) {
try {
var query = url.split("?").pop(); // take all the parameters which are placed after ? sign in the file url
var params = query.split("&"); // parameters are separated by & sign
var map = {}; // write parameters and their values to the map dictionary
for (var i = 0; i < params.length; i++) {
var parts = param.split("=");
map[parts[0]] = parts[1];
}
return map;
// eslint-disable-next-line no-unused-vars
const getUrlParams = function getUrlParams(url) {
try {
const query = url.split('?').pop(); // take all the parameters which are placed after ? sign in the file url
const params = query.split('&'); // parameters are separated by & sign
const map = {}; // write parameters and their values to the map dictionary
for (let i = 0; i < params.length; i++) {
// eslint-disable-next-line no-undef
const parts = param.split('=');
[, map[parts[0]]] = parts;
}
catch (ex) {
return null;
}
}
return map;
} catch (ex) {
return null;
}
};
// save all the functions to the fileUtility module to export it later in other files
module.exports = fileUtility;

View File

@ -1,4 +1,4 @@
/**
/**
*
* (c) Copyright Ascensio System SIA 2023
*
@ -17,11 +17,12 @@
*/
// generate 16 octet
var s4 = function () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
const s4 = function s4() {
return Math.trunc((1 + Math.random()) * 0x10000).toString(16)
.substring(1);
};
// create uuid v4
exports.newGuid = function () {
return (s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4());
};
exports.newGuid = function newGuid() {
return (`${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`);
};

View File

@ -16,80 +16,20 @@
*
*/
var descr_user_1 = [
"File author by default",
"Doesnt belong to any group",
"Can review all the changes",
"Can perform all actions with comments",
"The file favorite state is undefined",
"Can create files from templates using data from the editor",
"Can see the information about all users",
//"Can submit forms"
];
var descr_user_2 = [
"Belongs to Group2",
"Can review only his own changes or changes made by users with no group",
"Can view comments, edit his own comments and comments left by users with no group. Can remove his own comments only",
"This file is marked as favorite",
"Can create new files from the editor",
"Can see the information about users from Group2 and users who dont belong to any group",
//"Cant submit forms"
];
var descr_user_3 = [
"Belongs to Group3",
"Can review changes made by Group2 users",
"Can view comments left by Group2 and Group3 users. Can edit comments left by the Group2 users",
"This file isnt marked as favorite",
"Cant copy data from the file to clipboard",
"Cant download the file",
"Cant print the file",
"Can create new files from the editor",
"Can see the information about Group2 users",
//"Cant submit forms"
];
var descr_user_0 = [
"The name is requested when the editor is opened",
"Doesnt 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",
"Cant see anyones information",
"Can't rename files from the editor",
"Can't view chat",
"Can't protect file",
"View file without collaboration",
//"Cant submit forms"
];
var users = [
new User("uid-1", "John Smith", "smith@example.com",
null, null, {}, null,
null, [], descr_user_1, true),
new User("uid-2", "Mark Pottato", "pottato@example.com",
"group-2", ["group-2", ""], {
view: "",
edit: ["group-2", ""],
remove: ["group-2"]
}, ["group-2", ""],
true, [], descr_user_2, false), // own and without group
new User("uid-3", "Hamish Mitchell", null,
"group-3", ["group-2"], {
view: ["group-3", "group-2"],
edit: ["group-2"],
remove: []
}, ["group-2"],
false, ["copy", "download", "print"], descr_user_3, false), // other group only
new User("uid-0", null, null,
null, null, {}, [],
null, ["protect"], descr_user_0, false),
];
function User(id, name, email, group, reviewGroups, commentGroups, userInfoGroups, favorite, deniedPermissions, descriptions, templates) {
class User {
constructor(
id,
name,
email,
group,
reviewGroups,
commentGroups,
userInfoGroups,
favorite,
deniedPermissions,
descriptions,
templates,
) {
this.id = id;
this.name = name;
this.email = email;
@ -101,51 +41,117 @@ function User(id, name, email, group, reviewGroups, commentGroups, userInfoGroup
this.deniedPermissions = deniedPermissions;
this.descriptions = descriptions;
this.templates = templates;
};
}
}
const descrUser1 = [
'File author by default',
'Doesnt belong to any group',
'Can review all the changes',
'Can perform all actions with comments',
'The file favorite state is undefined',
'Can create files from templates using data from the editor',
'Can see the information about all users',
// "Can submit forms"
];
const descrUser2 = [
'Belongs to Group2',
'Can review only his own changes or changes made by users with no group',
'Can view comments, edit his own comments and comments left by users with no group. Can remove his own comments only',
'This file is marked as favorite',
'Can create new files from the editor',
'Can see the information about users from Group2 and users who dont belong to any group',
// "Cant submit forms"
];
const descrUser3 = [
'Belongs to Group3',
'Can review changes made by Group2 users',
'Can view comments left by Group2 and Group3 users. Can edit comments left by the Group2 users',
'This file isnt marked as favorite',
'Cant copy data from the file to clipboard',
'Cant download the file',
'Cant print the file',
'Can create new files from the editor',
'Can see the information about Group2 users',
// "Cant submit forms"
];
const descrUser0 = [
'The name is requested when the editor is opened',
'Doesnt 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',
'Cant see anyones information',
'Can\'t rename files from the editor',
'Can\'t view chat',
'Can\'t protect file',
'View file without collaboration',
// "Cant submit forms"
];
const users = [
new User('uid-1', 'John Smith', 'smith@example.com', null, null, {}, null, null, [], descrUser1, true),
new User('uid-2', 'Mark Pottato', 'pottato@example.com', 'group-2', ['group-2', ''], {
view: '',
edit: ['group-2', ''],
remove: ['group-2'],
}, ['group-2', ''], true, [], descrUser2, false), // own and without group
new User('uid-3', 'Hamish Mitchell', 'mitchell@example.com', 'group-3', ['group-2'], {
view: ['group-3', 'group-2'],
edit: ['group-2'],
remove: [],
}, ['group-2'], false, ['copy', 'download', 'print'], descrUser3, false), // other group only
new User('uid-0', null, null, null, null, {}, [], null, ['protect'], descrUser0, false),
];
// get a list of all the users
users.getAllUsers = function () {
return users;
users.getAllUsers = function getAllUsers() {
return users;
};
// get a user by id specified
users.getUser = function (id) {
var result = null;
this.forEach(user => {
if (user.id == id) {
result = user;
}
});
return result ? result : this[0];
users.getUser = function getUser(id) {
let result = null;
this.forEach((user) => {
if (user.id === id) {
result = user;
}
});
return result || this[0];
};
// get a list of users with their name and email for mentions
users.getUsersForMentions = function (id) {
var result = [];
this.forEach(user => {
if (user.id != id && user.name != null && user.email != null) {
result.push({
email: user.email,
name: user.name
});
}
});
return result;
users.getUsersForMentions = function getUsersForMentions(id) {
const result = [];
this.forEach((user) => {
if (user.id !== id && user.name && user.email) {
result.push({
email: user.email,
name: user.name,
});
}
});
return result;
};
// get a list of users with their name, id and email for protect
users.getUsersForProtect = function (id) {
var result = [];
this.forEach(user => {
if (user.id != id && user.name != null) {
result.push({
email: user.email,
id: user.id,
name: user.name
});
}
});
return result;
users.getUsersForProtect = function getUsersForProtect(id) {
const result = [];
this.forEach((user) => {
if (user.id !== id && user.name != null) {
result.push({
email: user.email,
id: user.id,
name: user.name,
});
}
});
return result;
};
module.exports = users;

View File

@ -16,14 +16,343 @@
*
*/
const fileSystem = require('fs');
const mime = require('mime');
const path = require('path');
const reqConsts = require('./request');
const fileUtility = require("../fileUtility");
const lockManager = require("./lockManager");
const fileSystem = require("fs");
const mime = require("mime");
const path = require("path");
const users = require("../users");
const docManager = require("../docManager");
const fileUtility = require('../fileUtility');
const lockManager = require('./lockManager');
const users = require('../users');
const DocManager = require('../docManager');
// return lock mismatch
const returnLockMismatch = function returnLockMismatch(res, lock, reason) {
res.setHeader(reqConsts.requestHeaders.Lock, lock || ''); // set the X-WOPI-Lock header
if (reason) { // if there is a reason for lock mismatch
res.setHeader(reqConsts.requestHeaders.LockFailureReason, reason); // set it as the X-WOPI-LockFailureReason header
}
res.sendStatus(409); // conflict
};
// lock file editing
const lock = function lock(wopi, req, res, userHost) {
const requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
const userAddress = req.DocManager.curUserHostAddress(userHost); // get current user host address
const filePath = req.DocManager.storagePath(wopi.id, userAddress); // get the storage path of the given file
if (!lockManager.hasLock(filePath)) {
// file isn't locked => lock
lockManager.lock(filePath, requestLock);
res.sendStatus(200);
} else if (lockManager.getLock(filePath) === requestLock) {
// lock matches current lock => extend duration
lockManager.lock(filePath, requestLock);
res.sendStatus(200);
} else {
// file locked by someone else => return lock mismatch
const locked = lockManager.getLock(filePath);
returnLockMismatch(res, lock, `File already locked by ${locked}`);
}
};
const saveFileFromBody = function saveFileFromBody(req, filename, userAddress, isNewVersion, callback) {
if (req.body) {
const storagePath = req.DocManager.storagePath(filename, userAddress);
let historyPath = req.DocManager.historyPath(filename, userAddress); // get the path to the file history
if (historyPath === '') { // if it is empty
historyPath = req.DocManager.historyPath(filename, userAddress, true); // create it
req.DocManager.createDirectory(historyPath); // and create a new directory for the history
}
let version = 0;
if (isNewVersion) {
const countVersion = req.DocManager.countVersion(historyPath); // get the last file version
version = countVersion + 1; // get a number of a new file version
// get the path to the specified file version
const versionPath = req.DocManager.versionPath(filename, userAddress, version);
req.DocManager.createDirectory(versionPath); // and create a new directory for the specified version
// get the path to the previous file version
const pathPrev = path.join(versionPath, `prev${fileUtility.getFileExtension(filename)}`);
fileSystem.renameSync(storagePath, pathPrev); // synchronously rename the given file as the previous file version
}
const filestream = fileSystem.createWriteStream(storagePath);
req.pipe(filestream);
req.on('end', () => {
filestream.close();
callback(null, version);
});
} else {
callback('empty body');
}
};
// return name that wopi-client can use as the value of X-WOPI-RelativeTarget in a future PutRelativeFile operation
const returnValidRelativeTarget = function returnValidRelativeTarget(res, filename) {
res.setHeader(reqConsts.requestHeaders.ValidRelativeTarget, filename); // set the X-WOPI-ValidRelativeTarget header
res.sendStatus(409); // file with that name already exists
};
// retrieve a lock on a file
const getLock = function getLock(wopi, req, res, userHost) {
const userAddress = req.DocManager.curUserHostAddress(userHost);
const filePath = req.DocManager.storagePath(wopi.id, userAddress);
// get the lock of the specified file and set it as the X-WOPI-Lock header
res.setHeader(reqConsts.requestHeaders.lock, lockManager.getLock(filePath));
res.sendStatus(200);
};
// refresh the lock on a file by resetting its automatic expiration timer to 30 minutes
const refreshLock = function refreshLock(wopi, req, res, userHost) {
const requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
const userAddress = req.DocManager.curUserHostAddress(userHost);
const filePath = req.DocManager.storagePath(wopi.id, userAddress);
if (!lockManager.hasLock(filePath)) {
// file isn't locked => mismatch
returnLockMismatch(res, '', 'File isn\'t locked');
} else if (lockManager.getLock(filePath) === requestLock) {
// lock matches current lock => extend duration
lockManager.lock(filePath, requestLock);
res.sendStatus(200);
} else {
// lock mismatch
returnLockMismatch(res, lockManager.getLock(filePath), 'Lock mismatch');
}
};
// allow for file editing
const unlock = function unlock(wopi, req, res, userHost) {
const requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
const userAddress = req.DocManager.curUserHostAddress(userHost);
const filePath = req.DocManager.storagePath(wopi.id, userAddress);
if (!lockManager.hasLock(filePath)) {
// file isn't locked => mismatch
returnLockMismatch(res, '', 'File isn\'t locked');
} else if (lockManager.getLock(filePath) === requestLock) {
// lock matches current lock => unlock
lockManager.unlock(filePath);
res.sendStatus(200);
} else {
// lock mismatch
returnLockMismatch(res, lockManager.getLock(filePath), 'Lock mismatch');
}
};
// allow for file editing, and then immediately take a new lock on the file
const unlockAndRelock = function unlockAndRelock(wopi, req, res, userHost) {
const requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
const oldLock = req.headers[reqConsts.requestHeaders.oldLock.toLowerCase()]; // get the X-WOPI-OldLock header
const userAddress = req.DocManager.curUserHostAddress(userHost);
const filePath = req.DocManager.storagePath(wopi.id, userAddress);
if (!lockManager.hasLock(filePath)) {
// file isn't locked => mismatch
returnLockMismatch(res, '', 'File isn\'t locked');
} else if (lockManager.getLock(filePath) === oldLock) {
// lock matches current lock => lock with new key
lockManager.lock(filePath, requestLock);
res.sendStatus(200);
} else {
// lock mismatch
returnLockMismatch(res, lockManager.getLock(filePath), 'Lock mismatch');
}
};
// request a message to retrieve a file
const getFile = function getFile(wopi, req, res, userHost) {
const userAddress = req.DocManager.curUserHostAddress(userHost);
const storagePath = req.DocManager.storagePath(wopi.id, userAddress);
res.setHeader('Content-Length', fileSystem.statSync(storagePath).size);
res.setHeader('Content-Type', mime.getType(storagePath));
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(wopi.id)}`);
const filestream = fileSystem.createReadStream(storagePath); // open a file as a readable stream
filestream.pipe(res); // retrieve data from file stream and output it to the response object
};
// request a message to update a file
const putFile = function putFile(wopi, req, res, userHost) {
const requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
const userAddress = req.DocManager.curUserHostAddress(userHost);
const storagePath = req.DocManager.storagePath(wopi.id, userAddress);
if (!lockManager.hasLock(storagePath)) {
// ToDo: if body length is 0 bytes => handle document creation
// file isn't locked => mismatch
returnLockMismatch(res, '', 'File isn\'t locked');
} else if (lockManager.getLock(storagePath) === requestLock) {
// lock matches current lock => put file
saveFileFromBody(req, wopi.id, userAddress, true, (err, version) => {
if (!err) {
res.setHeader(reqConsts.requestHeaders.ItemVersion, version); // set the X-WOPI-ItemVersion header
}
res.sendStatus(err ? 404 : 200);
});
} else {
// lock mismatch
returnLockMismatch(res, lockManager.getLock(storagePath), 'Lock mismatch');
}
};
const putRelativeFile = function putRelativeFile(wopi, req, res, userHost) {
const userAddress = req.DocManager.curUserHostAddress(userHost);
const storagePath = req.DocManager.storagePath(wopi.id, userAddress);
let filename = req.headers[reqConsts.requestHeaders.RelativeTarget.toLowerCase()]; // we cannot modify this filename
if (filename) {
if (req.DocManager.existsSync(storagePath)) { // check if already exists
const overwrite = req.headers[reqConsts.requestHeaders.OverwriteRelativeTarget.toLowerCase()]; // overwrite header
if (overwrite && overwrite === 'true') { // check if we can overwrite
if (lockManager.hasLock(storagePath)) { // check if file locked
// file is locked, cannot overwrite
returnValidRelativeTarget(res, req.DocManager.getCorrectName(wopi.id, userAddress));
return;
}
} else {
// file exists and overwrite header is false
returnValidRelativeTarget(res, req.DocManager.getCorrectName(wopi.id, userAddress));
return;
}
}
} else {
filename = req.headers[reqConsts.requestHeaders.SuggestedTarget.toLowerCase()]; // we can modify this filename
if (filename.startsWith('.')) { // check if extension
filename = fileUtility.getFileName(wopi.id, true) + filename; // get original filename with new extension
}
filename = req.DocManager.getCorrectName(filename, userAddress); // get correct filename if already exists
}
const isConverted = req.headers[reqConsts.requestHeaders.FileConversion.toLowerCase()];
console.log(`putRelativeFile after conversation: ${isConverted}`);
// if we got here, then we can save a file
saveFileFromBody(req, filename, userAddress, false, (err) => {
if (err) {
res.sendStatus(404);
return;
}
const serverUrl = req.DocManager.getServerUrl(true);
const fileActionUrl = `${serverUrl}/wopi-action/${filename}?action=`;
const fileInfo = {
Name: filename,
Url: `${serverUrl}/wopi/files/${filename}`,
HostViewUrl: `${fileActionUrl}view`,
HostEditNewUrl: `${fileActionUrl}editnew`,
HostEditUrl: `${fileActionUrl}edit`,
};
res.status(200).send(fileInfo);
});
};
// return information about the file properties, access rights and editor settings
const checkFileInfo = function checkFileInfo(wopi, req, res, userHost) {
const userAddress = req.DocManager.curUserHostAddress(userHost);
const version = req.DocManager.getKey(wopi.id, userAddress);
const storagePath = req.DocManager.storagePath(wopi.id, userAddress);
// add wopi query
const query = new URLSearchParams(wopi.accessToken);
const user = users.getUser(query.get('userid'));
// create the file information object
const fileInfo = {
BaseFileName: wopi.id,
OwnerId: req.DocManager.getFileData(wopi.id, userAddress)[1],
Size: fileSystem.statSync(storagePath).size,
UserId: user.id,
UserFriendlyName: user.name,
Version: version,
UserCanWrite: true,
SupportsGetLock: true,
SupportsLocks: true,
SupportsUpdate: true,
};
res.status(200).send(fileInfo);
};
// parse wopi request
const parseWopiRequest = function parseWopiRequest(req) {
const wopiData = {
requestType: reqConsts.requestType.None,
accessToken: req.query.access_token,
id: req.params.id,
};
// get the request path
const reqPath = req.path.substring('/wopi/'.length);
if (reqPath.startsWith('files')) { // if it starts with "files"
if (reqPath.endsWith('/contents')) { // ends with "/contents"
if (req.method === 'GET') { // and the request method is GET
wopiData.requestType = reqConsts.requestType.GetFile; // then the request type is GetFile
} else if (req.method === 'POST') { // if the request method is POST
wopiData.requestType = reqConsts.requestType.PutFile; // then the request type is PutFile
}
} else if (req.method === 'GET') { // otherwise, if the request method is GET
wopiData.requestType = reqConsts.requestType.CheckFileInfo; // the request type is CheckFileInfo
} else if (req.method === 'POST') { // if the request method is POST
// get the X-WOPI-Override header which determines the request type
const wopiOverride = req.headers[reqConsts.requestHeaders.RequestType.toLowerCase()];
switch (wopiOverride) {
case 'LOCK': // if it is equal to LOCK
// check if the request sends the X-WOPI-OldLock header
if (req.headers[reqConsts.requestHeaders.OldLock.toLowerCase()]) {
// if yes, then the request type is UnlockAndRelock
wopiData.requestType = reqConsts.requestType.UnlockAndRelock;
} else {
wopiData.requestType = reqConsts.requestType.Lock; // otherwise, it is Lock
}
break;
case 'GET_LOCK': // if it is equal to GET_LOCK
wopiData.requestType = reqConsts.requestType.GetLock; // the request type is GetLock
break;
case 'REFRESH_LOCK': // if it is equal to REFRESH_LOCK
wopiData.requestType = reqConsts.requestType.RefreshLock; // the request type is RefreshLock
break;
case 'UNLOCK': // if it is equal to UNLOCK
wopiData.requestType = reqConsts.requestType.Unlock; // the request type is Unlock
break;
case 'PUT_RELATIVE': // if it is equal to PUT_RELATIVE
// the request type is PutRelativeFile (creates a new file on the host based on the current file)
wopiData.requestType = reqConsts.requestType.PutRelativeFile;
break;
case 'RENAME_FILE': // if it is equal to RENAME_FILE
wopiData.requestType = reqConsts.requestType.RenameFile; // the request type is RenameFile (renames a file)
break;
case 'PUT_USER_INFO': // if it is equal to PUT_USER_INFO
// the request type is PutUserInfo (stores some basic user information on the host)
wopiData.requestType = reqConsts.requestType.PutUserInfo;
break;
default:
}
}
}
return wopiData;
};
const actionMapping = {};
actionMapping[reqConsts.requestType.GetFile] = getFile;
@ -36,352 +365,33 @@ actionMapping[reqConsts.requestType.GetLock] = getLock;
actionMapping[reqConsts.requestType.RefreshLock] = refreshLock;
actionMapping[reqConsts.requestType.Unlock] = unlock;
// parse wopi request
function parseWopiRequest(req) {
let wopiData = {
requestType: reqConsts.requestType.None,
accessToken: req.query["access_token"],
id: req.params['id']
}
// get the request path
let reqPath = req.path.substring("/wopi/".length)
if (reqPath.startsWith("files")) { // if it starts with "files"
if (reqPath.endsWith("/contents")) { // ends with "/contents"
if (req.method == "GET") { // and the request method is GET
wopiData.requestType = reqConsts.requestType.GetFile; // then the request type is GetFile
} else if (req.method == "POST") { // if the request method is POST
wopiData.requestType = reqConsts.requestType.PutFile; // then the request type is PutFile
}
} else {
if (req.method == "GET") { // otherwise, if the request method is GET
wopiData.requestType = reqConsts.requestType.CheckFileInfo; // the request type is CheckFileInfo
} else if (req.method == "POST") { // if the request method is POST
let wopiOverride = req.headers[reqConsts.requestHeaders.RequestType.toLowerCase()]; // get the X-WOPI-Override header which determines the request type
switch (wopiOverride) {
case "LOCK": // if it is equal to LOCK
if (req.headers[reqConsts.requestHeaders.OldLock.toLowerCase()]) { // check if the request sends the X-WOPI-OldLock header
wopiData.requestType = reqConsts.requestType.UnlockAndRelock; // if yes, then the request type is UnlockAndRelock
} else {
wopiData.requestType = reqConsts.requestType.Lock; // otherwise, it is Lock
}
break;
case "GET_LOCK": // if it is equal to GET_LOCK
wopiData.requestType = reqConsts.requestType.GetLock; // the request type is GetLock
break;
case "REFRESH_LOCK": // if it is equal to REFRESH_LOCK
wopiData.requestType = reqConsts.requestType.RefreshLock; // the request type is RefreshLock
break;
case "UNLOCK": // if it is equal to UNLOCK
wopiData.requestType = reqConsts.requestType.Unlock; // the request type is Unlock
break;
case "PUT_RELATIVE": // if it is equal to PUT_RELATIVE
wopiData.requestType = reqConsts.requestType.PutRelativeFile; // the request type is PutRelativeFile (creates a new file on the host based on the current file)
break;
case "RENAME_FILE": // if it is equal to RENAME_FILE
wopiData.requestType = reqConsts.requestType.RenameFile; // the request type is RenameFile (renames a file)
break;
case "PUT_USER_INFO": // if it is equal to PUT_USER_INFO
wopiData.requestType = reqConsts.requestType.PutUserInfo; // the request type is PutUserInfo (stores some basic user information on the host)
break;
}
}
}
} else if (reqPath.startsWith("folders")) {
}
return wopiData;
}
// lock file editing
function lock(wopi, req, res, userHost) {
let requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
let userAddress = req.docManager.curUserHostAddress(userHost); // get current user host address
let filePath = req.docManager.storagePath(wopi.id, userAddress); // get the storage path of the given file
if (!lockManager.hasLock(filePath)) {
// file isn't locked => lock
lockManager.lock(filePath, requestLock);
res.sendStatus(200);
} else if (lockManager.getLock(filePath) == requestLock) {
// lock matches current lock => extend duration
lockManager.lock(filePath, requestLock);
res.sendStatus(200);
} else {
// file locked by someone else => return lock mismatch
let lock = lockManager.getLock(filePath);
returnLockMismatch(res, lock, "File already locked by " + lock)
}
}
// retrieve a lock on a file
function getLock(wopi, req, res, userHost) {
let userAddress = req.docManager.curUserHostAddress(userHost);
let filePath = req.docManager.storagePath(wopi.id, userAddress);
// get the lock of the specified file and set it as the X-WOPI-Lock header
res.setHeader(reqConsts.requestHeaders.lock, lockManager.getLock(filePath));
res.sendStatus(200);
}
// refresh the lock on a file by resetting its automatic expiration timer to 30 minutes
function refreshLock(wopi, req, res, userHost) {
let requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
let userAddress = req.docManager.curUserHostAddress(userHost);
let filePath = req.docManager.storagePath(wopi.id, userAddress);
if (!lockManager.hasLock(filePath)) {
// file isn't locked => mismatch
returnLockMismatch(res, "", "File isn't locked");
} else if (lockManager.getLock(filePath) == requestLock) {
// lock matches current lock => extend duration
lockManager.lock(filePath, requestLock);
res.sendStatus(200);
} else {
// lock mismatch
returnLockMismatch(res, lockManager.getLock(filePath), "Lock mismatch");
}
}
// allow for file editing
function unlock(wopi, req, res, userHost) {
let requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
let userAddress = req.docManager.curUserHostAddress(userHost);
let filePath = req.docManager.storagePath(wopi.id, userAddress);
if (!lockManager.hasLock(filePath)) {
// file isn't locked => mismatch
returnLockMismatch(res, "", "File isn't locked");
} else if (lockManager.getLock(filePath) == requestLock) {
// lock matches current lock => unlock
lockManager.unlock(filePath);
res.sendStatus(200);
} else {
// lock mismatch
returnLockMismatch(res, lockManager.getLock(filePath), "Lock mismatch");
}
}
// allow for file editing, and then immediately take a new lock on the file
function unlockAndRelock(wopi, req, res, userHost) {
let requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
let oldLock = req.headers[reqConsts.requestHeaders.oldLock.toLowerCase()]; // get the X-WOPI-OldLock header
let userAddress = req.docManager.curUserHostAddress(userHost);
let filePath = req.docManager.storagePath(wopi.id, userAddress);
if (!lockManager.hasLock(filePath)) {
// file isn't locked => mismatch
returnLockMismatch(res, "", "File isn't locked");
} else if (lockManager.getLock(filePath) == oldLock) {
// lock matches current lock => lock with new key
lockManager.lock(filePath, requestLock);
res.sendStatus(200);
} else {
// lock mismatch
returnLockMismatch(res, lockManager.getLock(filePath), "Lock mismatch");
}
}
// request a message to retrieve a file
function getFile(wopi, req, res, userHost) {
let userAddress = req.docManager.curUserHostAddress(userHost);
let path = req.docManager.storagePath(wopi.id, userAddress);
res.setHeader("Content-Length", fileSystem.statSync(path).size);
res.setHeader("Content-Type", mime.getType(path));
res.setHeader("Content-Disposition", "attachment; filename*=UTF-8\'\'" + encodeURIComponent(wopi.id));
let filestream = fileSystem.createReadStream(path); // open a file as a readable stream
filestream.pipe(res); // retrieve data from file stream and output it to the response object
}
// request a message to update a file
function putFile(wopi, req, res, userHost) {
let requestLock = req.headers[reqConsts.requestHeaders.Lock.toLowerCase()];
let userAddress = req.docManager.curUserHostAddress(userHost);
let storagePath = req.docManager.storagePath(wopi.id, userAddress);
if (!lockManager.hasLock(storagePath)) {
// ToDo: if body length is 0 bytes => handle document creation
// file isn't locked => mismatch
returnLockMismatch(res, "", "File isn't locked");
} else if (lockManager.getLock(storagePath) == requestLock) {
// lock matches current lock => put file
saveFileFromBody(req, wopi.id, userAddress, true, (err, version) => {
if (!err) {
res.setHeader(reqConsts.requestHeaders.ItemVersion, version); // set the X-WOPI-ItemVersion header
}
res.sendStatus(err ? 404 : 200);
});
} else {
// lock mismatch
returnLockMismatch(res, lockManager.getLock(storagePath), "Lock mismatch");
}
}
function putRelativeFile(wopi, req, res, userHost) {
let userAddress = req.docManager.curUserHostAddress(userHost);
let storagePath = req.docManager.storagePath(wopi.id, userAddress);
let filename = req.headers[reqConsts.requestHeaders.RelativeTarget.toLowerCase()]; // we cannot modify this filename
if (filename) {
if (req.docManager.existsSync(storagePath)) { // check if already exists
let overwrite = req.headers[reqConsts.requestHeaders.OverwriteRelativeTarget.toLowerCase()]; // overwrite header
if (overwrite && overwrite === "true") { // check if we can overwrite
if (lockManager.hasLock(storagePath)) { // check if file locked
returnValidRelativeTarget(res, req.docManager.getCorrectName(wopi.id, userAddress)); // file is locked, cannot overwrite
return;
}
} else {
returnValidRelativeTarget(res, req.docManager.getCorrectName(wopi.id, userAddress)); // file exists and overwrite header is false
return;
}
}
} else {
filename = req.headers[reqConsts.requestHeaders.SuggestedTarget.toLowerCase()]; // we can modify this filename
if (filename.startsWith(".")) { // check if extension
filename = fileUtility.getFileName(wopi.id, true) + filename; // get original filename with new extension
}
filename = req.docManager.getCorrectName(filename, userAddress); // get correct filename if already exists
}
let isConverted = req.headers[reqConsts.requestHeaders.FileConversion.toLowerCase()];
console.log("putRelativeFile after conversation: " + isConverted);
// if we got here, then we can save a file
saveFileFromBody(req, filename, userAddress, false, (err) => {
if (err) {
res.sendStatus(404);
return;
}
let serverUrl = req.docManager.getServerUrl(true);
let fileActionUrl = serverUrl + "/wopi-action/" + filename + "?action=";
let fileInfo = {
"Name": filename,
"Url": serverUrl + "/wopi/files/" + filename,
"HostViewUrl": fileActionUrl + "view",
"HostEditNewUrl": fileActionUrl + "editnew",
"HostEditUrl": fileActionUrl + "edit",
};
res.status(200).send(fileInfo);
});
}
// return information about the file properties, access rights and editor settings
function checkFileInfo(wopi, req, res, userHost) {
let userAddress = req.docManager.curUserHostAddress(userHost);
let version = req.docManager.getKey(wopi.id, userAddress);
let path = req.docManager.storagePath(wopi.id, userAddress);
// add wopi query
var query = new URLSearchParams(wopi.accessToken);
let user = users.getUser(query.get("userid"));
// create the file information object
let fileInfo = {
"BaseFileName": wopi.id,
"OwnerId": req.docManager.getFileData(wopi.id, userAddress)[1],
"Size": fileSystem.statSync(path).size,
"UserId": user.id,
"UserFriendlyName": user.name,
"Version": version,
"UserCanWrite": true,
"SupportsGetLock": true,
"SupportsLocks": true,
"SupportsUpdate": true,
};
res.status(200).send(fileInfo);
}
function saveFileFromBody(req, filename, userAddress, isNewVersion, callback) {
if (req.body) {
var storagePath = req.docManager.storagePath(filename, userAddress);
var historyPath = req.docManager.historyPath(filename, userAddress); // get the path to the file history
if (historyPath == "") { // if it is empty
historyPath = req.docManager.historyPath(filename, userAddress, true); // create it
req.docManager.createDirectory(historyPath); // and create a new directory for the history
}
var version = 0;
if (isNewVersion) {
var count_version = req.docManager.countVersion(historyPath); // get the last file version
version = count_version + 1; // get a number of a new file version
var versionPath = req.docManager.versionPath(filename, userAddress, version); // get the path to the specified file version
req.docManager.createDirectory(versionPath); // and create a new directory for the specified version
var path_prev = path.join(versionPath, "prev" + fileUtility.getFileExtension(filename)); // get the path to the previous file version
fileSystem.renameSync(storagePath, path_prev); // synchronously rename the given file as the previous file version
}
let filestream = fileSystem.createWriteStream(storagePath);
req.pipe(filestream);
req.on('end', () => {
filestream.close();
callback(null, version);
})
} else {
callback("empty body");
}
}
// return name that wopi-client can use as the value of X-WOPI-RelativeTarget in a future PutRelativeFile operation
function returnValidRelativeTarget(res, filename) {
res.setHeader(reqConsts.requestHeaders.ValidRelativeTarget, filename); // set the X-WOPI-ValidRelativeTarget header
res.sendStatus(409); // file with that name already exists
}
// return lock mismatch
function returnLockMismatch(res, lock, reason) {
res.setHeader(reqConsts.requestHeaders.Lock, lock || ""); // set the X-WOPI-Lock header
if (reason) { // if there is a reason for lock mismatch
res.setHeader(reqConsts.requestHeaders.LockFailureReason, reason); // set it as the X-WOPI-LockFailureReason header
}
res.sendStatus(409); // conflict
}
exports.fileRequestHandler = (req, res) => {
let userAddress = null;
req.docManager = new docManager(req, res);
if (req.params['id'].includes("@")) { // if there is the "@" sign in the id parameter
let split = req.params['id'].split("@"); // split this parameter by "@"
req.params['id'] = split[0]; // rewrite id with the first part of the split parameter
userAddress = split[1]; // save the second part as the user address
}
let userAddress = null;
req.DocManager = new DocManager(req, res);
if (req.params.id.includes('@')) { // if there is the "@" sign in the id parameter
const split = req.params.id.split('@'); // split this parameter by "@"
[req.params.id] = split; // rewrite id with the first part of the split parameter
[, userAddress] = split; // save the second part as the user address
}
let wopiData = parseWopiRequest(req); // get the wopi data
const wopiData = parseWopiRequest(req); // get the wopi data
// an error of the unknown request type
if (wopiData.requestType == reqConsts.requestType.None) {
res.status(500).send({ 'title': 'fileHandler', 'method': req.method, 'id': req.params['id'], 'error': "unknown" });
return;
}
// an error of the unknown request type
if (wopiData.requestType === reqConsts.requestType.None) {
res.status(500).send({
title: 'fileHandler', method: req.method, id: req.params.id, error: 'unknown',
});
return;
}
// an error of the unsupported request type
let action = actionMapping[wopiData.requestType];
if (!action) {
res.status(501).send({ 'title': 'fileHandler', 'method': req.method, 'id': req.params['id'], 'error': "unsupported" });
return;
}
// an error of the unsupported request type
const action = actionMapping[wopiData.requestType];
if (!action) {
res.status(501).send({
title: 'fileHandler', method: req.method, id: req.params.id, error: 'unsupported',
});
return;
}
action(wopiData, req, res, userAddress);
}
action(wopiData, req, res, userAddress);
};

View File

@ -16,54 +16,54 @@
*
*/
var lockDict = {};
const lockDict = {};
// get the lock object of the specified file
function getLockObject(filePath) {
return lockDict[filePath];
}
const getLockObject = function getLockObject(filePath) {
return lockDict[filePath];
};
// clear the lock timeout
function clearLockTimeout(lockObject) {
if (lockObject && lockObject.timeout) {
clearTimeout(lockObject.timeout);
}
}
const clearLockTimeout = function clearLockTimeout(lockObject) {
if (lockObject && lockObject.timeout) {
clearTimeout(lockObject.timeout);
}
};
// get the lock value of the specified file
function getLockValue(filePath) {
let lock = getLockObject(filePath); // get the lock object of the specified file
if (lock) return lock.value; // if it exists, get the lock value from it
return "";
}
const getLockValue = function getLockValue(filePath) {
const lock = getLockObject(filePath); // get the lock object of the specified file
if (lock) return lock.value; // if it exists, get the lock value from it
return '';
};
// check if the specified file path has lock or not
function hasLock(filePath) {
return !!getLockObject(filePath);
}
// lock file editing
function lock(filePath, lockValue) {
let oldLock = getLockObject(filePath); // get the old lock of the specified file
clearLockTimeout(oldLock); // clear its timeout
// create a new lock object
lockDict[filePath] = {
value: lockValue,
timeout: setTimeout(unlock, 1000 * 60 * 30, filePath) // set lock for 30 minutes
}
}
const hasLock = function hasLock(filePath) {
return !!getLockObject(filePath);
};
// allow for file editing
function unlock(filePath) {
let lock = getLockObject(filePath); // get the lock of the specified file
clearLockTimeout(lock); // clear its timeout
delete lockDict[filePath]; // delete the lock
}
const unlock = function unlock(filePath) {
const lock = getLockObject(filePath); // get the lock of the specified file
clearLockTimeout(lock); // clear its timeout
delete lockDict[filePath]; // delete the lock
};
// lock file editing
const lock = function lock(filePath, lockValue) {
const oldLock = getLockObject(filePath); // get the old lock of the specified file
clearLockTimeout(oldLock); // clear its timeout
// create a new lock object
lockDict[filePath] = {
value: lockValue,
timeout: setTimeout(unlock, 1000 * 60 * 30, filePath), // set lock for 30 minutes
};
};
module.exports = {
hasLock: hasLock,
getLock: getLockValue,
lock: lock,
unlock: unlock
}
hasLock,
getLock: getLockValue,
lock,
unlock,
};

View File

@ -18,55 +18,55 @@
// request types
const requestType = Object.freeze({
"None": 0,
None: 0,
"CheckFileInfo": 1,
"PutRelativeFile": 2,
CheckFileInfo: 1,
PutRelativeFile: 2,
"Lock": 3,
"GetLock": 4,
"Unlock": 5,
"RefreshLock": 6,
"UnlockAndRelock": 7,
Lock: 3,
GetLock: 4,
Unlock: 5,
RefreshLock: 6,
UnlockAndRelock: 7,
"ExecuteCobaltRequest": 8,
ExecuteCobaltRequest: 8,
"DeleteFile": 9,
"ReadSecureStore": 10,
"GetRestrictedLink": 11,
"RevokeRestrictedLink": 12,
DeleteFile: 9,
ReadSecureStore: 10,
GetRestrictedLink: 11,
RevokeRestrictedLink: 12,
"CheckFolderInfo": 13,
CheckFolderInfo: 13,
"GetFile": 14,
"PutFile": 16,
GetFile: 14,
PutFile: 16,
"EnumerateChildren": 16,
EnumerateChildren: 16,
"RenameFile": 17,
"PutUserInfo": 18,
RenameFile: 17,
PutUserInfo: 18,
});
// request headers
const requestHeaders = Object.freeze({
"RequestType": "X-WOPI-Override",
"ItemVersion": "X-WOPI-ItemVersion",
RequestType: 'X-WOPI-Override',
ItemVersion: 'X-WOPI-ItemVersion',
"Lock": "X-WOPI-Lock",
"OldLock": "X-WOPI-OldLock",
"LockFailureReason": "X-WOPI-LockFailureReason",
"LockedByOtherInterface": "X-WOPI-LockedByOtherInterface",
Lock: 'X-WOPI-Lock',
OldLock: 'X-WOPI-OldLock',
LockFailureReason: 'X-WOPI-LockFailureReason',
LockedByOtherInterface: 'X-WOPI-LockedByOtherInterface',
"FileConversion": "X-WOPI-FileConversion",
FileConversion: 'X-WOPI-FileConversion',
"SuggestedTarget": "X-WOPI-SuggestedTarget",
"RelativeTarget": "X-WOPI-RelativeTarget",
"OverwriteRelativeTarget": "X-WOPI-OverwriteRelativeTarget",
SuggestedTarget: 'X-WOPI-SuggestedTarget',
RelativeTarget: 'X-WOPI-RelativeTarget',
OverwriteRelativeTarget: 'X-WOPI-OverwriteRelativeTarget',
"ValidRelativeTarget": "X-WOPI-ValidRelativeTarget",
ValidRelativeTarget: 'X-WOPI-ValidRelativeTarget',
});
module.exports = {
requestType: requestType,
requestHeaders: requestHeaders,
}
requestType,
requestHeaders,
};

View File

@ -16,8 +16,4 @@
*
*/
exports.isValidToken = (req, res, next) => {
if (true) {
return next();
}
}
exports.isValidToken = (req, res, next) => next();

View File

@ -16,129 +16,139 @@
*
*/
const config = require("config");
const configServer = config.get("server");
var urlModule = require("url");
var urllib = require("urllib");
const xmlParser = require("fast-xml-parser");
const he = require("he");
const siteUrl = configServer.get("siteUrl"); // the path to the editors installation
const config = require('config');
const urlModule = require('url');
const urllib = require('urllib');
const xmlParser = require('fast-xml-parser');
const he = require('he');
var cache = null;
const configServer = config.get('server');
const siteUrl = configServer.get('siteUrl'); // the path to the editors installation
async function initWopi(docManager) {
let absSiteUrl = siteUrl;
if (absSiteUrl.indexOf("/") === 0) {
absSiteUrl = docManager.getServerHost() + siteUrl;
}
let cache = null;
// get the wopi discovery information
await getDiscoveryInfo(absSiteUrl);
}
const requestDiscovery = async function requestDiscovery(url) {
// eslint-disable-next-line no-unused-vars
return new Promise((resolve, reject) => {
const actions = [];
urllib.request(urlModule.parse(url + configServer.get('wopi.discovery')), { method: 'GET' }, (err, data) => {
if (data) {
// create the discovery XML file with the parameters from the response
const discovery = xmlParser.parse(data.toString(), {
attributeNamePrefix: '',
ignoreAttributes: false,
parseAttributeValue: true,
// eslint-disable-next-line no-unused-vars
attrValueProcessor: (val, attrName) => he.decode(val, { isAttributeValue: true }),
});
if (discovery['wopi-discovery']) {
discovery['wopi-discovery']['net-zone'].app.forEach((app) => {
let appAction = app.action;
if (!Array.isArray(appAction)) {
appAction = [appAction];
}
appAction.forEach((action) => {
actions.push({ // write all the parameters to the actions element
app: app.name,
favIconUrl: app.favIconUrl,
checkLicense: app.checkLicense === 'true',
name: action.name,
ext: action.ext || '',
progid: action.progid || '',
isDefault: !!action.default,
urlsrc: action.urlsrc,
requires: action.requires || '',
});
});
});
}
}
resolve(actions);
});
});
};
// get the wopi discovery information
async function getDiscoveryInfo(siteUrl) {
let actions = [];
const getDiscoveryInfo = async function getDiscoveryInfo(url) {
let actions = [];
if (cache) return cache;
try {
actions = await requestDiscovery(siteUrl);
} catch (e) {
return actions;
}
cache = actions;
setTimeout(() => cache = null, 1000 * 60 * 60); // 1 hour
if (cache) return cache;
try {
actions = await requestDiscovery(url);
} catch (e) {
return actions;
}
}
async function requestDiscovery(siteUrl) {
return new Promise((resolve, reject) => {
var actions = [];
urllib.request(urlModule.parse(siteUrl + configServer.get("wopi.discovery")), {method: "GET"}, (err, data) => {
if (data) {
let discovery = xmlParser.parse(data.toString(), { // create the discovery XML file with the parameters from the response
attributeNamePrefix: "",
ignoreAttributes: false,
parseAttributeValue: true,
attrValueProcessor: (val, attrName) => he.decode(val, {isAttributeValue: true})
});
if (discovery["wopi-discovery"]) {
for (let app of discovery["wopi-discovery"]["net-zone"].app) {
if (!Array.isArray(app.action)) {
app.action = [app.action];
}
for (let action of app.action) {
actions.push({ // write all the parameters to the actions element
app: app.name,
favIconUrl: app.favIconUrl,
checkLicense: app.checkLicense == 'true',
name: action.name,
ext: action.ext || "",
progid: action.progid || "",
isDefault: action.default ? true : false,
urlsrc: action.urlsrc,
requires: action.requires || ""
});
}
}
}
}
resolve(actions);
});
})
}
cache = actions;
setTimeout(() => {
cache = null;
return cache;
}, 1000 * 60 * 60); // 1 hour
return actions;
};
const initWopi = async function initWopi(DocManager) {
let absSiteUrl = siteUrl;
if (absSiteUrl.indexOf('/') === 0) {
absSiteUrl = DocManager.getServerHost() + siteUrl;
}
// get the wopi discovery information
await getDiscoveryInfo(absSiteUrl);
};
// get actions of the specified extension
async function getActions(ext) {
let actions = await getDiscoveryInfo(); // get the wopi discovery information
let filtered = [];
const getActions = async function getActions(ext) {
const actions = await getDiscoveryInfo(); // get the wopi discovery information
const filtered = [];
for (let action of actions) { // and filter it by the specified extention
if (action.ext == ext) {
filtered.push(action);
}
actions.forEach((action) => { // and filter it by the specified extention
if (action.ext === ext) {
filtered.push(action);
}
});
return filtered;
}
return filtered;
};
// get an action for the specified extension and name
async function getAction(ext, name) {
let actions = await getDiscoveryInfo();
const getAction = async function getAction(ext, name) {
const actions = await getDiscoveryInfo();
let act = null;
for (let action of actions) {
if (action.ext == ext && action.name == name) {
return action;
}
actions.forEach((action) => {
if (action.ext === ext && action.name === name) {
act = action;
}
});
return null;
}
return act;
};
// get the default action for the specified extension
async function getDefaultAction(ext) {
let actions = await getDiscoveryInfo();
const getDefaultAction = async function getDefaultAction(ext) {
const actions = await getDiscoveryInfo();
let act = null;
for (let action of actions) {
if (action.ext == ext && action.isDefault) {
return action;
}
actions.forEach((action) => {
if (action.ext === ext && action.isDefault) {
act = action;
}
});
return null;
}
return act;
};
// get the action url
function getActionUrl(host, userAddress, action, filename) {
return action.urlsrc.replace(/<.*&>/g, "") + "WOPISrc=" + host + "/wopi/files/" + filename + "@" + userAddress;
}
const getActionUrl = function getActionUrl(host, userAddress, action, filename) {
return `${action.urlsrc.replace(/<.*&>/g, '')}WOPISrc=${host}/wopi/files/${filename}@${userAddress}`;
};
exports.initWopi = initWopi;
exports.getDiscoveryInfo = getDiscoveryInfo;
exports.getAction = getAction;
exports.getActions = getActions;
exports.getActionUrl = getActionUrl;
exports.getDefaultAction = getDefaultAction;
exports.getDefaultAction = getDefaultAction;

View File

@ -16,157 +16,159 @@
*
*/
const tokenValidator = require("./tokenValidator");
const filesController = require("./filesController");
const utils = require("./utils");
const docManager = require("../docManager");
const fileUtility = require("../fileUtility");
const config = require('config');
const tokenValidator = require('./tokenValidator');
const filesController = require('./filesController');
const utils = require('./utils');
const DocManager = require('../docManager');
const fileUtility = require('../fileUtility');
const users = require('../users');
const configServer = config.get('server');
const siteUrl = configServer.get("siteUrl"); // the path to the editors installation
const users = require("../users");
const siteUrl = configServer.get('siteUrl'); // the path to the editors installation
getCustomWopiParams = function (query) {
let tokenParams = "";
let actionParams = "";
const getCustomWopiParams = function getCustomWopiParams(query) {
let tokenParams = '';
let actionParams = '';
const userid = query.userid; // user id
tokenParams += (userid ? "&userid=" + userid : "");
const { userid } = query; // user id
tokenParams += (userid ? `&userid=${userid}` : '');
const lang = query.lang; // language
actionParams += (lang ? "&ui=" + lang : "");
const { lang } = query; // language
actionParams += (lang ? `&ui=${lang}` : '');
return { "tokenParams": tokenParams, "actionParams": actionParams };
return { tokenParams, actionParams };
};
exports.registerRoutes = function(app) {
exports.registerRoutes = function registerRoutes(app) {
// define a handler for the default wopi page
app.get('/wopi', async (req, res) => {
req.DocManager = new DocManager(req, res);
// define a handler for the default wopi page
app.get("/wopi", async function(req, res) {
await utils.initWopi(req.DocManager);
req.docManager = new docManager(req, res);
// get the wopi discovery information
const actions = await utils.getDiscoveryInfo();
const wopiEnable = actions.length !== 0;
const docsExtEdit = []; // Supported extensions for WOPI
await utils.initWopi(req.docManager);
// get the wopi discovery information
let actions = await utils.getDiscoveryInfo();
let wopiEnable = actions.length != 0 ? true : false;
let docsExtEdit = []; // Supported extensions for WOPI
actions.forEach(el => {
if (el.name == "edit") docsExtEdit.push("."+el.ext);
});
let editedExts = configServer.get('editedDocs').filter(i => docsExtEdit.includes(i)); // Checking supported extensions
let fillExts = configServer.get("fillDocs").filter(i => docsExtEdit.includes(i));
try {
// get all the stored files
let files = req.docManager.getStoredFiles();
// run through all the files and write the corresponding information to each file
for (var file of files) {
let ext = fileUtility.getFileExtension(file.name, true); // get an extension of each file
file.actions = await utils.getActions(ext); // get actions of the specified extension
file.defaultAction = await utils.getDefaultAction(ext); // get the default action of the specified extension
}
// render wopiIndex template with the parameters specified
res.render("wopiIndex", {
wopiEnable : wopiEnable,
storedFiles: wopiEnable ? files : [],
params: req.docManager.getCustomParams(),
users: users,
serverUrl: req.docManager.getServerUrl(),
preloaderUrl: siteUrl + configServer.get('preloaderUrl'),
convertExts: configServer.get('convertedDocs'),
editedExts: editedExts,
fillExts: fillExts,
languages: configServer.get('languages'),
});
} catch (ex) {
console.log(ex); // display error message in the console
res.status(500); // write status parameter to the response
res.render("error", { message: "Server error" }); // render error template with the message parameter specified
return;
}
});
// define a handler for creating a new wopi editing session
app.get("/wopi-new", function(req, res) {
var fileExt = req.query.fileExt; // get the file extension from the request
req.docManager = new docManager(req, res);
if (fileExt != null) { // if the file extension exists
var fileName = req.docManager.getCorrectName("new." + fileExt)
var redirectPath = req.docManager.getServerUrl(true) + "/wopi-action/" + encodeURIComponent(fileName) + "?action=editnew" + req.docManager.getCustomParams(); // get the redirect path
res.redirect(redirectPath);
return;
}
});
// define a handler for getting wopi action information by its id
app.get("/wopi-action/:id", async function(req, res) {
try {
req.docManager = new docManager(req, res);
await utils.initWopi(req.docManager);
var fileName = req.docManager.getCorrectName(req.params['id'])
var fileExt = fileUtility.getFileExtension(fileName, true); // get the file extension from the request
var user = users.getUser(req.query.userid); // get a user by the id
// get an action for the specified extension and name
let action = await utils.getAction(fileExt, req.query["action"]);
if (action != null && req.query["action"] == "editnew") {
fileName = req.docManager.RequestEditnew(req, fileName, user);
}
// render wopiAction template with the parameters specified
res.render("wopiAction", {
actionUrl: utils.getActionUrl(req.docManager.getServerUrl(true), req.docManager.curUserHostAddress(), action, req.params['id']),
token: "test",
tokenTtl: Date.now() + 1000 * 60 * 60 * 10,
params: getCustomWopiParams(req.query),
});
} catch (ex) {
console.log(ex);
res.status(500);
res.render("error", { message: "Server error" });
return;
}
actions.forEach((el) => {
if (el.name === 'edit') docsExtEdit.push(`.${el.ext}`);
});
// define a handler for getting file information by its id
app.route('/wopi/files/:id')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
// Checking supported extensions
const editedExts = configServer.get('editedDocs').filter((i) => docsExtEdit.includes(i));
const fillExts = configServer.get('fillDocs').filter((i) => docsExtEdit.includes(i));
// define a handler for reading/writing the file contents
app.route('/wopi/files/:id/contents')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
try {
// get all the stored files
const files = req.DocManager.getStoredFiles();
// define a handler for getting folder information by its id
app.route('/wopi/folders/:id')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
// run through all the files and write the corresponding information to each file
// eslint-disable-next-line no-restricted-syntax
for (const file of files) {
const ext = fileUtility.getFileExtension(file.name, true); // get an extension of each file
// eslint-disable-next-line no-await-in-loop
file.actions = await utils.getActions(ext); // get actions of the specified extension
// eslint-disable-next-line no-await-in-loop
file.defaultAction = await utils.getDefaultAction(ext);// get the default action of the specified extension
}
// define a handler for reading/writing the folder contents
app.route('/wopi/folders/:id/contents')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
// render wopiIndex template with the parameters specified
res.render('wopiIndex', {
wopiEnable,
storedFiles: wopiEnable ? files : [],
params: req.DocManager.getCustomParams(),
users,
preloaderUrl: siteUrl + configServer.get('preloaderUrl'),
convertExts: configServer.get('convertedDocs'),
editedExts,
fillExts,
languages: configServer.get('languages'),
});
} catch (ex) {
console.log(ex); // display error message in the console
res.status(500); // write status parameter to the response
res.render('error', { message: 'Server error' }); // render error template with the message parameter specified
}
});
// define a handler for creating a new wopi editing session
app.get('/wopi-new', (req, res) => {
const { fileExt } = req.query; // get the file extension from the request
// define a handler for upload files
app.route('/wopi/upload')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
req.DocManager = new DocManager(req, res);
if (fileExt) { // if the file extension exists
const fileName = req.DocManager.getCorrectName(`new.${fileExt}`);
const redirectPath = `${req.DocManager.getServerUrl(true)}/wopi-action/`
+ `${encodeURIComponent(fileName)}?action=editnew${req.DocManager.getCustomParams()}`; // get the redirect path
res.redirect(redirectPath);
}
});
// define a handler for getting wopi action information by its id
app.get('/wopi-action/:id', async (req, res) => {
try {
req.DocManager = new DocManager(req, res);
await utils.initWopi(req.DocManager);
let fileName = req.DocManager.getCorrectName(req.params.id);
const fileExt = fileUtility.getFileExtension(fileName, true); // get the file extension from the request
const user = users.getUser(req.query.userid); // get a user by the id
// get an action for the specified extension and name
const action = await utils.getAction(fileExt, req.query.action);
if (action && req.query.action === 'editnew') {
fileName = req.DocManager.requestEditnew(req, fileName, user);
}
// render wopiAction template with the parameters specified
res.render('wopiAction', {
actionUrl: utils.getActionUrl(
req.DocManager.getServerUrl(true),
req.DocManager.curUserHostAddress(),
action,
req.params.id,
),
token: 'test',
tokenTtl: Date.now() + 1000 * 60 * 60 * 10,
params: getCustomWopiParams(req.query),
});
} catch (ex) {
console.log(ex);
res.status(500);
res.render('error', { message: 'Server error' });
}
});
// define a handler for getting file information by its id
app.route('/wopi/files/:id')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
// define a handler for reading/writing the file contents
app.route('/wopi/files/:id/contents')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
// define a handler for getting folder information by its id
app.route('/wopi/folders/:id')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
// define a handler for reading/writing the folder contents
app.route('/wopi/folders/:id/contents')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
// define a handler for upload files
app.route('/wopi/upload')
.all(tokenValidator.isValidToken)
.get(filesController.fileRequestHandler)
.post(filesController.fileRequestHandler);
};

View File

@ -34,30 +34,17 @@ if (typeof jQuery != "undefined") {
else
language = jq("#language").val();
jq("#language").change(function() {
window.location = "?lang=" + jq(this).val() + "&userid=" + userid + "&directUrl=" + directUrl;
});
if ("" != userid && undefined != userid)
jq("#user").val(userid);
else
userid = jq("#user").val();
jq("#user").change(function() {
window.location = "?lang=" + language + "&userid=" + jq(this).val() + "&directUrl=" + directUrl;
});
if (directUrl)
jq("#directUrl").prop("checked", directUrl);
else
directUrl = jq("#directUrl").prop("checked");
jq("#directUrl").change(function() {
window.location = "?lang=" + language + "&userid=" + userid + "&directUrl=" + jq(this).prop("checked");
});
jq(function () {
jq('#fileupload').fileupload({
@ -111,7 +98,7 @@ if (typeof jQuery != "undefined") {
}
});
});
var timer = null;
var checkConvert = function (filePass) {
filePass = filePass ? filePass : null;
@ -230,6 +217,20 @@ if (typeof jQuery != "undefined") {
}
});
jq(document).on("click", ".action-link", function (e) {
e.preventDefault();
let url = this.href + collectParams(true);
let target = null;
if (e.target.hasAttribute("target")) {
target = e.target.getAttribute("target");
} else if (e.target.parentNode.hasAttribute("target")) {
target = e.target.parentNode.getAttribute("target");
}
target !== null ? window.open(url, target) : window.location = url;
});
jq(document).on("click", "#skipPass", function () {
jq("#blockPassword").hide();
loadScripts();
@ -238,32 +239,32 @@ if (typeof jQuery != "undefined") {
jq(document).on("click", "#beginEdit:not(.disable)", function () {
var fileId = encodeURIComponent(jq('#hiddenFileName').val());
if (UrlEditor == "wopi-action"){
var url = UrlEditor + "/" + fileId + "?action=edit";
var url = UrlEditor + "/" + fileId + "?action=edit" + collectParams(true);
}else{
var url = UrlEditor + "?fileName=" + fileId + "&lang=" + language + "&userid=" + userid + "&directUrl=" + directUrl;
var url = UrlEditor + "?fileName=" + fileId + collectParams(true);
}
window.open(url, "_blank");
jq('#hiddenFileName').val("");
jq.unblockUI();
document.location.reload(true);
window.location = collectParams();
});
jq(document).on("click", "#beginView:not(.disable)", function () {
var fileId = encodeURIComponent(jq('#hiddenFileName').val());
if (UrlEditor == "wopi-action"){
var url = UrlEditor + "/" + fileId + "?action=view";
var url = UrlEditor + "/" + fileId + "?action=view" + collectParams(true);
}else{
var url = UrlEditor + "?mode=view&fileName=" + fileId + "&lang=" + language + "&userid=" + userid + "&directUrl=" + directUrl;
var url = UrlEditor + "?mode=view&fileName=" + fileId + collectParams(true);
}
window.open(url, "_blank");
jq('#hiddenFileName').val("");
jq.unblockUI();
document.location.reload(true);
window.location = collectParams();
});
jq(document).on("click", "#beginEmbedded:not(.disable)", function () {
var fileId = encodeURIComponent(jq('#hiddenFileName').val());
var url = UrlEditor + "?type=embedded&fileName=" + fileId + "&lang=" + language + "&userid=" + userid + "&directUrl=" + directUrl;
var url = UrlEditor + "?type=embedded&fileName=" + fileId + collectParams(true);
jq("#mainProgress").addClass("embedded");
jq("#beginEmbedded").addClass("disable");
@ -272,13 +273,13 @@ if (typeof jQuery != "undefined") {
});
jq(document).on("click", ".reload-page", function () {
setTimeout(function () { document.location.reload(true); }, 1000);
setTimeout(function () { window.location = collectParams(); }, 1000);
return true;
});
jq(document).on("mouseup", ".reload-page", function (event) {
if (event.which == 2) {
setTimeout(function () { document.location.reload(true); }, 1000);
setTimeout(function () { window.location = collectParams(); }, 1000);
}
return true;
});
@ -288,12 +289,13 @@ if (typeof jQuery != "undefined") {
jq("#embeddedView").remove();
jq.unblockUI();
if (mustReload) {
document.location.reload(true);
window.location = collectParams();
}
});
jq(document).on("click", ".delete-file", function () {
var fileName = jq(this).attr("data");
const currentElement = jq(this);
var fileName = currentElement.attr("data");
var requestAddress = "file?filename=" + fileName;
@ -303,7 +305,16 @@ if (typeof jQuery != "undefined") {
type: "delete",
url: requestAddress,
complete: function (data) {
document.location.reload(true);
if (JSON.parse(data.responseText).success) {
const parentRow = currentElement.parents('tr')[0];
if (parentRow) {
jq(parentRow).remove();
}
const remainingRows = jq('tr.tableRow');
if (remainingRows.length === 0) {
window.location = collectParams();
}
}
}
});
});
@ -394,4 +405,32 @@ function getUrlVars() {
vars[hash[0]] = hash[1];
}
return vars;
};
};
function collectParams(startParams) {
let paramsObjects = Array.prototype.slice.call(document.getElementsByClassName('collectable'));
let params = [];
let startChar = startParams ? "&" : "?";
paramsObjects.forEach( function (element) {
if (element.name) {
switch (element.type) {
case "select-one":
case "text":
if (element.value) {
params.push(element.name + "=" + element.value);
}
break;
case "checkbox":
params.push(element.name + "=" + element.checked);
break;
case "radio":
if (element.checked) {
params.push(element.name + "=" + element.value);
}
break;
default:
}
}
});
return startChar + params.join("&");
}

View File

@ -39,6 +39,7 @@
var docEditor;
var config;
let historyObject;
var innerAlert = function (message, inEditor) {
if (console && console.log)
@ -72,26 +73,72 @@
};
var onRequestHistory = function (event) { // the user is trying to show the document version history
var historyObj = <%- JSON.stringify(history) %> || null;
docEditor.refreshHistory( // show the document version history
const fileName = "<%- file.name %>" || null;
const directUrl = "<%- file.directUrl %>" || null;
const data = {
fileName: fileName,
directUrl: directUrl
};
let xhr = new XMLHttpRequest();
xhr.open("POST", "historyObj");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(data));
xhr.onload = function () {
historyObject = JSON.parse(xhr.responseText);
docEditor.refreshHistory( // show the document version history
{
currentVersion: "<%- file.version %>",
history: historyObj
currentVersion: historyObject.countVersion,
history: historyObject.history
});
}
};
var onRequestHistoryData = function (data) { // the user is trying to click the specific document version in the document version history
var version = data.data;
var historyData = <%- JSON.stringify(historyData) %> || null;
docEditor.setHistoryData(historyData[version-1]); // send the link to the document for viewing the version history
var onRequestHistoryData = function (event) { // the user is trying to click the specific document version in the document version history
const version = event.data;
docEditor.setHistoryData(historyObject.historyData[version-1]); // send the link to the document for viewing the version history
};
var onRequestHistoryClose = function (event){ // the user is trying to go back to the document from viewing the document version history
document.location.reload();
};
var onRequestRestore = function (event) { // the user is trying to restore file version
const version = event.data.version;
const fileName = "<%- file.name %>" || null;
const directUrl = "<%- file.directUrl %>" || null;
const restoreData = {
version: version,
fileName: fileName,
};
let xhr = new XMLHttpRequest();
xhr.open("PUT", "restore");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(restoreData));
xhr.onload = function () {
const response = JSON.parse(xhr.responseText);
if (response.success && !response.error) {
const dataForHistory = {
fileName: fileName,
directUrl: directUrl
};
let xhr = new XMLHttpRequest();
xhr.open("POST", "historyObj");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(dataForHistory));
xhr.onload = function () {
historyObject = JSON.parse(xhr.responseText);
docEditor.refreshHistory( // show the document version history
{
currentVersion: historyObject.countVersion,
history: historyObject.history
});
}
} else {
innerAlert(response.error);
}
}
}
var onError = function (event) { // an error or some other specific event occurs
if (event)
innerAlert(event.data);
@ -235,6 +282,7 @@
config.events.onRequestHistory = onRequestHistory;
config.events.onRequestHistoryData = onRequestHistoryData;
config.events.onRequestHistoryClose = onRequestHistoryClose;
config.events.onRequestRestore = onRequestRestore;
config.events.onRequestRename = onRequestRename;
config.events.onRequestUsers = onRequestUsers;
config.events.onRequestSendNotify = onRequestSendNotify;

View File

@ -32,7 +32,7 @@
<body>
<header>
<div class="center">
<a href="">
<a href="./">
<img src ="images/logo.svg" alt="ONLYOFFICE" />
</a>
</div>
@ -48,16 +48,16 @@
<div class="create-panel clearFix">
<ul class="try-editor-list clearFix">
<li>
<a class="try-editor word reload-page" target="_blank" href="editor?fileExt=docx<%= params %>" title="Create new document">Document</a>
<a class="try-editor word reload-page action-link" target="_blank" href="editor?fileExt=docx" title="Create new document">Document</a>
</li>
<li>
<a class="try-editor cell reload-page" target="_blank" href="editor?fileExt=xlsx<%= params %>" title="Create new spreadsheet">Spreadsheet</a>
<a class="try-editor cell reload-page action-link" target="_blank" href="editor?fileExt=xlsx" title="Create new spreadsheet">Spreadsheet</a>
</li>
<li>
<a class="try-editor slide reload-page" target="_blank" href="editor?fileExt=pptx<%= params %>" title="Create new presentation">Presentation</a>
<a class="try-editor slide reload-page action-link" target="_blank" href="editor?fileExt=pptx" title="Create new presentation">Presentation</a>
</li>
<li>
<a class="try-editor form reload-page" target="_blank" href="editor?fileExt=docxf<%= params %>" title="Create new form template">Form template</a>
<a class="try-editor form reload-page action-link" target="_blank" href="editor?fileExt=docxf" title="Create new form template">Form template</a>
</li>
</ul>
<label class="side-option">
@ -67,7 +67,7 @@
<div class="upload-panel clearFix">
<a class="file-upload">Upload file
<input type="file" id="fileupload" name="uploadedFile" data-url="upload?<%= params %>" />
<input type="file" id="fileupload" name="uploadedFile" data-url="upload" />
</a>
</div>
@ -77,7 +77,7 @@
<td valign="middle">
<span class="select-user">Username</span>
<img id="info" class="info" src="images/info.svg" />
<select class="select-user" id="user">
<select class="select-user collectable" name="userid" id="user">
<% users.forEach(user => { %>
<option value="<%= user.id %>"><%= user.name == null ? "Anonymous" : user.name %></option>
<% }) %>
@ -88,7 +88,7 @@
<td valign="middle">
<span class="select-user">Language</span>
<img class="info info-tooltip" data-id="language" data-tooltip="Choose the language for ONLYOFFICE editors interface" src="images/info.svg" />
<select class="select-user" id="language">
<select class="select-user collectable" name="lang" id="language">
<% Object.keys(languages).forEach(key => { %>
<option value="<%= key %>"><%= languages[key] %></option>
<% }) %>
@ -98,7 +98,7 @@
<tr>
<td valign="middle">
<label class="side-option">
<input id="directUrl" type="checkbox" class="checkbox" />Try opening on client
<input id="directUrl" type="checkbox" class="checkbox collectable" name="directUrl" />Try opening on client
<img id="directUrlInfo" class="info info-tooltip" data-id="directUrlInfo" data-tooltip="Some files can be opened in the user's browser without connecting to the document server." src="images/info.svg" />
</label>
</td>
@ -107,7 +107,7 @@
</table>
<div class="links-panel links-panel-border clearFix">
<a href="<%= serverUrl %>/wopi" class="">Go to WOPI page</a>
<a href="wopi" class="">Go to WOPI page</a>
</div>
</div>
</div>
@ -154,33 +154,33 @@
<% for (var i = 0; i < storedFiles.length; i++) { %>
<tr class="tableRow" title="<%= storedFiles[i].name %> [<%= storedFiles[i].version %>]">
<td class="contentCells">
<a class="stored-edit <%= storedFiles[i].documentType %>" href="editor?fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="stored-edit <%= storedFiles[i].documentType %> action-link" href="editor?fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<span><%= storedFiles[i].name %></span>
</a>
</td>
<% if (storedFiles[i].canEdit) { %>
<td class="contentCells contentCells-icon">
<a href="editor?type=desktop&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=desktop&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/desktop.svg" alt="Open in editor for full size screens" title="Open in editor for full size screens" /></a>
</td>
<td class="contentCells contentCells-icon">
<a href="editor?type=desktop&mode=comment&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=desktop&mode=comment&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/comment.svg" alt="Open in editor for comment" title="Open in editor for comment" /></a>
</td>
<% if (storedFiles[i].documentType == "word") { %>
<td class="contentCells contentCells-icon">
<a href="editor?type=desktop&mode=review&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=desktop&mode=review&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/review.svg" alt="Open in editor for review" title="Open in editor for review" /></a>
</td>
<% } else if (storedFiles[i].documentType == "cell") { %>
<td class="contentCells contentCells-icon">
<a href="editor?type=desktop&mode=filter&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=desktop&mode=filter&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/filter.svg" alt="Open in editor without access to change the filter" title="Open in editor without access to change the filter" /></a>
</td>
<% } %>
<% if (storedFiles[i].documentType == "word") { %>
<td class="contentCells contentCells-icon">
<a href="editor?type=desktop&mode=blockcontent&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=desktop&mode=blockcontent&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/block-content.svg" alt="Open in editor without content control modification" title="Open in editor without content control modification" /></a>
</td>
<% } else { %>
@ -191,14 +191,14 @@
<% } %>
<% if (fillExts.indexOf(storedFiles[i].name.substring(storedFiles[i].name.lastIndexOf('.')).trim().toLowerCase()) !== -1) { %>
<td class="contentCells contentCells-icon">
<a href="editor?type=desktop&mode=fillForms&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=desktop&mode=fillForms&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/fill-forms.svg" alt="Open in editor for filling in forms" title="Open in editor for filling in forms" /></a>
</td>
<% } else {%>
<td class="contentCells contentCells-icon"></td>
<%}%>
<td class="contentCells contentCells-shift contentCells-icon firstContentCellShift">
<a href="editor?type=mobile&mode=edit&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=mobile&mode=edit&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/mobile.svg" alt="Open in editor for mobile devices" title="Open in editor for mobile devices" /></a>
</td>
<% } else if (fillExts.indexOf(storedFiles[i].name.substring(storedFiles[i].name.lastIndexOf('.')).trim().toLowerCase()) !== -1) { %>
@ -207,26 +207,26 @@
<td class="contentCells contentCells-icon "></td>
<td class="contentCells contentCells-icon "></td>
<td class="contentCells contentCells-icon">
<a href="editor?type=desktop&mode=fillForms&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=desktop&mode=fillForms&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/fill-forms.svg" alt="Open in editor for filling in forms" title="Open in editor for filling in forms" /></a>
</td>
<td class="contentCells contentCells-shift contentCells-icon firstContentCellShift">
<a href="editor?type=mobile&mode=fillForms&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=mobile&mode=fillForms&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/mobile-fill-forms.svg" alt="Open in editor for filling in forms for mobile devices" title="Open in editor for filling in forms for mobile devices" /></a>
</td>
<% } else { %>
<td class="contentCells contentCells-shift contentCells-icon contentCellsEmpty" colspan="6"></td>
<% } %>
<td class="contentCells contentCells-icon firstContentCellViewers">
<a href="editor?type=desktop&mode=view&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=desktop&mode=view&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/desktop.svg" alt="Open in viewer for full size screens" title="Open in viewer for full size screens" /></a>
</td>
<td class="contentCells contentCells-icon">
<a href="editor?type=mobile&mode=view&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=mobile&mode=view&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/mobile.svg" alt="Open in viewer for mobile devices" title="Open in viewer for mobile devices" /></a>
</td>
<td class="contentCells contentCells-icon contentCells-shift">
<a href="editor?type=embedded&mode=embedded&fileName=<%= encodeURIComponent(storedFiles[i].name) + params %>" target="_blank">
<a class="action-link" href="editor?type=embedded&mode=embedded&fileName=<%= encodeURIComponent(storedFiles[i].name) %>" target="_blank">
<img src="images/embeded.svg" alt="Open in embedded mode" title="Open in embedded mode" /></a>
</td>
<td class="contentCells contentCells-icon contentCells-shift downloadContentCellShift">

View File

@ -35,7 +35,7 @@
<body>
<header>
<div class="center">
<a href="">
<a href="wopi">
<img src="images/logo.svg" alt="ONLYOFFICE" />
</a>
</div>
@ -51,16 +51,16 @@
<div class="create-panel clearFix">
<ul class="try-editor-list clearFix">
<li>
<a class="try-editor word reload-page" target="_blank" href="<%= serverUrl %>/wopi-new?fileExt=docx<%= params %>" title="Create new document">Document</a>
<a class="try-editor word reload-page action-link" target="_blank" href="wopi-new?fileExt=docx" title="Create new document">Document</a>
</li>
<li>
<a class="try-editor cell reload-page" target="_blank" href="<%= serverUrl %>/wopi-new?fileExt=xlsx<%= params %>" title="Create new spreadsheet">Spreadsheet</a>
<a class="try-editor cell reload-page action-link" target="_blank" href="wopi-new?fileExt=xlsx" title="Create new spreadsheet">Spreadsheet</a>
</li>
<li>
<a class="try-editor slide reload-page" target="_blank" href="<%= serverUrl %>/wopi-new?fileExt=pptx<%= params %>" title="Create new presentation">Presentation</a>
<a class="try-editor slide reload-page action-link" target="_blank" href="wopi-new?fileExt=pptx" title="Create new presentation">Presentation</a>
</li>
<li>
<a class="try-editor form reload-page" target="_blank" href="<%= serverUrl %>/wopi-new?fileExt=docxf<%= params %>" title="Create new form template">Form template</a>
<a class="try-editor form reload-page action-link" target="_blank" href="wopi-new?fileExt=docxf" title="Create new form template">Form template</a>
</li>
</ul>
</div>
@ -68,7 +68,7 @@
<div class="upload-panel clearFix">
<a class="file-upload">Upload file
<input type="file" id="fileupload" name="uploadedFile" data-url="upload?<%= params %>" />
<input type="file" id="fileupload" name="uploadedFile" data-url="upload" />
</a>
</div>
@ -78,7 +78,7 @@
<td valign="middle">
<span class="select-user">Username</span>
<img id="info" class="info" data-id="user" src="images/info.svg" />
<select class="select-user" id="user">
<select class="select-user collectable" name="userid" id="user">
<% users.forEach(user => { %>
<option value="<%= user.id %>"><%= user.name == null ? "Anonymous" : user.name %></option>
<% }) %>
@ -89,7 +89,7 @@
<td valign="middle">
<span class="select-user">Language</span>
<img class="info info-tooltip" data-id="language" data-tooltip="Choose the language for ONLYOFFICE editors interface" src="images/info.svg" />
<select class="select-user" id="language">
<select class="select-user collectable" name="lang" id="language">
<% Object.keys(languages).forEach(key => { %>
<option value="<%= key %>"><%= languages[key] %></option>
<% }) %>
@ -100,7 +100,7 @@
</table>
<div class="links-panel links-panel-border clearFix">
<a href="<%= serverUrl %>/" class="">Go to Index page</a>
<a href="./" class="">Go to Index page</a>
</div>
</div>
</td>
@ -148,7 +148,7 @@
<tr class="tableRow" title="<%= storedFiles[i].name %> [<%= storedFiles[i].version %>]">
<td class="contentCells">
<% if (storedFiles[i].defaultAction) { %>
<a class="stored-edit <%= storedFiles[i].documentType %>" href="<%= serverUrl %>/wopi-action/<%= encodeURIComponent(storedFiles[i].name) %>?action=<%= storedFiles[i].defaultAction.name %><%= params %>" target="_blank">
<a class="stored-edit <%= storedFiles[i].documentType %> action-link" href="wopi-action/<%= encodeURIComponent(storedFiles[i].name) %>?action=<%= storedFiles[i].defaultAction.name %>" target="_blank">
<%} else { %>
<a class="stored-edit <%= storedFiles[i].documentType %>" href="#">
<% } %>
@ -158,7 +158,7 @@
<% if (storedFiles[i].actions && storedFiles[i].actions.length > 0) { %>
<td class="contentCells contentCells-wopi contentCells-shift">
<% for (var j = 0; j < storedFiles[i].actions.length; j++) { %>
<a href="<%= serverUrl %>/wopi-action/<%= encodeURIComponent(storedFiles[i].name) %>?action=<%= storedFiles[i].actions[j].name %><%= params %>" target="_blank">
<a class="action-link" href="wopi-action/<%= encodeURIComponent(storedFiles[i].name) %>?action=<%= storedFiles[i].actions[j].name %>" target="_blank">
<img
src="images/wopi-<%= storedFiles[i].actions[j].name %>.svg"
alt="<%= storedFiles[i].actions[j].name %>" title="<%= storedFiles[i].actions[j].name %>" />
@ -167,7 +167,7 @@
</td>
<% } %>
<td class="contentCells contentCells-icon contentCells-shift downloadContentCells">
<a href="<%= serverUrl %>/wopi/files/<%= encodeURIComponent(storedFiles[i].name) %>/contents">
<a href="wopi/files/<%= encodeURIComponent(storedFiles[i].name) %>/contents">
<img class="icon-download" src="images/download.svg" alt="Download" title="Download" /></a>
</td>
<td class="contentCells contentCells-icon contentCells-shift">

View File

@ -34,6 +34,7 @@ You can use any web server capable of running PHP code to run the example. We wi
* **IIS**: version 7 or later (refer to [Microsoft official website](https://www.iis.net/learn/application-frameworks/scenario-build-a-php-website-on-iis/configuring-step-1-install-iis-and-php) to learn how to install IIS);
* **PHP** (download it from the [http://php.net](https://php.net/downloads.php) site);
* **PHP Manager for IIS** (download it from the [Microsoft open source site](https://phpmanager.codeplex.com/releases/view/69115)).
* **Composer** (download it from the [Composer official website](https://getcomposer.org/download/)).
### Step 4. IIS configuration
@ -78,7 +79,13 @@ You can use any web server capable of running PHP code to run the example. We wi
After IIS manager configuration is complete, everything is ready for running the PHP example.
### Step 5. Run your website with the editors
### Step 5. Run *composer install*:
```
php composer.phar install
```
### Step 6. Run your website with the editors
1. Add your website in the IIS Manager.
@ -100,7 +107,7 @@ You can use any web server capable of running PHP code to run the example. We wi
![browse](screenshots/browse.png)
### Step 6. Check accessibility
### Step 7. 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.
@ -124,8 +131,11 @@ See the detailed guide to learn how to [install Document Server for Linux](https
2. Install **Composer**:
To install composer globally, use the following command which will download and install Composer as a system-wide command named composer, under /usr/local/bin:
```
instructions should be here
curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php
sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer
```
3. Download the archive with the PHP example and unpack the archive:

View File

@ -895,8 +895,8 @@ function getResponseUri($document_response, &$response_uri)
*/
function tryGetDefaultByType($createExt, $user)
{
$demoName = ($_GET["sample"] ? "sample." : "new.") . $createExt;
$demoPath = "assets" . DIRECTORY_SEPARATOR . ($_GET["sample"] ? "sample" : "new") . DIRECTORY_SEPARATOR;
$demoName = (isset($_GET["sample"]) ? "sample." : "new.") . $createExt;
$demoPath = "assets" . DIRECTORY_SEPARATOR . (isset($_GET["sample"]) ? "sample" : "new") . DIRECTORY_SEPARATOR;
$demoFilename = GetCorrectName($demoName);
if (!@copy(dirname(__FILE__) . DIRECTORY_SEPARATOR . $demoPath . $demoName, getStoragePath($demoFilename))) {

View File

@ -49,7 +49,7 @@ final class DocEditorView extends View
if (!empty($externalUrl)) {
$filename = doUpload($externalUrl);
} else { // if the file url doesn't exist, get file name and file extension
$filename = basename($request["fileID"]);
$filename = basename($request["fileID"] ?? "");
}
$createExt = $request["fileExt"] ?? "";

View File

@ -0,0 +1,16 @@
# User-specific files: editor, system, etc.
.DS_Store
.idea
.project
.settings
.vs
.vscode
*.suo
*.user
# Project files.
bin
db
log
sorbet
tmp

View File

@ -0,0 +1 @@
3.2.2

View File

@ -0,0 +1,17 @@
FROM ruby:3.2.2-alpine3.18 AS example
WORKDIR /srv
COPY . .
RUN \
apk update && \
apk add --no-cache \
build-base \
gcompat \
git \
make \
nodejs && \
gem install bundler -v 2.3.7 && \
make prod
CMD ["make", "prod-server"]
FROM nginx:1.23.4-alpine3.17 AS proxy
COPY proxy/nginx.conf /etc/nginx/nginx.conf

View File

@ -1,52 +1,23 @@
source 'https://rubygems.org'
source "https://rubygems.org"
gem 'mimemagic', github: 'mimemagicrb/mimemagic', ref: '01f92d86d15d85cfd0f20dabd025dcbd36a8a60f'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '7.0.3.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '1.4.2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 6.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 4.2.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 5.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.11.5'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 2.4.0', group: :doc
gem "tzinfo-data"
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 4.2.0'
end
gem 'uuid'
gem 'rack-cors'
gem 'webrick'
# A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
gem 'jwt', '~> 2.4.1'
gem "byebug", "~> 11.1", :groups => [:development, :test]
gem "coffee-rails", "~> 5.0"
gem "dalli", "~> 3.2", :group => :development
gem "jbuilder", "~> 2.11"
gem "jquery-rails", "~> 4.5"
gem "jwt", "~> 2.7"
gem "mimemagic", github: "mimemagicrb/mimemagic", ref: "01f92d86d15d85cfd0f20dabd025dcbd36a8a60f"
gem "rack-cors", "~> 2.0"
gem "rails", "~> 7.0"
gem "rubocop", "~> 1.52", :group => :development
gem "sass-rails", "~> 6.0"
gem "sdoc", "~> 2.6", :group => :doc
gem "sorbet", "~> 0.5.10871", :group => :development
gem "sorbet-runtime", "~> 0.5.10871"
gem "tapioca", "~> 0.11.6", :group => :development
gem "turbolinks", "~> 5.2"
gem "tzinfo-data", "~> 1.2023"
gem "uglifier", "~> 4.2"
gem "uuid", "~> 2.3"
gem "web-console", "~> 4.2", :groups => [:development, :test]
gem "webrick", "~> 1.8"

View File

@ -8,71 +8,72 @@ GIT
GEM
remote: https://rubygems.org/
specs:
actioncable (7.0.3.1)
actionpack (= 7.0.3.1)
activesupport (= 7.0.3.1)
actioncable (7.0.5)
actionpack (= 7.0.5)
activesupport (= 7.0.5)
nio4r (~> 2.0)
websocket-driver (>= 0.6.1)
actionmailbox (7.0.3.1)
actionpack (= 7.0.3.1)
activejob (= 7.0.3.1)
activerecord (= 7.0.3.1)
activestorage (= 7.0.3.1)
activesupport (= 7.0.3.1)
actionmailbox (7.0.5)
actionpack (= 7.0.5)
activejob (= 7.0.5)
activerecord (= 7.0.5)
activestorage (= 7.0.5)
activesupport (= 7.0.5)
mail (>= 2.7.1)
net-imap
net-pop
net-smtp
actionmailer (7.0.3.1)
actionpack (= 7.0.3.1)
actionview (= 7.0.3.1)
activejob (= 7.0.3.1)
activesupport (= 7.0.3.1)
actionmailer (7.0.5)
actionpack (= 7.0.5)
actionview (= 7.0.5)
activejob (= 7.0.5)
activesupport (= 7.0.5)
mail (~> 2.5, >= 2.5.4)
net-imap
net-pop
net-smtp
rails-dom-testing (~> 2.0)
actionpack (7.0.3.1)
actionview (= 7.0.3.1)
activesupport (= 7.0.3.1)
rack (~> 2.0, >= 2.2.0)
actionpack (7.0.5)
actionview (= 7.0.5)
activesupport (= 7.0.5)
rack (~> 2.0, >= 2.2.4)
rack-test (>= 0.6.3)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.2.0)
actiontext (7.0.3.1)
actionpack (= 7.0.3.1)
activerecord (= 7.0.3.1)
activestorage (= 7.0.3.1)
activesupport (= 7.0.3.1)
actiontext (7.0.5)
actionpack (= 7.0.5)
activerecord (= 7.0.5)
activestorage (= 7.0.5)
activesupport (= 7.0.5)
globalid (>= 0.6.0)
nokogiri (>= 1.8.5)
actionview (7.0.3.1)
activesupport (= 7.0.3.1)
actionview (7.0.5)
activesupport (= 7.0.5)
builder (~> 3.1)
erubi (~> 1.4)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.1, >= 1.2.0)
activejob (7.0.3.1)
activesupport (= 7.0.3.1)
activejob (7.0.5)
activesupport (= 7.0.5)
globalid (>= 0.3.6)
activemodel (7.0.3.1)
activesupport (= 7.0.3.1)
activerecord (7.0.3.1)
activemodel (= 7.0.3.1)
activesupport (= 7.0.3.1)
activestorage (7.0.3.1)
actionpack (= 7.0.3.1)
activejob (= 7.0.3.1)
activerecord (= 7.0.3.1)
activesupport (= 7.0.3.1)
activemodel (7.0.5)
activesupport (= 7.0.5)
activerecord (7.0.5)
activemodel (= 7.0.5)
activesupport (= 7.0.5)
activestorage (7.0.5)
actionpack (= 7.0.5)
activejob (= 7.0.5)
activerecord (= 7.0.5)
activesupport (= 7.0.5)
marcel (~> 1.0)
mini_mime (>= 1.1.0)
activesupport (7.0.3.1)
activesupport (7.0.5)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 1.6, < 2)
minitest (>= 5.1)
tzinfo (~> 2.0)
ast (2.4.2)
bindex (0.8.1)
builder (3.2.4)
byebug (11.1.3)
@ -83,92 +84,121 @@ GEM
coffee-script-source
execjs
coffee-script-source (1.12.2)
concurrent-ruby (1.1.10)
concurrent-ruby (1.2.2)
crass (1.0.6)
digest (3.1.0)
erubi (1.11.0)
dalli (3.2.4)
date (3.3.3)
diff-lcs (1.5.0)
erubi (1.12.0)
execjs (2.8.1)
ffi (1.15.5)
ffi (1.15.5-x64-mingw-ucrt)
globalid (1.0.1)
globalid (1.1.0)
activesupport (>= 5.0)
i18n (1.12.0)
i18n (1.14.1)
concurrent-ruby (~> 1.0)
jbuilder (2.11.5)
actionview (>= 5.0.0)
activesupport (>= 5.0.0)
jquery-rails (4.5.0)
jquery-rails (4.5.1)
rails-dom-testing (>= 1, < 3)
railties (>= 4.2.0)
thor (>= 0.14, < 2.0)
jwt (2.4.1)
loofah (2.19.1)
json (2.6.3)
jwt (2.7.0)
loofah (2.21.3)
crass (~> 1.0.2)
nokogiri (>= 1.5.9)
nokogiri (>= 1.12.0)
macaddr (1.7.2)
systemu (~> 2.6.5)
mail (2.7.1)
mail (2.8.1)
mini_mime (>= 0.1.1)
net-imap
net-pop
net-smtp
marcel (1.0.2)
method_source (1.0.0)
mini_mime (1.1.2)
minitest (5.17.0)
net-imap (0.2.3)
digest
minitest (5.18.0)
net-imap (0.3.4)
date
net-protocol
strscan
net-pop (0.1.1)
digest
net-pop (0.1.2)
net-protocol
net-protocol (0.2.1)
timeout
net-protocol (0.1.3)
timeout
net-smtp (0.3.1)
digest
net-smtp (0.3.3)
net-protocol
timeout
nio4r (2.5.8)
nokogiri (1.13.10-x64-mingw-ucrt)
netrc (0.11.0)
nio4r (2.5.9)
nokogiri (1.15.2-arm64-darwin)
racc (~> 1.4)
nokogiri (1.13.10-x86_64-linux)
nokogiri (1.15.2-x64-mingw-ucrt)
racc (~> 1.4)
psych (4.0.5)
nokogiri (1.15.2-x86_64-linux)
racc (~> 1.4)
parallel (1.23.0)
parser (3.2.2.3)
ast (~> 2.4.1)
racc
psych (5.1.0)
stringio
racc (1.6.1)
rack (2.2.6.4)
rack-cors (1.1.1)
racc (1.7.0)
rack (2.2.7)
rack-cors (2.0.1)
rack (>= 2.0.0)
rack-test (2.0.2)
rack-test (2.1.0)
rack (>= 1.3)
rails (7.0.3.1)
actioncable (= 7.0.3.1)
actionmailbox (= 7.0.3.1)
actionmailer (= 7.0.3.1)
actionpack (= 7.0.3.1)
actiontext (= 7.0.3.1)
actionview (= 7.0.3.1)
activejob (= 7.0.3.1)
activemodel (= 7.0.3.1)
activerecord (= 7.0.3.1)
activestorage (= 7.0.3.1)
activesupport (= 7.0.3.1)
rails (7.0.5)
actioncable (= 7.0.5)
actionmailbox (= 7.0.5)
actionmailer (= 7.0.5)
actionpack (= 7.0.5)
actiontext (= 7.0.5)
actionview (= 7.0.5)
activejob (= 7.0.5)
activemodel (= 7.0.5)
activerecord (= 7.0.5)
activestorage (= 7.0.5)
activesupport (= 7.0.5)
bundler (>= 1.15.0)
railties (= 7.0.3.1)
railties (= 7.0.5)
rails-dom-testing (2.0.3)
activesupport (>= 4.2.0)
nokogiri (>= 1.6)
rails-html-sanitizer (1.4.4)
loofah (~> 2.19, >= 2.19.1)
railties (7.0.3.1)
actionpack (= 7.0.3.1)
activesupport (= 7.0.3.1)
rails-html-sanitizer (1.6.0)
loofah (~> 2.21)
nokogiri (~> 1.14)
railties (7.0.5)
actionpack (= 7.0.5)
activesupport (= 7.0.5)
method_source
rake (>= 12.2)
thor (~> 1.0)
zeitwerk (~> 2.5)
rainbow (3.1.1)
rake (13.0.6)
rdoc (6.4.0)
rbi (0.0.16)
ast
parser (>= 2.6.4.0)
sorbet-runtime (>= 0.5.9204)
unparser
rdoc (6.5.0)
psych (>= 4.0.0)
regexp_parser (2.8.0)
rexml (3.2.5)
rubocop (1.52.0)
json (~> 2.3)
parallel (~> 1.10)
parser (>= 3.2.0.0)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 1.8, < 3.0)
rexml (>= 3.2.5, < 4.0)
rubocop-ast (>= 1.28.0, < 2.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 2.4.0, < 3.0)
rubocop-ast (1.29.0)
parser (>= 3.2.1.0)
ruby-progressbar (1.13.0)
sass-rails (6.0.0)
sassc-rails (~> 2.1, >= 2.1.1)
sassc (2.4.0)
@ -179,31 +209,54 @@ GEM
sprockets (> 3.0)
sprockets-rails
tilt
sdoc (2.4.0)
sdoc (2.6.1)
rdoc (>= 5.0)
sprockets (4.1.1)
sorbet (0.5.10871)
sorbet-static (= 0.5.10871)
sorbet-runtime (0.5.10871)
sorbet-static (0.5.10871-universal-darwin-22)
sorbet-static (0.5.10871-x86_64-linux)
sorbet-static-and-runtime (0.5.10871)
sorbet (= 0.5.10871)
sorbet-runtime (= 0.5.10871)
spoom (1.2.1)
sorbet (>= 0.5.10187)
sorbet-runtime (>= 0.5.9204)
thor (>= 0.19.2)
sprockets (4.2.0)
concurrent-ruby (~> 1.0)
rack (> 1, < 3)
rack (>= 2.2.4, < 4)
sprockets-rails (3.4.2)
actionpack (>= 5.2)
activesupport (>= 5.2)
sprockets (>= 3.0.0)
sqlite3 (1.4.2)
stringio (3.0.2)
strscan (3.0.4)
stringio (3.0.7)
systemu (2.6.5)
thor (1.2.1)
tilt (2.0.11)
timeout (0.3.0)
tapioca (0.11.6)
bundler (>= 2.2.25)
netrc (>= 0.11.0)
parallel (>= 1.21.0)
rbi (~> 0.0.0, >= 0.0.16)
sorbet-static-and-runtime (>= 0.5.10187)
spoom (~> 1.2.0, >= 1.2.0)
thor (>= 1.2.0)
yard-sorbet
thor (1.2.2)
tilt (2.2.0)
timeout (0.3.2)
turbolinks (5.2.1)
turbolinks-source (~> 5.2)
turbolinks-source (5.2.0)
tzinfo (2.0.5)
tzinfo (2.0.6)
concurrent-ruby (~> 1.0)
tzinfo-data (1.2022.4)
tzinfo-data (1.2023.3)
tzinfo (>= 1.0.0)
uglifier (4.2.0)
execjs (>= 0.3.0, < 3)
unicode-display_width (2.4.2)
unparser (0.6.7)
diff-lcs (~> 1.3)
parser (>= 3.2.0)
uuid (2.3.9)
macaddr (~> 1.0)
web-console (4.2.0)
@ -211,34 +264,43 @@ GEM
activemodel (>= 6.0.0)
bindex (>= 0.4.0)
railties (>= 6.0.0)
webrick (1.7.0)
webrick (1.8.1)
websocket-driver (0.7.5)
websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.5)
zeitwerk (2.6.0)
yard (0.9.34)
yard-sorbet (0.8.1)
sorbet-runtime (>= 0.5)
yard (>= 0.9)
zeitwerk (2.6.8)
PLATFORMS
arm64-darwin-22
x64-mingw-ucrt
x86_64-linux
DEPENDENCIES
byebug
coffee-rails (~> 5.0.0)
jbuilder (~> 2.11.5)
jquery-rails
jwt (~> 2.4.1)
byebug (~> 11.1)
coffee-rails (~> 5.0)
dalli (~> 3.2)
jbuilder (~> 2.11)
jquery-rails (~> 4.5)
jwt (~> 2.7)
mimemagic!
rack-cors
rails (= 7.0.3.1)
rack-cors (~> 2.0)
rails (~> 7.0)
rubocop (~> 1.52)
sass-rails (~> 6.0)
sdoc (~> 2.4.0)
sqlite3 (= 1.4.2)
turbolinks
tzinfo-data
uglifier (>= 4.2.0)
uuid
web-console (~> 4.2.0)
webrick
sdoc (~> 2.6)
sorbet (~> 0.5.10871)
sorbet-runtime (~> 0.5.10871)
tapioca (~> 0.11.6)
turbolinks (~> 5.2)
tzinfo-data (~> 1.2023)
uglifier (~> 4.2)
uuid (~> 2.3)
web-console (~> 4.2)
webrick (~> 1.8)
BUNDLED WITH
2.3.7
2.4.10

View File

@ -0,0 +1,36 @@
.DEFAULT_GOAL := help
.PHONY: help
help: # Show help message for each of the Makefile recipes.
@grep -E "^[a-z-]+: #" $(MAKEFILE_LIST) | \
sort --dictionary-order | \
awk 'BEGIN {FS = ": # "}; {printf "%s: %s\n", $$1, $$2}'
.PHONY: dev
dev: # Install development dependencies and initialize the project.
@bundle install
@rake app:update:bin
@bundle exec tapioca init
.PHONY: dev-server
dev-server: # Start the development server on localhost at $PORT (default: 3000).
@rails server --using webrick
.PHONY: lint
lint: # Lint the source code for style and check for types.
@bundle exec rubocop
@bundle exec srb tc
.PHONY: prod
prod: # Install production dependencies.
@bundle install --without development doc test
@rake app:update:bin
.PHONY: prod-server
prod-server: # Start the poruction server on 0.0.0.0 at $PORT (default: 3000).
@rails server --environment production --using webrick
.PHONY: up
up: # Build and up docker containers.
@docker-compose build
@docker-compose up -d

View File

@ -1,6 +1,3 @@
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
require_relative 'config/application'
Rails.application.load_tasks

View File

@ -0,0 +1,102 @@
#
# (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.
#
# frozen_string_literal: true
# typed: true
# rubocop:disable Metrics/MethodLength
require 'jwt'
require_relative 'models/configuration_manager'
require_relative 'response'
class AuthorizationManager
extend T::Sig
sig { params(config: ConfigurationManager).void }
def initialize(config:)
@config = config
end
sig { params(headers: ActionDispatch::Http::Headers).returns(T::Boolean) }
def authorize(headers:)
enabled ? verify(headers:) : true
end
sig { returns(T::Boolean) }
def enabled
!@config.jwt_secret.empty?
end
sig { params(headers: ActionDispatch::Http::Headers).returns(T::Boolean) }
def document_server_authorize(headers:)
document_server_enabled ? verify(headers:) : true
end
sig { returns(T::Boolean) }
def document_server_enabled
enabled && @config.jwt_use_for_request
end
sig { params(headers: ActionDispatch::Http::Headers).returns(T::Boolean) }
def verify(headers:)
header = headers[@config.jwt_header]
return false unless header
token = header.sub('Bearer ', '')
decoded = decode(token)
!decoded.nil?
end
sig { params(payload: T.untyped).returns(String) }
def encode(payload:)
JWT.encode(
payload,
@config.jwt_secret,
AuthorizationManager.algorithm
)
end
sig { params(payload: String).returns(T.untyped) }
def decode(payload:)
decoded = JWT.decode(
payload,
@config.jwt_secret,
true,
{
algorithm: AuthorizationManager.algorithm
}
)
decoded[0]
rescue StandardError
nil
end
def self.algorithm
'HS256'
end
end
class AuthorizationResponseError
include ResponseError
extend T::Sig
sig { returns(AuthorizationResponseError) }
def self.forbidden
AuthorizationResponseError.new(
'forbidden'
)
end
end

View File

@ -14,6 +14,13 @@
# limitations under the License.
#
# typed: true
# rubocop:disable Metrics/ClassLength
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/CyclomaticComplexity
# rubocop:disable Metrics/PerceivedComplexity
require 'net/http'
require 'mimemagic'
@ -92,7 +99,7 @@ class HomeController < ApplicationController
end
body = JSON.parse(file_data)
file_name = File.basename(body["filename"])
lang = cookies[:ulang] ? cookies[:ulang] : "en"
file_pass = body["filePass"] ? body["filePass"] : nil
@ -144,45 +151,6 @@ class HomeController < ApplicationController
end
# downloading a history file from public
def downloadhistory
begin
file_name = File.basename(params[:fileName])
user_address = params[:userAddress]
version = params[:ver]
file = params[:file]
isEmbedded = params[:dmode]
if JwtHelper.is_enabled && JwtHelper.use_for_request
jwtHeader = Rails.configuration.header.empty? ? "Authorization" : Rails.configuration.header;
if request.headers[jwtHeader]
hdr = request.headers[jwtHeader]
hdr.slice!(0, "Bearer ".length)
token = JwtHelper.decode(hdr)
if !token || token.eql?("")
render plain: "JWT validation failed", :status => 403
return
end
else
render plain: "JWT validation failed", :status => 403
return
end
end
hist_path = DocumentHelper.storage_path(file_name, user_address) + "-hist" # or to the original document
file_path = File.join(hist_path, version, file)
# add headers to the response to specify the page parameters
response.headers['Content-Length'] = File.size(file_path).to_s
response.headers['Content-Type'] = MimeMagic.by_path(file_path).eql?(nil) ? nil : MimeMagic.by_path(file_path).type
response.headers['Content-Disposition'] = "attachment;filename*=UTF-8\'\'" + ERB::Util.url_encode(file)
send_file file_path, :x_sendfile => true
rescue => ex
render plain: '{ "error": "File not found"}'
end
end
# tracking file changes
def track
file_data = TrackHelper.read_body(request) # read the request body
@ -325,7 +293,7 @@ class HomeController < ApplicationController
res = http.request(req)
data = res.body
if data.size <= 0 || data.size > Rails.configuration.fileSizeMax
if data.size <= 0 || data.size > ConfigurationManager.new.maximum_file_size
render plain: '{"error": "File size is incorrect"}'
return
end
@ -368,7 +336,7 @@ class HomeController < ApplicationController
def reference
body = JSON.parse(request.body.read)
fileName = ""
if body.key?("referenceData")
referenceData = body["referenceData"]
@ -411,4 +379,4 @@ class HomeController < ApplicationController
render plain: data.to_json
end
end
end

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,203 @@
#
# (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.
#
# frozen_string_literal: true
# typed: true
require 'uri'
# The Configuration class provides the environment based configuration for the
# example instance.
# rubocop:disable Metrics/ClassLength
class ConfigurationManager
extend T::Sig
def initialize
@version = T.let('1.5.1', String)
end
# The URI through which an example instance can be accessed.
sig { returns(T.nilable(URI::Generic)) }
def example_uri
url = ENV['EXAMPLE_URL']
return nil if url.nil?
URI.parse(url)
end
# The public URI through which a document-server instance can be accessed.
# For example, it can be used to grant the user's browser access to a
# document-server.
sig { returns(URI::Generic) }
def document_server_public_uri
url = ENV['DOCUMENT_SERVER_PUBLIC_URL'] || 'http://document-server'
URI.parse(url)
end
# The private URI through which a document-server instance can be accessed.
# If no private URI is specified, it will be redirected to the public URI.
# For example, it can be used when both an example instance and a
# document-server instance are on the same closed network.
sig { returns(URI::Generic) }
def document_server_private_uri
url = ENV['DOCUMENT_SERVER_PRIVATE_URL']
return document_server_public_uri if url.nil?
URI.parse(url)
end
sig { returns(URI::Generic) }
def document_server_api_uri
path =
ENV['DOCUMENT_SERVER_API_PATH'] ||
'/web-apps/apps/api/documents/api.js'
URI.join(document_server_public_uri.to_s, path)
end
sig { returns(URI::Generic) }
def document_server_preloader_uri
path =
ENV['DOCUMENT_SERVER_PRELOADER_PATH'] ||
'/web-apps/apps/api/documents/cache-scripts.html'
URI.join(document_server_public_uri.to_s, path)
end
sig { returns(URI::Generic) }
def document_server_command_uri
path =
ENV['DOCUMENT_SERVER_COMMAND_PATH'] ||
'/coauthoring/CommandService.ashx'
URI.join(document_server_private_uri.to_s, path)
end
sig { returns(URI::Generic) }
def document_server_converter_uri
path =
ENV['DOCUMENT_SERVER_CONVERTER_PATH'] ||
'/ConvertService.ashx'
URI.join(document_server_private_uri.to_s, path)
end
sig { returns(String) }
def jwt_secret
ENV['JWT_SECRET'] || ''
end
sig { returns(String) }
def jwt_header
ENV['JWT_HEADER'] || 'Authorization'
end
sig { returns(T::Boolean) }
def jwt_use_for_request
env = ENV['JWT_USE_FOR_REQUEST']
return ActiveModel::Type::Boolean.new.cast(env) if env
true
end
sig { returns(T::Boolean) }
def ssl_verify_peer_mode_enabled
env = ENV['SSL_VERIFY_PEER_MODE_ENABLED']
return ActiveModel::Type::Boolean.new.cast(env) if env
false
end
sig { returns(String) }
def storage_path
ENV['STORAGE_PATH'] || 'app_data'
end
sig { returns(Numeric) }
def maximum_file_size
env = ENV['MAXIMUM_FILE_SIZE']
return env.to_i if env
5 * 1024 * 1024
end
sig { returns(Numeric) }
def convertation_timeout
120
end
sig { returns(T::Array[String]) }
def fillable_file_extensions
'.docx|.oform'
.split('|')
end
sig { returns(T::Array[String]) }
def viewable_file_extensions
'.djvu|.oxps|.pdf|.xps'
.split('|')
end
sig { returns(T::Array[String]) }
def editable_file_extensions
'.csv|.docm|.docx|.docxf|.dotm|.dotx|.epub|.fb2|.html|.odp|.ods|.odt|.otp|.ots|.ott|.potm|.potx|.ppsm|.ppsx|.pptm|.pptx|.rtf|.txt|.xlsm|.xlsx|.xltm|.xltx'
.split('|')
end
sig { returns(T::Array[String]) }
def convertable_file_extensions
'.doc|.dot|.dps|.dpt|.epub|.et|.ett|.fb2|.fodp|.fods|.fodt|.htm|.html|.mht|.mhtml|.odp|.ods|.odt|.otp|.ots|.ott|.pot|.pps|.ppt|.rtf|.stw|.sxc|.sxi|.sxw|.wps|.wpt|.xls|.xlsb|.xlt|.xml'
.split('|')
end
sig { returns(T::Hash[String, String]) }
def languages
{
'en' => 'English',
'hy' => 'Armenian',
'az' => 'Azerbaijani',
'eu' => 'Basque',
'be' => 'Belarusian',
'bg' => 'Bulgarian',
'ca' => 'Catalan',
'zh' => 'Chinese (Simplified)',
'zh-TW' => 'Chinese (Traditional)',
'cs' => 'Czech',
'da' => 'Danish',
'nl' => 'Dutch',
'fi' => 'Finnish',
'fr' => 'French',
'gl' => 'Galego',
'de' => 'German',
'el' => 'Greek',
'hu' => 'Hungarian',
'id' => 'Indonesian',
'it' => 'Italian',
'ja' => 'Japanese',
'ko' => 'Korean',
'lo' => 'Lao',
'lv' => 'Latvian',
'ms' => 'Malay (Malaysia)',
'no' => 'Norwegian',
'pl' => 'Polish',
'pt' => 'Portuguese (Brazil)',
'pt-PT' => 'Portuguese (Portugal)',
'ro' => 'Romanian',
'ru' => 'Russian',
'si' => 'Sinhala (Sri Lanka)',
'sk' => 'Slovak',
'sl' => 'Slovenian',
'es' => 'Spanish',
'sv' => 'Swedish',
'tr' => 'Turkish',
'uk' => 'Ukrainian',
'vi' => 'Vietnamese',
'aa-AA' => 'Test Language'
}
end
end
# rubocop:enable Metrics/ClassLength

View File

@ -14,6 +14,8 @@
# limitations under the License.
#
# rubocop:disable all
class DocumentHelper
@@runtime_cache = {}
@ -29,11 +31,8 @@ class DocumentHelper
# define max file size
def file_size_max
if Rails.configuration.fileSizeMax == nil
5 * 1024 * 1024
else
Rails.configuration.fileSizeMax # or get it from the config
end
config = ConfigurationManager.new
config.maximum_file_size
end
# all the supported file extensions
@ -42,38 +41,26 @@ class DocumentHelper
end
def fill_forms_exts
if Rails.configuration.fillDocs.empty?
[]
else
Rails.configuration.fillDocs.split("|")
end
config = ConfigurationManager.new
config.fillable_file_extensions
end
# file extensions that can be viewed
def viewed_exts
if Rails.configuration.viewedDocs.empty?
[]
else
Rails.configuration.viewedDocs.split("|")
end
config = ConfigurationManager.new
config.viewable_file_extensions
end
# file extensions that can be edited
def edited_exts
if Rails.configuration.editedDocs.empty?
[]
else
Rails.configuration.editedDocs.split("|")
end
config = ConfigurationManager.new
config.editable_file_extensions
end
# file extensions that can be converted
def convert_exts
if Rails.configuration.convertDocs.empty?
[]
else
Rails.configuration.convertDocs.split("|")
end
config = ConfigurationManager.new
config.convertable_file_extensions
end
# get current user host address
@ -83,8 +70,9 @@ class DocumentHelper
# get the storage path of the given file
def storage_path(file_name, user_address)
directory = File.absolute_path?(Rails.configuration.storagePath) ? Rails.configuration.storagePath
: Rails.root.join('public', Rails.configuration.storagePath, cur_user_host_address(user_address)) # get the path to the directory for the host address
config = ConfigurationManager.new
directory = File.absolute_path?(config.storage_path) ? config.storage_path
: Rails.root.join('public', config.storage_path, cur_user_host_address(user_address)) # get the path to the directory for the host address
# create a new directory if it doesn't exist
unless File.directory?(directory)
@ -97,8 +85,9 @@ class DocumentHelper
# get the path to the forcesaved file version
def forcesave_path(file_name, user_address, create)
directory = File.absolute_path?(Rails.configuration.storagePath) ? Rails.configuration.storagePath
: Rails.root.join('public', Rails.configuration.storagePath, cur_user_host_address(user_address))
config = ConfigurationManager.new
directory = File.absolute_path?(config.storage_path) ? config.storage_path
: Rails.root.join('public', config.storage_path, cur_user_host_address(user_address))
# the directory with host address doesn't exist
unless File.directory?(directory)
@ -151,7 +140,8 @@ class DocumentHelper
Dir.foreach(hist_dir) {|e| # run through all the file versions
next if e.eql?(".")
next if e.eql?("..")
if File.directory?(File.join(hist_dir, e))
path = File.join(hist_dir, e)
if File.directory?(path) && !Dir.empty?(path)
ver += 1 # and count them
end
}
@ -176,8 +166,9 @@ class DocumentHelper
# get all the stored files from the folder
def get_stored_files(user_address)
directory = File.absolute_path?(Rails.configuration.storagePath) ? Rails.configuration.storagePath
: Rails.root.join('public', Rails.configuration.storagePath, cur_user_host_address(user_address))
config = ConfigurationManager.new
directory = File.absolute_path?(config.storage_path) ? config.storage_path
: Rails.root.join('public', config.storage_path, cur_user_host_address(user_address))
arr = [];
@ -230,26 +221,20 @@ class DocumentHelper
# get file url
def get_file_uri(file_name, for_document_server)
uri = get_server_url(for_document_server) + '/' + Rails.configuration.storagePath + '/' + cur_user_host_address(nil) + '/' + ERB::Util.url_encode(file_name)
config = ConfigurationManager.new
uri = get_server_url(for_document_server) + '/' + config.storage_path + '/' + cur_user_host_address(nil) + '/' + ERB::Util.url_encode(file_name)
return uri
end
# get history path url
def get_historypath_uri(file_name,version,file,is_serverUrl=true)
# for redirection to my link
user_host = is_serverUrl ? '&userAddress=' + cur_user_host_address(nil) : ""
uri = get_server_url(is_serverUrl) + '/downloadhistory/?fileName=' + ERB::Util.url_encode(file_name) + '&ver='+ version.to_s + '&file='+ ERB::Util.url_encode(file) + user_host
return uri
end
# get server url
def get_server_url(for_document_server)
if for_document_server && !Rails.configuration.urlExample.empty?
return Rails.configuration.urlExample
config = ConfigurationManager.new
if for_document_server && config.example_uri
return config.example_uri.to_s
else
return @@base_url
end
end
end
# get callback url
@ -323,7 +308,7 @@ class DocumentHelper
"contentLength" => "#{(File.size(directory)/ 1024.0).round(2)} KB",
"pureContentLength" => File.size(directory),
"title" => fileName,
"updated" => File.mtime(directory)
"updated" => File.mtime(directory)
}
if file_id == nil # if file id is undefined
@ -344,11 +329,11 @@ class DocumentHelper
end
# enable ignore certificate
def verify_ssl(file_uri, http)
if file_uri.start_with?('https') && Rails.configuration.verify_peer_off.eql?('true')
if file_uri.start_with?('https') && ConfigurationManager.new.ssl_verify_peer_mode_enabled
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # set the flags for the server certificate verification at the beginning of SSL session
end
end
end
end
end

View File

@ -14,6 +14,8 @@
# limitations under the License.
#
# rubocop:disable all
class FileModel
attr_accessor :file_name, :mode, :type, :user_ip, :lang, :user, :action_data, :direct_url
@ -39,14 +41,10 @@ class FileModel
File.extname(@file_name).downcase
end
# get file url
def file_uri
DocumentHelper.get_file_uri(@file_name, true)
end
# get file uri for document server
def file_uri_user
File.absolute_path?(Rails.configuration.storagePath) ? download_url + "&dmode=emb" : DocumentHelper.get_file_uri(@file_name, false)
config = ConfigurationManager.new
File.absolute_path?(config.storage_path) ? download_url + "&dmode=emb" : DocumentHelper.get_file_uri(@file_name, false)
end
# get document type from its name (word, cell or slide)
@ -146,7 +144,7 @@ class FileModel
:lang => @lang ? @lang : "en",
:callbackUrl => callback_url, # absolute URL to the document storage service
:coEditing => editorsmode.eql?("view") && @user.id.eql?("uid-0") ? {
:mode => "strict",
:mode => "strict",
:change => false
} : nil,
:createUrl => !@user.id.eql?("uid-0") ? create_url : nil,
@ -164,7 +162,7 @@ class FileModel
},
:customization => { # the parameters for the editor interface
:about => true, # the About section display
:comments => true,
:comments => true,
:feedback => true, # the Feedback & Support menu button display
:forcesave => false, # adding the request for the forced file saving to the callback handler
:submitForm => submitForm, # the Submit form button state
@ -182,111 +180,6 @@ class FileModel
return config
end
# get document history
def get_history
file_name = @file_name
file_ext = File.extname(file_name).downcase
doc_key = key()
doc_uri = file_uri()
hist_dir = DocumentHelper.history_dir(DocumentHelper.storage_path(@file_name, nil)) # get the path to the file history
cur_ver = DocumentHelper.get_file_version(hist_dir) # get the file version
if (cur_ver > 0) # if file was modified
hist = []
histData = {}
for i in 1..cur_ver # run through all the file versions
obj = {}
dataObj = {}
ver_dir = DocumentHelper.version_dir(hist_dir, i) # get the path to the given file version
# get document key
cur_key = doc_key
if (i != cur_ver)
File.open(File.join(ver_dir, "key.txt"), 'r') do |file|
cur_key = file.read()
end
end
obj["key"] = cur_key
obj["version"] = i
if (i == 1) # check if the version number is equal to 1
if File.file?(File.join(hist_dir, "createdInfo.json")) # check if the createdInfo.json file with meta data exists
File.open(File.join(hist_dir, "createdInfo.json"), 'r') do |file| # open it
cr_info = JSON.parse(file.read()) # parse the file content
# write information about changes to the object
obj["created"] = cr_info["created"]
obj["user"] = {
:id => cr_info["uid"],
:name => cr_info["uname"]
}
end
end
end
# get the history data from the previous file version and write key and url information about it
dataObj["fileType"] = file_ext[1..file_ext.length]
dataObj["key"] = cur_key
dataObj["url"] = i == cur_ver ? doc_uri : DocumentHelper.get_historypath_uri(file_name, i, "prev#{file_ext}")
if is_enable_direct_url == true
dataObj["directUrl"] = i == cur_ver ? download_url(false) : DocumentHelper.get_historypath_uri(file_name, i, "prev#{file_ext}", false)
end
dataObj["version"] = i
if (i > 1) # check if the version number is greater than 1
changes = nil
change = nil
File.open(File.join(DocumentHelper.version_dir(hist_dir, i - 1), "changes.json"), 'r') do |file| # get the path to the changes.json file
changes = JSON.parse(file.read()) # and parse its content
end
change = changes["changes"][0]
# write information about changes to the object
obj["changes"] = change ? changes["changes"] : nil
obj["serverVersion"] = changes["serverVersion"]
obj["created"] = change ? change["created"] : nil
obj["user"] = change ? change["user"] : nil
prev = histData[(i - 2).to_s] # get the history data from the previous file version
dataObj["previous"] = is_enable_direct_url == true ? { # write key and url information about previous file version with optional direct url
:fileType => prev["fileType"],
:key => prev["key"],
:url => prev["url"],
:directUrl => prev["directUrl"]
} : {
:fileType => prev["fileType"],
:key => prev["key"],
:url => prev["url"]
}
# write the path to the diff.zip archive with differences in this file version
dataObj["changesUrl"] = DocumentHelper.get_historypath_uri(file_name, i - 1, "diff.zip")
end
if JwtHelper.is_enabled # check if a secret key to generate token exists or not
dataObj["token"] = JwtHelper.encode(dataObj) # encode a payload object into a token and write it to the data object
end
hist.push(obj) # add object dictionary to the hist list
histData[(i - 1).to_s] = dataObj # write data object information to the history data
end
return {
:hist => { # write history information about the current file version to the hist
:currentVersion => cur_ver,
:history => hist
},
:histData => histData
}
end
return nil
end
# get image information
def get_insert_image
insert_image = is_enable_direct_url == true ? {
@ -319,7 +212,7 @@ class FileModel
if JwtHelper.is_enabled # check if a secret key to generate token exists or not
compare_file["token"] = JwtHelper.encode(compare_file) # encode a payload object into a token and write it to the compare_file object
end
return compare_file
end
@ -351,4 +244,4 @@ class FileModel
return @direct_url != nil && @direct_url == "true"
end
end
end

View File

@ -18,9 +18,9 @@ require 'jwt'
class JwtHelper
@jwt_secret = Rails.configuration.jwtSecret
@token_use_for_request = Rails.configuration.token_use_for_request
@jwt_secret = ConfigurationManager.new.jwt_secret
@token_use_for_request = ConfigurationManager.new.jwt_use_for_request
class << self
# check if a secret key to generate token exists or not
def is_enabled

View File

@ -0,0 +1,60 @@
#
# (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.
#
# frozen_string_literal: true
# typed: true
require 'uri'
# The Proxy class provides interfaces that may be useful if a document-server
# instance and an example instance communicate through a proxy server.
class Proxy
extend T::Sig
sig { params(configuration: ConfigurationManager).void }
def initialize(configuration)
@config = configuration
end
# Resolves with a private document-server URI if the specified URI based on a
# public document-server URI.
sig { params(url: String).returns(URI::Generic) }
def resolve_document_server_uri(url)
uri = URI(url)
return uri unless equal_document_server_public_uri(uri)
swap_docuemnt_server_public_uri(uri)
end
private
sig { params(uri: URI::Generic).returns(T::Boolean) }
def equal_document_server_public_uri(uri)
uri.scheme == @config.document_server_public_uri.scheme && \
uri.host == @config.document_server_public_uri.host && \
uri.port == @config.document_server_public_uri.port
end
sig { params(uri: URI::Generic).returns(URI::Generic) }
def swap_docuemnt_server_public_uri(uri)
swaped_uri = uri
swaped_uri.scheme = @config.document_server_private_uri.scheme
swaped_uri.host = @config.document_server_private_uri.host
swaped_uri.port = @config.document_server_private_uri.port
swaped_uri
end
end

View File

@ -16,8 +16,8 @@
class ServiceConverter
@@convert_timeout = Rails.configuration.timeout # get the convertion timeout from the config
@@document_converter_url = Rails.configuration.urlSite + Rails.configuration.urlConverter # get the converter url from the config
@@convert_timeout = ConfigurationManager.new.convertation_timeout
@@document_converter_url = ConfigurationManager.new.document_server_converter_uri.to_s
class << self

View File

@ -17,6 +17,7 @@
require 'net/http'
class TrackHelper
@@document_command_url = ConfigurationManager.new.document_server_command_uri.to_s
class << self
@ -60,8 +61,34 @@ class TrackHelper
return file_data
end
def resolve_file_data(file_data)
config = ConfigurationManager.new
proxy = Proxy.new(config)
url = file_data['url']
file_data['url'] = proxy.resolve_document_server_uri(url).to_s if url
changesurl = file_data['changesurl']
file_data['changesurl'] = proxy.resolve_document_server_uri(changesurl).to_s if changesurl
home = file_data['home']
if home
home_url = home['url']
home['url'] = proxy.resolve_document_server_uri(home_url).to_s if home_url
home_changesurl = home['changesurl']
home['changesurl'] = proxy.resolve_document_server_uri(home_changesurl).to_s if home_changesurl
file_data['home'] = home
end
file_data
end
# file saving process
def process_save(file_data, file_name, user_address)
def process_save(raw_file_data, file_name, user_address)
file_data = resolve_file_data(raw_file_data)
download_uri = file_data['url']
if download_uri.eql?(nil)
saved = 1
@ -211,8 +238,6 @@ class TrackHelper
# send the command request
def command_request(method, key, meta = nil)
document_command_url = Rails.configuration.urlSite + Rails.configuration.commandUrl # get the document command url
# create a payload object with the method and key
payload = {
:c => method,
@ -226,10 +251,10 @@ class TrackHelper
data = nil
begin
uri = URI.parse(document_command_url) # parse the document command url
uri = URI.parse(@@document_command_url) # parse the document command url
http = Net::HTTP.new(uri.host, uri.port) # create a connection to the http server
DocumentHelper.verify_ssl(document_command_url, http)
DocumentHelper.verify_ssl(@@document_command_url, http)
req = Net::HTTP::Post.new(uri.request_uri) # create the post request
req.add_field("Content-Type", "application/json") # set headers

View File

@ -0,0 +1,57 @@
#
# (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.
#
# frozen_string_literal: true
# typed: true
require 'uri'
require_relative 'models/configuration_manager'
class ProxyManager
extend T::Sig
sig do
params(
config: ConfigurationManager,
base_url: String,
remote_ip: String,
user_host: T.nilable(String)
)
.void
end
def initialize(
config:,
base_url:,
remote_ip:,
user_host: nil
)
@config = config
@base_url = base_url
@remote_ip = remote_ip
@user_host = user_host
end
sig { returns(URI::Generic) }
def example_uri
@config.example_uri || URI(@base_url)
end
sig { returns(String) }
def user_host
(@user_host || @remote_ip).gsub(/[^0-9\-.a-zA-Z_=]/, '_')
end
end

View File

@ -0,0 +1,39 @@
#
# (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.
#
# frozen_string_literal: true
# typed: true
module ResponseError
extend T::Sig
sig { params(error: String).void }
def initialize(error)
@error = error
@success = false
end
def to_json(*options)
as_json.to_json(*options)
end
def as_json(_ = {})
{
error: @error,
success: @success
}
end
end

View File

@ -0,0 +1,72 @@
#
# (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.
#
# frozen_string_literal: true
# typed: true
require 'pathname'
require_relative 'models/configuration_manager'
require_relative 'proxy'
# ```text
# /application_directory
# └─ storage_directory
# └─ user_directory
# └─ source_file
#
# /srv
# └─ storage
# └─ 172.19.0.1
# └─ document.docx
# ```
class StorageManager
extend T::Sig
sig do
params(
config: ConfigurationManager,
proxy_manager: ProxyManager,
source_basename: String
)
.void
end
def initialize(config:, proxy_manager:, source_basename:)
@config = config
@proxy_manager = proxy_manager
@source_basename = source_basename
end
sig { returns(Pathname) }
def source_file
user_directory.join(@source_basename)
end
sig { returns(Pathname) }
def user_directory
directory = storage_directory.join(@proxy_manager.user_host)
FileUtils.mkdir(directory) unless directory.exist?
directory
end
sig { returns(Pathname) }
def storage_directory
# TODO: move to the Configuration.
path = Pathname.new(@config.storage_path)
storage_path = path.absolute? ? path : Rails.root.join('public', path)
FileUtils.mkdir(storage_path) unless storage_path.exist?
storage_path
end
end

View File

@ -21,7 +21,7 @@
</div>
</div>
<script src="<%= Rails.configuration.urlSite + Rails.configuration.urlApi %>"></script>
<script src="<%= ConfigurationManager.new.document_server_api_uri.to_s %>"></script>
<script type="text/javascript" language="javascript">
@ -109,13 +109,67 @@
// the user is trying to select document for comparing by clicking the Document from Storage button
var onRequestCompareFile = function() {
docEditor.setRevisedFile(<%= raw @file.get_compare_file.to_json %>); // select a document for comparing
};
};
// the user is trying to select recipients data by clicking the Mail merge button
var onRequestMailMergeRecipients = function (event) {
docEditor.setMailMergeRecipients(<%= raw @file.dataMailMergeRecipients.to_json %>); // insert recipient data for mail merge into the file
};
function onRequestHistory() {
const fileName = "<%= @file.file_name %>"
// const directURL
const request = new XMLHttpRequest()
request.open("GET", `history/${fileName}`)
request.send()
request.onload = function () {
response = JSON.parse(request.response)
if (request.status != 200) {
innerAlert(response.error)
return
}
docEditor.refreshHistory(response)
}
}
function onRequestHistoryData(event) {
const fileName = "<%= @file.file_name %>"
const version = event.data
// const directURL
const request = new XMLHttpRequest()
request.open("GET", `history/${fileName}/${version}/data`)
request.send()
request.onload = function () {
response = JSON.parse(request.response)
if (request.status != 200) {
innerAlert(response.error)
return
}
docEditor.setHistoryData(response)
}
}
function onRequestHistoryClose() {
document.location.reload()
}
function onRequestRestore(event) {
const fileName = "<%= @file.file_name %>"
const userID = "<%= @file.user.id %>"
const version = event.data.version
const request = new XMLHttpRequest()
request.open("PUT", `history/${fileName}/${version}/restore?user_id=${userID}`)
request.send()
request.onload = function () {
if (request.status != 200) {
response = JSON.parse(request.response)
innerAlert(response.error)
return
}
onRequestHistory()
}
}
var onRequestSaveAs = function (event) { // the user is trying to save file by clicking Save Copy as... button
var title = event.data.title;
var url = event.data.url;
@ -152,7 +206,7 @@
};
var onRequestReferenceData = function(event) { // user refresh external data source
event.data.directUrl = !!config.document.directUrl;
let xhr = new XMLHttpRequest();
xhr.open("POST", "reference");
@ -179,30 +233,18 @@
'onMetaChange': onMetaChange,
'onRequestInsertImage': onRequestInsertImage,
'onRequestCompareFile': onRequestCompareFile,
'onRequestMailMergeRecipients': onRequestMailMergeRecipients,
'onRequestMailMergeRecipients': onRequestMailMergeRecipients
};
<%
history = @file.get_history
usersMentions = @file.get_users_mentions %>
if (config.editorConfig.user.id) {
<% if history %>
// the user is trying to show the document version history
config.events['onRequestHistory'] = function () {
docEditor.refreshHistory(<%= raw history[:hist].to_json %>); // show the document version history
};
// the user is trying to click the specific document version in the document version history
config.events['onRequestHistoryData'] = function (event) {
var ver = event.data;
var histData = <%= raw history[:histData].to_json %>;
docEditor.setHistoryData(histData[ver - 1]); // send the link to the document for viewing the version history
};
// the user is trying to go back to the document from viewing the document version history
config.events['onRequestHistoryClose'] = function () {
document.location.reload();
};
<% end %>
config.events.onRequestHistory = onRequestHistory
config.events.onRequestHistoryData = onRequestHistoryData
config.events.onRequestHistoryClose = onRequestHistoryClose
config.events.onRequestRestore = onRequestRestore
// add mentions for not anonymous users
config.events['onRequestUsers'] = function () {
docEditor.setUsers({ // set a list of users to mention in the comments
@ -241,4 +283,4 @@
window.attachEvent("load", сonnectEditor);
}
</script>
</script>

View File

@ -75,7 +75,7 @@
data-tooltip="Choose the language for ONLYOFFICE editors interface"
src="assets/info.svg" />
<select class="select-user" id="language">
<% Rails.configuration.languages.each { |key, language|%>
<% ConfigurationManager.new.languages.each { |key, language|%>
<option value="<%=key %>"> <%=language %> </option>
<% } %>
</select>
@ -304,7 +304,7 @@
</div>
</div>
<span id="loadScripts" data-docs="<%= Rails.configuration.urlSite + Rails.configuration.urlPreloader %>"></span>
<span id="loadScripts" data-docs="<%= ConfigurationManager.new.document_server_preloader_uri.to_s %>"></span>
<footer>
<div class="center">

View File

@ -1,3 +0,0 @@
#!/usr/bin/env ruby.exe
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
load Gem.bin_path('bundler', 'bundle')

View File

@ -1,4 +0,0 @@
#!/usr/bin/env ruby.exe
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'

View File

@ -1,4 +0,0 @@
#!/usr/bin/env ruby.exe
require_relative '../config/boot'
require 'rake'
Rake.application.run

View File

@ -1,29 +0,0 @@
#!/usr/bin/env ruby.exe
require 'pathname'
# path to your application root.
APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
Dir.chdir APP_ROOT do
# This script is a starting point to setup your application.
# Add necessary setup steps to this file:
puts "== Installing dependencies =="
system "gem install bundler --conservative"
system "bundle check || bundle install"
# puts "\n== Copying sample files =="
# unless File.exist?("config/database.yml")
# system "cp config/database.yml.sample config/database.yml"
# end
puts "\n== Preparing database =="
system "bin/rake db:setup"
puts "\n== Removing old logs and tempfiles =="
system "rm -f log/*"
system "rm -rf tmp/cache"
puts "\n== Restarting application server =="
system "touch tmp/restart.txt"
end

View File

@ -1,15 +1,4 @@
# This file is used by Rack-based servers to start the application.
require_relative 'config/application'
require ::File.expand_path('../config/environment', __FILE__)
Rails.application.initialize!
run Rails.application
require 'rack/cors'
use Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get]
end
end

View File

@ -1,97 +1,106 @@
require File.expand_path('../boot', __FILE__)
# rubocop:disable Metrics/BlockLength
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
require_relative 'boot'
require 'active_model/railtie'
require 'action_controller/railtie'
require 'action_view/railtie'
require 'sprockets/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module OnlineEditorsExampleRuby
require_relative '../app/controllers/application_controller'
require_relative '../app/history'
module Example
class Application < Rails::Application
# TODO: move to the Convifgutaion.
# It needs to be moved to the Configuration, but it can't be done at the
# moment because replacing it causes the application to crash.
Rails.configuration.header = 'Authorization'
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :patch, :delete, :put, :options]
resource '*', headers: :any, methods: %i[get post patch delete put options]
end
end
Rails.configuration.version="1.5.1"
config.action_controller.perform_caching = true
config.active_support.deprecation = :log
config.assets.debug = false
config.assets.digest = true
config.cache_classes = true
config.consider_all_requests_local = true
config.eager_load = true
config.require_master_key = false
config.secret_key_base = SecureRandom.uuid
Rails.configuration.fileSizeMax=5242880
Rails.configuration.storagePath="app_data"
Rails.configuration.timeout=120
routes.append do
root to: 'home#index'
match '/convert', to: 'home#convert', via: 'post'
match '/csv', to: 'home#csv', via: 'get'
match '/download', to: 'home#download', via: 'get'
match '/downloadhistory', to: 'home#downloadhistory', via: 'get'
match '/editor', to: 'home#editor', via: 'get'
match '/files', to: 'home#files', via: 'get'
match '/index', to: 'home#index', via: 'get'
match '/reference', to: 'home#reference', via: 'post'
match '/remove', to: 'home#remove', via: 'get'
match '/rename', to: 'home#rename', via: 'post'
match '/restore', to: 'home#restore', via: 'put'
match '/sample', to: 'home#sample', via: 'get'
match '/saveas', to: 'home#saveas', via: 'post'
match '/track', to: 'home#track', via: 'post'
match '/upload', to: 'home#upload', via: 'post'
Rails.configuration.fillDocs=".docx|.oform"
Rails.configuration.viewedDocs=".djvu|.oxps|.pdf|.xps"
Rails.configuration.editedDocs=".csv|.docm|.docx|.docxf|.dotm|.dotx|.epub|.fb2|.html|.odp|.ods|.odt|.otp|.ots|.ott|.potm|.potx|.ppsm|.ppsx|.pptm|.pptx|.rtf|.txt|.xlsm|.xlsx|.xltm|.xltx"
Rails.configuration.convertDocs=".doc|.dot|.dps|.dpt|.epub|.et|.ett|.fb2|.fodp|.fods|.fodt|.htm|.html|.mht|.mhtml|.odp|.ods|.odt|.otp|.ots|.ott|.pot|.pps|.ppt|.rtf|.stw|.sxc|.sxi|.sxw|.wps|.wpt|.xls|.xlsb|.xlt|.xml"
file_basename_constraint = /[^\/]*/
Rails.configuration.urlSite="http://documentserver/"
Rails.configuration.urlConverter="ConvertService.ashx"
Rails.configuration.urlApi="web-apps/apps/api/documents/api.js"
Rails.configuration.urlPreloader="web-apps/apps/api/documents/cache-scripts.html"
Rails.configuration.commandUrl="coauthoring/CommandService.ashx"
Rails.configuration.urlExample=""
Rails.configuration.jwtSecret = ""
Rails.configuration.header="Authorization"
Rails.configuration.token_use_for_request=true
Rails.configuration.verify_peer_off = "true"
Rails.configuration.languages={
'en' => 'English',
'hy' => 'Armenian',
'az' => 'Azerbaijani',
'eu' => 'Basque',
'be' => 'Belarusian',
'bg' => 'Bulgarian',
'ca' => 'Catalan',
'zh' => 'Chinese (Simplified)',
'zh-TW' => 'Chinese (Traditional)',
'cs' => 'Czech',
'da' => 'Danish',
'nl' => 'Dutch',
'fi' => 'Finnish',
'fr' => 'French',
'gl' => 'Galego',
'de' => 'German',
'el' => 'Greek',
'hu' => 'Hungarian',
'id' => 'Indonesian',
'it' => 'Italian',
'ja' => 'Japanese',
'ko' => 'Korean',
'lo' => 'Lao',
'lv' => 'Latvian',
'ms' => 'Malay (Malaysia)',
'no' => 'Norwegian',
'pl' => 'Polish',
'pt' => 'Portuguese (Brazil)',
'pt-PT' => 'Portuguese (Portugal)',
'ro' => 'Romanian',
'ru' => 'Russian',
'si' => 'Sinhala (Sri Lanka)',
'sk' => 'Slovak',
'sl' => 'Slovenian',
'es' => 'Spanish',
'sv' => 'Swedish',
'tr' => 'Turkish',
'uk' => 'Ukrainian',
'vi' => 'Vietnamese',
'aa-AA' => 'Test Language'
}
get(
'/history/:source_basename',
to: HistoryController.action('history'),
format: false,
defaults: {
format: 'html'
},
constraints: {
source_basename: file_basename_constraint
}
)
get(
'/history/:source_basename/:version/data',
to: HistoryController.action('data'),
format: false,
defaults: {
format: 'html'
},
constraints: {
source_basename: file_basename_constraint
}
)
get(
'/history/:source_basename/:version/download/:requested_basename',
to: HistoryController.action('download'),
format: false,
defaults: {
foramt: 'html'
},
constraints: {
source_basename: file_basename_constraint,
requested_basename: file_basename_constraint
}
)
put(
'/history/:source_basename/:version/restore',
to: HistoryController.action('restore'),
format: false,
defaults: {
foramt: 'html'
},
constraints: {
source_basename: file_basename_constraint
}
)
end
end
end

View File

@ -1,3 +1,3 @@
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
require 'bundler/setup'

View File

@ -1,25 +0,0 @@
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
#
default: &default
adapter: sqlite3
pool: 5
timeout: 5000
development:
<<: *default
database: db/development.sqlite3
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: db/test.sqlite3
production:
<<: *default
database: db/production.sqlite3

View File

@ -1,5 +0,0 @@
# Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Rails.application.initialize!

View File

@ -1,41 +0,0 @@
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end

View File

@ -1,79 +0,0 @@
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end

View File

@ -1,42 +0,0 @@
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static file server for tests with Cache-Control for performance.
config.serve_static_files = true
config.static_cache_control = 'public, max-age=3600'
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Randomize the order test cases are executed.
config.active_support.test_order = :random
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end

View File

@ -1,15 +0,0 @@
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile += %w( editor.css )
Rails.application.config.assets.precompile += %w( jquery-ui.css )
Rails.application.config.assets.precompile += %w( stylesheet.css )
Rails.application.config.assets.precompile += %w( media.css )
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )

View File

@ -1,7 +0,0 @@
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!

View File

@ -1,3 +0,0 @@
# Be sure to restart your server when you modify this file.
Rails.application.config.action_dispatch.cookies_serializer = :json

View File

@ -1,4 +0,0 @@
# Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]

View File

@ -1,16 +0,0 @@
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end

View File

@ -1,4 +0,0 @@
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf

View File

@ -1,3 +0,0 @@
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_OnlineEditorsExampleRuby_session'

View File

@ -1,14 +0,0 @@
# Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end

View File

@ -1,23 +0,0 @@
# Files in the config/locales directory are used for internationalization
# and are automatically loaded by Rails. If you want to use locales other
# than English, add the necessary files in this directory.
#
# To use the locales, use `I18n.t`:
#
# I18n.t 'hello'
#
# In views, this is aliased to just `t`:
#
# <%= t('hello') %>
#
# To use a different locale, set it with `I18n.locale`:
#
# I18n.locale = :es
#
# This would use the information in config/locales/es.yml.
#
# To learn more, please read the Rails Internationalization guide
# available at http://guides.rubyonrails.org/i18n.html.
en:
hello: "Hello world"

View File

@ -1,73 +0,0 @@
Rails.application.routes.draw do
root 'home#index'
match '/index', to: 'home#index', via: 'get'
match '/editor', to: 'home#editor', via: 'get'
match '/sample', to: 'home#sample', via: 'get'
match '/remove', to: 'home#remove', via: 'get'
match '/upload', to: 'home#upload', via: 'post'
match '/download', to: 'home#download', via: 'get'
match '/downloadhistory', to: 'home#downloadhistory', via: 'get'
match '/convert', to: 'home#convert', via: 'post'
match '/track', to: 'home#track', via: 'post'
match '/csv', to: 'home#csv', via: 'get'
match '/files', to: 'home#files', via: 'get'
match '/saveas', to: 'home#saveas', via: 'post'
match '/rename', to: 'home#rename', via: 'post'
match '/reference', to: 'home#reference', via: 'post'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end

View File

@ -1,22 +0,0 @@
# Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure the secrets in this file are kept private
# if you're sharing your code publicly.
development:
secret_key_base: fadb8c51b54ebcb061791161d507fdaaa6df77e2ed6611101903bf48a20fffe0164a1fe9da16b5b400453de6b05dd46810de12ee468b3d695a4aa618801402a4
test:
secret_key_base: 96b983c551091cb89dae1538233bbdba38f8ca742b61b2320fa7f9aa6a3f146bfda53da2c8cdf2001f66626826f8519eab4327a521d5485ab434f4241fe4d74f
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

View File

@ -1,7 +0,0 @@
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)

View File

@ -0,0 +1,33 @@
version: "3.8"
services:
document-server:
container_name: document-server
image: onlyoffice/documentserver:7.3.3.50
expose:
- "80"
environment:
- JWT_SECRET=your-256-bit-secret
example:
container_name: example
build:
context: .
target: example
expose:
- "80"
environment:
- DOCUMENT_SERVER_PRIVATE_URL=http://proxy:3000
- DOCUMENT_SERVER_PUBLIC_URL=http://localhost:3000
- EXAMPLE_URL=http://proxy:8080
- JWT_SECRET=your-256-bit-secret
- PORT=80
proxy:
container_name: proxy
build:
context: .
target: proxy
ports:
- "8080:8080"
- "3000:3000"

View File

@ -0,0 +1,38 @@
worker_processes auto;
events {
worker_connections 512;
}
http {
include /etc/nginx/mime.types;
server {
listen 8080;
server_name localhost;
location / {
proxy_http_version 1.1;
proxy_pass http://example;
}
}
server {
listen 3000;
server_name localhost;
location / {
client_max_body_size 100m;
proxy_http_version 1.1;
proxy_pass http://document-server;
proxy_redirect off;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $http_x_forwarded_host;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_set_header X-Real-IP $remote_addr;
}
}
}