105 lines
3.7 KiB
TypeScript
105 lines
3.7 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');
|
|
}
|
|
|
|
// Remove trailing slash if present
|
|
const normalizedBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
|
|
|
|
// Construct the full WebDAV URL
|
|
const webdavURL = `${normalizedBaseURL}/remote.php/dav`;
|
|
console.log('WebDAV base URL:', webdavURL);
|
|
|
|
const client = createClient(webdavURL, {
|
|
username: credentials.username,
|
|
password: credentials.password,
|
|
authType: 'password',
|
|
});
|
|
|
|
try {
|
|
// List files in the specified folder
|
|
const path = `/files/${credentials.username}/Private/${folder}`;
|
|
console.log('Fetching contents from path:', path);
|
|
|
|
const files = await client.getDirectoryContents(path);
|
|
console.log('Raw files response:', JSON.stringify(files, null, 2));
|
|
|
|
// Filter for .md files and format the response
|
|
const markdownFiles = files
|
|
.filter((file: any) => {
|
|
const isMarkdown = file.basename.endsWith('.md');
|
|
console.log(`File: ${file.basename}, isMarkdown: ${isMarkdown}`);
|
|
return isMarkdown;
|
|
})
|
|
.map((file: any) => {
|
|
const fileData = {
|
|
id: file.filename,
|
|
title: file.basename.replace('.md', ''),
|
|
lastModified: new Date(file.lastmod).toISOString(),
|
|
size: file.size,
|
|
type: 'file',
|
|
mime: file.mime,
|
|
etag: file.etag
|
|
};
|
|
console.log('Formatted file data:', JSON.stringify(fileData, null, 2));
|
|
return fileData;
|
|
});
|
|
|
|
console.log('Found markdown files:', markdownFiles.length);
|
|
console.log('Final response:', JSON.stringify(markdownFiles, null, 2));
|
|
return NextResponse.json(markdownFiles);
|
|
} catch (error) {
|
|
console.error('Error listing directory contents:', error);
|
|
if (error instanceof Error) {
|
|
console.error('Error details:', error.message);
|
|
console.error('Error stack:', error.stack);
|
|
}
|
|
return NextResponse.json({ error: 'Failed to list directory contents' }, { status: 500 });
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching files:', error);
|
|
if (error instanceof Error) {
|
|
console.error('Error details:', error.message);
|
|
console.error('Error stack:', error.stack);
|
|
}
|
|
return NextResponse.json({ error: 'Failed to fetch files' }, { status: 500 });
|
|
}
|
|
}
|