diff --git a/app/api/rocket-chat/messages/route.ts b/app/api/rocket-chat/messages/route.ts index 1e7b244a..5fd62342 100644 --- a/app/api/rocket-chat/messages/route.ts +++ b/app/api/rocket-chat/messages/route.ts @@ -163,12 +163,10 @@ export async function GET(request: Request) { const messages: any[] = []; const processedRooms = new Set(); + const latestMessagePerRoom: { [key: string]: any } = {}; // Step 5: Fetch messages using user token for (const subscription of userSubscriptions) { - if (messages.length >= 10 || processedRooms.has(subscription.rid)) continue; - processedRooms.add(subscription.rid); - try { // Determine the correct endpoint and parameters based on room type let endpoint; @@ -188,7 +186,7 @@ export async function GET(request: Request) { const queryParams = new URLSearchParams({ roomId: subscription.rid, - count: '5' + count: '5' // Keep this to ensure we get the latest message }); const messagesResponse = await fetch( @@ -215,36 +213,39 @@ export async function GET(request: Request) { const validMessages = messageData.messages.filter((message: any) => { // For channels, apply strict filtering if (subscription.t === 'c') { - // Skip if: - // 1. No message text - // 2. System message (has type 't') - // 3. No user info - // 4. Join/leave messages - // 5. User added/removed messages if (!message.msg || // No message text message.t || // System message !message.u || // No user info message.msg.includes('has joined the channel') || message.msg.includes('has left the channel') || message.msg.includes('added') || - message.msg.includes('removed')) { + message.msg.includes('removed') || + (message.msg.includes('started a call') && message.u._id === currentUser._id)) { return false; } } return true; }); - // Process filtered messages - for (const message of validMessages) { - const messageUser = message.u || {}; + // Only process the latest valid message from this room + if (validMessages.length > 0) { + // Get the latest message (they should already be sorted by timestamp) + const latestMessage = validMessages[0]; + const messageUser = latestMessage.u || {}; const username = messageUser.username || 'unknown'; // Get proper display names let roomDisplayName = subscription.fname || subscription.name; let userDisplayName = messageUser.name || username; + // Handle call messages + let messageText = latestMessage.msg || ''; + if (messageText.includes('started a call')) { + messageText = '📞 Call received'; + } + // Format timestamp - const timestamp = new Date(message.ts); + const timestamp = new Date(latestMessage.ts); const now = new Date(); let formattedTime = ''; @@ -270,11 +271,11 @@ export async function GET(request: Request) { .join('') .toUpperCase(); - messages.push({ - id: message._id, - text: message.msg || '', + const processedMessage = { + id: latestMessage._id, + text: messageText, timestamp: formattedTime, - rawTimestamp: message.ts, + rawTimestamp: latestMessage.ts, roomName: roomDisplayName, roomType: subscription.t, sender: { @@ -294,7 +295,13 @@ export async function GET(request: Request) { isDirect: subscription.t === 'd', link: `${baseUrl}/${subscription.t === 'd' ? 'direct' : subscription.t === 'p' ? 'group' : 'channel'}/${subscription.name}` } - }); + }; + + // Store this message if it's the latest for this room + if (!latestMessagePerRoom[subscription.rid] || + new Date(latestMessage.ts).getTime() > new Date(latestMessagePerRoom[subscription.rid].rawTimestamp).getTime()) { + latestMessagePerRoom[subscription.rid] = processedMessage; + } } } } catch (error) { @@ -303,15 +310,19 @@ export async function GET(request: Request) { } } - // Sort messages by timestamp (newest first) and limit - const sortedMessages = messages - .sort((a, b) => new Date(b.rawTimestamp).getTime() - new Date(a.rawTimestamp).getTime()) + // Convert the latest messages object to an array and sort by timestamp + const sortedMessages = Object.values(latestMessagePerRoom) + .sort((a, b) => { + const dateA = new Date(a.rawTimestamp); + const dateB = new Date(b.rawTimestamp); + return dateB.getTime() - dateA.getTime(); + }) .slice(0, 10); return NextResponse.json({ messages: sortedMessages, - total: messages.length, - hasMore: messages.length > 10 + total: Object.keys(latestMessagePerRoom).length, + hasMore: Object.keys(latestMessagePerRoom).length > 10 }, { status: 200 }); } catch (error) { console.error('Error in messages endpoint:', error);