Spaces:
Runtime error

Brozy123 commited on
Commit
e2bc2b2
·
verified ·
1 Parent(s): 0ebb36c

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +9 -608
server.js CHANGED
@@ -1,615 +1,16 @@
1
  const express = require('express');
2
  const path = require('path');
3
- const fs = require('fs');
4
- const crypto = require('crypto');
5
-
6
- console.log(">>> [MODULE] server.js: Initializing...");
7
  const app = express();
8
- const port = process.env.PORT || 7860;
9
-
10
-
11
- // Discord OAuth2 Config — reads from multiple possible env var names
12
- const CLIENT_SECRET = process.env.CLIENT_SECRET || process.env.DISCORD_CLIENT_SECRET || '';
13
- const REDIRECT_URI = process.env.REDIRECT_URI || process.env.DISCORD_REDIRECT_URL || '';
14
-
15
- // Store reference to the Discord client (set from index.js)
16
- let discordClient = null;
17
- let commandsDataRef = null;
18
-
19
- // Session store (persisted to disk so logins survive restarts)
20
- const storage = require('./storage');
21
- const SESSION_FILE = path.join(storage.PERSISTENT_DIR, 'sessions.json');
22
- let sessions = new Map();
23
-
24
- // Load sessions from disk on startup
25
- try {
26
- if (fs.existsSync(SESSION_FILE)) {
27
- const content = fs.readFileSync(SESSION_FILE, 'utf8').trim();
28
- if (content) {
29
- const raw = JSON.parse(content);
30
- if (raw && typeof raw === 'object') {
31
- sessions = new Map(Object.entries(raw));
32
- console.log(`[*] Dashboard: Loaded ${sessions.size} persistent session(s).`);
33
- }
34
- }
35
- }
36
- } catch (e) {
37
- console.error(`[*] Dashboard: Failed to load sessions: ${e.message}`);
38
- }
39
- console.log("[*] Dashboard: Session system initialized.");
40
-
41
- function saveSessions() {
42
- try {
43
- const dir = path.dirname(SESSION_FILE);
44
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
45
- const obj = Object.fromEntries(sessions);
46
- fs.writeFileSync(SESSION_FILE, JSON.stringify(obj), 'utf8');
47
- } catch (e) {}
48
- }
49
-
50
- // In-memory log buffer
51
- const logBuffer = [];
52
- const MAX_LOGS = 200;
53
-
54
- let isHijacked = false;
55
- function hijackConsole() {
56
- if (isHijacked) return;
57
- const origLog = console.log;
58
- const origErr = console.error;
59
- console.log = (...args) => {
60
- const line = args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
61
- logBuffer.push(line);
62
- if (logBuffer.length > MAX_LOGS) logBuffer.shift();
63
- origLog.apply(console, args);
64
- };
65
- console.error = (...args) => {
66
- const line = '[Error] ' + args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
67
- logBuffer.push(line);
68
- if (logBuffer.length > MAX_LOGS) logBuffer.shift();
69
- origErr.apply(console, args);
70
- };
71
- isHijacked = true;
72
- }
73
-
74
- app.use(express.json());
75
-
76
- function hasDashboardPermissions(permissionBits) {
77
- try {
78
- const perms = BigInt(permissionBits || '0');
79
- return (perms & BigInt(0x20)) !== BigInt(0) || (perms & BigInt(0x8)) !== BigInt(0);
80
- } catch (e) {
81
- return false;
82
- }
83
- }
84
-
85
- // --- Helper: Get redirect URI ---
86
- function getRedirectUri(req) {
87
- if (REDIRECT_URI) return REDIRECT_URI;
88
-
89
- // Fallback: If we have a request object, use it to build the URI dynamically
90
- if (req) {
91
- const host = req.get('host');
92
- const protocol = req.protocol === 'http' && host.includes('.hf.space') ? 'https' : req.protocol;
93
- const path = req.path === '/' ? '/' : '/callback';
94
- return `${protocol}://${host}${path}`;
95
- }
96
-
97
- const spaceId = process.env.SPACE_ID;
98
- if (spaceId) {
99
- const host = spaceId.includes('/') ? spaceId.replace('/', '-').toLowerCase() : spaceId.toLowerCase();
100
- return `https://${host}.hf.space/callback`;
101
- }
102
- return `http://localhost:${port}/callback`;
103
- }
104
-
105
- // --- Helper: Get Client ID from bot ---
106
- function getClientId() {
107
- return discordClient?.user?.id || process.env.CLIENT_ID || process.env.DISCORD_CLIENT_ID || '';
108
- }
109
-
110
- // --- Helper: Parse session cookie ---
111
- function getSession(req) {
112
- const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
113
- const [k, v] = c.trim().split('=');
114
- if (k && v) acc[k] = v;
115
- return acc;
116
- }, {});
117
- const sid = cookies['fb_session'];
118
- if (sid && sessions.has(sid)) return sessions.get(sid);
119
- return null;
120
- }
121
-
122
- // --- Auth Middleware ---
123
- function requireAuth(req, res, next) {
124
- const session = getSession(req);
125
- if (session && session.user) return next();
126
- res.status(401).json({ error: 'Unauthorized' });
127
- }
128
-
129
- // --- Attach user to req ---
130
- app.use((req, res, next) => {
131
- req.dashSession = getSession(req);
132
- next();
133
- });
134
-
135
- // --- Static Assets ---
136
- app.get('/', (req, res) => {
137
- // If we get an OAuth code on the root route, handle it using the root as the redirect_uri
138
- if (req.query.code) {
139
- console.log("[Dashboard] Received OAuth code on root route, handling...");
140
- return handleOAuthCallback(req, res, getRedirectUri(req));
141
- }
142
- res.sendFile(path.join(__dirname, 'dashboard.html'));
143
- });
144
- app.get('/logo.png', (req, res) => {
145
- const logo = path.join(__dirname, 'logo.png');
146
- if (fs.existsSync(logo)) res.sendFile(logo);
147
- else res.status(404).send('Not found');
148
- });
149
-
150
- // Returns 200 as long as the web server is running.
151
- // This prevents Hugging Face and other platforms from restarting the space
152
- // while the Discord bot is still performing its initial connection handshake.
153
- app.get('/healthz', (req, res) => {
154
- const discordReady = !!(discordClient && discordClient.isReady && discordClient.isReady());
155
- return res.status(200).json({
156
- ok: true,
157
- webReady: true,
158
- discordReady: discordReady,
159
- guilds: discordReady ? (discordClient.guilds?.cache?.size || 0) : 0
160
- });
161
- });
162
-
163
- app.get('/tos', (req, res) => {
164
- res.sendFile(path.join(__dirname, 'tos.html'));
165
- });
166
-
167
- app.get('/privacy', (req, res) => {
168
- res.sendFile(path.join(__dirname, 'privacy.html'));
169
- });
170
-
171
- // --- Discord OAuth2: Step 1 — Redirect to Discord ---
172
- app.get('/auth/login', (req, res) => {
173
- const clientId = getClientId();
174
- const redirect = encodeURIComponent(getRedirectUri(req));
175
- console.log(`[Dashboard] Starting OAuth login. Redirect URI: ${getRedirectUri(req)}`);
176
- const url = `https://discord.com/api/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`;
177
- res.redirect(url);
178
- });
179
-
180
- async function fetchWithRetry(url, options, retries = 3) {
181
- const proxyBase = process.env.DISCORD_BASE_URL ? process.env.DISCORD_BASE_URL.replace(/\/$/, '') : 'https://discord.com';
182
- const endpoints = [
183
- proxyBase,
184
- 'https://discord.com',
185
- 'https://canary.discord.com',
186
- 'https://ptb.discord.com'
187
- ];
188
-
189
- for (let i = 0; i < endpoints.length; i++) {
190
- const controller = new AbortController();
191
- const timeoutId = setTimeout(() => controller.abort(), 20000); // 20s timeout
192
-
193
- try {
194
- let targetUrl = url;
195
- const currentBase = endpoints[i];
196
-
197
- // Only swap if it's a discord API call
198
- if (url.includes('discord.com/api')) {
199
- targetUrl = url.replace('https://discord.com', currentBase);
200
- console.log(`[Dashboard] Connection Attempt ${i + 1} via ${new URL(currentBase).hostname}...`);
201
- }
202
-
203
- const res = await fetch(targetUrl, {
204
- ...options,
205
- signal: controller.signal
206
- });
207
- clearTimeout(timeoutId);
208
-
209
- if (!res.ok) {
210
- const text = await res.text().catch(() => '');
211
- console.warn(`[Dashboard] API returned ${res.status} from ${new URL(currentBase).hostname}`);
212
- if (i === endpoints.length - 1) throw new Error(`HTTP ${res.status}: ${text}`);
213
- continue; // Try next endpoint
214
- }
215
- return res;
216
- } catch (err) {
217
- clearTimeout(timeoutId);
218
- const isTimeout = err.name === 'AbortError';
219
- console.warn(`[Dashboard] Attempt ${i + 1} (${new URL(endpoints[i]).hostname}) failed: ${isTimeout ? 'Timeout' : err.message}`);
220
-
221
- if (i === endpoints.length - 1) throw err;
222
-
223
- // Short delay before next endpoint
224
- await new Promise(r => setTimeout(r, 1000));
225
- }
226
- }
227
- }
228
-
229
- // --- Discord OAuth2: Step 2 — Callback from Discord ---
230
- // Support both /callback and /auth/callback to match any Discord redirect config
231
- async function handleOAuthCallback(req, res, overrideRedirectUri) {
232
- const { code, error, error_description } = req.query;
233
-
234
- if (error) {
235
- console.error(`[Dashboard] Discord returned error: ${error} (${error_description})`);
236
- return res.redirect(`/?error=${error}`);
237
- }
238
-
239
- if (!code) {
240
- console.warn(`[Dashboard] No code found in query parameters. URL: ${req.originalUrl}`);
241
- return res.redirect('/?error=no_code');
242
- }
243
-
244
- // Ensure overrideRedirectUri is a string and not the 'next' function from Express
245
- const usedRedirectUri = (typeof overrideRedirectUri === 'string') ? overrideRedirectUri : getRedirectUri(req);
246
- console.log(`[Dashboard] Handling OAuth callback. Code: ${code.substring(0, 5)}... Redirect URI: ${usedRedirectUri}`);
247
-
248
- if (!CLIENT_SECRET) {
249
- console.error('[Dashboard] CRITICAL: CLIENT_SECRET is missing from environment variables.');
250
- return res.redirect('/?error=server_error');
251
- }
252
-
253
- try {
254
- console.log(`[Dashboard] Exchanging code for token... (Redirect URI: ${getRedirectUri()})`);
255
- // Exchange code for token
256
- const tokenRes = await fetchWithRetry('https://discord.com/api/oauth2/token', {
257
- method: 'POST',
258
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
259
- body: new URLSearchParams({
260
- client_id: getClientId(),
261
- client_secret: CLIENT_SECRET,
262
- grant_type: 'authorization_code',
263
- code,
264
- redirect_uri: usedRedirectUri
265
- })
266
- });
267
-
268
- const tokenData = await tokenRes.json();
269
- if (!tokenData.access_token) {
270
- console.error('[Dashboard] Token exchange failed:', tokenData);
271
- return res.redirect('/?error=token_failed');
272
- }
273
-
274
- console.log(`[Dashboard] Token received. Fetching user profile...`);
275
- // Fetch user profile
276
- const userRes = await fetchWithRetry('https://discord.com/api/users/@me', {
277
- headers: { Authorization: `Bearer ${tokenData.access_token}` }
278
- });
279
- const user = await userRes.json();
280
- if (!user.id) {
281
- console.error('[Dashboard] Failed to fetch user profile:', user);
282
- return res.redirect('/?error=user_failed');
283
- }
284
-
285
- // Fetch user guilds
286
- console.log(`[Dashboard] Fetching guilds for user ${user.username} (${user.id})...`);
287
- const guildsRes = await fetchWithRetry('https://discord.com/api/users/@me/guilds', {
288
- headers: { Authorization: `Bearer ${tokenData.access_token}` }
289
- });
290
- const userGuilds = await guildsRes.json();
291
-
292
- if (!Array.isArray(userGuilds)) {
293
- console.error('[Dashboard] Failed to fetch guilds:', userGuilds);
294
- } else {
295
- console.log(`[Dashboard] Found ${userGuilds.length} guilds for user.`);
296
- }
297
-
298
- // Create session
299
- const sid = crypto.randomBytes(32).toString('hex');
300
- sessions.set(sid, {
301
- user: {
302
- id: user.id,
303
- username: user.username,
304
- avatar: user.avatar
305
- ? `https://cdn.discord.com/avatars/${user.id}/${user.avatar}.png`
306
- : `https://cdn.discord.com/embed/avatars/${parseInt(user.discriminator || '0') % 5}.png`
307
- },
308
- guilds: Array.isArray(userGuilds) ? userGuilds : [],
309
- createdAt: Date.now()
310
- });
311
- saveSessions();
312
-
313
- // Set cookie (7 days)
314
- res.cookie('fb_session', sid, {
315
- httpOnly: true,
316
- maxAge: 7 * 24 * 60 * 60 * 1000,
317
- sameSite: 'lax'
318
- });
319
-
320
- res.redirect('/?login=success');
321
- } catch (err) {
322
- console.error('[Dashboard] OAuth error:', err);
323
- res.redirect('/?error=server_error');
324
- }
325
- }
326
- app.get('/callback', handleOAuthCallback);
327
- app.get('/auth/callback', handleOAuthCallback);
328
-
329
- // --- Check Auth Status ---
330
- app.get('/api/me', (req, res) => {
331
- const session = getSession(req);
332
- if (session && session.user) {
333
- res.json({ loggedIn: true, user: session.user });
334
- } else {
335
- res.json({ loggedIn: false });
336
- }
337
- });
338
-
339
- // --- Logout ---
340
- app.get('/auth/logout', (req, res) => {
341
- const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
342
- const [k, v] = c.trim().split('=');
343
- if (k && v) acc[k] = v;
344
- return acc;
345
- }, {});
346
- const sid = cookies['fb_session'];
347
- if (sid) {
348
- sessions.delete(sid);
349
- saveSessions();
350
- }
351
- res.clearCookie('fb_session');
352
- res.redirect('/');
353
- });
354
-
355
- // --- Stats ---
356
- app.get('/api/stats', requireAuth, (req, res) => {
357
- if (!discordClient || !discordClient.isReady()) {
358
- return res.json({ servers: 0, members: 0, uptime: '—', commands: 0 });
359
- }
360
- const up = process.uptime();
361
- const d = Math.floor(up / 86400);
362
- const h = Math.floor(up / 3600) % 24;
363
- const m = Math.floor(up / 60) % 60;
364
- const upStr = d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`;
365
-
366
- const totalMembers = discordClient.guilds.cache.reduce((acc, g) => acc + g.memberCount, 0);
367
- const botId = discordClient.user?.id;
368
- const inviteUrl = botId
369
- ? `https://discord.com/api/oauth2/authorize?client_id=${botId}&permissions=8&scope=bot%20applications.commands`
370
- : '#';
371
-
372
- res.json({
373
- servers: discordClient.guilds.cache.size,
374
- members: totalMembers,
375
- uptime: upStr,
376
- commands: commandsDataRef ? commandsDataRef.length : 0,
377
- inviteUrl
378
- });
379
- });
380
-
381
- // --- Server List ---
382
- // --- Server List (shared with bot + permissions) ---
383
- let cachedOwnerId = null;
384
- app.get('/api/servers', requireAuth, async (req, res) => {
385
- try {
386
- if (!discordClient || !discordClient.isReady()) {
387
- return res.json({ pending: true, servers: [] });
388
- }
389
-
390
- const userGuilds = req.dashSession.guilds || [];
391
-
392
- // recognize owner (cached to avoid redundant API calls)
393
- if (!cachedOwnerId) {
394
- const app = await discordClient.application.fetch().catch(() => null);
395
- if (app) {
396
- cachedOwnerId = app.owner?.ownerId || app.owner?.id;
397
- // Support teams
398
- if (!cachedOwnerId && app.owner?.members) {
399
- // Just check the first member as a fallback if ownerId is missing
400
- const firstMember = Array.from(app.owner.members.values())[0];
401
- cachedOwnerId = firstMember?.user?.id || firstMember?.id;
402
- }
403
- }
404
- }
405
-
406
- const isBotOwner = req.dashSession.user.id === cachedOwnerId;
407
- console.log(`[Dashboard] Request by ${req.dashSession.user.username} (Owner: ${isBotOwner})`);
408
-
409
- // Filter guilds to only those that the user is actually in AND has permissions for.
410
- const mutualGuilds = userGuilds
411
- .filter(ug => discordClient.guilds.cache.has(ug.id))
412
- .filter(Boolean);
413
-
414
- const manageableGuilds = mutualGuilds.filter(ug => {
415
- const permBits = ug.permissions ?? ug.permissions_new;
416
- return hasDashboardPermissions(permBits);
417
- });
418
-
419
- const guildsToShow = manageableGuilds;
420
-
421
- const visibleGuilds = guildsToShow
422
- .map(ug => discordClient.guilds.cache.get(ug.id))
423
- .filter(Boolean);
424
-
425
- const list = visibleGuilds.map(g => ({
426
- name: g.name,
427
- id: g.id,
428
- members: g.memberCount || 0,
429
- icon: g.iconURL({ size: 64 }) || null
430
- }));
431
-
432
- if (isBotOwner) console.log(`[Dashboard] Owner access verified for ${req.dashSession.user.username}`);
433
- console.log(`[Dashboard] Serving ${list.length} managed servers to ${req.dashSession.user.username}`);
434
- res.json({ pending: false, servers: list });
435
- } catch (err) {
436
- console.error('[Dashboard] /api/servers failed:', err);
437
- res.status(500).json({ pending: false, servers: [], error: 'Failed to load servers' });
438
- }
439
- });
440
-
441
- // --- Guild Config (Prefix) ---
442
- app.get('/api/config/:guildId', requireAuth, (req, res) => {
443
- const { guildId } = req.params;
444
- const userGuilds = req.dashSession.guilds || [];
445
- const ug = userGuilds.find(g => g.id === guildId);
446
-
447
- if (!ug) return res.status(403).json({ error: 'Access denied' });
448
- const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
449
- if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });
450
-
451
- const storage = require('./storage');
452
- const config = storage.data.config[guildId] || {};
453
- res.json({
454
- prefix: storage.getPrefix(guildId),
455
- autoFriendlyEnabled: config.autoFriendlyEnabled || false,
456
- autoFriendlyInterval: config.autoFriendlyInterval || 40,
457
- autoFriendlyChannel: config.autoFriendlyChannel || null,
458
- postEnabled: !!config.postEnabled, // Default to false (off)
459
- postChannelId: config.postChannelId || null,
460
- friendlyText: config.friendlyText || "⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: {needed}\n@everyone",
461
- cleanupHours: config.cleanupHours || 2,
462
- lineupCleanupHours: config.lineupCleanupHours || 2,
463
- remindersEnabled: !!config.remindersEnabled,
464
- remindersLead: config.remindersLead || 30
465
- });
466
- });
467
-
468
- app.get('/api/channels/:guildId', requireAuth, (req, res) => {
469
- const { guildId } = req.params;
470
- if (!discordClient) return res.json([]);
471
- const guild = discordClient.guilds.cache.get(guildId);
472
- if (!guild) return res.json([]);
473
-
474
- const channels = guild.channels.cache
475
- .filter(c => c.isTextBased())
476
- .map(c => ({ id: c.id, name: c.name }));
477
- res.json(channels);
478
- });
479
-
480
- app.post('/api/config/:guildId', requireAuth, (req, res) => {
481
- const { guildId } = req.params;
482
- const { prefix, autoFriendlyEnabled, autoFriendlyInterval, autoFriendlyChannel, postEnabled, postChannelId, friendlyText, cleanupHours, lineupCleanupHours, remindersEnabled, remindersLead } = req.body;
483
- const userGuilds = req.dashSession.guilds || [];
484
- const ug = userGuilds.find(g => g.id === guildId);
485
-
486
- if (!ug) return res.status(403).json({ error: 'Access denied' });
487
- const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
488
- if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });
489
-
490
- const storage = require('./storage');
491
-
492
- if (prefix) {
493
- if (prefix.length > 5) return res.status(400).json({ error: 'Invalid prefix' });
494
- storage.setPrefix(guildId, prefix);
495
- }
496
-
497
- if (storage.data.config[guildId] === undefined) storage.data.config[guildId] = {};
498
-
499
- if (autoFriendlyEnabled !== undefined) storage.data.config[guildId].autoFriendlyEnabled = !!autoFriendlyEnabled;
500
- if (autoFriendlyInterval !== undefined) storage.data.config[guildId].autoFriendlyInterval = parseInt(autoFriendlyInterval) || 40;
501
- if (autoFriendlyChannel !== undefined) storage.data.config[guildId].autoFriendlyChannel = autoFriendlyChannel;
502
- if (postEnabled !== undefined) storage.data.config[guildId].postEnabled = !!postEnabled;
503
- if (postChannelId !== undefined) storage.data.config[guildId].postChannelId = postChannelId;
504
- if (friendlyText !== undefined) storage.data.config[guildId].friendlyText = friendlyText;
505
- if (cleanupHours !== undefined) storage.data.config[guildId].cleanupHours = parseInt(cleanupHours) || 2;
506
- if (lineupCleanupHours !== undefined) storage.data.config[guildId].lineupCleanupHours = parseInt(lineupCleanupHours) || 2;
507
- if (remindersEnabled !== undefined) storage.data.config[guildId].remindersEnabled = !!remindersEnabled;
508
- if (remindersLead !== undefined) storage.data.config[guildId].remindersLead = parseInt(remindersLead) || 30;
509
-
510
- storage.save('config');
511
- res.json({ success: true, message: 'Settings updated successfully' });
512
- });
513
-
514
- // --- Command List ---
515
- app.get('/api/commands', requireAuth, (req, res) => {
516
- if (!commandsDataRef) return res.json([]);
517
-
518
- const adminCmds = ['setup', 'post', 'clear', 'lock', 'unlock', 'giverole', 'addrole', 'removerole'];
519
- const staffCmds = ['win', 'loss', 'draw', 'lineup', 'managerlineup', 'leaguematch', 'lineupimage'];
520
-
521
- const list = commandsDataRef.map(c => ({
522
- name: c.name,
523
- description: c.description,
524
- admin: adminCmds.includes(c.name),
525
- staff: staffCmds.includes(c.name)
526
- }));
527
- res.json(list);
528
- });
529
-
530
- // --- Invite URL ---
531
- app.get('/api/invite', (req, res) => {
532
- if (!discordClient || !discordClient.user) return res.redirect('/');
533
- const url = `https://discord.com/api/oauth2/authorize?client_id=${discordClient.user.id}&permissions=8&scope=bot%20applications.commands`;
534
- res.redirect(url);
535
- });
536
-
537
- // --- Logs ---
538
- app.get('/api/logs', requireAuth, (req, res) => {
539
- res.json({ logs: logBuffer.slice(-100) });
540
- });
541
-
542
- // --- Actions ---
543
- app.post('/api/action/:name', requireAuth, async (req, res) => {
544
- const action = req.params.name;
545
-
546
- if (action === 'sync' && discordClient && commandsDataRef) {
547
- let count = 0;
548
- for (const guild of discordClient.guilds.cache.values()) {
549
- await guild.commands.set(commandsDataRef).catch(() => {});
550
- count++;
551
- }
552
- return res.json({ message: `✅ Synced commands to ${count} servers!` });
553
- }
554
-
555
- if (action === 'backup') {
556
- return res.json({ message: '☁️ Cloud backup triggered! Check Discord for confirmation.' });
557
- }
558
-
559
- if (action === 'restart') {
560
- res.json({ message: '🔁 Restarting bot in 2 seconds...' });
561
- setTimeout(() => process.exit(1), 2000);
562
- return;
563
- }
564
-
565
- res.json({ message: 'Unknown action.' });
566
- });
567
-
568
- // --- Start ---
569
- function startServer(client, cmdsData) {
570
- console.log("[*] Dashboard: startServer() called. Initializing express...");
571
- const net = require('net');
572
- const checkServer = net.createServer();
573
-
574
- checkServer.on('listening', () => {
575
- checkServer.close(() => {
576
- console.log(`[*] Port ${port} is available, starting server...`);
577
- startServerInternal(client, cmdsData);
578
- });
579
- });
580
-
581
- checkServer.on('error', (err) => {
582
- if (err.code === 'EADDRINUSE') {
583
- console.error(`[!] ERROR: Port ${port} is already in use. Another bot instance is running.`);
584
- console.error(`[!] Please close other instances before starting this one.`);
585
- process.exit(1);
586
- } else {
587
- console.error(`[!] Server error: ${err.message}`);
588
- process.exit(1);
589
- }
590
- });
591
-
592
- checkServer.listen(port, '0.0.0.0');
593
- }
594
 
