NexaMusic / app.py
NexaCoders's picture
Create app.py
7e23bf5 verified
Raw History Blame Contribute Delete
7.81 kB
from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks, status
from fastapi.security import APIKeyHeader
from fastapi.responses import JSONResponse
import asyncio
import aiohttp
import os
import secrets
import sqlite3
from datetime import datetime, timedelta
from pydantic import BaseModel
from typing import Optional
import uvicorn
import yt_dlp
import logging
from contextlib import asynccontextmanager
# Logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Database init
DB_PATH = "api_users.db"
def init_db():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
api_key TEXT UNIQUE NOT NULL,
username TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_used TIMESTAMP,
usage_count INTEGER DEFAULT 0,
plan TEXT DEFAULT 'free',
expires_at TIMESTAMP,
is_active BOOLEAN DEFAULT 1
)
''')
conn.commit()
conn.close()
init_db()
app = FastAPI(title="🎵 Commercial Music Bot API", version="2.0")
# API Key header
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
class User(BaseModel):
username: str
plan: str = "free" # free, pro, enterprise
class PlayRequest(BaseModel):
chat_id: int
message_id: int
query: str
is_video: bool = False
bot_token: str
class ApiKeyResponse(BaseModel):
api_key: str
username: str
plan: str
expires_at: Optional[str]
message: str
# Dependency to validate API key
async def get_current_user(api_key: str = Depends(api_key_header)):
if not api_key:
raise HTTPException(status_code=401, detail="API key required")
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE api_key = ? AND is_active = 1", (api_key,))
user = cursor.fetchone()
conn.close()
if not user:
raise HTTPException(status_code=401, detail="Invalid or inactive API key")
# Update usage
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"UPDATE users SET usage_count = usage_count + 1, last_used = CURRENT_TIMESTAMP WHERE api_key = ?",
(api_key,)
)
conn.commit()
conn.close()
return {
"id": user[0],
"api_key": user[1],
"username": user[2],
"plan": user[3],
"usage_count": user[5]
}
@app.post("/generate-key", response_model=ApiKeyResponse)
async def generate_api_key(user: User):
"""Generate new API key for customer"""
api_key = secrets.token_urlsafe(32)
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
expires_at = None
if user.plan == "pro":
expires_at = (datetime.now() + timedelta(days=30)).isoformat()
elif user.plan == "enterprise":
expires_at = (datetime.now() + timedelta(days=365)).isoformat()
cursor.execute(
"INSERT INTO users (api_key, username, plan, expires_at) VALUES (?, ?, ?, ?)",
(api_key, user.username, user.plan, expires_at)
)
conn.commit()
conn.close()
plan_limits = {
"free": "10 requests/day",
"pro": "Unlimited (30 days)",
"enterprise": "Unlimited (1 year)"
}
return ApiKeyResponse(
api_key=api_key,
username=user.username,
plan=user.plan,
expires_at=expires_at,
message=f"✅ Key generated! Plan: {user.plan} ({plan_limits[user.plan]})"
)
@app.get("/my-stats")
async def get_user_stats(current_user: dict = Depends(get_current_user)):
"""Get user usage stats"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT usage_count, created_at, plan, expires_at FROM users WHERE api_key = ?",
(current_user["api_key"],))
stats = cursor.fetchone()
conn.close()
return {
"username": current_user["username"],
"plan": stats[2],
"usage_count": stats[0],
"created": stats[1],
"expires_at": stats[3],
"daily_limit": "10" if stats[2] == "free" else "Unlimited"
}
@app.post("/play")
async def play_music(request: PlayRequest, background_tasks: BackgroundTasks,
current_user: dict = Depends(get_current_user)):
"""Main play endpoint with API key auth"""
# Check plan limits (simple daily limit for free)
if current_user["plan"] == "free" and current_user["usage_count"] >= 10:
raise HTTPException(status_code=429, detail="Free plan limit reached (10/day)")
try:
token = request.bot_token
base_url = f"https://api.telegram.org/bot{token}"
# Fast YouTube download (same as before)
audio_url = await fast_download(request.query, request.is_video)
if not audio_url:
raise HTTPException(status_code=404, detail="No media found")
media_type = "video" if request.is_video else "audio"
send_method = "sendVideo" if request.is_video else "sendAudio"
payload = {
"chat_id": request.chat_id,
"reply_to_message_id": request.message_id,
"title": "🎵 Playing Now",
"performer": f"Powered by {current_user['username']}",
media_type: audio_url,
"thumb": MUSIC_THUMB,
"duration": 0,
"disable_notification": True
}
async with aiohttp.ClientSession() as session:
async with session.post(f"{base_url}/{send_method}", json=payload) as resp:
result = await resp.json()
if not result.get("ok"):
raise HTTPException(status_code=500, detail="Telegram API failed")
return {"success": True, "message_id": result["result"]["message_id"]}
except Exception as e:
logger.error(f"Play error for {current_user['username']}: {e}")
raise HTTPException(status_code=500, detail=str(e))
# Same fast download function as before
ydl_opts = {
'quiet': True, 'no_warnings': True, 'format': 'bestaudio/best[height<=480]/best',
'outtmpl': '%(title)s.%(ext)s', 'noplaylist': True,
'postprocessors': [{'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192'}]
}
async def fast_download(query: str, is_video: bool):
loop = asyncio.get_event_loop()
def download():
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(query, download=False)
return info.get('url') or info.get('formats', [{}])[0].get('url')
try:
return await loop.run_in_executor(None, download)
except:
return None
@app.get("/plans")
async def get_plans():
"""Show pricing plans"""
return {
"free": {"price": "0$", "requests": "10/day", "features": ["Basic audio"]},
"pro": {"price": "9.99$/month", "requests": "Unlimited", "features": ["Audio+Video", "Priority"]},
"enterprise": {"price": "99$/year", "requests": "Unlimited", "features": ["All features", "Support"]}
}
@app.get("/keys")
async def list_keys():
"""Admin: List all keys (add your admin check)"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT username, api_key, plan, usage_count, created_at FROM users ORDER BY created_at DESC LIMIT 50")
keys = [{"username": row[0], "api_key": row[1][:8]+"...", "plan": row[2], "usage": row[3], "created": row[4]} for row in cursor.fetchall()]
conn.close()
return {"keys": keys, "total": len(keys)}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)