feat: full stack revival, modularization, Jellyfin 12.4, GPU/overlays, security & UX fixes

This commit is contained in:
soulis-1256 2026-11-21 20:40:34 +02:00
parent 692d535418
commit 5529f74c0b
No known key found for this signature in database
98 changed files with 10023 additions and 7449 deletions

View file

@ -8,7 +8,7 @@ PGID=${PGID}
MEDIA_DIRECTORY=${MEDIA_DIRECTORY}
INSTALL_DIRECTORY=${INSTALL_DIRECTORY}
# jellyfin | emby | plex
# Supported core media server: jellyfin
MEDIA_SERVICE=${MEDIA_SERVICE}
# IANA timezone (e.g. Europe/Athens)
@ -28,13 +28,23 @@ WIREGUARD_ADDRESSES=${WIREGUARD_ADDRESSES}
PORT_FORWARD_ONLY=${PORT_FORWARD_ONLY}
VPN_PORT_FORWARDING=${VPN_PORT_FORWARDING}
# configure.sh API host
# Optional feature overlays
# y/n — VueTorrent alternate WebUI mod for qBittorrent
VUETORRENT_ENABLED=${VUETORRENT_ENABLED}
# none | intel | nvidia — hardware transcoding passthrough for Jellyfin
GPU_TRANSCODING=${GPU_TRANSCODING}
# y/n — Byparr Cloudflare solver wired into Prowlarr
BYPARR_ENABLED=${BYPARR_ENABLED}
# y/n — SABnzbd Usenet downloader wired into Sonarr/Radarr/Prowlarr
USENET_ENABLED=${USENET_ENABLED}
# config.sh API host (127.0.0.1 locally or LAN IP)
API_HOST=${API_HOST}
# seerr-gateway: 1 = DELETE /request cancels in-flight *arr/qB grabs (not library files).
# Set to 0 for stock Seerr (request row only). See docs/seerr-delete-request.md
SEERR_DELETE_REQUEST_PURGE=1
# media-purge-watch: 1 = inotify on library deletes (Jellyfin/*arr file remove → qB).
# media-purge-watch: 1 = inotify on library deletes (Jellyfin/*arr file remove -> qB/SABnzbd).
# Set to 0 to disable the watcher (CustomScript + seerr-gateway purge still run).
MEDIA_PURGE_WATCH=1

30
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,30 @@
name: CI
on:
push:
branches: [main, dev]
pull_request:
branches: [main, dev]
jobs:
verify:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install lint and test dependencies
run: |
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends jq gettext-base shellcheck python3
- name: Check bash syntax & shellcheck & Python compile
env:
CI: "true"
run: bash tests/run.sh lint
- name: Run unit tests (shell + Python unittest)
run: make test-unit
- name: Validate Docker Compose overlays
run: make test-compose

40
CHANGELOG.md Normal file
View file

@ -0,0 +1,40 @@
# Changelog
## [Unreleased] — Stack Revival & Modular Hardening
### Added
- **Four opt-in service overlays** (`compose/*.yaml`, selectable during manual setup or `assemblrr config edit`):
- `vuetorrent.yaml`: VueTorrent (`v2.37.0`) WebUI mod for qBittorrent (`VUETORRENT_ENABLED=y`).
- `gpu-intel.yaml` / `gpu-nvidia.yaml`: Intel/AMD VAAPI (`/dev/dri`) and NVIDIA NVENC hardware transcoding for Jellyfin (`GPU_TRANSCODING=intel|nvidia`).
- `byparr.yaml`: Byparr (`3.1.1`) Cloudflare challenge solver wired as a Prowlarr `FlareSolverr` proxy tagged `byparr` (`BYPARR_ENABLED=y`).
- `usenet.yaml`: SABnzbd (`5.1.3`) Usenet downloader wired automatically into Sonarr, Radarr, and Prowlarr via `lib/usenet.sh` (`USENET_ENABLED=y`).
- **Offline Usenet CI test harness**: `tests/fixtures/mock_nntp.py`, `tests/fixtures/mock_newznab.py`, and `tests/integration/usenet_mock_e2e.sh` (zero paid subscriptions required).
- **Komodo deployment documentation**: `docs/komodo.md`.
- **Legal & community docs**: `NOTICE`, `SECURITY.md`, `CONTRIBUTING.md`, `CHANGELOG.md`, SPDX license headers across scripts.
- **GitHub Actions CI**: `.github/workflows/ci.yml` (`bash -n`, `shellcheck`, `py_compile`, unit & compose validation).
- **Migration 004** (`migrations/004_jellyfin_12_and_stack_revival.sh`): prepares `config/sabnzbd`, backfills new feature flags, and prints upgrade notes for Jellyfin 12.4.
### Changed
- **Upgraded core container image pins**:
- Jellyfin `10.11.11` -> `12.4ubu2604-ls60` (removed `--profile jellyfin` gate; migrated API auth headers from legacy `X-Emby-Token` to `Authorization: MediaBrowser`).
- qBittorrent `5.2.3` -> `5.3.0`
- Sonarr `4.0.19.2979-ls321` -> `4.0.20.3014-ls6`
- Radarr `6.3.0.10514-ls313` -> `7.0.3.10918-ls328`
- Prowlarr `2.5.2.5491-ls156` -> `3.0.2.5780-ls169`
- Bazarr `1.6.0` -> `1.6.2`
- Seerr `v3.4.1` -> `v3.5.2`
- Recyclarr `8.7.1` -> `8.8.1`
- Deunhealth pinned by immutable SHA-256 digest; Gateway Python bumped to `3.12.16-alpine`; sidecar base images bumped to `alpine:3.24.4`.
- **Core architecture modularized**:
- Split `lib/core.sh` into `log.sh`, `tty.sh`, `paths.sh`, `fs.sh`, `docker.sh`, `languages.sh` (keeping `lib/core.sh` as a backward-compatible facade).
- Split `lib/arr.sh` into `qbit.sh`, `arr_common.sh`, `arr_quality.sh`, `prowlarr.sh`, `arr_import.sh`, and extracted `lib/recyclarr.sh` (keeping `lib/arr.sh` as a facade).
- Removed broken Emby/Plex stubs from `compose/base.yaml` and core setup (moved reference examples into `compose/examples/custom.yaml.example` with non-colliding `.30+` IPs).
- Standardized multi-select `fzf` TUI controls (`Tab=toggle`, `Enter=confirm`), added `--preview` for Prowlarr indexers, and added version compatibility checks for older `fzf` releases (`0.29+`).
- **Upgrade engine**: added atomic pre-apply staging & rollback on Compose validation failure, self-re-exec after copying managed files, `.assemblrr-channel` persistence, and migration function isolation (`unset -f` before `source`).
### Security & Bug Fixes
- **P0 — `scripts/seerr-gateway.py`**: fixed confused-deputy authorization bypass by verifying caller permissions via `GET /api/v1/auth/me` before invoking Radarr/Sonarr deletions; refused upstream 5xx fail-open behavior; added `GatewayConfig` DI and body size cap; extracted mock tests out of production script into `tests/unit/test_seerr_gateway_suite.py`.
- **P0 — `lib/config_edit.sh`**: fixed `_config_edit_all` missing `--reconfigure`, non-`fzf` picker menu output corrupting stdout capture, and quote escaping / `0600` permission preservation in `config_set_kv`.
- **P0 — `scripts/media-purge.sh`**: fixed `--tmdb`/`--tvdb` re-exec dropping `--dry-run`/`--qb-only`, tightened `qb_match_season_jq` lookahead boundaries so audio codecs (`DTS5.1`) no longer trigger bogus seasons, switched to `Authorization: MediaBrowser` + `/ScheduledTasks` check, and added SABnzbd cleanup support.
- **P1 — `lib/paths.sh`, `lib/bazarr.sh`, `lib/prompts.sh`**: removed unsafe `eval`/`source` in `safe_source`, fixed `curl -F` injection risk via `--form-string`, removed borrowed OpenSubtitles API key, fixed Gluetun VPN slugs (`private internet access`, `ivpn`), and replaced Windows `wmic` with PowerShell `Get-PSDrive`.
- **P1 — Sidecars (`vpn-watchdog.sh`, `media-purge-watch.sh`, `jellyfin-refresh.sh`)**: added restart cooldown & active-swarm guard in `vpn-watchdog.sh`, upgrade-history recency window & whole-TV-show Sonarr hold checks in `media-purge-watch.sh`, and atomic lock reclamation in `jellyfin-refresh.sh`.

25
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,25 @@
# Contributing to assemblrr
Thank you for contributing to assemblrr!
## Repository Guidelines
1. **Shell script conventions**
- Entrypoints (`bin/*.sh`, `scripts/*.sh`, `platform/linux/*.sh`) use `#!/usr/bin/env bash` or `#!/bin/bash` with `set -euo pipefail`.
- Sourced libraries (`lib/*.sh`) must **not** call `set -euo pipefail` globally, and every `lib/*.sh` module must include a `_ASSEMBLRR_*_SOURCED` idempotency guard and `# SPDX-License-Identifier: GPL-3.0-or-later`.
- Read interactive input with `read_prompt` / `read_masked` (`lib/tty.sh`), never raw `read -p` inside prompts/menus.
- Load config files via `safe_source` (`lib/paths.sh`).
- Do not modify Docker Compose pinned image tags without verifying upstream manifests and running full test validation.
2. **Legal & Content Neutrality**
- Do **not** include real copyrighted titles, release group names, piracy domains, or third-party proprietary API keys in code, comments, documentation, or tests.
- Use clearly synthetic titles (`Alpha Film (2016)`, `Sample Show`) or public-domain/CC fixtures (`Big Buck Bunny`, Ubuntu ISO).
3. **Running Checks Locally**
```bash
make test-unit
make test-compose
python3 -m unittest discover -s tests/unit -p 'test_*.py' -v
bash tests/run.sh --lint
```
All tests must pass offline without external paid services or live piracy indexers.

32
NOTICE Normal file
View file

@ -0,0 +1,32 @@
assemblrr — Third-Party Upstream Projects & Legal Notice
==========================================================
assemblrr is licensed under the GNU General Public License v3.0 or later
(GPL-3.0-or-later). See LICENSE for the full license text.
assemblrr is an orchestration and configuration tool only. It does NOT include,
host, distribute, index, or endorse copyrighted media content or unauthorized
sources. Users are solely responsible for configuring lawful indexers, media,
and subscriptions in their own deployments.
This project automates and integrates with independent upstream open-source
applications and container images maintained by their respective authors:
- Jellyfin https://jellyfin.org/
- LinuxServer.io Images https://www.linuxserver.io/
- Sonarr https://sonarr.tv/
- Radarr https://radarr.video/
- Prowlarr https://prowlarr.com/
- Bazarr https://www.bazarr.dev/
- Seerr https://github.com/seerr-team/seerr
- Recyclarr https://recyclarr.dev/
- TRaSH Guides https://trash-guides.info/
- qBittorrent https://www.qbittorrent.org/
- VueTorrent https://github.com/VueTorrent/VueTorrent
- Gluetun https://github.com/qdm12/gluetun
- Deunhealth https://github.com/qdm12/deunhealth
- Byparr https://github.com/ThePhaseless/Byparr
- SABnzbd https://sabnzbd.org/
All trademarks, service names, and container images remain the property of
their respective owners.

227
README.md
View file

@ -4,45 +4,57 @@
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](LICENSE)
[![Platform](https://img.shields.io/badge/Platform-Linux%20%7C%20WSL2-orange.svg)](#installation)
[![Stack](https://img.shields.io/badge/Stack-Jellyfin%20%2B%20*arr-green.svg)](#the-stack)
[![Stack](https://img.shields.io/badge/Stack-Jellyfin%2012.4%20%2B%20*arr-green.svg)](#the-stack)
[![Discussions](https://img.shields.io/github/discussions/soulis-1256/assemblrr)](https://github.com/soulis-1256/assemblrr/discussions)
assemblrr is an automated setup and management suite for self-hosted media stacks. It provisions, wires, and maintains a complete ecosystem (media server, torrent client, indexers, request management, subtitles, and quality profiles) with zero manual work.
assemblrr is an automated setup and management suite for self-hosted media stacks. It provisions, wires, and maintains a complete ecosystem (media server, download clients, indexers, request portal, subtitles, quality profiles, and optional overlays) with minimal friction.
[Features](#features) • [The Stack](#the-stack) • [Installation](#installation) • [CLI Usage](#cli-usage) • [Default Ports](#service-ports) • [Documentation](#documentation) • [Development](#development)
[Features](#features) • [The Stack](#the-stack) • [Optional Overlays](#optional-overlays) • [Installation](#installation) • [CLI Usage](#cli-usage) • [Service Ports](#service-ports) • [Documentation](#documentation) • [Development](#development)
---
## Features
- **Guided Multi-Platform Setup:** Interactive installer for bare-metal Linux and Windows (via automated WSL2 bridging).
- **Automated Service Wiring:** Auto-configures and interconnects Radarr, Sonarr, Prowlarr, qBittorrent, Bazarr, Seerr, Recyclarr, and Jellyfin out of the box.
- **VPN-First Networking:** Built-in Gluetun integration routes download traffic through your VPN, complete with start-up validation and a stalled-routing watchdog.
- **Unified Operator CLI:** Manage the stack (`start`, `stop`, `restart`, `status`), change settings, take backups, and run updates directly from your terminal.
- **Hardlink-Optimized Storage:** Atomic moves and hardlink-friendly directory layout with automated TRaSH Guides quality profile sync via Recyclarr.
- **Granular Media Purge:** Single-command cleanup (`assemblrr purge`) that cleanly removes titles across *arr apps, the disk, and matching torrents simultaneously.
- **Disaster Recovery & Migration:** Rebuild your entire stack on a clean host directly from a backup archive via the setup wizard (`Restore` mode) or `assemblrr restore`.
- **Guided Multi-Platform Setup:** Interactive installer for bare-metal Linux and Windows (via automated WSL2 bridging), with Express, Manual, Reconfigure (`--reconfigure`), and Restore modes.
- **Automated Service Wiring:** Auto-configures and interconnects Radarr, Sonarr, Prowlarr, qBittorrent, Bazarr, Seerr, Recyclarr, and Jellyfin (`12.4+` with `Authorization: MediaBrowser` auth) — plus optional SABnzbd and Byparr.
- **VPN-First Networking:** Built-in Gluetun integration routes torrent traffic through your VPN with start-up validation and a cooldown-guarded routing watchdog (`vpn-watchdog`).
- **Unified Operator CLI:** Manage the stack (`start`, `stop`, `restart`, `status`, `health`, `config edit`, `config apply`, `upgrade`, `backup`, `restore`, `purge`, `uninstall`) from your terminal.
- **Safe Rollback Upgrades:** `assemblrr upgrade` backs up managed files, applies atomic staged updates + migrations, validates resolved Docker Compose config before stamping, and rolls back automatically if validation fails.
- **Hardlink-Optimized Storage:** Atomic moves and hardlink-friendly layout across `/data/torrents`, `/data/usenet`, and `/data/media`, plus TRaSH Guides profile sync via Recyclarr.
- **Authenticated Request-Delete Gateway:** `seerr-gateway` verifies caller permissions (`GET /api/v1/auth/me`) before draining in-flight downloads and cleaning library/season files safely.
---
## The Stack
assemblrr provides an officially supported, fully-automated **express stack**:
assemblrr provides an officially supported core stack with pinned container versions:
| Service | Category | Default Port | Description |
|---|---|---|---|
| **[Jellyfin](https://jellyfin.org/)** | Media Server | `8096` | Open-source media streaming platform |
| **[qBittorrent](https://www.qbittorrent.org/)** | Download Client | `8081` | Torrent client isolated behind VPN (or direct access) |
| **[Jellyfin](https://jellyfin.org/)** (`12.4`) | Media Server | `8096` | Open-source media streaming platform |
| **[qBittorrent](https://www.qbittorrent.org/)** (`5.3.0`) | Torrent Client | `8081` | Torrent client isolated behind VPN (or direct access) |
| **[Sonarr](https://sonarr.tv/)** | TV Management | `8989` | Smart PVR & series download automation |
| **[Radarr](https://radarr.video/)** | Movie Management | `7878` | Movie collection manager and automation |
| **[Prowlarr](https://prowlarr.com/)** | Indexer Sync | `9696` | Centralized indexer proxy syncing to *arr apps |
| **[Seerr](https://github.com/seerr-team/seerr)** | Request Management | `5055` | Media discovery and user request gateway |
| **[Bazarr](https://www.bazarr.media/)** | Subtitles | `6767` | Automatic subtitle downloader for Sonarr and Radarr |
| **[Prowlarr](https://prowlarr.com/)** | Indexer Sync | `9696` | Centralized indexer manager syncing to *arr apps |
| **[Seerr](https://github.com/seerr-team/seerr)** | Request Portal | `5055` | Media discovery & requests behind authenticating `seerr-gateway` |
| **[Bazarr](https://www.bazarr.media/)** | Subtitles | `6767` | Automatic subtitle manager for Sonarr and Radarr |
| **[Recyclarr](https://recyclarr.dev/)** | Quality Profiles | — | Syncs recommended TRaSH Guides quality profiles & custom formats |
| **[Gluetun](https://github.com/qdm12/gluetun)** *(Optional)* | VPN & Killswitch | — | Secure VPN tunnel with health watchdog for download traffic |
| **[Gluetun](https://github.com/qdm12/gluetun)** *(Optional)* | VPN & Killswitch | — | Secure VPN tunnel with `deunhealth` & `vpn-watchdog` |
### Optional Overlays
Enable during `Manual` setup or toggle anytime via `assemblrr config edit`:
| Overlay File | Env Key | Description |
|---|---|---|
| [`compose/vuetorrent.yaml`](compose/vuetorrent.yaml) | `VUETORRENT_ENABLED=y` | Modern VueTorrent WebUI theme mod for qBittorrent *(default: enabled)* |
| [`compose/gpu-intel.yaml`](compose/gpu-intel.yaml) | `GPU_TRANSCODING=amd` / `intel` | AMD VAAPI / Intel QSV (`/dev/dri`) hardware transcoding + Jellyfin auto-wiring |
| [`compose/gpu-nvidia.yaml`](compose/gpu-nvidia.yaml) | `GPU_TRANSCODING=nvidia` | NVIDIA NVENC/NVDEC GPU reservation + Jellyfin auto-wiring *(auto-enabled when detected)* |
| [`compose/byparr.yaml`](compose/byparr.yaml) | `BYPARR_ENABLED=y` | Byparr Cloudflare solver wired into Prowlarr (`byparr` tag) |
| [`compose/usenet.yaml`](compose/usenet.yaml) | `USENET_ENABLED=y` | SABnzbd (`8085`) wired into Sonarr, Radarr, and Prowlarr (requires your own NNTP account) |
> [!TIP]
> **Custom & Extended Services:** You can easily add custom containers (e.g. Plex, Emby, SABnzbd, Portainer) via `compose/custom.yaml` or optional compose profiles. Official automated wiring and CLI maintenance workflows target the core stack above.
> Need self-managed extras (Plex, Emby, Lidarr, Komodo Periphery)? Copy [`compose/examples/custom.yaml.example`](compose/examples/custom.yaml.example) to `compose/custom.yaml`. Custom services use `.30+` IPs on `assemblrr_network` and are left untouched by upgrades.
---
@ -50,202 +62,151 @@ assemblrr provides an officially supported, fully-automated **express stack**:
### Linux / WSL2
Run the one-line bootstrap installer in your terminal (requires `bash` and `curl`):
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh)
```
### Windows (PowerShell)
Ensure Docker Desktop is running, then launch PowerShell as Administrator and run:
Ensure Docker Desktop is running with WSL2 integration enabled, then run PowerShell and execute:
```powershell
irm https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/windows/bootstrap.ps1 | iex
```
> [!NOTE]
> The Windows installer automatically bridges the stack into your default WSL2 Linux distribution.
### Advanced Options
#### Fish Shell
```fish
bash (curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh | psub)
```
#### Custom Branch or Tag
**Linux / WSL2:**
**Custom branch, tag, or commit SHA:**
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh) --ref dev
# or:
ASSEMBLRR_REF=dev bash <(curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh)
```
**Windows (PowerShell):**
```powershell
$env:ASSEMBLRR_REF = "dev"; irm https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/windows/bootstrap.ps1 | iex
```
#### Restore on a Clean Host from Backup
To rebuild your entire stack on a fresh host from an existing backup archive, run the bootstrap installer and select `3) Restore`, or pass the `--restore` flag:
**Linux / WSL2:**
**Restore on a clean host from backup:**
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh) --restore /path/to/assemblrr-backup.tar.gz
```
**Windows (PowerShell):**
```powershell
irm https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/windows/bootstrap.ps1 | iex -ArgumentList "--restore", "C:\path\to\assemblrr-backup.tar.gz"
```
> [!IMPORTANT]
> **Already installed?** Use `assemblrr upgrade` to update or `assemblrr uninstall` to remove. Do not re-run the bootstrap script on an existing installation.
> **Already installed?** Use `assemblrr upgrade` to update, `assemblrr config edit` to change settings/overlays, or `assemblrr uninstall` to remove.
---
## CLI Usage
Once installed, the `assemblrr` command-line interface is available on your system `PATH`:
```bash
assemblrr <command> [options]
```
### Stack Control
| Command | Description |
|---|---|
| `assemblrr start [service]` | Start all services (or a specific service) with VPN verification |
| `assemblrr stop [service]` | Stop all running services (or a specific service) |
| `assemblrr restart [service]` | Restart all services (or a specific service) |
| `assemblrr destroy [service]` | Teardown and reset container state |
| `assemblrr start [service]` | Start all (or named) services and wait for readiness |
| `assemblrr stop [service]` | Stop running services |
| `assemblrr restart [service]` | Restart running services |
| `assemblrr destroy [service]` | Stop and remove containers/network (keeps config & media) |
### Status & Inspection
| Command | Description |
|---|---|
| `assemblrr status` | Operator dashboard displaying service states, health, and access URLs |
| `assemblrr status --docker` | Raw `docker compose ps` output |
| `assemblrr health` | Compact health check pass/fail summary for all containers |
| `assemblrr logs [service]` | Tail and follow logs for all containers or a specific service |
| `assemblrr check-vpn` | Verify VPN connectivity, assigned IP, and tunnel health |
### Configuration & Wiring
| `assemblrr status` | Operator dashboard displaying service states, health, and URLs |
| `assemblrr status --docker` | Raw `docker compose ps` table |
| `assemblrr health` | Compact health pass/fail check across catalog services |
| `assemblrr logs [service]` | Tail container logs |
| `assemblrr check-vpn` | Compare host exit IP against Gluetun tunnel IP |
### Configuration & Maintenance
| Command | Description |
|---|---|
| `assemblrr config` | List all available configuration options |
| `assemblrr config show` | Display active environment configuration |
| `assemblrr config edit` | Interactive wizard to update settings (VPN, indexers, credentials, etc.) |
| `assemblrr config apply` | Re-run automated service wiring (alias: `config wire`) |
### Maintenance, Backups & Cleanup
| Command | Description |
|---|---|
| `assemblrr backup <path>` | Create a timestamped configuration backup archive |
| `assemblrr restore <file.tar.gz>` | Restore configuration from a backup archive |
| `assemblrr update-containers` | Pull the latest Docker images and restart the stack (prompts for backup first) |
| `assemblrr upgrade` | Upgrade assemblrr core scripts, apply migrations, and update wiring |
| `assemblrr upgrade --check` | Dry-run: preview upcoming file changes and migrations |
| `assemblrr upgrade --skip-stack`| Apply CLI and script updates without restarting running containers |
| `assemblrr purge` | Delete a title across Sonarr/Radarr, filesystem, and active qBittorrent torrents |
| `assemblrr uninstall` | Cleanly remove the entire stack (preserves media unless `--media` is passed) |
| `assemblrr config show` | Show active configuration & resolved compose overlays |
| `assemblrr config edit` | Interactive picker for VPN, quality, overlays (VueTorrent/GPU/Byparr/Usenet), auth, etc. |
| `assemblrr config apply` | Re-run non-interactive service API wiring (`alias: config wire`) |
| `assemblrr upgrade` | Upgrade managed files, apply migrations, validate & rebuild stack (`--check`, `--from DIR`, `--ref REF`, `--skip-stack`) |
| `assemblrr update-containers` | Rebuild local sidecars and pull any custom overlay images |
| `assemblrr purge ...` | Remove a movie/series/season across *arr, library disk, qBittorrent, and SABnzbd |
| `assemblrr backup <dir>` | Create a `0600` backup archive |
| `assemblrr restore <file.tar.gz>` | Validate archive and restore config/secrets |
| `assemblrr uninstall` | Clean removal (preserves media unless `--media` is passed) |
---
## Service Ports
When running the default stack, the following ports are mapped on `http://localhost:<PORT>`:
| Service | Port | Default URL | Purpose |
| Service | Host Port | Default URL | Notes |
|---|---|---|---|
| **Jellyfin** | `8096` | `http://localhost:8096` | Media streaming frontend |
| **qBittorrent** | `8081` | `http://localhost:8081` | Torrent Web UI |
| **Sonarr** | `8989` | `http://localhost:8989` | TV show manager |
| **Radarr** | `7878` | `http://localhost:7878` | Movie collection manager |
| **Prowlarr** | `9696` | `http://localhost:9696` | Indexer management |
| **Seerr** | `5055` | `http://localhost:5055` | Media request portal (via gateway) |
| **Seerr (Gateway)** | `5055` | `http://localhost:5055` | Media requests + delete-request purge |
| **Bazarr** | `6767` | `http://localhost:6767` | Subtitle manager |
| **Sonarr** | `8989` | `http://localhost:8989` | TV show manager |
| **Radarr** | `7878` | `http://localhost:7878` | Movie manager |
| **Prowlarr** | `9696` | `http://localhost:9696` | Indexer manager |
| **qBittorrent** | `8081` | `http://localhost:8081` | Torrent Web UI (+ VueTorrent when enabled) |
| **SABnzbd** *(opt.)* | `8085` | `http://localhost:8085` | Usenet downloader (`USENET_ENABLED=y`) |
---
## Configuration & Layout
Configuration and persistent state live in your installation directory (default: `~/assemblrr`):
```text
~/assemblrr/
├── .env # Environment variables generated during setup (see .env.example)
├── secrets/ # Authenticated credentials and VPN keys (kept separate from .env)
├── .env # Environment variables generated by setup
├── .assemblrr-config # Install metadata + active UI/feature settings
├── .assemblrr-channel # Active upgrade git ref (default: main)
├── .assemblrr-version # Recorded upgrade version stamp
├── .assemblrr-migrations # Applied migration IDs
├── secrets/ # 0700 dir of 0600 service passwords & VPN keys
├── compose/
│ ├── base.yaml # Core service definitions
│ ├── vpn.yaml # VPN network overlay (Gluetun)
│ ├── direct-access.yaml# Direct networking overlay (non-VPN)
│ └── custom.yaml # User-defined custom services
├── config/ # Persistent database and appdata for all services
└── scripts/ # Internal watchdog and gateway sidecar scripts
│ ├── base.yaml # Core service definitions
│ ├── vpn.yaml # Gluetun VPN network + watchdog overlay
│ ├── direct-access.yaml # Non-VPN overlay
│ ├── vuetorrent.yaml # Optional VueTorrent WebUI overlay
│ ├── gpu-intel.yaml # Optional Intel/AMD VAAPI GPU overlay
│ ├── gpu-nvidia.yaml # Optional NVIDIA NVENC GPU overlay
│ ├── byparr.yaml # Optional Byparr Cloudflare solver overlay
│ ├── usenet.yaml # Optional SABnzbd Usenet overlay
│ └── custom.yaml # User-defined custom services (untouched by upgrade)
├── config/ # Persistent service appdata
├── migrations/ # Idempotent upgrade migrations
└── scripts/ # Sidecar watchdog, purge & gateway hooks
```
---
## Documentation
- **[TRaSH Guides & Quality Profiles](docs/trash-guides.md):** Quality profile synchronization and custom format handling.
- **[Seerr Delete Request](docs/seerr-delete-request.md):** In-flight download cancellation workflow and gateway architecture.
- **[Uninstall Guide](docs/uninstall.md):** Complete removal walkthrough and resource inventory.
- **[API Reference](docs/api-reference.md):** Upstream API endpoints and integration notes.
- **[TRaSH Guides & Quality Profiles](docs/trash-guides.md):** Quality profile sync and custom format notes.
- **[Seerr Delete Request](docs/seerr-delete-request.md):** Gateway RBAC auth, queue drain, and season-scoped purge architecture.
- **[Komodo Integration](docs/komodo.md):** Running and monitoring assemblrr stacks via Komodo.
- **[API Reference](docs/api-reference.md):** Jellyfin 12 `MediaBrowser` auth headers, *arr/SABnzbd/Byparr endpoints.
- **[Uninstall Guide](docs/uninstall.md):** Complete removal walkthrough and directory inventory.
- **[Security Policy](SECURITY.md) • [Contributing](CONTRIBUTING.md) • [Changelog](CHANGELOG.md) • [Legal Notice](NOTICE)**
---
## Development
### Setting Up a Development Environment
**Linux / WSL2:**
```bash
git clone https://github.com/soulis-1256/assemblrr.git
cd assemblrr
bash bin/setup.sh
make test # Unit tests + compose validation + shellcheck lint
make test-unit # Offline shell + Python unit suites
make test-compose # Docker Compose validation across overlay matrix
make lint # Run shellcheck across shell scripts
```
**Windows (PowerShell):**
```powershell
git clone https://github.com/soulis-1256/assemblrr.git
cd assemblrr
.\platform\windows\bootstrap-dev.ps1 -Full # Full setup (copies files to WSL2 and runs setup.sh)
.\platform\windows\bootstrap-dev.ps1 -Full -Clean # Clean install (uninstalls previous setup first)
.\platform\windows\bootstrap-dev.ps1 -Update # Fast sync for local script/CLI edits
```
### Running Tests
```bash
make test # Run all unit tests, compose validation, and shellcheck
make test-unit # Pure shell unit tests (no Docker required)
make test-compose # Docker Compose syntax and configuration validation
make test-integration # Live integration tests (requires ASSEMBLRR_ALLOW_LIVE_TEST=1)
make lint # Run shellcheck on all scripts
```
See [tests/README.md](tests/README.md) for testing guidelines and environment flags.
See [tests/README.md](tests/README.md) for the test suite layout, including the offline NNTP/Newznab Usenet mock harness.
---
## Community & Legal
assemblrr is infrastructure automation tooling designed to wire together and manage self-hosted applications. It does not provide, index, host, or distribute media content. Users are solely responsible for complying with applicable laws and licensing regulations in their jurisdiction.
assemblrr is infrastructure automation tooling for self-hosted applications. It does **not** include, host, index, or distribute copyrighted media content or external subscriptions. Users are solely responsible for complying with applicable laws in their jurisdiction. See [NOTICE](NOTICE).
Join discussions, request features, and connect with the community on **[GitHub Discussions](https://github.com/soulis-1256/assemblrr/discussions)**.
Join discussions on **[GitHub Discussions](https://github.com/soulis-1256/assemblrr/discussions)**.
---
## Acknowledgments & License
## License
- Originally inspired by [YAMS](https://yams.media/) ([rogsme/yams](https://github.com/rogsme/yams)); assemblrr has since been completely re-architected and expanded into an independent platform.
- Licensed under the **[GNU General Public License v3.0](LICENSE)**.
- Inspired in early versions by [YAMS](https://yams.media/), now independently architected and modularized.
- Licensed under the **[GNU General Public License v3.0 or later](LICENSE)**.

22
SECURITY.md Normal file
View file

@ -0,0 +1,22 @@
# Security Policy
## Supported Versions
Security fixes apply to the latest release on the `main` branch (`assemblrr upgrade`).
## Reporting a Vulnerability
Please do **not** open a public GitHub issue with exploit details for an unpatched vulnerability.
Report security issues privately via GitHub Security Advisories or private contact with the repository maintainer (`soulis-1256`). Include:
- Affected script, service overlay, or API endpoint
- Reproduction steps or minimal proof of concept
- Potential impact (e.g., credential exposure, privilege boundary bypass, command injection)
## Security Architecture Highlights
- **Secret isolation**: Service credentials and API tokens live under `secrets/` (`0700` directory, `0600` files), never embedded in `.env` or container compose YAML.
- **No `eval`/`source` on untrusted config**: Config files are loaded via `safe_source` (`lib/paths.sh`), which parses literal `KEY=VALUE` assignments line-by-line and rejects command substitution or code execution.
- **Authenticated request-delete gateway**: `scripts/seerr-gateway.py` resolves caller identity and permissions against `GET /api/v1/auth/me` before invoking privileged Sonarr/Radarr APIs and fails closed (`502`/`403`) on missing or unauthorized sessions.
- **Safe curl usage**: Secrets are passed via headers or `--form-string` rather than raw `-F` file/stdin triggers.

966
bin/cli.sh Normal file → Executable file

File diff suppressed because it is too large Load diff

372
bin/config.sh Normal file → Executable file
View file

@ -1,17 +1,14 @@
#!/bin/bash
set -euo pipefail
# SPDX-License-Identifier: GPL-3.0-or-later
# Service wiring — invoked by setup and upgrade.
# Exit 0 if all required steps succeed; exit 1 if any required step fails.
set -euo pipefail
# --- Config discovery ---
# Locate lib/ directory (handles both repo layout and installed layout)
_cfg_self="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -f "$_cfg_self/../lib/core.sh" ]; then
_lib_dir="$_cfg_self/../lib" # repo: bin/ and lib/ are siblings
_lib_dir="$_cfg_self/../lib"
elif [ -f "$_cfg_self/lib/core.sh" ]; then
_lib_dir="$_cfg_self/lib" # installed: lib/ is subdirectory of install dir
_lib_dir="$_cfg_self/lib"
elif [ -f "${ASSEMBLRR_DIR:-$HOME/assemblrr}/lib/core.sh" ]; then
_lib_dir="${ASSEMBLRR_DIR:-$HOME/assemblrr}/lib"
else
@ -19,235 +16,234 @@ else
exit 1
fi
# Source core library (logging, colors, safe_source, find_install_directory)
# shellcheck source=/dev/null
source "$_lib_dir/core.sh"
# Source branding
# shellcheck source=/dev/null
source "$_lib_dir/branding.sh"
# shellcheck source=/dev/null
source "$_lib_dir/fzf-tui.sh"
# shellcheck source=/dev/null
source "$_lib_dir/api.sh"
# shellcheck source=/dev/null
source "$_lib_dir/arr.sh"
# shellcheck source=/dev/null
source "$_lib_dir/recyclarr.sh"
# shellcheck source=/dev/null
source "$_lib_dir/jellyfin.sh"
# shellcheck source=/dev/null
source "$_lib_dir/seerr.sh"
# shellcheck source=/dev/null
source "$_lib_dir/bazarr.sh"
# shellcheck source=/dev/null
source "$_lib_dir/usenet.sh"
INSTALL_DIR=$(find_install_directory)
if [ -z "$INSTALL_DIR" ]; then
log_error "Could not find installation. Run setup first."
fi
_cfg_log_info() {
echo " $1"
printf ' %s\n' "$1" >> "${CONFIGURE_LOG:-/dev/null}"
}
# Source runtime config and branding
safe_source "$INSTALL_DIR/.assemblrr-config"
load_branding "$INSTALL_DIR"
# Source .env for VPN_ENABLED and other settings
set -a; safe_source "$INSTALL_DIR/.env"; set +a
API_HOST="${API_HOST:-127.0.0.1}"
# --- Constants ---
# Docker network URLs (for inter-service communication)
RADARR_DOCKER_URL="http://radarr:7878"
SONARR_DOCKER_URL="http://sonarr:8989"
PROWLARR_DOCKER_URL="http://prowlarr:9696"
# Download client host depends on VPN mode
if [ "${VPN_ENABLED:-n}" = "y" ]; then
QBITTORRENT_HOST="gluetun"
else
QBITTORRENT_HOST="qbittorrent"
fi
# Auth credentials
AUTH_USERNAME=$(cat "$INSTALL_DIR/secrets/auth_username.txt" 2>/dev/null || echo "$USER")
AUTH_PASSWORD=$(cat "$INSTALL_DIR/secrets/auth_password.txt" 2>/dev/null || echo "")
# --- Logging ---
# Always create a configure log file (same output for both express and manual)
CONFIGURE_LOG="/tmp/${APP_NAME}-configure-$(date '+%Y%m%d-%H%M%S').log"
# Extended logging for configure (step markers on top of lib/core.sh base, tee to log file)
_cfg_log_info() { echo " $1" | tee -a "$CONFIGURE_LOG"; }
# Step markers for the summary line (exit code uses _wire_critical_fail)
_configure_total=0
_configure_ok=0
_configure_fail=0
log_step() { echo -e " ${GREEN}✓${NC} $1" | tee -a "$CONFIGURE_LOG"; _configure_ok=$((_configure_ok + 1)); _configure_total=$((_configure_total + 1)); }
log_step_fail() { echo -e " ${RED}✗${NC} $1" | tee -a "$CONFIGURE_LOG"; _configure_fail=$((_configure_fail + 1)); _configure_total=$((_configure_total + 1)); }
log_step() {
printf ' %b✓%b %s\n' "${GREEN:-}" "${NC:-}" "$1"
printf ' ✓ %s\n' "$1" >> "${CONFIGURE_LOG:-/dev/null}"
_configure_ok=$((_configure_ok + 1))
_configure_total=$((_configure_total + 1))
}
log_step_fail() {
printf ' %b✗%b %s\n' "${RED:-}" "${NC:-}" "$1" >&2
printf ' ✗ %s\n' "$1" >> "${CONFIGURE_LOG:-/dev/null}"
_configure_fail=$((_configure_fail + 1))
_configure_total=$((_configure_total + 1))
}
_wire_critical_fail=0
_wire_optional_fail=0
# Required step: on failure count and continue
run_critical() {
set +e
"$@"
local rc=$?
set -e
if [ "$rc" -ne 0 ]; then
if ! "$@"; then
_wire_critical_fail=$((_wire_critical_fail + 1))
fi
return 0
}
# Nice-to-have step: never fails the overall run
run_optional() {
set +e
"$@"
local rc=$?
set -e
if [ "$rc" -ne 0 ]; then
if ! "$@"; then
_wire_optional_fail=$((_wire_optional_fail + 1))
fi
return 0
}
# Prompt for custom indexers (fzf TUI)
source "$_lib_dir/fzf-tui.sh"
main() {
INSTALL_DIR=$(find_install_directory || true)
if [ -z "${INSTALL_DIR:-}" ]; then
log_error "Could not find installation. Run setup first."
fi
# --- API helpers ---
source "$_lib_dir/api.sh"
safe_source "$INSTALL_DIR/.assemblrr-config"
load_branding "$INSTALL_DIR"
set -a
[ -f "$INSTALL_DIR/.env" ] && safe_source "$INSTALL_DIR/.env"
set +a
# --- Service configuration modules ---
source "$_lib_dir/arr.sh"
source "$_lib_dir/jellyfin.sh"
source "$_lib_dir/seerr.sh"
source "$_lib_dir/bazarr.sh"
API_HOST="${API_HOST:-127.0.0.1}"
RADARR_DOCKER_URL="${RADARR_DOCKER_URL:-http://radarr:7878}"
SONARR_DOCKER_URL="${SONARR_DOCKER_URL:-http://sonarr:8989}"
PROWLARR_DOCKER_URL="${PROWLARR_DOCKER_URL:-http://prowlarr:9696}"
if [ "${VPN_ENABLED:-n}" = "y" ] || [ "${VPN_ENABLED:-n}" = "Y" ]; then
QBITTORRENT_HOST="gluetun"
else
QBITTORRENT_HOST="qbittorrent"
fi
# --- Main ---
AUTH_USERNAME=$(cat "$INSTALL_DIR/secrets/auth_username.txt" 2>/dev/null || echo "$USER")
AUTH_PASSWORD=$(cat "$INSTALL_DIR/secrets/auth_password.txt" 2>/dev/null || echo "")
CONFIGURE_LOG="${CONFIGURE_LOG:-/tmp/${APP_NAME:-assemblrr}-configure-$(date '+%Y%m%d-%H%M%S').log}"
echo
_cfg_log_info "Wiring ${APP_DISPLAY_NAME} services..."
echo
_cfg_log_info "Wiring ${APP_DISPLAY_NAME} services..."
# API keys from config.xml (services write these on first start)
RADARR_API_KEY=""
SONARR_API_KEY=""
PROWLARR_API_KEY=""
if ! RADARR_API_KEY=$(read_api_key "radarr"); then
RADARR_API_KEY=""
_wire_critical_fail=$((_wire_critical_fail + 1))
fi
if ! SONARR_API_KEY=$(read_api_key "sonarr"); then
SONARR_API_KEY=""
_wire_critical_fail=$((_wire_critical_fail + 1))
fi
if ! PROWLARR_API_KEY=$(read_api_key "prowlarr"); then
PROWLARR_API_KEY=""
_wire_critical_fail=$((_wire_critical_fail + 1))
fi
# Drop key if API never becomes ready so later steps skip that service
if [ -n "$RADARR_API_KEY" ]; then
if ! wait_for_api "Radarr" "7878" "$RADARR_API_KEY"; then
if ! RADARR_API_KEY=$(read_api_key "radarr"); then
RADARR_API_KEY=""
_wire_critical_fail=$((_wire_critical_fail + 1))
fi
if ! SONARR_API_KEY=$(read_api_key "sonarr"); then
SONARR_API_KEY=""
_wire_critical_fail=$((_wire_critical_fail + 1))
fi
if ! PROWLARR_API_KEY=$(read_api_key "prowlarr"); then
PROWLARR_API_KEY=""
_wire_critical_fail=$((_wire_critical_fail + 1))
fi
if [ -n "$RADARR_API_KEY" ] && ! wait_for_api "Radarr" "7878" "$RADARR_API_KEY"; then
_wire_critical_fail=$((_wire_critical_fail + 1))
RADARR_API_KEY=""
fi
fi
if [ -n "$SONARR_API_KEY" ]; then
if ! wait_for_api "Sonarr" "8989" "$SONARR_API_KEY"; then
if [ -n "$SONARR_API_KEY" ] && ! wait_for_api "Sonarr" "8989" "$SONARR_API_KEY"; then
_wire_critical_fail=$((_wire_critical_fail + 1))
SONARR_API_KEY=""
fi
fi
if [ -n "$PROWLARR_API_KEY" ]; then
if wait_for_api "Prowlarr" "9696" "$PROWLARR_API_KEY" "/api/v1/system/status"; then
run_optional configure_indexers "$PROWLARR_API_KEY"
else
_wire_critical_fail=$((_wire_critical_fail + 1))
PROWLARR_API_KEY=""
if [ -n "$PROWLARR_API_KEY" ]; then
if wait_for_api "Prowlarr" "9696" "$PROWLARR_API_KEY" "/api/v1/system/status"; then
run_optional configure_indexers "$PROWLARR_API_KEY"
else
_wire_critical_fail=$((_wire_critical_fail + 1))
PROWLARR_API_KEY=""
fi
fi
fi
if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then
run_critical qbit_set_credentials
fi
if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then
run_critical qbit_set_credentials
fi
if [ -n "$RADARR_API_KEY" ]; then
run_critical configure_radarr "$RADARR_API_KEY"
run_optional add_arr_purge_hook "Radarr" "7878" "$RADARR_API_KEY"
fi
if [ "${USENET_ENABLED:-n}" = "y" ] || [ "${USENET_ENABLED:-n}" = "Y" ]; then
run_critical configure_sabnzbd
fi
if [ -n "$SONARR_API_KEY" ]; then
run_critical configure_sonarr "$SONARR_API_KEY"
run_optional add_arr_purge_hook "Sonarr" "8989" "$SONARR_API_KEY"
fi
if [ -n "$RADARR_API_KEY" ]; then
run_critical configure_radarr "$RADARR_API_KEY"
run_optional add_arr_purge_hook "Radarr" "7878" "$RADARR_API_KEY"
fi
if [ -n "$PROWLARR_API_KEY" ]; then
run_critical configure_prowlarr "$PROWLARR_API_KEY" "$RADARR_API_KEY" "$SONARR_API_KEY"
fi
if [ -n "$SONARR_API_KEY" ]; then
run_critical configure_sonarr "$SONARR_API_KEY"
run_optional add_arr_purge_hook "Sonarr" "8989" "$SONARR_API_KEY"
fi
if [ "${USENET_ENABLED:-n}" = "y" ] || [ "${USENET_ENABLED:-n}" = "Y" ]; then
if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then
run_critical arr_configure_sabnzbd
fi
fi
if [ -n "$PROWLARR_API_KEY" ]; then
run_critical configure_prowlarr "$PROWLARR_API_KEY" "$RADARR_API_KEY" "$SONARR_API_KEY"
if [ "${BYPARR_ENABLED:-n}" = "y" ] || [ "${BYPARR_ENABLED:-n}" = "Y" ]; then
run_optional prowlarr_sync_byparr_proxy "$PROWLARR_API_KEY"
fi
fi
if [ "${MEDIA_SERVICE:-}" = "jellyfin" ]; then
run_critical configure_jellyfin
run_optional configure_jellyfin_notifications
fi
# Bazarr after *arr (+ Jellyfin key when available): auto-subs for Sonarr/Radarr library
if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then
run_optional configure_subtitle_providers
run_critical configure_bazarr
fi
# Recyclarr before Seerr (profiles must exist for Seerr defaults)
run_critical configure_recyclarr
if [ -n "$RADARR_API_KEY" ]; then
run_critical relax_quality_sizes "Radarr" "7878" "$RADARR_API_KEY"
run_critical set_default_quality_profile "Radarr" "7878" "$RADARR_API_KEY" "lookup_radarr_profile"
fi
if [ -n "$SONARR_API_KEY" ]; then
run_critical relax_quality_sizes "Sonarr" "8989" "$SONARR_API_KEY"
run_critical set_default_quality_profile "Sonarr" "8989" "$SONARR_API_KEY" "lookup_sonarr_profile"
fi
# Existing files under media roots → *arr library (so Bazarr/Seerr see them)
if [ -n "$RADARR_API_KEY" ]; then
run_optional import_radarr_existing_media "$RADARR_API_KEY"
fi
if [ -n "$SONARR_API_KEY" ]; then
run_optional import_sonarr_existing_media "$SONARR_API_KEY"
fi
# After imports, pull *arr library into Bazarr
run_optional trigger_bazarr_library_sync
run_critical configure_seerr
echo
if [ "$_wire_critical_fail" -gt 0 ]; then
echo -e " ${RED}Wiring failed: ${_wire_critical_fail} required step(s)${NC}" | tee -a "$CONFIGURE_LOG"
if [ "$_configure_ok" -gt 0 ] || [ "$_configure_fail" -gt 0 ]; then
echo -e " ${YELLOW}${_configure_ok} ok, ${_configure_fail} failed (see markers above)${NC}" | tee -a "$CONFIGURE_LOG"
if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then
run_optional configure_subtitle_providers
run_critical configure_bazarr
fi
echo -e " ${YELLOW}Log: $CONFIGURE_LOG${NC}" | tee -a "$CONFIGURE_LOG"
echo
_cfg_log_info "Fix issues, then re-run: ${APP_CLI_NAME:-assemblrr} config apply"
echo
exit 1
fi
if [ "$_configure_fail" -gt 0 ] || [ "$_wire_optional_fail" -gt 0 ]; then
echo -e " ${GREEN}Required wiring succeeded${NC}" | tee -a "$CONFIGURE_LOG"
echo -e " ${YELLOW}Some optional steps had issues — log: $CONFIGURE_LOG${NC}" | tee -a "$CONFIGURE_LOG"
echo
else
echo -e " ${GREEN}All ${_configure_ok} steps succeeded${NC}" | tee -a "$CONFIGURE_LOG"
echo
fi
if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then
run_critical configure_recyclarr
if [ -n "$RADARR_API_KEY" ]; then
run_critical relax_quality_sizes "Radarr" "7878" "$RADARR_API_KEY"
run_critical set_default_quality_profile "Radarr" "7878" "$RADARR_API_KEY" "lookup_radarr_profile"
fi
if [ -n "$SONARR_API_KEY" ]; then
run_critical relax_quality_sizes "Sonarr" "8989" "$SONARR_API_KEY"
run_critical set_default_quality_profile "Sonarr" "8989" "$SONARR_API_KEY" "lookup_sonarr_profile"
fi
if [ -n "$RADARR_API_KEY" ]; then
run_optional import_radarr_existing_media "$RADARR_API_KEY"
fi
if [ -n "$SONARR_API_KEY" ]; then
run_optional import_sonarr_existing_media "$SONARR_API_KEY"
fi
run_optional trigger_bazarr_library_sync
run_critical configure_seerr
else
_cfg_log_info "Skipping Recyclarr & Seerr wiring (neither Radarr nor Sonarr API key available)"
fi
_cfg_log_info "Next steps:"
if [ "${MEDIA_SERVICE:-}" = "jellyfin" ]; then
_cfg_log_info " 1. Open Jellyfin at http://${API_HOST}:8096"
_cfg_log_info " 2. Open Seerr at http://${API_HOST}:5055 and request a movie"
_cfg_log_info " 3. It will download via qBittorrent; Bazarr grabs subtitles; Jellyfin shows both"
_cfg_log_info " 4. Bazarr UI: http://${API_HOST}:6767"
else
_cfg_log_info " 1. Open Seerr at http://${API_HOST}:5055"
_cfg_log_info " 2. Request a movie — it will download automatically via qBittorrent"
_cfg_log_info " 3. Bazarr downloads subtitles alongside media (http://${API_HOST}:6767)"
_cfg_log_info " 4. Your media service will pick up video + sidecar subs from your media folder"
fi
echo
if [ -n "$AUTH_USERNAME" ]; then
_cfg_log_info "Login credentials: $AUTH_USERNAME / (the password you set during setup)"
fi
echo
if [ "$_wire_critical_fail" -gt 0 ]; then
printf ' %bWiring failed: %s required step(s)%b\n' "${RED:-}" "${_wire_critical_fail}" "${NC:-}"
printf ' Wiring failed: %s required step(s)\n' "${_wire_critical_fail}" >> "$CONFIGURE_LOG"
if [ "$_configure_ok" -gt 0 ] || [ "$_configure_fail" -gt 0 ]; then
printf ' %b%s ok, %s failed (see markers above)%b\n' "${YELLOW:-}" "${_configure_ok}" "${_configure_fail}" "${NC:-}"
printf ' %s ok, %s failed (see markers above)\n' "${_configure_ok}" "${_configure_fail}" >> "$CONFIGURE_LOG"
fi
printf ' %bLog: %s%b\n\n' "${YELLOW:-}" "$CONFIGURE_LOG" "${NC:-}"
_cfg_log_info "Fix issues, then re-run: ${APP_CLI_NAME:-assemblrr} config apply"
echo
exit 1
fi
exit 0
if [ "$_configure_fail" -gt 0 ] || [ "$_wire_optional_fail" -gt 0 ]; then
printf ' %bRequired wiring succeeded%b\n' "${GREEN:-}" "${NC:-}"
printf ' %bSome optional steps had issues — log: %s%b\n' "${YELLOW:-}" "$CONFIGURE_LOG" "${NC:-}"
printf ' Required wiring succeeded (optional issues: %s)\n' "$_wire_optional_fail" >> "$CONFIGURE_LOG"
else
printf ' %b✓ All %s wiring steps succeeded%b\n' "${GREEN:-}" "${_configure_ok}" "${NC:-}"
printf ' All %s wiring steps succeeded\n' "${_configure_ok}" >> "$CONFIGURE_LOG"
fi
if [ "${ASSEMBLRR_FROM_SETUP:-0}" = "1" ]; then
exit 0
fi
echo
local ui_host="$API_HOST"
[ "$ui_host" = "127.0.0.1" ] && ui_host="localhost"
_cfg_log_info "Next steps:"
_cfg_log_info " 1. Open Jellyfin at http://${ui_host}:8096"
_cfg_log_info " 2. Open Seerr at http://${ui_host}:5055 and request a movie or show"
_cfg_log_info " 3. qBittorrent UI: http://${ui_host}:8081 | Bazarr UI: http://${ui_host}:6767"
if [ "${USENET_ENABLED:-n}" = "y" ] || [ "${USENET_ENABLED:-n}" = "Y" ]; then
_cfg_log_info " 4. SABnzbd UI: http://${ui_host}:8085"
fi
echo
if [ -n "$AUTH_USERNAME" ]; then
_cfg_log_info "Login credentials: $AUTH_USERNAME / (the password you set during setup)"
fi
exit 0
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi

59
bin/docker-install.sh Normal file → Executable file
View file

@ -1,22 +1,24 @@
#!/bin/bash
set -euo pipefail
# Docker installation helper — supports multiple distros
# SPDX-License-Identifier: GPL-3.0-or-later
# Docker installation helper — supports Ubuntu/Debian/derivatives, Arch, Fedora
# Called by setup.sh when Docker is not found
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_ROOT="$SCRIPT_DIR"
# Source shared library (safe_source, logging, colors)
if [ -f "$SCRIPT_DIR/../lib/core.sh" ]; then
APP_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
# shellcheck source=/dev/null
source "$APP_ROOT/lib/core.sh"
# shellcheck source=/dev/null
source "$APP_ROOT/lib/branding.sh"
elif [ -f "$SCRIPT_DIR/lib/core.sh" ]; then
# shellcheck source=/dev/null
source "$SCRIPT_DIR/lib/core.sh"
# shellcheck source=/dev/null
source "$SCRIPT_DIR/lib/branding.sh"
else
# Minimal fallback if lib modules are not available
log_error() { echo -e "\033[0;31m$1\033[0m" >&2; exit 1; }
log_info() { echo "$1"; }
log_success() { echo -e "\033[0;32m$1\033[0m"; }
@ -27,14 +29,13 @@ else
}
fi
# Source branding — use load_branding for validation + fallback
load_branding "$APP_ROOT"
detect_distro() {
if [ -f /etc/os-release ]; then
# shellcheck disable=SC1091
. /etc/os-release
echo "$ID"
echo "${ID:-unknown}"
elif [ -f /etc/arch-release ]; then
echo "arch"
elif [ -f /etc/fedora-release ]; then
@ -46,17 +47,32 @@ detect_distro() {
install_docker_debian() {
local distro_id="$1"
local codename
codename=$(lsb_release -cs 2>/dev/null || echo "unknown")
local repo_distro="$distro_id"
local codename=""
if [ -f /etc/os-release ]; then
# shellcheck disable=SC1091
. /etc/os-release
codename="${UBUNTU_CODENAME:-${VERSION_CODENAME:-}}"
fi
if [ -z "$codename" ]; then
codename=$(lsb_release -cs 2>/dev/null || echo "noble")
fi
# Linux Mint, Pop!_OS, and elementary OS track Ubuntu upstream repos on download.docker.com
case "$distro_id" in
linuxmint|pop|elementary) repo_distro="ubuntu" ;;
esac
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg lsb-release
sudo mkdir -p /etc/apt/keyrings
curl -fsSL "https://download.docker.com/linux/$distro_id/gpg" | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
curl -fsSL "https://download.docker.com/linux/$repo_distro/gpg" \
| sudo gpg --yes --batch --dearmor -o /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/$distro_id \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/$repo_distro $codename stable" \
| sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
@ -72,7 +88,10 @@ install_docker_arch() {
install_docker_fedora() {
sudo dnf install -y dnf-plugins-core
sudo dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo
# Fedora 41+ uses DNF5 (`addrepo --from-repofile=...`); older releases use `--add-repo`.
if ! sudo dnf config-manager addrepo --overwrite --from-repofile=https://download.docker.com/linux/fedora/docker-ce.repo 2>/dev/null; then
sudo dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo
fi
sudo dnf install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
}
@ -97,12 +116,14 @@ main() {
;;
esac
# Add user to docker group
sudo usermod -aG docker "$USER"
# Start Docker service
sudo systemctl enable docker
sudo systemctl start docker
if [ "$(ps -p 1 -o comm= 2>/dev/null || true)" = "systemd" ]; then
sudo systemctl enable docker
sudo systemctl start docker
else
log_info "Non-systemd environment detected — start dockerd or Docker Desktop manually if needed."
fi
log_success "Docker installed successfully!"
log_info "NOTE: You may need to log out and back in for group changes to take effect."
@ -110,4 +131,6 @@ main() {
exit 0
}
main
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi

960
bin/setup.sh Normal file → Executable file

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,7 @@
services:
# Jellyfin — open source media server (recommended)
# Jellyfin — open source media server (Jellyfin 12.4+)
jellyfin:
profiles: ["jellyfin"]
image: lscr.io/linuxserver/jellyfin:10.11.11
image: lscr.io/linuxserver/jellyfin:12.4ubu2604-ls60
container_name: jellyfin
environment:
- PUID=${PUID}
@ -27,61 +26,9 @@ services:
assemblrr_network:
ipv4_address: 172.60.0.11
# Emby — UNSUPPORTED optional profile (express/default is Jellyfin only).
emby:
profiles: ["emby"]
image: lscr.io/linuxserver/emby
container_name: emby
environment:
- PUID=${PUID}
- PGID=${PGID}
- TZ=${TZ}
- VERSION=docker
volumes:
- /etc/localtime:/etc/localtime:ro
- ${MEDIA_DIRECTORY}:/data
- ${INSTALL_DIRECTORY}/config/emby:/config
ports:
- 8096:8096
healthcheck:
test: ["CMD", "curl", "-sf", "http://127.0.0.1:8096/emby/System/Ping"]
interval: 10s
timeout: 5s
retries: 3
start_period: 30s
start_interval: 2s
restart: unless-stopped
networks:
assemblrr_network:
ipv4_address: 172.60.0.11
# Plex — UNSUPPORTED optional profile (express/default is Jellyfin only).
plex:
profiles: ["plex"]
image: lscr.io/linuxserver/plex
container_name: plex
network_mode: host
environment:
- PUID=${PUID}
- PGID=${PGID}
- TZ=${TZ}
- VERSION=docker
volumes:
- /etc/localtime:/etc/localtime:ro
- ${MEDIA_DIRECTORY}:/data
- ${INSTALL_DIRECTORY}/config/plex:/config
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-sf", "http://127.0.0.1:32400/identity"]
interval: 10s
timeout: 5s
retries: 3
start_period: 30s
start_interval: 2s
# qBittorrent — torrent client (ports added by overlay)
# qBittorrent — torrent client (ports/network added by vpn or direct-access overlay)
qbittorrent:
image: lscr.io/linuxserver/qbittorrent:5.2.3
image: lscr.io/linuxserver/qbittorrent:5.3.0
container_name: qbittorrent
environment:
- PUID=${PUID}
@ -103,7 +50,7 @@ services:
# Sonarr — TV show management and automation
sonarr:
image: lscr.io/linuxserver/sonarr:4.0.19.2979-ls321
image: lscr.io/linuxserver/sonarr:4.0.20.3014-ls6
container_name: sonarr
environment:
- PUID=${PUID}
@ -131,7 +78,7 @@ services:
# Radarr — movie management and automation
radarr:
image: lscr.io/linuxserver/radarr:6.3.0.10514-ls313
image: lscr.io/linuxserver/radarr:7.0.3.10918-ls328
container_name: radarr
environment:
- PUID=${PUID}
@ -159,7 +106,7 @@ services:
# Prowlarr — indexer management for *arr apps
prowlarr:
image: lscr.io/linuxserver/prowlarr:2.5.2.5491-ls156
image: lscr.io/linuxserver/prowlarr:3.0.2.5780-ls169
container_name: prowlarr
environment:
- PUID=${PUID}
@ -182,12 +129,9 @@ services:
assemblrr_network:
ipv4_address: 172.60.0.15
# Seerr — media request management (successor to Jellyseerr/Overseerr)
# Host port 5055 is published by seerr-gateway (not seerr) so DELETE /request
# can cancel in-flight *arr/qB grabs. Seerr stays on the Docker network only.
# Retirement: see docs/seerr-delete-request.md
# Seerr — media request management (internal; published via seerr-gateway:5055)
seerr:
image: ghcr.io/seerr-team/seerr:v3.4.1
image: ghcr.io/seerr-team/seerr:v3.5.2
container_name: seerr
init: true
environment:
@ -209,11 +153,11 @@ services:
assemblrr_network:
ipv4_address: 172.60.0.17
# Thin reverse proxy in front of Seerr: pass-through + delete-request queue drain.
# Authenticating reverse proxy in front of Seerr: pass-through + delete-request purge.
# TV: season-scoped via Sonarr when the request is a subset of remaining seasons.
# SEERR_DELETE_REQUEST_PURGE=0 disables intercept (stock Seerr semantics).
seerr-gateway:
image: python:3.12.14-alpine
image: python:3.12.16-alpine
container_name: seerr-gateway
environment:
- TZ=${TZ}
@ -255,10 +199,9 @@ services:
assemblrr_network:
ipv4_address: 172.60.0.24
# Recyclarr - automatically syncs TRaSH guides
# :latest is no longer published; pin a 8.x release (see recyclarr.dev).
# Recyclarr — automatically syncs TRaSH guides (:latest not published; pin 8.x)
recyclarr:
image: ghcr.io/recyclarr/recyclarr:8.7.1
image: ghcr.io/recyclarr/recyclarr:8.8.1
container_name: recyclarr
user: ${PUID}:${PGID}
environment:
@ -272,7 +215,7 @@ services:
assemblrr_network:
ipv4_address: 172.60.0.18
# Deletes under /data/media → purge *arr entry + qB torrent/files
# Deletes under /data/media -> purge *arr entry + qB / SABnzbd items
media-purge-watch:
image: assemblrr/media-purge-watch:local
pull_policy: build
@ -286,6 +229,7 @@ services:
- CONFIG_DIR=/config
- RADARR_URL=http://radarr:7878
- SONARR_URL=http://sonarr:8989
- SABNZBD_URL=http://sabnzbd:8080
- AUTH_USERNAME_FILE=/run/secrets/auth_username.txt
- AUTH_PASSWORD_FILE=/run/secrets/auth_password.txt
- MEDIA_PURGE_WATCH=${MEDIA_PURGE_WATCH:-1}
@ -303,7 +247,7 @@ services:
# Bazarr — automatic subtitle management (Sonarr/Radarr companion)
bazarr:
image: lscr.io/linuxserver/bazarr:1.6.0
image: lscr.io/linuxserver/bazarr:1.6.2
container_name: bazarr
environment:
- PUID=${PUID}

25
compose/byparr.yaml Normal file
View file

@ -0,0 +1,25 @@
# Overlay: Byparr Cloudflare challenge solver (drop-in FlareSolverr replacement for Prowlarr)
services:
byparr:
image: ghcr.io/thephaseless/byparr:3.1.1
container_name: byparr
environment:
- TZ=${TZ}
shm_size: "1gb"
tmpfs:
- /tmp:exec,mode=1777,size=1G
healthcheck:
test:
[
"CMD-SHELL",
"curl -sf http://127.0.0.1:8191/health >/dev/null || python3 -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8191/health', timeout=5)\"",
]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
start_interval: 2s
restart: unless-stopped
networks:
assemblrr_network:
ipv4_address: 172.60.0.26

View file

@ -1,5 +1,5 @@
# Overlay: direct access ports and networks for qBittorrent (no VPN)
# Usage: docker compose -f base.yaml -f direct-access.yaml --profile <media_service> up -d
# Usage: docker compose -f base.yaml -f direct-access.yaml up -d
services:
qbittorrent:

View file

@ -1,9 +1,8 @@
# Custom services overlay — NOT officially supported.
# Rename this file to custom.yaml to add extra containers. They join assemblrr_network
# but are not wired, upgraded, or bugfixed by assemblrr. Express/default support is
# Jellyfin + qBittorrent + Sonarr/Radarr/Prowlarr/Bazarr/Seerr/Recyclarr (+ optional VPN).
#
# Usage: docker compose -f base.yaml -f [direct-access|vpn].yaml -f custom.yaml --profile <media_service> up -d
# (.30+ IPs reserved for custom services) and are left untouched by assemblrr upgrades.
# Official core stack: Jellyfin + qBittorrent + Sonarr/Radarr/Prowlarr/Bazarr/Seerr/Recyclarr
# + optional overlays (vuetorrent, gpu-intel/gpu-nvidia, byparr, usenet, vpn).
networks:
default:
@ -12,11 +11,48 @@ networks:
services:
# --- Emby (optional self-managed custom service; conflicts with Jellyfin 8096 unless remapped) ---
# Web UI: http://<host>:8097
# emby:
# image: lscr.io/linuxserver/emby:4.9.3.0
# container_name: emby
# environment:
# - PUID=${PUID}
# - PGID=${PGID}
# - TZ=${TZ}
# volumes:
# - /etc/localtime:/etc/localtime:ro
# - ${MEDIA_DIRECTORY}:/data
# - ${INSTALL_DIRECTORY}/config/emby:/config
# ports:
# - 8097:8096
# restart: unless-stopped
# networks:
# assemblrr_network:
# ipv4_address: 172.60.0.30
# --- Plex (optional self-managed custom service; uses host networking for DLNA/claim) ---
# Web UI: http://<host>:32400/web
# plex:
# image: lscr.io/linuxserver/plex:1.43.0
# container_name: plex
# network_mode: host
# environment:
# - PUID=${PUID}
# - PGID=${PGID}
# - TZ=${TZ}
# - VERSION=docker
# volumes:
# - /etc/localtime:/etc/localtime:ro
# - ${MEDIA_DIRECTORY}:/data
# - ${INSTALL_DIRECTORY}/config/plex:/config
# restart: unless-stopped
# --- Lidarr — Music management and automation ---
# Requires: Prowlarr indexer, qBittorrent download client (configure manually)
# Requires: Prowlarr indexer + download client (configure manually in Lidarr UI)
# Web UI: http://<host>:8686
# lidarr:
# image: lscr.io/linuxserver/lidarr:3.1.0.4875-ls39
# image: lscr.io/linuxserver/lidarr:3.1.0
# container_name: lidarr
# environment:
# - PUID=${PUID}
@ -31,68 +67,20 @@ services:
# restart: unless-stopped
# networks:
# assemblrr_network:
# ipv4_address: 172.60.0.20
# ipv4_address: 172.60.0.32
# --- SABnzbd — Usenet downloader ---
# Requires: A paid Usenet provider (Newshosting, Eweka, etc.)
# Note: Routes through VPN if enabled (same as qBittorrent)
# Web UI: http://<host>:8080
# sabnzbd:
# image: lscr.io/linuxserver/sabnzbd:5.1.0-ls267
# container_name: sabnzbd
# --- Komodo Periphery — connect this host to a Komodo dashboard (see docs/komodo.md) ---
# periphery:
# image: ghcr.io/moghtech/komodo-periphery:1.19
# container_name: komodo-periphery
# environment:
# - PUID=${PUID}
# - PGID=${PGID}
# - TZ=${TZ}
# volumes:
# - /etc/localtime:/etc/localtime:ro
# - ${MEDIA_DIRECTORY}:/data
# - ${INSTALL_DIRECTORY}/config/sabnzbd:/config
# restart: unless-stopped
# networks:
# assemblrr_network:
# ipv4_address: 172.60.0.21
# --- Bazarr ---
# Bazarr ships in compose/base.yaml (auto-wired by config.sh). Do not re-add it here.
# --- Portainer — optional Docker UI (not part of the default stack; prefer assemblrr CLI) ---
# Web UI: http://localhost:9000
# portainer:
# image: portainer/portainer-ce
# container_name: portainer
# ports:
# - 9000:9000
# volumes:
# - /etc/localtime:/etc/localtime:ro
# - /var/run/docker.sock:/var/run/docker.sock:ro
# - ${INSTALL_DIRECTORY}/config/portainer:/data
# restart: unless-stopped
# networks:
# assemblrr_network:
# ipv4_address: 172.60.0.16
# --- Watchtower — Automatic container update notifications ---
# MONITOR_ONLY=true: Notifies when updates are available, does NOT auto-update
# To enable notifications, set WATCHTOWER_NOTIFICATION_URL (see: https://containrrr.dev/shoutrrr/v0.5/services/)
# Examples:
# Discord: discord://token@id
# Telegram: telegram://bottoken@ChatID
# Slack: slack://token@channel
# Email: smtp://user:pass@host:port/?from=addr&to=addr
# watchtower:
# image: nickfedor/watchtower
# container_name: watchtower
# environment:
# - WATCHTOWER_CLEANUP=true
# - TZ=${TZ}
# - WATCHTOWER_SCHEDULE=0 0 4 * * *
# - WATCHTOWER_MONITOR_ONLY=true
# - WATCHTOWER_NOTIFICATIONS=shoutrrr
# - WATCHTOWER_NOTIFICATION_URL=discord://token@id
# volumes:
# - /var/run/docker.sock:/var/run/docker.sock
# - ${INSTALL_DIRECTORY}:${INSTALL_DIRECTORY}
# ports:
# - 8120:8120
# restart: unless-stopped
# networks:
# assemblrr_network:
# ipv4_address: 172.60.0.23
# ipv4_address: 172.60.0.33

5
compose/gpu-intel.yaml Normal file
View file

@ -0,0 +1,5 @@
# Overlay: Intel Quick Sync / AMD VAAPI hardware transcoding for Jellyfin
services:
jellyfin:
devices:
- /dev/dri:/dev/dri

13
compose/gpu-nvidia.yaml Normal file
View file

@ -0,0 +1,13 @@
# Overlay: NVIDIA NVENC/NVDEC hardware transcoding for Jellyfin
services:
jellyfin:
environment:
- NVIDIA_VISIBLE_DEVICES=all
- NVIDIA_DRIVER_CAPABILITIES=all
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]

View file

@ -1,5 +1,5 @@
# Built on the host so inotify/curl/jq are in the image, not apk'd at every start.
FROM alpine:3.21
FROM alpine:3.24.4
RUN apk add --no-cache bash curl jq inotify-tools
WORKDIR /scripts
ENTRYPOINT ["bash"]

View file

@ -1,5 +1,5 @@
# Built on the host (not through Gluetun) so Alpine packages never go out the VPN.
FROM alpine:3.21
FROM alpine:3.24.4
RUN apk add --no-cache bash curl jq docker-cli
WORKDIR /scripts
ENTRYPOINT ["bash"]

26
compose/usenet.yaml Normal file
View file

@ -0,0 +1,26 @@
# Overlay: SABnzbd Usenet downloader (wired automatically into Sonarr/Radarr/Prowlarr)
services:
sabnzbd:
image: lscr.io/linuxserver/sabnzbd:5.1.3
container_name: sabnzbd
environment:
- PUID=${PUID}
- PGID=${PGID}
- TZ=${TZ}
volumes:
- /etc/localtime:/etc/localtime:ro
- ${MEDIA_DIRECTORY}:/data
- ${INSTALL_DIRECTORY}/config/sabnzbd:/config
ports:
- 8085:8080
healthcheck:
test: ["CMD", "curl", "-sf", "http://127.0.0.1:8080/api?mode=version"]
interval: 10s
timeout: 5s
retries: 3
start_period: 30s
start_interval: 2s
restart: unless-stopped
networks:
assemblrr_network:
ipv4_address: 172.60.0.25

View file

@ -1,5 +1,5 @@
# Overlay: VPN via Gluetun — routes qBittorrent through VPN
# Usage: docker compose -f base.yaml -f vpn.yaml --profile <media_service> up -d
# Usage: docker compose -f base.yaml -f vpn.yaml up -d
services:
gluetun:
@ -65,7 +65,7 @@ services:
restart: unless-stopped
deunhealth:
image: qmcgaw/deunhealth:v0.3.0
image: qmcgaw/deunhealth@sha256:db1e4fcd3aceeb0da34a83f7a8a5432df586e6d0388ddb6ad8dd7b479e4aa25d
container_name: deunhealth
network_mode: "none"
environment:

5
compose/vuetorrent.yaml Normal file
View file

@ -0,0 +1,5 @@
# Overlay: VueTorrent alternate WebUI mod for LinuxServer.io qBittorrent
services:
qbittorrent:
environment:
- DOCKER_MODS=ghcr.io/vuetorrent/vuetorrent-lsio-mod:2.37.0

View file

@ -10,19 +10,25 @@ assemblrr services generate API keys during initial boot. Extract them using the
| Service | Port | Config / Secret Location | Auth Header / Query Parameter |
| :--- | :--- | :--- | :--- |
| **Radarr** | `7878` | `config/radarr/config.xml` | `?apikey=$KEY` or `X-Api-Key: $KEY` |
| **Sonarr** | `8989` | `config/sonarr/config.xml` | `?apikey=$KEY` or `X-Api-Key: $KEY` |
| **Prowlarr** | `9696` | `config/prowlarr/config.xml` | `?apikey=$KEY` or `X-Api-Key: $KEY` |
| **Bazarr** | `6767` | `secrets/bazarr_api_key.txt` | `?apikey=$KEY` or `X-API-KEY: $KEY` |
| **Radarr** | `7878` | `config/radarr/config.xml` | `X-Api-Key: $KEY` |
| **Sonarr** | `8989` | `config/sonarr/config.xml` | `X-Api-Key: $KEY` |
| **Prowlarr** | `9696` | `config/prowlarr/config.xml` | `X-Api-Key: $KEY` |
| **Bazarr** | `6767` | `secrets/bazarr_api_key.txt` | `X-API-KEY: $KEY` |
| **Seerr** | `5055` | `config/seerr/settings.json` | `X-Api-Key: $KEY` |
| **Jellyfin** | `8096` | `secrets/jellyfin_api_key.txt` | `X-Emby-Token: $KEY` or `Authorization: MediaBrowser Token="$KEY"` |
| **qBittorrent** | `8080` | `config/qbittorrent/` | Cookie-based auth via `/api/v2/auth/login` |
| **Jellyfin** | `8096` | `secrets/jellyfin_api_key.txt` | `Authorization: MediaBrowser Client="cli", Device="cli", DeviceId="cli", Version="1.0", Token="$KEY"` |
| **qBittorrent** | `8081` | `secrets/auth_*.txt` | Cookie-based auth (`SID` / `QBT_SID_*`) via `/api/v2/auth/login` |
| **SABnzbd** *(opt.)* | `8085` | `config/sabnzbd/sabnzbd.ini` | `?apikey=$KEY` (`mode=...&output=json`) |
| **Byparr** *(opt.)* | `8191` (internal) | — | Unauthenticated HTTP challenge proxy inside `assemblrr_network` |
> [!NOTE]
> Jellyfin 12.4 removed legacy `X-Emby-Token` defaults in favor of standard `Authorization: MediaBrowser ... Token="..."` headers. assemblrr uses `Authorization: MediaBrowser` across all scripts and setup modules.
### Quick Key Extraction (Bash Snippet)
```bash
RADARR_KEY=$(sed -n 's/.*<ApiKey>\(.*\)<\/ApiKey>.*/\1/p' config/radarr/config.xml | head -1)
SONARR_KEY=$(sed -n 's/.*<ApiKey>\(.*\)<\/ApiKey>.*/\1/p' config/sonarr/config.xml | head -1)
PROWLARR_KEY=$(sed -n 's/.*<ApiKey>\(.*\)<\/ApiKey>.*/\1/p' config/prowlarr/config.xml | head -1)
SABNZBD_KEY=$(sed -n 's/^[[:space:]]*api_key[[:space:]]*=[[:space:]]*//p' config/sabnzbd/sabnzbd.ini | head -1)
BAZARR_KEY=$(cat secrets/bazarr_api_key.txt 2>/dev/null)
JELLYFIN_KEY=$(cat secrets/jellyfin_api_key.txt 2>/dev/null)
```
@ -34,60 +40,60 @@ JELLYFIN_KEY=$(cat secrets/jellyfin_api_key.txt 2>/dev/null)
### 1. Quality Profiles
* **List all profiles:**
```bash
curl -s "http://127.0.0.1:7878/api/v3/qualityprofile?apikey=$RADARR_KEY" | jq '.[] | {id: .id, name: .name}'
curl -s -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/qualityprofile" | jq '.[] | {id: .id, name: .name}'
```
* **Inspect a specific profile:**
```bash
curl -s "http://127.0.0.1:7878/api/v3/qualityprofile/1?apikey=$RADARR_KEY" | jq .
```
* **Delete an orphaned profile:**
```bash
curl -s -X DELETE "http://127.0.0.1:7878/api/v3/qualityprofile/8?apikey=$RADARR_KEY"
curl -s -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/qualityprofile/1" | jq .
```
### 2. Media Management & Hardlinks
* **Inspect Media Management config:**
```bash
curl -s "http://127.0.0.1:7878/api/v3/config/mediamanagement?apikey=$RADARR_KEY" | jq '{copyUsingHardlinks, recycleBin, recycleBinCleanupDays}'
```
* **Disable recycle bin and verify hardlinks:**
```bash
curl -s "http://127.0.0.1:7878/api/v3/config/mediamanagement?apikey=$RADARR_KEY" \
| jq '.copyUsingHardlinks = true | .recycleBin = "" | .recycleBinCleanupDays = 0' \
| curl -s -X PUT "http://127.0.0.1:7878/api/v3/config/mediamanagement?apikey=$RADARR_KEY" -H "Content-Type: application/json" -d @-
curl -s -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/config/mediamanagement" | jq '{copyUsingHardlinks, recycleBin, recycleBinCleanupDays}'
```
### 3. Root Folders
* **List root folders and default profile IDs:**
```bash
curl -s "http://127.0.0.1:7878/api/v3/rootfolder?apikey=$RADARR_KEY" | jq .
```
### 4. Queue & Active Downloads
### 3. Queue & Active Downloads
* **Inspect download queue:**
```bash
curl -s "http://127.0.0.1:7878/api/v3/queue?apikey=$RADARR_KEY" | jq '.records[] | {id: .id, title: .title, status: .status, downloadId: .downloadId}'
curl -s -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/queue" | jq '.records[] | {id: .id, title: .title, status: .status, downloadId: .downloadId}'
```
* **Drain a specific queue item from *arr and download client:**
```bash
curl -s -X DELETE "http://127.0.0.1:7878/api/v3/queue/123?apikey=$RADARR_KEY&removeFromClient=true&blocklist=false"
curl -s -X DELETE -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/queue/123?removeFromClient=true&blocklist=false"
```
---
## Seerr & Seerr Gateway Recipes
`seerr-gateway` sits on port `5055` as a sidecar proxying Overseas/Jellyseerr.
`seerr-gateway` sits on port `5055` and verifies caller permissions via `GET /api/v1/auth/me` before intercepting `DELETE /api/v1/request/:id`.
* **Check gateway health & upstream readiness:**
```bash
curl -s http://127.0.0.1:5055/_assemblrr/ready | jq .
```
* **List pending/approved requests:**
```bash
curl -s "http://127.0.0.1:5055/api/v1/request?take=20" -H "X-Api-Key: $SEERR_KEY" | jq '.results[] | {id: .id, type: .type, media: .media.tmdbId, status: .status}'
```
* **Test request-delete cascade:**
---
## Optional Overlays: SABnzbd & Byparr
* **Check SABnzbd version and queue (when `USENET_ENABLED=y`):**
```bash
curl -i -X DELETE "http://127.0.0.1:5055/api/v1/request/42" -H "X-Api-Key: $SEERR_KEY"
curl -s "http://127.0.0.1:8085/api?mode=queue&output=json&apikey=$SABNZBD_KEY" | jq .
```
* **Check Byparr health (inside container network when `BYPARR_ENABLED=y`):**
```bash
docker exec byparr python3 -c "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8191/health').read().decode())"
```
* **Inspect Prowlarr indexer proxies (`byparr` tag):**
```bash
curl -s -H "X-Api-Key: $PROWLARR_KEY" "http://127.0.0.1:9696/api/v1/indexerProxy" | jq .
```
*(Responses will include `X-Assemblrr-Purge-Detail` headers indicating queue drains and media deletions.)*
---
@ -101,22 +107,19 @@ JELLYFIN_KEY=$(cat secrets/jellyfin_api_key.txt 2>/dev/null)
```bash
docker exec recyclarr recyclarr list quality-profiles radarr
docker exec recyclarr recyclarr list quality-profiles sonarr
docker exec recyclarr recyclarr list custom-formats radarr
```
---
## Official API Documentation Links
| Service | Official Documentation | Notes |
| :--- | :--- | :--- |
| **Radarr** | https://radarr.video/docs/api/ | OpenAPI / Swagger UI |
| **Sonarr** | https://sonarr.tv/docs/api/ | v3 OpenAPI spec (covers Sonarr v3 and v4) |
| **Prowlarr** | https://prowlarr.com/docs/api/ | OpenAPI / Swagger UI |
| **Bazarr** | https://wiki.bazarr.media/ | Companion subtitle manager API |
| **Seerr** | https://api-docs.overseerr.dev/ | Jellyseerr / Overseerr Swagger UI |
| **Jellyfin** | https://api.jellyfin.org/ | OpenAPI stable spec |
| **qBittorrent** | https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1) | Web API Reference |
| **Servarr Wiki** | https://wiki.servarr.com/ | Servarr community configuration & troubleshooting |
| Service | Official Documentation |
| :--- | :--- |
| **Radarr** | https://radarr.video/docs/api/ |
| **Sonarr** | https://sonarr.tv/docs/api/ |
| **Prowlarr** | https://prowlarr.com/docs/api/ |
| **Bazarr** | https://wiki.bazarr.media/ |
| **Seerr** | https://api-docs.overseerr.dev/ |
| **Jellyfin** | https://api.jellyfin.org/ |
| **qBittorrent** | https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1) |
| **SABnzbd** | https://sabnzbd.org/wiki/configuration/4.3/api |

37
docs/komodo.md Normal file
View file

@ -0,0 +1,37 @@
# Running assemblrr with Komodo
[Komodo](https://komo.do/) can deploy and monitor assemblrr's Compose stack once `setup` (or a manual `.env` + `secrets/` setup) has initialized the install directory.
## How Compose Overlays Fit Komodo
assemblrr keeps its stack modular under `compose/`:
- **Always required:** `compose/base.yaml` + **one** network mode (`compose/vpn.yaml` or `compose/direct-access.yaml`)
- **Optional feature overlays:**
- `compose/vuetorrent.yaml` (`VUETORRENT_ENABLED=y`)
- `compose/gpu-intel.yaml` (`GPU_TRANSCODING=intel`) or `compose/gpu-nvidia.yaml` (`GPU_TRANSCODING=nvidia`)
- `compose/byparr.yaml` (`BYPARR_ENABLED=y`)
- `compose/usenet.yaml` (`USENET_ENABLED=y`)
- **Custom services:** `compose/custom.yaml` (always appended last; see [`compose/examples/custom.yaml.example`](../compose/examples/custom.yaml.example) for a `komodo-periphery` service block on `.33`)
## Recommended Komodo Stack Configuration
1. Run `assemblrr` setup (or `restore`) once on the target host so `.env`, `secrets/`, `config/`, and `scripts/` exist with proper `PUID`/`PGID` permissions.
2. Point a **Komodo Stack** at your install directory (e.g. `~/assemblrr`) with **File Paths** matching your enabled overlays, in order:
```text
compose/base.yaml
compose/vpn.yaml
compose/vuetorrent.yaml
compose/gpu-intel.yaml
compose/byparr.yaml
compose/usenet.yaml
compose/custom.yaml
```
*(Omit any overlay you did not enable, or replace `compose/vpn.yaml` with `compose/direct-access.yaml`.)*
3. Configure **Env File Path**: `.env` (or paste generated `.env` values into Komodo's environment editor without duplicating secret files from `secrets/`).
4. Keep **Project Directory** set to the install root (`INSTALL_DIRECTORY`) so relative secret and config paths resolve correctly.
## Upgrades & Re-wiring
- Use `assemblrr upgrade --skip-stack` (from CLI) if you let Komodo handle `docker compose up -d --build`, or run `assemblrr upgrade` normally and let Komodo re-sync state.
- Whenever you add a service or change API credentials, run `assemblrr config apply` to re-run idempotent `*arr` / Jellyfin / Bazarr / Seerr / SABnzbd wiring.

View file

@ -1,8 +1,8 @@
# Seerr “Delete request” → media purge
assemblrr product intent: when a user deletes a Seerr **request**, the stack
should also remove **that request’s** library files under `media/` and the
matching qBittorrent torrent/data under `torrents/` (hardlink-aware).
assemblrr product intent: when an authorized user deletes a Seerr **request**, the stack
should also remove **that request’s** library files under `media/` and the matching download
items under `torrents/` / `usenet/` (hardlink-aware).
- **Movies:** the whole title.
- **TV:** only the seasons on that request. Other seasons of the same show stay,
@ -20,64 +20,47 @@ listens only on the Docker network. Almost all traffic is proxied unchanged.
On **`DELETE /api/v1/request/:id`** only (when purge is enabled):
1. `GET /api/v1/request/:id` — capture linked `media.id`, `is4k`, type, and
requested season numbers (same auth headers as the client).
2. **Drain the *arr download queue first** (while the title still exists):
`DELETE /api/v3/queue/{id}?removeFromClient=true`. That is how an in-progress
grab is cancelled — Radarr/Sonarr already know the torrent hash. Queue drain
is best-effort (missing API key or empty queue is not a hard failure).
3. Purge files:
1. `GET /api/v1/auth/me` — verify caller identity & Seerr permissions (`ADMIN` or `MANAGE_REQUESTS`)
before invoking any privileged `*arr` APIs (prevents confused-deputy deletion). Non-admin users
cancelling their own **pending** request pass straight through to Seerr `DELETE` without touching
downloaded files; unauthorized attempts fail closed (`401`/`403`).
2. `GET /api/v1/request/:id` — capture linked `media.id`, `is4k`, type, and
requested season numbers (fails closed with `502` on upstream 5xx).
3. **Drain the *arr download queue first** (while the title still exists):
`DELETE /api/v3/queue/{id}?removeFromClient=true`.
4. Purge files:
- **Movie**, or a TV request that covers every remaining on-disk/monitored
season (specials count as remaining) → `DELETE /api/v1/media/:mediaId/file?is4k=…`
(Seerr → *arr `deleteFiles` → assemblrr purge hooks / qB).
(Seerr → *arr `deleteFiles` → assemblrr purge hooks / qB / SABnzbd).
- **TV subset of seasons** → Sonarr `DELETE /episodefile/{id}` for those
seasons only, then unmonitor them. Seerr title-level file-delete is
**not** called, so `/data/media/tv/Show` is not wiped. `media-purge-watch`
then season-scopes qB cleanup when that season folder empties.
4. `DELETE /api/v1/request/:id` — drop the request row (response returned to
the client).
If media was never linked, step 2 is skipped; the request is still deleted.
Auth failures on step 1 are returned to the client with no deletes.
If a TV request has no season list, the Sonarr API key is missing, or a
season-scoped Sonarr call fails, the gateway returns **502** and does
**not** delete the request (it never title-deletes on uncertainty).
then season-scopes download cleanup when that season folder empties.
5. `DELETE /api/v1/request/:id` — drop the request row and return the response.
| Piece | Role |
|------|------|
| `scripts/seerr-gateway.py` | Reverse proxy + request-delete intercept (season-aware for TV) |
| `compose/base.yaml` → `seerr-gateway` | Publishes 5055; `seerr` is internal only; reads Sonarr API key |
| `scripts/arr-purge-hook.sh` / `media-purge.sh` | qB + disk cleanup; `--seasons` for partial TV |
| `scripts/media-purge-watch.sh` | inotify: empty season folder → `--seasons` purge (even if other seasons are only monitored/downloading); movie / series-root delete → title purge |
| `scripts/seerr-gateway.py` | Authenticating reverse proxy + request-delete intercept |
| `compose/base.yaml` → `seerr-gateway` | Publishes 5055; `seerr` is internal only; reads Sonarr/Radarr API keys |
| `scripts/arr-purge-hook.sh` / `media-purge.sh` | qB + SABnzbd + disk cleanup; `--seasons` for partial TV |
| `scripts/media-purge-watch.sh` | inotify: empty season folder → `--seasons` purge; movie / series-root delete → title purge |
### Title-level delete in Seerr (not season-safe)
Seerr’s own **bulk delete / “remove from library” / delete files** on a TV
card is `DELETE /api/v1/media/:id/file`. That always removes the **entire
series** from Sonarr (`deleteFiles: true`). assemblrr does **not** intercept
that path: it means “this title”.
When a title is deleted, library files are deleted immediately to instantly reclaim disk space. The series-delete hook then removes the matching qB torrent **and** leftover folders under `torrents/tv` / `torrents/movies` (Completed Download Handling often drops the qB row first, which used to leave the download directory behind).
### Purge safety (qB)
### Purge safety (`media-purge.sh`)
`media-purge.sh` prefers under-delete over collateral damage:
1. *arr **queue + history** download hashes that still exist in qB. The hash is
identity — a live grab named `The Avengers 2012 REPACK…` is removed even
though it does not look like `The Avengers (2012)`.
2. Title + year match on torrent name / content path. `(2012)` and `2012` are
the same year; indexer prefixes (`www.UIndex.org - …`) are allowed; the
token after the title must be that year so `Avengers Age of Ultron 2015`
and `It Comes at Night 2017` stay put.
1. *arr **queue + history** download IDs/hashes that still exist in qBittorrent or SABnzbd (`SABnzbd_nzo_*`).
2. Title + year match on release name / content path. `(2016)` and `2016` are
the same year; indexer domain prefixes (`indexer.example - …`) are allowed; the
token after the title must be that year so `Alpha Film Sequel Extended (2022)`
or `Nova Comes at Night 2017` stay untouched for `Alpha Film (2016)` or `Nova (2017)`.
3. Refuse ambiguous multi-matches on the name step. Short keys (`Oz`) skipped.
4. **Season purge:** torrent must name one of the requested seasons (`S01` /
`Season 1`) and must **not** also name another season. Packs like
`Show.S01.S02.COMPLETE` and ranges like `Show.S01-03` are left alone
when deleting S01 only. A torrent with no season token is left alone
on the name step (queue/history hashes for that season are still removed).
`Season 1` / `Specials`) with strict token boundaries (ignoring codecs like `DTS5.1` or `x265`)
and must **not** also name another season. Packs like `Sample.Show.S01.S02.COMPLETE`
and ranges like `Sample.Show.S01-03` are left alone when deleting S01 only.
See `media-purge.sh --match-self-test`.
See `tests/unit/test_media_purge_match.sh`.
Env:
@ -87,57 +70,18 @@ Env:
| `MEDIA_PURGE_WATCH` | `1` | `1` = inotify watcher on library video deletes; `0` = disable watcher only |
| `SEERR_UPSTREAM` | `http://seerr:5055` | Upstream Seerr (container) |
| `SONARR_URL` | `http://sonarr:8989` | Used by the gateway for TV season deletes + queue drain |
| `SONARR_CONFIG` | `/config/sonarr/config.xml` | API key source when `SONARR_API_KEY` is unset |
| `RADARR_URL` | `http://radarr:7878` | Used by the gateway to drain in-progress movie grabs |
| `RADARR_CONFIG` | `/config/radarr/config.xml` | API key source when `RADARR_API_KEY` is unset |
Debug response headers on intercepted deletes:
## When Seerr adds this natively
- `X-Assemblrr-Request-Delete-Purge: 1`
- `X-Assemblrr-Purge-Detail: …` (e.g. `queue_movie:1:1;media_file_deleted:7:204`,
`seasons_deleted:6:10:1:3`, `no_media`)
Health (gateway only, not Seerr):
- `GET /_assemblrr/health` — process up
- `GET /_assemblrr/ready` — upstream Seerr public settings reachable
## Why not a Seerr fork
Forking Seerr for one product preference is ongoing merge cost. The gateway
owns only this behavior and stays a small managed script.
## When Seerr adds this natively — **must adjust**
If a future Seerr/Overseerr release deletes media (or offers a setting to) on
request delete, **this gateway intercept becomes wrong or redundant** (double
delete races, confusing semantics). Do the following:
1. **Confirm** upstream behavior in Seerr release notes / source:
- Does `DELETE /api/v1/request/:id` call *arr with `deleteFiles`?
- Is it always on, or a setting?
- Is it season-scoped for TV?
2. **Short term:** set `SEERR_DELETE_REQUEST_PURGE=0` in the install `.env`
(or compose environment) and restart `seerr-gateway`. Traffic stays on 5055;
intercept is off. Verify once that stock delete-request still meets product
intent with your purge hooks.
3. **Long term (preferred once native behavior is permanent and correct):**
- Remove the `seerr-gateway` service from `compose/base.yaml`
- Publish `5055:5055` on `seerr` again
- Drop `scripts/seerr-gateway.py` from `lib/managed_files.sh` and the repo
- Update this doc, `lib/services.sh` (catalog back to `seerr|Seerr|5055`),
`docs/uninstall.md`, and live tests that assert gateway headers
- Remove any mention of `SEERR_DELETE_REQUEST_PURGE`
4. **Do not** leave the intercept enabled “just in case” after Seerr already
purges on request delete — that can double-call *arr delete paths.
Track ownership: this file and `scripts/seerr-gateway.py` header comment.
If a future Seerr release natively deletes media on request delete, set `SEERR_DELETE_REQUEST_PURGE=0`
or remove `seerr-gateway` from `compose/base.yaml` and publish `5055:5055` directly on `seerr`.
## Tests
```bash
# Offline unit (mock Seerr + mock Sonarr):
python3 scripts/seerr-gateway.py --self-test
# Offline gateway unit suite (mock Seerr + Sonarr + Radarr):
python3 -m unittest tests/unit/test_seerr_gateway_suite.py -v
# or
./tests/unit/test_seerr_gateway.sh
@ -148,7 +92,3 @@ python3 scripts/seerr-gateway.py --self-test
# Live (opt-in; real install):
ASSEMBLRR_ALLOW_LIVE_TEST=1 ./tests/integration/media_purge_e2e.sh
```
The live suite includes **delete request through the gateway** → full cascade
for a **movie**, and documents that stock Seerr request-delete alone does not
wipe files.

View file

@ -2,7 +2,7 @@
assemblrr uses [Recyclarr](https://recyclarr.dev/) to sync [TRaSH Guides](https://trash-guides.info/) quality profiles and custom formats into Radarr and Sonarr.
**Subtitles:** Bazarr is wired separately (not via Recyclarr). On first install and every `assemblrr upgrade`, assemblrr applies [TRaSH Bazarr suggested scoring](https://trash-guides.info/Bazarr/Bazarr-suggested-scoring/) (series min 90, movies 80, auto-sync 96/86). If any selected subtitle language is not English, those minimum scores drop to 70/50: OpenSubtitles.com rarely hash-matches non-English WEB-DL releases, and TRaSH 90/80 would skip them. Subsync still retimes anything below the sync thresholds. Subtitle languages are a two-step fzf: multi-select what to download, then (if more than one) which Jellyfin should prefer. Providers are chosen interactively from the running Bazarr image (fzf multi-select; nothing enabled unless you pick it). OpenSubtitles.com is enabled only when you saved credentials during setup. Greek also enables the `greeksubs` provider unless you confirmed a provider list without it.
**Subtitles:** Bazarr is wired separately (not via Recyclarr). On first install and every `assemblrr upgrade`, assemblrr applies [TRaSH Bazarr suggested scoring](https://trash-guides.info/Bazarr/Bazarr-suggested-scoring/) (series min 90, movies 80, auto-sync 96/86). If any selected subtitle language is not English, those minimum scores drop to 70/50: OpenSubtitles.com rarely hash-matches non-English WEB-DL releases, and TRaSH 90/80 would skip them. Subsync still retimes anything below the sync thresholds. Subtitle languages are a two-step fzf: multi-select what to download, then (if more than one) which Jellyfin should prefer. Providers are chosen interactively from the running Bazarr image (fzf multi-select; nothing auto-enabled beyond OpenSubtitles.com when credentials were explicitly saved).
**Both resolutions and both movie sources are always installed** as assemblrr-named profiles:

View file

@ -13,7 +13,7 @@ root-owned; plain `rm -rf` then fails — use the Docker removal step in Option
| Component | Default location |
|---|---|
| Containers | `jellyfin`/`emby`/`plex` (your choice), `qbittorrent`, `sonarr`, `radarr`, `prowlarr`, `bazarr`, `seerr`, `seerr-gateway`, `media-purge-watch`, `recyclarr` — plus `gluetun`, `deunhealth`, `vpn-watchdog` when VPN is enabled; older installs may still have `portainer` |
| Containers | `jellyfin`, `qbittorrent`, `sonarr`, `radarr`, `prowlarr`, `bazarr`, `seerr`, `seerr-gateway`, `media-purge-watch`, `recyclarr` — plus `sabnzbd` (`usenet`), `byparr` (`byparr`), and `gluetun`/`deunhealth`/`vpn-watchdog` (`vpn`) when enabled; older installs may have `portainer`/`emby`/`plex` |
| Docker network | `assemblrr_network` |
| Install directory (config, secrets, compose files) | `~/assemblrr` (or the path you chose) |
| Media directory (your movies/TV/downloads) | `~/assemblrr-media` (or the path you chose) |
@ -93,7 +93,7 @@ you deliberately remove it in step 3.
**1. Remove containers and the network:**
```bash
docker rm -f jellyfin emby plex qbittorrent sonarr radarr prowlarr bazarr \
docker rm -f jellyfin sabnzbd byparr qbittorrent sonarr radarr prowlarr bazarr \
seerr seerr-gateway media-purge-watch recyclarr portainer \
gluetun deunhealth vpn-watchdog 2>/dev/null
# portainer: only if an older install still has it
@ -141,12 +141,11 @@ rm -f ~/.assemblrr-config 2>/dev/null # discovery pointer
**5. Optional — remove the Docker images:**
```bash
# VPN mode also pulls qmcgaw/gluetun and qmcgaw/deunhealth;
# swap jellyfin for emby/plex if you chose a different media server
docker rmi lscr.io/linuxserver/jellyfin lscr.io/linuxserver/qbittorrent \
lscr.io/linuxserver/sonarr lscr.io/linuxserver/radarr \
lscr.io/linuxserver/prowlarr \
ghcr.io/seerr-team/seerr ghcr.io/recyclarr/recyclarr alpine:3
lscr.io/linuxserver/prowlarr lscr.io/linuxserver/bazarr \
lscr.io/linuxserver/sabnzbd ghcr.io/thephaseless/byparr \
ghcr.io/seerr-team/seerr ghcr.io/recyclarr/recyclarr alpine:3.24.4
# older installs: docker rmi portainer/portainer-ce
```

158
lib/api.sh Normal file → Executable file
View file

@ -1,28 +1,93 @@
#!/bin/bash
# assemblrr API helpers — sourced by config.sh
# Provides: jq helpers, API request wrappers, API key discovery, wait_for_api
# Requires: lib/core.sh already sourced (for logging), API_HOST and INSTALL_DIR set
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr API / HTTP helpers — sourced by wiring modules and entrypoints
# Requires: lib/core.sh (logging), API_HOST and INSTALL_DIR set
set -euo pipefail
if [ -n "${_ASSEMBLRR_API_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_API_SOURCED=1
# --- JSON helpers using jq ---
ASSEMBLRR_CURL_BIN="${ASSEMBLRR_CURL_BIN:-curl}"
HTTP_STATUS=""
HTTP_BODY=""
# --- JSON & encoding helpers ---
jq_json_get() {
local json="$1"
local key="$2"
echo "$json" | jq -r --arg k "$key" '.[$k] // empty' 2>/dev/null
printf '%s' "$json" | jq -r --arg k "$key" '.[$k] // empty' 2>/dev/null
}
jq_json_has_key() {
local json="$1"
local key="$2"
echo "$json" | jq -e --arg k "$key" 'has($k)' >/dev/null 2>&1
printf '%s' "$json" | jq -e --arg k "$key" 'has($k)' >/dev/null 2>&1
}
jq_json_list_values() {
local json="$1"
local key="$2"
echo "$json" | jq -r --arg k "$key" '.[][$k] // empty' 2>/dev/null
printf '%s' "$json" | jq -r --arg k "$key" '.[][$k] // empty' 2>/dev/null
}
urlencode() {
jq -rn --arg v "${1:-}" '$v | @uri' 2>/dev/null || printf '%s' "${1:-}"
}
# --- Shared HTTP transport ---
# Execute curl and populate globals HTTP_STATUS (3-digit code, "000" on network failure)
# and HTTP_BODY. Returns 0 on 2xx, 1 otherwise.
http_request() {
local method="$1"
local url="$2"
shift 2
local tmp rc=0
tmp=$(mktemp)
HTTP_STATUS=""
HTTP_BODY=""
HTTP_STATUS=$("$ASSEMBLRR_CURL_BIN" -s -o "$tmp" -w "%{http_code}" --connect-timeout 5 --max-time 30 \
-X "$method" "$@" "$url" 2>/dev/null) || rc=$?
HTTP_BODY=$(cat "$tmp" 2>/dev/null || true)
rm -f "$tmp"
HTTP_STATUS="${HTTP_STATUS//[^0-9]/}"
if [ "${#HTTP_STATUS}" -ne 3 ]; then
HTTP_STATUS="000"
fi
if [ "$rc" -eq 0 ] && [ "$HTTP_STATUS" -ge 200 ] && [ "$HTTP_STATUS" -lt 300 ]; then
return 0
fi
return 1
}
# Reusable polling helper: wait_until <label> <max_sec> <interval_sec> <cmd...>
wait_until() {
local label="$1"
local max_wait="$2"
local interval="$3"
shift 3
local elapsed=0
if "$@" 2>/dev/null; then
return 0
fi
while [ "$elapsed" -lt "$max_wait" ]; do
wait_inline "$label" "$elapsed"
sleep "$interval"
elapsed=$((elapsed + interval))
if "$@" 2>/dev/null; then
echo >&2
return 0
fi
done
echo >&2
return 1
}
# --- API key discovery from config.xml ---
@ -36,7 +101,7 @@ read_api_key() {
while [ $wait_time -lt $max_wait ]; do
if [ -f "$config_file" ]; then
local key
key=$(sed -n 's/.*<ApiKey>\(.*\)<\/ApiKey>.*/\1/p' "$config_file" 2>/dev/null | head -1)
key=$(sed -n 's/.*<ApiKey>\(.*\)<\/ApiKey>.*/\1/p' "$config_file" 2>/dev/null | head -1 | tr -d '\r')
if [ -n "$key" ]; then
[ "$wait_time" -gt 0 ] && echo >&2
echo "$key"
@ -52,13 +117,16 @@ read_api_key() {
return 1
}
# --- API request helpers ---
# --- Servarr API request helpers (use X-Api-Key header, not query strings) ---
api_get() {
local port="$1"
local endpoint="$2"
local apikey="$3"
curl -s --connect-timeout 5 "http://${API_HOST}:${port}${endpoint}?apikey=${apikey}" 2>/dev/null
local rc=0
http_request GET "http://${API_HOST}:${port}${endpoint}" -H "X-Api-Key: ${apikey}" || rc=$?
printf '%s' "$HTTP_BODY"
return "$rc"
}
api_post() {
@ -66,10 +134,11 @@ api_post() {
local endpoint="$2"
local apikey="$3"
local data="$4"
curl -s --connect-timeout 5 -X POST \
-H "Content-Type: application/json" \
-d "$data" \
"http://${API_HOST}:${port}${endpoint}?apikey=${apikey}" 2>/dev/null
local rc=0
http_request POST "http://${API_HOST}:${port}${endpoint}" \
-H "X-Api-Key: ${apikey}" -H "Content-Type: application/json" -d "$data" || rc=$?
printf '%s' "$HTTP_BODY"
return "$rc"
}
api_put() {
@ -77,30 +146,47 @@ api_put() {
local endpoint="$2"
local apikey="$3"
local data="$4"
curl -s --connect-timeout 5 -X PUT \
-H "Content-Type: application/json" \
-d "$data" \
"http://${API_HOST}:${port}${endpoint}?apikey=${apikey}" 2>/dev/null
local rc=0
http_request PUT "http://${API_HOST}:${port}${endpoint}" \
-H "X-Api-Key: ${apikey}" -H "Content-Type: application/json" -d "$data" || rc=$?
printf '%s' "$HTTP_BODY"
return "$rc"
}
api_delete() {
local port="$1"
local endpoint="$2"
local apikey="$3"
curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X DELETE \
"http://${API_HOST}:${port}${endpoint}?apikey=${apikey}" 2>/dev/null
http_request DELETE "http://${API_HOST}:${port}${endpoint}" -H "X-Api-Key: ${apikey}" || true
printf '%s' "$HTTP_STATUS"
}
# POST with forceSave query param (bypasses connectivity validation in Prowlarr/Radarr/Sonarr)
api_post_force() {
local port="$1"
local endpoint="$2"
local apikey="$3"
local data="$4"
curl -s --connect-timeout 5 -X POST \
-H "Content-Type: application/json" \
-d "$data" \
"http://${API_HOST}:${port}${endpoint}?apikey=${apikey}&forceSave=true" 2>/dev/null
local sep="?"
[[ "$endpoint" == *\?* ]] && sep="&"
local rc=0
http_request POST "http://${API_HOST}:${port}${endpoint}${sep}forceSave=true" \
-H "X-Api-Key: ${apikey}" -H "Content-Type: application/json" -d "$data" || rc=$?
printf '%s' "$HTTP_BODY"
return "$rc"
}
api_put_force() {
local port="$1"
local endpoint="$2"
local apikey="$3"
local data="$4"
local sep="?"
[[ "$endpoint" == *\?* ]] && sep="&"
local rc=0
http_request PUT "http://${API_HOST}:${port}${endpoint}${sep}forceSave=true" \
-H "X-Api-Key: ${apikey}" -H "Content-Type: application/json" -d "$data" || rc=$?
printf '%s' "$HTTP_BODY"
return "$rc"
}
qbit_cookie_sid() {
@ -114,9 +200,8 @@ _api_ready() {
local port="$1"
local apikey="$2"
local api_path="$3"
local response
response=$(curl -s --connect-timeout 3 "http://${API_HOST}:${port}${api_path}?apikey=${apikey}" 2>/dev/null || echo "")
[ -n "$response" ] && [ -n "$(jq_json_get "$response" "version")" ]
http_request GET "http://${API_HOST}:${port}${api_path}" -H "X-Api-Key: ${apikey}" || return 1
[ -n "$HTTP_BODY" ] && [ -n "$(jq_json_get "$HTTP_BODY" "version")" ]
}
wait_for_api() {
@ -125,23 +210,10 @@ wait_for_api() {
local apikey="$3"
local api_path="${4:-/api/v3/system/status}"
local max_wait="${API_READY_TIMEOUT_SECONDS:-120}"
local wait_time=0
# Happy path: already up — stay quiet (config edit / re-wire).
if _api_ready "$port" "$apikey" "$api_path"; then
if wait_until "Waiting for $name API" "$max_wait" 2 _api_ready "$port" "$apikey" "$api_path"; then
return 0
fi
while [ $wait_time -lt $max_wait ]; do
if _api_ready "$port" "$apikey" "$api_path"; then
[ "$wait_time" -gt 0 ] && echo >&2
return 0
fi
wait_inline "Waiting for $name API" "$wait_time"
sleep 2
wait_time=$((wait_time + 2))
done
echo >&2
log_step_fail "$name API not ready after ${max_wait}s"
return 1
}

1615
lib/arr.sh Normal file → Executable file

File diff suppressed because it is too large Load diff

396
lib/arr_common.sh Executable file
View file

@ -0,0 +1,396 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr shared Radarr/Sonarr service wiring
# Requires: lib/core.sh, lib/api.sh, lib/qbit.sh
if [ -n "${_ASSEMBLRR_ARR_COMMON_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_ARR_COMMON_SOURCED=1
set_arr_auth() {
local service_name="$1"
local port="$2"
local apikey="$3"
local api_version="${4:-v3}"
if [ -z "${AUTH_USERNAME:-}" ] || [ -z "${AUTH_PASSWORD:-}" ]; then
log_step_fail "${service_name}: auth credentials missing — cannot enable forms auth"
return 1
fi
local host_config
host_config=$(api_get "$port" "/api/${api_version}/config/host" "$apikey") || {
log_step_fail "${service_name}: failed to read host config for authentication"
return 1
}
if [ -z "$host_config" ]; then
log_step_fail "${service_name}: empty host config response"
return 1
fi
local host_id
host_id=$(jq_json_get "$host_config" "id")
host_id=${host_id:-1}
local updated_config
updated_config=$(printf '%s' "$host_config" | jq \
--arg hid "$host_id" --arg user "$AUTH_USERNAME" --arg pass "$AUTH_PASSWORD" \
'.id = ($hid | tonumber) | .authenticationMethod = "forms" | .authenticationRequired = "enabled" | .username = $user | .password = $pass | .passwordConfirmation = $pass' 2>/dev/null || echo "")
if [ -z "$updated_config" ]; then
log_step_fail "${service_name}: failed to build auth config payload"
return 1
fi
local auth_result
auth_result=$(api_put "$port" "/api/${api_version}/config/host" "$apikey" "$updated_config") || {
log_step_fail "${service_name}: failed to set authentication (HTTP ${HTTP_STATUS})"
return 1
}
if jq_json_has_key "$auth_result" "id"; then
log_step "${service_name}: set authentication (username: $AUTH_USERNAME)"
return 0
fi
log_step_fail "${service_name}: failed to set authentication"
return 1
}
# Point an existing *arr qBittorrent client at the current host (gluetun vs qbittorrent).
arr_update_qb_host() {
local service_name="$1"
local port="$2"
local apikey="$3"
local host="${QBITTORRENT_HOST:-qbittorrent}"
local clients dc_id existing updated result
[ -n "$apikey" ] || return 1
clients=$(api_get "$port" "/api/v3/downloadclient" "$apikey") || return 1
dc_id=$(printf '%s' "$clients" | jq -r \
'[.[] | select(.implementationName == "qBittorrent" or .implementation == "QBittorrent")][0].id // empty' \
2>/dev/null || true)
[ -n "$dc_id" ] || return 1
existing=$(printf '%s' "$clients" | jq --argjson id "$dc_id" '.[] | select(.id == $id)' 2>/dev/null || true)
[ -n "$existing" ] || return 1
updated=$(printf '%s' "$existing" | jq --arg host "$host" \
'.fields = [.fields[] | if .name == "host" then .value = $host else . end]' \
2>/dev/null || true)
[ -n "$updated" ] || return 1
result=$(api_put "$port" "/api/v3/downloadclient/${dc_id}" "$apikey" "$updated") || return 1
if jq_json_has_key "$result" "id"; then
log_step "${service_name}: qBittorrent host → ${host}"
return 0
fi
return 1
}
_arr_build_qbit_payload() {
local port="$1"
local apikey="$2"
local service_name="$3"
local category_name="$4"
local schemas="" base_schema=""
schemas=$(api_get "$port" "/api/v3/downloadclient/schema" "$apikey" 2>/dev/null || true)
if [ -n "$schemas" ]; then
base_schema=$(printf '%s' "$schemas" | jq '[.[] | select(.implementation == "QBittorrent")][0] // empty' 2>/dev/null || true)
fi
if [ -n "$base_schema" ]; then
printf '%s' "$base_schema" | jq \
--arg host "$QBITTORRENT_HOST" --arg user "$AUTH_USERNAME" --arg pass "$AUTH_PASSWORD" \
--arg cat_name "$category_name" --arg sn "$service_name" '
(if $sn == "Radarr" then "movieCategory" else "tvCategory" end) as $cat_key |
(if $sn == "Radarr" then "movieImportedCategory" else "tvImportedCategory" end) as $imp_key |
(if $sn == "Radarr" then "recentMoviePriority" else "recentTvPriority" end) as $rec_key |
(if $sn == "Radarr" then "olderMoviePriority" else "olderTvPriority" end) as $old_key |
.enable = true |
.removeCompletedDownloads = true |
.removeFailedDownloads = true |
.name = "qBittorrent" |
.priority = 1 |
.tags = [] |
.fields = [.fields[] |
if .name == "host" then .value = $host
elif .name == "port" then .value = 8081
elif .name == "useSsl" then .value = false
elif .name == "urlBase" then .value = ""
elif .name == "username" then .value = $user
elif .name == "password" then .value = $pass
elif .name == $cat_key then .value = $cat_name
elif .name == $imp_key then .value = ""
elif .name == $rec_key then .value = 0
elif .name == $old_key then .value = 0
elif .name == "initialState" then .value = 0
elif .name == "sequentialOrder" then .value = false
elif .name == "firstAndLast" then .value = false
elif .name == "contentLayout" then .value = 0
else . end
]
' 2>/dev/null || echo ""
return 0
fi
jq -n --arg host "$QBITTORRENT_HOST" --arg user "$AUTH_USERNAME" --arg pass "$AUTH_PASSWORD" \
--arg cat_name "$category_name" --arg sn "$service_name" '
{
"enable": true,
"removeCompletedDownloads": true,
"removeFailedDownloads": true,
"name": "qBittorrent",
"implementation": "QBittorrent",
"implementationName": "qBittorrent",
"configContract": "QBittorrentSettings",
"priority": 1,
"fields": [
{"name": "host", "value": $host},
{"name": "port", "value": 8081},
{"name": "useSsl", "value": false},
{"name": "urlBase", "value": ""},
{"name": "username", "value": $user},
{"name": "password", "value": $pass},
{"name": (if $sn == "Radarr" then "movieCategory" else "tvCategory" end), "value": $cat_name},
{"name": (if $sn == "Radarr" then "movieImportedCategory" else "tvImportedCategory" end), "value": ""},
{"name": (if $sn == "Radarr" then "recentMoviePriority" else "recentTvPriority" end), "value": 0},
{"name": (if $sn == "Radarr" then "olderMoviePriority" else "olderTvPriority" end), "value": 0},
{"name": "initialState", "value": 0},
{"name": "sequentialOrder", "value": false},
{"name": "firstAndLast", "value": false},
{"name": "contentLayout", "value": 0}
]
}' 2>/dev/null || echo ""
}
configure_arr_service() {
local service_name="$1"
local port="$2"
local apikey="$3"
local root_path="$4"
local category_name="$5"
local category_path="$6"
local unmonitor_field="$7"
local naming_jq="$8"
local critical_errors=0
# 1. Add root folder
local root_folders existing_paths
root_folders=$(api_get "$port" "/api/v3/rootfolder" "$apikey" || echo "[]")
existing_paths=$(jq_json_list_values "$root_folders" "path")
if ! printf '%s\n' "$existing_paths" | grep -Fxq "$root_path"; then
local rf_result
rf_result=$(api_post "$port" "/api/v3/rootfolder" "$apikey" "{\"path\":\"${root_path}\"}" || echo "")
if jq_json_has_key "$rf_result" "id"; then
log_step "${service_name}: added ${root_path} as root folder"
else
log_step_fail "${service_name}: failed to add root folder"
critical_errors=$((critical_errors + 1))
fi
else
log_step "${service_name}: root folder ${root_path} already exists"
fi
# Keep only the configured root folder
local all_root_folders extra_ids extra_id
all_root_folders=$(api_get "$port" "/api/v3/rootfolder" "$apikey" || echo "[]")
extra_ids=$(printf '%s' "$all_root_folders" | jq -r --arg rp "$root_path" '.[] | select(.path != $rp) | .id' 2>/dev/null || echo "")
for extra_id in $extra_ids; do
if [ -n "$extra_id" ]; then
api_delete "$port" "/api/v3/rootfolder/${extra_id}" "$apikey" >/dev/null || true
log_step "${service_name}: removed extra root folder (id: ${extra_id})"
fi
done
# 2. Add or update qBittorrent download client
local download_clients existing_impls qbit_payload
download_clients=$(api_get "$port" "/api/v3/downloadclient" "$apikey" || echo "[]")
existing_impls=$(jq_json_list_values "$download_clients" "implementationName")
qbit_payload=$(_arr_build_qbit_payload "$port" "$apikey" "$service_name" "$category_name")
if ! printf '%s\n' "$existing_impls" | grep -Fxq "qBittorrent"; then
if [ -n "$qbit_payload" ]; then
local dc_result
dc_result=$(api_post "$port" "/api/v3/downloadclient" "$apikey" "$qbit_payload" || echo "")
if jq_json_has_key "$dc_result" "id"; then
log_step "${service_name}: added qBittorrent as download client (host: ${QBITTORRENT_HOST})"
else
log_step_fail "${service_name}: failed to add qBittorrent download client"
critical_errors=$((critical_errors + 1))
fi
else
log_step_fail "${service_name}: failed to build qBittorrent payload"
critical_errors=$((critical_errors + 1))
fi
else
local existing_dc dc_id updated_dc dc_put
existing_dc=$(printf '%s' "$download_clients" | jq '[.[] | select(.implementationName == "qBittorrent" or .implementation == "QBittorrent")][0]' 2>/dev/null || echo "")
dc_id=$(printf '%s' "$existing_dc" | jq -r '.id // empty' 2>/dev/null || echo "")
if [ -n "$dc_id" ] && [ -n "$qbit_payload" ]; then
updated_dc=$(printf '%s' "$qbit_payload" | jq --argjson id "$dc_id" '.id = $id' 2>/dev/null || echo "")
if [ -n "$updated_dc" ]; then
dc_put=$(api_put "$port" "/api/v3/downloadclient/${dc_id}" "$apikey" "$updated_dc" || echo "")
if jq_json_has_key "$dc_put" "id"; then
log_step "${service_name}: updated qBittorrent download client (host: ${QBITTORRENT_HOST})"
else
log_step "${service_name}: qBittorrent download client already exists"
fi
else
log_step "${service_name}: qBittorrent download client already exists"
fi
else
log_step "${service_name}: qBittorrent download client already exists"
fi
fi
# 2b. Create qBittorrent category with correct save path
if ! qbit_create_category "$service_name" "$category_name" "$category_path"; then
critical_errors=$((critical_errors + 1))
fi
# 2c. Enable hardlinks in Media Management (recycle bin disabled)
local mediamgmt
mediamgmt=$(api_get "$port" "/api/v3/config/mediamanagement" "$apikey" || echo "")
if [ -n "$mediamgmt" ]; then
local mgmt_payload
mgmt_payload=$(printf '%s' "$mediamgmt" | jq --arg uf "$unmonitor_field" \
'.copyUsingHardlinks = true | .enableMediaManagement = true | .[$uf] = true
| .recycleBin = "" | .recycleBinCleanupDays = 0' 2>/dev/null || echo "")
if [ -n "$mgmt_payload" ]; then
local mgmt_result
mgmt_result=$(api_put "$port" "/api/v3/config/mediamanagement" "$apikey" "$mgmt_payload" || echo "")
if jq_json_has_key "$mgmt_result" "id"; then
log_step "${service_name}: enabled hardlinks (recycle bin disabled)"
else
log_step_fail "${service_name}: failed to enable hardlinks"
fi
fi
fi
# 3. Set naming convention
if [ -n "$naming_jq" ]; then
local naming
naming=$(api_get "$port" "/api/v3/config/naming" "$apikey" || echo "")
if [ -n "$naming" ]; then
local naming_payload
naming_payload=$(printf '%s' "$naming" | jq "$naming_jq" 2>/dev/null || echo "")
if [ -n "$naming_payload" ]; then
local naming_result
naming_result=$(api_put "$port" "/api/v3/config/naming" "$apikey" "$naming_payload" || echo "")
if jq_json_has_key "$naming_result" "id"; then
log_step "${service_name}: set naming convention"
else
log_step_fail "${service_name}: failed to set naming convention"
fi
else
log_step_fail "${service_name}: failed to build naming config payload"
fi
fi
fi
# 4. Set authentication
if ! set_arr_auth "$service_name" "$port" "$apikey"; then
critical_errors=$((critical_errors + 1))
fi
[ "$critical_errors" -eq 0 ]
}
# On movie/series delete, run arr-purge-hook.sh (download client + files).
add_arr_purge_hook() {
local app_name="$1"
local port="$2"
local apikey="$3"
[ -z "$apikey" ] && return 0
local notifications existing_id
notifications=$(api_get "$port" "/api/v3/notification" "$apikey" || echo "[]")
existing_id=$(printf '%s' "$notifications" | jq -r \
'.[] | select(.implementation == "CustomScript" and .name == "assemblrr Media Purge") | .id // ""' \
2>/dev/null | head -1 || echo "")
if [ -f "${INSTALL_DIR:-}/scripts/arr-purge-hook.sh" ]; then
chmod +x "${INSTALL_DIR}/scripts/arr-purge-hook.sh" 2>/dev/null || true
fi
if [ -f "${INSTALL_DIR:-}/scripts/media-purge.sh" ]; then
chmod +x "${INSTALL_DIR}/scripts/media-purge.sh" 2>/dev/null || true
fi
local schema payload result
schema=$(api_get "$port" "/api/v3/notification/schema" "$apikey" || echo "[]")
if [ "$app_name" = "Radarr" ]; then
payload=$(printf '%s' "$schema" | jq '
[.[] | select(.implementation == "CustomScript")][0] |
.fields = [.fields[] | if .name == "path" then .value = "/scripts/arr-purge-hook.sh" else . end] |
.onGrab = false | .onDownload = false | .onUpgrade = false |
.onRename = false | .onMovieAdded = false |
.onMovieDelete = true | .onMovieFileDelete = false |
.onMovieFileDeleteForUpgrade = false |
.onHealthIssue = false | .onHealthRestored = false |
.onApplicationUpdate = false | .onManualInteractionRequired = false |
.includeHealthWarnings = false |
.name = "assemblrr Media Purge" | .tags = []
' 2>/dev/null || echo "")
else
payload=$(printf '%s' "$schema" | jq '
[.[] | select(.implementation == "CustomScript")][0] |
.fields = [.fields[] | if .name == "path" then .value = "/scripts/arr-purge-hook.sh" else . end] |
.onGrab = false | .onDownload = false | .onUpgrade = false |
.onRename = false | .onSeriesAdd = false |
.onSeriesDelete = true | .onEpisodeFileDelete = false |
.onEpisodeFileDeleteForUpgrade = false |
.onHealthIssue = false | .onHealthRestored = false |
.onApplicationUpdate = false | .onManualInteractionRequired = false |
.includeHealthWarnings = false |
.name = "assemblrr Media Purge" | .tags = []
' 2>/dev/null || echo "")
fi
if [ -z "$payload" ]; then
log_step_fail "${app_name}: CustomScript schema not found for media purge"
return 1
fi
if [ -n "$existing_id" ]; then
payload=$(printf '%s' "$payload" | jq --argjson id "$existing_id" '.id = $id' 2>/dev/null || echo "$payload")
result=$(api_put "$port" "/api/v3/notification/${existing_id}" "$apikey" "$payload" || echo "")
if jq_json_has_key "$result" "id"; then
log_step "${app_name}: updated Media Purge hook"
return 0
fi
fi
result=$(api_post_force "$port" "/api/v3/notification" "$apikey" "$payload" || echo "")
if jq_json_has_key "$result" "id"; then
log_step "${app_name}: added Media Purge hook"
return 0
fi
local err_msg
err_msg=$(printf '%s' "$result" | jq -r 'if type == "array" then .[0].errorMessage // empty else .errorMessage // empty end' 2>/dev/null || echo "")
if [ -n "$err_msg" ]; then
log_step_fail "${app_name}: failed to add Media Purge hook (${err_msg})"
else
log_step_fail "${app_name}: failed to add Media Purge hook"
fi
return 1
}
configure_radarr() {
local apikey="$1"
configure_arr_service \
"Radarr" "7878" "$apikey" \
"/data/media/movies" "movies" "/data/torrents/movies" \
"autoUnmonitorPreviouslyDownloadedMovies" \
'.renameMovies = true | .standardMovieFormat = "{Movie CleanTitle} ({Release Year}) {Quality Full}" | .movieFolderFormat = "{Movie CleanTitle} ({Release Year})"'
}
configure_sonarr() {
local apikey="$1"
# Note: Sonarr v4 colonReplacementFormat=4 -> "Smart", multiEpisodeStyle=5 -> "Prefixed Range".
configure_arr_service \
"Sonarr" "8989" "$apikey" \
"/data/media/tv" "tv" "/data/torrents/tv" \
"autoUnmonitorPreviouslyDownloadedEpisodes" \
'.renameEpisodes = true | .replaceIllegalCharacters = true | .standardEpisodeFormat = "{Series Title} - S{season:00}E{episode:00} - {Episode Title} {Quality Full}" | .dailyEpisodeFormat = "{Series Title} - {Air-Date} - {Episode Title} {Quality Full}" | .animeEpisodeFormat = "{Series Title} - S{season:00}E{episode:00} - {Episode Title} {Quality Full}" | .seriesFolderFormat = "{Series Title}" | .seasonFolderFormat = "Season {season}" | .multiEpisodeStyle = 5 | .colonReplacementFormat = 4'
}

221
lib/arr_import.sh Executable file
View file

@ -0,0 +1,221 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr existing-library media importer for Radarr & Sonarr
# Requires: lib/core.sh, lib/api.sh, lib/arr_quality.sh
if [ -n "${_ASSEMBLRR_ARR_IMPORT_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_ARR_IMPORT_SOURCED=1
_folder_year() {
local name="$1"
if [[ "$name" =~ \(([0-9]{4})\)$ ]]; then
echo "${BASH_REMATCH[1]}"
fi
}
_folder_title_guess() {
local name="$1"
echo "$name" | sed -E 's/[[:space:]]*\([0-9]{4}\)[[:space:]]*$//'
}
import_radarr_existing_media() {
local apikey="$1"
local port=7878
local root_json existing_movies profile_info profile_id
local added=0 skipped=0 failed=0
local folder_path folder_name year title_guess
local lookup_json match payload result movie_id
root_json=$(api_get "$port" "/api/v3/rootfolder" "$apikey" || echo "[]")
if [ -z "$root_json" ] || [ "$root_json" = "[]" ]; then
log_step_fail "Radarr: no root folders — skip existing media import"
return 1
fi
profile_info=$(lookup_radarr_profile "$apikey")
profile_id=${profile_info%%:*}
profile_id=${profile_id:-1}
existing_movies=$(api_get "$port" "/api/v3/movie" "$apikey" || echo "[]")
while IFS=$'\t' read -r folder_path folder_name; do
[ -z "$folder_path" ] && continue
year=$(_folder_year "$folder_name")
title_guess=$(_folder_title_guess "$folder_name")
if printf '%s' "$existing_movies" | jq -e --arg p "$folder_path" 'any(.[]; .path == $p)' >/dev/null 2>&1; then
skipped=$((skipped + 1))
continue
fi
local term="$title_guess" enc_term
[ -n "$year" ] && term="${title_guess} ${year}"
enc_term=$(urlencode "$term")
lookup_json=$(api_get "$port" "/api/v3/movie/lookup?term=${enc_term}" "$apikey" || echo "[]")
if [ -z "$lookup_json" ] || [ "$lookup_json" = "[]" ]; then
log_step_fail "Radarr: no match for '${folder_name}'"
failed=$((failed + 1))
continue
fi
match=$(printf '%s' "$lookup_json" | jq -c --argjson y "${year:-0}" '
if $y > 0 then ([.[] | select(.year == $y)] | .[0]) // .[0]
else .[0] end
' 2>/dev/null || echo "")
if [ -z "$match" ] || [ "$match" = "null" ]; then
log_step_fail "Radarr: could not pick match for '${folder_name}'"
failed=$((failed + 1))
continue
fi
payload=$(printf '%s' "$match" | jq -c \
--argjson qid "$profile_id" \
--arg path "$folder_path" \
--arg root "/data/media/movies" '
{
title: .title,
tmdbId: .tmdbId,
year: .year,
qualityProfileId: $qid,
monitored: true,
minimumAvailability: (.minimumAvailability // "announced"),
rootFolderPath: $root,
path: $path,
addOptions: { searchForMovie: false }
}' 2>/dev/null || echo "")
if [ -z "$payload" ]; then
failed=$((failed + 1))
continue
fi
result=$(api_post "$port" "/api/v3/movie" "$apikey" "$payload" || echo "")
movie_id=$(printf '%s' "$result" | jq -r '.id // empty' 2>/dev/null || echo "")
if [ -z "$movie_id" ]; then
if printf '%s' "$result" | jq -e '.message' 2>/dev/null | grep -qi 'exist\|already' 2>/dev/null; then
skipped=$((skipped + 1))
else
log_step_fail "Radarr: import failed for '${folder_name}'"
failed=$((failed + 1))
fi
continue
fi
api_post "$port" "/api/v3/command" "$apikey" \
"{\"name\":\"RescanMovie\",\"movieId\":${movie_id}}" >/dev/null 2>&1 || true
added=$((added + 1))
log_step "Radarr: imported existing '${folder_name}' (id ${movie_id}, profile ${profile_id})"
done < <(printf '%s' "$root_json" | jq -r '.[] | .unmappedFolders[]? | "\(.path)\t\(.name)"' 2>/dev/null || true)
if [ "$added" -eq 0 ] && [ "$failed" -eq 0 ]; then
log_step "Radarr: no unmapped movie folders to import"
return 0
fi
log_step "Radarr: existing media import done (added=${added}, skipped=${skipped}, failed=${failed})"
[ "$failed" -eq 0 ]
}
import_sonarr_existing_media() {
local apikey="$1"
local port=8989
local root_json existing_series profile_info profile_id
local added=0 skipped=0 failed=0
local folder_path folder_name year title_guess
local lookup_json match payload result series_id language_profile_id
root_json=$(api_get "$port" "/api/v3/rootfolder" "$apikey" || echo "[]")
if [ -z "$root_json" ] || [ "$root_json" = "[]" ]; then
log_step_fail "Sonarr: no root folders — skip existing media import"
return 1
fi
profile_info=$(lookup_sonarr_profile "$apikey")
profile_id=${profile_info%%:*}
profile_id=${profile_id:-1}
# Sonarr v3 required languageProfileId; Sonarr v4 ignores/deprecates it. Query best-effort.
language_profile_id=$(api_get "$port" "/api/v3/languageprofile" "$apikey" 2>/dev/null | jq -r '.[0].id // 1' 2>/dev/null || echo "1")
[ -n "$language_profile_id" ] || language_profile_id=1
existing_series=$(api_get "$port" "/api/v3/series" "$apikey" || echo "[]")
while IFS=$'\t' read -r folder_path folder_name; do
[ -z "$folder_path" ] && continue
year=$(_folder_year "$folder_name")
title_guess=$(_folder_title_guess "$folder_name")
if printf '%s' "$existing_series" | jq -e --arg p "$folder_path" 'any(.[]; .path == $p)' >/dev/null 2>&1; then
skipped=$((skipped + 1))
continue
fi
local enc_term
enc_term=$(urlencode "$title_guess")
lookup_json=$(api_get "$port" "/api/v3/series/lookup?term=${enc_term}" "$apikey" || echo "[]")
if [ -z "$lookup_json" ] || [ "$lookup_json" = "[]" ]; then
log_step_fail "Sonarr: no match for '${folder_name}'"
failed=$((failed + 1))
continue
fi
match=$(printf '%s' "$lookup_json" | jq -c --argjson y "${year:-0}" '
if $y > 0 then ([.[] | select(.year == $y)] | .[0]) // .[0]
else .[0] end
' 2>/dev/null || echo "")
if [ -z "$match" ] || [ "$match" = "null" ]; then
failed=$((failed + 1))
continue
fi
payload=$(printf '%s' "$match" | jq -c \
--argjson qid "$profile_id" \
--argjson lid "$language_profile_id" \
--arg path "$folder_path" \
--arg root "/data/media/tv" '
. + {
qualityProfileId: $qid,
languageProfileId: $lid,
rootFolderPath: $root,
path: $path,
monitored: true,
seasonFolder: true,
addOptions: {
searchForMissingEpisodes: false,
searchForCutoffUnmetEpisodes: false,
monitor: "all"
}
} | del(.id, .statistics, .episodesChanged)
' 2>/dev/null || echo "")
if [ -z "$payload" ]; then
failed=$((failed + 1))
continue
fi
result=$(api_post "$port" "/api/v3/series" "$apikey" "$payload" || echo "")
series_id=$(printf '%s' "$result" | jq -r '.id // empty' 2>/dev/null || echo "")
if [ -z "$series_id" ]; then
log_step_fail "Sonarr: import failed for '${folder_name}'"
failed=$((failed + 1))
continue
fi
api_post "$port" "/api/v3/command" "$apikey" \
"{\"name\":\"RescanSeries\",\"seriesId\":${series_id}}" >/dev/null 2>&1 || true
added=$((added + 1))
log_step "Sonarr: imported existing '${folder_name}' (id ${series_id}, profile ${profile_id})"
done < <(printf '%s' "$root_json" | jq -r '.[] | .unmappedFolders[]? | "\(.path)\t\(.name)"' 2>/dev/null || true)
if [ "$added" -eq 0 ] && [ "$failed" -eq 0 ]; then
log_step "Sonarr: no unmapped series folders to import"
return 0
fi
log_step "Sonarr: existing media import done (added=${added}, skipped=${skipped}, failed=${failed})"
[ "$failed" -eq 0 ]
}

337
lib/arr_quality.sh Executable file
View file

@ -0,0 +1,337 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Radarr/Sonarr quality sizes & default quality-profile promotion
# Requires: lib/core.sh, lib/api.sh, lib/quality.sh
if [ -n "${_ASSEMBLRR_ARR_QUALITY_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_ARR_QUALITY_SOURCED=1
_arr_quality_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/quality.sh
[ -f "$_arr_quality_dir/quality.sh" ] && source "$_arr_quality_dir/quality.sh"
# Set minSize=0 on every quality definition (avoids rejecting small legitimate releases).
relax_quality_sizes() {
local service_name="$1"
local port="$2"
local apikey="$3"
local defs
defs=$(api_get "$port" "/api/v3/qualitydefinition" "$apikey" || echo "")
if [ -z "$defs" ] || [ "$defs" = "[]" ]; then
log_step_fail "${service_name}: no quality definitions to update"
return 1
fi
local payload
payload=$(printf '%s' "$defs" | jq '[.[] | .minSize = 0]' 2>/dev/null || echo "")
if [ -z "$payload" ]; then
log_step_fail "${service_name}: failed to build quality definition payload"
return 1
fi
local result=""
if result=$(api_put "$port" "/api/v3/qualitydefinition/update" "$apikey" "$payload") && \
printf '%s' "$result" | jq -e 'type == "array"' >/dev/null 2>&1; then
log_step "${service_name}: quality minSize set to 0"
return 0
fi
# Fallback: one PUT per definition (check actual HTTP status via api_put return code)
local ok=0 total=0 row id
while IFS= read -r row; do
[ -z "$row" ] && continue
total=$((total + 1))
id=$(printf '%s' "$row" | jq -r '.id // empty')
[ -z "$id" ] && continue
if api_put "$port" "/api/v3/qualitydefinition/${id}" "$apikey" "$row" >/dev/null 2>&1; then
ok=$((ok + 1))
fi
done < <(printf '%s' "$payload" | jq -c '.[]' 2>/dev/null || true)
if [ "$ok" -gt 0 ]; then
log_step "${service_name}: quality minSize set to 0 (${ok}/${total})"
return 0
fi
log_step_fail "${service_name}: failed to update quality definitions"
return 1
}
# Item ids whose qualityProfileId still needs updating.
# stdin: JSON array of {id, qualityProfileId}. $1 = target id. $2 = all | any-only | from:<id>
arr_quality_ids_needing_update() {
local pid="$1"
local mode="${2:-all}"
case "$mode" in
any-only)
jq -c --argjson pid "$pid" '[.[] | select((.qualityProfileId // 0) == 1 and .id != null) | .id]'
;;
from:*)
local from="${mode#from:}"
jq -c --argjson old "$from" '[.[] | select((.qualityProfileId // 0) == $old and .id != null) | .id]'
;;
*)
jq -c --argjson pid "$pid" '[.[] | select((.qualityProfileId // 0) != $pid and .id != null) | .id]'
;;
esac
}
arr_quality_profile_clone_json() {
local dest_id="$1"
local dest_name="$2"
jq --argjson id "$dest_id" --arg name "$dest_name" '.id = $id | .name = $name'
}
arr_rootfolder_with_default_profile() {
local pid="$1"
jq --argjson pid "$pid" 'del(.unmappedFolders) | .defaultQualityProfileId = $pid'
}
_arr_put_http() {
local port="$1"
local endpoint="$2"
local apikey="$3"
local data="$4"
http_request PUT "http://${API_HOST}:${port}${endpoint}" \
-H "X-Api-Key: ${apikey}" -H "Content-Type: application/json" -d "$data" || true
printf '%s' "$HTTP_STATUS"
}
arr_set_root_folder_quality_profile() {
local _service_name="$1"
local port="$2"
local apikey="$3"
local profile_id="$4"
local folders folder payload code ok=0
folders=$(api_get "$port" "/api/v3/rootfolder" "$apikey" || echo "[]")
if [ -z "$folders" ] || [ "$folders" = "[]" ]; then
return 1
fi
while IFS= read -r folder; do
[ -z "$folder" ] && continue
local fid
fid=$(printf '%s' "$folder" | jq -r '.id // empty')
[ -n "$fid" ] || continue
payload=$(printf '%s' "$folder" | arr_rootfolder_with_default_profile "$profile_id")
[ -n "$payload" ] || continue
code=$(_arr_put_http "$port" "/api/v3/rootfolder/${fid}" "$apikey" "$payload")
if [ "$code" -ge 200 ] && [ "$code" -lt 300 ]; then
ok=$((ok + 1))
fi
done < <(printf '%s' "$folders" | jq -c '.[]' 2>/dev/null || true)
[ "$ok" -gt 0 ]
}
arr_set_items_quality_profile() {
local service_name="$1"
local port="$2"
local apikey="$3"
local profile_id="$4"
local kind="$5"
local mode="${6:-all}"
local list_path editor_path id_key items ids payload code
if [ "$kind" = "series" ]; then
list_path="/api/v3/series"
editor_path="/api/v3/series/editor"
id_key="seriesIds"
else
list_path="/api/v3/movie"
editor_path="/api/v3/movie/editor"
id_key="movieIds"
fi
items=$(api_get "$port" "$list_path" "$apikey" || echo "[]")
if [ -z "$items" ] || [ "$items" = "[]" ]; then
return 0
fi
ids=$(printf '%s' "$items" | arr_quality_ids_needing_update "$profile_id" "$mode")
if [ -z "$ids" ] || [ "$ids" = "[]" ]; then
return 0
fi
payload=$(jq -nc --argjson ids "$ids" --argjson pid "$profile_id" --arg key "$id_key" \
'{($key): $ids, qualityProfileId: $pid}')
code=$(_arr_put_http "$port" "$editor_path" "$apikey" "$payload")
if [ "$code" -ge 200 ] && [ "$code" -lt 300 ]; then
local n
n=$(printf '%s' "$ids" | jq 'length' 2>/dev/null || echo 0)
log_step "${service_name}: moved ${n} title(s) → quality profile ${profile_id}"
return 0
fi
return 1
}
arr_set_importlist_quality_profile() {
local _service_name="$1"
local port="$2"
local apikey="$3"
local profile_id="$4"
local lists list payload code ok=0 total=0
lists=$(api_get "$port" "/api/v3/importlist" "$apikey" || echo "[]")
if [ -z "$lists" ] || [ "$lists" = "[]" ]; then
return 0
fi
while IFS= read -r list; do
[ -z "$list" ] && continue
local lid cur
lid=$(printf '%s' "$list" | jq -r '.id // empty')
cur=$(printf '%s' "$list" | jq -r '.qualityProfileId // empty')
[ -n "$lid" ] || continue
total=$((total + 1))
if [ "$cur" = "$profile_id" ]; then
ok=$((ok + 1))
continue
fi
payload=$(printf '%s' "$list" | jq --argjson pid "$profile_id" '.qualityProfileId = $pid')
code=$(_arr_put_http "$port" "/api/v3/importlist/${lid}" "$apikey" "$payload")
if [ "$code" -ge 200 ] && [ "$code" -lt 300 ]; then
ok=$((ok + 1))
fi
done < <(printf '%s' "$lists" | jq -c '.[]' 2>/dev/null || true)
[ "$total" -eq 0 ] || [ "$ok" -gt 0 ]
}
# *arr Add New defaults to quality profile id 1 (stock "Any").
# Promote the chosen assemblrr profile onto id 1 so Add Movie/Series opens on it.
arr_promote_quality_profile() {
local service_name="$1"
local port="$2"
local apikey="$3"
local src_id="$4"
local src_name="$5"
[ -n "$src_id" ] && [ -n "$src_name" ] || return 1
if [ "$src_id" = "1" ]; then
return 0
fi
local id1_name
id1_name=$(api_get "$port" "/api/v3/qualityprofile/1" "$apikey" 2>/dev/null | jq -r '.name // empty' || true)
if [ "$id1_name" = "$src_name" ]; then
return 0
fi
local src dest tmp_name tmp_payload code
src=$(api_get "$port" "/api/v3/qualityprofile/${src_id}" "$apikey" || echo "")
if [ -z "$src" ] || ! printf '%s' "$src" | jq -e '.id' >/dev/null 2>&1; then
return 1
fi
tmp_name="${src_name}.__assemblrr_tmp"
tmp_payload=$(printf '%s' "$src" | jq --arg n "$tmp_name" '.name = $n')
code=$(_arr_put_http "$port" "/api/v3/qualityprofile/${src_id}" "$apikey" "$tmp_payload")
if [ "$code" -lt 200 ] || [ "$code" -ge 300 ]; then
return 1
fi
dest=$(printf '%s' "$src" | arr_quality_profile_clone_json 1 "$src_name")
code=$(_arr_put_http "$port" "/api/v3/qualityprofile/1" "$apikey" "$dest")
if [ "$code" -lt 200 ] || [ "$code" -ge 300 ]; then
_arr_put_http "$port" "/api/v3/qualityprofile/${src_id}" "$apikey" "$src" >/dev/null || true
return 1
fi
local kind="movie"
[ "$service_name" = "Sonarr" ] && kind="series"
arr_set_items_quality_profile "$service_name" "$port" "$apikey" "1" "$kind" "from:${src_id}" || true
arr_set_importlist_quality_profile "$service_name" "$port" "$apikey" "1" || true
local del
del=$(api_delete "$port" "/api/v3/qualityprofile/${src_id}" "$apikey" || echo "000")
if [ "$del" -ge 200 ] && [ "$del" -lt 300 ]; then
log_step "${service_name}: Add New default is ${src_name}"
return 0
fi
log_step "${service_name}: Add New default is ${src_name} (left extra profile id ${src_id})"
return 0
}
clean_legacy_arr_quality_profiles() {
local _service_name="$1"
local port="$2"
local apikey="$3"
local profiles
profiles=$(api_get "$port" "/api/v3/qualityprofile" "$apikey" || echo "")
[ -n "$profiles" ] || return 0
local legacy_names=(
"assemblrr HD Bluray + WEB"
"assemblrr UHD Bluray + WEB"
"assemblrr WEB-1080p"
"assemblrr WEB-2160p"
)
local lname lid
for lname in "${legacy_names[@]}"; do
lid=$(printf '%s' "$profiles" | jq -r --arg n "$lname" '.[] | select(.name == $n) | .id // empty' 2>/dev/null || true)
if [ -n "$lid" ] && [ "$lid" != "1" ]; then
api_delete "$port" "/api/v3/qualityprofile/${lid}" "$apikey" >/dev/null 2>&1 || true
fi
done
}
set_default_quality_profile() {
local service_name="$1"
local port="$2"
local apikey="$3"
local profile_func="$4"
local profile profile_id profile_name
profile=$($profile_func "$apikey")
profile_id="${profile%%:*}"
profile_name="${profile##*:}"
if [ -z "$profile_id" ]; then
log_step_fail "${service_name}: no quality profile to apply"
return 1
fi
if quality_wants_named_profile && [ "$profile_id" = "1" ] && [ "$profile_name" = "Any" ]; then
log_step_fail "${service_name}: assemblrr quality profile not found (Recyclarr sync missing?)"
return 1
fi
if arr_promote_quality_profile "$service_name" "$port" "$apikey" "$profile_id" "$profile_name"; then
profile_id="1"
fi
clean_legacy_arr_quality_profiles "$service_name" "$port" "$apikey"
arr_set_root_folder_quality_profile "$service_name" "$port" "$apikey" "$profile_id" || true
arr_set_importlist_quality_profile "$service_name" "$port" "$apikey" "$profile_id" || true
log_step "${service_name}: default quality profile → ${profile_name} (id ${profile_id})"
}
lookup_arr_quality_profile() {
local apikey="$1"
local port="$2"
local kind="$3"
local profiles_json spec
profiles_json=$(api_get "$port" "/api/v3/qualityprofile" "$apikey" || echo "")
if [ -z "$profiles_json" ]; then
echo "1:Any"
return
fi
spec=$(quality_profile_names "$kind")
printf '%s' "$profiles_json" | arr_match_quality_profile "${spec%%|*}" "${spec##*|}"
}
lookup_radarr_profile() {
lookup_arr_quality_profile "$1" 7878 radarr
}
lookup_sonarr_profile() {
lookup_arr_quality_profile "$1" 8989 sonarr
}

371
lib/bazarr.sh Normal file → Executable file
View file

@ -1,15 +1,19 @@
#!/bin/bash
# assemblrr Bazarr configuration — sourced by config.sh
# Provides: configure_bazarr
# Requires: lib/core.sh, lib/api.sh, INSTALL_DIR, API_HOST, RADARR_API_KEY, SONARR_API_KEY
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Bazarr configuration — sourced by config.sh / config_edit.sh
# Requires: lib/core.sh, lib/api.sh, lib/languages.sh
set -euo pipefail
if [ -n "${_ASSEMBLRR_BAZARR_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_BAZARR_SOURCED=1
_bazarr_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/languages.sh
[ -f "$_bazarr_dir/languages.sh" ] && source "$_bazarr_dir/languages.sh"
BAZARR_PORT=6767
# --- helpers ---
# Resolve Bazarr config file (v1.x uses config.yaml; older used config.ini)
_bazarr_config_file() {
local candidates=(
"$INSTALL_DIR/config/bazarr/config/config.yaml"
@ -27,13 +31,11 @@ _bazarr_config_file() {
return 1
}
# Extract auth.apikey from yaml or ini
_bazarr_extract_apikey() {
local cfg="$1"
local key=""
case "$cfg" in
*.yaml|*.yml)
# Prefer yq if present; else awk under the auth: section
if command -v yq >/dev/null 2>&1; then
key=$(yq -r '.auth.apikey // empty' "$cfg" 2>/dev/null || true)
fi
@ -58,9 +60,7 @@ _bazarr_extract_apikey() {
}
read_bazarr_api_key() {
local max_wait=180
local wait_time=0
local cfg key
local max_wait=180 wait_time=0 cfg key
while [ $wait_time -lt $max_wait ]; do
if cfg=$(_bazarr_config_file 2>/dev/null); then
@ -80,78 +80,34 @@ read_bazarr_api_key() {
return 1
}
_bazarr_api_ready() {
local apikey="$1"
http_request GET "http://${API_HOST}:${BAZARR_PORT}/api/system/status" -H "X-API-KEY: ${apikey}"
}
wait_for_bazarr() {
local apikey="$1"
local max_wait="${API_READY_TIMEOUT_SECONDS:-120}"
local wait_time=0
local code
while [ $wait_time -lt $max_wait ]; do
code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 \
"http://${API_HOST}:${BAZARR_PORT}/api/system/status?apikey=${apikey}" 2>/dev/null || echo "000")
if [ "$code" = "200" ]; then
[ "$wait_time" -gt 0 ] && echo >&2
return 0
fi
wait_inline "Waiting for Bazarr API" "$wait_time"
sleep 3
wait_time=$((wait_time + 3))
done
echo >&2
if wait_until "Waiting for Bazarr API" "$max_wait" 3 _bazarr_api_ready "$apikey"; then
return 0
fi
log_step_fail "Bazarr: API not ready after ${max_wait}s"
return 1
}
# POST multipart form settings to Bazarr (args are curl -F fragments after apikey)
# POST multipart settings safely using --form-string (no @/< file-upload injection).
_bazarr_post_form() {
local apikey="$1"
shift
# Remaining args: -F "key=value" ...
curl -s -o /tmp/bazarr-settings-body.txt -w "%{http_code}" --connect-timeout 15 \
-X POST \
"http://${API_HOST}:${BAZARR_PORT}/api/system/settings?apikey=${apikey}" \
"$@" 2>/dev/null || echo "000"
http_request POST "http://${API_HOST}:${BAZARR_PORT}/api/system/settings" \
-H "X-API-KEY: ${apikey}" "$@" || true
printf '%s' "$HTTP_STATUS"
}
# Map setup / ISO 639-1 or 639-2 codes → Bazarr language filter code2 (ISO 639-1)
_bazarr_lang_code2() {
local code="${1:-en}"
code=${code%%$'\t'*}
code=${code// /}
case "$code" in
""|"none"|"None") echo "en"; return ;;
# Already 2-letter
[a-z][a-z]) echo "$code"; return ;;
# Common ISO 639-2/B (and some T) → 639-1 (setup has stored "eng" etc.)
eng) echo "en" ;;
gre|ell) echo "el" ;;
deu|ger) echo "de" ;;
fra|fre) echo "fr" ;;
spa) echo "es" ;;
ita) echo "it" ;;
por) echo "pt" ;;
nld|dut) echo "nl" ;;
rus) echo "ru" ;;
jpn) echo "ja" ;;
zho|chi) echo "zh" ;;
kor) echo "ko" ;;
ara) echo "ar" ;;
tur) echo "tr" ;;
pol) echo "pl" ;;
swe) echo "sv" ;;
nor) echo "no" ;;
dan) echo "da" ;;
fin) echo "fi" ;;
heb) echo "he" ;;
hin) echo "hi" ;;
*)
# Unknown 3-letter: keep as-is (Bazarr may reject; better than inventing)
echo "$code"
;;
esac
iso639_to_code2 "${1:-en}"
}
# Unique ISO 639-1 codes, preferred first. Args are stored picker codes (eng, ell, en, …).
_bazarr_code2_list() {
local -a out=()
local c mapped x seen
@ -171,9 +127,7 @@ _bazarr_code2_list() {
}
# TRaSH 90/80 assumes hash-rich English catalogs. Non-English OpenSubtitles.com
# hits typically miss hash and source (WEB-DL vs community BluRay) and score ~55-74,
# so a 90/80 floor skips them. Subsync still retimes anything below 96/86.
# Prints: "<series> <movie>"
# hits score lower (~55-74); drop min scores to 70/50 when non-English languages exist.
_bazarr_min_scores() {
local series=90 movie=80 c mapped
for c in "$@"; do
@ -187,28 +141,6 @@ _bazarr_min_scores() {
echo "$series $movie"
}
# Append a provider if it is not already in the providers array.
_bazarr_providers_add() {
local name="$1" p
for p in "${providers[@]+"${providers[@]}"}"; do
[ "$p" = "$name" ] && return 0
done
providers+=("$name")
}
# Providers that actually carry a language. Only when the picker did not
# confirm a set (same rule as auto-adding OpenSubtitles.com).
_bazarr_add_language_providers() {
local code
[ "${FZF_SELECT_STATUS:-}" = "confirmed" ] && return 0
for code in "$@"; do
case "$code" in
el) _bazarr_providers_add greeksubs ;;
esac
done
}
# Default profile JSON: every language in the list, no cutoff (download all of them).
_bazarr_languages_profile_json() {
local langs_json
langs_json=$(_bazarr_code2_list "$@" | jq -R . | jq -sc .)
@ -233,21 +165,21 @@ _bazarr_languages_profile_json() {
]'
}
# Fetch Jellyfin movie/TV library names + ids for Bazarr refresh (optional)
# Fetch Jellyfin movie/TV library names + ids using standard Jellyfin 12 auth header.
_bazarr_jellyfin_libraries() {
local jf_key="$1"
local folders
folders=$(curl -s --connect-timeout 5 \
-H "X-Emby-Token: ${jf_key}" \
"http://${API_HOST}:8096/Library/VirtualFolders" 2>/dev/null || echo "[]")
local folders="[]"
if http_request GET "http://${API_HOST}:8096/Library/VirtualFolders" \
-H "Authorization: MediaBrowser Client=\"assemblrr\", Device=\"assemblrr\", DeviceId=\"assemblrr-cli\", Version=\"1.0\", Token=\"${jf_key}\""; then
folders="$HTTP_BODY"
fi
# Export via globals used by caller
BAZARR_JF_MOVIE_NAMES=()
BAZARR_JF_MOVIE_IDS=()
BAZARR_JF_SERIES_NAMES=()
BAZARR_JF_SERIES_IDS=()
local line name id ctype
local name id ctype
while IFS=$'\t' read -r name id ctype; do
[ -z "$name" ] && continue
case "$ctype" in
@ -260,19 +192,16 @@ _bazarr_jellyfin_libraries() {
BAZARR_JF_SERIES_IDS+=("$id")
;;
esac
done < <(echo "$folders" | jq -r '.[] | select(.CollectionType=="movies" or .CollectionType=="tvshows") | "\(.Name)\t\(.ItemId // .Guid // "")\t\(.CollectionType)"' 2>/dev/null || true)
done < <(printf '%s' "$folders" | jq -r '.[] | select(.CollectionType=="movies" or .CollectionType=="tvshows") | "\(.Name)\t\(.ItemId // .Guid // "")\t\(.CollectionType)"' 2>/dev/null || true)
}
configure_bazarr() {
local bazarr_key=""
local os_user="" os_pass=""
local form_args=()
local http_code
local bazarr_key="" os_user="" os_pass=""
local form_args=() http_code
local providers=()
local profiles_json
local has_sonarr=0 has_radarr=0
local jf_key=""
local jellyfin_refresh=0
local jf_key="" jellyfin_refresh=0
if ! bazarr_key=$(read_bazarr_api_key); then
return 1
@ -282,11 +211,9 @@ configure_bazarr() {
fi
local -a stored_langs=() lang_code2s=()
if type _subtitle_stored_lang_codes >/dev/null 2>&1; then
while IFS= read -r lang_code2; do
[ -n "$lang_code2" ] && stored_langs+=("$lang_code2")
done < <(_subtitle_stored_lang_codes)
fi
while IFS= read -r lang_code2; do
[ -n "$lang_code2" ] && stored_langs+=("$lang_code2")
done < <(_subtitle_stored_lang_codes)
if [ ${#stored_langs[@]} -eq 0 ]; then
stored_langs=("${SUBTITLE_LANGUAGE:-en}")
fi
@ -294,26 +221,19 @@ configure_bazarr() {
[ -n "$lang_code2" ] && lang_code2s+=("$lang_code2")
done < <(_bazarr_code2_list "${stored_langs[@]}")
if [ -n "${SONARR_API_KEY:-}" ]; then
has_sonarr=1
fi
if [ -n "${RADARR_API_KEY:-}" ]; then
has_radarr=1
fi
[ -n "${SONARR_API_KEY:-}" ] && has_sonarr=1
[ -n "${RADARR_API_KEY:-}" ] && has_radarr=1
if [ "$has_sonarr" -eq 0 ] && [ "$has_radarr" -eq 0 ]; then
log_step_fail "Bazarr: neither Sonarr nor Radarr API keys available — skipping"
return 1
fi
# Optional OpenSubtitles.com credentials from secrets/
if [ -s "$INSTALL_DIR/secrets/opensubtitles_username.txt" ] && [ -s "$INSTALL_DIR/secrets/opensubtitles_password.txt" ]; then
os_user=$(cat "$INSTALL_DIR/secrets/opensubtitles_username.txt" 2>/dev/null || echo "")
os_pass=$(cat "$INSTALL_DIR/secrets/opensubtitles_password.txt" 2>/dev/null || echo "")
fi
# Providers: picker confirm = desired set (may be empty). Esc / no picker
# leaves Bazarr's current enabled list alone.
providers=()
if [ "${FZF_SELECT_STATUS:-}" = "confirmed" ]; then
if [ "${#SELECTED_SUBTITLE_PROVIDERS[@]}" -gt 0 ]; then
@ -331,10 +251,10 @@ configure_bazarr() {
[ "$has_os" -eq 0 ] && providers+=(opensubtitlescom)
fi
if [ "${#providers[@]}" -eq 0 ]; then
local current_p
current_p=$(curl -s --connect-timeout 8 \
"http://${API_HOST}:${BAZARR_PORT}/api/system/settings?apikey=${bazarr_key}" 2>/dev/null \
| jq -r '.general.enabled_providers[]? // empty' 2>/dev/null || true)
local current_p=""
if http_request GET "http://${API_HOST}:${BAZARR_PORT}/api/system/settings" -H "X-API-KEY: ${bazarr_key}"; then
current_p=$(printf '%s' "$HTTP_BODY" | jq -r '.general.enabled_providers[]? // empty' 2>/dev/null || true)
fi
if [ -n "$current_p" ]; then
while IFS= read -r p; do
[ -n "$p" ] && providers+=("$p")
@ -346,135 +266,119 @@ configure_bazarr() {
fi
fi
_bazarr_add_language_providers "${lang_code2s[@]}"
local min_series=90 min_movie=80
read -r min_series min_movie < <(_bazarr_min_scores "${stored_langs[@]}")
# --- Core integrations + TRaSH-style scoring ---
form_args=(
-F "settings-general-use_sonarr=$([ "$has_sonarr" -eq 1 ] && echo true || echo false)"
-F "settings-general-use_radarr=$([ "$has_radarr" -eq 1 ] && echo true || echo false)"
-F "settings-general-minimum_score=${min_series}"
-F "settings-general-minimum_score_movie=${min_movie}"
-F "settings-general-subfolder=current"
-F "settings-general-upgrade_subs=true"
-F "settings-general-days_to_upgrade_subs=7"
-F "settings-general-use_embedded_subs=true"
-F "settings-general-serie_default_enabled=true"
-F "settings-general-serie_default_profile=1"
-F "settings-general-movie_default_enabled=true"
-F "settings-general-movie_default_profile=1"
-F "settings-subsync-use_subsync=true"
-F "settings-subsync-use_subsync_threshold=true"
-F "settings-subsync-subsync_threshold=96"
-F "settings-subsync-use_subsync_movie_threshold=true"
-F "settings-subsync-subsync_movie_threshold=86"
--form-string "settings-general-use_sonarr=$([ "$has_sonarr" -eq 1 ] && echo true || echo false)"
--form-string "settings-general-use_radarr=$([ "$has_radarr" -eq 1 ] && echo true || echo false)"
--form-string "settings-general-minimum_score=${min_series}"
--form-string "settings-general-minimum_score_movie=${min_movie}"
--form-string "settings-general-subfolder=current"
--form-string "settings-general-upgrade_subs=true"
--form-string "settings-general-days_to_upgrade_subs=7"
--form-string "settings-general-use_embedded_subs=true"
--form-string "settings-general-serie_default_enabled=true"
--form-string "settings-general-serie_default_profile=1"
--form-string "settings-general-movie_default_enabled=true"
--form-string "settings-general-movie_default_profile=1"
--form-string "settings-subsync-use_subsync=true"
--form-string "settings-subsync-use_subsync_threshold=true"
--form-string "settings-subsync-subsync_threshold=96"
--form-string "settings-subsync-use_subsync_movie_threshold=true"
--form-string "settings-subsync-subsync_movie_threshold=86"
)
local p
for p in "${providers[@]+"${providers[@]}"}"; do
form_args+=(-F "settings-general-enabled_providers=${p}")
form_args+=(--form-string "settings-general-enabled_providers=${p}")
done
if [ "$has_sonarr" -eq 1 ]; then
form_args+=(
-F "settings-sonarr-ip=sonarr"
-F "settings-sonarr-port=8989"
-F "settings-sonarr-base_url=/"
-F "settings-sonarr-ssl=false"
-F "settings-sonarr-apikey=${SONARR_API_KEY}"
-F "settings-sonarr-only_monitored=true"
--form-string "settings-sonarr-ip=sonarr"
--form-string "settings-sonarr-port=8989"
--form-string "settings-sonarr-base_url=/"
--form-string "settings-sonarr-ssl=false"
--form-string "settings-sonarr-apikey=${SONARR_API_KEY}"
--form-string "settings-sonarr-only_monitored=true"
)
fi
if [ "$has_radarr" -eq 1 ]; then
form_args+=(
-F "settings-radarr-ip=radarr"
-F "settings-radarr-port=7878"
-F "settings-radarr-base_url=/"
-F "settings-radarr-ssl=false"
-F "settings-radarr-apikey=${RADARR_API_KEY}"
-F "settings-radarr-only_monitored=true"
--form-string "settings-radarr-ip=radarr"
--form-string "settings-radarr-port=7878"
--form-string "settings-radarr-base_url=/"
--form-string "settings-radarr-ssl=false"
--form-string "settings-radarr-apikey=${RADARR_API_KEY}"
--form-string "settings-radarr-only_monitored=true"
)
fi
if [ -n "$os_user" ] && [ -n "$os_pass" ]; then
form_args+=(
-F "settings-opensubtitlescom-username=${os_user}"
-F "settings-opensubtitlescom-password=${os_pass}"
-F "settings-opensubtitlescom-use_hash=true"
-F "settings-opensubtitlescom-include_ai_translated=false"
-F "settings-opensubtitlescom-include_machine_translated=false"
--form-string "settings-opensubtitlescom-username=${os_user}"
--form-string "settings-opensubtitlescom-password=${os_pass}"
--form-string "settings-opensubtitlescom-use_hash=true"
--form-string "settings-opensubtitlescom-include_ai_translated=false"
--form-string "settings-opensubtitlescom-include_machine_translated=false"
)
fi
# First wire only: Bazarr hashes the password on save, so later wires
# must not resend it (that would MD5 the hash). Auth edit uses bazarr_set_auth.
local auth_type=""
auth_type=$(curl -s --connect-timeout 8 \
"http://${API_HOST}:${BAZARR_PORT}/api/system/settings?apikey=${bazarr_key}" 2>/dev/null \
| jq -r '.auth.type // empty' 2>/dev/null || true)
if http_request GET "http://${API_HOST}:${BAZARR_PORT}/api/system/settings" -H "X-API-KEY: ${bazarr_key}"; then
auth_type=$(printf '%s' "$HTTP_BODY" | jq -r '.auth.type // empty' 2>/dev/null || true)
fi
if { [ -z "$auth_type" ] || [ "$auth_type" = "null" ] || [ "$auth_type" = "None" ]; } \
&& [ -n "${AUTH_USERNAME:-}" ] && [ -n "${AUTH_PASSWORD:-}" ]; then
form_args+=(
-F "settings-auth-type=form"
-F "settings-auth-username=${AUTH_USERNAME}"
-F "settings-auth-password=${AUTH_PASSWORD}"
--form-string "settings-auth-type=form"
--form-string "settings-auth-username=${AUTH_USERNAME}"
--form-string "settings-auth-password=${AUTH_PASSWORD}"
)
fi
# Jellyfin refresh after subtitle downloads
if [ "${MEDIA_SERVICE:-}" = "jellyfin" ]; then
if [ "${MEDIA_SERVICE:-jellyfin}" = "jellyfin" ]; then
jf_key=$(cat "$INSTALL_DIR/secrets/jellyfin_api_key.txt" 2>/dev/null || echo "")
if [ -n "$jf_key" ]; then
_bazarr_jellyfin_libraries "$jf_key"
form_args+=(
-F "settings-general-use_jellyfin=true"
-F "settings-jellyfin-url=http://jellyfin:8096"
-F "settings-jellyfin-apikey=${jf_key}"
-F "settings-jellyfin-update_movie_library=true"
-F "settings-jellyfin-update_series_library=true"
-F "settings-jellyfin-refresh_method=immediate"
--form-string "settings-general-use_jellyfin=true"
--form-string "settings-jellyfin-url=http://jellyfin:8096"
--form-string "settings-jellyfin-apikey=${jf_key}"
--form-string "settings-jellyfin-update_movie_library=true"
--form-string "settings-jellyfin-update_series_library=true"
--form-string "settings-jellyfin-refresh_method=immediate"
)
local n
if [ "${#BAZARR_JF_MOVIE_NAMES[@]}" -gt 0 ]; then
for n in "${BAZARR_JF_MOVIE_NAMES[@]}"; do
[ -n "$n" ] && form_args+=(-F "settings-jellyfin-movie_library=${n}")
done
fi
if [ "${#BAZARR_JF_MOVIE_IDS[@]}" -gt 0 ]; then
for n in "${BAZARR_JF_MOVIE_IDS[@]}"; do
[ -n "$n" ] && form_args+=(-F "settings-jellyfin-movie_library_ids=${n}")
done
fi
if [ "${#BAZARR_JF_SERIES_NAMES[@]}" -gt 0 ]; then
for n in "${BAZARR_JF_SERIES_NAMES[@]}"; do
[ -n "$n" ] && form_args+=(-F "settings-jellyfin-series_library=${n}")
done
fi
if [ "${#BAZARR_JF_SERIES_IDS[@]}" -gt 0 ]; then
for n in "${BAZARR_JF_SERIES_IDS[@]}"; do
[ -n "$n" ] && form_args+=(-F "settings-jellyfin-series_library_ids=${n}")
done
fi
for n in "${BAZARR_JF_MOVIE_NAMES[@]+"${BAZARR_JF_MOVIE_NAMES[@]}"}"; do
[ -n "$n" ] && form_args+=(--form-string "settings-jellyfin-movie_library=${n}")
done
for n in "${BAZARR_JF_MOVIE_IDS[@]+"${BAZARR_JF_MOVIE_IDS[@]}"}"; do
[ -n "$n" ] && form_args+=(--form-string "settings-jellyfin-movie_library_ids=${n}")
done
for n in "${BAZARR_JF_SERIES_NAMES[@]+"${BAZARR_JF_SERIES_NAMES[@]}"}"; do
[ -n "$n" ] && form_args+=(--form-string "settings-jellyfin-series_library=${n}")
done
for n in "${BAZARR_JF_SERIES_IDS[@]+"${BAZARR_JF_SERIES_IDS[@]}"}"; do
[ -n "$n" ] && form_args+=(--form-string "settings-jellyfin-series_library_ids=${n}")
done
jellyfin_refresh=1
else
_cfg_log_info "Bazarr: Jellyfin API key not found — skipping JF refresh integration"
fi
fi
# Language filter + profile (id 1 = Default). First language is preferred
# (listed first); cutoff stays null so Bazarr still downloads the extras.
profiles_json=$(_bazarr_languages_profile_json "${stored_langs[@]}")
local enabled
for enabled in "${lang_code2s[@]}"; do
form_args+=(-F "languages-enabled=${enabled}")
form_args+=(--form-string "languages-enabled=${enabled}")
done
if [ "${#lang_code2s[@]}" -gt 1 ]; then
form_args+=(-F "settings-general-single_language=false")
form_args+=(--form-string "settings-general-single_language=false")
fi
form_args+=(-F "languages-profiles=${profiles_json}")
form_args+=(--form-string "languages-profiles=${profiles_json}")
http_code=$(_bazarr_post_form "$bazarr_key" "${form_args[@]}")
if [ "$http_code" = "204" ] || [ "$http_code" = "200" ]; then
@ -488,39 +392,47 @@ configure_bazarr() {
log_step "Bazarr: Jellyfin refresh enabled"
fi
else
local body=""
body=$(cat /tmp/bazarr-settings-body.txt 2>/dev/null | head -c 200 || true)
local body="${HTTP_BODY:0:200}"
log_step_fail "Bazarr: settings POST failed (HTTP ${http_code}${body:+: $body})"
return 1
fi
# Persist key for operators / future tooling
echo -n "$bazarr_key" > "$INSTALL_DIR/secrets/bazarr_api_key.txt"
chmod 600 "$INSTALL_DIR/secrets/bazarr_api_key.txt" 2>/dev/null || true
write_secret_file "$INSTALL_DIR/secrets/bazarr_api_key.txt" "$bazarr_key"
# Kick library sync, then search wanted now (don't wait for the 6h interval).
if [ "$has_sonarr" -eq 1 ]; then
curl -s -o /dev/null --connect-timeout 5 -X POST \
-F "taskid=update_series" \
"http://${API_HOST}:${BAZARR_PORT}/api/system/tasks?apikey=${bazarr_key}" 2>/dev/null || true
curl -s -o /dev/null --connect-timeout 5 -X POST \
-F "taskid=wanted_search_missing_subtitles_series" \
"http://${API_HOST}:${BAZARR_PORT}/api/system/tasks?apikey=${bazarr_key}" 2>/dev/null || true
http_request POST "http://${API_HOST}:${BAZARR_PORT}/api/system/tasks" -H "X-API-KEY: ${bazarr_key}" \
--form-string "taskid=update_series" || true
http_request POST "http://${API_HOST}:${BAZARR_PORT}/api/system/tasks" -H "X-API-KEY: ${bazarr_key}" \
--form-string "taskid=wanted_search_missing_subtitles_series" || true
fi
if [ "$has_radarr" -eq 1 ]; then
curl -s -o /dev/null --connect-timeout 5 -X POST \
-F "taskid=update_movies" \
"http://${API_HOST}:${BAZARR_PORT}/api/system/tasks?apikey=${bazarr_key}" 2>/dev/null || true
curl -s -o /dev/null --connect-timeout 5 -X POST \
-F "taskid=wanted_search_missing_subtitles_movies" \
"http://${API_HOST}:${BAZARR_PORT}/api/system/tasks?apikey=${bazarr_key}" 2>/dev/null || true
http_request POST "http://${API_HOST}:${BAZARR_PORT}/api/system/tasks" -H "X-API-KEY: ${bazarr_key}" \
--form-string "taskid=update_movies" || true
http_request POST "http://${API_HOST}:${BAZARR_PORT}/api/system/tasks" -H "X-API-KEY: ${bazarr_key}" \
--form-string "taskid=wanted_search_missing_subtitles_movies" || true
fi
return 0
}
# Set Bazarr form login. Always sends a fresh password (Bazarr MD5s it).
# Do not call this from the regular wire loop — only from auth edit.
trigger_bazarr_library_sync() {
local cfg="" bazarr_key=""
if cfg=$(_bazarr_config_file 2>/dev/null); then
bazarr_key=$(_bazarr_extract_apikey "$cfg")
fi
if [ -z "$bazarr_key" ] && [ -f "$INSTALL_DIR/secrets/bazarr_api_key.txt" ]; then
bazarr_key=$(cat "$INSTALL_DIR/secrets/bazarr_api_key.txt" 2>/dev/null || echo "")
fi
[ -n "$bazarr_key" ] || return 0
http_request POST "http://${API_HOST}:${BAZARR_PORT}/api/system/tasks" -H "X-API-KEY: ${bazarr_key}" \
--form-string "taskid=update_movies" || true
http_request POST "http://${API_HOST}:${BAZARR_PORT}/api/system/tasks" -H "X-API-KEY: ${bazarr_key}" \
--form-string "taskid=update_series" || true
log_step "Bazarr: triggered library sync with Sonarr/Radarr"
return 0
}
bazarr_set_auth() {
local bazarr_key=""
if [ -z "${AUTH_USERNAME:-}" ] || [ -z "${AUTH_PASSWORD:-}" ]; then
@ -536,15 +448,14 @@ bazarr_set_auth() {
local http_code
http_code=$(_bazarr_post_form "$bazarr_key" \
-F "settings-auth-type=form" \
-F "settings-auth-username=${AUTH_USERNAME}" \
-F "settings-auth-password=${AUTH_PASSWORD}")
--form-string "settings-auth-type=form" \
--form-string "settings-auth-username=${AUTH_USERNAME}" \
--form-string "settings-auth-password=${AUTH_PASSWORD}")
if [ "$http_code" = "204" ] || [ "$http_code" = "200" ]; then
log_step "Bazarr: set login (${AUTH_USERNAME})"
return 0
fi
local body=""
body=$(cat /tmp/bazarr-settings-body.txt 2>/dev/null | head -c 200 || true)
local body="${HTTP_BODY:0:200}"
log_step_fail "Bazarr: failed to set login (HTTP ${http_code}${body:+: $body})"
return 1
}

20
lib/branding.sh Normal file → Executable file
View file

@ -1,4 +1,5 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr branding loader — sourced by entry points that need branding
# Requires: lib/core.sh (for safe_source)
@ -7,17 +8,20 @@ if [ -n "${_ASSEMBLRR_BRANDING_SOURCED:-}" ]; then
fi
readonly _ASSEMBLRR_BRANDING_SOURCED=1
# Load branding.conf from a given directory, with hardcoded fallback defaults.
# Usage: load_branding "$dir_containing_branding_conf"
# Load branding.conf from a given directory, with fallback defaults for every key.
load_branding() {
local _branding_dir="$1"
if [ -f "$_branding_dir/branding.conf" ]; then
safe_source "$_branding_dir/branding.conf"
else
APP_NAME="assemblrr"
APP_DISPLAY_NAME="assemblrr"
APP_CLI_NAME="assemblrr"
APP_NETWORK_NAME="assemblrr_network"
APP_BACKUP_PREFIX="assemblrr-backup"
fi
APP_NAME="${APP_NAME:-assemblrr}"
APP_DISPLAY_NAME="${APP_DISPLAY_NAME:-assemblrr}"
APP_DESCRIPTION="${APP_DESCRIPTION:-Your one-click media server}"
APP_CLI_NAME="${APP_CLI_NAME:-assemblrr}"
APP_NETWORK_NAME="${APP_NETWORK_NAME:-assemblrr_network}"
APP_REPO_URL="${APP_REPO_URL:-https://github.com/soulis-1256/assemblrr}"
APP_DEFAULT_INSTALL_DIR="${APP_DEFAULT_INSTALL_DIR:-$HOME/$APP_NAME}"
APP_DEFAULT_MEDIA_DIR="${APP_DEFAULT_MEDIA_DIR:-$HOME/$APP_NAME-media}"
APP_BACKUP_PREFIX="${APP_BACKUP_PREFIX:-assemblrr-backup}"
}

52
lib/compose.sh Normal file → Executable file
View file

@ -1,4 +1,5 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Docker Compose builder — sourced by entry points that manage containers
# Requires: lib/core.sh for compose_up_stack (wait_while, run_docker, log_warning)
@ -7,12 +8,10 @@ if [ -n "${_ASSEMBLRR_COMPOSE_SOURCED:-}" ]; then
fi
readonly _ASSEMBLRR_COMPOSE_SOURCED=1
# Builds the docker compose arguments array (COMPOSE_ARGS) based on VPN mode.
# Builds the docker compose arguments array (COMPOSE_ARGS) based on VPN & feature flags.
# Usage: build_compose_args "$install_dir" "$vpn_enabled"
# $1 = install directory (e.g. /home/user/assemblrr)
# $2 = vpn enabled flag ("y" or "n")
# After calling, COMPOSE_ARGS contains -f flags and --project-directory.
# Caller should add "--profile" and "docker compose" prefix as needed.
# Reads optional env flags: VUETORRENT_ENABLED, GPU_TRANSCODING, BYPARR_ENABLED, USENET_ENABLED.
# custom.yaml is always appended last so user overrides win.
build_compose_args() {
local _install_dir="$1"
local _vpn_enabled="${2:-n}"
@ -26,7 +25,34 @@ build_compose_args() {
COMPOSE_ARGS+=("-f" "$_install_dir/compose/direct-access.yaml")
fi
# Check for custom overlay
if [ "${VUETORRENT_ENABLED:-n}" = "y" ] || [ "${VUETORRENT_ENABLED:-n}" = "Y" ]; then
if [ -f "$_install_dir/compose/vuetorrent.yaml" ]; then
COMPOSE_ARGS+=("-f" "$_install_dir/compose/vuetorrent.yaml")
fi
fi
case "${GPU_TRANSCODING:-none}" in
intel|INTEL|amd|AMD|vaapi|VAAPI)
[ -f "$_install_dir/compose/gpu-intel.yaml" ] && COMPOSE_ARGS+=("-f" "$_install_dir/compose/gpu-intel.yaml")
;;
nvidia|NVIDIA)
[ -f "$_install_dir/compose/gpu-nvidia.yaml" ] && COMPOSE_ARGS+=("-f" "$_install_dir/compose/gpu-nvidia.yaml")
;;
esac
if [ "${BYPARR_ENABLED:-n}" = "y" ] || [ "${BYPARR_ENABLED:-n}" = "Y" ]; then
if [ -f "$_install_dir/compose/byparr.yaml" ]; then
COMPOSE_ARGS+=("-f" "$_install_dir/compose/byparr.yaml")
fi
fi
if [ "${USENET_ENABLED:-n}" = "y" ] || [ "${USENET_ENABLED:-n}" = "Y" ]; then
if [ -f "$_install_dir/compose/usenet.yaml" ]; then
COMPOSE_ARGS+=("-f" "$_install_dir/compose/usenet.yaml")
fi
fi
# User custom overlay always last so overrides win cleanly
if [ -f "$_install_dir/compose/custom.yaml" ]; then
COMPOSE_ARGS+=("-f" "$_install_dir/compose/custom.yaml")
fi
@ -34,20 +60,22 @@ build_compose_args() {
# Bring the stack up. Image pulls and sidecar Dockerfile builds (apk, layers)
# stay off the terminal. Failures print a tail of the captured log.
# Usage: compose_up_stack <profile> [extra docker compose args...]
# Requires COMPOSE_ARGS from build_compose_args.
# Usage: compose_up_stack [profile] [extra docker compose args...]
compose_up_stack() {
local profile="${1:-}"
if [ -z "$profile" ]; then
return 1
local -a profile_args=()
if [ -n "$profile" ]; then
shift
if [ "$profile" != "default" ]; then
profile_args=(--profile "$profile")
fi
fi
shift
if [ "${#COMPOSE_ARGS[@]}" -eq 0 ]; then
return 1
fi
if ! wait_while "Starting services" \
run_docker compose "${COMPOSE_ARGS[@]}" --profile "$profile" up -d --remove-orphans "$@"; then
run_docker compose "${COMPOSE_ARGS[@]}" "${profile_args[@]}" up -d --remove-orphans "$@"; then
log_warning "Failed to start services"
if [ -n "${WAIT_WHILE_OUTPUT:-}" ]; then
echo "$WAIT_WHILE_OUTPUT" | tail -n 40

231
lib/config_edit.sh Normal file → Executable file
View file

@ -1,7 +1,8 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Modular config edit — shared prompt/picker engines, post-install copy.
# Sourced by the CLI. Does not run on source.
# Provides: config_edit_run, config_edit_usage, config_edit_section_ids, config_set_kv
# Does not set -euo pipefail when sourced.
if [ -n "${_ASSEMBLRR_CONFIG_EDIT_SOURCED:-}" ]; then
return 0
@ -23,7 +24,10 @@ opensubtitles|OpenSubtitles.com username and password
auth|Shared login for every service UI
timezone|Container timezone
vpn|VPN on/off, provider, and credentials (restarts stack)
media|Jellyfin (supported) / Emby / Plex unsupported (restarts stack)
vuetorrent|qBittorrent VueTorrent WebUI theme (restarts stack)
gpu|Jellyfin hardware GPU transcoding: Intel/AMD or NVIDIA (restarts stack)
byparr|Byparr Cloudflare solver for Prowlarr (restarts stack)
usenet|SABnzbd Usenet downloader and NNTP provider (restarts stack)
all|Re-run the full setup wizard
EOF
}
@ -46,7 +50,6 @@ config_edit_usage() {
done < <(_config_edit_catalog)
}
# Resolve picker output to a catalog id. Empty → "".
config_edit_resolve() {
local want="${1:-}"
want=$(echo "$want" | tr '[:upper:]' '[:lower:]')
@ -62,40 +65,51 @@ config_edit_resolve() {
return 1
}
# Update or append KEY=value in a dotenv / runtime-config file.
# $4 = quoted (1, default) writes KEY="value"; 0 writes KEY=value
# Atomically update or append KEY=value in a dotenv / runtime-config file, preserving mode.
# $4 = quoted (1, default) writes KEY="escaped_value"; 0 writes KEY=value
config_set_kv() {
local file="$1"
local key="$2"
local value="$3"
local quoted="${4:-1}"
local tmp line_out
local tmp mode="" escaped
[ -n "$file" ] && [ -n "$key" ] || return 1
mkdir -p "$(dirname "$file")"
if [ -f "$file" ]; then
mode=$(stat -c '%a' "$file" 2>/dev/null || stat -f '%Lp' "$file" 2>/dev/null || echo "")
fi
tmp=$(mktemp)
if [ -f "$file" ]; then
grep -v "^${key}=" "$file" > "$tmp" || true
fi
if [ "$quoted" = "1" ]; then
printf '%s="%s"\n' "$key" "$value" >> "$tmp"
escaped="${value//\\/\\\\}"
escaped="${escaped//\"/\\\"}"
printf '%s="%s"\n' "$key" "$escaped" >> "$tmp"
else
printf '%s=%s\n' "$key" "$value" >> "$tmp"
fi
mv "$tmp" "$file"
if [ -n "$mode" ]; then
chmod "$mode" "$file" 2>/dev/null || true
fi
}
# Remove KEY=... lines from a dotenv / runtime-config file.
config_unset_kv() {
local file="$1"
local key="$2"
local tmp
local tmp mode=""
[ -n "$file" ] && [ -n "$key" ] || return 1
[ -f "$file" ] || return 0
mode=$(stat -c '%a' "$file" 2>/dev/null || stat -f '%Lp' "$file" 2>/dev/null || echo "")
tmp=$(mktemp)
grep -v "^${key}=" "$file" > "$tmp" || true
mv "$tmp" "$file"
if [ -n "$mode" ]; then
chmod "$mode" "$file" 2>/dev/null || true
fi
}
# --- load install + *arr libs (idempotent) ---
@ -109,6 +123,7 @@ _config_edit_load() {
if [ -z "${INSTALL_DIR:-}" ] || [ ! -d "$INSTALL_DIR" ]; then
log_error "Could not find installation. Run setup first."
return 1
fi
safe_source "$INSTALL_DIR/.assemblrr-config"
@ -131,12 +146,9 @@ _config_edit_load() {
AUTH_USERNAME=$(cat "$INSTALL_DIR/secrets/auth_username.txt" 2>/dev/null || echo "${AUTH_USERNAME:-$USER}")
AUTH_PASSWORD=$(cat "$INSTALL_DIR/secrets/auth_password.txt" 2>/dev/null || echo "${AUTH_PASSWORD:-}")
# Section editors always use the interactive prompts, never express defaults.
ui_set_mode edit
SETUP_MODE="manual"
if [ -z "${SUPPORTED_MEDIA_SERVICES+x}" ]; then
SUPPORTED_MEDIA_SERVICES=("jellyfin" "emby" "plex")
fi
SUPPORTED_MEDIA_SERVICES=("jellyfin")
CONFIGURE_LOG="${CONFIGURE_LOG:-/tmp/${APP_NAME:-assemblrr}-config-edit-$(date '+%Y%m%d-%H%M%S').log}"
if ! type _cfg_log_info >/dev/null 2>&1; then
@ -146,29 +158,16 @@ _config_edit_load() {
_configure_total=0
_configure_ok=0
_configure_fail=0
log_step() { echo -e " ${GREEN}✓${NC} $1" | tee -a "$CONFIGURE_LOG"; _configure_ok=$((_configure_ok + 1)); _configure_total=$((_configure_total + 1)); }
log_step_fail() { echo -e " ${RED}✗${NC} $1" | tee -a "$CONFIGURE_LOG"; _configure_fail=$((_configure_fail + 1)); _configure_total=$((_configure_total + 1)); }
log_step() { printf ' %b✓%b %s\n' "${GREEN:-}" "${NC:-}" "$1"; printf ' ✓ %s\n' "$1" >> "$CONFIGURE_LOG"; _configure_ok=$((_configure_ok + 1)); _configure_total=$((_configure_total + 1)); }
log_step_fail() { printf ' %b✗%b %s\n' "${RED:-}" "${NC:-}" "$1"; printf ' ✗ %s\n' "$1" >> "$CONFIGURE_LOG"; _configure_fail=$((_configure_fail + 1)); _configure_total=$((_configure_total + 1)); }
fi
local lib="${INSTALL_DIR}/lib"
# shellcheck source=/dev/null
[ -f "$lib/ui.sh" ] && source "$lib/ui.sh"
# shellcheck source=/dev/null
[ -f "$lib/fzf-tui.sh" ] && source "$lib/fzf-tui.sh"
# shellcheck source=/dev/null
[ -f "$lib/api.sh" ] && source "$lib/api.sh"
# shellcheck source=/dev/null
[ -f "$lib/quality.sh" ] && source "$lib/quality.sh"
# shellcheck source=/dev/null
[ -f "$lib/arr.sh" ] && source "$lib/arr.sh"
# shellcheck source=/dev/null
[ -f "$lib/jellyfin.sh" ] && source "$lib/jellyfin.sh"
# shellcheck source=/dev/null
[ -f "$lib/seerr.sh" ] && source "$lib/seerr.sh"
# shellcheck source=/dev/null
[ -f "$lib/bazarr.sh" ] && source "$lib/bazarr.sh"
# shellcheck source=/dev/null
[ -f "$lib/prompts.sh" ] && source "$lib/prompts.sh"
local m
for m in ui.sh fzf-tui.sh api.sh quality.sh arr.sh recyclarr.sh jellyfin.sh seerr.sh bazarr.sh usenet.sh prompts.sh; do
# shellcheck source=/dev/null
[ -f "$lib/$m" ] && source "$lib/$m"
done
_config_edit_load_keys
_config_edit_loaded=1
@ -196,8 +195,9 @@ _config_edit_runtime_file() {
_config_edit_restart_stack() {
log_info "Restarting stack to apply compose/env changes..."
build_compose_args "$INSTALL_DIR" "${VPN_ENABLED:-n}"
if ! compose_up_stack "${MEDIA_SERVICE:-jellyfin}"; then
if ! compose_up_stack "default"; then
log_error "docker compose up failed"
return 1
fi
log_success "Stack restarted"
}
@ -219,15 +219,16 @@ _config_edit_pick() {
echo "$selected"
return 0
fi
echo
log_info "What do you want to change?"
# Non-fzf fallback prints all UI/prompts to stderr so stdout returns ONLY the chosen section id
echo >&2
log_info "What do you want to change?" >&2
local i=1 id desc
while IFS='|' read -r id desc; do
printf " %2d) %-14s %s\n" "$i" "$id" "$desc"
printf " %2d) %-14s %s\n" "$i" "$id" "$desc" >&2
i=$((i + 1))
done < <(_config_edit_catalog)
local choice
read -p "Choose a section [1]: " choice || true
local choice=""
read_prompt "Choose a section [1]: " choice
choice=${choice:-1}
if [[ "$choice" =~ ^[0-9]+$ ]]; then
sed -n "${choice}p" < <(config_edit_section_ids)
@ -242,9 +243,11 @@ _config_edit_indexers() {
_config_edit_load
if [ -z "${PROWLARR_API_KEY:-}" ]; then
log_error "Prowlarr API key not available. Is Prowlarr running?"
return 1
fi
if ! wait_for_api "Prowlarr" "9696" "$PROWLARR_API_KEY" "/api/v1/system/status"; then
log_error "Prowlarr is not responding on port 9696"
return 1
fi
SELECTED_INDEXERS=()
configure_indexers "$PROWLARR_API_KEY"
@ -256,7 +259,7 @@ _config_edit_indexers() {
if [ -t 0 ] && [ "${ASSEMBLRR_NONINTERACTIVE:-0}" != "1" ]; then
echo
log_warning "No indexers selected."
read -p "Remove ALL Prowlarr indexers? (y/N) [Default = n]: " wipe
read_prompt "Remove ALL Prowlarr indexers? (y/N) [Default = n]: " wipe
wipe=${wipe:-n}
fi
if [ "${wipe,,}" != "y" ]; then
@ -282,7 +285,7 @@ _config_edit_providers() {
if [ -t 0 ] && [ "${ASSEMBLRR_NONINTERACTIVE:-0}" != "1" ]; then
echo
log_warning "No subtitle providers selected."
read -p "Disable ALL Bazarr providers? (y/N) [Default = n]: " wipe
read_prompt "Disable ALL Bazarr providers? (y/N) [Default = n]: " wipe
wipe=${wipe:-n}
fi
if [ "${wipe,,}" != "y" ]; then
@ -304,9 +307,7 @@ _config_edit_language() {
SUBTITLE_LANGUAGE="${subtitle_language:-}"
SUBTITLE_LANGUAGES="${subtitle_languages:-}"
configure_bazarr || true
if [ "${MEDIA_SERVICE:-}" = "jellyfin" ]; then
configure_jellyfin || true
fi
configure_jellyfin || true
}
_config_edit_profile() {
@ -333,8 +334,10 @@ _config_edit_opensubtitles() {
local secrets_dir="$INSTALL_DIR/secrets"
mkdir -p "$secrets_dir"
if [ "${opensubtitles_enabled:-n}" = "y" ] && [ -n "${opensubtitles_username:-}" ]; then
echo -n "${opensubtitles_username}" > "$secrets_dir/opensubtitles_username.txt"
echo -n "${opensubtitles_password:-}" > "$secrets_dir/opensubtitles_password.txt"
(umask 077
echo -n "${opensubtitles_username}" > "$secrets_dir/opensubtitles_username.txt"
echo -n "${opensubtitles_password:-}" > "$secrets_dir/opensubtitles_password.txt"
)
chmod 600 "$secrets_dir/opensubtitles_username.txt" "$secrets_dir/opensubtitles_password.txt"
log_success "OpenSubtitles.com credentials written to $secrets_dir"
configure_bazarr || true
@ -375,34 +378,27 @@ _config_edit_auth() {
fail=1
fi
case "${MEDIA_SERVICE:-jellyfin}" in
jellyfin)
jellyfin_change_credentials "$old_user" "$old_pass" "$AUTH_USERNAME" "$AUTH_PASSWORD" || fail=1
;;
emby)
jellyfin_change_credentials "$old_user" "$old_pass" "$AUTH_USERNAME" "$AUTH_PASSWORD" 8096 "Emby" || fail=1
;;
plex)
log_warning "Plex account password is not this login — change it in Plex."
;;
esac
jellyfin_change_credentials "$old_user" "$old_pass" "$AUTH_USERNAME" "$AUTH_PASSWORD" || fail=1
bazarr_set_auth || fail=1
if [ "${MEDIA_SERVICE:-jellyfin}" = "jellyfin" ] || [ "${MEDIA_SERVICE:-}" = "emby" ]; then
if type seerr_verify_login >/dev/null 2>&1; then
seerr_verify_login || true
fi
if sabnzbd_enabled 2>/dev/null; then
sabnzbd_change_credentials "$AUTH_USERNAME" "$AUTH_PASSWORD" || fail=1
fi
if type seerr_verify_login >/dev/null 2>&1; then
seerr_verify_login || true
fi
if [ "$fail" -ne 0 ]; then
log_warning "Some UIs did not take the new password. Secrets were left unchanged. Run ${APP_CLI_NAME:-assemblrr} config edit and pick login again (same password)."
log_warning "Some UIs did not take the new password. Secrets were left unchanged. Run ${APP_CLI_NAME:-assemblrr} config edit and pick auth again."
return 1
fi
mkdir -p "$secrets_dir"
echo -n "$AUTH_USERNAME" > "$secrets_dir/auth_username.txt"
echo -n "$AUTH_PASSWORD" > "$secrets_dir/auth_password.txt"
(umask 077
echo -n "$AUTH_USERNAME" > "$secrets_dir/auth_username.txt"
echo -n "$AUTH_PASSWORD" > "$secrets_dir/auth_password.txt"
)
chmod 600 "$secrets_dir/auth_username.txt" "$secrets_dir/auth_password.txt"
log_success "Auth credentials written to $secrets_dir"
}
@ -441,15 +437,17 @@ _config_edit_vpn() {
local secrets_dir="$INSTALL_DIR/secrets"
mkdir -p "$secrets_dir"
if [ "$enabled" = "y" ]; then
if [ "${vpn_type:-}" = "openvpn" ]; then
echo -n "${vpn_user:-}" > "$secrets_dir/openvpn_user.txt"
echo -n "${vpn_password:-}" > "$secrets_dir/openvpn_password.txt"
: > "$secrets_dir/wireguard_private_key.txt"
else
echo -n "${wireguard_private_key:-}" > "$secrets_dir/wireguard_private_key.txt"
: > "$secrets_dir/openvpn_user.txt"
: > "$secrets_dir/openvpn_password.txt"
fi
(umask 077
if [ "${vpn_type:-}" = "openvpn" ]; then
echo -n "${vpn_user:-}" > "$secrets_dir/openvpn_user.txt"
echo -n "${vpn_password:-}" > "$secrets_dir/openvpn_password.txt"
: > "$secrets_dir/wireguard_private_key.txt"
else
echo -n "${wireguard_private_key:-}" > "$secrets_dir/wireguard_private_key.txt"
: > "$secrets_dir/openvpn_user.txt"
: > "$secrets_dir/openvpn_password.txt"
fi
)
chmod 600 \
"$secrets_dir/openvpn_user.txt" \
"$secrets_dir/openvpn_password.txt" \
@ -478,19 +476,69 @@ _config_edit_vpn() {
fi
}
_config_edit_media() {
_config_edit_vuetorrent() {
_config_edit_load
local previous="${MEDIA_SERVICE:-jellyfin}"
configure_media_service
MEDIA_SERVICE="$media_service"
config_set_kv "$(_config_edit_runtime_file)" "MEDIA_SERVICE" "$MEDIA_SERVICE"
config_set_kv "$INSTALL_DIR/.env" "MEDIA_SERVICE" "$MEDIA_SERVICE" 0
configure_vuetorrent
VUETORRENT_ENABLED="${vuetorrent_enabled:-n}"
config_set_kv "$(_config_edit_runtime_file)" "VUETORRENT_ENABLED" "$VUETORRENT_ENABLED"
config_set_kv "$INSTALL_DIR/.env" "VUETORRENT_ENABLED" "$VUETORRENT_ENABLED" 0
_config_edit_restart_stack
if [ "$MEDIA_SERVICE" = "jellyfin" ]; then
configure_jellyfin || true
configure_jellyfin_notifications || true
elif [ "$previous" != "$MEDIA_SERVICE" ]; then
log_info "Switched media server to ${MEDIA_SERVICE}. Finish any first-run UI setup, then run: ${APP_CLI_NAME:-assemblrr} config apply"
qbit_set_credentials || true
}
_config_edit_gpu() {
_config_edit_load
configure_gpu_transcoding
GPU_TRANSCODING="${gpu_transcoding:-none}"
config_set_kv "$(_config_edit_runtime_file)" "GPU_TRANSCODING" "$GPU_TRANSCODING"
config_set_kv "$INSTALL_DIR/.env" "GPU_TRANSCODING" "$GPU_TRANSCODING" 0
_config_edit_restart_stack
if type configure_jellyfin_transcoding >/dev/null 2>&1; then
type _jf_is_up >/dev/null 2>&1 && wait_until "Waiting for Jellyfin" 60 2 _jf_is_up || true
configure_jellyfin_transcoding "" 8096 || true
fi
}
_config_edit_byparr() {
_config_edit_load
configure_byparr
BYPARR_ENABLED="${byparr_enabled:-n}"
config_set_kv "$(_config_edit_runtime_file)" "BYPARR_ENABLED" "$BYPARR_ENABLED"
config_set_kv "$INSTALL_DIR/.env" "BYPARR_ENABLED" "$BYPARR_ENABLED" 0
_config_edit_restart_stack
if [ -n "${PROWLARR_API_KEY:-}" ]; then
wait_for_api "Prowlarr" "9696" "$PROWLARR_API_KEY" "/api/v1/system/status" || true
prowlarr_sync_byparr_proxy "$PROWLARR_API_KEY" || true
fi
}
_config_edit_usenet() {
_config_edit_load
configure_usenet
USENET_ENABLED="${usenet_enabled:-n}"
config_set_kv "$(_config_edit_runtime_file)" "USENET_ENABLED" "$USENET_ENABLED"
config_set_kv "$INSTALL_DIR/.env" "USENET_ENABLED" "$USENET_ENABLED" 0
config_set_kv "$(_config_edit_runtime_file)" "USENET_HOST" "${usenet_host:-}"
config_set_kv "$(_config_edit_runtime_file)" "USENET_PORT" "${usenet_port:-563}"
config_set_kv "$(_config_edit_runtime_file)" "USENET_SSL" "${usenet_ssl:-y}"
config_set_kv "$(_config_edit_runtime_file)" "USENET_USERNAME" "${usenet_username:-}"
config_set_kv "$(_config_edit_runtime_file)" "USENET_CONNECTIONS" "${usenet_connections:-8}"
USENET_HOST="${usenet_host:-}"
USENET_PORT="${usenet_port:-563}"
USENET_SSL="${usenet_ssl:-y}"
USENET_USERNAME="${usenet_username:-}"
USENET_CONNECTIONS="${usenet_connections:-8}"
if [ -n "${usenet_password:-}" ]; then
mkdir -p "$INSTALL_DIR/secrets"
(umask 077; echo -n "$usenet_password" > "$INSTALL_DIR/secrets/usenet_password.txt")
chmod 600 "$INSTALL_DIR/secrets/usenet_password.txt"
fi
mkdir -p "$INSTALL_DIR/config/sabnzbd"
setup_directory_structure "$MEDIA_DIRECTORY" 2>/dev/null || true
_config_edit_restart_stack
if [ "$USENET_ENABLED" = "y" ]; then
configure_sabnzbd || true
arr_configure_sabnzbd || true
fi
}
@ -504,8 +552,9 @@ _config_edit_all() {
setup_script="$INSTALL_DIR/setup.sh"
else
log_error "setup.sh not found in $INSTALL_DIR"
return 1
fi
bash "$setup_script"
ASSEMBLRR_RECONFIGURE=1 bash "$setup_script" --reconfigure
}
_config_edit_load_picker() {
@ -533,6 +582,7 @@ config_edit_run() {
;;
*)
log_error "Just run '${APP_CLI_NAME:-assemblrr} config edit' and pick from the menu"
return 1
;;
esac
@ -546,9 +596,9 @@ config_edit_run() {
if ! section=$(config_edit_resolve "$raw"); then
log_error "Unknown config section: $raw"
return 1
fi
# fzf's Enter is still on the tty; drain it before any `read` prompt.
flush_tty_input
case "$section" in
@ -560,8 +610,11 @@ config_edit_run() {
auth) _config_edit_auth ;;
timezone) _config_edit_timezone ;;
vpn) _config_edit_vpn ;;
media) _config_edit_media ;;
vuetorrent) _config_edit_vuetorrent ;;
gpu) _config_edit_gpu ;;
byparr) _config_edit_byparr ;;
usenet) _config_edit_usenet ;;
all) _config_edit_all ;;
*) log_error "Unknown config section: $section" ;;
*) log_error "Unknown config section: $section"; return 1 ;;
esac
}

1036
lib/core.sh Normal file → Executable file

File diff suppressed because it is too large Load diff

85
lib/docker.sh Executable file
View file

@ -0,0 +1,85 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Docker & WSL2 Docker Desktop helpers
if [ -n "${_ASSEMBLRR_DOCKER_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_DOCKER_SOURCED=1
_wait_for_wsl_docker_desktop() {
local wait_msg="$1"
local check_cli="$2"
local docker_exe="/mnt/c/Program Files/Docker/Docker/Docker Desktop.exe"
grep -qi microsoft /proc/version 2>/dev/null || return 1
[ -f "$docker_exe" ] && command -v cmd.exe &>/dev/null || return 1
log_info "Docker daemon is not running. Attempting to start Docker Desktop on Windows..."
cmd.exe /c start "" "C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe" < /dev/null > /dev/null 2>&1 &
local i
for i in {1..45}; do
wait_inline "$wait_msg" "$i"
sleep 1
if { [ "$check_cli" != "1" ] || command -v docker &>/dev/null; } && docker info &>/dev/null; then
[ -t 2 ] && printf '\r\033[K' >&2
log_success "Docker Desktop started successfully and is ready."
return 0
fi
done
[ -t 2 ] && printf '\r\033[K' >&2
return 1
}
ensure_docker_running() {
if ! command -v docker &>/dev/null; then
if _wait_for_wsl_docker_desktop "Waiting for Docker Desktop integration" 1; then
return 0
fi
log_warning "Docker is not installed or not in PATH."
return 1
fi
if ! docker info &>/dev/null; then
if _wait_for_wsl_docker_desktop "Waiting for Docker daemon" 0; then
return 0
fi
return 1
fi
return 0
}
# Backwards-compatible alias
verify_docker() {
ensure_docker_running "$@"
}
# Wrapper around `docker` that attempts WSL2 Docker Desktop auto-start on failure,
# while preserving the caller's errexit (`set -e`) setting.
run_docker() {
local had_errexit=0 exit_code=0
[[ $- == *e* ]] && had_errexit=1
set +e
docker "$@"
exit_code=$?
[ "$had_errexit" = 1 ] && set -e
if [ "$exit_code" -ne 0 ]; then
if ! command -v docker &>/dev/null || ! docker info &>/dev/null; then
log_warning "Docker daemon is not running or integration is offline. Attempting auto-start..."
if ensure_docker_running; then
set +e
docker "$@"
exit_code=$?
[ "$had_errexit" = 1 ] && set -e
return "$exit_code"
else
log_error "Docker daemon is not running. Please start Docker and try again."
return 1
fi
fi
fi
return "$exit_code"
}

384
lib/fs.sh Executable file
View file

@ -0,0 +1,384 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr filesystem, secret-writing, ownership, and CLI wrapper helpers
if [ -n "${_ASSEMBLRR_FS_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_FS_SOURCED=1
readonly UTILITY_ALPINE_IMAGE="alpine:3.24.4"
readonly -a DEFAULT_MEDIA_SUBDIRS=(
"torrents/movies"
"torrents/tv"
"torrents/incomplete"
"media/movies"
"media/tv"
"usenet/incomplete"
"usenet/complete/movies"
"usenet/complete/tv"
)
# Write a secret safely: 0700 parent dir + 0600 file via atomic rename (no 0644 TOCTOU).
write_secret_file() {
local path="$1"
local value="${2:-}"
local dir tmp
[ -n "$path" ] || return 1
dir=$(dirname "$path")
mkdir -p "$dir"
chmod 700 "$dir" 2>/dev/null || true
tmp=$(mktemp "${dir}/.tmp.XXXXXX") || return 1
(
umask 077
printf '%s' "$value" > "$tmp"
)
chmod 600 "$tmp"
mv "$tmp" "$path"
}
remove_stale_user_cli_libs() {
local lib="$HOME/.local/bin/lib"
[ -d "$lib" ] || return 0
rm -f "$lib/"*.sh 2>/dev/null || true
rmdir "$lib" 2>/dev/null || true
}
write_user_cli_wrapper() {
local dest="$1"
mkdir -p "$(dirname "$dest")"
cat >"$dest" <<'EOF'
#!/bin/bash
set -euo pipefail
# PATH wrapper — runs the install-tree CLI.
_read_install_dir() {
local f="$1" line
[ -f "$f" ] || return 1
line=$(grep -E '^INSTALL_DIRECTORY=' "$f" | head -1) || return 1
line="${line#INSTALL_DIRECTORY=}"
line="${line%$'\r'}"
line="${line#\"}"
line="${line%\"}"
line="${line#\'}"
line="${line%\'}"
[ -n "$line" ] || return 1
printf '%s\n' "$line"
}
dir="${ASSEMBLRR_DIR:-}"
if [ -z "$dir" ]; then
for f in \
"${HOME}/.assemblrr-config" \
/opt/assemblrr/.assemblrr-config \
"${HOME}/assemblrr/.assemblrr-config"
do
if dir=$(_read_install_dir "$f"); then
break
fi
dir=""
done
fi
if [ -z "$dir" ] || [ ! -f "$dir/cli.sh" ]; then
echo "assemblrr: could not find the install. Run setup, or set ASSEMBLRR_DIR." >&2
exit 1
fi
exec bash "$dir/cli.sh" "$@"
EOF
chmod +x "$dest"
}
install_user_cli_wrapper() {
local dest="$HOME/.local/bin/${APP_CLI_NAME:-assemblrr}"
write_user_cli_wrapper "$dest"
remove_stale_user_cli_libs
ensure_local_bin_on_path
}
_append_path_line() {
local file="$1"
local line="$2"
local marker="$3"
if [ -f "$file" ] && grep -qF "$marker" "$file" 2>/dev/null; then
return 0
fi
mkdir -p "$(dirname "$file")"
printf '%s\n' "$line" >> "$file"
}
ensure_local_bin_on_path() {
export PATH="$HOME/.local/bin:$PATH"
local line='export PATH="$HOME/.local/bin:$PATH"'
local marker='.local/bin'
_append_path_line "$HOME/.profile" "$line" "$marker"
_append_path_line "$HOME/.bashrc" "$line" "$marker"
if [ -f "$HOME/.bash_profile" ]; then
_append_path_line "$HOME/.bash_profile" "$line" "$marker"
fi
if [ -f "$HOME/.zshrc" ] || command -v zsh >/dev/null 2>&1; then
_append_path_line "$HOME/.zshrc" "$line" "$marker"
fi
if command -v fish >/dev/null 2>&1 || [ -d "$HOME/.config/fish" ]; then
_append_path_line "$HOME/.config/fish/config.fish" 'fish_add_path $HOME/.local/bin' "$marker"
fi
}
_canonical_path() {
local p="$1"
if command -v realpath >/dev/null 2>&1; then
realpath -m "$p" 2>/dev/null && return 0
fi
# Pure-bash fallback normalizing /./ and /../ segments
local -a segs=() out=()
local s
IFS='/' read -ra segs <<< "$p"
for s in "${segs[@]}"; do
case "$s" in
""|".") continue ;;
"..") [ "${#out[@]}" -gt 0 ] && unset 'out[${#out[@]}-1]' ;;
*) out+=("$s") ;;
esac
done
local joined
joined=$(IFS=/; echo "${out[*]}")
echo "/$joined"
}
# Validate that a path is safe to remove (used by safe_rm_rf)
_is_safe_rm_path() {
local dir="$1"
if [ -z "$dir" ]; then
log_error "Refusing to remove empty path"
return 1
fi
case "$dir" in
/*) ;;
*)
log_error "Refusing to remove relative path: $dir"
return 1
;;
esac
dir=$(_canonical_path "$dir")
case "$dir" in
""|"/"|"/home"|"/usr"|"/etc"|"/var"|"/opt"|"/root"|"/tmp"|"/mnt"|"/media"|"/bin"|"/lib"|"/sbin"|"${HOME:-}")
log_error "Refusing to remove system path: $dir"
return 1
;;
/mnt/[a-z]|/etc/*|/usr/*|/var/lib|/var/log)
log_error "Refusing to remove protected path: $dir"
return 1
;;
esac
if [[ "$dir" =~ ^/home/[^/]+$ ]]; then
log_error "Refusing to remove home directory: $dir"
return 1
fi
# Require depth >= 3 (e.g. /home/user/assemblrr has 3 slashes).
local slashes="${dir//[^\/]/}"
local depth=${#slashes}
if [ "$depth" -lt 3 ]; then
log_error "Refusing to remove shallow path (depth < 3): $dir"
return 1
fi
return 0
}
safe_rm_rf() {
local dir="$1"
while [ "${dir%/}" != "$dir" ]; do
dir="${dir%/}"
done
if ! _is_safe_rm_path "$dir"; then
return 1
fi
dir=$(_canonical_path "$dir")
if ! rm -rf "$dir" 2>/dev/null; then
local parent_dir base_name
parent_dir="$(dirname "$dir")"
base_name="$(basename "$dir")"
if ! run_docker run --rm -v "$parent_dir:/target" "$UTILITY_ALPINE_IMAGE" rm -rf "/target/$base_name" 2>/dev/null; then
log_warning "Failed to remove $dir. You may need to remove it manually."
fi
fi
}
create_and_verify_directory() {
local dir="$1"
local dir_type="$2"
local quiet="${3:-0}"
local rc=0
if [ ! -d "$dir" ]; then
[ "$quiet" = "1" ] || echo "The directory \"$dir\" does not exist. Attempting to create..."
run_with_timeout 15 mkdir -p "$dir" || rc=$?
if [ "$rc" -eq 124 ]; then
log_error "Timed out creating \"$dir\" (15s). The drive looks stuck (flaky USB / WSL). From PowerShell: wsl --shutdown — then check the drive in Explorer, or re-run setup and pick Home."
elif [ "$rc" -ne 0 ]; then
log_error "Failed to create $dir_type directory at \"$dir\". Check permissions"
elif [ "$quiet" != "1" ]; then
log_success "Directory $dir created"
fi
fi
if [ ! -w "$dir" ] || [ ! -r "$dir" ]; then
log_error "Directory \"$dir\" is not writable or readable. Check permissions"
fi
}
# Set ownership on a path (recursive). Checks descendants before short-circuiting.
ensure_owned() {
local path="$1"
local uid="$2"
local gid="$3"
[ -e "$path" ] || return 0
local actual_uid actual_gid mismatch=""
actual_uid=$(stat -c '%u' "$path" 2>/dev/null || echo "")
actual_gid=$(stat -c '%g' "$path" 2>/dev/null || echo "")
if [ "$actual_uid" = "$uid" ] && [ "$actual_gid" = "$gid" ]; then
if [ -d "$path" ]; then
mismatch=$(find "$path" \( ! -uid "$uid" -o ! -gid "$gid" \) -print -quit 2>/dev/null || true)
if [ -z "$mismatch" ] && { [ "$(id -u)" != "$uid" ] || [ -w "$path" ]; }; then
return 0
fi
else
return 0
fi
fi
if chown -R "$uid:$gid" "$path" 2>/dev/null; then
return 0
fi
if command -v docker >/dev/null 2>&1 || declare -F run_docker >/dev/null 2>&1; then
if [ -d "$path" ]; then
if run_docker run --rm -v "$path:/target" "$UTILITY_ALPINE_IMAGE" chown -R "$uid:$gid" /target >/dev/null 2>&1; then
return 0
fi
elif [ -e "$path" ]; then
local _parent _base
_parent=$(dirname "$path")
_base=$(basename "$path")
if run_docker run --rm -v "$_parent:/target" "$UTILITY_ALPINE_IMAGE" chown "$uid:$gid" "/target/$_base" >/dev/null 2>&1; then
return 0
fi
fi
fi
if command -v sudo >/dev/null 2>&1 && sudo chown -R "$uid:$gid" "$path" 2>/dev/null; then
return 0
fi
log_error "Cannot set ownership of $path to ${uid}:${gid} (Docker may have created it as root). Fix with: sudo chown -R ${uid}:${gid} \"$path\""
}
# Create host bind-mount targets under the install tree before containers start.
prepare_install_dirs() {
local install_dir="$1"
local uid="${2:-$(id -u)}"
local gid="${3:-$(id -g)}"
if [ -z "$install_dir" ]; then
log_error "prepare_install_dirs: install_dir is required"
return 1
fi
local -a rel_paths=(
"config"
"config/gluetun"
"config/jellyfin"
"config/qbittorrent"
"config/sonarr"
"config/radarr"
"config/prowlarr"
"config/seerr"
"config/recyclarr"
"config/bazarr"
"config/sabnzbd"
"secrets"
"scripts"
)
if [ -d "$install_dir" ] && [ ! -w "$install_dir" ]; then
ensure_owned "$install_dir" "$(id -u)" "$(id -g)"
fi
if [ ! -d "$install_dir" ]; then
mkdir -p "$install_dir" || log_error "Failed to create install directory: $install_dir"
fi
if [ -d "$install_dir/config" ] && [ ! -w "$install_dir/config" ]; then
ensure_owned "$install_dir/config" "$(id -u)" "$(id -g)"
fi
local rel path
for rel in "${rel_paths[@]}"; do
path="$install_dir/$rel"
if [ ! -d "$path" ]; then
if ! mkdir -p "$path" 2>/dev/null; then
ensure_owned "$(dirname "$path")" "$(id -u)" "$(id -g)"
mkdir -p "$path" || log_error "Failed to create $path"
fi
fi
done
# Seerr runs as node (UID 1000); skip its subdir when aligning PUID != 1000 to avoid thrashing.
if [ "$uid" = "1000" ] && [ "$gid" = "1000" ]; then
ensure_owned "$install_dir/config" "$uid" "$gid"
else
chown "$uid:$gid" "$install_dir/config" 2>/dev/null || true
local _child
for _child in "$install_dir/config"/*; do
[ -e "$_child" ] || continue
[ "$(basename "$_child")" = "seerr" ] && continue
ensure_owned "$_child" "$uid" "$gid"
done
ensure_owned "$install_dir/config/seerr" "1000" "1000"
fi
ensure_owned "$install_dir/secrets" "$uid" "$gid"
chmod 700 "$install_dir/secrets" 2>/dev/null || true
ensure_owned "$install_dir/scripts" "$uid" "$gid"
if [ "$(id -u)" = "$uid" ] && [ ! -w "$install_dir/config" ]; then
log_error "Install config directory is not writable: $install_dir/config"
fi
}
setup_directory_structure() {
local media_dir="$1"
local -a subdirs=("${DEFAULT_MEDIA_SUBDIRS[@]}")
if [ -n "${MEDIA_SUBDIRS+x}" ] && [ "${#MEDIA_SUBDIRS[@]}" -gt 0 ]; then
subdirs=("${MEDIA_SUBDIRS[@]}")
fi
create_and_verify_directory "$media_dir" "media" 1
local subdir
for subdir in "${subdirs[@]}"; do
create_and_verify_directory "$media_dir/$subdir" "media subdirectory" 1
done
}
verify_user_permissions() {
local username="$1"
local directory="$2"
if ! id -u "$username" &>/dev/null; then
log_error "User \"$username\" doesn't exist!"
fi
if [ "$username" = "$(id -un)" ]; then
if [ ! -w "$directory" ]; then
log_error "User \"$username\" doesn't have write permissions to \"$directory\""
fi
elif ! sudo -u "$username" test -w "$directory"; then
log_error "User \"$username\" doesn't have write permissions to \"$directory\""
fi
}

191
lib/fzf-tui.sh Normal file → Executable file
View file

@ -1,45 +1,24 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# fzf-based TUI for selections (Prowlarr indexers, Bazarr providers, languages, paths)
# Provides reusable fzf selection patterns for assemblrr.
# Sets SELECTED_INDEXERS / SELECTED_SUBTITLE_PROVIDERS / SELECTED_SUBTITLE_LANGUAGES arrays.
# Usage: source lib/fzf-tui.sh; configure_indexers "$api_key"
# Does not set -euo pipefail when sourced.
set -euo pipefail
if [ -n "${_ASSEMBLRR_FZF_TUI_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_FZF_TUI_SOURCED=1
_fzf_tui_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
[ -f "$_fzf_tui_dir/ui.sh" ] && source "$_fzf_tui_dir/ui.sh"
# shellcheck source=/dev/null
[ -f "$_fzf_tui_dir/languages.sh" ] && source "$_fzf_tui_dir/languages.sh"
SELECTED_INDEXERS=()
SELECTED_SUBTITLE_PROVIDERS=()
SELECTED_SUBTITLE_LANGUAGES=()
# Stored picker codes, preferred first. SUBTITLE_LANGUAGES="eng,ell" wins;
# otherwise SUBTITLE_LANGUAGE (legacy single value).
_subtitle_stored_lang_codes() {
local raw="${SUBTITLE_LANGUAGES:-${SUBTITLE_LANGUAGE:-}}"
raw=${raw// /}
[ -z "$raw" ] && return 0
echo "$raw" | tr ',' '\n' | awk 'NF && !seen[$0]++'
}
# $1 = preferred code; remaining args = the full set (may include preferred).
# Prints comma-separated, preferred first, unique.
_subtitle_join_preferred_first() {
local preferred="${1:-}"
shift || true
local -a out=()
local c
[ -n "$preferred" ] && out+=("$preferred")
for c in "$@"; do
[ -z "$c" ] && continue
[ "$c" = "$preferred" ] && continue
out+=("$c")
done
(IFS=,; echo "${out[*]}")
}
# --- TTY detection (reused across functions) ---
_fzf_has_tty() {
[ -t 0 ] && [ -t 2 ]
}
@ -48,6 +27,18 @@ _fzf_can_render() {
command -v fzf &>/dev/null && echo "test" | timeout 1 fzf --height=5 --no-mouse --filter="test" &>/dev/null
}
# True when installed fzf >= major.minor (handles older distro fzf like 0.29 on Ubuntu 22.04).
_fzf_version_ge() {
local req_maj="${1:-0}" req_min="${2:-0}" ver maj min
ver=$(fzf --version 2>/dev/null | awk '{print $1}' | sed 's/[^0-9.].*//')
maj="${ver%%.*}"
min="${ver#*.}"; min="${min%%.*}"
[[ "$maj" =~ ^[0-9]+$ ]] || maj=0
[[ "$min" =~ ^[0-9]+$ ]] || min=0
[ "$maj" -gt "$req_maj" ] && return 0
[ "$maj" -eq "$req_maj" ] && [ "$min" -ge "$req_min" ]
}
# TSV: key<TAB>title<TAB>detail<TAB>install<TAB>media
# Extra args after the two defaults are injected storage roots (tests).
format_path_menu() {
@ -120,21 +111,19 @@ EOF
--height=60% \
--reverse \
--border \
--scrollbar='│' \
2>/dev/null) || true
rm -f "$gen"
echo "$selected"
return 0
fi
local i=0 line
local i=0 title detail
echo "$data" | while IFS=$'\t' read -r _ title detail _; do
i=$((i + 1))
printf ' %d) %s\n %s\n' "$i" "$title" "$detail" >&2
done
echo "Enter number (default: 1 = home): " >&2
local input=""
read -r input || true
read_prompt "Enter number (default: 1 = home): " input
input="${input:-1}"
if [[ "$input" =~ ^[0-9]+$ ]]; then
echo "$data" | awk -F '\t' -v n="$input" 'NR==n {print}'
@ -146,11 +135,11 @@ _prompt_parent_usage() {
local def_install="$2"
local app="${APP_NAME:-assemblrr}"
local choice=""
echo
echo "Use ${parent} for:"
echo " 1) Media only (recommended) — config stays in ${def_install}"
echo " 2) Everything — ${parent}/${app} + ${parent}/${app}-media"
read -p "Choose [1]: " choice
echo >&2
echo "Use ${parent} for:" >&2
echo " 1) Media only (recommended) — config stays in ${def_install}" >&2
echo " 2) Everything — ${parent}/${app} + ${parent}/${app}-media" >&2
read_prompt "Choose [1]: " choice
choice="${choice:-1}"
case "$choice" in
2)
@ -176,9 +165,9 @@ _browse_parent_folder() {
for r in "${HOME:-/}" "${roots[@]}"; do
[ -d "$r" ] || continue
if [ "$r" = "/mnt/c" ]; then
find "$r" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | head -80
find "$r" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | sed -n '1,80p' || true
else
find "$r" -mindepth 1 -maxdepth 2 -type d 2>/dev/null | head -200
find "$r" -mindepth 1 -maxdepth 2 -type d 2>/dev/null | sed -n '1,200p' || true
fi
done
} | sort -u > "$list"
@ -190,8 +179,7 @@ _browse_parent_folder() {
--height=60% --reverse --border \
< "$list" 2>/dev/null) || true
else
echo "Enter a parent folder path (blank to cancel): " >&2
read -r selected || true
read_prompt "Enter a parent folder path (blank to cancel): " selected
fi
rm -f "$list"
echo "$selected"
@ -200,10 +188,10 @@ _browse_parent_folder() {
_prompt_typed_paths() {
local def_install="$1"
local def_media="$2"
read -p "Installation directory? [${def_install}]: " install_directory
read_prompt "Installation directory? [${def_install}]: " install_directory
install_directory=${install_directory:-$def_install}
install_directory=$(expand_path "$install_directory")
read -p "Media directory? [${def_media}]: " media_directory
read_prompt "Media directory? [${def_media}]: " media_directory
media_directory=${media_directory:-$def_media}
media_directory=$(expand_path "$media_directory")
}
@ -212,7 +200,7 @@ _prompt_typed_paths() {
pick_storage_paths() {
local def_install="${APP_DEFAULT_INSTALL_DIR:-$HOME/${APP_NAME:-assemblrr}}"
local def_media="${APP_DEFAULT_MEDIA_DIR:-$HOME/${APP_NAME:-assemblrr}-media}"
local data row key parent
local row key parent
if [ "${ASSEMBLRR_NONINTERACTIVE:-0}" = "1" ]; then
install_directory="$def_install"
@ -229,12 +217,7 @@ pick_storage_paths() {
fi
key=$(printf '%s\n' "$row" | cut -f1)
case "$key" in
home)
install_directory=$(printf '%s\n' "$row" | cut -f4)
media_directory=$(printf '%s\n' "$row" | cut -f5)
return 0
;;
all:*|media:*)
home|all:*|media:*)
install_directory=$(printf '%s\n' "$row" | cut -f4)
media_directory=$(printf '%s\n' "$row" | cut -f5)
return 0
@ -266,8 +249,6 @@ pick_storage_paths() {
}
# Single-select from TSV rows (first column is the value).
# Args: $1 = data, $2 = prompt, $3 = header, $4 = default (Esc / empty / no TTY)
# Puts the default row first so fzf highlights it.
fzf_single_select_data() {
local data="$1"
local prompt="${2:-Select> }"
@ -289,11 +270,10 @@ fzf_single_select_data() {
fi
fi
if ! _fzf_has_tty; then
if ! _fzf_can_render || ! _fzf_has_tty; then
echo "$data" | head -25 >&2
echo "Enter selection (default: ${default:-first}): " >&2
local input=""
read -r input || true
read_prompt "Enter selection (default: ${default:-first}): " input
if [ -z "$input" ]; then
if [ -n "$default" ]; then
echo "$default"
@ -315,7 +295,6 @@ fzf_single_select_data() {
--header="$header" \
--delimiter=$'\t' \
--with-nth=1..2 \
--scrollbar='│' \
2>/dev/null | cut -f1) || true
if [ -z "$selected" ]; then
@ -327,7 +306,6 @@ fzf_single_select_data() {
# Format Prowlarr schema JSON + existing-name JSON array into TSV menu rows:
# name<TAB>badges<TAB>description
# Badges: [already enabled], [P] private (schema enable=false).
format_prowlarr_indexer_menu() {
local schema="$1"
local existing_json="${2:-[]}"
@ -345,44 +323,44 @@ format_prowlarr_indexer_menu() {
' 2>/dev/null || true
}
# fzf --bind start:… string that pre-selects rows whose first TSV field is in $2
# (newline-separated names). Empty if nothing matches.
# Single-pass awk builder for fzf --bind start:... pre-selection.
fzf_preselect_start_bind() {
local data="$1"
local names="$2"
[ -n "$data" ] && [ -n "$names" ] || return 0
local i=0 name binds=""
while IFS=$'\t' read -r name _; do
i=$((i + 1))
[ -n "$name" ] || continue
if printf '%s\n' "$names" | grep -q -F -x "$name"; then
if [ -n "$binds" ]; then
binds="${binds}+pos(${i})+select"
else
binds="pos(${i})+select"
fi
fi
done <<< "$data"
[ -n "$binds" ] && echo "start:${binds}"
awk -v names="$names" '
BEGIN {
n = split(names, arr, /\n/)
for (k = 1; k <= n; k++) {
if (arr[k] != "") want[arr[k]] = 1
}
binds = ""
}
{
split($0, f, "\t")
if (f[1] != "" && (f[1] in want)) {
tok = "pos(" NR ")+select"
binds = (binds == "" ? tok : binds "+" tok)
}
}
END {
if (binds != "") print "start:" binds
}
' <<< "$data"
}
# --- Generic multi-select fzf ---
# Args: $1 = tab-separated list lines
# $2 = prompt (optional)
# $3 = header (optional)
# $4 = result array name (optional; default SELECTED_INDEXERS)
# $5 = noun for log messages (optional; default "item")
# $6 = newline-separated names to pre-select (optional)
# Sets FZF_SELECT_STATUS=confirmed|cancelled.
# Return 0 on confirm (array may be empty), 1 on cancel (Esc).
# Appends selected first-column values into the named array.
# $2 = prompt, $3 = header, $4 = result array var, $5 = noun, $6 = preselect names, $7 = optional preview col
# Keybindings: Tab = toggle, Enter = confirm, Esc = cancel.
fzf_multi_select() {
local data="$1"
local prompt="${2:-Select items> }"
local header="${3:-Enter/TAB=toggle Ctrl-O=confirm Esc=cancel}"
local header="${3:-TAB=toggle Enter=confirm Esc=cancel}"
local result_var="${4:-SELECTED_INDEXERS}"
local noun="${5:-item}"
local preselect_names="${6:-}"
local show_preview="${7:-0}"
local has_tty=false
local -n _fzf_result_ref="$result_var"
FZF_SELECT_STATUS="cancelled"
@ -400,18 +378,23 @@ fzf_multi_select() {
--prompt="$prompt"
--delimiter=$'\t'
--with-nth=1..2
--bind='enter:toggle'
--bind='tab:toggle'
--bind='ctrl-o:accept'
--bind='enter:accept'
--header="$header"
--height=80%
--layout=reverse
--border
)
local start_bind
start_bind=$(fzf_preselect_start_bind "$data" "$preselect_names")
if [ -n "$start_bind" ]; then
fzf_args+=(--sync --bind="$start_bind")
if [ "$show_preview" = "1" ] && _fzf_version_ge 0 29; then
fzf_args+=(--preview='echo {3}' --preview-window='down,3,wrap')
fi
# start:pos(...) requires fzf >= 0.36; skip cleanly on older distros (e.g. Ubuntu 22.04 0.29)
if _fzf_version_ge 0 36; then
local start_bind
start_bind=$(fzf_preselect_start_bind "$data" "$preselect_names")
if [ -n "$start_bind" ]; then
fzf_args+=(--sync --bind="$start_bind")
fi
fi
selected=$(echo "$data" | fzf "${fzf_args[@]}" 2>/dev/null) || fzf_rc=$?
if [ "$fzf_rc" -ne 0 ]; then
@ -421,6 +404,7 @@ fzf_multi_select() {
selected=$(printf '%s\n' "$selected" | cut -f1)
FZF_SELECT_STATUS="confirmed"
if [ -n "$selected" ]; then
local idx
while IFS= read -r idx; do
[ -n "$idx" ] && _fzf_result_ref+=("$idx")
done <<< "$selected"
@ -429,11 +413,10 @@ fzf_multi_select() {
return 0
fi
echo "No interactive terminal available — listing available ${noun}s." >&2
echo "No interactive fzf terminal available — listing available ${noun}s." >&2
echo "$data" | cut -f1 | head -40 | sed 's/^/ /' >&2
echo "Enter ${noun} names separated by spaces (or blank to cancel):" >&2
local input_line=""
read -r input_line || true
local input_line="" idx
read_prompt "Enter ${noun} names separated by spaces (or blank to cancel): " input_line
if [ -z "${input_line:-}" ]; then
FZF_SELECT_STATUS="cancelled"
return 1
@ -448,6 +431,7 @@ fzf_multi_select() {
# --- Prowlarr Indexer Selection ---
configure_indexers() {
local provided_key="$1"
local host="${API_HOST:-127.0.0.1}"
FZF_SELECT_STATUS="cancelled"
if [ "${ASSEMBLRR_NONINTERACTIVE:-0}" = "1" ]; then
log_info "Skipping Prowlarr indexer picker (non-interactive)."
@ -458,7 +442,6 @@ configure_indexers() {
"Add or remove Prowlarr indexers. Esc keeps the current set."
log_info "Only enable sources you are authorized to use."
# Try to fetch indexer list from a running Prowlarr instance
local prowlarr_key="${provided_key:-}"
local indexer_data=""
@ -471,14 +454,14 @@ configure_indexers() {
if [ -n "$prowlarr_key" ]; then
indexer_data=$(curl -s --connect-timeout 3 \
-H "X-Api-Key: $prowlarr_key" \
"http://localhost:9696/api/v1/indexer/schema" 2>/dev/null || true)
"http://${host}:9696/api/v1/indexer/schema" 2>/dev/null || true)
fi
if [ -n "$indexer_data" ] && echo "$indexer_data" | jq -e 'type == "array"' >/dev/null 2>&1; then
local existing_indexers existing_json formatted preselect_names
existing_indexers=$(curl -s --connect-timeout 3 \
-H "X-Api-Key: $prowlarr_key" \
"http://localhost:9696/api/v1/indexer" 2>/dev/null || true)
"http://${host}:9696/api/v1/indexer" 2>/dev/null || true)
existing_json=$(echo "${existing_indexers:-}" | jq -c '[.[].name // empty]' 2>/dev/null || echo '[]')
[ -n "$existing_json" ] || existing_json='[]'
formatted=$(format_prowlarr_indexer_menu "$indexer_data" "$existing_json")
@ -486,17 +469,18 @@ configure_indexers() {
local prompt header
if ui_is_edit; then
prompt="Prowlarr indexers> "
header="Enter/TAB=toggle Ctrl-O=save Esc=cancel [P]=private"
header="TAB=toggle Enter=save Esc=cancel [P]=private"
else
prompt="Prowlarr indexers (optional)> "
header="Enter/TAB=toggle Ctrl-O=confirm Esc=skip [P]=private"
header="TAB=toggle Enter=confirm Esc=skip [P]=private"
fi
fzf_multi_select "$formatted" \
"$prompt" \
"$header" \
SELECTED_INDEXERS \
"indexer" \
"$preselect_names" || true
"$preselect_names" \
1 || true
ui_picker_done "indexers"
else
if ui_is_edit; then
@ -508,8 +492,6 @@ configure_indexers() {
fi
}
# List subtitle provider keys from the running Bazarr container (Bazarr's catalog, not ours).
# Skips internal modules only (mixins/utils/helpers), not branded providers.
_list_bazarr_providers_from_container() {
local dirs=(
/app/bazarr/bin/custom_libs/subliminal_patch/providers
@ -533,8 +515,8 @@ _list_bazarr_providers_from_container() {
return 1
}
# --- Bazarr subtitle provider selection (live from container, same idea as Prowlarr) ---
configure_subtitle_providers() {
local host="${API_HOST:-127.0.0.1}"
SELECTED_SUBTITLE_PROVIDERS=()
FZF_SELECT_STATUS="cancelled"
if [ "${ASSEMBLRR_NONINTERACTIVE:-0}" = "1" ]; then
@ -567,7 +549,7 @@ configure_subtitle_providers() {
local prompt header preselect_names=""
if ui_is_edit; then
prompt="Bazarr providers> "
header="Enter/TAB=toggle Ctrl-O=save Esc=cancel"
header="TAB=toggle Enter=save Esc=cancel"
if type _bazarr_config_file >/dev/null 2>&1 && type _bazarr_extract_apikey >/dev/null 2>&1; then
local bcfg bkey
bcfg=$(_bazarr_config_file 2>/dev/null || true)
@ -576,13 +558,14 @@ configure_subtitle_providers() {
fi
if [ -n "${bkey:-}" ]; then
preselect_names=$(curl -s --connect-timeout 5 \
"http://${API_HOST:-127.0.0.1}:${BAZARR_PORT:-6767}/api/system/settings?apikey=${bkey}" \
-H "X-API-KEY: ${bkey}" \
"http://${host}:${BAZARR_PORT:-6767}/api/system/settings" \
2>/dev/null | jq -r '.general.enabled_providers[]? // empty' 2>/dev/null || true)
fi
fi
else
prompt="Bazarr providers (optional)> "
header="Enter/TAB=toggle Ctrl-O=confirm Esc=skip"
header="TAB=toggle Enter=confirm Esc=skip"
fi
fzf_multi_select "$formatted" \
"$prompt" \

687
lib/jellyfin.sh Normal file → Executable file
View file

@ -1,48 +1,57 @@
#!/bin/bash
# assemblrr Jellyfin configuration — sourced by config.sh
# Provides: configure_jellyfin, configure_jellyfin_xml_fallback,
# configure_jellyfin_libraries, configure_jellyfin_notifications
# Requires: lib/core.sh (logging), lib/api.sh (api_get/post helpers),
# config.sh (_cfg_log_info, log_step, log_step_fail, AUTH_USERNAME, etc.)
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Jellyfin 12+ configuration — sourced by config.sh / config_edit.sh
# Uses standard `Authorization: MediaBrowser` headers (Jellyfin 12 removed legacy X-Emby-* headers).
# Requires: lib/core.sh, lib/api.sh, lib/languages.sh
set -euo pipefail
if [ -n "${_ASSEMBLRR_JELLYFIN_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_JELLYFIN_SOURCED=1
# --- Jellyfin configuration ---
_jellyfin_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/languages.sh
[ -f "$_jellyfin_dir/languages.sh" ] && source "$_jellyfin_dir/languages.sh"
_jf_auth_header() {
local token="${1:-}"
if [ -n "$token" ]; then
printf 'Authorization: MediaBrowser Client="assemblrr", Device="assemblrr", DeviceId="assemblrr-cli", Version="1.0", Token="%s"' "$token"
else
printf 'Authorization: MediaBrowser Client="assemblrr", Device="setup-script", DeviceId="assemblrr-setup", Version="1.0"'
fi
}
_jf_is_up() {
http_request GET "http://${API_HOST}:8096/System/Info/Public"
}
_jf_first_user_ready() {
http_request GET "http://${API_HOST}:8096/Startup/FirstUser" || return 1
[ -n "$(printf '%s' "$HTTP_BODY" | jq -r '.Name // ""' 2>/dev/null || echo "")" ]
}
_jf_health_up() {
http_request GET "http://${API_HOST}:8096/health"
}
configure_jellyfin() {
local jellyfin_port=8096
local max_wait=120
local wait_time=0
# Step 1: Wait for Jellyfin to be responsive
echo >&2
while [ $wait_time -lt $max_wait ]; do
local http_code
http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 \
"http://${API_HOST}:${jellyfin_port}/System/Info/Public" 2>/dev/null || echo "000")
if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 300 ]; then
break
fi
wait_inline "Waiting for Jellyfin to start" "$wait_time"
sleep 3
wait_time=$((wait_time + 3))
done
echo >&2
if [ $wait_time -ge $max_wait ]; then
if ! wait_until "Waiting for Jellyfin to start" "$max_wait" 3 _jf_is_up; then
log_step_fail "Jellyfin: not responsive after ${max_wait}s"
return 1
fi
echo >&2
# Step 2: Check if startup wizard is still pending
local public_info
public_info=$(curl -sf --connect-timeout 5 \
"http://${API_HOST}:${jellyfin_port}/System/Info/Public" 2>/dev/null || echo "")
local public_info wizard_complete=""
http_request GET "http://${API_HOST}:${jellyfin_port}/System/Info/Public" || true
public_info="$HTTP_BODY"
if [ -n "$public_info" ]; then
local wizard_complete
wizard_complete=$(echo "$public_info" | jq -r '.StartupWizardCompleted // ""' 2>/dev/null || echo "")
wizard_complete=$(printf '%s' "$public_info" | jq -r '.StartupWizardCompleted // ""' 2>/dev/null || echo "")
if [ "$wizard_complete" = "True" ] || [ "$wizard_complete" = "true" ]; then
log_step "Jellyfin: startup wizard already completed"
echo "Configuring Jellyfin libraries" >&2
@ -53,93 +62,49 @@ configure_jellyfin() {
fi
fi
# Step 3: Wait for the default startup user to be initialized
# Jellyfin creates a placeholder user on first boot; /Startup/User POST
# will return 500 if we hit it before the default user exists in the DB
_cfg_log_info "Jellyfin: attempting startup wizard bypass via API..."
echo >&2
local first_user_wait=0
while [ $first_user_wait -lt 60 ]; do
local first_user_resp
first_user_resp=$(curl -sf --connect-timeout 3 \
"http://${API_HOST}:${jellyfin_port}/Startup/FirstUser" 2>/dev/null || echo "")
if [ -n "$first_user_resp" ]; then
local first_user_name
first_user_name=$(echo "$first_user_resp" | jq -r '.Name // ""' 2>/dev/null || echo "")
if [ -n "$first_user_name" ]; then
break
fi
fi
wait_inline "Waiting for Jellyfin startup user to initialize" "$first_user_wait"
sleep 3
first_user_wait=$((first_user_wait + 3))
done
echo >&2
if [ $first_user_wait -ge 60 ]; then
if ! wait_until "Waiting for Jellyfin startup user to initialize" 60 3 _jf_first_user_ready; then
log_step_fail "Jellyfin: startup user not initialized after 60s"
configure_jellyfin_xml_fallback
return $?
fi
echo >&2
# Step 4: Set startup configuration (locale)
local locale_code
locale_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X POST \
if http_request POST "http://${API_HOST}:${jellyfin_port}/Startup/Configuration" \
-H "Content-Type: application/json" \
-d '{"UICulture":"en-US","MetadataCountryCode":"US","PreferredMetadataLanguage":"en"}' \
"http://${API_HOST}:${jellyfin_port}/Startup/Configuration" 2>/dev/null || echo "000")
if [ "$locale_code" -ge 200 ] && [ "$locale_code" -lt 300 ]; then
-d '{"UICulture":"en-US","MetadataCountryCode":"US","PreferredMetadataLanguage":"en"}'; then
log_step "Jellyfin: set startup locale (en-US)"
else
log_step_fail "Jellyfin: failed to set startup locale (HTTP $locale_code)"
log_step_fail "Jellyfin: failed to set startup locale (HTTP ${HTTP_STATUS})"
fi
# Step 5: Set admin user credentials via Startup API
local escaped_username escaped_password
escaped_username=$(printf '%s' "$AUTH_USERNAME" | jq -Rs . 2>/dev/null)
escaped_password=$(printf '%s' "$AUTH_PASSWORD" | jq -Rs . 2>/dev/null)
# Fallback if jq fails
escaped_username=${escaped_username:-"\"$AUTH_USERNAME\""}
escaped_password=${escaped_password:-"\"$AUTH_PASSWORD\""}
local user_payload="{\"Name\":${escaped_username},\"Password\":${escaped_password},\"EnableAutoLogin\":false}"
local user_code
user_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X POST \
local user_payload
user_payload=$(jq -nc --arg n "$AUTH_USERNAME" --arg p "$AUTH_PASSWORD" \
'{Name:$n,Password:$p,EnableAutoLogin:false}')
if http_request POST "http://${API_HOST}:${jellyfin_port}/Startup/User" \
-H "Content-Type: application/json" \
-d "$user_payload" \
"http://${API_HOST}:${jellyfin_port}/Startup/User" 2>/dev/null || echo "000")
if [ "$user_code" -ge 200 ] && [ "$user_code" -lt 300 ]; then
-d "$user_payload"; then
log_step "Jellyfin: set admin user credentials ($AUTH_USERNAME)"
else
log_step_fail "Jellyfin: failed to set admin user via API (HTTP $user_code)"
log_step_fail "Jellyfin: failed to set admin user via API (HTTP ${HTTP_STATUS})"
configure_jellyfin_xml_fallback
return $?
fi
# Step 6: Complete the startup wizard
local complete_code
complete_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X POST \
-H "Content-Type: application/json" \
"http://${API_HOST}:${jellyfin_port}/Startup/Complete" 2>/dev/null || echo "000")
if [ "$complete_code" -ge 200 ] && [ "$complete_code" -lt 300 ]; then
if http_request POST "http://${API_HOST}:${jellyfin_port}/Startup/Complete" \
-H "Content-Type: application/json"; then
log_step "Jellyfin: startup wizard completed via API"
else
log_step_fail "Jellyfin: failed to complete startup wizard (HTTP $complete_code)"
log_step_fail "Jellyfin: failed to complete startup wizard (HTTP ${HTTP_STATUS})"
configure_jellyfin_xml_fallback
return $?
fi
# Step 7: Verify wizard is complete
sleep 3
local verify_info
verify_info=$(curl -sf --connect-timeout 5 \
"http://${API_HOST}:${jellyfin_port}/System/Info/Public" 2>/dev/null || echo "")
http_request GET "http://${API_HOST}:${jellyfin_port}/System/Info/Public" || true
local wizard_status
wizard_status=$(echo "$verify_info" | jq -r '.StartupWizardCompleted // ""' 2>/dev/null || echo "")
wizard_status=$(printf '%s' "$HTTP_BODY" | jq -r '.StartupWizardCompleted // ""' 2>/dev/null || echo "")
if [ "$wizard_status" = "True" ] || [ "$wizard_status" = "true" ]; then
log_step "Jellyfin: startup wizard bypass verified"
@ -149,7 +114,6 @@ configure_jellyfin() {
return $?
fi
# Step 8: Add media libraries
echo "Configuring Jellyfin libraries" >&2
local lib_rc=0
configure_jellyfin_libraries || lib_rc=$?
@ -159,15 +123,11 @@ configure_jellyfin() {
configure_jellyfin_xml_fallback() {
local system_xml="$INSTALL_DIR/config/jellyfin/system.xml"
local max_wait=60
local wait_time=0
local max_wait=60 wait_time=0
# Wait for system.xml to appear
echo >&2
while [ $wait_time -lt $max_wait ]; do
if [ -f "$system_xml" ]; then
break
fi
[ -f "$system_xml" ] && break
wait_inline "Waiting for Jellyfin system.xml" "$wait_time"
sleep 3
wait_time=$((wait_time + 3))
@ -179,7 +139,6 @@ configure_jellyfin_xml_fallback() {
return 1
fi
# Mark wizard as complete
if grep -q '<IsStartupWizardCompleted>false</IsStartupWizardCompleted>' "$system_xml" 2>/dev/null; then
sed -i 's/<IsStartupWizardCompleted>false<\/IsStartupWizardCompleted>/<IsStartupWizardCompleted>true<\/IsStartupWizardCompleted>/g' "$system_xml"
log_step "Jellyfin: marked startup wizard as complete in system.xml"
@ -187,207 +146,372 @@ configure_jellyfin_xml_fallback() {
sed -i 's/<IsStartupWizardCompleted>[^<]*<\/IsStartupWizardCompleted>/<IsStartupWizardCompleted>true<\/IsStartupWizardCompleted>/g' "$system_xml"
log_step "Jellyfin: updated IsStartupWizardCompleted in system.xml"
else
# Tag doesn't exist — add it before the closing tag
sed -i 's/<\/ServerConfiguration>/ <IsStartupWizardCompleted>true<\/IsStartupWizardCompleted>\n<\/ServerConfiguration>/' "$system_xml"
log_step "Jellyfin: added IsStartupWizardCompleted to system.xml"
fi
# Restart Jellyfin to apply changes
docker restart jellyfin 2>/dev/null || true
run_docker restart jellyfin 2>/dev/null || true
log_step "Jellyfin: restarted to apply system.xml changes"
# Wait for Jellyfin to come back online
echo >&2
local back_wait=0
while [ $back_wait -lt 60 ]; do
if curl -sf --connect-timeout 3 "http://${API_HOST}:8096/health" >/dev/null 2>&1; then
break
fi
wait_inline "Waiting for Jellyfin to come back online" "$back_wait"
sleep 3
back_wait=$((back_wait + 3))
done
wait_until "Waiting for Jellyfin to come back online" 60 3 _jf_health_up || true
echo >&2
}
configure_jellyfin_libraries() {
local jellyfin_port=8096
local auth_payload auth_response access_token user_id
# Authenticate to get access token
local auth_response
local auth_payload
auth_payload=$(jq -nc --arg u "$AUTH_USERNAME" --arg p "$AUTH_PASSWORD" '{Username:$u,Pw:$p}')
auth_response=$(curl -sf --connect-timeout 10 -X POST \
if ! http_request POST "http://${API_HOST}:${jellyfin_port}/Users/AuthenticateByName" \
-H "Content-Type: application/json" \
-H 'X-Emby-Authorization: MediaBrowser Client="assemblrr", Version="1.0", Device="setup-script", DeviceId="assemblrr-setup"' \
-d "$auth_payload" \
"http://${API_HOST}:${jellyfin_port}/Users/AuthenticateByName" 2>/dev/null || echo "")
if [ -z "$auth_response" ]; then
log_step_fail "Jellyfin: failed to authenticate for library setup"
-H "$(_jf_auth_header)" \
-d "$auth_payload"; then
log_step_fail "Jellyfin: failed to authenticate for library setup (HTTP ${HTTP_STATUS})"
return 1
fi
auth_response="$HTTP_BODY"
local access_token
access_token=$(echo "$auth_response" | jq -r '.AccessToken // ""' 2>/dev/null || echo "")
access_token=$(printf '%s' "$auth_response" | jq -r '.AccessToken // ""' 2>/dev/null || echo "")
if [ -z "$access_token" ]; then
log_step_fail "Jellyfin: failed to get access token"
return 1
fi
user_id=$(printf '%s' "$auth_response" | jq -r '.User.Id // ""' 2>/dev/null || echo "")
local user_id
user_id=$(echo "$auth_response" | jq -r '.User.Id // ""' 2>/dev/null || echo "")
local auth_hdr
auth_hdr=$(_jf_auth_header "$access_token")
# Define media libraries to add
local -a lib_names=("Movies" "TV Shows")
local -a lib_types=("movies" "tvshows")
local -a lib_paths=("/data/media/movies" "/data/media/tv")
# Only add Music if the host media/music folder exists
if [ -n "${MEDIA_DIRECTORY:-}" ] && [ -d "${MEDIA_DIRECTORY}/media/music" ]; then
lib_names+=("Music")
lib_types+=("music")
lib_paths+=("/data/media/music")
fi
# Fetch existing libraries to avoid duplicates
local existing_libs
existing_libs=$(curl -sf --connect-timeout 5 \
-H "X-Emby-Token: ${access_token}" \
"http://${API_HOST}:${jellyfin_port}/Library/VirtualFolders" 2>/dev/null || echo "[]")
# Remove duplicate libraries (same path, different name — e.g. "Movies2")
local dupe_ids
dupe_ids=$(echo "$existing_libs" | jq -r '.[] | . as $lib | .Locations[]? as $loc | {"/data/media/movies": "Movies", "/data/media/tv": "TV Shows", "/data/media/music": "Music"}[$loc] as $expected | select($expected and $lib.Name != $expected) | "\(.ItemId)|\(.Name)"' 2>/dev/null || echo "")
if [ -n "$dupe_ids" ]; then
while IFS='|' read -r dupe_id dupe_name; do
curl -sf -o /dev/null -w "" -X DELETE \
-H "X-Emby-Token: ${access_token}" \
"http://${API_HOST}:${jellyfin_port}/Items/${dupe_id}" 2>/dev/null
log_step "Jellyfin: removed duplicate library '${dupe_name}'"
done <<< "$dupe_ids"
# Re-fetch after deletions
existing_libs=$(curl -sf --connect-timeout 5 \
-H "X-Emby-Token: ${access_token}" \
"http://${API_HOST}:${jellyfin_port}/Library/VirtualFolders" 2>/dev/null || echo "[]")
local existing_libs="[]"
if http_request GET "http://${API_HOST}:${jellyfin_port}/Library/VirtualFolders" -H "$auth_hdr"; then
existing_libs="$HTTP_BODY"
fi
local critical_errors=0
local dupe_ids
dupe_ids=$(printf '%s' "$existing_libs" | jq -r '.[] | . as $lib | .Locations[]? as $loc | {"/data/media/movies": "Movies", "/data/media/tv": "TV Shows", "/data/media/music": "Music"}[$loc] as $expected | select($expected and $lib.Name != $expected) | "\(.ItemId)|\(.Name)"' 2>/dev/null || echo "")
if [ -n "$dupe_ids" ]; then
local dupe_id dupe_name
while IFS='|' read -r dupe_id dupe_name; do
[ -n "$dupe_id" ] || continue
http_request DELETE "http://${API_HOST}:${jellyfin_port}/Items/${dupe_id}" -H "$auth_hdr" || true
log_step "Jellyfin: removed duplicate library '${dupe_name}'"
done <<< "$dupe_ids"
if http_request GET "http://${API_HOST}:${jellyfin_port}/Library/VirtualFolders" -H "$auth_hdr"; then
existing_libs="$HTTP_BODY"
fi
fi
local critical_errors=0 i
for i in "${!lib_names[@]}"; do
local lib_name="${lib_names[$i]}"
local lib_type="${lib_types[$i]}"
local lib_path="${lib_paths[$i]}"
# Check if a library with this name and path already exists
local lib_exists
lib_exists=$(echo "$existing_libs" | jq --arg ln "$lib_name" --arg lp "$lib_path" -r 'if [.[] | select(.Name == $ln and (.Locations // [] | index($lp)))][0] then "yes" else "no" end' 2>/dev/null || echo "no")
lib_exists=$(printf '%s' "$existing_libs" | jq --arg ln "$lib_name" --arg lp "$lib_path" -r 'if [.[] | select(.Name == $ln and (.Locations // [] | index($lp)))][0] then "yes" else "no" end' 2>/dev/null || echo "no")
if [ "$lib_exists" = "yes" ]; then
log_step "Jellyfin: ${lib_name} library already exists (${lib_path})"
continue
fi
# URL-encode the name and path for query params
local enc_name enc_path
enc_name=$(jq -rn --arg n "$lib_name" '$n | @uri' 2>/dev/null || echo "${lib_name}")
enc_name=$(urlencode "$lib_name")
enc_path=$(jq -rn --arg p "$lib_path" '($p | @uri) | gsub("%2F"; "/")' 2>/dev/null || echo "${lib_path}")
local add_code
add_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X POST \
-H "Content-Type: application/json" \
-H "X-Emby-Token: ${access_token}" \
if http_request POST \
"http://${API_HOST}:${jellyfin_port}/Library/VirtualFolders?name=${enc_name}&collectionType=${lib_type}&paths=${enc_path}&refreshProgress=0" \
2>/dev/null || echo "000")
if [ "$add_code" -ge 200 ] && [ "$add_code" -lt 300 ]; then
-H "Content-Type: application/json" \
-H "$auth_hdr"; then
log_step "Jellyfin: added ${lib_name} library (${lib_path})"
else
log_step_fail "Jellyfin: failed to add ${lib_name} library (HTTP $add_code)"
log_step_fail "Jellyfin: failed to add ${lib_name} library (HTTP ${HTTP_STATUS})"
if [ "$lib_type" = "movies" ] || [ "$lib_type" = "tvshows" ]; then
critical_errors=$((critical_errors + 1))
fi
fi
done
# Set subtitle preference: always show subtitles in user's preferred language
# Jellyfin's SubtitleLanguagePreference uses ISO 639-2/T three-letter codes
# (e.g. "eng", "fra", "deu") — NOT locale codes like "en-US" and NOT two-letter
# codes like "en". The UI dropdown matches these codes to display language names.
# We must also GET the full user config first and POST it back modified,
# otherwise Jellyfin wipes all other user settings.
# Set subtitle preference: always show subtitles in preferred ISO 639-2/T language.
if [ -n "$user_id" ]; then
local sub_lang="${SUBTITLE_LANGUAGE:-en}"
sub_lang="${sub_lang%%,*}"
sub_lang=${sub_lang// /}
# Convert ISO 639-1 (two-letter) to ISO 639-2/T (three-letter) code
# Jellyfin uses ISO 639-2/T (e.g., "eng" not "en"), so we must convert.
# If Jellyfin starts accepting 639-1 directly, this mapping can be removed.
local jf_lang
jf_lang=$(jq -rn --arg sl "$sub_lang" '($sl | ascii_downcase) | if length == 3 then . else ({"aa":"aar","ab":"abk","af":"afr","ak":"aka","am":"amh","an":"arg","ar":"ara","as":"asm","av":"ava","ay":"aym","az":"aze","ba":"bak","be":"bel","bg":"bul","bh":"bih","bi":"bis","bm":"bam","bn":"ben","bo":"bod","br":"bre","bs":"bos","ca":"cat","ce":"che","ch":"cha","co":"cos","cr":"cre","cs":"ces","cu":"chu","cv":"chv","cy":"cym","da":"dan","de":"deu","dv":"div","dz":"dzo","ee":"ewe","el":"ell","en":"eng","eo":"epo","es":"spa","et":"est","eu":"eus","fa":"fas","ff":"ful","fi":"fin","fj":"fij","fo":"fao","fr":"fra","fy":"fry","ga":"gle","gd":"gla","gl":"glg","gn":"grn","gu":"guj","gv":"glv","ha":"hau","he":"heb","hi":"hin","ho":"hmo","hr":"hrv","ht":"hat","hu":"hun","hy":"hye","hz":"her","ia":"ina","id":"ind","ie":"ile","ig":"ibo","ii":"iii","ik":"ipk","io":"ido","is":"isl","it":"ita","iu":"iku","ja":"jpn","jv":"jav","ka":"kat","kg":"kon","ki":"kik","kj":"kua","kk":"kaz","kl":"kal","km":"khm","kn":"kan","ko":"kor","kr":"kau","ks":"kas","ku":"kur","kv":"kom","kw":"cor","ky":"kir","la":"lat","lb":"ltz","lg":"lug","li":"lim","ln":"lin","lo":"lao","lt":"lit","lu":"lub","lv":"lav","mg":"mlg","mh":"mah","mi":"mri","mk":"mkd","ml":"mal","mn":"mon","mr":"mar","ms":"msa","mt":"mlt","my":"mya","na":"nau","nb":"nob","nd":"nde","ne":"nep","ng":"ndo","nl":"nld","nn":"nno","no":"nor","nr":"nbl","nv":"nav","ny":"nya","oc":"oci","oj":"oji","om":"orm","or":"ori","os":"oss","pa":"pan","pi":"pli","pl":"pol","ps":"pus","pt":"por","qu":"que","rm":"roh","rn":"run","ro":"ron","ru":"rus","rw":"kin","sa":"san","sc":"srd","sd":"snd","se":"sme","sg":"sag","si":"sin","sk":"slk","sl":"slv","sm":"smo","sn":"sna","so":"som","sq":"sqi","sr":"srp","ss":"ssw","st":"sot","su":"sun","sv":"swe","sw":"swa","ta":"tam","te":"tel","tg":"tgk","th":"tha","ti":"tir","tk":"tuk","tl":"tgl","tn":"tsn","to":"ton","tr":"tur","ts":"tso","tt":"tat","tw":"twi","ty":"tah","ug":"uig","uk":"ukr","ur":"urd","uz":"uzb","ve":"ven","vi":"vie","vo":"vol","wa":"wln","wo":"wol","xh":"xho","yi":"yid","yo":"yor","za":"zha","zh":"zho","zu":"zul"}[.] // .) end' 2>/dev/null || echo "$sub_lang")
jf_lang=$(iso639_to_code3 "$sub_lang")
# GET current config, patch subtitle fields, POST back
# Note: GET /Users/{id}/Configuration returns 405; must GET /Users/{id} instead
# and extract the Configuration object, then POST it to /Users/{id}/Configuration
local user_obj
user_obj=$(curl -s -H "X-Emby-Token: ${access_token}" \
"http://${API_HOST}:${jellyfin_port}/Users/${user_id}" 2>/dev/null)
local patched_cfg
patched_cfg=$(echo "$user_obj" | jq --arg lang "$jf_lang" '.Configuration.SubtitleMode = "Always" | .Configuration.SubtitleLanguagePreference = $lang | .Configuration' 2>/dev/null)
local sub_pref_code
sub_pref_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X POST \
-H "Content-Type: application/json" \
-H "X-Emby-Token: ${access_token}" \
-d "$patched_cfg" \
"http://${API_HOST}:${jellyfin_port}/Users/${user_id}/Configuration" \
2>/dev/null || echo "000")
if [ "$sub_pref_code" -ge 200 ] && [ "$sub_pref_code" -lt 300 ]; then
log_step "Jellyfin: set subtitle preference (Always, ${jf_lang})"
else
log_step_fail "Jellyfin: failed to set subtitle preference (HTTP $sub_pref_code)"
if http_request GET "http://${API_HOST}:${jellyfin_port}/Users/${user_id}" -H "$auth_hdr" && [ -n "$HTTP_BODY" ]; then
local patched_cfg
patched_cfg=$(printf '%s' "$HTTP_BODY" | jq --arg lang "$jf_lang" '.Configuration.SubtitleMode = "Always" | .Configuration.SubtitleLanguagePreference = $lang | .Configuration' 2>/dev/null || echo "")
if [ -n "$patched_cfg" ] && [ "$patched_cfg" != "null" ]; then
if http_request POST "http://${API_HOST}:${jellyfin_port}/Users/${user_id}/Configuration" \
-H "Content-Type: application/json" \
-H "$auth_hdr" \
-d "$patched_cfg"; then
log_step "Jellyfin: set subtitle preference (Always, ${jf_lang})"
else
log_step_fail "Jellyfin: failed to set subtitle preference (HTTP ${HTTP_STATUS})"
fi
fi
fi
fi
# Create an API key for Radarr/Sonarr notification connections
# POST /Auth/Keys?app=assemblrr returns 204 with no body, so we must
# create it first, then GET /Auth/Keys to retrieve the actual key value.
mkdir -p "$INSTALL_DIR/secrets"
# Reuse existing "assemblrr" API key if present; otherwise create one.
local jf_api_key=""
if http_request GET "http://${API_HOST}:${jellyfin_port}/Auth/Keys" -H "$auth_hdr"; then
jf_api_key=$(printf '%s' "$HTTP_BODY" | jq -r '.Items[]? | select(.AppName == "assemblrr") | .AccessToken // ""' 2>/dev/null | head -1 || echo "")
fi
local key_create_code
key_create_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X POST \
-H "X-Emby-Token: ${access_token}" \
"http://${API_HOST}:${jellyfin_port}/Auth/Keys?app=assemblrr" 2>/dev/null || echo "000")
if [ "$key_create_code" = "204" ] || [ "$key_create_code" = "200" ]; then
local keys_response
keys_response=$(curl -s --connect-timeout 5 \
-H "X-Emby-Token: ${access_token}" \
"http://${API_HOST}:${jellyfin_port}/Auth/Keys" 2>/dev/null || echo "")
local jf_api_key
jf_api_key=$(echo "$keys_response" | jq -r '.Items[] | select(.AppName == "assemblrr") | .AccessToken // ""' 2>/dev/null | head -1 || echo "")
if [ -n "$jf_api_key" ]; then
echo -n "$jf_api_key" > "$INSTALL_DIR/secrets/jellyfin_api_key.txt"
chmod 600 "$INSTALL_DIR/secrets/jellyfin_api_key.txt"
log_step "Jellyfin: created API key for Radarr/Sonarr connections"
if [ -z "$jf_api_key" ]; then
if http_request POST "http://${API_HOST}:${jellyfin_port}/Auth/Keys?app=assemblrr" -H "$auth_hdr"; then
if http_request GET "http://${API_HOST}:${jellyfin_port}/Auth/Keys" -H "$auth_hdr"; then
jf_api_key=$(printf '%s' "$HTTP_BODY" | jq -r '.Items[]? | select(.AppName == "assemblrr") | .AccessToken // ""' 2>/dev/null | head -1 || echo "")
fi
else
log_step_fail "Jellyfin: API key created but failed to retrieve value"
log_step_fail "Jellyfin: failed to create API key (HTTP ${HTTP_STATUS})"
fi
fi
if [ -n "$jf_api_key" ]; then
write_secret_file "$INSTALL_DIR/secrets/jellyfin_api_key.txt" "$jf_api_key"
log_step "Jellyfin: API key ready for Radarr/Sonarr connections"
else
log_step_fail "Jellyfin: failed to create API key (HTTP $key_create_code)"
log_step_fail "Jellyfin: API key missing after creation"
fi
if [ "${GPU_TRANSCODING:-none}" != "none" ]; then
configure_jellyfin_transcoding "$access_token" "$jellyfin_port" || true
fi
[ "$critical_errors" -eq 0 ]
}
# Change an existing Jellyfin/Emby user's password (and name if it changed).
# Usage: jellyfin_change_credentials <old_user> <old_pass> <new_user> <new_pass> [port] [label]
# Parse `vainfo --display drm` output into hardware decode/encode capabilities JSON.
# Outputs compact JSON {"decode":[...],"hevc10":bool,"vp9_10":bool,"hevc_enc":bool,"av1_enc":bool}; returns 1 if none found.
jellyfin_parse_vainfo_caps() {
local vainfo_text="${1:-}"
[ -n "$vainfo_text" ] || return 1
local parsed
parsed=$(printf '%s\n' "$vainfo_text" | awk -F: '
function trim(s) { gsub(/^[[:space:]]+|[[:space:]]+$/, "", s); return s }
NF >= 2 {
p = trim($1); e = trim($2)
if (e == "VAEntrypointVLD") {
if (p ~ /^VAProfileH264/) dec["h264"] = 1
else if (p == "VAProfileHEVCMain") dec["hevc"] = 1
else if (p ~ /^VAProfileMPEG2/) dec["mpeg2video"] = 1
else if (p ~ /^VAProfileVC1/) dec["vc1"] = 1
else if (p ~ /^VAProfileVP8/) dec["vp8"] = 1
else if (p == "VAProfileVP9Profile0") dec["vp9"] = 1
else if (p == "VAProfileAV1Profile0") dec["av1"] = 1
else if (p == "VAProfileHEVCMain10") { hevc10 = 1; dec["hevc"] = 1 }
else if (p == "VAProfileVP9Profile2") { vp9_10 = 1; dec["vp9"] = 1 }
} else if (e ~ /^VAEntrypointEnc/) {
if (p == "VAProfileHEVCMain" || p == "VAProfileHEVCMain10") hevc_enc = 1
else if (p == "VAProfileAV1Profile0") av1_enc = 1
}
}
END {
order[1]="h264"; order[2]="hevc"; order[3]="mpeg2video"; order[4]="vc1"; order[5]="vp8"; order[6]="vp9"; order[7]="av1"
out = ""
count = 0
for (i = 1; i <= 7; i++) {
c = order[i]
if (dec[c]) {
if (out != "") out = out ","
out = out "\"" c "\""
count++
}
}
if (count == 0) exit 1
printf "{\"decode\":[%s],\"hevc10\":%s,\"vp9_10\":%s,\"hevc_enc\":%s,\"av1_enc\":%s}\n",
out, (hevc10 ? "true" : "false"), (vp9_10 ? "true" : "false"),
(hevc_enc ? "true" : "false"), (av1_enc ? "true" : "false")
}
' 2>/dev/null || echo "")
[ -n "$parsed" ] || return 1
printf '%s\n' "$parsed"
}
# Build an updated /System/Configuration/encoding JSON payload for hardware transcoding.
# Mode: amd | vaapi | intel | qsv | nvidia | nvenc | none; optional caps_json overrides codecs.
jellyfin_build_encoding_patch_json() {
local current_json="${1:-"{}"}"
local gpu_mode="${2:-none}"
local render_dev="${3:-/dev/dri/renderD128}"
local caps_json="${4:-}"
gpu_mode="${gpu_mode,,}"
[ -n "$current_json" ] || current_json="{}"
local use_caps=0
if [ -n "$caps_json" ] && printf '%s' "$caps_json" | jq -e '(.decode // []) | length > 0' >/dev/null 2>&1; then
use_caps=1
fi
case "$gpu_mode" in
amd|vaapi)
if [ "$use_caps" -eq 1 ]; then
printf '%s' "$current_json" | jq -c --arg dev "$render_dev" --argjson caps "$caps_json" '
.HardwareAccelerationType = "vaapi" |
.VaapiDevice = $dev |
.EnableHardwareEncoding = true |
.HardwareDecodingCodecs = $caps.decode |
.EnableDecodingColorDepth10Hevc = $caps.hevc10 |
.EnableDecodingColorDepth10Vp9 = $caps.vp9_10 |
.AllowHevcEncoding = $caps.hevc_enc |
.AllowAv1Encoding = $caps.av1_enc
'
else
printf '%s' "$current_json" | jq -c --arg dev "$render_dev" '
.HardwareAccelerationType = "vaapi" |
.VaapiDevice = $dev |
.EnableHardwareEncoding = true |
.HardwareDecodingCodecs = ["h264", "hevc", "vp9", "av1"] |
.EnableDecodingColorDepth10Hevc = true |
.EnableDecodingColorDepth10Vp9 = true |
.AllowHevcEncoding = true |
.AllowAv1Encoding = false
'
fi
;;
intel|qsv)
if [ "$use_caps" -eq 1 ]; then
printf '%s' "$current_json" | jq -c --arg dev "$render_dev" --argjson caps "$caps_json" '
.HardwareAccelerationType = "qsv" |
.QsvDevice = $dev |
.VaapiDevice = $dev |
.EnableHardwareEncoding = true |
.HardwareDecodingCodecs = $caps.decode |
.EnableDecodingColorDepth10Hevc = $caps.hevc10 |
.EnableDecodingColorDepth10Vp9 = $caps.vp9_10 |
.AllowHevcEncoding = $caps.hevc_enc |
.AllowAv1Encoding = $caps.av1_enc
'
else
printf '%s' "$current_json" | jq -c --arg dev "$render_dev" '
.HardwareAccelerationType = "qsv" |
.QsvDevice = $dev |
.VaapiDevice = $dev |
.EnableHardwareEncoding = true |
.HardwareDecodingCodecs = ["h264", "hevc", "vp9", "av1"] |
.EnableDecodingColorDepth10Hevc = true |
.EnableDecodingColorDepth10Vp9 = true |
.AllowHevcEncoding = true |
.AllowAv1Encoding = false
'
fi
;;
nvidia|nvenc)
printf '%s' "$current_json" | jq -c '
.HardwareAccelerationType = "nvenc" |
.EnableHardwareEncoding = true |
.HardwareDecodingCodecs = ["h264", "hevc", "vp9", "av1"] |
.EnableDecodingColorDepth10Hevc = true |
.EnableDecodingColorDepth10Vp9 = true |
.AllowHevcEncoding = true
'
;;
*)
printf '%s' "$current_json" | jq -c '
.HardwareAccelerationType = "none" |
.EnableHardwareEncoding = false
'
;;
esac
}
# Configure Jellyfin hardware transcoding via /System/Configuration/encoding.
configure_jellyfin_transcoding() {
local token="${1:-}"
local jellyfin_port="${2:-8096}"
local gpu_mode="${GPU_TRANSCODING:-none}"
gpu_mode="${gpu_mode,,}"
if [ -z "$token" ] && [ -s "${INSTALL_DIR:-}/secrets/jellyfin_api_key.txt" ]; then
token=$(cat "$INSTALL_DIR/secrets/jellyfin_api_key.txt" 2>/dev/null || echo "")
fi
if [ -z "$token" ]; then
log_step_fail "Jellyfin: missing API token for hardware transcoding configuration"
return 1
fi
local render_dev="/dev/dri/renderD128"
if [ ! -c "$render_dev" ]; then
local cand
for cand in /dev/dri/renderD*; do
if [ -c "$cand" ]; then
render_dev="$cand"
break
fi
done
fi
local caps_json="" vainfo_out=""
case "$gpu_mode" in
amd|vaapi|intel|qsv)
if command -v docker >/dev/null 2>&1 || declare -F run_docker >/dev/null 2>&1; then
vainfo_out=$(run_docker exec jellyfin /usr/lib/jellyfin-ffmpeg/vainfo --display drm --device "$render_dev" 2>/dev/null || true)
caps_json=$(jellyfin_parse_vainfo_caps "$vainfo_out" 2>/dev/null || true)
fi
;;
esac
local auth_hdr
auth_hdr=$(_jf_auth_header "$token")
if ! http_request GET "http://${API_HOST}:${jellyfin_port}/System/Configuration/encoding" -H "$auth_hdr" || [ -z "$HTTP_BODY" ]; then
log_step_fail "Jellyfin: failed to read encoding configuration (HTTP ${HTTP_STATUS})"
return 1
fi
local patched_cfg
patched_cfg=$(jellyfin_build_encoding_patch_json "$HTTP_BODY" "$gpu_mode" "$render_dev" "$caps_json" 2>/dev/null || echo "")
if [ -z "$patched_cfg" ] || [ "$patched_cfg" = "null" ]; then
log_step_fail "Jellyfin: failed to build encoding configuration payload"
return 1
fi
local caps_summary=""
if [ -n "$caps_json" ]; then
local dec_csv enc_csv=""
dec_csv=$(printf '%s' "$caps_json" | jq -r '.decode | join(",")' 2>/dev/null || echo "")
[ "$(printf '%s' "$caps_json" | jq -r '.hevc_enc' 2>/dev/null)" = "true" ] && enc_csv="hevc"
[ "$(printf '%s' "$caps_json" | jq -r '.av1_enc' 2>/dev/null)" = "true" ] && enc_csv="${enc_csv:+${enc_csv},}av1"
caps_summary="; decode: ${dec_csv:-default}"
[ -n "$enc_csv" ] && caps_summary+="; enc: ${enc_csv}"
fi
if http_request POST "http://${API_HOST}:${jellyfin_port}/System/Configuration/encoding" \
-H "Content-Type: application/json" \
-H "$auth_hdr" \
-d "$patched_cfg"; then
case "$gpu_mode" in
amd|vaapi) log_step "Jellyfin: hardware transcoding configured (AMD VAAPI via ${render_dev}${caps_summary})" ;;
intel|qsv) log_step "Jellyfin: hardware transcoding configured (Intel QSV via ${render_dev}${caps_summary})" ;;
nvidia|nvenc) log_step "Jellyfin: hardware transcoding configured (NVIDIA NVENC)" ;;
*) log_step "Jellyfin: hardware transcoding disabled (CPU software)" ;;
esac
return 0
fi
log_step_fail "Jellyfin: failed to apply hardware transcoding (HTTP ${HTTP_STATUS})"
return 1
}
jellyfin_change_credentials() {
local old_user="$1"
local old_pass="$2"
@ -395,17 +519,16 @@ jellyfin_change_credentials() {
local new_pass="$4"
local jellyfin_port="${5:-8096}"
local label="${6:-Jellyfin}"
local auth_header='X-Emby-Authorization: MediaBrowser Client="assemblrr", Version="1.0", Device="config-edit", DeviceId="assemblrr-auth"'
if [ -z "$new_user" ] || [ -z "$new_pass" ]; then
log_step_fail "${label}: new credentials missing"
return 1
fi
local public_info wizard_complete
public_info=$(curl -sf --connect-timeout 5 \
"http://${API_HOST}:${jellyfin_port}/System/Info/Public" 2>/dev/null || echo "")
wizard_complete=$(echo "$public_info" | jq -r '.StartupWizardCompleted // ""' 2>/dev/null || echo "")
local wizard_complete=""
if http_request GET "http://${API_HOST}:${jellyfin_port}/System/Info/Public"; then
wizard_complete=$(printf '%s' "$HTTP_BODY" | jq -r '.StartupWizardCompleted // ""' 2>/dev/null || echo "")
fi
if [ "$wizard_complete" != "True" ] && [ "$wizard_complete" != "true" ]; then
if [ "$label" = "Jellyfin" ] && type configure_jellyfin >/dev/null 2>&1; then
configure_jellyfin
@ -415,29 +538,23 @@ jellyfin_change_credentials() {
return 1
fi
local auth_payload auth_response
local auth_hdr_anon auth_payload auth_response=""
auth_hdr_anon=$(_jf_auth_header)
auth_payload=$(jq -nc --arg u "$old_user" --arg p "$old_pass" '{Username:$u,Pw:$p}')
auth_response=$(curl -sf --connect-timeout 10 -X POST \
-H "Content-Type: application/json" \
-H "$auth_header" \
-d "$auth_payload" \
"http://${API_HOST}:${jellyfin_port}/Users/AuthenticateByName" 2>/dev/null || echo "")
if [ -z "$auth_response" ]; then
if http_request POST "http://${API_HOST}:${jellyfin_port}/Users/AuthenticateByName" \
-H "Content-Type: application/json" -H "$auth_hdr_anon" -d "$auth_payload"; then
auth_response="$HTTP_BODY"
else
auth_payload=$(jq -nc --arg u "$new_user" --arg p "$new_pass" '{Username:$u,Pw:$p}')
auth_response=$(curl -sf --connect-timeout 10 -X POST \
-H "Content-Type: application/json" \
-H "$auth_header" \
-d "$auth_payload" \
"http://${API_HOST}:${jellyfin_port}/Users/AuthenticateByName" 2>/dev/null || echo "")
if [ -n "$auth_response" ]; then
if http_request POST "http://${API_HOST}:${jellyfin_port}/Users/AuthenticateByName" \
-H "Content-Type: application/json" -H "$auth_hdr_anon" -d "$auth_payload"; then
auth_response="$HTTP_BODY"
local already_name
already_name=$(echo "$auth_response" | jq -r '.User.Name // ""' 2>/dev/null || echo "")
already_name=$(printf '%s' "$auth_response" | jq -r '.User.Name // ""' 2>/dev/null || echo "")
if [ "$already_name" = "$new_user" ]; then
log_step "${label}: already using the new password"
return 0
fi
# New password already works — only the display name still needs updating.
old_pass="$new_pass"
else
log_step_fail "${label}: could not log in with the old password"
@ -446,48 +563,41 @@ jellyfin_change_credentials() {
fi
local access_token user_id
access_token=$(echo "$auth_response" | jq -r '.AccessToken // ""' 2>/dev/null || echo "")
user_id=$(echo "$auth_response" | jq -r '.User.Id // ""' 2>/dev/null || echo "")
access_token=$(printf '%s' "$auth_response" | jq -r '.AccessToken // ""' 2>/dev/null || echo "")
user_id=$(printf '%s' "$auth_response" | jq -r '.User.Id // ""' 2>/dev/null || echo "")
if [ -z "$access_token" ] || [ -z "$user_id" ]; then
log_step_fail "${label}: login response missing token"
return 1
fi
local auth_hdr
auth_hdr=$(_jf_auth_header "$access_token")
if [ "$old_pass" != "$new_pass" ]; then
local pw_payload pw_code
local pw_payload
pw_payload=$(jq -nc --arg cur "$old_pass" --arg new "$new_pass" '{CurrentPw:$cur,NewPw:$new}')
pw_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 8 -X POST \
-H "Content-Type: application/json" \
-H "X-Emby-Token: ${access_token}" \
-d "$pw_payload" \
"http://${API_HOST}:${jellyfin_port}/Users/${user_id}/Password" 2>/dev/null || echo "000")
if [ "$pw_code" -lt 200 ] || [ "$pw_code" -ge 300 ]; then
log_step_fail "${label}: failed to set password (HTTP $pw_code)"
if ! http_request POST "http://${API_HOST}:${jellyfin_port}/Users/${user_id}/Password" \
-H "Content-Type: application/json" -H "$auth_hdr" -d "$pw_payload"; then
log_step_fail "${label}: failed to set password (HTTP ${HTTP_STATUS})"
return 1
fi
fi
if [ "$old_user" != "$new_user" ]; then
local enc_name name_code
enc_name=$(jq -rn --arg n "$new_user" '$n | @uri' 2>/dev/null || echo "$new_user")
name_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 8 -X POST \
-H "X-Emby-Token: ${access_token}" \
"http://${API_HOST}:${jellyfin_port}/Users/${user_id}/Name?name=${enc_name}" \
2>/dev/null || echo "000")
if [ "$name_code" -lt 200 ] || [ "$name_code" -ge 300 ]; then
local user_obj patched
user_obj=$(curl -s --connect-timeout 8 \
-H "X-Emby-Token: ${access_token}" \
"http://${API_HOST}:${jellyfin_port}/Users/${user_id}" 2>/dev/null || echo "")
patched=$(echo "$user_obj" | jq --arg n "$new_user" '.Name = $n' 2>/dev/null || echo "")
name_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 8 -X POST \
-H "Content-Type: application/json" \
-H "X-Emby-Token: ${access_token}" \
-d "$patched" \
"http://${API_HOST}:${jellyfin_port}/Users/${user_id}" 2>/dev/null || echo "000")
local enc_name name_ok=0
enc_name=$(urlencode "$new_user")
if http_request POST "http://${API_HOST}:${jellyfin_port}/Users/${user_id}/Name?name=${enc_name}" -H "$auth_hdr"; then
name_ok=1
elif http_request GET "http://${API_HOST}:${jellyfin_port}/Users/${user_id}" -H "$auth_hdr" && [ -n "$HTTP_BODY" ]; then
local patched
patched=$(printf '%s' "$HTTP_BODY" | jq --arg n "$new_user" '.Name = $n' 2>/dev/null || echo "")
if [ -n "$patched" ] && http_request POST "http://${API_HOST}:${jellyfin_port}/Users/${user_id}" \
-H "Content-Type: application/json" -H "$auth_hdr" -d "$patched"; then
name_ok=1
fi
fi
if [ "$name_code" -lt 200 ] || [ "$name_code" -ge 300 ]; then
log_step_fail "${label}: password updated, username change failed (HTTP $name_code)"
if [ "$name_ok" -ne 1 ]; then
log_step_fail "${label}: password updated, username change failed (HTTP ${HTTP_STATUS})"
return 1
fi
fi
@ -496,8 +606,6 @@ jellyfin_change_credentials() {
return 0
}
# --- Jellyfin notification connections (Radarr/Sonarr → Jellyfin) ---
configure_jellyfin_notifications() {
local jf_api_key
jf_api_key=$(cat "$INSTALL_DIR/secrets/jellyfin_api_key.txt" 2>/dev/null || echo "")
@ -507,14 +615,6 @@ configure_jellyfin_notifications() {
return 1
fi
# NOTE: The MediaBrowser/Emby notification type calls /Library/Media/Updated which
# only refreshes EXISTING items in Jellyfin's DB — it cannot discover NEW files.
# CustomScript → jellyfin-refresh.sh POSTs /Library/Refresh (full scan).
# A second POST cancels the in-progress scan; Jellyfin 10.11 can then leave a
# new series with 0 children in the UI. Sonarr fires onImportComplete (once per
# release, not per file). Radarr has no onImportComplete, so onDownload is one movie.
# The script also skips if a scan is already running and heals empty series.
local errors=0
if ! add_jellyfin_refresh_notif "Radarr" "7878" "$RADARR_API_KEY"; then
errors=$((errors + 1))
@ -525,25 +625,19 @@ configure_jellyfin_notifications() {
[ "$errors" -eq 0 ]
}
# Add a CustomScript notification to an *arr app that triggers Jellyfin library refresh.
# Usage: add_jellyfin_refresh_notif <app_name> <port> <api_key>
add_jellyfin_refresh_notif() {
local app_name="$1"
local port="$2"
local apikey="$3"
if [ -z "$apikey" ]; then
return 0
fi
[ -z "$apikey" ] && return 0
local notifications existing_id schema payload result
notifications=$(api_get "$port" "/api/v3/notification" "$apikey")
existing_id=$(echo "$notifications" | jq -r '.[] | select(.implementation == "CustomScript" and .name == "Jellyfin Refresh") | .id // ""' 2>/dev/null | head -1 || echo "")
notifications=$(api_get "$port" "/api/v3/notification" "$apikey" || echo "[]")
existing_id=$(printf '%s' "$notifications" | jq -r '.[] | select(.implementation == "CustomScript" and .name == "Jellyfin Refresh") | .id // ""' 2>/dev/null | head -1 || echo "")
schema=$(api_get "$port" "/api/v3/notification/schema" "$apikey")
# Sonarr 4: onImportComplete fires once per release (season pack). Radarr has
# no onImportComplete — keep onDownload (one event per movie).
payload=$(echo "$schema" | jq '
schema=$(api_get "$port" "/api/v3/notification/schema" "$apikey" || echo "[]")
payload=$(printf '%s' "$schema" | jq '
[.[] | select(.implementation == "CustomScript")][0] |
.fields = [.fields[] | if .name == "path" then .value = "/scripts/jellyfin-refresh.sh" else . end] |
.onUpgrade = true | .name = "Jellyfin Refresh" | .tags = [] |
@ -559,29 +653,26 @@ add_jellyfin_refresh_notif() {
return 1
fi
# Ensure the mounted script is executable. Radarr/Sonarr try to start the
# process when saving a CustomScript (even with forceSave) and reject the
# notification with "Permission denied" if the bit is missing.
if [ -f "$INSTALL_DIR/scripts/jellyfin-refresh.sh" ]; then
chmod +x "$INSTALL_DIR/scripts/jellyfin-refresh.sh" 2>/dev/null || true
fi
if [ -n "$existing_id" ]; then
payload=$(echo "$payload" | jq --argjson id "$existing_id" '.id = $id' 2>/dev/null || echo "$payload")
result=$(api_put "$port" "/api/v3/notification/${existing_id}" "$apikey" "$payload")
payload=$(printf '%s' "$payload" | jq --argjson id "$existing_id" '.id = $id' 2>/dev/null || echo "$payload")
result=$(api_put "$port" "/api/v3/notification/${existing_id}" "$apikey" "$payload" || echo "")
if jq_json_has_key "$result" "id"; then
log_step "${app_name}: updated Jellyfin Refresh script (scan on import complete)"
return 0
fi
fi
result=$(api_post_force "$port" "/api/v3/notification" "$apikey" "$payload")
result=$(api_post_force "$port" "/api/v3/notification" "$apikey" "$payload" || echo "")
if jq_json_has_key "$result" "id"; then
log_step "${app_name}: added Jellyfin Refresh script (scan on import complete)"
return 0
fi
local err_msg
err_msg=$(echo "$result" | jq -r 'if type == "array" then .[0].errorMessage // empty else .errorMessage // empty end' 2>/dev/null || echo "")
err_msg=$(printf '%s' "$result" | jq -r 'if type == "array" then .[0].errorMessage // empty else .errorMessage // empty end' 2>/dev/null || echo "")
if [ -n "$err_msg" ]; then
log_step_fail "${app_name}: failed to add Jellyfin Refresh script (${err_msg})"
else

202
lib/languages.sh Executable file
View file

@ -0,0 +1,202 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr shared ISO 639 language tables and subtitle-language helpers
if [ -n "${_ASSEMBLRR_LANGUAGES_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_LANGUAGES_SOURCED=1
# Stored picker codes, preferred first. SUBTITLE_LANGUAGES="eng,ell" wins;
# otherwise SUBTITLE_LANGUAGE (legacy single value).
_subtitle_stored_lang_codes() {
local raw="${SUBTITLE_LANGUAGES:-${SUBTITLE_LANGUAGE:-}}"
raw=${raw// /}
[ -z "$raw" ] && return 0
echo "$raw" | tr ',' '\n' | awk 'NF && !seen[$0]++'
}
# $1 = preferred code; remaining args = full set. Prints comma-separated, preferred first, unique.
_subtitle_join_preferred_first() {
local preferred="${1:-}"
shift || true
local -a out=()
local c
[ -n "$preferred" ] && out+=("$preferred")
for c in "$@"; do
[ -z "$c" ] && continue
[ "$c" = "$preferred" ] && continue
out+=("$c")
done
(IFS=,; echo "${out[*]}")
}
# Map ISO 639-2/T, 639-2/B, or 639-1 → ISO 639-1 two-letter code (defaults to "en" on empty).
iso639_to_code2() {
local code="${1:-en}"
code=${code%%$'\t'*}
code=${code// /}
code=$(printf '%s' "$code" | tr '[:upper:]' '[:lower:]')
case "$code" in
""|"none") echo "en"; return ;;
[a-z][a-z]) echo "$code"; return ;;
aar) echo "aa" ;; abk) echo "ab" ;; afr) echo "af" ;; aka) echo "ak" ;;
alb|sqi) echo "sq" ;; amh) echo "am" ;; ara) echo "ar" ;; arg) echo "an" ;;
arm|hye) echo "hy" ;; asm) echo "as" ;; ava) echo "av" ;; ave) echo "ae" ;;
aym) echo "ay" ;; aze) echo "az" ;; bak) echo "ba" ;; bam) echo "bm" ;;
baq|eus) echo "eu" ;; bel) echo "be" ;; ben) echo "bn" ;; bih) echo "bh" ;;
bis) echo "bi" ;; bos) echo "bs" ;; bre) echo "br" ;; bul) echo "bg" ;;
bur|mya) echo "my" ;; cat) echo "ca" ;; cha) echo "ch" ;; che) echo "ce" ;;
chi|zho) echo "zh" ;; chu) echo "cu" ;; chv) echo "cv" ;; cor) echo "kw" ;;
cos) echo "co" ;; cre) echo "cr" ;; cze|ces) echo "cs" ;; dan) echo "da" ;;
div) echo "dv" ;; dut|nld) echo "nl" ;; dzo) echo "dz" ;; ell|gre) echo "el" ;;
eng) echo "en" ;; epo) echo "eo" ;; est) echo "et" ;; ewe) echo "ee" ;;
fao) echo "fo" ;; fij) echo "fj" ;; fin) echo "fi" ;; fra|fre) echo "fr" ;;
fry) echo "fy" ;; ful) echo "ff" ;; geo|kat) echo "ka" ;; ger|deu) echo "de" ;;
gla) echo "gd" ;; gle) echo "ga" ;; glg) echo "gl" ;; glv) echo "gv" ;;
grn) echo "gn" ;; guj) echo "gu" ;; hat) echo "ht" ;; hau) echo "ha" ;;
heb) echo "he" ;; her) echo "hz" ;; hin) echo "hi" ;; hmo) echo "ho" ;;
hrv) echo "hr" ;; hun) echo "hu" ;; ibo) echo "ig" ;; ice|isl) echo "is" ;;
ido) echo "io" ;; iii) echo "ii" ;; iku) echo "iu" ;; ile) echo "ie" ;;
ina) echo "ia" ;; ind) echo "id" ;; ipk) echo "ik" ;; ita) echo "it" ;;
jav) echo "jv" ;; jpn) echo "ja" ;; kal) echo "kl" ;; kan) echo "kn" ;;
kas) echo "ks" ;; kau) echo "kr" ;; kaz) echo "kk" ;; khm) echo "km" ;;
kik) echo "ki" ;; kin) echo "rw" ;; kir) echo "ky" ;; kom) echo "kv" ;;
kon) echo "kg" ;; kor) echo "ko" ;; kua) echo "kj" ;; kur) echo "ku" ;;
lao) echo "lo" ;; lat) echo "la" ;; lav) echo "lv" ;; lim) echo "li" ;;
lin) echo "ln" ;; lit) echo "lt" ;; ltz) echo "lb" ;; lub) echo "lu" ;;
lug) echo "lg" ;; mac|mkd) echo "mk" ;; mah) echo "mh" ;; mal) echo "ml" ;;
mao|mri) echo "mi" ;; mar) echo "mr" ;; may|msa) echo "ms" ;; mlg) echo "mg" ;;
mlt) echo "mt" ;; mon) echo "mn" ;; nau) echo "na" ;; nav) echo "nv" ;;
nbl) echo "nr" ;; nde) echo "nd" ;; ndo) echo "ng" ;; nep) echo "ne" ;;
nno) echo "nn" ;; nob) echo "nb" ;; nor) echo "no" ;; nya) echo "ny" ;;
oci) echo "oc" ;; oji) echo "oj" ;; ori) echo "or" ;; orm) echo "om" ;;
oss) echo "os" ;; pan) echo "pa" ;; per|fas) echo "fa" ;; pli) echo "pi" ;;
pol) echo "pl" ;; por) echo "pt" ;; pus) echo "ps" ;; que) echo "qu" ;;
roh) echo "rm" ;; ron|rum) echo "ro" ;; run) echo "rn" ;; rus) echo "ru" ;;
sag) echo "sg" ;; san) echo "sa" ;; sin) echo "si" ;; slo|slk) echo "sk" ;;
slv) echo "sl" ;; sme) echo "se" ;; smo) echo "sm" ;; sna) echo "sn" ;;
snd) echo "sd" ;; som) echo "so" ;; sot) echo "st" ;; spa) echo "es" ;;
srd) echo "sc" ;; srp) echo "sr" ;; ssw) echo "ss" ;; sun) echo "su" ;;
swa) echo "sw" ;; swe) echo "sv" ;; tah) echo "ty" ;; tam) echo "ta" ;;
tat) echo "tt" ;; tel) echo "te" ;; tgk) echo "tg" ;; tgl) echo "tl" ;;
tha) echo "th" ;; tib|bod) echo "bo" ;; tir) echo "ti" ;; ton) echo "to" ;;
tsn) echo "tn" ;; tso) echo "ts" ;; tuk) echo "tk" ;; tur) echo "tr" ;;
twi) echo "tw" ;; uig) echo "ug" ;; ukr) echo "uk" ;; urd) echo "ur" ;;
uzb) echo "uz" ;; ven) echo "ve" ;; vie) echo "vi" ;; vol) echo "vo" ;;
wel|cym) echo "cy" ;; wln) echo "wa" ;; wol) echo "wo" ;; xho) echo "xh" ;;
yid) echo "yi" ;; yor) echo "yo" ;; zha) echo "za" ;; zul) echo "zu" ;;
*) echo "$code" ;;
esac
}
# Map ISO 639-1 two-letter (or 639-2/B) → ISO 639-2/T three-letter code (Jellyfin format).
iso639_to_code3() {
local code="${1:-en}"
code=${code%%$'\t'*}
code=${code// /}
code=$(printf '%s' "$code" | tr '[:upper:]' '[:lower:]')
case "$code" in
""|"none") echo "eng"; return ;;
alb) echo "sqi"; return ;; arm) echo "hye"; return ;; baq) echo "eus"; return ;;
bur) echo "mya"; return ;; chi) echo "zho"; return ;; cze) echo "ces"; return ;;
dut) echo "nld"; return ;; fre) echo "fra"; return ;; geo) echo "kat"; return ;;
ger) echo "deu"; return ;; gre) echo "ell"; return ;; ice) echo "isl"; return ;;
mac) echo "mkd"; return ;; mao) echo "mri"; return ;; may) echo "msa"; return ;;
per) echo "fas"; return ;; rum) echo "ron"; return ;; slo) echo "slk"; return ;;
tib) echo "bod"; return ;; wel) echo "cym"; return ;;
[a-z][a-z][a-z]) echo "$code"; return ;;
aa) echo "aar" ;; ab) echo "abk" ;; af) echo "afr" ;; ak) echo "aka" ;;
am) echo "amh" ;; an) echo "arg" ;; ar) echo "ara" ;; as) echo "asm" ;;
av) echo "ava" ;; ae) echo "ave" ;; ay) echo "aym" ;; az) echo "aze" ;;
ba) echo "bak" ;; be) echo "bel" ;; bg) echo "bul" ;; bh) echo "bih" ;;
bi) echo "bis" ;; bm) echo "bam" ;; bn) echo "ben" ;; bo) echo "bod" ;;
br) echo "bre" ;; bs) echo "bos" ;; ca) echo "cat" ;; ce) echo "che" ;;
ch) echo "cha" ;; co) echo "cos" ;; cr) echo "cre" ;; cs) echo "ces" ;;
cu) echo "chu" ;; cv) echo "chv" ;; cy) echo "cym" ;; da) echo "dan" ;;
de) echo "deu" ;; dv) echo "div" ;; dz) echo "dzo" ;; ee) echo "ewe" ;;
el) echo "ell" ;; en) echo "eng" ;; eo) echo "epo" ;; es) echo "spa" ;;
et) echo "est" ;; eu) echo "eus" ;; fa) echo "fas" ;; ff) echo "ful" ;;
fi) echo "fin" ;; fj) echo "fij" ;; fo) echo "fao" ;; fr) echo "fra" ;;
fy) echo "fry" ;; ga) echo "gle" ;; gd) echo "gla" ;; gl) echo "glg" ;;
gn) echo "grn" ;; gu) echo "guj" ;; gv) echo "glv" ;; ha) echo "hau" ;;
he) echo "heb" ;; hi) echo "hin" ;; ho) echo "hmo" ;; hr) echo "hrv" ;;
ht) echo "hat" ;; hu) echo "hun" ;; hy) echo "hye" ;; hz) echo "her" ;;
ia) echo "ina" ;; id) echo "ind" ;; ie) echo "ile" ;; ig) echo "ibo" ;;
ii) echo "iii" ;; ik) echo "ipk" ;; io) echo "ido" ;; is) echo "isl" ;;
it) echo "ita" ;; iu) echo "iku" ;; ja) echo "jpn" ;; jv) echo "jav" ;;
ka) echo "kat" ;; kg) echo "kon" ;; ki) echo "kik" ;; kj) echo "kua" ;;
kk) echo "kaz" ;; kl) echo "kal" ;; km) echo "khm" ;; kn) echo "kan" ;;
ko) echo "kor" ;; kr) echo "kau" ;; ks) echo "kas" ;; ku) echo "kur" ;;
kv) echo "kom" ;; kw) echo "cor" ;; ky) echo "kir" ;; la) echo "lat" ;;
lb) echo "ltz" ;; lg) echo "lug" ;; li) echo "lim" ;; ln) echo "lin" ;;
lo) echo "lao" ;; lt) echo "lit" ;; lu) echo "lub" ;; lv) echo "lav" ;;
mg) echo "mlg" ;; mh) echo "mah" ;; mi) echo "mri" ;; mk) echo "mkd" ;;
ml) echo "mal" ;; mn) echo "mon" ;; mr) echo "mar" ;; ms) echo "msa" ;;
mt) echo "mlt" ;; my) echo "mya" ;; na) echo "nau" ;; nb) echo "nob" ;;
nd) echo "nde" ;; ne) echo "nep" ;; ng) echo "ndo" ;; nl) echo "nld" ;;
nn) echo "nno" ;; no) echo "nor" ;; nr) echo "nbl" ;; nv) echo "nav" ;;
ny) echo "nya" ;; oc) echo "oci" ;; oj) echo "oji" ;; om) echo "om" ;;
or) echo "ori" ;; os) echo "oss" ;; pa) echo "pan" ;; pi) echo "pli" ;;
pl) echo "pol" ;; ps) echo "pus" ;; pt) echo "por" ;; qu) echo "que" ;;
rm) echo "roh" ;; rn) echo "run" ;; ro) echo "ron" ;; ru) echo "rus" ;;
rw) echo "kin" ;; sa) echo "san" ;; sc) echo "srd" ;; sd) echo "snd" ;;
se) echo "sme" ;; sg) echo "sag" ;; si) echo "sin" ;; sk) echo "slk" ;;
sl) echo "slv" ;; sm) echo "smo" ;; sn) echo "sna" ;; so) echo "som" ;;
sq) echo "sqi" ;; sr) echo "srp" ;; ss) echo "ssw" ;; st) echo "sot" ;;
su) echo "sun" ;; sv) echo "swe" ;; sw) echo "swa" ;; ta) echo "tam" ;;
te) echo "tel" ;; tg) echo "tgk" ;; th) echo "tha" ;; ti) echo "tir" ;;
tk) echo "tuk" ;; tl) echo "tgl" ;; tn) echo "tsn" ;; to) echo "ton" ;;
tr) echo "tur" ;; ts) echo "tso" ;; tt) echo "tat" ;; tw) echo "twi" ;;
ty) echo "tah" ;; ug) echo "uig" ;; uk) echo "ukr" ;; ur) echo "urd" ;;
uz) echo "uzb" ;; ve) echo "ven" ;; vi) echo "vie" ;; vo) echo "vol" ;;
wa) echo "wln" ;; wo) echo "wol" ;; xh) echo "xho" ;; yi) echo "yid" ;;
yo) echo "yor" ;; za) echo "zha" ;; zh) echo "zho" ;; zu) echo "zul" ;;
*) echo "$code" ;;
esac
}
# Offline fallback list (ISO 639-2/T<TAB>Name) when GitHub iso6392.txt is unreachable.
iso639_bundled_menu() {
cat <<'EOF'
ara Arabic
bul Bulgarian
cat Catalan
ces Czech
dan Danish
deu German
ell Greek
eng English
est Estonian
fas Persian
fin Finnish
fra French
heb Hebrew
hin Hindi
hrv Croatian
hun Hungarian
ind Indonesian
ita Italian
jpn Japanese
kor Korean
lit Lithuanian
lav Latvian
msa Malay
nld Dutch
nor Norwegian
pol Polish
por Portuguese
ron Romanian
rus Russian
slk Slovak
slv Slovenian
spa Spanish
srp Serbian
swe Swedish
tha Thai
tur Turkish
ukr Ukrainian
vie Vietnamese
zho Chinese
EOF
}

96
lib/log.sh Executable file
View file

@ -0,0 +1,96 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr logging and progress indicators
if [ -n "${_ASSEMBLRR_LOG_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_LOG_SOURCED=1
_log_init_colors() {
if [ -n "${NO_COLOR:-}" ] || [ "${TERM:-}" = "dumb" ] || { [ ! -t 1 ] && [ ! -t 2 ]; }; then
RED=''
GREEN=''
YELLOW=''
NC=''
else
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
fi
}
_log_init_colors
readonly RED GREEN YELLOW NC
_log_to_file() {
if [ -n "${LOG_FILE:-}" ]; then
printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1" >> "$LOG_FILE" 2>/dev/null || true
fi
return 0
}
log_success() { printf '%b\n' "${GREEN}$1${NC}"; _log_to_file "INFO: $1"; return 0; }
log_warning() { printf '%b\n' "${YELLOW}$1${NC}"; _log_to_file "WARN: $1"; return 0; }
log_info() { printf '%s\n' "$1"; _log_to_file "INFO: $1"; return 0; }
log_debug() { _log_to_file "DEBUG: $1"; return 0; }
log_error_inline() { printf '%b\n' "${RED}$1${NC}" >&2; _log_to_file "ERROR: $1"; return 0; }
die() { printf '%b\n' "${RED}$1${NC}" >&2; _log_to_file "ERROR: $1"; exit 1; }
log_error() { die "$@"; }
# Rewrite the current line on TTY stderr: "Waiting for Radarr API (12s)".
# In non-TTY stderr, avoid carriage-return / ANSI escapes.
wait_inline() {
local label="$1"
local secs="${2:-0}"
if [ -t 2 ]; then
printf '\r\033[K%s (%ss)' "$label" "$secs" >&2
else
printf '%s (%ss)\n' "$label" "$secs" >&2
fi
}
# Run a command while updating wait_inline every second.
# Captures stdout+stderr in WAIT_WHILE_OUTPUT. Returns the command's exit status.
wait_while() {
local label="$1"
shift
local out ticker rc=0 had_errexit=0
[ $# -gt 0 ] || return 1
out=$(mktemp)
[[ $- == *e* ]] && had_errexit=1
(
secs=0
trap 'exit 0' TERM INT
while true; do
wait_inline "$label" "$secs"
sleep 1
secs=$((secs + 1))
done
) &
ticker=$!
_wait_while_cleanup() {
kill "$ticker" 2>/dev/null || true
wait "$ticker" 2>/dev/null || true
[ -t 2 ] && printf '\r\033[K' >&2
rm -f "$out" 2>/dev/null || true
}
trap '_wait_while_cleanup; exit 130' INT
trap '_wait_while_cleanup; exit 143' TERM
set +e
"$@" >"$out" 2>&1
rc=$?
[ "$had_errexit" = 1 ] && set -e
trap - INT TERM
kill "$ticker" 2>/dev/null || true
wait "$ticker" 2>/dev/null || true
[ -t 2 ] && printf '\r\033[K' >&2
WAIT_WHILE_OUTPUT=$(cat "$out" 2>/dev/null || true)
rm -f "$out"
return "$rc"
}

29
lib/managed_files.sh Normal file → Executable file
View file

@ -1,26 +1,36 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr managed file manifest — files upgrade/setup may replace in the install dir
# Sacred (never overwritten by upgrade): secrets/, config/* service data, .env,
# .assemblrr-config, compose/custom.yaml
# .assemblrr-config, .assemblrr-channel, .assemblrr-version, .assemblrr-migrations, compose/custom.yaml
#
# Format printed by list_managed_files: SOURCE_REL|DEST_REL
# SOURCE_REL is relative to the package source tree (repo root).
# DEST_REL is relative to the install directory.
# Re-sourceable: redefines list_managed_files from the active package tree.
list_managed_files() {
cat <<'EOF'
lib/core.sh|lib/core.sh
lib/log.sh|lib/log.sh
lib/tty.sh|lib/tty.sh
lib/paths.sh|lib/paths.sh
lib/fs.sh|lib/fs.sh
lib/docker.sh|lib/docker.sh
lib/languages.sh|lib/languages.sh
lib/branding.sh|lib/branding.sh
lib/compose.sh|lib/compose.sh
lib/vpn.sh|lib/vpn.sh
lib/api.sh|lib/api.sh
lib/arr.sh|lib/arr.sh
lib/qbit.sh|lib/qbit.sh
lib/arr_common.sh|lib/arr_common.sh
lib/arr_quality.sh|lib/arr_quality.sh
lib/prowlarr.sh|lib/prowlarr.sh
lib/arr_import.sh|lib/arr_import.sh
lib/recyclarr.sh|lib/recyclarr.sh
lib/quality.sh|lib/quality.sh
lib/jellyfin.sh|lib/jellyfin.sh
lib/seerr.sh|lib/seerr.sh
lib/bazarr.sh|lib/bazarr.sh
lib/usenet.sh|lib/usenet.sh
lib/prompts.sh|lib/prompts.sh
lib/fzf-tui.sh|lib/fzf-tui.sh
lib/managed_files.sh|lib/managed_files.sh
@ -31,6 +41,11 @@ lib/config_edit.sh|lib/config_edit.sh
compose/base.yaml|compose/base.yaml
compose/direct-access.yaml|compose/direct-access.yaml
compose/vpn.yaml|compose/vpn.yaml
compose/vuetorrent.yaml|compose/vuetorrent.yaml
compose/gpu-intel.yaml|compose/gpu-intel.yaml
compose/gpu-nvidia.yaml|compose/gpu-nvidia.yaml
compose/byparr.yaml|compose/byparr.yaml
compose/usenet.yaml|compose/usenet.yaml
compose/examples/custom.yaml.example|compose/examples/custom.yaml.example
compose/sidecars/vpn-watchdog.Dockerfile|compose/sidecars/vpn-watchdog.Dockerfile
compose/sidecars/media-purge-watch.Dockerfile|compose/sidecars/media-purge-watch.Dockerfile
@ -45,6 +60,7 @@ templates/recyclarr/includes/sonarr-1080p-web.yml|templates/recyclarr/includes/s
templates/recyclarr/includes/sonarr-4k-web.yml|templates/recyclarr/includes/sonarr-4k-web.yml
templates/recyclarr/includes/sonarr-soft-cfs.yml|templates/recyclarr/includes/sonarr-soft-cfs.yml
branding.conf|branding.conf
NOTICE|NOTICE
bin/cli.sh|cli.sh
bin/config.sh|config.sh
bin/setup.sh|setup.sh
@ -56,13 +72,12 @@ scripts/arr-purge-hook.sh|scripts/arr-purge-hook.sh
scripts/media-purge-watch.sh|scripts/media-purge-watch.sh
scripts/seerr-gateway.py|scripts/seerr-gateway.py
docs/api-reference.md|docs/api-reference.md
docs/komodo.md|docs/komodo.md
docs/trash-guides.md|docs/trash-guides.md
docs/uninstall.md|docs/uninstall.md
docs/seerr-delete-request.md|docs/seerr-delete-request.md
README.md|README.md
EOF
# Migrations (all files under migrations/)
# Listed dynamically when a source root is available via UPGRADE_SOURCE_ROOT
if [ -n "${UPGRADE_SOURCE_ROOT:-}" ] && [ -d "$UPGRADE_SOURCE_ROOT/migrations" ]; then
local f rel
while IFS= read -r -d '' f; do

512
lib/paths.sh Executable file
View file

@ -0,0 +1,512 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr config parsing, path discovery, storage probes, and leftover scan
if [ -n "${_ASSEMBLRR_PATHS_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_PATHS_SOURCED=1
# Expand $VAR and ${VAR} references inside a validated string without eval/source.
_safe_expand_vars() {
local val="$1"
local out="" rest="$val" var="" repl=""
while [[ "$rest" =~ ^([^$]*)\$(.*)$ ]]; do
out+="${BASH_REMATCH[1]}"
rest="${BASH_REMATCH[2]}"
if [[ "$rest" =~ ^\{([A-Za-z_][A-Za-z0-9_]*)\}(.*)$ ]]; then
var="${BASH_REMATCH[1]}"
rest="${BASH_REMATCH[2]}"
repl="${!var-}"
out+="$repl"
elif [[ "$rest" =~ ^([A-Za-z_][A-Za-z0-9_]*)(.*)$ ]]; then
var="${BASH_REMATCH[1]}"
rest="${BASH_REMATCH[2]}"
repl="${!var-}"
out+="$repl"
else
out+='$'
fi
done
out+="$rest"
printf '%s' "$out"
}
# Safely parse a KEY=VALUE file without executing shell code (no eval / source).
safe_source() {
local file="$1"
if [ ! -f "$file" ]; then
return 1
fi
local do_export=0
[[ $- == *a* ]] && do_export=1
local -a keys=() vals=()
local line key raw val
while IFS= read -r line || [ -n "$line" ]; do
line="${line%$'\r'}"
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
if ! [[ "$line" =~ ^([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
log_error_inline "Rejecting unsafe line in $file: $line"
return 1
fi
key="${BASH_REMATCH[1]}"
raw="${BASH_REMATCH[2]}"
# Reject trailing backslash continuations.
if [[ "$raw" == *\\ ]]; then
log_error_inline "Rejecting unsafe line continuation in $file: $line"
return 1
fi
if [[ "$raw" =~ ^\'([^\']*)\'$ ]]; then
val="${BASH_REMATCH[1]}"
elif [[ "$raw" =~ ^\"(([^\"\\]|\\.)*)\"$ ]]; then
val="${BASH_REMATCH[1]}"
if [[ "$val" == *'$('* ]] || [[ "$val" == *'`'* ]]; then
log_error_inline "Rejecting command substitution in $file: $line"
return 1
fi
val="${val//\\\"/\"}"
val="${val//\\\\/\\}"
val="${val//\\\$/\$}"
val=$(_safe_expand_vars "$val")
else
# Unquoted value: reject whitespace, shell metacharacters, or quotes
case "$raw" in
*[[:space:]]*|*'$('*|*'`'*|*';'*|*'|'*|*'&'*|*'>'*|*'<'*|*'('*|*')'*|*\"*|*\'*)
log_error_inline "Rejecting unsafe value in $file: $line"
return 1
;;
esac
val=$(_safe_expand_vars "$raw")
fi
keys+=("$key")
vals+=("$val")
# Make earlier assignments visible to subsequent lines (e.g. branding.conf)
printf -v "$key" '%s' "$val"
if [ "$do_export" -eq 1 ]; then
export "$key"
fi
done < "$file"
return 0
}
# Discover installation directory from ASSEMBLRR_DIR or runtime pointers.
find_install_directory() {
if [ -n "${ASSEMBLRR_DIR:-}" ]; then
echo "$ASSEMBLRR_DIR"
return 0
fi
local name="${APP_NAME:-assemblrr}"
local -a search_order=(
"$HOME/.assemblrr-config"
"$HOME/.${name}-config"
"/opt/${name}/.${name}-config"
"$HOME/${name}/.${name}-config"
)
local config_file
for config_file in "${search_order[@]}"; do
if [ -f "$config_file" ]; then
safe_source "$config_file" || continue
if [ -n "${INSTALL_DIRECTORY:-}" ]; then
echo "$INSTALL_DIRECTORY"
return 0
fi
fi
done
echo ""
return 1
}
# Read KEY="value" from a dotenv file without mutating shell globals.
_pointer_get() {
local file="$1"
local key="$2"
local line
[ -f "$file" ] || return 0
line=$(grep -E "^${key}=" "$file" 2>/dev/null | tail -1) || true
line="${line#${key}=}"
line="${line%$'\r'}"
line="${line#\"}"
line="${line%\"}"
line="${line#\'}"
line="${line%\'}"
printf '%s\n' "$line"
}
# $1 = pipe-separated list, $2 = path to add. Prints the new list (no dups).
_known_path_list_add() {
local list="${1:-}"
local add="${2:-}"
local p
add="${add%/}"
[ -n "$add" ] || { printf '%s\n' "$list"; return 0; }
if [ -n "$list" ]; then
local -a parts=()
IFS='|' read -ra parts <<< "$list"
for p in "${parts[@]}"; do
[ "$p" = "$add" ] && { printf '%s\n' "$list"; return 0; }
done
printf '%s|%s\n' "$list" "$add"
else
printf '%s\n' "$add"
fi
}
# Home pointer so the CLI can find a non-default (or mid-setup) install.
write_install_pointer() {
local install_dir="${1%/}"
local media_dir="${2:-}"
local pointer="$HOME/.assemblrr-config"
local known_i known_m prev_i prev_m
media_dir="${media_dir%/}"
known_i=$(_pointer_get "$pointer" "KNOWN_INSTALLS")
known_m=$(_pointer_get "$pointer" "KNOWN_MEDIA")
prev_i=$(_pointer_get "$pointer" "INSTALL_DIRECTORY")
prev_m=$(_pointer_get "$pointer" "MEDIA_DIRECTORY")
known_i=$(_known_path_list_add "$known_i" "$prev_i")
known_i=$(_known_path_list_add "$known_i" "$install_dir")
known_m=$(_known_path_list_add "$known_m" "$prev_m")
known_m=$(_known_path_list_add "$known_m" "$media_dir")
(
umask 077
{
printf 'INSTALL_DIRECTORY="%s"\n' "$install_dir"
if [ -n "$media_dir" ]; then
printf 'MEDIA_DIRECTORY="%s"\n' "$media_dir"
fi
[ -n "$known_i" ] && printf 'KNOWN_INSTALLS="%s"\n' "$known_i"
[ -n "$known_m" ] && printf 'KNOWN_MEDIA="%s"\n' "$known_m"
} > "$pointer"
)
chmod 600 "$pointer" 2>/dev/null || true
}
load_install_pointer() {
local pointer=""
if [ -f "$HOME/.assemblrr-config" ]; then
pointer="$HOME/.assemblrr-config"
elif [ -f "$HOME/.${APP_NAME:-assemblrr}-config" ]; then
pointer="$HOME/.${APP_NAME:-assemblrr}-config"
else
return 1
fi
safe_source "$pointer"
}
is_assemblrr_install_tree() {
local d="$1"
local name="${APP_NAME:-assemblrr}"
[ -d "$d" ] || return 1
[ "$(basename "$d")" = "$name" ] || return 1
if [ -f "$d/.assemblrr-config" ] || [ -f "$d/.${name}-config" ] || \
[ -f "$d/cli.sh" ] || [ -f "$d/compose/base.yaml" ] || [ -d "$d/lib" ]; then
return 0
fi
[ -z "$(find "$d" -mindepth 1 -maxdepth 1 2>/dev/null | head -n 1 || true)" ]
}
is_assemblrr_media_tree() {
local d="$1"
local name="${APP_NAME:-assemblrr}"
[ -d "$d" ] || return 1
[ "$(basename "$d")" = "${name}-media" ] || return 1
[ -d "$d/torrents/movies" ] || [ -d "$d/media/movies" ] || [ -d "$d/usenet/complete" ] || [ -d "$d/blackhole" ]
}
is_complete_assemblrr_install() {
local d="$1"
[ -n "$d" ] && [ -d "$d" ] || return 1
[ ! -f "$d/.assemblrr-setup-in-progress" ] || return 1
{ [ -f "$d/.assemblrr-config" ] || [ -f "$d/.${APP_NAME:-assemblrr}-config" ]; } || return 1
[ -f "$d/cli.sh" ] || [ -f "$d/compose/base.yaml" ]
}
# Print detected Config, Media, and CLI paths (and optionally scan leftovers).
# Set ASSEMBLRR_SHOW_LEFTOVERS=0 to skip scanning external mounts (e.g. `status`).
print_detected_locations() {
local heading="${1:-}"
local cli_path="$HOME/.local/bin/${APP_CLI_NAME:-assemblrr}"
local kind path
[ -n "$heading" ] && echo "$heading"
printf ' Config: %s\n' "${INSTALL_DIR:-unknown}"
printf ' Media: %s\n' "${MEDIA_DIRECTORY:-unknown}"
if [ -e "$cli_path" ]; then
printf ' CLI: %s\n' "$cli_path"
fi
if [ "${ASSEMBLRR_SHOW_LEFTOVERS:-1}" = "1" ]; then
while IFS=$'\t' read -r kind path; do
[ -n "$path" ] || continue
case "$kind" in
install) printf ' Leftover install: %s\n' "$path" ;;
media) printf ' Leftover media: %s\n' "$path" ;;
esac
done < <(list_assemblrr_leftovers "${INSTALL_DIR:-}" "${MEDIA_DIRECTORY:-}")
fi
}
_assemblrr_tree_media_dir() {
local d="$1"
local cfg="" media=""
[ -f "$d/.assemblrr-config" ] && cfg="$d/.assemblrr-config"
[ -z "$cfg" ] && [ -f "$d/.${APP_NAME:-assemblrr}-config" ] && cfg="$d/.${APP_NAME:-assemblrr}-config"
[ -n "$cfg" ] || return 0
media=$(_pointer_get "$cfg" "MEDIA_DIRECTORY")
printf '%s\n' "${media%/}"
}
# TSV: kind<TAB>path kind is install|media
list_assemblrr_leftovers() {
local skip_install="${1:-}"
local skip_media="${2:-}"
local name="${APP_NAME:-assemblrr}"
local pointer="" root media
local -A seen_i=()
local -A seen_m=()
skip_install="${skip_install%/}"
skip_media="${skip_media%/}"
_leftover_emit_install() {
local p="${1%/}"
local trust="${2:-0}"
[ -n "$p" ] && [ -d "$p" ] || return 0
[ "$p" != "$skip_install" ] || return 0
[ -z "${seen_i[$p]:-}" ] || return 0
if [ "$trust" != "1" ] && ! is_assemblrr_install_tree "$p"; then
return 0
fi
seen_i[$p]=1
printf 'install\t%s\n' "$p"
media=$(_assemblrr_tree_media_dir "$p")
if [ -n "$media" ] && [ -d "$media" ] && [ "$media" != "$skip_media" ] && \
[ -z "${seen_m[$media]:-}" ]; then
seen_m[$media]=1
printf 'media\t%s\n' "$media"
fi
}
_leftover_emit_media() {
local p="${1%/}"
local trust="${2:-0}"
[ -n "$p" ] && [ -d "$p" ] || return 0
[ "$p" != "$skip_media" ] || return 0
[ -z "${seen_m[$p]:-}" ] || return 0
if [ "$trust" != "1" ] && ! is_assemblrr_media_tree "$p"; then
return 0
fi
seen_m[$p]=1
printf 'media\t%s\n' "$p"
}
if [ -f "$HOME/.assemblrr-config" ]; then
pointer="$HOME/.assemblrr-config"
elif [ -f "$HOME/.${name}-config" ]; then
pointer="$HOME/.${name}-config"
fi
if [ -n "$pointer" ]; then
local -a parts=()
local part raw_list
raw_list=$(_pointer_get "$pointer" "KNOWN_INSTALLS")
if [ -n "$raw_list" ]; then
IFS='|' read -ra parts <<< "$raw_list"
for part in "${parts[@]}"; do
[ -n "$part" ] && _leftover_emit_install "$part" 1
done
fi
raw_list=$(_pointer_get "$pointer" "KNOWN_MEDIA")
if [ -n "$raw_list" ]; then
IFS='|' read -ra parts <<< "$raw_list"
for part in "${parts[@]}"; do
[ -n "$part" ] && _leftover_emit_media "$part" 1
done
fi
fi
_leftover_scan_root() {
local r="${1%/}"
[ -n "$r" ] && [ -d "$r" ] || return 0
_leftover_emit_install "${r}/${name}" 0
_leftover_emit_media "${r}/${name}-media" 0
local c
for c in "$r"/*; do
[ -d "$c" ] || continue
_leftover_emit_install "${c}/${name}" 0
_leftover_emit_media "${c}/${name}-media" 0
done
}
_leftover_scan_root "${HOME:-}"
_leftover_scan_root /opt
while IFS= read -r root; do
[ -n "$root" ] || continue
_leftover_scan_root "$root"
done < <(list_storage_roots)
}
expand_path() {
local path="$1"
echo "${path/#\~/$HOME}"
}
storage_root_label() {
local root="${1%/}"
local letter
case "$root" in
/mnt/[a-z])
letter="${root##*/}"
echo "Windows ${letter^^}:"
;;
/media/*|/run/media/*)
echo "${root##*/}"
;;
*)
echo "$root"
;;
esac
}
storage_free_label() {
local root="$1"
local avail
avail=$(df -hP "$root" 2>/dev/null | awk 'NR==2 {print $4}')
if [ -n "$avail" ]; then
echo " (${avail} free)"
fi
}
list_storage_roots() {
local d
local -A seen=()
_list_storage_emit() {
local p="${1%/}"
[ -n "$p" ] && [ -d "$p" ] || return 0
[ "$p" = "${HOME:-}" ] && return 0
[ -n "${seen[$p]:-}" ] && return 0
seen[$p]=1
printf '%s\n' "$p"
}
for d in /mnt/[a-z]; do
[ -d "$d" ] || continue
if grep -Eq "[[:space:]]${d}[[:space:]]" /proc/mounts 2>/dev/null; then
_list_storage_emit "$d"
fi
done
for d in /media/"${USER:-}"/* /media/* /run/media/"${USER:-}"/*; do
[ -d "$d" ] || continue
case "$d" in
/media|"/media/${USER:-}"|/run/media|"/run/media/${USER:-}") continue ;;
esac
[ -r "$d" ] || continue
_list_storage_emit "$d"
done
}
# Trigger WSL drive automounts using PowerShell Get-PSDrive (replaces Win11-removed wmic).
poke_wsl_automounts() {
grep -qi microsoft /proc/version 2>/dev/null || return 0
local letters="" letter mountpoint
if command -v powershell.exe >/dev/null 2>&1; then
letters=$(timeout 5 powershell.exe -NoProfile -NonInteractive -Command \
'(Get-PSDrive -PSProvider FileSystem).Name' 2>/dev/null \
| tr -d '\r' | grep -Eo '^[A-Za-z]$' | tr '[:upper:]' '[:lower:]' || true)
fi
for letter in $letters; do
mountpoint="/mnt/$letter"
[ -d "$mountpoint" ] || mkdir -p "$mountpoint" 2>/dev/null || true
timeout 2 ls "$mountpoint" >/dev/null 2>&1 || true
if [ -d "$mountpoint" ] && ! grep -Eq "[[:space:]]${mountpoint}[[:space:]]" /proc/mounts 2>/dev/null; then
rmdir "$mountpoint" 2>/dev/null || true
fi
done
for mountpoint in /mnt/[a-z]; do
[ -d "$mountpoint" ] || continue
timeout 2 ls "$mountpoint" >/dev/null 2>&1 || true
done
}
storage_mount_root() {
local p="${1%/}"
local rest
case "$p" in
/mnt/[a-z]) echo "$p" ;;
/mnt/[a-z]/*)
rest="${p#/mnt/}"
echo "/mnt/${rest%%/*}"
;;
/run/media/*)
echo "$p" | awk -F/ '{ if (NF >= 5) print "/"$2"/"$3"/"$4"/"$5; else print $0 }'
;;
/media/*)
echo "$p" | awk -F/ '{ if (NF >= 4) print "/"$2"/"$3"/"$4; else print $0 }'
;;
*) echo "$p" ;;
esac
}
storage_needs_probe() {
case "${1%/}" in
/mnt/[a-z]|/mnt/[a-z]/*|/media/*|/run/media/*) return 0 ;;
*) return 1 ;;
esac
}
run_with_timeout() {
local secs="$1"
shift
if command -v timeout >/dev/null 2>&1; then
timeout --foreground "$secs" "$@"
else
"$@"
fi
}
probe_writable_path() {
local path="$1"
local secs="${2:-8}"
local root probe start now elapsed rc=0
root=$(storage_mount_root "$path")
[ -n "$root" ] || return 1
probe="$root/.assemblrr-write-test.$$"
start=$(date +%s)
export ASSEMBLRR_PROBE_FILE="$probe"
run_with_timeout "$secs" bash -c \
'printf ok > "$ASSEMBLRR_PROBE_FILE" && grep -qx ok "$ASSEMBLRR_PROBE_FILE" && rm -f "$ASSEMBLRR_PROBE_FILE"' \
|| rc=$?
unset ASSEMBLRR_PROBE_FILE
rm -f "$probe" 2>/dev/null || true
now=$(date +%s)
elapsed=$((now - start))
if [ "$rc" -eq 124 ]; then
log_warning "No response from ${root} after ${secs}s — the drive looks stuck."
log_info "Common on flaky USB / WSL drive letters (Explorer may freeze on that disk too)."
log_info "From PowerShell: wsl --shutdown"
log_info "Then check the drive in Explorer, or pick Home in the list."
return 1
fi
if [ "$rc" -ne 0 ]; then
log_warning "Cannot write to ${root} (disconnected, or no permission)."
return 1
fi
if [ "$elapsed" -ge 3 ]; then
log_warning "${root} is slow (${elapsed}s). USB/WSL mounts can stall setup and Docker later."
fi
return 0
}

584
lib/prompts.sh Normal file → Executable file
View file

@ -1,62 +1,26 @@
#!/bin/bash
# assemblrr setup prompts — sourced by setup.sh
# Provides: interactive prompt functions for service configuration
# Requires: lib/core.sh (logging, read_masked, expand_path, directory helpers),
# SETUP_MODE, SUPPORTED_MEDIA_SERVICES, APP_DEFAULT_INSTALL_DIR,
# APP_DEFAULT_MEDIA_DIR, MEDIA_SUBDIRS (all set by setup.sh)
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr setup prompts — sourced by setup.sh & config_edit.sh
# Provides: interactive prompt functions for service and feature configuration
# Does not set -euo pipefail when sourced.
set -euo pipefail
if [ -n "${_ASSEMBLRR_PROMPTS_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_PROMPTS_SOURCED=1
_prompts_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
[ -f "$_prompts_dir/ui.sh" ] && source "$_prompts_dir/ui.sh"
# shellcheck source=/dev/null
[ -f "$_prompts_dir/languages.sh" ] && source "$_prompts_dir/languages.sh"
configure_media_service() {
# Express mode: use Jellyfin by default
if [ "${SETUP_MODE:-}" = "express" ]; then
media_service="jellyfin"
media_service_port=8096
log_success "Media service: Jellyfin (port $media_service_port)"
export media_service media_service_port
return 0
fi
ui_intro \
"Time to choose your media service." \
"Change the media server. This restarts the stack."
echo " 1) Jellyfin (recommended, easier)"
echo " 2) Emby"
echo " 3) Plex (advanced, uses host networking)"
while true; do
read -p "Choose your media service [1]: " media_service_choice
media_service_choice=${media_service_choice:-1}
case "$media_service_choice" in
1) media_service="jellyfin"; break ;;
2) media_service="emby"; break ;;
3) media_service="plex"; break ;;
*) media_service=$(echo "$media_service_choice" | awk '{print tolower($0)}') ;;
esac
if [[ ! " ${SUPPORTED_MEDIA_SERVICES[@]} " =~ " ${media_service} " ]]; then
log_warning "\"$media_service\" is not supported. Please choose 1, 2, or 3."
else
break
fi
done
# Set media service port
if [ "$media_service" == "plex" ]; then
media_service_port=32400
else
media_service_port=8096
fi
echo
log_success "${APP_DISPLAY_NAME} will install \"$media_service\" on port \"$media_service_port\""
media_service="jellyfin"
media_service_port=8096
log_success "Media service: Jellyfin (port $media_service_port)"
export media_service media_service_port
return 0
}
configure_quality_profile() {
@ -67,8 +31,9 @@ configure_quality_profile() {
echo " 2) 1080p (TV: assemblrr 1080p WEB)"
echo " 3) Any (stock *arr profile — no quality preference)"
local quality_choice source_choice
while true; do
read -p "Choose your default quality profile [1]: " quality_choice
read_prompt "Choose your default quality profile [1]: " quality_choice
quality_choice=${quality_choice:-1}
case "$quality_choice" in
@ -87,7 +52,7 @@ configure_quality_profile() {
echo " 1) WEB only (smaller files; no Blu-ray upgrades)"
echo " 2) Bluray + WEB (upgrades WEB to a Blu-ray encode when one exists)"
while true; do
read -p "Choose movie source [2]: " source_choice
read_prompt "Choose movie source [2]: " source_choice
source_choice=${source_choice:-2}
case "$source_choice" in
1) QUALITY_SOURCE="web"; break ;;
@ -121,13 +86,11 @@ configure_quality_profile() {
esac
}
# Older name — setup / config edit used this when the question was Seerr-only.
configure_seerr_profile() {
configure_quality_profile
}
configure_subtitle_language() {
# Jellyfin iso6392.txt: iso639-2/T|iso639-2/B|iso639-1|english_name|french_name
local iso639_url="https://raw.githubusercontent.com/jellyfin/jellyfin/master/Emby.Server.Implementations/Localization/iso6392.txt"
local awk_filter='$4 != "" {print $1 "\t" $4}'
@ -146,18 +109,18 @@ configure_subtitle_language() {
local data
data=$(curl -sf --connect-timeout 5 "$iso639_url" 2>/dev/null | awk -F'|' "$awk_filter" | sort -k2) || true
if [ -z "$data" ]; then
log_info "Could not load language list — leaving subtitle language unchanged."
return 0
log_info "Could not fetch full ISO-639 list online — using bundled common languages."
data=$(iso639_bundled_menu)
fi
local prompt header preselect_names=""
preselect_names=$(_subtitle_stored_lang_codes)
if ui_is_edit; then
prompt="Subtitle languages> "
header="Enter/TAB=toggle Ctrl-O=save Esc=cancel"
header="TAB=toggle Enter=save Esc=cancel"
else
prompt="Subtitle languages> "
header="Enter/TAB=toggle Ctrl-O=confirm Esc=skip"
header="TAB=toggle Enter=confirm Esc=skip"
fi
fzf_multi_select "$data" \
"$prompt" \
@ -220,120 +183,36 @@ configure_subtitle_language() {
export subtitle_language subtitle_languages
}
# OpenSubtitles.com website login accepts email or username; the REST API (and
# Bazarr) require the profile username. Consumer Api-Key is Bazarr's public key
# from upstream so we validate the same path Bazarr will use at runtime.
# Override with OPENSUBTITLES_API_KEY if needed.
_verify_opensubtitles_login() {
local user="$1"
local pass="$2"
local api_key="${OPENSUBTITLES_API_KEY:-s38zmzVlW7IlYruWi7mHwDYl2SfMQoC1}"
local ua="${OPENSUBTITLES_USER_AGENT:-assemblrr/1.0}"
local tmp http_code body
local attempt
tmp=$(mktemp)
for attempt in 1 2 3; do
http_code=$(curl -sS -o "$tmp" -w "%{http_code}" --connect-timeout 10 --max-time 30 \
-X POST "https://api.opensubtitles.com/api/v1/login" \
-H "Content-Type: application/json" \
-H "Api-Key: ${api_key}" \
-H "User-Agent: ${ua}" \
-d "$(jq -nc --arg u "$user" --arg p "$pass" '{username:$u,password:$p}')" \
2>/dev/null || echo "000")
body=$(cat "$tmp" 2>/dev/null || true)
case "$http_code" in
200)
if echo "$body" | jq -e '.token // empty' >/dev/null 2>&1; then
rm -f "$tmp"
return 0
fi
rm -f "$tmp"
return 1
;;
429)
log_warning "OpenSubtitles rate limit — retrying (${attempt}/3)..."
sleep $((attempt + 1))
continue
;;
000)
log_warning "OpenSubtitles: network error (could not reach API)"
rm -f "$tmp"
return 2
;;
*)
# Prefer API message when present
local msg
msg=$(echo "$body" | jq -r '.message // empty' 2>/dev/null || true)
if [ -n "$msg" ]; then
log_warning "OpenSubtitles: $msg"
else
log_warning "OpenSubtitles: login failed (HTTP ${http_code})"
fi
rm -f "$tmp"
return 1
;;
esac
done
rm -f "$tmp"
return 1
}
# Collect verified OpenSubtitles.com username/password into the usual globals.
# $1 = cancel_on_empty_user (1 for config edit, 0 for setup).
# Returns 0 on verified login, 1 on cancel/skip.
_opensubtitles_ask_and_verify() {
# Collect OpenSubtitles.com username/password cleanly (Bazarr validates them directly).
_opensubtitles_collect() {
local cancel_on_empty="${1:-0}"
local retry=""
opensubtitles_username=""
opensubtitles_password=""
while true; do
opensubtitles_username=""
opensubtitles_password=""
while [ -z "$opensubtitles_username" ]; do
read_prompt "OpenSubtitles.com username (profile name, not email): " opensubtitles_username
if [ -z "$opensubtitles_username" ]; then
if [ "$cancel_on_empty" = "1" ]; then
return 1
fi
log_warning "Username cannot be empty."
continue
while [ -z "$opensubtitles_username" ]; do
read_prompt "OpenSubtitles.com username (profile name, not email; blank to cancel): " opensubtitles_username
if [ -z "$opensubtitles_username" ]; then
if [ "$cancel_on_empty" = "1" ]; then
return 1
fi
if [[ "$opensubtitles_username" == *@* ]]; then
log_warning "That looks like an email. OpenSubtitles API rejects email logins."
log_warning "Use your profile username (website login may accept email; Bazarr does not)."
opensubtitles_username=""
fi
done
while [ -z "$opensubtitles_password" ]; do
if [ -r /dev/tty ]; then
read_masked "OpenSubtitles.com password: " opensubtitles_password </dev/tty
else
read_masked "OpenSubtitles.com password: " opensubtitles_password
fi
if [ -z "$opensubtitles_password" ]; then
log_warning "Password cannot be empty."
fi
done
log_info "Verifying OpenSubtitles.com login..."
if _verify_opensubtitles_login "$opensubtitles_username" "$opensubtitles_password"; then
log_success "OpenSubtitles.com: login OK — credentials will be stored under secrets/"
return 0
fi
read_prompt "Try again? (Y/n) [Default = y]: " retry
retry=${retry:-y}
if [ "${retry,,}" != "y" ]; then
return 1
fi
if [[ "$opensubtitles_username" == *@* ]]; then
log_warning "That looks like an email. Bazarr / OpenSubtitles API require your profile username."
opensubtitles_username=""
fi
done
while [ -z "$opensubtitles_password" ]; do
read_masked "OpenSubtitles.com password: " opensubtitles_password
if [ -z "$opensubtitles_password" ]; then
log_warning "Password cannot be empty."
fi
done
log_success "OpenSubtitles.com credentials collected (Bazarr will store and validate them)."
return 0
}
# Optional OpenSubtitles.com account for Bazarr (free registration).
# Setup: y/N first (optional). Config edit: user already picked this section,
# so go straight to username/password. Empty username cancels with no change.
configure_opensubtitles() {
opensubtitles_enabled="n"
opensubtitles_username=""
@ -341,7 +220,7 @@ configure_opensubtitles() {
if ui_is_edit; then
echo
if _opensubtitles_ask_and_verify 1; then
if _opensubtitles_collect 1; then
opensubtitles_enabled="y"
else
opensubtitles_enabled="n"
@ -355,8 +234,7 @@ configure_opensubtitles() {
ui_intro \
"Optional: OpenSubtitles.com credentials for Bazarr (https://www.opensubtitles.com/)." \
"Update OpenSubtitles.com credentials for Bazarr."
log_info "The website login accepts email or username; Bazarr/API require your profile username."
log_info "Find it under your OpenSubtitles profile (not the signup email)."
log_info "The website login accepts email or username; Bazarr requires your profile username."
ui_note \
"Other subtitle providers can be configured later with: ${APP_CLI_NAME:-assemblrr} config edit" \
""
@ -370,44 +248,203 @@ configure_opensubtitles() {
return 0
fi
if _opensubtitles_ask_and_verify 0; then
if _opensubtitles_collect 0; then
opensubtitles_enabled="y"
else
opensubtitles_enabled="n"
opensubtitles_username=""
opensubtitles_password=""
log_warning "OpenSubtitles.com: skipped (credentials not verified)"
log_info "OpenSubtitles.com: skipped"
fi
export opensubtitles_enabled opensubtitles_username opensubtitles_password
}
configure_vuetorrent() {
vuetorrent_enabled="y"
if [ "${SETUP_MODE:-}" = "express" ]; then
export vuetorrent_enabled
return 0
fi
ui_intro \
"Optional: VueTorrent gives qBittorrent a modern responsive WebUI theme." \
"Enable or disable VueTorrent theme on qBittorrent (restarts stack)."
local ans="y"
read_prompt "Enable VueTorrent WebUI theme for qBittorrent? (Y/n) [Default = y]: " ans
ans=${ans:-y}
[ "${ans,,}" = "n" ] && vuetorrent_enabled="n" || vuetorrent_enabled="y"
log_success "VueTorrent: $vuetorrent_enabled"
export vuetorrent_enabled
}
# Detect host GPU acceleration safely: NVIDIA only if Docker runtime exists, else /dev/dri vendor.
detect_gpu_transcoding() {
if command -v nvidia-smi >/dev/null 2>&1; then
if docker info --format '{{json .Runtimes}}' 2>/dev/null | grep -qi '"nvidia"' || \
docker info 2>/dev/null | grep -qiE 'Runtimes:.*nvidia'; then
echo "nvidia"
return 0
fi
fi
local dev node vendor=""
for dev in /dev/dri/renderD*; do
[ -c "$dev" ] || continue
node=$(basename "$dev")
if [ -r "/sys/class/drm/${node}/device/vendor" ]; then
vendor=$(cat "/sys/class/drm/${node}/device/vendor" 2>/dev/null || echo "")
fi
case "$vendor" in
0x1002) echo "amd"; return 0 ;;
0x8086) echo "intel"; return 0 ;;
*) echo "vaapi"; return 0 ;;
esac
done
echo "none"
}
configure_gpu_transcoding() {
gpu_transcoding=$(detect_gpu_transcoding)
if [ "${SETUP_MODE:-}" = "express" ]; then
export gpu_transcoding
return 0
fi
local has_nvidia_smi=0
command -v nvidia-smi >/dev/null 2>&1 && has_nvidia_smi=1
local hinted="1" amd_note="" intel_note="" nv_note=""
case "$gpu_transcoding" in
amd) hinted="2"; amd_note=" [detected]" ;;
vaapi) hinted="2"; amd_note=" [detected]" ;;
intel) hinted="3"; intel_note=" [detected]" ;;
nvidia) hinted="4"; nv_note=" [detected]" ;;
*)
if [ "$has_nvidia_smi" -eq 1 ]; then
nv_note=" [nvidia-smi found, install nvidia-container-toolkit first]"
fi
;;
esac
ui_intro \
"Optional: hardware GPU transcoding passthrough and Jellyfin auto-configuration." \
"Select hardware GPU transcoding mode for Jellyfin (restarts stack & configures Jellyfin)."
echo " 1) None (CPU software transcoding)"
echo " 2) AMD (VAAPI via /dev/dri)${amd_note}"
echo " 3) Intel (QSV via /dev/dri)${intel_note}"
echo " 4) NVIDIA (NVENC via nvidia-container-toolkit)${nv_note}"
local choice
while true; do
read_prompt "Choose GPU transcoding mode [${hinted}]: " choice
choice=${choice:-$hinted}
case "${choice,,}" in
1|none) gpu_transcoding="none"; break ;;
2|amd|vaapi) gpu_transcoding="amd"; break ;;
3|intel|qsv) gpu_transcoding="intel"; break ;;
4|nvidia) gpu_transcoding="nvidia"; break ;;
*) log_warning "Invalid choice. Choose 1, 2, 3, or 4." ;;
esac
done
log_success "GPU transcoding: $gpu_transcoding"
export gpu_transcoding
}
configure_byparr() {
byparr_enabled="n"
if [ "${SETUP_MODE:-}" = "express" ]; then
export byparr_enabled
return 0
fi
ui_intro \
"Optional: Byparr solves Cloudflare challenges for Prowlarr indexers (FlareSolverr drop-in)." \
"Enable or disable Byparr Cloudflare solver in Prowlarr (restarts stack)."
local ans="n"
read_prompt "Enable Byparr challenge solver container? (y/N) [Default = n]: " ans
ans=${ans:-n}
[ "${ans,,}" = "y" ] && byparr_enabled="y" || byparr_enabled="n"
log_success "Byparr: $byparr_enabled"
export byparr_enabled
}
configure_usenet() {
usenet_enabled="n"
usenet_host=""
usenet_port="563"
usenet_ssl="y"
usenet_username=""
usenet_password=""
usenet_connections="8"
if [ "${SETUP_MODE:-}" = "express" ]; then
export usenet_enabled usenet_host usenet_port usenet_ssl usenet_username usenet_password usenet_connections
return 0
fi
ui_intro \
"Optional: SABnzbd Usenet downloader (wired automatically into Sonarr/Radarr/Prowlarr)." \
"Enable or configure SABnzbd Usenet downloader and NNTP provider (restarts stack)."
log_info "Note: real Usenet downloads require your own NNTP provider account (no subscription is bundled)."
local ans="n"
read_prompt "Enable SABnzbd Usenet downloader? (y/N) [Default = n]: " ans
ans=${ans:-n}
if [ "${ans,,}" != "y" ]; then
usenet_enabled="n"
log_success "SABnzbd / Usenet: disabled"
export usenet_enabled usenet_host usenet_port usenet_ssl usenet_username usenet_password usenet_connections
return 0
fi
usenet_enabled="y"
local add_nntp="n"
read_prompt "Configure an NNTP server now? (y/N, or 'n' to add in SABnzbd UI later): " add_nntp
add_nntp=${add_nntp:-n}
if [ "${add_nntp,,}" = "y" ]; then
read_prompt "NNTP host (e.g. news.provider.example): " usenet_host
read_prompt "NNTP port [563]: " usenet_port
usenet_port=${usenet_port:-563}
read_prompt "Use SSL/TLS? (Y/n) [Default = y]: " usenet_ssl
usenet_ssl=${usenet_ssl:-y}
read_prompt "NNTP username: " usenet_username
read_masked "NNTP password: " usenet_password
read_prompt "Max connections [8]: " usenet_connections
usenet_connections=${usenet_connections:-8}
fi
log_success "SABnzbd / Usenet: enabled"
export usenet_enabled usenet_host usenet_port usenet_ssl usenet_username usenet_password usenet_connections
}
configure_vpn() {
ui_intro \
"Time to set up the VPN." \
"Change VPN settings. This restarts the stack and can interrupt downloads."
log_info "Supported VPN providers: https://github.com/qdm12/gluetun-wiki"
read -p "Configure VPN? (Y/n) [Default = y]: " setup_vpn
setup_vpn=${setup_vpn:-"y"}
while true; do
read_prompt "Configure VPN? (Y/n) [Default = y]: " setup_vpn
setup_vpn=${setup_vpn:-"y"}
case "${setup_vpn,,}" in
y|yes) setup_vpn="y"; break ;;
n|no)
export setup_vpn="n"
export vpn_service=""
export vpn_type="openvpn"
export wireguard_addresses=""
export enable_port_forwarding="n"
return 0
;;
*) log_warning "Please answer y or n." ;;
esac
done
if [ "${setup_vpn,,}" != "y" ]; then
export setup_vpn="n"
export vpn_service=""
export vpn_type="openvpn"
export enable_port_forwarding="n"
return 0
fi
# Supported VPN providers (from Gluetun)
local -a vpn_providers=(
"protonvpn"
"surfshark"
"mullvad"
"nordvpn"
"expressvpn"
"pia"
"private internet access"
"windscribe"
"ivyvpn"
"ivpn"
"custom"
)
@ -418,38 +455,36 @@ configure_vpn() {
echo " 5) ExpressVPN"
echo " 6) Private Internet Access"
echo " 7) Windscribe"
echo " 8) IvyVPN"
echo " 8) IVPN"
echo " 9) Custom (manual configuration)"
read -p "Choose your VPN provider [1]: " vpn_choice
vpn_choice=${vpn_choice:-1}
if [[ "$vpn_choice" =~ ^[0-9]+$ ]] && [ "$vpn_choice" -ge 1 ] && [ "$vpn_choice" -le ${#vpn_providers[@]} ]; then
vpn_service="${vpn_providers[$((vpn_choice-1))]}"
else
vpn_service="$vpn_choice"
fi
local vpn_choice vpn_type_choice
while true; do
read_prompt "Choose your VPN provider [1]: " vpn_choice
vpn_choice=${vpn_choice:-1}
if [[ "$vpn_choice" =~ ^[0-9]+$ ]]; then
if [ "$vpn_choice" -ge 1 ] && [ "$vpn_choice" -le ${#vpn_providers[@]} ]; then
vpn_service="${vpn_providers[$((vpn_choice-1))]}"
break
fi
log_warning "Please choose a number from 1 to ${#vpn_providers[@]} (or type a Gluetun provider slug)."
else
vpn_service="${vpn_choice,,}"
break
fi
done
echo
echo " 1) WireGuard (recommended)"
echo " 2) OpenVPN"
read -p "Choose VPN type [1]: " vpn_type_choice
vpn_type_choice=${vpn_type_choice:-1}
while true; do
read_prompt "Choose VPN type [1]: " vpn_type_choice
vpn_type_choice=${vpn_type_choice:-1}
case "$vpn_type_choice" in
1) vpn_type="wireguard"; break ;;
2) vpn_type="openvpn"; break ;;
*) vpn_type="$vpn_type_choice" ;;
1|wireguard) vpn_type="wireguard"; break ;;
2|openvpn) vpn_type="openvpn"; break ;;
*) log_warning "Unsupported VPN type. Please choose 1 or 2." ;;
esac
if [[ "$vpn_type" != "openvpn" && "$vpn_type" != "wireguard" ]]; then
log_warning "Unsupported VPN type. Please choose 1 or 2."
read -p "Choose VPN type [1]: " vpn_type_choice
vpn_type_choice=${vpn_type_choice:-1}
else
break
fi
done
echo
@ -458,17 +493,18 @@ configure_vpn() {
prompt_vpn_credentials
# Port forwarding — we do not maintain a provider allowlist (lists go stale).
log_info "Port forwarding only helps if your provider supports it (and Gluetun can use it)."
log_info "If they do not, leave this off — turning it on can limit which servers Gluetun picks."
read -p "Enable port forwarding? (y/N) [Default = n]: " enable_port_forwarding
read_prompt "Enable port forwarding? (y/N) [Default = n]: " enable_port_forwarding
enable_port_forwarding=${enable_port_forwarding:-"n"}
case "${enable_port_forwarding,,}" in
y|yes) enable_port_forwarding="y" ;;
*) enable_port_forwarding="n" ;;
esac
export setup_vpn vpn_service vpn_type enable_port_forwarding
export vpn_user vpn_password wireguard_private_key wireguard_addresses
}
# Prompt only for credentials (uses existing vpn_type). Safe to call again on VPN test failure.
prompt_vpn_credentials() {
if [ "${vpn_type:-}" = "wireguard" ]; then
wireguard_private_key=""
@ -478,7 +514,7 @@ prompt_vpn_credentials() {
done
wireguard_addresses=""
while [ -z "$wireguard_addresses" ]; do
read_masked "WireGuard interface addresses (e.g., 10.64.0.1/32): " wireguard_addresses
read_prompt "WireGuard interface addresses (e.g., 10.64.0.1/32): " wireguard_addresses
[ -z "$wireguard_addresses" ] && log_warning "Addresses cannot be empty. Try again."
done
vpn_user=""
@ -486,7 +522,7 @@ prompt_vpn_credentials() {
else
vpn_user=""
while [ -z "$vpn_user" ]; do
read -p "VPN username (without spaces): " vpn_user
read_prompt "VPN username (without spaces): " vpn_user
[ -z "$vpn_user" ] && log_warning "Username cannot be empty. Try again."
done
vpn_password=""
@ -515,13 +551,13 @@ configure_auth() {
"Set one username and password for every service web UI." \
"Change the shared login on every service UI."
ui_note \
"Same login on Radarr, Sonarr, Prowlarr, qBittorrent, Jellyfin, and Bazarr. Seerr signs in with the Jellyfin (or Emby) user." \
"Updates Radarr, Sonarr, Prowlarr, qBittorrent, Jellyfin, and Bazarr. Seerr signs in with the Jellyfin (or Emby) user."
"Same login on Radarr, Sonarr, Prowlarr, qBittorrent, Jellyfin, Bazarr, and SABnzbd (when enabled). Seerr signs in via Jellyfin." \
"Updates Radarr, Sonarr, Prowlarr, qBittorrent, Jellyfin, Bazarr, and SABnzbd (when enabled). Seerr signs in via Jellyfin."
echo
auth_username=""
while [ -z "$auth_username" ]; do
read -p "Username for service login? [$USER]: " auth_username
read_prompt "Username for service login? [$USER]: " auth_username
auth_username=${auth_username:-$USER}
[ -z "$auth_username" ] && log_warning "Username cannot be empty. Try again."
done
@ -549,7 +585,6 @@ configure_timezone() {
detected_tz=$(cat /etc/timezone 2>/dev/null || timedatectl show -p Timezone -v 2>/dev/null | tail -1 || echo "UTC")
detected_tz=${detected_tz:-"UTC"}
# Express mode: auto-detect timezone
if [ "${SETUP_MODE:-}" = "express" ]; then
tz="$detected_tz"
log_success "Timezone: $tz (auto-detected)"
@ -557,14 +592,22 @@ configure_timezone() {
return 0
fi
read -p "Timezone? [$detected_tz]: " tz
tz=${tz:-$detected_tz}
while true; do
read_prompt "Timezone? [$detected_tz]: " tz
tz=${tz:-$detected_tz}
if [ -d /usr/share/zoneinfo ] && [ ! -f "/usr/share/zoneinfo/${tz}" ]; then
log_warning "Timezone '$tz' not found under /usr/share/zoneinfo (example: Europe/Athens, America/New_York, UTC)."
local keep="n"
read_prompt "Keep '$tz' anyway? (y/N) [Default = n]: " keep
[ "${keep,,}" = "y" ] && break
continue
fi
break
done
export tz
}
# running_services_location lives in lib/services.sh (sourced by setup via core path
# or explicitly). Keep a thin wrapper if services.sh not loaded yet.
if ! type running_services_location >/dev/null 2>&1; then
running_services_location() {
if [ -f "${_lib_dir:-}/services.sh" ]; then
@ -578,7 +621,6 @@ if ! type running_services_location >/dev/null 2>&1; then
fi
get_user_info() {
# Express mode: use current user
if [ "${SETUP_MODE:-}" = "express" ]; then
username="$USER"
puid=$(id -u "$username")
@ -589,7 +631,7 @@ get_user_info() {
fi
while true; do
read -p "User to own the media server files? [$USER]: " username
read_prompt "User to own the media server files? [$USER]: " username
username=${username:-$USER}
if id -u "$username" &>/dev/null; then
@ -623,8 +665,10 @@ _probe_selected_storage() {
return 0
}
# Setup is first-time only. A complete tree means use the CLI, not bootstrap again.
refuse_setup_if_already_installed() {
if [ "${ASSEMBLRR_RECONFIGURE:-0}" = "1" ]; then
return 0
fi
poke_wsl_automounts 2>/dev/null || true
local existing=""
existing=$(find_install_directory 2>/dev/null || true)
@ -654,24 +698,61 @@ refuse_setup_if_already_installed() {
exit 1
}
# Incomplete trees from an aborted setup. Offer to delete them before we start.
# Stop containers created by an aborted setup before removing the leftover directory.
_cleanup_leftover_compose() {
local path="$1"
command -v docker >/dev/null 2>&1 || return 0
[ -f "$path/compose/base.yaml" ] || return 0
local vpn_enabled="n" cfg=""
if [ -f "$path/.assemblrr-config" ]; then
cfg="$path/.assemblrr-config"
elif [ -f "$path/.${APP_NAME:-assemblrr}-config" ]; then
cfg="$path/.${APP_NAME:-assemblrr}-config"
elif [ -f "$path/.env" ]; then
cfg="$path/.env"
fi
if [ -n "$cfg" ]; then
vpn_enabled=$(_pointer_get "$cfg" "VPN_ENABLED")
fi
local -a cargs=(--project-directory "$path" -f "$path/compose/base.yaml")
if [ "${vpn_enabled,,}" = "y" ] && [ -f "$path/compose/vpn.yaml" ]; then
cargs+=(-f "$path/compose/vpn.yaml")
elif [ -f "$path/compose/direct-access.yaml" ]; then
cargs+=(-f "$path/compose/direct-access.yaml")
fi
[ -f "$path/.env" ] && cargs+=(--env-file "$path/.env")
docker compose "${cargs[@]}" down --remove-orphans >/dev/null 2>&1 || true
}
offer_leftover_cleanup() {
poke_wsl_automounts 2>/dev/null || true
local leftover kind path ans
leftover=$(list_assemblrr_leftovers || true)
[ -n "$leftover" ] || return 0
local has_install=false
local has_media=false
if echo "$leftover" | grep -q $'^install\t'; then
has_install=true
fi
if echo "$leftover" | grep -q $'^media\t'; then
has_media=true
fi
local has_install=false has_media=false has_incomplete=false removed_install=false
while IFS=$'\t' read -r kind path; do
[ -n "$path" ] || continue
case "$kind" in
install)
has_install=true
[ -f "$path/.assemblrr-setup-in-progress" ] && has_incomplete=true
;;
media)
has_media=true
;;
esac
done <<< "$leftover"
echo
log_warning "Found leftover ${APP_DISPLAY_NAME:-assemblrr} files from an earlier attempt:"
if [ "$has_incomplete" = true ]; then
log_warning "Found an incomplete ${APP_DISPLAY_NAME:-assemblrr} setup from an earlier attempt:"
else
log_warning "Found leftover ${APP_DISPLAY_NAME:-assemblrr} files from an earlier attempt:"
fi
while IFS=$'\t' read -r kind path; do
[ -n "$path" ] || continue
case "$kind" in
@ -686,11 +767,15 @@ offer_leftover_cleanup() {
if [ "$has_media" = true ]; then
prompt_msg="Remove leftover install files (keeps media)? (Y/n) [Default = y]: "
fi
read -p "$prompt_msg" ans
read_prompt "$prompt_msg" ans
ans=${ans:-y}
if [ "${ans,,}" = "y" ]; then
removed_install=true
while IFS=$'\t' read -r kind path; do
[ "$kind" = "install" ] && [ -n "$path" ] && safe_rm_rf "$path"
if [ "$kind" = "install" ] && [ -n "$path" ]; then
_cleanup_leftover_compose "$path"
safe_rm_rf "$path"
fi
done <<< "$leftover"
fi
fi
@ -701,7 +786,7 @@ offer_leftover_cleanup() {
if [ "$has_install" = true ]; then
prompt_media="Also remove leftover media directories? (y/N) [Default = n]: "
fi
read -p "$prompt_media" ans
read_prompt "$prompt_media" ans
ans=${ans:-n}
if [ "${ans,,}" = "y" ]; then
while IFS=$'\t' read -r kind path; do
@ -709,11 +794,26 @@ offer_leftover_cleanup() {
done <<< "$leftover"
fi
fi
if [ "$removed_install" = true ]; then
local ptr ptr_inst removed_ptr=false
for ptr in "$HOME/.assemblrr-config" "$HOME/.${APP_NAME:-assemblrr}-config"; do
[ -f "$ptr" ] || continue
ptr_inst=$(_pointer_get "$ptr" "INSTALL_DIRECTORY")
if [ -n "$ptr_inst" ] && [ ! -d "$ptr_inst" ]; then
rm -f "$ptr"
removed_ptr=true
fi
done
if [ "$removed_ptr" = true ]; then
rm -f "$HOME/.local/bin/${APP_CLI_NAME:-assemblrr}" 2>/dev/null || true
fi
fi
}
get_installation_paths() {
ui_intro \
"Where should assemblrr store config and media? External drives (WSL E:, USB, …) show up in the list." \
"Where should assemblrr store config and media? External drives (WSL E:, USB, ...) show up in the list." \
"Change install and media directories. This does not move existing files."
while true; do
@ -725,16 +825,18 @@ get_installation_paths() {
continue
fi
# Record both paths before any copy so uninstall can find an external
# drive even if setup dies mid-copy.
write_install_pointer "$install_directory" "$media_directory"
# VPN gate bootstraps ~/assemblrr first. If the user then picked another
# install path, drop that leftover tree so CLI discovery cannot shadow it.
if [ -n "${_ASSEMBLRR_PROVISIONAL_INSTALL:-}" ] && \
[ "$install_directory" != "$_ASSEMBLRR_PROVISIONAL_INSTALL" ] && \
[ -d "$_ASSEMBLRR_PROVISIONAL_INSTALL" ]; then
log_info "Install path changed — removing temporary files at $_ASSEMBLRR_PROVISIONAL_INSTALL"
log_info "Install path changed — stopping temporary containers and removing $_ASSEMBLRR_PROVISIONAL_INSTALL"
if command -v docker >/dev/null 2>&1 && [ -f "$_ASSEMBLRR_PROVISIONAL_INSTALL/compose/base.yaml" ]; then
docker compose --project-directory "$_ASSEMBLRR_PROVISIONAL_INSTALL" \
-f "$_ASSEMBLRR_PROVISIONAL_INSTALL/compose/base.yaml" \
-f "$_ASSEMBLRR_PROVISIONAL_INSTALL/compose/vpn.yaml" \
down --remove-orphans >/dev/null 2>&1 || true
fi
safe_rm_rf "$_ASSEMBLRR_PROVISIONAL_INSTALL"
fi

471
lib/prowlarr.sh Executable file
View file

@ -0,0 +1,471 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Prowlarr wiring, indexer sync, Gluetun HTTP proxy, and Byparr solver
# Requires: lib/core.sh, lib/api.sh, lib/qbit.sh
if [ -n "${_ASSEMBLRR_PROWLARR_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_PROWLARR_SOURCED=1
readonly PROWLARR_GLUETUN_PROXY_NAME="assemblrr Gluetun"
readonly PROWLARR_GLUETUN_PROXY_HOST="gluetun"
readonly PROWLARR_GLUETUN_PROXY_PORT="8888"
readonly PROWLARR_BYPARR_PROXY_NAME="assemblrr Byparr"
readonly PROWLARR_BYPARR_HOST="http://byparr:8191/"
readonly PROWLARR_BYPARR_TAG="byparr"
_prowlarr_byparr_enabled() {
case "${BYPARR_ENABLED:-n}" in
y|Y|yes|YES) return 0 ;;
*) return 1 ;;
esac
}
prowlarr_set_app_profile_min_seeders() {
local prowlarr_key="$1"
local profiles
profiles=$(api_get "9696" "/api/v1/appprofile" "$prowlarr_key" || echo "")
if [ -z "$profiles" ] || [ "$profiles" = "[]" ]; then
return 1
fi
local updated=0 row profile_id profile_payload
while IFS= read -r row; do
[ -z "$row" ] && continue
profile_id=$(printf '%s' "$row" | jq -r '.id // empty')
[ -z "$profile_id" ] && continue
profile_payload=$(printf '%s' "$row" | jq '.minimumSeeders = 0' 2>/dev/null || echo "")
[ -z "$profile_payload" ] && continue
if api_put "9696" "/api/v1/appprofile/${profile_id}" "$prowlarr_key" "$profile_payload" >/dev/null 2>&1; then
updated=$((updated + 1))
fi
done < <(printf '%s' "$profiles" | jq -c '.[]' 2>/dev/null || true)
if [ "$updated" -gt 0 ]; then
log_step "Prowlarr: app profile minimumSeeders → 0"
return 0
fi
return 1
}
arr_set_indexer_min_seeders() {
local service_name="$1"
local port="$2"
local apikey="$3"
[ -z "$apikey" ] && return 1
local indexers
indexers=$(api_get "$port" "/api/v3/indexer" "$apikey" || echo "")
if [ -z "$indexers" ] || [ "$indexers" = "[]" ]; then
return 1
fi
local ok=0 idx idx_id idx_payload result
while IFS= read -r idx; do
[ -z "$idx" ] && continue
idx_id=$(printf '%s' "$idx" | jq -r '.id // empty')
[ -z "$idx_id" ] && continue
idx_payload=$(printf '%s' "$idx" | jq '
.fields = [.fields[] |
if .name == "minimumSeeders" then .value = 0
else . end
]
' 2>/dev/null || echo "")
[ -z "$idx_payload" ] && continue
result=$(api_put "$port" "/api/v3/indexer/${idx_id}" "$apikey" "$idx_payload" || echo "")
if printf '%s' "$result" | jq -e '.id' >/dev/null 2>&1; then
ok=$((ok + 1))
fi
done < <(printf '%s' "$indexers" | jq -c '.[]' 2>/dev/null || true)
if [ "$ok" -gt 0 ]; then
log_step "${service_name}: indexer minSeeders=0 (${ok})"
return 0
fi
return 1
}
_radarr_has_indexers() {
local radarr_key="$1"
local rc
rc=$(api_get "7878" "/api/v3/indexer" "$radarr_key" 2>/dev/null | jq 'length' 2>/dev/null || echo 0)
[ "${rc:-0}" -gt 0 ]
}
wait_for_arr_indexer_sync() {
local radarr_key="${1:-}"
[ -z "$radarr_key" ] && return 0
wait_until "Waiting for Radarr indexers from Prowlarr" 30 2 _radarr_has_indexers "$radarr_key"
}
_prowlarr_gluetun_proxy_id() {
local proxies="$1"
local mode="${2:-any}"
printf '%s' "$proxies" | jq -r \
--arg name "$PROWLARR_GLUETUN_PROXY_NAME" \
--arg host "$PROWLARR_GLUETUN_PROXY_HOST" \
--argjson port "$PROWLARR_GLUETUN_PROXY_PORT" \
--arg mode "$mode" '
.[] | select(
.name == $name
or (
$mode == "any"
and .implementation == "Http"
and (([.fields[]? | select(.name == "host") | .value][0] // "") | tostring) == $host
and (([.fields[]? | select(.name == "port") | .value][0] // 0) | tonumber) == $port
)
) | .id
' 2>/dev/null | head -1
}
_prowlarr_gluetun_proxy_payload() {
local schema="$1"
printf '%s' "$schema" | jq -c \
--arg name "$PROWLARR_GLUETUN_PROXY_NAME" \
--arg host "$PROWLARR_GLUETUN_PROXY_HOST" \
--argjson port "$PROWLARR_GLUETUN_PROXY_PORT" '
[.[] | select(.implementation == "Http")][0] |
.fields = [.fields[] | if .name == "host" then .value = $host
elif .name == "port" then .value = $port
elif .name == "username" then .value = ""
elif .name == "password" then .value = ""
else . end] |
.name = $name | .tags = []
' 2>/dev/null || echo ""
}
prowlarr_sync_gluetun_proxy() {
local apikey="$1"
local proxies existing_id
if [ -z "$apikey" ]; then
log_step_fail "Prowlarr: no API key — cannot send searches through the VPN"
return 1
fi
proxies=$(api_get "9696" "/api/v1/indexerProxy" "$apikey" || echo "")
if [ -z "$proxies" ]; then
log_step_fail "Prowlarr: could not list search proxies"
return 1
fi
if ! stack_vpn_enabled; then
existing_id=$(_prowlarr_gluetun_proxy_id "$proxies" "name")
[ -z "$existing_id" ] && return 0
local code
code=$(api_delete "9696" "/api/v1/indexerProxy/${existing_id}" "$apikey")
if [ "$code" = "200" ] || [ "$code" = "204" ]; then
log_step "Prowlarr: searches no longer go through the VPN"
return 0
fi
log_step_fail "Prowlarr: could not stop sending searches through the VPN (HTTP ${code:-?})"
return 1
fi
existing_id=$(_prowlarr_gluetun_proxy_id "$proxies" "any")
local schema payload result
schema=$(api_get "9696" "/api/v1/indexerProxy/schema" "$apikey" || echo "")
payload=$(_prowlarr_gluetun_proxy_payload "$schema")
if [ -z "$payload" ]; then
log_step_fail "Prowlarr: could not set up VPN search routing"
return 1
fi
if [ -n "$existing_id" ]; then
payload=$(printf '%s' "$payload" | jq -c --argjson id "$existing_id" '.id = $id' 2>/dev/null || echo "$payload")
result=$(api_put_force "9696" "/api/v1/indexerProxy/${existing_id}" "$apikey" "$payload" || echo "")
else
result=$(api_post_force "9696" "/api/v1/indexerProxy" "$apikey" "$payload" || echo "")
fi
if jq_json_has_key "$result" "id"; then
log_step "Prowlarr: searches go through the VPN"
return 0
fi
log_step_fail "Prowlarr: could not send searches through the VPN"
return 1
}
_prowlarr_ensure_tag() {
local apikey="$1"
local label="$2"
local tags tid created
tags=$(api_get "9696" "/api/v1/tag" "$apikey" || echo "[]")
tid=$(printf '%s' "$tags" | jq -r --arg l "$label" \
'[.[] | select((.label // "") | ascii_downcase == ($l | ascii_downcase))][0].id // empty' 2>/dev/null || true)
if [ -n "$tid" ]; then
echo "$tid"
return 0
fi
created=$(api_post "9696" "/api/v1/tag" "$apikey" "$(jq -nc --arg l "$label" '{label:$l}')" || echo "")
tid=$(printf '%s' "$created" | jq -r '.id // empty' 2>/dev/null || true)
[ -n "$tid" ] && echo "$tid"
}
# Sync Byparr (FlareSolverr-compatible API solver) in Prowlarr.
prowlarr_sync_byparr_proxy() {
local apikey="$1"
[ -n "$apikey" ] || return 1
local proxies existing_id
proxies=$(api_get "9696" "/api/v1/indexerProxy" "$apikey" || echo "")
[ -n "$proxies" ] || return 1
existing_id=$(printf '%s' "$proxies" | jq -r --arg name "$PROWLARR_BYPARR_PROXY_NAME" '
[.[] | select(.name == $name or .implementation == "FlareSolverr")][0].id // empty
' 2>/dev/null || true)
if ! _prowlarr_byparr_enabled; then
[ -z "$existing_id" ] && return 0
# Only delete the proxy assemblrr manages
local managed_id
managed_id=$(printf '%s' "$proxies" | jq -r --arg name "$PROWLARR_BYPARR_PROXY_NAME" \
'[.[] | select(.name == $name)][0].id // empty' 2>/dev/null || true)
[ -z "$managed_id" ] && return 0
local code
code=$(api_delete "9696" "/api/v1/indexerProxy/${managed_id}" "$apikey")
if [ "$code" = "200" ] || [ "$code" = "204" ]; then
log_step "Prowlarr: removed Byparr solver proxy"
return 0
fi
log_step_fail "Prowlarr: could not remove Byparr proxy (HTTP ${code:-?})"
return 1
fi
local tag_id schema payload result
tag_id=$(_prowlarr_ensure_tag "$apikey" "$PROWLARR_BYPARR_TAG" || true)
schema=$(api_get "9696" "/api/v1/indexerProxy/schema" "$apikey" || echo "")
if [ -n "$tag_id" ]; then
payload=$(printf '%s' "$schema" | jq -c \
--arg name "$PROWLARR_BYPARR_PROXY_NAME" \
--arg host "$PROWLARR_BYPARR_HOST" \
--argjson tid "$tag_id" '
[.[] | select(.implementation == "FlareSolverr")][0] |
.fields = [.fields[] |
if .name == "host" then .value = $host
elif .name == "requestTimeout" then .value = 60
else . end
] |
.name = $name | .tags = [$tid]
' 2>/dev/null || echo "")
else
payload=$(printf '%s' "$schema" | jq -c \
--arg name "$PROWLARR_BYPARR_PROXY_NAME" \
--arg host "$PROWLARR_BYPARR_HOST" '
[.[] | select(.implementation == "FlareSolverr")][0] |
.fields = [.fields[] |
if .name == "host" then .value = $host
elif .name == "requestTimeout" then .value = 60
else . end
] |
.name = $name | .tags = []
' 2>/dev/null || echo "")
fi
if [ -z "$payload" ]; then
log_step_fail "Prowlarr: FlareSolverr/Byparr proxy schema not found"
return 1
fi
if [ -n "$existing_id" ]; then
payload=$(printf '%s' "$payload" | jq -c --argjson id "$existing_id" '.id = $id' 2>/dev/null || echo "$payload")
result=$(api_put_force "9696" "/api/v1/indexerProxy/${existing_id}" "$apikey" "$payload" || echo "")
else
result=$(api_post_force "9696" "/api/v1/indexerProxy" "$apikey" "$payload" || echo "")
fi
if jq_json_has_key "$result" "id"; then
log_step "Prowlarr: Byparr Cloudflare solver wired (${PROWLARR_BYPARR_HOST}, tag: ${PROWLARR_BYPARR_TAG})"
return 0
fi
log_step_fail "Prowlarr: failed to wire Byparr proxy"
return 1
}
apply_selected_indexers() {
local apikey="$1"
local indexer_schemas
indexer_schemas=$(api_get "9696" "/api/v1/indexer/schema" "$apikey" || echo "")
if [ -z "$indexer_schemas" ]; then
log_step_fail "Prowlarr: failed to fetch indexer schemas"
return 1
fi
local selected_indexers=()
if [ -n "${SELECTED_INDEXERS+x}" ] && [ "${#SELECTED_INDEXERS[@]}" -gt 0 ]; then
selected_indexers=("${SELECTED_INDEXERS[@]}")
echo "Applying ${#selected_indexers[@]} selected Prowlarr indexer(s)" >&2
fi
local existing_indexers existing_names indexer_name
existing_indexers=$(api_get "9696" "/api/v1/indexer" "$apikey" || echo "[]")
existing_names=$(jq_json_list_values "$existing_indexers" "name")
for indexer_name in "${selected_indexers[@]+"${selected_indexers[@]}"}"; do
if printf '%s\n' "$existing_names" | grep -q -F -x "$indexer_name"; then
log_step "Prowlarr: ${indexer_name} indexer already exists"
continue
fi
# Prefer exact case-insensitive match before falling back to prefix match.
local indexer_payload
indexer_payload=$(printf '%s' "$indexer_schemas" | jq --arg idx "$indexer_name" '
(
[.[] | select((.name | ascii_downcase) == ($idx | ascii_downcase))][0]
// [.[] | select(.name | ascii_downcase | startswith($idx | ascii_downcase))][0]
) |
.fields = [.fields[] | select(.value != "") | {name: .name, value: .value}] |
.enable = true | .enableAutoSearch = true | .appProfileId = 1 | .priority = (.priority // 25)
' 2>/dev/null || echo "")
if [ -z "$indexer_payload" ]; then
log_step_fail "Prowlarr: ${indexer_name} schema not found"
continue
fi
local idx_result
idx_result=$(api_post_force "9696" "/api/v1/indexer" "$apikey" "$indexer_payload" || echo "")
if jq_json_has_key "$idx_result" "id"; then
log_step "Prowlarr: added ${indexer_name} indexer"
else
local err_msg disabled_payload
err_msg=$(printf '%s' "$idx_result" | jq -r 'if type == "array" then .[0].errorMessage // empty else .errorMessage // empty end' 2>/dev/null || echo "")
disabled_payload=$(printf '%s' "$indexer_payload" | jq -c '.enable = false' 2>/dev/null || echo "")
idx_result=$(api_post_force "9696" "/api/v1/indexer" "$apikey" "$disabled_payload" || echo "")
if jq_json_has_key "$idx_result" "id"; then
log_step "Prowlarr: added ${indexer_name} indexer, but could not enable it"
[ -n "$err_msg" ] && log_step "Prowlarr: ${err_msg}"
else
log_step_fail "Prowlarr: failed to add ${indexer_name} indexer"
fi
fi
done
if [ "${#selected_indexers[@]}" -gt 0 ]; then
echo >&2
log_success "Prowlarr indexer configuration finished (check markers above for any failures)" >&2
fi
return 0
}
sync_selected_indexers() {
local apikey="$1"
apply_selected_indexers "$apikey" || return 1
local existing_indexers
existing_indexers=$(api_get "9696" "/api/v1/indexer" "$apikey" || echo "[]")
if [ -z "$existing_indexers" ] || [ "$existing_indexers" = "[]" ]; then
return 0
fi
local id name
while IFS=$'\t' read -r id name; do
[ -n "$id" ] && [ -n "$name" ] || continue
if printf '%s\n' "${SELECTED_INDEXERS[@]+"${SELECTED_INDEXERS[@]}"}" | grep -q -F -x "$name"; then
continue
fi
local code
code=$(api_delete "9696" "/api/v1/indexer/${id}" "$apikey")
if [ "$code" = "200" ] || [ "$code" = "204" ]; then
log_step "Prowlarr: removed ${name} indexer"
else
log_step_fail "Prowlarr: failed to remove ${name} indexer (HTTP ${code:-?})"
fi
done < <(printf '%s' "$existing_indexers" | jq -r '.[] | "\(.id)\t\(.name)"' 2>/dev/null)
return 0
}
configure_prowlarr() {
local apikey="$1"
local radarr_apikey="$2"
local sonarr_apikey="${3:-}"
local critical_errors=0
# 1. App profile min seeders (best-effort)
prowlarr_set_app_profile_min_seeders "$apikey" || true
# 2. Add Radarr and Sonarr as connected applications
local apps existing_impls app_schema=""
apps=$(api_get "9696" "/api/v1/applications" "$apikey" || echo "[]")
existing_impls=$(jq_json_list_values "$apps" "implementationName")
if ! printf '%s\n' "$existing_impls" | grep -Fxq "Radarr"; then
if [ -z "$radarr_apikey" ]; then
log_step_fail "Prowlarr: Radarr API key missing — cannot connect application"
critical_errors=$((critical_errors + 1))
else
app_schema=$(api_get "9696" "/api/v1/applications/schema" "$apikey" || echo "[]")
local app_payload app_result
app_payload=$(printf '%s' "$app_schema" | jq --arg prowlarr_url "$PROWLARR_DOCKER_URL" --arg radarr_url "$RADARR_DOCKER_URL" --arg radarr_key "$radarr_apikey" '
[.[] | select(.implementationName == "Radarr")][0] |
.fields = [.fields[] | if .name == "prowlarrUrl" then .value = $prowlarr_url elif .name == "baseUrl" then .value = $radarr_url elif .name == "apiKey" then .value = $radarr_key elif .name == "syncCategories" then .value = [2000] elif .name == "syncRejectBlocklistedTorrentHashesWhileGrabbing" then .value = false else . end] |
.enable = true | .syncLevel = "fullSync" | .name = "Radarr" | .priority = (.priority // 25) | .tags = []
' 2>/dev/null || echo "")
if [ -z "$app_payload" ]; then
log_step_fail "Prowlarr: Radarr application schema not found"
critical_errors=$((critical_errors + 1))
else
app_result=$(api_post_force "9696" "/api/v1/applications" "$apikey" "$app_payload" || echo "")
if jq_json_has_key "$app_result" "id"; then
log_step "Prowlarr: added Radarr as connected application"
else
log_step_fail "Prowlarr: failed to add Radarr application"
critical_errors=$((critical_errors + 1))
fi
fi
fi
else
log_step "Prowlarr: Radarr application already connected"
fi
if [ -n "$sonarr_apikey" ]; then
if ! printf '%s\n' "$existing_impls" | grep -Fxq "Sonarr"; then
[ -z "$app_schema" ] && app_schema=$(api_get "9696" "/api/v1/applications/schema" "$apikey" || echo "[]")
local sonarr_app_payload sonarr_app_result
sonarr_app_payload=$(printf '%s' "$app_schema" | jq --arg prowlarr_url "$PROWLARR_DOCKER_URL" --arg sonarr_url "$SONARR_DOCKER_URL" --arg sonarr_key "$sonarr_apikey" '
[.[] | select(.implementationName == "Sonarr")][0] |
.fields = [.fields[] | if .name == "prowlarrUrl" then .value = $prowlarr_url elif .name == "baseUrl" then .value = $sonarr_url elif .name == "apiKey" then .value = $sonarr_key elif .name == "syncCategories" then .value = [5000, 5010, 5020, 5030, 5040, 5045, 5050, 5090] elif .name == "animeSyncCategories" then .value = [5070] elif .name == "syncRejectBlocklistedTorrentHashesWhileGrabbing" then .value = false else . end] |
.enable = true | .syncLevel = "fullSync" | .name = "Sonarr" | .priority = (.priority // 25) | .tags = []
' 2>/dev/null || echo "")
if [ -z "$sonarr_app_payload" ]; then
log_step_fail "Prowlarr: Sonarr application schema not found"
critical_errors=$((critical_errors + 1))
else
sonarr_app_result=$(api_post_force "9696" "/api/v1/applications" "$apikey" "$sonarr_app_payload" || echo "")
if jq_json_has_key "$sonarr_app_result" "id"; then
log_step "Prowlarr: added Sonarr as connected application"
else
log_step_fail "Prowlarr: failed to add Sonarr application"
critical_errors=$((critical_errors + 1))
fi
fi
else
log_step "Prowlarr: Sonarr application already connected"
fi
fi
# 3. Search proxy via Gluetun when VPN is on
if ! prowlarr_sync_gluetun_proxy "$apikey"; then
critical_errors=$((critical_errors + 1))
fi
# 4. Byparr solver proxy (best-effort optional feature)
prowlarr_sync_byparr_proxy "$apikey" || true
# 5. Selected indexers + minSeeders sync
apply_selected_indexers "$apikey"
wait_for_arr_indexer_sync "$radarr_apikey" || true
arr_set_indexer_min_seeders "Radarr" "7878" "$radarr_apikey" || true
arr_set_indexer_min_seeders "Sonarr" "8989" "$sonarr_apikey" || true
# 6. Forms authentication
if ! set_arr_auth "Prowlarr" "9696" "$apikey" "v1"; then
critical_errors=$((critical_errors + 1))
fi
[ "$critical_errors" -eq 0 ]
}

328
lib/qbit.sh Executable file
View file

@ -0,0 +1,328 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr qBittorrent configuration & credential management
# Requires: lib/core.sh, lib/api.sh
if [ -n "${_ASSEMBLRR_QBIT_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_QBIT_SOURCED=1
# True when this install routes qBittorrent through Gluetun.
stack_vpn_enabled() {
case "${VPN_ENABLED:-${setup_vpn:-n}}" in
y|Y|yes|YES) return 0 ;;
*) return 1 ;;
esac
}
# Backwards-compatible alias
qbit_vpn_enabled() {
stack_vpn_enabled
}
qbit_vuetorrent_enabled() {
case "${VUETORRENT_ENABLED:-n}" in
y|Y|yes|YES) return 0 ;;
*) return 1 ;;
esac
}
# Generate PBKDF2 password hash for qBittorrent WebUI (@ByteArray(salt:hash)).
qbit_generate_pbkdf2() {
local password="$1"
if [ -z "$password" ]; then
echo ""
return
fi
if command -v python3 &>/dev/null; then
QBIT_PWD="$password" python3 -c "import hashlib, os, base64; salt = os.urandom(16); dk = hashlib.pbkdf2_hmac('sha512', os.environ.get('QBIT_PWD', '').encode('utf-8'), salt, 100000); print(f'@ByteArray({base64.b64encode(salt).decode()}:{base64.b64encode(dk).decode()})')" 2>/dev/null || echo ""
elif command -v python &>/dev/null; then
QBIT_PWD="$password" python -c "import hashlib, os, base64; salt = os.urandom(16); dk = hashlib.pbkdf2_hmac('sha512', os.environ.get('QBIT_PWD', '').encode('utf-8'), salt, 100000); print(f'@ByteArray({base64.b64encode(salt).decode()}:{base64.b64encode(dk).decode()})')" 2>/dev/null || echo ""
else
echo ""
fi
}
# Write qBittorrent.conf pre-start (always preserves VPN tun0 bind even if python3 is absent).
write_qbittorrent_config() {
local base_dir="${install_directory:-${INSTALL_DIR:-}}"
[ -n "$base_dir" ] || return 1
local qbit_config_dir="$base_dir/config/qbittorrent/qBittorrent"
local conf_file="$qbit_config_dir/qBittorrent.conf"
mkdir -p "$qbit_config_dir"
local pbkdf2_hash
pbkdf2_hash=$(qbit_generate_pbkdf2 "${auth_password:-${AUTH_PASSWORD:-}}")
local user="${auth_username:-${AUTH_USERNAME:-admin}}"
local alt_ui="false"
qbit_vuetorrent_enabled && alt_ui="true"
(
umask 077
{
if stack_vpn_enabled; then
printf '[BitTorrent]\n'
printf 'Session\\Interface=tun0\n'
printf 'Session\\InterfaceName=tun0\n\n'
fi
printf '[Preferences]\n'
printf 'WebUI\\Username=%s\n' "$user"
if [ -n "$pbkdf2_hash" ]; then
printf 'WebUI\\Password_PBKDF2=%s\n' "$pbkdf2_hash"
fi
printf 'WebUI\\Port=8081\n'
if [ "$alt_ui" = "true" ]; then
printf 'WebUI\\AlternativeUIEnabled=true\n'
printf 'WebUI\\RootFolder=/vuetorrent\n'
else
printf 'WebUI\\AlternativeUIEnabled=false\n'
fi
} > "$conf_file"
)
chmod 600 "$conf_file" 2>/dev/null || true
if stack_vpn_enabled; then
log_success "Pre-configured qBittorrent credentials and tun0 bind"
elif [ -n "$pbkdf2_hash" ]; then
log_success "Pre-configured qBittorrent credentials (bypassing WebAPI restrictions)"
else
log_warning "python3 unavailable — skipped qBittorrent PBKDF2 hash; WebUI temp password will be used on first boot"
fi
}
# setPreferences JSON: save paths, ATM, tun0 (when VPN is on), VueTorrent WebUI, optional creds.
qbit_core_prefs_json() {
local user="${1:-}"
local pass="${2:-}"
local iface=""
if qbit_vpn_enabled; then
iface="tun0"
fi
local alt_ui=false
local alt_path=""
if qbit_vuetorrent_enabled; then
alt_ui=true
alt_path="/vuetorrent"
fi
if [ -n "$user" ]; then
jq -nc \
--arg iface "$iface" \
--argjson alt_ui "$alt_ui" \
--arg alt_path "$alt_path" \
--arg user "$user" \
--arg pass "$pass" \
'({
save_path:"/data/torrents",
temp_path:"/data/torrents/incomplete",
temp_path_enabled:true,
auto_tmm_enabled:true,
current_network_interface:$iface,
alternative_webui_enabled:$alt_ui,
web_ui_username:$user,
web_ui_password:$pass
} + (if $alt_ui then {alternative_webui_path:$alt_path} else {} end))'
else
jq -nc \
--arg iface "$iface" \
--argjson alt_ui "$alt_ui" \
--arg alt_path "$alt_path" \
'({
save_path:"/data/torrents",
temp_path:"/data/torrents/incomplete",
temp_path_enabled:true,
auto_tmm_enabled:true,
current_network_interface:$iface,
alternative_webui_enabled:$alt_ui
} + (if $alt_ui then {alternative_webui_path:$alt_path} else {} end))'
fi
}
qbit_login_form() {
local cookie_jar="$1"
local user="$2"
local pass="$3"
local qbit_port="${4:-8081}"
http_request POST "http://${API_HOST}:${qbit_port}/api/v2/auth/login" \
-c "$cookie_jar" \
-H "Referer: http://${API_HOST}:${qbit_port}" \
--data-urlencode "username=${user}" \
--data-urlencode "password=${pass}" || return 1
}
qbit_apply_prefs() {
local cookie_jar="$1"
local user="${2:-}"
local pass="${3:-}"
local qbit_port=8081
local json
json=$(qbit_core_prefs_json "$user" "$pass")
if ! http_request POST "http://${API_HOST}:${qbit_port}/api/v2/app/setPreferences" \
-b "$cookie_jar" \
-H "Referer: http://${API_HOST}:${qbit_port}" \
--data-urlencode "json=${json}"; then
log_warning "qBittorrent: setPreferences failed (HTTP ${HTTP_STATUS})"
return 1
fi
return 0
}
_qbit_latest_temp_password() {
run_docker logs qbittorrent 2>&1 \
| awk -F': ' '/temporary password is provided for this session:/ { pw=$NF } END { if (pw) print pw }' \
|| true
}
# Set qBittorrent WebUI credentials, save paths, and VPN interface.
qbit_set_credentials() {
local qbit_port=8081
local qbit_cookie_jar
qbit_cookie_jar=$(mktemp)
if [ -n "${AUTH_USERNAME:-}" ] && [ -n "${AUTH_PASSWORD:-}" ]; then
qbit_login_form "$qbit_cookie_jar" "$AUTH_USERNAME" "$AUTH_PASSWORD" "$qbit_port" || true
local qbit_sid
qbit_sid=$(qbit_cookie_sid "$qbit_cookie_jar")
if [ -n "$qbit_sid" ]; then
if ! qbit_apply_prefs "$qbit_cookie_jar"; then
rm -f "$qbit_cookie_jar"
return 1
fi
if qbit_vpn_enabled; then
_cfg_log_info "qBittorrent credentials already set; BitTorrent bound to tun0"
else
_cfg_log_info "qBittorrent credentials already set"
fi
rm -f "$qbit_cookie_jar"
return 0
fi
fi
local wait_time=0 max_wait=60
while [ "$wait_time" -lt "$max_wait" ]; do
local qbit_temp_pass
qbit_temp_pass=$(_qbit_latest_temp_password)
if [ -n "$qbit_temp_pass" ]; then
qbit_login_form "$qbit_cookie_jar" "admin" "$qbit_temp_pass" "$qbit_port" || true
local qbit_sid
qbit_sid=$(qbit_cookie_sid "$qbit_cookie_jar")
if [ -n "$qbit_sid" ]; then
if ! qbit_apply_prefs "$qbit_cookie_jar" "$AUTH_USERNAME" "$AUTH_PASSWORD"; then
rm -f "$qbit_cookie_jar"
return 1
fi
echo >&2
if qbit_vpn_enabled; then
_cfg_log_info "Set qBittorrent credentials, save path, and tun0 bind"
else
_cfg_log_info "Set qBittorrent credentials and save path"
fi
rm -f "$qbit_cookie_jar"
return 0
fi
fi
wait_inline "Waiting for qBittorrent to initialize" "$wait_time"
sleep 3
wait_time=$((wait_time + 3))
done
echo >&2
log_warning "Could not login to qBittorrent with temp password"
rm -f "$qbit_cookie_jar"
return 1
}
qbit_try_login() {
local user="$1"
local pass="$2"
local cookie_jar="$3"
local qbit_port=8081
[ -n "$user" ] && [ -n "$pass" ] || return 1
: >"$cookie_jar"
qbit_login_form "$cookie_jar" "$user" "$pass" "$qbit_port" || return 1
[ -n "$(qbit_cookie_sid "$cookie_jar")" ]
}
qbit_change_credentials() {
local old_user="$1"
local old_pass="$2"
local new_user="$3"
local new_pass="$4"
local cookie_jar verify_jar
if [ -z "$new_user" ] || [ -z "$new_pass" ]; then
log_step_fail "qBittorrent: new credentials missing"
return 1
fi
cookie_jar=$(mktemp)
verify_jar=$(mktemp)
if ! qbit_try_login "$old_user" "$old_pass" "$cookie_jar"; then
if qbit_try_login "$new_user" "$new_pass" "$cookie_jar"; then
qbit_apply_prefs "$cookie_jar" || true
rm -f "$cookie_jar" "$verify_jar"
log_step "qBittorrent: already using the new password"
return 0
fi
local qbit_temp_pass
qbit_temp_pass=$(_qbit_latest_temp_password)
if [ -z "$qbit_temp_pass" ] || ! qbit_try_login "admin" "$qbit_temp_pass" "$cookie_jar"; then
rm -f "$cookie_jar" "$verify_jar"
log_step_fail "qBittorrent: could not log in with the old password"
return 1
fi
fi
qbit_apply_prefs "$cookie_jar" "$new_user" "$new_pass" || true
rm -f "$cookie_jar"
if qbit_try_login "$new_user" "$new_pass" "$verify_jar"; then
rm -f "$verify_jar"
log_step "qBittorrent: set login (${new_user})"
return 0
fi
rm -f "$verify_jar"
log_step_fail "qBittorrent: password change did not stick"
return 1
}
qbit_create_category() {
local service_name="$1"
local category="$2"
local save_path="$3"
local qbit_port=8081
local qbit_cookie_jar
qbit_cookie_jar=$(mktemp)
qbit_login_form "$qbit_cookie_jar" "$AUTH_USERNAME" "$AUTH_PASSWORD" "$qbit_port" || true
local qbit_sid
qbit_sid=$(qbit_cookie_sid "$qbit_cookie_jar")
if [ -z "$qbit_sid" ]; then
log_step_fail "${service_name}: could not login to qBittorrent to create categories"
rm -f "$qbit_cookie_jar"
return 1
fi
local created=0 edited=0
if http_request POST "http://${API_HOST}:${qbit_port}/api/v2/torrents/createCategory" \
-b "$qbit_cookie_jar" -H "Referer: http://${API_HOST}:${qbit_port}" \
--data-urlencode "category=${category}" --data-urlencode "savePath=${save_path}"; then
created=1
fi
if http_request POST "http://${API_HOST}:${qbit_port}/api/v2/torrents/editCategory" \
-b "$qbit_cookie_jar" -H "Referer: http://${API_HOST}:${qbit_port}" \
--data-urlencode "category=${category}" --data-urlencode "savePath=${save_path}"; then
edited=1
fi
rm -f "$qbit_cookie_jar"
if [ "$created" -eq 1 ] || [ "$edited" -eq 1 ]; then
log_step "${service_name}: qBittorrent '${category}' category → ${save_path}"
return 0
fi
log_step_fail "${service_name}: failed to set qBittorrent '${category}' category (HTTP ${HTTP_STATUS})"
return 1
}

1
lib/quality.sh Normal file → Executable file
View file

@ -1,4 +1,5 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# One quality choice for Radarr, Sonarr, and Seerr.
# Canonical: QUALITY_TIER=uhd|hd|any
# QUALITY_SOURCE=web|bluray (movies only; TV is always WEB)

74
lib/recyclarr.sh Executable file
View file

@ -0,0 +1,74 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Recyclarr TRaSH Guides sync configuration
# Requires: lib/core.sh, lib/quality.sh, config.sh logging
if [ -n "${_ASSEMBLRR_RECYCLARR_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_RECYCLARR_SOURCED=1
_recyclarr_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/quality.sh
[ -f "$_recyclarr_dir/quality.sh" ] && source "$_recyclarr_dir/quality.sh"
configure_recyclarr() {
local recyclarr_config_dir="$INSTALL_DIR/config/recyclarr"
local template_root="$INSTALL_DIR/templates/recyclarr"
mkdir -p "$recyclarr_config_dir/includes"
if [ ! -w "$recyclarr_config_dir" ]; then
log_step_fail "Recyclarr: config directory not writable (${recyclarr_config_dir})"
return 1
fi
export RADARR_API_KEY SONARR_API_KEY
local default_label
default_label=$(quality_profile_names radarr)
default_label="${default_label%%|*}"
if [ ! -f "$template_root/recyclarr.yml" ]; then
log_step_fail "Recyclarr: template root not found (${template_root}/recyclarr.yml)"
return 1
fi
# Write with 0600 (contains Radarr/Sonarr API keys)
if ! (
umask 077
envsubst '${RADARR_API_KEY} ${SONARR_API_KEY}' \
< "$template_root/recyclarr.yml" \
> "$recyclarr_config_dir/recyclarr.yml"
); then
log_step_fail "Recyclarr: failed to write config (${recyclarr_config_dir}/recyclarr.yml)"
return 1
fi
chmod 600 "$recyclarr_config_dir/recyclarr.yml" 2>/dev/null || true
local include_src="$template_root/includes"
if [ ! -d "$include_src" ]; then
log_step_fail "Recyclarr: includes directory not found (${include_src})"
return 1
fi
rm -f "$recyclarr_config_dir/includes"/*.yml 2>/dev/null || true
if ! cp "$include_src"/*.yml "$recyclarr_config_dir/includes/"; then
log_step_fail "Recyclarr: failed to copy include packs"
return 1
fi
local pack_count
pack_count=$(find "$recyclarr_config_dir/includes" -maxdepth 1 -name '*.yml' | wc -l | tr -d ' ')
log_step "Recyclarr: generated config (${pack_count} include packs; Seerr default: ${default_label})"
local sync_out
if wait_while "Syncing Recyclarr (TRaSH Guides)" run_docker exec recyclarr recyclarr sync; then
log_step "Recyclarr: synced Custom Formats and Quality Profiles successfully"
else
sync_out="${WAIT_WHILE_OUTPUT:-}"
log_step_fail "Recyclarr: failed to sync to Radarr/Sonarr"
printf '%s\n' "$sync_out" | grep -E '•|Error|error|Invalid|YAML' | head -5 | while IFS= read -r line; do
_cfg_log_info " $line"
done
return 1
fi
}

459
lib/seerr.sh Normal file → Executable file
View file

@ -1,20 +1,17 @@
#!/bin/bash
# assemblrr Seerr & Recyclarr configuration — sourced by config.sh
# Provides: configure_seerr, configure_recyclarr
# Requires: lib/core.sh (logging), lib/api.sh (api_get/post helpers),
# lib/quality.sh (tier + names), lib/arr.sh (lookups),
# config.sh (_cfg_log_info, log_step, log_step_fail, etc.)
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Seerr configuration — sourced by config.sh / config_edit.sh
# Requires: lib/core.sh, lib/api.sh, lib/quality.sh, lib/arr_quality.sh
set -euo pipefail
if [ -n "${_ASSEMBLRR_SEERR_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_SEERR_SOURCED=1
_seerr_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
# shellcheck source=lib/quality.sh
[ -f "$_seerr_dir/quality.sh" ] && source "$_seerr_dir/quality.sh"
# --- Shared helper: connect or update a service (Radarr/Sonarr) in Seerr ---
# Usage: seerr_connect_service <service_type> <port> <api_key> <profile_func> <active_dir> <is_4k> <cookie_jar> [existing_id]
# With existing_id: PUT update; without: POST create.
# Example: seerr_connect_service "radarr" 7878 "$RADARR_API_KEY" "lookup_radarr_profile" "/data/media/movies" "true" "$cookie_jar"
seerr_connect_service() {
local service_type="$1"
local service_port="$2"
@ -29,447 +26,261 @@ seerr_connect_service() {
log_step_fail "Seerr: ${service_type} API key not provided"
return 1
fi
if [ -z "$cookie_jar" ] || [ ! -f "$cookie_jar" ]; then
log_step_fail "Seerr: cookie jar not found for ${service_type} connection"
return 1
fi
local profile
local profile profile_id profile_name
profile=$($profile_func "$api_key")
local profile_id="${profile%%:*}"
local profile_name="${profile##*:}"
profile_id="${profile%%:*}"
profile_name="${profile##*:}"
# id is read-only on PUT — omit it from the body
local payload
payload=$(cat <<EOF
{
"name": "${service_type^}",
"hostname": "${service_type}",
"port": ${service_port},
"apiKey": "${api_key}",
"useSsl": false,
"baseUrl": "",
"isDefault": true,
"is4k": ${is_4k},
"minimumAvailability": "released",
"syncEnabled": true,
"activeProfileId": ${profile_id},
"activeProfileName": "${profile_name}",
"activeDirectory": "${active_dir}",
"tags": []
}
EOF
)
payload=$(jq -nc \
--arg name "${service_type^}" \
--arg host "$service_type" \
--argjson port "$service_port" \
--arg apikey "$api_key" \
--argjson is4k "$is_4k" \
--argjson pid "$profile_id" \
--arg pname "$profile_name" \
--arg dir "$active_dir" \
--arg stype "$service_type" '
{
name: $name,
hostname: $host,
port: $port,
apiKey: $apikey,
useSsl: false,
baseUrl: "",
isDefault: true,
is4k: $is4k,
minimumAvailability: "released",
syncEnabled: true,
activeProfileId: $pid,
activeProfileName: $pname,
activeDirectory: $dir,
tags: []
} + (if $stype == "sonarr" then {enableSeasonFolders: true} else {} end)
' 2>/dev/null || echo "")
# Special handling for Sonarr (needs enableSeasonFolders)
if [ "$service_type" = "sonarr" ]; then
payload=$(echo "$payload" | jq '.enableSeasonFolders = true' 2>/dev/null || echo "$payload")
if [ -z "$payload" ]; then
log_step_fail "Seerr: failed to build ${service_type} payload"
return 1
fi
local http_code
if [ -n "$existing_id" ]; then
http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X PUT -b "$cookie_jar" \
-H "Content-Type: application/json" \
-d "$payload" \
"http://${API_HOST}:5055/api/v1/settings/${service_type}/${existing_id}" 2>/dev/null || echo "000")
if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 300 ]; then
if http_request PUT "http://${API_HOST}:5055/api/v1/settings/${service_type}/${existing_id}" \
-b "$cookie_jar" -H "Content-Type: application/json" -d "$payload"; then
log_step "Seerr: updated ${service_type^} profile → ${profile_name}"
return 0
else
log_step_fail "Seerr: failed to update ${service_type} (HTTP $http_code)"
return 1
fi
log_step_fail "Seerr: failed to update ${service_type} (HTTP ${HTTP_STATUS})"
return 1
fi
# POST new connection
http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X POST -b "$cookie_jar" \
-H "Content-Type: application/json" \
-d "$payload" \
"http://${API_HOST}:5055/api/v1/settings/${service_type}" 2>/dev/null || echo "000")
if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 300 ]; then
if http_request POST "http://${API_HOST}:5055/api/v1/settings/${service_type}" \
-b "$cookie_jar" -H "Content-Type: application/json" -d "$payload"; then
log_step "Seerr: connected ${service_type^} (profile: ${profile_name})"
return 0
else
log_step_fail "Seerr: failed to connect ${service_type} (HTTP $http_code)"
return 1
fi
log_step_fail "Seerr: failed to connect ${service_type} (HTTP ${HTTP_STATUS})"
return 1
}
# --- Shared helper: check if a service is already connected to Seerr ---
# Usage: seerr_service_connected <service_type> <cookie_jar>
# Returns 0 and prints count if connected, or 1 on failure
seerr_service_connected() {
local service_type="$1"
local cookie_jar="$2"
local svc_list
svc_list=$(curl -sf --connect-timeout 5 -b "$cookie_jar" \
"http://${API_HOST}:5055/api/v1/service/${service_type}" 2>/dev/null || echo "")
if [ -z "$svc_list" ]; then
return 1
fi
local count
count=$(echo "$svc_list" | jq 'length' 2>/dev/null || echo "0")
echo "$count"
return 0
}
# --- Shared helper: first existing Seerr server id for a service (or empty) ---
# Usage: seerr_service_id <service_type> <cookie_jar>
seerr_service_id() {
local service_type="$1"
local cookie_jar="$2"
local settings
settings=$(curl -sf --connect-timeout 5 -b "$cookie_jar" \
"http://${API_HOST}:5055/api/v1/settings/${service_type}" 2>/dev/null || echo "")
if [ -z "$settings" ] || [ "$settings" = "[]" ]; then
if ! http_request GET "http://${API_HOST}:5055/api/v1/settings/${service_type}" -b "$cookie_jar"; then
echo ""
return 1
fi
echo "$settings" | jq -r '.[0].id // empty' 2>/dev/null || echo ""
if [ -z "$HTTP_BODY" ] || [ "$HTTP_BODY" = "[]" ]; then
echo ""
return 1
fi
printf '%s' "$HTTP_BODY" | jq -r '.[0].id // empty' 2>/dev/null || echo ""
}
# --- Shared helper: get Seerr session cookie ---
# Usage: seerr_get_cookie <cookie_jar> <include_hostname>
# Returns 0 on success, cookie file will be populated
seerr_get_cookie() {
local cookie_jar="$1"
local include_hostname="$2" # "true" or "false"
local include_hostname="$2"
local payload
if [ "$include_hostname" = "true" ]; then
# Full auth with hostname (for initial setup)
local media_host="jellyfin"
case "${MEDIA_SERVICE:-jellyfin}" in
jellyfin) media_host="jellyfin"; media_port=8096; media_type=2 ;;
emby) media_host="emby"; media_port=8096; media_type=3 ;;
plex) media_host="host.docker.internal"; media_port=32400; media_type=1 ;;
esac
if [ "$include_hostname" = "true" ]; then
payload=$(jq -nc \
--arg user "$AUTH_USERNAME" \
--arg pass "$AUTH_PASSWORD" \
--arg host "$media_host" \
--argjson port "$media_port" \
--argjson stype "$media_type" \
'{username:$user,password:$pass,hostname:$host,port:$port,useSsl:false,urlBase:"",email:"",serverType:$stype}')
'{username:$user,password:$pass,hostname:"jellyfin",port:8096,useSsl:false,urlBase:"",email:"",serverType:2}')
else
# Login-only (for re-runs when media server is already configured)
payload=$(jq -nc --arg user "$AUTH_USERNAME" --arg pass "$AUTH_PASSWORD" \
'{username:$user,password:$pass}')
fi
local auth_endpoint="jellyfin"
curl -s --connect-timeout 5 -c "$cookie_jar" \
-H "Content-Type: application/json" \
-d "$payload" \
"http://${API_HOST}:5055/api/v1/auth/${auth_endpoint}" 2>/dev/null >/dev/null || return 1
http_request POST "http://${API_HOST}:5055/api/v1/auth/jellyfin" \
-c "$cookie_jar" -H "Content-Type: application/json" -d "$payload" >/dev/null || true
# Verify cookie was created
if [ ! -s "$cookie_jar" ] || ! grep -q "connect.sid" "$cookie_jar" 2>/dev/null; then
return 1
fi
return 0
}
# --- Recyclarr configuration ---
configure_recyclarr() {
local recyclarr_config_dir="$INSTALL_DIR/config/recyclarr"
local template_root="$INSTALL_DIR/templates/recyclarr"
mkdir -p "$recyclarr_config_dir/includes"
if [ ! -w "$recyclarr_config_dir" ]; then
log_step_fail "Recyclarr: config directory not writable (${recyclarr_config_dir})"
return 1
fi
# Only substitute known vars so $schema in YAML comments is left alone
export RADARR_API_KEY SONARR_API_KEY
local default_label
default_label=$(quality_profile_names radarr)
default_label="${default_label%%|*}"
if [ ! -f "$template_root/recyclarr.yml" ]; then
log_step_fail "Recyclarr: template root not found (${template_root}/recyclarr.yml)"
return 1
fi
if ! envsubst '${RADARR_API_KEY} ${SONARR_API_KEY}' \
< "$template_root/recyclarr.yml" \
> "$recyclarr_config_dir/recyclarr.yml"; then
log_step_fail "Recyclarr: failed to write config (${recyclarr_config_dir}/recyclarr.yml)"
return 1
fi
# Include packs (no secrets). Replace the directory contents with the template set.
local include_src="$template_root/includes"
if [ ! -d "$include_src" ]; then
log_step_fail "Recyclarr: includes directory not found (${include_src})"
return 1
fi
rm -f "$recyclarr_config_dir/includes"/*.yml 2>/dev/null || true
if ! cp "$include_src"/*.yml "$recyclarr_config_dir/includes/"; then
log_step_fail "Recyclarr: failed to copy include packs"
return 1
fi
local pack_count
pack_count=$(find "$recyclarr_config_dir/includes" -maxdepth 1 -name '*.yml' | wc -l | tr -d ' ')
log_step "Recyclarr: generated config (${pack_count} include packs; Seerr default: ${default_label})"
local sync_out
if wait_while "Syncing Recyclarr (TRaSH Guides)" docker exec recyclarr recyclarr sync; then
log_step "Recyclarr: synced Custom Formats and Quality Profiles successfully"
else
sync_out="${WAIT_WHILE_OUTPUT:-}"
log_step_fail "Recyclarr: failed to sync to Radarr/Sonarr"
echo "$sync_out" | grep -E '•|Error|error|Invalid|YAML' | head -5 | while IFS= read -r line; do
_cfg_log_info " $line"
done
return 1
fi
_seerr_ready() {
http_request GET "http://${API_HOST}:5055/api/v1/settings/public"
}
# --- Seerr configuration ---
configure_seerr() {
local seerr_port=5055
local max_wait=120
local wait_time=0
# Step 1: Wait for Seerr to be responsive
echo >&2
while [ $wait_time -lt $max_wait ]; do
local http_code
http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 \
"http://${API_HOST}:${seerr_port}/api/v1/settings/public" 2>/dev/null || echo "000")
if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 300 ]; then
break
fi
wait_inline "Waiting for Seerr to start" "$wait_time"
sleep 3
wait_time=$((wait_time + 3))
done
echo >&2
if [ $wait_time -ge $max_wait ]; then
if ! wait_until "Waiting for Seerr to start" "$max_wait" 3 _seerr_ready; then
log_step_fail "Seerr: not responsive after ${max_wait}s"
return 1
fi
# Step 2: Check if setup is already complete
local public_settings
public_settings=$(curl -s --connect-timeout 5 \
"http://${API_HOST}:${seerr_port}/api/v1/settings/public" 2>/dev/null || echo "")
if [ -n "$public_settings" ]; then
local initialized
initialized=$(echo "$public_settings" | jq -r '.initialized // ""' 2>/dev/null || echo "")
if [ "$initialized" = "True" ] || [ "$initialized" = "true" ]; then
log_step "Seerr: setup already completed — configuring services"
local seerr_cookie_jar="/tmp/seerr_cookie_jar_$$_${seerr_port}"
# Get session cookie (no hostname needed — already configured)
if ! seerr_get_cookie "$seerr_cookie_jar" "false"; then
log_step_fail "Seerr: failed to get session cookie for reconfiguration"
return 1
fi
echo "Connecting Seerr services" >&2
local connect_errors=0
local is_4k
is_4k=$(quality_seerr_is_4k)
if [ -n "$RADARR_API_KEY" ]; then
local radarr_id
radarr_id=$(seerr_service_id "radarr" "$seerr_cookie_jar" || true)
if ! seerr_connect_service "radarr" 7878 "$RADARR_API_KEY" "lookup_radarr_profile" \
"/data/media/movies" "$is_4k" "$seerr_cookie_jar" "$radarr_id"; then
log_step_fail "Seerr: failed to configure Radarr (re-run to retry)"
connect_errors=$((connect_errors + 1))
fi
fi
if [ -n "$SONARR_API_KEY" ]; then
local sonarr_id
sonarr_id=$(seerr_service_id "sonarr" "$seerr_cookie_jar" || true)
if ! seerr_connect_service "sonarr" 8989 "$SONARR_API_KEY" "lookup_sonarr_profile" \
"/data/media/tv" "$is_4k" "$seerr_cookie_jar" "$sonarr_id"; then
log_step_fail "Seerr: failed to configure Sonarr (re-run to retry)"
connect_errors=$((connect_errors + 1))
fi
fi
echo >&2
rm -f "$seerr_cookie_jar"
[ "$connect_errors" -eq 0 ]
return $?
fi
fi
# Step 3: Determine media server connection details
local media_server_type=""
local media_server_host=""
local media_server_port=0
case "${MEDIA_SERVICE:-jellyfin}" in
jellyfin)
media_server_type="2"
media_server_host="jellyfin"
media_server_port=8096
;;
emby)
media_server_type="3"
media_server_host="emby"
media_server_port=8096
;;
plex)
# Plex uses host networking — Seerr needs the host IP
media_server_type="1"
media_server_host="host.docker.internal"
media_server_port=32400
;;
esac
if [ -z "$media_server_type" ]; then
log_step_fail "Seerr: unsupported media service '${MEDIA_SERVICE:-}'"
if [ "${MEDIA_SERVICE:-jellyfin}" != "jellyfin" ]; then
log_step_fail "Seerr: unsupported media service '${MEDIA_SERVICE:-}' (core stack supports Jellyfin)"
return 1
fi
# Step 4: Authenticate against the media server via Seerr's setup endpoint
# This creates the admin user in Seerr and stores the media server connection
local auth_payload
if [ "${MEDIA_SERVICE:-}" = "plex" ]; then
# Plex requires an authToken from Plex.tv OAuth — cannot automate without user interaction
log_step "Seerr: Plex detected — manual setup required via web UI at http://${API_HOST}:${seerr_port}"
_cfg_log_info " Log in with your Plex account to complete Seerr setup"
return 0
local public_settings initialized=""
http_request GET "http://${API_HOST}:${seerr_port}/api/v1/settings/public" || true
public_settings="$HTTP_BODY"
if [ -n "$public_settings" ]; then
initialized=$(printf '%s' "$public_settings" | jq -r '.initialized // ""' 2>/dev/null || echo "")
fi
# Jellyfin/Emby: use credential-based auth (both use /auth/jellyfin endpoint)
local auth_endpoint="jellyfin"
local seerr_cookie_jar
seerr_cookie_jar=$(mktemp)
if [ "$initialized" = "True" ] || [ "$initialized" = "true" ]; then
log_step "Seerr: setup already completed — configuring services"
if ! seerr_get_cookie "$seerr_cookie_jar" "false"; then
rm -f "$seerr_cookie_jar"
log_step_fail "Seerr: failed to get session cookie for reconfiguration"
return 1
fi
local connect_errors=0 is_4k
is_4k=$(quality_seerr_is_4k)
if [ -n "${RADARR_API_KEY:-}" ]; then
local radarr_id
radarr_id=$(seerr_service_id "radarr" "$seerr_cookie_jar" || true)
if ! seerr_connect_service "radarr" 7878 "$RADARR_API_KEY" "lookup_radarr_profile" \
"/data/media/movies" "$is_4k" "$seerr_cookie_jar" "$radarr_id"; then
log_step_fail "Seerr: failed to configure Radarr (re-run to retry)"
connect_errors=$((connect_errors + 1))
fi
fi
if [ -n "${SONARR_API_KEY:-}" ]; then
local sonarr_id
sonarr_id=$(seerr_service_id "sonarr" "$seerr_cookie_jar" || true)
if ! seerr_connect_service "sonarr" 8989 "$SONARR_API_KEY" "lookup_sonarr_profile" \
"/data/media/tv" "$is_4k" "$seerr_cookie_jar" "$sonarr_id"; then
log_step_fail "Seerr: failed to configure Sonarr (re-run to retry)"
connect_errors=$((connect_errors + 1))
fi
fi
echo >&2
rm -f "$seerr_cookie_jar"
[ "$connect_errors" -eq 0 ]
return $?
fi
local auth_payload
auth_payload=$(jq -nc \
--arg user "$AUTH_USERNAME" \
--arg pass "$AUTH_PASSWORD" \
--arg host "$media_server_host" \
--argjson port "$media_server_port" \
--argjson stype "$media_server_type" \
'{username:$user,password:$pass,hostname:$host,port:$port,useSsl:false,urlBase:"",email:"",serverType:$stype}')
'{username:$user,password:$pass,hostname:"jellyfin",port:8096,useSsl:false,urlBase:"",email:"",serverType:2}')
_cfg_log_info "Seerr: authenticating against ${MEDIA_SERVICE:-jellyfin}..."
_cfg_log_info "Seerr: authenticating against Jellyfin..."
# Use -s (not -sf) so we can capture error responses too
local auth_response
auth_response=$(curl -s --connect-timeout 10 -X POST \
-H "Content-Type: application/json" \
-d "$auth_payload" \
"http://${API_HOST}:${seerr_port}/api/v1/auth/${auth_endpoint}" 2>/dev/null || echo "")
http_request POST "http://${API_HOST}:${seerr_port}/api/v1/auth/jellyfin" \
-c "$seerr_cookie_jar" -H "Content-Type: application/json" -d "$auth_payload" || true
local auth_response="$HTTP_BODY"
if [ -z "$auth_response" ]; then
rm -f "$seerr_cookie_jar"
log_step_fail "Seerr: failed to authenticate (empty response)"
_cfg_log_info " Complete setup manually at http://${API_HOST}:${seerr_port}"
return 1
fi
# "already configured" is success when re-running against an initialized Seerr
local auth_error
auth_error=$(echo "$auth_response" | jq -r '.error // ""' 2>/dev/null || echo "")
auth_error=$(printf '%s' "$auth_response" | jq -r '.error // ""' 2>/dev/null || echo "")
if [ -n "$auth_error" ]; then
if echo "$auth_error" | grep -qi "already configured"; then
log_step "Seerr: media server already connected"
else
local auth_message
auth_message=$(echo "$auth_response" | jq -r '.message // .error // "unknown error"' 2>/dev/null || echo "unknown error")
auth_message=$(printf '%s' "$auth_response" | jq -r '.message // .error // "unknown error"' 2>/dev/null || echo "unknown error")
rm -f "$seerr_cookie_jar"
log_step_fail "Seerr: authentication failed — ${auth_message}"
_cfg_log_info " Complete setup manually at http://${API_HOST}:${seerr_port}"
return 1
fi
else
local auth_id
auth_id=$(echo "$auth_response" | jq -r '.id // ""' 2>/dev/null || echo "")
auth_id=$(printf '%s' "$auth_response" | jq -r '.id // ""' 2>/dev/null || echo "")
if [ -n "$auth_id" ]; then
log_step "Seerr: authenticated against ${MEDIA_SERVICE:-jellyfin} (admin user created)"
log_step "Seerr: authenticated against Jellyfin (admin user created)"
else
rm -f "$seerr_cookie_jar"
log_step_fail "Seerr: authentication returned unexpected response"
_cfg_log_info " Complete setup manually at http://${API_HOST}:${seerr_port}"
return 1
fi
fi
# Step 5: session cookie for subsequent API calls
local seerr_cookie_jar="/tmp/seerr_cookie_jar_$$_${seerr_port}"
if ! seerr_get_cookie "$seerr_cookie_jar" "true"; then
if ! seerr_get_cookie "$seerr_cookie_jar" "false"; then
log_step_fail "Seerr: failed to get session cookie"
if [ ! -s "$seerr_cookie_jar" ] || ! grep -q "connect.sid" "$seerr_cookie_jar" 2>/dev/null; then
if ! seerr_get_cookie "$seerr_cookie_jar" "true" && ! seerr_get_cookie "$seerr_cookie_jar" "false"; then
rm -f "$seerr_cookie_jar"
log_step_fail "Seerr: failed to get session cookie"
return 1
fi
fi
# Step 6: mark setup complete
local init_code
init_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -X POST -b "$seerr_cookie_jar" \
-H "Content-Type: application/json" \
"http://${API_HOST}:${seerr_port}/api/v1/settings/initialize" 2>/dev/null || echo "000")
if [ "$init_code" -ge 200 ] && [ "$init_code" -lt 300 ]; then
if http_request POST "http://${API_HOST}:${seerr_port}/api/v1/settings/initialize" \
-b "$seerr_cookie_jar" -H "Content-Type: application/json"; then
log_step "Seerr: setup completed successfully"
else
log_step_fail "Seerr: failed to finalize setup (HTTP $init_code)"
_cfg_log_info " Complete setup manually at http://${API_HOST}:${seerr_port}"
rm -f "$seerr_cookie_jar"
log_step_fail "Seerr: failed to finalize setup (HTTP ${HTTP_STATUS})"
_cfg_log_info " Complete setup manually at http://${API_HOST}:${seerr_port}"
return 1
fi
echo "Connecting Seerr services" >&2
# Connect Radarr and Sonarr using shared helper
local connect_errors=0
local is_4k
local connect_errors=0 is_4k
is_4k=$(quality_seerr_is_4k)
if [ -n "$RADARR_API_KEY" ]; then
if [ -n "${RADARR_API_KEY:-}" ]; then
if ! seerr_connect_service "radarr" 7878 "$RADARR_API_KEY" "lookup_radarr_profile" \
"/data/media/movies" "$is_4k" "$seerr_cookie_jar"; then
connect_errors=$((connect_errors + 1))
fi
fi
if [ -n "$SONARR_API_KEY" ]; then
if [ -n "${SONARR_API_KEY:-}" ]; then
if ! seerr_connect_service "sonarr" 8989 "$SONARR_API_KEY" "lookup_sonarr_profile" \
"/data/media/tv" "$is_4k" "$seerr_cookie_jar"; then
connect_errors=$((connect_errors + 1))
fi
fi
echo >&2
rm -f "$seerr_cookie_jar"
if [ $connect_errors -gt 0 ]; then
return 1
fi
[ "$connect_errors" -eq 0 ]
}
# Seerr has no separate password — it authenticates against Jellyfin/Emby.
seerr_verify_login() {
local seerr_cookie_jar="/tmp/seerr_cookie_jar_verify_$$"
local seerr_cookie_jar
seerr_cookie_jar=$(mktemp)
if seerr_get_cookie "$seerr_cookie_jar" "false" || seerr_get_cookie "$seerr_cookie_jar" "true"; then
rm -f "$seerr_cookie_jar"
log_step "Seerr: session works with the new Jellyfin/Emby password"
log_step "Seerr: session works with the new Jellyfin password"
return 0
fi
rm -f "$seerr_cookie_jar"
log_step_fail "Seerr: could not open a session (it uses the Jellyfin/Emby login)"
log_step_fail "Seerr: could not open a session (it uses the Jellyfin login)"
return 1
}

66
lib/services.sh Normal file → Executable file
View file

@ -1,6 +1,7 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr service catalog — UI URLs and display labels for status
# Requires: MEDIA_SERVICE, VPN_ENABLED optional (from install config)
# Requires: MEDIA_SERVICE, VPN_ENABLED, USENET_ENABLED, BYPARR_ENABLED optional
if [ -n "${_ASSEMBLRR_SERVICES_SOURCED:-}" ]; then
return 0
@ -11,49 +12,30 @@ readonly _ASSEMBLRR_SERVICES_SOURCED=1
# compose_service|Display Name|port|path|kind
# kind: ui = browser URL, internal = no public UI
list_service_catalog() {
local media="${MEDIA_SERVICE:-jellyfin}"
local media_port=8096
local media_path="/"
local media_label="Jellyfin"
case "$media" in
jellyfin)
media_label="Jellyfin"
media_port=8096
media_path="/"
;;
emby)
media_label="Emby"
media_port=8096
media_path="/"
;;
plex)
media_label="Plex"
media_port=32400
media_path="/web"
;;
*)
media_label="$media"
media_port=8096
media_path="/"
;;
esac
printf '%s\n' \
"${media}|${media_label}|${media_port}|${media_path}|ui" \
"jellyfin|Jellyfin|8096|/|ui" \
"seerr-gateway|Seerr|5055|/|ui" \
"bazarr|Bazarr|6767|/|ui" \
"sonarr|Sonarr|8989|/|ui" \
"radarr|Radarr|7878|/|ui" \
"prowlarr|Prowlarr|9696|/|ui" \
"qbittorrent|qBittorrent|8081|/|ui" \
"recyclarr|Recyclarr|||internal"
"qbittorrent|qBittorrent|8081|/|ui"
if [ "${USENET_ENABLED:-n}" = "y" ] || [ "${USENET_ENABLED:-n}" = "Y" ]; then
printf '%s\n' "sabnzbd|SABnzbd|8085|/|ui"
fi
printf '%s\n' \
"seerr|Seerr (internal)|||internal" \
"media-purge-watch|Media purge watch|||internal"
"recyclarr|Recyclarr|||internal" \
"seerr|Seerr (internal)|||internal"
if [ "${VPN_ENABLED:-n}" = "y" ]; then
if [ "${BYPARR_ENABLED:-n}" = "y" ] || [ "${BYPARR_ENABLED:-n}" = "Y" ]; then
printf '%s\n' "byparr|Byparr (solver)|||internal"
fi
printf '%s\n' "media-purge-watch|Media purge watch|||internal"
if [ "${VPN_ENABLED:-n}" = "y" ] || [ "${VPN_ENABLED:-n}" = "Y" ]; then
printf '%s\n' \
"gluetun|Gluetun (VPN)|||internal" \
"deunhealth|Deunhealth|||internal" \
@ -61,11 +43,15 @@ list_service_catalog() {
fi
}
# Build URL for a catalog row (localhost — stable across DHCP changes)
# Build URL for a catalog row (uses localhost unless API_HOST points to a LAN/remote host)
service_ui_url() {
local port="$1"
local path="${2:-/}"
local host="${3:-localhost}"
local host="${3:-${API_HOST:-localhost}}"
case "$host" in
""|127.0.0.1|0.0.0.0) host="localhost" ;;
esac
[ -z "$port" ] && { echo ""; return 0; }
if [ "$path" != "/" ] && [[ "$path" != /* ]]; then
@ -79,7 +65,7 @@ service_ui_url() {
}
# True when a compose ps row is ready for the operator.
# healthy → ready; starting/unhealthy → not; no healthcheck + running → ready.
# healthy -> ready; starting/unhealthy -> not; no healthcheck + running -> ready.
service_row_ready() {
local state="${1:-}"
local health="${2:-}"
@ -94,12 +80,12 @@ service_row_ready() {
# Human-readable service URLs only (setup summary / scripting)
running_services_location() {
local host_ip="localhost"
local host_ip="${1:-${API_HOST:-localhost}}"
local line svc label port path kind
echo "Service URLs (live: ${APP_CLI_NAME:-assemblrr} status):"
while IFS='|' read -r svc label port path kind; do
[ "$kind" = "ui" ] || continue
printf ' %-12s %s\n' "$label" "$(service_ui_url "$port" "$path" "$host_ip")"
printf ' %-14s %s\n' "$label" "$(service_ui_url "$port" "$path" "$host_ip")"
done < <(list_service_catalog)
}

125
lib/tty.sh Executable file
View file

@ -0,0 +1,125 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr terminal input helpers (prompting, TTY drain, masked passwords)
if [ -n "${_ASSEMBLRR_TTY_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_TTY_SOURCED=1
# Discard a pending line on the tty (e.g., fzf's confirming Enter). Non-blocking.
flush_tty_input() {
local __ft_junk
[ -t 0 ] && [ -r /dev/tty ] || return 0
while read -r -t 0.01 __ft_junk </dev/tty 2>/dev/null; do
:
done
return 0
}
# Prompt and read a line cleanly (always -r, EOF-safe under set -e; defaults to REPLY).
read_prompt() {
local prompt="$1"
local __rp_var="${2:-REPLY}"
local __rp_reply=""
if [ -t 0 ] && [ -r /dev/tty ]; then
read -r -p "$prompt" __rp_reply </dev/tty || true
else
read -r -p "$prompt" __rp_reply || true
fi
printf -v "$__rp_var" '%s' "$__rp_reply"
}
# Read masked input (shows asterisks for each character, restores terminal on Ctrl+C).
read_masked() {
local prompt="$1"
local var_name="$2"
local value=""
local charcount=0
local old_settings=""
_clear_masked_input() {
while [ "$charcount" -gt 0 ]; do
printf '\b \b' >&2
charcount=$((charcount - 1))
done
value=""
}
if [ ! -t 0 ]; then
printf '%s' "$prompt" >&2
IFS= read -r value || true
printf '\n' >&2
printf -v "$var_name" '%s' "$value"
return 0
fi
printf '%s' "$prompt" >&2
old_settings=$(stty -g 2>/dev/null || true)
_restore_masked_tty() {
if [ -n "$old_settings" ]; then
stty "$old_settings" 2>/dev/null || stty echo 2>/dev/null || true
else
stty echo 2>/dev/null || true
fi
}
local prev_int_trap prev_term_trap
prev_int_trap=$(trap -p INT 2>/dev/null || true)
prev_term_trap=$(trap -p TERM 2>/dev/null || true)
_restore_masked_traps() {
if [ -n "$prev_int_trap" ]; then
eval "$prev_int_trap"
else
trap - INT
fi
if [ -n "$prev_term_trap" ]; then
eval "$prev_term_trap"
else
trap - TERM
fi
}
trap '_restore_masked_tty; printf "\n" >&2; _restore_masked_traps; kill -s INT "$$"' INT
trap '_restore_masked_tty; printf "\n" >&2; _restore_masked_traps; kill -s TERM "$$"' TERM
stty -echo 2>/dev/null || true
local char=""
while IFS= read -r -n 1 char; do
if [[ $char == $'\n' ]] || [[ -z "$char" ]]; then
break
fi
if [[ $char == $'\177' ]] || [[ $char == $'\b' ]]; then
if [ $charcount -gt 0 ]; then
charcount=$((charcount - 1))
printf '\b \b' >&2
value="${value%?}"
fi
elif [[ $char == $'\025' ]] || [[ $char == $'\027' ]]; then
_clear_masked_input
elif [[ $char == $'\e' ]]; then
local seq="" next=""
while IFS= read -r -s -n 1 -t 0.01 next; do
seq+="$next"
[[ $next == "~" ]] && break
[ ${#seq} -ge 8 ] && break
done
case "$seq" in
"[3;5~"|"[127;5u"|"[8;5~")
_clear_masked_input
;;
esac
else
charcount=$((charcount + 1))
printf '*' >&2
value+="$char"
fi
done
_restore_masked_traps
_restore_masked_tty
printf '\n' >&2
printf -v "$var_name" '%s' "$value"
}

1
lib/ui.sh Normal file → Executable file
View file

@ -1,4 +1,5 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Operator-facing UI mode for shared prompt/picker engines.
# setup = first install / full wizard (optional picks, skip is fine)
# edit = post-install `config edit` (change current state, Esc = no change)

261
lib/upgrade.sh Normal file → Executable file
View file

@ -1,26 +1,45 @@
#!/bin/bash
# assemblrr upgrade engine — source tree → install dir (git ref or local --from)
# Provides: upgrade_app, upgrade_check
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr upgrade engine — source tree -> install dir (git ref or local --from)
# Provides: upgrade_app, apply_managed_files, run_migrations, validate_install_compose
# Requires: core.sh, branding.sh, compose.sh, managed_files.sh; INSTALL_DIR set
# Optional: backup_app from cli context
if [ -n "${_ASSEMBLRR_UPGRADE_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_UPGRADE_SOURCED=1
# Defaults
UPGRADE_DEFAULT_REF="main"
UPGRADE_VERSION_FILE=".assemblrr-version"
UPGRADE_CHANNEL_FILE=".assemblrr-channel"
UPGRADE_MIGRATIONS_FILE=".assemblrr-migrations"
# --- Source resolution (transport layer) ---
_upgrade_default_ref() {
local install_dir="${1:-${INSTALL_DIR:-}}"
local ref=""
if [ -n "${ASSEMBLRR_CHANNEL:-}" ]; then
printf '%s\n' "$ASSEMBLRR_CHANNEL"
return 0
fi
if [ -n "$install_dir" ] && [ -f "$install_dir/$UPGRADE_CHANNEL_FILE" ]; then
ref=$(tr -d '\r\n ' < "$install_dir/$UPGRADE_CHANNEL_FILE" 2>/dev/null || true)
fi
printf '%s\n' "${ref:-$UPGRADE_DEFAULT_REF}"
}
_write_upgrade_channel() {
local install_dir="$1"
local ref="$2"
[ -n "$ref" ] || return 0
printf '%s\n' "$ref" > "$install_dir/$UPGRADE_CHANNEL_FILE"
}
# resolve_upgrade_source --from DIR | --ref REF
# Sets: UPGRADE_SOURCE_ROOT, UPGRADE_SOURCE_LABEL, UPGRADE_SOURCE_TEMP (if cleanup needed)
# Sets: UPGRADE_SOURCE_ROOT, UPGRADE_SOURCE_LABEL, UPGRADE_SOURCE_TEMP
resolve_upgrade_source() {
local from_dir=""
local ref="${UPGRADE_DEFAULT_REF}"
local ref
ref=$(_upgrade_default_ref "${INSTALL_DIR:-}")
local tmp=""
while [ $# -gt 0 ]; do
@ -29,7 +48,7 @@ resolve_upgrade_source() {
from_dir="${2:-}"
shift 2
;;
--ref)
--ref|--branch)
ref="${2:-}"
shift 2
;;
@ -39,17 +58,19 @@ resolve_upgrade_source() {
esac
done
UPGRADE_SOURCE_TEMP=""
UPGRADE_SOURCE_TEMP="${UPGRADE_SOURCE_TEMP:-}"
UPGRADE_SOURCE_ROOT=""
UPGRADE_SOURCE_LABEL=""
if [ -n "$from_dir" ]; then
if [ ! -d "$from_dir" ]; then
log_error "Upgrade source not a directory: $from_dir"
return 1
fi
UPGRADE_SOURCE_ROOT=$(cd "$from_dir" && pwd)
if [ ! -f "$UPGRADE_SOURCE_ROOT/lib/core.sh" ] || [ ! -f "$UPGRADE_SOURCE_ROOT/compose/base.yaml" ]; then
log_error "Not an assemblrr source tree (missing lib/core.sh or compose/base.yaml): $UPGRADE_SOURCE_ROOT"
return 1
fi
local sha="unknown"
if [ -d "$UPGRADE_SOURCE_ROOT/.git" ]; then
@ -59,21 +80,25 @@ resolve_upgrade_source() {
return 0
fi
# Git transport (production path) — same apply path as --from
local repo="${APP_REPO_URL:-https://github.com/soulis-1256/assemblrr}"
tmp=$(mktemp -d)
UPGRADE_SOURCE_TEMP="$tmp"
if ! wait_while "Fetching assemblrr @ ${ref}" git clone --depth=1 --branch "$ref" "$repo" "$tmp/assemblrr"; then
# branch might be a commit or default branch name failed; try without --branch then checkout
rm -rf "$tmp/assemblrr"
if ! wait_while "Fetching assemblrr (default branch)" git clone --depth=1 "$repo" "$tmp/assemblrr"; then
[ -n "$UPGRADE_SOURCE_TEMP" ] && rm -rf "$UPGRADE_SOURCE_TEMP"
if ! wait_while "Fetching assemblrr (fallback clone)" git clone --depth=1 "$repo" "$tmp/assemblrr"; then
rm -rf "$UPGRADE_SOURCE_TEMP"
UPGRADE_SOURCE_TEMP=""
log_error "Failed to clone ${repo}. Check network and APP_REPO_URL."
return 1
fi
if [ "$ref" != "main" ] && [ "$ref" != "master" ]; then
git -C "$tmp/assemblrr" fetch --depth=1 origin "$ref" 2>/dev/null || true
git -C "$tmp/assemblrr" checkout "$ref" 2>/dev/null || \
if ! git -C "$tmp/assemblrr" fetch --depth=1 origin "$ref" 2>/dev/null \
|| ! git -C "$tmp/assemblrr" checkout -q FETCH_HEAD 2>/dev/null; then
if ! git -C "$tmp/assemblrr" checkout -q "$ref" 2>/dev/null; then
rm -rf "$UPGRADE_SOURCE_TEMP"
UPGRADE_SOURCE_TEMP=""
log_error "Failed to checkout ref: $ref"
return 1
fi
fi
fi
UPGRADE_SOURCE_ROOT="$tmp/assemblrr"
@ -88,9 +113,53 @@ cleanup_upgrade_source() {
rm -rf "$UPGRADE_SOURCE_TEMP"
fi
UPGRADE_SOURCE_TEMP=""
if [ -n "${_UPGRADE_ROLLBACK_DIR:-}" ] && [ -d "$_UPGRADE_ROLLBACK_DIR" ]; then
rm -rf "$_UPGRADE_ROLLBACK_DIR"
fi
_UPGRADE_ROLLBACK_DIR=""
}
# --- Managed files ---
_stage_managed_rollback() {
local source_root="$1"
local install_dir="$2"
local stage_dir="$3"
local src dest dest_path
UPGRADE_SOURCE_ROOT="$source_root"
if [ -f "$source_root/lib/managed_files.sh" ]; then
# shellcheck source=/dev/null
source "$source_root/lib/managed_files.sh"
fi
: >"$stage_dir/.added"
while IFS='|' read -r src dest; do
[ -z "$dest" ] && continue
[[ "$dest" =~ ^# ]] && continue
dest_path="$install_dir/$dest"
if [ -f "$dest_path" ]; then
mkdir -p "$stage_dir/files/$(dirname "$dest")"
cp -p "$dest_path" "$stage_dir/files/$dest" 2>/dev/null || cp "$dest_path" "$stage_dir/files/$dest"
else
printf '%s\n' "$dest" >>"$stage_dir/.added"
fi
done < <(list_managed_files)
}
_restore_managed_rollback() {
local install_dir="$1"
local stage_dir="$2"
[ -n "$stage_dir" ] && [ -d "$stage_dir" ] || return 0
if [ -d "$stage_dir/files" ]; then
cp -a "$stage_dir/files/." "$install_dir/" 2>/dev/null || true
fi
if [ -f "$stage_dir/.added" ]; then
local rel
while IFS= read -r rel; do
[ -n "$rel" ] && rm -f "$install_dir/$rel" 2>/dev/null || true
done <"$stage_dir/.added"
fi
log_warning "Rolled back managed files in ${install_dir} after failed validation."
}
apply_managed_files() {
local source_root="$1"
@ -100,7 +169,7 @@ apply_managed_files() {
local copied=0 skipped=0 missing=0
UPGRADE_SOURCE_ROOT="$source_root"
# Prefer source tree manifest (may be newer than install).
# Prefer source tree manifest (may include new modules/overlays).
# shellcheck source=/dev/null
if [ -f "$source_root/lib/managed_files.sh" ]; then
source "$source_root/lib/managed_files.sh"
@ -133,7 +202,9 @@ apply_managed_files() {
mkdir -p "$(dirname "$dest_path")"
cp "$src_path" "$dest_path"
case "$src" in
scripts/*|bin/cli.sh|bin/config.sh|bin/setup.sh) chmod +x "$dest_path" 2>/dev/null || true ;;
scripts/*.sh|scripts/*.py|bin/*.sh|migrations/*.sh|platform/linux/*.sh)
chmod +x "$dest_path" 2>/dev/null || true
;;
esac
copied=$((copied + 1))
done < <(list_managed_files)
@ -178,7 +249,8 @@ run_migrations() {
fi
while IFS= read -r -d '' f; do
# shellcheck disable=SC1090
# Unset BEFORE sourcing so a malformed file never inherits the previous migration's handlers
unset -f migration_should_skip migration_apply 2>/dev/null || true
migration_id=""
migration_description=""
# shellcheck source=/dev/null
@ -186,11 +258,13 @@ run_migrations() {
if [ -z "${migration_id:-}" ]; then
log_warning "Migration without migration_id: $f"
unset -f migration_should_skip migration_apply 2>/dev/null || true
continue
fi
if _migration_already_recorded "$install_dir" "$migration_id"; then
log_info "Migration ${migration_id}: already recorded — skip"
unset -f migration_should_skip migration_apply 2>/dev/null || true
continue
fi
@ -215,7 +289,9 @@ run_migrations() {
_record_migration "$install_dir" "$migration_id"
log_success "Migration ${migration_id}: done"
else
unset -f migration_should_skip migration_apply 2>/dev/null || true
log_error "Migration ${migration_id}: failed"
return 1
fi
else
log_warning "Migration ${migration_id}: no migration_apply — recording as done"
@ -231,8 +307,6 @@ write_upgrade_version() {
printf '%s\n' "$label" > "$install_dir/$UPGRADE_VERSION_FILE"
}
# --- CLI install refresh ---
refresh_user_cli() {
local install_dir="$1"
if [ -n "$install_dir" ] && [ ! -f "$HOME/.assemblrr-config" ]; then
@ -241,12 +315,10 @@ refresh_user_cli() {
install_user_cli_wrapper
}
# --- Validate compose after apply ---
validate_install_compose() {
local install_dir="$1"
build_compose_args "$install_dir" "${VPN_ENABLED:-n}"
if ! run_docker compose "${COMPOSE_ARGS[@]}" --profile "${MEDIA_SERVICE:-jellyfin}" config --quiet 2>/tmp/assemblrr-compose-validate.err; then
if ! run_docker compose "${COMPOSE_ARGS[@]}" config --quiet 2>/tmp/assemblrr-compose-validate.err; then
log_warning "Compose validation failed:"
sed 's/^/ /' /tmp/assemblrr-compose-validate.err 2>/dev/null | head -20
return 1
@ -254,114 +326,143 @@ validate_install_compose() {
return 0
}
# --- Public entrypoints ---
# upgrade_app [--check] [--from DIR] [--ref REF] [--skip-backup] [--skip-stack] [--skip-wire] [-y]
# upgrade_app [--check] [--from DIR] [--ref REF] [--skip-backup] [--skip-stack|--no-restart] [--skip-wire] [-y]
upgrade_app() {
local check_only=0
local skip_backup=0
local skip_stack=0
local skip_wire=0
local assume_yes=0
local stage2=0
local from_dir=""
local ref=""
local explicit_ref=0
local parse_args=()
while [ $# -gt 0 ]; do
case "$1" in
--check) check_only=1; shift ;;
--skip-backup) skip_backup=1; shift ;;
--skip-stack) skip_stack=1; shift ;;
--skip-stack|--no-restart) skip_stack=1; shift ;;
--skip-wire) skip_wire=1; shift ;;
-y|--yes) assume_yes=1; shift ;;
--stage2) stage2=1; shift ;;
--from)
from_dir="${2:-}"
[ -z "$from_dir" ] && log_error "Usage: upgrade --from DIR"
parse_args+=(--from "$from_dir")
shift 2
;;
--ref)
--ref|--branch)
ref="${2:-}"
[ -z "$ref" ] && log_error "Usage: upgrade --ref REF"
explicit_ref=1
parse_args+=(--ref "$ref")
shift 2
;;
*)
log_error "Unknown upgrade option: $1"
return 1
;;
esac
done
if [ -z "$from_dir" ] && [ -z "$ref" ]; then
parse_args+=(--ref "$UPGRADE_DEFAULT_REF")
ref=$(_upgrade_default_ref "$INSTALL_DIR")
parse_args+=(--ref "$ref")
fi
trap cleanup_upgrade_source EXIT
resolve_upgrade_source "${parse_args[@]}"
log_info "Upgrade source: $UPGRADE_SOURCE_LABEL"
log_info "Install: $INSTALL_DIR"
if [ -f "$INSTALL_DIR/$UPGRADE_VERSION_FILE" ]; then
log_info "Current: $(cat "$INSTALL_DIR/$UPGRADE_VERSION_FILE")"
else
log_info "Current: (no version stamp — first upgrade)"
fi
echo
log_info "=== Plan: managed files ==="
apply_managed_files "$UPGRADE_SOURCE_ROOT" "$INSTALL_DIR" 1
echo
log_info "=== Plan: migrations ==="
run_migrations "$UPGRADE_SOURCE_ROOT" "$INSTALL_DIR" 1
echo
if [ "$stage2" -eq 0 ]; then
log_info "Upgrade source: $UPGRADE_SOURCE_LABEL"
log_info "Install: $INSTALL_DIR"
if [ -f "$INSTALL_DIR/$UPGRADE_VERSION_FILE" ]; then
log_info "Current: $(cat "$INSTALL_DIR/$UPGRADE_VERSION_FILE")"
else
log_info "Current: (no version stamp — first upgrade)"
fi
echo
if [ "$check_only" = "1" ]; then
log_success "Dry-run complete (no changes made)."
cleanup_upgrade_source
trap - EXIT
return 0
fi
log_info "=== Plan: managed files ==="
apply_managed_files "$UPGRADE_SOURCE_ROOT" "$INSTALL_DIR" 1
echo
log_info "=== Plan: migrations ==="
run_migrations "$UPGRADE_SOURCE_ROOT" "$INSTALL_DIR" 1
echo
if [ "$assume_yes" != "1" ]; then
read -p "Apply this upgrade to ${INSTALL_DIR}? [y/N]: " -r
if [[ ! ${REPLY,,} =~ ^y$ ]]; then
log_info "Upgrade cancelled."
if [ "$check_only" = "1" ]; then
log_success "Dry-run complete (no changes made)."
cleanup_upgrade_source
trap - EXIT
return 0
fi
fi
# Backup (reuses cli backup_app if defined)
if [ "$skip_backup" != "1" ]; then
local backup_dest="${HOME}/${APP_NAME:-assemblrr}-backups"
log_info "Backing up to ${backup_dest}..."
if type backup_app >/dev/null 2>&1; then
backup_app "$backup_dest"
else
log_warning "backup_app not available — skipping automatic backup"
if [ "$assume_yes" != "1" ]; then
read_prompt "Apply this upgrade to ${INSTALL_DIR}? [y/N]: "
if [[ ! ${REPLY,,} =~ ^y$ ]]; then
log_info "Upgrade cancelled."
cleanup_upgrade_source
trap - EXIT
return 0
fi
fi
if [ "$skip_backup" != "1" ]; then
local backup_dest="${HOME}/${APP_NAME:-assemblrr}-backups"
log_info "Backing up to ${backup_dest}..."
if type backup_app >/dev/null 2>&1; then
backup_app "$backup_dest"
else
log_warning "backup_app not available — skipping automatic backup"
fi
else
log_warning "Skipping backup (--skip-backup)"
fi
_UPGRADE_ROLLBACK_DIR=$(mktemp -d)
_stage_managed_rollback "$UPGRADE_SOURCE_ROOT" "$INSTALL_DIR" "$_UPGRADE_ROLLBACK_DIR"
log_info "Applying managed files..."
apply_managed_files "$UPGRADE_SOURCE_ROOT" "$INSTALL_DIR" 0
refresh_user_cli "$INSTALL_DIR"
# Re-exec the newly installed cli.sh so newly split lib/*.sh modules execute cleanly
if [ "${ASSEMBLRR_UPGRADE_REEXEC:-1}" = "1" ] && [ -f "$INSTALL_DIR/cli.sh" ] \
&& [[ "${BASH_SOURCE[0]:-}" != "" ]] && [[ "${0##*/}" == cli.sh || "${0##*/}" == assemblrr ]]; then
local -a next_args=(upgrade --stage2 --from "$UPGRADE_SOURCE_ROOT" --skip-backup -y)
[ "$skip_stack" = "1" ] && next_args+=(--skip-stack)
[ "$skip_wire" = "1" ] && next_args+=(--skip-wire)
[ "$explicit_ref" = "1" ] && next_args+=(--ref "$ref")
export UPGRADE_SOURCE_TEMP _UPGRADE_ROLLBACK_DIR
export _ASSEMBLRR_UPGRADE_LABEL_OVERRIDE="$UPGRADE_SOURCE_LABEL"
trap - EXIT
exec bash "$INSTALL_DIR/cli.sh" "${next_args[@]}"
fi
else
log_warning "Skipping backup (--skip-backup)"
fi
log_info "Applying managed files..."
apply_managed_files "$UPGRADE_SOURCE_ROOT" "$INSTALL_DIR" 0
local stamp_label="${_ASSEMBLRR_UPGRADE_LABEL_OVERRIDE:-$UPGRADE_SOURCE_LABEL}"
# Ensure migrations dir exists in install for record-keeping transparency
mkdir -p "$INSTALL_DIR/migrations"
if [ -d "$UPGRADE_SOURCE_ROOT/migrations" ]; then
cp -a "$UPGRADE_SOURCE_ROOT/migrations/." "$INSTALL_DIR/migrations/" 2>/dev/null || true
if type prepare_install_dirs >/dev/null 2>&1; then
prepare_install_dirs "$INSTALL_DIR"
fi
log_info "Running migrations..."
run_migrations "$UPGRADE_SOURCE_ROOT" "$INSTALL_DIR" 0
write_upgrade_version "$INSTALL_DIR" "$UPGRADE_SOURCE_LABEL"
refresh_user_cli "$INSTALL_DIR"
if ! validate_install_compose "$INSTALL_DIR"; then
log_error "Compose invalid after upgrade. Restore with: ${APP_CLI_NAME:-assemblrr} restore <backup.tar.gz>"
_restore_managed_rollback "$INSTALL_DIR" "${_UPGRADE_ROLLBACK_DIR:-}"
cleanup_upgrade_source
trap - EXIT
log_error "Compose invalid after upgrade — managed files restored to previous state."
return 1
fi
write_upgrade_version "$INSTALL_DIR" "$stamp_label"
if [ "$explicit_ref" = "1" ] && [ -n "$ref" ]; then
_write_upgrade_channel "$INSTALL_DIR" "$ref"
fi
if [ "$skip_stack" = "1" ]; then
@ -370,9 +471,10 @@ upgrade_app() {
log_info "Bringing stack up with updated compose..."
build_compose_args "$INSTALL_DIR" "${VPN_ENABLED:-n}"
# --remove-orphans drops containers for services removed from managed compose
# (e.g. Portainer) while leaving services still defined in custom.yaml alone.
if ! compose_up_stack "${MEDIA_SERVICE:-jellyfin}" --build; then
# while leaving services defined in custom.yaml alone.
if ! compose_up_stack "default" --build; then
log_error "docker compose up failed. Restore with: ${APP_CLI_NAME:-assemblrr} restore <backup.tar.gz>"
return 1
fi
fi
@ -380,8 +482,7 @@ upgrade_app() {
log_info "Skipping service wiring (--skip-wire)"
elif [ -f "$INSTALL_DIR/config.sh" ]; then
log_info "Wiring services..."
# Re-wire must not open fzf/read prompts (would hang unattended upgrades
# and can wipe Bazarr providers if the picker is skipped).
# Re-wire must not open fzf/read prompts during unattended upgrades.
if ASSEMBLRR_NONINTERACTIVE=1 bash "$INSTALL_DIR/config.sh"; then
log_success "Service wiring completed"
else

321
lib/usenet.sh Executable file
View file

@ -0,0 +1,321 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr SABnzbd / Usenet wiring — sourced by config.sh / config_edit.sh / setup.sh
# Requires: lib/core.sh, lib/api.sh
if [ -n "${_ASSEMBLRR_USENET_SOURCED:-}" ]; then
return 0
fi
readonly _ASSEMBLRR_USENET_SOURCED=1
SABNZBD_PORT="${SABNZBD_PORT:-8080}"
sabnzbd_enabled() {
case "${USENET_ENABLED:-n}" in
y|Y|yes|YES) return 0 ;;
*) return 1 ;;
esac
}
# Read api_key from sabnzbd.ini (handles `api_key = xxx` or `api_key=xxx`).
sabnzbd_extract_api_key() {
local ini_file="$1"
[ -f "$ini_file" ] || return 1
awk -F= '/^[[:space:]]*api_key[[:space:]]*=/{
val=$2
gsub(/^[[:space:]]+|[[:space:]]+$/, "", val)
gsub(/\r/, "", val)
print val
exit
}' "$ini_file" 2>/dev/null
}
read_sabnzbd_api_key() {
local ini_file="$INSTALL_DIR/config/sabnzbd/sabnzbd.ini"
local max_wait=120 wait_time=0 key=""
while [ "$wait_time" -lt "$max_wait" ]; do
key=$(sabnzbd_extract_api_key "$ini_file" || true)
if [ -n "$key" ]; then
[ "$wait_time" -gt 0 ] && echo >&2
echo "$key"
return 0
fi
wait_inline "Waiting for SABnzbd to initialize" "$wait_time"
sleep 3
wait_time=$((wait_time + 3))
done
echo >&2
log_step_fail "SABnzbd: sabnzbd.ini api_key missing after ${max_wait}s"
return 1
}
# Pre-seed sabnzbd.ini before first start (or update whitelist/paths cleanly if absent).
write_sabnzbd_config() {
local base_dir="${install_directory:-${INSTALL_DIR:-}}"
[ -n "$base_dir" ] || return 1
local ini_dir="$base_dir/config/sabnzbd"
local ini_file="$ini_dir/sabnzbd.ini"
mkdir -p "$ini_dir"
# Never overwrite an existing initialized sabnzbd.ini (preserve generated api_key & user tweaks).
[ -f "$ini_file" ] && return 0
local user="${auth_username:-${AUTH_USERNAME:-}}"
local pass="${auth_password:-${AUTH_PASSWORD:-}}"
local host_api="${API_HOST:-127.0.0.1}"
(
umask 077
cat > "$ini_file" <<EOF
__version__ = 19
[misc]
host = 0.0.0.0
port = 8080
host_whitelist = sabnzbd, localhost, 127.0.0.1, ${host_api}
username = ${user}
password = ${pass}
download_dir = /data/usenet/incomplete
complete_dir = /data/usenet/complete
permissions = 755
[categories]
[[*]]
name = *
order = 0
pp = 3
script = None
priority = 0
[[movies]]
name = movies
order = 1
dir = movies
pp = 3
script = Default
priority = -100
[[tv]]
name = tv
order = 2
dir = tv
pp = 3
script = Default
priority = -100
EOF
)
chmod 600 "$ini_file" 2>/dev/null || true
}
_sabnzbd_ready() {
local apikey="$1"
http_request GET "http://${API_HOST}:${SABNZBD_PORT}/api?mode=version&output=json&apikey=${apikey}" || return 1
[ -n "$HTTP_BODY" ] && printf '%s' "$HTTP_BODY" | jq -e '.version // empty' >/dev/null 2>&1
}
_sab_set_config_misc() {
local apikey="$1"
local keyword="$2"
local value="$3"
local enc_val
enc_val=$(urlencode "$value")
http_request GET "http://${API_HOST}:${SABNZBD_PORT}/api?mode=set_config&section=misc&keyword=${keyword}&value=${enc_val}&output=json&apikey=${apikey}"
}
_sab_set_category() {
local apikey="$1"
local name="$2"
local dir="$3"
http_request GET "http://${API_HOST}:${SABNZBD_PORT}/api?mode=set_config&section=categories&name=${name}&dir=${dir}&pp=3&output=json&apikey=${apikey}"
}
_sab_set_server() {
local apikey="$1"
local host="$2"
local port="$3"
local ssl="$4"
local user="$5"
local pass="$6"
local enc_host enc_user enc_pass
enc_host=$(urlencode "$host")
enc_user=$(urlencode "$user")
enc_pass=$(urlencode "$pass")
http_request GET \
"http://${API_HOST}:${SABNZBD_PORT}/api?mode=set_config&section=servers&name=${enc_host}&host=${enc_host}&port=${port}&ssl=${ssl}&username=${enc_user}&password=${enc_pass}&connections=8&enable=1&output=json&apikey=${apikey}"
}
configure_sabnzbd() {
sabnzbd_enabled || return 0
local sab_key
if ! sab_key=$(read_sabnzbd_api_key); then
return 1
fi
if ! wait_until "Waiting for SABnzbd API" "${API_READY_TIMEOUT_SECONDS:-120}" 3 _sabnzbd_ready "$sab_key"; then
log_step_fail "SABnzbd: API not ready"
return 1
fi
write_secret_file "$INSTALL_DIR/secrets/sabnzbd_api_key.txt" "$sab_key"
_sab_set_config_misc "$sab_key" "host_whitelist" "sabnzbd, localhost, 127.0.0.1, ${API_HOST:-127.0.0.1}" || true
_sab_set_config_misc "$sab_key" "download_dir" "/data/usenet/incomplete" || true
_sab_set_config_misc "$sab_key" "complete_dir" "/data/usenet/complete" || true
if [ -n "${AUTH_USERNAME:-}" ] && [ -n "${AUTH_PASSWORD:-}" ]; then
_sab_set_config_misc "$sab_key" "username" "$AUTH_USERNAME" || true
_sab_set_config_misc "$sab_key" "password" "$AUTH_PASSWORD" || true
fi
_sab_set_category "$sab_key" "movies" "movies" || true
_sab_set_category "$sab_key" "tv" "tv" || true
# Optional Usenet NNTP server credentials stored in secrets/usenet_*.txt
local nntp_host="" nntp_port="563" nntp_ssl="1" nntp_user="" nntp_pass=""
[ -s "$INSTALL_DIR/secrets/usenet_host.txt" ] && nntp_host=$(tr -d '\r\n' < "$INSTALL_DIR/secrets/usenet_host.txt")
[ -s "$INSTALL_DIR/secrets/usenet_port.txt" ] && nntp_port=$(tr -d '\r\n' < "$INSTALL_DIR/secrets/usenet_port.txt")
[ -s "$INSTALL_DIR/secrets/usenet_ssl.txt" ] && nntp_ssl=$(tr -d '\r\n' < "$INSTALL_DIR/secrets/usenet_ssl.txt")
[ -s "$INSTALL_DIR/secrets/usenet_user.txt" ] && nntp_user=$(tr -d '\r\n' < "$INSTALL_DIR/secrets/usenet_user.txt")
[ -s "$INSTALL_DIR/secrets/usenet_password.txt" ] && nntp_pass=$(tr -d '\r\n' < "$INSTALL_DIR/secrets/usenet_password.txt")
if [ -n "$nntp_host" ]; then
if _sab_set_server "$sab_key" "$nntp_host" "$nntp_port" "$nntp_ssl" "$nntp_user" "$nntp_pass"; then
log_step "SABnzbd: wired NNTP server (${nntp_host}:${nntp_port})"
else
log_step_fail "SABnzbd: failed to configure NNTP server (${nntp_host})"
fi
fi
log_step "SABnzbd: configured folders (/data/usenet/complete) & categories (movies, tv)"
return 0
}
# Wire SABnzbd as a download client inside Radarr or Sonarr via /api/v3/downloadclient/schema.
arr_build_sabnzbd_payload() {
local schemas_json="$1"
local sab_key="$2"
local category_field="$3"
local category_val="$4"
local sab_host="${5:-sabnzbd}"
local sab_port="${6:-8080}"
local base_schema
base_schema=$(printf '%s' "$schemas_json" | jq '[.[] | select(.implementation == "Sabnzbd")][0] // empty' 2>/dev/null || true)
if [ -n "$base_schema" ]; then
printf '%s' "$base_schema" | jq -c \
--arg host "$sab_host" \
--argjson port "$sab_port" \
--arg key "$sab_key" \
--arg cf "$category_field" \
--arg cv "$category_val" '
.enable = true |
.removeCompletedDownloads = true |
.removeFailedDownloads = true |
.name = "SABnzbd" |
.priority = 1 |
.tags = [] |
.fields = [.fields[] |
if .name == "host" then .value = $host
elif .name == "port" then .value = $port
elif .name == "useSsl" then .value = false
elif .name == "urlBase" then .value = ""
elif .name == "apiKey" then .value = $key
elif .name == $cf then .value = $cv
else . end
]
' 2>/dev/null || echo ""
return 0
fi
jq -nc \
--arg host "$sab_host" \
--argjson port "$sab_port" \
--arg key "$sab_key" \
--arg cf "$category_field" \
--arg cv "$category_val" '
{
enable: true,
removeCompletedDownloads: true,
removeFailedDownloads: true,
name: "SABnzbd",
implementation: "Sabnzbd",
implementationName: "SABnzbd",
configContract: "SabnzbdSettings",
priority: 1,
tags: [],
fields: [
{name: "host", value: $host},
{name: "port", value: $port},
{name: "useSsl", value: false},
{name: "urlBase", value: ""},
{name: "apiKey", value: $key},
{name: $cf, value: $cv}
]
}'
}
arr_configure_sabnzbd() {
sabnzbd_enabled || return 0
if [ "$#" -eq 0 ]; then
local rc=0
local r_key="${RADARR_API_KEY:-}" s_key="${SONARR_API_KEY:-}"
[ -z "$r_key" ] && [ -f "${INSTALL_DIR:-}/config/radarr/config.xml" ] && \
r_key=$(sed -n 's/.*<ApiKey>\(.*\)<\/ApiKey>.*/\1/p' "$INSTALL_DIR/config/radarr/config.xml" | head -1)
[ -z "$s_key" ] && [ -f "${INSTALL_DIR:-}/config/sonarr/config.xml" ] && \
s_key=$(sed -n 's/.*<ApiKey>\(.*\)<\/ApiKey>.*/\1/p' "$INSTALL_DIR/config/sonarr/config.xml" | head -1)
if [ -n "$r_key" ]; then
arr_configure_sabnzbd "Radarr" "7878" "$r_key" "movieCategory" "movies" || rc=1
fi
if [ -n "$s_key" ]; then
arr_configure_sabnzbd "Sonarr" "8989" "$s_key" "tvCategory" "tv" || rc=1
fi
return "$rc"
fi
local app_name="$1"
local port="$2"
local arr_apikey="$3"
local category_field="$4"
local category_val="$5"
local sab_key=""
[ -s "$INSTALL_DIR/secrets/sabnzbd_api_key.txt" ] && sab_key=$(cat "$INSTALL_DIR/secrets/sabnzbd_api_key.txt" 2>/dev/null || true)
[ -z "$sab_key" ] && sab_key=$(sabnzbd_extract_api_key "$INSTALL_DIR/config/sabnzbd/sabnzbd.ini" || true)
if [ -z "$sab_key" ]; then
log_step_fail "${app_name}: SABnzbd API key missing — cannot wire Usenet client"
return 1
fi
local clients schemas payload existing_id result
clients=$(api_get "$port" "/api/v3/downloadclient" "$arr_apikey" || echo "[]")
schemas=$(api_get "$port" "/api/v3/downloadclient/schema" "$arr_apikey" || echo "[]")
payload=$(arr_build_sabnzbd_payload "$schemas" "$sab_key" "$category_field" "$category_val")
if [ -z "$payload" ]; then
log_step_fail "${app_name}: failed to build SABnzbd payload"
return 1
fi
existing_id=$(printf '%s' "$clients" | jq -r '[.[] | select(.implementation == "Sabnzbd")][0].id // empty' 2>/dev/null || true)
if [ -n "$existing_id" ]; then
payload=$(printf '%s' "$payload" | jq -c --argjson id "$existing_id" '.id = $id')
result=$(api_put "$port" "/api/v3/downloadclient/${existing_id}" "$arr_apikey" "$payload" || echo "")
else
result=$(api_post_force "$port" "/api/v3/downloadclient" "$arr_apikey" "$payload" || echo "")
fi
if jq_json_has_key "$result" "id"; then
log_step "${app_name}: wired SABnzbd download client (category: ${category_val})"
return 0
fi
log_step_fail "${app_name}: failed to wire SABnzbd download client"
return 1
}
sabnzbd_change_credentials() {
sabnzbd_enabled || return 0
local sab_key=""
[ -s "$INSTALL_DIR/secrets/sabnzbd_api_key.txt" ] && sab_key=$(cat "$INSTALL_DIR/secrets/sabnzbd_api_key.txt" 2>/dev/null || true)
[ -z "$sab_key" ] && sab_key=$(sabnzbd_extract_api_key "$INSTALL_DIR/config/sabnzbd/sabnzbd.ini" || true)
[ -n "$sab_key" ] || { log_step_fail "SABnzbd: API key missing"; return 1; }
if _sab_set_config_misc "$sab_key" "username" "$AUTH_USERNAME" && \
_sab_set_config_misc "$sab_key" "password" "$AUTH_PASSWORD"; then
log_step "SABnzbd: set login (${AUTH_USERNAME})"
return 0
fi
log_step_fail "SABnzbd: failed to update login"
return 1
}

8
lib/vpn.sh Normal file → Executable file
View file

@ -1,4 +1,5 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr VPN helpers — sourced by entry points that handle VPN orchestration
# Requires: lib/core.sh (for logging, safe_source)
@ -68,10 +69,11 @@ validate_vpn_secrets() {
return 0
fi
# Source .env for WIREGUARD_ADDRESSES
# Read WIREGUARD_ADDRESSES from .env without polluting caller exports
local WIREGUARD_ADDRESSES="${WIREGUARD_ADDRESSES:-}"
local _env_file="$_install_dir/.env"
if [ -f "$_env_file" ]; then
set -a; safe_source "$_env_file"; set +a
if [ -f "$_env_file" ] && grep -qE '^WIREGUARD_ADDRESSES=' "$_env_file" 2>/dev/null; then
WIREGUARD_ADDRESSES=$(_pointer_get "$_env_file" "WIREGUARD_ADDRESSES")
fi
local _secrets_dir="$_install_dir/secrets"

9
migrations/001_add_bazarr.sh Normal file → Executable file
View file

@ -1,11 +1,11 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Migration: ensure Bazarr is part of the stack and can be wired.
# Skip if the install already defines a bazarr service (user-managed).
migration_id="001_add_bazarr"
migration_description="Add Bazarr subtitle service (compose + config dir + wire flag)"
# Return 0 = skip (already satisfied / user owns it)
migration_should_skip() {
local install_dir="${1:-}"
local f
@ -16,25 +16,18 @@ migration_should_skip() {
"$install_dir/compose/direct-access.yaml"
do
[ -f "$f" ] || continue
# Service key at start of a line (compose service name)
if grep -qE '^[[:space:]]*bazarr:[[:space:]]*$' "$f" 2>/dev/null; then
# If only custom.yaml has it, user added it themselves before our managed base did
if [ "$(basename "$f")" = "custom.yaml" ]; then
return 0
fi
# base.yaml already has bazarr: either previous upgrade or we just applied managed files.
# Skip only if config already looks configured (api key secret from prior wire).
if [ -s "$install_dir/secrets/bazarr_api_key.txt" ]; then
return 0
fi
fi
done
# Running container not from our compose project is rare; still skip re-wiring if present
# and has non-empty bazarr config from a manual setup
if [ -d "$install_dir/config/bazarr" ] && [ -n "$(find "$install_dir/config/bazarr" -type f 2>/dev/null | head -1)" ]; then
if ! grep -qE '^[[:space:]]*bazarr:[[:space:]]*$' "$install_dir/compose/base.yaml" 2>/dev/null; then
# Data dir exists but base has no bazarr — treat as user-managed external
return 0
fi
fi

7
migrations/002_remove_portainer.sh Normal file → Executable file
View file

@ -1,21 +1,19 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Migration: drop Portainer from the default stack (use assemblrr CLI instead).
# Skip if the user still defines portainer in custom.yaml (optional path).
migration_id="002_remove_portainer"
migration_description="Remove Portainer container when no longer in managed compose"
# Return 0 = skip
migration_should_skip() {
local install_dir="${1:-}"
local f="$install_dir/compose/custom.yaml"
# User opted back in via custom overlay — leave their Portainer alone
if [ -f "$f" ] && grep -qE '^[[:space:]]*portainer:[[:space:]]*$' "$f" 2>/dev/null; then
return 0
fi
# Nothing to do if no container is present
if command -v docker >/dev/null 2>&1; then
if ! docker ps -a --format '{{.Names}}' 2>/dev/null | grep -qx 'portainer'; then
return 0
@ -28,8 +26,7 @@ migration_should_skip() {
}
migration_apply() {
local install_dir="${1:-}"
# Container only — leave config/portainer on disk (user can delete manually)
local _install_dir="${1:-}"
if command -v docker >/dev/null 2>&1; then
if docker rm -f portainer >/dev/null 2>&1; then
echo "Removed portainer container (dropped from default stack)" >&2

2
migrations/003_standardize_quality_profiles.sh Normal file → Executable file
View file

@ -1,4 +1,5 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Migration: remove legacy Recyclarr template files superseded by 4K / 1080p standardization.
migration_id="003_standardize_quality_profiles"
@ -13,7 +14,6 @@ LEGACY_RECYCLARR_INCLUDES=(
"sonarr-web-2160.yml"
)
# Return 0 = skip
migration_should_skip() {
local install_dir="${1:-}"
local legacy_file

View file

@ -0,0 +1,51 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Migration: Jellyfin 12.4 upgrade readiness, SABnzbd dir prep, and new overlay flag defaults.
migration_id="004_jellyfin_12_and_stack_revival"
migration_description="Backfill feature flags, create config/sabnzbd, and emit Jellyfin 12.4 upgrade notes"
_m004_append_if_missing() {
local file="$1" key="$2" line="$3"
[ -f "$file" ] || return 0
if ! grep -qE "^[[:space:]]*${key}=" "$file" 2>/dev/null; then
printf '%s\n' "$line" >> "$file"
fi
}
migration_should_skip() {
local install_dir="${1:-}"
[ -d "$install_dir/config/sabnzbd" ] || return 1
local key
for key in VUETORRENT_ENABLED GPU_TRANSCODING BYPARR_ENABLED USENET_ENABLED; do
if [ -f "$install_dir/.env" ] && ! grep -qE "^[[:space:]]*${key}=" "$install_dir/.env" 2>/dev/null; then
return 1
fi
if [ -f "$install_dir/.assemblrr-config" ] && ! grep -qE "^[[:space:]]*${key}=" "$install_dir/.assemblrr-config" 2>/dev/null; then
return 1
fi
done
return 0
}
migration_apply() {
local install_dir="${1:-}"
mkdir -p "$install_dir/config/sabnzbd"
_m004_append_if_missing "$install_dir/.env" "VUETORRENT_ENABLED" "VUETORRENT_ENABLED=n"
_m004_append_if_missing "$install_dir/.env" "GPU_TRANSCODING" "GPU_TRANSCODING=none"
_m004_append_if_missing "$install_dir/.env" "BYPARR_ENABLED" "BYPARR_ENABLED=n"
_m004_append_if_missing "$install_dir/.env" "USENET_ENABLED" "USENET_ENABLED=n"
_m004_append_if_missing "$install_dir/.assemblrr-config" "VUETORRENT_ENABLED" 'VUETORRENT_ENABLED="n"'
_m004_append_if_missing "$install_dir/.assemblrr-config" "GPU_TRANSCODING" 'GPU_TRANSCODING="none"'
_m004_append_if_missing "$install_dir/.assemblrr-config" "BYPARR_ENABLED" 'BYPARR_ENABLED="n"'
_m004_append_if_missing "$install_dir/.assemblrr-config" "USENET_ENABLED" 'USENET_ENABLED="n"'
if [ -f "$install_dir/.assemblrr-config" ] && grep -qE '^MEDIA_SERVICE="(emby|plex)"' "$install_dir/.assemblrr-config" 2>/dev/null; then
echo "NOTICE: Emby/Plex are no longer in core compose/base.yaml; move your container override to compose/custom.yaml (see compose/examples/custom.yaml.example). Existing config/* data was untouched." >&2
fi
echo "NOTICE: Stack upgraded to Jellyfin 12.4 (Authorization: MediaBrowser auth). Keep your pre-upgrade backup in case rollback is ever needed." >&2
return 0
}

33
platform/linux/bootstrap.sh Normal file → Executable file
View file

@ -1,21 +1,9 @@
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Linux Bootstrap Script
# Clones the repository (branch, tag, or commit SHA) and launches bin/setup.sh
set -euo pipefail
# assemblrr Bootstrap Script
# Clones the repository and launches setup.sh
#
# Usage (bash/zsh):
# bash <(curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh)
# bash <(curl -fsSL ...) --ref dev
# ASSEMBLRR_REF=dev bash <(curl -fsSL ...)
# Usage (fish):
# bash (curl -fsSL ... | psub)
# bash (curl -fsSL ... | psub) --ref dev
#
# Ref selection (first match wins among flags; env is the default):
# --ref REF | --branch REF | ASSEMBLRR_REF (default: main)
# Remaining args are passed to bin/setup.sh.
REPO="https://github.com/soulis-1256/assemblrr"
REF="${ASSEMBLRR_REF:-main}"
setup_args=()
@ -24,7 +12,7 @@ while [ $# -gt 0 ]; do
case "$1" in
--ref|--branch)
if [ -z "${2:-}" ]; then
echo "error: $1 requires a value (branch, tag, or commit-ish)" >&2
echo "error: $1 requires a value (branch, tag, or commit SHA)" >&2
exit 1
fi
REF="$2"
@ -50,10 +38,17 @@ cleanup() { rm -rf "$TMPDIR"; }
trap cleanup EXIT
echo "Cloning assemblrr @ ${REF}..."
if ! git clone --depth=1 --branch "$REF" "$REPO" "$TMPDIR"; then
echo "error: failed to clone ${REPO} @ ${REF}" >&2
exit 1
if ! git clone --depth=1 --branch "$REF" "$REPO" "$TMPDIR" 2>/dev/null; then
rm -rf "$TMPDIR"
mkdir -p "$TMPDIR"
if ! git clone --depth=1 "$REPO" "$TMPDIR" \
|| ! git -C "$TMPDIR" fetch --depth=1 origin "$REF" 2>/dev/null \
|| ! git -C "$TMPDIR" checkout -q FETCH_HEAD 2>/dev/null; then
echo "error: failed to clone/checkout ${REPO} @ ${REF}" >&2
exit 1
fi
fi
export ASSEMBLRR_INSTALL_REF="$REF"
cd "$TMPDIR"
bash bin/setup.sh "${setup_args[@]}"

View file

@ -1,13 +1,6 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Dev Bootstrap
# Copies local project files to WSL2 and runs setup.sh
# Alternative to bootstrap.ps1 — skips git clone, uses local files instead
# Usage:
# .\bootstrap-dev.ps1 Show help
# .\bootstrap-dev.ps1 -Full Full setup (copy files + run setup.sh)
# .\bootstrap-dev.ps1 -Full -Clean Uninstall first, then full setup
# .\bootstrap-dev.ps1 -Update Only copy updated files to WSL2
# .\bootstrap-dev.ps1 -Exec <cmd> Run an assemblrr CLI command in WSL2
# .\bootstrap-dev.ps1 -Help Show this help screen
# Copies local project files to WSL2 and runs setup.sh / update / exec
[CmdletBinding()]
param(
@ -19,6 +12,7 @@ param(
)
$ErrorActionPreference = "Stop"
$env:WSL_UTF8 = "1"
$ProjectDir = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$AppName = "assemblrr"
@ -28,47 +22,35 @@ function Show-Help {
Write-Host "assemblrr Dev Bootstrap" -ForegroundColor Cyan
Write-Host "========================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Copies local project files to WSL2 for development." -ForegroundColor White
Write-Host "Alternative to bootstrap.ps1 - skips git clone, uses local files instead." -ForegroundColor White
Write-Host ""
Write-Host "Usage:" -ForegroundColor Yellow
Write-Host " .\bootstrap-dev.ps1 Show this help screen"
Write-Host " .\bootstrap-dev.ps1 -Full Full setup: copy files to WSL2 and run setup.sh"
Write-Host " .\bootstrap-dev.ps1 -Full -Clean Uninstall first, then full setup"
Write-Host " .\bootstrap-dev.ps1 -Update Quick update: only copy changed files to WSL2"
Write-Host " .\bootstrap-dev.ps1 -Update Sync managed files into WSL2 install"
Write-Host " .\bootstrap-dev.ps1 -Exec <cmd> Run an assemblrr CLI command in WSL2"
Write-Host " .\bootstrap-dev.ps1 -Help Show this help screen"
Write-Host ""
Write-Host "Parameters:" -ForegroundColor Yellow
Write-Host " -Full Copy project files to WSL2 and launch setup.sh"
Write-Host " -Clean Uninstall existing installation (use with -Full for clean reinstall)"
Write-Host " -Update Copy project files to WSL2 without running setup.sh"
Write-Host " Use this when you made changes on Windows that need to be"
Write-Host " reflected in the WSL2 environment"
Write-Host " -Exec Run an assemblrr CLI command in WSL2 (e.g. -Exec 'uninstall -f')"
Write-Host " Requires an existing installation; runs with full TTY support"
Write-Host " -Help Show this help screen"
Write-Host ""
}
function Find-WSL2Distro {
$distro = ""
try {
$guid = (Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss").DefaultDistribution
$distro = (Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss\$guid").DistributionName
} catch {
$output = wsl --list --verbose 2>$null
$line = $output | Where-Object { $_ -match '^\*' }
if ($line) {
$distro = ($line -replace '^\*\s+', '' -replace '\s+.*', '').Trim()
$distro = $distro -replace "^\xEF\xBB\xBF", ""
if ($distro -and $distro -notin @("docker-desktop", "docker-desktop-data")) {
return $distro
}
} catch { }
$output = wsl --list --quiet 2>$null
foreach ($rawLine in $output) {
$candidate = ($rawLine -replace "\x00", "" -replace "^\xEF\xBB\xBF", "").Trim()
if ($candidate -and $candidate -notin @("docker-desktop", "docker-desktop-data")) {
return $candidate
}
}
return $distro
return ""
}
function Copy-ProjectToWSL2 {
param([string]$Distro)
if (-not $AppName) {
@ -77,23 +59,21 @@ function Copy-ProjectToWSL2 {
}
Write-Host "Copying project to WSL2 /tmp/$AppName..." -ForegroundColor Yellow
# Safety check: refuse to remove if path is a symlink (prevents TOCTOU race condition)
wsl -d $Distro -- bash -c "if [ -L /tmp/$AppName ]; then echo 'Refusing to remove symlink at /tmp/$AppName' >&2; exit 1; fi; rm -rf /tmp/$AppName 2>/dev/null; mkdir -p /tmp/$AppName"
wsl -d $Distro -- bash -c "if [ -L '/tmp/$AppName' ]; then echo 'Refusing symlink' >&2; exit 1; fi; rm -rf '/tmp/$AppName' 2>/dev/null; mkdir -p '/tmp/$AppName'"
$driveLetter = $ProjectDir.Substring(0,1).ToLower()
$driveLetter = $ProjectDir.Substring(0, 1).ToLower()
$wslSourcePath = "/mnt/$driveLetter" + ($ProjectDir.Substring(2) -replace '\\', '/')
wsl -d $Distro -- bash -c "cp -r $wslSourcePath/* /tmp/$AppName/ && cp -r $wslSourcePath/.env.example $wslSourcePath/.gitignore /tmp/$AppName/ 2>/dev/null; true"
$quotedSrc = "'" + ($wslSourcePath -replace "'", "'\"'\"'") + "'"
wsl -d $Distro -- bash -c "cp -r $quotedSrc/. '/tmp/$AppName/' 2>/dev/null || true"
wsl -d $Distro -- bash -c "chmod +x /tmp/$AppName/bin/setup.sh /tmp/$AppName/bin/cli.sh /tmp/$AppName/bin/docker-install.sh /tmp/$AppName/bin/config.sh /tmp/$AppName/lib/*.sh /tmp/$AppName/scripts/*.sh 2>/dev/null"
# Convert CRLF to LF (Windows line endings break bash / Dockerfiles / Python)
wsl -d $Distro -- bash -c "chmod +x /tmp/$AppName/bin/*.sh /tmp/$AppName/lib/*.sh /tmp/$AppName/scripts/*.sh /tmp/$AppName/migrations/*.sh 2>/dev/null || true"
wsl -d $Distro -- bash -c "find /tmp/$AppName -type f \( -name '*.sh' -o -name '*.py' -o -name '*.yaml' -o -name '*.yml' -o -name '*.conf' -o -name '.env.example' -o -name 'Dockerfile' -o -name '*.Dockerfile' \) -exec sed -i 's/\r$//' {} + 2>/dev/null; true"
Write-Host "Files copied successfully." -ForegroundColor Green
}
function Test-InstallConfigExists {
param([string]$Distro)
$result = wsl -d $Distro -- bash -c "cat /opt/$AppName/.$AppName-config `$HOME/$AppName/.$AppName-config `$HOME/.$AppName-config 2>/dev/null | grep INSTALL_DIRECTORY"
$result = wsl -d $Distro -- bash -c "cat `$HOME/.$AppName-config /opt/$AppName/.$AppName-config `$HOME/$AppName/.$AppName-config 2>/dev/null | grep INSTALL_DIRECTORY"
return (-not [string]::IsNullOrWhiteSpace($result))
}
@ -110,36 +90,17 @@ function Test-InstallationExists {
function Invoke-ResidueCleanup {
param([string]$Distro)
Write-Host "Partial installation detected without runtime config. Cleaning known WSL2 dev paths..." -ForegroundColor Yellow
$cleanupScript = @"
set -euo pipefail
source /tmp/$AppName/lib/core.sh
install_dir="`$HOME/$AppName"
media_dir="`$HOME/$AppName-media"
cli_path="`$HOME/.local/bin/$AppName"
system_cli="/usr/local/bin/$AppName"
for dir in "`$install_dir" "`$media_dir"; do
case "`$dir" in
"`$HOME/$AppName"|"`$HOME/$AppName-media") ;;
*) echo "Refusing unexpected cleanup path: `$dir" >&2; exit 1 ;;
esac
if [ -e "`$dir" ]; then
safe_rm_rf "`$dir"
fi
for dir in "`$HOME/$AppName" "`$HOME/$AppName-media"; do
[ -e "`$dir" ] && safe_rm_rf "`$dir"
done
rm -f "`$cli_path" 2>/dev/null || true
rm -f "`$system_cli" 2>/dev/null || true
rm -f "`$HOME/.local/bin/$AppName" "/usr/local/bin/$AppName" 2>/dev/null || true
"@
$cleanupScriptBytes = [System.Text.Encoding]::UTF8.GetBytes($cleanupScript)
$cleanupScriptBase64 = [Convert]::ToBase64String($cleanupScriptBytes)
$remoteCleanupScript = "/tmp/$AppName-cleanup-residue.sh"
wsl -d $Distro -- bash -c "printf '%s' '$cleanupScriptBase64' | base64 -d | sed 's/\r$//' > '$remoteCleanupScript' && bash '$remoteCleanupScript'; status=`$?; rm -f '$remoteCleanupScript'; exit `$status"
$b64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($cleanupScript))
wsl -d $Distro -- bash -c "printf '%s' '$b64' | base64 -d | sed 's/\r$//' | bash"
}
function Invoke-Uninstall {
@ -148,55 +109,39 @@ function Invoke-Uninstall {
Write-Host "No existing installation to clean." -ForegroundColor Yellow
return
}
if (-not (Test-InstallConfigExists -Distro $Distro)) {
Invoke-ResidueCleanup -Distro $Distro
if ($LASTEXITCODE -ne 0) {
Write-Host "Residue cleanup failed." -ForegroundColor Red
exit 1
}
Write-Host "Residue cleanup complete." -ForegroundColor Green
if ($LASTEXITCODE -ne 0) { exit 1 }
return
}
Write-Host "Uninstalling existing installation..." -ForegroundColor Yellow
wsl -d $Distro -- bash -c "source /tmp/$AppName/branding.conf && bash /tmp/$AppName/bin/cli.sh uninstall -f"
if ($LASTEXITCODE -ne 0) {
if ($ContinueOnError -and -not (Test-InstallationExists -Distro $Distro)) {
Write-Host "Uninstall reported an error, but no installation files remain. Continuing..." -ForegroundColor Yellow
} else {
if (-not $ContinueOnError -or (Test-InstallationExists -Distro $Distro)) {
Write-Host "Uninstall failed." -ForegroundColor Red
exit 1
}
} else {
Write-Host "Uninstall complete." -ForegroundColor Green
}
}
# No parameters or -Help → show help
if (-not $Full -and -not $Clean -and -not $Update -and -not $Exec -or $Help) {
Show-Help
exit 0
}
# Detect WSL2 distro
$defaultDistro = Find-WSL2Distro
if (-not $defaultDistro) {
Write-Host "No WSL2 distro found." -ForegroundColor Red
Write-Host "No usable WSL2 distro found." -ForegroundColor Red
exit 1
}
Write-Host "Using WSL2 distro: $defaultDistro" -ForegroundColor Cyan
# -Clean standalone: copy files first (need CLI for uninstall), then uninstall and exit
if ($Clean -and -not $Full) {
Copy-ProjectToWSL2 -Distro $defaultDistro
Invoke-Uninstall -Distro $defaultDistro
exit 0
}
# -Update/-Exec: verify installation exists before doing anything
if ($Update -or $Exec) {
if (-not (Test-InstallationExists -Distro $defaultDistro)) {
Write-Host "No existing installation found. Run -Full first to set up." -ForegroundColor Red
@ -204,75 +149,38 @@ if ($Update -or $Exec) {
}
}
# Copy project files to WSL2 (skip for -Exec — CLI is already installed)
if (-not $Exec) {
Copy-ProjectToWSL2 -Distro $defaultDistro
}
# -Full: also run setup.sh
if ($Full) {
# -Clean: uninstall existing installation first
# Use CLI from /tmp (just copied) — installed CLI may be missing/broken
if ($Clean) {
Invoke-Uninstall -Distro $defaultDistro -ContinueOnError
Write-Host ""
}
Write-Host "Launching setup.sh in WSL2..." -ForegroundColor Green
Write-Host ""
# Run wsl directly in the current terminal — inherits ConPTY for full TTY/fzf support
wsl -d $defaultDistro -- bash -i -c "cd /tmp/$AppName && bash bin/setup.sh"
$setupExit = $LASTEXITCODE
if ($setupExit -ne 0) {
Write-Host ""
Write-Host "Setup did not finish. The operator CLI may already be installed in WSL." -ForegroundColor Yellow
Write-Host " wsl -d $defaultDistro -- ~/.local/bin/$AppName status" -ForegroundColor Cyan
Write-Host " wsl -d $defaultDistro -- ~/.local/bin/$AppName uninstall" -ForegroundColor Cyan
Write-Host ""
exit $setupExit
}
wsl -d $defaultDistro -- bash -i -c "cd '/tmp/$AppName' && bash bin/setup.sh"
exit $LASTEXITCODE
}
# -Update: sync files to install directory and reinstall CLI
if ($Update) {
Write-Host "Syncing updated files to install directory..." -ForegroundColor Yellow
Write-Host "Syncing managed files into install directory via lib/managed_files.sh..." -ForegroundColor Yellow
$updateScript = @"
#!/bin/bash
source /tmp/$AppName/branding.conf
INSTALL_DIR=""
for cfg in "/opt/`$APP_NAME/.`$APP_NAME-config" "`$HOME/`$APP_NAME/.`$APP_NAME-config" "`$HOME/.`$APP_NAME-config"; do
if [ -f "`$cfg" ]; then
INSTALL_DIR=`$(grep INSTALL_DIRECTORY "`$cfg" | cut -d= -f2 | tr -d '"' | tr -d "'")
break
fi
done
if [ -z "`$INSTALL_DIR" ]; then
echo "No existing installation found. Run -Full first to set up." >&2
exit 1
fi
echo "Install directory: `$INSTALL_DIR"
cp /tmp/$AppName/bin/cli.sh /tmp/$AppName/bin/setup.sh /tmp/$AppName/bin/docker-install.sh /tmp/$AppName/bin/config.sh /tmp/$AppName/branding.conf "`$INSTALL_DIR/"
rm -f "`$INSTALL_DIR/configure.sh" 2>/dev/null || true
mkdir -p "`$INSTALL_DIR/lib"
cp /tmp/$AppName/lib/*.sh "`$INSTALL_DIR/lib/"
cp /tmp/$AppName/compose/base.yaml /tmp/$AppName/compose/vpn.yaml /tmp/$AppName/compose/direct-access.yaml "`$INSTALL_DIR/compose/"
mkdir -p "`$INSTALL_DIR/compose/examples"
cp /tmp/$AppName/compose/examples/custom.yaml.example "`$INSTALL_DIR/compose/examples/" 2>/dev/null || true
cp /tmp/$AppName/.env.example "`$INSTALL_DIR/" 2>/dev/null || true
mkdir -p "`$INSTALL_DIR/templates/recyclarr/includes"
cp /tmp/$AppName/templates/recyclarr/recyclarr.yml "`$INSTALL_DIR/templates/recyclarr/"
cp /tmp/$AppName/templates/recyclarr/includes/*.yml "`$INSTALL_DIR/templates/recyclarr/includes/"
mkdir -p "`$INSTALL_DIR/scripts"
cp /tmp/$AppName/scripts/* "`$INSTALL_DIR/scripts/"
echo "Files synced to install directory"
mkdir -p "`$HOME/.local/bin/lib"
cp "`$INSTALL_DIR/lib/"*.sh "`$HOME/.local/bin/lib/"
cp "`$INSTALL_DIR/cli.sh" "`$HOME/.local/bin/`$APP_CLI_NAME" && chmod +x "`$HOME/.local/bin/`$APP_CLI_NAME"
rm -f "/usr/local/bin/`$APP_CLI_NAME" 2>/dev/null || true
echo "CLI reinstalled to `$HOME/.local/bin/`$APP_CLI_NAME"
set -euo pipefail
source /tmp/$AppName/lib/core.sh
source /tmp/$AppName/lib/branding.sh
source /tmp/$AppName/lib/compose.sh
source /tmp/$AppName/lib/managed_files.sh
source /tmp/$AppName/lib/upgrade.sh
load_branding /tmp/$AppName
INSTALL_DIR=`$(find_install_directory || true)
[ -n "`$INSTALL_DIR" ] || { echo "No existing installation found." >&2; exit 1; }
apply_managed_files /tmp/$AppName "`$INSTALL_DIR" 0
refresh_user_cli "`$INSTALL_DIR"
echo "Synced managed files to `$INSTALL_DIR and updated CLI wrapper"
"@
$updateScript | wsl -d $defaultDistro -- bash -c "sed 's/\r$//' | bash"
$b64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($updateScript))
wsl -d $defaultDistro -- bash -c "printf '%s' '$b64' | base64 -d | sed 's/\r$//' | bash"
if ($LASTEXITCODE -ne 0) {
Write-Host "Update failed." -ForegroundColor Red
exit 1
@ -280,12 +188,7 @@ echo "CLI reinstalled to `$HOME/.local/bin/`$APP_CLI_NAME"
Write-Host "Update complete." -ForegroundColor Green
}
# -Exec: run an assemblrr CLI command in WSL2
if ($Exec) {
Write-Host "Running assemblrr $Exec in WSL2..." -ForegroundColor Green
Write-Host ""
# Run wsl directly in the current terminal — inherits ConPTY for full TTY/fzf support
# bash -l sources .profile (which has PATH set by install_cli)
Write-Host "Running $AppName $Exec in WSL2..." -ForegroundColor Green
wsl -d $defaultDistro -- bash -l -c "$AppName $Exec"
}

View file

@ -1,3 +1,4 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# assemblrr Windows Bootstrap
# Clones the repository, copies to WSL2, and launches setup.sh
#
@ -5,8 +6,6 @@
# irm https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/windows/bootstrap.ps1 | iex
# $env:ASSEMBLRR_REF = "dev"; irm ... | iex
# .\bootstrap.ps1 -Ref dev
#
# Ref: -Ref / -Branch / $env:ASSEMBLRR_REF (default: main)
param(
[Parameter(Mandatory = $false)]
@ -15,6 +14,7 @@ param(
)
$ErrorActionPreference = "Stop"
$env:WSL_UTF8 = "1"
$AppName = "assemblrr"
$RepoURL = "https://github.com/soulis-1256/assemblrr"
@ -27,93 +27,101 @@ if (-not $Ref) {
}
}
# Step 1: Check WSL2 is available
if (-not (Get-Command wsl -ErrorAction SilentlyContinue)) {
Write-Host "WSL2 is not installed." -ForegroundColor Red
Write-Host ""
Write-Host "Please install Docker Desktop for Windows first:" -ForegroundColor Yellow
Write-Host "https://docs.docker.com/desktop/install/windows-install/" -ForegroundColor Cyan
Write-Host ""
Write-Host "Docker Desktop will set up WSL2 automatically." -ForegroundColor Yellow
Write-Host "Please install Docker Desktop for Windows first: https://docs.docker.com/desktop/install/windows-install/" -ForegroundColor Yellow
exit 1
}
# Step 2: Detect default WSL2 distro from Windows Registry
$defaultDistro = ""
try {
$defaultGuid = (Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss").DefaultDistribution
$defaultDistro = (Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss\$defaultGuid").DistributionName
} catch {
# Fallback: parse wsl --list --verbose output
$wslOutput = wsl --list --verbose 2>$null
$defaultLine = $wslOutput | Where-Object { $_ -match '^\*' }
if ($defaultLine) {
# Parse the * marker line: "* archlinux Running 2"
$defaultDistro = ($defaultLine -replace '^\*\s+', '' -replace '\s+.*', '').Trim()
# Strip BOM if present
$defaultDistro = $defaultDistro -replace "^\xEF\xBB\xBF", ""
}
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
Write-Host "Git for Windows is required to clone the repository." -ForegroundColor Red
Write-Host "Install Git (https://git-scm.com/download/win) and re-run this script." -ForegroundColor Yellow
exit 1
}
function Get-TargetWSLDistro {
try {
$defaultGuid = (Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss").DefaultDistribution
$name = (Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss\$defaultGuid").DistributionName
if ($name -and $name -notin @("docker-desktop", "docker-desktop-data")) {
return $name
}
} catch { }
$wslOutput = wsl --list --quiet 2>$null
foreach ($rawLine in $wslOutput) {
$candidate = ($rawLine -replace "\x00", "" -replace "^\xEF\xBB\xBF", "").Trim()
if ($candidate -and $candidate -notin @("docker-desktop", "docker-desktop-data")) {
return $candidate
}
}
return ""
}
$defaultDistro = Get-TargetWSLDistro
if (-not $defaultDistro) {
Write-Host "No WSL2 distribution found." -ForegroundColor Red
Write-Host ""
Write-Host "Please install Docker Desktop for Windows first:" -ForegroundColor Yellow
Write-Host "https://docs.docker.com/desktop/install/windows-install/" -ForegroundColor Cyan
Write-Host "No usable WSL2 Linux distribution found (excluding docker-desktop)." -ForegroundColor Red
Write-Host "Install Ubuntu on WSL2 with: wsl --install -d Ubuntu" -ForegroundColor Yellow
exit 1
}
Write-Host "Using WSL2 distro: $defaultDistro" -ForegroundColor Green
Write-Host ""
# Step 4: Clone repository to temporary Windows directory
Write-Host "Cloning repository @ $Ref..." -ForegroundColor White
$tempDir = [System.IO.Path]::GetTempPath() + $AppName + "." + [System.Guid]::NewGuid().ToString("N").Substring(0, 8)
git clone --depth=1 --branch $Ref $RepoURL $tempDir
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("$AppName." + [System.Guid]::NewGuid().ToString("N").Substring(0, 8))
git clone --depth=1 --branch $Ref $RepoURL $tempDir 2>$null
if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to clone repository @ $Ref. Is git installed and is the ref valid?" -ForegroundColor Red
Remove-Item -Recurse -Force $tempDir -ErrorAction SilentlyContinue
git clone --depth=1 $RepoURL $tempDir
if ($LASTEXITCODE -eq 0) {
git -C $tempDir fetch --depth=1 origin $Ref
git -C $tempDir checkout -q FETCH_HEAD
}
}
if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to clone repository @ $Ref." -ForegroundColor Red
exit 1
}
Write-Host "Repository cloned." -ForegroundColor Green
Write-Host ""
# Step 5: Copy project files to WSL2
Write-Host "Copying project to WSL2..." -ForegroundColor White
wsl -d $defaultDistro -- bash -c "if [ -L /tmp/$AppName ]; then echo 'Refusing to remove symlink at /tmp/$AppName' >&2; exit 1; fi; rm -rf /tmp/$AppName 2>/dev/null; mkdir -p /tmp/$AppName"
wsl -d $defaultDistro -- bash -c "if [ -L '/tmp/$AppName' ]; then echo 'Refusing to remove symlink at /tmp/$AppName' >&2; exit 1; fi; rm -rf '/tmp/$AppName' 2>/dev/null; mkdir -p '/tmp/$AppName'"
# Convert Windows path to WSL path
$wslSourcePath = $tempDir -replace '\\', '/'
$driveLetter = $tempDir.Substring(0,1).ToLower()
$driveLetter = $tempDir.Substring(0, 1).ToLower()
$wslSourcePath = "/mnt/$driveLetter" + ($tempDir.Substring(2) -replace '\\', '/')
$quotedSrc = "'" + ($wslSourcePath -replace "'", "'\"'\"'") + "'"
wsl -d $defaultDistro -- bash -c "cp -r $wslSourcePath/* /tmp/$AppName/ && cp -r $wslSourcePath/.env.example $wslSourcePath/.gitignore /tmp/$AppName/ 2>/dev/null; true"
# Fix line endings and set permissions
wsl -d $defaultDistro -- bash -c "cp -r $quotedSrc/. '/tmp/$AppName/' 2>/dev/null || true"
wsl -d $defaultDistro -- bash -c "find /tmp/$AppName -type f \( -name '*.sh' -o -name '*.py' -o -name '*.yaml' -o -name '*.yml' -o -name '*.conf' -o -name '.env.example' -o -name 'Dockerfile' -o -name '*.Dockerfile' \) -exec sed -i 's/\r$//' {} + 2>/dev/null; true"
wsl -d $defaultDistro -- bash -c "chmod +x /tmp/$AppName/bin/*.sh /tmp/$AppName/lib/*.sh /tmp/$AppName/scripts/*.sh /tmp/$AppName/platform/linux/bootstrap.sh 2>/dev/null; true"
# Cleanup temp directory
Remove-Item -Recurse -Force $tempDir -ErrorAction SilentlyContinue
Write-Host "Project files copied." -ForegroundColor Green
Write-Host ""
# Step 6: Launch setup.sh in WSL2
# Translate Windows backup file paths in --restore arguments into WSL /mnt/... paths
$translatedArgs = @()
for ($i = 0; $i -lt $args.Count; $i++) {
$a = [string]$args[$i]
if ($a -match '^[A-Za-z]:\\' -and (Test-Path $a)) {
$drv = $a.Substring(0, 1).ToLower()
$translatedArgs += "/mnt/$drv" + ($a.Substring(2) -replace '\\', '/')
} else {
$translatedArgs += $a
}
}
$setupArgs = ($translatedArgs | ForEach-Object { "'" + ($_ -replace "'", "'\"'\"'") + "'" }) -join ' '
Write-Host "Launching ${AppName} setup in WSL2..." -ForegroundColor White
Write-Host ""
# Pass any PowerShell args through to setup.sh
$setupArgs = $args -join ' '
# Run wsl directly in the current terminal — inherits ConPTY for full TTY/fzf support
wsl -d $defaultDistro -- bash -i -c "cd /tmp/$AppName && bash bin/setup.sh $setupArgs"
wsl -d $defaultDistro -- bash -i -c "cd '/tmp/$AppName' && ASSEMBLRR_INSTALL_REF='$Ref' bash bin/setup.sh $setupArgs"
$setupExit = $LASTEXITCODE
if ($setupExit -ne 0) {
Write-Host ""
Write-Host "Setup did not finish. The operator CLI may already be installed in WSL." -ForegroundColor Yellow
Write-Host "From PowerShell:" -ForegroundColor White
Write-Host " wsl -d $defaultDistro -- ~/.local/bin/$AppName status" -ForegroundColor Cyan
Write-Host " wsl -d $defaultDistro -- ~/.local/bin/$AppName uninstall" -ForegroundColor Cyan
Write-Host "Or open WSL and run those same commands there." -ForegroundColor White
Write-Host ""
}
exit $setupExit

View file

@ -1,13 +1,11 @@
#!/bin/sh
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Triggered by Radarr/Sonarr after import (see lib/jellyfin.sh).
#
# POST /Library/Refresh discovers new files. A second POST cancels the
# in-progress scan. Jellyfin 10.11 can then save a new series under a TVDB
# PresentationUniqueKey while its episodes keep the series GUID as
# SeriesPresentationUniqueKey — the UI shows 0 episodes / 0 minutes even
# though the files are in the DB. Do not cancel a running scan; after the
# scan goes idle, recursively refresh any series that still look empty
# despite video files on disk.
# POST /Library/Refresh discovers new files. A second POST cancels an
# in-progress scan, which can leave newly imported series empty in Jellyfin's
# metadata DB. Do not cancel a running scan; after the scan goes idle,
# recursively refresh any series that still look empty despite video files on disk.
JF_HOST="${JELLYFIN_HOST:-jellyfin}"
JF_PORT="${JELLYFIN_PORT:-8096}"
@ -38,12 +36,12 @@ jf_refresh_scan_busy() {
}
# True when the Shows API reports no episodes but the library folder has video.
# That is the 10.11 identity-key miss (series page empty; item-by-id still works).
jf_refresh_dir_has_video() {
local dir="${1:-}"
[ -n "$dir" ] && [ -d "$dir" ] || return 1
find "$dir" \( -iname '*.mkv' -o -iname '*.mp4' -o -iname '*.m4v' \
-o -iname '*.avi' -o -iname '*.ts' -o -iname '*.m2ts' -o -iname '*.wmv' \) \
-o -iname '*.avi' -o -iname '*.ts' -o -iname '*.m2ts' -o -iname '*.wmv' \
-o -iname '*.mov' -o -iname '*.webm' -o -iname '*.mpg' -o -iname '*.mpeg' \) \
-type f -print 2>/dev/null | head -1 | grep -q .
}
@ -51,19 +49,26 @@ jf_refresh_empty_series_ids() {
printf '%s' "${1:-}" | jq -r '.Items[]? | .Id // empty' 2>/dev/null
}
jf_refresh_auth_header() {
printf 'Authorization: MediaBrowser Client="assemblrr", Device="arr-hook", DeviceId="assemblrr-refresh", Version="1.0", Token="%s"' \
"${JF_API_KEY:-}"
}
if [ "${JF_REFRESH_SOURCE_ONLY:-0}" = "1" ]; then
return 0 2>/dev/null || exit 0
fi
_JF_KEY_FROM_SECRET=0
if [ -f "/run/secrets/jellyfin_api_key.txt" ]; then
JF_API_KEY=$(cat /run/secrets/jellyfin_api_key.txt)
JF_API_KEY=$(tr -d '\r\n' < /run/secrets/jellyfin_api_key.txt)
_JF_KEY_FROM_SECRET=1
else
JF_API_KEY="${JELLYFIN_API_KEY:-}"
fi
jf_refresh_curl() {
curl -sS --connect-timeout 5 --max-time 30 \
-H "X-Emby-Token: ${JF_API_KEY}" \
-H "$(jf_refresh_auth_header)" \
"$@" 2>/dev/null
}
@ -85,15 +90,15 @@ jf_refresh_heal_after_scan() {
"http://${JF_HOST}:${JF_PORT}/Items?IncludeItemTypes=Series&Recursive=true&Fields=Path" \
|| echo "")
echo "$series_json" | jq -c '.Items[]? | {Id, Path}' 2>/dev/null | while read -r row; do
sid=$(echo "$row" | jq -r '.Id // empty')
path=$(echo "$row" | jq -r '.Path // empty')
printf '%s\n' "$series_json" | jq -c '.Items[]? | {Id, Path}' 2>/dev/null | while IFS= read -r row; do
sid=$(printf '%s' "$row" | jq -r '.Id // empty')
path=$(printf '%s' "$row" | jq -r '.Path // empty')
[ -n "$sid" ] || continue
jf_refresh_dir_has_video "$path" || continue
eps=$(jf_refresh_curl \
"http://${JF_HOST}:${JF_PORT}/Shows/${sid}/Episodes" || echo "")
if [ "$(echo "$eps" | jq -r '.TotalRecordCount // 0' 2>/dev/null || echo 0)" != "0" ]; then
if [ "$(printf '%s' "$eps" | jq -r '.TotalRecordCount // 0' 2>/dev/null || echo 0)" != "0" ]; then
continue
fi
@ -104,24 +109,46 @@ jf_refresh_heal_after_scan() {
done
}
# Acquire heal lock atomically using mkdir + atomic rename of dead-PID locks.
jf_refresh_acquire_lock() {
local attempt=0 oldpid stale
while [ "$attempt" -lt 2 ]; do
if mkdir "$JF_HEAL_LOCK_DIR" 2>/dev/null; then
echo $$ >"${JF_HEAL_LOCK_DIR}/pid"
return 0
fi
oldpid=$(cat "${JF_HEAL_LOCK_DIR}/pid" 2>/dev/null || echo "")
if [ -n "$oldpid" ] && kill -0 "$oldpid" 2>/dev/null; then
echo "Jellyfin refresh: heal already running (pid ${oldpid})"
return 1
fi
# Wait briefly in case the lock owner just created the directory and is writing pid
if [ -z "$oldpid" ] && [ "$attempt" -eq 0 ]; then
sleep 1
attempt=$((attempt + 1))
continue
fi
stale="${JF_HEAL_LOCK_DIR}.stale.$$"
if mv "$JF_HEAL_LOCK_DIR" "$stale" 2>/dev/null; then
rm -rf "$stale"
else
return 1
fi
attempt=$((attempt + 1))
done
if mkdir "$JF_HEAL_LOCK_DIR" 2>/dev/null; then
echo $$ >"${JF_HEAL_LOCK_DIR}/pid"
return 0
fi
return 1
}
if [ "${1:-}" = "--heal-only" ]; then
if [ -z "$JF_API_KEY" ]; then
echo "Jellyfin refresh: JELLYFIN_API_KEY not set" >&2
exit 1
fi
if mkdir "$JF_HEAL_LOCK_DIR" 2>/dev/null; then
echo $$ >"$JF_HEAL_LOCK_DIR/pid"
trap 'rm -rf "$JF_HEAL_LOCK_DIR"' EXIT
jf_refresh_heal_after_scan
else
oldpid=$(cat "$JF_HEAL_LOCK_DIR/pid" 2>/dev/null || echo "")
if [ -n "$oldpid" ] && kill -0 "$oldpid" 2>/dev/null; then
echo "Jellyfin refresh: heal already running (pid ${oldpid})"
exit 0
fi
rm -rf "$JF_HEAL_LOCK_DIR"
mkdir "$JF_HEAL_LOCK_DIR" 2>/dev/null || exit 0
echo $$ >"$JF_HEAL_LOCK_DIR/pid"
if jf_refresh_acquire_lock; then
trap 'rm -rf "$JF_HEAL_LOCK_DIR"' EXIT
jf_refresh_heal_after_scan
fi
@ -144,9 +171,9 @@ SCAN_STATE=$(jf_refresh_scan_state "$TASKS_JSON")
if jf_refresh_scan_busy "$SCAN_STATE"; then
echo "Jellyfin refresh: scan already ${SCAN_STATE}, not cancelling"
else
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 \
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 --max-time 15 \
-X POST \
-H "X-Emby-Token: ${JF_API_KEY}" \
-H "$(jf_refresh_auth_header)" \
"http://${JF_HOST}:${JF_PORT}/Library/Refresh" 2>/dev/null || echo "000")
if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
@ -164,12 +191,19 @@ case "$SCRIPT_PATH" in
/*) ;;
*) SCRIPT_PATH="$(pwd)/$SCRIPT_PATH" ;;
esac
nohup env \
JELLYFIN_HOST="$JF_HOST" \
JELLYFIN_PORT="$JF_PORT" \
JELLYFIN_API_KEY="$JF_API_KEY" \
JF_REFRESH_HEAL_POLL_SEC="$JF_REFRESH_HEAL_POLL_SEC" \
JF_REFRESH_HEAL_MAX_POLLS="$JF_REFRESH_HEAL_MAX_POLLS" \
JF_HEAL_LOCK_DIR="$JF_HEAL_LOCK_DIR" \
_env_args=(
"JELLYFIN_HOST=$JF_HOST"
"JELLYFIN_PORT=$JF_PORT"
"JF_REFRESH_HEAL_POLL_SEC=$JF_REFRESH_HEAL_POLL_SEC"
"JF_REFRESH_HEAL_MAX_POLLS=$JF_REFRESH_HEAL_MAX_POLLS"
"JF_HEAL_LOCK_DIR=$JF_HEAL_LOCK_DIR"
)
# Only pass API key via env when the mounted secret file is absent (never expose secret in ps/environ)
if [ "$_JF_KEY_FROM_SECRET" -eq 0 ]; then
_env_args+=("JELLYFIN_API_KEY=$JF_API_KEY")
fi
nohup env "${_env_args[@]}" \
"$SCRIPT_PATH" --heal-only >/tmp/assemblrr-jf-heal.log 2>&1 &
exit 0

View file

@ -1,9 +1,10 @@
#!/bin/bash
# inotify on /data/media → media-purge when a library *video* is deleted.
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# inotify on /data/media -> media-purge when a library *video* is deleted.
# Ignores *arr write-tests, sidecars, and upgrade races (new file not yet written).
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PURGE="${SCRIPT_DIR}/media-purge.sh"
MEDIA_ROOT="${MEDIA_ROOT:-/data}"
WATCH_ROOT="${WATCH_ROOT:-${MEDIA_ROOT}/media}"
@ -11,6 +12,10 @@ WATCH_ROOT="${WATCH_ROOT:-${MEDIA_ROOT}/media}"
DEBOUNCE_SEC="${DEBOUNCE_SEC:-8}"
# Second look: Radarr/Sonarr upgrades delete the old file before writing the new one.
UPGRADE_GRACE_SEC="${UPGRADE_GRACE_SEC:-20}"
# Only treat recent upgrade deletes as active upgrade races.
UPGRADE_WINDOW_SEC="${UPGRADE_WINDOW_SEC:-600}"
# Cooldown per title/season key so bulk multi-file deletes do not sleep 28s * N.
EVENT_DEDUP_SEC="${EVENT_DEDUP_SEC:-30}"
export API_HOST="${API_HOST:-127.0.0.1}"
export RADARR_URL="${RADARR_URL:-http://radarr:7878}"
@ -57,6 +62,16 @@ purge_watch_is_video() {
esac
}
# Classify library path as "movie" or "tv" (empty if outside library roots).
purge_watch_library_kind() {
local p="${1:-}"
case "$p" in
*/media/movies|*/media/movies/*) echo "movie" ;;
*/media/tv|*/media/tv/*) echo "tv" ;;
*) echo "" ;;
esac
}
# Folder we would ask *arr to delete (title directory under movies/ or tv/).
purge_watch_library_folder() {
local p="$1"
@ -112,7 +127,8 @@ purge_watch_folder_has_video() {
find "$folder" -type f \( \
-iname '*.mkv' -o -iname '*.mp4' -o -iname '*.avi' -o \
-iname '*.m4v' -o -iname '*.ts' -o -iname '*.m2ts' -o \
-iname '*.webm' -o -iname '*.mov' \
-iname '*.webm' -o -iname '*.mov' -o -iname '*.wmv' -o \
-iname '*.mpg' -o -iname '*.mpeg' \
\) 2>/dev/null | grep -q .
}
@ -135,13 +151,25 @@ purge_watch_arr_key() {
}
# History JSON: hold if a recent file-delete was an *arr upgrade.
# Optional args: $2 = now_epoch (default: current time), $3 = window_sec (default: UPGRADE_WINDOW_SEC)
purge_watch_json_has_upgrade_delete() {
printf '%s' "${1:-}" | jq -e '
local json="${1:-}"
local now_ts="${2:-$(date +%s)}"
local win_sec="${3:-${UPGRADE_WINDOW_SEC:-600}}"
printf '%s' "$json" | jq -e \
--argjson now "$now_ts" --argjson win "$win_sec" '
def recs: if type == "array" then . elif has("records") then .records else [] end;
def recent($rec):
($rec.date // "") as $d
| if ($d | length) == 0 then true
else
($d | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601? // null) as $ts
| ($ts != null and $ts >= ($now - $win) and $ts <= ($now + 120))
end;
recs[]
| ((.eventType // "") | ascii_downcase) as $e
| ((.data.reason // "") | ascii_downcase) as $r
| select(($e == "moviefiledeleted" or $e == "episodefiledeleted") and $r == "upgrade")
| select(($e == "moviefiledeleted" or $e == "episodefiledeleted") and $r == "upgrade" and recent(.))
' >/dev/null 2>&1
}
@ -163,12 +191,22 @@ purge_watch_arr_get() {
}
# 0 = do not purge (upgrade/import still in flight, or *arr unreachable).
# Args: <arr_path> [season] [kind: movie|tv]
purge_watch_arr_hold() {
local arr_path="$1"
local season="${2:-}"
local kind="${3:-}"
local key json id hist queue
if [ -n "$season" ]; then
if [ -z "$kind" ]; then
if [ -n "$season" ] || [ "$(purge_watch_library_kind "$arr_path")" = "tv" ]; then
kind="tv"
else
kind="movie"
fi
fi
if [ "$kind" = "tv" ]; then
key=$(purge_watch_arr_key sonarr || true)
[ -n "$key" ] || return 0
json=$(purge_watch_arr_get "${SONARR_URL:-http://sonarr:8989}" "$key" "/api/v3/series")
@ -202,8 +240,6 @@ if [ "${PURGE_WATCH_SOURCE_ONLY:-0}" = "1" ]; then
return 0 2>/dev/null || exit 0
fi
[ -x "$PURGE" ] || chmod +x "$PURGE" 2>/dev/null || true
if [ "${MEDIA_PURGE_WATCH:-1}" = "0" ] || [ "${MEDIA_PURGE_WATCH:-1}" = "false" ] || [ "${MEDIA_PURGE_WATCH:-1}" = "off" ]; then
log "disabled (MEDIA_PURGE_WATCH=${MEDIA_PURGE_WATCH}); idling"
exec sleep infinity
@ -221,24 +257,31 @@ fi
log "watching ${WATCH_ROOT} (qB=${QBITTORRENT_URL})"
LAST_PURGE_PATH=""
LAST_PURGE_TS=0
declare -A _PURGE_WATCH_LAST_HANDLED=()
_run_purge() {
if [ -x "$PURGE" ]; then
"$PURGE" "$@"
else
bash "$PURGE" "$@"
fi
}
handle_event() {
local path="$1"
local folder
local folder kind
folder=$(purge_watch_library_folder "$path")
[ -n "$folder" ] || return 0
kind=$(purge_watch_library_kind "$path")
local now
local now season dedup_key last_ts
now=$(date +%s)
local season
season=$(purge_watch_season_number "$path")
# Dedup per season so S01 then S02 in the same window both run.
local dedup_key="$folder"
# Dedup per season (or title) so multi-episode / multi-show bulk deletes do not re-sleep 28s per file.
dedup_key="$folder"
[ -n "$season" ] && dedup_key="${folder}/s${season}"
if [ "$dedup_key" = "$LAST_PURGE_PATH" ] && [ $((now - LAST_PURGE_TS)) -lt 15 ]; then
last_ts="${_PURGE_WATCH_LAST_HANDLED[$dedup_key]:-0}"
if [ "$last_ts" -gt 0 ] && [ $((now - last_ts)) -lt "$EVENT_DEDUP_SEC" ]; then
return 0
fi
@ -256,40 +299,44 @@ handle_event() {
local sfolder
sfolder=$(purge_watch_season_folder "$folder" "$season" || true)
if [ -n "$sfolder" ] && purge_watch_folder_busy "$sfolder"; then
_PURGE_WATCH_LAST_HANDLED["$dedup_key"]=$(date +%s)
return 0
fi
sleep "$UPGRADE_GRACE_SEC"
sfolder=$(purge_watch_season_folder "$folder" "$season" || true)
if [ -n "$sfolder" ] && purge_watch_folder_busy "$sfolder"; then
_PURGE_WATCH_LAST_HANDLED["$dedup_key"]=$(date +%s)
return 0
fi
if purge_watch_arr_hold "$arr_path" "$season"; then
if purge_watch_arr_hold "$arr_path" "$season" "$kind"; then
log "hold $arr_path season ${season} (queue or upgrade in *arr)"
_PURGE_WATCH_LAST_HANDLED["$dedup_key"]=$(date +%s)
return 0
fi
LAST_PURGE_PATH="$dedup_key"
LAST_PURGE_TS=$(date +%s)
_PURGE_WATCH_LAST_HANDLED["$dedup_key"]=$(date +%s)
log "purge $arr_path season ${season}"
"$PURGE" --path "$arr_path" --seasons "$season" || log "purge failed for $arr_path season ${season}"
_run_purge --path "$arr_path" --seasons "$season" || log "purge failed for $arr_path season ${season}"
return 0
fi
if purge_watch_folder_busy "$folder"; then
_PURGE_WATCH_LAST_HANDLED["$dedup_key"]=$(date +%s)
return 0
fi
sleep "$UPGRADE_GRACE_SEC"
if purge_watch_folder_busy "$folder"; then
_PURGE_WATCH_LAST_HANDLED["$dedup_key"]=$(date +%s)
return 0
fi
if purge_watch_arr_hold "$arr_path" ""; then
if purge_watch_arr_hold "$arr_path" "" "$kind"; then
log "hold $arr_path (queue or upgrade in *arr)"
_PURGE_WATCH_LAST_HANDLED["$dedup_key"]=$(date +%s)
return 0
fi
LAST_PURGE_PATH="$dedup_key"
LAST_PURGE_TS=$(date +%s)
_PURGE_WATCH_LAST_HANDLED["$dedup_key"]=$(date +%s)
log "purge $arr_path"
"$PURGE" --path "$arr_path" || log "purge failed for $arr_path"
_run_purge --path "$arr_path" || log "purge failed for $arr_path"
}
mkdir -p "$WATCH_ROOT/movies" "$WATCH_ROOT/tv" 2>/dev/null || true
@ -314,7 +361,7 @@ inotifywait -m -r \
continue
fi
# Title folder removed or moved to the recycle bin (MOVED_FROM).
# Sonarr "delete files" often renames media/tv/Show → media/.recycle/...
# Sonarr "delete files" often renames media/tv/Show -> media/.recycle/...
if purge_watch_is_title_folder "$full"; then
case ",${events}," in
*,DELETE_SELF,*|*,MOVED_FROM,*|*,DELETE,*)

View file

@ -1,21 +1,21 @@
#!/bin/bash
# Remove a title from *arr, library files, and qBittorrent.
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Remove a title from *arr, library files, qBittorrent, and (if enabled) SABnzbd.
# Usage: media-purge.sh --movie-id N | --series-id N | --path P | --tmdb ID | --tvdb ID
# media-purge.sh --series-id N --seasons 1,2
# media-purge.sh --radarr-event | --sonarr-event | --qb-only --path P
# media-purge.sh --match-self-test
#
# TV: --seasons (or a path under Season N) deletes only those seasons' files,
# unmonitors them, and only removes the series when nothing monitored/on-disk
# remains. qB matching then requires a season token and refuses packs that
# also name another season.
#
# Safety ladder for qB cleanup (prefer under-delete over collateral damage):
# 1) *arr queue + history download hashes that still exist in qB (hash is identity)
# 2) Title + year match on torrent name / content path (The Avengers (2012) ==
# The Avengers 2012 REPACK…; indexer prefixes allowed; next token after the
# Safety ladder for download cleanup (prefer under-delete over collateral damage):
# 1) *arr queue + history download IDs/hashes that still exist in qB / SABnzbd
# 2) Title + year match on item name / content path (Alpha Film (2016) ==
# Alpha Film 2016 REPACK...; indexer prefixes allowed; next token after the
# title must be that year). No-year keys still require a season/year/end
# boundary so Lost does not hit Lost in Space.
# boundary so Sample Show does not hit Sample Show Extended.
# 3) Never bare short titles (len < 3). Refuse ambiguous multi-matches on
# the name step. Season purge still refuses packs / other seasons.
# After a successful non-qb-only purge, best-effort Jellyfin /Library/Refresh.
@ -26,6 +26,7 @@ API_HOST="${API_HOST:-127.0.0.1}"
RADARR_URL="${RADARR_URL:-http://${API_HOST}:7878}"
SONARR_URL="${SONARR_URL:-http://${API_HOST}:8989}"
JELLYFIN_URL="${JELLYFIN_URL:-http://jellyfin:8096}"
SABNZBD_URL="${SABNZBD_URL:-http://${API_HOST}:8085}"
CONFIG_DIR="${CONFIG_DIR:-}"
DRY_RUN="${DRY_RUN:-0}"
QB_ONLY=0
@ -40,6 +41,16 @@ TVDB_ID=""
SEASONS=""
# Set when we actually removed something worth notifying the media server about.
PURGE_TOUCHED=0
QBIT_JAR=""
QBIT_BASE=""
_QBIT_LOGGED_IN=0
cleanup_purge() {
if [ -n "${QBIT_JAR:-}" ] && [ -f "${QBIT_JAR:-}" ]; then
rm -f "$QBIT_JAR"
fi
}
trap cleanup_purge EXIT INT TERM
log() { echo "media-purge: $*" >&2; }
die() { log "ERROR: $*"; exit 1; }
@ -75,7 +86,7 @@ folder_key_from() {
echo ""
}
# "1,02 3" → unique integers as lines. Empty / junk → nothing.
# "1,02 3" -> unique integers as lines. Empty / junk -> nothing.
parse_season_list() {
local raw="${1:-}"
[ -n "$raw" ] || return 0
@ -84,7 +95,7 @@ parse_season_list() {
' | sort -n | uniq
}
# Path under .../Season N/... or .../Specials/... → season number. Else empty.
# Path under .../Season N/... or .../Specials/... -> season number. Else empty.
path_season_number() {
local p="${1:-}"
local n
@ -146,9 +157,37 @@ discover_api_key() {
return 1
}
discover_sabnzbd_api_key() {
if [ -n "${SABNZBD_API_KEY:-}" ]; then
echo "$SABNZBD_API_KEY"
return 0
fi
local f
for f in \
"${CONFIG_DIR:+$CONFIG_DIR/sabnzbd/sabnzbd.ini}" \
"/config/sabnzbd/sabnzbd.ini" \
"${INSTALL_DIR:+$INSTALL_DIR/config/sabnzbd/sabnzbd.ini}"; do
[ -n "${f:-}" ] && [ -f "$f" ] || continue
local k
k=$(sed -n 's/^[[:space:]]*api_key[[:space:]]*=[[:space:]]*//p' "$f" 2>/dev/null | head -1 | tr -d '\r')
if [ -n "$k" ]; then
echo "$k"
return 0
fi
done
return 1
}
qbit_login() {
local user pass jar
jar="${1:-/tmp/media-purge-qb.cookies}"
local user pass
if [ -n "${1:-}" ]; then
QBIT_JAR="$1"
_QBIT_LOGGED_IN=0
fi
if [ "$_QBIT_LOGGED_IN" -eq 1 ] && [ -n "${QBIT_JAR:-}" ] && [ -f "$QBIT_JAR" ]; then
return 0
fi
user="${AUTH_USERNAME:-}"
pass="${AUTH_PASSWORD:-}"
[ -z "$user" ] && user=$(read_secret_file "${AUTH_USERNAME_FILE:-/run/secrets/auth_username.txt}" 2>/dev/null || true)
@ -169,7 +208,9 @@ qbit_login() {
[ -n "$QBIT_BASE" ] || QBIT_BASE="http://${API_HOST}:8081"
fi
QBIT_JAR="$jar"
if [ -z "${QBIT_JAR:-}" ]; then
QBIT_JAR=$(mktemp "${TMPDIR:-/tmp}/media-purge-qb.XXXXXX")
fi
curl -s --connect-timeout 8 -c "$QBIT_JAR" \
-H "Referer: ${QBIT_BASE}/" \
--data-urlencode "username=${user}" \
@ -179,6 +220,7 @@ qbit_login() {
"${QBIT_BASE}/api/v2/app/version" 2>/dev/null | grep -q .; then
die "qBittorrent login failed (${QBIT_BASE})"
fi
_QBIT_LOGGED_IN=1
log "qB session ok (${QBIT_BASE})"
}
@ -204,17 +246,20 @@ qbit_delete_hashes() {
log "DRY_RUN: skip qB delete"
return 0
fi
curl -s --connect-timeout 15 -b "$QBIT_JAR" -H "Referer: ${QBIT_BASE}/" \
local code
code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 15 \
-b "$QBIT_JAR" -H "Referer: ${QBIT_BASE}/" \
-d "hashes=${csv}&deleteFiles=true" \
"${QBIT_BASE}/api/v2/torrents/delete" >/dev/null || true
"${QBIT_BASE}/api/v2/torrents/delete" 2>/dev/null || echo "000")
log "qB: torrents/delete HTTP ${code}"
PURGE_TOUCHED=1
}
# Title + year matcher shared by name fallback and leftover-dir cleanup.
# A movie key "The Avengers (2012)" hits "The Avengers 2012 REPACK…" and
# "www.UIndex.org - The Avengers 2012 …" because the title tokens appear
# consecutively and the next token is that year. It does not hit Age of Ultron
# (next token is not 2012) or "It Comes at Night" for It (2017).
# Example: "Alpha Film (2016)" matches "Alpha Film 2016 REPACK..." and
# "indexer.example - Alpha Film 2016 ..." because title tokens appear
# consecutively and the next token is that year, while rejecting unrelated sequels
# ("Alpha Film Sequel Extended (2022)") or longer titles ("Brief Story Extended").
QB_TITLE_YEAR_JQ=$(cat <<'JQ'
def norm:
ascii_downcase
@ -307,8 +352,9 @@ qb_match_jq() {
}
# Season-scoped matcher: title+year (or no-year title boundary) plus season
# tokens. Refuse packs that also name a season we are not deleting
# (S01.S02 / S01-03 / Season 1-3). No season token → skip (under-delete).
# tokens (with strict non-alphanumeric left boundaries so dts5/ps4/x265 do not
# trigger false seasons). Handles Specials (season 0) too. Refuse packs that
# also name a season we are not deleting (S01.S02 / S01-03 / Season 1-3).
qb_match_season_jq() {
jq -r --arg folder "$1" --argjson seasons "$2" "${QB_TITLE_YEAR_JQ}"'
def expand_range($a; $b):
@ -320,10 +366,11 @@ qb_match_season_jq() {
def ranges($re):
[ $t | scan($re) | if type == "array" then expand_range(.[0]|tonumber; .[1]|tonumber)[] else empty end ];
(
ranges("s0*([0-9]{1,2})[[:space:]]*[-–][[:space:]]*s?0*([0-9]{1,2})")
+ ranges("season[s]?[[:space:]]*0*([0-9]{1,2})[[:space:]]*[-–][[:space:]]*0*([0-9]{1,2})")
+ nums("s([0-9]{1,2})")
+ nums("season[[:space:]]*0*([0-9]{1,2})")
ranges("(?:^|[^a-z0-9])s0*([0-9]{1,2})[[:space:]]*[-–][[:space:]]*s?0*([0-9]{1,2})(?=$|[^0-9])")
+ ranges("(?:^|[^a-z0-9])seasons?[[:space:]]*0*([0-9]{1,2})[[:space:]]*[-–][[:space:]]*0*([0-9]{1,2})(?=$|[^0-9])")
+ nums("(?:^|[^a-z0-9])s0*([0-9]{1,2})(?=e[0-9]{1,3}|$|[^0-9])")
+ nums("(?:^|[^a-z0-9])seasons?[[:space:]]*0*([0-9]{1,2})(?=$|[^0-9])")
+ (if ($t | test("(?:^|[^a-z0-9])specials(?=$|[^a-z0-9])")) then [0] else [] end)
) | unique;
def in_wanted($n): ($seasons | index($n)) != null;
.[]
@ -344,11 +391,9 @@ qb_match_season_jq() {
}
# Keep *arr queue/history hashes that still exist in qB. The hash is identity —
# do not also require a folder-key name match (release names rarely look like
# "Title (YYYY)"). stdin: qB info JSON. args: candidate hashes.
# do not also require a folder-key name match. stdin: qB info JSON. args: hashes.
qbit_filter_hashes_jq() {
local hashes_json
# Lowercase/trim only — do not strip non-hex (breaks tests and rare non-standard ids).
hashes_json=$(printf '%s\n' "$@" | jq -R . | jq -s -c 'map(ascii_downcase | gsub("^ +| +$"; "")) | map(select(length > 0)) | unique')
jq -r --argjson want "$hashes_json" '
.[]
@ -385,24 +430,39 @@ qbit_delete_by_folder_key() {
remove_orphan_torrent_dirs "$folder_key"
}
# *arr Completed Download Handling often removes the qB item but leaves
# torrents/tv|movies/<release>. Title-delete then finds no qB row.
# Clean up completed/incomplete torrent & usenet dirs left behind on disk.
remove_orphan_torrent_dirs() {
local folder_key="$1"
local seasons_json="${2:-}"
local root="${MEDIA_ROOT:-/data}/torrents"
local d base info tokens_json hashes
local torrents_root="${MEDIA_ROOT:-/data}/torrents"
local usenet_root="${MEDIA_ROOT:-/data}/usenet"
local -a dirs=()
[ -n "$folder_key" ] || return 0
[ -d "$root/tv" ] || [ -d "$root/movies" ] || return 0
tokens_json=$(jq -nc --arg k "$folder_key" '[$k]')
shopt -s nullglob
for d in "$root/tv"/* "$root/movies"/* \
"$root/incomplete/tv"/* "$root/incomplete/movies"/*; do
if [ -d "$torrents_root/tv" ] || [ -d "$torrents_root/movies" ]; then
dirs+=(
"$torrents_root/tv"/* "$torrents_root/movies"/*
"$torrents_root/incomplete/tv"/* "$torrents_root/incomplete/movies"/*
)
fi
if [ -d "$usenet_root/complete" ] || [ -d "$usenet_root/incomplete" ]; then
dirs+=(
"$usenet_root/complete/tv"/* "$usenet_root/complete/movies"/*
"$usenet_root/incomplete/tv"/* "$usenet_root/incomplete/movies"/*
"$usenet_root/incomplete"/*
)
fi
shopt -u nullglob
[ "${#dirs[@]}" -gt 0 ] || return 0
local d base info tokens_json hashes
tokens_json=$(jq -nc --arg k "$folder_key" '[$k]')
for d in "${dirs[@]}"; do
[ -d "$d" ] || continue
base=$(basename_of "$d")
case "$base" in
tv|movies|incomplete|""|.) continue ;;
tv|movies|incomplete|complete|""|.) continue ;;
esac
info=$(jq -nc --arg n "$base" --arg p "$d" '[{hash:"fs",name:$n,content_path:$p}]')
if [ -n "$seasons_json" ] && [ "$seasons_json" != "[]" ]; then
@ -418,7 +478,6 @@ remove_orphan_torrent_dirs() {
fi
rm -rf -- "$d" && PURGE_TOUCHED=1
done
shopt -u nullglob
}
qbit_delete_by_folder_key_seasons() {
@ -447,10 +506,8 @@ qbit_delete_by_folder_key_seasons() {
remove_orphan_torrent_dirs "$folder_key" "$seasons_json"
}
# Back-compat name used by older call sites / mental model.
qbit_delete_by_tokens() {
local folder=""
local t b
local folder="" t b
for t in "$@"; do
[ -n "$t" ] || continue
b=$(basename_of "$t")
@ -464,7 +521,7 @@ qbit_delete_by_tokens() {
[ -n "$t" ] || continue
b=$(basename_of "$t")
case "$b" in
media|movies|tv|torrents|data|incomplete|"") continue ;;
media|movies|tv|torrents|usenet|data|incomplete|complete|"") continue ;;
esac
if [ "${#b}" -ge 10 ]; then
folder="$b"
@ -475,6 +532,30 @@ qbit_delete_by_tokens() {
qbit_delete_by_folder_key "$folder"
}
# Best-effort SABnzbd queue/history deletion for matching SABnzbd_nzo_* IDs.
sabnzbd_delete_nzo_ids() {
local nzo_ids=("$@")
[ "${#nzo_ids[@]}" -gt 0 ] || return 0
local sab_key
sab_key=$(discover_sabnzbd_api_key 2>/dev/null || true)
[ -n "$sab_key" ] || return 0
local id
for id in "${nzo_ids[@]}"; do
[ -n "$id" ] || continue
log "SABnzbd: deleting download ${id}"
if [ "$DRY_RUN" = "1" ]; then
log "DRY_RUN: skip SABnzbd delete ${id}"
continue
fi
curl -sf --connect-timeout 5 --max-time 15 \
"${SABNZBD_URL%/}/api?mode=queue&name=delete&del_files=1&value=${id}&apikey=${sab_key}&output=json" >/dev/null 2>&1 || true
curl -sf --connect-timeout 5 --max-time 15 \
"${SABNZBD_URL%/}/api?mode=history&name=delete&del_files=1&value=${id}&apikey=${sab_key}&output=json" >/dev/null 2>&1 || true
PURGE_TOUCHED=1
done
}
arr_get() {
local base="$1" key="$2" path="$3"
curl -s --connect-timeout 10 -H "X-Api-Key: ${key}" "${base}${path}" 2>/dev/null || true
@ -499,7 +580,6 @@ arr_history_hashes() {
fi
}
# Active *arr queue download hashes (in-progress grabs). Hash is identity.
arr_queue_hashes() {
local base="$1" key="$2" kind="$3" id="$4"
local endpoint raw
@ -536,28 +616,19 @@ arr_queue_hashes_seasons() {
else empty end
| select((.seriesId // empty) == ($id|tonumber))
| . as $r
| (
$r.episode.seasonNumber
// $r.seasonNumber
// empty
) as $sn
| ($r.episode.seasonNumber // $r.seasonNumber // empty) as $sn
| select(($sn != null) and (($seasons | index($sn)) != null))
| $r.downloadId // $r.data.torrentInfoHash // empty
' 2>/dev/null | tr 'A-F' 'a-f' | sort -u
}
# Same as series history, but only grab/import rows whose episode season is in $5 (lines of ints).
arr_history_hashes_seasons() {
local base="$1" key="$2" id="$3" seasons_json="$4"
local hist
hist=$(arr_get "$base" "$key" "/api/v3/history?pageSize=250&seriesId=${id}")
echo "$hist" | jq -r --argjson seasons "$seasons_json" '
.records[]? as $r
| (
$r.episode.seasonNumber
// $r.data.seasonNumber
// empty
) as $sn
| ($r.episode.seasonNumber // $r.data.seasonNumber // empty) as $sn
| select(($sn != null) and (($seasons | index($sn)) != null))
| $r.downloadId // $r.data.torrentInfoHash // empty
' 2>/dev/null | tr 'A-F' 'a-f' | sort -u
@ -592,7 +663,6 @@ arr_delete_series() {
}
# Remaining seasons from Sonarr series + episodefile JSON (includes specials / 0).
# Used to decide series delete vs season-scoped delete.
seasons_remaining_json() {
local series="${1:-}"
local files="${2:-}"
@ -608,8 +678,6 @@ seasons_remaining_json() {
printf '%s\n' "$out"
}
# True when this season list covers every remaining on-disk / monitored season
# (specials/0 count; deleting S01 must not wipe Specials).
seasons_list_covers_remaining() {
local seasons_json="$1"
local remain_json="$2"
@ -645,7 +713,6 @@ arr_unmonitor_seasons() {
"${SONARR_URL}/api/v3/series/${id}" 2>/dev/null || echo "000")
log "Sonarr: unmonitor seasons ${seasons_json} HTTP ${code}"
# Also flip per-episode monitored so missing-search will not re-grab.
local eps ids
eps=$(arr_get "$SONARR_URL" "$key" "/api/v3/episode?seriesId=${id}")
ids=$(echo "$eps" | jq -c --argjson seasons "$seasons_json" \
@ -681,13 +748,12 @@ arr_delete_series_seasons() {
arr_unmonitor_seasons "$key" "$id" "$seasons_json"
}
# Exact *arr path match only (no bare endswith of short basenames).
arr_id_for_path() {
local base="$1" key="$2" kind="$3" path="$4"
local b json
b=$(basename_of "$path")
case "$b" in
movies|tv|media|torrents|incomplete|data|""|.) return 0 ;;
movies|tv|media|torrents|usenet|incomplete|complete|data|""|.) return 0 ;;
esac
if [ "$kind" = "movie" ]; then
json=$(arr_get "$base" "$key" "/api/v3/movie")
@ -713,10 +779,10 @@ arr_id_for_path() {
purge_qb() {
local kind="$1" base_url="$2" key="$3" id="$4" title="$5" path="$6"
local seasons_json="${7:-}"
local folder hlist=() filtered=() info h
local folder hlist=() qb_ids=() nzo_ids=() filtered=() info h
folder=$(folder_key_from "$path" "$title")
log "qB purge kind=${kind} id=${id} folder_key=${folder:-<none>} seasons=${seasons_json:-<all>}"
log "download purge kind=${kind} id=${id} folder_key=${folder:-<none>} seasons=${seasons_json:-<all>}"
if [ -n "$seasons_json" ] && [ "$seasons_json" != "[]" ]; then
while IFS= read -r h; do
@ -733,27 +799,37 @@ purge_qb() {
[ -n "$h" ] && hlist+=("$h")
done < <(arr_history_hashes "$base_url" "$key" "$kind" "$id")
fi
if [ "${#hlist[@]}" -gt 0 ]; then
# Unique, keep order
hlist=($(printf '%s\n' "${hlist[@]}" | awk 'NF && !seen[$0]++'))
fi
if [ "${#hlist[@]}" -gt 0 ]; then
log "${kind} queue/history candidates: ${hlist[*]}"
mapfile -t hlist < <(printf '%s\n' "${hlist[@]}" | awk 'NF && !seen[$0]++')
for h in "${hlist[@]}"; do
case "$h" in
sabnzbd_nzo_*) nzo_ids+=("SABnzbd_nzo_${h#sabnzbd_nzo_}") ;;
*) qb_ids+=("$h") ;;
esac
done
fi
if [ "${#nzo_ids[@]}" -gt 0 ]; then
sabnzbd_delete_nzo_ids "${nzo_ids[@]}"
fi
if [ "${#qb_ids[@]}" -gt 0 ]; then
log "${kind} queue/history qB candidates: ${qb_ids[*]}"
info=$(qbit_torrents_info)
while IFS= read -r h; do
[ -n "$h" ] && filtered+=("$h")
done < <(echo "$info" | qbit_filter_hashes_jq "${hlist[@]}" 2>/dev/null || true)
done < <(echo "$info" | qbit_filter_hashes_jq "${qb_ids[@]}" 2>/dev/null || true)
if [ "${#filtered[@]}" -gt 0 ]; then
log "qB: queue/history hashes in qB (${#filtered[@]}): ${filtered[*]}"
qbit_delete_hashes "${filtered[@]}"
remove_orphan_torrent_dirs "$folder" "$seasons_json"
else
log "qB: queue/history hashes not in qB; trying title+year match"
return 0
fi
log "qB: queue/history hashes not in qB; trying title+year match"
else
log "no queue/history hashes for ${kind} ${id}"
log "no qB queue/history hashes for ${kind} ${id}"
fi
if [ -n "$folder" ]; then
@ -775,7 +851,7 @@ purge_qb_for_series() {
purge_qb series "$SONARR_URL" "$1" "$2" "$3" "$4" "${5:-}"
}
# Best-effort library refresh so deletes do not leave ghost items.
# Best-effort Jellyfin library refresh so deletes do not leave ghost items.
notify_jellyfin() {
if [ "$SKIP_JELLYFIN" = "1" ] || [ "$DRY_RUN" = "1" ]; then
return 0
@ -783,13 +859,12 @@ notify_jellyfin() {
if [ "$PURGE_TOUCHED" != "1" ]; then
return 0
fi
# Only meaningful for Jellyfin (and Emby-compatible token header).
case "${MEDIA_SERVICE:-jellyfin}" in
jellyfin|emby|"") ;;
jellyfin|"") ;;
*) log "media server ${MEDIA_SERVICE}: skip library refresh"; return 0 ;;
esac
local key="" url code
local key="" auth_hdr tasks scan_state code
if [ -n "${JELLYFIN_API_KEY:-}" ]; then
key="$JELLYFIN_API_KEY"
elif [ -f "${JELLYFIN_API_KEY_FILE:-/run/secrets/jellyfin_api_key.txt}" ]; then
@ -804,9 +879,24 @@ notify_jellyfin() {
return 0
fi
url="${JELLYFIN_URL%/}/Library/Refresh"
auth_hdr="Authorization: MediaBrowser Client=\"assemblrr\", Device=\"media-purge\", DeviceId=\"assemblrr-purge\", Version=\"1.0\", Token=\"${key}\""
# Never cancel an active RefreshLibrary scan in Jellyfin 12
tasks=$(curl -sS --connect-timeout 5 --max-time 10 \
-H "$auth_hdr" \
"${JELLYFIN_URL%/}/ScheduledTasks" 2>/dev/null || echo "")
scan_state=$(printf '%s' "$tasks" | jq -r \
'([.[]? | select(.Key == "RefreshLibrary") | .State] | first) // "Idle"' \
2>/dev/null || echo "Idle")
case "$scan_state" in
Running|Cancelling)
log "Jellyfin: scan already ${scan_state}, skipping /Library/Refresh"
return 0
;;
esac
code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 8 \
-X POST -H "X-Emby-Token: ${key}" "$url" 2>/dev/null || echo "000")
-X POST -H "$auth_hdr" "${JELLYFIN_URL%/}/Library/Refresh" 2>/dev/null || echo "000")
if [ "$code" -ge 200 ] && [ "$code" -lt 300 ]; then
log "Jellyfin: library refresh triggered (HTTP ${code})"
else
@ -814,203 +904,52 @@ notify_jellyfin() {
fi
}
# Offline matcher self-test (no Docker / qB): media-purge.sh --match-self-test
if [ "${1:-}" = "--match-self-test" ]; then
failures=0
check() {
local want="$1" name="$2" tokens="$3" torrents="$4"
local got
got=$(echo "$torrents" | qb_match_jq "$tokens" | tr '\n' ' ' | sed 's/[[:space:]]*$//')
if [ "$got" = "$want" ]; then
echo " PASS: $name"
else
echo " FAIL: $name (want='$want' got='$got')"
failures=$((failures + 1))
fi
}
check_filter() {
local want="$1" name="$2" torrents="$3"
shift 3
local got
got=$(echo "$torrents" | qbit_filter_hashes_jq "$@" | tr '\n' ' ' | sed 's/[[:space:]]*$//')
if [ "$got" = "$want" ]; then
echo " PASS: $name"
else
echo " FAIL: $name (want='$want' got='$got')"
failures=$((failures + 1))
fi
}
echo "=== media-purge qB match self-test ==="
# Synthetic titles only — prove match rules, not real catalog entries.
check "hash_a" "year folder hits only first film" \
'["Alpha Film (2016)"]' \
'[{"hash":"hash_a","name":"Alpha Film (2016) [GRP]","content_path":"/data/torrents/movies/Alpha Film (2016)"},{"hash":"hash_b","name":"Alpha Film Sequel Extended (2022)","content_path":"/data/torrents/movies/Alpha Film Sequel Extended (2022)"}]'
check "" "bare short title does not hit longer sequel name" \
'["Alpha Film"]' \
'[{"hash":"hash_b","name":"Alpha Film Sequel Extended (2022)","content_path":"/data/torrents/movies/Alpha Film Sequel Extended (2022)"}]'
check "hash_a" "bare short title hits exact name only" \
'["Alpha Film"]' \
'[{"hash":"hash_a","name":"Alpha Film","content_path":"/data/torrents/movies/Alpha Film"},{"hash":"hash_b","name":"Alpha Film Sequel Extended","content_path":"/data/torrents/movies/Alpha Film Sequel Extended"}]'
check "hash_y" "year preferred when bare+year present" \
'["Sample Title","Sample Title (2008)"]' \
'[{"hash":"hash_y","name":"Sample Title (2008) [e2e]","content_path":"/data/torrents/movies/Sample Title (2008) [e2e]"},{"hash":"hash_z","name":"Sample Title Adventures","content_path":"/data/torrents/movies/Sample Title Adventures"}]'
check "hash_m1" "bare title does not hit same-prefix sequel" \
'["Beta Movie"]' \
'[{"hash":"hash_m1","name":"Beta Movie","content_path":"/data/torrents/movies/Beta Movie"},{"hash":"hash_m2","name":"Beta Movie Reloaded","content_path":"/data/torrents/movies/Beta Movie Reloaded"}]'
check_filter "hash_a" "history filter keeps live hash even when name is a release" \
'[{"hash":"hash_a","name":"The Avengers 2012 REPACK BluRay","content_path":"/data/torrents/incomplete/movies/The Avengers 2012 REPACK BluRay"},{"hash":"hash_b","name":"Other Title","content_path":"/data/torrents/movies/Other"}]' \
hash_a
check_filter "hash_a" "history filter keeps every live candidate hash" \
'[{"hash":"hash_a","name":"Alpha Film Sequel Extended (2022)","content_path":"/data/torrents/movies/Alpha Film Sequel Extended (2022)"}]' \
hash_a hash_b
check_filter "" "history filter drops hashes not in qB" \
'[{"hash":"hash_b","name":"Other","content_path":"/x"}]' \
hash_a
check "hash_av" "title+year hits release name without parens" \
'["The Avengers (2012)"]' \
'[{"hash":"hash_av","name":"The Avengers 2012 REPACK BluRay 1080p DDP 5 1 x264-hallowed","content_path":"/data/torrents/incomplete/movies/www.UIndex.org - The Avengers 2012 REPACK BluRay 1080p DDP 5 1 x264-hallowed"}]'
check "hash_av" "title+year hits indexer-prefixed incomplete path" \
'["The Avengers (2012)"]' \
'[{"hash":"hash_av","name":"www.UIndex.org - The Avengers 2012 REPACK","content_path":"/data/torrents/incomplete/movies/www.UIndex.org - The Avengers 2012 REPACK"}]'
check "" "title+year does not hit Age of Ultron" \
'["The Avengers (2012)"]' \
'[{"hash":"hash_u","name":"Avengers Age of Ultron 2015 1080p","content_path":"/data/torrents/movies/Avengers Age of Ultron 2015 1080p"}]'
check "" "short It (2017) does not hit It Comes at Night" \
'["It (2017)"]' \
'[{"hash":"hash_n","name":"It Comes at Night 2017 1080p","content_path":"/data/torrents/movies/It Comes at Night 2017"}]'
check "hash_it" "It (2017) hits It 2017 release" \
'["It (2017)"]' \
'[{"hash":"hash_it","name":"It 2017 1080p BluRay","content_path":"/data/torrents/movies/It 2017 1080p BluRay"}]'
check "hash_bb" "article-stripped title still needs the year next" \
'["The Avengers (2012)"]' \
'[{"hash":"hash_bb","name":"Avengers 2012 1080p","content_path":"/data/torrents/movies/Avengers 2012 1080p"}]'
check_season() {
local want="$1" name="$2" folder="$3" seasons="$4" torrents="$5"
local got
got=$(echo "$torrents" | qb_match_season_jq "$folder" "$seasons" | tr '\n' ' ' | sed 's/[[:space:]]*$//')
if [ "$got" = "$want" ]; then
echo " PASS: $name"
else
echo " FAIL: $name (want='$want' got='$got')"
failures=$((failures + 1))
fi
}
check_season "hash_s1" "S01 pack matches season 1 only" \
"Loki" '[1]' \
'[{"hash":"hash_s1","name":"Loki.S01.COMPLETE.1080p","content_path":"/data/torrents/tv/Loki.S01.COMPLETE.1080p"},{"hash":"hash_s2","name":"Loki.S02.COMPLETE.1080p","content_path":"/data/torrents/tv/Loki.S02.COMPLETE.1080p"}]'
check_season "" "S02 pack is not deleted with season 1" \
"Loki" '[1]' \
'[{"hash":"hash_s2","name":"Loki.S02.COMPLETE.1080p.DSNP.WEB-DL","content_path":"/data/torrents/tv/Loki.S02.COMPLETE.1080p.DSNP.WEB-DL"}]'
check_season "" "multi-season pack refused when deleting S01 only" \
"Loki" '[1]' \
'[{"hash":"hash_both","name":"Loki.S01.S02.COMPLETE","content_path":"/data/torrents/tv/Loki.S01.S02.COMPLETE"}]'
check_season "" "no season token is skipped (under-delete)" \
"Loki" '[1]' \
'[{"hash":"hash_bare","name":"Loki","content_path":"/data/torrents/tv/Loki"}]'
check_season "" "other show S01 is not matched" \
"Loki" '[1]' \
'[{"hash":"hash_x","name":"Other Show.S01.COMPLETE","content_path":"/data/torrents/tv/Other Show.S01.COMPLETE"}]'
check_season "" "S01-03 range pack refused when deleting S01 only" \
"Loki" '[1]' \
'[{"hash":"hash_r","name":"Loki.S01-03.COMPLETE","content_path":"/data/torrents/tv/Loki.S01-03.COMPLETE"}]'
check_season "" "Season 1-3 range pack refused when deleting S01 only" \
"Loki" '[1]' \
'[{"hash":"hash_r2","name":"Loki Season 1-3","content_path":"/data/torrents/tv/Loki Season 1-3"}]'
check_season "" "short folder key does not match any S01 torrent" \
"Oz" '[1]' \
'[{"hash":"hash_oz","name":"Other.S01.COMPLETE","content_path":"/data/torrents/tv/Other.S01.COMPLETE"}]'
check_season "" "Lost S01 does not match Lost in Space S01" \
"Lost" '[1]' \
'[{"hash":"hash_lis","name":"Lost in Space.S01.COMPLETE","content_path":"/data/torrents/tv/Lost in Space.S01.COMPLETE"}]'
check_season "hash_e1 hash_e2" "multiple S01E0x torrents all match" \
"Loki" '[1]' \
'[{"hash":"hash_e1","name":"Loki.S01E01","content_path":"/data/torrents/tv/Loki.S01E01"},{"hash":"hash_e2","name":"Loki.S01E02","content_path":"/data/torrents/tv/Loki.S01E02"}]'
check "hash_s2" "title-level Loki matches S02 complete pack" \
'["Loki"]' \
'[{"hash":"hash_s2","name":"Loki.S02.COMPLETE.1080p.DSNP.WEB-DL","content_path":"/data/torrents/tv/Loki.S02.COMPLETE.1080p.DSNP.WEB-DL"}]'
check "" "title-level Lost still does not match Lost in Space pack" \
'["Lost"]' \
'[{"hash":"hash_lis","name":"Lost in Space.S01.COMPLETE","content_path":"/data/torrents/tv/Lost in Space.S01.COMPLETE"}]'
run_movie_purge() {
local mid="$1"
[ -n "$mid" ] || die "--movie-id required"
[ -n "$RADARR_API_KEY" ] || die "Radarr API key missing"
local movie title path
movie=$(arr_get "$RADARR_URL" "$RADARR_API_KEY" "/api/v3/movie/${mid}")
title=$(echo "$movie" | jq -r '.title // empty')
path=$(echo "$movie" | jq -r '.path // empty')
purge_qb_for_movie "$RADARR_API_KEY" "$mid" "$title" "$path"
if [ "$QB_ONLY" != "1" ]; then
arr_delete_movie "$RADARR_API_KEY" "$mid"
fi
}
echo "=== media-purge remaining-season cover ==="
cover_check() {
local want="$1" name="$2" seasons="$3" series="$4" files="$5"
local remain got
remain=$(seasons_remaining_json "$series" "$files")
if seasons_list_covers_remaining "$seasons" "$remain"; then
got="cover"
else
got="partial"
run_series_purge() {
local sid="$1"
[ -n "$sid" ] || die "--series-id required"
[ -n "$SONARR_API_KEY" ] || die "Sonarr API key missing"
local series title path season_lines seasons_json
series=$(arr_get "$SONARR_URL" "$SONARR_API_KEY" "/api/v3/series/${sid}")
title=$(echo "$series" | jq -r '.title // empty')
path=$(echo "$series" | jq -r '.path // empty')
season_lines=$(parse_season_list "$SEASONS")
if [ -n "$season_lines" ]; then
seasons_json=$(seasons_json_from_list "$season_lines")
log "series ${sid} season-scoped ${seasons_json}"
purge_qb_for_series "$SONARR_API_KEY" "$sid" "$title" "$path" "$seasons_json"
if [ "$QB_ONLY" != "1" ]; then
if seasons_cover_remaining "$SONARR_API_KEY" "$sid" "$seasons_json"; then
log "requested seasons cover remaining library; deleting series"
arr_delete_series "$SONARR_API_KEY" "$sid"
else
arr_delete_series_seasons "$SONARR_API_KEY" "$sid" "$seasons_json"
fi
fi
if [ "$got" = "$want" ]; then
echo " PASS: $name"
else
echo " FAIL: $name (want='$want' got='$got' remain='$remain')"
failures=$((failures + 1))
else
purge_qb_for_series "$SONARR_API_KEY" "$sid" "$title" "$path"
if [ "$QB_ONLY" != "1" ]; then
arr_delete_series "$SONARR_API_KEY" "$sid"
fi
}
_series_s01s02='{"seasons":[{"seasonNumber":1,"monitored":true},{"seasonNumber":2,"monitored":true}]}'
_files_s01s02='[{"seasonNumber":1},{"seasonNumber":2}]'
_series_s01_spec='{"seasons":[{"seasonNumber":0,"monitored":true},{"seasonNumber":1,"monitored":true}]}'
_files_s01_spec='[{"seasonNumber":0},{"seasonNumber":1}]'
_series_spec_only='{"seasons":[{"seasonNumber":0,"monitored":true}]}'
_files_spec_only='[{"seasonNumber":0}]'
cover_check "partial" "S01 request does not cover S01+S02" \
'[1]' "$_series_s01s02" "$_files_s01s02"
cover_check "cover" "S01+S02 request covers S01+S02" \
'[1,2]' "$_series_s01s02" "$_files_s01s02"
cover_check "partial" "S01 request does not cover S01+specials" \
'[1]' "$_series_s01_spec" "$_files_s01_spec"
cover_check "cover" "S01+specials request covers both" \
'[0,1]' "$_series_s01_spec" "$_files_s01_spec"
cover_check "partial" "S01 request does not cover specials-only leftover" \
'[1]' "$_series_spec_only" "$_files_spec_only"
cover_check "cover" "specials request covers specials-only leftover" \
'[0]' "$_series_spec_only" "$_files_spec_only"
fi
}
echo "=== media-purge leftover download dirs ==="
_old_root="${MEDIA_ROOT:-}"
MEDIA_ROOT=$(mktemp -d)
mkdir -p "$MEDIA_ROOT/torrents/tv/Loki.S02.COMPLETE.1080p.DSNP.WEB-DL" \
"$MEDIA_ROOT/torrents/tv/Lost in Space.S01.COMPLETE" \
"$MEDIA_ROOT/torrents/incomplete/movies/www.UIndex.org - The Avengers 2012 REPACK BluRay" \
"$MEDIA_ROOT/torrents/movies/Avengers Age of Ultron 2015 1080p"
DRY_RUN=0
remove_orphan_torrent_dirs "Loki"
if [ ! -d "$MEDIA_ROOT/torrents/tv/Loki.S02.COMPLETE.1080p.DSNP.WEB-DL" ]; then
echo " PASS: Loki leftover pack dir removed"
else
echo " FAIL: Loki leftover pack dir still present"
failures=$((failures + 1))
fi
if [ -d "$MEDIA_ROOT/torrents/tv/Lost in Space.S01.COMPLETE" ]; then
echo " PASS: Lost in Space leftover left alone"
else
echo " FAIL: Lost in Space leftover was removed"
failures=$((failures + 1))
fi
remove_orphan_torrent_dirs "The Avengers (2012)"
if [ ! -d "$MEDIA_ROOT/torrents/incomplete/movies/www.UIndex.org - The Avengers 2012 REPACK BluRay" ]; then
echo " PASS: Avengers incomplete leftover removed"
else
echo " FAIL: Avengers incomplete leftover still present"
failures=$((failures + 1))
fi
if [ -d "$MEDIA_ROOT/torrents/movies/Avengers Age of Ultron 2015 1080p" ]; then
echo " PASS: Age of Ultron leftover left alone"
else
echo " FAIL: Age of Ultron leftover was removed"
failures=$((failures + 1))
fi
rm -rf "$MEDIA_ROOT"
MEDIA_ROOT="${_old_root}"
if [ "$failures" -gt 0 ]; then
echo "match-self-test: FAILED ($failures)"
exit 1
fi
echo "match-self-test: OK"
exit 0
# --- sourced by unit tests: stop here ---
if [ "${MEDIA_PURGE_SOURCE_ONLY:-0}" = "1" ]; then
return 0 2>/dev/null || exit 0
fi
# --- args ---
@ -1027,7 +966,7 @@ while [ $# -gt 0 ]; do
--qb-only) QB_ONLY=1; shift ;;
--dry-run) DRY_RUN=1; shift ;;
--skip-jellyfin) SKIP_JELLYFIN=1; shift ;;
-h|--help) sed -n '2,20p' "$0"; exit 0 ;;
-h|--help) sed -n '2,22p' "$0"; exit 0 ;;
*) die "unknown arg: $1" ;;
esac
done
@ -1041,7 +980,6 @@ case "$MODE" in
log "radarr event type=${et}"
case "$et" in
Test) log "Test ok"; exit 0 ;;
# Movie-level only: file deletes are partial and must not wipe whole qB items by title.
MovieDelete) ;;
MovieFileDelete)
log "ignore MovieFileDelete (movie-level purge only)"
@ -1057,7 +995,6 @@ case "$MODE" in
else
qbit_delete_by_folder_key "$(folder_key_from "$path" "$title")"
fi
# Files already removed by Radarr; still refresh Jellyfin.
PURGE_TOUCHED=1
notify_jellyfin
exit 0
@ -1087,42 +1024,10 @@ case "$MODE" in
exit 0
;;
movie)
[ -n "$MOVIE_ID" ] || die "--movie-id required"
[ -n "$RADARR_API_KEY" ] || die "Radarr API key missing"
movie=$(arr_get "$RADARR_URL" "$RADARR_API_KEY" "/api/v3/movie/${MOVIE_ID}")
title=$(echo "$movie" | jq -r '.title // empty')
path=$(echo "$movie" | jq -r '.path // empty')
# qB first (history still available), then *arr delete
purge_qb_for_movie "$RADARR_API_KEY" "$MOVIE_ID" "$title" "$path"
if [ "$QB_ONLY" != "1" ]; then
arr_delete_movie "$RADARR_API_KEY" "$MOVIE_ID"
fi
run_movie_purge "$MOVIE_ID"
;;
series)
[ -n "$SERIES_ID" ] || die "--series-id required"
[ -n "$SONARR_API_KEY" ] || die "Sonarr API key missing"
series=$(arr_get "$SONARR_URL" "$SONARR_API_KEY" "/api/v3/series/${SERIES_ID}")
title=$(echo "$series" | jq -r '.title // empty')
path=$(echo "$series" | jq -r '.path // empty')
season_lines=$(parse_season_list "$SEASONS")
if [ -n "$season_lines" ]; then
seasons_json=$(seasons_json_from_list "$season_lines")
log "series ${SERIES_ID} season-scoped ${seasons_json}"
purge_qb_for_series "$SONARR_API_KEY" "$SERIES_ID" "$title" "$path" "$seasons_json"
if [ "$QB_ONLY" != "1" ]; then
if seasons_cover_remaining "$SONARR_API_KEY" "$SERIES_ID" "$seasons_json"; then
log "requested seasons cover remaining library; deleting series"
arr_delete_series "$SONARR_API_KEY" "$SERIES_ID"
else
arr_delete_series_seasons "$SONARR_API_KEY" "$SERIES_ID" "$seasons_json"
fi
fi
else
purge_qb_for_series "$SONARR_API_KEY" "$SERIES_ID" "$title" "$path"
if [ "$QB_ONLY" != "1" ]; then
arr_delete_series "$SONARR_API_KEY" "$SERIES_ID"
fi
fi
run_series_purge "$SERIES_ID"
;;
path)
[ -n "$PATH_ARG" ] || die "--path required"
@ -1191,7 +1096,7 @@ case "$MODE" in
movies=$(arr_get "$RADARR_URL" "$RADARR_API_KEY" "/api/v3/movie")
mid=$(echo "$movies" | jq -r --argjson t "$TMDB_ID" '.[] | select(.tmdbId == $t) | .id' | head -1)
[ -n "$mid" ] || die "no Radarr movie tmdbId=${TMDB_ID}"
exec "$0" --movie-id "$mid"
run_movie_purge "$mid"
;;
tvdb)
[ -n "$TVDB_ID" ] || die "--tvdb required"
@ -1199,10 +1104,7 @@ case "$MODE" in
series_json=$(arr_get "$SONARR_URL" "$SONARR_API_KEY" "/api/v3/series")
sid=$(echo "$series_json" | jq -r --argjson t "$TVDB_ID" '.[] | select(.tvdbId == $t) | .id' | head -1)
[ -n "$sid" ] || die "no Sonarr series tvdbId=${TVDB_ID}"
if [ -n "$SEASONS" ]; then
exec "$0" --series-id "$sid" --seasons "$SEASONS"
fi
exec "$0" --series-id "$sid"
run_series_purge "$sid"
;;
*)
die "specify --movie-id, --series-id, --path, --tmdb, --tvdb, --radarr-event, or --sonarr-event"

File diff suppressed because it is too large Load diff

View file

@ -1,20 +1,21 @@
#!/bin/bash
# VPN Watchdog for qBittorrent - Automated Tracker Routing Check
# Monitors qBittorrent for generic broken-network symptoms.
# Restarts gluetun if a failure is detected.
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# VPN Watchdog for qBittorrent — Automated Tracker Routing Check
# Monitors qBittorrent for systemic broken-network symptoms and restarts Gluetun
# with cooldown & healthy-traffic guards to prevent single-magnet false positives
# and restart storms.
set -euo pipefail
QBIT_HOST="${QBIT_HOST:-127.0.0.1:8081}"
AUTH_USERNAME_FILE="${AUTH_USERNAME_FILE:-/run/secrets/auth_username.txt}"
AUTH_PASSWORD_FILE="${AUTH_PASSWORD_FILE:-/run/secrets/auth_password.txt}"
QBIT_USER="$(cat "$AUTH_USERNAME_FILE")"
QBIT_PASS="$(cat "$AUTH_PASSWORD_FILE")"
COOKIE_JAR="/tmp/qbit_watchdog_cookie.txt"
GLUETUN_CONTROL_URL="${GLUETUN_CONTROL_URL:-http://127.0.0.1:8000}"
# Heartbeat and log levels config
WATCHDOG_INTERVAL="${WATCHDOG_INTERVAL:-30}"
HEARTBEAT_INTERVAL="${HEARTBEAT_INTERVAL:-3600}"
WATCHDOG_COOLDOWN_SEC="${WATCHDOG_COOLDOWN_SEC:-300}"
WATCHDOG_STATE_DIR="${WATCHDOG_STATE_DIR:-/tmp}"
LOG_LEVEL="${LOG_LEVEL:-INFO}"
log_watchdog() {
@ -29,15 +30,93 @@ log_debug() {
fi
}
# Initial startup log (only printed on the very first execution in this container lifecycle)
if [ ! -f "/tmp/qbit_watchdog_started" ]; then
log_watchdog INFO "VPN Watchdog active. Monitoring qBittorrent at ${QBIT_HOST} (Interval: ${WATCHDOG_INTERVAL}s, Heartbeat: ${HEARTBEAT_INTERVAL}s)."
touch "/tmp/qbit_watchdog_started"
# Pure helper: evaluate torrent properties + trackers JSON for broken routing.
# Prints: "<broken 0|1> <working 0|1>"
watchdog_classify_torrent() {
local props_json="${1:-}"
local trackers_json="${2:-}"
local has_metadata nb_conn failed_trackers routing_errs working_trackers
has_metadata=$(printf '%s' "$props_json" | jq -r '.has_metadata // false' 2>/dev/null || echo false)
nb_conn=$(printf '%s' "$props_json" | jq -r '.nb_connections // 0' 2>/dev/null || echo 0)
[[ "$nb_conn" =~ ^[0-9]+$ ]] || nb_conn=0
failed_trackers=$(printf '%s' "$trackers_json" | jq '[.[]? | select(.status == 4)] | length' 2>/dev/null || echo 0)
[[ "$failed_trackers" =~ ^[0-9]+$ ]] || failed_trackers=0
routing_errs=$(printf '%s' "$trackers_json" | jq '[.[]? | select(.status == 4 and ((.msg // "") | test("Operation not permitted|timed out|Host not found|Network is unreachable"; "i")))] | length' 2>/dev/null || echo 0)
[[ "$routing_errs" =~ ^[0-9]+$ ]] || routing_errs=0
working_trackers=$(printf '%s' "$trackers_json" | jq '[.[]? | select(.status == 2)] | length' 2>/dev/null || echo 0)
[[ "$working_trackers" =~ ^[0-9]+$ ]] || working_trackers=0
local is_working=0 is_broken=0
if [ "$nb_conn" -gt 0 ] || [ "$working_trackers" -gt 0 ]; then
is_working=1
fi
if [ "$has_metadata" = "false" ] && [ "$nb_conn" -eq 0 ] \
&& [ "$failed_trackers" -ge 3 ] && [ "$routing_errs" -gt 0 ]; then
is_broken=1
fi
echo "${is_broken} ${is_working}"
}
# Return 0 if a curl Netscape cookie jar contains a non-empty qBittorrent session cookie
# (including #HttpOnly_ prefixed lines and port-suffixed QBT_SID_<port> cookies from qBit 5.x).
watchdog_cookie_has_sid() {
local jar="$1"
[ -f "$jar" ] || return 1
awk '($1 !~ /^#/ || $1 ~ /^#HttpOnly_/) && NF >= 7 && ($6 ~ /^QBT_SID/ || $6 == "SID") && $7 != "" { found = 1 } END { exit(found ? 0 : 1) }' "$jar" 2>/dev/null
}
# Pure helper: return 0 when broken routing warrants a gluetun restart, 1 otherwise.
# Args: <broken_count> <working_count> <now_epoch> <last_restart_epoch> <cooldown_sec>
watchdog_should_restart_vpn() {
local broken="${1:-0}"
local working="${2:-0}"
local now="${3:-0}"
local last_restart="${4:-0}"
local cooldown="${5:-300}"
[ "$broken" -gt 0 ] || return 1
# Any active peer connection or healthy status-2 tracker proves the VPN path works;
# do not nuke everyone's transfers because of one unseeded/dead magnet link.
[ "$working" -eq 0 ] || return 1
if [ "$last_restart" -gt 0 ] && [ "$((now - last_restart))" -lt "$cooldown" ]; then
return 1
fi
return 0
}
if [ "${WATCHDOG_SOURCE_ONLY:-0}" = "1" ]; then
return 0 2>/dev/null || exit 0
fi
COOKIE_JAR=$(mktemp "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_cookie.XXXXXX")
LOGIN_BODY=$(mktemp "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_login.XXXXXX")
cleanup_watchdog() {
rm -f "${COOKIE_JAR:-}" "${LOGIN_BODY:-}"
}
trap cleanup_watchdog EXIT INT TERM
if [ ! -r "$AUTH_USERNAME_FILE" ] || [ ! -r "$AUTH_PASSWORD_FILE" ]; then
log_watchdog ERROR "Watchdog credentials not readable ($AUTH_USERNAME_FILE / $AUTH_PASSWORD_FILE)."
exit 1
fi
QBIT_USER=$(tr -d '\r\n' < "$AUTH_USERNAME_FILE")
QBIT_PASS=$(tr -d '\r\n' < "$AUTH_PASSWORD_FILE")
if [ ! -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_started" ]; then
log_watchdog INFO "VPN Watchdog active. Monitoring qBittorrent at ${QBIT_HOST} (Interval: ${WATCHDOG_INTERVAL}s, Heartbeat: ${HEARTBEAT_INTERVAL}s, Cooldown: ${WATCHDOG_COOLDOWN_SEC}s)."
touch "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_started"
fi
login_qbit() {
local http_code
http_code=$(curl -s -o /tmp/qbit_watchdog_login_body.txt -w "%{http_code}" -c "$COOKIE_JAR" \
http_code=$(curl -sS -o "$LOGIN_BODY" -w "%{http_code}" --connect-timeout 5 --max-time 15 \
-c "$COOKIE_JAR" \
-H "Referer: http://${QBIT_HOST}" \
--data-urlencode "username=${QBIT_USER}" \
--data-urlencode "password=${QBIT_PASS}" \
@ -47,87 +126,110 @@ login_qbit() {
return 1
fi
awk '$6 ~ /^QBT_SID_/ { found = 1 } END { exit(found ? 0 : 1) }' "$COOKIE_JAR" 2>/dev/null
watchdog_cookie_has_sid "$COOKIE_JAR"
}
api_get() {
qbit_watchdog_get() {
local endpoint="$1"
curl -s -b "$COOKIE_JAR" "http://${QBIT_HOST}${endpoint}"
curl -sS --connect-timeout 5 --max-time 15 \
-b "$COOKIE_JAR" \
-H "Referer: http://${QBIT_HOST}" \
"http://${QBIT_HOST}${endpoint}" 2>/dev/null || true
}
if ! login_qbit; then
log_watchdog ERROR "Failed to authenticate to qBittorrent API."
echo "auth_failed" > "/tmp/qbit_watchdog_last_status"
echo "auth_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status"
exit 1
fi
TORRENTS=$(api_get "/api/v2/torrents/info")
# Check if we recovered from a previous failure
last_status=""
if [ -f "/tmp/qbit_watchdog_last_status" ]; then
last_status=$(cat "/tmp/qbit_watchdog_last_status")
TORRENTS=$(qbit_watchdog_get "/api/v2/torrents/info")
if [ -z "$TORRENTS" ] || ! printf '%s' "$TORRENTS" | jq -e 'type == "array"' >/dev/null 2>&1; then
log_watchdog ERROR "Failed to fetch valid torrent list from qBittorrent API."
echo "api_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status"
exit 1
fi
last_status=""
if [ -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" ]; then
last_status=$(cat "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status")
fi
if [ -n "$last_status" ] && [ "$last_status" != "success" ]; then
log_watchdog INFO "Watchdog recovered: Connection to qBittorrent API restored."
fi
echo "success" > "/tmp/qbit_watchdog_last_status"
echo "success" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status"
num_torrents=0
if [ -n "$TORRENTS" ] && [ "$TORRENTS" != "[]" ]; then
num_torrents=$(echo "$TORRENTS" | jq '. | length')
fi
num_torrents=$(printf '%s' "$TORRENTS" | jq 'length' 2>/dev/null || echo 0)
[[ "$num_torrents" =~ ^[0-9]+$ ]] || num_torrents=0
# Heartbeat log (periodic verification message)
current_time=$(date +%s)
last_heartbeat=0
if [ -f "/tmp/qbit_watchdog_last_heartbeat" ]; then
last_heartbeat=$(cat "/tmp/qbit_watchdog_last_heartbeat")
if [ -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_heartbeat" ]; then
last_heartbeat=$(cat "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_heartbeat" 2>/dev/null || echo 0)
[[ "$last_heartbeat" =~ ^[0-9]+$ ]] || last_heartbeat=0
fi
time_diff=$((current_time - last_heartbeat))
if [ "$time_diff" -ge "$HEARTBEAT_INTERVAL" ]; then
log_watchdog INFO "Heartbeat: Watchdog is active. Connected to qBittorrent. Monitoring ${num_torrents} torrent(s). VPN routing is healthy."
echo "$current_time" > "/tmp/qbit_watchdog_last_heartbeat"
echo "$current_time" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_heartbeat"
fi
if [ -z "$TORRENTS" ] || [ "$TORRENTS" = "[]" ]; then
if [ "$num_torrents" -eq 0 ]; then
log_debug "No torrents found to check. Watchdog check completed silently."
rm -f "$COOKIE_JAR"
exit 0
fi
DETECTED_TORRENTS=()
working_count=0
while IFS='|' read -r hash name; do
while IFS=$'\t' read -r hash name; do
[ -z "$hash" ] && continue
PROPERTIES=$(api_get "/api/v2/torrents/properties?hash=${hash}")
TRACKERS=$(api_get "/api/v2/torrents/trackers?hash=${hash}")
PROPERTIES=$(qbit_watchdog_get "/api/v2/torrents/properties?hash=${hash}")
TRACKERS=$(qbit_watchdog_get "/api/v2/torrents/trackers?hash=${hash}")
has_metadata=$(echo "$PROPERTIES" | jq -r '.has_metadata')
nb_connections=$(echo "$PROPERTIES" | jq -r '.nb_connections')
failed_trackers=$(echo "$TRACKERS" | jq '[.[] | select(.status == 4)] | length')
operation_not_permitted=$(echo "$TRACKERS" | jq '[.[] | select(.status == 4 and (.msg | contains("Operation not permitted")))] | length')
timed_out=$(echo "$TRACKERS" | jq '[.[] | select(.status == 4 and (.msg | contains("timed out")))] | length')
host_not_found=$(echo "$TRACKERS" | jq '[.[] | select(.status == 4 and (.msg | contains("Host not found")))] | length')
if [ "$has_metadata" = "false" ] && [ "$nb_connections" -eq 0 ] && [ "$failed_trackers" -ge 3 ] && \
{ [ "$operation_not_permitted" -gt 0 ] || [ "$timed_out" -gt 0 ] || [ "$host_not_found" -gt 0 ]; }; then
read -r is_broken is_working < <(watchdog_classify_torrent "$PROPERTIES" "$TRACKERS")
if [ "$is_working" -eq 1 ]; then
working_count=$((working_count + 1))
fi
if [ "$is_broken" -eq 1 ]; then
DETECTED_TORRENTS+=("$name")
fi
done < <(echo "$TORRENTS" | jq -r '.[] | [.hash, .name] | @tsv' | tr '\t' '|')
done < <(printf '%s' "$TORRENTS" | jq -r '.[] | [(.hash // ""), (.name // "")] | @tsv' 2>/dev/null || true)
rm -f "$COOKIE_JAR"
broken_count=${#DETECTED_TORRENTS[@]}
if [ "$broken_count" -gt 0 ]; then
last_restart=0
if [ -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_restart" ]; then
last_restart=$(cat "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_restart" 2>/dev/null || echo 0)
[[ "$last_restart" =~ ^[0-9]+$ ]] || last_restart=0
fi
if [ "$working_count" -gt 0 ]; then
log_debug "Ignoring ${broken_count} stalled torrent(s): ${working_count} torrent(s) have active peers/trackers (not a global VPN failure)."
exit 0
fi
# Optional: check Gluetun's local control endpoint if open without blocking on auth
gluetun_status=$(curl -sS --connect-timeout 2 --max-time 5 "${GLUETUN_CONTROL_URL}/v1/openvpn/status" 2>/dev/null | jq -r '.status // empty' 2>/dev/null || true)
if [ -n "$gluetun_status" ] && [ "$gluetun_status" != "running" ]; then
log_watchdog DETECTED "Gluetun reported VPN status '${gluetun_status}'."
fi
if ! watchdog_should_restart_vpn "$broken_count" "$working_count" "$current_time" "$last_restart" "$WATCHDOG_COOLDOWN_SEC"; then
remaining=$((WATCHDOG_COOLDOWN_SEC - (current_time - last_restart)))
log_watchdog INFO "VPN restart cooldown active (${remaining}s remaining); skipping restart for ${broken_count} stalled torrent(s)."
exit 0
fi
if [ ${#DETECTED_TORRENTS[@]} -gt 0 ]; then
log_watchdog DETECTED "VPN routing failure! Torrents with broken-network symptoms found:"
for torrent_name in "${DETECTED_TORRENTS[@]}"; do
log_watchdog DETECTED "$torrent_name"
done
log_watchdog ACTION "Triggering Gluetun restart to fetch a new VPN IP..."
echo "routing_failed" > "/tmp/qbit_watchdog_last_status"
echo "routing_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status"
echo "$current_time" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_restart"
docker restart gluetun
exit 1
fi

View file

@ -30,6 +30,7 @@ Install dir resolution: `ASSEMBLRR_DIR`, `ASSEMBLRR_CONFIG`, then `~/assemblrr`.
|--------|----------------|
| `watchdog_stall.sh` | Stalls qBittorrent connections; checks `vpn-watchdog` |
| `media_purge_e2e.sh` | Full delete cascade for Big Buck Bunny (TMDB 10378) via **Radarr**, **Seerr** (file + request/gateway), and **Jellyfin** APIs |
| `usenet_mock_e2e.sh` | Offline SABnzbd E2E verification against free local `mock_nntp.py` + `mock_newznab.py` servers (zero subscriptions) |
### media_purge_e2e
@ -42,7 +43,13 @@ Requires a running stack with purge wiring (`media-purge-watch` up, `seerr-gatew
5. **Jellyfin** `DELETE /Items/:id` → filesystem delete → `media-purge-watch` → full purge.
6. Asserts Radarr row, `media/`, `torrents/`, and qB torrent are all gone (other titles untouched).
Offline unit for the gateway (no Docker stack): `./tests/unit/test_seerr_gateway.sh` or `python3 scripts/seerr-gateway.py --self-test`.
Offline unit suites for the gateway (no Docker stack):
```bash
./tests/unit/test_seerr_gateway.sh
python3 -m unittest discover -s tests/unit -p 'test_*.py' -v
./tests/unit/test_usenet.sh
```
See also: `docs/seerr-delete-request.md` (behavior + how to retire when Seerr does this natively).

133
tests/fixtures/mock_newznab.py vendored Executable file
View file

@ -0,0 +1,133 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Minimal offline mock Newznab HTTP server for testing SABnzbd/Prowlarr integration
without external Usenet indexers or paid accounts.
"""
from __future__ import annotations
import argparse
import html
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Tuple
from urllib.parse import parse_qs, urlparse
NZB_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE nzb PUBLIC "-//newzBin//DTD NZB 1.1//EN" "http://www.newzbin.com/DTD/nzb/nzb-1.1.dtd">
<nzb xmlns="http://www.newzbin.com/DTD/2003/nzb">
<file poster="test@assemblrr.local" date="1760000000" subject="[1/1] - &quot;assemblrr-sample.txt&quot; yEnc (1/1)">
<groups>
<group>alt.binaries.test</group>
</groups>
<segments>
<segment bytes="{nbytes}" number="1">sample-part1@assemblrr.test</segment>
</segments>
</file>
</nzb>
"""
CAPS_XML = """<?xml version="1.0" encoding="UTF-8"?>
<caps>
<server version="1.0" title="assemblrr mock newznab"/>
<limits max="100" default="100"/>
<searching>
<search available="yes" supportedParams="q"/>
<tv-search available="yes" supportedParams="q,tvdbid,season,ep"/>
<movie-search available="yes" supportedParams="q,imdbid,tmdbid"/>
</searching>
<categories>
<category id="2000" name="Movies">
<subcat id="2040" name="Movies/HD"/>
</category>
<category id="5000" name="TV">
<subcat id="5040" name="TV/HD"/>
</category>
</categories>
</caps>
"""
class _NewznabHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt: str, *args) -> None:
return
def _send(self, status: int, content_type: str, body: str) -> None:
raw = body.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_GET(self) -> None: # noqa: N802
parsed = urlparse(self.path)
qs = parse_qs(parsed.query)
t = (qs.get("t") or [""])[0].lower()
if parsed.path in ("/health", "/ping"):
self._send(200, "application/json", '{"ok":true}')
return
if t == "caps":
self._send(200, "application/xml; charset=utf-8", CAPS_XML)
return
if t in ("search", "movie", "tvsearch"):
host = self.headers.get("Host") or f"127.0.0.1:{self.server.server_address[1]}"
nzb_url = html.escape(f"http://{host}/api?t=get&id=sample-1")
rss = (
'<?xml version="1.0" encoding="UTF-8"?>'
'<rss version="2.0" xmlns:newznab="http://www.newznab.com/DTD/2010/feeds/attributes/">'
"<channel><title>assemblrr mock newznab</title>"
"<item><title>Alpha.Film.2016.1080p.WEB</title>"
'<guid isPermaLink="false">sample-1</guid>'
f'<link>{nzb_url}</link>'
f'<enclosure url="{nzb_url}" length="33" type="application/x-nzb"/>'
'<category>2040</category>'
'<newznab:attr name="category" value="2000"/>'
"</item></channel></rss>"
)
self._send(200, "application/rss+xml; charset=utf-8", rss)
return
if t == "get":
self._send(200, "application/x-nzb; charset=utf-8", NZB_TEMPLATE.format(nbytes=4096))
return
self._send(404, "application/xml; charset=utf-8", '<error code="404" description="not found"/>')
class MockNewznabServer(ThreadingHTTPServer):
daemon_threads = True
def start_background(host: str = "127.0.0.1", port: int = 0) -> MockNewznabServer:
srv = MockNewznabServer((host, port), _NewznabHandler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
def main() -> int:
ap = argparse.ArgumentParser(description="Offline mock Newznab HTTP server")
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--port", type=int, default=8182)
ap.add_argument("--port-file", default="")
args = ap.parse_args()
srv = MockNewznabServer((args.host, args.port), _NewznabHandler)
actual_port = srv.server_address[1]
if args.port_file:
with open(args.port_file, "w", encoding="utf-8") as fh:
fh.write(f"{actual_port}\n")
print(f"LISTENING {actual_port}", flush=True)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
finally:
srv.server_close()
return 0
if __name__ == "__main__":
sys.exit(main())

196
tests/fixtures/mock_nntp.py vendored Executable file
View file

@ -0,0 +1,196 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Minimal offline mock NNTP server for testing SABnzbd / Usenet integrations
without external Usenet subscriptions or network access.
Serves a synthetic yEnc-encoded payload for `<sample-part1@assemblrr.test>`.
"""
from __future__ import annotations
import argparse
import binascii
import socketserver
import sys
import threading
from typing import Optional, Tuple
PAYLOAD_NAME = "assemblrr-sample.txt"
PAYLOAD_BYTES = b"assemblrr mock usenet payload ok\n"
MESSAGE_ID = "<sample-part1@assemblrr.test>"
GROUP_NAME = "alt.binaries.test"
def yenc_encode(data: bytes, filename: str = PAYLOAD_NAME) -> bytes:
"""Encode bytes into a single-part yEnc article body."""
crc = binascii.crc32(data) & 0xFFFFFFFF
encoded = bytearray()
col = 0
for b in data:
yb = (b + 42) & 0xFF
if yb in (0, 10, 13, 61):
encoded.append(61)
encoded.append((yb + 64) & 0xFF)
col += 2
else:
encoded.append(yb)
col += 1
if col >= 128:
encoded.extend(b"\r\n")
col = 0
if col > 0:
encoded.extend(b"\r\n")
header = (
f"=ybegin part=1 line=128 size={len(data)} name={filename}\r\n"
f"=ypart begin=1 end={len(data)}\r\n"
).encode("ascii")
footer = (
f"=yend size={len(data)} part=1 pcrc32={crc:08x} crc32={crc:08x}\r\n"
).encode("ascii")
return header + bytes(encoded) + footer
ARTICLE_BODY = yenc_encode(PAYLOAD_BYTES, PAYLOAD_NAME)
ARTICLE_HEADERS = (
f"From: test@assemblrr.local\r\n"
f"Newsgroups: {GROUP_NAME}\r\n"
f'Subject: [1/1] - "{PAYLOAD_NAME}" yEnc (1/1)\r\n'
f"Message-ID: {MESSAGE_ID}\r\n"
).encode("ascii")
def _dot_stuff(body: bytes) -> bytes:
lines = body.split(b"\r\n")
out = []
for line in lines:
if line.startswith(b"."):
out.append(b"." + line)
else:
out.append(line)
return b"\r\n".join(out)
class _NNTPHandler(socketserver.StreamRequestHandler):
def handle(self) -> None:
server = self.server # type: ignore[attr-defined]
authed = not bool(server.username)
pending_user: Optional[str] = None
self.wfile.write(b"200 assemblrr-mock-nntp Service Ready\r\n")
self.wfile.flush()
while True:
raw = self.rfile.readline(4096)
if not raw:
break
line = raw.decode("utf-8", errors="replace").strip()
if not line:
continue
parts = line.split()
cmd = parts[0].upper()
arg = " ".join(parts[1:]) if len(parts) > 1 else ""
if cmd == "QUIT":
self.wfile.write(b"205 closing connection\r\n")
self.wfile.flush()
break
if cmd == "CAPABILITIES":
self.wfile.write(
b"101 Capability list:\r\nVERSION 2\r\nREADER\r\nAUTHINFO USER\r\n.\r\n"
)
elif cmd == "MODE" and arg.upper() == "READER":
self.wfile.write(b"200 Reading active\r\n")
elif cmd == "DATE":
self.wfile.write(b"111 20261121120000\r\n")
elif cmd == "AUTHINFO":
sub = parts[1].upper() if len(parts) > 1 else ""
val = " ".join(parts[2:]) if len(parts) > 2 else ""
if sub == "USER":
pending_user = val
if server.username and not server.password:
if val == server.username:
authed = True
self.wfile.write(b"281 Authentication accepted\r\n")
else:
self.wfile.write(b"481 Authentication rejected\r\n")
else:
self.wfile.write(b"381 Password required\r\n")
elif sub == "PASS":
if (not server.username) or (
pending_user == server.username and val == server.password
):
authed = True
self.wfile.write(b"281 Authentication accepted\r\n")
else:
self.wfile.write(b"481 Authentication rejected\r\n")
else:
self.wfile.write(b"501 Syntax error\r\n")
elif not authed:
self.wfile.write(b"480 Authentication required\r\n")
elif cmd == "GROUP":
self.wfile.write(f"211 1 1 1 {arg or GROUP_NAME}\r\n".encode("ascii"))
elif cmd in ("STAT", "HEAD", "BODY", "ARTICLE"):
target = arg or "1"
found = target in ("1", MESSAGE_ID, MESSAGE_ID.strip("<>"))
if not found:
self.wfile.write(b"430 No such article found\r\n")
elif cmd == "STAT":
self.wfile.write(f"223 1 {MESSAGE_ID} article exists\r\n".encode("ascii"))
elif cmd == "HEAD":
self.wfile.write(f"221 1 {MESSAGE_ID} headers\r\n".encode("ascii"))
self.wfile.write(ARTICLE_HEADERS + b".\r\n")
elif cmd == "BODY":
self.wfile.write(f"222 1 {MESSAGE_ID} body\r\n".encode("ascii"))
self.wfile.write(_dot_stuff(ARTICLE_BODY) + b".\r\n")
else:
self.wfile.write(f"220 1 {MESSAGE_ID} article\r\n".encode("ascii"))
self.wfile.write(ARTICLE_HEADERS + b"\r\n" + _dot_stuff(ARTICLE_BODY) + b".\r\n")
else:
self.wfile.write(b"500 Unknown command\r\n")
self.wfile.flush()
class MockNNTPServer(socketserver.ThreadingTCPServer):
allow_reuse_address = True
daemon_threads = True
def __init__(self, server_address: Tuple[str, int], username: str = "", password: str = ""):
self.username = username
self.password = password
super().__init__(server_address, _NNTPHandler)
def start_background(
host: str = "127.0.0.1", port: int = 0, username: str = "", password: str = ""
) -> MockNNTPServer:
srv = MockNNTPServer((host, port), username=username, password=password)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
def main() -> int:
ap = argparse.ArgumentParser(description="Offline mock NNTP server")
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--port", type=int, default=1119)
ap.add_argument("--user", default="")
ap.add_argument("--password", default="")
ap.add_argument("--port-file", default="")
args = ap.parse_args()
srv = MockNNTPServer((args.host, args.port), username=args.user, password=args.password)
actual_port = srv.server_address[1]
if args.port_file:
with open(args.port_file, "w", encoding="utf-8") as fh:
fh.write(f"{actual_port}\n")
print(f"LISTENING {actual_port}", flush=True)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
finally:
srv.server_close()
return 0
if __name__ == "__main__":
sys.exit(main())

View file

@ -0,0 +1,100 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Offline Docker E2E test for SABnzbd + Usenet wiring against local mock_nntp.py & mock_newznab.py.
# Zero external internet calls or paid Usenet providers required.
# Opt-in live container check: ASSEMBLRR_ALLOW_LIVE_TEST=1 ./tests/integration/usenet_mock_e2e.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
if [ "${ASSEMBLRR_ALLOW_LIVE_TEST:-}" != "1" ]; then
echo "Refusing to spin up temporary SABnzbd container without ASSEMBLRR_ALLOW_LIVE_TEST=1" >&2
exit 2
fi
command -v docker >/dev/null || { echo "docker is required" >&2; exit 1; }
command -v python3 >/dev/null || { echo "python3 is required" >&2; exit 1; }
command -v curl >/dev/null || { echo "curl is required" >&2; exit 1; }
command -v jq >/dev/null || { echo "jq is required" >&2; exit 1; }
tmp=$(mktemp -d)
nntp_pid="" newznab_pid="" cid=""
cleanup() {
[ -n "$cid" ] && docker rm -f "$cid" >/dev/null 2>&1 || true
[ -n "$nntp_pid" ] && kill "$nntp_pid" >/dev/null 2>&1 || true
[ -n "$newznab_pid" ] && kill "$newznab_pid" >/dev/null 2>&1 || true
rm -rf "$tmp"
}
trap cleanup EXIT INT TERM
mkdir -p "$tmp/config" "$tmp/data/usenet/incomplete" "$tmp/data/usenet/complete/movies" "$tmp/data/usenet/complete/tv"
python3 "$REPO_ROOT/tests/fixtures/mock_nntp.py" --host 0.0.0.0 --port 0 --user mockuser --password mockpass --port-file "$tmp/nntp.port" &
nntp_pid=$!
python3 "$REPO_ROOT/tests/fixtures/mock_newznab.py" --host 0.0.0.0 --port 0 --port-file "$tmp/newznab.port" &
newznab_pid=$!
for _ in $(seq 1 30); do
[ -s "$tmp/nntp.port" ] && [ -s "$tmp/newznab.port" ] && break
sleep 0.2
done
nntp_port=$(tr -d '\r\n' < "$tmp/nntp.port")
newznab_port=$(tr -d '\r\n' < "$tmp/newznab.port")
echo "Started mock NNTP :${nntp_port} and mock Newznab :${newznab_port}"
cid=$(docker run -d --network host \
-e "PUID=$(id -u)" -e "PGID=$(id -g)" -e "TZ=UTC" \
-v "$tmp/config:/config" \
-v "$tmp/data:/data" \
lscr.io/linuxserver/sabnzbd:5.1.3)
# shellcheck source=/dev/null
source "$REPO_ROOT/lib/core.sh"
# shellcheck source=/dev/null
source "$REPO_ROOT/lib/api.sh"
# shellcheck source=/dev/null
source "$REPO_ROOT/lib/usenet.sh"
INSTALL_DIR="$tmp"
USENET_ENABLED="y"
USENET_HOST="127.0.0.1"
USENET_PORT="$nntp_port"
USENET_SSL="n"
USENET_USERNAME="mockuser"
USENET_CONNECTIONS="2"
AUTH_USERNAME="admin"
AUTH_PASSWORD="testpassword123"
API_HOST="127.0.0.1"
SABNZBD_PORT=8080
mkdir -p "$tmp/secrets"
write_secret_file "$tmp/secrets/usenet_password.txt" "mockpass"
# Wait for SABnzbd first-boot ini & API
sab_key=$(read_sabnzbd_api_key 2>/dev/null || true)
[ -n "$sab_key" ] || { echo "SABnzbd did not initialize sabnzbd.ini" >&2; exit 1; }
# Configure mock NNTP server in SABnzbd via configure_sabnzbd
configure_sabnzbd
# Fetch mock NZB and push via SABnzbd addfile/addurl
curl -sf "http://127.0.0.1:${newznab_port}/api?t=get&id=sample-1" > "$tmp/sample.nzb"
curl -sf -F "name=@${tmp}/sample.nzb" -F "cat=movies" \
"http://127.0.0.1:${SABNZBD_PORT}/api?mode=addfile&apikey=${sab_key}&output=json" >/dev/null
# Wait up to 30s for mock NZB completion
ok=0
for _ in $(seq 1 30); do
hist=$(curl -sf "http://127.0.0.1:${SABNZBD_PORT}/api?mode=history&apikey=${sab_key}&output=json" || echo "{}")
if printf '%s' "$hist" | jq -e '.history.slots[]? | select(.status == "Completed")' >/dev/null 2>&1; then
ok=1
break
fi
sleep 1
done
[ "$ok" -eq 1 ] || { echo "Mock NZB did not complete in SABnzbd" >&2; exit 1; }
found=$(find "$tmp/data/usenet/complete" -name "assemblrr-sample.txt" 2>/dev/null | head -1 || true)
[ -n "$found" ] || { echo "Decoded file missing under $tmp/data/usenet/complete" >&2; exit 1; }
grep -qx "assemblrr mock usenet payload ok" "$found"
echo "STATUS: OK (SABnzbd downloaded & yEnc-decoded mock NZB from mock_nntp.py)"

View file

@ -1,4 +1,5 @@
#!/bin/bash
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Usage: ./tests/run.sh [unit|compose|integration|lint|all]
set -euo pipefail
@ -9,13 +10,10 @@ cd "$REPO_ROOT"
MODE="${1:-unit}"
FAILED=0
run_scripts() {
local dir="$1"
local pattern="$2"
local count=0
local f
shopt -s nullglob
for f in "$dir"/$pattern; do
run_unit() {
echo "Running shell unit tests..."
local count=0 f
while IFS= read -r -d '' f; do
count=$((count + 1))
echo ""
echo "######## $(basename "$f") ########"
@ -25,44 +23,23 @@ run_scripts() {
echo "-> FAILED"
FAILED=$((FAILED + 1))
fi
done
shopt -u nullglob
done < <(find "$SCRIPT_DIR/unit" -maxdepth 1 -type f -name 'test_*.sh' -print0 | sort -z)
if [ "$count" -eq 0 ]; then
echo "No tests matched $dir/$pattern"
echo "No shell unit tests found under $SCRIPT_DIR/unit"
FAILED=$((FAILED + 1))
fi
}
run_unit() {
echo "Running unit tests..."
for f in \
"$SCRIPT_DIR/unit/test_api.sh" \
"$SCRIPT_DIR/unit/test_arr_quality.sh" \
"$SCRIPT_DIR/unit/test_compose.sh" \
"$SCRIPT_DIR/unit/test_config_edit.sh" \
"$SCRIPT_DIR/unit/test_core.sh" \
"$SCRIPT_DIR/unit/test_env_example.sh" \
"$SCRIPT_DIR/unit/test_fzf_tui.sh" \
"$SCRIPT_DIR/unit/test_jellyfin_refresh.sh" \
"$SCRIPT_DIR/unit/test_media_purge_match.sh" \
"$SCRIPT_DIR/unit/test_media_purge_watch.sh" \
"$SCRIPT_DIR/unit/test_prepare_install_dirs.sh" \
"$SCRIPT_DIR/unit/test_quality.sh" \
"$SCRIPT_DIR/unit/test_qbit_prefs.sh" \
"$SCRIPT_DIR/unit/test_seerr_gateway.sh" \
"$SCRIPT_DIR/unit/test_ui.sh" \
"$SCRIPT_DIR/unit/test_upgrade.sh" \
"$SCRIPT_DIR/unit/test_vpn_secrets.sh"
do
if command -v python3 >/dev/null 2>&1; then
echo ""
echo "######## $(basename "$f") ########"
if bash "$f"; then
echo "######## Python unittest suite ########"
if python3 -m unittest discover -s "$SCRIPT_DIR/unit" -p 'test_*.py' -v; then
echo "-> OK"
else
echo "-> FAILED"
FAILED=$((FAILED + 1))
fi
done
fi
}
run_compose() {
@ -82,8 +59,10 @@ run_integration() {
local f
for f in \
"$SCRIPT_DIR/integration/watchdog_stall.sh" \
"$SCRIPT_DIR/integration/media_purge_e2e.sh"
"$SCRIPT_DIR/integration/media_purge_e2e.sh" \
"$SCRIPT_DIR/integration/usenet_mock_e2e.sh"
do
[ -f "$f" ] || continue
echo ""
echo "######## $(basename "$f") ########"
if bash "$f"; then
@ -97,22 +76,49 @@ run_integration() {
}
run_lint() {
local files=() f
while IFS= read -r -d '' f; do
files+=("$f")
done < <(find bin lib scripts migrations platform/linux tests -name '*.sh' -print0 2>/dev/null)
if [ "${#files[@]}" -gt 0 ]; then
echo "Running bash -n syntax checks (${#files[@]} files)..."
if bash -n "${files[@]}"; then
echo "bash -n: OK"
else
echo "bash -n: FAILED"
FAILED=$((FAILED + 1))
fi
fi
if command -v python3 >/dev/null 2>&1; then
local py_files=()
while IFS= read -r -d '' f; do
py_files+=("$f")
done < <(find scripts tests -name '*.py' -print0 2>/dev/null)
if [ "${#py_files[@]}" -gt 0 ]; then
echo "Running Python py_compile (${#py_files[@]} files)..."
if python3 -m py_compile "${py_files[@]}"; then
echo "py_compile: OK"
else
echo "py_compile: FAILED"
FAILED=$((FAILED + 1))
fi
fi
fi
if ! command -v shellcheck >/dev/null 2>&1; then
echo "shellcheck not installed — skip lint"
if [ "${CI:-}" = "true" ]; then
echo "ERROR: shellcheck is missing in CI environment" >&2
FAILED=$((FAILED + 1))
return 1
fi
echo "shellcheck not installed — skip locally (enforced in CI)"
echo " Install: https://github.com/koalaman/shellcheck#installing"
return 0
fi
echo "Running shellcheck..."
local files=()
while IFS= read -r -d '' f; do
files+=("$f")
done < <(find bin lib scripts tests -name '*.sh' -print0 2>/dev/null)
if [ "${#files[@]}" -eq 0 ]; then
echo "No shell files found"
return 0
fi
if shellcheck -x -e SC1091,SC2034 "${files[@]}"; then
echo "shellcheck: OK"
else
@ -122,18 +128,10 @@ run_lint() {
}
case "$MODE" in
unit)
run_unit
;;
compose)
run_compose
;;
integration|live)
run_integration
;;
lint)
run_lint
;;
unit) run_unit ;;
compose) run_compose ;;
integration|live) run_integration ;;
lint) run_lint ;;
all)
run_unit
run_compose

0
tests/unit/test_api.sh Normal file → Executable file
View file

2
tests/unit/test_arr_quality.sh Normal file → Executable file
View file

@ -36,7 +36,7 @@ assert_eq "null" "$(echo "$out" | jq -r '.unmappedFolders')" "drops unmappedFold
assert_eq "/data/media/movies" "$(echo "$out" | jq -r '.path')" "keeps path"
test_suite "set_default_quality_profile applies, not just records"
src="$REPO_ROOT/lib/arr.sh"
src="$REPO_ROOT/lib/arr_quality.sh"
apply=$(sed -n '/^set_default_quality_profile()/,/^}/p' "$src")
assert_true "sets root-folder default" "grep -q defaultQualityProfileId \"$src\""
assert_true "updates import lists" "grep -q '/api/v3/importlist/' \"$src\""

78
tests/unit/test_cli.sh Executable file
View file

@ -0,0 +1,78 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Unit tests for bin/cli.sh (help, source-safety, archive validation, show_config)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/../helpers.sh"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
test_suite "cli.sh --help works without existing install tree"
help_out=$(HOME="$tmp" ASSEMBLRR_DIR="" bash "$REPO_ROOT/bin/cli.sh" --help)
assert_contains "$help_out" "Lifecycle:" "grouped help shows Lifecycle"
assert_contains "$help_out" "Configuration & Upgrades:" "grouped help shows Configuration"
assert_contains "$help_out" "Operations & Backups:" "grouped help shows Operations"
assert_contains "$help_out" "config [show|edit|apply]" "lists config subcommands"
help_short=$(HOME="$tmp" ASSEMBLRR_DIR="" bash "$REPO_ROOT/bin/cli.sh" -h)
assert_eq "$help_out" "$help_short" "-h matches --help deterministically"
test_suite "cli.sh can be sourced without running main or needing install dir"
# shellcheck source=/dev/null
source "$REPO_ROOT/bin/cli.sh"
INSTALL_DIR="$tmp/inst"
MEDIA_DIRECTORY="$tmp/media"
mkdir -p "$INSTALL_DIR" "$MEDIA_DIRECTORY"
cfg_out=$(ASSEMBLRR_SHOW_LEFTOVERS=0 show_config)
assert_contains "$cfg_out" "Media service: jellyfin" "show_config displays jellyfin"
assert_contains "$cfg_out" "SABnzbd / Usenet:" "show_config displays new feature rows"
test_suite "validate_backup_archive rejects missing .env and path traversal"
bad_noenv="$tmp/noenv.tar.gz"
mkdir -p "$tmp/b1"
touch "$tmp/b1/foo.txt"
tar -czf "$bad_noenv" -C "$tmp/b1" .
assert_failure "rejects archive missing .env" validate_backup_archive "$bad_noenv"
bad_trav="$tmp/trav.tar.gz"
python3 - "$bad_trav" <<'PY'
import io, sys, tarfile
with tarfile.open(sys.argv[1], "w:gz") as tf:
info = tarfile.TarInfo("../evil.txt")
data = b"x"
info.size = len(data)
tf.addfile(info, io.BytesIO(data))
PY
assert_failure "rejects archive with .. traversal" validate_backup_archive "$bad_trav"
good_arc="$tmp/good.tar.gz"
mkdir -p "$tmp/b2"
echo "PUID=1000" > "$tmp/b2/.env"
tar -czf "$good_arc" -C "$tmp/b2" .
assert_success "accepts valid backup containing .env" validate_backup_archive "$good_arc"
test_suite "update_containers explains pinned images"
uc_fn=$(sed -n '/^update_containers()/,/^}/p' "$REPO_ROOT/bin/cli.sh")
assert_contains "$uc_fn" "pins core service image tags" "mentions pinned core images"
assert_contains "$uc_fn" "upgrade" "points users to assemblrr upgrade"
test_suite "read_prompt 1-arg REPLY and interactive uninstall_app cancel"
REPLY=""
read_prompt "Confirm: " <<< "yes"
assert_eq "yes" "$REPLY" "1-arg read_prompt populates REPLY under set -u"
uninst_out=$(ASSEMBLRR_SHOW_LEFTOVERS=0 HOME="$tmp" uninstall_app <<< "no" 2>&1)
assert_contains "$uninst_out" "Uninstall cancelled." "1-arg read_prompt in uninstall_app cancels cleanly"
assert_true "INSTALL_DIR preserved on cancel" "[ -d \"$INSTALL_DIR\" ]"
uninst_fn=$(sed -n '/^uninstall_app()/,/^}/p' "$REPO_ROOT/bin/cli.sh")
assert_not_contains "$uninst_fn" "Type the full path" "does not require typing full paths"
assert_contains "$uninst_fn" "wait_while" "shows live spinner while stopping containers"
test_suite "status --help documents --all and --docker"
status_help=$(check_status --help)
assert_contains "$status_help" "--all" "status help documents --all"
assert_contains "$status_help" "--docker" "status help documents --docker"
test_summary

View file

@ -1,5 +1,6 @@
#!/bin/bash
# Unit tests for lib/compose.sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Unit tests for lib/compose.sh and Compose image pinning
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@ -14,7 +15,11 @@ tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
mkdir -p "$tmp/compose"
touch "$tmp/compose/base.yaml" "$tmp/compose/vpn.yaml" "$tmp/compose/direct-access.yaml"
touch "$tmp/compose/base.yaml" "$tmp/compose/vpn.yaml" "$tmp/compose/direct-access.yaml" \
"$tmp/compose/vuetorrent.yaml" "$tmp/compose/gpu-intel.yaml" "$tmp/compose/gpu-nvidia.yaml" \
"$tmp/compose/byparr.yaml" "$tmp/compose/usenet.yaml"
VUETORRENT_ENABLED=n GPU_TRANSCODING=none BYPARR_ENABLED=n USENET_ENABLED=n
test_suite "build_compose_args (VPN enabled)"
build_compose_args "$tmp" "y"
@ -30,37 +35,67 @@ joined="${COMPOSE_ARGS[*]}"
assert_contains "$joined" "-f $tmp/compose/direct-access.yaml" "includes direct-access when VPN=n"
assert_not_contains "$joined" "vpn.yaml" "excludes vpn when VPN=n"
test_suite "build_compose_args (custom overlay)"
test_suite "build_compose_args (feature overlays & custom order)"
VUETORRENT_ENABLED=y GPU_TRANSCODING=intel BYPARR_ENABLED=y USENET_ENABLED=y
touch "$tmp/compose/custom.yaml"
build_compose_args "$tmp" "n"
build_compose_args "$tmp" "y"
joined="${COMPOSE_ARGS[*]}"
assert_contains "$joined" "-f $tmp/compose/custom.yaml" "includes custom.yaml when present"
assert_contains "$joined" "-f $tmp/compose/vuetorrent.yaml" "includes vuetorrent.yaml"
assert_contains "$joined" "-f $tmp/compose/gpu-intel.yaml" "includes gpu-intel.yaml"
assert_not_contains "$joined" "gpu-nvidia.yaml" "excludes gpu-nvidia when intel selected"
assert_contains "$joined" "-f $tmp/compose/byparr.yaml" "includes byparr.yaml"
assert_contains "$joined" "-f $tmp/compose/usenet.yaml" "includes usenet.yaml"
assert_contains "$joined" "usenet.yaml -f $tmp/compose/custom.yaml" "custom.yaml appended last"
GPU_TRANSCODING=nvidia
build_compose_args "$tmp" "n"
assert_contains "${COMPOSE_ARGS[*]}" "-f $tmp/compose/gpu-nvidia.yaml" "includes gpu-nvidia.yaml"
VUETORRENT_ENABLED=n GPU_TRANSCODING=none BYPARR_ENABLED=n USENET_ENABLED=n
rm -f "$tmp/compose/custom.yaml"
test_suite "build_compose_args (case-insensitive VPN flag)"
rm -f "$tmp/compose/custom.yaml"
build_compose_args "$tmp" "Y"
joined="${COMPOSE_ARGS[*]}"
assert_contains "$joined" "vpn.yaml" "VPN=Y treated as enabled"
assert_contains "${COMPOSE_ARGS[*]}" "vpn.yaml" "VPN=Y treated as enabled"
test_suite "recyclarr image tag"
recyclarr_image=$(grep -E '^\s+image:.*recyclarr' "$REPO_ROOT/compose/base.yaml")
assert_contains "$recyclarr_image" "ghcr.io/recyclarr/recyclarr:8.7.1" "pins recyclarr 8.7.1"
assert_contains "$recyclarr_image" "ghcr.io/recyclarr/recyclarr:8.8.1" "pins recyclarr 8.8.1"
assert_not_contains "$recyclarr_image" ":latest" "does not use unpublished :latest"
assert_contains "$(grep CRON "$REPO_ROOT/compose/base.yaml")" "CRON_SCHEDULE" "uses CRON_SCHEDULE"
test_suite "default stack images are version-pinned"
images=$(grep -E '^\s+image:' "$REPO_ROOT/compose/base.yaml" "$REPO_ROOT/compose/vpn.yaml")
assert_not_contains "$images" ":latest" "no :latest in default compose"
assert_contains "$images" "linuxserver/jellyfin:10.11.11" "jellyfin pinned"
assert_contains "$images" "linuxserver/qbittorrent:5.2.3" "qbittorrent pinned"
assert_contains "$images" "seerr-team/seerr:v3.4.1" "seerr pinned"
assert_contains "$images" "python:3.12.14-alpine" "gateway python pinned"
assert_contains "$images" "gluetun:v3.41.3" "gluetun pinned"
assert_contains "$images" "deunhealth:v0.3.0" "deunhealth pinned"
# Local sidecar tags are not registry floats
test_suite "default & feature stack images are pinned (no :latest)"
images=$(grep -E '^\s+image:' \
"$REPO_ROOT/compose/base.yaml" \
"$REPO_ROOT/compose/vpn.yaml" \
"$REPO_ROOT/compose/byparr.yaml" \
"$REPO_ROOT/compose/usenet.yaml")
assert_not_contains "$images" ":latest" "no :latest in any compose file"
assert_contains "$images" "linuxserver/jellyfin:12.4ubu2604-ls60" "jellyfin 12.4 pinned"
assert_contains "$images" "linuxserver/qbittorrent:5.3.0" "qbittorrent 5.3.0 pinned"
assert_contains "$images" "linuxserver/sonarr:4.0.20.3014-ls6" "sonarr pinned"
assert_contains "$images" "linuxserver/radarr:7.0.3.10918-ls328" "radarr pinned"
assert_contains "$images" "linuxserver/prowlarr:3.0.2.5780-ls169" "prowlarr pinned"
assert_contains "$images" "linuxserver/bazarr:1.6.2" "bazarr 1.6.2 pinned"
assert_contains "$images" "linuxserver/sabnzbd:5.1.3" "sabnzbd 5.1.3 pinned"
assert_contains "$images" "seerr-team/seerr:v3.5.2" "seerr v3.5.2 pinned"
assert_contains "$images" "python:3.12.16-alpine" "gateway python pinned"
assert_contains "$images" "gluetun:v3.41.3" "gluetun v3.41.3 pinned"
assert_contains "$images" "deunhealth@sha256:db1e4fcd3aceeb0da34a83f7a8a5432df586e6d0388ddb6ad8dd7b479e4aa25d" "deunhealth digest pinned"
assert_contains "$images" "thephaseless/byparr:3.1.1" "byparr 3.1.1 pinned"
assert_contains "$(cat "$REPO_ROOT/compose/vuetorrent.yaml")" "vuetorrent/vuetorrent-lsio-mod:2.37.0" "vuetorrent mod pinned"
assert_contains "$images" "assemblrr/media-purge-watch:local" "purge sidecar is local"
assert_contains "$images" "assemblrr/vpn-watchdog:local" "watchdog sidecar is local"
test_suite "sidecar Dockerfiles pin alpine:3.24.4"
assert_contains "$(cat "$REPO_ROOT/compose/sidecars/media-purge-watch.Dockerfile")" "FROM alpine:3.24.4" "purge-watch alpine pinned"
assert_contains "$(cat "$REPO_ROOT/compose/sidecars/vpn-watchdog.Dockerfile")" "FROM alpine:3.24.4" "vpn-watchdog alpine pinned"
test_suite "jellyfin is default without --profile gate & no broken plex/emby in base.yaml"
assert_not_contains "$(cat "$REPO_ROOT/compose/base.yaml")" 'profiles: ["jellyfin"]' "no jellyfin profile gate"
assert_not_contains "$(cat "$REPO_ROOT/compose/base.yaml")" 'container_name: emby' "emby removed from base.yaml"
assert_not_contains "$(cat "$REPO_ROOT/compose/base.yaml")" 'container_name: plex' "plex removed from base.yaml"
test_suite "local sidecar images do not pull from a registry"
assert_contains "$(awk '/media-purge-watch:/,/^ [a-z]/{print}' "$REPO_ROOT/compose/base.yaml")" \
"pull_policy: build" "media-purge-watch builds locally"

View file

@ -1,5 +1,6 @@
#!/bin/bash
# Validate compose files resolve with docker compose config
# SPDX-License-Identifier: GPL-3.0-or-later
# Validate all compose files and feature overlays resolve with docker compose config
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@ -24,7 +25,7 @@ run_config() {
local label="$1"
shift
echo " checking: $label"
if docker compose --project-directory "$tmp" "$@" --profile jellyfin config --quiet 2>"$tmp/compose-err.txt"; then
if docker compose --project-directory "$tmp" "$@" config --quiet 2>"$tmp/compose-err.txt"; then
_TEST_PASSES=$((_TEST_PASSES + 1))
echo " PASS: $label"
return 0
@ -35,20 +36,45 @@ run_config() {
return 0
}
test_suite "docker compose config"
test_suite "docker compose config (default & overlays)"
run_config "base + direct-access" \
-f "$tmp/compose/base.yaml" \
-f "$tmp/compose/direct-access.yaml"
run_config "base + direct-access (--profile jellyfin back-compat)" \
-f "$tmp/compose/base.yaml" \
-f "$tmp/compose/direct-access.yaml" \
--profile jellyfin
run_config "base + vpn" \
-f "$tmp/compose/base.yaml" \
-f "$tmp/compose/vpn.yaml"
# example custom.yaml has only commented services; use a valid empty overlay
run_config "base + vpn + vuetorrent + gpu-intel + byparr + usenet" \
-f "$tmp/compose/base.yaml" \
-f "$tmp/compose/vpn.yaml" \
-f "$tmp/compose/vuetorrent.yaml" \
-f "$tmp/compose/gpu-intel.yaml" \
-f "$tmp/compose/byparr.yaml" \
-f "$tmp/compose/usenet.yaml"
run_config "base + direct-access + gpu-nvidia + usenet" \
-f "$tmp/compose/base.yaml" \
-f "$tmp/compose/direct-access.yaml" \
-f "$tmp/compose/gpu-nvidia.yaml" \
-f "$tmp/compose/usenet.yaml"
# Verify a real service in custom overlay with .30+ IP validates cleanly
cat >"$tmp/compose/custom.yaml" <<'EOF'
services: {}
services:
lidarr:
image: lscr.io/linuxserver/lidarr:3.1.0
container_name: lidarr
networks:
assemblrr_network:
ipv4_address: 172.60.0.32
EOF
run_config "base + direct-access + custom overlay" \
run_config "base + direct-access + custom overlay (.32 IP)" \
-f "$tmp/compose/base.yaml" \
-f "$tmp/compose/direct-access.yaml" \
-f "$tmp/compose/custom.yaml"

17
tests/unit/test_config_edit.sh Normal file → Executable file
View file

@ -21,6 +21,10 @@ assert_contains "$ids" "providers" "lists providers"
assert_contains "$ids" "language" "lists language"
assert_contains "$ids" "profile" "lists profile"
assert_contains "$ids" "vpn" "lists vpn"
assert_contains "$ids" "vuetorrent" "lists vuetorrent"
assert_contains "$ids" "gpu" "lists gpu"
assert_contains "$ids" "byparr" "lists byparr"
assert_contains "$ids" "usenet" "lists usenet"
assert_contains "$ids" "all" "lists all (full wizard)"
test_suite "config_edit_resolve"
@ -158,4 +162,17 @@ assert_contains "$(sed -n '/^configure_seerr()/,/^seerr_verify_login()/p' "$REPO
assert_contains "$(sed -n '/^configure_jellyfin_libraries()/,/^}/p' "$REPO_ROOT/lib/jellyfin.sh")" \
'jq -nc --arg u' "jellyfin library auth jq-escapes password"
test_suite "config_edit regressions: _config_edit_all, non-fzf stdout, kv escaping & mode"
assert_contains "$(sed -n '/^_config_edit_all()/,/^}/p' "$REPO_ROOT/lib/config_edit.sh")" \
'--reconfigure' "_config_edit_all passes --reconfigure"
sec_f="$tmp/sec.conf"
: > "$sec_f"
chmod 600 "$sec_f"
config_set_kv "$sec_f" "VAL" 'a"b' 1
assert_contains "$(cat "$sec_f")" 'VAL="a\"b"' "escapes embedded quotes cleanly"
perm=$(stat -c '%a' "$sec_f" 2>/dev/null || stat -f '%Lp' "$sec_f")
assert_eq "600" "$perm" "preserves 0600 permissions after atomic update"
picked=$(_config_edit_pick <<< "1" 2>/dev/null)
assert_eq "indexers" "$picked" "non-fzf _config_edit_pick emits only the section id on stdout"
test_summary

View file

@ -17,16 +17,20 @@ test_suite "flush_tty_input / read_prompt"
assert_success "flush_tty_input returns 0" flush_tty_input
assert_true "read_prompt exists" "type read_prompt >/dev/null"
# EOF on stdin must not trip set -e when /dev/tty is unavailable to the helper's else branch.
src=$(sed -n '/^read_prompt()/,/^}/p' "$REPO_ROOT/lib/core.sh")
src=$(sed -n '/^read_prompt()/,/^}/p' "$REPO_ROOT/lib/tty.sh")
assert_contains "$src" '</dev/tty' "read_prompt reads the tty"
assert_contains "$src" '|| true' "read_prompt ignores EOF"
flush_src=$(sed -n '/^flush_tty_input()/,/^}/p' "$REPO_ROOT/lib/core.sh")
flush_src=$(sed -n '/^flush_tty_input()/,/^}/p' "$REPO_ROOT/lib/tty.sh")
assert_contains "$flush_src" 'read -r -t' "flush drains leftover Enter"
assert_not_contains "$flush_src" 'stty' "flush does not change stty"
assert_contains "$src" 'EPOCHREALTIME' "read_prompt ignores instant empty (leaked Enter)"
# Behavioral test: piped empty Enter returns immediately without double-prompting
rp_val="unset"
read_prompt "Test: " rp_val </dev/null >/dev/null 2>&1
assert_eq "" "$rp_val" "read_prompt handles EOF cleanly under set -e"
os_fn=$(sed -n '/^configure_opensubtitles()/,/^}/p' "$REPO_ROOT/lib/prompts.sh")
assert_contains "$os_fn" 'ui_is_edit' "edit skips the optional y/N"
assert_contains "$os_fn" '_opensubtitles_ask_and_verify 1' "edit goes straight to username/password"
assert_contains "$os_fn" '_opensubtitles_collect 1' "edit goes straight to username/password"
assert_not_contains "$(cat "$REPO_ROOT/lib/prompts.sh")" 's38zmzVlW7IlYruWi7mHwDYl2SfMQoC1' "no borrowed OpenSubtitles API key"
assert_not_contains "$os_fn" 'Answer n to clear' "edit does not ask n to clear"
edit_os=$(sed -n '/^_config_edit_opensubtitles()/,/^}/p' "$REPO_ROOT/lib/config_edit.sh")
assert_contains "$edit_os" 'Cancelled.' "edit cancel is one line"
@ -183,6 +187,10 @@ mkdir -p "$done/compose"
: >"$done/.assemblrr-config"
: >"$done/cli.sh"
assert_success "config+cli is complete" is_complete_assemblrr_install "$done"
: >"$done/.assemblrr-setup-in-progress"
assert_failure "in-progress marker marks install incomplete" is_complete_assemblrr_install "$done"
rm -f "$done/.assemblrr-setup-in-progress"
assert_success "removing in-progress marker restores completeness" is_complete_assemblrr_install "$done"
empty="$tmp/empty/assemblrr"
mkdir -p "$empty"
assert_failure "empty dir is not complete" is_complete_assemblrr_install "$empty"
@ -195,6 +203,10 @@ assert_failure "cli without runtime config is not complete" is_complete_assemblr
test_suite "setup refuses a complete install"
assert_true "setup calls the gate" "grep -q refuse_setup_if_already_installed \"$REPO_ROOT/bin/setup.sh\""
assert_true "setup offers leftover cleanup" "grep -q offer_leftover_cleanup \"$REPO_ROOT/bin/setup.sh\""
assert_true "setup writes in-progress marker in bootstrap_operator" \
"sed -n '/^bootstrap_operator()/,/^}/p' \"$REPO_ROOT/bin/setup.sh\" | grep -q '\.assemblrr-setup-in-progress'"
assert_true "setup clears in-progress marker in main" \
"sed -n '/^main()/,/^}/p' \"$REPO_ROOT/bin/setup.sh\" | grep -q 'rm -f .*\.assemblrr-setup-in-progress'"
gate=$(sed -n '/^refuse_setup_if_already_installed()/,/^}/p' "$REPO_ROOT/lib/prompts.sh")
assert_contains "$gate" "already installed" "says already installed"
assert_contains "$gate" "uninstall" "points at uninstall"
@ -236,6 +248,30 @@ HOME="$both_home" offer_leftover_cleanup <<< $'y\nn' >/dev/null 2>&1 || true
assert_false "install directory removed on y" "[ -d \"$both_home/assemblrr\" ]"
assert_true "media directory kept on n" "[ -d \"$both_home/assemblrr-media\" ]"
aborted_home="$tmp/aborted-home"
mkdir -p "$aborted_home/assemblrr" "$aborted_home/.local/bin"
cat > "$aborted_home/assemblrr/.assemblrr-config" <<EOF
INSTALL_DIRECTORY="$aborted_home/assemblrr"
MEDIA_DIRECTORY="$aborted_home/assemblrr-media"
VPN_ENABLED="y"
EOF
: > "$aborted_home/assemblrr/cli.sh"
: > "$aborted_home/assemblrr/.assemblrr-setup-in-progress"
cat > "$aborted_home/.assemblrr-config" <<EOF
INSTALL_DIRECTORY="$aborted_home/assemblrr"
MEDIA_DIRECTORY="$aborted_home/assemblrr-media"
KNOWN_INSTALLS="$aborted_home/assemblrr"
EOF
: > "$aborted_home/.local/bin/assemblrr"
aborted_rc=0
(HOME="$aborted_home" refuse_setup_if_already_installed) || aborted_rc=$?
assert_eq "0" "$aborted_rc" "aborted install does not trigger already-installed block"
out_aborted=$(HOME="$aborted_home" offer_leftover_cleanup <<< "y" 2>&1 || true)
assert_contains "$out_aborted" "incomplete" "aborted leftover cleanup labels incomplete setup"
assert_false "aborted install directory removed on y" "[ -d \"$aborted_home/assemblrr\" ]"
assert_false "stale pointer removed after aborted install cleanup" "[ -f \"$aborted_home/.assemblrr-config\" ]"
assert_false "stale CLI wrapper removed after aborted install cleanup" "[ -f \"$aborted_home/.local/bin/assemblrr\" ]"
test_suite "print_detected_locations"
loc=$(INSTALL_DIR=/mnt/e/assemblrr MEDIA_DIRECTORY=/mnt/e/assemblrr-media \
HOME="$ptr_home" print_detected_locations "Detected installation:")
@ -316,4 +352,10 @@ chmod +x "$other/cli.sh"
out=$(HOME="$wrap_home" ASSEMBLRR_DIR="$other" "$wrap_home/.local/bin/assemblrr")
assert_eq "other-cli" "$out" "ASSEMBLRR_DIR wins over pointer"
test_suite "Graceful Ctrl+C interrupt handling & read_masked trap preservation"
setup_src=$(cat "$REPO_ROOT/bin/setup.sh")
assert_contains "$setup_src" "setup_on_interrupt()" "setup defines graceful interrupt handler"
assert_contains "$setup_src" "trap 'setup_on_interrupt' INT TERM" "main installs INT/TERM trap"
assert_contains "$(cat "$REPO_ROOT/lib/tty.sh")" "trap -p INT" "read_masked preserves outer INT trap"
test_summary

View file

@ -84,6 +84,8 @@ export PUID=1000 PGID=1000 \
VPN_ENABLED=n VPN_SERVICE= VPN_TYPE=openvpn \
WIREGUARD_ADDRESSES= \
PORT_FORWARD_ONLY=off VPN_PORT_FORWARDING=off \
VUETORRENT_ENABLED=n GPU_TRANSCODING=none \
BYPARR_ENABLED=n USENET_ENABLED=n \
API_HOST=127.0.0.1
envsubst "$envsubst_arg" < "$example" > "$tmp"

0
tests/unit/test_fzf_tui.sh Normal file → Executable file
View file

105
tests/unit/test_jellyfin12.sh Executable file
View file

@ -0,0 +1,105 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Unit tests for Jellyfin 12.4 Authorization: MediaBrowser migration
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/../helpers.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/core.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/api.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/jellyfin.sh"
test_suite "Jellyfin 12.4 auth headers across all scripts"
for f in lib/jellyfin.sh lib/bazarr.sh scripts/jellyfin-refresh.sh scripts/media-purge.sh; do
content=$(cat "$REPO_ROOT/$f")
assert_contains "$content" 'Authorization: MediaBrowser' "$f uses MediaBrowser header"
assert_not_contains "$content" 'X-Emby-Token' "$f has no X-Emby-Token"
assert_not_contains "$content" 'X-Emby-Authorization' "$f has no X-Emby-Authorization"
done
test_suite "_jf_auth_header formatting"
hdr_tok=$(_jf_auth_header "tok-abc")
assert_contains "$hdr_tok" 'Client="assemblrr"' "includes Client"
assert_contains "$hdr_tok" 'DeviceId="assemblrr-cli"' "includes DeviceId"
assert_contains "$hdr_tok" 'Token="tok-abc"' "includes Token when provided"
hdr_notok=$(_jf_auth_header "")
assert_not_contains "$hdr_notok" 'Token=""' "omits empty Token cleanly"
test_suite "configure_jellyfin_libraries reuses existing assemblrr API key"
libs_fn=$(sed -n '/^configure_jellyfin_libraries()/,/^}/p' "$REPO_ROOT/lib/jellyfin.sh")
assert_contains "$libs_fn" 'select(.AppName == "assemblrr")' "queries /Auth/Keys for existing assemblrr key"
assert_contains "$libs_fn" '_jf_auth_header' "uses _jf_auth_header helper for MediaBrowser auth"
test_suite "Jellyfin pinned to 12.4 in compose/base.yaml"
assert_contains "$(cat "$REPO_ROOT/compose/base.yaml")" 'lscr.io/linuxserver/jellyfin:12.4ubu2604-ls60' "base.yaml pins Jellyfin 12.4"
test_suite "jellyfin_parse_vainfo_caps"
rdna4_vainfo=$(cat <<'EOF'
Trying display: drm
vainfo: Driver version: Mesa Gallium driver 26.0.8 for AMD Radeon RX 9060 XT
vainfo: Supported profile and entrypoints
VAProfileH264ConstrainedBaseline: VAEntrypointVLD
VAProfileH264Main : VAEntrypointVLD
VAProfileH264High : VAEntrypointVLD
VAProfileH264High : VAEntrypointEncSlice
VAProfileHEVCMain : VAEntrypointVLD
VAProfileHEVCMain : VAEntrypointEncSlice
VAProfileHEVCMain10 : VAEntrypointVLD
VAProfileVP9Profile0 : VAEntrypointVLD
VAProfileVP9Profile2 : VAEntrypointVLD
VAProfileAV1Profile0 : VAEntrypointVLD
VAProfileAV1Profile0 : VAEntrypointEncSlice
EOF
)
rdna4_caps=$(jellyfin_parse_vainfo_caps "$rdna4_vainfo")
assert_eq "h264,hevc,vp9,av1" "$(printf '%s' "$rdna4_caps" | jq -r '.decode | join(",")')" "RDNA4 decode excludes MPEG2/VC1"
assert_eq "true" "$(printf '%s' "$rdna4_caps" | jq -r '.av1_enc')" "RDNA4 enables AV1 encode"
assert_eq "true" "$(printf '%s' "$rdna4_caps" | jq -r '.hevc_enc')" "RDNA4 enables HEVC encode"
assert_eq "true" "$(printf '%s' "$rdna4_caps" | jq -r '.hevc10 and .vp9_10')" "RDNA4 enables 10-bit HEVC & VP9"
legacy_vainfo=$(cat <<'EOF'
VAProfileMPEG2Simple : VAEntrypointVLD
VAProfileVC1Main : VAEntrypointVLD
VAProfileH264High : VAEntrypointVLD
VAProfileHEVCMain : VAEntrypointVLD
VAProfileHEVCMain : VAEntrypointEncSliceLP
EOF
)
legacy_caps=$(jellyfin_parse_vainfo_caps "$legacy_vainfo")
assert_eq "h264,hevc,mpeg2video,vc1" "$(printf '%s' "$legacy_caps" | jq -r '.decode | join(",")')" "legacy GPU includes MPEG2/VC1 when reported"
assert_eq "false" "$(printf '%s' "$legacy_caps" | jq -r '.av1_enc')" "legacy GPU omits AV1 encode"
assert_eq "true" "$(printf '%s' "$legacy_caps" | jq -r '.hevc_enc')" "legacy LP slice enables HEVC encode"
assert_failure "empty vainfo fails gracefully" jellyfin_parse_vainfo_caps "no profiles"
test_suite "jellyfin_build_encoding_patch_json"
base_enc='{"EncodingThreadCount":-1,"HardwareAccelerationType":"none","EnableHardwareEncoding":false,"VaapiDevice":"/dev/dri/renderD129"}'
amd_probed=$(jellyfin_build_encoding_patch_json "$base_enc" "amd" "/dev/dri/renderD128" "$rdna4_caps")
assert_eq "vaapi" "$(printf '%s' "$amd_probed" | jq -r '.HardwareAccelerationType')" "amd -> vaapi"
assert_eq "/dev/dri/renderD128" "$(printf '%s' "$amd_probed" | jq -r '.VaapiDevice')" "sets VaapiDevice"
assert_eq "h264,hevc,vp9,av1" "$(printf '%s' "$amd_probed" | jq -r '.HardwareDecodingCodecs | join(",")')" "probed AMD omits MPEG2/VC1"
assert_eq "true" "$(printf '%s' "$amd_probed" | jq -r '.AllowAv1Encoding')" "probed RDNA4 enables AV1 encode"
assert_eq "-1" "$(printf '%s' "$amd_probed" | jq -r '.EncodingThreadCount')" "preserves unrelated fields"
amd_enc=$(jellyfin_build_encoding_patch_json "$base_enc" "amd" "/dev/dri/renderD128")
assert_eq "h264,hevc,vp9,av1" "$(printf '%s' "$amd_enc" | jq -r '.HardwareDecodingCodecs | join(",")')" "offline fallback defaults exclude MPEG2/VC1"
assert_eq "true" "$(printf '%s' "$amd_enc" | jq -r '.EnableHardwareEncoding')" "enables HW encoding"
intel_enc=$(jellyfin_build_encoding_patch_json "$base_enc" "intel" "/dev/dri/renderD128")
assert_eq "qsv" "$(printf '%s' "$intel_enc" | jq -r '.HardwareAccelerationType')" "intel -> qsv"
assert_eq "/dev/dri/renderD128" "$(printf '%s' "$intel_enc" | jq -r '.QsvDevice')" "sets QsvDevice"
nv_enc=$(jellyfin_build_encoding_patch_json "$base_enc" "nvidia" "/dev/dri/renderD128")
assert_eq "nvenc" "$(printf '%s' "$nv_enc" | jq -r '.HardwareAccelerationType')" "nvidia -> nvenc"
assert_eq "true" "$(printf '%s' "$nv_enc" | jq -r '.EnableHardwareEncoding')" "nvidia enables HW encoding"
none_enc=$(jellyfin_build_encoding_patch_json "$amd_enc" "none" "/dev/dri/renderD128")
assert_eq "none" "$(printf '%s' "$none_enc" | jq -r '.HardwareAccelerationType')" "none resets acceleration"
assert_eq "false" "$(printf '%s' "$none_enc" | jq -r '.EnableHardwareEncoding')" "none disables HW encoding"
test_summary

View file

@ -48,20 +48,29 @@ sonarr_eventtype=""
test_suite "jf_refresh_dir_has_video"
_jf_tmp=$(mktemp -d)
assert_false "missing dir" "jf_refresh_dir_has_video /no/such/loki"
assert_false "missing dir" "jf_refresh_dir_has_video /no/such/sample-show"
assert_false "empty dir" "jf_refresh_dir_has_video $_jf_tmp"
mkdir -p "$_jf_tmp/Season 1"
: >"$_jf_tmp/Season 1/notes.txt"
assert_false "only txt" "jf_refresh_dir_has_video $_jf_tmp"
: >"$_jf_tmp/Season 1/Show - S01E01.mkv"
: >"$_jf_tmp/Season 1/Sample Show - S01E01.mkv"
assert_true "has mkv" "jf_refresh_dir_has_video $_jf_tmp"
rm -rf "$_jf_tmp"
test_suite "jf_refresh_empty_series_ids"
assert_eq "aa11" \
"$(jf_refresh_empty_series_ids '{"Items":[{"Id":"aa11","Path":"/data/media/tv/Loki"}]}')" \
"$(jf_refresh_empty_series_ids '{"Items":[{"Id":"aa11","Path":"/data/media/tv/Sample Show"}]}')" \
"extracts series id"
test_suite "jf_refresh uses bash, MediaBrowser header, and avoids env key leak"
_jf_script=$(cat "$REPO_ROOT/scripts/jellyfin-refresh.sh")
assert_contains "$_jf_script" '#!/usr/bin/env bash' "shebang uses bash"
assert_contains "$_jf_script" 'Authorization: MediaBrowser' "uses MediaBrowser auth header"
assert_not_contains "$_jf_script" 'X-Emby-Token' "no legacy X-Emby-Token header"
assert_contains "$_jf_script" '_JF_KEY_FROM_SECRET' "avoids passing secret-file key through nohup env"
JF_API_KEY="tok-123"
assert_contains "$(jf_refresh_auth_header)" 'Token="tok-123"' "auth header formats Token"
test_suite "jellyfin refresh notif payload"
_sonarr_schema='[{"implementation":"CustomScript","fields":[{"name":"path","value":""}],"onDownload":false,"onUpgrade":false,"onImportComplete":false}]'
_radarr_schema='[{"implementation":"CustomScript","fields":[{"name":"path","value":""}],"onDownload":false,"onUpgrade":false}]'

View file

@ -1,22 +1,174 @@
#!/bin/bash
# Unit tests for media-purge qB folder-key matching (synthetic titles only).
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Unit tests for media-purge matcher, season scoping, and download dir cleanup (synthetic titles only).
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/../helpers.sh"
test_suite "media-purge qB token match"
MEDIA_PURGE_SOURCE_ONLY=1
# shellcheck disable=SC1091
source "$REPO_ROOT/scripts/media-purge.sh"
purge="$REPO_ROOT/scripts/media-purge.sh"
assert_true "media-purge.sh exists" "[ -f \"$purge\" ]"
check_match() {
local want="$1" name="$2" tokens="$3" torrents="$4"
local got
got=$(echo "$torrents" | qb_match_jq "$tokens" | tr '\n' ' ' | sed 's/[[:space:]]*$//')
assert_eq "$want" "$got" "$name"
}
if bash "$purge" --match-self-test; then
_TEST_PASSES=$((_TEST_PASSES + 1))
echo " PASS: media-purge --match-self-test"
else
_TEST_FAILURES=$((_TEST_FAILURES + 1))
echo " FAIL: media-purge --match-self-test"
fi
check_filter() {
local want="$1" name="$2" torrents="$3"
shift 3
local got
got=$(echo "$torrents" | qbit_filter_hashes_jq "$@" | tr '\n' ' ' | sed 's/[[:space:]]*$//')
assert_eq "$want" "$got" "$name"
}
check_season() {
local want="$1" name="$2" folder="$3" seasons="$4" torrents="$5"
local got
got=$(echo "$torrents" | qb_match_season_jq "$folder" "$seasons" | tr '\n' ' ' | sed 's/[[:space:]]*$//')
assert_eq "$want" "$got" "$name"
}
check_cover() {
local want="$1" name="$2" seasons="$3" series="$4" files="$5"
local remain got
remain=$(seasons_remaining_json "$series" "$files")
if seasons_list_covers_remaining "$seasons" "$remain"; then
got="cover"
else
got="partial"
fi
assert_eq "$want" "$got" "$name"
}
test_suite "media-purge qB title+year match (synthetic titles)"
check_match "hash_a" "year folder hits only first film" \
'["Alpha Film (2016)"]' \
'[{"hash":"hash_a","name":"Alpha Film (2016) [GRP]","content_path":"/data/torrents/movies/Alpha Film (2016)"},{"hash":"hash_b","name":"Alpha Film Sequel Extended (2022)","content_path":"/data/torrents/movies/Alpha Film Sequel Extended (2022)"}]'
check_match "" "bare short title does not hit longer sequel name" \
'["Alpha Film"]' \
'[{"hash":"hash_b","name":"Alpha Film Sequel Extended (2022)","content_path":"/data/torrents/movies/Alpha Film Sequel Extended (2022)"}]'
check_match "hash_a" "bare short title hits exact name only" \
'["Alpha Film"]' \
'[{"hash":"hash_a","name":"Alpha Film","content_path":"/data/torrents/movies/Alpha Film"},{"hash":"hash_b","name":"Alpha Film Sequel Extended","content_path":"/data/torrents/movies/Alpha Film Sequel Extended"}]'
check_match "hash_y" "year preferred when bare+year present" \
'["Sample Title","Sample Title (2008)"]' \
'[{"hash":"hash_y","name":"Sample Title (2008) [e2e]","content_path":"/data/torrents/movies/Sample Title (2008) [e2e]"},{"hash":"hash_z","name":"Sample Title Adventures","content_path":"/data/torrents/movies/Sample Title Adventures"}]'
check_match "hash_m1" "bare title does not hit same-prefix sequel" \
'["Beta Movie"]' \
'[{"hash":"hash_m1","name":"Beta Movie","content_path":"/data/torrents/movies/Beta Movie"},{"hash":"hash_m2","name":"Beta Movie Reloaded","content_path":"/data/torrents/movies/Beta Movie Reloaded"}]'
check_match "hash_p1" "title+year hits release name with indexer prefix" \
'["The Horizon (2012)"]' \
'[{"hash":"hash_p1","name":"The Horizon 2012 REPACK 1080p DDP 5 1 x264-grp","content_path":"/data/torrents/incomplete/movies/indexer.example - The Horizon 2012 REPACK 1080p DDP 5 1 x264-grp"}]'
check_match "hash_p2" "title+year hits indexer-prefixed incomplete path" \
'["The Horizon (2012)"]' \
'[{"hash":"hash_p2","name":"indexer.example - The Horizon 2012 REPACK","content_path":"/data/torrents/incomplete/movies/indexer.example - The Horizon 2012 REPACK"}]'
check_match "" "title+year does not hit sequel with different year" \
'["The Horizon (2012)"]' \
'[{"hash":"hash_u","name":"Horizon Chapter Two 2015 1080p","content_path":"/data/torrents/movies/Horizon Chapter Two 2015 1080p"}]'
check_match "" "short title+year does not hit longer title sharing first word" \
'["Nova (2017)"]' \
'[{"hash":"hash_n","name":"Nova Comes at Night 2017 1080p","content_path":"/data/torrents/movies/Nova Comes at Night 2017"}]'
check_match "hash_it" "short title+year hits exact short title release" \
'["Nova (2017)"]' \
'[{"hash":"hash_it","name":"Nova 2017 1080p REMUX","content_path":"/data/torrents/movies/Nova 2017 1080p REMUX"}]'
check_match "hash_bb" "article-stripped title still needs the year next" \
'["The Horizon (2012)"]' \
'[{"hash":"hash_bb","name":"Horizon 2012 1080p","content_path":"/data/torrents/movies/Horizon 2012 1080p"}]'
test_suite "media-purge qbit_filter_hashes_jq"
check_filter "hash_a" "history filter keeps live hash even when name is a release" \
'[{"hash":"hash_a","name":"The Horizon 2012 REPACK","content_path":"/data/torrents/incomplete/movies/The Horizon 2012 REPACK"},{"hash":"hash_b","name":"Other Title","content_path":"/data/torrents/movies/Other"}]' \
hash_a
check_filter "hash_a" "history filter keeps every live candidate hash" \
'[{"hash":"hash_a","name":"Alpha Film Sequel Extended (2022)","content_path":"/data/torrents/movies/Alpha Film Sequel Extended (2022)"}]' \
hash_a hash_b
check_filter "" "history filter drops hashes not in qB" \
'[{"hash":"hash_b","name":"Other","content_path":"/x"}]' \
hash_a
test_suite "media-purge season-scoped matcher + boundary safety"
check_season "hash_s1" "S01 pack matches season 1 only" \
"Sample Show" '[1]' \
'[{"hash":"hash_s1","name":"Sample.Show.S01.COMPLETE.1080p","content_path":"/data/torrents/tv/Sample.Show.S01.COMPLETE.1080p"},{"hash":"hash_s2","name":"Sample.Show.S02.COMPLETE.1080p","content_path":"/data/torrents/tv/Sample.Show.S02.COMPLETE.1080p"}]'
check_season "" "S02 pack is not deleted with season 1" \
"Sample Show" '[1]' \
'[{"hash":"hash_s2","name":"Sample.Show.S02.COMPLETE.1080p.WEB-DL","content_path":"/data/torrents/tv/Sample.Show.S02.COMPLETE.1080p.WEB-DL"}]'
check_season "" "multi-season pack refused when deleting S01 only" \
"Sample Show" '[1]' \
'[{"hash":"hash_both","name":"Sample.Show.S01.S02.COMPLETE","content_path":"/data/torrents/tv/Sample.Show.S01.S02.COMPLETE"}]'
check_season "" "no season token is skipped (under-delete)" \
"Sample Show" '[1]' \
'[{"hash":"hash_bare","name":"Sample Show","content_path":"/data/torrents/tv/Sample Show"}]'
check_season "" "other show S01 is not matched" \
"Sample Show" '[1]' \
'[{"hash":"hash_x","name":"Other Show.S01.COMPLETE","content_path":"/data/torrents/tv/Other Show.S01.COMPLETE"}]'
check_season "" "S01-03 range pack refused when deleting S01 only" \
"Sample Show" '[1]' \
'[{"hash":"hash_r","name":"Sample.Show.S01-03.COMPLETE","content_path":"/data/torrents/tv/Sample.Show.S01-03.COMPLETE"}]'
check_season "" "Season 1-3 range pack refused when deleting S01 only" \
"Sample Show" '[1]' \
'[{"hash":"hash_r2","name":"Sample Show Season 1-3","content_path":"/data/torrents/tv/Sample Show Season 1-3"}]'
check_season "" "short folder key does not match unrelated S01 torrent" \
"Oz" '[1]' \
'[{"hash":"hash_oz","name":"Other.S01.COMPLETE","content_path":"/data/torrents/tv/Other.S01.COMPLETE"}]'
check_season "" "Echo does not match Echo in Space S01" \
"Echo" '[1]' \
'[{"hash":"hash_lis","name":"Echo in Space.S01.COMPLETE","content_path":"/data/torrents/tv/Echo in Space.S01.COMPLETE"}]'
check_season "hash_e1 hash_e2" "multiple S01E0x torrents all match" \
"Sample Show" '[1]' \
'[{"hash":"hash_e1","name":"Sample.Show.S01E01","content_path":"/data/torrents/tv/Sample.Show.S01E01"},{"hash":"hash_e2","name":"Sample.Show.S01E02","content_path":"/data/torrents/tv/Sample.Show.S01E02"}]'
check_match "hash_s2" "title-level Sample Show matches S02 complete pack" \
'["Sample Show"]' \
'[{"hash":"hash_s2","name":"Sample.Show.S02.COMPLETE.1080p.WEB-DL","content_path":"/data/torrents/tv/Sample.Show.S02.COMPLETE.1080p.WEB-DL"}]'
check_match "" "title-level Echo does not match Echo in Space pack" \
'["Echo"]' \
'[{"hash":"hash_lis","name":"Echo in Space.S01.COMPLETE","content_path":"/data/torrents/tv/Echo in Space.S01.COMPLETE"}]'
check_season "hash_dts" "dts5 / ps4 / x265 do not invent bogus seasons 5/4/26" \
"Sample Show" '[1]' \
'[{"hash":"hash_dts","name":"Sample.Show.S01.1080p.DTS5.1.x265-GRP","content_path":"/data/torrents/tv/Sample.Show.S01.1080p.DTS5.1.x265-GRP"}]'
check_season "hash_sp" "Specials pack matches season 0" \
"Sample Show" '[0]' \
'[{"hash":"hash_sp","name":"Sample.Show.Specials.1080p","content_path":"/data/torrents/tv/Sample.Show.Specials.1080p"}]'
test_suite "media-purge remaining-season cover"
_series_s01s02='{"seasons":[{"seasonNumber":1,"monitored":true},{"seasonNumber":2,"monitored":true}]}'
_files_s01s02='[{"seasonNumber":1},{"seasonNumber":2}]'
_series_s01_spec='{"seasons":[{"seasonNumber":0,"monitored":true},{"seasonNumber":1,"monitored":true}]}'
_files_s01_spec='[{"seasonNumber":0},{"seasonNumber":1}]'
_series_spec_only='{"seasons":[{"seasonNumber":0,"monitored":true}]}'
_files_spec_only='[{"seasonNumber":0}]'
check_cover "partial" "S01 request does not cover S01+S02" '[1]' "$_series_s01s02" "$_files_s01s02"
check_cover "cover" "S01+S02 request covers S01+S02" '[1,2]' "$_series_s01s02" "$_files_s01s02"
check_cover "partial" "S01 request does not cover S01+specials" '[1]' "$_series_s01_spec" "$_files_s01_spec"
check_cover "cover" "S01+specials request covers both" '[0,1]' "$_series_s01_spec" "$_files_s01_spec"
check_cover "partial" "S01 request does not cover specials-only leftover" '[1]' "$_series_spec_only" "$_files_spec_only"
check_cover "cover" "specials request covers specials-only leftover" '[0]' "$_series_spec_only" "$_files_spec_only"
test_suite "media-purge leftover torrent & usenet dirs + script hygiene"
MEDIA_ROOT=$(mktemp -d)
trap 'rm -rf "$MEDIA_ROOT"' EXIT
mkdir -p "$MEDIA_ROOT/torrents/tv/Sample.Show.S02.COMPLETE.1080p.WEB-DL" \
"$MEDIA_ROOT/torrents/tv/Echo in Space.S01.COMPLETE" \
"$MEDIA_ROOT/torrents/incomplete/movies/indexer.example - The Horizon 2012 REPACK" \
"$MEDIA_ROOT/torrents/movies/Horizon Chapter Two 2015 1080p" \
"$MEDIA_ROOT/usenet/complete/movies/The.Horizon.2012.1080p.WEB"
DRY_RUN=0
remove_orphan_torrent_dirs "Sample Show"
assert_false "Sample Show leftover pack dir removed" "[ -d '$MEDIA_ROOT/torrents/tv/Sample.Show.S02.COMPLETE.1080p.WEB-DL' ]"
assert_true "Echo in Space leftover left alone" "[ -d '$MEDIA_ROOT/torrents/tv/Echo in Space.S01.COMPLETE' ]"
remove_orphan_torrent_dirs "The Horizon (2012)"
assert_false "The Horizon incomplete torrent dir removed" "[ -d '$MEDIA_ROOT/torrents/incomplete/movies/indexer.example - The Horizon 2012 REPACK' ]"
assert_false "The Horizon usenet complete dir removed" "[ -d '$MEDIA_ROOT/usenet/complete/movies/The.Horizon.2012.1080p.WEB' ]"
assert_true "Horizon Chapter Two leftover left alone" "[ -d '$MEDIA_ROOT/torrents/movies/Horizon Chapter Two 2015 1080p' ]"
_mp_src=$(cat "$REPO_ROOT/scripts/media-purge.sh")
assert_not_contains "$_mp_src" 'exec "$0"' "--tmdb / --tvdb do not re-exec and drop --dry-run"
assert_contains "$_mp_src" 'Authorization: MediaBrowser' "notify_jellyfin uses MediaBrowser header"
assert_not_contains "$_mp_src" 'X-Emby-Token' "notify_jellyfin does not use legacy X-Emby-Token"
test_summary

54
tests/unit/test_media_purge_watch.sh Normal file → Executable file
View file

@ -1,5 +1,6 @@
#!/bin/bash
# media-purge-watch ignore / video / folder-key helpers
# SPDX-License-Identifier: GPL-3.0-or-later
# media-purge-watch ignore / video / folder-key / hold helpers (synthetic titles only)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@ -16,24 +17,36 @@ trap 'rm -rf "$tmp"' EXIT
test_suite "purge_watch_is_ignored"
assert_true "write test" "purge_watch_is_ignored /data/media/movies/radarr_write_test.txt"
assert_true "sonarr write test" "purge_watch_is_ignored /data/media/tv/sonarr_write_test.txt"
assert_true "partial" "purge_watch_is_ignored /data/media/movies/Title/file.mkv.part"
assert_true "partial" "purge_watch_is_ignored /data/media/movies/SampleTitle/file.mkv.part"
assert_true "nfs" "purge_watch_is_ignored /data/media/movies/.nfs123"
assert_false "real mkv" "purge_watch_is_ignored '/data/media/movies/The Hobbit (2012)/movie.mkv'"
assert_false "real mkv" "purge_watch_is_ignored '/data/media/movies/Sample Movie (2012)/movie.mkv'"
test_suite "purge_watch_is_video"
test_suite "purge_watch_is_video & folder_has_video parity"
assert_true "mkv" "purge_watch_is_video /data/media/movies/x/a.mkv"
assert_true "MP4 case" "purge_watch_is_video /data/media/movies/x/A.MP4"
assert_true "wmv video" "purge_watch_is_video /data/media/movies/x/a.wmv"
assert_true "mpg video" "purge_watch_is_video /data/media/movies/x/a.mpg"
assert_false "txt" "purge_watch_is_video /data/media/movies/x/note.txt"
assert_false "nfo" "purge_watch_is_video /data/media/movies/x/movie.nfo"
assert_false "srt" "purge_watch_is_video /data/media/movies/x/movie.en.srt"
_vdir="$tmp/wmv-check"
mkdir -p "$_vdir"
: > "$_vdir/sample.wmv"
assert_true "folder_has_video detects wmv too" "purge_watch_folder_has_video '$_vdir'"
test_suite "purge_watch_library_folder"
assert_eq "/data/media/movies/The Hobbit (2012)" \
"$(purge_watch_library_folder '/data/media/movies/The Hobbit (2012)/file.mkv')" \
test_suite "purge_watch_library_folder & kind"
assert_eq "/data/media/movies/Sample Movie (2012)" \
"$(purge_watch_library_folder '/data/media/movies/Sample Movie (2012)/file.mkv')" \
"movie title dir"
assert_eq "movie" \
"$(purge_watch_library_kind '/data/media/movies/Sample Movie (2012)/file.mkv')" \
"movie kind"
assert_eq "/data/media/tv/Show Name" \
"$(purge_watch_library_folder '/data/media/tv/Show Name/Season 01/ep.mkv')" \
"series title dir"
assert_eq "tv" \
"$(purge_watch_library_kind '/data/media/tv/Show Name')" \
"tv kind at title folder root"
assert_eq "" "$(purge_watch_library_folder /data/torrents/movies/x.mkv)" "torrents path ignored"
test_suite "purge_watch_folder_busy"
@ -47,10 +60,17 @@ rm -f "$busy/copying.mkv.part"
assert_true "video is busy" "purge_watch_folder_busy '$busy'"
test_suite "purge_watch_json_has_upgrade_delete"
upg='{"records":[{"eventType":"movieFileDeleted","data":{"reason":"Upgrade"}}]}'
_now=1760000600
_recent_iso=$(date -u -d "@$((_now - 60))" '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || python3 -c "import datetime; print(datetime.datetime.fromtimestamp($_now - 60, datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'))")
_old_iso=$(date -u -d "@$((_now - 3600))" '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || python3 -c "import datetime; print(datetime.datetime.fromtimestamp($_now - 3600, datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'))")
upg_nodate='{"records":[{"eventType":"movieFileDeleted","data":{"reason":"Upgrade"}}]}'
upg_recent="{\"records\":[{\"date\":\"${_recent_iso}\",\"eventType\":\"movieFileDeleted\",\"data\":{\"reason\":\"Upgrade\"}}]}"
upg_stale="{\"records\":[{\"date\":\"${_old_iso}\",\"eventType\":\"movieFileDeleted\",\"data\":{\"reason\":\"Upgrade\"}}]}"
manual='{"records":[{"eventType":"movieFileDeleted","data":{"reason":"Manual"}}]}'
assert_success "upgrade delete is a hold" purge_watch_json_has_upgrade_delete "$upg"
assert_failure "manual delete is not a hold" purge_watch_json_has_upgrade_delete "$manual"
assert_success "upgrade delete without date is a hold" purge_watch_json_has_upgrade_delete "$upg_nodate" "$_now" 600
assert_success "recent upgrade delete is a hold" purge_watch_json_has_upgrade_delete "$upg_recent" "$_now" 600
assert_failure "stale upgrade delete (1h ago) does not hold forever" purge_watch_json_has_upgrade_delete "$upg_stale" "$_now" 600
assert_failure "manual delete is not a hold" purge_watch_json_has_upgrade_delete "$manual" "$_now" 600
test_suite "purge_watch_queue_mentions_id"
q='{"records":[{"movieId":12},{"movieId":99}]}'
@ -66,14 +86,20 @@ assert_eq "" "$(purge_watch_season_number '/data/media/movies/Title (2012)/movie
test_suite "purge_watch recycle and title-folder events"
assert_true "recycle path ignored" \
"purge_watch_is_ignored '/data/media/.recycle/Loki'"
"purge_watch_is_ignored '/data/media/.recycle/Sample Show'"
assert_true "recycle file ignored" \
"purge_watch_is_ignored '/data/media/.recycle/Loki/Season 2/ep.mkv'"
"purge_watch_is_ignored '/data/media/.recycle/Sample Show/Season 2/ep.mkv'"
assert_true "tv title folder" \
"purge_watch_is_title_folder '/data/media/tv/Loki'"
"purge_watch_is_title_folder '/data/media/tv/Sample Show'"
assert_true "movie title folder" \
"purge_watch_is_title_folder '/data/media/movies/Title (2012)'"
assert_false "episode path is not the title folder" \
"purge_watch_is_title_folder '/data/media/tv/Loki/Season 2/ep.mkv'"
"purge_watch_is_title_folder '/data/media/tv/Sample Show/Season 2/ep.mkv'"
test_suite "purge_watch whole-TV-show hold uses Sonarr, not Radarr"
assert_contains "$(sed -n '/^purge_watch_arr_hold()/,/^}/p' "$REPO_ROOT/scripts/media-purge-watch.sh")" \
'purge_watch_library_kind' "hold infers TV vs movie from library path when season is empty"
assert_not_contains "$(cat "$REPO_ROOT/scripts/media-purge-watch.sh")" \
'chmod +x' "no chmod +x on read-only script mount"
test_summary

67
tests/unit/test_overlays.sh Executable file
View file

@ -0,0 +1,67 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Unit tests for feature overlays & conditional service catalog (VueTorrent, GPU, Byparr, Usenet)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/../helpers.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/core.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/compose.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/services.sh"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
mkdir -p "$tmp/compose"
touch "$tmp/compose/base.yaml" "$tmp/compose/vpn.yaml" "$tmp/compose/direct-access.yaml" \
"$tmp/compose/vuetorrent.yaml" "$tmp/compose/gpu-intel.yaml" "$tmp/compose/gpu-nvidia.yaml" \
"$tmp/compose/byparr.yaml" "$tmp/compose/usenet.yaml"
test_suite "Conditional service catalog reflects feature overlays"
VPN_ENABLED=n USENET_ENABLED=n BYPARR_ENABLED=n
cat_off=$(list_service_catalog)
assert_contains "$cat_off" "jellyfin|Jellyfin|8096" "has jellyfin"
assert_not_contains "$cat_off" "sabnzbd|" "omits sabnzbd when USENET_ENABLED=n"
assert_not_contains "$cat_off" "byparr|" "omits byparr when BYPARR_ENABLED=n"
assert_not_contains "$cat_off" "gluetun|" "omits gluetun when VPN_ENABLED=n"
VPN_ENABLED=y USENET_ENABLED=y BYPARR_ENABLED=y
cat_on=$(list_service_catalog)
assert_contains "$cat_on" "sabnzbd|SABnzbd|8085|/|ui" "lists sabnzbd UI when USENET_ENABLED=y"
assert_contains "$cat_on" "byparr|Byparr (solver)|||internal" "lists byparr when BYPARR_ENABLED=y"
assert_contains "$cat_on" "gluetun|Gluetun (VPN)|||internal" "lists gluetun when VPN_ENABLED=y"
test_suite "service_ui_url honors API_HOST"
assert_eq "http://localhost:8085/" "$(service_ui_url 8085 / 127.0.0.1)" "127.0.0.1 -> localhost"
assert_eq "http://192.168.1.50:8085/" "$(service_ui_url 8085 / 192.168.1.50)" "preserves LAN IP host"
test_suite "GPU overlays exclude mutually exclusive configs cleanly"
VUETORRENT_ENABLED=n GPU_TRANSCODING=intel BYPARR_ENABLED=n USENET_ENABLED=n
build_compose_args "$tmp" "n"
assert_contains "${COMPOSE_ARGS[*]}" "gpu-intel.yaml" "intel overlay included"
assert_not_contains "${COMPOSE_ARGS[*]}" "gpu-nvidia.yaml" "nvidia overlay excluded"
GPU_TRANSCODING=amd
build_compose_args "$tmp" "n"
assert_contains "${COMPOSE_ARGS[*]}" "gpu-intel.yaml" "amd selects /dev/dri overlay"
assert_not_contains "${COMPOSE_ARGS[*]}" "gpu-nvidia.yaml" "amd excludes nvidia overlay"
GPU_TRANSCODING=vaapi
build_compose_args "$tmp" "n"
assert_contains "${COMPOSE_ARGS[*]}" "gpu-intel.yaml" "vaapi selects /dev/dri overlay"
GPU_TRANSCODING=nvidia
build_compose_args "$tmp" "n"
assert_contains "${COMPOSE_ARGS[*]}" "gpu-nvidia.yaml" "nvidia overlay included"
assert_not_contains "${COMPOSE_ARGS[*]}" "gpu-intel.yaml" "intel overlay excluded"
test_suite "Express VueTorrent default is y"
# shellcheck source=/dev/null
source "$REPO_ROOT/lib/prompts.sh"
SETUP_MODE=express configure_vuetorrent
assert_eq "y" "${vuetorrent_enabled:-}" "express mode enables VueTorrent by default"
test_summary

View file

@ -47,4 +47,22 @@ test_suite "mkdir under config after prepare"
assert_success "can create sibling of gluetun" mkdir -p "$tmp/config/__test_sibling"
assert_true "sibling exists" "[ -d \"$tmp/config/__test_sibling\" ]"
test_suite "ensure_owned prefers Docker chown before sudo"
mkdir -p "$tmp/root_owned_sim"
(
chown() { return 1; }
run_docker() {
printf '%s\n' "$*" > "$tmp/docker_called"
return 0
}
sudo() {
: > "$tmp/sudo_called"
return 0
}
ensure_owned "$tmp/root_owned_sim" 9999 9999
)
assert_true "Docker chown fallback ran" "[ -f \"$tmp/docker_called\" ]"
assert_contains "$(cat "$tmp/docker_called")" "chown -R 9999:9999 /target" "Docker runs chown -R on /target"
assert_false "sudo was not invoked when Docker chown succeeded" "[ -f \"$tmp/sudo_called\" ]"
test_summary

4
tests/unit/test_qbit_prefs.sh Normal file → Executable file
View file

@ -35,11 +35,11 @@ assert_contains "$json" '"web_ui_username":"x"' "username field set"
assert_contains "$json" '"web_ui_password":"p&q\"r"' "password JSON-escaped"
test_suite "qbit login form encodes reserved characters"
src=$(sed -n '/^qbit_login_form()/,/^}/p' "$REPO_ROOT/lib/arr.sh")
src=$(sed -n '/^qbit_login_form()/,/^}/p' "$REPO_ROOT/lib/qbit.sh")
assert_contains "$src" "--data-urlencode" "qbit_login_form url-encodes fields"
assert_not_contains "$src" '-d "username=' "qbit_login_form does not raw-concat form body"
src=$(sed -n '/^qbit_apply_prefs()/,/^}/p' "$REPO_ROOT/lib/arr.sh")
src=$(sed -n '/^qbit_apply_prefs()/,/^}/p' "$REPO_ROOT/lib/qbit.sh")
assert_contains "$src" "--data-urlencode" "setPreferences url-encodes json="
assert_contains "$src" "qbit_core_prefs_json" "prefs built via jq helper"

6
tests/unit/test_quality.sh Normal file → Executable file
View file

@ -129,15 +129,15 @@ assert_contains "$hd_web" "assemblrr 1080p WEB" "1080p WEB pack scores itself"
assert_contains "$uhd_web" "assemblrr 4K WEB" "4K WEB pack scores itself"
test_suite "configure_recyclarr syncs every movie pack"
recyc=$(sed -n '/^configure_recyclarr()/,/^}/p' "$REPO_ROOT/lib/seerr.sh")
recyc=$(sed -n '/^configure_recyclarr()/,/^}/p' "$REPO_ROOT/lib/recyclarr.sh")
assert_not_contains "$recyc" "grep -vE" "does not drop HD or WEB movie packs"
assert_contains "$(cat "$REPO_ROOT/templates/recyclarr/recyclarr.yml")" "radarr-1080p-bluray.yml" "root still includes 1080p Bluray + WEB"
assert_contains "$(cat "$REPO_ROOT/templates/recyclarr/recyclarr.yml")" "radarr-1080p-web.yml" "root still includes 1080p WEB"
test_suite "sonarr and seerr follow the same flag"
assert_contains "$(sed -n '/^lookup_sonarr_profile()/,/^}/p' "$REPO_ROOT/lib/arr.sh")" \
assert_contains "$(sed -n '/^lookup_sonarr_profile()/,/^}/p' "$REPO_ROOT/lib/arr_quality.sh")" \
"lookup_arr_quality_profile" "sonarr uses shared lookup"
assert_not_contains "$(cat "$REPO_ROOT/lib/arr.sh")" \
assert_not_contains "$(cat "$REPO_ROOT/lib/arr_quality.sh")" \
"movies 4K choice does not change this" "old TV hardcode is gone"
sonarr_connect=$(grep -n 'seerr_connect_service "sonarr"' -A2 "$REPO_ROOT/lib/seerr.sh")
assert_not_contains "$sonarr_connect" '"false"' "seerr sonarr is4k is not hardcoded false"

69
tests/unit/test_security.sh Executable file
View file

@ -0,0 +1,69 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Security & legal-hygiene regression tests (safe_source, safe_rm_rf, secrets, API headers, neutral content)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/../helpers.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/core.sh"
stub_log_error_no_exit
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
test_suite "safe_source blocks shell injection"
evil1="$tmp/evil1.env"
cat > "$evil1" <<'EOF'
FOO=$(id)
EOF
assert_failure "rejects command substitution" safe_source "$evil1"
evil2="$tmp/evil2.env"
cat > "$evil2" <<'EOF'
FOO=`id`
EOF
assert_failure "rejects backticks" safe_source "$evil2"
evil3="$tmp/evil3.env"
cat > "$evil3" <<'EOF'
FOO=bar; rm -rf /tmp/x
EOF
assert_failure "rejects unquoted semicolons" safe_source "$evil3"
good_brand="$tmp/branding.conf"
cat > "$good_brand" <<'EOF'
APP_NAME="assemblrr"
APP_DEFAULT_INSTALL_DIR="$HOME/$APP_NAME"
EOF
safe_source "$good_brand"
assert_eq "$HOME/assemblrr" "$APP_DEFAULT_INSTALL_DIR" "expands safe vars in branding.conf without eval"
test_suite "_is_safe_rm_path rejects traversal and shallow roots"
assert_failure "rejects .. traversal" _is_safe_rm_path "/home/user/../assemblrr"
assert_failure "rejects trailing .." _is_safe_rm_path "/home/user/assemblrr/.."
assert_failure "rejects relative path" _is_safe_rm_path "assemblrr/config"
assert_failure "rejects /tmp" _is_safe_rm_path "/tmp"
assert_failure "rejects $HOME" _is_safe_rm_path "$HOME"
assert_success "accepts install dir" _is_safe_rm_path "$HOME/assemblrr/config"
test_suite "write_secret_file sets 0600 and omits trailing newline"
sec="$tmp/secret.txt"
write_secret_file "$sec" "s3cr3t!"
assert_eq "s3cr3t!" "$(cat "$sec")" "secret content exact"
perm=$(stat -c '%a' "$sec" 2>/dev/null || stat -f '%Lp' "$sec")
assert_eq "600" "$perm" "secret permissions 0600"
test_suite "No borrowed OpenSubtitles API key or X-Emby-Token in runtime code"
assert_not_contains "$(cat "$REPO_ROOT/lib/prompts.sh")" "s38zmzVlW7IlYruWi7mHwDYl2SfMQoC1" "no borrowed OpenSubtitles key"
emby_hits=$(grep -rn 'X-Emby-Token' "$REPO_ROOT/bin" "$REPO_ROOT/lib" "$REPO_ROOT/scripts" 2>/dev/null || true)
assert_eq "" "$emby_hits" "no X-Emby-Token anywhere in bin/lib/scripts"
test_suite "No piracy domains or copyrighted sample titles in repository"
bad_hits=$(grep -rniE 'uindex\.org|DSNP\.WEB-DL|The Avengers|Age of Ultron|It Comes at Night|The Hobbit|Lost in Space|Iron Man' \
"$REPO_ROOT/bin" "$REPO_ROOT/lib" "$REPO_ROOT/scripts" "$REPO_ROOT/docs" "$REPO_ROOT/tests" \
--exclude="test_security.sh" 2>/dev/null || true)
assert_eq "" "$bad_hits" "zero copyrighted/piracy strings in repo code, docs, or tests"
test_summary

View file

@ -1,12 +1,13 @@
#!/bin/bash
# Unit tests for scripts/seerr-gateway.py (offline mock Seerr via --self-test)
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Unit tests for scripts/seerr-gateway.py (offline mock Seerr via unittest suite)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/../helpers.sh"
test_suite "seerr-gateway self-test"
test_suite "seerr-gateway unittest suite"
if ! command -v python3 >/dev/null 2>&1; then
echo "SKIP: python3 not available"
@ -14,21 +15,22 @@ if ! command -v python3 >/dev/null 2>&1; then
fi
gw="$REPO_ROOT/scripts/seerr-gateway.py"
suite="$REPO_ROOT/tests/unit/test_seerr_gateway_suite.py"
assert_true "gateway script exists" "[ -f \"$gw\" ]"
assert_true "gateway unittest suite exists" "[ -f \"$suite\" ]"
if python3 "$gw" --self-test; then
if python3 "$suite"; then
_TEST_PASSES=$((_TEST_PASSES + 1))
echo " PASS: seerr-gateway --self-test"
echo " PASS: seerr-gateway unittest suite"
else
_TEST_FAILURES=$((_TEST_FAILURES + 1))
echo " FAIL: seerr-gateway --self-test"
echo " FAIL: seerr-gateway unittest suite"
fi
# Compose wiring: seerr-gateway publishes 5055; seerr does not bind host 5055
test_suite "compose seerr-gateway wiring"
base="$REPO_ROOT/compose/base.yaml"
assert_contains "$(grep -A2 'container_name: seerr-gateway' "$base" || true)" "seerr-gateway" "gateway service present"
# Host publish 5055 should appear under seerr-gateway, not as seerr's ports block alone
seerr_block=$(awk '/^ seerr:/{p=1} p&&/^ [a-z]/{if(!/^ seerr:/)exit} p' "$base")
assert_not_contains "$seerr_block" "5055:5055" "seerr service does not publish host 5055"
gw_block=$(awk '/^ seerr-gateway:/{p=1} p&&/^ [a-z]/{if(!/^ seerr-gateway:/)exit} p' "$base")

View file

@ -0,0 +1,522 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Offline unit tests for scripts/seerr-gateway.py (no Docker stack required)."""
from __future__ import annotations
import importlib.util
import json
import os
import re
import socket
import threading
import time
import unittest
import urllib.error
import urllib.request
from http.client import HTTPConnection
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Dict, List, Optional, Tuple
REPO_ROOT = Path(__file__).resolve().parents[2]
_GW_PATH = REPO_ROOT / "scripts" / "seerr-gateway.py"
_SPEC = importlib.util.spec_from_file_location("seerr_gateway", _GW_PATH)
assert _SPEC and _SPEC.loader
gw_mod = importlib.util.module_from_spec(_SPEC)
import sys
sys.modules["seerr_gateway"] = gw_mod
_SPEC.loader.exec_module(gw_mod)
class _MockSeerr(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
calls: List[str] = []
request_payload: dict = {}
request_status: int = 200
file_delete_status: int = 204
request_delete_status: int = 204
users_by_key: Dict[str, dict] = {
"test-key": {"id": 1, "permissions": 2}, # ADMIN
"manager-key": {"id": 2, "permissions": 4}, # MANAGE_REQUESTS
"user-key": {"id": 99, "permissions": 32}, # Regular REQUEST user
}
last_request_headers: Dict[str, str] = {}
def log_message(self, fmt: str, *args) -> None:
return
def _caller(self) -> Optional[dict]:
key = self.headers.get("X-Api-Key") or ""
return self.users_by_key.get(key)
def _send(self, status: int, body: bytes = b"", content_type: str = "application/json") -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if self.command != "HEAD" and body:
self.wfile.write(body)
def do_GET(self) -> None: # noqa: N802
path = self.path.split("?", 1)[0]
_MockSeerr.last_request_headers = {k: v for k, v in self.headers.items()}
_MockSeerr.calls.append(f"GET {path}")
if path == "/redir":
self.send_response(302)
self.send_header("Location", "http://seerr:5055/login")
self.send_header("Content-Length", "0")
self.end_headers()
return
if path == "/api/v1/settings/public":
self._send(200, b'{"initialized":true}')
return
user = self._caller()
if user is None:
self._send(401, b'{"error":"Unauthorized"}')
return
if path == "/api/v1/auth/me":
self._send(200, json.dumps(user).encode("utf-8"))
return
if re.match(r"^/api/v1/request/(\d+)/?$", path):
if _MockSeerr.request_status != 200:
self._send(_MockSeerr.request_status, b'{"error":"upstream error"}')
return
self._send(200, json.dumps(_MockSeerr.request_payload).encode("utf-8"))
return
self._send(404, b'{"error":"not found"}')
def do_DELETE(self) -> None: # noqa: N802
path = self.path.split("?", 1)[0]
_MockSeerr.calls.append(f"DELETE {self.path}")
if self._caller() is None:
self._send(401, b'{"error":"Unauthorized"}')
return
if re.match(r"^/api/v1/media/\d+/file", path):
self._send(_MockSeerr.file_delete_status, b"")
return
if re.match(r"^/api/v1/request/\d+", path):
self._send(_MockSeerr.request_delete_status, b"")
return
self._send(404, b'{"error":"not found"}')
def do_POST(self) -> None: # noqa: N802
length = int(self.headers.get("Content-Length") or "0")
body = self.rfile.read(length) if length else b""
self._send(200, body)
class _MockSonarr(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
calls: List[str] = []
files: List[dict] = []
series: dict = {}
queue: List[dict] = []
episodefile_status: int = 200
def log_message(self, fmt: str, *args) -> None:
return
@classmethod
def reset(cls) -> None:
cls.calls = []
cls.episodefile_status = 200
cls.files = [
{"id": 1, "seasonNumber": 1, "seriesId": 10},
{"id": 2, "seasonNumber": 2, "seriesId": 10},
]
cls.series = {
"id": 10,
"title": "Sample Show",
"tvdbId": 362472,
"seasons": [
{"seasonNumber": 1, "monitored": True},
{"seasonNumber": 2, "monitored": True},
],
}
cls.queue = [
{"id": 201, "seriesId": 10, "downloadId": "aaa", "episode": {"seasonNumber": 1}},
{"id": 202, "seriesId": 10, "downloadId": "bbb", "episode": {"seasonNumber": 2}},
{"id": 203, "seriesId": 11, "downloadId": "ccc", "episode": {"seasonNumber": 1}},
]
def _send(self, status: int, body: bytes = b"") -> None:
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if self.command != "HEAD" and body:
self.wfile.write(body)
def do_GET(self) -> None: # noqa: N802
path = self.path.split("?", 1)[0]
_MockSonarr.calls.append(f"GET {self.path}")
if path == "/api/v3/series/10":
self._send(200, json.dumps(_MockSonarr.series).encode("utf-8"))
return
if path == "/api/v3/series":
self._send(200, json.dumps([_MockSonarr.series]).encode("utf-8"))
return
if path == "/api/v3/episodefile":
if _MockSonarr.episodefile_status != 200:
self._send(_MockSonarr.episodefile_status, b'{"error":"episodefile failed"}')
return
self._send(200, json.dumps(_MockSonarr.files).encode("utf-8"))
return
if path == "/api/v3/episode":
eps = [{"id": 100 + f["id"], "seasonNumber": f["seasonNumber"], "seriesId": 10} for f in _MockSonarr.files]
self._send(200, json.dumps(eps).encode("utf-8"))
return
if path == "/api/v3/queue":
self._send(200, json.dumps({"records": list(_MockSonarr.queue)}).encode("utf-8"))
return
self._send(404, b"{}")
def do_DELETE(self) -> None: # noqa: N802
path = self.path.split("?", 1)[0]
_MockSonarr.calls.append(f"DELETE {path}")
m = re.match(r"^/api/v3/episodefile/(\d+)$", path)
if m:
fid = int(m.group(1))
_MockSonarr.files = [f for f in _MockSonarr.files if f.get("id") != fid]
self._send(200, b"")
return
m = re.match(r"^/api/v3/queue/(\d+)$", path)
if m:
qid = int(m.group(1))
_MockSonarr.queue = [q for q in _MockSonarr.queue if q.get("id") != qid]
self._send(200, b"")
return
self._send(404, b"{}")
def do_PUT(self) -> None: # noqa: N802
path = self.path.split("?", 1)[0]
_MockSonarr.calls.append(f"PUT {path}")
length = int(self.headers.get("Content-Length") or "0")
if length:
self.rfile.read(length)
self._send(202, b"{}")
class _MockRadarr(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
calls: List[str] = []
movies: List[dict] = []
queue: List[dict] = []
def log_message(self, fmt: str, *args) -> None:
return
@classmethod
def reset(cls) -> None:
cls.calls = []
cls.movies = [
{"id": 1, "tmdbId": 10378, "title": "Big Buck Bunny"},
{"id": 2, "tmdbId": 999999, "title": "Sample Movie Two"},
]
cls.queue = [
{"id": 99, "movieId": 1, "downloadId": "abc123"},
{"id": 100, "movieId": 2, "downloadId": "def456"},
]
def _send(self, status: int, body: bytes = b"") -> None:
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if self.command != "HEAD" and body:
self.wfile.write(body)
def do_GET(self) -> None: # noqa: N802
path = self.path.split("?", 1)[0]
_MockRadarr.calls.append(f"GET {self.path}")
if path == "/api/v3/movie":
self._send(200, json.dumps(list(_MockRadarr.movies)).encode("utf-8"))
return
if path == "/api/v3/queue":
self._send(200, json.dumps({"records": list(_MockRadarr.queue)}).encode("utf-8"))
return
self._send(404, b"{}")
def do_DELETE(self) -> None: # noqa: N802
path = self.path.split("?", 1)[0]
_MockRadarr.calls.append(f"DELETE {path}")
m = re.match(r"^/api/v3/queue/(\d+)$", path)
if m:
qid = int(m.group(1))
_MockRadarr.queue = [q for q in _MockRadarr.queue if q.get("id") != qid]
self._send(200, b"")
return
self._send(404, b"{}")
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
class SeerrGatewayTests(unittest.TestCase):
mock_httpd: ThreadingHTTPServer
sonarr_httpd: ThreadingHTTPServer
radarr_httpd: ThreadingHTTPServer
gw_httpd: gw_mod.GatewayHTTPServer
cfg: gw_mod.GatewayConfig
gw_port: int
@classmethod
def setUpClass(cls) -> None:
mock_port = _free_port()
sonarr_port = _free_port()
radarr_port = _free_port()
cls.gw_port = _free_port()
cls.mock_httpd = ThreadingHTTPServer(("127.0.0.1", mock_port), _MockSeerr)
cls.sonarr_httpd = ThreadingHTTPServer(("127.0.0.1", sonarr_port), _MockSonarr)
cls.radarr_httpd = ThreadingHTTPServer(("127.0.0.1", radarr_port), _MockRadarr)
cls.cfg = gw_mod.GatewayConfig(
listen_host="127.0.0.1",
listen_port=cls.gw_port,
upstream=f"http://127.0.0.1:{mock_port}",
purge_on_delete_request=True,
max_body_bytes=1024,
sonarr_url=f"http://127.0.0.1:{sonarr_port}",
sonarr_api_key="sonarr-test-key",
sonarr_config="/tmp/assemblrr-no-such-sonarr-config.xml",
radarr_url=f"http://127.0.0.1:{radarr_port}",
radarr_api_key="radarr-test-key",
radarr_config="/tmp/assemblrr-no-such-radarr-config.xml",
)
cls.gw_httpd = gw_mod.GatewayHTTPServer(("127.0.0.1", cls.gw_port), gw_mod.GatewayHandler, cls.cfg)
for srv in (cls.mock_httpd, cls.sonarr_httpd, cls.radarr_httpd, cls.gw_httpd):
srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
time.sleep(0.1)
@classmethod
def tearDownClass(cls) -> None:
for srv in (cls.gw_httpd, cls.mock_httpd, cls.sonarr_httpd, cls.radarr_httpd):
srv.shutdown()
srv.server_close()
def setUp(self) -> None:
_MockSeerr.calls = []
_MockSeerr.request_status = 200
_MockSeerr.file_delete_status = 204
_MockSeerr.request_delete_status = 204
_MockSeerr.last_request_headers = {}
_MockSeerr.request_payload = {
"id": 42,
"status": 2,
"requestedBy": {"id": 1},
"is4k": False,
"media": {"id": 7, "tmdbId": 10378, "mediaType": "movie", "externalServiceId": 1},
}
_MockSonarr.reset()
_MockRadarr.reset()
self.cfg.purge_on_delete_request = True
self.cfg.sonarr_api_key = "sonarr-test-key"
def _http(
self, method: str, path: str, headers: Optional[dict] = None, data: Optional[bytes] = None
) -> Tuple[int, dict, bytes]:
url = f"http://127.0.0.1:{self.gw_port}{path}"
req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
try:
with urllib.request.urlopen(req, timeout=5) as resp:
return resp.status, dict(resp.headers), resp.read()
except urllib.error.HTTPError as e:
try:
return e.code, dict(e.headers), e.read()
finally:
e.close()
def test_health_and_ready(self) -> None:
st, _, body = self._http("GET", "/_assemblrr/health")
self.assertEqual(st, 200)
self.assertIn(b"purge_on_delete_request", body)
st, _, _ = self._http("GET", "/_assemblrr/ready")
self.assertEqual(st, 200)
def test_movie_cascade_order_and_queue_drain(self) -> None:
st, hdrs, _ = self._http("DELETE", "/api/v1/request/42", {"X-Api-Key": "test-key"})
self.assertEqual(st, 204)
self.assertEqual(hdrs.get("X-Assemblrr-Request-Delete-Purge"), "1")
self.assertIn("queue_movie:1:1", hdrs.get("X-Assemblrr-Purge-Detail") or "")
calls = list(_MockSeerr.calls)
i_me = next(i for i, c in enumerate(calls) if c == "GET /api/v1/auth/me")
i_get = next(i for i, c in enumerate(calls) if c.startswith("GET /api/v1/request/42"))
i_file = next(i for i, c in enumerate(calls) if "DELETE /api/v1/media/7/file" in c)
i_del = next(i for i, c in enumerate(calls) if c.startswith("DELETE /api/v1/request/42"))
self.assertLess(i_me, i_get)
self.assertLess(i_get, i_file)
self.assertLess(i_file, i_del)
self.assertTrue(any(c.startswith("DELETE /api/v3/queue/99") for c in _MockRadarr.calls))
self.assertFalse(any(c.startswith("DELETE /api/v3/queue/100") for c in _MockRadarr.calls))
def test_auth_failure_and_non_admin_confused_deputy_blocked(self) -> None:
# 1) Invalid key -> 401, zero deletes
st, _, _ = self._http("DELETE", "/api/v1/request/42", {"X-Api-Key": "wrong"})
self.assertEqual(st, 401)
self.assertFalse(any(c.startswith("DELETE") for c in _MockSeerr.calls))
self.assertEqual(_MockRadarr.calls, [])
# 2) Regular non-admin user trying to delete someone else's approved request -> 403, ZERO *arr calls!
_MockSeerr.calls = []
st, hdrs, _ = self._http("DELETE", "/api/v1/request/42", {"X-Api-Key": "user-key"})
self.assertEqual(st, 403)
self.assertEqual(hdrs.get("X-Assemblrr-Purge-Detail"), "forbidden_non_admin")
self.assertEqual(_MockRadarr.calls, [])
self.assertEqual(_MockSonarr.calls, [])
self.assertFalse(any(c.startswith("DELETE") for c in _MockSeerr.calls))
# 3) Regular non-admin user cancelling OWN pending request -> passes DELETE through, ZERO *arr calls!
_MockSeerr.calls = []
_MockSeerr.request_payload = {
"id": 42,
"status": 1, # pending
"requestedBy": {"id": 99},
"is4k": False,
"media": {"id": 7, "tmdbId": 10378, "mediaType": "movie", "externalServiceId": 1},
}
st, hdrs, _ = self._http("DELETE", "/api/v1/request/42", {"X-Api-Key": "user-key"})
self.assertEqual(st, 204)
self.assertEqual(hdrs.get("X-Assemblrr-Purge-Detail"), "passthrough_own_pending")
self.assertEqual(_MockRadarr.calls, [])
self.assertFalse(any("media/7/file" in c for c in _MockSeerr.calls))
self.assertTrue(any(c == "DELETE /api/v1/request/42" for c in _MockSeerr.calls))
def test_upstream_500_fails_closed(self) -> None:
_MockSeerr.request_status = 500
st, _, _ = self._http("DELETE", "/api/v1/request/42", {"X-Api-Key": "test-key"})
self.assertEqual(st, 502)
self.assertFalse(any(c.startswith("DELETE") for c in _MockSeerr.calls))
self.assertEqual(_MockRadarr.calls, [])
def test_forwarding_headers_and_https_location_rewrite(self) -> None:
st, _, _ = self._http("GET", "/api/v1/settings/public")
self.assertEqual(st, 200)
conn = HTTPConnection("127.0.0.1", self.gw_port, timeout=5)
conn.request("GET", "/redir", headers={"Host": "localhost:5055", "X-Forwarded-Proto": "https"})
resp = conn.getresponse()
loc = resp.getheader("Location") or ""
resp.read()
conn.close()
self.assertEqual(resp.status, 302)
self.assertEqual(loc, "https://localhost:5055/login")
conn = HTTPConnection("127.0.0.1", self.gw_port, timeout=5)
conn.request("GET", "/api/v1/settings/public", headers={"Host": "localhost:5055"})
conn.getresponse().read()
conn.close()
got_host = _MockSeerr.last_request_headers.get("Host") or _MockSeerr.last_request_headers.get("host")
got_proto = _MockSeerr.last_request_headers.get("X-Forwarded-Proto") or _MockSeerr.last_request_headers.get("x-forwarded-proto")
self.assertEqual(got_host, "localhost:5055")
self.assertEqual(got_proto, "http")
def test_purge_disabled_and_no_media(self) -> None:
self.cfg.purge_on_delete_request = False
st, _, _ = self._http("DELETE", "/api/v1/request/99", {"X-Api-Key": "test-key"})
self.assertEqual(st, 204)
self.assertFalse(any("media" in c for c in _MockSeerr.calls))
self.cfg.purge_on_delete_request = True
_MockSeerr.calls = []
_MockSeerr.request_payload = {"id": 5, "is4k": False, "media": {}}
st, hdrs, _ = self._http("DELETE", "/api/v1/request/5", {"X-Api-Key": "test-key"})
self.assertEqual(st, 204)
self.assertIn("no_media", hdrs.get("X-Assemblrr-Purge-Detail") or "")
def test_tv_partial_seasons_vs_all_seasons_and_specials(self) -> None:
# S01 only when S02 exists
_MockSeerr.request_payload = {
"id": 8,
"type": "tv",
"is4k": False,
"seasons": [{"seasonNumber": 1, "status": 2}],
"media": {"id": 6, "tmdbId": 84958, "tvdbId": 362472, "mediaType": "tv", "externalServiceId": 10},
}
st, hdrs, _ = self._http("DELETE", "/api/v1/request/8", {"X-Api-Key": "manager-key"})
self.assertEqual(st, 204)
self.assertFalse(any("DELETE /api/v1/media/6/file" in c for c in _MockSeerr.calls))
self.assertTrue(any(c == "DELETE /api/v3/episodefile/1" for c in _MockSonarr.calls))
self.assertFalse(any(c == "DELETE /api/v3/episodefile/2" for c in _MockSonarr.calls))
self.assertTrue(any(c == "DELETE /api/v3/queue/201" for c in _MockSonarr.calls))
self.assertFalse(any(c == "DELETE /api/v3/queue/202" for c in _MockSonarr.calls))
self.assertIn("seasons_deleted", hdrs.get("X-Assemblrr-Purge-Detail") or "")
# S01 with specials surviving
_MockSonarr.reset()
_MockSonarr.files = [{"id": 1, "seasonNumber": 1, "seriesId": 10}, {"id": 3, "seasonNumber": 0, "seriesId": 10}]
_MockSonarr.series = {
"id": 10, "title": "Sample Show", "tvdbId": 362472,
"seasons": [{"seasonNumber": 0, "monitored": True}, {"seasonNumber": 1, "monitored": True}],
}
_MockSeerr.calls = []
st, _, _ = self._http("DELETE", "/api/v1/request/8", {"X-Api-Key": "test-key"})
self.assertEqual(st, 204)
self.assertTrue(any(f.get("seasonNumber") == 0 for f in _MockSonarr.files))
self.assertFalse(any("DELETE /api/v1/media/6/file" in c for c in _MockSeerr.calls))
# All seasons covered -> title delete
_MockSonarr.reset()
_MockSeerr.calls = []
_MockSeerr.request_payload = {
"id": 9, "type": "tv", "is4k": False,
"seasons": [{"seasonNumber": 1}, {"seasonNumber": 2}],
"media": {"id": 6, "mediaType": "tv", "externalServiceId": 10, "tvdbId": 362472},
}
st, _, _ = self._http("DELETE", "/api/v1/request/9", {"X-Api-Key": "test-key"})
self.assertEqual(st, 204)
self.assertTrue(any("DELETE /api/v1/media/6/file" in c for c in _MockSeerr.calls))
self.assertFalse(any(c.startswith("DELETE /api/v3/episodefile/") for c in _MockSonarr.calls))
def test_tv_safety_gates_and_body_limit(self) -> None:
# Missing Sonarr key -> 502
self.cfg.sonarr_api_key = ""
_MockSeerr.request_payload = {
"id": 8, "type": "tv", "is4k": False,
"seasons": [{"seasonNumber": 1}],
"media": {"id": 6, "mediaType": "tv", "externalServiceId": 10},
}
st, hdrs, _ = self._http("DELETE", "/api/v1/request/8", {"X-Api-Key": "test-key"})
self.assertEqual(st, 502)
self.assertIn("sonarr_key_missing", hdrs.get("X-Assemblrr-Purge-Detail") or "")
self.cfg.sonarr_api_key = "sonarr-test-key"
# Empty TV seasons -> 502
_MockSeerr.request_payload = {
"id": 11, "type": "tv", "is4k": False, "seasons": [],
"media": {"id": 6, "mediaType": "tv", "externalServiceId": 10},
}
st, _, _ = self._http("DELETE", "/api/v1/request/11", {"X-Api-Key": "test-key"})
self.assertEqual(st, 502)
# Episodefile 500 -> 502
_MockSonarr.episodefile_status = 500
_MockSeerr.request_payload = {
"id": 8, "type": "tv", "is4k": False,
"seasons": [{"seasonNumber": 1}],
"media": {"id": 6, "mediaType": "tv", "externalServiceId": 10},
}
st, _, _ = self._http("DELETE", "/api/v1/request/8", {"X-Api-Key": "test-key"})
self.assertEqual(st, 502)
# is4k uses externalServiceId4k
self.assertEqual(
gw_mod.sonarr_lookup_series_id(
self.cfg,
{"is4k": True, "media": {"externalServiceId": 10, "externalServiceId4k": 42}},
"sonarr-test-key",
),
42,
)
# Oversized body -> 413
st, _, _ = self._http("POST", "/echo", data=b"x" * 2048)
self.assertEqual(st, 413)
if __name__ == "__main__":
unittest.main(verbosity=2)

0
tests/unit/test_ui.sh Normal file → Executable file
View file

64
tests/unit/test_upgrade.sh Normal file → Executable file
View file

@ -55,21 +55,15 @@ assert_eq "70 50" "$(_bazarr_min_scores ell)" "greek alone is lenient"
assert_eq "70 50" "$(_bazarr_min_scores eng ell)" "english+greek is lenient"
assert_eq "70 50" "$(_bazarr_min_scores de)" "german is lenient"
test_suite "_bazarr_add_language_providers greeksubs"
providers=()
FZF_SELECT_STATUS=""
_bazarr_add_language_providers el en
assert_eq "greeksubs" "${providers[*]}" "adds greeksubs for el"
providers=(opensubtitlescom)
_bazarr_add_language_providers el
assert_eq "opensubtitlescom greeksubs" "${providers[*]}" "keeps existing and appends"
providers=(greeksubs)
_bazarr_add_language_providers el
assert_eq "greeksubs" "${providers[*]}" "does not duplicate"
providers=()
FZF_SELECT_STATUS="confirmed"
_bazarr_add_language_providers el
assert_eq "" "${providers[*]-}" "respects confirmed picker"
test_suite "iso639_to_code2 covers full subtitle map & bazarr stays neutral"
assert_eq "cs" "$(_bazarr_lang_code2 ces)" "ces -> cs"
assert_eq "uk" "$(_bazarr_lang_code2 ukr)" "ukr -> uk"
assert_eq "ro" "$(_bazarr_lang_code2 ron)" "ron -> ro"
assert_eq "hu" "$(_bazarr_lang_code2 hun)" "hun -> hu"
assert_eq "ja" "$(_bazarr_lang_code2 jpn)" "jpn -> ja"
assert_not_contains "$(cat "$REPO_ROOT/lib/bazarr.sh")" "greeksubs" "bazarr does not auto-inject greeksubs"
assert_contains "$(sed -n '/^_bazarr_post_form()/,/^}/p' "$REPO_ROOT/lib/bazarr.sh")" "http_request" "bazarr uses http_request"
assert_not_contains "$(sed -n '/^configure_bazarr()/,/^}/p' "$REPO_ROOT/lib/bazarr.sh")" ' -F ' "bazarr uses --form-string, never curl -F"
test_suite "migration 001 skip when custom.yaml has bazarr"
tmp="" tmp2=""
@ -200,5 +194,45 @@ assert_contains "$dev" "-name '*.py'" "bootstrap-dev.ps1 strips Python"
assert_contains "$dev" "-name '*.Dockerfile'" "bootstrap-dev.ps1 strips sidecar Dockerfiles"
assert_not_contains "$win" "sed -i 's/\\r\$//' /tmp/\$AppName/.env.example /tmp/\$AppName/bin/*.sh" \
"bootstrap.ps1 no longer uses the stale glob list"
assert_not_contains "$dev" ".local/bin/lib" "bootstrap-dev.ps1 does not copy stale ~/.local/bin/lib"
assert_contains "$dev" "apply_managed_files" "bootstrap-dev.ps1 syncs via managed_files.sh"
test_suite "migration 004 backfills feature flags & creates sabnzbd dir"
tmp5=$(mktemp -d)
printf 'TZ=UTC\n' > "$tmp5/.env"
printf 'TZ="UTC"\nMEDIA_SERVICE="emby"\n' > "$tmp5/.assemblrr-config"
unset -f migration_should_skip migration_apply 2>/dev/null || true
# shellcheck source=/dev/null
source "$REPO_ROOT/migrations/004_jellyfin_12_and_stack_revival.sh"
if migration_should_skip "$tmp5"; then
_TEST_FAILURES=$((_TEST_FAILURES + 1))
echo " FAIL: 004 should not skip when new keys missing"
else
_TEST_PASSES=$((_TEST_PASSES + 1))
echo " PASS: 004 detects missing keys & sabnzbd dir"
fi
migration_apply "$tmp5" 2>/dev/null
assert_true "004 created config/sabnzbd" "[ -d '$tmp5/config/sabnzbd' ]"
assert_contains "$(cat "$tmp5/.env")" "USENET_ENABLED=n" "004 backfills .env USENET_ENABLED"
assert_contains "$(cat "$tmp5/.assemblrr-config")" 'BYPARR_ENABLED="n"' "004 backfills config BYPARR_ENABLED"
if migration_should_skip "$tmp5"; then
_TEST_PASSES=$((_TEST_PASSES + 1))
echo " PASS: 004 skips once applied"
else
_TEST_FAILURES=$((_TEST_FAILURES + 1))
echo " FAIL: 004 should skip after apply"
fi
rm -rf "$tmp4" "$tmp5"
test_suite "managed files include modular libs & feature overlays"
for req in lib/log.sh lib/usenet.sh lib/recyclarr.sh lib/languages.sh compose/vuetorrent.yaml compose/gpu-intel.yaml compose/gpu-nvidia.yaml compose/byparr.yaml compose/usenet.yaml docs/komodo.md NOTICE; do
assert_true "has $req" "echo \"\$list\" | grep -q '${req}|${req}'"
done
test_suite "upgrade engine rollback & channel support"
up_src=$(cat "$REPO_ROOT/lib/upgrade.sh")
assert_contains "$up_src" "_restore_managed_rollback" "upgrade rolls back on invalid compose"
assert_contains "$up_src" "ASSEMBLRR_UPGRADE_REEXEC" "upgrade re-execs updated cli"
assert_contains "$up_src" ".assemblrr-channel" "upgrade supports .assemblrr-channel"
test_summary

121
tests/unit/test_usenet.sh Executable file
View file

@ -0,0 +1,121 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Offline unit tests for lib/usenet.sh + free mock_nntp.py / mock_newznab.py fixtures
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/../helpers.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/core.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/api.sh"
# shellcheck disable=SC1091
source "$REPO_ROOT/lib/usenet.sh"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
test_suite "sabnzbd_enabled flag"
USENET_ENABLED=n
assert_false "disabled when n" sabnzbd_enabled
USENET_ENABLED=y
assert_true "enabled when y" sabnzbd_enabled
USENET_ENABLED=Y
assert_true "enabled when Y" sabnzbd_enabled
test_suite "sabnzbd_extract_api_key parses sabnzbd.ini"
ini="$tmp/sabnzbd.ini"
printf 'host = 0.0.0.0\r\napi_key = deadbeef123456\r\nnzb_key = abc\r\n' > "$ini"
assert_eq "deadbeef123456" "$(sabnzbd_extract_api_key "$ini")" "extracts key without CR"
test_suite "write_sabnzbd_config creates dirs & validates secret"
INSTALL_DIR="$tmp/install"
MEDIA_DIRECTORY="$tmp/media"
mkdir -p "$INSTALL_DIR/secrets" "$INSTALL_DIR/config"
write_secret_file "$INSTALL_DIR/secrets/usenet_password.txt" "secretpw"
write_sabnzbd_config
assert_true "creates config/sabnzbd" "[ -d '$INSTALL_DIR/config/sabnzbd' ]"
test_suite "arr_build_sabnzbd_payload generates valid Radarr & Sonarr payloads"
r_json=$(arr_build_sabnzbd_payload '[]' "sabkey-1" "movieCategory" "movies")
assert_eq "SABnzbd" "$(echo "$r_json" | jq -r '.name')" "client name SABnzbd"
assert_eq "Sabnzbd" "$(echo "$r_json" | jq -r '.implementation')" "implementation Sabnzbd"
assert_eq "sabnzbd" "$(echo "$r_json" | jq -r '.fields[] | select(.name=="host") | .value')" "host sabnzbd"
assert_eq "8080" "$(echo "$r_json" | jq -r '.fields[] | select(.name=="port") | .value')" "internal port 8080"
assert_eq "movies" "$(echo "$r_json" | jq -r '.fields[] | select(.name=="movieCategory") | .value')" "movieCategory=movies"
s_json=$(arr_build_sabnzbd_payload '[]' "sabkey-1" "tvCategory" "tv")
assert_eq "tv" "$(echo "$s_json" | jq -r '.fields[] | select(.name=="tvCategory") | .value')" "tvCategory=tv"
mock_schema='[{"implementation":"Sabnzbd","implementationName":"SABnzbd","configContract":"SabnzbdSettings","fields":[{"name":"host","value":""},{"name":"port","value":0},{"name":"useSsl","value":true},{"name":"urlBase","value":"/sab"},{"name":"apiKey","value":""},{"name":"movieCategory","value":""}]}]'
schema_json=$(arr_build_sabnzbd_payload "$mock_schema" "sabkey-2" "movieCategory" "movies")
assert_eq "sabkey-2" "$(echo "$schema_json" | jq -r '.fields[] | select(.name=="apiKey") | .value')" "injects apiKey from *arr schema"
assert_eq "false" "$(echo "$schema_json" | jq -r '.fields[] | select(.name=="useSsl") | .value')" "disables internal TLS on bridge network"
USENET_ENABLED=y
assert_success "0-arg arr_configure_sabnzbd handles missing API keys cleanly" \
env -u RADARR_API_KEY -u SONARR_API_KEY bash -c 'source "$1/lib/core.sh"; source "$1/lib/api.sh"; source "$1/lib/usenet.sh"; USENET_ENABLED=y; INSTALL_DIR="$2"; arr_configure_sabnzbd' _ "$REPO_ROOT" "$tmp/install"
test_suite "Free mock_nntp.py + mock_newznab.py loopback protocol check"
if command -v python3 >/dev/null 2>&1; then
if python3 - "$REPO_ROOT" <<'PY'
import sys, socket, urllib.request, xml.etree.ElementTree as ET
from pathlib import Path
repo = Path(sys.argv[1])
sys.path.insert(0, str(repo / "tests" / "fixtures"))
import mock_nntp
import mock_newznab
nntp = mock_nntp.start_background("127.0.0.1", 0, username="u1", password="p1")
newznab = mock_newznab.start_background("127.0.0.1", 0)
try:
nntp_port = nntp.server_address[1]
nzb_port = newznab.server_address[1]
# 1) Newznab caps & NZB fetch
caps = urllib.request.urlopen(f"http://127.0.0.1:{nzb_port}/api?t=caps", timeout=3).read().decode()
assert "<caps>" in caps and "movie-search" in caps
nzb_xml = urllib.request.urlopen(f"http://127.0.0.1:{nzb_port}/api?t=get&id=sample-1", timeout=3).read().decode()
root = ET.fromstring(nzb_xml)
seg = root.find(".//{http://www.newzbin.com/DTD/2003/nzb}segment")
assert seg is not None and seg.text == "sample-part1@assemblrr.test"
# 2) NNTP auth + ARTICLE + yEnc body present
with socket.create_connection(("127.0.0.1", nntp_port), timeout=3) as s:
f = s.makefile("rwb", buffering=0)
assert f.readline().startswith(b"200 ")
f.write(b"AUTHINFO USER u1\r\n")
assert f.readline().startswith(b"381 ")
f.write(b"AUTHINFO PASS p1\r\n")
assert f.readline().startswith(b"281 ")
f.write(f"ARTICLE <{seg.text}>\r\n".encode())
first = f.readline()
assert first.startswith(b"220 "), first
body_lines = []
while True:
ln = f.readline()
if ln == b".\r\n" or not ln:
break
body_lines.append(ln)
joined = b"".join(body_lines)
assert b"=ybegin" in joined and b"=yend" in joined
f.write(b"QUIT\r\n")
assert f.readline().startswith(b"205 ")
finally:
nntp.shutdown(); nntp.server_close()
newznab.shutdown(); newznab.server_close()
PY
then
_TEST_PASSES=$((_TEST_PASSES + 1))
echo " PASS: mock NNTP auth/ARTICLE/yEnc + Newznab caps/NZB work offline"
else
_TEST_FAILURES=$((_TEST_FAILURES + 1))
echo " FAIL: mock NNTP/Newznab protocol check failed"
fi
else
echo " SKIP: python3 unavailable"
fi
test_summary

48
tests/unit/test_vpn_watchdog.sh Executable file
View file

@ -0,0 +1,48 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Unit tests for scripts/vpn-watchdog.sh (cooldown & false-positive suppression)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/../helpers.sh"
WATCHDOG_SOURCE_ONLY=1
# shellcheck disable=SC1091
source "$REPO_ROOT/scripts/vpn-watchdog.sh"
test_suite "watchdog_classify_torrent"
_props_broken='{"has_metadata":false,"nb_connections":0}'
_props_healthy='{"has_metadata":true,"nb_connections":4}'
_trk_broken='[{"status":4,"msg":"Operation not permitted"},{"status":4,"msg":"timed out"},{"status":4,"msg":"Host not found"}]'
_trk_healthy='[{"status":2,"msg":"OK"},{"status":4,"msg":"timed out"}]'
_trk_single_err='[{"status":4,"msg":"timed out"}]'
assert_eq "1 0" "$(watchdog_classify_torrent "$_props_broken" "$_trk_broken")" "broken metadata + 3 failed trackers"
assert_eq "0 1" "$(watchdog_classify_torrent "$_props_healthy" "$_trk_healthy")" "healthy connected + status 2 tracker"
assert_eq "0 0" "$(watchdog_classify_torrent "$_props_broken" "$_trk_single_err")" "single tracker error is not systemic routing break"
test_suite "watchdog_should_restart_vpn guards"
# Systemic failure, no working torrents, no prior restart -> restart
assert_success "global outage triggers restart" watchdog_should_restart_vpn 2 0 1000 0 300
# Single broken magnet while healthy torrents have active trackers/peers -> DO NOT restart
assert_failure "1 dead magnet + healthy torrent skips restart" watchdog_should_restart_vpn 1 3 1000 0 300
# Within cooldown (last restart 120s ago, cooldown 300s) -> DO NOT restart
assert_failure "cooldown prevents restart storm" watchdog_should_restart_vpn 2 0 1120 1000 300
# Cooldown elapsed (301s ago) -> restart allowed again
assert_success "cooldown elapsed allows restart" watchdog_should_restart_vpn 2 0 1301 1000 300
_wd_src=$(cat "$REPO_ROOT/scripts/vpn-watchdog.sh")
assert_not_contains "$_wd_src" 'api_get()' "renamed api_get to avoid collision"
assert_contains "$_wd_src" 'WATCHDOG_COOLDOWN_SEC' "cooldown wired"
_jar=$(mktemp)
printf '# Netscape HTTP Cookie File\n#HttpOnly_gluetun\tFALSE\t/\tFALSE\t1795288207\tQBT_SID_8081\tabc123\n' > "$_jar"
assert_success "accepts #HttpOnly_ QBT_SID_8081 cookie" watchdog_cookie_has_sid "$_jar"
printf '# Netscape HTTP Cookie File\ngluetun\tFALSE\t/\tFALSE\t1795288207\tSID\tlegacy123\n' > "$_jar"
assert_success "accepts legacy SID cookie" watchdog_cookie_has_sid "$_jar"
printf '# Netscape HTTP Cookie File\n# just a comment\ngluetun\tFALSE\t/\tFALSE\t1795288207\tOTHER\tval\n' > "$_jar"
assert_failure "rejects comment-only or unrelated cookie jar" watchdog_cookie_has_sid "$_jar"
rm -f "$_jar"
test_summary