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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const session = require('express-session');
|
| 3 |
+
const bodyParser = require('body-parser');
|
| 4 |
+
const cors = require('cors');
|
| 5 |
+
const multer = require('multer');
|
| 6 |
+
const path = require('path');
|
| 7 |
+
const fs = require('fs-extra');
|
| 8 |
+
const unzipper = require('unzipper');
|
| 9 |
+
const pm2 = require('pm2');
|
| 10 |
+
const { Server } = require('socket.io');
|
| 11 |
+
const http = require('http');
|
| 12 |
+
const bcrypt = require('bcryptjs');
|
| 13 |
+
const pidusage = require('pidusage');
|
| 14 |
+
|
| 15 |
+
const app = express();
|
| 16 |
+
const server = http.createServer(app);
|
| 17 |
+
const io = new Server(server, {
|
| 18 |
+
cors: {
|
| 19 |
+
origin: "*",
|
| 20 |
+
methods: ["GET", "POST"]
|
| 21 |
+
}
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
const PORT = process.env.PORT || 7860;
|
| 25 |
+
|
| 26 |
+
// Middleware
|
| 27 |
+
app.use(cors());
|
| 28 |
+
app.use(bodyParser.json());
|
| 29 |
+
app.use(bodyParser.urlencoded({ extended: true }));
|
| 30 |
+
app.use(express.static(path.join(__dirname, 'public')));
|
| 31 |
+
app.use('/views', express.static(path.join(__dirname, 'views')));
|
| 32 |
+
app.use(session({
|
| 33 |
+
secret: 'personal-bot-panel-secret-key-2024',
|
| 34 |
+
resave: false,
|
| 35 |
+
saveUninitialized: false,
|
| 36 |
+
cookie: {
|
| 37 |
+
secure: false,
|
| 38 |
+
maxAge: 24 * 60 * 60 * 1000 // 24 hours
|
| 39 |
+
}
|
| 40 |
+
}));
|
| 41 |
+
|
| 42 |
+
// Simple auth middleware
|
| 43 |
+
const authMiddleware = (req, res, next) => {
|
| 44 |
+
if (req.session && req.session.authenticated) {
|
| 45 |
+
return next();
|
| 46 |
+
}
|
| 47 |
+
// If API request, send JSON error
|
| 48 |
+
if (req.path.startsWith('/api/')) {
|
| 49 |
+
return res.status(401).json({ error: 'Unauthorized' });
|
| 50 |
+
}
|
| 51 |
+
// Otherwise redirect to login
|
| 52 |
+
res.redirect('/login');
|
| 53 |
+
};
|
| 54 |
+
|
| 55 |
+
// Default admin credentials (change these in production)
|
| 56 |
+
const ADMIN_USERNAME = 'admin';
|
| 57 |
+
const ADMIN_PASSWORD = bcrypt.hashSync('admin123', 10);
|
| 58 |
+
|
| 59 |
+
// Login page route
|
| 60 |
+
app.get('/login', (req, res) => {
|
| 61 |
+
if (req.session.authenticated) {
|
| 62 |
+
return res.redirect('/');
|
| 63 |
+
}
|
| 64 |
+
res.sendFile(path.join(__dirname, 'public', 'login.html'));
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
// Login API
|
| 68 |
+
app.post('/api/login', (req, res) => {
|
| 69 |
+
const { username, password } = req.body;
|
| 70 |
+
|
| 71 |
+
if (username === ADMIN_USERNAME && bcrypt.compareSync(password, ADMIN_PASSWORD)) {
|
| 72 |
+
req.session.authenticated = true;
|
| 73 |
+
return res.json({ success: true, redirect: '/' });
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
res.status(401).json({ error: 'Invalid credentials' });
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
// Logout
|
| 80 |
+
app.get('/api/logout', (req, res) => {
|
| 81 |
+
req.session.destroy();
|
| 82 |
+
res.json({ success: true });
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
// Protect all other routes
|
| 86 |
+
app.get('/', authMiddleware, (req, res) => {
|
| 87 |
+
res.sendFile(path.join(__dirname, 'public', 'index.html'));
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
app.get('/dashboard', authMiddleware, (req, res) => {
|
| 91 |
+
res.sendFile(path.join(__dirname, 'views', 'dashboard.html'));
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
app.get('/filemanager', authMiddleware, (req, res) => {
|
| 95 |
+
res.sendFile(path.join(__dirname, 'views', 'filemanager.html'));
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
app.get('/filemanager/:botName', authMiddleware, (req, res) => {
|
| 99 |
+
res.sendFile(path.join(__dirname, 'views', 'filemanager.html'));
|
| 100 |
+
});
|
| 101 |
+
|
| 102 |
+
// Multer configuration for file uploads
|
| 103 |
+
const storage = multer.diskStorage({
|
| 104 |
+
destination: (req, file, cb) => {
|
| 105 |
+
const uploadDir = path.join(__dirname, 'uploads');
|
| 106 |
+
fs.ensureDirSync(uploadDir);
|
| 107 |
+
cb(null, uploadDir);
|
| 108 |
+
},
|
| 109 |
+
filename: (req, file, cb) => {
|
| 110 |
+
cb(null, Date.now() + '-' + file.originalname);
|
| 111 |
+
}
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
const upload = multer({
|
| 115 |
+
storage: storage,
|
| 116 |
+
limits: {
|
| 117 |
+
fileSize: 100 * 1024 * 1024 // 100MB limit
|
| 118 |
+
},
|
| 119 |
+
fileFilter: (req, file, cb) => {
|
| 120 |
+
if (file.mimetype === 'application/zip' ||
|
| 121 |
+
file.mimetype === 'application/x-zip-compressed' ||
|
| 122 |
+
file.originalname.endsWith('.zip')) {
|
| 123 |
+
cb(null, true);
|
| 124 |
+
} else {
|
| 125 |
+
cb(new Error('Only ZIP files are allowed'));
|
| 126 |
+
}
|
| 127 |
+
}
|
| 128 |
+
});
|
| 129 |
+
|
| 130 |
+
// API Routes
|
| 131 |
+
|
| 132 |
+
// Get all bots
|
| 133 |
+
app.get('/api/bots', authMiddleware, async (req, res) => {
|
| 134 |
+
try {
|
| 135 |
+
const botsDir = path.join(__dirname, 'bots');
|
| 136 |
+
fs.ensureDirSync(botsDir);
|
| 137 |
+
|
| 138 |
+
const botFolders = await fs.readdir(botsDir);
|
| 139 |
+
const bots = [];
|
| 140 |
+
|
| 141 |
+
for (const folder of botFolders) {
|
| 142 |
+
const botPath = path.join(botsDir, folder);
|
| 143 |
+
const stat = await fs.stat(botPath);
|
| 144 |
+
|
| 145 |
+
if (stat.isDirectory()) {
|
| 146 |
+
const configPath = path.join(botPath, 'bot-config.json');
|
| 147 |
+
let config = {};
|
| 148 |
+
|
| 149 |
+
if (await fs.pathExists(configPath)) {
|
| 150 |
+
config = await fs.readJson(configPath);
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
// Get PM2 process info
|
| 154 |
+
const processName = `bot-${folder}`;
|
| 155 |
+
let status = 'offline';
|
| 156 |
+
let pid = null;
|
| 157 |
+
|
| 158 |
+
try {
|
| 159 |
+
const processInfo = await new Promise((resolve, reject) => {
|
| 160 |
+
pm2.describe(processName, (err, desc) => {
|
| 161 |
+
if (err) return reject(err);
|
| 162 |
+
resolve(desc);
|
| 163 |
+
});
|
| 164 |
+
});
|
| 165 |
+
|
| 166 |
+
if (processInfo && processInfo.length > 0) {
|
| 167 |
+
status = processInfo[0].pm2_env.status === 'online' ? 'online' : 'offline';
|
| 168 |
+
pid = processInfo[0].pid;
|
| 169 |
+
}
|
| 170 |
+
} catch (err) {
|
| 171 |
+
// Process doesn't exist, keep offline status
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
let cpuUsage = 0;
|
| 175 |
+
let memoryUsage = 0;
|
| 176 |
+
|
| 177 |
+
if (pid) {
|
| 178 |
+
try {
|
| 179 |
+
const stats = await pidusage(pid);
|
| 180 |
+
cpuUsage = stats.cpu.toFixed(2);
|
| 181 |
+
memoryUsage = (stats.memory / 1024 / 1024).toFixed(2); // MB
|
| 182 |
+
} catch (err) {
|
| 183 |
+
// Process may have ended
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
bots.push({
|
| 188 |
+
name: folder,
|
| 189 |
+
type: config.type || 'unknown',
|
| 190 |
+
mainFile: config.mainFile || 'unknown',
|
| 191 |
+
status: status,
|
| 192 |
+
pid: pid,
|
| 193 |
+
cpu: cpuUsage,
|
| 194 |
+
memory: memoryUsage,
|
| 195 |
+
uptime: processInfo && processInfo.length > 0 ? processInfo[0].pm2_env.pm_uptime : null,
|
| 196 |
+
restartCount: processInfo && processInfo.length > 0 ? processInfo[0].pm2_env.restart_time : 0,
|
| 197 |
+
createdAt: stat.birthtime
|
| 198 |
+
});
|
| 199 |
+
}
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
res.json({ bots });
|
| 203 |
+
} catch (error) {
|
| 204 |
+
res.status(500).json({ error: error.message });
|
| 205 |
+
}
|
| 206 |
+
});
|
| 207 |
+
|
| 208 |
+
// Upload bot
|
| 209 |
+
app.post('/api/bots/upload', authMiddleware, upload.single('bot'), async (req, res) => {
|
| 210 |
+
try {
|
| 211 |
+
if (!req.file) {
|
| 212 |
+
return res.status(400).json({ error: 'No file uploaded' });
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
const zipPath = req.file.path;
|
| 216 |
+
const botName = req.body.name || path.basename(req.file.originalname, '.zip');
|
| 217 |
+
|
| 218 |
+
// Validate bot name
|
| 219 |
+
if (!/^[a-zA-Z0-9_-]+$/.test(botName)) {
|
| 220 |
+
await fs.remove(zipPath);
|
| 221 |
+
return res.status(400).json({ error: 'Invalid bot name. Use only letters, numbers, hyphens, and underscores.' });
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
const botDir = path.join(__dirname, 'bots', botName);
|
| 225 |
+
|
| 226 |
+
// Check if bot already exists
|
| 227 |
+
if (await fs.pathExists(botDir)) {
|
| 228 |
+
await fs.remove(zipPath);
|
| 229 |
+
return res.status(400).json({ error: 'Bot with this name already exists' });
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
// Extract ZIP
|
| 233 |
+
await fs.ensureDir(botDir);
|
| 234 |
+
|
| 235 |
+
await new Promise((resolve, reject) => {
|
| 236 |
+
fs.createReadStream(zipPath)
|
| 237 |
+
.pipe(unzipper.Extract({ path: botDir }))
|
| 238 |
+
.on('close', resolve)
|
| 239 |
+
.on('error', reject);
|
| 240 |
+
});
|
| 241 |
+
|
| 242 |
+
// Clean up uploaded zip
|
| 243 |
+
await fs.remove(zipPath);
|
| 244 |
+
|
| 245 |
+
// Detect bot type
|
| 246 |
+
const files = await fs.readdir(botDir);
|
| 247 |
+
let botType = 'unknown';
|
| 248 |
+
let mainFile = null;
|
| 249 |
+
|
| 250 |
+
// Check for Node.js project
|
| 251 |
+
if (files.includes('package.json')) {
|
| 252 |
+
botType = 'nodejs';
|
| 253 |
+
const packageJson = await fs.readJson(path.join(botDir, 'package.json'));
|
| 254 |
+
mainFile = packageJson.main || 'index.js';
|
| 255 |
+
|
| 256 |
+
// Install npm dependencies
|
| 257 |
+
const { exec } = require('child_process');
|
| 258 |
+
exec('npm install', { cwd: botDir }, (err, stdout, stderr) => {
|
| 259 |
+
if (err) {
|
| 260 |
+
console.error(`npm install error for ${botName}:`, stderr);
|
| 261 |
+
}
|
| 262 |
+
});
|
| 263 |
+
}
|
| 264 |
+
// Check for Python project
|
| 265 |
+
else if (files.includes('requirements.txt') || files.includes('main.py')) {
|
| 266 |
+
botType = 'python';
|
| 267 |
+
mainFile = files.includes('main.py') ? 'main.py' : files.find(f => f.endsWith('.py'));
|
| 268 |
+
|
| 269 |
+
// Install pip dependencies
|
| 270 |
+
if (files.includes('requirements.txt')) {
|
| 271 |
+
const { exec } = require('child_process');
|
| 272 |
+
exec('pip install -r requirements.txt', { cwd: botDir }, (err, stdout, stderr) => {
|
| 273 |
+
if (err) {
|
| 274 |
+
console.error(`pip install error for ${botName}:`, stderr);
|
| 275 |
+
}
|
| 276 |
+
});
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
// Detect main file
|
| 280 |
+
else {
|
| 281 |
+
mainFile = files.find(f => f.endsWith('.js') || f.endsWith('.py'));
|
| 282 |
+
if (mainFile && mainFile.endsWith('.js')) {
|
| 283 |
+
botType = 'nodejs';
|
| 284 |
+
} else if (mainFile && mainFile.endsWith('.py')) {
|
| 285 |
+
botType = 'python';
|
| 286 |
+
}
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
// Save bot configuration
|
| 290 |
+
const config = {
|
| 291 |
+
name: botName,
|
| 292 |
+
type: botType,
|
| 293 |
+
mainFile: mainFile,
|
| 294 |
+
createdAt: new Date().toISOString()
|
| 295 |
+
};
|
| 296 |
+
|
| 297 |
+
await fs.writeJson(path.join(botDir, 'bot-config.json'), config);
|
| 298 |
+
|
| 299 |
+
res.json({ success: true, bot: { name: botName, type: botType, mainFile: mainFile } });
|
| 300 |
+
} catch (error) {
|
| 301 |
+
res.status(500).json({ error: error.message });
|
| 302 |
+
}
|
| 303 |
+
});
|
| 304 |
+
|
| 305 |
+
// Start bot
|
| 306 |
+
app.post('/api/bots/:name/start', authMiddleware, async (req, res) => {
|
| 307 |
+
try {
|
| 308 |
+
const botName = req.params.name;
|
| 309 |
+
const botDir = path.join(__dirname, 'bots', botName);
|
| 310 |
+
|
| 311 |
+
if (!await fs.pathExists(botDir)) {
|
| 312 |
+
return res.status(404).json({ error: 'Bot not found' });
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
const configPath = path.join(botDir, 'bot-config.json');
|
| 316 |
+
if (!await fs.pathExists(configPath)) {
|
| 317 |
+
return res.status(400).json({ error: 'Bot configuration not found' });
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
const config = await fs.readJson(configPath);
|
| 321 |
+
const processName = `bot-${botName}`;
|
| 322 |
+
|
| 323 |
+
// Build PM2 start command
|
| 324 |
+
let script = '';
|
| 325 |
+
let interpreter = '';
|
| 326 |
+
let args = [];
|
| 327 |
+
|
| 328 |
+
if (config.type === 'nodejs') {
|
| 329 |
+
script = path.join(botDir, config.mainFile || 'index.js');
|
| 330 |
+
interpreter = 'node';
|
| 331 |
+
} else if (config.type === 'python') {
|
| 332 |
+
script = path.join(botDir, config.mainFile || 'main.py');
|
| 333 |
+
interpreter = 'python3';
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
// Connect to PM2 and start the process
|
| 337 |
+
await new Promise((resolve, reject) => {
|
| 338 |
+
pm2.connect((err) => {
|
| 339 |
+
if (err) return reject(err);
|
| 340 |
+
|
| 341 |
+
pm2.start({
|
| 342 |
+
name: processName,
|
| 343 |
+
script: script,
|
| 344 |
+
interpreter: interpreter,
|
| 345 |
+
args: args,
|
| 346 |
+
cwd: botDir,
|
| 347 |
+
autorestart: true,
|
| 348 |
+
max_restarts: 10,
|
| 349 |
+
watch: false,
|
| 350 |
+
env: {
|
| 351 |
+
NODE_ENV: 'production',
|
| 352 |
+
BOT_NAME: botName
|
| 353 |
+
}
|
| 354 |
+
}, (err, apps) => {
|
| 355 |
+
if (err) {
|
| 356 |
+
pm2.disconnect();
|
| 357 |
+
return reject(err);
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
// Save PM2 process list
|
| 361 |
+
pm2.save((err) => {
|
| 362 |
+
pm2.disconnect();
|
| 363 |
+
if (err) return reject(err);
|
| 364 |
+
resolve(apps);
|
| 365 |
+
});
|
| 366 |
+
});
|
| 367 |
+
});
|
| 368 |
+
});
|
| 369 |
+
|
| 370 |
+
// Notify via socket
|
| 371 |
+
io.emit('botStatusChanged', { name: botName, status: 'online' });
|
| 372 |
+
|
| 373 |
+
res.json({ success: true, message: 'Bot started successfully' });
|
| 374 |
+
} catch (error) {
|
| 375 |
+
res.status(500).json({ error: error.message });
|
| 376 |
+
}
|
| 377 |
+
});
|
| 378 |
+
|
| 379 |
+
// Stop bot
|
| 380 |
+
app.post('/api/bots/:name/stop', authMiddleware, async (req, res) => {
|
| 381 |
+
try {
|
| 382 |
+
const botName = req.params.name;
|
| 383 |
+
const processName = `bot-${botName}`;
|
| 384 |
+
|
| 385 |
+
await new Promise((resolve, reject) => {
|
| 386 |
+
pm2.connect((err) => {
|
| 387 |
+
if (err) return reject(err);
|
| 388 |
+
|
| 389 |
+
pm2.stop(processName, (err) => {
|
| 390 |
+
if (err) {
|
| 391 |
+
pm2.disconnect();
|
| 392 |
+
return reject(err);
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
pm2.save((err) => {
|
| 396 |
+
pm2.disconnect();
|
| 397 |
+
if (err) return reject(err);
|
| 398 |
+
resolve();
|
| 399 |
+
});
|
| 400 |
+
});
|
| 401 |
+
});
|
| 402 |
+
});
|
| 403 |
+
|
| 404 |
+
io.emit('botStatusChanged', { name: botName, status: 'offline' });
|
| 405 |
+
|
| 406 |
+
res.json({ success: true, message: 'Bot stopped successfully' });
|
| 407 |
+
} catch (error) {
|
| 408 |
+
res.status(500).json({ error: error.message });
|
| 409 |
+
}
|
| 410 |
+
});
|
| 411 |
+
|
| 412 |
+
// Restart bot
|
| 413 |
+
app.post('/api/bots/:name/restart', authMiddleware, async (req, res) => {
|
| 414 |
+
try {
|
| 415 |
+
const botName = req.params.name;
|
| 416 |
+
const processName = `bot-${botName}`;
|
| 417 |
+
|
| 418 |
+
await new Promise((resolve, reject) => {
|
| 419 |
+
pm2.connect((err) => {
|
| 420 |
+
if (err) return reject(err);
|
| 421 |
+
|
| 422 |
+
pm2.restart(processName, (err) => {
|
| 423 |
+
if (err) {
|
| 424 |
+
pm2.disconnect();
|
| 425 |
+
return reject(err);
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
pm2.save((err) => {
|
| 429 |
+
pm2.disconnect();
|
| 430 |
+
if (err) return reject(err);
|
| 431 |
+
resolve();
|
| 432 |
+
});
|
| 433 |
+
});
|
| 434 |
+
});
|
| 435 |
+
});
|
| 436 |
+
|
| 437 |
+
io.emit('botStatusChanged', { name: botName, status: 'online' });
|
| 438 |
+
|
| 439 |
+
res.json({ success: true, message: 'Bot restarted successfully' });
|
| 440 |
+
} catch (error) {
|
| 441 |
+
res.status(500).json({ error: error.message });
|
| 442 |
+
}
|
| 443 |
+
});
|
| 444 |
+
|
| 445 |
+
// Delete bot
|
| 446 |
+
app.delete('/api/bots/:name', authMiddleware, async (req, res) => {
|
| 447 |
+
try {
|
| 448 |
+
const botName = req.params.name;
|
| 449 |
+
const botDir = path.join(__dirname, 'bots', botName);
|
| 450 |
+
const processName = `bot-${botName}`;
|
| 451 |
+
|
| 452 |
+
// Stop and delete from PM2 first
|
| 453 |
+
await new Promise((resolve, reject) => {
|
| 454 |
+
pm2.connect((err) => {
|
| 455 |
+
if (err) return reject(err);
|
| 456 |
+
|
| 457 |
+
pm2.delete(processName, (err) => {
|
| 458 |
+
if (err && !err.message.includes('not found')) {
|
| 459 |
+
pm2.disconnect();
|
| 460 |
+
return reject(err);
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
pm2.save((err) => {
|
| 464 |
+
pm2.disconnect();
|
| 465 |
+
if (err) return reject(err);
|
| 466 |
+
resolve();
|
| 467 |
+
});
|
| 468 |
+
});
|
| 469 |
+
});
|
| 470 |
+
});
|
| 471 |
+
|
| 472 |
+
// Remove bot directory
|
| 473 |
+
await fs.remove(botDir);
|
| 474 |
+
|
| 475 |
+
io.emit('botDeleted', { name: botName });
|
| 476 |
+
|
| 477 |
+
res.json({ success: true, message: 'Bot deleted successfully' });
|
| 478 |
+
} catch (error) {
|
| 479 |
+
res.status(500).json({ error: error.message });
|
| 480 |
+
}
|
| 481 |
+
});
|
| 482 |
+
|
| 483 |
+
// Get bot logs
|
| 484 |
+
app.get('/api/bots/:name/logs', authMiddleware, async (req, res) => {
|
| 485 |
+
try {
|
| 486 |
+
const botName = req.params.name;
|
| 487 |
+
const processName = `bot-${botName}`;
|
| 488 |
+
|
| 489 |
+
const logs = await new Promise((resolve, reject) => {
|
| 490 |
+
pm2.connect((err) => {
|
| 491 |
+
if (err) return reject(err);
|
| 492 |
+
|
| 493 |
+
pm2.describe(processName, (err, desc) => {
|
| 494 |
+
if (err) {
|
| 495 |
+
pm2.disconnect();
|
| 496 |
+
return reject(err);
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
if (!desc || desc.length === 0) {
|
| 500 |
+
pm2.disconnect();
|
| 501 |
+
return resolve('');
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
const logPath = desc[0].pm2_env.pm_out_log_path;
|
| 505 |
+
pm2.disconnect();
|
| 506 |
+
|
| 507 |
+
if (logPath && fs.existsSync(logPath)) {
|
| 508 |
+
const logContent = fs.readFileSync(logPath, 'utf8');
|
| 509 |
+
// Return last 1000 lines
|
| 510 |
+
const lines = logContent.split('\n');
|
| 511 |
+
const recentLines = lines.slice(-1000);
|
| 512 |
+
resolve(recentLines.join('\n'));
|
| 513 |
+
} else {
|
| 514 |
+
resolve('');
|
| 515 |
+
}
|
| 516 |
+
});
|
| 517 |
+
});
|
| 518 |
+
});
|
| 519 |
+
|
| 520 |
+
res.json({ logs: logs || '' });
|
| 521 |
+
} catch (error) {
|
| 522 |
+
// If PM2 process doesn't exist, try reading from a potential log file
|
| 523 |
+
try {
|
| 524 |
+
const logPath = path.join(process.env.HOME || '/tmp', '.pm2', 'logs', `bot-${req.params.name}-out.log`);
|
| 525 |
+
if (await fs.pathExists(logPath)) {
|
| 526 |
+
const content = await fs.readFile(logPath, 'utf8');
|
| 527 |
+
return res.json({ logs: content });
|
| 528 |
+
}
|
| 529 |
+
} catch (err) {
|
| 530 |
+
// Ignore
|
| 531 |
+
}
|
| 532 |
+
res.json({ logs: '' });
|
| 533 |
+
}
|
| 534 |
+
});
|
| 535 |
+
|
| 536 |
+
// Get file list for a bot
|
| 537 |
+
app.get('/api/bots/:name/files', authMiddleware, async (req, res) => {
|
| 538 |
+
try {
|
| 539 |
+
const botName = req.params.name;
|
| 540 |
+
const botDir = path.join(__dirname, 'bots', botName);
|
| 541 |
+
|
| 542 |
+
if (!await fs.pathExists(botDir)) {
|
| 543 |
+
return res.status(404).json({ error: 'Bot not found' });
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
const files = await listFiles(botDir, botDir);
|
| 547 |
+
res.json({ files });
|
| 548 |
+
} catch (error) {
|
| 549 |
+
res.status(500).json({ error: error.message });
|
| 550 |
+
}
|
| 551 |
+
});
|
| 552 |
+
|
| 553 |
+
// Read file content
|
| 554 |
+
app.get('/api/bots/:name/files/read', authMiddleware, async (req, res) => {
|
| 555 |
+
try {
|
| 556 |
+
const botName = req.params.name;
|
| 557 |
+
const filePath = req.query.path;
|
| 558 |
+
|
| 559 |
+
if (!filePath) {
|
| 560 |
+
return res.status(400).json({ error: 'File path required' });
|
| 561 |
+
}
|
| 562 |
+
|
| 563 |
+
// Prevent path traversal
|
| 564 |
+
const botDir = path.join(__dirname, 'bots', botName);
|
| 565 |
+
const fullPath = path.join(botDir, filePath);
|
| 566 |
+
|
| 567 |
+
if (!fullPath.startsWith(botDir)) {
|
| 568 |
+
return res.status(403).json({ error: 'Access denied' });
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
if (!await fs.pathExists(fullPath)) {
|
| 572 |
+
return res.status(404).json({ error: 'File not found' });
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
const stat = await fs.stat(fullPath);
|
| 576 |
+
if (stat.isDirectory()) {
|
| 577 |
+
const files = await listFiles(fullPath, botDir);
|
| 578 |
+
return res.json({ type: 'directory', files });
|
| 579 |
+
}
|
| 580 |
+
|
| 581 |
+
const content = await fs.readFile(fullPath, 'utf8');
|
| 582 |
+
res.json({ type: 'file', content, size: stat.size });
|
| 583 |
+
} catch (error) {
|
| 584 |
+
res.status(500).json({ error: error.message });
|
| 585 |
+
}
|
| 586 |
+
});
|
| 587 |
+
|
| 588 |
+
// Save file content
|
| 589 |
+
app.post('/api/bots/:name/files/save', authMiddleware, async (req, res) => {
|
| 590 |
+
try {
|
| 591 |
+
const botName = req.params.name;
|
| 592 |
+
const { path: filePath, content } = req.body;
|
| 593 |
+
|
| 594 |
+
if (!filePath) {
|
| 595 |
+
return res.status(400).json({ error: 'File path required' });
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
const botDir = path.join(__dirname, 'bots', botName);
|
| 599 |
+
const fullPath = path.join(botDir, filePath);
|
| 600 |
+
|
| 601 |
+
if (!fullPath.startsWith(botDir)) {
|
| 602 |
+
return res.status(403).json({ error: 'Access denied' });
|
| 603 |
+
}
|
| 604 |
+
|
| 605 |
+
await fs.writeFile(fullPath, content);
|
| 606 |
+
res.json({ success: true });
|
| 607 |
+
} catch (error) {
|
| 608 |
+
res.status(500).json({ error: error.message });
|
| 609 |
+
}
|
| 610 |
+
});
|
| 611 |
+
|
| 612 |
+
// Delete file
|
| 613 |
+
app.delete('/api/bots/:name/files/delete', authMiddleware, async (req, res) => {
|
| 614 |
+
try {
|
| 615 |
+
const botName = req.params.name;
|
| 616 |
+
const filePath = req.query.path;
|
| 617 |
+
|
| 618 |
+
if (!filePath) {
|
| 619 |
+
return res.status(400).json({ error: 'File path required' });
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
const botDir = path.join(__dirname, 'bots', botName);
|
| 623 |
+
const fullPath = path.join(botDir, filePath);
|
| 624 |
+
|
| 625 |
+
if (!fullPath.startsWith(botDir)) {
|
| 626 |
+
return res.status(403).json({ error: 'Access denied' });
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
await fs.remove(fullPath);
|
| 630 |
+
res.json({ success: true });
|
| 631 |
+
} catch (error) {
|
| 632 |
+
res.status(500).json({ error: error.message });
|
| 633 |
+
}
|
| 634 |
+
});
|
| 635 |
+
|
| 636 |
+
// Create directory
|
| 637 |
+
app.post('/api/bots/:name/files/mkdir', authMiddleware, async (req, res) => {
|
| 638 |
+
try {
|
| 639 |
+
const botName = req.params.name;
|
| 640 |
+
const { path: dirPath, name } = req.body;
|
| 641 |
+
|
| 642 |
+
const botDir = path.join(__dirname, 'bots', botName);
|
| 643 |
+
const fullPath = path.join(botDir, dirPath || '', name);
|
| 644 |
+
|
| 645 |
+
if (!fullPath.startsWith(botDir)) {
|
| 646 |
+
return res.status(403).json({ error: 'Access denied' });
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
await fs.ensureDir(fullPath);
|
| 650 |
+
res.json({ success: true });
|
| 651 |
+
} catch (error) {
|
| 652 |
+
res.status(500).json({ error: error.message });
|
| 653 |
+
}
|
| 654 |
+
});
|
| 655 |
+
|
| 656 |
+
// Upload file to bot
|
| 657 |
+
app.post('/api/bots/:name/files/upload', authMiddleware, upload.single('file'), async (req, res) => {
|
| 658 |
+
try {
|
| 659 |
+
const botName = req.params.name;
|
| 660 |
+
const uploadPath = req.body.path || '';
|
| 661 |
+
|
| 662 |
+
const botDir = path.join(__dirname, 'bots', botName);
|
| 663 |
+
const destDir = path.join(botDir, uploadPath);
|
| 664 |
+
const destPath = path.join(destDir, req.file.originalname);
|
| 665 |
+
|
| 666 |
+
if (!destPath.startsWith(botDir)) {
|
| 667 |
+
await fs.remove(req.file.path);
|
| 668 |
+
return res.status(403).json({ error: 'Access denied' });
|
| 669 |
+
}
|
| 670 |
+
|
| 671 |
+
await fs.ensureDir(destDir);
|
| 672 |
+
await fs.move(req.file.path, destPath, { overwrite: true });
|
| 673 |
+
|
| 674 |
+
res.json({ success: true });
|
| 675 |
+
} catch (error) {
|
| 676 |
+
res.status(500).json({ error: error.message });
|
| 677 |
+
}
|
| 678 |
+
});
|
| 679 |
+
|
| 680 |
+
// Get system info
|
| 681 |
+
app.get('/api/system/info', authMiddleware, async (req, res) => {
|
| 682 |
+
try {
|
| 683 |
+
const os = require('os');
|
| 684 |
+
const totalMem = os.totalmem();
|
| 685 |
+
const freeMem = os.freemem();
|
| 686 |
+
const usedMem = totalMem - freeMem;
|
| 687 |
+
|
| 688 |
+
res.json({
|
| 689 |
+
platform: os.platform(),
|
| 690 |
+
arch: os.arch(),
|
| 691 |
+
cpus: os.cpus().length,
|
| 692 |
+
totalMemory: (totalMem / 1024 / 1024 / 1024).toFixed(2),
|
| 693 |
+
usedMemory: (usedMem / 1024 / 1024 / 1024).toFixed(2),
|
| 694 |
+
freeMemory: (freeMem / 1024 / 1024 / 1024).toFixed(2),
|
| 695 |
+
uptime: os.uptime(),
|
| 696 |
+
nodeVersion: process.version
|
| 697 |
+
});
|
| 698 |
+
} catch (error) {
|
| 699 |
+
res.status(500).json({ error: error.message });
|
| 700 |
+
}
|
| 701 |
+
});
|
| 702 |
+
|
| 703 |
+
// Helper function to list files recursively
|
| 704 |
+
async function listFiles(dir, baseDir) {
|
| 705 |
+
const files = await fs.readdir(dir);
|
| 706 |
+
const fileList = [];
|
| 707 |
+
|
| 708 |
+
for (const file of files) {
|
| 709 |
+
if (file === 'node_modules' || file === '__pycache__' || file.startsWith('.')) {
|
| 710 |
+
continue;
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
const fullPath = path.join(dir, file);
|
| 714 |
+
const relativePath = path.relative(baseDir, fullPath);
|
| 715 |
+
const stat = await fs.stat(fullPath);
|
| 716 |
+
|
| 717 |
+
fileList.push({
|
| 718 |
+
name: file,
|
| 719 |
+
path: relativePath,
|
| 720 |
+
type: stat.isDirectory() ? 'directory' : 'file',
|
| 721 |
+
size: stat.size,
|
| 722 |
+
modifiedAt: stat.mtime
|
| 723 |
+
});
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
return fileList;
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
// Socket.io connection for realtime logs
|
| 730 |
+
io.on('connection', (socket) => {
|
| 731 |
+
console.log('Client connected');
|
| 732 |
+
|
| 733 |
+
socket.on('subscribe-logs', async (botName) => {
|
| 734 |
+
const processName = `bot-${botName}`;
|
| 735 |
+
|
| 736 |
+
// Send initial logs
|
| 737 |
+
try {
|
| 738 |
+
const logs = await new Promise((resolve) => {
|
| 739 |
+
pm2.connect((err) => {
|
| 740 |
+
if (err) {
|
| 741 |
+
resolve('');
|
| 742 |
+
return;
|
| 743 |
+
}
|
| 744 |
+
|
| 745 |
+
pm2.describe(processName, (err, desc) => {
|
| 746 |
+
pm2.disconnect();
|
| 747 |
+
if (err || !desc || desc.length === 0) {
|
| 748 |
+
resolve('');
|
| 749 |
+
return;
|
| 750 |
+
}
|
| 751 |
+
|
| 752 |
+
const logPath = desc[0].pm2_env.pm_out_log_path;
|
| 753 |
+
if (logPath && fs.existsSync(logPath)) {
|
| 754 |
+
const content = fs.readFileSync(logPath, 'utf8');
|
| 755 |
+
const lines = content.split('\n').slice(-100);
|
| 756 |
+
resolve(lines.join('\n'));
|
| 757 |
+
} else {
|
| 758 |
+
resolve('');
|
| 759 |
+
}
|
| 760 |
+
});
|
| 761 |
+
});
|
| 762 |
+
});
|
| 763 |
+
|
| 764 |
+
socket.emit('logs-update', { botName, logs });
|
| 765 |
+
} catch (err) {
|
| 766 |
+
console.error('Error fetching logs:', err);
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
// Set up log watching
|
| 770 |
+
const watcher = setInterval(async () => {
|
| 771 |
+
try {
|
| 772 |
+
const logs = await new Promise((resolve) => {
|
| 773 |
+
pm2.connect((err) => {
|
| 774 |
+
if (err) {
|
| 775 |
+
resolve('');
|
| 776 |
+
return;
|
| 777 |
+
}
|
| 778 |
+
|
| 779 |
+
pm2.describe(processName, (err, desc) => {
|
| 780 |
+
pm2.disconnect();
|
| 781 |
+
if (err || !desc || desc.length === 0) {
|
| 782 |
+
resolve('');
|
| 783 |
+
return;
|
| 784 |
+
}
|
| 785 |
+
|
| 786 |
+
const logPath = desc[0].pm2_env.pm_out_log_path;
|
| 787 |
+
if (logPath && fs.existsSync(logPath)) {
|
| 788 |
+
const content = fs.readFileSync(logPath, 'utf8');
|
| 789 |
+
resolve(content);
|
| 790 |
+
} else {
|
| 791 |
+
resolve('');
|
| 792 |
+
}
|
| 793 |
+
});
|
| 794 |
+
});
|
| 795 |
+
});
|
| 796 |
+
|
| 797 |
+
socket.emit('logs-update', { botName, logs });
|
| 798 |
+
} catch (err) {
|
| 799 |
+
console.error('Error watching logs:', err);
|
| 800 |
+
}
|
| 801 |
+
}, 2000);
|
| 802 |
+
|
| 803 |
+
socket.on('disconnect', () => {
|
| 804 |
+
clearInterval(watcher);
|
| 805 |
+
});
|
| 806 |
+
});
|
| 807 |
+
|
| 808 |
+
socket.on('disconnect', () => {
|
| 809 |
+
console.log('Client disconnected');
|
| 810 |
+
});
|
| 811 |
+
});
|
| 812 |
+
|
| 813 |
+
// Initialize PM2 and restore saved processes
|
| 814 |
+
async function initializePM2() {
|
| 815 |
+
return new Promise((resolve, reject) => {
|
| 816 |
+
pm2.connect((err) => {
|
| 817 |
+
if (err) {
|
| 818 |
+
console.error('Error connecting to PM2:', err);
|
| 819 |
+
return reject(err);
|
| 820 |
+
}
|
| 821 |
+
|
| 822 |
+
// Try to resurrect previously saved processes
|
| 823 |
+
pm2.resurrect((err) => {
|
| 824 |
+
if (err) {
|
| 825 |
+
console.log('No previous processes to restore or error restoring:', err.message);
|
| 826 |
+
} else {
|
| 827 |
+
console.log('Restored previously saved processes');
|
| 828 |
+
}
|
| 829 |
+
|
| 830 |
+
pm2.save((err) => {
|
| 831 |
+
if (err) {
|
| 832 |
+
console.error('Error saving PM2 process list:', err);
|
| 833 |
+
}
|
| 834 |
+
pm2.disconnect();
|
| 835 |
+
resolve();
|
| 836 |
+
});
|
| 837 |
+
});
|
| 838 |
+
});
|
| 839 |
+
});
|
| 840 |
+
}
|
| 841 |
+
|
| 842 |
+
// Start server
|
| 843 |
+
async function startServer() {
|
| 844 |
+
try {
|
| 845 |
+
await initializePM2();
|
| 846 |
+
|
| 847 |
+
server.listen(PORT, '0.0.0.0', () => {
|
| 848 |
+
console.log(`Bot Hosting Panel running on port ${PORT}`);
|
| 849 |
+
console.log(`Open http://localhost:${PORT} in your browser`);
|
| 850 |
+
});
|
| 851 |
+
} catch (error) {
|
| 852 |
+
console.error('Failed to start server:', error);
|
| 853 |
+
process.exit(1);
|
| 854 |
+
}
|
| 855 |
+
}
|
| 856 |
+
|
| 857 |
+
startServer();
|