Notes/services/utils.js

107 lines
2.2 KiB
JavaScript
Raw Normal View History

2017-10-21 21:10:33 -04:00
"use strict";
const crypto = require('crypto');
const randtoken = require('rand-token').generator({source: 'crypto'});
function newNoteId() {
return randomString(12);
}
2017-11-19 08:47:22 -05:00
function newNoteTreeId() {
2017-11-19 12:06:48 -05:00
return randomString(12);
2017-11-19 08:47:22 -05:00
}
function newNoteHistoryId() {
return randomString(12);
}
function randomString(length) {
return randtoken.generate(length);
}
function randomSecureToken(bytes = 32) {
2017-10-29 11:22:41 -04:00
return crypto.randomBytes(bytes).toString('base64');
}
function nowTimestamp() {
2017-10-15 17:07:34 -04:00
return Math.floor(Date.now() / 1000);
}
function nowDate() {
return dateStr(new Date());
}
function dateStr(date) {
return date.toISOString().replace("T", " ").replace("Z", "");
}
/**
* @param str - needs to be in the "YYYY-MM-DD HH:MM:SS.sss" format as outputted by dateStr().
* also is assumed to be GMT time, *not* local time
*/
function parseDate(str) {
try {
const isoDate = str.replace(" ", "T") + "Z";
return new Date(Date.parse(isoDate));
}
catch (e) {
throw new Error("Can't parse date from " + str + ": " + e.stack);
}
}
function toBase64(plainText) {
return Buffer.from(plainText).toString('base64');
}
function fromBase64(encodedText) {
return Buffer.from(encodedText, 'base64');
}
2017-10-29 14:55:48 -04: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-05 21:56:42 -05: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-21 22:11:27 -05:00
function hash(text) {
return crypto.createHash('sha1').update(text).digest('base64');
}
function isEmptyOrWhitespace(str) {
return str === null || str.match(/^ *$/) !== null;
}
2017-11-21 22:11:27 -05:00
module.exports = {
randomSecureToken,
2017-10-28 12:12:20 -04:00
randomString,
nowTimestamp,
nowDate,
dateStr,
parseDate,
newNoteId,
2017-11-19 08:47:22 -05:00
newNoteTreeId,
newNoteHistoryId,
toBase64,
2017-10-29 14:55:48 -04:00
fromBase64,
hmac,
2017-11-05 21:56:42 -05:00
isElectron,
2017-11-21 22:11:27 -05:00
formatTwoTimestamps,
hash,
isEmptyOrWhitespace
};