Files
TikDown/downloader.py
X4Lo d12483d53c Add profile downloader with web UI; optional cookies for downloader
Profile downloader (profile-downloader/), now built on gallery-dl:
- Local web UI (app.py): load a profile by username, URL, post link or
  secUid; stories shown above posts; select all/none/not downloaded,
  shift-click ranges, filters; live download progress with Stop
- CLI (main.py) replaces the hard-coded script: --cookies, --refresh,
  --retry-failed, --limit, --no-stories
- Photo posts save their slide images and music; cover thumbnails are
  no longer saved; filenames include seconds and the post ID so posts
  from the same minute cannot collide; partial files are cleaned up
- Backoff and retry when TikTok blocks requests, stopping after three
  blocked posts in a row; per-profile failed.txt
- Profile IDs are cached and looked up from a post page when the
  profile page is blocked; photo posts download straight from the
  post-list links
- README for the profile downloader

downloader.py:
- Optional --cookies FILE (or TIKDOWN_COOKIES)
- Failed-URL helpers accept a file path so the profile tool reuses them

Ignore cookies.txt and __pycache__ in every folder.
2026-11-22 03:57:49 +00:00

402 lines
14 KiB
Python

"""
TikTok downloader powered by yt-dlp.
Used both as a CLI (``python downloader.py <url|file> ...``) and as a library
by ``bot.py`` (download_video, extract_tiktok_id, load_downloaded_ids,
save_downloaded_id, log_failed_url).
"""
import argparse
import logging
import os
import re
import shutil
import subprocess
import sys
import threading
import time
from dataclasses import dataclass, field
from typing import Iterable, List, Optional
from urllib.parse import urlparse, urlunparse
try: # Optional: lets .env override the settings below
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
logger = logging.getLogger(__name__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def _default_yt_dlp() -> str:
for name in ("yt-dlp.exe", "yt-dlp"):
candidate = os.path.join(BASE_DIR, name)
if os.path.isfile(candidate):
return candidate
return shutil.which("yt-dlp") or "yt-dlp"
# --- Configuration (each value can be overridden by an environment variable) ---
YT_DLP_PATH = os.getenv("YT_DLP_PATH") or _default_yt_dlp()
DOWNLOAD_DIR = os.getenv("TIKDOWN_DOWNLOAD_DIR") or os.path.join(BASE_DIR, "downloads")
DOWNLOADED_IDS_FILE = os.path.join(BASE_DIR, "downloaded_ids.txt")
FAILED_FILE = os.path.join(BASE_DIR, "failed.txt")
COOKIES_FILE = os.getenv("TIKDOWN_COOKIES") # optional cookies.txt for private posts
DOWNLOAD_DELAY = float(os.getenv("TIKDOWN_DELAY", "1")) # seconds between downloads
DOWNLOAD_TIMEOUT = 600 # seconds before a single yt-dlp run is killed
# <upload date>_<id>_<uploader>_<uploader_id>.<ext> (same naming as before).
# yt-dlp fills and sanitizes the fields itself, so odd characters in
# nicknames can no longer break the path.
OUTPUT_TEMPLATE = "%(upload_date>%Y-%m-%d|unknown-date)s_%(id)s_%(uploader)s_%(uploader_id)s.%(ext)s"
_PRINT_MARKER = "TIKDOWN_FILE"
_ID_RE = re.compile(r"/(?:video|photo)/(\d+)")
_URL_RE = re.compile(r"https?://[^\s<>\"']+")
_file_lock = threading.Lock()
class DownloadError(Exception):
"""Raised when yt-dlp fails; the message is short enough to show a user."""
@dataclass
class DownloadResult:
tiktok_id: Optional[str]
files: List[str] = field(default_factory=list)
# --- URL helpers ---
def _is_tiktok_host(netloc: str) -> bool:
host = netloc.lower().split(":")[0]
return host == "tiktok.com" or host.endswith(".tiktok.com")
def is_valid_tiktok_url(url: str) -> bool:
"""Accepts post URLs (/video/<id>, /photo/<id>) and short links (vm./vt.tiktok.com)."""
parsed = urlparse(url.strip())
if parsed.scheme not in ("http", "https") or not _is_tiktok_host(parsed.netloc):
return False
if _ID_RE.search(parsed.path):
return True
host = parsed.netloc.lower()
return host.startswith(("vm.", "vt.")) and len(parsed.path.strip("/")) > 0
def is_tiktok_photo_url(url: str) -> bool:
"""Checks if a TikTok URL points to a photo/slideshow post."""
return is_valid_tiktok_url(url) and "/photo/" in urlparse(url.strip()).path
def extract_tiktok_id(url: str) -> Optional[str]:
"""
Extracts the TikTok video/photo ID from a URL.
https://www.tiktok.com/@user/video/7500623452873723158 -> 7500623452873723158
https://www.tiktok.com/@user/photo/7500623452873723158 -> 7500623452873723158
Short links (vm.tiktok.com/...) return None; their ID is only known after download.
"""
match = _ID_RE.search(url)
return match.group(1) if match else None
def normalize_tiktok_url(url: str) -> str:
"""
Strips tracking query strings and rewrites /photo/ to /video/.
yt-dlp's TikTok extractor only matches /video/<id>; a /photo/<id> URL falls
through to the generic extractor and fails. Extraction only needs the ID.
"""
parsed = urlparse(url.strip())
path = re.sub(r"/photo/(\d+)", r"/video/\1", parsed.path)
return urlunparse((parsed.scheme, parsed.netloc, path, "", "", ""))
def extract_urls(lines: Iterable[str]) -> List[str]:
"""Pulls TikTok URLs out of free text, skipping blank lines and # comments."""
urls = []
for line in lines:
line = line.strip()
if not line or line.startswith("#"):
continue
for candidate in _URL_RE.findall(line):
candidate = candidate.rstrip(".,;)")
if is_valid_tiktok_url(candidate):
urls.append(candidate)
return urls
# --- Tracking files ---
def load_downloaded_ids() -> set:
"""Loads the set of already-downloaded TikTok IDs from disk."""
if not os.path.exists(DOWNLOADED_IDS_FILE):
return set()
with open(DOWNLOADED_IDS_FILE, "r", encoding="utf-8") as f:
return {line.strip() for line in f if line.strip()}
def save_downloaded_id(video_id: str) -> None:
"""Appends a TikTok ID to the downloaded-ids tracking file."""
with _file_lock, open(DOWNLOADED_IDS_FILE, "a", encoding="utf-8") as f:
f.write(video_id + "\n")
def read_failed_urls(path: Optional[str] = None) -> List[str]:
"""Returns the URLs listed in a failed-URLs file (failed.txt by default)."""
path = path or FAILED_FILE
if not os.path.exists(path):
return []
with open(path, "r", encoding="utf-8") as f:
return [line.strip() for line in f if line.strip()]
def log_failed_url(url: str, path: Optional[str] = None) -> None:
"""Records a failed URL in failed.txt (once; repeated failures are not duplicated)."""
url, path = url.strip(), path or FAILED_FILE
with _file_lock:
if url in read_failed_urls(path):
return
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
with open(path, "a", encoding="utf-8") as f:
f.write(url + "\n")
def clear_failed_urls(urls: Iterable[str], ids: Iterable[str] = (), path: Optional[str] = None) -> None:
"""Removes now-successful URLs (matched by URL or post ID) from failed.txt."""
urls, ids, path = {u.strip() for u in urls}, set(ids), path or FAILED_FILE
with _file_lock:
current = read_failed_urls(path)
kept = [u for u in current if u not in urls and extract_tiktok_id(u) not in ids]
if len(kept) == len(current):
return
with open(path, "w", encoding="utf-8") as f:
f.writelines(u + "\n" for u in kept)
# --- Downloading ---
def _yt_dlp_error(stderr: str) -> str:
"""Returns yt-dlp's last ERROR line, which is the useful part of its output."""
errors = [line.strip() for line in stderr.splitlines() if line.startswith("ERROR:")]
if errors:
message = errors[-1][len("ERROR:"):].strip()
# Drop yt-dlp's repeated "(caused by ...)" tail and curl doc links
message = re.split(r" \(caused by | See https?://", message)[0]
return message.rstrip(". ")
lines = [line.strip() for line in stderr.splitlines() if line.strip()]
return lines[-1] if lines else "yt-dlp failed with no output"
def _find_existing_files(tiktok_id: str) -> List[str]:
if not os.path.isdir(DOWNLOAD_DIR):
return []
return sorted(
entry.path
for entry in os.scandir(DOWNLOAD_DIR)
if entry.is_file() and f"_{tiktok_id}_" in entry.name and not entry.name.endswith(".part")
)
def download(url: str) -> DownloadResult:
"""
Downloads a TikTok post (video or photo post) with a single yt-dlp run.
yt-dlp prints the final path of every file it writes, so there is no
guessing from log lines or directory timestamps. Raises DownloadError.
"""
if not os.path.isfile(YT_DLP_PATH) and not shutil.which(YT_DLP_PATH):
raise DownloadError(f"yt-dlp not found at '{YT_DLP_PATH}' (set YT_DLP_PATH)")
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
cmd = [
YT_DLP_PATH,
"--no-check-certificate",
"--encoding", "utf-8",
"--no-simulate",
"--no-progress",
"--retries", "3",
"--extractor-retries", "3",
"--socket-timeout", "30",
"--format", "bv*+ba/b",
"--output", os.path.join(DOWNLOAD_DIR, OUTPUT_TEMPLATE),
"--print", f"after_move:{_PRINT_MARKER}\t%(id)s\t%(filepath)s",
]
if COOKIES_FILE:
cmd += ["--cookies", COOKIES_FILE]
cmd.append(normalize_tiktok_url(url))
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=DOWNLOAD_TIMEOUT,
)
except subprocess.TimeoutExpired:
raise DownloadError(f"yt-dlp timed out after {DOWNLOAD_TIMEOUT}s")
if result.returncode != 0:
logger.debug("yt-dlp stderr:\n%s", result.stderr)
raise DownloadError(_yt_dlp_error(result.stderr))
tiktok_id = extract_tiktok_id(url)
files = []
for line in result.stdout.splitlines():
parts = line.rstrip("\r").split("\t", 2)
if len(parts) == 3 and parts[0] == _PRINT_MARKER:
tiktok_id = parts[1] or tiktok_id
if os.path.isfile(parts[2]) and parts[2] not in files:
files.append(parts[2])
# Fallback for runs where yt-dlp skipped an already-present file
if not files and tiktok_id:
files = _find_existing_files(tiktok_id)
if not files:
logger.debug("yt-dlp output:\n%s\n%s", result.stdout, result.stderr)
raise DownloadError("yt-dlp finished but no downloaded file was found")
return DownloadResult(tiktok_id=tiktok_id, files=files)
def download_video(url: str) -> str:
"""Downloads a TikTok post and returns the path of its main media file."""
return download(url).files[0]
def download_photo(url: str) -> List[str]:
"""Downloads a TikTok photo post and returns all file paths."""
return download(url).files
def process_urls(urls: Iterable[str], delay: float = DOWNLOAD_DELAY, force: bool = False) -> dict:
"""
Downloads each valid TikTok URL, skipping IDs already downloaded.
Returns counts: {"downloaded", "skipped", "failed", "invalid"}.
"""
stats = {"downloaded": 0, "skipped": 0, "failed": 0, "invalid": 0}
seen_urls = set()
queue = []
for raw in urls:
url = raw.strip()
if not url:
continue
if not is_valid_tiktok_url(url):
logger.warning(f"Not a TikTok post URL, ignoring: {url}")
stats["invalid"] += 1
elif normalize_tiktok_url(url) not in seen_urls:
seen_urls.add(normalize_tiktok_url(url))
queue.append(url)
if not queue:
logger.error("No valid TikTok URLs found.")
return stats
known_ids = load_downloaded_ids() # what is already recorded on disk
downloaded_ids = set() if force else set(known_ids)
succeeded_urls, succeeded_ids = [], []
attempted = 0
for i, url in enumerate(queue, start=1):
prefix = f"[{i}/{len(queue)}]"
video_id = extract_tiktok_id(url)
if video_id and video_id in downloaded_ids:
logger.info(f"{prefix} Skipping (already downloaded): {url}")
stats["skipped"] += 1
continue
if attempted and delay > 0:
time.sleep(delay)
attempted += 1
logger.info(f"{prefix} Downloading: {url}")
try:
result = download(url)
except DownloadError as e:
logger.error(f"{prefix} Failed: {e}")
log_failed_url(url)
stats["failed"] += 1
continue
for path in result.files:
logger.info(f"{prefix} Saved: {os.path.basename(path)}")
if result.tiktok_id:
if result.tiktok_id not in known_ids:
save_downloaded_id(result.tiktok_id)
known_ids.add(result.tiktok_id)
downloaded_ids.add(result.tiktok_id)
succeeded_ids.append(result.tiktok_id)
succeeded_urls.append(url)
stats["downloaded"] += 1
if succeeded_urls:
clear_failed_urls(succeeded_urls, succeeded_ids)
logger.info(
"Done. Downloaded: {downloaded}, skipped: {skipped}, failed: {failed}, invalid: {invalid}".format(**stats)
)
if stats["failed"]:
logger.info(f"Failed URLs are listed in {FAILED_FILE}")
return stats
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser(description="Download TikTok videos and photo posts with yt-dlp.")
parser.add_argument("inputs", nargs="+", help="TikTok URLs and/or text files containing URLs")
parser.add_argument("--delay", type=float, default=DOWNLOAD_DELAY, help="seconds between downloads")
parser.add_argument("--force", action="store_true", help="re-download IDs already in downloaded_ids.txt")
parser.add_argument("-v", "--verbose", action="store_true", help="show yt-dlp output on errors")
parser.add_argument(
"--cookies",
metavar="FILE",
help="optional cookies.txt exported from your browser (for private or age-restricted posts)",
)
args = parser.parse_args(argv)
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(message)s",
level=logging.DEBUG if args.verbose else logging.INFO,
)
global COOKIES_FILE
if args.cookies:
COOKIES_FILE = args.cookies
if COOKIES_FILE:
if not os.path.isfile(COOKIES_FILE):
logger.error(f"Cookies file not found: {COOKIES_FILE}")
return 2
logger.info(f"Using cookies from {COOKIES_FILE}")
urls: List[str] = []
for item in args.inputs:
if os.path.isfile(item):
try:
with open(item, "r", encoding="utf-8-sig") as f:
found = extract_urls(f)
except OSError as e:
logger.error(f"Could not read {item}: {e}")
return 2
logger.info(f"Read {len(found)} URLs from {item}")
urls += found
else:
urls.append(item)
stats = process_urls(urls, delay=args.delay, force=args.force)
return 1 if stats["failed"] or not (stats["downloaded"] or stats["skipped"]) else 0
if __name__ == "__main__":
sys.exit(main())