Refactor caching and Telegram integration
- Updated configuration to enforce Redis caching for notified articles, removing memory cache options. - Enhanced wallamonitor.py to load Redis cache settings and handle errors more effectively. - Implemented new API endpoints for clearing Redis cache and retrieving Telegram forum topics. - Improved frontend components to support fetching and displaying available Telegram threads. - Added functionality for clearing cache from the UI, ensuring better management of notified articles.
This commit is contained in:
@@ -327,6 +327,51 @@ app.delete('/api/favorites/:platform/:id', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Limpiar toda la caché de Redis
|
||||
app.delete('/api/cache', async (req, res) => {
|
||||
try {
|
||||
if (!redisClient) {
|
||||
return res.status(500).json({ error: 'Redis no está disponible' });
|
||||
}
|
||||
|
||||
// Obtener todas las claves que empiezan con 'notified:'
|
||||
const keys = await redisClient.keys('notified:*');
|
||||
|
||||
if (!keys || keys.length === 0) {
|
||||
return res.json({
|
||||
success: true,
|
||||
message: 'Cache ya está vacío',
|
||||
count: 0
|
||||
});
|
||||
}
|
||||
|
||||
// Eliminar todas las claves
|
||||
const count = keys.length;
|
||||
for (const key of keys) {
|
||||
await redisClient.del(key);
|
||||
}
|
||||
|
||||
// Notificar a los clientes WebSocket
|
||||
broadcast({
|
||||
type: 'cache_cleared',
|
||||
data: { count, timestamp: Date.now() }
|
||||
});
|
||||
|
||||
// También actualizar favoritos (debería estar vacío ahora)
|
||||
const favorites = await getFavorites();
|
||||
broadcast({ type: 'favorites_updated', data: favorites });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `Cache limpiado: ${count} artículos eliminados`,
|
||||
count
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error limpiando cache de Redis:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Obtener artículos notificados
|
||||
app.get('/api/articles', async (req, res) => {
|
||||
try {
|
||||
@@ -454,6 +499,64 @@ app.get('/api/config', (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Obtener threads/topics de Telegram
|
||||
app.get('/api/telegram/threads', async (req, res) => {
|
||||
try {
|
||||
if (!config) {
|
||||
config = yaml.parse(readFileSync(CONFIG_PATH, 'utf8'));
|
||||
}
|
||||
|
||||
const token = config?.telegram_token;
|
||||
const channel = config?.telegram_channel;
|
||||
|
||||
if (!token || !channel) {
|
||||
return res.status(400).json({ error: 'Token o canal de Telegram no configurados' });
|
||||
}
|
||||
|
||||
// Convertir el canal a chat_id si es necesario
|
||||
let chatId = channel;
|
||||
if (channel.startsWith('@')) {
|
||||
// Para canales con @, necesitamos obtener el chat_id primero
|
||||
const getChatUrl = `https://api.telegram.org/bot${token}/getChat?chat_id=${encodeURIComponent(channel)}`;
|
||||
const chatResponse = await fetch(getChatUrl);
|
||||
const chatData = await chatResponse.json();
|
||||
|
||||
if (!chatData.ok) {
|
||||
return res.status(400).json({ error: `Error obteniendo chat: ${chatData.description || 'Chat no encontrado'}` });
|
||||
}
|
||||
|
||||
chatId = chatData.result.id;
|
||||
}
|
||||
|
||||
// Intentar obtener forum topics
|
||||
const forumTopicsUrl = `https://api.telegram.org/bot${token}/getForumTopics?chat_id=${chatId}&limit=100`;
|
||||
const topicsResponse = await fetch(forumTopicsUrl);
|
||||
const topicsData = await topicsResponse.json();
|
||||
|
||||
if (topicsData.ok && topicsData.result?.topics) {
|
||||
const threads = topicsData.result.topics.map(topic => ({
|
||||
id: topic.message_thread_id,
|
||||
name: topic.name || `Thread ${topic.message_thread_id}`,
|
||||
icon_color: topic.icon_color,
|
||||
icon_custom_emoji_id: topic.icon_custom_emoji_id,
|
||||
}));
|
||||
|
||||
return res.json({ threads, success: true });
|
||||
} else {
|
||||
// Si no hay forum topics, devolver un mensaje informativo
|
||||
return res.json({
|
||||
threads: [],
|
||||
success: false,
|
||||
message: 'El chat no tiene forum topics habilitados o no se pudieron obtener. Puedes obtener el Thread ID manualmente copiando el enlace del tema.',
|
||||
info: 'Para obtener el Thread ID manualmente: 1. Haz clic derecho en el tema/hilo en Telegram 2. Selecciona "Copiar enlace del tema" 3. El número al final de la URL es el Thread ID (ej: t.me/c/1234567890/8 → Thread ID = 8)'
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo threads de Telegram:', error.message);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// WebSocket connection
|
||||
wss.on('connection', (ws) => {
|
||||
console.log('Cliente WebSocket conectado');
|
||||
|
||||
Reference in New Issue
Block a user