mirror of
https://github.com/ONLYOFFICE/document-server-integration.git
synced 2026-04-07 14:06:11 +08:00
Compare commits
71 Commits
v7.4.1.30
...
v99.99.99.
| Author | SHA1 | Date | |
|---|---|---|---|
| 693cc5a951 | |||
| ff9ba7fbf1 | |||
| f0651dabf0 | |||
| ccf85c1c0f | |||
| 6ea35bf55c | |||
| f6afde346a | |||
| ce4074bcce | |||
| 5697b58aa2 | |||
| d5e6301211 | |||
| 9048082cb7 | |||
| 56e46466b2 | |||
| fa9731ab57 | |||
| c2ba46ce85 | |||
| 4c5780f1d6 | |||
| 0419611a62 | |||
| bcc1011ddd | |||
| 91a4fe1e52 | |||
| 21fed8a81e | |||
| f2fc63c24f | |||
| 521608fa15 | |||
| e16ad4e53d | |||
| 7205e383c8 | |||
| 9bf317b3e0 | |||
| ac668a41c5 | |||
| 606f4255dc | |||
| 22a64dd932 | |||
| dd3255779f | |||
| 89c7e63ab8 | |||
| 447c604fe9 | |||
| dff9602852 | |||
| f4d7915dd6 | |||
| 01204d544e | |||
| a06aa8c8b3 | |||
| 7977427038 | |||
| 0b8d0ed10a | |||
| efec141039 | |||
| 6736555ff3 | |||
| d94fe30a3e | |||
| 3079320534 | |||
| 4f3af51e54 | |||
| d19c81c944 | |||
| bc3cbbbb82 | |||
| 8ee3ddc925 | |||
| 173c05dbf3 | |||
| b13c548c4d | |||
| ef8237adfd | |||
| c80379da31 | |||
| a54c43c0c2 | |||
| 5e524aa148 | |||
| e84ee9e01b | |||
| 27ceb1e6c6 | |||
| 508b0d913c | |||
| 5999b070dc | |||
| 3ed13f3975 | |||
| 1789f7c9fd | |||
| a05ea11dd7 | |||
| c6dd46a004 | |||
| bf04979c31 | |||
| e9274b7303 | |||
| 03022c5b45 | |||
| ce4ccdd5b0 | |||
| 07eba65458 | |||
| 072b082240 | |||
| c664bc4ee9 | |||
| f113d7eeb1 | |||
| 9409bf0785 | |||
| d51e724130 | |||
| 9489b4dcde | |||
| d9c139a42b | |||
| 534f1d8284 | |||
| f177af8791 |
@ -11,5 +11,10 @@ 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 }],
|
||||
},
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -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 = {};
|
||||
};
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
"use strict";
|
||||
/**
|
||||
*
|
||||
* (c) Copyright Ascensio System SIA 2023
|
||||
@ -17,488 +16,523 @@
|
||||
*
|
||||
*/
|
||||
|
||||
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"]);
|
||||
DocManager.prototype.getServerHost = function getServerHost() {
|
||||
return `${this.getProtocol()}://${this.req.headers['x-forwarded-host'] || this.req.headers.host}`;
|
||||
};
|
||||
|
||||
// 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.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;
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
};
|
||||
const userAddress = this.curUserHostAddress();
|
||||
|
||||
return res;
|
||||
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;
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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()}`);
|
||||
};
|
||||
|
||||
@ -16,80 +16,20 @@
|
||||
*
|
||||
*/
|
||||
|
||||
var descr_user_1 = [
|
||||
"File author by default",
|
||||
"Doesn’t 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 don’t belong to any group",
|
||||
//"Can’t 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 isn’t marked as favorite",
|
||||
"Can’t copy data from the file to clipboard",
|
||||
"Can’t download the file",
|
||||
"Can’t print the file",
|
||||
"Can create new files from the editor",
|
||||
"Can see the information about Group2 users",
|
||||
//"Can’t submit forms"
|
||||
];
|
||||
|
||||
var descr_user_0 = [
|
||||
"The name is requested when the editor is opened",
|
||||
"Doesn’t belong to any group",
|
||||
"Can review all the changes",
|
||||
"Can perform all actions with comments",
|
||||
"The file favorite state is undefined",
|
||||
"Can't mention others in comments",
|
||||
"Can't create new files from the editor",
|
||||
"Can’t see anyone’s information",
|
||||
"Can't rename files from the editor",
|
||||
"Can't view chat",
|
||||
"Can't protect file",
|
||||
"View file without collaboration",
|
||||
//"Can’t 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", "mitchell@example.com",
|
||||
"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,36 +41,102 @@ function User(id, name, email, group, reviewGroups, commentGroups, userInfoGroup
|
||||
this.deniedPermissions = deniedPermissions;
|
||||
this.descriptions = descriptions;
|
||||
this.templates = templates;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const descrUser1 = [
|
||||
'File author by default',
|
||||
'Doesn’t 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 don’t belong to any group',
|
||||
// "Can’t 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 isn’t marked as favorite',
|
||||
'Can’t copy data from the file to clipboard',
|
||||
'Can’t download the file',
|
||||
'Can’t print the file',
|
||||
'Can create new files from the editor',
|
||||
'Can see the information about Group2 users',
|
||||
// "Can’t submit forms"
|
||||
];
|
||||
|
||||
const descrUser0 = [
|
||||
'The name is requested when the editor is opened',
|
||||
'Doesn’t belong to any group',
|
||||
'Can review all the changes',
|
||||
'Can perform all actions with comments',
|
||||
'The file favorite state is undefined',
|
||||
'Can\'t mention others in comments',
|
||||
'Can\'t create new files from the editor',
|
||||
'Can’t see anyone’s information',
|
||||
'Can\'t rename files from the editor',
|
||||
'Can\'t view chat',
|
||||
'Can\'t protect file',
|
||||
'View file without collaboration',
|
||||
// "Can’t 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
|
||||
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;
|
||||
};
|
||||
|
||||
module.exports = users;
|
||||
|
||||
@ -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);
|
||||
};
|
||||
|
||||
@ -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,
|
||||
};
|
||||
|
||||
@ -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,
|
||||
};
|
||||
|
||||
@ -16,8 +16,4 @@
|
||||
*
|
||||
*/
|
||||
|
||||
exports.isValidToken = (req, res, next) => {
|
||||
if (true) {
|
||||
return next();
|
||||
}
|
||||
}
|
||||
exports.isValidToken = (req, res, next) => next();
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -16,157 +16,160 @@
|
||||
*
|
||||
*/
|
||||
|
||||
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,
|
||||
serverUrl: req.DocManager.getServerUrl(),
|
||||
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);
|
||||
};
|
||||
|
||||
@ -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))) {
|
||||
|
||||
@ -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"] ?? "";
|
||||
|
||||
|
||||
Reference in New Issue
Block a user