mohammed978 commited on
Commit
46f09ee
·
verified ·
1 Parent(s): d431b1e

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +550 -440
bot.py CHANGED
@@ -1,509 +1,619 @@
1
- """
2
- 🐺 White Wolf Ultimate - Premium Hosting System
3
- Architecture: Single File, Component-based (PaaS Level)
4
- """
5
-
6
  import os
7
- import re
 
8
  import uuid
9
- import shutil
10
- import sqlite3
11
  import zipfile
 
 
 
 
12
  import logging
13
- import subprocess
14
- from datetime import datetime
15
-
16
- # مكتبات النظام الخارجي (يجب توفرها)
17
- import psutil
18
- import telebot
19
- from telebot import types
20
 
21
- # ================= CONFIGURATION =================
 
 
22
  TOKEN = '7847673598:AAGeqJb591uZWCwpSqS8VJGWTRtDOr0CTEE'
23
  ADMIN_ID = 6812997550
24
- CHANNELS = ['@EQJ_1']
 
25
 
26
- # مسارات النظام
27
- HOSTING_DIR = os.path.abspath('wolf_cluster')
28
- DB_PATH = os.path.join(HOSTING_DIR, 'core.db')
 
29
 
30
- os.makedirs(HOSTING_DIR, exist_ok=True)
 
 
31
 
