Spaces:
Sleeping
Sleeping
feat(download): dự phòng TikTok qua tikwm (giống SnapTik) — video + slideshow
Browse filesyt-dlp nay hay chỉ bóc được audio cho TikTok (bị chặn extraction) -> báo "không
phải video" dù link CÓ video. Thêm _tiktok_via_tikwm: khi yt-dlp fail, gọi API
công cộng tikwm lấy link video no-watermark (hdplay/play) rồi tải thẳng. Bài
ẢNH/SLIDESHOW (images + music) -> tải ảnh + nhạc rồi ffmpeg ghép thành mp4 khung
dọc (giống SnapTik dựng slideshow). Nối vào download_one như 1 fallback cho
source=tiktok. Test thật: link trước đó (yt-dlp ra audio) giờ ra video 1080x1920.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
backend/app/services/downloader/ydl.py
CHANGED
|
@@ -426,6 +426,94 @@ def _youtube_via_public(url: str, out_dir: str) -> DownloadResult:
|
|
| 426 |
raise RuntimeError("Invidious/Piped đều thất bại (" + " | ".join(errs[:3]) + ")")
|
| 427 |
|
| 428 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
def download_one(url: str, out_dir: str, cookies_file: str | None = None) -> DownloadResult:
|
| 430 |
try:
|
| 431 |
import yt_dlp # noqa: F401 # type: ignore
|
|
@@ -465,6 +553,14 @@ def download_one(url: str, out_dir: str, cookies_file: str | None = None) -> Dow
|
|
| 465 |
except Exception as e2:
|
| 466 |
return DownloadResult(url=url, ok=False,
|
| 467 |
error=clean_error(f"{source}: {e2}"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
# YouTube bị chặn (IP datacenter) -> lưới an toàn: thử Invidious/Piped.
|
| 469 |
if source == "youtube":
|
| 470 |
try:
|
|
|
|
| 426 |
raise RuntimeError("Invidious/Piped đều thất bại (" + " | ".join(errs[:3]) + ")")
|
| 427 |
|
| 428 |
|
| 429 |
+
def _tiktok_via_tikwm(url: str, out_dir: str) -> DownloadResult:
|
| 430 |
+
"""Dự phòng TikTok qua API công cộng tikwm (giống SnapTik).
|
| 431 |
+
|
| 432 |
+
yt-dlp nay hay chỉ bóc được audio (TikTok chặn extraction) -> lấy link video
|
| 433 |
+
no-watermark qua tikwm. Bài ẢNH/SLIDESHOW -> tải ảnh + nhạc rồi ffmpeg ghép
|
| 434 |
+
thành mp4 khung dọc (giống SnapTik dựng slideshow).
|
| 435 |
+
"""
|
| 436 |
+
import shutil as _sh
|
| 437 |
+
import subprocess
|
| 438 |
+
import tempfile
|
| 439 |
+
|
| 440 |
+
import requests # type: ignore
|
| 441 |
+
|
| 442 |
+
ffmpeg = _sh.which("ffmpeg") or "ffmpeg"
|
| 443 |
+
headers = {"User-Agent": _UA_MOBILE, "Referer": "https://www.tikwm.com/"}
|
| 444 |
+
r = requests.get("https://www.tikwm.com/api/", params={"url": url, "hd": 1},
|
| 445 |
+
timeout=25, headers={"User-Agent": _UA_MOBILE})
|
| 446 |
+
r.raise_for_status()
|
| 447 |
+
j = r.json()
|
| 448 |
+
if j.get("code") != 0:
|
| 449 |
+
raise RuntimeError(f"tikwm báo lỗi: {j.get('msg')}")
|
| 450 |
+
d = j.get("data") or {}
|
| 451 |
+
title = (d.get("title") or "").strip()
|
| 452 |
+
m = re.search(r"/(?:video|photo)/(\d+)", url) or re.search(r"(\d{6,})", url)
|
| 453 |
+
vid_id = str(d.get("id") or (m.group(1) if m else "tiktok"))
|
| 454 |
+
safe = re.sub(r'[\\/:*?"<>|\n\r\t]+', "_", title)[:60].strip() or vid_id
|
| 455 |
+
|
| 456 |
+
def _abs(u: str) -> str:
|
| 457 |
+
u = u or ""
|
| 458 |
+
return u if u.startswith("http") else ("https://www.tikwm.com" + u if u else "")
|
| 459 |
+
|
| 460 |
+
out = os.path.join(out_dir, f"{safe} [{vid_id}].mp4")
|
| 461 |
+
images = d.get("images") or []
|
| 462 |
+
dur = float(d.get("duration") or 0)
|
| 463 |
+
|
| 464 |
+
if images:
|
| 465 |
+
# SLIDESHOW: tải ảnh + nhạc -> ghép mp4 khung dọc, chia đều thời gian.
|
| 466 |
+
tmp = tempfile.mkdtemp(dir=out_dir)
|
| 467 |
+
img_paths = []
|
| 468 |
+
for i, im in enumerate(images):
|
| 469 |
+
ir = requests.get(_abs(im), timeout=30, headers=headers)
|
| 470 |
+
ir.raise_for_status()
|
| 471 |
+
ip = os.path.join(tmp, f"img_{i:03d}.jpg")
|
| 472 |
+
with open(ip, "wb") as f:
|
| 473 |
+
f.write(ir.content)
|
| 474 |
+
img_paths.append(ip)
|
| 475 |
+
music = os.path.join(tmp, "music.mp3")
|
| 476 |
+
murl = _abs(d.get("music") or "")
|
| 477 |
+
if murl:
|
| 478 |
+
try:
|
| 479 |
+
mr = requests.get(murl, timeout=30, headers=headers)
|
| 480 |
+
with open(music, "wb") as f:
|
| 481 |
+
f.write(mr.content)
|
| 482 |
+
except Exception:
|
| 483 |
+
music = ""
|
| 484 |
+
else:
|
| 485 |
+
music = ""
|
| 486 |
+
per = max(1.0, (dur or len(img_paths) * 3.0) / len(img_paths))
|
| 487 |
+
listf = os.path.join(tmp, "list.txt")
|
| 488 |
+
with open(listf, "w", encoding="utf-8") as f:
|
| 489 |
+
for p in img_paths:
|
| 490 |
+
f.write(f"file '{p.replace(chr(92), '/')}'\nduration {per:.3f}\n")
|
| 491 |
+
f.write(f"file '{img_paths[-1].replace(chr(92), '/')}'\n") # concat demuxer cần lặp ảnh cuối
|
| 492 |
+
vf = ("scale=1080:1920:force_original_aspect_ratio=decrease,"
|
| 493 |
+
"pad=1080:1920:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=30,format=yuv420p")
|
| 494 |
+
cmd = [ffmpeg, "-y", "-hide_banner", "-loglevel", "error",
|
| 495 |
+
"-f", "concat", "-safe", "0", "-i", listf]
|
| 496 |
+
if music:
|
| 497 |
+
cmd += ["-i", music, "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-shortest"]
|
| 498 |
+
cmd += ["-vf", vf, "-c:v", "libx264", "-preset", "veryfast", "-crf", "20",
|
| 499 |
+
"-movflags", "+faststart", out]
|
| 500 |
+
subprocess.run(cmd, check=True, capture_output=True)
|
| 501 |
+
else:
|
| 502 |
+
vurl = _abs(d.get("hdplay") or d.get("play") or "")
|
| 503 |
+
if not vurl:
|
| 504 |
+
raise RuntimeError("tikwm không trả link video")
|
| 505 |
+
vr = requests.get(vurl, timeout=90, headers=headers)
|
| 506 |
+
vr.raise_for_status()
|
| 507 |
+
with open(out, "wb") as f:
|
| 508 |
+
f.write(vr.content)
|
| 509 |
+
|
| 510 |
+
if not _has_video_stream(out):
|
| 511 |
+
raise RuntimeError("tikwm: file tải về không phải video xem được")
|
| 512 |
+
return DownloadResult(
|
| 513 |
+
url=url, ok=True, path=out, title=title or safe, ext="mp4",
|
| 514 |
+
size=os.path.getsize(out), duration=dur, thumbnail=d.get("cover") or "")
|
| 515 |
+
|
| 516 |
+
|
| 517 |
def download_one(url: str, out_dir: str, cookies_file: str | None = None) -> DownloadResult:
|
| 518 |
try:
|
| 519 |
import yt_dlp # noqa: F401 # type: ignore
|
|
|
|
| 553 |
except Exception as e2:
|
| 554 |
return DownloadResult(url=url, ok=False,
|
| 555 |
error=clean_error(f"{source}: {e2}"))
|
| 556 |
+
# TikTok: yt-dlp hay chỉ bóc audio -> dự phòng qua tikwm (giống SnapTik):
|
| 557 |
+
# lấy video no-watermark, hoặc ghép slideshow ảnh+nhạc thành mp4.
|
| 558 |
+
if source == "tiktok":
|
| 559 |
+
try:
|
| 560 |
+
return _tiktok_via_tikwm(url, out_dir)
|
| 561 |
+
except Exception as e_tk:
|
| 562 |
+
return DownloadResult(url=url, ok=False,
|
| 563 |
+
error=clean_error(f"{first_err} | tikwm: {e_tk}"))
|
| 564 |
# YouTube bị chặn (IP datacenter) -> lưới an toàn: thử Invidious/Piped.
|
| 565 |
if source == "youtube":
|
| 566 |
try:
|