Reooiq commited on
Commit
9619656
·
verified ·
1 Parent(s): 4f882cc

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +333 -285
bot.py CHANGED
@@ -3,18 +3,20 @@ import asyncio
3
  import logging
4
  import time
5
  import threading
 
 
6
  import aiosqlite
7
  import gradio as gr
8
  from hydrogram import Client, filters
9
  from hydrogram.errors import FloodWait, RPCError
10
  from hydrogram.types import (
11
  InputMediaPhoto, InputMediaVideo, InputMediaDocument,
12
- InputMediaAudio
13
  )
14
  from fastapi import FastAPI
15
  import uvicorn
16
 
17
- # ============ حل مشكلة استيراد الأخطاء بأمان ============
18
  try:
19
  from hydrogram.errors import FloodPremiumWait
20
  except ImportError:
@@ -31,12 +33,13 @@ try:
31
  except ImportError:
32
  MessageIdInvalid = RPCError
33
 
34
- # ============ إعداد السجلات ============
35
  logging.basicConfig(
36
  level=logging.INFO,
37
- format='%(asctime)s - %(levelname)s - %(message)s'
 
38
  )
39
- logger = logging.getLogger("ArchiverPro")
40
 
41
  # ============ الإعدادات والمتغيرات ============
42
  API_ID = int(os.environ.get("API_ID", 0))
@@ -45,139 +48,134 @@ SESSION_STRING = os.environ.get("SESSION_STRING", "")
45
  TARGET_CHAT_RAW = os.environ.get("TARGET_CHAT", "me")
46
  CHANNELS_TO_SCRAPE = os.environ.get("CHANNELS_TO_SCRAPE", "")
47
 
 
48
  DATA_DIR = "/data" if os.path.exists("/data") else "/tmp/data"
49
  DOWNLOAD_DIR = os.path.join(DATA_DIR, "downloads")
50
- DB_PATH = os.path.join(DATA_DIR, "archiver_queue.db")
51
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
52
 
53
  # ============ إنشاء العميل ============
54
  app = Client(
55
- "archiver_pro",
56
  api_id=API_ID,
57
  api_hash=API_HASH,
58
  session_string=SESSION_STRING,
59
  in_memory=True,
60
- workers=4,
61
- device_model="Desktop Archiver",
62
- system_version="Linux Archiver 64bit",
63
- app_version="2.0.0",
 
64
  lang_code="ar"
65
  )
66
 
67
  TARGET_CHAT = "me"
68
- MAIN_LOOP = None
69
 
 
70
  stats = {
71
  "total_queued": 0,
72
  "total_transferred": 0,
73
  "total_failed": 0,
 
74
  "status": "Starting..."
75
  }
76
 
77
- # ============ إدارة التحكم بالسرعة ============
78
- class RateLimiter:
79
- def __init__(self, delay=2.5):
80
- self.delay = delay
81
- self.last_call = 0
82
  self.lock = asyncio.Lock()
83
- self.flood_until = 0
84
 
85
  async def wait(self):
86
  async with self.lock:
87
  now = time.time()
88
  if self.flood_until > now:
89
- wait_sec = self.flood_until - now
90
- logger.warning(f"FloodWait active, waiting {wait_sec:.1f}s...")
91
- await asyncio.sleep(wait_sec)
92
 
93
  now = time.time()
94
  elapsed = now - self.last_call
95
- if elapsed < self.delay:
96
- await asyncio.sleep(self.delay - elapsed)
97
  self.last_call = time.time()
98
 
99
- def set_flood(self, seconds):
100
- self.flood_until = time.time() + seconds + 2
101
- logger.warning(f"FloodWait received: {seconds}s")
 
102
 
103
- rate_limiter = RateLimiter(delay=2.0)
104
 
105
- # ============ المعالجة التلقائية لقاعدة البيانات (Self-Healing DB) ============
106
- def cleanup_corrupt_db():
107
- logger.warning("Cleaning up corrupted database files...")
108
  for ext in ["", "-wal", "-shm", "-journal"]:
109
- file_to_del = f"{DB_PATH}{ext}"
110
- if os.path.exists(file_to_del):
111
  try:
112
- os.remove(file_to_del)
113
- logger.info(f"Deleted: {file_to_del}")
114
  except Exception as e:
115
- logger.error(f"Failed to delete {file_to_del}: {e}")
116
 
117
  async def init_db():
118
- try:
119
- # فحص سلامة الملف إذا كان موجوداً
120
- if os.path.exists(DB_PATH):
121
- try:
122
- async with aiosqlite.connect(DB_PATH) as db:
123
- cursor = await db.execute("PRAGMA integrity_check;")
124
- res = await cursor.fetchone()
125
- if not res or res[0] != "ok":
126
- raise Exception("Integrity check failed")
127
- except Exception as e:
128
- logger.error(f"Detected corrupt database ({e}), resetting...")
129
- cleanup_corrupt_db()
130
 
131
- async with aiosqlite.connect(DB_PATH) as db:
132
- await db.execute("PRAGMA journal_mode=WAL;")
133
- await db.execute("PRAGMA synchronous=NORMAL;")
134
- await db.execute("""
135
- CREATE TABLE IF NOT EXISTS jobs (
136
- id INTEGER PRIMARY KEY AUTOINCREMENT,
137
- chat_id INTEGER NOT NULL,
138
- message_id INTEGER NOT NULL,
139
- media_group_id TEXT,
140
- media_type TEXT,
141
- caption TEXT,
142
- source_name TEXT,
143
- album_total INTEGER DEFAULT 1,
144
- album_index INTEGER DEFAULT 1,
145
- status TEXT DEFAULT 'pending',
146
- attempts INTEGER DEFAULT 0,
147
- error TEXT,
148
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
149
- UNIQUE(chat_id, message_id)
150
- )
151
- """)
152
- await db.execute("CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status)")
153
- await db.execute("CREATE INDEX IF NOT EXISTS idx_jobs_media_group ON jobs(media_group_id)")
154
- await db.commit()
155
- logger.info("Database initialized successfully.")
156
- except Exception as e:
157
- logger.error(f"Critical error initializing DB: {e}, recreating fresh DB...")
158
- cleanup_corrupt_db()
159
- async with aiosqlite.connect(DB_PATH) as db:
160
- await db.execute("""
161
- CREATE TABLE IF NOT EXISTS jobs (
162
- id INTEGER PRIMARY KEY AUTOINCREMENT,
163
- chat_id INTEGER NOT NULL,
164
- message_id INTEGER NOT NULL,
165
- media_group_id TEXT,
166
- media_type TEXT,
167
- caption TEXT,
168
- source_name TEXT,
169
- album_total INTEGER DEFAULT 1,
170
- album_index INTEGER DEFAULT 1,
171
- status TEXT DEFAULT 'pending',
172
- attempts INTEGER DEFAULT 0,
173
- error TEXT,
174
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
175
- UNIQUE(chat_id, message_id)
176
- )
177
- """)
178
- await db.commit()
179
 
