photo_server_json_flutter_c.../routes/photos.js

199 lines
5.7 KiB
JavaScript

// routes/photos.js
const express = require('express');
const router = express.Router();
const db = require('../db/knex');
const wss = require('../ws-server');
// -----------------------------------------------------
// Normalizzazione record DB → formato identico al vecchio index.json
// -----------------------------------------------------
function normalizePhoto(p) {
return {
...p,
gps: (p.lat != null && p.lon != null)
? {
lat: p.lat,
lng: p.lon,
alt: p.alt ?? null
}
: null,
location: p.location ? JSON.parse(p.location) : null,
_indexHash: p._indexHash || null,
lat: undefined,
lon: undefined,
alt: undefined,
location_json: undefined
};
}
// -----------------------------------------------------
// POST /photos → salva una foto inviata dallo scanner locale
// -----------------------------------------------------
router.post('/', async (req, res) => {
console.log("📥 [POST /photos] Richiesta ricevuta");
console.log("📥 Body:", req.body);
try {
const p = req.body;
console.log(`📸 [DB INSERT] Salvo foto id=${p.id} user=${p.user}`);
await db('photos').insert({
id: p.id,
user: p.user,
cartella: p.cartella,
name: p.name,
path: p.path,
thub1: p.thub1,
thub2: p.thub2,
mime_type: p.mime_type,
width: p.width,
height: p.height,
rotation: p.rotation,
size_bytes: p.size_bytes,
mtimeMs: p.mtimeMs,
duration_ms: p.duration_ms,
taken_at: p.taken_at,
data: p.data,
lat: p.gps?.lat ?? null,
lon: p.gps?.lng ?? null,
alt: p.gps?.alt ?? null,
location: p.location ? JSON.stringify(p.location) : null,
_indexHash: p._indexHash,
fast_hash: p.fast_hash
});
console.log(`🟢 [DB CHANGE] Inserisco evento ADDED per id=${p.id}`);
await db('photo_changes').insert({
photo_id: p.id,
user: p.user,
change_type: 'added',
timestamp: new Date().toISOString()
});
console.log(`📡 [WS] Invio evento real-time a user=${p.user}`);
wss.broadcastToUser(p.user, {
type: "added",
photo_id: p.id
});
console.log(`✅ [POST /photos] Foto id=${p.id} salvata con successo`);
res.json({ ok: true });
} catch (err) {
console.error("❌ Errore POST /photos:", err);
res.status(500).json({ error: err.message });
}
});
// -----------------------------------------------------
// GET /photos → Admin vede tutto, altri vedono solo loro + Common
// -----------------------------------------------------
router.get('/', async (req, res) => {
const user = req.query.user || req.user?.name;
console.log("📤 [GET /photos] Richiesta ricevuta user=", user);
try {
let rows;
if (user === "Admin") {
console.log("👑 Admin → restituisco TUTTE le foto");
rows = await db('photos')
.select('*')
.orderBy('mtimeMs', 'desc');
} else {
console.log(`👤 Utente normale → foto di ${user} + Common`);
rows = await db('photos')
.whereIn('user', [user, "Common"])
.orderBy('mtimeMs', 'desc');
}
console.log(`📤 [GET /photos] Restituisco ${rows.length} foto`);
res.json(rows.map(normalizePhoto));
} catch (err) {
console.error("❌ Errore GET /photos:", err);
res.status(500).json({ error: err.message });
}
});
// -----------------------------------------------------
// GET /photos/changes → Admin vede tutto
// -----------------------------------------------------
router.get('/changes', async (req, res) => {
const since = req.query.since;
const users = Array.isArray(req.query.user) ? req.query.user : [req.query.user];
console.log(`📤 [GET /photos/changes] since=${since} users=${users}`);
if (!since || !users.length) {
return res.status(400).json({ error: "Parametri richiesti: since, user" });
}
try {
let rows;
if (users.includes("Admin")) {
console.log("👑 Admin → restituisco TUTTI i cambiamenti");
rows = await db('photo_changes')
.where('timestamp', '>', since)
.orderBy('timestamp', 'asc');
} else {
console.log("👤 Utente normale → cambiamenti filtrati");
rows = await db('photo_changes')
.where('timestamp', '>', since)
.whereIn('user', users)
.orderBy('timestamp', 'asc');
}
console.log(`📤 [GET /photos/changes] Restituisco ${rows.length} cambiamenti`);
res.json({ changes: rows });
} catch (err) {
console.error("❌ Errore /photos/changes:", err);
res.status(500).json({ error: err.message });
}
});
// -----------------------------------------------------
// GET /photos/byIds → Admin vede tutto
// -----------------------------------------------------
router.get('/byIds', async (req, res) => {
const ids = req.query.id;
const users = Array.isArray(req.query.user) ? req.query.user : [req.query.user];
console.log("📤 [GET /photos/byIds] ids:", ids);
console.log("📤 [GET /photos/byIds] users:", users);
if (!ids) return res.json([]);
const list = Array.isArray(ids) ? ids : [ids];
try {
let rows;
if (users.includes("Admin")) {
console.log("👑 Admin → byIds senza filtro user");
rows = await db('photos')
.whereIn('id', list);
} else {
console.log("👤 Utente normale → byIds filtrato");
rows = await db('photos')
.whereIn('id', list)
.whereIn('user', users);
}
console.log(`📤 [GET /photos/byIds] trovate ${rows.length} foto`);
res.json(rows.map(normalizePhoto));
} catch (err) {
console.error("❌ Errore /photos/byIds:", err);
res.status(500).json({ error: err.message });
}
});
module.exports = router;