Notes/src/routes/custom.js

89 lines
2.6 KiB
JavaScript
Raw Normal View History

const log = require('../services/log');
const fileService = require('./api/files.js');
const scriptService = require('../services/script.js');
2024-02-16 21:18:38 +02:00
const cls = require('../services/cls');
2024-02-16 22:44:12 +02:00
const sql = require('../services/sql');
const becca = require('../becca/becca');
function handleRequest(req, res) {
// express puts content after first slash into 0 index element
const path = req.params.path + req.params[0];
2021-05-02 19:59:16 +02:00
const attributeIds = sql.getColumn("SELECT attributeId FROM attributes WHERE isDeleted = 0 AND type = 'label' AND name IN ('customRequestHandler', 'customResourceProvider')");
const attrs = attributeIds.map(attrId => becca.getAttribute(attrId));
2019-01-27 15:47:40 +01:00
for (const attr of attrs) {
if (!attr.value.trim()) {
continue;
}
2023-04-22 19:37:49 +08:00
const regex = new RegExp(`^${attr.value}$`);
let match;
try {
match = path.match(regex);
}
catch (e) {
2023-05-03 10:23:20 +02:00
log.error(`Testing path for label '${attr.attributeId}', regex '${attr.value}' failed with error: ${e.message}, stack: ${e.stack}`);
continue;
}
if (!match) {
continue;
}
2019-01-27 15:47:40 +01:00
if (attr.name === 'customRequestHandler') {
const note = attr.getNote();
2023-05-03 10:23:20 +02:00
log.info(`Handling custom request '${path}' with note '${note.noteId}'`);
try {
scriptService.executeNote(note, {
pathParams: match.slice(1),
req,
res
});
}
catch (e) {
2023-05-03 10:23:20 +02:00
log.error(`Custom handler '${note.noteId}' failed with: ${e.message}, ${e.stack}`);
2019-01-27 16:37:18 +01:00
res.setHeader("Content-Type", "text/plain")
.status(500)
.send(e.message);
2019-01-27 16:37:18 +01:00
}
}
else if (attr.name === 'customResourceProvider') {
2023-05-03 10:23:20 +02:00
fileService.downloadNoteInt(attr.noteId, res);
}
else {
2023-05-03 10:23:20 +02:00
throw new Error(`Unrecognized attribute name '${attr.name}'`);
}
2019-01-27 16:37:18 +01:00
2023-05-05 23:41:11 +02:00
return; // only the first handler is executed
}
2019-01-27 16:37:18 +01:00
2023-05-03 10:23:20 +02:00
const message = `No handler matched for custom '${path}' request.`;
log.info(message);
res.setHeader("Content-Type", "text/plain")
.status(404)
.send(message);
}
2019-01-27 16:37:18 +01:00
function register(router) {
// explicitly no CSRF middleware since it's meant to allow integration from external services
router.all('/custom/:path*', (req, res, next) => {
cls.namespace.bindEmitter(req);
cls.namespace.bindEmitter(res);
2019-01-27 15:47:40 +01:00
cls.init(() => handleRequest(req, res));
});
}
module.exports = {
register
2020-06-20 12:31:38 +02:00
};