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.
This commit is contained in:
1 parent
1c17487ce4
commit
d12483d53c
9 files changed
+1436
-15
No files matched your search
@@ -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()
|
||||
Reference in new issue
Block a user