Update app.py
Browse files85 unmodified lines868788899091184 unmodified lines2762772782792802812822832842852 unmodified lines2882892902912922932942956 unmodified lines3023033043053063073083097 unmodified lines31731831932032132232319 unmodified lines34334434534685 unmodified linesTRACT_API = os.getenv("EXTRACT_API")ALT_API = os.getenv("ALT_API")target_domains = ["pornhub.com","xhamster.com",184 unmodified lines@app.post("/maxs")async def download_high_quality_video(request: Request):user_ip = get_user_ip(request)base_url = str(request.base_url)if 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 linesquality = data.get('quality', '720') # Default to 720 if not specifiedlogger.info(f'input: {video_url}, {quality}')# Check if the requested quality is above 1080pif int(quality) > 720: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 URLreturn {"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# Determine format string based on qualityformat_str = f'bestvideo[height<={max_height}][vcodec^=avc]+bestaudio/best'19 unmodified linesgc.collect()return {"url": download_url}85 unmodified lines86878889909192939495184 unmodified lines2802812822832842852862872882892902912922932942 unmodified lines2972982993003013026 unmodified lines3093103113123133143153167 unmodified lines32432532632732832933033133233333419 unmodified lines35435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647785 unmodified linesTRACT_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+ qualityhas_valid_token = bool(ACCESS_TOKEN) and data.get('token') == ACCESS_TOKENuser_ip = get_user_ip(request)base_url = str(request.base_url)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"})video_url = data.get('url')if "t.me" in video_url or "chrunos.com" in video_url:6 unmodified linesquality = data.get('quality', '720') # Default to 720 if not specifiedlogger.info(f'input: {video_url}, {quality}')# 1080p and higher require a valid tokenif 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 URLreturn {"error": error_message, "url": help_url}7 unmodified lines'720': 720,'1080': 1080}# Token users may request any height (e.g. 1440, 2160); tokenless users stay <= 720pif has_valid_token:max_height = int(quality)else:max_height = height_map.get(quality, 720)# Determine format string based on qualityformat_str = f'bestvideo[height<={max_height}][vcodec^=avc]+bestaudio/best'19 unmodified linesgc.collect()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 unlimitedand the tokenless 50-item cap is lifted (optional).Read from the X-Access-Token header first; if the headeris absent, the ?token= query param is used.Response:items: up to MAX_PLAYLIST_ITEMS entries for the requested pagepage: current page numbertotal: total items seen so far up to (and including) this pagehas_next: whether another page is availablenext_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 paramclient_token = request.headers.get("X-Access-Token") or request.query_params.get("token")has_valid_token = bool(ACCESS_TOKEN) and client_token == ACCESS_TOKENuser_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 = 1if page < 1:page = 1# For tokenless users, block pages that would exceed the 50-item capif not has_valid_token:max_allowed_page = (MAX_TOKENLESS_TOTAL + MAX_PLAYLIST_ITEMS - 1) // MAX_PLAYLIST_ITEMSif 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_ITEMSydl_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 itemif 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 totalif not has_valid_token and len(entries) > MAX_TOKENLESS_TOTAL:entries = entries[:MAX_TOKENLESS_TOTAL]start = (page - 1) * MAX_PLAYLIST_ITEMSend = start + MAX_PLAYLIST_ITEMSpage_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 = Nonereturn {"items": page_items,"page": page,"total": total_seen,"has_next": has_next,"next_page": next_page,}
app.py+139-8