Fichiers
site-principal/tools/admin-news.js
T
2026-10-11 01:57:33 +02:00

612 lignes
18 KiB
JavaScript

#!/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 = `<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin News — gastinel.me</title>
<style>
:root {
--bg: #0d0e12;
--panel: #16181f;
--border: #262933;
--text: #e1e3ea;
--muted: #8b90a0;
--accent: #2563eb;
--accent-hover: #1d4ed8;
--danger: #dc2626;
--success: #10b981;
--radius: 8px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: var(--bg);
color: var(--text);
font-family: var(--font);
padding: 30px 20px;
line-height: 1.5;
}
.container {
max-width: 960px;
margin: 0 auto;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid var(--border);
padding-bottom: 18px;
margin-bottom: 28px;
}
h1 { font-size: 1.4rem; font-weight: 700; letter-spacing: -0.02em; }
.badge-local {
background: rgba(37, 99, 235, 0.15);
color: #60a5fa;
padding: 4px 10px;
border-radius: 999px;
font-size: 0.75rem;
font-weight: 600;
}
.layout {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 28px;
}
@media (max-width: 820px) {
.layout { grid-template-columns: 1fr; }
}
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 24px;
}
.card h2 {
font-size: 1.1rem;
margin-bottom: 16px;
display: flex;
justify-content: space-between;
align-items: center;
}
.form-group {
margin-bottom: 14px;
}
label {
display: block;
font-size: 0.82rem;
font-weight: 600;
color: var(--muted);
margin-bottom: 6px;
text-transform: uppercase;
letter-spacing: 0.04em;
}
input, select, textarea {
width: 100%;
background: #090a0d;
border: 1px solid var(--border);
color: var(--text);
padding: 10px 12px;
border-radius: 6px;
font-family: inherit;
font-size: 0.92rem;
transition: border-color 0.2s;
}
input:focus, select:focus, textarea:focus {
outline: none;
border-color: var(--accent);
}
textarea { min-height: 80px; resize: vertical; }
.row { display: flex; gap: 12px; }
.row .form-group { flex: 1; }
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 10px 18px;
font-size: 0.9rem;
font-weight: 600;
border-radius: 6px;
border: none;
cursor: pointer;
transition: background 0.2s, opacity 0.2s;
}
.btn-primary { background: var(--accent); color: #fff; width: 100%; }
.btn-primary:hover { background: var(--accent-hover); }
.btn-sync {
background: #1f2937;
color: #e5e7eb;
border: 1px solid #374151;
}
.btn-sync:hover { background: #374151; }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.news-list {
display: flex;
flex-direction: column;
gap: 12px;
max-height: 480px;
overflow-y: auto;
padding-right: 4px;
}
.news-item {
background: #090a0d;
border: 1px solid var(--border);
border-radius: 6px;
padding: 14px;
position: relative;
}
.item-meta {
display: flex;
justify-content: space-between;
font-size: 0.75rem;
margin-bottom: 6px;
}
.item-tag {
background: rgba(255,255,255,0.08);
padding: 2px 8px;
border-radius: 4px;
font-weight: 600;
color: #d1d5db;
}
.item-date { color: var(--muted); }
.item-title {
font-size: 0.95rem;
font-weight: 700;
margin-bottom: 4px;
}
.item-desc {
font-size: 0.85rem;
color: var(--muted);
margin-bottom: 8px;
line-height: 1.4;
}
.item-actions {
display: flex;
justify-content: space-between;
align-items: center;
}
.item-link {
font-size: 0.78rem;
color: #60a5fa;
text-decoration: none;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 75%;
}
.item-link:hover { text-decoration: underline; }
.btn-delete {
background: none;
border: none;
color: #f87171;
cursor: pointer;
font-size: 0.75rem;
padding: 2px 6px;
border-radius: 4px;
}
.btn-delete:hover { background: rgba(239, 68, 68, 0.15); }
.sync-panel {
margin-top: 24px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 20px 24px;
}
.sync-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.console {
background: #090a0d;
border: 1px solid var(--border);
border-radius: 6px;
padding: 12px;
font-family: monospace;
font-size: 0.82rem;
color: #94a3b8;
white-space: pre-wrap;
max-height: 150px;
overflow-y: auto;
}
</style>
</head>
<body>
<div class="container">
<header>
<div>
<h1>Dépêches & Articles — Gastinel.me</h1>
<span style="font-size:0.8rem; color:var(--muted)">Gestionnaire local statique pour news.json</span>
</div>
<span class="badge-local">127.0.0.1:3000 (LOCAL ONLY)</span>
</header>
<div class="layout">
<!-- Formulaire d'ajout -->
<div class="card">
<h2>Rédiger une dépêche</h2>
<form id="newsForm">
<div class="row">
<div class="form-group">
<label>Date (YYYY-MM)</label>
<input type="text" id="date" required value="${new Date().toISOString().slice(0, 7)}">
</div>
<div class="form-group">
<label>Tag / Thème</label>
<input type="text" id="tag" required placeholder="Audiovisuel, Infrastructure..." list="tagList">
<datalist id="tagList">
<option value="Audiovisuel">
<option value="Infrastructure">
<option value="Logiciel">
<option value="Expédition">
<option value="Radio / Réseau">
</datalist>
</div>
</div>
<div class="form-group">
<label>Titre de l'article</label>
<input type="text" id="title" required placeholder="Ex: Tournage 4K au crépuscule...">
</div>
<div class="form-group">
<label>Résumé court (2 à 3 lignes max)</label>
<textarea id="desc" required placeholder="Description percutante affichée sur la carte d'accueil..."></textarea>
</div>
<div class="form-group">
<label>Lien complet de l'article</label>
<input type="url" id="link" required placeholder="https://news.gastinel.me/mon-article">
</div>
<button type="submit" class="btn btn-primary" id="submitBtn">
+ Ajouter en tête de news.json
</button>
</form>
</div>
<!-- Liste des articles -->
<div class="card">
<h2>
Articles enregistrés
<span id="countBadge" style="font-size:0.8rem; color:var(--muted); font-weight:normal">0 article</span>
</h2>
<div class="news-list" id="newsList"></div>
</div>
</div>
<!-- Panneau de synchronisation VPS -->
<div class="sync-panel">
<div class="sync-header">
<div>
<h3 style="font-size:1rem; font-weight:600">Déploiement VPS Suisse (SSH / SCP / Rsync)</h3>
<p style="font-size:0.8rem; color:var(--muted)">Cible : ${VPS_CONFIG.user}@${VPS_CONFIG.host}:${VPS_CONFIG.remotePath}</p>
</div>
<button class="btn btn-sync" id="syncBtn">⚡ Synchroniser maintenant</button>
</div>
<div class="console" id="syncConsole">En attente d'une action...</div>
</div>
</div>
<script>
const form = document.getElementById('newsForm');
const newsList = document.getElementById('newsList');
const countBadge = document.getElementById('countBadge');
const syncBtn = document.getElementById('syncBtn');
const syncConsole = document.getElementById('syncConsole');
function log(msg) {
syncConsole.textContent = msg;
}
async function loadNews() {
try {
const res = await fetch('/api/news');
const items = await res.json();
countBadge.textContent = items.length + ' article' + (items.length > 1 ? 's' : '');
if (!items.length) {
newsList.innerHTML = '<div style="color:var(--muted); font-size:0.85rem; padding:20px; text-align:center">Aucun article dans news.json</div>';
return;
}
newsList.innerHTML = items.map(a => \`
<div class="news-item">
<div class="item-meta">
<span class="item-tag">\${escapeHtml(a.tag)}</span>
<span class="item-date">\${escapeHtml(a.date)} (ID: \${a.id})</span>
</div>
<div class="item-title">\${escapeHtml(a.title)}</div>
<div class="item-desc">\${escapeHtml(a.desc)}</div>
<div class="item-actions">
<a href="\${escapeHtml(a.link)}" target="_blank" class="item-link">\${escapeHtml(a.link)}</a>
<button class="btn-delete" onclick="deleteItem(\${a.id})">Supprimer</button>
</div>
</div>
\`).join('');
} catch (err) {
newsList.innerHTML = '<div style="color:var(--danger)">Erreur de chargement des articles</div>';
}
}
function escapeHtml(str) {
if (!str) return '';
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
const item = {
date: document.getElementById('date').value.trim(),
tag: document.getElementById('tag').value.trim(),
title: document.getElementById('title').value.trim(),
desc: document.getElementById('desc').value.trim(),
link: document.getElementById('link').value.trim()
};
try {
const res = await fetch('/api/news', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(item)
});
if (res.ok) {
form.reset();
document.getElementById('date').value = new Date().toISOString().slice(0, 7);
log('[SUCCÈS] Article ajouté en tête de news.json ! Pense à synchroniser.');
loadNews();
} else {
const err = await res.json();
alert('Erreur: ' + (err.error || 'Échec de l\\ajout'));
}
} catch (err) {
alert('Erreur réseau: ' + err.message);
}
});
async function deleteItem(id) {
if (!confirm('Supprimer cet article ?')) return;
try {
const res = await fetch('/api/news/' + id, { method: 'DELETE' });
if (res.ok) {
log('[INFO] Article ID ' + id + ' supprimé.');
loadNews();
}
} catch (err) {
alert('Erreur: ' + err.message);
}
}
syncBtn.addEventListener('click', async () => {
syncBtn.disabled = true;
syncBtn.textContent = 'Transfert en cours...';
log('[SYNC] Démarrage du déploiement vers le VPS suisse...');
try {
const res = await fetch('/api/sync', { method: 'POST' });
const data = await res.json();
if (data.success) {
log('[SUCCÈS] ' + data.stdout + '\\nDurée : ' + data.durationMs + ' ms\\nCommande : ' + data.command);
} else {
log('[ERREUR] Échec de synchronisation :\\n' + (data.stderr || data.error) + '\\nCommande : ' + data.command);
}
} catch (err) {
log('[ERREUR RÉSEAU] ' + err.message);
} finally {
syncBtn.disabled = false;
syncBtn.textContent = '⚡ Synchroniser maintenant';
}
});
loadNews();
</script>
</body>
</html>`;
// 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('====================================================');
});