From d12483d53cd9b235b064d85e9a849c705a547175 Mon Sep 17 00:00:00 2001 From: X4Lo Date: Sun, 22 Nov 2026 03:57:49 +0000 Subject: [PATCH] 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. --- .env.example | 4 +- .gitignore | 5 +- README.md | 13 +- downloader.py | 39 +- profile-downloader/README.md | 123 ++++++ profile-downloader/app.py | 159 +++++++ profile-downloader/core.py | 616 +++++++++++++++++++++++++++ profile-downloader/main.py | 69 +++ profile-downloader/static/index.html | 423 ++++++++++++++++++ 9 files changed, 1436 insertions(+), 15 deletions(-) create mode 100644 profile-downloader/README.md create mode 100644 profile-downloader/app.py create mode 100644 profile-downloader/core.py create mode 100644 profile-downloader/main.py create mode 100644 profile-downloader/static/index.html diff --git a/.env.example b/.env.example index 6f9fcf6..c4fdde3 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,4 @@ TELEGRAM_API_TOKEN= -BOT_AUTH_PASSWORD= \ No newline at end of file +BOT_AUTH_PASSWORD= +# Optional: cookies.txt exported from your browser, used by downloader.py and the bot +TIKDOWN_COOKIES= diff --git a/.gitignore b/.gitignore index 45fca6d..f0d862a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ youtube-dl* yt-dlp* authorized_users.txt .env -__pycache__/* +__pycache__/ metadata.json *.log @@ -11,3 +11,6 @@ in.txt in/* downloaded_ids.txt failed.txt + +# Browser session cookies (never commit) +cookies.txt diff --git a/README.md b/README.md index c1b5ca6..de65ca4 100644 --- a/README.md +++ b/README.md @@ -36,14 +36,23 @@ 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) +# Optional: use your browser's cookies (for private or age-restricted posts) +python downloader.py --cookies cookies.txt https://www.tiktok.com/@user/video/123456789 + +# Options: --delay SECONDS, --force (ignore downloaded_ids.txt), --cookies FILE, -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`. +`TIKDOWN_COOKIES` (cookies.txt for private posts; also used by the Telegram bot), `TIKDOWN_DELAY`. +Cookies are off unless you pass `--cookies` or set `TIKDOWN_COOKIES`. `cookies.txt` is git-ignored. + +## Profile downloader + +To download a whole profile — or pick posts and stories from it in a web UI — see +[profile-downloader/README.md](profile-downloader/README.md). ## Downloads diff --git a/downloader.py b/downloader.py index 6b02e48..87d168b 100644 --- a/downloader.py +++ b/downloader.py @@ -149,32 +149,35 @@ def save_downloaded_id(video_id: str) -> None: f.write(video_id + "\n") -def _read_failed() -> List[str]: - if not os.path.exists(FAILED_FILE): +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(FAILED_FILE, "r", encoding="utf-8") as f: + 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) -> None: +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 = url.strip() + url, path = url.strip(), path or FAILED_FILE with _file_lock: - if url in _read_failed(): + if url in read_failed_urls(path): return - with open(FAILED_FILE, "a", encoding="utf-8") as f: + 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] = ()) -> None: +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 = {u.strip() for u in urls}, set(ids) + urls, ids, path = {u.strip() for u in urls}, set(ids), path or FAILED_FILE with _file_lock: - current = _read_failed() + 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(FAILED_FILE, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8") as f: f.writelines(u + "\n" for u in kept) @@ -355,6 +358,11 @@ def main(argv: Optional[List[str]] = None) -> int: 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( @@ -362,6 +370,15 @@ def main(argv: Optional[List[str]] = None) -> int: 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): diff --git a/profile-downloader/README.md b/profile-downloader/README.md new file mode 100644 index 0000000..6d1ed5d --- /dev/null +++ b/profile-downloader/README.md @@ -0,0 +1,123 @@ +# Profile Downloader + +Downloads posts and stories from a TikTok profile — through a local web UI where you pick +exactly which posts you want, or from the command line. + +Built on [gallery-dl](https://github.com/mikf/gallery-dl), which (unlike yt-dlp) saves the +actual images of photo posts, not just their background music. + +## Setup + +```bash +pip install gallery-dl flask requests +``` + +### Cookies (recommended) + +TikTok often refuses profile requests from logged-out visitors. Export your browser's +TikTok cookies to `cookies.txt` in this folder (for example with the "Get cookies.txt LOCALLY" +browser extension, while logged in to tiktok.com). It is picked up automatically; you can also +point to another file, or turn cookies off. `cookies.txt` is git-ignored — never share it, it +logs in as you. + +## Web UI + +```bash +python app.py +``` + +Opens (use `--port` to change it, `--no-browser` to not open a tab). +The server only listens on your own computer. + +1. Enter a **username**, `@username`, profile URL, link to one of the profile's posts, or + **secUid** (`MS4wLjABAAAA…`), then **Load profile**. +2. **Stories** are pinned at the top, followed by all **posts**, newest first. Each card shows + the cover, date, caption, type (video length or number of photos) and whether it's already + downloaded or failed before. +3. Select posts: + - click a card (or press Space/Enter on it) to select or deselect it + - Shift-click to select a range + - **Select all** / **Deselect all** / **Select not downloaded** (these act on the current filter) + - filter by **Videos**, **Photos** or **Not downloaded** +4. **Download selected**. A panel at the bottom shows progress and any failures; **Stop** ends + the run after the current post. + +The post list is cached for an hour. Tick **Fetch fresh list** to reload it (e.g. to see new +posts or stories). + +## Command line + +Downloads everything on the profile that isn't downloaded yet: + +```bash +python main.py some.username +python main.py https://www.tiktok.com/@some.username --limit 20 +python main.py some.username --retry-failed +``` + +| Option | Meaning | +| --- | --- | +| `--cookies FILE` | cookies file to use (default: `cookies.txt` here, if present) | +| `--no-cookies` | don't use cookies | +| `--refresh` | ignore the cached post list | +| `--no-stories` | skip stories | +| `--retry-failed` | only retry posts in `failed.txt` | +| `--limit N` | download at most N posts this run, newest first | +| `--delay SECONDS` | pause between posts (default 1.5, plus a random extra) | +| `-v` | show gallery-dl's output when something fails | + +## Where files go + +``` +downloads/profile// + 2026-11-08 16-53-54 7705844899718958356 01.jpg photo post, slide 1 + 2026-11-08 16-53-54 7705844899718958356 02.jpg photo post, slide 2 + 2026-11-08 16-53-54 7705844899718958356.mp3 photo post music + 2026-08-06 00-57-14 7670716372560727317.mp4 video + .archive.txt IDs of downloaded posts (these are skipped / marked "Downloaded") + failed.txt links of posts that failed; removed again once they succeed + .profile.json the profile's IDs, so it doesn't need to be looked up again + .listing_cache.json cached post list +``` + +The date is the post's upload time in your local time zone. Cover thumbnails are not saved. +Files downloaded by the old version of this script (`2026-06-11 23-26 0001.image` and so on) +are left as they are, and those posts stay marked as downloaded. + +## When TikTok blocks requests + +TikTok rate-limits scrapers, usually with "403 Forbidden". + +- **Downloads** wait 30 s, 90 s and 180 s and retry. After 3 posts in a row stay blocked, the + run stops so it doesn't burn through the whole list. Wait a while (or refresh your cookies) + and download again; already-downloaded posts are skipped. +- **Photo posts** are downloaded straight from the links in the post list, so they usually still + work while post pages are blocked. Videos need their post page. +- **Loading a profile by username** needs the profile page once. If that is blocked, it tries the + pages of posts you already downloaded, then asks you to paste a **post link** or the + **secUid**. After one successful load, the profile's IDs are remembered and the page isn't + needed again. + +To find a secUid: open the profile in your browser, view the page source (Ctrl+U) and search +for `"secUid":"`. + +## Settings + +Environment variables: + +| Variable | Default | +| --- | --- | +| `PROFILE_DOWNLOAD_DIR` | `downloads/profile` in this folder | +| `PROFILE_DELAY` | `1.5` seconds between posts | +| `PROFILE_UI_PORT` | `5050` | + +## Files + +| File | Purpose | +| --- | --- | +| `app.py` | web UI server (Flask) | +| `static/index.html` | the web page | +| `main.py` | command line | +| `core.py` | listing, downloading, archive, retries — shared by both | + +Failed-link bookkeeping is shared with the single-post downloader (`../downloader.py`). diff --git a/profile-downloader/app.py b/profile-downloader/app.py new file mode 100644 index 0000000..fc2bdff --- /dev/null +++ b/profile-downloader/app.py @@ -0,0 +1,159 @@ +""" +Local web UI for the profile downloader. + + python app.py # opens http://127.0.0.1:5050 in your browser + python app.py --port 8080 --no-browser +""" + +import argparse +import logging +import os +import threading +import webbrowser + +from flask import Flask, abort, jsonify, request, send_from_directory + +import core + +app = Flask(__name__, static_folder=None) +log = logging.getLogger("profile") + +_state_lock = threading.Lock() +_listings = {} # username -> {id: record} from the latest listing +_job = None # the current/last core.DownloadJob +_listing_task = None # {"state": running|done|error, "message", "result"} +_allowed_hosts = set() + + +@app.before_request +def _local_only(): + # Blocks other websites from driving this server through your browser + # (DNS rebinding); JSON-only POSTs also force a CORS preflight that fails. + if request.host not in _allowed_hosts: + abort(403) + if request.method == "POST" and not request.is_json: + abort(415) + + +@app.get("/") +def index(): + return send_from_directory(os.path.join(core.ROOT, "static"), "index.html") + + +@app.get("/api/config") +def config(): + return jsonify(default_cookies=core.DEFAULT_COOKIES if os.path.isfile(core.DEFAULT_COOKIES) else "") + + +def _cookies_from(body: dict): + if not body.get("use_cookies", True): + return None + return core.resolve_cookies((body.get("cookies") or "").strip() or None) + + +def _run_listing(task: dict, body: dict, cookies): + def progress(message): + log.info(message) + with _state_lock: + task["message"] = message + + try: + listing = core.list_profile( + body.get("profile", ""), + cookies, + refresh=bool(body.get("refresh")), + include_stories=body.get("stories", True), + progress=progress, + ) + except Exception as e: # ProfileError, or anything unexpected from gallery-dl + if not isinstance(e, core.ProfileError): + log.exception("Listing failed") + with _state_lock: + task.update(state="error", message=str(e)) + return + username = listing["profile"]["username"] + with _state_lock: + _listings[username] = {r["id"]: r for r in listing["stories"] + listing["posts"]} + task.update(state="done", result=listing) + + +@app.post("/api/profile") +def load_profile(): + """Starts loading a profile in the background; poll /api/profile/status.""" + global _listing_task + body = request.get_json() + try: + core.parse_profile_input(body.get("profile", "")) + cookies = _cookies_from(body) + except core.ProfileError as e: + return jsonify(error=str(e)), 400 + with _state_lock: + if _listing_task and _listing_task["state"] == "running": + return jsonify(error="A profile is already loading."), 409 + _listing_task = {"state": "running", "message": "Starting...", "result": None} + threading.Thread(target=_run_listing, args=(_listing_task, body, cookies), daemon=True).start() + return jsonify(_listing_task) + + +@app.get("/api/profile/status") +def profile_status(): + with _state_lock: + return jsonify(_listing_task) + + +@app.post("/api/download") +def start_download(): + global _job + body = request.get_json() + username = body.get("username", "") + with _state_lock: + if _job and _job.state in ("running", "stopping"): + return jsonify(error="A download is already running."), 409 + known = _listings.get(username) + if not known: + return jsonify(error="Load the profile first."), 400 + records = [known[i] for i in body.get("ids", []) if i in known] + if not records: + return jsonify(error="Select at least one post."), 400 + try: + cookies = _cookies_from(body) + except core.ProfileError as e: + return jsonify(error=str(e)), 400 + _job = core.DownloadJob(username, records, cookies, on_event=log.info) + threading.Thread(target=_job.run, daemon=True).start() + return jsonify(_job.snapshot()) + + +@app.get("/api/job") +def job_status(): + with _state_lock: + return jsonify(_job.snapshot() if _job else None) + + +@app.post("/api/job/stop") +def stop_job(): + with _state_lock: + if _job: + _job.stop() + return jsonify(_job.snapshot() if _job else None) + + +def main(): + parser = argparse.ArgumentParser(description="Web UI for the TikTok profile downloader.") + parser.add_argument("--port", type=int, default=int(os.getenv("PROFILE_UI_PORT", "5050"))) + parser.add_argument("--no-browser", action="store_true", help="don't open the browser automatically") + args = parser.parse_args() + + logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO) + logging.getLogger("werkzeug").setLevel(logging.WARNING) + _allowed_hosts.update({f"127.0.0.1:{args.port}", f"localhost:{args.port}"}) + + url = f"http://127.0.0.1:{args.port}" + log.info(f"Profile downloader UI: {url} (Ctrl+C to quit)") + if not args.no_browser: + threading.Timer(1.0, webbrowser.open, [url]).start() + app.run(host="127.0.0.1", port=args.port, threaded=True) + + +if __name__ == "__main__": + main() diff --git a/profile-downloader/core.py b/profile-downloader/core.py new file mode 100644 index 0000000..e20a23c --- /dev/null +++ b/profile-downloader/core.py @@ -0,0 +1,616 @@ +""" +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 + +# " [ ].", 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) +# Seconds + post ID keep posts made in the same minute from colliding. +FILENAME_FORMAT = "{date:Olocal/%Y-%m-%d %H-%M-%S} {id}{num:? //>02}.{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") + targets = [(f"{stamp} {record['id']} {n:02}", url) for n, url in enumerate(media["images"], start=1)] + if media.get("music"): + targets.append((f"{stamp} {record['id']}", 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) + + +def download_post(url: str, post_id: str, directory: str, cookies: Optional[str]) -> Outcome: + """Downloads one post (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] + 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 "# " 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 /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) diff --git a/profile-downloader/main.py b/profile-downloader/main.py new file mode 100644 index 0000000..a336b62 --- /dev/null +++ b/profile-downloader/main.py @@ -0,0 +1,69 @@ +""" +Download every new post (and story) from a TikTok profile. + + python main.py [options] + +For picking individual posts, use the web UI instead: python app.py +""" + +import argparse +import logging +import sys + +import core + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description="Download new posts from a TikTok profile.") + parser.add_argument("profile", help="username, @username, profile URL, or secUid (MS4wLjABAAAA...)") + parser.add_argument("--cookies", metavar="FILE", + help=f"cookies.txt exported from your browser (default: {core.DEFAULT_COOKIES} if it exists)") + parser.add_argument("--no-cookies", action="store_true", help="don't use any cookies file") + parser.add_argument("--refresh", action="store_true", help="ignore the cached post list and fetch it again") + parser.add_argument("--no-stories", action="store_true", help="skip the profile's stories") + parser.add_argument("--retry-failed", action="store_true", help="only retry posts listed in failed.txt") + parser.add_argument("--limit", type=int, help="download at most N posts this run (newest first)") + parser.add_argument("--delay", type=float, default=core.DOWNLOAD_DELAY, help="seconds between posts") + parser.add_argument("-v", "--verbose", action="store_true", help="show gallery-dl 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) + log = logging.getLogger("profile") + + try: + cookies = None if args.no_cookies else core.resolve_cookies(args.cookies) + if cookies: + log.info(f"Using cookies from {cookies}") + listing = core.list_profile(args.profile, cookies, refresh=args.refresh, + include_stories=not args.no_stories) + except core.ProfileError as e: + log.error(str(e)) + return 2 + + username = listing["profile"]["username"] + records = listing["stories"] + listing["posts"] + wanted = ("failed",) if args.retry_failed else ("new", "failed") + todo = [r for r in records if r["status"] in wanted] + if args.limit: + todo = todo[: args.limit] + + log.info(f"@{username}: {len(records)} items, " + f"{sum(r['status'] == 'downloaded' for r in records)} already downloaded, {len(todo)} to download") + if not todo: + log.info("Everything is already up to date.") + return 0 + + job = core.DownloadJob(username, todo, cookies, delay=args.delay, on_event=log.info) + try: + job.run() + except KeyboardInterrupt: + job.stop() + log.warning("Interrupted.") + return 130 + log.info(f"Files are in {core.profile_dir(username)}") + return 1 if job.snapshot()["counts"].get("failed") else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/profile-downloader/static/index.html b/profile-downloader/static/index.html new file mode 100644 index 0000000..253009b --- /dev/null +++ b/profile-downloader/static/index.html @@ -0,0 +1,423 @@ + + + + + + +Profile Downloader + + + +
+

Profile Downloader

+ +
+ +
+ + + + +
+
+
+ + +
+ + + + + +