Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Apply corrections identified by SonarQube #8457

Merged
merged 7 commits into from
May 3, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 5 additions & 11 deletions src/ContentMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,11 +380,11 @@ export default class ContentMessages {
const tooBigFiles = [];
const okFiles = [];

for (let i = 0; i < files.length; ++i) {
if (this.isFileSizeAcceptable(files[i])) {
okFiles.push(files[i]);
for (const file of files) {
if (this.isFileSizeAcceptable(file)) {
okFiles.push(file);
} else {
tooBigFiles.push(files[i]);
tooBigFiles.push(file);
}
}

Expand Down Expand Up @@ -450,13 +450,7 @@ export default class ContentMessages {
}

public cancelUpload(promise: Promise<any>, matrixClient: MatrixClient): void {
let upload: IUpload;
for (let i = 0; i < this.inprogress.length; ++i) {
if (this.inprogress[i].promise === promise) {
upload = this.inprogress[i];
break;
}
}
const upload = this.inprogress.find(item => item.promise === promise);
if (upload) {
upload.canceled = true;
matrixClient.cancelUpload(upload.promise);
Expand Down
12 changes: 8 additions & 4 deletions src/HtmlUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,17 @@ import katex from 'katex';
import { AllHtmlEntities } from 'html-entities';
import { IContent } from 'matrix-js-sdk/src/models/event';

import { _linkifyElement, _linkifyString } from './linkify-matrix';
import {
_linkifyElement,
_linkifyString,
ELEMENT_URL_PATTERN,
options as linkifyMatrixOptions,
} from './linkify-matrix';
import { IExtendedSanitizeOptions } from './@types/sanitize-html';
import SettingsStore from './settings/SettingsStore';
import { tryTransformPermalinkToLocalHref } from "./utils/permalinks/Permalinks";
import { getEmojiFromUnicode } from "./emoji";
import { mediaFromMxc } from "./customisations/Media";
import { ELEMENT_URL_PATTERN, options as linkifyMatrixOptions } from './linkify-matrix';
import { stripHTMLReply, stripPlainReply } from './utils/Reply';

// Anything outside the basic multilingual plane will be a surrogate pair
Expand All @@ -45,10 +49,10 @@ const SURROGATE_PAIR_PATTERN = /([\ud800-\udbff])([\udc00-\udfff])/;
const SYMBOL_PATTERN = /([\u2100-\u2bff])/;

// Regex pattern for Zero-Width joiner unicode characters
const ZWJ_REGEX = new RegExp("\u200D|\u2003", "g");
const ZWJ_REGEX = /[\u200D\u2003]/g;

// Regex pattern for whitespace characters
const WHITESPACE_REGEX = new RegExp("\\s", "g");
const WHITESPACE_REGEX = /\s/g;

const BIGEMOJI_REGEX = new RegExp(`^(${EMOJIBASE_REGEX.source})+$`, 'i');

Expand Down
21 changes: 7 additions & 14 deletions src/KeyBindingsDefaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,10 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { isMac, Key } from "./Keyboard";
import { IS_MAC, Key } from "./Keyboard";
import SettingsStore from "./settings/SettingsStore";
import SdkConfig from "./SdkConfig";
import {
IKeyBindingsProvider,
KeyBinding,
KeyCombo,
} from "./KeyBindingsManager";
import { IKeyBindingsProvider, KeyBinding } from "./KeyBindingsManager";
import {
CATEGORIES,
CategoryName,
Expand All @@ -31,13 +27,10 @@ import {
import { getKeyboardShortcuts } from "./accessibility/KeyboardShortcutUtils";

export const getBindingsByCategory = (category: CategoryName): KeyBinding[] => {
return CATEGORIES[category].settingNames.reduce((bindings, name) => {
const value = getKeyboardShortcuts()[name]?.default;
if (value) {
bindings.push({
action: name as KeyBindingAction,
keyCombo: value as KeyCombo,
});
return CATEGORIES[category].settingNames.reduce((bindings, action) => {
const keyCombo = getKeyboardShortcuts()[action]?.default;
if (keyCombo) {
bindings.push({ action, keyCombo });
}
return bindings;
}, []);
Expand Down Expand Up @@ -81,7 +74,7 @@ const messageComposerBindings = (): KeyBinding[] => {
shiftKey: true,
},
});
if (isMac) {
if (IS_MAC) {
bindings.push({
action: KeyBindingAction.NewLine,
keyCombo: {
Expand Down
4 changes: 2 additions & 2 deletions src/KeyBindingsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.

import { KeyBindingAction } from "./accessibility/KeyboardShortcuts";
import { defaultBindingsProvider } from './KeyBindingsDefaults';
import { isMac } from './Keyboard';
import { IS_MAC } from './Keyboard';

/**
* Represent a key combination.
Expand Down Expand Up @@ -127,7 +127,7 @@ export class KeyBindingsManager {
): KeyBindingAction | undefined {
for (const getter of getters) {
const bindings = getter();
const binding = bindings.find(it => isKeyComboMatch(ev, it.keyCombo, isMac));
const binding = bindings.find(it => isKeyComboMatch(ev, it.keyCombo, IS_MAC));
if (binding) {
return binding.action;
}
Expand Down
6 changes: 3 additions & 3 deletions src/Keyboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,18 +74,18 @@ export const Key = {
Z: "z",
};

export const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
export const IS_MAC = navigator.platform.toUpperCase().includes('MAC');

export function isOnlyCtrlOrCmdKeyEvent(ev) {
if (isMac) {
if (IS_MAC) {
return ev.metaKey && !ev.altKey && !ev.ctrlKey && !ev.shiftKey;
} else {
return ev.ctrlKey && !ev.altKey && !ev.metaKey && !ev.shiftKey;
}
}

export function isOnlyCtrlOrCmdIgnoreShiftKeyEvent(ev) {
if (isMac) {
if (IS_MAC) {
return ev.metaKey && !ev.altKey && !ev.ctrlKey;
} else {
return ev.ctrlKey && !ev.altKey && !ev.metaKey;
Expand Down
2 changes: 1 addition & 1 deletion src/Lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -832,7 +832,7 @@ async function startMatrixClient(startSyncing = true): Promise<void> {
}

// Now that we have a MatrixClientPeg, update the Jitsi info
await Jitsi.getInstance().start();
Jitsi.getInstance().start();

// dispatch that we finished starting up to wire up any other bits
// of the matrix client that cannot be set prior to starting up.
Expand Down
1 change: 0 additions & 1 deletion src/Markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,6 @@ export default class Markdown {
renderer.html_inline = function(node: commonmark.Node) {
if (isAllowedHtmlTag(node)) {
this.lit(node.literal);
return;
} else {
this.lit(escape(node.literal));
}
Expand Down
3 changes: 0 additions & 3 deletions src/MatrixClientPeg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,6 @@ class MatrixClientPegClass implements IMatrixClientPeg {
// used if we tear it down & recreate it with a different store
private currentClientCreds: IMatrixClientCreds;

constructor() {
}

public get(): MatrixClient {
return this.matrixClient;
}
Expand Down
6 changes: 1 addition & 5 deletions src/RoomInvite.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,8 @@ export function isValid3pidInvite(event: MatrixEvent): boolean {

// any events without these keys are not valid 3pid invites, so we ignore them
const requiredKeys = ['key_validity_url', 'public_key', 'display_name'];
for (let i = 0; i < requiredKeys.length; ++i) {
if (!event.getContent()[requiredKeys[i]]) return false;
}

// Valid enough by our standards
t3chguy marked this conversation as resolved.
Show resolved Hide resolved
return true;
return requiredKeys.every(key => !!event.getContent()[key]);
}

export function inviteUsersToRoom(
Expand Down
17 changes: 9 additions & 8 deletions src/SecurityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,11 @@ async function confirmToDismiss(): Promise<boolean> {
return !sure;
}

type KeyParams = { passphrase: string, recoveryKey: string };

function makeInputToKey(
keyInfo: ISecretStorageKeyInfo,
): (keyParams: { passphrase: string, recoveryKey: string }) => Promise<Uint8Array> {
): (keyParams: KeyParams) => Promise<Uint8Array> {
return async ({ passphrase, recoveryKey }) => {
if (passphrase) {
return deriveKey(
Expand All @@ -101,11 +103,10 @@ function makeInputToKey(

async function getSecretStorageKey(
{ keys: keyInfos }: { keys: Record<string, ISecretStorageKeyInfo> },
ssssItemName,
): Promise<[string, Uint8Array]> {
const cli = MatrixClientPeg.get();
let keyId = await cli.getDefaultSecretStorageKeyId();
let keyInfo;
let keyInfo: ISecretStorageKeyInfo;
if (keyId) {
// use the default SSSS key if set
keyInfo = keyInfos[keyId];
Expand Down Expand Up @@ -154,9 +155,9 @@ async function getSecretStorageKey(
/* props= */
{
keyInfo,
checkPrivateKey: async (input) => {
checkPrivateKey: async (input: KeyParams) => {
const key = await inputToKey(input);
return await MatrixClientPeg.get().checkSecretStorageKey(key, keyInfo);
return MatrixClientPeg.get().checkSecretStorageKey(key, keyInfo);
},
},
/* className= */ null,
Expand All @@ -171,11 +172,11 @@ async function getSecretStorageKey(
},
},
);
const [input] = await finished;
if (!input) {
const [keyParams] = await finished;
if (!keyParams) {
throw new AccessCancelledError();
}
const key = await inputToKey(input);
const key = await inputToKey(keyParams);

// Save to cache to avoid future prompts in the current session
cacheSecretStorageKey(keyId, keyInfo, key);
Expand Down
16 changes: 10 additions & 6 deletions src/TextForEvent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ const onViewJoinRuleSettingsClick = () => {
});
};

function textForJoinRulesEvent(ev: MatrixEvent, allowJSX: boolean): () => string | JSX.Element | null {
function textForJoinRulesEvent(ev: MatrixEvent, allowJSX: boolean): () => Renderable {
const senderDisplayName = ev.sender && ev.sender.name ? ev.sender.name : ev.getSender();
switch (ev.getContent().join_rule) {
case JoinRule.Public:
Expand Down Expand Up @@ -281,7 +281,7 @@ function textForServerACLEvent(ev: MatrixEvent): () => string | null {
const prev = {
deny: Array.isArray(prevContent.deny) ? prevContent.deny : [],
allow: Array.isArray(prevContent.allow) ? prevContent.allow : [],
allow_ip_literals: !(prevContent.allow_ip_literals === false),
allow_ip_literals: prevContent.allow_ip_literals !== false,
};

let getText = null;
Expand Down Expand Up @@ -372,13 +372,15 @@ function textForCanonicalAliasEvent(ev: MatrixEvent): () => string | null {
addresses: addedAltAliases.join(", "),
count: addedAltAliases.length,
});
} if (removedAltAliases.length && !addedAltAliases.length) {
}
if (removedAltAliases.length && !addedAltAliases.length) {
return () => _t('%(senderName)s removed the alternative addresses %(addresses)s for this room.', {
senderName,
addresses: removedAltAliases.join(", "),
count: removedAltAliases.length,
});
} if (removedAltAliases.length && addedAltAliases.length) {
}
if (removedAltAliases.length && addedAltAliases.length) {
return () => _t('%(senderName)s changed the alternative addresses for this room.', {
senderName,
});
Expand Down Expand Up @@ -504,7 +506,7 @@ const onPinnedMessagesClick = (): void => {
RightPanelStore.instance.setCard({ phase: RightPanelPhases.PinnedMessages }, false);
};

function textForPinnedEvent(event: MatrixEvent, allowJSX: boolean): () => string | JSX.Element | null {
function textForPinnedEvent(event: MatrixEvent, allowJSX: boolean): () => Renderable {
if (!SettingsStore.getValue("feature_pinning")) return null;
const senderName = getSenderName(event);
const roomId = event.getRoomId();
Expand Down Expand Up @@ -758,10 +760,12 @@ function textForPollEndEvent(event: MatrixEvent): () => string | null {
});
}

type Renderable = string | JSX.Element | null;

interface IHandlers {
[type: string]:
(ev: MatrixEvent, allowJSX: boolean, showHiddenEvents?: boolean) =>
(() => string | JSX.Element | null);
(() => Renderable);
}

const handlers: IHandlers = {
Expand Down
4 changes: 2 additions & 2 deletions src/accessibility/KeyboardShortcutUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ limitations under the License.
*/

import { KeyCombo } from "../KeyBindingsManager";
import { isMac, Key } from "../Keyboard";
import { IS_MAC, Key } from "../Keyboard";
import { _t, _td } from "../languageHandler";
import PlatformPeg from "../PlatformPeg";
import SettingsStore from "../settings/SettingsStore";
Expand Down Expand Up @@ -96,7 +96,7 @@ export const getKeyboardShortcuts = (): IKeyboardShortcuts => {

return Object.keys(KEYBOARD_SHORTCUTS).filter((k: KeyBindingAction) => {
if (KEYBOARD_SHORTCUTS[k]?.controller?.settingDisabled) return false;
if (MAC_ONLY_SHORTCUTS.includes(k) && !isMac) return false;
if (MAC_ONLY_SHORTCUTS.includes(k) && !IS_MAC) return false;
if (DESKTOP_SHORTCUTS.includes(k) && !overrideBrowserShortcuts) return false;

return true;
Expand Down
24 changes: 12 additions & 12 deletions src/accessibility/KeyboardShortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ limitations under the License.
*/

import { _td } from "../languageHandler";
import { isMac, Key } from "../Keyboard";
import { IS_MAC, Key } from "../Keyboard";
import { IBaseSetting } from "../settings/Settings";
import IncompatibleController from "../settings/controllers/IncompatibleController";
import { KeyCombo } from "../KeyBindingsManager";
Expand Down Expand Up @@ -200,7 +200,7 @@ export const KEY_ICON: Record<string, string> = {
[Key.ARROW_LEFT]: "←",
[Key.ARROW_RIGHT]: "→",
};
if (isMac) {
if (IS_MAC) {
KEY_ICON[Key.META] = "⌘";
KEY_ICON[Key.ALT] = "⌥";
}
Expand Down Expand Up @@ -528,8 +528,8 @@ export const KEYBOARD_SHORTCUTS: IKeyboardShortcuts = {
[KeyBindingAction.GoToHome]: {
default: {
ctrlOrCmdKey: true,
altKey: !isMac,
shiftKey: isMac,
altKey: !IS_MAC,
shiftKey: IS_MAC,
key: Key.H,
},
displayName: _td("Go to Home View"),
Expand Down Expand Up @@ -621,25 +621,25 @@ export const KEYBOARD_SHORTCUTS: IKeyboardShortcuts = {
},
[KeyBindingAction.EditRedo]: {
default: {
key: isMac ? Key.Z : Key.Y,
key: IS_MAC ? Key.Z : Key.Y,
ctrlOrCmdKey: true,
shiftKey: isMac,
shiftKey: IS_MAC,
},
displayName: _td("Redo edit"),
},
[KeyBindingAction.PreviousVisitedRoomOrSpace]: {
default: {
metaKey: isMac,
altKey: !isMac,
key: isMac ? Key.SQUARE_BRACKET_LEFT : Key.ARROW_LEFT,
metaKey: IS_MAC,
altKey: !IS_MAC,
key: IS_MAC ? Key.SQUARE_BRACKET_LEFT : Key.ARROW_LEFT,
},
displayName: _td("Previous recently visited room or space"),
},
[KeyBindingAction.NextVisitedRoomOrSpace]: {
default: {
metaKey: isMac,
altKey: !isMac,
key: isMac ? Key.SQUARE_BRACKET_RIGHT : Key.ARROW_RIGHT,
metaKey: IS_MAC,
altKey: !IS_MAC,
key: IS_MAC ? Key.SQUARE_BRACKET_RIGHT : Key.ARROW_RIGHT,
},
displayName: _td("Next recently visited room or space"),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ export default class CreateSecretStorageDialog extends React.PureComponent<IProp

private doBootstrapUIAuth = async (makeRequest: (authData: any) => void): Promise<void> => {
if (this.state.canUploadKeysWithPasswordOnly && this.state.accountPassword) {
await makeRequest({
makeRequest({
type: 'm.login.password',
identifier: {
type: 'm.id.user',
Expand Down
2 changes: 1 addition & 1 deletion src/autocomplete/Autocompleter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export default class Autocompleter {
*/
// list of results from each provider, each being a list of completions or null if it times out
const completionsList: ICompletion[][] = await Promise.all(this.providers.map(async provider => {
return await timeout(
return timeout(
provider.getCompletions(query, selection, force, limit),
null,
PROVIDER_COMPLETION_TIMEOUT,
Expand Down
Loading