photo_server_json_con_aves22/api_v1/scanner/orphanCleanup.js
2026-04-18 20:14:42 +02:00

108 lines
2.8 KiB
JavaScript

// api_v1/scanner/orphanCleanup.js
const fsp = require('fs/promises');
const path = require('path');
module.exports = function createCleanupFunctions(db, RETENTION_DAYS = 30) {
// 1) Recupera gli ID dal DB per una cartella specifica
async function buildIdsListForFolder(userName, cartella) {
try {
const rows = await db("photos")
.select("id")
.where({ user: userName, cartella });
return rows.map(r => r.id);
} catch (err) {
console.error("Errore buildIdsListForFolder:", err);
return [];
}
}
// 2) Rimuove un ID dalla lista (invariati)
function removeIdFromList(idsIndex, id) {
return idsIndex.filter(x => x !== id);
}
// 3) Cancella thumbs dal filesystem
async function deleteThumbsById(id) {
const rec = await db('photos').where({ id }).first();
if (!rec) return false;
const thumbs = [rec.thub1, rec.thub2].filter(Boolean);
let deleted = false;
for (const t of thumbs) {
const abs = path.resolve(__dirname, '..', '..', 'public', t);
try {
await fsp.rm(abs, { force: true });
console.log(` 🔴 Thumb eliminato: ${abs}`);
deleted = true;
} catch {}
}
return deleted;
}
// 4) Soft delete + Hard delete con retention
async function deleteFromDB(id, userName) {
const now = new Date();
const nowIso = now.toISOString();
// Recupera record attuale
const rec = await db("photos").where({ id, user: userName }).first();
if (!rec) {
console.log(`⚠️ deleteFromDB: foto ${id} non trovata`);
return false;
}
// Se NON era già soft-deleted → SOFT DELETE
if (!rec.deleted_at) {
await db("photos")
.where({ id, user: userName })
.update({
deleted_at: nowIso,
updated_at: nowIso
});
console.log(`🟡 Soft delete → id=${id}`);
return true;
}
// Se ERA già soft-deleted → controlla retention
const deletedAt = new Date(rec.deleted_at);
const retentionMs = RETENTION_DAYS * 24 * 60 * 60 * 1000;
const shouldHardDelete = now - deletedAt > retentionMs;
if (!shouldHardDelete) {
console.log(`🟡 Soft delete già presente → id=${id} (in retention)`);
return true;
}
// 🔥 HARD DELETE
console.log(`🔴 HARD DELETE → id=${id}`);
// 1) Elimina thumbs
await deleteThumbsById(id);
// 2) Elimina record dal DB
await db("photos").where({ id, user: userName }).del();
// 3) Registra hard delete per progressive sync
await db("deleted_hard").insert({
id,
user: userName,
deleted_at: nowIso
});
return true;
}
return {
buildIdsListForFolder,
removeIdFromList,
deleteThumbsById,
deleteFromDB
};
};