Skip to content
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
33 changes: 33 additions & 0 deletions apps/meteor/app/api/server/v1/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
isChatSyncThreadMessagesProps,
isChatGetStarredMessagesProps,
isChatGetDiscussionsProps,
isChatGetMessageReadCountProps,
validateBadRequestErrorResponse,
validateUnauthorizedErrorResponse,
} from '@rocket.chat/rest-typings';
Expand All @@ -48,6 +49,7 @@ import { processWebhookMessage } from '../../../lib/server/functions/processWebh
import { getSingleMessage } from '../../../lib/server/methods/getSingleMessage';
import { executeSendMessage } from '../../../lib/server/methods/sendMessage';
import { executeUpdateMessage } from '../../../lib/server/methods/updateMessage';
import { getMessageReadCount as getMessageReadCountHelper } from '../../../read-counter/server/getMessageReadCount';
import { applyAirGappedRestrictionsValidation } from '../../../license/server/airGappedRestrictionsWrapper';
import { pinMessage, unpinMessage } from '../../../message-pin/server/pinMessage';
import { starMessage } from '../../../message-star/server/starMessage';
Expand Down Expand Up @@ -174,6 +176,37 @@ API.v1.addRoute(
},
);

API.v1.addRoute(
'chat.getMessageReadCount',
{
authRequired: true,
validateParams: isChatGetMessageReadCountProps,
},
{
async get() {
const { messageId } = this.queryParams;

const message = await Messages.findOneById(messageId, { projection: { rid: 1 } });

if (!message) {
return API.v1.failure('The required "messageId" param is missing or invalid.');
}

if (!(await canAccessRoomIdAsync(message.rid, this.userId))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed');
}

const result = await getMessageReadCountHelper(messageId, this.userId);

if (!result) {
return API.v1.failure();
}

return API.v1.success(result);
},
},
);

type ChatPinMessage = {
messageId: IMessage['_id'];
};
Expand Down
16 changes: 16 additions & 0 deletions apps/meteor/app/lib/server/functions/loadMessageHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { FindOptions } from 'mongodb';
import { settings } from '../../../settings/server/cached';
import { normalizeMessagesForUser } from '../../../utils/server/lib/normalizeMessagesForUser';
import { getHiddenSystemMessages } from '../lib/getHiddenSystemMessages';
import { getMessageReadCount } from '../../../read-counter/server/getMessageReadCount';
import { SystemLogger } from '../../../../server/lib/logger/system';

