-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
2203 lines (1945 loc) · 103 KB
/
Copy pathbot.py
File metadata and controls
2203 lines (1945 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import time
from math import floor
import threading
import uuid
from pathlib import Path
from urllib.parse import urlparse
import aiohttp
try:
from pyrogram import Client as PyroClient
from pyrogram.errors import FloodWait, RPCError
PYROGRAM_AVAILABLE = True
except ImportError:
PYROGRAM_AVAILABLE = False
# =========================
# Developer: @anujbyedit
# =========================
from flask import Flask, request, Response
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.constants import ChatAction
from telegram.ext import (
Application, CallbackQueryHandler, CommandHandler,
ContextTypes, MessageHandler, filters,
)
from telegram.request import HTTPXRequest
# =========================
# Settings
# =========================
BOT_TOKEN = os.environ.get("BOT_TOKEN", "8015464564:AAFe6QCyYpfSWPGbwih_u_XejaDLcho1KOI")
BOT_USERNAME = os.environ.get("BOT_USERNAME", "unzip_anuj_bot")
WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "")
PORT = int(os.environ.get("PORT", 5000))
API_ID = int(os.environ.get("API_ID", "37476811"))
API_HASH = os.environ.get("API_HASH", "7aa60670b871050820086c6267371ee6")
ADMIN_USER_ID = int(os.environ.get("ADMIN_USER_ID", "7168219724"))
YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY", "AIzaSyCGfwA660Ba65cheWLn8ybj7eIbA4xhPQ0")
REQUIRED_CHANNEL_USERNAME = os.environ.get("REQUIRED_CHANNEL_USERNAME", "@log_ak_bots")
REQUIRED_CHANNEL_URL = os.environ.get("REQUIRED_CHANNEL_URL", "https://t.me/log_ak_bots")
INSTAGRAM_COOKIE_FILE = "downloads/instagram_cookies.txt"
TIKTOK_COOKIE_FILE = "downloads/tiktok_cookies.txt"
YOUTUBE_COOKIE_FILE = "downloads/youtube_cookies.txt"
FACEBOOK_COOKIE_FILE = "downloads/facebook_cookies.txt"
SPOTIFY_COOKIE_FILE = "downloads/spotify_cookies.txt"
BASE_DIR = Path(__file__).resolve().parent
DOWNLOAD_DIR = BASE_DIR / "downloads"
DOWNLOAD_DIR.mkdir(exist_ok=True)
STATS_FILE = BASE_DIR / "bot_stats.json"
COOKIE_FILES = {
"youtube": BASE_DIR / "downloads/youtube_cookies.txt",
"instagram": BASE_DIR / "downloads/instagram_cookies.txt",
"facebook": BASE_DIR / "downloads/facebook_cookies.txt",
"tiktok": BASE_DIR / "downloads/tiktok_cookies.txt",
"spotify": BASE_DIR / "downloads/spotify_cookies.txt",
}
_cookie_pending: dict[int, str] = {}
MAX_CONCURRENT_DOWNLOADS = 4
DOWNLOAD_TIMEOUT = 14400
UPLOAD_READ_TIMEOUT = 7200
UPLOAD_WRITE_TIMEOUT = 7200
UPLOAD_CONNECT_TIMEOUT = 60
UPLOAD_POOL_TIMEOUT = 60
download_semaphore: asyncio.Semaphore
TG_MAX_FILE_SIZE = 2000 * 1024 * 1024
TG_STANDARD_LIMIT = 50 * 1024 * 1024
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
VIDEO_EXTS = {".mp4", ".mov", ".mkv", ".webm", ".m4v"}
AUDIO_EXTS = {".mp3", ".m4a", ".aac", ".flac", ".opus", ".ogg"}
FILE_CAPTION_BASE = "Downloaded by @anujbyedit\n🚀 Bot: @url_ak_uploader_bot"
logging.basicConfig(
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
level=logging.INFO,
)
logger = logging.getLogger("Downloader-Bot")
flask_app = Flask(__name__)
# =========================
# Cookie helpers
# =========================
def get_cookie_expiry_info() -> dict:
import time as _t
now = int(_t.time())
result = {}
for platform, path in COOKIE_FILES.items():
if not path.exists():
result[platform] = {"status": "missing", "days_left": None}
continue
min_exp, valid = None, False
try:
for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split("\t")
if len(parts) >= 7:
valid = True
try:
exp = int(parts[4])
if exp > 0 and (min_exp is None or exp < min_exp):
min_exp = exp
except ValueError:
pass
except Exception:
pass
if not valid:
result[platform] = {"status": "empty", "days_left": None}
elif min_exp is None:
result[platform] = {"status": "ok_session", "days_left": None}
else:
dl = (min_exp - now) // 86400
result[platform] = {
"status": "expired" if dl < 0 else ("expiring_soon" if dl < 7 else "ok"),
"days_left": dl,
}
return result
def format_cookie_status_text() -> str:
info = get_cookie_expiry_info()
icons = {"ok": "✅", "ok_session": "✅", "expiring_soon": "⚠️", "expired": "❌", "missing": "🚫", "empty": "🚫"}
lines = ["🍪 <b>Cookie Status</b>\n"]
for platform, data in info.items():
icon = icons.get(data["status"], "❓")
name = platform.capitalize()
st = data["status"]
if st in ("missing", "empty"):
lines.append(f"{icon} <b>{name}</b>: Not found")
elif st == "expired":
lines.append(f"{icon} <b>{name}</b>: EXPIRED {abs(data['days_left'])} days ago")
elif st == "expiring_soon":
lines.append(f"{icon} <b>{name}</b>: Expires in {data['days_left']} days ⚠️")
elif st == "ok_session":
lines.append(f"{icon} <b>{name}</b>: Active (session cookie)")
else:
lines.append(f"{icon} <b>{name}</b>: Valid — {data['days_left']} days left")
lines += ["", "📋 <b>Commands:</b>",
"/setcookies youtube", "/setcookies instagram",
"/setcookies facebook", "/setcookies tiktok",
"/setcookies spotify", "/cookies — status check karo"]
return "\n".join(lines)
# =========================
# Pyrogram Client
# =========================
_pyro_client: "PyroClient | None" = None
_pyro_lock: asyncio.Lock | None = None
async def _get_pyro_lock() -> asyncio.Lock:
global _pyro_lock
if _pyro_lock is None:
_pyro_lock = asyncio.Lock()
return _pyro_lock
async def get_pyro_client() -> "PyroClient | None":
global _pyro_client
if not PYROGRAM_AVAILABLE or not API_ID or not API_HASH:
return None
lock = await _get_pyro_lock()
async with lock:
if _pyro_client is not None:
try:
await _pyro_client.get_me()
return _pyro_client
except Exception:
logger.warning("Pyrogram reconnecting...")
try:
await _pyro_client.stop()
except Exception:
pass
_pyro_client = None
for attempt in range(1, 4):
try:
client = PyroClient(
name="downloader_bot_pyro",
api_id=API_ID,
api_hash=API_HASH,
bot_token=BOT_TOKEN,
in_memory=True,
max_concurrent_transmissions=4,
)
await client.start()
_pyro_client = client
logger.info("✅ Pyrogram ready (attempt %d) — 2GB upload!", attempt)
return _pyro_client
except Exception as e:
logger.warning("Pyrogram attempt %d failed: %s", attempt, e)
await asyncio.sleep(3)
logger.error("❌ Pyrogram start failed after 3 attempts.")
return None
# =========================
# Stats Store
# =========================
class StatsStore:
def __init__(self, path: Path):
self.path = path
self._lock: asyncio.Lock | None = None
self.data = self._load()
@property
def lock(self) -> asyncio.Lock:
if self._lock is None:
self._lock = asyncio.Lock()
return self._lock
def _default_data(self): return {"total_downloads": 0, "users": {}}
def _load(self) -> dict:
if not self.path.exists():
d = self._default_data(); self._save_sync(d); return d
try:
d = json.loads(self.path.read_text(encoding="utf-8"))
d.setdefault("total_downloads", 0); d.setdefault("users", {})
return d
except Exception:
d = self._default_data(); self._save_sync(d); return d
def _save_sync(self, data):
self.path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
async def register_user(self, user) -> bool:
uid = str(user.id)
async with self.lock:
is_new = uid not in self.data["users"]
self.data["users"][uid] = {
"id": user.id, "username": user.username or "",
"first_name": user.first_name or "", "last_name": user.last_name or "",
}
self._save_sync(self.data)
return is_new
async def increment_downloads(self):
async with self.lock:
self.data["total_downloads"] = int(self.data.get("total_downloads", 0)) + 1
self._save_sync(self.data)
async def get_stats(self) -> dict:
async with self.lock:
return {"total_users": len(self.data.get("users", {})),
"total_downloads": int(self.data.get("total_downloads", 0))}
stats_store = StatsStore(STATS_FILE)
# =========================
# Stores
# =========================
_url_store: dict[str, tuple] = {}
_search_store: dict[str, tuple] = {}
_playlist_store: dict[str, tuple] = {}
_STORE_TTL = 3600
def _purge(store: dict, ttl: float):
now = time.time()
for k in [k for k, v in store.items() if now - v[-1] > ttl]:
store.pop(k, None)
def store_url(url, platform, video_info=None) -> str:
_purge(_url_store, _STORE_TTL)
key = uuid.uuid4().hex[:8]
_url_store[key] = (url, platform, video_info, time.time())
return key
def get_url(key):
e = _url_store.get(key)
return (e[0], e[1]) if e else None
def get_url_with_info(key):
e = _url_store.get(key)
return (e[0], e[1], e[2]) if e else None
def cleanup_url(key): _url_store.pop(key, None)
def store_search_results(results, query="", page=0) -> str:
_purge(_search_store, _STORE_TTL)
key = uuid.uuid4().hex[:8]
_search_store[key] = (results, query, page, time.time())
return key
def get_search_results(key): e = _search_store.get(key); return e[0] if e else None
def get_search_query(key): e = _search_store.get(key); return e[1] if e else ""
def get_search_page(key): e = _search_store.get(key); return e[2] if e else 0
def cleanup_search_results(key): _search_store.pop(key, None)
def store_playlist(videos, title="", url="") -> str:
_purge(_playlist_store, _STORE_TTL)
key = uuid.uuid4().hex[:8]
_playlist_store[key] = (videos, title, url, time.time())
return key
def get_playlist(key):
e = _playlist_store.get(key)
return (e[0], e[1], e[2]) if e else None
def cleanup_playlist(key): _playlist_store.pop(key, None)
# =========================
# Helpers
# =========================
def extract_first_url(text: str):
if not text: return None
m = re.search(r"https?://[^\s]+", text)
return m.group(0).strip() if m else None
def is_search_query(text: str) -> bool:
if not text or not text.strip(): return False
if re.search(r"https?://", text): return False
if text.startswith("/"): return False
s = text.strip()
return len(s.split()) >= 2 or len(s) >= 3
def is_youtube_playlist(url: str) -> bool:
try:
from urllib.parse import parse_qs
parsed = urlparse(url)
host = (parsed.netloc or "").lower()
if host not in {"youtube.com", "www.youtube.com", "m.youtube.com", "youtu.be"}: return False
qs = parse_qs(parsed.query)
return "list" in qs and ("playlist" in parsed.path.lower() or "v" not in qs)
except Exception:
return False
def get_platform(url: str):
try: host = (urlparse(url).netloc or "").lower()
except Exception: return None
if host in {"instagram.com", "www.instagram.com"}: return "instagram"
if host in {"tiktok.com", "www.tiktok.com", "m.tiktok.com", "vm.tiktok.com", "vt.tiktok.com"}: return "tiktok"
if host in {"youtube.com", "www.youtube.com", "youtu.be", "m.youtube.com"}: return "youtube"
if host in {"pinterest.com", "www.pinterest.com", "pin.it", "pinterest.co.uk"}: return "pinterest"
if host in {"snapchat.com", "www.snapchat.com"}: return "snapchat"
if host in {"likee.video", "www.likee.video", "like.video"}: return "likee"
if host in {"vk.com", "www.vk.com", "vkvideo.ru", "www.vkvideo.ru"}: return "vk"
if host in {"facebook.com", "www.facebook.com", "m.facebook.com", "fb.watch"}: return "facebook"
if host in {"threads.net", "www.threads.net"}: return "threads"
if host in {"soundcloud.com", "www.soundcloud.com", "on.soundcloud.com",
"open.spotify.com", "deezer.com", "www.deezer.com", "music.apple.com"}: return "music"
return None
SHOW_QUALITY_PLATFORMS = {"youtube", "facebook", "instagram", "tiktok", "vk", "snapchat", "likee", "threads", "pinterest"}
SKIP_QUALITY_PLATFORMS = {"music"}
GALLERY_DL_PREFERRED = {"pinterest"}
def format_size(b: int) -> str:
if b < 1024: return f"{b} B"
if b < 1024**2: return f"{b/1024:.1f} KB"
if b < 1024**3: return f"{b/1024**2:.1f} MB"
return f"{b/1024**3:.2f} GB"
def format_duration(s: int) -> str:
if s < 0: return "??:??"
h, r = divmod(s, 3600)
m, s = divmod(r, 60)
return f"{h:02d}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"
def format_speed(bps: float) -> str:
if bps <= 0: return "Starting up..."
if bps < 1024: return f"{bps:.0f} B/s"
if bps < 1024**2: return f"{bps/1024:.1f} KB/s"
return f"{bps/1024**2:.1f} MB/s"
def build_progress_bar(done, total=100, width=10) -> str:
if not total or total <= 0:
dots = int((time.time() * 2) % (width + 1))
bar = "⬢" * dots + "⬡" * (width - dots)
else:
filled = min(width, floor(width * done / total))
bar = "⬢" * filled + "⬡" * (width - filled)
return f"[{bar}]"
def build_video_caption(info: dict | None) -> str:
if not info: return FILE_CAPTION_BASE
title = (info.get("title") or info.get("description") or "")[:80]
channel = info.get("uploader") or info.get("channel") or info.get("creator") or ""
handle = info.get("uploader_id") or info.get("channel_id") or ""
views = info.get("view_count") or 0
dur = info.get("duration") or 0
likes = info.get("like_count") or 0
comments= info.get("comment_count") or 0
shares = info.get("repost_count") or 0
subs = info.get("channel_follower_count") or info.get("uploader_follower_count") or 0
cats = info.get("categories") or []
cat = cats[0] if cats else ""
ud = info.get("upload_date") or ""
if ud and len(ud) == 8: ud = f"{ud[:4]}-{ud[4:6]}-{ud[6:]}"
lines = []
if title: lines.append(f"🎬 {title} →")
if channel: lines.append(f"👤 {channel}")
if handle and handle != channel: lines.append(f"@{handle.lstrip('@')} ✓ →")
if subs: lines.append(f"👥 {subs:,}")
if dur: lines.append(f"🕐 {format_duration(int(dur))}")
sp = []
if views: sp.append(f"👁 {views:,}")
if likes: sp.append(f"👍 {likes:,}")
if comments: sp.append(f"💬 {comments:,}")
if shares: sp.append(f"🔁 {shares:,}")
if sp: lines.append(" | ".join(sp))
if cat: lines.append(f"🏷 {cat}")
if ud: lines.append(f"📅 {ud}")
lines += ["", FILE_CAPTION_BASE]
return "\n".join(lines)
def build_welcome_text(first_name) -> str:
name = (first_name or "there").strip()
return (
f"🤝 Hello {name}\n\n"
"📥 I can help you download videos and images from:\n\n"
"▶️ YouTube 📷 Instagram 🎵 TikTok 📍 Pinterest\n"
"👻 Snapchat 💛 Likee 🔷 VK 💬 Facebook 🔘 Threads 🎶 Music\n\n"
"📋 <b>YouTube Playlist:</b> Playlist link bhejo, sari videos download!\n\n"
"🔍 <b>YouTube Search:</b> Song ya movie ka naam type karo\n"
" Example: <code>haseen dillruba song</code>\n\n"
"<i>(The bot also works in groups 👇)</i>"
)
def join_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[InlineKeyboardButton("Join Channel 📢", url=REQUIRED_CHANNEL_URL)],
[InlineKeyboardButton("I Joined ✅", callback_data="check_join")],
])
def welcome_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([[
InlineKeyboardButton("➕ Add to Group", url=f"https://t.me/{BOT_USERNAME}?startgroup=true")
]])
def parse_format_sizes(info: dict) -> dict[str, int]:
sizes: dict[str, int] = {}
formats = info.get("formats") or []
for fmt in formats:
h = fmt.get("height") or 0
if not h or h < 100: continue
if (fmt.get("vcodec") or "none").lower() == "none": continue
fs = fmt.get("filesize") or fmt.get("filesize_approx") or 0
lbl = f"{h}p"
if lbl not in sizes or fs > sizes[lbl]: sizes[lbl] = int(fs)
best_fs, best_abr = 0, 0.0
for fmt in formats:
if (fmt.get("vcodec") or "none").lower() != "none": continue
if (fmt.get("acodec") or "none").lower() == "none": continue
fs = fmt.get("filesize") or fmt.get("filesize_approx") or 0
abr = float(fmt.get("abr") or fmt.get("tbr") or 0)
if abr > best_abr or (abr == best_abr and fs > best_fs):
best_abr, best_fs = abr, int(fs)
if best_abr > 0 or best_fs > 0:
ai = int(best_abr)
albl = "MP3 320kbps" if ai >= 320 else "MP3 256kbps" if ai >= 256 else "MP3 192kbps" if ai >= 192 else "MP3 128kbps" if ai >= 128 else (f"MP3 {ai}kbps" if ai > 0 else "MP3")
sizes[albl] = best_fs
return sizes
def _sorted_video_heights(sizes: dict) -> list[str]:
lbls = [k for k in sizes if re.match(r"^\d+p$", k)]
lbls.sort(key=lambda x: int(x[:-1]), reverse=True)
return lbls
def _audio_labels(sizes: dict) -> list[str]:
return [k for k in sizes if k.startswith("MP3")]
def quality_keyboard(url_key: str, video_info=None) -> InlineKeyboardMarkup:
buttons = []
def _icon(h):
if h >= 4320: return "⭐"
if h >= 2160: return "🔵"
if h >= 1440: return "💎"
if h >= 1080: return "🖥"
if h >= 720: return "📺"
if h >= 480: return "📱"
if h >= 360: return "📉"
return "🔹"
def _qlabel(h):
m = {4320:"4320p (8K)",2160:"2160p (4K)",1440:"1440p (2K)",
1080:"1080p (FHD)",720:"720p (HD)",480:"480p (SD)",360:"360p",240:"240p",144:"144p (Lowest)"}
return m.get(h, f"{h}p")
if video_info:
sizes = parse_format_sizes(video_info)
vheights = _sorted_video_heights(sizes)
alabels = _audio_labels(sizes)
if vheights or alabels:
buttons.append([InlineKeyboardButton("🔥 Best Quality", callback_data=f"q|best|{url_key}")])
for lbl in vheights:
h = int(lbl[:-1])
cb = f"q|{lbl}|{url_key}"
if len(cb.encode()) > 64: continue
fs = sizes.get(lbl, 0)
warn = " ⚠️" if fs > TG_MAX_FILE_SIZE else ""
sz = f" ({format_size(fs)})" if fs else ""
buttons.append([InlineKeyboardButton(f"{_icon(h)} {_qlabel(h)}{sz}{warn}", callback_data=cb)])
for albl in alabels:
cb = f"q|audio_only|{url_key}"
if len(cb.encode()) > 64: continue
fs = sizes.get(albl, 0)
sz = f" ({format_size(fs)})" if fs else ""
buttons.append([InlineKeyboardButton(f"🎵 {albl}{sz}", callback_data=cb)])
if not alabels:
buttons.append([InlineKeyboardButton("🎵 Audio Only (MP3)", callback_data=f"q|audio_only|{url_key}")])
if not vheights:
buttons[0] = [InlineKeyboardButton("🔥 Best Quality (Audio)", callback_data=f"q|best|{url_key}")]
else:
_static_quality_buttons(buttons, url_key)
else:
_static_quality_buttons(buttons, url_key)
buttons.append([
InlineKeyboardButton("🖼 Thumbnail", callback_data=f"thumb|{url_key}"),
InlineKeyboardButton("📝 Description", callback_data=f"desc|{url_key}"),
])
return InlineKeyboardMarkup(buttons)
def _static_quality_buttons(buttons, url_key):
for label, q in [
("🔥 Best Quality","best"),("🖥 1080p (FHD)","1080p"),("📺 720p (HD)","720p"),
("📱 480p (SD)","480p"),("📉 360p","360p"),("🔹 240p","240p"),("🔹 144p","144p"),
]:
cb = f"q|{q}|{url_key}"
if len(cb.encode()) <= 64:
buttons.append([InlineKeyboardButton(label, callback_data=cb)])
buttons.append([InlineKeyboardButton("🎵 Audio Only (MP3)", callback_data=f"q|audio_only|{url_key}")])
def search_results_keyboard(results, search_key, page=0, has_prev=False) -> InlineKeyboardMarkup:
buttons = []
row1 = [InlineKeyboardButton(str(i), callback_data=f"sr|{i-1}|{search_key}") for i in range(1, min(6, len(results)+1))]
row2 = [InlineKeyboardButton(str(i), callback_data=f"sr|{i-1}|{search_key}") for i in range(6, min(11, len(results)+1))]
if row1: buttons.append(row1)
if row2: buttons.append(row2)
nav = []
if has_prev: nav.append(InlineKeyboardButton("⬅️", callback_data=f"sr_page|{page}|prev|{search_key}"))
nav.append(InlineKeyboardButton("➡️", callback_data=f"sr_page|{page}|next|{search_key}"))
buttons.append(nav)
buttons.append([InlineKeyboardButton("❌ Cancel", callback_data="sr_cancel")])
return InlineKeyboardMarkup(buttons)
def playlist_keyboard(playlist_key) -> InlineKeyboardMarkup:
rows = [
("🔥 Best Quality (All)", "best"), ("🖥 1080p", "1080p"),
("📺 720p", "720p"), ("📱 480p", "480p"), ("📉 360p", "360p"),
("🎵 Audio Only MP3", "audio_only"), ("❌ Cancel", None),
]
buttons = []
for label, q in rows:
if q is None:
buttons.append([InlineKeyboardButton(label, callback_data="pl_cancel")])
else:
cb = f"pl|{q}|{playlist_key}"
if len(cb.encode()) <= 64:
buttons.append([InlineKeyboardButton(label, callback_data=cb)])
return InlineKeyboardMarkup(buttons)
def media_priority(path: Path):
ext = path.suffix.lower()
if ext in VIDEO_EXTS: return (0, path.name)
if ext in IMAGE_EXTS: return (1, path.name)
if ext in AUDIO_EXTS: return (2, path.name)
return (3, path.name)
def collect_media_files(root: Path) -> list[Path]:
all_exts = IMAGE_EXTS | VIDEO_EXTS | AUDIO_EXTS
files = [p for p in root.rglob("*") if p.is_file() and p.suffix.lower() in all_exts]
files.sort(key=media_priority)
return files
def build_gallery_dl_command(url, temp_dir, platform) -> list:
cmd = ["gallery-dl", "--directory", str(temp_dir), "--no-mtime", "--retries", "3", "--timeout", "30"]
if platform == "pinterest":
cmd += ["--config-option", "extractor.pinterest.videos=true",
"--config-option", "extractor.pinterest.video-format=best"]
cmd.append(url)
cmap = {"instagram": INSTAGRAM_COOKIE_FILE, "facebook": FACEBOOK_COOKIE_FILE,
"tiktok": TIKTOK_COOKIE_FILE, "youtube": YOUTUBE_COOKIE_FILE}
cf = cmap.get(platform)
if cf:
cp = BASE_DIR / cf
if cp.exists(): cmd[1:1] = ["--cookies", str(cp)]
return cmd
def _make_format_string(quality: str) -> str:
if quality == "audio_only":
return "bestaudio/best"
if quality == "best":
return ("bestvideo[ext=mp4][vcodec^=avc1]+bestaudio[ext=m4a]"
"/bestvideo[ext=mp4][vcodec^=avc1]+bestaudio"
"/bestvideo[ext=mp4]+bestaudio[ext=m4a]"
"/bestvideo[ext=mp4]+bestaudio/bestvideo+bestaudio/best[ext=mp4]/best")
if re.match(r"^\d+p$", quality):
h = quality[:-1]
return (f"bestvideo[height<={h}][ext=mp4][vcodec^=avc1]+bestaudio[ext=m4a]"
f"/bestvideo[height<={h}][ext=mp4][vcodec^=avc1]+bestaudio"
f"/bestvideo[height<={h}][ext=mp4]+bestaudio"
f"/bestvideo[height<={h}]+bestaudio/best[height<={h}][ext=mp4]"
f"/best[height<={h}]/bestvideo[ext=mp4]+bestaudio/bestvideo+bestaudio/best")
return "bestvideo[ext=mp4][vcodec^=avc1]+bestaudio[ext=m4a]/bestvideo[ext=mp4]+bestaudio/bestvideo+bestaudio/best"
def build_ytdlp_command(url, temp_dir, platform, quality="best") -> list:
out = str(temp_dir / "%(title).50s.%(ext)s")
flags_map = {
"youtube": ["--extractor-args","youtube:player_client=ios,web,android_vr,tv_embedded",
"--no-check-certificates","--retries","5","--fragment-retries","10",
"--retry-sleep","exp=2","--socket-timeout","60","--concurrent-fragments","4",
"--sleep-interval","1","--max-sleep-interval","3",
"--add-header","User-Agent:com.google.ios.youtube/19.45.4 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)",
"--no-playlist"],
"facebook": ["--no-check-certificates","--retries","10","--fragment-retries","10",
"--retry-sleep","3","--socket-timeout","60","--buffer-size","16K",
"--add-header","User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
"--add-header","Accept-Language:en-US,en;q=0.9"],
"instagram":["--no-check-certificates","--retries","5","--socket-timeout","60",
"--add-header","User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
"--add-header","Accept-Language:en-US,en;q=0.9"],
"tiktok": ["--no-check-certificates","--impersonate","chrome","--retries","5","--socket-timeout","60",
"--add-header","Accept-Language:en-US,en;q=0.9","--add-header","Referer:https://www.tiktok.com/"],
"threads": ["--no-check-certificates","--retries","5","--socket-timeout","60",
"--add-header","User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1"],
}
flags = flags_map.get(platform, ["--no-check-certificates","--retries","5","--socket-timeout","60"])
if platform in {"vk","snapchat","likee"}:
flags = ["--no-check-certificates","--retries","5","--socket-timeout","60",
"--add-header","User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"]
fmt = _make_format_string(quality)
if quality == "audio_only":
cmd = ["yt-dlp",*flags,"--format",fmt,"--extract-audio","--audio-format","mp3","--audio-quality","0","-o",out,url]
else:
cmd = ["yt-dlp",*flags,"--format",fmt,"--merge-output-format","mp4","--postprocessor-args","ffmpeg:-c:v copy -c:a aac","-o",out,url]
cmap = {"youtube": YOUTUBE_COOKIE_FILE, "facebook": FACEBOOK_COOKIE_FILE,
"instagram": INSTAGRAM_COOKIE_FILE, "tiktok": TIKTOK_COOKIE_FILE, "music": SPOTIFY_COOKIE_FILE}
cf = cmap.get(platform)
if cf:
cp = BASE_DIR / cf
if cp.exists(): cmd[1:1] = ["--cookies", str(cp)]
return cmd
def build_ytdlp_playlist_command(url, temp_dir, quality="best") -> list:
out = str(temp_dir / "%(playlist_index)s - %(title).50s.%(ext)s")
fmt = _make_format_string(quality)
base = ["yt-dlp","--extractor-args","youtube:player_client=ios,web,android_vr,tv_embedded",
"--no-check-certificates","--retries","5","--fragment-retries","10","--retry-sleep","exp=2",
"--socket-timeout","60","--concurrent-fragments","4",
"--add-header","User-Agent:com.google.ios.youtube/19.45.4 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)",
"--yes-playlist"]
if quality == "audio_only":
cmd = [*base,"--format",fmt,"--extract-audio","--audio-format","mp3","--audio-quality","0","-o",out,url]
else:
cmd = [*base,"--format",fmt,"--merge-output-format","mp4","--postprocessor-args","ffmpeg:-c:v copy -c:a aac","-o",out,url]
cf = BASE_DIR / YOUTUBE_COOKIE_FILE
if cf.exists(): cmd[1:1] = ["--cookies", str(cf)]
return cmd
def build_ytdlp_info_command(url, platform) -> list:
flags_map = {
"youtube": ["--extractor-args","youtube:player_client=ios,web,android_vr,tv_embedded",
"--no-check-certificates","--socket-timeout","30",
"--add-header","User-Agent:com.google.ios.youtube/19.45.4 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)",
"--no-playlist"],
"facebook": ["--no-check-certificates","--socket-timeout","30",
"--add-header","User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
"--add-header","Accept-Language:en-US,en;q=0.9","--add-header","Referer:https://www.facebook.com/"],
"instagram":["--no-check-certificates","--socket-timeout","30",
"--add-header","User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
"--add-header","Accept-Language:en-US,en;q=0.9"],
"tiktok": ["--no-check-certificates","--impersonate","chrome","--socket-timeout","30",
"--add-header","Accept-Language:en-US,en;q=0.9","--add-header","Referer:https://www.tiktok.com/"],
"threads": ["--no-check-certificates","--socket-timeout","30",
"--add-header","User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1"],
}
flags = flags_map.get(platform, ["--no-check-certificates"])
if platform in {"vk","snapchat","likee","pinterest"}:
flags = ["--no-check-certificates","--add-header","User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"]
cmd = ["yt-dlp",*flags,"--dump-json","--no-playlist",url]
cmap = {"youtube": YOUTUBE_COOKIE_FILE, "facebook": FACEBOOK_COOKIE_FILE,
"instagram": INSTAGRAM_COOKIE_FILE, "tiktok": TIKTOK_COOKIE_FILE, "music": SPOTIFY_COOKIE_FILE}
cf = cmap.get(platform)
if cf:
cp = BASE_DIR / cf
if cp.exists(): cmd[1:1] = ["--cookies", str(cp)]
return cmd
def build_ytdlp_playlist_info_command(url) -> list:
cmd = ["yt-dlp","--extractor-args","youtube:player_client=ios,web,android_vr,tv_embedded",
"--no-check-certificates","--socket-timeout","30",
"--add-header","User-Agent:com.google.ios.youtube/19.45.4 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)",
"--yes-playlist","--flat-playlist","--dump-json",url]
cf = BASE_DIR / YOUTUBE_COOKIE_FILE
if cf.exists(): cmd[1:1] = ["--cookies", str(cf)]
return cmd
def safe_remove_tree(path):
if not path: return
try:
if path.exists(): shutil.rmtree(path, ignore_errors=True)
except Exception as e:
logger.warning("Could not delete temp folder %s: %s", path, e)
async def safe_edit_text(message, text: str, reply_markup=None):
try:
await message.edit_text(text, reply_markup=reply_markup, parse_mode="HTML")
except Exception:
pass
async def is_user_joined(context, user_id) -> bool:
try:
member = await context.bot.get_chat_member(chat_id=REQUIRED_CHANNEL_USERNAME, user_id=user_id)
return getattr(member, "status", "") not in {"left", "kicked", "banned"}
except Exception as e:
logger.warning("Could not verify membership: %s", e)
return False
async def require_join(update, context, pending_action) -> bool:
user = update.effective_user
if not user: return True
if await is_user_joined(context, user.id): return False
context.user_data["pending_action"] = pending_action
text = f"You must join our channel first.\n\nChannel: {REQUIRED_CHANNEL_USERNAME}"
if update.callback_query:
await update.callback_query.answer()
try: await update.callback_query.message.reply_text(text, reply_markup=join_keyboard())
except Exception: pass
else:
msg = update.effective_message
if msg: await msg.reply_text(text, reply_markup=join_keyboard())
return True
async def notify_admin_new_user(context, user):
if not ADMIN_USER_ID: return
try:
username = f"@{user.username}" if user.username else "No username"
full_name = " ".join(p for p in [user.first_name or "", user.last_name or ""] if p).strip() or "No name"
await context.bot.send_message(
chat_id=ADMIN_USER_ID,
text=f"👤 New user joined\n\nName: {full_name}\nUsername: {username}\nUser ID: {user.id}",
)
except Exception as e:
logger.warning("Could not notify admin: %s", e)
async def register_user_and_notify(update, context):
user = update.effective_user
if not user: return
is_new = await stats_store.register_user(user)
if is_new: await notify_admin_new_user(context, user)
# =========================
# YouTube Search
# =========================
async def _search_youtube_via_api(query, max_results=10, page=0) -> list:
if not YOUTUBE_API_KEY: return []
try:
params = {"part":"snippet","q":query,"type":"video","maxResults":max_results,"key":YOUTUBE_API_KEY}
async with aiohttp.ClientSession() as s:
async with s.get("https://www.googleapis.com/youtube/v3/search", params=params, timeout=aiohttp.ClientTimeout(total=15)) as resp:
if resp.status != 200: return []
data = await resp.json()
items = data.get("items", [])
video_ids = [i.get("id",{}).get("videoId","") for i in items if i.get("id",{}).get("videoId")]
durations = {}
if video_ids:
vp = {"part":"contentDetails","id":",".join(video_ids),"key":YOUTUBE_API_KEY}
async with aiohttp.ClientSession() as s:
async with s.get("https://www.googleapis.com/youtube/v3/videos", params=vp, timeout=aiohttp.ClientTimeout(total=15)) as r2:
if r2.status == 200:
vd = await r2.json()
for v in vd.get("items",[]):
iso = v.get("contentDetails",{}).get("duration","PT0S")
h = int((re.search(r"(\d+)H",iso) or re.Match()).group(1)) if re.search(r"(\d+)H",iso) else 0
m = int((re.search(r"(\d+)M",iso) or re.Match()).group(1)) if re.search(r"(\d+)M",iso) else 0
sec = int((re.search(r"(\d+)S",iso) or re.Match()).group(1)) if re.search(r"(\d+)S",iso) else 0
durations[v.get("id","")] = h*3600+m*60+sec
results = []
for item in items:
sn = item.get("snippet",{}); vid = item.get("id",{}).get("videoId","")
if not vid: continue
results.append({"title":sn.get("title","Unknown"),"duration":durations.get(vid,0),
"channel":sn.get("channelTitle",""),"url":f"https://www.youtube.com/watch?v={vid}","views":0,"id":vid})
return results
except Exception as e:
logger.error("YouTube API search error: %s", e)
return []
async def search_youtube(query, max_results=10, page=0) -> list:
search_url = f"ytsearch{max_results*(page+1)}:{query}"
cmd = ["yt-dlp","--extractor-args","youtube:player_client=ios,web,android_vr",
"--no-check-certificates","--dump-json","--no-playlist","--flat-playlist",
"--add-header","User-Agent:com.google.ios.youtube/19.45.4 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)",
search_url]
cp = BASE_DIR / YOUTUBE_COOKIE_FILE
if cp.exists(): cmd[1:1] = ["--cookies", str(cp)]
try:
proc = await asyncio.create_subprocess_exec(*cmd, cwd=str(BASE_DIR),
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=40)
results = []
if stdout:
for line in stdout.decode(errors="replace").strip().split("\n"):
line = line.strip()
if not line: continue
try:
d = json.loads(line)
vid = d.get("id","")
url = d.get("url") or d.get("webpage_url") or (f"https://www.youtube.com/watch?v={vid}" if vid else "")
if not url: continue
results.append({"title":d.get("title","Unknown"),"duration":d.get("duration",0),
"channel":d.get("channel") or d.get("uploader",""),
"url":url,"views":d.get("view_count",0),"id":vid})
except Exception: continue
if results:
start = page * max_results
paged = results[start:start+max_results]
return paged if paged else results[:max_results]
return await _search_youtube_via_api(query, max_results, page)
except asyncio.TimeoutError:
return await _search_youtube_via_api(query, max_results, page)
except Exception as e:
logger.error("YouTube search error: %s", e)
return await _search_youtube_via_api(query, max_results, page)
def build_search_results_text(query, results, page=0) -> str:
if not results:
return f"❌ <b>No results found for:</b> <code>{query}</code>\n\nPlease try a different search term."
pl = f" — Page {page+1}" if page > 0 else ""
lines = [f"🔍 Search results: <b>{query}</b>{pl}\n"]
for i, r in enumerate(results, 1):
lines.append(f"{i}. {r['title']}")
lines.append("\n👇 <i>Number button dabao download ke liye</i>")
return "\n".join(lines)
# =========================
# Video Info
# =========================
async def fetch_video_info(url, platform) -> dict | None:
tmap = {"instagram":60,"facebook":60,"tiktok":45,"youtube":50,"threads":45,"vk":45,"snapchat":45,"likee":45,"pinterest":45}
timeout = tmap.get(platform, 45)
def _fix_thumb(info):
thumb = info.get("thumbnail") or ""
if not thumb or not str(thumb).startswith("http"):
thumbs = info.get("thumbnails") or []
valid = [t for t in thumbs if isinstance(t,dict) and str(t.get("url","")).startswith("http")]
if valid:
best = max(valid, key=lambda t:(t.get("width",0))*(t.get("height",0)))
info["thumbnail"] = best["url"]
return info
try:
cmd = build_ytdlp_info_command(url, platform)
proc = await asyncio.create_subprocess_exec(*cmd, cwd=str(BASE_DIR),
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
if proc.returncode == 0 and stdout:
info = json.loads(stdout.decode(errors="replace").strip().split("\n")[0])
return _fix_thumb(info)
if platform == "youtube":
fb = ["yt-dlp","--extractor-args","youtube:player_client=web,android_vr",
"--no-check-certificates","--socket-timeout","30","--no-playlist","--dump-json",url]
cp = BASE_DIR / YOUTUBE_COOKIE_FILE
if cp.exists(): fb[1:1] = ["--cookies",str(cp)]
p2 = await asyncio.create_subprocess_exec(*fb, cwd=str(BASE_DIR),
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
s2, _ = await asyncio.wait_for(p2.communicate(), timeout=40)
if p2.returncode == 0 and s2:
return _fix_thumb(json.loads(s2.decode(errors="replace").strip().split("\n")[0]))
if platform in ("instagram","pinterest"):
if platform == "pinterest":
try:
gp = await asyncio.create_subprocess_exec(
"gallery-dl","--no-mtime","--print","json",
"--config-option","extractor.pinterest.videos=true",url,
cwd=str(BASE_DIR), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
go, _ = await asyncio.wait_for(gp.communicate(), timeout=30)
if go:
for line in go.decode(errors="replace").strip().split("\n"):
line = line.strip()
if not line: continue
try:
gd = json.loads(line)
item = gd[2] if isinstance(gd,list) and len(gd)>=3 else (gd if isinstance(gd,dict) else None)
if not item: continue
return _fix_thumb({"title":(item.get("title") or item.get("description") or "Pinterest Video")[:80],
"thumbnail":item.get("thumbnail") or item.get("image_url",""),
"duration":item.get("duration",0),"formats":[],"webpage_url":url})
except Exception: continue
except Exception: pass
return None
except asyncio.TimeoutError:
logger.warning("fetch_video_info timeout for %s/%s", platform, url[:60])
except Exception as e:
logger.warning("fetch_video_info error for %s: %s", platform, e)
return None
async def fetch_playlist_info(url) -> tuple[list, str]:
cmd = build_ytdlp_playlist_info_command(url)
try:
proc = await asyncio.create_subprocess_exec(*cmd, cwd=str(BASE_DIR),
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=60)
videos, title = [], ""
if stdout:
for line in stdout.decode(errors="replace").strip().split("\n"):
line = line.strip()
if not line: continue
try:
d = json.loads(line)
if not title: title = d.get("playlist_title") or d.get("playlist","")
vid = d.get("id","")
url_v = d.get("url") or d.get("webpage_url") or (f"https://www.youtube.com/watch?v={vid}" if vid else "")
if url_v:
videos.append({"id":vid,"title":d.get("title","Unknown"),"url":url_v,"duration":d.get("duration",0)})
except Exception: continue
return videos, title
except Exception: return [], ""
def build_info_message(info, platform, sizes) -> str:
title = (info.get("title") or "Unknown Title")[:80]
channel = info.get("uploader") or info.get("channel","")
handle = info.get("uploader_id") or info.get("channel_id","")
views = info.get("view_count",0) or 0
dur = info.get("duration",0) or 0
likes = info.get("like_count",0) or 0
comments= info.get("comment_count",0) or 0
cats = info.get("categories",[]) or []
cat = cats[0] if cats else ""
ud = info.get("upload_date","")
if ud and len(ud)==8: ud = f"{ud[:4]}-{ud[4:6]}-{ud[6:]}"
lines = [f"🎬 <b>{title}</b> →"]
if channel: lines.append(f"👤 {channel}")
if handle and handle != channel: lines.append(f"@{handle.lstrip('@')} ✓ →")
if views: lines.append(f"👥 {views:,}")
if dur: lines.append(f"⏱ {format_duration(int(dur))}")
sp = []
if views: sp.append(f"👁 {views:,}")
if likes: sp.append(f"👍 {likes:,}")
if comments: sp.append(f"💬 {comments:,}")
if sp: lines.append(" | ".join(sp))
if cat: lines.append(f"🏷 {cat}")
if ud: lines.append(f"📅 {ud}")
if sizes:
lines.append("")
for q in _sorted_video_heights(sizes) + _audio_labels(sizes):
if q in sizes: