Merge branch 'develop' of github.com:matrix-org/matrix-react-sdk into t3chguy/fix/18969

 Conflicts:
	src/components/views/dialogs/LeaveSpaceDialog.tsx
	src/i18n/strings/en_EN.json
This commit is contained in:
Michael Telatynski 2021-09-27 11:18:57 +01:00
commit 6d0af83df4
236 changed files with 4971 additions and 17999 deletions

View file

@ -14,9 +14,12 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import { IInstance } from "matrix-js-sdk/src/client";
import { Protocols } from "../components/views/directory/NetworkDropdown";
// Find a protocol 'instance' with a given instance_id
// in the supplied protocols dict
export function instanceForInstanceId(protocols, instanceId) {
export function instanceForInstanceId(protocols: Protocols, instanceId: string): IInstance {
if (!instanceId) return null;
for (const proto of Object.keys(protocols)) {
if (!protocols[proto].instances && protocols[proto].instances instanceof Array) continue;
@ -28,7 +31,7 @@ export function instanceForInstanceId(protocols, instanceId) {
// given an instance_id, return the name of the protocol for
// that instance ID in the supplied protocols dict
export function protocolNameForInstanceId(protocols, instanceId) {
export function protocolNameForInstanceId(protocols: Protocols, instanceId: string): string {
if (!instanceId) return null;
for (const proto of Object.keys(protocols)) {
if (!protocols[proto].instances && protocols[proto].instances instanceof Array) continue;

View file

@ -20,9 +20,10 @@ limitations under the License.
* author Roel Nieskens, https://pixelambacht.nl
* MIT license
*/
import { logger } from "matrix-js-sdk/src/logger";
function safariVersionCheck(ua: string): boolean {
console.log("Browser is Safari - checking version for COLR support");
logger.log("Browser is Safari - checking version for COLR support");
try {
const safariVersionMatch = ua.match(/Mac OS X ([\d|_]+).*Version\/([\d|.]+).*Safari/);
if (safariVersionMatch) {
@ -32,7 +33,7 @@ function safariVersionCheck(ua: string): boolean {
const safariVersion = safariVersionStr.split(".").map(n => parseInt(n, 10));
const colrFontSupported = macOSVersion[0] >= 10 && macOSVersion[1] >= 14 && safariVersion[0] >= 12;
// https://www.colorfonts.wtf/ states safari supports COLR fonts from this version on
console.log(`COLR support on Safari requires macOS 10.14 and Safari 12, ` +
logger.log(`COLR support on Safari requires macOS 10.14 and Safari 12, ` +
`detected Safari ${safariVersionStr} on macOS ${macOSVersionStr}, ` +
`COLR supported: ${colrFontSupported}`);
return colrFontSupported;
@ -45,7 +46,7 @@ function safariVersionCheck(ua: string): boolean {
}
async function isColrFontSupported(): Promise<boolean> {
console.log("Checking for COLR support");
logger.log("Checking for COLR support");
const { userAgent } = navigator;
// Firefox has supported COLR fonts since version 26
@ -53,7 +54,7 @@ async function isColrFontSupported(): Promise<boolean> {
// "Extract canvas data" permissions
// when content blocking is enabled.
if (userAgent.includes("Firefox")) {
console.log("Browser is Firefox - assuming COLR is supported");
logger.log("Browser is Firefox - assuming COLR is supported");
return true;
}
// Safari doesn't wait for the font to load (if it doesn't have it in cache)
@ -87,12 +88,12 @@ async function isColrFontSupported(): Promise<boolean> {
img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
console.log("Waiting for COLR SVG to load");
logger.log("Waiting for COLR SVG to load");
await new Promise(resolve => img.onload = resolve);
console.log("Drawing canvas to detect COLR support");
logger.log("Drawing canvas to detect COLR support");
context.drawImage(img, 0, 0);
const colrFontSupported = (context.getImageData(10, 10, 1, 1).data[0] === 200);
console.log("Canvas check revealed COLR is supported? " + colrFontSupported);
logger.log("Canvas check revealed COLR is supported? " + colrFontSupported);
return colrFontSupported;
} catch (e) {
console.error("Couldn't load COLR font", e);

View file

@ -104,7 +104,10 @@ export function getUserNameColorClass(userId: string): string {
* @returns {string} a string constructed by joining `items` with a comma
* between each item, but with the last item appended as " and [lastItem]".
*/
export function formatCommaSeparatedList(items: Array<string | JSX.Element>, itemLimit?: number): string | JSX.Element {
export function formatCommaSeparatedList(items: string[], itemLimit?: number): string;
export function formatCommaSeparatedList(items: JSX.Element[], itemLimit?: number): JSX.Element;
export function formatCommaSeparatedList(items: Array<JSX.Element | string>, itemLimit?: number): JSX.Element | string;
export function formatCommaSeparatedList(items: Array<JSX.Element | string>, itemLimit?: number): JSX.Element | string {
const remaining = itemLimit === undefined ? 0 : Math.max(
items.length - itemLimit, 0,
);
@ -112,11 +115,25 @@ export function formatCommaSeparatedList(items: Array<string | JSX.Element>, ite
return "";
} else if (items.length === 1) {
return items[0];
} else if (remaining > 0) {
items = items.slice(0, itemLimit);
return _t("%(items)s and %(count)s others", { items: jsxJoin(items, ', '), count: remaining } );
} else {
const lastItem = items.pop();
return _t("%(items)s and %(lastItem)s", { items: jsxJoin(items, ', '), lastItem: lastItem });
let lastItem;
if (remaining > 0) {
items = items.slice(0, itemLimit);
} else {
lastItem = items.pop();
}
let joinedItems;
if (items.every(e => typeof e === "string")) {
joinedItems = items.join(", ");
} else {
joinedItems = jsxJoin(items, ", ");
}
if (remaining > 0) {
return _t("%(items)s and %(count)s others", { items: joinedItems, count: remaining } );
} else {
return _t("%(items)s and %(lastItem)s", { items: joinedItems, lastItem });
}
}
}

View file

@ -17,7 +17,7 @@ limitations under the License.
import SdkConfig from '../SdkConfig';
import { MatrixClientPeg } from '../MatrixClientPeg';
export function getHostingLink(campaign) {
export function getHostingLink(campaign: string): string {
const hostingLink = SdkConfig.get().hosting_signup_link;
if (!hostingLink) return null;
if (!campaign) return hostingLink;
@ -27,7 +27,7 @@ export function getHostingLink(campaign) {
try {
const hostingUrl = new URL(hostingLink);
hostingUrl.searchParams.set("utm_campaign", campaign);
return hostingUrl.format();
return hostingUrl.toString();
} catch (e) {
return hostingLink;
}

View file

@ -17,14 +17,14 @@ limitations under the License.
import { MatrixClientPeg } from '../MatrixClientPeg';
import { _t } from '../languageHandler';
export function getNameForEventRoom(userId, roomId) {
export function getNameForEventRoom(userId: string, roomId: string): string {
const client = MatrixClientPeg.get();
const room = client.getRoom(roomId);
const member = room && room.getMember(userId);
return member ? member.name : userId;
}
export function userLabelForEventRoom(userId, roomId) {
export function userLabelForEventRoom(userId: string, roomId: string): string {
const name = getNameForEventRoom(userId, roomId);
if (name !== userId) {
return _t("%(name)s (%(userId)s)", { name, userId });

View file

@ -18,23 +18,25 @@ limitations under the License.
import { _t } from '../languageHandler';
import SdkConfig from '../SdkConfig';
import { logger } from "matrix-js-sdk/src/logger";
const subtleCrypto = window.crypto.subtle || window.crypto.webkitSubtle;
/**
* Make an Error object which has a friendlyText property which is already
* translated and suitable for showing to the user.
*
* @param {string} msg message for the exception
* @param {string} message message for the exception
* @param {string} friendlyText
* @returns {Error}
* @returns {{message: string, friendlyText: string}}
*/
function friendlyError(msg, friendlyText) {
const e = new Error(msg);
e.friendlyText = friendlyText;
return e;
function friendlyError(
message: string, friendlyText: string,
): { message: string, friendlyText: string } {
return { message, friendlyText };
}
function cryptoFailMsg() {
function cryptoFailMsg(): string {
return _t('Your browser does not support the required cryptography extensions');
}
@ -47,7 +49,7 @@ function cryptoFailMsg() {
*
*
*/
export async function decryptMegolmKeyFile(data, password) {
export async function decryptMegolmKeyFile(data: ArrayBuffer, password: string): Promise<string> {
const body = unpackMegolmKeyFile(data);
const brand = SdkConfig.get().brand;
@ -122,7 +124,11 @@ export async function decryptMegolmKeyFile(data, password) {
* key-derivation function.
* @return {Promise<ArrayBuffer>} promise for encrypted output
*/
export async function encryptMegolmKeyFile(data, password, options) {
export async function encryptMegolmKeyFile(
data: string,
password: string,
options?: { kdf_rounds?: number }, // eslint-disable-line camelcase
): Promise<ArrayBuffer> {
options = options || {};
const kdfRounds = options.kdf_rounds || 500000;
@ -194,7 +200,7 @@ export async function encryptMegolmKeyFile(data, password, options) {
* @param {String} password password
* @return {Promise<[CryptoKey, CryptoKey]>} promise for [aes key, hmac key]
*/
async function deriveKeys(salt, iterations, password) {
async function deriveKeys(salt: Uint8Array, iterations: number, password: string): Promise<[CryptoKey, CryptoKey]> {
const start = new Date();
let key;
@ -227,7 +233,7 @@ async function deriveKeys(salt, iterations, password) {
}
const now = new Date();
console.log("E2e import/export: deriveKeys took " + (now - start) + "ms");
logger.log("E2e import/export: deriveKeys took " + (now.getTime() - start.getTime()) + "ms");
const aesKey = keybits.slice(0, 32);
const hmacKey = keybits.slice(32);
@ -269,7 +275,7 @@ const TRAILER_LINE = '-----END MEGOLM SESSION DATA-----';
* @param {ArrayBuffer} data input file
* @return {Uint8Array} unbase64ed content
*/
function unpackMegolmKeyFile(data) {
function unpackMegolmKeyFile(data: ArrayBuffer): Uint8Array {
// parse the file as a great big String. This should be safe, because there
// should be no non-ASCII characters, and it means that we can do string
// comparisons to find the header and footer, and feed it into window.atob.
@ -277,6 +283,7 @@ function unpackMegolmKeyFile(data) {
// look for the start line
let lineStart = 0;
// eslint-disable-next-line no-constant-condition
while (1) {
const lineEnd = fileStr.indexOf('\n', lineStart);
if (lineEnd < 0) {
@ -295,6 +302,7 @@ function unpackMegolmKeyFile(data) {
const dataStart = lineStart;
// look for the end line
// eslint-disable-next-line no-constant-condition
while (1) {
const lineEnd = fileStr.indexOf('\n', lineStart);
const line = fileStr.slice(lineStart, lineEnd < 0 ? undefined : lineEnd).trim();
@ -322,7 +330,7 @@ function unpackMegolmKeyFile(data) {
* @param {Uint8Array} data raw data
* @return {ArrayBuffer} formatted file
*/
function packMegolmKeyFile(data) {
function packMegolmKeyFile(data: Uint8Array): ArrayBuffer {
// we split into lines before base64ing, because encodeBase64 doesn't deal
// terribly well with large arrays.
const LINE_LENGTH = (72 * 4 / 3);
@ -345,7 +353,7 @@ function packMegolmKeyFile(data) {
* @param {Uint8Array} uint8Array The data to encode.
* @return {string} The base64.
*/
function encodeBase64(uint8Array) {
function encodeBase64(uint8Array: Uint8Array): string {
// Misinterpt the Uint8Array as Latin-1.
// window.btoa expects a unicode string with codepoints in the range 0-255.
const latin1String = String.fromCharCode.apply(null, uint8Array);
@ -358,7 +366,7 @@ function encodeBase64(uint8Array) {
* @param {string} base64 The base64 to decode.
* @return {Uint8Array} The decoded data.
*/
function decodeBase64(base64) {
function decodeBase64(base64: string): Uint8Array {
// window.atob returns a unicode string with codepoints in the range 0-255.
const latin1String = window.atob(base64);
// Encode the string as a Uint8Array

View file

@ -25,6 +25,8 @@ import Modal from "../Modal";
import SettingsStore from "../settings/SettingsStore";
import AskInviteAnywayDialog from "../components/views/dialogs/AskInviteAnywayDialog";
import { logger } from "matrix-js-sdk/src/logger";
export enum InviteState {
Invited = "invited",
Error = "error",
@ -161,7 +163,7 @@ export default class MultiInviter {
private doInvite(address: string, ignoreProfile = false): Promise<void> {
return new Promise<void>((resolve, reject) => {
console.log(`Inviting ${address}`);
logger.log(`Inviting ${address}`);
let doInvite;
if (this.groupId !== null) {
@ -271,7 +273,7 @@ export default class MultiInviter {
return;
}
console.log("Showing failed to invite dialog...");
logger.log("Showing failed to invite dialog...");
Modal.createTrackedDialog('Failed to invite', '', AskInviteAnywayDialog, {
unknownProfileUsers: unknownProfileUsers.map(u => ({
userId: u,

View file

@ -19,6 +19,8 @@ import Analytics from '../Analytics';
import { IndexedDBStore } from "matrix-js-sdk/src/store/indexeddb";
import { IndexedDBCryptoStore } from "matrix-js-sdk/src/crypto/store/indexeddb-crypto-store";
import { logger } from "matrix-js-sdk/src/logger";
const localStorage = window.localStorage;
// just *accessing* indexedDB throws an exception in firefox with
@ -33,7 +35,7 @@ const SYNC_STORE_NAME = "riot-web-sync";
const CRYPTO_STORE_NAME = "matrix-js-sdk:crypto";
function log(msg: string) {
console.log(`StorageManager: ${msg}`);
logger.log(`StorageManager: ${msg}`);
}
function error(msg: string, ...args: string[]) {
@ -47,15 +49,15 @@ function track(action: string) {
export function tryPersistStorage() {
if (navigator.storage && navigator.storage.persist) {
navigator.storage.persist().then(persistent => {
console.log("StorageManager: Persistent?", persistent);
logger.log("StorageManager: Persistent?", persistent);
});
} else if (document.requestStorageAccess) { // Safari
document.requestStorageAccess().then(
() => console.log("StorageManager: Persistent?", true),
() => console.log("StorageManager: Persistent?", false),
() => logger.log("StorageManager: Persistent?", true),
() => logger.log("StorageManager: Persistent?", false),
);
} else {
console.log("StorageManager: Persistence unsupported");
logger.log("StorageManager: Persistence unsupported");
}
}