Rework downloader: single yt-dlp call, reliable file paths, better CLI

- Download each post with one yt-dlp run and take the saved file paths
  from yt-dlp's own output instead of parsing logs or guessing by mtime
- Let yt-dlp build and sanitize filenames (same naming as before) and
  read its output as UTF-8 so non-ASCII uploader names work on Windows
- Rewrite /photo/ URLs to /video/, strip query strings, accept
  vm./vt.tiktok.com short links, and require a real tiktok.com host
- Stop duplicating entries in failed.txt and remove URLs from it once
  they download successfully
- Raise DownloadError with yt-dlp's short error line; add retries and
  timeouts
- CLI: multiple URLs/files, comments in input files, --delay, --force,
  -v, non-zero exit code on failures; settings via environment/.env
This commit is contained in:
X4Lo committed 2026-11-15 22:37:58 +00:00
1 parent 7c71ed6df8
commit 1c17487ce4
2 files changed
+324 -256

No files matched your search

+12 -1
View File
@@ -30,10 +30,21 @@ python downloader.py https://www.tiktok.com/@user/video/123456789
# Batch download from a file (one URL per line) # Batch download from a file (one URL per line)
python downloader.py in/my-urls.txt python downloader.py in/my-urls.txt
# Retry previously failed downloads # Retry previously failed downloads (successes are removed from failed.txt)
python downloader.py failed.txt python downloader.py failed.txt
# Mix URLs and files; short links (vm.tiktok.com / vt.tiktok.com) work too
python downloader.py https://vm.tiktok.com/ZMabc123/ in/more-urls.txt
# Options: --delay SECONDS, --force (ignore downloaded_ids.txt), -v (show yt-dlp output on errors)
``` ```
Input files may contain blank lines, `# comments`, and URLs mixed with other text.
The exit code is non-zero when any download fails.
Optional environment variables (or `.env`): `YT_DLP_PATH`, `TIKDOWN_DOWNLOAD_DIR`,
`TIKDOWN_COOKIES` (cookies.txt for private posts), `TIKDOWN_DELAY`.
## Downloads ## Downloads
Videos and photos are saved to `./downloads/`. Filenames include the upload date when metadata is available: Videos and photos are saved to `./downloads/`. Filenames include the upload date when metadata is available:
+312 -255
View File
@@ -1,327 +1,384 @@
import json """
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 logging
import os import os
import re import re
import shutil
import subprocess import subprocess
import sys import sys
import threading
import time import time
from typing import List from dataclasses import dataclass, field
from urllib.parse import urlparse 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
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
DOWNLOAD_DIR = "./downloads" BASE_DIR = os.path.dirname(os.path.abspath(__file__))
YT_DLP_PATH = "./yt-dlp"
DOWNLOADED_IDS_FILE = "./downloaded_ids.txt"
FAILED_FILE = "./failed.txt"
# Rate limiting configuration
DOWNLOAD_DELAY = 1 # Delay in seconds between downloads
def extract_tiktok_id(url: str) -> str | None: 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. Extracts the TikTok video/photo ID from a URL.
Examples:
https://www.tiktok.com/@user/video/7500623452873723158 -> 7500623452873723158 https://www.tiktok.com/@user/video/7500623452873723158 -> 7500623452873723158
https://www.tiktok.com/@user/photo/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 = re.search(r"/(?:video|photo)/(\d+)", url) match = _ID_RE.search(url)
return match.group(1) if match else None 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: def load_downloaded_ids() -> set:
"""Loads the set of already-downloaded TikTok IDs from disk.""" """Loads the set of already-downloaded TikTok IDs from disk."""
if not os.path.exists(DOWNLOADED_IDS_FILE): if not os.path.exists(DOWNLOADED_IDS_FILE):
return set() return set()
with open(DOWNLOADED_IDS_FILE, "r") as f: with open(DOWNLOADED_IDS_FILE, "r", encoding="utf-8") as f:
return set(line.strip() for line in f if line.strip()) return {line.strip() for line in f if line.strip()}
def save_downloaded_id(video_id: str) -> None: def save_downloaded_id(video_id: str) -> None:
"""Appends a TikTok ID to the downloaded-ids tracking file.""" """Appends a TikTok ID to the downloaded-ids tracking file."""
with open(DOWNLOADED_IDS_FILE, "a") as f: with _file_lock, open(DOWNLOADED_IDS_FILE, "a", encoding="utf-8") as f:
f.write(video_id + "\n") f.write(video_id + "\n")
def _read_failed() -> List[str]:
if not os.path.exists(FAILED_FILE):
return []
with open(FAILED_FILE, "r", encoding="utf-8") as f:
return [line.strip() for line in f if line.strip()]
def log_failed_url(url: str) -> None: def log_failed_url(url: str) -> None:
"""Appends a failed URL to ./failed.txt.""" """Records a failed URL in failed.txt (once; repeated failures are not duplicated)."""
with open(FAILED_FILE, "a") as f: url = url.strip()
with _file_lock:
if url in _read_failed():
return
with open(FAILED_FILE, "a", encoding="utf-8") as f:
f.write(url + "\n") f.write(url + "\n")
def download_video(url: str) -> str: def clear_failed_urls(urls: Iterable[str], ids: Iterable[str] = ()) -> None:
""" """Removes now-successful URLs (matched by URL or post ID) from failed.txt."""
Downloads a TikTok video using yt-dlp. urls, ids = {u.strip() for u in urls}, set(ids)
with _file_lock:
current = _read_failed()
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(FAILED_FILE, "w", encoding="utf-8") as f:
f.writelines(u + "\n" for u in kept)
Args:
url (str): The TikTok video URL.
Returns: # --- Downloading ---
str: Path to the downloaded video file.
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) os.makedirs(DOWNLOAD_DIR, exist_ok=True)
# First, get metadata to extract the publish date
metadata_cmd = [YT_DLP_PATH, "--no-check-certificate", "--dump-json", url]
metadata_result = subprocess.run(metadata_cmd, capture_output=True, text=True)
# Default template without date
output_template = os.path.join(DOWNLOAD_DIR, "%(id)s.%(ext)s")
# Try to extract date from metadata
try:
if metadata_result.returncode == 0:
metadata = json.loads(metadata_result.stdout)
# Extract the upload date if available
if "upload_date" in metadata:
# Format is typically YYYYMMDD
upload_date = metadata["upload_date"]
uploader = metadata["uploader"]
uploader_id = metadata["uploader_id"]
# You can reformat it if you want (e.g., YYYY-MM-DD)
formatted_date = (
f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
)
# Update the output template to include the date
output_template = os.path.join(
DOWNLOAD_DIR,
f"{formatted_date}_%(id)s_{uploader}_{uploader_id}.%(ext)s",
)
# logger.info(f"Using date format: {formatted_date}")
except Exception as e:
logger.error(f"Error parsing metadata: {str(e)}")
# Continue with the default template if there's an error
# Download the video with the determined output template
cmd = [ cmd = [
YT_DLP_PATH, YT_DLP_PATH,
"--no-check-certificate", "--no-check-certificate",
"--format", "--encoding", "utf-8",
"bestvideo+bestaudio/best", "--no-simulate",
"--verbose", "--no-progress",
"-o", "--retries", "3",
output_template, "--extractor-retries", "3",
url, "--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))
result = subprocess.run(cmd, capture_output=True, text=True) 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: if result.returncode != 0:
logger.error(f"yt-dlp error: {result.stderr}") logger.debug("yt-dlp stderr:\n%s", result.stderr)
return None raise DownloadError(_yt_dlp_error(result.stderr))
# Look for the file path in both stdout and stderr tiktok_id = extract_tiktok_id(url)
full_output = result.stdout + result.stderr 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])
# Try to find the destination file # Fallback for runs where yt-dlp skipped an already-present file
filename = None if not files and tiktok_id:
for line in full_output.split("\n"): files = _find_existing_files(tiktok_id)
if "[download]" in line and "Destination:" in line:
parts = line.split("Destination:")
if len(parts) > 1:
filename = parts[1].strip()
break
# If we couldn't find it with the above method, try alternative approaches if not files:
if not filename: logger.debug("yt-dlp output:\n%s\n%s", result.stdout, result.stderr)
# Look for the "[download] ... has already been downloaded" message raise DownloadError("yt-dlp finished but no downloaded file was found")
for line in full_output.split("\n"):
if "[download]" in line and "has already been downloaded" in line:
match = re.search(
r"\[download\] (.*?) has already been downloaded", line
)
if match:
filename = match.group(1)
break
# If we still couldn't find it, try to find any file in the download directory that was recently created return DownloadResult(tiktok_id=tiktok_id, files=files)
if not filename:
try:
files = [os.path.join(DOWNLOAD_DIR, f) for f in os.listdir(DOWNLOAD_DIR)]
if files:
newest_file = max(files, key=os.path.getctime)
if time.time() - os.path.getctime(newest_file) < 30:
filename = newest_file
except Exception as e:
logger.error(f"Error finding recent files: {str(e)}")
# logger.info(f"Found filename: {filename}")
if not filename or not os.path.exists(filename): def download_video(url: str) -> str:
logger.error(f"Full yt-dlp output: {full_output}") """Downloads a TikTok post and returns the path of its main media file."""
raise Exception("Failed to retrieve downloaded file") return download(url).files[0]
return filename
def download_photo(url: str) -> List[str]: 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 a TikTok photo slideshow and returns list of file paths. Downloads each valid TikTok URL, skipping IDs already downloaded.
Files are saved as: xxx1.jpg, xxx2.jpg, etc. Returns counts: {"downloaded", "skipped", "failed", "invalid"}.
""" """
os.makedirs(DOWNLOAD_DIR, exist_ok=True) 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)
# Get metadata to extract ID or date if not queue:
metadata_cmd = [YT_DLP_PATH, "--no-check-certificate", "--dump-json", url]
metadata_result = subprocess.run(metadata_cmd, capture_output=True, text=True)
base_name = "xxx"
try:
if metadata_result.returncode == 0:
metadata = json.loads(metadata_result.stdout)
upload_date = metadata.get("upload_date", "")
if upload_date:
formatted_date = (
f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
)
base_name = f"{formatted_date}_xxx"
except Exception as e:
logger.warning(f"Could not parse metadata for photo naming: {e}")
# Output template for photos
output_template = os.path.join(
DOWNLOAD_DIR, f"{base_name}%(playlist_index)s.%(ext)s"
)
# Download command with best image quality
cmd = [
YT_DLP_PATH,
"--no-check-certificate",
"--format",
"bestvideo+bestaudio/best",
"-o",
output_template,
url,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"yt-dlp error downloading photo: {result.stderr}")
raise Exception("Failed to download TikTok photo slideshow")
full_output = result.stdout + result.stderr
downloaded_files = []
# Parse downloaded files from output
for line in full_output.split("\n"):
if "[download]" in line and "Destination:" in line:
parts = line.split("Destination:")
if len(parts) > 1:
file_path = parts[1].strip()
downloaded_files.append(file_path)
if not downloaded_files:
logger.warning("No photo files were found in the output.")
return downloaded_files
def is_valid_tiktok_url(url: str) -> bool:
"""
Validates a TikTok URL.
Args:
url (str): The URL to validate.
Returns:
bool: True if valid, False otherwise.
"""
parsed = urlparse(url)
return (
parsed.scheme in ["http", "https"]
and "tiktok.com" in parsed.netloc
and ("/video/" in parsed.path or "/photo/" in parsed.path)
)
def is_tiktok_photo_url(url: str) -> bool:
"""
Checks if a TikTok URL points to a photo/slideshow post.
"""
parsed = urlparse(url)
return (
parsed.scheme in ["http", "https"]
and "tiktok.com" in parsed.netloc
and "/photo/" in parsed.path
)
def process_urls(urls: List[str]):
"""
Processes a list of TikTok URLs for downloading.
Args:
urls (List[str]): List of TikTok video URLs.
"""
valid_urls = [url.strip() for url in urls if is_valid_tiktok_url(url.strip())]
if not valid_urls:
logger.error("No valid TikTok URLs found.") logger.error("No valid TikTok URLs found.")
print("No valid TikTok URLs found.") return stats
return
downloaded_ids = load_downloaded_ids() 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(valid_urls, start=1): for i, url in enumerate(queue, start=1):
logger.info(f"Processing URL {i}/{len(valid_urls)}: {url}") prefix = f"[{i}/{len(queue)}]"
# print(f"Processing URL {i}/{len(valid_urls)}: {url}")
try:
# Extract ID and check if already downloaded
video_id = extract_tiktok_id(url) video_id = extract_tiktok_id(url)
if video_id and video_id in downloaded_ids: if video_id and video_id in downloaded_ids:
logger.info(f"Skipping (already downloaded): {url}") logger.info(f"{prefix} Skipping (already downloaded): {url}")
stats["skipped"] += 1
continue continue
if is_tiktok_photo_url(url): if attempted and delay > 0:
photo_paths = download_photo(url) time.sleep(delay)
for path in photo_paths: attempted += 1
logger.info(f"Downloaded photo: {path}")
else:
video_path = download_video(url)
logger.info(f"Downloaded video: {video_path}")
# Mark as downloaded logger.info(f"{prefix} Downloading: {url}")
if video_id: try:
save_downloaded_id(video_id) result = download(url)
except DownloadError as e:
except Exception as e: logger.error(f"{prefix} Failed: {e}")
logger.error(f"Error processing {url}: {str(e)}")
log_failed_url(url) log_failed_url(url)
stats["failed"] += 1
continue
# Apply rate limiting for path in result.files:
if i < len(valid_urls): logger.info(f"{prefix} Saved: {os.path.basename(path)}")
logger.info(f"Waiting {DOWNLOAD_DELAY} seconds before next download...") if result.tiktok_id:
time.sleep(DOWNLOAD_DELAY) 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")
args = parser.parse_args(argv)
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(message)s",
level=logging.DEBUG if args.verbose else logging.INFO,
)
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__": if __name__ == "__main__":
if len(sys.argv) < 2: sys.exit(main())
print("Usage: python downloader.py <url_or_input_file>")
sys.exit(1)
input_arg = sys.argv[1]
# Check if the input is a file
if os.path.isfile(input_arg):
try:
with open(input_arg, "r") as f:
urls = f.readlines()
logger.info(f"Processing URLs from file: {input_arg}")
process_urls(urls)
except Exception as e:
logger.error(f"Error reading input file: {str(e)}")
print(f"Error reading input file: {str(e)}")
else:
# Assume it's a single URL
urls = [input_arg]
process_urls(urls)