NeahNew/app/api/storage/status/route.ts
2025-05-04 13:45:45 +02:00

100 lines
3.1 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { S3Client, ListBucketsCommand } from '@aws-sdk/client-s3';
import { createUserFolderStructure, listUserObjects } from '@/lib/s3';
// Cache for folder lists
const folderCache = new Map<string, { folders: string[], timestamp: number }>();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
export async function GET() {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userId = session.user.id;
// Check if we have cached folders for this user
const cachedData = folderCache.get(userId);
if (cachedData && (Date.now() - cachedData.timestamp < CACHE_TTL)) {
return NextResponse.json({
status: 'ready',
folders: cachedData.folders
});
}
// Check S3 connectivity
const s3Client = new S3Client({
region: process.env.MINIO_AWS_REGION || 'eu-east-1',
endpoint: process.env.MINIO_S3_UPLOAD_BUCKET_URL || 'https://dome-api.slm-lab.net/',
forcePathStyle: true
});
try {
// Simple check by listing buckets
await s3Client.send(new ListBucketsCommand({}));
} catch (error) {
console.error('S3 connectivity check failed:', error);
return NextResponse.json({
error: 'S3 storage service is not accessible',
status: 'error'
}, { status: 503 });
}
// List the user's base folders
try {
// Standard folder list for the user
const standardFolders = ['notes', 'diary', 'health', 'contacts'];
let userFolders: string[] = [];
// Try to list existing folders
for (const folder of standardFolders) {
try {
const files = await listUserObjects(userId, folder);
if (files.length > 0 || folder === 'notes') {
userFolders.push(folder);
}
} catch (error) {
console.error(`Error checking folder ${folder}:`, error);
}
}
// If no folders found, create the standard structure
if (userFolders.length === 0) {
await createUserFolderStructure(userId);
userFolders = standardFolders;
}
// Convert to Pascal case for backwards compatibility with NextCloud
const formattedFolders = userFolders.map(folder =>
folder.charAt(0).toUpperCase() + folder.slice(1)
);
// Update cache
folderCache.set(userId, {
folders: formattedFolders,
timestamp: Date.now()
});
return NextResponse.json({
status: 'ready',
folders: formattedFolders
});
} catch (error) {
console.error('Error fetching user folders:', error);
return NextResponse.json({
error: 'Failed to fetch folders',
status: 'error'
}, { status: 500 });
}
} catch (error) {
console.error('Error in storage status check:', error);
return NextResponse.json({
error: 'Internal server error',
status: 'error'
}, { status: 500 });
}
}