diff --git a/.gitignore b/.gitignore index 2c889c4..c33aa24 100644 --- a/.gitignore +++ b/.gitignore @@ -50,3 +50,4 @@ helm.sh .coverage coverage.xml htmlcov/ +personal_notes/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 6657f8b..4025df4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog All notable changes to this project will be documented in this file. +## [0.10.0] - 2026-09-08 + + +### Added +- **Prowlarr Integration**: Full support for Prowlarr indexing alongside Jackett. Helm now natively discovers over 600+ indexers via Prowlarr's `/api/v1/indexer/schema` API. +- **Privacy Display**: Prowlarr indexers in the TUI now clearly display their status as `public`, `private`, or `semi-private` . +- **Tracker Origin Tagging**: JSON output now prefixes trackers with their source (`Jackett (1337x)` vs `Prowlarr (1337x)`) to determine indexer accountability. +- **Interactive Installer Options**: `setup.sh` now prompts users to choose between Jackett, Prowlarr, or both for their core indexer manager. +- **Native Prowlarr Installation**: `setup.sh` now supports downloading and installing Prowlarr directly to `/opt/Prowlarr` and configuring a `systemd` daemon for bare-metal deployments (includes BETA safety warnings). +- **Container Status Command**: Added a new `helm status` (and global `--status` flag) command that natively queries Docker or Podman to list the uptime of all running Helm containers and prints their active Web UI URLs for easy access. +- **Robust Exception Handling**: Implemented a global `KeyboardInterrupt` trap in `cli.py` to prevent ugly stack traces. The ephemeral stack now safely spins down via `teardown_oneshot()` if the user cancels operations prematurely. +- **Network Resiliency**: Added explicit timeouts to all Jackett and Prowlarr API calls in `indexer_manager.py` and `rss_fetcher.py`. ReadTimeouts will no longer hang the app. + +### Changed +- **Port Conflict Avoidance**: Migrated Prowlarr's ephemeral docker port from `9696` to `19696` to strictly match Jackett (`19117`) and qBittorrent (`18080`). This guarantees no "Address already in use" errors when running Helm on servers that already have these native apps running. +- **JSON Stdout Sanitization**: The `-j/--json` flag is now guaranteed to return pure, `jq`-parseable JSON. Ephemeral boot logs have been properly redirected to `stderr`. +- **Linting & Code Cleanup**: Cleaned up the repository of temporary patching scripts. +- **Unified Concurrent Lite Pipeline**: The three inline Lite sources (apibay, torrents-csv, Nyaa RSS) now run inside the same bounded worker pool as the search plugins instead of serially before them. Worst-case search latency dropped from a ~75s serial chain of timeouts to a single ~25s bound. +- **Shared HTTP Session**: Lite fetchers and the JSON-API plugins (BitTorrented, EZTV, SubsPlease, YTS) now reuse one connection-pooled `requests.Session` (keep-alive + pool of 32 sockets) via `helm.core.http`, eliminating a fresh TLS handshake per request on multi-page HTML plugins. +- **Single apibay Fetch**: The bundled `piratebay.py` plugin (a duplicate of the inline apibay source) is no longer loaded by the plugin loader, so The Pirate Bay is queried exactly once per search. + +### Fixed +- **Lite-Mode fallback crash on empty manager results**: `search_indexers()` referenced a never-implemented `search_all_plugins` import, so any search where Jackett/Prowlarr returned zero results raised `ImportError` (surfacing as a confusing "Indexer Manager not available" message). The async aggregator is now implemented and the fallback silently returns Lite results. +- **Empty piped stdout on exit**: CLI termination paths used `os._exit`, which bypasses Python's stdout flush and produced empty output when `--json` was piped. All exits now use `raise SystemExit(...) from None`, flushing buffered stdout reliably. +- **Prowlarr default indexer seeding actually implemented**: `ProwlarrManager.seed_default_indexers()` now provisions working defaults (1337x, YTS, TorrentGalaxy, NyaaPantsu, EZTV) on first use against Prowlarr's live schema rather than remaining a no-op. + The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). diff --git a/README.md b/README.md index aceeb2b..8fcb486 100644 --- a/README.md +++ b/README.md @@ -38,19 +38,19 @@ Helm is a blazing-fast CLI-based torrent automation tool designed to fetch, filter, and send magnet links to qBittorrent. -It completely automates its own setup, orchestrating Jackett, Flaresolverr, and qBittorrent using Docker or Podman under the hood. +It completely automates its own setup, orchestrating Jackett, Prowlarr, Flaresolverr, and qBittorrent using Docker or Podman under the hood. --- ## Features -- **Automated Container Setup:** No more manually configuring Jackett, qBittorrent, or Flaresolverr. `setup.sh` orchestrates everything via Docker/Podman compose. +- **Automated Container Setup:** No more manually configuring Jackett, Prowlarr, qBittorrent, or Flaresolverr. `setup.sh` orchestrates everything via Docker/Podman compose. - **Ephemeral (One-Shot) Mode:** Containers spin up when you search/download, and tear down immediately after to save RAM and CPU. - **Permanent Mode:** Keep the stack running 24/7 if you prefer. - **VPN Support:** Automatically route qBittorrent traffic through Gluetun (Wireguard/OpenVPN). - **Live Search & Filter:** A fast, interactive CLI interface to search indexers and select torrents. -- **Lite Mode (Zero Setup):** Search and get Magnet links instantly using built-in Python scrapers without needing Docker or Jackett installed! -- **CLI Indexer Management:** Add and remove Jackett indexers directly from the command line. +- **Lite Mode (Zero Setup):** Search and get Magnet links instantly using built-in Python scrapers — no Docker or Jackett needed. All sources (apibay, torrents-csv, Nyaa, and the bundled search plugins) run concurrently over a connection-pooled session, so even a hung index tops out at one socket timeout. +- **CLI Indexer Management:** Manage both Jackett and Prowlarr indexers directly from the command line. --- @@ -105,7 +105,7 @@ Honestly for the most part it's for myself and my own usage i wanted to get magn Helm is actively roaming the 7seas and trying to get more treasures: -- Prowlarr integration (Replacing Jackett). +- ~~Prowlarr integration (Replacing Jackett).~~ Done in 0.10.0 — Jackett, Prowlarr, or both. - Scrumptious TUI interface. - Better indexer management. @@ -115,7 +115,7 @@ For more detailed tasks breakdown check [TODO.md](docs/TODO.md) All notable changes are tracked in [CHANGELOG](CHANGELOG.md). -**Latest release: [0.9.5](CHANGELOG.md#095---2026-08-31)** — Major UI improvements including multi-select category checkboxes, inline filtering and sorting, stateful navigation, tracker origins in results, and auto-injection of default Jackett indexers on initialization. See the full file for everything that came before. +**Latest release: [0.10.0](CHANGELOG.md#0100---2026-09-08)** — Full Prowlarr integration with native default-indexer seeding, a new container `status` command, guaranteed-pure `--json` output, and a rewritten Lite pipeline that runs every source concurrently over a shared connection-pooled session. See the full file for everything that came before. ## Configuration @@ -191,10 +191,22 @@ Helm pulls torrent RSS feeds from configured indexers, applies filtering and ded ## Credits -Shoutout to the goats! This project is built utilizing these fantastic open-source tools: qBittorrent, Jackett, and Flaresolverr. +Shoutout to the goats! This project is built utilizing these fantastic open-source tools: + +(i lwk feel like a sales person pitching these but wtv lol) + +- **[qBittorrent](https://www.qbittorrent.org)** — the torrent client that receives all our magnets. +- **[Jackett](https://github.com/Jackett/Jackett)** — the battle-tested indexer manager for public trackers. +- **[Prowlarr](https://github.com/Prowlarr/Prowlarr)** — the modern, community-indexer-powered search indexer manager. Helm natively discovers its 600+ indexer schema alongside Jackett. +- **[Flaresolverr](https://github.com/FlareSolverr/FlareSolverr)** — busts Cloudflare walls so the indexers actually talk to us. +- **[Gluetun](https://github.com/qdm12/gluetun)** — keeps qBittorrent safely behind your VPN with zero config headaches. +- **[LinuxServer.io](https://www.linuxserver.io)** — their massively maintained container images are what the Docker/Podman stack runs on (always coming in clutch istg). **Lite Mode Plugins:** -A massive thank you to the [qBittorrent search engine plugins community](https://github.com/qbittorrent/search-plugins) and developers. Helm's lightweight search mode natively supports their `.py` plugins, making it possible to search dozens of torrent indexers instantly without any Docker overhead. +A massive thank you to the [qBittorrent search engine plugins community](https://github.com/qbittorrent/search-plugins) and developers. Helm's lightweight search mode natively supports their `.py` plugins, making it possible to search dozens of torrent indexers instantly without any Docker overhead. Bundled and adapted from that community (licensed for adaptation): **BitSearch, EZTV, LimeTorrents, SubsPlease, TorLock, TorrentProject, YTS, 1337x, The Pirate Bay/apibay** — alongside Helm's own **BitTorrented** plugin and the inline **apibay, torrents-csv & Nyaa** feeds. + +**Built with these Python libraries:** +**[requests](https://github.com/psf/requests)** (originally Kenneth Reitz), **[beautifulsoup4](https://www.crummy.com/software/BeautifulSoup/)** (Leonard Richardson), **[python-dotenv](https://github.com/theskumar/python-dotenv)** (theskumar), and **[libtorrent](https://github.com/arvidn/libtorrent)** (Arvid Norberg) doing the heavy lifting. ## License diff --git a/docker-compose.yml.example b/docker-compose.yml.example index fa6b341..13cfcf1 100644 --- a/docker-compose.yml.example +++ b/docker-compose.yml.example @@ -63,8 +63,8 @@ services: - 18191:8191 restart: unless-stopped - mini-helm: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-mini-helm" + cli: + container_name: "${COMPOSE_PROJECT_NAME:-helm}-cli" image: ghcr.io/piratebird/helm:latest dns: - 8.8.8.8 diff --git a/docs/BENCHMARK.md b/docs/BENCHMARK.md index 68fc0ac..05b3349 100644 --- a/docs/BENCHMARK.md +++ b/docs/BENCHMARK.md @@ -35,3 +35,18 @@ While Docker achieves incredible compression on the application memory, you must #### 3. Verdict The optimizations we just committed to `setup.sh` are game-changing. By enforcing limits on the containers, your users will actually save *more* memory running Helm via Podman or Docker than they would if they compiled and ran the apps manually on their own host! + +--- + +### Update (September 2026): Full Ephemeral Stack with Prowlarr & Flaresolverr + +Following the integration of **Prowlarr** and **Flaresolverr** into the one-shot stack, we re-ran the memory profiling using the exact same constraints. + +| Deployment Architecture | qBittorrent | Jackett | Prowlarr | Flaresolverr | CLI Runner (Python) | Total Active Memory | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| **Docker** | `~17.2 MB` | `~53.1 MB`| `~67.9 MB`| `~40.2 MB` | `~31.0 MB` | **`~209.4 MB`** | +| **Podman** | `~15.0 MB` | `~47.0 MB`| `~61.0 MB`| `~36.0 MB` | `~31.0 MB` | **`~190.0 MB`** | +| **Native (Lite Mode)** | N/A | N/A | N/A | N/A | `~31.0 MB` | **`~31.0 MB`** | + +#### 4. The Ephemeral Advantage +With Prowlarr and Flaresolverr added, a standard daemonized setup would idle at nearly ~200MB 24/7. However, because Helm utilizes the **One-Shot Ephemeral Stack**, this memory is *only* consumed during the exact moment you execute a search and download a torrent. The second you exit the TUI, the containers are spun down (`teardown_oneshot()`), and the stack's memory footprint returns to **0 MB**. diff --git a/docs/TODO.md b/docs/TODO.md index f96bc5f..b5a2622 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -33,14 +33,16 @@ - [x] Allow users to search and get Magnet links instantly *without* Docker or Jackett installed. ### 2. Tracker Management -- [ ] **Prowlarr Integration (Optional Mode):** - - [ ] Give users a choice during setup between Jackett and Prowlarr. - - [ ] Implement API handlers for Prowlarr so users who prefer modern tracker syncing can use it seamlessly. +- [x] **Prowlarr Integration (Optional Mode):** + - [x] Give users a choice during setup between Jackett and Prowlarr. + - [x] Implement API handlers for Prowlarr so users who prefer modern tracker syncing can use it seamlessly. - [x] **Improve Jackett Interaction:** - [x] Allow adding/removing indexers directly from the CLI. - [x] Auto-inject default indexers (1337x, YTS, etc.) during `helm init` via internal API. ### 3. Distribution & Installation +- [ ] **Uninstall Script (`uninstall.sh`):** + - [ ] Provide an automated script to cleanly remove Helm containers, networks, volumes, and Python packages based on user choice. - [x] **Publish to PyPI (`pip install helm-torrent`):** - [x] Restructure directory to standard Python package layout. - [x] Implement `helm init` to automatically bootstrap the Docker environment on first run. diff --git a/pyproject.toml b/pyproject.toml index 0359c4f..34da5c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "helm-torrent" -version = "0.9.5" +version = "0.10.0" authors = [ { name="Piratebird" }, ] diff --git a/setup.sh b/setup.sh index c539607..afc0f8b 100755 --- a/setup.sh +++ b/setup.sh @@ -73,7 +73,7 @@ echo "" if [ -n "$SKIP_PROMPTS" ]; then install_mode=1 else - echo "How would you like to install the required services (Jackett & qBittorrent)?" + echo "How would you like to install the required services (Jackett/Prowlarr & qBittorrent)?" echo " [1] Docker (Recommended) - Uses standard docker-compose, isolates dependencies." echo " [2] Podman - Daemonless, rootless containers for lower memory overhead." echo " [3] Native - Installs directly to your OS (/opt/Jackett & /usr/bin/qbittorrent). Highest performance but clutters OS." @@ -82,6 +82,19 @@ else echo "" fi +if [ -n "$SKIP_PROMPTS" ]; then + indexer_mode=3 +else + echo "Which indexer manager would you like to use?" + echo " [1] Jackett (Default) - Stable, battle-tested." + echo " [2] Prowlarr (BETA) - Modern UI, becoming the standard." + echo " [3] Both - Run both Jackett and Prowlarr simultaneously." + read -r -p "Choose your indexer manager (1/2/3, default 1): " indexer_mode + indexer_mode=${indexer_mode:-1} + echo "" +fi + + check_docker() { if ! command -v docker &> /dev/null; then echo "[-] Error: Docker is not installed or not in your PATH." @@ -205,6 +218,20 @@ check_podman() { install_native() { echo "--- Native Installation ---" + + if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then + echo -e " +[WARNING] Prowlarr integration is currently in BETA." + echo -e "Installing Prowlarr natively involves complex .NET dependencies that might clutter your system." + echo -e "It is HIGHLY RECOMMENDED to use Docker (Option 1) or Podman (Option 2) for Prowlarr instead. +" + read -r -p "Are you sure you want to continue with Native Installation? [y/N]: " confirm_native + confirm_native=${confirm_native:-N} + if [[ ! "$confirm_native" =~ ^[Yy]$ ]]; then + echo "Aborting native installation. Please run the script again and select Docker." + exit 1 + fi + fi if [ "$(uname)" == "Darwin" ]; then echo -e "\n\033[31m[ERROR] Native mode on macOS is blocked.\033[0m" echo "i aint messing with yall system" @@ -253,6 +280,7 @@ install_native() { echo "[OK] qBittorrent-nox is installed." fi + if [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; then if [ ! -d "/opt/Jackett" ]; then echo "Installing Jackett to /opt/Jackett..." cd /opt @@ -264,8 +292,42 @@ install_native() { else echo "Jackett already installed at /opt/Jackett" fi + fi + - echo "Native installation completed! Ensure services are running using systemctl." + if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then + if [ ! -d "/opt/Prowlarr" ]; then + echo "Installing Prowlarr to /opt/Prowlarr..." + cd /opt + wget -O - -o /dev/null https://github.com/Prowlarr/Prowlarr/releases/latest/download/Prowlarr.master.linux-core-x64.tar.gz | sudo tar -xz + sudo chown "$(whoami)":"$(id -g)" -R "/opt/Prowlarr" + + # Create a simple systemd service for Prowlarr + cat << SVC | sudo tee /etc/systemd/system/prowlarr.service > /dev/null +[Unit] +Description=Prowlarr Daemon +After=network.target + +[Service] +User=$(whoami) +Group=$(id -g) +Type=simple +ExecStart=/opt/Prowlarr/Prowlarr -nobrowser +TimeoutStopSec=20 +KillMode=process +Restart=on-failure + +[Install] +WantedBy=multi-user.target +SVC + sudo systemctl daemon-reload + sudo systemctl enable --now prowlarr + cd - + else + echo "Prowlarr already installed at /opt/Prowlarr" + fi + fi +echo "Native installation completed! Ensure services are running using systemctl." exit 0 } @@ -280,10 +342,33 @@ fi echo "[OK] Container engine and compose are functional." -mkdir -p "$HELM_STATE/jackett" "$HELM_STATE/qbittorrent" "$HELM_STATE/gluetun" "$HELM_DL" +mkdir -p "$HELM_STATE/jackett" "$HELM_STATE/prowlarr" "$HELM_STATE/qbittorrent" "$HELM_STATE/gluetun" "$HELM_DL" mkdir -p "$HELM_CONFIG" touch "$HELM_CONFIG/config.json" +# Record the chosen indexer manager so the CLI knows which backend to query. +if [ "$indexer_mode" == "2" ]; then + INDEXER_MANAGER="prowlarr" +elif [ "$indexer_mode" == "3" ]; then + INDEXER_MANAGER="both" +else + INDEXER_MANAGER="jackett" +fi +python3 - "$HELM_CONFIG/config.json" "$INDEXER_MANAGER" <<'PY' || true +import json +import sys + +path, manager = sys.argv[1], sys.argv[2] +try: + with open(path) as f: + data = json.load(f) +except (OSError, json.JSONDecodeError): + data = {} +data["INDEXER_MANAGER"] = manager +with open(path, "w") as f: + json.dump(data, f, indent=4) +PY + echo "" if [ -n "$SKIP_PROMPTS" ]; then run_mode=2 @@ -298,10 +383,16 @@ fi if [ -n "$SKIP_PROMPTS" ]; then JACKETT_API="" + PROWLARR_API="" qb_user="admin" use_vpn="n" else - read -r -p "Enter Jackett API Key (press Enter to auto-extract later): " JACKETT_API + if [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; then + read -r -p "Enter Jackett API Key (press Enter to auto-extract later): " JACKETT_API + fi + if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then + read -r -p "Enter Prowlarr API Key (press Enter to auto-extract later): " PROWLARR_API + fi read -r -p "Enter qBittorrent Username (default: admin): " qb_user qb_user=${qb_user:-admin} @@ -312,6 +403,10 @@ fi # Write docker-compose.yml cat << 'EOF' > docker-compose.yml services: +EOF + +if [[ ( "$indexer_mode" == "1" || "$indexer_mode" == "3" ) && -z "$EXTERNAL_JACKETT_API" ]]; then +cat << 'EOF' >> docker-compose.yml jackett: container_name: "${COMPOSE_PROJECT_NAME:-helm}-jackett" image: lscr.io/linuxserver/jackett:latest @@ -339,7 +434,41 @@ services: ports: - 19117:9117 restart: unless-stopped +EOF +fi +if [[ ( "$indexer_mode" == "2" || "$indexer_mode" == "3" ) && -z "$EXTERNAL_PROWLARR_API" ]]; then +cat << 'EOF' >> docker-compose.yml + prowlarr: + container_name: "${COMPOSE_PROJECT_NAME:-helm}-prowlarr" + image: lscr.io/linuxserver/prowlarr:latest + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + labels: + - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" + - "com.docker.compose.service=prowlarr" + - "com.docker.compose.oneoff=False" + dns: + - 8.8.8.8 + - 1.1.1.1 + environment: + - PUID=1000 + - PGID=1000 + - TZ=Etc/UTC + security_opt: + - label=disable + volumes: + - "$HELM_STATE"/prowlarr:/config + ports: + - 19696:9696 + restart: unless-stopped +EOF +fi + +cat << 'EOF' >> docker-compose.yml flaresolverr: container_name: "${COMPOSE_PROJECT_NAME:-helm}-flaresolverr" image: ghcr.io/flaresolverr/flaresolverr:latest @@ -364,8 +493,10 @@ services: - 18191:8191 restart: unless-stopped - mini-helm: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-mini-helm" + cli: + container_name: "${COMPOSE_PROJECT_NAME:-helm}-cli" + extra_hosts: + - "host.docker.internal:host-gateway" image: ghcr.io/piratebird/helm:latest dns: - 8.8.8.8 @@ -546,8 +677,10 @@ sed -i "s|\"\$HELM_DL\"|$HELM_DL|g" docker-compose.yml cat << EOF > "$HELM_STATE"/.env.docker # --- Helm Container Isolated Configuration --- -JACKETT_URL=http://jackett:9117 +JACKETT_URL=http://${EXTERNAL_JACKETT_PORT:+host.docker.internal:$EXTERNAL_JACKETT_PORT}${EXTERNAL_JACKETT_PORT:-jackett:9117} JACKETT_API_KEY=\${JACKETT_API:-placeholder} +PROWLARR_URL=http://${EXTERNAL_PROWLARR_PORT:+host.docker.internal:$EXTERNAL_PROWLARR_PORT}${EXTERNAL_PROWLARR_PORT:-prowlarr:9696} +PROWLARR_API_KEY=\${PROWLARR_API:-placeholder} QB_WEBUI=http://qbittorrent:18080 QB_USERNAME=$qb_user QB_PASSWORD=adminadmin @@ -565,8 +698,59 @@ $vpn_extra EOF fi + +# Orchestrate existing containers +detect_existing_indexer() { + local indexer_name=$1 + local existing_container + local bound_port + local ext_api + existing_container=$($DOCKER_CMD ps --format '{{.Names}}' | grep -i "$indexer_name" | grep -v "helm-$indexer_name" | head -n 1 || true) + if [ -n "$existing_container" ]; then + echo "[+] Found existing external $indexer_name container: $existing_container" + # Try to extract the port it's bound to + bound_port=$($DOCKER_CMD port "$existing_container" | head -n 1 | awk -F':' '{print $NF}') + if [ -z "$bound_port" ]; then + if [ "$indexer_name" == "prowlarr" ]; then bound_port="9696"; else bound_port="9117"; fi + fi + + # Try to extract API key + ext_api="" + if [ "$indexer_name" == "prowlarr" ]; then + ext_api=$($DOCKER_CMD exec "$existing_container" grep -oP '(?<=)[^<]+' /config/config.xml 2>/dev/null || true) + elif [ "$indexer_name" == "jackett" ]; then + ext_api=$($DOCKER_CMD exec "$existing_container" grep -o '"APIKey": "[^"]*"' /config/Jackett/ServerConfig.json 2>/dev/null | cut -d'"' -f4 || true) + fi + + if [ -n "$ext_api" ]; then + echo "[+] Successfully extracted API key from external $indexer_name!" + if [ "$indexer_name" == "prowlarr" ]; then + EXTERNAL_PROWLARR_PORT="$bound_port" + EXTERNAL_PROWLARR_API="$ext_api" + else + EXTERNAL_JACKETT_PORT="$bound_port" + EXTERNAL_JACKETT_API="$ext_api" + fi + return 0 + fi + fi + return 1 +} + +EXTERNAL_PROWLARR_PORT="" +EXTERNAL_PROWLARR_API="" +EXTERNAL_JACKETT_PORT="" +EXTERNAL_JACKETT_API="" + +if [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; then + detect_existing_indexer "jackett" || true +fi +if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then + detect_existing_indexer "prowlarr" || true +fi + echo "Pulling the latest helm image..." -$COMPOSE_CMD --profile cli pull mini-helm +$COMPOSE_CMD --profile cli pull cli run_compose() { if [ "$DOCKER_CMD" == "podman" ]; then @@ -605,7 +789,16 @@ EOF echo "" echo "Starting containers in the background to initialize configurations..." -run_compose up -d --remove-orphans jackett qbittorrent flaresolverr + +SERVICES_TO_START=(qbittorrent flaresolverr) +if [[ ( "$indexer_mode" == "1" || "$indexer_mode" == "3" ) && -z "$EXTERNAL_JACKETT_API" ]]; then + SERVICES_TO_START+=("jackett") +fi +if [[ ( "$indexer_mode" == "2" || "$indexer_mode" == "3" ) && -z "$EXTERNAL_PROWLARR_API" ]]; then + SERVICES_TO_START+=("prowlarr") +fi + +run_compose up -d --remove-orphans "${SERVICES_TO_START[@]}" echo "[INFO] Waiting for services to initialize..." @@ -613,7 +806,13 @@ TIMEOUT=45 ELAPSED=0 while [ "$ELAPSED" -lt "$TIMEOUT" ]; do - CRITICAL_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-jackett" | head -n 1 || true) + if [ "$indexer_mode" == "2" ]; then + CRITICAL_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-prowlarr" | head -n 1 || true) + CRITICAL_NAME="prowlarr" + else + CRITICAL_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-jackett" | head -n 1 || true) + CRITICAL_NAME="jackett" + fi if [ -n "$CRITICAL_CONTAINER" ]; then IS_RUNNING=$($DOCKER_CMD inspect -f '{{.State.Running}}' "$CRITICAL_CONTAINER" 2>/dev/null || true) @@ -625,8 +824,8 @@ while [ "$ELAPSED" -lt "$TIMEOUT" ]; do IS_EXITED=$($DOCKER_CMD inspect -f '{{.State.Status}}' "$CRITICAL_CONTAINER" 2>/dev/null || true) if [ "$IS_EXITED" == "exited" ]; then - echo "[ERROR] Container jackett started but crashed immediately." - echo "Resolution: Run 'run_compose logs jackett' to inspect the failure." + echo "[ERROR] Container $CRITICAL_NAME started but crashed immediately." + echo "Resolution: Run 'run_compose logs $CRITICAL_NAME' to inspect the failure." exit 1 fi fi @@ -643,36 +842,64 @@ fi JACKETT_CONTAINER="" -if [ -z "$JACKETT_API" ]; then - for _ in {1..15}; do - JACKETT_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-jackett" | head -n 1 || true) - if [ -n "$JACKETT_CONTAINER" ]; then - extracted_api=$($DOCKER_CMD exec "$JACKETT_CONTAINER" cat /config/Jackett/ServerConfig.json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('APIKey',''))" 2>/dev/null || true) - if [ ! -z "$extracted_api" ]; then - JACKETT_API="$extracted_api" - echo "[+] Successfully grabbed Jackett API Key." - - $DOCKER_CMD exec "$JACKETT_CONTAINER" sed -i 's|"FlareSolverrUrl":.*|"FlareSolverrUrl": "http://flaresolverr:8191",|' /config/Jackett/ServerConfig.json 2>/dev/null || true - run_compose restart jackett - echo "[+] Jackett configured with FlareSolverr." - break +if [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; then + if [ -n "$EXTERNAL_JACKETT_API" ]; then JACKETT_API="$EXTERNAL_JACKETT_API"; fi + if [ -z "$JACKETT_API" ]; then + for _ in {1..15}; do + JACKETT_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-jackett" | head -n 1 || true) + if [ -n "$JACKETT_CONTAINER" ]; then + extracted_api=$($DOCKER_CMD exec "$JACKETT_CONTAINER" cat /config/Jackett/ServerConfig.json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('APIKey',''))" 2>/dev/null || true) + if [ ! -z "$extracted_api" ]; then + JACKETT_API="$extracted_api" + echo "[+] Successfully grabbed Jackett API Key." + + $DOCKER_CMD exec "$JACKETT_CONTAINER" sed -i 's|"FlareSolverrUrl":.*|"FlareSolverrUrl": "http://flaresolverr:8191",|' /config/Jackett/ServerConfig.json 2>/dev/null || true + run_compose restart jackett + echo "[+] Jackett configured with FlareSolverr." + break + fi fi + sleep 3 + done + + if [ -z "$JACKETT_API" ]; then + echo "[-] Could not find APIKey in Jackett configuration. Using placeholder." + JACKETT_API="your_jackett_api_key_here" fi - sleep 3 - done - - if [ -z "$JACKETT_API" ]; then - echo "[-] Could not find APIKey in Jackett configuration. Using placeholder." - JACKETT_API="your_jackett_api_key_here" fi + # Re-write .env.docker with the true JACKETT_API_KEY + sed -i "s|JACKETT_API_KEY=.*|JACKETT_API_KEY=$JACKETT_API|" "$HELM_STATE"/.env.docker fi -# Re-write .env.docker with the true JACKETT_API_KEY -sed -i "s|JACKETT_API_KEY=.*|JACKETT_API_KEY=$JACKETT_API|" "$HELM_STATE"/.env.docker +if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then + if [ -n "$EXTERNAL_PROWLARR_API" ]; then PROWLARR_API="$EXTERNAL_PROWLARR_API"; fi + if [ -z "$PROWLARR_API" ]; then + for _ in {1..15}; do + PROWLARR_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-prowlarr" | head -n 1 || true) + if [ -n "$PROWLARR_CONTAINER" ]; then + extracted_api=$($DOCKER_CMD exec "$PROWLARR_CONTAINER" grep -oP '(?<=)[^<]+' /config/config.xml 2>/dev/null || true) + if [ ! -z "$extracted_api" ]; then + PROWLARR_API="$extracted_api" + echo "[+] Successfully grabbed Prowlarr API Key." + break + fi + fi + sleep 3 + done + + if [ -z "$PROWLARR_API" ]; then + echo "[-] Could not find APIKey in Prowlarr configuration. Using placeholder." + PROWLARR_API="your_prowlarr_api_key_here" + fi + fi + # Re-write .env.docker with the true PROWLARR_API_KEY + sed -i "s|PROWLARR_API_KEY=.*|PROWLARR_API_KEY=$PROWLARR_API|" "$HELM_STATE"/.env.docker +fi echo "" echo "Setup is 100% complete! Everything is configured." -echo "Your native .env and config.json were left completely untouched." +echo "Your native .env and config.json secrets were left completely untouched." +echo "helm's own config.json gained an INDEXER_MANAGER setting only." echo "---" echo "Security Summary & Data Locations:" echo " - Settings: ~/.config/helm/" @@ -687,25 +914,30 @@ if [ "$run_mode" == "2" ]; then if [ "$DOCKER_CMD" == "podman" ]; then # Use podman stop directly - avoids docker compose's network namespace destruction # which triggers the "rootless netns: kill network process: permission denied" bug - podman stop "${COMPOSE_PROJECT_NAME:-helm}"-jackett "${COMPOSE_PROJECT_NAME:-helm}"-qbittorrent "${COMPOSE_PROJECT_NAME:-helm}"-flaresolverr "${COMPOSE_PROJECT_NAME:-helm}"-gluetun 2>/dev/null || true + podman stop "${COMPOSE_PROJECT_NAME:-helm}"-prowlarr "${COMPOSE_PROJECT_NAME:-helm}"-jackett "${COMPOSE_PROJECT_NAME:-helm}"-qbittorrent "${COMPOSE_PROJECT_NAME:-helm}"-flaresolverr "${COMPOSE_PROJECT_NAME:-helm}"-gluetun 2>/dev/null || true else run_compose stop || true fi echo "Generating helm launcher script..." cat << EOF > helm.sh #!/usr/bin/env bash +ARGS="\$@" +if [[ "\$*" != *"--oneshot"* ]] && [[ "\$*" != *"-o"* ]]; then + ARGS="--oneshot \$@" +fi + if [ "$DOCKER_CMD" == "podman" ]; then NETWORK="${COMPOSE_PROJECT_NAME:-helm}_default" - podman run -it --rm --entrypoint="" --security-opt label=disable --network "\$NETWORK" -v "\$PWD:/app" -v "$PODMAN_SOCK:/var/run/docker.sock" --env-file "$HELM_STATE"/.env.docker mini-helm python -m helm.cli "\$@" 2> >(grep -v "rootless netns" >&2) + podman run -it --rm --entrypoint="" --security-opt label=disable --network "\$NETWORK" -v "\$PWD:/app" -v "$PODMAN_SOCK:/var/run/docker.sock" --env-file "$HELM_STATE"/.env.docker mini-helm python -m helm.cli \$ARGS 2> >(grep -v "rootless netns" >&2) else - $COMPOSE_CMD --profile cli run --rm mini-helm "\$@" + $COMPOSE_CMD --profile cli run --rm cli \$ARGS fi EOF chmod +x helm.sh echo "Containers stopped. Helm will spin them up automatically when you trigger a download." echo "" - echo "To start using the app in its isolated mini container, run:" + echo "To start using the app in its isolated CLI container, run:" echo " ./helm.sh --oneshot" echo "===========================================" else @@ -739,7 +971,7 @@ EOF echo "Systemd service 'helm-app.service' created and enabled." fi echo "" - echo "To start using the app in its isolated mini container, run:" - echo " $COMPOSE_CMD --profile cli run --rm mini-helm" + echo "To start using the app in its isolated CLI container, run:" + echo " $COMPOSE_CMD --profile cli run --rm cli" echo "===========================================" fi diff --git a/src/helm/cli.py b/src/helm/cli.py index bb54b71..5514082 100644 --- a/src/helm/cli.py +++ b/src/helm/cli.py @@ -2,6 +2,8 @@ import json import os import re +import shutil +import subprocess import sys import time @@ -40,6 +42,44 @@ def _send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent download_magnet(selected.link) +def _cmd_status(): + """Print running helm containers and the configured Web UI URLs (never prompts).""" + print("Checking container status and Web UIs...") + cmd_runner = "docker" if shutil.which("docker") else "podman" if shutil.which("podman") else None + res = None + if cmd_runner: + cmd = [cmd_runner, "ps", "--format", "{{.Names}}: {{.Status}}"] + try: + res = subprocess.run(cmd, check=True, capture_output=True, text=True) + except Exception: + print(f"Failed to run {cmd_runner} ps.") + else: + print("Native Mode - No containers running.") + + if res is not None: + print("-" * 40) + helm_containers = [line for line in res.stdout.splitlines() if "helm" in line.lower()] + print("\n".join(helm_containers) if helm_containers else "No helm containers found.") + print("-" * 40) + + cfg = load_config() + container_text = (res.stdout or "").lower() if res else "" + print("\n--- Web UIs ---") + if container_text and "jackett" not in container_text: + print("Jackett: not running") + else: + print(f"Jackett: {cfg.get('JACKETT_URL') or 'http://localhost:19117'}") + if container_text and "prowlarr" not in container_text: + print("Prowlarr: not running") + else: + print(f"Prowlarr: {cfg.get('PROWLARR_URL') or 'http://localhost:19696'}") + if container_text and "qbittorrent" not in container_text: + print("qBittorrent: not running") + else: + print(f"qBittorrent: {cfg.get('QB_WEBUI') or 'http://localhost:18080'}") + print("---------------") + + def main(): base_parser = argparse.ArgumentParser(add_help=False) global_opts = base_parser.add_argument_group("Global Options") @@ -47,6 +87,7 @@ def main(): "--config-dir", type=str, default=argparse.SUPPRESS, help="Override the configuration directory" ) global_opts.add_argument("--state-dir", type=str, default=argparse.SUPPRESS, help="Override the state directory") + global_opts.add_argument("--status", action="store_true", help="List running containers and their Web UI URLs") global_opts.add_argument("--dl-dir", type=str, default=argparse.SUPPRESS, help="Override the downloads directory") global_opts.add_argument( "-o", @@ -96,9 +137,12 @@ def main(): ) # Indexers - subparsers.add_parser("indexers", help="Manage Jackett indexers interactively", parents=[base_parser]) + idx_parser = subparsers.add_parser("indexers", help="Manage Indexers interactively", parents=[base_parser]) + idx_parser.add_argument("--prowlarr", action="store_true", help="Manage Prowlarr indexers explicitly") + idx_parser.add_argument("--jackett", action="store_true", help="Manage Jackett indexers explicitly") # Utility Commands + subparsers.add_parser("status", help="List running containers and their Web UI URLs", parents=[base_parser]) subparsers.add_parser("logs", help="Tail the last 20 lines of the application log", parents=[base_parser]) subparsers.add_parser( "paths", help="Print all system data locations (Config, State, Downloads)", parents=[base_parser] @@ -108,7 +152,9 @@ def main(): ) # Parse arguments - args = parser.parse_args() + args, unknown = parser.parse_known_args() + if getattr(args, "status", False): + args.command = "status" if not args.command: args.command = "ui" @@ -139,6 +185,13 @@ def main(): get_logger("") # Initialize root logger after directory overrides + if args.command == "status": + # Container status is a read-only query: it must never spin up the + # ephemeral stack, prompt for config, or require an API key. Reap it + # as early as possible so agents can call it non-interactively. + _cmd_status() + return + if args.command == "init": from helm.core.init_env import bootstrap_env @@ -146,7 +199,7 @@ def main(): bootstrap_env() except (KeyboardInterrupt, EOFError): print(f"\n{C_SUB}later bozo!{C_RST}") - os._exit(0) + raise SystemExit(0) from None if args.command == "paths": from helm.core.config_manager import get_config_dir, get_dl_dir, get_log_dir @@ -155,7 +208,7 @@ def main(): print(f" Configuration: {get_config_dir()}") print(f" State/Logs: {get_log_dir()}") print(f" Downloads: {get_dl_dir()}") - os._exit(0) + raise SystemExit(0) from None if args.command == "logs": from helm.core.config_manager import get_log_dir @@ -173,7 +226,7 @@ def main(): print(f"Could not read log file: {e}") else: print("Log file does not exist yet.") - os._exit(0) + raise SystemExit(0) from None if args.command == "bug-report": import zipfile @@ -201,13 +254,18 @@ def main(): zipf.write(log_file, arcname="helm.log") print(f"Bug report successfully created at: {zip_path}") print("Please attach this zip file when creating an issue on GitHub.") - os._exit(0) + raise SystemExit(0) from None if not args.lite: config = load_config() if config.get("LITE_MODE_ONLY"): args.lite = True - elif not os.getenv("JACKETT_API_KEY") and not get_secret("JACKETT_API_KEY"): + elif ( + not os.getenv("JACKETT_API_KEY") + and not get_secret("JACKETT_API_KEY") + and not os.getenv("PROWLARR_API_KEY") + and not get_secret("PROWLARR_API_KEY") + ): if args.json: # Machine-readable output must never interleave prompts; fall # back to Lite Mode silently instead of asking the user. @@ -235,7 +293,7 @@ def main(): ensure_config() except (KeyboardInterrupt, EOFError): print(f"\n{C_SUB}later bozo!{C_RST}") - os._exit(0) + raise SystemExit(0) from None else: ensure_config() @@ -247,22 +305,42 @@ def main(): except KeyboardInterrupt: print(f"\n{C_SUB}later bozo!{C_RST}") teardown_oneshot() - os._exit(0) + raise SystemExit(0) from None if args.command == "indexers": if args.lite: - print(f"{C_ERR}Cannot manage Jackett indexers in Lite Mode.{C_RST}", file=sys.stderr) - os._exit(1) + print(f"{C_ERR}Cannot manage Indexers in Lite Mode.{C_RST}", file=sys.stderr) + raise SystemExit(1) from None ensure_config() - from helm.core.indexer_manager import JackettManager + + config = load_config() + + use_prowlarr = getattr(args, "prowlarr", False) + use_jackett = getattr(args, "jackett", False) + + if not use_prowlarr and not use_jackett: + manager_type = config.get("INDEXER_MANAGER", "jackett") + elif use_prowlarr: + manager_type = "prowlarr" + else: + manager_type = "jackett" try: - manager = JackettManager() + if manager_type == "prowlarr": + from helm.core.indexer_manager import ProwlarrManager + + manager = ProwlarrManager() + mgr_name = "Prowlarr" + else: + from helm.core.indexer_manager import JackettManager + + manager = JackettManager() + mgr_name = "Jackett" except Exception as e: - print(f"{C_ERR}Failed to initialize Jackett Manager: {e}{C_RST}", file=sys.stderr) - os._exit(1) + print(f"{C_ERR}Failed to initialize Manager: {e}{C_RST}", file=sys.stderr) + raise SystemExit(1) from None - sys.stdout.write(f"{C_LOGO}Fetching indexers from Jackett...{C_RST}\r\n") + sys.stdout.write(f"{C_LOGO}Fetching indexers from {mgr_name}...{C_RST}\r\n") sys.stdout.flush() all_indexers = manager.get_all_indexers() @@ -312,14 +390,14 @@ def main(): from helm.core.oneshot import teardown_oneshot teardown_oneshot() - os._exit(0) + raise SystemExit(0) from None except (KeyboardInterrupt, EOFError): print(f"\n{C_SUB}later bozo!{C_RST}") if args.oneshot: from helm.core.oneshot import teardown_oneshot teardown_oneshot() - os._exit(0) + raise SystemExit(0) from None mode_str = " (ONE-SHOT MODE)" if args.oneshot else "" @@ -346,7 +424,7 @@ def main(): print(f"\n{C_SUB}later bozo!{C_RST}") if args.oneshot: teardown_oneshot() - os._exit(0) + raise SystemExit(0) from None if not search_query: continue @@ -361,7 +439,7 @@ def main(): print(f"\n{C_SUB}later bozo!{C_RST}") if args.oneshot: teardown_oneshot() - os._exit(0) + raise SystemExit(0) from None if selected_cats == "BACK": # Go back to query prompt by staying in PROMPT @@ -402,7 +480,7 @@ def main(): print(f"\n{C_SUB}later bozo!{C_RST}") if args.oneshot: teardown_oneshot() - os._exit(0) + raise SystemExit(0) from None source_name = "Lite mode" if args.lite else "Jackett & Lite" if not args.json: @@ -417,21 +495,21 @@ def main(): if not filtered: if args.json: print(json.dumps([])) + if args.oneshot: + teardown_oneshot() + raise SystemExit(1) from None else: print(f"\n{C_ERR}No torrents were found :({C_RST}", file=sys.stderr) # If we have arguments, we exit. Else we go back to prompt. if args.query: if args.oneshot: teardown_oneshot() - os._exit(1) + raise SystemExit(1) from None else: input("Press Enter to try again...") print("\033[2J\033[H", end="") state = "PROMPT" continue - if args.oneshot: - teardown_oneshot() - os._exit(1) if args.json: from helm.core.secret_manager import sanitize_link @@ -446,9 +524,10 @@ def main(): for t in filtered ] print(json.dumps(json_output, indent=2)) + sys.stdout.flush() if args.oneshot: teardown_oneshot() - os._exit(0) + raise SystemExit(0) from None if args.auto: selected = filtered[0] @@ -456,7 +535,7 @@ def main(): if args.oneshot and not args.lite: wait_for_download() teardown_oneshot() - os._exit(0) + raise SystemExit(0) from None state = "RESULTS" @@ -472,7 +551,7 @@ def main(): print("\033[2J\033[H", end="") if args.query: # Cannot go back if started from CLI args - os._exit(0) + raise SystemExit(0) from None state = "PROMPT" continue @@ -490,8 +569,33 @@ def main(): teardown_oneshot() except Exception: pass - os._exit(0) + raise SystemExit(0) from None if __name__ == "__main__": - main() + try: + main() + except KeyboardInterrupt: + import sys + + print("\n\033[33m[!] Process interrupted by user.\033[0m", file=sys.stderr) + if "-o" in sys.argv or "--oneshot" in sys.argv: + try: + from helm.core.oneshot import teardown_oneshot + + teardown_oneshot() + except Exception: + pass + sys.exit(130) + except Exception as e: + import sys + + print(f"\n\033[31m[!] An unexpected error occurred: {e}\033[0m", file=sys.stderr) + if "-o" in sys.argv or "--oneshot" in sys.argv: + try: + from helm.core.oneshot import teardown_oneshot + + teardown_oneshot() + except Exception: + pass + sys.exit(1) diff --git a/src/helm/core/config_manager.py b/src/helm/core/config_manager.py index 14eba25..4bb175c 100644 --- a/src/helm/core/config_manager.py +++ b/src/helm/core/config_manager.py @@ -20,6 +20,7 @@ [ "JACKETT_API_KEY", "JACKETT_PASSWORD", + "PROWLARR_API_KEY", "QB_PASSWORD", ] ) diff --git a/src/helm/core/config_wizard.py b/src/helm/core/config_wizard.py index c514e9c..6ef3e8a 100644 --- a/src/helm/core/config_wizard.py +++ b/src/helm/core/config_wizard.py @@ -18,10 +18,12 @@ def run_wizard(): print("You can run Helm in two modes:") print(" 1. Lite Mode (Native plugins only, no media server required)") - print(" 2. Full Automation (Requires Jackett & qBittorrent running)") + print(" 2. Full Automation (Requires Jackett/Prowlarr & qBittorrent running)") choice = ( - input("\nDo you want to configure Jackett and qBittorrent for full automation? (y/N): ").strip().lower() + input("\nDo you want to configure an Indexer Manager and qBittorrent for full automation? (y/N): ") + .strip() + .lower() ) if choice not in ("y", "yes"): print("\n\033[32mOpting for Lite Mode. You can change this later.\033[0m\n") @@ -31,71 +33,114 @@ def run_wizard(): config["LITE_MODE_ONLY"] = False - # Jackett - jackett_url = config.get("JACKETT_URL", os.getenv("JACKETT_URL", "http://localhost:9117")) - jackett_api = get_secret("JACKETT_API_KEY") or "" - jackett_pwd = get_secret("JACKETT_PASSWORD") or "" - - while True: - jackett_url_input = input(f"Jackett URL [{jackett_url}]: ").strip() - if jackett_url_input.lower() in ("exit", "quit", "q") or "\x03" in jackett_url_input: - print("\n\033[33mConfiguration aborted. later bozo!\033[0m") - sys.exit(0) - if jackett_url_input: - jackett_url = jackett_url_input - - # Obscure the API key if it exists - masked_api = ( - f"{jackett_api[:4]}...{jackett_api[-4:]}" if len(jackett_api) > 8 else "***" if jackett_api else "" - ) - jackett_api_input = input(f"Jackett API Key [{masked_api}]: ").strip() - if jackett_api_input.lower() in ("exit", "quit", "q") or "\x03" in jackett_api_input: - print("\n\033[33mConfiguration aborted. later bozo!\033[0m") - sys.exit(0) - if jackett_api_input: - jackett_api = jackett_api_input - - jackett_pwd_input = input( - f"Jackett Admin Password (leave blank if none) [{'***' if jackett_pwd else ''}]: " - ).strip() - if jackett_pwd_input.lower() in ("exit", "quit", "q") or "\x03" in jackett_pwd_input: - print("\n\033[33mConfiguration aborted. later bozo!\033[0m") - sys.exit(0) - if jackett_pwd_input: - jackett_pwd = jackett_pwd_input - # To allow clearing the password if one was set, we could allow a special string, but for now we just take the input if truthy or keep it if they just pressed enter. - - if jackett_api: - # Validate Jackett - print("Validating Jackett connection...") - try: - r = requests.get( - f"{jackett_url}/api/v2.0/indexers/all/results/torznab/api?apikey={jackett_api}&t=indexers", - timeout=5, - ) - if r.status_code == 200: - # Also test if password works for UI APIs - session = requests.Session() - r_auth = session.post(f"{jackett_url}/UI/Dashboard", data={"password": jackett_pwd}) - if r_auth.status_code in (200, 302): - # Try to fetch a config schema to ensure auth worked (or it returns HTML) - r_conf = session.get(f"{jackett_url}/api/v2.0/indexers/3dtorrents/config") - if r_conf.status_code == 200 and r_conf.text.startswith("["): - print("Jackett connection and authentication successful!\n") - break + indexer_choice = input("Which Indexer Manager are you using? [1] Jackett [2] Prowlarr (default 1): ").strip() + + if indexer_choice == "2": + # Prowlarr + prowlarr_url = config.get("PROWLARR_URL", os.getenv("PROWLARR_URL", "http://localhost:19696")) + prowlarr_api = get_secret("PROWLARR_API_KEY") or "" + + while True: + prowlarr_url_input = input(f"Prowlarr URL [{prowlarr_url}]: ").strip() + if prowlarr_url_input.lower() in ("exit", "quit", "q") or "\x03" in prowlarr_url_input: + sys.exit(0) + if prowlarr_url_input: + prowlarr_url = prowlarr_url_input + + masked_api = ( + f"{prowlarr_api[:4]}...{prowlarr_api[-4:]}" + if len(prowlarr_api) > 8 + else "***" + if prowlarr_api + else "" + ) + prowlarr_api_input = input(f"Prowlarr API Key [{masked_api}]: ").strip() + if prowlarr_api_input.lower() in ("exit", "quit", "q") or "\x03" in prowlarr_api_input: + sys.exit(0) + if prowlarr_api_input: + prowlarr_api = prowlarr_api_input + + if prowlarr_api: + print("Validating Prowlarr connection...") + try: + r = requests.get( + f"{prowlarr_url}/api/v1/indexer", headers={"X-Api-Key": prowlarr_api}, timeout=5 + ) + if r.status_code == 200: + print("Prowlarr connection successful!\n") + break + else: + print(f"Prowlarr connection failed: HTTP {r.status_code}\n") + except Exception as e: + print(f"Prowlarr connection failed: {e}\n") + else: + print("Prowlarr API key is required.\n") + + config["PROWLARR_URL"] = prowlarr_url + set_secrets({"PROWLARR_API_KEY": prowlarr_api}) + config["INDEXER_MANAGER"] = "prowlarr" + else: + # Jackett + jackett_url = config.get("JACKETT_URL", os.getenv("JACKETT_URL", "http://localhost:9117")) + jackett_api = get_secret("JACKETT_API_KEY") or "" + jackett_pwd = get_secret("JACKETT_PASSWORD") or "" + + while True: + jackett_url_input = input(f"Jackett URL [{jackett_url}]: ").strip() + if jackett_url_input.lower() in ("exit", "quit", "q") or "\x03" in jackett_url_input: + print("\n\033[33mConfiguration aborted. later bozo!\033[0m") + sys.exit(0) + if jackett_url_input: + jackett_url = jackett_url_input + + masked_api = ( + f"{jackett_api[:4]}...{jackett_api[-4:]}" if len(jackett_api) > 8 else "***" if jackett_api else "" + ) + jackett_api_input = input(f"Jackett API Key [{masked_api}]: ").strip() + if jackett_api_input.lower() in ("exit", "quit", "q") or "\x03" in jackett_api_input: + print("\n\033[33mConfiguration aborted. later bozo!\033[0m") + sys.exit(0) + if jackett_api_input: + jackett_api = jackett_api_input + + jackett_pwd_input = input( + f"Jackett Admin Password (leave blank if none) [{'***' if jackett_pwd else ''}]: " + ).strip() + if jackett_pwd_input.lower() in ("exit", "quit", "q") or "\x03" in jackett_pwd_input: + print("\n\033[33mConfiguration aborted. later bozo!\033[0m") + sys.exit(0) + if jackett_pwd_input: + jackett_pwd = jackett_pwd_input + + if jackett_api: + print("Validating Jackett connection...") + try: + r = requests.get( + f"{jackett_url}/api/v2.0/indexers/all/results/torznab/api?apikey={jackett_api}&t=indexers", + timeout=5, + ) + if r.status_code == 200: + session = requests.Session() + r_auth = session.post(f"{jackett_url}/UI/Dashboard", data={"password": jackett_pwd}) + if r_auth.status_code in (200, 302): + r_conf = session.get(f"{jackett_url}/api/v2.0/indexers/3dtorrents/config") + if r_conf.status_code == 200 and r_conf.text.startswith("["): + print("Jackett connection and authentication successful!\n") + break + else: + print("Jackett API key works, but Admin Password appears to be incorrect.\n") else: - print("Jackett API key works, but Admin Password appears to be incorrect.\n") + print(f"Jackett auth failed: HTTP {r_auth.status_code}\n") else: - print(f"Jackett auth failed: HTTP {r_auth.status_code}\n") - else: - print(f"Jackett connection failed: HTTP {r.status_code}\n") - except Exception as e: - print(f"Jackett connection failed: {e}\n") - else: - print("Jackett API key is required.\n") - - config["JACKETT_URL"] = jackett_url - set_secrets({"JACKETT_API_KEY": jackett_api, "JACKETT_PASSWORD": jackett_pwd}) + print(f"Jackett connection failed: HTTP {r.status_code}\n") + except Exception as e: + print(f"Jackett connection failed: {e}\n") + else: + print("Jackett API key is required.\n") + + config["JACKETT_URL"] = jackett_url + set_secrets({"JACKETT_API_KEY": jackett_api, "JACKETT_PASSWORD": jackett_pwd}) + config["INDEXER_MANAGER"] = "jackett" # qBittorrent qb_webui = config.get("QB_WEBUI", os.getenv("QB_WEBUI", "http://localhost:18080")) diff --git a/src/helm/core/http.py b/src/helm/core/http.py new file mode 100644 index 0000000..4e888a1 --- /dev/null +++ b/src/helm/core/http.py @@ -0,0 +1,16 @@ +import requests + +_MAX_SOCKETS = 32 + +_session = requests.Session() +_adapter = requests.adapters.HTTPAdapter(pool_connections=_MAX_SOCKETS, pool_maxsize=_MAX_SOCKETS) +_session.mount("https://", _adapter) +_session.mount("http://", _adapter) + + +def get_shared_session() -> requests.Session: + """Return the process-wide session so keep-alive connections are reused across fetchers. + + The session is not used for cookies/auth, so sharing it across worker threads is safe. + """ + return _session diff --git a/src/helm/core/indexer_manager.py b/src/helm/core/indexer_manager.py index 34ed36b..f42ba58 100644 --- a/src/helm/core/indexer_manager.py +++ b/src/helm/core/indexer_manager.py @@ -3,8 +3,11 @@ import requests +from helm.core.logger import get_logger from helm.core.secret_manager import get_secret +logger = get_logger(__name__) + class JackettManager: def __init__(self): @@ -22,38 +25,187 @@ def _authenticate(self): self.session.post(auth_url, data={"password": self.password}) def get_all_indexers(self): - # Torznab API returns all indexers (configured and unconfigured) in XML endpoint = f"{self.url}/api/v2.0/indexers/all/results/torznab/api" - r = requests.get(endpoint, params={"apikey": self.api_key, "t": "indexers"}) + try: + r = requests.get(endpoint, params={"apikey": self.api_key, "t": "indexers"}, timeout=15) + r.raise_for_status() + root = ET.fromstring(r.content) + indexers = [] + for idx in root.findall("indexer"): + indexers.append( + { + "id": idx.get("id"), + "configured": idx.get("configured") == "true", + "title": idx.find("title").text if idx.find("title") is not None else idx.get("id"), + "type": idx.find("type").text if idx.find("type") is not None else "unknown", + } + ) + return indexers + except KeyboardInterrupt: + raise + except Exception as e: + logger.error("Failed to fetch Jackett indexers: %s", e, exc_info=True) + return [] + + def add_indexer(self, indexer_id): + config_url = f"{self.url}/api/v2.0/indexers/{indexer_id}/config" + try: + r = self.session.get(config_url, timeout=15) + r.raise_for_status() + config_payload = r.json() + r_post = self.session.post(config_url, json=config_payload, timeout=15) + r_post.raise_for_status() + return True + except KeyboardInterrupt: + raise + except Exception as e: + logger.error("Failed to add Jackett indexer: %s", e, exc_info=True) + return False + + def remove_indexer(self, indexer_id): + endpoint = f"{self.url}/api/v2.0/indexers/{indexer_id}" + try: + r = self.session.delete(endpoint, timeout=15) + r.raise_for_status() + return True + except KeyboardInterrupt: + raise + except Exception as e: + logger.error("Failed to remove Jackett indexer: %s", e, exc_info=True) + return False + + +class ProwlarrManager: + # Public trackers Helm enables by default when none are configured. + DEFAULT_SEED_NAMES = ("1337x", "yts", "torrentgalaxy", "nyaapantsu", "eztv") + + def __init__(self): + self.url = os.getenv("PROWLARR_URL", "http://localhost:19696") + self.api_key = get_secret("PROWLARR_API_KEY") + if not self.api_key: + raise RuntimeError("PROWLARR_API_KEY environment variable not set") + self.headers = {"X-Api-Key": self.api_key} + self._definitions = {} + + def _fetch(self, path, timeout=15): + r = requests.get(f"{self.url}{path}", headers=self.headers, timeout=timeout) r.raise_for_status() + return r.json() + + def get_all_indexers(self): + try: + definitions = self._fetch("/api/v1/indexer/schema", timeout=60) + active = self._fetch("/api/v1/indexer", timeout=60) + except Exception as e: + logger.error("Failed to connect to Prowlarr: %s", e, exc_info=True) + return [] + + # Index resources don't aggressively repeat schema keys, so key the + # active list by every identifier Prowlarr exposes and match a schema + # definition against each candidate in order of specificity. + active_map = {} + for idx in active: + for key in (idx.get("definitionName"), idx.get("implementation"), idx.get("name")): + if key: + active_map[key] = idx - root = ET.fromstring(r.content) indexers = [] - for idx in root.findall("indexer"): + for d in definitions: + name = d.get("name") + impl = d.get("implementation") + definition_name = d.get("definitionName") + + act = None + for key in (definition_name, impl, name): + if key and key in active_map: + act = active_map[key] + break + + if act: + is_configured = act.get("enable", False) + idx_id = str(act.get("id")) + else: + is_configured = False + # definitionName is unique per schema def (unlike implementation, + # where every Cardigann indexer shares the same implementation). + idx_id = str(definition_name) if definition_name else str(impl) if impl else str(name) + + self._definitions[idx_id] = d + indexers.append( { - "id": idx.get("id"), - "configured": idx.get("configured") == "true", - "title": idx.find("title").text if idx.find("title") is not None else idx.get("id"), - "type": idx.find("type").text if idx.find("type") is not None else "unknown", + "id": idx_id, + "configured": is_configured, + "title": name, + "type": d.get("privacy", "unknown").lower().replace("semiprivate", "semi-private"), } ) return indexers def add_indexer(self, indexer_id): - # 1. Fetch default config schema - config_url = f"{self.url}/api/v2.0/indexers/{indexer_id}/config" - r = self.session.get(config_url) - r.raise_for_status() - config_payload = r.json() + endpoint = f"{self.url}/api/v1/indexer/{indexer_id}" + try: + r = requests.get(endpoint, headers=self.headers, timeout=5) + if r.status_code == 200: + payload = r.json() + payload["enable"] = True + r_put = requests.put(endpoint, json=payload, headers=self.headers, timeout=5) + r_put.raise_for_status() + return True + except Exception as e: + logger.error("Failed to update Prowlarr indexer: %s", e, exc_info=True) + + if indexer_id in self._definitions: + payload = dict(self._definitions[indexer_id]) + payload["enable"] = True + r_post = requests.post(f"{self.url}/api/v1/indexer", json=payload, headers=self.headers, timeout=5) + r_post.raise_for_status() + return True - # 2. Submit the config back - r_post = self.session.post(config_url, json=config_payload) - r_post.raise_for_status() - return True + raise Exception(f"Indexer ID {indexer_id} not found in Prowlarr definitions.") def remove_indexer(self, indexer_id): - endpoint = f"{self.url}/api/v2.0/indexers/{indexer_id}" - r = self.session.delete(endpoint) - r.raise_for_status() - return True + endpoint = f"{self.url}/api/v1/indexer/{indexer_id}" + try: + r = requests.get(endpoint, headers=self.headers, timeout=5) + if r.status_code == 200: + payload = r.json() + payload["enable"] = False + r_put = requests.put(endpoint, json=payload, headers=self.headers, timeout=5) + r_put.raise_for_status() + return True + except Exception as e: + logger.error("Failed to connect to Prowlarr: %s", e, exc_info=True) + return False + + def seed_default_indexers(self): + # Enable a small set of well-known public trackers if none are configured. + try: + definitions = self._fetch("/api/v1/indexer/schema", timeout=60) + active = self._fetch("/api/v1/indexer", timeout=60) + except Exception as e: + logger.error("Failed to fetch Prowlarr definitions: %s", e, exc_info=True) + return 0 + + active_names = set() + for idx in active: + for key in (idx.get("definitionName"), idx.get("implementation"), idx.get("name")): + if key: + active_names.add(key.lower()) + + enabled = 0 + for d in definitions: + name = d.get("name") or "" + key = d.get("definitionName") or d.get("implementation") or name + if key in active_names or name in active_names: + continue + if key.lower() in self.DEFAULT_SEED_NAMES or name.lower() in self.DEFAULT_SEED_NAMES: + payload = dict(d) + payload["enable"] = True + try: + r = requests.post(f"{self.url}/api/v1/indexer", json=payload, headers=self.headers, timeout=5) + r.raise_for_status() + enabled += 1 + except Exception as e: + logger.error("Failed to seed Prowlarr indexer '%s': %s", name, e, exc_info=True) + return enabled diff --git a/src/helm/core/init_env.py b/src/helm/core/init_env.py index 4c479e3..33aae3b 100644 --- a/src/helm/core/init_env.py +++ b/src/helm/core/init_env.py @@ -116,6 +116,35 @@ restart: unless-stopped """ +PROWLARR_BASE = """ + prowlarr: + container_name: "{project_name}-prowlarr" + image: lscr.io/linuxserver/prowlarr:latest + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + labels: + - "com.docker.compose.project={project_name}" + - "com.docker.compose.service=prowlarr" + - "com.docker.compose.oneoff=False" + dns: + - 8.8.8.8 + - 1.1.1.1 + environment: + - PUID=1000 + - PGID=1000 + - TZ=Etc/UTC + security_opt: + - label=disable + volumes: + - "{state_dir}/prowlarr:/config" + ports: + - 19696:9696 + restart: unless-stopped +""" + def bootstrap_env(): print("===========================================") @@ -167,6 +196,7 @@ def bootstrap_env(): vpn_extra = f"OPENVPN_USER={ovpn_user}\nOPENVPN_PASSWORD={ovpn_pass}" compose_yaml = DOCKER_COMPOSE_BASE.format(project_name=project_name, state_dir=state_dir, dl_dir=dl_dir) + compose_yaml += PROWLARR_BASE.format(project_name=project_name, state_dir=state_dir) if use_vpn == "y": compose_yaml += GLUETUN_BASE.format(project_name=project_name, state_dir=state_dir) @@ -194,6 +224,8 @@ def bootstrap_env(): env_docker_content = f"""# --- Helm Container Isolated Configuration --- JACKETT_URL=http://jackett:9117 JACKETT_API_KEY=placeholder +PROWLARR_URL=http://prowlarr:9696 +PROWLARR_API_KEY=placeholder QB_WEBUI=http://qbittorrent:18080 QB_USERNAME=admin QB_PASSWORD=adminadmin @@ -224,7 +256,8 @@ def bootstrap_env(): print("\nStarting containers to initialize Jackett...") subprocess.run( - compose_cmd + ["-f", compose_path, "up", "-d", "--remove-orphans", "jackett", "qbittorrent", "flaresolverr"], + compose_cmd + + ["-f", compose_path, "up", "-d", "--remove-orphans", "jackett", "prowlarr", "qbittorrent", "flaresolverr"], check=False, ) @@ -249,34 +282,67 @@ def bootstrap_env(): f.write(env_docker_content) print("[+] Successfully grabbed Jackett API Key.") - print("\n[INFO] Auto-configuring default Jackett indexers...") - # Override env vars temporarily so JackettManager targets the fresh container - os.environ["JACKETT_URL"] = "http://localhost:19117" - os.environ["JACKETT_API_KEY"] = jackett_api - os.environ["JACKETT_PASSWORD"] = "" + prowlarr_api = "" + try: + p_config = os.path.join(state_dir, "prowlarr", "config.xml") + if os.path.exists(p_config): + with open(p_config, "r") as f: + for line in f: + if "" in line: + prowlarr_api = line.split("")[1].split("")[0].strip() + break + except Exception: + pass + + if prowlarr_api: + env_docker_content = env_docker_content.replace( + "PROWLARR_API_KEY=placeholder", f"PROWLARR_API_KEY={prowlarr_api}" + ) + with open(os.path.join(state_dir, ".env.docker"), "w") as f: + f.write(env_docker_content) + print("[+] Successfully grabbed Prowlarr API Key.") + print("\n[INFO] Auto-configuring default Prowlarr indexers...") + os.environ["PROWLARR_URL"] = "http://localhost:19696" + os.environ["PROWLARR_API_KEY"] = prowlarr_api + if prowlarr_api: try: - from helm.core.indexer_manager import JackettManager - - manager = JackettManager() - - # The most reliable and widely used public trackers - DEFAULT_INDEXERS = ["1337x", "yts", "torrentgalaxy", "nyaasi", "eztv"] - all_indexers = manager.get_all_indexers() - - configured_count = 0 - for idx in all_indexers: - if idx["id"] in DEFAULT_INDEXERS and not idx["configured"]: - try: - manager.add_indexer(idx["id"]) - print(f" [+] Activated tracker: {idx['title']}") - configured_count += 1 - except Exception as e: - print(f" [-] Failed to activate {idx['title']}: {e}") - if configured_count == 0: - print(" [+] Default trackers are already active.") + from helm.core.indexer_manager import ProwlarrManager + + manager = ProwlarrManager() + enabled = manager.seed_default_indexers() + print(f" [+] Activated {enabled} default Prowlarr indexer(s).") except Exception as e: - print(f"[-] Could not auto-configure indexers: {e}") + print(f"[-] Could not auto-configure Prowlarr indexers: {e}") + + print("\n[INFO] Auto-configuring default Jackett indexers...") + # Override env vars temporarily so JackettManager targets the fresh container + os.environ["JACKETT_URL"] = "http://localhost:19117" + os.environ["JACKETT_API_KEY"] = jackett_api + os.environ["JACKETT_PASSWORD"] = "" + + try: + from helm.core.indexer_manager import JackettManager + + manager = JackettManager() + + # The most reliable and widely used public trackers + DEFAULT_INDEXERS = ["1337x", "yts", "torrentgalaxy", "nyaasi", "eztv"] + all_indexers = manager.get_all_indexers() + + configured_count = 0 + for idx in all_indexers: + if idx["id"] in DEFAULT_INDEXERS and not idx["configured"]: + try: + manager.add_indexer(idx["id"]) + print(f" [+] Activated tracker: {idx['title']}") + configured_count += 1 + except Exception as e: + print(f" [-] Failed to activate {idx['title']}: {e}") + if configured_count == 0: + print(" [+] Default trackers are already active.") + except Exception as e: + print(f"[-] Could not auto-configure indexers: {e}") if run_mode != "1": print("\nTearing down containers for Ephemeral (One-Shot) mode...") diff --git a/src/helm/core/lite_fetcher.py b/src/helm/core/lite_fetcher.py index caa55e6..1880989 100644 --- a/src/helm/core/lite_fetcher.py +++ b/src/helm/core/lite_fetcher.py @@ -1,28 +1,26 @@ +import asyncio +import concurrent.futures import datetime import os import xml.etree.ElementTree as ET from email.utils import parsedate_to_datetime - -import requests +from typing import List +from urllib.parse import quote from helm.core.config_manager import get_config_dir +from helm.core.http import get_shared_session from helm.core.logger import get_logger from helm.core.rss_fetcher import TorrentItem logger = get_logger(__name__) -def search_lite(query): - """ - Lite mode fetcher using public APIs (e.g., apibay) without needing Jackett. - """ +def _fetch_apibay(query: str) -> List[TorrentItem]: + """The Pirate Bay public API (apibay).""" items = [] - - # Apibay (The Pirate Bay API) - before = len(items) apibay_url = "https://apibay.org/q.php" try: - r = requests.get(apibay_url, params={"q": query}, timeout=15) + r = get_shared_session().get(apibay_url, params={"q": query}, timeout=15) r.raise_for_status() data = r.json() @@ -36,7 +34,7 @@ def search_lite(query): continue # Construct magnet link with popular public trackers - encoded_name = requests.utils.quote(title) + encoded_name = quote(title) magnet = ( f"magnet:?xt=urn:btih:{info_hash}" f"&dn={encoded_name}" @@ -75,13 +73,16 @@ def search_lite(query): except Exception as e: logger.debug(f"Event: Apibay connection failed: {e}") - logger.info(f"Event: Apibay returned {len(items) - before} results") + logger.info(f"Event: Apibay returned {len(items)} results") + return items + - # Torrents-csv API (Aggregator) - before = len(items) +def _fetch_torrents_csv(query: str) -> List[TorrentItem]: + """Torrents-csv API (Aggregator).""" + items = [] torrents_csv_url = "https://torrents-csv.com/service/search" try: - r = requests.get(torrents_csv_url, params={"q": query, "size": 100}, timeout=15) + r = get_shared_session().get(torrents_csv_url, params={"q": query, "size": "100"}, timeout=15) if r.status_code == 200: data = r.json() for item in data.get("torrents", []): @@ -90,7 +91,7 @@ def search_lite(query): if not info_hash: continue - encoded_name = requests.utils.quote(title) + encoded_name = quote(title) magnet = ( f"magnet:?xt=urn:btih:{info_hash}" f"&dn={encoded_name}" @@ -111,13 +112,16 @@ def search_lite(query): except Exception as e: logger.debug(f"Event: Torrents-csv connection failed: {e}") - logger.info(f"Event: Torrents-csv returned {len(items) - before} results") + logger.info(f"Event: Torrents-csv returned {len(items)} results") + return items + - # Nyaa RSS API (Anime/Asian content) - before = len(items) - nyaa_url = f"https://nyaa.si/?page=rss&q={requests.utils.quote(query)}&c=0_0&f=0" +def _fetch_nyaa(query: str) -> List[TorrentItem]: + """Nyaa RSS API (Anime/Asian content).""" + items = [] + nyaa_url = f"https://nyaa.si/?page=rss&q={quote(query)}&c=0_0&f=0" try: - r = requests.get(nyaa_url, timeout=15) + r = get_shared_session().get(nyaa_url, timeout=15) if r.status_code == 200: root = ET.fromstring(r.content) for item in root.findall("./channel/item"): @@ -141,7 +145,7 @@ def search_lite(query): size = int(float(size_str.replace(" MiB", "")) * 1024**2) elif child.tag.endswith("infoHash"): info_hash = child.text - magnet = f"magnet:?xt=urn:btih:{info_hash}&dn={requests.utils.quote(title)}&tr=http%3A%2F%2Fnyaa.tracker.wf%3A7777%2Fannounce" + magnet = f"magnet:?xt=urn:btih:{info_hash}&dn={quote(title)}&tr=http%3A%2F%2Fnyaa.tracker.wf%3A7777%2Fannounce" pubdate = item.findtext("pubDate") or None if pubdate: @@ -156,25 +160,62 @@ def search_lite(query): except Exception as e: logger.debug(f"Event: Nyaa connection failed: {e}") - logger.info(f"Event: Nyaa returned {len(items) - before} results") + logger.info(f"Event: Nyaa returned {len(items)} results") + return items - # --- qBittorrent Plugins Integration --- # - before = len(items) - try: - from helm.core.lite_plugin_loader import run_plugins - - # Define where to look for plugins - plugin_dirs = [ - os.path.join(get_config_dir(), "plugins"), # User plugins (XDG config dir) - os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "plugins"), # Bundled plugins - ] - - plugin_results = run_plugins(query, plugin_dirs) - if plugin_results: - items.extend(plugin_results) - logger.info(f"Event: Native plugins returned {len(plugin_results)} results") - except Exception as e: - logger.debug(f"Event: Plugin loader failed: {e}") +def _collect_plugins(query: str) -> List[TorrentItem]: + """Run the bundled/user search plugins (parallel) via the plugin loader.""" + from helm.core.lite_plugin_loader import run_plugins - return items + plugin_dirs = [ + os.path.join(get_config_dir(), "plugins"), # User plugins (XDG config dir) + os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "plugins"), # Bundled plugins + ] + + plugin_results = run_plugins(query, plugin_dirs) or [] + logger.info(f"Event: Native plugins returned {len(plugin_results)} results") + return list(plugin_results) + + +def _collect_all(query: str) -> List[TorrentItem]: + """Fetch every lite source concurrently and merge the results. + + Sources run in a single bounded pool so one hung socket slows a search to a + single request timeout instead of a serial chain of failures. + """ + sources = [ + _fetch_apibay, + _fetch_torrents_csv, + _fetch_nyaa, + _collect_plugins, + ] + pool = concurrent.futures.ThreadPoolExecutor(max_workers=len(sources)) + futures = [pool.submit(source, query) for source in sources] + # Give each source the full budget; sockets themselves time out at ~15s, + # so this bound only protects against an abandoned straggler. Done futures + # are drained eagerly; stragglers keep their private thread-local state and + # can never contaminate this or any later search. + done, _ = concurrent.futures.wait(futures, timeout=25) + pool.shutdown(wait=False) + + pooled = [] + for future in done: + try: + pooled.extend(future.result()) + except Exception: + logger.debug("Event: Failed to collect lite source results", exc_info=True) + return pooled + + +def search_lite(query): + """Lite mode fetcher using public APIs (e.g., apibay) without needing Jackett.""" + return _collect_all(query) + + +async def search_all_plugins(query, content_type="video"): + """Async aggregate search over every lite source, for the indexer-manager fallback. + + All I/O is delegated to the worker pool inside :func:`search_lite`. + """ + return await asyncio.get_running_loop().run_in_executor(None, search_lite, query) diff --git a/src/helm/core/lite_plugin_loader.py b/src/helm/core/lite_plugin_loader.py index 5425e26..d7a7080 100644 --- a/src/helm/core/lite_plugin_loader.py +++ b/src/helm/core/lite_plugin_loader.py @@ -23,8 +23,18 @@ def load_plugins(plugin_dir): sys.path.insert(0, plugin_dir) for file in os.listdir(plugin_dir): - # Ignore our SDK files and standard dunder files - if file.endswith(".py") and not file.startswith("__") and file not in ("helpers.py", "novaprinter.py"): + # Ignore our SDK files, standard dunder files, and plugins whose sources + # are already fetched inline by the lite pipeline (piratebay == apibay). + if ( + file.endswith(".py") + and not file.startswith("__") + and file + not in ( + "helpers.py", + "novaprinter.py", + "piratebay.py", + ) + ): filepath = os.path.join(plugin_dir, file) module_name = file[:-3] try: diff --git a/src/helm/core/oneshot.py b/src/helm/core/oneshot.py index 54fc602..9aba24c 100644 --- a/src/helm/core/oneshot.py +++ b/src/helm/core/oneshot.py @@ -1,3 +1,4 @@ +import builtins import os import subprocess import sys @@ -5,13 +6,21 @@ import requests + +def print(*args, **kwargs): + # Route this module's boot/teardown logs to stderr so `--json` output on + # stdout stays pure and jq-parseable. + kwargs.setdefault("file", sys.stderr) + builtins.print(*args, **kwargs) + + # The CLI runs inside the mini-helm container, whose docker socket is mounted at # /var/run/docker.sock. Both Docker and Podman provide that socket, so the docker # CLI works for either engine; override via HELM_DOCKER_CMD if you ever run the # CLI without the socket (e.g. native mode with a remote daemon). DOCKER_CMD = os.environ.get("HELM_DOCKER_CMD", "docker") -CONTAINER_SERVICES = frozenset(["jackett", "qbittorrent", "flaresolverr", "gluetun"]) +CONTAINER_SERVICES = frozenset(["jackett", "prowlarr", "qbittorrent", "flaresolverr", "gluetun"]) def _docker_run(args, **kwargs): @@ -25,7 +34,7 @@ def _container_name(service): def spin_up_oneshot(): print("\n\033[1m\033[36mInitializing One-Shot Ephemeral Stack...\033[0m") - print("\033[3mBringing up Jackett, Flaresolverr, and qBittorrent via docker compose...\033[0m") + print("\033[3mBringing up Jackett, Prowlarr, Flaresolverr, and qBittorrent via docker compose...\033[0m") from helm.core.config_manager import get_log_dir @@ -36,7 +45,9 @@ def spin_up_oneshot(): # Explicitly ensure all background containers are up just in case host depends_on fails try: _docker_run( - ["compose"] + compose_flags + ["up", "-d", "--remove-orphans", "jackett", "qbittorrent", "flaresolverr"], + ["compose"] + + compose_flags + + ["up", "-d", "--remove-orphans", "jackett", "prowlarr", "qbittorrent", "flaresolverr"], check=False, ) except Exception: @@ -73,6 +84,7 @@ def check_container_status(service_name, timeout=45): return False check_container_status("jackett") + check_container_status("prowlarr") check_container_status("qbittorrent") check_container_status("flaresolverr") print("\033[36mWaiting for internal HTTP servers to fully boot (this ensures 1337x doesn't fail)...\033[0m") @@ -86,7 +98,7 @@ def check_container_status(service_name, timeout=45): if r.status_code in [200, 401]: jackett_ready = True break - except requests.exceptions.ConnectionError: + except Exception: pass time.sleep(2) @@ -102,7 +114,7 @@ def check_container_status(service_name, timeout=45): if "ready" in r.text.lower() or r.status_code == 200: flaresolverr_ready = True break - except requests.exceptions.ConnectionError: + except Exception: pass time.sleep(2) diff --git a/src/helm/core/rss_fetcher.py b/src/helm/core/rss_fetcher.py index 3dfd2cd..adf489a 100644 --- a/src/helm/core/rss_fetcher.py +++ b/src/helm/core/rss_fetcher.py @@ -103,7 +103,7 @@ def _search_indexer(jackett_url, api_key, indexer_id, query, cat): params = {"apikey": api_key, "q": query} if cat: params["cat"] = cat - r = requests.get(url, params=params, timeout=20) + r = requests.get(url, params=params, timeout=60) r.raise_for_status() return _parse_feed(r.text) @@ -118,6 +118,137 @@ def _fetch_aggregate(jackett_url, api_key, query, cat): return _parse_feed(r.text) +def search_prowlarr(query, content_type="video"): + from helm.core.config_manager import load_config + from helm.core.secret_manager import get_secret + + config = load_config() + prowlarr_url = config.get("PROWLARR_URL", "http://localhost:19696") + api_key = get_secret("PROWLARR_API_KEY") + + if not api_key or "your_prowlarr_api_key_here" in api_key.lower(): + logger.warning("Event: Prowlarr API key not configured or is placeholder.") + return [] + + # Seed default indexers on first use when none are configured. + try: + idx_r = requests.get(f"{prowlarr_url}/api/v1/indexer", headers={"X-Api-Key": api_key}, timeout=5) + if idx_r.status_code == 200 and len(idx_r.json()) == 0: + logger.info("Event: Prowlarr indexers empty. Seeding defaults...") + from helm.core.indexer_manager import ProwlarrManager + + os.environ["PROWLARR_URL"] = prowlarr_url + seed_count = ProwlarrManager().seed_default_indexers() + logger.info("Event: Seeded %s default Prowlarr indexers.", seed_count) + except Exception: + pass + + endpoint = f"{prowlarr_url}/api/v1/search" + params = {"query": query, "apikey": api_key} + + try: + r = requests.get(endpoint, params=params, timeout=60) + r.raise_for_status() + + results = [] + data = r.json() + + for item in data: + title = item.get("title", "unknown") + size = item.get("size", 0) + seeders = item.get("seeders") or 0 + leechers = item.get("leechers") or 0 + indexer = item.get("indexer", "unknown") + download_url = item.get("magnetUrl") or item.get("downloadUrl") + + if not download_url: + continue + + results.append( + TorrentItem( + title, + download_url, + seeders, + leechers, + size, + pubdate=None, + indexer=f"Prowlarr ({indexer})", + ) + ) + + logger.info(f"Event: Prowlarr aggregated JSON search returned {len(results)} results") + return sorted(results, key=lambda x: x.seeders, reverse=True) + + except Exception as e: + logger.error(f"Event: Prowlarr JSON search failed: {e}. Falling back to Torznab XML parsing.") + + cats = content_type.split(",") + cat_ids = [] + for c in cats: + if c in CATEGORY_MAP: + cat_ids.append(CATEGORY_MAP[c]) + cat = ",".join(cat_ids) if cat_ids else CATEGORY_MAP.get("video") + + # Prowlarr Torznab: /{appId}/api?apikey=...&t=search&q=... + torznab_url = f"{prowlarr_url}/1/api" + params_xml = {"t": "search", "q": query, "apikey": api_key} + if cat: + params_xml["cat"] = cat + + try: + r = requests.get(torznab_url, params=params_xml, timeout=120) + r.raise_for_status() + items = _parse_feed(r.text) + logger.info(f"Event: Prowlarr Torznab fallback returned {len(items)} results") + return items + except Exception as ex: + logger.error(f"Event: Prowlarr Torznab fallback also failed: {ex}", exc_info=True) + return [] + + +def search_indexers(query, content_type="video"): + """ + Search using the configured Indexer Manager. + + Runs the configured manager (Prowlarr, Jackett, or both), falls back to the + other manager when configured, and finally to native Lite Mode plugins so a + search never comes up empty. + """ + from helm.core.config_manager import load_config + + config = load_config() + manager = config.get("INDEXER_MANAGER", "jackett") + + def dedupe(items): + seen = set() + unique = [] + for item in items: + key = (item.title.lower().strip(), item.size) + if key not in seen: + seen.add(key) + unique.append(item) + return unique + + items = [] + if manager in ("prowlarr", "both"): + items.extend(search_prowlarr(query, content_type)) + if manager in ("jackett", "both"): + items.extend(search_jackett(query, content_type)) + elif manager == "prowlarr" and not items: + logger.info("Event: Prowlarr returned no results, falling back to Jackett.") + items.extend(search_jackett(query, content_type)) + + if items: + return dedupe(items) + + logger.info("Event: Media Server search failed or returned 0 results, falling back to Lite mode...") + import asyncio + + from helm.core.lite_fetcher import search_all_plugins + + return dedupe(asyncio.run(search_all_plugins(query, content_type))) + + def search_jackett(query, content_type="video"): jackett_url = os.getenv("JACKETT_URL", "http://localhost:9117") api_key = get_secret("JACKETT_API_KEY") @@ -125,6 +256,40 @@ def search_jackett(query, content_type="video"): logger.info("Event: Jackett API key not configured. Seamlessly falling back to native Lite Mode plugins.") return [] + # 1) Try JSON API first + endpoint = f"{jackett_url}/api/v2.0/indexers/all/results" + params = {"Query": query, "apikey": api_key} + try: + r = requests.get(endpoint, params=params, timeout=60) + r.raise_for_status() + + results = [] + data = r.json() + items = data.get("Results", []) + + for item in items: + title = item.get("Title", "unknown") + size = item.get("Size", 0) + seeders = item.get("Seeders") or 0 + leechers = item.get("Peers") or 0 + indexer = item.get("Tracker", "unknown") + download_url = item.get("MagnetUri") or item.get("Link") + + if not download_url: + continue + + results.append( + TorrentItem(title, download_url, seeders, leechers, size, pubdate=None, indexer=f"Jackett ({indexer})") + ) + + if results: + logger.info(f"Event: Jackett aggregated JSON search returned {len(results)} results") + return sorted(results, key=lambda x: x.seeders, reverse=True) + + except Exception as e: + logger.error(f"Event: Jackett JSON search failed: {e}. Falling back to ThreadPool Torznab XML parsing.") + + # 2) Hard fallback to XML Torznab Parsing cats = content_type.split(",") cat_ids = [] for c in cats: @@ -155,42 +320,28 @@ def run(indexer_id): futures = [executor.submit(run, idx) for idx in indexers] for future in concurrent.futures.as_completed(futures, timeout=120): indexer_id, indexer_items = future.result() - logger.info(f"Event: Jackett indexer '{indexer_id}' returned {len(indexer_items)} results") - items.extend(indexer_items) + if indexer_items: + logger.info(f"Event: Jackett indexer '{indexer_id}' returned {len(indexer_items)} results") + items.extend(indexer_items) # If every per-indexer query failed (e.g. all returned errors), retry # with Jackett's aggregate endpoint before giving up. if not items: try: items = _fetch_aggregate(jackett_url, api_key, query, cat) - logger.info(f"Event: Jackett aggregate fallback returned {len(items)} results") - except requests.exceptions.RequestException as e: - logger.debug("Event: Network error while connecting to Jackett", exc_info=True) - raise RuntimeError(f"Jackett connection failed: {e}") # noqa: B904 except Exception as e: - logger.debug("Event: Unexpected error during aggregate fallback", exc_info=True) - raise RuntimeError(f"Unexpected error querying Jackett: {e}") # noqa: B904 + logger.debug(f"Event: Jackett aggregate torznab also failed: {e}", exc_info=True) + else: + # No specific indexers found, try aggregate try: items = _fetch_aggregate(jackett_url, api_key, query, cat) - logger.info(f"Event: Jackett aggregate returned {len(items)} results") - except requests.exceptions.RequestException as e: - logger.debug("Event: Network error while connecting to Jackett", exc_info=True) - raise RuntimeError(f"Jackett connection failed: {e}") # noqa: B904 - except ET.ParseError: - logger.debug("Event: XML parsing error", exc_info=True) - raise RuntimeError("Invalid response from Jackett (XML Parse Error)") # noqa: B904 - except ValueError as e: - logger.debug("Event: Value error while parsing results", exc_info=True) - raise RuntimeError(f"Value error while parsing Jackett results: {e}") # noqa: B904 except Exception as e: - logger.debug("Event: Unexpected error parsing results", exc_info=True) - raise RuntimeError(f"Unexpected error parsing Jackett results: {e}") # noqa: B904 + logger.debug(f"Event: Jackett aggregate torznab failed: {e}", exc_info=True) # Jackett's per-indexer endpoints can hand back the same release twice. - # Collapse exact title+size duplicates before returning so the CLI dedupe - # and display stay clean. - if len(indexers) > 1: + # Collapse exact title+size duplicates so the dedupe and display stay clean. + if len(items) > 1: seen = set() unique = [] for item in items: @@ -198,8 +349,5 @@ def run(indexer_id): if key not in seen: seen.add(key) unique.append(item) - items = unique - - if len(items) == 0: - logger.debug(f"Event: Jackett returned 0 items for query: '{query}'") + return unique return items diff --git a/src/helm/plugins/bittorrented.py b/src/helm/plugins/bittorrented.py index 91513b2..8b94f98 100644 --- a/src/helm/plugins/bittorrented.py +++ b/src/helm/plugins/bittorrented.py @@ -11,6 +11,7 @@ import requests from novaprinter import prettyPrinter +from helm.core.http import get_shared_session from helm.core.logger import get_logger logger = get_logger(__name__) @@ -53,7 +54,7 @@ def search(self, what, cat="all"): if len(query) < MIN_QUERY: return try: - r = requests.get( + r = get_shared_session().get( API_URL, params={ "q": query, diff --git a/src/helm/plugins/eztv.py b/src/helm/plugins/eztv.py index c62a4a6..144ee55 100644 --- a/src/helm/plugins/eztv.py +++ b/src/helm/plugins/eztv.py @@ -9,6 +9,7 @@ import requests from novaprinter import prettyPrinter +from helm.core.http import get_shared_session from helm.core.logger import get_logger logger = get_logger(__name__) @@ -22,7 +23,7 @@ class eztv(object): def search(self, what, cat="all"): query = what.strip().lower() try: - r = requests.get( + r = get_shared_session().get( f"{self.url}/api/get-torrents", params={"limit": 100, "page": 1}, headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) helm/0.9.1"}, diff --git a/src/helm/plugins/helpers.py b/src/helm/plugins/helpers.py index 3fa2bb4..539b342 100644 --- a/src/helm/plugins/helpers.py +++ b/src/helm/plugins/helpers.py @@ -1,4 +1,4 @@ -import requests +from helm.core.http import get_shared_session def retrieve_url(url, request_data=None): @@ -8,10 +8,11 @@ def retrieve_url(url, request_data=None): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } + session = get_shared_session() if request_data: - r = requests.post(url, data=request_data, headers=headers, timeout=15) + r = session.post(url, data=request_data, headers=headers, timeout=15) else: - r = requests.get(url, headers=headers, timeout=15) + r = session.get(url, headers=headers, timeout=15) return r.text @@ -19,7 +20,7 @@ def download_file(url, filename=None): """ Downloads a file to a specific location. Used by qBittorrent search plugins. """ - r = requests.get(url, timeout=15) + r = get_shared_session().get(url, timeout=15) if filename: with open(filename, "wb") as f: f.write(r.content) diff --git a/src/helm/plugins/subsplease.py b/src/helm/plugins/subsplease.py index 3623572..d4255ef 100644 --- a/src/helm/plugins/subsplease.py +++ b/src/helm/plugins/subsplease.py @@ -7,9 +7,9 @@ import re -import requests from novaprinter import prettyPrinter +from helm.core.http import get_shared_session from helm.core.logger import get_logger logger = get_logger(__name__) @@ -39,7 +39,7 @@ def search(self, what, cat="all"): if not query: return try: - r = requests.get( + r = get_shared_session().get( API_URL, params={"f": "search", "s": query, "tz": "UTC"}, headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) helm/0.9.1"}, diff --git a/src/helm/plugins/yts.py b/src/helm/plugins/yts.py index d3250e4..2856c97 100644 --- a/src/helm/plugins/yts.py +++ b/src/helm/plugins/yts.py @@ -7,6 +7,7 @@ import requests from novaprinter import prettyPrinter +from helm.core.http import get_shared_session from helm.core.logger import get_logger logger = get_logger(__name__) @@ -29,7 +30,7 @@ class yts(object): def search(self, what, cat="all"): try: - r = requests.get( + r = get_shared_session().get( API_URL, params={"query_term": what, "limit": 50}, headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) Helm/0.9"}, diff --git a/src/helm/ui/tui.py b/src/helm/ui/tui.py index 93b94b1..52a92b3 100644 --- a/src/helm/ui/tui.py +++ b/src/helm/ui/tui.py @@ -93,9 +93,9 @@ def animate(): import concurrent.futures def fetch_jackett(): - from helm.core.rss_fetcher import search_jackett + from helm.core.rss_fetcher import search_indexers - return search_jackett(query, content_type) + return search_indexers(query, content_type) def fetch_lite(): from helm.core.lite_fetcher import search_lite @@ -115,7 +115,7 @@ def fetch_lite(): except Exception as e: sys.stdout.write("\r" + " " * 30 + "\r") sys.stdout.write( - f"\n\033[33m[!] Jackett not available ({e}). Auto-falling back to LITE MODE...\033[0m\n" + f"\n\033[33m[!] Indexer Manager not available ({e}). Auto-falling back to LITE MODE...\033[0m\n" ) sys.stdout.flush() used_lite = True diff --git a/tests/test_lite_fetcher.py b/tests/test_lite_fetcher.py index dbad0c5..e19f5aa 100644 --- a/tests/test_lite_fetcher.py +++ b/tests/test_lite_fetcher.py @@ -1,6 +1,8 @@ +import asyncio + import responses -from helm.core.lite_fetcher import search_lite +from helm.core.lite_fetcher import search_all_plugins, search_lite NYAA_RSS = """ @@ -76,3 +78,14 @@ def test_search_lite_aggregates_all_sources(monkeypatch): assert nyaa.leechers == 3 assert nyaa.size == int(1.5 * 1024**3) assert nyaa.pubdate == "2024-12-08" + + +def test_search_all_plugins_delegates_to_search_lite(monkeypatch): + from helm.core.rss_fetcher import TorrentItem + + item = TorrentItem("Ubuntu 24.04 ISO", "magnet:?xt=urn:btih:cafe", 42, 7, 999) + monkeypatch.setattr("helm.core.lite_fetcher.search_lite", lambda query: [item]) + + result = asyncio.run(search_all_plugins("ubuntu", "video")) + + assert result == [item] diff --git a/tests/test_prowlarr_manager.py b/tests/test_prowlarr_manager.py new file mode 100644 index 0000000..236b401 --- /dev/null +++ b/tests/test_prowlarr_manager.py @@ -0,0 +1,87 @@ +import pytest +import responses + +from helm.core.indexer_manager import ProwlarrManager + + +@pytest.fixture(autouse=True) +def _prowlarr_env(monkeypatch): + monkeypatch.setenv("PROWLARR_URL", "http://localhost:19696") + monkeypatch.setenv("PROWLARR_API_KEY", "testapikey") + + +@pytest.fixture +def schema_payload(): + return [ + {"definitionName": "1337x", "name": "1337x", "implementation": "Cardigann", "privacy": "public"}, + {"definitionName": "YTS", "name": "YTS (Public)", "implementation": "YtsApi", "privacy": "public"}, + ] + + +@responses.activate +def test_prowlarr_manager_get_indexers(schema_payload): + responses.add(responses.GET, "http://localhost:19696/api/v1/indexer/schema", json=schema_payload, status=200) + responses.add( + responses.GET, + "http://localhost:19696/api/v1/indexer", + json=[ + {"id": 1, "enable": True, "definitionName": "1337x", "implementation": "Cardigann"}, + {"id": 2, "enable": False, "definitionName": "YTS", "implementation": "YtsApi"}, + ], + status=200, + ) + + manager = ProwlarrManager() + indexers = manager.get_all_indexers() + + assert len(indexers) == 2 + assert indexers[0]["id"] == "1" + assert indexers[0]["configured"] is True + assert indexers[0]["title"] == "1337x" + assert indexers[1]["id"] == "2" + assert indexers[1]["configured"] is False + + +@responses.activate +def test_prowlarr_manager_add_remove(): + responses.add( + responses.GET, + "http://localhost:19696/api/v1/indexer/1", + json={"id": 1, "enable": False, "name": "1337x"}, + status=200, + ) + responses.add( + responses.PUT, + "http://localhost:19696/api/v1/indexer/1", + json={"id": 1, "enable": True, "name": "1337x"}, + status=200, + ) + + manager = ProwlarrManager() + assert manager.add_indexer("1") is True + + responses.add( + responses.GET, + "http://localhost:19696/api/v1/indexer/2", + json={"id": 2, "enable": True, "name": "YTS"}, + status=200, + ) + responses.add( + responses.PUT, + "http://localhost:19696/api/v1/indexer/2", + json={"id": 2, "enable": False, "name": "YTS"}, + status=200, + ) + assert manager.remove_indexer("2") is True + + +@responses.activate +def test_prowlarr_seed_default_indexers(schema_payload): + responses.add(responses.GET, "http://localhost:19696/api/v1/indexer/schema", json=schema_payload, status=200) + responses.add(responses.GET, "http://localhost:19696/api/v1/indexer", json=[], status=200) + responses.add(responses.POST, "http://localhost:19696/api/v1/indexer", json={"id": 9, "enable": True}, status=200) + + manager = ProwlarrManager() + enabled = manager.seed_default_indexers() + + assert enabled == 2 diff --git a/tests/test_rss_fetcher.py b/tests/test_rss_fetcher.py index 5fa3d84..f781779 100644 --- a/tests/test_rss_fetcher.py +++ b/tests/test_rss_fetcher.py @@ -64,3 +64,36 @@ def test_search_jackett_aggregate_fallback_when_no_indexers_configured(monkeypat def test_search_jackett_returns_empty_without_api_key(monkeypatch): monkeypatch.delenv("JACKETT_API_KEY", raising=False) assert search_jackett("ubuntu", "video") == [] + + +def test_search_indexers_falls_back_to_lite_when_manager_returns_nothing(monkeypatch): + from helm.core import config_manager, lite_fetcher + from helm.core.rss_fetcher import TorrentItem + + monkeypatch.setattr(config_manager, "load_config", lambda: {"INDEXER_MANAGER": "jackett"}) + monkeypatch.setattr(rf, "search_jackett", lambda *a, **k: []) + + lite = TorrentItem("Ubuntu 24.04 Lite", "magnet:?xt=urn:btih:cafe", 5) + monkeypatch.setattr(lite_fetcher, "search_lite", lambda query: [lite]) + + # Must NOT raise ImportError despite the async search_all_plugins wrapper. + items = rf.search_indexers("ubuntu", "video") + + assert items == [lite] + + +def test_search_indexers_falls_back_to_lite_with_prowlarr_manager(monkeypatch): + from helm.core import config_manager, lite_fetcher + from helm.core.rss_fetcher import TorrentItem + + monkeypatch.setattr(config_manager, "load_config", lambda: {"INDEXER_MANAGER": "prowlarr"}) + monkeypatch.setattr(rf, "search_prowlarr", lambda *a, **k: []) + monkeypatch.setattr(rf, "search_jackett", lambda *a, **k: []) + + lite = TorrentItem("Ubuntu 24.04 Lite", "magnet:?xt=urn:btih:cafe", 5) + monkeypatch.setattr(lite_fetcher, "search_lite", lambda query: [lite]) + + ret = rf.search_indexers("ubuntu", "video") + + # Same list, deduped (no duplicates here). + assert ret == [lite]