Spaces:
iq7se2
/
5
Sleeping

5
File size: 4,758 Bytes
17fd2c2
 
 
21f4d9e
83b6a51
31cf358
83b6a51
 
 
 
 
 
 
 
 
 
17fd2c2
 
 
 
 
d7e681e
17fd2c2
 
99e5c70
17fd2c2
 
89438fd
17fd2c2
 
4ad87f6
17fd2c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ad87f6
17fd2c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21f4d9e
17fd2c2
 
 
 
 
 
73e87db
17fd2c2
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import os, time, threading, zipfile, io, re, telebot, requests
from flask import Flask
from playwright.sync_api import sync_playwright
from PIL import Image
import socket

# إضافة هذا السطر لإصلاح مشاكل الاتصال في بعض سيرفرات HF
def run_bot():
    while True:
        try:
            print("Trying to connect to Telegram...")
            bot.remove_webhook()
            bot.infinity_polling(timeout=20, long_polling_timeout=20)
        except Exception as e:
            print(f"Network error: {e}. Retrying in 5 seconds...")
            time.sleep(5)
# --- الإعدادات ---
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
# ضع آيدي قناتك هنا أو في Secrets
ARCHIVE_CH = os.getenv("ARCHIVE_CHANNEL_ID") 
ADMIN_HANDLE = "@svipfast"

bot = telebot.TeleBot(BOT_TOKEN, threaded=False)
app = Flask(__name__)

# قاعدة بيانات بسيطة للحفظ (تصفر عند الرستارت، للأفضل استخدم ملف .txt)
archive_db = {}

@app.route('/')
def home(): return "<h1>System is Online - @svipfast</h1>"

def fetch_with_browser(url):
    """محرك السحب الاحترافي لمحاكاة المتصفح البشري"""
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
        page = context.new_page()
        try:
            page.goto(url, wait_until="networkidle", timeout=60000)
            # التمرير لضمان ظهور الصور المخفية
            page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
            time.sleep(2)
            
            images = page.query_selector_all("img")
            img_data = []
            for img in images:
                src = img.get_attribute("src") or img.get_attribute("data-src")
                if src and any(x in src.lower() for x in ['.jpg', '.jpeg', '.png', '.webp']):
                    if "logo" in src.lower() or "banner" in src.lower(): continue
                    res = requests.get(src, timeout=10)
                    if res.status_code == 200 and len(res.content) > 25000:
                        img_data.append(res.content)
            browser.close()
            return img_data
        except:
            browser.close()
            return []

@bot.message_handler(func=lambda m: True)
def handle_request(message):
    try:
        # التنسيق: الرابط 1-5
        url, ch_range = message.text.split(' ')
        start, end = map(int, ch_range.split('-'))
        
        manga_id = re.sub(r'\W+', '', url.split('/')[-2])
        status = bot.reply_to(message, "🔍 جاري الفحص في الأرشيف والسحب الذكي...")
        
        files_to_send = []
        for i in range(start, end + 1):
            key = f"{manga_id}_{i}"
            # إذا كان موجوداً في الأرشيف، نرسله فوراً
            if key in archive_db:
                files_to_send.append(archive_db[key])
            else:
                # إذا غير موجود، نشغل المحرك الثقيل للسحب
                bot.edit_message_text(f"⏳ الفصل {i} غير مؤرشف.. جاري سحبه الآن من المصدر.", message.chat.id, status.message_id)
                target_url = url.rsplit('/', 1)[0] + f"/{i}" # تعديل الرابط تلقائياً
                imgs = fetch_with_browser(target_url)
                
                if imgs:
                    zip_name = f"CH_{i}.zip"
                    with zipfile.ZipFile(zip_name, 'w') as z:
                        for idx, data in enumerate(imgs):
                            z.writestr(f"{idx:03d}.jpg", data)
                    
                    # الرفع للأرشيف
                    with open(zip_name, 'rb') as f:
                        archived = bot.send_document(ARCHIVE_CH, f, caption=f"Manga: {manga_id} | Ch: {i}")
                        file_id = archived.document.file_id
                        archive_db[key] = file_id
                        files_to_send.append(file_id)
                    os.remove(zip_name)

        if files_to_send:
            for fid in files_to_send:
                bot.send_document(message.chat.id, fid)
            bot.delete_message(message.chat.id, status.message_id)
    except Exception as e:
        bot.reply_to(message, f"❌ حدث خطأ: {str(e)}\nتواصل مع {ADMIN_HANDLE}")

if __name__ == "__main__":
    # تثبيت المتصفح عند التشغيل
    os.system("playwright install chromium")
    threading.Thread(target=lambda: bot.infinity_polling(), daemon=True).start()
    app.run(host="0.0.0.0", port=7860)