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, // ⭐ Timestamp necessari per progressive sync created_at: new Date().toISOString(), updated_at: new Date().toISOString() }); // WS realtime (solo UI) wss.broadcastToUser(p.user, { type: "added", 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/changes → progressive sync (ADD + UPDATE) // ----------------------------------------------------- // ⭐ Deve stare PRIMA di /:id router.get('/changes', async (req, res) => { const user = req.user.name; const since = req.query.since; if (!since) { return res.status(400).json({ error: "Missing ?since=timestamp" }); } try { let rows; if (user === "Admin") { rows = await db("photos") .where(builder => { builder.where("created_at", ">", since) .orWhere("updated_at", ">", since); }) .orderBy("updated_at", "desc"); } else { rows = await db("photos") .whereIn("user", [user, "Common"]) .andWhere(builder => { builder.where("created_at", ">", since) .orWhere("updated_at", ">", since); }) .orderBy("updated_at", "desc"); } res.json(rows.map(normalizePhoto)); } catch (err) { console.error("❌ Errore GET /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")) { rows = await db('photos') .whereIn('id', list); } else { 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 }); } }); // ----------------------------------------------------- // GET /photos → Admin vede tutto, altri vedono solo loro + Common // ----------------------------------------------------- router.get('/', async (req, res) => { const loggedUser = req.user?.name; console.log("📤 [GET /photos] Richiesta ricevuta da:", loggedUser); try { let rows; if (loggedUser === "Admin") { rows = await db('photos') .select('*') .orderBy('mtimeMs', 'desc'); } else { rows = await db('photos') .whereIn('user', [loggedUser, "Common"]) .orderBy('mtimeMs', 'desc'); } res.json(rows.map(normalizePhoto)); } catch (err) { console.error("❌ Errore GET /photos:", err); res.status(500).json({ error: err.message }); } }); // ----------------------------------------------------- // GET /photos/:id → restituisce una singola foto // ----------------------------------------------------- router.get('/:id', async (req, res) => { const id = req.params.id; const loggedUser = req.user?.name; console.log(`📤 [GET /photos/${id}] Richiesta ricevuta da:`, loggedUser); try { let rows; if (loggedUser === "Admin") { rows = await db('photos').where({ id }); } else { rows = await db('photos') .where({ id }) .whereIn('user', [loggedUser, "Common"]); } if (!rows.length) { return res.json([]); } res.json(rows.map(normalizePhoto)); } catch (err) { console.error("❌ Errore GET /photos/:id:", err); res.status(500).json({ error: err.message }); } }); module.exports = router;