Signed-off-by: Omar Sánchez Pizarro <omar.sanchez@pistacero.net>
This commit is contained in:
Omar Sánchez Pizarro
2026-01-20 03:21:50 +01:00
parent 19932854ca
commit 81bf0675ed
32 changed files with 3081 additions and 932 deletions

View File

@@ -1,74 +1,57 @@
import { getRedisClient, initNotifiedArticleKeys } from './redis.js';
import { getDB, initNotifiedArticleKeys } from './mongodb.js';
import { broadcast } from './websocket.js';
import { sendPushNotifications } from './webPush.js';
import { ARTICLE_MONITORING } from '../config/constants.js';
let notifiedArticleKeys = new Set();
let notifiedArticleIds = new Set();
let articlesCheckInterval = null;
// Función para detectar y enviar artículos nuevos
async function checkForNewArticles() {
const redisClient = getRedisClient();
if (!redisClient) {
const db = getDB();
if (!db) {
return;
}
try {
const currentKeys = await redisClient.keys('notified:*');
const currentKeysSet = new Set(currentKeys);
const articlesCollection = db.collection('articles');
// Obtener todos los artículos con sus IDs
const allArticles = await articlesCollection.find(
{},
{ projection: { platform: 1, id: 1, title: 1, price: 1, currency: 1, url: 1, images: 1 } }
).toArray();
// Encontrar claves nuevas
const newKeys = currentKeys.filter(key => !notifiedArticleKeys.has(key));
const currentIds = new Set(
allArticles.map(a => `${a.platform}:${a.id}`)
);
if (newKeys.length > 0) {
// Obtener los artículos nuevos
const newArticles = [];
for (const key of newKeys) {
try {
const value = await redisClient.get(key);
if (value) {
// Intentar parsear como JSON
let articleData = {};
try {
articleData = JSON.parse(value);
} catch (e) {
// Si no es JSON válido, extraer información de la key
const parts = key.split(':');
if (parts.length >= 3) {
articleData = {
platform: parts[1],
id: parts.slice(2).join(':'),
};
}
}
// Añadir información adicional si está disponible
if (articleData.platform && articleData.id) {
newArticles.push({
platform: articleData.platform || 'unknown',
id: articleData.id || 'unknown',
title: articleData.title || null,
price: articleData.price || null,
currency: articleData.currency || '€',
url: articleData.url || null,
images: articleData.images || [],
});
}
}
} catch (error) {
console.error(`Error obteniendo artículo de Redis (${key}):`, error.message);
}
}
// Encontrar artículos nuevos
const newArticles = allArticles.filter(article => {
const articleId = `${article.platform}:${article.id}`;
return !notifiedArticleIds.has(articleId);
});
if (newArticles.length > 0) {
// Preparar artículos para enviar
const articlesToSend = newArticles.map(article => ({
platform: article.platform || 'unknown',
id: article.id || 'unknown',
title: article.title || null,
price: article.price || null,
currency: article.currency || '',
url: article.url || null,
images: article.images || [],
}));
// Enviar artículos nuevos por WebSocket
if (newArticles.length > 0) {
if (articlesToSend.length > 0) {
broadcast({
type: 'new_articles',
data: newArticles
data: articlesToSend
});
// Enviar notificaciones push para cada artículo nuevo
for (const article of newArticles) {
for (const article of articlesToSend) {
await sendPushNotifications({
title: `Nuevo artículo en ${article.platform?.toUpperCase() || 'Wallabicher'}`,
body: article.title || 'Artículo nuevo disponible',
@@ -83,20 +66,29 @@ async function checkForNewArticles() {
}
}
// Actualizar el set de claves notificadas
notifiedArticleKeys = currentKeysSet;
// Actualizar el set de IDs notificadas
notifiedArticleIds = currentIds;
}
} catch (error) {
console.error('Error verificando artículos nuevos:', error.message);
}
}
// Inicializar el check de artículos cuando Redis esté listo
// Inicializar el check de artículos cuando MongoDB esté listo
export async function startArticleMonitoring() {
const redisClient = getRedisClient();
if (redisClient) {
// Inicializar claves conocidas
notifiedArticleKeys = await initNotifiedArticleKeys();
const db = getDB();
if (db) {
// Inicializar IDs conocidas
const keys = await initNotifiedArticleKeys();
notifiedArticleIds = new Set(
Array.from(keys).map(key => {
const parts = key.replace('notified:', '').split(':');
if (parts.length >= 2) {
return `${parts[0]}:${parts.slice(1).join(':')}`;
}
return key;
})
);
// Iniciar intervalo para verificar nuevos artículos
articlesCheckInterval = setInterval(checkForNewArticles, ARTICLE_MONITORING.CHECK_INTERVAL);