32
- # إعداد البوت
33
- bot = telebot.TeleBot(TOKEN, parse_mode='Markdown')
34
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
35
- # =================================================
36
-
37
- class DatabaseManager:
38
- """إدارة قاعدة البيانات بكفاءة وأمان بين المسارات"""
39
- def __init__(self, path):
40
- self.db_path = path
41
- self._init_db()
42
-
43
- def _get_conn(self):
44
- conn = sqlite3.connect(self.db_path, check_same_thread=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  conn.row_factory = sqlite3.Row
46
  return conn
47
 
48
- def _init_db(self):
49
- with self._get_conn() as c:
 
50
  c.execute('''CREATE TABLE IF NOT EXISTS users (
51
- user_id INTEGER PRIMARY KEY, username TEXT, plan TEXT DEFAULT 'free', joined_at TIMESTAMP
 
 
52
  )''')
53
  c.execute('''CREATE TABLE IF NOT EXISTS projects (
54
- project_id TEXT PRIMARY KEY, user_id INTEGER, file_name TEXT, file_type TEXT,
55
- path TEXT, container_name TEXT, created_at TIMESTAMP
 
56
  )''')
57
- c.commit()
58
-
59
- def register_user(self, uid, username):
60
- with self._get_conn() as c:
61
- c.execute("INSERT OR IGNORE INTO users (user_id, username, joined_at) VALUES (?, ?, ?)",
62
- (uid, username, datetime.now()))
63
- c.commit()
64
-
65
- def get_user(self, uid):
66
- with self._get_conn() as c:
67
- res = c.execute("SELECT * FROM users WHERE user_id = ?", (uid,)).fetchone()
68
- return dict(res) if res else {'plan': 'free'}
69
-
70
- def get_projects(self, uid):
71
- with self._get_conn() as c:
72
- return[dict(r) for r in c.execute("SELECT * FROM projects WHERE user_id = ?", (uid,)).fetchall()]
73
-
74
- def get_project(self, pid):
75
- with self._get_conn() as c:
76
- res = c.execute("SELECT * FROM projects WHERE project_id = ?", (pid,)).fetchone()
77
- return dict(res) if res else None
78
-
79
- def add_project(self, pid, uid, fname, ftype, path):
80
- with self._get_conn() as c:
81
- c.execute("INSERT INTO projects (project_id, user_id, file_name, file_type, path, container_name, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
82
- (pid, uid, fname, ftype, path, f"wolf_{pid}", datetime.now()))
83
- c.commit()
84
-
85
- def delete_project(self, pid):
86
- with self._get_conn() as c:
87
- c.execute("DELETE FROM projects WHERE project_id = ?", (pid,))
88
- c.commit()
89
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  class SecurityScanner:
91
- """نظام فحص أمني دقيق لمنع الملفات الخبيثة وتأمين السيرفر"""
92
- DANGEROUS_PATTERNS =[
93
- rb"os\.system", rb"os\.popen", rb"subprocess", rb"eval\(", rb"exec\(",
94
- rb"__import__", rb"pty\.spawn", rb"shutil\.rmtree", rb"sys\.exit"
95
- ]
96
-
97
  @staticmethod
98
- def scan_file(file_path):
 
99
  try:
100
- with open(file_path, 'rb') as f:
101
- content = f.read()
102
-
103
- # منع الملفات التنفيذية أو الثنائية (Binaries)
104
- if b'\x00' in content or content.startswith(b'MZ') or content.startswith(b'\x7fELF'):
105
- return False, "تم العثور على صيغ ثنائية غير مسموحة."
106
-
107
- # منع الأكواد التي تتحكم بالنظام
108
- for pattern in SecurityScanner.DANGEROUS_PATTERNS:
109
- if re.search(pattern, content):
110
- return False, f"تم حظر الملف لاحتوائه على دوال محظورة."
111
-
112
- return True, "✅ آمن"
113
- except Exception:
114
- return False, "فشل فحص الملف."
115
-
116
- class DockerManager:
117
- """محرك التشغيل باستخدام Docker لضمان العزل ومحدودية الموارد"""
118
  @staticmethod
119
- def check_system():
120
- try:
121
- subprocess.run(['docker', 'info'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
122
- return True
123
- except: return False
124
-
125
- @staticmethod
126
- def run_container(proj_id, file_path, file_type):
127
- if not DockerManager.check_system():
128
- return False, "⚠️ نظام Docker غير متصل بالسيرفر."
129
-
130
- container_name = f"wolf_{proj_id}"
131
- proj_dir = os.path.dirname(os.path.abspath(file_path))
132
- file_name = os.path.basename(file_path)
133
-
134
- DockerManager.remove_container(proj_id)
135
-
136
- # القيود الذكية حسب الطلب + خاصية Auto Restart
137
- cmd =[
138
- 'docker', 'run', '-d',
139
- '--name', container_name,
140
- '--memory=256m',
141
- '--cpus=0.5',
142
- '--pids-limit=64',
143
- '--network=bridge',
144
- '--restart=on-failure:5',
145
- '-v', f"{proj_dir}:/app",
146
- '-w', '/app'
147
- ]
148
-
149
- if file_type == 'py':
150
- req_path = os.path.join(proj_dir, 'requirements.txt')
151
- pip_cmd = "pip install -r requirements.txt > /dev/null 2>&1" if os.path.exists(req_path) else "pip install --quiet pyTelegramBotAPI requests aiohttp python-dotenv > /dev/null 2>&1"
152
- cmd.extend(['python:3.10-slim', 'sh', '-c', f"{pip_cmd} && python -u {file_name}"])
153
- else:
154
- cmd.extend(['node:18-alpine', 'sh', '-c', f"npm install --quiet > /dev/null 2>&1 && node {file_name}"])
155
-
156
  try:
157
- subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
158
- return True, "✅ تم تشغيل المشروع."
159
- except subprocess.CalledProcessError:
160
- return False, "⚠️ فشل بدء حاوية المشروع."
161
-
162
- @staticmethod
163
- def stop_container(proj_id):
164
- subprocess.run(['docker', 'stop', '-t', '2', f"wolf_{proj_id}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
165
 
166
- @staticmethod
167
- def remove_container(proj_id):
168
- subprocess.run(['docker', 'rm', '-f', f"wolf_{proj_id}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
 
 
169
 
170
- @staticmethod
171
- def get_logs(proj_id):
172
  try:
173
- res = subprocess.run(['docker', 'logs', '--tail', '20', f"wolf_{proj_id}"], capture_output=True, text=True)
174
- logs = (res.stdout + res.stderr).strip()
175
- return logs if logs else "📭 لا توجد سجلات بعد."
176
- except: return "⚠️ تعذر جلب السجلات."
 
 
 
 
 
 
 
 
 
 
 
177
 
178
  @staticmethod
179
- def get_status(proj_id):
 
180
  try:
181
- res = subprocess.run(['docker', 'inspect', '--format', '{{.State.Status}}', f"wolf_{proj_id}"], capture_output=True, text=True)
182
- status = res.stdout.strip()
183
- if status == 'running': return '🟢 يعمل'
184
- if status == 'exited': return '🔴 متوقف'
185
- if status == 'restarting': return '⏳ يعيد التشغيل'
186
- return f"⚪ {status}"
187
- except: return "⚪ غير متصل"
188
-
189
- class UIEngine:
190
- """محرك واجهة المستخدم المتطور"""
191
- @staticmethod
192
- def safe_send(chat_id, text, markup=None):
193
- try: return bot.send_message(chat_id, text, reply_markup=markup, parse_mode='Markdown')
194
- except: pass
195
-
196
- @staticmethod
197
- def safe_edit(call, text, markup=None):
198
- try: bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup, parse_mode='Markdown')
199
  except: pass
200
 
201
  @staticmethod
202
- def loading(call, text="⏳ جاري التنفيذ..."):
203
- UIEngine.safe_edit(call, text)
 
 
 
 
204
 
205
  @staticmethod
206
- def btn(text, cb):
207
- """تصنيف ذكي للأزرار لمحاكاة ستايلات Telegram / CSS"""
208
- danger =['حذف', 'إلغاء', 'إيقاف', 'رفض']
209
- success =['تشغيل', 'تأكيد', 'قبول', 'نعم', 'تفعيل']
210
-
211
- style = 'primary'
212
- icon = "🔵"
213
- if any(w in text for w in danger): style, icon = 'danger', "🔴"
214
- elif any(w in text for w in success): style, icon = 'success', "🟢"
215
-
216
- # إضافة الآيقونة إذا لم يكن النص يحتوي على إيموجي بالفعل
217
- if not any(e in text for e in['🟢', '🔴', '🔵', '🗑️', '🛑', '▶️', '🔙', '📤', '📋', '👤', '📊', '⚙️', '📋']):
218
- text = f"{icon} {text}"
219
-
220
- btn = types.InlineKeyboardButton(text=text, callback_data=cb)
221
- btn.style = style # تعيين الخاصية منطقياً كما طُلب لسهولة التحكم
222
- return btn
223
-
224
  @staticmethod
225
- def menu_main(user):
226
  markup = types.InlineKeyboardMarkup(row_width=2)
227
- markup.add(UIEngine.btn("📤 رفع مشروع", "ui_upload"), UIEngine.btn("📋 مشاريعي", "ui_projects"))
228
- markup.add(UIEngine.btn("👤 حسابي", "ui_profile"), UIEngine.btn("📊 النظام", "ui_sys"))
229
- if user['user_id'] == ADMIN_ID: markup.add(UIEngine.btn("⚙️ لوحة الإدارة", "ui_admin"))
 
 
 
 
 
 
 
 
 
230
  return markup
231
 
232
  @staticmethod
233
- def menu_project(proj, status):
234
  markup = types.InlineKeyboardMarkup(row_width=2)
235
- if 'يعمل' in status: markup.add(UIEngine.btn("🛑 إيقاف المشروع", f"proj_stop_{proj['project_id']}"))
236
- else: markup.add(UIEngine.btn("▶️ تشغيل المشروع", f"proj_start_{proj['project_id']}"))
237
-
238
- markup.add(UIEngine.btn("📋 السجلات", f"proj_logs_{proj['project_id']}"), UIEngine.btn("🔄 إعادة تشغيل", f"proj_restart_{proj['project_id']}"))
239
- markup.add(UIEngine.btn("🗑️ حذف المشروع", f"proj_del_{proj['project_id']}"))
240
- markup.add(UIEngine.btn("🔙 رجوع", "ui_projects"))
 
 
 
 
 
 
 
 
 
 
 
241
  return markup
242
 
243
- # تهيئة قاعدة البيانات والحالة
244
- db = DatabaseManager(DB_PATH)
 
 
 
 
 
245
  user_states = {}
246
 
247
- # ================= HANDLERS =================
 
 
 
 
 
 
 
 
 
248
 
249
  @bot.message_handler(commands=['start'])
250
- def cmd_start(msg):
251
- uid = msg.from_user.id
252
- db.register_user(uid, msg.from_user.username)
253
- user = db.get_user(uid)
254
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  text = (
256
- f"👋 أهلاً بك يا {msg.from_user.first_name} في **White Wolf Ultimate** 🐺\n\n"
257
- "✨ *نظام الاستضافة السحابية الأقوى*\n"
258
- "🔹 تشغيل عبر حاويات Docker المعزولة.\n"
259
- "🔹 أمان عالي، استقرار مطلق ومراقبة حية.\n\n"
260
- "اختر من القائمة أدناه للبدء:"
261
  )
262
- UIEngine.safe_send(msg.chat.id, text, UIEngine.menu_main(user))
263
 
264
- @bot.message_handler(content_types=['document'])
265
- def handle_upload(msg):
266
- uid = msg.from_user.id
267
- if user_states.get(uid) != 'upload': return
 
268
 
269
- user = db.get_user(uid)
270
- projs = db.get_projects(uid)
271
- limit = 1 if user.get('plan') != 'vip' else 10
272
- if uid == ADMIN_ID: limit = 999
273
-
274
- if len(projs) >= limit:
275
- UIEngine.safe_send(msg.chat.id, "⚠️ **وصلت للحد الأقصى للمشاريع المسموحة في باقتك.**")
276
- user_states.pop(uid, None)
277
- return
278
-
279
- fname = msg.document.file_name
280
- if not (fname.endswith('.py') or fname.endswith('.js') or fname.endswith('.zip')):
281
- UIEngine.safe_send(msg.chat.id, "⚠️ **عذراً،** النظام يدعم ملفات `.py`, `.js`, و `.zip` فقط.")
282
- return
283
-
284
- UIEngine.safe_send(msg.chat.id, "⏳ جاري تحميل وفحص الملف بأمان...")
285
-
286
- try:
287
- file_info = bot.get_file(msg.document.file_id)
288
- content = bot.download_file(file_info.file_path)
289
- except:
290
- return UIEngine.safe_send(msg.chat.id, "❌ حدث خطأ أثناء جلب الملف من تيليجرام.")
291
-
292
- proj_id = str(uuid.uuid4())[:8]
293
- user_dir = os.path.join(HOSTING_DIR, str(uid))
294
- os.makedirs(user_dir, exist_ok=True)
295
- tmp_path = os.path.join(user_dir, f"tmp_{proj_id}_{fname}")
296
-
297
- with open(tmp_path, 'wb') as f: f.write(content)
298
-
299
- # معالجة ملفات ZIP
300
- if fname.endswith('.zip'):
301
- extract_dir = os.path.join(user_dir, proj_id)
302
- with zipfile.ZipFile(tmp_path, 'r') as zf: zf.extractall(extract_dir)
303
- os.remove(tmp_path)
304
-
305
- main_file = next((os.path.join(r, f) for r, d, files in os.walk(extract_dir) for f in files if f in['main.py', 'bot.py', 'index.js']), None)
306
- if not main_file:
307
- shutil.rmtree(extract_dir)
308
- return UIEngine.safe_send(msg.chat.id, "⚠️ **لم يتم العثور على ملف التشغيل.** يجب أن يحتوي المجلد على `main.py` أو `bot.py` أو `index.js`.")
309
-
310
- for r, d, files in os.walk(extract_dir):
311
- for f in files:
312
- if f.endswith('.py') or f.endswith('.js'):
313
- safe, sec_msg = SecurityScanner.scan_file(os.path.join(r, f))
314
- if not safe:
315
- shutil.rmtree(extract_dir)
316
- return UIEngine.safe_send(msg.chat.id, f"🚫 **تم رفض الكود لاحتوائه على ثغرة أو أمر خطير:**\n{sec_msg}")
317
-
318
- final_path = main_file
319
- fname = os.path.basename(main_file)
320
- else:
321
- # معالجة ملف فردي
322
- safe, sec_msg = SecurityScanner.scan_file(tmp_path)
323
- if not safe:
324
- os.remove(tmp_path)
325
- return UIEngine.safe_send(msg.chat.id, f"🚫 **مرفوض:**\n{sec_msg}")
326
-
327
- final_path = os.path.join(user_dir, f"{proj_id}_{fname}")
328
- os.rename(tmp_path, final_path)
329
-
330
- file_type = 'py' if fname.endswith('.py') else 'js'
331
- db.add_project(proj_id, uid, fname, file_type, final_path)
332
- user_states.pop(uid, None)
333
-
334
- markup = types.InlineKeyboardMarkup().add(
335
- UIEngine.btn("▶️ تشغيل الآن", f"proj_start_{proj_id}"),
336
- UIEngine.btn("🔙 القائمة", "main_menu")
337
- )
338
- UIEngine.safe_send(msg.chat.id, "✅ **تم معالجة ورفع المشروع بأمان!**\nهو الآن معزول بالكامل وجاهز للاستخدام.", markup)
339
 
340
- @bot.callback_query_handler(func=lambda c: True)
341
- def handle_callbacks(call):
342
- uid = call.from_user.id
343
- data = call.data
344
- user = db.get_user(uid)
345
 
346
- if data == "main_menu":
347
- user_states.pop(uid, None)
348
- UIEngine.safe_edit(call, "🏠 **القائمة الرئيسية**\nاختر الإجراء المطلوب:", UIEngine.menu_main(user))
349
-
350
- elif data == "ui_upload":
351
- user_states[uid] = 'upload'
352
- UIEngine.safe_edit(call, "📤 **رفع مشروع جديد**\n\nأرسل الآن ملف `bot.py` أو `index.js` أو ملف `.zip` متكامل.\nسيقوم النظام بفحصه ورفعه لبيئة Docker فوراً.", markup=types.InlineKeyboardMarkup().add(UIEngine.btn("🔙 إلغاء", "main_menu")))
 
 
 
 
 
353
 
354
- elif data == "ui_projects":
355
- projs = db.get_projects(uid)
356
- if not projs: return bot.answer_callback_query(call.id, "📭 لا تملك أي مشاريع حالياً.", show_alert=True)
 
357
 
 
358
  markup = types.InlineKeyboardMarkup(row_width=1)
 
 
 
 
 
 
 
 
 
 
359
  for p in projs:
360
- icon = "🟢" if 'يعمل' in DockerManager.get_status(p['project_id']) else "🔴"
361
- markup.add(UIEngine.btn(f"{icon} {p['file_name']}", f"proj_view_{p['project_id']}"))
362
- markup.add(UIEngine.btn("🔙 رجوع", "main_menu"))
363
- UIEngine.safe_edit(call, "📋 **مشاريعك الحالية:**\nاختر مشروعاً للتحكم به:", markup)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
 
365
- elif data.startswith("proj_view_"):
366
- pid = data.split("_")[2]
367
- p = db.get_project(pid)
368
- if not p: return bot.answer_callback_query(call.id, "⚠️ المشروع غير موجود.", show_alert=True)
 
 
 
 
 
 
 
 
 
 
 
369
 
370
- status = DockerManager.get_status(pid)
371
- text = (
372
- f"📦 **المشروع:** `{p['file_name']}`\n"
373
- f"🆔 **المعرف:** `{p['project_id']}`\n"
374
- f"🚦 **الحالة:** {status}\n"
375
- f"📅 **الإنشاء:** `{p['created_at'][:16]}`"
376
- )
377
- UIEngine.safe_edit(call, text, UIEngine.menu_project(p, status))
378
-
379
- elif data.startswith("proj_start_"):
380
- pid = data.split("_")[2]
381
- p = db.get_project(pid)
382
- UIEngine.loading(call, "⏳ جاري إعداد وتجهيز الحاوية المعزولة...")
383
- success, msg = DockerManager.run_container(pid, p['path'], p['file_type'])
384
- bot.answer_callback_query(call.id, msg, show_alert=not success)
385
-
386
- call.data = f"proj_view_{pid}"
387
- handle_callbacks(call)
388
-
389
- elif data.startswith("proj_stop_"):
390
- pid = data.split("_")[2]
391
- UIEngine.loading(call, "🛑 جاري إيقاف العملية بأمان...")
392
- DockerManager.stop_container(pid)
393
- bot.answer_callback_query(call.id, "✅ تم إيقاف المشروع.")
394
-
395
- call.data = f"proj_view_{pid}"
396
- handle_callbacks(call)
397
-
398
- elif data.startswith("proj_restart_"):
399
- pid = data.split("_")[2]
400
- p = db.get_project(pid)
401
- UIEngine.loading(call, "🔄 جاري إعادة الإقلاع...")
402
- DockerManager.run_container(pid, p['path'], p['file_type'])
403
- bot.answer_callback_query(call.id, "✅ تمت إعادة التشغيل.")
404
-
405
- call.data = f"proj_view_{pid}"
406
- handle_callbacks(call)
407
 
408
- elif data.startswith("proj_logs_"):
409
- pid = data.split("_")[2]
410
- logs = DockerManager.get_logs(pid)
411
- if len(logs) > 3000: logs = logs[-3000:] # تحديد حجم العرض
412
-
413
- text = f"📋 **سجلات المخرجات (Console):**\n```text\n{logs}\n```"
414
- markup = types.InlineKeyboardMarkup().add(UIEngine.btn("🔙 رجوع للمشروع", f"proj_view_{pid}"))
415
- UIEngine.safe_edit(call, text, markup)
416
-
417
- elif data.startswith("proj_del_"):
418
- pid = data.split("_")[2]
419
- markup = types.InlineKeyboardMarkup().add(
420
- UIEngine.btn("⚠️ تأكيد الحذف النهائي", f"proj_confirmdel_{pid}"),
421
- UIEngine.btn("🔙 تراجع", f"proj_view_{pid}")
422
- )
423
- UIEngine.safe_edit(call, "⚠️ **تنبيه أمني:**\nهل أنت متأكد من حذف هذا المشروع نهائياً؟ سيتم مسح جميع الملفات وإيقاف الحاوية.", markup)
424
-
425
- elif data.startswith("proj_confirmdel_"):
426
- pid = data.split("_")[2]
427
- p = db.get_project(pid)
428
- if p:
429
- UIEngine.loading(call, "🗑️ جاري التنظيف وإزالة المشروع...")
430
- DockerManager.remove_container(pid)
431
- target_path = p['path'] if p['file_type'] != 'zip' else os.path.dirname(p['path'])
432
- if os.path.exists(target_path):
433
- shutil.rmtree(os.path.dirname(p['path']), ignore_errors=True)
434
- db.delete_project(pid)
435
- bot.answer_callback_query(call.id, "✅ تم الحذف بالكامل.")
436
-
437
- call.data = "ui_projects"
438
- handle_callbacks(call)
439
-
440
- elif data == "ui_profile":
441
- projs = db.get_projects(uid)
442
- limit = 1 if user['plan'] != 'vip' else 10
443
- plan_name = "Premium VIP 💎" if user['plan'] == 'vip' else "مجاني 🆓"
444
-
445
- text = (
446
- f"👤 **الملف الشخصي**\n\n"
447
- f"🔸 **معرف الحساب:** `{uid}`\n"
448
- f"🔸 **نوع الباقة:** {plan_name}\n"
449
- f"🔸 **استهلاك المشاريع:** `{len(projs)} / {limit}`\n"
 
 
450
  )
451
- UIEngine.safe_edit(call, text, types.InlineKeyboardMarkup().add(UIEngine.btn("🔙 القائمة", "main_menu")))
 
452
 
453
- elif data == "ui_sys":
454
- cpu = psutil.cpu_percent()
455
- ram = psutil.virtual_memory()
 
456
 
457
- text = (
458
- f"📊 **مراقبة موارد السيرفر (Live):**\n\n"
459
- f"🧠 **استهلاك المعالج:** `{cpu}%`\n"
460
- f"💾 **استهلاك الذاكرة:** `{ram.percent}%`\n"
461
- f"🐳 **حالة محرك Docker:** `{'نشط 🟢' if DockerManager.check_system() else 'مغلق 🔴'}`\n"
462
- )
463
- UIEngine.safe_edit(call, text, types.InlineKeyboardMarkup().add(UIEngine.btn("🔙 القائمة", "main_menu")))
464
 
465
- elif data == "ui_admin":
466
- if uid != ADMIN_ID: return
467
- users_count = db._get_conn().execute("SELECT COUNT(*) FROM users").fetchone()[0]
468
- projs_count = db._get_conn().execute("SELECT COUNT(*) FROM projects").fetchone()[0]
469
-
470
  text = (
471
- f"👑 **مركز الإدارة المتطور**\n\n"
472
- f"👥 **العملاء المسجلين:** `{users_count}`\n"
473
- f"📦 **المشاريع المحتضنة:** `{projs_count}`\n"
 
 
 
 
 
474
  )
475
- markup = types.InlineKeyboardMarkup(row_width=1).add(
476
- UIEngine.btn("📢 إرسال بث للجميع", "admin_broadcast"),
477
- UIEngine.btn("🔙 القائمة", "main_menu")
478
- )
479
- UIEngine.safe_edit(call, text, markup)
480
-
481
- elif data == "admin_broadcast":
482
- if uid != ADMIN_ID: return
483
- user_states[uid] = 'broadcast'
484
- UIEngine.safe_edit(call, "📢 **أرسل الرسالة ليتم بثها الآن:**\n(تدعم جميع أنواع الوسائط والنصوص)", markup=types.InlineKeyboardMarkup().add(UIEngine.btn("🔙 إلغاء", "ui_admin")))
485
-
486
- @bot.message_handler(func=lambda m: user_states.get(m.from_user.id) == 'broadcast')
487
- def handle_broadcast(msg):
488
- uid = msg.from_user.id
489
- if uid != ADMIN_ID: return
490
- user_states.pop(uid, None)
491
-
492
- users = db._get_conn().execute("SELECT user_id FROM users").fetchall()
493
- success = 0
494
- UIEngine.safe_send(msg.chat.id, "⏳ جاري تنفيذ الإذاعة الشاملة...")
 
 
 
495
 
496
- for u in users:
497
- try:
498
- bot.copy_message(u[0], msg.chat.id, msg.message_id)
499
- success += 1
500
- except: pass
501
-
502
- UIEngine.safe_send(msg.chat.id, f"✅ **اكتملت الإذاعة بنجاح إلى {success} عميل!**", markup=types.InlineKeyboardMarkup().add(UIEngine.btn("🔙 لوحة الإدارة", "ui_admin")))
503
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504
  if __name__ == '__main__':
505
- logging.info(f"🐺 White Wolf PaaS Edition is Booting Up...")
506
  try:
507
- bot.infinity_polling(timeout=60, skip_pending=True)
508
  except Exception as e:
509
- logging.error(f"Critical System Error: {e}")
 
1
+ import telebot
2
+ from telebot import types
3
+ import docker
4
+ import sqlite3
5
+ import threading
6
  import os
7
+ import sys
8
+ import time
9
  import uuid
10
+ import json
11
+ import psutil
12
  import zipfile
13
+ import shutil
14
+ import ast
15
+ import random
16
+ import string
17
  import logging
18
+ from datetime import datetime, timedelta
19
+ from apscheduler.schedulers.background import BackgroundScheduler
 
 
 
 
 
20
 
21
+ # ==========================================
22
+ # ⚙️ الإعدادات الأساسية (Configuration)
23
+ # ==========================================
24
  TOKEN = '7847673598:AAGeqJb591uZWCwpSqS8VJGWTRtDOr0CTEE'
25
  ADMIN_ID = 6812997550
26
+ YOUR_USERNAME = '@EQJ_1'
27
+ CHANNELS =['@EQJ_1']
28
 
29
+ HOSTING_DIR = 'wolf_projects'
30
+ BACKUP_DIR = 'wolf_backups'
31
+ DB_NAME = 'whitewolf_cloud.db'
32
+ VERSION = '6.0.0 Ultimate Docker Edition'
33
 
34
+ # إنشاء مسارات النظام
35
+ for d in [HOSTING_DIR, BACKUP_DIR]:
36
+ os.makedirs(d, exist_ok=True)
37
 
38
+ # إعداد السجلات
 
39
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
40
+ logger = logging.getLogger("WhiteWolf-Cloud")
41
+
42
+ bot = telebot.TeleBot(TOKEN, parse_mode="Markdown")
43
+
44
+ # الاتصال بـ Docker
45
+ try:
46
+ docker_client = docker.from_env()
47
+ logger.info("✅ تم الاتصال بمحرك Docker بنجاح!")
48
+ except Exception as e:
49
+ logger.error(f"❌ فشل الاتصال بـ Docker: {e}")
50
+ docker_client = None
51
+
52
+ # ==========================================
53
+ # 📊 الخطط والأسعار (Plans & Pricing)
54
+ # ==========================================
55
+ PLAN_LIMITS = {
56
+ 'free': {'projects': 1, 'label': '🆓 مجاني', 'price': 0, 'ram': '50m'},
57
+ 'silver': {'projects': 3, 'label': '🥈 فضي', 'price': 10, 'ram': '100m'},
58
+ 'gold': {'projects': 5, 'label': '🥇 ذهبي', 'price': 25, 'ram': '250m'},
59
+ 'diamond': {'projects': 10, 'label': '💎 ماسي', 'price': 50, 'ram': '512m'},
60
+ }
61
+ INVITE_REWARD = 2
62
+
63
+ # ==========================================
64
+ # 🗄️ محرك قاعدة البيانات (Database Engine)
65
+ # ==========================================
66
+ class DatabaseEngine:
67
+ def __init__(self):
68
+ self.lock = threading.Lock()
69
+ self.init_db()
70
+
71
+ def get_conn(self):
72
+ conn = sqlite3.connect(DB_NAME, check_same_thread=False)
73
  conn.row_factory = sqlite3.Row
74
  return conn
75
 
76
+ def init_db(self):
77
+ with self.lock, self.get_conn() as conn:
78
+ c = conn.cursor()
79
  c.execute('''CREATE TABLE IF NOT EXISTS users (
80
+ user_id INTEGER PRIMARY KEY, username TEXT, points INTEGER DEFAULT 0,
81
+ plan TEXT DEFAULT 'free', plan_expires TIMESTAMP, is_vip INTEGER DEFAULT 0,
82
+ total_invites INTEGER DEFAULT 0, is_banned INTEGER DEFAULT 0, joined_at TIMESTAMP
83
  )''')
84
  c.execute('''CREATE TABLE IF NOT EXISTS projects (
85
+ project_id TEXT PRIMARY KEY, user_id INTEGER, file_name TEXT, path TEXT,
86
+ container_id TEXT, status TEXT DEFAULT 'pending', auto_restart INTEGER DEFAULT 1,
87
+ env_vars TEXT DEFAULT '{}', created_at TIMESTAMP
88
  )''')
89
+ c.execute('''CREATE TABLE IF NOT EXISTS coupons (
90
+ code TEXT PRIMARY KEY, value INTEGER, max_uses INTEGER, used_count INTEGER DEFAULT 0
91
+ )''')
92
+ c.execute('''CREATE TABLE IF NOT EXISTS templates (
93
+ id TEXT PRIMARY KEY, name TEXT, desc TEXT, path TEXT, downloads INTEGER DEFAULT 0
94
+ )''')
95
+ conn.commit()
96
+
97
+ def add_user(self, user_id, username):
98
+ with self.lock, self.get_conn() as conn:
99
+ conn.execute('INSERT OR IGNORE INTO users (user_id, username, joined_at) VALUES (?, ?, ?)',
100
+ (user_id, username, datetime.now()))
101
+ conn.commit()
102
+
103
+ def get_user(self, user_id):
104
+ with self.get_conn() as conn:
105
+ return conn.execute('SELECT * FROM users WHERE user_id = ?', (user_id,)).fetchone()
106
+
107
+ def add_points(self, user_id, amount):
108
+ with self.lock, self.get_conn() as conn:
109
+ conn.execute('UPDATE users SET points = points + ? WHERE user_id = ?', (amount, user_id))
110
+ conn.commit()
111
+
112
+ def deduct_points(self, user_id, amount):
113
+ with self.lock, self.get_conn() as conn:
114
+ conn.execute('UPDATE users SET points = points - ? WHERE user_id = ?', (amount, user_id))
115
+ conn.commit()
116
+
117
+ def set_plan(self, user_id, plan, days=30):
118
+ expires = datetime.now() + timedelta(days=days)
119
+ with self.lock, self.get_conn() as conn:
120
+ conn.execute('UPDATE users SET plan = ?, plan_expires = ? WHERE user_id = ?', (plan, expires, user_id))
121
+ conn.commit()
122
+
123
+ def get_projects(self, user_id=None):
124
+ with self.get_conn() as conn:
125
+ if user_id: return conn.execute('SELECT * FROM projects WHERE user_id = ?', (user_id,)).fetchall()
126
+ return conn.execute('SELECT * FROM projects').fetchall()
127
+
128
+ def update_project_status(self, project_id, container_id, status):
129
+ with self.lock, self.get_conn() as conn:
130
+ conn.execute('UPDATE projects SET container_id = ?, status = ? WHERE project_id = ?',
131
+ (container_id, status, project_id))
132
+ conn.commit()
133
+
134
+ def delete_project(self, project_id):
135
+ with self.lock, self.get_conn() as conn:
136
+ conn.execute('DELETE FROM projects WHERE project_id = ?', (project_id,))
137
+ conn.commit()
138
+
139
+ db = DatabaseEngine()
140
+
141
+ # ==========================================
142
+ # 🛡️ محرك الأمان (Security Scanner)
143
+ # ==========================================
144
  class SecurityScanner:
 
 
 
 
 
 
145
  @staticmethod
146
+ def is_safe_code(file_path, user_id):
147
+ if user_id == ADMIN_ID: return True, "Admin Bypass"
148
  try:
149
+ with open(file_path, 'r', encoding='utf-8') as f:
150
+ tree = ast.parse(f.read())
151
+ banned_imports =['os', 'subprocess', 'pty', 'shutil', 'socket', 'sys']
152
+ banned_funcs =['eval', 'exec', 'open', 'system', 'popen']
153
+ for node in ast.walk(tree):
154
+ if isinstance(node, ast.Import):
155
+ for alias in node.names:
156
+ if alias.name in banned_imports: return False, f"مكتبة ممنوعة أمنياً: {alias.name}"
157
+ elif isinstance(node, ast.Call) and getattr(node.func, 'id', '') in banned_funcs:
158
+ return False, f"دالة خطيرة ممنوعة: {node.func.id}"
159
+ return True, "Safe"
160
+ except Exception as e:
161
+ return False, f"خطأ في بناء الكود: {str(e)[:50]}"
162
+
163
+ # ==========================================
164
+ # 🐳 محرك الدوكر السحابي (Docker Engine)
165
+ # ==========================================
166
+ class DockerEngine:
167
  @staticmethod
168
+ def deploy(project_id, file_path, ram_limit, env_vars_str, auto_restart):
169
+ if not docker_client: return False, "نظام Docker معطل."
170
+ container_name = f"wolf_{project_id}"
171
+
172
+ # تنظيف الحاوية السابقة إن وجدت
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  try:
174
+ old = docker_client.containers.get(container_name)
175
+ old.remove(force=True)
176
+ except: pass
 
 
 
 
 
177
 
178
+ abs_path = os.path.abspath(file_path)
179
+ project_dir = os.path.dirname(abs_path)
180
+ file_name = os.path.basename(abs_path)
181
+ env_dict = json.loads(env_vars_str) if env_vars_str else {}
182
+ restart_policy = {"Name": "always"} if auto_restart else {"Name": "no"}
183
 
 
 
184
  try:
185
+ container = docker_client.containers.run(
186
+ "python:3.10-slim",
187
+ command=f"sh -c 'pip install -q pyTelegramBotAPI telebot requests bs4 numpy && python {file_name}'",
188
+ name=container_name,
189
+ volumes={project_dir: {'bind': '/app', 'mode': 'ro'}},
190
+ working_dir='/app',
191
+ environment=env_dict,
192
+ mem_limit=ram_limit,
193
+ restart_policy=restart_policy,
194
+ detach=True
195
+ )
196
+ return True, container.id
197
+ except Exception as e:
198
+ logger.error(f"Deploy Error: {e}")
199
+ return False, str(e)
200
 
201
  @staticmethod
202
+ def stop_and_remove(project_id):
203
+ if not docker_client: return
204
  try:
205
+ container = docker_client.containers.get(f"wolf_{project_id}")
206
+ container.stop(timeout=3)
207
+ container.remove(force=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  except: pass
209
 
210
  @staticmethod
211
+ def get_logs(project_id):
212
+ if not docker_client: return "بدون سجلات."
213
+ try:
214
+ container = docker_client.containers.get(f"wolf_{project_id}")
215
+ return container.logs(tail=25).decode('utf-8', errors='ignore')
216
+ except: return "الحاوية لا تعمل أو لا توجد سجلات."
217
 
218
  @staticmethod
219
+ def get_stats(project_id):
220
+ if not docker_client: return "N/A"
221
+ try:
222
+ container = docker_client.containers.get(f"wolf_{project_id}")
223
+ if container.status != 'running': return "متوقف 🔴"
224
+ stats = container.stats(stream=False)
225
+ ram_usage = stats['memory_stats'].get('usage', 0) / (1024 * 1024)
226
+ cpu_delta = stats['cpu_stats']['cpu_usage']['total_usage'] - stats['precpu_stats']['cpu_usage']['total_usage']
227
+ sys_delta = stats['cpu_stats']['system_cpu_usage'] - stats['precpu_stats']['system_cpu_usage']
228
+ cpu_percent = (cpu_delta / sys_delta) * stats['cpu_stats']['online_cpus'] * 100 if sys_delta > 0 else 0
229
+ return f"🟢 يعمل | RAM: {ram_usage:.1f}MB | CPU: {cpu_percent:.1f}%"
230
+ except: return "غير متاح"
231
+
232
+ # ==========================================
233
+ # 🎨 واجهة المستخدم (UI Engine)
234
+ # ==========================================
235
+ class UI:
 
236
  @staticmethod
237
+ def main_menu(user_id):
238
  markup = types.InlineKeyboardMarkup(row_width=2)
239
+ markup.add(
240
+ types.InlineKeyboardButton("📤 رفع مشروع (Deploy)", callback_data="ui_upload"),
241
+ types.InlineKeyboardButton("📋 إدارة مشاريعي", callback_data="ui_projects"),
242
+ types.InlineKeyboardButton("👤 حسابي", callback_data="ui_profile"),
243
+ types.InlineKeyboardButton("🛒 المتجر", callback_data="ui_store"),
244
+ types.InlineKeyboardButton("🔗 كسب نقاط", callback_data="ui_earn"),
245
+ types.InlineKeyboardButton("🎟️ استرداد كوبون", callback_data="ui_coupon"),
246
+ types.InlineKeyboardButton("📚 القوالب الجاهزة", callback_data="ui_templates"),
247
+ types.InlineKeyboardButton("👨‍💻 الدعم", url=f"https://t.me/{YOUR_USERNAME[1:]}")
248
+ )
249
+ if user_id == ADMIN_ID:
250
+ markup.add(types.InlineKeyboardButton("🛡️ لوحة المطور (Admin)", callback_data="admin_root"))
251
  return markup
252
 
253
  @staticmethod
254
+ def project_ctrl(project_id, status, auto_restart):
255
  markup = types.InlineKeyboardMarkup(row_width=2)
256
+ if status == 'running':
257
+ markup.add(types.InlineKeyboardButton("🛑 إيقاف الحاوية", callback_data=f"p_stop_{project_id}"))
258
+ else:
259
+ markup.add(types.InlineKeyboardButton("▶️ تشغيل الحاوية", callback_data=f"p_start_{project_id}"))
260
+
261
+ markup.add(
262
+ types.InlineKeyboardButton("📋 السجلات (Logs)", callback_data=f"p_logs_{project_id}"),
263
+ types.InlineKeyboardButton("🔄 ريستارت", callback_data=f"p_restart_{project_id}"),
264
+ types.InlineKeyboardButton("🌍 المتغيرات (ENV)", callback_data=f"p_env_{project_id}"),
265
+ types.InlineKeyboardButton("📊 الإحصائيات الحية", callback_data=f"p_stats_{project_id}")
266
+ )
267
+ ar_text = "🔁 إيقاف الريستارت التلقائي" if auto_restart else "🔁 تفعيل الريستارت التلقائي"
268
+ markup.add(
269
+ types.InlineKeyboardButton(ar_text, callback_data=f"p_ar_{project_id}"),
270
+ types.InlineKeyboardButton("🗑️ حذف المشروع", callback_data=f"p_del_{project_id}")
271
+ )
272
+ markup.add(types.InlineKeyboardButton("🔙 رجوع", callback_data="ui_projects"))
273
  return markup
274
 
275
+ @staticmethod
276
+ def back(callback_data="ui_main"):
277
+ return types.InlineKeyboardMarkup().add(types.InlineKeyboardButton("🔙 رجوع", callback_data=callback_data))
278
+
279
+ # ==========================================
280
+ # 🤖 دوال الاستقبال (Bot Handlers)
281
+ # ==========================================
282
  user_states = {}
283
 
284
+ def check_sub(user_id):
285
+ if user_id == ADMIN_ID: return True
286
+ user = db.get_user(user_id)
287
+ if user and user['is_vip']: return True
288
+ for ch in CHANNELS:
289
+ try:
290
+ status = bot.get_chat_member(ch, user_id).status
291
+ if status not in ['member', 'administrator', 'creator']: return False
292
+ except: return False
293
+ return True
294
 
295
  @bot.message_handler(commands=['start'])
296
+ def start_cmd(message):
297
+ user_id = message.from_user.id
298
+ username = message.from_user.username or f"User{user_id}"
299
+ db.add_user(user_id, username)
300
+ user = db.get_user(user_id)
301
+
302
+ if user['is_banned']:
303
+ return bot.reply_to(message, "🚫 حسابك محظور من استخدام النظام הסحابي.")
304
+
305
+ if not check_sub(user_id):
306
+ markup = types.InlineKeyboardMarkup()
307
+ for ch in CHANNELS: markup.add(types.InlineKeyboardButton("📡 اشترك هنا أولاً", url=f"https://t.me/{ch[1:]}"))
308
+ markup.add(types.InlineKeyboardButton("✅ تم الاشتراك", callback_data="ui_main"))
309
+ return bot.send_message(user_id, "⚠️ **يجب الاشتراك في القناة لاستخدام الاستضافة:**", reply_markup=markup)
310
+
311
+ # نظام الإحالة (Referral)
312
+ args = message.text.split()
313
+ if len(args) > 1 and args[1].isdigit():
314
+ inviter = int(args[1])
315
+ if inviter != user_id and not user['total_invites']: # استخدمناها كعلامة للـ rewarded
316
+ db.add_points(inviter, INVITE_REWARD)
317
+ with db.get_conn() as c:
318
+ c.execute('UPDATE users SET total_invites = total_invites + 1 WHERE user_id = ?', (inviter,))
319
+ c.execute('UPDATE users SET total_invites = -1 WHERE user_id = ?', (user_id,)) # علامة أنه دُعي
320
+ c.commit()
321
+ bot.send_message(inviter, f"🎉 لقد ربحت {INVITE_REWARD} نقطة لدعوتك مستخدم جديد!")
322
+
323
+ plan_name = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['label']
324
  text = (
325
+ f"🐺 **مرحباً بك في White Wolf Cloud**\n\n"
326
+ f"أقوى نظام استضافة سحابي مبني على معمارية **Docker Containers**.\n"
327
+ f"نوفر لك أقصى درجات الأمان، الاستقرار، والعمل 24/7.\n\n"
328
+ f"📦 خطتك: {plan_name}"
 
329
  )
330
+ bot.send_message(user_id, text, reply_markup=UI.main_menu(user_id))
331
 
332
+ @bot.callback_query_handler(func=lambda call: call.data.startswith("ui_"))
333
+ def ui_handler(call):
334
+ user_id = call.from_user.id
335
+ action = call.data[3:]
336
+ user = db.get_user(user_id)
337
 
338
+ if not check_sub(user_id):
339
+ return bot.answer_callback_query(call.id, "❌ يرجى الاشتراك بالقناة أولاً", show_alert=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
 
341
+ if action == "main":
342
+ plan_name = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['label']
343
+ safe_edit(call, f"🐺 **لوحة التحكم الرئيسية**\n📦 خطتك: {plan_name}", UI.main_menu(user_id))
 
 
344
 
345
+ elif action == "profile":
346
+ projs = db.get_projects(user_id)
347
+ plan_info = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])
348
+ text = (
349
+ f"👤 **الملف الشخصي** {'💎 VIP' if user['is_vip'] else ''}\n\n"
350
+ f"🆔 الايدي: `{user_id}`\n"
351
+ f"💰 النقاط: `{user['points']}`\n"
352
+ f"📦 الخطة: {plan_info['label']}\n"
353
+ f"📂 المشاريع: `{len(projs)}/{plan_info['projects']}`\n"
354
+ f"🚀 الرام المسموح لكل مشروع: `{plan_info['ram']}`"
355
+ )
356
+ safe_edit(call, text, UI.back())
357
 
358
+ elif action == "earn":
359
+ link = f"https://t.me/{bot.get_me().username}?start={user_id}"
360
+ text = f"🔗 **رابط الدعوة الخاص بك:**\n`{link}`\n\n🎁 احصل على {INVITE_REWARD} نقطة لكل شخص يدخل."
361
+ safe_edit(call, text, UI.back())
362
 
363
+ elif action == "store":
364
  markup = types.InlineKeyboardMarkup(row_width=1)
365
+ for k, v in PLAN_LIMITS.items():
366
+ if k == 'free': continue
367
+ markup.add(types.InlineKeyboardButton(f"{v['label']} | {v['projects']} مشاريع | {v['price']} نقطة", callback_data=f"buy_{k}"))
368
+ markup.add(types.InlineKeyboardButton("🔙 رجوع", callback_data="ui_main"))
369
+ safe_edit(call, f"🛒 **المتجر**\n💰 رصيدك: `{user['points']}` نقطة\nالمدة: 30 يوم.", markup)
370
+
371
+ elif action == "projects":
372
+ projs = db.get_projects(user_id)
373
+ if not projs: return bot.answer_callback_query(call.id, "📭 لا تمتلك أي مشاريع.", show_alert=True)
374
+ markup = types.InlineKeyboardMarkup()
375
  for p in projs:
376
+ icon = "🟢" if p['status'] == 'running' else "🔴"
377
+ markup.add(types.InlineKeyboardButton(f"{icon} {p['file_name']}", callback_data=f"p_view_{p['project_id']}"))
378
+ markup.add(types.InlineKeyboardButton("🔙 رجوع", callback_data="ui_main"))
379
+ safe_edit(call, "📋 **قائمة مشاريعك السحابية:**", markup)
380
+
381
+ elif action == "upload":
382
+ limit = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['projects']
383
+ if len(db.get_projects(user_id)) >= limit and not user['is_vip'] and user_id != ADMIN_ID:
384
+ return bot.answer_callback_query(call.id, f"⚠️ وصلت للحد الأقصى ({limit}). قم بالترقية!", show_alert=True)
385
+
386
+ user_states[user_id] = 'upload'
387
+ safe_edit(call, "📤 **أرسل ملف المشروع الآن**\n(مسموح `.py` مفرد أو `.zip` لمشروع كامل)\n⌨️ أرسل /cancel للإلغاء", UI.back())
388
+
389
+ @bot.callback_query_handler(func=lambda call: call.data.startswith("buy_"))
390
+ def buy_plan(call):
391
+ plan_key = call.data[4:]
392
+ user = db.get_user(call.from_user.id)
393
+ price = PLAN_LIMITS[plan_key]['price']
394
+
395
+ if user['points'] < price:
396
+ return bot.answer_callback_query(call.id, f"❌ رصيدك غير كافٍ. تحتاج {price} نقطة.", show_alert=True)
397
+
398
+ db.deduct_points(user['user_id'], price)
399
+ db.set_plan(user['user_id'], plan_key)
400
+ bot.answer_callback_query(call.id, "✅ تم تفعيل الخطة بنجاح!", show_alert=True)
401
+ ui_handler(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data="ui_profile"))
402
+
403
+ # ==========================================
404
+ # 🚀 إدارة المشاريع السحابية (Project Control)
405
+ # ==========================================
406
+ @bot.callback_query_handler(func=lambda call: call.data.startswith("p_"))
407
+ def project_control(call):
408
+ user_id = call.from_user.id
409
+ parts = call.data.split('_')
410
+ action = parts[1]
411
+ project_id = parts[2]
412
+
413
+ with db.get_conn() as conn:
414
+ p = conn.execute('SELECT * FROM projects WHERE project_id = ?', (project_id,)).fetchone()
415
+
416
+ if not p or (p['user_id'] != user_id and user_id != ADMIN_ID):
417
+ return bot.answer_callback_query(call.id, "❌ المشروع غير موجود أو لا تملك صلاحية.", show_alert=True)
418
+
419
+ if action == "view":
420
+ stats = DockerEngine.get_stats(project_id) if p['status'] == 'running' else "متوقف 🔴"
421
+ text = f"📄 **معلومات المشروع:**\n📁 `{p['file_name']}`\n🆔 `{project_id}`\n📊 الحالة: {stats}"
422
+ safe_edit(call, text, UI.project_ctrl(project_id, p['status'], p['auto_restart']))
423
+
424
+ elif action == "start":
425
+ user = db.get_user(user_id)
426
+ ram_limit = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['ram']
427
+ success, cid = DockerEngine.deploy(project_id, p['path'], ram_limit, p['env_vars'], p['auto_restart'])
428
+ if success:
429
+ db.update_project_status(project_id, cid, 'running')
430
+ bot.answer_callback_query(call.id, "▶️ تم التشغيل في حاوية معزولة!")
431
+ else:
432
+ bot.answer_callback_query(call.id, f"❌ فشل: {cid}", show_alert=True)
433
+ project_control(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data=f"p_view_{project_id}"))
434
+
435
+ elif action == "stop":
436
+ DockerEngine.stop_and_remove(project_id)
437
+ db.update_project_status(project_id, None, 'stopped')
438
+ bot.answer_callback_query(call.id, "🛑 تم إيقاف الحاوية.")
439
+ project_control(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data=f"p_view_{project_id}"))
440
+
441
+ elif action == "restart":
442
+ bot.answer_callback_query(call.id, "🔄 جاري إعادة التشغيل...")
443
+ DockerEngine.stop_and_remove(project_id)
444
+ user = db.get_user(user_id)
445
+ ram_limit = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['ram']
446
+ success, cid = DockerEngine.deploy(project_id, p['path'], ram_limit, p['env_vars'], p['auto_restart'])
447
+ if success: db.update_project_status(project_id, cid, 'running')
448
+ project_control(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data=f"p_view_{project_id}"))
449
+
450
+ elif action == "logs":
451
+ logs = DockerEngine.get_logs(project_id)
452
+ safe_edit(call, f"📋 **السجلات (Logs):**\n```\n{logs[-3500:]}\n```", UI.back(f"p_view_{project_id}"))
453
+
454
+ elif action == "stats":
455
+ stats = DockerEngine.get_stats(project_id)
456
+ safe_edit(call, f"📊 **الموارد المستهلكة الآن:**\n{stats}", UI.back(f"p_view_{project_id}"))
457
+
458
+ elif action == "ar":
459
+ new_val = 0 if p['auto_restart'] else 1
460
+ with db.lock, db.get_conn() as conn:
461
+ conn.execute('UPDATE projects SET auto_restart = ? WHERE project_id = ?', (new_val, project_id))
462
+ conn.commit()
463
+ bot.answer_callback_query(call.id, "✅ تم التعديل.")
464
+ project_control(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data=f"p_view_{project_id}"))
465
+
466
+ elif action == "del":
467
+ DockerEngine.stop_and_remove(project_id)
468
+ try: shutil.rmtree(os.path.dirname(p['path'])) if os.path.isdir(os.path.dirname(p['path'])) else os.remove(p['path'])
469
+ except: pass
470
+ db.delete_project(project_id)
471
+ bot.answer_callback_query(call.id, "🗑️ تم الحذف نهائياً.", show_alert=True)
472
+ ui_handler(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data="ui_projects"))
473
 
