Neah/app/api/nextcloud/files/route.ts
2025-04-20 21:40:34 +02:00

207 lines
6.8 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;
// Helper function to create WebDAV client
const createWebDAVClient = async (userId: string) => {
const credentials = await prisma.webDAVCredentials.findUnique({
where: { userId },
});
if (!credentials) {
throw new Error('No WebDAV credentials found');
}
const baseURL = process.env.NEXTCLOUD_URL;
if (!baseURL) {
throw new Error('NEXTCLOUD_URL environment variable is not set');
}
const normalizedBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
const webdavURL = `${normalizedBaseURL}/remote.php/dav`;
return {
client: createClient(webdavURL, {
username: credentials.username,
password: credentials.password,
authType: 'password',
}),
username: credentials.username
};
};
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';
const { client, username } = await createWebDAVClient(session.user.id);
try {
const path = `/files/${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));
// Return all files for the Contacts folder
if (folder === 'Contacts') {
return NextResponse.json(files);
}
// For other folders, filter markdown files
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,
type: 'file',
mime: file.mime,
etag: file.etag
}));
return NextResponse.json(markdownFiles);
} catch (error) {
console.error('Error listing directory contents:', error);
return NextResponse.json({ error: 'Failed to list directory contents' }, { status: 500 });
}
} catch (error) {
console.error('Error fetching files:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { title, content, folder } = await request.json();
if (!title || !content || !folder) {
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
}
const { client, username } = await createWebDAVClient(session.user.id);
try {
const path = `/files/${username}/Private/${folder}/${title}.md`;
console.log('Saving note to path:', path);
await client.putFileContents(path, content);
// Get the file details after saving
const fileDetails = await client.stat(path);
return NextResponse.json({
id: fileDetails.filename,
title: fileDetails.basename.replace('.md', ''),
lastModified: new Date(fileDetails.lastmod).toISOString(),
size: fileDetails.size,
type: 'file',
mime: fileDetails.mime,
etag: fileDetails.etag
});
} catch (error) {
console.error('Error saving note:', error);
return NextResponse.json({ error: 'Failed to save note' }, { status: 500 });
}
} catch (error) {
console.error('Error in POST request:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function PUT(request: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id, title, content, folder, mime } = await request.json();
if (!id || !title || !content || !folder) {
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
}
const { client, username } = await createWebDAVClient(session.user.id);
try {
// Use the provided path directly
const path = id;
console.log('Updating file at path:', path);
// Set the correct content type based on file extension or provided mime type
const contentType = mime || (title.endsWith('.vcf') ? 'text/vcard' : 'text/markdown');
await client.putFileContents(path, content, { contentType });
// Get the updated file details
const fileDetails = await client.stat(path);
return NextResponse.json({
id: fileDetails.filename,
title: fileDetails.basename,
lastModified: new Date(fileDetails.lastmod).toISOString(),
size: fileDetails.size,
type: 'file',
mime: fileDetails.mime,
etag: fileDetails.etag
});
} catch (error) {
console.error('Error updating file:', error);
return NextResponse.json({ error: 'Failed to update file' }, { status: 500 });
}
} catch (error) {
console.error('Error in PUT request:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function DELETE(request: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id, folder } = await request.json();
if (!id || !folder) {
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
}
const { client, username } = await createWebDAVClient(session.user.id);
try {
const path = `/files/${username}/Private/${folder}/${id.split('/').pop()}`;
console.log('Deleting note at path:', path);
await client.deleteFile(path);
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error deleting note:', error);
return NextResponse.json({ error: 'Failed to delete note' }, { status: 500 });
}
} catch (error) {
console.error('Error in DELETE request:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}