Skip to content

Commit

Permalink
Merge branch 'develop' into feat/audit-room-members
Browse files Browse the repository at this point in the history
  • Loading branch information
kodiakhq[bot] authored Aug 12, 2024
2 parents 026c27b + 08ac2f3 commit f613c82
Show file tree
Hide file tree
Showing 8 changed files with 60 additions and 44 deletions.
8 changes: 6 additions & 2 deletions apps/meteor/app/federation/server/endpoints/dispatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,12 @@ const eventHandlers = {

await processThreads(denormalizedMessage, room);

// Notify users
await notifyUsersOnMessage(denormalizedMessage, room);
const roomUpdater = Rooms.getUpdater();
await notifyUsersOnMessage(denormalizedMessage, room, roomUpdater);
if (roomUpdater.hasChanges()) {
await roomUpdater.persist({ _id: room._id });
}

sendAllNotifications(denormalizedMessage, room);
messageForNotification = denormalizedMessage;
} catch (err) {
Expand Down
24 changes: 17 additions & 7 deletions apps/meteor/app/lib/server/lib/notifyUsersOnMessage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { IMessage, IRoom, IUser, RoomType } from '@rocket.chat/core-typings';
import { isEditedMessage } from '@rocket.chat/core-typings';
import type { Updater } from '@rocket.chat/models';
import { Subscriptions, Rooms } from '@rocket.chat/models';
import { escapeRegExp } from '@rocket.chat/string-helpers';
import moment from 'moment';
Expand Down Expand Up @@ -141,12 +142,12 @@ export async function updateThreadUsersSubscriptions(message: IMessage, replies:
await Subscriptions.setLastReplyForRoomIdAndUserIds(message.rid, repliesPlusSender, new Date());
}

export async function notifyUsersOnMessage(message: IMessage, room: IRoom): Promise<IMessage> {
export async function notifyUsersOnMessage(message: IMessage, room: IRoom, roomUpdater: Updater<IRoom>): Promise<IMessage> {
// Skips this callback if the message was edited and increments it if the edit was way in the past (aka imported)
if (isEditedMessage(message)) {
if (Math.abs(moment(message.editedAt).diff(Date.now())) > 60000) {
// TODO: Review as I am not sure how else to get around this as the incrementing of the msgs count shouldn't be in this callback
await Rooms.incMsgCountById(message.rid, 1);
Rooms.getIncMsgCountUpdateQuery(1, roomUpdater);
return message;
}

Expand All @@ -156,33 +157,42 @@ export async function notifyUsersOnMessage(message: IMessage, room: IRoom): Prom
(!message.tmid || message.tshow) &&
(!room.lastMessage || room.lastMessage._id === message._id)
) {
await Rooms.setLastMessageById(message.rid, message);
Rooms.getLastMessageUpdateQuery(message, roomUpdater);
}

return message;
}

if (message.ts && Math.abs(moment(message.ts).diff(Date.now())) > 60000) {
await Rooms.incMsgCountById(message.rid, 1);
Rooms.getIncMsgCountUpdateQuery(1, roomUpdater);
return message;
}

// If message sent ONLY on a thread, skips the rest as it is done on a callback specific to threads
if (message.tmid && !message.tshow) {
await Rooms.incMsgCountById(message.rid, 1);
Rooms.getIncMsgCountUpdateQuery(1, roomUpdater);
return message;
}

// Update all the room activity tracker fields
await Rooms.incMsgCountAndSetLastMessageById(message.rid, 1, message.ts, settings.get('Store_Last_Message') ? message : undefined);
Rooms.setIncMsgCountAndSetLastMessageUpdateQuery(1, message, !!settings.get('Store_Last_Message'), roomUpdater);
await updateUsersSubscriptions(message, room);

return message;
}

callbacks.add(
'afterSaveMessage',
(message, room) => notifyUsersOnMessage(message, room),
async (message, room) => {
const roomUpdater = Rooms.getUpdater();
await notifyUsersOnMessage(message, room, roomUpdater);

if (roomUpdater.hasChanges()) {
await roomUpdater.persist({ _id: room._id });
}

return message;
},
callbacks.priority.MEDIUM,
'notifyUsersOnMessage',
);
7 changes: 6 additions & 1 deletion apps/meteor/server/models/dummy/BaseDummy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { RocketChatRecordDeleted } from '@rocket.chat/core-typings';
import type { DefaultFields, FindPaginated, IBaseModel, InsertionModel, ResultFields } from '@rocket.chat/model-typings';
import { getCollectionName } from '@rocket.chat/models';
import { getCollectionName, UpdaterImpl } from '@rocket.chat/models';
import type { Updater } from '@rocket.chat/models';
import type {
BulkWriteOptions,
ChangeStream,
Expand Down Expand Up @@ -40,6 +41,10 @@ export class BaseDummy<
// nothing to do
}

public getUpdater(): Updater<T> {
return new UpdaterImpl<T>(this.col as unknown as IBaseModel<T>);
}

getCollectionName(): string {
return this.collectionName;
}
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/server/models/raw/BaseRaw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export abstract class BaseRaw<
return this.collectionName;
}

