// api_v1/scanner/scanPhotoCartella.js const scanCartella = require('./scanCartella'); const scanPhotoSingle = require('./scanPhotoSingle'); const { log } = require('./logger'); async function scanPhotoCartella( db, user, cartella, absCartella, newFiles, updateStatusFile, CURRENT, TOTAL_FILES, start, deleteThumbsById, deleteFromDB, onProgress ) { log(`๐Ÿ“ Scan cartella: ${cartella}`); let lastProgress = 0; // --------------------------------------------------------- // CARICA TUTTI I RECORD DELLA CARTELLA UNA SOLA VOLTA // --------------------------------------------------------- const rows = await db('photos') .where({ user, cartella }) .select( 'id', 'size_bytes', 'mtimeMs', 'fast_hash', 'path' ); // Map: id -> record DB const photosMap = new Map( rows.map(row => [row.id, row]) ); // Manteniamo il Set per individuare gli orfani const idsSet = new Set( rows.map(row => row.id) ); log( `๐Ÿ“Š DB cartella=${cartella}: ${rows.length} record` ); // --------------------------------------------------------- // SCANSIONE FILESYSTEM // --------------------------------------------------------- for await ( const f of scanCartella( user, cartella, absCartella, db ) ) { // Aggiorna contatore CURRENT.value++; // --------------------------------------------------------- // PROGRESS THROTTLED // // Evita una scrittura su disco per ogni singolo file. // Aggiorniamo al massimo ogni 500 ms. // --------------------------------------------------------- const now = Date.now(); if (now - lastProgress >= 500) { lastProgress = now; if (updateStatusFile) { await updateStatusFile( CURRENT, TOTAL_FILES, start ); } if (onProgress) { await onProgress(); } } // Recupera il record DB dalla Map const prev = photosMap.get(f.id) || null; // Processa il file await scanPhotoSingle( db, user, cartella, f, newFiles, '', prev ); // Il file esiste realmente nel filesystem: // quindi non รจ un orfano. idsSet.delete(f.id); } // --------------------------------------------------------- // ULTIMO AGGIORNAMENTO PROGRESS // --------------------------------------------------------- if (updateStatusFile) { await updateStatusFile( CURRENT, TOTAL_FILES, start ); } if (onProgress) { await onProgress(); } // --------------------------------------------------------- // GESTIONE ORFANI // --------------------------------------------------------- for (const orphanId of idsSet) { log(`๐Ÿ”ด Orfano: ${orphanId}`); await deleteThumbsById(orphanId); await deleteFromDB(orphanId, user); } } module.exports = scanPhotoCartella;