export async function loadMessageHistory({
userId,
Expand Down Expand Up @@ -52,6 +54,20 @@ export async function loadMessageHistory({
).toArray()
: await Messages.findVisibleByRoomIdNotContainingTypes(rid, hiddenMessageTypes, options, showThreadMessages).toArray();
const messages = await normalizeMessagesForUser(records, userId);

if (messages[0]?._id && userId) {
const readCountResult = await getMessageReadCount(messages[0]._id, userId);

if (readCountResult) {
SystemLogger.info({
msg: '[read-count demo] newest message readCount',
rid,
mid: messages[0]._id,
readCount: readCountResult.readCount,
uid: userId,
});
}
}
let unreadNotLoaded = 0;
let firstUnread;

Expand Down
45 changes: 45 additions & 0 deletions apps/meteor/app/read-counter/server/getMessageReadCount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { IMessage, IRoom, IUser } from '@rocket.chat/core-typings';
import { Authorization } from '@rocket.chat/core-services';
import { Messages, Rooms, Subscriptions } from '@rocket.chat/models';

export const getMessageReadCount = async (
messageId: IMessage['_id'],
userId: IUser['_id'],
): Promise<{ readCount: number } | null> => {
const message = await Messages.findOneById(messageId, {
projection: { _id: 1, rid: 1, ts: 1, 'u._id': 1 },
});

if (!message) {
return null;
}

const room = await Rooms.findOneById(message.rid as IRoom['_id'], {
projection: { _id: 1, t: 1 },
});

if (!room) {
return null;
}

// Exclude DMs from read counter
if (room.t === 'd') {
return null;
}

// Ensure the requesting user can access the room
if (!(await Authorization.canReadRoom(room, { _id: userId }))) {
return null;
}

if (!message.ts) {
return { readCount: 0 };
}

const excludeUserId = message.u?._id;

const readCount = await Subscriptions.countReadersByRoomIdAndMessageTs(message.rid, message.ts, excludeUserId);

return { readCount };
};

27 changes: 27 additions & 0 deletions apps/meteor/server/methods/getMessageReadCount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { IMessage } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';

import { getMessageReadCount as getMessageReadCountHelper } from '../../app/read-counter/server/getMessageReadCount';

declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
getMessageReadCount(options: { messageId: IMessage['_id'] }): { readCount: number } | null;
}
}

Meteor.methods<ServerMethods>({
async getMessageReadCount({ messageId }) {
check(messageId, String);

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

return getMessageReadCountHelper(messageId, uid);
},
});

1 change: 1 addition & 0 deletions apps/meteor/server/methods/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import './createDirectMessage';
import './deleteFileMessage';
import './deleteUser';
import './getAvatarSuggestion';
import './getMessageReadCount';
import './getRoomById';
import './getRoomIdByNameOrId';
import './getRoomNameById';
Expand Down
2 changes: 2 additions & 0 deletions packages/model-typings/src/models/ISubscriptionsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import type { DocumentWithProjection } from '../types/DocumentWithProjection';
export interface ISubscriptionsModel extends IBaseModel<ISubscription> {
getBadgeCount(uid: string): Promise<number>;

countReadersByRoomIdAndMessageTs(rid: string, messageTs: Date, excludeUserId?: string): Promise<number>;

findOneByRoomIdAndUserId(rid: string, uid: string, options?: FindOptions<ISubscription>): Promise<ISubscription | null>;

findByUserIdAndRoomIds(userId: string, roomIds: Array<string>, options?: FindOptions<ISubscription>): FindCursor<ISubscription>;
Expand Down
14 changes: 14 additions & 0 deletions packages/models/src/models/Subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@
return result?.total || 0;
}

countReadersByRoomIdAndMessageTs(rid: string, messageTs: Date, excludeUserId?: string): Promise<number> {
const query: Filter<ISubscription> = {
rid,
archived: { $ne: true },

Check failure on line 92 in packages/models/src/models/Subscriptions.ts

View workflow job for this annotation

GitHub Actions / 🔎 Code Check / Code Lint

Replace `archived` with `'archived'`
ls: { $gte: messageTs },

Check failure on line 93 in packages/models/src/models/Subscriptions.ts

View workflow job for this annotation

GitHub Actions / 🔎 Code Check / Code Lint

Replace `ls` with `'ls'`
'u._id': {
...(excludeUserId ? { $ne: excludeUserId } : {}),
$exists: true,
},
};

return this.countDocuments(query);
}

findOneByRoomIdAndUserId(rid: string, uid: string, options: FindOptions<ISubscription> = {}): Promise<ISubscription | null> {
const query = {
rid,
Expand Down
20 changes: 20 additions & 0 deletions packages/rest-typings/src/v1/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,23 @@ const ChatGetMessageReadReceiptsSchema = {

export const isChatGetMessageReadReceiptsProps = ajv.compile<ChatGetMessageReadReceipts>(ChatGetMessageReadReceiptsSchema);

type ChatGetMessageReadCount = {
messageId: IMessage['_id'];
};

const ChatGetMessageReadCountSchema = {
type: 'object',
properties: {
messageId: {
type: 'string',
},
},
required: ['messageId'],
additionalProperties: false,
};

export const isChatGetMessageReadCountProps = ajv.compile<ChatGetMessageReadCount>(ChatGetMessageReadCountSchema);

type GetStarredMessages = {
roomId: IRoom['_id'];
count?: number;
Expand Down Expand Up @@ -1054,6 +1071,9 @@ export type ChatEndpoints = {
'/v1/chat.getMessageReadReceipts': {
GET: (params: ChatGetMessageReadReceipts) => { receipts: IReadReceiptWithUser[] };
};
'/v1/chat.getMessageReadCount': {
GET: (params: ChatGetMessageReadCount) => { readCount: number };
};
'/v1/chat.getStarredMessages': {
GET: (params: GetStarredMessages) => {
messages: IMessage[];
Expand Down
Loading