72 lines
2.4 KiB
TypeScript
72 lines
2.4 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { PrismaClient } from '@prisma/client';
|
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
|
import { createClient } from 'webdav';
|
|
|
|
// Use a single PrismaClient instance
|
|
declare global {
|
|
var prisma: PrismaClient | undefined;
|
|
}
|
|
|
|
const prisma = global.prisma || new PrismaClient();
|
|
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
|
|
|
|
export async function GET(
|
|
request: Request,
|
|
{ params }: { params: { id: string } }
|
|
) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
// Get WebDAV credentials
|
|
const credentials = await prisma.webDAVCredentials.findUnique({
|
|
where: { userId: session.user.id },
|
|
});
|
|
|
|
if (!credentials) {
|
|
console.error('No WebDAV credentials found for user:', session.user.id);
|
|
return NextResponse.json({ error: 'No WebDAV credentials found' }, { status: 404 });
|
|
}
|
|
|
|
// Initialize WebDAV client
|
|
const baseURL = process.env.NEXTCLOUD_URL;
|
|
if (!baseURL) {
|
|
throw new Error('NEXTCLOUD_URL environment variable is not set');
|
|
}
|
|
|
|
// Remove trailing slash if present
|
|
const normalizedBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
|
|
|
|
const client = createClient(`${normalizedBaseURL}/remote.php/dav`, {
|
|
username: credentials.username,
|
|
password: credentials.password,
|
|
authType: 'password',
|
|
});
|
|
|
|
try {
|
|
// Get the file content
|
|
const content = await client.getFileContents(params.id);
|
|
const textContent = content.toString('utf-8');
|
|
|
|
return NextResponse.json({ content: textContent });
|
|
} catch (error) {
|
|
console.error('Error fetching file content:', error);
|
|
if (error instanceof Error) {
|
|
console.error('Error details:', error.message);
|
|
console.error('Error stack:', error.stack);
|
|
}
|
|
return NextResponse.json({ error: 'Failed to fetch file content' }, { status: 500 });
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching file:', error);
|
|
if (error instanceof Error) {
|
|
console.error('Error details:', error.message);
|
|
console.error('Error stack:', error.stack);
|
|
}
|
|
return NextResponse.json({ error: 'Failed to fetch file' }, { status: 500 });
|
|
}
|
|
}
|