Files
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

179 lines
5.7 KiB
Python

"""
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()