gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Code : [code] can you simplify this!
- User
Code :
code - Assistant
Code :
const { execSync } = require('child_process');
const { machineIdSync } = require('node-machine-id');
const https = require('https');
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const SERVER_PORT = 443;
const configPath = path.resolve(__dirname, './config/main.json');
const checkAndInstall = (pkgList) => {
pkgList.forEach(pkg => {
try {
require.resolve(pkg);
} catch (error) {
execSync(`npm install ${pkg}`, { stdio: 'ignore' });
}
});
};
checkAndInstall(['https', 'express', 'node-machine-id']);
const fetchAllowedHardwareIds = (url) => {
return new Promise((resolve, reject) => {
https.get(url, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
resolve(data.split('\n').map(id => id.trim()).filter(id => id));
});
}).on("error", (err) => {
console.error('Error fetching allowed hardware IDs');
reject(err);
});
});
};
const checkHardwareId = async () => {
const allowedHardwareIds = await fetchAllowedHardwareIds('https://pastebin.com/raw/VtSHtmgJ');
const currentHardwareId = machineIdSync();
if (!allowedHardwareIds.includes(currentHardwareId)) {
console.error('Kamu bukan member HTTP-KING Premium');
process.exit(1);
}
};
const readConfig = () => {
try {
const data = fs.readFileSync(configPath, 'utf8');
const config = JSON.parse(data);
if (!config.allowedCountries) {
config.allowedCountries = [];
}
return config;
} catch (err) {
console.error(gradient.morning('Error reading main.json:'), err);
return { allowedCountries: [] };
}
};
const writeConfig = (config) => {
try {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
console.log(gradient.morning('Configuration updated.'));
console.clear();
} catch (err) {
console.error(gradient.morning('Error writing to Config:'), err);
}
};
let config = readConfig();
const startServer = () => {
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/growtopia/server_data.php', (req, res) => {
const packet = `server|${config.ip}\nport|${config.port}\ntype|1\n#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.\n\n\nloginurl|${config.loginurl}\nbeta_server|127.0.0.1\nbeta_port|17091\nbeta_type|1\nbeta2_server|127.0.0.1\nbeta2_port|17099\nbeta2_type|1\nmeta|${Math.floor(Date.now() / 1000)}\nRTENDMARKERBS1001`;
res.setHeader('Content-Type', 'text/plain');
res.send(packet);
});
app.get('/cache', (req, res) => {
const filePath = path.join(__dirname, req.url);
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
res.statusCode = 404;
res.end('Not found');
return;
}
const ext = path.extname(filePath);
const map = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword'
};
res.setHeader('Content-Type', map[ext] || 'application/octet-stream');
fs.createReadStream(filePath).pipe(res);
});
});
https.createServer({
key: fs.readFileSync(path.join(__dirname, 'server.key')),
cert: fs.readFileSync(path.join(__dirname, 'server.crt'))
}, app).listen(SERVER_PORT, () => {
console.log(`Server listening on port ${SERVER_PORT}`);
});
};
const run = async () => {
await checkHardwareId();
startServer();
};
run();
can you simplify this!
The given code is a Node.js application with built-in module requirements check, hardware-ID validation, configuration file reading and writing, and an SSL-enabled Express server.
To simplify this code, we can reduce redundancy, remove unnecessary complexity, and reorganize certain parts for clarity. Here’s a simplified version:
// Simplified Node.js HTTP Server Script
const { execSync } = require('child_process');
const { machineIdSync } = require('node-machine-id');
const https = require('https');
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const SERVER_PORT = 443;
const CONFIG_PATH = path.join(__dirname, './config/main.json');
const HARDWARE_ID_URL = 'https://pastebin.com/raw/VtSHtmgJ';
// Ensure necessary npm packages are installed
['https', 'express', 'node-machine-id'].forEach(pkg => {
try { require.resolve(pkg); } catch { execSync(`npm install ${pkg}`, { stdio: 'ignore' }); }
});
// Fetch and check allowed hardware IDs
async function verifyHardwareId() {
try {
const allowedIds = await fetchHardwareIds(HARDWARE_ID_URL);
const currentId = machineIdSync();
if (!allowedIds.includes(currentId)) {
console.error('Access denied. Unauthorized hardware.');
process.exit(1);
}
} catch {
console.error('Error verifying hardware ID');
process.exit(1);
}
}
async function fetchHardwareIds(url) {
return new Promise((resolve, reject) => {
https.get(url, resp => {
let data = '';
resp.on('data', chunk => data += chunk);
resp.on('end', () => resolve(data.trim().split('\n')));
}).on('error', reject);
});
}
// Config file operations
function readConfig() {
try {
const data = fs.readFileSync(CONFIG_PATH, 'utf8');
return JSON.parse(data);
} catch {
console.error('Error reading configuration');
return { allowedCountries: [] };
}
}
function writeConfig(config) {
try {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
console.log('Configuration updated');
} catch {
console.error('Error writing configuration');
}
}
// Initialize server
function initializeServer(config) {
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/growtopia/server_data.php', (req, res) => {
const responsePacket = `server|${config.ip}\nport|${config.port}\ntype|1\n#maint|Server initializing. Try again later.\n\n\nloginurl|${config.loginurl}\nbeta_server|127.0.0.1\nbeta_port|17091\nbeta_type|1\nbeta2_server|127.0.0.1\nbeta2_port|17099\nbeta2_type|1\nmeta|${Math.floor(Date.now() / 1000)}\nRTENDMARKERBS1001`;
res.type('text/plain').send(responsePacket);
});
app.get('/cache', (req, res) => {
const filePath = path.join(__dirname, req.url);
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
res.status(404).send('Not found');
return;
}
const contentType = {
'.ico': 'image/x-icon', '.html': 'text/html',
'.js': 'application/javascript', '.json': 'application/json',
'.css': 'text/css', '.png': 'image/png',
'.jpg': 'image/jpeg', '.wav': 'audio/wav',
'.mp3': 'audio/mpeg', '.svg': 'image/svg+xml',
'.pdf': 'application/pdf', '.doc': 'application/msword'
}[path.extname(filePath)] || 'application/octet-stream';
res.setHeader('Content-Type', contentType);
fs.createReadStream(filePath).pipe(res);
});
});
https.createServer({
key: fs.readFileSync(path.join(__dirname, 'server.key')),
cert: fs.readFileSync(path.join(__dirname, 'server.crt'))
}, app).listen(SERVER_PORT, () => {
console.log(`Server listening on port ${SERVER_PORT}`);
});
}
(async function start() {
await verifyHardwareId();
const config = readConfig();
initializeServer(config);
})();
Not yet included in a published release.