Script pour afficher les NEWS AFP sur AWTRIX

// Configuration Awtrix mettre votre adresse IP AWTRIX CI-APRES
const AWTRIX_IP = '192.168.XX.XX';
const CUSTOM_APP_NAME = 'afpflash';

// Flux Google News "AFP France"
const RSS_URL = 'https://news.google.com/rss/search?q=AFP%20France&hl=fr&gl=FR&ceid=FR:fr';
// Regex tolérante pour extraire le titre du premier item
const RSS_REGEX = /<item>[\s\S]*?<title>(?:<!\[CDATA\[)?\s*([^<\]]+?)\s*(?:\]\]>)?<\/title>/i;

// Génère une couleur hexadécimale aléatoire
function getRandomColor() {
  return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0');
}

async function getDerniereDepêche() {
  try {
    log('🔍 Récupération du flux RSS AFP...');
    const res = await fetch(RSS_URL);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const xml = await res.text();
    const match = xml.match(RSS_REGEX);
    if (match && match[1]) {
      const titre = match[1].trim();
      log(`✅ Dépêche extraite: ${titre}`);
      return titre;
    }
    throw new Error('Aucun titre trouvé');
  } catch (err) {
    log('❌ Échec récupération dépêche:', err.message);
    return null;
  }
}

async function clearAwtrix() {
  try {
    log('🗑️ Effacement ancienne custom app...');
    await fetch(`http://${AWTRIX_IP}/api/custom?name=${CUSTOM_APP_NAME}`, { method: 'DELETE' });
    log('✅ Ancienne app effacée');
  } catch (e) {
    log('⚠️ Erreur effacement Awtrix:', e.message);
  }
}

async function sendToAwtrix(message) {
  const isNoNews = !message;
  const display = isNoNews ? 'No news' : message;
  const payload = {
    text: display,
    color: getRandomColor(),   // Couleur aléatoire à chaque envoi
    background: '#000000',     // Fond noir
    duration: 15,
    repeat: 1,
    hold: false,
    textCase: 2,               // Respecte la casse telle qu'envoyée
    scrollSpeed: 150
  };
  await clearAwtrix();
  try {
    log('📤 Envoi vers Awtrix:', JSON.stringify(payload));
    const r = await fetch(`http://${AWTRIX_IP}/api/custom?name=${CUSTOM_APP_NAME}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });
    if (r.ok) log('✅ Message affiché');
    else log(`❌ Erreur Awtrix: HTTP ${r.status}`);
  } catch (e) {
    log('❌ Erreur comm Awtrix:', e.message);
  }
}

async function main() {
  log('🚀 Début script dépêche AFP');
  const depêche = await getDerniereDepêche();
  if (!depêche) {
    log('ℹ️ Pas de dépêche, affichage "No news"');
    await sendToAwtrix(null);
  } else {
    await sendToAwtrix(depêche);
  }
  log('✅ Terminé');
}

main();

1 Like