Update app.py
Browse files142 unmodified lines1431441451461471481404 unmodified lines15531554155515561557155815591560156189 unmodified lines165116521653142 unmodified linestime_window=timedelta(days=1))def get_user_ip(request: Request) -> str:"""Helper function to get user's IP address."""1404 unmodified linesuser_ip = get_user_ip(request)base_url = str(request.base_url)if not has_valid_token and rate_limiter.is_rate_limited(user_ip):logger.warning(f'rate limited: {user_ip}')current_count = rate_limiter.get_current_count(user_ip)raise HTTPException(status_code=429,detail={89 unmodified linesreturn {"url": download_url}142 unmodified lines1431441451461471481491501511521531541404 unmodified lines15591560156115621563156415651566156789 unmodified lines16571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781142 unmodified linestime_window=timedelta(days=1))# Separate limiter for /maxs: 10 requests per daymaxs_rate_limiter = RateLimiter(max_requests=10,time_window=timedelta(days=1))def get_user_ip(request: Request) -> str:"""Helper function to get user's IP address."""1404 unmodified linesuser_ip = get_user_ip(request)base_url = str(request.base_url)if not has_valid_token and maxs_rate_limiter.is_rate_limited(user_ip):logger.warning(f'rate limited: {user_ip}')current_count = maxs_rate_limiter.get_current_count(user_ip)raise HTTPException(status_code=429,detail={89 unmodified linesreturn {"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_page(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.# Fetch N+1 entries (one extra probe): yt-dlp hard-stops at playlistend,# so requesting exactly page*20 makes has_next always false even when the# profile has hundreds more videos. If the probe entry comes back, another# page exists; if the result is short by one, we're at the end.needed = page * MAX_PLAYLIST_ITEMS + 1ydl_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+130-2