carnet uix layout
This commit is contained in:
parent
4427aa9937
commit
79f83ad97f
@ -1,6 +1,6 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import { NextResponse } from 'next/server';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
import { authOptions } from '@/lib/auth';
|
||||||
import { DOMParser } from '@xmldom/xmldom';
|
import { DOMParser } from '@xmldom/xmldom';
|
||||||
import { Buffer } from 'buffer';
|
import { Buffer } from 'buffer';
|
||||||
import { PrismaClient } from '@prisma/client';
|
import { PrismaClient } from '@prisma/client';
|
||||||
@ -13,6 +13,9 @@ declare global {
|
|||||||
const prisma = global.prisma || new PrismaClient();
|
const prisma = global.prisma || new PrismaClient();
|
||||||
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
|
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) {
|
async function sleep(ms: number) {
|
||||||
return new Promise(resolve => setTimeout(resolve, ms));
|
return new Promise(resolve => setTimeout(resolve, ms));
|
||||||
}
|
}
|
||||||
@ -201,126 +204,60 @@ async function getWebDAVCredentials(nextcloudUrl: string, username: string, admi
|
|||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
|
if (!session?.user?.email) {
|
||||||
if (!session?.user?.email || !session?.user?.id || !session?.accessToken) {
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
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 nextcloudUrl = process.env.NEXTCLOUD_URL;
|
||||||
const adminUsername = process.env.NEXTCLOUD_ADMIN_USERNAME;
|
const webDAVUrl = `${nextcloudUrl}/remote.php/dav/files/${nextcloudUsername}/Private/`;
|
||||||
const adminPassword = process.env.NEXTCLOUD_ADMIN_PASSWORD;
|
|
||||||
|
|
||||||
if (!nextcloudUrl || !adminUsername || !adminPassword) {
|
// Check cache first
|
||||||
console.error('Missing Nextcloud configuration');
|
const cacheKey = nextcloudUsername;
|
||||||
return NextResponse.json(
|
const cachedData = folderCache.get(cacheKey);
|
||||||
{ error: 'Nextcloud configuration is missing' },
|
if (cachedData) {
|
||||||
{ status: 500 }
|
const cacheAge = Date.now() - cachedData.timestamp;
|
||||||
);
|
if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache
|
||||||
|
return NextResponse.json({ folders: cachedData.folders });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test Nextcloud connectivity
|
// Fetch folder structure
|
||||||
const testResponse = await fetch(`${nextcloudUrl}/status.php`);
|
const response = await fetch(webDAVUrl, {
|
||||||
if (!testResponse.ok) {
|
|
||||||
console.error('Nextcloud is not accessible:', await testResponse.text());
|
|
||||||
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);
|
|
||||||
|
|
||||||
// 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: {
|
headers: {
|
||||||
'Authorization': `Basic ${Buffer.from(`${nextcloudUsername}:${webdavPassword}`).toString('base64')}`,
|
'Authorization': `Basic ${Buffer.from(`${nextcloudUsername}:${process.env.NEXTCLOUD_ADMIN_PASSWORD}`).toString('base64')}`,
|
||||||
'Depth': '1',
|
'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) {
|
if (!response.ok) {
|
||||||
// Rate limited, wait and retry
|
throw new Error('Failed to fetch folder structure');
|
||||||
const retryAfter = foldersResponse.headers.get('Retry-After');
|
|
||||||
await sleep((retryAfter ? parseInt(retryAfter) : 5) * 1000);
|
|
||||||
return GET(); // Retry the entire request
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!foldersResponse.ok) {
|
const xmlData = await response.text();
|
||||||
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 parser = new DOMParser();
|
||||||
const xmlDoc = parser.parseFromString(folderData, 'text/xml');
|
const doc = parser.parseFromString(xmlData, 'text/xml');
|
||||||
const responses = Array.from(xmlDoc.getElementsByTagName('d:response'));
|
|
||||||
|
|
||||||
const folders: string[] = [];
|
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 responses = doc.getElementsByTagName('d:response');
|
||||||
const href = response.getElementsByTagName('d:href')[0]?.textContent;
|
for (let i = 0; i < responses.length; i++) {
|
||||||
if (href) {
|
const response = responses[i];
|
||||||
// Extract folder name from href
|
const displayName = response.getElementsByTagName('d:displayname')[0]?.textContent;
|
||||||
const folderName = decodeURIComponent(href.split('/').filter(Boolean).pop() || '');
|
if (displayName && displayName !== 'Private') {
|
||||||
if (folderName && folderName !== 'Private') {
|
folders.push(displayName);
|
||||||
folders.push(folderName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('Parsed folders:', folders);
|
// Update cache
|
||||||
|
folderCache.set(cacheKey, {
|
||||||
return NextResponse.json({
|
folders,
|
||||||
isConnected: true,
|
timestamp: Date.now()
|
||||||
folders
|
|
||||||
});
|
});
|
||||||
} catch (error: any) {
|
|
||||||
console.error('Error accessing Nextcloud WebDAV:', error);
|
return NextResponse.json({ folders });
|
||||||
return NextResponse.json(
|
} catch (error) {
|
||||||
{ error: "Erreur d'accès aux dossiers Nextcloud", details: error?.message || String(error) },
|
console.error('Error in Nextcloud status:', error);
|
||||||
{ status: 503 }
|
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
||||||
);
|
|
||||||
}
|
|
||||||
} 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 }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState, useRef } from "react";
|
||||||
import { useSession } from "next-auth/react";
|
import { useSession } from "next-auth/react";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import Navigation from "@/components/carnet/navigation";
|
import Navigation from "@/components/carnet/navigation";
|
||||||
@ -44,23 +44,45 @@ export default function CarnetPage() {
|
|||||||
const isSmallScreen = useMediaQuery("(max-width: 768px)");
|
const isSmallScreen = useMediaQuery("(max-width: 768px)");
|
||||||
const isMediumScreen = useMediaQuery("(max-width: 1024px)");
|
const isMediumScreen = useMediaQuery("(max-width: 1024px)");
|
||||||
|
|
||||||
|
// Cache for Nextcloud folders
|
||||||
|
const foldersCache = useRef<{ folders: string[]; timestamp: number } | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchNextcloudFolders = async () => {
|
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 {
|
try {
|
||||||
const response = await fetch('/api/nextcloud/status');
|
const response = await fetch('/api/nextcloud/status');
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Failed to fetch Nextcloud folders');
|
throw new Error('Failed to fetch Nextcloud folders');
|
||||||
}
|
}
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setNextcloudFolders(data.folders || []);
|
const folders = data.folders || [];
|
||||||
|
|
||||||
|
// Update cache
|
||||||
|
foldersCache.current = {
|
||||||
|
folders,
|
||||||
|
timestamp: Date.now()
|
||||||
|
};
|
||||||
|
|
||||||
|
setNextcloudFolders(folders);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error fetching Nextcloud folders:', err);
|
console.error('Error fetching Nextcloud folders:', err);
|
||||||
setNextcloudFolders([]);
|
setNextcloudFolders([]);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (status === "authenticated") {
|
||||||
fetchNextcloudFolders();
|
fetchNextcloudFolders();
|
||||||
}, []);
|
}
|
||||||
|
}, [status]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (status === "unauthenticated") {
|
if (status === "unauthenticated") {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user