signal-desktop/libtextsecure/helpers.js

71 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-07-21 21:51:20 +00:00
/* global window, dcodeIO */
/* eslint-disable no-proto, no-restricted-syntax, guard-for-in */
2014-05-17 05:53:58 +00:00
window.textsecure = window.textsecure || {};
2018-07-21 21:51:20 +00:00
/** *******************************
2014-01-12 07:32:13 +00:00
*** Type conversion utilities ***
2018-07-21 21:51:20 +00:00
******************************** */
2014-01-15 07:46:05 +00:00
// Strings/arrays
2018-07-21 21:51:20 +00:00
// TODO: Throw all this shit in favor of consistent types
// TODO: Namespace
const StaticByteBufferProto = new dcodeIO.ByteBuffer().__proto__;
const StaticArrayBufferProto = new ArrayBuffer().__proto__;
const StaticUint8ArrayProto = new Uint8Array().__proto__;
2014-01-12 07:32:13 +00:00
function getString(thing) {
if (thing === Object(thing)) {
2018-07-21 21:51:20 +00:00
if (thing.__proto__ === StaticUint8ArrayProto)
return String.fromCharCode.apply(null, thing);
2018-07-21 21:51:20 +00:00
if (thing.__proto__ === StaticArrayBufferProto)
return getString(new Uint8Array(thing));
2018-07-21 21:51:20 +00:00
if (thing.__proto__ === StaticByteBufferProto)
return thing.toString('binary');
}
return thing;
2014-01-12 07:32:13 +00:00
}
2014-03-05 01:31:15 +00:00
function getStringable(thing) {
return (
2018-07-21 21:51:20 +00:00
typeof thing === 'string' ||
typeof thing === 'number' ||
typeof thing === 'boolean' ||
(thing === Object(thing) &&
2018-07-21 21:51:20 +00:00
(thing.__proto__ === StaticArrayBufferProto ||
thing.__proto__ === StaticUint8ArrayProto ||
thing.__proto__ === StaticByteBufferProto))
);
2014-03-05 01:31:15 +00:00
}
// Number formatting utils
2018-07-21 21:51:20 +00:00
window.textsecure.utils = (() => {
const self = {};
self.unencodeNumber = number => number.split('.');
self.isNumberSane = number =>
number[0] === '+' && /^[0-9]+$/.test(number.substring(1));
2018-07-21 21:51:20 +00:00
/** ************************
*** JSON'ing Utilities ***
2018-07-21 21:51:20 +00:00
************************* */
function ensureStringed(thing) {
if (getStringable(thing)) return getString(thing);
else if (thing instanceof Array) {
2018-07-21 21:51:20 +00:00
const res = [];
for (let i = 0; i < thing.length; i += 1)
res[i] = ensureStringed(thing[i]);
return res;
} else if (thing === Object(thing)) {
2018-07-21 21:51:20 +00:00
const res = {};
for (const key in thing) res[key] = ensureStringed(thing[key]);
return res;
} else if (thing === null) {
return null;
}
2018-07-21 21:51:20 +00:00
throw new Error(`unsure of how to jsonify object of type ${typeof thing}`);
}
2018-07-21 21:51:20 +00:00
self.jsonThing = thing => JSON.stringify(ensureStringed(thing));
2014-05-25 22:45:22 +00:00
return self;
})();