'use strict'; // Message handling, separated from the WhatsApp connection so it can be tested. // `io` is supplied by the caller: reply(text) -> key, edit(key, text), sendFile(item). const crypto = require('crypto'); const SINHALA = /[඀-෿]/; const CODE_RE = /^(?:[.!/]?(?:get|dl|code)\s+)?([A-Za-z0-9_-]{3,20})$/i; const DAY_MS = 24 * 60 * 60 * 1000; const MSG = { welcome: { si: 'ආයුබෝවන්! 👋 ගොනුවක් ලබා ගැනීමට `.dl` සහ ගොනුවේ ID එක එවන්න.\nඋදා: .dl ABC12{catalog}', en: 'Welcome! 👋 To get a file, send `.dl` and the file ID.\nExample: .dl ABC12{catalog}', }, catalogLine: { si: '\n\nගොනු ලැයිස්තුව: {url}', en: '\n\nFile list: {url}', }, blocked: { si: '🚫 ඔබගේ ගිණුම අත්හිටුවා ඇත. වැඩි විස්තර සඳහා පරිපාලකයා අමතන්න.', en: '🚫 Your account is suspended. Please contact the admin.', }, notFound: { si: '❌ මෙම කේතය සොයාගත නොහැක. නැවත පරීක්ෂා කර බලන්න.', en: '❌ Code not found. Please check it and try again.', }, limit: { si: '⏳ අද දින සඳහා ඔබගේ බාගත කිරීමේ සීමාව ({limit}) සම්පූර්ණයි. පැය 24කින් පසු නැවත උත්සාහ කරන්න.', en: "⏳ You've used today's {limit} downloads. Try again in 24 hours.", }, preparing: { si: '⏳ *{title}* සූදානම් වෙමින්...', en: '⏳ Preparing *{title}*...', }, done: { si: '✅ *{title}* යවන ලදී. {left}{note}', en: '✅ Sent *{title}*. {left}{note}', }, deleteNote: { si: '\n⏱ පැය {hours}කින් මෙම පණිවිඩය මැකේ.', en: '\n⏱ This message will be deleted in {hours} hours.', }, leftToday: { si: 'අද ඉතිරි: {n}', en: 'Left today: {n}', }, error: { si: '⚠️ දැනට ගොනුව යැවිය නොහැක. මිනිත්තු කිහිපයකින් නැවත උත්සාහ කරන්න. (ref: {ref})', en: '⚠️ Could not send right now. Please try again in a few minutes. (ref: {ref})', }, langSet: { si: 'භාෂාව සිංහල ලෙස සකසන ලදී. ✅', en: 'Language set to English. ✅', }, help: { si: 'කේතය එවන්න (උදා: ABC12). භාෂාව: /lang si | /lang en', en: 'Send a code (e.g. ABC12). Language: /lang si | /lang en', }, }; function t(key, lang, vars = {}) { const set = MSG[key]; const text = set[lang] || set.en; return text.replace(/\{(\w+)\}/g, (_, k) => (vars[k] ?? '')); } // Downloads allowed per 24h. A user's own dailyLimit overrides the role limit. // Returns Infinity for unlimited. function limitFor(user, limits) { if (user.dailyLimit != null) return user.dailyLimit; const v = limits[user.role]; if (v === null) return Infinity; return v ?? 0; } function createBot({ db, log = console, cooldownMs = 5000, maxConcurrent = 3, catalogUrl = null }) { const cooldown = new Map(); // Simple concurrency limit: at most maxConcurrent sends at once. Others wait. let active = 0; const waiting = []; const acquire = () => { if (active < maxConcurrent) { active += 1; return Promise.resolve(); } return new Promise((resolve) => waiting.push(resolve)); }; const release = () => { const next = waiting.shift(); if (next) next(); else active -= 1; }; // Edits the progress message; if WhatsApp refuses the edit, sends a new message instead. // Returns the key of whichever message now shows the text. async function safeEdit(io, key, text) { try { await io.edit(key, text); return key; } catch { return io.reply(text); } } async function adminCommand(cmd, args, io) { const [a1, a2] = args.trim().split(/\s+/); const phone = (a1 || '').replace(/\D/g, ''); if (cmd === 'stats') { const s = await db.stats(); return io.reply( `Users: ${s.users} (premium ${s.premium}, admins ${s.admins}, blocked ${s.blocked})\n` + `Downloads today: ${s.downloads_today} · total: ${s.downloads_total}\n` + `Files: ${s.files}` ); } if (cmd === 'grant') { const role = (a2 || '').toLowerCase(); if (!phone || !['free', 'premium', 'admin'].includes(role)) return io.reply('Usage: /grant free|premium|admin'); const user = await db.updateUser(phone, { role }); return io.reply(user ? `✅ ${phone} is now ${role}.` : `User ${phone} not found. They must message the bot first.`); } if (cmd === 'block' || cmd === 'unblock') { if (!phone) return io.reply(`Usage: /${cmd} `); const user = await db.updateUser(phone, { blocked: cmd === 'block' }); return io.reply(user ? `✅ ${phone} ${cmd === 'block' ? 'blocked' : 'unblocked'}.` : `User ${phone} not found.`); } return io.reply('Admin commands: /stats · /grant free|premium|admin · /block · /unblock '); } async function handle({ id, text, io }) { const clean = String(text || '').trim(); if (!clean) return; const { user, isNew } = await db.touchUser(id, SINHALA.test(clean) ? 'si' : null); const lang = user.lang; if (isNew) { const catalog = catalogUrl ? t('catalogLine', lang, { url: catalogUrl }) : ''; await io.reply(t('welcome', lang, { catalog })); } if (user.blocked) return io.reply(t('blocked', lang)); const cmd = clean.match(/^\/(\w+)\s*(.*)$/); if (cmd) { const name = cmd[1].toLowerCase(); if (name === 'lang') { const v = cmd[2].trim().toLowerCase(); if (v !== 'si' && v !== 'en') return io.reply(t('help', lang)); await db.updateUser(id, { lang: v }); return io.reply(t('langSet', v)); } if (name === 'help') return io.reply(t('help', lang)); if (user.role === 'admin') return adminCommand(name, cmd[2], io); } const match = clean.match(CODE_RE); if (!match) return; const settings = await db.getSettings(); const explicit = /^[.!/]?(get|dl|code)\s/i.test(clean); const item = await db.findFile(match[1]); if (!item) { if (explicit) await io.reply(t('notFound', lang)); return; } const now = Date.now(); if (now - (cooldown.get(id) || 0) < cooldownMs) return; if (cooldown.size > 1000) cooldown.clear(); cooldown.set(id, now); const limit = limitFor(user, settings.limits); let used = 0; if (limit !== Infinity) { used = await db.downloadsToday(id); if (used >= limit) return io.reply(t('limit', lang, { limit })); } const progress = await io.reply(t('preparing', lang, { title: item.title })); await acquire(); try { const fileKey = await io.sendFile(item); await db.recordDownload(id, item.code); await db.recordSend(item.code); const left = limit === Infinity ? '' : t('leftToday', lang, { n: limit - used - 1 }); const hours = settings.autoDeleteHours; const note = hours > 0 ? t('deleteNote', lang, { hours }) : ''; const doneKey = await safeEdit(io, progress, t('done', lang, { title: item.title, left, note })); // Delete the file message and the status message for everyone after the set hours. if (io.schedule && hours > 0) { try { await io.schedule([fileKey, doneKey], Date.now() + hours * 3600000); } catch (e) { log.error('Could not schedule auto-delete:', e.message); } } } catch (e) { const ref = 'E-' + crypto.randomInt(100, 999); log.error(`Send failed for ${item.code} (${ref}):`, e.message); await safeEdit(io, progress, t('error', lang, { ref })); } finally { release(); } } return { handle, MSG, t }; } module.exports = { createBot, t, limitFor, CODE_RE, SINHALA };