NeahFront7/app/api/rocket-chat/messages/route.ts
2025-04-13 00:12:49 +02:00

162 lines
5.3 KiB
TypeScript

import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { NextResponse } from "next/server";
// Helper function to get user token using admin credentials
async function getUserToken(baseUrl: string) {
try {
// Step 1: Use admin token to authenticate
const adminHeaders = {
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
'X-User-Id': process.env.ROCKET_CHAT_USER_ID!,
'Content-Type': 'application/json'
};
// Step 2: Create user token using admin credentials
const createTokenResponse = await fetch(`${baseUrl}/api/v1/users.createToken`, {
method: 'POST',
headers: adminHeaders
});
if (!createTokenResponse.ok) {
console.error('Failed to create user token:', createTokenResponse.status);
return null;
}
const tokenData = await createTokenResponse.json();
return {
authToken: tokenData.data.authToken,
userId: tokenData.data.userId
};
} catch (error) {
console.error('Error getting user token:', error);
return null;
}
}
export async function GET(request: Request) {
const session = await getServerSession(authOptions);
if (!session) {
console.error('No session found');
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}
console.log('Session data:', {
hasToken: !!session.rocketChatToken,
hasUserId: !!session.rocketChatUserId,
tokenLength: session.rocketChatToken?.length,
userIdLength: session.rocketChatUserId?.length,
username: session.user?.username
});
if (!session.rocketChatToken || !session.rocketChatUserId) {
console.error('Missing Rocket.Chat credentials in session:', {
hasToken: !!session.rocketChatToken,
hasUserId: !!session.rocketChatUserId,
username: session.user?.username
});
return new Response(JSON.stringify({ error: 'Missing Rocket.Chat credentials' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}
try {
const baseUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0];
if (!baseUrl) {
console.error('Failed to get Rocket.Chat base URL');
return new Response(JSON.stringify({ error: 'Server configuration error' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
// Step 1 & 2: Get user token using admin credentials
const userToken = await getUserToken(baseUrl);
if (!userToken) {
return new Response(JSON.stringify({ error: 'Failed to create user token' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}
// Step 3: Use the user token to fetch subscriptions
const subscriptionsResponse = await fetch(`${baseUrl}/api/v1/subscriptions.get`, {
headers: {
'X-Auth-Token': userToken.authToken,
'X-User-Id': userToken.userId,
},
});
if (!subscriptionsResponse.ok) {
console.error('Failed to get subscriptions:', subscriptionsResponse.status);
return new Response(JSON.stringify({ error: 'Failed to get subscriptions' }), {
status: subscriptionsResponse.status,
headers: { 'Content-Type': 'application/json' },
});
}
const subscriptionsData = await subscriptionsResponse.json();
const userSubscriptions = subscriptionsData.update;
const messages: any[] = [];
const processedRooms = new Set();
// Step 3: Use the same user token to fetch messages
for (const subscription of userSubscriptions) {
if (messages.length >= 6 || processedRooms.has(subscription.rid)) continue;
processedRooms.add(subscription.rid);
try {
const messagesResponse = await fetch(
`${baseUrl}/api/v1/chat.getMessage`, {
method: 'POST',
headers: {
'X-Auth-Token': userToken.authToken,
'X-User-Id': userToken.userId,
'Content-Type': 'application/json',
},
body: JSON.stringify({
msgId: subscription.lastMessage?._id,
roomId: subscription.rid,
}),
});
if (!messagesResponse.ok) continue;
const messageData = await messagesResponse.json();
if (messageData.message) {
messages.push({
...messageData.message,
roomName: subscription.fname || subscription.name || 'Direct Message',
roomType: subscription.t,
unread: subscription.unread || 0,
userMentions: subscription.userMentions || 0,
alert: subscription.alert || false
});
}
} catch (error) {
console.error(`Error fetching message for room ${subscription.rid}`);
continue;
}
}
// Sort messages by timestamp (newest first) and limit to 6
messages.sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime());
const limitedMessages = messages.slice(0, 6);
return new Response(JSON.stringify({ messages: limitedMessages }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.error('Error fetching messages');
return new Response(JSON.stringify({ error: 'Internal server error' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}