Update app.py
Browse files20 unmodified lines212223242526262 unmodified lines28929029129229329411 unmodified lines3063073083093103113123133143153161 unmodified line3183193203213223233243253263273283293303313323333343353363371 unmodified line33934034134234334434534634734834935035135235335420 unmodified lineslogger = logging.getLogger(__name__)load_dotenv()app = FastAPI()262 unmodified linesbase_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,11 unmodified linesif "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 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}1 unmodified linetimestamp = 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 heightheight_map = {'480': 480,'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'ydl_opts = {'format': format_str,1 unmodified line'quiet': True,'no_warnings': True,'noprogress': True,'merge_output_format': 'mp4'}await run_in_threadpool(lambda: yt_dlp.YoutubeDL(ydl_opts).download([video_url]))downloaded_files = list(Path(global_download_dir).glob(f"*_{timestamp}.mp4"))if not downloaded_files:return {"error": "Download failed. Report error on Telegram", "url": "https://t.me/chrunoss"}downloaded_file = downloaded_files[0]encoded_filename = urllib.parse.quote(downloaded_file.name)download_url = f"{base_url}file/{encoded_filename}"20 unmodified lines2122232425262728293031323334262 unmodified lines29729829930030130230311 unmodified lines3153163173183193203213223233243253263273283293303313323333343353363373383391 unmodified line3413423433443453463473483493503513523533541 unmodified line35635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139220 unmodified lineslogger = logging.getLogger(__name__)class _SilentYtdlLogger:"""Swallows yt-dlp's own stderr lines; errors are logged via `logger` instead."""def debug(self, msg): passdef info(self, msg): passdef warning(self, msg): passdef error(self, msg): passload_dotenv()app = FastAPI()262 unmodified linesbase_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 linesif "threads.com" in video_url or "threads.net" in video_url:return await _download_threads(video_url)quality = str(data.get('quality', '720')) # Default to 720 if not specifiedlogger.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 tokenif 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 URLreturn {"error": error_message, "url": help_url}1 unmodified linetimestamp = datetime.now().strftime('%Y%m%d%H%M%S')output_template = str(Path(global_download_dir) / f'%(title).70s_{timestamp}.%(ext)s')# 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: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','logger': _SilentYtdlLogger(),}if is_audio:ydl_opts['postprocessors'] = [{'key': 'FFmpegExtractAudio','preferredcodec': 'mp3','preferredquality': '192',}]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 logerr = (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 = 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