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 { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
||||||
import { NextResponse } from "next/server";
|
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) {
|
export async function GET(request: Request) {
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
|
|
||||||
@ -34,30 +62,39 @@ export async function GET(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get the base URL from the environment variable
|
|
||||||
const baseUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0];
|
const baseUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0];
|
||||||
if (!baseUrl) {
|
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' }), {
|
return new Response(JSON.stringify({ error: 'Server configuration error' }), {
|
||||||
status: 500,
|
status: 500,
|
||||||
headers: { 'Content-Type': 'application/json' },
|
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`, {
|
const subscriptionsResponse = await fetch(`${baseUrl}/api/v1/subscriptions.get`, {
|
||||||
headers: {
|
headers: {
|
||||||
'X-Auth-Token': session.rocketChatToken,
|
'X-Auth-Token': tokenInfo.token,
|
||||||
'X-User-Id': session.rocketChatUserId,
|
'X-User-Id': tokenInfo.userId,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!subscriptionsResponse.ok) {
|
if (!subscriptionsResponse.ok) {
|
||||||
console.error('Failed to get subscriptions:', {
|
console.error('Failed to get subscriptions:', subscriptionsResponse.status);
|
||||||
status: subscriptionsResponse.status,
|
|
||||||
statusText: subscriptionsResponse.statusText,
|
|
||||||
username: session.user?.username
|
|
||||||
});
|
|
||||||
return new Response(JSON.stringify({ error: 'Failed to get subscriptions' }), {
|
return new Response(JSON.stringify({ error: 'Failed to get subscriptions' }), {
|
||||||
status: subscriptionsResponse.status,
|
status: subscriptionsResponse.status,
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
@ -65,81 +102,61 @@ export async function GET(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const subscriptionsData = await subscriptionsResponse.json();
|
const subscriptionsData = await subscriptionsResponse.json();
|
||||||
console.log('Subscriptions response:', subscriptionsData);
|
const userSubscriptions = subscriptionsData.update.filter((subscription: any) =>
|
||||||
|
subscription.t === 'd' ? subscription.rid.includes(tokenInfo.userId) : true
|
||||||
// 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 messages: any[] = [];
|
|
||||||
|
|
||||||
for (const subscription of userSubscriptions) {
|
|
||||||
// Skip if we already have 6 messages
|
|
||||||
if (messages.length >= 6) break;
|
|
||||||
|
|
||||||
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`,
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
'X-Auth-Token': session.rocketChatToken,
|
|
||||||
'X-User-Id': session.rocketChatUserId,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!messagesResponse.ok) {
|
const messages: any[] = [];
|
||||||
console.error(`Failed to get messages for room ${subscription.name}:`, {
|
const processedRooms = new Set();
|
||||||
status: messagesResponse.status,
|
|
||||||
statusText: messagesResponse.statusText,
|
for (const subscription of userSubscriptions) {
|
||||||
username: session.user?.username
|
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': tokenInfo.token,
|
||||||
|
'X-User-Id': tokenInfo.userId,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
msgId: subscription.lastMessage?._id,
|
||||||
|
roomId: subscription.rid,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const messagesData = await messagesResponse.json();
|
if (!messagesResponse.ok) continue;
|
||||||
console.log(`Messages response for ${subscription.name}:`, messagesData);
|
|
||||||
|
|
||||||
if (messagesData.messages && messagesData.messages.length > 0) {
|
const messageData = await messagesResponse.json();
|
||||||
const lastMessage = messagesData.messages[0];
|
if (messageData.message) {
|
||||||
messages.push({
|
messages.push({
|
||||||
...lastMessage,
|
...messageData.message,
|
||||||
roomName: subscription.fname || subscription.name || 'Direct Message',
|
roomName: subscription.fname || subscription.name || 'Direct Message',
|
||||||
roomType: subscription.t,
|
roomType: subscription.t,
|
||||||
unread: subscription.unread || 0,
|
unread: subscription.unread || 0,
|
||||||
userMentions: subscription.userMentions || 0,
|
userMentions: subscription.userMentions || 0,
|
||||||
groupMentions: subscription.groupMentions || 0,
|
|
||||||
alert: subscription.alert || false
|
alert: subscription.alert || false
|
||||||
});
|
});
|
||||||
} else {
|
}
|
||||||
console.log(`No messages found for room: ${roomId}`);
|
} catch (error) {
|
||||||
|
console.error(`Error fetching message for room ${subscription.rid}`);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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());
|
messages.sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime());
|
||||||
const limitedMessages = messages.slice(0, 6);
|
const limitedMessages = messages.slice(0, 6);
|
||||||
|
|
||||||
console.log('Found messages:', limitedMessages.length);
|
|
||||||
return new Response(JSON.stringify({ messages: limitedMessages }), {
|
return new Response(JSON.stringify({ messages: limitedMessages }), {
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching messages:', error);
|
console.error('Error fetching messages');
|
||||||
return new Response(JSON.stringify({ error: 'Internal server error' }), {
|
return new Response(JSON.stringify({ error: 'Internal server error' }), {
|
||||||
status: 500,
|
status: 500,
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user