File size: 13,435 Bytes
3760017
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
'use strict';

require('dotenv').config();

// Media is encrypted into a temp file before upload. If the drive that holds
// the temp folder is full, WhatsApp sends fail. MEDIA_TMP_DIR lets you point
// that temp folder at a drive with space. Set it before anything is sent.
const MEDIA_TMP_DIR = process.env.MEDIA_TMP_DIR || '';
if (MEDIA_TMP_DIR) {
  require('fs').mkdirSync(MEDIA_TMP_DIR, { recursive: true });
  process.env.TMP = process.env.TEMP = process.env.TMPDIR = MEDIA_TMP_DIR;
}

const fs = require('fs');
const os = require('os');
const path = require('path');
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');

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
const PORT = Number(process.env.PORT) || 3000;
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || '';
const COOLDOWN_MS = 5000;

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;

function sweepStaleMediaTemp() {
  const dir = os.tmpdir();
  let removed = 0;
  try {
    for (const name of fs.readdirSync(dir)) {
      if (!STALE_TEMP.test(name)) continue;
      const full = path.join(dir, name);
      try {
        if (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 sweep skipped:', e.message);
  }
  if (removed) console.log(`Removed ${removed} stale 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(os.tmpdir());
  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 (${os.tmpdir()}): 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;
const cooldown = new Map();

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;
          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;
  }
}

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 || '').trim();
  // Accepts "ABC12", "get ABC12", ".get ABC12", "dl ABC12", "code ABC12"
  const match = text.match(/^(?:[.!/]?(?:get|dl|code)\s+)?([A-Za-z0-9_-]{3,20})$/i);
  if (!match) return;

  const item = await db.findFile(match[1]);
  const explicit = /^[.!/]?(get|dl|code)\s/i.test(text);
  if (!item) {
    if (explicit) await s.sendMessage(jid, { text: '❌ Code not found. Please check the code and try again.' }, { quoted: m });
    return;
  }

  const now = Date.now();
  if (now - (cooldown.get(jid) || 0) < COOLDOWN_MS) return;
  if (cooldown.size > 1000) cooldown.clear();
  cooldown.set(jid, now);

  await s.sendMessage(jid, { text: `⏳ Sending *${item.title}*, please wait...` }, { quoted: m });

  try {
    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}*`;
    if (item.type === 'video') {
      await s.sendMessage(jid, { video: { url: item.url }, caption, mimetype: MIME[ext] || 'video/mp4' }, { quoted: m });
    } else {
      const fileName = `${item.title.replace(/[^\w.-]+/g, '_')}${ext}`;
      await s.sendMessage(
        jid,
        { document: { url: item.url }, mimetype: MIME[ext] || 'application/octet-stream', fileName, caption },
        { quoted: m }
      );
    }
    await db.markSent(item.code);
  } catch (e) {
    console.error(`Send failed for ${item.code}:`, e.message);
    await s.sendMessage(jid, { text: '⚠️ Could not send the file right now. Please try again later.' }, { quoted: m });
  }
}

// ---------------------------------------------------------------------------
// 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('/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.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';
  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 });
    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.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;
  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();
  sweepStaleMediaTemp();
  setInterval(sweepStaleMediaTemp, 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);
});