Local social media automation dashboard for TikTok, Instagram, and YouTube.
Prepare AutoSocial for open source
AutoSocial Studio contributors4771789292f0
diff --git a/.env.example b/.env.examplenew file mode 100644index 0000000..06c5819--- /dev/null+++ b/.env.example@@ -0,0 +1,52 @@+CRON_EXPRESSION=0 */2 * * *+INSTAGRAM_CRON_EXPRESSION=0 */2 * * *+YOUTUBE_CRON_EXPRESSION=0 */2 * * *+TZ=UTC+BROWSER_LOCALE=en-US+HEADLESS=false+POST_DELAY_MS=15000+POST_PUBLISH_HOLD_MS=25000+FAILURE_HOLD_MS=8000+AUTO_ADD_SOUND=false+DEFAULT_SOUND_QUERY=+RANDOM_QUEUE_ORDER=false+DEFAULT_CAPTION=+TIKTOK_UPLOAD_URL=https://www.tiktok.com/tiktokstudio/upload+INSTAGRAM_UPLOAD_URL=https://www.instagram.com/create/style/+YOUTUBE_UPLOAD_URL=https://studio.youtube.com+DASHBOARD_HOST=127.0.0.1+DASHBOARD_PORT=3000+# DASHBOARD_ALLOW_REMOTE=false++# Video uniquifier options+# UNIQUIFY_INPUT_DIR=queue/uniquify-input+# UNIQUIFY_OUTPUT_DIR=queue/uniquify-output+# UNIQUIFY_LOGO_IMAGE=user-assets/logo.png+# UNIQUIFY_INTRO_SECONDS=1+# UNIQUIFY_END_HOLD_SECONDS=0.4++# Advanced path overrides.+# The dashboard normally uses per-account folders under queue/<account>/ and .profiles/<account>/.+# These overrides are mainly useful for CLI-only or legacy default-account setups.+# QUEUE_DIR=queue/default/tiktok/pending+# POSTED_DIR=queue/default/tiktok/posted+# FAILED_DIR=queue/default/tiktok/failed+# BROWSER_PROFILE_DIR=.profile+# INSTAGRAM_QUEUE_DIR=queue/default/instagram/pending+# INSTAGRAM_POSTED_DIR=queue/default/instagram/posted+# INSTAGRAM_FAILED_DIR=queue/default/instagram/failed+# INSTAGRAM_PROFILE_DIR=.profile-instagram+# YOUTUBE_QUEUE_DIR=queue/default/youtube/pending+# YOUTUBE_POSTED_DIR=queue/default/youtube/posted+# YOUTUBE_FAILED_DIR=queue/default/youtube/failed+# YOUTUBE_PROFILE_DIR=.profile-youtube++# Auto-download and auto-post pipeline+WATCH_CHANNEL=+WATCH_INTERVAL=10+WATCH_MAX_VIDEOS=5+WATCH_MIN_VIEWS=0+AUTO_POST_PLATFORMS=tiktok,instagram,youtube++# Standalone watcher only+# ACCOUNT_ID=defaultdiff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..dfe0770--- /dev/null+++ b/.gitattributes@@ -0,0 +1,2 @@+# Auto detect text files and perform LF normalization+* text=autodiff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.mdnew file mode 100644index 0000000..e092d69--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.md@@ -0,0 +1,34 @@+---+name: Bug report+about: Report a reproducible problem+title: "[Bug]: "+labels: bug+assignees: ""+---++## What happened?++Describe the problem clearly.++## Steps to reproduce++1.+2.+3.++## Expected behavior++What did you expect to happen?++## Environment++- OS:+- Node.js version:+- Browser/Playwright installed: yes/no+- FFmpeg installed: yes/no+- Platform flow affected: TikTok / Instagram / YouTube / dashboard / downloader / uniquifier++## Logs or screenshots++Paste relevant dashboard logs or terminal output. Do not include cookies,+session data, `.env` contents, or private account details.diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.mdnew file mode 100644index 0000000..6ef3472--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.md@@ -0,0 +1,24 @@+---+name: Feature request+about: Suggest an improvement+title: "[Feature]: "+labels: enhancement+assignees: ""+---++## Problem++What workflow would this improve?++## Proposed solution++Describe the behavior you would like.++## Alternatives considered++What have you tried or considered?++## Notes++Please include any platform-specific constraints, but do not include private+account details or session data.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..a1e80a9--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,30 @@+name: CI++on:+ push:+ branches:+ - main+ pull_request:++jobs:+ check:+ runs-on: ubuntu-latest++ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: 20+ cache: npm++ - name: Install dependencies+ run: npm ci++ - name: Run checks+ run: npm run check++ - name: Audit production dependencies+ run: npm audit --omit=devdiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..a7186a3--- /dev/null+++ b/.gitignore@@ -0,0 +1,56 @@+# Dependencies+node_modules/++# Environment+.env++# Browser profiles (session data)+.profile/+.profile-instagram/+.profile-youtube/+.profiles/++# Scheduler and runtime state+.scheduler-state/+*-state.json++# Queue and render outputs+queue/*/*/posted/+queue/*/*/failed/+queue/uniquify-output/++# Auto-download runtime data+autodownload/downloads/+autodownload/profile_downloads/+autodownload/archive.txt+autodownload/yt-dlp.exe+autodownload/info.json+autodownload/*.info.json++# Legacy/manual runtime folders+downloads/+user-assets/++# Local notes+.local/++# Debug screenshots+last-*.png+.dashboard.*.log++# Saved browser pages (dev reference, root-level only)+/*.html+/*_files/++# Media files generated or dropped into runtime workflows+*.mp4+*.mov+*.webm+*.avi+*.mkv+queue/**/*.description+queue/**/*.txt++# Keep docs visible+!README.md+!SETUP.mddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..1af2849--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,53 @@+# Contributing++Thanks for helping improve AutoSocial Studio.++## Development Setup++```bash+npm ci+npx playwright install chromium+npm run doctor+npm run check+```++Start the local dashboard with:++```bash+npm run dashboard+```++Open http://127.0.0.1:3000.++## Before Opening a Pull Request++Run:++```bash+npm run check+npm audit --omit=dev+```++For changes that touch upload automation, also test the relevant platform flow+manually with a throwaway account or safe draft workflow. Platform selectors+change often, so include screenshots or logs when reporting upload breakage.++## What To Avoid Committing++Do not commit session data, queue media, downloaded videos, `.env`, debug+screenshots, yt-dlp metadata, or browser profiles. The `.gitignore` covers the+known runtime paths, but always check `git status --short` before committing.++## Code Style++- Keep changes small and tied to one behavior.+- Prefer existing CommonJS patterns used in the repo.+- Add tests for queue, scheduler, filesystem, config, and API behavior when the+ change can be tested without real social platform access.+- Avoid broad selector rewrites unless you have verified the current platform UI.++## Responsible Use++This project is for local automation workflows. Contributors should avoid+features that encourage spam, deceptive behavior, account abuse, or posting+content without rights.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..86fab37--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 AutoSocial Studio contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..1a484c6--- /dev/null+++ b/README.md@@ -0,0 +1,235 @@+# AutoSocial Studio++[](https://github.com/Katzca/AutoSocial/actions/workflows/ci.yml)+[](LICENSE)+[](package.json)++AutoSocial Studio is a local, multi-account automation dashboard for short-form+video workflows across TikTok, Instagram, and YouTube. It combines a local+Express dashboard, Playwright-powered upload flows, per-account queues,+schedulers, yt-dlp downloader utilities, and an FFmpeg-based video uniquifier.++This project is built for a local workstation. It is not a hosted SaaS app and+does not include user authentication.++++## Why This Exists++AI coding tools make it easier than ever for indie builders to ship products.+Distribution is still the hard part. AutoSocial Studio helps builders turn+launch clips, demos, product updates, and short-form experiments into a+repeatable local marketing workflow without handing account sessions to a+hosted service.++The goal is not mass posting or engagement spam. The goal is a practical+creator operations dashboard: organize accounts, prepare queues, schedule+posts, reuse captions, download reference material, and process videos from one+local control plane.++## Who It Helps++- Indie hackers launching multiple products.+- AI builders who need a repeatable content workflow after shipping with AI+ coding tools.+- Small teams that want local browser sessions instead of a hosted service+ storing account credentials.+- Maintainers and contributors experimenting with responsible automation around+ product updates, demos, and community content.++## Features++- Manage multiple brands/accounts with isolated queues and browser sessions.+- Post queued videos to TikTok, Instagram, and YouTube.+- Persist Playwright login sessions under `.profiles/<account>/<platform>`.+- Schedule posts with cron expressions, daily times, or instant-post mode.+- Download recent TikTok videos with yt-dlp and fan them out into queues.+- Scan/download TikTok profiles into `autodownload/profile_downloads`.+- Run FFmpeg-based video uniquification from the dashboard or CLI, with an+ optional user-provided logo overlay.++## Requirements++- Node.js 18++- npm+- Playwright Chromium+- FFmpeg and ffprobe in `PATH`+- Optional: `yt-dlp.exe` in `autodownload/` for downloader features++Windows is the primary target for the bundled `yt-dlp.exe` workflow, but the+dashboard and core Node services are ordinary Node.js.++## Quick Start++```bash+npm ci+npx playwright install chromium+npm run doctor+```++Create your local environment file:++```powershell+Copy-Item .env.example .env+```++Start the dashboard:++```bash+npm run dashboard+```++Open http://127.0.0.1:3000.++## Configuration++Copy `.env.example` to `.env` and review the values that matter for your+workflow.++Common settings:++- `CRON_EXPRESSION`, `INSTAGRAM_CRON_EXPRESSION`, `YOUTUBE_CRON_EXPRESSION`+- `TZ`, `BROWSER_LOCALE`+- `HEADLESS`+- `POST_DELAY_MS`, `POST_PUBLISH_HOLD_MS`, `FAILURE_HOLD_MS`+- `AUTO_ADD_SOUND`, `DEFAULT_SOUND_QUERY`+- `RANDOM_QUEUE_ORDER`+- `DEFAULT_CAPTION`+- `UNIQUIFY_LOGO_IMAGE`+- `WATCH_CHANNEL`, `WATCH_INTERVAL`, `WATCH_MAX_VIDEOS`, `WATCH_MIN_VIEWS`+- `AUTO_POST_PLATFORMS`+- `DASHBOARD_HOST`, `DASHBOARD_PORT`++Hashtag captions in `.env` should be quoted:++```env+DEFAULT_CAPTION="#mybrand #shorts"+```++The sample config ships without a default caption, watch channel, logo, or+sound query. Set those in `.env` or in the dashboard for your own workflow.++## Dashboard Security++The dashboard binds to `127.0.0.1` by default and has no authentication layer.+Keep it local.++Mutating dashboard requests include a same-origin guard so random websites+cannot blindly trigger local dashboard actions through the browser.++Binding to a non-local address is blocked unless `DASHBOARD_ALLOW_REMOTE=true`+is set. Only use that on a trusted network and only if you understand that+anyone who can reach the dashboard can operate the local automation controls.++See [SECURITY.md](SECURITY.md) for more details.++## First-Time Login++Open the dashboard, go to `Accounts`, and start a login session for each+platform you want to use. Sessions are stored on disk and reused between runs.++The CLI `login` command is still TikTok-specific:++```bash+npm run login+```++## Queue Layout++Queues are account-aware:++```text+queue/<account>/tiktok/pending+queue/<account>/instagram/pending+queue/<account>/youtube/pending+```++Successful uploads move into `posted`; failed uploads move into `failed`.++Supported video extensions:++- `.mp4`+- `.mov`+- `.webm`+- `.avi`+- `.mkv`++Caption sidecars can use the same base filename:++- `.description`+- `.txt`++## Commands++```bash+npm run dashboard+npm run doctor+npm run check+npm run login+npm run post+npm run daemon+npm run uniquify+npm run video-info -- --video "C:\path\video.mp4"+npm run autodownload+```++Notes:++- The dashboard is the preferred workflow.+- `login`, `post`, and `daemon` are TikTok CLI flows.+- Instagram and YouTube posting are managed through the dashboard.+- `uniquify` and `video-info` require FFmpeg and ffprobe.+- `autodownload` requires yt-dlp.++## Development++Run the local checks:++```bash+npm run check+npm audit --omit=dev+```++The test suite focuses on local logic that does not require live social+platform access: queue handling, sidecars, filesystem archiving, scheduler time+logic, and config parsing.++## Runtime Data++Do not commit local runtime data. The `.gitignore` covers known generated paths,+including:++- `.env`+- `.profiles/`+- `.scheduler-state/`+- `*-state.json`+- `queue/`+- `downloads/`+- `user-assets/`+- `autodownload/downloads/`+- `autodownload/profile_downloads/`+- `autodownload/info.json`+- `last-*.png`++Before publishing a fork, inspect `git status --short` and `git status+--ignored`.++## Responsible Use++Users are responsible for complying with platform terms, account policies, rate+limits, local law, and content rights. This project does not grant permission to+post content you do not own or have permission to use.++Prefer official platform APIs where they are available for your workflow. Avoid+spam, deceptive behavior, unauthorized scraping, and posting without consent.+Keep sessions local, rotate credentials if they are exposed, and review+platform limits before enabling scheduled automation.++## Roadmap++See [ROADMAP.md](ROADMAP.md) for planned work around safer automation controls,+official API integrations, creator workflow templates, and maintainer tooling.++## License++MIT. See [LICENSE](LICENSE).diff --git a/ROADMAP.md b/ROADMAP.mdnew file mode 100644index 0000000..8860091--- /dev/null+++ b/ROADMAP.md@@ -0,0 +1,55 @@+# Roadmap++AutoSocial Studio is early-stage open source software. The roadmap focuses on+making local creator workflows safer, easier to maintain, and more useful for+builders shipping products with AI coding tools.++## Near Term++- Add a first-run onboarding checklist for local setup, platform login status,+ queue folders, FFmpeg, Playwright Chromium, and yt-dlp.+- Improve dashboard empty states so new users can understand the workflow+ without reading every setup step first.+- Add screenshot-based troubleshooting guides for TikTok, Instagram, and+ YouTube selector breakage.+- Expand local tests around dashboard settings, account state, queue migration,+ and downloader configuration.+- Add release notes and a lightweight changelog process.++## Responsible Automation++- Add scheduler guardrails such as per-platform cooldowns, daily caps, and+ clearer warnings before enabling frequent posting.+- Make platform limits and responsible-use notes visible near automation+ controls, not only in documentation.+- Add safer defaults for newly created accounts and queues.+- Explore official platform APIs where they are available and practical for+ user-consented posting workflows.++## Creator Workflow++- Add campaign templates for product launches, demos, updates, and build-in-+ public content.+- Add reusable caption templates and per-account content presets.+- Add a local review queue before scheduled posts are allowed to publish.+- Improve the video uniquifier controls with preview metadata and clearer+ recipe options.++## Maintainer Tooling++- Use AI coding tools for pull request review, selector-change triage, and test+ coverage suggestions.+- Add automated security and dependency review workflows.+- Build issue templates for platform breakage reports with required logs,+ screenshots, and local environment details.+- Create a small contributor guide for maintaining Playwright selectors across+ changing social media UIs.++## Long Term++- Plugin-style platform adapters so contributors can add or maintain platforms+ without touching unrelated queues and dashboard code.+- Optional API-backed publishing paths for platforms that support official+ upload APIs.+- Cross-platform packaging so non-technical users can run the local dashboard+ with less setup friction.diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..2d5895e--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,56 @@+# Security Policy++AutoSocial Studio is designed as a local workstation tool. It is not a hosted+multi-user web application.++## Local Dashboard++The dashboard binds to `127.0.0.1` by default and has no authentication layer.+Keep it on localhost unless you add your own network controls.++Mutating dashboard requests reject cross-origin browser requests using Origin,+Referer, and Fetch Metadata headers. This reduces accidental local CSRF+exposure, but it is not a replacement for authentication or network isolation.++Binding to a non-local address is intentionally blocked unless+`DASHBOARD_ALLOW_REMOTE=true` is set. Only enable this on a trusted network and+only if you understand that anyone who can reach the dashboard can operate the+local automation controls.++## Sensitive Local Data++The following paths can contain credentials, session cookies, downloaded media,+runtime state, or debug artifacts and should not be committed:++- `.env`+- `.profile/`+- `.profile-instagram/`+- `.profile-youtube/`+- `.profiles/`+- `.scheduler-state/`+- `accounts-state.json`+- `*-state.json`+- `queue/`+- `downloads/`+- `user-assets/`+- `autodownload/downloads/`+- `autodownload/profile_downloads/`+- `autodownload/info.json`+- `autodownload/*.info.json`+- `last-*.png`++Before publishing a fork, run a local secret/runtime scan and inspect+`git status --ignored` for surprises.++## Reporting Vulnerabilities++Please do not open public issues for vulnerabilities that expose secrets,+credentials, or session data. If the repository owner has not published a+private reporting channel yet, open a minimal issue asking for a security+contact without including exploit details.++## Responsible Use++Users are responsible for complying with platform terms, local law, rate limits,+account policies, and content rights. This project does not grant permission to+post content you do not own or have permission to use.diff --git a/SETUP.md b/SETUP.mdnew file mode 100644index 0000000..dc5b248--- /dev/null+++ b/SETUP.md@@ -0,0 +1,244 @@+# AutoSocial Studio Setup Guide++This guide walks through a fresh local setup for AutoSocial Studio.++## Prerequisites++- Node.js 18++- npm+- Git+- FFmpeg and ffprobe in `PATH`+- Playwright Chromium+- Optional: yt-dlp for downloader features++## 1. Clone and Install++```bash+git clone https://github.com/Katzca/AutoSocial.git+cd AutoSocial+npm ci+npx playwright install chromium+```++Run the environment check:++```bash+npm run doctor+```++`yt-dlp` is optional. If the doctor reports it as missing, only the downloader+features are affected.++## 2. Add yt-dlp for Downloader Features++Download the latest Windows binary from the yt-dlp releases page and place it+here:++```text+autodownload/yt-dlp.exe+```++You can skip this if you do not use auto-download or profile-download features.++## 3. Create `.env`++```powershell+Copy-Item .env.example .env+```++Important settings:++- `TZ`+- `BROWSER_LOCALE`+- `CRON_EXPRESSION`, `INSTAGRAM_CRON_EXPRESSION`, `YOUTUBE_CRON_EXPRESSION`+- `DEFAULT_CAPTION`+- `WATCH_CHANNEL`, `WATCH_INTERVAL`, `WATCH_MAX_VIDEOS`, `WATCH_MIN_VIEWS`+- `AUTO_POST_PLATFORMS`+- `HEADLESS`+- `AUTO_ADD_SOUND`+- `RANDOM_QUEUE_ORDER`+- `DASHBOARD_HOST`, `DASHBOARD_PORT`++Hashtag captions must be quoted:++```env+DEFAULT_CAPTION="#mybrand #shorts"+```++## 4. Start the Dashboard++```bash+npm run dashboard+```++Open http://127.0.0.1:3000.++The dashboard controls:++- Account switching+- Platform login sessions+- TikTok, Instagram, and YouTube schedulers+- Queue status and logs+- Auto-download management+- Profile downloads+- Video uniquifier runs++## 5. Create or Select Accounts++Use the brand/account switcher in the dashboard sidebar.++Each account gets separate runtime directories:++```text+queue/<account>/<platform>/{pending,posted,failed}+.profiles/<account>/<platform>+.scheduler-state/<account>/+```++The active account is tracked in `accounts-state.json`, which is ignored by Git.++## 6. Log In to Platforms++Open the `Accounts` view and start a login session for each platform.++- TikTok: `.profiles/<account>/tiktok`+- Instagram: `.profiles/<account>/instagram`+- YouTube: `.profiles/<account>/youtube`++Sessions persist across restarts.++## 7. Queue Videos++Place video files into the pending folder for the account and platform:++```text+queue/default/tiktok/pending+queue/default/instagram/pending+queue/default/youtube/pending+```++Supported video files:++- `.mp4`+- `.mov`+- `.webm`+- `.avi`+- `.mkv`++Optional caption sidecars:++- `.description`+- `.txt`++## 8. Configure Posting++From each platform view in the dashboard you can:++- Run one post immediately+- Set a cron expression+- Use daily posting times+- Enable or disable instant-post mode+- Start or stop the scheduler++Schedule settings persist, but scheduler processes do not auto-start after an+app restart. Start them again from the dashboard.++## Optional Subsystems++### Auto Download++The auto-download watcher polls a TikTok channel through yt-dlp, downloads new+videos, and copies them into pending queues for selected platforms.++Dashboard-managed watcher: use the `Auto Download` view.++Standalone watcher:++```bash+npm run autodownload+```++### Profile Downloader++The profile downloader saves videos into `autodownload/profile_downloads`+without auto-queueing them. It can scan channels, filter by views, and collect+slideshow/image assets where available.++### Video Uniquifier++The uniquifier runs FFmpeg recipes against videos in an input folder and writes+modified outputs to a separate folder. It is available from the dashboard and+from the CLI.++Logo overlay is optional. Put your own logo in `user-assets/` or point to any+local image path, then enter it in the dashboard's `Logo Image` field before+starting a batch. You can also set `UNIQUIFY_LOGO_IMAGE` in `.env`. Leave it+empty to run without a logo overlay.++## CLI Reference++```bash+npm run dashboard+npm run doctor+npm run check+npm run login+npm run post+npm run daemon+npm run uniquify+npm run video-info -- --video "C:\path\video.mp4"+npm run autodownload+```++## Environment Variables++| Variable | Default | Description |+| --- | --- | --- |+| `CRON_EXPRESSION` | `0 */2 * * *` | TikTok scheduler cron expression |+| `INSTAGRAM_CRON_EXPRESSION` | `0 */2 * * *` | Instagram scheduler cron expression |+| `YOUTUBE_CRON_EXPRESSION` | `0 */2 * * *` | YouTube scheduler cron expression |+| `TZ` | `UTC` | Timezone used by scheduler logic |+| `BROWSER_LOCALE` | `en-US` | Locale used by Playwright browser contexts that need an explicit locale |+| `HEADLESS` | `false` | Run Playwright in headless mode |+| `POST_DELAY_MS` | `15000` | Delay after file upload before publish steps continue |+| `POST_PUBLISH_HOLD_MS` | `25000` | Keep browser open after a successful post |+| `FAILURE_HOLD_MS` | `8000` | Keep browser open after a failure for inspection |+| `AUTO_ADD_SOUND` | `false` | Try to add a TikTok sound before publishing |+| `DEFAULT_SOUND_QUERY` | empty | Optional TikTok sound search query |+| `RANDOM_QUEUE_ORDER` | `false` | Pick a random pending file instead of alphabetic order |+| `DEFAULT_CAPTION` | empty | Caption fallback when no sidecar caption exists |+| `WATCH_CHANNEL` | empty | TikTok account watched by auto-download |+| `WATCH_INTERVAL` | `10` | Minutes between auto-download checks |+| `WATCH_MAX_VIDEOS` | `5` | Number of recent videos checked per poll |+| `WATCH_MIN_VIEWS` | `0` | Minimum views filter for downloader flows |+| `AUTO_POST_PLATFORMS` | `tiktok,instagram,youtube` | Platforms that receive copied downloads |+| `UNIQUIFY_INPUT_DIR` | `queue/uniquify-input` | Default dashboard input folder for uniquifier |+| `UNIQUIFY_OUTPUT_DIR` | `queue/uniquify-output` | Default dashboard output folder for uniquifier |+| `UNIQUIFY_LOGO_IMAGE` | empty | Optional default logo image used by uniquifier |+| `DASHBOARD_HOST` | `127.0.0.1` | Dashboard bind host |+| `DASHBOARD_PORT` | `3000` | Dashboard bind port |+| `DASHBOARD_ALLOW_REMOTE` | `false` | Allow non-local dashboard bind host |+| `TIKTOK_UPLOAD_URL` | `https://www.tiktok.com/tiktokstudio/upload` | TikTok upload page override |+| `INSTAGRAM_UPLOAD_URL` | `https://www.instagram.com/create/style/` | Instagram upload page override |+| `YOUTUBE_UPLOAD_URL` | `https://studio.youtube.com` | YouTube Studio upload page override |++## Troubleshooting++- `npm run doctor` fails for FFmpeg: install FFmpeg and add it to PATH.+- `Playwright Chromium missing`: run `npx playwright install chromium`.+- `yt-dlp missing`: add `autodownload/yt-dlp.exe` or skip downloader features.+- `No session found`: open the dashboard and log in for that platform.+- Upload opens but does not finish: inspect `last-*.png` and dashboard logs.+- Schedule looks saved but nothing posts after restart: start the scheduler again.+- Dashboard refuses remote bind: use `DASHBOARD_HOST=127.0.0.1` or explicitly set `DASHBOARD_ALLOW_REMOTE=true`.++## Open Source Publishing Checklist++Before publishing a fork:++- Confirm `.env`, profiles, queues, screenshots, state files, and downloader+ metadata are not committed.+- Run `npm run check`.+- Run `npm audit --omit=dev`.+- Review `SECURITY.md`.+- If sensitive files were ever committed, scrub Git history or publish from a+ fresh repository.diff --git a/autodownload/download_tiktok.bat b/autodownload/download_tiktok.batnew file mode 100644index 0000000..0788609--- /dev/null+++ b/autodownload/download_tiktok.bat@@ -0,0 +1,26 @@+@echo off+setlocal EnableDelayedExpansion+if not exist "downloads" mkdir downloads++set /p CHANNEL="Enter the TikTok channel URL or username (e.g. @username): "+if "!CHANNEL!"=="" (+ echo No channel entered. Exiting.+ goto done+)++set /p MIN_VIEWS="Enter the minimum view count filter (press Enter for no filter): "++set YTDLP_ARGS=-o "downloads/%%(uploader)s/%%(upload_date)s_%%(id)s.%%(ext)s" --write-description -S vcodec:h264,res,acodec++if not "!MIN_VIEWS!"=="" (+ echo Downloading videos from https://www.tiktok.com/!CHANNEL!...+ .\yt-dlp.exe !YTDLP_ARGS! --match-filter "view_count >= !MIN_VIEWS!" https://www.tiktok.com/!CHANNEL!+) else (+ echo Downloading videos from https://www.tiktok.com/!CHANNEL!...+ .\yt-dlp.exe !YTDLP_ARGS! https://www.tiktok.com/!CHANNEL!+)++echo Download complete.+:done+endlocal+pausediff --git a/autodownload/watcher.js b/autodownload/watcher.jsnew file mode 100644index 0000000..7a20524--- /dev/null+++ b/autodownload/watcher.js@@ -0,0 +1,227 @@+/**+ * TikTok Auto-Downloader -> Auto-Post Pipeline+ *+ * Polls a TikTok channel on a schedule. When new videos are found,+ * downloads them and copies into each platform's queue folder so the+ * existing scheduler automatically posts them.+ *+ * Config is read from .env (WATCH_CHANNEL, WATCH_INTERVAL, etc.)+ * CLI flags override env: --channel, --interval, --max, --account+ *+ * Usage:+ * node autodownload/watcher.js+ * node autodownload/watcher.js --channel "@someone" --interval 5+ * node autodownload/watcher.js --account default+ */++const { execFile } = require("child_process");+const path = require("path");+const fs = require("fs");+const fsp = require("fs/promises");++// Load .env from project root+require("dotenv").config({ path: path.resolve(__dirname, "..", ".env") });++const { config } = require("../src/config");+const {+ getActiveAccount,+ getAccountQueueDirs,+ ensureAccountDirs,+} = require("../src/account-manager");++const args = process.argv.slice(2);++function getArg(name, fallback) {+ const idx = args.indexOf(`--${name}`);+ const val = idx !== -1 ? args[idx + 1] : undefined;+ if (!val || val.startsWith("--")) return fallback;+ return val;+}++const CHANNEL = getArg("channel", config.autoDownload.channel);+const INTERVAL = parseInt(getArg("interval", String(config.autoDownload.interval)), 10);+const MAX_VIDEOS = parseInt(getArg("max", String(config.autoDownload.maxVideos)), 10);+const MIN_VIEWS = parseInt(getArg("min-views", String(config.autoDownload.minViews || 0)), 10);+const PLATFORMS = config.autoDownload.platforms;+const ACCOUNT_ARG = getArg("account", process.env.ACCOUNT_ID || "");++const BASE_DIR = __dirname;+const YT_DLP = path.join(BASE_DIR, "yt-dlp.exe");+const DOWNLOADS = path.join(BASE_DIR, "downloads");+const ARCHIVE = path.join(BASE_DIR, "archive.txt");++const CHANNEL_URL = CHANNEL.startsWith("http")+ ? CHANNEL+ : `https://www.tiktok.com/${CHANNEL}`;++function log(msg) {+ const ts = new Date().toLocaleTimeString();+ console.log(`[${ts}] ${msg}`);+}++function ensureDir(dir) {+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });+}++function getPlatformQueueMap(accountId) {+ const queueDirs = getAccountQueueDirs(accountId);+ return {+ tiktok: queueDirs.tiktok.pending,+ instagram: queueDirs.instagram.pending,+ youtube: queueDirs.youtube.pending,+ };+}++async function resolveAccountId() {+ const requestedAccountId = String(ACCOUNT_ARG || "").trim();+ if (requestedAccountId) {+ return requestedAccountId;+ }+ const activeAccount = await getActiveAccount();+ return activeAccount.id;+}++/**+ * Copy a downloaded video into each platform's pending queue.+ * We copy (not move) so the original stays in downloads/ as a record.+ */+async function distributeToQueues(videoPath, accountId) {+ const filename = path.basename(videoPath);+ const parsed = path.parse(videoPath);+ const platformQueues = getPlatformQueueMap(accountId);++ const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);+ if (!VIDEO_EXTS.has(parsed.ext.toLowerCase())) {+ log(` Skipping non-video file distribution: ${filename}`);+ return;+ }++ const descriptionPath = path.join(parsed.dir, `${parsed.name}.description`);+ let captionText = "";+ try {+ captionText = (await fsp.readFile(descriptionPath, "utf-8")).trim();+ if (captionText) {+ log(` Found original caption (${captionText.length} chars)`);+ }+ } catch {+ // No description file.+ }++ for (const platform of PLATFORMS) {+ const queueDir = platformQueues[platform];+ if (!queueDir) {+ log(` Unknown platform "${platform}", skipping.`);+ continue;+ }++ ensureDir(queueDir);+ const dest = path.join(queueDir, filename);++ try {+ await fsp.copyFile(videoPath, dest);+ if (captionText) {+ const captionDest = path.join(queueDir, `${parsed.name}.txt`);+ await fsp.writeFile(captionDest, captionText, "utf-8");+ }+ log(` Queued for ${platform.toUpperCase()} -> ${dest} (account: ${accountId})`);+ } catch (err) {+ log(` Failed to queue for ${platform}: ${err.message}`);+ }+ }+}++function runYtDlp() {+ return new Promise((resolve) => {+ const dlArgs = [+ "--no-warnings",+ "--write-description",+ "-S", "vcodec:h264,res,acodec",+ "--playlist-items", `1:${MAX_VIDEOS}`,+ "--download-archive", ARCHIVE,+ "-o", path.join(DOWNLOADS, "%(uploader)s", "%(upload_date)s_%(id)s.%(ext)s"),+ ];++ if (MIN_VIEWS > 0) {+ dlArgs.push("--match-filter", `view_count >= ${MIN_VIEWS}`);+ }++ dlArgs.push(CHANNEL_URL);++ log(`Checking ${CHANNEL_URL} for new videos...`);++ execFile(YT_DLP, dlArgs, { timeout: 180_000 }, (err, stdout, stderr) => {+ if (stdout) {+ const lines = stdout.trim().split("\n");+ lines.forEach((line) => log(` yt-dlp: ${line}`));+ }+ if (err) {+ if (err.code === 101 || (stderr && stderr.includes("has already been recorded"))) {+ log("No new videos found.");+ return resolve([]);+ }+ log(`yt-dlp error: ${err.message}`);+ return resolve([]);+ }++ const downloaded = [];+ if (stdout) {+ const matches = stdout.matchAll(/\[download\] Destination: (.+)/g);+ for (const match of matches) {+ downloaded.push(match[1].trim());+ }+ const mergeMatches = stdout.matchAll(/\[Merger\] Merging formats into "(.+)"/g);+ for (const match of mergeMatches) {+ downloaded.push(match[1].trim());+ }+ }++ resolve(downloaded);+ });+ });+}++async function poll(accountId) {+ const newFiles = await runYtDlp();++ if (newFiles.length > 0) {+ log(`${newFiles.length} new video(s) downloaded. Distributing to queues...`);+ for (const filePath of newFiles) {+ log(` Processing: ${path.basename(filePath)}`);+ await distributeToQueues(filePath, accountId);+ }+ log("Distribution complete.");+ }+}++async function main() {+ const accountId = await resolveAccountId();+ await ensureAccountDirs(accountId);+ ensureDir(DOWNLOADS);++ const platformList = PLATFORMS.map((platform) => platform.toUpperCase()).join(", ");++ log("Auto-Download -> Auto-Post Pipeline");+ log(`Channel: ${CHANNEL_URL}`);+ log(`Interval: Every ${INTERVAL} minutes`);+ log(`Max check: Last ${MAX_VIDEOS} videos per poll`);+ log(`Min views: ${MIN_VIEWS > 0 ? MIN_VIEWS : "None"}`);+ log(`Post to: ${platformList}`);+ log(`Account: ${accountId}`);+ log(`Downloads: ${DOWNLOADS}`);+ log(`Archive: ${ARCHIVE}`);++ await poll(accountId);++ setInterval(() => {+ poll(accountId).catch((error) => {+ log(`Poll error: ${error.message}`);+ });+ }, INTERVAL * 60 * 1000);++ log(`Next check in ${INTERVAL} minutes. Press Ctrl+C to stop.`);+}++main().catch((error) => {+ log(`Fatal error: ${error.message}`);+ process.exitCode = 1;+});diff --git a/docs/assets/dashboard-overview.png b/docs/assets/dashboard-overview.pngnew file mode 100644index 0000000..1973289Binary files /dev/null and b/docs/assets/dashboard-overview.png differdiff --git a/package-lock.json b/package-lock.jsonnew file mode 100644index 0000000..ac3b64b--- /dev/null+++ b/package-lock.json@@ -0,0 +1,1057 @@+{+ "name": "autosocial-studio",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "autosocial-studio",+ "version": "0.1.0",+ "license": "MIT",+ "dependencies": {+ "dotenv": "^17.3.1",+ "express": "^5.2.1",+ "node-cron": "^4.2.1",+ "playwright": "^1.58.2",+ "yargs": "^18.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/ansi-regex": {+ "version": "6.2.2",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",+ "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },+ "node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/body-parser": {+ "version": "2.2.2",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",+ "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^1.0.5",+ "debug": "^4.4.3",+ "http-errors": "^2.0.0",+ "iconv-lite": "^0.7.0",+ "on-finished": "^2.4.1",+ "qs": "^6.14.1",+ "raw-body": "^3.0.1",+ "type-is": "^2.0.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/cliui": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^7.2.0",+ "strip-ansi": "^7.1.0",+ "wrap-ansi": "^9.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/content-disposition": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz",+ "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/dotenv": {+ "version": "17.3.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",+ "integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },+ "node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.4.0.tgz",+ "integrity": "sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/iconv-lite": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/node-cron": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-4.2.1.tgz",+ "integrity": "sha512-lgimEHPE/QDgFlywTd8yTR61ptugX3Qer29efeyWw2rv259HtGBNn1vZVmp8lB9uo9wC0t/AT4iGqXxia+CJFg==",+ "license": "ISC",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/playwright": {+ "version": "1.58.2",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz",+ "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==",+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.58.2"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.58.2",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz",+ "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/qs": {+ "version": "6.15.2",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",+ "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },+ "node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },+ "node_modules/side-channel": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3",+ "side-channel-list": "^1.0.0",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.1.2",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz",+ "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.0.1"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },+ "node_modules/type-is": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",+ "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^1.0.5",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/wrap-ansi": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.2.1",+ "string-width": "^7.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yargs": {+ "version": "18.0.0",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.0.0.tgz",+ "integrity": "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^9.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "string-width": "^7.2.0",+ "y18n": "^5.0.5",+ "yargs-parser": "^22.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yargs-parser": {+ "version": "22.0.0",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",+ "license": "ISC",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ }+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..06b0a07--- /dev/null+++ b/package.json@@ -0,0 +1,54 @@+{+ "name": "autosocial-studio",+ "version": "0.1.0",+ "description": "Local multi-account social media automation dashboard for TikTok, Instagram, and YouTube",+ "private": true,+ "main": "src/cli.js",+ "scripts": {+ "start": "node src/dashboard-server.js",+ "check": "npm run check:syntax && npm test",+ "check:syntax": "node scripts/check-syntax.js",+ "doctor": "node scripts/doctor.js",+ "test": "node --test",+ "login": "node src/cli.js login",+ "post": "node src/cli.js post",+ "daemon": "node src/cli.js daemon",+ "dashboard": "node src/dashboard-server.js",+ "uniquify": "node src/cli.js uniquify",+ "video-info": "node src/cli.js video-info",+ "autodownload": "node autodownload/watcher.js"+ },+ "keywords": [+ "automation",+ "dashboard",+ "creator-tools",+ "marketing",+ "social-media",+ "indie-hackers",+ "ai-builders",+ "playwright",+ "tiktok",+ "instagram",+ "youtube"+ ],+ "author": "AutoSocial Studio contributors",+ "license": "MIT",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/Katzca/AutoSocial.git"+ },+ "bugs": {+ "url": "https://github.com/Katzca/AutoSocial/issues"+ },+ "homepage": "https://github.com/Katzca/AutoSocial#readme",+ "engines": {+ "node": ">=18"+ },+ "dependencies": {+ "dotenv": "^17.3.1",+ "express": "^5.2.1",+ "node-cron": "^4.2.1",+ "playwright": "^1.58.2",+ "yargs": "^18.0.0"+ }+}diff --git a/scripts/check-syntax.js b/scripts/check-syntax.jsnew file mode 100644index 0000000..1e7279e--- /dev/null+++ b/scripts/check-syntax.js@@ -0,0 +1,51 @@+#!/usr/bin/env node+const fs = require("fs");+const path = require("path");+const { spawnSync } = require("child_process");++const projectRoot = path.resolve(__dirname, "..");+const ignoredDirs = new Set([".git", "node_modules"]);++function walk(dir) {+ const entries = fs.readdirSync(dir, { withFileTypes: true });+ const files = [];++ for (const entry of entries) {+ if (ignoredDirs.has(entry.name)) {+ continue;+ }++ const fullPath = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ files.push(...walk(fullPath));+ } else if (entry.isFile() && entry.name.endsWith(".js")) {+ files.push(fullPath);+ }+ }++ return files;+}++const jsFiles = walk(projectRoot);+const failures = [];++for (const filePath of jsFiles) {+ const result = spawnSync(process.execPath, ["--check", filePath], {+ cwd: projectRoot,+ encoding: "utf8",+ });++ if (result.status !== 0) {+ failures.push({ filePath, output: result.stderr || result.stdout });+ }+}++if (failures.length > 0) {+ for (const failure of failures) {+ console.error(`Syntax check failed: ${path.relative(projectRoot, failure.filePath)}`);+ console.error(failure.output.trim());+ }+ process.exit(1);+}++console.log(`Syntax OK (${jsFiles.length} files).`);diff --git a/scripts/doctor.js b/scripts/doctor.jsnew file mode 100644index 0000000..f57b437--- /dev/null+++ b/scripts/doctor.js@@ -0,0 +1,144 @@+#!/usr/bin/env node+const fs = require("fs");+const path = require("path");+const { spawnSync } = require("child_process");++const projectRoot = path.resolve(__dirname, "..");+const minimumNodeMajor = 18;+const checks = [];++function addCheck(name, status, detail) {+ checks.push({ name, status, detail });+}++function commandWorks(command, args) {+ const candidates =+ process.platform === "win32" && !/\.(cmd|exe)$/i.test(command)+ ? [command, `${command}.cmd`, `${command}.exe`]+ : [command];++ let result = null;+ for (const candidate of candidates) {+ result = spawnSync(candidate, args, {+ cwd: projectRoot,+ encoding: "utf8",+ windowsHide: true,+ });++ if (!result.error || result.error.code !== "ENOENT") {+ break;+ }+ }++ result = result || {};++ return {+ ok: result.status === 0,+ output: (result.stdout || result.stderr || "").trim().split(/\r?\n/)[0] || "",+ error: result.error,+ };+}++function checkNode() {+ const version = process.versions.node;+ const major = Number(version.split(".")[0]);+ addCheck(+ "Node.js",+ major >= minimumNodeMajor ? "ok" : "fail",+ `${version} (requires >= ${minimumNodeMajor})`+ );+}++function checkNpm() {+ if (process.env.npm_execpath) {+ const userAgent = process.env.npm_config_user_agent || "npm available";+ addCheck("npm", "ok", userAgent);+ return;+ }++ if (process.platform === "win32") {+ const npm = commandWorks("cmd.exe", ["/d", "/s", "/c", "npm --version"]);+ addCheck("npm", npm.ok ? "ok" : "fail", npm.ok ? npm.output : npm.error?.message || "not found");+ return;+ }++ const npm = commandWorks("npm", ["--version"]);+ addCheck("npm", npm.ok ? "ok" : "fail", npm.ok ? npm.output : npm.error?.message || "not found");+}++function checkFfmpeg() {+ const ffmpeg = commandWorks("ffmpeg", ["-version"]);+ addCheck("FFmpeg", ffmpeg.ok ? "ok" : "fail", ffmpeg.ok ? ffmpeg.output : "ffmpeg not found in PATH");++ const ffprobe = commandWorks("ffprobe", ["-version"]);+ addCheck("ffprobe", ffprobe.ok ? "ok" : "fail", ffprobe.ok ? ffprobe.output : "ffprobe not found in PATH");+}++function checkPlaywrightChromium() {+ try {+ const { chromium } = require("playwright");+ const executablePath = chromium.executablePath();+ addCheck(+ "Playwright Chromium",+ fs.existsSync(executablePath) ? "ok" : "fail",+ fs.existsSync(executablePath)+ ? executablePath+ : "missing; run `npx playwright install chromium`"+ );+ } catch (error) {+ addCheck("Playwright Chromium", "fail", error.message);+ }+}++function checkYtDlp() {+ const localExe = path.join(projectRoot, "autodownload", "yt-dlp.exe");+ if (fs.existsSync(localExe)) {+ addCheck("yt-dlp", "ok", localExe);+ return;+ }++ const pathTool = commandWorks("yt-dlp", ["--version"]);+ addCheck(+ "yt-dlp",+ pathTool.ok ? "ok" : "warn",+ pathTool.ok+ ? `PATH version ${pathTool.output}`+ : "optional; add autodownload/yt-dlp.exe for downloader features"+ );+}++function checkEnvExample() {+ const envExamplePath = path.join(projectRoot, ".env.example");+ addCheck(+ ".env.example",+ fs.existsSync(envExamplePath) ? "ok" : "fail",+ fs.existsSync(envExamplePath) ? envExamplePath : "missing"+ );+}++checkNode();+checkNpm();+checkFfmpeg();+checkPlaywrightChromium();+checkYtDlp();+checkEnvExample();++const label = {+ ok: "OK",+ warn: "WARN",+ fail: "FAIL",+};++for (const check of checks) {+ console.log(`[${label[check.status]}] ${check.name}: ${check.detail}`);+}++const failed = checks.filter((check) => check.status === "fail");+if (failed.length > 0) {+ console.error("");+ console.error(`${failed.length} required check(s) failed.`);+ process.exit(1);+}++console.log("");+console.log("Doctor checks passed.");diff --git a/src/account-manager.js b/src/account-manager.jsnew file mode 100644index 0000000..ba172eb--- /dev/null+++ b/src/account-manager.js@@ -0,0 +1,206 @@+const fs = require("fs/promises");+const path = require("path");+const { config } = require("./config");++const STATE_FILE = path.resolve(config.projectRoot, "accounts-state.json");+const DEFAULT_ACCOUNT = { id: "default", name: "Default" };+const LEGACY_PROFILE_DIRS = {+ tiktok: config.profileDir,+ instagram: config.instagramProfileDir,+ youtube: config.youtubeProfileDir,+};++let state = {+ activeAccountId: DEFAULT_ACCOUNT.id,+ accounts: [DEFAULT_ACCOUNT],+};+let loaded = false;++function clone(value) {+ return JSON.parse(JSON.stringify(value));+}++function normalizeState(raw) {+ const accounts = Array.isArray(raw?.accounts)+ ? raw.accounts+ .filter((item) => item && typeof item.id === "string" && typeof item.name === "string")+ .map((item) => ({ id: item.id, name: item.name }))+ : [];+ if (!accounts.length) {+ accounts.push({ ...DEFAULT_ACCOUNT });+ }++ const activeExists = accounts.some((item) => item.id === raw?.activeAccountId);+ const activeAccountId = activeExists ? raw.activeAccountId : accounts[0].id;+ return { accounts, activeAccountId };+}++function sanitizeName(name) {+ return (name || "").toString().trim().replace(/\s+/g, " ").slice(0, 60);+}++function makeId(name) {+ const base = name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 40);+ return base || "account";+}++function ensureUniqueId(baseId, existing) {+ if (!existing.has(baseId)) return baseId;+ let index = 2;+ while (existing.has(`${baseId}-${index}`)) {+ index += 1;+ }+ return `${baseId}-${index}`;+}++async function saveState() {+ await fs.writeFile(STATE_FILE, JSON.stringify(state, null, 2), "utf8");+}++async function ensureLoaded() {+ if (loaded) return;+ try {+ const raw = await fs.readFile(STATE_FILE, "utf8");+ state = normalizeState(JSON.parse(raw));+ } catch {+ state = normalizeState(state);+ await saveState();+ }+ loaded = true;+}++async function getState() {+ await ensureLoaded();+ return clone(state);+}++// Queue directory helpers++const PLATFORMS = ["tiktok", "instagram", "youtube"];+const SUBDIRS = ["pending", "posted", "failed"];++function getAccountQueueDirs(accountId) {+ const base = path.resolve(config.projectRoot, "queue", accountId);+ const dirs = {};+ for (const platform of PLATFORMS) {+ dirs[platform] = {};+ for (const sub of SUBDIRS) {+ dirs[platform][sub] = path.resolve(base, platform, sub);+ }+ }+ return dirs;+}++async function ensureAccountDirs(accountId) {+ const dirs = getAccountQueueDirs(accountId);+ const allPaths = [];+ for (const platform of PLATFORMS) {+ for (const sub of SUBDIRS) {+ allPaths.push(dirs[platform][sub]);+ }+ }+ // Also ensure browser profile dirs+ const profileBase = path.resolve(config.projectRoot, ".profiles", accountId);+ for (const platform of PLATFORMS) {+ allPaths.push(path.resolve(profileBase, platform));+ }+ await Promise.all(allPaths.map((d) => fs.mkdir(d, { recursive: true })));+ return dirs;+}++// Account CRUD++async function addAccount(name) {+ await ensureLoaded();+ const cleanName = sanitizeName(name);+ if (!cleanName) {+ throw new Error("Account name is required.");+ }++ const existingIds = new Set(state.accounts.map((item) => item.id));+ const id = ensureUniqueId(makeId(cleanName), existingIds);+ const account = { id, name: cleanName };+ state.accounts.push(account);+ state.activeAccountId = account.id;+ await saveState();++ // Create queue and profile directories for the new account+ await ensureAccountDirs(id);++ return clone(account);+}++async function selectAccount(accountId) {+ await ensureLoaded();+ const target = state.accounts.find((item) => item.id === accountId);+ if (!target) {+ throw new Error("Account not found.");+ }+ state.activeAccountId = target.id;+ await saveState();+ return clone(target);+}++async function getActiveAccount() {+ await ensureLoaded();+ return clone(+ state.accounts.find((item) => item.id === state.activeAccountId) || state.accounts[0]+ );+}++async function getAllAccounts() {+ await ensureLoaded();+ return clone(state.accounts);+}++async function getPlatformProfileDir(platform, accountId) {+ const acctId = accountId || (await getActiveAccount()).id;+ if (acctId === DEFAULT_ACCOUNT.id && LEGACY_PROFILE_DIRS[platform]) {+ try {+ await fs.stat(LEGACY_PROFILE_DIRS[platform]);+ return LEGACY_PROFILE_DIRS[platform];+ } catch {+ // Fall through to new path+ }+ }+ return path.resolve(config.projectRoot, ".profiles", acctId, platform);+}++async function hasSavedPlatformSession(platform, accountId) {+ const profileDir = await getPlatformProfileDir(platform, accountId);+ const cookieCandidates = [+ path.resolve(profileDir, "Default", "Cookies"),+ path.resolve(profileDir, "Cookies"),+ path.resolve(profileDir, "Network", "Cookies"),+ ];++ for (const filePath of cookieCandidates) {+ try {+ const stat = await fs.stat(filePath);+ if (stat.isFile() && stat.size > 0) {+ return true;+ }+ } catch {+ // continue+ }+ }++ return false;+}++module.exports = {+ getState,+ addAccount,+ selectAccount,+ getActiveAccount,+ getAllAccounts,+ getAccountQueueDirs,+ ensureAccountDirs,+ getPlatformProfileDir,+ hasSavedPlatformSession,+ PLATFORMS,+};diff --git a/src/autodownload-controller.js b/src/autodownload-controller.jsnew file mode 100644index 0000000..f82c3d4--- /dev/null+++ b/src/autodownload-controller.js@@ -0,0 +1,333 @@+/**+ * AutoDownloadController+ *+ * Wraps autodownload/watcher.js logic into a dashboard-manageable controller.+ * Supports start/stop, live logs, and runtime configuration of channel,+ * interval, and max-videos. State is persisted to autodownload-state.json.+ */++const fs = require("fs/promises");+const fsSync = require("fs");+const path = require("path");+const { execFile } = require("child_process");+const { config } = require("./config");+const { getActiveAccount, getAccountQueueDirs, ensureAccountDirs } = require("./account-manager");++function nowIso() {+ return new Date().toISOString();+}++function ensureDir(dir) {+ if (!fsSync.existsSync(dir)) fsSync.mkdirSync(dir, { recursive: true });+}++class AutoDownloadController {+ constructor() {+ this.channel = config.autoDownload.channel || "";+ this.interval = config.autoDownload.interval || 10;+ this.maxVideos = config.autoDownload.maxVideos || 5;+ this.minViews = config.autoDownload.minViews || 0;+ this.platforms = config.autoDownload.platforms || ["tiktok"];+ this.accountId = "default";+ this.running = false;+ this.isDownloading = false;+ this.lastCheckAt = null;+ this.totalDownloaded = 0;+ this.logs = [];+ this._timer = null;++ this.baseDir = path.resolve(config.projectRoot, "autodownload");+ this.ytDlp = path.join(this.baseDir, "yt-dlp.exe");+ this.downloadsDir = path.join(this.baseDir, "downloads");+ this.archivePath = path.join(this.baseDir, "archive.txt");+ this.statePath = path.resolve(config.projectRoot, "autodownload-state.json");++ this._loadState();+ }++ _loadState() {+ try {+ const data = fsSync.readFileSync(this.statePath, "utf-8");+ const state = JSON.parse(data);+ if (state.channel) this.channel = state.channel;+ if (state.interval) this.interval = state.interval;+ if (state.maxVideos) this.maxVideos = state.maxVideos;+ if (state.minViews !== undefined) this.minViews = state.minViews;+ if (Array.isArray(state.platforms) && state.platforms.length) {+ this.platforms = state.platforms;+ }+ if (state.accountId) {+ this.accountId = state.accountId;+ }+ } catch {+ // Ignore missing state file.+ }+ }++ async _saveState() {+ try {+ await fs.writeFile(+ this.statePath,+ JSON.stringify(+ {+ channel: this.channel,+ interval: this.interval,+ maxVideos: this.maxVideos,+ minViews: this.minViews,+ platforms: this.platforms,+ accountId: this.accountId,+ },+ null,+ 2+ )+ );+ } catch (err) {+ this.log(`Failed to save state: ${err.message}`, "error");+ }+ }++ log(message, level = "info") {+ const entry = { at: nowIso(), level, message };+ this.logs.unshift(entry);+ this.logs = this.logs.slice(0, 120);+ const prefix = `[${entry.at}] [autodownload]`;+ if (level === "error") {+ console.error(`${prefix} ${message}`);+ } else {+ console.log(`${prefix} ${message}`);+ }+ }++ async configure({ channel, interval, maxVideos, minViews, platforms, accountId }) {+ if (channel !== undefined) this.channel = String(channel).trim();+ if (interval !== undefined) {+ const n = parseInt(interval, 10);+ if (isNaN(n) || n < 1) throw new Error("Interval must be at least 1 minute.");+ this.interval = n;+ }+ if (maxVideos !== undefined) {+ const n = parseInt(maxVideos, 10);+ if (isNaN(n) || n < 1) throw new Error("Max videos must be at least 1.");+ this.maxVideos = n;+ }+ if (minViews !== undefined) {+ const n = parseInt(minViews, 10);+ if (isNaN(n) || n < 0) throw new Error("Min views must be 0 or greater.");+ this.minViews = n;+ }+ if (platforms !== undefined && Array.isArray(platforms)) {+ this.platforms = platforms;+ }+ if (accountId !== undefined && String(accountId).trim()) {+ this.accountId = String(accountId).trim();+ }++ await this._saveState();+ this.log(+ `Configuration updated - channel: ${this.channel}, interval: ${this.interval}m, max: ${this.maxVideos}, minViews: ${this.minViews}, account: ${this.accountId}`+ );++ if (this.running) {+ this.stop();+ await this.start({ accountId: this.accountId });+ }+ return { ok: true };+ }++ async start(options = {}) {+ if (this.running) return { ok: true, alreadyRunning: true };+ if (!this.channel) {+ throw new Error("No channel configured. Set a TikTok username first.");+ }++ if (options.accountId) {+ this.accountId = String(options.accountId).trim();+ }+ if (!this.accountId) {+ const activeAccount = await getActiveAccount();+ this.accountId = activeAccount.id;+ }++ await ensureAccountDirs(this.accountId);+ await this._saveState();++ this.running = true;+ ensureDir(this.downloadsDir);++ const platformList = this.platforms.map((p) => p.toUpperCase()).join(", ");+ this.log(+ `Watcher started - channel: ${this._channelUrl()}, every ${this.interval}m, posting to: ${platformList}, account: ${this.accountId}`+ );++ this._poll();+ this._timer = setInterval(() => this._poll(), this.interval * 60 * 1000);++ return { ok: true, alreadyRunning: false, accountId: this.accountId };+ }++ stop() {+ if (!this.running) return { ok: true, alreadyStopped: true };+ clearInterval(this._timer);+ this._timer = null;+ this.running = false;+ this.log("Watcher stopped.");+ return { ok: true, alreadyStopped: false };+ }++ _getPlatformQueueMap() {+ const queueDirs = getAccountQueueDirs(this.accountId || "default");+ return {+ tiktok: queueDirs.tiktok.pending,+ instagram: queueDirs.instagram.pending,+ youtube: queueDirs.youtube.pending,+ };+ }++ _channelUrl() {+ const ch = this.channel;+ return ch.startsWith("http") ? ch : `https://www.tiktok.com/${ch}`;+ }++ async _poll() {+ if (this.isDownloading) {+ this.log("Skipping poll - previous download still in progress.");+ return;+ }+ this.isDownloading = true;+ this.lastCheckAt = nowIso();++ try {+ const newFiles = await this._runYtDlp();+ if (newFiles.length > 0) {+ this.log(`${newFiles.length} new video(s) downloaded. Distributing to queues...`);+ for (const filePath of newFiles) {+ this.log(` Processing: ${path.basename(filePath)}`);+ await this._distributeToQueues(filePath);+ }+ this.totalDownloaded += newFiles.length;+ this.log("Distribution complete.");+ }+ } catch (err) {+ this.log(`Poll error: ${err.message}`, "error");+ } finally {+ this.isDownloading = false;+ if (this.running) {+ this.log(`Next check in ${this.interval} minutes.`);+ }+ }+ }++ _runYtDlp() {+ return new Promise((resolve) => {+ const dlArgs = [+ "--no-warnings",+ "--write-description",+ "-S", "vcodec:h264,res,acodec",+ "--playlist-items",+ `1:${this.maxVideos}`,+ "--download-archive",+ this.archivePath,+ "-o",+ path.join(this.downloadsDir, "%(uploader)s", "%(upload_date)s_%(id)s.%(ext)s")+ ];++ if (this.minViews > 0) {+ dlArgs.push("--match-filter", `view_count >= ${this.minViews}`);+ }++ dlArgs.push(this._channelUrl());++ this.log(`Checking ${this._channelUrl()} for new videos...`);++ execFile(this.ytDlp, dlArgs, { timeout: 180_000 }, (err, stdout, stderr) => {+ if (stdout) {+ const lines = stdout.trim().split("\n");+ lines.forEach((line) => this.log(` yt-dlp: ${line}`));+ }+ if (err) {+ if (err.code === 101 || (stderr && stderr.includes("has already been recorded"))) {+ this.log("No new videos found.");+ return resolve([]);+ }+ this.log(`yt-dlp error: ${err.message}`, "error");+ return resolve([]);+ }++ const downloaded = [];+ if (stdout) {+ const destMatches = stdout.matchAll(/\[download\] Destination: (.+)/g);+ for (const match of destMatches) downloaded.push(match[1].trim());+ const mergeMatches = stdout.matchAll(/\[Merger\] Merging formats into "(.+)"/g);+ for (const match of mergeMatches) downloaded.push(match[1].trim());+ }++ resolve(downloaded);+ });+ });+ }++ async _distributeToQueues(videoPath) {+ const filename = path.basename(videoPath);+ const parsed = path.parse(videoPath);++ const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);+ if (!VIDEO_EXTS.has(parsed.ext.toLowerCase())) {+ this.log(` Skipping non-video file distribution: ${filename}`);+ return;+ }++ const descriptionPath = path.join(parsed.dir, `${parsed.name}.description`);+ let captionText = "";+ try {+ captionText = await fs.readFile(descriptionPath, "utf-8");+ captionText = captionText.trim();+ if (captionText) {+ this.log(` Found original caption (${captionText.length} chars)`);+ }+ } catch {+ // No description file - upload time will fall back to DEFAULT_CAPTION.+ }++ const platformQueues = this._getPlatformQueueMap();++ for (const platform of this.platforms) {+ const queueDir = platformQueues[platform];+ if (!queueDir) {+ this.log(` Unknown platform "${platform}", skipping.`);+ continue;+ }++ ensureDir(queueDir);+ const dest = path.join(queueDir, filename);++ try {+ await fs.copyFile(videoPath, dest);+ if (captionText) {+ const captionDest = path.join(queueDir, `${parsed.name}.txt`);+ await fs.writeFile(captionDest, captionText, "utf-8");+ }+ this.log(` Queued for ${platform.toUpperCase()} -> ${path.basename(dest)} (account: ${this.accountId})`);+ } catch (err) {+ this.log(` Failed to queue for ${platform}: ${err.message}`, "error");+ }+ }+ }++ getStatus() {+ return {+ running: this.running,+ isDownloading: this.isDownloading,+ channel: this.channel,+ interval: this.interval,+ maxVideos: this.maxVideos,+ minViews: this.minViews,+ platforms: this.platforms,+ accountId: this.accountId,+ lastCheckAt: this.lastCheckAt,+ totalDownloaded: this.totalDownloaded,+ logs: this.logs,+ };+ }+}++module.exports = { AutoDownloadController };diff --git a/src/cli.js b/src/cli.jsnew file mode 100644index 0000000..ce89ee8--- /dev/null+++ b/src/cli.js@@ -0,0 +1,186 @@+#!/usr/bin/env node+const path = require("path");+const yargs = require("yargs/yargs");+const { hideBin } = require("yargs/helpers");+const { startLoginSession } = require("./tiktok-uploader");+const { postNextFromQueue, postFromManualInput } = require("./post-service");+const { startDaemon, runScheduledPost } = require("./scheduler");+const { config } = require("./config");+const { ensureDirectories } = require("./fs-utils");+const { uniquifyVideo, uniquifyInPlace, uniquifyDirectory, checkFfmpeg, getVideoInfo } = require("./video-uniquifier");++async function bootstrap() {+ await ensureDirectories([+ config.queueDir,+ config.postedDir,+ config.failedDir,+ config.profileDir,+ ]);+}++function logResult(result) {+ if (result.skipped) {+ console.log(result.reason);+ return;+ }++ if (result.ok) {+ console.log("Post complete.");+ console.log(`Moved video: ${result.movedVideo}`);+ return;+ }++ console.error("Post failed.");+ console.error(result.error);+ if (result.screenshotPath) {+ console.error(`Screenshot: ${result.screenshotPath}`);+ }+}++async function run() {+ await bootstrap();++ yargs(hideBin(process.argv))+ .scriptName("autosocial")+ .command(+ "login",+ "Open browser to log in and persist session",+ () => {},+ async () => {+ await startLoginSession();+ }+ )+ .command(+ "post",+ "Post a specific video or next queue item",+ (builder) =>+ builder+ .option("video", {+ type: "string",+ describe: "Path to video file. If omitted, takes next item from queue.",+ })+ .option("caption", {+ type: "string",+ describe: "Caption text for manual --video posting.",+ }),+ async (argv) => {+ const result = argv.video+ ? await postFromManualInput(path.resolve(argv.video), argv.caption)+ : await postNextFromQueue();+ logResult(result);+ }+ )+ .command(+ "daemon",+ "Start scheduler daemon to post from queue automatically",+ () => {},+ async () => {+ await runScheduledPost();+ startDaemon();+ }+ )+ .command(+ "uniquify",+ "Modify video metadata & pixels to make it unique before uploading",+ (builder) =>+ builder+ .option("video", {+ type: "string",+ describe: "Path to a single video file to uniquify.",+ })+ .option("dir", {+ type: "string",+ describe: "Path to a directory of videos to uniquify. Defaults to queue/default/tiktok/pending.",+ })+ .option("in-place", {+ type: "boolean",+ default: false,+ describe: "Replace the original file instead of creating a new one.",+ })+ .option("overlay", {+ type: "string",+ describe: "Path to an image (PNG/JPG) to use as a flickering watermark overlay.",+ })+ .option("remove-audio", {+ type: "boolean",+ default: false,+ describe: "Remove audio track from output video.",+ })+ .option("no-color-shift", { type: "boolean", default: false, describe: "Skip brightness/contrast/saturation changes." })+ .option("no-hue-shift", { type: "boolean", default: false, describe: "Skip hue rotation." })+ .option("no-noise", { type: "boolean", default: false, describe: "Skip noise overlay." })+ .option("no-pixel-shift", { type: "boolean", default: false, describe: "Skip pixel grid micro-crop." })+ .option("no-speed-shift", { type: "boolean", default: false, describe: "Skip micro speed adjustment." })+ .option("no-audio-pitch", { type: "boolean", default: false, describe: "Skip audio pitch shift." })+ .option("no-volume-shift", { type: "boolean", default: false, describe: "Skip volume adjustment." })+ .check((argv) => {+ if (!argv.video && !argv.dir) return true;+ if (argv.video && argv.dir) throw new Error("Provide either --video or --dir, not both.");+ return true;+ }),+ async (argv) => {+ const hasFfmpeg = await checkFfmpeg();+ if (!hasFfmpeg) {+ console.error("ffmpeg is not installed or not in PATH.");+ console.error("Install it from https://ffmpeg.org/download.html");+ process.exit(1);+ }++ const options = {+ inPlace: argv.inPlace,+ overlayImage: argv.overlay ? path.resolve(argv.overlay) : null,+ removeAudio: argv.removeAudio,+ colorShift: !argv.noColorShift,+ hueShift: !argv.noHueShift,+ noise: !argv.noNoise,+ pixelShift: !argv.noPixelShift,+ speedShift: !argv.noSpeedShift,+ audioPitch: !argv.noAudioPitch,+ volumeShift: !argv.noVolumeShift,+ };++ if (argv.video) {+ const videoPath = path.resolve(argv.video);+ if (options.inPlace) {+ await uniquifyInPlace(videoPath, options);+ } else {+ const result = await uniquifyVideo(videoPath, null, options);+ console.log(`\nUniquified file: ${result.outputPath}`);+ }+ } else {+ const targetDir = argv.dir ? path.resolve(argv.dir) : config.queueDir;+ await uniquifyDirectory(targetDir, options);+ }+ }+ )+ .command(+ "video-info",+ "Show metadata and stream info for a video file",+ (builder) =>+ builder.option("video", {+ type: "string",+ demandOption: true,+ describe: "Path to the video file.",+ }),+ async (argv) => {+ const hasFfmpeg = await checkFfmpeg();+ if (!hasFfmpeg) {+ console.error("ffmpeg/ffprobe is not installed or not in PATH.");+ process.exit(1);+ }++ const info = await getVideoInfo(path.resolve(argv.video));+ console.log(JSON.stringify(info, null, 2));+ }+ )+ .demandCommand(1, "Provide a command: login, post, daemon, uniquify, video-info")+ .strict()+ .help()+ .parse();+}++run().catch((error) => {+ console.error(error);+ process.exit(1);+});+diff --git a/src/config.js b/src/config.jsnew file mode 100644index 0000000..96ead7d--- /dev/null+++ b/src/config.js@@ -0,0 +1,116 @@+const path = require("path");+const dotenv = require("dotenv");++dotenv.config();++function getBoolean(value, defaultValue = false) {+ if (value === undefined || value === null || value === "") {+ return defaultValue;+ }+ return value.toString().toLowerCase() === "true";+}++const projectRoot = path.resolve(__dirname, "..");++function resolveOptionalProjectPath(value) {+ const trimmed = String(value || "").trim();+ if (!trimmed) {+ return "";+ }+ return path.resolve(projectRoot, trimmed);+}++const config = {+ projectRoot,+ queueDir: path.resolve(projectRoot, process.env.QUEUE_DIR || "queue/default/tiktok/pending"),+ postedDir: path.resolve(projectRoot, process.env.POSTED_DIR || "queue/default/tiktok/posted"),+ failedDir: path.resolve(projectRoot, process.env.FAILED_DIR || "queue/default/tiktok/failed"),+ profileDir: path.resolve(projectRoot, process.env.BROWSER_PROFILE_DIR || ".profile"),+ instagramQueueDir: path.resolve(+ projectRoot,+ process.env.INSTAGRAM_QUEUE_DIR || "queue/default/instagram/pending"+ ),+ instagramPostedDir: path.resolve(+ projectRoot,+ process.env.INSTAGRAM_POSTED_DIR || "queue/default/instagram/posted"+ ),+ instagramFailedDir: path.resolve(+ projectRoot,+ process.env.INSTAGRAM_FAILED_DIR || "queue/default/instagram/failed"+ ),+ instagramProfileDir: path.resolve(+ projectRoot,+ process.env.INSTAGRAM_PROFILE_DIR || ".profile-instagram"+ ),+ youtubeQueueDir: path.resolve(+ projectRoot,+ process.env.YOUTUBE_QUEUE_DIR || "queue/default/youtube/pending"+ ),+ youtubePostedDir: path.resolve(+ projectRoot,+ process.env.YOUTUBE_POSTED_DIR || "queue/default/youtube/posted"+ ),+ youtubeFailedDir: path.resolve(+ projectRoot,+ process.env.YOUTUBE_FAILED_DIR || "queue/default/youtube/failed"+ ),+ youtubeProfileDir: path.resolve(+ projectRoot,+ process.env.YOUTUBE_PROFILE_DIR || ".profile-youtube"+ ),+ cronExpression: process.env.CRON_EXPRESSION || "0 */2 * * *",+ instagramCronExpression: process.env.INSTAGRAM_CRON_EXPRESSION || "0 */2 * * *",+ youtubeCronExpression: process.env.YOUTUBE_CRON_EXPRESSION || "0 */2 * * *",+ timezone: process.env.TZ || "UTC",+ browserLocale: process.env.BROWSER_LOCALE || "en-US",+ headless: getBoolean(process.env.HEADLESS, false),+ postDelayMs: Number(process.env.POST_DELAY_MS || 15000),+ postPublishHoldMs: Number(process.env.POST_PUBLISH_HOLD_MS || 25000),+ failureHoldMs: Number(process.env.FAILURE_HOLD_MS || 8000),+ autoAddSound: getBoolean(process.env.AUTO_ADD_SOUND, false),+ randomQueueOrder: getBoolean(process.env.RANDOM_QUEUE_ORDER, false),+ defaultSoundQuery: process.env.DEFAULT_SOUND_QUERY || "",+ defaultCaption: process.env.DEFAULT_CAPTION || "",+ uploadPageUrl:+ process.env.TIKTOK_UPLOAD_URL || "https://www.tiktok.com/tiktokstudio/upload",+ instagramUploadPageUrl:+ process.env.INSTAGRAM_UPLOAD_URL || "https://www.instagram.com/create/style/",+ youtubeUploadPageUrl:+ process.env.YOUTUBE_UPLOAD_URL || "https://studio.youtube.com",+ dashboardHost: process.env.DASHBOARD_HOST || "127.0.0.1",+ dashboardPort: Number(process.env.DASHBOARD_PORT || 3000),+ dashboardAllowRemote: getBoolean(process.env.DASHBOARD_ALLOW_REMOTE, false),+ uniquifyInputDir: path.resolve(+ projectRoot,+ process.env.UNIQUIFY_INPUT_DIR || "queue/uniquify-input"+ ),+ uniquifyOutputDir: path.resolve(+ projectRoot,+ process.env.UNIQUIFY_OUTPUT_DIR || "queue/uniquify-output"+ ),+ uniquifyLogoImage: resolveOptionalProjectPath(process.env.UNIQUIFY_LOGO_IMAGE),+ uniquifyIntroSeconds: Number(process.env.UNIQUIFY_INTRO_SECONDS || 1),+ uniquifyEndHoldSeconds: Number(process.env.UNIQUIFY_END_HOLD_SECONDS || 0.4),++ // Auto-download pipeline+ autoDownload: {+ channel: process.env.WATCH_CHANNEL || "",+ interval: Number(process.env.WATCH_INTERVAL || 10),+ maxVideos: Number(process.env.WATCH_MAX_VIDEOS || 5),+ minViews: Number(process.env.WATCH_MIN_VIEWS || 0),+ platforms: (process.env.AUTO_POST_PLATFORMS || "tiktok")+ .split(",")+ .map((p) => p.trim().toLowerCase()),+ },+};++// Map platform names to their queue directories+config.platformQueues = {+ tiktok: config.queueDir,+ instagram: config.instagramQueueDir,+ youtube: config.youtubeQueueDir,+};++module.exports = {+ config,+};diff --git a/src/daemon-controller.js b/src/daemon-controller.jsnew file mode 100644index 0000000..e99fac6--- /dev/null+++ b/src/daemon-controller.js@@ -0,0 +1,391 @@+const fs = require("fs/promises");+const fsSync = require("fs");+const path = require("path");+const cron = require("node-cron");+const { config } = require("./config");+const { postNextFromQueue } = require("./post-service");++function nowIso() {+ return new Date().toISOString();+}++function normalizeDailyTimes(times) {+ const source = Array.isArray(times) ? times : [];+ const normalized = source+ .map((value) => String(value || "").trim())+ .filter(Boolean)+ .map((value) => {+ const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value);+ if (!match) {+ throw new Error(`Invalid time "${value}". Use HH:MM (24h).`);+ }+ return `${match[1].padStart(2, "0")}:${match[2]}`;+ });++ const uniqueSorted = Array.from(new Set(normalized)).sort((a, b) =>+ a.localeCompare(b)+ );+ if (!uniqueSorted.length) {+ throw new Error("Please provide at least one valid time.");+ }+ return uniqueSorted;+}++function getLocalTimeKey(date, timezone) {+ return new Intl.DateTimeFormat("en-GB", {+ hour: "2-digit",+ minute: "2-digit",+ hour12: false,+ timeZone: timezone,+ }).format(date);+}++class DaemonController {+ constructor(options = {}) {+ this.accountId = options.accountId || "default";+ this.queueDir = options.queueDir || config.queueDir;+ this.postedDir = options.postedDir || config.postedDir;+ this.failedDir = options.failedDir || config.failedDir;++ this.task = null;+ this.isPosting = false;+ this.lastRunAt = null;+ this.lastResult = null;+ this.logs = [];+ this.cronExpression = config.cronExpression;+ this.schedulePlan = { type: "cron", expression: this.cronExpression };+ this.lastScheduleTriggerKey = null;+ this.instantPost = false;+ this._queueWatcher = null;+ this._watchDebounce = null;+ this._scheduledTimers = new Set();+ this.statePath = options.statePath || path.resolve(config.projectRoot, "scheduler-state.json");+ this._loadState();+ }++ _loadState() {+ try {+ const data = fsSync.readFileSync(this.statePath, "utf-8");+ const state = JSON.parse(data);+ if (state.schedulePlan && state.schedulePlan.type === "daily-times") {+ this.schedulePlan = {+ type: "daily-times",+ times: normalizeDailyTimes(state.schedulePlan.times),+ };+ } else if (state.schedulePlan && state.schedulePlan.type === "cron") {+ this.cronExpression = state.schedulePlan.expression || this.cronExpression;+ this.schedulePlan = { type: "cron", expression: this.cronExpression };+ } else if (state.cronExpression) {+ this.cronExpression = state.cronExpression;+ this.schedulePlan = { type: "cron", expression: this.cronExpression };+ }+ if (typeof state.instantPost === "boolean") {+ this.instantPost = state.instantPost;+ if (this.instantPost) {+ this._startWatching();+ }+ }+ } catch (error) {+ // Ignore missing file or parse error+ }+ }++ async _saveState() {+ try {+ await fs.writeFile(+ this.statePath,+ JSON.stringify(+ {+ cronExpression: this.cronExpression,+ schedulePlan: this.schedulePlan,+ instantPost: this.instantPost,+ },+ null,+ 2+ )+ );+ } catch (error) {+ this.log(`Failed to save scheduler state: ${error.message}`, "error");+ }+ }++ async setSchedule(expression) {+ if (!cron.validate(expression)) {+ throw new Error(`Invalid cron expression: ${expression}`);+ }++ this.cronExpression = expression;+ this.schedulePlan = { type: "cron", expression };+ await this._saveState();+ this.log(`Schedule updated to: ${expression}`);++ if (this.task) {+ this.stop();+ this.start();+ }++ return { ok: true, cronExpression: this.cronExpression };+ }++ async setDailyTimes(times) {+ const normalizedTimes = normalizeDailyTimes(times);+ this.schedulePlan = { type: "daily-times", times: normalizedTimes };+ this.lastScheduleTriggerKey = null;+ await this._saveState();+ this.log(`Schedule updated to daily times: ${normalizedTimes.join(", ")}`);++ if (this.task) {+ this.stop();+ this.start();+ }+ return { ok: true, schedulePlan: this.schedulePlan };+ }++ log(message, level = "info") {+ const entry = {+ at: nowIso(),+ level,+ message,+ };+ this.logs.unshift(entry);+ this.logs = this.logs.slice(0, 50);+ const prefix = `[${entry.at}] [tiktok:${this.accountId}]`;+ if (level === "error") {+ console.error(`${prefix} ${message}`);+ } else {+ console.log(`${prefix} ${message}`);+ }+ }++ async runOnce(source = "manual") {+ if (this.isPosting) {+ return {+ ok: false,+ skipped: true,+ reason: "A post is already in progress.",+ };+ }++ this.isPosting = true;+ this.lastRunAt = nowIso();+ this.log(`Run triggered by ${source}.`);++ try {+ const result = await postNextFromQueue({+ source,+ queueDir: this.queueDir,+ postedDir: this.postedDir,+ failedDir: this.failedDir,+ accountId: this.accountId,+ });+ this.lastResult = result;++ if (result.skipped) {+ this.log(result.reason);+ } else if (result.ok) {+ this.log(`Posted successfully: ${result.movedVideo}`);+ } else {+ this.log(`Post failed: ${result.error}`, "error");+ if (result.screenshotPath) {+ this.log(`Screenshot: ${result.screenshotPath}`, "error");+ }+ }++ return result;+ } catch (error) {+ const failedResult = {+ ok: false,+ error: error.message || "Unexpected scheduler error",+ };+ this.lastResult = failedResult;+ this.log(`Post failed: ${failedResult.error}`, "error");+ return failedResult;+ } finally {+ this.isPosting = false;+ }+ }++ _scheduleWithJitter(source) {+ const MAX_JITTER_MS = 10 * 60 * 1000; // 10 minutes+ const jitterMs = Math.floor(Math.random() * MAX_JITTER_MS);+ const jitterMin = Math.round(jitterMs / 1000 / 60 * 10) / 10;+ this.log(`Scheduled post will fire in ~${jitterMin} min (jitter).`);+ const timer = setTimeout(() => {+ this._scheduledTimers.delete(timer);+ if (!this.task) {+ this.log("Scheduled post skipped because scheduler is stopped.");+ return;+ }+ this.runOnce(source);+ }, jitterMs);+ this._scheduledTimers.add(timer);+ }++ _clearScheduledTimers() {+ for (const timer of this._scheduledTimers) {+ clearTimeout(timer);+ }+ this._scheduledTimers.clear();+ }++ start() {+ if (this.task) {+ return {+ ok: true,+ alreadyRunning: true,+ };+ }++ if (this.schedulePlan.type === "daily-times") {+ const times = normalizeDailyTimes(this.schedulePlan.times);+ this.schedulePlan = { type: "daily-times", times };+ this.task = cron.schedule(+ "* * * * *",+ async () => {+ const currentTime = getLocalTimeKey(new Date(), config.timezone);+ if (!times.includes(currentTime)) {+ return;+ }+ const minuteKey = `${new Date().toISOString().slice(0, 16)}|${currentTime}`;+ if (this.lastScheduleTriggerKey === minuteKey) {+ return;+ }+ this.lastScheduleTriggerKey = minuteKey;+ this._scheduleWithJitter("daily-times");+ },+ { timezone: config.timezone }+ );+ this.log(+ `Scheduler started (daily times: ${times.join(", ")}, timezone: ${config.timezone}).`+ );+ return { ok: true, alreadyRunning: false };+ }++ if (!cron.validate(this.cronExpression)) {+ throw new Error(`Invalid CRON_EXPRESSION: ${this.cronExpression}`);+ }++ this.task = cron.schedule(+ this.cronExpression,+ async () => {+ this._scheduleWithJitter("cron");+ },+ { timezone: config.timezone }+ );++ this.log(`Scheduler started (${this.cronExpression}, timezone: ${config.timezone}).`);+ return { ok: true, alreadyRunning: false };+ }++ stop() {+ this._clearScheduledTimers();+ if (!this.task) {+ return {+ ok: true,+ alreadyStopped: true,+ };+ }++ this.task.stop();+ this.task.destroy();+ this.task = null;+ this.log("Scheduler stopped.");+ return { ok: true, alreadyStopped: false };+ }++ async setInstantPost(enabled) {+ this.instantPost = Boolean(enabled);+ await this._saveState();+ if (this.instantPost) {+ this._startWatching();+ this.log("Instant post ENABLED - will post as soon as files land in queue.");+ } else {+ this._stopWatching();+ this.log("Instant post DISABLED.");+ }+ return { ok: true, instantPost: this.instantPost };+ }++ _startWatching() {+ if (this._queueWatcher) return;+ const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);+ try {+ this._queueWatcher = fsSync.watch(this.queueDir, (eventType, filename) => {+ if (eventType !== "rename" || !filename) return;+ const ext = path.extname(filename).toLowerCase();+ if (!VIDEO_EXTS.has(ext)) return;+ clearTimeout(this._watchDebounce);+ this._watchDebounce = setTimeout(() => {+ this.log('Instant post: detected new file "' + filename + '"');+ this.runOnce("instant-post");+ }, 2000);+ });+ } catch (err) {+ this.log("Failed to watch queue directory: " + err.message, "error");+ }+ }++ _stopWatching() {+ if (this._queueWatcher) {+ this._queueWatcher.close();+ this._queueWatcher = null;+ }+ clearTimeout(this._watchDebounce);+ }++ async getQueueState() {+ const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);++ const pendingEntries = await fs.readdir(this.queueDir, { withFileTypes: true });+ const postedEntries = await fs.readdir(this.postedDir, { withFileTypes: true });+ const failedEntries = await fs.readdir(this.failedDir, { withFileTypes: true });++ const isVideo = (entry) => entry.isFile() && VIDEO_EXTS.has(path.extname(entry.name).toLowerCase());++ const pendingVideos = pendingEntries+ .filter(isVideo)+ .map((entry) => {+ const ext = path.extname(entry.name);+ const base = entry.name.slice(0, -ext.length);+ const hasCaption = pendingEntries.some(e => e.isFile() && (e.name === `${base}.description` || e.name === `${base}.txt`));+ return { name: entry.name, hasCaption };+ })+ .sort((a, b) => a.name.localeCompare(b.name));++ return {+ counts: {+ pending: pendingVideos.length,+ posted: postedEntries.filter(isVideo).length,+ failed: failedEntries.filter(isVideo).length,+ },+ pendingVideos,+ };+ }++ async getStatus() {+ const queue = await this.getQueueState();+ return {+ running: Boolean(this.task),+ isPosting: this.isPosting,+ cronExpression: this.cronExpression,+ schedulePlan: this.schedulePlan,+ instantPost: this.instantPost,+ timezone: config.timezone,+ autoAddSound: config.autoAddSound,+ defaultCaption: config.defaultCaption,+ defaultSoundQuery: config.defaultSoundQuery,+ randomQueueOrder: config.randomQueueOrder,+ accountId: this.accountId,+ queue,+ lastRunAt: this.lastRunAt,+ lastResult: this.lastResult,+ logs: this.logs,+ };+ }+}++module.exports = {+ DaemonController,+ normalizeDailyTimes,+ getLocalTimeKey,+};diff --git a/src/daemon-registry.js b/src/daemon-registry.jsnew file mode 100644index 0000000..9794d54--- /dev/null+++ b/src/daemon-registry.js@@ -0,0 +1,92 @@+const path = require("path");+const { config } = require("./config");+const { DaemonController } = require("./daemon-controller");+const { InstagramDaemonController } = require("./instagram-daemon-controller");+const { YouTubeDaemonController } = require("./youtube-daemon-controller");+const { getAccountQueueDirs, ensureAccountDirs } = require("./account-manager");++/**+ * Central registry that manages per-profile daemon controller instances.+ * Each profile gets its own set of 3 daemon controllers (tiktok, instagram, youtube)+ * so they can run concurrently across profiles.+ *+ * Map<accountId, { tiktok, instagram, youtube }>+ */+const registry = new Map();++function getStateDir(accountId) {+ return path.resolve(config.projectRoot, ".scheduler-state", accountId);+}++/**+ * Get (or lazily create) the daemon controllers for a specific account.+ */+async function getDaemons(accountId) {+ if (registry.has(accountId)) {+ return registry.get(accountId);+ }++ // Ensure queue directories exist+ const dirs = await ensureAccountDirs(accountId);+ const queueDirs = getAccountQueueDirs(accountId);+ const stateDir = getStateDir(accountId);++ // Ensure state directory exists+ const fs = require("fs/promises");+ await fs.mkdir(stateDir, { recursive: true });++ const daemons = {+ tiktok: new DaemonController({+ accountId,+ queueDir: queueDirs.tiktok.pending,+ postedDir: queueDirs.tiktok.posted,+ failedDir: queueDirs.tiktok.failed,+ statePath: path.resolve(stateDir, "tiktok-scheduler-state.json"),+ }),+ instagram: new InstagramDaemonController({+ accountId,+ queueDir: queueDirs.instagram.pending,+ postedDir: queueDirs.instagram.posted,+ failedDir: queueDirs.instagram.failed,+ statePath: path.resolve(stateDir, "instagram-scheduler-state.json"),+ }),+ youtube: new YouTubeDaemonController({+ accountId,+ queueDir: queueDirs.youtube.pending,+ postedDir: queueDirs.youtube.posted,+ failedDir: queueDirs.youtube.failed,+ statePath: path.resolve(stateDir, "youtube-scheduler-state.json"),+ }),+ };++ registry.set(accountId, daemons);+ return daemons;+}++/**+ * Get status for all registered profiles (for overview dashboard).+ */+async function getAllStatus() {+ const results = {};+ for (const [accountId, daemons] of registry) {+ results[accountId] = {+ tiktok: await daemons.tiktok.getStatus(),+ instagram: await daemons.instagram.getStatus(),+ youtube: await daemons.youtube.getStatus(),+ };+ }+ return results;+}++/**+ * Get all registered account IDs.+ */+function getRegisteredAccountIds() {+ return Array.from(registry.keys());+}++module.exports = {+ getDaemons,+ getAllStatus,+ getRegisteredAccountIds,+};diff --git a/src/dashboard-server.js b/src/dashboard-server.jsnew file mode 100644index 0000000..13c4ee5--- /dev/null+++ b/src/dashboard-server.js@@ -0,0 +1,623 @@+const path = require("path");+const os = require("os");+const fs = require("fs/promises");+const { spawn } = require("child_process");+const express = require("express");+const { config } = require("./config");+const { ensureDirectories } = require("./fs-utils");+const { UniquifierController } = require("./uniquifier-controller");+const { AutoDownloadController } = require("./autodownload-controller");+const { ProfileDownloadController } = require("./profile-download-controller");+const { getDaemons, getAllStatus } = require("./daemon-registry");+const { migrateQueueIfNeeded } = require("./migrate-queue");+const { createDashboardRequestGuard } = require("./request-guard");+const {+ startDashboardLoginSession: startTikTokLoginSession,+ getLoginSessionStatus: getTikTokLoginSessionStatus,+ closeLoginSession: closeTikTokLoginSession,+} = require("./tiktok-uploader");+const {+ startLoginSession: startInstagramLoginSession,+ getLoginSessionStatus: getInstagramLoginSessionStatus,+ closeLoginSession: closeInstagramLoginSession,+} = require("./instagram-uploader");+const {+ startLoginSession: startYouTubeLoginSession,+ getLoginSessionStatus: getYouTubeLoginSessionStatus,+ closeLoginSession: closeYouTubeLoginSession,+} = require("./youtube-uploader");+const {+ getState,+ addAccount,+ selectAccount,+ getActiveAccount,+ getAllAccounts,+ ensureAccountDirs,+} = require("./account-manager");++function openFolder(folderPath) {+ return new Promise((resolve, reject) => {+ const platform = os.platform();+ if (platform === "win32") {+ const child = spawn("explorer", [folderPath], { detached: true, stdio: "ignore" });+ child.on("error", reject);+ child.unref();+ resolve();+ return;+ }+ if (platform === "darwin") {+ const child = spawn("open", [folderPath], { detached: true, stdio: "ignore" });+ child.on("error", reject);+ child.unref();+ resolve();+ return;+ }+ const child = spawn("xdg-open", [folderPath], { detached: true, stdio: "ignore" });+ child.on("error", reject);+ child.unref();+ resolve();+ });+}++/**+ * Helper: resolve the active account and get its daemons from the registry.+ */+async function getActiveDaemons() {+ const active = await getActiveAccount();+ return getDaemons(active.id);+}++const SETTINGS_ENV_KEYS = new Set([+ "AUTO_ADD_SOUND",+ "DEFAULT_CAPTION",+ "DEFAULT_SOUND_QUERY",+ "RANDOM_QUEUE_ORDER",+]);++function serializeEnvValue(value) {+ const text = String(value ?? "");+ if (/^[A-Za-z0-9_./:@,-]+$/.test(text)) {+ return text;+ }+ return JSON.stringify(text);+}++function applyRuntimeSetting(envKey, value) {+ if (envKey === "AUTO_ADD_SOUND") {+ config.autoAddSound = String(value).toLowerCase() === "true";+ } else if (envKey === "DEFAULT_CAPTION") {+ config.defaultCaption = String(value ?? "");+ } else if (envKey === "DEFAULT_SOUND_QUERY") {+ config.defaultSoundQuery = String(value ?? "");+ } else if (envKey === "RANDOM_QUEUE_ORDER") {+ config.randomQueueOrder = String(value).toLowerCase() === "true";+ }+}++function isLoopbackHost(host) {+ const normalized = String(host || "").trim().toLowerCase();+ return normalized === "127.0.0.1" || normalized === "localhost" || normalized === "::1";+}++function ensureDashboardBindAllowed() {+ if (config.dashboardAllowRemote || isLoopbackHost(config.dashboardHost)) {+ return;+ }++ throw new Error(+ `Refusing to bind dashboard to "${config.dashboardHost}". ` ++ "Use DASHBOARD_HOST=127.0.0.1 or set DASHBOARD_ALLOW_REMOTE=true if you understand the risk."+ );+}++async function createServer() {+ // Run migration from old flat queue layout to per-profile structure+ await migrateQueueIfNeeded();++ // Ensure dirs for all existing accounts+ const allAccounts = await getAllAccounts();+ for (const acct of allAccounts) {+ await ensureAccountDirs(acct.id);+ }++ // Ensure uniquifier dirs+ await ensureDirectories([+ config.uniquifyInputDir,+ config.uniquifyOutputDir,+ ]);++ // Pre-initialize daemons for all existing accounts+ for (const acct of allAccounts) {+ await getDaemons(acct.id);+ }++ const app = express();+ const uniquifier = new UniquifierController();+ const autoDownloader = new AutoDownloadController();+ const profileDownloader = new ProfileDownloadController();++ app.use(express.json());+ app.use(createDashboardRequestGuard());+ app.use(express.static(path.join(__dirname, "..", "web")));++ // TikTok endpoints (profile-aware)++ app.get("/api/status", async (req, res) => {+ const daemons = await getActiveDaemons();+ const status = await daemons.tiktok.getStatus();+ res.json(status);+ });++ app.post("/api/start", async (req, res) => {+ const daemons = await getActiveDaemons();+ const result = daemons.tiktok.start();+ res.json(result);+ });++ app.post("/api/stop", async (req, res) => {+ const daemons = await getActiveDaemons();+ const result = daemons.tiktok.stop();+ res.json(result);+ });++ app.post("/api/run-once", async (req, res) => {+ const daemons = await getActiveDaemons();+ const result = await daemons.tiktok.runOnce("dashboard");+ res.json(result);+ });++ app.post("/api/schedule", async (req, res) => {+ try {+ const { expression } = req.body;+ if (!expression) {+ return res.status(400).json({ ok: false, error: "Missing expression" });+ }+ const daemons = await getActiveDaemons();+ const result = await daemons.tiktok.setSchedule(expression);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/instant-post", async (req, res) => {+ try {+ const { enabled } = req.body;+ if (typeof enabled !== "boolean") {+ return res.status(400).json({ ok: false, error: "Missing 'enabled' (boolean)" });+ }+ const daemons = await getActiveDaemons();+ const result = await daemons.tiktok.setInstantPost(enabled);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/schedule-plan", async (req, res) => {+ try {+ const { type, times } = req.body || {};+ if (type !== "daily-times") {+ return res.status(400).json({ ok: false, error: "Unsupported schedule plan type." });+ }+ const daemons = await getActiveDaemons();+ const result = await daemons.tiktok.setDailyTimes(times);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // Settings++ app.post("/api/settings/save", async (req, res) => {+ try {+ const { payload } = req.body || {};+ if (!payload || typeof payload !== "object") {+ return res.status(400).json({ ok: false, error: "Invalid payload." });+ }++ const envPath = path.resolve(config.projectRoot, ".env");+ let envContent = "";+ try {+ envContent = await fs.readFile(envPath, "utf-8");+ } catch (err) {+ // file might not exist+ }++ const lines = envContent.split("\n");+ for (const [key, value] of Object.entries(payload)) {+ const envKey = key.toUpperCase();+ if (!SETTINGS_ENV_KEYS.has(envKey)) {+ return res.status(400).json({ ok: false, error: `Unsupported setting: ${envKey}` });+ }++ const serializedValue = serializeEnvValue(value);+ let found = false;++ for (let i = 0; i < lines.length; i++) {+ if (lines[i].trim().startsWith(`${envKey}=`)) {+ lines[i] = `${envKey}=${serializedValue}`;+ found = true;+ break;+ }+ }++ if (!found) {+ lines.push(`${envKey}=${serializedValue}`);+ }++ applyRuntimeSetting(envKey, value);+ }++ await fs.writeFile(envPath, lines.join("\n").replace(/\n{2,}/g, "\n"));+ res.json({ ok: true });+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // Account endpoints++ app.get("/api/accounts", async (req, res) => {+ const state = await getState();+ const active = await getActiveAccount();+ res.json({ ...state, activeAccount: active });+ });++ app.post("/api/accounts/add", async (req, res) => {+ try {+ const account = await addAccount(req.body?.name);+ // Pre-initialize daemons for the new account+ await getDaemons(account.id);+ const state = await getState();+ res.json({ ok: true, account, state });+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/accounts/select", async (req, res) => {+ try {+ const account = await selectAccount(req.body?.accountId);+ const state = await getState();+ res.json({ ok: true, account, state });+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // Login endpoints (TikTok)++ app.post("/api/tiktok/login", async (req, res) => {+ try {+ const result = await startTikTokLoginSession();+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.get("/api/tiktok/login/status", async (req, res) => {+ res.json(await getTikTokLoginSessionStatus());+ });++ app.post("/api/tiktok/login/close", async (req, res) => {+ try {+ const result = await closeTikTokLoginSession();+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // Instagram endpoints (profile-aware)++ app.get("/api/instagram/status", async (req, res) => {+ const daemons = await getActiveDaemons();+ const status = await daemons.instagram.getStatus();+ res.json(status);+ });++ app.post("/api/instagram/start", async (req, res) => {+ const daemons = await getActiveDaemons();+ const result = daemons.instagram.start();+ res.json(result);+ });++ app.post("/api/instagram/stop", async (req, res) => {+ const daemons = await getActiveDaemons();+ const result = daemons.instagram.stop();+ res.json(result);+ });++ app.post("/api/instagram/run-once", async (req, res) => {+ const daemons = await getActiveDaemons();+ const result = await daemons.instagram.runOnce("dashboard");+ res.json(result);+ });++ app.post("/api/instagram/schedule", async (req, res) => {+ try {+ const { expression } = req.body;+ if (!expression) {+ return res.status(400).json({ ok: false, error: "Missing expression" });+ }+ const daemons = await getActiveDaemons();+ const result = await daemons.instagram.setSchedule(expression);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/instagram/schedule-plan", async (req, res) => {+ try {+ const { type, times } = req.body || {};+ if (type !== "daily-times") {+ return res.status(400).json({ ok: false, error: "Unsupported schedule plan type." });+ }+ const daemons = await getActiveDaemons();+ const result = await daemons.instagram.setDailyTimes(times);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/instagram/instant-post", async (req, res) => {+ try {+ const { enabled } = req.body;+ if (typeof enabled !== "boolean") {+ return res.status(400).json({ ok: false, error: "Missing 'enabled' (boolean)" });+ }+ const daemons = await getActiveDaemons();+ const result = await daemons.instagram.setInstantPost(enabled);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // Login endpoints (Instagram)++ app.post("/api/instagram/login", async (req, res) => {+ try {+ const result = await startInstagramLoginSession();+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.get("/api/instagram/login/status", async (req, res) => {+ res.json(await getInstagramLoginSessionStatus());+ });++ app.post("/api/instagram/login/close", async (req, res) => {+ try {+ const result = await closeInstagramLoginSession();+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // YouTube endpoints (profile-aware)++ app.get("/api/youtube/status", async (req, res) => {+ const daemons = await getActiveDaemons();+ const status = await daemons.youtube.getStatus();+ res.json(status);+ });++ app.post("/api/youtube/start", async (req, res) => {+ const daemons = await getActiveDaemons();+ const result = daemons.youtube.start();+ res.json(result);+ });++ app.post("/api/youtube/stop", async (req, res) => {+ const daemons = await getActiveDaemons();+ const result = daemons.youtube.stop();+ res.json(result);+ });++ app.post("/api/youtube/run-once", async (req, res) => {+ const daemons = await getActiveDaemons();+ const result = await daemons.youtube.runOnce("dashboard");+ res.json(result);+ });++ app.post("/api/youtube/schedule", async (req, res) => {+ try {+ const { expression } = req.body;+ if (!expression) {+ return res.status(400).json({ ok: false, error: "Missing expression" });+ }+ const daemons = await getActiveDaemons();+ const result = await daemons.youtube.setSchedule(expression);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/youtube/schedule-plan", async (req, res) => {+ try {+ const { type, times } = req.body || {};+ if (type !== "daily-times") {+ return res.status(400).json({ ok: false, error: "Unsupported schedule plan type." });+ }+ const daemons = await getActiveDaemons();+ const result = await daemons.youtube.setDailyTimes(times);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/youtube/instant-post", async (req, res) => {+ try {+ const { enabled } = req.body;+ if (typeof enabled !== "boolean") {+ return res.status(400).json({ ok: false, error: "Missing 'enabled' (boolean)" });+ }+ const daemons = await getActiveDaemons();+ const result = await daemons.youtube.setInstantPost(enabled);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // Login endpoints (YouTube)++ app.post("/api/youtube/login", async (req, res) => {+ try {+ const result = await startYouTubeLoginSession();+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.get("/api/youtube/login/status", async (req, res) => {+ res.json(await getYouTubeLoginSessionStatus());+ });++ app.post("/api/youtube/login/close", async (req, res) => {+ try {+ const result = await closeYouTubeLoginSession();+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // Overview endpoint (aggregates all profiles)++ app.get("/api/overview", async (req, res) => {+ try {+ const allStatus = await getAllStatus();+ res.json(allStatus);+ } catch (error) {+ res.status(500).json({ ok: false, error: error.message });+ }+ });++ // Uniquifier endpoints++ app.get("/api/uniquifier/status", async (req, res) => {+ const status = await uniquifier.getStatus();+ res.json(status);+ });++ app.post("/api/uniquifier/start", async (req, res) => {+ try {+ const { inputDir, outputDir, logoImage } = req.body || {};+ const result = await uniquifier.start({ inputDir, outputDir, logoImage });+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/uniquifier/stop", (req, res) => {+ const result = uniquifier.stop();+ res.json(result);+ });++ app.post("/api/uniquifier/open-folder", async (req, res) => {+ try {+ const { kind, folderPath } = req.body || {};+ const status = await uniquifier.getStatus();+ const targetPath =+ folderPath ||+ (kind === "output" ? status.outputDir : kind === "input" ? status.inputDir : null);+ if (!targetPath) {+ return res.status(400).json({ ok: false, error: "Missing folder path or kind." });+ }+ await openFolder(targetPath);+ res.json({ ok: true, path: targetPath });+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // Auto-download endpoints+ app.get("/api/autodownload/status", (req, res) => {+ res.json(autoDownloader.getStatus());+ });++ app.post("/api/autodownload/start", async (req, res) => {+ try {+ const active = await getActiveAccount();+ const result = await autoDownloader.start({ accountId: req.body?.accountId || active.id });+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/autodownload/stop", (req, res) => {+ const result = autoDownloader.stop();+ res.json(result);+ });++ app.post("/api/autodownload/configure", async (req, res) => {+ try {+ const active = await getActiveAccount();+ const payload = { ...(req.body || {}) };+ if (!payload.accountId) {+ payload.accountId = active.id;+ }+ const result = await autoDownloader.configure(payload);+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ // Profile download endpoints+ app.get("/api/profile-download/status", (req, res) => {+ res.json(profileDownloader.getStatus());+ });++ app.post("/api/profile-download/start", async (req, res) => {+ try {+ const { channel, minViews, maxVideos, scanOnly } = req.body || {};+ const result = await profileDownloader.start({ channel, minViews, maxVideos, scanOnly });+ res.json(result);+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.post("/api/profile-download/open-folder", async (req, res) => {+ try {+ const status = profileDownloader.getStatus();+ await openFolder(status.downloadsDir);+ res.json({ ok: true });+ } catch (error) {+ res.status(400).json({ ok: false, error: error.message });+ }+ });++ app.use((error, req, res, next) => {+ console.error(error);+ res.status(500).json({ ok: false, error: error.message });+ });++ ensureDashboardBindAllowed();+ app.listen(config.dashboardPort, config.dashboardHost, () => {+ console.log(+ `Dashboard running at http://${config.dashboardHost}:${config.dashboardPort}`+ );+ });+}++createServer().catch((error) => {+ console.error(error);+ process.exit(1);+});diff --git a/src/fs-utils.js b/src/fs-utils.jsnew file mode 100644index 0000000..1c1ad70--- /dev/null+++ b/src/fs-utils.js@@ -0,0 +1,67 @@+const fs = require("fs/promises");+const path = require("path");+const crypto = require("crypto");++async function ensureDirectories(dirs) {+ await Promise.all(+ dirs.map(async (dir) => {+ await fs.mkdir(dir, { recursive: true });+ })+ );+}++async function fileExists(filePath) {+ try {+ await fs.access(filePath);+ return true;+ } catch {+ return false;+ }+}++function withTimestampPrefix(fileName) {+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");+ return `${timestamp}_${fileName}`;+}++function makeShortArchivedName(fileName, maxStemLength = 64) {+ const parsed = path.parse(fileName);+ const safeStem = parsed.name.replace(/[^\w.-]/g, "_");+ const shortStem = safeStem.slice(0, maxStemLength);+ const hash = crypto+ .createHash("sha1")+ .update(fileName)+ .digest("hex")+ .slice(0, 8);+ return `${shortStem}_${hash}${parsed.ext}`;+}++async function moveWithTimestamp(sourcePath, targetDir) {+ if (!(await fileExists(sourcePath))) {+ throw new Error(`Source file no longer exists: ${sourcePath}`);+ }++ const fileName = path.basename(sourcePath);+ const archivedName = withTimestampPrefix(makeShortArchivedName(fileName));+ const targetPath = path.join(targetDir, archivedName);++ try {+ await fs.rename(sourcePath, targetPath);+ } catch (error) {+ // Fallback path for occasional Windows rename issues.+ if (error && ["ENOENT", "EPERM", "EACCES"].includes(error.code)) {+ await fs.copyFile(sourcePath, targetPath);+ await fs.unlink(sourcePath);+ } else {+ throw error;+ }+ }++ return targetPath;+}++module.exports = {+ ensureDirectories,+ fileExists,+ moveWithTimestamp,+};diff --git a/src/instagram-daemon-controller.js b/src/instagram-daemon-controller.jsnew file mode 100644index 0000000..8d04078--- /dev/null+++ b/src/instagram-daemon-controller.js@@ -0,0 +1,352 @@+const fs = require("fs/promises");+const fsSync = require("fs");+const path = require("path");+const cron = require("node-cron");+const { config } = require("./config");+const { postNextFromQueue } = require("./instagram-post-service");++function nowIso() {+ return new Date().toISOString();+}++function normalizeDailyTimes(times) {+ const source = Array.isArray(times) ? times : [];+ const normalized = source+ .map((value) => String(value || "").trim())+ .filter(Boolean)+ .map((value) => {+ const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value);+ if (!match) {+ throw new Error(`Invalid time "${value}". Use HH:MM (24h).`);+ }+ return `${match[1].padStart(2, "0")}:${match[2]}`;+ });++ const uniqueSorted = Array.from(new Set(normalized)).sort((a, b) =>+ a.localeCompare(b)+ );+ if (!uniqueSorted.length) {+ throw new Error("Please provide at least one valid time.");+ }+ return uniqueSorted;+}++function getLocalTimeKey(date, timezone) {+ return new Intl.DateTimeFormat("en-GB", {+ hour: "2-digit",+ minute: "2-digit",+ hour12: false,+ timeZone: timezone,+ }).format(date);+}++class InstagramDaemonController {+ constructor(options = {}) {+ this.accountId = options.accountId || "default";+ this.queueDir = options.queueDir || config.instagramQueueDir;+ this.postedDir = options.postedDir || config.instagramPostedDir;+ this.failedDir = options.failedDir || config.instagramFailedDir;++ this.task = null;+ this.isPosting = false;+ this.lastRunAt = null;+ this.lastResult = null;+ this.logs = [];+ this.cronExpression = config.instagramCronExpression;+ this.schedulePlan = { type: "cron", expression: this.cronExpression };+ this.lastScheduleTriggerKey = null;+ this.instantPost = false;+ this._queueWatcher = null;+ this._watchDebounce = null;+ this._scheduledTimers = new Set();+ this.statePath = options.statePath || path.resolve(config.projectRoot, "instagram-scheduler-state.json");+ this._loadState();+ }++ _loadState() {+ try {+ const data = fsSync.readFileSync(this.statePath, "utf-8");+ const state = JSON.parse(data);+ if (state.schedulePlan && state.schedulePlan.type === "daily-times") {+ this.schedulePlan = {+ type: "daily-times",+ times: normalizeDailyTimes(state.schedulePlan.times),+ };+ } else if (state.schedulePlan && state.schedulePlan.type === "cron") {+ this.cronExpression = state.schedulePlan.expression || this.cronExpression;+ this.schedulePlan = { type: "cron", expression: this.cronExpression };+ } else if (state.cronExpression) {+ this.cronExpression = state.cronExpression;+ this.schedulePlan = { type: "cron", expression: this.cronExpression };+ }+ if (typeof state.instantPost === "boolean") {+ this.instantPost = state.instantPost;+ if (this.instantPost) {+ this._startWatching();+ }+ }+ } catch (error) {+ // Ignore missing file or parse error+ }+ }++ async _saveState() {+ try {+ await fs.writeFile(+ this.statePath,+ JSON.stringify(+ {+ cronExpression: this.cronExpression,+ schedulePlan: this.schedulePlan,+ instantPost: this.instantPost,+ },+ null,+ 2+ )+ );+ } catch (error) {+ this.log(`Failed to save scheduler state: ${error.message}`, "error");+ }+ }++ async setSchedule(expression) {+ if (!cron.validate(expression)) {+ throw new Error(`Invalid cron expression: ${expression}`);+ }+ this.cronExpression = expression;+ this.schedulePlan = { type: "cron", expression };+ await this._saveState();+ this.log(`Schedule updated to: ${expression}`);+ if (this.task) {+ this.stop();+ this.start();+ }+ return { ok: true, cronExpression: this.cronExpression };+ }++ async setDailyTimes(times) {+ const normalizedTimes = normalizeDailyTimes(times);+ this.schedulePlan = { type: "daily-times", times: normalizedTimes };+ this.lastScheduleTriggerKey = null;+ await this._saveState();+ this.log(`Schedule updated to daily times: ${normalizedTimes.join(", ")}`);+ if (this.task) {+ this.stop();+ this.start();+ }+ return { ok: true, schedulePlan: this.schedulePlan };+ }++ log(message, level = "info") {+ const entry = { at: nowIso(), level, message };+ this.logs.unshift(entry);+ this.logs = this.logs.slice(0, 50);+ const prefix = `[${entry.at}] [instagram:${this.accountId}]`;+ if (level === "error") {+ console.error(`${prefix} ${message}`);+ } else {+ console.log(`${prefix} ${message}`);+ }+ }++ async runOnce(source = "manual") {+ if (this.isPosting) {+ return { ok: false, skipped: true, reason: "An Instagram post is already in progress." };+ }++ this.isPosting = true;+ this.lastRunAt = nowIso();+ this.log(`Run triggered by ${source}.`);++ try {+ const result = await postNextFromQueue({+ source,+ queueDir: this.queueDir,+ postedDir: this.postedDir,+ failedDir: this.failedDir,+ accountId: this.accountId,+ });+ this.lastResult = result;++ if (result.skipped) {+ this.log(result.reason);+ } else if (result.ok) {+ this.log(`Posted successfully: ${result.movedVideo}`);+ } else {+ this.log(`Post failed: ${result.error}`, "error");+ if (result.screenshotPath) {+ this.log(`Screenshot: ${result.screenshotPath}`, "error");+ }+ }+ return result;+ } catch (error) {+ const failedResult = { ok: false, error: error.message || "Unexpected Instagram scheduler error" };+ this.lastResult = failedResult;+ this.log(`Post failed: ${failedResult.error}`, "error");+ return failedResult;+ } finally {+ this.isPosting = false;+ }+ }++ _scheduleWithJitter(source) {+ const MAX_JITTER_MS = 10 * 60 * 1000;+ const jitterMs = Math.floor(Math.random() * MAX_JITTER_MS);+ const jitterMin = Math.round(jitterMs / 1000 / 60 * 10) / 10;+ this.log(`Scheduled post will fire in ~${jitterMin} min (jitter).`);+ const timer = setTimeout(() => {+ this._scheduledTimers.delete(timer);+ if (!this.task) {+ this.log("Scheduled post skipped because scheduler is stopped.");+ return;+ }+ this.runOnce(source);+ }, jitterMs);+ this._scheduledTimers.add(timer);+ }++ _clearScheduledTimers() {+ for (const timer of this._scheduledTimers) {+ clearTimeout(timer);+ }+ this._scheduledTimers.clear();+ }++ start() {+ if (this.task) {+ return { ok: true, alreadyRunning: true };+ }++ if (this.schedulePlan.type === "daily-times") {+ const times = normalizeDailyTimes(this.schedulePlan.times);+ this.schedulePlan = { type: "daily-times", times };+ this.task = cron.schedule(+ "* * * * *",+ async () => {+ const currentTime = getLocalTimeKey(new Date(), config.timezone);+ if (!times.includes(currentTime)) return;+ const minuteKey = `${new Date().toISOString().slice(0, 16)}|${currentTime}`;+ if (this.lastScheduleTriggerKey === minuteKey) return;+ this.lastScheduleTriggerKey = minuteKey;+ this._scheduleWithJitter("daily-times");+ },+ { timezone: config.timezone }+ );+ this.log(`Scheduler started (daily times: ${times.join(", ")}, timezone: ${config.timezone}).`);+ return { ok: true, alreadyRunning: false };+ }++ if (!cron.validate(this.cronExpression)) {+ throw new Error(`Invalid CRON_EXPRESSION: ${this.cronExpression}`);+ }+ this.task = cron.schedule(+ this.cronExpression,+ async () => { this._scheduleWithJitter("cron"); },+ { timezone: config.timezone }+ );+ this.log(`Scheduler started (${this.cronExpression}, timezone: ${config.timezone}).`);+ return { ok: true, alreadyRunning: false };+ }++ stop() {+ this._clearScheduledTimers();+ if (!this.task) return { ok: true, alreadyStopped: true };+ this.task.stop();+ this.task.destroy();+ this.task = null;+ this.log("Scheduler stopped.");+ return { ok: true, alreadyStopped: false };+ }++ async setInstantPost(enabled) {+ this.instantPost = Boolean(enabled);+ await this._saveState();+ if (this.instantPost) {+ this._startWatching();+ this.log("Instant post ENABLED.");+ } else {+ this._stopWatching();+ this.log("Instant post DISABLED.");+ }+ return { ok: true, instantPost: this.instantPost };+ }++ _startWatching() {+ if (this._queueWatcher) return;+ const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);+ try {+ this._queueWatcher = fsSync.watch(this.queueDir, (eventType, filename) => {+ if (eventType !== "rename" || !filename) return;+ const ext = path.extname(filename).toLowerCase();+ if (!VIDEO_EXTS.has(ext)) return;+ clearTimeout(this._watchDebounce);+ this._watchDebounce = setTimeout(() => {+ this.log('Instant post: detected new file "' + filename + '"');+ this.runOnce("instant-post");+ }, 2000);+ });+ } catch (err) {+ this.log("Failed to watch queue directory: " + err.message, "error");+ }+ }++ _stopWatching() {+ if (this._queueWatcher) {+ this._queueWatcher.close();+ this._queueWatcher = null;+ }+ clearTimeout(this._watchDebounce);+ }++ async getQueueState() {+ const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);+ const pendingEntries = await fs.readdir(this.queueDir, { withFileTypes: true });+ const postedEntries = await fs.readdir(this.postedDir, { withFileTypes: true });+ const failedEntries = await fs.readdir(this.failedDir, { withFileTypes: true });++ const isVideo = (entry) => entry.isFile() && VIDEO_EXTS.has(path.extname(entry.name).toLowerCase());++ const pendingVideos = pendingEntries+ .filter(isVideo)+ .map((entry) => {+ const ext = path.extname(entry.name);+ const base = entry.name.slice(0, -ext.length);+ const hasCaption = pendingEntries.some(e => e.isFile() && (e.name === `${base}.description` || e.name === `${base}.txt`));+ return { name: entry.name, hasCaption };+ })+ .sort((a, b) => a.name.localeCompare(b.name));++ return {+ counts: {+ pending: pendingVideos.length,+ posted: postedEntries.filter(isVideo).length,+ failed: failedEntries.filter(isVideo).length,+ },+ pendingVideos,+ };+ }++ async getStatus() {+ const queue = await this.getQueueState();+ return {+ running: Boolean(this.task),+ isPosting: this.isPosting,+ cronExpression: this.cronExpression,+ schedulePlan: this.schedulePlan,+ instantPost: this.instantPost,+ timezone: config.timezone,+ randomQueueOrder: config.randomQueueOrder,+ accountId: this.accountId,+ queue,+ lastRunAt: this.lastRunAt,+ lastResult: this.lastResult,+ logs: this.logs,+ };+ }+}++module.exports = {+ InstagramDaemonController,+ normalizeDailyTimes,+ getLocalTimeKey,+};diff --git a/src/instagram-post-service.js b/src/instagram-post-service.jsnew file mode 100644index 0000000..37f9045--- /dev/null+++ b/src/instagram-post-service.js@@ -0,0 +1,86 @@+const fs = require("fs/promises");+const path = require("path");+const { config } = require("./config");+const { getNextQueuedItem, getCaptionPaths } = require("./instagram-queue");+const { uploadVideo } = require("./instagram-uploader");+const { ensureDirectories, fileExists, moveWithTimestamp } = require("./fs-utils");++async function moveCaptionsIfExists(captionPaths, targetDir) {+ const moved = [];+ for (const cp of captionPaths) {+ if (await fileExists(cp)) {+ const result = await moveFileSafely(cp, targetDir, "caption file");+ if (result) moved.push(result);+ }+ }+ return moved.length > 0 ? moved[0] : null;+}++async function moveFileSafely(sourcePath, targetDir, label) {+ try {+ return await moveWithTimestamp(sourcePath, targetDir);+ } catch (error) {+ console.error(`Could not move ${label}: ${error.message}`);+ return null;+ }+}++async function postSingleVideo({ videoPath, caption, postedDir, failedDir, accountId }) {+ const posted = postedDir || config.instagramPostedDir;+ const failed = failedDir || config.instagramFailedDir;+ await ensureDirectories([posted, failed]);++ const result = await uploadVideo({ videoPath, caption, accountId });+ const captionPaths = getCaptionPaths(videoPath);++ if (result.ok) {+ const movedVideo = await moveFileSafely(videoPath, posted, "posted video");+ const movedCaption = await moveCaptionsIfExists(captionPaths, posted);+ if (!movedVideo) {+ return {+ ok: false,+ error: "Video posted, but could not archive file from Instagram queue.",+ screenshotPath: result.screenshotPath,+ };+ }+ return { ok: true, movedVideo, movedCaption };+ }++ const movedVideo = await moveFileSafely(videoPath, failed, "failed video");+ const movedCaption = await moveCaptionsIfExists(captionPaths, failed);+ return {+ ok: false,+ movedVideo,+ movedCaption,+ error: result.error,+ screenshotPath: result.screenshotPath,+ };+}++async function postNextFromQueue({ source, queueDir, postedDir, failedDir, accountId } = {}) {+ const queue = queueDir || config.instagramQueueDir;+ const posted = postedDir || config.instagramPostedDir;+ const failed = failedDir || config.instagramFailedDir;+ await ensureDirectories([queue, posted, failed]);++ const nextItem = await getNextQueuedItem(queue);+ if (!nextItem) {+ return { ok: true, skipped: true, reason: "Instagram queue is empty." };+ }++ return postSingleVideo({ ...nextItem, postedDir: posted, failedDir: failed, accountId });+}++async function postFromManualInput(videoPath, caption) {+ const resolvedPath = path.resolve(videoPath);+ await fs.access(resolvedPath);+ return postSingleVideo({+ videoPath: resolvedPath,+ caption: caption || "",+ });+}++module.exports = {+ postNextFromQueue,+ postFromManualInput,+};diff --git a/src/instagram-queue.js b/src/instagram-queue.jsnew file mode 100644index 0000000..78669c0--- /dev/null+++ b/src/instagram-queue.js@@ -0,0 +1,68 @@+const fs = require("fs/promises");+const path = require("path");+const { config } = require("./config");++const VIDEO_EXTENSIONS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);++function getCaptionPaths(videoPath) {+ const parsed = path.parse(videoPath);+ return [+ path.join(parsed.dir, `${parsed.name}.description`),+ path.join(parsed.dir, `${parsed.name}.txt`),+ ];+}++async function readCaption(videoPath) {+ const captionPaths = getCaptionPaths(videoPath);+ for (const cp of captionPaths) {+ try {+ const text = await fs.readFile(cp, "utf8");+ return text.trim();+ } catch {+ // try next+ }+ }+ return "";+}++async function listQueueVideos(queueDir) {+ const dir = queueDir || config.instagramQueueDir;+ const entries = await fs.readdir(dir, { withFileTypes: true });+ const videos = entries+ .filter((entry) => entry.isFile())+ .filter((entry) => VIDEO_EXTENSIONS.has(path.extname(entry.name).toLowerCase()))+ .map((entry) => path.join(dir, entry.name));++ videos.sort((a, b) => a.localeCompare(b));+ return videos;+}++function pickNextVideo(videos) {+ if (videos.length === 0) {+ return null;+ }+ if (config.randomQueueOrder) {+ return videos[Math.floor(Math.random() * videos.length)];+ }+ return videos[0];+}++async function getNextQueuedItem(queueDir) {+ const videos = await listQueueVideos(queueDir);+ const videoPath = pickNextVideo(videos);+ if (!videoPath) {+ return null;+ }++ const caption = await readCaption(videoPath);+ return {+ videoPath,+ caption,+ captionPaths: getCaptionPaths(videoPath),+ };+}++module.exports = {+ getNextQueuedItem,+ getCaptionPaths,+};\ No newline at end of filediff --git a/src/instagram-uploader.js b/src/instagram-uploader.jsnew file mode 100644index 0000000..292e33e--- /dev/null+++ b/src/instagram-uploader.js@@ -0,0 +1,381 @@+const path = require("path");+const fs = require("fs/promises");+const { chromium } = require("playwright");+const { config } = require("./config");+const uiLabels = require("./platform-ui-labels");+const {+ getActiveAccount,+ getPlatformProfileDir,+ hasSavedPlatformSession,+} = require("./account-manager");++const REALISTIC_USER_AGENT =+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";++let loginSessionContext = null;+let loginSessionAccountId = null;++async function openPersistentContext(accountId) {+ const profileDir = await getPlatformProfileDir("instagram", accountId);+ await fs.mkdir(profileDir, { recursive: true });+ return chromium.launchPersistentContext(profileDir, {+ headless: config.headless,+ viewport: { width: 1400, height: 1000 },+ userAgent: REALISTIC_USER_AGENT,+ locale: config.browserLocale,+ timezoneId: config.timezone,+ args: [+ "--disable-blink-features=AutomationControlled",+ "--disable-infobars",+ "--no-first-run",+ "--no-default-browser-check",+ "--disable-extensions",+ ],+ });+}++/**+ * Navigate with retry logic and exponential backoff.+ * On 429 / network errors, waits and retries up to `maxRetries` times.+ */+async function navigateWithRetry(page, url, { maxRetries = 3, waitUntil = "domcontentloaded" } = {}) {+ const backoffMs = [5000, 15000, 30000];+ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ try {+ const response = await page.goto(url, { waitUntil, timeout: 60000 });+ if (response && response.status() === 429) {+ throw new Error("HTTP 429 - Instagram rate limit");+ }+ // Random human-like pause after navigation (1.5-3.5 s)+ await page.waitForTimeout(1500 + Math.random() * 2000);+ return response;+ } catch (error) {+ if (attempt >= maxRetries) {+ throw error;+ }+ const delay = backoffMs[attempt] || 30000;+ console.log(+ `Instagram navigation failed (attempt ${attempt + 1}/${maxRetries + 1}): ${error.message}. ` ++ `Retrying in ${delay / 1000}s...`+ );+ await page.waitForTimeout(delay);+ }+ }+}++async function gotoUploadPage(page) {+ await navigateWithRetry(page, config.instagramUploadPageUrl);+}++async function startLoginSession() {+ const activeAccount = await getActiveAccount();+ if (loginSessionContext && loginSessionAccountId !== activeAccount.id) {+ const previous = loginSessionContext;+ loginSessionContext = null;+ loginSessionAccountId = null;+ await previous.close().catch(() => { });+ }++ if (loginSessionContext) {+ return { ok: true, alreadyOpen: true };+ }++ const context = await openPersistentContext(activeAccount.id);+ const page = context.pages()[0] || (await context.newPage());+ loginSessionContext = context;+ loginSessionAccountId = activeAccount.id;+ context.on("close", () => {+ if (loginSessionContext === context) {+ loginSessionContext = null;+ loginSessionAccountId = null;+ }+ });++ // Navigate to the homepage first; less suspicious than going straight to /create/.+ await navigateWithRetry(page, "https://www.instagram.com/");+ return { ok: true, alreadyOpen: false, url: page.url() };+}++async function getLoginSessionStatus() {+ const activeAccount = await getActiveAccount();+ const saved = await hasSavedPlatformSession("instagram", activeAccount.id);+ return {+ open: Boolean(loginSessionContext) && loginSessionAccountId === activeAccount.id,+ saved,+ };+}++async function closeLoginSession() {+ if (!loginSessionContext) {+ return { ok: true, alreadyClosed: true };+ }+ const context = loginSessionContext;+ loginSessionContext = null;+ loginSessionAccountId = null;+ await context.close().catch(() => { });+ return { ok: true, alreadyClosed: false };+}++async function clickFirstVisibleEnabledLocator(page, locator) {+ const total = await locator.count();+ for (let i = 0; i < total; i += 1) {+ const candidate = locator.nth(i);+ const visible = await candidate.isVisible().catch(() => false);+ if (!visible) continue;+ const disabled = await candidate.isDisabled().catch(() => false);+ if (disabled) continue;+ try {+ await candidate.scrollIntoViewIfNeeded({ timeout: 3000 });+ await candidate.click({ timeout: 5000 });+ return true;+ } catch {+ try {+ await candidate.click({ timeout: 5000, force: true });+ return true;+ } catch {+ // continue+ }+ }+ }+ return false;+}++async function ensureCreateFlowInput(page) {+ const input = page.locator('input[type="file"]').first();+ if ((await input.count()) > 0) return input;++ const createPattern = uiLabels.pattern("create");+ const postFormatPattern = uiLabels.pattern("instagramPostFormat", "instagramReelFormat");+ const createEntryPoints = [+ page.getByRole("link", { name: createPattern }),+ page.getByRole("button", { name: createPattern }),+ page.locator('a[href*="/create"]').filter({ hasText: createPattern }),+ page.locator('nav a, nav [role="link"], nav button, nav [role="button"]').filter({+ hasText: createPattern,+ }),+ ];++ for (const entry of createEntryPoints) {+ const clicked = await clickFirstVisibleEnabledLocator(page, entry);+ if (!clicked) continue;+ console.log("Instagram create entry clicked.");+ await page.waitForTimeout(1200);+ if ((await input.count()) > 0) return input;+ }++ // Some flows open a chooser first (post/reel/story).+ const formatPickers = [+ ...uiLabels+ .terms("instagramPostFormat", "instagramReelFormat")+ .map((term) => page.getByText(term, { exact: true })),+ page.getByRole("button", { name: postFormatPattern }),+ page.getByRole("menuitem", { name: postFormatPattern }),+ page.getByRole("button", { name: /reel|reels/i }),+ page.locator('[role="menuitem"], [role="option"], button, a').filter({+ hasText: postFormatPattern,+ }),+ ];+ for (const picker of formatPickers) {+ const clicked = await clickFirstVisibleEnabledLocator(page, picker);+ if (!clicked) continue;+ console.log("Instagram post format selected (Post/Reel).");+ await page.waitForTimeout(1200);+ if ((await input.count()) > 0) return input;+ }++ const createButtons = [+ page.getByRole("button", { name: uiLabels.pattern("create", "instagramPostFormat") }),+ page.locator('[role="button"]').filter({ hasText: uiLabels.pattern("create", "instagramPostFormat") }),+ page.locator("a, [role='link']").filter({ hasText: uiLabels.pattern("create", "instagramPostFormat") }),+ ];++ for (const button of createButtons) {+ const clicked = await clickFirstVisibleEnabledLocator(page, button);+ if (clicked) {+ await page.waitForTimeout(1200);+ if ((await input.count()) > 0) return input;+ }+ }++ return input;+}++async function setVideoFile(page, videoPath) {+ let input = await ensureCreateFlowInput(page);+ if ((await input.count()) > 0) {+ await input.waitFor({ state: "attached", timeout: 120000 });+ await input.setInputFiles(videoPath);+ return;+ }++ // Fallback: use file chooser event if no file input is exposed yet.+ const chooserPromise = page.waitForEvent("filechooser", { timeout: 10000 }).catch(() => null);+ const uploadTriggerPattern = uiLabels.pattern("instagramUploadTrigger");+ const uploadTriggers = [+ page.getByRole("button", { name: uploadTriggerPattern }),+ page.locator('button, [role="button"]').filter({+ hasText: uploadTriggerPattern,+ }),+ ];++ for (const trigger of uploadTriggers) {+ const clicked = await clickFirstVisibleEnabledLocator(page, trigger);+ if (clicked) {+ console.log("Instagram upload trigger clicked.");+ break;+ }+ }++ const chooser = await chooserPromise;+ if (chooser) {+ await chooser.setFiles(videoPath);+ return;+ }++ // One last attempt to locate input after opening dialogs.+ input = page.locator('input[type="file"]').first();+ await input.waitFor({ state: "attached", timeout: 120000 });+ await input.setInputFiles(videoPath);+}++async function clickNextButtons(page) {+ const nextSelectors = [+ page.getByRole("button", { name: uiLabels.pattern("next") }),+ page.locator("button").filter({ hasText: uiLabels.pattern("next") }),+ ];++ for (let pass = 0; pass < 3; pass += 1) {+ let clicked = false;+ for (const selector of nextSelectors) {+ const didClick = await clickFirstVisibleEnabledLocator(page, selector);+ if (didClick) {+ clicked = true;+ await page.waitForTimeout(1200);+ break;+ }+ }+ if (!clicked) break;+ }+}++async function setCaption(page, caption) {+ if (!caption) return;+ const candidates = [+ uiLabels.attrSelector("textarea", "aria-label", "captionAttribute"),+ uiLabels.attrSelector("textarea", "placeholder", "captionAttribute"),+ 'textarea',+ 'div[contenteditable="true"]',+ ];++ for (const selector of candidates) {+ const target = page.locator(selector).first();+ if ((await target.count()) === 0) continue;+ try {+ await target.click({ timeout: 8000 });+ await page.keyboard.press("Control+A");+ await page.keyboard.press("Delete");+ await target.type(caption, { delay: 10 });+ return;+ } catch {+ // next+ }+ }+}++async function clickShare(page) {+ const sharePattern = uiLabels.pattern("share");+ const shareLocators = [+ page.getByRole("button", { name: sharePattern }),+ page.locator("button").filter({ hasText: sharePattern }),+ page.locator('[role="button"]').filter({ hasText: sharePattern }),+ ];++ for (const locator of shareLocators) {+ const clicked = await clickFirstVisibleEnabledLocator(page, locator);+ if (clicked) return true;+ }+ return false;+}++async function waitForPostConfirmation(page, startedUrl) {+ // Wait up to 60 * 1500ms = 90 seconds for upload processing+ for (let i = 0; i < 60; i += 1) {+ const text = await page.locator("body").innerText().catch(() => "");+ if (uiLabels.pattern("posted").test(text)) {+ return { ok: true };+ }+ if (uiLabels.pattern("error").test(text)) {+ return { ok: false, reason: "Instagram reported an error while posting." };+ }++ const currentUrl = page.url();+ if (currentUrl !== startedUrl && !/\/create\//i.test(currentUrl)) {+ return { ok: true };+ }+ await page.waitForTimeout(1500);+ }+ return { ok: false, reason: "No reliable Instagram post confirmation within timeout." };+}++async function uploadVideo({ videoPath, caption, accountId }) {+ const absoluteVideoPath = path.resolve(videoPath);+ const context = await openPersistentContext(accountId);+ const page = context.pages()[0] || (await context.newPage());+ let closeHoldMs = 0;++ try {+ await gotoUploadPage(page);+ await setVideoFile(page, absoluteVideoPath);+ await page.waitForTimeout(Math.max(config.postDelayMs, 5000));+ await clickNextButtons(page);+ await setCaption(page, caption || config.defaultCaption);++ const startedUrl = page.url();+ const shared = await clickShare(page);+ if (!shared) {+ throw new Error("Could not find/click Instagram Share button.");+ }++ const confirmation = await waitForPostConfirmation(page, startedUrl);+ if (!confirmation.ok) {+ throw new Error(confirmation.reason);+ }++ const successScreenshotPath = path.resolve(+ config.projectRoot,+ "last-instagram-upload-success.png"+ );+ await page.screenshot({ path: successScreenshotPath, fullPage: true }).catch(() => { });++ // Hold the browser open so background processing finishes+ closeHoldMs = Math.max(config.postPublishHoldMs || 15000, 15000);+ return { ok: true };+ } catch (error) {+ const screenshotPath = path.resolve(+ config.projectRoot,+ "last-instagram-upload-error.png"+ );+ await page.screenshot({ path: screenshotPath, fullPage: true }).catch(() => { });++ closeHoldMs = Math.max(config.failureHoldMs, 0);+ return {+ ok: false,+ error: error.message,+ screenshotPath,+ };+ } finally {+ if (closeHoldMs > 0) {+ console.log(`Holding browser for ${closeHoldMs / 1000}s before closing...`);+ await page.waitForTimeout(closeHoldMs).catch(() => { });+ }+ await context.close();+ }+}++module.exports = {+ uploadVideo,+ startLoginSession,+ getLoginSessionStatus,+ closeLoginSession,+};+diff --git a/src/migrate-queue.js b/src/migrate-queue.jsnew file mode 100644index 0000000..3c4dc0d--- /dev/null+++ b/src/migrate-queue.js@@ -0,0 +1,152 @@+const fs = require("fs/promises");+const path = require("path");+const { config } = require("./config");+const { ensureAccountDirs } = require("./account-manager");++const QUEUE_ROOT = path.resolve(config.projectRoot, "queue");+const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);++/**+ * Migrate old flat queue layout to new per-profile structure.+ *+ * Old: queue/pending/ queue/posted/ queue/failed/+ * queue/instagram/pending/ queue/instagram/posted/ queue/instagram/failed/+ * queue/youtube/pending/ queue/youtube/posted/ queue/youtube/failed/+ *+ * New: queue/default/tiktok/pending/ ...+ * queue/default/instagram/pending/ ...+ * queue/default/youtube/pending/ ...+ */+async function migrateQueueIfNeeded() {+ // Check if migration is needed: old layout has queue/pending as a direct child+ const oldPendingDir = path.resolve(QUEUE_ROOT, "pending");+ const newDefaultDir = path.resolve(QUEUE_ROOT, "default", "tiktok");++ let needsMigration = false;+ try {+ const stat = await fs.stat(oldPendingDir);+ if (stat.isDirectory()) {+ needsMigration = true;+ }+ } catch {+ // No old pending dir = no migration needed+ }++ // Also check if old instagram/ youtube dirs exist at queue level+ const oldIgDir = path.resolve(QUEUE_ROOT, "instagram");+ const oldYtDir = path.resolve(QUEUE_ROOT, "youtube");++ let hasOldIg = false;+ let hasOldYt = false;+ try {+ const stat = await fs.stat(path.resolve(oldIgDir, "pending"));+ hasOldIg = stat.isDirectory();+ } catch { }+ try {+ const stat = await fs.stat(path.resolve(oldYtDir, "pending"));+ hasOldYt = stat.isDirectory();+ } catch { }++ if (!needsMigration && !hasOldIg && !hasOldYt) {+ return { migrated: false, reason: "No old layout detected" };+ }++ console.log("[migrate] Old queue layout detected. Migrating to per-profile structure...");++ // Ensure new default dirs exist+ await ensureAccountDirs("default");++ const moved = { tiktok: 0, instagram: 0, youtube: 0 };++ // Migrate TikTok: queue/pending -> queue/default/tiktok/pending+ if (needsMigration) {+ for (const sub of ["pending", "posted", "failed"]) {+ const src = path.resolve(QUEUE_ROOT, sub);+ const dst = path.resolve(QUEUE_ROOT, "default", "tiktok", sub);+ moved.tiktok += await moveFiles(src, dst);+ }+ }++ // Migrate Instagram: queue/instagram/pending -> queue/default/instagram/pending+ if (hasOldIg) {+ for (const sub of ["pending", "posted", "failed"]) {+ const src = path.resolve(oldIgDir, sub);+ const dst = path.resolve(QUEUE_ROOT, "default", "instagram", sub);+ moved.instagram += await moveFiles(src, dst);+ }+ }++ // Migrate YouTube: queue/youtube/pending -> queue/default/youtube/pending+ if (hasOldYt) {+ for (const sub of ["pending", "posted", "failed"]) {+ const src = path.resolve(oldYtDir, sub);+ const dst = path.resolve(QUEUE_ROOT, "default", "youtube", sub);+ moved.youtube += await moveFiles(src, dst);+ }+ }++ // Clean up empty old directories+ await cleanupOldDirs();++ console.log(`[migrate] Done. Moved: TikTok=${moved.tiktok}, Instagram=${moved.instagram}, YouTube=${moved.youtube}`);+ return { migrated: true, moved };+}++async function moveFiles(srcDir, dstDir) {+ let count = 0;+ try {+ const entries = await fs.readdir(srcDir, { withFileTypes: true });+ for (const entry of entries) {+ if (!entry.isFile()) continue;+ const srcPath = path.resolve(srcDir, entry.name);+ const dstPath = path.resolve(dstDir, entry.name);+ try {+ await fs.rename(srcPath, dstPath);+ count++;+ } catch (err) {+ // If rename fails (cross-device), copy + delete+ try {+ await fs.copyFile(srcPath, dstPath);+ await fs.unlink(srcPath);+ count++;+ } catch (copyErr) {+ console.warn(`[migrate] Failed to move ${entry.name}: ${copyErr.message}`);+ }+ }+ }+ } catch {+ // Source dir doesn't exist, nothing to move+ }+ return count;+}++async function cleanupOldDirs() {+ // Remove old flat dirs if they're now empty+ const dirsToClean = [+ path.resolve(QUEUE_ROOT, "pending"),+ path.resolve(QUEUE_ROOT, "posted"),+ path.resolve(QUEUE_ROOT, "failed"),+ path.resolve(QUEUE_ROOT, "instagram", "pending"),+ path.resolve(QUEUE_ROOT, "instagram", "posted"),+ path.resolve(QUEUE_ROOT, "instagram", "failed"),+ path.resolve(QUEUE_ROOT, "instagram"),+ path.resolve(QUEUE_ROOT, "youtube", "pending"),+ path.resolve(QUEUE_ROOT, "youtube", "posted"),+ path.resolve(QUEUE_ROOT, "youtube", "failed"),+ path.resolve(QUEUE_ROOT, "youtube"),+ ];++ for (const dir of dirsToClean) {+ try {+ const entries = await fs.readdir(dir);+ if (entries.length === 0) {+ await fs.rmdir(dir);+ console.log(`[migrate] Removed empty dir: ${path.relative(QUEUE_ROOT, dir)}`);+ }+ } catch {+ // Dir doesn't exist or not empty, skip+ }+ }+}++module.exports = { migrateQueueIfNeeded };diff --git a/src/platform-ui-labels.js b/src/platform-ui-labels.jsnew file mode 100644index 0000000..704970a--- /dev/null+++ b/src/platform-ui-labels.js@@ -0,0 +1,110 @@+// Localized third-party platform labels used only for browser automation selectors.+const LABELS = {+ create: ["create", "erstellen"],+ instagramPostFormat: ["post", "beitrag"],+ instagramReelFormat: ["reel", "reels"],+ instagramUploadTrigger: ["from computer", "select from computer", "vom computer", "ausw\u00e4hlen"],+ next: ["next", "weiter"],+ captionAttribute: ["caption", "beschreib"],+ share: ["share", "post", "publish", "teilen", "posten"],+ posted: ["shared", "posted", "geteilt", "ver\u00f6ffentlicht", "beitrag wurde geteilt"],+ error: ["error", "failed", "couldn't", "fehler", "nicht m\u00f6glich", "konnte nicht"],++ youtubeCreate: ["create", "erstellen"],+ youtubeUploadVideo: ["upload videos", "upload video", "videos hochladen", "video hochladen"],+ youtubeSelectFiles: ["select files", "dateien ausw\u00e4hlen"],+ youtubeTitleAttribute: ["title", "titel"],+ youtubeDescriptionAttribute: ["description", "beschreibung"],+ youtubeNotMadeForKids: [+ "not made for kids",+ "nicht fur kinder",+ "nicht f\u00fcr kinder",+ "nicht speziell fur kinder",+ "nicht speziell f\u00fcr kinder",+ ],+ youtubePublic: ["public", "\u00f6ffentlich"],+ youtubePublish: ["publish", "ver\u00f6ffentlichen"],+ youtubeSave: ["save", "speichern"],+ youtubePublished: ["published", "processing", "ver\u00f6ffentlicht", "verarbeitet"],++ tiktokSearchSounds: ["Search sounds", "Sounds suchen"],+ tiktokEdit: ["edit", "bearbeiten"],+ tiktokSounds: ["sound", "sounds", "audio"],+ tiktokText: ["text"],+ tiktokSave: ["Save", "Speichern"],+ tiktokCancel: ["Cancel", "Abbrechen"],+ tiktokShortContentCheck: ["short content check", "kurze inhaltsprufung", "kurze inhaltspr\u00fcfung"],+ tiktokEnable: ["enable", "turn on", "allow", "ok", "einschalten", "aktivieren"],+ tiktokContinue: ["got it", "continue", "verstanden", "weiter", "fortfahren"],+ tiktokLater: ["later", "not now", "skip", "spater", "spaeter", "sp\u00e4ter"],+ tiktokClose: ["cancel", "close", "abbrechen", "schliessen", "schlie\u00dfen"],+ tiktokPublish: ["publish", "post", "ver\u00f6ffentlichen", "veroeffentlichen", "publicar", "publier", "pubblica"],+ tiktokPublished: [+ "published",+ "posted",+ "success",+ "scheduled",+ "ver\u00f6ffentlicht",+ "veroeffentlicht",+ "erfolgreich",+ "geplant",+ "zur prufung eingereicht",+ "zur pr\u00fcfung eingereicht",+ ],+ tiktokFailed: [+ "failed",+ "error",+ "could not",+ "retry",+ "nicht moglich",+ "nicht m\u00f6glich",+ "fehlgeschlagen",+ "erneut versuchen",+ ],+ tiktokConfirm: [+ "publish",+ "post",+ "confirm",+ "continue",+ "ver\u00f6ffentlichen",+ "veroeffentlichen",+ "best\u00e4tigen",+ "bestaetigen",+ "fortfahren",+ ],+};++function escapeRegExp(value) {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++function terms(...keys) {+ return keys.flatMap((key) => LABELS[key] || []);+}++function pattern(...keys) {+ const values = terms(...keys);+ if (values.length === 0) {+ throw new Error(`No platform UI labels configured for: ${keys.join(", ")}`);+ }+ return new RegExp(values.map(escapeRegExp).join("|"), "i");+}++function textSelector(selector, ...keys) {+ return terms(...keys)+ .map((value) => `${selector}:has-text("${value.replace(/"/g, '\\"')}")`)+ .join(", ");+}++function attrSelector(selector, attr, ...keys) {+ return terms(...keys)+ .map((value) => `${selector}[${attr}*="${value.replace(/"/g, '\\"')}" i]`)+ .join(", ");+}++module.exports = {+ attrSelector,+ pattern,+ terms,+ textSelector,+};diff --git a/src/post-service.js b/src/post-service.jsnew file mode 100644index 0000000..b693f06--- /dev/null+++ b/src/post-service.js@@ -0,0 +1,86 @@+const fs = require("fs/promises");+const path = require("path");+const { config } = require("./config");+const { getNextQueuedItem, getCaptionPaths } = require("./queue");+const { uploadVideo } = require("./tiktok-uploader");+const { ensureDirectories, fileExists, moveWithTimestamp } = require("./fs-utils");++async function moveCaptionsIfExists(captionPaths, targetDir) {+ const moved = [];+ for (const cp of captionPaths) {+ if (await fileExists(cp)) {+ const result = await moveFileSafely(cp, targetDir, "caption file");+ if (result) moved.push(result);+ }+ }+ return moved.length > 0 ? moved[0] : null;+}++async function moveFileSafely(sourcePath, targetDir, label) {+ try {+ return await moveWithTimestamp(sourcePath, targetDir);+ } catch (error) {+ console.error(`Could not move ${label}: ${error.message}`);+ return null;+ }+}++async function postSingleVideo({ videoPath, caption, source, postedDir, failedDir, accountId }) {+ const posted = postedDir || config.postedDir;+ const failed = failedDir || config.failedDir;+ await ensureDirectories([posted, failed]);++ const result = await uploadVideo({ videoPath, caption, source, accountId });+ const captionPaths = getCaptionPaths(videoPath);++ if (result.ok) {+ const movedVideo = await moveFileSafely(videoPath, posted, "posted video");+ const movedCaption = await moveCaptionsIfExists(captionPaths, posted);+ if (!movedVideo) {+ return {+ ok: false,+ error: "Video posted, but could not archive file from queue.",+ screenshotPath: result.screenshotPath,+ };+ }+ return { ok: true, movedVideo, movedCaption };+ }++ const movedVideo = await moveFileSafely(videoPath, failed, "failed video");+ const movedCaption = await moveCaptionsIfExists(captionPaths, failed);+ return {+ ok: false,+ movedVideo,+ movedCaption,+ error: result.error,+ screenshotPath: result.screenshotPath,+ };+}++async function postNextFromQueue({ source, queueDir, postedDir, failedDir, accountId } = {}) {+ const queue = queueDir || config.queueDir;+ const posted = postedDir || config.postedDir;+ const failed = failedDir || config.failedDir;+ await ensureDirectories([queue, posted, failed]);++ const nextItem = await getNextQueuedItem(queue);+ if (!nextItem) {+ return { ok: true, skipped: true, reason: "Queue is empty." };+ }++ return postSingleVideo({ ...nextItem, source, postedDir: posted, failedDir: failed, accountId });+}++async function postFromManualInput(videoPath, caption) {+ const resolvedPath = path.resolve(videoPath);+ await fs.access(resolvedPath);+ return postSingleVideo({+ videoPath: resolvedPath,+ caption: caption || "",+ });+}++module.exports = {+ postNextFromQueue,+ postFromManualInput,+};diff --git a/src/profile-download-controller.js b/src/profile-download-controller.jsnew file mode 100644index 0000000..5646564--- /dev/null+++ b/src/profile-download-controller.js@@ -0,0 +1,165 @@+/**+ * ProfileDownloadController+ *+ * One-off downloader allowing the user to scrape a specific TikTok channel+ * with filters (like min-views), saving it explicitly to autodownload/profile_downloads/+ * to prevent auto-queue insertion.+ */++const fsSync = require("fs");+const path = require("path");+const { execFile } = require("child_process");+const { config } = require("./config");+const { enrichRecentSlideshowDownloads } = require("./tiktok-slideshow-downloader");++function nowIso() {+ return new Date().toISOString();+}++function ensureDir(dir) {+ if (!fsSync.existsSync(dir)) fsSync.mkdirSync(dir, { recursive: true });+}++class ProfileDownloadController {+ constructor() {+ this.running = false;+ this.logs = [];++ this.baseDir = path.resolve(config.projectRoot, "autodownload");+ this.ytDlp = path.join(this.baseDir, "yt-dlp.exe");+ this.downloadsDir = path.join(this.baseDir, "profile_downloads");++ ensureDir(this.downloadsDir);+ }++ log(message, level = "info") {+ const entry = { at: nowIso(), level, message };+ this.logs.unshift(entry);+ this.logs = this.logs.slice(0, 120);+ const prefix = `[${entry.at}] [profile-download]`;+ if (level === "error") {+ console.error(`${prefix} ${message}`);+ } else {+ console.log(`${prefix} ${message}`);+ }+ }++ _channelUrl(channel) {+ let ch = String(channel).trim();+ if (ch.startsWith("http")) return ch;+ if (!ch.startsWith("@")) ch = "@" + ch;+ return `https://www.tiktok.com/${ch}`;+ }++ async start({ channel, minViews, maxVideos, scanOnly }) {+ if (this.running) {+ return { ok: false, error: "A profile download is already in progress." };+ }+ if (!channel) {+ return { ok: false, error: "No channel provided." };+ }++ const max = parseInt(maxVideos, 10) || 0;+ const min = parseInt(minViews, 10) || 0;+ const isScan = Boolean(scanOnly);+ const url = this._channelUrl(channel);++ this.running = true;+ this.logs = [];++ this.log(`Starting Profile ${isScan ? "Scan" : "Download"} - Target: ${url}`);+ this.log(`Parameters - Max loop: ${max > 0 ? max : "All"} videos, Minimum views: ${min > 0 ? min : "None"}`);++ this._runYtDlp(url, min, max, isScan)+ .then(() => {+ this.log("Profile download session finished.");+ this.running = false;+ })+ .catch((err) => {+ this.log(`Profile download error: ${err.message}`, "error");+ this.running = false;+ });++ return { ok: true };+ }++ _runYtDlp(url, minViews, maxVideos, scanOnly) {+ return new Promise((resolve) => {+ const startedAtMs = Date.now();+ const dlArgs = [+ "--no-warnings",+ "-S", "vcodec:h264,res,acodec"+ ];++ if (maxVideos > 0) {+ dlArgs.push("--playlist-items", `1:${maxVideos}`);+ }++ if (scanOnly) {+ dlArgs.push("--simulate");+ dlArgs.push("--print", "Found Video - ID: %(id)s | Views: %(view_count)s");+ } else {+ dlArgs.push("-o", path.join(this.downloadsDir, "%(uploader)s", "%(upload_date)s_%(id)s.%(ext)s"));+ dlArgs.push("--write-description");+ dlArgs.push("--write-info-json");+ }++ if (minViews > 0) {+ dlArgs.push("--match-filter", `view_count >= ${minViews}`);+ }++ dlArgs.push(url);++ this.log(`Checking ${url} for videos matching criteria...`);++ execFile(this.ytDlp, dlArgs, { timeout: 300_000 }, async (err, stdout, stderr) => {+ if (stdout) {+ const lines = stdout.trim().split("\n").filter(Boolean);+ lines.forEach((line) => this.log(` yt-dlp: ${line}`));+ }+ if (stderr) {+ const lines = stderr.trim().split("\n").filter(Boolean);+ lines.forEach((line) => this.log(` yt-dlp: ${line}`));+ }+ if (err) {+ if (err.code === 101) {+ this.log("Search criteria likely returned no videos.");+ return resolve();+ }+ this.log(`yt-dlp error: ${err.message}`, "error");+ return resolve();+ }++ if (!scanOnly) {+ try {+ const summary = await enrichRecentSlideshowDownloads(+ this.downloadsDir,+ startedAtMs,+ (message, level = "info") => this.log(message, level)+ );++ if (summary.processed > 0) {+ this.log(+ `Slideshow enrichment complete - processed ${summary.processed} post(s), saved ${summary.images} image(s).`+ );+ }+ } catch (slideshowError) {+ this.log(`Slideshow enrichment failed: ${slideshowError.message}`, "error");+ }+ }++ resolve();+ });+ });+ }++ getStatus() {+ return {+ running: this.running,+ logs: this.logs,+ downloadsDir: this.downloadsDir+ };+ }+}++module.exports = { ProfileDownloadController };diff --git a/src/queue.js b/src/queue.jsnew file mode 100644index 0000000..3bd2e30--- /dev/null+++ b/src/queue.js@@ -0,0 +1,70 @@+const fs = require("fs/promises");+const path = require("path");+const { config } = require("./config");++const VIDEO_EXTENSIONS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);++function getCaptionPaths(videoPath) {+ const parsed = path.parse(videoPath);+ return [+ path.join(parsed.dir, `${parsed.name}.description`),+ path.join(parsed.dir, `${parsed.name}.txt`),+ ];+}++async function readCaption(videoPath) {+ const captionPaths = getCaptionPaths(videoPath);+ for (const cp of captionPaths) {+ try {+ const text = await fs.readFile(cp, "utf8");+ return text.trim();+ } catch {+ // try next+ }+ }+ return "";+}++async function listQueueVideos(queueDir) {+ const dir = queueDir || config.queueDir;+ const entries = await fs.readdir(dir, { withFileTypes: true });+ const videos = entries+ .filter((entry) => entry.isFile())+ .filter((entry) => VIDEO_EXTENSIONS.has(path.extname(entry.name).toLowerCase()))+ .map((entry) => path.join(dir, entry.name));++ videos.sort((a, b) => a.localeCompare(b));+ return videos;+}++function pickNextVideo(videos) {+ if (videos.length === 0) {+ return null;+ }+ if (config.randomQueueOrder) {+ return videos[Math.floor(Math.random() * videos.length)];+ }+ return videos[0];+}++async function getNextQueuedItem(queueDir) {+ const videos = await listQueueVideos(queueDir);+ const videoPath = pickNextVideo(videos);+ if (!videoPath) {+ return null;+ }++ const caption = await readCaption(videoPath);+ return {+ videoPath,+ caption,+ captionPaths: getCaptionPaths(videoPath),+ };+}++module.exports = {+ getNextQueuedItem,+ getCaptionPaths,+ listQueueVideos,+ VIDEO_EXTENSIONS,+};\ No newline at end of filediff --git a/src/request-guard.js b/src/request-guard.jsnew file mode 100644index 0000000..ad40847--- /dev/null+++ b/src/request-guard.js@@ -0,0 +1,66 @@+const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);++function getHeader(headers, name) {+ if (!headers) return "";+ if (typeof headers.get === "function") {+ return headers.get(name) || "";+ }+ return headers[name.toLowerCase()] || headers[name] || "";+}++function hasSameHost(urlValue, host) {+ if (!urlValue || !host || urlValue === "null") {+ return false;+ }++ try {+ const parsed = new URL(urlValue);+ return parsed.host.toLowerCase() === String(host).toLowerCase();+ } catch {+ return false;+ }+}++function isAllowedDashboardRequest({ method, headers }) {+ if (SAFE_METHODS.has(String(method || "").toUpperCase())) {+ return true;+ }++ const host = getHeader(headers, "host");+ const origin = getHeader(headers, "origin");+ const referer = getHeader(headers, "referer");+ const fetchSite = getHeader(headers, "sec-fetch-site").toLowerCase();++ if (origin) {+ return hasSameHost(origin, host);+ }++ if (referer) {+ return hasSameHost(referer, host);+ }++ if (fetchSite === "cross-site") {+ return false;+ }++ return true;+}++function createDashboardRequestGuard() {+ return (req, res, next) => {+ if (isAllowedDashboardRequest({ method: req.method, headers: req.headers })) {+ next();+ return;+ }++ res.status(403).json({+ ok: false,+ error: "Cross-origin dashboard requests are blocked.",+ });+ };+}++module.exports = {+ createDashboardRequestGuard,+ isAllowedDashboardRequest,+};diff --git a/src/scheduler.js b/src/scheduler.jsnew file mode 100644index 0000000..12df6bd--- /dev/null+++ b/src/scheduler.js@@ -0,0 +1,49 @@+const cron = require("node-cron");+const { config } = require("./config");+const { postNextFromQueue } = require("./post-service");++function now() {+ return new Date().toISOString();+}++async function runScheduledPost() {+ console.log(`[${now()}] Checking queue...`);+ const result = await postNextFromQueue();+ if (result.skipped) {+ console.log(`[${now()}] ${result.reason}`);+ return;+ }++ if (result.ok) {+ console.log(`[${now()}] Posted successfully: ${result.movedVideo}`);+ } else {+ console.error(`[${now()}] Post failed: ${result.error}`);+ if (result.screenshotPath) {+ console.error(`[${now()}] Screenshot: ${result.screenshotPath}`);+ }+ }+}++function startDaemon() {+ if (!cron.validate(config.cronExpression)) {+ throw new Error(`Invalid CRON_EXPRESSION: ${config.cronExpression}`);+ }++ console.log(`Starting scheduler: ${config.cronExpression} (${config.timezone})`);+ console.log("Press Ctrl+C to stop.");++ cron.schedule(+ config.cronExpression,+ async () => {+ await runScheduledPost();+ },+ {+ timezone: config.timezone,+ }+ );+}++module.exports = {+ startDaemon,+ runScheduledPost,+};diff --git a/src/tiktok-slideshow-downloader.js b/src/tiktok-slideshow-downloader.jsnew file mode 100644index 0000000..2c7d64d--- /dev/null+++ b/src/tiktok-slideshow-downloader.js@@ -0,0 +1,540 @@+const fs = require("fs/promises");+const path = require("path");++const INFO_JSON_SUFFIX = ".info.json";++function normalizeUrlCandidate(value) {+ if (typeof value !== "string") {+ return null;+ }++ const trimmed = value.trim();+ if (!trimmed) {+ return null;+ }++ if (/^https?:\/\//i.test(trimmed)) {+ return trimmed;+ }++ if (trimmed.startsWith("//")) {+ return `https:${trimmed}`;+ }++ return null;+}++function pickFirstUrl(...candidates) {+ for (const candidate of candidates) {+ if (!candidate) {+ continue;+ }++ if (Array.isArray(candidate)) {+ for (const value of candidate) {+ const normalized = normalizeUrlCandidate(value);+ if (normalized) {+ return normalized;+ }+ }+ continue;+ }++ const normalized = normalizeUrlCandidate(candidate);+ if (normalized) {+ return normalized;+ }+ }++ return null;+}++function isObject(value) {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function escapeRegExp(value) {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++function extractScriptJson(html, scriptId) {+ const escapedId = escapeRegExp(scriptId);+ const regex = new RegExp(+ `<script[^>]+id=["']${escapedId}["'][^>]*>([\\s\\S]*?)<\\/script>`,+ "i"+ );+ const match = html.match(regex);+ if (!match) {+ return null;+ }++ try {+ return JSON.parse(match[1]);+ } catch {+ return null;+ }+}++function findItemStructById(root, videoId) {+ if (!root || typeof root !== "object") {+ return null;+ }++ const stack = [root];+ const seen = new Set();++ while (stack.length > 0) {+ const current = stack.pop();+ if (!current || typeof current !== "object") {+ continue;+ }+ if (seen.has(current)) {+ continue;+ }+ seen.add(current);++ if (+ isObject(current) &&+ (current.id === videoId ||+ current.aweme_id === videoId ||+ current.awemeId === videoId ||+ current.itemId === videoId)+ ) {+ return current;+ }++ if (Array.isArray(current)) {+ for (const entry of current) {+ stack.push(entry);+ }+ continue;+ }++ for (const value of Object.values(current)) {+ if (value && typeof value === "object") {+ stack.push(value);+ }+ }+ }++ return null;+}++function findFirstArrayByKeys(root, allowedKeys) {+ if (!root || typeof root !== "object") {+ return null;+ }++ const stack = [root];+ const seen = new Set();++ while (stack.length > 0) {+ const current = stack.pop();+ if (!current || typeof current !== "object") {+ continue;+ }+ if (seen.has(current)) {+ continue;+ }+ seen.add(current);++ if (Array.isArray(current)) {+ for (const entry of current) {+ if (entry && typeof entry === "object") {+ stack.push(entry);+ }+ }+ continue;+ }++ for (const [key, value] of Object.entries(current)) {+ if (allowedKeys.has(key) && Array.isArray(value) && value.length > 0) {+ return value;+ }++ if (value && typeof value === "object") {+ stack.push(value);+ }+ }+ }++ return null;+}++function extractImageUrlFromEntry(entry) {+ if (typeof entry === "string") {+ return normalizeUrlCandidate(entry);+ }++ if (!isObject(entry)) {+ return null;+ }++ return pickFirstUrl(+ entry.imageURL?.urlList,+ entry.imageUrl?.urlList,+ entry.displayImage?.urlList,+ entry.ownerWatermarkImage?.urlList,+ entry.thumbnail?.urlList,+ entry.urlList,+ entry.url,+ entry.src+ );+}++function extractItemStructFromHtml(html, videoId) {+ const universal = extractScriptJson(html, "__UNIVERSAL_DATA_FOR_REHYDRATION__");+ const universalItem =+ universal?.__DEFAULT_SCOPE__?.["webapp.video-detail"]?.itemInfo?.itemStruct ||+ findItemStructById(universal, videoId);+ if (universalItem) {+ return universalItem;+ }++ const sigi =+ extractScriptJson(html, "SIGI_STATE") ||+ extractScriptJson(html, "sigi-persisted-data");+ return findItemStructById(sigi, videoId);+}++function extractSlideshowImageUrls(itemStruct) {+ if (!itemStruct) {+ return [];+ }++ const imageEntries =+ itemStruct.imagePost?.images ||+ itemStruct.imagePost?.imageList ||+ itemStruct.images ||+ findFirstArrayByKeys(+ itemStruct.imagePost || itemStruct,+ new Set(["images", "imageList", "slides"])+ );++ if (!Array.isArray(imageEntries) || imageEntries.length === 0) {+ return [];+ }++ const urls = [];+ const seen = new Set();++ for (const entry of imageEntries) {+ const url = extractImageUrlFromEntry(entry);+ if (!url || seen.has(url)) {+ continue;+ }++ seen.add(url);+ urls.push(url);+ }++ return urls;+}++function looksLikeAudioOnlyFormat(formats) {+ if (!Array.isArray(formats) || formats.length === 0) {+ return false;+ }++ let sawAudioOnly = false;+ for (const format of formats) {+ if (!format || typeof format !== "object") {+ continue;+ }++ const vcodec = String(format.vcodec || "").toLowerCase();+ if (vcodec && vcodec !== "none") {+ return false;+ }++ if (vcodec === "none") {+ sawAudioOnly = true;+ }+ }++ return sawAudioOnly;+}++function isLikelySlideshowInfo(info) {+ if (!info || typeof info !== "object") {+ return false;+ }++ const webpageUrl = String(info.webpage_url || info.original_url || "");+ if (!/tiktok\.com/i.test(webpageUrl)) {+ return false;+ }++ if (looksLikeAudioOnlyFormat(info.formats)) {+ return true;+ }++ const ext = String(info.ext || "").toLowerCase();+ return ext === "m4a" || ext === "mp3" || ext === "aac";+}++function getBaseStemFromInfoJsonPath(infoJsonPath) {+ const fileName = path.basename(infoJsonPath);+ if (!fileName.endsWith(INFO_JSON_SUFFIX)) {+ return path.join(path.dirname(infoJsonPath), path.parse(fileName).name);+ }++ return path.join(+ path.dirname(infoJsonPath),+ fileName.slice(0, -INFO_JSON_SUFFIX.length)+ );+}++function getHeadersFromInfo(info) {+ const sourceHeaders = isObject(info.http_headers) ? info.http_headers : {};+ const headers = {+ "User-Agent":+ sourceHeaders["User-Agent"] ||+ sourceHeaders["user-agent"] ||+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",+ Accept:+ sourceHeaders.Accept ||+ sourceHeaders.accept ||+ "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",+ "Accept-Language":+ sourceHeaders["Accept-Language"] ||+ sourceHeaders["accept-language"] ||+ "en-US,en;q=0.9",+ };++ const referer =+ sourceHeaders.Referer ||+ sourceHeaders.referer ||+ info.webpage_url ||+ info.original_url;+ if (referer) {+ headers.Referer = referer;+ }++ return headers;+}++async function fetchText(url, headers) {+ if (typeof fetch !== "function") {+ throw new Error("Global fetch is unavailable. Node 18+ is required.");+ }++ const response = await fetch(url, {+ headers,+ redirect: "follow",+ });++ if (!response.ok) {+ throw new Error(`HTTP ${response.status} while requesting ${url}`);+ }++ return response.text();+}++function inferImageExtension(url, contentType) {+ const normalizedType = String(contentType || "")+ .split(";")[0]+ .trim()+ .toLowerCase();++ const typeMap = {+ "image/jpeg": "jpg",+ "image/jpg": "jpg",+ "image/png": "png",+ "image/webp": "webp",+ "image/heic": "heic",+ "image/heif": "heif",+ };++ if (typeMap[normalizedType]) {+ return typeMap[normalizedType];+ }++ try {+ const pathname = new URL(url).pathname;+ const ext = path.extname(pathname).replace(/^\./, "").toLowerCase();+ if (ext) {+ return ext;+ }+ } catch {+ // Ignore bad URLs and fall back to jpg.+ }++ return "jpg";+}++async function downloadImage(url, destinationStem, headers) {+ const response = await fetch(url, {+ headers: {+ ...headers,+ Accept: "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",+ },+ redirect: "follow",+ });++ if (!response.ok) {+ throw new Error(`HTTP ${response.status} while downloading ${url}`);+ }++ const extension = inferImageExtension(+ response.url || url,+ response.headers.get("content-type")+ );+ const finalPath = `${destinationStem}.${extension}`;+ const buffer = Buffer.from(await response.arrayBuffer());+ await fs.writeFile(finalPath, buffer);+ return finalPath;+}++async function collectRecentInfoJsonFiles(rootDir, sinceMs) {+ const infoFiles = [];++ async function walk(currentDir) {+ let entries = [];+ try {+ entries = await fs.readdir(currentDir, { withFileTypes: true });+ } catch {+ return;+ }++ for (const entry of entries) {+ const fullPath = path.join(currentDir, entry.name);+ if (entry.isDirectory()) {+ await walk(fullPath);+ continue;+ }++ if (!entry.isFile() || !entry.name.endsWith(INFO_JSON_SUFFIX)) {+ continue;+ }++ try {+ const stat = await fs.stat(fullPath);+ if (stat.mtimeMs >= sinceMs - 2000) {+ infoFiles.push(fullPath);+ }+ } catch {+ // Ignore files that disappear mid-scan.+ }+ }+ }++ await walk(rootDir);+ return infoFiles.sort((a, b) => a.localeCompare(b));+}++async function downloadSlideshowAssetsForInfo(infoJsonPath, log) {+ let info;+ try {+ info = JSON.parse(await fs.readFile(infoJsonPath, "utf8"));+ } catch (error) {+ log(+ `Could not read slideshow info file ${path.basename(infoJsonPath)}: ${error.message}`,+ "error"+ );+ return { processed: false, imageCount: 0 };+ }++ if (!isLikelySlideshowInfo(info)) {+ return { processed: false, imageCount: 0 };+ }++ const webpageUrl = info.webpage_url || info.original_url;+ if (!webpageUrl) {+ log(+ `Skipping slideshow asset lookup for ${path.basename(infoJsonPath)}: missing webpage URL.`,+ "error"+ );+ return { processed: false, imageCount: 0 };+ }++ log(+ `Detected audio-only TikTok post ${info.id || path.basename(+ infoJsonPath+ )}. Looking for slideshow images...`+ );++ let html;+ try {+ html = await fetchText(webpageUrl, getHeadersFromInfo(info));+ } catch (error) {+ log(`Could not fetch slideshow page ${webpageUrl}: ${error.message}`, "error");+ return { processed: false, imageCount: 0 };+ }++ const itemStruct = extractItemStructFromHtml(html, String(info.id || ""));+ const imageUrls = extractSlideshowImageUrls(itemStruct);++ if (imageUrls.length === 0) {+ log(`No slideshow images found for ${info.id || path.basename(infoJsonPath)}.`, "error");+ return { processed: true, imageCount: 0 };+ }++ const slidesDir = `${getBaseStemFromInfoJsonPath(infoJsonPath)}_slides`;+ await fs.mkdir(slidesDir, { recursive: true });++ const headers = getHeadersFromInfo(info);+ let downloadedCount = 0;++ for (let index = 0; index < imageUrls.length; index += 1) {+ const targetStem = path.join(+ slidesDir,+ `slide-${String(index + 1).padStart(2, "0")}`+ );++ try {+ const finalPath = await downloadImage(imageUrls[index], targetStem, headers);+ downloadedCount += 1;+ log(+ ` Saved slideshow image ${downloadedCount}/${imageUrls.length}: ${path.basename(+ finalPath+ )}`+ );+ } catch (error) {+ log(` Failed to download slideshow image ${index + 1}: ${error.message}`, "error");+ }+ }++ if (downloadedCount > 0) {+ log(`Saved ${downloadedCount} slideshow image(s) to ${slidesDir}`);+ }++ return {+ processed: true,+ imageCount: downloadedCount,+ };+}++async function enrichRecentSlideshowDownloads(downloadsDir, sinceMs, log) {+ const infoJsonFiles = await collectRecentInfoJsonFiles(downloadsDir, sinceMs);+ if (infoJsonFiles.length === 0) {+ return {+ candidates: 0,+ processed: 0,+ images: 0,+ };+ }++ let processed = 0;+ let images = 0;++ for (const infoJsonPath of infoJsonFiles) {+ const result = await downloadSlideshowAssetsForInfo(infoJsonPath, log);+ if (!result.processed) {+ continue;+ }++ processed += 1;+ images += result.imageCount;+ }++ return {+ candidates: infoJsonFiles.length,+ processed,+ images,+ };+}++module.exports = {+ enrichRecentSlideshowDownloads,+};diff --git a/src/tiktok-uploader.js b/src/tiktok-uploader.jsnew file mode 100644index 0000000..921b871--- /dev/null+++ b/src/tiktok-uploader.js@@ -0,0 +1,1089 @@+const path = require("path");+const fs = require("fs/promises");+const { chromium } = require("playwright");+const { config } = require("./config");+const uiLabels = require("./platform-ui-labels");+const {+ getActiveAccount,+ getPlatformProfileDir,+ hasSavedPlatformSession,+} = require("./account-manager");++let loginSessionContext = null;+let loginSessionAccountId = null;++async function openPersistentContext(accountId) {+ const profileDir = await getPlatformProfileDir("tiktok", accountId);+ await fs.mkdir(profileDir, { recursive: true });+ return chromium.launchPersistentContext(profileDir, {+ headless: config.headless,+ viewport: { width: 1400, height: 1000 },+ locale: config.browserLocale,+ timezoneId: config.timezone,+ args: ["--disable-blink-features=AutomationControlled"],+ });+}++async function gotoUploadPage(page) {+ await page.goto(config.uploadPageUrl, { waitUntil: "domcontentloaded" });+}++async function setVideoFile(page, videoPath) {+ const fileInput = page.locator('input[type="file"]').first();+ await fileInput.waitFor({ state: "attached", timeout: 120000 });+ await fileInput.setInputFiles(videoPath);+}++async function setCaption(page, caption) {+ if (!caption) {+ return;+ }++ const candidates = [+ 'div[contenteditable="true"]',+ 'textarea[placeholder*="caption" i]',+ 'textarea',+ ];++ for (const selector of candidates) {+ const target = page.locator(selector).first();+ const count = await target.count();+ if (count === 0) {+ continue;+ }++ try {+ await target.click({ timeout: 8000 });+ await page.keyboard.press("Control+A");+ await page.keyboard.press("Delete");+ await target.type(caption, { delay: 10 });+ return;+ } catch {+ // Try the next candidate selector.+ }+ }++ throw new Error("Could not find caption input field.");+}++function escapeRegExp(value) {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++async function clickFirstVisibleEnabledLocator(page, locator) {+ const total = await locator.count();+ if (total === 0) {+ return false;+ }++ for (let i = 0; i < total; i += 1) {+ const candidate = locator.nth(i);+ const visible = await candidate.isVisible().catch(() => false);+ if (!visible) {+ continue;+ }++ const disabled = await candidate.isDisabled().catch(() => false);+ if (disabled) {+ continue;+ }++ try {+ await candidate.scrollIntoViewIfNeeded({ timeout: 3000 });+ await page.waitForTimeout(250);+ await candidate.click({ timeout: 5000 });+ return true;+ } catch {+ try {+ await candidate.click({ timeout: 5000, force: true });+ return true;+ } catch {+ // Continue to next candidate.+ }+ }+ }++ return false;+}++function normalizeUiText(value) {+ return String(value || "").trim().replace(/\s+/g, " ").toLowerCase();+}++function isLikelyPublishCandidateInfo(info, publishTerms = uiLabels.terms("tiktokPublish")) {+ const text = normalizeUiText(info?.text || info?.ariaLabel);+ if (!text || info?.disabled || info?.inNavigation) {+ return false;+ }++ const tagName = normalizeUiText(info?.tagName);+ const role = normalizeUiText(info?.role);+ if (!["button", "a"].includes(tagName) && role !== "button") {+ return false;+ }++ const href = normalizeUiText(info?.href);+ if (href && /\/(post|posts|analytics|comment|home|inspiration|monetization|academy|sound|feedback)(\/|$|\?)/i.test(href)) {+ return false;+ }++ if (text === "posts") {+ return false;+ }++ const labels = publishTerms.map(normalizeUiText).filter(Boolean);+ const exactMatch = labels.includes(text);+ const nonAmbiguousMatch = labels+ .filter((label) => label !== "post")+ .some((label) => text.includes(label));+ if (!exactMatch && !nonAmbiguousMatch) {+ return false;+ }++ const rect = info?.rect || {};+ const viewportWidth = Number(info?.viewportWidth) || 0;+ if (viewportWidth >= 900 && Number(rect.left) < Math.min(280, viewportWidth * 0.25)) {+ return false;+ }++ return true;+}++async function getPublishCandidateInfo(candidate) {+ return candidate.evaluate((el) => {+ const clickable = el.closest("button, [role='button'], a") || el;+ const rect = clickable.getBoundingClientRect();+ const className = (clickable.className || "").toString();+ const inNavigation = Boolean(+ clickable.closest(+ [+ "nav",+ "aside",+ "[role='navigation']",+ "[class*='sidebar' i]",+ "[class*='side-bar' i]",+ "[class*='sidenav' i]",+ "[class*='side-nav' i]",+ "[class*='menu' i]",+ ].join(", ")+ )+ );+ const anchor = clickable.closest("a");+ return {+ ariaLabel: clickable.getAttribute("aria-label") || "",+ className,+ disabled: Boolean(clickable.disabled) || clickable.getAttribute("aria-disabled") === "true",+ href: anchor ? anchor.getAttribute("href") || "" : "",+ inNavigation,+ rect: {+ left: rect.left,+ top: rect.top,+ width: rect.width,+ height: rect.height,+ },+ role: clickable.getAttribute("role") || "",+ tagName: clickable.tagName,+ text: clickable.textContent || "",+ viewportWidth: window.innerWidth,+ };+ });+}++async function clickFirstLikelyPublishLocator(page, locator) {+ const total = await locator.count();+ if (total === 0) {+ return false;+ }++ for (let i = 0; i < total; i += 1) {+ const candidate = locator.nth(i);+ const visible = await candidate.isVisible().catch(() => false);+ if (!visible) {+ continue;+ }++ const info = await getPublishCandidateInfo(candidate).catch(() => null);+ if (!isLikelyPublishCandidateInfo(info)) {+ continue;+ }++ try {+ await candidate.scrollIntoViewIfNeeded({ timeout: 3000 });+ await page.waitForTimeout(250);+ await candidate.click({ timeout: 5000 });+ return true;+ } catch {+ try {+ await candidate.click({ timeout: 5000, force: true });+ return true;+ } catch {+ // Continue to next candidate.+ }+ }+ }++ return false;+}++async function addDefaultSound(page, source) {+ if (source === "instant-post") {+ console.log("Skipping auto-add sound: Post triggered via Instant Post (video already has sound).");+ return;+ }++ if (!config.autoAddSound) {+ console.log("Auto-add sound disabled by config.");+ return;+ }++ const query = (config.defaultSoundQuery || "").trim();+ if (!query) {+ console.log("Auto-add sound enabled, but DEFAULT_SOUND_QUERY is empty; skipping sound change.");+ return;+ }++ console.log(`Adding sound flow started${query ? `: ${query}` : ""}`);++ async function clickUploadEditorSoundsButton() {+ // Strict targeting for the editor action row under the preview.+ const rowPattern = uiLabels.pattern("tiktokEdit");+ const soundsPattern = uiLabels.pattern("tiktokSounds");+ const textPattern = uiLabels.pattern("tiktokText");++ const rowCandidates = page+ .locator("div, section")+ .filter({ hasText: rowPattern })+ .filter({ hasText: soundsPattern })+ .filter({ hasText: textPattern });++ const rowCount = await rowCandidates.count();+ for (let i = 0; i < rowCount; i += 1) {+ const row = rowCandidates.nth(i);+ const rowVisible = await row.isVisible().catch(() => false);+ if (!rowVisible) {+ continue;+ }++ const box = await row.boundingBox().catch(() => null);+ if (!box) {+ continue;+ }++ // Keep only right-side rows near the phone preview area.+ if (box.x < 520) {+ continue;+ }++ const exactSounds = row.locator(+ uiLabels.textSelector("button", "tiktokSounds") ++ ", " ++ uiLabels.textSelector('[role="button"]', "tiktokSounds")+ );+ const clickedExact = await clickFirstVisibleEnabledLocator(page, exactSounds);+ if (clickedExact) {+ console.log("Sound panel open strategy: strict editor row");+ return true;+ }++ const looseSounds = row.locator("button, [role='button'], div").filter({+ hasText: soundsPattern,+ });+ const clickedLoose = await clickFirstVisibleEnabledLocator(page, looseSounds);+ if (clickedLoose) {+ console.log("Sound panel open strategy: editor row fallback");+ return true;+ }+ }++ // Last resort: right-side clickable element named Sounds/Audio, never nav/aside.+ const soundLabels = uiLabels.terms("tiktokSounds").map((term) => term.toLowerCase());+ const clicked = await page.evaluate((labels) => {+ const isVisible = (el) => {+ const rect = el.getBoundingClientRect();+ return rect.width > 0 && rect.height > 0;+ };++ const nodes = Array.from(document.querySelectorAll("button, [role='button']"));+ for (const el of nodes) {+ const text = (el.textContent || "").trim().toLowerCase();+ if (!labels.includes(text)) {+ continue;+ }+ if (el.closest("nav, aside, [role='navigation']")) {+ continue;+ }+ if (!isVisible(el)) {+ continue;+ }++ const rect = el.getBoundingClientRect();+ // Stronger right-side lock so it cannot hit left menu.+ if (rect.left < window.innerWidth * 0.65) {+ continue;+ }++ el.scrollIntoView({ block: "center", inline: "center" });+ el.click();+ return true;+ }++ return false;+ }, soundLabels);++ if (clicked) {+ console.log("Sound panel open strategy: right-side hard fallback");+ return true;+ }++ return false;+ }++ const previousUrl = page.url();+ const opened = await clickUploadEditorSoundsButton();++ if (!opened) {+ console.log("Could not open sound panel; continuing without sound change.");+ return;+ }++ await page.waitForTimeout(700);+ // Guard: if wrong control caused navigation, jump back to upload page and skip sound.+ if (!page.url().includes("/upload")) {+ console.log(`Sounds click navigated away (${page.url()}); returning to upload page.`);+ await gotoUploadPage(page);+ await page.waitForTimeout(1000);+ return;+ }++ if (page.url() !== previousUrl) {+ console.log(`Upload page URL changed after sounds click: ${page.url()}`);+ }++ await page.waitForTimeout(1000);++ let added = false;++ // The "Use this sound" button in the sound panel is the ArrowLeftRight icon button.+ // The PlusBold icon button is typically disabled. We target both but prefer ArrowLeftRight.+ const useButtonSelector = [+ 'button:has([data-testid="ArrowLeftRight"])',+ 'button:has([data-icon="ArrowLeftRight"])',+ ].join(", ");++ // Step 1: try direct row match first (avoids flaky input focus/autocomplete issues).+ const queryPattern = new RegExp(escapeRegExp(query), "i");+ const directRow = page+ .locator('[role="listitem"], .MusicPanelMusicItem__wrap')+ .filter({ hasText: queryPattern });+ const directUse = directRow.locator(useButtonSelector);+ added = await clickFirstVisibleEnabledLocator(page, directUse);+ if (added) {+ console.log(`Sound used directly from visible "${query}" row (ArrowLeftRight).`);+ await page.waitForTimeout(1500);+ }++ // Step 2: fallback to search when direct row is unavailable.+ if (!added) {+ const soundSearchInput = page.getByPlaceholder(uiLabels.pattern("tiktokSearchSounds")).first();+ const inputVisible = await soundSearchInput.isVisible().catch(() => false);++ if (!inputVisible) {+ console.log("Sound search input not visible; skipping search.");+ } else {+ const queryPrefix = query.split(/\s+/).slice(0, 2).join(" ");+ const searchQueries = Array.from(new Set([query, queryPrefix].filter(Boolean)));++ for (const currentQuery of searchQueries) {+ await soundSearchInput.click({ timeout: 3000 });+ await page.waitForTimeout(300);++ await soundSearchInput.evaluate((el) => {+ el.focus();+ el.value = "";+ el.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await page.waitForTimeout(200);++ await page.keyboard.type(currentQuery, { delay: 30 });+ await page.waitForTimeout(300);+ await page.keyboard.press("Enter");+ await page.waitForTimeout(2000);++ const typedValue = await soundSearchInput.inputValue().catch(() => "");+ console.log(`Sound search typed: "${typedValue}" (wanted: "${currentQuery}")`);++ const rows = page+ .locator('[role="listitem"], .MusicPanelMusicItem__wrap')+ .filter({ hasText: new RegExp(escapeRegExp(currentQuery), "i") });+ const rowCount = await rows.count();+ if (rowCount === 0) {+ console.log(`No rows found for "${currentQuery}".`);+ continue;+ }++ const maxRowsToTry = Math.min(rowCount, 5);+ for (let i = 0; i < maxRowsToTry; i += 1) {+ const row = rows.nth(i);+ const rowVisible = await row.isVisible().catch(() => false);+ if (!rowVisible) continue;++ const addStrategies = [+ row.locator(useButtonSelector),+ row.locator(".MusicPanelMusicItem__operation button").first(),+ ];++ for (const locator of addStrategies) {+ added = await clickFirstVisibleEnabledLocator(page, locator);+ if (added) {+ console.log(`Sound "${currentQuery}" applied via use-button.`);+ await page.waitForTimeout(1500);+ break;+ }+ }+ if (added) break;+ }+ if (added) break;+ }+ }+ }++ // Step 3: hard fallback - click first enabled use-button in the panel.+ if (!added) {+ const firstUse = page.locator(+ `.MusicPanelMusicItem__operation ${useButtonSelector}`+ );+ added = await clickFirstVisibleEnabledLocator(page, firstUse);+ if (added) {+ console.log("Sound applied via first visible ArrowLeftRight fallback.");+ await page.waitForTimeout(1500);+ }+ }++ if (!added) {+ throw new Error(`Could not click use-button for sound "${query}".`);+ }++ // Step 4: Click "Save" to confirm the sound selection.+ // The sound panel is an overlay; the Publish button may be visible behind it,+ // so we must NOT rely on publishVisible to decide if we are done.+ let saved = false;+ const saveLocator = page.locator("button.Button__root--type-primary, button").filter({+ hasText: uiLabels.pattern("tiktokSave"),+ });++ // Retry a few times with waits; the button may need a moment after the sound loads.+ for (let attempt = 0; attempt < 5; attempt++) {+ saved = await clickFirstVisibleEnabledLocator(page, saveLocator);+ if (saved) {+ console.log(`Sound saved via Save (attempt ${attempt + 1}).`);+ break;+ }+ console.log(`Save not ready yet, waiting... (attempt ${attempt + 1}/5)`);+ await page.waitForTimeout(1500);+ }++ if (!saved) {+ // Last resort: try clicking via page.evaluate to force-find and click the button.+ const saveTerms = uiLabels.terms("tiktokSave").map((term) => term.toLowerCase());+ saved = await page.evaluate((labels) => {+ const buttons = Array.from(document.querySelectorAll("button"));+ const saveBtn = buttons.find(+ (b) =>+ labels.includes((b.textContent || "").trim().toLowerCase())+ );+ if (saveBtn && !saveBtn.disabled) {+ saveBtn.scrollIntoView();+ saveBtn.click();+ return true;+ }+ return false;+ }, saveTerms);+ if (saved) {+ console.log("Sound saved via evaluate fallback.");+ }+ }++ if (!saved) {+ // Check if the panel actually closed on its own.+ const soundSearchStillVisible = await page+ .getByPlaceholder(uiLabels.pattern("tiktokSearchSounds"))+ .first()+ .isVisible()+ .catch(() => false);+ const cancelVisible = await page+ .locator("button")+ .filter({ hasText: uiLabels.pattern("tiktokCancel") })+ .first()+ .isVisible()+ .catch(() => false);++ if (!soundSearchStillVisible && !cancelVisible) {+ console.log("Sound panel closed on its own after applying sound.");+ await page.waitForTimeout(800);+ return;+ }++ console.log(+ "WARNING: Could not click Save. Trying Cancel to avoid stuck panel."+ );+ await clickFirstVisibleEnabledLocator(+ page,+ page.locator("button").filter({ hasText: uiLabels.pattern("tiktokCancel") })+ );+ throw new Error("Could not click Save in sound editor.");+ }++ await page.waitForTimeout(1500);+}++async function disableShortContentCheck(page) {+ const labelPattern =+ uiLabels.pattern("tiktokShortContentCheck");+ const section = page+ .locator("section, div, li, form")+ .filter({ hasText: labelPattern })+ .first();++ if ((await section.count()) === 0) {+ console.log("Short content check toggle not found; continuing.");+ return;+ }++ async function readSwitchState(candidate) {+ return candidate.evaluate((el) => {+ const ariaChecked = (el.getAttribute("aria-checked") || "").toLowerCase();+ if (ariaChecked === "true") {+ return true;+ }+ if (ariaChecked === "false") {+ return false;+ }++ if (el instanceof HTMLInputElement && el.type === "checkbox") {+ return el.checked;+ }++ const className = (el.className || "").toString().toLowerCase();+ if (+ className.includes("checked") ||+ className.includes("active") ||+ className.includes("enabled") ||+ className.includes("on")+ ) {+ return true;+ }+ if (+ className.includes("disabled") ||+ className.includes("inactive") ||+ className.includes("off")+ ) {+ return false;+ }++ return null;+ });+ }++ const switchCandidates = [+ section.locator('[role="switch"]'),+ section.locator('button[aria-checked], button[class*="switch" i], button[class*="toggle" i]'),+ section.locator('input[type="checkbox"]'),+ ];++ for (const pool of switchCandidates) {+ const count = await pool.count();+ for (let i = 0; i < count; i += 1) {+ const candidate = pool.nth(i);+ const visible = await candidate.isVisible().catch(() => false);+ if (!visible) {+ continue;+ }++ await candidate.scrollIntoViewIfNeeded({ timeout: 3000 }).catch(() => { });+ const before = await readSwitchState(candidate).catch(() => null);+ if (before === false) {+ console.log("Short content check already disabled.");+ return;+ }++ await candidate.click({ timeout: 3000, force: true }).catch(() => { });+ await page.waitForTimeout(800);+ const after = await readSwitchState(candidate).catch(() => null);++ if (after === false || (before === true && after !== true)) {+ console.log("Short content check disabled.");+ return;+ }+ }+ }++ console.log("Short content check toggle found but could not be switched off.");+}++async function clickFirstVisibleButton(page, nameRegex, timeout = 3000) {+ const button = page.getByRole("button", { name: nameRegex }).first();+ if ((await button.count()) === 0) {+ return false;+ }+ try {+ await button.click({ timeout });+ return true;+ } catch {+ return false;+ }+}++async function dismissInterferingOverlays(page) {+ // TikTok Studio sometimes opens "content checks" and other hints dialogs+ // that block the publish button; dismiss/accept them before publishing.+ const overlayActions = [+ uiLabels.pattern("tiktokEnable"),+ uiLabels.pattern("tiktokContinue"),+ uiLabels.pattern("tiktokLater"),+ uiLabels.pattern("tiktokClose"),+ ];++ for (let pass = 0; pass < 3; pass += 1) {+ let clickedSomething = false;+ for (const action of overlayActions) {+ const clicked = await clickFirstVisibleButton(page, action, 1200);+ if (clicked) {+ clickedSomething = true;+ await page.waitForTimeout(400);+ }+ }++ const closeIcon = page+ .locator(uiLabels.attrSelector("button", "aria-label", "tiktokClose"))+ .first();+ if ((await closeIcon.count()) > 0) {+ await closeIcon.click({ timeout: 1200 }).catch(() => { });+ clickedSomething = true;+ await page.waitForTimeout(300);+ }++ if (!clickedSomething) {+ break;+ }+ }+}++async function scrollToBottom(page) {+ await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));+ await page.waitForTimeout(600);+}++async function tryClickPublishButton(page) {+ // Strategy 1: exact text buttons (most reliable on TikTok Studio)+ const exactSelectors = [+ uiLabels.textSelector("button", "tiktokPublish"),+ uiLabels.textSelector('[role="button"]', "tiktokPublish"),+ ];++ for (const selector of exactSelectors) {+ const locator = page.locator(selector);+ const clicked = await clickFirstLikelyPublishLocator(page, locator);+ if (clicked) {+ console.log(`Publish click strategy: exact selector ${selector}`);+ return true;+ }+ }++ // Strategy 2: role-based labels.+ const roleTexts = [+ uiLabels.pattern("tiktokPublish"),+ ];++ for (const textPattern of roleTexts) {+ const button = page.getByRole("button", { name: textPattern });+ const clicked = await clickFirstLikelyPublishLocator(page, button);+ if (clicked) {+ console.log(`Publish click strategy: role ${textPattern}`);+ return true;+ }+ }++ // Strategy 3: CSS selectors for the red publish button+ const cssSelectors = [+ 'button[class*="publish" i]',+ 'button[class*="post-btn" i]',+ 'button[class*="submit" i]',+ 'div[class*="publish" i] button',+ 'div[class*="btn-post" i]',+ ];++ for (const selector of cssSelectors) {+ const el = page.locator(selector);+ const clicked = await clickFirstLikelyPublishLocator(page, el);+ if (clicked) {+ console.log(`Publish click strategy: css ${selector}`);+ return true;+ }+ }++ // Strategy 4: find by visible text content (any clickable element)+ const textLabels = uiLabels.terms("tiktokPublish");++ for (const label of textLabels) {+ const el = page.locator(`text="${label}"`);+ const clicked = await clickFirstLikelyPublishLocator(page, el);+ if (clicked) {+ console.log(`Publish click strategy: text ${label}`);+ return true;+ }+ }++ // Strategy 5: brute-force - find any likely submit element by text.+ const publishTerms = uiLabels.terms("tiktokPublish").map((term) => term.toLowerCase());+ const clicked = await page.evaluate((labels) => {+ const normalize = (value) => String(value || "").trim().replace(/\s+/g, " ").toLowerCase();+ const normalizedLabels = labels.map(normalize).filter(Boolean);+ const isPublishText = (text) => {+ const exactMatch = normalizedLabels.includes(text);+ const nonAmbiguousMatch = normalizedLabels+ .filter((label) => label !== "post")+ .some((label) => text.includes(label));+ return exactMatch || nonAmbiguousMatch;+ };+ const isLikelyCandidate = (btn) => {+ const text = normalize(btn.textContent || btn.getAttribute("aria-label"));+ if (!text || text === "posts" || !isPublishText(text)) {+ return false;+ }+ if (btn.disabled || btn.getAttribute("aria-disabled") === "true") {+ return false;+ }+ if (+ btn.closest(+ "nav, aside, [role='navigation'], [class*='sidebar' i], [class*='side-bar' i], [class*='sidenav' i], [class*='side-nav' i], [class*='menu' i]"+ )+ ) {+ return false;+ }+ const anchor = btn.closest("a");+ const href = normalize(anchor ? anchor.getAttribute("href") : "");+ if (href && /\/(post|posts|analytics|comment|home|inspiration|monetization|academy|sound|feedback)(\/|$|\?)/i.test(href)) {+ return false;+ }+ const rect = btn.getBoundingClientRect();+ if (window.innerWidth >= 900 && rect.left < Math.min(280, window.innerWidth * 0.25)) {+ return false;+ }+ return true;+ };++ const buttons = Array.from(document.querySelectorAll("button, [role='button']"));+ for (const btn of buttons) {+ if (isLikelyCandidate(btn)) {+ btn.scrollIntoView({ block: "center" });+ btn.click();+ return true;+ }+ }+ return false;+ }, publishTerms);+ if (clicked) {+ console.log("Publish click strategy: DOM evaluate fallback");+ }++ return clicked;+}++async function clickPublish(page) {+ await dismissInterferingOverlays(page);++ for (let attempt = 0; attempt < 6; attempt += 1) {+ await scrollToBottom(page);+ await page.waitForTimeout(500);++ const clicked = await tryClickPublishButton(page);+ if (clicked) {+ console.log(`Publish button clicked on attempt ${attempt + 1}.`);+ return;+ }++ await dismissInterferingOverlays(page);+ await page.waitForTimeout(2000);+ }++ throw new Error("Could not find an enabled Publish/Post button after 6 attempts.");+}++function hasSuccessCueText(text) {+ const successPatterns = [+ uiLabels.pattern("tiktokPublished"),+ ];++ return successPatterns.some((pattern) => pattern.test(text));+}++function hasFailureCueText(text) {+ const failurePatterns = [+ uiLabels.pattern("tiktokFailed"),+ ];++ return failurePatterns.some((pattern) => pattern.test(text));+}++function isLikelyPublishApiResponse(response) {+ const url = response.url().toLowerCase();+ const method = response.request().method().toUpperCase();++ if (!["POST", "PUT", "PATCH"].includes(method)) {+ return false;+ }++ const urlPatterns = [+ "/publish",+ "/post",+ "/aweme",+ "/upload",+ "/creator",+ "/studio",+ "/web/project",+ "/web/post",+ ];++ return urlPatterns.some((pattern) => url.includes(pattern));+}++async function trySecondaryPublishConfirm(page) {+ const confirmButtons = [+ uiLabels.pattern("tiktokConfirm"),+ ];++ for (const nameRegex of confirmButtons) {+ const clicked = await clickFirstVisibleButton(page, nameRegex, 800);+ if (clicked) {+ await page.waitForTimeout(500);+ return true;+ }+ }++ return false;+}++async function waitForPublishConfirmation(page) {+ const startedUrl = page.url();+ let publishApiSuccess = false;+ let publishApiFailure = null;++ const responseHandler = (response) => {+ if (!isLikelyPublishApiResponse(response)) {+ return;+ }++ const status = response.status();+ const url = response.url();++ if (status >= 200 && status < 300) {+ publishApiSuccess = true;+ console.log(`Publish API success: ${status} ${url}`);+ return;+ }++ if (status >= 400) {+ publishApiFailure = `Publish API returned ${status}: ${url}`;+ console.log(publishApiFailure);+ }+ };++ page.on("response", responseHandler);++ try {+ for (let attempt = 0; attempt < 30; attempt += 1) {+ await dismissInterferingOverlays(page);++ const bodyText = await page+ .locator("body")+ .innerText()+ .then((value) => value || "")+ .catch(() => "");+ if (hasFailureCueText(bodyText)) {+ return {+ ok: false,+ reason: "TikTok displayed an error after publish click.",+ };+ }++ if (publishApiFailure) {+ return {+ ok: false,+ reason: publishApiFailure,+ };+ }++ if (publishApiSuccess) {+ return {+ ok: true,+ reason: "Publish API call succeeded.",+ };+ }++ if (hasSuccessCueText(bodyText)) {+ return {+ ok: true,+ reason: "Success confirmation text found.",+ };+ }++ await trySecondaryPublishConfirm(page);++ const urlChanged = page.url() !== startedUrl;+ if (urlChanged && !page.url().includes("/upload")) {+ return {+ ok: true,+ reason: `Navigation changed to ${page.url()}.`,+ };+ }++ await page.waitForTimeout(2000);+ }++ return {+ ok: false,+ reason: "No reliable publish confirmation observed within timeout.",+ };+ } finally {+ page.off("response", responseHandler);+ }+}++async function waitForUploadReady(page) {+ await page.waitForTimeout(Math.max(config.postDelayMs, 5000));+}++async function holdBrowserBeforeClose(page, holdMs, reason) {+ if (!Number.isFinite(holdMs) || holdMs <= 0) {+ return;+ }++ console.log(`Holding browser for ${holdMs}ms (${reason}).`);+ await page.waitForTimeout(holdMs).catch(() => { });+}++async function startLoginSession() {+ const activeAccount = await getActiveAccount();+ if (loginSessionContext && loginSessionAccountId !== activeAccount.id) {+ const previous = loginSessionContext;+ loginSessionContext = null;+ loginSessionAccountId = null;+ await previous.close().catch(() => { });+ }++ if (loginSessionContext) {+ return { ok: true, alreadyOpen: true };+ }++ const context = await openPersistentContext(activeAccount.id);+ const page = context.pages()[0] || (await context.newPage());+ loginSessionContext = context;+ loginSessionAccountId = activeAccount.id;+ context.on("close", () => {+ if (loginSessionContext === context) {+ loginSessionContext = null;+ loginSessionAccountId = null;+ }+ });+ await gotoUploadPage(page);++ return { ok: true, alreadyOpen: false, url: page.url() };+}++async function getLoginSessionStatus() {+ const activeAccount = await getActiveAccount();+ const saved = await hasSavedPlatformSession("tiktok", activeAccount.id);+ return {+ open: Boolean(loginSessionContext) && loginSessionAccountId === activeAccount.id,+ saved,+ };+}++async function closeLoginSession() {+ if (!loginSessionContext) {+ return { ok: true, alreadyClosed: true };+ }+ const context = loginSessionContext;+ loginSessionContext = null;+ loginSessionAccountId = null;+ await context.close().catch(() => { });+ return { ok: true, alreadyClosed: false };+}++async function startLoginSessionCli() {+ const result = await startLoginSession();++ console.log("");+ console.log("Log in to TikTok in the opened browser window.");+ console.log("After login is complete, press Ctrl+C in this terminal.");+ console.log("Your session will be reused for future automated posts.");+ console.log("");++ if (result.alreadyOpen) {+ return;+ }++ await new Promise(() => {+ // Keep process alive until manual interruption.+ });+}++async function uploadVideo({ videoPath, caption, source, accountId }) {+ const absoluteVideoPath = path.resolve(videoPath);+ const context = await openPersistentContext(accountId);+ const page = context.pages()[0] || (await context.newPage());+ let closeHoldMs = 0;++ try {+ await gotoUploadPage(page);+ await setVideoFile(page, absoluteVideoPath);+ await waitForUploadReady(page);+ await setCaption(page, caption || config.defaultCaption);+ await addDefaultSound(page, source).catch((error) => {+ console.log(`Sound step failed softly: ${error.message}`);+ });+ await disableShortContentCheck(page);+ await clickPublish(page);+ const confirmation = await waitForPublishConfirmation(page);+ if (!confirmation.ok) {+ throw new Error(`Publish verification failed: ${confirmation.reason}`);+ }++ const successScreenshotPath = path.resolve(+ config.projectRoot,+ "last-upload-success.png"+ );+ await page+ .screenshot({ path: successScreenshotPath, fullPage: true })+ .catch(() => { });++ closeHoldMs = Math.max(config.postPublishHoldMs, 0);+ return { ok: true };+ } catch (error) {+ const screenshotPath = path.resolve(+ config.projectRoot,+ "last-upload-error.png"+ );+ await page.screenshot({ path: screenshotPath, fullPage: true }).catch(() => { });+ closeHoldMs = Math.max(config.failureHoldMs, 0);+ return {+ ok: false,+ error: error.message,+ screenshotPath,+ };+ } finally {+ await holdBrowserBeforeClose(page, closeHoldMs, "post-finalization");+ await context.close();+ }+}++module.exports = {+ startLoginSession: startLoginSessionCli,+ startDashboardLoginSession: startLoginSession,+ getLoginSessionStatus,+ closeLoginSession,+ uploadVideo,+ _private: {+ isLikelyPublishCandidateInfo,+ },+};diff --git a/src/uniquifier-controller.js b/src/uniquifier-controller.jsnew file mode 100644index 0000000..84f6c5e--- /dev/null+++ b/src/uniquifier-controller.js@@ -0,0 +1,295 @@+const fs = require("fs/promises");+const path = require("path");+const { config } = require("./config");+const { ensureDirectories } = require("./fs-utils");+const { uniquifyVideo, checkFfmpeg } = require("./video-uniquifier");++const VIDEO_EXTENSIONS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);++function nowIso() {+ return new Date().toISOString();+}++class UniquifierController {+ constructor() {+ this.inputDir = config.uniquifyInputDir;+ this.outputDir = config.uniquifyOutputDir;+ this.logoImage = config.uniquifyLogoImage || "";+ this.running = false;+ this.stopRequested = false;+ this.startedAt = null;+ this.finishedAt = null;+ this.currentFile = null;+ this.processed = 0;+ this.total = 0;+ this.succeeded = 0;+ this.failed = 0;+ this.logs = [];+ }++ log(message, level = "info") {+ this.logs.unshift({+ at: nowIso(),+ level,+ message,+ });+ this.logs = this.logs.slice(0, 200);+ const prefix = `[${this.logs[0].at}] [uniquifier]`;+ if (level === "error") {+ console.error(`${prefix} ${message}`);+ } else {+ console.log(`${prefix} ${message}`);+ }+ }++ resolveFolder(folderPath, fallbackPath) {+ if (!folderPath || typeof folderPath !== "string") {+ return fallbackPath;+ }+ const trimmed = folderPath.trim();+ if (!trimmed) return fallbackPath;+ return path.isAbsolute(trimmed)+ ? path.normalize(trimmed)+ : path.resolve(config.projectRoot, trimmed);+ }++ resolveOptionalFile(filePath, fallbackPath) {+ if (filePath === undefined) {+ return fallbackPath;+ }+ if (filePath === null) {+ return "";+ }+ const trimmed = String(filePath).trim();+ if (!trimmed) {+ return "";+ }+ return path.isAbsolute(trimmed)+ ? path.normalize(trimmed)+ : path.resolve(config.projectRoot, trimmed);+ }++ async setFolders({ inputDir, outputDir, logoImage } = {}) {+ this.inputDir = this.resolveFolder(inputDir, this.inputDir);+ this.outputDir = this.resolveFolder(outputDir, this.outputDir);+ this.logoImage = this.resolveOptionalFile(logoImage, this.logoImage);+ await ensureDirectories([this.inputDir, this.outputDir]);++ if (this.logoImage) {+ await fs.access(this.logoImage);+ }++ return {+ ok: true,+ inputDir: this.inputDir,+ outputDir: this.outputDir,+ logoImage: this.logoImage,+ };+ }++ async listVideoFiles(dirPath) {+ const entries = await fs.readdir(dirPath, { withFileTypes: true });+ return entries+ .filter(+ (entry) =>+ entry.isFile() &&+ VIDEO_EXTENSIONS.has(path.extname(entry.name).toLowerCase())+ )+ .map((entry) => entry.name)+ .sort((a, b) => a.localeCompare(b));+ }++ buildOutputPath(inputFileName, index) {+ return path.join(this.outputDir, inputFileName);+ }++ getSidecarPaths(filePath) {+ const parsed = path.parse(filePath);+ return [+ path.join(parsed.dir, `${parsed.name}.description`),+ path.join(parsed.dir, `${parsed.name}.txt`),+ ];+ }++ async copySidecarsToOutput(inputPath, outputPath) {+ const outputParsed = path.parse(outputPath);+ const copied = [];++ for (const sourcePath of this.getSidecarPaths(inputPath)) {+ try {+ await fs.access(sourcePath);+ } catch {+ continue;+ }++ const sidecarExt = path.extname(sourcePath);+ const destinationPath = path.join(+ outputParsed.dir,+ `${outputParsed.name}${sidecarExt}`+ );++ await fs.copyFile(sourcePath, destinationPath);+ copied.push(path.basename(destinationPath));+ }++ return copied;+ }++ async start({ inputDir, outputDir, logoImage } = {}) {+ if (this.running) {+ return { ok: true, alreadyRunning: true };+ }++ await this.setFolders({ inputDir, outputDir, logoImage });++ const hasFfmpeg = await checkFfmpeg();+ if (!hasFfmpeg) {+ throw new Error("ffmpeg is not installed or not in PATH.");+ }++ const files = await this.listVideoFiles(this.inputDir);+ this.running = true;+ this.stopRequested = false;+ this.startedAt = nowIso();+ this.finishedAt = null;+ this.currentFile = null;+ this.processed = 0;+ this.total = files.length;+ this.succeeded = 0;+ this.failed = 0;++ this.log(+ `Batch started. Input: ${this.inputDir}, Output: ${this.outputDir}, Files: ${files.length}`+ );+ this.log(+ this.logoImage+ ? `Logo overlay: ${this.logoImage}`+ : "Logo overlay disabled."+ );++ this.runBatch(files).catch((error) => {+ this.log(`Unexpected batch error: ${error.message}`, "error");+ this.running = false;+ this.currentFile = null;+ this.finishedAt = nowIso();+ });++ return {+ ok: true,+ alreadyRunning: false,+ total: files.length,+ };+ }++ async runBatch(files) {+ if (files.length === 0) {+ this.log("No video files found in input folder.");+ this.running = false;+ this.finishedAt = nowIso();+ return;+ }++ for (let i = 0; i < files.length; i += 1) {+ if (this.stopRequested) {+ this.log("Stop requested. Batch halted.");+ break;+ }++ const fileName = files[i];+ const inputPath = path.join(this.inputDir, fileName);+ const outputPath = this.buildOutputPath(fileName, i);+ this.currentFile = fileName;+ this.log(`Processing ${i + 1}/${files.length}: ${fileName}`);++ try {+ await uniquifyVideo(inputPath, outputPath, {+ overlayImage: this.logoImage || null,+ removeAudio: false,+ });++ const copiedSidecars = await this.copySidecarsToOutput(inputPath, outputPath);+ if (copiedSidecars.length > 0) {+ this.log(`Copied sidecar files: ${copiedSidecars.join(", ")}`);+ }++ this.succeeded += 1;+ this.log(`Done: ${path.basename(outputPath)}`);+ } catch (error) {+ this.failed += 1;+ this.log(`Failed: ${fileName} - ${error.message}`, "error");+ } finally {+ this.processed += 1;+ }+ }++ this.running = false;+ this.currentFile = null;+ this.finishedAt = nowIso();+ this.log(+ `Batch finished. Success: ${this.succeeded}, Failed: ${this.failed}, Processed: ${this.processed}/${this.total}`+ );+ }++ stop() {+ if (!this.running) {+ return { ok: true, alreadyStopped: true };+ }+ this.stopRequested = true;+ this.log("Stop requested by dashboard.");+ return { ok: true, alreadyStopped: false };+ }++ async getStatus() {+ await ensureDirectories([this.inputDir, this.outputDir]);+ const [inputEntries, outputEntries] = await Promise.all([+ fs.readdir(this.inputDir, { withFileTypes: true }),+ fs.readdir(this.outputDir, { withFileTypes: true }),+ ]);++ const inputFiles = inputEntries+ .filter(+ (entry) =>+ entry.isFile() &&+ VIDEO_EXTENSIONS.has(path.extname(entry.name).toLowerCase())+ )+ .map((entry) => entry.name)+ .sort((a, b) => a.localeCompare(b));++ const outputFiles = outputEntries+ .filter(+ (entry) =>+ entry.isFile() &&+ VIDEO_EXTENSIONS.has(path.extname(entry.name).toLowerCase())+ )+ .map((entry) => entry.name)+ .sort((a, b) => b.localeCompare(a));++ return {+ running: this.running,+ stopRequested: this.stopRequested,+ inputDir: this.inputDir,+ outputDir: this.outputDir,+ logoImage: this.logoImage,+ currentFile: this.currentFile,+ startedAt: this.startedAt,+ finishedAt: this.finishedAt,+ progress: {+ processed: this.processed,+ total: this.total,+ succeeded: this.succeeded,+ failed: this.failed,+ },+ counts: {+ input: inputFiles.length,+ output: outputFiles.length,+ },+ inputFiles: inputFiles.slice(0, 100),+ outputFiles: outputFiles.slice(0, 100),+ logs: this.logs,+ };+ }+}++module.exports = {+ UniquifierController,+};diff --git a/src/video-uniquifier.js b/src/video-uniquifier.jsnew file mode 100644index 0000000..201c644--- /dev/null+++ b/src/video-uniquifier.js@@ -0,0 +1,560 @@+const { execFile } = require("child_process");+const path = require("path");+const fs = require("fs/promises");+const crypto = require("crypto");+const os = require("os");++function randFloat(min, max) {+ return Math.random() * (max - min) + min;+}++function randInt(min, max) {+ return Math.floor(Math.random() * (max - min + 1)) + min;+}++function pick(arr) {+ return arr[Math.floor(Math.random() * arr.length)];+}++function runFfmpeg(args) {+ return new Promise((resolve, reject) => {+ execFile("ffmpeg", args, { maxBuffer: 50 * 1024 * 1024 }, (error, stdout, stderr) => {+ if (error) {+ reject(new Error(`ffmpeg failed: ${error.message}\n${stderr}`));+ return;+ }+ resolve({ stdout, stderr });+ });+ });+}++function runFfprobe(args) {+ return new Promise((resolve, reject) => {+ execFile("ffprobe", args, { maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {+ if (error) {+ reject(new Error(`ffprobe failed: ${error.message}\n${stderr}`));+ return;+ }+ resolve({ stdout, stderr });+ });+ });+}++async function getVideoInfo(inputPath) {+ const { stdout } = await runFfprobe([+ "-v", "quiet",+ "-print_format", "json",+ "-show_format",+ "-show_streams",+ inputPath,+ ]);+ return JSON.parse(stdout);+}++async function checkFfmpeg() {+ try {+ await runFfmpeg(["-version"]);+ return true;+ } catch {+ return false;+ }+}++function buildMetadataArgs() {+ const now = new Date();+ const fakeDate = new Date(+ now.getTime() + randInt(-365, 365) * 86400000 + randInt(-23, 23) * 3600000+ );++ const titles = [+ "",+ `clip_${crypto.randomBytes(8).toString("hex")}`,+ `VID_${randInt(20200101, 20261231)}_${randInt(100000, 999999)}`,+ `IMG_${randInt(1000, 9999)}`,+ ];++ const encoders = [+ `Lavf ${randInt(57, 61)}.${randInt(10, 99)}.${randInt(100, 999)}`,+ `HandBrake ${randInt(1, 2)}.${randInt(0, 8)}.${randInt(0, 4)}`,+ "",+ ];++ return [+ "-metadata", `title=${pick(titles)}`,+ "-metadata", `comment=${crypto.randomBytes(12).toString("hex")}`,+ "-metadata", `creation_time=${fakeDate.toISOString()}`,+ "-metadata", `encoder=${pick(encoders)}`,+ "-metadata", `description=`,+ "-metadata", `artist=`,+ ];+}++/**+ * Video filters: each one changes the pixel data in a different way.+ * Kept lean to avoid CPU overload.+ */+function buildVideoFilters(options = {}) {+ const filters = [];++ // Slow down slightly to extend duration by ~0.5-1.5s+ if (options.extendDuration !== false) {+ const slowdown = randFloat(0.97, 0.995).toFixed(4);+ filters.push(`setpts=PTS/${slowdown}`);+ }++ // Freeze-clone first/last frame for a short bit+ if (options.freezeFrames !== false) {+ const s = randFloat(0.05, 0.3).toFixed(2);+ const e = randFloat(0.05, 0.3).toFixed(2);+ filters.push(`tpad=start_duration=${s}:start_mode=clone:stop_duration=${e}:stop_mode=clone`);+ }++ // Brightness / contrast / saturation+ if (options.colorShift !== false) {+ filters.push(+ `eq=brightness=${randFloat(-0.03, 0.03).toFixed(3)}` ++ `:contrast=${randFloat(0.97, 1.03).toFixed(3)}` ++ `:saturation=${randFloat(0.95, 1.05).toFixed(3)}` ++ `:gamma=${randFloat(0.97, 1.03).toFixed(3)}`+ );+ }++ // Hue rotation+ if (options.hueShift !== false) {+ filters.push(`hue=h=${randFloat(-4, 4).toFixed(2)}:s=${randFloat(0.96, 1.04).toFixed(3)}`);+ }++ // Color channel bleed+ if (options.channelMix !== false) {+ const rr = randFloat(0.97, 1.0).toFixed(3);+ const rg = randFloat(0.0, 0.02).toFixed(3);+ const rb = randFloat(0.0, 0.02).toFixed(3);+ const gr = randFloat(0.0, 0.02).toFixed(3);+ const gg = randFloat(0.97, 1.0).toFixed(3);+ const gb = randFloat(0.0, 0.02).toFixed(3);+ const br = randFloat(0.0, 0.02).toFixed(3);+ const bg = randFloat(0.0, 0.02).toFixed(3);+ const bb = randFloat(0.97, 1.0).toFixed(3);+ filters.push(`colorchannelmixer=${rr}:${rg}:${rb}:0:${gr}:${gg}:${gb}:0:${br}:${bg}:${bb}:0`);+ }++ // Subtle noise+ if (options.noise !== false) {+ filters.push(`noise=alls=${randInt(1, 3)}:allf=t`);+ }++ // Micro crop + pad (shifts pixel grid)+ if (options.pixelShift !== false) {+ const px = randInt(1, 2);+ filters.push(`crop=iw-${px * 2}:ih-${px * 2}:${px}:${px}`);+ filters.push(`pad=iw+${px * 2}:ih+${px * 2}:${px}:${px}:black`);+ }++ // Color balance nudge+ if (options.colorOverlay !== false) {+ filters.push(+ `colorbalance=rs=${randFloat(-0.04, 0.04).toFixed(3)}` ++ `:gs=${randFloat(-0.04, 0.04).toFixed(3)}` ++ `:bs=${randFloat(-0.04, 0.04).toFixed(3)}`+ );+ }++ // Ensure even dimensions+ filters.push(`crop=trunc(iw/2)*2:trunc(ih/2)*2`);+ filters.push(`format=yuv420p`);++ return filters;+}++/**+ * Audio filters: change the audio fingerprint without sounding noticeably different.+ */+function buildAudioFilters(options = {}) {+ const filters = [];++ // Slow audio to match video extension+ if (options.extendDuration !== false) {+ const slowdown = randFloat(0.97, 0.995).toFixed(4);+ filters.push(`atempo=${slowdown}`);+ }++ // Pitch shift via asetrate -> aresample+ if (options.audioPitch !== false) {+ const dir = Math.random() > 0.5 ? 1 : -1;+ const pct = randFloat(1.5, 3.5);+ const rate = Math.round(44100 * (1 + (dir * pct / 100)));+ filters.push(`asetrate=${rate}`);+ filters.push(`aresample=44100`);+ }++ // 3-band EQ+ if (options.audioEq !== false) {+ filters.push(`bass=g=${randFloat(-2.5, 2.5).toFixed(1)}:f=80`);+ filters.push(`equalizer=f=1000:t=h:w=500:g=${randFloat(-2, 2).toFixed(1)}`);+ filters.push(`treble=g=${randFloat(-2.5, 2.5).toFixed(1)}:f=5000`);+ }++ // Subtle echo+ if (options.audioReverb !== false) {+ filters.push(`aecho=0.8:0.8:${randInt(10, 35)}:${randFloat(0.04, 0.12).toFixed(3)}`);+ }++ // Volume+ if (options.volumeShift !== false) {+ filters.push(`volume=${randFloat(0.95, 1.05).toFixed(3)}`);+ }++ // Highpass / lowpass+ if (options.audioFilter !== false) {+ filters.push(`highpass=f=${randInt(15, 40)}`);+ filters.push(`lowpass=f=${randInt(16000, 19000)}`);+ }++ return filters;+}++/**+ * Encoding: fast preset, reasonable CRF, hard bitrate cap.+ */+function buildEncodingArgs(options = {}) {+ const args = [];++ args.push("-c:v", "libx264");+ args.push("-crf", String(randInt(23, 27)));+ args.push("-preset", pick(["fast", "medium"]));+ args.push("-profile:v", pick(["high", "main"]));++ // Hard cap: max 2 Mbps so files stay small+ args.push("-maxrate", "2M");+ args.push("-bufsize", "4M");++ // Randomize some x264 internals for uniqueness+ const x264Params = [+ `ref=${randInt(2, 5)}`,+ `bframes=${randInt(2, 4)}`,+ `keyint=${randInt(120, 300)}`,+ `scenecut=${randInt(30, 45)}`,+ `aq-mode=${randInt(1, 3)}`,+ `aq-strength=${randFloat(0.8, 1.3).toFixed(2)}`,+ ];+ args.push("-x264-params", x264Params.join(":"));++ // Limit threads so it doesn't freeze the PC+ const maxThreads = Math.max(2, Math.floor(os.cpus().length / 2));+ args.push("-threads", String(maxThreads));++ // Audio (skip when no-audio output requested)+ if (!options.removeAudio) {+ args.push("-c:a", "aac");+ args.push("-b:a", `${pick([96, 128, 160])}k`);+ args.push("-ar", "44100");+ args.push("-ac", "2");+ }++ return args;+}++/**+ * Subtle static logo overlay filter.+ */+function buildOverlayFilter(options = {}) {+ const logoSize = options.overlaySize || randInt(60, 100);+ // Very low opacity; barely visible but enough to change the hash.+ const opacity = options.overlayOpacity || randFloat(0.08, 0.15).toFixed(2);+ const margin = randInt(12, 28);++ // Pick a random fixed corner: 0=top-right, 1=bottom-left, 2=bottom-right, 3=top-left+ const corner = randInt(0, 3);+ const xExpr = (corner === 0 || corner === 2)+ ? `main_w-overlay_w-${margin}`+ : `${margin}`;+ const yExpr = (corner === 1 || corner === 2)+ ? `main_h-overlay_h-${margin}`+ : `${margin}`;++ const logoChain = `[1:v]scale=${logoSize}:-1,format=rgba,colorchannelmixer=aa=${opacity}[logo]`;+ const overlayChain =+ `[processed][logo]overlay=${xExpr}:${yExpr}:eof_action=repeat[out]`;++ return { logoChain, overlayChain };+}++function getPrimaryVideoStream(videoInfo) {+ const streams = Array.isArray(videoInfo?.streams) ? videoInfo.streams : [];+ return streams.find((stream) => stream.codec_type === "video") || null;+}++function parsePositiveNumber(value, fallback) {+ const numeric = Number(value);+ if (!Number.isFinite(numeric) || numeric <= 0) {+ return fallback;+ }+ return numeric;+}++function buildRecipeFilterGraph({+ width,+ height,+ introSeconds,+ endHoldSeconds,+}) {+ const speedFactor = randFloat(0.985, 0.995).toFixed(4);+ const brightness = randFloat(0.004, 0.016).toFixed(3);+ const contrast = randFloat(1.01, 1.03).toFixed(3);+ const saturation = randFloat(1.015, 1.045).toFixed(3);+ const noiseStrength = randInt(1, 2);+ const watermarkOpacity = randFloat(0.2, 0.3).toFixed(2);+ const cornerSegment = randFloat(2.4, 3.4).toFixed(2);+ const margin = randInt(14, 24);+ const logoWidth = Math.max(180, Math.round(width * 0.24));+ const introLogoWidth = Math.max(260, Math.round(width * 0.42));+ const watermarkCycle = (Number(cornerSegment) * 4).toFixed(2);++ const xExpr =+ `'if(lt(mod(t\\,${watermarkCycle})\\,${cornerSegment})\\,main_w-overlay_w-${margin},` ++ `if(lt(mod(t\\,${watermarkCycle})\\,${(Number(cornerSegment) * 2).toFixed(2)})\\,${margin},` ++ `if(lt(mod(t\\,${watermarkCycle})\\,${(Number(cornerSegment) * 3).toFixed(2)})\\,main_w-overlay_w-${margin},` ++ `${margin})))'`;+ const yExpr =+ `'if(lt(mod(t\\,${watermarkCycle})\\,${cornerSegment})\\,${margin},` ++ `if(lt(mod(t\\,${watermarkCycle})\\,${(Number(cornerSegment) * 2).toFixed(2)})\\,main_h-overlay_h-${margin},` ++ `if(lt(mod(t\\,${watermarkCycle})\\,${(Number(cornerSegment) * 3).toFixed(2)})\\,main_h-overlay_h-${margin},` ++ `${margin})))'`;++ const filterGraph = [+ `[0:v]setpts=PTS/${speedFactor},` ++ `eq=brightness=${brightness}:contrast=${contrast}:saturation=${saturation},` ++ `noise=alls=${noiseStrength}:allf=t,` ++ `tpad=stop_duration=${endHoldSeconds.toFixed(2)}:stop_mode=clone,` ++ `format=yuv420p[main]`,+ `[1:v]scale=${logoWidth}:-1,format=rgba,colorchannelmixer=aa=${watermarkOpacity}[wm]`,+ `[main][wm]overlay=${xExpr}:${yExpr}:shortest=1[watermarked]`,+ `[1:v]scale=${introLogoWidth}:-1,format=rgba[intro_logo]`,+ `color=c=black:s=${width}x${height}:d=${introSeconds.toFixed(2)}[intro_bg]`,+ `[intro_bg][intro_logo]overlay=(W-w)/2:(H-h)/2:shortest=1[intro]`,+ `[intro][watermarked]concat=n=2:v=1:a=0[outv]`,+ ].join(";");++ return {+ filterGraph,+ modifications: [+ `logo-intro-${introSeconds.toFixed(2)}s`,+ `end-hold-${endHoldSeconds.toFixed(2)}s`,+ "visual-randomization-light",+ "watermark-corners-no-flicker",+ "audio-removed",+ "re-encode-h264-capped",+ ],+ };+}++/**+ * Main uniquification function.+ */+async function uniquifyVideo(inputPath, outputPath, options = {}) {+ const resolvedInput = path.resolve(inputPath);+ await fs.access(resolvedInput);++ const overlayImage = options.overlayImage || null;+ if (overlayImage) {+ await fs.access(path.resolve(overlayImage));+ }++ if (!outputPath) {+ const parsed = path.parse(resolvedInput);+ const hash = crypto.randomBytes(4).toString("hex");+ outputPath = path.join(parsed.dir, `${parsed.name}_unique_${hash}${parsed.ext}`);+ }+ const resolvedOutput = path.resolve(outputPath);+ const removeAudio = options.removeAudio === true;+ const useNewRecipe = options.mode === "logo-intro-watermark-noaudio";++ const modifications = [];+ const args = ["-y"];++ if (useNewRecipe) {+ if (!overlayImage) {+ throw new Error("Recipe mode requires overlayImage (logo file).");+ }++ const videoInfo = await getVideoInfo(resolvedInput);+ const primaryVideo = getPrimaryVideoStream(videoInfo);+ if (!primaryVideo) {+ throw new Error("Could not read primary video stream from input.");+ }++ const width = parsePositiveNumber(primaryVideo.width, 1080);+ const height = parsePositiveNumber(primaryVideo.height, 1920);+ const introSeconds = Math.min(+ parsePositiveNumber(options.introSeconds, 1),+ 1+ );+ const endHoldSeconds = parsePositiveNumber(options.endHoldSeconds, 0.4);++ args.push("-i", resolvedInput);+ args.push("-loop", "1", "-i", path.resolve(overlayImage));++ const recipe = buildRecipeFilterGraph({+ width,+ height,+ introSeconds,+ endHoldSeconds,+ });+ args.push("-filter_complex", recipe.filterGraph);+ args.push("-map", "[outv]");++ const encArgs = buildEncodingArgs({+ ...options,+ removeAudio: true,+ });+ args.push(...encArgs);+ args.push("-an");++ const metaArgs = buildMetadataArgs();+ args.push(...metaArgs);+ args.push("-map_metadata", "-1");+ args.push("-fflags", "+bitexact");+ args.push("-movflags", "+faststart");+ args.push(resolvedOutput);++ modifications.push(...recipe.modifications);+ } else {+ args.push("-i", resolvedInput);++ // Add overlay as second input (single frame, no -loop needed)+ if (overlayImage) {+ args.push("-i", path.resolve(overlayImage));+ }++ const vFilters = buildVideoFilters(options);+ const aFilters = removeAudio ? [] : buildAudioFilters(options);++ if (overlayImage && vFilters.length > 0) {+ const { logoChain, overlayChain } = buildOverlayFilter(options);+ const videoChain = `[0:v]${vFilters.join(",")}[processed]`;+ const audioChain = aFilters.length > 0 ? `[0:a]${aFilters.join(",")}[aout]` : null;++ const filterParts = [videoChain, logoChain, overlayChain];+ if (audioChain) filterParts.push(audioChain);++ args.push("-filter_complex", filterParts.join(";"));+ args.push("-map", "[out]");+ if (!removeAudio) {+ args.push("-map", audioChain ? "[aout]" : "0:a");+ }+ modifications.push("flickering-logo-overlay");+ } else {+ if (vFilters.length > 0) args.push("-vf", vFilters.join(","));+ if (!removeAudio && aFilters.length > 0) args.push("-af", aFilters.join(","));+ }++ modifications.push(+ "extend-duration",+ "freeze-frames",+ "color-shift",+ "hue-shift",+ "channel-mix",+ "noise",+ "pixel-shift",+ "color-balance"+ );+ if (!removeAudio) {+ modifications.push(+ "pitch-shift",+ "3-band-eq",+ "echo",+ "volume-shift",+ "freq-bounds"+ );+ } else {+ modifications.push("audio-removed");+ }++ const encArgs = buildEncodingArgs(options);+ args.push(...encArgs);+ modifications.push("re-encode");++ if (removeAudio) {+ args.push("-an");+ }++ const metaArgs = buildMetadataArgs();+ args.push(...metaArgs);+ args.push("-map_metadata", "-1");+ args.push("-fflags", "+bitexact");+ args.push("-movflags", "+faststart");+ modifications.push("metadata-randomize");++ args.push(resolvedOutput);+ }++ console.log(`Uniquifying video...`);+ console.log(` Input: ${resolvedInput}`);+ if (overlayImage) console.log(` Overlay: ${path.resolve(overlayImage)}`);+ console.log(` Output: ${resolvedOutput}`);++ await runFfmpeg(args);++ const stat = await fs.stat(resolvedOutput);+ console.log(` Output size: ${(stat.size / 1024 / 1024).toFixed(2)} MB`);+ console.log(` Done.`);++ return { outputPath: resolvedOutput, modifications };+}++async function uniquifyInPlace(inputPath, options = {}) {+ const resolvedInput = path.resolve(inputPath);+ const parsed = path.parse(resolvedInput);+ const tempPath = path.join(parsed.dir, `${parsed.name}_tmp_${crypto.randomBytes(4).toString("hex")}${parsed.ext}`);++ const result = await uniquifyVideo(resolvedInput, tempPath, options);++ await fs.unlink(resolvedInput);+ await fs.rename(tempPath, resolvedInput);++ console.log(` Replaced original file.`);+ return { outputPath: resolvedInput, modifications: result.modifications };+}++async function uniquifyDirectory(dirPath, options = {}) {+ const VIDEO_EXTENSIONS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);+ const resolvedDir = path.resolve(dirPath);+ const entries = await fs.readdir(resolvedDir, { withFileTypes: true });++ const videos = entries+ .filter((e) => e.isFile() && VIDEO_EXTENSIONS.has(path.extname(e.name).toLowerCase()))+ .map((e) => path.join(resolvedDir, e.name));++ if (videos.length === 0) {+ console.log("No video files found in directory.");+ return [];+ }++ console.log(`Found ${videos.length} video(s) to uniquify.\n`);+ const results = [];++ for (const videoPath of videos) {+ try {+ const result = options.inPlace+ ? await uniquifyInPlace(videoPath, options)+ : await uniquifyVideo(videoPath, null, options);+ results.push({ videoPath, ...result, ok: true });+ } catch (error) {+ console.error(` Failed: ${error.message}`);+ results.push({ videoPath, ok: false, error: error.message });+ }+ console.log("");+ }++ const succeeded = results.filter((r) => r.ok).length;+ console.log(`Uniquified ${succeeded}/${videos.length} video(s).`);+ return results;+}++module.exports = {+ uniquifyVideo,+ uniquifyInPlace,+ uniquifyDirectory,+ checkFfmpeg,+ getVideoInfo,+};diff --git a/src/youtube-daemon-controller.js b/src/youtube-daemon-controller.jsnew file mode 100644index 0000000..6dce2c7--- /dev/null+++ b/src/youtube-daemon-controller.js@@ -0,0 +1,352 @@+const fs = require("fs/promises");+const fsSync = require("fs");+const path = require("path");+const cron = require("node-cron");+const { config } = require("./config");+const { postNextFromQueue } = require("./youtube-post-service");++function nowIso() {+ return new Date().toISOString();+}++function normalizeDailyTimes(times) {+ const source = Array.isArray(times) ? times : [];+ const normalized = source+ .map((value) => String(value || "").trim())+ .filter(Boolean)+ .map((value) => {+ const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value);+ if (!match) {+ throw new Error(`Invalid time "${value}". Use HH:MM (24h).`);+ }+ return `${match[1].padStart(2, "0")}:${match[2]}`;+ });++ const uniqueSorted = Array.from(new Set(normalized)).sort((a, b) =>+ a.localeCompare(b)+ );+ if (!uniqueSorted.length) {+ throw new Error("Please provide at least one valid time.");+ }+ return uniqueSorted;+}++function getLocalTimeKey(date, timezone) {+ return new Intl.DateTimeFormat("en-GB", {+ hour: "2-digit",+ minute: "2-digit",+ hour12: false,+ timeZone: timezone,+ }).format(date);+}++class YouTubeDaemonController {+ constructor(options = {}) {+ this.accountId = options.accountId || "default";+ this.queueDir = options.queueDir || config.youtubeQueueDir;+ this.postedDir = options.postedDir || config.youtubePostedDir;+ this.failedDir = options.failedDir || config.youtubeFailedDir;++ this.task = null;+ this.isPosting = false;+ this.lastRunAt = null;+ this.lastResult = null;+ this.logs = [];+ this.cronExpression = config.youtubeCronExpression;+ this.schedulePlan = { type: "cron", expression: this.cronExpression };+ this.lastScheduleTriggerKey = null;+ this.instantPost = false;+ this._queueWatcher = null;+ this._watchDebounce = null;+ this._scheduledTimers = new Set();+ this.statePath = options.statePath || path.resolve(config.projectRoot, "youtube-scheduler-state.json");+ this._loadState();+ }++ _loadState() {+ try {+ const data = fsSync.readFileSync(this.statePath, "utf-8");+ const state = JSON.parse(data);+ if (state.schedulePlan && state.schedulePlan.type === "daily-times") {+ this.schedulePlan = {+ type: "daily-times",+ times: normalizeDailyTimes(state.schedulePlan.times),+ };+ } else if (state.schedulePlan && state.schedulePlan.type === "cron") {+ this.cronExpression = state.schedulePlan.expression || this.cronExpression;+ this.schedulePlan = { type: "cron", expression: this.cronExpression };+ } else if (state.cronExpression) {+ this.cronExpression = state.cronExpression;+ this.schedulePlan = { type: "cron", expression: this.cronExpression };+ }+ if (typeof state.instantPost === "boolean") {+ this.instantPost = state.instantPost;+ if (this.instantPost) {+ this._startWatching();+ }+ }+ } catch (error) {+ // Ignore missing file or parse error+ }+ }++ async _saveState() {+ try {+ await fs.writeFile(+ this.statePath,+ JSON.stringify(+ {+ cronExpression: this.cronExpression,+ schedulePlan: this.schedulePlan,+ instantPost: this.instantPost,+ },+ null,+ 2+ )+ );+ } catch (error) {+ this.log(`Failed to save scheduler state: ${error.message}`, "error");+ }+ }++ async setSchedule(expression) {+ if (!cron.validate(expression)) {+ throw new Error(`Invalid cron expression: ${expression}`);+ }+ this.cronExpression = expression;+ this.schedulePlan = { type: "cron", expression };+ await this._saveState();+ this.log(`Schedule updated to: ${expression}`);+ if (this.task) {+ this.stop();+ this.start();+ }+ return { ok: true, cronExpression: this.cronExpression };+ }++ async setDailyTimes(times) {+ const normalizedTimes = normalizeDailyTimes(times);+ this.schedulePlan = { type: "daily-times", times: normalizedTimes };+ this.lastScheduleTriggerKey = null;+ await this._saveState();+ this.log(`Schedule updated to daily times: ${normalizedTimes.join(", ")}`);+ if (this.task) {+ this.stop();+ this.start();+ }+ return { ok: true, schedulePlan: this.schedulePlan };+ }++ log(message, level = "info") {+ const entry = { at: nowIso(), level, message };+ this.logs.unshift(entry);+ this.logs = this.logs.slice(0, 50);+ const prefix = `[${entry.at}] [youtube:${this.accountId}]`;+ if (level === "error") {+ console.error(`${prefix} ${message}`);+ } else {+ console.log(`${prefix} ${message}`);+ }+ }++ async runOnce(source = "manual") {+ if (this.isPosting) {+ return { ok: false, skipped: true, reason: "A YouTube post is already in progress." };+ }++ this.isPosting = true;+ this.lastRunAt = nowIso();+ this.log(`Run triggered by ${source}.`);++ try {+ const result = await postNextFromQueue({+ source,+ queueDir: this.queueDir,+ postedDir: this.postedDir,+ failedDir: this.failedDir,+ accountId: this.accountId,+ });+ this.lastResult = result;++ if (result.skipped) {+ this.log(result.reason);+ } else if (result.ok) {+ this.log(`Posted successfully: ${result.movedVideo}`);+ } else {+ this.log(`Post failed: ${result.error}`, "error");+ if (result.screenshotPath) {+ this.log(`Screenshot: ${result.screenshotPath}`, "error");+ }+ }+ return result;+ } catch (error) {+ const failedResult = { ok: false, error: error.message || "Unexpected YouTube scheduler error" };+ this.lastResult = failedResult;+ this.log(`Post failed: ${failedResult.error}`, "error");+ return failedResult;+ } finally {+ this.isPosting = false;+ }+ }++ _scheduleWithJitter(source) {+ const MAX_JITTER_MS = 10 * 60 * 1000;+ const jitterMs = Math.floor(Math.random() * MAX_JITTER_MS);+ const jitterMin = Math.round(jitterMs / 1000 / 60 * 10) / 10;+ this.log(`Scheduled post will fire in ~${jitterMin} min (jitter).`);+ const timer = setTimeout(() => {+ this._scheduledTimers.delete(timer);+ if (!this.task) {+ this.log("Scheduled post skipped because scheduler is stopped.");+ return;+ }+ this.runOnce(source);+ }, jitterMs);+ this._scheduledTimers.add(timer);+ }++ _clearScheduledTimers() {+ for (const timer of this._scheduledTimers) {+ clearTimeout(timer);+ }+ this._scheduledTimers.clear();+ }++ start() {+ if (this.task) {+ return { ok: true, alreadyRunning: true };+ }++ if (this.schedulePlan.type === "daily-times") {+ const times = normalizeDailyTimes(this.schedulePlan.times);+ this.schedulePlan = { type: "daily-times", times };+ this.task = cron.schedule(+ "* * * * *",+ async () => {+ const currentTime = getLocalTimeKey(new Date(), config.timezone);+ if (!times.includes(currentTime)) return;+ const minuteKey = `${new Date().toISOString().slice(0, 16)}|${currentTime}`;+ if (this.lastScheduleTriggerKey === minuteKey) return;+ this.lastScheduleTriggerKey = minuteKey;+ this._scheduleWithJitter("daily-times");+ },+ { timezone: config.timezone }+ );+ this.log(`Scheduler started (daily times: ${times.join(", ")}, timezone: ${config.timezone}).`);+ return { ok: true, alreadyRunning: false };+ }++ if (!cron.validate(this.cronExpression)) {+ throw new Error(`Invalid CRON_EXPRESSION: ${this.cronExpression}`);+ }+ this.task = cron.schedule(+ this.cronExpression,+ async () => { this._scheduleWithJitter("cron"); },+ { timezone: config.timezone }+ );+ this.log(`Scheduler started (${this.cronExpression}, timezone: ${config.timezone}).`);+ return { ok: true, alreadyRunning: false };+ }++ stop() {+ this._clearScheduledTimers();+ if (!this.task) return { ok: true, alreadyStopped: true };+ this.task.stop();+ this.task.destroy();+ this.task = null;+ this.log("Scheduler stopped.");+ return { ok: true, alreadyStopped: false };+ }++ async setInstantPost(enabled) {+ this.instantPost = Boolean(enabled);+ await this._saveState();+ if (this.instantPost) {+ this._startWatching();+ this.log("Instant post ENABLED.");+ } else {+ this._stopWatching();+ this.log("Instant post DISABLED.");+ }+ return { ok: true, instantPost: this.instantPost };+ }++ _startWatching() {+ if (this._queueWatcher) return;+ const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);+ try {+ this._queueWatcher = fsSync.watch(this.queueDir, (eventType, filename) => {+ if (eventType !== "rename" || !filename) return;+ const ext = path.extname(filename).toLowerCase();+ if (!VIDEO_EXTS.has(ext)) return;+ clearTimeout(this._watchDebounce);+ this._watchDebounce = setTimeout(() => {+ this.log('Instant post: detected new file "' + filename + '"');+ this.runOnce("instant-post");+ }, 2000);+ });+ } catch (err) {+ this.log("Failed to watch queue directory: " + err.message, "error");+ }+ }++ _stopWatching() {+ if (this._queueWatcher) {+ this._queueWatcher.close();+ this._queueWatcher = null;+ }+ clearTimeout(this._watchDebounce);+ }++ async getQueueState() {+ const VIDEO_EXTS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);+ const pendingEntries = await fs.readdir(this.queueDir, { withFileTypes: true });+ const postedEntries = await fs.readdir(this.postedDir, { withFileTypes: true });+ const failedEntries = await fs.readdir(this.failedDir, { withFileTypes: true });++ const isVideo = (entry) => entry.isFile() && VIDEO_EXTS.has(path.extname(entry.name).toLowerCase());++ const pendingVideos = pendingEntries+ .filter(isVideo)+ .map((entry) => {+ const ext = path.extname(entry.name);+ const base = entry.name.slice(0, -ext.length);+ const hasCaption = pendingEntries.some(e => e.isFile() && (e.name === `${base}.description` || e.name === `${base}.txt`));+ return { name: entry.name, hasCaption };+ })+ .sort((a, b) => a.name.localeCompare(b.name));++ return {+ counts: {+ pending: pendingVideos.length,+ posted: postedEntries.filter(isVideo).length,+ failed: failedEntries.filter(isVideo).length,+ },+ pendingVideos,+ };+ }++ async getStatus() {+ const queue = await this.getQueueState();+ return {+ running: Boolean(this.task),+ isPosting: this.isPosting,+ cronExpression: this.cronExpression,+ schedulePlan: this.schedulePlan,+ instantPost: this.instantPost,+ timezone: config.timezone,+ randomQueueOrder: config.randomQueueOrder,+ accountId: this.accountId,+ queue,+ lastRunAt: this.lastRunAt,+ lastResult: this.lastResult,+ logs: this.logs,+ };+ }+}++module.exports = {+ YouTubeDaemonController,+ normalizeDailyTimes,+ getLocalTimeKey,+};diff --git a/src/youtube-post-service.js b/src/youtube-post-service.jsnew file mode 100644index 0000000..38ff023--- /dev/null+++ b/src/youtube-post-service.js@@ -0,0 +1,86 @@+const fs = require("fs/promises");+const path = require("path");+const { config } = require("./config");+const { getNextQueuedItem, getCaptionPaths } = require("./youtube-queue");+const { uploadVideo } = require("./youtube-uploader");+const { ensureDirectories, fileExists, moveWithTimestamp } = require("./fs-utils");++async function moveCaptionsIfExists(captionPaths, targetDir) {+ const moved = [];+ for (const cp of captionPaths) {+ if (await fileExists(cp)) {+ const result = await moveFileSafely(cp, targetDir, "caption file");+ if (result) moved.push(result);+ }+ }+ return moved.length > 0 ? moved[0] : null;+}++async function moveFileSafely(sourcePath, targetDir, label) {+ try {+ return await moveWithTimestamp(sourcePath, targetDir);+ } catch (error) {+ console.error(`Could not move ${label}: ${error.message}`);+ return null;+ }+}++async function postSingleVideo({ videoPath, caption, postedDir, failedDir, accountId }) {+ const posted = postedDir || config.youtubePostedDir;+ const failed = failedDir || config.youtubeFailedDir;+ await ensureDirectories([posted, failed]);++ const result = await uploadVideo({ videoPath, caption, accountId });+ const captionPaths = getCaptionPaths(videoPath);++ if (result.ok) {+ const movedVideo = await moveFileSafely(videoPath, posted, "posted video");+ const movedCaption = await moveCaptionsIfExists(captionPaths, posted);+ if (!movedVideo) {+ return {+ ok: false,+ error: "Video posted, but could not archive file from YouTube queue.",+ screenshotPath: result.screenshotPath,+ };+ }+ return { ok: true, movedVideo, movedCaption };+ }++ const movedVideo = await moveFileSafely(videoPath, failed, "failed video");+ const movedCaption = await moveCaptionsIfExists(captionPaths, failed);+ return {+ ok: false,+ movedVideo,+ movedCaption,+ error: result.error,+ screenshotPath: result.screenshotPath,+ };+}++async function postNextFromQueue({ source, queueDir, postedDir, failedDir, accountId } = {}) {+ const queue = queueDir || config.youtubeQueueDir;+ const posted = postedDir || config.youtubePostedDir;+ const failed = failedDir || config.youtubeFailedDir;+ await ensureDirectories([queue, posted, failed]);++ const nextItem = await getNextQueuedItem(queue);+ if (!nextItem) {+ return { ok: true, skipped: true, reason: "YouTube queue is empty." };+ }++ return postSingleVideo({ ...nextItem, postedDir: posted, failedDir: failed, accountId });+}++async function postFromManualInput(videoPath, caption) {+ const resolvedPath = path.resolve(videoPath);+ await fs.access(resolvedPath);+ return postSingleVideo({+ videoPath: resolvedPath,+ caption: caption || "",+ });+}++module.exports = {+ postNextFromQueue,+ postFromManualInput,+};diff --git a/src/youtube-queue.js b/src/youtube-queue.jsnew file mode 100644index 0000000..fc307de--- /dev/null+++ b/src/youtube-queue.js@@ -0,0 +1,68 @@+const fs = require("fs/promises");+const path = require("path");+const { config } = require("./config");++const VIDEO_EXTENSIONS = new Set([".mp4", ".mov", ".webm", ".avi", ".mkv"]);++function getCaptionPaths(videoPath) {+ const parsed = path.parse(videoPath);+ return [+ path.join(parsed.dir, `${parsed.name}.description`),+ path.join(parsed.dir, `${parsed.name}.txt`),+ ];+}++async function readCaption(videoPath) {+ const captionPaths = getCaptionPaths(videoPath);+ for (const cp of captionPaths) {+ try {+ const text = await fs.readFile(cp, "utf8");+ return text.trim();+ } catch {+ // try next+ }+ }+ return "";+}++async function listQueueVideos(queueDir) {+ const dir = queueDir || config.youtubeQueueDir;+ const entries = await fs.readdir(dir, { withFileTypes: true });+ const videos = entries+ .filter((entry) => entry.isFile())+ .filter((entry) => VIDEO_EXTENSIONS.has(path.extname(entry.name).toLowerCase()))+ .map((entry) => path.join(dir, entry.name));++ videos.sort((a, b) => a.localeCompare(b));+ return videos;+}++function pickNextVideo(videos) {+ if (videos.length === 0) {+ return null;+ }+ if (config.randomQueueOrder) {+ return videos[Math.floor(Math.random() * videos.length)];+ }+ return videos[0];+}++async function getNextQueuedItem(queueDir) {+ const videos = await listQueueVideos(queueDir);+ const videoPath = pickNextVideo(videos);+ if (!videoPath) {+ return null;+ }++ const caption = await readCaption(videoPath);+ return {+ videoPath,+ caption,+ captionPaths: getCaptionPaths(videoPath),+ };+}++module.exports = {+ getNextQueuedItem,+ getCaptionPaths,+};\ No newline at end of filediff --git a/src/youtube-uploader.js b/src/youtube-uploader.jsnew file mode 100644index 0000000..ae39a34--- /dev/null+++ b/src/youtube-uploader.js@@ -0,0 +1,465 @@+const path = require("path");+const fs = require("fs/promises");+const { chromium } = require("playwright");+const { config } = require("./config");+const uiLabels = require("./platform-ui-labels");+const {+ getActiveAccount,+ getPlatformProfileDir,+ hasSavedPlatformSession,+} = require("./account-manager");++let loginSessionContext = null;+let loginSessionAccountId = null;++async function openPersistentContext(accountId) {+ const profileDir = await getPlatformProfileDir("youtube", accountId);+ await fs.mkdir(profileDir, { recursive: true });+ return chromium.launchPersistentContext(profileDir, {+ headless: config.headless,+ viewport: { width: 1400, height: 1000 },+ locale: config.browserLocale,+ timezoneId: config.timezone,+ args: ["--disable-blink-features=AutomationControlled"],+ });+}++async function gotoUploadPage(page) {+ await page.goto(config.youtubeUploadPageUrl, { waitUntil: "domcontentloaded" });+}++async function clickFirstVisibleEnabledLocator(page, locator) {+ const total = await locator.count();+ for (let i = 0; i < total; i += 1) {+ const candidate = locator.nth(i);+ const visible = await candidate.isVisible().catch(() => false);+ if (!visible) continue;+ const disabled = await candidate.isDisabled().catch(() => false);+ if (disabled) continue;+ try {+ await candidate.scrollIntoViewIfNeeded({ timeout: 3000 });+ await candidate.click({ timeout: 5000 });+ return true;+ } catch {+ try {+ await candidate.click({ timeout: 5000, force: true });+ return true;+ } catch {+ // continue+ }+ }+ }+ return false;+}++async function openUploadDialog(page) {+ async function recoverFromInvalidUploadPage() {+ const bodyText = (await page.locator("body").innerText().catch(() => "")) || "";+ const onBrokenUploadPage =+ /studio\.youtube\.com\/videos\/upload/.test(page.url()) &&+ uiLabels.pattern("error").test(bodyText);+ if (!onBrokenUploadPage) return;++ await page.goto("https://studio.youtube.com", { waitUntil: "domcontentloaded" });+ await page.waitForTimeout(1200);+ }++ await recoverFromInvalidUploadPage();++ const hasFileInput = async () => (await page.locator('input[type="file"]').count()) > 0;+ if (await hasFileInput()) return true;++ const createButtons = [+ // Explicitly target YouTube Studio's top-right create button host.+ page.locator(uiLabels.attrSelector("ytcp-button.ytcpAppHeaderCreateIcon button", "aria-label", "youtubeCreate")),+ page.getByRole("button", { name: uiLabels.pattern("youtubeCreate") }),+ page.locator(uiLabels.attrSelector("button", "aria-label", "youtubeCreate")),+ ];++ const uploadTargets = [+ page.locator('a[href*="/channel/"][href*="/videos/upload"]'),+ page.getByRole("menuitem", { name: uiLabels.pattern("youtubeUploadVideo") }),+ page.getByRole("button", { name: uiLabels.pattern("youtubeUploadVideo") }),+ page.locator(uiLabels.attrSelector("ytcp-icon-button", "aria-label", "youtubeUploadVideo")),+ page.locator(uiLabels.attrSelector("ytcp-button button", "aria-label", "youtubeUploadVideo")),+ page.locator('a[href*="/videos/upload"]'),+ page.locator('[role="menuitem"], a, button').filter({+ hasText: uiLabels.pattern("youtubeUploadVideo"),+ }),+ ];++ for (const btn of createButtons) {+ const clicked = await clickFirstVisibleEnabledLocator(page, btn);+ if (!clicked) continue;+ await page.waitForTimeout(700);+ for (const target of uploadTargets) {+ const picked = await clickFirstVisibleEnabledLocator(page, target);+ if (!picked) continue;+ await page.waitForTimeout(1200);+ if ((await hasFileInput()) || /\/videos\/upload/.test(page.url())) {+ return true;+ }+ }+ }++ // Fallback: use explicit channel upload link if available.+ const directUploadLink = page.locator('a[href*="/channel/"][href*="/videos/upload"]').first();+ if ((await directUploadLink.count()) > 0) {+ await clickFirstVisibleEnabledLocator(page, directUploadLink);+ await page.waitForTimeout(1200);+ if ((await hasFileInput()) || /\/videos\/upload/.test(page.url())) {+ return true;+ }+ }++ return await hasFileInput();+}++async function setVideoFile(page, videoPath) {+ await openUploadDialog(page);++ const tryViaFileChooser = async () => {+ const triggers = [+ page.getByRole("button", {+ name: uiLabels.pattern("youtubeUploadVideo", "youtubeSelectFiles"),+ }),+ page.locator(uiLabels.attrSelector("button", "aria-label", "youtubeUploadVideo")),+ page.locator(uiLabels.attrSelector("button", "aria-label", "youtubeSelectFiles")),+ page.locator("ytcp-upload-video-button button, ytcp-button#upload-button button"),+ page.locator(uiLabels.attrSelector("ytcp-icon-button", "aria-label", "youtubeUploadVideo")),+ page.locator('a[test-id="upload-icon-url"], a[href*="/videos/upload"]'),+ page.locator("button, [role='button']").filter({+ hasText: uiLabels.pattern("youtubeUploadVideo", "youtubeSelectFiles"),+ }),+ ];++ for (const trigger of triggers) {+ const chooserPromise = page+ .waitForEvent("filechooser", { timeout: 2500 })+ .catch(() => null);+ const clicked = await clickFirstVisibleEnabledLocator(page, trigger);+ if (!clicked) continue;+ const chooser = await chooserPromise;+ if (chooser) {+ await chooser.setFiles(videoPath);+ return true;+ }+ }+ return false;+ };++ if (await tryViaFileChooser()) {+ return;+ }++ let fileInput = page.locator('input[type="file"]').first();+ if ((await fileInput.count()) > 0) {+ await fileInput.setInputFiles(videoPath);+ return;+ }++ await page.waitForTimeout(1200);+ if (await tryViaFileChooser()) {+ return;+ }++ fileInput = page.locator('input[type="file"]').first();+ try {+ await fileInput.waitFor({ state: "attached", timeout: 10000 });+ await fileInput.setInputFiles(videoPath);+ return;+ } catch {+ const uploadUrl = page.url();+ throw new Error(+ `Could not open YouTube file picker on upload page. Current URL: ${uploadUrl}`+ );+ }+}++async function setTitleAndDescription(page, caption, fileNameStem) {+ const effectiveCaption = caption && caption.trim() ? caption.trim() : "";+ const baseTitle = effectiveCaption || fileNameStem;+ const shortTitle = baseTitle.slice(0, 95);+ const descriptionText = effectiveCaption || config.defaultCaption || "";++ async function fillContentEditable(locator, value) {+ if ((await locator.count()) === 0) return false;+ try {+ await locator.first().click({ timeout: 5000 });+ await page.keyboard.press("Control+A");+ await page.keyboard.press("Delete");+ if (value) {+ await page.keyboard.type(value, { delay: 8 });+ }++ // Force model sync in Polymer inputs.+ await locator.first().evaluate((el, nextValue) => {+ const node = el;+ node.textContent = nextValue;+ node.dispatchEvent(new InputEvent("input", { bubbles: true, composed: true }));+ node.dispatchEvent(new Event("change", { bubbles: true, composed: true }));+ }, value);+ return true;+ } catch {+ return false;+ }+ }++ const titleCandidates = [+ page.locator('#title-textarea #textbox[contenteditable="true"]').first(),+ page.locator('#title-textarea [role="textbox"][contenteditable="true"]').first(),+ page.locator(uiLabels.attrSelector("textarea", "aria-label", "youtubeTitleAttribute")).first(),+ page.locator('#title-textarea textarea').first(),+ ];++ let titleSet = false;+ for (const titleInput of titleCandidates) {+ titleSet = await fillContentEditable(titleInput, shortTitle);+ if (titleSet) break;+ }++ const descCandidates = [+ page.locator('#description-textarea #textbox[contenteditable="true"]').first(),+ page.locator('#description-textarea [role="textbox"][contenteditable="true"]').first(),+ page.locator(uiLabels.attrSelector("textarea", "aria-label", "youtubeDescriptionAttribute")).first(),+ page.locator('#description-textarea textarea').first(),+ ];+ let descSet = false;+ for (const descInput of descCandidates) {+ descSet = await fillContentEditable(descInput, descriptionText);+ if (descSet) break;+ }++ if (!titleSet) {+ throw new Error("Could not set YouTube title field in upload wizard.");+ }+ if (!descSet) {+ throw new Error("Could not set YouTube description field in upload wizard.");+ }+}++async function markNotMadeForKids(page) {+ const selectors = [+ page.locator('tp-yt-paper-radio-button[name="VIDEO_MADE_FOR_KIDS_NOT_MFK"]'),+ page.locator('[name="VIDEO_MADE_FOR_KIDS_NOT_MFK"]'),+ page.getByRole("radio", { name: uiLabels.pattern("youtubeNotMadeForKids") }),+ page.locator('[name="VIDEO_MADE_FOR_KIDS_NOT_MFK"], tp-yt-paper-radio-button').filter({+ hasText: uiLabels.pattern("youtubeNotMadeForKids"),+ }),+ ];+ for (const selector of selectors) {+ const clicked = await clickFirstVisibleEnabledLocator(page, selector);+ if (!clicked) continue;+ const chosen = page.locator('tp-yt-paper-radio-button[name="VIDEO_MADE_FOR_KIDS_NOT_MFK"]');+ const checked = await chosen+ .first()+ .getAttribute("aria-checked")+ .catch(() => null);+ if (checked === "true") {+ return;+ }+ }++ throw new Error('Could not select "not made for kids" option.');+}++async function setNotAgeRestricted(page) {+ const desired = page.locator('tp-yt-paper-radio-button[name="VIDEO_AGE_RESTRICTION_NONE"]');+ const isSelected = async () =>+ (await desired.first().getAttribute("aria-checked").catch(() => null)) === "true";++ if (await isSelected()) {+ return;+ }++ const expandButton = page.locator('button[aria-controls="age-restriction"]').first();+ if ((await desired.count()) === 0 || !(await desired.first().isVisible().catch(() => false))) {+ const canExpand = (await expandButton.count()) > 0;+ if (canExpand) {+ await clickFirstVisibleEnabledLocator(page, expandButton);+ await page.waitForTimeout(500);+ }+ }++ const clicked = await clickFirstVisibleEnabledLocator(+ page,+ page.locator(+ 'tp-yt-paper-radio-button[name="VIDEO_AGE_RESTRICTION_NONE"], [name="VIDEO_AGE_RESTRICTION_NONE"]'+ )+ );+ if (!clicked || !(await isSelected())) {+ throw new Error('Could not select "not age restricted" option.');+ }+}++async function clickNext(page) {+ const nextLocators = [+ page.locator("ytcp-button#next-button button"),+ page.getByRole("button", { name: uiLabels.pattern("next") }),+ page.locator(uiLabels.attrSelector("button", "aria-label", "next")),+ ];++ for (let i = 0; i < 6; i += 1) {+ const doneBtn = page.locator("ytcp-button#done-button button").first();+ const doneVisible = await doneBtn.isVisible().catch(() => false);+ if (doneVisible) {+ return;+ }++ let clicked = false;+ for (const locator of nextLocators) {+ clicked = await clickFirstVisibleEnabledLocator(page, locator);+ if (clicked) {+ await page.waitForTimeout(1200);+ break;+ }+ }+ if (!clicked) break;+ }+}++async function setVisibilityAndPublish(page) {+ const visibilityOptions = [+ page.getByRole("radio", { name: uiLabels.pattern("youtubePublic") }),+ page.locator('tp-yt-paper-radio-button').filter({ hasText: uiLabels.pattern("youtubePublic") }),+ ];+ for (const option of visibilityOptions) {+ const clicked = await clickFirstVisibleEnabledLocator(page, option);+ if (clicked) break;+ }++ const publishButtons = [+ page.locator("ytcp-button#done-button button"),+ page.getByRole("button", { name: uiLabels.pattern("youtubePublish") }),+ page.getByRole("button", { name: uiLabels.pattern("youtubeSave") }),+ page.locator("ytcp-button#done-button button"),+ page.locator("button").filter({ hasText: uiLabels.pattern("youtubePublish", "youtubeSave") }),+ ];+ for (const btn of publishButtons) {+ const disabled = await btn.first().isDisabled().catch(() => false);+ if (disabled) continue;+ const clicked = await clickFirstVisibleEnabledLocator(page, btn);+ if (clicked) return true;+ }+ return false;+}++async function waitForPublishConfirmation(page) {+ for (let i = 0; i < 40; i += 1) {+ const bodyText = await page.locator("body").innerText().catch(() => "");+ if (uiLabels.pattern("youtubePublished").test(bodyText)) {+ return { ok: true };+ }+ if (uiLabels.pattern("error").test(bodyText)) {+ return { ok: false, reason: "YouTube reported an error while publishing." };+ }+ await page.waitForTimeout(1500);+ }+ return { ok: false, reason: "No reliable YouTube publish confirmation within timeout." };+}++async function startLoginSession() {+ const activeAccount = await getActiveAccount();+ if (loginSessionContext && loginSessionAccountId !== activeAccount.id) {+ const previous = loginSessionContext;+ loginSessionContext = null;+ loginSessionAccountId = null;+ await previous.close().catch(() => { });+ }++ if (loginSessionContext) {+ return { ok: true, alreadyOpen: true };+ }+ const context = await openPersistentContext(activeAccount.id);+ const page = context.pages()[0] || (await context.newPage());+ loginSessionContext = context;+ loginSessionAccountId = activeAccount.id;+ context.on("close", () => {+ if (loginSessionContext === context) {+ loginSessionContext = null;+ loginSessionAccountId = null;+ }+ });+ await gotoUploadPage(page);+ return { ok: true, alreadyOpen: false, url: page.url() };+}++async function getLoginSessionStatus() {+ const activeAccount = await getActiveAccount();+ const saved = await hasSavedPlatformSession("youtube", activeAccount.id);+ return {+ open: Boolean(loginSessionContext) && loginSessionAccountId === activeAccount.id,+ saved,+ };+}++async function closeLoginSession() {+ if (!loginSessionContext) {+ return { ok: true, alreadyClosed: true };+ }+ const context = loginSessionContext;+ loginSessionContext = null;+ loginSessionAccountId = null;+ await context.close().catch(() => { });+ return { ok: true, alreadyClosed: false };+}++async function uploadVideo({ videoPath, caption, accountId }) {+ const absoluteVideoPath = path.resolve(videoPath);+ const context = await openPersistentContext(accountId);+ const page = context.pages()[0] || (await context.newPage());+ let closeHoldMs = 0;+ try {+ await gotoUploadPage(page);+ await setVideoFile(page, absoluteVideoPath);+ await page.waitForTimeout(Math.max(config.postDelayMs, 5000));+ await setTitleAndDescription(+ page,+ caption,+ path.parse(absoluteVideoPath).name+ );+ await markNotMadeForKids(page);+ await setNotAgeRestricted(page);+ await clickNext(page);+ const published = await setVisibilityAndPublish(page);+ if (!published) {+ throw new Error("Could not find/click YouTube publish button.");+ }++ const confirmation = await waitForPublishConfirmation(page);+ if (!confirmation.ok) {+ throw new Error(confirmation.reason);+ }++ const successScreenshotPath = path.resolve(+ config.projectRoot,+ "last-youtube-upload-success.png"+ );+ await page.screenshot({ path: successScreenshotPath, fullPage: true }).catch(() => { });+ closeHoldMs = Math.max(config.postPublishHoldMs, 0);+ return { ok: true };+ } catch (error) {+ const screenshotPath = path.resolve(+ config.projectRoot,+ "last-youtube-upload-error.png"+ );+ await page.screenshot({ path: screenshotPath, fullPage: true }).catch(() => { });+ closeHoldMs = Math.max(config.failureHoldMs, 0);+ return {+ ok: false,+ error: error.message,+ screenshotPath,+ };+ } finally {+ await page.waitForTimeout(closeHoldMs).catch(() => { });+ await context.close();+ }+}++module.exports = {+ uploadVideo,+ startLoginSession,+ getLoginSessionStatus,+ closeLoginSession,+};+diff --git a/test/config-example.test.js b/test/config-example.test.jsnew file mode 100644index 0000000..a9b1921--- /dev/null+++ b/test/config-example.test.js@@ -0,0 +1,15 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("fs");+const path = require("path");+const dotenv = require("dotenv");++test(".env.example ships without personal content defaults", () => {+ const envExamplePath = path.resolve(__dirname, "..", ".env.example");+ const parsed = dotenv.parse(fs.readFileSync(envExamplePath));++ assert.equal(parsed.AUTO_ADD_SOUND, "false");+ assert.equal(parsed.DEFAULT_CAPTION, "");+ assert.equal(parsed.DEFAULT_SOUND_QUERY, "");+ assert.equal(parsed.WATCH_CHANNEL, "");+});diff --git a/test/fs-utils.test.js b/test/fs-utils.test.jsnew file mode 100644index 0000000..532369b--- /dev/null+++ b/test/fs-utils.test.js@@ -0,0 +1,26 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("fs/promises");+const os = require("os");+const path = require("path");++const { moveWithTimestamp } = require("../src/fs-utils");++async function makeTempDir() {+ return fs.mkdtemp(path.join(os.tmpdir(), "autosocial-fs-"));+}++test("moveWithTimestamp archives a file without losing content", async () => {+ const root = await makeTempDir();+ const source = path.join(root, "source video.mp4");+ const archiveDir = path.join(root, "posted");+ await fs.mkdir(archiveDir);+ await fs.writeFile(source, "video-content");++ const archivedPath = await moveWithTimestamp(source, archiveDir);++ assert.equal(await fs.readFile(archivedPath, "utf8"), "video-content");+ await assert.rejects(fs.access(source));+ assert.equal(path.dirname(archivedPath), archiveDir);+ assert.match(path.basename(archivedPath), /source_video_[a-f0-9]{8}\.mp4$/);+});diff --git a/test/queue.test.js b/test/queue.test.jsnew file mode 100644index 0000000..f2102b6--- /dev/null+++ b/test/queue.test.js@@ -0,0 +1,42 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("fs/promises");+const os = require("os");+const path = require("path");++const { getNextQueuedItem, listQueueVideos } = require("../src/queue");++async function makeTempDir() {+ return fs.mkdtemp(path.join(os.tmpdir(), "autosocial-queue-"));+}++test("listQueueVideos returns only supported videos in sorted order", async () => {+ const dir = await makeTempDir();+ await fs.writeFile(path.join(dir, "b.mov"), "");+ await fs.writeFile(path.join(dir, "a.mp4"), "");+ await fs.writeFile(path.join(dir, "notes.txt"), "");++ const videos = await listQueueVideos(dir);++ assert.deepEqual(+ videos.map((filePath) => path.basename(filePath)),+ ["a.mp4", "b.mov"]+ );+});++test("getNextQueuedItem reads .description before .txt sidecars", async () => {+ const dir = await makeTempDir();+ const videoPath = path.join(dir, "clip.mp4");+ await fs.writeFile(videoPath, "");+ await fs.writeFile(path.join(dir, "clip.txt"), "txt caption");+ await fs.writeFile(path.join(dir, "clip.description"), "description caption");++ const item = await getNextQueuedItem(dir);++ assert.equal(item.videoPath, videoPath);+ assert.equal(item.caption, "description caption");+ assert.deepEqual(+ item.captionPaths.map((filePath) => path.basename(filePath)),+ ["clip.description", "clip.txt"]+ );+});diff --git a/test/repository-language.test.js b/test/repository-language.test.jsnew file mode 100644index 0000000..1a6cc8c--- /dev/null+++ b/test/repository-language.test.js@@ -0,0 +1,97 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("fs");+const path = require("path");+const { spawnSync } = require("child_process");++const projectRoot = path.resolve(__dirname, "..");+const excludedTextFiles = new Set([+ "src/platform-ui-labels.js",+ "test/repository-language.test.js",+]);+const binaryExtensions = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico"]);+const localizedTermHex = [+ "776569746572",+ "7465696c656e",+ "706f7374656e",+ "626573636872656962756e67",+ "626573636872656962",+ "617573776165686c656e",+ "6175737761686c656e",+ "6461746569",+ "6461746569656e",+ "686f63686c6164656e",+ "7665726f656666656e746c696368656e",+ "7665726f656666656e746c69636874",+ "6f656666656e746c696368",+ "73706569636865726e",+ "7a7573636861756572",+ "6665686c6572",+ "67657465696c74",+ "62656974726167",+ "6d6f65676c696368",+ "6d6f676c696368",+ "6b6f6e6e7465",+ "6e69636874",+ "766f6d20636f6d7075746572",+ "766964656f7320686f63686c6164656e",+ "766964656f207775726465",+ "7665726172626569746574",+ "6e65696e",+ "65727374656c6c656e",+ "737061746572",+ "73706165746572",+ "61626272656368656e",+ "7363686c69657373656e",+ "626573746165746967656e",+ "666f727466616872656e",+ "6572666f6c677265696368",+ "6765706c616e74",+ "7072756566756e67",+ "70727566756e67",+ "696e68616c74737072756566756e67",+ "616b746976696572656e",+ "65696e736368616c74656e",+ "7665727374616e64656e",+ "65726e657574",+ "76657273756368656e",+];+const localizedTerms = localizedTermHex.map((value) => Buffer.from(value, "hex").toString("utf8"));++function escapeRegExp(value) {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++function hasLocalizedTerm(content) {+ return localizedTerms.some((term) => {+ const pattern = new RegExp(`(^|[^a-z0-9])${escapeRegExp(term)}($|[^a-z0-9])`, "i");+ return pattern.test(content);+ });+}++function getTrackedFiles() {+ const result = spawnSync("git", ["ls-files"], {+ cwd: projectRoot,+ encoding: "utf8",+ });+ assert.equal(result.status, 0, result.stderr || "git ls-files failed");+ return result.stdout+ .split(/\r?\n/)+ .filter(Boolean)+ .filter((filePath) => !excludedTextFiles.has(filePath))+ .filter((filePath) => !binaryExtensions.has(path.extname(filePath).toLowerCase()));+}++test("public-facing tracked text files are English-only ASCII", () => {+ const failures = [];++ for (const relativePath of getTrackedFiles()) {+ const absolutePath = path.join(projectRoot, relativePath);+ const content = fs.readFileSync(absolutePath, "utf8");+ if (/[^\x00-\x7F]/.test(content) || hasLocalizedTerm(content)) {+ failures.push(relativePath);+ }+ }++ assert.deepEqual(failures, []);+});diff --git a/test/request-guard.test.js b/test/request-guard.test.jsnew file mode 100644index 0000000..65b2684--- /dev/null+++ b/test/request-guard.test.js@@ -0,0 +1,52 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { isAllowedDashboardRequest } = require("../src/request-guard");++test("dashboard request guard allows safe methods", () => {+ assert.equal(+ isAllowedDashboardRequest({+ method: "GET",+ headers: { host: "127.0.0.1:3000", origin: "https://example.com" },+ }),+ true+ );+});++test("dashboard request guard allows same-origin mutations", () => {+ assert.equal(+ isAllowedDashboardRequest({+ method: "POST",+ headers: {+ host: "127.0.0.1:3000",+ origin: "http://127.0.0.1:3000",+ },+ }),+ true+ );+});++test("dashboard request guard blocks cross-origin mutations", () => {+ assert.equal(+ isAllowedDashboardRequest({+ method: "POST",+ headers: {+ host: "127.0.0.1:3000",+ origin: "https://example.com",+ },+ }),+ false+ );+});++test("dashboard request guard blocks cross-site fetch metadata without origin", () => {+ assert.equal(+ isAllowedDashboardRequest({+ method: "POST",+ headers: {+ host: "127.0.0.1:3000",+ "sec-fetch-site": "cross-site",+ },+ }),+ false+ );+});diff --git a/test/scheduler.test.js b/test/scheduler.test.jsnew file mode 100644index 0000000..6f58f01--- /dev/null+++ b/test/scheduler.test.js@@ -0,0 +1,26 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ normalizeDailyTimes,+ getLocalTimeKey,+} = require("../src/daemon-controller");++test("normalizeDailyTimes validates, pads, de-duplicates and sorts times", () => {+ assert.deepEqual(+ normalizeDailyTimes(["9:05", "21:30", "09:05", " 7:00 "]),+ ["07:00", "09:05", "21:30"]+ );+});++test("normalizeDailyTimes rejects invalid or empty schedules", () => {+ assert.throws(() => normalizeDailyTimes([]), /at least one/);+ assert.throws(() => normalizeDailyTimes(["24:00"]), /Invalid time/);+ assert.throws(() => normalizeDailyTimes(["12:99"]), /Invalid time/);+});++test("getLocalTimeKey formats a date in the requested timezone", () => {+ const date = new Date("2026-06-03T10:15:00.000Z");+ assert.equal(getLocalTimeKey(date, "Europe/Berlin"), "12:15");+ assert.equal(getLocalTimeKey(date, "UTC"), "10:15");+});diff --git a/test/tiktok-uploader.test.js b/test/tiktok-uploader.test.jsnew file mode 100644index 0000000..c0c3147--- /dev/null+++ b/test/tiktok-uploader.test.js@@ -0,0 +1,62 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const { _private } = require("../src/tiktok-uploader");++const { isLikelyPublishCandidateInfo } = _private;++test("TikTok publish candidate rejects the Studio sidebar Posts item", () => {+ const candidate = {+ disabled: false,+ inNavigation: true,+ rect: { left: 48, top: 300, width: 120, height: 36 },+ role: "button",+ tagName: "button",+ text: "Posts",+ viewportWidth: 1200,+ };++ assert.equal(isLikelyPublishCandidateInfo(candidate), false);+});++test("TikTok publish candidate accepts the main upload Post button", () => {+ const candidate = {+ disabled: false,+ inNavigation: false,+ rect: { left: 900, top: 780, width: 160, height: 44 },+ role: "",+ tagName: "button",+ text: "Post",+ viewportWidth: 1200,+ };++ assert.equal(isLikelyPublishCandidateInfo(candidate), true);+});++test("TikTok publish candidate rejects ambiguous left-side Post controls", () => {+ const candidate = {+ disabled: false,+ inNavigation: false,+ rect: { left: 80, top: 320, width: 120, height: 36 },+ role: "",+ tagName: "button",+ text: "Post",+ viewportWidth: 1200,+ };++ assert.equal(isLikelyPublishCandidateInfo(candidate), false);+});++test("TikTok publish candidate allows Post controls in the main content area", () => {+ const candidate = {+ disabled: false,+ inNavigation: false,+ rect: { left: 300, top: 760, width: 160, height: 44 },+ role: "",+ tagName: "button",+ text: "Post",+ viewportWidth: 1200,+ };++ assert.equal(isLikelyPublishCandidateInfo(candidate), true);+});diff --git a/test/uniquifier-controller.test.js b/test/uniquifier-controller.test.jsnew file mode 100644index 0000000..41c77e7--- /dev/null+++ b/test/uniquifier-controller.test.js@@ -0,0 +1,33 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("fs/promises");+const os = require("os");+const path = require("path");++const { UniquifierController } = require("../src/uniquifier-controller");++async function makeTempDir() {+ return fs.mkdtemp(path.join(os.tmpdir(), "autosocial-uniquifier-"));+}++test("UniquifierController accepts optional user logo paths", async () => {+ const root = await makeTempDir();+ const inputDir = path.join(root, "input");+ const outputDir = path.join(root, "output");+ const logoPath = path.join(root, "logo.png");+ await fs.writeFile(logoPath, "");++ const controller = new UniquifierController();++ const withLogo = await controller.setFolders({+ inputDir,+ outputDir,+ logoImage: logoPath,+ });+ assert.equal(withLogo.logoImage, logoPath);++ const withoutLogo = await controller.setFolders({+ logoImage: "",+ });+ assert.equal(withoutLogo.logoImage, "");+});diff --git a/web/app.js b/web/app.jsnew file mode 100644index 0000000..0355fa4--- /dev/null+++ b/web/app.js@@ -0,0 +1,1814 @@+const API = {+ async get(endpoint) {+ const res = await fetch(endpoint);+ if (!res.ok) throw new Error(`API Error: ${res.status}`);+ return res.json();+ },+ async post(endpoint, body) {+ const options = {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ };+ if (body !== undefined) {+ options.body = JSON.stringify(body);+ }+ const res = await fetch(endpoint, options);+ if (!res.ok) throw new Error(`API Error: ${res.status}`);+ return res.json();+ },+};++function escapeHtml(value) {+ return String(value ?? "")+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'");+}++const Router = {+ init() {+ const navItems = document.querySelectorAll(".nav-item");+ navItems.forEach((btn) => {+ btn.addEventListener("click", () => {+ const view = btn.dataset.view;+ this.navigate(view);+ });+ });+ },++ navigate(viewName) {+ document.querySelectorAll(".nav-item").forEach((btn) => {+ btn.classList.toggle("active", btn.dataset.view === viewName);+ });+ document.querySelectorAll(".view-section").forEach((sec) => {+ sec.classList.toggle("active", sec.id === `view-${viewName}`);+ });+ },+};++const UI = {+ accountState: {+ tiktok: { loginOpen: false, sessionSaved: false, schedulerRunning: false },+ instagram: { loginOpen: false, sessionSaved: false, schedulerRunning: false },+ youtube: { loginOpen: false, sessionSaved: false, schedulerRunning: false },+ brands: [],+ activeBrandId: null,+ activeBrandName: "",+ },+ scheduleDraftDirty: {+ tiktok: false,+ instagram: false,+ youtube: false,+ },++ els: {+ brandSelect: document.getElementById("brandSelect"),+ addBrandBtn: document.getElementById("addBrandBtn"),+ brandCreateRow: document.getElementById("brandCreateRow"),+ brandNameInput: document.getElementById("brandNameInput"),+ saveBrandBtn: document.getElementById("saveBrandBtn"),+ cancelBrandBtn: document.getElementById("cancelBrandBtn"),+ activeBrandLabel: document.getElementById("activeBrandLabel"),+ statusBadge: document.getElementById("statusBadge"),++ pendingCount: document.getElementById("pendingCount"),+ successCount: document.getElementById("successCount"),+ failedCount: document.getElementById("failedCount"),+ activeAccountsCount: document.getElementById("activeAccountsCount"),+ overviewProfilesContainer: document.getElementById("overviewProfilesContainer"),++ ttQueueList: document.getElementById("ttQueueList"),+ logsContainer: document.getElementById("logsContainer"),+ ttLogsContainer: document.getElementById("ttLogsContainer"),+ accountsTableBody: document.getElementById("accountsTableBody"),++ ttRunBtn: document.getElementById("ttRunBtn"),+ ttStartBtn: document.getElementById("ttStartBtn"),+ ttStopBtn: document.getElementById("ttStopBtn"),+ ttCronInput: document.getElementById("ttCronInput"),+ ttUpdateScheduleBtn: document.getElementById("ttUpdateScheduleBtn"),+ ttPlanType: document.getElementById("ttPlanType"),+ ttPlanTime: document.getElementById("ttPlanTime"),+ ttPlanTimes: document.getElementById("ttPlanTimes"),+ ttPlanWeekday: document.getElementById("ttPlanWeekday"),+ ttPlanApplyBtn: document.getElementById("ttPlanApplyBtn"),+ ttPendingCount: document.getElementById("ttPendingCount"),+ ttPostedCount: document.getElementById("ttPostedCount"),+ ttFailedCount: document.getElementById("ttFailedCount"),+ ttSchedulerState: document.getElementById("ttSchedulerState"),+ ttTimezoneLabel: document.getElementById("ttTimezoneLabel"),+ ttLastRunLabel: document.getElementById("ttLastRunLabel"),+ ttInstantPostToggle: document.getElementById("ttInstantPostToggle"),+ ttAutoAddSoundToggle: document.getElementById("ttAutoAddSoundToggle"),+ ttSoundQueryInput: document.getElementById("ttSoundQueryInput"),+ ttSoundQuerySaveBtn: document.getElementById("ttSoundQuerySaveBtn"),+ ttRandomQueueToggle: document.getElementById("ttRandomQueueToggle"),+ igRunBtn: document.getElementById("igRunBtn"),+ igStartBtn: document.getElementById("igStartBtn"),+ igStopBtn: document.getElementById("igStopBtn"),+ igCronInput: document.getElementById("igCronInput"),+ igUpdateScheduleBtn: document.getElementById("igUpdateScheduleBtn"),+ igPlanType: document.getElementById("igPlanType"),+ igPlanTime: document.getElementById("igPlanTime"),+ igPlanTimes: document.getElementById("igPlanTimes"),+ igPlanWeekday: document.getElementById("igPlanWeekday"),+ igPlanApplyBtn: document.getElementById("igPlanApplyBtn"),+ igPendingCount: document.getElementById("igPendingCount"),+ igPostedCount: document.getElementById("igPostedCount"),+ igFailedCount: document.getElementById("igFailedCount"),+ igSchedulerState: document.getElementById("igSchedulerState"),+ igTimezoneLabel: document.getElementById("igTimezoneLabel"),+ igLastRunLabel: document.getElementById("igLastRunLabel"),+ igInstantPostToggle: document.getElementById("igInstantPostToggle"),+ igRandomQueueToggle: document.getElementById("igRandomQueueToggle"),+ igQueueList: document.getElementById("igQueueList"),+ igLogsContainer: document.getElementById("igLogsContainer"),+ ytRunBtn: document.getElementById("ytRunBtn"),+ ytStartBtn: document.getElementById("ytStartBtn"),+ ytStopBtn: document.getElementById("ytStopBtn"),+ ytCronInput: document.getElementById("ytCronInput"),+ ytUpdateScheduleBtn: document.getElementById("ytUpdateScheduleBtn"),+ ytPlanType: document.getElementById("ytPlanType"),+ ytPlanTime: document.getElementById("ytPlanTime"),+ ytPlanTimes: document.getElementById("ytPlanTimes"),+ ytPlanWeekday: document.getElementById("ytPlanWeekday"),+ ytPlanApplyBtn: document.getElementById("ytPlanApplyBtn"),+ ytPendingCount: document.getElementById("ytPendingCount"),+ ytPostedCount: document.getElementById("ytPostedCount"),+ ytFailedCount: document.getElementById("ytFailedCount"),+ ytSchedulerState: document.getElementById("ytSchedulerState"),+ ytTimezoneLabel: document.getElementById("ytTimezoneLabel"),+ ytLastRunLabel: document.getElementById("ytLastRunLabel"),+ ytInstantPostToggle: document.getElementById("ytInstantPostToggle"),+ ytRandomQueueToggle: document.getElementById("ytRandomQueueToggle"),+ ytQueueList: document.getElementById("ytQueueList"),+ ytLogsContainer: document.getElementById("ytLogsContainer"),++ uniqStartBtn: document.getElementById("uniqStartBtn"),+ uniqStopBtn: document.getElementById("uniqStopBtn"),+ uniqOpenInputBtn: document.getElementById("uniqOpenInputBtn"),+ uniqOpenOutputBtn: document.getElementById("uniqOpenOutputBtn"),+ uniqInputDir: document.getElementById("uniqInputDir"),+ uniqOutputDir: document.getElementById("uniqOutputDir"),+ uniqLogoImage: document.getElementById("uniqLogoImage"),+ uniqState: document.getElementById("uniqState"),+ uniqProgress: document.getElementById("uniqProgress"),+ uniqSucceeded: document.getElementById("uniqSucceeded"),+ uniqFailed: document.getElementById("uniqFailed"),+ uniqInputFiles: document.getElementById("uniqInputFiles"),+ uniqOutputFiles: document.getElementById("uniqOutputFiles"),+ uniqLogs: document.getElementById("uniqLogs"),++ adStartBtn: document.getElementById("adStartBtn"),+ adStopBtn: document.getElementById("adStopBtn"),+ adChannel: document.getElementById("adChannel"),+ adInterval: document.getElementById("adInterval"),+ adMaxVideos: document.getElementById('adMaxVideos'),+ adPlatTiktok: document.getElementById('adPlatTiktok'),+ adPlatInstagram: document.getElementById("adPlatInstagram"),+ adPlatYoutube: document.getElementById("adPlatYoutube"),+ adSaveSettingsBtn: document.getElementById("adSaveSettingsBtn"),+ adWatcherState: document.getElementById("adWatcherState"),+ adTotalDownloaded: document.getElementById("adTotalDownloaded"),+ adLastCheck: document.getElementById("adLastCheck"),+ adLogsContainer: document.getElementById("adLogsContainer"),+ defaultCaptionInput: document.getElementById("defaultCaptionInput"),+ defaultCaptionSaveBtn: document.getElementById("defaultCaptionSaveBtn"),++ // Profile Downloader+ pdChannel: document.getElementById("pdChannel"),+ pdMaxVideos: document.getElementById("pdMaxVideos"),+ pdMinViews: document.getElementById("pdMinViews"),+ pdStartBtn: document.getElementById("pdStartBtn"),+ pdScanBtn: document.getElementById("pdScanBtn"),+ pdOpenFolderBtn: document.getElementById("pdOpenFolderBtn"),+ pdLogsContainer: document.getElementById("pdLogsContainer"),+ pdStatusBadge: document.getElementById("pdStatusBadge"),+ },++ init() {+ Router.init();+ this.bindEvents();+ this.updateFriendlyScheduleVisibility("tiktok");+ this.updateFriendlyScheduleVisibility("instagram");+ this.updateFriendlyScheduleVisibility("youtube");+ this.startPolling();+ this.renderAccounts();+ },++ bindEvents() {+ if (this.els.brandSelect) {+ this.els.brandSelect.addEventListener("change", (event) =>+ this.handleBrandSelect(event.target.value)+ );+ }+ if (this.els.addBrandBtn) {+ this.els.addBrandBtn.addEventListener("click", () => this.handleAddBrand());+ }+ if (this.els.saveBrandBtn) {+ this.els.saveBrandBtn.addEventListener("click", () => this.handleCreateBrand());+ }+ if (this.els.cancelBrandBtn) {+ this.els.cancelBrandBtn.addEventListener("click", () => this.hideBrandCreator());+ }+ if (this.els.brandNameInput) {+ this.els.brandNameInput.addEventListener("keydown", (event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ this.handleCreateBrand();+ } else if (event.key === "Escape") {+ this.hideBrandCreator();+ }+ });+ }++ if (this.els.ttStartBtn) {+ this.els.ttStartBtn.addEventListener("click", () => this.handleAction("/api/start"));+ }+ if (this.els.ttStopBtn) {+ this.els.ttStopBtn.addEventListener("click", () => this.handleAction("/api/stop"));+ }+ if (this.els.ttRunBtn) {+ this.els.ttRunBtn.addEventListener("click", () => this.handleAction("/api/run-once"));+ }+ if (this.els.ttUpdateScheduleBtn) {+ this.els.ttUpdateScheduleBtn.addEventListener("click", () =>+ this.handleUpdateSchedule(true)+ );+ }+ if (this.els.ttPlanType) {+ this.els.ttPlanType.addEventListener("change", () =>+ this.handleFriendlyScheduleDraftChange("tiktok")+ );+ }+ if (this.els.ttPlanTime) {+ this.els.ttPlanTime.addEventListener("change", () =>+ this.handleFriendlyScheduleDraftChange("tiktok")+ );+ }+ if (this.els.ttPlanWeekday) {+ this.els.ttPlanWeekday.addEventListener("change", () =>+ this.handleFriendlyScheduleDraftChange("tiktok")+ );+ }+ if (this.els.ttPlanTimes) {+ this.els.ttPlanTimes.addEventListener("input", () =>+ this.handleFriendlyScheduleDraftChange("tiktok")+ );+ }+ if (this.els.ttPlanApplyBtn) {+ this.els.ttPlanApplyBtn.addEventListener("click", () =>+ this.handleFriendlySchedule("tiktok")+ );+ }+ if (this.els.ttInstantPostToggle) {+ this.els.ttInstantPostToggle.addEventListener("change", (e) =>+ this.handleInstantPostToggle("tiktok", e.target.checked)+ );+ }++ if (this.els.ttAutoAddSoundToggle) {+ this.els.ttAutoAddSoundToggle.addEventListener("change", async (e) => {+ try {+ const result = await API.post("/api/settings/save", {+ payload: { AUTO_ADD_SOUND: e.target.checked }+ });+ if (result?.ok === false && result?.error) {+ alert(result.error);+ e.target.checked = !e.target.checked; // Revert visually on error+ }+ this.refresh();+ } catch (err) {+ alert(`Failed to save auto-add sound setting: ${err.message}`);+ e.target.checked = !e.target.checked;+ }+ });+ }++ if (this.els.ttSoundQuerySaveBtn) {+ this.els.ttSoundQuerySaveBtn.addEventListener("click", () =>+ this.handleSaveTextSetting(+ "DEFAULT_SOUND_QUERY",+ this.els.ttSoundQueryInput,+ this.els.ttSoundQuerySaveBtn,+ "Save Sound",+ "Sound query"+ )+ );+ }++ if (this.els.ttRandomQueueToggle) {+ this.els.ttRandomQueueToggle.addEventListener("change", (e) =>+ this.handleRandomQueueToggle(e.target.checked)+ );+ }++ if (this.els.igStartBtn) {+ this.els.igStartBtn.addEventListener("click", () =>+ this.handleAction("/api/instagram/start")+ );+ }+ if (this.els.igStopBtn) {+ this.els.igStopBtn.addEventListener("click", () =>+ this.handleAction("/api/instagram/stop")+ );+ }+ if (this.els.igRunBtn) {+ this.els.igRunBtn.addEventListener("click", () =>+ this.handleAction("/api/instagram/run-once")+ );+ }+ if (this.els.igUpdateScheduleBtn) {+ this.els.igUpdateScheduleBtn.addEventListener("click", () =>+ this.handleUpdateSchedule(false, true)+ );+ }+ if (this.els.igPlanType) {+ this.els.igPlanType.addEventListener("change", () =>+ this.handleFriendlyScheduleDraftChange("instagram")+ );+ }+ if (this.els.igPlanTime) {+ this.els.igPlanTime.addEventListener("change", () =>+ this.handleFriendlyScheduleDraftChange("instagram")+ );+ }+ if (this.els.igPlanWeekday) {+ this.els.igPlanWeekday.addEventListener("change", () =>+ this.handleFriendlyScheduleDraftChange("instagram")+ );+ }+ if (this.els.igPlanTimes) {+ this.els.igPlanTimes.addEventListener("input", () =>+ this.handleFriendlyScheduleDraftChange("instagram")+ );+ }+ if (this.els.igPlanApplyBtn) {+ this.els.igPlanApplyBtn.addEventListener("click", () =>+ this.handleFriendlySchedule("instagram")+ );+ }+ if (this.els.igInstantPostToggle) {+ this.els.igInstantPostToggle.addEventListener("change", () =>+ this.handleInstantPostToggle("instagram", this.els.igInstantPostToggle.checked)+ );+ }+ if (this.els.igRandomQueueToggle) {+ this.els.igRandomQueueToggle.addEventListener("change", () =>+ this.handleRandomQueueToggle(this.els.igRandomQueueToggle.checked)+ );+ }+ if (this.els.ytStartBtn) {+ this.els.ytStartBtn.addEventListener("click", () =>+ this.handleAction("/api/youtube/start")+ );+ }+ if (this.els.ytStopBtn) {+ this.els.ytStopBtn.addEventListener("click", () =>+ this.handleAction("/api/youtube/stop")+ );+ }+ if (this.els.ytRunBtn) {+ this.els.ytRunBtn.addEventListener("click", () =>+ this.handleAction("/api/youtube/run-once")+ );+ }+ if (this.els.ytUpdateScheduleBtn) {+ this.els.ytUpdateScheduleBtn.addEventListener("click", () =>+ this.handleUpdateSchedule(false, false, true)+ );+ }+ if (this.els.ytPlanType) {+ this.els.ytPlanType.addEventListener("change", () =>+ this.handleFriendlyScheduleDraftChange("youtube")+ );+ }+ if (this.els.ytPlanTime) {+ this.els.ytPlanTime.addEventListener("change", () =>+ this.handleFriendlyScheduleDraftChange("youtube")+ );+ }+ if (this.els.ytPlanWeekday) {+ this.els.ytPlanWeekday.addEventListener("change", () =>+ this.handleFriendlyScheduleDraftChange("youtube")+ );+ }+ if (this.els.ytPlanTimes) {+ this.els.ytPlanTimes.addEventListener("input", () =>+ this.handleFriendlyScheduleDraftChange("youtube")+ );+ }+ if (this.els.ytPlanApplyBtn) {+ this.els.ytPlanApplyBtn.addEventListener("click", () =>+ this.handleFriendlySchedule("youtube")+ );+ }+ if (this.els.ytInstantPostToggle) {+ this.els.ytInstantPostToggle.addEventListener("change", () =>+ this.handleInstantPostToggle("youtube", this.els.ytInstantPostToggle.checked)+ );+ }+ if (this.els.ytRandomQueueToggle) {+ this.els.ytRandomQueueToggle.addEventListener("change", () =>+ this.handleRandomQueueToggle(this.els.ytRandomQueueToggle.checked)+ );+ }+ if (this.els.accountsTableBody) {+ this.els.accountsTableBody.addEventListener("click", (event) =>+ this.handleAccountsTableClick(event)+ );+ }++ if (this.els.uniqStartBtn) {+ this.els.uniqStartBtn.addEventListener("click", () => this.handleUniquifierStart());+ }+ if (this.els.uniqStopBtn) {+ this.els.uniqStopBtn.addEventListener("click", () => this.handleUniquifierStop());+ }+ if (this.els.uniqOpenInputBtn) {+ this.els.uniqOpenInputBtn.addEventListener("click", () =>+ this.handleOpenFolder("input", this.els.uniqInputDir?.value)+ );+ }+ if (this.els.uniqOpenOutputBtn) {+ this.els.uniqOpenOutputBtn.addEventListener("click", () =>+ this.handleOpenFolder("output", this.els.uniqOutputDir?.value)+ );+ }++ // Auto-download events+ if (this.els.adStartBtn) {+ this.els.adStartBtn.addEventListener("click", () => this.handleAutoDownloadAction("/api/autodownload/start"));+ }+ if (this.els.adStopBtn) {+ this.els.adStopBtn.addEventListener("click", () => this.handleAutoDownloadAction("/api/autodownload/stop"));+ }+ if (this.els.adSaveSettingsBtn) {+ this.els.adSaveSettingsBtn.addEventListener("click", () => this.handleAutoDownloadSave());+ }+ if (this.els.defaultCaptionSaveBtn) {+ this.els.defaultCaptionSaveBtn.addEventListener("click", () =>+ this.handleSaveTextSetting(+ "DEFAULT_CAPTION",+ this.els.defaultCaptionInput,+ this.els.defaultCaptionSaveBtn,+ "Save Caption",+ "Default caption"+ )+ );+ }++ // Profile Downloader Listeners+ if (this.els.pdStartBtn) {+ this.els.pdStartBtn.addEventListener("click", () => this.handleProfileDownloadStart(false));+ }+ if (this.els.pdScanBtn) {+ this.els.pdScanBtn.addEventListener("click", () => this.handleProfileDownloadStart(true));+ }+ if (this.els.pdOpenFolderBtn) {+ this.els.pdOpenFolderBtn.addEventListener("click", () => this.handleProfileDownloadOpenFolder());+ }+ },++ async handleAddBrand() {+ if (!this.els.brandCreateRow) {+ const name = prompt("Brand name?");+ if (!name || !name.trim()) return;+ try {+ const result = await API.post("/api/accounts/add", { name: name.trim() });+ if (result?.ok === false && result?.error) {+ alert(result.error);+ }+ await this.refresh();+ } catch (err) {+ alert(`Could not add brand: ${err.message}`);+ }+ return;+ }++ this.els.brandCreateRow.classList.remove("hidden");+ if (this.els.brandNameInput) {+ this.els.brandNameInput.value = "";+ this.els.brandNameInput.focus();+ }+ },++ hideBrandCreator() {+ if (!this.els.brandCreateRow) return;+ this.els.brandCreateRow.classList.add("hidden");+ if (this.els.brandNameInput) {+ this.els.brandNameInput.value = "";+ }+ },++ async handleCreateBrand() {+ const name = this.els.brandNameInput?.value?.trim();+ if (!name) return;+ try {+ const result = await API.post("/api/accounts/add", { name });+ if (result?.ok === false && result?.error) {+ alert(result.error);+ return;+ }+ this.hideBrandCreator();+ await this.refresh();+ } catch (err) {+ alert(`Could not add brand: ${err.message}`);+ }+ },++ async handleBrandSelect(accountId) {+ if (!accountId || accountId === this.accountState.activeBrandId) return;+ try {+ await API.post("/api/accounts/select", { accountId });+ await this.refresh();+ } catch (err) {+ alert(`Could not switch brand: ${err.message}`);+ }+ },++ async handleAction(endpoint) {+ try {+ const result = await API.post(endpoint);+ if (result && result.skipped && result.reason) {+ alert(result.reason);+ } else if (result && result.ok === false && result.error) {+ alert(result.error);+ }+ this.refresh();+ } catch (err) {+ alert(`Action failed: ${err.message}`);+ }+ },++ getPlatformScheduleControls(platform) {+ const map = {+ tiktok: {+ type: this.els.ttPlanType,+ time: this.els.ttPlanTime,+ times: this.els.ttPlanTimes,+ weekday: this.els.ttPlanWeekday,+ cronInput: this.els.ttCronInput,+ },+ instagram: {+ type: this.els.igPlanType,+ time: this.els.igPlanTime,+ times: this.els.igPlanTimes,+ weekday: this.els.igPlanWeekday,+ cronInput: this.els.igCronInput,+ },+ youtube: {+ type: this.els.ytPlanType,+ time: this.els.ytPlanTime,+ times: this.els.ytPlanTimes,+ weekday: this.els.ytPlanWeekday,+ cronInput: this.els.ytCronInput,+ },+ };+ return map[platform];+ },++ getPlatformEndpoints(platform) {+ const map = {+ tiktok: { schedule: "/api/schedule", runOnce: "/api/run-once" },+ instagram: { schedule: "/api/instagram/schedule", runOnce: "/api/instagram/run-once" },+ youtube: { schedule: "/api/youtube/schedule", runOnce: "/api/youtube/run-once" },+ };+ return map[platform];+ },++ markScheduleDraftDirty(platform, dirty = true) {+ if (!Object.prototype.hasOwnProperty.call(this.scheduleDraftDirty, platform)) return;+ this.scheduleDraftDirty[platform] = dirty;+ },++ isScheduleDraftDirty(platform) {+ return Boolean(this.scheduleDraftDirty[platform]);+ },++ handleFriendlyScheduleDraftChange(platform) {+ this.markScheduleDraftDirty(platform, true);+ this.updateFriendlyScheduleVisibility(platform);+ },++ updateFriendlyScheduleVisibility(platform) {+ const controls = this.getPlatformScheduleControls(platform);+ if (+ !controls?.type ||+ !controls?.time ||+ !controls?.times ||+ !controls?.weekday ||+ !controls?.cronInput+ ) {+ return;+ }+ const mode = controls.type.value;+ controls.weekday.style.display = mode === "weekly" ? "" : "none";+ controls.time.style.display = /^every\d+h$/.test(mode) || mode === "dailyTimes" ? "none" : "";+ controls.times.style.display = mode === "dailyTimes" ? "" : "none";+ controls.cronInput.disabled = mode !== "custom";+ },++ parseCronToFriendly(cronExpression) {+ const cron = (cronExpression || "").trim();+ const daily = cron.match(/^(\d{1,2})\s+(\d{1,2})\s+\*\s+\*\s+\*$/);+ if (daily) {+ const minute = String(Number(daily[1])).padStart(2, "0");+ const hour = String(Number(daily[2])).padStart(2, "0");+ return { mode: "daily", time: `${hour}:${minute}` };+ }++ const weekly = cron.match(/^(\d{1,2})\s+(\d{1,2})\s+\*\s+\*\s+([0-6])$/);+ if (weekly) {+ const minute = String(Number(weekly[1])).padStart(2, "0");+ const hour = String(Number(weekly[2])).padStart(2, "0");+ return { mode: "weekly", time: `${hour}:${minute}`, weekday: weekly[3] };+ }++ const everyNh = cron.match(/^(\d{1,2})\s+\*\/(\d{1,2})\s+\*\s+\*\s+\*$/);+ if (everyNh) {+ const step = Number(everyNh[2]);+ if ([2, 3, 4, 6, 8, 12].includes(step)) {+ return { mode: `every${step}h` };+ }+ }++ return { mode: "custom" };+ },++ applyFriendlyScheduleFromCron(platform, cronExpression) {+ if (this.isScheduleDraftDirty(platform)) {+ this.updateFriendlyScheduleVisibility(platform);+ return;+ }+ const controls = this.getPlatformScheduleControls(platform);+ if (!controls?.type) return;+ const parsed = this.parseCronToFriendly(cronExpression);+ if (controls.type && document.activeElement !== controls.type) {+ controls.type.value = parsed.mode;+ }+ if (controls.time && parsed.time && document.activeElement !== controls.time) {+ controls.time.value = parsed.time;+ }+ if (controls.weekday && parsed.weekday && document.activeElement !== controls.weekday) {+ controls.weekday.value = parsed.weekday;+ }+ this.updateFriendlyScheduleVisibility(platform);+ },++ applySchedulePlanFromStatus(platform, statusData) {+ const controls = this.getPlatformScheduleControls(platform);+ if (!controls?.type) return;+ const plan = statusData?.schedulePlan;+ if (plan?.type === "daily-times") {+ if (!this.isScheduleDraftDirty(platform)) {+ controls.type.value = "dailyTimes";+ if (controls.times && document.activeElement !== controls.times) {+ controls.times.value = (plan.times || []).join(", ");+ }+ }+ this.updateFriendlyScheduleVisibility(platform);+ return;+ }++ this.applyFriendlyScheduleFromCron(platform, statusData?.cronExpression || "");+ },++ buildCronFromFriendly(mode, timeValue, weekdayValue) {+ const everyMatch = /^every(\d+)h$/.exec(mode || "");+ if (everyMatch) {+ const step = Number(everyMatch[1]);+ if ([2, 3, 4, 6, 8, 12].includes(step)) {+ return `0 */${step} * * *`;+ }+ }+ if (mode === "daily" || mode === "weekly") {+ const [hourRaw, minuteRaw] = (timeValue || "12:00").split(":");+ const hour = Math.min(Math.max(Number(hourRaw) || 0, 0), 23);+ const minute = Math.min(Math.max(Number(minuteRaw) || 0, 0), 59);+ if (mode === "daily") {+ return `${minute} ${hour} * * *`;+ }+ const weekday = ["0", "1", "2", "3", "4", "5", "6"].includes(String(weekdayValue))+ ? String(weekdayValue)+ : "1";+ return `${minute} ${hour} * * ${weekday}`;+ }+ return null;+ },++ parseTimesInput(value) {+ return String(value || "")+ .split(",")+ .map((item) => item.trim())+ .filter(Boolean);+ },++ async handleFriendlySchedule(platform) {+ const controls = this.getPlatformScheduleControls(platform);+ const endpoints = this.getPlatformEndpoints(platform);+ if (!controls?.type || !endpoints) return;++ const mode = controls.type.value;+ if (mode === "once") {+ this.markScheduleDraftDirty(platform, false);+ await this.handleAction(endpoints.runOnce);+ return;+ }++ if (mode === "dailyTimes") {+ const parsedTimes = this.parseTimesInput(controls.times?.value);+ if (!parsedTimes.length) {+ alert("Please enter at least one time, e.g. 09:30, 13:15, 20:45");+ return;+ }+ try {+ await API.post(`${endpoints.schedule}-plan`, {+ type: "daily-times",+ times: parsedTimes,+ });+ this.markScheduleDraftDirty(platform, false);+ await this.refresh();+ } catch (err) {+ alert(`Schedule update failed: ${err.message}`);+ }+ return;+ }++ if (mode === "custom") {+ const cronExpression = controls.cronInput?.value?.trim();+ if (!cronExpression) {+ alert("Please enter a cron expression.");+ return;+ }+ try {+ await API.post(endpoints.schedule, { expression: cronExpression });+ this.markScheduleDraftDirty(platform, false);+ await this.refresh();+ } catch (err) {+ alert(`Schedule update failed: ${err.message}`);+ }+ return;+ }++ const cronExpression = this.buildCronFromFriendly(+ mode,+ controls.time?.value,+ controls.weekday?.value+ );+ if (!cronExpression) return;+ try {+ await API.post(endpoints.schedule, { expression: cronExpression });+ this.markScheduleDraftDirty(platform, false);+ await this.refresh();+ } catch (err) {+ alert(`Schedule update failed: ${err.message}`);+ }+ },++ async handleUpdateSchedule(+ fromTikTokView,+ fromInstagramView = false,+ fromYouTubeView = false+ ) {+ const platform = fromYouTubeView+ ? "youtube"+ : fromInstagramView+ ? "instagram"+ : "tiktok";+ const input = platform === "youtube"+ ? this.els.ytCronInput+ : platform === "instagram"+ ? this.els.igCronInput+ : this.els.ttCronInput;+ const saveBtn = platform === "youtube"+ ? this.els.ytUpdateScheduleBtn+ : platform === "instagram"+ ? this.els.igUpdateScheduleBtn+ : this.els.ttUpdateScheduleBtn;+ if (!input || !saveBtn) return;++ const expression = input.value.trim();+ if (!expression) return;++ try {+ const defaultLabel = "Save Schedule";+ saveBtn.textContent = "Saved!";+ setTimeout(() => {+ saveBtn.textContent = defaultLabel;+ }, 2000);++ const endpoint = fromYouTubeView+ ? "/api/youtube/schedule"+ : fromInstagramView+ ? "/api/instagram/schedule"+ : "/api/schedule";+ await API.post(endpoint, { expression });+ this.markScheduleDraftDirty(platform, false);+ this.refresh();+ } catch (err) {+ alert(`Schedule update failed: ${err.message}`);+ }+ },++ async handleUniquifierStart() {+ try {+ await API.post("/api/uniquifier/start", {+ inputDir: this.els.uniqInputDir?.value?.trim(),+ outputDir: this.els.uniqOutputDir?.value?.trim(),+ logoImage: this.els.uniqLogoImage?.value?.trim(),+ });+ await this.refresh();+ } catch (err) {+ alert(`Uniquifier start failed: ${err.message}`);+ }+ },++ async handleUniquifierStop() {+ try {+ await API.post("/api/uniquifier/stop");+ await this.refresh();+ } catch (err) {+ alert(`Uniquifier stop failed: ${err.message}`);+ }+ },++ async handleOpenFolder(kind, folderPath) {+ try {+ await API.post("/api/uniquifier/open-folder", {+ kind,+ folderPath: folderPath || undefined,+ });+ } catch (err) {+ alert(`Could not open folder: ${err.message}`);+ }+ },++ async handleInstantPostToggle(platform, enabled) {+ const endpointMap = {+ tiktok: "/api/instant-post",+ instagram: "/api/instagram/instant-post",+ youtube: "/api/youtube/instant-post",+ };+ const toggleMap = {+ tiktok: this.els.ttInstantPostToggle,+ instagram: this.els.igInstantPostToggle,+ youtube: this.els.ytInstantPostToggle,+ };+ try {+ await API.post(endpointMap[platform], { enabled });+ this.refresh();+ } catch (err) {+ alert(`Could not toggle instant post: ${err.message}`);+ if (toggleMap[platform]) {+ toggleMap[platform].checked = !enabled;+ }+ }+ },++ async handleRandomQueueToggle(enabled) {+ const toggles = [+ this.els.ttRandomQueueToggle,+ this.els.igRandomQueueToggle,+ this.els.ytRandomQueueToggle,+ ].filter(Boolean);+ try {+ const result = await API.post("/api/settings/save", {+ payload: { RANDOM_QUEUE_ORDER: enabled },+ });+ if (result?.ok === false && result?.error) {+ throw new Error(result.error);+ }+ this.refresh();+ } catch (err) {+ alert(`Could not update random queue order: ${err.message}`);+ toggles.forEach((toggle) => {+ toggle.checked = !enabled;+ });+ }+ },++ async handleSaveTextSetting(envKey, inputEl, buttonEl, idleLabel, label) {+ if (!inputEl) return;++ try {+ const result = await API.post("/api/settings/save", {+ payload: { [envKey]: inputEl.value || "" },+ });+ if (result?.ok === false && result?.error) {+ throw new Error(result.error);+ }+ if (buttonEl) {+ buttonEl.innerHTML = '<i class="ph ph-check"></i> Saved!';+ setTimeout(() => {+ buttonEl.textContent = idleLabel;+ }, 2000);+ }+ this.refresh();+ } catch (err) {+ alert(`${label} save failed: ${err.message}`);+ }+ },++ async handleInstagramLogin() {+ await this.handlePlatformLogin("instagram");+ },++ async handleYouTubeLogin() {+ await this.handlePlatformLogin("youtube");+ },++ async handlePlatformLogin(platform) {+ const endpointMap = {+ tiktok: "/api/tiktok/login",+ instagram: "/api/instagram/login",+ youtube: "/api/youtube/login",+ };+ const labelMap = {+ tiktok: "TikTok",+ instagram: "Instagram",+ youtube: "YouTube",+ };+ try {+ const result = await API.post(endpointMap[platform]);+ if (result.alreadyOpen) {+ alert(`${labelMap[platform]} login browser is already open.`);+ } else {+ alert(`${labelMap[platform]} Chromium opened. Please log in there once.`);+ }+ await this.refresh();+ } catch (err) {+ alert(`${labelMap[platform]} login failed: ${err.message}`);+ }+ },++ async handlePlatformCloseLogin(platform) {+ const endpointMap = {+ tiktok: "/api/tiktok/login/close",+ instagram: "/api/instagram/login/close",+ youtube: "/api/youtube/login/close",+ };+ const labelMap = {+ tiktok: "TikTok",+ instagram: "Instagram",+ youtube: "YouTube",+ };+ try {+ const result = await API.post(endpointMap[platform]);+ if (!result.alreadyClosed) {+ alert(`${labelMap[platform]} login browser closed.`);+ }+ await this.refresh();+ } catch (err) {+ alert(`Could not close ${labelMap[platform]} login browser: ${err.message}`);+ }+ },++ async handleAccountsTableClick(event) {+ const button = event.target.closest("button[data-platform][data-action]");+ if (!button) return;+ const { platform, action } = button.dataset;+ if (action === "login") {+ await this.handlePlatformLogin(platform);+ return;+ }+ if (action === "close") {+ await this.handlePlatformCloseLogin(platform);+ }+ },++ startPolling() {+ this.refresh();+ setInterval(() => this.refresh(), 3000);+ },++ async refresh() {+ try {+ const [+ status,+ instagramStatus,+ youtubeStatus,+ uniquifier,+ accounts,+ tiktokLoginStatus,+ instagramLoginStatus,+ youtubeLoginStatus,+ ] = await Promise.all([+ API.get("/api/status"),+ API.get("/api/instagram/status"),+ API.get("/api/youtube/status"),+ API.get("/api/uniquifier/status"),+ API.get("/api/accounts"),+ API.get("/api/tiktok/login/status"),+ API.get("/api/instagram/login/status"),+ API.get("/api/youtube/login/status"),+ ]);+ // Fetch autodownload status in parallel but don't block others+ API.get("/api/autodownload/status").then((ad) => this.renderAutoDownloadStatus(ad)).catch(() => { });+ API.get("/api/profile-download/status").then((pd) => this.renderProfileDownloadStatus(pd)).catch(() => { });+ API.get("/api/overview").then((ov) => this.renderOverview(ov)).catch(() => { });++ this.renderStatus(status);+ this.renderInstagramStatus(instagramStatus);+ this.renderYouTubeStatus(youtubeStatus);+ this.renderUniquifierStatus(uniquifier);+ this.renderBrandSelector(accounts);+ this.accountState = {+ tiktok: {+ loginOpen: Boolean(tiktokLoginStatus?.open),+ sessionSaved: Boolean(tiktokLoginStatus?.saved),+ schedulerRunning: Boolean(status?.running),+ },+ instagram: {+ loginOpen: Boolean(instagramLoginStatus?.open),+ sessionSaved: Boolean(instagramLoginStatus?.saved),+ schedulerRunning: Boolean(instagramStatus?.running),+ },+ youtube: {+ loginOpen: Boolean(youtubeLoginStatus?.open),+ sessionSaved: Boolean(youtubeLoginStatus?.saved),+ schedulerRunning: Boolean(youtubeStatus?.running),+ },+ brands: accounts?.accounts || [],+ activeBrandId: accounts?.activeAccountId || null,+ activeBrandName: accounts?.activeAccount?.name || "",+ };+ this.renderAccounts();+ } catch (err) {+ console.warn("Polling error", err);+ }+ },++ updateLogContainer(container, html) {+ if (!container) return;+ const nextHtml = html || "";+ if (container.innerHTML === nextHtml) return;++ const topThreshold = 24;+ const wasNearTop = container.scrollTop <= topThreshold;+ const bottomOffset = Math.max(+ 0,+ container.scrollHeight - container.clientHeight - container.scrollTop+ );++ container.innerHTML = nextHtml;++ if (wasNearTop) {+ container.scrollTop = 0;+ return;+ }++ container.scrollTop = Math.max(+ 0,+ container.scrollHeight - container.clientHeight - bottomOffset+ );+ },++ renderBrandSelector(data) {+ if (!this.els.brandSelect || !data) return;+ const brands = Array.isArray(data.accounts) ? data.accounts : [];+ const activeAccountId = data.activeAccountId || brands[0]?.id || "";+ const currentValue = this.els.brandSelect.value;++ this.els.brandSelect.innerHTML = brands+ .map((brand) => `<option value="${escapeHtml(brand.id)}">${escapeHtml(brand.name)}</option>`)+ .join("");++ if (brands.some((brand) => brand.id === currentValue)) {+ this.els.brandSelect.value = currentValue;+ } else {+ this.els.brandSelect.value = activeAccountId;+ }+ },++ renderOverview(overviewData) {+ if (!overviewData || typeof overviewData !== "object") return;+ const container = this.els.overviewProfilesContainer;+ if (!container) return;++ const platformMeta = {+ tiktok: {+ label: "TikTok",+ icon: "ph-tiktok-logo",+ color: "#ff0050",+ bg: "linear-gradient(135deg,#00f2ea,#ff0050)",+ },+ instagram: {+ label: "Instagram",+ icon: "ph-instagram-logo",+ color: "#E1306C",+ bg: "linear-gradient(135deg,#833AB4,#E1306C,#F77737)",+ },+ youtube: {+ label: "YouTube",+ icon: "ph-youtube-logo",+ color: "#FF0000",+ bg: "#FF0000",+ },+ };++ const escapeHtml = (value) => String(value ?? "")+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'");++ const getProfileName = (profileId) => {+ const brands = this.accountState?.brands || [];+ const match = brands.find((brand) => brand.id === profileId);+ return match?.name || profileId;+ };++ const formatSchedule = (status) => {+ if (status?.schedulePlan?.type === "daily-times") {+ const times = Array.isArray(status.schedulePlan.times) && status.schedulePlan.times.length+ ? status.schedulePlan.times.join(", ")+ : "Not set";+ return `Daily: ${times}`;+ }+ if (status?.cronExpression) {+ return `Cron: ${status.cronExpression}`;+ }+ return "Not scheduled";+ };++ const formatLastRun = (status) => (+ status?.lastRunAt ? new Date(status.lastRunAt).toLocaleString() : "Never"+ );++ const getBadge = (status) => {+ if (status?.isPosting) {+ return { text: "Posting", color: "var(--status-warn)" };+ }+ if (status?.running) {+ return { text: "Running", color: "var(--status-good)" };+ }+ return { text: "Stopped", color: "var(--status-bad)" };+ };++ let totalPending = 0;+ let totalPosted = 0;+ let totalFailed = 0;+ let activeSchedulers = 0;+ const allLogs = [];+ const profileSections = [];++ for (const [profileId, statuses] of Object.entries(overviewData)) {+ const profileName = getProfileName(profileId);+ const cards = [];++ for (const [platformKey, meta] of Object.entries(platformMeta)) {+ const status = statuses?.[platformKey];+ if (!status) continue;++ const queueCounts = status.queue?.counts || {};+ const pending = Number(queueCounts.pending || 0);+ const posted = Number(queueCounts.posted || 0);+ const failed = Number(queueCounts.failed || 0);+ const badge = getBadge(status);++ totalPending += pending;+ totalPosted += posted;+ totalFailed += failed;+ if (status.running) {+ activeSchedulers += 1;+ }++ for (const log of status.logs || []) {+ allLogs.push({ ...log, platform: meta.label, profile: profileName });+ }++ cards.push(`+ <div class="card" style="border-left:3px solid ${meta.color};">+ <div style="display:flex; align-items:center; gap:12px; margin-bottom:14px;">+ <div class="brand-icon" style="background:${meta.bg}; width:34px; height:34px; font-size:18px;">+ <i class="ph ${meta.icon}"></i>+ </div>+ <div style="min-width:0;">+ <div style="font-weight:600; font-size:15px;">${escapeHtml(meta.label)}</div>+ <div class="status-badge" style="margin-top:4px; color:${badge.color}; border:1px solid ${badge.color}; background:rgba(255,255,255,0.03);">+ ${escapeHtml(badge.text)}+ </div>+ </div>+ </div>+ <div style="display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:8px; text-align:center;">+ <div>+ <div style="font-size:22px; font-weight:700;">${pending}</div>+ <div style="font-size:11px; color:var(--text-muted);">Pending</div>+ </div>+ <div>+ <div style="font-size:22px; font-weight:700; color:var(--success);">${posted}</div>+ <div style="font-size:11px; color:var(--text-muted);">Posted</div>+ </div>+ <div>+ <div style="font-size:22px; font-weight:700; color:var(--danger);">${failed}</div>+ <div style="font-size:11px; color:var(--text-muted);">Failed</div>+ </div>+ </div>+ <div style="margin-top:12px; padding-top:10px; border-top:1px solid rgba(255,255,255,0.06); font-size:12px; color:var(--text-muted);">+ <div><i class="ph ph-clock"></i> ${escapeHtml(formatSchedule(status))}</div>+ <div style="margin-top:4px;"><i class="ph ph-calendar-blank"></i> Last: ${escapeHtml(formatLastRun(status))}</div>+ </div>+ </div>+ `);+ }++ if (cards.length > 0) {+ profileSections.push(`+ <div style="margin-bottom:22px;">+ <div style="display:flex; align-items:center; gap:10px; margin-bottom:12px; font-size:14px; font-weight:600; color:var(--text-primary);">+ <i class="ph ph-user"></i>+ <span>${escapeHtml(profileName)}</span>+ </div>+ <div style="display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:12px;">+ ${cards.join("")}+ </div>+ </div>+ `);+ }+ }++ container.innerHTML = profileSections.join("") || `+ <div class="card full-width">+ <div style="text-align:center; padding:28px; color:var(--text-muted);">No profile overview data yet.</div>+ </div>+ `;++ const setValue = (el, value) => {+ if (el) el.textContent = value;+ };+ setValue(this.els.pendingCount, totalPending);+ setValue(this.els.successCount, totalPosted);+ setValue(this.els.failedCount, totalFailed);+ setValue(this.els.activeAccountsCount, activeSchedulers);++ allLogs.sort((a, b) => (b.at || "").localeCompare(a.at || ""));+ const recentLogs = allLogs.slice(0, 50);++ const logsHtml = recentLogs.length+ ? recentLogs.map((logEntry) => {+ const time = logEntry.at ? new Date(logEntry.at).toLocaleTimeString() : "";+ const color = logEntry.level === "error" ? "var(--danger)" : "var(--text-muted)";+ const platformColor = logEntry.platform === "TikTok"+ ? "#ff0050"+ : logEntry.platform === "Instagram"+ ? "#E1306C"+ : "#FF0000";+ return `<div class="log-entry" style="color:${color}">+ <span style="opacity:0.5;">${escapeHtml(time)}</span>+ <span style="color:${platformColor}; font-weight:600; font-size:11px;">[${escapeHtml(logEntry.platform)}]</span>+ <span style="opacity:0.4; font-size:10px;">${escapeHtml(logEntry.profile || "")}</span>+ ${escapeHtml(logEntry.message || "")}+ </div>`;+ }).join("")+ : '<div style="text-align:center; padding:20px; color:#666;">No logs yet</div>';+ this.updateLogContainer(this.els.logsContainer, logsHtml);+ },+ renderStatus(data) {+ const pending = data.queue?.counts?.pending ?? 0;+ const posted = data.queue?.counts?.posted ?? 0;+ const failed = data.queue?.counts?.failed ?? 0;+ const pendingVideos = data.queue?.pendingVideos || [];+ const timezone = data.timezone || "UTC";+ const lastRunText = data.lastRunAt+ ? new Date(data.lastRunAt).toLocaleString()+ : "Never";+++ if (this.els.ttPendingCount) this.els.ttPendingCount.textContent = pending;+ if (this.els.ttPostedCount) this.els.ttPostedCount.textContent = posted;+ if (this.els.ttFailedCount) this.els.ttFailedCount.textContent = failed;+ if (this.els.ttSchedulerState) {+ this.els.ttSchedulerState.textContent = data.running ? "Running" : "Stopped";+ this.els.ttSchedulerState.classList.toggle("success", Boolean(data.running));+ this.els.ttSchedulerState.classList.toggle("error", !data.running);+ }++ // Sync instant-post toggle+ if (this.els.ttInstantPostToggle && document.activeElement !== this.els.ttInstantPostToggle) {+ this.els.ttInstantPostToggle.checked = Boolean(data.instantPost);+ }++ if (this.els.ttAutoAddSoundToggle && document.activeElement !== this.els.ttAutoAddSoundToggle) {+ this.els.ttAutoAddSoundToggle.checked = Boolean(data.autoAddSound);+ }++ if (this.els.ttSoundQueryInput && document.activeElement !== this.els.ttSoundQueryInput) {+ this.els.ttSoundQueryInput.value = data.defaultSoundQuery || "";+ }++ if (this.els.ttRandomQueueToggle && document.activeElement !== this.els.ttRandomQueueToggle) {+ this.els.ttRandomQueueToggle.checked = Boolean(data.randomQueueOrder);+ }++ const logHtml = (data.logs || [])+ .slice()+ .reverse()+ .map(+ (logEntry) => `+ <div class="log-entry">+ <span class="log-time">${logEntry.at.split("T")[1].split(".")[0]}</span>+ <span class="log-msg ${logEntry.level === "error" ? "log-error" : ""}">${escapeHtml(logEntry.message)}</span>+ </div>+ `+ )+ .join("");+ this.updateLogContainer(this.els.ttLogsContainer, logHtml);++ const queueHtml = pendingVideos.length+ ? pendingVideos+ .map((video) => {+ const videoName = typeof video === "string" ? video : video.name;+ const hasCaption = typeof video === "object" && video.hasCaption;+ return `+ <div class="queue-item">+ <div style="display:flex; align-items:center; gap:10px;">+ <i class="ph ph-file-video" style="font-size:20px;"></i>+ <span>${escapeHtml(videoName)}</span>+ ${hasCaption ? '<span class="status-badge" style="background:rgba(255,255,255,0.1); color:#ccc; border:1px solid #444; margin-left:8px;"><i class="ph ph-text-align-left"></i> Caption</span>' : ''}+ </div>+ <span class="status-badge active">Pending</span>+ </div>+ `;+ })+ .join("")+ : '<div style="text-align:center; padding:20px; color:#666;">Queue is empty</div>';+ if (this.els.ttQueueList) this.els.ttQueueList.innerHTML = queueHtml;++ if (+ this.els.ttCronInput &&+ document.activeElement !== this.els.ttCronInput &&+ !this.isScheduleDraftDirty("tiktok")+ ) {+ this.els.ttCronInput.value = data.cronExpression || "";+ }+ this.applySchedulePlanFromStatus("tiktok", data);++ if (this.els.ttTimezoneLabel) this.els.ttTimezoneLabel.textContent = timezone;+ if (this.els.ttLastRunLabel) this.els.ttLastRunLabel.textContent = lastRunText;+ if (this.els.defaultCaptionInput && document.activeElement !== this.els.defaultCaptionInput) {+ this.els.defaultCaptionInput.value = data.defaultCaption || "";+ }++ if (this.els.statusBadge) {+ const textEl = this.els.statusBadge.querySelector("span");+ const dot = this.els.statusBadge.querySelector(".connection-dot");+ const isPosting = Boolean(data.isPosting);+ const running = Boolean(data.running);+ if (textEl) {+ textEl.textContent = isPosting+ ? "Posting in progress"+ : running+ ? "Scheduler running"+ : "Scheduler stopped";+ }+ if (dot) {+ const color = isPosting+ ? "var(--status-warn)"+ : running+ ? "var(--status-good)"+ : "var(--status-bad)";+ dot.style.backgroundColor = color;+ dot.style.boxShadow = `0 0 8px ${color}`;+ }+ }+ },++ renderInstagramStatus(data) {+ const pending = data.queue?.counts?.pending ?? 0;+ const posted = data.queue?.counts?.posted ?? 0;+ const failed = data.queue?.counts?.failed ?? 0;+ const pendingVideos = data.queue?.pendingVideos || [];+ const timezone = data.timezone || "UTC";+ const lastRunText = data.lastRunAt ? new Date(data.lastRunAt).toLocaleString() : "Never";++ if (this.els.igPendingCount) this.els.igPendingCount.textContent = pending;+ if (this.els.igPostedCount) this.els.igPostedCount.textContent = posted;+ if (this.els.igFailedCount) this.els.igFailedCount.textContent = failed;+ if (this.els.igSchedulerState) {+ this.els.igSchedulerState.textContent = data.running ? "Running" : "Stopped";+ this.els.igSchedulerState.classList.toggle("success", Boolean(data.running));+ this.els.igSchedulerState.classList.toggle("error", !data.running);+ }++ // Sync instant-post toggle+ if (this.els.igInstantPostToggle && document.activeElement !== this.els.igInstantPostToggle) {+ this.els.igInstantPostToggle.checked = Boolean(data.instantPost);+ }++ if (this.els.igRandomQueueToggle && document.activeElement !== this.els.igRandomQueueToggle) {+ this.els.igRandomQueueToggle.checked = Boolean(data.randomQueueOrder);+ }++ const logsHtml = (data.logs || [])+ .slice()+ .reverse()+ .map(+ (logEntry) => `+ <div class="log-entry">+ <span class="log-time">${logEntry.at.split("T")[1].split(".")[0]}</span>+ <span class="log-msg ${logEntry.level === "error" ? "log-error" : ""}">${escapeHtml(logEntry.message)}</span>+ </div>+ `+ )+ .join("");+ this.updateLogContainer(this.els.igLogsContainer, logsHtml);++ const queueHtml = pendingVideos.length+ ? pendingVideos+ .map((video) => {+ const videoName = typeof video === "string" ? video : video.name;+ const hasCaption = typeof video === "object" && video.hasCaption;+ return `+ <div class="queue-item">+ <div style="display:flex; align-items:center; gap:10px;">+ <i class="ph ph-file-video" style="font-size:20px;"></i>+ <span>${escapeHtml(videoName)}</span>+ ${hasCaption ? '<span class="status-badge" style="background:rgba(255,255,255,0.1); color:#ccc; border:1px solid #444; margin-left:8px;"><i class="ph ph-text-align-left"></i> Caption</span>' : ''}+ </div>+ <span class="status-badge active">Pending</span>+ </div>+ `;+ })+ .join("")+ : '<div style="text-align:center; padding:20px; color:#666;">Queue is empty</div>';+ if (this.els.igQueueList) this.els.igQueueList.innerHTML = queueHtml;++ if (+ this.els.igCronInput &&+ document.activeElement !== this.els.igCronInput &&+ !this.isScheduleDraftDirty("instagram")+ ) {+ this.els.igCronInput.value = data.cronExpression || "";+ }+ this.applySchedulePlanFromStatus("instagram", data);+ if (this.els.igTimezoneLabel) this.els.igTimezoneLabel.textContent = timezone;+ if (this.els.igLastRunLabel) this.els.igLastRunLabel.textContent = lastRunText;+ },++ renderYouTubeStatus(data) {+ const pending = data.queue?.counts?.pending ?? 0;+ const posted = data.queue?.counts?.posted ?? 0;+ const failed = data.queue?.counts?.failed ?? 0;+ const pendingVideos = data.queue?.pendingVideos || [];+ const timezone = data.timezone || "UTC";+ const lastRunText = data.lastRunAt ? new Date(data.lastRunAt).toLocaleString() : "Never";++ if (this.els.ytPendingCount) this.els.ytPendingCount.textContent = pending;+ if (this.els.ytPostedCount) this.els.ytPostedCount.textContent = posted;+ if (this.els.ytFailedCount) this.els.ytFailedCount.textContent = failed;+ if (this.els.ytSchedulerState) {+ this.els.ytSchedulerState.textContent = data.running ? "Running" : "Stopped";+ this.els.ytSchedulerState.classList.toggle("success", Boolean(data.running));+ this.els.ytSchedulerState.classList.toggle("error", !data.running);+ }++ // Sync instant-post toggle+ if (this.els.ytInstantPostToggle && document.activeElement !== this.els.ytInstantPostToggle) {+ this.els.ytInstantPostToggle.checked = Boolean(data.instantPost);+ }++ if (this.els.ytRandomQueueToggle && document.activeElement !== this.els.ytRandomQueueToggle) {+ this.els.ytRandomQueueToggle.checked = Boolean(data.randomQueueOrder);+ }++ const logsHtml = (data.logs || [])+ .slice()+ .reverse()+ .map(+ (logEntry) => `+ <div class="log-entry">+ <span class="log-time">${logEntry.at.split("T")[1].split(".")[0]}</span>+ <span class="log-msg ${logEntry.level === "error" ? "log-error" : ""}">${escapeHtml(logEntry.message)}</span>+ </div>+ `+ )+ .join("");+ this.updateLogContainer(this.els.ytLogsContainer, logsHtml);++ const queueHtml = pendingVideos.length+ ? pendingVideos+ .map((video) => {+ const videoName = typeof video === "string" ? video : video.name;+ const hasCaption = typeof video === "object" && video.hasCaption;+ return `+ <div class="queue-item">+ <div style="display:flex; align-items:center; gap:10px;">+ <i class="ph ph-file-video" style="font-size:20px;"></i>+ <span>${escapeHtml(videoName)}</span>+ ${hasCaption ? '<span class="status-badge" style="background:rgba(255,255,255,0.1); color:#ccc; border:1px solid #444; margin-left:8px;"><i class="ph ph-text-align-left"></i> Caption</span>' : ''}+ </div>+ <span class="status-badge active">Pending</span>+ </div>+ `;+ })+ .join("")+ : '<div style="text-align:center; padding:20px; color:#666;">Queue is empty</div>';+ if (this.els.ytQueueList) this.els.ytQueueList.innerHTML = queueHtml;++ if (+ this.els.ytCronInput &&+ document.activeElement !== this.els.ytCronInput &&+ !this.isScheduleDraftDirty("youtube")+ ) {+ this.els.ytCronInput.value = data.cronExpression || "";+ }+ this.applySchedulePlanFromStatus("youtube", data);+ if (this.els.ytTimezoneLabel) this.els.ytTimezoneLabel.textContent = timezone;+ if (this.els.ytLastRunLabel) this.els.ytLastRunLabel.textContent = lastRunText;+ },++ renderUniquifierStatus(data) {+ if (!data) return;++ if (this.els.uniqInputDir && document.activeElement !== this.els.uniqInputDir) {+ this.els.uniqInputDir.value = data.inputDir || "";+ }+ if (this.els.uniqOutputDir && document.activeElement !== this.els.uniqOutputDir) {+ this.els.uniqOutputDir.value = data.outputDir || "";+ }+ if (this.els.uniqLogoImage && document.activeElement !== this.els.uniqLogoImage) {+ this.els.uniqLogoImage.value = data.logoImage || "";+ }++ if (this.els.uniqState) {+ this.els.uniqState.textContent = data.running ? "Running" : "Idle";+ this.els.uniqState.classList.toggle("success", Boolean(data.running));+ this.els.uniqState.classList.toggle("error", !data.running);+ }++ const processed = data.progress?.processed ?? 0;+ const total = data.progress?.total ?? 0;+ const succeeded = data.progress?.succeeded ?? 0;+ const failed = data.progress?.failed ?? 0;+ if (this.els.uniqProgress) this.els.uniqProgress.textContent = `${processed} / ${total}`;+ if (this.els.uniqSucceeded) this.els.uniqSucceeded.textContent = String(succeeded);+ if (this.els.uniqFailed) this.els.uniqFailed.textContent = String(failed);++ if (this.els.uniqStartBtn) this.els.uniqStartBtn.disabled = Boolean(data.running);+ if (this.els.uniqStopBtn) this.els.uniqStopBtn.disabled = !data.running;++ const inputFiles = data.inputFiles || [];+ const outputFiles = data.outputFiles || [];++ if (this.els.uniqInputFiles) {+ this.els.uniqInputFiles.innerHTML = inputFiles.length+ ? inputFiles+ .map(+ (fileName) => `+ <div class="queue-item">+ <div style="display:flex; align-items:center; gap:10px;">+ <i class="ph ph-file-video" style="font-size:20px;"></i>+ <span>${escapeHtml(fileName)}</span>+ </div>+ <span class="status-badge active">Input</span>+ </div>+ `+ )+ .join("")+ : '<div style="text-align:center; padding:20px; color:#666;">No videos in input folder</div>';+ }++ if (this.els.uniqOutputFiles) {+ this.els.uniqOutputFiles.innerHTML = outputFiles.length+ ? outputFiles+ .map(+ (fileName) => `+ <div class="queue-item">+ <div style="display:flex; align-items:center; gap:10px;">+ <i class="ph ph-file-video" style="font-size:20px;"></i>+ <span>${escapeHtml(fileName)}</span>+ </div>+ <span class="status-badge active">Output</span>+ </div>+ `+ )+ .join("")+ : '<div style="text-align:center; padding:20px; color:#666;">No videos in output folder</div>';+ }++ const logs = data.logs || [];+ if (this.els.uniqLogs) {+ this.els.uniqLogs.innerHTML = logs+ .slice()+ .reverse()+ .map(+ (logEntry) => `+ <div class="log-entry">+ <span class="log-time">${logEntry.at.split("T")[1].split(".")[0]}</span>+ <span class="log-msg ${logEntry.level === "error" ? "log-error" : ""}">${escapeHtml(logEntry.message)}</span>+ </div>+ `+ )+ .join("");+ }+ },++ renderAccounts() {+ const rows = [+ {+ platformKey: "tiktok",+ platform: "TikTok",+ icon: "ph-tiktok-logo",+ },+ {+ platformKey: "instagram",+ platform: "Instagram",+ icon: "ph-instagram-logo",+ },+ {+ platformKey: "youtube",+ platform: "YouTube",+ icon: "ph-youtube-logo",+ },+ ];++ const activeCount = rows.filter(+ (row) =>+ this.accountState[row.platformKey]?.loginOpen ||+ this.accountState[row.platformKey]?.sessionSaved+ ).length;+ if (this.els.activeAccountsCount) {+ this.els.activeAccountsCount.textContent = String(activeCount);+ }+ if (this.els.activeBrandLabel) {+ const suffix = this.accountState.activeBrandName+ ? `- ${this.accountState.activeBrandName}`+ : "";+ this.els.activeBrandLabel.textContent = suffix;+ }+ if (!this.els.accountsTableBody) return;++ this.els.accountsTableBody.innerHTML = rows+ .map(+ (row) => {+ const platformState = this.accountState[row.platformKey] || {};+ const sessionText = platformState.loginOpen+ ? "Open"+ : platformState.sessionSaved+ ? "Saved"+ : "Not connected";+ return `+ <tr>+ <td><div class="platform-cell"><span class="platform-icon"><i class="ph ${row.icon}"></i></span> ${row.platform}</div></td>+ <td>${sessionText}</td>+ <td><span class="status-badge ${platformState.schedulerRunning ? "active" : ""}">${platformState.schedulerRunning ? "Scheduler Running" : "Scheduler Stopped"}</span></td>+ <td>+ <button class="control-btn-small" data-platform="${row.platformKey}" data-action="login"><i class="ph ph-sign-in"></i> Login Session</button>+ <button class="control-btn-small danger" data-platform="${row.platformKey}" data-action="close"><i class="ph ph-x-circle"></i> Close Session</button>+ </td>+ </tr>+ `;+ }+ )+ .join("");+ },++ async handleAutoDownloadAction(endpoint) {+ try {+ const result = await API.post(endpoint);+ if (result?.ok === false && result?.error) alert(result.error);+ this.refresh();+ } catch (err) {+ alert(`Auto-download action failed: ${err.message}`);+ }+ },++ async handleAutoDownloadSave() {+ const platforms = [];+ if (this.els.adPlatTiktok?.checked) platforms.push("tiktok");+ if (this.els.adPlatInstagram?.checked) platforms.push("instagram");+ if (this.els.adPlatYoutube?.checked) platforms.push("youtube");++ try {+ await API.post("/api/autodownload/configure", {+ channel: this.els.adChannel?.value || '',+ interval: parseInt(this.els.adInterval?.value, 10) || 10,+ maxVideos: parseInt(this.els.adMaxVideos?.value, 10) || 5,+ platforms+ });+ if (this.els.adSaveSettingsBtn) {+ this.els.adSaveSettingsBtn.innerHTML = '<i class="ph ph-check"></i> Saved!';+ setTimeout(() => {+ this.els.adSaveSettingsBtn.innerHTML = '<i class="ph ph-floppy-disk"></i> Save Settings';+ }, 2000);+ }+ this.refresh();+ } catch (err) {+ alert(`Save failed: ${err.message}`);+ }+ },++ renderAutoDownloadStatus(data) {+ if (!data) return;++ if (this.els.adWatcherState) {+ this.els.adWatcherState.textContent = data.running ? "Running" : "Stopped";+ this.els.adWatcherState.classList.toggle("success", Boolean(data.running));+ this.els.adWatcherState.classList.toggle("error", !data.running);+ }+ if (this.els.adTotalDownloaded) {+ this.els.adTotalDownloaded.textContent = data.totalDownloaded ?? 0;+ }+ if (this.els.adLastCheck) {+ this.els.adLastCheck.textContent = data.lastCheckAt+ ? new Date(data.lastCheckAt).toLocaleTimeString()+ : "Never";+ }++ // Sync form fields only when user isn't focused+ if (this.els.adChannel && document.activeElement !== this.els.adChannel) {+ this.els.adChannel.value = data.channel || '';+ this.els.adInterval.value = data.interval || 10;+ this.els.adMaxVideos.value = data.maxVideos || 5;+ const platforms = data.platforms || [];+ if (this.els.adPlatTiktok) this.els.adPlatTiktok.checked = platforms.includes("tiktok");+ if (this.els.adPlatInstagram) this.els.adPlatInstagram.checked = platforms.includes("instagram");+ if (this.els.adPlatYoutube) this.els.adPlatYoutube.checked = platforms.includes("youtube");++ // Logs+ const logsHtml = (data.logs || [])+ .slice()+ .reverse()+ .map(+ (logEntry) => `+ <div class="log-entry">+ <span class="log-time">${logEntry.at.split("T")[1].split(".")[0]}</span>+ <span class="log-msg ${logEntry.level === "error" ? "log-error" : ""}">${escapeHtml(logEntry.message)}</span>+ </div>+ `+ )+ .join("");+ this.updateLogContainer(this.els.adLogsContainer, logsHtml);+ }+ },+++ async handleProfileDownloadStart(scanOnly = false) {+ try {+ const channel = this.els.pdChannel?.value?.trim();+ const maxVideos = parseInt(this.els.pdMaxVideos?.value, 10) || 0;+ const minViews = parseInt(this.els.pdMinViews?.value, 10) || 0;++ if (!channel) {+ alert("Please provide a valid TikTok channel URL or username.");+ return;+ }++ const result = await API.post("/api/profile-download/start", {+ channel,+ maxVideos,+ minViews,+ scanOnly+ });++ if (result?.ok === false && result?.error) alert(result.error);+ this.refresh();+ } catch (err) {+ alert(`Profile downloader failed to start: ${err.message}`);+ }+ },++ async handleProfileDownloadOpenFolder() {+ try {+ await API.post("/api/profile-download/open-folder");+ } catch (err) {+ alert(`Could not open profile downloads folder: ${err.message}`);+ }+ },++ renderProfileDownloadStatus(data) {+ if (!data) return;++ if (this.els.pdStatusBadge) {+ this.els.pdStatusBadge.textContent = data.running ? "Scraping" : "Idle";+ this.els.pdStatusBadge.classList.toggle("success", Boolean(data.running));+ this.els.pdStatusBadge.classList.toggle("error", !data.running);+ }+ if (this.els.pdStartBtn) {+ this.els.pdStartBtn.disabled = Boolean(data.running);+ }+ if (this.els.pdScanBtn) {+ this.els.pdScanBtn.disabled = Boolean(data.running);+ }++ const logsHtml = (data.logs || [])+ .slice()+ .reverse()+ .map(+ (logEntry) => `+ <div class="log-entry">+ <span class="log-time">${logEntry.at.split("T")[1].split(".")[0]}</span>+ <span class="log-msg ${logEntry.level === "error" ? "log-error" : ""}">${escapeHtml(logEntry.message)}</span>+ </div>+ `+ )+ .join("");+ this.updateLogContainer(this.els.pdLogsContainer, logsHtml);+ }+};++document.addEventListener("DOMContentLoaded", () => UI.init());diff --git a/web/index.html b/web/index.htmlnew file mode 100644index 0000000..613b6df--- /dev/null+++ b/web/index.html@@ -0,0 +1,760 @@+<!DOCTYPE html>+<html lang="en">++<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>AutoSocial Studio</title>+ <link rel="stylesheet" href="style.css" />+ <link+ href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap"+ rel="stylesheet">+ <!-- Using a CDN for icons for the premium look (Phosphor Icons or similar) -->+ <script src="https://unpkg.com/@phosphor-icons/web"></script>+</head>++<body>+ <div class="app-container">++ <!-- Sidebar -->+ <aside class="sidebar">+ <div class="brand">+ <div class="brand-icon">A</div>+ <div class="brand-meta">+ <h1>AutoSocial</h1>+ <div class="brand-account-switcher">+ <select id="brandSelect" class="control-input brand-select"></select>+ <button id="addBrandBtn" type="button" class="control-btn-small brand-add-btn" title="Add brand">+ <i class="ph ph-plus"></i>+ </button>+ </div>+ <div id="brandCreateRow" class="brand-create-row hidden">+ <input id="brandNameInput" type="text" class="control-input brand-name-input"+ placeholder="New brand name" />+ <button id="saveBrandBtn" type="button" class="control-btn-small primary brand-create-btn">+ Add+ </button>+ <button id="cancelBrandBtn" type="button" class="control-btn-small brand-create-btn">+ Cancel+ </button>+ </div>+ </div>+ </div>++ <nav class="nav-menu">+ <button class="nav-item active" data-view="overview">+ <i class="ph ph-squares-four"></i>+ <span>Overview</span>+ </button>++ <div class="nav-label">Auto Post</div>+ <button class="nav-item" data-view="tiktok">+ <i class="ph ph-tiktok-logo"></i>+ <span>TikTok</span>+ </button>+ <button class="nav-item" data-view="instagram">+ <i class="ph ph-instagram-logo"></i>+ <span>Instagram</span>+ </button>+ <button class="nav-item" data-view="youtube">+ <i class="ph ph-youtube-logo"></i>+ <span>YouTube</span>+ </button>++ <div class="nav-label">Tools</div>+ <button class="nav-item" data-view="uniquifier">+ <i class="ph ph-fingerprint"></i>+ <span>Video Uniquifier</span>+ </button>+ <button class="nav-item" data-view="autodownload">+ <i class="ph ph-download-simple"></i>+ <span>Auto Download</span>+ </button>+ <button class="nav-item" data-view="profile-download">+ <i class="ph ph-download"></i>+ <span>Profile Downloader</span>+ </button>++ <div class="nav-label">Management</div>+ <button class="nav-item" data-view="accounts">+ <i class="ph ph-users"></i>+ <span>Accounts</span>+ </button>+ <button class="nav-item" data-view="settings">+ <i class="ph ph-gear"></i>+ <span>Settings</span>+ </button>+ </nav>++ <div class="sidebar-footer">+ <div class="connection-status" id="statusBadge">+ <div class="connection-dot"></div>+ <span>System Ready</span>+ </div>+ </div>+ </aside>++ <!-- Main Content -->+ <main class="main-content">++ <!-- View: Overview -->+ <section id="view-overview" class="view-section active">+ <header class="view-header">+ <h2>Dashboard Overview</h2>+ </header>++ <!-- Totals Row -->+ <div style="display:grid; grid-template-columns:repeat(4, 1fr); gap:12px; margin-bottom:20px;">+ <div class="stat-card">+ <div class="stat-icon"><i class="ph ph-film-strip"></i></div>+ <div class="stat-value" id="pendingCount">0</div>+ <div class="stat-label">Total Pending</div>+ </div>+ <div class="stat-card">+ <div class="stat-icon success"><i class="ph ph-check-circle"></i></div>+ <div class="stat-value success" id="successCount">0</div>+ <div class="stat-label">Total Posted</div>+ </div>+ <div class="stat-card">+ <div class="stat-icon error"><i class="ph ph-warning-circle"></i></div>+ <div class="stat-value error" id="failedCount">0</div>+ <div class="stat-label">Total Failed</div>+ </div>+ <div class="stat-card">+ <div class="stat-icon"><i class="ph ph-users-three"></i></div>+ <div class="stat-value" id="activeAccountsCount">0</div>+ <div class="stat-label">Active Schedulers</div>+ </div>+ </div>++ <!-- Profiles container (JS populates per-profile sections) -->+ <div id="overviewProfilesContainer"></div>++ <!-- Recent Logs -->+ <div class="card full-width" style="margin-top:20px;">+ <div class="card-title">Live System Logs</div>+ <div class="logs-container" id="logsContainer">+ <!-- JS Populates this -->+ </div>+ </div>+ </section>++ <!-- View: Accounts -->+ <section id="view-accounts" class="view-section">+ <header class="view-header">+ <h2>Account Management <span id="activeBrandLabel" style="color:var(--text-muted); font-size:14px;"></span>+ </h2>+ </header>++ <div class="card">+ <table class="data-table">+ <thead>+ <tr>+ <th>Platform</th>+ <th>Session</th>+ <th>Status</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody id="accountsTableBody">+ <!-- JS Populates this -->+ </tbody>+ </table>+ </div>+ </section>++ <!-- View: TikTok -->+ <section id="view-tiktok" class="view-section">+ <header class="view-header">+ <div style="display:flex; align-items:center; gap:12px;">+ <div class="brand-icon"+ style="background:linear-gradient(135deg, #00f2ea, #ff0050); width:40px; height:40px; font-size:24px;"><i+ class="ph ph-tiktok-logo"></i></div>+ <div>+ <h2 style="margin:0;">TikTok Auto Post</h2>+ <span style="color:var(--text-muted); font-size:13px;">Manage your TikTok schedule and queue</span>+ </div>+ </div>+ <div style="display:flex; gap:8px; flex-wrap:wrap;">+ <button id="ttRunBtn" class="control-btn-small primary"><i class="ph ph-play"></i> Run Once</button>+ <button id="ttStartBtn" class="control-btn-small success"><i class="ph ph-play-circle"></i> Start</button>+ <button id="ttStopBtn" class="control-btn-small danger"><i class="ph ph-stop-circle"></i> Stop</button>+ </div>+ </header>++ <div class="dashboard-grid">+ <div class="stats-cards">+ <div class="stat-card">+ <div class="stat-value" id="ttPendingCount">-</div>+ <div class="stat-label">Pending TikToks</div>+ </div>+ <div class="stat-card">+ <div class="stat-value success" id="ttPostedCount">-</div>+ <div class="stat-label">Posted Total</div>+ </div>+ <div class="stat-card">+ <div class="stat-value error" id="ttFailedCount">-</div>+ <div class="stat-label">Failed Total</div>+ </div>+ <div class="stat-card">+ <div class="stat-value" id="ttSchedulerState">-</div>+ <div class="stat-label">Scheduler State</div>+ </div>+ </div>++ <div class="card full-width">+ <div class="card-title">TikTok Scheduler</div>+ <div class="input-group" style="margin-bottom:10px; flex-wrap:wrap;">+ <select id="ttPlanType" class="control-input" style="max-width:180px;">+ <option value="once">Once (run now)</option>+ <option value="daily" selected>Daily</option>+ <option value="dailyTimes">Daily at specific times</option>+ <option value="weekly">Weekly</option>+ <option value="every2h">Every 2 hours</option>+ <option value="every3h">Every 3 hours</option>+ <option value="every4h">Every 4 hours</option>+ <option value="every6h">Every 6 hours</option>+ <option value="every8h">Every 8 hours</option>+ <option value="every12h">Every 12 hours</option>+ <option value="custom">Custom Cron</option>+ </select>+ <input id="ttPlanTime" type="time" class="control-input" value="12:00" style="max-width:140px;">+ <input id="ttPlanTimes" type="text" class="control-input" placeholder="e.g. 09:30, 13:15, 20:45"+ style="display:none; min-width:260px;">+ <select id="ttPlanWeekday" class="control-input" style="max-width:160px; display:none;">+ <option value="1">Monday</option>+ <option value="2">Tuesday</option>+ <option value="3">Wednesday</option>+ <option value="4">Thursday</option>+ <option value="5">Friday</option>+ <option value="6">Saturday</option>+ <option value="0">Sunday</option>+ </select>+ <button id="ttPlanApplyBtn" class="control-btn-small primary">Apply</button>+ </div>+ <div class="input-group">+ <input type="text" id="ttCronInput" class="control-input" placeholder="0 */2 * * *">+ <button id="ttUpdateScheduleBtn" class="control-btn-small">Save Schedule</button>+ </div>+ <div+ style="display:flex; gap:18px; margin-top:12px; flex-wrap:wrap; color:var(--text-muted); font-size:13px;">+ <span>Timezone: <span id="ttTimezoneLabel" class="mono">UTC</span></span>+ <span>Last run: <span id="ttLastRunLabel" class="mono">Never</span></span>+ </div>+ <div+ style="display:flex; flex-direction:column; gap:16px; margin-top:16px; border-top:1px solid var(--border-color); padding-top:16px;">+ <label class="switch-container">+ <input type="checkbox" id="ttInstantPostToggle">+ <span class="slider"></span>+ <span class="switch-label">+ <strong>Instant Post Mode</strong>+ <div style="font-size:12px; color:var(--text-muted); font-weight:normal;">Skips queue intervals and+ Auto-Add Sound to post immediately when video appears in pending folder.</div>+ </span>+ </label>++ <label class="switch-container">+ <input type="checkbox" id="ttAutoAddSoundToggle">+ <span class="slider"></span>+ <span class="switch-label">+ <strong>Auto-Add Trending Sound</strong>+ <div style="font-size:12px; color:var(--text-muted); font-weight:normal;">Automatically searches and+ applies a background sound during upload to satisfy TikTok algorithm. (Ignored during Instant Post)+ </div>+ </span>+ </label>++ <div class="form-group">+ <label>Sound Search Query</label>+ <div class="input-group">+ <input id="ttSoundQueryInput" type="text" class="control-input"+ placeholder="Optional TikTok sound search term">+ <button id="ttSoundQuerySaveBtn" class="control-btn-small">+ Save Sound+ </button>+ </div>+ </div>++ <label class="switch-container">+ <input type="checkbox" id="ttRandomQueueToggle">+ <span class="slider"></span>+ <span class="switch-label">+ <strong>Random Queue Order (Global)</strong>+ <div style="font-size:12px; color:var(--text-muted); font-weight:normal;">Chooses a random pending video each run instead of the first file alphabetically. Captions still stay attached to the selected video.</div>+ </span>+ </label>+ </div>++ <div class="card full-width">+ <div class="card-title">TikTok Queue</div>+ <div class="queue-list" id="ttQueueList"></div>+ </div>++ <div class="card full-width">+ <div class="card-title">TikTok Live Logs</div>+ <div class="logs-container" id="ttLogsContainer"></div>+ </div>+ </div>+ </section>++ <!-- View: Instagram -->+ <section id="view-instagram" class="view-section">+ <header class="view-header">+ <div style="display:flex; align-items:center; gap:12px;">+ <div class="brand-icon"+ style="background:linear-gradient(135deg, #833ab4, #fd1d1d, #fcb045); width:40px; height:40px; font-size:24px;">+ <i class="ph ph-instagram-logo"></i>+ </div>+ <div>+ <h2 style="margin:0;">Instagram Reels</h2>+ <span style="color:var(--text-muted); font-size:13px;">Manage your Reels schedule</span>+ </div>+ </div>+ <div style="display:flex; gap:8px; flex-wrap:wrap;">+ <button id="igRunBtn" class="control-btn-small primary"><i class="ph ph-play"></i> Run Once</button>+ <button id="igStartBtn" class="control-btn-small success"><i class="ph ph-play-circle"></i> Start</button>+ <button id="igStopBtn" class="control-btn-small danger"><i class="ph ph-stop-circle"></i> Stop</button>+ </div>+ </header>++ <div class="dashboard-grid">+ <div class="stats-cards">+ <div class="stat-card">+ <div class="stat-value" id="igPendingCount">-</div>+ <div class="stat-label">Pending Reels</div>+ </div>+ <div class="stat-card">+ <div class="stat-value success" id="igPostedCount">-</div>+ <div class="stat-label">Posted Total</div>+ </div>+ <div class="stat-card">+ <div class="stat-value error" id="igFailedCount">-</div>+ <div class="stat-label">Failed Total</div>+ </div>+ <div class="stat-card">+ <div class="stat-value" id="igSchedulerState">-</div>+ <div class="stat-label">Scheduler State</div>+ </div>+ </div>++ <div class="card full-width">+ <div class="card-title">Instagram Scheduler</div>+ <div class="input-group" style="margin-bottom:10px; flex-wrap:wrap;">+ <select id="igPlanType" class="control-input" style="max-width:180px;">+ <option value="once">Once (run now)</option>+ <option value="daily" selected>Daily</option>+ <option value="dailyTimes">Daily at specific times</option>+ <option value="weekly">Weekly</option>+ <option value="every2h">Every 2 hours</option>+ <option value="every3h">Every 3 hours</option>+ <option value="every4h">Every 4 hours</option>+ <option value="every6h">Every 6 hours</option>+ <option value="every8h">Every 8 hours</option>+ <option value="every12h">Every 12 hours</option>+ <option value="custom">Custom Cron</option>+ </select>+ <input id="igPlanTime" type="time" class="control-input" value="12:00" style="max-width:140px;">+ <input id="igPlanTimes" type="text" class="control-input" placeholder="e.g. 09:30, 13:15, 20:45"+ style="display:none; min-width:260px;">+ <select id="igPlanWeekday" class="control-input" style="max-width:160px; display:none;">+ <option value="1">Monday</option>+ <option value="2">Tuesday</option>+ <option value="3">Wednesday</option>+ <option value="4">Thursday</option>+ <option value="5">Friday</option>+ <option value="6">Saturday</option>+ <option value="0">Sunday</option>+ </select>+ <button id="igPlanApplyBtn" class="control-btn-small primary">Apply</button>+ </div>+ <div class="input-group">+ <input type="text" id="igCronInput" class="control-input" placeholder="0 */2 * * *">+ <button id="igUpdateScheduleBtn" class="control-btn-small">Save Schedule</button>+ </div>+ <div+ style="display:flex; gap:18px; margin-top:12px; flex-wrap:wrap; color:var(--text-muted); font-size:13px;">+ <span>Timezone: <span id="igTimezoneLabel" class="mono">UTC</span></span>+ <span>Last run: <span id="igLastRunLabel" class="mono">Never</span></span>+ </div>+ <div+ style="display:flex; align-items:center; gap:12px; margin-top:16px; padding-top:14px; border-top:1px solid var(--border-color);">+ <label class="toggle-switch">+ <input type="checkbox" id="igInstantPostToggle">+ <span class="toggle-slider"></span>+ </label>+ <div>+ <div style="font-weight:600; font-size:13px;">Instant Post</div>+ <div style="color:var(--text-muted); font-size:12px;">Post immediately when a new file lands in the+ queue</div>+ </div>+ </div>+ <div style="display:flex; align-items:center; gap:12px; margin-top:12px;">+ <label class="toggle-switch">+ <input type="checkbox" id="igRandomQueueToggle">+ <span class="toggle-slider"></span>+ </label>+ <div>+ <div style="font-weight:600; font-size:13px;">Random Queue Order (Global)</div>+ <div style="color:var(--text-muted); font-size:12px;">Pick a random pending file each run instead of the first alphabetic one. Captions still follow the chosen video.</div>+ </div>+ </div>+ </div>++ <div class="card full-width">+ <div class="card-title">Instagram Queue</div>+ <div class="queue-list" id="igQueueList"></div>+ </div>++ <div class="card full-width">+ <div class="card-title">Instagram Live Logs</div>+ <div class="logs-container" id="igLogsContainer"></div>+ </div>+ </div>+ </section>++ <!-- View: YouTube -->+ <section id="view-youtube" class="view-section">+ <header class="view-header">+ <div style="display:flex; align-items:center; gap:12px;">+ <div class="brand-icon" style="background:#ff0000; width:40px; height:40px; font-size:24px;"><i+ class="ph ph-youtube-logo"></i></div>+ <div>+ <h2 style="margin:0;">YouTube Shorts</h2>+ <span style="color:var(--text-muted); font-size:13px;">Manage your Shorts schedule</span>+ </div>+ </div>+ <div style="display:flex; gap:8px; flex-wrap:wrap;">+ <button id="ytRunBtn" class="control-btn-small primary"><i class="ph ph-play"></i> Run Once</button>+ <button id="ytStartBtn" class="control-btn-small success"><i class="ph ph-play-circle"></i> Start</button>+ <button id="ytStopBtn" class="control-btn-small danger"><i class="ph ph-stop-circle"></i> Stop</button>+ </div>+ </header>++ <div class="dashboard-grid">+ <div class="stats-cards">+ <div class="stat-card">+ <div class="stat-value" id="ytPendingCount">-</div>+ <div class="stat-label">Pending Shorts</div>+ </div>+ <div class="stat-card">+ <div class="stat-value success" id="ytPostedCount">-</div>+ <div class="stat-label">Posted Total</div>+ </div>+ <div class="stat-card">+ <div class="stat-value error" id="ytFailedCount">-</div>+ <div class="stat-label">Failed Total</div>+ </div>+ <div class="stat-card">+ <div class="stat-value" id="ytSchedulerState">-</div>+ <div class="stat-label">Scheduler State</div>+ </div>+ </div>++ <div class="card full-width">+ <div class="card-title">YouTube Scheduler</div>+ <div class="input-group" style="margin-bottom:10px; flex-wrap:wrap;">+ <select id="ytPlanType" class="control-input" style="max-width:180px;">+ <option value="once">Once (run now)</option>+ <option value="daily" selected>Daily</option>+ <option value="dailyTimes">Daily at specific times</option>+ <option value="weekly">Weekly</option>+ <option value="every2h">Every 2 hours</option>+ <option value="every3h">Every 3 hours</option>+ <option value="every4h">Every 4 hours</option>+ <option value="every6h">Every 6 hours</option>+ <option value="every8h">Every 8 hours</option>+ <option value="every12h">Every 12 hours</option>+ <option value="custom">Custom Cron</option>+ </select>+ <input id="ytPlanTime" type="time" class="control-input" value="12:00" style="max-width:140px;">+ <input id="ytPlanTimes" type="text" class="control-input" placeholder="e.g. 09:30, 13:15, 20:45"+ style="display:none; min-width:260px;">+ <select id="ytPlanWeekday" class="control-input" style="max-width:160px; display:none;">+ <option value="1">Monday</option>+ <option value="2">Tuesday</option>+ <option value="3">Wednesday</option>+ <option value="4">Thursday</option>+ <option value="5">Friday</option>+ <option value="6">Saturday</option>+ <option value="0">Sunday</option>+ </select>+ <button id="ytPlanApplyBtn" class="control-btn-small primary">Apply</button>+ </div>+ <div class="input-group">+ <input type="text" id="ytCronInput" class="control-input" placeholder="0 */2 * * *">+ <button id="ytUpdateScheduleBtn" class="control-btn-small">Save Schedule</button>+ </div>+ <div+ style="display:flex; gap:18px; margin-top:12px; flex-wrap:wrap; color:var(--text-muted); font-size:13px;">+ <span>Timezone: <span id="ytTimezoneLabel" class="mono">UTC</span></span>+ <span>Last run: <span id="ytLastRunLabel" class="mono">Never</span></span>+ </div>+ <div+ style="display:flex; align-items:center; gap:12px; margin-top:16px; padding-top:14px; border-top:1px solid var(--border-color);">+ <label class="toggle-switch">+ <input type="checkbox" id="ytInstantPostToggle">+ <span class="toggle-slider"></span>+ </label>+ <div>+ <div style="font-weight:600; font-size:13px;">Instant Post</div>+ <div style="color:var(--text-muted); font-size:12px;">Post immediately when a new file lands in the+ queue</div>+ </div>+ </div>+ <div style="display:flex; align-items:center; gap:12px; margin-top:12px;">+ <label class="toggle-switch">+ <input type="checkbox" id="ytRandomQueueToggle">+ <span class="toggle-slider"></span>+ </label>+ <div>+ <div style="font-weight:600; font-size:13px;">Random Queue Order (Global)</div>+ <div style="color:var(--text-muted); font-size:12px;">Pick a random pending file each run instead of the first alphabetic one. Captions still follow the chosen video.</div>+ </div>+ </div>+ </div>++ <div class="card full-width">+ <div class="card-title">YouTube Queue</div>+ <div class="queue-list" id="ytQueueList"></div>+ </div>++ <div class="card full-width">+ <div class="card-title">YouTube Live Logs</div>+ <div class="logs-container" id="ytLogsContainer"></div>+ </div>+ </div>+ </section>++ <!-- View: Video Uniquifier -->+ <section id="view-uniquifier" class="view-section">+ <header class="view-header">+ <h2>Video Uniquifier</h2>+ <div style="display:flex; gap:8px; flex-wrap:wrap;">+ <button id="uniqStartBtn" class="control-btn-small success">+ <i class="ph ph-play-circle"></i> Start Uniquifying+ </button>+ <button id="uniqStopBtn" class="control-btn-small danger">+ <i class="ph ph-stop-circle"></i> Stop+ </button>+ </div>+ </header>++ <div class="dashboard-grid">+ <div class="card full-width">+ <div class="card-title">Folders</div>+ <div class="form-group">+ <label>Input Folder (put original videos here)</label>+ <div class="input-group">+ <input id="uniqInputDir" class="control-input" type="text" placeholder="Input folder path">+ <button id="uniqOpenInputBtn" class="control-btn-small">+ <i class="ph ph-folder-open"></i> Open+ </button>+ </div>+ </div>+ <div class="form-group" style="margin-top:12px;">+ <label>Output Folder (uniquified videos will be saved here)</label>+ <div class="input-group">+ <input id="uniqOutputDir" class="control-input" type="text" placeholder="Output folder path">+ <button id="uniqOpenOutputBtn" class="control-btn-small">+ <i class="ph ph-folder-open"></i> Open+ </button>+ </div>+ </div>+ <div class="form-group" style="margin-top:12px;">+ <label>Logo Image (optional overlay)</label>+ <input id="uniqLogoImage" class="control-input" type="text"+ placeholder="user-assets/logo.png or C:\path\to\logo.png">+ </div>+ </div>++ <div class="stats-cards">+ <div class="stat-card">+ <div class="stat-value" id="uniqState">-</div>+ <div class="stat-label">Batch State</div>+ </div>+ <div class="stat-card">+ <div class="stat-value" id="uniqProgress">0 / 0</div>+ <div class="stat-label">Progress</div>+ </div>+ <div class="stat-card">+ <div class="stat-value success" id="uniqSucceeded">0</div>+ <div class="stat-label">Succeeded</div>+ </div>+ <div class="stat-card">+ <div class="stat-value error" id="uniqFailed">0</div>+ <div class="stat-label">Failed</div>+ </div>+ </div>++ <div class="card full-width">+ <div class="card-title">Input Videos</div>+ <div class="queue-list" id="uniqInputFiles"></div>+ </div>++ <div class="card full-width">+ <div class="card-title">Output Videos</div>+ <div class="queue-list" id="uniqOutputFiles"></div>+ </div>++ <div class="card full-width">+ <div class="card-title">Uniquifier Logs</div>+ <div class="logs-container" id="uniqLogs"></div>+ </div>+ </div>+ </section>++ <!-- View: Settings -->+ <section id="view-settings" class="view-section">+ <header class="view-header">+ <h2>Settings</h2>+ </header>++ <div class="settings-grid">+ <div class="card">+ <div class="card-title">Content Defaults</div>+ <div class="form-group">+ <label>Default Caption</label>+ <textarea id="defaultCaptionInput" class="control-input" rows="4"+ placeholder="Optional fallback caption when no sidecar file exists"></textarea>+ </div>+ <button id="defaultCaptionSaveBtn" class="control-btn-small primary" style="margin-top:8px;">+ <i class="ph ph-floppy-disk"></i> Save Caption+ </button>+ </div>+ </div>+ </section>++ <!-- View: Auto Download -->+ <section id="view-autodownload" class="view-section">+ <header class="view-header">+ <div style="display:flex; align-items:center; gap:12px;">+ <div class="brand-icon"+ style="background:linear-gradient(135deg, #6366f1, #a855f7); width:40px; height:40px; font-size:24px;"><i+ class="ph ph-download-simple"></i></div>+ <div>+ <h2 style="margin:0;">Auto Download</h2>+ <span style="color:var(--text-muted); font-size:13px;">Watch a TikTok channel and auto-queue new+ videos</span>+ </div>+ </div>+ <div style="display:flex; gap:8px;">+ <button id="adStartBtn" class="control-btn-small success"><i class="ph ph-play-circle"></i> Start</button>+ <button id="adStopBtn" class="control-btn-small danger"><i class="ph ph-stop-circle"></i> Stop</button>+ </div>+ </header>++ <div class="dashboard-grid">+ <div class="stats-cards">+ <div class="stat-card">+ <div class="stat-value" id="adWatcherState">-</div>+ <div class="stat-label">Watcher State</div>+ </div>+ <div class="stat-card">+ <div class="stat-value" id="adTotalDownloaded">0</div>+ <div class="stat-label">Videos Downloaded</div>+ </div>+ <div class="stat-card">+ <div class="stat-value" id="adLastCheck">Never</div>+ <div class="stat-label">Last Checked</div>+ </div>+ </div>++ <div class="card full-width">+ <div class="card-title">Download Settings</div>+ <div style="display:grid; grid-template-columns:1fr 1fr; gap:16px;">+ <div class="form-group">+ <label>TikTok Channel / Username</label>+ <input type="text" id="adChannel" class="control-input" placeholder="@username or full URL">+ </div>+ <div class="form-group">+ <label>Check Interval (minutes)</label>+ <input type="number" id="adInterval" class="control-input" min="1" value="10">+ </div>+ <div class="form-group">+ <label>Max Videos Per Check</label>+ <input type="number" id="adMaxVideos" class="control-input" min="1" value="5">+ </div>+ <div class="form-group">+ <label>Post To Platforms</label>+ <div style="display:flex; gap:12px; align-items:center; padding-top:6px;">+ <label style="display:flex; align-items:center; gap:6px; font-size:13px; cursor:pointer;">+ <input type="checkbox" id="adPlatTiktok" value="tiktok" checked> TikTok+ </label>+ <label style="display:flex; align-items:center; gap:6px; font-size:13px; cursor:pointer;">+ <input type="checkbox" id="adPlatInstagram" value="instagram"> Instagram+ </label>+ <label style="display:flex; align-items:center; gap:6px; font-size:13px; cursor:pointer;">+ <input type="checkbox" id="adPlatYoutube" value="youtube"> YouTube+ </label>+ </div>+ </div>+ </div>+ <button id="adSaveSettingsBtn" class="control-btn-small primary" style="margin-top:8px;"><i+ class="ph ph-floppy-disk"></i> Save Settings</button>+ </div>++ <div class="card full-width">+ <div class="card-title">Download Live Logs</div>+ <div class="logs-container" id="adLogsContainer" style="height:320px;"></div>+ </div>+ </div>+ </section>++ <!-- Profile downloader view -->+ <section id="view-profile-download" class="view-section">+ <div class="view-header">+ <h1>Profile Downloader</h1>+ <p>Scrape specific TikTok channels and filter by view count. Videos will be saved to <code+ style="padding: 2px 4px; background: rgba(255,255,255,0.1); border-radius: 4px;">autodownload/profile_downloads/</code>.+ </p>+ </div>++ <div class="card" style="margin-bottom: 24px;">+ <h2 class="card-title"><i class="ph ph-sliders"></i> Configuration</h2>+ <div class="settings-grid">+ <div class="form-group">+ <label>TikTok Channel</label>+ <input type="text" id="pdChannel" class="control-input" placeholder="e.g. @username">+ </div>+ <div class="form-group">+ <label>Max Videos to Scan</label>+ <input type="number" id="pdMaxVideos" class="control-input" min="0" placeholder="0 = All Videos"+ value="0">+ </div>+ <div class="form-group">+ <label>Min Views Filter</label>+ <input type="number" id="pdMinViews" class="control-input" min="0" placeholder="0 = No filter"+ value="0">+ </div>+ </div>+ <div style="margin-top:20px; display:flex; gap:12px;">+ <button id="pdStartBtn" class="control-btn primary">+ <i class="ph ph-play"></i> Start Scraping+ </button>+ <button id="pdScanBtn" class="control-btn neutral" style="border: 1px solid var(--border-color);">+ <i class="ph ph-magnifying-glass"></i> Check Videos+ </button>+ <button id="pdOpenFolderBtn" class="control-btn neutral">+ <i class="ph ph-folder-open"></i> Open Downloads+ </button>+ </div>+ </div>++ <div class="two-col-layout">+ <!-- Live Logs -->+ <div class="card" style="grid-column: 1 / -1;">+ <div class="card-header">+ <h2 class="card-title">Live Logs</h2>+ <span id="pdStatusBadge" class="status-badge">Idle</span>+ </div>+ <div class="logs-container" id="pdLogsContainer">+ </div>+ </div>+ </div>+ </section>+ </main>+ </div>+ <script src="app.js"></script>+</body>++</html>diff --git a/web/style.css b/web/style.cssnew file mode 100644index 0000000..adaab72--- /dev/null+++ b/web/style.css@@ -0,0 +1,687 @@+:root {+ --bg-app: #09090b;+ /* Zinc 950 */+ --bg-sidebar: #101012;+ /* Slightly lighter than app bg */+ --bg-card: #18181b;+ /* Zinc 900 */+ --bg-card-hover: #27272a;+ /* Zinc 800 */+ --border-color: #27272a;++ --primary: #3b82f6;+ /* Blue 500 */+ --primary-hover: #2563eb;+ /* Blue 600 */++ --text-main: #f4f4f5;+ /* Zinc 100 */+ --text-muted: #a1a1aa;+ /* Zinc 400 */++ --status-good: #10b981;+ /* Emerald 500 */+ --status-good-bg: rgba(16, 185, 129, 0.1);+ --status-bad: #ef4444;+ /* Red 500 */+ --status-bad-bg: rgba(239, 68, 68, 0.1);+ --status-warn: #f59e0b;+ /* Amber 500 */+ --status-warn-bg: rgba(245, 158, 11, 0.1);++ --font-sans: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;+ --font-mono: "JetBrains Mono", "Fira Code", monospace;++ --sidebar-width: 292px;+}++* {+ box-sizing: border-box;+}++body {+ margin: 0;+ background-color: var(--bg-app);+ color: var(--text-main);+ font-family: var(--font-sans);+ -webkit-font-smoothing: antialiased;+ height: 100vh;+ overflow: hidden;+ /* App container handles scroll */+}++.app-container {+ display: flex;+ height: 100%;+}++/* Sidebar */+.sidebar {+ width: var(--sidebar-width);+ background: var(--bg-sidebar);+ border-right: 1px solid var(--border-color);+ display: flex;+ flex-direction: column;+ padding: 24px 12px;+}++.brand {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ margin-bottom: 28px;+ padding: 0 4px;+ overflow: visible;+}++.brand h1 {+ margin: 0;+ font-size: 20px;+ font-weight: 700;+ letter-spacing: -0.02em;+ color: white;+}++.brand-meta {+ display: flex;+ flex-direction: column;+ gap: 10px;+ min-width: 0;+ flex: 1;+}++.brand-account-switcher {+ display: flex;+ align-items: center;+ gap: 4px;+ width: 100%;+}++.brand-account-switcher .brand-select {+ flex: 1;+ min-width: 0;+}++select.brand-select {+ height: 34px;+ font-size: 13px;+ padding: 4px 8px;+ line-height: normal;+}++.brand-add-btn {+ height: 30px;+ width: 30px;+ justify-content: center;+ padding: 0;+ flex: 0 0 auto;+}++.brand-create-row {+ display: flex;+ align-items: center;+ gap: 6px;+ width: 100%;+}++.brand-create-row.hidden {+ display: none;+}++.brand-name-input {+ height: 34px;+ font-size: 12px;+ padding: 6px 8px;+ flex: 1;+ min-width: 0;+}++.brand-create-btn {+ height: 34px;+ padding: 0 10px;+ font-size: 11px;+ flex: 0 0 auto;+}++.brand-icon {+ width: 32px;+ height: 32px;+ background: linear-gradient(135deg, #00f2ea, #ff0050);+ border-radius: 8px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-weight: 900;+ color: white;+ font-size: 18px;+ flex: 0 0 auto;+}++.nav-menu {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 4px;+}++.nav-item {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 10px 12px;+ border-radius: 8px;+ color: var(--text-muted);+ font-weight: 500;+ font-size: 14px;+ text-align: left;+ border: none;+ background: transparent;+ cursor: pointer;+ transition: all 0.2s;+}++.nav-item i {+ font-size: 18px;+}++.nav-item:hover {+ background: var(--bg-card-hover);+ color: var(--text-main);+}++.nav-item.active {+ background: var(--bg-card-hover);+ color: var(--text-main);+ box-shadow: inset 2px 0 0 0 var(--primary);+ /* Left accent border */+}++.nav-label {+ color: var(--text-muted);+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ font-weight: 700;+ margin-top: 16px;+ margin-bottom: 4px;+ padding-left: 12px;+}++.sidebar-footer {+ margin-top: auto;+ border-top: 1px solid var(--border-color);+ padding-top: 16px;+}++/* Main Content */+.main-content {+ flex: 1;+ overflow-y: auto;+ padding: 32px 40px;+ background: var(--bg-app);+}++/* Views */+.view-section {+ display: none;+ animation: fadeIn 0.3s ease;+}++.view-section.active {+ display: block;+}++@keyframes fadeIn {+ from {+ opacity: 0;+ transform: translateY(5px);+ }++ to {+ opacity: 1;+ transform: translateY(0);+ }+}++.view-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 32px;+}++.view-header h2 {+ font-size: 24px;+ font-weight: 600;+ margin: 0;+}++/* Dashboard Grid & Cards */+.dashboard-grid {+ display: grid;+ grid-template-columns: repeat(12, 1fr);+ gap: 24px;+}++.card {+ background: var(--bg-card);+ border: 1px solid var(--border-color);+ border-radius: 12px;+ padding: 24px;+}++.full-width {+ grid-column: span 12;+}++.stats-cards {+ grid-column: span 12;+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: 24px;+ margin-bottom: 24px;+}++.stat-card {+ background: var(--bg-card);+ border: 1px solid var(--border-color);+ border-radius: 12px;+ padding: 20px;+ display: flex;+ flex-direction: column;+}++.stat-icon {+ width: 36px;+ height: 36px;+ border-radius: 8px;+ background: var(--bg-card-hover);+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--text-muted);+ font-size: 18px;+ margin-bottom: 12px;+}++.stat-icon.success {+ color: var(--status-good);+ background: var(--status-good-bg);+}++.stat-icon.error {+ color: var(--status-bad);+ background: var(--status-bad-bg);+}++.stat-value {+ font-size: 28px;+ font-weight: 700;+ color: var(--text-main);+ margin-bottom: 4px;+}++.stat-value.success {+ color: var(--status-good);+}++.stat-value.error {+ color: var(--status-bad);+}++.stat-label {+ font-size: 13px;+ color: var(--text-muted);+}++/* Tables (Accounts View) */+.data-table {+ width: 100%;+ border-collapse: collapse;+}++.data-table th,+.data-table td {+ padding: 14px;+ text-align: left;+ border-bottom: 1px solid var(--border-color);+}++.data-table th {+ color: var(--text-muted);+ font-size: 12px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ font-weight: 600;+}++.data-table td {+ font-size: 14px;+}++.data-table tr:last-child td {+ border-bottom: none;+}++.platform-cell {+ display: flex;+ align-items: center;+ gap: 10px;+}++.platform-icon {+ font-size: 18px;+}++.proxy-cell {+ font-family: var(--font-mono);+ font-size: 12px;+ color: var(--text-muted);+}++.status-badge {+ display: inline-block;+ padding: 4px 8px;+ border-radius: 6px;+ font-size: 11px;+ font-weight: 600;+}++.status-badge.active {+ background: var(--status-good-bg);+ color: var(--status-good);+}++.status-badge.locked {+ background: var(--status-warn-bg);+ color: var(--status-warn);+}++.status-badge.error {+ background: var(--status-bad-bg);+ color: var(--status-bad);+}++/* Forms */+.form-group {+ margin-bottom: 16px;+}++.form-group label {+ display: block;+ font-size: 13px;+ margin-bottom: 6px;+ color: var(--text-muted);+}++.control-input {+ width: 100%;+ background: var(--bg-app);+ border: 1px solid var(--border-color);+ border-radius: 8px;+ padding: 10px;+ color: var(--text-main);+ font-family: inherit;+ font-size: 14px;+ outline: none;+}++.control-input:focus {+ border-color: var(--primary);+}++textarea.control-input {+ resize: vertical;+}++/* Buttons */+.control-btn {+ padding: 12px 20px;+ border-radius: 8px;+ border: none;+ font-weight: 600;+ cursor: pointer;+}++.control-btn.primary {+ background: var(--primary);+ color: white;+}++.control-btn.primary:hover {+ background: var(--primary-hover);+}++.control-btn.large-btn {+ width: 100%;+ display: flex;+ justify-content: center;+ align-items: center;+ gap: 8px;+}++.control-btn-small {+ background: var(--bg-card-hover);+ border: 1px solid var(--border-color);+ color: var(--text-main);+ padding: 8px 12px;+ border-radius: 6px;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ gap: 6px;+}++.control-btn-small:hover {+ border-color: var(--text-muted);+}++.control-btn-small.primary {+ background: var(--primary);+ border: none;+ color: white;+}++.control-btn-small.success {+ background: var(--status-good);+ border: none;+ color: white;+}++.control-btn-small.danger {+ background: var(--status-bad);+ border: none;+ color: white;+}++.control-btn-small:disabled,+.control-btn:disabled {+ opacity: 0.6;+ cursor: not-allowed;+}++.input-group {+ display: flex;+ gap: 8px;+ align-items: center;+}++.input-group .control-input {+ flex: 1;+}++.mono {+ font-family: var(--font-mono);+}++/* Status Indicator (Sidebar) */+.connection-status {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ font-size: 12px;+ font-weight: 500;+ padding: 8px;+ border-radius: 8px;+ background: rgba(255, 255, 255, 0.05);+ color: var(--text-muted);+}++.connection-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background-color: var(--status-good);+ box-shadow: 0 0 8px var(--status-good);+}++/* Queue List Items */+.queue-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.queue-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 12px;+ background: var(--bg-app);+ border-radius: 8px;+}++.queue-meta {+ font-size: 12px;+ color: var(--text-muted);+ margin-left: 8px;+}++/* Logs */+.logs-container {+ height: 200px;+ overflow-y: auto;+ font-family: var(--font-mono);+ font-size: 12px;+ background: #000;+ padding: 12px;+ border-radius: 8px;+}++.log-entry {+ margin-bottom: 4px;+ display: flex;+ gap: 8px;+}++.log-time {+ color: #555;+ min-width: 120px;+}++.log-msg {+ color: #aaa;+}++.log-error {+ color: var(--status-bad);+}++/* Toggle Switch */+.toggle-switch {+ position: relative;+ display: inline-block;+ width: 44px;+ height: 24px;+ flex-shrink: 0;+}++.toggle-switch input {+ opacity: 0;+ width: 0;+ height: 0;+}++.toggle-slider {+ position: absolute;+ cursor: pointer;+ inset: 0;+ background: var(--bg-card-hover);+ border: 1px solid var(--border-color);+ border-radius: 24px;+ transition: all 0.3s;+}++.toggle-slider::before {+ content: "";+ position: absolute;+ height: 18px;+ width: 18px;+ left: 2px;+ bottom: 2px;+ background: var(--text-muted);+ border-radius: 50%;+ transition: all 0.3s;+}++.toggle-switch input:checked+.toggle-slider {+ background: var(--primary);+ border-color: var(--primary);+}++.toggle-switch input:checked+.toggle-slider::before {+ transform: translateX(20px);+ background: white;+}++/* Responsive */+@media (max-width: 900px) {+ .app-container {+ flex-direction: column;+ overflow: auto;+ }++ .sidebar {+ width: 100%;+ flex-direction: row;+ align-items: center;+ padding: 12px;+ height: auto;+ }++ .nav-menu {+ flex-direction: row;+ overflow-x: auto;+ }++ .brand {+ margin-bottom: 0;+ margin-right: 24px;+ }++ .sidebar-footer {+ display: none;+ }++ .main-content {+ padding: 20px;+ }+}++/* Form Group */+.form-group {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.form-group label {+ font-size: 12px;+ font-weight: 600;+ color: var(--text-muted);+ text-transform: uppercase;+ letter-spacing: 0.4px;+}