Fondation

This commit is contained in:
alma 2026-01-17 13:44:45 +01:00
parent 672333a6db
commit 866b8fb3dc
10 changed files with 162 additions and 91 deletions

View File

@ -79,7 +79,12 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'Server configuration error' }, { status: 500 });
}
logger.debug('[ROCKET_CHAT] Using Rocket.Chat base URL');
logger.debug('[ROCKET_CHAT] Using Rocket.Chat base URL', {
baseUrl,
hasToken: !!process.env.ROCKET_CHAT_TOKEN,
hasUserId: !!process.env.ROCKET_CHAT_USER_ID,
hasSecret: !!process.env.ROCKET_CHAT_CREATE_TOKEN_SECRET,
});
// Step 1: Use admin token to authenticate
const adminHeaders = {
@ -100,15 +105,37 @@ export async function GET(request: Request) {
// Get all users to find the current user
let usersData;
try {
usersData = await fetchJsonWithTimeout(`${baseUrl}/api/v1/users.list`, {
const usersListUrl = `${baseUrl}/api/v1/users.list`;
logger.debug('[ROCKET_CHAT] Fetching users list', { url: usersListUrl });
usersData = await fetchJsonWithTimeout(usersListUrl, {
method: 'GET',
timeout: 10000, // 10 seconds
headers: adminHeaders
});
} catch (error) {
logger.error('[ROCKET_CHAT] Error fetching users list', {
error: error instanceof Error ? error.message : String(error),
logger.debug('[ROCKET_CHAT] Successfully fetched users list', {
success: usersData.success,
count: usersData.count,
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error('[ROCKET_CHAT] Error fetching users list', {
error: errorMessage,
baseUrl,
url: `${baseUrl}/api/v1/users.list`,
hasToken: !!process.env.ROCKET_CHAT_TOKEN,
hasUserId: !!process.env.ROCKET_CHAT_USER_ID,
});
// If it's an HTML response error, log more details
if (errorMessage.includes('text/html')) {
logger.error('[ROCKET_CHAT] RocketChat returned HTML instead of JSON - possible authentication or URL issue', {
baseUrl,
checkUrl: `${baseUrl}/api/v1/users.list`,
});
}
// Return empty messages instead of failing completely
return NextResponse.json({ messages: [] }, { status: 200 });
}
@ -412,10 +439,28 @@ export async function GET(request: Request) {
return NextResponse.json(finalResponse);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error('[ROCKET_CHAT] Error fetching messages', {
error: error instanceof Error ? error.message : String(error),
error: errorMessage,
baseUrl: process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0],
hasToken: !!process.env.ROCKET_CHAT_TOKEN,
hasUserId: !!process.env.ROCKET_CHAT_USER_ID,
hasSecret: !!process.env.ROCKET_CHAT_CREATE_TOKEN_SECRET,
});
return NextResponse.json({ error: 'Failed to fetch messages' }, { status: 500 });
// If it's an HTML response error, provide more helpful message
if (errorMessage.includes('text/html') || errorMessage.includes('HTML')) {
logger.error('[ROCKET_CHAT] RocketChat is returning HTML - possible causes:', {
cause1: 'Invalid or expired ROCKET_CHAT_TOKEN',
cause2: 'Invalid or expired ROCKET_CHAT_USER_ID',
cause3: 'Incorrect baseUrl (check NEXT_PUBLIC_IFRAME_PAROLE_URL)',
cause4: 'RocketChat server is down or unreachable',
cause5: 'RocketChat API endpoint changed or requires different authentication',
});
}
// Return empty messages instead of error to prevent widget from breaking
return NextResponse.json({ messages: [], total: 0, hasMore: false, totalUnreadCount: 0 }, { status: 200 });
}
}

View File

@ -27,6 +27,13 @@ export async function GET(request: Request) {
);
}
logger.debug('[ROCKET_CHAT_USER_TOKEN] Using Rocket.Chat base URL', {
baseUrl,
hasToken: !!process.env.ROCKET_CHAT_TOKEN,
hasUserId: !!process.env.ROCKET_CHAT_USER_ID,
hasSecret: !!process.env.ROCKET_CHAT_CREATE_TOKEN_SECRET,
});
// Use admin token to authenticate
const adminHeaders = {
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
@ -46,14 +53,26 @@ export async function GET(request: Request) {
// Get all users to find the current user
let usersResponse;
const usersListUrl = `${baseUrl}/api/v1/users.list`;
try {
usersResponse = await fetch(`${baseUrl}/api/v1/users.list`, {
logger.debug('[ROCKET_CHAT_USER_TOKEN] Fetching users list', { url: usersListUrl });
usersResponse = await fetch(usersListUrl, {
method: 'GET',
headers: adminHeaders
});
logger.debug('[ROCKET_CHAT_USER_TOKEN] Users list response', {
status: usersResponse.status,
statusText: usersResponse.statusText,
contentType: usersResponse.headers.get('content-type'),
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error('[ROCKET_CHAT_USER_TOKEN] Error fetching users list', {
error: error instanceof Error ? error.message : String(error),
error: errorMessage,
baseUrl,
url: usersListUrl,
});
return NextResponse.json(
{ error: 'Failed to connect to RocketChat' },

View File

@ -78,8 +78,18 @@ export async function fetchJsonWithTimeout<T = any>(
): Promise<T> {
const response = await fetchWithTimeout(url, options);
// Clone response early so we can read it multiple times if needed
const clonedResponse = response.clone();
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
const errorText = await clonedResponse.text().catch(() => 'Unknown error');
const contentType = response.headers.get('content-type') || '';
// If it's HTML, provide more context
if (contentType.includes('text/html') || errorText.trim().startsWith('<!DOCTYPE') || errorText.trim().startsWith('<html')) {
throw new Error(`HTTP ${response.status} ${response.statusText}: Server returned HTML page instead of JSON. This usually means authentication failed or URL is incorrect. Preview: ${errorText.substring(0, 300)}`);
}
throw new Error(
`HTTP ${response.status} ${response.statusText}: ${errorText.substring(0, 200)}`
);
@ -89,26 +99,23 @@ export async function fetchJsonWithTimeout<T = any>(
// Check if response is JSON
if (!contentType.includes('application/json')) {
// Try to read the response text to see what we got
const responseText = await response.text().catch(() => 'Unable to read response');
const preview = responseText.substring(0, 200);
// Read the response text to see what we got
const responseText = await clonedResponse.text().catch(() => 'Unable to read response');
const preview = responseText.substring(0, 500);
// If it looks like HTML, provide a more helpful error
if (responseText.trim().startsWith('<!DOCTYPE') || responseText.trim().startsWith('<html')) {
throw new Error(`Expected JSON response, got text/html. Server may be returning an error page. Preview: ${preview}`);
throw new Error(`Expected JSON response, got text/html. Server may be returning an error page or login page. URL: ${url}. Preview: ${preview}`);
}
throw new Error(`Expected JSON response, got ${contentType || 'unknown'}. Preview: ${preview}`);
throw new Error(`Expected JSON response, got ${contentType || 'unknown'}. URL: ${url}. Preview: ${preview}`);
}
// Clone the response before reading it, in case we need to read it again
const clonedResponse = response.clone();
try {
return await response.json();
} catch (jsonError) {
// If JSON parsing fails, try to read the text to see what we got
const responseText = await clonedResponse.text().catch(() => 'Unable to read response');
throw new Error(`Failed to parse JSON response. Content: ${responseText.substring(0, 200)}`);
throw new Error(`Failed to parse JSON response from ${url}. Content: ${responseText.substring(0, 500)}`);
}
}