trilium/services/utils.js

83 lines
1.7 KiB
JavaScript
Raw Normal View History

2017-10-22 09:10:33 +08:00
"use strict";
const crypto = require('crypto');
function newNoteId() {
2017-11-20 01:06:48 +08:00
return randomString(8);
}
2017-11-19 21:47:22 +08:00
function newNoteTreeId() {
2017-11-20 01:06:48 +08:00
return randomString(12);
2017-11-19 21:47:22 +08:00
}
function newNoteHistoryId() {
return randomString(12);
}
2017-10-29 00:12:20 +08:00
const ALPHA_NUMERIC = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function randomString(length) {
let result = '';
for (let i = length; i > 0; --i) {
2017-10-29 00:12:20 +08:00
result += ALPHA_NUMERIC[Math.floor(Math.random() * ALPHA_NUMERIC.length)];
}
return result;
}
function randomSecureToken(bytes = 32) {
2017-10-29 23:22:41 +08:00
return crypto.randomBytes(bytes).toString('base64');
}
function nowTimestamp() {
2017-10-16 05:07:34 +08:00
return Math.floor(Date.now() / 1000);
}
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-06 10:56:42 +08:00
function formatDateTimeFromTS(timestamp) {
const date = new Date(timestamp * 1000);
return date.toISOString();
}
function formatTwoTimestamps(origTS, newTS) {
return "orig: " + formatDateTimeFromTS(origTS) + ", new: " + formatDateTimeFromTS(newTS);
}
2017-11-22 11:11:27 +08:00
function hash(text) {
return crypto.createHash('sha1').update(text).digest('base64');
}
module.exports = {
randomSecureToken,
2017-10-29 00:12:20 +08:00
randomString,
nowTimestamp,
newNoteId,
2017-11-19 21:47:22 +08:00
newNoteTreeId,
newNoteHistoryId,
toBase64,
2017-10-30 02:55:48 +08:00
fromBase64,
hmac,
2017-11-06 10:56:42 +08:00
isElectron,
2017-11-22 11:11:27 +08:00
formatTwoTimestamps,
hash
};