180
- async def add_message_to_queue(message, album_info=None):
 
181
  if not message.media:
182
  return False
183
 
@@ -186,25 +184,19 @@ async def add_message_to_queue(message, album_info=None):
186
  media_group_id = str(message.media_group_id) if message.media_group_id else None
187
 
188
  media_type = "unknown"
189
- if message.photo:
190
- media_type = "photo"
191
- elif message.video:
192
- media_type = "video"
193
- elif message.document:
194
- media_type = "document"
195
- elif message.audio:
196
- media_type = "audio"
197
- elif message.voice:
198
- media_type = "voice"
199
- elif message.video_note:
200
- media_type = "video_note"
201
- elif message.animation:
202
- media_type = "animation"
203
-
204
  chat = message.chat
205
  source_name = chat.title or chat.first_name or chat.username or f"Chat_{chat_id}"
 
206
  raw_caption = message.caption or ""
207
-
208
  album_total = 1
209
  album_index = 1
210
  if album_info:
@@ -213,47 +205,56 @@ async def add_message_to_queue(message, album_info=None):
213
 
214
  try:
215
  async with aiosqlite.connect(DB_PATH) as db:
216
- await db.execute("""
 
217
  INSERT OR IGNORE INTO jobs
218
- (chat_id, message_id, media_group_id, media_type, caption, source_name, album_total, album_index, status)
219
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
220
- """, (chat_id, message_id, media_group_id, media_type, raw_caption, source_name, album_total, album_index))
221
  await db.commit()
222
- stats["total_queued"] += 1
223
- return True
 
 
224
  except Exception as e:
225
- logger.error(f"Error adding message to DB queue: {e}")
226
- if "malformed" in str(e).lower():
227
- await init_db()
228
  return False
229
 
230
- # ============ إعداد الكابشن ============
231
- def format_caption(raw_cap, source_name, album_index, album_total):
232
  lines = []
233
  if raw_cap and raw_cap.strip():
234
  lines.append(raw_cap.strip())
235
  lines.append("")
236
 
237
- lines.append(f"📢 **المصدر:** {source_name}")
238
- if album_total > 1:
239
- lines.append(f"🔢 **الجزء:** {album_index} من {album_total}")
 
 
 
240
 
 
 
 
241
  return "\n".join(lines)
242
 
243
- # ============ معالجة ونقل الرسائل ============
244
- async def process_single_job(job):
245
  chat_id = job["chat_id"]
246
  msg_id = job["message_id"]
247
  raw_caption = job["caption"]
248
  source_name = job["source_name"]
 
249
  album_index = job["album_index"]
250
  album_total = job["album_total"]
 
251
 
252
- caption = format_caption(raw_caption, source_name, album_index, album_total)
253
 
254
- await rate_limiter.wait()
255
-
256
- # 1. محاولة النسخ المباشر من السيرفر
257
  try:
258
  await app.copy_message(
259
  chat_id=TARGET_CHAT,
@@ -261,33 +262,33 @@ async def process_single_job(job):
261
  message_id=msg_id,
262
  caption=caption
263
  )
264
- logger.info(f"Fast copied message {msg_id} from {source_name}")
265
- return True
266
  except (FloodWait, FloodPremiumWait) as e:
267
- wait_val = getattr(e, 'value', 30)
268
- rate_limiter.set_flood(wait_val)
269
  raise e
270
- except ChatForwardsRestricted:
271
- logger.warning(f"Protected content in {msg_id}, falling back to download & upload...")
272
  except MessageIdInvalid:
273
- logger.error(f"Message {msg_id} is invalid or deleted.")
274
  return "DELETED"
 
 
275
  except Exception as e:
276
- logger.warning(f"Direct copy failed for {msg_id} ({e}), falling back to download & upload...")
277
 
278
- # 2. التحميل والرفع في حال الحماية
 
279
  try:
280
  msg = await app.get_messages(chat_id, msg_id)
281
  if not msg or not msg.media:
282
  return "DELETED"
283
-
284
- file_path = os.path.join(DOWNLOAD_DIR, f"temp_{chat_id}_{msg_id}")
285
- downloaded = await app.download_media(msg, file_name=file_path)
286
 
 
287
  if not downloaded or not os.path.exists(downloaded):
288
- raise Exception("File download failed")
289
 
290
- mtype = job["media_type"]
291
  if mtype == "photo":
292
  await app.send_photo(TARGET_CHAT, photo=downloaded, caption=caption)
293
  elif mtype == "video":
@@ -305,22 +306,27 @@ async def process_single_job(job):
305
  else:
306
  await app.send_document(TARGET_CHAT, document=downloaded, caption=caption)
307
 
308
- if os.path.exists(downloaded):
309
- os.remove(downloaded)
310
-
311
- logger.info(f"Downloaded and uploaded message {msg_id}")
312
- return True
313
  except (FloodWait, FloodPremiumWait) as e:
314
- wait_val = getattr(e, 'value', 30)
315
- rate_limiter.set_flood(wait_val)
316
  raise e
317
  except Exception as e:
318
- logger.error(f"Total failure processing message {msg_id}: {e}")
319
- return False
 
 
 
 
 
 
 
 
 
