File size: 5,808 Bytes
4a521a0 384ca1a 4a521a0 384ca1a 4a521a0 384ca1a 4a521a0 384ca1a 4a521a0 384ca1a 4a521a0 384ca1a 4a521a0 | 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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | 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. استقبال الفيديو في تيليجرام وتوليد الرابط فوراً
@client.on(events.NewMessage)
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())
|