UNPKG

@waboyz-baileys/jobs

Version:

55 lines (54 loc) 2.27 kB
import cron from 'node-cron'; import { promise as fastqPromise } from 'fastq'; function createProfilePictureQueue(logger, maxAgeMs, concurrency, batchSize) { return fastqPromise(async ({ storage }) => { try { const handler = storage.pps; if (!handler) return; logger?.info(`[CRON]: Fetching profile pictures...`); await handler.fetch(maxAgeMs, concurrency, batchSize); } catch (err) { logger?.error(`[CRON]: Failed to fetch profile pictures: ${err}`); } }, concurrency); } async function runProfilePictureFetch(storage, queue, logger) { try { logger?.info(`[CRON] Starting batch profile picture fetch...`); if (storage) { queue.push({ storage }).catch(() => { }); } await queue.drained(); logger?.info(`[CRON] Profile picture fetcher completed.`); } catch (err) { logger?.error(`[CRON]: Failed to fetch profile pictures: ${err}`); } } function getRandomTimeBetween(minHour, maxHour) { const hour = Math.floor(Math.random() * (maxHour - minHour + 1)) + minHour; const minute = Math.floor(Math.random() * 60); return { hour, minute }; } export function startGlobalProfilePictureFetcher(getStorage, logger, maxAgeMs = 7 * 24 * 60 * 60 * 1000, concurrency = 3, batchSize = 50) { const queue = createProfilePictureQueue(logger, maxAgeMs, concurrency, batchSize); const { hour, minute } = getRandomTimeBetween(3, 6); const cronExpr = `${minute} ${hour} * * *`; cron.schedule(cronExpr, () => { runProfilePictureFetch(getStorage(), queue, logger); }, { timezone: 'Europe/Istanbul' }); logger?.info(`[CRON] Global profile picture fetcher scheduled at ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')} every day.`); } export async function startPPsFetcher(storage, logger, maxAgeMs = 7 * 24 * 60 * 60 * 1000, concurrency = 3, batchSize = 50) { try { const queue = createProfilePictureQueue(logger, maxAgeMs, concurrency, batchSize); await runProfilePictureFetch(storage, queue, logger); } catch (err) { logger?.error(`[CRON]: Failed to fetch profile pictures: ${err}`); } }