595
- function startServerInternal(client, cmdsData) {
596
- hijackConsole();
597
- discordClient = client || null;
598
- commandsDataRef = cmdsData || null;
599
 
600
- app.listen(port, '0.0.0.0', () => {
601
- const finalRedirect = getRedirectUri();
602
- console.log(`[*] --------------------------------------------------`);
603
- console.log(`[*] Web Server running on port ${port}`);
604
- console.log(`[*] --------------------------------------------------`);
605
- console.log(`[*] DASHBOARD URL: ${finalRedirect.replace('/callback', '').replace('/auth/callback', '')}`);
606
- console.log(`[*] REDIRECT URI: ${finalRedirect}`);
607
- console.log(`[*] --------------------------------------------------`);
608
- console.log(`[*] IMPORTANT: Ensure the REDIRECT URI above is added exactly to your`);
609
- console.log(`[*] Discord Developer Portal -> OAuth2 -> Redirects section.`);
610
- console.log(`[*] --------------------------------------------------`);
611
- });
612
- }
613
 
 
 
614
 
615
- module.exports = { startServer, app };
 
1
  const express = require('express');
2
  const path = require('path');
 
 
 
 
3
  const app = express();
4
+ const port = process.env.PORT || 3000;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ // Serve static files from repo root
7
+ app.use(express.static(path.resolve(__dirname)));
 
 
8
 
9
+ app.get('/', (req, res) => res.sendFile(path.resolve(__dirname, 'dashboard.html')));
10
+ app.get('/league', (req, res) => res.sendFile(path.resolve(__dirname, 'league.html')));
11
+ app.get('/league.html', (req, res) => res.sendFile(path.resolve(__dirname, 'league.html')));
 
 
 
 
 
 
 
 
 
 
12
 
13
+ // Fallback for unknown routes
14
+ app.get('*', (req, res) => res.status(404).send('Cannot GET ' + req.path));
15
 
16
+ app.listen(port, () => console.log(`Server running on http://localhost:${port}`));