diff --git a/app/api/nextcloud/status/route.ts b/app/api/nextcloud/status/route.ts index 7d6437a9..0182faed 100644 --- a/app/api/nextcloud/status/route.ts +++ b/app/api/nextcloud/status/route.ts @@ -17,14 +17,35 @@ if (process.env.NODE_ENV !== 'production') global.prisma = prisma; const folderCache = new Map(); const credentialsCache = new Map(); +// Cache for Nextcloud connectivity check +let lastConnectivityCheck = 0; +let isNextcloudAccessible = false; + async function sleep(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)); } +async function checkNextcloudConnectivity(nextcloudUrl: string): Promise { + const now = Date.now(); + if (now - lastConnectivityCheck < 5 * 60 * 1000) { // 5 minutes cache + return isNextcloudAccessible; + } + + try { + const testResponse = await fetch(`${nextcloudUrl}/status.php`); + isNextcloudAccessible = testResponse.ok; + lastConnectivityCheck = now; + return isNextcloudAccessible; + } catch (error) { + console.error('Nextcloud connectivity check failed:', error); + isNextcloudAccessible = false; + lastConnectivityCheck = now; + return false; + } +} + async function parseXMLResponse(response: Response): Promise { const text = await response.text(); - console.log('XML Response:', text); - const parser = new DOMParser(); const xmlDoc = parser.parseFromString(text, 'text/xml'); @@ -217,6 +238,58 @@ async function getWebDAVCredentials(nextcloudUrl: string, username: string, admi } } +async function getFolderStructure(nextcloudUrl: string, username: string, password: string): Promise { + try { + const webdavUrl = `${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/Private/`; + const foldersResponse = await fetch(webdavUrl, { + method: 'PROPFIND', + headers: { + 'Authorization': `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`, + 'Depth': '1', + 'Content-Type': 'application/xml', + }, + body: '', + }); + + if (foldersResponse.status === 429) { + // Rate limited, wait and retry + const retryAfter = foldersResponse.headers.get('Retry-After'); + await sleep((retryAfter ? parseInt(retryAfter) : 5) * 1000); + return getFolderStructure(nextcloudUrl, username, password); + } + + if (!foldersResponse.ok) { + throw new Error(`Failed to fetch folders: ${foldersResponse.status} ${foldersResponse.statusText}`); + } + + const folderData = await foldersResponse.text(); + 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 href = response.getElementsByTagName('d:href')[0]?.textContent; + if (href) { + const folderName = href.split('/').pop(); + if (folderName && folderName !== 'Private') { + folders.push(folderName); + } + } + } + } + + return folders; + } catch (error) { + console.error('Error getting folder structure:', error); + throw error; + } +} + export async function GET() { try { const session = await getServerSession(authOptions); @@ -233,120 +306,58 @@ export async function GET() { 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()); + // Check Nextcloud connectivity with caching + const isAccessible = await checkNextcloudConnectivity(nextcloudUrl); + if (!isAccessible) { return NextResponse.json({ error: "Nextcloud n'est pas accessible" }, { status: 503 }); } - try { - // Use the Keycloak ID as the Nextcloud username - const nextcloudUsername = `cube-${session.user.id}`; - console.log('Using Nextcloud username:', nextcloudUsername); + // Use the Keycloak ID as the Nextcloud username + const nextcloudUsername = `cube-${session.user.id}`; + console.log('Using Nextcloud username:', nextcloudUsername); - // Check cache first - const cachedData = folderCache.get(nextcloudUsername); - if (cachedData) { - const cacheAge = Date.now() - cachedData.timestamp; - if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache - return NextResponse.json({ - isConnected: true, - folders: cachedData.folders - }); - } + // Check cache first + const cachedData = folderCache.get(nextcloudUsername); + if (cachedData) { + const cacheAge = Date.now() - cachedData.timestamp; + if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache + return NextResponse.json({ + isConnected: true, + folders: cachedData.folders + }); } - - // Get or create WebDAV credentials - const webdavPassword = await getWebDAVCredentials( - nextcloudUrl, - nextcloudUsername, - adminUsername, - adminPassword, - session.user.id - ); - - if (!webdavPassword) { - throw new Error('Failed to get WebDAV credentials'); - } - - // Get user's folders using WebDAV with Basic authentication - const webdavUrl = `${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(nextcloudUsername)}/Private/`; - console.log('Requesting WebDAV URL:', webdavUrl); - - const foldersResponse = await fetch(webdavUrl, { - method: 'PROPFIND', - headers: { - 'Authorization': `Basic ${Buffer.from(`${nextcloudUsername}:${webdavPassword}`).toString('base64')}`, - 'Depth': '1', - 'Content-Type': 'application/xml', - }, - body: '', - }); - - if (foldersResponse.status === 429) { - // Rate limited, wait and retry - const retryAfter = foldersResponse.headers.get('Retry-After'); - await sleep((retryAfter ? parseInt(retryAfter) : 5) * 1000); - return GET(); // Retry the entire request - } - - if (!foldersResponse.ok) { - const errorText = await foldersResponse.text(); - console.error('Failed to fetch folders. Status:', foldersResponse.status); - console.error('Response:', errorText); - console.error('Response headers:', Object.fromEntries(foldersResponse.headers.entries())); - 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 - 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 href = response.getElementsByTagName('d:href')[0]?.textContent; - if (href) { - // Extract folder name from href - const folderName = decodeURIComponent(href.split('/').filter(Boolean).pop() || ''); - if (folderName && folderName !== 'Private') { - folders.push(folderName); - } - } - } - } - - console.log('Parsed folders:', folders); - - // Update cache - folderCache.set(nextcloudUsername, { - folders, - timestamp: Date.now() - }); - - 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); + + // Get or create WebDAV credentials + const webdavPassword = await getWebDAVCredentials( + nextcloudUrl, + nextcloudUsername, + adminUsername, + adminPassword, + session.user.id + ); + + if (!webdavPassword) { + throw new Error('Failed to get WebDAV credentials'); + } + + // Get folder structure + const folders = await getFolderStructure(nextcloudUrl, nextcloudUsername, webdavPassword); + + // Update cache + folderCache.set(nextcloudUsername, { + folders, + timestamp: Date.now() + }); + + return NextResponse.json({ + isConnected: true, + folders + }); + } catch (error) { + console.error('Error in Nextcloud status endpoint:', error); return NextResponse.json( - { error: 'Failed to check Nextcloud status', details: error?.message || String(error) }, + { error: error instanceof Error ? error.message : 'An error occurred' }, { status: 500 } ); }