carnet api

This commit is contained in:
alma 2025-04-20 12:07:50 +02:00
parent 50d85967ca
commit 01ba7f754a
2 changed files with 129 additions and 11 deletions

View File

@ -0,0 +1,43 @@
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { getNextCloudService } from '@/lib/nextcloud-utils';
export async function GET(request: Request) {
try {
const session = await getServerSession();
if (!session?.user?.email) {
return NextResponse.json(
{ error: 'Not authenticated' },
{ status: 401 }
);
}
console.log('Test endpoint called with session:', {
email: session.user.email,
name: session.user.name
});
const service = await getNextCloudService();
// Try to initialize folders
await service.initializeUserFolders(session.user.email);
// Try to list notes
const notes = await service.listNotes(session.user.email);
return NextResponse.json({
success: true,
message: 'Test completed successfully',
notes
});
} catch (error) {
console.error('Test endpoint error:', error);
return NextResponse.json(
{
error: 'Test failed',
message: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}

View File

@ -7,6 +7,7 @@ export class NextCloudService {
private subFolders: string[] = ['Journal', 'Santé', 'Notes']; private subFolders: string[] = ['Journal', 'Santé', 'Notes'];
constructor(token: string) { constructor(token: string) {
console.log('Initializing NextCloudService with URL:', process.env.NEXTCLOUD_URL);
this.webdav = new WebDAV( this.webdav = new WebDAV(
process.env.NEXTCLOUD_URL + '/remote.php/dav/files', process.env.NEXTCLOUD_URL + '/remote.php/dav/files',
{ {
@ -18,105 +19,177 @@ export class NextCloudService {
} }
async initializeUserFolders(username: string) { async initializeUserFolders(username: string) {
console.log(`Initializing folders for user: ${username}`);
const userBasePath = `${username}${this.basePath}`; const userBasePath = `${username}${this.basePath}`;
console.log('Base path:', userBasePath);
// Create base Carnet folder // Create base Carnet folder
try { try {
console.log('Checking if base folder exists:', userBasePath);
const baseExists = await this.webdav.exists(userBasePath); const baseExists = await this.webdav.exists(userBasePath);
console.log('Base folder exists:', baseExists);
if (!baseExists) { if (!baseExists) {
console.log('Creating base folder:', userBasePath);
await this.webdav.createDirectory(userBasePath, { recursive: true }); await this.webdav.createDirectory(userBasePath, { recursive: true });
console.log('Base folder created successfully');
} }
} catch (error) { } catch (error) {
console.error('Error checking/creating base folder:', error); console.error('Error checking/creating base folder:', {
path: userBasePath,
error: error instanceof Error ? error.message : error,
fullError: error
});
throw new Error('Failed to initialize base folder'); throw new Error('Failed to initialize base folder');
} }
// Create subfolders // Create subfolders
for (const folder of this.subFolders) { for (const folder of this.subFolders) {
const folderPath = `${userBasePath}/${folder}`; const folderPath = `${userBasePath}/${folder}`;
console.log(`Processing subfolder: ${folder}`);
try { try {
console.log('Checking if subfolder exists:', folderPath);
const exists = await this.webdav.exists(folderPath); const exists = await this.webdav.exists(folderPath);
console.log(`Subfolder ${folder} exists:`, exists);
if (!exists) { if (!exists) {
console.log('Creating subfolder:', folderPath);
await this.webdav.createDirectory(folderPath, { recursive: true }); await this.webdav.createDirectory(folderPath, { recursive: true });
console.log(`Subfolder ${folder} created successfully`);
} }
} catch (error) { } catch (error) {
console.error(`Error checking/creating ${folder} folder:`, error); console.error(`Error checking/creating ${folder} folder:`, {
path: folderPath,
error: error instanceof Error ? error.message : error,
fullError: error
});
throw new Error(`Failed to initialize ${folder} folder`); throw new Error(`Failed to initialize ${folder} folder`);
} }
} }
console.log('All folders initialized successfully');
} }
async saveNote(username: string, content: string, category: string = 'Notes', date: Date = new Date()) { async saveNote(username: string, content: string, category: string = 'Notes', date: Date = new Date()) {
console.log('Saving note:', { username, category, date });
if (!this.subFolders.includes(category)) { if (!this.subFolders.includes(category)) {
console.error('Invalid category provided:', category);
throw new Error(`Invalid category: ${category}`); throw new Error(`Invalid category: ${category}`);
} }
const fileName = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}.md`; const fileName = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}.md`;
const filePath = `${username}${this.basePath}/${category}/${fileName}`; const filePath = `${username}${this.basePath}/${category}/${fileName}`;
console.log('File path for save:', filePath);
await this.initializeUserFolders(username); try {
await this.webdav.putFileContents(filePath, content, { overwrite: true }); await this.initializeUserFolders(username);
console.log('Saving file content to:', filePath);
return { fileName, category }; await this.webdav.putFileContents(filePath, content, { overwrite: true });
console.log('File saved successfully');
return { fileName, category };
} catch (error) {
console.error('Error saving note:', {
path: filePath,
error: error instanceof Error ? error.message : error,
fullError: error
});
throw error;
}
} }
async getNote(username: string, category: string, date: Date) { async getNote(username: string, category: string, date: Date) {
console.log('Getting note:', { username, category, date });
if (!this.subFolders.includes(category)) { if (!this.subFolders.includes(category)) {
console.error('Invalid category provided:', category);
throw new Error(`Invalid category: ${category}`); throw new Error(`Invalid category: ${category}`);
} }
const fileName = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}.md`; const fileName = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}.md`;
const filePath = `${username}${this.basePath}/${category}/${fileName}`; const filePath = `${username}${this.basePath}/${category}/${fileName}`;
console.log('File path for get:', filePath);
try { try {
console.log('Fetching file content from:', filePath);
const content = await this.webdav.getFileContents(filePath, { format: 'text' }); const content = await this.webdav.getFileContents(filePath, { format: 'text' });
console.log('File content fetched successfully');
return content; return content;
} catch (error) { } catch (error) {
if (error.response?.status === 404) { if (error.response?.status === 404) {
console.log('Note not found:', filePath);
return null; return null;
} }
console.error('Error getting note:', {
path: filePath,
error: error instanceof Error ? error.message : error,
fullError: error
});
throw error; throw error;
} }
} }
async listNotes(username: string, category?: string) { async listNotes(username: string, category?: string) {
await this.initializeUserFolders(username); console.log('Listing notes:', { username, category });
const userPath = `${username}${this.basePath}`;
const results = [];
try { try {
await this.initializeUserFolders(username);
const userPath = `${username}${this.basePath}`;
const results = [];
if (category) { if (category) {
if (!this.subFolders.includes(category)) { if (!this.subFolders.includes(category)) {
console.error('Invalid category provided:', category);
throw new Error(`Invalid category: ${category}`); throw new Error(`Invalid category: ${category}`);
} }
const folderPath = `${userPath}/${category}`; const folderPath = `${userPath}/${category}`;
console.log('Listing files in category folder:', folderPath);
const files = await this.webdav.getDirectoryContents(folderPath); const files = await this.webdav.getDirectoryContents(folderPath);
console.log(`Found ${files.length} files in ${category}`);
results.push(...this.processFiles(files, category)); results.push(...this.processFiles(files, category));
} else { } else {
for (const folder of this.subFolders) { for (const folder of this.subFolders) {
const folderPath = `${userPath}/${folder}`; const folderPath = `${userPath}/${folder}`;
try { try {
console.log('Listing files in folder:', folderPath);
const files = await this.webdav.getDirectoryContents(folderPath); const files = await this.webdav.getDirectoryContents(folderPath);
console.log(`Found ${files.length} files in ${folder}`);
results.push(...this.processFiles(files, folder)); results.push(...this.processFiles(files, folder));
} catch (error) { } catch (error) {
if (error.response?.status !== 404) { if (error.response?.status !== 404) {
console.error(`Error listing files in ${folder}:`, {
path: folderPath,
error: error instanceof Error ? error.message : error,
fullError: error
});
throw error; throw error;
} }
console.log(`No files found in ${folder}`);
} }
} }
} }
console.log(`Total notes found: ${results.length}`);
return results; return results;
} catch (error) { } catch (error) {
if (error.response?.status === 404) { if (error.response?.status === 404) {
console.log('No notes found');
return []; return [];
} }
console.error('Error listing notes:', {
username,
category,
error: error instanceof Error ? error.message : error,
fullError: error
});
throw error; throw error;
} }
} }
private processFiles(files: any[], category: string) { private processFiles(files: any[], category: string) {
return files const processed = files
.filter(file => file.basename.endsWith('.md')) .filter(file => file.basename.endsWith('.md'))
.map(file => ({ .map(file => ({
date: this.fileNameToDate(file.basename), date: this.fileNameToDate(file.basename),
@ -124,6 +197,8 @@ export class NextCloudService {
path: file.filename, path: file.filename,
category category
})); }));
console.log(`Processed ${processed.length} files in ${category}`);
return processed;
} }
private fileNameToDate(fileName: string): Date { private fileNameToDate(fileName: string): Date {