-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
90 lines (77 loc) · 2.5 KB
/
Copy pathmain.py
File metadata and controls
90 lines (77 loc) · 2.5 KB
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
import os
from fastapi import FastAPI, Response, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pyrogram import Client
from motor.motor_asyncio import AsyncIOMotorClient
import uvicorn
# --- CONFIGURATION ---
# Use Environment Variables for security on Render
API_ID = int(os.environ.get("API_ID", 12345))
API_HASH = os.environ.get("API_HASH", "your_api_hash")
SESSION_STRING = os.environ.get("SESSION_STRING", "your_session_string")
MONGO_URL = os.environ.get("MONGO_URL", "mongodb://localhost:27017")
# --- INITIALIZATION ---
app = FastAPI()
# Enable CORS so your Blogger site can talk to Render
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # For production, replace with your blogger URL
allow_methods=["*"],
allow_headers=["*"],
)
# Pyrogram Client using Session String
tg_client = Client(
"music_streamer",
api_id=API_ID,
api_hash=API_HASH,
session_string=SESSION_STRING,
in_memory=True
)
# MongoDB Client
db_client = AsyncIOMotorClient(MONGO_URL)
db = db_client["music_database"]
@app.on_event("startup")
async def startup_event():
await tg_client.start()
@app.on_event("shutdown")
async def shutdown_event():
await tg_client.stop()
# --- ENDPOINTS ---
@app.get("/")
async def root():
return {"status": "Music Server Running"}
@app.get("/songs")
async def list_songs():
"""Fetch song list from MongoDB metadata"""
songs = []
cursor = db.songs.find({})
async for doc in cursor:
songs.append({
"id": str(doc["_id"]),
"title": doc.get("title", "Unknown"),
"artist": doc.get("artist", "Unknown artist"),
"file_id": doc.get("file_id") # This is the TG file_id
})
return songs
@app.get("/stream/{file_id}")
async def stream_audio(file_id: str):
"""Streams audio directly from Telegram to the browser"""
try:
# Define a generator to yield bytes from Telegram
async def audio_generator():
async for chunk in tg_client.stream_media(file_id):
yield chunk
return Response(
audio_generator(),
media_type="audio/mpeg",
headers={
"Accept-Ranges": "bytes",
"Content-Type": "audio/mpeg",
}
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
# Get port from Render's environment
port = int(os.environ.get("PORT", 8000))
uvicorn.run(app, host="0.0.0.0", port=port)