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