Download app.py from iSoFe/TGCDN: direct link, hf CLI and curl.
- Browser
- Download file 5.81 kB
-
https://huggingface.co/spaces/iSoFe/TGCDN/resolve/main/app.py
- Command line
-
hf download hf://spaces/iSoFe/TGCDN/app.py
-
curl -L -o app.py https://huggingface.co/spaces/iSoFe/TGCDN/resolve/main/app.py
5.81 kB
| import os | |
| import re | |
| import asyncio | |
| from aiohttp import web | |
| from telethon import TelegramClient, events | |
| # بيانات البوت الخاصة بك | |
| API_ID = int(os.environ.get("API_ID", 34727408)) | |
| API_HASH = os.environ.get("API_HASH", "d15bfa45deb7af8b8c035ba9cd620b16") | |
| BOT_TOKEN = os.environ.get("BOT_TOKEN", "8941152436:AAHFspzGDVn82Zi4vpsXsALuBpc-pvwKPyU") | |
| # استخراج رابط مساحة Hugging Face تلقائياً | |
| SPACE_HOST = os.environ.get("SPACE_HOST", "") | |
| BASE_URL = f"https://{SPACE_HOST}" if SPACE_HOST else "" | |
| client = TelegramClient('hf_stream_session', API_ID, API_HASH) | |
| MEDIA_STORE = {} | |
| # 1. محرك تدفق الفيديو المباشر (Range Streaming) | |
| async def stream_handler(request): | |
| key = f"{request.match_info['chat_id']}_{request.match_info['msg_id']}" | |
| message = MEDIA_STORE.get(key) | |
| if not message or not message.media: | |
| return web.Response(status=404, text="الفيديو غير متوفر أو تمت إعادة تشغيل السيرفر") | |
| file_size = message.file.size | |
| range_header = request.headers.get('Range') | |
| if range_header: | |
| m = re.search(r'bytes=(\d+)-(\d*)', range_header) | |
| start = int(m.group(1)) | |
| end = int(m.group(2)) if m.group(2) else file_size - 1 | |
| else: | |
| start = 0 | |
| end = file_size - 1 | |
| length = end - start + 1 | |
| headers = { | |
| 'Content-Type': message.file.mime_type or 'video/mp4', | |
| 'Accept-Ranges': 'bytes', | |
| 'Content-Range': f'bytes {start}-{end}/{file_size}', | |
| 'Content-Length': str(length), | |
| 'Access-Control-Allow-Origin': '*' | |
| } | |
| response = web.StreamResponse(status=206 if range_header else 200, headers=headers) | |
| await response.prepare(request) | |
| # سحب قطع صغيرة جداً (512KB) من تيليجرام عند نقطة التقديم والتأخير فقط | |
| chunk_size = 512 * 1024 | |
| aligned_start = (start // chunk_size) * chunk_size | |
| skip = start - aligned_start | |
| bytes_left = length | |
| async for chunk in client.iter_download(message.media, offset=aligned_start, request_size=chunk_size): | |
| if skip > 0: | |
| if len(chunk) <= skip: | |
| skip -= len(chunk) | |
| continue | |
| else: | |
| chunk = chunk[skip:] | |
| skip = 0 | |
| if len(chunk) > bytes_left: | |
| chunk = chunk[:bytes_left] | |
| await response.write(chunk) | |
| bytes_left -= len(chunk) | |
| if bytes_left <= 0: | |
| break | |
| return response | |
| # 2. صفحة مشغل الفيديو النقي للمتصفح | |
| async def watch_handler(request): | |
| chat_id = request.match_info['chat_id'] | |
| msg_id = request.match_info['msg_id'] | |
| stream_url = f"/stream/{chat_id}/{msg_id}" | |
| html = f""" | |
| <!DOCTYPE html> | |
| <html dir="rtl"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>مشغل البث التجريبي</title> | |
| <style> | |
| body {{ | |
| margin: 0; background-color: #0b0c0f; display: flex; flex-direction: column; | |
| align-items: center; justify-content: center; height: 100vh; | |
| font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; | |
| color: #fff; | |
| }} | |
| .container {{ width: 95%; max-width: 900px; text-align: center; }} | |
| video {{ | |
| width: 100%; max-height: 70vh; background: #000; | |
| border-radius: 14px; box-shadow: 0 10px 40px rgba(0,0,0,0.8); outline: none; | |
| }} | |
| .note {{ margin-top: 20px; color: #4ade80; font-size: 15px; font-weight: 500; }} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <video controls autoplay playsinline src="{stream_url}"></video> | |
| <div class="note">⚡ جرب القفز والتقديم لنصف الفيديو لتلاحظ سلاسة الستريم بدون أي تنزيل على جهازك.</div> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| return web.Response(text=html, content_type='text/html') | |
| # 3. استقبال الفيديو في تيليجرام وتوليد الرابط فوراً | |
| async def on_new_video(event): | |
| if event.video or event.document: | |
| key = f"{event.chat_id}_{event.id}" | |
| MEDIA_STORE[key] = event.message | |
| # إنشاء رابط البث | |
| host = BASE_URL if BASE_URL else f"https://{request_host}" | |
| watch_url = f"{host}/watch/{event.chat_id}/{event.id}" | |
| direct_stream_url = f"{host}/stream/{event.chat_id}/{event.id}" | |
| msg = ( | |
| "🎬 **تم إنشاء رابط الستريم عبر سيرفر Hugging Face!**\n\n" | |
| f"🌐 **صفحة المشاهدة المباشرة:**\n{watch_url}\n\n" | |
| f"🔗 **رابط الستريم الصافي (للمشغلات والتطبيقات):**\n`{direct_stream_url}`" | |
| ) | |
| await event.reply(msg) | |
| # 4. بدء تشغيل البوت والسيرفر على منفذ 7860 | |
| async def main(): | |
| await client.start(bot_token=BOT_TOKEN) | |
| print("✅ تم ربط حساب تليثون بنجاح") | |
| app = web.Application() | |
| app.router.add_get('/watch/{chat_id}/{msg_id}', watch_handler) | |
| app.router.add_get('/stream/{chat_id}/{msg_id}', stream_handler) | |
| runner = web.AppRunner(app) | |
| await runner.setup() | |
| # 7860 هو المنفذ الإلزامي لمساحات Hugging Face | |
| site = web.TCPSite(runner, '0.0.0.0', 7860) | |
| await site.start() | |
| print("🚀 سيرفر البث يعمل الآن على منفذ Hugging Face (7860)") | |
| await client.run_until_disconnected() | |
| if __name__ == '__main__': | |
| asyncio.run(main()) | |