import { createFeed, getFeedByLink, deleteFeedByLink } from '../modules/mongo-wrappers/mongoFeedsWrappers.mjs'; class SourceManager { constructor(sourceFailureLimit) { this.sourceFailureLimit = sourceFailureLimit; this.runningSourcesToRemove = {}; } async removeSource(sourceURL) { log.INFO(`Removing source: ${sourceURL}`); const currentTime = Date.now(); const sourceData = this.runningSourcesToRemove[sourceURL]; if (!sourceData) { this.runningSourcesToRemove[sourceURL] = { count: 1, timestamp: currentTime, ignoredAttempts: 0 }; return; } const elapsedTimeSinceLastAttempt = currentTime - sourceData.timestamp; const waitTime = sourceData.count * 30000; if (elapsedTimeSinceLastAttempt <= waitTime) { sourceData.ignoredAttempts += 1; return; } if (sourceData.count < this.sourceFailureLimit) { sourceData.count += 1; sourceData.timestamp = currentTime; return; } try { const record = await getFeedByLink(sourceURL); if (!record) { log.ERROR(`Source not found in storage: ${sourceURL}`); return; } const results = await deleteFeedByLink(sourceURL); if (!results) { log.WARN(`Failed to remove source: ${sourceURL}`); return; } log.DEBUG(`Source removed after exceeding failure limit: ${sourceURL}`); // Optionally, clean up the entry from runningSourcesToRemove delete this.runningSourcesToRemove[sourceURL]; } catch (err) { log.ERROR(`Error removing source from storage: ${sourceURL}`, err); } } async addSource(title, link, category, guildId, channelId, callback) { try { const feed = { title, link, category, guild_id: guildId, channel_id: channelId }; const record = await createFeed(feed); log.DEBUG("Source added:", record); if (callback) callback(null, record); } catch (err) { log.ERROR("Error adding source:", err); if (callback) callback(err, null); } } } // Create a default instance of SourceManager const defaultSourceManager = new SourceManager(); // Export the class and default instance methods export { SourceManager }; export const addSource = defaultSourceManager.addSource.bind(defaultSourceManager); export const removeSource = defaultSourceManager.removeSource.bind(defaultSourceManager);