474
+ # ==========================================
475
+ # 📤 نظام الرفع الذكي والمحمي (Upload Engine)
476
+ # ==========================================
477
+ @bot.message_handler(content_types=['document'])
478
+ def handle_docs(message):
479
+ user_id = message.from_user.id
480
+ if user_states.get(user_id) != 'upload': return
481
+ user_states.pop(user_id, None)
482
+
483
+ file_name = message.document.file_name
484
+ if not (file_name.endswith('.py') or file_name.endswith('.zip')):
485
+ return bot.reply_to(message, "❌ مسموح فقط بملفات `.py` أو `.zip`")
486
+
487
+ if message.document.file_size > 5 * 1024 * 1024:
488
+ return bot.reply_to(message, "❌ الحد الأقصى 5MB.")
489
 
490
+ msg = bot.reply_to(message, "⏳ جاري الفحص الأمني...")
491
+ project_id = str(uuid.uuid4())[:8]
492
+ proj_dir = os.path.join(HOSTING_DIR, f"{user_id}_{project_id}")
493
+ os.makedirs(proj_dir, exist_ok=True)
494
+
495
+ save_path = os.path.join(proj_dir, file_name)
496
+ downloaded = bot.download_file(bot.get_file(message.document.file_id).file_path)
497
+
498
+ with open(save_path, 'wb') as f: f.write(downloaded)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
499
 
