186 lines
6.2 KiB
TypeScript
186 lines
6.2 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' },
|
|
});
|
|
}
|
|
|
|
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' },
|
|
});
|
|
}
|
|
|
|
console.log('Using Rocket.Chat base URL:', baseUrl);
|
|
|
|
// Use admin token to get messages
|
|
const adminHeaders = {
|
|
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
|
|
'X-User-Id': process.env.ROCKET_CHAT_USER_ID!,
|
|
'Content-Type': 'application/json'
|
|
};
|
|
|
|
// First, get the user's Rocket.Chat ID using their email
|
|
const userInfoResponse = await fetch(`${baseUrl}/api/v1/users.info`, {
|
|
method: 'GET',
|
|
headers: {
|
|
...adminHeaders,
|
|
'Content-Type': 'application/json'
|
|
},
|
|
// Add email as query parameter
|
|
query: `?username=${session.user.email?.split('@')[0]}`
|
|
});
|
|
|
|
if (!userInfoResponse.ok) {
|
|
console.error('Failed to get user info:', userInfoResponse.status);
|
|
return new Response(JSON.stringify({ error: 'Failed to get user info' }), {
|
|
status: userInfoResponse.status,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
const userInfo = await userInfoResponse.json();
|
|
console.log('Found Rocket.Chat user:', {
|
|
username: userInfo.user?.username,
|
|
id: userInfo.user?._id
|
|
});
|
|
|
|
// Get user's subscriptions using admin token
|
|
const subscriptionsResponse = await fetch(`${baseUrl}/api/v1/subscriptions.list`, {
|
|
method: 'GET',
|
|
headers: adminHeaders
|
|
});
|
|
|
|
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();
|
|
console.log('Subscriptions response:', {
|
|
success: subscriptionsData.success,
|
|
count: subscriptionsData.count,
|
|
subscriptionsCount: subscriptionsData.subscriptions?.length
|
|
});
|
|
|
|
// Filter subscriptions for the current user
|
|
const userSubscriptions = subscriptionsData.subscriptions.filter((sub: any) =>
|
|
sub.u?._id === userInfo.user._id ||
|
|
(sub.userMentions > 0 && sub.alert)
|
|
);
|
|
|
|
console.log('Filtered subscriptions:', {
|
|
total: userSubscriptions.length,
|
|
roomTypes: userSubscriptions.map((sub: any) => sub.t)
|
|
});
|
|
|
|
const messages: any[] = [];
|
|
const processedRooms = new Set();
|
|
|
|
// Fetch messages using admin token
|
|
for (const subscription of userSubscriptions) {
|
|
if (messages.length >= 6 || processedRooms.has(subscription._id)) continue;
|
|
processedRooms.add(subscription._id);
|
|
|
|
try {
|
|
// Get the latest messages from the room
|
|
const messagesResponse = await fetch(
|
|
`${baseUrl}/api/v1/channels.messages`, {
|
|
method: 'GET',
|
|
headers: adminHeaders,
|
|
query: `?roomId=${subscription.rid}&count=1`
|
|
});
|
|
|
|
if (!messagesResponse.ok) {
|
|
console.error(`Failed to get messages for room ${subscription.name}:`, messagesResponse.status);
|
|
continue;
|
|
}
|
|
|
|
const messageData = await messagesResponse.json();
|
|
console.log(`Messages for room ${subscription.name}:`, {
|
|
success: messageData.success,
|
|
count: messageData.count,
|
|
hasMessages: messageData.messages?.length > 0
|
|
});
|
|
|
|
if (messageData.success && messageData.messages?.length > 0) {
|
|
messages.push({
|
|
...messageData.messages[0],
|
|
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.name}:`, error);
|
|
continue;
|
|
}
|
|
}
|
|
|
|
console.log('Final messages count:', messages.length);
|
|
|
|
// 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:', error);
|
|
return new Response(JSON.stringify({ error: 'Internal server error' }), {
|
|
status: 500,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
}
|