Skip to content

Node.js based forum software built for the modern web

feat: #14202, naive fulltext search on chats list

Julian Lam3f311050389e
diff --git a/public/src/client/chats.js b/public/src/client/chats.js
index 4614eea474..cf844cb709 100644
--- a/public/src/client/chats.js
+++ b/public/src/client/chats.js
@@ -12,6 +12,7 @@ define('forum/chats', [
'forum/chats/message-search',
'forum/chats/pinned-messages',
'forum/chats/events',
+ 'forum/chats/search',
'autocomplete',
'hooks',
'bootbox',
@@ -22,8 +23,8 @@ define('forum/chats', [
], function (
components, mousetrap, recentChats, create,
manage, messages, userList, messageSearch, pinnedMessages,
- events, autocomplete, hooks, bootbox, alerts, chatModule,
- api, uploadHelpers
+ events, search, autocomplete, hooks, bootbox, alerts,
+ chatModule, api, uploadHelpers
) {
const Chats = {
activeAutocomplete: {},
@@ -85,6 +86,7 @@ define('forum/chats', [
messages.scrollToBottomAfterImageLoad(chatContentEl);
}
create.init();
+ search.init(document.getElementById('search-chats'), document.getElementById('private-rooms'));
hooks.fire('action:chat.loaded', $('.chats-full'));
};
diff --git a/public/src/client/chats/search.js b/public/src/client/chats/search.js
new file mode 100644
index 0000000000..9dc1655896
--- /dev/null
+++ b/public/src/client/chats/search.js
@@ -0,0 +1,25 @@
+'use strict';
+
+import { get } from 'api';
+
+export function init(searchEl, listEl) {
+ if (!searchEl || !listEl) {
+ console.warn('[chats/search] Search element not found');
+ }
+
+ // Debounce function to limit how often the keyup handler fires
+ const debounce = (func, delay) => {
+ let timeoutId;
+ return function (...args) {
+ clearTimeout(timeoutId);
+ timeoutId = setTimeout(() => func.apply(this, args), delay);
+ };
+ };
+
+ searchEl.addEventListener('keyup', debounce(async function (e) {
+ const data = await get(`/chats/search?query=${e.target.value}`);
+ console.log(data);
+ const html = await app.parseAndTranslate('chats', 'rooms', data);
+ $(listEl).html(html);
+ }, 300));
+}
\ No newline at end of file
diff --git a/src/controllers/write/chats.js b/src/controllers/write/chats.js
index 81f4fb27e8..2f00cb586c 100644
--- a/src/controllers/write/chats.js
+++ b/src/controllers/write/chats.js
@@ -1,6 +1,8 @@
'use strict';
+
const api = require('../../api');
+const messaging = require('../../messaging');
const helpers = require('../helpers');
const Chats = module.exports;
@@ -24,6 +26,17 @@ Chats.list = async (req, res) => {
helpers.formatApiResponse(200, res, { rooms, nextStart });
};
+Chats.search = async (req, res) => {
+ const { query } = req.query;
+
+ if (!query) {
+ return Chats.list(req, res);
+ }
+
+ const rooms = await messaging.searchRecentChats(req.uid, req.uid, query);
+ helpers.formatApiResponse(200, res, rooms);
+};
+
Chats.create = async (req, res) => {
const roomObj = await api.chats.create(req, req.body);
helpers.formatApiResponse(200, res, roomObj);
diff --git a/src/messaging/index.js b/src/messaging/index.js
index 7c810ec6d8..b6044821a9 100644
--- a/src/messaging/index.js
+++ b/src/messaging/index.js
@@ -171,6 +171,22 @@ Messaging.getPublicRooms = async (callerUid, uid) => {
return roomData;
};
+async function getUsers(roomIds, exceptUid) {
+ const arrayOfUids = await Promise.all(
+ roomIds.map(roomId => Messaging.getUidsInRoom(roomId, 0, 9))
+ );
+ const uniqUids = _.uniq(_.flatten(arrayOfUids)).filter(
+ _uid => _uid && parseInt(_uid, 10) !== parseInt(exceptUid, 10)
+ );
+ const uidToUser = _.zipObject(
+ uniqUids,
+ await user.getUsersFields(uniqUids, [
+ 'uid', 'username', 'userslug', 'picture', 'status', 'lastonline',
+ ])
+ );
+ return arrayOfUids.map(uids => uids.map(uid => uidToUser[uid]));
+}
+
Messaging.getRecentChats = async (callerUid, uid, start, stop) => {
const ok = await canGet('filter:messaging.canGetRecentChats', callerUid, uid);
if (!ok) {
@@ -179,30 +195,68 @@ Messaging.getRecentChats = async (callerUid, uid, start, stop) => {
const roomIds = await db.getSortedSetRevRange(`uid:${uid}:chat:rooms`, start, stop);
- async function getUsers(roomIds) {
- const arrayOfUids = await Promise.all(
- roomIds.map(roomId => Messaging.getUidsInRoom(roomId, 0, 9))
- );
- const uniqUids = _.uniq(_.flatten(arrayOfUids)).filter(
- _uid => _uid && parseInt(_uid, 10) !== parseInt(uid, 10)
- );
- const uidToUser = _.zipObject(
- uniqUids,
- await user.getUsersFields(uniqUids, [
- 'uid', 'username', 'userslug', 'picture', 'status', 'lastonline',
- ])
- );
- return arrayOfUids.map(uids => uids.map(uid => uidToUser[uid]));
+ const results = await utils.promiseParallel({
+ roomData: Messaging.getRoomsData(roomIds),
+ unread: db.isSortedSetMembers(`uid:${uid}:chat:rooms:unread`, roomIds),
+ users: getUsers(roomIds, uid),
+ teasers: Messaging.getTeasers(uid, roomIds),
+ settings: user.getSettings(uid),
+ });
+
+ results.roomData = await modifyChatRooms(uid, results);
+
+ const ref = { rooms: results.roomData, nextStart: stop + 1 };
+ return await plugins.hooks.fire('filter:messaging.getRecentChats', {
+ rooms: ref.rooms,
+ nextStart: ref.nextStart,
+ uid: uid,
+ callerUid: callerUid,
+ });
+};
+
+Messaging.searchRecentChats = async (callerUid, uid, query) => {
+ const ok = await canGet('filter:messaging.canGetRecentChats', callerUid, uid);
+ if (!ok) {
+ throw new Error('[[error:no-privileges]]');
}
+ const roomIds = await db.getSortedSetRevRange(`uid:${uid}:chat:rooms`, 0, -1);
const results = await utils.promiseParallel({
roomData: Messaging.getRoomsData(roomIds),
unread: db.isSortedSetMembers(`uid:${uid}:chat:rooms:unread`, roomIds),
- users: getUsers(roomIds),
+ users: getUsers(roomIds, uid),
teasers: Messaging.getTeasers(uid, roomIds),
settings: user.getSettings(uid),
});
+ // Filter rooms based on query
+ results.roomData = results.roomData
+ .filter((room, idx) => {
+ if (!room) return false;
+
+ // Search in room title
+ const titleMatch = room.roomName && room.roomName.toLowerCase().includes(query.toLowerCase());
+
+ // Search in usernames
+ const users = results.users[idx] || [];
+ const usernameMatch = users.some(user => user && (
+ (user.displayname && user.displayname.toLowerCase().includes(query.toLowerCase())) ||
+ (user.username && user.username.toLowerCase().includes(query.toLowerCase()))
+ ));
+
+ return titleMatch || usernameMatch;
+ });
+
+ results.roomData = await modifyChatRooms(uid, results);
+
+ return await plugins.hooks.fire('filter:messaging.searchRecentChats', {
+ rooms: results.roomData,
+ uid: uid,
+ callerUid: callerUid,
+ });
+};
+
+async function modifyChatRooms(uid, results) {
await Promise.all(results.roomData.map(async (room, index) => {
if (room) {
room.users = results.users[index];
@@ -222,15 +276,8 @@ Messaging.getRecentChats = async (callerUid, uid, start, stop) => {
}
}));
- results.roomData = results.roomData.filter(Boolean);
- const ref = { rooms: results.roomData, nextStart: stop + 1 };
- return await plugins.hooks.fire('filter:messaging.getRecentChats', {
- rooms: ref.rooms,
- nextStart: ref.nextStart,
- uid: uid,
- callerUid: callerUid,
- });
-};
+ return results.roomData.filter(Boolean);
+}
Messaging.generateUsernames = function (room, excludeUid) {
const users = room.users.filter(u => u && parseInt(u.uid, 10) !== excludeUid);
diff --git a/src/routes/write/chats.js b/src/routes/write/chats.js
index 7fd2c8e392..ea52de5bd3 100644
--- a/src/routes/write/chats.js
+++ b/src/routes/write/chats.js
@@ -13,6 +13,8 @@ module.exports = function () {
setupApiRoute(router, 'get', '/', [...middlewares], controllers.write.chats.list);
setupApiRoute(router, 'post', '/', [...middlewares, middleware.checkRequired.bind(null, ['uids'])], controllers.write.chats.create);
+ setupApiRoute(router, 'get', '/search', [...middlewares], controllers.write.chats.search);
+
setupApiRoute(router, 'get', '/unread', [...middlewares], controllers.write.chats.getUnread);
setupApiRoute(router, 'put', '/sort', [...middlewares, middleware.checkRequired.bind(null, ['roomIds', 'scores'])], controllers.write.chats.sortPublicRooms);
diff --git a/src/views/chats.tpl b/src/views/chats.tpl
index 2be62f31e0..5ad174f8dd 100644
--- a/src/views/chats.tpl
+++ b/src/views/chats.tpl
@@ -3,8 +3,9 @@
<div class="chats-full d-flex gap-1 h-100 mt-3 mt-md-0 py-md-3">
<div component="chat/nav-wrapper" class="flex-shrink-0 d-flex flex-column h-100 gap-1" data-loaded="{{{ if roomId }}}1{{{ else }}}0{{{ end }}}">
- <div>
+ <div class="d-flex flex-column">
<button component="chat/create" class="btn btn-primary btn-sm w-100">[[modules:chat.create-room]]</button>
+ <input id="search-chats" class="form-control mt-2" type="text" placeholder="Search chats..." />
</div>
{{{ if publicRooms.length }}}