protected getUpdater(): Updater<T> {
public getUpdater(): Updater<T> {
return new UpdaterImpl<T>(this.col as unknown as IBaseModel<T>);
}

Expand Down
4 changes: 0 additions & 4 deletions apps/meteor/server/models/raw/LivechatRooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,6 @@ export class LivechatRoomsRaw extends BaseRaw<IOmnichannelRoom> implements ILive
];
}

getUpdater(): Updater<IOmnichannelRoom> {
return super.getUpdater();
}

getQueueMetrics({
departmentId,
agentId,
Expand Down
45 changes: 18 additions & 27 deletions apps/meteor/server/models/raw/Rooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
} from '@rocket.chat/core-typings';
import type { FindPaginated, IRoomsModel, IChannelsWithNumberOfMessagesBetweenDate } from '@rocket.chat/model-typings';
import { Subscriptions } from '@rocket.chat/models';
import type { Updater } from '@rocket.chat/models';
import { escapeRegExp } from '@rocket.chat/string-helpers';
import type {
AggregationCursor,
Expand Down Expand Up @@ -888,6 +889,10 @@ export class RoomsRaw extends BaseRaw<IRoom> implements IRoomsModel {
return this.updateOne(query, update);
}

getIncMsgCountUpdateQuery(inc: number, roomUpdater: Updater<IRoom>): Updater<IRoom> {
return roomUpdater.inc('msgs', inc);
}

decreaseMessageCountById(_id: IRoom['_id'], count = 1) {
return this.incMsgCountById(_id, -count);
}
Expand Down Expand Up @@ -1527,25 +1532,19 @@ export class RoomsRaw extends BaseRaw<IRoom> implements IRoomsModel {
return this.updateOne(query, update);
}

incMsgCountAndSetLastMessageById(
_id: IRoom['_id'],
inc = 1,
lastMessageTimestamp: NonNullable<IRoom['lm']>,
lastMessage?: IMessage,
): Promise<UpdateResult> {
const query: Filter<IRoom> = { _id };
setIncMsgCountAndSetLastMessageUpdateQuery(
inc: number,
lastMessage: IMessage,
shouldStoreLastMessage: boolean,
roomUpdater: Updater<IRoom>,
): Updater<IRoom> {
roomUpdater.inc('msgs', inc).set('lm', lastMessage.ts);

const update: UpdateFilter<IRoom> = {
$set: {
lm: lastMessageTimestamp,
...(lastMessage ? { lastMessage } : {}),
},
$inc: {
msgs: inc,
},
};
if (shouldStoreLastMessage) {
roomUpdater.set('lastMessage', lastMessage);
}

return this.updateOne(query, update);
return roomUpdater;
}

incUsersCountById(_id: IRoom['_id'], inc = 1): Promise<UpdateResult> {
Expand Down Expand Up @@ -1578,16 +1577,8 @@ export class RoomsRaw extends BaseRaw<IRoom> implements IRoomsModel {
return this.updateMany(query, update);
}

setLastMessageById(_id: IRoom['_id'], lastMessage: IRoom['lastMessage']): Promise<UpdateResult> {
const query: Filter<IRoom> = { _id };

const update: UpdateFilter<IRoom> = {
$set: {
lastMessage,
},
};

return this.updateOne(query, update);
getLastMessageUpdateQuery(lastMessage: IRoom['lastMessage'], roomUpdater: Updater<IRoom>): Updater<IRoom> {
return roomUpdater.set('lastMessage', lastMessage);
}

async resetLastMessageById(_id: IRoom['_id'], lastMessage: IRoom['lastMessage'] | null, msgCountDelta?: number): Promise<UpdateResult> {
Expand Down
3 changes: 3 additions & 0 deletions packages/model-typings/src/models/IBaseModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import type {
WithId,
} from 'mongodb';

import type { Updater } from '../updater';

export type DefaultFields<Base> = Record<keyof Base, 1> | Record<keyof Base, 0> | void;
export type ResultFields<Base, Defaults> = Defaults extends void
? Base
Expand All @@ -48,6 +50,7 @@ export interface IBaseModel<
createIndexes(): Promise<string[] | void>;

getCollectionName(): string;
getUpdater(): Updater<T>;

findOneAndUpdate(query: Filter<T>, update: UpdateFilter<T> | T, options?: FindOneAndUpdateOptions): Promise<ModifyResult<T>>;

Expand Down
11 changes: 9 additions & 2 deletions packages/model-typings/src/models/IRoomsModel.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { IDirectMessageRoom, IMessage, IOmnichannelGenericRoom, IRoom, IRoomFederated, ITeam, IUser } from '@rocket.chat/core-typings';
import type { AggregationCursor, DeleteResult, Document, FindCursor, FindOptions, UpdateOptions, UpdateResult } from 'mongodb';

import type { Updater } from '../updater';
import type { FindPaginated, IBaseModel } from './IBaseModel';

export interface IChannelsWithNumberOfMessagesBetweenDate {
Expand Down Expand Up @@ -162,6 +163,7 @@ export interface IRoomsModel extends IBaseModel<IRoom> {

countFederatedRooms(): Promise<number>;
incMsgCountById(rid: string, inc: number): Promise<UpdateResult>;
getIncMsgCountUpdateQuery(inc: number, roomUpdater: Updater<IRoom>): Updater<IRoom>;
decreaseMessageCountById(rid: string, dec: number): Promise<UpdateResult>;
findOneByIdOrName(_idOrName: string, options?: FindOptions<IRoom>): Promise<IRoom | null>;
setCallStatus(_id: string, callStatus: IRoom['callStatus']): Promise<UpdateResult>;
Expand Down Expand Up @@ -234,10 +236,15 @@ export interface IRoomsModel extends IBaseModel<IRoom> {
archiveById(rid: string): Promise<UpdateResult>;
unarchiveById(rid: string): Promise<UpdateResult>;
setNameById(rid: string, name: string, fname: string): Promise<UpdateResult>;
incMsgCountAndSetLastMessageById(rid: IRoom['_id'], inc: number, lastMessageTs: Date, lastMessage?: IMessage): Promise<UpdateResult>;
setIncMsgCountAndSetLastMessageUpdateQuery(
inc: number,
lastMessage: IMessage,
shouldStoreLastMessage: boolean,
roomUpdater: Updater<IRoom>,
): Updater<IRoom>;
incUsersCountById(rid: string, inc: number): Promise<UpdateResult>;
incUsersCountNotDMsByIds(rids: string[], inc: number): Promise<Document | UpdateResult>;
setLastMessageById(rid: string, lastMessage: IRoom['lastMessage']): Promise<UpdateResult>;
getLastMessageUpdateQuery(lastMessage: IRoom['lastMessage'], roomUpdater: Updater<IRoom>): Updater<IRoom>;
resetLastMessageById(rid: string, lastMessage: IMessage | null, msgCountDelta?: number): Promise<UpdateResult>;
replaceUsername(username: string, newUsername: string): Promise<UpdateResult | Document>;
replaceMutedUsername(username: string, newUsername: string): Promise<UpdateResult | Document>;
Expand Down

0 comments on commit f613c82

Please sign in to comment.