Compare commits

..
2 Commits
Author SHA1 Message Date
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
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
9 changed files with 1526 additions and 15 deletions

No files matched your search

+3 -1
View File
@@ -1,2 +1,4 @@
TELEGRAM_API_TOKEN=
BOT_AUTH_PASSWORD=
BOT_AUTH_PASSWORD=
# Optional: cookies.txt exported from your browser, used by downloader.py and the bot
TIKDOWN_COOKIES=
+7 -1
View File
@@ -3,7 +3,7 @@ youtube-dl*
yt-dlp*
authorized_users.txt
.env
__pycache__/*
__pycache__/
metadata.json
*.log
@@ -11,3 +11,9 @@ in.txt
in/*
downloaded_ids.txt
failed.txt
# Browser session cookies (never commit)
cookies.txt
# Personal list of profiles for the profile downloader UI
favorites.txt
+11 -2
View File
@@ -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
+28 -11
View File
@@ -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):
+141
View File
@@ -0,0 +1,141 @@
# 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 <http://127.0.0.1:5050> (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).
### Favorites
Put profiles you open often in `favorites.txt` in this folder, one per line (anything the
profile box accepts: username, `@username`, profile URL, post link or secUid). Lines starting
with `#` are ignored. They show up as buttons under the profile box; click one to load that
profile. The file is read each time the page loads, so just reload after editing it.
`favorites.txt` is git-ignored.
```
# favorites.txt
some.username
@another.user
MS4wLjABAAAA...
```
## 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/<username>/
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
2026-11-21 20-37-01 7710726500621782294 story.mp4 video story
2026-11-21 20-37-01 7710726500621782295 01 story.jpg photo story, slide 1
.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 |
| `favorites.txt` | your favorite profiles for the web UI (optional, git-ignored) |
Failed-link bookkeeping is shared with the single-post downloader (`../downloader.py`).
+178
View File
@@ -0,0 +1,178 @@
"""
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 "")
FAVORITES_FILE = os.path.join(core.ROOT, "favorites.txt")
@app.get("/api/favorites")
def favorites():
"""Profiles listed in favorites.txt: one username, link or ID per line, # for comments.
Read on every request, so edits show up after reloading the page."""
entries = []
try:
with open(FAVORITES_FILE, encoding="utf-8-sig") as f:
for line in f:
entry = line.strip()
if entry and not entry.startswith("#") and entry not in entries:
entries.append(entry)
except FileNotFoundError:
pass
return jsonify(favorites=entries)
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()
+624
View File
@@ -0,0 +1,624 @@
"""
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)
+69
View File
@@ -0,0 +1,69 @@
"""
Download every new post (and story) from a TikTok profile.
python main.py <username | @username | profile URL | secUid> [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())
+465
View File
@@ -0,0 +1,465 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="referrer" content="no-referrer">
<title>Profile Downloader</title>
<style>
:root {
--bg: #f6f6f4; --surface: #ffffff; --surface-2: #efefec; --text: #1c1c1a; --muted: #6b6b66;
--border: #dcdcd6; --accent: #e5304f; --accent-text: #ffffff; --ok: #1f8a4c; --warn: #b26a00; --bad: #c62828;
--ring: rgba(229, 48, 79, .35); --shadow: 0 1px 2px rgba(0,0,0,.06), 0 4px 16px rgba(0,0,0,.05);
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #121212; --surface: #1c1c1c; --surface-2: #262626; --text: #ececea; --muted: #9a9a94;
--border: #333331; --accent: #ff4d6a; --accent-text: #ffffff; --ok: #4cc07f; --warn: #f0a63a; --bad: #ff6b6b;
--ring: rgba(255, 77, 106, .4); --shadow: 0 1px 2px rgba(0,0,0,.4);
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; }
main { max-width: 1280px; margin: 0 auto; padding: 20px 16px 140px; }
h1 { font-size: 20px; margin: 0 0 14px; letter-spacing: -.01em; }
h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 22px 0 10px; display: flex; gap: 8px; align-items: center; }
h2 .count { background: var(--surface-2); color: var(--text); border-radius: 999px; padding: 0 8px; font-size: 12px; letter-spacing: 0; }
button, input { font: inherit; color: inherit; }
button { border: 1px solid var(--border); background: var(--surface); padding: 7px 12px; border-radius: 8px; cursor: pointer; }
button:hover:not(:disabled) { background: var(--surface-2); }
button:disabled { opacity: .45; cursor: default; }
button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); font-weight: 600; }
button.primary:hover:not(:disabled) { filter: brightness(1.05); background: var(--accent); }
button:focus-visible, input:focus-visible { outline: 2px solid var(--ring); outline-offset: 1px; }
.panel { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px; box-shadow: var(--shadow); }
.search { display: flex; gap: 8px; }
.search input { flex: 1; min-width: 0; padding: 9px 12px; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); }
.options { display: flex; flex-wrap: wrap; gap: 8px 18px; margin-top: 10px; color: var(--muted); align-items: center; }
.options label { display: inline-flex; gap: 6px; align-items: center; cursor: pointer; }
.options input[type=text] { width: min(420px, 100%); padding: 5px 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); }
.favorites { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border); }
.favorites .label { color: var(--muted); margin-right: 4px; }
.favorites button { padding: 4px 11px; border-radius: 999px; font-size: 13px; max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.favorites button[aria-current=true] { border-color: var(--accent); color: var(--accent); font-weight: 600; }
.status { margin-top: 10px; color: var(--muted); min-height: 1.4em; }
.status.error { color: var(--bad); }
.spinner { display: inline-block; width: 12px; height: 12px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: -2px; margin-right: 6px; }
@keyframes spin { to { transform: rotate(360deg); } }
.profile { display: flex; gap: 12px; align-items: center; margin-top: 16px; }
.profile img { width: 44px; height: 44px; border-radius: 50%; background: var(--surface-2); object-fit: cover; }
.profile .name { font-weight: 600; font-size: 16px; }
.profile .meta { color: var(--muted); }
.toolbar { position: sticky; top: 0; z-index: 5; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 10px 0; margin-top: 8px; background: var(--bg); border-bottom: 1px solid var(--border); }
.toolbar .spacer { flex: 1; }
.toolbar .selected { color: var(--muted); }
.chips { display: inline-flex; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
.chips button { border: 0; border-radius: 0; border-right: 1px solid var(--border); }
.chips button:last-child { border-right: 0; }
.chips button[aria-pressed=true] { background: var(--surface-2); font-weight: 600; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; }
.card { position: relative; background: var(--surface); border: 1px solid var(--border); border-radius: 10px; overflow: hidden; cursor: pointer; user-select: none; transition: box-shadow .12s, border-color .12s; }
.card:hover { border-color: var(--muted); }
.card.selected { border-color: var(--accent); box-shadow: 0 0 0 2px var(--ring); }
.card.story { border-style: dashed; }
.thumb { position: relative; aspect-ratio: 9 / 13; background: var(--surface-2); }
.thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
.thumb .noimg { position: absolute; inset: 0; display: grid; place-items: center; color: var(--muted); font-size: 12px; }
.check { position: absolute; top: 8px; right: 8px; width: 22px; height: 22px; border-radius: 6px; background: rgba(0,0,0,.45); border: 2px solid #fff; display: grid; place-items: center; color: #fff; font-size: 14px; }
.card.selected .check { background: var(--accent); border-color: var(--accent); }
.card.selected .check::after { content: "✓"; font-weight: 700; }
.badge { position: absolute; left: 8px; padding: 1px 7px; border-radius: 999px; font-size: 11px; font-weight: 600; background: rgba(0,0,0,.6); color: #fff; }
.badge.type { bottom: 8px; }
.badge.state { top: 8px; }
.badge.downloaded, .badge.done { background: var(--ok); }
.badge.failed { background: var(--bad); }
.badge.downloading, .badge.waiting, .badge.queued { background: var(--warn); }
.info { padding: 7px 9px 9px; }
.info .date { font-size: 12px; color: var(--muted); }
.info .caption { font-size: 12px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; min-height: 2.9em; word-break: break-word; }
.empty { color: var(--muted); padding: 6px 0 4px; }
.progress { position: fixed; left: 0; right: 0; bottom: 0; z-index: 10; background: var(--surface); border-top: 1px solid var(--border); box-shadow: 0 -4px 16px rgba(0,0,0,.08); }
.progress .inner { max-width: 1280px; margin: 0 auto; padding: 12px 16px; display: grid; gap: 8px; }
.progress .row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.progress .row .text { flex: 1; min-width: 200px; }
.bar { height: 6px; background: var(--surface-2); border-radius: 999px; overflow: hidden; }
.bar > div { height: 100%; width: 0; background: var(--accent); transition: width .3s; }
.failures { max-height: 120px; overflow: auto; font-size: 12px; color: var(--bad); margin: 0; padding-left: 18px; }
.hidden { display: none !important; }
@media (max-width: 560px) {
.grid { grid-template-columns: repeat(2, 1fr); gap: 8px; }
.search { flex-direction: column; }
}
</style>
</head>
<body>
<main>
<h1>Profile Downloader</h1>
<form class="panel" id="form" autocomplete="off">
<div class="search">
<input id="profile" placeholder="Username, @username, profile URL, post link, or secUid" required>
<button class="primary" id="loadBtn" type="submit">Load profile</button>
</div>
<div class="options">
<label><input type="checkbox" id="useCookies" checked> Use cookies</label>
<input type="text" id="cookies" placeholder="Path to cookies.txt (optional)">
<label><input type="checkbox" id="stories" checked> Include stories</label>
<label><input type="checkbox" id="refresh"> Fetch fresh list (ignore cache)</label>
</div>
<div class="favorites hidden" id="favorites" role="group" aria-label="Favorites"><span class="label">Favorites</span></div>
<div class="status" id="status"></div>
</form>
<section id="results" class="hidden">
<div class="profile">
<img id="avatar" alt="">
<div>
<div class="name" id="nickname"></div>
<div class="meta" id="profileMeta"></div>
</div>
</div>
<div class="toolbar">
<button type="button" id="selectAll">Select all</button>
<button type="button" id="selectNone">Deselect all</button>
<button type="button" id="selectNew">Select not downloaded</button>
<div class="chips" role="group" aria-label="Filter">
<button type="button" data-filter="all" aria-pressed="true">All</button>
<button type="button" data-filter="video" aria-pressed="false">Videos</button>
<button type="button" data-filter="photo" aria-pressed="false">Photos</button>
<button type="button" data-filter="new" aria-pressed="false">Not downloaded</button>
</div>
<span class="spacer"></span>
<span class="selected" id="selectedCount">0 selected</span>
<button type="button" class="primary" id="downloadBtn" disabled>Download selected</button>
</div>
<h2>Stories <span class="count" id="storyCount">0</span></h2>
<div class="grid" id="storyGrid"></div>
<div class="empty hidden" id="storyEmpty">No active stories.</div>
<h2>Posts <span class="count" id="postCount">0</span></h2>
<div class="grid" id="postGrid"></div>
<div class="empty hidden" id="postEmpty">No posts match this filter.</div>
</section>
</main>
<div class="progress hidden" id="progress">
<div class="inner">
<div class="row">
<div class="text" id="progressText"></div>
<button type="button" id="stopBtn">Stop</button>
<button type="button" id="closeBtn" class="hidden">Close</button>
</div>
<div class="bar"><div id="progressBar"></div></div>
<ol class="failures hidden" id="failures"></ol>
</div>
</div>
<script>
const $ = (id) => document.getElementById(id);
const state = { listing: null, selected: new Set(), filter: "all", lastClicked: null, job: null, polling: null };
const STATUS_LABEL = { downloaded: "Downloaded", failed: "Failed", done: "Downloaded", downloading: "Downloading…", waiting: "Waiting…", queued: "Queued" };
async function api(path, body) {
const options = body === undefined ? {} : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
const res = await fetch(path, options);
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || `Request failed (${res.status})`);
return data;
}
function setStatus(text, kind) {
const el = $("status");
el.className = "status" + (kind === "error" ? " error" : "");
el.innerHTML = "";
if (kind === "busy") el.insertAdjacentHTML("afterbegin", '<span class="spinner"></span>');
el.append(text || "");
}
function requestBody(extra) {
return Object.assign({ use_cookies: $("useCookies").checked, cookies: $("cookies").value.trim() }, extra);
}
// --- Loading ---
$("form").addEventListener("submit", async (event) => {
event.preventDefault();
const profile = $("profile").value.trim();
if (!profile || $("loadBtn").disabled) return;
$("loadBtn").disabled = true;
setFavoritesDisabled(true);
markFavorite(profile);
setStatus("Loading profile…", "busy");
try {
let task = await api("/api/profile", requestBody({ profile, refresh: $("refresh").checked, stories: $("stories").checked }));
while (task.state === "running") {
setStatus(task.message, "busy");
await new Promise((resolve) => setTimeout(resolve, 800));
task = await api("/api/profile/status");
}
if (task.state === "error") throw new Error(task.message);
const listing = task.result;
state.listing = listing;
state.selected.clear();
$("refresh").checked = false;
const age = listing.cache_age > 60 ? ` · list cached ${Math.round(listing.cache_age / 60)} min ago` : "";
setStatus(`Loaded @${listing.profile.username}${age}${listing.stories_note ? " · " + listing.stories_note : ""}`);
render();
} catch (err) {
setStatus(err.message, "error");
} finally {
$("loadBtn").disabled = false;
setFavoritesDisabled(false);
}
});
// --- Favorites (favorites.txt) ---
function favoriteLabel(entry) {
if (/^MS4wLjABAAAA/.test(entry)) return entry.slice(0, 18) + "…"; // secUid
const user = entry.match(/tiktok\.com\/@([\w.-]+)/i);
if (user) return "@" + user[1];
if (/^https?:/i.test(entry)) return entry.replace(/^https?:\/\/(www\.)?/i, "");
if (/^\d+$/.test(entry)) return entry; // numeric ID
return "@" + entry.replace(/^@/, "");
}
function renderFavorites(entries) {
const box = $("favorites");
box.querySelectorAll("button").forEach((b) => b.remove());
for (const entry of entries) {
const button = document.createElement("button");
button.type = "button";
button.textContent = favoriteLabel(entry);
button.title = entry;
button.dataset.entry = entry;
button.onclick = () => { $("profile").value = entry; $("form").requestSubmit(); };
box.append(button);
}
box.classList.toggle("hidden", entries.length === 0);
}
function setFavoritesDisabled(disabled) {
$("favorites").querySelectorAll("button").forEach((b) => { b.disabled = disabled; });
}
function markFavorite(profile) {
$("favorites").querySelectorAll("button").forEach((b) => b.setAttribute("aria-current", b.dataset.entry === profile));
}
// --- Rendering ---
function allItems() { return state.listing ? [...state.listing.stories, ...state.listing.posts] : []; }
function visible(item) {
const f = state.filter;
return f === "all" || (f === "new" ? item.status !== "downloaded" : item.type === f);
}
function visibleItems() { return allItems().filter(visible); }
function formatDuration(seconds) {
return seconds ? `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}` : "";
}
function card(item) {
const el = document.createElement("div");
el.className = "card" + (item.kind === "story" ? " story" : "");
el.dataset.id = item.id;
el.tabIndex = 0;
el.setAttribute("role", "checkbox");
const thumb = document.createElement("div");
thumb.className = "thumb";
if (item.thumb) {
const img = document.createElement("img");
img.loading = "lazy"; img.referrerPolicy = "no-referrer"; img.alt = ""; img.src = item.thumb;
img.onerror = () => { img.remove(); thumb.insertAdjacentHTML("afterbegin", '<div class="noimg">No preview</div>'); };
thumb.append(img);
} else {
thumb.innerHTML = '<div class="noimg">No preview</div>';
}
const type = document.createElement("span");
type.className = "badge type";
type.textContent = item.type === "photo" ? `Photos · ${item.images}` : `Video ${formatDuration(item.duration)}`.trim();
const status = document.createElement("span");
status.className = "badge state";
const check = document.createElement("span");
check.className = "check";
thumb.append(type, status, check);
const info = document.createElement("div");
info.className = "info";
const date = document.createElement("div");
date.className = "date";
date.textContent = (item.kind === "story" ? "Story · " : "") + item.date;
const caption = document.createElement("div");
caption.className = "caption";
caption.textContent = item.caption || "—";
caption.title = item.caption;
info.append(date, caption);
el.append(thumb, info);
el.addEventListener("click", (event) => toggle(item.id, event.shiftKey));
el.addEventListener("keydown", (event) => { if (event.key === " " || event.key === "Enter") { event.preventDefault(); toggle(item.id, event.shiftKey); } });
updateCard(el, item);
return el;
}
function currentStatus(item) {
const jobItem = state.job && state.job.items.find((i) => i.id === item.id);
if (jobItem && jobItem.status !== "skipped") return jobItem.status === "done" ? "downloaded" : jobItem.status;
return item.status;
}
function updateCard(el, item) {
const status = currentStatus(item);
const badge = el.querySelector(".badge.state");
badge.className = "badge state " + status;
badge.textContent = STATUS_LABEL[status] || "";
badge.classList.toggle("hidden", !STATUS_LABEL[status]);
const jobItem = state.job && state.job.items.find((i) => i.id === item.id);
badge.title = jobItem && jobItem.error ? jobItem.error : "";
const selected = state.selected.has(item.id);
el.classList.toggle("selected", selected);
el.setAttribute("aria-checked", selected);
}
function render() {
const listing = state.listing;
$("results").classList.remove("hidden");
$("avatar").src = listing.profile.avatar || "";
$("nickname").textContent = listing.profile.nickname || listing.profile.username;
const items = allItems();
const done = items.filter((i) => i.status === "downloaded").length;
$("profileMeta").textContent = `@${listing.profile.username} · ${listing.posts.length} posts · ${listing.stories.length} stories · ${done} downloaded · ${items.length - done} not downloaded`;
for (const [list, grid, count, empty] of [[listing.stories, "storyGrid", "storyCount", "storyEmpty"], [listing.posts, "postGrid", "postCount", "postEmpty"]]) {
const shown = list.filter(visible);
$(grid).replaceChildren(...shown.map(card));
$(count).textContent = shown.length === list.length ? list.length : `${shown.length} / ${list.length}`;
$(empty).classList.toggle("hidden", shown.length > 0);
}
$("storyEmpty").textContent = listing.stories.length ? "No stories match this filter." : (listing.stories_note || "No active stories.");
updateSelection();
}
function refreshCards() {
const byId = new Map(allItems().map((i) => [i.id, i]));
document.querySelectorAll(".card").forEach((el) => updateCard(el, byId.get(el.dataset.id)));
}
// --- Selection ---
function toggle(id, range) {
const order = visibleItems().map((i) => i.id);
if (range && state.lastClicked && order.includes(state.lastClicked)) {
const [a, b] = [order.indexOf(state.lastClicked), order.indexOf(id)].sort((x, y) => x - y);
const select = !state.selected.has(id);
order.slice(a, b + 1).forEach((i) => select ? state.selected.add(i) : state.selected.delete(i));
} else {
state.selected.has(id) ? state.selected.delete(id) : state.selected.add(id);
}
state.lastClicked = id;
updateSelection();
}
function updateSelection() {
refreshCards();
const n = state.selected.size;
$("selectedCount").textContent = `${n} selected`;
$("downloadBtn").disabled = n === 0 || isRunning();
$("downloadBtn").textContent = n ? `Download ${n} selected` : "Download selected";
}
$("selectAll").onclick = () => { visibleItems().forEach((i) => state.selected.add(i.id)); updateSelection(); };
$("selectNone").onclick = () => { state.selected.clear(); updateSelection(); };
$("selectNew").onclick = () => {
state.selected.clear();
visibleItems().filter((i) => currentStatus(i) !== "downloaded").forEach((i) => state.selected.add(i.id));
updateSelection();
};
document.querySelectorAll(".chips button").forEach((button) => {
button.onclick = () => {
state.filter = button.dataset.filter;
document.querySelectorAll(".chips button").forEach((b) => b.setAttribute("aria-pressed", b === button));
render();
};
});
// --- Downloading ---
function isRunning() { return state.job && ["running", "stopping"].includes(state.job.state); }
$("downloadBtn").onclick = async () => {
const order = allItems().map((i) => i.id).filter((id) => state.selected.has(id));
try {
state.job = await api("/api/download", requestBody({ username: state.listing.profile.username, ids: order }));
showJob();
poll();
} catch (err) {
setStatus(err.message, "error");
}
};
$("stopBtn").onclick = async () => { state.job = await api("/api/job/stop", {}); showJob(); };
$("closeBtn").onclick = () => $("progress").classList.add("hidden");
function poll() {
clearInterval(state.polling);
state.polling = setInterval(async () => {
try { state.job = await api("/api/job"); } catch { return; }
showJob();
if (!isRunning()) {
clearInterval(state.polling);
// Fold the results into the listing so badges stay after closing the panel
for (const jobItem of state.job.items) {
const item = allItems().find((i) => i.id === jobItem.id);
if (item && jobItem.status === "done") { item.status = "downloaded"; state.selected.delete(item.id); }
if (item && jobItem.status === "failed") item.status = "failed";
}
render();
}
}, 1000);
}
function showJob() {
const job = state.job;
if (!job) return;
$("progress").classList.remove("hidden");
const c = job.counts || {};
const finished = (c.done || 0) + (c.failed || 0) + (c.skipped || 0);
const current = job.items.find((i) => i.status === "downloading" || i.status === "waiting");
let text = `${c.done || 0} of ${job.total} downloaded` + (c.failed ? ` · ${c.failed} failed` : "");
if (current) text += ` · ${current.status === "waiting" ? current.error : "downloading " + (current.kind === "story" ? "story " : "post ") + current.id}`;
if (job.state === "stopping") text += " · stopping after this post…";
if (!isRunning()) text = job.message;
$("progressText").textContent = text;
$("progressBar").style.width = `${job.total ? (finished / job.total) * 100 : 0}%`;
$("stopBtn").classList.toggle("hidden", !isRunning());
$("stopBtn").disabled = job.state === "stopping";
$("closeBtn").classList.toggle("hidden", isRunning());
const failed = job.items.filter((i) => i.status === "failed");
$("failures").replaceChildren(...failed.map((i) => {
const li = document.createElement("li");
li.textContent = `${i.id}: ${i.error}`;
return li;
}));
$("failures").classList.toggle("hidden", failed.length === 0);
updateSelection();
}
// --- Start-up ---
(async () => {
try {
const config = await api("/api/config");
$("cookies").placeholder = config.default_cookies ? `Default: ${config.default_cookies}` : "Path to cookies.txt (optional)";
renderFavorites((await api("/api/favorites")).favorites);
const job = await api("/api/job");
if (job) { state.job = job; showJob(); if (isRunning()) poll(); }
} catch { /* server not ready yet */ }
$("profile").focus();
})();
</script>
</body>
</html>