diff --git a/.gitignore b/.gitignore index f0d862a..73a0f4c 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ failed.txt # Browser session cookies (never commit) cookies.txt + +# Personal list of profiles for the profile downloader UI +favorites.txt diff --git a/profile-downloader/README.md b/profile-downloader/README.md index 6d1ed5d..0435626 100644 --- a/profile-downloader/README.md +++ b/profile-downloader/README.md @@ -45,6 +45,21 @@ The server only listens on your own computer. 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: @@ -74,6 +89,8 @@ downloads/profile// 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 @@ -119,5 +136,6 @@ Environment variables: | `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`). diff --git a/profile-downloader/app.py b/profile-downloader/app.py index fc2bdff..6a22b26 100644 --- a/profile-downloader/app.py +++ b/profile-downloader/app.py @@ -45,6 +45,25 @@ 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 diff --git a/profile-downloader/core.py b/profile-downloader/core.py index e20a23c..4fb2f0d 100644 --- a/profile-downloader/core.py +++ b/profile-downloader/core.py @@ -33,12 +33,18 @@ LISTING_CACHE_TTL = 3600 # seconds before a cached profile listing is fetched a 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. +# " [ ][ story].", 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. -FILENAME_FORMAT = "{date:Olocal/%Y-%m-%d %H-%M-%S} {id}{num:? //>02}.{extension}" +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 @@ -430,9 +436,10 @@ def _download_photo_post_direct(record: dict, directory: str) -> Outcome: 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)] + 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']}", media["music"])) + targets.append((f"{stamp} {record['id']}{suffix}", media["music"])) os.makedirs(directory, exist_ok=True) session = requests.Session() @@ -467,13 +474,14 @@ def download_record(record: dict, directory: str, cookies: Optional[str]) -> Out 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) + 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]) -> Outcome: - """Downloads one post (all photo slides + music, or the video) with gallery-dl.""" +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] + cmd = [sys.executable, "-P", "-m", "gallery_dl", "-D", directory, "-f", _filename_format(kind)] if cookies: cmd += ["--cookies", cookies] cmd.append(url) diff --git a/profile-downloader/static/index.html b/profile-downloader/static/index.html index 253009b..98a0c0f 100644 --- a/profile-downloader/static/index.html +++ b/profile-downloader/static/index.html @@ -38,6 +38,10 @@ .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; } @@ -107,6 +111,7 @@ +
@@ -185,8 +190,10 @@ function requestBody(extra) { $("form").addEventListener("submit", async (event) => { event.preventDefault(); const profile = $("profile").value.trim(); - if (!profile) return; + 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 })); @@ -207,9 +214,43 @@ $("form").addEventListener("submit", async (event) => { 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) { @@ -413,6 +454,7 @@ function showJob() { 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 */ }