Selaa lähdekoodia

Use `crypto.randomUUID()` if available

JC Brand 2 vuotta sitten
vanhempi
commit
fdcab413f5
2 muutettua tiedostoa jossa 14 lisäystä ja 11 poistoa
  1. 10 8
      src/headless/utils/core.js
  2. 4 3
      src/plugins/omemo/device.js

+ 10 - 8
src/headless/utils/core.js

@@ -437,9 +437,9 @@ u.getSelectValues = function (select) {
     return result;
 };
 
-u.getRandomInt = function (max) {
-    return Math.floor(Math.random() * Math.floor(max));
-};
+export function getRandomInt (max) {
+    return (Math.random() * max) | 0;
+}
 
 u.placeCaretAtEnd = function (textarea) {
     if (textarea !== document.activeElement) {
@@ -455,11 +455,12 @@ u.placeCaretAtEnd = function (textarea) {
 };
 
 export function getUniqueId (suffix) {
-    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
-        const r = Math.random() * 16 | 0;
-        const v = c === 'x' ? r : r & 0x3 | 0x8;
-        return v.toString(16);
-    });
+    const uuid = crypto.randomUUID?.() ??
+        'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
+            const r = getRandomInt(16);
+            const v = c === 'x' ? r : r & 0x3 | 0x8;
+            return v.toString(16);
+        });
     if (typeof(suffix) === "string" || typeof(suffix) === "number") {
         return uuid + ":" + suffix;
     } else {
@@ -578,6 +579,7 @@ export function decodeHTMLEntities (str) {
 }
 
 export default Object.assign({
+    getRandomInt,
     getUniqueId,
     isEmptyMessage,
     isValidJID,

+ 4 - 3
src/plugins/omemo/device.js

@@ -2,10 +2,11 @@ import log from '@converse/headless/log';
 import { IQError } from './errors.js';
 import { Model } from '@converse/skeletor/src/model.js';
 import { UNDECIDED } from './consts.js';
-import { _converse, api, converse } from '@converse/headless/core';
+import { _converse, api, converse } from '@converse/headless/core.js';
+import { getRandomInt } from '@converse/headless/utils/core.js';
 import { parseBundle } from './utils.js';
 
-const { Strophe, sizzle, u, $iq } = converse.env;
+const { Strophe, sizzle, $iq } = converse.env;
 
 
 /**
@@ -22,7 +23,7 @@ const Device = Model.extend({
     getRandomPreKey () {
         // XXX: assumes that the bundle has already been fetched
         const bundle = this.get('bundle');
-        return bundle.prekeys[u.getRandomInt(bundle.prekeys.length)];
+        return bundle.prekeys[getRandomInt(bundle.prekeys.length)];
     },
 
     async fetchBundleFromServer () {