MyanmarSwe commited on
Commit
0f6ad68
·
verified ·
1 Parent(s): c3af0ee

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +99 -80
main.py CHANGED
@@ -1,96 +1,115 @@
 
 
1
  import asyncio
2
- import logging
3
- from pyrogram import Client, filters
4
- from motor.motor_asyncio import AsyncIOMotorClient
5
- from aiohttp import web
6
- from config import Config
7
 
8
- # Logging သတ်မှတ်ခြင်း
9
- logging.basicConfig(level=logging.INFO)
10
- logger = logging.getLogger(__name__)
 
 
11
 
12
- # --- Database Initialize ---
13
- db_client = AsyncIOMotorClient(Config.DATABASE_URL)
14
- db = db_client[Config.DATABASE_NAME]
15
- collection = db[Config.COLLECTION_NAME]
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- # --- Telegram Clients ---
18
- # Bot Client (Bot Token ဖြင့်)
19
- bot = Client(
20
- "TgIndexBot",
21
- api_id=Config.API_ID,
22
- api_hash=Config.API_HASH,
23
- bot_token=Config.BOT_TOKEN
24
- )
25
 
26
- # User Client (Session String ဖြင့- Channel history ဖတ်ရန်)
27
- user_bot = Client(
28
- "TgUserSession",
29
- api_id=Config.API_ID,
30
- api_hash=Config.API_HASH,
31
- session_string=Config.SESSION
32
- )
33
 
34
- # --- Bot Commands ---
 
 
 
 
 
 
 
35
 
36
- @bot.on_message(filters.command("start") & filters.private)
37
- async def start_cmd(client, message):
38
- if message.from_user.id in Config.OWNER_ID:
39
- await message.reply_text(f"မင်္ဂလာပါ Owner {message.from_user.first_name}!\nBot အောင်မြင်စွာ တက်လာပါပြီ။")
40
- else:
41
- await message.reply_text("သင်သည် ဤ Bot ၏ Owner မဟုတ်ပါ။")
42
 
43
- @bot.on_message(filters.command("index") & filters.private)
44
- async def index_files(client, message):
45
- if message.from_user.id not in Config.OWNER_ID:
46
- return
47
-
48
- await message.reply_text("Indexing စတင်နေပါပြီ... ခေတ္တစောင့်ပါ။")
49
 
50
- count = 0
51
- async for msg in user_bot.get_chat_history(Config.INDEX_CHANNEL):
52
- if msg.media:
53
- # Media file data ကို database ထဲသိမ်းခြင်း
54
- file_data = {
55
- "message_id": msg.id,
56
- "file_name": getattr(msg.document or msg.video or msg.audio, 'file_name', 'Unknown'),
57
- "file_type": str(msg.media),
58
- "caption": msg.caption or ""
59
- }
60
- await collection.update_one({"message_id": msg.id}, {"$set": file_data}, upsert=True)
61
- count += 1
62
-
63
- await message.reply_text(f"အောင်မြင်စွာ Index လုပ်ပြီးပါပြီ။ ဖိုင်ပေါင်း {count} ဖိုင် သိမ်းဆည်းခဲ့သည်။")
64
 
65
- # --- Web Server (for Health Check/Hugging Face) ---
 
 
 
 
 
 
 
66
 
