Spaces:
Sleeping
Sleeping
File size: 8,240 Bytes
6980b1d |
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const database_1 = require("../db/database");
const router = express_1.default.Router();
// Configure multer for file uploads
const storage = multer_1.default.diskStorage({
destination: (req, file, cb) => {
const uploadDir = process.env.UPLOAD_DIR || './uploads';
if (!fs_1.default.existsSync(uploadDir)) {
fs_1.default.mkdirSync(uploadDir, { recursive: true });
}
cb(null, uploadDir);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path_1.default.extname(file.originalname));
}
});
const upload = (0, multer_1.default)({
storage,
limits: {
fileSize: parseInt(process.env.MAX_FILE_SIZE || '10485760') // 10MB default
},
fileFilter: (req, file, cb) => {
const allowedTypes = ['.pdf', '.docx', '.txt', '.md'];
const ext = path_1.default.extname(file.originalname).toLowerCase();
if (allowedTypes.includes(ext)) {
cb(null, true);
}
else {
cb(new Error('Invalid file type. Only PDF, DOCX, TXT, and MD files are allowed.'));
}
}
});
// Get knowledge base documents
router.get('/', async (req, res) => {
try {
const { tenantId } = req.user;
const documents = await database_1.database.query('SELECT id, name, type, source, status, size, created_at, updated_at FROM knowledge_base WHERE tenant_id = ? ORDER BY created_at DESC', [tenantId]);
res.json({ documents });
}
catch (error) {
console.error('Get knowledge base error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Upload document
router.post('/upload', upload.single('document'), async (req, res) => {
try {
const { tenantId } = req.user;
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
const { originalname, filename, size, mimetype } = req.file;
const fileType = path_1.default.extname(originalname).toLowerCase().substring(1);
// Save to database
const result = await database_1.database.run('INSERT INTO knowledge_base (tenant_id, name, type, source, status, size, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)', [
tenantId,
originalname,
fileType,
filename,
'processing',
size,
JSON.stringify({ mimetype, uploadedAt: new Date().toISOString() })
]);
// Log analytics event
await database_1.database.run('INSERT INTO analytics_events (tenant_id, event_type, event_data) VALUES (?, ?, ?)', [tenantId, 'document_uploaded', JSON.stringify({
documentId: result.lastID,
type: fileType,
size
})]);
res.status(201).json({
id: result.lastID,
name: originalname,
type: fileType,
status: 'processing',
message: 'Document uploaded successfully'
});
}
catch (error) {
console.error('Upload document error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Add website URL
router.post('/url', async (req, res) => {
try {
const { tenantId } = req.user;
const { url, name } = req.body;
if (!url) {
return res.status(400).json({ error: 'URL is required' });
}
// Basic URL validation
try {
new URL(url);
}
catch {
return res.status(400).json({ error: 'Invalid URL format' });
}
const displayName = name || new URL(url).hostname;
// Save to database
const result = await database_1.database.run('INSERT INTO knowledge_base (tenant_id, name, type, source, status, metadata) VALUES (?, ?, ?, ?, ?, ?)', [
tenantId,
displayName,
'website',
url,
'processing',
JSON.stringify({ addedAt: new Date().toISOString() })
]);
// Log analytics event
await database_1.database.run('INSERT INTO analytics_events (tenant_id, event_type, event_data) VALUES (?, ?, ?)', [tenantId, 'website_added', JSON.stringify({
documentId: result.lastID,
url
})]);
res.status(201).json({
id: result.lastID,
name: displayName,
type: 'website',
source: url,
status: 'processing',
message: 'Website added successfully'
});
}
catch (error) {
console.error('Add URL error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Delete document
router.delete('/:documentId', async (req, res) => {
try {
const { tenantId } = req.user;
const { documentId } = req.params;
// Get document info
const document = await database_1.database.get('SELECT * FROM knowledge_base WHERE id = ? AND tenant_id = ?', [documentId, tenantId]);
if (!document) {
return res.status(404).json({ error: 'Document not found' });
}
// Delete file if it's a uploaded document
if (document.type !== 'website') {
const filePath = path_1.default.join(process.env.UPLOAD_DIR || './uploads', document.source);
if (fs_1.default.existsSync(filePath)) {
fs_1.default.unlinkSync(filePath);
}
}
// Delete from database
await database_1.database.run('DELETE FROM knowledge_base WHERE id = ? AND tenant_id = ?', [documentId, tenantId]);
// Log analytics event
await database_1.database.run('INSERT INTO analytics_events (tenant_id, event_type, event_data) VALUES (?, ?, ?)', [tenantId, 'document_deleted', JSON.stringify({
documentId,
name: document.name,
type: document.type
})]);
res.json({ message: 'Document deleted successfully' });
}
catch (error) {
console.error('Delete document error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Update document status (for processing updates)
router.put('/:documentId/status', async (req, res) => {
try {
const { tenantId } = req.user;
const { documentId } = req.params;
const { status } = req.body;
if (!['processing', 'active', 'error'].includes(status)) {
return res.status(400).json({ error: 'Invalid status' });
}
await database_1.database.run('UPDATE knowledge_base SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?', [status, documentId, tenantId]);
res.json({ message: 'Document status updated successfully' });
}
catch (error) {
console.error('Update document status error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Get document by ID
router.get('/:documentId', async (req, res) => {
try {
const { tenantId } = req.user;
const { documentId } = req.params;
const document = await database_1.database.get('SELECT * FROM knowledge_base WHERE id = ? AND tenant_id = ?', [documentId, tenantId]);
if (!document) {
return res.status(404).json({ error: 'Document not found' });
}
res.json({
...document,
metadata: JSON.parse(document.metadata || '{}')
});
}
catch (error) {
console.error('Get document error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
exports.default = router;
//# sourceMappingURL=knowledge-base.js.map |