Merge branch release/v7.2.0 into master

This commit is contained in:
papacarlo
2022-09-22 12:21:14 +00:00
44 changed files with 2998 additions and 2459 deletions

View File

@ -98,28 +98,14 @@ License: MIT License
License File: license/jsrsasign.license
15. JSZip - SZip is a javascript library for creating, reading and editing .zip files, with a lovely and simple API.
URL: http://stuk.github.io/jszip/
License: MIT license or the GPLv3 license
License File: license/jszip.license
16. JSZipUtils - A collection of cross-browser utilities to go along with JSZip.
URL: http://stuk.github.io/jszip-utils/
License: MIT license or the GPLv3 license
License File: license/jszip.license
17. less - Less is a CSS pre-processor
15. less - Less is a CSS pre-processor
URL: http://lesscss.org/
License: Apache 2 License
License File: license/less.license
18. requirejs-text - A RequireJS/AMD loader plugin for loading text resources
16. requirejs-text - A RequireJS/AMD loader plugin for loading text resources
URL: http://lesscss.org/
License: MIT License

View File

@ -27,6 +27,7 @@
"endpoint": "http://localhost/s3",
"bucketName": "cache",
"storageFolderName": "files",
"cacheFolderName": "data",
"urlExpires": 604800,
"accessKeyId": "AKID",
"secretAccessKey": "SECRET",
@ -97,6 +98,18 @@
"privateKeyOld": "MIIEowIBAAKCAQEAqnro3nUUjvZK1i7UqeOlXmCrVPiDtHlRgIPReAjt2nKL1GG3SBXO6N0aPbiM5rtK0XRPUoLmKu2rYvSJ/Kmkdp14a/3uiEl788VVn0hb/l9OuQtH3HBjmM0/LKRgJQuU3LgHI67uRVZYtSJ/n9fYdZqnLfveLsrgZpgRCoabrp+H5Uem9N+x0OJR3LpToVRZhzSkYQrxnERJmF3bhR5yF8Zn+3BoSiUpVOCAvJRAYl8cAIs3BwQcTEyXJjnt+wW5Q1VyKr+bXp/39+tnugQeTe1jjdPy6rOTftQwzjro81oZpOMazwwR1aeQuQWCrmHQZqyV3Rvo6X3xYlOQnlo1/wIDAQABAoIBAQCKtUSBs8tNYrGTQTlBHXrwpkDg+u7WSZt5sEcfnkxA39BLtlHU8gGO0E9Ihr8GAL+oWjUsEltJ9GTtN8CJ9lFdPVS8sTiCZR/YQOggmFRZTJyVzMrkXgF7Uwwiu3+KxLiTOZx9eRhfDBlTD8W9fXaegX2i2Xp2ohUhBHthEBLdaZTWFi5Sid/Y0dDzBeP6UIJorZ5D+1ybaeIVHjndpwNsIEUGUxPFLrkeiU8Rm4MJ9ahxfywcP7DjQoPGY9Ge5cBhpxfzERWf732wUD6o3+L9tvOBU00CLVjULbGZKTVE2FJMyXK9jr6Zor9Mkhomp6/8Agkr9rp+TPyelFGYEz8hAoGBAOEc09CrL3eYBkhNEcaMQzxBLvOGpg8kaDX5SaArHfl9+U9yzRqss4ARECanp9HuHfjMQo7iejao0ngDjL7BNMSaH74QlSsPOY2iOm8Qvx8/zb7g4h9r1zLjFZb3mpSA4snRZvvdiZ9ugbuVPmhXnDzRRMg45MibJeeOTJNylofRAoGBAMHfF/WutqKDoX25qZo9m74W4bttOj6oIDk1N4/c6M1Z1v/aptYSE06bkWngj9P46kqjaay4hgMtzyGruc5aojPx5MHHf5bo14+Jv4NzYtR2llrUxO+UJX7aCfUYXI7RC93GUmhpeQ414j7SNAXec58d7e+ETw+6cHiAWO4uOSTPAoGATPq5qDLR4Zi4FUNdn8LZPyKfNqHF6YmupT5hIgd8kZO1jKiaYNPL8jBjkIRmjBBcaXcYD5p85nImvumf2J9jNxPpZOpwyC/Fo5xlVROp97qu1eY7DTmodntXJ6/2SXAlnZQhHmHsrPtyG752f+HtyJJbbgiem8cKWDu+DfHybfECgYBbSLo1WiBwgN4nHqZ3E48jgA6le5azLeKOTTpuKKwNFMIhEkj//t7MYn+jhLL0Mf3PSwZU50Vidc1To1IHkbFSGBGIFHFFEzl8QnXEZS4hr/y3o/teezj0c6HAn8nlDRUzRVBEDXWMdV6kCcGpCccTIrqHzpqTY0vV0UkOTQFnDQKBgAxSEhm/gtCYJIMCBe+KBJT9uECV5xDQopTTjsGOkd4306EN2dyPOIlAfwM6K/0qWisa0Ei5i8TbRRuBeTTdLEYLqXCJ7fj5tdD1begBdSVtHQ2WHqzPJSuImTkFi9NXxd1XUyZFM3y6YQvlssSuL7QSxUIEtZHnrJTt3QDd10dj",
"refreshLockInterval": "10m"
},
"tenants": {
"baseDir": "",
"baseDomain": "",
"filenameSecret": "secret.key",
"filenameLicense": "license.lic",
"defaultTenant": "localhost",
"cache" : {
"stdTTL": 300,
"checkperiod": 60,
"useClones": false
}
},
"services": {
"CoAuthoring": {
"server": {
@ -182,7 +195,7 @@
"files": 86400,
"filesCron": "00 00 */1 * * *",
"filesremovedatonce": 100,
"sessionidle": "0",
"sessionidle": "1h",
"sessionabsolute": "30d",
"sessionclosecommand": "2m",
"pemStdTTL": "1h",
@ -200,8 +213,7 @@
"allowMetaIPAddress": true
},
"secret": {
"browser": {"string": "secret", "file": "", "tenants": {}},
"inbox": {"string": "secret", "file": "", "tenants": {}},
"inbox": {"string": "secret", "file": ""},
"outbox": {"string": "secret", "file": ""},
"session": {"string": "secret", "file": ""}
},
@ -213,9 +225,6 @@
"outbox": false
}
},
"browser": {
"secretFromInbox": true
},
"inbox": {
"header": "Authorization",
"prefix": "Bearer ",
@ -254,6 +263,7 @@
},
"sockjs": {
"sockjs_url": "",
"disable_cors": true,
"websocket": true
},
"callbackBackoffOptions": {
@ -287,8 +297,6 @@
"presentationThemesDir": "null",
"x2tPath": "null",
"docbuilderPath": "null",
"docbuilderAllFontsPath": "null",
"docbuilderCoreFontsPath": "",
"args": "",
"spawnOptions": {},
"errorfiles": "",

View File

@ -54,9 +54,7 @@
"fontDir": "/usr/share/fonts",
"presentationThemesDir": "../../sdkjs/slide/themes",
"x2tPath": "../FileConverter/bin/x2t",
"docbuilderPath": "../FileConverter/bin/docbuilder",
"docbuilderAllFontsPath": "../App_Data/docbuilder/AllFonts.js",
"docbuilderCoreFontsPath": "../../core-fonts"
"docbuilderPath": "../FileConverter/bin/docbuilder"
}
},
"SpellChecker": {

View File

@ -61,8 +61,6 @@
"presentationThemesDir": "../../sdkjs/slide/themes",
"x2tPath": "../FileConverter/bin/x2t",
"docbuilderPath": "../FileConverter/Bin/docbuilder",
"docbuilderAllFontsPath": "../App_Data/docbuilder/AllFonts.js",
"docbuilderCoreFontsPath": "../../core-fonts",
"errorfiles": "error"
}
},

View File

@ -61,8 +61,6 @@
"presentationThemesDir": "../../sdkjs/slide/themes",
"x2tPath": "../FileConverter/Bin/x2t.exe",
"docbuilderPath": "../FileConverter/Bin/docbuilder.exe",
"docbuilderAllFontsPath": "../App_Data/docbuilder/AllFonts.js",
"docbuilderCoreFontsPath": "../../core-fonts",
"errorfiles": "error"
}
},

View File

@ -4,7 +4,7 @@
"type": "console",
"layout": {
"type": "pattern",
"pattern": "%[[%d] [%p] %c -%] %.10000m"
"pattern": "%[[%d] [%p] [%X{TENANT}] [%X{DOCID}] [%X{USERID}] %c -%] %.10000m"
}
}
},

View File

@ -4,7 +4,7 @@
"type": "console",
"layout": {
"type": "pattern",
"pattern": "[%d] [%p] %c - %.10000m"
"pattern": "[%d] [%p] [%X{TENANT}] [%X{DOCID}] [%X{USERID}] %c - %.10000m"
}
}
},

View File

@ -63,9 +63,7 @@
"fontDir": "/usr/share/fonts",
"presentationThemesDir": "/var/www/onlyoffice/documentserver/sdkjs/slide/themes",
"x2tPath": "/var/www/onlyoffice/documentserver/server/FileConverter/bin/x2t",
"docbuilderPath": "/var/www/onlyoffice/documentserver/server/FileConverter/bin/docbuilder",
"docbuilderAllFontsPath": "/var/lib/onlyoffice/documentserver/App_Data/docbuilder/AllFonts.js",
"docbuilderCoreFontsPath": "/var/www/onlyoffice/documentserver/core-fonts"
"docbuilderPath": "/var/www/onlyoffice/documentserver/server/FileConverter/bin/docbuilder"
}
},
"SpellChecker": {

View File

@ -59,9 +59,7 @@
"fontDir": "",
"presentationThemesDir": "../../sdkjs/slide/themes",
"x2tPath": "../FileConverter/bin/x2t.exe",
"docbuilderPath": "../FileConverter/bin/docbuilder.exe",
"docbuilderAllFontsPath": "../App_Data/docbuilder/AllFonts.js",
"docbuilderCoreFontsPath": "../../core-fonts"
"docbuilderPath": "../FileConverter/bin/docbuilder.exe"
}
},
"SpellChecker": {

View File

@ -34,6 +34,7 @@
var config = require('config');
var container = require('rhea');
var logger = require('./logger');
const operationContext = require('./operationContext');
const cfgRabbitSocketOptions = config.get('activemq.connectOptions');
@ -45,20 +46,20 @@ function connetPromise(reconnectOnConnectionError, closeCallback) {
let conn = container.create_container().connect(cfgRabbitSocketOptions);
let isConnected = false;
conn.on('connection_open', function(context) {
logger.debug('[AMQP] connected');
operationContext.global.logger.debug('[AMQP] connected');
isConnected = true;
resolve(conn);
});
conn.on('connection_error', function(context) {
//todo
logger.debug('[AMQP] connection_error %s', context.error);
operationContext.global.logger.debug('[AMQP] connection_error %s', context.error);
});
conn.on('connection_close', function() {
//todo
logger.debug('[AMQP] conn close');
operationContext.global.logger.debug('[AMQP] conn close');
});
conn.on('disconnected', function(context) {
logger.error('[AMQP] disconnected %s', context.error && context.error.stack);
operationContext.global.logger.error('[AMQP] disconnected %s', context.error && context.error.stack);
if (isConnected) {
closeCallback();
} else {

View File

@ -708,6 +708,7 @@ CMailMergeSendData.prototype.setIsJsonKey = function(v) {
};
function TaskQueueData(data) {
if (data) {
this['ctx'] = data['ctx'];
this['cmd'] = new InputCommand(data['cmd'], true);
this['toFile'] = data['toFile'];
this['fromOrigin'] = data['fromOrigin'];
@ -718,6 +719,7 @@ function TaskQueueData(data) {
this['dataKey'] = data['dataKey'];
this['visibilityTimeout'] = data['visibilityTimeout'];
} else {
this['ctx'] = undefined;
this['cmd'] = undefined;
this['toFile'] = undefined;
this['fromOrigin'] = undefined;
@ -730,6 +732,12 @@ function TaskQueueData(data) {
}
}
TaskQueueData.prototype = {
getCtx : function() {
return this['ctx'];
},
setCtx : function(data) {
return this['ctx'] = data;
},
getCmd : function() {
return this['cmd'];
},
@ -896,7 +904,7 @@ function OutputMailMerge(mailMergeSendData) {
this['title'] = mailMergeSendData.getFileName();
const mailFormat = mailMergeSendData.getMailFormat();
switch (mailFormat) {
case constants.AVS_OFFICESTUDIO_FILE_OTHER_HTMLZIP :
case constants.AVS_OFFICESTUDIO_FILE_DOCUMENT_HTML :
this['type'] = 0;
break;
case constants.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX :

View File

@ -35,6 +35,7 @@
exports.DOC_ID_PATTERN = '0-9-.a-zA-Z_=';
exports.DOC_ID_REGEX = new RegExp("^[" + exports.DOC_ID_PATTERN + "]*$", 'i');
exports.DOC_ID_REPLACE_REGEX = new RegExp("[^" + exports.DOC_ID_PATTERN + "]", 'g');
exports.DOC_ID_SOCKET_PATTERN = new RegExp("^/doc/([" + exports.DOC_ID_PATTERN + "]*)/c.+", 'i');
exports.DOC_ID_MAX_LENGTH = 240;
exports.USER_ID_MAX_LENGTH = 240;//255-240=15 symbols to make user id unique
exports.USER_NAME_MAX_LENGTH = 255;
@ -45,6 +46,9 @@ exports.OUTPUT_NAME = 'output';
exports.ONLY_OFFICE_URL_PARAM = 'ooname';
exports.DISPLAY_PREFIX = 'display';
exports.CHANGES_NAME = 'changes';
exports.VIEWER_ONLY = /^(?:(pdf|djvu|xps|oxps))$/;
exports.DEFAULT_DOC_ID = 'docId';
exports.DEFAULT_USER_ID = 'userId';
exports.RIGHTS = {
None : 0,
@ -72,7 +76,11 @@ exports.LICENSE_RESULT = {
UsersCount : 8,
ConnectionsOS : 9,
UsersCountOS : 10,
ExpiredLimited: 11
ExpiredLimited: 11,
ConnectionsLiveOS: 12,
ConnectionsLive: 13,
UsersViewCount: 14,
UsersViewCountOS: 15
};
exports.LICENSE_CONNECTIONS = 20;
@ -239,6 +247,9 @@ exports.REDIS_KEY_PRESENCE_SET = 'presence:set:';
exports.REDIS_KEY_PRESENCE_UNIQUE_USERS = 'presence:unique:users';
exports.REDIS_KEY_PRESENCE_UNIQUE_USERS_HASH = 'presence:unique:users:hash';
exports.REDIS_KEY_PRESENCE_MONTH_UNIQUE_USERS_HASH = 'presence:unique:users:month';
exports.REDIS_KEY_PRESENCE_UNIQUE_USERS_VIEW = 'presence:unique:usersview';
exports.REDIS_KEY_PRESENCE_UNIQUE_USERS_VIEW_HASH = 'presence:unique:usersview:hash';
exports.REDIS_KEY_PRESENCE_MONTH_UNIQUE_USERS_VIEW_HASH = 'presence:unique:usersview:month';
exports.REDIS_KEY_LOCKS = 'locks:';
exports.REDIS_KEY_LOCK_DOCUMENT = 'lockdocument:';
exports.REDIS_KEY_MESSAGE = 'message:';
@ -255,6 +266,8 @@ exports.REDIS_KEY_LICENSE_T = 'licenseT';
exports.REDIS_KEY_EDITOR_CONNECTIONS = 'editorconnections';
exports.REDIS_KEY_SHARD_CONNECTIONS_EDIT_ZSET = 'shardconnections:edit:zset';
exports.REDIS_KEY_SHARD_CONNECTIONS_EDIT_HASH = 'shardconnections:edit:hash';
exports.REDIS_KEY_SHARD_CONNECTIONS_LIVE_VIEW_ZSET = 'shardconnections:liveview:zset';
exports.REDIS_KEY_SHARD_CONNECTIONS_LIVE_VIEW_HASH = 'shardconnections:liveview:hash';
exports.REDIS_KEY_SHARD_CONNECTIONS_VIEW_ZSET = 'shardconnections:view:zset';
exports.REDIS_KEY_SHARD_CONNECTIONS_VIEW_HASH = 'shardconnections:view:hash';
@ -276,6 +289,8 @@ exports.UPDATE_VERSION_CODE = 4008;
exports.UPDATE_VERSION = 'update version';
exports.NO_CACHE_CODE = 4009;
exports.NO_CACHE = 'no cache';
exports.RESTORE_CODE = 4010;
exports.RESTORE = 'no cache';
exports.CONTENT_DISPOSITION_INLINE = 'inline';
exports.CONTENT_DISPOSITION_ATTACHMENT = 'attachment';

View File

@ -34,7 +34,6 @@
var path = require('path');
var constants = require('./constants');
var logger = require('./logger');
function getImageFormatBySignature(buffer) {
var length = buffer.length;
@ -500,7 +499,7 @@ exports.getStringFromFormat = function(format) {
return '';
}
};
exports.getImageFormat = function(buffer, optExt) {
exports.getImageFormat = function(ctx, buffer, optExt) {
var format = constants.AVS_OFFICESTUDIO_FILE_UNKNOWN;
try {
//signature
@ -519,8 +518,7 @@ exports.getImageFormat = function(buffer, optExt) {
}
}
catch (e) {
logger.error(optExt);
logger.error('error getImageFormat:\r\n%s', e.stack);
ctx.logger.error('error getImageFormat ext=%s: %s', optExt, e.stack);
}
return format;
};
@ -539,3 +537,21 @@ exports.isPresentationFormat = function(format) {
format === constants.AVS_OFFICESTUDIO_FILE_CANVAS_PRESENTATION ||
format === constants.AVS_OFFICESTUDIO_FILE_TEAMLAB_PPTY;
};
exports.isOOXFormat = function(format) {
return constants.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX === format
|| constants.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCM === format
|| constants.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOTX === format
|| constants.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOTM === format
|| constants.AVS_OFFICESTUDIO_FILE_DOCUMENT_OFORM === format
|| constants.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCXF === format
|| constants.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPTX === format
|| constants.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPSX === format
|| constants.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPTM === format
|| constants.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPSM === format
|| constants.AVS_OFFICESTUDIO_FILE_PRESENTATION_POTX === format
|| constants.AVS_OFFICESTUDIO_FILE_PRESENTATION_POTM === format
|| constants.AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLSX === format
|| constants.AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLSM === format
|| constants.AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLTX === format
|| constants.AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLTM === format;
};

View File

@ -49,8 +49,10 @@ exports.readLicense = function*() {
mode: constants.LICENSE_MODE.None,
branding: false,
connections: constants.LICENSE_CONNECTIONS,
connectionsView: constants.LICENSE_CONNECTIONS,
customization: false,
usersCount: 0,
usersViewCount: 0,
usersExpire: constants.LICENSE_EXPIRE_USERS_ONE_DAY,
hasLicense: false,
plugins: false,

View File

@ -73,7 +73,9 @@ if (config.get('log.options.replaceConsole')) {
console.error = logger.error.bind(logger);
console.debug = logger.debug.bind(logger);
}
exports.getLogger = function (){
return log4js.getLogger.apply(log4js, Array.prototype.slice.call(arguments));
};
exports.trace = function (){
return logger.trace.apply(logger, Array.prototype.slice.call(arguments));
};

View File

@ -0,0 +1,91 @@
/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
'use strict';
const utils = require('./utils');
const logger = require('./logger');
const constants = require('./constants');
const tenantManager = require('./tenantManager');
function Context(){
this.logger = logger.getLogger('nodeJS');
this.initDefault();
}
Context.prototype.init = function(tenant, docId, userId) {
this.setTenant(tenant);
this.setDocId(docId);
this.setUserId(userId);
};
Context.prototype.initDefault = function() {
this.init(tenantManager.getDefautTenant(), constants.DEFAULT_DOC_ID, constants.DEFAULT_USER_ID);
};
Context.prototype.initFromConnection = function(conn) {
let tenant = tenantManager.getTenantByConnection(this, conn);
let docId = conn.docid;
if (!docId) {
const docIdParsed = constants.DOC_ID_SOCKET_PATTERN.exec(conn.url);
if (docIdParsed && 1 < docIdParsed.length) {
docId = docIdParsed[1];
}
}
let userId = conn.user?.id;
this.init(tenant, docId || this.docId, userId || this.userId);
};
Context.prototype.initFromRequest = function(req) {
let tenant = tenantManager.getTenantByRequest(this, req);
this.init(tenant, this.docId, this.userId);
};
Context.prototype.initFromTaskQueueData = function(task) {
let ctx = task.getCtx();
this.init(ctx.tenant, ctx.docId, ctx.userId);
};
Context.prototype.initFromPubSub = function(data) {
let ctx = data.ctx;
this.init(ctx.tenant, ctx.docId, ctx.userId);
};
Context.prototype.setTenant = function(tenant) {
this.tenant = tenant;
this.logger.addContext('TENANT', tenant);
};
Context.prototype.setDocId = function(docId) {
this.docId = docId;
this.logger.addContext('DOCID', docId);
};
Context.prototype.setUserId = function(userId) {
this.userId = userId;
this.logger.addContext('USERID', userId);
};
exports.Context = Context;
exports.global = new Context();

View File

@ -34,6 +34,7 @@
var config = require('config');
var amqp = require('amqplib/callback_api');
var logger = require('./logger');
const operationContext = require('./operationContext');
var cfgRabbitUrl = config.get('rabbitmq.url');
var cfgRabbitSocketOptions = config.get('rabbitmq.socketOptions');
@ -45,7 +46,7 @@ function connetPromise(reconnectOnConnectionError, closeCallback) {
function startConnect() {
amqp.connect(cfgRabbitUrl, cfgRabbitSocketOptions, function(err, conn) {
if (null != err) {
logger.error('[AMQP] %s', err.stack);
operationContext.global.logger.error('[AMQP] %s', err.stack);
if (reconnectOnConnectionError) {
setTimeout(startConnect, RECONNECT_TIMEOUT);
} else {
@ -53,16 +54,16 @@ function connetPromise(reconnectOnConnectionError, closeCallback) {
}
} else {
conn.on('error', function(err) {
logger.error('[AMQP] conn error', err.stack);
operationContext.global.logger.error('[AMQP] conn error', err.stack);
});
var closeEventCallback = function() {
//in some case receive multiple close events
conn.removeListener('close', closeEventCallback);
logger.debug('[AMQP] conn close');
operationContext.global.logger.debug('[AMQP] conn close');
closeCallback();
};
conn.on('close', closeEventCallback);
logger.debug('[AMQP] connected');
operationContext.global.logger.debug('[AMQP] connected');
resolve(conn);
}
});

View File

@ -33,84 +33,102 @@
'use strict';
var config = require('config');
var utils = require('./utils');
var logger = require('./logger');
var storage = require('./' + config.get('storage.name'));
function getStoragePath(strPath) {
return strPath.replace(/\\/g, '/');
var tenantManager = require('./tenantManager');
const cfgCacheFolderName = config.get('storage.cacheFolderName');
function getStoragePath(ctx, strPath, opt_specialDir) {
opt_specialDir = opt_specialDir || cfgCacheFolderName;
return opt_specialDir + '/' + tenantManager.getTenantPathPrefix(ctx) + strPath.replace(/\\/g, '/')
}
exports.headObject = function(strPath) {
return storage.headObject(getStoragePath(strPath));
exports.headObject = function(ctx, strPath, opt_specialDir) {
return storage.headObject(getStoragePath(ctx, strPath, opt_specialDir));
};
exports.getObject = function(strPath) {
return storage.getObject(getStoragePath(strPath));
exports.getObject = function(ctx, strPath, opt_specialDir) {
return storage.getObject(getStoragePath(ctx, strPath, opt_specialDir));
};
exports.createReadStream = function(strPath) {
return storage.createReadStream(getStoragePath(strPath));
exports.createReadStream = function(ctx, strPath, opt_specialDir) {
return storage.createReadStream(getStoragePath(ctx, strPath, opt_specialDir));
};
exports.putObject = function(strPath, buffer, contentLength) {
return storage.putObject(getStoragePath(strPath), buffer, contentLength);
exports.putObject = function(ctx, strPath, buffer, contentLength, opt_specialDir) {
return storage.putObject(getStoragePath(ctx, strPath, opt_specialDir), buffer, contentLength);
};
exports.uploadObject = function(strPath, filePath) {
return storage.uploadObject(strPath, filePath);
exports.uploadObject = function(ctx, strPath, filePath, opt_specialDir) {
return storage.uploadObject(getStoragePath(ctx, strPath, opt_specialDir), filePath);
};
exports.copyObject = function(sourceKey, destinationKey) {
return storage.copyObject(sourceKey, destinationKey);
exports.copyObject = function(ctx, sourceKey, destinationKey, opt_specialDirSrc, opt_specialDirDst) {
let storageSrc = getStoragePath(ctx, sourceKey, opt_specialDirSrc);
let storageDst = getStoragePath(ctx, destinationKey, opt_specialDirDst);
return storage.copyObject(storageSrc, storageDst);
};
exports.copyPath = function(sourcePath, destinationPath) {
return exports.listObjects(getStoragePath(sourcePath)).then(function(list) {
exports.copyPath = function(ctx, sourcePath, destinationPath, opt_specialDirSrc, opt_specialDirDst) {
let storageSrc = getStoragePath(ctx, sourcePath, opt_specialDirSrc);
let storageDst = getStoragePath(ctx, destinationPath, opt_specialDirDst);
return storage.listObjects(storageSrc).then(function(list) {
return Promise.all(list.map(function(curValue) {
return exports.copyObject(curValue, destinationPath + '/' + exports.getRelativePath(sourcePath, curValue));
return storage.copyObject(curValue, storageDst + '/' + exports.getRelativePath(storageSrc, curValue));
}));
});
};
exports.listObjects = function(strPath) {
return storage.listObjects(getStoragePath(strPath)).catch(function(e) {
logger.error('storage.listObjects:\r\n%s', e.stack);
exports.listObjects = function(ctx, strPath, opt_specialDir) {
let prefix = getStoragePath(ctx, "", opt_specialDir);
return storage.listObjects(getStoragePath(ctx, strPath, opt_specialDir)).then(function(list) {
return list.map((currentValue) => {
return currentValue.substring(prefix.length);
});
}).catch(function(e) {
ctx.logger.error('storage.listObjects: %s', e.stack);
return [];
});
};
exports.deleteObject = function(strPath) {
return storage.deleteObject(getStoragePath(strPath));
exports.deleteObject = function(ctx, strPath, opt_specialDir) {
return storage.deleteObject(getStoragePath(ctx, strPath, opt_specialDir));
};
exports.deleteObjects = function(strPaths) {
exports.deleteObjects = function(ctx, strPaths, opt_specialDir) {
var StoragePaths = strPaths.map(function(curValue) {
return getStoragePath(curValue);
return getStoragePath(ctx, curValue, opt_specialDir);
});
return storage.deleteObjects(StoragePaths);
};
exports.deletePath = function(strPath) {
return exports.listObjects(getStoragePath(strPath)).then(function(list) {
return exports.deleteObjects(list);
exports.deletePath = function(ctx, strPath, opt_specialDir) {
let storageSrc = getStoragePath(ctx, strPath, opt_specialDir);
return storage.listObjects(storageSrc).then(function(list) {
return storage.deleteObjects(list);
});
};
exports.getSignedUrl = function(baseUrl, strPath, urlType, optFilename, opt_creationDate) {
return storage.getSignedUrl(baseUrl, getStoragePath(strPath), urlType, optFilename, opt_creationDate);
exports.getSignedUrl = function(ctx, baseUrl, strPath, urlType, optFilename, opt_creationDate, opt_specialDir) {
return storage.getSignedUrl(baseUrl, getStoragePath(ctx, strPath, opt_specialDir), urlType, optFilename, opt_creationDate);
};
exports.getSignedUrls = function(baseUrl, strPath, urlType, opt_creationDate) {
return exports.listObjects(getStoragePath(strPath)).then(function(list) {
exports.getSignedUrls = function(ctx, baseUrl, strPath, urlType, opt_creationDate, opt_specialDir) {
let storageSrc = getStoragePath(ctx, strPath, opt_specialDir);
return storage.listObjects(storageSrc).then(function(list) {
return Promise.all(list.map(function(curValue) {
return exports.getSignedUrl(baseUrl, curValue, urlType, undefined, opt_creationDate);
return storage.getSignedUrl(baseUrl, curValue, urlType, undefined, opt_creationDate);
})).then(function(urls) {
var outputMap = {};
for (var i = 0; i < list.length && i < urls.length; ++i) {
outputMap[exports.getRelativePath(strPath, list[i])] = urls[i];
outputMap[exports.getRelativePath(storageSrc, list[i])] = urls[i];
}
return outputMap;
});
});
};
exports.getSignedUrlsArrayByArray = function(baseUrl, list, urlType) {
return Promise.all(list.map(function(curValue) {
return exports.getSignedUrl(baseUrl, curValue, urlType, undefined);
exports.getSignedUrlsArrayByArray = function(ctx, baseUrl, list, urlType, opt_specialDir) {
return Promise.all(list.map(function(curValue) {
let storageSrc = getStoragePath(ctx, curValue, opt_specialDir);
return storage.getSignedUrl(baseUrl, storageSrc, urlType, undefined);
}));
};
exports.getSignedUrlsByArray = function(baseUrl, list, optPath, urlType) {
return exports.getSignedUrlsArrayByArray(baseUrl, list, urlType).then(function(urls) {
exports.getSignedUrlsByArray = function(ctx, baseUrl, list, optPath, urlType, opt_specialDir) {
return exports.getSignedUrlsArrayByArray(ctx, baseUrl, list, urlType, opt_specialDir).then(function(urls) {
var outputMap = {};
for (var i = 0; i < list.length && i < urls.length; ++i) {
if (optPath) {
outputMap[exports.getRelativePath(optPath, list[i])] = urls[i];
let storageSrc = getStoragePath(ctx, optPath, opt_specialDir);
outputMap[exports.getRelativePath(storageSrc, list[i])] = urls[i];
} else {
outputMap[list[i]] = urls[i];
}

View File

@ -41,6 +41,7 @@ var rabbitMQCore = require('./rabbitMQCore');
var activeMQCore = require('./activeMQCore');
const logger = require('./logger');
const commonDefines = require('./commondefines');
const operationContext = require('./operationContext');
const cfgMaxRedeliveredCount = config.get('FileConverter.converter.maxRedeliveredCount');
const cfgQueueType = config.get('queue.type');
@ -251,9 +252,9 @@ function clear(taskqueue) {
taskqueue.channelDelayed = null;
}
function* pushBackRedeliveredRabbit(taskqueue, message, ack) {
if (message.fields.redelivered) {
if (message?.fields?.redelivered) {
try {
logger.warn('checkRedelivered redelivered data=%j', message);
operationContext.global.logger.warn('checkRedelivered redelivered data=%j', message);
//remove current task and add new into tail of queue to remove redelivered flag
let data = message.content.toString();
let redeliveredCount = message.properties.headers['x-redelivered-count'];
@ -264,7 +265,7 @@ function* pushBackRedeliveredRabbit(taskqueue, message, ack) {
yield taskqueue.addResponse(taskqueue.simulateErrorResponse(data));
}
} catch (err) {
logger.error('checkRedelivered error: %s', err.stack);
operationContext.global.logger.error('checkRedelivered error: %s', err.stack);
} finally{
ack();
}
@ -274,14 +275,14 @@ function* pushBackRedeliveredRabbit(taskqueue, message, ack) {
}
function* pushBackRedeliveredActive(taskqueue, context, ack) {
if (undefined !== context.message.delivery_count) {
logger.warn('checkRedelivered redelivered data=%j', context.message);
operationContext.global.logger.warn('checkRedelivered redelivered data=%j', context.message);
if (context.message.delivery_count > cfgMaxRedeliveredCount) {
try {
if (taskqueue.simulateErrorResponse) {
yield taskqueue.addResponse(taskqueue.simulateErrorResponse(context.message.body));
}
} catch (err) {
logger.error('checkRedelivered error: %s', err.stack);
operationContext.global.logger.error('checkRedelivered error: %s', err.stack);
} finally {
ack();
}

View File

@ -0,0 +1,155 @@
/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
'use strict';
const config = require('config');
const co = require('co');
const NodeCache = require( "node-cache" );
const license = require('./../../Common/sources/license');
const constants = require('./../../Common/sources/constants');
const commonDefines = require('./../../Common/sources/commondefines');
const utils = require('./../../Common/sources/utils');
const { readFile } = require('fs/promises');
const path = require('path');
const oPackageType = config.get('license.packageType');
const cfgTenantsBaseDomain = config.get('tenants.baseDomain');
const cfgTenantsBaseDir = config.get('tenants.baseDir');
const cfgTenantsFilenameSecret = config.get('tenants.filenameSecret');
const cfgTenantsFilenameLicense = config.get('tenants.filenameLicense');
const cfgTenantsDefaultTenant = config.get('tenants.defaultTenant');
const cfgTenantsCache = config.get('tenants.cache');
const cfgSecretInbox = config.get('services.CoAuthoring.secret.inbox');
const cfgSecretOutbox = config.get('services.CoAuthoring.secret.outbox');
const cfgSecretSession = config.get('services.CoAuthoring.secret.session');
let licenseInfo;
let licenseOriginal;
const nodeCache = new NodeCache(cfgTenantsCache);
function getDefautTenant() {
return cfgTenantsDefaultTenant;
}
function getTenant(ctx, domain) {
let tenant = getDefautTenant();
if (domain) {
//remove port
domain = domain.replace(/\:.*$/, '');
tenant = domain;
if (cfgTenantsBaseDomain) {
let index = domain.indexOf('.' + cfgTenantsBaseDomain);
if (-1 !== index) {
tenant = domain.substring(0, index);
}
}
}
return tenant;
}
function getTenantByConnection(ctx, conn) {
return isMultitenantMode() ? getTenant(ctx, utils.getDomainByConnection(ctx, conn)) : getDefautTenant();
}
function getTenantByRequest(ctx, req) {
return isMultitenantMode() ? getTenant(ctx, utils.getDomainByRequest(ctx, req)) : getDefautTenant();
}
function getTenantPathPrefix(ctx) {
return isMultitenantMode() ? utils.removeIllegalCharacters(ctx.tenant) + '/' : '';
}
function getTenantSecret(ctx, type) {
return co(function*() {
let res = undefined;
if (isMultitenantMode()) {
let tenantPath = utils.removeIllegalCharacters(ctx.tenant);
let secretPath = path.join(cfgTenantsBaseDir, tenantPath, cfgTenantsFilenameSecret);
res = nodeCache.get(secretPath);
if (res) {
ctx.logger.debug('getTenantSecret from cache');
} else {
res = yield readFile(secretPath, {encoding: 'utf8'});
nodeCache.set(secretPath, res);
ctx.logger.debug('getTenantSecret from %s', secretPath);
}
} else {
switch (type) {
case commonDefines.c_oAscSecretType.Browser:
case commonDefines.c_oAscSecretType.Inbox:
res = utils.getSecretByElem(cfgSecretInbox);
break;
case commonDefines.c_oAscSecretType.Outbox:
res = utils.getSecretByElem(cfgSecretOutbox);
break;
case commonDefines.c_oAscSecretType.Session:
res = utils.getSecretByElem(cfgSecretSession);
break;
}
}
return res;
});
}
function setDefLicense(data, original) {
licenseInfo = data;
licenseOriginal = original;
}
function getTenantLicense(ctx) {
return co(function*() {
let res = undefined;
if (isMultitenantMode()) {
let tenantPath = utils.removeIllegalCharacters(ctx.tenant);
let licensePath = path.join(cfgTenantsBaseDir, tenantPath, cfgTenantsFilenameLicense);
res = nodeCache.get(licensePath);
if (res) {
ctx.logger.debug('getTenantLicense from cache');
} else {
[res] = yield* license.readLicense(licensePath);
nodeCache.set(licensePath, res);
ctx.logger.debug('getTenantLicense from %s', licensePath);
}
} else {
res = licenseInfo;
}
return res;
});
}
function isMultitenantMode() {
return !!cfgTenantsBaseDir;
}
exports.getDefautTenant = getDefautTenant;
exports.getTenantByConnection = getTenantByConnection;
exports.getTenantByRequest = getTenantByRequest;
exports.getTenantPathPrefix = getTenantPathPrefix;
exports.getTenantSecret = getTenantSecret;
exports.getTenantLicense = getTenantLicense;
exports.setDefLicense = setDefLicense;
exports.isMultitenantMode = isMultitenantMode;

View File

@ -72,7 +72,6 @@ var cfgTokenOutboxHeader = config.get('services.CoAuthoring.token.outbox.header'
var cfgTokenOutboxPrefix = config.get('services.CoAuthoring.token.outbox.prefix');
var cfgTokenOutboxAlgorithm = config.get('services.CoAuthoring.token.outbox.algorithm');
var cfgTokenOutboxExpires = config.get('services.CoAuthoring.token.outbox.expires');
var cfgSignatureSecretOutbox = config.get('services.CoAuthoring.secret.outbox');
var cfgVisibilityTimeout = config.get('queue.visibilityTimeout');
var cfgQueueRetentionPeriod = config.get('queue.retentionPeriod');
var cfgRequestDefaults = config.get('services.CoAuthoring.requestDefaults');
@ -261,13 +260,13 @@ function raiseErrorObj(ro, error) {
function isRedirectResponse(response) {
return response && response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location');
}
function downloadUrlPromise(uri, optTimeout, optLimit, opt_Authorization, opt_filterPrivate, opt_headers, opt_streamWriter) {
function downloadUrlPromise(ctx, uri, optTimeout, optLimit, opt_Authorization, opt_filterPrivate, opt_headers, opt_streamWriter) {
//todo replace deprecated request module
const maxRedirects = (undefined !== cfgRequestDefaults.maxRedirects) ? cfgRequestDefaults.maxRedirects : 10;
const followRedirect = (undefined !== cfgRequestDefaults.followRedirect) ? cfgRequestDefaults.followRedirect : true;
var redirectsFollowed = 0;
let doRequest = function(curUrl) {
return downloadUrlPromiseWithoutRedirect(curUrl, optTimeout, optLimit, opt_Authorization, opt_filterPrivate, opt_headers, opt_streamWriter)
return downloadUrlPromiseWithoutRedirect(ctx, curUrl, optTimeout, optLimit, opt_Authorization, opt_filterPrivate, opt_headers, opt_streamWriter)
.catch(function(err) {
let response = err.response;
if (isRedirectResponse(response)) {
@ -277,7 +276,7 @@ function downloadUrlPromise(uri, optTimeout, optLimit, opt_Authorization, opt_fi
redirectTo = url.resolve(err.request.uri.href, redirectTo)
}
logger.debug('downloadUrlPromise redirectsFollowed:%d redirectTo: %s', redirectsFollowed, redirectTo);
ctx.logger.debug('downloadUrlPromise redirectsFollowed:%d redirectTo: %s', redirectsFollowed, redirectTo);
redirectsFollowed++;
return doRequest(redirectTo);
}
@ -287,7 +286,7 @@ function downloadUrlPromise(uri, optTimeout, optLimit, opt_Authorization, opt_fi
};
return doRequest(uri);
}
function downloadUrlPromiseWithoutRedirect(uri, optTimeout, optLimit, opt_Authorization, opt_filterPrivate, opt_headers, opt_streamWriter) {
function downloadUrlPromiseWithoutRedirect(ctx, uri, optTimeout, optLimit, opt_Authorization, opt_filterPrivate, opt_headers, opt_streamWriter) {
return new Promise(function (resolve, reject) {
//IRI to URI
uri = URI.serialize(URI.parse(uri));
@ -323,7 +322,7 @@ function downloadUrlPromiseWithoutRedirect(uri, optTimeout, optLimit, opt_Author
} else {
var contentLength = response.caseless.get('content-length');
if (contentLength && body.length !== (contentLength - 0)) {
logger.warn('downloadUrlPromise body size mismatch: uri=%s; content-length=%s; body.length=%d', uri, contentLength, body.length);
ctx.logger.warn('downloadUrlPromise body size mismatch: uri=%s; content-length=%s; body.length=%d', uri, contentLength, body.length);
}
resolve({response: response, body: body});
}
@ -654,6 +653,9 @@ function containsAllAsciiNP(str) {
return /^[\040-\176]*$/.test(str);//non-printing characters
}
exports.containsAllAsciiNP = containsAllAsciiNP;
function getDomain(hostHeader, forwardedHostHeader) {
return forwardedHostHeader || hostHeader || 'localhost';
};
function getBaseUrl(protocol, hostHeader, forwardedProtoHeader, forwardedHostHeader, forwardedPrefixHeader) {
var url = '';
if (forwardedProtoHeader) {
@ -664,13 +666,7 @@ function getBaseUrl(protocol, hostHeader, forwardedProtoHeader, forwardedHostHea
url += 'http';
}
url += '://';
if (forwardedHostHeader) {
url += forwardedHostHeader;
} else if (hostHeader) {
url += hostHeader;
} else {
url += 'localhost';
}
url += getDomain(hostHeader, forwardedHostHeader);
if (forwardedPrefixHeader) {
url += forwardedPrefixHeader;
}
@ -684,6 +680,20 @@ function getBaseUrlByRequest(req) {
}
exports.getBaseUrlByConnection = getBaseUrlByConnection;
exports.getBaseUrlByRequest = getBaseUrlByRequest;
function getDomainByConnection(ctx, conn) {
let host = conn.headers['host'];
let forwardedHost = conn.headers['x-forwarded-host'];
ctx.logger.debug("getDomainByConnection headers['host']=%s headers['x-forwarded-host']=%s", host, forwardedHost);
return getDomain(host, forwardedHost);
}
function getDomainByRequest(ctx, req) {
let host = req.get('host');
let forwardedHost = req.get('x-forwarded-host');
ctx.logger.debug("getDomainByRequest headers['host']=%s headers['x-forwarded-host']=%s", host, forwardedHost);
return getDomain(req.get('host'), req.get('x-forwarded-host'));
}
exports.getDomainByConnection = getDomainByConnection;
exports.getDomainByRequest = getDomainByRequest;
function stream2Buffer(stream) {
return new Promise(function(resolve, reject) {
if (!stream.readable) {
@ -761,14 +771,14 @@ function checkIpFilter(ipString, opt_hostname) {
return status;
}
exports.checkIpFilter = checkIpFilter;
function* checkHostFilter(hostname) {
function* checkHostFilter(ctx, hostname) {
let status = 0;
let hostIp;
try {
hostIp = yield dnsLookup(hostname);
} catch (e) {
status = cfgIpFilterErrorCode;
logger.error('dnsLookup error: hostname = %s\r\n%s', hostname, e.stack);
ctx.logger.error('dnsLookup error: hostname = %s %s', hostname, e.stack);
}
if (0 === status) {
status = checkIpFilter(hostIp, hostname);
@ -832,29 +842,7 @@ function getSecretByElem(secretElem) {
return secret;
}
exports.getSecretByElem = getSecretByElem;
function getSecret(docId, secretElem, opt_iss, opt_token) {
if (!isEmptyObject(secretElem.tenants)) {
var iss;
if (opt_token) {
//look for issuer
var decodedTemp = jwt.decode(opt_token);
if (decodedTemp && decodedTemp.iss) {
iss = decodedTemp.iss;
}
} else {
iss = opt_iss;
}
if (iss) {
secretElem = secretElem.tenants[iss];
if (!secretElem) {
logger.error('getSecret unknown issuer: docId = %s iss = %s', docId, iss);
}
}
}
return getSecretByElem(secretElem);
}
exports.getSecret = getSecret;
function fillJwtForRequest(payload, opt_inBody) {
function fillJwtForRequest(payload, secret, opt_inBody) {
//todo refuse prototypes in payload(they are simple getter/setter).
//JSON.parse/stringify is more universal but Object.assign is enough for our inputs
payload = Object.assign(Object.create(null), payload);
@ -866,7 +854,6 @@ function fillJwtForRequest(payload, opt_inBody) {
}
let options = {algorithm: cfgTokenOutboxAlgorithm, expiresIn: cfgTokenOutboxExpires};
let secret = getSecretByElem(cfgSignatureSecretOutbox);
return jwt.sign(data, secret, options);
}
exports.fillJwtForRequest = fillJwtForRequest;
@ -874,13 +861,13 @@ exports.forwarded = forwarded;
exports.getIndexFromUserId = function(userId, userIdOriginal){
return parseInt(userId.substring(userIdOriginal.length));
};
exports.checkPathTraversal = function(docId, rootDirectory, filename) {
exports.checkPathTraversal = function(ctx, docId, rootDirectory, filename) {
if (filename.indexOf('\0') !== -1) {
logger.warn('checkPathTraversal Poison Null Bytes docId=%s filename=%s', docId, filename);
ctx.logger.warn('checkPathTraversal Poison Null Bytes filename=%s', filename);
return false;
}
if (!filename.startsWith(rootDirectory)) {
logger.warn('checkPathTraversal Path Traversal docId=%s filename=%s', docId, filename);
ctx.logger.warn('checkPathTraversal Path Traversal filename=%s', filename);
return false;
}
return true;
@ -895,6 +882,7 @@ exports.getConnectionInfo = function(conn){
view: user.view,
connectionId: conn.id,
isCloseCoAuthoring: conn.isCloseCoAuthoring,
isLiveViewer: exports.isLiveViewer(conn),
encrypted: conn.encrypted
};
return data;
@ -902,14 +890,17 @@ exports.getConnectionInfo = function(conn){
exports.getConnectionInfoStr = function(conn){
return JSON.stringify(exports.getConnectionInfo(conn));
};
exports.canIncludeOutboxAuthorization = function (url) {
exports.isLiveViewer = function(conn){
return conn.user?.view && "fast" === conn.coEditingMode;
};
exports.canIncludeOutboxAuthorization = function (ctx, url) {
if (cfgTokenEnableRequestOutbox) {
if (!outboxUrlExclusionRegex) {
return true;
} else if (!outboxUrlExclusionRegex.test(url)) {
return true;
} else {
logger.debug('canIncludeOutboxAuthorization excluded by token.outbox.urlExclusionRegex url=%s', url);
ctx.logger.debug('canIncludeOutboxAuthorization excluded by token.outbox.urlExclusionRegex url=%s', url);
}
}
return false;
@ -955,9 +946,12 @@ exports.convertLicenseInfoToFileParams = function(licenseInfo) {
license.light = licenseInfo.light;
license.branding = licenseInfo.branding;
license.customization = licenseInfo.customization;
license.advanced_api = licenseInfo.advancedApi;
license.plugins = licenseInfo.plugins;
license.connections = licenseInfo.connections;
license.connections_view = licenseInfo.connectionsView;
license.users_count = licenseInfo.usersCount;
license.users_view_count = licenseInfo.usersViewCount;
license.users_expire = licenseInfo.usersExpire / constants.LICENSE_EXPIRE_USERS_ONE_DAY;
return license;
};
@ -976,8 +970,7 @@ exports.checkBaseUrl = function(baseUrl) {
};
exports.resolvePath = function(object, path, defaultValue) {
return path.split('.').reduce((o, p) => o ? o[p] : defaultValue, object);
}
};
Date.isLeapYear = function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};
@ -1018,3 +1011,15 @@ exports.getLicensePeriod = function(startDate, now) {
startDate.setUTCHours(0,0,0,0);
return startDate.getTime();
};
exports.removeIllegalCharacters = function(filename) {
return filename?.replace(/[/\\?%*:|"<>]/g, '-') || filename;
}
exports.getFunctionArguments = function(func) {
return func.toString().
replace(/[\r\n\s]+/g, ' ').
match(/(?:function\s*\w*)?\s*(?:\((.*?)\)|([^\s]+))/).
slice(1, 3).
join('').
split(/\s*,\s*/);
};

View File

@ -59,11 +59,6 @@
"resolved": "https://registry.npmjs.org/base64-stream/-/base64-stream-1.0.0.tgz",
"integrity": "sha512-BQQZftaO48FcE1Kof9CmXMFaAdqkcNorgc8CxesZv9nMbbTF1EFyQe89UOuh//QMmdtfUDXyO8rgUalemL5ODA=="
},
"bignumber.js": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
"integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA=="
},
"body-parser": {
"version": "1.18.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.3.tgz",
@ -220,6 +215,11 @@
"resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz",
"integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU="
},
"denque": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/denque/-/denque-2.0.1.tgz",
"integrity": "sha512-tfiWc6BQLXNLpNiR5iGd0Ocu3P3VpxfzFiqubLgMfhfOw9WyvgJBd46CClNn9k3qfbjvT//0cf7AlYRX/OslMQ=="
},
"depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
@ -489,6 +489,14 @@
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
},
"generate-function": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
"requires": {
"is-property": "^1.0.2"
}
},
"http-errors": {
"version": "1.6.3",
"resolved": "http://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz",
@ -523,6 +531,11 @@
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="
},
"is-property": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
"integrity": "sha1-V/4cTkhHTt1lsJkR8msc1Ald2oQ="
},
"isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
@ -611,6 +624,19 @@
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w="
},
"long": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz",
"integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA=="
},
"lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"requires": {
"yallist": "^4.0.0"
}
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
@ -727,15 +753,58 @@
}
}
},
"mysql": {
"version": "2.16.0",
"resolved": "https://registry.npmjs.org/mysql/-/mysql-2.16.0.tgz",
"integrity": "sha512-dPbN2LHonQp7D5ja5DJXNbCLe/HRdu+f3v61aguzNRQIrmZLOeRoymBYyeThrR6ug+FqzDL95Gc9maqZUJS+Gw==",
"mysql2": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-2.3.3.tgz",
"integrity": "sha512-wxJUev6LgMSgACDkb/InIFxDprRa6T95+VEoR+xPvtngtccNH2dGjEB/fVZ8yg1gWv1510c9CvXuJHi5zUm0ZA==",
"requires": {
"bignumber.js": "4.1.0",
"readable-stream": "2.3.6",
"safe-buffer": "5.1.2",
"sqlstring": "2.3.1"
"denque": "^2.0.1",
"generate-function": "^2.3.1",
"iconv-lite": "^0.6.3",
"long": "^4.0.0",
"lru-cache": "^6.0.0",
"named-placeholders": "^1.1.2",
"seq-queue": "^0.0.5",
"sqlstring": "^2.3.2"
},
"dependencies": {
"iconv-lite": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
"requires": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
}
},
"sqlstring": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz",
"integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg=="
}
}
},
"named-placeholders": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.2.tgz",
"integrity": "sha512-wiFWqxoLL3PGVReSZpjLVxyJ1bRqe+KKJVbr4hGs1KWfTZTQyezHFBbuKj9hsizHyGV2ne7EMjHdxEGAybD5SA==",
"requires": {
"lru-cache": "^4.1.3"
},
"dependencies": {
"lru-cache": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz",
"integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==",
"requires": {
"pseudomap": "^1.0.2",
"yallist": "^2.1.2"
}
},
"yallist": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz",
"integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI="
}
}
},
"negotiator": {
@ -867,6 +936,11 @@
"ipaddr.js": "1.9.1"
}
},
"pseudomap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz",
"integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM="
},
"punycode": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz",
@ -1020,6 +1094,11 @@
}
}
},
"seq-queue": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz",
"integrity": "sha1-1WgS4cAXpuTnw+Ojeh2m143TyT4="
},
"serve-static": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz",
@ -1066,11 +1145,6 @@
}
}
},
"sqlstring": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz",
"integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A="
},
"statuses": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
@ -1186,6 +1260,11 @@
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="
},
"yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
}
}
}

View File

@ -29,7 +29,7 @@
"multer": "^1.4.3",
"multi-integer-range": "^4.0.7",
"multiparty": "^4.2.1",
"mysql": "^2.16.0",
"mysql2": "^2.3.3",
"pg": "^8.5.1",
"redis": "^2.8.0",
"retry": "^0.12.0",

File diff suppressed because it is too large Load Diff

View File

@ -40,7 +40,6 @@ var sqlDataBaseType = {
var config = require('config').get('services.CoAuthoring.sql');
var baseConnector = (sqlDataBaseType.mySql === config.get('type') || sqlDataBaseType.mariaDB === config.get('type')) ? require('./mySqlBaseConnector') : require('./postgreSqlBaseConnector');
var logger = require('./../../Common/sources/logger');
let constants = require('./../../Common/sources/constants');
const tableChanges = config.get('tableChanges'),
@ -52,9 +51,9 @@ let addSqlParam = baseConnector.addSqlParameter;
var maxPacketSize = config.get('max_allowed_packet'); // Размер по умолчанию для запроса в базу данных 1Mb - 1 (т.к. он не пишет 1048575, а пишет 1048574)
exports.baseConnector = baseConnector;
exports.insertChangesPromiseCompatibility = function (objChanges, docId, index, user) {
exports.insertChangesPromiseCompatibility = function (ctx, objChanges, docId, index, user) {
return new Promise(function(resolve, reject) {
_insertChangesCallback(0, objChanges, docId, index, user, function(error, result) {
_insertChangesCallback(ctx, 0, objChanges, docId, index, user, function(error, result) {
if (error) {
reject(error);
} else {
@ -63,13 +62,13 @@ exports.insertChangesPromiseCompatibility = function (objChanges, docId, index,
});
});
};
exports.insertChangesPromiseFast = function (objChanges, docId, index, user) {
exports.insertChangesPromiseFast = function (ctx, objChanges, docId, index, user) {
return new Promise(function(resolve, reject) {
baseConnector.insertChanges(tableChanges, 0, objChanges, docId, index, user, function(error, result, isSupported) {
baseConnector.insertChanges(ctx, tableChanges, 0, objChanges, docId, index, user, function(error, result, isSupported) {
isSupportFastInsert = isSupported;
if (error) {
if (!isSupportFastInsert) {
resolve(exports.insertChangesPromiseCompatibility(objChanges, docId, index, user));
resolve(exports.insertChangesPromiseCompatibility(ctx, objChanges, docId, index, user));
} else {
reject(error);
}
@ -79,11 +78,11 @@ exports.insertChangesPromiseFast = function (objChanges, docId, index, user) {
});
});
};
exports.insertChangesPromise = function (objChanges, docId, index, user) {
exports.insertChangesPromise = function (ctx, objChanges, docId, index, user) {
if (isSupportFastInsert) {
return exports.insertChangesPromiseFast(objChanges, docId, index, user);
return exports.insertChangesPromiseFast(ctx, objChanges, docId, index, user);
} else {
return exports.insertChangesPromiseCompatibility(objChanges, docId, index, user);
return exports.insertChangesPromiseCompatibility(ctx, objChanges, docId, index, user);
}
};
@ -93,7 +92,7 @@ function _getDateTime2(oDate) {
exports.getDateTime = _getDateTime2;
function _insertChangesCallback (startIndex, objChanges, docId, index, user, callback) {
function _insertChangesCallback (ctx, startIndex, objChanges, docId, index, user, callback) {
var sqlCommand = `INSERT INTO ${tableChanges} VALUES`;
var i = startIndex, l = objChanges.length, lengthUtf8Current = sqlCommand.length, lengthUtf8Row = 0, values = [];
if (i === l)
@ -106,13 +105,14 @@ function _insertChangesCallback (startIndex, objChanges, docId, index, user, cal
if (lengthUtf8Row + lengthUtf8Current >= maxPacketSize && i > startIndex) {
sqlCommand += ';';
(function(tmpStart, tmpIndex) {
baseConnector.sqlQuery(sqlCommand, function() {
baseConnector.sqlQuery(ctx, sqlCommand, function() {
// lock не снимаем, а продолжаем добавлять
_insertChangesCallback(tmpStart, objChanges, docId, tmpIndex, user, callback);
_insertChangesCallback(ctx, tmpStart, objChanges, docId, tmpIndex, user, callback);
}, undefined, undefined, values);
})(i, index);
return;
}
let p0 = addSqlParam(ctx.tenant, values);
let p1 = addSqlParam(docId, values);
let p2 = addSqlParam(index, values);
let p3 = addSqlParam(user.id, values);
@ -123,27 +123,28 @@ function _insertChangesCallback (startIndex, objChanges, docId, index, user, cal
if (i > startIndex) {
sqlCommand += ',';
}
sqlCommand += `(${p1},${p2},${p3},${p4},${p5},${p6},${p7})`;
sqlCommand += `(${p0},${p1},${p2},${p3},${p4},${p5},${p6},${p7})`;
lengthUtf8Current += lengthUtf8Row;
}
sqlCommand += ';';
baseConnector.sqlQuery(sqlCommand, callback, undefined, undefined, values);
baseConnector.sqlQuery(ctx, sqlCommand, callback, undefined, undefined, values);
}
exports.deleteChangesCallback = function(docId, deleteIndex, callback) {
exports.deleteChangesCallback = function(ctx, docId, deleteIndex, callback) {
let sqlCommand, values = [];
let sqlParam1 = addSqlParam(docId, values);
let p1 = addSqlParam(ctx.tenant, values);
let p2 = addSqlParam(docId, values);
if (null !== deleteIndex) {
let sqlParam2 = addSqlParam(deleteIndex, values);
sqlCommand = `DELETE FROM ${tableChanges} WHERE id=${sqlParam1} AND change_id >= ${sqlParam2};`;
sqlCommand = `DELETE FROM ${tableChanges} WHERE tenant=${p1} AND id=${p2} AND change_id >= ${sqlParam2};`;
} else {
sqlCommand = `DELETE FROM ${tableChanges} WHERE id=${sqlParam1};`;
sqlCommand = `DELETE FROM ${tableChanges} WHERE tenant=${p1} AND id=${p2};`;
}
baseConnector.sqlQuery(sqlCommand, callback, undefined, undefined, values);
baseConnector.sqlQuery(ctx, sqlCommand, callback, undefined, undefined, values);
};
exports.deleteChangesPromise = function (docId, deleteIndex) {
exports.deleteChangesPromise = function (ctx, docId, deleteIndex) {
return new Promise(function(resolve, reject) {
exports.deleteChangesCallback(docId, deleteIndex, function(error, result) {
exports.deleteChangesCallback(ctx, docId, deleteIndex, function(error, result) {
if (error) {
reject(error);
} else {
@ -152,21 +153,22 @@ exports.deleteChangesPromise = function (docId, deleteIndex) {
});
});
};
exports.deleteChanges = function (docId, deleteIndex) {
lockCriticalSection(docId, function () {_deleteChanges(docId, deleteIndex);});
exports.deleteChanges = function (ctx, docId, deleteIndex) {
lockCriticalSection(docId, function () {_deleteChanges(ctx, docId, deleteIndex);});
};
function _deleteChanges (docId, deleteIndex) {
exports.deleteChangesCallback(docId, deleteIndex, function () {unLockCriticalSection(docId);});
function _deleteChanges (ctx, docId, deleteIndex) {
exports.deleteChangesCallback(ctx, docId, deleteIndex, function () {unLockCriticalSection(docId);});
}
exports.getChangesIndex = function(docId, callback) {
exports.getChangesIndex = function(ctx, docId, callback) {
let values = [];
let sqlParam = addSqlParam(docId, values);
var sqlCommand = `SELECT MAX(change_id) as change_id FROM ${tableChanges} WHERE id=${sqlParam};`;
baseConnector.sqlQuery(sqlCommand, callback, undefined, undefined, values);
let p1 = addSqlParam(ctx.tenant, values);
let p2 = addSqlParam(docId, values);
var sqlCommand = `SELECT MAX(change_id) as change_id FROM ${tableChanges} WHERE tenant=${p1} AND id=${p2};`;
baseConnector.sqlQuery(ctx, sqlCommand, callback, undefined, undefined, values);
};
exports.getChangesIndexPromise = function(docId) {
exports.getChangesIndexPromise = function(ctx, docId) {
return new Promise(function(resolve, reject) {
exports.getChangesIndex(docId, function(error, result) {
exports.getChangesIndex(ctx, docId, function(error, result) {
if (error) {
reject(error);
} else {
@ -175,11 +177,13 @@ exports.getChangesIndexPromise = function(docId) {
});
});
};
exports.getChangesPromise = function (docId, optStartIndex, optEndIndex, opt_time) {
exports.getChangesPromise = function (ctx, docId, optStartIndex, optEndIndex, opt_time) {
return new Promise(function(resolve, reject) {
let values = [];
let sqlParam = addSqlParam(docId, values);
let sqlWhere = `id=${sqlParam}`;
let sqlParam = addSqlParam(ctx.tenant, values);
let sqlWhere = `tenant=${sqlParam}`;
sqlParam = addSqlParam(docId, values);
sqlWhere += ` AND id=${sqlParam}`;
if (null != optStartIndex) {
sqlParam = addSqlParam(optStartIndex, values);
sqlWhere += ` AND change_id>=${sqlParam}`;
@ -198,7 +202,7 @@ exports.getChangesPromise = function (docId, optStartIndex, optEndIndex, opt_tim
sqlWhere += ' ORDER BY change_id ASC';
var sqlCommand = `SELECT * FROM ${tableChanges} WHERE ${sqlWhere};`;
baseConnector.sqlQuery(sqlCommand, function(error, result) {
baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {
@ -207,23 +211,6 @@ exports.getChangesPromise = function (docId, optStartIndex, optEndIndex, opt_tim
}, undefined, undefined, values);
});
};
exports.checkStatusFile = function (docId, callbackFunction) {
let values = [];
let sqlParam = addSqlParam(docId, values);
var sqlCommand = `SELECT status, status_info FROM ${tableResult} WHERE id=${sqlParam};`;
baseConnector.sqlQuery(sqlCommand, callbackFunction, undefined, undefined, values);
};
exports.checkStatusFilePromise = function (docId) {
return new Promise(function(resolve, reject) {
exports.checkStatusFile(docId, function(error, result) {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
};
exports.isLockCriticalSection = function (id) {
return !!(g_oCriticalSection[id]);
@ -249,11 +236,11 @@ function unLockCriticalSection (id) {
else
delete g_oCriticalSection[id];
}
exports.healthCheck = function () {
exports.healthCheck = function (ctx) {
return new Promise(function(resolve, reject) {
//SELECT 1; usefull for H2, MySQL, Microsoft SQL Server, PostgreSQL, SQLite
//http://stackoverflow.com/questions/3668506/efficient-sql-test-query-or-validation-query-that-will-work-across-all-or-most
baseConnector.sqlQuery('SELECT 1;', function(error, result) {
baseConnector.sqlQuery(ctx, 'SELECT 1;', function(error, result) {
if (error) {
reject(error);
} else {
@ -263,10 +250,22 @@ exports.healthCheck = function () {
});
};
exports.getEmptyCallbacks = function() {
exports.getEmptyCallbacks = function(ctx) {
return new Promise(function(resolve, reject) {
const sqlCommand = "SELECT DISTINCT t1.id FROM doc_changes t1 LEFT JOIN task_result t2 ON t2.id = t1.id WHERE t2.callback = '';";
baseConnector.sqlQuery(sqlCommand, function(error, result) {
const sqlCommand = "SELECT DISTINCT t1.tenant, t1.id FROM doc_changes t1 LEFT JOIN task_result t2 ON t2.tenant = t1.tenant AND t2.id = t1.id WHERE t2.callback = '';";
baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
};
exports.getTableColumns = function(ctx, tableName) {
return new Promise(function(resolve, reject) {
const sqlCommand = `SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME = '${tableName}';`;
baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {
@ -291,8 +290,8 @@ UserCallback.prototype.delimiter = constants.CHAR_DELIMITER;
UserCallback.prototype.toSQLInsert = function(){
return this.delimiter + JSON.stringify(this);
};
UserCallback.prototype.getCallbackByUserIndex = function(docId, callbacksStr, opt_userIndex) {
logger.debug("getCallbackByUserIndex: docId = %s userIndex = %s callbacks = %s", docId, opt_userIndex, callbacksStr);
UserCallback.prototype.getCallbackByUserIndex = function(ctx, callbacksStr, opt_userIndex) {
ctx.logger.debug("getCallbackByUserIndex: userIndex = %s callbacks = %s", opt_userIndex, callbacksStr);
if (!callbacksStr || !callbacksStr.startsWith(UserCallback.prototype.delimiter)) {
let index = callbacksStr.indexOf(UserCallback.prototype.delimiter);
if (-1 === index) {
@ -314,8 +313,8 @@ UserCallback.prototype.getCallbackByUserIndex = function(docId, callbacksStr, op
}
return callbackUrl;
};
UserCallback.prototype.getCallbacks = function(docId, callbacksStr) {
logger.debug("getCallbacks: docId = %s callbacks = %s", docId, callbacksStr);
UserCallback.prototype.getCallbacks = function(ctx, callbacksStr) {
ctx.logger.debug("getCallbacks: callbacks = %s", callbacksStr);
if (!callbacksStr || !callbacksStr.startsWith(UserCallback.prototype.delimiter)) {
let index = callbacksStr.indexOf(UserCallback.prototype.delimiter);
if (-1 === index) {
@ -359,10 +358,10 @@ DocumentPassword.prototype.toSQLInsert = function(){
DocumentPassword.prototype.isInitial = function(){
return !this.change;
};
DocumentPassword.prototype.getDocPassword = function(docId, docPasswordStr) {
DocumentPassword.prototype.getDocPassword = function(ctx, docPasswordStr) {
let res = {initial: undefined, current: undefined, change: undefined};
if (docPasswordStr) {
logger.debug("getDocPassword: docId = %s passwords = %s", docId, docPasswordStr);
ctx.logger.debug("getDocPassword: passwords = %s", docPasswordStr);
let passwords = docPasswordStr.split(UserCallback.prototype.delimiter);
for (let i = 1; i < passwords.length; ++i) {
@ -378,12 +377,12 @@ DocumentPassword.prototype.getDocPassword = function(docId, docPasswordStr) {
}
return res;
};
DocumentPassword.prototype.getCurPassword = function(docId, docPasswordStr) {
let docPassword = this.getDocPassword(docId, docPasswordStr);
DocumentPassword.prototype.getCurPassword = function(ctx, docPasswordStr) {
let docPassword = this.getDocPassword(ctx, docPasswordStr);
return docPassword.current;
};
DocumentPassword.prototype.hasPasswordChanges = function(docId, docPasswordStr) {
let docPassword = this.getDocPassword(docId, docPasswordStr);
DocumentPassword.prototype.hasPasswordChanges = function(ctx, docPasswordStr) {
let docPassword = this.getDocPassword(ctx, docPasswordStr);
return docPassword.initial !== docPassword.current;
};
exports.DocumentPassword = DocumentPassword;

File diff suppressed because it is too large Load Diff

View File

@ -37,7 +37,6 @@ var config = require('config');
var co = require('co');
const locale = require('windows-locale');
var taskResult = require('./taskresult');
var logger = require('./../../Common/sources/logger');
var utils = require('./../../Common/sources/utils');
var constants = require('./../../Common/sources/constants');
var commonDefines = require('./../../Common/sources/commondefines');
@ -47,26 +46,46 @@ var storage = require('./../../Common/sources/storage-base');
var formatChecker = require('./../../Common/sources/formatchecker');
var statsDClient = require('./../../Common/sources/statsdclient');
var storageBase = require('./../../Common/sources/storage-base');
var operationContext = require('./../../Common/sources/operationContext');
const sqlBase = require('./baseConnector');
var CONVERT_ASYNC_DELAY = 1000;
var clientStatsD = statsDClient.getClient();
function* getConvertStatus(cmd, selectRes) {
function* getConvertStatus(ctx, cmd, selectRes, opt_checkPassword) {
var status = new commonDefines.ConvertStatus(constants.NO_ERROR);
if (selectRes.length > 0) {
var docId = cmd.getDocId();
var row = selectRes[0];
let password = opt_checkPassword && sqlBase.DocumentPassword.prototype.getCurPassword(ctx, row.password);
switch (row.status) {
case taskResult.FileStatus.Ok:
status.end = true;
if (password) {
let encryptedUserPassword = cmd.getPassword();
let isCorrectPassword;
if (encryptedUserPassword) {
let decryptedPassword = yield utils.decryptPassword(password);
let userPassword = yield utils.decryptPassword(encryptedUserPassword);
isCorrectPassword = decryptedPassword === userPassword;
}
if (isCorrectPassword) {
ctx.logger.debug("getConvertStatus password match");
status.end = true;
} else {
ctx.logger.debug("getConvertStatus password mismatch");
status.err = constants.CONVERT_PASSWORD;
}
} else {
status.end = true;
}
break;
case taskResult.FileStatus.Err:
case taskResult.FileStatus.ErrToReload:
case taskResult.FileStatus.NeedPassword:
status.err = row.status_info;
if (taskResult.FileStatus.ErrToReload == row.status || taskResult.FileStatus.NeedPassword == row.status) {
yield canvasService.cleanupCache(docId);
yield canvasService.cleanupCache(ctx);
}
break;
case taskResult.FileStatus.NeedParams:
@ -84,9 +103,9 @@ function* getConvertStatus(cmd, selectRes) {
}
return status;
}
function* getConvertPath(docId, fileTo, formatTo) {
function* getConvertPath(ctx, docId, fileTo, formatTo) {
if (constants.AVS_OFFICESTUDIO_FILE_OTHER_OOXML === formatTo || constants.AVS_OFFICESTUDIO_FILE_OTHER_ODF === formatTo) {
let list = yield storage.listObjects(docId);
let list = yield storage.listObjects(ctx, docId);
let baseName = path.basename(fileTo, path.extname(fileTo));
for (let i = 0; i < list.length; ++i) {
if (path.basename(list[i], path.extname(list[i])) === baseName) {
@ -96,28 +115,29 @@ function* getConvertPath(docId, fileTo, formatTo) {
}
return docId + '/' + fileTo;
}
function* getConvertUrl(baseUrl, fileToPath, title) {
function* getConvertUrl(ctx, baseUrl, fileToPath, title) {
if (title) {
title = path.basename(title, path.extname(title)) + path.extname(fileToPath);
}
return yield storage.getSignedUrl(baseUrl, fileToPath, commonDefines.c_oAscUrlTypes.Temporary, title);
return yield storage.getSignedUrl(ctx, baseUrl, fileToPath, commonDefines.c_oAscUrlTypes.Temporary, title);
}
function* convertByCmd(cmd, async, opt_fileTo, opt_taskExist, opt_priority, opt_expiration, opt_queue) {
function* convertByCmd(ctx, cmd, async, opt_fileTo, opt_taskExist, opt_priority, opt_expiration, opt_queue, opt_checkPassword) {
var docId = cmd.getDocId();
var startDate = null;
if (clientStatsD) {
startDate = new Date();
}
logger.debug('Start convert request docId = %s', docId);
ctx.logger.debug('Start convert request');
let bCreate = false;
if (!opt_taskExist) {
let task = new taskResult.TaskResultData();
task.tenant = ctx.tenant;
task.key = docId;
task.status = taskResult.FileStatus.WaitQueue;
task.statusInfo = constants.NO_ERROR;
let upsertRes = yield taskResult.upsert(task);
let upsertRes = yield taskResult.upsert(ctx, task);
//if CLIENT_FOUND_ROWS don't specify 1 row is inserted , 2 row is updated, and 0 row is set to its current values
//http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
bCreate = upsertRes.affectedRows == 1;
@ -125,10 +145,11 @@ function* convertByCmd(cmd, async, opt_fileTo, opt_taskExist, opt_priority, opt_
var selectRes;
var status;
if (!bCreate) {
selectRes = yield taskResult.select(docId);
status = yield* getConvertStatus(cmd, selectRes);
selectRes = yield taskResult.select(ctx, docId);
status = yield* getConvertStatus(ctx, cmd, selectRes, opt_checkPassword);
} else {
var queueData = new commonDefines.TaskQueueData();
queueData.setCtx(ctx);
queueData.setCmd(cmd);
if (opt_fileTo) {
queueData.setToFile(opt_fileTo);
@ -146,22 +167,22 @@ function* convertByCmd(cmd, async, opt_fileTo, opt_taskExist, opt_priority, opt_
break;
}
yield utils.sleep(CONVERT_ASYNC_DELAY);
selectRes = yield taskResult.select(docId);
status = yield* getConvertStatus(cmd, selectRes);
selectRes = yield taskResult.select(ctx, docId);
status = yield* getConvertStatus(ctx, cmd, selectRes, opt_checkPassword);
waitTime += CONVERT_ASYNC_DELAY;
if (waitTime > utils.CONVERTION_TIMEOUT) {
status.err = constants.CONVERT_TIMEOUT;
}
}
}
logger.debug('End convert request end %s url %s status %s docId = %s', status.end, status.url, status.err, docId);
ctx.logger.debug('End convert request end %s status %s', status.end, status.err);
if (clientStatsD) {
clientStatsD.timing('coauth.convertservice', new Date() - startDate);
}
return status;
}
function* convertFromChanges(docId, baseUrl, forceSave, externalChangeInfo, opt_userdata, opt_userConnectionId,
let convertFromChanges = co.wrap(function*(ctx, docId, baseUrl, forceSave, externalChangeInfo, opt_userdata, opt_userConnectionId,
opt_responseKey, opt_priority, opt_expiration, opt_queue, opt_redisKey) {
var cmd = new commonDefines.InputCommand();
cmd.setCommand('sfcm');
@ -185,50 +206,56 @@ function* convertFromChanges(docId, baseUrl, forceSave, externalChangeInfo, opt_
cmd.setRedisKey(opt_redisKey);
}
yield* canvasService.commandSfctByCmd(cmd, opt_priority, opt_expiration, opt_queue);
yield canvasService.commandSfctByCmd(ctx, cmd, opt_priority, opt_expiration, opt_queue);
var fileTo = constants.OUTPUT_NAME;
let outputExt = formatChecker.getStringFromFormat(cmd.getOutputFormat());
if (outputExt) {
fileTo += '.' + outputExt;
}
let status = yield* convertByCmd(cmd, true, fileTo, undefined, opt_priority, opt_expiration, opt_queue);
let status = yield* convertByCmd(ctx, cmd, true, fileTo, undefined, opt_priority, opt_expiration, opt_queue);
if (status.end) {
let fileToPath = yield* getConvertPath(docId, fileTo, cmd.getOutputFormat());
let fileToPath = yield* getConvertPath(ctx, docId, fileTo, cmd.getOutputFormat());
status.setExtName(path.extname(fileToPath));
status.setUrl(yield* getConvertUrl(baseUrl, fileToPath, cmd.getTitle()));
status.setUrl(yield* getConvertUrl(ctx, baseUrl, fileToPath, cmd.getTitle()));
}
return status;
}
});
function parseIntParam(val){
return (typeof val === 'string') ? parseInt(val) : val;
}
function convertRequest(req, res, isJson) {
return co(function* () {
var docId = 'convertRequest';
let ctx = new operationContext.Context();
try {
ctx.initFromRequest(req);
ctx.logger.info('convertRequest start');
let params;
let authRes = docsCoServer.getRequestParams(docId, req);
let authRes = yield docsCoServer.getRequestParams(ctx, req);
if(authRes.code === constants.NO_ERROR){
params = authRes.params;
} else {
ctx.logger.warn('convertRequest auth failed %j', authRes);
utils.fillResponse(req, res, new commonDefines.ConvertStatus(authRes.code), isJson);
return;
}
let outputtype = params.outputtype || '';
let docId = 'conv_' + params.key + '_' + outputtype;
ctx.setDocId(docId);
if (params.key && !constants.DOC_ID_REGEX.test(params.key)) {
logger.warn('convertRequest unexpected key = %s: docId = %s', params.key, docId);
ctx.logger.warn('convertRequest unexpected key = %s', params.key);
utils.fillResponse(req, res, new commonDefines.ConvertStatus(constants.CONVERT_PARAMS), isJson);
return;
}
if (params.filetype && !constants.EXTENTION_REGEX.test(params.filetype)) {
logger.warn('convertRequest unexpected filetype = %s: docId = %s', params.filetype, docId);
ctx.logger.warn('convertRequest unexpected filetype = %s', params.filetype);
utils.fillResponse(req, res, new commonDefines.ConvertStatus(constants.CONVERT_PARAMS), isJson);
return;
}
let outputtype = params.outputtype || '';
let outputFormat = formatChecker.getFormatFromString(outputtype);
if (constants.AVS_OFFICESTUDIO_FILE_UNKNOWN === outputFormat) {
logger.warn('convertRequest unexpected outputtype = %s: docId = %s', outputtype, docId);
ctx.logger.warn('convertRequest unexpected outputtype = %s', outputtype);
utils.fillResponse(req, res, new commonDefines.ConvertStatus(constants.CONVERT_PARAMS), isJson);
return;
}
@ -237,7 +264,6 @@ function convertRequest(req, res, isJson) {
cmd.setUrl(params.url);
cmd.setEmbeddedFonts(false);//params.embeddedfonts'];
cmd.setFormat(params.filetype);
docId = 'conv_' + params.key + '_' + outputtype;
cmd.setDocId(docId);
cmd.setOutputFormat(outputFormat);
@ -256,7 +282,7 @@ function convertRequest(req, res, isJson) {
}
if (params.password) {
if (params.password.length > constants.PASSWORD_MAX_LENGTH) {
logger.warn('convertRequest password too long actual = %s; max = %s;docId = %s', params.password.length, constants.PASSWORD_MAX_LENGTH, docId);
ctx.logger.warn('convertRequest password too long actual = %s; max = %s', params.password.length, constants.PASSWORD_MAX_LENGTH);
utils.fillResponse(req, res, new commonDefines.ConvertStatus(constants.CONVERT_PARAMS), isJson);
return;
}
@ -321,22 +347,24 @@ function convertRequest(req, res, isJson) {
if (constants.AVS_OFFICESTUDIO_FILE_UNKNOWN !== cmd.getOutputFormat()) {
let fileTo = constants.OUTPUT_NAME + '.' + outputExt;
var status = yield* convertByCmd(cmd, async, fileTo);
var status = yield* convertByCmd(ctx, cmd, async, fileTo, undefined, undefined, undefined, undefined, true);
if (status.end) {
let fileToPath = yield* getConvertPath(docId, fileTo, cmd.getOutputFormat());
let fileToPath = yield* getConvertPath(ctx, docId, fileTo, cmd.getOutputFormat());
status.setExtName(path.extname(fileToPath));
status.setUrl(yield* getConvertUrl(utils.getBaseUrlByRequest(req), fileToPath, cmd.getTitle()));
status.setUrl(yield* getConvertUrl(ctx, utils.getBaseUrlByRequest(req), fileToPath, cmd.getTitle()));
ctx.logger.debug('convertRequest: url = %s', status.url);
}
utils.fillResponse(req, res, status, isJson);
} else {
var addresses = utils.forwarded(req);
logger.warn('Error convert unknown outputtype: query = %j from = %s docId = %s', params, addresses, docId);
ctx.logger.warn('Error convert unknown outputtype: query = %j from = %s', params, addresses);
utils.fillResponse(req, res, new commonDefines.ConvertStatus(constants.UNKNOWN), isJson);
}
}
catch (e) {
logger.error('Error convert: docId = %s\r\n%s', docId, e.stack);
} catch (e) {
ctx.logger.error('convertRequest error: %s', e.stack);
utils.fillResponse(req, res, new commonDefines.ConvertStatus(constants.UNKNOWN), isJson);
} finally {
ctx.logger.info('convertRequest end');
}
});
}
@ -349,59 +377,65 @@ function convertRequestXml(req, res) {
function builderRequest(req, res) {
return co(function* () {
let docId = 'builderRequest';
let ctx = new operationContext.Context();
try {
ctx.initFromRequest(req);
ctx.logger.info('builderRequest start');
let authRes;
if (!utils.isEmptyObject(req.query)) {
//todo this is a stub for compatibility. remove in future version
authRes = docsCoServer.getRequestParams(docId, req, true);
authRes = yield docsCoServer.getRequestParams(ctx, req, true);
} else {
authRes = docsCoServer.getRequestParams(docId, req);
authRes = yield docsCoServer.getRequestParams(ctx, req);
}
let params = authRes.params;
let docId = params.key;
ctx.setDocId(docId);
let error = authRes.code;
let urls;
let end = false;
if (error === constants.NO_ERROR &&
(params.key || params.url || (req.body && Buffer.isBuffer(req.body) && req.body.length > 0))) {
docId = params.key;
let cmd = new commonDefines.InputCommand();
cmd.setCommand('builder');
cmd.setIsBuilder(true);
cmd.setWithAuthorization(true);
cmd.setDocId(docId);
if (!docId) {
let task = yield* taskResult.addRandomKeyTask(undefined, 'bld_', 8);
let task = yield* taskResult.addRandomKeyTask(ctx, undefined, 'bld_', 8);
docId = task.key;
cmd.setDocId(docId);
if (params.url) {
cmd.setUrl(params.url);
cmd.setFormat('docbuilder');
} else {
yield storageBase.putObject(docId + '/script.docbuilder', req.body, req.body.length);
yield storageBase.putObject(ctx, docId + '/script.docbuilder', req.body, req.body.length);
}
let queueData = new commonDefines.TaskQueueData();
queueData.setCtx(ctx);
queueData.setCmd(cmd);
yield* docsCoServer.addTask(queueData, constants.QUEUE_PRIORITY_LOW);
}
let async = (typeof params.async === 'string') ? 'true' === params.async : params.async;
let status = yield* convertByCmd(cmd, async, utils.getBaseUrlByRequest(req), undefined, true);
let status = yield* convertByCmd(ctx, cmd, async, utils.getBaseUrlByRequest(req), undefined, true);
end = status.end;
error = status.err;
if (end) {
urls = yield storageBase.getSignedUrls(utils.getBaseUrlByRequest(req), docId + '/output',
urls = yield storageBase.getSignedUrls(ctx, utils.getBaseUrlByRequest(req), docId + '/output',
commonDefines.c_oAscUrlTypes.Temporary);
}
} else if (error === constants.NO_ERROR) {
error = constants.UNKNOWN;
}
logger.debug('End builderRequest request: docId = %s urls = %j end = %s error = %s', docId, urls, end, error);
ctx.logger.debug('End builderRequest request: urls = %j end = %s error = %s', urls, end, error);
utils.fillResponseBuilder(res, docId, urls, end, error);
}
catch (e) {
logger.error('Error builderRequest: docId = %s\r\n%s', docId, e.stack);
ctx.logger.error('Error builderRequest: %s', e.stack);
utils.fillResponseBuilder(res, undefined, undefined, undefined, constants.UNKNOWN);
} finally {
ctx.logger.info('builderRequest end');
}
});
}

View File

@ -35,6 +35,7 @@ const config = require('config');
const ms = require('ms');
const utils = require('./../../Common/sources/utils');
const commonDefines = require('./../../Common/sources/commondefines');
const tenantManager = require('./../../Common/sources/tenantManager');
const cfgExpMonthUniqueUsers = ms(config.get('services.CoAuthoring.expire.monthUniqueUsers'));
@ -43,19 +44,25 @@ function EditorData() {
this.forceSaveTimer = {};
this.uniqueUser = {};
this.uniqueUsersOfMonth = {};
this.uniqueViewUser = {};
this.uniqueViewUsersOfMonth = {};
this.shutdown = {};
this.stat = [];
this.stat = {};
}
EditorData.prototype._getDocumentData = function(docId) {
let options = this.data[docId];
EditorData.prototype._getDocumentData = function(ctx, docId) {
let tenantData = this.data[ctx.tenant];
if (!tenantData) {
this.data[ctx.tenant] = tenantData = {};
}
let options = tenantData[docId];
if (!options) {
this.data[docId] = options = {};
tenantData[docId] = options = {};
}
return options;
};
EditorData.prototype._checkAndLock = function(name, docId, fencingToken, ttl) {
let data = this._getDocumentData(docId);
EditorData.prototype._checkAndLock = function(ctx, name, docId, fencingToken, ttl) {
let data = this._getDocumentData(ctx, docId);
const now = Date.now();
let res = true;
if (data[name] && now < data[name].expireAt && fencingToken !== data[name].fencingToken) {
@ -66,8 +73,8 @@ EditorData.prototype._checkAndLock = function(name, docId, fencingToken, ttl) {
}
return Promise.resolve(res);
};
EditorData.prototype._checkAndUnlock = function(name, docId, fencingToken) {
let data = this._getDocumentData(docId);
EditorData.prototype._checkAndUnlock = function(ctx, name, docId, fencingToken) {
let data = this._getDocumentData(ctx, docId);
const now = Date.now();
let res;
if (data[name] && now < data[name].expireAt) {
@ -84,100 +91,101 @@ EditorData.prototype._checkAndUnlock = function(name, docId, fencingToken) {
return Promise.resolve(res);
};
EditorData.prototype.addPresence = function(docId, userId, userInfo) {
EditorData.prototype.addPresence = function(ctx, docId, userId, userInfo) {
return Promise.resolve();
};
EditorData.prototype.removePresence = function(docId, userId) {
EditorData.prototype.removePresence = function(ctx, docId, userId) {
return Promise.resolve();
};
EditorData.prototype.getPresence = function(docId, connections) {
EditorData.prototype.getPresence = function(ctx, docId, connections) {
let hvals = [];
for (let i = 0; i < connections.length; ++i) {
if (connections[i].docId === docId) {
hvals.push(utils.getConnectionInfoStr(connections[i]));
let conn = connections[i];
if (conn.docId === docId && ctx.tenant === tenantManager.getTenantByConnection(ctx, conn)) {
hvals.push(utils.getConnectionInfoStr(conn));
}
}
return Promise.resolve(hvals);
};
EditorData.prototype.lockSave = function(docId, userId, ttl) {
return this._checkAndLock('lockSave', docId, userId, ttl);
EditorData.prototype.lockSave = function(ctx, docId, userId, ttl) {
return this._checkAndLock(ctx, 'lockSave', docId, userId, ttl);
};
EditorData.prototype.unlockSave = function(docId, userId) {
return this._checkAndUnlock('lockSave', docId, userId);
EditorData.prototype.unlockSave = function(ctx, docId, userId) {
return this._checkAndUnlock(ctx, 'lockSave', docId, userId);
};
EditorData.prototype.lockAuth = function(docId, userId, ttl) {
return this._checkAndLock('lockAuth', docId, userId, ttl);
EditorData.prototype.lockAuth = function(ctx, docId, userId, ttl) {
return this._checkAndLock(ctx, 'lockAuth', docId, userId, ttl);
};
EditorData.prototype.unlockAuth = function(docId, userId) {
return this._checkAndUnlock('lockAuth', docId, userId);
EditorData.prototype.unlockAuth = function(ctx, docId, userId) {
return this._checkAndUnlock(ctx, 'lockAuth', docId, userId);
};
EditorData.prototype.getDocumentPresenceExpired = function(now) {
return Promise.resolve([]);
};
EditorData.prototype.removePresenceDocument = function(docId) {
EditorData.prototype.removePresenceDocument = function(ctx, docId) {
return Promise.resolve();
};
EditorData.prototype.addLocks = function(docId, locks) {
let data = this._getDocumentData(docId);
EditorData.prototype.addLocks = function(ctx, docId, locks) {
let data = this._getDocumentData(ctx, docId);
if (!data.locks) {
data.locks = [];
}
data.locks = data.locks.concat(locks);
return Promise.resolve();
};
EditorData.prototype.removeLocks = function(docId) {
let data = this._getDocumentData(docId);
EditorData.prototype.removeLocks = function(ctx, docId) {
let data = this._getDocumentData(ctx, docId);
data.locks = undefined;
return Promise.resolve();
};
EditorData.prototype.getLocks = function(docId) {
let data = this._getDocumentData(docId);
EditorData.prototype.getLocks = function(ctx, docId) {
let data = this._getDocumentData(ctx, docId);
return Promise.resolve(data.locks || []);
};
EditorData.prototype.addMessage = function(docId, msg) {
let data = this._getDocumentData(docId);
EditorData.prototype.addMessage = function(ctx, docId, msg) {
let data = this._getDocumentData(ctx, docId);
if (!data.messages) {
data.messages = [];
}
data.messages.push(msg);
return Promise.resolve();
};
EditorData.prototype.removeMessages = function(docId) {
let data = this._getDocumentData(docId);
EditorData.prototype.removeMessages = function(ctx, docId) {
let data = this._getDocumentData(ctx, docId);
data.messages = undefined;
return Promise.resolve();
};
EditorData.prototype.getMessages = function(docId) {
let data = this._getDocumentData(docId);
EditorData.prototype.getMessages = function(ctx, docId) {
let data = this._getDocumentData(ctx, docId);
return Promise.resolve(data.messages || []);
};
EditorData.prototype.setSaved = function(docId, status) {
let data = this._getDocumentData(docId);
EditorData.prototype.setSaved = function(ctx, docId, status) {
let data = this._getDocumentData(ctx, docId);
data.saved = status;
return Promise.resolve();
};
EditorData.prototype.getdelSaved = function(docId) {
let data = this._getDocumentData(docId);
EditorData.prototype.getdelSaved = function(ctx, docId) {
let data = this._getDocumentData(ctx, docId);
let res = data.saved;
data.saved = undefined;
return Promise.resolve(res);
};
EditorData.prototype.setForceSave = function(docId, time, index, baseUrl, changeInfo) {
let data = this._getDocumentData(docId);
EditorData.prototype.setForceSave = function(ctx, docId, time, index, baseUrl, changeInfo) {
let data = this._getDocumentData(ctx, docId);
data.forceSave = {time: time, index: index, baseUrl: baseUrl, changeInfo: changeInfo, started: false, ended: false};
return Promise.resolve();
};
EditorData.prototype.getForceSave = function(docId) {
let data = this._getDocumentData(docId);
EditorData.prototype.getForceSave = function(ctx, docId) {
let data = this._getDocumentData(ctx, docId);
return Promise.resolve(data.forceSave || null);
};
EditorData.prototype.checkAndStartForceSave = function(docId) {
let data = this._getDocumentData(docId);
EditorData.prototype.checkAndStartForceSave = function(ctx, docId) {
let data = this._getDocumentData(ctx, docId);
let res;
if (data.forceSave && !data.forceSave.started) {
data.forceSave.started = true;
@ -186,8 +194,8 @@ EditorData.prototype.checkAndStartForceSave = function(docId) {
}
return Promise.resolve(res);
};
EditorData.prototype.checkAndSetForceSave = function(docId, time, index, started, ended) {
let data = this._getDocumentData(docId);
EditorData.prototype.checkAndSetForceSave = function(ctx, docId, time, index, started, ended) {
let data = this._getDocumentData(ctx, docId);
let res;
if (data.forceSave && time === data.forceSave.time && index === data.forceSave.index) {
data.forceSave.started = started;
@ -196,120 +204,235 @@ EditorData.prototype.checkAndSetForceSave = function(docId, time, index, started
}
return Promise.resolve(res);
};
EditorData.prototype.removeForceSave = function(docId) {
let data = this._getDocumentData(docId);
EditorData.prototype.removeForceSave = function(ctx, docId) {
let data = this._getDocumentData(ctx, docId);
data.forceSave = undefined;
return Promise.resolve();
};
EditorData.prototype.cleanDocumentOnExit = function(docId) {
delete this.data[docId];
delete this.forceSaveTimer[docId];
EditorData.prototype.cleanDocumentOnExit = function(ctx, docId) {
let tenantData = this.data[ctx.tenant];
if (tenantData) {
delete tenantData[docId];
}
let tenantTimer = this.forceSaveTimer[ctx.tenant];
if (tenantTimer) {
delete tenantTimer[docId];
}
return Promise.resolve();
};
EditorData.prototype.addForceSaveTimerNX = function(docId, expireAt) {
if (!this.forceSaveTimer[docId]) {
this.forceSaveTimer[docId] = expireAt;
EditorData.prototype.addForceSaveTimerNX = function(ctx, docId, expireAt) {
let tenantTimer = this.forceSaveTimer[ctx.tenant];
if (!tenantTimer) {
this.forceSaveTimer[ctx.tenant] = tenantTimer = {};
}
if (!tenantTimer[docId]) {
tenantTimer[docId] = expireAt;
}
return Promise.resolve();
};
EditorData.prototype.getForceSaveTimer = function(now) {
let res = [];
for (let docId in this.forceSaveTimer) {
if (this.forceSaveTimer.hasOwnProperty(docId)) {
if (this.forceSaveTimer[docId] < now) {
res.push(docId);
delete this.forceSaveTimer[docId];
for (let tenant in this.forceSaveTimer) {
if (this.forceSaveTimer.hasOwnProperty(tenant)) {
let tenantTimer = this.forceSaveTimer[tenant];
for (let docId in tenantTimer) {
if (tenantTimer.hasOwnProperty(docId)) {
if (tenantTimer[docId] < now) {
res.push([tenant, docId]);
delete tenantTimer[docId];
}
}
}
}
}
return Promise.resolve(res);
};
EditorData.prototype.addPresenceUniqueUser = function(userId, expireAt, userInfo) {
this.uniqueUser[userId] = {expireAt: expireAt, userInfo: userInfo};
EditorData.prototype.addPresenceUniqueUser = function(ctx, userId, expireAt, userInfo) {
let tenantUser = this.uniqueUser[ctx.tenant];
if (!tenantUser) {
this.uniqueUser[ctx.tenant] = tenantUser = {};
}
tenantUser[userId] = {expireAt: expireAt, userInfo: userInfo};
return Promise.resolve();
};
EditorData.prototype.getPresenceUniqueUser = function(nowUTC) {
EditorData.prototype.getPresenceUniqueUser = function(ctx, nowUTC) {
let res = [];
for (let userId in this.uniqueUser) {
if (this.uniqueUser.hasOwnProperty(userId)) {
if (this.uniqueUser[userId].expireAt > nowUTC) {
let elem = this.uniqueUser[userId];
let tenantUser = this.uniqueUser[ctx.tenant];
if (!tenantUser) {
this.uniqueUser[ctx.tenant] = tenantUser = {};
}
for (let userId in tenantUser) {
if (tenantUser.hasOwnProperty(userId)) {
if (tenantUser[userId].expireAt > nowUTC) {
let elem = tenantUser[userId];
let newElem = {userid: userId, expire: new Date(elem.expireAt * 1000)};
Object.assign(newElem, elem.userInfo);
res.push(newElem);
} else {
delete this.uniqueUser[userId];
delete tenantUser[userId];
}
}
}
return Promise.resolve(res);
};
EditorData.prototype.addPresenceUniqueUsersOfMonth = function(userId, period, userInfo) {
if(!this.uniqueUsersOfMonth[period]) {
let expireAt = Date.now() + cfgExpMonthUniqueUsers;
this.uniqueUsersOfMonth[period] = {expireAt: expireAt, data: {}};
EditorData.prototype.addPresenceUniqueUsersOfMonth = function(ctx, userId, period, userInfo) {
let tenantUser = this.uniqueUsersOfMonth[ctx.tenant];
if (!tenantUser) {
this.uniqueUsersOfMonth[ctx.tenant] = tenantUser = {};
}
this.uniqueUsersOfMonth[period].data[userId] = userInfo;
if(!tenantUser[period]) {
let expireAt = Date.now() + cfgExpMonthUniqueUsers;
tenantUser[period] = {expireAt: expireAt, data: {}};
}
tenantUser[period].data[userId] = userInfo;
return Promise.resolve();
};
EditorData.prototype.getPresenceUniqueUsersOfMonth = function() {
let res = [];
EditorData.prototype.getPresenceUniqueUsersOfMonth = function(ctx) {
let res = {};
let nowUTC = Date.now();
for (let periodId in this.uniqueUsersOfMonth) {
if (this.uniqueUsersOfMonth.hasOwnProperty(periodId)) {
if (this.uniqueUsersOfMonth[periodId].expireAt <= nowUTC) {
delete this.uniqueUsersOfMonth[periodId];
let tenantUser = this.uniqueUsersOfMonth[ctx.tenant];
if (!tenantUser) {
this.uniqueUsersOfMonth[ctx.tenant] = tenantUser = {};
}
for (let periodId in tenantUser) {
if (tenantUser.hasOwnProperty(periodId)) {
if (tenantUser[periodId].expireAt <= nowUTC) {
delete tenantUser[periodId];
} else {
let date = new Date(parseInt(periodId)).toISOString();
res.push({date: date, users: this.uniqueUsersOfMonth[periodId].data});
res[date] = tenantUser[periodId].data;
}
}
}
return Promise.resolve(res);
};
EditorData.prototype.setEditorConnections = function(countEdit, countView, now, precision) {
this.stat.push({time: now, edit: countEdit, view: countView});
EditorData.prototype.addPresenceUniqueViewUser = function(ctx, userId, expireAt, userInfo) {
let tenantUser = this.uniqueViewUser[ctx.tenant];
if (!tenantUser) {
this.uniqueViewUser[ctx.tenant] = tenantUser = {};
}
tenantUser[userId] = {expireAt: expireAt, userInfo: userInfo};
return Promise.resolve();
};
EditorData.prototype.getPresenceUniqueViewUser = function(ctx, nowUTC) {
let res = [];
let tenantUser = this.uniqueViewUser[ctx.tenant];
if (!tenantUser) {
this.uniqueViewUser[ctx.tenant] = tenantUser = {};
}
for (let userId in tenantUser) {
if (tenantUser.hasOwnProperty(userId)) {
if (tenantUser[userId].expireAt > nowUTC) {
let elem = tenantUser[userId];
let newElem = {userid: userId, expire: new Date(elem.expireAt * 1000)};
Object.assign(newElem, elem.userInfo);
res.push(newElem);
} else {
delete tenantUser[userId];
}
}
}
return Promise.resolve(res);
};
EditorData.prototype.addPresenceUniqueViewUsersOfMonth = function(ctx, userId, period, userInfo) {
let tenantUser = this.uniqueViewUsersOfMonth[ctx.tenant];
if (!tenantUser) {
this.uniqueViewUsersOfMonth[ctx.tenant] = tenantUser = {};
}
if(!tenantUser[period]) {
let expireAt = Date.now() + cfgExpMonthUniqueUsers;
tenantUser[period] = {expireAt: expireAt, data: {}};
}
tenantUser[period].data[userId] = userInfo;
return Promise.resolve();
};
EditorData.prototype.getPresenceUniqueViewUsersOfMonth = function(ctx) {
let res = {};
let nowUTC = Date.now();
let tenantUser = this.uniqueViewUsersOfMonth[ctx.tenant];
if (!tenantUser) {
this.uniqueViewUsersOfMonth[ctx.tenant] = tenantUser = {};
}
for (let periodId in tenantUser) {
if (tenantUser.hasOwnProperty(periodId)) {
if (tenantUser[periodId].expireAt <= nowUTC) {
delete tenantUser[periodId];
} else {
let date = new Date(parseInt(periodId)).toISOString();
res[date] = tenantUser[periodId].data;
}
}
}
return Promise.resolve(res);
};
EditorData.prototype.setEditorConnections = function(ctx, countEdit, countLiveView, countView, now, precision) {
let tenantStat = this.stat[ctx.tenant];
if (!tenantStat) {
this.stat[ctx.tenant] = tenantStat = [];
}
tenantStat.push({time: now, edit: countEdit, liveview: countLiveView, view: countView});
let i = 0;
while (i < this.stat.length && this.stat[i] < now - precision[precision.length - 1].val) {
while (i < tenantStat.length && tenantStat[i] < now - precision[precision.length - 1].val) {
i++;
}
this.stat.splice(0, i);
tenantStat.splice(0, i);
return Promise.resolve();
};
EditorData.prototype.getEditorConnections = function() {
return Promise.resolve(this.stat);
EditorData.prototype.getEditorConnections = function(ctx) {
let tenantStat = this.stat[ctx.tenant];
if (!tenantStat) {
this.stat[ctx.tenant] = tenantStat = [];
}
return Promise.resolve(tenantStat);
};
EditorData.prototype.setEditorConnectionsCountByShard = function(shardId, count) {
EditorData.prototype.setEditorConnectionsCountByShard = function(ctx, shardId, count) {
return Promise.resolve();
};
EditorData.prototype.incrEditorConnectionsCountByShard = function(shardId, count) {
EditorData.prototype.incrEditorConnectionsCountByShard = function(ctx, shardId, count) {
return Promise.resolve();
};
EditorData.prototype.getEditorConnectionsCount = function(connections) {
EditorData.prototype.getEditorConnectionsCount = function(ctx, connections) {
let count = 0;
for (let i = 0; i < connections.length; ++i) {
let conn = connections[i];
if (!(conn.isCloseCoAuthoring || (conn.user && conn.user.view))) {
if (!(conn.isCloseCoAuthoring || (conn.user && conn.user.view)) && ctx.tenant === tenantManager.getTenantByConnection(ctx, conn)) {
count++;
}
}
return Promise.resolve(count);
};
EditorData.prototype.setViewerConnectionsCountByShard = function(shardId, count) {
EditorData.prototype.setViewerConnectionsCountByShard = function(ctx, shardId, count) {
return Promise.resolve();
};
EditorData.prototype.incrViewerConnectionsCountByShard = function(shardId, count) {
EditorData.prototype.incrViewerConnectionsCountByShard = function(ctx, shardId, count) {
return Promise.resolve();
};
EditorData.prototype.getViewerConnectionsCount = function(connections) {
EditorData.prototype.getViewerConnectionsCount = function(ctx, connections) {
let count = 0;
for (let i = 0; i < connections.length; ++i) {
let conn = connections[i];
if (conn.isCloseCoAuthoring || (conn.user && conn.user.view)) {
if (conn.isCloseCoAuthoring || (conn.user && conn.user.view) && ctx.tenant === tenantManager.getTenantByConnection(ctx, conn)) {
count++;
}
}
return Promise.resolve(count);
};
EditorData.prototype.setLiveViewerConnectionsCountByShard = function(ctx, shardId, count) {
return Promise.resolve();
};
EditorData.prototype.incrLiveViewerConnectionsCountByShard = function(ctx, shardId, count) {
return Promise.resolve();
};
EditorData.prototype.getLiveViewerConnectionsCount = function(ctx, connections) {
let count = 0;
for (let i = 0; i < connections.length; ++i) {
let conn = connections[i];
if (utils.isLiveViewer(conn) && ctx.tenant === tenantManager.getTenantByConnection(ctx, conn)) {
count++;
}
}

View File

@ -41,8 +41,8 @@ var utils = require('./../../Common/sources/utils');
var constants = require('./../../Common/sources/constants');
var storageBase = require('./../../Common/sources/storage-base');
var formatChecker = require('./../../Common/sources/formatchecker');
var logger = require('./../../Common/sources/logger');
const commonDefines = require('./../../Common/sources/commondefines');
const operationContext = require('./../../Common/sources/operationContext');
var config = require('config');
var configServer = config.get('services.CoAuthoring.server');
@ -57,9 +57,12 @@ const PATTERN_ENCRYPTED = 'ENCRYPTED;';
exports.uploadTempFile = function(req, res) {
return co(function* () {
var docId = 'uploadTempFile';
let ctx = new operationContext.Context();
try {
ctx.initFromRequest(req);
ctx.logger.info('uploadTempFile start');
let params;
let authRes = docsCoServer.getRequestParams(docId, req, true);
let authRes = yield docsCoServer.getRequestParams(ctx, req, true);
if(authRes.code === constants.NO_ERROR){
params = authRes.params;
} else {
@ -67,33 +70,34 @@ exports.uploadTempFile = function(req, res) {
return;
}
docId = params.key;
logger.debug('Start uploadTempFile: docId = %s', docId);
ctx.setDocId(docId);
ctx.logger.debug('Start uploadTempFile');
if (docId && constants.DOC_ID_REGEX.test(docId) && req.body && Buffer.isBuffer(req.body)) {
var task = yield* taskResult.addRandomKeyTask(docId);
var task = yield* taskResult.addRandomKeyTask(ctx, docId);
var strPath = task.key + '/' + docId + '.tmp';
yield storageBase.putObject(strPath, req.body, req.body.length);
var url = yield storageBase.getSignedUrl(utils.getBaseUrlByRequest(req), strPath,
yield storageBase.putObject(ctx, strPath, req.body, req.body.length);
var url = yield storageBase.getSignedUrl(ctx, utils.getBaseUrlByRequest(req), strPath,
commonDefines.c_oAscUrlTypes.Temporary);
utils.fillResponse(req, res, new commonDefines.ConvertStatus(constants.NO_ERROR, url), false);
} else {
if (!constants.DOC_ID_REGEX.test(docId)) {
logger.warn('Error uploadTempFile unexpected key: docId = %s', docId);
ctx.logger.warn('Error uploadTempFile unexpected key');
}
utils.fillResponse(req, res, new commonDefines.ConvertStatus(constants.UNKNOWN), false);
}
logger.debug('End uploadTempFile: docId = %s', docId);
}
catch (e) {
logger.error('Error uploadTempFile: docId = %s\r\n%s', docId, e.stack);
} catch (e) {
ctx.logger.error('Error uploadTempFile: %s', e.stack);
utils.fillResponse(req, res, new commonDefines.ConvertStatus(constants.UNKNOWN), false);
} finally {
ctx.logger.info('uploadTempFile end');
}
});
};
function checkJwtUpload(docId, errorName, token){
let checkJwtRes = docsCoServer.checkJwt(docId, token, commonDefines.c_oAscSecretType.Session);
return checkJwtUploadTransformRes(docId, errorName, checkJwtRes);
function* checkJwtUpload(ctx, errorName, token){
let checkJwtRes = yield docsCoServer.checkJwt(ctx, token, commonDefines.c_oAscSecretType.Session);
return checkJwtUploadTransformRes(ctx, errorName, checkJwtRes);
}
function checkJwtUploadTransformRes(docId, errorName, checkJwtRes){
function checkJwtUploadTransformRes(ctx, errorName, checkJwtRes){
var res = {err: true, docId: null, userid: null, encrypted: null};
if (checkJwtRes.decoded) {
var doc = checkJwtRes.decoded.document;
@ -106,94 +110,98 @@ function checkJwtUploadTransformRes(docId, errorName, checkJwtRes){
res.userid = edit.user.id;
}
} else {
logger.warn('Error %s jwt: docId = %s\r\n%s', errorName, docId, 'access deny');
ctx.logger.warn('Error %s jwt: %s', errorName, 'access deny');
}
} else {
logger.warn('Error %s jwt: docId = %s\r\n%s', errorName, docId, checkJwtRes.description);
ctx.logger.warn('Error %s jwt: %s', errorName, checkJwtRes.description);
}
return res;
}
exports.uploadImageFileOld = function(req, res) {
var docId = req.params.docid;
logger.debug('Start uploadImageFileOld: docId = %s', docId);
var userid = req.params.userid;
if (cfgTokenEnableBrowser) {
var checkJwtRes = checkJwtUpload(docId, 'uploadImageFileOld', req.query['token']);
if(!checkJwtRes.err){
docId = checkJwtRes.docId || docId;
userid = checkJwtRes.userid || userid;
} else {
res.sendStatus(403);
return;
}
}
var listImages = [];
//todo userid
if (docId) {
var isError = false;
var form = new multiparty.Form();
form.on('error', function(err) {
logger.error('Error parsing form: docId = %s\r\n%s', docId, err.toString());
res.sendStatus(400);
});
form.on('part', function(part) {
if (!part.filename) {
// ignore field's content
part.resume();
}
if (part.filename) {
if (part.byteCount > cfgImageSize) {
isError = true;
}
if (isError) {
part.resume();
} else {
//в начале пишется хеш, чтобы избежать ошибок при параллельном upload в совместном редактировании
var strImageName = crypto.randomBytes(16).toString("hex");
var strPath = docId + '/media/' + strImageName + '.jpg';
listImages.push(strPath);
utils.stream2Buffer(part).then(function(buffer) {
return storageBase.putObject(strPath, buffer, buffer.length);
}).then(function() {
part.resume();
}).catch(function(err) {
logger.error('Upload putObject: docId = %s\r\n%s', docId, err.stack);
isError = true;
part.resume();
});
}
}
part.on('error', function(err) {
logger.error('Error parsing form part: docId = %s\r\n%s', docId, err.toString());
});
});
form.on('close', function() {
if (isError) {
res.sendStatus(400);
return co(function* () {
let ctx = new operationContext.Context();
ctx.initFromRequest(req);
var docId = req.params.docid;
ctx.setDocId(docId);
ctx.logger.debug('Start uploadImageFileOld');
if (cfgTokenEnableBrowser) {
var checkJwtRes = yield* checkJwtUpload(ctx, 'uploadImageFileOld', req.query['token']);
if(!checkJwtRes.err){
docId = checkJwtRes.docId || docId;
ctx.setDocId(docId);
ctx.setUserId(checkJwtRes.userid);
} else {
storageBase.getSignedUrlsByArray(utils.getBaseUrlByRequest(req), listImages, docId,
commonDefines.c_oAscUrlTypes.Session).then(function(urls) {
var outputData = {'type': 0, 'error': constants.NO_ERROR, 'urls': urls, 'input': req.query};
var output = '<html><head><script type="text/javascript">function load(){ parent.postMessage("';
output += JSON.stringify(outputData).replace(/"/g, '\\"');
output += '", "*"); }</script></head><body onload="load()"></body></html>';
//res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'text/html');
res.send(output);
logger.debug('End uploadImageFileOld: docId = %s %s', docId, output);
}
).catch(function(err) {
res.sendStatus(400);
logger.error('upload getSignedUrlsByArray: docId = %s\r\n%s', docId, err.stack);
});
res.sendStatus(403);
return;
}
});
form.parse(req);
} else {
logger.debug('Error params uploadImageFileOld: docId = %s', docId);
res.sendStatus(400);
}
}
var listImages = [];
if (docId) {
var isError = false;
var form = new multiparty.Form();
form.on('error', function(err) {
ctx.logger.error('Error parsing form:%s', err.toString());
res.sendStatus(400);
});
form.on('part', function(part) {
if (!part.filename) {
// ignore field's content
part.resume();
}
if (part.filename) {
if (part.byteCount > cfgImageSize) {
isError = true;
}
if (isError) {
part.resume();
} else {
//в начале пишется хеш, чтобы избежать ошибок при параллельном upload в совместном редактировании
var strImageName = crypto.randomBytes(16).toString("hex");
var strPath = docId + '/media/' + strImageName + '.jpg';
listImages.push(strPath);
utils.stream2Buffer(part).then(function(buffer) {
return storageBase.putObject(ctx, strPath, buffer, buffer.length);
}).then(function() {
part.resume();
}).catch(function(err) {
ctx.logger.error('Upload putObject:%s', err.stack);
isError = true;
part.resume();
});
}
}
part.on('error', function(err) {
ctx.logger.error('Error parsing form part:%s', err.toString());
});
});
form.once('close', function() {
if (isError) {
res.sendStatus(400);
} else {
storageBase.getSignedUrlsByArray(ctx, utils.getBaseUrlByRequest(req), listImages, docId,
commonDefines.c_oAscUrlTypes.Session).then(function(urls) {
var outputData = {'type': 0, 'error': constants.NO_ERROR, 'urls': urls, 'input': req.query};
var output = '<html><head><script type="text/javascript">function load(){ parent.postMessage("';
output += JSON.stringify(outputData).replace(/"/g, '\\"');
output += '", "*"); }</script></head><body onload="load()"></body></html>';
//res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'text/html');
res.send(output);
ctx.logger.debug('End uploadImageFileOld:%s', output);
}
).catch(function(err) {
ctx.logger.error('error getSignedUrlsByArray:%s', err.stack);
res.sendStatus(400);
});
}
});
form.parse(req);
} else {
ctx.logger.debug('Error params uploadImageFileOld');
res.sendStatus(400);
}
});
};
exports.uploadImageFile = function(req, res) {
return co(function* () {
@ -201,21 +209,26 @@ exports.uploadImageFile = function(req, res) {
var docId = 'null';
let output = {};
let isValidJwt = true;
let ctx = new operationContext.Context();
try {
ctx.initFromRequest(req);
docId = req.params.docid;
ctx.setDocId(docId);
let encrypted = false;
logger.debug('Start uploadImageFile: docId = %s', docId);
ctx.logger.debug('Start uploadImageFile');
if (cfgTokenEnableBrowser) {
let checkJwtRes = docsCoServer.checkJwtHeader(docId, req, 'Authorization', 'Bearer ', commonDefines.c_oAscSecretType.Session);
let checkJwtRes = yield docsCoServer.checkJwtHeader(ctx, req, 'Authorization', 'Bearer ', commonDefines.c_oAscSecretType.Session);
if (!checkJwtRes) {
//todo remove compatibility with previous versions
checkJwtRes = docsCoServer.checkJwt(docId, req.query['token'], commonDefines.c_oAscSecretType.Session);
checkJwtRes = yield docsCoServer.checkJwt(ctx, req.query['token'], commonDefines.c_oAscSecretType.Session);
}
let transformedRes = checkJwtUploadTransformRes(docId, 'uploadImageFile', checkJwtRes);
let transformedRes = checkJwtUploadTransformRes(ctx, 'uploadImageFile', checkJwtRes);
if (!transformedRes.err) {
docId = transformedRes.docId || docId;
encrypted = transformedRes.encrypted;
ctx.setDocId(docId);
ctx.setUserId(transformedRes.userid);
} else {
isValidJwt = false;
}
@ -224,7 +237,7 @@ exports.uploadImageFile = function(req, res) {
if (isValidJwt && docId && req.body && Buffer.isBuffer(req.body)) {
let buffer = req.body;
if (buffer.length <= cfgImageSize) {
var format = formatChecker.getImageFormat(buffer, undefined);
var format = formatChecker.getImageFormat(ctx, buffer);
var formatStr = formatChecker.getStringFromFormat(format);
if (encrypted && PATTERN_ENCRYPTED === buffer.toString('utf8', 0, PATTERN_ENCRYPTED.length)) {
formatStr = buffer.toString('utf8', PATTERN_ENCRYPTED.length, buffer.indexOf(';', PATTERN_ENCRYPTED.length));
@ -236,20 +249,20 @@ exports.uploadImageFile = function(req, res) {
var strImageName = crypto.randomBytes(16).toString("hex");
var strPathRel = 'media/' + strImageName + '.' + formatStr;
var strPath = docId + '/' + strPathRel;
yield storageBase.putObject(strPath, buffer, buffer.length);
output[strPathRel] = yield storageBase.getSignedUrl(utils.getBaseUrlByRequest(req), strPath,
yield storageBase.putObject(ctx, strPath, buffer, buffer.length);
output[strPathRel] = yield storageBase.getSignedUrl(ctx, utils.getBaseUrlByRequest(req), strPath,
commonDefines.c_oAscUrlTypes.Session);
isError = false;
} else {
logger.debug('uploadImageFile format is not supported: docId = %s', docId);
ctx.logger.debug('uploadImageFile format is not supported');
}
} else {
logger.debug('uploadImageFile size limit exceeded: buffer.length = %d docId = %s', buffer.length, docId);
ctx.logger.debug('uploadImageFile size limit exceeded: buffer.length = %d', buffer.length);
}
}
} catch (e) {
isError = true;
logger.error('Error uploadImageFile: docId = %s\r\n%s', docId, e.stack);
ctx.logger.error('Error uploadImageFile:%s', e.stack);
} finally {
try {
if (!isError) {
@ -258,9 +271,9 @@ exports.uploadImageFile = function(req, res) {
} else {
res.sendStatus(isValidJwt ? 400 : 403);
}
logger.debug('End uploadImageFile: isError = %s docId = %s', isError, docId);
ctx.logger.debug('End uploadImageFile: isError = %s', isError);
} catch (e) {
logger.error('Error uploadImageFile: docId = %s\r\n%s', docId, e.stack);
ctx.logger.error('Error uploadImageFile:%s', e.stack);
}
}
});

View File

@ -46,6 +46,7 @@ var logger = require('./../../Common/sources/logger');
var constants = require('./../../Common/sources/constants');
var commondefines = require('./../../Common/sources/commondefines');
var queueService = require('./../../Common/sources/taskqueueRabbitMQ');
var operationContext = require('./../../Common/sources/operationContext');
var pubsubService = require('./pubsubRabbitMQ');
var cfgExpFilesCron = config.get('expire.filesCron');
@ -65,31 +66,36 @@ let expDocumentsStep = getCronStep(cfgExpDocumentsCron);
var checkFileExpire = function() {
return co(function* () {
let ctx = new operationContext.Context();
try {
logger.debug('checkFileExpire start');
ctx.logger.info('checkFileExpire start');
let removedCount = 0;
var expired;
var removedCount = 0;
var currentRemovedCount;
do {
currentRemovedCount = 0;
expired = yield taskResult.getExpired(cfgExpFilesRemovedAtOnce, cfgExpFiles);
expired = yield taskResult.getExpired(ctx, cfgExpFilesRemovedAtOnce, cfgExpFiles);
for (var i = 0; i < expired.length; ++i) {
var docId = expired[i].id;
let tenant = expired[i].tenant;
let docId = expired[i].id;
ctx.init(tenant, docId, ctx.userId);
//todo tenant
//проверяем что никто не сидит в документе
let editorsCount = yield docsCoServer.getEditorsCountPromise(docId);
let editorsCount = yield docsCoServer.getEditorsCountPromise(ctx, docId);
if(0 === editorsCount){
if (yield canvasService.cleanupCache(docId)) {
if (yield canvasService.cleanupCache(ctx)) {
currentRemovedCount++;
}
} else {
logger.debug('checkFileExpire expire but presence: editorsCount = %d; docId = %s', editorsCount, docId);
ctx.logger.debug('checkFileExpire expire but presence: editorsCount = %d', editorsCount);
}
}
removedCount += currentRemovedCount;
} while (currentRemovedCount > 0);
logger.debug('checkFileExpire end: removedCount = %d', removedCount);
ctx.initDefault();
ctx.logger.info('checkFileExpire end: removedCount = %d', removedCount);
} catch (e) {
logger.error('checkFileExpire error:\r\n%s', e.stack);
ctx.logger.error('checkFileExpire error: %s', e.stack);
} finally {
setTimeout(checkFileExpire, expFilesStep);
}
@ -100,8 +106,9 @@ var checkDocumentExpire = function() {
var queue = null;
var removedCount = 0;
var startSaveCount = 0;
let ctx = new operationContext.Context();
try {
logger.debug('checkDocumentExpire start');
ctx.logger.info('checkDocumentExpire start');
var now = (new Date()).getTime();
let expiredKeys = yield docsCoServer.editorData.getDocumentPresenceExpired(now);
if (expiredKeys.length > 0) {
@ -109,30 +116,33 @@ var checkDocumentExpire = function() {
yield queue.initPromise(true, false, false, false, false, false);
for (var i = 0; i < expiredKeys.length; ++i) {
var docId = expiredKeys[i];
let tenant = expiredKeys[i][0];
let docId = expiredKeys[i][1];
if (docId) {
var hasChanges = yield docsCoServer.hasChanges(docId);
ctx.init(tenant, docId, ctx.userId);
var hasChanges = yield docsCoServer.hasChanges(ctx, docId);
if (hasChanges) {
yield docsCoServer.createSaveTimerPromise(docId, null, null, queue, true);
yield docsCoServer.createSaveTimer(ctx, docId, null, null, queue, true);
startSaveCount++;
} else {
yield docsCoServer.cleanDocumentOnExitNoChangesPromise(docId);
yield docsCoServer.cleanDocumentOnExitNoChangesPromise(ctx, docId);
removedCount++;
}
}
}
}
ctx.initDefault();
ctx.logger.info('checkDocumentExpire end: startSaveCount = %d, removedCount = %d', startSaveCount, removedCount);
} catch (e) {
logger.error('checkDocumentExpire error:\r\n%s', e.stack);
ctx.logger.error('checkDocumentExpire error: %s', e.stack);
} finally {
try {
if (queue) {
yield queue.close();
}
} catch (e) {
logger.error('checkDocumentExpire error:\r\n%s', e.stack);
ctx.logger.error('checkDocumentExpire error: %s', e.stack);
}
logger.debug('checkDocumentExpire end: startSaveCount = %d, removedCount = %d', startSaveCount, removedCount);
setTimeout(checkDocumentExpire, expDocumentsStep);
}
});
@ -141,8 +151,9 @@ let forceSaveTimeout = function() {
return co(function* () {
let queue = null;
let pubsub = null;
let ctx = new operationContext.Context();
try {
logger.debug('forceSaveTimeout start');
ctx.logger.info('forceSaveTimeout start');
let now = (new Date()).getTime();
let expiredKeys = yield docsCoServer.editorData.getForceSaveTimer(now);
if (expiredKeys.length > 0) {
@ -154,18 +165,21 @@ let forceSaveTimeout = function() {
let actions = [];
for (let i = 0; i < expiredKeys.length; ++i) {
let docId = expiredKeys[i];
let tenant = expiredKeys[i][0];
let docId = expiredKeys[i][1];
if (docId) {
actions.push(docsCoServer.startForceSave(docId, commondefines.c_oAscForceSaveTypes.Timeout,
ctx.init(tenant, docId, ctx.userId);
actions.push(docsCoServer.startForceSave(ctx, docId, commondefines.c_oAscForceSaveTypes.Timeout,
undefined, undefined, undefined, undefined, undefined, undefined, queue, pubsub));
}
}
yield Promise.all(actions);
logger.debug('forceSaveTimeout actions.length %d', actions.length);
ctx.logger.debug('forceSaveTimeout actions.length %d', actions.length);
}
logger.debug('forceSaveTimeout end');
ctx.initDefault();
ctx.logger.info('forceSaveTimeout end');
} catch (e) {
logger.error('forceSaveTimeout error:\r\n%s', e.stack);
ctx.logger.error('forceSaveTimeout error: %s', e.stack);
} finally {
try {
if (queue) {
@ -175,7 +189,7 @@ let forceSaveTimeout = function() {
yield pubsub.close();
}
} catch (e) {
logger.error('checkDocumentExpire error:\r\n%s', e.stack);
ctx.logger.error('checkDocumentExpire error: %s', e.stack);
}
setTimeout(forceSaveTimeout, cfgForceSaveStep);
}

View File

@ -32,7 +32,7 @@
'use strict';
var mysql = require('mysql');
var mysql = require('mysql2');
var sqlBase = require('./baseConnector');
var configSql = require('config').get('services.CoAuthoring.sql');
var pool = mysql.createPool({
@ -43,25 +43,24 @@ var pool = mysql.createPool({
database : configSql.get('dbName'),
charset : configSql.get('charset'),
connectionLimit : configSql.get('connectionlimit'),
timezone : '+0000',
timezone : 'Z',
flags : '-FOUND_ROWS'
});
var logger = require('./../../Common/sources/logger');
exports.sqlQuery = function (sqlCommand, callbackFunction, opt_noModifyRes, opt_noLog, opt_values) {
exports.sqlQuery = function (ctx, sqlCommand, callbackFunction, opt_noModifyRes, opt_noLog, opt_values) {
pool.getConnection(function(err, connection) {
if (err) {
logger.error('pool.getConnection error: %s', err);
ctx.logger.error('pool.getConnection error: %s', err);
if (callbackFunction) callbackFunction(err, null);
return;
}
let queryCallback = function (error, result) {
connection.release();
if (error) {
logger.error('________________________error_____________________');
logger.error('sqlQuery: %s sqlCommand: %s', error.code, sqlCommand);
logger.error(error);
logger.error('_____________________end_error_____________________');
ctx.logger.error('________________________error_____________________');
ctx.logger.error('sqlQuery: %s sqlCommand: %s', error.code, sqlCommand);
ctx.logger.error(error);
ctx.logger.error('_____________________end_error_____________________');
}
if (callbackFunction) callbackFunction(error, result);
};
@ -82,7 +81,7 @@ let concatParams = function (val1, val2) {
};
exports.concatParams = concatParams;
exports.upsert = function(task, opt_updateUserIndex) {
exports.upsert = function(ctx, task, opt_updateUserIndex) {
return new Promise(function(resolve, reject) {
task.completeDefaults();
let dateNow = new Date();
@ -93,6 +92,7 @@ exports.upsert = function(task, opt_updateUserIndex) {
userCallback.fromValues(task.userIndex, task.callback);
cbInsert = userCallback.toSQLInsert();
}
let p0 = addSqlParam(task.tenant, values);
let p1 = addSqlParam(task.key, values);
let p2 = addSqlParam(task.status, values);
let p3 = addSqlParam(task.statusInfo, values);
@ -102,8 +102,8 @@ exports.upsert = function(task, opt_updateUserIndex) {
let p7 = addSqlParam(cbInsert, values);
let p8 = addSqlParam(task.baseurl, values);
let p9 = addSqlParam(dateNow, values);
var sqlCommand = 'INSERT INTO task_result (id, status, status_info, last_open_date, user_index, change_id, callback, baseurl)'+
` VALUES (${p1}, ${p2}, ${p3}, ${p4}, ${p5}, ${p6}, ${p7}, ${p8}) ON DUPLICATE KEY UPDATE` +
var sqlCommand = 'INSERT INTO task_result (tenant, id, status, status_info, last_open_date, user_index, change_id, callback, baseurl)'+
` VALUES (${p0}, ${p1}, ${p2}, ${p3}, ${p4}, ${p5}, ${p6}, ${p7}, ${p8}) ON DUPLICATE KEY UPDATE` +
` last_open_date = ${p9}`;
if (task.callback) {
let p10 = addSqlParam(JSON.stringify(task.callback), values);
@ -118,7 +118,7 @@ exports.upsert = function(task, opt_updateUserIndex) {
}
sqlCommand += ';';
exports.sqlQuery(sqlCommand, function(error, result) {
exports.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {

View File

@ -36,7 +36,8 @@ var pg = require('pg');
var co = require('co');
var types = require('pg').types;
var sqlBase = require('./baseConnector');
var configSql = require('config').get('services.CoAuthoring.sql');
const config = require('config');
var configSql = config.get('services.CoAuthoring.sql');
var pgPoolExtraOptions = configSql.get('pgPoolExtraOptions');
let connectionConfig = {
host: configSql.get('dbHost'),
@ -49,7 +50,8 @@ let connectionConfig = {
ssl: false,
idleTimeoutMillis: 30000
};
Object.assign(connectionConfig, pgPoolExtraOptions);
//clone pgPoolExtraOptions to resolve 'TypeError: Cannot redefine property: key' in pg-pool
config.util.extendDeep(connectionConfig, pgPoolExtraOptions);
var pool = new pg.Pool(connectionConfig);
//todo datetime timezone
pg.defaults.parseInputDatesAsUTC = true;
@ -60,11 +62,9 @@ types.setTypeParser(1184, function(stringValue) {
return new Date(stringValue + '+0000');
});
var logger = require('./../../Common/sources/logger');
var maxPacketSize = configSql.get('max_allowed_packet');
exports.sqlQuery = function(sqlCommand, callbackFunction, opt_noModifyRes, opt_noLog, opt_values) {
exports.sqlQuery = function(ctx, sqlCommand, callbackFunction, opt_noModifyRes, opt_noLog, opt_values) {
co(function *() {
var result = null;
var error = null;
@ -73,7 +73,7 @@ exports.sqlQuery = function(sqlCommand, callbackFunction, opt_noModifyRes, opt_n
} catch (err) {
error = err;
if (!opt_noLog) {
logger.warn('sqlQuery error sqlCommand: %s:\r\n%s', sqlCommand.slice(0, 50), err.stack);
ctx.logger.warn('sqlQuery error sqlCommand: %s: %s', sqlCommand.slice(0, 50), err.stack);
}
} finally {
if (callbackFunction) {
@ -110,6 +110,7 @@ function getUpsertString(task, values) {
userCallback.fromValues(task.userIndex, task.callback);
cbInsert = userCallback.toSQLInsert();
}
let p0 = addSqlParam(task.tenant, values);
let p1 = addSqlParam(task.key, values);
let p2 = addSqlParam(task.status, values);
let p3 = addSqlParam(task.statusInfo, values);
@ -121,9 +122,9 @@ function getUpsertString(task, values) {
if (isSupportOnConflict) {
let p9 = addSqlParam(dateNow, values);
//http://stackoverflow.com/questions/34762732/how-to-find-out-if-an-upsert-was-an-update-with-postgresql-9-5-upsert
let sqlCommand = "INSERT INTO task_result (id, status, status_info, last_open_date, user_index, change_id, callback, baseurl)";
sqlCommand += ` VALUES (${p1}, ${p2}, ${p3}, ${p4}, ${p5}, ${p6}, ${p7}, ${p8})`;
sqlCommand += ` ON CONFLICT (id) DO UPDATE SET last_open_date = ${p9}`;
let sqlCommand = "INSERT INTO task_result (tenant, id, status, status_info, last_open_date, user_index, change_id, callback, baseurl)";
sqlCommand += ` VALUES (${p0}, ${p1}, ${p2}, ${p3}, ${p4}, ${p5}, ${p6}, ${p7}, ${p8})`;
sqlCommand += ` ON CONFLICT (tenant, id) DO UPDATE SET last_open_date = ${p9}`;
if (task.callback) {
let p10 = addSqlParam(JSON.stringify(task.callback), values);
sqlCommand += `, callback = task_result.callback || '${sqlBase.UserCallback.prototype.delimiter}{"userIndex":' `;
@ -136,20 +137,20 @@ function getUpsertString(task, values) {
sqlCommand += ", user_index = task_result.user_index + 1 RETURNING user_index as userindex;";
return sqlCommand;
} else {
return `SELECT * FROM merge_db(${p1}, ${p2}, ${p3}, ${p4}, ${p5}, ${p6}, ${p7}, ${p8});`;
return `SELECT * FROM merge_db(${p0}, ${p1}, ${p2}, ${p3}, ${p4}, ${p5}, ${p6}, ${p7}, ${p8});`;
}
}
exports.upsert = function(task) {
exports.upsert = function(ctx, task) {
return new Promise(function(resolve, reject) {
let values = [];
var sqlCommand = getUpsertString(task, values);
exports.sqlQuery(sqlCommand, function(error, result) {
exports.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
if (isSupportOnConflict && '42601' === error.code) {
//SYNTAX ERROR
isSupportOnConflict = false;
logger.warn('checkIsSupportOnConflict false');
resolve(exports.upsert(task));
ctx.logger.warn('checkIsSupportOnConflict false');
resolve(exports.upsert(ctx, task));
} else {
reject(error);
}
@ -165,12 +166,13 @@ exports.upsert = function(task) {
}, true, undefined, values);
});
};
exports.insertChanges = function(tableChanges, startIndex, objChanges, docId, index, user, callback) {
exports.insertChanges = function(ctx, tableChanges, startIndex, objChanges, docId, index, user, callback) {
let i = startIndex;
if (i >= objChanges.length) {
return;
}
let isSupported = true;
let tenant = [];
let id = [];
let changeId = [];
let userId = [];
@ -179,27 +181,28 @@ exports.insertChanges = function(tableChanges, startIndex, objChanges, docId, in
let change = [];
let time = [];
//Postgres 9.4 multi-argument unnest
let sqlCommand = `INSERT INTO ${tableChanges} (id, change_id, user_id, user_id_original, user_name, change_data, change_date) `;
sqlCommand += "SELECT * FROM UNNEST ($1::text[], $2::int[], $3::text[], $4::text[], $5::text[], $6::text[], $7::timestamp[]);";
let values = [id, changeId, userId, userIdOriginal, username, change, time];
let sqlCommand = `INSERT INTO ${tableChanges} (tenant, id, change_id, user_id, user_id_original, user_name, change_data, change_date) `;
sqlCommand += "SELECT * FROM UNNEST ($1::text[], $2::text[], $3::int[], $4::text[], $5::text[], $6::text[], $7::text[], $8::timestamp[]);";
let values = [tenant, id, changeId, userId, userIdOriginal, username, change, time];
let curLength = sqlCommand.length;
for (; i < objChanges.length; ++i) {
//4 is max utf8 bytes per symbol
curLength += 4 * (docId.length + user.id.length + user.idOriginal.length + user.username.length + objChanges[i].change.length) + 4 + 8;
if (curLength >= maxPacketSize && i > startIndex) {
exports.sqlQuery(sqlCommand, function(error, output) {
exports.sqlQuery(ctx, sqlCommand, function(error, output) {
if (error && '42883' == error.code) {
isSupported = false;
logger.warn('postgresql does not support UNNEST');
ctx.logger.warn('postgresql does not support UNNEST');
}
if (error) {
callback(error, output, isSupported);
} else {
exports.insertChanges(tableChanges, i, objChanges, docId, index, user, callback);
exports.insertChanges(ctx, tableChanges, i, objChanges, docId, index, user, callback);
}
}, undefined, undefined, values);
return;
}
tenant.push(ctx.tenant);
id.push(docId);
changeId.push(index++);
userId.push(user.id);
@ -208,10 +211,10 @@ exports.insertChanges = function(tableChanges, startIndex, objChanges, docId, in
change.push(objChanges[i].change);
time.push(objChanges[i].time);
}
exports.sqlQuery(sqlCommand, function(error, output) {
exports.sqlQuery(ctx, sqlCommand, function(error, output) {
if (error && '42883' == error.code) {
isSupported = false;
logger.warn('postgresql does not support UNNEST');
ctx.logger.warn('postgresql does not support UNNEST');
}
callback(error, output, isSupported);
}, undefined, undefined, values);

View File

@ -40,7 +40,6 @@ const commonDefines = require('./../../Common/sources/commondefines');
var utils = require('./../../Common/sources/utils');
var rabbitMQCore = require('./../../Common/sources/rabbitMQCore');
var activeMQCore = require('./../../Common/sources/activeMQCore');
const logger = require('./../../Common/sources/logger');
const cfgQueueType = config.get('queue.type');
var cfgRabbitExchangePubSub = config.get('rabbitmq.exchangepubsub');

View File

@ -56,6 +56,8 @@ const wopiClient = require('./wopiClient');
const constants = require('./../../Common/sources/constants');
const utils = require('./../../Common/sources/utils');
const commonDefines = require('./../../Common/sources/commondefines');
const operationContext = require('./../../Common/sources/operationContext');
const tenantManager = require('./../../Common/sources/tenantManager');
const configStorage = configCommon.get('storage');
const cfgWopiEnable = configCommon.get('wopi.enable');
@ -63,8 +65,10 @@ const cfgHtmlTemplate = configCommon.get('wopi.htmlTemplate');
const cfgTokenEnableBrowser = configCommon.get('services.CoAuthoring.token.enable.browser');
const cfgTokenEnableRequestInbox = configCommon.get('services.CoAuthoring.token.enable.request.inbox');
const cfgTokenEnableRequestOutbox = configCommon.get('services.CoAuthoring.token.enable.request.outbox');
const cfgLicenseFile = configCommon.get('license.license_file');
const app = express();
app.disable('x-powered-by');
//path.resolve uses __dirname by default(unexpected path in pkg)
app.set("views", path.resolve(process.cwd(), cfgHtmlTemplate));
app.set("view engine", "ejs");
@ -73,43 +77,49 @@ const server = http.createServer(app);
let licenseInfo, licenseOriginal, updatePluginsTime, userPlugins, pluginsLoaded;
const updatePlugins = (eventType, filename) => {
console.log('update Folder: %s ; %s', eventType, filename);
operationContext.global.logger.info('update Folder: %s ; %s', eventType, filename);
if (updatePluginsTime && 1000 >= (new Date() - updatePluginsTime)) {
return;
}
console.log('update Folder true: %s ; %s', eventType, filename);
operationContext.global.logger.info('update Folder true: %s ; %s', eventType, filename);
updatePluginsTime = new Date();
pluginsLoaded = false;
};
const readLicense = function*() {
[licenseInfo, licenseOriginal] = yield* license.readLicense();
[licenseInfo, licenseOriginal] = yield* license.readLicense(cfgLicenseFile);
};
const updateLicense = () => {
return co(function*() {
try {
yield* readLicense();
docsCoServer.setLicenseInfo(licenseInfo, licenseOriginal);
console.log('End updateLicense');
operationContext.global.logger.info('End updateLicense');
} catch (err) {
logger.error('updateLicense error:\r\n%s', err.stack);
operationContext.global.logger.error('updateLicense error: %s', err.stack);
}
});
};
logger.warn('Express server starting...');
operationContext.global.logger.warn('Express server starting...');
if (!(cfgTokenEnableBrowser && cfgTokenEnableRequestInbox && cfgTokenEnableRequestOutbox)) {
logger.warn('Set services.CoAuthoring.token.enable.browser, services.CoAuthoring.token.enable.request.inbox, ' +
operationContext.global.logger.warn('Set services.CoAuthoring.token.enable.browser, services.CoAuthoring.token.enable.request.inbox, ' +
'services.CoAuthoring.token.enable.request.outbox in the Document Server config ' +
'to prevent an unauthorized access to your documents and the substitution of important parameters in ONLYOFFICE Document Server requests.');
}
updateLicense();
if (!tenantManager.isMultitenantMode()) {
updateLicense();
fs.watchFile(cfgLicenseFile, updateLicense);
setInterval(updateLicense, 86400000);
}
if (config.has('server.static_content')) {
const staticContent = config.get('server.static_content');
for (let i in staticContent) {
app.use(i, express.static(staticContent[i]['path'], staticContent[i]['options']));
if (staticContent.hasOwnProperty(i)) {
app.use(i, express.static(staticContent[i]['path'], staticContent[i]['options']));
}
}
}
@ -132,7 +142,7 @@ if (configStorage.has('fs.folderPath')) {
const realUrl = req.url.substring(0, index);
res.sendFile(realUrl, sendFileOptions, (err) => {
if (err) {
logger.error(err);
operationContext.global.logger.error(err);
res.status(400).end();
}
});
@ -145,33 +155,41 @@ if (configStorage.has('fs.folderPath')) {
try {
fs.watch(config.get('plugins.path'), updatePlugins);
} catch (e) {
logger.warn('Failed to subscribe to plugin folder updates. When changing the list of plugins, you must restart the server. https://nodejs.org/docs/latest/api/fs.html#fs_availability');
operationContext.global.logger.warn('Failed to subscribe to plugin folder updates. When changing the list of plugins, you must restart the server. https://nodejs.org/docs/latest/api/fs.html#fs_availability');
}
fs.watchFile(configCommon.get('license').get('license_file'), updateLicense);
setInterval(updateLicense, 86400000);
// Если захочется использовать 'development' и 'production',
// то с помощью app.settings.env (https://github.com/strongloop/express/issues/936)
// Если нужна обработка ошибок, то теперь она такая https://github.com/expressjs/errorhandler
docsCoServer.install(server, () => {
console.log('Start callbackFunction');
operationContext.global.logger.info('Start callbackFunction');
server.listen(config.get('server.port'), () => {
logger.warn("Express server listening on port %d in %s mode. Version: %s. Build: %s", config.get('server.port'), app.settings.env, commonDefines.buildVersion, commonDefines.buildNumber);
operationContext.global.logger.warn("Express server listening on port %d in %s mode. Version: %s. Build: %s", config.get('server.port'), app.settings.env, commonDefines.buildVersion, commonDefines.buildNumber);
});
app.get('/index.html', (req, res) => {
let buildVersion = commonDefines.buildVersion;
let buildNumber = commonDefines.buildNumber;
let buildDate, packageType, customerId = "";
if (licenseInfo) {
buildDate = licenseInfo.buildDate.toISOString();
packageType = licenseInfo.packageType;
customerId = licenseInfo.customerId;
}
let output = `Server is functioning normally. Version: ${buildVersion}. Build: ${buildNumber}`;
output += `. Release date: ${buildDate}. Package type: ${packageType}. Customer Id: ${customerId}`;
res.send(output);
return co(function*() {
let ctx = new operationContext.Context();
try {
ctx.initFromRequest(req);
let licenseInfo = yield tenantManager.getTenantLicense(ctx);
let buildVersion = commonDefines.buildVersion;
let buildNumber = commonDefines.buildNumber;
let buildDate, packageType, customerId = "";
if (licenseInfo) {
buildDate = licenseInfo.buildDate.toISOString();
packageType = licenseInfo.packageType;
customerId = licenseInfo.customerId;
}
let output = `Server is functioning normally. Version: ${buildVersion}. Build: ${buildNumber}`;
output += `. Release date: ${buildDate}. Package type: ${packageType}. Customer Id: ${customerId}`;
res.send(output);
} catch (err) {
ctx.logger.error('index.html error: %s', err.stack);
res.sendStatus(400);
}
});
});
const rawFileParser = bodyParser.raw(
{inflate: true, limit: config.get('server.limits_tempfile_upload'), type: function() {return true;}});
@ -204,8 +222,9 @@ docsCoServer.install(server, () => {
res.sendStatus(403);
}
});
app.post('/uploadold/:docid/:userid/:index', fileUploaderService.uploadImageFileOld);
app.post('/upload/:docid/:userid/:index', rawFileParser, fileUploaderService.uploadImageFile);
//'*' for backward compatible
app.post('/uploadold/:docid*', fileUploaderService.uploadImageFileOld);
app.post('/upload/:docid*', rawFileParser, fileUploaderService.uploadImageFile);
app.post('/downloadas/:docid', rawFileParser, canvasService.downloadAs);
app.post('/savefile/:docid', rawFileParser, canvasService.saveFile);
@ -232,11 +251,13 @@ docsCoServer.install(server, () => {
if (cfgWopiEnable) {
app.get('/hosting/discovery', utils.checkClientIp, wopiClient.discovery);
app.get('/hosting/capabilities', utils.checkClientIp, wopiClient.collaboraCapabilities);
app.post('/hosting/wopi/:documentType/:mode', utils.checkClientIp, urleEcodedParser, forms.none(), utils.lowercaseQueryString, wopiClient.getEditorHtml);
app.post('/hosting/wopi/:documentType/:mode', urleEcodedParser, forms.none(), utils.lowercaseQueryString, wopiClient.getEditorHtml);
}
app.post('/dummyCallback', utils.checkClientIp, rawFileParser, function(req, res){
logger.debug(`dummyCallback req.body:%s`, req.body);
let ctx = new operationContext.Context();
ctx.initFromRequest(req);
ctx.logger.debug(`dummyCallback req.body:%s`, req.body);
utils.fillResponseSimple(res, JSON.stringify({error: 0}, "application/json"));
});
@ -291,8 +312,10 @@ docsCoServer.install(server, () => {
app.get('/themes.json', apicache.middleware("5 minutes"), (req, res) => {
return co(function*() {
let themes = [];
let ctx = new operationContext.Context();
try {
logger.info('themes.json start');
ctx.initFromRequest(req);
ctx.logger.info('themes.json start');
if (!config.has('server.static_content') || !config.has('themes.uri')) {
return;
}
@ -304,8 +327,8 @@ docsCoServer.install(server, () => {
if (staticContent.hasOwnProperty(i) && themesUri.startsWith(i)) {
let dir = staticContent[i].path + themesUri.substring(i.length);
themesList = yield utils.listObjects(dir, true);
logger.debug('themes.json dir:%s', dir);
logger.debug('themes.json themesList:%j', themesList);
ctx.logger.debug('themes.json dir:%s', dir);
ctx.logger.debug('themes.json themesList:%j', themesList);
for (let j = 0; j < themesList.length; ++j) {
if (themesList[j].endsWith('.json')) {
let data = yield utils.readFile(themesList[j], true);
@ -316,7 +339,7 @@ docsCoServer.install(server, () => {
}
}
} catch (err) {
logger.error('themes.json error:%s', err.stack);
ctx.logger.error('themes.json error:%s', err.stack);
} finally {
if (themes.length > 0) {
res.setHeader('Content-Type', 'application/json');
@ -324,15 +347,15 @@ docsCoServer.install(server, () => {
} else {
res.sendStatus(404);
}
logger.info('themes.json end');
ctx.logger.info('themes.json end');
}
});
});
});
process.on('uncaughtException', (err) => {
logger.error((new Date).toUTCString() + ' uncaughtException:', err.message);
logger.error(err.stack);
operationContext.global.logger.error((new Date).toUTCString() + ' uncaughtException:', err.message);
operationContext.global.logger.error(err.stack);
logger.shutdown(() => {
process.exit(1);
});

View File

@ -47,11 +47,11 @@ var WAIT_TIMEOUT = 30000;
var LOOP_TIMEOUT = 1000;
var EXEC_TIMEOUT = WAIT_TIMEOUT + utils.CONVERTION_TIMEOUT;
exports.shutdown = function(editorData, status) {
exports.shutdown = function(ctx, editorData, status) {
return co(function*() {
var res = true;
try {
logger.debug('shutdown start:' + EXEC_TIMEOUT);
ctx.logger.debug('shutdown start:' + EXEC_TIMEOUT);
//redisKeyShutdown не простой счетчик, чтобы его не уменьшала сборка, которая началась перед запуском Shutdown
//сбрасываем redisKeyShutdown на всякий случай, если предыдущий запуск не дошел до конца
@ -60,24 +60,24 @@ exports.shutdown = function(editorData, status) {
var pubsub = new pubsubService();
yield pubsub.initPromise();
//inner ping to update presence
logger.debug('shutdown pubsub shutdown message');
pubsub.publish(JSON.stringify({type: commonDefines.c_oPublishType.shutdown, status: status}));
ctx.logger.debug('shutdown pubsub shutdown message');
pubsub.publish(JSON.stringify({type: commonDefines.c_oPublishType.shutdown, ctx: ctx, status: status}));
//wait while pubsub deliver and start conversion
logger.debug('shutdown start wait pubsub deliver');
ctx.logger.debug('shutdown start wait pubsub deliver');
var startTime = new Date().getTime();
var isStartWait = true;
while (true) {
var curTime = new Date().getTime() - startTime;
if (isStartWait && curTime >= WAIT_TIMEOUT) {
isStartWait = false;
logger.debug('shutdown stop wait pubsub deliver');
ctx.logger.debug('shutdown stop wait pubsub deliver');
} else if (curTime >= EXEC_TIMEOUT) {
res = false;
logger.debug('shutdown timeout');
ctx.logger.debug('shutdown timeout');
break;
}
var remainingFiles = yield editorData.getShutdownCount(redisKeyShutdown);
logger.debug('shutdown remaining files:%d', remainingFiles);
ctx.logger.debug('shutdown remaining files:%d', remainingFiles);
if (!isStartWait && remainingFiles <= 0) {
break;
}
@ -88,10 +88,10 @@ exports.shutdown = function(editorData, status) {
yield editorData.cleanupShutdown(redisKeyShutdown);
yield pubsub.close();
logger.debug('shutdown end');
ctx.logger.debug('shutdown end');
} catch (e) {
res = false;
logger.error('shutdown error:\r\n%s', e.stack);
ctx.logger.error('shutdown error: %s', e.stack);
}
return res;
});

View File

@ -34,9 +34,9 @@
const crypto = require('crypto');
var sqlBase = require('./baseConnector');
var logger = require('./../../Common/sources/logger');
var utils = require('./../../Common/sources/utils');
var constants = require('./../../Common/sources/constants');
var tenantManager = require('./../../Common/sources/tenantManager');
let addSqlParam = sqlBase.baseConnector.addSqlParameter;
let concatParams = sqlBase.baseConnector.concatParams;
@ -56,6 +56,7 @@ var FileStatus = {
};
function TaskResultData() {
this.tenant = null;
this.key = null;
this.status = null;
this.statusInfo = null;
@ -71,6 +72,9 @@ function TaskResultData() {
this.innerPasswordChange = null;//not a DB field
}
TaskResultData.prototype.completeDefaults = function() {
if (!this.tenant) {
this.tenant = tenantManager.getDefautTenant();
}
if (!this.key) {
this.key = '';
}
@ -100,16 +104,17 @@ TaskResultData.prototype.completeDefaults = function() {
}
};
function upsert(task, opt_updateUserIndex) {
return sqlBase.baseConnector.upsert(task, opt_updateUserIndex);
function upsert(ctx, task, opt_updateUserIndex) {
return sqlBase.baseConnector.upsert(ctx, task, opt_updateUserIndex);
}
function select(docId) {
function select(ctx, docId) {
return new Promise(function(resolve, reject) {
let values = [];
let sqlParam = addSqlParam(docId, values);
let sqlCommand = `SELECT * FROM task_result WHERE id=${sqlParam};`;
sqlBase.baseConnector.sqlQuery(sqlCommand, function(error, result) {
let p1 = addSqlParam(ctx.tenant, values);
let p2 = addSqlParam(docId, values);
let sqlCommand = `SELECT * FROM task_result WHERE tenant=${p1} AND id=${p2};`;
sqlBase.baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {
@ -170,14 +175,15 @@ function toUpdateArray(task, updateTime, isMask, values, setPassword) {
return res;
}
function update(task, setPassword) {
function update(ctx, task, setPassword) {
return new Promise(function(resolve, reject) {
let values = [];
let updateElems = toUpdateArray(task, true, false, values, setPassword);
let sqlSet = updateElems.join(', ');
let sqlParam = addSqlParam(task.key, values);
let sqlCommand = `UPDATE task_result SET ${sqlSet} WHERE id=${sqlParam};`;
sqlBase.baseConnector.sqlQuery(sqlCommand, function(error, result) {
let p1 = addSqlParam(task.tenant, values);
let p2 = addSqlParam(task.key, values);
let sqlCommand = `UPDATE task_result SET ${sqlSet} WHERE tenant=${p1} AND id=${p2};`;
sqlBase.baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {
@ -187,16 +193,17 @@ function update(task, setPassword) {
});
}
function updateIf(task, mask) {
function updateIf(ctx, task, mask) {
return new Promise(function(resolve, reject) {
let values = [];
let commandArg = toUpdateArray(task, true, false, values, false);
let commandArgMask = toUpdateArray(mask, false, true, values, false);
commandArgMask.push('tenant=' + addSqlParam(mask.tenant, values));
commandArgMask.push('id=' + addSqlParam(mask.key, values));
let sqlSet = commandArg.join(', ');
let sqlWhere = commandArgMask.join(' AND ');
let sqlCommand = `UPDATE task_result SET ${sqlSet} WHERE ${sqlWhere};`;
sqlBase.baseConnector.sqlQuery(sqlCommand, function(error, result) {
sqlBase.baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {
@ -205,28 +212,30 @@ function updateIf(task, mask) {
}, undefined, undefined, values);
});
}
function restoreInitialPassword(docId) {
return select(docId).then(function(selectRes) {
function restoreInitialPassword(ctx, docId) {
return select(ctx, docId).then(function(selectRes) {
if (selectRes.length > 0) {
var row = selectRes[0];
let docPassword = sqlBase.DocumentPassword.prototype.getDocPassword(docId, row.password);
let docPassword = sqlBase.DocumentPassword.prototype.getDocPassword(ctx, row.password);
var updateTask = new TaskResultData();
updateTask.tenant = ctx.tenant;
updateTask.key = docId;
if (docPassword.initial) {
var documentPassword = new sqlBase.DocumentPassword();
documentPassword.fromValues(docPassword.initial);
updateTask.password = documentPassword.toSQLInsert();
return update(updateTask, true);
return update(ctx, updateTask, true);
} else if (docPassword.current) {
updateTask.password = null;
return update(updateTask, true);
return update(ctx, updateTask, true);
}
}
});
}
function addRandomKey(task, opt_prefix, opt_size) {
function addRandomKey(ctx, task, opt_prefix, opt_size) {
return new Promise(function(resolve, reject) {
task.tenant = ctx.tenant;
if (undefined !== opt_prefix && undefined !== opt_size) {
task.key = opt_prefix + crypto.randomBytes(opt_size).toString("hex");
} else {
@ -234,6 +243,7 @@ function addRandomKey(task, opt_prefix, opt_size) {
}
task.completeDefaults();
let values = [];
let p0 = addSqlParam(task.tenant, values);
let p1 = addSqlParam(task.key, values);
let p2 = addSqlParam(task.status, values);
let p3 = addSqlParam(task.statusInfo, values);
@ -242,9 +252,9 @@ function addRandomKey(task, opt_prefix, opt_size) {
let p6 = addSqlParam(task.changeId, values);
let p7 = addSqlParam(task.callback, values);
let p8 = addSqlParam(task.baseurl, values);
let sqlCommand = 'INSERT INTO task_result (id, status, status_info, last_open_date, user_index, change_id, callback, baseurl)' +
` VALUES (${p1}, ${p2}, ${p3}, ${p4}, ${p5}, ${p6}, ${p7}, ${p8});`;
sqlBase.baseConnector.sqlQuery(sqlCommand, function(error, result) {
let sqlCommand = 'INSERT INTO task_result (tenant, id, status, status_info, last_open_date, user_index, change_id, callback, baseurl)' +
` VALUES (${p0}, ${p1}, ${p2}, ${p3}, ${p4}, ${p5}, ${p6}, ${p7}, ${p8});`;
sqlBase.baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {
@ -253,8 +263,9 @@ function addRandomKey(task, opt_prefix, opt_size) {
}, undefined, undefined, values);
});
}
function* addRandomKeyTask(key, opt_prefix, opt_size) {
function* addRandomKeyTask(ctx, key, opt_prefix, opt_size) {
var task = new TaskResultData();
task.tenant = ctx.tenant;
task.key = key;
task.status = FileStatus.WaitQueue;
//nTryCount чтобы не зависнуть если реально будут проблемы с DB
@ -262,7 +273,7 @@ function* addRandomKeyTask(key, opt_prefix, opt_size) {
var addRes = null;
while (nTryCount-- > 0) {
try {
addRes = yield addRandomKey(task, opt_prefix, opt_size);
addRes = yield addRandomKey(ctx, task, opt_prefix, opt_size);
} catch (e) {
addRes = null;
//key exist, try again
@ -278,12 +289,13 @@ function* addRandomKeyTask(key, opt_prefix, opt_size) {
}
}
function remove(docId) {
function remove(ctx, docId) {
return new Promise(function(resolve, reject) {
let values = [];
let sqlParam = addSqlParam(docId, values);
const sqlCommand = `DELETE FROM task_result WHERE id=${sqlParam};`;
sqlBase.baseConnector.sqlQuery(sqlCommand, function(error, result) {
let p1 = addSqlParam(ctx.tenant, values);
let p2 = addSqlParam(docId, values);
const sqlCommand = `DELETE FROM task_result WHERE tenant=${p1} AND id=${p2};`;
sqlBase.baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {
@ -292,14 +304,15 @@ function remove(docId) {
}, undefined, undefined, values);
});
}
function removeIf(mask) {
function removeIf(ctx, mask) {
return new Promise(function(resolve, reject) {
let values = [];
let commandArgMask = toUpdateArray(mask, false, true, values, false);
commandArgMask.push('tenant=' + addSqlParam(mask.tenant, values));
commandArgMask.push('id=' + addSqlParam(mask.key, values));
let sqlWhere = commandArgMask.join(' AND ');
const sqlCommand = `DELETE FROM task_result WHERE ${sqlWhere};`;
sqlBase.baseConnector.sqlQuery(sqlCommand, function(error, result) {
sqlBase.baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {
@ -308,7 +321,7 @@ function removeIf(mask) {
}, undefined, undefined, values);
});
}
function getExpired(maxCount, expireSeconds) {
function getExpired(ctx, maxCount, expireSeconds) {
return new Promise(function(resolve, reject) {
let values = [];
let expireDate = new Date();
@ -316,8 +329,8 @@ function getExpired(maxCount, expireSeconds) {
let sqlParam1 = addSqlParam(expireDate, values);
let sqlParam2 = addSqlParam(maxCount, values);
let sqlCommand = `SELECT * FROM task_result WHERE last_open_date <= ${sqlParam1}` +
` AND NOT EXISTS(SELECT id FROM doc_changes WHERE doc_changes.id = task_result.id LIMIT 1) LIMIT ${sqlParam2};`;
sqlBase.baseConnector.sqlQuery(sqlCommand, function(error, result) {
` AND NOT EXISTS(SELECT tenant, id FROM doc_changes WHERE doc_changes.tenant = task_result.tenant AND doc_changes.id = task_result.id LIMIT 1) LIMIT ${sqlParam2};`;
sqlBase.baseConnector.sqlQuery(ctx, sqlCommand, function(error, result) {
if (error) {
reject(error);
} else {

View File

@ -44,13 +44,14 @@ const logger = require('./../../Common/sources/logger');
const utils = require('./../../Common/sources/utils');
const constants = require('./../../Common/sources/constants');
const commonDefines = require('./../../Common/sources/commondefines');
const operationContext = require('./../../Common/sources/operationContext');
const tenantManager = require('./../../Common/sources/tenantManager');
const sqlBase = require('./baseConnector');
const taskResult = require('./taskresult');
const canvasService = require('./canvasservice');
const cfgTokenOutboxAlgorithm = config.get('services.CoAuthoring.token.outbox.algorithm');
const cfgTokenOutboxExpires = config.get('services.CoAuthoring.token.outbox.expires');
const cfgSignatureSecretOutbox = config.get('services.CoAuthoring.secret.outbox');
const cfgTokenEnableBrowser = config.get('services.CoAuthoring.token.enable.browser');
const cfgCallbackRequestTimeout = config.get('services.CoAuthoring.server.callbackRequestTimeout');
const cfgDownloadTimeout = config.get('FileConverter.converter.downloadTimeout');
@ -97,15 +98,17 @@ let mimeTypesByExt = (function() {
function discovery(req, res) {
return co(function*() {
let output = '';
let ctx = new operationContext.Context();
try {
logger.info('wopiDiscovery start');
ctx.initFromRequest(req);
ctx.logger.info('wopiDiscovery start');
let baseUrl = cfgWopiHost || utils.getBaseUrlByRequest(req);
let names = ['Word','Excel','PowerPoint'];
let favIconUrls = [cfgWopiFavIconUrlWord, cfgWopiFavIconUrlCell, cfgWopiFavIconUrlSlide];
let exts = [{view: cfgWopiWordView, edit: cfgWopiWordEdit}, {view: cfgWopiCellView, edit: cfgWopiCellEdit},
{view: cfgWopiSlideView, edit: cfgWopiSlideEdit}];
let templateStart = `${baseUrl}/hosting/wopi`;
let templateEnd = `&amp;&lt;rs=DC_LLCC&amp;&gt;&lt;dchat=DISABLE_CHAT&amp;&gt;&lt;e=EMBEDDED&amp;&gt;`;
let templateEnd = `&amp;&lt;rs=DC_LLCC&amp;&gt;&lt;dchat=DISABLE_CHAT&amp;&gt;&lt;embed=EMBEDDED&amp;&gt;`;
templateEnd += `&lt;fs=FULLSCREEN&amp;&gt;&lt;hid=HOST_SESSION_ID&amp;&gt;&lt;rec=RECORDING&amp;&gt;`;
templateEnd += `&lt;sc=SESSION_CONTEXT&amp;&gt;&lt;thm=THEME_ID&amp;&gt;&lt;ui=UI_LLCC&amp;&gt;`;
templateEnd += `&lt;wopisrc=WOPI_SOURCE&amp;&gt;&amp;`;
@ -120,13 +123,16 @@ function discovery(req, res) {
}
let ext = exts[i];
let urlTemplateView = `${templateStart}/${documentTypes[i]}/view?${templateEnd}`;
let urlTemplateEmbedView = `${templateStart}/${documentTypes[i]}/view?embed=1${templateEnd}`;
let urlTemplateEdit = `${templateStart}/${documentTypes[i]}/edit?${templateEnd}`;
output +=`<app name="${name}" favIconUrl="${favIconUrl}">`;
for (let j = 0; j < ext.view.length; ++j) {
output += `<action name="view" ext="${ext.view[j]}" urlsrc="${urlTemplateView}" />`;
output += `<action name="embedview" ext="${ext.view[j]}" urlsrc="${urlTemplateEmbedView}" />`;
}
for (let j = 0; j < ext.edit.length; ++j) {
output += `<action name="view" ext="${ext.edit[j]}" urlsrc="${urlTemplateView}" />`;
output += `<action name="embedview" ext="${ext.edit[j]}" urlsrc="${urlTemplateEmbedView}" />`;
if ("oform" !== ext.edit[j]) {
//todo config
output += `<action name="editnew" ext="${ext.edit[j]}" requires="locks,update" urlsrc="${urlTemplateEdit}" />`;
@ -140,6 +146,7 @@ function discovery(req, res) {
for(let i = 0; i < exts.length; ++i) {
let ext = exts[i];
let urlTemplateView = `${templateStart}/${documentTypes[i]}/view?${templateEnd}`;
let urlTemplateEmbedView = `${templateStart}/${documentTypes[i]}/view?embed=1${templateEnd}`;
let urlTemplateEdit = `${templateStart}/${documentTypes[i]}/edit?${templateEnd}`;
for (let j = 0; j < ext.view.length; ++j) {
let mimeTypes = mimeTypesByExt[ext.view[j]];
@ -147,6 +154,7 @@ function discovery(req, res) {
mimeTypes.forEach((value) => {
output += `<app name="${value}">`;
output += `<action name="view" ext="" default="true" urlsrc="${urlTemplateView}" />`;
output += `<action name="embedview" ext="" urlsrc="${urlTemplateEmbedView}" />`;
output += `</app>`;
});
}
@ -174,11 +182,11 @@ function discovery(req, res) {
}
output += `</net-zone>${proofKey}</wopi-discovery>`;
} catch (err) {
logger.error('wopiDiscovery error:%s', err.stack);
ctx.logger.error('wopiDiscovery error:%s', err.stack);
} finally {
res.setHeader('Content-Type', 'text/xml');
res.send(output);
logger.info('wopiDiscovery end');
ctx.logger.info('wopiDiscovery end');
}
});
}
@ -188,13 +196,15 @@ function collaboraCapabilities(req, res) {
"convert-to": {"available": false}, "hasMobileSupport": true, "hasProxyPrefix": false, "hasTemplateSaveAs": false,
"hasTemplateSource": true, "productVersion": commonDefines.buildVersion
};
let ctx = new operationContext.Context();
try {
logger.info('collaboraCapabilities start');
ctx.initFromRequest(req);
ctx.logger.info('collaboraCapabilities start');
} catch (err) {
logger.error('collaboraCapabilities error:%s', err.stack);
ctx.logger.error('collaboraCapabilities error:%s', err.stack);
} finally {
utils.fillResponseSimple(res, JSON.stringify(output), "application/json");
logger.info('collaboraCapabilities end');
ctx.logger.info('collaboraCapabilities end');
}
});
}
@ -228,7 +238,7 @@ function getLastModifiedTimeFromCallbacks(callbacks) {
function isCorrectUserAuth(userAuth) {
return undefined !== userAuth.wopiSrc;
}
function parseWopiCallback(docId, userAuthStr, opt_url) {
function parseWopiCallback(ctx, userAuthStr, opt_url) {
let wopiParams = null;
if (isWopiCallback(userAuthStr)) {
let userAuth = JSON.parse(userAuthStr);
@ -238,58 +248,59 @@ function parseWopiCallback(docId, userAuthStr, opt_url) {
let commonInfo = null;
let lastModifiedTime = null;
if (opt_url) {
let commonInfoStr = sqlBase.UserCallback.prototype.getCallbackByUserIndex(docId, opt_url, 1);
let commonInfoStr = sqlBase.UserCallback.prototype.getCallbackByUserIndex(ctx, opt_url, 1);
if (isWopiCallback(commonInfoStr)) {
commonInfo = JSON.parse(commonInfoStr);
lastModifiedTime = commonInfo.fileInfo.LastModifiedTime;
if (lastModifiedTime) {
let callbacks = sqlBase.UserCallback.prototype.getCallbacks(docId, opt_url);
let callbacks = sqlBase.UserCallback.prototype.getCallbacks(ctx, opt_url);
lastModifiedTime = getLastModifiedTimeFromCallbacks(callbacks);
}
}
}
wopiParams = {commonInfo: commonInfo, userAuth: userAuth, LastModifiedTime: lastModifiedTime};
logger.debug('parseWopiCallback wopiParams:%j', wopiParams);
ctx.logger.debug('parseWopiCallback wopiParams:%j', wopiParams);
}
return wopiParams;
}
function checkAndInvalidateCache(docId, fileInfo) {
function checkAndInvalidateCache(ctx, docId, fileInfo) {
return co(function*() {
let res = {success: true, lockId: undefined};
let selectRes = yield taskResult.select(docId);
let selectRes = yield taskResult.select(ctx, docId);
if (selectRes.length > 0) {
let row = selectRes[0];
if (row.callback) {
let commonInfoStr = sqlBase.UserCallback.prototype.getCallbackByUserIndex(docId, row.callback, 1);
let commonInfoStr = sqlBase.UserCallback.prototype.getCallbackByUserIndex(ctx, row.callback, 1);
if (isWopiCallback(commonInfoStr)) {
let commonInfo = JSON.parse(commonInfoStr);
res.lockId = commonInfo.lockId;
logger.debug('wopiEditor lockId from DB lockId=%s', res.lockId);
let unlockMarkStr = sqlBase.UserCallback.prototype.getCallbackByUserIndex(docId, row.callback);
logger.debug('wopiEditor commonInfoStr=%s', commonInfoStr);
logger.debug('wopiEditor unlockMarkStr=%s', unlockMarkStr);
ctx.logger.debug('wopiEditor lockId from DB lockId=%s', res.lockId);
let unlockMarkStr = sqlBase.UserCallback.prototype.getCallbackByUserIndex(ctx, row.callback);
ctx.logger.debug('wopiEditor commonInfoStr=%s', commonInfoStr);
ctx.logger.debug('wopiEditor unlockMarkStr=%s', unlockMarkStr);
let hasUnlockMarker = isWopiUnlockMarker(unlockMarkStr);
logger.debug('wopiEditor hasUnlockMarker=%s', hasUnlockMarker);
ctx.logger.debug('wopiEditor hasUnlockMarker=%s', hasUnlockMarker);
if (hasUnlockMarker) {
let fileInfoVersion = fileInfo.Version;
let cacheVersion = commonInfo.fileInfo.Version;
let fileInfoModified = fileInfo.LastModifiedTime;
let cacheModified = commonInfo.fileInfo.LastModifiedTime;
logger.debug('wopiEditor version fileInfo=%s; cache=%s', fileInfoVersion, cacheVersion);
logger.debug('wopiEditor LastModifiedTime fileInfo=%s; cache=%s', fileInfoModified, cacheModified);
ctx.logger.debug('wopiEditor version fileInfo=%s; cache=%s', fileInfoVersion, cacheVersion);
ctx.logger.debug('wopiEditor LastModifiedTime fileInfo=%s; cache=%s', fileInfoModified, cacheModified);
if (fileInfoVersion !== cacheVersion || (fileInfoModified !== cacheModified)) {
var mask = new taskResult.TaskResultData();
mask.tenant = ctx.tenant;
mask.key = docId;
mask.last_open_date = row.last_open_date;
//cleanupRes can be false in case of simultaneous opening. it is OK
let cleanupRes = yield canvasService.cleanupCacheIf(mask);
logger.debug('wopiEditor cleanupRes=%s', cleanupRes);
let cleanupRes = yield canvasService.cleanupCacheIf(ctx, mask);
ctx.logger.debug('wopiEditor cleanupRes=%s', cleanupRes);
res.lockId = undefined;
}
}
} else {
res.success = false;
logger.warn('wopiEditor attempt to open not wopi record');
ctx.logger.warn('wopiEditor attempt to open not wopi record');
}
}
}
@ -299,14 +310,19 @@ function checkAndInvalidateCache(docId, fileInfo) {
function getEditorHtml(req, res) {
return co(function*() {
let params = {key: undefined, fileInfo: {}, userAuth: {}, queryParams: req.query, token: undefined, documentType: undefined};
let ctx = new operationContext.Context();
try {
logger.info('wopiEditor start');
logger.debug(`wopiEditor req.url:%s`, req.url);
logger.debug(`wopiEditor req.query:%j`, req.query);
logger.debug(`wopiEditor req.body:%j`, req.body);
ctx.initFromRequest(req);
let wopiSrc = req.query['wopisrc'];
let fileId = wopiSrc.substring(wopiSrc.lastIndexOf('/') + 1);
ctx.setDocId(fileId);
ctx.logger.info('wopiEditor start');
ctx.logger.debug(`wopiEditor req.url:%s`, req.url);
ctx.logger.debug(`wopiEditor req.query:%j`, req.query);
ctx.logger.debug(`wopiEditor req.body:%j`, req.body);
params.documentType = req.params.documentType;
let mode = req.params.mode;
let wopiSrc = req.query['wopisrc'];
let sc = req.query['sc'];
let hostSessionId = req.query['hid'];
let access_token = req.body['access_token'] || "";
@ -314,7 +330,7 @@ function getEditorHtml(req, res) {
let uri = `${encodeURI(wopiSrc)}?access_token=${encodeURIComponent(access_token)}`;
let fileInfo = params.fileInfo = yield checkFileInfo(uri, access_token, sc);
let fileInfo = params.fileInfo = yield checkFileInfo(ctx, uri, access_token, sc);
if (!fileInfo) {
params.fileInfo = {};
return;
@ -325,7 +341,6 @@ function getEditorHtml(req, res) {
}
//docId
let docId = undefined;
let fileId = wopiSrc.substring(wopiSrc.lastIndexOf('/') + 1);
if ('view' !== mode) {
docId = `${fileId}`;
} else {
@ -339,7 +354,7 @@ function getEditorHtml(req, res) {
}
}
docId = docId.replace(constants.DOC_ID_REPLACE_REGEX, '_').substring(0, constants.DOC_ID_MAX_LENGTH);
logger.debug(`wopiEditor docId=%s`, docId);
ctx.logger.debug(`wopiEditor`);
params.key = docId;
let userAuth = params.userAuth = {
wopiSrc: wopiSrc, access_token: access_token, access_token_ttl: access_token_ttl,
@ -347,7 +362,7 @@ function getEditorHtml(req, res) {
};
//check and invalidate cache
let checkRes = yield checkAndInvalidateCache(docId, fileInfo);
let checkRes = yield checkAndInvalidateCache(ctx, docId, fileInfo);
let lockId = checkRes.lockId;
if (!checkRes.success) {
params.fileInfo = {};
@ -359,12 +374,12 @@ function getEditorHtml(req, res) {
fileType = fileInfo.FileExtension ? fileInfo.FileExtension.substr(1) : fileType;
lockId = crypto.randomBytes(16).toString('base64');
let commonInfo = JSON.stringify({lockId: lockId, fileInfo: fileInfo});
yield canvasService.commandOpenStartPromise(docId, utils.getBaseUrlByRequest(req), 1, commonInfo, fileType);
yield canvasService.commandOpenStartPromise(ctx, docId, utils.getBaseUrlByRequest(req), 1, commonInfo, fileType);
}
//Lock
if ('view' !== mode) {
let lockRes = yield lock('LOCK', lockId, fileInfo, userAuth);
let lockRes = yield lock(ctx, 'LOCK', lockId, fileInfo, userAuth);
if (!lockRes) {
params.fileInfo = {};
return;
@ -379,36 +394,36 @@ function getEditorHtml(req, res) {
if (cfgTokenEnableBrowser) {
let options = {algorithm: cfgTokenOutboxAlgorithm, expiresIn: cfgTokenOutboxExpires};
let secret = utils.getSecretByElem(cfgSignatureSecretOutbox);
let secret = yield tenantManager.getTenantSecret(ctx, commonDefines.c_oAscSecretType.Inbox);
params.token = jwt.sign(params, secret, options);
}
} catch (err) {
logger.error('wopiEditor error:%s', err.stack);
ctx.logger.error('wopiEditor error:%s', err.stack);
params.fileInfo = {};
} finally {
logger.debug('wopiEditor render params=%j', params);
ctx.logger.debug('wopiEditor render params=%j', params);
try {
res.render("editor-wopi", params);
} catch (err) {
logger.error('wopiEditor error:%s', err.stack);
ctx.logger.error('wopiEditor error:%s', err.stack);
res.sendStatus(400);
}
logger.info('wopiEditor end');
ctx.logger.info('wopiEditor end');
}
});
}
function putFile(wopiParams, data, dataStream, dataSize, userLastChangeId, isModifiedByUser, isAutosave, isExitSave) {
function putFile(ctx, wopiParams, data, dataStream, dataSize, userLastChangeId, isModifiedByUser, isAutosave, isExitSave) {
return co(function* () {
let postRes = null;
try {
logger.info('wopi PutFile start');
ctx.logger.info('wopi PutFile start');
if (!wopiParams.userAuth) {
return postRes;
}
let fileInfo = wopiParams.commonInfo.fileInfo;
let userAuth = wopiParams.userAuth;
let uri = `${userAuth.wopiSrc}/contents?access_token=${userAuth.access_token}`;
let filterStatus = yield checkIpFilter(uri);
let filterStatus = yield checkIpFilter(ctx, uri);
if (0 !== filterStatus) {
return postRes;
}
@ -427,33 +442,33 @@ function putFile(wopiParams, data, dataStream, dataSize, userLastChangeId, isMod
headers['X-LOOL-WOPI-Timestamp'] = wopiParams.LastModifiedTime;
}
logger.debug('wopi PutFile request uri=%s headers=%j', uri, headers);
ctx.logger.debug('wopi PutFile request uri=%s headers=%j', uri, headers);
postRes = yield utils.postRequestPromise(uri, data, dataStream, dataSize, cfgCallbackRequestTimeout, undefined, headers);
logger.debug('wopi PutFile response headers=%j', postRes.response.headers);
logger.debug('wopi PutFile response body:%s', postRes.body);
ctx.logger.debug('wopi PutFile response headers=%j', postRes.response.headers);
ctx.logger.debug('wopi PutFile response body:%s', postRes.body);
} else {
logger.warn('wopi SupportsUpdate = false or UserCanWrite = false');
ctx.logger.warn('wopi SupportsUpdate = false or UserCanWrite = false');
}
} catch (err) {
logger.error('wopi error PutFile:%s', err.stack);
ctx.logger.error('wopi error PutFile:%s', err.stack);
} finally {
logger.info('wopi PutFile end');
ctx.logger.info('wopi PutFile end');
}
return postRes;
});
}
function renameFile(wopiParams, name) {
function renameFile(ctx, wopiParams, name) {
return co(function* () {
let res;
let res = undefined;
try {
logger.info('wopi RenameFile start');
ctx.logger.info('wopi RenameFile start');
if (!wopiParams.userAuth) {
return res;
}
let fileInfo = wopiParams.commonInfo.fileInfo;
let userAuth = wopiParams.userAuth;
let uri = `${userAuth.wopiSrc}?access_token=${userAuth.access_token}`;
let filterStatus = yield checkIpFilter(uri);
let filterStatus = yield checkIpFilter(ctx, uri);
if (0 !== filterStatus) {
return res;
}
@ -466,9 +481,9 @@ function renameFile(wopiParams, name) {
let headers = {'X-WOPI-Override': 'RENAME_FILE', 'X-WOPI-Lock': commonInfo.lockId, 'X-WOPI-RequestedName': utf7.encode(name)};
fillStandardHeaders(headers, uri, userAuth.access_token);
logger.debug('wopi RenameFile request uri=%s headers=%j', uri, headers);
ctx.logger.debug('wopi RenameFile request uri=%s headers=%j', uri, headers);
let postRes = yield utils.postRequestPromise(uri, undefined, undefined, undefined, cfgCallbackRequestTimeout, undefined, headers);
logger.debug('wopi RenameFile response headers=%j body=%s', postRes.response.headers, postRes.body);
ctx.logger.debug('wopi RenameFile response headers=%j body=%s', postRes.response.headers, postRes.body);
if (postRes.body) {
res = JSON.parse(postRes.body);
} else {
@ -476,22 +491,22 @@ function renameFile(wopiParams, name) {
res = {"Name": name};
}
} else {
logger.info('wopi SupportsRename = false');
ctx.logger.info('wopi SupportsRename = false');
}
} catch (err) {
logger.error('wopi error RenameFile:%s', err.stack);
ctx.logger.error('wopi error RenameFile:%s', err.stack);
} finally {
logger.info('wopi RenameFile end');
ctx.logger.info('wopi RenameFile end');
}
return res;
});
}
function checkFileInfo(uri, access_token, sc) {
function checkFileInfo(ctx, uri, access_token, sc) {
return co(function* () {
let fileInfo;
let fileInfo = undefined;
try {
logger.info('wopi checkFileInfo start');
let filterStatus = yield checkIpFilter(uri);
ctx.logger.info('wopi checkFileInfo start');
let filterStatus = yield checkIpFilter(ctx, uri);
if (0 !== filterStatus) {
return fileInfo;
}
@ -500,23 +515,23 @@ function checkFileInfo(uri, access_token, sc) {
headers['X-WOPI-SessionContext'] = sc;
}
fillStandardHeaders(headers, uri, access_token);
logger.debug('wopi checkFileInfo request uri=%s headers=%j', uri, headers);
let getRes = yield utils.downloadUrlPromise(uri, cfgDownloadTimeout, undefined, undefined, false, headers);
logger.debug(`wopi checkFileInfo headers=%j body=%s`, getRes.response.headers, getRes.body);
ctx.logger.debug('wopi checkFileInfo request uri=%s headers=%j', uri, headers);
let getRes = yield utils.downloadUrlPromise(ctx, uri, cfgDownloadTimeout, undefined, undefined, false, headers);
ctx.logger.debug(`wopi checkFileInfo headers=%j body=%s`, getRes.response.headers, getRes.body);
fileInfo = JSON.parse(getRes.body);
} catch (err) {
logger.error('wopi error checkFileInfo:%s', err.stack);
ctx.logger.error('wopi error checkFileInfo:%s', err.stack);
} finally {
logger.info('wopi checkFileInfo end');
ctx.logger.info('wopi checkFileInfo end');
}
return fileInfo;
});
}
function lock(command, lockId, fileInfo, userAuth) {
function lock(ctx, command, lockId, fileInfo, userAuth) {
return co(function* () {
let res = true;
try {
logger.info('wopi %s start', command);
ctx.logger.info('wopi %s start', command);
if (fileInfo && fileInfo.SupportsLocks) {
if (!userAuth) {
return false;
@ -524,32 +539,32 @@ function lock(command, lockId, fileInfo, userAuth) {
let wopiSrc = userAuth.wopiSrc;
let access_token = userAuth.access_token;
let uri = `${wopiSrc}?access_token=${access_token}`;
let filterStatus = yield checkIpFilter(uri);
let filterStatus = yield checkIpFilter(ctx, uri);
if (0 !== filterStatus) {
return false;
}
let headers = {"X-WOPI-Override": command, "X-WOPI-Lock": lockId};
fillStandardHeaders(headers, uri, access_token);
logger.debug('wopi %s request uri=%s headers=%j', command, uri, headers);
ctx.logger.debug('wopi %s request uri=%s headers=%j', command, uri, headers);
let postRes = yield utils.postRequestPromise(uri, undefined, undefined, undefined, cfgCallbackRequestTimeout, undefined, headers);
logger.debug('wopi %s response headers=%j', command, postRes.response.headers);
ctx.logger.debug('wopi %s response headers=%j', command, postRes.response.headers);
} else {
logger.info('wopi %s SupportsLocks = false', command);
ctx.logger.info('wopi %s SupportsLocks = false', command);
}
} catch (err) {
res = false;
logger.error('wopi error %s:%s', command, err.stack);
ctx.logger.error('wopi error %s:%s', command, err.stack);
} finally {
logger.info('wopi %s end', command);
ctx.logger.info('wopi %s end', command);
}
return res;
});
}
function unlock(wopiParams) {
function unlock(ctx, wopiParams) {
return co(function* () {
try {
logger.info('wopi Unlock start');
ctx.logger.info('wopi Unlock start');
let fileInfo = wopiParams.commonInfo.fileInfo;
if (fileInfo && fileInfo.SupportsLocks) {
if (!wopiParams.userAuth) {
@ -559,23 +574,23 @@ function unlock(wopiParams) {
let lockId = wopiParams.commonInfo.lockId;
let access_token = wopiParams.userAuth.access_token;
let uri = `${wopiSrc}?access_token=${access_token}`;
let filterStatus = yield checkIpFilter(uri);
let filterStatus = yield checkIpFilter(ctx, uri);
if (0 !== filterStatus) {
return;
}
let headers = {"X-WOPI-Override": "UNLOCK", "X-WOPI-Lock": lockId};
fillStandardHeaders(headers, uri, access_token);
logger.debug('wopi Unlock request uri=%s headers=%j', uri, headers);
ctx.logger.debug('wopi Unlock request uri=%s headers=%j', uri, headers);
let postRes = yield utils.postRequestPromise(uri, undefined, undefined, undefined, cfgCallbackRequestTimeout, undefined, headers);
logger.debug('wopi Unlock response headers=%j', postRes.response.headers);
ctx.logger.debug('wopi Unlock response headers=%j', postRes.response.headers);
} else {
logger.info('wopi SupportsLocks = false');
ctx.logger.info('wopi SupportsLocks = false');
}
} catch (err) {
logger.error('wopi error Unlock:%s', err.stack);
ctx.logger.error('wopi error Unlock:%s', err.stack);
} finally {
logger.info('wopi Unlock end');
ctx.logger.info('wopi Unlock end');
}
});
}
@ -625,12 +640,12 @@ function fillStandardHeaders(headers, url, access_token) {
headers['Authorization'] = `Bearer ${access_token}`;
}
function checkIpFilter(uri){
function checkIpFilter(ctx, uri){
return co(function* () {
let urlParsed = new URL(uri);
let filterStatus = yield* utils.checkHostFilter(urlParsed.hostname);
let filterStatus = yield* utils.checkHostFilter(ctx, urlParsed.hostname);
if (0 !== filterStatus) {
logger.warn('wopi checkIpFilter error: url = %s', uri);
ctx.logger.warn('wopi checkIpFilter error: url = %s', uri);
}
return filterStatus;
});

View File

@ -53,6 +53,8 @@ const wopiClient = require('./../../DocService/sources/wopiClient');
var statsDClient = require('./../../Common/sources/statsdclient');
var queueService = require('./../../Common/sources/taskqueueRabbitMQ');
const formatChecker = require('./../../Common/sources/formatchecker');
const operationContext = require('./../../Common/sources/operationContext');
const tenantManager = require('./../../Common/sources/tenantManager');
var cfgDownloadMaxBytes = configConverter.has('maxDownloadBytes') ? configConverter.get('maxDownloadBytes') : 100000000;
var cfgDownloadTimeout = configConverter.has('downloadTimeout') ? configConverter.get('downloadTimeout') : 60;
@ -62,8 +64,6 @@ var cfgFontDir = configConverter.get('fontDir');
var cfgPresentationThemesDir = configConverter.get('presentationThemesDir');
var cfgX2tPath = configConverter.get('x2tPath');
var cfgDocbuilderPath = configConverter.get('docbuilderPath');
var cfgDocbuilderAllFontsPath = configConverter.get('docbuilderAllFontsPath');
var cfgDocbuilderCoreFontsPath = configConverter.get('docbuilderCoreFontsPath');
var cfgArgs = configConverter.get('args');
var cfgSpawnOptions = configConverter.get('spawnOptions');
if (cfgSpawnOptions.env) {
@ -74,6 +74,7 @@ var cfgInputLimits = configConverter.get('inputLimits');
const cfgStreamWriterBufferSize = configConverter.get('streamWriterBufferSize');
//cfgMaxRequestChanges was obtained as a result of the test: 84408 changes - 5,16 MB
const cfgMaxRequestChanges = config.get('services.CoAuthoring.server.maxRequestChanges');
const cfgForgottenFiles = config.get('services.CoAuthoring.server.forgottenfiles');
const cfgForgottenFilesName = config.get('services.CoAuthoring.server.forgottenfilesname');
const cfgNewFileTemplate = config.get('services.CoAuthoring.server.newFileTemplate');
@ -280,7 +281,7 @@ function getTempDir() {
fs.mkdirSync(resultDir);
return {temp: newTemp, source: sourceDir, result: resultDir};
}
function* replaceEmptyFile(docId, fileFrom, ext, _lcid) {
function* replaceEmptyFile(ctx, fileFrom, ext, _lcid) {
if (!fs.existsSync(fileFrom) || 0 === fs.lstatSync(fileFrom).size) {
let locale = 'en-US';
if (_lcid) {
@ -290,11 +291,11 @@ function* replaceEmptyFile(docId, fileFrom, ext, _lcid) {
if (fs.existsSync(path.join(cfgNewFileTemplate, localeNew))) {
locale = localeNew;
} else {
logger.debug('replaceEmptyFile empty locale dir locale=%s (id=%s)', localeNew, docId);
ctx.logger.debug('replaceEmptyFile empty locale dir locale=%s', localeNew);
}
}
}
logger.debug('replaceEmptyFile format=%s locale=%s (id=%s)', ext, locale, docId);
ctx.logger.debug('replaceEmptyFile format=%s locale=%s', ext, locale);
let format = formatChecker.getFormatFromString(ext);
if (formatChecker.isDocumentFormat(format)) {
fs.copyFileSync(path.join(cfgNewFileTemplate, locale, 'new.docx'), fileFrom);
@ -305,25 +306,26 @@ function* replaceEmptyFile(docId, fileFrom, ext, _lcid) {
}
}
}
function* downloadFile(docId, uri, fileFrom, withAuthorization, filterPrivate, opt_headers) {
function* downloadFile(ctx, uri, fileFrom, withAuthorization, filterPrivate, opt_headers) {
var res = constants.CONVERT_DOWNLOAD;
var data = null;
var downloadAttemptCount = 0;
var urlParsed = url.parse(uri);
var filterStatus = yield* utils.checkHostFilter(urlParsed.hostname);
var filterStatus = yield* utils.checkHostFilter(ctx, urlParsed.hostname);
if (0 == filterStatus) {
while (constants.NO_ERROR !== res && downloadAttemptCount++ < cfgDownloadAttemptMaxCount) {
try {
let authorization;
if (utils.canIncludeOutboxAuthorization(uri) && withAuthorization) {
authorization = utils.fillJwtForRequest({url: uri}, false);
if (utils.canIncludeOutboxAuthorization(ctx, uri) && withAuthorization) {
let secret = yield tenantManager.getTenantSecret(ctx, commonDefines.c_oAscSecretType.Outbox);
authorization = utils.fillJwtForRequest({url: uri}, secret, false);
}
let getRes = yield utils.downloadUrlPromise(uri, cfgDownloadTimeout, cfgDownloadMaxBytes, authorization, filterPrivate, opt_headers);
let getRes = yield utils.downloadUrlPromise(ctx, uri, cfgDownloadTimeout, cfgDownloadMaxBytes, authorization, filterPrivate, opt_headers);
data = getRes.body;
res = constants.NO_ERROR;
} catch (err) {
res = constants.CONVERT_DOWNLOAD;
logger.error('error downloadFile:url=%s;attempt=%d;code:%s;connect:%s;(id=%s)\r\n%s', uri, downloadAttemptCount, err.code, err.connect, docId, err.stack);
ctx.logger.error('error downloadFile:url=%s;attempt=%d;code:%s;connect:%s %s', uri, downloadAttemptCount, err.code, err.connect, err.stack);
//not continue attempts if timeout
if (err.code === 'ETIMEDOUT' || err.code === 'ESOCKETTIMEDOUT') {
break;
@ -336,18 +338,18 @@ function* downloadFile(docId, uri, fileFrom, withAuthorization, filterPrivate, o
}
}
if (constants.NO_ERROR === res) {
logger.debug('downloadFile complete filesize=%d (id=%s)', data.length, docId);
ctx.logger.debug('downloadFile complete filesize=%d', data.length);
fs.writeFileSync(fileFrom, data);
}
} else {
logger.error('checkIpFilter error:url=%s;code:%s;(id=%s)', uri, filterStatus, docId);
ctx.logger.error('checkIpFilter error:url=%s;code:%s;', uri, filterStatus);
res = constants.CONVERT_DOWNLOAD;
}
return res;
}
function* downloadFileFromStorage(id, strPath, dir) {
var list = yield storage.listObjects(strPath);
logger.debug('downloadFileFromStorage list %s (id=%s)', list.toString(), id);
function* downloadFileFromStorage(ctx, strPath, dir, opt_specialDir) {
var list = yield storage.listObjects(ctx, strPath, opt_specialDir);
ctx.logger.debug('downloadFileFromStorage list %s', list.toString());
//create dirs
var dirsToCreate = [];
var dirStruct = {};
@ -373,36 +375,49 @@ function* downloadFileFromStorage(id, strPath, dir) {
for (var i = 0; i < list.length; ++i) {
var file = list[i];
var fileRel = storage.getRelativePath(strPath, file);
var data = yield storage.getObject(file);
var data = yield storage.getObject(ctx, file, opt_specialDir);
fs.writeFileSync(path.join(dir, fileRel), data);
}
}
function* processDownloadFromStorage(dataConvert, cmd, task, tempDirs, authorProps) {
function* processDownloadFromStorage(ctx, dataConvert, cmd, task, tempDirs, authorProps) {
let res = constants.NO_ERROR;
let needConcatFiles = false;
if (task.getFromOrigin() || task.getFromSettings()) {
dataConvert.fileFrom = path.join(tempDirs.source, 'origin.' + cmd.getFormat());
} else {
//перезаписываем некоторые файлы из m_sKey(например Editor.bin или changes)
yield* downloadFileFromStorage(cmd.getSaveKey(), cmd.getSaveKey(), tempDirs.source);
yield* downloadFileFromStorage(ctx, cmd.getSaveKey(), tempDirs.source);
let format = cmd.getFormat() || 'bin';
dataConvert.fileFrom = path.join(tempDirs.source, 'Editor.' + format);
needConcatFiles = true;
}
if (!utils.checkPathTraversal(dataConvert.key, tempDirs.source, dataConvert.fileFrom)) {
if (!utils.checkPathTraversal(ctx, dataConvert.key, tempDirs.source, dataConvert.fileFrom)) {
return constants.CONVERT_PARAMS;
}
//mail merge
let mailMergeSend = cmd.getMailMergeSend();
if (mailMergeSend) {
yield* downloadFileFromStorage(mailMergeSend.getJsonKey(), mailMergeSend.getJsonKey(), tempDirs.source);
yield* downloadFileFromStorage(ctx, mailMergeSend.getJsonKey(), tempDirs.source);
needConcatFiles = true;
}
if (needConcatFiles) {
yield* concatFiles(tempDirs.source);
}
if (task.getFromChanges()) {
res = yield* processChanges(tempDirs, cmd, authorProps);
res = yield* processChanges(ctx, tempDirs, cmd, authorProps);
}
//todo rework
if (!fs.existsSync(dataConvert.fileFrom)) {
if (fs.existsSync(path.join(tempDirs.source, 'origin.docx'))) {
dataConvert.fileFrom = path.join(tempDirs.source, 'origin.docx');
} else if (fs.existsSync(path.join(tempDirs.source, 'origin.xlsx'))) {
dataConvert.fileFrom = path.join(tempDirs.source, 'origin.xlsx');
} else if (fs.existsSync(path.join(tempDirs.source, 'origin.pptx'))) {
dataConvert.fileFrom = path.join(tempDirs.source, 'origin.pptx');
}
let fileFromNew = path.join(path.dirname(dataConvert.fileFrom), "Editor.bin");
fs.renameSync(dataConvert.fileFrom, fileFromNew);
dataConvert.fileFrom = fileFromNew;
}
return res;
}
@ -432,7 +447,7 @@ function* concatFiles(source) {
}
}
function* processChanges(tempDirs, cmd, authorProps) {
function* processChanges(ctx, tempDirs, cmd, authorProps) {
let res = constants.NO_ERROR;
let changesDir = path.join(tempDirs.source, constants.CHANGES_NAME);
fs.mkdirSync(changesDir);
@ -461,13 +476,13 @@ function* processChanges(tempDirs, cmd, authorProps) {
}];
}
let streamObj = yield* streamCreate(cmd.getDocId(), changesDir, indexFile++, {highWaterMark: cfgStreamWriterBufferSize});
let streamObj = yield* streamCreate(ctx, changesDir, indexFile++, {highWaterMark: cfgStreamWriterBufferSize});
let curIndexStart = 0;
let curIndexEnd = Math.min(curIndexStart + cfgMaxRequestChanges, forceSaveIndex);
while (curIndexStart < curIndexEnd || extChanges) {
let changes = [];
if (curIndexStart < curIndexEnd) {
changes = yield baseConnector.getChangesPromise(cmd.getDocId(), curIndexStart, curIndexEnd, forceSaveTime);
changes = yield baseConnector.getChangesPromise(ctx, cmd.getDocId(), curIndexStart, curIndexEnd, forceSaveTime);
}
if (0 === changes.length && extChanges) {
changes = extChanges;
@ -476,7 +491,7 @@ function* processChanges(tempDirs, cmd, authorProps) {
for (let i = 0; i < changes.length; ++i) {
let change = changes[i];
if (change.change_data.startsWith('ENCRYPTED;')) {
logger.warn('processChanges encrypted changes (id=%s)', cmd.getDocId());
ctx.logger.warn('processChanges encrypted changes');
//todo sql request instead?
res = constants.EDITOR_CHANGES;
break;
@ -484,7 +499,7 @@ function* processChanges(tempDirs, cmd, authorProps) {
if (null === changesAuthor || changesAuthor !== change.user_id_original) {
if (null !== changesAuthor) {
yield* streamEnd(streamObj, ']');
streamObj = yield* streamCreate(cmd.getDocId(), changesDir, indexFile++);
streamObj = yield* streamCreate(ctx, changesDir, indexFile++);
}
let strDate = baseConnector.getDateTime(change.change_date);
changesHistory.changes.push({'created': strDate, 'user': {'id': change.user_id_original, 'name': change.user_name}});
@ -526,13 +541,13 @@ function* processChanges(tempDirs, cmd, authorProps) {
return res;
}
function* streamCreate(docId, changesDir, indexFile, opt_options) {
function* streamCreate(ctx, changesDir, indexFile, opt_options) {
let fileName = constants.CHANGES_NAME + indexFile + '.json';
let filePath = path.join(changesDir, fileName);
let writeStream = yield utils.promiseCreateWriteStream(filePath, opt_options);
writeStream.on('error', function(err) {
//todo integrate error handle in main thread (probable: set flag here and check it in main thread)
logger.error('WriteStreamError (id=%s)\r\n%s', docId, err.stack);
ctx.logger.error('WriteStreamError %s', err.stack);
});
return {writeStream: writeStream, filePath: filePath, isNoChangesInFile: true};
}
@ -547,41 +562,41 @@ function* streamEnd(streamObj, text) {
streamObj.writeStream.end(text, 'utf8');
yield utils.promiseWaitClose(streamObj.writeStream);
}
function* processUploadToStorage(dir, storagePath) {
function* processUploadToStorage(ctx, dir, storagePath) {
var list = yield utils.listObjects(dir);
if (list.length < MAX_OPEN_FILES) {
yield* processUploadToStorageChunk(list, dir, storagePath);
yield* processUploadToStorageChunk(ctx, list, dir, storagePath);
} else {
for (var i = 0, j = list.length; i < j; i += MAX_OPEN_FILES) {
yield* processUploadToStorageChunk(list.slice(i, i + MAX_OPEN_FILES), dir, storagePath);
yield* processUploadToStorageChunk(ctx, list.slice(i, i + MAX_OPEN_FILES), dir, storagePath);
}
}
}
function* processUploadToStorageChunk(list, dir, storagePath) {
function* processUploadToStorageChunk(ctx, list, dir, storagePath) {
yield Promise.all(list.map(function (curValue) {
let localValue = storagePath + '/' + curValue.substring(dir.length + 1);
return storage.uploadObject(localValue, curValue);
return storage.uploadObject(ctx, localValue, curValue);
}));
}
function writeProcessOutputToLog(docId, childRes, isDebug) {
function writeProcessOutputToLog(ctx, childRes, isDebug) {
if (childRes) {
if (undefined !== childRes.stdout) {
if (isDebug) {
logger.debug('stdout (id=%s):%s', docId, childRes.stdout);
ctx.logger.debug('stdout:%s', childRes.stdout);
} else {
logger.error('stdout (id=%s):%s', docId, childRes.stdout);
ctx.logger.error('stdout:%s', childRes.stdout);
}
}
if (undefined !== childRes.stderr) {
if (isDebug) {
logger.debug('stderr (id=%s):%s', docId, childRes.stderr);
ctx.logger.debug('stderr:%s', childRes.stderr);
} else {
logger.error('stderr (id=%s):%s', docId, childRes.stderr);
ctx.logger.error('stderr:%s', childRes.stderr);
}
}
}
}
function* postProcess(cmd, dataConvert, tempDirs, childRes, error, isTimeout) {
function* postProcess(ctx, cmd, dataConvert, tempDirs, childRes, error, isTimeout) {
var exitCode = 0;
var exitSignal = null;
if(childRes) {
@ -597,23 +612,23 @@ function* postProcess(cmd, dataConvert, tempDirs, childRes, error, isTimeout) {
error = constants.CONVERT;
}
if (-1 !== exitCodesMinorError.indexOf(error)) {
writeProcessOutputToLog(dataConvert.key, childRes, true);
logger.debug('ExitCode (code=%d;signal=%s;error:%d;id=%s)', exitCode, exitSignal, error, dataConvert.key);
writeProcessOutputToLog(ctx, childRes, true);
ctx.logger.debug('ExitCode (code=%d;signal=%s;error:%d)', exitCode, exitSignal, error);
} else {
writeProcessOutputToLog(dataConvert.key, childRes, false);
logger.error('ExitCode (code=%d;signal=%s;error:%d;id=%s)', exitCode, exitSignal, error, dataConvert.key);
writeProcessOutputToLog(ctx, childRes, false);
ctx.logger.error('ExitCode (code=%d;signal=%s;error:%d)', exitCode, exitSignal, error);
if (cfgErrorFiles) {
yield* processUploadToStorage(tempDirs.temp, cfgErrorFiles + '/' + dataConvert.key);
logger.debug('processUploadToStorage error complete(id=%s)', dataConvert.key);
yield* processUploadToStorage(ctx, tempDirs.temp, dataConvert.key, cfgErrorFiles);
ctx.logger.debug('processUploadToStorage error complete(id=%s)', dataConvert.key);
}
}
} else {
writeProcessOutputToLog(dataConvert.key, childRes, true);
logger.debug('ExitCode (code=%d;signal=%s;error:%d;id=%s)', exitCode, exitSignal, error, dataConvert.key);
writeProcessOutputToLog(ctx, childRes, true);
ctx.logger.debug('ExitCode (code=%d;signal=%s;error:%d)', exitCode, exitSignal, error);
}
if (-1 !== exitCodesUpload.indexOf(error)) {
yield* processUploadToStorage(tempDirs.result, dataConvert.key);
logger.debug('processUploadToStorage complete(id=%s)', dataConvert.key);
yield* processUploadToStorage(ctx, tempDirs.result, dataConvert.key);
ctx.logger.debug('processUploadToStorage complete');
}
cmd.setStatusInfo(error);
var existFile = false;
@ -640,27 +655,77 @@ function* postProcess(cmd, dataConvert, tempDirs, childRes, error, isTimeout) {
cmd.setTitle(cmd.getOutputPath());
}
var res = new commonDefines.TaskQueueData();
res.setCmd(cmd);
logger.debug('output (data=%s;id=%s)', JSON.stringify(res), dataConvert.key);
return res;
}
function deleteFolderRecursive(strPath) {
if (fs.existsSync(strPath)) {
var files = fs.readdirSync(strPath);
files.forEach(function(file) {
var curPath = path.join(strPath, file);
if (fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(strPath);
}
var queueData = new commonDefines.TaskQueueData();
queueData.setCtx(ctx);
queueData.setCmd(cmd);
ctx.logger.debug('output (data=%j)', queueData);
return queueData;
}
function* ExecuteTask(task) {
function* spawnProcess(ctx, isBuilder, tempDirs, dataConvert, authorProps, getTaskTime, task) {
let childRes, isTimeout = false;
let childArgs;
if (cfgArgs.length > 0) {
childArgs = cfgArgs.trim().replace(/ +/g, ' ').split(' ');
} else {
childArgs = [];
}
let processPath;
if (!isBuilder) {
processPath = cfgX2tPath;
let paramsFile = path.join(tempDirs.temp, 'params.xml');
dataConvert.serialize(paramsFile);
childArgs.push(paramsFile);
let hiddenXml = yield dataConvert.serializeHidden();
if (hiddenXml) {
childArgs.push(hiddenXml);
}
} else {
fs.mkdirSync(path.join(tempDirs.result, 'output'));
processPath = cfgDocbuilderPath;
childArgs.push('--check-fonts=0');
childArgs.push('--save-use-only-names=' + tempDirs.result + '/output');
childArgs.push(dataConvert.fileFrom);
}
let timeoutId;
try {
let spawnOptions = cfgSpawnOptions;
if (authorProps.lastModifiedBy && authorProps.modified) {
//copy to avoid modification of global cfgSpawnOptions
spawnOptions = Object.assign({}, cfgSpawnOptions);
spawnOptions.env = Object.assign({}, spawnOptions.env || process.env);
spawnOptions.env['LAST_MODIFIED_BY'] = authorProps.lastModifiedBy;
spawnOptions.env['MODIFIED'] = authorProps.modified;
}
let spawnAsyncPromise = spawnAsync(processPath, childArgs, spawnOptions);
childRes = spawnAsyncPromise.child;
let waitMS = task.getVisibilityTimeout() * 1000 - (new Date().getTime() - getTaskTime.getTime());
timeoutId = setTimeout(function() {
isTimeout = true;
timeoutId = undefined;
//close stdio streams to enable emit 'close' event even if HtmlFileInternal is hung-up
childRes.stdin.end();
childRes.stdout.destroy();
childRes.stderr.destroy();
childRes.kill();
}, waitMS);
childRes = yield spawnAsyncPromise;
} catch (err) {
if (null === err.status) {
ctx.logger.error('error spawnAsync %s', err.stack);
} else {
ctx.logger.debug('error spawnAsync %s', err.stack);
}
childRes = err;
}
if (undefined !== timeoutId) {
clearTimeout(timeoutId);
}
return {childRes: childRes, isTimeout: isTimeout};
}
function* ExecuteTask(ctx, task) {
var startDate = null;
var curDate = null;
if(clientStatsD) {
@ -671,7 +736,7 @@ function* ExecuteTask(task) {
var getTaskTime = new Date();
var cmd = task.getCmd();
var dataConvert = new TaskQueueDataConvert(task);
logger.debug('Start Task(id=%s)', dataConvert.key);
ctx.logger.info('Start Task');
var error = constants.NO_ERROR;
tempDirs = getTempDir();
let fileTo = task.getToFile();
@ -681,7 +746,7 @@ function* ExecuteTask(task) {
if (cmd.getUrl()) {
let format = cmd.getFormat();
dataConvert.fileFrom = path.join(tempDirs.source, dataConvert.key + '.' + format);
if (utils.checkPathTraversal(dataConvert.key, tempDirs.source, dataConvert.fileFrom)) {
if (utils.checkPathTraversal(ctx, dataConvert.key, tempDirs.source, dataConvert.fileFrom)) {
let url = cmd.getUrl();
let withAuthorization = cmd.getWithAuthorization();
let filterPrivate = !withAuthorization;
@ -703,13 +768,13 @@ function* ExecuteTask(task) {
headers = {'X-WOPI-MaxExpectedSize': cfgDownloadMaxBytes, 'X-WOPI-ItemVersion': fileInfo.Version};
wopiClient.fillStandardHeaders(headers, url, userAuth.access_token);
}
logger.debug('wopi url=%s; headers=%j(id=%s)', url, headers, dataConvert.key);
ctx.logger.debug('wopi url=%s; headers=%j', url, headers);
}
if (undefined === fileSize || fileSize > 0) {
error = yield* downloadFile(dataConvert.key, url, dataConvert.fileFrom, withAuthorization, filterPrivate, headers);
error = yield* downloadFile(ctx, url, dataConvert.fileFrom, withAuthorization, filterPrivate, headers);
}
if (constants.NO_ERROR === error) {
yield* replaceEmptyFile(dataConvert.key, dataConvert.fileFrom, format, cmd.getLCID());
yield* replaceEmptyFile(ctx, dataConvert.fileFrom, format, cmd.getLCID());
}
if(clientStatsD) {
clientStatsD.timing('conv.downloadFile', new Date() - curDate);
@ -719,16 +784,16 @@ function* ExecuteTask(task) {
error = constants.CONVERT_PARAMS;
}
} else if (cmd.getSaveKey()) {
yield* downloadFileFromStorage(cmd.getDocId(), cmd.getDocId(), tempDirs.source);
logger.debug('downloadFileFromStorage complete(id=%s)', dataConvert.key);
yield* downloadFileFromStorage(ctx, cmd.getDocId(), tempDirs.source);
ctx.logger.debug('downloadFileFromStorage complete');
if(clientStatsD) {
clientStatsD.timing('conv.downloadFileFromStorage', new Date() - curDate);
curDate = new Date();
}
error = yield* processDownloadFromStorage(dataConvert, cmd, task, tempDirs, authorProps);
error = yield* processDownloadFromStorage(ctx, dataConvert, cmd, task, tempDirs, authorProps);
} else if (cmd.getForgotten()) {
yield* downloadFileFromStorage(cmd.getDocId(), cmd.getForgotten(), tempDirs.source);
logger.debug('downloadFileFromStorage complete(id=%s)', dataConvert.key);
yield* downloadFileFromStorage(ctx, cmd.getForgotten(), tempDirs.source, cfgForgottenFiles);
ctx.logger.debug('downloadFileFromStorage complete');
let list = yield utils.listObjects(tempDirs.source, false);
if (list.length > 0) {
dataConvert.fileFrom = list[0];
@ -740,8 +805,8 @@ function* ExecuteTask(task) {
}
} else if (isBuilder) {
//in cause script in POST body
yield* downloadFileFromStorage(cmd.getDocId(), cmd.getDocId(), tempDirs.source);
logger.debug('downloadFileFromStorage complete(id=%s)', dataConvert.key);
yield* downloadFileFromStorage(ctx, cmd.getDocId(), tempDirs.source);
ctx.logger.debug('downloadFileFromStorage complete');
let list = yield utils.listObjects(tempDirs.source, false);
if (list.length > 0) {
dataConvert.fileFrom = list[0];
@ -749,86 +814,34 @@ function* ExecuteTask(task) {
} else {
error = constants.UNKNOWN;
}
var childRes = null;
let childRes = null;
let isTimeout = false;
if (constants.NO_ERROR === error) {
if(constants.AVS_OFFICESTUDIO_FILE_OTHER_HTMLZIP === dataConvert.formatTo && cmd.getSaveKey() && !dataConvert.mailMergeSend) {
//todo заглушка.вся конвертация на клиенте, но нет простого механизма сохранения на клиенте
yield utils.pipeFiles(dataConvert.fileFrom, dataConvert.fileTo);
} else {
var childArgs;
if (cfgArgs.length > 0) {
childArgs = cfgArgs.trim().replace(/ +/g, ' ').split(' ');
} else {
childArgs = [];
}
let processPath;
if (!isBuilder) {
processPath = cfgX2tPath;
let paramsFile = path.join(tempDirs.temp, 'params.xml');
dataConvert.serialize(paramsFile);
childArgs.push(paramsFile);
let hiddenXml = yield dataConvert.serializeHidden();
if (hiddenXml) {
childArgs.push(hiddenXml);
}
} else {
fs.mkdirSync(path.join(tempDirs.result, 'output'));
processPath = cfgDocbuilderPath;
childArgs.push('--all-fonts-path=' + cfgDocbuilderAllFontsPath);
if (cfgDocbuilderCoreFontsPath) {
childArgs.push('--fonts-dir=' + cfgDocbuilderCoreFontsPath);
}
childArgs.push('--save-use-only-names=' + tempDirs.result + '/output');
childArgs.push(dataConvert.fileFrom);
}
let timeoutId;
try {
let spawnOptions = cfgSpawnOptions;
if (authorProps.lastModifiedBy && authorProps.modified) {
//copy to avoid modification of global cfgSpawnOptions
spawnOptions = Object.assign({}, cfgSpawnOptions);
spawnOptions.env = Object.assign({}, spawnOptions.env || process.env);
spawnOptions.env['LAST_MODIFIED_BY'] = authorProps.lastModifiedBy;
spawnOptions.env['MODIFIED'] = authorProps.modified;
}
let spawnAsyncPromise = spawnAsync(processPath, childArgs, spawnOptions);
childRes = spawnAsyncPromise.child;
let waitMS = task.getVisibilityTimeout() * 1000 - (new Date().getTime() - getTaskTime.getTime());
timeoutId = setTimeout(function() {
isTimeout = true;
timeoutId = undefined;
//close stdio streams to enable emit 'close' event even if HtmlFileInternal is hung-up
childRes.stdin.end();
childRes.stdout.destroy();
childRes.stderr.destroy();
childRes.kill();
}, waitMS);
childRes = yield spawnAsyncPromise;
} catch (err) {
let fLog = null === err.status ? logger.error : logger.debug;
fLog.call(logger, 'error spawnAsync(id=%s)\r\n%s', cmd.getDocId(), err.stack);
childRes = err;
}
if (undefined !== timeoutId) {
clearTimeout(timeoutId);
}
({childRes, isTimeout} = yield* spawnProcess(ctx, isBuilder, tempDirs, dataConvert, authorProps, getTaskTime, task));
if (childRes && 0 !== childRes.status && !isTimeout && task.getFromChanges()
&& constants.AVS_OFFICESTUDIO_FILE_OTHER_OOXML !== dataConvert.formatTo
&& !formatChecker.isOOXFormat(dataConvert.formatTo) && !cmd.getWopiParams()) {
ctx.logger.warn('rollback to save changes to ooxml. See assemblyFormatAsOrigin param. formatTo=%s', formatChecker.getStringFromFormat(dataConvert.formatTo));
let extOld = path.extname(dataConvert.fileTo);
let extNew = '.' + formatChecker.getStringFromFormat(constants.AVS_OFFICESTUDIO_FILE_OTHER_OOXML);
dataConvert.formatTo = constants.AVS_OFFICESTUDIO_FILE_OTHER_OOXML;
dataConvert.fileTo = dataConvert.fileTo.slice(0, -extOld.length) + extNew;
({childRes, isTimeout} = yield* spawnProcess(ctx, isBuilder, tempDirs, dataConvert, authorProps, getTaskTime, task));
}
if(clientStatsD) {
clientStatsD.timing('conv.spawnSync', new Date() - curDate);
curDate = new Date();
}
}
resData = yield* postProcess(cmd, dataConvert, tempDirs, childRes, error, isTimeout);
logger.debug('postProcess (id=%s)', dataConvert.key);
resData = yield* postProcess(ctx, cmd, dataConvert, tempDirs, childRes, error, isTimeout);
ctx.logger.debug('postProcess');
if(clientStatsD) {
clientStatsD.timing('conv.postProcess', new Date() - curDate);
curDate = new Date();
}
if (tempDirs) {
deleteFolderRecursive(tempDirs.temp);
logger.debug('deleteFolderRecursive (id=%s)', dataConvert.key);
fs.rmSync(tempDirs.temp, { recursive: true, force: true });
ctx.logger.debug('deleteFolderRecursive');
if(clientStatsD) {
clientStatsD.timing('conv.deleteFolderRecursive', new Date() - curDate);
curDate = new Date();
@ -837,6 +850,7 @@ function* ExecuteTask(task) {
if(clientStatsD) {
clientStatsD.timing('conv.allconvert', new Date() - startDate);
}
ctx.logger.info('End Task');
return resData;
}
@ -844,13 +858,15 @@ function receiveTask(data, ack) {
return co(function* () {
var res = null;
var task = null;
let ctx = new operationContext.Context();
try {
task = new commonDefines.TaskQueueData(JSON.parse(data));
if (task) {
res = yield* ExecuteTask(task);
ctx.initFromTaskQueueData(task);
res = yield* ExecuteTask(ctx, task);
}
} catch (err) {
logger.error(err);
ctx.logger.error(err);
} finally {
try {
if (!res && task) {
@ -858,13 +874,14 @@ function receiveTask(data, ack) {
var cmd = task.getCmd();
cmd.setStatusInfo(constants.CONVERT);
res = new commonDefines.TaskQueueData();
res.setCtx(ctx);
res.setCmd(cmd);
}
if (res) {
yield queue.addResponse(res);
}
} catch (err) {
logger.error(err);
ctx.logger.error(err);
} finally {
ack();
}
@ -873,10 +890,13 @@ function receiveTask(data, ack) {
}
function simulateErrorResponse(data){
let task = new commonDefines.TaskQueueData(JSON.parse(data));
let ctx = new operationContext.Context();
ctx.initFromTaskQueueData(task);
//simulate error response
let cmd = task.getCmd();
cmd.setStatusInfo(constants.CONVERT);
let res = new commonDefines.TaskQueueData();
task.setCtx(ctx);
res.setCmd(cmd);
return res;
}
@ -885,7 +905,7 @@ function run() {
queue.on('task', receiveTask);
queue.init(true, true, true, false, false, false, function(err) {
if (null != err) {
logger.error('createTaskQueue error :\r\n%s', err.stack);
operationContext.global.logger.error('createTaskQueue error: %s', err.stack);
}
});
}

View File

@ -34,6 +34,7 @@
const cluster = require('cluster');
const logger = require('./../../Common/sources/logger');
const operationContext = require('./../../Common/sources/operationContext');
if (cluster.isMaster) {
const fs = require('fs');
@ -42,12 +43,18 @@ if (cluster.isMaster) {
const configCommon = require('config');
const config = configCommon.get('FileConverter.converter');
const license = require('./../../Common/sources/license');
const tenantManager = require('./../../Common/sources/tenantManager');
const cfgLicenseFile = configCommon.get('license.license_file');
const cfgMaxProcessCount = config.get('maxprocesscount');
var licenseInfo, workersCount = 0;
var workersCount = 0;
const readLicense = function* () {
[licenseInfo] = yield* license.readLicense();
workersCount = Math.min(licenseInfo.count, Math.ceil(numCPUs * cfgMaxProcessCount));
workersCount = Math.ceil(numCPUs * cfgMaxProcessCount);
if (!tenantManager.isMultitenantMode()) {
let [licenseInfo] = yield* license.readLicense(cfgLicenseFile);
workersCount = Math.min(licenseInfo.count, workersCount);
}
};
const updateWorkers = () => {
var i;
@ -55,7 +62,7 @@ if (cluster.isMaster) {
if (arrKeyWorkers.length < workersCount) {
for (i = arrKeyWorkers.length; i < workersCount; ++i) {
const newWorker = cluster.fork();
logger.warn('worker %s started.', newWorker.process.pid);
operationContext.global.logger.warn('worker %s started.', newWorker.process.pid);
}
} else {
for (i = workersCount; i < arrKeyWorkers.length; ++i) {
@ -70,31 +77,33 @@ if (cluster.isMaster) {
return co(function*() {
try {
yield* readLicense();
logger.warn('update cluster with %s workers', workersCount);
operationContext.global.logger.warn('update cluster with %s workers', workersCount);
updateWorkers();
} catch (err) {
logger.error('updateLicense error:\r\n%s', err.stack);
operationContext.global.logger.error('updateLicense error: %s', err.stack);
}
});
};
cluster.on('exit', (worker, code, signal) => {
logger.warn('worker %s died (code = %s; signal = %s).', worker.process.pid, code, signal);
operationContext.global.logger.warn('worker %s died (code = %s; signal = %s).', worker.process.pid, code, signal);
updateWorkers();
});
updateLicense();
fs.watchFile(configCommon.get('license').get('license_file'), updateLicense);
setInterval(updateLicense, 86400000);
if (!tenantManager.isMultitenantMode()) {
fs.watchFile(cfgLicenseFile, updateLicense);
setInterval(updateLicense, 86400000);
}
} else {
const converter = require('./converter');
converter.run();
}
process.on('uncaughtException', (err) => {
logger.error((new Date).toUTCString() + ' uncaughtException:', err.message);
logger.error(err.stack);
operationContext.global.logger.error((new Date).toUTCString() + ' uncaughtException:', err.message);
operationContext.global.logger.error(err.stack);
logger.shutdown(() => {
process.exit(1);
});

View File

@ -31,6 +31,7 @@
min-width: 600px;
width: 100%;
padding-top: 4px;
flex-shrink: 0;
}
header img {
@ -40,7 +41,7 @@
table {
table-layout: fixed;
border-spacing: 0;
margin-bottom: 30px;
margin-bottom: 25px;
}
td {
@ -54,6 +55,10 @@
padding-bottom: 4px;
}
.td-caption-main:last-child {
width: 208px;
}
.td-value-main {
font-size: 32px;
line-height: 28px;
@ -63,25 +68,56 @@
.td-caption {
font-size: 16px;
padding-bottom: 4px;
background: #EFEFEF;
border-radius: 1px;
}
.td-caption-small {
font-size: 12px;
padding-bottom: 4px;
font-weight: 600;
}
.td-value {
font-size: 26px;
line-height: 28px;
padding-bottom: 8px;
width: 150px;
}
.td-value:last-child {
width: 224px;
}
.td-separator {
padding-left: 0;
padding-right: 24px;
}
.td-separator:not(:last-child) {
padding-right: 20px;
}
.td-separator-vert {
padding: 0 10px;
}
.td-last {
padding-bottom: 30px;
padding-bottom: 15px;
}
.td-link {
padding: 0;
font-size: 14px;
cursor: pointer;
}
.td-link.current {
font-weight: 700;
}
.main-panel {
margin: 40px auto 16px;
padding-left: calc(100vw - 100%);
width: 672px;
}
@ -98,6 +134,7 @@
font-size: 16px;
font-weight: 600;
padding-bottom: 25px;
text-align: center;
}
#doc-server-wait {
@ -142,6 +179,13 @@
border-top: 1px solid #dadada;
}
.separator-vert {
display: inline;
width: 0;
height: 100%;
border-left: 1px dotted #333333;
}
</style>
</head>
<body>
@ -167,98 +211,40 @@
<tr>
<td id="build-type">Type:</td>
<td><span id="lic-valid-type">Valid: </span><span id="lic-valid"></span></td>
<td rowspan="3" id="lic-limit" class="td-value-main"></td>
<td id="lic-limit-edit"></td>
</tr>
<tr>
<td id="build-version">Version:</td>
<td id="trial"></td>
<td id="lic-limit-view"></td>
</tr>
<tr>
<td id="build-date">Release date:</td>
<td></td>
<td></td>
</tr>
</table>
<table style="margin-left: 15px;">
<tr>
<td class="td-link" value="all">All</td>
<td class="td-separator-vert"><div class="separator-vert"></div></td>
<td class="td-link" value="edit">Editors</td>
<td class="td-separator-vert"><div class="separator-vert"></div></td>
<td class="td-link" value="view">Live Viewer</td>
</tr>
<tr>
<td class="td-separator" colspan="5"></td>
</tr>
</table>
<table id="user-activity-info" class="hidden">
<tr>
<td colspan="4" class="td-caption" id="user-activity-info-caption">User activity in the last 10 days</td>
</tr>
<tr>
<td class="td-separator" colspan="4"><div class="separator"></div></td>
</tr>
<tr>
<td id="cell-use-up" class="td-value" width="150">0</td>
<td id="cell-internal" class="td-value" width="150">0</td>
<td id="cell-external" class="td-value" width="150">0</td>
<td id="cell-left" class="td-value" width="224">0</td>
</tr>
<tr>
<td>Use up</td>
<td>Internal</td>
<td>External</td>
<td>Left</td>
</tr>
</table>
<table id="connection-activity-info" class="hidden">
<tr>
<td colspan="4" class="td-caption">Current connections</td>
</tr>
<tr>
<td class="td-separator" colspan="4"><div class="separator"></div></td>
</tr>
<tr>
<td id="cell-conn-use-up" class="td-value" width="150">0</td>
<td id="cell-conn-left" class="td-value" width="150">0</td>
<td class="td-value" width="150"></td>
<td class="td-value" width="224"></td>
</tr>
<tr>
<td>Use up</td>
<td>Left</td>
<td></td>
<td></td>
</tr>
</table>
<table id="connections-peaks" class="hidden">
<tr>
<td colspan="4" class="td-caption">Peaks</td>
</tr>
<tr>
<td class="td-separator" colspan="4"><div class="separator"></div></td>
</tr>
<tr>
<td id="cell-hour-max" class="td-value" width="150">0</td>
<td id="cell-day-max" class="td-value" width="150">0</td>
<td id="cell-week-max" class="td-value" width="150">0</td>
<td id="cell-month-max" class="td-value" width="224">0</td>
</tr>
<tr>
<td>Last Hour</td>
<td>24 Hours</td>
<td>Week</td>
<td>Month</td>
</tr>
</table>
<table id="connections-average" class="hidden">
<tr>
<td colspan="4" class="td-caption">Average</td>
</tr>
<tr>
<td class="td-separator" colspan="4"><div class="separator"></div></td>
</tr>
<tr>
<td id="cell-hour-avr" class="td-value" width="150">0</td>
<td id="cell-day-avr" class="td-value" width="150">0</td>
<td id="cell-week-avr" class="td-value" width="150">0</td>
<td id="cell-month-avr" class="td-value" width="224">0</td>
</tr>
<tr>
<td>Last Hour</td>
<td>24 Hours</td>
<td>Week</td>
<td>Month</td>
</tr>
</table>
<div id="user-statistics-caption" class="header2 hidden">Usage statistics for the reporting period:</div>
<div id="user-statistics-caption" class="header2 hidden">Usage statistics for the reporting period</div>
<table id="user-statistics" class="hidden">
</table>
</div>
@ -307,8 +293,12 @@
elem = document.getElementById('limit-type');
elem.innerText = (licenseInfo.usersCount>0) ? 'Users limit' : 'Connections limit' ;
elem = document.getElementById('lic-limit');
elem.innerText = (licenseInfo.usersCount || licenseInfo.connections);
elem = document.getElementById('lic-limit-edit');
elem.innerText = 'Editors: ' + (licenseInfo.usersCount || licenseInfo.connections);
elem = document.getElementById('lic-limit-view');
elem.innerText = 'Live Viewer: ' + (licenseInfo.usersViewCount || licenseInfo.connectionsView);
if (licenseInfo.endDate===null) {
elem = document.getElementById('lic-valid-type');
elem.innerText = 'No license';
@ -326,38 +316,42 @@
elem.innerText = (licenseInfo.mode & 4) ? 'Trial' : '';
}
var quota = info.quota;
var quotaEdit = info.quota.edit,
quotaView = info.quota.view;
if (licenseInfo.usersCount>0) { // users limit
var days = parseInt(licenseInfo.usersExpire/86400) || 1;
var value = licenseInfo.usersCount - quotaEdit.usersCount.unique;
var editor = [
[quotaEdit.usersCount.unique, ''],
[quotaEdit.usersCount.unique - quotaEdit.usersCount.anonymous, ''],
[quotaEdit.usersCount.anonymous, ''],
[value, value > licenseInfo.usersCount * 0.1 ? "normal" : "critical"]
];
value = licenseInfo.usersViewCount - quotaView.usersCount.unique;
var viewer = [
[quotaView.usersCount.unique, ''],
[quotaView.usersCount.unique - quotaView.usersCount.anonymous, ''],
[quotaView.usersCount.anonymous, ''],
[value, value > licenseInfo.usersViewCount * 0.1 ? "normal" : "critical"]
];
elem = document.getElementById('user-activity-info');
elem.classList.remove('hidden');
elem = document.getElementById('user-activity-info-caption');
var days = parseInt(licenseInfo.usersExpire/86400) || 1;
elem.innerText = 'User activity in the last ' + days + (days>1 ? ' days' : ' day');
elem = document.getElementById('cell-use-up');
elem.innerText = quota.uniqueUserCount;
elem = document.getElementById('cell-external');
elem.innerText = quota.anonymousUserCount;
elem = document.getElementById('cell-internal');
elem.innerText = quota.uniqueUserCount - quota.anonymousUserCount;
elem = document.getElementById('cell-left');
var value = licenseInfo.usersCount - quota.uniqueUserCount;
elem.innerText = value;
elem.classList.add(value > licenseInfo.usersCount * 0.1 ? "normal" : "critical");
createInfoTable(elem, 'User activity in the last ' + days + (days>1 ? ' days' : ' day'), editor, viewer, ['Active', 'Internal', 'External', 'Remaining']);
} else { // connections limit
var value = licenseInfo.connections - (quotaEdit.connectionsCount || 0);
var editor = [
[quotaEdit.connectionsCount || 0, ''],
[value, value > licenseInfo.connections * 0.1 ? "normal" : "critical"]
];
value = licenseInfo.connectionsView - (quotaView.connectionsCount || 0);
var viewer = [
[quotaView.connectionsCount || 0, ''],
[value, value > licenseInfo.connectionsView * 0.1 ? "normal" : "critical"]
];
elem = document.getElementById('connection-activity-info');
elem.classList.remove('hidden');
elem = document.getElementById('cell-conn-use-up');
elem.innerText = (quota.editorConnectionsCount || 0);
elem = document.getElementById('cell-conn-left');
var value = licenseInfo.connections - (quota.editorConnectionsCount || 0);
elem.innerText = value;
elem.classList.add(value > licenseInfo.connections * 0.1 ? "normal" : "critical");
createInfoTable(elem, 'Current connections', editor, viewer, ['Active', 'Remaining']);
}
}
function fillConnections(info) {
@ -365,22 +359,36 @@
if (licenseInfo.usersCount>0) return;
var limit = licenseInfo.connections;
document.getElementById('connections-peaks').classList.remove('hidden');
document.getElementById('connections-average').classList.remove('hidden');
var limitEdit = licenseInfo.connections,
limitView = licenseInfo.connectionsView,
peaksEdit = [], peaksView = [], avrEdit = [], avrView = [], // value and class
desc = ['Last Hour', '24 Hours', 'Week', 'Month'];
for (var precision in info.connectionsStat) {
for (var agregate in info.connectionsStat[precision].edit) {
var value = info.connectionsStat[precision].edit[agregate];
var elem = document.getElementById('cell-' + precision + '-' + agregate);
if (elem) {
elem.innerText = value;
if (value >= limit) {
elem.classList.add("critical");
}
['hour', 'day', 'week', 'month'].forEach(function(item, index){
item = info.connectionsStat[item];
if (item) {
if (item.edit) {
var value = item.edit['max'] || 0;
peaksEdit[index] = [value, value >= limitEdit ? "critical" : "" ];
value = item.edit['avr'] || 0;
avrEdit[index] = [value, value >= limitEdit ? "critical" : "" ];
}
if (item.liveview) {
var value = item.liveview['max'] || 0;
peaksView[index] = [value, value >= limitView ? "critical" : "" ];
value = item.liveview['avr'] || 0;
avrView[index] = [value, value >= limitView ? "critical" : "" ];
}
}
}
});
var elem = document.getElementById('connections-peaks');
elem.classList.remove('hidden');
createInfoTable(elem, 'Peaks', peaksEdit, peaksView, desc);
elem = document.getElementById('connections-average');
elem.classList.remove('hidden');
createInfoTable(elem, 'Average', avrEdit, avrView, desc);
}
function fillStatistic(info) {
@ -396,18 +404,26 @@
byMonth.forEach(function(item){
var date = item.date,
users = item.users,
internal = 0,
external = 0;
internalEdit = 0, internalView = 0,
externalEdit = 0, externalView = 0;
if (date && users) {
for (var uid in users) {
if (users.hasOwnProperty(uid)) {
users[uid].anonym ? external++ : internal++;
users[uid].anonym ? externalEdit++ : internalEdit++;
}
}
users = item.usersView;
for (var uid in users) {
if (users.hasOwnProperty(uid)) {
users[uid].anonym ? externalView++ : internalView++;
}
}
arr.push({
startDate: new Date(date),
internal: internal,
external: external
internalEdit: internalEdit,
externalEdit: externalEdit,
internalView: internalView,
externalView: externalView
});
if (arr.length>1) {
arr[arr.length-2].endDate = new Date(new Date(date) - 86400000);
@ -417,28 +433,87 @@
for (var i=0; i<arr.length; i++) {
var item = arr[arr.length-i-1];
var tr = document.createElement("tr");
tr.innerHTML = '<td colspan="4" class="td-caption">' + (item.endDate ? item.startDate.toLocaleDateString() + ' - ' + item.endDate.toLocaleDateString(): 'From ' + item.startDate.toLocaleDateString()) + '</td>';
elem.appendChild(tr);
createInfoTable(elem, item.endDate ? item.startDate.toLocaleDateString() + ' - ' + item.endDate.toLocaleDateString(): 'From ' + item.startDate.toLocaleDateString(),
[[item.internalEdit, ''], [item.externalEdit, ''], [item.internalEdit + item.externalEdit, '']],
[[item.internalView, ''], [item.externalView, ''], [item.internalView + item.externalView, '']],
['Internal', 'External', 'Active', ''])
}
}
tr = document.createElement("tr");
tr.innerHTML = '<td class="td-separator" colspan="4"><div class="separator"></div></td>';
elem.appendChild(tr);
function createInfoTableSection(elem, caption, cls, values, desc) {
var tr = document.createElement("tr"); tr.classList.add('all-info');
tr.innerHTML = '<td colspan="4" class="td-caption-small">' + caption + '</td>';
elem.appendChild(tr);
tr = document.createElement("tr"); tr.classList.add('all-info');
tr.innerHTML = '<td class="td-separator" colspan="4"><div class="separator"></div></td>';
elem.appendChild(tr);
tr = document.createElement("tr");
tr.innerHTML = '<td class="td-value" width="150">' + item.internal + '</td>' +
'<td class="td-value" width="150">' + item.external + '</td>' +
'<td class="td-value" width="150">' + (item.internal + item.external) + '</td>' +
'<td class="td-value" width="224"></td>';
elem.appendChild(tr);
tr = document.createElement("tr"); tr.classList.add(cls); tr.innerHTML = '';
for (var i=0; i<4; i++) {
var value = values[i];
tr.innerHTML += '<td class="td-value ' + (value && value[1] ? value[1] : '') + '">' + (value && (value[0]!==undefined) ? value[0] : '') + '</td>';
}
elem.appendChild(tr);
tr = document.createElement("tr");
tr.innerHTML = '<td class="td-last">Internal</td>' +
'<td class="td-last">External</td>' +
'<td class="td-last">Active</td>' +
'<td class="td-last"></td>';
elem.appendChild(tr);
tr = document.createElement("tr"); tr.classList.add(cls); tr.innerHTML = '';
for (var i=0; i<4; i++)
tr.innerHTML += '<td class="td-last">' + (desc[i] || '') + '</td>';
elem.appendChild(tr);
tr = document.createElement("tr"); tr.classList.add('all-info');
tr.innerHTML = '<td class="td-separator" colspan="4"></div></td>';
elem.appendChild(tr);
}
function createInfoTable(elem, caption, editor, viewer, desc) {
var tr = document.createElement("tr");
tr.innerHTML = '<td colspan="4" class="td-caption">' + caption + '</td>';
elem.appendChild(tr);
tr = document.createElement("tr");
tr.innerHTML = '<td class="td-separator" colspan="4"></div></td>';
elem.appendChild(tr);
createInfoTableSection(elem, 'EDITORS', 'editor-info', editor, desc);
createInfoTableSection(elem, 'LIVE VIEWER', 'viewer-info', viewer, desc);
}
function applyMode() {
var current = document.querySelector('.td-link.current').getAttribute('value') || 'all';
var arr = document.getElementsByClassName('editor-info');
for (var i=0; i < arr.length; i++) {
(current==='view') ? arr[i].classList.add("hidden") : arr[i].classList.remove("hidden");
}
arr = document.getElementsByClassName('viewer-info');
for (var i=0; i < arr.length; i++) {
(current==='edit') ? arr[i].classList.add("hidden") : arr[i].classList.remove("hidden");
}
arr = document.getElementsByClassName('all-info');
for (var i=0; i < arr.length; i++) {
(current==='all') ? arr[i].classList.remove("hidden") : arr[i].classList.add("hidden");
}
}
function initEvents() {
var arr = document.getElementsByClassName('td-link');
var onClick = function (evt) {
for (var i=0; i < arr.length; i++) {
arr[i].classList.remove("current");
}
evt.target.classList.add('current');
window.localStorage && window.localStorage.setItem('server-info-display-mode', evt.target.getAttribute('value'));
applyMode();
};
for (var i=0; i < arr.length; i++) {
if (arr[i].addEventListener) {
arr[i].addEventListener("click", onClick)
} else if (arr[i].attachEvent) {
arr[i].attachEvent("click", onClick);
}
}
var value = window.localStorage ? window.localStorage.getItem('server-info-display-mode') || 'all' : 'all';
document.querySelector('.td-link[value=' + value + ']').classList.add('current');
}
(function(){
@ -457,6 +532,8 @@
fillInfo(info);
fillConnections(info);
fillStatistic(info);
initEvents();
applyMode();
} else {
document.getElementById('doc-server-err').classList.remove("hidden");
}

View File

@ -1,228 +0,0 @@
JSZipUtils is dual licensed. You may use it under the MIT license or the GPLv3 license.
The MIT License
Copyright (c) 2014 Stuart Knightley, David Duponchel
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
GPL version 3
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. http://fsf.org/ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section
This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS

View File

@ -1,226 +0,0 @@
JSZip is dual licensed. You may use it under the MIT license or the GPLv3 license.
The MIT License
Copyright (c) 2009-2016 Stuart Knightley, David Duponchel, Franz Buchinger, Antonio Afonso
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
GPL version 3
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. http://fsf.org/ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section
This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

View File

@ -26,6 +26,7 @@ USE onlyoffice;
--
CREATE TABLE IF NOT EXISTS `doc_changes` (
`tenant` varchar(255) NOT NULL,
`id` varchar(255) NOT NULL,
`change_id` int(10) unsigned NOT NULL,
`user_id` varchar(255) NOT NULL,
@ -33,7 +34,7 @@ CREATE TABLE IF NOT EXISTS `doc_changes` (
`user_name` varchar(255) NOT NULL,
`change_data` longtext NOT NULL,
`change_date` datetime NOT NULL,
PRIMARY KEY (`id`,`change_id`)
PRIMARY KEY (`tenant`, `id`,`change_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
@ -48,6 +49,7 @@ CREATE TABLE IF NOT EXISTS `doc_changes` (
--
CREATE TABLE IF NOT EXISTS `task_result` (
`tenant` varchar(255) NOT NULL,
`id` varchar(255) NOT NULL,
`status` tinyint(3) NOT NULL,
`status_info` int(10) NOT NULL,
@ -59,7 +61,7 @@ CREATE TABLE IF NOT EXISTS `task_result` (
`baseurl` text NOT NULL,
`password` longtext NULL,
`additional` longtext NULL,
PRIMARY KEY (`id`)
PRIMARY KEY (`tenant`, `id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--

View File

@ -8,6 +8,7 @@
-- Table structure for doc_changes
-- ----------------------------
CREATE TABLE IF NOT EXISTS "public"."doc_changes" (
"tenant" varchar(255) COLLATE "default" NOT NULL,
"id" varchar(255) COLLATE "default" NOT NULL,
"change_id" int4 NOT NULL,
"user_id" varchar(255) COLLATE "default" NOT NULL,
@ -15,7 +16,7 @@ CREATE TABLE IF NOT EXISTS "public"."doc_changes" (
"user_name" varchar(255) COLLATE "default" NOT NULL,
"change_data" text COLLATE "default" NOT NULL,
"change_date" timestamp without time zone NOT NULL,
PRIMARY KEY ("id", "change_id")
PRIMARY KEY ("tenant", "id", "change_id")
)
WITH (OIDS=FALSE);
@ -23,6 +24,7 @@ WITH (OIDS=FALSE);
-- Table structure for task_result
-- ----------------------------
CREATE TABLE IF NOT EXISTS "public"."task_result" (
"tenant" varchar(255) COLLATE "default" NOT NULL,
"id" varchar(255) COLLATE "default" NOT NULL,
"status" int2 NOT NULL,
"status_info" int4 NOT NULL,
@ -34,11 +36,11 @@ CREATE TABLE IF NOT EXISTS "public"."task_result" (
"baseurl" text COLLATE "default" NOT NULL,
"password" text COLLATE "default" NULL,
"additional" text COLLATE "default" NULL,
PRIMARY KEY ("id")
PRIMARY KEY ("tenant", "id")
)
WITH (OIDS=FALSE);
CREATE OR REPLACE FUNCTION merge_db(_id varchar(255), _status int2, _status_info int4, _last_open_date timestamp without time zone, _user_index int4, _change_id int4, _callback text, _baseurl text, OUT isupdate char(5), OUT userindex int4) AS
CREATE OR REPLACE FUNCTION merge_db(_tenant varchar(255), _id varchar(255), _status int2, _status_info int4, _last_open_date timestamp without time zone, _user_index int4, _change_id int4, _callback text, _baseurl text, OUT isupdate char(5), OUT userindex int4) AS
$$
DECLARE
t_var "public"."task_result"."user_index"%TYPE;
@ -47,9 +49,9 @@ BEGIN
-- first try to update the key
-- note that "a" must be unique
IF ((_callback <> '') IS TRUE) AND ((_baseurl <> '') IS TRUE) THEN
UPDATE "public"."task_result" SET last_open_date=_last_open_date, user_index=user_index+1,callback=_callback,baseurl=_baseurl WHERE id = _id RETURNING user_index into userindex;
UPDATE "public"."task_result" SET last_open_date=_last_open_date, user_index=user_index+1,callback=_callback,baseurl=_baseurl WHERE tenant = _tenant AND id = _id RETURNING user_index into userindex;
ELSE
UPDATE "public"."task_result" SET last_open_date=_last_open_date, user_index=user_index+1 WHERE id = _id RETURNING user_index into userindex;
UPDATE "public"."task_result" SET last_open_date=_last_open_date, user_index=user_index+1 WHERE tenant = _tenant AND id = _id RETURNING user_index into userindex;
END IF;
IF found THEN
isupdate := 'true';
@ -59,7 +61,7 @@ BEGIN
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO "public"."task_result"(id, status, status_info, last_open_date, user_index, change_id, callback, baseurl) VALUES(_id, _status, _status_info, _last_open_date, _user_index, _change_id, _callback, _baseurl) RETURNING user_index into userindex;
INSERT INTO "public"."task_result"(tenant, id, status, status_info, last_open_date, user_index, change_id, callback, baseurl) VALUES(_tenant, _id, _status, _status_info, _last_open_date, _user_index, _change_id, _callback, _baseurl) RETURNING user_index into userindex;
isupdate := 'false';
RETURN;
EXCEPTION WHEN unique_violation THEN