e-subs / server.js
000x's picture
Upload 18 files
8a636d7 verified
Raw History Blame Contribute Delete
18 kB
'use strict';
require('dotenv').config();
const fs = require('fs');
const os = require('os');
const path = require('path');
// Baileys encrypts each media file into the temp folder before uploading.
// The app owns this folder: it is created automatically, cleaned on start and
// stop, and used for nothing else. Override with MEDIA_TMP_DIR if needed.
const MEDIA_TMP_DIR = path.resolve(process.env.MEDIA_TMP_DIR || path.join(os.tmpdir(), 'filebot-media'));
fs.mkdirSync(MEDIA_TMP_DIR, { recursive: true });
process.env.TMP = process.env.TEMP = process.env.TMPDIR = MEDIA_TMP_DIR;
const crypto = require('crypto');
const express = require('express');
const pino = require('pino');
const QRCode = require('qrcode');
const {
default: makeWASocket,
DisconnectReason,
fetchLatestBaileysVersion,
makeCacheableSignalKeyStore,
} = require('@whiskeysockets/baileys');
const db = require('./db');
const { createBot, limitFor } = require('./bot');
const { runDeletes } = require('./sweeper');
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
const PORT = Number(process.env.PORT) || 3000;
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || '';
const ADMIN_PHONES = String(process.env.ADMIN_PHONES || '').split(',').map((p) => p.replace(/\D/g, '')).filter(Boolean);
// The welcome message does not include the file list link.
const bot = createBot({ db, log: console, cooldownMs: 5000, maxConcurrent: 3 });
let botNumber = String(process.env.BOT_NUMBER || '').replace(/\D/g, '');
if (ADMIN_PASSWORD.length < 8) {
console.error('ADMIN_PASSWORD is missing or shorter than 8 characters. Set it in .env and restart.');
process.exit(1);
}
const MIME = {
'.mp4': 'video/mp4', '.mkv': 'video/x-matroska', '.mov': 'video/quicktime',
'.pdf': 'application/pdf', '.zip': 'application/zip', '.mp3': 'audio/mpeg',
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.srt': 'text/plain',
};
const GB = 1024 ** 3;
const MB = 1024 ** 2;
// ---------------------------------------------------------------------------
// Temp-folder housekeeping
// Baileys leaves "<type><id>-enc" / "-original" files behind when a send
// crashes. Remove those older than 15 minutes so they stop filling the disk.
// ---------------------------------------------------------------------------
const STALE_TEMP = /^(image|video|audio|document|sticker)[0-9a-z]+-(enc|original)$/i;
// Remove leftover encrypted media files. all=true removes every one now
// (used at start and stop); otherwise only ones older than 15 minutes.
function sweepStaleMediaTemp(all = false) {
let removed = 0;
try {
fs.mkdirSync(MEDIA_TMP_DIR, { recursive: true }); // recreate if someone deleted it
for (const name of fs.readdirSync(MEDIA_TMP_DIR)) {
if (!STALE_TEMP.test(name)) continue;
const full = path.join(MEDIA_TMP_DIR, name);
try {
if (all || Date.now() - fs.statSync(full).mtimeMs > 15 * 60 * 1000) {
fs.unlinkSync(full);
removed += 1;
}
} catch { /* in use or already gone */ }
}
} catch (e) {
console.error('Temp cleanup skipped:', e.message);
}
if (removed) console.log(`Removed ${removed} media temp file(s).`);
}
// Before sending a URL file, check the temp folder has room for it.
// Returns an error message, or null when it is fine (or the size is unknown).
async function checkTempSpace(url) {
if (typeof fs.statfsSync !== 'function') return null;
let size = 0;
try {
const head = await fetch(url, { method: 'HEAD', redirect: 'follow', signal: AbortSignal.timeout(10000) });
size = Number(head.headers.get('content-length')) || 0;
} catch { /* server does not answer HEAD: try the send anyway */ }
if (!size) return null;
const st = fs.statfsSync(MEDIA_TMP_DIR);
const free = Number(st.bavail) * Number(st.bsize);
const needed = size + 100 * MB;
if (free >= needed) return null;
return `Not enough free space for the temp folder (${MEDIA_TMP_DIR}): need about ${(needed / GB).toFixed(2)} GB, free ${(free / GB).toFixed(2)} GB. Free up disk space or set MEDIA_TMP_DIR to a drive with room.`;
}
// ---------------------------------------------------------------------------
// WhatsApp bot
// ---------------------------------------------------------------------------
let sock = null;
let connected = false;
let qrImage = null;
let starting = false;
let shuttingDown = false;
let server = null;
function scheduleStart(ms) {
if (shuttingDown) return;
setTimeout(() => startBot().catch((e) => {
console.error('Start failed:', e.message);
scheduleStart(8000);
}), ms);
}
async function startBot() {
if (starting || shuttingDown) return;
starting = true;
try {
const { state, saveCreds } = await db.useSqlAuthState();
let version;
try { ({ version } = await fetchLatestBaileysVersion()); } catch { /* use library default */ }
const logger = pino({ level: 'silent' });
const s = makeWASocket({
version,
logger,
printQRInTerminal: false,
markOnlineOnConnect: false,
syncFullHistory: false,
auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, logger) },
});
sock = s;
// Only the current socket may write credentials (stops an old socket
// from re-saving a session after Unlink).
s.ev.on('creds.update', () => { if (s === sock) saveCreds().catch((e) => console.error('Save creds failed:', e.message)); });
s.ev.on('connection.update', async ({ connection, lastDisconnect, qr }) => {
if (s !== sock) return; // old socket
try {
if (qr) qrImage = await QRCode.toDataURL(qr);
if (connection === 'open') {
connected = true;
if (s.user?.id) botNumber = String(s.user.id).split(':')[0].split('@')[0];
qrImage = null;
console.log('WhatsApp connected.');
}
if (connection === 'close') {
connected = false;
qrImage = null;
sock = null;
const code = lastDisconnect?.error?.output?.statusCode;
const loggedOut = code === DisconnectReason.loggedOut;
console.log(`Connection closed (code ${code}).`);
if (loggedOut) await db.clearAuth();
scheduleStart(loggedOut ? 1000 : 3000);
}
} catch (e) {
console.error('connection.update error:', e.message);
}
});
s.ev.on('messages.upsert', ({ messages, type }) => {
if (type !== 'notify') return;
for (const m of messages) onMessage(s, m).catch((e) => console.error('Message error:', e.message));
});
} finally {
starting = false;
}
}
// Sends a file's WhatsApp message (document or video) from its stored URL.
async function sendItem(s, jid, quoted, item) {
const problem = await checkTempSpace(item.url);
if (problem) throw new Error(problem);
const ext = path.extname(new URL(item.url).pathname).toLowerCase();
const caption = `📁 *${item.title}*`;
let sent;
if (item.type === 'video') {
sent = await s.sendMessage(jid, { video: { url: item.url }, caption, mimetype: MIME[ext] || 'video/mp4' }, { quoted });
} else {
const fileName = `${item.title.replace(/[^\w.-]+/g, '_')}${ext}`;
sent = await s.sendMessage(
jid,
{ document: { url: item.url }, mimetype: MIME[ext] || 'application/octet-stream', fileName, caption },
{ quoted }
);
}
return sent.key;
}
async function onMessage(s, m) {
if (!m.message || m.key.fromMe) return;
const jid = m.key.remoteJid || '';
if (!/@(s\.whatsapp\.net|lid)$/.test(jid)) return; // private chats only
const text = m.message.conversation || m.message.extendedTextMessage?.text || '';
const id = jid.split('@')[0].split(':')[0];
const io = {
reply: async (t) => (await s.sendMessage(jid, { text: t }, { quoted: m })).key,
edit: async (key, t) => { await s.sendMessage(jid, { text: t, edit: key }); },
sendFile: (item) => sendItem(s, jid, m, item),
schedule: (keys, at) => db.scheduleDeletes(keys.map((k) => ({ jid: k?.remoteJid, msgId: k?.id })), new Date(at)),
};
await bot.handle({ id, text, io }).catch((e) => console.error('Message error:', e.message));
}
// ---------------------------------------------------------------------------
// Admin API
// ---------------------------------------------------------------------------
const app = express();
app.set('trust proxy', 1);
app.use(express.json({ limit: '100kb' }));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/catalog', (req, res) => res.sendFile(path.join(__dirname, 'public', 'catalog.html')));
// Public file list. Codes and titles only. Each item opens WhatsApp with ".dl CODE" filled in.
app.get('/api/catalog', async (req, res) => {
try {
const rows = await db.listCatalog();
const items = rows.map((r) => ({
code: r.code,
title: r.title,
type: r.type,
link: botNumber ? `https://wa.me/${botNumber}?text=${encodeURIComponent('.dl ' + r.code)}` : null,
}));
res.set('Cache-Control', 'no-store');
res.json({ botNumber: botNumber || null, items });
} catch (e) {
console.error('Catalog error:', e.message);
res.status(500).json({ error: 'Could not load the file list.' });
}
});
app.get('/health', (req, res) => res.json({ status: 'ok', whatsapp: connected }));
const safeEq = (a, b) => {
const x = Buffer.from(String(a));
const y = Buffer.from(String(b));
return x.length === y.length && crypto.timingSafeEqual(x, y);
};
const failed = new Map();
function auth(req, res, next) {
const rec = failed.get(req.ip) || { n: 0, until: 0 };
if (Date.now() < rec.until) {
return res.status(429).json({ error: 'Too many wrong attempts. Try again in a few minutes.' });
}
if (safeEq(req.get('x-admin-key') || '', ADMIN_PASSWORD)) {
failed.delete(req.ip);
return next();
}
rec.n += 1;
if (rec.n >= 5) { rec.until = Date.now() + 10 * 60 * 1000; rec.n = 0; }
failed.set(req.ip, rec);
return res.status(401).json({ error: 'Wrong password.' });
}
app.use('/api', auth);
const wrap = (fn) => (req, res) => Promise.resolve(fn(req, res)).catch((e) => {
console.error('API error:', e.message);
res.status(500).json({ error: 'Server error. Check the console log.' });
});
app.get('/api/status', (req, res) => res.json({ connected, qr: qrImage }));
app.post('/api/pair', wrap(async (req, res) => {
const phone = String(req.body?.phone || '').replace(/\D/g, '');
if (phone.length < 10 || phone.length > 15) {
return res.status(400).json({ error: 'Use country code + number, e.g. 94771234567.' });
}
if (!sock) return res.status(503).json({ error: 'Bot is starting. Try again in 10 seconds.' });
if (connected || sock.authState?.creds?.registered) {
return res.status(409).json({ error: 'Already linked. Use "Unlink" first to link a different number.' });
}
try {
const code = await sock.requestPairingCode(phone);
return res.json({ code });
} catch (e) {
return res.status(500).json({ error: `Could not create pairing code: ${e.message}` });
}
}));
app.post('/api/unlink', wrap(async (req, res) => {
const old = sock;
sock = null;
connected = false;
qrImage = null;
try { await old?.logout(); } catch { /* already closed */ }
try { old?.end(undefined); } catch { /* noop */ }
await db.clearAuth();
scheduleStart(500);
res.json({ ok: true });
}));
app.get('/api/files', wrap(async (req, res) => res.json(await db.listFiles())));
app.get('/api/stats', wrap(async (req, res) => res.json(await db.stats())));
app.get('/api/users', wrap(async (req, res) => {
const q = String(req.query.q || '').replace(/\D/g, '');
const [users, settings] = await Promise.all([db.listUsers(q), db.getSettings()]);
// limit: null means unlimited (admins)
res.json(users.map((u) => {
const l = limitFor(u, settings.limits);
return { ...u, limit: Number.isFinite(l) ? l : null };
}));
}));
app.get('/api/settings', wrap(async (req, res) => res.json(await db.getSettings())));
app.put('/api/settings', wrap(async (req, res) => {
const patch = {};
const body = req.body || {};
if (body.limits) {
patch.limits = {};
for (const role of ['free', 'premium', 'admin']) {
if (body.limits[role] === undefined) continue;
const v = body.limits[role];
if (v === null || v === '') {
if (role !== 'admin') return res.status(400).json({ error: `${role} needs a number.` });
patch.limits[role] = null; // unlimited
continue;
}
const n = Number(v);
if (!Number.isInteger(n) || n < 0 || n > 10000) {
return res.status(400).json({ error: `${role} limit must be a whole number from 0 to 10000.` });
}
patch.limits[role] = n;
}
}
if (body.autoDeleteHours !== undefined) {
const n = Number(body.autoDeleteHours);
if (!Number.isInteger(n) || n < 0 || n > 720) {
return res.status(400).json({ error: 'Auto-delete hours must be a whole number from 0 (never) to 720.' });
}
patch.autoDeleteHours = n;
}
res.json(await db.setSettings(patch));
}));
app.patch('/api/users/:id', wrap(async (req, res) => {
const id = String(req.params.id).replace(/\D/g, '');
const patch = {};
if (req.body?.role !== undefined) {
if (!['free', 'premium', 'admin'].includes(req.body.role)) return res.status(400).json({ error: 'Role must be free, premium or admin.' });
patch.role = req.body.role;
}
if (req.body?.blocked !== undefined) patch.blocked = req.body.blocked === true;
if (req.body?.dailyLimit !== undefined) {
const v = req.body.dailyLimit;
if (v === null || v === '') patch.dailyLimit = null;
else {
const n = Number(v);
if (!Number.isInteger(n) || n < 0 || n > 10000) return res.status(400).json({ error: 'Daily limit must be a whole number from 0 to 10000.' });
patch.dailyLimit = n;
}
}
const user = await db.updateUser(id, patch);
if (!user) return res.status(404).json({ error: 'User not found.' });
return res.json(user);
}));
app.post('/api/files', wrap(async (req, res) => {
const title = String(req.body?.title || '').trim();
const url = String(req.body?.url || '').trim();
const type = req.body?.type === 'video' ? 'video' : 'document';
const deleteAfterSend = req.body?.deleteAfterSend === true;
let code = String(req.body?.code || '').trim();
if (!title || title.length > 100) return res.status(400).json({ error: 'Title is required (max 100 characters).' });
try {
const u = new URL(url);
if (!['http:', 'https:'].includes(u.protocol)) throw new Error('bad protocol');
} catch {
return res.status(400).json({ error: 'Enter a valid http(s) file URL.' });
}
if (code) {
if (!/^[A-Za-z0-9_-]{3,20}$/.test(code)) {
return res.status(400).json({ error: 'Code must be 3-20 letters, numbers, - or _.' });
}
if (await db.findFile(code)) return res.status(409).json({ error: 'That code is already used.' });
} else {
code = await makeCode();
}
try {
const item = await db.addFile({ code, title, url, type, deleteAfterSend });
return res.status(201).json(item);
} catch (e) {
if (e.code === '23505') return res.status(409).json({ error: 'That code is already used.' });
throw e;
}
}));
app.patch('/api/files/:code', wrap(async (req, res) => {
if (typeof req.body?.listed !== 'boolean') return res.status(400).json({ error: 'listed must be true or false.' });
const item = await db.setListed(req.params.code, req.body.listed);
if (!item) return res.status(404).json({ error: 'Code not found.' });
return res.json(item);
}));
app.delete('/api/files/:code', wrap(async (req, res) => {
const n = await db.deleteFile(req.params.code);
if (n === 0) return res.status(404).json({ error: 'Code not found.' });
return res.json({ ok: true });
}));
async function makeCode() {
const abc = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
let code;
do {
code = Array.from(crypto.randomBytes(5), (b) => abc[b % abc.length]).join('');
} while (await db.findFile(code));
return code;
}
// ---------------------------------------------------------------------------
// Boot + shutdown
// ---------------------------------------------------------------------------
// A full disk makes Baileys' temp-file stream emit an error nobody listens to,
// which would kill the whole app (dashboard included). Log it and keep running.
process.on('uncaughtException', (err) => {
if (err.code === 'ENOSPC') {
console.error('DISK FULL: a write failed with ENOSPC. Free space on the temp drive or set MEDIA_TMP_DIR.');
} else {
console.error('Uncaught error:', err.message);
}
});
function shutdown() {
shuttingDown = true;
sweepStaleMediaTemp(true);
try { sock?.end(undefined); } catch { /* noop */ }
const done = () => db.pool.end().catch(() => {}).finally(() => process.exit(0));
if (server) server.close(done); else done();
setTimeout(() => process.exit(0), 5000).unref();
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
process.on('unhandledRejection', (r) => console.error('Unhandled rejection:', r?.message || r));
(async () => {
await db.init();
for (const phone of ADMIN_PHONES) {
await db.touchUser(phone);
await db.updateUser(phone, { role: 'admin' });
}
setInterval(() => runDeletes({
db,
isConnected: () => connected && !!sock,
sendDelete: (key) => sock.sendMessage(key.remoteJid, { delete: key }),
log: console,
}).catch((e) => console.error('Auto-delete pass failed:', e.message)), 60 * 1000).unref();
sweepStaleMediaTemp(true);
setInterval(() => sweepStaleMediaTemp(false), 30 * 60 * 1000).unref();
server = app.listen(PORT, '0.0.0.0', () => console.log(`Dashboard: http://localhost:${PORT}`));
scheduleStart(0);
})().catch((e) => {
console.error('Startup failed:', e.message);
process.exit(1);
});