Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | /**
* EvolutionPollingService
*
* Polls Evolution API for new messages since webhooks are not working
* This is a temporary solution until webhookByEvents can be enabled
*/
const { logger } = require('../config/logger');
const EvolutionInstance = require('../models/EvolutionInstance');
const EvolutionAPIService = require('./EvolutionAPIService');
const eventBus = require('../core/whatsapp/EventBus');
const Events = require('../core/whatsapp/CoreEvents');
class EvolutionPollingService {
constructor() {
this.pollingIntervals = new Map();
this.lastMessageTimestamps = new Map();
this.isPolling = false;
}
/**
* Start polling for all active Evolution instances
*/
async startPolling(intervalMs = 5000) {
if (this.isPolling) {
logger.warn('Polling already started');
return;
}
this.isPolling = true;
logger.info('Starting Evolution API polling service', { intervalMs });
// Poll every X seconds
const pollInterval = setInterval(async () => {
try {
await this.pollAllInstances();
} catch (error) {
logger.error('Error in polling cycle', { error: error.message });
}
}, intervalMs);
this.pollingIntervals.set('main', pollInterval);
}
/**
* Stop polling
*/
stopPolling() {
this.pollingIntervals.forEach((interval) => {
clearInterval(interval);
});
this.pollingIntervals.clear();
this.isPolling = false;
logger.info('Evolution API polling service stopped');
}
/**
* Poll all active instances for new messages
*/
async pollAllInstances() {
try {
// Get all connected Evolution instances
const instances = await EvolutionInstance.getAllActive();
for (const instance of instances) {
try {
await this.pollInstance(instance);
} catch (error) {
logger.error('Error polling instance', {
instanceId: instance.id,
error: error.message
});
}
}
} catch (error) {
logger.error('Error getting active instances', { error: error.message });
}
}
/**
* Poll a single instance for new messages
*/
async pollInstance(instance) {
// Implementation will fetch messages from Evolution API
// and emit them to the event bus
logger.debug('Polling instance', { instanceId: instance.id });
// TODO: Implement actual polling logic
// This would call Evolution API to get recent messages
// and compare with lastMessageTimestamps to find new ones
}
}
module.exports = new EvolutionPollingService();
|