feat: Реализован полный CRUD для админ-панели и улучшена функциональность
- Portfolio CRUD: добавление, редактирование, удаление, переключение публикации - Services CRUD: полное управление услугами с возможностью активации/деактивации - Banner system: новая модель Banner с CRUD операциями и аналитикой кликов - Telegram integration: расширенные настройки бота, обнаружение чатов, отправка сообщений - Media management: улучшенная загрузка файлов с оптимизацией изображений и превью - UI improvements: обновлённые админ-панели с rich-text редактором и drag&drop загрузкой - Database: добавлена таблица banners с полями для баннеров и аналитики
This commit is contained in:
444
routes/media.js
444
routes/media.js
@@ -280,50 +280,210 @@ router.delete('/:filename', requireAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// List uploaded images
|
||||
// List uploaded images with advanced filtering and search
|
||||
router.get('/list', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const uploadPath = path.join(__dirname, '../public/uploads');
|
||||
|
||||
// Create uploads directory if it doesn't exist
|
||||
try {
|
||||
await fs.mkdir(uploadPath, { recursive: true });
|
||||
} catch (mkdirError) {
|
||||
// Directory might already exist, continue
|
||||
}
|
||||
|
||||
const page = parseInt(req.query.page) || 1;
|
||||
const limit = parseInt(req.query.limit) || 20;
|
||||
const limit = parseInt(req.query.limit) || 24;
|
||||
const search = req.query.search?.toLowerCase() || '';
|
||||
const sortBy = req.query.sortBy || 'date'; // date, name, size
|
||||
const sortOrder = req.query.sortOrder || 'desc'; // asc, desc
|
||||
const fileType = req.query.fileType || 'all'; // all, image, video, document
|
||||
|
||||
const files = await fs.readdir(uploadPath);
|
||||
const imageFiles = files.filter(file =>
|
||||
/\.(jpg|jpeg|png|gif|webp)$/i.test(file)
|
||||
);
|
||||
let files;
|
||||
try {
|
||||
files = await fs.readdir(uploadPath);
|
||||
} catch (readdirError) {
|
||||
if (readdirError.code === 'ENOENT') {
|
||||
return res.json({
|
||||
success: true,
|
||||
images: [],
|
||||
pagination: {
|
||||
current: 1,
|
||||
total: 0,
|
||||
limit,
|
||||
totalItems: 0,
|
||||
hasNext: false,
|
||||
hasPrev: false
|
||||
},
|
||||
filters: {
|
||||
search: '',
|
||||
sortBy: 'date',
|
||||
sortOrder: 'desc',
|
||||
fileType: 'all'
|
||||
}
|
||||
});
|
||||
}
|
||||
throw readdirError;
|
||||
}
|
||||
|
||||
// Filter by file type
|
||||
let filteredFiles = files;
|
||||
if (fileType !== 'all') {
|
||||
const typePatterns = {
|
||||
image: /\.(jpg|jpeg|png|gif|webp|svg|bmp|tiff?)$/i,
|
||||
video: /\.(mp4|webm|avi|mov|mkv|wmv|flv)$/i,
|
||||
document: /\.(pdf|doc|docx|txt|rtf|odt)$/i
|
||||
};
|
||||
|
||||
const pattern = typePatterns[fileType];
|
||||
if (pattern) {
|
||||
filteredFiles = files.filter(file => pattern.test(file));
|
||||
}
|
||||
} else {
|
||||
// Only show supported media files
|
||||
filteredFiles = files.filter(file =>
|
||||
/\.(jpg|jpeg|png|gif|webp|svg|bmp|tiff?|mp4|webm|avi|mov|mkv|pdf|doc|docx)$/i.test(file)
|
||||
);
|
||||
}
|
||||
|
||||
const total = imageFiles.length;
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
const start = (page - 1) * limit;
|
||||
const end = start + limit;
|
||||
|
||||
const paginatedFiles = imageFiles.slice(start, end);
|
||||
|
||||
const imagesWithStats = await Promise.all(
|
||||
paginatedFiles.map(async (file) => {
|
||||
// Apply search filter
|
||||
if (search) {
|
||||
filteredFiles = filteredFiles.filter(file =>
|
||||
file.toLowerCase().includes(search)
|
||||
);
|
||||
}
|
||||
|
||||
// Get file stats and create file objects
|
||||
const filesWithStats = await Promise.all(
|
||||
filteredFiles.map(async (file) => {
|
||||
try {
|
||||
const filePath = path.join(uploadPath, file);
|
||||
const stats = await fs.stat(filePath);
|
||||
|
||||
return {
|
||||
filename: file,
|
||||
url: `/uploads/${file}`,
|
||||
size: stats.size,
|
||||
modified: stats.mtime,
|
||||
isImage: true
|
||||
};
|
||||
return { file, stats, filePath };
|
||||
} catch (error) {
|
||||
console.error(`Error getting stats for ${file}:`, error);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const validImages = imagesWithStats.filter(img => img !== null);
|
||||
const validFiles = filesWithStats.filter(item => item !== null);
|
||||
|
||||
// Sort files
|
||||
validFiles.sort((a, b) => {
|
||||
let aValue, bValue;
|
||||
|
||||
switch (sortBy) {
|
||||
case 'name':
|
||||
aValue = a.file.toLowerCase();
|
||||
bValue = b.file.toLowerCase();
|
||||
break;
|
||||
case 'size':
|
||||
aValue = a.stats.size;
|
||||
bValue = b.stats.size;
|
||||
break;
|
||||
case 'date':
|
||||
default:
|
||||
aValue = a.stats.mtime;
|
||||
bValue = b.stats.mtime;
|
||||
break;
|
||||
}
|
||||
|
||||
if (sortOrder === 'asc') {
|
||||
return aValue > bValue ? 1 : -1;
|
||||
} else {
|
||||
return aValue < bValue ? 1 : -1;
|
||||
}
|
||||
});
|
||||
|
||||
const total = validFiles.length;
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
const start = (page - 1) * limit;
|
||||
const end = start + limit;
|
||||
|
||||
const paginatedFiles = validFiles.slice(start, end);
|
||||
|
||||
const filesWithDetails = await Promise.all(
|
||||
paginatedFiles.map(async ({ file, stats, filePath }) => {
|
||||
try {
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
let fileDetails = {
|
||||
filename: file,
|
||||
url: `/uploads/${file}`,
|
||||
size: stats.size,
|
||||
uploadedAt: stats.birthtime || stats.mtime,
|
||||
modifiedAt: stats.mtime,
|
||||
extension: ext,
|
||||
isImage: false,
|
||||
isVideo: false,
|
||||
isDocument: false
|
||||
};
|
||||
|
||||
// Determine file type and get additional info
|
||||
if (/\.(jpg|jpeg|png|gif|webp|svg|bmp|tiff?)$/i.test(file)) {
|
||||
fileDetails.isImage = true;
|
||||
fileDetails.mimetype = `image/${ext.replace('.', '')}`;
|
||||
|
||||
// Get image dimensions
|
||||
try {
|
||||
const metadata = await sharp(filePath).metadata();
|
||||
fileDetails.dimensions = {
|
||||
width: metadata.width,
|
||||
height: metadata.height
|
||||
};
|
||||
fileDetails.format = metadata.format;
|
||||
} catch (sharpError) {
|
||||
console.warn(`Could not get image metadata for ${file}`);
|
||||
}
|
||||
} else if (/\.(mp4|webm|avi|mov|mkv|wmv|flv)$/i.test(file)) {
|
||||
fileDetails.isVideo = true;
|
||||
fileDetails.mimetype = `video/${ext.replace('.', '')}`;
|
||||
} else if (/\.(pdf|doc|docx|txt|rtf|odt)$/i.test(file)) {
|
||||
fileDetails.isDocument = true;
|
||||
fileDetails.mimetype = `application/${ext.replace('.', '')}`;
|
||||
}
|
||||
|
||||
// Generate thumbnail for images
|
||||
if (fileDetails.isImage && !file.includes('-thumbnail.')) {
|
||||
const thumbnailPath = path.join(uploadPath, `${path.parse(file).name}-thumbnail.webp`);
|
||||
try {
|
||||
await fs.access(thumbnailPath);
|
||||
fileDetails.thumbnail = `/uploads/${path.basename(thumbnailPath)}`;
|
||||
} catch {
|
||||
// Thumbnail doesn't exist, create it
|
||||
try {
|
||||
await sharp(filePath)
|
||||
.resize(200, 150, {
|
||||
fit: 'cover',
|
||||
withoutEnlargement: false
|
||||
})
|
||||
.webp({ quality: 80 })
|
||||
.toFile(thumbnailPath);
|
||||
fileDetails.thumbnail = `/uploads/${path.basename(thumbnailPath)}`;
|
||||
} catch (thumbError) {
|
||||
console.warn(`Could not create thumbnail for ${file}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fileDetails;
|
||||
} catch (error) {
|
||||
console.error(`Error getting details for ${file}:`, error);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const validMedia = filesWithDetails.filter(item => item !== null);
|
||||
|
||||
// Calculate storage stats
|
||||
const totalSize = validFiles.reduce((sum, file) => sum + file.stats.size, 0);
|
||||
const imageCount = validMedia.filter(f => f.isImage).length;
|
||||
const videoCount = validMedia.filter(f => f.isVideo).length;
|
||||
const documentCount = validMedia.filter(f => f.isDocument).length;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
images: validImages,
|
||||
files: validMedia,
|
||||
pagination: {
|
||||
current: page,
|
||||
total: totalPages,
|
||||
@@ -331,15 +491,243 @@ router.get('/list', requireAuth, async (req, res) => {
|
||||
totalItems: total,
|
||||
hasNext: page < totalPages,
|
||||
hasPrev: page > 1
|
||||
},
|
||||
filters: {
|
||||
search,
|
||||
sortBy,
|
||||
sortOrder,
|
||||
fileType
|
||||
},
|
||||
stats: {
|
||||
totalFiles: total,
|
||||
totalSize,
|
||||
imageCount,
|
||||
videoCount,
|
||||
documentCount,
|
||||
formattedSize: formatFileSize(totalSize)
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('List images error:', error);
|
||||
console.error('List media error:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error listing images'
|
||||
message: 'Error listing media files'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Create folder structure
|
||||
router.post('/folder', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const { folderName } = req.body;
|
||||
|
||||
if (!folderName || !folderName.trim()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Folder name is required'
|
||||
});
|
||||
}
|
||||
|
||||
// Sanitize folder name
|
||||
const sanitizedName = folderName.trim().replace(/[^a-zA-Z0-9-_]/g, '-');
|
||||
const folderPath = path.join(__dirname, '../public/uploads', sanitizedName);
|
||||
|
||||
try {
|
||||
await fs.mkdir(folderPath, { recursive: true });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Folder created successfully',
|
||||
folderName: sanitizedName,
|
||||
folderPath: `/uploads/${sanitizedName}`
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.code === 'EEXIST') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Folder already exists'
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Create folder error:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error creating folder'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Get media file info
|
||||
router.get('/info/:filename', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const filename = req.params.filename;
|
||||
|
||||
// Security check
|
||||
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Invalid filename'
|
||||
});
|
||||
}
|
||||
|
||||
const filePath = path.join(__dirname, '../public/uploads', filename);
|
||||
|
||||
try {
|
||||
const stats = await fs.stat(filePath);
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
|
||||
let fileInfo = {
|
||||
filename,
|
||||
url: `/uploads/${filename}`,
|
||||
size: stats.size,
|
||||
formattedSize: formatFileSize(stats.size),
|
||||
uploadedAt: stats.birthtime || stats.mtime,
|
||||
modifiedAt: stats.mtime,
|
||||
extension: ext,
|
||||
mimetype: getMimeType(ext)
|
||||
};
|
||||
|
||||
// Get additional info for images
|
||||
if (/\.(jpg|jpeg|png|gif|webp|svg|bmp|tiff?)$/i.test(filename)) {
|
||||
try {
|
||||
const metadata = await sharp(filePath).metadata();
|
||||
fileInfo.dimensions = {
|
||||
width: metadata.width,
|
||||
height: metadata.height
|
||||
};
|
||||
fileInfo.format = metadata.format;
|
||||
fileInfo.hasAlpha = metadata.hasAlpha;
|
||||
fileInfo.density = metadata.density;
|
||||
} catch (sharpError) {
|
||||
console.warn(`Could not get image metadata for ${filename}`);
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
fileInfo
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'File not found'
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Get file info error:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error getting file information'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Resize image
|
||||
router.post('/resize/:filename', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const filename = req.params.filename;
|
||||
const { width, height, quality = 85 } = req.body;
|
||||
|
||||
if (!width && !height) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Width or height must be specified'
|
||||
});
|
||||
}
|
||||
|
||||
// Security check
|
||||
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Invalid filename'
|
||||
});
|
||||
}
|
||||
|
||||
const originalPath = path.join(__dirname, '../public/uploads', filename);
|
||||
const nameWithoutExt = path.parse(filename).name;
|
||||
const resizedPath = path.join(
|
||||
path.dirname(originalPath),
|
||||
`${nameWithoutExt}-${width || 'auto'}x${height || 'auto'}.webp`
|
||||
);
|
||||
|
||||
try {
|
||||
let sharpInstance = sharp(originalPath);
|
||||
|
||||
if (width && height) {
|
||||
sharpInstance = sharpInstance.resize(parseInt(width), parseInt(height), {
|
||||
fit: 'cover'
|
||||
});
|
||||
} else if (width) {
|
||||
sharpInstance = sharpInstance.resize(parseInt(width));
|
||||
} else {
|
||||
sharpInstance = sharpInstance.resize(null, parseInt(height));
|
||||
}
|
||||
|
||||
await sharpInstance
|
||||
.webp({ quality: parseInt(quality) })
|
||||
.toFile(resizedPath);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Image resized successfully',
|
||||
originalFile: filename,
|
||||
resizedFile: path.basename(resizedPath),
|
||||
resizedUrl: `/uploads/${path.basename(resizedPath)}`
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Original file not found'
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Resize image error:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error resizing image'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Utility functions
|
||||
function formatFileSize(bytes) {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
const k = 1024;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
function getMimeType(ext) {
|
||||
const mimeTypes = {
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.png': 'image/png',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.bmp': 'image/bmp',
|
||||
'.tiff': 'image/tiff',
|
||||
'.tif': 'image/tiff',
|
||||
'.mp4': 'video/mp4',
|
||||
'.webm': 'video/webm',
|
||||
'.avi': 'video/x-msvideo',
|
||||
'.mov': 'video/quicktime',
|
||||
'.mkv': 'video/x-matroska',
|
||||
'.pdf': 'application/pdf',
|
||||
'.doc': 'application/msword',
|
||||
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
||||
};
|
||||
|
||||
return mimeTypes[ext.toLowerCase()] || 'application/octet-stream';
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user