Skip to content

Commit

Permalink
Iron out some assertions
Browse files Browse the repository at this point in the history
  • Loading branch information
tassoevan committed Mar 10, 2023
1 parent 63cd390 commit 397fc66
Show file tree
Hide file tree
Showing 37 changed files with 130 additions and 57 deletions.
2 changes: 1 addition & 1 deletion apps/meteor/.eslintcache

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions apps/meteor/app/2fa/server/methods/disable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ Meteor.methods({
});
}

if (!user.services?.totp?.secret) {
throw new Meteor.Error('error-user-has-no-2fa', 'User has no 2FA', {
method: '2fa:disable',
});
}

const verified = TOTP.verify({
secret: user.services.totp.secret,
token: code,
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/2fa/server/methods/validateTempToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Meteor.methods({
});
}

if (!user.services || !user.services.totp || !user.services.totp.tempSecret) {
if (!user.services?.totp?.tempSecret) {
throw new Meteor.Error('invalid-totp');
}

Expand Down
3 changes: 3 additions & 0 deletions apps/meteor/app/custom-sounds/client/lib/CustomSounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@ class CustomSoundsClass {
return list.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
}

/**
* @return {HTMLAudioElement | undefined}
*/
play = (sound, { volume = 1, loop = false } = {}) => {
const audio = document.querySelector(`#${getCustomSoundId(sound)}`);
if (!audio || !audio.play) {
Expand Down
5 changes: 3 additions & 2 deletions apps/meteor/app/settings/client/lib/settings.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Meteor } from 'meteor/meteor';
import { ReactiveDict } from 'meteor/reactive-dict';
import type { SettingValue } from '@rocket.chat/core-typings';
import type { EJSONableProperty } from 'meteor/ejson';

import { PublicSettingsCachedCollection } from '../../../../client/lib/settings/PublicSettingsCachedCollection';
import { SettingsBase } from '../../lib/settings';
Expand All @@ -12,14 +13,14 @@ class Settings extends SettingsBase {

dict = new ReactiveDict('settings');

get(_id: string | RegExp, ...args: []): any {
get<TValue extends EJSONableProperty>(_id: string | RegExp, ...args: []): TValue | undefined {
if (_id instanceof RegExp) {
throw new Error('RegExp Settings.get(RegExp)');
}
if (args.length > 0) {
throw new Error('settings.get(String, callback) only works on backend');
}
return this.dict.get(_id);
return this.dict.get(_id) as TValue | undefined;
}

private _storeSettingValue(record: { _id: string; value: SettingValue }, initialLoad: boolean): void {
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/ui-utils/client/lib/MessageAction.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ComponentProps, ContextType } from 'react';
import type { ComponentProps, ContextType, UIEvent } from 'react';
import mem from 'mem';
import { Meteor } from 'meteor/meteor';
import { ReactiveVar } from 'meteor/reactive-var';
Expand Down Expand Up @@ -57,7 +57,7 @@ export type MessageActionConfig = {
group?: MessageActionGroup | MessageActionGroup[];
context?: MessageActionContext[];
action: (
e: Pick<Event, 'preventDefault' | 'stopPropagation' | 'currentTarget'>,
e: UIEvent<Element>,
{
message,
tabbar,
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/ui-utils/client/lib/messageContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const fields = {

export const createMessageContext = ({
uid = Meteor.userId(),
user = (uid ? Users.findOne({ _id: uid }, { fields }) : {}) || {},
user = uid ? Users.findOne({ _id: uid }, { fields }) : undefined,
rid = (Template.instance() as CommonRoomTemplateInstance).data.rid,
room = Tracker.nonreactive(() =>
Rooms.findOne(
Expand Down Expand Up @@ -72,7 +72,7 @@ export const createMessageContext = ({
Message_GroupingPeriod = settings.get('Message_GroupingPeriod') * 1000,
}: {
uid?: IUser['_id'] | null;
user?: Partial<IUser>;
user?: Pick<IUser, '_id' | 'name' | 'username' | 'settings'>;
rid?: IRoom['_id'];
room?: Omit<IRoom, '_updatedAt' | 'lastMessage'>;
subscription?: Pick<ISubscription, 'name' | 'autoTranslate' | 'rid' | 'tunread' | 'tunreadUser' | 'tunreadGroup'>;
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/ui/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import './lib/parentTemplate';
import './lib/codeMirror';
import './views/app/roomSearch.html';
import './views/app/roomSearch';
import './views/app/photoswipeContent.ts'; // without the *.ts extension, *.html gets loaded first
import './views/app/photoswipe.ts'; // without the *.ts extension, *.html gets loaded first

export { UserAction, USER_ACTIVITIES } from './lib/UserAction';
export { KonchatNotification } from './lib/notification';
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/utils/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { t } from '../lib/tapi18n';
export { Info } from '../rocketchat.info';
export { getUserPreference } from '../lib/getUserPreference';
export { getUserPreference } from './lib/getUserPreference';
export { fileUploadIsValidContentType } from '../lib/fileUploadRestrictions';
export { getUserAvatarURL } from '../lib/getUserAvatarURL';
export { slashCommands } from '../lib/slashCommand';
Expand Down
48 changes: 48 additions & 0 deletions apps/meteor/app/utils/client/lib/getUserPreference.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { IUser } from '@rocket.chat/core-typings';

import { Users } from '../../../models/client';
import { settings } from '../../../settings/client';

/**
* Get a user preference
* @param user The user ID
* @param key The preference name
* @returns The preference value
*/
export function getUserPreference<TValue>(user: IUser['_id'] | null | undefined, key: string): TValue | undefined;
/**
* Get a user preference
* @param user The user
* @param key The preference name
* @returns The preference value
*/
export function getUserPreference<TValue>(user: Pick<IUser, '_id' | 'settings'> | null | undefined, key: string): TValue | undefined;
/**
* Get a user preference
* @param user The user ID
* @param key The preference name
* @param defaultValue The default value
* @returns The preference value or the default value
*/
export function getUserPreference<TValue>(user: IUser['_id'] | null | undefined, key: string, defaultValue: TValue): TValue;
/**
* Get a user preference
* @param user The user
* @param key The preference name
* @param defaultValue The default value
* @returns The preference value or the default value
*/
export function getUserPreference<TValue>(
user: Pick<IUser, '_id' | 'settings'> | null | undefined,
key: string,
defaultValue: TValue,
): TValue;
export function getUserPreference<TValue>(
userIdOrUser: IUser['_id'] | Pick<IUser, '_id' | 'settings'> | null | undefined,
key: string,
defaultValue?: TValue,
): TValue {
const user =
typeof userIdOrUser === 'string' ? Users.findOne(userIdOrUser, { fields: { [`settings.preferences.${key}`]: 1 } }) : userIdOrUser;
return user?.settings?.preferences[key] ?? defaultValue ?? settings.get(`Accounts_Default_User_ Preferences_${key}`);
}
3 changes: 2 additions & 1 deletion apps/meteor/app/utils/server/functions/safeGetMeteorUser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { IUser } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';

const invalidEnvironmentErrorMessage = 'Meteor.userId can only be invoked in method calls or publications.';
Expand All @@ -14,7 +15,7 @@ const invalidEnvironmentErrorMessage = 'Meteor.userId can only be invoked in met
*
* @returns The current user in the Meteor session, or null if not available
*/
export function safeGetMeteorUser(): Meteor.User | null {
export function safeGetMeteorUser(): IUser | null {
try {
return Meteor.user();
} catch (error: any) {
Expand Down
13 changes: 5 additions & 8 deletions apps/meteor/client/startup/actionButtons/autotranslate.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ITranslatedMessage } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';

Expand All @@ -20,8 +21,7 @@ Meteor.startup(() => {
icon: 'language',
label: 'Translate',
context: ['message', 'message-mobile', 'threads'],
action(_, props) {
const { message = messageArgs(this).msg } = props;
action(this: unknown, _, { message = messageArgs(this).msg }) {
const language = AutoTranslate.getLanguage(message.rid);
if (!hasTranslationLanguageInMessage(message, language) && !hasTranslationLanguageInAttachments(message.attachments, language)) {
AutoTranslate.messageIdsToWait.add(message._id);
Expand All @@ -35,6 +35,7 @@ Meteor.startup(() => {
if (!user) {
return false;
}

const language = subscription?.autoTranslateLanguage || AutoTranslate.getLanguage(message.rid) || '';
const isLivechatRoom = roomCoordinator.isLivechatRoom(room?.t);
const isDifferentUser = message?.u && message.u._id !== user._id;
Expand All @@ -43,8 +44,7 @@ Meteor.startup(() => {
hasTranslationLanguageInMessage(message, language) || hasTranslationLanguageInAttachments(message.attachments, language);

return Boolean(
(message as { autoTranslateShowInverse?: boolean }).autoTranslateShowInverse ||
(isDifferentUser && autoTranslateEnabled && !hasLanguage),
(message as ITranslatedMessage).autoTranslateShowInverse || (isDifferentUser && autoTranslateEnabled && !hasLanguage),
);
},
order: 90,
Expand Down Expand Up @@ -77,10 +77,7 @@ Meteor.startup(() => {
hasTranslationLanguageInMessage(message, language) || hasTranslationLanguageInAttachments(message.attachments, language);

return Boolean(
!(message as { autoTranslateShowInverse?: boolean }).autoTranslateShowInverse &&
isDifferentUser &&
autoTranslateEnabled &&
hasLanguage,
!(message as ITranslatedMessage).autoTranslateShowInverse && isDifferentUser && autoTranslateEnabled && hasLanguage,
);
},
order: 90,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Meteor.startup(() => {
context: ['message', 'message-mobile', 'threads', 'federated'],
action(this: unknown, event, { message = messageArgs(this).msg }) {
event.stopPropagation();
EmojiPicker.open(event.currentTarget as Element, (emoji) => Meteor.call('setReaction', `:${emoji}:`, message._id));
EmojiPicker.open(event.currentTarget, (emoji) => Meteor.call('setReaction', `:${emoji}:`, message._id));
},
condition({ message, user, room, subscription }) {
if (!user) {
Expand Down
5 changes: 3 additions & 2 deletions apps/meteor/client/startup/actionButtons/starMessage.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { IUser } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';

import { settings } from '../../../app/settings/client';
Expand All @@ -15,7 +16,7 @@ Meteor.startup(() => {
context: ['starred', 'message', 'message-mobile', 'threads', 'federated'],
action(_, props) {
const { message = messageArgs(this).msg } = props;
Meteor.call('starMessage', { ...message, starred: true }, (error: any) => {
Meteor.call('starMessage', { ...message, starred: true }, (error: Error) => {
if (error) {
dispatchToastMessage({ type: 'error', message: error });
return;
Expand All @@ -33,7 +34,7 @@ Meteor.startup(() => {
return false;
}

return !Array.isArray(message.starred) || !message.starred.find((star: any) => star._id === user?._id);
return !Array.isArray(message.starred) || !message.starred.find((star: Pick<IUser, '_id'>) => star._id === user?._id);
},
order: 9,
group: 'menu',
Expand Down
5 changes: 3 additions & 2 deletions apps/meteor/client/startup/actionButtons/unstarMessage.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { IUser } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';

import { settings } from '../../../app/settings/client';
Expand All @@ -15,7 +16,7 @@ Meteor.startup(() => {
action(_, props) {
const { message = messageArgs(this).msg } = props;

Meteor.call('starMessage', { ...message, starred: false }, (error?: any) => {
Meteor.call('starMessage', { ...message, starred: false }, (error?: Error) => {
if (error) {
dispatchToastMessage({ type: 'error', message: error });
return;
Expand All @@ -29,7 +30,7 @@ Meteor.startup(() => {
return false;
}

return Boolean(message.starred?.find((star: any) => star._id === user?._id));
return Boolean(message.starred?.find((star: Pick<IUser, '_id'>) => star._id === user?._id));
},
order: 9,
group: 'menu',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { usePermission } from '@rocket.chat/ui-contexts';
import type { LazyExoticComponent, FC } from 'react';
import { useMemo, lazy } from 'react';

import { addAction } from '../../views/room/lib/Toolbox';
Expand All @@ -15,7 +14,7 @@ addAction('export-messages', ({ room }) => {
anonymous: true,
title: 'Export_Messages',
icon: 'mail',
template: lazy(() => import('../../views/room/contextualBar/ExportMessages')) as LazyExoticComponent<FC>,
template: lazy(() => import('../../views/room/contextualBar/ExportMessages')),
full: true,
order: 12,
}
Expand Down
3 changes: 2 additions & 1 deletion apps/meteor/client/startup/deleteCustomSound.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ICustomSound } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';

import { CustomSounds } from '../../app/custom-sounds/client/lib/CustomSounds';
Expand All @@ -6,6 +7,6 @@ import { CachedCollectionManager } from '../../app/ui-cached-collection/client';

Meteor.startup(() =>
CachedCollectionManager.onLogin(() =>
Notifications.onAll('deleteCustomSound', (data: { soundData: any }) => CustomSounds.remove(data.soundData)),
Notifications.onAll('deleteCustomSound', (data: { soundData: ICustomSound }) => CustomSounds.remove(data.soundData)),
),
);
5 changes: 4 additions & 1 deletion apps/meteor/client/startup/deleteEmojiCustom.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { ICustomEmojiDescriptor } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';

import { deleteEmojiCustom } from '../../app/emoji-custom/client/lib/emojiCustom';
import { Notifications } from '../../app/notifications/client';

Meteor.startup(() => Notifications.onLogged('deleteEmojiCustom', (data: { emojiData: any }) => deleteEmojiCustom(data.emojiData)));
Meteor.startup(() =>
Notifications.onLogged('deleteEmojiCustom', (data: { emojiData: ICustomEmojiDescriptor }) => deleteEmojiCustom(data.emojiData)),
);
2 changes: 1 addition & 1 deletion apps/meteor/client/startup/galleryItemClick.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import $ from 'jquery';
import { Meteor } from 'meteor/meteor';

import { createEventListenerFor } from '../../app/ui/client/views/app/photoswipeContent.ts';
import { createEventListenerFor } from '../../app/ui/client/views/app/photoswipe';

Meteor.startup(() => {
$(document).on('click', '.gallery-item', createEventListenerFor('.gallery-item'));
Expand Down
3 changes: 1 addition & 2 deletions apps/meteor/client/startup/i18n.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { IUser } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';
import { ReactiveVar } from 'meteor/reactive-var';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
Expand Down Expand Up @@ -77,7 +76,7 @@ Meteor.startup(() => {
return;
}

const user = Users.findOne(uid, { fields: { language: 1 } }) as IUser | undefined;
const user = Users.findOne(uid, { fields: { language: 1 } });

setLanguage(user?.language || defaultUserLanguage());
});
Expand Down
8 changes: 6 additions & 2 deletions apps/meteor/client/startup/ldap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ import { Meteor } from 'meteor/meteor';
declare module 'meteor/meteor' {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Meteor {
function loginWithLDAP(username: string, password: string, callback?: (err?: any) => void): void;
function loginWithLDAP(username: string | object, password: string, callback?: (err?: Meteor.Error | Meteor.TypedError) => void): void;
}
}

Meteor.loginWithLDAP = function (username: string, password: string, callback?: (err?: any) => void): void {
Meteor.loginWithLDAP = function (
username: string | object,
password: string,
callback?: (err?: Meteor.Error | Meteor.TypedError) => void,
): void {
Accounts.callLoginMethod({
methodArguments: [
{
Expand Down
5 changes: 3 additions & 2 deletions apps/meteor/client/startup/listCustomSounds.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import type { ICustomSound } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';

import { CustomSounds } from '../../app/custom-sounds/client/lib/CustomSounds';
import { CachedCollectionManager } from '../../app/ui-cached-collection/client';

Meteor.startup(() =>
CachedCollectionManager.onLogin(() => {
Meteor.call('listCustomSounds', (_error: Error | null, result: any[]) => {
for (const sound of result) {
Meteor.call('listCustomSounds', (_error?: Error, result?: ICustomSound[]) => {
for (const sound of result ?? []) {
CustomSounds.add(sound);
}
});
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/client/startup/listCustomUserStatus.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ICustomUserStatus, UserStatus } from '@rocket.chat/core-typings';
import type { ICustomUserStatus } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';

Expand All @@ -19,7 +19,7 @@ Meteor.startup(() => {
const newUserStatus = {
name: customStatus.name,
id: customStatus._id,
statusType: customStatus.statusType as UserStatus,
statusType: customStatus.statusType,
localizeName: false,
};

Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/client/startup/livechatNotifyUnreadRooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { settings } from '../../app/settings/client';
import { getUserPreference } from '../../app/utils/client';

Meteor.startup(() => {
let audio: HTMLMediaElement | null = null;
let audio: HTMLMediaElement | undefined;

Tracker.autorun(() => {
if (!settings.get('Livechat_continuous_sound_notification_new_livechat_room')) {
Expand Down Expand Up @@ -35,6 +35,6 @@ Meteor.startup(() => {

const newRoomNotification = getUserPreference(user, 'newRoomNotification');

audio = CustomSounds.play(newRoomNotification, { loop: true }) as HTMLMediaElement | null;
audio = CustomSounds.play(newRoomNotification, { loop: true });
});
});
Loading

0 comments on commit 397fc66

Please sign in to comment.