320
 
321
- # ============ عامل الطابور ============
322
- async def queue_worker():
323
- logger.info("Queue Worker started")
324
  while True:
325
  try:
326
  if not app.is_connected:
@@ -328,220 +334,262 @@ async def queue_worker():
328
  continue
329
 
330
  job = None
331
- try:
332
- async with aiosqlite.connect(DB_PATH) as db:
333
- db.row_factory = aiosqlite.Row
334
- cursor = await db.execute("""
335
- SELECT * FROM jobs
336
- WHERE status = 'pending' AND attempts < 5
337
- ORDER BY id ASC LIMIT 1
338
- """)
339
- job_row = await cursor.fetchone()
340
-
341
- if not job_row:
342
- await asyncio.sleep(2)
343
- continue
344
-
345
- job = dict(job_row)
346
- job_id = job["id"]
347
-
348
- await db.execute("UPDATE jobs SET status='processing' WHERE id=?", (job_id,))
349
- await db.commit()
350
- except Exception as db_err:
351
- if "malformed" in str(db_err).lower():
352
- logger.error("Database malformed in worker, resetting database...")
353
- await init_db()
354
  await asyncio.sleep(2)
355
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  else:
357
- raise db_err
358
-
359
- result = await process_single_job(job)
360
-
361
- try:
362
- async with aiosqlite.connect(DB_PATH) as db:
363
- if result is True:
364
- await db.execute("UPDATE jobs SET status='completed' WHERE id=?", (job["id"],))
365
- stats["total_transferred"] += 1
366
- elif result == "DELETED":
367
- await db.execute("UPDATE jobs SET status='failed', error='Message Deleted/Invalid' WHERE id=?", (job["id"],))
368
- stats["total_failed"] += 1
369
- else:
370
- await db.execute("""
371
- UPDATE jobs SET status='pending', attempts=attempts+1, error='Retry later' WHERE id=?
372
- """, (job["id"],))
373
- await db.commit()
374
- except Exception as db_err:
375
- logger.error(f"Failed to update job status: {db_err}")
376
 
377
  except (FloodWait, FloodPremiumWait) as e:
378
- wait_val = getattr(e, 'value', 30)
379
- logger.warning(f"FloodWait sleeping: {wait_val}s")
380
- await asyncio.sleep(wait_val + 1)
381
  except Exception as e:
382
- logger.error(f"Unexpected error in worker: {e}")
383
- await asyncio.sleep(5)
384
 
385
- # ============ ماسح الرسائل القديمة ============
386
- async def scrape_channel_history(chat_identifier, limit=0):
 
387
  try:
388
  chat = await app.get_chat(chat_identifier)
389
  chat_id = chat.id
390
- chat_title = chat.title or chat.first_name or chat_identifier
391
- logger.info(f"Starting history scrape for: {chat_title} ({chat_id})")
392
-
 
 
 
 
 
 
 
 
 
393
  count = 0
394
- media_groups = {}
395
-
396
- async for message in app.get_chat_history(chat_id, limit=limit if limit > 0 else 0):
 
 
 
 
 
 
 
397
  if message.media:
398
  if message.media_group_id:
399
  mg_id = str(message.media_group_id)
400
  media_groups.setdefault(mg_id, []).append(message)
401
  else:
402
- await add_message_to_queue(message)
403
  count += 1
404
-
405
- if count % 50 == 0 and count > 0:
406
- logger.info(f"Queued {count} messages from {chat_title}...")
 
 
 
 
 
 
 
 
 
 
407
  await asyncio.sleep(0.1)
408
 
409
  for mg_id, msgs in media_groups.items():
410
  msgs.sort(key=lambda m: m.id)
411
  total = len(msgs)
412
  for idx, msg in enumerate(msgs, start=1):
413
- await add_message_to_queue(msg, album_info={"total": total, "index": idx})
414
  count += 1
415
 
416
- logger.info(f"Finished scrape for {chat_title}! Total items: {count}")
417
- return f"تم فحص {chat_title} بنجاح وجدولة {count} ملف."
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  except Exception as e:
419
- logger.error(f"Failed to scrape channel {chat_identifier}: {e}")
420
- return f"خطأ في فحص {chat_identifier}: {str(e)}"
 
 
 
421
 
422
- # ============ رصد الرسائل الجديدة ============
423
  @app.on_message(filters.incoming & ~filters.me & filters.media)
424
- async def realtime_media_handler(client, message):
425
  try:
426
  if str(message.chat.id) == str(TARGET_CHAT):
427
  return
428
 
429
  if message.media_group_id:
430
- await asyncio.sleep(1.5)
431
  try:
432
- group_messages = await client.get_media_group(message.chat.id, message.id)
433
- group_messages.sort(key=lambda m: m.id)
434
- total = len(group_messages)
435
- for idx, msg in enumerate(group_messages, start=1):
436
- await add_message_to_queue(msg, album_info={"total": total, "index": idx})
437
  except Exception:
438
- await add_message_to_queue(message)
439
  else:
440
- await add_message_to_queue(message)
441
 
442
- logger.info(f"New incoming media from {message.chat.title or message.chat.id}")
443
  except Exception as e:
444
- logger.error(f"Realtime handler error: {e}")
445
 
446
- # ============ تحديد الوجهة ============
447
- async def resolve_target():
448
  global TARGET_CHAT
449
  raw = TARGET_CHAT_RAW.strip()
450
  if raw.lower() in ["me", "saved", ""]:
451
  TARGET_CHAT = "me"
452
- logger.info("Target chat: Saved Messages (me)")
453
  return
454
  try:
455
  chat_id_int = int(raw)
456
  chat = await app.get_chat(chat_id_int)
457
  TARGET_CHAT = chat_id_int
458
- logger.info(f"Target chat: {chat.title} ({TARGET_CHAT})")
459
  except ValueError:
460
  try:
461
  chat = await app.get_chat(raw)
462
  TARGET_CHAT = chat.id
463
- logger.info(f"Target chat: {chat.title} ({TARGET_CHAT})")
464
  except Exception as e:
