Make Sonar happier

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
pull/28236/head
Michael Telatynski 2024-10-16 17:38:22 +01:00
parent eedeb2cdaf
commit 44b23d2191
No known key found for this signature in database
GPG Key ID: A2B008A5F49F5D0D
17 changed files with 44 additions and 65 deletions

View File

@ -201,7 +201,7 @@ export default class AddThreepid {
// implemented it without, so this may just succeed and that's OK.
return [true];
} catch (err) {
if (!(err instanceof MatrixError) || err.httpStatus !== 401 || !err.data || !err.data.flows) {
if (!(err instanceof MatrixError) || err.httpStatus !== 401 || !err.data?.flows) {
// doesn't look like an interactive-auth failure
throw err;
}
@ -300,7 +300,7 @@ export default class AddThreepid {
// implemented it without, so this may just succeed and that's OK.
return [true];
} catch (err) {
if (!(err instanceof MatrixError) || err.httpStatus !== 401 || !err.data || !err.data.flows) {
if (!(err instanceof MatrixError) || err.httpStatus !== 401 || !err.data?.flows) {
// doesn't look like an interactive-auth failure
throw err;
}

View File

@ -68,7 +68,7 @@ function isValidHexColor(color: string): boolean {
return (
typeof color === "string" &&
(color.length === 7 || color.length === 9) &&
color.charAt(0) === "#" &&
color.startsWith("#") &&
!color
.slice(1)
.split("")

View File

@ -396,11 +396,7 @@ export default class ContentMessages {
}
public getUploadLimit(): number | null {
if (this.mediaConfig !== null && this.mediaConfig["m.upload.size"] !== undefined) {
return this.mediaConfig["m.upload.size"];
} else {
return null;
}
return this.mediaConfig?.["m.upload.size"] ?? null;
}
public async sendContentListToRoom(
@ -578,7 +574,7 @@ export default class ContentMessages {
logger.error(e);
content.msgtype = MsgType.File;
}
} else if (file.type.indexOf("audio/") === 0) {
} else if (file.type.startsWith("audio/")) {
content.msgtype = MsgType.Audio;
try {
const audioInfo = await infoForAudioFile(file);
@ -588,7 +584,7 @@ export default class ContentMessages {
logger.error(e);
content.msgtype = MsgType.File;
}
} else if (file.type.indexOf("video/") === 0) {
} else if (file.type.startsWith("video/")) {
content.msgtype = MsgType.Video;
try {
const videoInfo = await infoForVideoFile(matrixClient, roomId, file);
@ -648,11 +644,7 @@ export default class ContentMessages {
}
private isFileSizeAcceptable(file: File): boolean {
if (
this.mediaConfig !== null &&
this.mediaConfig["m.upload.size"] !== undefined &&
file.size > this.mediaConfig["m.upload.size"]
) {
if (this.mediaConfig?.["m.upload.size"] !== undefined && file.size > this.mediaConfig["m.upload.size"]) {
return false;
}
return true;

View File

@ -170,7 +170,7 @@ export default class IdentityAuthClient {
// XXX: The spec is `token`, but we used `access_token` for a Sydent release.
const { access_token: accessToken, token } =
await this.identityClient.registerWithIdentityServer(hsOpenIdToken);
const identityAccessToken = token ? token : accessToken;
const identityAccessToken = token || accessToken;
if (check) await this.checkToken(identityAccessToken);
return identityAccessToken;
}

View File

@ -661,7 +661,7 @@ export async function setLoggedIn(credentials: IMatrixClientCreds): Promise<Matr
logger.log("Pickle key not created");
}
return doSetLoggedIn(Object.assign({}, credentials, { pickleKey }), true, true);
return doSetLoggedIn({ ...credentials, pickleKey: pickleKey ?? undefined }, true, true);
}
/**

View File

@ -18,9 +18,6 @@ interface IProps {
// either a list of child nodes, or a single child.
children: React.ReactNode;
// optional transition information for changing existing children
transition?: object;
// a list of state objects to apply to each child node in turn
startStyles: React.CSSProperties[];

View File

@ -71,7 +71,7 @@ type of tile.
*/
const msgTypeHandlers: Record<string, (event: MatrixEvent) => string | null> = {
[MsgType.KeyVerificationRequest]: (event: MatrixEvent) => {
const name = (event.sender || {}).name;
const name = event.sender?.name;
return _t("notifier|m.key.verification.request", { name });
},
[M_LOCATION.name]: (event: MatrixEvent) => {
@ -233,7 +233,7 @@ class NotifierClass extends TypedEventEmitter<keyof EmittedEvents, EmittedEvents
// Play notification sound here
const sound = this.getSoundForRoom(room.roomId);
logger.log(`Got sound ${(sound && sound.name) || "default"} for ${room.roomId}`);
logger.log(`Got sound ${sound?.name || "default"} for ${room.roomId}`);
if (sound) {
await this.backgroundAudio.play(sound.url);

View File

@ -296,10 +296,10 @@ export class PosthogAnalytics {
// until the next time account data is refreshed and this function is called (most likely on next
// page load). This will happen pretty infrequently, so we can tolerate the possibility.
analyticsID = analyticsIdGenerator();
await client.setAccountData(
PosthogAnalytics.ANALYTICS_EVENT_TYPE,
Object.assign({ id: analyticsID }, accountData),
);
await client.setAccountData(PosthogAnalytics.ANALYTICS_EVENT_TYPE, {
id: analyticsID,
...accountData,
});
}
if (this.posthog.get_distinct_id() === analyticsID) {
// No point identifying again

View File

@ -42,7 +42,7 @@ export function inviteMultipleToRoom(
progressCallback?: () => void,
): Promise<IInviteResult> {
const inviter = new MultiInviter(client, roomId, progressCallback);
return inviter.invite(addresses, undefined).then((states) => Promise.resolve({ states, inviter }));
return inviter.invite(addresses).then((states) => Promise.resolve({ states, inviter }));
}
export function showStartChatInviteDialog(initialText = ""): void {
@ -104,7 +104,7 @@ export function inviteUsersToRoom(
logger.error(err.stack);
Modal.createDialog(ErrorDialog, {
title: _t("invite|failed_title"),
description: err && err.message ? err.message : _t("invite|failed_generic"),
description: err?.message ?? _t("invite|failed_generic"),
});
});
}

View File

@ -450,7 +450,7 @@ export const Commands = [
const matches = args.match(/^(\S+)$/);
if (matches) {
let roomAlias = matches[1];
if (roomAlias[0] !== "#") return reject(this.getUsage());
if (!roomAlias.startsWith("#")) return reject(this.getUsage());
if (!roomAlias.includes(":")) {
roomAlias += ":" + cli.getDomain();
@ -994,7 +994,7 @@ Commands.forEach((cmd) => {
export function parseCommandString(input: string): { cmd?: string; args?: string } {
// trim any trailing whitespace, as it can confuse the parser for IRC-style commands
input = input.trimEnd();
if (input[0] !== "/") return {}; // not a command
if (input.startsWith("/")) return {}; // not a command
const bits = input.match(/^(\S+?)(?:[ \n]+((.|\n)*))?$/);
let cmd: string;

View File

@ -72,27 +72,23 @@ const DEFAULT_ROOM_SUBSCRIPTION_INFO = {
};
// lazy load room members so rooms like Matrix HQ don't take forever to load
const UNENCRYPTED_SUBSCRIPTION_NAME = "unencrypted";
const UNENCRYPTED_SUBSCRIPTION = Object.assign(
{
required_state: [
[MSC3575_WILDCARD, MSC3575_WILDCARD], // all events
[EventType.RoomMember, MSC3575_STATE_KEY_ME], // except for m.room.members, get our own membership
[EventType.RoomMember, MSC3575_STATE_KEY_LAZY], // ...and lazy load the rest.
],
},
DEFAULT_ROOM_SUBSCRIPTION_INFO,
);
const UNENCRYPTED_SUBSCRIPTION = {
required_state: [
[MSC3575_WILDCARD, MSC3575_WILDCARD], // all events
[EventType.RoomMember, MSC3575_STATE_KEY_ME], // except for m.room.members, get our own membership
[EventType.RoomMember, MSC3575_STATE_KEY_LAZY], // ...and lazy load the rest.
],
...DEFAULT_ROOM_SUBSCRIPTION_INFO,
};
// we need all the room members in encrypted rooms because we need to know which users to encrypt
// messages for.
const ENCRYPTED_SUBSCRIPTION = Object.assign(
{
required_state: [
[MSC3575_WILDCARD, MSC3575_WILDCARD], // all events
],
},
DEFAULT_ROOM_SUBSCRIPTION_INFO,
);
const ENCRYPTED_SUBSCRIPTION = {
required_state: [
[MSC3575_WILDCARD, MSC3575_WILDCARD], // all events
],
...DEFAULT_ROOM_SUBSCRIPTION_INFO,
};
export type PartialSlidingSyncRequest = {
filters?: MSC3575Filter;
@ -199,10 +195,10 @@ export class SlidingSyncManager {
[EventType.RoomMember, MSC3575_STATE_KEY_ME], // lets the client calculate that we are in fact in the room
],
},
...updateArgs,
};
list = Object.assign(list, updateArgs);
} else {
const updatedList = Object.assign({}, list, updateArgs);
const updatedList = { ...list, ...updateArgs };
// cannot use objectHasDiff as we need to do deep diff checking
if (JSON.stringify(list) === JSON.stringify(updatedList)) {
logger.debug("list matches, not sending, update => ", updateArgs);

View File

@ -102,13 +102,8 @@ export async function startTermsFlow(
});
// fetch the set of agreed policy URLs from account data
const currentAcceptedTerms = await client.getAccountData("m.accepted_terms");
let agreedUrlSet: Set<string>;
if (!currentAcceptedTerms || !currentAcceptedTerms.getContent() || !currentAcceptedTerms.getContent().accepted) {
agreedUrlSet = new Set();
} else {
agreedUrlSet = new Set(currentAcceptedTerms.getContent().accepted);
}
const currentAcceptedTerms = client.getAccountData("m.accepted_terms")?.getContent();
const agreedUrlSet = new Set<string>(currentAcceptedTerms?.accepted || []);
// remove any policies the user has already agreed to and any services where
// they've already agreed to all the policies

View File

@ -79,7 +79,7 @@ export default class RoomListActions {
logger.error("Failed to set DM tag " + err);
Modal.createDialog(ErrorDialog, {
title: _t("room_list|failed_set_dm_tag"),
description: err && err.message ? err.message : _t("invite|failed_generic"),
description: err?.message ?? _t("invite|failed_generic"),
});
});
}
@ -95,7 +95,7 @@ export default class RoomListActions {
logger.error("Failed to remove tag " + oldTag + " from room: " + err);
Modal.createDialog(ErrorDialog, {
title: _t("room_list|failed_remove_tag", { tagName: oldTag }),
description: err && err.message ? err.message : _t("invite|failed_generic"),
description: err?.message ?? _t("invite|failed_generic"),
});
});
@ -108,7 +108,7 @@ export default class RoomListActions {
logger.error("Failed to add tag " + newTag + " to room: " + err);
Modal.createDialog(ErrorDialog, {
title: _t("room_list|failed_add_tag", { tagName: newTag }),
description: err && err.message ? err.message : _t("invite|failed_generic"),
description: err?.message ?? _t("invite|failed_generic"),
});
throw err;

View File

@ -1317,7 +1317,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
const errCode = err.errcode || _td("error|unknown_error_code");
Modal.createDialog(ErrorDialog, {
title: _t("error_dialog|forget_room_failed", { errCode }),
description: err && err.message ? err.message : _t("invite|failed_generic"),
description: err?.message ?? _t("invite|failed_generic"),
});
});
}

View File

@ -52,8 +52,7 @@ export default class RoomUpgradeDialog extends React.Component<IProps, IState> {
.catch((err) => {
Modal.createDialog(ErrorDialog, {
title: _t("room_settings|advanced|error_upgrade_title"),
description:
err && err.message ? err.message : _t("room_settings|advanced|error_upgrade_description"),
description: err?.message ?? _t("room_settings|advanced|error_upgrade_description"),
});
})
.finally(() => {

View File

@ -725,7 +725,7 @@ export const RoomKickButton = ({
logger.error("Kick error: " + err);
Modal.createDialog(ErrorDialog, {
title: _t("user_info|error_kicking_user"),
description: err && err.message ? err.message : "Operation failed",
description: err?.message ?? "Operation failed",
});
},
)

View File

@ -74,7 +74,7 @@ const ExistingThreepid: React.FC<ExistingThreepidProps> = ({ mode, threepid, onC
logger.error("Unable to remove contact information: " + err);
Modal.createDialog(ErrorDialog, {
title: _t("settings|general|error_remove_3pid"),
description: err && err.message ? err.message : _t("invite|failed_generic"),
description: err?.message ?? _t("invite|failed_generic"),
});
});
},