import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import { getObjectContent } from '@/lib/s3'; export async function GET(request: Request) { try { const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const { searchParams } = new URL(request.url); const path = searchParams.get('path'); const id = searchParams.get('id'); if (!path && !id) { return NextResponse.json({ error: 'Path or ID parameter is required' }, { status: 400 }); } // Determine the key to use let key: string; if (id) { // If id is provided directly, use it as the key key = id; // Ensure the user can only access their own files if (!key.startsWith(`user-${session.user.id}/`)) { return NextResponse.json({ error: 'Unauthorized access to file' }, { status: 403 }); } } else if (path) { // If a path is provided, ensure it contains the user's ID if (!path.includes(`/files/cube-${session.user.id}/`) && !path.includes(`user-${session.user.id}/`)) { // For backward compatibility, convert NextCloud path to S3 path if (path.startsWith('/files/') || path.includes('/Private/')) { // Extract folder and filename from path const parts = path.split('/').filter(Boolean); const file = parts[parts.length - 1]; let folder = 'notes'; // Default folder // Try to determine folder from path if (path.includes('/Notes/')) folder = 'notes'; else if (path.includes('/Diary/')) folder = 'diary'; else if (path.includes('/Contacts/')) folder = 'contacts'; else if (path.includes('/Health/')) folder = 'health'; key = `user-${session.user.id}/${folder}/${file}`; } else { return NextResponse.json({ error: 'Unauthorized access to file' }, { status: 403 }); } } else { // If it already contains user ID, use the path directly key = path; } } else { return NextResponse.json({ error: 'Invalid parameters' }, { status: 400 }); } // Get the file content const content = await getObjectContent(key); if (!content) { return NextResponse.json({ error: 'File not found' }, { status: 404 }); } return NextResponse.json({ content }); } catch (error) { console.error('Error fetching file content:', error); return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); } }