// api_v1/scanner/scanPhoto.js const path = require('path'); const fsp = require('fs/promises'); const { log } = require('./logger'); const scanPhotoCartella = require('./scanPhotoCartella'); const postWithAuth = require('./postWithAuth'); const createCleanupFunctions = require('./orphanCleanup'); const { WEB_ROOT, SEND_PHOTOS, BASE_URL } = require('../config'); // --------------------------------------------------------- // FORMAT TIME // --------------------------------------------------------- function formatTime(ms) { const sec = Math.floor(ms / 1000); const h = String(Math.floor(sec / 3600)).padStart(2, '0'); const m = String(Math.floor((sec % 3600) / 60)).padStart(2, '0'); const s = String(sec % 60).padStart(2, '0'); return `${h}:${m}:${s}`; } // --------------------------------------------------------- // UPDATE STATUS FILE (legacy, può restare per compatibilità) // --------------------------------------------------------- async function updateStatusFile(CURRENT, TOTAL_FILES, start) { const now = Date.now(); const elapsedMs = now - start; const avg = elapsedMs / Math.max(CURRENT.value, 1); const remainingMs = (TOTAL_FILES - CURRENT.value) * avg; const status = { current: CURRENT.value, total: TOTAL_FILES, percent: Number((CURRENT.value / TOTAL_FILES * 100).toFixed(2)), eta: formatTime(remainingMs), elapsed: formatTime(elapsedMs) }; const statusPath = path.resolve(__dirname, "..", "..", "public/photos/scan_status.json"); await fsp.writeFile(statusPath, JSON.stringify(status)); } // --------------------------------------------------------- // SCAN UNA SOLA CARTELLA // --------------------------------------------------------- async function scanPhoto(dir, userName, db, CURRENT, TOTAL_FILES, start, onProgress) { const newFiles = []; const { deleteThumbsById, deleteFromDB } = createCleanupFunctions(db); const photosRoot = path.resolve(__dirname, '..', '..', WEB_ROOT, 'photos'); const userDir = path.join(photosRoot, userName, 'original'); const cartella = dir; const absCartella = path.join(userDir, cartella); log(`📁 [SCAN CARTELLA] ${cartella}`); await scanPhotoCartella( db, userName, cartella, absCartella, newFiles, updateStatusFile, // può restare, ma non è più essenziale CURRENT, TOTAL_FILES, start, deleteThumbsById, deleteFromDB, onProgress // 🔥 PASSIAMO LA CALLBACK ); // --------------------------------------------------------- // INVIO AL SERVER REMOTO // --------------------------------------------------------- if (SEND_PHOTOS && BASE_URL && newFiles.length > 0) { log(`📤 [SEND START] newFiles=${newFiles.length}`); for (const p of newFiles) { try { p.user = userName; await postWithAuth(`${BASE_URL}/photos`, p); log(`📥 [SENT TO SERVER] ${p.name}`); } catch (err) { log(`❌ [SERVER SENT ERROR] ${p.name} → ${err.message}`); } } } else { log(`⚠️ [NO SEND] newFiles=${newFiles.length}`); } return newFiles; } module.exports = scanPhoto;