Spaces:
Sleeping
Sleeping
Update terabox_utils.py
Browse files2 unmodified lines34567891011121314151617181920213 unmodified lines252627282930313233343536373839404142439 unmodified lines535455565758596017 unmodified lines7879808182838485868712 unmodified lines1001011021031041051061071 unmodified line1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651662 unmodified linesimport reimport requestsimport asyncioimport osimport timeimport mathimport loggingfrom functools import partialfrom typing import Optional, Tupleimport configlogger = logging.getLogger(__name__)os.makedirs("downloads", exist_ok=True)# --- Utility Functions ---def format_bytes(size_bytes: int) -> str:if size_bytes <= 0:return "0 B"3 unmodified liness = round(size_bytes / p, 2)return f"{s} {size_name[i]}"def format_eta(seconds_left: float) -> str:seconds_left = int(seconds_left)h, remainder = divmod(seconds_left, 3600)m, s = divmod(remainder, 60)if h > 0:return f"{h}h {m}m {s}s"elif m > 0:return f"{m}m {s}s"else:return f"{s}s"# --- Short ID Extract ---async def extract_terabox_short_id(full_url: str) -> Optional[str]:patterns = [r'terabox\.com/s/([a-zA-Z0-9_-]+)',r'teraboxapp\.com/s/([a-zA-Z0-9_-]+)',9 unmodified linesreturn m.group(1)return None# --- Get Final URL and Filename ---async def get_final_url_and_filename(original_link: str) -> Tuple[Optional[str], Optional[str], Optional[str]]:payload = {"link": original_link}headers = {"User-Agent": "Mozilla/5.0"}17 unmodified linesexcept Exception as e:return None, None, str(e)# --- Download with Progress ---async def download_terabox_file(bot_instance, chat_id, msg_id, url, filename) -> Tuple[Optional[str], Optional[str], Optional[str]]:safe_fn = re.sub(r'[\\/*?:"<>|]', "_", filename)[:200]download_path = os.path.join("downloads", f"{chat_id}_{time.time()}_{safe_fn}")try:loop = asyncio.get_event_loop()12 unmodified linestotal_size = int(r.headers.get('content-length', 0))dl_size = 0last_update = time.time()start_time = time.time()with open(download_path, 'wb') as f:for chunk in r.iter_content(chunk_size=1024 * 1024):1 unmodified linef.write(chunk)dl_size += len(chunk)elapsed = time.time() - start_timespeed = dl_size / elapsed if elapsed > 0 else 0eta = (total_size - dl_size) / speed if speed > 0 else 0pct = (dl_size / total_size * 100) if total_size > 0 else 0prog_text = (f"📥 <b>Downloading:</b> <code>{filename}</code>\n"f"Progress: {format_bytes(dl_size)}/{format_bytes(total_size)} ({pct:.1f}%)\n"f"Speed: {format_bytes(speed)}/s\n"f"ETA: {format_eta(eta)}")if time.time() - last_update > 2.5:try:await bot_instance.edit_message_text(chat_id=chat_id,message_id=msg_id,text=prog_text,parse_mode="HTML")except Exception:passlast_update = time.time()# Optional thumbnail generation — skip if not a videovideo_exts = ('.mp4', '.mkv', '.mov', '.avi', '.webm')thumb_path = Noneif safe_fn.lower().endswith(video_exts):thumb_path = await generate_video_thumbnail(download_path, chat_id)return download_path, thumb_path, Noneexcept Exception as e:if os.path.exists(download_path):os.remove(download_path)return None, None, str(e)# --- Generate Video Thumbnail (Optional) ---async def generate_video_thumbnail(filepath: str, chat_id: int) -> Optional[str]:try:import subprocessthumb_path = os.path.join("downloads", f"{chat_id}_{time.time()}_thumb.jpg")ffmpeg_cmd = ["ffmpeg", "-y", "-i", filepath,"-ss", "00:00:01.000", "-vframes", "1", thumb_path]subprocess.run(ffmpeg_cmd, check=True)if os.path.exists(thumb_path):return thumb_pathexcept Exception as e:logger.warning(f"Thumbnail generation failed: {e}")return None2 unmodified lines345678910111213141516171819203 unmodified lines24252627282930319 unmodified lines4142434445464717 unmodified lines65666768697071727312 unmodified lines8687888990911 unmodified line939495969798991001011021032 unmodified linesimport reimport requestsimport asynciofrom functools import partialimport loggingimport osimport mathimport timeimport configlogger = logging.getLogger(__name__)os.makedirs("downloads", exist_ok=True)# --- Utility ---def format_bytes(size_bytes: int) -> str:if size_bytes <= 0:return "0 B"3 unmodified liness = round(size_bytes / p, 2)return f"{s} {size_name[i]}"# --- Terabox ---async def extract_terabox_short_id(full_url: str):patterns = [r'terabox\.com/s/([a-zA-Z0-9_-]+)',r'teraboxapp\.com/s/([a-zA-Z0-9_-]+)',9 unmodified linesreturn m.group(1)return Noneasync def get_final_url_and_filename(original_link: str):payload = {"link": original_link}headers = {"User-Agent": "Mozilla/5.0"}17 unmodified linesexcept Exception as e:return None, None, str(e)async def download_terabox_file(url: str, filename: str):safe_fn = re.sub(r'[\\/*?:"<>|]', "_", filename)[:200]download_path = os.path.join("downloads", f"{int(time.time())}_{safe_fn}")try:loop = asyncio.get_event_loop()12 unmodified linestotal_size = int(r.headers.get('content-length', 0))dl_size = 0with open(download_path, 'wb') as f:for chunk in r.iter_content(chunk_size=1024 * 1024):1 unmodified linef.write(chunk)dl_size += len(chunk)logger.info(f"Downloaded {safe_fn} ({format_bytes(dl_size)})")return download_path, Noneexcept Exception as e:if os.path.exists(download_path):os.remove(download_path)return None, str(e)
terabox_utils.py+13-76