Skip to content

Node.js based forum software built for the modern web

feat: add action:messaging.markRead hook with previous read timestamp (#14777)

palmoni5fcaeec1b4555
diff --git a/src/messaging/unread.js b/src/messaging/unread.js
index 8ca893a638..c6ab5d1dc9 100644
--- a/src/messaging/unread.js
+++ b/src/messaging/unread.js
@@ -3,6 +3,7 @@
const db = require('../database');
const utils = require('../utils');
const io = require('../socket.io');
+const plugins = require('../plugins');
module.exports = function (Messaging) {
Messaging.getUnreadCount = async (uid) => {
@@ -28,10 +29,22 @@ module.exports = function (Messaging) {
return;
}
+ const prevTimestamp = parseInt(
+ await db.getObjectField(`uid:${uid}:chat:rooms:read`, roomId), 10
+ ) || 0;
+ const timestamp = Date.now();
+
await Promise.all([
db.sortedSetRemove(`uid:${uid}:chat:rooms:unread`, roomId),
- db.setObjectField(`uid:${uid}:chat:rooms:read`, roomId, Date.now()),
+ db.setObjectField(`uid:${uid}:chat:rooms:read`, roomId, timestamp),
]);
+
+ plugins.hooks.fire('action:messaging.markRead', {
+ uid: uid,
+ roomId: roomId,
+ timestamp: timestamp,
+ prevTimestamp: prevTimestamp,
+ });
};
Messaging.hasRead = async (uids, roomId) => {
diff --git a/test/messaging.js b/test/messaging.js
index adaff8a1c4..b391d0f4a3 100644
--- a/test/messaging.js
+++ b/test/messaging.js
@@ -1032,4 +1032,46 @@ describe('Messaging Library', () => {
assert.equal(response.statusCode, 404);
});
});
+
+ describe('.markRead()', () => {
+ const plugins = require('../src/plugins');
+ let markReadRoomId;
+
+ before(async () => {
+ markReadRoomId = await Messaging.newRoom(mocks.users.foo.uid, {
+ uids: [mocks.users.herp.uid],
+ });
+ });
+
+ async function markReadAndCaptureHook(uid, roomId) {
+ const fired = new Promise((resolve) => {
+ plugins.hooks.register('my-test-plugin', {
+ hook: 'action:messaging.markRead',
+ method: resolve,
+ });
+ });
+ await Messaging.markRead(uid, roomId);
+ const data = await fired;
+ plugins.hooks.unregister('my-test-plugin', 'action:messaging.markRead');
+ return data;
+ }
+
+ it('should fire action:messaging.markRead with no previous timestamp on first read', async () => {
+ const data = await markReadAndCaptureHook(mocks.users.herp.uid, markReadRoomId);
+
+ assert.strictEqual(parseInt(data.uid, 10), mocks.users.herp.uid);
+ assert.strictEqual(parseInt(data.roomId, 10), parseInt(markReadRoomId, 10));
+ assert(data.timestamp > 0);
+ assert.strictEqual(data.prevTimestamp, 0);
+ });
+
+ it('should hand the timestamp of the previous read to the hook', async () => {
+ const first = await markReadAndCaptureHook(mocks.users.herp.uid, markReadRoomId);
+ await sleep(5);
+ const second = await markReadAndCaptureHook(mocks.users.herp.uid, markReadRoomId);
+
+ assert.strictEqual(second.prevTimestamp, first.timestamp);
+ assert(second.timestamp > second.prevTimestamp);
+ });
+ });
});