import { getServerSession } from "next-auth"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { NextResponse } from "next/server"; export async function GET() { try { const session = await getServerSession(authOptions); if (!session) { console.error('No session found'); return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } console.log('Session data:', { hasToken: !!session.rocketChatToken, hasUserId: !!session.rocketChatUserId, tokenLength: session.rocketChatToken?.length, userIdLength: session.rocketChatUserId?.length }); // Get the user's Rocket.Chat token from their session const rocketChatToken = session.rocketChatToken; const rocketChatUserId = session.rocketChatUserId; if (!rocketChatToken || !rocketChatUserId) { console.error('Missing Rocket.Chat credentials in session:', { hasToken: !!rocketChatToken, hasUserId: !!rocketChatUserId, session: session }); return NextResponse.json({ error: "User not authenticated with Rocket.Chat" }, { status: 401 }); } // Get the user's subscriptions (rooms they are in) const subscriptionsResponse = await fetch( 'https://parole.slm-lab.net/api/v1/subscriptions.get', { headers: { 'X-Auth-Token': rocketChatToken, 'X-User-Id': rocketChatUserId, 'Content-Type': 'application/json' } } ); if (!subscriptionsResponse.ok) { console.error('Rocket.Chat subscriptions error:', { status: subscriptionsResponse.status, statusText: subscriptionsResponse.statusText, response: await subscriptionsResponse.text().catch(() => 'Could not get response text') }); return NextResponse.json( { error: "Failed to fetch subscriptions" }, { status: subscriptionsResponse.status } ); } const subscriptions = await subscriptionsResponse.json(); console.log('Subscriptions response:', subscriptions); if (!subscriptions.update || subscriptions.update.length === 0) { console.log('No subscriptions found'); return NextResponse.json({ messages: [] }); } // Get the last message from each room const messages = await Promise.all( subscriptions.update.map(async (subscription: any) => { try { if (!subscription.rid) { console.log('No room ID found for subscription:', subscription); return null; } // Choose the appropriate endpoint based on room type const endpoint = subscription.t === 'd' ? 'im.messages' : subscription.t === 'c' ? 'channels.messages' : 'groups.messages'; console.log(`Fetching messages for room ${subscription.name} using endpoint ${endpoint}`); // Get the most recent messages from the room const messagesResponse = await fetch( `https://parole.slm-lab.net/api/v1/${endpoint}?roomId=${subscription.rid}&count=1`, { headers: { 'X-Auth-Token': rocketChatToken, 'X-User-Id': rocketChatUserId, 'Content-Type': 'application/json' } } ); if (!messagesResponse.ok) { console.error('Failed to fetch messages:', { roomId: subscription.rid, endpoint, status: messagesResponse.status, response: await messagesResponse.text().catch(() => 'Could not get response text') }); return null; } const messagesData = await messagesResponse.json(); console.log(`Messages response for ${subscription.name}:`, { count: messagesData.messages?.length, success: messagesData.success }); if (messagesData.messages && messagesData.messages.length > 0) { const message = messagesData.messages[0]; // For direct messages, check if the room ID contains the user's ID if (subscription.t === 'd') { // Extract the other user's ID from the room ID const roomIdParts = subscription.rid.split(rocketChatUserId); const otherUserId = roomIdParts[0] || roomIdParts[1]; // Only include messages where the user is either the sender or the recipient if (message.u._id === rocketChatUserId || message.u._id === otherUserId) { return { ...message, roomName: subscription.fname || subscription.name || 'Direct Message', roomType: subscription.t, }; } } else { // For channels and groups, only include messages where the user is the sender if (message.u._id === rocketChatUserId) { return { ...message, roomName: subscription.fname || subscription.name || 'Direct Message', roomType: subscription.t, }; } } } console.log('No messages found for room:', subscription.rid); return null; } catch (error) { console.error('Error processing room:', subscription.rid, error); return null; } }) ); // Filter out any null messages and sort by timestamp const validMessages = messages .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); return NextResponse.json( { error: "Internal server error" }, { status: 500 } ); } }