76 lines
2.2 KiB
TypeScript
76 lines
2.2 KiB
TypeScript
import { WebDAV } from 'webdav';
|
|
import { getSession } from 'next-auth/react';
|
|
|
|
export class NextCloudService {
|
|
private webdav: WebDAV;
|
|
private basePath: string = '/Personal/Carnet';
|
|
|
|
constructor(token: string) {
|
|
this.webdav = new WebDAV(
|
|
process.env.NEXTCLOUD_URL + '/remote.php/dav/files',
|
|
{
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
}
|
|
);
|
|
}
|
|
|
|
async ensureCarnetFolder(username: string) {
|
|
const userPath = `${username}${this.basePath}`;
|
|
try {
|
|
await this.webdav.exists(userPath);
|
|
} catch {
|
|
await this.webdav.createDirectory(userPath, { recursive: true });
|
|
}
|
|
}
|
|
|
|
async saveNote(username: string, content: string, date: Date = new Date()) {
|
|
const fileName = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}.md`;
|
|
const filePath = `${username}${this.basePath}/${fileName}`;
|
|
|
|
await this.ensureCarnetFolder(username);
|
|
await this.webdav.putFileContents(filePath, content, { overwrite: true });
|
|
|
|
return fileName;
|
|
}
|
|
|
|
async getNote(username: string, date: Date) {
|
|
const fileName = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}.md`;
|
|
const filePath = `${username}${this.basePath}/${fileName}`;
|
|
|
|
try {
|
|
const content = await this.webdav.getFileContents(filePath, { format: 'text' });
|
|
return content;
|
|
} catch (error) {
|
|
if (error.response?.status === 404) {
|
|
return null;
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async listNotes(username: string) {
|
|
const userPath = `${username}${this.basePath}`;
|
|
try {
|
|
const files = await this.webdav.getDirectoryContents(userPath);
|
|
return files
|
|
.filter(file => file.basename.endsWith('.md'))
|
|
.map(file => ({
|
|
date: this.fileNameToDate(file.basename),
|
|
name: file.basename,
|
|
path: file.filename
|
|
}));
|
|
} catch (error) {
|
|
if (error.response?.status === 404) {
|
|
return [];
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
private fileNameToDate(fileName: string): Date {
|
|
const [year, month, day] = fileName.split('.')[0].split('-').map(Number);
|
|
return new Date(year, month - 1, day);
|
|
}
|
|
}
|