465
- logger.error(f"Target verification failed for ({raw}): {e}. Defaulting to 'me'.")
466
  TARGET_CHAT = "me"
467
 
468
- # ============ واجهة Gradio ============
469
- def create_ui():
470
- with gr.Blocks(title="Telegram Archiver Pro") as demo:
471
- gr.Markdown("## 🚀 محول وأرشيف تيليجرام الاحترافي (بدون ضياع ملفات)")
472
-
 
 
 
 
 
 
 
473
  with gr.Row():
474
- gr.Textbox(label="حالة النظام", value="يعمل بنجاح ✅", interactive=False)
475
-
 
 
 
476
  gr.Markdown("---")
477
- gr.Markdown("### 📥 سحب الأرشيف القديم من قناة أو كروب:")
478
  with gr.Row():
479
- channel_input = gr.Textbox(
480
- label="معرف أو رابط القناة / الكروب",
481
- placeholder="@my_channel أو -100123456789"
482
  )
483
- limit_input = gr.Number(label="أقصى عدد رسائل (0 = الكل)", value=0)
484
- scrape_btn = gr.Button("بدء السحب الآن 📥", variant="primary")
485
-
486
- scrape_output = gr.Textbox(label="حالة الطلب", interactive=False)
487
-
488
- def do_scrape(ch, lim):
489
- if not ch:
490
- return "يرجى كتابة معرف القناة أولاً"
491
  if MAIN_LOOP and MAIN_LOOP.is_running():
492
  asyncio.run_coroutine_threadsafe(
493
- scrape_channel_history(ch.strip(), int(lim)),
494
  MAIN_LOOP
495
  )
496
- return f"تم بدء جلب الأرشيف من {ch} في الخلفية بنجاح! راقب السجلات."
497
- return "حدث خطأ في تشغيل المهمة، تأكد من اتصال البوت."
 
 
498
 
499
- scrape_btn.click(fn=do_scrape, inputs=[channel_input, limit_input], outputs=[scrape_output])
500
-
501
  return demo
502
 
503
- # ============ خادم الويب ============
504
- def run_web():
505
  fastapi_app = FastAPI()
506
- demo = create_ui()
507
  gr.mount_gradio_app(fastapi_app, demo, path="/")
508
 
509
- @fastapi_app.get("/ping")
510
- async def ping():
511
- return {"status": "alive", "stats": stats}
512
 
513
  uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)
514
 
515
- # ============ نقطة الدخول الرئيسية ============
516
  async def main():
517
  global MAIN_LOOP
518
  MAIN_LOOP = asyncio.get_running_loop()
519
-
520
- logger.info("Logging into Telegram...")
521
  await app.start()
522
 
523
  me = await app.get_me()
524
- logger.info(f"Logged in as: {me.first_name} (@{me.username or me.id})")
525
-
526
- await resolve_target()
527
  await init_db()
528
-
529
- asyncio.create_task(queue_worker())
530
-
 
 
531
  if CHANNELS_TO_SCRAPE:
532
- channels = [c.strip() for c in CHANNELS_TO_SCRAPE.split(",") if c.strip()]
533
- for ch in channels:
534
- asyncio.create_task(scrape_channel_history(ch))
535
 
536
- stats["status"] = "Running"
537
 
538
  stop_event = asyncio.Event()
539
  await stop_event.wait()
540
 
541
  if __name__ == "__main__":
542
- web_thread = threading.Thread(target=run_web, daemon=True)
543
  web_thread.start()
544
-
545
  loop = asyncio.get_event_loop()
546
  try:
547
  loop.run_until_complete(main())
 
3
  import logging
4
  import time
5
  import threading
6
+ import shutil
7
+ from typing import Optional, List, Dict, Any
8
  import aiosqlite
9
  import gradio as gr
10
  from hydrogram import Client, filters
11
  from hydrogram.errors import FloodWait, RPCError
12
  from hydrogram.types import (
13
  InputMediaPhoto, InputMediaVideo, InputMediaDocument,
14
+ InputMediaAudio, Message
15
  )
16
  from fastapi import FastAPI
17
  import uvicorn
18
 
19
+ # ============ معالجة استيراد الاستثناءات بأمان ============
20
  try:
21
  from hydrogram.errors import FloodPremiumWait
22
  except ImportError:
 
33
  except ImportError:
34
  MessageIdInvalid = RPCError
35
 
36
+ # ============ إعداد نظام السجلات الاحترافي ============
37
  logging.basicConfig(
38
  level=logging.INFO,
39
+ format='%(asctime)s | %(levelname)-7s | %(message)s',
40
+ datefmt='%Y-%m-%d %H:%M:%S'
41
  )
42
+ logger = logging.getLogger("UltraArchiver")
43
 
44
  # ============ الإعدادات والمتغيرات ============
45
  API_ID = int(os.environ.get("API_ID", 0))
 
48
  TARGET_CHAT_RAW = os.environ.get("TARGET_CHAT", "me")
49
  CHANNELS_TO_SCRAPE = os.environ.get("CHANNELS_TO_SCRAPE", "")
50
 
51
+ # إعداد مسارات التخزين
52
  DATA_DIR = "/data" if os.path.exists("/data") else "/tmp/data"
53
  DOWNLOAD_DIR = os.path.join(DATA_DIR, "downloads")
54
+ DB_PATH = os.path.join(DATA_DIR, "ultra_archiver.db")
55
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
56
 
57
  # ============ إنشاء العميل ============
58
  app = Client(
59
+ "ultra_archiver",
60
  api_id=API_ID,
61
  api_hash=API_HASH,
62
  session_string=SESSION_STRING,
63
  in_memory=True,
64
+ workers=8,
65
+ max_concurrent_transmissions=4,
66
+ device_model="UltraArchiver Server",
67
+ system_version="Linux 64bit",
68
+ app_version="3.0.0",
69
  lang_code="ar"
70
  )
71
 
72
  TARGET_CHAT = "me"
73
+ MAIN_LOOP: Optional[asyncio.AbstractEventLoop] = None
74
 
