Files
drb-server/src/rss-manager/sourceManager.mjs
Logan Cusano 066404dd10
Some checks failed
Update Wiki from JSDoc / update-wiki (pull_request) Has been cancelled
Lint JavaScript/Node.js / lint-js (pull_request) Failing after 11s
DRB Tests / drb_mocha_tests (pull_request) Has been cancelled
Updated dir structure to put the actual source code in the general /src dir
2024-08-17 18:44:18 -04:00

93 lines
2.5 KiB
JavaScript

import { DebugBuilder } from "../modules/debugger.mjs";
const log = new DebugBuilder("server", "sourceManager");
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);