helpers.ts 12 KB

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