File size: 13,028 Bytes
a08f3c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
'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 };