Ajout de la gestion des images avec scan, suppression et mise à jour des mesures dans la base de données

This commit is contained in:
2025-02-11 17:51:24 +01:00
parent 5119ee488a
commit 83dd43e0c2
4 changed files with 224 additions and 24 deletions

42
src/data/filewatcher.js Normal file
View File

@@ -0,0 +1,42 @@
import db from '../../db.js';
import path from 'path';
import storageManager from '../data/storageManager.js';
import fs from 'fs';
async function checkAndRemoveInvalidEntries() {
console.log('Checking for invalid entries...');
try {
const measurementsRes = await db.query('SELECT id, path FROM measurements');
console.log('Fetched measurements:', measurementsRes.rows);
for (const row of measurementsRes.rows) {
console.log('Checking file path:', row.path);
if (!fs.existsSync(row.path)) {
// Remove invalid entry
await db.query('DELETE FROM measurements WHERE id = $1', [row.id]);
console.log(`Deleted invalid measurement entry with id: ${row.id}`);
}
}
// Scan all images in storage
const allImages = await storageManager.scanAllImages();
console.log('Scanned all images:', allImages);
for (const imagePath of allImages) {
const entryRes = await db.query('SELECT id FROM measurements WHERE path = $1', [imagePath]);
if (entryRes.rows.length === 0) {
// Remove the file if the entry does not exist
fs.unlinkSync(imagePath);
console.log(`Deleted file at path: ${imagePath} as its database entry does not exist`);
}
}
} catch (err) {
console.error('Error checking and removing invalid entries:', err);
}
}
// Run the check periodically
setInterval(checkAndRemoveInvalidEntries, 10000); // Every second
// Initial run
checkAndRemoveInvalidEntries();

View File

@@ -19,6 +19,27 @@ function deleteFolder(name){
}
}
function scanAllImages(dir = 'storage') {
const projectDir = path.join(PROJECTS_DIR, dir);
let results = [];
function scanDirectory(directory) {
const files = fs.readdirSync(directory);
files.forEach(file => {
const filePath = path.join(directory, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
scanDirectory(filePath);
} else if (file.endsWith('.jpg')) {
results.push(filePath);
}
});
}
scanDirectory(projectDir);
return results;
}
function saveFile(filePath, content) {
// Ensure content is a buffer
if (Buffer.isBuffer(content)) {
@@ -28,16 +49,23 @@ function saveFile(filePath, content) {
}
}
function getFile(name){
const filePath = path.join(PROJECTS_DIR, `${name}`);
return fs
.readFileSync(filePath);
}
function deleteFile(name){
const filePath = path.join(PROJECTS_DIR, `${name}`);
if (fs.existsSync(filePath))
fs.rmSync(filePath);
}
module.exports = {
createFolder,
deleteFolder,
scanAllImages,
saveFile,
getFile
getFile,
deleteFile
};