Neah/app/api/nextcloud/status/route.ts
2025-04-20 13:07:24 +02:00

129 lines
4.2 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { DOMParser } from '@xmldom/xmldom';
async function getNextcloudAccessToken(clientId: string, clientSecret: string) {
const nextcloudUrl = process.env.NEXTCLOUD_URL;
const tokenEndpoint = `${nextcloudUrl}/apps/oauth2/api/v1/token`;
const params = new URLSearchParams({
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
});
const response = await fetch(tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
});
if (!response.ok) {
throw new Error('Failed to get Nextcloud access token');
}
const data = await response.json();
return data.access_token;
}
export async function GET() {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const nextcloudUrl = process.env.NEXTCLOUD_URL;
const nextcloudClientId = process.env.NEXTCLOUD_CLIENT_ID;
const nextcloudClientSecret = process.env.NEXTCLOUD_CLIENT_SECRET;
if (!nextcloudUrl || !nextcloudClientId || !nextcloudClientSecret) {
console.error('Missing Nextcloud configuration');
return NextResponse.json(
{ error: 'Nextcloud configuration is missing' },
{ status: 500 }
);
}
// Test Nextcloud connectivity
const testResponse = await fetch(`${nextcloudUrl}/status.php`);
if (!testResponse.ok) {
console.error('Nextcloud is not accessible:', await testResponse.text());
return NextResponse.json(
{ error: "Nextcloud n'est pas accessible" },
{ status: 503 }
);
}
try {
// Get access token
const accessToken = await getNextcloudAccessToken(nextcloudClientId, nextcloudClientSecret);
// Get user's folders using WebDAV
const webdavUrl = `${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(session.user.email)}/`;
console.log('Requesting WebDAV URL:', webdavUrl);
const foldersResponse = await fetch(webdavUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Depth': '1',
'Content-Type': 'application/xml',
},
});
if (!foldersResponse.ok) {
const errorText = await foldersResponse.text();
console.error('Failed to fetch folders. Status:', foldersResponse.status);
console.error('Response:', errorText);
throw new Error(`Failed to fetch folders: ${errorText}`);
}
const folderData = await foldersResponse.text();
console.log('Folder data:', folderData);
// Parse the XML response to get folder names and filter only directories
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(folderData, 'text/xml');
const responses = Array.from(xmlDoc.getElementsByTagName('d:response'));
const folders: string[] = [];
for (const response of responses) {
const resourceType = response.getElementsByTagName('d:resourcetype')[0];
const isCollection = resourceType?.getElementsByTagName('d:collection').length > 0;
if (isCollection) {
const displayName = response.getElementsByTagName('d:displayname')[0]?.textContent;
if (displayName && displayName !== session.user.email) {
folders.push(displayName);
}
}
}
console.log('Parsed folders:', folders);
return NextResponse.json({
isConnected: true,
folders
});
} catch (error: any) {
console.error('Error accessing Nextcloud WebDAV:', error);
return NextResponse.json(
{ error: "Erreur d'accès aux dossiers Nextcloud", details: error?.message || String(error) },
{ status: 503 }
);
}
} catch (error: any) {
console.error('Error checking Nextcloud status:', error);
return NextResponse.json(
{ error: 'Failed to check Nextcloud status', details: error?.message || String(error) },
{ status: 500 }
);
}
}