#!/usr/bin/env node /** * tools/admin-news.js * * Gestionnaire local autonome pour l'administration et la synchronisation * des dépêches et articles de gastinel.me. * * Zéro dépendance externe (Node.js natif : http, fs, path, child_process). * Écoute strictement sur 127.0.0.1:3000. * * Usage : * node tools/admin-news.js -> Lance le serveur d'administration web sur http://127.0.0.1:3000 * node tools/admin-news.js sync -> Déclenche la synchronisation SSH/SCP immédiate sans interface */ const http = require('http'); const fs = require('fs'); const path = require('path'); const { exec, spawn } = require('child_process'); // Configuration const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000; const HOST = '127.0.0.1'; const NEWS_FILE = path.resolve(__dirname, '../data/news.json'); // Paramètres de synchronisation VPS Suisse (surchargeables via variables d'environnement) const VPS_CONFIG = { host: process.env.VPS_HOST || 'vps.gastinel.me', user: process.env.VPS_USER || 'root', port: process.env.VPS_PORT || '22', remotePath: process.env.VPS_PATH || '/usr/share/nginx/html/data/', sshKey: process.env.SSH_KEY || '' // ex: C:/Users/theog/.ssh/id_ed25519 ou ~/.ssh/id_ed25519 }; function ensureDataFile() { const dir = path.dirname(NEWS_FILE); if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); if (!fs.existsSync(NEWS_FILE)) fs.writeFileSync(NEWS_FILE, '[]', 'utf8'); } function readNews() { ensureDataFile(); try { const raw = fs.readFileSync(NEWS_FILE, 'utf8'); return JSON.parse(raw); } catch (err) { return []; } } function writeNews(items) { ensureDataFile(); fs.writeFileSync(NEWS_FILE, JSON.stringify(items, null, 2), 'utf8'); } function runSync(callback) { ensureDataFile(); // Vérifier si rsync est disponible (Linux/WSL/Git Bash), sinon utiliser scp (Windows natif) exec('rsync --version', (err) => { let cmd = ''; const keyOpt = VPS_CONFIG.sshKey ? `-i "${VPS_CONFIG.sshKey}"` : ''; if (!err) { const sshCmd = VPS_CONFIG.port !== '22' || keyOpt ? `-e "ssh -p ${VPS_CONFIG.port} ${keyOpt}"` : ''; cmd = `rsync -avz ${sshCmd} "${NEWS_FILE}" ${VPS_CONFIG.user}@${VPS_CONFIG.host}:${VPS_CONFIG.remotePath}`; } else { // Repli robuste sur SCP natif const portOpt = VPS_CONFIG.port !== '22' ? `-P ${VPS_CONFIG.port}` : ''; cmd = `scp ${keyOpt} ${portOpt} "${NEWS_FILE}" ${VPS_CONFIG.user}@${VPS_CONFIG.host}:${VPS_CONFIG.remotePath}`; } const startTime = Date.now(); exec(cmd, (execErr, stdout, stderr) => { const duration = Date.now() - startTime; if (execErr) { callback({ success: false, command: cmd, durationMs: duration, error: execErr.message, stderr: stderr || execErr.message }); } else { callback({ success: true, command: cmd, durationMs: duration, stdout: stdout || 'news.json transféré avec succès.' }); } }); }); } // Mode CLI direct : node tools/admin-news.js sync if (process.argv[2] === 'sync') { console.log(`[SYNC] Démarrage de la synchronisation vers ${VPS_CONFIG.user}@${VPS_CONFIG.host}...`); runSync((res) => { if (res.success) { console.log(`[OK] Synchronisé en ${res.durationMs}ms`); console.log(res.stdout); process.exit(0); } else { console.error(`[ERREUR] Échec de la synchronisation :`); console.error(res.error); if (res.stderr) console.error(res.stderr); console.error(`Commande exécutée : ${res.command}`); process.exit(1); } }); return; } // HTML & CSS de l'interface locale const HTML_UI = ` Admin News — gastinel.me

Dépêches & Articles — Gastinel.me

Gestionnaire local statique pour news.json
127.0.0.1:3000 (LOCAL ONLY)

Rédiger une dépêche

Articles enregistrés 0 article

Déploiement VPS Suisse (SSH / SCP / Rsync)

Cible : ${VPS_CONFIG.user}@${VPS_CONFIG.host}:${VPS_CONFIG.remotePath}

En attente d'une action...
`; // Serveur HTTP local const server = http.createServer((req, res) => { const parsedUrl = new URL(req.url, `http://${req.headers.host || HOST}`); const pathname = parsedUrl.pathname; // GET / -> Page d'administration if (req.method === 'GET' && pathname === '/') { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(HTML_UI); return; } // GET /api/news -> Flux d'articles if (req.method === 'GET' && pathname === '/api/news') { const news = readNews(); res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(news)); return; } // POST /api/news -> Ajouter un article en tête if (req.method === 'POST' && pathname === '/api/news') { let body = ''; req.on('data', chunk => { body += chunk; }); req.on('end', () => { try { const payload = JSON.parse(body); if (!payload.title || !payload.desc || !payload.link) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Champs obligatoires manquants.' })); return; } const news = readNews(); const nextId = news.reduce((max, item) => Math.max(max, item.id || 0), 0) + 1; const newEntry = { id: nextId, date: payload.date || new Date().toISOString().slice(0, 7), tag: payload.tag || 'Actualité', title: payload.title, desc: payload.desc, link: payload.link }; // Ajout automatique en tête de tableau news.unshift(newEntry); writeNews(news); res.writeHead(201, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ success: true, item: newEntry })); } catch (err) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: err.message })); } }); return; } // DELETE /api/news/:id if (req.method === 'DELETE' && pathname.startsWith('/api/news/')) { const idToDelete = parseInt(pathname.replace('/api/news/', ''), 10); const news = readNews(); const filtered = news.filter(n => n.id !== idToDelete); writeNews(filtered); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ success: true, deletedId: idToDelete })); return; } // POST /api/sync -> Synchronisation VPS if (req.method === 'POST' && pathname === '/api/sync') { runSync((result) => { res.writeHead(result.success ? 200 : 500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(result)); }); return; } res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not Found'); }); server.listen(PORT, HOST, () => { console.log('===================================================='); console.log(` Admin News gastinel.me en écoute sur :`); console.log(` http://${HOST}:${PORT}`); console.log(` Cible VPS : ${VPS_CONFIG.user}@${VPS_CONFIG.host}:${VPS_CONFIG.remotePath}`); console.log('===================================================='); });