trilium/src/services/utils.js

92 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-10-22 09:10:33 +08:00
"use strict";
const crypto = require('crypto');
const randtoken = require('rand-token').generator({source: 'crypto'});
const unescape = require('unescape');
2018-04-03 08:30:00 +08:00
function newEntityId() {
2018-02-11 13:18:59 +08:00
return randomString(12);
}
function randomString(length) {
return randtoken.generate(length);
}
function randomSecureToken(bytes = 32) {
2017-10-29 23:22:41 +08:00
return crypto.randomBytes(bytes).toString('base64');
}
function toBase64(plainText) {
return Buffer.from(plainText).toString('base64');
}
function fromBase64(encodedText) {
return Buffer.from(encodedText, 'base64');
}
2017-10-30 02:55:48 +08:00
function hmac(secret, value) {
const hmac = crypto.createHmac('sha256', Buffer.from(secret.toString(), 'ASCII'));
hmac.update(value.toString());
return hmac.digest('base64');
}
function isElectron() {
return !!process.versions['electron'];
}
2017-11-22 11:11:27 +08:00
function hash(text) {
return crypto.createHash('sha1').update(text).digest('base64');
}
function isEmptyOrWhitespace(str) {
return str === null || str.match(/^ *$/) !== null;
}
function sanitizeSql(str) {
// should be improved or usage eliminated
return str.replace(/'/g, "\\'");
}
async function stopWatch(what, func) {
const start = new Date();
const ret = await func();
const tookMs = new Date().getTime() - start.getTime();
console.log(`${what} took ${tookMs}ms`);
return ret;
}
function unescapeHtml(str) {
return unescape(str);
}
2018-03-05 01:06:35 +08:00
function toObject(array, fn) {
const obj = {};
for (const item of array) {
const ret = fn(item);
obj[ret[0]] = ret[1];
}
return obj;
}
module.exports = {
randomSecureToken,
2017-10-29 00:12:20 +08:00
randomString,
2018-04-03 08:30:00 +08:00
newEntityId,
toBase64,
2017-10-30 02:55:48 +08:00
fromBase64,
hmac,
2017-11-06 10:56:42 +08:00
isElectron,
hash,
2017-12-16 13:05:37 +08:00
isEmptyOrWhitespace,
2018-01-07 04:56:00 +08:00
sanitizeSql,
stopWatch,
2018-03-05 01:06:35 +08:00
unescapeHtml,
toObject
};