500
+ main_file = save_path
501
+ if file_name.endswith('.zip'):
502
+ try:
503
+ with zipfile.ZipFile(save_path, 'r') as zf:
504
+ for member in zf.namelist():
505
+ if not os.path.realpath(os.path.join(proj_dir, member)).startswith(os.path.realpath(proj_dir)):
506
+ raise Exception("محاولة اختراق Zip Slip")
507
+ zf.extractall(proj_dir)
508
+ os.remove(save_path)
509
+ py_files = [f for f in os.listdir(proj_dir) if f.endswith('.py')]
510
+ if not py_files: raise Exception("لا يوجد ملف بايثون في הـ ZIP")
511
+ main_file = os.path.join(proj_dir, 'main.py' if 'main.py' in py_files else py_files[0])
512
+ file_name = os.path.basename(main_file)
513
+ except Exception as e:
514
+ shutil.rmtree(proj_dir)
515
+ return bot.edit_message_text(f"❌ خطأ بالملف المضغوط: {e}", message.chat.id, msg.message_id)
516
+
517
+ is_safe, reason = SecurityScanner.is_safe_code(main_file, user_id)
518
+ if not is_safe:
519
+ shutil.rmtree(proj_dir)
520
+ return bot.edit_message_text(f"🚨 **مرفوض أمنياً:**\n`{reason}`", message.chat.id, msg.message_id)
521
+
522
+ with db.lock, db.get_conn() as conn:
523
+ conn.execute('INSERT INTO projects (project_id, user_id, file_name, path, created_at) VALUES (?, ?, ?, ?, ?)',
524
+ (project_id, user_id, file_name, main_file, datetime.now()))
525
+ conn.commit()
526
+
527
+ bot.edit_message_text("✅ **تم قبول الكود وحفظه بنجاح!**\nاذهب إلى `مشاريعي` لتشغيله.", message.chat.id, msg.message_id, reply_markup=UI.main_menu(user_id))
528
+
529
+ # ==========================================
530
+ # 🛡️ لوحة المطور الأسطورية (Admin Panel)
531
+ # ==========================================
532
+ @bot.callback_query_handler(func=lambda call: call.data.startswith("admin_"))
533
+ def admin_panel(call):
534
+ if call.from_user.id != ADMIN_ID: return
535
+ action = call.data[6:]
536
+
537
+ if action == "root":
538
+ markup = types.InlineKeyboardMarkup(row_width=2)
539
+ markup.add(
540
+ types.InlineKeyboardButton("📊 إحصائيات النظام", callback_data="admin_stats"),
541
+ types.InlineKeyboardButton("📢 إذاعة للمستخدمين", callback_data="admin_bc"),
542
+ types.InlineKeyboardButton("🎁 إضافة كوبون", callback_data="admin_add_coupon"),
543
+ types.InlineKeyboardButton("🛑 إيقاف كل الحاويات", callback_data="admin_killall")
544
  )
