76 lines
2.6 KiB
TypeScript
76 lines
2.6 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) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
const folder = searchParams.get('folder') || 'Notes';
|
|
|
|
// 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 });
|
|
}
|
|
|
|
console.log('Using credentials for user:', credentials.username);
|
|
console.log('Accessing folder:', folder);
|
|
|
|
// Initialize WebDAV client with proper URL construction
|
|
const baseURL = process.env.NEXTCLOUD_URL;
|
|
if (!baseURL) {
|
|
throw new Error('NEXTCLOUD_URL environment variable is not set');
|
|
}
|
|
|
|
// Ensure baseURL ends with a slash
|
|
const normalizedBaseURL = baseURL.endsWith('/') ? baseURL : `${baseURL}/`;
|
|
|
|
const client = createClient({
|
|
username: credentials.username,
|
|
password: credentials.password,
|
|
baseURL: normalizedBaseURL,
|
|
});
|
|
|
|
// Construct the folder path without leading slash
|
|
const folderPath = `remote.php/dav/files/${credentials.username}/Private/${folder}`;
|
|
console.log('Full folder path:', folderPath);
|
|
|
|
// List files in the specified folder
|
|
const files = await client.getDirectoryContents(folderPath);
|
|
console.log('Found files:', files.length);
|
|
|
|
// Filter for .md files and format the response
|
|
const markdownFiles = files
|
|
.filter((file: any) => file.basename.endsWith('.md'))
|
|
.map((file: any) => ({
|
|
id: file.filename,
|
|
title: file.basename.replace('.md', ''),
|
|
lastModified: new Date(file.lastmod).toISOString(),
|
|
size: file.size,
|
|
}));
|
|
|
|
return NextResponse.json(markdownFiles);
|
|
} catch (error) {
|
|
console.error('Error fetching files:', error);
|
|
return NextResponse.json({ error: 'Failed to fetch files' }, { status: 500 });
|
|
}
|
|
}
|