Files
Proxer-Downloader/README.md
T
2026-10-23 18:19:44 +02:00

147 lines
15 KiB
Markdown
Executable File

# Proxer-Downloader
Express/EJS submission and status pages, a MongoDB episode queue, Node workers managed by PM2, and Python download entrypoints.
## Phase 2: dashboard, worker activity, and reusable session tokens
The interface has a responsive top bar, a default Dashboard, active-download cards per worker, a searchable paginated queue with state-specific clearing controls, and numbered quick-add workers. Series submissions include a separate Season field and an exact filename preview. A supplied token is saved in MongoDB after a successful download-access check and checked again on every new submission. See the [refinement guide and verification report](docs/phase-2-refinements.md).
The user confirmed successful series and single-episode workflows with the first Phase 2 UI, after previously confirming that the verification pause retained and retried the affected episode and completed the queue. These refinements preserve that execution behavior and every original file in `scripts/lib/`. Worker identity is diagnostic metadata; durable ownership, recovery, shared execution modules, and enforced bandwidth controls remain in the [later rollout phases](docs/rollout-roadmap.md).
The current worker records success only when Python exits with code 0, emits exactly one valid completed result, and produces a nonempty regular output file. This is a completion contract, not full media-integrity verification. The protected stream library still writes directly to the target file and cannot resume a partial transfer.
## Runtime and configuration
- Node.js **20.19.0 or later**, matching the locked MongoDB driver's minimum requirement.
- A Python environment with the existing dependencies in `scripts/requirements.txt`. Keep the working stream dependency versions for this rollout; validate them against the target interpreter before deployment.
- MongoDB accessible to the application and workers.
- PM2 on the download account's `PATH` when using the worker-management page.
- An existing writable output directory, normally `/mnt/media/WIP`, accessible to the download account through its `plex` group or the existing ACL.
The application can live under `/home/<download_user>/Proxer-Downloader/` or another chosen checkout path. Worker script paths are resolved from the checkout; there is no account name embedded in the browser or server code.
Install the locked Node dependencies, copy `.env.example` to `.env`, and replace the example settings with the working deployment values. Do not overwrite an existing production `.env` with the example.
```sh
npm ci --ignore-scripts
```
| Variable | Meaning | Default |
|---|---|---|
| `MONGO_URI` | Private connection string | Required when connecting |
| `MONGO_DB` | Database used by both web and workers | `downloads` |
| `OUTPUT_DIR` | Existing media output directory | `/mnt/media/WIP` |
| `VENV_PYTHON` | Python executable; use the absolute virtual-environment path in production | `python3` |
| `TOKEN_PREFIX` | Existing cookie name followed by `=` | Required for submission |
| `MAX_SERIES_EPISODES` | Maximum episodes in one submission, from 1 to 10000 | `500` |
| `HOST` | Web listener address; the example uses loopback for a reverse proxy | `0.0.0.0` |
| `PORT` | Web listener port | `3000` |
Configuration is loaded from the checkout's `.env`, independently of the caller's working directory. The web form accepts the cookie **value**; the server prepends `TOKEN_PREFIX`. The example cookie name is a placeholder: retain the name from the working configuration. No live token belongs in source control.
Run PM2 and the application as the download account. Group access to media is separate from administrative network privileges. Preserve the deployment's existing reverse-proxy/firewall access boundary; this phase does not add application login or multi-user authorization. See [Debian 13 deployment and bandwidth assessment](docs/debian-13-deployment.md).
## Verification
```sh
npm run check:protected
npm test
```
The test runner checks the entire protected directory before and after all suites. It uses a temporary workspace and removes it afterward. Node tests use fake databases/processes and local fixtures; subprocess integration tests use copied CLI files with a synthetic stream module. Python tests use the standard library and disable bytecode generation. No test connects to production MongoDB or downloads media.
Set `TEST_PYTHON` to an absolute interpreter path when the test interpreter should differ from `python3`. The protected check covers all seven original files, their executable flags, exact directory entries, additions, deletions, and symlinks. The frozen baseline must not be regenerated to hide an unexpected change.
The current refinement run passed **258 tests** (214 Node and 44 Python), plus **42 browser checks**. The [current refinement report](docs/phase-2-refinements.md) records the expanded verification and deployment scope; the [initial UI report](docs/phase-2-ui.md) and [Phase 1 report](docs/phase-1-verification.md) preserve their earlier baselines.
## Start locally
After configuring the database, interpreter, and output directory, start the web application and a worker in separate terminals or under the existing supervisor:
```sh
npm start
```
```sh
npm run worker
```
The worker-management page creates workers using the configured checkout and current Node interpreter. It only lists and controls PM2 processes whose executable is this checkout's `queue_worker.js`; unrelated services are excluded. PM2 IDs are resolved on the server. Saving the host-wide PM2 process list is a deployment operation (`pm2 save` as the download account), so the web control is removed.
## Using the interface
- **Dashboard** (`/`): see current claims by worker, waiting/active/history counts, and the latest five completed and five failed-attempt records. Each summary links to the relevant full queue or history.
- **New download** (`/download`): choose Series or Single episode and check the filename preview. Series has a Season field, defaulting to 1. Leave the token blank to use the saved token, or paste a replacement. Each submission checks access before adding any jobs.
- **Queue** (`/status`): choose Queued, Active, Completed, or Failed attempts. Search filenames and choose 10, 25, or 50 results per page. Refresh preserves expanded logs, filters, and unsent search input. The danger button beside Refresh clears the selected waiting/history state after confirmation; Active has no clear operation.
- **Workers** (`/pm2`): use **Quick add worker** for `proxer-worker-1`, `proxer-worker-2`, and subsequent numbers. The counter persists in MongoDB and avoids existing PM2 names. Custom names remain available. Select a worker to inspect metrics and logs or start/stop/restart/delete it. Disruptive commands ask for confirmation.
The dashboard and queue show a card for each managed worker. A newly claimed job carries a startup identity so it can be matched to the correct live process. Legacy claims and ambiguous/stale assignments remain visible without guessing. File sizes describe the current file on disk; there is no guessed percentage or speed. Restart workers after installing this refinement so subsequent claims carry identity metadata.
The status API returns one selected page in `items`, together with `counts`, `pagination`, `filters`, `global`, and bounded `activity`. It accepts `state`, `q`, `page`, and `pageSize`. `/status-summary` stays count-only, while `/dashboard-data` returns overview counts, activity, and bounded recent history. See the [API details](docs/phase-2-refinements.md#api-and-data-additions).
Queue/history clearing applies to all records in the selected state, including those outside the current filter or page. Clearing history keeps media files on disk. Active processing flags remain protected.
### Saved session token
The cache is a single document in the existing MongoDB `settings` collection (`_id: "proxer-session-token"`), shared by this application deployment. The token field is always empty when a page is rendered; safe metadata reports whether a token is saved and the last successful check. No token is sent back in HTML/JSON, stored in browser storage, or added to a URL.
Each submission checks the first requested episode's source page using the configured cookie and stream preference. It requires the same positive embed-code evidence as the protected resolver, with a 12-second timeout and 1 MiB response limit. It performs no media transfer and never follows redirects with the cookie. HTTP 200 alone is insufficient.
A rejected token prompts for a replacement and prevents enqueueing. Verification challenges, missing sources, unfamiliar responses, and connection failures have separate warnings and keep the saved token. A successful replacement is saved only after validation. Revision checks prevent an older in-flight request from erasing or overwriting a newer saved token.
This validates download access at submission time; it does not prove account identity or guarantee the token will remain usable during a long queue. Existing queued jobs retain their original token. The existing worker pause/verification flow still handles failures after enqueueing. MongoDB access and backups protect the cached credential just as they protect credentials already held in queue records.
## Submission and filenames
Only HTTPS Proxer watch URLs on `proxer.me` or `www.proxer.me` are accepted. The URL must identify a positive integer series ID, positive integer episode, and one of `engsub`, `engdub`, `gersub`, or `gerdub`. Fragments and an optional trailing slash are normalized away. Query parameters, credentials in URLs, and custom ports are rejected.
| Source | Filename before `.mp4` |
|---|---|
| Web video with title | Explicit legacy `filename`, then the form's `name` |
| Web video without title | `{id} E{episode} {language}` |
| Web series with Season | `{trimmedNameOrId}S{season:03}E{episode:03}_{language}` |
| Legacy web/API series without `season` | `{trimmedNameOrId}E{paddedEpisode}_{language}` |
| Standalone series CLI | `{name}_Episode_{episode}_{language}` |
The current form always submits a season: for example, `My SeriesS001E009_engsub.mp4`. Season and episode use a minimum of three digits and expand beyond 999. Season 0 represents specials. Season affects only the filename, not the source episode numbers; there is no automatic season-to-absolute-episode mapping. Enter the title without an existing season/episode suffix. Legacy clients that omit `season` retain padding based on the highest requested episode. Existing files and queue names are not renamed. All destinations are validated before a batch is queued. Filenames must be single names inside the configured directory; symlink and non-file targets are rejected. The corrected video-title fallback is intentional. [Compatibility fixtures](tests/fixtures/legacy-contracts.json) record the original conventions.
## Python CLI compatibility
Both original entrypoints remain available:
```sh
python3 -B scripts/proxer-dl-video.py --help
python3 -B scripts/proxer-dl-series.py --help
```
Video arguments: `-u/--url`, `-f/--filename`, `-o/--output`, and either `-t/--token` or `--token-stdin`.
Series arguments: `-i/--id`, `-n/--name`, `-e/--episodes` (inclusive `start-end`), `-l/--language`, `-o/--output`, and either token option.
`--token-stdin` accepts one complete `cookie_name=value` followed by an optional newline and EOF. It preserves `=` inside the value and limits the complete cookie to 8192 UTF-8 bytes. Workers use this interface so credentials do not appear in process arguments. Legacy `-t` remains for compatibility. For a filename beginning with a dash, use `--filename=-Example` so the parser treats it as a value.
Each download invocation emits a final `PROXER_RESULT` JSON record outside the library's progress output. Exit codes are 0 for completion, 1 for runtime failure, and 2 for invalid input. A series invocation returns a failure exit code when any episode fails and includes counts for completed, failed, and unattempted episodes. Help output remains normal CLI help.
Both scripts disable bytecode writing before imports, and workers additionally launch Python with `-B` and `PYTHONDONTWRITEBYTECODE=1`.
## Failure and shutdown behavior
- Ordinary source/network/validation failures are recorded in failed history with the original job ID, source URL, filename, category, and a bounded sanitized log. They do not pause unrelated jobs. Automatic retries are deferred to the explicit attempt model.
- A missing embed or MP4 marker now produces a `resolution` result and pauses new downloads at the first failure. The full job stays queued for a deliberate retry, while its failed attempt remains visible in history. The banner describes possible CAPTCHA/login verification, an unavailable video, or a changed source page; it does not claim CAPTCHA is confirmed. Verified HTTP 404 remains an ordinary source failure.
- Verified HTTP 401/403 access rejection also pauses the pool and retains the job. The pause is persisted before attempt history and claim release. Workers recheck it after claiming and immediately before launching Python; transfers already admitted may finish. The global action resumes after external verification; it does not solve CAPTCHA or refresh an expired token stored in a queued job.
- Missing interpreter/dependencies and systemic output-storage failures retain the queued request and halt the worker. They do not consume the remaining queue or set a CAPTCHA block.
- On a handled stop, a started child must terminate before its job is made eligible again. A stop during pre-launch validation prevents the child from starting. Resuming an interrupted transfer restarts it from the beginning.
- History persistence must succeed before the queue record is removed. A database error leaves the processing claim held and stops the worker.
The blanket `clear-processing` operation is disabled and returns HTTP 409. Phase 1 still uses legacy claims: forced kills, host loss, database failure, or multi-step history persistence can require manual reconciliation. Expiring ownership, automatic recovery, atomic job state, collision policy, staged output publication, and safe drain controls are later rollout phases. Never clear a claim while its Python process might still be writing.
## Documentation
- [Phase 2 refinements, token cache, and verification](docs/phase-2-refinements.md)
- [Initial Phase 2 interface baseline](docs/phase-2-ui.md)
- [Phase 1 baseline and compatibility boundary](docs/phase-1-baseline.md)
- [Phase 1 verification report](docs/phase-1-verification.md)
- [Unresolved-link pause fix and recovery](docs/phase-1-resolution-fix.md)
- [Debian 13 deployment and bandwidth assessment](docs/debian-13-deployment.md)
- [Rollout roadmap](docs/rollout-roadmap.md)