Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889const fs = require('fs-extra');const path = require('path');const cron = require('node-cron');const config = require('../config');const crypto = require('crypto');const ImageHashManager = require('../utils/imageHashManager');const mediaCache = require('../utils/mediaCache');const { isAmbiguousDeliveryError } = require('../utils/telegramErrorHelper');
class QueueManager { constructor() { // Allow custom queue file location via environment variable this.queueFile = config.queueFilePath || path.join(__dirname, 'queue.json'); this.queueBackupFile = `${this.queueFile}.backup`; this.cronSchedule = config.defaultCronSchedule; this.imagesPerInterval = config.imagesPerInterval; this.scheduledTask = null; this.autoSaveInterval = null; this.queueData = { queue: [], shuffleMode: false }; this.postServices = ['telegram']; this.shuffleMode = false; // Whether queue should be shuffled after item removal this.isProcessingPost = false; // Prevent concurrent post cycles during slow timeouts // Add Discord to services if enabled if (config.discord?.enabled) { this.postServices.push('discord'); } // Initialize image hash manager for duplicate detection try { this.imageHashManager = new ImageHashManager(); console.log('[QueueManager] ImageHashManager initialized for duplicate detection'); } catch (error) { console.error('[QueueManager] Failed to initialize ImageHashManager:', error); this.imageHashManager = null; } this.initPromise = this.initialize(); }
async initialize() { await this.loadQueueFromDisk(); this.startAutoSave(); // Log queue status on startup const queueLength = this.queueData.queue.length; const shuffleStatus = this.shuffleMode ? 'enabled' : 'disabled'; console.log(`[QueueManager] Queue loaded with ${queueLength} item${queueLength !== 1 ? 's' : ''}, shuffle mode ${shuffleStatus}`); // Initialize service tracking for any existing items that don't have it this.initializeServiceTracking(); }
/** * Initialize service tracking for items that don't have it yet */ initializeServiceTracking() { let updated = false; for (let i = 0; i < this.queueData.queue.length; i++) { const item = this.queueData.queue[i]; // If the item doesn't have a postedTo property, initialize it if (!item.postedTo) { this.queueData.queue[i].postedTo = {}; this.postServices.forEach(service => { this.queueData.queue[i].postedTo[service] = false; }); updated = true; } // Initialize sourceImgUrl if not present if (!item.sourceImgUrl) { // Try to set sourceImgUrl from existing data if (item.originalImageUrl) { this.queueData.queue[i].sourceImgUrl = item.originalImageUrl; updated = true; } else if (item.downloadUrl) { this.queueData.queue[i].sourceImgUrl = item.downloadUrl; updated = true; } }
// Initialize imageUrls if not present if (!item.isVideo && (!Array.isArray(item.imageUrls) || item.imageUrls.length === 0) && item.imageUrl) { this.queueData.queue[i].imageUrls = [item.imageUrl]; updated = true; } } if (updated) { this.saveQueueToDisk() .then(() => console.log('Queue items updated with service tracking, sourceImgUrl, and imageUrls')) .catch(err => console.error('Error initializing service tracking:', err)); } }
/** * Start auto-saving the queue periodically */ startAutoSave() { // Auto-save the queue every 5 minutes const autoSaveMinutes = 5; this.autoSaveInterval = setInterval(() => { this.saveQueueToDisk() .then(() => console.log(`Queue auto-saved (${this.queueData.queue.length} items)`)) .catch(err => console.error('Error auto-saving queue:', err)); }, autoSaveMinutes * 60 * 1000); }
/** * Load queue data from disk with error recovery */ async loadQueueFromDisk() { try { // Check if main queue file exists if (!await fs.pathExists(this.queueFile) && await fs.pathExists(this.queueBackupFile)) { try { console.log('Main queue file missing, attempting recovery from backup...'); const backupContent = await fs.readJson(this.queueBackupFile); if (backupContent && Array.isArray(backupContent.queue)) { this.queueData = backupContent; this.shuffleMode = backupContent.shuffleMode || false; await this.saveQueueToDisk(); // Update the main file console.log('Queue successfully recovered from backup'); return; } } catch (backupError) { console.error('Error reading backup queue file:', backupError); } }
if (await fs.pathExists(this.queueFile)) { try { const content = await fs.readJson(this.queueFile); if (content && Array.isArray(content.queue)) { this.queueData = content; // Load shuffle mode from saved data, default to false if not present this.shuffleMode = content.shuffleMode || false; return; } } catch (mainError) { console.error('Error reading main queue file:', mainError); // Try to recover from backup if main file is corrupted if (await fs.pathExists(this.queueBackupFile)) { try { console.log('Attempting to recover queue from backup file...'); const backupContent = await fs.readJson(this.queueBackupFile); if (backupContent && Array.isArray(backupContent.queue)) { this.queueData = backupContent; // Load shuffle mode from backup data, default to false if not present this.shuffleMode = backupContent.shuffleMode || false; await this.saveQueueToDisk(); // Update the main file console.log('Queue successfully recovered from backup'); return; } } catch (backupError) { console.error('Error reading backup queue file:', backupError); } } } } // If we reach here, initialize an empty queue this.queueData = { queue: [], shuffleMode: false }; this.shuffleMode = false; await this.saveQueueToDisk(); } catch (error) { console.error('Error during queue initialization:', error); this.queueData = { queue: [], shuffleMode: false }; this.shuffleMode = false; } }
/** * Save queue to disk with atomic write operations */ async saveQueueToDisk() { try { // Update shuffle mode in queueData before saving this.queueData.shuffleMode = this.shuffleMode; // First, update the backup file await fs.writeJson(this.queueBackupFile, this.queueData, { spaces: 2 }); // Then, atomically replace the main queue file const tempFile = `${this.queueFile}.temp`; await fs.writeJson(tempFile, this.queueData, { spaces: 2 }); await fs.move(tempFile, this.queueFile, { overwrite: true }); return true; } catch (error) { console.error('Error saving queue to disk:', error); return false; } }
async getQueue() { return this.queueData.queue || []; }
async addToQueue(imageData, addedBy = null) { try { // Initialize postedTo tracking for all services const postedTo = {}; this.postServices.forEach(service => { postedTo[service] = false; }); // Determine the sourceImgUrl from available data let sourceImgUrl = null; // Check various possible sources for the raw upstream URL if (imageData.originalImageUrl && imageData.originalImageUrl.startsWith('http')) { sourceImgUrl = imageData.originalImageUrl; } else if (imageData.downloadUrl && imageData.downloadUrl.startsWith('http')) { sourceImgUrl = imageData.downloadUrl; } else if (imageData.imageUrl && imageData.imageUrl.startsWith('http')) { // Only use imageUrl if it's a web URL, not a local path sourceImgUrl = imageData.imageUrl; } console.log(`Adding item to queue with sourceImgUrl: ${sourceImgUrl || 'none'}`); // Check for duplicates using perceptual hash if (this.imageHashManager && imageData.imageUrl) { try { // Extract filename from path to get perceptual hash const filename = path.basename(imageData.imageUrl, path.extname(imageData.imageUrl)); // Check if this hash already exists in the queue const duplicate = this.queueData.queue.find(item => { if (item.imageUrl) { const itemFilename = path.basename(item.imageUrl, path.extname(item.imageUrl)); return itemFilename === filename; } return false; }); if (duplicate) { console.log(`[QueueManager] Duplicate detected! Image with hash ${filename} already in queue`); console.log(`[QueueManager] Existing item added by: ${duplicate.addedBy || 'unknown'}`); console.log(`[QueueManager] Existing item source: ${duplicate.sourceImgUrl || 'unknown'}`); return { success: false, duplicate: true, existingItem: { addedBy: duplicate.addedBy, sourceUrl: duplicate.sourceImgUrl, timestamp: duplicate.timestamp } }; } } catch (error) { console.error('[QueueManager] Error checking for duplicates:', error); // Continue with adding if duplicate check fails } } // Ensure imageUrls is populated for image items let imageUrls = Array.isArray(imageData.imageUrls) && imageData.imageUrls.length > 0 ? imageData.imageUrls : (!imageData.isVideo && imageData.imageUrl ? [imageData.imageUrl] : imageData.imageUrls);
this.queueData.queue.push({ ...imageData, ...(imageUrls ? { imageUrls } : {}), timestamp: new Date().toISOString(), id: `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`, postedTo, sourceImgUrl, // Add the new field addedBy // Add the username who added this item }); await this.saveQueueToDisk(); return { success: true }; } catch (error) { console.error('Error adding to queue:', error); return false; } }
async getNextFromQueue() { if (this.queueData.queue.length === 0) { return null; } return this.queueData.queue[0]; }
/** * Mark an item as posted by a specific service * @param {number} index - Index of the item in the queue * @param {string} service - Service name (e.g., 'telegram', 'discord') * @returns {Promise<boolean>} - Whether marking was successful */ async markPostedByService(index = 0, service) { try { if (this.queueData.queue.length === 0 || index >= this.queueData.queue.length) { return false; } // Make sure the service is valid if (!this.postServices.includes(service)) { console.warn(`Unknown service: ${service}`); return false; } // Mark the item as posted by the service if (!this.queueData.queue[index].postedTo) { this.queueData.queue[index].postedTo = {}; } this.queueData.queue[index].postedTo[service] = true; // Check if all services have posted the item const allPosted = this.postServices.every(s => this.queueData.queue[index].postedTo[s] === true ); // If all services have posted, remove the item if (allPosted) { const removed = this.queueData.queue.splice(index, 1)[0]; console.log(`All services posted item: ${removed.title}, removed from queue`); // If shuffle mode is enabled and there are items remaining in the queue, shuffle them if (this.shuffleMode && this.queueData.queue.length > 1) { await this.shuffleQueue(); } else { await this.saveQueueToDisk(); } } else { await this.saveQueueToDisk(); } return true; } catch (error) { console.error('Error marking item as posted:', error); return false; } }
/** * Check if an item has been posted by a specific service * @param {number} index - Index of the item in the queue * @param {string} service - Service name * @returns {boolean} - Whether the item has been posted by the service */ hasBeenPostedByService(index = 0, service) { if (this.queueData.queue.length === 0 || index >= this.queueData.queue.length) { return false; } const item = this.queueData.queue[index]; return item.postedTo && item.postedTo[service] === true; }
/** * Get the next item that has not been posted by a specific service * @param {string} service - Service name * @returns {Object|null} - Next item to post or null if none found */ async getNextForService(service) { for (let i = 0; i < this.queueData.queue.length; i++) { const item = this.queueData.queue[i]; if (item.postedTo && item.postedTo[service] === false) { return { item, index: i }; } } return null; }
/** * Find item index by ID * @param {string} id - Queue item ID * @returns {number} - Index in queue or -1 if not found */ findItemIndexById(id) { if (!id || !this.queueData || !Array.isArray(this.queueData.queue)) { return -1; } return this.queueData.queue.findIndex(item => item && item.id === id); }
/** * Get an item from queue by index or ID * @param {number|string} indexOrId - Index or item ID * @returns {Object|null} */ getItem(indexOrId) { if (!this.queueData || !Array.isArray(this.queueData.queue) || this.queueData.queue.length === 0) { return null; } if (typeof indexOrId === 'number') { return this.queueData.queue[indexOrId] || null; } const index = this.findItemIndexById(indexOrId); if (index !== -1) { return this.queueData.queue[index]; } if (!isNaN(Number(indexOrId))) { return this.queueData.queue[parseInt(indexOrId, 10)] || null; } return null; }
/** * Move an item to the top of the queue * @param {number|string} indexOrId - Index or item ID * @returns {Promise<Object|null>} - The moved item or null */ async moveToTop(indexOrId) { try { if (!this.queueData || !Array.isArray(this.queueData.queue) || this.queueData.queue.length === 0) { return null; }
let index = -1; if (typeof indexOrId === 'number') { index = indexOrId; } else if (typeof indexOrId === 'string') { index = this.findItemIndexById(indexOrId); if (index === -1 && !isNaN(Number(indexOrId))) { index = parseInt(indexOrId, 10); } }
if (index < 0 || index >= this.queueData.queue.length) { return null; }
if (index === 0) { return this.queueData.queue[0]; }
const [item] = this.queueData.queue.splice(index, 1); this.queueData.queue.unshift(item); await this.saveQueueToDisk(); return item; } catch (error) { console.error('Error moving item to top of queue:', error); return null; } }
/** * Force remove an item from queue regardless of posting status * @param {number|string} indexOrId - Index or ID of the item to remove * @returns {Promise<Object|null>} - The removed item or null if not found */ async removeFromQueue(indexOrId = 0) { try { if (!this.queueData || !Array.isArray(this.queueData.queue) || this.queueData.queue.length === 0) { return null; }
let index = -1; if (typeof indexOrId === 'number') { index = indexOrId; } else if (typeof indexOrId === 'string') { index = this.findItemIndexById(indexOrId); if (index === -1 && !isNaN(Number(indexOrId))) { index = parseInt(indexOrId, 10); } }
if (index < 0 || index >= this.queueData.queue.length) { return null; } const removed = this.queueData.queue.splice(index, 1)[0]; await this.saveQueueToDisk(); return removed; } catch (error) { console.error('Error removing from queue:', error); return null; } }
async getQueueLength() { return this.queueData.queue.length; }
setCronSchedule(schedule) { try { if (this.scheduledTask) { this.scheduledTask.stop(); } // Validate the schedule if (cron.validate(schedule)) { this.cronSchedule = schedule; return true; } return false; } catch (error) { console.error('Error setting cron schedule:', error); return false; } }
setImagesPerInterval(count) { if (typeof count !== 'number' || count < 1) { return false; } this.imagesPerInterval = count; return true; }
/** * Check if an item has been successfully posted to all configured services * @param {number} index - Index of item in queue * @returns {boolean} - Whether item is posted to all services */ isItemPostedToAllServices(index = 0) { if (this.queueData.queue.length === 0 || index >= this.queueData.queue.length) { return false; } const item = this.queueData.queue[index]; if (!item || !item.postedTo) return false; return this.postServices.every(s => item.postedTo[s] === true); }
/** * Attempt to send an item to all unposted services * @param {Object} item - Media item to post * @param {Object} postFunctions - Service post functions * @param {number} index - Current queue index * @returns {Promise<{allPosted: boolean, errors: Object}>} */ async sendItemToServices(item, postFunctions, index = 0) { const errors = {}; const ambiguousServices = {};
for (const service of this.postServices) { // Skip if service already posted this item if (this.hasBeenPostedByService(index, service)) { console.log(`Item "${item.title || 'Untitled'}" already posted by ${service}, skipping`); continue; }
const postFunction = postFunctions[service]; if (!postFunction) { console.warn(`[QueueManager] No post function for service: ${service}`); errors[service] = new Error(`No post function configured for service: ${service}`); continue; }
const options = {}; try { const success = await postFunction(item, options); if (success) { await this.markPostedByService(index, service); console.log(`[QueueManager] Posted to ${service}: ${item.title || 'Untitled'}`); } else { console.error(`[QueueManager] Failed to post to ${service}: ${item.title || 'Untitled'}`); errors[service] = options.error || new Error(`Posting to ${service} returned false`); if (options.ambiguousDelivery || isAmbiguousDeliveryError(options.error)) { ambiguousServices[service] = true; } } } catch (error) { console.error(`[QueueManager] Exception posting to ${service}:`, error); errors[service] = error; if (isAmbiguousDeliveryError(error)) { ambiguousServices[service] = true; } } }
const itemAtPos = this.queueData.queue[index]; const allPosted = (itemAtPos !== item) || this.isItemPostedToAllServices(index); return { allPosted, errors, ambiguousServices }; }
/** * Notify failure handler for any services that have not posted the item * @param {Function} onFailure - Failure handler callback * @param {Object} item - Queue item * @param {Object} errors - Map of service -> error * @param {string} defaultMessage - Fallback error message template */ async _notifyFailures(onFailure, item, errors, defaultMessage) { if (!onFailure) return; for (const service of this.postServices) { if (!this.hasBeenPostedByService(0, service)) { try { const errorDetails = errors[service] || new Error(defaultMessage.replace('{service}', service)); await onFailure(service, item, errorDetails); } catch (failHandlerErr) { console.error(`[QueueManager] Error running failure handler for ${service}:`, failHandlerErr); } } } }
/** * Process a queue item with confirmation, recaching, 2 retries, delete, next send, and requeue * @param {Object} postFunctions - Service post functions * @param {Function} onFailure - Failure handler callback * @param {boolean} isFallback - Whether this is a fallback send for a previous failed item * @returns {Promise<Object>} - Execution result summary */ async processPostWithRetries(postFunctions, onFailure, isFallback = false) { if (!isFallback) { if (this.isProcessingPost) { console.warn('[QueueManager] Post processing already in progress; skipping concurrent run.'); return { success: false, busy: true }; } this.isProcessingPost = true; }
try { if (this.queueData.queue.length === 0) { console.log('[QueueManager] Queue is empty, nothing to post'); return { success: false, empty: true }; }
const currentItem = this.queueData.queue[0]; console.log(`[QueueManager] Processing queue post: "${currentItem.title || 'Untitled'}" (isFallback: ${isFallback})`);
const isDeliveredToAll = () => { if (!currentItem || !currentItem.postedTo) return false; return this.postServices.every(s => currentItem.postedTo[s] === true); };
const hasAmbiguousError = (result) => Boolean(result && result.ambiguousServices && Object.keys(result.ambiguousServices).length > 0);
const handleAmbiguousDelivery = async (result, retriesUsed) => { console.warn(`[QueueManager] Ambiguous delivery error (e.g. 504 Gateway Timeout) for "${currentItem.title || 'Untitled'}". Skipping remaining retries and fallback to prevent duplicate posts.`);
await this._notifyFailures( onFailure, currentItem, result.errors, 'Ambiguous delivery error posting to {service}' );
const failedItem = this.queueData.queue.splice(0, 1)[0]; this.queueData.queue.push(failedItem); await this.saveQueueToDisk(); console.log(`[QueueManager] Requeued "${failedItem.title || 'Untitled'}" to end of queue without retrying.`);
return { success: false, failedItem, retriesUsed, requeued: true, ambiguousDelivery: true, nextItemResult: null }; };
// Attempt 1: Send to all platforms let sendResult = await this.sendItemToServices(currentItem, postFunctions, 0);
// Check if the post went to all platforms on attempt 1 if (isDeliveredToAll()) { console.log(`[QueueManager] Confirmed: Post "${currentItem.title || 'Untitled'}" went to all platforms.`); return { success: true, item: currentItem, retriesUsed: 0 }; }
// If Telegram returned a 504 Gateway Timeout (or similar ambiguous error), do not retry or fall back if (hasAmbiguousError(sendResult)) { return await handleAmbiguousDelivery(sendResult, 0); }
// If there is an error and the bot can't send the post: console.warn(`[QueueManager] Post "${currentItem.title || 'Untitled'}" did not go to all platforms on attempt 1. Recaching...`);
// Recache the erroring post try { await mediaCache.recacheItem(currentItem, { force: true }); await this.saveQueueToDisk(); } catch (recacheErr) { console.error(`[QueueManager] Error recaching post "${currentItem.title || 'Untitled'}":`, recacheErr); }
// Try sending two more times for (let retry = 1; retry <= 2; retry++) { console.log(`[QueueManager] Extra send attempt ${retry} of 2 for "${currentItem.title || 'Untitled'}"...`); await new Promise(resolve => setTimeout(resolve, 2000));
sendResult = await this.sendItemToServices(currentItem, postFunctions, 0);
if (isDeliveredToAll()) { console.log(`[QueueManager] Confirmed: Post "${currentItem.title || 'Untitled'}" went to all platforms after extra send ${retry}.`); return { success: true, item: currentItem, retriesUsed: retry }; }
if (hasAmbiguousError(sendResult)) { return await handleAmbiguousDelivery(sendResult, retry); } }
// If it fails those two extra sends: console.error(`[QueueManager] Post "${currentItem.title || 'Untitled'}" failed all extra sends.`);
// 1. Trigger the error for any failed platforms await this._notifyFailures( onFailure, currentItem, sendResult.errors, 'Failed to post to {service} after initial send and 2 retries' );
// 2. Delete the item from queue const failedItem = this.queueData.queue.splice(0, 1)[0]; await this.saveQueueToDisk(); console.log(`[QueueManager] Deleted failed item "${failedItem.title || 'Untitled'}" from front of queue.`);
// 3. Send the next one instead (prevent cascading beyond 1 fallback level) let nextItemResult = null; if (!isFallback && this.queueData.queue.length > 0) { console.log(`[QueueManager] Sending next item in queue instead...`); nextItemResult = await this.processPostWithRetries(postFunctions, onFailure, true); } else if (this.queueData.queue.length === 0) { console.log('[QueueManager] No other items in queue to send instead.'); }
// 4. And then requeue the failed post this.queueData.queue.push(failedItem); await this.saveQueueToDisk(); console.log(`[QueueManager] Requeued failed post "${failedItem.title || 'Untitled'}" to end of queue.`);
return { success: false, failedItem, retriesUsed: 2, requeued: true, nextItemResult }; } finally { if (!isFallback) { this.isProcessingPost = false; } } }
/** * Process the next queue post using stored or provided post functions */ async processNextPost(postFunctions = this.postFunctions, onFailure = this.onFailure) { return await this.processPostWithRetries(postFunctions, onFailure, false); }
/** * Start scheduler with multi-service support * @param {Object} postFunctions - Object mapping service names to post functions * @param {Function} onFailure - Failure handler callback * @returns {boolean} - Whether scheduler was started successfully */ startScheduler(postFunctions, onFailure) { if (this.scheduledTask) { this.scheduledTask.stop(); }
this.postFunctions = postFunctions; this.onFailure = onFailure;
try { this.scheduledTask = cron.schedule(this.cronSchedule, async () => { console.log('Running scheduled post task...');
for (let i = 0; i < this.imagesPerInterval; i++) { if (this.queueData.queue.length === 0) { console.log('Queue is empty, nothing to post'); break; }
const result = await this.processPostWithRetries(this.postFunctions, this.onFailure, false); // If queue is now empty or posting failed completely without next item, stop interval loop if (this.queueData.queue.length === 0) { break; } if (!result.success && (!result.nextItemResult || !result.nextItemResult.success)) { break; } } });
return true; } catch (error) { console.error('Error starting scheduler:', error); return false; } }
stopScheduler() { if (this.scheduledTask) { this.scheduledTask.stop(); this.scheduledTask = null; } if (this.autoSaveInterval) { clearInterval(this.autoSaveInterval); this.autoSaveInterval = null; } // Save queue one last time before stopping return this.saveQueueToDisk(); } /** * Clean up resources on application shutdown */ async shutdown() { this.stopScheduler(); return this.saveQueueToDisk(); }
/** * Toggle shuffle mode on/off * @returns {boolean} - New state of shuffle mode */ toggleShuffleMode() { this.shuffleMode = !this.shuffleMode; console.log(`Queue shuffle mode ${this.shuffleMode ? 'enabled' : 'disabled'}`); // Save the new shuffle state to disk this.saveQueueToDisk() .then(() => console.log('Shuffle mode state saved')) .catch(err => console.error('Error saving shuffle mode state:', err)); return this.shuffleMode; }
/** * Get current state of shuffle mode * @returns {boolean} - Current state of shuffle mode */ isShuffleModeEnabled() { return this.shuffleMode; }
/** * Shuffle the remaining items in the queue using age-weighted sampling * without replacement (Efraimidis-Spirakis / exponential race), weighing * older entries toward the front of the queue more frequently. * @returns {Promise<boolean>} - Whether shuffle was successful */ async shuffleQueue() { try { if (this.queueData.queue.length <= 1) { // No need to shuffle if queue is empty or has only one item return true; }
const queue = this.queueData.queue; const now = Date.now(); const timestamps = queue.map(item => { const parsed = item && item.timestamp ? Date.parse(item.timestamp) : NaN; return Number.isFinite(parsed) ? parsed : now; });
const minTs = Math.min(...timestamps); const maxTs = Math.max(...timestamps); const span = maxTs - minTs;
// Oldest item gets weight (1 + MAX_AGE_BONUS), newest gets weight 1 const MAX_AGE_BONUS = 4;
const weighted = queue.map((item, idx) => { const normalizedAge = span > 0 ? (maxTs - timestamps[idx]) / span : 0; const weight = 1 + normalizedAge * MAX_AGE_BONUS; // Uniform random in (0, 1) so Math.log(u) is always finite and negative const u = crypto.randomInt(1, 0x100000000) / 0x100000000; // Exponential race key: smaller key sorts toward the front of the queue const key = -Math.log(u) / weight; return { item, key }; });
weighted.sort((a, b) => a.key - b.key); for (let i = 0; i < weighted.length; i++) { queue[i] = weighted[i].item; }
console.log(`Queue shuffled with age weighting (${queue.length} items)`); await this.saveQueueToDisk(); return true; } catch (error) { console.error('Error shuffling queue:', error); return false; } }}
module.exports = new QueueManager();