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

refactor: remove method calls from chat endpoints (server) #35069

Open
wants to merge 12 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
41 changes: 33 additions & 8 deletions apps/meteor/app/api/server/v1/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { escapeRegExp } from '@rocket.chat/string-helpers';
import { Meteor } from 'meteor/meteor';

import { reportMessage } from '../../../../server/lib/moderation/reportMessage';
import { ignoreUser } from '../../../../server/methods/ignoreUser';
import { messageSearch } from '../../../../server/methods/messageSearch';
import { getMessageHistory } from '../../../../server/publications/messages';
import { roomAccessAttributes } from '../../../authorization/server';
Expand All @@ -42,13 +43,17 @@ import { canSendMessageAsync } from '../../../authorization/server/functions/can
import { hasPermissionAsync } from '../../../authorization/server/functions/hasPermission';
import { deleteMessageValidatingPermission } from '../../../lib/server/functions/deleteMessage';
import { processWebhookMessage } from '../../../lib/server/functions/processWebhookMessage';
import { getSingleMessage } from '../../../lib/server/methods/getSingleMessage';
import { executeSendMessage } from '../../../lib/server/methods/sendMessage';
import { executeUpdateMessage } from '../../../lib/server/methods/updateMessage';
import { applyAirGappedRestrictionsValidation } from '../../../license/server/airGappedRestrictionsWrapper';
import { pinMessage } from '../../../message-pin/server/pinMessage';
import { pinMessage, unpinMessage } from '../../../message-pin/server/pinMessage';
import { starMessage } from '../../../message-star/server/starMessage';
import { OEmbed } from '../../../oembed/server/server';
import { executeSetReaction } from '../../../reactions/server/setReaction';
import { settings } from '../../../settings/server';
import { followMessage } from '../../../threads/server/methods/followMessage';
import { unfollowMessage } from '../../../threads/server/methods/unfollowMessage';
import { MessageTypes } from '../../../ui-utils/server';
import { normalizeMessagesForUser } from '../../../utils/server/lib/normalizeMessagesForUser';
import { API } from '../api';
Expand Down Expand Up @@ -148,7 +153,11 @@ API.v1.addRoute(
},
{
async get() {
const msg = await Meteor.callAsync('getSingleMessage', this.queryParams.msgId);
if (!this.queryParams.msgId) {
return API.v1.failure('The "msgId" query parameter must be provided.');
}

const msg = await getSingleMessage(this.userId, this.queryParams.msgId);

if (!msg) {
return API.v1.failure();
Expand Down Expand Up @@ -289,7 +298,7 @@ API.v1.addRoute(
throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.');
}

await Meteor.callAsync('starMessage', {
await starMessage(this.userId, {
_id: msg._id,
rid: msg.rid,
starred: true,
Expand All @@ -311,7 +320,7 @@ API.v1.addRoute(
throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.');
}

await Meteor.callAsync('unpinMessage', msg);
await unpinMessage(this.userId, msg);

return API.v1.success();
},
Expand All @@ -329,7 +338,7 @@ API.v1.addRoute(
throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.');
}

await Meteor.callAsync('starMessage', {
await starMessage(this.userId, {
_id: msg._id,
rid: msg.rid,
starred: false,
Expand Down Expand Up @@ -437,7 +446,15 @@ API.v1.addRoute(

ignore = typeof ignore === 'string' ? /true|1/.test(ignore) : ignore;

await Meteor.callAsync('ignoreUser', { rid, userId, ignore });
if (!rid?.trim()) {
throw new Meteor.Error('error-room-id-param-not-provided', 'The required "rid" param is missing.');
}

if (!userId?.trim()) {
throw new Meteor.Error('error-user-id-param-not-provided', 'The required "userId" param is missing.');
}

await ignoreUser(this.userId, { rid, userId, ignore });

return API.v1.success();
},
Expand Down Expand Up @@ -685,7 +702,11 @@ API.v1.addRoute(
async post() {
const { mid } = this.bodyParams;

await Meteor.callAsync('followMessage', { mid });
if (!mid) {
throw new Meteor.Error('The required "mid" body param is missing.');
}

await followMessage(this.userId, { mid });

return API.v1.success();
},
Expand All @@ -699,7 +720,11 @@ API.v1.addRoute(
async post() {
const { mid } = this.bodyParams;

await Meteor.callAsync('unfollowMessage', { mid });
if (!mid) {
throw new Meteor.Error('The required "mid" body param is missing.');
}

await unfollowMessage(this.userId, { mid });

return API.v1.success();
},
Expand Down
26 changes: 15 additions & 11 deletions apps/meteor/app/lib/server/methods/getSingleMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ declare module '@rocket.chat/ddp-client' {
}
}

export const getSingleMessage = async (userId: string, mid: IMessage['_id']): Promise<IMessage | null> => {
const msg = await Messages.findOneById(mid);

if (!msg?.rid) {
return null;
}

if (!(await canAccessRoomIdAsync(msg.rid, userId))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getSingleMessage' });
}

return msg;
};

Meteor.methods<ServerMethods>({
async getSingleMessage(mid) {
check(mid, String);
Expand All @@ -23,16 +37,6 @@ Meteor.methods<ServerMethods>({
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getSingleMessage' });
}

const msg = await Messages.findOneById(mid);

if (!msg?.rid) {
return null;
}

if (!(await canAccessRoomIdAsync(msg.rid, uid))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getSingleMessage' });
}

return msg;
return getSingleMessage(uid, mid);
},
});
168 changes: 86 additions & 82 deletions apps/meteor/app/message-pin/server/pinMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,15 @@ declare module '@rocket.chat/ddp-client' {
}
}

export async function pinMessage(originalMessage: IMessage, userId: string, pinnedAt?: Date) {
export async function pinMessage(message: IMessage, userId: string, pinnedAt?: Date) {
let originalMessage = await Messages.findOneById(message._id);
if (!originalMessage?.rid) {
throw new Meteor.Error('error-invalid-message', 'Message you are pinning was not found', {
method: 'pinMessage',
action: 'Message_pinning',
});
}

if (!settings.get('Message_AllowPinning')) {
throw new Meteor.Error('error-action-not-allowed', 'Message pinning not allowed', {
method: 'pinMessage',
Expand Down Expand Up @@ -118,6 +126,81 @@ export async function pinMessage(originalMessage: IMessage, userId: string, pinn
});
}

export const unpinMessage = async (userId: string, message: IMessage) => {
if (!settings.get('Message_AllowPinning')) {
throw new Meteor.Error('error-action-not-allowed', 'Message pinning not allowed', {
method: 'unpinMessage',
action: 'Message_pinning',
});
}

let originalMessage = await Messages.findOneById(message._id);
if (originalMessage == null || originalMessage._id == null) {
throw new Meteor.Error('error-invalid-message', 'Message you are unpinning was not found', {
method: 'unpinMessage',
action: 'Message_pinning',
});
}

const subscription = await Subscriptions.findOneByRoomIdAndUserId(originalMessage.rid, userId, { projection: { _id: 1 } });
if (!subscription) {
// If it's a valid message but on a room that the user is not subscribed to, report that the message was not found.
throw new Meteor.Error('error-invalid-message', 'Message you are unpinning was not found', {
method: 'unpinMessage',
action: 'Message_pinning',
});
}

if (!(await hasPermissionAsync(userId, 'pin-message', originalMessage.rid))) {
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'unpinMessage' });
}

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') && isRegisterUser(me)) {
await Messages.cloneAndSaveAsHistoryById(originalMessage._id, me);
}

originalMessage.pinned = false;
originalMessage.pinnedBy = {
_id: userId,
username: me.username,
};

const room = await Rooms.findOneById(originalMessage.rid, { projection: { ...roomAccessAttributes, lastMessage: 1 } });
if (!room) {
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'unpinMessage' });
}

if (!(await canAccessRoomAsync(room, { _id: userId }))) {
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'unpinMessage' });
}

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

if (isTheLastMessage(room, message)) {
await Rooms.setLastMessagePinned(room._id, originalMessage.pinnedBy, originalMessage.pinned);
void notifyOnRoomChangedById(room._id);
}

// App IPostMessagePinned event hook
await Apps.self?.triggerEvent(AppEvents.IPostMessagePinned, originalMessage, await Meteor.userAsync(), originalMessage.pinned);

await Messages.setPinnedByIdAndUserId(originalMessage._id, originalMessage.pinnedBy, originalMessage.pinned);
if (settings.get('Message_Read_Receipt_Store_Users')) {
await ReadReceipts.setPinnedByMessageId(originalMessage._id, originalMessage.pinned);
}
void notifyOnMessageChange({
id: message._id,
});

return true;
};

Meteor.methods<ServerMethods>({
async pinMessage(message, pinnedAt) {
check(message._id, String);
Expand All @@ -129,15 +212,7 @@ Meteor.methods<ServerMethods>({
});
}

const originalMessage = await Messages.findOneById(message._id);
if (!originalMessage?.rid) {
throw new Meteor.Error('error-invalid-message', 'Message you are pinning was not found', {
method: 'pinMessage',
action: 'Message_pinning',
});
}

return pinMessage(originalMessage, userId, pinnedAt);
return pinMessage(message, userId, pinnedAt);
},
async unpinMessage(message) {
check(message._id, String);
Expand All @@ -150,77 +225,6 @@ Meteor.methods<ServerMethods>({
});
}

if (!settings.get('Message_AllowPinning')) {
throw new Meteor.Error('error-action-not-allowed', 'Message pinning not allowed', {
method: 'unpinMessage',
action: 'Message_pinning',
});
}

let originalMessage = await Messages.findOneById(message._id);
if (originalMessage == null || originalMessage._id == null) {
throw new Meteor.Error('error-invalid-message', 'Message you are unpinning was not found', {
method: 'unpinMessage',
action: 'Message_pinning',
});
}

const subscription = await Subscriptions.findOneByRoomIdAndUserId(originalMessage.rid, userId, { projection: { _id: 1 } });
if (!subscription) {
// If it's a valid message but on a room that the user is not subscribed to, report that the message was not found.
throw new Meteor.Error('error-invalid-message', 'Message you are unpinning was not found', {
method: 'unpinMessage',
action: 'Message_pinning',
});
}

if (!(await hasPermissionAsync(userId, 'pin-message', originalMessage.rid))) {
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'unpinMessage' });
}

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') && isRegisterUser(me)) {
await Messages.cloneAndSaveAsHistoryById(originalMessage._id, me);
}

originalMessage.pinned = false;
originalMessage.pinnedBy = {
_id: userId,
username: me.username,
};

const room = await Rooms.findOneById(originalMessage.rid, { projection: { ...roomAccessAttributes, lastMessage: 1 } });
if (!room) {
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'unpinMessage' });
}

if (!(await canAccessRoomAsync(room, { _id: userId }))) {
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'unpinMessage' });
}

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

if (isTheLastMessage(room, message)) {
await Rooms.setLastMessagePinned(room._id, originalMessage.pinnedBy, originalMessage.pinned);
void notifyOnRoomChangedById(room._id);
}

// App IPostMessagePinned event hook
await Apps.self?.triggerEvent(AppEvents.IPostMessagePinned, originalMessage, await Meteor.userAsync(), originalMessage.pinned);

await Messages.setPinnedByIdAndUserId(originalMessage._id, originalMessage.pinnedBy, originalMessage.pinned);
if (settings.get('Message_Read_Receipt_Store_Users')) {
await ReadReceipts.setPinnedByMessageId(originalMessage._id, originalMessage.pinned);
}
void notifyOnMessageChange({
id: message._id,
});

return true;
return unpinMessage(userId, message);
},
});
Loading
Loading