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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
'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);
});