'use strict'; /** * ╔══════════════════════════════════════════════════════════════════════════╗ * Aternos API — v19.1 | WebSocket Protocol (يعمل على HuggingFace Spaces) ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ WebSocket Protocol الفعلي لـ Aternos ║ * ✅ يعمل بدون Puppeteer/Chrome — يستخدم HTTP + WebSocket ║ * ✅ كشف الحالة: Online/Offline/Starting/Queued ║ * ✅ تشغيل السيرفر عبر WebSocket ║ * ✅ متوافق مع HuggingFace Spaces ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */ const https = require('https'); const http = require('http'); const { EventEmitter } = require('events'); const WebSocket = require('ws'); const crypto = require('crypto'); const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms))); const randInt = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a; const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19); class AternosAPI extends EventEmitter { constructor(config = {}) { super(); this.username = config.username || process.env.ATERNOS_USER || ''; this.password = config.password || process.env.ATERNOS_PASS || ''; this.serverName = config.serverName || process.env.ATERNOS_SERVER || ''; this.baseUrl = 'https://aternos.org'; this.wsUrl = 'wss://binaryapi.aternos.org'; this.cookies = {}; this.serverId = null; this.ws = null; this.connected = false; this.serverStatus = 'unknown'; this.queuePosition = 0; this.serverInfo = { motd: '', players: 0, maxPlayers: 0, version: '', ram: 0 }; this.lastCheck = null; this._packetId = 0; this._xorKey = null; this._sessionId = null; this._token = null; this._reconnectAttempts = 0; this._maxReconnectAttempts = 10; this._statusResolve = null; this._log('API', 'تم إنشاء Aternos API wrapper (WebSocket Protocol)'); } _log(tag, msg) { const ts = tsNow(); console.log(`[${ts}] [ATERNOS-API] ${tag} ${msg}`); } _parseCookies(setCookies) { if (!setCookies) return; for (const c of setCookies) { const [kv] = c.split(';'); const [k, v] = kv.split('='); if (k && v) this.cookies[k.trim()] = v.trim(); } } _getCookieString() { return Object.entries(this.cookies).map(([k, v]) => `${k}=${v}`).join('; '); } async _httpRequest(method, path, body = null) { return new Promise((resolve, reject) => { const url = new URL(path, this.baseUrl); const headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.9', 'Origin': this.baseUrl, 'Referer': `${this.baseUrl}/go/` }; if (Object.keys(this.cookies).length) { headers['Cookie'] = this._getCookieString(); } if (body) { headers['Content-Type'] = 'application/x-www-form-urlencoded'; } const options = { hostname: url.hostname, port: 443, path: url.pathname + url.search, method, headers, timeout: 15000 }; const req = https.request(options, (res) => { let data = ''; this._parseCookies(res.headers['set-cookie']); res.on('data', chunk => data += chunk); res.on('end', () => resolve({ status: res.statusCode, data, headers: res.headers })); }); req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); }); req.on('error', reject); if (body) req.write(body); req.end(); }); } async login() { this._log('🔑', 'جاري تسجيل الدخول...'); try { const pageRes = await this._httpRequest('GET', '/go/'); const sessionMatch = pageRes.data.match(/session=([a-f0-9]+)/i); if (sessionMatch) { this._sessionId = sessionMatch[1]; this._log('✅', `Session ID: ${this._sessionId.slice(0, 8)}...`); } const tokenMatch = pageRes.data.match(/token=([a-f0-9]+)/i); if (tokenMatch) { this._token = tokenMatch[1]; this._log('✅', `Token: ${this._token.slice(0, 8)}...`); } if (this.username && this.password) { const formData = `user=${encodeURIComponent(this.username)}&password=${encodeURIComponent(this.password)}`; const loginRes = await this._httpRequest('POST', '/login/', formData); this._log('📊', `Login status: ${loginRes.status}`); if (loginRes.status === 302 || loginRes.status === 200) { this.connected = true; this._log('✅', 'تم تسجيل الدخول بنجاح!'); return true; } } if (this.cookies['ATERNOS_SESSION'] || this._sessionId) { this.connected = true; this._log('✅', 'جلسة موجودة!'); return true; } this._log('⚠️', 'يجب تسجيل الدخول يدوياً أو تفعيل ATERNOS_USER/PASS'); return false; } catch (e) { this._log('❌', `فشل تسجيل الدخول: ${e.message}`); return false; } } _encryptPacket(data) { if (!this._xorKey) return data; const buf = Buffer.from(data); for (let i = 0; i < buf.length; i++) { buf[i] ^= this._xorKey[i % this._xorKey.length]; } return buf; } _decryptPacket(data) { return this._encryptPacket(data); } _buildPacket(action, payload = {}) { const id = ++this._packetId; const packet = { id, action, ...payload }; return JSON.stringify(packet); } async _connectWebSocket() { return new Promise((resolve, reject) => { try { const cookieHeader = this._getCookieString(); this.ws = new WebSocket(this.wsUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', 'Origin': this.baseUrl, 'Cookie': cookieHeader }, rejectUnauthorized: false }); this.ws.on('open', () => { this._log('🔗', 'WebSocket متصل!'); this._reconnectAttempts = 0; resolve(true); }); this.ws.on('message', (data) => { try { const msg = data.toString(); this._handleMessage(msg); } catch (_) {} }); this.ws.on('close', (code, reason) => { this._log('🔌', `WebSocket انقطع: ${code} ${reason}`); this.emit('wsDisconnected'); }); this.ws.on('error', (err) => { this._log('❌', `WebSocket خطأ: ${err.message}`); reject(err); }); setTimeout(() => { if (this.ws.readyState !== WebSocket.OPEN) { this.ws.close(); reject(new Error('WebSocket timeout')); } }, 10000); } catch (e) { reject(e); } }); } _handleMessage(raw) { try { const msg = JSON.parse(raw); if (msg.type === 'server') { if (msg.status !== undefined) { const statusMap = { 0: 'offline', 1: 'starting', 2: 'online', 3: 'stopping', 4: 'queued' }; const oldStatus = this.serverStatus; this.serverStatus = statusMap[msg.status] || 'unknown'; if (oldStatus !== this.serverStatus) { this._log('🔄', `الحالة: ${oldStatus} → ${this.serverStatus}`); this.emit('statusChange', this.serverStatus); } } if (msg.players) { this.serverInfo.players = msg.players.online || 0; this.serverInfo.maxPlayers = msg.players.max || 0; } if (msg.motd) this.serverInfo.motd = msg.motd; if (msg.version) this.serverInfo.version = msg.version; if (msg.ram) this.serverInfo.ram = msg.ram; if (msg.queue !== undefined) { this.queuePosition = msg.queue; if (msg.queue > 0) { this._log('⏳', `في الطابور — المركز: ${msg.queue}`); this.emit('queue', msg.queue); } } if (this._statusResolve) { this._statusResolve(this.serverStatus); this._statusResolve = null; } } if (msg.type === 'xorkey') { this._xorKey = Buffer.from(msg.key, 'base64'); this._log('🔑', 'تم استلام XOR key'); } } catch (_) {} } async getServerStatus() { if (!this.connected) { const loggedIn = await this.login(); if (!loggedIn) return 'unknown'; } try { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { await this._connectWebSocket(); } const packet = this._buildPacket('info'); this.ws.send(packet); return new Promise((resolve) => { this._statusResolve = resolve; setTimeout(() => { if (this._statusResolve) { this._statusResolve = null; resolve(this.serverStatus); } }, 5000); }); } catch (e) { this._log('❌', `خطأ في فحص الحالة: ${e.message}`); return this.serverStatus; } } async startServer() { if (!this.connected) { const loggedIn = await this.login(); if (!loggedIn) return false; } this._log('🚀', 'جاري تشغيل السيرفر...'); try { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { await this._connectWebSocket(); } const packet = this._buildPacket('start'); this.ws.send(packet); this.serverStatus = 'starting'; this.emit('statusChange', 'starting'); this._log('✅', 'تم إرسال أمر التشغيل!'); return true; } catch (e) { this._log('❌', `فشل التشغيل: ${e.message}`); return false; } } async stopServer() { if (!this.connected) return false; this._log('⏹', 'جاري إيقاف السيرفر...'); try { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { await this._connectWebSocket(); } const packet = this._buildPacket('stop'); this.ws.send(packet); this.serverStatus = 'stopping'; this.emit('statusChange', 'stopping'); return true; } catch (e) { this._log('❌', `فشل الإيقاف: ${e.message}`); return false; } } async waitForStatus(targetStatus, timeoutMs = 600000, pollIntervalMs = 10000) { this._log('⏳', `في انتظار: ${targetStatus} (مهلة: ${Math.round(timeoutMs / 1000)}ث)`); const start = Date.now(); while (Date.now() - start < timeoutMs) { const status = await this.getServerStatus(); if (status === targetStatus) { this._log('✅', `وصل: ${targetStatus}`); return true; } if (status === 'offline' && targetStatus === 'online') { this._log('🔄', 'السيرفر Offline — محاولة إعادة التشغيل...'); await this.startServer(); } await sleep(pollIntervalMs); } this._log('⏱️', `انتهت المهلة — لم يصل: ${targetStatus}`); return false; } async autoStart() { this._log('🔄', 'Auto-start: فحص الحالة...'); const status = await this.getServerStatus(); if (status === 'online') { this._log('✅', 'السيرفر يعمل بالفعل!'); return true; } if (status === 'starting' || status === 'loading') { return await this.waitForStatus('online', 600000); } if (status === 'offline' || status === 'unknown') { const started = await this.startServer(); if (!started) return false; return await this.waitForStatus('online', 600000); } return false; } async getFullStatus() { await this.getServerStatus(); return { connected: this.connected, wsConnected: this.ws && this.ws.readyState === WebSocket.OPEN, serverId: this.serverId, status: this.serverStatus, queue: this.queuePosition, info: this.serverInfo, lastCheck: Date.now(), timestamp: Date.now() }; } disconnect() { if (this.ws) { this.ws.close(); this.ws = null; } this.connected = false; } } module.exports = { AternosAPI };