File size: 7,807 Bytes
7e23bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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)