75
+ # إحصائيات حية
76
  stats = {
77
  "total_queued": 0,
78
  "total_transferred": 0,
79
  "total_failed": 0,
80
+ "active_scrapes": 0,
81
  "status": "Starting..."
82
  }
83
 
84
+ # ============ إدارة التحكم بالسرعة ومكافحة الحظر ============
85
+ class SmartFloodManager:
86
+ def __init__(self, normal_delay: float = 1.5):
87
+ self.normal_delay = normal_delay
88
+ self.last_call = 0.0
89
  self.lock = asyncio.Lock()
90
+ self.flood_until = 0.0
91
 
92
  async def wait(self):
93
  async with self.lock:
94
  now = time.time()
95
  if self.flood_until > now:
96
+ sleep_time = self.flood_until - now
97
+ logger.warning(f"⏳ FloodWait فعال - إيقاف مؤقت لمدة {sleep_time:.1f} ثانية...")
98
+ await asyncio.sleep(sleep_time)
99
 
100
  now = time.time()
101
  elapsed = now - self.last_call
102
+ if elapsed < self.normal_delay:
103
+ await asyncio.sleep(self.normal_delay - elapsed)
104
  self.last_call = time.time()
105
 
106
+ def handle_flood(self, seconds: int):
107
+ wait_seconds = max(seconds, 5) + 2
108
+ self.flood_until = time.time() + wait_seconds
109
+ logger.warning(f"🚨 تم استلام FloodWait من تيليجرام: {seconds} ثانية. تهدئة العمليات حتى {wait_seconds} ثانية.")
110
 
111
+ flood_manager = SmartFloodManager(normal_delay=1.8)
112
 
113
+ # ============ قاعدة البيانات ذاتية المعالجة مع الحفظ الدائم ============
114
+ def cleanup_corrupted_files():
 
115
  for ext in ["", "-wal", "-shm", "-journal"]:
116
+ p = f"{DB_PATH}{ext}"
117
+ if os.path.exists(p):
118
  try:
119
+ os.remove(p)
 
120
  except Exception as e:
121
+ logger.error(f"Failed removing {p}: {e}")
122
 
123
  async def init_db():
124
+ if os.path.exists(DB_PATH):
125
+ try:
126
+ async with aiosqlite.connect(DB_PATH) as db:
127
+ cur = await db.execute("PRAGMA integrity_check;")
128
+ res = await cur.fetchone()
129
+ if not res or res[0] != "ok":
130
+ raise Exception("Corrupt DB check failed")
131
+ except Exception as e:
132
+ logger.error(f"Database corruption detected ({e}), performing reset...")
133
+ cleanup_corrupted_files()
 
 
134
 
135
+ async with aiosqlite.connect(DB_PATH) as db:
136
+ await db.execute("PRAGMA journal_mode=WAL;")
137
+ await db.execute("PRAGMA synchronous=NORMAL;")
138
+ await db.execute("PRAGMA busy_timeout=30000;")
139
+
140
+ # جدول الوظائف (الطابور)
141
+ await db.execute("""
142
+ CREATE TABLE IF NOT EXISTS jobs (
143
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
144
+ chat_id INTEGER NOT NULL,
145
+ message_id INTEGER NOT NULL,
146
+ media_group_id TEXT,
147
+ media_type TEXT,
148
+ caption TEXT,
149
+ source_name TEXT,
150
+ source_username TEXT,
151
+ album_total INTEGER DEFAULT 1,
152
+ album_index INTEGER DEFAULT 1,
153
+ status TEXT DEFAULT 'pending', -- pending, processing, completed, failed
154
+ attempts INTEGER DEFAULT 0,
155
+ error TEXT,
156
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
157
+ UNIQUE(chat_id, message_id)
158
+ )
159
+ """)
160
+ await db.execute("CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status)")
161
+ await db.execute("CREATE INDEX IF NOT EXISTS idx_jobs_media_group ON jobs(media_group_id)")
162
+
163
+ # جدول نقاط الحفظ للاستئناف (Checkpoints)
164
+ await db.execute("""
165
+ CREATE TABLE IF NOT EXISTS scrape_checkpoints (
166
+ chat_id INTEGER PRIMARY KEY,
167
+ channel_name TEXT,
168
+ last_scraped_id INTEGER DEFAULT 0,
169
+ total_queued INTEGER DEFAULT 0,
170
+ status TEXT DEFAULT 'in_progress', -- in_progress, completed
171
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
172
+ )
173
+ """)
174
+ await db.commit()
175
+ logger.info("✅ قاعدة البيانات جاهزة ومؤمنة بنظام WAL Mode.")
 
 
 
 
 
 
 
176
 
177
+ # ============ إضافة رسالة إلى الطابور ============
178
+ async def add_job_to_queue(message: Message, album_info: Optional[Dict[str, int]] = None) -> bool:
179
  if not message.media:
180
  return False
181
 
 
184
  media_group_id = str(message.media_group_id) if message.media_group_id else None
185
 
186
  media_type = "unknown"
187
+ if message.photo: media_type = "photo"
188
+ elif message.video: media_type = "video"
189
+ elif message.document: media_type = "document"
190
+ elif message.audio: media_type = "audio"
191
+ elif message.voice: media_type = "voice"
192
+ elif message.video_note: media_type = "video_note"
193
+ elif message.animation: media_type = "animation"
194
+
 
 
 
 
 
 
 
195
  chat = message.chat
196
  source_name = chat.title or chat.first_name or chat.username or f"Chat_{chat_id}"
197
+ source_username = chat.username or ""
198
  raw_caption = message.caption or ""
199
+
200
  album_total = 1
201
  album_index = 1
202
  if album_info:
 
205
 
206
  try:
207
  async with aiosqlite.connect(DB_PATH) as db:
208
+ await db.execute("PRAGMA busy_timeout=30000;")
209
+ cursor = await db.execute("""
210
  INSERT OR IGNORE INTO jobs
211
+ (chat_id, message_id, media_group_id, media_type, caption, source_name, source_username, album_total, album_index, status)
212
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
213
+ """, (chat_id, message_id, media_group_id, media_type, raw_caption, source_name, source_username, album_total, album_index))
214
  await db.commit()
