File size: 1,455 Bytes
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const fs = require('fs');
const path = require('path');

const getNextImageNumber = () => {
  const uploadDir = path.join(__dirname, '../../frontend/public/images/products');
  
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
    return 43;
  }
  
  const files = fs.readdirSync(uploadDir);
  const numbers = files
    .filter(file => /^\d+\.(jpg|jpeg|png|webp|gif)$/i.test(file))
    .map(file => parseInt(file.split('.')[0]))
    .filter(num => !isNaN(num));
  
  return numbers.length > 0 ? Math.max(...numbers) + 1 : 43;
};

const isValidImageFile = (filename) => {
  const validExtensions = ['.jpg', '.jpeg', '.png', '.webp', '.gif'];
  const ext = path.extname(filename).toLowerCase();
  return validExtensions.includes(ext);
};

const cleanupOldFiles = (daysOld = 30) => {
  const uploadDir = path.join(__dirname, '../../frontend/public/images/products');
  
  if (!fs.existsSync(uploadDir)) {
    return;
  }
  
  const files = fs.readdirSync(uploadDir);
  const now = Date.now();
  const cutoff = now - (daysOld * 24 * 60 * 60 * 1000);
  
  files.forEach(file => {
    const filePath = path.join(uploadDir, file);
    const stats = fs.statSync(filePath);
    
    if (stats.mtime.getTime() < cutoff && file.startsWith('temp-')) {
      fs.unlinkSync(filePath);
      console.log(`Cleaned up old file: ${file}`);
    }
  });
};

module.exports = {
  getNextImageNumber,
  isValidImageFile,
  cleanupOldFiles
};