diff --git a/src/controllers/index.ts b/src/controllers/index.ts index 5a30b1025..5b31fc138 100644 --- a/src/controllers/index.ts +++ b/src/controllers/index.ts @@ -118,6 +118,7 @@ export async function set(app) { app.get('/messages', messages.getMessages) app.delete('/message/:id', messages.deleteMessage) app.post('/messages/:chat_id/read', messages.readMessages) + app.post('/messages/:chat_id/toggleChatReadUnread', messages.toggleChatReadUnread) app.post('/messages/clear', messages.clearMessages) app.delete('/messages', messages.disappearingMessages) app.get('/message/:uuid', messages.getMessageByUuid) diff --git a/src/controllers/messages.ts b/src/controllers/messages.ts index 02818ede7..c7861d7e2 100644 --- a/src/controllers/messages.ts +++ b/src/controllers/messages.ts @@ -797,6 +797,66 @@ export const receiveDeleteMessage = async (payload: Payload): Promise => { ) } +/** +Either makes all messages of a chat read or it marks the last message of the given chat as unread. + +@param {Req} req - The request object containing the chat ID. +@param {Res} res - The response object used to send the updated chat information. +@returns {Promise} - An empty promise. +*/ +export const toggleChatReadUnread = async (req: Req, res: Res): Promise => { + if (!req.owner) return failure(res, 'no owner') + + //We want to mark the chat as read + if (req.shouldMarkAsUnread === false) { + // Call the readMessages function with the same req and res objects + const result = await readMessages(req, res); + return result; // Exit the function after calling readMessages + } + + //we want to mark the last message + chat as unread + const chat_id = req.params.chat_id + const owner = req.owner + const tenant: number = owner.id + + // Find the latest message that is not from the user and has been read + const latestMessage = await models.Message.findOne({ + where: { + sender: { + [Op.ne]: owner.id, + }, + chatId: chat_id, + [Op.or]: [{ seen: true }, { seen: null }], + tenant, + }, + order: [['date', 'DESC']], + }); + + // Update just the latest message found in the database to mark it as unseen + if (latestMessage) { + await latestMessage.update({ seen: false }); + } + //mark the chat as unseen + const chat: Chat = (await models.Chat.findOne({ + where: { id: chat_id, tenant }, + })) as Chat + if (chat) { + resetNotifyTribeCount(parseInt(chat_id)) + await chat.update({ seen: false }) + success(res, {}) + sendNotification(chat, '', 'badge', owner) + socket.sendJson( + { + type: 'chat_unseen', + response: jsonUtils.chatToJson(chat), + }, + tenant + ) + } else { + failure(res, 'no chat') + } +} + /** Updates the messages in the specified chat to mark them as seen by the owner and sends a notification to the other chat members.