108 lines
3.3 KiB
JavaScript
108 lines
3.3 KiB
JavaScript
import { getDB, initNotifiedArticleKeys } from './mongodb.js';
|
|
import { broadcast } from './websocket.js';
|
|
import { sendPushNotifications } from './webPush.js';
|
|
import { ARTICLE_MONITORING } from '../config/constants.js';
|
|
|
|
let notifiedArticleIds = new Set();
|
|
let articlesCheckInterval = null;
|
|
|
|
// Función para detectar y enviar artículos nuevos
|
|
async function checkForNewArticles() {
|
|
const db = getDB();
|
|
if (!db) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
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();
|
|
|
|
const currentIds = new Set(
|
|
allArticles.map(a => `${a.platform}:${a.id}`)
|
|
);
|
|
|
|
// 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 (articlesToSend.length > 0) {
|
|
broadcast({
|
|
type: 'new_articles',
|
|
data: articlesToSend
|
|
});
|
|
|
|
// Enviar notificaciones push para cada artículo nuevo
|
|
for (const article of articlesToSend) {
|
|
await sendPushNotifications({
|
|
title: `Nuevo artículo en ${article.platform?.toUpperCase() || 'Wallabicher'}`,
|
|
body: article.title || 'Artículo nuevo disponible',
|
|
icon: '/android-chrome-192x192.png',
|
|
image: article.images?.[0] || null,
|
|
url: article.url || '/',
|
|
platform: article.platform,
|
|
price: article.price,
|
|
currency: article.currency || '€',
|
|
id: article.id,
|
|
});
|
|
}
|
|
}
|
|
|
|
// 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 MongoDB esté listo
|
|
export async function startArticleMonitoring() {
|
|
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);
|
|
console.log('✅ Monitoreo de artículos nuevos iniciado');
|
|
}
|
|
}
|
|
|
|
// Detener el monitoreo
|
|
export function stopArticleMonitoring() {
|
|
if (articlesCheckInterval) {
|
|
clearInterval(articlesCheckInterval);
|
|
articlesCheckInterval = null;
|
|
}
|
|
}
|
|
|
|
|