Spaces:
Sleeping
Sleeping
Update terabox_utils.py
Browse files- terabox_utils.py +13 -76
terabox_utils.py
CHANGED
|
@@ -3,19 +3,18 @@
|
|
| 3 |
import re
|
| 4 |
import requests
|
| 5 |
import asyncio
|
|
|
|
|
|
|
| 6 |
import os
|
| 7 |
-
import time
|
| 8 |
import math
|
| 9 |
-
import
|
| 10 |
-
from functools import partial
|
| 11 |
-
from typing import Optional, Tuple
|
| 12 |
|
| 13 |
import config
|
| 14 |
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
os.makedirs("downloads", exist_ok=True)
|
| 17 |
|
| 18 |
-
# --- Utility
|
| 19 |
def format_bytes(size_bytes: int) -> str:
|
| 20 |
if size_bytes <= 0:
|
| 21 |
return "0 B"
|
|
@@ -25,19 +24,8 @@ def format_bytes(size_bytes: int) -> str:
|
|
| 25 |
s = round(size_bytes / p, 2)
|
| 26 |
return f"{s} {size_name[i]}"
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
h, remainder = divmod(seconds_left, 3600)
|
| 31 |
-
m, s = divmod(remainder, 60)
|
| 32 |
-
if h > 0:
|
| 33 |
-
return f"{h}h {m}m {s}s"
|
| 34 |
-
elif m > 0:
|
| 35 |
-
return f"{m}m {s}s"
|
| 36 |
-
else:
|
| 37 |
-
return f"{s}s"
|
| 38 |
-
|
| 39 |
-
# --- Short ID Extract ---
|
| 40 |
-
async def extract_terabox_short_id(full_url: str) -> Optional[str]:
|
| 41 |
patterns = [
|
| 42 |
r'terabox\.com/s/([a-zA-Z0-9_-]+)',
|
| 43 |
r'teraboxapp\.com/s/([a-zA-Z0-9_-]+)',
|
|
@@ -53,8 +41,7 @@ async def extract_terabox_short_id(full_url: str) -> Optional[str]:
|
|
| 53 |
return m.group(1)
|
| 54 |
return None
|
| 55 |
|
| 56 |
-
|
| 57 |
-
async def get_final_url_and_filename(original_link: str) -> Tuple[Optional[str], Optional[str], Optional[str]]:
|
| 58 |
payload = {"link": original_link}
|
| 59 |
headers = {"User-Agent": "Mozilla/5.0"}
|
| 60 |
|
|
@@ -78,10 +65,9 @@ async def get_final_url_and_filename(original_link: str) -> Tuple[Optional[str],
|
|
| 78 |
except Exception as e:
|
| 79 |
return None, None, str(e)
|
| 80 |
|
| 81 |
-
|
| 82 |
-
async def download_terabox_file(bot_instance, chat_id, msg_id, url, filename) -> Tuple[Optional[str], Optional[str], Optional[str]]:
|
| 83 |
safe_fn = re.sub(r'[\\/*?:"<>|]', "_", filename)[:200]
|
| 84 |
-
download_path = os.path.join("downloads", f"{
|
| 85 |
|
| 86 |
try:
|
| 87 |
loop = asyncio.get_event_loop()
|
|
@@ -100,8 +86,6 @@ async def download_terabox_file(bot_instance, chat_id, msg_id, url, filename) ->
|
|
| 100 |
|
| 101 |
total_size = int(r.headers.get('content-length', 0))
|
| 102 |
dl_size = 0
|
| 103 |
-
last_update = time.time()
|
| 104 |
-
start_time = time.time()
|
| 105 |
|
| 106 |
with open(download_path, 'wb') as f:
|
| 107 |
for chunk in r.iter_content(chunk_size=1024 * 1024):
|
|
@@ -109,58 +93,11 @@ async def download_terabox_file(bot_instance, chat_id, msg_id, url, filename) ->
|
|
| 109 |
f.write(chunk)
|
| 110 |
dl_size += len(chunk)
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
pct = (dl_size / total_size * 100) if total_size > 0 else 0
|
| 117 |
-
prog_text = (
|
| 118 |
-
f"📥 <b>Downloading:</b> <code>{filename}</code>\n"
|
| 119 |
-
f"Progress: {format_bytes(dl_size)}/{format_bytes(total_size)} ({pct:.1f}%)\n"
|
| 120 |
-
f"Speed: {format_bytes(speed)}/s\n"
|
| 121 |
-
f"ETA: {format_eta(eta)}"
|
| 122 |
-
)
|
| 123 |
-
if time.time() - last_update > 2.5:
|
| 124 |
-
try:
|
| 125 |
-
await bot_instance.edit_message_text(
|
| 126 |
-
chat_id=chat_id,
|
| 127 |
-
message_id=msg_id,
|
| 128 |
-
text=prog_text,
|
| 129 |
-
parse_mode="HTML"
|
| 130 |
-
)
|
| 131 |
-
except Exception:
|
| 132 |
-
pass
|
| 133 |
-
|
| 134 |
-
last_update = time.time()
|
| 135 |
-
|
| 136 |
-
# Optional thumbnail generation — skip if not a video
|
| 137 |
-
video_exts = ('.mp4', '.mkv', '.mov', '.avi', '.webm')
|
| 138 |
-
thumb_path = None
|
| 139 |
-
if safe_fn.lower().endswith(video_exts):
|
| 140 |
-
thumb_path = await generate_video_thumbnail(download_path, chat_id)
|
| 141 |
-
|
| 142 |
-
return download_path, thumb_path, None
|
| 143 |
|
| 144 |
except Exception as e:
|
| 145 |
if os.path.exists(download_path):
|
| 146 |
os.remove(download_path)
|
| 147 |
-
return None,
|
| 148 |
-
|
| 149 |
-
# --- Generate Video Thumbnail (Optional) ---
|
| 150 |
-
async def generate_video_thumbnail(filepath: str, chat_id: int) -> Optional[str]:
|
| 151 |
-
try:
|
| 152 |
-
import subprocess
|
| 153 |
-
thumb_path = os.path.join("downloads", f"{chat_id}_{time.time()}_thumb.jpg")
|
| 154 |
-
|
| 155 |
-
ffmpeg_cmd = [
|
| 156 |
-
"ffmpeg", "-y", "-i", filepath,
|
| 157 |
-
"-ss", "00:00:01.000", "-vframes", "1", thumb_path
|
| 158 |
-
]
|
| 159 |
-
subprocess.run(ffmpeg_cmd, check=True)
|
| 160 |
-
|
| 161 |
-
if os.path.exists(thumb_path):
|
| 162 |
-
return thumb_path
|
| 163 |
-
except Exception as e:
|
| 164 |
-
logger.warning(f"Thumbnail generation failed: {e}")
|
| 165 |
-
|
| 166 |
-
return None
|
|
|
|
| 3 |
import re
|
| 4 |
import requests
|
| 5 |
import asyncio
|
| 6 |
+
from functools import partial
|
| 7 |
+
import logging
|
| 8 |
import os
|
|
|
|
| 9 |
import math
|
| 10 |
+
import time
|
|
|
|
|
|
|
| 11 |
|
| 12 |
import config
|
| 13 |
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
os.makedirs("downloads", exist_ok=True)
|
| 16 |
|
| 17 |
+
# --- Utility ---
|
| 18 |
def format_bytes(size_bytes: int) -> str:
|
| 19 |
if size_bytes <= 0:
|
| 20 |
return "0 B"
|
|
|
|
| 24 |
s = round(size_bytes / p, 2)
|
| 25 |
return f"{s} {size_name[i]}"
|
| 26 |
|
| 27 |
+
# --- Terabox ---
|
| 28 |
+
async def extract_terabox_short_id(full_url: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
patterns = [
|
| 30 |
r'terabox\.com/s/([a-zA-Z0-9_-]+)',
|
| 31 |
r'teraboxapp\.com/s/([a-zA-Z0-9_-]+)',
|
|
|
|
| 41 |
return m.group(1)
|
| 42 |
return None
|
| 43 |
|
| 44 |
+
async def get_final_url_and_filename(original_link: str):
|
|
|
|
| 45 |
payload = {"link": original_link}
|
| 46 |
headers = {"User-Agent": "Mozilla/5.0"}
|
| 47 |
|
|
|
|
| 65 |
except Exception as e:
|
| 66 |
return None, None, str(e)
|
| 67 |
|
| 68 |
+
async def download_terabox_file(url: str, filename: str):
|
|
|
|
| 69 |
safe_fn = re.sub(r'[\\/*?:"<>|]', "_", filename)[:200]
|
| 70 |
+
download_path = os.path.join("downloads", f"{int(time.time())}_{safe_fn}")
|
| 71 |
|
| 72 |
try:
|
| 73 |
loop = asyncio.get_event_loop()
|
|
|
|
| 86 |
|
| 87 |
total_size = int(r.headers.get('content-length', 0))
|
| 88 |
dl_size = 0
|
|
|
|
|
|
|
| 89 |
|
| 90 |
with open(download_path, 'wb') as f:
|
| 91 |
for chunk in r.iter_content(chunk_size=1024 * 1024):
|
|
|
|
| 93 |
f.write(chunk)
|
| 94 |
dl_size += len(chunk)
|
| 95 |
|
| 96 |
+
logger.info(f"Downloaded {safe_fn} ({format_bytes(dl_size)})")
|
| 97 |
+
|
| 98 |
+
return download_path, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
except Exception as e:
|
| 101 |
if os.path.exists(download_path):
|
| 102 |
os.remove(download_path)
|
| 103 |
+
return None, str(e)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|