lint: Run eslint --fix on src/

This commit is contained in:
Richard Hansen 2020-11-23 13:24:19 -05:00 committed by John McLear
parent b8d07a42eb
commit 8e5fd19db2
109 changed files with 9061 additions and 10572 deletions

View file

@ -18,131 +18,118 @@
* limitations under the License.
*/
var absolutePaths = require('../utils/AbsolutePaths');
var fs = require("fs");
var api = require("../db/API");
var log4js = require('log4js');
var padManager = require("../db/PadManager");
var randomString = require("../utils/randomstring");
var argv = require('../utils/Cli').argv;
var createHTTPError = require('http-errors');
const absolutePaths = require('../utils/AbsolutePaths');
const fs = require('fs');
const api = require('../db/API');
const log4js = require('log4js');
const padManager = require('../db/PadManager');
const randomString = require('../utils/randomstring');
const argv = require('../utils/Cli').argv;
const createHTTPError = require('http-errors');
var apiHandlerLogger = log4js.getLogger('APIHandler');
const apiHandlerLogger = log4js.getLogger('APIHandler');
//ensure we have an apikey
var apikey = null;
var apikeyFilename = absolutePaths.makeAbsolute(argv.apikey || "./APIKEY.txt");
// ensure we have an apikey
let apikey = null;
const apikeyFilename = absolutePaths.makeAbsolute(argv.apikey || './APIKEY.txt');
try {
apikey = fs.readFileSync(apikeyFilename,"utf8");
apikey = fs.readFileSync(apikeyFilename, 'utf8');
apiHandlerLogger.info(`Api key file read from: "${apikeyFilename}"`);
} catch(e) {
} catch (e) {
apiHandlerLogger.info(`Api key file "${apikeyFilename}" not found. Creating with random contents.`);
apikey = randomString(32);
fs.writeFileSync(apikeyFilename,apikey,"utf8");
fs.writeFileSync(apikeyFilename, apikey, 'utf8');
}
// a list of all functions
var version = {};
const version = {};
version["1"] = Object.assign({},
{ "createGroup" : []
, "createGroupIfNotExistsFor" : ["groupMapper"]
, "deleteGroup" : ["groupID"]
, "listPads" : ["groupID"]
, "createPad" : ["padID", "text"]
, "createGroupPad" : ["groupID", "padName", "text"]
, "createAuthor" : ["name"]
, "createAuthorIfNotExistsFor": ["authorMapper" , "name"]
, "listPadsOfAuthor" : ["authorID"]
, "createSession" : ["groupID", "authorID", "validUntil"]
, "deleteSession" : ["sessionID"]
, "getSessionInfo" : ["sessionID"]
, "listSessionsOfGroup" : ["groupID"]
, "listSessionsOfAuthor" : ["authorID"]
, "getText" : ["padID", "rev"]
, "setText" : ["padID", "text"]
, "getHTML" : ["padID", "rev"]
, "setHTML" : ["padID", "html"]
, "getRevisionsCount" : ["padID"]
, "getLastEdited" : ["padID"]
, "deletePad" : ["padID"]
, "getReadOnlyID" : ["padID"]
, "setPublicStatus" : ["padID", "publicStatus"]
, "getPublicStatus" : ["padID"]
, "listAuthorsOfPad" : ["padID"]
, "padUsersCount" : ["padID"]
}
version['1'] = Object.assign({},
{createGroup: [],
createGroupIfNotExistsFor: ['groupMapper'],
deleteGroup: ['groupID'],
listPads: ['groupID'],
createPad: ['padID', 'text'],
createGroupPad: ['groupID', 'padName', 'text'],
createAuthor: ['name'],
createAuthorIfNotExistsFor: ['authorMapper', 'name'],
listPadsOfAuthor: ['authorID'],
createSession: ['groupID', 'authorID', 'validUntil'],
deleteSession: ['sessionID'],
getSessionInfo: ['sessionID'],
listSessionsOfGroup: ['groupID'],
listSessionsOfAuthor: ['authorID'],
getText: ['padID', 'rev'],
setText: ['padID', 'text'],
getHTML: ['padID', 'rev'],
setHTML: ['padID', 'html'],
getRevisionsCount: ['padID'],
getLastEdited: ['padID'],
deletePad: ['padID'],
getReadOnlyID: ['padID'],
setPublicStatus: ['padID', 'publicStatus'],
getPublicStatus: ['padID'],
listAuthorsOfPad: ['padID'],
padUsersCount: ['padID']},
);
version["1.1"] = Object.assign({}, version["1"],
{ "getAuthorName" : ["authorID"]
, "padUsers" : ["padID"]
, "sendClientsMessage" : ["padID", "msg"]
, "listAllGroups" : []
}
version['1.1'] = Object.assign({}, version['1'],
{getAuthorName: ['authorID'],
padUsers: ['padID'],
sendClientsMessage: ['padID', 'msg'],
listAllGroups: []},
);
version["1.2"] = Object.assign({}, version["1.1"],
{ "checkToken" : []
}
version['1.2'] = Object.assign({}, version['1.1'],
{checkToken: []},
);
version["1.2.1"] = Object.assign({}, version["1.2"],
{ "listAllPads" : []
}
version['1.2.1'] = Object.assign({}, version['1.2'],
{listAllPads: []},
);
version["1.2.7"] = Object.assign({}, version["1.2.1"],
{ "createDiffHTML" : ["padID", "startRev", "endRev"]
, "getChatHistory" : ["padID", "start", "end"]
, "getChatHead" : ["padID"]
}
version['1.2.7'] = Object.assign({}, version['1.2.1'],
{createDiffHTML: ['padID', 'startRev', 'endRev'],
getChatHistory: ['padID', 'start', 'end'],
getChatHead: ['padID']},
);
version["1.2.8"] = Object.assign({}, version["1.2.7"],
{ "getAttributePool" : ["padID"]
, "getRevisionChangeset" : ["padID", "rev"]
}
version['1.2.8'] = Object.assign({}, version['1.2.7'],
{getAttributePool: ['padID'],
getRevisionChangeset: ['padID', 'rev']},
);
version["1.2.9"] = Object.assign({}, version["1.2.8"],
{ "copyPad" : ["sourceID", "destinationID", "force"]
, "movePad" : ["sourceID", "destinationID", "force"]
}
version['1.2.9'] = Object.assign({}, version['1.2.8'],
{copyPad: ['sourceID', 'destinationID', 'force'],
movePad: ['sourceID', 'destinationID', 'force']},
);
version["1.2.10"] = Object.assign({}, version["1.2.9"],
{ "getPadID" : ["roID"]
}
version['1.2.10'] = Object.assign({}, version['1.2.9'],
{getPadID: ['roID']},
);
version["1.2.11"] = Object.assign({}, version["1.2.10"],
{ "getSavedRevisionsCount" : ["padID"]
, "listSavedRevisions" : ["padID"]
, "saveRevision" : ["padID", "rev"]
, "restoreRevision" : ["padID", "rev"]
}
version['1.2.11'] = Object.assign({}, version['1.2.10'],
{getSavedRevisionsCount: ['padID'],
listSavedRevisions: ['padID'],
saveRevision: ['padID', 'rev'],
restoreRevision: ['padID', 'rev']},
);
version["1.2.12"] = Object.assign({}, version["1.2.11"],
{ "appendChatMessage" : ["padID", "text", "authorID", "time"]
}
version['1.2.12'] = Object.assign({}, version['1.2.11'],
{appendChatMessage: ['padID', 'text', 'authorID', 'time']},
);
version["1.2.13"] = Object.assign({}, version["1.2.12"],
{ "appendText" : ["padID", "text"]
}
version['1.2.13'] = Object.assign({}, version['1.2.12'],
{appendText: ['padID', 'text']},
);
version["1.2.14"] = Object.assign({}, version["1.2.13"],
{ "getStats" : []
}
version['1.2.14'] = Object.assign({}, version['1.2.13'],
{getStats: []},
);
version["1.2.15"] = Object.assign({}, version["1.2.14"],
{ "copyPadWithoutHistory" : ["sourceID", "destinationID", "force"]
}
version['1.2.15'] = Object.assign({}, version['1.2.14'],
{copyPadWithoutHistory: ['sourceID', 'destinationID', 'force']},
);
// set the latest available API version here
@ -158,7 +145,7 @@ exports.version = version;
* @req express request object
* @res express response object
*/
exports.handle = async function(apiVersion, functionName, fields, req, res) {
exports.handle = async function (apiVersion, functionName, fields, req, res) {
// say goodbye if this is an unknown API version
if (!(apiVersion in version)) {
throw new createHTTPError.NotFound('no such api version');
@ -170,31 +157,29 @@ exports.handle = async function(apiVersion, functionName, fields, req, res) {
}
// check the api key!
fields["apikey"] = fields["apikey"] || fields["api_key"];
fields.apikey = fields.apikey || fields.api_key;
if (fields["apikey"] !== apikey.trim()) {
if (fields.apikey !== apikey.trim()) {
throw new createHTTPError.Unauthorized('no or wrong API Key');
}
// sanitize any padIDs before continuing
if (fields["padID"]) {
fields["padID"] = await padManager.sanitizePadId(fields["padID"]);
if (fields.padID) {
fields.padID = await padManager.sanitizePadId(fields.padID);
}
// there was an 'else' here before - removed it to ensure
// that this sanitize step can't be circumvented by forcing
// the first branch to be taken
if (fields["padName"]) {
fields["padName"] = await padManager.sanitizePadId(fields["padName"]);
if (fields.padName) {
fields.padName = await padManager.sanitizePadId(fields.padName);
}
// put the function parameters in an array
var functionParams = version[apiVersion][functionName].map(function (field) {
return fields[field]
});
const functionParams = version[apiVersion][functionName].map((field) => fields[field]);
// call the api function
return api[functionName].apply(this, functionParams);
}
};
exports.exportedForTestingOnly = {
apiKey: apikey,

View file

@ -19,15 +19,15 @@
* limitations under the License.
*/
var exporthtml = require("../utils/ExportHtml");
var exporttxt = require("../utils/ExportTxt");
var exportEtherpad = require("../utils/ExportEtherpad");
var fs = require("fs");
var settings = require('../utils/Settings');
var os = require('os');
var hooks = require("ep_etherpad-lite/static/js/pluginfw/hooks");
var TidyHtml = require('../utils/TidyHtml');
const util = require("util");
const exporthtml = require('../utils/ExportHtml');
const exporttxt = require('../utils/ExportTxt');
const exportEtherpad = require('../utils/ExportEtherpad');
const fs = require('fs');
const settings = require('../utils/Settings');
const os = require('os');
const hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks');
const TidyHtml = require('../utils/TidyHtml');
const util = require('util');
const fsp_writeFile = util.promisify(fs.writeFile);
const fsp_unlink = util.promisify(fs.unlink);
@ -36,12 +36,12 @@ let convertor = null;
// load abiword only if it is enabled
if (settings.abiword != null) {
convertor = require("../utils/Abiword");
convertor = require('../utils/Abiword');
}
// Use LibreOffice if an executable has been defined in the settings
if (settings.soffice != null) {
convertor = require("../utils/LibreOffice");
convertor = require('../utils/LibreOffice');
}
const tempDirectory = os.tmpdir();
@ -51,10 +51,10 @@ const tempDirectory = os.tmpdir();
*/
async function doExport(req, res, padId, readOnlyId, type) {
// avoid naming the read-only file as the original pad's id
var fileName = readOnlyId ? readOnlyId : padId;
let fileName = readOnlyId ? readOnlyId : padId;
// allow fileName to be overwritten by a hook, the type type is kept static for security reasons
let hookFileName = await hooks.aCallFirst("exportFileName", padId);
const hookFileName = await hooks.aCallFirst('exportFileName', padId);
// if fileName is set then set it to the padId, note that fileName is returned as an array.
if (hookFileName.length) {
@ -62,15 +62,15 @@ async function doExport(req, res, padId, readOnlyId, type) {
}
// tell the browser that this is a downloadable file
res.attachment(fileName + "." + type);
res.attachment(`${fileName}.${type}`);
// if this is a plain text export, we can do this directly
// We have to over engineer this because tabs are stored as attributes and not plain text
if (type === "etherpad") {
let pad = await exportEtherpad.getPadRaw(padId);
if (type === 'etherpad') {
const pad = await exportEtherpad.getPadRaw(padId);
res.send(pad);
} else if (type === "txt") {
let txt = await exporttxt.getPadTXTDocument(padId, req.params.rev);
} else if (type === 'txt') {
const txt = await exporttxt.getPadTXTDocument(padId, req.params.rev);
res.send(txt);
} else {
// render the html document
@ -79,17 +79,17 @@ async function doExport(req, res, padId, readOnlyId, type) {
// decide what to do with the html export
// if this is a html export, we can send this from here directly
if (type === "html") {
if (type === 'html') {
// do any final changes the plugin might want to make
let newHTML = await hooks.aCallFirst("exportHTMLSend", html);
const newHTML = await hooks.aCallFirst('exportHTMLSend', html);
if (newHTML.length) html = newHTML;
res.send(html);
throw "stop";
throw 'stop';
}
// else write the html export to a file
let randNum = Math.floor(Math.random()*0xFFFFFFFF);
let srcFile = tempDirectory + "/etherpad_export_" + randNum + ".html";
const randNum = Math.floor(Math.random() * 0xFFFFFFFF);
const srcFile = `${tempDirectory}/etherpad_export_${randNum}.html`;
await fsp_writeFile(srcFile, html);
// Tidy up the exported HTML
@ -98,42 +98,42 @@ async function doExport(req, res, padId, readOnlyId, type) {
await TidyHtml.tidy(srcFile);
// send the convert job to the convertor (abiword, libreoffice, ..)
let destFile = tempDirectory + "/etherpad_export_" + randNum + "." + type;
const destFile = `${tempDirectory}/etherpad_export_${randNum}.${type}`;
// Allow plugins to overwrite the convert in export process
let result = await hooks.aCallAll("exportConvert", { srcFile, destFile, req, res });
const result = await hooks.aCallAll('exportConvert', {srcFile, destFile, req, res});
if (result.length > 0) {
// console.log("export handled by plugin", destFile);
handledByPlugin = true;
} else {
// @TODO no Promise interface for convertors (yet)
await new Promise((resolve, reject) => {
convertor.convertFile(srcFile, destFile, type, function(err) {
err ? reject("convertFailed") : resolve();
convertor.convertFile(srcFile, destFile, type, (err) => {
err ? reject('convertFailed') : resolve();
});
});
}
// send the file
let sendFile = util.promisify(res.sendFile);
const sendFile = util.promisify(res.sendFile);
await res.sendFile(destFile, null);
// clean up temporary files
await fsp_unlink(srcFile);
// 100ms delay to accommodate for slow windows fs
if (os.type().indexOf("Windows") > -1) {
await new Promise(resolve => setTimeout(resolve, 100));
if (os.type().indexOf('Windows') > -1) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
await fsp_unlink(destFile);
}
}
exports.doExport = function(req, res, padId, readOnlyId, type) {
doExport(req, res, padId, readOnlyId, type).catch(err => {
if (err !== "stop") {
exports.doExport = function (req, res, padId, readOnlyId, type) {
doExport(req, res, padId, readOnlyId, type).catch((err) => {
if (err !== 'stop') {
throw err;
}
});
}
};

View file

@ -20,36 +20,36 @@
* limitations under the License.
*/
var padManager = require("../db/PadManager")
, padMessageHandler = require("./PadMessageHandler")
, fs = require("fs")
, path = require("path")
, settings = require('../utils/Settings')
, formidable = require('formidable')
, os = require("os")
, importHtml = require("../utils/ImportHtml")
, importEtherpad = require("../utils/ImportEtherpad")
, log4js = require("log4js")
, hooks = require("ep_etherpad-lite/static/js/pluginfw/hooks.js")
, util = require("util");
const padManager = require('../db/PadManager');
const padMessageHandler = require('./PadMessageHandler');
const fs = require('fs');
const path = require('path');
const settings = require('../utils/Settings');
const formidable = require('formidable');
const os = require('os');
const importHtml = require('../utils/ImportHtml');
const importEtherpad = require('../utils/ImportEtherpad');
const log4js = require('log4js');
const hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks.js');
const util = require('util');
let fsp_exists = util.promisify(fs.exists);
let fsp_rename = util.promisify(fs.rename);
let fsp_readFile = util.promisify(fs.readFile);
let fsp_unlink = util.promisify(fs.unlink)
const fsp_exists = util.promisify(fs.exists);
const fsp_rename = util.promisify(fs.rename);
const fsp_readFile = util.promisify(fs.readFile);
const fsp_unlink = util.promisify(fs.unlink);
let convertor = null;
let exportExtension = "htm";
let exportExtension = 'htm';
// load abiword only if it is enabled and if soffice is disabled
if (settings.abiword != null && settings.soffice === null) {
convertor = require("../utils/Abiword");
convertor = require('../utils/Abiword');
}
// load soffice only if it is enabled
if (settings.soffice != null) {
convertor = require("../utils/LibreOffice");
exportExtension = "html";
convertor = require('../utils/LibreOffice');
exportExtension = 'html';
}
const tmpDirectory = os.tmpdir();
@ -58,28 +58,28 @@ const tmpDirectory = os.tmpdir();
* do a requested import
*/
async function doImport(req, res, padId) {
var apiLogger = log4js.getLogger("ImportHandler");
const apiLogger = log4js.getLogger('ImportHandler');
// pipe to a file
// convert file to html via abiword or soffice
// set html in the pad
var randNum = Math.floor(Math.random()*0xFFFFFFFF);
const randNum = Math.floor(Math.random() * 0xFFFFFFFF);
// setting flag for whether to use convertor or not
let useConvertor = (convertor != null);
let form = new formidable.IncomingForm();
const form = new formidable.IncomingForm();
form.keepExtensions = true;
form.uploadDir = tmpDirectory;
form.maxFileSize = settings.importMaxFileSize;
// Ref: https://github.com/node-formidable/formidable/issues/469
// Crash in Etherpad was Uploading Error: Error: Request aborted
// [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed
form.onPart = part => {
form.onPart = (part) => {
form.handlePart(part);
if (part.filename !== undefined) {
form.openedFiles[form.openedFiles.length - 1]._writeStream.on('error', err => {
form.openedFiles[form.openedFiles.length - 1]._writeStream.on('error', (err) => {
form.emit('error', err);
});
}
@ -87,23 +87,23 @@ async function doImport(req, res, padId) {
// locally wrapped Promise, since form.parse requires a callback
let srcFile = await new Promise((resolve, reject) => {
form.parse(req, function(err, fields, files) {
form.parse(req, (err, fields, files) => {
if (err || files.file === undefined) {
// the upload failed, stop at this point
if (err) {
console.warn("Uploading Error: " + err.stack);
console.warn(`Uploading Error: ${err.stack}`);
}
// I hate doing indexOf here but I can't see anything to use...
if (err && err.stack && err.stack.indexOf("maxFileSize") !== -1) {
reject("maxFileSize");
if (err && err.stack && err.stack.indexOf('maxFileSize') !== -1) {
reject('maxFileSize');
}
reject("uploadFailed");
reject('uploadFailed');
}
if(!files.file){ // might not be a graceful fix but it works
reject("uploadFailed");
}else{
if (!files.file) { // might not be a graceful fix but it works
reject('uploadFailed');
} else {
resolve(files.file.path);
}
});
@ -111,47 +111,47 @@ async function doImport(req, res, padId) {
// ensure this is a file ending we know, else we change the file ending to .txt
// this allows us to accept source code files like .c or .java
let fileEnding = path.extname(srcFile).toLowerCase()
, knownFileEndings = [".txt", ".doc", ".docx", ".pdf", ".odt", ".html", ".htm", ".etherpad", ".rtf"]
, fileEndingUnknown = (knownFileEndings.indexOf(fileEnding) < 0);
const fileEnding = path.extname(srcFile).toLowerCase();
const knownFileEndings = ['.txt', '.doc', '.docx', '.pdf', '.odt', '.html', '.htm', '.etherpad', '.rtf'];
const fileEndingUnknown = (knownFileEndings.indexOf(fileEnding) < 0);
if (fileEndingUnknown) {
// the file ending is not known
if (settings.allowUnknownFileEnds === true) {
// we need to rename this file with a .txt ending
let oldSrcFile = srcFile;
const oldSrcFile = srcFile;
srcFile = path.join(path.dirname(srcFile), path.basename(srcFile, fileEnding) + ".txt");
srcFile = path.join(path.dirname(srcFile), `${path.basename(srcFile, fileEnding)}.txt`);
await fsp_rename(oldSrcFile, srcFile);
} else {
console.warn("Not allowing unknown file type to be imported", fileEnding);
throw "uploadFailed";
console.warn('Not allowing unknown file type to be imported', fileEnding);
throw 'uploadFailed';
}
}
let destFile = path.join(tmpDirectory, "etherpad_import_" + randNum + "." + exportExtension);
const destFile = path.join(tmpDirectory, `etherpad_import_${randNum}.${exportExtension}`);
// Logic for allowing external Import Plugins
let result = await hooks.aCallAll("import", { srcFile, destFile, fileEnding });
let importHandledByPlugin = (result.length > 0); // This feels hacky and wrong..
const result = await hooks.aCallAll('import', {srcFile, destFile, fileEnding});
const importHandledByPlugin = (result.length > 0); // This feels hacky and wrong..
let fileIsEtherpad = (fileEnding === ".etherpad");
let fileIsHTML = (fileEnding === ".html" || fileEnding === ".htm");
let fileIsTXT = (fileEnding === ".txt");
const fileIsEtherpad = (fileEnding === '.etherpad');
const fileIsHTML = (fileEnding === '.html' || fileEnding === '.htm');
const fileIsTXT = (fileEnding === '.txt');
if (fileIsEtherpad) {
// we do this here so we can see if the pad has quite a few edits
let _pad = await padManager.getPad(padId);
let headCount = _pad.head;
const _pad = await padManager.getPad(padId);
const headCount = _pad.head;
if (headCount >= 10) {
apiLogger.warn("Direct database Import attempt of a pad that already has content, we won't be doing this");
throw "padHasData";
throw 'padHasData';
}
const fsp_readFile = util.promisify(fs.readFile);
let _text = await fsp_readFile(srcFile, "utf8");
const _text = await fsp_readFile(srcFile, 'utf8');
req.directDatabaseAccess = true;
await importEtherpad.setPadRaw(padId, _text);
}
@ -170,11 +170,11 @@ async function doImport(req, res, padId) {
} else {
// @TODO - no Promise interface for convertors (yet)
await new Promise((resolve, reject) => {
convertor.convertFile(srcFile, destFile, exportExtension, function(err) {
convertor.convertFile(srcFile, destFile, exportExtension, (err) => {
// catch convert errors
if (err) {
console.warn("Converting Error:", err);
reject("convertFailed");
console.warn('Converting Error:', err);
reject('convertFailed');
}
resolve();
});
@ -184,13 +184,13 @@ async function doImport(req, res, padId) {
if (!useConvertor && !req.directDatabaseAccess) {
// Read the file with no encoding for raw buffer access.
let buf = await fsp_readFile(destFile);
const buf = await fsp_readFile(destFile);
// Check if there are only ascii chars in the uploaded file
let isAscii = ! Array.prototype.some.call(buf, c => (c > 240));
const isAscii = !Array.prototype.some.call(buf, (c) => (c > 240));
if (!isAscii) {
throw "uploadFailed";
throw 'uploadFailed';
}
}
@ -201,7 +201,7 @@ async function doImport(req, res, padId) {
let text;
if (!req.directDatabaseAccess) {
text = await fsp_readFile(destFile, "utf8");
text = await fsp_readFile(destFile, 'utf8');
/*
* The <title> tag needs to be stripped out, otherwise it is appended to the
@ -211,13 +211,13 @@ async function doImport(req, res, padId) {
* added to the <title> tag. This is a quick & dirty way of matching the
* title and comment it out independently on the classes that are set on it.
*/
text = text.replace("<title", "<!-- <title");
text = text.replace("</title>","</title>-->");
text = text.replace('<title', '<!-- <title');
text = text.replace('</title>', '</title>-->');
// node on windows has a delay on releasing of the file lock.
// We add a 100ms delay to work around this
if (os.type().indexOf("Windows") > -1){
await new Promise(resolve => setTimeout(resolve, 100));
if (os.type().indexOf('Windows') > -1) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
@ -227,7 +227,7 @@ async function doImport(req, res, padId) {
try {
await importHtml.setPadHTML(pad, text);
} catch (e) {
apiLogger.warn("Error importing, possibly caused by malformed HTML");
apiLogger.warn('Error importing, possibly caused by malformed HTML');
}
} else {
await pad.setText(text);
@ -274,16 +274,16 @@ exports.doImport = function (req, res, padId) {
* the function above there's no other way to return
* a value to the caller.
*/
let status = "ok";
doImport(req, res, padId).catch(err => {
let status = 'ok';
doImport(req, res, padId).catch((err) => {
// check for known errors and replace the status
if (err == "uploadFailed" || err == "convertFailed" || err == "padHasData" || err == "maxFileSize") {
if (err == 'uploadFailed' || err == 'convertFailed' || err == 'padHasData' || err == 'maxFileSize') {
status = err;
} else {
throw err;
}
}).then(() => {
// close the connection
res.send("<script>document.addEventListener('DOMContentLoaded', function(){ var impexp = window.parent.padimpexp.handleFrameCall('" + req.directDatabaseAccess +"', '" + status + "'); })</script>");
res.send(`<script>document.addEventListener('DOMContentLoaded', function(){ var impexp = window.parent.padimpexp.handleFrameCall('${req.directDatabaseAccess}', '${status}'); })</script>`);
});
}
};

File diff suppressed because it is too large Load diff

View file

@ -19,53 +19,53 @@
* limitations under the License.
*/
var log4js = require('log4js');
var messageLogger = log4js.getLogger("message");
var securityManager = require("../db/SecurityManager");
var readOnlyManager = require("../db/ReadOnlyManager");
var settings = require('../utils/Settings');
const log4js = require('log4js');
const messageLogger = log4js.getLogger('message');
const securityManager = require('../db/SecurityManager');
const readOnlyManager = require('../db/ReadOnlyManager');
const settings = require('../utils/Settings');
/**
* Saves all components
* key is the component name
* value is the component module
*/
var components = {};
const components = {};
var socket;
let socket;
/**
* adds a component
*/
exports.addComponent = function(moduleName, module) {
exports.addComponent = function (moduleName, module) {
// save the component
components[moduleName] = module;
// give the module the socket
module.setSocketIO(socket);
}
};
/**
* sets the socket.io and adds event functions for routing
*/
exports.setSocketIO = function(_socket) {
exports.setSocketIO = function (_socket) {
// save this socket internaly
socket = _socket;
socket.sockets.on('connection', function(client) {
socket.sockets.on('connection', (client) => {
// wrap the original send function to log the messages
client._send = client.send;
client.send = function(message) {
client.send = function (message) {
messageLogger.debug(`to ${client.id}: ${JSON.stringify(message)}`);
client._send(message);
}
};
// tell all components about this connect
for (let i in components) {
for (const i in components) {
components[i].handleConnect(client);
}
client.on('message', async function(message) {
client.on('message', async (message) => {
if (message.protocolVersion && message.protocolVersion != 2) {
messageLogger.warn(`Protocolversion header is not correct: ${JSON.stringify(message)}`);
return;
@ -78,11 +78,11 @@ exports.setSocketIO = function(_socket) {
await components[message.component].handleMessage(client, message);
});
client.on('disconnect', function() {
client.on('disconnect', () => {
// tell all components about this disconnect
for (let i in components) {
for (const i in components) {
components[i].handleDisconnect(client);
}
});
});
}
};