Files
TikDown/profile-downloader/core.py
T
X4Lo 3dc4b0757f Profile downloader: favorites list in the web UI; mark story filenames
- favorites.txt (git-ignored): profiles listed there show as buttons in the
  web UI that load the profile with one click
- stories are saved as '<date> <id> story.<ext>' so they stand apart from posts
2026-11-23 00:52:35 +00:00

625 lines
25 KiB
Python

"""
Listing and downloading a TikTok profile, built on gallery-dl.
gallery-dl is used instead of yt-dlp because it returns the actual images of
photo posts (yt-dlp only gives their background music) and supports stories.
Used by main.py (command line) and app.py (web UI).
"""
import json
import logging
import os
import random
import re
import subprocess
import sys
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime
from typing import Callable, Dict, List, Optional, Tuple
ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(ROOT))
import downloader as shared # noqa: E402 (failed-URL helpers shared with the main script)
logger = logging.getLogger("profile")
# --- Configuration (environment variables override the defaults) ---
DOWNLOAD_ROOT = os.getenv("PROFILE_DOWNLOAD_DIR") or os.path.join(ROOT, "downloads", "profile")
DEFAULT_COOKIES = os.path.join(ROOT, "cookies.txt")
LISTING_CACHE_TTL = 3600 # seconds before a cached profile listing is fetched again
DOWNLOAD_DELAY = float(os.getenv("PROFILE_DELAY", "1.5")) # seconds between posts (plus jitter)
DOWNLOAD_TIMEOUT = 900 # seconds before one post's download is abandoned
# "<local date+time> <post id>[ <slide no.>][ story].<ext>", e.g.
# 2026-11-08 16-53-54 7705844899718958356 01.jpg (photo post slide)
# 2026-11-08 16-53-54 7705844899718958356.mp3 (photo post music)
# 2026-08-06 00-57-14 7670716372560727317.mp4 (video)
# 2026-11-21 20-37-01 7710726500621782294 story.mp4 (story)
# Seconds + post ID keep posts made in the same minute from colliding.
STORY_SUFFIX = " story"
def _filename_format(kind: str) -> str:
suffix = STORY_SUFFIX if kind == "story" else ""
return "{date:Olocal/%Y-%m-%d %H-%M-%S} {id}{num:? //>02}" + suffix + ".{extension}"
BACKOFF_WAITS = (30, 90, 180) # seconds to wait before retrying a blocked request
MAX_BLOCKED_IN_A_ROW = 3 # stop the run after this many posts in a row stay blocked
_SEC_UID_RE = re.compile(r"^MS4wLjABAAAA[\w-]{20,}$")
_BLOCKED_RE = re.compile(r"\b(403|429)\b|too many requests|captcha|verify|rate.?limit", re.I)
_listing_lock = threading.Lock()
_archive_lock = threading.Lock()
class ProfileError(Exception):
"""A problem worth showing to the user as-is."""
# --- Profile input and paths ---
def parse_profile_input(text: str) -> Tuple[Optional[str], Optional[str], Optional[str]]:
"""
Accepts a username, @username, profile URL, link to one of the profile's
posts, or secUid ("MS4wLjABAAAA...").
Returns (username, sec_uid, post_url); any of them may be None.
"""
text = (text or "").strip()
if _SEC_UID_RE.match(text):
return None, text, None
match = re.search(r"tiktok\.com/@([\w.-]+)(?:/(?:video|photo)/(\d+))?", text)
if match:
username, post_id = match.groups()
post_url = f"https://www.tiktok.com/@{username}/video/{post_id}" if post_id else None
return username, None, post_url
match = re.fullmatch(r"@?([\w.-]{1,64})", text)
if match:
return match.group(1), None, None
raise ProfileError("Enter a TikTok username, @username, profile URL, post link, or secUid.")
def profile_dir(username: str) -> str:
return os.path.join(DOWNLOAD_ROOT, username)
def _profile_file(username: str, name: str) -> str:
return os.path.join(profile_dir(username), name)
def failed_file(username: str) -> str:
return _profile_file(username, "failed.txt")
def resolve_cookies(cookies: Optional[str], use_default: bool = True) -> Optional[str]:
"""Returns a usable cookies path: the given one, else cookies.txt next to this file."""
if cookies:
if not os.path.isfile(cookies):
raise ProfileError(f"Cookies file not found: {cookies}")
return cookies
if use_default and os.path.isfile(DEFAULT_COOKIES):
return DEFAULT_COOKIES
return None
def _read_json(path: str) -> Optional[dict]:
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except (OSError, ValueError):
return None
def _write_json(path: str, data) -> None:
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
os.replace(tmp, path)
def _find_profile_by_sec_uid(sec_uid: str) -> Optional[dict]:
if not os.path.isdir(DOWNLOAD_ROOT):
return None
for name in os.listdir(DOWNLOAD_ROOT):
info = _read_json(os.path.join(DOWNLOAD_ROOT, name, ".profile.json"))
if info and info.get("sec_uid") == sec_uid:
return info
return None
# --- Archive (IDs of fully downloaded posts) ---
def load_archive(username: str) -> set:
path = _profile_file(username, ".archive.txt")
if not os.path.exists(path):
return set()
with open(path, "r", encoding="utf-8") as f:
return {line.strip() for line in f if line.strip()}
def save_to_archive(username: str, post_id: str) -> None:
path = _profile_file(username, ".archive.txt")
with _archive_lock:
if post_id in load_archive(username):
return
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "a", encoding="utf-8") as f:
f.write(post_id + "\n")
# --- Listing ---
class _GalleryDlLog:
"""gallery-dl's extractors expect a logger with a .traceback() method."""
def __init__(self):
self._log = logging.getLogger("gallery-dl")
def __getattr__(self, name):
return getattr(self._log, name)
def traceback(self, exc):
self._log.debug("gallery-dl traceback", exc_info=exc)
def _extractor(url: str, cookies: Optional[str]):
from gallery_dl import config, extractor
config.clear()
if cookies:
config.set(("extractor",), "cookies", cookies)
extr = extractor.find(url)
if extr is None:
raise ProfileError(f"gallery-dl does not recognise {url}")
extr.log = _GalleryDlLog()
extr.initialize()
return extr
def _with_backoff(action: Callable, what: str, progress: Callable[[str], None]):
"""Runs action(), waiting and retrying when TikTok blocks the request."""
for attempt, wait in enumerate((0,) + BACKOFF_WAITS[:2]):
if wait:
progress(f"TikTok blocked the {what} request, retrying in {wait}s...")
time.sleep(wait)
try:
return action()
except Exception as e: # gallery-dl raises its own HttpError types
if not _BLOCKED_RE.search(str(e)) or attempt == 2:
raise ProfileError(f"Could not load the {what}: {e}") from e
def _author_from_post(extr, post_url: str) -> dict:
data = extr._extract_rehydration_data(post_url)
return data["webapp.video-detail"]["itemInfo"]["itemStruct"]["author"]
def _resolve_sec_uid(extr, username: Optional[str], post_url: Optional[str],
progress: Callable[[str], None]) -> Tuple[str, str]:
"""
Finds a profile's secUid (needed for the post list API).
TikTok often answers the profile page with 403 even when its APIs work, so
this falls back to reading the author from a post page: a pasted post link,
or the newest posts already downloaded from this profile.
Returns (sec_uid, username).
"""
post_urls = [post_url] if post_url else []
if username:
newest = sorted(load_archive(username), key=lambda i: int(i) if i.isdigit() else 0, reverse=True)
post_urls += [f"https://www.tiktok.com/@{username}/video/{i}" for i in newest[:3]]
attempts = []
if username:
attempts.append(("profile page", lambda: extr._extract_sec_uid(
f"https://www.tiktok.com/@{username}", username)))
for url in post_urls:
attempts.append(("post page", lambda url=url: _author_from_post(extr, url)))
if username:
attempts.append(("profile page (retry)", attempts[0][1]))
last_error = None
for index, (what, action) in enumerate(attempts):
if what.endswith("(retry)"):
progress("Still blocked, waiting 20s before one last try...")
time.sleep(20)
progress(f"Looking up the profile via the {what}...")
try:
result = action()
except Exception as e:
last_error = e
logger.debug("secUid lookup via %s failed: %s", what, e)
continue
if isinstance(result, dict): # author dict from a post page
if username and result.get("uniqueId", "").lower() != username.lower():
continue
return result["secUid"], result.get("uniqueId") or username
return result, username
raise ProfileError(
"TikTok is blocking the profile lookup"
+ (f" ({last_error})" if last_error else "")
+ ". Paste a link to one of the profile's posts, or its secUid, and try again."
)
def _thumbnail(item: dict) -> str:
image_post = item.get("imagePost") or {}
for img in [image_post.get("cover")] + list(image_post.get("images") or []):
urls = ((img or {}).get("imageURL") or {}).get("urlList") or []
if urls:
return urls[0]
video = item.get("video") or {}
return video.get("cover") or video.get("originCover") or video.get("dynamicCover") or ""
def _record(item: dict, kind: str, username: str) -> dict:
images = (item.get("imagePost") or {}).get("images") or []
timestamp = int(item.get("createTime") or 0)
author = (item.get("author") or {}).get("uniqueId") or username
# Photo posts can be downloaded straight from these CDN links, without
# loading the post page (which TikTok blocks more often than its APIs).
media = None
if images:
media = {
"images": [((img.get("imageURL") or {}).get("urlList") or [None])[0] for img in images],
"music": (item.get("music") or {}).get("playUrl") or None,
}
return {
"media": media,
"id": str(item["id"]),
"url": f"https://www.tiktok.com/@{author}/video/{item['id']}",
"kind": kind, # "story" or "post"
"type": "photo" if images else "video",
"images": len(images),
"duration": int((item.get("video") or {}).get("duration") or 0),
"timestamp": timestamp,
"date": datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M") if timestamp else "",
"caption": item.get("desc") or "",
"thumb": _thumbnail(item),
}
def _fetch_stories(username: str, author_id: str, cookies: Optional[str]) -> List[dict]:
"""
Fetches active stories directly from the story/item_list endpoint.
(gallery-dl's stories extractor crashes when a profile has no stories.)
"""
from gallery_dl.extractor import tiktok
extr = _extractor(f"https://www.tiktok.com/@{username}/stories", cookies)
request = tiktok.TiktokStoryItemListRequest()
cursor = tiktok.TiktokStoryTimeCursor()
params = {"authorId": author_id, "loadBackward": "false", "count": "20"}
items: Dict[str, dict] = {}
for _ in range(10): # stories are few; this is only a safety limit
data, final_params = request._request_data(extr, cursor, params)
for item in data.get("itemList") or []:
items[str(item["id"])] = item
if not data.get("itemList") or not data.get("HasMoreAfter"):
break
try:
if cursor.next_page(data, final_params):
break
except Exception:
break
return list(items.values())
def list_profile(
text: str,
cookies: Optional[str] = None,
refresh: bool = False,
include_stories: bool = True,
progress: Callable[[str], None] = logger.info,
) -> dict:
"""
Lists a profile's stories and posts (stories first, then newest posts first).
The listing is cached for LISTING_CACHE_TTL; download status is always current.
"""
username, sec_uid, post_url = parse_profile_input(text)
info = (_read_json(_profile_file(username, ".profile.json")) if username else None) or (
_find_profile_by_sec_uid(sec_uid) if sec_uid else None
) or {}
username = username or info.get("username")
sec_uid = sec_uid or info.get("sec_uid")
cached = _read_json(_profile_file(username, ".listing_cache.json")) if username else None
if cached and not refresh and time.time() - cached.get("saved", 0) < LISTING_CACHE_TTL:
progress(f"Using cached listing ({(time.time() - cached['saved']) / 60:.0f} min old)")
return _with_status(cached)
with _listing_lock:
extr = _extractor(f"https://www.tiktok.com/@{username or 'unknown'}/posts", cookies)
if not sec_uid:
sec_uid, username = _resolve_sec_uid(extr, username, post_url, progress)
extr._extract_sec_uid = lambda *args, **kwargs: sec_uid
progress("Fetching the post list (about 15 posts per request)...")
posts = _with_backoff(lambda: extr.posts(), "post list", progress) or {}
items = list(posts.values()) if isinstance(posts, dict) else []
if not items:
hint = "" if cookies else " Try again with a cookies file."
raise ProfileError(f"No posts found (private profile, or TikTok blocked the request).{hint}")
author = items[0].get("author") or {}
username = author.get("uniqueId") or username
info = {
"username": username,
"sec_uid": author.get("secUid") or sec_uid,
"author_id": str(author.get("id") or info.get("author_id") or ""),
"nickname": author.get("nickname") or username,
"avatar": author.get("avatarThumb") or author.get("avatarMedium") or "",
}
_write_json(_profile_file(username, ".profile.json"), info)
stories, stories_note = [], ""
if include_stories and info["author_id"]:
progress("Fetching stories...")
try:
stories = _fetch_stories(username, info["author_id"], cookies)
except Exception as e:
logger.warning(f"Could not load stories: {e}")
stories_note = "Stories could not be loaded."
listing = {
"saved": time.time(),
"profile": info,
"stories": sorted(
(_record(i, "story", username) for i in stories), key=lambda r: r["timestamp"], reverse=True
),
"posts": [_record(i, "post", username) for i in items],
"stories_note": stories_note,
}
_write_json(_profile_file(username, ".listing_cache.json"), listing)
progress(f"Found {len(listing['stories'])} stories and {len(listing['posts'])} posts")
return _with_status(listing)
def _with_status(listing: dict) -> dict:
"""Adds per-item download status ("new", "downloaded", "failed")."""
username = listing["profile"]["username"]
archive = load_archive(username)
failed = {shared.extract_tiktok_id(u) for u in shared.read_failed_urls(failed_file(username))}
for record in listing["stories"] + listing["posts"]:
record["status"] = (
"downloaded" if record["id"] in archive else "failed" if record["id"] in failed else "new"
)
listing["cache_age"] = int(time.time() - listing.get("saved", time.time()))
return listing
# --- Downloading ---
@dataclass
class Outcome:
ok: bool
files: List[str] = field(default_factory=list)
error: str = ""
blocked: bool = False
def _gallery_dl_error(stderr: str) -> str:
errors = [line for line in stderr.splitlines() if "][error]" in line]
line = (errors or [l for l in stderr.splitlines() if l.strip()] or ["gallery-dl failed"])[-1]
return re.sub(r"^\[[^\]]+\]\[error\]\s*", "", line).strip()
def _remove_partials(directory: str, post_id: str) -> None:
if not os.path.isdir(directory):
return
for name in os.listdir(directory):
if post_id in name and name.endswith(".part"):
try:
os.remove(os.path.join(directory, name))
except OSError:
pass
_EXTENSIONS = {"image/jpeg": "jpg", "image/png": "png", "image/webp": "webp", "image/heic": "heic",
"audio/mpeg": "mp3", "audio/mp4": "m4a", "audio/x-m4a": "m4a", "audio/aac": "aac"}
def _download_photo_post_direct(record: dict, directory: str) -> Outcome:
"""Downloads a photo post's slides and music from the CDN links in the listing."""
import requests
media = record.get("media") or {}
if not media.get("images") or not all(media["images"]):
return Outcome(False, error="no direct links")
stamp = datetime.fromtimestamp(record["timestamp"]).strftime("%Y-%m-%d %H-%M-%S")
suffix = STORY_SUFFIX if record.get("kind") == "story" else ""
targets = [(f"{stamp} {record['id']} {n:02}{suffix}", url) for n, url in enumerate(media["images"], start=1)]
if media.get("music"):
targets.append((f"{stamp} {record['id']}{suffix}", media["music"]))
os.makedirs(directory, exist_ok=True)
session = requests.Session()
session.headers.update({"User-Agent": "Mozilla/5.0", "Referer": "https://www.tiktok.com/"})
files = []
for base, url in targets:
existing = [n for n in os.listdir(directory) if n.startswith(base + ".") and not n.endswith(".part")]
if existing:
files.append(os.path.join(directory, existing[0]))
continue
try:
response = session.get(url, timeout=60)
except requests.RequestException as e:
return Outcome(False, files, f"direct download failed: {e}")
content_type = response.headers.get("Content-Type", "").split(";")[0].strip()
if response.status_code != 200 or not content_type.startswith(("image/", "audio/")):
return Outcome(False, files, f"direct download failed: HTTP {response.status_code}",
response.status_code in (403, 429))
path = os.path.join(directory, f"{base}.{_EXTENSIONS.get(content_type, content_type.split('/')[-1])}")
with open(path + ".part", "wb") as f:
f.write(response.content)
os.replace(path + ".part", path)
files.append(path)
return Outcome(True, files)
def download_record(record: dict, directory: str, cookies: Optional[str]) -> Outcome:
"""Downloads one listed post: photo posts directly when possible, else via gallery-dl."""
if record.get("media"):
outcome = _download_photo_post_direct(record, directory)
if outcome.ok:
return outcome
_remove_partials(directory, record["id"])
logger.debug("Direct download of %s failed (%s), using gallery-dl", record["id"], outcome.error)
return download_post(record["url"], record["id"], directory, cookies, record.get("kind", "post"))
def download_post(url: str, post_id: str, directory: str, cookies: Optional[str],
kind: str = "post") -> Outcome:
"""Downloads one post or story (all photo slides + music, or the video) with gallery-dl."""
os.makedirs(directory, exist_ok=True)
cmd = [sys.executable, "-P", "-m", "gallery_dl", "-D", directory, "-f", _filename_format(kind)]
if cookies:
cmd += ["--cookies", cookies]
cmd.append(url)
env = dict(os.environ, PYTHONIOENCODING="utf-8")
try:
result = subprocess.run(
cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
timeout=DOWNLOAD_TIMEOUT, env=env,
)
except subprocess.TimeoutExpired:
_remove_partials(directory, post_id)
return Outcome(False, error=f"timed out after {DOWNLOAD_TIMEOUT}s")
# gallery-dl prints each new file's path, and "# <path>" for files it skipped as existing
files = [line.lstrip("# ").strip() for line in result.stdout.splitlines() if line.strip()]
files = [f for f in files if os.path.isfile(f)]
errors = "][error]" in result.stderr
if result.returncode != 0 or errors or not files:
_remove_partials(directory, post_id)
message = _gallery_dl_error(result.stderr) if result.stderr.strip() else "no files were downloaded"
logger.debug("gallery-dl output for %s:\n%s\n%s", url, result.stdout, result.stderr)
return Outcome(False, files, message, bool(_BLOCKED_RE.search(result.stderr)))
return Outcome(True, files)
class DownloadJob:
"""
Downloads a list of posts one by one. Thread-safe snapshot() for the UI.
- waits DOWNLOAD_DELAY (+ jitter) between posts
- when TikTok blocks a request, waits 30s / 90s / 180s and retries
- stops after MAX_BLOCKED_IN_A_ROW posts in a row stay blocked
- records failures in <profile>/failed.txt and clears them on success
"""
def __init__(self, username: str, records: List[dict], cookies: Optional[str],
delay: float = DOWNLOAD_DELAY, on_event: Callable[[str], None] = logger.info):
self.username = username
self.cookies = cookies
self.delay = delay
self.on_event = on_event
self.items = [
{"id": r["id"], "url": r["url"], "kind": r.get("kind", "post"),
"status": "queued", "error": "", "files": 0}
for r in records
]
self._records = {r["id"]: r for r in records}
self.state = "running"
self.message = ""
self.started = time.time()
self._stop = threading.Event()
self._lock = threading.Lock()
def stop(self) -> None:
self._stop.set()
with self._lock:
if self.state == "running":
self.state = "stopping"
def snapshot(self) -> dict:
with self._lock:
counts = {}
for item in self.items:
counts[item["status"]] = counts.get(item["status"], 0) + 1
return {
"username": self.username,
"state": self.state,
"message": self.message,
"total": len(self.items),
"counts": counts,
"items": [dict(i) for i in self.items],
}
def _set(self, item: dict, **changes) -> None:
with self._lock:
item.update(changes)
def run(self) -> None:
directory = profile_dir(self.username)
# Leftover from the old yt-dlp based script, which crashed mid-rename
legacy_temp = os.path.join(directory, ".temp")
if os.path.isdir(legacy_temp):
import shutil
shutil.rmtree(legacy_temp, ignore_errors=True)
blocked_in_a_row = 0
total = len(self.items)
for index, item in enumerate(self.items, start=1):
if self._stop.is_set():
break
if index > 1 and self._stop.wait(self.delay + random.uniform(0, self.delay / 2)):
break
self._set(item, status="downloading")
self.on_event(f"[{index}/{total}] {item['url']}")
record = self._records[item["id"]]
outcome = download_record(record, directory, self.cookies)
for wait in BACKOFF_WAITS:
if outcome.ok or not outcome.blocked:
break
self._set(item, status="waiting", error=f"TikTok is blocking requests, retrying in {wait}s")
self.on_event(f" blocked by TikTok, retrying in {wait}s")
if self._stop.wait(wait):
break
self._set(item, status="downloading")
outcome = download_record(record, directory, self.cookies)
if outcome.ok:
save_to_archive(self.username, item["id"])
shared.clear_failed_urls([item["url"]], [item["id"]], path=failed_file(self.username))
self._set(item, status="done", error="", files=len(outcome.files))
self.on_event(f" saved {len(outcome.files)} file(s)")
blocked_in_a_row = 0
continue
if self._stop.is_set() and item["status"] == "waiting":
self._set(item, status="skipped", error="")
break
shared.log_failed_url(item["url"], path=failed_file(self.username))
self._set(item, status="failed", error=outcome.error, files=len(outcome.files))
self.on_event(f" failed: {outcome.error}")
blocked_in_a_row = blocked_in_a_row + 1 if outcome.blocked else 0
if blocked_in_a_row >= MAX_BLOCKED_IN_A_ROW:
with self._lock:
self.message = ("Stopped: TikTok kept blocking requests. Wait a while, "
"or refresh your cookies file, then try again.")
self._stop.set()
with self._lock:
for item in self.items:
if item["status"] in ("queued", "downloading", "waiting"):
item["status"] = "skipped"
done = sum(i["status"] == "done" for i in self.items)
failed = sum(i["status"] == "failed" for i in self.items)
if not self.message:
self.message = f"Downloaded {done}, failed {failed}" + (
f", skipped {total - done - failed}" if done + failed < total else "")
self.state = "stopped" if self._stop.is_set() else "done"
self.on_event(self.message)