helpers.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /**
  2. * This file is part of Threema Web.
  3. *
  4. * Threema Web is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU Affero General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. // tslint:disable:no-reference
  18. /// <reference path="threema.d.ts" />
  19. import {Logger} from 'ts-log';
  20. /**
  21. * Convert an Uint8Array to a hex string.
  22. *
  23. * Example:
  24. *
  25. * >>> u8aToHex(new Uint8Array([1, 255]))
  26. * "01ff"
  27. */
  28. export function u8aToHex(array: Uint8Array): string {
  29. const results: string[] = [];
  30. array.forEach((arrayByte) => {
  31. results.push(arrayByte.toString(16).replace(/^([\da-f])$/, '0$1'));
  32. });
  33. return results.join('');
  34. }
  35. /**
  36. * Convert a hexadecimal string to a Uint8Array.
  37. *
  38. * Example:
  39. *
  40. * >>> hexToU8a("01ff")
  41. * [1, 255]
  42. */
  43. export function hexToU8a(hexstring: string): Uint8Array {
  44. let array;
  45. let i;
  46. let j = 0;
  47. let k;
  48. let ref;
  49. // If number of characters is odd, add padding
  50. if (hexstring.length % 2 === 1) {
  51. hexstring = '0' + hexstring;
  52. }
  53. array = new Uint8Array(hexstring.length / 2);
  54. for (i = k = 0, ref = hexstring.length; k <= ref; i = k += 2) {
  55. array[j++] = parseInt(hexstring.substr(i, 2), 16);
  56. }
  57. return array;
  58. }
  59. /**
  60. * Convert an Uint8Array to a base 64 string.
  61. */
  62. export function u8aToBase64(array: Uint8Array): string {
  63. return btoa(Array.from(array, (byte: number) => String.fromCharCode(byte)).join(''));
  64. }
  65. /**
  66. * Convert a base 64 string to an Uint8Array.
  67. */
  68. export function base64ToU8a(base64String: string): Uint8Array {
  69. return Uint8Array.from(atob(base64String), (char: string) => char.charCodeAt(0));
  70. }
  71. /**
  72. * Generate a (non-cryptographically-secure!) random string.
  73. *
  74. * Based on http://stackoverflow.com/a/1349426/284318.
  75. */
  76. export function randomString(
  77. length = 32,
  78. chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
  79. ): string {
  80. let str = '';
  81. for (let i = 0; i < length; i++) {
  82. str += chars.charAt(Math.floor(Math.random() * chars.length));
  83. }
  84. return str;
  85. }
  86. /* tslint:disable */
  87. /**
  88. * Convert a JS string to a UTF-8 "byte" array.
  89. *
  90. * Copyright 2008 The Closure Library Authors. All Rights Reserved.
  91. *
  92. * Licensed under the Apache License, Version 2.0 (the "License");
  93. * you may not use this file except in compliance with the License.
  94. * You may obtain a copy of the License at
  95. *
  96. * http://www.apache.org/licenses/LICENSE-2.0
  97. *
  98. * Unless required by applicable law or agreed to in writing, software
  99. * distributed under the License is distributed on an "AS-IS" BASIS,
  100. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  101. * See the License for the specific language governing permissions and
  102. * limitations under the License.
  103. *
  104. * https://github.com/google/closure-library/commit/e877b1eac410c0d842bcda118689759512e0e26f
  105. *
  106. * @param {string} str 16-bit unicode string.
  107. * @return {!Array<number>} UTF-8 byte array.
  108. */
  109. export function stringToUtf8a(str: string): Uint8Array {
  110. var out = [], p = 0;
  111. for (var i = 0; i < str.length; i++) {
  112. var c = str.charCodeAt(i);
  113. if (c < 128) {
  114. out[p++] = c;
  115. } else if (c < 2048) {
  116. out[p++] = (c >> 6) | 192;
  117. out[p++] = (c & 63) | 128;
  118. } else if (
  119. ((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&
  120. ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {
  121. // Surrogate Pair
  122. c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
  123. out[p++] = (c >> 18) | 240;
  124. out[p++] = ((c >> 12) & 63) | 128;
  125. out[p++] = ((c >> 6) & 63) | 128;
  126. out[p++] = (c & 63) | 128;
  127. } else {
  128. out[p++] = (c >> 12) | 224;
  129. out[p++] = ((c >> 6) & 63) | 128;
  130. out[p++] = (c & 63) | 128;
  131. }
  132. }
  133. return Uint8Array.from(out);
  134. }
  135. /**
  136. * Convert a UTF-8 byte array to JavaScript's 16-bit Unicode.
  137. *
  138. * Copyright 2008 The Closure Library Authors. All Rights Reserved.
  139. *
  140. * Licensed under the Apache License, Version 2.0 (the "License");
  141. * you may not use this file except in compliance with the License.
  142. * You may obtain a copy of the License at
  143. *
  144. * http://www.apache.org/licenses/LICENSE-2.0
  145. *
  146. * Unless required by applicable law or agreed to in writing, software
  147. * distributed under the License is distributed on an "AS-IS" BASIS,
  148. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  149. * See the License for the specific language governing permissions and
  150. * limitations under the License.
  151. *
  152. * https://github.com/google/closure-library/commit/e877b1eac410c0d842bcda118689759512e0e26f
  153. *
  154. * @param {Uint8Array|Array<number>} bytes UTF-8 byte array.
  155. * @return {string} 16-bit Unicode string.
  156. */
  157. export function utf8aToString(bytes: Uint8Array): string {
  158. var out = [], pos = 0, c = 0;
  159. while (pos < bytes.length) {
  160. var c1 = bytes[pos++];
  161. if (c1 < 128) {
  162. out[c++] = String.fromCharCode(c1);
  163. } else if (c1 > 191 && c1 < 224) {
  164. var c2 = bytes[pos++];
  165. out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63);
  166. } else if (c1 > 239 && c1 < 365) {
  167. // Surrogate Pair
  168. var c2 = bytes[pos++];
  169. var c3 = bytes[pos++];
  170. var c4 = bytes[pos++];
  171. var u = ((c1 & 7) << 18 | (c2 & 63) << 12 | (c3 & 63) << 6 | c4 & 63) - 0x10000;
  172. out[c++] = String.fromCharCode(0xD800 + (u >> 10));
  173. out[c++] = String.fromCharCode(0xDC00 + (u & 1023));
  174. } else {
  175. var c2 = bytes[pos++];
  176. var c3 = bytes[pos++];
  177. out[c++] = String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
  178. }
  179. }
  180. return out.join('');
  181. }
  182. /* tslint:enable */
  183. /**
  184. * Filter an array or object.
  185. */
  186. export function filter(obj: object | any[], callback: (arg: any) => boolean) {
  187. if (obj instanceof Array) {
  188. // Filter arrays using Array.filter
  189. return (obj as any[]).filter(callback);
  190. } else {
  191. // Filter objects by iterating over them
  192. // and selectively copying values
  193. const out = {};
  194. for (const key in Object.keys(obj)) { // tslint:disable-line:forin
  195. const value = obj[key];
  196. if (callback(value)) {
  197. out[key] = value;
  198. }
  199. }
  200. return out;
  201. }
  202. }
  203. /**
  204. * Check whether a variable is a string.
  205. */
  206. export function isString(val: any): boolean {
  207. return typeof val === 'string' || val instanceof String;
  208. }
  209. /**
  210. * Detect whether browser supports passive event listeners.
  211. *
  212. * Taken from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  213. */
  214. export function supportsPassive(): boolean {
  215. // Test via a getter in the options object to see if the passive property is accessed
  216. let support = false;
  217. try {
  218. const opts = Object.defineProperty({}, 'passive', {
  219. get: () => support = true,
  220. });
  221. window.addEventListener('test', null, opts);
  222. } catch (e) { /* do nothing */ }
  223. return support;
  224. }
  225. /**
  226. * Excape a RegEx, so that none of the string characters are considered special characters.
  227. *
  228. * Taken from https://stackoverflow.com/a/17606289/284318
  229. */
  230. export function escapeRegExp(str: string) {
  231. return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  232. }
  233. /**
  234. * Generate a link to the msgpack visualizer from an Uint8Array containing
  235. * msgpack encoded data.
  236. */
  237. export function msgpackVisualizer(array: Uint8Array): string {
  238. return 'https://msgpack.dbrgn.ch#base64=' + encodeURIComponent(u8aToBase64(array));
  239. }
  240. /**
  241. * Check the featureMask of a contactReceiver
  242. */
  243. export function hasFeature(contactReceiver: threema.ContactReceiver,
  244. feature: threema.ContactReceiverFeature,
  245. log: Logger): boolean {
  246. if (contactReceiver !== undefined) {
  247. if (contactReceiver.featureMask === 0) {
  248. log.warn(`Contact receiver with id ${contactReceiver.id} has featureMask 0`);
  249. return false;
  250. }
  251. if (feature === threema.ContactReceiverFeature.NONE) {
  252. return true;
  253. }
  254. // tslint:disable:no-bitwise
  255. return (contactReceiver.featureMask & feature) !== 0;
  256. // tslint:enable:no-bitwise
  257. }
  258. log.warn('Cannot check featureMask of an undefined contact receiver');
  259. return false;
  260. }
  261. /**
  262. * Convert an ArrayBuffer to a data URL.
  263. */
  264. export function bufferToUrl(buffer: ArrayBuffer, mimeType: string, log: Logger): string {
  265. switch (mimeType) {
  266. case 'image/jpg':
  267. case 'image/jpeg':
  268. case 'image/png':
  269. case 'image/webp':
  270. case 'image/gif':
  271. case 'audio/mp4':
  272. case 'audio/aac':
  273. case 'audio/ogg':
  274. case 'audio/webm':
  275. // OK
  276. break;
  277. default:
  278. const fallbackMimeType = 'image/jpeg';
  279. log.warn(`Unknown mimeType "${mimeType}", falling back to "${fallbackMimeType}"`);
  280. mimeType = fallbackMimeType;
  281. break;
  282. }
  283. return 'data:' + mimeType + ';base64,' + u8aToBase64(new Uint8Array(buffer));
  284. }
  285. /**
  286. * Convert a TypedArray to an ArrayBuffer.
  287. *
  288. * **Important:** If the source array's data occupies the underlying buffer
  289. * completely, the underlying buffer will be returned directly. Thus, the
  290. * caller may not assume that the data has been copied.
  291. */
  292. export function arrayToBuffer(array: ArrayBufferView): ArrayBuffer {
  293. if (array.byteOffset === 0 && array.byteLength === array.buffer.byteLength) {
  294. return array.buffer;
  295. }
  296. return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength);
  297. }
  298. /**
  299. * Return whether a value is not null and not undefined.
  300. */
  301. export function hasValue<T>(val?: T | null): val is T {
  302. return val !== null && val !== undefined;
  303. }
  304. /**
  305. * Awaitable timeout function.
  306. */
  307. export function sleep(ms: number): Promise<void> {
  308. return new Promise((resolve) => setTimeout(resolve, ms));
  309. }
  310. /**
  311. * Compare two Uint8Array instances. Return true if all elements are equal
  312. * (compared using ===).
  313. */
  314. export function arraysAreEqual(a1: Uint8Array, a2: Uint8Array): boolean {
  315. if (a1.length !== a2.length) {
  316. return false;
  317. }
  318. for (let i = 0; i < a1.length; i++) {
  319. if (a1[i] !== a2[i]) {
  320. return false;
  321. }
  322. }
  323. return true;
  324. }
  325. /*
  326. * Return whether this key event should trigger a button.
  327. * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
  328. */
  329. export function isActionTrigger(ev: KeyboardEvent): boolean {
  330. if (ev.key === undefined) {
  331. return false;
  332. }
  333. switch (ev.key) {
  334. case 'Enter':
  335. case ' ':
  336. return true;
  337. default:
  338. return false;
  339. }
  340. }
  341. /**
  342. * Create a shallow copy of an object.
  343. */
  344. export function copyShallow(object: object): object {
  345. return Object.assign({}, object);
  346. }
  347. /**
  348. * Create a deep copy (mostly).
  349. *
  350. * This handles the following types:
  351. *
  352. * - copies `undefined` and `null`,
  353. * - copies `Boolean`, `Number` and `String`,
  354. * - copies `object` recursively,
  355. * - copies `Array` recursively,
  356. * - copies `ArrayBuffer`,
  357. * - copies `Uint8Array`,
  358. *
  359. * Everything else will be **referenced**.
  360. */
  361. export function copyDeepOrReference(value: any): any {
  362. // Handle `null` and `undefined` early
  363. if (value === null || value === undefined) {
  364. return value;
  365. }
  366. // Plain object
  367. if (value.constructor === Object) {
  368. const object = {};
  369. for (const [k, v] of Object.entries(value)) {
  370. object[k] = copyDeepOrReference(v);
  371. }
  372. return object;
  373. }
  374. // Plain array
  375. if (value instanceof Array) {
  376. return value.map((item) => copyDeepOrReference(item));
  377. }
  378. // ArrayBuffer
  379. if (value instanceof ArrayBuffer) {
  380. return value.slice(0);
  381. }
  382. // Uint8Array
  383. if (value instanceof Uint8Array) {
  384. // Note: To mimic the byte offset, we copy the whole underlying buffer.
  385. const buffer = value.buffer.slice(0);
  386. return new Uint8Array(buffer, value.byteOffset, value.byteLength);
  387. }
  388. // Reference everything else
  389. return value;
  390. }
  391. /**
  392. * Replace spaces with `&nbsp;` and tabs with `&nbsp;&nbsp;`.
  393. */
  394. export function replaceWhitespace(text: string): string {
  395. return text
  396. .replace(/ /g, '&nbsp;')
  397. .replace(/\t/, '&nbsp;&nbsp;');
  398. }