Skip to content

Commit

Permalink
Merge pull request #28236 from element-hq/t3chguy/sonar-happy
Browse files Browse the repository at this point in the history
  • Loading branch information
t3chguy authored Oct 18, 2024
2 parents d638d5d + 51c308f commit 4e93233
Show file tree
Hide file tree
Showing 18 changed files with 46 additions and 67 deletions.
4 changes: 2 additions & 2 deletions src/AddThreepid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Avatar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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("")
Expand Down
16 changes: 4 additions & 12 deletions src/ContentMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/IdentityAuthClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down
3 changes: 0 additions & 3 deletions src/NodeAnimator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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[];

Expand Down
4 changes: 2 additions & 2 deletions src/Notifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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);
Expand Down
8 changes: 4 additions & 4 deletions src/PosthogAnalytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions src/RoomInvite.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ export interface IInviteResult {
* @param {function} progressCallback optional callback, fired after each invite.
* @returns {Promise} Promise
*/
export function inviteMultipleToRoom(
export async function inviteMultipleToRoom(
client: MatrixClient,
roomId: string,
addresses: string[],
progressCallback?: () => void,
): Promise<IInviteResult> {
const inviter = new MultiInviter(client, roomId, progressCallback);
return inviter.invite(addresses, undefined).then((states) => Promise.resolve({ states, inviter }));
return { states: await inviter.invite(addresses), inviter };
}

export function showStartChatInviteDialog(initialText = ""): void {
Expand Down Expand Up @@ -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"),
});
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/SlashCommands.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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;
Expand Down
36 changes: 16 additions & 20 deletions src/SlidingSyncManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 2 additions & 7 deletions src/Terms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions src/actions/RoomListActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
});
});
}
Expand All @@ -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"),
});
});

Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/MatrixChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
});
});
}
Expand Down
3 changes: 1 addition & 2 deletions src/components/views/dialogs/RoomUpgradeDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/right_panel/UserInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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",
});
},
)
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/settings/AddRemoveThreepids.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
});
});
},
Expand Down
2 changes: 1 addition & 1 deletion test/unit-tests/Lifecycle-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,7 @@ describe("Lifecycle", () => {
deviceId,
freshLogin: true,
guest: false,
pickleKey: null,
pickleKey: undefined,
},
undefined,
);
Expand Down

0 comments on commit 4e93233

Please sign in to comment.