175 lines
6.1 KiB
Text
175 lines
6.1 KiB
Text
from flask import Flask, render_template, request, redirect
|
|
from apscheduler.schedulers.background import BackgroundScheduler
|
|
from datetime import datetime
|
|
import feedparser
|
|
import hashlib
|
|
import re
|
|
import mysql.connector
|
|
|
|
app = Flask(__name__)
|
|
|
|
DB_CONFIG = {
|
|
'host': 'localhost',
|
|
'user': 'x',
|
|
'password': 'x',
|
|
'database': 'noticiasrss'
|
|
}
|
|
|
|
@app.route('/')
|
|
def index():
|
|
conn = None
|
|
try:
|
|
conn = mysql.connector.connect(**DB_CONFIG)
|
|
cursor = conn.cursor()
|
|
cursor.execute("SELECT id, nombre, url, categoria_id, activo FROM feeds")
|
|
feeds = cursor.fetchall()
|
|
cursor.execute("SELECT id, nombre FROM categorias_estandar ORDER BY nombre")
|
|
categorias = cursor.fetchall()
|
|
except mysql.connector.Error as db_err:
|
|
app.logger.error(f"[DB ERROR] Al leer feeds o categorías: {db_err}", exc_info=True)
|
|
feeds = []
|
|
categorias = []
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
return render_template("index.html", feeds=feeds, categorias=categorias)
|
|
|
|
@app.route('/add', methods=['POST'])
|
|
def add_feed():
|
|
nombre = request.form.get('nombre')
|
|
url = request.form.get('url')
|
|
categoria_id = request.form.get('categoria_id')
|
|
try:
|
|
conn = mysql.connector.connect(**DB_CONFIG)
|
|
cursor = conn.cursor()
|
|
cursor.execute(
|
|
"INSERT INTO feeds (nombre, url, categoria_id) VALUES (%s, %s, %s)",
|
|
(nombre, url, categoria_id)
|
|
)
|
|
conn.commit()
|
|
except mysql.connector.Error as db_err:
|
|
app.logger.error(f"[DB ERROR] Al agregar feed: {db_err}", exc_info=True)
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
return redirect('/')
|
|
|
|
@app.route('/noticias')
|
|
def show_noticias():
|
|
conn = None
|
|
noticias = []
|
|
categorias = []
|
|
cat_id = request.args.get('categoria_id')
|
|
try:
|
|
conn = mysql.connector.connect(**DB_CONFIG)
|
|
cursor = conn.cursor()
|
|
cursor.execute("SELECT id, nombre FROM categorias_estandar ORDER BY nombre")
|
|
categorias = cursor.fetchall()
|
|
|
|
sql = """
|
|
SELECT n.fecha, n.titulo, n.resumen, n.url, n.imagen_url, c.nombre
|
|
FROM noticias n
|
|
LEFT JOIN categorias_estandar c ON n.categoria_id = c.id
|
|
"""
|
|
params = []
|
|
if cat_id:
|
|
sql += " WHERE n.categoria_id = %s"
|
|
params.append(cat_id)
|
|
sql += " ORDER BY n.fecha DESC LIMIT 50"
|
|
cursor.execute(sql, params)
|
|
noticias = cursor.fetchall()
|
|
except mysql.connector.Error as db_err:
|
|
app.logger.error(f"[DB ERROR] Al leer noticias: {db_err}", exc_info=True)
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
return render_template('noticias.html', noticias=noticias, categorias=categorias, cat_id=int(cat_id) if cat_id else None)
|
|
|
|
def fetch_and_store():
|
|
conn = None
|
|
try:
|
|
conn = mysql.connector.connect(**DB_CONFIG)
|
|
cursor = conn.cursor()
|
|
cursor.execute("SELECT url, categoria_id FROM feeds WHERE activo = TRUE")
|
|
feeds = cursor.fetchall()
|
|
except mysql.connector.Error as db_err:
|
|
app.logger.error(f"[DB ERROR] No se pudo conectar o leer feeds: {db_err}", exc_info=True)
|
|
return
|
|
|
|
for rss_url, categoria_id in feeds:
|
|
try:
|
|
app.logger.info(f"Procesando feed: {rss_url} [{categoria_id}]")
|
|
parsed = feedparser.parse(rss_url)
|
|
except Exception as e:
|
|
app.logger.error(f"[PARSE ERROR] Al parsear {rss_url}: {e}", exc_info=True)
|
|
continue
|
|
|
|
if getattr(parsed, 'bozo', False):
|
|
bozo_exc = getattr(parsed, 'bozo_exception', 'Unknown')
|
|
app.logger.warning(f"[BOZO] Feed mal formado: {rss_url} - {bozo_exc}")
|
|
continue
|
|
|
|
for entry in parsed.entries:
|
|
link = entry.get('link') or entry.get('id')
|
|
if not link:
|
|
links_list = entry.get('links', [])
|
|
if isinstance(links_list, list) and links_list:
|
|
href = next((l.get('href') for l in links_list if l.get('href')), None)
|
|
link = href
|
|
if not link:
|
|
app.logger.error(f"[ENTRY ERROR] Entrada sin link en feed {rss_url}, salto entrada.")
|
|
continue
|
|
|
|
try:
|
|
noticia_id = hashlib.md5(link.encode()).hexdigest()
|
|
titulo = entry.get('title', '')
|
|
resumen = entry.get('summary', '')
|
|
imagen_url = ''
|
|
fecha = None
|
|
|
|
if 'media_content' in entry:
|
|
imagen_url = entry.media_content[0].get('url', '')
|
|
else:
|
|
img = re.search(r'<img.+?src="(.+?)"', resumen)
|
|
if img:
|
|
imagen_url = img.group(1)
|
|
|
|
published = entry.get('published_parsed') or entry.get('updated_parsed')
|
|
if published:
|
|
try:
|
|
fecha = datetime(*published[:6])
|
|
except Exception:
|
|
fecha = None
|
|
|
|
cursor.execute(
|
|
"""
|
|
INSERT IGNORE INTO noticias
|
|
(id, titulo, resumen, url, fecha, imagen_url, categoria_id)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
|
""",
|
|
(noticia_id, titulo, resumen, link, fecha, imagen_url, categoria_id)
|
|
)
|
|
except Exception as entry_err:
|
|
app.logger.error(
|
|
f"[ENTRY ERROR] Falló procesar entrada {link}: {entry_err}", exc_info=True
|
|
)
|
|
continue
|
|
|
|
try:
|
|
conn.commit()
|
|
except Exception as commit_err:
|
|
app.logger.error(f"[DB ERROR] Al confirmar transacción: {commit_err}", exc_info=True)
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
app.logger.info(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Feeds procesados.")
|
|
|
|
if __name__ == '__main__':
|
|
scheduler = BackgroundScheduler()
|
|
scheduler.add_job(fetch_and_store, 'interval', minutes=2, id='rss_job')
|
|
scheduler.start()
|
|
try:
|
|
app.run(host="0.0.0.0", port=5000, debug=True)
|
|
finally:
|
|
scheduler.shutdown()
|
|
|