VersaWhiteboard/scripts/server-backend.js

283 lines
10 KiB
JavaScript
Raw Normal View History

const path = require("path");
2018-02-08 17:45:07 +01:00
const config = require("./config/config");
const WhiteboardServerSideInfo = require("./WhiteboardServerSideInfo");
function startBackendServer(port) {
var fs = require("fs-extra");
2020-05-09 15:40:26 +02:00
var express = require("express");
var formidable = require("formidable"); //form upload processing
const createDOMPurify = require("dompurify"); //Prevent xss
const { JSDOM } = require("jsdom");
const window = new JSDOM("").window;
const DOMPurify = createDOMPurify(window);
2020-05-09 15:40:26 +02:00
const { createClient } = require("webdav");
2020-05-09 15:40:26 +02:00
var s_whiteboard = require("./s_whiteboard.js");
2020-05-09 15:40:26 +02:00
var app = express();
2020-05-09 15:40:26 +02:00
app.use(express.static(path.join(__dirname, "..", "dist")));
app.use("/uploads", express.static(path.join(__dirname, "..", "public", "uploads")));
var server = require("http").Server(app);
server.listen(port);
2020-05-09 15:40:26 +02:00
var io = require("socket.io")(server, { path: "/ws-api" });
console.log("Webserver & socketserver running on port:" + port);
2020-05-09 15:40:26 +02:00
2020-05-11 16:00:45 +02:00
const { accessToken, enableWebdav } = config.backend;
2020-05-09 15:40:26 +02:00
app.get("/api/loadwhiteboard", function (req, res) {
var wid = req["query"]["wid"];
var at = req["query"]["at"]; //accesstoken
if (accessToken === "" || accessToken == at) {
var ret = s_whiteboard.loadStoredData(wid);
res.send(ret);
res.end();
} else {
2020-05-09 15:40:26 +02:00
res.status(401); //Unauthorized
res.end();
}
2018-02-08 23:16:28 +01:00
});
2020-05-09 15:40:26 +02:00
app.post("/api/upload", function (req, res) {
//File upload
var form = new formidable.IncomingForm(); //Receive form
var formData = {
files: {},
2020-05-09 15:40:26 +02:00
fields: {},
};
form.on("file", function (name, file) {
formData["files"][file.name] = file;
});
2020-05-09 15:40:26 +02:00
form.on("field", function (name, value) {
formData["fields"][name] = value;
});
2020-05-09 15:40:26 +02:00
form.on("error", function (err) {
console.log("File uplaod Error!");
});
2020-05-09 15:40:26 +02:00
form.on("end", function () {
if (accessToken === "" || accessToken == formData["fields"]["at"]) {
progressUploadFormData(formData, function (err) {
if (err) {
if (err == "403") {
res.status(403);
2019-07-01 13:15:11 +02:00
} else {
res.status(500);
2019-07-01 13:15:11 +02:00
}
res.end();
2019-07-01 13:15:11 +02:00
} else {
res.send("done");
2019-07-01 13:15:11 +02:00
}
});
} else {
2020-05-09 15:40:26 +02:00
res.status(401); //Unauthorized
res.end();
2019-07-01 13:15:11 +02:00
}
//End file upload
2019-07-01 13:15:11 +02:00
});
form.parse(req);
});
2020-05-09 15:40:26 +02:00
function progressUploadFormData(formData, callback) {
console.log("Progress new Form Data");
var fields = escapeAllContentStrings(formData.fields);
var files = formData.files;
var whiteboardId = fields["whiteboardId"];
2020-05-09 15:40:26 +02:00
var name = fields["name"] || "";
2020-05-09 15:40:26 +02:00
var date = fields["date"] || +new Date();
var filename = whiteboardId + "_" + date + ".png";
var webdavaccess = fields["webdavaccess"] || false;
try {
webdavaccess = JSON.parse(webdavaccess);
} catch (e) {
webdavaccess = false;
}
fs.ensureDir("./public/uploads", function (err) {
if (err) {
console.log("Could not create upload folder!", err);
return;
}
var imagedata = fields["imagedata"];
2020-05-09 15:40:26 +02:00
if (imagedata && imagedata != "") {
//Save from base64 data
imagedata = imagedata
.replace(/^data:image\/png;base64,/, "")
.replace(/^data:image\/jpeg;base64,/, "");
console.log(filename, "uploaded");
2020-05-09 15:40:26 +02:00
fs.writeFile("./public/uploads/" + filename, imagedata, "base64", function (err) {
if (err) {
console.log("error", err);
callback(err);
} else {
2020-05-09 15:40:26 +02:00
if (webdavaccess) {
//Save image to webdav
2020-05-11 16:00:45 +02:00
if (enableWebdav) {
2020-05-09 15:40:26 +02:00
saveImageToWebdav(
"./public/uploads/" + filename,
filename,
webdavaccess,
function (err) {
if (err) {
console.log("error", err);
callback(err);
} else {
callback();
}
}
2020-05-09 15:40:26 +02:00
);
} else {
callback("Webdav is not enabled on the server!");
}
} else {
callback();
}
}
});
} else {
callback("no imagedata!");
console.log("No image Data found for this upload!", name);
}
});
}
2020-05-09 15:40:26 +02:00
function saveImageToWebdav(imagepath, filename, webdavaccess, callback) {
if (webdavaccess) {
var webdavserver = webdavaccess["webdavserver"] || "";
var webdavpath = webdavaccess["webdavpath"] || "/";
var webdavusername = webdavaccess["webdavusername"] || "";
var webdavpassword = webdavaccess["webdavpassword"] || "";
2020-05-09 15:40:26 +02:00
const client = createClient(webdavserver, {
username: webdavusername,
password: webdavpassword,
});
2020-05-09 15:40:26 +02:00
client
.getDirectoryContents(webdavpath)
.then((items) => {
var cloudpath = webdavpath + "" + filename;
console.log("webdav saving to:", cloudpath);
fs.createReadStream(imagepath).pipe(client.createWriteStream(cloudpath));
callback();
})
.catch((error) => {
callback("403");
console.log("Could not connect to webdav!");
});
} else {
2020-05-09 15:40:26 +02:00
callback("Error: no access data!");
}
}
2020-05-09 15:40:26 +02:00
/**
* @type {Map<string, WhiteboardServerSideInfo>}
*/
const infoByWhiteboard = new Map();
setInterval(() => {
infoByWhiteboard.forEach((info, whiteboardId) => {
if (info.shouldSendInfo()) {
io.sockets
.in(whiteboardId)
.compress(false)
.emit("whiteboardInfoUpdate", info.asObject());
info.infoWasSent();
}
});
}, (1 / config.backend.performance.whiteboardInfoBroadcastFreq) * 1000);
2020-05-09 15:40:26 +02:00
io.on("connection", function (socket) {
var whiteboardId = null;
2020-05-09 15:40:26 +02:00
socket.on("disconnect", function () {
2020-05-10 23:10:54 +02:00
if (infoByWhiteboard.has(whiteboardId)) {
2020-05-10 23:13:55 +02:00
const whiteboardServerSideInfo = infoByWhiteboard.get(whiteboardId);
2020-05-10 23:13:55 +02:00
if (socket && socket.id) {
whiteboardServerSideInfo.deleteScreenResolutionOfClient(socket.id);
}
2020-05-10 23:13:55 +02:00
whiteboardServerSideInfo.decrementNbConnectedUsers();
2020-05-10 23:10:54 +02:00
2020-05-10 23:13:55 +02:00
if (whiteboardServerSideInfo.hasConnectedUser()) {
socket.compress(false).broadcast.emit("refreshUserBadges", null); //Removes old user Badges
} else {
infoByWhiteboard.delete(whiteboardId);
}
2020-05-10 23:10:54 +02:00
}
});
2020-05-09 15:40:26 +02:00
socket.on("drawToWhiteboard", function (content) {
content = escapeAllContentStrings(content);
if (accessToken === "" || accessToken == content["at"]) {
2020-05-09 15:40:26 +02:00
socket.compress(false).broadcast.to(whiteboardId).emit("drawToWhiteboard", content); //Send to all users in the room (not own socket)
s_whiteboard.handleEventsAndData(content); //save whiteboardchanges on the server
} else {
2020-05-09 15:40:26 +02:00
socket.emit("wrongAccessToken", true);
}
});
2020-05-09 15:40:26 +02:00
socket.on("joinWhiteboard", function (content) {
content = escapeAllContentStrings(content);
if (accessToken === "" || accessToken == content["at"]) {
2020-05-10 23:13:55 +02:00
socket.emit("whiteboardConfig", { common: config.frontend });
whiteboardId = content["wid"];
socket.join(whiteboardId); //Joins room name=wid
if (!infoByWhiteboard.has(whiteboardId)) {
infoByWhiteboard.set(whiteboardId, new WhiteboardServerSideInfo());
}
const whiteboardServerSideInfo = infoByWhiteboard.get(whiteboardId);
whiteboardServerSideInfo.incrementNbConnectedUsers();
whiteboardServerSideInfo.setScreenResolutionForClient(
socket.id,
content["windowWidthHeight"] || WhiteboardServerSideInfo.defaultScreenResolution
);
} else {
2020-05-09 15:40:26 +02:00
socket.emit("wrongAccessToken", true);
}
});
2020-05-09 15:40:26 +02:00
socket.on("updateScreenResolution", function (content) {
content = escapeAllContentStrings(content);
if (accessToken === "" || accessToken == content["at"]) {
const whiteboardServerSideInfo = infoByWhiteboard.get(whiteboardId);
whiteboardServerSideInfo.setScreenResolutionForClient(
socket.id,
content["windowWidthHeight"] || WhiteboardServerSideInfo.defaultScreenResolution
);
}
});
});
2020-05-09 15:40:26 +02:00
//Prevent cross site scripting (xss)
function escapeAllContentStrings(content, cnt) {
2020-05-09 15:40:26 +02:00
if (!cnt) cnt = 0;
if (typeof content === "string") {
return DOMPurify.sanitize(content);
}
for (var i in content) {
2020-05-09 15:40:26 +02:00
if (typeof content[i] === "string") {
content[i] = DOMPurify.sanitize(content[i]);
2020-05-09 15:40:26 +02:00
}
if (typeof content[i] === "object" && cnt < 10) {
content[i] = escapeAllContentStrings(content[i], ++cnt);
}
2018-02-08 23:43:14 +01:00
}
return content;
2018-02-08 23:43:14 +01:00
}
2020-05-09 15:40:26 +02:00
process.on("unhandledRejection", (error) => {
// Will print "unhandledRejection err is not defined"
2020-05-09 15:40:26 +02:00
console.log("unhandledRejection", error.message);
});
2019-07-01 13:15:11 +02:00
}
2020-05-09 15:40:26 +02:00
module.exports = startBackendServer;