Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Move bad words filter callback to service #30241

Merged
merged 17 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from 15 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
5 changes: 2 additions & 3 deletions apps/meteor/app/api/server/v1/channels.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Team } from '@rocket.chat/core-services';
import { Team, Room } from '@rocket.chat/core-services';
import type { IRoom, ISubscription, IUser, RoomType } from '@rocket.chat/core-typings';
import { Integrations, Messages, Rooms, Subscriptions, Uploads, Users } from '@rocket.chat/models';
import {
Expand Down Expand Up @@ -31,7 +31,6 @@ import { saveRoomSettings } from '../../../channel-settings/server/methods/saveR
import { mountIntegrationQueryBasedOnPermissions } from '../../../integrations/server/lib/mountQueriesBasedOnPermission';
import { addUsersToRoomMethod } from '../../../lib/server/methods/addUsersToRoom';
import { createChannelMethod } from '../../../lib/server/methods/createChannel';
import { joinRoomMethod } from '../../../lib/server/methods/joinRoom';
import { leaveRoomMethod } from '../../../lib/server/methods/leaveRoom';
import { settings } from '../../../settings/server';
import { normalizeMessagesForUser } from '../../../utils/server/lib/normalizeMessagesForUser';
Expand Down Expand Up @@ -209,7 +208,7 @@ API.v1.addRoute(
const { joinCode, ...params } = this.bodyParams;
const findResult = await findChannelByIdOrName({ params });

await joinRoomMethod(this.userId, findResult._id, joinCode);
await Room.join({ room: findResult, user: this.user, joinCode });

return API.v1.success({
channel: await findChannelByIdOrName({ params, userId: this.userId }),
Expand Down
29 changes: 0 additions & 29 deletions apps/meteor/app/discussion/server/hooks/joinDiscussionOnMessage.ts

This file was deleted.

5 changes: 0 additions & 5 deletions apps/meteor/app/lib/server/functions/notifications/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { escapeRegExp } from '@rocket.chat/string-helpers';
import { callbacks } from '../../../../../lib/callbacks';
import { i18n } from '../../../../../server/lib/i18n';
import { settings } from '../../../../settings/server';
import { joinRoomMethod } from '../../methods/joinRoom';

/**
* This function returns a string ready to be shown in the notification
Expand Down Expand Up @@ -66,7 +65,3 @@ export function messageContainsHighlight(message: IMessage, highlights: string[]
return regexp.test(message.msg);
});
}

export async function callJoinRoom(userId: string, rid: string): Promise<void> {
await joinRoomMethod(userId, rid);
}
3 changes: 3 additions & 0 deletions apps/meteor/app/lib/server/functions/sendMessage.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Message } from '@rocket.chat/core-services';
import { Messages } from '@rocket.chat/models';
import { Match, check } from 'meteor/check';

Expand Down Expand Up @@ -247,6 +248,8 @@ export const sendMessage = async function (user, message, room, upsert = false,

parseUrlsInMessage(message, previewUrls);

message = await Message.beforeSave({ message, room, user });

message = await callbacks.run('beforeSaveMessage', message, room);
if (message) {
if (message.t === 'otr') {
Expand Down
15 changes: 9 additions & 6 deletions apps/meteor/app/lib/server/functions/updateMessage.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Message } from '@rocket.chat/core-services';
import type { IEditedMessage, IMessage, IUser, AtLeast } from '@rocket.chat/core-typings';
import { Messages, Rooms } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
Expand Down Expand Up @@ -48,6 +49,14 @@ export const updateMessage = async function (

parseUrlsInMessage(message, previewUrls);

const room = await Rooms.findOneById(message.rid);
if (!room) {
return;
}

// TODO remove type cast
message = await Message.beforeSave({ message: message as IMessage, room, user });

message = await callbacks.run('beforeSaveMessage', message);

const { _id, ...editedMessage } = message;
Expand All @@ -67,12 +76,6 @@ export const updateMessage = async function (
},
);

const room = await Rooms.findOneById(message.rid);

if (!room) {
return;
}

if (Apps?.isLoaded()) {
// This returns a promise, but it won't mutate anything about the message
// so, we don't really care if it is successful or fails
Expand Down
1 change: 0 additions & 1 deletion apps/meteor/app/lib/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import './methods/deleteUserOwnAccount';
import './methods/executeSlashCommandPreview';
import './startup/filterATAllTag';
import './startup/filterATHereTag';
import './methods/filterBadWords';
import './methods/getChannelHistory';
import './methods/getRoomJoinCode';
import './methods/getRoomRoles';
Expand Down
10 changes: 3 additions & 7 deletions apps/meteor/app/lib/server/lib/sendNotificationsOnMessage.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Room } from '@rocket.chat/core-services';
import { Subscriptions, Users } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import moment from 'moment';
Expand All @@ -7,12 +8,7 @@ import { roomCoordinator } from '../../../../server/lib/rooms/roomCoordinator';
import { hasPermissionAsync } from '../../../authorization/server/functions/hasPermission';
import { Notification } from '../../../notification-queue/server/NotificationQueue';
import { settings } from '../../../settings/server';
import {
callJoinRoom,
messageContainsHighlight,
parseMessageTextPerUser,
replaceMentionedUsernamesWithFullNames,
} from '../functions/notifications';
import { messageContainsHighlight, parseMessageTextPerUser, replaceMentionedUsernamesWithFullNames } from '../functions/notifications';
import { notifyDesktopUser, shouldNotifyDesktop } from '../functions/notifications/desktop';
import { getEmailData, shouldNotifyEmail } from '../functions/notifications/email';
import { getPushData, shouldNotifyMobile } from '../functions/notifications/mobile';
Expand Down Expand Up @@ -365,7 +361,7 @@ export async function sendAllNotifications(message, room) {

const users = await Promise.all(
mentions.map(async (userId) => {
await callJoinRoom(userId, room._id);
await Room.join({ room, user: { _id: userId } });

return userId;
}),
Expand Down
65 changes: 0 additions & 65 deletions apps/meteor/app/lib/server/methods/filterBadWords.ts

This file was deleted.

52 changes: 10 additions & 42 deletions apps/meteor/app/lib/server/methods/joinRoom.ts
Original file line number Diff line number Diff line change
@@ -1,63 +1,31 @@
import type { IRoom, IRoomWithJoinCode, IUser } from '@rocket.chat/core-typings';
import { Rooms, Users } from '@rocket.chat/models';
import { Room } from '@rocket.chat/core-services';
import type { IRoom } from '@rocket.chat/core-typings';
import { Rooms } from '@rocket.chat/models';
import type { ServerMethods } from '@rocket.chat/ui-contexts';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';

import { RoomMemberActions } from '../../../../definition/IRoomTypeConfig';
import { roomCoordinator } from '../../../../server/lib/rooms/roomCoordinator';
import { canAccessRoomAsync } from '../../../authorization/server';
import { hasPermissionAsync } from '../../../authorization/server/functions/hasPermission';
import { addUserToRoom } from '../functions/addUserToRoom';

declare module '@rocket.chat/ui-contexts' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
joinRoom(rid: IRoom['_id'], code?: unknown): boolean | undefined;
joinRoom(rid: IRoom['_id'], code?: string): boolean | undefined;
}
}

export const joinRoomMethod = async (userId: IUser['_id'], rid: IRoom['_id'], code?: unknown): Promise<boolean | undefined> => {
check(rid, String);

const user = await Users.findOneById(userId);

if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'joinRoom' });
}

const room = await Rooms.findOneById<IRoomWithJoinCode>(rid);

if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'joinRoom' });
}

if (!(await roomCoordinator.getRoomDirectives(room.t)?.allowMemberAction(room, RoomMemberActions.JOIN, user._id))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'joinRoom' });
}

if (!(await canAccessRoomAsync(room, user))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'joinRoom' });
}
if (room.joinCodeRequired === true && code !== room.joinCode && !(await hasPermissionAsync(user._id, 'join-without-join-code'))) {
throw new Meteor.Error('error-code-invalid', 'Invalid Room Password', {
method: 'joinRoom',
});
}

return addUserToRoom(rid, user);
};

Meteor.methods<ServerMethods>({
async joinRoom(rid, code) {
check(rid, String);

const userId = await Meteor.userId();

if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'joinRoom' });
}

return joinRoomMethod(userId, rid, code);
const room = await Rooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'joinRoom' });
}

return Room.join({ room, user: { _id: userId }, ...(code ? { joinCode: code } : {}) });
},
});
23 changes: 12 additions & 11 deletions apps/meteor/app/message-pin/server/pinMessage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Message } from '@rocket.chat/core-services';
import { isQuoteAttachment } from '@rocket.chat/core-typings';
import type { IMessage, IUser, MessageAttachment, MessageQuoteAttachment } from '@rocket.chat/core-typings';
import { isQuoteAttachment, isRegisterUser } from '@rocket.chat/core-typings';
import type { IMessage, MessageAttachment, MessageQuoteAttachment } from '@rocket.chat/core-typings';
import { Messages, Rooms, Subscriptions, Users, ReadReceipts } from '@rocket.chat/models';
import type { ServerMethods } from '@rocket.chat/ui-contexts';
import { check } from 'meteor/check';
Expand Down Expand Up @@ -82,15 +82,13 @@ Meteor.methods<ServerMethods>({
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'pinMessage' });
}

const me = await Users.findOneById<Required<Pick<IUser, '_id' | 'username' | 'name'>>>(userId, {
projection: { username: 1, name: 1 },
});
const me = await Users.findOneById(userId);
if (!me) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'pinMessage' });
}

// If we keep history of edits, insert a new message to store history information
if (settings.get('Message_KeepHistory') && me.username) {
if (settings.get('Message_KeepHistory') && isRegisterUser(me)) {
await Messages.cloneAndSaveAsHistoryById(message._id, me);
}

Expand All @@ -110,6 +108,8 @@ Meteor.methods<ServerMethods>({
username: me.username,
};

originalMessage = await Message.beforeSave({ message: originalMessage, room, user: me });

originalMessage = await callbacks.run('beforeSaveMessage', originalMessage);

await Messages.setPinnedByIdAndUserId(originalMessage._id, originalMessage.pinnedBy, originalMessage.pinned);
Expand Down Expand Up @@ -186,15 +186,13 @@ Meteor.methods<ServerMethods>({
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'unpinMessage' });
}

const me = await Users.findOneById<Required<Pick<IUser, '_id' | 'username' | 'name'>>>(userId, {
projection: { username: 1, name: 1 },
});
const me = await Users.findOneById(userId);
if (!me) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'unpinMessage' });
}

// If we keep history of edits, insert a new message to store history information
if (settings.get('Message_KeepHistory') && me.username) {
if (settings.get('Message_KeepHistory') && isRegisterUser(me)) {
await Messages.cloneAndSaveAsHistoryById(originalMessage._id, me);
}

Expand All @@ -203,7 +201,6 @@ Meteor.methods<ServerMethods>({
_id: userId,
username: me.username,
};
originalMessage = await callbacks.run('beforeSaveMessage', originalMessage);

const room = await Rooms.findOneById(originalMessage.rid, { projection: { ...roomAccessAttributes, lastMessage: 1 } });
if (!room) {
Expand All @@ -214,6 +211,10 @@ Meteor.methods<ServerMethods>({
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'unpinMessage' });
}

originalMessage = await Message.beforeSave({ message: originalMessage, room, user: me });

originalMessage = await callbacks.run('beforeSaveMessage', originalMessage);

if (isTheLastMessage(room, message)) {
await Rooms.setLastMessagePinned(room._id, originalMessage.pinnedBy, originalMessage.pinned);
}
Expand Down
Loading