Update app.py
Browse files85 unmodified lines86878889909192939495184 unmodified lines2802812822832842852862872882892812822902912922932942 unmodified lines2972982992912923003013026 unmodified lines3093103113053063123133143153167 unmodified lines32432532632032732832933033133233333419 unmodified lines35435535634635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647785 unmodified lines
TRACT_API = os.getenv("EXTRACT_API")ALT_API = os.getenv("ALT_API")
# Optional access token: clients with a valid token bypass the rate limit# and unlock 1080p+ quality downloadsACCESS_TOKEN = os.getenv("TOKEN")target_domains = [ "pornhub.com", "xhamster.com",184 unmodified lines
@app.post("/maxs")async def download_high_quality_video(request: Request): data = await request.json()
# Clients with a valid token bypass the rate limit and unlock 1080p+ quality has_valid_token = bool(ACCESS_TOKEN) and data.get('token') == ACCESS_TOKEN
user_ip = get_user_ip(request) base_url = str(request.base_url) if rate_limiter.is_rate_limited(user_ip):
if not has_valid_token and rate_limiter.is_rate_limited(user_ip): current_count = rate_limiter.get_current_count(user_ip) raise HTTPException( status_code=429,2 unmodified lines "url": "https://t.me/chrunoss" } ) data = await request.json()
video_url = data.get('url') if "t.me" in video_url or "chrunos.com" in video_url:6 unmodified lines quality = data.get('quality', '720') # Default to 720 if not specified logger.info(f'input: {video_url}, {quality}')
# Check if the requested quality is above 1080p if int(quality) > 720: # 1080p and higher require a valid token if int(quality) > 720 and not has_valid_token: error_message = "Quality above 720p is for Premium Members Only. Please check the URL for more information." help_url = "https://chrunos.com/premium-shortcuts/" # Replace with your actual URL return {"error": error_message, "url": help_url}7 unmodified lines '720': 720, '1080': 1080 } max_height = height_map.get(quality, 1080) # Use the quality variable correctly # Token users may request any height (e.g. 1440, 2160); tokenless users stay <= 720p if has_valid_token: max_height = int(quality) else: max_height = height_map.get(quality, 720)
# Determine format string based on quality format_str = f'bestvideo[height<={max_height}][vcodec^=avc]+bestaudio/best'19 unmodified lines
gc.collect()
return {"url": download_url} return {"url": download_url}
# =====================================================================# /api/playlist — yt-dlp playlist / profile pagination# =====================================================================MAX_PLAYLIST_ITEMS = 20
# Tokenless clients are capped at 50 total items across all pages# (they can paginate up to 50 entries, but no more).MAX_TOKENLESS_TOTAL = 50
@app.get("/api/playlist")async def fetch_playlist(request: Request): """ Fetches paginated items from a playlist or user profile via yt-dlp.
Query params: url: playlist/profile URL (required) page: page number to fetch, 1-based (optional, default 1) token: access token; when it matches TOKEN, pagination is unlimited and the tokenless 50-item cap is lifted (optional). Read from the X-Access-Token header first; if the header is absent, the ?token= query param is used.
Response: items: up to MAX_PLAYLIST_ITEMS entries for the requested page page: current page number total: total items seen so far up to (and including) this page has_next: whether another page is available next_page: full URL to fetch the next page (same base + ?page=N+1) or null if there is no next page """ # Token: X-Access-Token header wins over ?token= query param client_token = request.headers.get("X-Access-Token") or request.query_params.get("token") has_valid_token = bool(ACCESS_TOKEN) and client_token == ACCESS_TOKEN
user_ip = get_user_ip(request) if not has_valid_token and rate_limiter.is_rate_limited(user_ip): raise HTTPException( status_code=429, detail={ "error": "You have exceeded the maximum number of requests per day. Please try again tomorrow.", "url": "https://t.me/chrunoss" } )
playlist_url = request.query_params.get("url") if not playlist_url: raise HTTPException(status_code=400, detail="Missing 'url' query parameter") if "t.me" in playlist_url or "chrunos.com" in playlist_url: return {"error": f"{playlist_url} is not supported", "url": "https://t.me/chrunoss"}
page = request.query_params.get("page", "1") try: page = int(page) except (TypeError, ValueError): page = 1 if page < 1: page = 1
# For tokenless users, block pages that would exceed the 50-item cap if not has_valid_token: max_allowed_page = (MAX_TOKENLESS_TOTAL + MAX_PLAYLIST_ITEMS - 1) // MAX_PLAYLIST_ITEMS if page > max_allowed_page: return { "error": "Free tier is limited to 50 playlist items. Provide a valid token for full access.", "url": "https://chrunos.com/premium-shortcuts/" }
# yt-dlp flat extraction: fast metadata-only fetch of entries # playlistend caps how many entries yt-dlp will walk — request enough # to cover the current page, then slice in-process. needed = page * MAX_PLAYLIST_ITEMS ydl_opts = { 'quiet': True, 'no_warnings': True, 'skip_download': True, 'extract_flat': True, # Cap the number of entries fetched from the upstream site. 'playlistend': needed, }
try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = await run_in_threadpool(ydl.extract_info, playlist_url, download=False) except Exception as e: logger.error(f"playlist extract failed: {e}") return {"error": f"yt-dlp failed: {str(e)}", "url": "https://t.me/chrunoss"}
# info may be a single video dict (no playlist) — wrap it as one item if not isinstance(info, dict) or 'entries' not in info: entries = [info] if info else [] else: entries = list(info.get('entries') or [])
# Tokenless cap: enforce 50 total if not has_valid_token and len(entries) > MAX_TOKENLESS_TOTAL: entries = entries[:MAX_TOKENLESS_TOTAL]
start = (page - 1) * MAX_PLAYLIST_ITEMS end = start + MAX_PLAYLIST_ITEMS page_items = entries[start:end] total_seen = min(len(entries), end)
has_next = end < len(entries) base_url = str(request.base_url).rstrip('/') if has_next: encoded_url = urllib.parse.quote(playlist_url, safe='') next_page = f"{base_url}/api/playlist?page={page + 1}&url={encoded_url}" else: next_page = None
return { "items": page_items, "page": page, "total": total_seen, "has_next": has_next, "next_page": next_page, }app.py+139-8