helpers.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. * Throttle function.
  211. *
  212. * Taken from https://remysharp.com/2010/07/21/throttling-function-calls
  213. */
  214. export function throttle(fn, threshold: number = 250, scope) {
  215. let last;
  216. let deferTimer;
  217. return function() {
  218. const context = scope || this;
  219. const now = +(new Date());
  220. const args = arguments;
  221. if (last && now < last + threshold) {
  222. // hold on to it
  223. clearTimeout(deferTimer);
  224. deferTimer = setTimeout(function() {
  225. last = now;
  226. fn.apply(context, args);
  227. }, threshold);
  228. } else {
  229. last = now;
  230. fn.apply(context, args);
  231. }
  232. };
  233. }
  234. /**
  235. * Detect whether browser supports passive event listeners.
  236. *
  237. * Taken from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  238. */
  239. export function supportsPassive(): boolean {
  240. // Test via a getter in the options object to see if the passive property is accessed
  241. let support = false;
  242. try {
  243. const opts = Object.defineProperty({}, 'passive', {
  244. get: () => support = true,
  245. });
  246. window.addEventListener('test', null, opts);
  247. } catch (e) { /* do nothing */ }
  248. return support;
  249. }
  250. /**
  251. * Excape a RegEx, so that none of the string characters are considered special characters.
  252. *
  253. * Taken from https://stackoverflow.com/a/17606289/284318
  254. */
  255. export function escapeRegExp(str: string) {
  256. return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  257. }
  258. /**
  259. * Generate a link to the msgpack visualizer from an Uint8Array containing
  260. * msgpack encoded data.
  261. */
  262. export function msgpackVisualizer(array: Uint8Array): string {
  263. return 'https://msgpack.dbrgn.ch#base64=' + encodeURIComponent(u8aToBase64(array));
  264. }
  265. /**
  266. * Check the featureMask of a contactReceiver
  267. */
  268. export function hasFeature(contactReceiver: threema.ContactReceiver,
  269. feature: threema.ContactReceiverFeature,
  270. log: Logger): boolean {
  271. if (contactReceiver !== undefined) {
  272. if (contactReceiver.featureMask === 0) {
  273. log.warn(`Contact receiver with id ${contactReceiver.id} has featureMask 0`);
  274. return false;
  275. }
  276. // tslint:disable:no-bitwise
  277. return (contactReceiver.featureMask & feature) !== 0;
  278. // tslint:enable:no-bitwise
  279. }
  280. log.warn('Cannot check featureMask of a undefined contact receiver');
  281. return false;
  282. }
  283. /**
  284. * Convert an ArrayBuffer to a data URL.
  285. */
  286. export function bufferToUrl(buffer: ArrayBuffer, mimeType: string, log: Logger): string {
  287. switch (mimeType) {
  288. case 'image/jpg':
  289. case 'image/jpeg':
  290. case 'image/png':
  291. case 'image/webp':
  292. case 'image/gif':
  293. case 'audio/mp4':
  294. case 'audio/aac':
  295. case 'audio/ogg':
  296. case 'audio/webm':
  297. // OK
  298. break;
  299. default:
  300. const fallbackMimeType = 'image/jpeg';
  301. log.warn(`Unknown mimeType "${mimeType}", falling back to "${fallbackMimeType}"`);
  302. mimeType = fallbackMimeType;
  303. break;
  304. }
  305. return 'data:' + mimeType + ';base64,' + u8aToBase64(new Uint8Array(buffer));
  306. }
  307. /**
  308. * Return whether a value is not null and not undefined.
  309. */
  310. export function hasValue<T>(val?: T | null): val is T {
  311. return val !== null && val !== undefined;
  312. }
  313. /**
  314. * Awaitable timeout function.
  315. */
  316. export function sleep(ms: number): Promise<void> {
  317. return new Promise((resolve) => setTimeout(resolve, ms));
  318. }
  319. /**
  320. * Compare two Uint8Array instances. Return true if all elements are equal
  321. * (compared using ===).
  322. */
  323. export function arraysAreEqual(a1: Uint8Array, a2: Uint8Array): boolean {
  324. if (a1.length !== a2.length) {
  325. return false;
  326. }
  327. for (let i = 0; i < a1.length; i++) {
  328. if (a1[i] !== a2[i]) {
  329. return false;
  330. }
  331. }
  332. return true;
  333. }
  334. /*
  335. * Return whether this key event should trigger a button.
  336. * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
  337. */
  338. export function isActionTrigger(ev: KeyboardEvent): boolean {
  339. if (ev.key === undefined) {
  340. return false;
  341. }
  342. switch (ev.key) {
  343. case 'Enter':
  344. case ' ':
  345. return true;
  346. default:
  347. return false;
  348. }
  349. }
  350. /**
  351. * Create a shallow copy of an object.
  352. */
  353. export function copyShallow(object: object): object {
  354. return Object.assign({}, object);
  355. }
  356. /**
  357. * Create a deep copy (mostly).
  358. *
  359. * This handles the following types:
  360. *
  361. * - copies `undefined` and `null`,
  362. * - copies `Boolean`, `Number` and `String`,
  363. * - copies `object` recursively,
  364. * - copies `Array` recursively,
  365. * - copies `ArrayBuffer`,
  366. * - copies `Uint8Array`,
  367. *
  368. * Everything else will be **referenced**.
  369. */
  370. export function copyDeepOrReference(value: any): any {
  371. // Handle `null` and `undefined` early
  372. if (value === null || value === undefined) {
  373. return value;
  374. }
  375. // Plain object
  376. if (value.constructor === Object) {
  377. const object = {};
  378. for (const [k, v] of Object.entries(value)) {
  379. object[k] = copyDeepOrReference(v);
  380. }
  381. return object;
  382. }
  383. // Plain array
  384. if (value instanceof Array) {
  385. return value.map((item) => copyDeepOrReference(item));
  386. }
  387. // ArrayBuffer
  388. if (value instanceof ArrayBuffer) {
  389. return value.slice(0);
  390. }
  391. // Uint8Array
  392. if (value instanceof Uint8Array) {
  393. // Note: To mimic the byte offset, we copy the whole underlying buffer.
  394. const buffer = value.buffer.slice(0);
  395. return new Uint8Array(buffer, value.byteOffset, value.byteLength);
  396. }
  397. // Reference everything else
  398. return value;
  399. }
  400. /**
  401. * Replace spaces with `&nbsp;` and tabs with `&nbsp;&nbsp;`.
  402. */
  403. export function replaceWhitespace(text: string): string {
  404. return text
  405. .replace(/ /g, '&nbsp;')
  406. .replace(/\t/, '&nbsp;&nbsp;');
  407. }