Update bot.py
Browse files
bot.py
CHANGED
|
@@ -32,7 +32,6 @@ API_HASH = os.environ.get("API_HASH", "")
|
|
| 32 |
SESSION_STRING = os.environ.get("SESSION_STRING", "")
|
| 33 |
TARGET_CHAT_RAW = os.environ.get("TARGET_CHAT", "me")
|
| 34 |
|
| 35 |
-
# 🔑 استخدام /data للـ persistent storage (1TB)
|
| 36 |
DATA_DIR = "/data"
|
| 37 |
DOWNLOAD_DIR = os.path.join(DATA_DIR, "downloads")
|
| 38 |
DB_PATH = os.path.join(DATA_DIR, "queue.db")
|
|
@@ -54,10 +53,9 @@ app = Client(
|
|
| 54 |
|
| 55 |
TARGET_CHAT = None
|
| 56 |
|
| 57 |
-
# ============ Throttle Controller
|
| 58 |
class ThrottleController:
|
| 59 |
-
|
| 60 |
-
def __init__(self, rate=1.0):
|
| 61 |
self.rate = rate
|
| 62 |
self.last_send = defaultdict(float)
|
| 63 |
self.lock = asyncio.Lock()
|
|
@@ -68,19 +66,17 @@ class ThrottleController:
|
|
| 68 |
elapsed = now - self.last_send[chat_id]
|
| 69 |
if elapsed < self.rate:
|
| 70 |
wait_time = self.rate - elapsed
|
| 71 |
-
logger.debug(f"⏳ Throttle: انتظار {wait_time:.2f}s للدردشة {chat_id}")
|
| 72 |
await asyncio.sleep(wait_time)
|
| 73 |
self.last_send[chat_id] = time.time()
|
| 74 |
|
| 75 |
-
throttle = ThrottleController(rate=1.2)
|
| 76 |
|
| 77 |
# ============ Semaphores ============
|
| 78 |
-
download_sem = asyncio.Semaphore(
|
| 79 |
-
send_sem = asyncio.Semaphore(2)
|
| 80 |
|
| 81 |
# ============ قاعدة البيانات ============
|
| 82 |
async def init_db():
|
| 83 |
-
"""إنشاء جداول SQLite في /data (persistent)"""
|
| 84 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 85 |
await db.execute("""
|
| 86 |
CREATE TABLE IF NOT EXISTS jobs (
|
|
@@ -103,16 +99,6 @@ async def init_db():
|
|
| 103 |
UNIQUE(chat_id, message_id)
|
| 104 |
)
|
| 105 |
""")
|
| 106 |
-
await db.execute("""
|
| 107 |
-
CREATE TABLE IF NOT EXISTS albums (
|
| 108 |
-
media_group_id TEXT PRIMARY KEY,
|
| 109 |
-
chat_id INTEGER,
|
| 110 |
-
total_expected INTEGER DEFAULT 0,
|
| 111 |
-
collected INTEGER DEFAULT 0,
|
| 112 |
-
status TEXT DEFAULT 'collecting',
|
| 113 |
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 114 |
-
)
|
| 115 |
-
""")
|
| 116 |
await db.execute("""
|
| 117 |
CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status)
|
| 118 |
""")
|
|
@@ -120,15 +106,13 @@ async def init_db():
|
|
| 120 |
CREATE INDEX IF NOT EXISTS idx_jobs_media_group ON jobs(media_group_id)
|
| 121 |
""")
|
| 122 |
await db.commit()
|
| 123 |
-
logger.info("
|
| 124 |
|
| 125 |
async def add_job(message):
|
| 126 |
-
"""إضافة مهمة جديدة للـ queue"""
|
| 127 |
m_type, ext = get_media_info(message)
|
| 128 |
if not m_type:
|
| 129 |
return
|
| 130 |
|
| 131 |
-
# الحصول على file_id و file_size
|
| 132 |
file_id = None
|
| 133 |
file_size = 0
|
| 134 |
file_name = None
|
|
@@ -160,7 +144,7 @@ async def add_job(message):
|
|
| 160 |
|
| 161 |
src_name = get_source_name(message)
|
| 162 |
raw_cap = message.caption or ""
|
| 163 |
-
final_cap = f"{raw_cap}\n\
|
| 164 |
|
| 165 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 166 |
try:
|
|
@@ -174,10 +158,9 @@ async def add_job(message):
|
|
| 174 |
))
|
| 175 |
await db.commit()
|
| 176 |
except Exception as e:
|
| 177 |
-
logger.error(f"
|
| 178 |
|
| 179 |
async def update_job_status(chat_id, message_id, status, file_path=None, error=None):
|
| 180 |
-
"""تحديث حالة المهمة"""
|
| 181 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 182 |
if file_path:
|
| 183 |
await db.execute("""
|
|
@@ -196,8 +179,7 @@ async def update_job_status(chat_id, message_id, status, file_path=None, error=N
|
|
| 196 |
""", (status, chat_id, message_id))
|
| 197 |
await db.commit()
|
| 198 |
|
| 199 |
-
async def get_pending_jobs(limit=
|
| 200 |
-
"""جلب المهام المعلقة"""
|
| 201 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 202 |
db.row_factory = aiosqlite.Row
|
| 203 |
cursor = await db.execute("""
|
|
@@ -210,7 +192,6 @@ async def get_pending_jobs(limit=5):
|
|
| 210 |
return [dict(row) for row in rows]
|
| 211 |
|
| 212 |
async def get_downloaded_album_jobs(media_group_id):
|
| 213 |
-
"""جلب كل ملفات ألبوم محملة وجاهزة للإرسال"""
|
| 214 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 215 |
db.row_factory = aiosqlite.Row
|
| 216 |
cursor = await db.execute("""
|
|
@@ -222,7 +203,6 @@ async def get_downloaded_album_jobs(media_group_id):
|
|
| 222 |
return [dict(row) for row in rows]
|
| 223 |
|
| 224 |
async def get_album_pending_count(media_group_id):
|
| 225 |
-
"""عدد الملفات المتبقية في الألبوم"""
|
| 226 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 227 |
cursor = await db.execute("""
|
| 228 |
SELECT COUNT(*) FROM jobs
|
|
@@ -232,7 +212,6 @@ async def get_album_pending_count(media_group_id):
|
|
| 232 |
return row[0]
|
| 233 |
|
| 234 |
async def delete_job(chat_id, message_id):
|
| 235 |
-
"""حذف مهمة ناجحة + تنظيف الملف"""
|
| 236 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 237 |
cursor = await db.execute("""
|
| 238 |
SELECT file_path FROM jobs WHERE chat_id=? AND message_id=?
|
|
@@ -241,7 +220,6 @@ async def delete_job(chat_id, message_id):
|
|
| 241 |
if row and row[0] and os.path.exists(row[0]):
|
| 242 |
try:
|
| 243 |
os.remove(row[0])
|
| 244 |
-
logger.info(f"🗑️ ملف محذوف: {row[0]}")
|
| 245 |
except:
|
| 246 |
pass
|
| 247 |
await db.execute("DELETE FROM jobs WHERE chat_id=? AND message_id=?", (chat_id, message_id))
|
|
@@ -270,32 +248,25 @@ def get_media_info(message):
|
|
| 270 |
def get_source_name(message):
|
| 271 |
chat = message.chat
|
| 272 |
if chat.type in ["channel", "supergroup", "group"]:
|
| 273 |
-
return chat.title or "
|
| 274 |
elif chat.type == "private":
|
| 275 |
-
return chat.first_name or chat.username or "
|
| 276 |
-
return "
|
| 277 |
-
|
| 278 |
-
def get_file_id_from_job(job):
|
| 279 |
-
"""استخراج file_id من الرسالة الأصلية"""
|
| 280 |
-
# نستخدم app.download_media مباشرة بالـ message_id
|
| 281 |
-
return job['file_id']
|
| 282 |
|
| 283 |
# ============ التحميل مع التحقق ============
|
| 284 |
async def verify_download(file_path, expected_size):
|
| 285 |
-
"""التحقق من اكتمال التحميل"""
|
| 286 |
if not file_path or not os.path.exists(file_path):
|
| 287 |
return False
|
| 288 |
actual_size = os.path.getsize(file_path)
|
| 289 |
if expected_size > 0 and actual_size < expected_size:
|
| 290 |
-
logger.warning(f"
|
| 291 |
return False
|
| 292 |
if actual_size == 0:
|
| 293 |
-
logger.warning(f"
|
| 294 |
return False
|
| 295 |
return True
|
| 296 |
|
| 297 |
async def download_job(job):
|
| 298 |
-
"""تحميل ملف مهمة مع التحقق من الاكتمال"""
|
| 299 |
chat_id = job['chat_id']
|
| 300 |
message_id = job['message_id']
|
| 301 |
expected_size = job['file_size'] or 0
|
|
@@ -309,10 +280,8 @@ async def download_job(job):
|
|
| 309 |
file_path = os.path.join(DOWNLOAD_DIR, f"{chat_id}_{message_id}{ext}")
|
| 310 |
|
| 311 |
try:
|
| 312 |
-
# تحديث الحالة إلى downloading
|
| 313 |
await update_job_status(chat_id, message_id, 'downloading')
|
| 314 |
|
| 315 |
-
# 🔑 التحميل باستخدام file_id
|
| 316 |
downloaded = await app.download_media(
|
| 317 |
job['file_id'],
|
| 318 |
file_name=file_path
|
|
@@ -321,10 +290,8 @@ async def download_job(job):
|
|
| 321 |
if not downloaded:
|
| 322 |
raise Exception("download_media returned None")
|
| 323 |
|
| 324 |
-
# 🔑 التحقق من اكتمال الملف
|
| 325 |
if not await verify_download(downloaded, expected_size):
|
| 326 |
-
|
| 327 |
-
logger.info(f"🔄 إعادة تحميل {message_id}")
|
| 328 |
if os.path.exists(downloaded):
|
| 329 |
os.remove(downloaded)
|
| 330 |
downloaded = await app.download_media(
|
|
@@ -332,18 +299,18 @@ async def download_job(job):
|
|
| 332 |
file_name=file_path
|
| 333 |
)
|
| 334 |
if not await verify_download(downloaded, expected_size):
|
| 335 |
-
raise Exception(f"
|
| 336 |
|
| 337 |
await update_job_status(chat_id, message_id, 'downloaded', file_path=downloaded)
|
| 338 |
-
logger.info(f"
|
| 339 |
return True
|
| 340 |
|
| 341 |
except Exception as e:
|
| 342 |
await update_job_status(chat_id, message_id, 'pending', error=str(e))
|
| 343 |
-
logger.error(f"
|
| 344 |
return False
|
| 345 |
|
| 346 |
-
# ============ الإرسال
|
| 347 |
@retry(
|
| 348 |
stop=stop_after_attempt(5),
|
| 349 |
wait=wait_exponential_jitter(initial=1, max=60),
|
|
@@ -354,13 +321,12 @@ async def safe_send(send_func):
|
|
| 354 |
return await send_func()
|
| 355 |
|
| 356 |
async def send_job(job):
|
| 357 |
-
"""إرسال مهمة محملة"""
|
| 358 |
chat_id = job['chat_id']
|
| 359 |
message_id = job['message_id']
|
| 360 |
file_path = job['file_path']
|
| 361 |
|
| 362 |
if not file_path or not os.path.exists(file_path):
|
| 363 |
-
logger.error(f"
|
| 364 |
await update_job_status(chat_id, message_id, 'pending', error="File not found")
|
| 365 |
return False
|
| 366 |
|
|
@@ -385,42 +351,33 @@ async def send_job(job):
|
|
| 385 |
elif m_type == 'animation':
|
| 386 |
await safe_send(lambda: app.send_animation(TARGET_CHAT, animation=file_path, caption=caption))
|
| 387 |
|
| 388 |
-
logger.info(f"
|
| 389 |
await delete_job(chat_id, message_id)
|
| 390 |
return True
|
| 391 |
|
| 392 |
except Exception as e:
|
| 393 |
-
logger.error(f"
|
| 394 |
await update_job_status(chat_id, message_id, 'downloaded', error=str(e))
|
| 395 |
return False
|
| 396 |
|
| 397 |
-
# ============ إرسال الألبوم ============
|
| 398 |
async def send_album_group(media_group_id):
|
| 399 |
-
"""إرسال ألبوم كامل بعد تحميل كل ملفاته"""
|
| 400 |
jobs = await get_downloaded_album_jobs(media_group_id)
|
| 401 |
if not jobs:
|
| 402 |
return
|
| 403 |
|
| 404 |
-
# التحقق من عدم وجود ملفات معلقة
|
| 405 |
pending = await get_album_pending_count(media_group_id)
|
| 406 |
if pending > 0:
|
| 407 |
-
logger.info(f"
|
| 408 |
return
|
| 409 |
|
| 410 |
-
# ترتيب الملفات
|
| 411 |
jobs.sort(key=lambda j: j['message_id'])
|
| 412 |
|
| 413 |
-
# فصل المدعوم في الألبوم عن المنفرد
|
| 414 |
album_inputs = []
|
| 415 |
album_jobs = []
|
| 416 |
standalone_jobs = []
|
| 417 |
|
| 418 |
for i, job in enumerate(jobs):
|
| 419 |
-
if i == 0
|
| 420 |
-
cap = job['caption']
|
| 421 |
-
else:
|
| 422 |
-
cap = None
|
| 423 |
-
|
| 424 |
m_type = job['media_type']
|
| 425 |
file_path = job['file_path']
|
| 426 |
|
|
@@ -440,7 +397,6 @@ async def send_album_group(media_group_id):
|
|
| 440 |
standalone_jobs.append(job)
|
| 441 |
|
| 442 |
async with send_sem:
|
| 443 |
-
# إرسال الألبوم المدعوم (تقسيم إلى 10)
|
| 444 |
chunk_size = 10
|
| 445 |
for idx in range(0, len(album_inputs), chunk_size):
|
| 446 |
chunk = album_inputs[idx:idx+chunk_size]
|
|
@@ -458,28 +414,33 @@ async def send_album_group(media_group_id):
|
|
| 458 |
|
| 459 |
for j in chunk_jobs:
|
| 460 |
await delete_job(j['chat_id'], j['message_id'])
|
| 461 |
-
logger.info(f"
|
| 462 |
except Exception as e:
|
| 463 |
-
logger.error(f"
|
| 464 |
|
| 465 |
-
# إرسال المنفردات
|
| 466 |
for job in standalone_jobs:
|
| 467 |
await send_job(job)
|
| 468 |
|
| 469 |
# ============ Workers ============
|
| 470 |
async def download_worker():
|
| 471 |
-
"
|
| 472 |
-
|
|
|
|
| 473 |
while True:
|
| 474 |
try:
|
| 475 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
if not jobs:
|
| 477 |
await asyncio.sleep(2)
|
| 478 |
continue
|
| 479 |
|
| 480 |
tasks = []
|
| 481 |
for job in jobs:
|
| 482 |
-
if len(tasks) >=
|
| 483 |
break
|
| 484 |
tasks.append(download_job(job))
|
| 485 |
|
|
@@ -487,62 +448,68 @@ async def download_worker():
|
|
| 487 |
await asyncio.gather(*tasks, return_exceptions=True)
|
| 488 |
|
| 489 |
except Exception as e:
|
| 490 |
-
logger.error(f"
|
| 491 |
await asyncio.sleep(5)
|
| 492 |
|
| 493 |
async def send_worker():
|
| 494 |
-
"
|
| 495 |
-
|
|
|
|
| 496 |
while True:
|
| 497 |
try:
|
| 498 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 499 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 500 |
db.row_factory = aiosqlite.Row
|
|
|
|
| 501 |
cursor = await db.execute("""
|
| 502 |
SELECT * FROM jobs
|
| 503 |
WHERE status='downloaded' AND (media_group_id IS NULL OR media_group_id='')
|
| 504 |
-
ORDER BY created_at LIMIT
|
| 505 |
""")
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
album_rows = await cursor.fetchall()
|
| 516 |
|
| 517 |
-
# إرسال المنفردات
|
| 518 |
for job in single_jobs:
|
|
|
|
|
|
|
| 519 |
async with send_sem:
|
| 520 |
await send_job(job)
|
| 521 |
|
| 522 |
-
# معالجة الألبومات
|
| 523 |
for (mg_id,) in album_rows:
|
|
|
|
|
|
|
| 524 |
await send_album_group(mg_id)
|
| 525 |
|
| 526 |
await asyncio.sleep(1)
|
| 527 |
|
| 528 |
except Exception as e:
|
| 529 |
-
logger.error(f"
|
| 530 |
await asyncio.sleep(5)
|
| 531 |
|
| 532 |
-
# ============
|
| 533 |
async def fetch_full_album(message):
|
| 534 |
-
"""جلب كل رسائل الألبوم مرة واحدة باستخدام get_media_group"""
|
| 535 |
try:
|
| 536 |
messages = await app.get_media_group(message.chat.id, message.id)
|
| 537 |
-
logger.info(f"
|
| 538 |
for msg in messages:
|
| 539 |
await add_job(msg)
|
| 540 |
return True
|
| 541 |
except Exception as e:
|
| 542 |
-
logger.warning(f"
|
| 543 |
return False
|
| 544 |
|
| 545 |
-
# ============
|
| 546 |
@app.on_message(filters.incoming & ~filters.me & filters.media)
|
| 547 |
async def on_media(client, message):
|
| 548 |
chat_id = message.chat.id
|
|
@@ -551,13 +518,11 @@ async def on_media(client, message):
|
|
| 551 |
|
| 552 |
src_name = get_source_name(message)
|
| 553 |
m_type, _ = get_media_info(message)
|
| 554 |
-
logger.info(f"
|
| 555 |
|
| 556 |
if message.media_group_id:
|
| 557 |
-
# 🔑 محاولة جلب الألبوم كاملاً
|
| 558 |
success = await fetch_full_album(message)
|
| 559 |
if not success:
|
| 560 |
-
# Fallback: إضافة الرسالة الحالية فقط
|
| 561 |
await add_job(message)
|
| 562 |
else:
|
| 563 |
await add_job(message)
|
|
@@ -566,7 +531,7 @@ async def on_media(client, message):
|
|
| 566 |
async def monitor_all(client, message):
|
| 567 |
if str(message.chat.id) == str(TARGET_CHAT):
|
| 568 |
return
|
| 569 |
-
logger.info(f"
|
| 570 |
|
| 571 |
async def resolve_target_chat():
|
| 572 |
global TARGET_CHAT
|
|
@@ -578,17 +543,17 @@ async def resolve_target_chat():
|
|
| 578 |
chat_id_int = int(raw)
|
| 579 |
chat = await app.get_chat(chat_id_int)
|
| 580 |
TARGET_CHAT = chat_id_int
|
| 581 |
-
logger.info(f"
|
| 582 |
except Exception as e:
|
| 583 |
-
logger.error(f"
|
| 584 |
TARGET_CHAT = "me"
|
| 585 |
|
| 586 |
# ============ Gradio + FastAPI ============
|
| 587 |
def run_gradio():
|
| 588 |
with gr.Blocks(title="Telegram Archiver Pro") as demo:
|
| 589 |
-
gr.Markdown("#
|
| 590 |
-
gr.Markdown("
|
| 591 |
-
gr.Textbox(label="
|
| 592 |
|
| 593 |
fastapi_app = FastAPI()
|
| 594 |
|
|
@@ -605,23 +570,34 @@ def run_gradio():
|
|
| 605 |
import uvicorn
|
| 606 |
uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)
|
| 607 |
|
| 608 |
-
# ============
|
| 609 |
async def main():
|
| 610 |
await app.start()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 611 |
me = await app.get_me()
|
| 612 |
await resolve_target_chat()
|
| 613 |
await init_db()
|
| 614 |
|
| 615 |
-
|
| 616 |
asyncio.create_task(download_worker())
|
|
|
|
| 617 |
asyncio.create_task(send_worker())
|
| 618 |
|
| 619 |
logger.info("=" * 60)
|
| 620 |
-
logger.info(f"
|
| 621 |
-
logger.info(f"
|
| 622 |
-
logger.info(f"
|
| 623 |
-
logger.info(f"
|
| 624 |
-
logger.info(f"📁 مجلد التحميل: {DOWNLOAD_DIR}")
|
| 625 |
logger.info("=" * 60)
|
| 626 |
|
| 627 |
stop_event = asyncio.Event()
|
|
|
|
| 32 |
SESSION_STRING = os.environ.get("SESSION_STRING", "")
|
| 33 |
TARGET_CHAT_RAW = os.environ.get("TARGET_CHAT", "me")
|
| 34 |
|
|
|
|
| 35 |
DATA_DIR = "/data"
|
| 36 |
DOWNLOAD_DIR = os.path.join(DATA_DIR, "downloads")
|
| 37 |
DB_PATH = os.path.join(DATA_DIR, "queue.db")
|
|
|
|
| 53 |
|
| 54 |
TARGET_CHAT = None
|
| 55 |
|
| 56 |
+
# ============ Throttle Controller ============
|
| 57 |
class ThrottleController:
|
| 58 |
+
def __init__(self, rate=1.2):
|
|
|
|
| 59 |
self.rate = rate
|
| 60 |
self.last_send = defaultdict(float)
|
| 61 |
self.lock = asyncio.Lock()
|
|
|
|
| 66 |
elapsed = now - self.last_send[chat_id]
|
| 67 |
if elapsed < self.rate:
|
| 68 |
wait_time = self.rate - elapsed
|
|
|
|
| 69 |
await asyncio.sleep(wait_time)
|
| 70 |
self.last_send[chat_id] = time.time()
|
| 71 |
|
| 72 |
+
throttle = ThrottleController(rate=1.2)
|
| 73 |
|
| 74 |
# ============ Semaphores ============
|
| 75 |
+
download_sem = asyncio.Semaphore(2)
|
| 76 |
+
send_sem = asyncio.Semaphore(2)
|
| 77 |
|
| 78 |
# ============ قاعدة البيانات ============
|
| 79 |
async def init_db():
|
|
|
|
| 80 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 81 |
await db.execute("""
|
| 82 |
CREATE TABLE IF NOT EXISTS jobs (
|
|
|
|
| 99 |
UNIQUE(chat_id, message_id)
|
| 100 |
)
|
| 101 |
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
await db.execute("""
|
| 103 |
CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status)
|
| 104 |
""")
|
|
|
|
| 106 |
CREATE INDEX IF NOT EXISTS idx_jobs_media_group ON jobs(media_group_id)
|
| 107 |
""")
|
| 108 |
await db.commit()
|
| 109 |
+
logger.info("Database ready")
|
| 110 |
|
| 111 |
async def add_job(message):
|
|
|
|
| 112 |
m_type, ext = get_media_info(message)
|
| 113 |
if not m_type:
|
| 114 |
return
|
| 115 |
|
|
|
|
| 116 |
file_id = None
|
| 117 |
file_size = 0
|
| 118 |
file_name = None
|
|
|
|
| 144 |
|
| 145 |
src_name = get_source_name(message)
|
| 146 |
raw_cap = message.caption or ""
|
| 147 |
+
final_cap = f"{raw_cap}\n\nSource: {src_name}".strip() if raw_cap else f"Source: {src_name}"
|
| 148 |
|
| 149 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 150 |
try:
|
|
|
|
| 158 |
))
|
| 159 |
await db.commit()
|
| 160 |
except Exception as e:
|
| 161 |
+
logger.error(f"Add job error: {e}")
|
| 162 |
|
| 163 |
async def update_job_status(chat_id, message_id, status, file_path=None, error=None):
|
|
|
|
| 164 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 165 |
if file_path:
|
| 166 |
await db.execute("""
|
|
|
|
| 179 |
""", (status, chat_id, message_id))
|
| 180 |
await db.commit()
|
| 181 |
|
| 182 |
+
async def get_pending_jobs(limit=3):
|
|
|
|
| 183 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 184 |
db.row_factory = aiosqlite.Row
|
| 185 |
cursor = await db.execute("""
|
|
|
|
| 192 |
return [dict(row) for row in rows]
|
| 193 |
|
| 194 |
async def get_downloaded_album_jobs(media_group_id):
|
|
|
|
| 195 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 196 |
db.row_factory = aiosqlite.Row
|
| 197 |
cursor = await db.execute("""
|
|
|
|
| 203 |
return [dict(row) for row in rows]
|
| 204 |
|
| 205 |
async def get_album_pending_count(media_group_id):
|
|
|
|
| 206 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 207 |
cursor = await db.execute("""
|
| 208 |
SELECT COUNT(*) FROM jobs
|
|
|
|
| 212 |
return row[0]
|
| 213 |
|
| 214 |
async def delete_job(chat_id, message_id):
|
|
|
|
| 215 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 216 |
cursor = await db.execute("""
|
| 217 |
SELECT file_path FROM jobs WHERE chat_id=? AND message_id=?
|
|
|
|
| 220 |
if row and row[0] and os.path.exists(row[0]):
|
| 221 |
try:
|
| 222 |
os.remove(row[0])
|
|
|
|
| 223 |
except:
|
| 224 |
pass
|
| 225 |
await db.execute("DELETE FROM jobs WHERE chat_id=? AND message_id=?", (chat_id, message_id))
|
|
|
|
| 248 |
def get_source_name(message):
|
| 249 |
chat = message.chat
|
| 250 |
if chat.type in ["channel", "supergroup", "group"]:
|
| 251 |
+
return chat.title or "Channel/Group"
|
| 252 |
elif chat.type == "private":
|
| 253 |
+
return chat.first_name or chat.username or "Private"
|
| 254 |
+
return "Source"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
# ============ التحميل مع التحقق ============
|
| 257 |
async def verify_download(file_path, expected_size):
|
|
|
|
| 258 |
if not file_path or not os.path.exists(file_path):
|
| 259 |
return False
|
| 260 |
actual_size = os.path.getsize(file_path)
|
| 261 |
if expected_size > 0 and actual_size < expected_size:
|
| 262 |
+
logger.warning(f"Incomplete file: {actual_size}/{expected_size} bytes")
|
| 263 |
return False
|
| 264 |
if actual_size == 0:
|
| 265 |
+
logger.warning(f"Zero-byte file: {file_path}")
|
| 266 |
return False
|
| 267 |
return True
|
| 268 |
|
| 269 |
async def download_job(job):
|
|
|
|
| 270 |
chat_id = job['chat_id']
|
| 271 |
message_id = job['message_id']
|
| 272 |
expected_size = job['file_size'] or 0
|
|
|
|
| 280 |
file_path = os.path.join(DOWNLOAD_DIR, f"{chat_id}_{message_id}{ext}")
|
| 281 |
|
| 282 |
try:
|
|
|
|
| 283 |
await update_job_status(chat_id, message_id, 'downloading')
|
| 284 |
|
|
|
|
| 285 |
downloaded = await app.download_media(
|
| 286 |
job['file_id'],
|
| 287 |
file_name=file_path
|
|
|
|
| 290 |
if not downloaded:
|
| 291 |
raise Exception("download_media returned None")
|
| 292 |
|
|
|
|
| 293 |
if not await verify_download(downloaded, expected_size):
|
| 294 |
+
logger.info(f"Retrying download {message_id}")
|
|
|
|
| 295 |
if os.path.exists(downloaded):
|
| 296 |
os.remove(downloaded)
|
| 297 |
downloaded = await app.download_media(
|
|
|
|
| 299 |
file_name=file_path
|
| 300 |
)
|
| 301 |
if not await verify_download(downloaded, expected_size):
|
| 302 |
+
raise Exception(f"Incomplete after retry")
|
| 303 |
|
| 304 |
await update_job_status(chat_id, message_id, 'downloaded', file_path=downloaded)
|
| 305 |
+
logger.info(f"Download complete: {message_id} | {os.path.getsize(downloaded)} bytes")
|
| 306 |
return True
|
| 307 |
|
| 308 |
except Exception as e:
|
| 309 |
await update_job_status(chat_id, message_id, 'pending', error=str(e))
|
| 310 |
+
logger.error(f"Download failed {message_id}: {e}")
|
| 311 |
return False
|
| 312 |
|
| 313 |
+
# ============ الإرسال ============
|
| 314 |
@retry(
|
| 315 |
stop=stop_after_attempt(5),
|
| 316 |
wait=wait_exponential_jitter(initial=1, max=60),
|
|
|
|
| 321 |
return await send_func()
|
| 322 |
|
| 323 |
async def send_job(job):
|
|
|
|
| 324 |
chat_id = job['chat_id']
|
| 325 |
message_id = job['message_id']
|
| 326 |
file_path = job['file_path']
|
| 327 |
|
| 328 |
if not file_path or not os.path.exists(file_path):
|
| 329 |
+
logger.error(f"File not found: {file_path}")
|
| 330 |
await update_job_status(chat_id, message_id, 'pending', error="File not found")
|
| 331 |
return False
|
| 332 |
|
|
|
|
| 351 |
elif m_type == 'animation':
|
| 352 |
await safe_send(lambda: app.send_animation(TARGET_CHAT, animation=file_path, caption=caption))
|
| 353 |
|
| 354 |
+
logger.info(f"Sent: {message_id}")
|
| 355 |
await delete_job(chat_id, message_id)
|
| 356 |
return True
|
| 357 |
|
| 358 |
except Exception as e:
|
| 359 |
+
logger.error(f"Send failed {message_id}: {e}")
|
| 360 |
await update_job_status(chat_id, message_id, 'downloaded', error=str(e))
|
| 361 |
return False
|
| 362 |
|
|
|
|
| 363 |
async def send_album_group(media_group_id):
|
|
|
|
| 364 |
jobs = await get_downloaded_album_jobs(media_group_id)
|
| 365 |
if not jobs:
|
| 366 |
return
|
| 367 |
|
|
|
|
| 368 |
pending = await get_album_pending_count(media_group_id)
|
| 369 |
if pending > 0:
|
| 370 |
+
logger.info(f"Album {media_group_id} waiting for {pending} files")
|
| 371 |
return
|
| 372 |
|
|
|
|
| 373 |
jobs.sort(key=lambda j: j['message_id'])
|
| 374 |
|
|
|
|
| 375 |
album_inputs = []
|
| 376 |
album_jobs = []
|
| 377 |
standalone_jobs = []
|
| 378 |
|
| 379 |
for i, job in enumerate(jobs):
|
| 380 |
+
cap = job['caption'] if i == 0 else None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
m_type = job['media_type']
|
| 382 |
file_path = job['file_path']
|
| 383 |
|
|
|
|
| 397 |
standalone_jobs.append(job)
|
| 398 |
|
| 399 |
async with send_sem:
|
|
|
|
| 400 |
chunk_size = 10
|
| 401 |
for idx in range(0, len(album_inputs), chunk_size):
|
| 402 |
chunk = album_inputs[idx:idx+chunk_size]
|
|
|
|
| 414 |
|
| 415 |
for j in chunk_jobs:
|
| 416 |
await delete_job(j['chat_id'], j['message_id'])
|
| 417 |
+
logger.info(f"Album {media_group_id} part {idx//chunk_size + 1} sent")
|
| 418 |
except Exception as e:
|
| 419 |
+
logger.error(f"Album send failed: {e}")
|
| 420 |
|
|
|
|
| 421 |
for job in standalone_jobs:
|
| 422 |
await send_job(job)
|
| 423 |
|
| 424 |
# ============ Workers ============
|
| 425 |
async def download_worker():
|
| 426 |
+
logger.info("Download Worker started")
|
| 427 |
+
await asyncio.sleep(3)
|
| 428 |
+
|
| 429 |
while True:
|
| 430 |
try:
|
| 431 |
+
if not app.is_connected:
|
| 432 |
+
logger.warning("Pyrogram not connected, waiting...")
|
| 433 |
+
await asyncio.sleep(5)
|
| 434 |
+
continue
|
| 435 |
+
|
| 436 |
+
jobs = await get_pending_jobs(limit=3)
|
| 437 |
if not jobs:
|
| 438 |
await asyncio.sleep(2)
|
| 439 |
continue
|
| 440 |
|
| 441 |
tasks = []
|
| 442 |
for job in jobs:
|
| 443 |
+
if len(tasks) >= 2:
|
| 444 |
break
|
| 445 |
tasks.append(download_job(job))
|
| 446 |
|
|
|
|
| 448 |
await asyncio.gather(*tasks, return_exceptions=True)
|
| 449 |
|
| 450 |
except Exception as e:
|
| 451 |
+
logger.error(f"Download Worker error: {e}")
|
| 452 |
await asyncio.sleep(5)
|
| 453 |
|
| 454 |
async def send_worker():
|
| 455 |
+
logger.info("Send Worker started")
|
| 456 |
+
await asyncio.sleep(5)
|
| 457 |
+
|
| 458 |
while True:
|
| 459 |
try:
|
| 460 |
+
if not app.is_connected:
|
| 461 |
+
logger.warning("Pyrogram not connected, waiting...")
|
| 462 |
+
await asyncio.sleep(5)
|
| 463 |
+
continue
|
| 464 |
+
|
| 465 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 466 |
db.row_factory = aiosqlite.Row
|
| 467 |
+
|
| 468 |
cursor = await db.execute("""
|
| 469 |
SELECT * FROM jobs
|
| 470 |
WHERE status='downloaded' AND (media_group_id IS NULL OR media_group_id='')
|
| 471 |
+
ORDER BY created_at LIMIT 3
|
| 472 |
""")
|
| 473 |
+
single_jobs = [dict(row) for row in await cursor.fetchall()]
|
| 474 |
+
|
| 475 |
+
cursor = await db.execute("""
|
| 476 |
+
SELECT media_group_id FROM jobs
|
| 477 |
+
WHERE status='downloaded' AND media_group_id IS NOT NULL AND media_group_id!=''
|
| 478 |
+
GROUP BY media_group_id
|
| 479 |
+
LIMIT 2
|
| 480 |
+
""")
|
| 481 |
+
album_rows = await cursor.fetchall()
|
|
|
|
| 482 |
|
|
|
|
| 483 |
for job in single_jobs:
|
| 484 |
+
if not app.is_connected:
|
| 485 |
+
break
|
| 486 |
async with send_sem:
|
| 487 |
await send_job(job)
|
| 488 |
|
|
|
|
| 489 |
for (mg_id,) in album_rows:
|
| 490 |
+
if not app.is_connected:
|
| 491 |
+
break
|
| 492 |
await send_album_group(mg_id)
|
| 493 |
|
| 494 |
await asyncio.sleep(1)
|
| 495 |
|
| 496 |
except Exception as e:
|
| 497 |
+
logger.error(f"Send Worker error: {e}")
|
| 498 |
await asyncio.sleep(5)
|
| 499 |
|
| 500 |
+
# ============ Album Fetch ============
|
| 501 |
async def fetch_full_album(message):
|
|
|
|
| 502 |
try:
|
| 503 |
messages = await app.get_media_group(message.chat.id, message.id)
|
| 504 |
+
logger.info(f"get_media_group: {len(messages)} messages")
|
| 505 |
for msg in messages:
|
| 506 |
await add_job(msg)
|
| 507 |
return True
|
| 508 |
except Exception as e:
|
| 509 |
+
logger.warning(f"get_media_group failed: {e}")
|
| 510 |
return False
|
| 511 |
|
| 512 |
+
# ============ Handlers ============
|
| 513 |
@app.on_message(filters.incoming & ~filters.me & filters.media)
|
| 514 |
async def on_media(client, message):
|
| 515 |
chat_id = message.chat.id
|
|
|
|
| 518 |
|
| 519 |
src_name = get_source_name(message)
|
| 520 |
m_type, _ = get_media_info(message)
|
| 521 |
+
logger.info(f"New: {chat_id}/{message.id} | {m_type} | album: {message.media_group_id is not None}")
|
| 522 |
|
| 523 |
if message.media_group_id:
|
|
|
|
| 524 |
success = await fetch_full_album(message)
|
| 525 |
if not success:
|
|
|
|
| 526 |
await add_job(message)
|
| 527 |
else:
|
| 528 |
await add_job(message)
|
|
|
|
| 531 |
async def monitor_all(client, message):
|
| 532 |
if str(message.chat.id) == str(TARGET_CHAT):
|
| 533 |
return
|
| 534 |
+
logger.info(f"Text from {message.chat.id}")
|
| 535 |
|
| 536 |
async def resolve_target_chat():
|
| 537 |
global TARGET_CHAT
|
|
|
|
| 543 |
chat_id_int = int(raw)
|
| 544 |
chat = await app.get_chat(chat_id_int)
|
| 545 |
TARGET_CHAT = chat_id_int
|
| 546 |
+
logger.info(f"Target: {chat.title}")
|
| 547 |
except Exception as e:
|
| 548 |
+
logger.error(f"Target check failed: {e}")
|
| 549 |
TARGET_CHAT = "me"
|
| 550 |
|
| 551 |
# ============ Gradio + FastAPI ============
|
| 552 |
def run_gradio():
|
| 553 |
with gr.Blocks(title="Telegram Archiver Pro") as demo:
|
| 554 |
+
gr.Markdown("# Telegram Archiver Pro")
|
| 555 |
+
gr.Markdown("Status: Running")
|
| 556 |
+
gr.Textbox(label="Status", value="Active | SQLite Queue | 3 Workers", interactive=False)
|
| 557 |
|
| 558 |
fastapi_app = FastAPI()
|
| 559 |
|
|
|
|
| 570 |
import uvicorn
|
| 571 |
uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)
|
| 572 |
|
| 573 |
+
# ============ Main ============
|
| 574 |
async def main():
|
| 575 |
await app.start()
|
| 576 |
+
|
| 577 |
+
retries = 0
|
| 578 |
+
while not app.is_connected and retries < 10:
|
| 579 |
+
await asyncio.sleep(1)
|
| 580 |
+
retries += 1
|
| 581 |
+
logger.info(f"Waiting for connection... ({retries}/10)")
|
| 582 |
+
|
| 583 |
+
if not app.is_connected:
|
| 584 |
+
logger.error("Failed to connect to Telegram")
|
| 585 |
+
return
|
| 586 |
+
|
| 587 |
me = await app.get_me()
|
| 588 |
await resolve_target_chat()
|
| 589 |
await init_db()
|
| 590 |
|
| 591 |
+
await asyncio.sleep(2)
|
| 592 |
asyncio.create_task(download_worker())
|
| 593 |
+
await asyncio.sleep(2)
|
| 594 |
asyncio.create_task(send_worker())
|
| 595 |
|
| 596 |
logger.info("=" * 60)
|
| 597 |
+
logger.info(f"Archiver Pro running!")
|
| 598 |
+
logger.info(f"Account: {me.first_name}")
|
| 599 |
+
logger.info(f"Target: {TARGET_CHAT}")
|
| 600 |
+
logger.info(f"Database: {DB_PATH}")
|
|
|
|
| 601 |
logger.info("=" * 60)
|
| 602 |
|
| 603 |
stop_event = asyncio.Event()
|