545
+ markup.add(types.InlineKeyboardButton("🔙 خروج من اللوحة", callback_data="ui_main"))
546
+ safe_edit(call, "🛡️ **لوحة التحكم المركزية السحابية**", markup)
547
 
548
+ elif action == "stats":
549
+ with db.get_conn() as conn:
550
+ users = conn.execute('SELECT COUNT(*) FROM users').fetchone()[0]
551
+ projs = conn.execute('SELECT COUNT(*) FROM projects').fetchone()[0]
552
 
553
+ cpu = psutil.cpu_percent()
554
+ ram = psutil.virtual_memory().percent
555
+ disk = psutil.disk_usage('/').percent
556
+ active_containers = len(docker_client.containers.list(filters={"name": "wolf_"})) if docker_client else 0
 
 
 
557
 
 
 
 
 
 
558
  text = (
559
+ f"📊 **إحصائيات السيرفر السحابي**\n\n"
560
+ f"👥 المستخدمين: `{users}`\n"
561
+ f"📂 إجمالي المشاريع: `{projs}`\n"
562
+ f"🐳 الحاويات النشطة: `{active_containers}`\n\n"
563
+ f"🖥️ حالة الـ Host:\n"
564
+ f"🧠 المعالج: `{cpu}%`\n"
565
+ f"💾 الرام: `{ram}%`\n"
566
+ f"💿 التخزين: `{disk}%`"
567
  )
