File size: 2,430 Bytes
6efa67a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import express from 'express';
import fs, { promises as fsPromises } from 'node:fs';
import path from 'node:path';
import sanitize from 'sanitize-filename';
import { CHAT_BACKUPS_PREFIX, getChatInfo } from './chats.js';
export const router = express.Router();
router.post('/chat/get', async (request, response) => {
try {
const backupModels = [];
const backupFiles = await fsPromises
.readdir(request.user.directories.backups, { withFileTypes: true })
.then(d => d .filter(d => d.isFile() && path.extname(d.name) === '.jsonl' && d.name.startsWith(CHAT_BACKUPS_PREFIX)).map(d => d.name));
for (const name of backupFiles) {
const filePath = path.join(request.user.directories.backups, name);
const info = await getChatInfo(filePath);
if (!info || !info.file_name) {
continue;
}
backupModels.push(info);
}
return response.json(backupModels);
} catch (error) {
console.error(error);
return response.sendStatus(500);
}
});
router.post('/chat/delete', async (request, response) => {
try {
const { name } = request.body;
const filePath = path.join(request.user.directories.backups, sanitize(name));
if (!path.parse(filePath).base.startsWith(CHAT_BACKUPS_PREFIX)) {
console.warn('Attempt to delete non-chat backup file:', name);
return response.sendStatus(400);
}
if (!fs.existsSync(filePath)) {
return response.sendStatus(404);
}
await fsPromises.unlink(filePath);
return response.sendStatus(200);
}
catch (error) {
console.error(error);
return response.sendStatus(500);
}
});
router.post('/chat/download', async (request, response) => {
try {
const { name } = request.body;
const filePath = path.join(request.user.directories.backups, sanitize(name));
if (!path.parse(filePath).base.startsWith(CHAT_BACKUPS_PREFIX)) {
console.warn('Attempt to download non-chat backup file:', name);
return response.sendStatus(400);
}
if (!fs.existsSync(filePath)) {
return response.sendStatus(404);
}
return response.download(filePath);
}
catch (error) {
console.error(error);
return response.sendStatus(500);
}
});
|