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(promise.await): createRoom.ts, createDirectRoom.ts and cleanRoomHistory.ts #28492

Merged
merged 9 commits into from Mar 20, 2023
6 changes: 3 additions & 3 deletions apps/meteor/app/discussion/server/methods/createDiscussion.ts
Expand Up @@ -58,7 +58,7 @@ type CreateDiscussionProperties = {
encrypted?: boolean;
};

const create = ({ prid, pmid, t_name: discussionName, reply, users, user, encrypted }: CreateDiscussionProperties) => {
const create = async ({ prid, pmid, t_name: discussionName, reply, users, user, encrypted }: CreateDiscussionProperties) => {
// if you set both, prid and pmid, and the rooms dont match... should throw an error)
let message: undefined | IMessage;
if (pmid) {
Expand Down Expand Up @@ -138,7 +138,7 @@ const create = ({ prid, pmid, t_name: discussionName, reply, users, user, encryp
});
}

const discussion = createRoom(
const discussion = await createRoom(
type,
name,
user.username as string,
Expand Down Expand Up @@ -196,7 +196,7 @@ Meteor.methods<ServerMethods>({
* @param {string[]} users - users to be added
* @param {boolean} encrypted - if the discussion's e2e encryption should be enabled.
*/
createDiscussion({ prid, pmid, t_name: discussionName, reply, users, encrypted }: CreateDiscussionProperties) {
async createDiscussion({ prid, pmid, t_name: discussionName, reply, users, encrypted }: CreateDiscussionProperties) {
if (!settings.get('Discussion_enabled')) {
throw new Meteor.Error('error-action-not-allowed', 'You are not allowed to create a discussion', { method: 'createDiscussion' });
}
Expand Down
Expand Up @@ -14,7 +14,7 @@ export default function handleJoinedChannel(args) {
let room = Rooms.findOneByName(args.roomName);

if (!room) {
const createdRoom = createRoom('c', args.roomName, user.username, []);
const createdRoom = await createRoom('c', args.roomName, user.username, []);
room = Rooms.findOne({ _id: createdRoom.rid });

this.log(`${user.username} created room ${args.roomName}`);
Expand Down
13 changes: 4 additions & 9 deletions apps/meteor/app/lib/server/functions/cleanRoomHistory.ts
@@ -1,4 +1,3 @@
import type { FindCursor } from 'mongodb';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import type { IMessage, IMessageDiscussion } from '@rocket.chat/core-typings';
import { api } from '@rocket.chat/core-services';
Expand Down Expand Up @@ -45,14 +44,10 @@ export const cleanRoomHistory = function ({
}

if (!ignoreDiscussion) {
Promise.await(
(
Messages.findDiscussionByRoomIdPinnedTimestampAndUsers(rid, excludePinned, ts, fromUsers, {
fields: { drid: 1 },
...(limit && { limit }),
}) as FindCursor<IMessageDiscussion>
).forEach(({ drid }) => deleteRoom(drid)),
);
Messages.findDiscussionByRoomIdPinnedTimestampAndUsers(rid, excludePinned, ts, fromUsers, {
fields: { drid: 1 },
...(limit && { limit }),
}).forEach(({ drid }: IMessageDiscussion) => deleteRoom(drid));
}

if (!ignoreThreads) {
Expand Down
21 changes: 9 additions & 12 deletions apps/meteor/app/lib/server/functions/createDirectRoom.ts
Expand Up @@ -93,22 +93,19 @@ export async function createDirectRoom(
_USERNAMES: usernames,
};

const prevent = Promise.await(
Apps.triggerEvent('IPreRoomCreatePrevent', tmpRoom).catch((error) => {
if (error instanceof AppsEngineException) {
throw new Meteor.Error('error-app-prevented', error.message);
}

throw error;
}),
);
const prevent = await Apps.triggerEvent('IPreRoomCreatePrevent', tmpRoom).catch((error) => {
if (error instanceof AppsEngineException) {
throw new Meteor.Error('error-app-prevented', error.message);
}

throw error;
});

if (prevent) {
throw new Meteor.Error('error-app-prevented', 'A Rocket.Chat App prevented the room creation.');
}

const result = Promise.await(
Apps.triggerEvent('IPreRoomCreateModify', Promise.await(Apps.triggerEvent('IPreRoomCreateExtend', tmpRoom))),
);
const result = await Apps.triggerEvent('IPreRoomCreateModify', await Apps.triggerEvent('IPreRoomCreateExtend', tmpRoom));

if (typeof result === 'object') {
Object.assign(roomInfo, result);
Expand Down
28 changes: 12 additions & 16 deletions apps/meteor/app/lib/server/functions/createRoom.ts
Expand Up @@ -16,20 +16,20 @@ const isValidName = (name: unknown): name is string => {
};

// eslint-disable-next-line complexity
export const createRoom = <T extends RoomType>(
export const createRoom = async <T extends RoomType>(
type: T,
name: T extends 'd' ? undefined : string,
ownerUsername: string | undefined,
members: T extends 'd' ? IUser[] : string[] = [],
readOnly?: boolean,
roomExtraData?: Partial<IRoom> & { customFields?: unknown },
options?: ICreateRoomParams['options'],
): ICreatedRoom => {
): Promise<ICreatedRoom> => {
const { teamId, ...extraData } = roomExtraData || ({} as IRoom);
callbacks.run('beforeCreateRoom', { type, name, owner: ownerUsername, members, readOnly, extraData, options });

if (type === 'd') {
return Promise.await(createDirectRoom(members as IUser[], extraData, { ...options, creator: options?.creator || ownerUsername }));
return createDirectRoom(members as IUser[], extraData, { ...options, creator: options?.creator || ownerUsername });
}

if (!isValidName(name)) {
Expand Down Expand Up @@ -81,7 +81,7 @@ export const createRoom = <T extends RoomType>(
};

if (teamId) {
const team = Promise.await(Team.getOneById(teamId, { projection: { _id: 1 } }));
const team = await Team.getOneById(teamId, { projection: { _id: 1 } });
if (team) {
roomProps.teamId = team._id;
}
Expand All @@ -92,23 +92,19 @@ export const createRoom = <T extends RoomType>(
_USERNAMES: members,
};

const prevent = Promise.await(
Apps.triggerEvent('IPreRoomCreatePrevent', tmp).catch((error) => {
if (error instanceof AppsEngineException) {
throw new Meteor.Error('error-app-prevented', error.message);
}
const prevent = await Apps.triggerEvent('IPreRoomCreatePrevent', tmp).catch((error) => {
if (error instanceof AppsEngineException) {
throw new Meteor.Error('error-app-prevented', error.message);
}

throw error;
}),
);
throw error;
});

if (prevent) {
throw new Meteor.Error('error-app-prevented', 'A Rocket.Chat App prevented the room creation.');
}

const eventResult = Promise.await(
Apps.triggerEvent('IPreRoomCreateModify', Promise.await(Apps.triggerEvent('IPreRoomCreateExtend', tmp))),
);
const eventResult = await Apps.triggerEvent('IPreRoomCreateModify', await Apps.triggerEvent('IPreRoomCreateExtend', tmp));

if (eventResult && typeof eventResult === 'object' && delete eventResult._USERNAMES) {
Object.assign(roomProps, eventResult);
Expand Down Expand Up @@ -164,7 +160,7 @@ export const createRoom = <T extends RoomType>(

if (type === 'c') {
if (room.teamId) {
const team = Promise.await(Team.getOneById(room.teamId));
const team = await Team.getOneById(room.teamId);
team && Messages.createUserAddRoomToTeamWithRoomIdAndUser(team.roomId, room.name, owner);
}
callbacks.run('afterCreateChannel', owner, room);
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/lib/server/methods/createChannel.ts
Expand Up @@ -20,7 +20,7 @@ declare module '@rocket.chat/ui-contexts' {
}

Meteor.methods<ServerMethods>({
createChannel(name, members, readOnly = false, customFields = {}, extraData = {}) {
async createChannel(name, members, readOnly = false, customFields = {}, extraData = {}) {
check(name, String);
check(members, Match.Optional([String]));

Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/lib/server/methods/createPrivateGroup.js
Expand Up @@ -5,7 +5,7 @@ import { hasPermission } from '../../../authorization/server';
import { createRoom } from '../functions';

Meteor.methods({
createPrivateGroup(name, members, readOnly = false, customFields = {}, extraData = {}) {
async createPrivateGroup(name, members, readOnly = false, customFields = {}, extraData = {}) {
check(name, String);
check(members, Match.Optional([String]));

Expand Down
12 changes: 6 additions & 6 deletions apps/meteor/app/meteor-accounts-saml/server/lib/SAML.ts
Expand Up @@ -77,7 +77,7 @@ export class SAML {
await CredentialTokens.create(credentialToken, loginResult);
}

public static insertOrUpdateSAMLUser(userObject: ISAMLUser): { userId: string; token: string } {
public static async insertOrUpdateSAMLUser(userObject: ISAMLUser): Promise<{ userId: string; token: string }> {
const {
generateUsername,
immutableProperty,
Expand Down Expand Up @@ -166,7 +166,7 @@ export class SAML {
user = Users.findOne(userId);

if (userObject.channels && channelsAttributeUpdate !== true) {
SAML.subscribeToSAMLChannels(userObject.channels, user);
await SAML.subscribeToSAMLChannels(userObject.channels, user);
}
}

Expand Down Expand Up @@ -205,7 +205,7 @@ export class SAML {
}

if (userObject.channels && channelsAttributeUpdate === true) {
SAML.subscribeToSAMLChannels(userObject.channels, user);
await SAML.subscribeToSAMLChannels(userObject.channels, user);
}

Users.update(
Expand Down Expand Up @@ -467,10 +467,10 @@ export class SAML {
.replace(/^\w/, (u) => u.toUpperCase());
}

private static subscribeToSAMLChannels(channels: Array<string>, user: IUser): void {
private static async subscribeToSAMLChannels(channels: Array<string>, user: IUser): Promise<void> {
const { includePrivateChannelsInUpdate } = SAMLUtils.globalSettings;
try {
for (let roomName of channels) {
for await (let roomName of channels) {
roomName = roomName.trim();
if (!roomName) {
continue;
Expand All @@ -492,7 +492,7 @@ export class SAML {
if (!room && !privRoom) {
// If the user doesn't have an username yet, we can't create new rooms for them
if (user.username) {
createRoom('c', roomName, user.username);
await createRoom('c', roomName, user.username);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/meteor-accounts-saml/server/loginHandler.ts
Expand Up @@ -11,7 +11,7 @@ const makeError = (message: string): Record<string, any> => ({
error: new Meteor.Error(Accounts.LoginCancelledError.numericError, message),
});

Accounts.registerLoginHandler('saml', function (loginRequest) {
Accounts.registerLoginHandler('saml', async function (loginRequest) {
if (!loginRequest.saml || !loginRequest.credentialToken || typeof loginRequest.credentialToken !== 'string') {
return undefined;
}
Expand All @@ -29,7 +29,7 @@ Accounts.registerLoginHandler('saml', function (loginRequest) {

try {
const userObject = SAMLUtils.mapProfileToUserObject(loginResult.profile);
const updatedUser = SAML.insertOrUpdateSAMLUser(userObject);
const updatedUser = await SAML.insertOrUpdateSAMLUser(userObject);
SAMLUtils.events.emit('updateCustomFields', loginResult, updatedUser);

return updatedUser;
Expand Down
10 changes: 5 additions & 5 deletions apps/meteor/app/slackbridge/server/RocketAdapter.js
Expand Up @@ -226,7 +226,7 @@ export default class RocketAdapter {
}
}

getChannel(slackMessage) {
async getChannel(slackMessage) {
return slackMessage.channel ? this.findChannel(slackMessage.channel) || this.addChannel(slackMessage.channel) : null;
}

Expand Down Expand Up @@ -259,11 +259,11 @@ export default class RocketAdapter {
return slackChannel.creator ? this.findUser(slackChannel.creator) || this.addUser(slackChannel.creator) : null;
}

addChannel(slackChannelID, hasRetried = false) {
async addChannel(slackChannelID, hasRetried = false) {
rocketLogger.debug('Adding Rocket.Chat channel from Slack', slackChannelID);
let addedRoom;

this.slackAdapters.forEach((slack) => {
for await (const slack of this.slackAdapters) {
if (addedRoom) {
return;
}
Expand Down Expand Up @@ -292,7 +292,7 @@ export default class RocketAdapter {

try {
const isPrivate = slackChannel.is_private;
const rocketChannel = createRoom(isPrivate ? 'p' : 'c', slackChannel.name, rocketUserCreator.username, rocketUsers);
const rocketChannel = await createRoom(isPrivate ? 'p' : 'c', slackChannel.name, rocketUserCreator.username, rocketUsers);
rocketChannel.rocketId = rocketChannel.rid;
} catch (e) {
if (!hasRetried) {
Expand Down Expand Up @@ -324,7 +324,7 @@ export default class RocketAdapter {

addedRoom = Rooms.findOneById(slackChannel.rocketId);
}
});
}

if (!addedRoom) {
rocketLogger.debug('Channel not added');
Expand Down
16 changes: 8 additions & 8 deletions apps/meteor/app/slackbridge/server/SlackAdapter.js
Expand Up @@ -477,10 +477,10 @@ export default class SlackAdapter {
if (slackMessage.subtype) {
switch (slackMessage.subtype) {
case 'message_deleted':
this.processMessageDeleted(slackMessage);
await this.processMessageDeleted(slackMessage);
break;
case 'message_changed':
this.processMessageChanged(slackMessage);
await this.processMessageChanged(slackMessage);
break;
case 'channel_join':
this.processChannelJoin(slackMessage);
Expand Down Expand Up @@ -784,7 +784,7 @@ export default class SlackAdapter {
const file = slackMessage.files[0];

if (file && file.url_private_download !== undefined) {
const rocketChannel = this.rocket.getChannel(slackMessage);
const rocketChannel = await this.rocket.getChannel(slackMessage);
const rocketUser = this.rocket.getUser(slackMessage.user);

// Hack to notify that a file was attempted to be uploaded
Expand All @@ -811,9 +811,9 @@ export default class SlackAdapter {
/*
https://api.slack.com/events/message/message_deleted
*/
processMessageDeleted(slackMessage) {
async processMessageDeleted(slackMessage) {
if (slackMessage.previous_message) {
const rocketChannel = this.rocket.getChannel(slackMessage);
const rocketChannel = await this.rocket.getChannel(slackMessage);
const rocketUser = Users.findOneById('rocket.cat', { fields: { username: 1 } });

if (rocketChannel && rocketUser) {
Expand All @@ -837,13 +837,13 @@ export default class SlackAdapter {
/*
https://api.slack.com/events/message/message_changed
*/
processMessageChanged(slackMessage) {
async processMessageChanged(slackMessage) {
if (slackMessage.previous_message) {
const currentMsg = Messages.findOneById(this.rocket.createRocketID(slackMessage.channel, slackMessage.message.ts));

// Only process this change, if its an actual update (not just Slack repeating back our Rocket original change)
if (currentMsg && slackMessage.message.text !== currentMsg.msg) {
const rocketChannel = this.rocket.getChannel(slackMessage);
const rocketChannel = await this.rocket.getChannel(slackMessage);
const rocketUser = slackMessage.previous_message.user
? this.rocket.findUser(slackMessage.previous_message.user) || this.rocket.addUser(slackMessage.previous_message.user)
: null;
Expand All @@ -866,7 +866,7 @@ export default class SlackAdapter {
This method will get refactored and broken down into single responsibilities
*/
async processNewMessage(slackMessage, isImporting) {
const rocketChannel = this.rocket.getChannel(slackMessage);
const rocketChannel = await this.rocket.getChannel(slackMessage);
let rocketUser = null;
if (slackMessage.subtype === 'bot_message') {
rocketUser = Users.findOneById('rocket.cat', { fields: { username: 1 } });
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/utils/lib/slashCommand.ts
Expand Up @@ -79,7 +79,7 @@ export const slashCommands = {
throw new Meteor.Error('invalid-command-usage', 'Executing a command requires at least a message with a room id.');
}

const previewInfo = cmd.previewer(command, params, message);
const previewInfo = Promise.await(cmd.previewer(command, params, message));

if (!previewInfo?.items?.length) {
return;
Expand Down Expand Up @@ -113,7 +113,7 @@ export const slashCommands = {
throw new Meteor.Error('error-invalid-preview', 'Preview Item must have an id, type, and value.');
}

return cmd.previewCallback(command, params, message, preview, triggerId);
return Promise.await(cmd.previewCallback(command, params, message, preview, triggerId));
},
};

Expand Down
6 changes: 3 additions & 3 deletions apps/meteor/ee/server/configuration/oauth.ts
Expand Up @@ -55,13 +55,13 @@ function getChannelsMap(channelsMap: string): Record<string, any> | undefined {
}

onLicense('oauth-enterprise', () => {
callbacks.add('afterProcessOAuthUser', (auth: IOAuthUserService) => {
callbacks.add('afterProcessOAuthUser', async (auth: IOAuthUserService) => {
auth.serviceName = capitalize(auth.serviceName);
const settings = getOAuthSettings(auth.serviceName);

if (settings.mapChannels) {
const channelsMap = getChannelsMap(settings.channelsMap);
OAuthEEManager.mapSSOGroupsToChannels(auth.user, auth.serviceData, settings.groupsClaim, channelsMap, settings.channelsAdmin);
await OAuthEEManager.mapSSOGroupsToChannels(auth.user, auth.serviceData, settings.groupsClaim, channelsMap, settings.channelsAdmin);
}

if (settings.mergeRoles) {
Expand All @@ -80,7 +80,7 @@ onLicense('oauth-enterprise', () => {

if (settings.mapChannels) {
const channelsMap = getChannelsMap(settings.channelsMap);
OAuthEEManager.mapSSOGroupsToChannels(auth.user, auth.identity, settings.groupsClaim, channelsMap, settings.channelsAdmin);
await OAuthEEManager.mapSSOGroupsToChannels(auth.user, auth.identity, settings.groupsClaim, channelsMap, settings.channelsAdmin);
}

if (settings.mergeRoles) {
Expand Down