568
+ safe_edit(call, text, UI.back("admin_root"))
569
+
570
+ elif action == "killall":
571
+ if docker_client:
572
+ for c in docker_client.containers.list(filters={"name": "wolf_"}): c.stop(timeout=1)
573
+ with db.lock, db.get_conn() as conn:
574
+ conn.execute('UPDATE projects SET status = "stopped", container_id = NULL')
575
+ conn.commit()
576
+ bot.answer_callback_query(call.id, "⚡ تم إعدام جميع الحاويات!", show_alert=True)
577
+ admin_panel(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data="admin_root"))
578
+
579
+ # ==========================================
580
+ # 🕒 المهام المجدولة (Cron & Background)
581
+ # ==========================================
582
+ def system_maintenance():
583
+ # 1. تحديث الخطط المنتهية
584
+ with db.lock, db.get_conn() as conn:
585
+ expired = conn.execute("SELECT user_id FROM users WHERE plan != 'free' AND plan_expires < ?", (datetime.now(),)).fetchall()
586
+ for u in expired:
587
+ conn.execute("UPDATE users SET plan = 'free' WHERE user_id = ?", (u[0],))
588
+ try: bot.send_message(u[0], "⚠️ انتهت صلاحية خطتك المدفوعة.")
589
+ except: pass
590
+ conn.commit()
591
 
