diff --git a/app/api/rocket-chat/messages/route.ts b/app/api/rocket-chat/messages/route.ts index 95fb4c87..bb795199 100644 --- a/app/api/rocket-chat/messages/route.ts +++ b/app/api/rocket-chat/messages/route.ts @@ -90,9 +90,9 @@ export async function GET() { username: userInfo.user.username }); - // Get the user's subscriptions (rooms they are in) + // Get the user's subscriptions (rooms they are in) using their user ID const subscriptionsResponse = await fetch( - 'https://parole.slm-lab.net/api/v1/subscriptions.get', + `https://parole.slm-lab.net/api/v1/users.list.rooms?userId=${userInfo.user._id}`, { headers: { 'X-Auth-Token': ROCKET_CHAT_TOKEN, @@ -115,17 +115,18 @@ export async function GET() { } const subscriptions = await subscriptionsResponse.json(); - if (!subscriptions.update || subscriptions.update.length === 0) { + console.log('Subscriptions response:', subscriptions); + + if (!subscriptions.rooms || subscriptions.rooms.length === 0) { return NextResponse.json({ messages: [] }); } // Get the last message from each room const messages = await Promise.all( - subscriptions.update.map(async (room: any) => { - if (!room.lastMessage?._id) return null; - - const messageResponse = await fetch( - `https://parole.slm-lab.net/api/v1/chat.getMessage?msgId=${room.lastMessage._id}`, + subscriptions.rooms.map(async (room: any) => { + // Get the most recent messages from the room + const messagesResponse = await fetch( + `https://parole.slm-lab.net/api/v1/channels.messages?roomId=${room._id}&count=1`, { headers: { 'X-Auth-Token': ROCKET_CHAT_TOKEN, @@ -135,20 +136,23 @@ export async function GET() { } ); - if (messageResponse.ok) { - const messageData = await messageResponse.json(); - return { - ...messageData.message, - roomName: room.name || 'Direct Message', - roomType: room.t, - }; + if (messagesResponse.ok) { + const messagesData = await messagesResponse.json(); + if (messagesData.messages && messagesData.messages.length > 0) { + const message = messagesData.messages[0]; + return { + ...message, + roomName: room.name || 'Direct Message', + roomType: room.t, + }; + } + } else { + console.error('Failed to fetch messages for room:', { + roomId: room._id, + status: messagesResponse.status, + response: await messagesResponse.text().catch(() => 'Could not get response text') + }); } - console.error('Failed to fetch message:', { - roomId: room._id, - messageId: room.lastMessage._id, - status: messageResponse.status, - response: await messageResponse.text().catch(() => 'Could not get response text') - }); return null; }) ); @@ -158,6 +162,7 @@ export async function GET() { .filter((msg): msg is NonNullable => msg !== null) .sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime()); + console.log('Found messages:', validMessages.length); return NextResponse.json({ messages: validMessages }); } catch (error) { console.error('Error fetching messages:', error);