Cipher_MD_api / main.py
gimhan
Update main.py
ad3aa57 verified
import os
import uuid
import subprocess
from fastapi import FastAPI, BackgroundTasks, HTTPException
from fastapi.responses import FileResponse
import yt_dlp
import socket
app = FastAPI()
COOKIES_FILE = "cookies.txt"
def cleanup_file(path: str):
if os.path.exists(path):
os.remove(path)
@app.get("/")
def home():
# FFmpeg තියෙනවද කියලා චෙක් කරනවා
ffmpeg_check = subprocess.run(["ffmpeg", "-version"], capture_output=True, text=True)
return {
"status": "Alive",
"ffmpeg": "Installed" if ffmpeg_check.returncode == 0 else "Not Found"
}
@app.get("/download")
async def download_song(url: str, background_tasks: BackgroundTasks):
file_id = str(uuid.uuid4())
output_filename = f"{file_id}.mp3"
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': f"{file_id}.%(ext)s",
'source_address': '0.0.0.0', # 🔥 මේ පේළිය අනිවාර්යයෙන්ම දාන්න (Force IPv4)
'nocheckcertificate': True, # SSL අවුල් මගහරින්න
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'quiet': False,
'cookiefile': COOKIES_FILE if os.path.exists(COOKIES_FILE) else None,
'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
if os.path.exists(output_filename):
return FileResponse(
output_filename,
media_type="audio/mpeg",
filename="song.mp3",
background=background_tasks.add_task(cleanup_file, output_filename)
)
else:
return {"error": "File not found after download."}
except Exception as e:
# මෙතනින් තමයි ඇත්තම ලෙඩේ එළියට එවන්නේ
return {"error": str(e)}
import socket
@app.get("/debug")
def debug_network():
try:
# YouTube resolve වෙනවද කියලා බලනවා
host = "www.youtube.com"
ip = socket.gethostbyname(host)
return {"status": "Success", "host": host, "ip": ip}
except Exception as e:
return {"status": "Failed", "error": str(e)}