carnet uix layout
This commit is contained in:
parent
4427aa9937
commit
79f83ad97f
@ -1,6 +1,6 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
import { DOMParser } from '@xmldom/xmldom';
|
||||
import { Buffer } from 'buffer';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
@ -13,6 +13,9 @@ declare global {
|
||||
const prisma = global.prisma || new PrismaClient();
|
||||
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
|
||||
|
||||
// Cache for folder structure
|
||||
const folderCache = new Map<string, { folders: string[]; timestamp: number }>();
|
||||
|
||||
async function sleep(ms: number) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
@ -201,126 +204,60 @@ async function getWebDAVCredentials(nextcloudUrl: string, username: string, admi
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user?.email || !session?.user?.id || !session?.accessToken) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
);
|
||||
if (!session?.user?.email) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const userId = session.user.email.split('@')[0];
|
||||
const nextcloudUsername = `cube-${userId}`;
|
||||
const nextcloudUrl = process.env.NEXTCLOUD_URL;
|
||||
const adminUsername = process.env.NEXTCLOUD_ADMIN_USERNAME;
|
||||
const adminPassword = process.env.NEXTCLOUD_ADMIN_PASSWORD;
|
||||
const webDAVUrl = `${nextcloudUrl}/remote.php/dav/files/${nextcloudUsername}/Private/`;
|
||||
|
||||
if (!nextcloudUrl || !adminUsername || !adminPassword) {
|
||||
console.error('Missing Nextcloud configuration');
|
||||
return NextResponse.json(
|
||||
{ error: 'Nextcloud configuration is missing' },
|
||||
{ status: 500 }
|
||||
);
|
||||
// Check cache first
|
||||
const cacheKey = nextcloudUsername;
|
||||
const cachedData = folderCache.get(cacheKey);
|
||||
if (cachedData) {
|
||||
const cacheAge = Date.now() - cachedData.timestamp;
|
||||
if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache
|
||||
return NextResponse.json({ folders: cachedData.folders });
|
||||
}
|
||||
}
|
||||
|
||||
// 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 }
|
||||
);
|
||||
// Fetch folder structure
|
||||
const response = await fetch(webDAVUrl, {
|
||||
headers: {
|
||||
'Authorization': `Basic ${Buffer.from(`${nextcloudUsername}:${process.env.NEXTCLOUD_ADMIN_PASSWORD}`).toString('base64')}`,
|
||||
'Depth': '1'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch folder structure');
|
||||
}
|
||||
|
||||
try {
|
||||
// Use the Keycloak ID as the Nextcloud username
|
||||
const nextcloudUsername = `cube-${session.user.id}`;
|
||||
console.log('Using Nextcloud username:', nextcloudUsername);
|
||||
const xmlData = await response.text();
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(xmlData, 'text/xml');
|
||||
const folders: string[] = [];
|
||||
|
||||
// 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');
|
||||
const responses = doc.getElementsByTagName('d:response');
|
||||
for (let i = 0; i < responses.length; i++) {
|
||||
const response = responses[i];
|
||||
const displayName = response.getElementsByTagName('d:displayname')[0]?.textContent;
|
||||
if (displayName && displayName !== 'Private') {
|
||||
folders.push(displayName);
|
||||
}
|
||||
|
||||
// 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: '<?xml version="1.0" encoding="UTF-8"?><d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/><d:displayname/></d:prop></d:propfind>',
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
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 }
|
||||
);
|
||||
|
||||
// Update cache
|
||||
folderCache.set(cacheKey, {
|
||||
folders,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
|
||||
return NextResponse.json({ folders });
|
||||
} catch (error) {
|
||||
console.error('Error in Nextcloud status:', error);
|
||||
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { redirect } from "next/navigation";
|
||||
import Navigation from "@/components/carnet/navigation";
|
||||
@ -44,23 +44,45 @@ export default function CarnetPage() {
|
||||
const isSmallScreen = useMediaQuery("(max-width: 768px)");
|
||||
const isMediumScreen = useMediaQuery("(max-width: 1024px)");
|
||||
|
||||
// Cache for Nextcloud folders
|
||||
const foldersCache = useRef<{ folders: string[]; timestamp: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchNextcloudFolders = async () => {
|
||||
// Check cache first
|
||||
if (foldersCache.current) {
|
||||
const cacheAge = Date.now() - foldersCache.current.timestamp;
|
||||
if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache
|
||||
setNextcloudFolders(foldersCache.current.folders);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/nextcloud/status');
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch Nextcloud folders');
|
||||
}
|
||||
const data = await response.json();
|
||||
setNextcloudFolders(data.folders || []);
|
||||
const folders = data.folders || [];
|
||||
|
||||
// Update cache
|
||||
foldersCache.current = {
|
||||
folders,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
|
||||
setNextcloudFolders(folders);
|
||||
} catch (err) {
|
||||
console.error('Error fetching Nextcloud folders:', err);
|
||||
setNextcloudFolders([]);
|
||||
}
|
||||
};
|
||||
|
||||
fetchNextcloudFolders();
|
||||
}, []);
|
||||
if (status === "authenticated") {
|
||||
fetchNextcloudFolders();
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "unauthenticated") {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user