helpers.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * vim: ts=4:sw=4:expandtab
  3. */
  4. window.textsecure = window.textsecure || {};
  5. /*********************************
  6. *** Type conversion utilities ***
  7. *********************************/
  8. // Strings/arrays
  9. //TODO: Throw all this shit in favor of consistent types
  10. //TODO: Namespace
  11. var StaticByteBufferProto = new dcodeIO.ByteBuffer().__proto__;
  12. var StaticArrayBufferProto = new ArrayBuffer().__proto__;
  13. var StaticUint8ArrayProto = new Uint8Array().__proto__;
  14. function getString(thing) {
  15. if (thing === Object(thing)) {
  16. if (thing.__proto__ == StaticUint8ArrayProto)
  17. return String.fromCharCode.apply(null, thing);
  18. if (thing.__proto__ == StaticArrayBufferProto)
  19. return getString(new Uint8Array(thing));
  20. if (thing.__proto__ == StaticByteBufferProto)
  21. return thing.toString("binary");
  22. }
  23. return thing;
  24. }
  25. function getStringable(thing) {
  26. return (typeof thing == "string" || typeof thing == "number" || typeof thing == "boolean" ||
  27. (thing === Object(thing) &&
  28. (thing.__proto__ == StaticArrayBufferProto ||
  29. thing.__proto__ == StaticUint8ArrayProto ||
  30. thing.__proto__ == StaticByteBufferProto)));
  31. }
  32. // Number formatting utils
  33. window.textsecure.utils = function() {
  34. var self = {};
  35. self.unencodeNumber = function(number) {
  36. return number.split(".");
  37. };
  38. self.isNumberSane = function(number) {
  39. return number[0] == "+" &&
  40. /^[0-9]+$/.test(number.substring(1));
  41. }
  42. /**************************
  43. *** JSON'ing Utilities ***
  44. **************************/
  45. function ensureStringed(thing) {
  46. if (getStringable(thing))
  47. return getString(thing);
  48. else if (thing instanceof Array) {
  49. var res = [];
  50. for (var i = 0; i < thing.length; i++)
  51. res[i] = ensureStringed(thing[i]);
  52. return res;
  53. } else if (thing === Object(thing)) {
  54. var res = {};
  55. for (var key in thing)
  56. res[key] = ensureStringed(thing[key]);
  57. return res;
  58. } else if (thing === null) {
  59. return null;
  60. }
  61. throw new Error("unsure of how to jsonify object of type " + typeof thing);
  62. }
  63. self.jsonThing = function(thing) {
  64. return JSON.stringify(ensureStringed(thing));
  65. }
  66. return self;
  67. }();