import os import time import asyncio import aiohttp import subprocess import urllib.parse from fastapi import FastAPI, BackgroundTasks, HTTPException from fastapi.responses import FileResponse, JSONResponse from fastapi.middleware.cors import CORSMiddleware # ========================================== # 🚀 API SETUP & DOCUMENTATION # ========================================== app = FastAPI( title="SILENT TECH Media API", description="High-Speed API for YouTube Searching, MP4 fetching, and ultra-fast FFmpeg MP3 Extraction.", version="1.0.0" ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) def cleanup_files(files: list): for f in files: if os.path.exists(f): try: os.remove(f) except: pass # ========================================== # 📡 ENDPOINTS (WHITE-LABELED) # ========================================== @app.get("/") def read_root(): return {"status": "Online", "creator": "SILENT TECH", "message": "Visit /docs for the API Documentation!"} @app.get("/api/search") async def search_yt(query: str): """🔍 Search YouTube and return metadata.""" async with aiohttp.ClientSession() as session: url = f"https://apis.davidcyril.name.ng/play?query={urllib.parse.quote(query)}" async with session.get(url) as resp: data = await resp.json() if not data.get("status"): raise HTTPException(status_code=404, detail="Not found") # 🥷 THE NINJA MOVE: Overwrite the creator name! data["creator"] = "SILENT TECH" return data @app.get("/api/ytmp4") async def get_ytmp4(url: str): """🎬 Get a direct MP4 Download URL.""" async with aiohttp.ClientSession() as session: api_url = f"https://apis.davidcyril.name.ng/download/ytmp4?url={urllib.parse.quote(url)}" async with session.get(api_url) as resp: data = await resp.json() if not data.get("success"): raise HTTPException(status_code=400, detail="Failed to fetch video link") # 🥷 THE NINJA MOVE: Overwrite the creator name! data["creator"] = "SILENT TECH" return data @app.get("/api/ytmp3") async def get_ytmp3(url: str, background_tasks: BackgroundTasks): """🎵 Download MP4, convert to MP3 instantly via FFmpeg, and return the audio file.""" timestamp = int(time.time() * 1000) temp_vid = f"temp_vid_{timestamp}.mp4" temp_aud = f"temp_aud_{timestamp}.mp3" background_tasks.add_task(cleanup_files, [temp_vid, temp_aud]) try: async with aiohttp.ClientSession() as session: api_url = f"https://apis.davidcyril.name.ng/download/ytmp4?url={urllib.parse.quote(url)}" async with session.get(api_url) as resp: data = await resp.json() if not data.get("success") or not data.get("result", {}).get("download_url"): raise HTTPException(status_code=400, detail="Failed to fetch stream") download_url = data["result"]["download_url"] title = data["result"].get("title", "Silent_Tech_Audio").replace("/", "_") async with session.get(download_url) as video_resp: with open(temp_vid, 'wb') as f: while True: chunk = await video_resp.content.read(2 * 1024 * 1024) if not chunk: break f.write(chunk) command = [ "ffmpeg", "-y", "-i", temp_vid, "-vn", "-acodec", "libmp3lame", "-q:a", "2", temp_aud ] process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if process.returncode != 0: raise Exception("FFmpeg audio extraction failed.") return FileResponse( path=temp_aud, media_type="audio/mpeg", filename=f"{title}.mp3" ) except Exception as e: background_tasks.add_task(cleanup_files, [temp_vid, temp_aud]) raise HTTPException(status_code=500, detail=str(e))