215
+ if cursor.rowcount > 0:
216
+ stats["total_queued"] += 1
217
+ return True
218
+ return False
219
  except Exception as e:
220
+ logger.error(f"خطأ في إضافة الرسالة {message_id}: {e}")
 
 
221
  return False
222
 
223
+ # ============ توليد الكابشن الذكي ============
224
+ def format_smart_caption(raw_cap: str, source_name: str, source_username: str, msg_id: int, album_index: int, album_total: int) -> str:
225
  lines = []
226
  if raw_cap and raw_cap.strip():
227
  lines.append(raw_cap.strip())
228
  lines.append("")
229
 
230
+ if source_username:
231
+ source_tag = f"[{source_name}](https://t.me/{source_username}/{msg_id})"
232
+ else:
233
+ source_tag = f"**{source_name}**"
234
+
235
+ lines.append(f"📢 المصدر: {source_tag}")
236
 
237
+ if album_total > 1:
238
+ lines.append(f"🔢 المقطع: {album_index} من إجمالي {album_total}")
239
+
240
  return "\n".join(lines)
241
 
242
+ # ============ معالجة وإرسال الوظيفة (محمي 100% ضد الضياع) ============
243
+ async def process_job(job: Dict[str, Any]) -> str:
244
  chat_id = job["chat_id"]
245
  msg_id = job["message_id"]
246
  raw_caption = job["caption"]
247
  source_name = job["source_name"]
248
+ source_username = job.get("source_username", "")
249
  album_index = job["album_index"]
250
  album_total = job["album_total"]
251
+ mtype = job["media_type"]
252
 
253
+ caption = format_smart_caption(raw_caption, source_name, source_username, msg_id, album_index, album_total)
254
 
255
+ await flood_manager.wait()
256
+
257
+ # 1. المحاولة السريعة: Copy Message مباشرة من سيرفرات تيليجرام
258
  try:
259
  await app.copy_message(
260
  chat_id=TARGET_CHAT,
 
262
  message_id=msg_id,
263
  caption=caption
264
  )
265
+ logger.info(f"⚡ تم النقل السريع بنجاح: رسالة {msg_id} من {source_name}")
266
+ return "SUCCESS"
267
  except (FloodWait, FloodPremiumWait) as e:
268
+ flood_manager.handle_flood(getattr(e, 'value', 30))
 
269
  raise e
 
 
270
  except MessageIdInvalid:
271
+ logger.warning(f"⚠️ الرسالة {msg_id} حُذفت من المصدر.")
272
  return "DELETED"
273
+ except ChatForwardsRestricted:
274
+ logger.info(f"🔒 محتوى محمي للرسالة {msg_id}، تحويل تلقائي لنظام التحميل والرفع المباشر...")
275
  except Exception as e:
276
+ logger.warning(f"تعذر النقل السريع ({e})، جاري استخدام محرك التنزيل والرفع الموثوق...")
277
 
278
+ # 2. المحاولة المضمونة: التنزيل المؤقت وإعادة الرفع التلقائي
279
+ temp_file = None
280
  try:
281
  msg = await app.get_messages(chat_id, msg_id)
282
  if not msg or not msg.media:
283
  return "DELETED"
284
+
285
+ file_prefix = f"temp_{chat_id}_{msg_id}"
286
+ temp_file = os.path.join(DOWNLOAD_DIR, file_prefix)
287
 
288
+ downloaded = await app.download_media(msg, file_name=temp_file)
289
  if not downloaded or not os.path.exists(downloaded):
290
+ raise Exception("فشل تنزيل الوسائط إلى السيرفر")
291
 
 
292
  if mtype == "photo":
293
  await app.send_photo(TARGET_CHAT, photo=downloaded, caption=caption)
294
  elif mtype == "video":
 
306
  else:
307
  await app.send_document(TARGET_CHAT, document=downloaded, caption=caption)
308
 
309
+ logger.info(f"📥 تم التحميل والرفع بنجاح للرسالة {msg_id}")
310
+ return "SUCCESS"
 
 
 
311
  except (FloodWait, FloodPremiumWait) as e:
312
+ flood_manager.handle_flood(getattr(e, 'value', 30))
 
313
  raise e
314
  except Exception as e:
315
+ logger.error(f"❌ فشل تام في معالجة الرسالة {msg_id}: {e}")
316
+ return "RETRY"
317
+ finally:
318
+ if temp_file and os.path.exists(temp_file):
319
+ try:
320
+ if os.path.isdir(temp_file):
321
+ shutil.rmtree(temp_file, ignore_errors=True)
322
+ else:
323
+ os.remove(temp_file)
324
+ except Exception:
325
+ pass
326
 
327
+ # ============ معالج طابور الإرسال (Queue Worker) ============
328
+ async def queue_worker_loop():
329
+ logger.info("⚙️ بدء تشغيل محرك معالجة الطابور التلقائي...")
330
  while True:
331
  try:
332
  if not app.is_connected:
 
334
  continue
335
 
336
  job = None
337
+ async with aiosqlite.connect(DB_PATH) as db:
338
+ db.row_factory = aiosqlite.Row
339
+ await db.execute("PRAGMA busy_timeout=30000;")
340
+ cursor = await db.execute("""
341
+ SELECT * FROM jobs
342
+ WHERE status = 'pending' AND attempts < 10
343
+ ORDER BY id ASC LIMIT 1
344
+ """)
345
+ row = await cursor.fetchone()
346
+ if not row:
 
 
 
 
 
 
 
 
 
 
 
 
 
347
  await asyncio.sleep(2)
348
  continue
349
+
350
+ job = dict(row)
351
+ await db.execute("UPDATE jobs SET status='processing' WHERE id=?", (job["id"],))
352
+ await db.commit()
353
+
354
+ result = await process_job(job)
355
+
356
+ async with aiosqlite.connect(DB_PATH) as db:
357
+ await db.execute("PRAGMA busy_timeout=30000;")
358
+ if result == "SUCCESS":
359
+ await db.execute("UPDATE jobs SET status='completed', error=NULL WHERE id=?", (job["id"],))
360
+ stats["total_transferred"] += 1
361
+ elif result == "DELETED":
362
+ await db.execute("UPDATE jobs SET status='failed', error='حذفت الرسالة من المصدر' WHERE id=?", (job["id"],))
363
+ stats["total_failed"] += 1
364
  else:
365
+ await db.execute("""
366
+ UPDATE jobs SET status='pending', attempts=attempts+1, error='فشل وسيعاد المحاولة' WHERE id=?
367
+ """, (job["id"],))
368
+ await db.commit()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369
 
370
  except (FloodWait, FloodPremiumWait) as e:
371
+ sec = getattr(e, 'value', 30)
372
+ logger.warning(f"توقف مؤقت بسبب قيود تيليجرام: {sec} ثانية")
373
+ await asyncio.sleep(sec + 1)
374
  except Exception as e:
375
+ logger.error(f"خطأ غير متوقع في محرك الإرسال: {e}")
376
+ await asyncio.sleep(4)
377
 
378
+ # ============ ماسح الأرشيف القديم مع الاستئناف الذكي (History Scraper) ============
379
+ async def scrape_channel_with_checkpoint(chat_identifier: str, limit: int = 0) -> str:
380
+ stats["active_scrapes"] += 1
381
  try:
382
  chat = await app.get_chat(chat_identifier)
383
  chat_id = chat.id
384
+ chat_title = chat.title or chat.first_name or str(chat_identifier)
385
+ logger.info(f"🔎 بدء فحص أرشيف: {chat_title} ({chat_id})")
386
+
387
+ last_id = 0
388
+ async with aiosqlite.connect(DB_PATH) as db:
389
+ await db.execute("PRAGMA busy_timeout=30000;")
390
+ cursor = await db.execute("SELECT last_scraped_id FROM scrape_checkpoints WHERE chat_id=?", (chat_id,))
391
+ row = await cursor.fetchone()
392
+ if row:
393
+ last_id = row[0]
394
+ logger.info(f"📌 استئناف الفحص للقناة {chat_title} من الرسالة رقم: {last_id}")
395
+
396
  count = 0
397
+ media_groups: Dict[str, List[Message]] = {}
398
+ highest_msg_id = last_id
399
+
400
+ async for message in app.get_chat_history(chat_id, limit=limit if limit > 0 else 0, offset_id=0):
401
+ if message.id <= last_id and last_id > 0:
402
+ break
403
+
404
+ if message.id > highest_msg_id:
405
+ highest_msg_id = message.id
406
+
407
  if message.media:
408
  if message.media_group_id:
409
  mg_id = str(message.media_group_id)
410
  media_groups.setdefault(mg_id, []).append(message)
411
  else:
412
+ await add_job_to_queue(message)
413
  count += 1
414
+
415
+ if count > 0 and count % 100 == 0:
416
+ logger.info(f"📦 تم جدولة {count} ملف من {chat_title} حتى الآن...")
417
+ async with aiosqlite.connect(DB_PATH) as db:
418
+ await db.execute("""
419
+ INSERT INTO scrape_checkpoints (chat_id, channel_name, last_scraped_id, total_queued, status)
420
+ VALUES (?, ?, ?, ?, 'in_progress')
421
+ ON CONFLICT(chat_id) DO UPDATE SET
422
+ last_scraped_id=excluded.last_scraped_id,
423
+ total_queued=total_queued+excluded.total_queued,
424
+ updated_at=CURRENT_TIMESTAMP
425
+ """, (chat_id, chat_title, highest_msg_id, 100))
426
+ await db.commit()
427
  await asyncio.sleep(0.1)
428
 
429
  for mg_id, msgs in media_groups.items():
430
  msgs.sort(key=lambda m: m.id)
431
  total = len(msgs)
432
  for idx, msg in enumerate(msgs, start=1):
433
+ await add_job_to_queue(msg, album_info={"total": total, "index": idx})
434
  count += 1
435
 
436
+ async with aiosqlite.connect(DB_PATH) as db:
437
+ await db.execute("""
438
+ INSERT INTO scrape_checkpoints (chat_id, channel_name, last_scraped_id, total_queued, status)
439
+ VALUES (?, ?, ?, ?, 'completed')
440
+ ON CONFLICT(chat_id) DO UPDATE SET
441
+ last_scraped_id=excluded.last_scraped_id,
442
+ total_queued=total_queued+excluded.total_queued,
443
+ status='completed',
444
+ updated_at=CURRENT_TIMESTAMP
445
+ """, (chat_id, chat_title, highest_msg_id, count))
446
+ await db.commit()
447
+
448
+ msg_result = f"✅ اكتمل فحص {chat_title}! تمت جدولة {count} ملف بنجاح."
449
+ logger.info(msg_result)
450
+ return msg_result
451
  except Exception as e:
452
+ err_msg = f"❌ خطأ أثناء فحص {chat_identifier}: {e}"
453
+ logger.error(err_msg)
454
+ return err_msg
455
+ finally:
456
+ stats["active_scrapes"] = max(0, stats["active_scrapes"] - 1)
457
 
458
+ # ============ رصد الرسائل الجديدة لحظياً (Real-Time Listener) ============
459
  @app.on_message(filters.incoming & ~filters.me & filters.media)
460
+ async def incoming_media_listener(client, message: Message):
461
  try:
462
  if str(message.chat.id) == str(TARGET_CHAT):
463
  return
464
 
465
  if message.media_group_id:
466
+ await asyncio.sleep(2.0)
467
  try:
468
+ album_msgs = await client.get_media_group(message.chat.id, message.id)
469
+ album_msgs.sort(key=lambda m: m.id)
470
+ total = len(album_msgs)
471
+ for idx, msg in enumerate(album_msgs, start=1):
472
+ await add_job_to_queue(msg, album_info={"total": total, "index": idx})
473
  except Exception:
474
+ await add_job_to_queue(message)
475
  else:
476
+ await add_job_to_queue(message)
477
 
478
+ logger.info(f"✨ رصد فوري لملف جديد من: {message.chat.title or message.chat.id}")
479
  except Exception as e:
