Update app.py
Browse files20 unmodified lines2122232425262728293031323334262 unmodified lines29729829930030130230311 unmodified lines3153163173093103183193203213223233243253263273283293303313323333343353133363373383391 unmodified line3413423433213223233243253263273283293443453463473483493503313323333343513523533541 unmodified line35635735834235936036136234536336436536636736836934737037137237337437537637737837938038138238338438538638735138838939039139220 unmodified lineslogger = logging.getLogger(__name__)
class _SilentYtdlLogger: """Swallows yt-dlp's own stderr lines; errors are logged via `logger` instead.""" def debug(self, msg): pass def info(self, msg): pass def warning(self, msg): pass def error(self, msg): pass
load_dotenv()app = FastAPI()262 unmodified lines 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,11 unmodified lines if "threads.com" in video_url or "threads.net" in video_url: return await _download_threads(video_url)
quality = data.get('quality', '720') # Default to 720 if not specified logger.info(f'input: {video_url}, {quality}') quality = str(data.get('quality', '720')) # Default to 720 if not specified logger.info(f'input: {video_url}, {quality}, token={has_valid_token}')
# Audio-only mode: extract best audio and transcode to MP3 (e.g. SoundCloud tracks) is_audio = quality.lower() in ('mp3', 'audio')
# Normalize quality to a video height. Token users may request any height # (e.g. 2160 for 4K); tokenless users stay <= 720p. height_map = {'480': 480, '720': 720, '1080': 1080, '2k': 1440, '4k': 2160} if quality.lower() in height_map: max_height = height_map[quality.lower()] else: try: max_height = int(quality) except ValueError: max_height = 720
# 1080p and higher require a valid token if int(quality) > 720 and not has_valid_token: if not is_audio and max_height > 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}1 unmodified line timestamp = datetime.now().strftime('%Y%m%d%H%M%S') output_template = str(Path(global_download_dir) / f'%(title).70s_{timestamp}.%(ext)s')
# Convert quality string to height height_map = { '480': 480, '720': 720, '1080': 1080 } # Token users may request any height (e.g. 1440, 2160); tokenless users stay <= 720p if has_valid_token: max_height = int(quality) # Determine format string based on quality. Above 1080p YouTube only offers # VP9/AV1 (no H.264), so the avc filter is dropped for token users to make 4K reachable. if is_audio: format_str = 'bestaudio/best' elif has_valid_token and max_height > 1080: format_str = f'bestvideo[height<={max_height}]+bestaudio/best' 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' format_str = f'bestvideo[height<={max_height}][vcodec^=avc]+bestaudio/best'
ydl_opts = { 'format': format_str,1 unmodified line 'quiet': True, 'no_warnings': True, 'noprogress': True, 'merge_output_format': 'mp4' 'merge_output_format': 'mp4', 'logger': _SilentYtdlLogger(), }
await run_in_threadpool(lambda: yt_dlp.YoutubeDL(ydl_opts).download([video_url])) if is_audio: ydl_opts['postprocessors'] = [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }]
downloaded_files = list(Path(global_download_dir).glob(f"*_{timestamp}.mp4")) try: await run_in_threadpool(lambda: yt_dlp.YoutubeDL(ydl_opts).download([video_url])) except Exception as e: # One-line summary only — yt-dlp's full traceback stays out of the log err = (str(e).splitlines() or ['unknown error'])[0] logger.error(f'failed: {video_url}, {quality} - {err}') return {"error": "Download failed. Report error on Telegram", "url": "https://t.me/chrunoss"}
# Audio-only sources (e.g. SoundCloud at a video quality) keep their native # container (.webm/.m4a/...), so match any extension, excluding partials. downloaded_files = [ p for p in Path(global_download_dir).glob(f"*_{timestamp}.*") if p.suffix.lower() not in ('.part', '.ytdl') ] if not downloaded_files: logger.error(f'no output file: {video_url}, {quality}') return {"error": "Download failed. Report error on Telegram", "url": "https://t.me/chrunoss"}
downloaded_file = downloaded_files[0] downloaded_file = max(downloaded_files, key=lambda p: p.stat().st_mtime) logger.info(f'success: {video_url}, {quality} -> {downloaded_file.name}') encoded_filename = urllib.parse.quote(downloaded_file.name) download_url = f"{base_url}file/{encoded_filename}"
app.py+58-20