Skip to content

Commit

Permalink
refactor(models): Use Messages Raw model (5/N) (#28590)
Browse files Browse the repository at this point in the history
  • Loading branch information
sampaiodiego authored Mar 24, 2023
1 parent 4dfe071 commit a791efa
Show file tree
Hide file tree
Showing 17 changed files with 145 additions and 159 deletions.
2 changes: 1 addition & 1 deletion apps/meteor/app/api/server/v1/rooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ API.v1.addRoute(
throw new Meteor.Error('error-invalid-messages');
}

const result = dataExport.sendViaEmail(
const result = await dataExport.sendViaEmail(
{
rid,
toUsers: (toUsers as string[]) || [],
Expand Down
30 changes: 18 additions & 12 deletions apps/meteor/app/autotranslate/server/autotranslate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ import type {
ISupportedLanguage,
ITranslationResult,
} from '@rocket.chat/core-typings';
import { Subscriptions } from '@rocket.chat/models';
import { Messages, Subscriptions } from '@rocket.chat/models';

import { settings } from '../../settings/server';
import { callbacks } from '../../../lib/callbacks';
import { Messages } from '../../models/server';
import { Markdown } from '../../markdown/server';
import { Logger } from '../../logger/server';
import { isTruthy } from '../../../lib/isTruthy';
Expand Down Expand Up @@ -69,10 +68,17 @@ export class TranslationProviderRegistry {
return TranslationProviderRegistry.enabled ? TranslationProviderRegistry.getActiveProvider()?.getSupportedLanguages(target) : undefined;
}

static async translateMessage(message: IMessage, room: IRoom, targetLanguage?: string): Promise<IMessage | undefined> {
return TranslationProviderRegistry.enabled
? TranslationProviderRegistry.getActiveProvider()?.translateMessage(message, room, targetLanguage)
: undefined;
static async translateMessage(message: IMessage, room: IRoom, targetLanguage?: string): Promise<IMessage | null> {
if (!TranslationProviderRegistry.enabled) {
return null;
}

const provider = TranslationProviderRegistry.getActiveProvider();
if (!provider) {
return null;
}

return provider.translateMessage(message, room, targetLanguage);
}

static getProviders(): AutoTranslate[] {
Expand Down Expand Up @@ -283,37 +289,37 @@ export abstract class AutoTranslate {
* @param {object} targetLanguage
* @returns {object} unmodified message object.
*/
async translateMessage(message: IMessage, room: IRoom, targetLanguage?: string): Promise<IMessage> {
async translateMessage(message: IMessage, room: IRoom, targetLanguage?: string): Promise<IMessage | null> {
let targetLanguages: string[];
if (targetLanguage) {
targetLanguages = [targetLanguage];
} else {
targetLanguages = (await Subscriptions.getAutoTranslateLanguagesByRoomAndNotUser(room._id, message.u?._id)).filter(isTruthy);
}
if (message.msg) {
Meteor.defer(() => {
Meteor.defer(async () => {
let targetMessage = Object.assign({}, message);
targetMessage.html = escapeHTML(String(targetMessage.msg));
targetMessage = this.tokenize(targetMessage);

const translations = this._translateMessage(targetMessage, targetLanguages);
if (!_.isEmpty(translations)) {
Messages.addTranslations(message._id, translations, TranslationProviderRegistry[Provider]);
await Messages.addTranslations(message._id, translations, TranslationProviderRegistry[Provider] || '');
}
});
}

if (message.attachments && message.attachments.length > 0) {
Meteor.defer(() => {
for (const [index, attachment] of message.attachments?.entries() ?? []) {
Meteor.defer(async () => {
for await (const [index, attachment] of message.attachments?.entries() ?? []) {
if (attachment.description || attachment.text) {
// Removes the initial link `[ ](quoterl)` from quote message before translation
const translatedText = attachment?.text?.replace(/\[(.*?)\]\(.*?\)/g, '$1') || attachment?.text;
const attachmentMessage = { ...attachment, text: translatedText };
const translations = this._translateAttachmentDescriptions(attachmentMessage, targetLanguages);

if (!_.isEmpty(translations)) {
Messages.addAttachmentTranslations(message._id, index, translations);
await Messages.addAttachmentTranslations(message._id, String(index), translations);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Meteor } from 'meteor/meteor';
import { Integrations } from '@rocket.chat/models';
import { Integrations, Messages } from '@rocket.chat/models';
import { isRoomFederated } from '@rocket.chat/core-typings';

import { Rooms, Messages, Subscriptions } from '../../../models/server';
import { Rooms, Subscriptions } from '../../../models/server';
import { settings } from '../../../settings/server';
import { getValidRoomName } from '../../../utils/server';
import { callbacks } from '../../../../lib/callbacks';
import { checkUsernameAvailability } from '../../../lib/server/functions/checkUsernameAvailability';
Expand Down Expand Up @@ -53,7 +54,7 @@ export async function saveRoomName(rid, displayName, user, sendMessage = true) {

await Integrations.updateRoomName(room.name, displayName);
if (sendMessage) {
Messages.createRoomRenamedWithRoomIdRoomNameAndUser(rid, displayName, user);
await Messages.createRoomRenamedWithRoomIdRoomNameAndUser(rid, displayName, user, settings.get('Message_Read_Receipt_Enabled'));
}
callbacks.run('afterRoomNameChange', { rid, name: displayName, oldName: room.name });
return displayName;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Meteor } from 'meteor/meteor';
import { Match } from 'meteor/check';
import { Rooms, Messages } from '@rocket.chat/models';
import type { IUser } from '@rocket.chat/core-typings';

import { settings } from '../../../settings/server';

export async function saveRoomReadOnly(
rid: string,
readOnly: boolean,
user: Required<Pick<IUser, '_id' | 'username' | 'name'>>,
sendMessage = true,
) {
if (!Match.test(rid, String)) {
throw new Meteor.Error('invalid-room', 'Invalid room', {
function: 'RocketChat.saveRoomReadOnly',
});
}

const result = await Rooms.setReadOnlyById(rid, readOnly);

if (result && sendMessage) {
if (readOnly) {
await Messages.createRoomSetReadOnlyByRoomIdAndUser(rid, user, settings.get('Message_Read_Receipt_Enabled'));
} else {
await Messages.createRoomRemovedReadOnlyByRoomIdAndUser(rid, user, settings.get('Message_Read_Receipt_Enabled'));
}
}
return result;
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type RoomSettings = {
roomCustomFields: unknown;
roomDescription: unknown;
roomType: unknown;
readOnly: unknown;
readOnly: boolean;
reactWhenReadOnly: unknown;
systemMessages: unknown;
default: unknown;
Expand Down Expand Up @@ -203,7 +203,7 @@ const validators: RoomSettingsValidators = {
type RoomSettingsSavers = {
[TRoomSetting in keyof RoomSettings]?: (params: {
userId: IUser['_id'];
user: IUser;
user: IUser & Required<Pick<IUser, 'username' | 'name'>>;
value: RoomSettings[TRoomSetting];
room: IRoom;
rid: IRoom['_id'];
Expand Down Expand Up @@ -270,9 +270,9 @@ const settingSavers: RoomSettingsSavers = {
streamingOptions({ value, rid }) {
saveStreamingOptions(rid, value);
},
readOnly({ value, room, rid, user }) {
async readOnly({ value, room, rid, user }) {
if (value !== room.ro) {
saveRoomReadOnly(rid, value, user);
await saveRoomReadOnly(rid, value, user);
}
},
reactWhenReadOnly({ value, room, rid, user }) {
Expand Down Expand Up @@ -377,7 +377,7 @@ async function save<TRoomSetting extends keyof RoomSettings>(
setting: TRoomSetting,
params: {
userId: IUser['_id'];
user: IUser;
user: IUser & Required<Pick<IUser, 'username' | 'name'>>;
value: RoomSettings[TRoomSetting];
room: IRoom;
rid: IRoom['_id'];
Expand Down Expand Up @@ -448,7 +448,7 @@ async function saveRoomSettings(
});
}

const user = Meteor.user() as IUser | null;
const user = Meteor.user() as (IUser & Required<Pick<IUser, 'username' | 'name'>>) | null;
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'saveRoomSettings',
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/livechat/server/api/v1/videoCall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ API.v1.addRoute(
await Settings.incrementValueById('WebRTC_Calls_Count');
callStatus = 'ringing';
await Rooms.setCallStatusAndCallStartTime(room._id, callStatus);
await Messages.createWithTypeRoomIdMessageAndUser(
Messages.createWithTypeRoomIdMessageAndUser(
'livechat_webrtc_video_call',
room._id,
TAPi18n.__('Join_my_room_to_start_the_video_call'),
Expand Down
49 changes: 0 additions & 49 deletions apps/meteor/app/models/server/models/Messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,6 @@ export class Messages extends Base {
this.tryEnsureIndex({ 'navigation.token': 1 }, { sparse: true });
}

setReactions(messageId, reactions) {
return this.update({ _id: messageId }, { $set: { reactions } });
}

createRoomArchivedByRoomIdAndUser(roomId, user) {
return this.createWithTypeRoomIdMessageAndUser('room-archived', roomId, '', user);
}
Expand All @@ -47,14 +43,6 @@ export class Messages extends Base {
return this.createWithTypeRoomIdMessageAndUser('room-unarchived', roomId, '', user);
}

createRoomSetReadOnlyByRoomIdAndUser(roomId, user) {
return this.createWithTypeRoomIdMessageAndUser('room-set-read-only', roomId, '', user);
}

createRoomRemovedReadOnlyByRoomIdAndUser(roomId, user) {
return this.createWithTypeRoomIdMessageAndUser('room-removed-read-only', roomId, '', user);
}

createRoomAllowedReactingByRoomIdAndUser(roomId, user) {
return this.createWithTypeRoomIdMessageAndUser('room-allowed-reacting', roomId, '', user);
}
Expand All @@ -63,10 +51,6 @@ export class Messages extends Base {
return this.createWithTypeRoomIdMessageAndUser('room-disallowed-reacting', roomId, '', user);
}

unsetReactions(messageId) {
return this.update({ _id: messageId }, { $unset: { reactions: 1 } });
}

updateOTRAck(_id, otrAck) {
const query = { _id };
const update = { $set: { otrAck } };
Expand All @@ -77,28 +61,6 @@ export class Messages extends Base {
return this.createWithTypeRoomIdMessageAndUser(type, roomId, message, user, extraData);
}

createRoomRenamedWithRoomIdRoomNameAndUser(roomId, roomName, user, extraData) {
return this.createWithTypeRoomIdMessageAndUser('r', roomId, roomName, user, extraData);
}

addTranslations(messageId, translations, providerName) {
const updateObj = { translationProvider: providerName };
Object.keys(translations).forEach((key) => {
const translation = translations[key];
updateObj[`translations.${key}`] = translation;
});
return this.update({ _id: messageId }, { $set: updateObj });
}

addAttachmentTranslations = function (messageId, attachmentIndex, translations) {
const updateObj = {};
Object.keys(translations).forEach((key) => {
const translation = translations[key];
updateObj[`attachments.${attachmentIndex}.translations.${key}`] = translation;
});
return this.update({ _id: messageId }, { $set: updateObj });
};

setImportFileRocketChatAttachment(importFileId, rocketChatUrl, attachment) {
const query = {
'_importFile.id': importFileId,
Expand Down Expand Up @@ -277,17 +239,6 @@ export class Messages extends Base {
return this.find(query, options);
}

findByRoomIdAndMessageIds(rid, messageIds, options) {
const query = {
rid,
_id: {
$in: messageIds,
},
};

return this.find(query, options);
}

findOneBySlackBotIdAndSlackTs(slackBotId, slackTs) {
const query = {
slackBotId,
Expand Down
13 changes: 0 additions & 13 deletions apps/meteor/app/models/server/models/Rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,19 +176,6 @@ class Rooms extends Base {
return this.update({ _id }, update);
}

setReadOnlyById(_id, readOnly) {
const query = {
_id,
};
const update = {
$set: {
ro: readOnly,
},
};

return this.update(query, update);
}

setDmReadOnlyByUserId(_id, ids, readOnly, reactWhenReadOnly) {
const query = {
uids: {
Expand Down
18 changes: 9 additions & 9 deletions apps/meteor/app/reactions/server/setReaction.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Meteor } from 'meteor/meteor';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import _ from 'underscore';
import { EmojiCustom } from '@rocket.chat/models';
import { Messages, EmojiCustom } from '@rocket.chat/models';
import { api } from '@rocket.chat/core-services';
import type { IMessage, IRoom, IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ui-contexts';

import { Messages, Rooms } from '../../models/server';
import { Rooms } from '../../models/server';
import { callbacks } from '../../../lib/callbacks';
import { emoji } from '../../emoji/server';
import { isTheLastMessage, msgStream } from '../../lib/server';
Expand Down Expand Up @@ -71,9 +71,9 @@ async function setReaction(room: IRoom, user: IUser, message: IMessage, reaction
if (isTheLastMessage(room, message)) {
Rooms.unsetReactionsInLastMessage(room._id);
}
Messages.unsetReactions(message._id);
await Messages.unsetReactions(message._id);
} else {
Messages.setReactions(message._id, message.reactions);
await Messages.setReactions(message._id, message.reactions);
if (isTheLastMessage(room, message)) {
Rooms.setReactionsInLastMessage(room._id, message);
}
Expand All @@ -92,7 +92,7 @@ async function setReaction(room: IRoom, user: IUser, message: IMessage, reaction
};
}
message.reactions[reaction].usernames.push(user.username as string);
Messages.setReactions(message._id, message.reactions);
await Messages.setReactions(message._id, message.reactions);
if (isTheLastMessage(room, message)) {
Rooms.setReactionsInLastMessage(room._id, message);
}
Expand All @@ -107,14 +107,14 @@ async function setReaction(room: IRoom, user: IUser, message: IMessage, reaction
msgStream.emit(message.rid, message);
}

export const executeSetReaction = async (reaction: string, messageId: IMessage['_id'], shouldReact?: boolean) => {
export async function executeSetReaction(reaction: string, messageId: IMessage['_id'], shouldReact?: boolean) {
const user = Meteor.user() as IUser | null;

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

const message = Messages.findOneById(messageId);
const message = await Messages.findOneById(messageId);
if (!message) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setReaction' });
}
Expand All @@ -129,7 +129,7 @@ export const executeSetReaction = async (reaction: string, messageId: IMessage['
}

return setReaction(room, user, message, reaction, shouldReact);
};
}

declare module '@rocket.chat/ui-contexts' {
// eslint-disable-next-line @typescript-eslint/naming-convention
Expand All @@ -146,7 +146,7 @@ Meteor.methods<ServerMethods>({
}

try {
void executeSetReaction(reaction, messageId, shouldReact);
await executeSetReaction(reaction, messageId, shouldReact);
} catch (e: any) {
if (e.error === 'error-not-allowed' && e.reason && e.details && e.details.rid) {
void api.broadcast('notify.ephemeralMessage', uid, e.details.rid, {
Expand Down
Loading

0 comments on commit a791efa

Please sign in to comment.