gallery_server_client_s190js/api_v1/scanner/scanPhotoCartella.js
2026-10-26 11:00:14 +01:00

141 lines
2.9 KiB
JavaScript

// 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;