67
- async def handle_web(request):
68
- return web.Response(text="🚀 TgindexPro is Running!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- async def start_webserver():
71
- app = web.Application()
72
- app.router.add_get("/", handle_web)
73
- runner = web.AppRunner(app)
74
- await runner.setup()
75
- site = web.TCPSite(runner, "0.0.0.0", Config.PORT)
76
- await site.start()
77
- logger.info(f"Web server started on port {Config.PORT}")
78
 
79
- # --- Main Function ---
 
 
 
 
80
 
81
- async def main():
82
- logger.info("Starting TgindexPro...")
83
-
84
- # Web Server run ခြင်း
85
- await start_webserver()
86
-
87
- # Bot နှင့် User Client တို့ကို run ခြင်း
88
- await bot.start()
89
- await user_bot.start()
90
-
91
- logger.info("Bot and User Session are online!")
92
- await asyncio.Event().wait()
93
 
94
  if __name__ == "__main__":
95
- loop = asyncio.get_event_loop()
96
- loop.run_until_complete(main())
 
1
+ import os
2
+ import re
3
  import asyncio
4
+ from fastapi import FastAPI, HTTPException, Request
5
+ from fastapi.responses import StreamingResponse, JSONResponse
6
+ from pyrogram import Client
7
+ import uvicorn
8
+ from contextlib import asynccontextmanager
9
 
10
+ # --- Config ---
11
+ API_ID = os.getenv("API_ID")
12
+ API_HASH = os.getenv("API_HASH")
13
+ STRING_SESSION = os.getenv("STRING_SESSION")
14
+ ACCESS_KEY = os.getenv("ACCESS_KEY", "0000")
15
 
16
+ @asynccontextmanager
17
+ async def lifespan(app: FastAPI):
18
+ # Bot ကို စတင်ခြင်း
19
+ user_bot = Client(
20
+ "tg_streamer",
21
+ api_id=API_ID,
22
+ api_hash=API_HASH,
23
+ session_string=STRING_SESSION,
24
+ in_memory=True,
25
+ workers=16
26
+ )
27
+ await user_bot.start()
28
+ app.state.tg = user_bot
29
+ print("🚀 Ultimate Smooth Streamer is Online!")
30
+ yield
31
+ # Bot ကို ပိတ်ခြင်း
32
+ await user_bot.stop()
33
 
34
+ app = FastAPI(lifespan=lifespan)
 
 
 
 
 
 
 
35
 
36
+ # --- Cron-job.org အတွကHealth Check Endpoint ---
37
+ @app.get("/")
38
+ async def health_check():
39
+ return JSONResponse(content={"status": "running", "message": "Server is alive!"})
 
 
 
40
 
41
+ def parse_tg_link(link: str):
42
+ match = re.search(r't\.me/(?:c/)?([^/]+)/(\d+)', link)
43
+ if match:
44
+ chat_id = match.group(1)
45
+ if chat_id.isdigit():
46
+ chat_id = int("-100" + chat_id)
47
+ return chat_id, int(match.group(2))
48
+ return None, None
49
 
50
+ @app.get("/stream")
51
+ async def stream_telegram(request: Request, url: str, key: str = None):
52
+ if key != ACCESS_KEY:
53
+ raise HTTPException(status_code=403, detail="Invalid Key")
 
 
54
 
55
+ chat_id, msg_id = parse_tg_link(url)
56
+ if not chat_id:
57
+ raise HTTPException(status_code=400, detail="Invalid URL")
58
+
59
+ client = request.app.state.tg
 
60
 
61
+ try:
62
+ msg = await client.get_messages(chat_id, msg_id)
63
+ media = msg.video or msg.document or msg.audio or msg.animation
64
+ if not media: raise Exception()
65
+ except:
66
+ raise HTTPException(status_code=404, detail="File not found")
 
 
 
 
 
 
 
 
67
 
68
+ file_size = media.file_size
69
+ range_header = request.headers.get("range")
70
+
71
+ start_byte = 0
72
+ if range_header:
73
+ match = re.search(r'bytes=(\d+)-', range_header)
74
+ if match:
75
+ start_byte = int(match.group(1))
76
 
77
+ async def refined_generator():
78
+ offset_in_mb = start_byte // (1024 * 1024)
79
+ skip_bytes = start_byte % (1024 * 1024)
80
+
81
+ try:
82
+ generator = client.stream_media(msg, offset=offset_in_mb, limit=30)
83
+ first_chunk = True
84
+ async for chunk in generator:
85
+ if first_chunk:
86
+ if len(chunk) > skip_bytes:
87
+ yield chunk[skip_bytes:]
88
+ first_chunk = False
89
+ else:
90
+ yield chunk
91
+ except Exception as e:
92
+ print(f"Stream interrupted: {e}")
93
+ return
94
 
95
+ headers = {
96
+ "Content-Type": getattr(media, "mime_type", "video/mp4"),
97
+ "Accept-Ranges": "bytes",
98
+ "Access-Control-Allow-Origin": "*",
99
+ "Cache-Control": "public, max-age=3600",
100
+ }
 
 
101
 
102
+ if range_header:
103
+ headers["Content-Range"] = f"bytes {start_byte}-{file_size-1}/{file_size}"
104
+ status_code = 206
105
+ else:
106
+ status_code = 200
107
 
108
+ return StreamingResponse(
109
+ refined_generator(),
110
+ status_code=status_code,
111
+ headers=headers
112
+ )
 
 
 
 
 
 
 
113
 
114
  if __name__ == "__main__":
115
+ uvicorn.run(app, host="0.0.0.0", port=7860)