widget parole 2
This commit is contained in:
parent
78e37c8969
commit
5a5dc7990a
@ -2,6 +2,34 @@ import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
// Helper function to create/refresh token
|
||||
async function ensureValidToken(baseUrl: string, userId: string, currentToken: string | null) {
|
||||
try {
|
||||
// Try to create a new token
|
||||
const tokenResponse = await fetch(`${baseUrl}/api/v1/users.createToken`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Auth-Token': currentToken || '',
|
||||
'X-User-Id': userId,
|
||||
},
|
||||
});
|
||||
|
||||
if (tokenResponse.ok) {
|
||||
const tokenData = await tokenResponse.json();
|
||||
return {
|
||||
token: tokenData.data.authToken,
|
||||
userId: tokenData.data.userId,
|
||||
};
|
||||
}
|
||||
|
||||
console.error('Failed to create/refresh token:', tokenResponse.status);
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Error creating/refreshing token:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
@ -34,30 +62,39 @@ export async function GET(request: Request) {
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the base URL from the environment variable
|
||||
const baseUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0];
|
||||
if (!baseUrl) {
|
||||
console.error('Failed to get Rocket.Chat base URL from environment variables');
|
||||
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' },
|
||||
});
|
||||
}
|
||||
|
||||
// Get user's subscriptions
|
||||
// Ensure we have valid token
|
||||
const tokenInfo = await ensureValidToken(
|
||||
baseUrl,
|
||||
session.rocketChatUserId || '',
|
||||
session.rocketChatToken || null
|
||||
);
|
||||
|
||||
if (!tokenInfo) {
|
||||
return new Response(JSON.stringify({ error: 'Failed to authenticate with Rocket.Chat' }), {
|
||||
status: 401,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
// Get user's subscriptions with new token
|
||||
const subscriptionsResponse = await fetch(`${baseUrl}/api/v1/subscriptions.get`, {
|
||||
headers: {
|
||||
'X-Auth-Token': session.rocketChatToken,
|
||||
'X-User-Id': session.rocketChatUserId,
|
||||
'X-Auth-Token': tokenInfo.token,
|
||||
'X-User-Id': tokenInfo.userId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!subscriptionsResponse.ok) {
|
||||
console.error('Failed to get subscriptions:', {
|
||||
status: subscriptionsResponse.status,
|
||||
statusText: subscriptionsResponse.statusText,
|
||||
username: session.user?.username
|
||||
});
|
||||
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' },
|
||||
@ -65,81 +102,61 @@ export async function GET(request: Request) {
|
||||
}
|
||||
|
||||
const subscriptionsData = await subscriptionsResponse.json();
|
||||
console.log('Subscriptions response:', subscriptionsData);
|
||||
|
||||
// Filter subscriptions to only include rooms where the user is a participant
|
||||
const userSubscriptions = subscriptionsData.update.filter((subscription: any) => {
|
||||
// For direct messages, check if the room ID contains the user's ID
|
||||
if (subscription.t === 'd') {
|
||||
return subscription.rid.includes(session.rocketChatUserId);
|
||||
}
|
||||
// For channels and groups, include all subscriptions
|
||||
return true;
|
||||
});
|
||||
|
||||
console.log('Filtered subscriptions for user:', userSubscriptions.length);
|
||||
const userSubscriptions = subscriptionsData.update.filter((subscription: any) =>
|
||||
subscription.t === 'd' ? subscription.rid.includes(tokenInfo.userId) : true
|
||||
);
|
||||
|
||||
const messages: any[] = [];
|
||||
const processedRooms = new Set();
|
||||
|
||||
for (const subscription of userSubscriptions) {
|
||||
// Skip if we already have 6 messages
|
||||
if (messages.length >= 6) break;
|
||||
if (messages.length >= 6 || processedRooms.has(subscription.rid)) continue;
|
||||
processedRooms.add(subscription.rid);
|
||||
|
||||
console.log(`Fetching messages for room ${subscription.name} using endpoint ${subscription.t === 'c' ? 'channels.messages' : 'im.messages'}`);
|
||||
|
||||
const endpoint = subscription.t === 'c' ? 'channels.messages' : 'im.messages';
|
||||
const roomId = subscription.t === 'c' ? subscription.name : subscription.rid;
|
||||
|
||||
// Only fetch the last message
|
||||
const messagesResponse = await fetch(
|
||||
`${baseUrl}/api/v1/${endpoint}?roomId=${roomId}&count=1`,
|
||||
{
|
||||
try {
|
||||
const messagesResponse = await fetch(
|
||||
`${baseUrl}/api/v1/chat.getMessage`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Auth-Token': session.rocketChatToken,
|
||||
'X-User-Id': session.rocketChatUserId,
|
||||
'X-Auth-Token': tokenInfo.token,
|
||||
'X-User-Id': tokenInfo.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
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
if (!messagesResponse.ok) {
|
||||
console.error(`Failed to get messages for room ${subscription.name}:`, {
|
||||
status: messagesResponse.status,
|
||||
statusText: messagesResponse.statusText,
|
||||
username: session.user?.username
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`Error fetching message for room ${subscription.rid}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const messagesData = await messagesResponse.json();
|
||||
console.log(`Messages response for ${subscription.name}:`, messagesData);
|
||||
|
||||
if (messagesData.messages && messagesData.messages.length > 0) {
|
||||
const lastMessage = messagesData.messages[0];
|
||||
messages.push({
|
||||
...lastMessage,
|
||||
roomName: subscription.fname || subscription.name || 'Direct Message',
|
||||
roomType: subscription.t,
|
||||
unread: subscription.unread || 0,
|
||||
userMentions: subscription.userMentions || 0,
|
||||
groupMentions: subscription.groupMentions || 0,
|
||||
alert: subscription.alert || false
|
||||
});
|
||||
} else {
|
||||
console.log(`No messages found for room: ${roomId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort messages by timestamp (newest first) and take only the first 6
|
||||
// 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);
|
||||
|
||||
console.log('Found messages:', limitedMessages.length);
|
||||
return new Response(JSON.stringify({ messages: limitedMessages }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching messages:', error);
|
||||
console.error('Error fetching messages');
|
||||
return new Response(JSON.stringify({ error: 'Internal server error' }), {
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
Loading…
Reference in New Issue
Block a user