480
+ logger.error(f"خطأ في الرصد الفوري: {e}")
481
 
482
+ # ============ تحديد وضبط الوجهة ============
483
+ async def resolve_target_chat():
484
  global TARGET_CHAT
485
  raw = TARGET_CHAT_RAW.strip()
486
  if raw.lower() in ["me", "saved", ""]:
487
  TARGET_CHAT = "me"
488
+ logger.info("🎯 الوجهة المحددة: الرسائل المحفوظة (Saved Messages)")
489
  return
490
  try:
491
  chat_id_int = int(raw)
492
  chat = await app.get_chat(chat_id_int)
493
  TARGET_CHAT = chat_id_int
494
+ logger.info(f"🎯 الوجهة المحددة: {chat.title} ({TARGET_CHAT})")
495
  except ValueError:
496
  try:
497
  chat = await app.get_chat(raw)
498
  TARGET_CHAT = chat.id
499
+ logger.info(f"🎯 الوجهة المحددة: {chat.title} ({TARGET_CHAT})")
500
  except Exception as e:
501
+ logger.error(f"تعذر العثور على الوجهة ({raw}): {e}. التحويل للرسائل المحفوظة.")
502
  TARGET_CHAT = "me"
503
 
504
+ # ============ واجهة التحكم (Gradio Dashboard) ============
505
+ def create_dashboard():
506
+ with gr.Blocks(title="Ultra Archiver Pro 2026") as demo:
507
+ gr.Markdown("""
508
+ # 🚀 Ultra Archiver Pro (النسخة النهائية المتكاملة)
509
+ **نظام أرشفة ونقل وسائط تيليجرام الشامل:**
510
+ * ✅ نقل فوري مباشر من السيرفر بدون استهلاك مساحة الـ Space.
511
+ * ✅ نظام حماية متقدم ضد الـ FloodWait وحظر التليجرام.
512
+ * ✅ دعم الألبومات، الفيديوهات، الصور، الملفات مع كتابة المصدر ورقم الجزء.
513
+ * ✅ استئناف ذكي للأرشيف القديم (Checkpoints) وحفظ دائم للطابور.
514
+ """)
515
+
516
  with gr.Row():
517
+ status_box = gr.Textbox(label="حالة النظام", value="يعمل بنشاط ✅", interactive=False)
518
+ queued_box = gr.Number(label="إجمالي الملفات في الطابور", value=0, interactive=False)
519
+ transferred_box = gr.Number(label="الملفات المنقولة بنجاح", value=0, interactive=False)
520
+ failed_box = gr.Number(label="الملفات الفاشلة / المحذوفة", value=0, interactive=False)
521
+
522
  gr.Markdown("---")
523
+ gr.Markdown("### 📥 سحب الأرشيف القديم من قناة أو مجموعة:")
524
  with gr.Row():
525
+ target_channel = gr.Textbox(
526
+ label="معرف القناة أو رابطها",
527
+ placeholder="@my_channel أو https://t.me/channel_name أو -100123456789"
528
  )
529
+ max_limit = gr.Number(label="الحد الأقصى للرسائل (0 = كامل الأرشيف بدون توقف)", value=0)
530
+ start_btn = gr.Button("بدء الفحص والسحب الآن 📥", variant="primary")
531
+
532
+ scrape_status = gr.Textbox(label="نتيجة الفحص والجدولة", interactive=False)
533
+
534
+ def trigger_scrape(ch, lim):
535
+ if not ch or not ch.strip():
536
+ return "⚠️ يرجى كتابة معرف أو رابط القناة أولاً."
537
  if MAIN_LOOP and MAIN_LOOP.is_running():
538
  asyncio.run_coroutine_threadsafe(
539
+ scrape_channel_with_checkpoint(ch.strip(), int(lim)),
540
  MAIN_LOOP
541
  )
542
+ return f"🚀 تم إطلاق مهمة الفحص لـ ({ch}) في الخلفية بنجاح! يتم الآن حفظ الملفات في الطابور."
543
+ return "❌ تعذر إطلاق المهمة، تأكد من اتصال البوت."
544
+
545
+ start_btn.click(fn=trigger_scrape, inputs=[target_channel, max_limit], outputs=[scrape_status])
546
 
 
 
547
  return demo
548
 
549
+ # ============ تشغيل الويب ============
550
+ def run_web_server():
551
  fastapi_app = FastAPI()
552
+ demo = create_dashboard()
553
  gr.mount_gradio_app(fastapi_app, demo, path="/")
554
 
555
+ @fastapi_app.get("/health")
556
+ async def health():
557
+ return {"status": "ok", "stats": stats}
558
 
559
  uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)
560
 
561
+ # ============ الدالة الرئيسية ============
562
  async def main():
563
  global MAIN_LOOP
564
  MAIN_LOOP = asyncio.get_running_loop()
565
+
566
+ logger.info("جاري الاتصال بحساب تيليجرام...")
567
  await app.start()
568
 
569
  me = await app.get_me()
570
+ logger.info(f"✨ تم تسجيل الدخول بنجاح بحساب: {me.first_name} (@{me.username or me.id})")
571
+
572
+ await resolve_target_chat()
573
  await init_db()
574
+
575
+ # تشغيل محرك معالجة الطابور
576
+ asyncio.create_task(queue_worker_loop())
577
+
578
+ # فحص القنوات المحددة في البيئة تلقائياً
579
  if CHANNELS_TO_SCRAPE:
580
+ ch_list = [c.strip() for c in CHANNELS_TO_SCRAPE.split(",") if c.strip()]
581
+ for c in ch_list:
582
+ asyncio.create_task(scrape_channel_with_checkpoint(c))
583
 
584
+ stats["status"] = "Active"
585
 
586
  stop_event = asyncio.Event()
587
  await stop_event.wait()
588
 
589
  if __name__ == "__main__":
590
+ web_thread = threading.Thread(target=run_web_server, daemon=True)
591
  web_thread.start()
592
+
593
  loop = asyncio.get_event_loop()
594
  try:
595
  loop.run_until_complete(main())