592
+ # 2. أخذ نسخة احتياطية من الداتا بيز
593
+ backup_path = os.path.join(BACKUP_DIR, f"db_backup_{datetime.now().strftime('%A')}.db")
594
+ shutil.copy2(DB_NAME, backup_path)
595
+ logger.info("✅ تمت الصيانة الدورية وأخذ نسخة احتياطية بنجاح.")
596
+
597
+ scheduler = BackgroundScheduler()
598
+ scheduler.add_job(system_maintenance, 'interval', hours=12)
599
+ scheduler.start()
600
+
601
+ # دوال المساعدة
602
+ def safe_edit(call, text, markup=None):
603
+ try: bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup, parse_mode="Markdown")
604
+ except: pass
605
+
606
+ @bot.message_handler(commands=['cancel'])
607
+ def cancel_cmd(message):
608
+ user_states.pop(message.from_user.id, None)
609
+ bot.reply_to(message, "❌ تم الإلغاء.", reply_markup=UI.main_menu(message.from_user.id))
610
+
611
+ # ==========================================
612
+ # 🚀 تشغيل النظام (Ignition)
613
+ # ==========================================
614
  if __name__ == '__main__':
615
+ logger.info(f"🐺 إقلاع نظام White Wolf Cloud v{VERSION}...")
616
  try:
617
+ bot.infinity_polling(timeout=60, long_polling_timeout=30)
618
  except Exception as e:
619
+ logger.error(f"انقطاع عام: {e}")