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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks, status
|
| 2 |
+
from fastapi.security import APIKeyHeader
|
| 3 |
+
from fastapi.responses import JSONResponse
|
| 4 |
+
import asyncio
|
| 5 |
+
import aiohttp
|
| 6 |
+
import os
|
| 7 |
+
import secrets
|
| 8 |
+
import sqlite3
|
| 9 |
+
from datetime import datetime, timedelta
|
| 10 |
+
from pydantic import BaseModel
|
| 11 |
+
from typing import Optional
|
| 12 |
+
import uvicorn
|
| 13 |
+
import yt_dlp
|
| 14 |
+
import logging
|
| 15 |
+
from contextlib import asynccontextmanager
|
| 16 |
+
|
| 17 |
+
# Logging
|
| 18 |
+
logging.basicConfig(level=logging.INFO)
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
# Database init
|
| 22 |
+
DB_PATH = "api_users.db"
|
| 23 |
+
|
| 24 |
+
def init_db():
|
| 25 |
+
conn = sqlite3.connect(DB_PATH)
|
| 26 |
+
cursor = conn.cursor()
|
| 27 |
+
cursor.execute('''
|
| 28 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 29 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 30 |
+
api_key TEXT UNIQUE NOT NULL,
|
| 31 |
+
username TEXT,
|
| 32 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 33 |
+
last_used TIMESTAMP,
|
| 34 |
+
usage_count INTEGER DEFAULT 0,
|
| 35 |
+
plan TEXT DEFAULT 'free',
|
| 36 |
+
expires_at TIMESTAMP,
|
| 37 |
+
is_active BOOLEAN DEFAULT 1
|
| 38 |
+
)
|
| 39 |
+
''')
|
| 40 |
+
conn.commit()
|
| 41 |
+
conn.close()
|
| 42 |
+
|
| 43 |
+
init_db()
|
| 44 |
+
|
| 45 |
+
app = FastAPI(title="🎵 Commercial Music Bot API", version="2.0")
|
| 46 |
+
|
| 47 |
+
# API Key header
|
| 48 |
+
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
| 49 |
+
|
| 50 |
+
class User(BaseModel):
|
| 51 |
+
username: str
|
| 52 |
+
plan: str = "free" # free, pro, enterprise
|
| 53 |
+
|
| 54 |
+
class PlayRequest(BaseModel):
|
| 55 |
+
chat_id: int
|
| 56 |
+
message_id: int
|
| 57 |
+
query: str
|
| 58 |
+
is_video: bool = False
|
| 59 |
+
bot_token: str
|
| 60 |
+
|
| 61 |
+
class ApiKeyResponse(BaseModel):
|
| 62 |
+
api_key: str
|
| 63 |
+
username: str
|
| 64 |
+
plan: str
|
| 65 |
+
expires_at: Optional[str]
|
| 66 |
+
message: str
|
| 67 |
+
|
| 68 |
+
# Dependency to validate API key
|
| 69 |
+
async def get_current_user(api_key: str = Depends(api_key_header)):
|
| 70 |
+
if not api_key:
|
| 71 |
+
raise HTTPException(status_code=401, detail="API key required")
|
| 72 |
+
|
| 73 |
+
conn = sqlite3.connect(DB_PATH)
|
| 74 |
+
cursor = conn.cursor()
|
| 75 |
+
cursor.execute("SELECT * FROM users WHERE api_key = ? AND is_active = 1", (api_key,))
|
| 76 |
+
user = cursor.fetchone()
|
| 77 |
+
conn.close()
|
| 78 |
+
|
| 79 |
+
if not user:
|
| 80 |
+
raise HTTPException(status_code=401, detail="Invalid or inactive API key")
|
| 81 |
+
|
| 82 |
+
# Update usage
|
| 83 |
+
conn = sqlite3.connect(DB_PATH)
|
| 84 |
+
cursor = conn.cursor()
|
| 85 |
+
cursor.execute(
|
| 86 |
+
"UPDATE users SET usage_count = usage_count + 1, last_used = CURRENT_TIMESTAMP WHERE api_key = ?",
|
| 87 |
+
(api_key,)
|
| 88 |
+
)
|
| 89 |
+
conn.commit()
|
| 90 |
+
conn.close()
|
| 91 |
+
|
| 92 |
+
return {
|
| 93 |
+
"id": user[0],
|
| 94 |
+
"api_key": user[1],
|
| 95 |
+
"username": user[2],
|
| 96 |
+
"plan": user[3],
|
| 97 |
+
"usage_count": user[5]
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
@app.post("/generate-key", response_model=ApiKeyResponse)
|
| 101 |
+
async def generate_api_key(user: User):
|
| 102 |
+
"""Generate new API key for customer"""
|
| 103 |
+
api_key = secrets.token_urlsafe(32)
|
| 104 |
+
|
| 105 |
+
conn = sqlite3.connect(DB_PATH)
|
| 106 |
+
cursor = conn.cursor()
|
| 107 |
+
|
| 108 |
+
expires_at = None
|
| 109 |
+
if user.plan == "pro":
|
| 110 |
+
expires_at = (datetime.now() + timedelta(days=30)).isoformat()
|
| 111 |
+
elif user.plan == "enterprise":
|
| 112 |
+
expires_at = (datetime.now() + timedelta(days=365)).isoformat()
|
| 113 |
+
|
| 114 |
+
cursor.execute(
|
| 115 |
+
"INSERT INTO users (api_key, username, plan, expires_at) VALUES (?, ?, ?, ?)",
|
| 116 |
+
(api_key, user.username, user.plan, expires_at)
|
| 117 |
+
)
|
| 118 |
+
conn.commit()
|
| 119 |
+
conn.close()
|
| 120 |
+
|
| 121 |
+
plan_limits = {
|
| 122 |
+
"free": "10 requests/day",
|
| 123 |
+
"pro": "Unlimited (30 days)",
|
| 124 |
+
"enterprise": "Unlimited (1 year)"
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
return ApiKeyResponse(
|
| 128 |
+
api_key=api_key,
|
| 129 |
+
username=user.username,
|
| 130 |
+
plan=user.plan,
|
| 131 |
+
expires_at=expires_at,
|
| 132 |
+
message=f"✅ Key generated! Plan: {user.plan} ({plan_limits[user.plan]})"
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
@app.get("/my-stats")
|
| 136 |
+
async def get_user_stats(current_user: dict = Depends(get_current_user)):
|
| 137 |
+
"""Get user usage stats"""
|
| 138 |
+
conn = sqlite3.connect(DB_PATH)
|
| 139 |
+
cursor = conn.cursor()
|
| 140 |
+
cursor.execute("SELECT usage_count, created_at, plan, expires_at FROM users WHERE api_key = ?",
|
| 141 |
+
(current_user["api_key"],))
|
| 142 |
+
stats = cursor.fetchone()
|
| 143 |
+
conn.close()
|
| 144 |
+
|
| 145 |
+
return {
|
| 146 |
+
"username": current_user["username"],
|
| 147 |
+
"plan": stats[2],
|
| 148 |
+
"usage_count": stats[0],
|
| 149 |
+
"created": stats[1],
|
| 150 |
+
"expires_at": stats[3],
|
| 151 |
+
"daily_limit": "10" if stats[2] == "free" else "Unlimited"
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
@app.post("/play")
|
| 155 |
+
async def play_music(request: PlayRequest, background_tasks: BackgroundTasks,
|
| 156 |
+
current_user: dict = Depends(get_current_user)):
|
| 157 |
+
"""Main play endpoint with API key auth"""
|
| 158 |
+
|
| 159 |
+
# Check plan limits (simple daily limit for free)
|
| 160 |
+
if current_user["plan"] == "free" and current_user["usage_count"] >= 10:
|
| 161 |
+
raise HTTPException(status_code=429, detail="Free plan limit reached (10/day)")
|
| 162 |
+
|
| 163 |
+
try:
|
| 164 |
+
token = request.bot_token
|
| 165 |
+
base_url = f"https://api.telegram.org/bot{token}"
|
| 166 |
+
|
| 167 |
+
# Fast YouTube download (same as before)
|
| 168 |
+
audio_url = await fast_download(request.query, request.is_video)
|
| 169 |
+
if not audio_url:
|
| 170 |
+
raise HTTPException(status_code=404, detail="No media found")
|
| 171 |
+
|
| 172 |
+
media_type = "video" if request.is_video else "audio"
|
| 173 |
+
send_method = "sendVideo" if request.is_video else "sendAudio"
|
| 174 |
+
|
| 175 |
+
payload = {
|
| 176 |
+
"chat_id": request.chat_id,
|
| 177 |
+
"reply_to_message_id": request.message_id,
|
| 178 |
+
"title": "🎵 Playing Now",
|
| 179 |
+
"performer": f"Powered by {current_user['username']}",
|
| 180 |
+
media_type: audio_url,
|
| 181 |
+
"thumb": MUSIC_THUMB,
|
| 182 |
+
"duration": 0,
|
| 183 |
+
"disable_notification": True
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
async with aiohttp.ClientSession() as session:
|
| 187 |
+
async with session.post(f"{base_url}/{send_method}", json=payload) as resp:
|
| 188 |
+
result = await resp.json()
|
| 189 |
+
|
| 190 |
+
if not result.get("ok"):
|
| 191 |
+
raise HTTPException(status_code=500, detail="Telegram API failed")
|
| 192 |
+
|
| 193 |
+
return {"success": True, "message_id": result["result"]["message_id"]}
|
| 194 |
+
|
| 195 |
+
except Exception as e:
|
| 196 |
+
logger.error(f"Play error for {current_user['username']}: {e}")
|
| 197 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 198 |
+
|
| 199 |
+
# Same fast download function as before
|
| 200 |
+
ydl_opts = {
|
| 201 |
+
'quiet': True, 'no_warnings': True, 'format': 'bestaudio/best[height<=480]/best',
|
| 202 |
+
'outtmpl': '%(title)s.%(ext)s', 'noplaylist': True,
|
| 203 |
+
'postprocessors': [{'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192'}]
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
async def fast_download(query: str, is_video: bool):
|
| 207 |
+
loop = asyncio.get_event_loop()
|
| 208 |
+
def download():
|
| 209 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 210 |
+
info = ydl.extract_info(query, download=False)
|
| 211 |
+
return info.get('url') or info.get('formats', [{}])[0].get('url')
|
| 212 |
+
try:
|
| 213 |
+
return await loop.run_in_executor(None, download)
|
| 214 |
+
except:
|
| 215 |
+
return None
|
| 216 |
+
|
| 217 |
+
@app.get("/plans")
|
| 218 |
+
async def get_plans():
|
| 219 |
+
"""Show pricing plans"""
|
| 220 |
+
return {
|
| 221 |
+
"free": {"price": "0$", "requests": "10/day", "features": ["Basic audio"]},
|
| 222 |
+
"pro": {"price": "9.99$/month", "requests": "Unlimited", "features": ["Audio+Video", "Priority"]},
|
| 223 |
+
"enterprise": {"price": "99$/year", "requests": "Unlimited", "features": ["All features", "Support"]}
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
@app.get("/keys")
|
| 227 |
+
async def list_keys():
|
| 228 |
+
"""Admin: List all keys (add your admin check)"""
|
| 229 |
+
conn = sqlite3.connect(DB_PATH)
|
| 230 |
+
cursor = conn.cursor()
|
| 231 |
+
cursor.execute("SELECT username, api_key, plan, usage_count, created_at FROM users ORDER BY created_at DESC LIMIT 50")
|
| 232 |
+
keys = [{"username": row[0], "api_key": row[1][:8]+"...", "plan": row[2], "usage": row[3], "created": row[4]} for row in cursor.fetchall()]
|
| 233 |
+
conn.close()
|
| 234 |
+
return {"keys": keys, "total": len(keys)}
|
| 235 |
+
|
| 236 |
+
if __name__ == "__main__":
|
| 237 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|