gextto

package module
v0.0.0-...-18d643c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: EUPL-1.2 Imports: 79 Imported by: 0

README

Gextto — EXpert Torrent Transfer Orchestrator

Tell Gextto what you want to watch. It finds the best release, downloads it, verifies it, names it and shelves it in your library — then keeps watching for a better copy.

Gextto is a self-hosted media automation daemon: it searches, downloads, verifies, renames and archives series, movies and comics. It features its own pure-Go BitTorrent engine (gx-torrent), a server-rendered web UI and a terminal client. Two binaries, no C dependencies, no Node.js build, six languages.

Go Tests Platforms BEPs Languages Documentation

Italiano: README.it.md · Manual: English · italiano · Issues: bugs and feature requests · Contribute: developer guide · Documentation site: https://buzzqw.github.io/gextto/

What it does

Add a title and Gextto orchestrates the entire lifecycle autonomously: it queries your configured sources, scores candidate releases, downloads the best match, verifies file integrity, cleans audio tracks, and shelves the media into your library with proper naming. When a better quality release appears, it upgrades seamlessly; if a swarm stalls, it recovers automatically.

flowchart LR
    A["🎯 Title added<br/>(Web UI, PWA, Jellyseerr)"] --> B["🔍 Search & Scoring<br/>(Torznab, RSS, eD2k)"]
    B --> C["⚡ Swarm Download<br/>(gx-torrent + aMule)"]
    C --> D["🛡️ Verification & Audio Cleanup<br/>(Lossless, zero re-encode)"]
    D --> E["📁 Media Library<br/>(Jellyfin, Plex, NAS)"]
Key superpowers
  • 🤝 Two networks, one file (Shareaza-style): When an episode downloads on both BitTorrent and eD2k (aMule) with matching file size, verified blocks (SHA-1) are shared between engines on the fly. Whichever finishes first completes the other, and a torrent stuck at 95% recovers using eD2k sources while sharing a single speed limit. (read more)
  • ⚡ Pure-Go BitTorrent engine (gx-torrent): Original, zero-CGO implementation supporting BitTorrent v1, v2 and hybrid (BEP 52), IPv6 DHT, and uTP. Operates at ~28 MB RSS at rest and up to 290 MB/s throughput — outperforming libtorrent-based clients. Also runs as a standalone daemon on Linux and Windows. (measurements · BEP list)
  • 🧹 Lossless smart audio cleanup: Drops unwanted foreign audio tracks on import, preserving only your preferred languages without re-encoding video or audio. Every packet is compared with the original to guarantee 100% audio/video sync and zero quality loss.
  • 📉 Latency-aware automatic bandwidth: Auto mode takes the full line when idle, but continuously probes ping latency. If someone in the house streams or games, Gextto yields instantly and reclaims bandwidth once the line clears.
  • 🛡️ Bulletproof library safety: Zero duplicate storage using hardlinks during seeding, NAS mount-loss protection to avoid accidental deletions, an automated recycle bin for upgrades, and periodic background file integrity checks with automatic replacement.
At a glance
Area Highlights Details
Numbers 290 MB/s throughput · 28 MB RSS at rest · 0.3–0.5% CPU Benchmark figures
Protocol BitTorrent v1, v2 & hybrid (BEP 52) · 34 BEPs implemented and tested BEP compliance
Network TCP + uTP on one port · UPnP, NAT-PMP, PCP · BEP 55 holepunching · SOCKS5/HTTP · VPN killswitch gx-torrent doc
Automation TV series, movies, comics · Torznab, RSS, HTML listings · stuck-download replacement User manual
Two networks Simultaneous Torrent + eD2k downloads on matching files · verified pieces from aMule .part aMule integration
Integrations Jellyfin, Plex, Jellyseerr (v3 API), aMule (eD2k/Kad), Telegram, Discord, Slack, ntfy, Pushover, iCal User manual
Interfaces Responsive web UI (SSR + HTMX, installable PWA, 20+ themes) · terminal TUI over SSH · JSON API TUI reference · API
Build Pure Go (CGO_ENABLED=0) · Linux x86_64/aarch64 · gx-torrent also native on Windows Developer manual

A look

A test instance downloading six public, legal torrents: Debian, Ubuntu Server and the Blender open movies Big Buck Bunny, Sintel, Tears of Steel and Cosmos Laundromat. More screens — library, settings, first start, maintenance, health, the gx-torrent page and the other languages — are in the guided tour.

Bandwidth menu Torrent details, piece map
Bandwidth. What applies now and where it comes from; an exception for now, Auto or a limit, in one click. Torrent details. General, trackers, content, peers, the piece map, limits and storage.
Dashboard Speed rule in the settings
Dashboard. The session at a glance, the live traffic and what needs checking. Settings. One choice for the speed rule; the rows that depend on it appear only when they matter.
Downloads on a phone

On a phone the same pages reflow into cards, the menus open in place and the actions on the selection stay within thumb reach. The web UI is also installable as an app (PWA), and a terminal client covers the same work over SSH.

Guided tour with every screen →

Install on Linux

For 64-bit Linux with systemd: Debian 12+, Ubuntu 22.04+, Fedora, openSUSE Leap 15.6+/Tumbleweed, Arch. Run as root:

curl -fsSL https://raw.githubusercontent.com/buzzqw/gextto/main/install.sh | sudo bash

Prefer Docker? The full stack starts Gextto, gx-torrent, indexarr, Jackett, Prowlarr, FlareSolverr and aMule together with docker compose.

The installer sets up /opt/gextto, data in /var/lib/gextto, and serves the UI on port 5000, with gx-torrent alongside gexttod — pure Go, nothing else to install for torrents. When available, it installs ffmpeg, mediainfo and mkvtoolnix for real media analysis and lossless audio-track cleanup (--no-media-tools skips them). eD2k and Kad are optional and connect to an amuled you run yourself (aMule integration). By default, the service runs as the invoking user; --user gextto uses a dedicated system account.

[!IMPORTANT] Gextto is meant for a trusted network: the web UI and API are open by default. For access from outside, enable the optional login (Configuration → Access and services; the LAN stays free) and still use HTTPS via reverse proxy or VPN. Read the security policy before exposing it remotely.

Install from source

Go 1.26.8+; pure Go build, embedded web UI:

make build                 # gexttod and gx-torrent in bin/

make test runs the full test suite, make test-ui the browser suite, and make fuzz-smoke the network fuzzers. See the developer manual for details.

First safe run
  1. Open http://<server>:5000: the first visit opens the setup wizard (password, folders with permission check, indexer and TMDB, first title). Reopenable at /?view=setup.
  2. Keep dry-run on, add one test title and run a manual search.
  3. Check Health and Logs, then enable active mode.

NAS setup and troubleshooting: the user manual and advanced guide.

Update and uninstall

An Update available button appears when a release is published; Maintenance → Updates shows the changes and Update now backs up databases, installs the update, and rolls back automatically if the new version fails health checks. Re-running the installer updates from a shell with the same rollback. See the changelog for full change history.

sudo bash install.sh --help       # all options
sudo bash install.sh --dry-run    # print what would happen, change nothing
sudo bash install.sh --uninstall  # stop and remove the program (keeps data)
sudo bash install.sh --uninstall --purge   # also remove the data directory

Features

Smart search and acquisition
  • Quality-aware scoring: Deterministic scores grouped into video cards (4K, Full HD, HD, SD, codec) and audio cards (lossless, DTS/DD+, AC3/5.1, AAC/Opus, MP3), plus 5.1/7.1 and Atmos/DTS:X. Higher-grade library files are protected from downgrade, and dead swarms cannot win over active ones.
  • Named quality profiles: Create reusable profiles (resolution, audio presets, language, subtitles, upgrade cutoffs). The profile list is served directly to Jellyseerr through the /api/v3 subset (system/status, qualityprofile, rootfolder, series/movie lookup, queue).
  • Season pack intelligence: Packs are downloaded only when they fill real missing gaps; unneeded episodes are excluded before downloading, and airing packs (IN CORSO n/m) are safely imported for available episodes.
  • Stuck-download auto-recovery: A download that stalls or a magnet waiting endlessly for metadata is automatically superseded by a valid alternative and temporarily blocklisted.
  • Comprehensive source management: Torznab indexers (Jackett, Prowlarr, indexarr), public RSS feeds, HTML listings and web search. Indexer managers are queried one tracker at a time to prevent rate-limit choking, with per-feed activity and failure tracking.
  • Archive extraction (RAR): Automatically unpacks uncompressed and RAR 5 compressed multi-volume archives directly into the library, preserving the original archive for continuous seeding.
  • eD2k and Kad through aMule or emule-qt: Drives amuled via the External Connections protocol, or emule-qt via its REST API — one or the other; emule-qt can also be run and updated by Gextto in Docker. Search Kad, paste ed2k:// links, monitor downloads and share lists directly from Gextto. (read more)

→ Full documentation: Sources and Quality in the User Manual

Library safety and maintenance
  • Zero-waste seeding: Uses hardlinks so completed downloads appear in your media library instantly without duplicating disk space while seeding continues.
  • NAS and mount guard: Detects unmounted network shares to prevent accidental deletion storms, resumes interrupted moves, and isolates hung storage without stalling the engine.
  • Recycle bin: Upgraded or deleted media moves to a safety bin first, protecting against accidental loss.
  • No pointless replacements: Score-only differences (file size, subtitles) never trigger an upgrade unless real technical gain (REPACK, PROPER, higher resolution/codec) is achieved.
  • Damaged-file watchdog: Periodic background scans probe and decode archived videos with ffprobe and ffmpeg. 4K keyframe check spots corruption in minutes; damaged files can be automatically replaced and re-downloaded.
  • Night maintenance window: Runs heavy tasks when idle (duplicate archive titles merged, database compaction, weekly integrity checks, MediaInfo scans, audio cleanup).

→ Full documentation: Library Safety and Maintenance · Advanced NAS Guide

Bandwidth and latency control
  • One rule, one exception: Choose between Auto, fixed speed limits, or a weekly schedule. From the Downloads page, set temporary exceptions (1 to 12 hours) in a single click.
  • Latency-aware Auto mode: Gextto measures ping round-trip times to the Internet; when someone else uses the line, it backs off gracefully to keep interactive traffic and gaming responsive, then reclaims speed.
  • Tracker-aware seeding rules: Configure ratio, time, and inactivity limits globally or per indexer/tracker, with identical behavior on both gx-torrent and qBittorrent-nox.

→ Full documentation: Speed and Seeding Rules

Integrations and interfaces
  • Rich notifications: Telegram, e-mail, webhooks, Discord, Slack, Gotify, ntfy, Pushover, Apprise, and custom scripts, with fine-grained event filtering and anti-spam windows.
  • Media server sync: Automatic folder refresh triggers for Jellyfin and Plex, plus an iCal feed of arrivals and air dates.
  • *Browser & arr ecosystem: Direct magnet/torrent capture via browser handlers, support for qBittorrent extensions (e.g. Torrent Control), and a qBittorrent-compatible /api/v2 endpoint.
  • Accessible & modern UI: Server-rendered HTMX interface (PWA installable on mobile), 20+ contrast-checked themes, keyboard navigation (axe-core WCAG verified), and a full terminal TUI over SSH. Available in six languages (IT, EN, DE, FR, ES, PL).

→ Full documentation: API Reference · TUI Reference

Numbers

These figures come from the live installation and from real swarms, indexers and the home line, on a 4-core Intel N97 with 16 GB. Throughput was measured on an FTTC line (100 Mbit/s down, 15 Mbit/s up): the line was the limit, not the engine; on FTTH the same setup is no longer capped by the line. Each figure is in docs/measurements.md with the machine, the date and the command to reproduce it.

Area Result
Compared with other clients Same limits in Docker, N97: at full speed 290 MB/s, ahead of Deluge and qBittorrent (239–246, measured in an earlier round) and of rain, anacrolix/torrent and Transmission (30–175), with 24 MiB of own memory against 33–53. On a shaped 100 Mbit/s line anacrolix/torrent is 2 % ahead (11.2 MB/s against 11.4, inside the spread), and gx-torrent spends the least CPU per GiB of the four that reach the line; at a recheck of 4 GiB gx-torrent is first (3.6 s against 3.9–10.2) and on upload it is first too (203 MB/s, against qBittorrent's 191). At rest rain and anacrolix/torrent are the lightest (0.01 % of a core against 0.05); with a hundred torrents gx-torrent spends 0.13 %, against anacrolix's 0.01, Deluge's 0.37 and rain's 2.18. Full tables
Real swarm 9.3–9.4 MB/s on the Ubuntu ISO, against 6.3–7.1 MB/s for libtorrent on the same swarm (one measured campaign)
Engine memory 28–30 MB RSS at rest (16–18 MB anonymous), DHT on and a full IP filter (172,740 rules). With 10 torrents downloading to a NAS: ~507 MB outside the two caches; the write cache sizes itself from free RAM
Engine CPU 18–37 % of one core at 8.2–8.8 MB/s with 116–132 peers, 2.0–4.3 s of CPU per 100 MB; 0.3–0.5 % of one core at rest
Indexer searches Jackett and Prowlarr searched one indexer at a time: a cycle of 30 titles in 110 s, 205 requests and none failed, 5,935 releases
Sharing the line A saturated download adds ~40 ms of latency to the whole house. Alone on the line Gextto keeps all of it (8.5 MB/s); with another device downloading, that device gets 6.8–7.3 MB/s of the 9 MB/s FTTC line
Reusing local data A torrent sharing files with one already on disk takes only 25 % of the file from the network (Debian and Arch ISOs), also after a restart and in any adding order
Disk writes 16 KiB writes on NFS at 81 MiB/s with batched durability; opt-in mmap ~7.0 GB/s on tmpfs
Feed archive 447,000 releases in 320 MB, one row per torrent; 1,000 new releases archived in 36 ms into an archive of 50,000, and 1,000 already archived in 9 ms; the standalone archive searches 100,000 releases in 7.4 ms
Daemon at rest ~0.7 % CPU at rest; ~5,000 metadata calls a day for 55 series; the health probes never write to a NAS, so its disks can sleep

The same document records what was measured and dropped — io_uring, batched uTP I/O on this load, a write-back cache — so the same ideas are not tried twice.

Torrent engine

Gextto keeps the control plane (queue, scoring, post-processing, archiving) and delegates transfers to one selectable engine (Configuration → Torrent engine); switching is a coordinated migration.

Engine Where it runs When to pick it
gx-torrent (default) Separate supervised Go process Pure Go, self-contained, v1/v2/hybrid, DHT and MSE/PE; also standalone on Linux and Windows; no WebTorrent/WebRTC
qBittorrent-nox External daemon via its Web API, or one Gextto downloads and runs privately You already run it or prefer its UI (setup guide); also the first step of the automatic fallback

Automatic fallback. If the active engine cannot stay up, Gextto first rolls an updated gx-torrent back to the previous binary, then switches to a managed qBittorrent-nox (downloaded on demand, SHA-256 verified) or an external one, and finally to a recovery state with the UI up. A cooldown prevents ping-pong; GEXTTO_ENGINE=qbittorrent (or gx-torrent) forces the engine for one run.

gx-core and gx-torrent

gx-core (internal/gxcore) and its DHT (internal/dht) are original code written in this repository under EUPL-1.2, with no third-party-derived code (THIRD-PARTY-NOTICES lists only linked libraries). gx-torrent runs it as a supervised process that survives orchestrator restarts: Gextto re-attaches when binary and options match.

  • Protocol: BitTorrent v1, v2-only and hybrid (BEP 52) with SHA-256 Merkle verification. 34 BEPs implemented and tested (docs/bep.md): wire protocol, Fast Extension, metadata, PEX with IPv6, multitracker, LSD, super-seeding, web seeds, private torrents, lt_donthave, UDP trackers with scrape, DHT IPv6, scrape, secure IDs, and K/V store.
  • Local reuse: Automatically detects and reuses local pieces and 16 KiB blocks already verified on disk by another torrent without redownloading; private torrents are kept strictly isolated.
  • Network: TCP and uTP (BEP 29) multiplexed on a single port; BEP 55 holepunching (client and relay); UPnP, NAT-PMP, and PCP; SOCKS5 and HTTP CONNECT proxy; interface-bound VPN killswitch.
  • Resource efficiency: OS page cache coalescing, batched fdatasync, sparse files, fallocate, zero-allocation hot paths (in-place RC4, zero-copy uTP), binary-searched IP blocklist.
  • Streaming and DLNA: Separate playback and readahead windows, live per-file priorities, HTTP Range seeking, and an opt-in DLNA/UPnP media server for smart TVs.
  • Bandwidth policies: Per-torrent bandwidth shares (Tixati-style), trading split favoring peers sending data, out-of-the-box client filtering against leechers, and local GeoIP country lookup (DB-IP).

→ Full details: gx-torrent Technical Document · BEP Compliance

gx-torrent as a standalone client

gx-torrent can also be used as a lightweight, full-featured standalone client without Gextto, serving as a pure-Go alternative to qbittorrent-nox or transmission-daemon:

  • qBittorrent Web API v2 (/api/v2/...): Fully compatible with Sonarr, Radarr, Lidarr, Readarr, and mobile managers.
  • Rich Web UI: Dark and light themes, 24 customizable columns, category manager, tag filters, detail drawer (peers, piece map, files), magnet preview, drag-and-drop, and mobile-friendly cards.
  • Automation & RSS: Dedicated Series & movies status page, rule-based RSS engine with PASS/FAIL filters, and local feed archive.
  • Prometheus & Events: Exposes /api/v1/metrics for Grafana/Home Assistant and /api/v1/events for Node-RED or shell integrations.
  • Platforms: Linux x86_64/aarch64 (systemd unit, Dockerfile) and a native Windows service (amd64/arm64).

→ Full manual: Illustrated gx-core Manual

Tests

What runs on every push (make test, make test-ui, make fuzz-smoke and CI):

Layer What runs
Unit and integration 2,191 Go test functions in 426 files: engine, DHT, uTP, storage, scoring, post-processing, API, UI rendering. The TUI is driven against the real router
End-to-end 110 Playwright tests drive the real daemon in a browser — pages, mobile, six languages, security, settings — including 20 accessibility tests, 12 of them axe-core WCAG audits
Fuzzing 23 network-facing parsers (DHT, bencode, magnet, BEP 10/52, trackers, Torznab, RSS, MSE) fuzzed in CI; every crash found becomes a committed seed
Real-world harnesses 14 opt-in measurements: real public swarms, the public DHT, a real libtorrent peer, local merge on real ISOs, choking and pipelining, the live Jackett/Prowlarr, the latency of the home line
Static guards Every UI button points at a registered route, every internal call resolves on the real router, every setting is writable, translated in six languages and has its tooltip, every API route is documented
Platforms and packaging CI cross-compiles engine and daemon for Windows and runs the Windows platform tests and a real service install; the installers are self-tested (every flag, a dry-run that changes nothing) and the standalone and full Docker images are built and smoke-tested; CodeQL scans every push
Benchmarks 45 Go benchmarks on the hot paths (picker, storage, uTP, archive, merge, logging), run before and after every data-path change

Accessibility

Keyboard navigation, accessible names, dialog focus management, semantic sortable tables, live announcements, responsive reflow and contrast-checked themes, covered by axe-core and Playwright (cd uiweb/end2end && npm ci && npm run test:a11y). This is not a legal certification: manual screen-reader and assistive-technology testing is still required (scope, tests and limits).

Documentation

Need Document
Operate the service English manual · Manuale italiano
What changed Changelog · Italiano
Measurements and method Measurements
Open work TODO
Architecture and design Architecture
BitTorrent specifications (BEPs) BEP compliance
NAS, reverse proxy, recovery Advanced guide
HTTP integrations API reference
Move an existing installation Migration guide
Terminal client TUI reference
gx-torrent engine and standalone client gx-torrent technical document · gx-core
eD2k and Kad through aMule or emule-qt aMule and emule-qt integration
qBittorrent-nox backend Setup guide
Build or contribute Developer manual
Network and data safety Security policy

Full tree: the documentation index.

Support the project

If Gextto is useful and you would like to support its development, a PayPal donation is welcome — thank you. A Donate button is also always visible in the UI, bottom right; the standalone gx-torrent page has the same button.

Donate with PayPal Ko-fi

Gextto is a download automation tool. It does not host, index or distribute any copyrighted content.

  • It connects to indexers you configure (Jackett, Prowlarr, indexarr, public RSS feeds). It ships no index of its own.
  • What you download is your responsibility. Use Gextto only for content you have the right to access — public domain, Creative Commons, or media you own.
  • BitTorrent and the engines Gextto drives are neutral technology; this project does not encourage or facilitate piracy.
  • Released under the EUPL 1.2 open-source licence.

License

Gextto is licensed under the EUPL-1.2. The engine core (gx-core, internal/gxcore) and the DHT (internal/dht) are original code in this repository under the same licence. See THIRD-PARTY-NOTICES for the linked third-party libraries (also on the web UI Licence page).

Acknowledgements

Thanks to DeepSeek for its support and patience while this project grew.

Documentation

Index

Constants

View Source
const (
	ManagerProwlarr = "prowlarr"
	ManagerJackett  = "jackett"
	// ManagerIndexarr is the indexarr manager. It speaks the Jackett Torznab
	// layout for the indexer list and the per-indexer lanes, and its own /api
	// endpoint for the aggregate search.
	ManagerIndexarr = "indexarr"
)

Manager identifiers for the supported indexer managers.

View Source
const (
	BackendQbittorrent = "qbittorrent"
	BackendGxTorrent   = "gx-torrent"
)

Backend identifiers accepted by `torrent_backend`.

View Source
const ArchiveStem = "gextto-linux"

ArchiveStem is the prefix of the per-architecture release asset.

View Source
const (
	// BackendRecovery is not a torrent engine: it is the terminal state of the
	// fallback chain, where no alternative engine can be made to work, the
	// transfers stay stopped and the UI is kept up for the operator.
	BackendRecovery = "recovery"
)
View Source
const CalendarParallel = 8

CalendarParallel bounds the calendar's concurrent metadata lookups.

View Source
const DefaultRepo = "buzzqw/gextto"

DefaultRepo is the repository used when none is configured.

View Source
const DefaultTorrentBackend = BackendGxTorrent

DefaultTorrentBackend is the engine a fresh installation uses when no `torrent_backend` has ever been saved. gx-torrent is the default since it is pure Go and runs in its own supervised process.

View Source
const DefaultUpgradeMinScoreDiff int64 = 200

DefaultUpgradeMinScoreDiff is the default upgrade threshold used by callers without a `Config`.

View Source
const EngineOverrideEnv = "GEXTTO_ENGINE"

EngineOverrideEnv forces the torrent engine for one run, so a service whose saved backend is broken can be recovered from a shell without editing the database.

View Source
const ExternalSearchTimeout = 12 * time.Second

ExternalSearchTimeout bounds the metadata lookup of the search action.

View Source
const FEEDFETCHATTEMPTS = 3

Tentativi per scaricare il corpo di un feed: Cloudflare a volte chiude lo stream a metà. I feed sono testi piccoli, quindi in caso di errore transitorio si può riscaricare.

View Source
const FEEDFETCHTIMEOUT = 20 * time.Second

Timeout del singolo tentativo.

View Source
const HOSTMAXCONCURRENCY = 8

Aggregate concurrency per host. A single feed keeps its own small limit, but many feeds run at once and detail scraping can fan out to dozens of requests; without a shared cap a host starts answering `429 Too Many Requests`. 8 concurrent requests per host is well within what torrentgalaxy/ext.to tolerate in testing.

View Source
const InstanceLockFile = "gextto.instance.lock"

InstanceLockFile is the name of the lock inside the data folder.

View Source
const KNABENSTREAMBODYLIMIT = 512 * 1024
View Source
const KNABENSTREAMITEMLIMIT = 50

Knaben keeps streaming a very large RSS response instead of closing it promptly. Stop after one normal listing page.

View Source
const ManualSearchBudget = 90 * time.Second

ManualSearchBudget bounds a manual search, so the request cannot wait forever on a slow source.

View Source
const ServiceName = "gextto.service"

ServiceName is the systemd unit updated/restarted after an install.

View Source
const TmdbImageBaseURL = "https://image.tmdb.org/t/p"

TmdbImageBaseURL is the TMDB image CDN prefix. Callers append a size segment (for example "w154") and the poster path, exactly as the web module did with "https://image.tmdb.org/t/p/w154{path}".

Variables

View Source
var ErrInferiorDuplicate = errors.New("release inferior to existing file")

ErrInferiorDuplicate is returned when an incoming release is discarded because an existing file is equal or superior in quality.

View Source
var ErrPathMappingMissing = errors.New("backend path mapping missing")

ErrPathMappingMissing is returned when a path cannot be translated into the backend namespace.

View Source
var ErrTorrentMoving = errors.New("the torrent payload is being moved")

ErrTorrentMoving reports that the engine is relocating a torrent's payload and refuses to change it (file priorities, start, pause) until the move ends. It is a postponement, not a failure: callers retry at the next inspection without a warning. Backends map their own wording onto it.

Functions

func AcquireInstanceLock

func AcquireInstanceLock(dataDir string) (func(), error)

AcquireInstanceLock takes the data-folder lock and returns the function that releases it. A second process gets a sentence naming the folder, not a raw EWOULDBLOCK.

func AcquisitionsApi

func AcquisitionsApi(w http.ResponseWriter, r *http.Request, s *AppState)

AcquisitionsApi returns the story of downloads (acquisition.go): by torrent `hash`, by the short `acq` ID printed in the log, or the latest events of a `series` (optionally narrowed to `season` and `episode`, at most `limit`).

func AddAllFromArchive

func AddAllFromArchive(w http.ResponseWriter, r *http.Request, s *AppState)

AddAllFromArchive ports extto's `add_all_from_archive`: it scans the archive root and registers every folder that is not already a monitored series.

The defaults match the legacy endpoint (seasons `*`, quality `1080p`, configured default language, enabled, `archive_path` set to the folder). A leading dot and well-known system folders are skipped; existing series are matched case-insensitively so no duplicate is created.

func AddArchiveEntry

func AddArchiveEntry(w http.ResponseWriter, r *http.Request, s *AppState)

func AddComic

func AddComic(w http.ResponseWriter, r *http.Request, s *AppState)

func AddDownloadTag

func AddDownloadTag(w http.ResponseWriter, r *http.Request, s *AppState)

AddDownloadTag adds a tag to the stored download tags, skipping one that differs from an existing tag only by case.

func AddEd2kLink(cfg *Config, link string) error

AddEd2kLink queues one ed2k:// file link in aMule. A refusal or a timeout is checked against aMule's queue: aMule refuses a file it already has, and it can stall for a while when it creates a large part file, yet in both cases the file is queued and the add has done its job.

func AddParsedRelease

func AddParsedRelease(s *AppState, release models.Release) (int, any)

AddParsedRelease queues a release chosen for the library: an eD2k link through aMule, a magnet or a .torrent URL through the active torrent engine.

func AddRelease

func AddRelease(s *AppState, release models.Release) (int, any)

AddRelease queues a release chosen for the library, falling back to a search of its title when its URL cannot be fetched.

func AddSearchRelease

func AddSearchRelease(s *AppState, release models.Release) (int, any)

AddSearchRelease queues a free search result: it is downloaded into the download folder and stays there, outside the library.

func AddSearchResult

func AddSearchResult(w http.ResponseWriter, r *http.Request, s *AppState)

AddSearchResult is the handler of POST /api/search/add: it queues a result chosen in the interface.

func AddTorrentHandler

func AddTorrentHandler(w http.ResponseWriter, r *http.Request, s *AppState)

AddTorrentHandler adds a torrent with the options carried by the request: start paused, sequential, seed mode, queue position, preallocation, a preferred save path and the no-rename flag.

func ApplyEngineOverride

func ApplyEngineOverride(cfg *Config) string

ApplyEngineOverride rewrites the backend setting from EngineOverrideEnv when it names a known engine. It reports the applied backend (empty when nothing was overridden). The saved setting is left untouched, so the override lasts only for this run: a later start without the variable keeps the stored choice.

func ApplyLibraryBulkEdit

func ApplyLibraryBulkEdit(series []SeriesConfig, movies []MovieConfig, edit LibraryBulkEdit) ([]SeriesConfig, []MovieConfig, int, error)

ApplyLibraryBulkEdit returns copies of series and movies with the edit applied to the selected titles, and how many titles it touched. The input slices are never modified: they may be the shared cached configuration.

func ApplyMovieMetadata

func ApplyMovieMetadata(w http.ResponseWriter, r *http.Request, s *AppState)

func ApplySidecars

func ApplySidecars(source, target string, cfg *Config)

ApplySidecars applies the sidecar rename and logs the outcome (implementation of `apply_sidecars`).

func ApplySidecarsTo

func ApplySidecarsTo(source, target string, cfg *Config)

ApplySidecarsTo moves the sidecars of source into the directory of target, renaming them after the target stem. Used when the video moves to a different directory (manual archive): RenameSidecars would only rename them in place in the source folder, leaving the archived video without subtitles/NFO.

func ApplyTuning

func ApplyTuning(dataDir string, cfg *Config, proposals []TuningProposal, chosen map[string]bool) (int, error)

ApplyTuning writes the confirmed proposals. It applies only the keys the caller confirmed, using the proposed value the server computed itself (never a value taken from the request), each through validateSettingValue. A key that is not in the proposal list is ignored, so the request can never write a setting the tuning did not suggest. Every write is recorded as "auto" with the reason, so re-optimizing recognises its own values and the user's stay theirs.

func ArchiveAndRemoveTorrent

func ArchiveAndRemoveTorrent(s *AppState, cfg *Config, hash string) (bool, error)

ArchiveAndRemoveTorrent stops a completed torrent from seeding, moves its files to the configured NAS archive destination (or default download dir if none is configured), performs filename renaming and quality checks, updates database records, and unloads the torrent from the engine.

func ArchiveEntries

func ArchiveEntries(w http.ResponseWriter, r *http.Request, s *AppState)

ArchiveEntries handles GET /api/archive.

func ArchiveImportAnyBusy

func ArchiveImportAnyBusy() bool

ArchiveImportAnyBusy reports whether any operation holds a series archive: a copy into the library or the audio cleanup of the library.

func ArchiveImportBusyContains

func ArchiveImportBusyContains(name string) bool

ArchiveImportBusyContains reports whether a copy or the audio cleanup is working on the series.

func ArchiveMovieQuality

func ArchiveMovieQuality(cfg *Config, release *models.Release) *models.ArchiveQuality

ArchiveMovieQuality finds the best matching movie already present in the configured archive root. It is the pre-download counterpart of DiscardIfInferiorMovie: a movie file can exist on the library volume while its database row is missing (legacy import, manual copy, a removed row or a rebuilt database). Without this check the cycle would download it again and only discard it after completion, wasting the whole transfer.

func ArchiveQuality

func ArchiveQuality(cfg *Config, release *models.Release) *models.ArchiveQuality

ArchiveQuality scans the configured series archive. This is deliberately exposed to the HTTP layer so it can run in a blocking task; walking a NAS must not occupy a worker.

func ArchiveURL

func ArchiveURL(repo, release, arch string) string

ArchiveURL builds the release asset URL for a repository, release and architecture.

func AudioAllowed

func AudioAllowed(quality *models.Quality, requirement, channels string) bool

AudioAllowed applies the per-title minimum audio group and channel layout. The empty value (the UI "Qualsiasi") accepts every audio track, so existing titles keep their behaviour. A title with a requirement rejects releases whose track is below it; a missing or unrecognised track never guesses.

func AudioCleanupAvailable

func AudioCleanupAvailable() bool

AudioCleanupAvailable reports whether the feature can run at all.

func AudioCleanupMissingTools

func AudioCleanupMissingTools() []string

AudioCleanupMissingTools lists the external binaries the feature needs and that are not on PATH. All three are required: ffprobe decides and checks, ffmpeg is the second remuxer, mkvmerge is the first one for Matroska.

func AudioLabel

func AudioLabel(codec string) (string, bool)

AudioLabel maps an ffprobe codec name to a Gextto quality audio label.

func AuthMiddleware

func AuthMiddleware(s *AppState, next http.Handler) http.Handler

AuthMiddleware enforces the optional access control in front of every route. With access control off (the default) it only forwards the request.

func Available

func Available() bool

Available reports whether `ffprobe` can be executed. It lets the scheduler skip runs instead of retrying every entry when the binary is missing.

func BackfillMediaInfo

func BackfillMediaInfo(w http.ResponseWriter, r *http.Request, s *AppState)

func BackupExtraPaths

func BackupExtraPaths(value string) []string

BackupExtraPaths parses the backup_extra_paths setting: absolute paths of files or folders to add to the archive, one per line (commas are accepted too). Empty fields and relative paths are ignored, so a stray line never points the backup at an unexpected place.

func BackupSendTelegram

func BackupSendTelegram(w http.ResponseWriter, r *http.Request, s *AppState)

func BackupSettings

func BackupSettings(w http.ResponseWriter, r *http.Request, s *AppState)

BackupSettings returns the backup options stored in settings, with their defaults, and tells whether an FTP password is set without revealing it.

func BackupTestFtp

func BackupTestFtp(w http.ResponseWriter, r *http.Request, s *AppState)

BackupTestFtp runs connection, login, path, upload and delete against the FTP server configured or sent in the request, and returns the outcome of every step.

func BatchArchiveDownload

func BatchArchiveDownload(w http.ResponseWriter, r *http.Request, s *AppState)

BatchArchiveDownload queues 1-100 archive results, each one by eD2k link or by torrent, and reports which ones were accepted.

func BestEpisodeFile

func BestEpisodeFile(dir string, season, episode int64) (string, bool)

BestEpisodeFile returns the best-quality video file in dir matching the given season/episode (implementation of `best_episode_file`).

func BestEpisodeFileFromFiles

func BestEpisodeFileFromFiles(files []string, season, episode int64) (string, bool)

BestEpisodeFileFromFiles is BestEpisodeFile over an already-enumerated file list, so callers that process many episodes can walk the directory once instead of once per episode.

func BitDepthFromPixFmt

func BitDepthFromPixFmt(pixFmt string) int64

BitDepthFromPixFmt is a best-effort bit depth from the pixel format: `yuv420p10le` -> 10, `yuv420p` -> 8. Falls back to 8 when unknown.

func BlocklistEntries

func BlocklistEntries(w http.ResponseWriter, r *http.Request, s *AppState)

func BrowseDir

func BrowseDir(w http.ResponseWriter, r *http.Request, s *AppState)

BrowseDir lists the sub-folders of a directory for the folder pickers. With files=video it also lists the video files, for the pickers that choose a file (manual import).

func BrowserHandlerDownload

func BrowserHandlerDownload(w http.ResponseWriter, r *http.Request, s *AppState)

BrowserHandlerDownload handles GET /api/browser-handlers/download.

func CacheGet

func CacheGet(key string, ttl time.Duration) (map[string]any, bool)

CacheGet returns a cached JSON payload younger than ttl.

func CachePut

func CachePut(key string, value map[string]any)

CachePut stores a JSON payload in the short-lived response cache.

func Calendar

func Calendar(w http.ResponseWriter, r *http.Request, s *AppState)

func CalendarICS

func CalendarICS(w http.ResponseWriter, r *http.Request, s *AppState)

CalendarICS serves GET /feed/calendar.ics.

func CancelHTTPDownload

func CancelHTTPDownload(id string, deleteFiles bool) bool

CancelHTTPDownload removes a download from the list. With deleteFiles it also deletes the partial `.part` file and the finished file. MEGA downloads (which have no control) are only removed from the list.

func CapabilityMatrix

func CapabilityMatrix(backend string) map[string]string

CapabilityMatrix returns the explicit capability/level map for a backend.

func CapabilityParity

func CapabilityParity() map[string]map[string]string

CapabilityParity returns, for every capability, the level of each backend. It backs the parity test and the UI capability table.

func CategoryDirs

func CategoryDirs(cfg *Config, category string) (temp string, tempOK bool, finalDir string, finalDirOK bool)

CategoryDirs returns the temporary and final directories of a category from the "Percorsi NAS per categoria (tag)" rules. `temp` is only reported when it exists as a directory (implementation of `category_dirs`).

func CategoryDownloadDir

func CategoryDownloadDir(cfg *Config, category string) (string, bool)

CategoryDownloadDir prefers the final destination of a category, then the temporary one (implementation of `category_download_dir`).

func ChannelFromMarker

func ChannelFromMarker(marker string) string

ChannelFromMarker maps the installed release marker to the channel that updates it: a tagged release ("v1.2.3") follows the stable releases ("latest"), anything else ("continuous", "continuous-<sha>") the continuous build. An update never silently switches channel.

func CheckPorts

func CheckPorts(w http.ResponseWriter, r *http.Request, s *AppState)

func CheckpointConnection

func CheckpointConnection(db *sql.DB) error

CheckpointConnection checkpoints the WAL and truncates the `-wal` file.

func ClampFloat

func ClampFloat(value, low, high float64) float64

ClampFloat clamps a float to the inclusive range.

func CleanDuplicates

func CleanDuplicates(w http.ResponseWriter, r *http.Request, s *AppState)

CleanDuplicates scans the series archives for inferior duplicates: it lists them, or removes them when execute is set.

func CleanOrphanedDownloads

func CleanOrphanedDownloads(cfg *Config, db *Database, torrents TorrentEngine) (int, int64, error)

CleanOrphanedDownloads re-scans and moves every safe entry to the trash. It returns how many entries and how many bytes were moved. Nothing is deleted when the trash path is not configured.

func CleanTrash

func CleanTrash(w http.ResponseWriter, r *http.Request, s *AppState)

CleanTrash empties the trash folder, honouring the retention days unless force is set.

func CleanupDatabase

func CleanupDatabase(w http.ResponseWriter, r *http.Request, s *AppState)

CleanupDatabase applies the archive retention and then cleans the database.

func CleanupInferiorDuplicatesInDir

func CleanupInferiorDuplicatesInDir(cfg *Config, series, archivePath string, protected map[string]struct{}) (int, error)

CleanupInferiorDuplicatesInDir moves the inferior duplicates found by FindInferiorDuplicatesInDir to the trash.

func CleanupMovieRequirements

func CleanupMovieRequirements(dataDir string) error

CleanupMovieRequirements is a one-time cleanup of legacy/imported dirty movie requirement rows. It also folds the legacy «Lingue richieste» into the movie's single «Lingua»: when present the requirement decided alone, so the language becomes the required list and the requirement is cleared (the decision does not change). A subtitle requirement without a preferred subtitle language gives it one: «Sottotitoli obbligatori» is then just the switch on that language.

func CleanupOldEpisode

func CleanupOldEpisode(cfg *Config, series string, season, episode, newScore int64, newFile, archivePath string) (int, error)

CleanupOldEpisode removes archived files of the same series/season/episode that are clearly inferior to the new file.

func CleanupOldEpisodeWithQuality

func CleanupOldEpisodeWithQuality(cfg *Config, series string, season, episode, newScore int64, newFile, archivePath string, candidateQuality models.Quality) (int, error)

CleanupOldEpisodeWithQuality is used when the caller still has the approved release metadata. The final archive filename intentionally omits some release flags (notably REPACK), so technical tags parsed from the filename are merged with the release quality before comparing older files.

func CleanupOrphanThumbs

func CleanupOrphanThumbs(cfg *Config, archivePath string) (int, error)

CleanupOrphanThumbs removes, below a series folder, the thumbnails whose video no longer exists next to them (renamed or discarded): media servers recreate them for the current files. Other sidecars are left alone.

func ClearComicsHistory

func ClearComicsHistory(w http.ResponseWriter, r *http.Request, s *AppState)

ClearComicsHistory handles POST /api/comics/history/clear.

func ClearComicsWeeklyHistory

func ClearComicsWeeklyHistory(w http.ResponseWriter, r *http.Request, s *AppState)

ClearComicsWeeklyHistory handles POST /api/comics/weekly/history/clear.

func ClearFinishedHTTPDownloads

func ClearFinishedHTTPDownloads() int

ClearFinishedHTTPDownloads removes completed/errored downloads from the list, keeping their files.

func ClearProvidersStatus

func ClearProvidersStatus(w http.ResponseWriter, r *http.Request, s *AppState)

ClearProvidersStatus drops the saved backoff rows of one provider or of all of them.

func ClearSettingOrigin

func ClearSettingOrigin(dataDir, key string) error

ClearSettingOrigin forgets a setting's origin, used when a value goes back to the default.

func CodecLabel

func CodecLabel(codec string) (string, bool)

CodecLabel maps an ffprobe codec name to a Gextto quality codec label.

func ComicCheckLinks(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicCycle

func ComicCycle(w http.ResponseWriter, r *http.Request, s *AppState)

ComicCycle handles POST /api/comics/cycle.

func ComicDownloadDir

func ComicDownloadDir(cfg *Config) (string, bool)

ComicDownloadDir resolves the comics download folder, accepting both `Comic` and `Fumetto` as the category name (implementation of `comic_download_dir`).

func ComicDownloadHandler

func ComicDownloadHandler(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicDownloadPause

func ComicDownloadPause(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicDownloadRemove

func ComicDownloadRemove(w http.ResponseWriter, r *http.Request, s *AppState)

ComicDownloadRemove cancels a manual comics download, deleting its files when the caller asks for it.

func ComicDownloadResume

func ComicDownloadResume(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicDownloadTag

func ComicDownloadTag(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicDownloads

func ComicDownloads(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicExplore

func ComicExplore(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicLinksHandler

func ComicLinksHandler(w http.ResponseWriter, r *http.Request, s *AppState)

ComicLinksHandler handles POST /api/comics/links.

func ComicWeeklyLinks(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicWeeklySettings

func ComicWeeklySettings(w http.ResponseWriter, r *http.Request, s *AppState)

func Comics

func Comics(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicsHistory

func ComicsHistory(w http.ResponseWriter, r *http.Request, s *AppState)

func ComicsWeekly

func ComicsWeekly(w http.ResponseWriter, r *http.Request, s *AppState)

func CompleteSetup

func CompleteSetup(cfg *Config) error

CompleteSetup writes the setup marker file.

func CompletionPath

func CompletionPath(event *models.TorrentEvent) string

CompletionPath is the path of the completed download inside the torrent's `save_path` (implementation of `completion_path`). `event.name` is untrusted: only its final component is kept, and a missing name never falls back to the shared root.

func ConfigGeneration

func ConfigGeneration() uint64

ConfigGeneration returns the current monotonic configuration generation.

func ConfigView

func ConfigView(w http.ResponseWriter, r *http.Request, s *AppState)

ConfigView returns the configuration snapshot shown by the settings UI.

func ConfigureCloudflareState

func ConfigureCloudflareState(dataDir string)

ConfigureCloudflareState selects the data directory used for the small persisted memory of domains that required FlareSolverr. Cookies and User-Agents are deliberately kept in memory only.

func ConfigureTorrentEngine

func ConfigureTorrentEngine(s *AppState, cfg *Config) error

ConfigureTorrentEngine installs the engine selected by the current settings. It is called at startup and whenever the backend settings change.

func ConfiguredDestinationFor

func ConfiguredDestinationFor(release *models.Release, cfg *Config) (string, bool)

ConfiguredDestinationFor resolves only an explicitly configured archive destination. It deliberately does not fall back to the download directory: folder-shaped downloads must stay there when no NAS/archive is configured.

func ConnectionRowCount

func ConnectionRowCount(db *sql.DB) int64

ConnectionRowCount returns the total number of rows in the user tables of a SQLite connection. SQLite/FTS internal tables are excluded from the count.

func ConnectionSizeBytes

func ConnectionSizeBytes(db *sql.DB) int64

ConnectionSizeBytes estimates the database size in bytes (page_count × page_size).

func Consume

func Consume(path string, delete bool) error

Consume removes a successfully imported file, or renames it to `*.imported` when `delete` is false so the scanner does not pick it up again.

func CopyMatchingPackFiles

func CopyMatchingPackFiles(source, destination string, release *models.Release) ([]string, error)

CopyMatchingPackFiles copies only the pack files whose identity agrees with the release metadata (implementation of `copy_matching_pack_files`).

func CopyPackFiles

func CopyPackFiles(source, destination string) ([]string, error)

CopyPackFiles copies every video file of a season pack flat into destination without removing the source (implementation of `copy_pack_files`).

func CopySnapshot

func CopySnapshot(archive, targetDir string) (string, error)

CopySnapshot copies a snapshot to an external directory (e.g. a cloud-synced folder or a mounted remote), creating the destination if needed. It returns the copy path.

func CreateBackup

func CreateBackup(w http.ResponseWriter, r *http.Request, s *AppState)

CreateBackup creates a snapshot, copies it to FTP, to the cloud directory and to Telegram as configured, sends the backup_completed notification and answers with the outcome of each step.

func CreateRamdisk

func CreateRamdisk(w http.ResponseWriter, r *http.Request, s *AppState)

CreateRamdisk creates /dev/shm/gextto and saves it as the RAM disk of the downloads.

func CreateSnapshot

func CreateSnapshot(dataDir, backupRoot string, retain int) (string, error)

CreateSnapshot creates a zip archive of the configuration files plus transaction-consistent snapshots of the live databases, then prunes the existing archives keeping the newest `retain` ones.

func CreateSnapshotWithExtras

func CreateSnapshotWithExtras(dataDir, backupRoot string, retain int, extras []string) (string, error)

CreateSnapshotWithExtras is CreateSnapshot plus the files and folders listed in backup_extra_paths, stored under extra/ in the archive.

func Cycles

func Cycles(w http.ResponseWriter, r *http.Request, s *AppState)

Cycles handles GET /api/cycles (and the aliases routed to it).

func DbAction

func DbAction(w http.ResponseWriter, r *http.Request, s *AppState)

func DbInfo

func DbInfo(w http.ResponseWriter, r *http.Request, s *AppState)

func DbPrune

func DbPrune(w http.ResponseWriter, r *http.Request, s *AppState)

DbPrune prunes the series database (old cycles, old errors, seen entries) and reports what it removed.

func DbPruneByIds

func DbPruneByIds(w http.ResponseWriter, r *http.Request, s *AppState)

DbPruneByIds prunes the given seen rows, movies and series, by id.

func DbPruneKeyword

func DbPruneKeyword(w http.ResponseWriter, r *http.Request, s *AppState)

DbPruneKeyword removes the archived releases matching the given keywords; with preview it only counts and lists them.

func DbPrunePreview

func DbPrunePreview(w http.ResponseWriter, r *http.Request, s *AppState)

DbPrunePreview reports what DbPrune would remove without modifying the database.

func DebugTorrentMatch

func DebugTorrentMatch(w http.ResponseWriter, r *http.Request, s *AppState)

DebugTorrentMatch ports extto's `debug_torrent_match`: given a torrent or file name (`?name=...`) it reports how gextto parses it and which configured series it matches, plus whether the target folders exist. It is a diagnostic aid, not part of the acquisition flow.

func DecodeMountField

func DecodeMountField(value string) string

DecodeMountField decodes the octal escaping used for mount points in /proc/self/mountinfo.

func DecodeOptionalJSON

func DecodeOptionalJSON(w http.ResponseWriter, r *http.Request, target any) bool

DecodeOptionalJSON decodes a request body that may be absent: an empty body leaves the target at its zero value, a malformed one answers 400.

func DecorateTorrents

func DecorateTorrents(s *AppState, items []models.TorrentView) []map[string]any

DecorateTorrents turns the torrent views into the maps the API returns, adding the archive state, the stall information and the progress of the downloads that are finished or archived.

func DefaultMetadataSource

func DefaultMetadataSource() string

DefaultMetadataSource is `default_metadata_source`.

func DefaultTmdbKind

func DefaultTmdbKind() string

DefaultTmdbKind is `default_tmdb_kind`.

func DeleteArchiveEntry

func DeleteArchiveEntry(w http.ResponseWriter, r *http.Request, s *AppState)

DeleteArchiveEntry removes the archive entries given by id, or the one matching the magnet.

func DeleteComicsHistory

func DeleteComicsHistory(w http.ResponseWriter, r *http.Request, s *AppState)

DeleteComicsHistory handles POST /api/comics/history/delete.

func DeleteEpisode

func DeleteEpisode(w http.ResponseWriter, r *http.Request, s *AppState)

func DeleteMovie

func DeleteMovie(w http.ResponseWriter, r *http.Request, s *AppState)

func DeleteSeries

func DeleteSeries(w http.ResponseWriter, r *http.Request, s *AppState)

DeleteSeries removes one series from the monitored library.

func DeleteSetting

func DeleteSetting(dataDir string, key string) (bool, error)

DeleteSetting removes one setting from `gextto_config.db`, reporting whether a row was actually deleted.

func DeleteSettingHandler

func DeleteSettingHandler(w http.ResponseWriter, r *http.Request, s *AppState)

DeleteSettingHandler deletes a custom score group; only `score_group_` keys are accepted here.

func DeleteTrashEntries

func DeleteTrashEntries(w http.ResponseWriter, r *http.Request, s *AppState)

DeleteTrashEntries deletes the named entries of the trash, or all of them.

func DestinationFor

func DestinationFor(release *models.Release, cfg *Config) (string, bool)

DestinationFor resolves the archive folder of a release (implementation of `destination_for`). Its historical download-directory fallback remains for direct single-file downloads; folder-shaped downloads use ConfiguredDestinationFor when they must distinguish a real archive from the download area.

func DetachCompletedArchivedSingles

func DetachCompletedArchivedSingles(cfg *Config, torrents TorrentSession, db *Database, notDetachable map[string]time.Time)

DetachCompletedArchivedSingles implements `detach_completed_archived_singles`. notDetachable, when not nil, remembers until when a torrent was found not to be detached, so the 750 ms tick does not query the database and stat the archive for every seeding torrent.

func DetachErrorTorrents

func DetachErrorTorrents(torrents TorrentSession, db *Database, startupHashes map[string]struct{}, notError map[string]time.Time)

DetachErrorTorrents implements `detach_error_torrents`: it removes torrents that were already in the session when the daemon started and are persisted as `error` (a leftover from a previous run; files are kept). Torrents added later are never detached this way, so re-adding a previously failed torrent works. notError, when not nil, remembers until when a torrent was found not in error, so the 750 ms tick does not query every torrent kept from the startup.

func DetectedRamdiskMounts

func DetectedRamdiskMounts() [][2]string

DetectedRamdiskMounts returns the mounted tmpfs/ramfs roots visible to the daemon, sorted by path and de-duplicated.

func DiagnoseTorrent

func DiagnoseTorrent(torrent *models.TorrentView) (code, reason, hint string)

DiagnoseTorrent explains a torrent's situation as a short machine code plus a human reason and hint. It makes extreme cases explicit (no seeders, a leechers-only swarm, missing metadata, dead trackers) in the logs and in the GET /api/torrents/{hash}/why endpoint.

func DirectorySize

func DirectorySize(path string) uint64

DirectorySize is the total size in bytes of a directory and everything in it.

func DirectoryWritable

func DirectoryWritable(path string) bool

DirectoryWritable reports whether the daemon can write to path.

func DiscardIfInferior

func DiscardIfInferior(cfg *Config, series string, season, episode, newScore int64, newFile, archivePath string) (bool, error)

DiscardIfInferior reports whether the incoming file must be discarded because an existing file of the same series/season/episode is better. When it returns true the incoming file has been handled as a duplicate.

func DiscardIfInferiorMovie

func DiscardIfInferiorMovie(cfg *Config, movie string, year *int64, newScore int64, newFile, archivePath string, incoming *models.Quality) (bool, error)

DiscardIfInferiorMovie reports whether the incoming movie file must be discarded because an existing file of the same movie is better.

func DiscardIfInferiorWithQuality

func DiscardIfInferiorWithQuality(cfg *Config, series string, season, episode, newScore int64, newFile, archivePath string, incoming *models.Quality) (bool, error)

DiscardIfInferiorWithQuality is DiscardIfInferior with the release quality preserved across a display-name rename. In particular, normalized archive filenames intentionally omit markers such as REPACK, but that marker remains meaningful to the replacement policy.

func DiscardSidecars

func DiscardSidecars(source string, cfg *Config) (int, error)

DiscardSidecars moves the sidecars of a discarded duplicate video to the trash (implementation of `discard_sidecars`).

func DismissUpdateNotes

func DismissUpdateNotes(cfg *Config)

DismissUpdateNotes removes the notes once the popup was closed.

func Dispatch

func Dispatch(hooks []EventHook, event string, payload map[string]any)

Dispatch dispatches hooks for one event on a detached goroutine. It never blocks the caller (notification delivery) and logs each outcome.

func DownloadAndAdd

func DownloadAndAdd(s *AppState, rawURL string, options AddOptions) (*string, error)

DownloadAndAdd adds a magnet link, or fetches and adds a .torrent file; it returns the info hash, and nil when the torrent was already there.

func DownloadDirFor

func DownloadDirFor(release *models.Release, cfg *Config) (string, bool)

DownloadDirFor returns the per-tag temporary download directory for a release, if configured (implementation of `download_dir_for`).

func DownloadHTTP

func DownloadHTTP(client *http.Client, rawURL, targetDir, title string) (string, error)

DownloadHTTP is the awaited HTTP download used by the automatic comics cycle. It registers a row and controls so it can still be paused or removed from the UI.

func DownloadMega

func DownloadMega(executable, rawURL, targetDir string) (string, error)

DownloadMega downloads a MEGA URL with an external downloader.

func DownloadTagsList

func DownloadTagsList(w http.ResponseWriter, r *http.Request, s *AppState)

func DownloadTorrentFile

func DownloadTorrentFile(client *http.Client, rawURL, targetDir string) (string, error)

DownloadTorrentFile downloads a `.torrent` file to targetDir.

func DryRunSessionPreview

func DryRunSessionPreview(s *AppState) []models.TorrentView

DryRunSessionPreview builds the torrent rows shown in dry-run from the stored torrents that still have a fastresume file in the state directory.

func Ed2kDownloadAction

func Ed2kDownloadAction(cfg *Config, action, hash string) error

Ed2kDownloadAction pauses, resumes or removes a download by MD4 hash. A completed file is only taken off the list: its data stays in aMule's incoming folder (and in the library, if it was imported).

func Ed2kDownloadActionAPI

func Ed2kDownloadActionAPI(w http.ResponseWriter, r *http.Request, s *AppState)

Ed2kDownloadActionAPI implements `POST /api/ed2k/downloads/{hash}/{action}` for pause, resume and remove.

func Ed2kDownloads

func Ed2kDownloads(cfg *Config) []amule.Download

Ed2kDownloads returns aMule's download queue, or nil when the integration is off or the core cannot be reached.

func Ed2kDownloadsAPI

func Ed2kDownloadsAPI(w http.ResponseWriter, r *http.Request, s *AppState)

Ed2kDownloadsAPI implements `GET /api/ed2k/downloads`.

func Ed2kLimits

func Ed2kLimits(cfg *Config) (amule.Preferences, error)

Ed2kLimits returns aMule's global bandwidth limits in KiB/s.

func Ed2kLimitsAPI

func Ed2kLimitsAPI(w http.ResponseWriter, r *http.Request, s *AppState)

Ed2kLimitsAPI implements `GET` and `POST /api/ed2k/limits`.

func Ed2kLogAPI

func Ed2kLogAPI(w http.ResponseWriter, r *http.Request, s *AppState)

Ed2kLogAPI implements `GET /api/ed2k/log`.

func Ed2kLogLines

func Ed2kLogLines(cfg *Config) ([]string, error)

Ed2kLogLines returns aMule's log, newest last.

func Ed2kPriorityAPI

func Ed2kPriorityAPI(w http.ResponseWriter, r *http.Request, s *AppState)

Ed2kPriorityAPI implements `POST /api/ed2k/downloads/{hash}/priority`.

func Ed2kRuntimeStatus

func Ed2kRuntimeStatus(cfg *Config) map[string]any

Ed2kRuntimeStatus is the state shown by diagnostics and the settings page.

func Ed2kSetPriority

func Ed2kSetPriority(cfg *Config, hash, name string) error

Ed2kSetPriority changes the priority of one download (low, normal, high or auto).

func Ed2kSharedAPI

func Ed2kSharedAPI(w http.ResponseWriter, r *http.Request, s *AppState)

Ed2kSharedAPI implements `GET /api/ed2k/shared`.

func Ed2kSharedReloadAPI

func Ed2kSharedReloadAPI(w http.ResponseWriter, r *http.Request, s *AppState)

Ed2kSharedReloadAPI implements `POST /api/ed2k/shared/reload`.

func Ed2kStatus

func Ed2kStatus(w http.ResponseWriter, r *http.Request, s *AppState)

Ed2kStatus implements `GET /api/ed2k/status`.

func EnforceSeedPolicy

func EnforceSeedPolicy(cfg *Config, torrents TorrentSession, db *Database, postSeedMoves map[string]struct{}, retries map[string]StorageMoveRetry, seedCopyWarnings map[string]time.Time)

EnforceSeedPolicy implements `enforce_seed_policy`.

func EnsureComicsSchema

func EnsureComicsSchema(db *sql.DB) error

EnsureComicsSchema creates the comics tables and applies the `post_url` migration, mirroring `comics::ensure_schema`.

func EpisodeNameConforms

func EpisodeNameConforms(path string, release *models.Release, cfg *Config) bool

EpisodeNameConforms reports whether a file already follows the configured rename format, without TMDB or MediaInfo (implementation of `episode_name_conforms`).

func EpisodeSources

func EpisodeSources(w http.ResponseWriter, r *http.Request, s *AppState)

EpisodeSources returns the sources already collected for one episode. It is deliberately read-only: opening the list must not start another search.

func EventHooksView

func EventHooksView(w http.ResponseWriter, r *http.Request, s *AppState)

func Expand

func Expand(template string, vars map[string]string) string

Expand expands `{key}` placeholders. Unknown keys are left untouched so a typo is visible in the executed arguments instead of silently vanishing.

func ExplainRelease

func ExplainRelease(w http.ResponseWriter, r *http.Request, s *AppState)

ExplainRelease is the handler of POST /api/search/explain: it returns the trace of the decision taken on a release.

func ExportMagnet

func ExportMagnet(w http.ResponseWriter, r *http.Request, s *AppState)

ExportMagnet handles GET /api/torrents/{hash}/magnet. With ?raw=1 it answers with the magnet itself as text/plain, for the "open the magnet" link of the detail page; without it the usual JSON body is returned.

func ExportTorrent

func ExportTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

func Favicon

func Favicon(w http.ResponseWriter, r *http.Request, s *AppState)

Favicon serves the site favicon.

func FeedStatus

func FeedStatus(w http.ResponseWriter, r *http.Request, s *AppState)

func FetchFeed

func FetchFeed(ctx context.Context, rawURL string, flaresolverr *string, maxPages int, maxAgeDays int64, oldRatio float64) ([]models.Release, error)

FetchFeed downloads a feed/listing and parses it. ext.to / Corsaro / TorrentGalaxy are HTML listings, not RSS. Every release carries the feed line it came from, so the archive can tell the rows of a feed removed from Sources apart from the ones still configured.

func FetchTorznab

func FetchTorznab(ctx context.Context, indexer IndexerConfig, query string) ([]models.Release, error)

FetchTorznab runs a Torznab search without FlareSolverr or external ids.

func FetchTorznabFlareSolverr

func FetchTorznabFlareSolverr(ctx context.Context, indexer IndexerConfig, query string, externalIDs [][2]string, flaresolverr *string) ([]models.Release, error)

FetchTorznabFlareSolverr runs a Torznab search with an optional FlareSolverr fallback when the indexer blocks the request (Cloudflare / 403).

func FetchTorznabWith

func FetchTorznabWith(ctx context.Context, indexer IndexerConfig, query string, externalIDs [][2]string) ([]models.Release, error)

FetchTorznabWith runs a Torznab search with extra external-id query pairs.

func FilesystemSpace

func FilesystemSpace(path string) (uint64, uint64, bool)

FilesystemSpace returns (total, free, ok) bytes for the filesystem holding path.

func FindEpisodeFile

func FindEpisodeFile(dir string, season, episode int64) (string, bool)

FindEpisodeFile returns the single video file for a season/episode inside a directory, if exactly one matches (implementation of `find_episode_file`).

func FlaresolverrTest

func FlaresolverrTest(w http.ResponseWriter, r *http.Request, s *AppState)

FlaresolverrTest asks the configured FlareSolverr for its session list and reports the status it answers with.

func ForceEpisode

func ForceEpisode(w http.ResponseWriter, r *http.Request, s *AppState)

func FreeSpaceBytes

func FreeSpaceBytes(path string) *uint64

FreeSpaceBytes returns the free space in bytes for the filesystem containing path, or nil when it cannot be determined.

func Gaps

func Gaps(w http.ResponseWriter, r *http.Request, s *AppState)

func GenerateAccessKey

func GenerateAccessKey(w http.ResponseWriter, r *http.Request, s *AppState)

GenerateAccessKey implements POST /api/access/generate-key: it creates a strong random value for one of the access secrets, stores it and returns it once, so the operator can copy it. The gx-torrent token is passed to the daemon at launch, so a new value applies at the next gx-torrent restart.

func GetTempLimits

func GetTempLimits(w http.ResponseWriter, r *http.Request, s *AppState)

GetTempLimits reports the speed policy in force: the temporary limit (with its expiry), the bandwidth schedule and the base limits, plus which one is applied now. The TUI shows it on the downloads tab.

func HDRFromStream

func HDRFromStream(stream map[string]any) string

HDRFromStream maps ffprobe colour metadata to a display HDR label. Dolby Vision is detected from the DOVI side data first, then HLG/PQ from the transfer.

func HTTPDownload

func HTTPDownload(ctx context.Context, rawURL string, headers map[string]string, writer io.Writer) (int64, error)

HTTPDownload streams a URL into a file writer, returning the byte count. The stream is capped so a misconfigured or hostile source cannot fill the target volume through an unbounded copy.

func HTTPGet

func HTTPGet(ctx context.Context, rawURL string, headers map[string]string) (*http.Response, error)

HTTPGet performs a GET request.

func HTTPGetBytes

func HTTPGetBytes(ctx context.Context, rawURL string, headers map[string]string) ([]byte, int, error)

HTTPGetBytes performs a GET and returns the body plus status code.

func HTTPGetString

func HTTPGetString(ctx context.Context, rawURL string, headers map[string]string) (string, int, error)

HTTPGetString performs a GET and returns the body as a string.

func HTTPPostJSON

func HTTPPostJSON(ctx context.Context, rawURL string, headers map[string]string, payload []byte) ([]byte, int, error)

HTTPPostJSON posts a JSON payload and returns the response body and status.

func HTTPRequest

func HTTPRequest(ctx context.Context, method, rawURL string, headers map[string]string, body []byte, contentType string) (*http.Response, error)

HTTPRequest performs an HTTP request with the given headers and body.

func HandleTorrentEvent

func HandleTorrentEvent(cfg *Config, torrents TorrentSession, db *Database, moveRequests map[string]struct{}, postSeedMoves map[string]struct{}, retries map[string]StorageMoveRetry, event models.TorrentEvent, tmdb *TmdbClient, notifier *Notifier) (bool, error)

HandleTorrentEvent implements `handle_torrent_event`: one engine event of a download, dispatched by phase. Engine alerts are handled before the release lookup; a torrent Gextto did not choose is only marked completed; the rest follow the download from its metadata to the library.

func HardenConnection

func HardenConnection(db *sql.DB) error

HardenConnection sets the durability/concurrency pragmas shared by all Gextto databases.

func HealthApi

func HealthApi(w http.ResponseWriter, r *http.Request, s *AppState)

HealthApi returns the system health report, cached for 8 seconds.

func HealthProbeURL

func HealthProbeURL(indexer IndexerConfig) string

HealthProbeURL is the read-only endpoint used by the health check. For Jackett `t=caps` validates both the service and the API key. For Prowlarr the native status endpoint validates the key and the service (the Torznab `caps` endpoint is not reliable on aggregate search).

func HistoryTimestampLocal

func HistoryTimestampLocal(value string) (time.Time, bool)

HistoryTimestampLocal parses a stored history timestamp and returns it in the local timezone. The database stores UTC SQLite timestamps; the UI shows local time, so the "Oggi" filter must use the same convention.

func HookMatchesEvent

func HookMatchesEvent(hook EventHook, event string) bool

HookMatchesEvent reports whether a hook subscribes to an event; an empty list means all events.

func I18nActive

func I18nActive(w http.ResponseWriter, r *http.Request, s *AppState)

I18nActive returns the active UI language.

func I18nLanguage

func I18nLanguage(w http.ResponseWriter, r *http.Request, s *AppState)

I18nLanguage switches the active UI language.

func I18nLanguages

func I18nLanguages(w http.ResponseWriter, r *http.Request, s *AppState)

I18nLanguages lists the supported languages.

func IgnoreEpisode

func IgnoreEpisode(w http.ResponseWriter, r *http.Request, s *AppState)

func ImportMigrationManifest

func ImportMigrationManifest(s *AppState, cfg *Config) (int, []string, error)

ImportMigrationManifest re-adds the torrents of a pending manifest into the active backend. It is safe at startup: it only acts when the manifest targets the active backend and is not completed, and re-adding is idempotent. On success the manifest is marked completed so a restart does not repeat it.

func IndexArchive

func IndexArchive(seriesName, archivePath string, cfg *Config) models.ArchiveQualityIndex

IndexArchive implements `index_archive`: scans an archive folder recursively, groups video files by `(season, episode)` and keeps the file with the highest score. It implements the legacy `_best_quality_in_path`/`episode_archive_presence` helpers.

func IndexerTest

func IndexerTest(w http.ResponseWriter, r *http.Request, s *AppState)

IndexerTest is the handler of POST /api/indexer/test: probe a single indexer as typed in the editor (which may not be saved yet) and report reachability plus any Torznab application error. It is the per-row "Testa" action of the Indexer editor.

func InspectActiveContent

func InspectActiveContent(cfg *Config, torrents TorrentEngine, db *Database, notifier *Notifier, checked map[string]contentInspectionCheck)

InspectActiveContent removes the torrents whose payload the guard refuses (content_guard.go). checked caches the verdicts so the 750 ms tick does not ask the engine for the file list of every settled torrent.

func InspectActivePacks

func InspectActivePacks(cfg *Config, torrents TorrentEngine, db *Database, notifier *Notifier, checked map[string]packInspectionCheck)

InspectActivePacks checks the packs currently downloading against what the library already has. checked, when not nil, caches the verdicts so the 750 ms tick does not call the engine and the database for every settled pack.

func IpfilterStatus

func IpfilterStatus(w http.ResponseWriter, r *http.Request, s *AppState)

IpfilterStatus reports whether the IP filter is configured and active and how many rules it holds.

func IpfilterUpdate

func IpfilterUpdate(w http.ResponseWriter, r *http.Request, s *AppState)

IpfilterUpdate handles POST /api/torrents/ipfilter_update.

func IsEd2kURL

func IsEd2kURL(value string) bool

IsEd2kURL reports an eD2k file link. Torznab results from an indexarr eD2k source carry it in <link> (and in the ed2k attribute); the release is queued in aMule, not downloaded as a torrent.

func IsTorrentURL

func IsTorrentURL(value string) bool

IsTorrentURL is true per un link HTTP(S) che punta a un file `.torrent`. Jackett does not use a `.torrent` suffix: its download links are `/dl/<indexer>/?path=...`.

func JellyfinRefresh

func JellyfinRefresh(w http.ResponseWriter, r *http.Request, s *AppState)

func JellyfinTest

func JellyfinTest(w http.ResponseWriter, r *http.Request, s *AppState)

func JobsCancel

func JobsCancel(w http.ResponseWriter, r *http.Request, s *AppState)

JobsCancel is `POST /api/jobs/{id}/cancel`: asks a queued or running job to stop. The running function must observe its context (see JobFunc).

func JobsGet

func JobsGet(w http.ResponseWriter, r *http.Request, s *AppState)

JobsGet is `GET /api/jobs/{id}`: one job snapshot.

func JobsList

func JobsList(w http.ResponseWriter, r *http.Request, s *AppState)

JobsList is `GET /api/jobs`: the observable state of background jobs. The optional `kind` and `state` query parameters filter the result.

Phase 3 of the technical review: rename-all, scan-archives and media-info-backfill already publish their jobs here. The endpoints are read-only (creation happens inside each operation); the record shape (id, kind, state, progress, error, result) is covered by jobs_test.go.

func LastCycle

func LastCycle(w http.ResponseWriter, r *http.Request, s *AppState)

func LibraryView

func LibraryView(w http.ResponseWriter, r *http.Request, s *AppState)

LibraryView returns the library configuration with the episode counts and the last download of every series.

func LicenseApi

func LicenseApi(w http.ResponseWriter, r *http.Request, s *AppState)

LicenseApi ports extto's `get_license`: it returns the bundled licence text and the third-party notices.

func ListBackups

func ListBackups(w http.ResponseWriter, r *http.Request, s *AppState)

ListBackups returns the snapshots stored in the backups directory, newest first.

func ListenConflicts

func ListenConflicts(cfg *Config) []string

ListenConflicts reports the configured listen addresses that are already in use by another process, so the daemon can warn only when there is a real conflict (a legacy extto/rextto, or a previous Gextto) instead of doing it unconditionally at every start. It binds and immediately releases each address; a non-EADDRINUSE error is ignored here because Serve will surface it with a proper message.

func LogLevelGet

func LogLevelGet(w http.ResponseWriter, r *http.Request, s *AppState)

func Logs

func Logs(w http.ResponseWriter, r *http.Request, s *AppState)

Logs returns the tail of the daemon log.

func LogsStream

func LogsStream(w http.ResponseWriter, r *http.Request, s *AppState)

LogsStream streams the log tail over SSE and then follows the file, reading only the bytes appended since the previous tick.

func LtMemSuggest

func LtMemSuggest(w http.ResponseWriter, r *http.Request, s *AppState)

LtMemSuggest ports extto's `lt_mem_suggest`: it reads the system RAM and returns the libtorrent session values sized for it (disk cache, queued disk bytes, send buffer and peer list).

func MagnetFeed

func MagnetFeed(w http.ResponseWriter, r *http.Request, s *AppState)

MagnetFeed handles GET /feed.xml (and /api/feed.xml).

func MagnetFromFile

func MagnetFromFile(path string) *string

MagnetFromFile reads the magnet URI from a `.magnet` file (the file may contain extra text; the first `magnet:?` token wins).

func MagnetHandler

func MagnetHandler(w http.ResponseWriter, r *http.Request, s *AppState)

MagnetHandler is the landing page for `magnet:` links.

func MaintenanceRenameFolderApply

func MaintenanceRenameFolderApply(w http.ResponseWriter, r *http.Request, s *AppState)

MaintenanceRenameFolderApply applies only the source/target pairs sent by the review UI. The root and same-directory checks prevent a modified client request from moving files outside the scanned folder.

func MaintenanceRenameFolderScan

func MaintenanceRenameFolderScan(w http.ResponseWriter, r *http.Request, s *AppState)

MaintenanceRenameFolderScan implements the review phase of the arbitrary folder rename tool. It never modifies files.

func MakeDirectory

func MakeDirectory(w http.ResponseWriter, r *http.Request, s *AppState)

func ManagerIndexerHealth

func ManagerIndexerHealth(ctx context.Context, baseURL, apiKey, kind string) ([]map[string]any, error)

ManagerIndexerHealth reads the indexer list and the failure status of a manager and returns one ready-to-render item per indexer, so the Sources view shows which indexers the manager currently considers failing instead of leaving an empty result unexplained. Prowlarr and indexarr answer the same /api/v1/indexer and /api/v1/indexerstatus documents; the kind only labels the row.

func ManualArchiveSearch

func ManualArchiveSearch(w http.ResponseWriter, r *http.Request, s *AppState)

func ManualImport

func ManualImport(ctx context.Context, cfg *Config, db *Database, req ManualImportRequest) (string, error)

ManualImport applies one confirmed candidate. It returns the final path.

func ManualImportAPI

func ManualImportAPI(w http.ResponseWriter, r *http.Request, s *AppState)

ManualImportAPI is POST /api/import with the fields of ManualImportRequest.

func ManualImportPreviewAPI

func ManualImportPreviewAPI(w http.ResponseWriter, r *http.Request, s *AppState)

ManualImportPreviewAPI is GET /api/import/preview?path=…

func ManualSearch

func ManualSearch(w http.ResponseWriter, r *http.Request, s *AppState)

ManualSearch is the handler of POST /api/search, the classic manual search.

func ManualSearchDashboard

func ManualSearchDashboard(w http.ResponseWriter, r *http.Request, s *AppState)

ManualSearchDashboard is the v2 manual search. Unlike the classic endpoint, it keeps globally rejected releases visible because the user is explicitly inspecting arbitrary RSS/indexer/web results and may choose to queue one.

func ManualSearchGet

func ManualSearchGet(w http.ResponseWriter, r *http.Request, s *AppState)

ManualSearchGet runs a manual search for the query in the URL parameters.

func ManualSettings

func ManualSettings(dataDir string) map[string]bool

ManualSettings is the set of keys the user set by hand: the tuning never proposes them again. On a database problem it returns an empty set, so the tuning falls back to "nothing is protected" rather than failing.

func MarkSettingOrigin

func MarkSettingOrigin(dataDir, key string, origin SettingOrigin, detail string) error

MarkSettingOrigin records who wrote a setting and why.

func MarkTorrentFailed

func MarkTorrentFailed(w http.ResponseWriter, r *http.Request, s *AppState)

MarkTorrentFailed blocklists the release of a torrent the user marked as failed and drops it from the session.

func MediaInfoGet

func MediaInfoGet(w http.ResponseWriter, r *http.Request, s *AppState)

MediaInfoGet returns the stored media information of one episode or movie.

func MediaInfoProbe

func MediaInfoProbe(w http.ResponseWriter, r *http.Request, s *AppState)

MediaInfoProbe runs ffprobe on the given path and reports what it returns.

func MediaIntegrityStart

func MediaIntegrityStart(w http.ResponseWriter, r *http.Request, s *AppState)

MediaIntegrityStart begins (or resumes) the check. It answers 202 at once: the scan runs in the background and its progress is read from GET /api/maintenance/media-integrity.

func MediaIntegrityStatusAPI

func MediaIntegrityStatusAPI(w http.ResponseWriter, r *http.Request, s *AppState)

MediaIntegrityStatusAPI returns the saved position, the counters and the damaged files of the last pass.

func MediaIntegrityStop

func MediaIntegrityStop(w http.ResponseWriter, r *http.Request, s *AppState)

MediaIntegrityStop asks the running check to stop after the current file. The saved position is kept, so the next start resumes from there.

func MergeQuality

func MergeQuality(primary, fallback models.Quality) models.Quality

MergeQuality combina due `Quality`: usa i campi di `primary` quando valorizzati, altrimenti quelli di `fallback`. Serve a recuperare sorgente/codec/ecc. dal titolo originale della release quando il nome file attuale li ha persi.

func MonitorEd2kStalled

func MonitorEd2kStalled(cfg *Config, db *Database, notifier *Notifier, now time.Time)

MonitorEd2kStalled gives up on eD2k downloads Gextto started by itself that received nothing for ed2k_stall_days: a rare file can sit in aMule's queue for ever, and while it does the episode counts as being downloaded, so the gap filler would never look for it elsewhere. The download is cancelled in aMule, the release is blocklisted and the gap is searched again at the next cycle. Downloads added by hand and paused ones are left alone: the user chose to wait for them.

func MonitorMetadata

func MonitorMetadata(cfg *Config, torrents TorrentSession, db *Database, notifier *Notifier, waitStart, firstSeen, lastWarning map[string]time.Time)

MonitorMetadata implements `monitor_metadata`. The retry cadence and give-up policy are unchanged; the repeated warning is rate-limited, and the wait start is kept in the database so a restart does not restart the give-up clock.

func MonitorStalled

func MonitorStalled(cfg *Config, torrents TorrentSession, db *Database, notifier *Notifier, watch map[string]StallWatch)

MonitorStalled implements `monitor_stalled`.

func MoveSidecarsToTarget

func MoveSidecarsToTarget(source, target string, cfg *Config) ([][2]string, error)

MoveSidecarsToTarget moves the sidecar files sitting next to source into the directory of target, renamed after the target stem.

func MoveToTrash

func MoveToTrash(source, trash string) (string, error)

MoveToTrash moves a file or directory to the trash with a unique name; it falls back to a recursive copy + remove when the trash is on another filesystem (a plain rename fails with EXDEV, typical with a NAS).

func MoveTorrentStorage

func MoveTorrentStorage(w http.ResponseWriter, r *http.Request, s *AppState)

MoveTorrentStorage handles POST /api/torrents/{hash}/storage.

func MovieDetail

func MovieDetail(w http.ResponseWriter, r *http.Request, s *AppState)

func MovieHistoryHandler

func MovieHistoryHandler(w http.ResponseWriter, r *http.Request, s *AppState)

func MovieList

func MovieList(w http.ResponseWriter, r *http.Request, s *AppState)

func MovieMetadataSearch

func MovieMetadataSearch(w http.ResponseWriter, r *http.Request, s *AppState)

func MovieSearch

func MovieSearch(w http.ResponseWriter, r *http.Request, s *AppState)

func MovieSubtitleBonus

func MovieSubtitleBonus(movie *MovieConfig, quality *models.Quality) int64

MovieSubtitleBonus is the optional bonus when the release contains the movie's preferred subtitles ("Sottotitoli" field). It never blocks the download: it only helps prefer, at equal quality, releases that contain them.

func MoviesSeenGroupedView

func MoviesSeenGroupedView(w http.ResponseWriter, r *http.Request, s *AppState)

func MoviesSeenView

func MoviesSeenView(w http.ResponseWriter, r *http.Request, s *AppState)

func NetworkInterfacesView

func NetworkInterfacesView(w http.ResponseWriter, r *http.Request, s *AppState)

NetworkInterfacesView handles GET /api/network/interfaces.

func NightMaintenanceForgetAPI

func NightMaintenanceForgetAPI(w http.ResponseWriter, r *http.Request, s *AppState)

NightMaintenanceForgetAPI answers POST /api/maintenance/night/forget: the episode is marked missing, so the search downloads it again.

func NightMaintenanceRunAPI

func NightMaintenanceRunAPI(w http.ResponseWriter, _ *http.Request, _ *AppState)

NightMaintenanceRunAPI answers POST /api/maintenance/night/run: one pass now, outside the window. Busy downloads and imports still make it wait.

func NightMaintenanceStatusAPI

func NightMaintenanceStatusAPI(w http.ResponseWriter, _ *http.Request, s *AppState)

NightMaintenanceStatusAPI answers GET /api/maintenance/night.

func NormalizeSeriesName

func NormalizeSeriesName(value string) string

NormalizeSeriesName normalizza il nome di una serie per il confronto.

func NotificationsStream

func NotificationsStream(w http.ResponseWriter, r *http.Request, s *AppState)

NotificationsStream pushes torrent lifecycle events over SSE as they appear.

func OpenConfigDB

func OpenConfigDB(path string) (*sql.DB, error)

OpenConfigDB opens the shared `gextto_config.db` (used by the daemon, i18n and libtorrent) with the pragmas required for concurrent access: WAL journal mode and a busy timeout, so a concurrent writer waits instead of failing with `SQLITE_BUSY` and silently losing the update.

func OpenSQLite

func OpenSQLite(path string) (*sql.DB, error)

OpenSQLite opens a SQLite database with conservative pragmas (`busy_timeout`, WAL, foreign keys, synchronous FULL). A single connection is kept so concurrent goroutines never race on write locks.

func OptimizeConnection

func OptimizeConnection(db *sql.DB, action string) error

OptimizeConnection runs `VACUUM`/`ANALYZE` on an arbitrary connection.

func OptimizeTransferSettings

func OptimizeTransferSettings(w http.ResponseWriter, r *http.Request, s *AppState)

func ParseEd2kRelease

func ParseEd2kRelease(name, link, source string, size, sources int64, discoveredAt time.Time) *models.Release

ParseEd2kRelease turns a Kad/eD2k result into a Release. eD2k names are free-form, so the title parsing is the same one used for torrents: a synthetic infohash built from the MD4 hash lets ParseRelease run its full identity inference, then the magnet is replaced by the eD2k link. Network and Sources are kept separate from SizeBytes/Seeders so the UI and the score cannot mistake an eD2k source count for a BitTorrent swarm.

func ParseEpisodeKey

func ParseEpisodeKey(name string) *models.LiveEpisodeKey

ParseEpisodeKey costruisce la chiave `(nome serie normalizzato, stagione, episodio)` da un nome file o titolo di release. Usata per confrontare le release coi torrent già attivi nella sessione.

func ParseQuality

func ParseQuality(title string) models.Quality

func ParseRelease

func ParseRelease(title, magnet, source string) *models.Release

ParseRelease parses a release discovered now.

func ParseReleaseAt

func ParseReleaseAt(title, magnet, source string, discoveredAt time.Time) *models.Release

ParseReleaseAt parses a release discovered at a given time.

func ParseReleaseSource

func ParseReleaseSource(title, magnet string, torrentURL *string, source string, discoveredAt time.Time) *models.Release

ParseReleaseSource is like [`ParseReleaseAt`], but also accepts a direct `.torrent` link: many RSS feeds (e.g. TorrentLeech) do not expose a magnet, only the `.torrent` download. A release is valid if it has at least one magnet **or** a link.

func PassesMovieFilter

func PassesMovieFilter(title string) bool

PassesMovieFilter is the legacy `Parser.parse_movie` gate: returns false when the release is clearly not a movie (an episode, season pack, wrestling/sport, magazine, videogame, console ROM, or a music release with a genre prefix).

func PathOnRamdisk

func PathOnRamdisk(savePath, ramdisk string) bool

PathOnRamdisk is true when savePath lies inside the ramdisk directory (component-wise, following symlinks when possible).

func PauseHTTPDownload

func PauseHTTPDownload(id string) bool

PauseHTTPDownload pauses a running HTTP download, keeping the `.part` file.

func PauseTorrent

func PauseTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

func PersistMigrationManifest

func PersistMigrationManifest(cfg *Config, manifest MigrationManifest) (string, error)

PersistMigrationManifest writes the manifest atomically so a crash during the switch does not lose the recovery information.

func PinTorrent

func PinTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

PinTorrent pins a torrent and saves its hash among the settings.

func PlexRefresh

func PlexRefresh(w http.ResponseWriter, r *http.Request, s *AppState)

PlexRefresh asks Plex to refresh all of its library sections.

func PlexTest

func PlexTest(w http.ResponseWriter, r *http.Request, s *AppState)

PlexTest probes the configured Plex server and reports its identity.

func PreviewEpisodeRename

func PreviewEpisodeRename(
	ctx context.Context,
	path string,
	release *models.Release,
	cfg *Config,
	tmdb *TmdbClient,
) (string, error)

PreviewEpisodeRename reports only the files that would actually change name (implementation of `preview_episode_rename`).

func ProcessMetricsApi

func ProcessMetricsApi(w http.ResponseWriter, r *http.Request, s *AppState)

ProcessMetricsApi returns the lightweight process-only metrics.

func ProvidersStatusView

func ProvidersStatusView(w http.ResponseWriter, r *http.Request, s *AppState)

ProvidersStatusView returns the provider health rows: the saved backoffs, the live service probes and a row for every configured indexer.

func ProwlarrIndexerHealth

func ProwlarrIndexerHealth(ctx context.Context, baseURL, apiKey string) ([]map[string]any, error)

ProwlarrIndexerHealth reads the indexer list and the failure status of a Prowlarr instance. It is the historical entry point; the indexarr manager speaks the same read-only endpoints, so both go through ManagerIndexerHealth.

func QbitCompatAdd

func QbitCompatAdd(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatAdd handles POST /api/v2/torrents/add: `urls` (magnets and http(s) links) and the uploaded `.torrent` files, with the options a browser extension sends.

func QbitCompatDefaultSavePath

func QbitCompatDefaultSavePath(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatDefaultSavePath handles GET /api/v2/app/defaultSavePath.

func QbitCompatDelete

func QbitCompatDelete(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatDelete handles POST /api/v2/torrents/delete.

func QbitCompatLogin

func QbitCompatLogin(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatLogin handles POST /api/v2/auth/login. The credentials are the ones of Gextto's access control; when that is off (or the client is on the local network with the local exemption on) any credentials are accepted, as a qBittorrent without a password does. A successful login leaves the SID cookie the client echoes on the following calls.

func QbitCompatLogout

func QbitCompatLogout(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatLogout handles POST /api/v2/auth/logout.

func QbitCompatPause

func QbitCompatPause(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatPause handles POST /api/v2/torrents/pause and its 5.x alias stop.

func QbitCompatRecheck

func QbitCompatRecheck(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatRecheck handles POST /api/v2/torrents/recheck.

func QbitCompatResume

func QbitCompatResume(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatResume handles POST /api/v2/torrents/resume and its 5.x alias start.

func QbitCompatTorrentsInfo

func QbitCompatTorrentsInfo(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatTorrentsInfo handles GET /api/v2/torrents/info. Only `hashes` and the common values of `filter` are honoured; sorting, paging and the category/tag filters are not part of the subset.

func QbitCompatTransferInfo

func QbitCompatTransferInfo(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatTransferInfo handles GET /api/v2/transfer/info: the global speeds a client shows in its header.

func QbitCompatVersion

func QbitCompatVersion(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatVersion handles GET /api/v2/app/version.

func QbitCompatWebAPIVersion

func QbitCompatWebAPIVersion(w http.ResponseWriter, r *http.Request, s *AppState)

QbitCompatWebAPIVersion handles GET /api/v2/app/webapiVersion.

func QbittorrentRuntimeUpdate

func QbittorrentRuntimeUpdate(w http.ResponseWriter, r *http.Request, s *AppState)

QbittorrentRuntimeUpdate reports the latest v2 static release and, on POST, downloads it into Gextto's private DATA_DIR/qbittorrent directory. It never touches a system qBittorrent installation.

func QualityAllowed

func QualityAllowed(quality *models.Quality, requirement string, language string, subtitle string) bool

QualityAllowed implements the legacy resolution/language/subtitle checks, kept static for compatibility with tests and callers that have no `Config`.

func QualityProfilesView

func QualityProfilesView(w http.ResponseWriter, r *http.Request, s *AppState)

QualityProfilesView is GET /api/quality-profiles.

func QuickCheck

func QuickCheck(db *sql.DB) ([]string, error)

QuickCheck runs `PRAGMA quick_check` and returns the rows (`["ok"]` when healthy).

func RamdiskCheck

func RamdiskCheck(w http.ResponseWriter, r *http.Request, s *AppState)

RamdiskCheck ports extto's `ramdisk_check` (`?path=...`): it verifies that the path exists, is writable, is actually backed by tmpfs/ramfs and reports its capacity. It complements RamdiskView, which only lists the mounted RAM disks.

func RamdiskEntry

func RamdiskEntry(path string, filesystem string, configured *string) map[string]any

RamdiskEntry implements `ramdisk_entry`.

func RamdiskFits

func RamdiskFits(thresholdBytes, marginBytes, freeBytes, uncommittedBytes, totalSize uint64) error

RamdiskFits decides whether a torrent of totalSize bytes fits on the RAM disk. uncommittedBytes is the space still to be written there by other in-flight torrents.

func RamdiskFitsRemaining

func RamdiskFitsRemaining(thresholdBytes, marginBytes, freeBytes, uncommittedBytes, totalSize, remainingBytes uint64) error

RamdiskFitsRemaining is the space-aware variant: the size threshold still applies to the whole torrent (a file larger than the RAM disk must never be staged there), but the free-space requirement is checked against the bytes that still have to be written (remainingBytes), not the full size.

This matters for a download that is already mostly on the RAM disk: with the full size it would be relocated mid-transfer (risking a corrupted or reset file) even though only a small tail is left. Relocating on the remaining bytes keeps a nearly complete torrent in place.

func RamdiskNeedsMetadata

func RamdiskNeedsMetadata(release *models.Release, cfg *Config) bool

RamdiskNeedsMetadata reports whether an acquisition must be staged off the RAM disk until its metadata reveals the real size. The RAM disk is a small tmpfs: an unknown-size release must not be placed there only to be moved out moments later. The metadata handler then decides whether it fits (`ramdisk_admission`) and moves it onto the tmpfs if so.

This is an engine-independent policy: it only looks at the release size and the configuration, never at the download daemon.

func RamdiskPendingBytes

func RamdiskPendingBytes(view models.TorrentView) uint64

RamdiskPendingBytes is the space a torrent on the RAM disk still has to take there: the bytes not downloaded yet, minus what is already allocated. A payload copied onto the tmpfs from a preallocated file on disk occupies its whole size from the start, so the free space already accounts for it; counting the missing bytes again would require twice the torrent size and push a fitting download off the RAM disk.

func RamdiskRecommendation

func RamdiskRecommendation(path string) map[string]any

RamdiskRecommendation implements `ramdisk_recommendation`.

func RamdiskView

func RamdiskView(w http.ResponseWriter, r *http.Request, s *AppState)

RamdiskView lists the detected RAM disks and reports the state of the configured one.

func ReannounceTorrent

func ReannounceTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

ReannounceTorrent handles POST /api/torrents/{hash}/reannounce.

func RecentDownloads

func RecentDownloads(w http.ResponseWriter, r *http.Request, s *AppState)

func RecheckTorrent

func RecheckTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

func ReconcilePackIdentity

func ReconcilePackIdentity(release *models.Release, torrentName string) *models.Release

ReconcilePackIdentity reconciles a season pack with the name supplied by the torrent itself.

Indexers occasionally publish a title whose season differs from the actual torrent name (for example an RSS title saying `S06E01-06` while the torrent and its files are `S05E01-06`). The legacy importer parsed the completed filenames, so the torrent's identity is authoritative at that point.

func ReconcileRamdisk

func ReconcileRamdisk(cfg *Config, torrents TorrentSession, attempts map[string]time.Time)

ReconcileRamdisk implements `reconcile_ramdisk`.

func RedownloadEpisode

func RedownloadEpisode(w http.ResponseWriter, r *http.Request, s *AppState)

RedownloadEpisode is the "Riscarica" action: it moves the archived file to the trash (so the disk check does not see it), deletes the episode row and records an explicit forced gap, then starts a series search. The forced gap is what makes the episode eligible again even when a season pack covers the season or a later episode is already archived.

func RedownloadMovie

func RedownloadMovie(w http.ResponseWriter, r *http.Request, s *AppState)

func RefreshMediaLibraries

func RefreshMediaLibraries(cfg *Config, folders ...string)

RefreshMediaLibraries asks Jellyfin and Plex to pick up new files. With folders it rescans only those (falling back to a full refresh when that is not possible); without folders it refreshes the whole library.

func RegisteredRoutes

func RegisteredRoutes() []string

RegisteredRoutes returns every HTTP route pattern installed by Router. It is used by the route smoke test to make sure no endpoint returns a 500.

func RejectActivePackIdentityMismatches

func RejectActivePackIdentityMismatches(torrents TorrentSession, db *Database, checked map[string]packIdentityCheck)

RejectActivePackIdentityMismatches implements `reject_active_pack_identity_mismatches`. checked, when not nil, remembers the torrents found consistent so the 750 ms tick does not read and decode every torrent's metadata again.

func ReleaseFitsRamdisk

func ReleaseFitsRamdisk(release *models.Release, cfg *Config) bool

ReleaseFitsRamdisk reports whether a release whose size is already known can be admitted to the RAM disk. An unknown or non-positive size is treated as fitting here; the add path pairs this with RamdiskNeedsMetadata so an unknown-size release is staged off the tmpfs and decided at metadata time.

This lets an automatic acquisition that already knows it is a multi-gigabyte season pack skip the tmpfs entirely instead of being moved out moments later.

func ReleaseName

func ReleaseName(opts UpdateOptions) string

ReleaseName resolves the release name to download.

func RemoveBlocklistEntry

func RemoveBlocklistEntry(w http.ResponseWriter, r *http.Request, s *AppState)

func RemoveComic

func RemoveComic(w http.ResponseWriter, r *http.Request, s *AppState)

func RemoveCompletedTorrents

func RemoveCompletedTorrents(w http.ResponseWriter, r *http.Request, s *AppState)

RemoveCompletedTorrents removes the completed torrents whose seed limits are reached, finalizing the archive import first when it never ran.

func RemoveSeededCompleted

func RemoveSeededCompleted(cfg *Config, torrents TorrentSession, db *Database, postSeedMoves map[string]struct{})

RemoveSeededCompleted implements `remove_seeded_completed`.

func RemoveTorrent

func RemoveTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

RemoveTorrent handles DELETE /api/torrents/{hash}.

func RemoveTorrentLegacy

func RemoveTorrentLegacy(w http.ResponseWriter, r *http.Request, s *AppState)

func RemoveTorrentWithOptions

func RemoveTorrentWithOptions(w http.ResponseWriter, r *http.Request, s *AppState)

func RemoveTrashContents

func RemoveTrashContents(root string, olderThanDays int64) (int, uint64, error)

RemoveTrashContents empties a trash folder, keeping the entries modified less than olderThanDays ago when the value is positive; it returns how many files it removed and their size.

func RenameAll

func RenameAll(w http.ResponseWriter, r *http.Request, s *AppState)

RenameAll starts the background job that renames every enabled series.

func RenameEpisode

func RenameEpisode(
	ctx context.Context,
	path string,
	release *models.Release,
	cfg *Config,
	tmdb *TmdbClient,
) (string, error)

RenameEpisode renames an episode file according to the configured template and returns the new path, or "" when there is nothing to do (implementation of `rename_episode`).

func RenameMovie

func RenameMovie(
	ctx context.Context,
	path string,
	release *models.Release,
	cfg *Config,
	tmdb *TmdbClient,
) (string, error)

RenameMovie renames a movie file according to the configured template and returns the new path, or "" when there is nothing to do (implementation of `rename_movie`).

func RenameProgressView

func RenameProgressView(w http.ResponseWriter, r *http.Request, s *AppState)

RenameProgressView returns the progress of the library rename.

func RenameSidecars

func RenameSidecars(source, target string, cfg *Config) ([][2]string, error)

RenameSidecars renames the files associated with a video (thumbnail, subtitles, nfo, …) so they follow the new base name (implementation of `rename_sidecars`). The second element of each pair is empty when the sidecar was moved to the trash.

func RescoreDatabase

func RescoreDatabase(w http.ResponseWriter, r *http.Request, s *AppState)

RescoreDatabase recomputes the stored scores with the current settings.

func ResolveBySearch

func ResolveBySearch(s *AppState, title string) *models.Release

ResolveBySearch searches for a release whose title starts with the one given and whose source can be used.

func ResolveExistingTarget

func ResolveExistingTarget(source, target string, newScore int64, cfg *Config, kind, title string, incoming *models.Quality) (bool, error)

ResolveExistingTarget decides whether an incoming file must be discarded because an equal/better target already exists. It returns true when the incoming source was handled as a duplicate.

func RestartTorrent

func RestartTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

RestartTorrent restarts a torrent in the session.

func RestoreSource

func RestoreSource(w http.ResponseWriter, r *http.Request, s *AppState)

RestoreSource puts the source token back into the names of the archived episodes: it lists the renames, or applies them when execute is set.

func RestoreSourceToken

func RestoreSourceToken(name, source string) (string, bool)

RestoreSourceToken restores the source token in a name that lost it, inserting `[WEB-DL]`/`[HDTV]`… right before the first resolution tag (implementation of `restore_source_token`).

func ResumeAudioCleanup

func ResumeAudioCleanup(cfg *Config, db *Database)

ResumeAudioCleanup queues again the files the previous run did not finish cleaning. It is called once at startup, after the databases are open.

func ResumeHTTPDownload

func ResumeHTTPDownload(id string) bool

ResumeHTTPDownload resumes a paused HTTP download, spawning a task when none is running.

func ResumeTorrent

func ResumeTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

ResumeTorrent handles POST /api/torrents/{hash}/resume.

func RetryStorageMoves

func RetryStorageMoves(torrents TorrentSession, moveRequests map[string]struct{}, postSeedMoves map[string]struct{}, retries map[string]StorageMoveRetry)

RetryStorageMoves implements `retry_storage_moves`.

func Router

func Router(s *AppState) *http.ServeMux

Router builds the HTTP mux for the web UI and API.

It implements the `router()` : every route from the contract table is registered through `handle`, which installs shared cache-control middleware.

func Run

func Run(ctx context.Context, opts UpdateOptions) error

Run executes `gexttod --update`.

func RunAdaptiveTuning

func RunAdaptiveTuning(dataDir string, cfg *Config) int

RunAdaptiveTuning is the slow loop: it re-tunes the values the system already chose when the facts moved and returns how many it changed. It never touches a value the user set, and it is a no-op when nothing moved.

func RunComicsCycle

func RunComicsCycle(ctx context.Context, db *ComicsDb, client *GetComicsClient, notifier *Notifier, defaultRoot string, torrents TorrentEngine, mainDB *Database, cfg *Config) (int, error)

RunComicsCycle implements `comics::run_cycle` (renamed to avoid the collision with the orchestrator's own run cycle).

func RunCycle

func RunCycle(
	ctx context.Context,
	cfg *Config,
	engine *Engine,
	db *Database,
	archive *Archive,
	comics *ComicsDb,
	notifier *Notifier,
	torrents TorrentEngine,
) (*models.CycleStats, error)

RunCycle runs a full cycle (no domain restriction).

func RunCycleDomain

func RunCycleDomain(
	ctx context.Context,
	cfg *Config,
	engine *Engine,
	db *Database,
	archive *Archive,
	comics *ComicsDb,
	notifier *Notifier,
	torrents TorrentEngine,
	domain *string,
) (*models.CycleStats, error)

RunCycleDomain runs a cycle restricted to an optional domain (`series`, `movies` or `comics`). A nil domain means "full".

func RunHousekeepingNow

func RunHousekeepingNow(w http.ResponseWriter, r *http.Request, s *AppState)

func RunNow

func RunNow(w http.ResponseWriter, r *http.Request, s *AppState)

func SafeRemoveTorrent

func SafeRemoveTorrent(s *AppState, cfg *Config, hash string, requestedDeleteFiles bool) (bool, error)

SafeRemoveTorrent safely removes a torrent from the active engine. It ensures that:

  1. Files in the permanent archive library (NAS) are NEVER deleted when the user didn't explicitly request deletion, even if the torrent payload is marked disposable.
  2. When file deletion is requested and trash is configured, files are moved to the trash directory instead of being permanently unlinked.
  3. Engine removal is properly recorded in the database.

func SamePath

func SamePath(left, right string) bool

SamePath reports whether two paths refer to the same filesystem location (implementation of `same_path`).

func SanitizeLanguageRequirements

func SanitizeLanguageRequirements(raw string) string

SanitizeLanguageRequirements cleans a stored `language_requirements`: drops empty/`-` entries and returns the canonical JSON form (or an empty string).

func SanitizeSubtitleRequirements

func SanitizeSubtitleRequirements(raw string) string

SanitizeSubtitleRequirements cleans a stored `subtitle_requirements` into a plain comma list.

func SaveBackupSettings

func SaveBackupSettings(w http.ResponseWriter, r *http.Request, s *AppState)

SaveBackupSettings stores the backup options sent in the request, in key order: keys outside the backup section are ignored, an empty FTP password is skipped so the stored one is not erased, and an extra path must be absolute.

func SaveConfigRoot

func SaveConfigRoot(w http.ResponseWriter, r *http.Request, s *AppState)

SaveConfigRoot accepts a full library configuration and delegates to the library saver, mirroring `save_config_root`.

func SaveEventHooks

func SaveEventHooks(w http.ResponseWriter, r *http.Request, s *AppState)

SaveEventHooks validates and stores the event hooks, then reloads them in the notifier.

func SaveHooks

func SaveHooks(dataDir string, hooks []EventHook) error

SaveHooks persists hooks into the settings table.

func SaveLibrary

func SaveLibrary(dataDir string, series []SeriesConfig, movies []MovieConfig) error

SaveLibrary persists the monitored series and movies into `gextto_config.db`.

func SaveLibraryConfig

func SaveLibraryConfig(dataDir string, series []SeriesConfig, movies []MovieConfig) error

SaveLibraryConfig is the config-persistence helper used by the web handler; it mirrors Config::save_library without colliding with the handler name.

func SaveLibraryHandler

func SaveLibraryHandler(w http.ResponseWriter, r *http.Request, s *AppState)

SaveLibraryHandler saves the whole library configuration (series and movies).

func SaveMovieAliases

func SaveMovieAliases(dataDir string, id int64, aliases []string) error

SaveMovieAliases stores the alternative titles of one movie without rewriting the whole library: the TMDB refresh runs in the background and must not overwrite a form the user is editing.

func SaveMovieTitleTranslations

func SaveMovieTitleTranslations(dataDir string, id int64, titles map[string]string) error

SaveMovieTitleTranslations stores the per-language titles of one movie without rewriting the whole library, like SaveMovieAliases.

func SaveMoviesConfig

func SaveMoviesConfig(w http.ResponseWriter, r *http.Request, s *AppState)

SaveMoviesConfig saves the movie list and leaves the series untouched.

func SaveQualityProfiles

func SaveQualityProfiles(w http.ResponseWriter, r *http.Request, s *AppState)

SaveQualityProfiles is POST /api/quality-profiles with {"items":[…]}. It also accepts a bare array, so a script can send the list directly.

func SaveRamdiskSettings

func SaveRamdiskSettings(dataDir string, path string) (map[string]any, error)

SaveRamdiskSettings persists the RAM-disk settings and returns the computed recommendation.

func SaveSeedRules

func SaveSeedRules(w http.ResponseWriter, r *http.Request, s *AppState)

SaveSeedRules handles POST /api/seed-rules: it replaces the rules.

func SaveSeriesConfig

func SaveSeriesConfig(w http.ResponseWriter, r *http.Request, s *AppState)

SaveSeriesConfig saves the series list and leaves the movies untouched.

func SaveSetting

func SaveSetting(dataDir string, key string, value string) error

SaveSetting persists one setting in `gextto_config.db`.

func SaveSettingHandler

func SaveSettingHandler(w http.ResponseWriter, r *http.Request, s *AppState)

SaveSetting handles POST /api/config/settings.

func SaveSimklSettings

func SaveSimklSettings(w http.ResponseWriter, r *http.Request, s *AppState)

func SaveSourceFilters

func SaveSourceFilters(w http.ResponseWriter, r *http.Request, s *AppState)

func SaveTagDirRules

func SaveTagDirRules(w http.ResponseWriter, r *http.Request, s *AppState)

SaveTagDirRules replaces the tag directory rules.

func SaveWatchedFolders

func SaveWatchedFolders(dataDir string, folders []WatchedFolder) error

SaveWatchedFolders stores watched folders under the `watched_folders` settings key as JSON.

func SaveWatchedFoldersHandler

func SaveWatchedFoldersHandler(w http.ResponseWriter, r *http.Request, s *AppState)

func ScanAllArchives

func ScanAllArchives(w http.ResponseWriter, r *http.Request, s *AppState)

ScanAllArchives starts the archive scan as a background job.

The scan is long (it walks every archive folder) and used to run inside the HTTP request. It is now a background job: the request validates quickly and returns 202 with a job id, while /api/jobs/{id} exposes progress, result and errors. Cancellation is observed between series; a single folder scan is never interrupted half-way.

func ScanFolder

func ScanFolder(folder WatchedFolder) []string

ScanFolder lists the `.torrent`/`.magnet` files in a watched folder, sorted for a stable processing order.

func ScanSeriesArchive

func ScanSeriesArchive(w http.ResponseWriter, r *http.Request, s *AppState)

func ScorePreview

func ScorePreview(w http.ResponseWriter, r *http.Request, s *AppState)

ScorePreview parses a release title and returns the score breakdown and the matching library entry the search would apply.

func ScoreQuality

func ScoreQuality(quality *models.Quality, settings map[string]string) int64

ScoreQuality applies the configured quality weights without requiring a full `Config`. Archive indexing uses this same primitive while it is handed a settings map rather than the complete runtime configuration.

func Search(ctx context.Context, cfg *Config, query string) []models.Release

Search runs a web search over the configured engines with no overall budget.

func SearchED2K

func SearchED2K(ctx context.Context, cfg *Config, query string) []models.Release

SearchED2K searches eD2k/Kad through aMule and normalizes the results. It returns nil when the integration is disabled, unreachable or finds nothing: an eD2k failure must never fail the torrent search that called it.

func SearchED2KManual

func SearchED2KManual(ctx context.Context, cfg *Config, query string) []models.Release

SearchED2KManual is the search behind the eD2k checkbox of the manual search. It needs the integration switched on, like every eD2k feature.

func SearchEpisode

func SearchEpisode(w http.ResponseWriter, r *http.Request, s *AppState)

SearchEpisode handles POST /api/episodes/{series}/{season}/{episode}/search.

func SearchMissing

func SearchMissing(w http.ResponseWriter, r *http.Request, s *AppState)

func SearchQueryFromTitle

func SearchQueryFromTitle(title string) string

SearchQueryFromTitle turns a release title into a search query: it keeps the leading words and stops at the year or at the first quality marker.

func SearchWithTimeout

func SearchWithTimeout(ctx context.Context, cfg *Config, query string, timeout *time.Duration) []models.Release

SearchWithTimeout runs a web search with an optional per-source budget: each engine gets that long once it starts, so a source queued behind the shared limiter is not cut off before it has had its turn. Answers already received are always kept.

func SeasonAllowedForScan

func SeasonAllowedForScan(specification string, season int64) bool

SeasonAllowedForScan is the static season-range check for archive scans.

func SeedRulesView

func SeedRulesView(w http.ResponseWriter, r *http.Request, s *AppState)

SeedRulesView handles GET /api/seed-rules.

func SeenGrouped

func SeenGrouped(state *AppState, kind string, r *http.Request) (int, any)

func SelectRamdisk

func SelectRamdisk(w http.ResponseWriter, r *http.Request, s *AppState)

func SendMagnet

func SendMagnet(w http.ResponseWriter, r *http.Request, s *AppState)

SendMagnet adds a magnet link, or a remote http(s) .torrent, to the active engine.

func SeriesDetail

func SeriesDetail(w http.ResponseWriter, r *http.Request, s *AppState)

func SeriesEpisodes

func SeriesEpisodes(w http.ResponseWriter, r *http.Request, s *AppState)

func SeriesInfo

func SeriesInfo(w http.ResponseWriter, r *http.Request, s *AppState)

func SeriesList

func SeriesList(w http.ResponseWriter, r *http.Request, s *AppState)

func SeriesMetadataRefresh

func SeriesMetadataRefresh(w http.ResponseWriter, r *http.Request, s *AppState)

SeriesMetadataRefresh handles POST /api/series/{name}/metadata.

func SeriesNamesMatch

func SeriesNamesMatch(a, b string) bool

SeriesNamesMatch confronta due nomi di serie.

func SeriesRenameExecute

func SeriesRenameExecute(w http.ResponseWriter, r *http.Request, s *AppState)

func SeriesRenamePreview

func SeriesRenamePreview(w http.ResponseWriter, r *http.Request, s *AppState)

func SeriesSearchMissing

func SeriesSearchMissing(w http.ResponseWriter, r *http.Request, s *AppState)

func SeriesSeenGroupedView

func SeriesSeenGroupedView(w http.ResponseWriter, r *http.Request, s *AppState)

func SeriesSeenView

func SeriesSeenView(w http.ResponseWriter, r *http.Request, s *AppState)

func SeriesSubtitleBonus

func SeriesSubtitleBonus(series *SeriesConfig, quality *models.Quality) int64

SeriesSubtitleBonus is the optional score bonus for a monitored series' preferred subtitle languages. The series subtitle field is a preference, not a hard requirement; generic values such as yes/true/1 still mean that the release must carry subtitles, as in the legacy rule.

func Serve

func Serve(state *AppState) error

Serve binds the web and engine listeners, starts the background workers and blocks until the process receives SIGINT/SIGTERM, then shuts down gracefully.

func ServiceRestart

func ServiceRestart(w http.ResponseWriter, r *http.Request, s *AppState)

ServiceRestart starts, stops or restarts the Gextto systemd service.

func ServicesStatus

func ServicesStatus(w http.ResponseWriter, r *http.Request, s *AppState)

ServicesStatus reports the state of the Gextto unit, of every enabled indexer and of FlareSolverr.

func SessionSnapshot

func SessionSnapshot(torrents TorrentSession) []models.TorrentView

SessionSnapshot reads the torrents for a path that only displays them: it uses the cached snapshot when the backend has one, and falls back to List (which refreshes first) for any other backend. The UI, the latency guard and the problems panel call it several times per second and must not queue behind a poll to the daemon that is already in flight.

func SetComicEnabled

func SetComicEnabled(w http.ResponseWriter, r *http.Request, s *AppState)

SetComicEnabled handles POST /api/comics/{id}/enabled.

func SetFilePriorities

func SetFilePriorities(w http.ResponseWriter, r *http.Request, s *AppState)

func SetHTTPDownloadTag

func SetHTTPDownloadTag(id, tag string) bool

SetHTTPDownloadTag updates the user-assigned tag of an HTTP download.

func SetLogLevel

func SetLogLevel(w http.ResponseWriter, r *http.Request, s *AppState)

func SetPeerOptions

func SetPeerOptions(w http.ResponseWriter, r *http.Request, s *AppState)

SetPeerOptions sets a torrent's bandwidth share and its DHT, PEX and LSD switches when the active engine supports them.

func SetSequential

func SetSequential(w http.ResponseWriter, r *http.Request, s *AppState)

SetSequential turns sequential download on or off and saves the choice.

func SetSeriesPath

func SetSeriesPath(w http.ResponseWriter, r *http.Request, s *AppState)

func SetSpeedLimits

func SetSpeedLimits(w http.ResponseWriter, r *http.Request, s *AppState)

SetSpeedLimits stores the global transfer limits and applies them to the active engine.

func SetSuperSeeding

func SetSuperSeeding(w http.ResponseWriter, r *http.Request, s *AppState)

SetSuperSeeding turns super-seeding on or off when the active engine supports it.

func SetTempLimits

func SetTempLimits(w http.ResponseWriter, r *http.Request, s *AppState)

SetTempLimits sets or clears the temporary speed limit, or switches the "auto speed" exception on and off.

func SetTorrentLimits

func SetTorrentLimits(w http.ResponseWriter, r *http.Request, s *AppState)

SetTorrentLimits handles POST /api/torrents/{hash}/limits.

func SetTorrentLimitsLegacy

func SetTorrentLimitsLegacy(w http.ResponseWriter, r *http.Request, s *AppState)

func SetTorrentNoRename

func SetTorrentNoRename(w http.ResponseWriter, r *http.Request, s *AppState)

func SetTorrentTag

func SetTorrentTag(w http.ResponseWriter, r *http.Request, s *AppState)

SetTorrentTag sets the tag of a torrent.

func SetTorrentTrackers

func SetTorrentTrackers(w http.ResponseWriter, r *http.Request, s *AppState)

SetTorrentTrackers replaces the trackers of a torrent.

func SetWebSeeds

func SetWebSeeds(w http.ResponseWriter, r *http.Request, s *AppState)

SetWebSeeds adds or removes the web seeds of a torrent.

func SettingOrigins

func SettingOrigins(dataDir string) (map[string]Provenance, error)

SettingOrigins returns the recorded origin of every setting that has one.

func SettingsIndexKeys

func SettingsIndexKeys() []string

SettingsIndexKeys lists the keys of the settings page, in the order the index declares them: the settings index first, then the score weights. The generated constants (settings_keys_gen.go) and the guard that keeps them in step with the index are built from it, so a new row cannot exist without a name.

func SetupComplete

func SetupComplete(cfg *Config) bool

SetupComplete reports whether the setup marker exists.

func SetupCompleteExisting

func SetupCompleteExisting(w http.ResponseWriter, r *http.Request, s *AppState)

SetupCompleteExisting marks the initial setup as complete for an existing installation.

func SetupMarker

func SetupMarker(cfg *Config) string

SetupMarker implements `setup_marker`.

func SetupStatus

func SetupStatus(w http.ResponseWriter, r *http.Request, s *AppState)

SetupStatus reports the first-run setup state.

func ShutdownTorrentEngine

func ShutdownTorrentEngine(s *AppState) error

ShutdownTorrentEngine releases the active engine when it owns process-level resources (the managed qBittorrent process, the gx-torrent daemon adoption).

func SimklAuthPoll

func SimklAuthPoll(w http.ResponseWriter, r *http.Request, s *AppState)

SimklAuthPoll handles POST /api/simkl/auth/poll.

func SimklAuthRevoke

func SimklAuthRevoke(w http.ResponseWriter, r *http.Request, s *AppState)

func SimklAuthStart

func SimklAuthStart(w http.ResponseWriter, r *http.Request, s *AppState)

func SimklCalendar

func SimklCalendar(w http.ResponseWriter, r *http.Request, s *AppState)

SimklCalendar returns the user's Simkl calendar; it needs a configured and authenticated client.

func SimklScrobble

func SimklScrobble(w http.ResponseWriter, r *http.Request, s *AppState)

SimklScrobble marks the items sent in the request as watched on Simkl.

func SimklSettings

func SimklSettings(w http.ResponseWriter, r *http.Request, s *AppState)

SimklSettings returns the Simkl options stored in settings, with their defaults, plus whether the client is configured and authenticated.

func SimklStatus

func SimklStatus(w http.ResponseWriter, r *http.Request, s *AppState)

SimklStatus reports whether Simkl is configured and authenticated.

func SimklWatchlist

func SimklWatchlist(w http.ResponseWriter, r *http.Request, s *AppState)

SimklWatchlist returns the user's Simkl watchlist; it needs a configured and authenticated client.

func SimklWatchlistImport

func SimklWatchlistImport(w http.ResponseWriter, r *http.Request, s *AppState)

SimklWatchlistImport handles POST /api/simkl/watchlist/import.

func SingleComponent

func SingleComponent(name string) bool

SingleComponent reports whether `name` is exactly one path component.

func SizeOfPath

func SizeOfPath(path string) (int64, error)

SizeOfPath returns the total size of a file or directory tree without following symlinks (implementation of `size_of_path`).

func SourceFiltersView

func SourceFiltersView(w http.ResponseWriter, r *http.Request, s *AppState)

func SourceIsUsable

func SourceIsUsable(source string) bool

SourceIsUsable reports whether the source is an HTTP URL or a magnet link with a valid info hash.

func SourcesHealth

func SourcesHealth(w http.ResponseWriter, r *http.Request, s *AppState)

func SplitArgs

func SplitArgs(input string) []string

SplitArgs splits an argument template honoring single/double quotes and backslash escapes, without invoking a shell.

func StagePackFile

func StagePackFile(
	file *PackSourceFile,
	source, destination string,
	destinationFiles []string,
	cfg *Config,
	releaseQuality models.Quality,
) (string, bool, error)

StagePackFile copies one season-pack episode into the destination through a temporary `.gextto-part` file (implementation of `stage_pack_file`). destinationFiles is the pre-enumerated content of the destination directory, so the caller can walk it once for the whole pack instead of once per episode.

func StartAcquisitionRecorder

func StartAcquisitionRecorder(db *Database) func()

StartAcquisitionRecorder installs the event sink that stores the acquisition history in db, prunes old events, and returns the function that flushes the queue and removes the sink (call it before closing db).

func StatsApi

func StatsApi(w http.ResponseWriter, r *http.Request, s *AppState)

StatsApi returns the last cycle, the engine statistics and the consumption figures.

func Status

func Status(w http.ResponseWriter, r *http.Request, s *AppState)

Status returns the daemon status summary.

func SweepStaleTempFiles

func SweepStaleTempFiles(cfg *Config) int

SweepStaleTempFiles cleans up abandoned `.gextto-copy-*` and `*.gextto-part` files left behind by aborted atomic copies or daemon crashes. Only files older than minAge (2 hours) are removed so in-progress transfers are never disturbed.

func SystemStats

func SystemStats(w http.ResponseWriter, r *http.Request, s *AppState)

SystemStats returns the disk health checks, the engine statistics and the last cycle.

func TagDirRules

func TagDirRules(w http.ResponseWriter, r *http.Request, s *AppState)

TagDirRules returns the configured tag directory rules.

func TestNotification

func TestNotification(w http.ResponseWriter, r *http.Request, s *AppState)

TestNotification sends a test message through the configured notification channels.

func TmdbAdd

func TmdbAdd(w http.ResponseWriter, r *http.Request, s *AppState)

TmdbAdd adds the movie or series chosen on the discovery page to the library and saves it; an explicit quality profile is applied to the new entry.

func TmdbDiscover

func TmdbDiscover(w http.ResponseWriter, r *http.Request, s *AppState)

TmdbDiscover returns the trending, popular or category list of TMDB for the requested kind, with the in-library flag already computed.

func TmdbSearch

func TmdbSearch(w http.ResponseWriter, r *http.Request, s *AppState)

TmdbSearch handles POST /api/tmdb/search.

func ToggleSeason

func ToggleSeason(w http.ResponseWriter, r *http.Request, s *AppState)

func TokenString

func TokenString(value any, key string) (string, error)

TokenString extracts a non-empty string field from an integration JSON response, mirroring gextto's token_string helper.

func TorrentBackendActivate

func TorrentBackendActivate(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentBackendActivate implements `POST /api/torrent-backend`: it validates the configured engine and reports whether a restart is needed. A running daemon never installs a second engine: switching the transfer plane changes who owns the files, so it is applied at startup after a clean shutdown (see the backend-specific implementation notes).

func TorrentBackendName

func TorrentBackendName(cfg *Config) string

TorrentBackendName returns the configured backend. A missing or empty `torrent_backend` selects DefaultTorrentBackend (gx-torrent for a fresh installation); a value that was saved but is unknown (a backend removed in a previous release, including the old `embedded`) is normalised to gx-torrent so existing installations keep transferring after an upgrade.

func TorrentBackendPortCheck

func TorrentBackendPortCheck(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentBackendPortCheck tests the peer port of the active engine: is it listening and does the router forward it (the eMule-style "test ports")? Only gx-torrent, whose daemon owns the router mapping, can answer.

func TorrentBackendPreflight

func TorrentBackendPreflight(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentBackendPreflight implements `torrent_backend_preflight`: it validates the path mappings and the connectivity of the configured backend before it is ever activated. A path-mapping failure is blocking.

func TorrentBackendStatus

func TorrentBackendStatus(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentBackendStatus implements `torrent_backend_status`.

func TorrentBackendTest

func TorrentBackendTest(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentBackendTest implements `torrent_backend_test`: it logs into the configured qBittorrent-nox and reports its versions and torrent count without changing anything.

func TorrentDetails

func TorrentDetails(w http.ResponseWriter, r *http.Request, s *AppState)

func TorrentEvents

func TorrentEvents(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentEvents returns the last 100 torrent events.

func TorrentFiles

func TorrentFiles(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentFiles returns the files of a torrent.

func TorrentHistory

func TorrentHistory(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentHistory returns the completed downloads (torrents and comics) newest first, paginated.

func TorrentIdle

func TorrentIdle(torrent models.TorrentView) bool

TorrentIdle reports whether an unfinished, not paused torrent is stuck at 0 B/s both ways (no peer has the missing pieces, a recheck, a stall).

func TorrentMigrationCancel

func TorrentMigrationCancel(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentMigrationCancel implements POST /api/torrent-migrations/cancel: it removes the persisted manifest once the operator completed the switch.

func TorrentMigrationPlan

func TorrentMigrationPlan(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentMigrationPlan implements POST /api/torrent-migrations/plan: it builds (and optionally persists) the dry-run manifest without touching files.

func TorrentMigrations

func TorrentMigrations(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentMigrations implements GET /api/torrent-migrations: it reports the active backend and any persisted migration manifest.

func TorrentNoRenameList

func TorrentNoRenameList(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentNoRenameList returns the torrents marked as not to be renamed.

func TorrentPeers

func TorrentPeers(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentPeers returns the peers of a torrent.

func TorrentPeersLegacy

func TorrentPeersLegacy(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentPeersLegacy handles POST /api/torrents/peers.

func TorrentPieces

func TorrentPieces(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentPieces implements GET /api/torrents/{hash}/pieces.

func TorrentSelective

func TorrentSelective(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentSelective implements POST /api/torrents/{hash}/selective.

func TorrentSessionStats

func TorrentSessionStats(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentSessionStats implements GET /api/torrents/session-stats: the active engine's session counters, for every backend that exposes them.

func TorrentStats

func TorrentStats(w http.ResponseWriter, r *http.Request, s *AppState)

func TorrentStream

func TorrentStream(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentStream implements GET /api/torrents/{hash}/stream?file=N.

func TorrentTags

func TorrentTags(w http.ResponseWriter, r *http.Request, s *AppState)

func TorrentTrackers

func TorrentTrackers(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentTrackers returns the trackers of a torrent.

func TorrentTransferring

func TorrentTransferring(torrent models.TorrentView) bool

TorrentTransferring reports whether a torrent is really moving data right now (downloading or uploading). Only these count as "active": a torrent in the downloading state at 0 B/s both ways is waiting, not working.

func TorrentWhy

func TorrentWhy(w http.ResponseWriter, r *http.Request, s *AppState)

TorrentWhy implements GET /api/torrents/{hash}/why: it explains the current situation of one torrent (why it is or is not downloading), which makes extreme cases such as a swarm with no seeders explicit.

func Torrents

func Torrents(w http.ResponseWriter, r *http.Request, s *AppState)

Torrents returns the torrent list decorated for the interface; in dry-run, when the live session is empty, it shows the stored torrents instead.

func TorznabError

func TorznabError(body string) string

TorznabError detects a Torznab application error embedded in an HTTP 200 body. Torznab uses HTTP 200 even for application errors such as a wrong API key; without this check the parser would return zero results and the provider would be marked healthy instead of backing off. Returns "" when healthy.

func TorznabErrorBytes

func TorznabErrorBytes(body []byte) string

TorznabErrorBytes is TorznabError for a body kept as bytes: a Torznab response is parsed from its buffer without copying it into a string.

func TouchConfigGeneration

func TouchConfigGeneration()

TouchConfigGeneration bumps the configuration generation.

func TranslateBackendToGextto

func TranslateBackendToGextto(path string, mappings []PathMapping) (string, bool)

TranslateBackendToGextto maps a backend-reported path into the Gextto view.

func TranslateGexttoToBackend

func TranslateGexttoToBackend(path string, mappings []PathMapping) (string, bool)

TranslateGexttoToBackend maps a Gextto path into the active backend's view.

func TrashEntries

func TrashEntries(w http.ResponseWriter, r *http.Request, s *AppState)

TrashEntries lists the trash folder with the size of every entry, largest first.

func TrimMemory

func TrimMemory()

TrimMemory returns the free heap to the operating system.

The engine is pure Go: a cycle, a library scan or a finished transfer allocates tens of times the live heap, and the collector keeps that headroom until the next allocation burst. During the long idle window nothing allocates, so the free pages stay resident even though the daemon does not need them. debug.FreeOSMemory collects and hands the free spans back, what the allocator trim of the old embedded engine used to do.

func TryAcquireArchiveRename

func TryAcquireArchiveRename(series string) (func(), string, bool)

TryAcquireArchiveRename reserves the archive of a series for a rename. It never waits: it fails when a copy, the audio cleanup or another rename of the same series is in progress, and the caller skips the rename. The returned reason names the operation that is holding the archive. The returned function releases the reservation and wakes the imports waiting for it.

func TvdbSearch

func TvdbSearch(w http.ResponseWriter, r *http.Request, s *AppState)

TvdbSearch handles POST /api/tvdb/search.

func TvdbSeries

func TvdbSeries(w http.ResponseWriter, r *http.Request, s *AppState)

func UiNoCache

func UiNoCache(next http.Handler) http.Handler

UiNoCache disables browser caching for every server-rendered UI route — the shell (`/`), its HTMX fragments and the static assets (`/static/*`). The JSON and streaming API under `/api` keeps its own cache semantics.

func UnpinTorrent

func UnpinTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

func UpdateApplyApi

func UpdateApplyApi(w http.ResponseWriter, r *http.Request, s *AppState)

UpdateApplyApi requests the update (POST /api/update/apply).

func UpdateCheckApi

func UpdateCheckApi(w http.ResponseWriter, r *http.Request, s *AppState)

UpdateCheckApi checks now (POST /api/update/check).

func UpdateMovie

func UpdateMovie(w http.ResponseWriter, r *http.Request, s *AppState)

func UpdateSeries

func UpdateSeries(w http.ResponseWriter, r *http.Request, s *AppState)

UpdateSeries changes the given fields of one monitored series.

func UpdateStatusApi

func UpdateStatusApi(w http.ResponseWriter, r *http.Request, s *AppState)

UpdateStatusApi returns the update state (GET /api/update).

func UpgradeImpact

func UpgradeImpact(cfg *Config, db *Database, archive *Archive) (upgradeImpactReport, error)

UpgradeImpact replays the archived feed releases of every monitored series through the dry-run decision and reports the episodes they would upgrade.

func UploadFTP

func UploadFTP(archive, host, user, password, remotePath string) error

UploadFTP uploads a snapshot archive to an FTP server.

func UploadTorrent

func UploadTorrent(w http.ResponseWriter, r *http.Request, s *AppState)

UploadTorrent adds the .torrent file sent in the request body to the active engine.

func Usage

func Usage() string

Usage is the text shown by `gexttod --help`.

func V2ArchiveSQLDelete

func V2ArchiveSQLDelete(w http.ResponseWriter, r *http.Request, s *AppState)

V2ArchiveSQLDelete deletes the rows of a destructive operation after the preview. The confirmation field is required, so a bare link or a stray form submission cannot trigger the deletion.

func V2ArchiveSQLPreview

func V2ArchiveSQLPreview(w http.ResponseWriter, r *http.Request, s *AppState)

V2ArchiveSQLPreview runs the read-only query of one operation and renders the result table. It never modifies the archive.

func V2ChromePartial

func V2ChromePartial(w http.ResponseWriter, r *http.Request, s *AppState)

V2ChromePartial refreshes the live performance metrics without reloading the page or replacing the controls in the top bar.

func V2ChromeSSE

func V2ChromeSSE(w http.ResponseWriter, r *http.Request, s *AppState)

func V2ComicsDownload

func V2ComicsDownload(w http.ResponseWriter, r *http.Request, s *AppState)

func V2ComicsEdit

func V2ComicsEdit(w http.ResponseWriter, r *http.Request, s *AppState)

func V2ComicsExploreAdd

func V2ComicsExploreAdd(w http.ResponseWriter, r *http.Request, s *AppState)

func V2ComicsExploreDownload

func V2ComicsExploreDownload(w http.ResponseWriter, r *http.Request, s *AppState)

func V2ComicsExploreSelect

func V2ComicsExploreSelect(w http.ResponseWriter, r *http.Request, s *AppState)
func V2ComicsLinks(w http.ResponseWriter, r *http.Request, s *AppState)

func V2ComicsSave

func V2ComicsSave(w http.ResponseWriter, r *http.Request, s *AppState)

func V2ComicsWeeklyForce

func V2ComicsWeeklyForce(w http.ResponseWriter, r *http.Request, s *AppState)

V2ComicsWeeklyForce queues a Weekly Pack from its recorded magnet or torrent link. It is separate from the generic table action so the user sees whether the pack was queued or was already present in the torrent client.

func V2DBMaintenance

func V2DBMaintenance(w http.ResponseWriter, r *http.Request, s *AppState)

V2DBMaintenance runs VACUUM/ANALYZE (or just refreshes sizes) and re-renders.

func V2DashboardBackup

func V2DashboardBackup(w http.ResponseWriter, r *http.Request, s *AppState)

V2DashboardBackup creates a backup and reports its result in the same confirmation modal used by the dashboard's manual monitoring actions.

func V2DashboardFeed

func V2DashboardFeed(w http.ResponseWriter, r *http.Request, s *AppState)

func V2DashboardFeedAdd

func V2DashboardFeedAdd(w http.ResponseWriter, r *http.Request, s *AppState)

func V2DashboardProblems

func V2DashboardProblems(w http.ResponseWriter, r *http.Request, s *AppState)

V2DashboardProblems renders the "Da controllare" panel body; the dashboard loads it on its own and refreshes it every minute.

func V2DashboardProblemsAck

func V2DashboardProblemsAck(w http.ResponseWriter, r *http.Request, s *AppState)

V2DashboardProblemsAck marks the shown warnings as read (the "Pulisci" button): the panel stops listing them, and a download that produces a new warning shows again because its event id is above the watermark. It answers with the refreshed panel.

func V2DashboardSearch

func V2DashboardSearch(w http.ResponseWriter, r *http.Request, s *AppState)

func V2DownloadsAdd

func V2DownloadsAdd(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsAdd accepts the magnet/URL or the uploaded .torrent and forwards it to the same API the classic form uses. It answers with a browser redirect so the form keeps working without JavaScript.

func V2DownloadsDetail

func V2DownloadsDetail(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsDetail renders the whole detail modal.

func V2DownloadsDetailAction

func V2DownloadsDetailAction(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsDetailAction keeps all torrent-detail mutations inside the v2 modal. The browser submits ordinary form fields; this handler translates them into the existing JSON API payloads and returns the refreshed active tab.

func V2DownloadsDetailPanel

func V2DownloadsDetailPanel(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsDetailPanel renders only the tab panel.

func V2DownloadsOrphansClean

func V2DownloadsOrphansClean(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsOrphansClean moves the safe leftovers to the trash in a background job: a cross-filesystem copy can be tens of gigabytes and must not block the HTTP request. The modal says the job started; progress and the final count are in the jobs panel.

func V2DownloadsOrphansModal

func V2DownloadsOrphansModal(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsOrphansModal lists the download-folder leftovers that no live torrent owns, with the verdict of the library check.

func V2DownloadsRemove

func V2DownloadsRemove(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsRemove removes a torrent and swaps the table back in, clearing the modal with an out-of-band swap.

func V2DownloadsRemoveModal

func V2DownloadsRemoveModal(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsRemoveModal renders the remove-with-options dialog.

func V2DownloadsRowsPartial

func V2DownloadsRowsPartial(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsRowsPartial refreshes only the rows of the download list: the 5 s tick no longer rebuilds the filter, the sort menu and the tools above, so the list updates in place without the toolbar flickering and without taking the focus away from the filter. The counters that live outside travel with the answer as out-of-band fragments.

func V2DownloadsSettings

func V2DownloadsSettings(w http.ResponseWriter, r *http.Request, s *AppState)

func V2DownloadsTable

func V2DownloadsTable(w http.ResponseWriter, r *http.Request, s *AppState)

V2DownloadsTable is the single POST endpoint the torrent table form talks to.

func V2Duplicates

func V2Duplicates(w http.ResponseWriter, r *http.Request, s *AppState)

V2Duplicates runs the duplicate scan/cleanup and re-renders the panel.

func V2Ed2kAction

func V2Ed2kAction(w http.ResponseWriter, r *http.Request, s *AppState)

V2Ed2kAction runs a connection command and re-renders the state panel.

func V2Ed2kAdd

func V2Ed2kAdd(w http.ResponseWriter, r *http.Request, s *AppState)

V2Ed2kAdd queues one or more ed2k:// links (one result's button, or the pasted-links box) and registers them like a manual download.

func V2Ed2kCreateDirs

func V2Ed2kCreateDirs(w http.ResponseWriter, r *http.Request, s *AppState)

V2Ed2kCreateDirs creates aMule's missing incoming/temp folders, so its disk checks stop failing, and re-renders the state panel.

func V2Ed2kDetail

func V2Ed2kDetail(w http.ResponseWriter, r *http.Request, s *AppState)

V2Ed2kDetail renders the detail dialog of an aMule download.

func V2Ed2kLog

func V2Ed2kLog(w http.ResponseWriter, r *http.Request, s *AppState)

V2Ed2kLog renders aMule's log on the eD2k page.

func V2Ed2kPriority

func V2Ed2kPriority(w http.ResponseWriter, r *http.Request, s *AppState)

V2Ed2kPriority changes the priority of an aMule download from the detail dialog and renders its body again.

func V2Ed2kSearch

func V2Ed2kSearch(w http.ResponseWriter, r *http.Request, s *AppState)

V2Ed2kSearch searches eD2k/Kad through aMule and renders the results.

func V2Ed2kSharedReload

func V2Ed2kSharedReload(w http.ResponseWriter, r *http.Request, s *AppState)

V2Ed2kSharedReload asks aMule to rescan its shared folders, then renders the panel again with the fresh list.

func V2Empty

func V2Empty(w http.ResponseWriter, r *http.Request, s *AppState)

V2Empty clears a modal container.

func V2FolderRenameApply

func V2FolderRenameApply(w http.ResponseWriter, r *http.Request, s *AppState)

V2FolderRenameApply applies the accepted proposals and re-renders.

func V2FolderRenameScan

func V2FolderRenameScan(w http.ResponseWriter, r *http.Request, s *AppState)

V2FolderRenameScan scans a folder and re-renders the review panel.

func V2GxLogsPartial

func V2GxLogsPartial(w http.ResponseWriter, r *http.Request, s *AppState)

V2GxLogsPartial re-renders the gx-torrent log panel in Maintenance (filter, refresh and the log-file selector). Like V2LogsPartial it updates the line count out of band, since only the <pre> is swapped.

func V2HTTPDownloadDetail

func V2HTTPDownloadDetail(w http.ResponseWriter, r *http.Request, s *AppState)

func V2HealthQueuePartial

func V2HealthQueuePartial(w http.ResponseWriter, r *http.Request, s *AppState)

V2HealthQueuePartial refreshes the "Coda titoli" and "Import falliti" panels without reloading the page. The fragment shows only those two lists: it reads them from the database instead of paying the whole health check every minute.

func V2HealthTilePartial

func V2HealthTilePartial(w http.ResponseWriter, r *http.Request, s *AppState)

V2HealthTilePartial refreshes a single Salute tile without reloading the page. The caller picks the tile with `name`; Stato, Memoria and Uptime poll every few seconds, while Disco polls hourly.

func V2HealthTilesPartial

func V2HealthTilesPartial(w http.ResponseWriter, r *http.Request, s *AppState)

V2HealthTilesPartial refreshes the three quick tiles (Stato, Memoria, Uptime) in one answer. Each of them used to have its own 5 s request: three round trips, three times the work of one on a small machine.

func V2ImportApply

func V2ImportApply(w http.ResponseWriter, r *http.Request, s *AppState)

V2ImportApply performs one confirmed candidate (POST /import/apply).

func V2ImportPreview

func V2ImportPreview(w http.ResponseWriter, r *http.Request, s *AppState)

V2ImportPreview renders the candidate list for the page (GET /import/preview).

func V2JobCancel

func V2JobCancel(w http.ResponseWriter, r *http.Request, s *AppState)

V2JobCancel cancels a queued/running job and refreshes the list.

func V2JobsPartial

func V2JobsPartial(w http.ResponseWriter, r *http.Request, s *AppState)

V2JobsPartial renders the background-job list (polled by HTMX).

func V2LibraryBulkApply

func V2LibraryBulkApply(w http.ResponseWriter, r *http.Request, s *AppState)

V2LibraryBulkApply is POST /library/bulk: it applies the marked values to the ticked titles and reports how many changed.

func V2LibraryBulkProfile

func V2LibraryBulkProfile(w http.ResponseWriter, r *http.Request, s *AppState)

V2LibraryBulkProfile is GET /library/bulk/profile?id=…: the value fields filled from a quality profile, each marked to be applied.

func V2LogsPartial

func V2LogsPartial(w http.ResponseWriter, r *http.Request, s *AppState)

V2LogsPartial re-renders the log view (filter, refresh and periodic poll). It also updates the line count out of band, since only the <pre> is swapped.

func V2Manifest

func V2Manifest(w http.ResponseWriter, r *http.Request, s *AppState)

V2Manifest serves the web app manifest.

func V2MediaIntegrityAction

func V2MediaIntegrityAction(w http.ResponseWriter, r *http.Request, s *AppState)

V2MediaIntegrityAction starts, restarts or stops the check and re-renders the panel with the new state.

func V2MediaIntegrityPanel

func V2MediaIntegrityPanel(w http.ResponseWriter, r *http.Request, s *AppState)

V2MediaIntegrityPanel renders the panel on demand: the maintenance page polls it while a check is running.

func V2NightMaintenanceAction

func V2NightMaintenanceAction(w http.ResponseWriter, r *http.Request, s *AppState)

V2NightMaintenanceAction runs a pass now or marks a missing episode, then re-renders the panel.

func V2NightMaintenancePanel

func V2NightMaintenancePanel(w http.ResponseWriter, r *http.Request, s *AppState)

V2NightMaintenancePanel renders the panel on demand: it polls itself while a job runs.

func V2OAuthPoll

func V2OAuthPoll(w http.ResponseWriter, r *http.Request, s *AppState)

V2OAuthPoll confirms the code/PIN entered by the user.

func V2OAuthStart

func V2OAuthStart(w http.ResponseWriter, r *http.Request, s *AppState)

V2OAuthStart starts the device/PIN flow and renders the provider answer.

func V2Page

func V2Page(w http.ResponseWriter, r *http.Request, s *AppState)

V2Page renders the requested v2 page inside the shell.

func V2Ramdisk

func V2Ramdisk(w http.ResponseWriter, r *http.Request, s *AppState)

V2Ramdisk selects/creates a RAM disk and re-renders the panel.

func V2RenameProgress

func V2RenameProgress(w http.ResponseWriter, r *http.Request, s *AppState)

V2RenameProgress renders the progress fragment used by the polling panel.

func V2RunCycle

func V2RunCycle(w http.ResponseWriter, r *http.Request, s *AppState)

V2RunCycle starts a manual cycle by reusing the existing RunNow handler and returning a modal confirmation to the dashboard action that requested it.

func V2Search

func V2Search(w http.ResponseWriter, r *http.Request, s *AppState)

V2Search runs the manual release search server-side.

func V2SearchAdd

func V2SearchAdd(w http.ResponseWriter, r *http.Request, s *AppState)

V2SearchAdd adds a release to the acquisition queue.

func V2SearchAddAll

func V2SearchAddAll(w http.ResponseWriter, r *http.Request, s *AppState)

V2SearchAddAll queues every ed2k link in the pasted block, reusing the same /api/search/add path as the per-row button.

func V2SearchExplain

func V2SearchExplain(w http.ResponseWriter, r *http.Request, s *AppState)

V2SearchExplain renders the decision trace for an archive release without sending the user back to the classic UI.

func V2SearchLink(w http.ResponseWriter, r *http.Request, s *AppState)

V2SearchLink validates a pasted ed2k:// link and shows it as a search result. While aMule is off or unreachable the row is visible but not addable: the link is checked, the user sees name, size and hash, and Gextto does not queue something it cannot hand to aMule.

func V2SectionAction

func V2SectionAction(w http.ResponseWriter, r *http.Request, s *AppState)

V2SectionAction forwards a maintenance/settings action to the existing API and tells HTMX to reload the page.

func V2SectionForm

func V2SectionForm(w http.ResponseWriter, r *http.Request, s *AppState)

V2SectionForm forwards a rendered form to the existing API. Numbers are sent as JSON numbers, strings as strings; Wrap nests them under an object key, exactly like the classic client did.

func V2SectionTestFTP

func V2SectionTestFTP(w http.ResponseWriter, r *http.Request, s *AppState)

V2SectionTestFTP tests the backup FTP values currently displayed in the section without saving them first.

func V2SeriesEpisodeSearch

func V2SeriesEpisodeSearch(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesEpisodeSearch renders the inline episode-search panel: the releases already in the archive, then the online search it follows.

func V2SeriesEpisodeSearchStatus

func V2SeriesEpisodeSearchStatus(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesEpisodeSearchStatus renders the polled part of the panel: the live progress, or the online releases once the search is over.

func V2SeriesGapsDownloadBest

func V2SeriesGapsDownloadBest(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesGapsDownloadBest is POST /series/gaps/download-best: it queues, for every missing episode the search found, the best copy (the score, then the seeders). It runs as a background job because a `.torrent` link has to be opened first: a series with a hundred gaps would otherwise hold the request for minutes.

func V2SeriesGapsListPartial

func V2SeriesGapsListPartial(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesGapsListPartial renders only the list of missing episodes, filtered by `f`. The search box above it asks for this while the person types, so the list narrows without a full page load and the focus stays in the field.

func V2SeriesGapsSearch

func V2SeriesGapsSearch(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesGapsSearch is POST /series/gaps/search: it starts the whole-series search as a background job and answers with a fragment that polls it. The search used to stop at 15 episodes and hold the request open for minutes; the job covers every gap and can be followed (or cancelled) while it runs.

func V2SeriesGapsSearchCancel

func V2SeriesGapsSearchCancel(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesGapsSearchCancel is POST /series/gaps/search/cancel: it asks the job to stop and renders the status again, which shows the cancellation when the worker has observed it.

func V2SeriesGapsSearchStatus

func V2SeriesGapsSearchStatus(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesGapsSearchStatus is GET /series/gaps/search/status: it renders the running progress or, once the job is done, the same result table.

func V2SeriesHistory

func V2SeriesHistory(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesHistory renders the acquisition events of a series, or of one season/episode, newest first: a modal for an episode, a panel body for the whole series. With `hash` it shows the story of one download instead.

func V2SeriesRenameExecute

func V2SeriesRenameExecute(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesRenameExecute runs the rename and re-renders the panel with the result.

func V2SeriesRenamePreview

func V2SeriesRenamePreview(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesRenamePreview renders the server-side rename preview panel.

func V2SeriesSave

func V2SeriesSave(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesSave mirrors the classic series editor: it reads the whole library and replaces the edited series, then saves the array exactly like /api/config/series.

func V2SeriesSources

func V2SeriesSources(w http.ResponseWriter, r *http.Request, s *AppState)

V2SeriesSources renders the per-episode sources modal using only the local archive. It never triggers an online search (MirCrew / RSS feeds); use the search button for that.

func V2ServiceWorker

func V2ServiceWorker(w http.ResponseWriter, r *http.Request, s *AppState)

V2ServiceWorker serves the service worker from the site root, so its scope covers the whole interface.

func V2SetLanguage

func V2SetLanguage(w http.ResponseWriter, r *http.Request, s *AppState)

V2SetLanguage persists the interface language and goes back to the referer.

func V2SettingsBody

func V2SettingsBody(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsBody swaps the settings navigation and section (tab navigation, search results). The address bar follows the section actually shown.

func V2SettingsCheckbox

func V2SettingsCheckbox(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsCheckbox saves a checkbox group immediately.

func V2SettingsContentArchiveDelete

func V2SettingsContentArchiveDelete(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsContentArchiveDelete deletes one row, selected rows, or all archive rows matching the active title query, then returns the refreshed results.

func V2SettingsContentArchiveSearch

func V2SettingsContentArchiveSearch(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsContentArchiveSearch searches archived releases by title for the cleanup panel shown with content filters.

func V2SettingsEd2kPreallocation

func V2SettingsEd2kPreallocation(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsEd2kPreallocation applies aMule's full-file preallocation from the eD2k settings tab, where the switch lives (it is aMule's setting, not one saved in Gextto's configuration).

func V2SettingsEditorRow

func V2SettingsEditorRow(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsEditorRow returns one empty row (and advances the add button index).

func V2SettingsEditorSave

func V2SettingsEditorSave(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsEditorSave saves a structured list editor.

func V2SettingsEditorTest

func V2SettingsEditorTest(w http.ResponseWriter, r *http.Request, s *AppState)

func V2SettingsFeed

func V2SettingsFeed(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsFeed saves the RSS feed list as the `url` setting (JSON array). A line starting with '#' is stored as well: it disables the source without deleting it.

func V2SettingsIPFilterApply

func V2SettingsIPFilterApply(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsIPFilterApply loads the configured IP filter (downloading the URL if needed) and reports the result in place, from the network settings tab.

func V2SettingsIPFilterStatus

func V2SettingsIPFilterStatus(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsIPFilterStatus reports the configured filter and whether it is already on disk, shown when the network tab opens.

func V2SettingsQbittorrentMappings

func V2SettingsQbittorrentMappings(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsQbittorrentMappings reads qBittorrent's own folder preferences and re-renders the mapping field with the paths that cover Gextto's folders.

func V2SettingsRenamePreview

func V2SettingsRenamePreview(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsRenamePreview recomputes the example file names (episode and movie) without touching the saved settings, so the composer shows a live preview while the user edits.

func V2SettingsRenameSave

func V2SettingsRenameSave(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsRenameSave saves the rename format and template.

func V2SettingsRenameToken

func V2SettingsRenameToken(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsRenameToken appends a placeholder to the rename template.

func V2SettingsSave

func V2SettingsSave(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsSave saves one setting and re-renders its field with the result.

func V2SettingsScoreGroup

func V2SettingsScoreGroup(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsScoreGroup adds, updates or removes one user-defined release-group score. Group suffixes use the same lower-case spelling as release parsing.

func V2SettingsScoreTest

func V2SettingsScoreTest(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsScoreTest scores a release name with the current weights and explains the decision, without downloading anything.

func V2SettingsSearch

func V2SettingsSearch(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsSearch filters the settings index server-side.

func V2SettingsSourceTest

func V2SettingsSourceTest(w http.ResponseWriter, r *http.Request, s *AppState)

func V2SettingsTuningApply

func V2SettingsTuningApply(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsTuningApply applies the proposal and re-renders the card. The value written is the server's own proposal, never one coming from the request: the form only chooses which rows to apply (all of them in Facilitata).

func V2SettingsUpgradeImpact

func V2SettingsUpgradeImpact(w http.ResponseWriter, r *http.Request, s *AppState)

V2SettingsUpgradeImpact runs UpgradeImpact and renders its summary.

func V2SetupAuth

func V2SetupAuth(w http.ResponseWriter, r *http.Request, s *AppState)

V2SetupAuth saves step 1.

func V2SetupFinish

func V2SetupFinish(w http.ResponseWriter, r *http.Request, s *AppState)

V2SetupFinish saves step 5 (start the automatic cycle, leave dry-run) and marks the setup as completed; action=skip only marks it.

func V2SetupPaths

func V2SetupPaths(w http.ResponseWriter, r *http.Request, s *AppState)

V2SetupPaths checks (action=check) or saves (action=save) step 2.

func V2SetupSources

func V2SetupSources(w http.ResponseWriter, r *http.Request, s *AppState)

V2SetupSources saves step 3: an optional indexer and the TMDB/TVDB keys.

func V2Share

func V2Share(w http.ResponseWriter, r *http.Request, s *AppState)

V2Share receives the system share sheet: it never adds anything by itself, it opens Scarico with the shared link in the "add" field.

func V2SourcesCheck

func V2SourcesCheck(w http.ResponseWriter, r *http.Request, s *AppState)

V2SourcesCheck runs the source health check on demand and returns the table.

func V2Table

func V2Table(w http.ResponseWriter, r *http.Request, s *AppState)

V2Table renders only the table body (search, pagination, actions).

func V2TableAction

func V2TableAction(w http.ResponseWriter, r *http.Request, s *AppState)

V2TableAction forwards a generic table action to the existing JSON API and returns the refreshed table body.

func V2TableGapSearch

func V2TableGapSearch(w http.ResponseWriter, r *http.Request, s *AppState)

V2TableGapSearch starts a manual search for a missing episode.

func V2TableLibrary

func V2TableLibrary(w http.ResponseWriter, r *http.Request, s *AppState)

V2TableLibrary toggles or removes a series/movie, mirroring the classic read-modify-write of /api/config/library.

func V2ThemeDelete

func V2ThemeDelete(w http.ResponseWriter, r *http.Request, s *AppState)

V2ThemeDelete removes a saved theme by name.

func V2ThemeModal

func V2ThemeModal(w http.ResponseWriter, r *http.Request, s *AppState)

V2ThemeModal renders the theme picker.

func V2ThemeSave

func V2ThemeSave(w http.ResponseWriter, r *http.Request, s *AppState)

V2ThemeSave stores (or replaces, by name) a theme with four colours.

func V2TmdbAdd

func V2TmdbAdd(w http.ResponseWriter, r *http.Request, s *AppState)

V2TmdbAdd adds a TMDB result to the library.

func V2TmdbCalendar

func V2TmdbCalendar(w http.ResponseWriter, r *http.Request, s *AppState)

V2TmdbCalendar renders the upcoming-releases calendar on demand.

func V2TmdbDiscover

func V2TmdbDiscover(w http.ResponseWriter, r *http.Request, s *AppState)

V2TmdbDiscover renders a trending/popular/category list.

func V2TmdbManual

func V2TmdbManual(w http.ResponseWriter, r *http.Request, s *AppState)

func V2TmdbSearch

func V2TmdbSearch(w http.ResponseWriter, r *http.Request, s *AppState)

V2TmdbSearch searches TMDB (with the TVDB fallback) by title.

func V2TrashDelete

func V2TrashDelete(w http.ResponseWriter, r *http.Request, s *AppState)

V2TrashDelete deletes one entry or empties the trash. It reports back, as a toast, which entries were removed and how much space was freed.

func V2TrashList

func V2TrashList(w http.ResponseWriter, r *http.Request, s *AppState)

V2TrashList renders the trash entries on demand.

func V2Update

func V2Update(w http.ResponseWriter, r *http.Request, s *AppState)

V2Update renders the update panel; POST action=check checks now and action=apply requests the update. While an update runs the panel polls itself with ?from=<version>: once the restarted daemon answers with another version it reports the update as done.

func V2UpdateNotesDismiss

func V2UpdateNotesDismiss(w http.ResponseWriter, r *http.Request, s *AppState)

V2UpdateNotesDismiss closes the "updated" popup for good.

func V3LanguageProfiles

func V3LanguageProfiles(w http.ResponseWriter, r *http.Request, s *AppState)

func V3MovieAdd

func V3MovieAdd(w http.ResponseWriter, r *http.Request, s *AppState)

func V3MovieLookup

func V3MovieLookup(w http.ResponseWriter, r *http.Request, s *AppState)

func V3MovieUpdate

func V3MovieUpdate(w http.ResponseWriter, r *http.Request, s *AppState)

V3MovieUpdate is PUT /api/v3/movie: Jellyseerr sends it for a movie that is in the library but not monitored, to monitor it again.

func V3QualityProfiles

func V3QualityProfiles(w http.ResponseWriter, r *http.Request, s *AppState)

func V3Queue

func V3Queue(w http.ResponseWriter, r *http.Request, s *AppState)

func V3RootFolders

func V3RootFolders(w http.ResponseWriter, r *http.Request, s *AppState)

func V3SeriesAdd

func V3SeriesAdd(w http.ResponseWriter, r *http.Request, s *AppState)

func V3SeriesLookup

func V3SeriesLookup(w http.ResponseWriter, r *http.Request, s *AppState)

func V3SeriesUpdate

func V3SeriesUpdate(w http.ResponseWriter, r *http.Request, s *AppState)

V3SeriesUpdate is PUT /api/v3/series: Jellyseerr sends it when a request adds seasons to a series that is already in the library. The newly monitored seasons are added to the series' season list; nothing is removed.

func V3SystemStatus

func V3SystemStatus(w http.ResponseWriter, r *http.Request, s *AppState)

func V3Tags

func V3Tags(w http.ResponseWriter, r *http.Request, s *AppState)

func ValidateBackup

func ValidateBackup(w http.ResponseWriter, r *http.Request, s *AppState)

ValidateBackup verifies a named local backup before a recovery operation. It never extracts the archive: ZIP names are untrusted and a validation must not be able to write into the data directory.

func ValidateDestination

func ValidateDestination(destination string) error

ValidateDestination creates the post-processing destination (implementation of `validate_destination`). It also verifies that the target directory is writable, catching read-only mounts, network timeouts or disconnected NAS shares. A destination that does not answer within destinationProbeTimeout is reported as an error rather than hanging the caller.

func ValidateDestinationFrom

func ValidateDestinationFrom(source, destination string) error

ValidateDestinationFrom creates the destination and refuses to write inside the source tree (implementation of `validate_destination_from`).

func ValidateHooks

func ValidateHooks(hooks []EventHook) string

ValidateHooks validates a hook list before it is persisted. It returns an error message, or an empty string when the list is valid.

func ValidatePathMappings

func ValidatePathMappings(mappings []PathMapping, required []string) error

ValidatePathMappings is the mandatory preflight: when a backend runs with a different filesystem namespace (Docker, separate mount), every Gextto path that can be handed to it must be covered by an explicit mapping. It also refuses overlapping mappings that would make translation ambiguous.

func ValidateWatchedFolders

func ValidateWatchedFolders(folders []WatchedFolder) string

ValidateWatchedFolders returns an error message, or an empty string when the list is valid.

func Variables

func Variables(event string, payload map[string]any) map[string]string

Variables flattens a JSON payload into `key` and `a.b` string variables and adds the event/time fields every hook can rely on.

func VersionString

func VersionString() string

VersionString returns the installed version, including the release marker written next to the executable by the installer (when present) and the compiled-in build and commit.

func VideoFiles

func VideoFiles(path string) ([]string, error)

VideoFiles returns every video file under path without following symlinks (implementation of `video_files`).

func WarnIfAudioCleanupUnavailable

func WarnIfAudioCleanupUnavailable(cfg *Config)

WarnIfAudioCleanupUnavailable logs once at startup when the feature is on but a tool vanished, so the operator knows why nothing is being cleaned.

func WatchedFoldersView

func WatchedFoldersView(w http.ResponseWriter, r *http.Request, s *AppState)

Types

type AcquisitionEvent

type AcquisitionEvent struct {
	ID         int64  `json:"id"`
	Hash       string `json:"hash"`
	AcqID      string `json:"acq"`
	FirstAt    string `json:"first_at"`
	At         string `json:"at"`
	Repeat     int64  `json:"repeat"`
	Level      string `json:"level"`
	Message    string `json:"message"`
	Fields     string `json:"fields"`
	Kind       string `json:"kind"`
	Title      string `json:"title"`
	SeriesName string `json:"series_name"`
	Season     *int64 `json:"season"`
	Episode    *int64 `json:"episode"`
}

AcquisitionEvent is one stored step of an acquisition.

func (AcquisitionEvent) EpisodeLabel

func (e AcquisitionEvent) EpisodeLabel() string

EpisodeLabel names what the event is about inside its series: S01E03, a whole season (S01) or, for a movie, its title.

func (AcquisitionEvent) LevelClass

func (e AcquisitionEvent) LevelClass() string

LevelClass is the lower-case level, used as a CSS class suffix.

type AddAllFromArchiveInput

type AddAllFromArchiveInput struct {
	Root string `json:"root"`
}

AddAllFromArchiveInput is the body of POST /api/config/add_all_from_archive. `root` is optional when exactly one `archive_root` is configured.

type AddOptions

type AddOptions struct {
	// Paused adds the torrent in pause (no data transfer until resumed).
	Paused bool
	// Sequential enables per-torrent sequential download.
	Sequential bool
	// SeedMode assumes the data is already complete and skips the hash check.
	SeedMode bool
	// QueueTop moves the torrent to the top of the queue.
	QueueTop bool
	// FirstLast prioritises the first and last piece of every file.
	FirstLast bool
	// StopAtMetadata pauses automatically as soon as metadata is received.
	StopAtMetadata bool
	// Preallocate reserves the full size on disk up front (libtorrent
	// `storage_mode_allocate`). The caller resolves the default from the
	// `libtorrent_preallocate` setting.
	Preallocate bool
	// StopWhenReady pauses the torrent as soon as it has finished checking, so
	// metadata/files are present but no data is transferred until resumed.
	StopWhenReady bool
}

AddOptions are the options applied when a torrent is added, based on qBittorrent's rich AddTorrentParams.

type AddTorrentInput

type AddTorrentInput struct {
	Magnet         string  `json:"magnet"`
	SavePath       *string `json:"save_path"`
	StartPaused    bool    `json:"start_paused"`
	NoRename       bool    `json:"no_rename"`
	Sequential     bool    `json:"sequential"`
	SeedMode       bool    `json:"seed_mode"`
	QueueTop       bool    `json:"queue_top"`
	FirstLast      bool    `json:"first_last"`
	StopAtMetadata bool    `json:"stop_at_metadata"`
	// Preallocate overrides the global `libtorrent_preallocate` setting for
	// this add; nil means "use the global default".
	Preallocate *bool `json:"preallocate"`
}

AddTorrentInput is the input of `add_torrent`.

type AppState

type AppState struct {
	// contains filtered or unexported fields
}

AppState is shared by every web handler.

func NewAppState

func NewAppState(
	cfg *Config,
	configPath string,
	i18n *I18nDb,
	db *Database,
	archive *Archive,
	comics *ComicsDb,
	engine *Engine,
	notifier *Notifier,
	tmdb *TmdbClient,
) *AppState

NewAppState builds the shared daemon state. It exists so `cmd/gexttod` (a different package) can construct the state whose fields stay unexported for the in-package web handlers.

func (*AppState) BackgroundContext

func (s *AppState) BackgroundContext() (context.Context, context.CancelFunc)

BackgroundContext returns a context that is cancelled when the daemon starts shutting down. Long operations that touch the torrent engine (the acquisition cycle, manual cycles) take it so they abort before the session is destroyed.

func (*AppState) BackgroundStop

func (s *AppState) BackgroundStop() <-chan struct{}

BackgroundStop is closed as soon as the daemon begins shutting down. Workers select on it so they return before the torrent session is destroyed.

func (*AppState) SetDryRunForced

func (s *AppState) SetDryRunForced(forced bool)

SetDryRunForced records that dry-run was requested on the command line, so no settings change may take the daemon out of it. cmd/gexttod calls it once after NewAppState.

func (*AppState) SleepBackground

func (s *AppState) SleepBackground(d time.Duration) bool

SleepBackground sleeps for d and returns false when a shutdown was requested meanwhile. Workers use it instead of time.Sleep so they can exit promptly.

type Archive

type Archive struct {
	// contains filtered or unexported fields
}

Archive is the durable catalogue of every release that passed through the daemon, backed by its own SQLite database with an FTS5 index over titles.

func OpenArchive

func OpenArchive(path string) (*Archive, error)

OpenArchive opens (creating if needed) the archive database at path.

func (*Archive) Browse

func (a *Archive) Browse(query string, limit int) ([]ArchiveEntry, error)

Browse returns up to `limit` archive entries, optionally filtered by an FTS5 query.

func (*Archive) BrowseContentFilteredPage

func (a *Archive) BrowseContentFilteredPage(query string, filters []string, page, limit int) (*ArchivePage, error)

BrowseContentFilteredPage returns archive rows whose titles match the text query and at least one selected content filter. The regular expression and Unicode-script rules intentionally share titleIsContentFiltered with intake.

func (*Archive) BrowsePage

func (a *Archive) BrowsePage(query string, page, limit int) (*ArchivePage, error)

BrowsePage returns one page of archive entries with the total count.

func (*Archive) CanonicalizeRelease

func (a *Archive) CanonicalizeRelease(release *models.Release, magnet string) error

CanonicalizeRelease is CanonicalizeTorrentURL for a release that still knows its listing guid. The guid is the same key SaveBatch used, so the row is found even when Jackett has already regenerated the download URL.

func (*Archive) CanonicalizeTorrentURL

func (a *Archive) CanonicalizeTorrentURL(torrentURL, magnet string) error

CanonicalizeTorrentURL replaces an ephemeral `.torrent` URL with its durable infohash magnet once the torrent has been downloaded successfully. If the same magnet or torrent is already archived, the obsolete URL row is removed.

func (*Archive) Checkpoint

func (a *Archive) Checkpoint() error

Checkpoint truncates the WAL after a checkpoint (see `CheckpointConnection`).

func (*Archive) CleanupOlderThan

func (a *Archive) CleanupOlderThan(days int64) (int, error)

CleanupOlderThan deletes archive rows older than `days` days.

func (*Archive) CleanupOlderThanKeeping

func (a *Archive) CleanupOlderThanKeeping(days, keepMin int64) (int, error)

CleanupOlderThanKeeping deletes archive rows older than `days` days, always keeping at least the `keepMin` most recent rows.

func (*Archive) Close

func (a *Archive) Close() error

Close closes the underlying SQLite connections (see Database.Close).

func (*Archive) Count

func (a *Archive) Count() (int64, error)

Count returns the number of archived rows.

func (*Archive) Delete

func (a *Archive) Delete(magnet string) (bool, error)

Delete removes the row matching the magnet or its infohash.

func (*Archive) DeleteArchiveSQL

func (a *Archive) DeleteArchiveSQL(ctx context.Context, operation ArchiveSQLOperation, language string) (int64, error)

DeleteArchiveSQL runs the paired DELETE in one transaction and returns the number of removed archive rows.

func (*Archive) DeleteContentFiltered

func (a *Archive) DeleteContentFiltered(query string, filters []string) (int, error)

DeleteContentFiltered removes every archive row matching the text query and at least one selected content filter. Filters are kept explicit so bulk deletion cannot accidentally target the entire catalogue.

func (*Archive) DeleteIDs

func (a *Archive) DeleteIDs(ids []int64) (int, error)

DeleteIDs deletes the given row ids, ignoring non-positive ids.

func (*Archive) DeleteMatching

func (a *Archive) DeleteMatching(query string) (int, error)

DeleteMatching removes every archive listing matching a positive title query. Exclusions use the same syntax as BrowsePage; at least one positive term is required so a typo or an exclusion-only query cannot wipe the catalogue.

func (*Archive) Optimize

func (a *Archive) Optimize(action string) error

Optimize runs VACUUM or ANALYZE (see `OptimizeConnection`).

func (*Archive) PreviewArchiveSQL

func (a *Archive) PreviewArchiveSQL(ctx context.Context, operation ArchiveSQLOperation, language string) (ArchiveSQLPreview, error)

PreviewArchiveSQL runs the read-only query and returns up to archiveSQLMaxRows rows plus the total number of matching rows.

func (*Archive) QuickCheck

func (a *Archive) QuickCheck() ([]string, error)

QuickCheck runs `PRAGMA quick_check` (see `QuickCheck` in database.go).

func (*Archive) RecentEntries

func (a *Archive) RecentEntries(limit int) ([][3]string, error)

RecentEntries returns the most recent `limit` (title, magnet, source) tuples using the index on `added_at`: it avoids loading the whole archive (hundreds of thousands of rows) into memory on every feed-status computation.

func (*Archive) RemoveHash

func (a *Archive) RemoveHash(hash string) (int, error)

RemoveHash removes every archived listing for a rejected infohash. Indexers can publish the same torrent under conflicting season/title metadata, so leaving the rows visible would make the bad release return on every archive pass even after it has been blocklisted.

func (*Archive) ResolveListing

func (a *Archive) ResolveListing(torrentURL, magnet, title string, qualityScore int64) (bool, error)

ResolveListing replaces a `.torrent`-only listing with the magnet and the real torrent name learned by opening it. The row is found by its current link text: the caller is a search result, which does not carry the listing key (a guid), and the URL identifies the row anyway. When another row already holds that torrent the link-only copy is dropped, not rewritten: it is the same listing seen twice and only one row may carry an infohash. It reports whether a row changed.

func (*Archive) RowCount

func (a *Archive) RowCount() int64

RowCount returns the number of rows stored in the archive database.

func (*Archive) SaveBatch

func (a *Archive) SaveBatch(releases []models.Release, cfg *Config) error

SaveBatch archives releases: one row per magnet/listing and per infohash.

func (*Archive) Search

func (a *Archive) Search(query string) ([][3]string, error)

Search returns up to 200 newest (title, magnet, source) tuples matching an FTS5 query. See SearchEntries for the same rows with their infohash.

func (*Archive) SearchEntries

func (a *Archive) SearchEntries(query string) ([]ArchiveListing, error)

SearchEntries returns up to archiveSearchLimit newest archived listings matching the FTS5 query, with the infohash each row already knows. Ordering by discovery time ensures recently released episodes are not hidden behind older catalogue entries when a monitored title has more matches.

func (*Archive) SizeBytes

func (a *Archive) SizeBytes() int64

SizeBytes returns the estimated database size in bytes.

type ArchiveAddInput

type ArchiveAddInput struct {
	Title  string `json:"title"`
	Magnet string `json:"magnet"`
	Source string `json:"source"`
}

ArchiveAddInput is the input of `add_archive_entry`.

type ArchiveBatchInput

type ArchiveBatchInput struct {
	Items []ArchiveBatchItem `json:"items"`
}

ArchiveBatchInput is the input of `batch_archive_download`.

type ArchiveBatchItem

type ArchiveBatchItem struct {
	Title    string `json:"title"`
	Magnet   string `json:"magnet"`
	Source   string `json:"source"`
	Ed2kLink string `json:"ed2k_link"`
}

ArchiveBatchItem is one item of `batch_archive_download`.

type ArchiveDeleteInput

type ArchiveDeleteInput struct {
	Magnet string  `json:"magnet"`
	Ids    []int64 `json:"ids"`
}

ArchiveDeleteInput is the input of `delete_archive_entry`.

type ArchiveEntry

type ArchiveEntry struct {
	ID           int64           `json:"id"`
	Title        string          `json:"title"`
	Magnet       string          `json:"magnet"`
	Source       string          `json:"source"`
	QualityScore int64           `json:"quality_score"`
	AddedAt      string          `json:"added_at"`
	Release      *models.Release `json:"release,omitempty"`
}

ArchiveEntry is one row of the archive with the parsed release attached.

type ArchiveFileRecord

type ArchiveFileRecord struct {
	Season       int64
	Episode      int64
	Title        string
	Path         string
	SizeBytes    int64
	QualityScore int64
}

ArchiveFileRecord is one video file found by a library scan.

type ArchiveImportGuard

type ArchiveImportGuard struct {
	// contains filtered or unexported fields
}

ArchiveImportGuard is an RAII marker for "a download of this series is being copied into the library right now".

func AcquireArchiveImport

func AcquireArchiveImport(series *string) *ArchiveImportGuard

AcquireArchiveImport marks the trimmed series name as busy with a copy into the library and returns the guard. When a rename of the same series is running it waits for it to finish, so files are never renamed while they are being copied. Imports never wait for each other (nested acquisitions are safe). A nil or empty series yields a no-op guard.

func AcquireArchiveImportFor

func AcquireArchiveImportFor(series *string, reason string) *ArchiveImportGuard

AcquireArchiveImportFor is AcquireArchiveImport with the operation that holds the archive: a rename that has to wait then names it (the audio cleanup of the library is not a download being copied, and saying so sent people looking for an import that never existed).

func (*ArchiveImportGuard) Release

func (g *ArchiveImportGuard) Release()

Release clears the busy marker. It is safe to call more than once.

type ArchiveListing

type ArchiveListing struct {
	Title    string
	Magnet   string
	Source   string
	InfoHash string
	// FeedURL is the feed the listing came from, empty for indexer results and
	// for the rows archived before it was stored.
	FeedURL string
}

ArchiveListing is one archived listing as returned by SearchEntries. InfoHash is the infohash known for the torrent: the magnet's own, or the one the indexer declared next to a `.torrent`-only listing. The latter is kept even though the transfer still needs the link, so callers can recognise the torrent (blocklist, duplicates) without downloading it again.

type ArchivePage

type ArchivePage struct {
	Items []ArchiveEntry `json:"items"`
	Total int64          `json:"total"`
	Page  int            `json:"page"`
	Pages int            `json:"pages"`
}

ArchivePage is a page of archive entries plus pagination metadata.

type ArchiveQuery

type ArchiveQuery struct {
	Query *string `json:"query"`
	Q     *string `json:"q"`
	Page  *int    `json:"page"`
	Limit *int    `json:"limit"`
}

ArchiveQuery is the query of `archive_entries`.

type ArchiveSQLLanguage

type ArchiveSQLLanguage struct {
	Code  string
	Label string
	// contains filtered or unexported fields
}

ArchiveSQLLanguage is one language the UI can select for the language-aware operations. Tokens are matched as words after the title is normalised; raw markers are matched against the lower-case title as they are (bracketed forms such as [it] cannot be distinguished from the English word "it" after normalisation).

func ArchiveSQLLanguages

func ArchiveSQLLanguages() []ArchiveSQLLanguage

ArchiveSQLLanguages returns a copy of the languages offered by the UI.

type ArchiveSQLOperation

type ArchiveSQLOperation struct {
	ID            string
	Title         string
	Description   string
	Category      string
	Order         int
	Destructive   bool
	NeedsLanguage bool
	PreviewSQL    string
	DeleteSQL     string
}

ArchiveSQLOperation is one maintenance operation: a preview query and, optionally, the matching delete query.

func LoadArchiveSQLOperations

func LoadArchiveSQLOperations() ([]ArchiveSQLOperation, error)

LoadArchiveSQLOperations returns the operations bundled from scripts/sql.

type ArchiveSQLPreview

type ArchiveSQLPreview struct {
	Columns []string
	Rows    [][]string
	Total   int64
	Shown   int
	Limited bool
}

ArchiveSQLPreview is the read-only result shown before a deletion.

type ArchiveScanInput

type ArchiveScanInput struct {
	Path *string `json:"path"`
}

ArchiveScanInput is the input of `scan_all_archives`.

type AudioCleanupOptions

type AudioCleanupOptions struct {
	Language string `json:"language"`
	Policy   string `json:"policy"`
	Untagged string `json:"untagged"`
}

AudioCleanupOptions is the resolved configuration of one job. It is copied when the job is queued so a later settings change cannot alter work already scheduled.

type AudioCleanupPlan

type AudioCleanupPlan struct {
	Info          MediaInfo
	Keep          []AudioTrackInfo
	Drop          []AudioTrackInfo
	KeepPositions []int // positions inside Info.AudioTracks, in file order
	DropPositions []int // positions inside Info.AudioTracks, in file order
	// DefaultPosition is the kept track that becomes the default one because
	// the default track was removed; -1 when the flags stay as they are.
	DefaultPosition int
	SkipReason      string
}

AudioCleanupPlan is the decision taken from the container alone.

func PlanAudioCleanup

func PlanAudioCleanup(info MediaInfo, opts AudioCleanupOptions) AudioCleanupPlan

PlanAudioCleanup decides what to keep from the probed container. No file name, release tag or external metadata is consulted.

func (AudioCleanupPlan) Skipped

func (p AudioCleanupPlan) Skipped() bool

Skipped reports a file that must not be touched.

type AudioCleanupReport

type AudioCleanupReport struct {
	Path         string
	Applied      bool
	SkipReason   string
	Backend      string
	Kept         []AudioTrackInfo
	Dropped      []AudioTrackInfo
	OriginalSize int64
	NewSize      int64
	SavedBytes   int64
	Elapsed      time.Duration
}

AudioCleanupReport is the outcome of one file.

func RunAudioCleanup

func RunAudioCleanup(ctx context.Context, path string, opts AudioCleanupOptions) (report AudioCleanupReport, err error)

RunAudioCleanup probes path, decides, remuxes, checks and publishes the result. A skipped file returns no error: skipping is a normal outcome. On any error the library file is exactly as it was.

type AudioTrackInfo

type AudioTrackInfo struct {
	Index      int     `json:"index"`
	Codec      string  `json:"codec"`
	Language   string  `json:"language,omitempty"`
	Title      string  `json:"title,omitempty"`
	Channels   int64   `json:"channels,omitempty"`
	Bitrate    int64   `json:"bitrate,omitempty"`
	Default    bool    `json:"default,omitempty"`
	Forced     bool    `json:"forced,omitempty"`
	Commentary bool    `json:"commentary,omitempty"`
	StartTime  float64 `json:"start_time,omitempty"`
	HasStart   bool    `json:"-"`
}

AudioTrackInfo is one audio stream exactly as the container declares it. The release name is only a hint; these fields are what the file really carries, so the audio cleanup can decide without trusting any filename.

type AuthCode

type AuthCode struct {
	Code string `json:"code"`
}

AuthCode is the input of the Simkl PIN poll endpoint.

type BackfillMediaInfoInput

type BackfillMediaInfoInput struct {
	Limit *int `json:"limit"`
}

type BlocklistRecord

type BlocklistRecord struct {
	Reason string
	// ExpiresAt is empty when the block stays for good: the operator's own
	// entries and the permanent ones.
	ExpiresAt string
}

BlocklistRecord is the live entry that keeps one release out of the candidates: why it was blocked and until when.

type BrowseQuery

type BrowseQuery struct {
	Path *string `json:"path"`
}

type CastMember

type CastMember struct {
	ID        *int64  `json:"id"`
	Name      *string `json:"name"`
	Character *string `json:"character"`
	Order     *int64  `json:"order"`
}

CastMember mirrors the `CastMember`.

type CleanTrashInput

type CleanTrashInput struct {
	Force bool `json:"force"`
}

CleanTrashInput is the input of `clean_trash`.

type ComicCheckLinksInput

type ComicCheckLinksInput struct {
	Urls []string `json:"urls"`
}

ComicCheckLinksInput is the input of `comic_check_links`.

type ComicDownload

type ComicDownload struct {
	ID              string  `json:"id"`
	Title           string  `json:"title"`
	Method          string  `json:"method"`
	Status          string  `json:"status"`
	Progress        float64 `json:"progress"`
	DownloadedBytes uint64  `json:"downloaded_bytes"`
	TotalBytes      *uint64 `json:"total_bytes"`
	SpeedBytes      uint64  `json:"speed_bytes"`
	ETASeconds      *uint64 `json:"eta_seconds"`
	Error           *string `json:"error"`
	// Free-form label assigned by the user, shown in the unified download list
	// together with the torrent tags. Kept in memory for the download lifetime
	// because the download row itself is not persisted.
	Tag string `json:"tag"`
	// Resolved URL the download is reading from.
	URL string `json:"url"`
	// Final file path (available once the response headers are known).
	Destination string `json:"destination"`
	// Temporary `.part` path used while the download is in progress.
	Temporary string `json:"temporary"`
	UpdatedAt string `json:"updated_at"`
}

ComicDownload is one visible entry of the comics download list. HTTP and MEGA downloads are kept in memory for their whole lifetime, so the row is never persisted.

func HTTPDownloads

func HTTPDownloads() []ComicDownload

HTTPDownloads returns a snapshot of the comics downloads, most recently updated first.

type ComicDownloadInput

type ComicDownloadInput struct {
	Url      string `json:"url"`
	Method   string `json:"method"`
	Title    string `json:"title"`
	PostUrl  string `json:"post_url"`
	SavePath string `json:"save_path"`
}

ComicDownloadInput is the input of `comic_download`.

type ComicDownloadTagInput

type ComicDownloadTagInput struct {
	Id  string `json:"id"`
	Tag string `json:"tag"`
}

ComicDownloadTagInput is the input of `comic_download_tag`.

type ComicEnabled

type ComicEnabled struct {
	Enabled bool `json:"enabled"`
}

ComicEnabled is the input of `set_comic_enabled`.

type ComicExploreInput

type ComicExploreInput struct {
	Query string `json:"query"`
}

ComicExploreInput is the input of `comic_explore`.

type ComicInput

type ComicInput struct {
	Title       string `json:"title"`
	TagUrl      string `json:"tag_url"`
	FromDate    string `json:"from_date"`
	SavePath    string `json:"save_path"`
	PostUrl     string `json:"post_url"`
	CoverUrl    string `json:"cover_url"`
	Publisher   string `json:"publisher"`
	Description string `json:"description"`
}

ComicInput is the input of `add_comic`.

type ComicLinks struct {
	Magnets     []string `json:"magnets"`
	Torrents    []string `json:"torrents"`
	Mega        []string `json:"mega"`
	Direct      []string `json:"direct"`
	DownloadNow []string `json:"download_now"`
}

ComicLinks groups the download links found in a GetComics post.

type ComicLinksInput

type ComicLinksInput struct {
	Url string `json:"url"`
}

ComicLinksInput is the input of `comic_links`.

type ComicMonitored

type ComicMonitored struct {
	ID                    int64   `json:"id"`
	Title                 string  `json:"title"`
	TagURL                string  `json:"tag_url"`
	PostURL               string  `json:"post_url"`
	CoverURL              string  `json:"cover_url"`
	Publisher             string  `json:"publisher"`
	Description           string  `json:"description"`
	FromDate              string  `json:"from_date"`
	SavePath              string  `json:"save_path"`
	Enabled               bool    `json:"enabled"`
	LastChecked           *string `json:"last_checked"`
	LatestDownloadedTitle string  `json:"latest_downloaded_title"`
}

ComicMonitored is one monitored GetComics tag or post.

type ComicPost

type ComicPost struct {
	Title       string `json:"title"`
	URL         string `json:"url"`
	TagURL      string `json:"tag_url"`
	CoverURL    string `json:"cover_url"`
	Publisher   string `json:"publisher"`
	Description string `json:"description"`
	Date        string `json:"date"`
}

ComicPost is one article found on a GetComics listing or search page.

type ComicTorrent

type ComicTorrent struct {
	Hash          string  `json:"hash"`
	Title         string  `json:"title"`
	PostURL       string  `json:"post_url"`
	SavePath      string  `json:"save_path"`
	CompletedAt   *string `json:"completed_at"`
	ProcessedPath *string `json:"processed_path"`
}

ComicTorrent is one torrent queued by the comics module.

type ComicWeeklyInput

type ComicWeeklyInput struct {
	Date string `json:"date"`
}

ComicWeeklyInput is the input of `comic_weekly_links`.

type ComicsDb

type ComicsDb struct {
	// contains filtered or unexported fields
}

ComicsDb wraps the SQLite connection of the comics database.

func OpenComicsDb

func OpenComicsDb(path string) (*ComicsDb, error)

OpenComicsDb opens (creating it if needed) the comics database at path.

func (*ComicsDb) AddHistory

func (d *ComicsDb) AddHistory(monitoredID int64, postURL, title, magnet, torrentURL string) (bool, error)

AddHistory records a downloaded post. It returns false when the post URL was already present.

func (*ComicsDb) AddMonitored

func (d *ComicsDb) AddMonitored(title, tagURL, fromDate, savePath string) (int64, error)

AddMonitored inserts a monitored title without the rich metadata.

func (*ComicsDb) AddMonitoredWithMetadata

func (d *ComicsDb) AddMonitoredWithMetadata(title, tagURL, postURL, coverURL, publisher, description, fromDate, savePath string) (int64, error)

AddMonitoredWithMetadata inserts (or updates) a monitored title.

func (*ComicsDb) AddTorrent

func (d *ComicsDb) AddTorrent(hash, postURL, title, savePath string) error

AddTorrent registers a torrent queued by the comics module.

func (*ComicsDb) AddWeekly

func (d *ComicsDb) AddWeekly(packDate, magnet, torrentURL string) (bool, error)

AddWeekly records a weekly pack. It returns false when the pack date already existed.

func (*ComicsDb) AlreadySent

func (d *ComicsDb) AlreadySent(postURL string) (bool, error)

AlreadySent reports whether a post URL is already in the comics history.

func (*ComicsDb) Checkpoint

func (d *ComicsDb) Checkpoint() error

Checkpoint truncates the WAL after a checkpoint.

func (*ComicsDb) ClearHistory

func (d *ComicsDb) ClearHistory() (int64, error)

ClearHistory removes the manual/monitored comic download history without touching the separate Weekly Pack history.

func (*ComicsDb) ClearWeeklyHistory

func (d *ComicsDb) ClearWeeklyHistory() (int64, error)

ClearWeeklyHistory removes the Weekly Pack history without touching comic download history.

func (*ComicsDb) Close

func (d *ComicsDb) Close() error

Close closes the underlying SQLite connection (see Database.Close).

func (*ComicsDb) CompleteTorrent

func (d *ComicsDb) CompleteTorrent(hash, path string) error

CompleteTorrent marks a comics torrent as completed with its processed path.

func (*ComicsDb) CompletedTorrents

func (d *ComicsDb) CompletedTorrents(hashes []string) map[string]bool

CompletedTorrents returns, among hashes, the comics torrents already completed (lowercase hash set). The comics pipeline archives them itself, so torrent_meta does not know they are done.

func (*ComicsDb) History

func (d *ComicsDb) History(limit int64) ([]map[string]any, error)

History returns the most recent history rows.

func (*ComicsDb) HistoryLimit

func (d *ComicsDb) HistoryLimit() int64

HistoryLimit is the shared retention limit for comics and Weekly Pack history. It is stored with the comics settings so it is independent from the torrent seed/removal settings.

func (*ComicsDb) ListMonitored

func (d *ComicsDb) ListMonitored(enabledOnly bool) ([]ComicMonitored, error)

ListMonitored returns the monitored comics, ordered by title.

func (*ComicsDb) MarkChecked

func (d *ComicsDb) MarkChecked(id int64) error

MarkChecked records the last check time of a monitored comic.

func (*ComicsDb) MarkWeeklySent

func (d *ComicsDb) MarkWeeklySent(packDate string) error

MarkWeeklySent marks a weekly pack as sent.

func (*ComicsDb) Optimize

func (d *ComicsDb) Optimize(action string) error

Optimize runs `VACUUM`/`ANALYZE`.

func (*ComicsDb) PendingWeekly

func (d *ComicsDb) PendingWeekly() ([]WeeklyPending, error)

PendingWeekly returns the recorded weekly packs that have a link but were never sent.

func (d *ComicsDb) PendingWeeklyWithoutLinks(fromDate string) ([]string, error)

PendingWeeklyWithoutLinks returns the recorded packs whose page was found before GetComics published a download link, oldest first. They are kept apart from PendingWeekly because they are not ready to download yet: their page has to be read again.

func (*ComicsDb) PruneConfiguredHistory

func (d *ComicsDb) PruneConfiguredHistory() error

PruneConfiguredHistory applies the current shared retention setting.

func (*ComicsDb) PruneHistory

func (d *ComicsDb) PruneHistory(limit int64) error

PruneHistory keeps the newest rows in both comic history tables. Weekly rows are retained by pack date/id, so deleting old rows cannot affect the current pending-pack state.

func (*ComicsDb) QuickCheck

func (d *ComicsDb) QuickCheck() ([]string, error)

QuickCheck runs `PRAGMA quick_check`.

func (*ComicsDb) RemoveHistory

func (d *ComicsDb) RemoveHistory(postURL string) (bool, error)

RemoveHistory deletes the history row of a post URL.

func (*ComicsDb) RemoveMonitored

func (d *ComicsDb) RemoveMonitored(id int64) (bool, error)

RemoveMonitored deletes a monitored comic.

func (*ComicsDb) RowCount

func (d *ComicsDb) RowCount() int64

RowCount returns the number of rows stored in the comics database.

func (*ComicsDb) SetEnabled

func (d *ComicsDb) SetEnabled(id int64, enabled bool) (bool, error)

SetEnabled enables or disables a monitored comic.

func (*ComicsDb) SetSetting

func (d *ComicsDb) SetSetting(key, value string) error

SetSetting writes a comics setting.

func (*ComicsDb) Setting

func (d *ComicsDb) Setting(key, fallback string) (string, error)

Setting reads a comics setting, returning the default when it is missing.

func (*ComicsDb) SizeBytes

func (d *ComicsDb) SizeBytes() int64

SizeBytes estimates the database size in bytes.

func (*ComicsDb) Torrent

func (d *ComicsDb) Torrent(hash string) (*ComicTorrent, error)

Torrent returns the comics torrent with the given hash, or nil.

func (d *ComicsDb) UpsertWeeklyLinks(packDate, magnet, torrentURL string) (bool, error)

UpsertWeeklyLinks records the links of a weekly pack, filling a row that was created before the torrent was available. It returns true when the row now has a link and is still to be sent.

func (*ComicsDb) Weekly

func (d *ComicsDb) Weekly(limit int64) ([]map[string]any, error)

Weekly returns the most recent weekly pack rows.

func (d *ComicsDb) WeeklyLinks(packDate string) (magnet, torrentURL string, known bool, err error)

WeeklyLinks returns the links already recorded for a weekly pack, before the row is updated with the links of this cycle. It reports whether the pack was known at all, so the caller can say in the log why it is being downloaded now.

func (*ComicsDb) WeeklySent

func (d *ComicsDb) WeeklySent(packDate string) (bool, error)

WeeklySent reports whether a weekly pack was already sent.

type ComicsImportReport

type ComicsImportReport struct {
	Monitored int `json:"monitored"`
	History   int `json:"history"`
	Weekly    int `json:"weekly"`
	Settings  int `json:"settings"`
	Skipped   int `json:"skipped"`
}

ComicsImportReport is the Result of `import_from_extto`.

func ImportFromExtto

func ImportFromExtto(source string, destination *sql.DB) (ComicsImportReport, error)

ImportFromExtto imports the comics data of an extto source directory into the destination database. `source` is the directory containing `comics.db`.

type Command

type Command struct {
	Kind CommandKind

	// Serve fields.
	DryRun bool
	Config *string

	// Migrate fields.
	From string
	To   string

	// TUI fields.
	TUIURL  string
	TUILang string

	// Update fields.
	Options UpdateOptions
}

Command is a parsed command line.

func DefaultCommand

func DefaultCommand() Command

DefaultCommand returns the command used when no arguments are given.

func Parse

func Parse(args []string) Command

Parse parses the process arguments, excluding `argv[0]`.

type CommandKind

type CommandKind int

CommandKind identifies which Command a parsed line represents.

const (
	// CommandServe runs the daemon (default command).
	CommandServe CommandKind = iota
	// CommandVersion prints the installed version and exits.
	CommandVersion
	// CommandHelp prints usage and exits.
	CommandHelp
	// CommandUpdate downloads and installs the latest components, then exits.
	CommandUpdate
	// CommandMigrate copies and renames a legacy data directory into the
	// current gextto layout.
	CommandMigrate
	// CommandTUI opens the interactive terminal interface.
	CommandTUI
)

type Config

type Config struct {
	DataDir           string            `json:"data_dir"`
	Listen            string            `json:"listen"`
	EngineListen      string            `json:"engine_listen"`
	RefreshSecs       uint64            `json:"refresh_secs"`
	Active            bool              `json:"active"`
	DryRun            bool              `json:"dry_run"`
	FeedURLs          []string          `json:"feed_urls"`
	Blacklist         []string          `json:"blacklist"`
	ContentFilters    []string          `json:"content_filters"`
	SourceFilters     []SourceFilter    `json:"source_filters"`
	MaxReleaseAgeDays int64             `json:"max_release_age_days"`
	Series            []SeriesConfig    `json:"series"`
	Movies            []MovieConfig     `json:"movies"`
	Indexers          []IndexerConfig   `json:"indexers"`
	WebsearchEngines  []string          `json:"websearch_engines"`
	FlaresolverrURL   *string           `json:"flaresolverr_url"`
	Settings          map[string]string `json:"settings"`
	TmdbAPIKey        *string           `json:"tmdb_api_key"`
	RenameEpisodes    bool              `json:"rename_episodes"`
	RenameFormat      string            `json:"rename_format"`
	RenameTemplate    string            `json:"rename_template"`
	// RenameMovieTemplate is the "custom" format for movies: the episode
	// template has season and episode tokens a movie does not have.
	RenameMovieTemplate string  `json:"rename_movie_template"`
	ArchiveRoot         *string `json:"archive_root"`
	TrashPath           *string `json:"trash_path"`
	NotifyTelegram      bool    `json:"notify_telegram"`
	TelegramBotToken    *string `json:"telegram_bot_token"`
	TelegramChatID      *string `json:"telegram_chat_id"`
	NotifyWebhookURL    *string `json:"notify_webhook_url"`
	NotifyWebhookSecret *string `json:"notify_webhook_secret"`
	NotifyWebhookFormat string  `json:"notify_webhook_format"`
	NotifyWebhookToken  *string `json:"notify_webhook_token"`
	NotifyWebhookUser   *string `json:"notify_webhook_user"`
	NotifyEmail         bool    `json:"notify_email"`
	EmailSMTP           string  `json:"email_smtp"`
	EmailFrom           *string `json:"email_from"`
	EmailTo             *string `json:"email_to"`
	EmailPassword       *string `json:"email_password"`
	// Dedicated notification channels, the same ones indexarr and the
	// gx-torrent daemon offer next to Telegram, the generic webhook and e-mail.
	NotifyDiscordURL       *string `json:"notify_discord_url"`
	NotifySlackURL         *string `json:"notify_slack_url"`
	NotifyGotifyURL        *string `json:"notify_gotify_url"`
	NotifyGotifyToken      *string `json:"notify_gotify_token"`
	NotifyNtfyURL          *string `json:"notify_ntfy_url"`
	NotifyNtfyTopic        *string `json:"notify_ntfy_topic"`
	NotifyNtfyToken        *string `json:"notify_ntfy_token"`
	NotifyPushoverToken    *string `json:"notify_pushover_token"`
	NotifyPushoverUser     *string `json:"notify_pushover_user"`
	NotifyAppriseURL       *string `json:"notify_apprise_url"`
	NotifyAppriseKey       *string `json:"notify_apprise_key"`
	NotifyScriptPath       *string `json:"notify_script_path"`
	NotifyScriptArgs       *string `json:"notify_script_args"`
	NotifyEventDownloads   bool    `json:"notify_events_downloads"`
	NotifyEventErrors      bool    `json:"notify_events_errors"`
	NotifyEventHealth      bool    `json:"notify_events_health"`
	NotifyEventMaintenance bool    `json:"notify_events_maintenance"`
	NotifyCooldownMinutes  int64   `json:"notify_cooldown_minutes"`
	NotifyLanguage         string  `json:"notify_language"`
	CleanupUpgrades        bool    `json:"cleanup_upgrades"`
	CleanupMinScoreDiff    int64   `json:"cleanup_min_score_diff"`
	UpgradeMinScoreDiff    int64   `json:"upgrade_min_score_diff"`
	UpgradeUntilScore      int64   `json:"upgrade_until_score"`
	// StallAlternativeAfterMin/ScoreDrop relax the quality floor for an episode
	// whose download is stuck: after this many minutes without progress an
	// alternative scoring up to ScoreDrop points less may be started, while the
	// stuck torrent stays in the session. 0 disables either half.
	StallAlternativeAfterMin  int64            `json:"stall_alternative_after_min"`
	StallAlternativeScoreDrop int64            `json:"stall_alternative_score_drop"`
	CleanupAction             string           `json:"cleanup_action"`
	Transfer                  TransferSettings `json:"transfer"`
	DownloadDir               string           `json:"torrent_dir"`
	DownloadTempDir           *string          `json:"torrent_temp_dir"`
	StateDir                  string           `json:"state_dir"`
}

Config is the runtime configuration of the daemon.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig implements `impl Default for Config`.

func LatestConfig

func LatestConfig(s *AppState) *Config

LatestConfig returns the configuration reloaded when the generation changed.

func LoadConfig

func LoadConfig(path string) (Config, error)

LoadConfig reads the JSON configuration file, overlays the settings stored in `gextto_config.db` and finally applies the environment overrides.

func (*Config) AcquisitionScore

func (c *Config) AcquisitionScore(release *models.Release) int64

AcquisitionScore is ReleaseScore plus the swarm-health adjustment, and it is used only where a release is weighed against alternatives to actually claim a download slot. It is deliberately not folded into ReleaseScore: that score is also used for archived files and for the UI, where a swarm is meaningless (archived releases carry `Seeders = -1`, which the adjustment leaves neutral).

The adjustment is intentionally small relative to quality: the bonus is capped below DefaultUpgradeMinScoreDiff and the empty-swarm penalty is bounded, so a better resolution always wins and health alone never forces an upgrade.

func (*Config) AllReleaseDeniedReason

func (c *Config) AllReleaseDeniedReason(release *models.Release) string

AllReleaseDeniedReason combines every global rejection reason (static filters, per-source filters and the built-in sanity rules). Used for logging and the manual search `allowed` flag so all layers speak with one voice.

func (*Config) ArchiveTorrentLinkUnavailable

func (c *Config) ArchiveTorrentLinkUnavailable(rawURL, feedURL string) bool

ArchiveTorrentLinkUnavailable reports whether an archived `.torrent` link must not be opened any more: it belongs to a switched-off indexer or to a feed removed from Sources.

func (*Config) DebugEnabled

func (c *Config) DebugEnabled() bool

DebugEnabled reports whether to log debug-level diagnostics (legacy `debug_*`).

func (*Config) DefaultLanguage

func (c *Config) DefaultLanguage() string

DefaultLanguage is the default language for acquisitions and rename fallback (e.g. `ita`).

func (*Config) DelayBypassScore

func (c *Config) DelayBypassScore() int64

DelayBypassScore is the score at or above which a release is grabbed immediately, bypassing the delay profile. `0` disables the bypass.

func (*Config) DelayMinutes

func (c *Config) DelayMinutes(kind string) int64

DelayMinutes is the delay profile: minutes a series (`series`) or movie (`movie`) release is held before grabbing. `0` disables the delay.

func (*Config) FeedMaxPages

func (c *Config) FeedMaxPages() int

FeedMaxPages is the number of listing pages to fetch per feed (legacy `MAX_PAGES`, default 3). This used to be read from `stop_on_old_page_threshold`, which in legacy is a 0..1 ratio — a value like `0.8` could not parse as a page count and silently fell back to 3.

func (*Config) FileScore

func (c *Config) FileScore(path string, kind string, title string) int64

FileScore scores an already archived file with the same release scorer used at acquisition time. `title` is the monitored identity for movies (and is only informational for series); an empty title falls back to the file name. This keeps archive scans and post-processing from silently dropping the size/subtitle parts of the score.

func (*Config) FindMovieMatch

func (c *Config) FindMovieMatch(title string, year *int64) *MovieConfig

FindMovieMatch finds the monitored movie matching title and year.

func (*Config) FindMovieMatchForRelease

func (c *Config) FindMovieMatchForRelease(release *models.Release, manual bool) *MovieConfig

FindMovieMatchForRelease resolves a monitored movie from a collected release. Prowlarr supplies TmdbID in its native JSON response; use that authoritative identifier before the title/year fallback, because release titles frequently omit the theatrical year.

func (*Config) FindMovieMatchManual

func (c *Config) FindMovieMatchManual(title string, year *int64) *MovieConfig

FindMovieMatchManual is like `FindMovieMatch`, but for manual queueing (archive, search, feed results): the title must match, while the year is optional. If both years are present they must stay within ±1; if the movie or release year is missing the match is accepted, so a monitored movie is not rejected with "film non monitorato".

func (*Config) FindSeriesByName

func (c *Config) FindSeriesByName(name string) *SeriesConfig

FindSeriesByName finds a configured series by name/alias ignoring the monitored season and enabled filters. Used to rename/operate on already-archived files, which must not be skipped just because their season is not monitored.

func (*Config) FindSeriesMatch

func (c *Config) FindSeriesMatch(name string, season *int64) *SeriesConfig

FindSeriesMatch finds the monitored series a release belongs to, honouring enabled state, ignored seasons and the configured season ranges.

func (*Config) FromEnv

func (c *Config) FromEnv()

FromEnv applies the environment overrides (implementation of `from_env`).

func (*Config) MovieReleaseAllowed

func (c *Config) MovieReleaseAllowed(movie *MovieConfig, quality *models.Quality) bool

MovieReleaseAllowed checks a movie release against the title requirements.

func (*Config) MovieReleaseAllowedForTitle

func (c *Config) MovieReleaseAllowedForTitle(movie *MovieConfig, quality *models.Quality, title string) bool

MovieReleaseAllowedForTitle applies the movie's technical requirements and its title-specific exclusion list to the raw release title.

func (*Config) PrepareDirs

func (c *Config) PrepareDirs() error

PrepareDirs creates the runtime directories.

func (*Config) PrepareDirsReport

func (c *Config) PrepareDirsReport() (warnings []string, err error)

PrepareDirsReport creates the working folders. Only the data and state folders are required to start: a download, temporary or trash folder that cannot be created (a configuration restored on another machine, a NAS not mounted yet) is returned as a warning, so the daemon still starts and the paths can be fixed from the interface, where Health reports them.

func (*Config) QualityScore

func (c *Config) QualityScore(quality *models.Quality) int64

QualityScore is the score used for every release decision's quality component.

func (*Config) RamdiskDir

func (c *Config) RamdiskDir() *string

RamdiskDir returns the configured RAM disk directory, when non-empty.

func (*Config) RamdiskEnabled

func (c *Config) RamdiskEnabled() bool

RamdiskEnabled is true when the RAM disk download tier is active. A configured directory enables it unless `libtorrent_ramdisk_enabled` is explicitly falsy.

func (*Config) RamdiskMarginBytes

func (c *Config) RamdiskMarginBytes() uint64

RamdiskMarginBytes is the free space (bytes) to keep on the RAM disk after a download finishes.

func (*Config) RamdiskMinFreeBytes

func (c *Config) RamdiskMinFreeBytes() uint64

RamdiskMinFreeBytes is the explicit free-space floor in bytes; `0` derives it from the margin.

func (*Config) RamdiskThresholdBytes

func (c *Config) RamdiskThresholdBytes() uint64

RamdiskThresholdBytes is the maximum size (bytes) for a single torrent admitted to the RAM disk.

func (*Config) ReleaseAllowed

func (c *Config) ReleaseAllowed(release *models.Release) bool

ReleaseAllowed reports whether a release passes every global filter.

func (*Config) ReleaseDeniedReason

func (c *Config) ReleaseDeniedReason(release *models.Release) string

ReleaseDeniedReason is the human-readable reason a release is refused by the global filters, or `""` when it is allowed. Used to make every filter decision visible in the log instead of silently dropping releases.

func (*Config) ReleaseIsMonitored

func (c *Config) ReleaseIsMonitored(release *models.Release) bool

ReleaseIsMonitored reports whether a release belongs to a monitored title. Global filters run before acquisition matching, so unrelated indexer noise must not produce rejection logs (not even at DEBUG).

func (*Config) ReleaseScore

func (c *Config) ReleaseScore(release *models.Release) int64

ReleaseScore is the score used for acquisition, upgrade decisions and archive comparisons.

func (*Config) ReleaseScoreForMovie

func (c *Config) ReleaseScoreForMovie(release *models.Release, movie *MovieConfig) int64

ReleaseScoreForMovie is the variant used by a movie-specific search, where the monitored movie is already known even if the raw release title is not a perfect match.

func (*Config) ResolveArchivePath

func (c *Config) ResolveArchivePath(series *SeriesConfig) *string

ResolveArchivePath is the effective archive folder of a series: `archive_path` when configured, otherwise a subfolder of `archive_root` whose name matches the series (or an alias). Port of the legacy auto-detect: it serves both the download destination and the on-disk file scan.

func (*Config) ResolveTrashPath

func (c *Config) ResolveTrashPath() string

ResolveTrashPath returns the configured trash directory or a safe default under DataDir ("trash") when no path was explicitly configured.

func (*Config) ScoreWeightsFingerprint

func (c *Config) ScoreWeightsFingerprint() string

ScoreWeightsFingerprint is a stable hash of every score-* setting and of the scorer version. The daemon compares it across restarts to detect a scoring change: stored quality scores are then recomputed so a weight edit cannot masquerade as an upgrade and trigger pointless re-downloads.

func (*Config) SeriesLastResortAllowed

func (c *Config) SeriesLastResortAllowed(series *SeriesConfig, quality *models.Quality, title string) bool

SeriesLastResortAllowed reports whether a series release fails only the resolution of the quality profile: language, subtitles, audio and the exclusions still hold. The missing-episode search takes such a release when nothing within the profile exists, rather than leaving the hole open.

func (*Config) SeriesReleaseAllowed

func (c *Config) SeriesReleaseAllowed(series *SeriesConfig, quality *models.Quality, title string) bool

SeriesReleaseAllowed checks a series release against the title requirements.

func (*Config) ShouldSearchTitlesInCycle

func (c *Config) ShouldSearchTitlesInCycle() bool

ShouldSearchTitlesInCycle reports whether the daemon's scheduled cycle should run the online title search fan-out across Torznab indexers.

By default ("auto" or empty), when feeds are configured they provide the continuous stream of releases that populate the local SQLite archive; the cycle then queries the archive in milliseconds, skipping the multi-minute online sweep across dozens of series and movies. When no feeds are configured, title search runs so installations without RSS/HTML feeds can still discover releases on their Torznab indexers.

The operator can override this with the `cycle_title_search` setting: - "never" / "no" / "false": never search titles online during cycles. - "always" / "yes" / "true": always search titles online during cycles. - "auto" (default): search titles online only if FeedURLs is empty.

func (*Config) SourceFilterDeniedReason

func (c *Config) SourceFilterDeniedReason(release *models.Release) string

SourceFilterDeniedReason is the reason a release is refused by a per-source filter, if any. Unlike the global filters this needs the dynamic source/keyword names, so it returns an owned string.

func (*Config) StopOnOldPageRatio

func (c *Config) StopOnOldPageRatio() float64

StopOnOldPageRatio is the legacy `stop_on_old_page_threshold`: ratio (0..=1) of old releases on a page above which the listing walk stops early. Only meaningful together with `max_release_age_days`.

func (*Config) TmdbLanguage

func (c *Config) TmdbLanguage() string

TmdbLanguage returns the BCP-47 language used for TMDB API calls (e.g. `it-IT`).

func (*Config) TorrentCopyDir

func (c *Config) TorrentCopyDir() *string

TorrentCopyDir is the optional folder where the `.torrent` file of every started torrent is copied (empty disables the copy).

func (*Config) TorrentLinkFromDisabledIndexer

func (c *Config) TorrentLinkFromDisabledIndexer(rawURL string) bool

TorrentLinkFromDisabledIndexer reports whether a `.torrent` link belongs to an indexer manager that is configured but switched off. Its links are no longer served — Jackett answers "this indexer is not configured" for the downloads it still has in its catalogue — so a release whose only source is one of them cannot be downloaded. The release archive keeps those listings for a year: opening one every cycle costs a request and an error message about a source the operator already turned off.

func (*Config) TorrentLinkFromRemovedFeed

func (c *Config) TorrentLinkFromRemovedFeed(feedURL string) bool

TorrentLinkFromRemovedFeed reports whether a listing comes from a feed that is no longer in Sources. The archive row remembers the feed line it came from (models.Release.FeedURL), because the source label does not identify it: the ext.to uploader listings all read as `ExtTo - <user>` and several feeds can share a name. A feed deleted or commented out in the list behaves like a switched-off indexer: its rows stay in the catalogue and stay browsable, but their `.torrent` links are no longer opened. Rows archived before the feed line was stored carry an empty value and keep the old behaviour.

func (*Config) TorrentPreallocate

func (c *Config) TorrentPreallocate() bool

TorrentPreallocate reports whether new downloads reserve their full size on disk up front (`storage_mode_allocate`) instead of growing sparsely. Default true: it avoids fragmentation on NAS/HDD and surfaces "no space" immediately. It can be overridden per add.

func (*Config) TvdbAPIKey

func (c *Config) TvdbAPIKey() *string

TvdbAPIKey returns TheTVDB API key, when configured.

func (*Config) TvdbLanguage

func (c *Config) TvdbLanguage() string

TvdbLanguage is the preferred TVDB language (falls back to the default acquisition language).

func (*Config) TvdbPin

func (c *Config) TvdbPin() string

TvdbPin is the TheTVDB subscriber PIN, needed at login by the "user-supported" API keys (blank when not set).

func (*Config) UnmarshalJSON

func (c *Config) UnmarshalJSON(data []byte) error

UnmarshalJSON reproduces the JSON JSON default attributes of `Config`: `blacklist`, `rename_format` and `rename_template` fall back to their defaults when the key is absent.

type ConfigCache

type ConfigCache struct {
	// contains filtered or unexported fields
}

ConfigCache holds the loaded configuration together with the generation it was loaded at.

type ConsumptionStats

type ConsumptionStats struct {
	TotalBytes      int64              `json:"total_bytes"`
	Last30DaysBytes int64              `json:"last_30_days_bytes"`
	Last7DaysBytes  int64              `json:"last_7_days_bytes"`
	Daily7d         []DailyConsumption `json:"daily_7d"`
}

ConsumptionStats is the aggregate download consumption.

type CpuSample

type CpuSample struct {
	// contains filtered or unexported fields
}

CpuSample is the last system CPU reading from /proc/stat.

type CycleState

type CycleState struct {
	// contains filtered or unexported fields
}

CycleState guards the latest cycle statistics.

func (*CycleState) Mutate

func (c *CycleState) Mutate(fn func(*models.CycleStats))

Mutate runs fn against the current cycle statistics while holding the lock.

func (*CycleState) Set

func (c *CycleState) Set(value models.CycleStats)

Set replaces the current cycle statistics.

func (*CycleState) Snapshot

func (c *CycleState) Snapshot() models.CycleStats

Snapshot returns the current cycle statistics.

type DailyConsumption

type DailyConsumption struct {
	Date  string `json:"date"`
	Bytes int64  `json:"bytes"`
}

DailyConsumption is one day of consumption.

type DailyCount

type DailyCount struct {
	Day   string `json:"day"`
	Count int    `json:"count"`
}

DailyCount is one day of a daily metric.

type Database

type Database struct {
	// contains filtered or unexported fields
}

Database implements the `Database`: a wrapper around the single SQLite connection of one Gextto database.

func OpenDatabase

func OpenDatabase(path string) (*Database, error)

OpenDatabase opens the database at path, applies the shared pragmas and runs the schema migrations.

func (*Database) AckProblems

func (d *Database) AckProblems() (int64, error)

AckProblems marks every acquisition event seen so far as read and returns the id it stored. Events written afterwards have a higher id and show again.

func (*Database) AcquisitionEvents

func (d *Database) AcquisitionEvents(hash string) ([]AcquisitionEvent, error)

AcquisitionEvents returns the story of one torrent, oldest first.

func (*Database) AcquisitionEventsByAcqID

func (d *Database) AcquisitionEventsByAcqID(acq string) ([]AcquisitionEvent, error)

AcquisitionEventsByAcqID returns the story of the acquisition whose short ID (as printed in the log) is acq, oldest first.

func (*Database) AcquisitionEventsForTitle

func (d *Database) AcquisitionEventsForTitle(series string, season, episode *int64, limit int) ([]AcquisitionEvent, error)

AcquisitionEventsForTitle returns the most recent events of a series (or of one season/episode when given), newest first, at most limit rows. A season pack has no episode: it is included in the story of each of its episodes.

func (*Database) AcquisitionProblems

func (d *Database) AcquisitionProblems(ackID int64, limit int) ([]AcquisitionEvent, error)

AcquisitionProblems returns, for every download with an unresolved warning, an error or a salvage (🛟), its most recent such event, newest first, at most limit rows. Repeat holds how many there were. It does not look at a time window: a warning stays until the download is resolved, so "ultime 24 ore" is no longer the rule. A download whose file was added to the library, or which superseded an existing copy (♻️), is left out: its cycle completed correctly, so a later warning (a finalization or cleanup that failed after the import) is noise, not something to check.

ackID is the watermark of the events the operator already marked as read (ProblemsAckID): events up to it are hidden. A download that produces a new warning gets a higher id and shows again, so "Pulisci" never hides a future problem. Both the problem and the "good" event are anchored to the last download start (📥): only the current cycle counts, so a stale warning from a previous cycle, before a re-download, does not show and does not resurface.

func (*Database) AddForcedGap

func (d *Database) AddForcedGap(series string, season, episode int64) error

AddForcedGap records an explicit "re-download this episode" request. A forced gap bypasses the season-pack cover, the ignored set and the "a later episode is already archived" rule, so an episode removed from the library can be fetched again. It is cleared as soon as the episode is present again.

func (*Database) AllSeriesEpisodes

func (d *Database) AllSeriesEpisodes() (*SeriesEpisodeIndex, error)

AllSeriesEpisodes reads the SeriesEpisodeIndex of the whole library.

func (*Database) AnySourceSuccessToday

func (d *Database) AnySourceSuccessToday(kind, exclude string) (bool, error)

AnySourceSuccessToday reports whether a source of the same kind other than exclude succeeded today. The automatic-disable rule uses it to tell a broken feed from a network/DNS outage that affects every feed at once.

func (*Database) ApplyMediaIntegrityManifest

func (d *Database) ApplyMediaIntegrityManifest(entries map[string]mediaIntegrityManifestEntry) (int, error)

ApplyMediaIntegrityManifest marks the archived files the external tool already verified as checked, so the pass does not decode them again. It only trusts an entry when the file on disk still has the size and modification time the report recorded.

func (*Database) ArchiveGaps

func (d *Database) ArchiveGaps() ([]SeriesGap, error)

ArchiveGaps computes the missing episodes for every series/season.

func (*Database) ArchiveGapsForSeries

func (d *Database) ArchiveGapsForSeries(seriesName string) ([][2]int64, error)

ArchiveGapsForSeries is the same gap calculation restricted to one series.

func (*Database) ArchivedEpisodeFiles

func (d *Database) ArchivedEpisodeFiles() ([][2]string, error)

ArchivedEpisodeFiles returns `(series name, archive path)` for downloaded episodes with a stored archive path.

func (*Database) ArchivedEpisodeForPath

func (d *Database) ArchivedEpisodeForPath(path string) (series string, season, episode int64, title, hash string, ok bool, err error)

ArchivedEpisodeForPath finds the archived episode a file belongs to. The stored path is usually the file itself; older imports stored the series folder, so a row whose path is the folder of the file counts when its season and episode are the ones written in the file name. hash is the magnet hash of the episode, "" when it has none.

func (*Database) ArchivedEpisodePath

func (d *Database) ArchivedEpisodePath(series string, season, episode int64) (string, error)

ResetEpisode resets the state of one episode. ArchivedEpisodePath returns the archived file path of an episode, or "" when the episode has no archived file.

func (*Database) ArchivedEpisodeRows

func (d *Database) ArchivedEpisodeRows() ([]archivedEpisodeRow, error)

ArchivedEpisodeRows lists the archived episodes with a stored path.

func (*Database) ArchivedMovieForPath

func (d *Database) ArchivedMovieForPath(path string) (hash, name string, year int64, ok bool, err error)

ArchivedMovieForPath finds the archived movie a file belongs to: the stored path of its torrent, a file usually and the movie folder when the files were not flattened.

func (*Database) ArchivedMoviePaths

func (d *Database) ArchivedMoviePaths() ([]string, error)

ArchivedMoviePaths lists the library paths of the movies still in the library.

func (*Database) BeginTorrentAdd

func (d *Database) BeginTorrentAdd(release *models.Release, score int64) error

BeginTorrentAdd records the intent to add the release's torrent. It fails for a release without a magnet hash: such a torrent could be neither registered nor withdrawn, so it must not reach the engine.

func (*Database) BlockedProviders

func (d *Database) BlockedProviders() (map[[2]string]struct{}, error)

BlockedProviders returns all currently disabled `(kind, provider)` pairs.

func (*Database) Blocklist

func (d *Database) Blocklist(release *models.Release, reason string) error

Blocklist adds a release to the blocklist for good.

func (*Database) BlocklistDeadSwarm

func (d *Database) BlocklistDeadSwarm(release *models.Release, base time.Duration) (time.Duration, error)

BlocklistDeadSwarm blocks a release refused for an empty swarm for the period it has earned, and returns that period (zero means forever). The first refusal lasts the configured base period, the second four times as long and the third twelve times, capped at three months: a release whose swarm never revives stops coming back at every cycle, while a swarm that revives is still seen again. A zero base keeps the release blocked forever, as the setting says.

func (*Database) BlocklistDeadSwarmBecause

func (d *Database) BlocklistDeadSwarmBecause(release *models.Release, base time.Duration, reason string) (time.Duration, error)

BlocklistDeadSwarmBecause is BlocklistDeadSwarm for a release nobody was sharing while it downloaded, under a reason of its own: an eD2k file that stalled is the same situation, and its episode is left unfillable for ever if the block never expires.

func (*Database) BlocklistEntries

func (d *Database) BlocklistEntries(limit int64) ([]any, error)

BlocklistEntries returns the blocklist entries for the UI/API. Expired entries are dropped first, so the page never shows a block that no longer applies.

func (*Database) BlocklistRecordFor

func (d *Database) BlocklistRecordFor(hash string) (BlocklistRecord, bool)

BlocklistRecordFor returns the live blocklist entry of a hash, if any. It is asked one release at a time, for the few copies whose refusal is about to be told in the log.

func (*Database) BlocklistUntil

func (d *Database) BlocklistUntil(release *models.Release, reason string, until time.Time) error

BlocklistUntil adds a release to the blocklist until `until`; after that the entry stops counting and the release returns among the candidates. A zero `until` means forever (see Blocklist).

func (*Database) BlocklistedHashes

func (d *Database) BlocklistedHashes() (map[string]struct{}, error)

BlocklistedHashes loads the immutable blocklist snapshot used during one orchestration cycle. Entries whose block has expired are dropped first: they are no longer a block, so the cycle must be free to pick those releases.

func (*Database) BlocklistedTitles

func (d *Database) BlocklistedTitles() (map[string]struct{}, error)

BlocklistedTitles returns the normalized titles of the releases in the blocklist, using the same key as duplicate detection. It is the fallback for a listing that carries only a `.torrent` link: until its link is opened its infohash is unknown, but its title already says which release it is. Without this check every cycle would ask the indexer for the magnet of a release that is blocked, only to reject it immediately afterwards.

func (*Database) CheckMovie

func (d *Database) CheckMovie(release *models.Release) (bool, string, error)

CheckMovie implements `Database::check_movie`.

func (*Database) CheckMovieScored

func (d *Database) CheckMovieScored(release *models.Release, score, minScoreDiff int64) (bool, string, error)

CheckMovieScored implements `Database::check_movie_scored`.

func (*Database) CheckMovieScoredWith

func (d *Database) CheckMovieScoredWith(release *models.Release, score, minScoreDiff int64, forbidUpgrade bool) (bool, string, error)

CheckMovieScoredWith refuses to replace a real imported movie when `forbidUpgrade` is set.

func (*Database) CheckSeries

func (d *Database) CheckSeries(release *models.Release) (bool, string, error)

checkSeries implements `Database::check_series`.

func (*Database) CheckSeriesManualScored

func (d *Database) CheckSeriesManualScored(release *models.Release, score, minScoreDiff int64, context *models.ApprovalContext) (bool, string, error)

CheckSeriesManualScored approves the explicit "Accoda" action. A download incomplete (even present in the client) does not equal a copy: only an already archived release, the same active hash or a blocklisted release are refused.

func (*Database) CheckSeriesScored

func (d *Database) CheckSeriesScored(release *models.Release, score, minScoreDiff int64, context *models.ApprovalContext) (bool, string, error)

CheckSeriesScored implements `Database::check_series_scored`.

func (*Database) Checkpoint

func (d *Database) Checkpoint() error

Checkpoint truncates the WAL (see `CheckpointConnection`).

func (*Database) Cleanup

func (d *Database) Cleanup(retainCycles, errorAgeDays int64) (MaintenanceReport, error)

Cleanup removes old cycle history and stale errored torrents.

func (*Database) ClearForcedGap

func (d *Database) ClearForcedGap(series string, season, episode int64) error

ClearForcedGap drops a forced-gap request (the episode is back in the library or a download for it is active again).

func (*Database) ClearGapSearched

func (d *Database) ClearGapSearched(seriesName string, season, episode int64) error

ClearGapSearched forgets the last online search of a gap so the next cycle retries it immediately. Used when a dead-swarm download is abandoned and an alternative release must be sought without waiting for the throttle.

func (*Database) ClearMediaIntegrityChecks

func (d *Database) ClearMediaIntegrityChecks() error

ClearMediaIntegrityChecks forgets every outcome: the next pass rechecks the whole library.

func (*Database) ClearMediaIntegrityProblem

func (d *Database) ClearMediaIntegrityProblem(problem MediaIntegrityProblem) error

ClearMediaIntegrityProblem removes one item once it has been sent back to the downloads, so the panel does not keep offering a file that is already gone.

func (*Database) ClearMetadataWait

func (d *Database) ClearMetadataWait(hash string) error

ClearMetadataWait drops the saved metadata wait of a torrent: the file list arrived, the download was paused or it left the metadata state.

func (*Database) ClearProviderStatus

func (d *Database) ClearProviderStatus(provider *string) error

ClearProviderStatus clears one provider, or every provider when `provider` is nil.

func (*Database) ClearTorrentLinkFailure

func (d *Database) ClearTorrentLinkFailure(rawURL string) error

ClearTorrentLinkFailure forgets the URL: it worked, so it is not dead and must be eligible again if the indexer breaks later.

func (*Database) Close

func (d *Database) Close() error

Close closes the underlying SQLite connection. The OS reclaims the handle at process exit, but an explicit close keeps shutdown deterministic and lets the daemon be embedded without leaking connections.

func (*Database) CompletedTorrents

func (d *Database) CompletedTorrents(offset, limit int, query string) ([]StoredTorrent, int64, error)

CompletedTorrents returns the download-history page and total count.

func (*Database) ConsumptionStats

func (d *Database) ConsumptionStats() (ConsumptionStats, error)

ConsumptionStats returns the aggregate download consumption.

func (*Database) CountKeyword

func (d *Database) CountKeyword(keyword string) (int64, error)

CountKeyword counts the rows matching one keyword.

func (*Database) CountKeywords

func (d *Database) CountKeywords(keywords []string) (int64, error)

CountKeywords counts the rows matching every keyword.

func (*Database) CountMediaIntegrityTargets

func (d *Database) CountMediaIntegrityTargets(force bool) (int, error)

CountMediaIntegrityTargets counts the files the next pass will check.

func (*Database) DBSizeBytes

func (d *Database) DBSizeBytes() int64

DBSizeBytes returns the estimated database size in bytes.

func (*Database) DBTotalRows

func (d *Database) DBTotalRows() int64

DBTotalRows returns the total number of rows in the main tables.

func (*Database) DeadSwarmStrikes

func (d *Database) DeadSwarmStrikes(hash string) (int, error)

DeadSwarmStrikes reports how many times a release was refused for an empty swarm, counting the refusals whose block has already expired.

func (*Database) DeletePackFileCheck

func (d *Database) DeletePackFileCheck(hash string) error

DeletePackFileCheck forgets the announcement once it is sent or dropped.

func (*Database) DeleteProviderStatus

func (d *Database) DeleteProviderStatus(kind, provider string) error

DeleteProviderStatus removes the backoff row of a source that is no longer configured or is switched off, so it cannot outlive the integration.

func (*Database) DeleteStallWatch

func (d *Database) DeleteStallWatch(hash string) error

DeleteStallWatch forgets monitor state once progress resumes, completion is reached, or the torrent leaves the session.

func (*Database) DownloadedMovieCopies

func (d *Database) DownloadedMovieCopies() ([]DownloadedMovieCopy, error)

DownloadedMovieCopies returns every movie already in the library, newest first, with the archive path of the torrent that imported it. It feeds the "downloaded" check of the monitored-movies list: a movie with a copy shows where the file is, without opening its detail.

func (*Database) DownloadedMovies

func (d *Database) DownloadedMovies(limit int) ([]MovieHistory, error)

DownloadedMovies returns the downloaded movies of the history view.

func (*Database) EndTorrentAdd

func (d *Database) EndTorrentAdd(release *models.Release) error

EndTorrentAdd clears the intent once the add's outcome is recorded.

func (*Database) EpisodeAirDates

func (d *Database) EpisodeAirDates() (map[airDateKey]string, error)

EpisodeAirDates is the date cache for the global missing-episodes view.

func (*Database) EpisodeCurrentRelease

func (d *Database) EpisodeCurrentRelease(series string, season, episode int64) (models.Release, bool, error)

EpisodeCurrentRelease reconstructs the release stored on an episode row so a re-download can blocklist it and search for a different copy.

func (*Database) EpisodeMediaInfo

func (d *Database) EpisodeMediaInfo(series string, season, episode int64) (map[string]any, error)

EpisodeMediaInfo returns the stored probe of an episode, if any.

func (*Database) EpisodesForSeries

func (d *Database) EpisodesForSeries(seriesName string, extraIgnored []int64) ([]EpisodeView, error)

EpisodesForSeries returns every episode of a series, merging the configured ignored seasons with the DB ones.

func (*Database) FailedImportsDaily

func (d *Database) FailedImportsDaily(days int) ([]DailyCount, error)

FailedImportsDaily counts failed library imports per day over the last `days` days, newest first. An import failure is an ERROR acquisition event with the completion-handling failure message (the current wording or the earlier «completion handling failed», still in older history) or the integrity-validation refusal (both logged with the torrent hash at the import choke point).

func (*Database) ForgetMissingEpisode

func (d *Database) ForgetMissingEpisode(series string, season, episode int64) (bool, error)

ForgetMissingEpisode clears the archive row of an episode whose file is confirmed gone, so the search treats it as missing. It refuses when the file is back or the folder cannot be read.

func (*Database) ForgetRemovedTorrent

func (d *Database) ForgetRemovedTorrent(hash string) error

ForgetRemovedTorrent cleans up the database when a torrent is removed by the user (or is abandoned).

func (*Database) GapSearchedTimes

func (d *Database) GapSearchedTimes() (map[gapTarget]time.Time, error)

GapSearchedTimes returns when every gap in the search log was last searched online. One query for the whole set: the deep pass asks about every open gap, and a point query per gap would grow with the library.

func (*Database) HasData

func (d *Database) HasData() (bool, error)

HasData reports whether the database holds any series, movie or episode.

func (*Database) Housekeeping

func (d *Database) Housekeeping(params HousekeepingParams) (HousekeepingReport, error)

Housekeeping trims the bounded tables and compacts the database.

func (*Database) Info

func (d *Database) Info() (map[string]any, error)

Info returns the database statistics for the UI/API.

func (*Database) IsBlocklisted

func (d *Database) IsBlocklisted(hash string) (bool, error)

IsBlocklisted reports whether a hash is in the blocklist.

func (*Database) LastCycleAt

func (d *Database) LastCycleAt() (time.Time, bool)

LastCycleAt returns the start time of the most recent persisted cycle, so a restart can resume the schedule instead of running a full scrape immediately.

func (*Database) LaterArchivedMaxResolutionRank

func (d *Database) LaterArchivedMaxResolutionRank(seriesName string, season, episode int64) (*int, error)

LaterArchivedMaxResolutionRank returns the highest resolution rank among archived episodes after the given one.

func (*Database) LoadMediaIntegrityState

func (d *Database) LoadMediaIntegrityState() MediaIntegrityState

LoadMediaIntegrityState reads the resumable scan state.

func (*Database) LoadMetadataWaits

func (d *Database) LoadMetadataWaits() (map[string]time.Time, error)

LoadMetadataWaits returns the torrents still waiting for their file list, keyed by lower-case hash.

func (*Database) LoadStallWatches

func (d *Database) LoadStallWatches() (map[string]StallWatch, error)

LoadStallWatches restores torrents deliberately parked by the stalled download monitor. Normal user-paused torrents are not represented here.

func (*Database) LoadTorrentMoves

func (d *Database) LoadTorrentMoves() (map[string]TorrentMoveState, error)

LoadTorrentMoves restores the storage-move state saved by SaveTorrentMove. The in-flight flag and the next attempt time are not stored: after a restart no move is running, and the caller decides when to check them again.

func (*Database) MarkEd2kAbsorbed

func (d *Database) MarkEd2kAbsorbed(hash string) error

MarkEd2kAbsorbed closes an eD2k download whose file another download of the same episode took over (the torrent finished first, or took the eD2k file to complete): it leaves the pending list without touching the episode's placeholders, which the torrent still owns.

func (*Database) MarkGapSearched

func (d *Database) MarkGapSearched(seriesName string, season, episode int64) error

MarkGapSearched records the last search time of a gap.

func (*Database) MarkMediaIntegrityReplacement

func (d *Database) MarkMediaIntegrityReplacement(problem MediaIntegrityProblem, oldTitle string) error

MarkMediaIntegrityReplacement records that a damaged item was sent back to the downloads. The completion handler reads it to log which release replaced the damaged copy.

func (*Database) MarkPackCompleted

func (d *Database) MarkPackCompleted(release *models.Release, episodes []PackEpisode, path string, sizeBytes int64) error

MarkPackCompleted marks a season pack as completed for each archived episode.

func (*Database) MarkReleaseCompleted

func (d *Database) MarkReleaseCompleted(release *models.Release, path string, sizeBytes int64) error

func (*Database) MarkSourceAutoDisabled

func (d *Database) MarkSourceAutoDisabled(kind, provider, reason string, at time.Time) error

MarkSourceAutoDisabled records why a source was disabled automatically. The daily history stays: the panel still shows what the feed did before.

func (*Database) MarkTorrentCompleted

func (d *Database) MarkTorrentCompleted(hash, path string, sizeBytes int64) error

MarkTorrentCompleted marks a torrent and its files as completed.

func (*Database) MarkTorrentCompletedUnarchived

func (d *Database) MarkTorrentCompletedUnarchived(hash, name string) (bool, error)

MarkTorrentCompletedUnarchived records the first completion of a torrent that has no registered release metadata (manually added or foreign). It is completed but not archived, so `processed_path` is left untouched and the downloaded files are never treated as a disposable archived copy. The bool is false for duplicate completion events, allowing callers to notify once.

func (*Database) MarkTorrentError

func (d *Database) MarkTorrentError(hash, failureError string) error

MarkTorrentError marks a torrent as failed and clears its placeholders.

func (*Database) MarkTorrentRemoved

func (d *Database) MarkTorrentRemoved(hash string) error

MarkTorrentRemoved marks a non-completed torrent as `removed` and clears its not-yet-downloaded placeholders.

func (*Database) MarkTorrentRemovedAt

func (d *Database) MarkTorrentRemovedAt(hash string) error

MarkTorrentRemovedAt records that a torrent has left the session (entering the download history).

func (*Database) MediaInfoBackfillTargets

func (d *Database) MediaInfoBackfillTargets(limit int) ([]MediaInfoBackfillTarget, error)

MediaInfoBackfillTargets returns archived entries with a known path, an existing regular file, and no stored probe yet. Files that only exist as stale database references are deliberately ignored: ffprobe/MediaInfo must never be invoked for paths that are not on disk.

func (*Database) MediaIntegrityProblems

func (d *Database) MediaIntegrityProblems() ([]MediaIntegrityProblem, error)

MediaIntegrityProblems lists the damaged or unreadable files, newest first.

func (*Database) MediaIntegrityTargets

func (d *Database) MediaIntegrityTargets(after string, limit int, force bool) ([]MediaIntegrityTarget, string, error)

MediaIntegrityTargets returns up to limit files that need a check after the given cursor, and the cursor to use for the next call. Files already checked and unchanged are skipped unless force is set. "done" means the library has been walked completely.

func (*Database) MovieArchivedSize

func (d *Database) MovieArchivedSize(name string, year *int64) (*int64, error)

MovieArchivedSize returns the archived file size for a movie, used by the adaptive size floor.

func (*Database) MovieCurrentRelease

func (d *Database) MovieCurrentRelease(id int64) (models.Release, bool, error)

MovieCurrentRelease reconstructs the release stored on a movie row.

func (*Database) MovieIdentityForRelease

func (d *Database) MovieIdentityForRelease(title string, year *int64) (string, int64, bool, error)

MovieIdentityForRelease finds the configured movie name of a release, so a replacement recorded by movie name can be matched at completion.

func (*Database) MovieMediaInfo

func (d *Database) MovieMediaInfo(name string, year *int64) (map[string]any, error)

MovieMediaInfo returns the stored probe of a movie, if any.

func (*Database) MovieProcessedPath

func (d *Database) MovieProcessedPath(id int64) (string, error)

MovieProcessedPath returns the archived path of a movie, when known.

func (*Database) MoviesSeenGrouped

func (d *Database) MoviesSeenGrouped(offset, limit int, query string) ([]FeedSeenGroup, int64, error)

MoviesSeenGrouped returns the grouped "seen in feed" movies and total count.

func (*Database) NoRenameTorrents

func (d *Database) NoRenameTorrents() ([][2]string, error)

NoRenameTorrents returns torrents explicitly excluded from renaming (hash, display name).

func (*Database) Optimize

func (d *Database) Optimize(action string) error

Optimize runs SQLite maintenance (`vacuum` or `analyze`).

func (*Database) PackFileCheck

func (d *Database) PackFileCheck(hash string) (*packFileCheck, error)

PackFileCheck returns the deferred announcement of a pack, nil when the pack was announced when it was added.

func (*Database) PendingCount

func (d *Database) PendingCount() (int64, error)

PendingCount returns the number of pending downloads.

func (*Database) PendingEd2kHashes

func (d *Database) PendingEd2kHashes() ([]string, error)

PendingEd2kHashes returns the eD2k files Gextto handed to aMule and has not seen complete yet. Completed files leave aMule's download queue at once, so these are the hashes whose completion is looked up in aMule's shared files.

func (*Database) PendingQueue

func (d *Database) PendingQueue(now time.Time) ([]PendingQueueItem, error)

PendingQueue lists the series and movie releases currently held by the delay profile, oldest first, with the wait time since they were first seen.

func (*Database) ProblemsAckID

func (d *Database) ProblemsAckID() int64

ProblemsAckID returns the highest acquisition-event id the operator has marked as read in the Dashboard "Da controllare" panel (0 when never).

func (*Database) ProviderBlocked

func (d *Database) ProviderBlocked(kind, provider string) (bool, error)

ProviderBlocked reports whether a source is inside its disabled window.

func (*Database) ProviderFailure

func (d *Database) ProviderFailure(kind, provider, failureError string) error

ProviderFailure records a failed source attempt and moves it down the escalation schedule.

func (*Database) ProviderFailureUntil

func (d *Database) ProviderFailureUntil(kind, provider, failureError string, notBefore time.Time) error

ProviderFailureUntil records a failed source attempt but keeps the source disabled at least until notBefore. It is used when the source itself says when to come back (a `Retry-After` on HTTP 429), so Gextto does not hammer an indexer that has asked for a pause.

func (*Database) ProviderStatuses

func (d *Database) ProviderStatuses() ([]models.ProviderStatus, error)

ProviderStatuses is the full provider status list for the UI/API.

func (*Database) ProviderSuccess

func (d *Database) ProviderSuccess(kind, provider string) error

ProviderSuccess steps the escalation level down and lifts the disabled window. The row is removed entirely once fully recovered.

func (*Database) PruneAcquisitionEvents

func (d *Database) PruneAcquisitionEvents(now time.Time) (int64, error)

PruneAcquisitionEvents drops events older than the retention and trims each acquisition to its most recent acquisitionMaxPerHash rows.

func (*Database) PruneKeyword

func (d *Database) PruneKeyword(keyword string) (int, error)

PruneKeyword removes the rows matching one keyword.

func (*Database) PruneKeywords

func (d *Database) PruneKeywords(keywords []string) (int, error)

PruneKeywords removes the rows matching every keyword.

func (*Database) PruneMediaIntegrityChecks

func (d *Database) PruneMediaIntegrityChecks() error

PruneMediaIntegrityChecks removes the outcomes of episodes and movies that left the library, so the panel and the skip list only describe current items.

func (*Database) PrunePackFileChecks

func (d *Database) PrunePackFileChecks(live map[string]struct{}) error

PrunePackFileChecks drops the rows of packs no longer in the session (the operator removed them, or their metadata never came), once they are a day old: a row is never needed after its torrent is gone.

func (*Database) PrunePreview

func (d *Database) PrunePreview(retainCycles, errorAgeDays, seenDays int64) (PrunePreview, error)

PrunePreview counts what `cleanup` + `prune_seen_older_than` would remove, without deleting anything.

func (*Database) PruneSeenByIDs

func (d *Database) PruneSeenByIDs(movieIDs, seriesIDs []int64) (int, int, error)

PruneSeenByIDs deletes specific "seen in feed" rows by id, at most 1000 per table. The deletes share one transaction: with synchronous=FULL every autocommit statement is an fsync, and a selection can be a thousand rows.

func (*Database) PruneSeenOlderThan

func (d *Database) PruneSeenOlderThan(days int64) (int, error)

PruneSeenOlderThan deletes the "seen" releases older than `days` days.

func (*Database) PurgeMovie

func (d *Database) PurgeMovie(name string) (int, error)

PurgeMovie removes every trace of a movie that is no longer monitored.

func (*Database) PurgeSeries

func (d *Database) PurgeSeries(name string) (int, error)

PurgeSeries removes every trace of a series that is no longer monitored.

func (d *Database) QuarantineTorrentLink(rawURL, reason string, now time.Time, wait time.Duration) error

QuarantineTorrentLink puts a link out of use immediately, for a reason that is not a transient HTTP failure: for example an "in progress" pack whose .torrent is behind its title. The link is not resolved again until the quarantine ends, so the same stale pack does not cost a request every cycle.

func (d *Database) QuarantinedTorrentLinks(now time.Time) (map[string]string, error)

QuarantinedTorrentLinks returns the URLs still under quarantine as a map from URL to the last error, so the acquisition loop checks one set per cycle instead of querying the database for every release.

func (*Database) QueuePending

func (d *Database) QueuePending(release *models.Release, timeframeHours int64) error

QueuePending holds a series release for `timeframe_hours` hours.

func (*Database) QueuePendingMovieScored

func (d *Database) QueuePendingMovieScored(release *models.Release, delayMinutes, qualityScore int64) error

QueuePendingMovieScored holds a movie release for `delay_minutes`.

func (*Database) QueuePendingScored

func (d *Database) QueuePendingScored(release *models.Release, delayMinutes, qualityScore int64) error

QueuePendingScored holds a series release for `delay_minutes`. The best scoring candidate seen during the window is the one that will be grabbed.

func (*Database) QuickCheck

func (d *Database) QuickCheck() ([]string, error)

QuickCheck runs `PRAGMA quick_check` (see `QuickCheck`).

func (*Database) ReadyPending

func (d *Database) ReadyPending() ([]ReadyPending, error)

ReadyPending returns series releases whose delay window has elapsed.

func (*Database) ReadyPendingMovies

func (d *Database) ReadyPendingMovies() ([]ReadyPendingMovie, error)

ReadyPendingMovies returns movies whose delay window has elapsed.

func (*Database) RecentCycleStats

func (d *Database) RecentCycleStats(limit int64) ([]models.CycleHistoryEntry, error)

RecentCycleStats returns the most recent cycle history as typed rows, for the Salute page trends. Entries whose payload cannot be read are skipped.

func (*Database) RecentCycles

func (d *Database) RecentCycles(limit int64) ([]any, error)

RecentCycles returns the most recent cycle history entries with an `at` field merged into the payload.

func (*Database) RecentDownloads

func (d *Database) RecentDownloads(limit int) ([]RecentDownload, error)

RecentDownloads merges series and movie downloads.

func (*Database) ReconcileMissingTorrents

func (d *Database) ReconcileMissingTorrents(liveHashes map[string]struct{}) (int, error)

ReconcileMissingTorrents marks orphan active torrents as `error` and removes their not-yet-downloaded placeholders.

func (*Database) ReconcilePackRelease

func (d *Database) ReconcilePackRelease(hash string, release *models.Release, cfg *Config) error

ReconcilePackRelease persists the identity found in the actual torrent name when an indexer advertised a different season.

func (*Database) RecordAcquisitionEvent

func (d *Database) RecordAcquisitionEvent(event logging.Event) error

RecordAcquisitionEvent stores one event. An event equal to the last one of the same acquisition (same level, message and fields) only bumps its repeat count and time: retries logged every few minutes stay one row.

func (*Database) RecordManualMovie

func (d *Database) RecordManualMovie(name string, year int64, title string, size, score int64) error

RecordManualMovie marks a manually imported movie as archived: the movies table holds the library state the acquisition cycle reads, so a manual import must create or refresh that row or the movie would still look missing.

func (*Database) RecordSeenBatch

func (d *Database) RecordSeenBatch(releases []models.Release, cfg *Config) error

RecordSeenBatch records every release of a cycle in the "seen in feed" tables.

func (*Database) RecordSourceAccepted

func (d *Database) RecordSourceAccepted(kind, provider string) error

RecordSourceAccepted counts a release the source returned and Gextto took.

func (*Database) RecordSourceAttempt

func (d *Database) RecordSourceAttempt(attempt SourceAttempt) error

RecordSourceAttempt appends one request outcome to the daily history and refreshes the source's first/last success. A success also clears a previous automatic-disable marker: the operator has re-enabled the feed and it works.

func (*Database) RecordTorrentLinkFailure

func (d *Database) RecordTorrentLinkFailure(rawURL, reason string, now time.Time) (int, error)

RecordTorrentLinkFailure counts one strike for the URL and quarantines it once the limit is reached (or refreshes the error while a quarantine is still active). Failures closer than torrentLinkStrikeWindow to the previous one only update the message: one cycle proposing the same dead release twice is not two strikes. It returns the strike count.

func (*Database) RefreshEpisodeFileStats

func (d *Database) RefreshEpisodeFileStats(cfg *Config, seriesName string, season, episode int64, path string) error

RefreshEpisodeFileStats re-aligns size and quality score of an episode to the file it currently points to, without touching its title.

func (*Database) RegisterTorrent

func (d *Database) RegisterTorrent(release *models.Release) error

RegisterTorrent implements `Database::register_torrent`.

func (*Database) RegisterTorrentScored

func (d *Database) RegisterTorrentScored(release *models.Release, qualityScore int64) error

RegisterTorrentScored implements `Database::register_torrent_scored`.

The same infohash can be downloaded again — the archived copy was deleted, or the release is proposed once more after the last attempt failed — so a row that still says "completed" is cleared first: see beginNewDownloadAttempt.

func (*Database) RemoveBlocklist

func (d *Database) RemoveBlocklist(hash string) (bool, error)

RemoveBlocklist deletes a hash from the blocklist.

func (*Database) RemovePending

func (d *Database) RemovePending(seriesName string, season, episode int64) error

RemovePending marks a pending series release as downloaded.

func (*Database) RemovePendingMovie

func (d *Database) RemovePendingMovie(name string, year *int64) error

RemovePendingMovie marks a pending movie release as downloaded.

func (*Database) RenameMovieIdentity

func (d *Database) RenameMovieIdentity(oldName, oldYear, newName, newYear string) (int, error)

RenameMovieIdentity updates the name/year identity of a movie without touching hash, quality, dates or download state.

func (*Database) RenameSeries

func (d *Database) RenameSeries(oldName, newName string) error

RenameSeries moves every stored row of a monitored series from oldName to newName in one transaction. Episodes and pending downloads point at the series row's id, so they follow the renamed row automatically; the tables keyed by series name (metadata, history, torrents, blocklist, integrity checks) are updated in place. The archive files are not touched.

func (*Database) Rescore

func (d *Database) Rescore(cfg *Config) (int, error)

func (*Database) ResetEpisode

func (d *Database) ResetEpisode(seriesName string, season, episode int64, removeHistory bool) error

func (*Database) ResetMovieByName

func (d *Database) ResetMovieByName(name string) (int, error)

ResetMovieByName clears the download state of a movie.

func (*Database) ResetProviderStatus

func (d *Database) ResetProviderStatus(provider string) error

ResetProviderStatus clears a provider's backoff and error but keeps its row.

func (*Database) RestoreUpgrade

func (d *Database) RestoreUpgrade(hash string) (bool, error)

func (*Database) RollbackRelease

func (d *Database) RollbackRelease(release *models.Release) error

RollbackRelease removes the placeholder rows of a non-downloaded release.

func (*Database) RowCount

func (d *Database) RowCount() int64

RowCount returns the number of rows stored in the database's user tables.

func (*Database) SalvagePackEpisodes

func (d *Database) SalvagePackEpisodes(hash string, release *models.Release, episodes []PackEpisode) (bool, error)

SalvagePackEpisodes records the episodes imported from an abandoned pack. Upgrade backups are restored only for the episodes that were NOT salvaged (their previous library copy is still the valid one); the salvaged ones keep the new file. The backup row is consumed, so the RestoreUpgrade of the give-up that follows has nothing left to undo, and MarkTorrentError then clears only the placeholders of the episodes still missing. It reports whether any previous copy was restored.

func (*Database) SaveCycle

func (d *Database) SaveCycle(value *models.CycleStats) error

SaveCycle stores one cycle history entry.

func (*Database) SaveEpisodeAirDates

func (d *Database) SaveEpisodeAirDates(seriesName string, episodes []EpisodeAirDate) error

SaveEpisodeAirDates caches the TMDB air dates of a series.

func (*Database) SaveMediaIntegrityCheck

func (d *Database) SaveMediaIntegrityCheck(check MediaIntegrityProblem) error

SaveMediaIntegrityCheck stores or updates the outcome of one file, including the identity used to skip it while it does not change.

func (*Database) SaveMediaIntegrityState

func (d *Database) SaveMediaIntegrityState(state MediaIntegrityState) error

SaveMediaIntegrityState writes the resumable scan state.

func (*Database) SaveMetadataWait

func (d *Database) SaveMetadataWait(hash string, since time.Time) error

SaveMetadataWait records since when a magnet has been waiting for its file list, so the give-up clock (monitor_metadata) survives a restart.

func (*Database) SaveSeriesEndRecord

func (d *Database) SaveSeriesEndRecord(seriesName string, record SeriesEndRecord) error

SaveSeriesEndRecord stores every end-of-series signal of a series: the provider status and dates, and TVmaze's status ("" when not asked).

func (*Database) SaveSeriesMetadata

func (d *Database) SaveSeriesMetadata(seriesName string, counts [][2]int64) error

SaveSeriesMetadata upserts the TMDB season episode counts of a series.

func (*Database) SaveSeriesStatus

func (d *Database) SaveSeriesStatus(seriesName, status, lastAirDate string) error

SaveSeriesStatus stores the TMDB status of a series.

func (*Database) SaveStallWatch

func (d *Database) SaveStallWatch(hash string, entry StallWatch) error

SaveStallWatch atomically records a stalled torrent's retry state, or the progress clock of a download idle long enough to be persisted (empty stalled_since).

func (*Database) SaveTorrentMove

func (d *Database) SaveTorrentMove(hash string, state TorrentMoveState) error

SaveTorrentMove records the storage-move state of a torrent, or deletes its row when there is nothing left to remember.

func (*Database) SearchKeywords

func (d *Database) SearchKeywords(keywords []string, limit int) ([]any, error)

SearchKeywords previews the rows matching the given keywords without removing them.

func (*Database) SeedIdleStops

func (d *Database) SeedIdleStops() ([]string, error)

SeedIdleStops returns the torrents stopped for inactivity.

func (*Database) SeenByGroup

func (d *Database) SeenByGroup(kind, groupKey string, limit int) ([]FeedSeenEntry, error)

SeenByGroup returns the releases of one "seen" group, best quality first.

func (*Database) SeenCounts

func (d *Database) SeenCounts() (int64, int64, error)

SeenCounts returns the number of distinct "seen in feed" groups (movies, series).

func (*Database) SeriesArchivedMinSize

func (d *Database) SeriesArchivedMinSize(seriesName string) (*int64, error)

SeriesArchivedMinSize returns the smallest archived episode size for a series, used by the adaptive size floor.

func (*Database) SeriesEndRecords

func (d *Database) SeriesEndRecords() (map[string]SeriesEndRecord, error)

SeriesEndRecords returns the stored end-of-series signals of every series.

func (*Database) SeriesFeedForEpisode

func (d *Database) SeriesFeedForEpisode(season, episode int64, limit int) ([][3]string, error)

SeriesFeedForEpisode returns the releases of an episode already seen during RSS/HTML scans.

func (*Database) SeriesMetadataStale

func (d *Database) SeriesMetadataStale(seriesName string, maxAgeHours int64) (bool, error)

SeriesMetadataStale reports whether the series metadata is older than `max_age_hours`.

func (*Database) SeriesQualityIndex

func (d *Database) SeriesQualityIndex(seriesName string, season int64, cfg *Config) *models.ArchiveQualityIndex

SeriesQualityIndex returns the best known quality score per episode of one season, read from the episodes table. It is the cheap counterpart of IndexArchive (which walks the library folder) for the in-download pack inspection, where a NAS scan at every tick would block the event loop.

func (*Database) SeriesSeasonCounts

func (d *Database) SeriesSeasonCounts(seriesName string) ([][2]int64, error)

SeriesSeasonCounts returns the recorded TMDB episode counts of a series.

func (*Database) SeriesSeasonCountsBulk

func (d *Database) SeriesSeasonCountsBulk() (map[string][][2]int64, error)

SeriesSeasonCountsBulk returns the recorded episode counts of every series in one query.

func (*Database) SeriesSeenGrouped

func (d *Database) SeriesSeenGrouped(offset, limit int, query string) ([]FeedSeenGroup, int64, error)

SeriesSeenGrouped returns the grouped "seen in feed" series and total count.

func (*Database) SeriesStatuses

func (d *Database) SeriesStatuses() (map[string]string, error)

SeriesStatuses returns every stored series status.

func (*Database) SeriesSummaries

func (d *Database) SeriesSummaries() ([]SeriesSummary, error)

SeriesSummaries returns the per-series aggregate.

func (*Database) SetEpisodeArchivePath

func (d *Database) SetEpisodeArchivePath(cfg *Config, seriesName string, season, episode int64, path string) error

SetEpisodeArchivePath updates the stored archive path of an episode, together with the real size and (monotonic) quality score of the file.

func (*Database) SetEpisodeIgnored

func (d *Database) SetEpisodeIgnored(seriesName string, season, episode int64, ignored bool, reason string) error

SetEpisodeIgnored marks (or unmarks) an episode as ignored.

func (*Database) SetEpisodeMediaInfo

func (d *Database) SetEpisodeMediaInfo(series string, season, episode int64, jsonValue string) (int, error)

SetEpisodeMediaInfo updates one archived episode's media info directly (backfill path).

func (*Database) SetMediaInfo

func (d *Database) SetMediaInfo(release *models.Release, info *MediaInfo) error

SetMediaInfo persists the `ffprobe` result for a release's archived file.

func (*Database) SetMovieMediaInfo

func (d *Database) SetMovieMediaInfo(name string, year *int64, jsonValue string) (int, error)

SetMovieMediaInfo updates one archived movie's media info directly (backfill path).

func (*Database) SetPackFileCheck

func (d *Database) SetPackFileCheck(hash, logMessage string, payload map[string]any) error

SetPackFileCheck records the announcement of a pack waiting for its files.

func (*Database) SetSeedIdleStop

func (d *Database) SetSeedIdleStop(hash string, stopped bool) error

SetSeedIdleStop records or clears the inactivity stop of a torrent.

func (*Database) SetTorrentNoRename

func (d *Database) SetTorrentNoRename(hash string, value bool) error

SetTorrentNoRename sets the "do not rename" flag for a torrent (creating the row when missing).

func (*Database) SetTorrentProcessedPath

func (d *Database) SetTorrentProcessedPath(hash, path string) error

SetTorrentProcessedPath records where a torrent's file is after a rename.

func (*Database) SetTorrentReason

func (d *Database) SetTorrentReason(hash, reason string) error

SetTorrentReason records why a release was accepted and put in download.

func (*Database) SetTorrentSkippedEpisodes

func (d *Database) SetTorrentSkippedEpisodes(hash string, episodes []int64) error

SetTorrentSkippedEpisodes records in the torrent metadata which episodes the in-download inspection left out (file priority 0), so the pack identity check at completion accepts the files that were actually downloaded.

func (*Database) SetTorrentTag

func (d *Database) SetTorrentTag(hash, tag string) error

SetTorrentTag sets the tag of a torrent, creating the row when it is a manually added torrent.

func (*Database) SourceHealth

func (d *Database) SourceHealth(kind, provider string) (models.SourceStat, error)

SourceHealth returns the first/last attempt, last success and disable marker of one source.

func (*Database) SourceStats

func (d *Database) SourceStats(kind string) ([]models.SourceStat, error)

SourceStats returns the 1, 7 and 30 day history of every source of one kind.

func (*Database) StalledAlternatives

func (d *Database) StalledAlternatives(minStall time.Time) (map[models.LiveEpisodeKey]int64, error)

StalledAlternatives returns, per episode covered by a download that has not received a byte since minStall (and is parked as stalled), the best score of the stuck release. It powers the temporary quality tolerance of the search: while an episode is stuck, an alternative within a few points may be started without removing the stuck torrent. Episodes whose season already holds a healthy active download are omitted, so a stuck episode never piles a second alternative on top of a download that is still progressing.

func (*Database) StoredTorrents

func (d *Database) StoredTorrents(limit int) ([]StoredTorrent, error)

StoredTorrents returns the torrents still downloading.

func (*Database) StoredTorrentsAll

func (d *Database) StoredTorrentsAll(limit int) ([]StoredTorrent, error)

StoredTorrentsAll returns every named torrent row.

func (*Database) SyncArchiveFile

func (d *Database) SyncArchiveFile(seriesName string, season, episode int64, title, path string, sizeBytes int64) error

SyncArchiveFile records an archived episode file, scoring it from its title.

func (*Database) SyncArchiveFileScored

func (d *Database) SyncArchiveFileScored(seriesName string, season, episode int64, title, path string, sizeBytes, qualityScore int64) error

SyncArchiveFileScored records an archived episode file with an explicit score.

func (*Database) SyncArchiveFilesScored

func (d *Database) SyncArchiveFilesScored(seriesName string, records []ArchiveFileRecord) (int, error)

SyncArchiveFilesScored records the files of one series in a single transaction. A library scan used to commit once per file, so every file cost an fsync: on this machine 1.7 ms per file against 0.14 ms on a RAM disk.

func (*Database) SyncScoresWithSettings

func (d *Database) SyncScoresWithSettings(cfg *Config) (int, error)

Rescore recomputes every stored quality score with the configured weights. SyncScoresWithSettings recomputes the stored quality scores with the current scoring weights, but only when those weights changed since the last run. A weight change (for example a higher Dolby Vision bonus) otherwise leaves every archived release with a stale score, so the next cycle sees an artificial improvement and re-downloads content that already has the right quality.

func (*Database) TakeMediaIntegrityReplacement

func (d *Database) TakeMediaIntegrityReplacement(kind, series string, season, episode int64, movieName string, movieYear int64) (string, string, bool, error)

TakeMediaIntegrityReplacement returns and clears the pending replacement of one item, if any.

func (*Database) TorrentAddIntentsBefore

func (d *Database) TorrentAddIntentsBefore(before time.Time) ([]torrentAddIntent, error)

TorrentAddIntentsBefore lists the intents recorded before the given instant.

func (*Database) TorrentAux

func (d *Database) TorrentAux(hash string) ([3]string, error)

TorrentAux returns `(processed_path, source, reason)` for a torrent.

func (*Database) TorrentAuxBulk

func (d *Database) TorrentAuxBulk(hashes []string) (map[string][3]string, error)

TorrentAuxBulk is `TorrentAux` for many hashes in one query.

func (*Database) TorrentMeta

func (d *Database) TorrentMeta(hash string) (*models.TorrentMeta, error)

TorrentMeta returns the release associated with a torrent hash, restoring it from episodes/movies when no metadata was stored.

func (*Database) TorrentNetwork

func (d *Database) TorrentNetwork(hash string) string

TorrentNetwork returns the stored network of a file ("torrent" or "ed2k"); an unknown hash is a torrent.

func (*Database) TorrentNoRename

func (d *Database) TorrentNoRename(hash string) (bool, error)

TorrentNoRename reports the stored flag for a torrent.

func (*Database) TorrentOrigins

func (d *Database) TorrentOrigins() (map[string]seedOrigin, error)

TorrentOrigins returns the source and category of every recorded torrent, keyed by lowercase hash.

func (*Database) TorrentProcessed

func (d *Database) TorrentProcessed(hash string) (*string, error)

TorrentProcessed returns the path where a completed torrent was archived.

func (*Database) TorrentReason

func (d *Database) TorrentReason(hash string) (*string, error)

TorrentReason returns the recorded reason for a torrent, if present and not empty.

func (*Database) TorrentStatus

func (d *Database) TorrentStatus(hash string) (*string, error)

func (*Database) TorrentStatusProcessed

func (d *Database) TorrentStatusProcessed(hash string) (*string, *string, error)

TorrentStatus returns the stored status of a torrent. TorrentStatusProcessed returns TorrentStatus and TorrentProcessed in one query: both nil when the torrent has no row.

func (*Database) TorrentTags

func (d *Database) TorrentTags() ([][2]string, error)

TorrentTags returns the `(hash, tag)` pairs of tagged torrents.

func (*Database) TorrentTimes

func (d *Database) TorrentTimes(hash string) (*TorrentTimes, error)

TorrentTimes returns the `created_at` / `completed_at` of a torrent.

func (*Database) UpdateArchivedSizeAfterCleanup

func (d *Database) UpdateArchivedSizeAfterCleanup(hash, path string, sizeBytes int64) error

MarkReleaseCompleted marks a torrent as completed, updating every episode covered by the release. UpdateArchivedSizeAfterCleanup keeps the archived row's size aligned with a file whose foreign audio tracks were removed after the import. Episodes are matched by archive path (one row per file, packs included); the movie by its magnet hash, since the movies table does not store the file path.

func (*Database) UpgradeBackupsFor

func (d *Database) UpgradeBackupsFor(hash string) ([]upgradeBackup, error)

RestoreUpgrade restores a previous release from its upgrade backup. UpgradeBackupsFor returns the archived copies an upgrade with this hash is replacing (none for a new episode or movie).

func (*Database) UpgradeReplacedInfo

func (d *Database) UpgradeReplacedInfo(hash string) (string, bool)

UpgradeReplacedInfo returns the name of the previous release replaced by this upgrade, if an upgrade backup was recorded. It returns false when there is no usable backup entry.

type DbActionInput

type DbActionInput struct {
	Action string `json:"action"`
}

DbActionInput is the input of `db_action`.

type DecisionStep

type DecisionStep struct {
	Rule   string `json:"rule"`
	Result string `json:"result"`
	Detail string `json:"detail"`
}

DecisionStep is one labelled check of the decision trace.

type DecisionTrace

type DecisionTrace struct {
	Decision        string           `json:"decision"`
	Reason          string           `json:"reason"`
	Candidate       string           `json:"candidate"`
	Target          string           `json:"target"`
	Score           int64            `json:"score"`
	ScoreComponents []map[string]any `json:"score_components"`
	Steps           []DecisionStep   `json:"steps"`
	Comparison      map[string]any   `json:"comparison"`
}

DecisionTrace is the structured, side-effect-free explanation of a decision.

func Explain

func Explain(cfg *Config, db *Database, release *models.Release) (*DecisionTrace, error)

Explain produces a detailed, side-effect-free explanation of the automatic decision.

func ExplainWithArchive

func ExplainWithArchive(
	cfg *Config,
	db *Database,
	release *models.Release,
	disk *models.ArchiveQuality,
) (*DecisionTrace, error)

ExplainWithArchive is the same explanation using a previously computed archive index. The web layer uses this variant after moving the filesystem scan to a blocking task.

type DiscoverInput

type DiscoverInput struct {
	Kind   *string `json:"kind"`
	Window *string `json:"window"`
	Mode   *string `json:"mode"`
}

DiscoverInput is the input of `tmdb_discover`.

type DiskInfo

type DiskInfo struct {
	Mount      string `json:"mount"`
	Filesystem string `json:"filesystem"`
	TotalBytes uint64 `json:"total_bytes"`
	FreeBytes  uint64 `json:"free_bytes"`
}

DiskInfo describes a real mounted filesystem.

type DownloadTagInput

type DownloadTagInput struct {
	Tag string `json:"tag"`
}

DownloadTagInput is the input of `add_download_tag`.

type DownloadedMovieCopy

type DownloadedMovieCopy struct {
	ID           int64
	Name         string
	Year         *int64
	Title        string
	QualityScore int64
	DownloadedAt *string
	SizeBytes    int64
	Path         string
}

DownloadedMovieCopy is a movie already in the library, with the archive path left by the torrent that imported it. The monitored-movies list shows the path (or the title, when the move is not recorded) in the tooltip of its "downloaded" check.

type DuplicateCandidate

type DuplicateCandidate struct {
	Series         string `json:"series"`
	Season         int64  `json:"season"`
	Episode        int64  `json:"episode"`
	Path           string `json:"path"`
	ResolutionRank int    `json:"resolution_rank"`
	BestRank       int    `json:"best_rank"`
	// Reason is why the file is inferior: "resolution", "language", "quality"
	// (same resolution, the best copy would be an upgrade) or "identical" (a
	// second copy of the same file under another name).
	Reason string `json:"reason,omitempty"`
}

DuplicateCandidate is a clearly inferior duplicate found in the library.

func FindInferiorDuplicatesInDir

func FindInferiorDuplicatesInDir(series, archivePath string, protected map[string]struct{}, preferredLanguage string, aliases ...string) ([]DuplicateCandidate, error)

FindInferiorDuplicatesInDir looks for strictly lower-resolution duplicates per episode inside a series folder. It is deliberately conservative: files at the same resolution (e.g. different languages) and files with an unrecognised resolution are never reported.

func FindSeriesDuplicatesInDir

func FindSeriesDuplicatesInDir(cfg *Config, series, archivePath string, protected map[string]struct{}) ([]DuplicateCandidate, error)

FindSeriesDuplicatesInDir is FindInferiorDuplicatesInDir for a configured series: files named after one of its aliases count too, and copies at the same resolution are compared by quality, so an older or identical copy kept next to a better one is found as well.

type DuplicatesInput

type DuplicatesInput struct {
	Execute bool `json:"execute"`
}

type Ed2kLimitsInput

type Ed2kLimitsInput struct {
	DownloadKib int64 `json:"download_kib"`
	UploadKib   int64 `json:"upload_kib"`
}

Ed2kLimitsInput is the body of `POST /api/ed2k/limits` (KiB/s, 0 = unlimited).

type Ed2kPriorityInput

type Ed2kPriorityInput struct {
	Priority string `json:"priority"`
}

Ed2kPriorityInput is the body of `POST /api/ed2k/downloads/{hash}/priority`.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine fans a scrape or a single title search out to every configured source. `db` is optional: `nil` in read-only tools that never touch the archive database.

func NewEngine

func NewEngine() *Engine

NewEngine builds the default engine, mirroring `Engine::new`.

func (*Engine) FetchTorrent

func (e *Engine) FetchTorrent(ctx context.Context, rawURL string) ([]byte, string, error)

FetchTorrent downloads a `.torrent` file or resolves a magnet redirect from a feed that does not expose a magnet directly. Returns either the torrent file bytes or the target magnet link. The full URL is never logged: it can carry a passkey.

func (*Engine) ScrapeAll

func (e *Engine) ScrapeAll(ctx context.Context, cfg *Config) ([]models.Release, []models.CycleSourceStat, error)

ScrapeAll scans every configured feed and then searches every enabled series and movie on the Torznab indexers and web engines, returning the unique releases that survive the global filters.

func (*Engine) ScrapeAllDomain

func (e *Engine) ScrapeAllDomain(ctx context.Context, cfg *Config, domain *string) ([]models.Release, []models.CycleSourceStat, error)

ScrapeAllDomain is ScrapeAll with the online title search restricted to one domain (`series` or `movies`); a nil domain means "full". The feeds are still read whole because they fill the shared local archive, but a movies-only cycle must not spend minutes querying the indexers for every enabled series only to discard those releases afterwards: the domain filter runs before the search, not after it.

func (*Engine) SearchMovie

func (e *Engine) SearchMovie(ctx context.Context, cfg *Config, movie *MovieConfig, manual, includeRejected bool) []models.Release

SearchMovie searches one configured movie using its movie mode and TMDB id where available, under every title it is known by (the monitored name, the original title and the first alternative titles TMDB supplied). `includeRejected` is reserved for the manual movie view, which applies its own per-movie filters before displaying results.

func (*Engine) SearchMovieED2K

func (e *Engine) SearchMovieED2K(ctx context.Context, cfg *Config, movie *MovieConfig) []models.Release

SearchMovieED2K looks a monitored movie up on eD2k: one search per title it is released under ("Title 2010"), on Kad and the servers, keeping the results that resolve to the same movie and pass the automatic acceptance. It is what helps a slow torrent of that movie.

func (*Engine) SearchQuery

func (e *Engine) SearchQuery(ctx context.Context, cfg *Config, query string) []models.Release

SearchQuery is the gap-fill title search: the whole fan-out is bounded by the automatic timeout.

func (*Engine) SearchQueryIDs

func (e *Engine) SearchQueryIDs(ctx context.Context, cfg *Config, query string, externalIDs [][2]string) []models.Release

SearchQueryIDs searches with explicit external ids (`tvdbid`/`tmdbid`).

func (*Engine) SearchQueryManual

func (e *Engine) SearchQueryManual(ctx context.Context, cfg *Config, query string) []models.Release

SearchQueryManual is the interactive search: Torznab indexers stay available for their whole search, while each web engine gets a short budget of its own once it starts, so a source waiting for a slot is not cut off unseen.

func (*Engine) SearchQueryManualAll

func (e *Engine) SearchQueryManualAll(ctx context.Context, cfg *Config, query string) []models.Release

SearchQueryManualAll keeps globally rejected releases visible so the user can inspect or manually queue them. Automatic acquisition still uses the filtered methods above.

func (*Engine) SearchSeasonED2K

func (e *Engine) SearchSeasonED2K(ctx context.Context, cfg *Config, series *SeriesConfig, season int64) []models.Release

SearchSeasonED2K looks up a whole season with one query ("Name Sxx"). The manual series missing search uses it so aMule runs one search per season instead of one per episode, which keeps the wait bounded.

func (*Engine) SearchSeriesED2K

func (e *Engine) SearchSeriesED2K(ctx context.Context, cfg *Config, series *SeriesConfig, season, episode int64, manual bool) []models.Release

SearchSeriesED2K is the gap-filling entry point. It builds the same `Name SxxExx` query as SearchSeriesEpisode, then keeps only the results that match the episode and pass the automatic acceptance (a video file, the source floor). The profile is applied later, by the caller: a copy it refuses may still be taken as a last resort. The caller (the deep gap pass) has already established that the torrent plane found nothing.

func (*Engine) SearchSeriesEpisode

func (e *Engine) SearchSeriesEpisode(ctx context.Context, cfg *Config, series *SeriesConfig, season, episode int64, manual bool) []models.Release

SearchSeriesEpisode searches one known episode using its structured TV identity. It is used by gap filling and episode-level manual searches: a broad title search can miss older episodes even when the indexer supports an exact season/episode request. The query runs under the monitored name and under the aliases (see searchSeriesTitles).

func (*Engine) SearchSeriesSeason

func (e *Engine) SearchSeriesSeason(ctx context.Context, cfg *Config, series *SeriesConfig, season int64, manual bool) []models.Release

SearchSeriesSeason is the broader fallback for a known episode gap. It can discover partial and complete season packs that an episode-specific indexer query does not return. Callers must still verify that each result covers the target episode before accepting it.

func (*Engine) WithDB

func (e *Engine) WithDB(db *Database) *Engine

WithDB binds the engine to the archive database so provider backoff survives restarts and is shared with the rest of the daemon.

type EngineFailure

type EngineFailure struct {
	Engine string `json:"engine"`
	Count  int    `json:"count"`
}

EngineFailure is one drained per-cycle web-engine failure aggregate.

func TakeEngineFailures

func TakeEngineFailures() []EngineFailure

TakeEngineFailures drains the accumulated web-engine failures (`engine -> count`), most frequent first.

type EpisodeAirDate

type EpisodeAirDate struct {
	Season  int64
	Episode int64
	AirDate string
}

EpisodeAirDate is one cached air date: `(season, episode, air_date)`.

type EpisodeView

type EpisodeView struct {
	ID           int64   `json:"id"`
	SeriesName   string  `json:"series_name"`
	Season       int64   `json:"season"`
	Episode      int64   `json:"episode"`
	Title        string  `json:"title"`
	AirDate      string  `json:"air_date"`
	RenamedTitle string  `json:"renamed_title"`
	QualityScore int64   `json:"quality_score"`
	DownloadedAt *string `json:"downloaded_at"`
	ArchivePath  *string `json:"archive_path"`
	SizeBytes    int64   `json:"size_bytes"`
	MagnetHash   *string `json:"magnet_hash"`
	MagnetLink   *string `json:"magnet_link"`
	Status       string  `json:"status"`
	Error        string  `json:"error"`
	Ignored      bool    `json:"ignored"`
}

EpisodeView is one episode of the series detail view.

type ErrCapabilityUnavailable

type ErrCapabilityUnavailable struct {
	Backend    string
	Capability string
}

ErrCapabilityUnavailable is returned by a backend for an operation it does not support. Callers must surface it instead of simulating success.

func (ErrCapabilityUnavailable) Error

func (e ErrCapabilityUnavailable) Error() string

type EventHook

type EventHook struct {
	Name string `json:"name"`
	// Enabled defaults to true when the key is absent.
	Enabled bool `json:"enabled"`
	// Events are the event names to react to; empty means every event.
	Events []string `json:"events"`
	// Program is the executable path (no shell interpretation).
	Program string `json:"program"`
	// Args is the argument template; supimplements `{placeholder}` expansion and
	// quotes.
	Args string `json:"args"`
	// TimeoutSecs kills the process after this many seconds (default 60, max
	// 86400).
	TimeoutSecs uint64 `json:"timeout_secs"`
}

EventHook is one external program bound to a set of events.

func DefaultEventHook

func DefaultEventHook() EventHook

DefaultEventHook returns the `EventHook::default()` value.

func LoadHooks

func LoadHooks(settings map[string]string) []EventHook

LoadHooks loads hooks from the `event_hooks` settings key (a JSON array). Bad or missing input yields an empty list.

func (*EventHook) UnmarshalJSON

func (h *EventHook) UnmarshalJSON(data []byte) error

UnmarshalJSON applies the JSON defaults: `enabled` defaults to true and `timeout_secs` to 60 when the keys are absent.

type EventLog

type EventLog struct {
	// contains filtered or unexported fields
}

EventLog is the capped torrent-event buffer ( `Arc<Mutex<Vec<TorrentEvent>>>` with a 512-entry cap).

func (*EventLog) Drain

func (e *EventLog) Drain() []models.TorrentEvent

Drain removes and returns every buffered event.

func (*EventLog) Push

func (e *EventLog) Push(event models.TorrentEvent)

Push appends one event, dropping the oldest entries past the 512 cap.

func (*EventLog) Snapshot

func (e *EventLog) Snapshot() []models.TorrentEvent

Snapshot returns a copy of the buffered events.

func (*EventLog) SnapshotAndClear

func (e *EventLog) SnapshotAndClear() []models.TorrentEvent

SnapshotAndClear returns a copy of the buffered events and empties the log.

type ExplainReleaseInput

type ExplainReleaseInput struct {
	Release models.Release `json:"release"`
}

ExplainReleaseInput is the input of `explain_release`.

type FeedRead

type FeedRead struct {
	Rows int
	Kept int
}

FeedRead is one successful read of a feed line: the rows the page carried and the releases the parser kept from them. A page with rows and no release is a listing whose markup no longer matches the parser, not an empty listing.

func FetchFeedWithRead

func FetchFeedWithRead(ctx context.Context, rawURL string, flaresolverr *string, maxPages int, maxAgeDays int64, oldRatio float64) ([]models.Release, FeedRead, error)

FetchFeedWithRead is FetchFeed plus how many rows the page carried: a caller that reports the state of a feed tells a listing that yields nothing from one that is simply empty.

type FeedSeenEntry

type FeedSeenEntry struct {
	ID           int64  `json:"id"`
	Title        string `json:"title"`
	Name         string `json:"name"`
	Year         int64  `json:"year"`
	Season       int64  `json:"season"`
	Episode      int64  `json:"episode"`
	Resolution   string `json:"resolution"`
	Codec        string `json:"codec"`
	Audio        string `json:"audio"`
	QualityScore int64  `json:"quality_score"`
	Magnet       string `json:"magnet"`
	Source       string `json:"source"`
	FoundAt      string `json:"found_at"`
}

FeedSeenEntry is one release "seen in feed".

type FeedSeenGroup

type FeedSeenGroup struct {
	GroupKey       string `json:"group_key"`
	GroupName      string `json:"group_name"`
	Year           int64  `json:"year"`
	Season         int64  `json:"season"`
	Count          int64  `json:"count"`
	BestScore      int64  `json:"best_score"`
	BestResolution string `json:"best_resolution"`
	LatestFound    string `json:"latest_found"`
	FirstFound     string `json:"first_found"`
}

FeedSeenGroup is a group of "seen in feed" releases (same title, optionally with a TMDB id).

type FilePrioritiesInput

type FilePrioritiesInput struct {
	Priorities []int32 `json:"priorities"`
}

type FtpTestInput

type FtpTestInput struct {
	Host     *string `json:"host"`
	User     *string `json:"user"`
	Password *string `json:"password"`
	Path     *string `json:"path"`
}

type FtpTestReport

type FtpTestReport struct {
	Host        string  `json:"host"`
	User        string  `json:"user"`
	Path        string  `json:"path"`
	TestFile    string  `json:"test_file"`
	Connected   bool    `json:"connected"`
	LoggedIn    bool    `json:"logged_in"`
	EnteredPath bool    `json:"entered_path"`
	Uploaded    bool    `json:"uploaded"`
	Deleted     bool    `json:"deleted"`
	Error       *string `json:"error"`
}

FtpTestReport is the outcome of a full FTP test (connect, login, CWD, upload and delete a probe file). Every step is logged and reported so the UI can show what worked.

func TestFTP

func TestFTP(host, user, password, remotePath string) FtpTestReport

TestFTP connects, logs in, enters the remote directory, uploads a small probe file and deletes it again — so a successful test proves the backup copy can work.

func (FtpTestReport) OK

func (r FtpTestReport) OK() bool

OK reports whether the whole test completed without an error.

type GetComicsClient

type GetComicsClient struct {
	// contains filtered or unexported fields
}

GetComicsClient is the GetComics scraper.

func NewGetComicsClient

func NewGetComicsClient() *GetComicsClient

NewGetComicsClient is `GetComicsClient::new`.

func (*GetComicsClient) DownloadDirect

func (c *GetComicsClient) DownloadDirect(rawURL, targetDir, title string) (string, error)

DownloadDirect resolves a GetComics redirect and downloads it to disk.

func (*GetComicsClient) DownloadTorrent

func (c *GetComicsClient) DownloadTorrent(rawURL, targetDir string) (string, error)

DownloadTorrent downloads a `.torrent` file.

func (c *GetComicsClient) Links(postURL string) (ComicLinks, error)

Links parses the download links of a post page.

func (*GetComicsClient) ResolveMega

func (c *GetComicsClient) ResolveMega(rawURL string) (string, error)

ResolveMega resolves a GetComics redirect to its final MEGA URL.

func (*GetComicsClient) SearchPosts

func (c *GetComicsClient) SearchPosts(query string) (string, []ComicPost, error)

SearchPosts searches GetComics through its WordPress search endpoint. The returned URL can also be stored as a monitored source.

func (*GetComicsClient) StartDirectDownload

func (c *GetComicsClient) StartDirectDownload(rawURL, targetDir, title string) (string, error)

StartDirectDownload resolves a GetComics redirect and starts the HTTP download in the background, returning the id used by the comics download list.

func (*GetComicsClient) StartDirectDownloadWithCompletion

func (c *GetComicsClient) StartDirectDownloadWithCompletion(rawURL, targetDir, title string, onComplete func(string)) (string, error)

StartDirectDownloadWithCompletion starts a direct download and invokes onComplete only after the final file has been written successfully.

func (*GetComicsClient) TagPosts

func (c *GetComicsClient) TagPosts(tagURL, fromDate string) ([]ComicPost, error)

TagPosts fetches a tag page and parses its articles.

func (c *GetComicsClient) WeeklyLinks(date string) (string, ComicLinks, error)

WeeklyLinks finds the weekly pack page of a date, trying the known paths and then GetComics' search.

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request, s *AppState)

HandlerFunc is the common web handler signature: the state is injected by `handle` instead of being a global.

type HandlerQuery

type HandlerQuery struct {
	File string `json:"file"`
}

type Health

type Health struct {
	Status               string       `json:"status"`
	UnixTime             uint64       `json:"unix_time"`
	ProcessID            uint32       `json:"process_id"`
	ResidentBytes        uint64       `json:"resident_bytes"`
	MemoryTotalBytes     uint64       `json:"memory_total_bytes"`
	MemoryAvailableBytes uint64       `json:"memory_available_bytes"`
	DataDirWritable      bool         `json:"data_dir_writable"`
	DiskTotalBytes       uint64       `json:"disk_total_bytes"`
	DiskFreeBytes        uint64       `json:"disk_free_bytes"`
	UptimeSeconds        uint64       `json:"uptime_seconds"`
	ProcessUptimeSeconds uint64       `json:"process_uptime_seconds"`
	LoadAverage          *float64     `json:"load_average"`
	CPUPercent           *float64     `json:"cpu_percent"`
	ProcessCPUPercent    *float64     `json:"process_cpu_percent"`
	TrashFileCount       uint64       `json:"trash_file_count"`
	TrashBytes           uint64       `json:"trash_bytes"`
	Disks                []DiskInfo   `json:"disks"`
	Paths                []PathCheck  `json:"paths"`
	Ramdisk              *RamDiskInfo `json:"ramdisk"`
	LastErrors           []string     `json:"last_errors"`
}

Health is the full health report exposed by the dashboard/health endpoints.

func Check

func Check(dataDir string) Health

Check runs the health check for the given data directory.

func CheckWithPaths

func CheckWithPaths(paths *HealthPaths) Health

CheckWithPaths runs the full health check over the supplied operational paths.

type HealthPaths

type HealthPaths struct {
	DataDir      string
	TrashPath    string
	DownloadPath string
	ArchiveRoot  string
	RamdiskPath  string
}

HealthPaths is the context of the paths inspected by the health check.

type HistoryQuery

type HistoryQuery struct {
	Page  *int    `json:"page"`
	Limit *int    `json:"limit"`
	Q     *string `json:"q"`
}

HistoryQuery is the query of the history endpoints.

type HookRun

type HookRun struct {
	Hook     string `json:"hook"`
	Program  string `json:"program"`
	ExitCode *int   `json:"exit_code"`
	Success  bool   `json:"success"`
	Stdout   string `json:"stdout"`
	Stderr   string `json:"stderr"`
}

HookRun is the result of executing one hook.

func RunHook

func RunHook(hook EventHook, event string, payload map[string]any) (HookRun, error)

RunHook runs a hook, expanding its program and arguments and exporting the variables as environment. It returns an error only when the process cannot be spawned or times out.

type HousekeepingParams

type HousekeepingParams struct {
	RetainCycles      int64 `json:"retain_cycles"`
	ErrorAgeDays      int64 `json:"error_age_days"`
	SeenDays          int64 `json:"seen_days"`
	GapLogDays        int64 `json:"gap_log_days"`
	UpgradeBackupDays int64 `json:"upgrade_backup_days"`
	HistoryDays       int64 `json:"history_days"`
}

HousekeepingParams are the retention knobs for a housekeeping run. `0` disables the corresponding cleanup so the user can keep as much history as they want.

func DefaultHousekeepingParams

func DefaultHousekeepingParams() HousekeepingParams

DefaultHousekeepingParams mirrors `impl Default for HousekeepingParams`.

func (HousekeepingParams) FromSettings

func (p HousekeepingParams) FromSettings(settings map[string]string) HousekeepingParams

FromSettings builds the retention knobs from the settings map.

type HousekeepingReport

type HousekeepingReport struct {
	OldCyclesRemoved      int `json:"old_cycles_removed"`
	StaleTorrentsRemoved  int `json:"stale_torrents_removed"`
	SeenRemoved           int `json:"seen_removed"`
	GapLogsRemoved        int `json:"gap_logs_removed"`
	UpgradeBackupsRemoved int `json:"upgrade_backups_removed"`
	OldHistoryRemoved     int `json:"old_history_removed"`
	StaleProvidersRemoved int `json:"stale_providers_removed"`
	StagedTorrentsRemoved int `json:"staged_torrents_removed"`
}

HousekeepingReport is the serialisable result of `housekeeping`.

type I18n

type I18n struct {
	// contains filtered or unexported fields
}

I18n holds the in-memory key/value dictionary loaded from a YAML file.

func (*I18n) Load

func (i *I18n) Load(path string) (*I18n, error)

Load reads a flat key/value YAML translation file. A missing path yields an empty dictionary, matching the `Path::exists` guard.

func (*I18n) T

func (i *I18n) T(key string) string

T returns the translation for key, falling back to the key itself.

type I18nDb

type I18nDb struct {
	// contains filtered or unexported fields
}

I18nDb is the persisted interface-translation database. It shares the `gextto_config.db` schema with the daemon.

func OpenI18nDb

func OpenI18nDb(path string) (*I18nDb, error)

OpenI18nDb opens (creating if needed) the translation database at path.

func (*I18nDb) Checkpoint

func (i *I18nDb) Checkpoint() error

Checkpoint truncates the WAL after a checkpoint. It mirrors the database checkpoint.

func (*I18nDb) Close

func (d *I18nDb) Close() error

Close closes the underlying SQLite connection (see Database.Close).

func (*I18nDb) DeleteLang

func (i *I18nDb) DeleteLang(lang string) (int, error)

DeleteLang removes every translation row for a language. It returns how many rows were deleted.

func (*I18nDb) Dictionary

func (d *I18nDb) Dictionary(lang string) (map[string]string, error)

Dictionary returns the {key: value} map for a language, building and caching it on first use. The returned map is shared and must not be modified.

func (*I18nDb) Language

func (i *I18nDb) Language() (string, error)

Language returns the active UI language (public two-letter code).

func (*I18nDb) List

func (i *I18nDb) List(lang string) ([]Translation, error)

List returns every translation stored for a language, ordered by key.

func (*I18nDb) QuickCheck

func (i *I18nDb) QuickCheck() ([]string, error)

QuickCheck runs `PRAGMA quick_check` and returns its rows (`["ok"]` when the database is healthy). It mirrors the database quick check.

func (*I18nDb) RowCount

func (d *I18nDb) RowCount() int64

RowCount returns the number of rows stored in the translation database.

func (*I18nDb) SeedDefaultTranslations

func (i *I18nDb) SeedDefaultTranslations() (int, error)

SeedDefaultTranslations makes the translation database mirror the bundled catalogs. It returns how many rows were added. Parsing the catalogs and rewriting the rows costs about a second of CPU, so the merge is skipped while the database records the same catalogs as already merged; deleting a language clears that record.

func (*I18nDb) Set

func (i *I18nDb) Set(lang, key, value string) error

Set stores (or replaces) a single translation.

func (*I18nDb) SetBulk

func (i *I18nDb) SetBulk(lang string, values map[string]string) error

SetBulk stores (or replaces) many translations in a single transaction.

func (*I18nDb) SetLanguage

func (i *I18nDb) SetLanguage(lang string) error

SetLanguage persists the active UI language.

func (*I18nDb) TranslationsGeneration

func (d *I18nDb) TranslationsGeneration() uint64

TranslationsGeneration returns a counter bumped on every translation write.

type IgnoreEpisodeInput

type IgnoreEpisodeInput struct {
	Ignored bool   `json:"ignored"`
	Reason  string `json:"reason"`
}

IgnoreEpisodeInput is the input of `ignore_episode`.

type IndexerConfig

type IndexerConfig struct {
	Name    string `json:"name"`
	URL     string `json:"url"`
	APIKey  string `json:"api_key"`
	Enabled bool   `json:"enabled"`
	Manager string `json:"manager,omitempty"`
}

IndexerConfig describes one configured indexer.

`Manager` optionally declares that the indexer is a Jackett/Prowlarr manager entry ("jackett" or "prowlarr"), so the endpoint is chosen explicitly instead of being inferred from the URL/port/name.

func (*IndexerConfig) UnmarshalJSON

func (i *IndexerConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON applies the JSON default: `enabled` defaults to true when the key is absent. The plain Go zero value keeps it false, matching `IndexerConfig::default()`.

type Job

type Job struct {
	ID         string     `json:"id"`
	Kind       string     `json:"kind"`
	State      JobState   `json:"state"`
	Progress   float64    `json:"progress"`
	Message    string     `json:"message"`
	Error      string     `json:"error,omitempty"`
	Result     any        `json:"result,omitempty"`
	CreatedAt  time.Time  `json:"created_at"`
	StartedAt  *time.Time `json:"started_at,omitempty"`
	FinishedAt *time.Time `json:"finished_at,omitempty"`
	// contains filtered or unexported fields
}

Job is the observable snapshot of one background operation. It is designed to be serialised to the UI.

type JobFunc

type JobFunc func(ctx context.Context, id string)

JobFunc is the body of a job. It must return promptly when ctx is canceled and must not keep references to the JobManager after it returns. Progress and messages are reported through SetProgress so the manager stays the single owner of the job state.

type JobManager

type JobManager struct {
	// contains filtered or unexported fields
}

JobManager owns the lifecycle of background jobs: bounded concurrency, de-duplication of equivalent operations, retention of the most recent completed jobs and ordered shutdown. Producers register work with Create + Start; consumers read List/Get and stop work with Cancel.

Rename-all, scan-archives and media-info-backfill run as jobs; each keeps its visible HTTP contract and observes cancellation at safe points.

func NewJobManager

func NewJobManager(maxConcurrent, retention int) *JobManager

NewJobManager builds a manager with the given concurrency limit and retention of completed jobs. Non-positive values fall back to safe defaults.

func (*JobManager) Cancel

func (m *JobManager) Cancel(id string) bool

Cancel requests cancellation of a queued or running job. It reports whether the job existed and was still cancellable.

func (*JobManager) Close

func (m *JobManager) Close()

Close stops accepting jobs, cancels every active job and waits for the running goroutines. Producers must return when their context is canceled, or Close blocks.

func (*JobManager) Create

func (m *JobManager) Create(kind, dedupKey string) (*Job, bool)

Create registers a queued job. When dedupKey is non-empty and an equivalent job is still queued or running, the existing job is returned with created false, so callers cannot start two identical operations by mistake.

func (*JobManager) Fail

func (m *JobManager) Fail(id string, err error)

Fail marks a job as failed from inside its function, so a late error is observable in the job state and not only in the logs. It is a no-op when the job already reached a terminal state.

func (*JobManager) Get

func (m *JobManager) Get(id string) (Job, bool)

Get returns a snapshot of a job.

func (*JobManager) List

func (m *JobManager) List(kind string, state JobState) []Job

List returns job snapshots filtered by kind and state. Empty filters match everything. Jobs are ordered newest first.

func (*JobManager) SetProgress

func (m *JobManager) SetProgress(id string, progress float64, message string)

SetProgress updates the observable progress of a job still in flight.

func (*JobManager) SetResult

func (m *JobManager) SetResult(id string, result any)

SetResult stores a structured outcome on a job so callers that cannot wait for the HTTP response (the operation now runs in the background) can still read the detailed report from /api/jobs/{id}.

func (*JobManager) Start

func (m *JobManager) Start(id string, fn JobFunc) error

Start schedules fn for execution. It returns an error when the id is unknown, already started or the manager is closing. The goroutine is tracked so Close can wait for it.

type JobState

type JobState string

JobState is the lifecycle state of a background job tracked by JobManager.

const (
	JobQueued    JobState = "queued"
	JobRunning   JobState = "running"
	JobSucceeded JobState = "succeeded"
	JobFailed    JobState = "failed"
	JobCanceled  JobState = "canceled"
)

type KeywordPruneInput

type KeywordPruneInput struct {
	Keyword  string   `json:"keyword"`
	Keywords []string `json:"keywords"`
	Preview  bool     `json:"preview"`
}

type LanguageInput

type LanguageInput struct {
	Lang string `json:"lang"`
}

LanguageInput is the input of `i18n_language`.

type LibraryBulkEdit

type LibraryBulkEdit struct {
	Series   []string
	Movies   []int64
	Quality  *string
	Audio    *string
	Language *string
	Subtitle *string
	Exclude  *string
	Upgrades *bool
	Enabled  *bool
}

LibraryBulkEdit is one bulk change. A nil pointer leaves the field as it is; a pointer to "" clears it.

type LibraryInput

type LibraryInput struct {
	Series []SeriesConfig `json:"series"`
	Movies []MovieConfig  `json:"movies"`
}

LibraryInput is the input of `save_library` / `save_config_root`.

type LocalProcessReporter

type LocalProcessReporter interface {
	LocalProcessPID() (int, bool)
}

LocalProcessReporter is optionally implemented by a backend that runs a process on this machine and can name it, so the header can show its CPU and memory. A backend reached over the network (an external qBittorrent, a daemon on another host) reports false.

type LogLevel

type LogLevel struct {
	Level string `json:"level"`
}

LogLevel is the input of `set_log_level`.

type LogQuery

type LogQuery struct {
	Limit *int `json:"limit"`
}

LogQuery is the query of `logs` / `logs_stream`.

type MaintenanceReport

type MaintenanceReport struct {
	Rescored             int `json:"rescored"`
	OldCyclesRemoved     int `json:"old_cycles_removed"`
	StaleTorrentsRemoved int `json:"stale_torrents_removed"`
}

MaintenanceReport is the result of `cleanup`.

type ManualImportCandidate

type ManualImportCandidate struct {
	Path        string
	Name        string
	Kind        string
	ParsedTitle string
	Series      string
	Season      int64
	Episode     int64
	Episodes    []int64
	Year        int64
	Matched     bool
	Destination string
	Target      string
	Error       string
}

ManualImportCandidate is one video file the page proposes to import.

func ManualImportPreview

func ManualImportPreview(cfg *Config, path string) ([]ManualImportCandidate, error)

ManualImportPreview lists the video files under path with what the import would do. It never touches the filesystem.

type ManualImportRequest

type ManualImportRequest struct {
	Path     string
	Kind     string
	Series   string
	Movie    string
	Year     int64
	Season   int64
	Episode  int64
	Replace  bool
	TMDBKey  string
	Language string
}

ManualImportRequest is what the page confirms for one file.

type ManualSearchQuery

type ManualSearchQuery struct {
	Q     *string `json:"q"`
	Query *string `json:"query"`
}

ManualSearchQuery is the query of `manual_search_get`.

type MediaInfo

type MediaInfo struct {
	Container string `json:"container"`
	Width     int64  `json:"width"`
	Height    int64  `json:"height"`
	// VideoCodec is the raw ffprobe codec_name.
	VideoCodec string `json:"video_codec"`
	BitDepth   int64  `json:"bit_depth"`
	// HDR is "", "HDR10", "HDR10+", "HLG", "DV", "DV HDR10", ...
	HDR               string           `json:"hdr"`
	AudioCodec        string           `json:"audio_codec"`
	AudioChannels     int64            `json:"audio_channels"`
	AudioLanguages    []string         `json:"audio_languages"`
	AudioTracks       []AudioTrackInfo `json:"audio_tracks,omitempty"`
	Streams           []StreamInfo     `json:"streams,omitempty"`
	SubtitleLanguages []string         `json:"subtitle_languages"`
	// RuntimeSeconds is the duration in seconds, rounded.
	RuntimeSeconds int64 `json:"runtime_seconds"`
}

MediaInfo is the parsed result of probing a media file.

func ParseFfprobe

func ParseFfprobe(root map[string]any) MediaInfo

ParseFfprobe parses the JSON produced by `ffprobe -v error -print_format json -show_format -show_streams`.

func Probe

func Probe(path string) *MediaInfo

Probe runs `ffprobe` on path. It returns nil when the binary is missing, the file is unreadable, or the output is not valid JSON.

func ProbeBest

func ProbeBest(path string) *MediaInfo

ProbeBest probes a video file, or the largest video file directly inside a directory (archive entries are sometimes stored as a folder). It returns nil on failure.

func ProbeBestResult

func ProbeBestResult(path string) (MediaInfo, error)

ProbeBestResult is like ProbeBest but keeps the failure reason, so the backfill can tell the user which file failed and why instead of only counting it.

func ProbeResult

func ProbeResult(path string) (MediaInfo, error)

ProbeResult runs `ffprobe` on path and returns a human-readable reason on failure, so the caller can log the exact file that could not be analyzed.

func (MediaInfo) AddsToQuality

func (m MediaInfo) AddsToQuality(quality models.Quality) bool

AddsToQuality reports whether the probe found something the given quality does not carry: the fields a later upgrade decision takes from the file instead of the release name. It is the effect ApplyToQuality would have, without changing the caller's value.

func (MediaInfo) ApplyToQuality

func (m MediaInfo) ApplyToQuality(quality *models.Quality)

ApplyToQuality enriches a filename-derived quality with ground-truth attributes. It is additive: it fills HDR/codec/audio/resolution only when the probe found them and the filename value is unknown, so it can never clear a value or regress an existing file. Used to make upgrade comparisons read the real archived file, not just its name.

func (MediaInfo) HasHDR

func (m MediaInfo) HasHDR() bool

HasHDR reports whether the probe found an HDR flavour.

func (MediaInfo) Resolution

func (m MediaInfo) Resolution() string

Resolution is the resolution bucket derived from the real frame size, used to sanity-check (or replace) the filename-derived resolution.

type MediaInfoBackfillTarget

type MediaInfoBackfillTarget struct {
	Kind    string `json:"kind"`
	Series  string `json:"series"`
	Season  *int64 `json:"season"`
	Episode *int64 `json:"episode"`
	Name    string `json:"name"`
	Year    *int64 `json:"year"`
	Path    string `json:"path"`
	// Title is the release title stored with the row. It may still name a
	// release that was later replaced, so it is only used to explain the
	// difference against the file that is actually on disk.
	Title string `json:"title,omitempty"`
}

MediaInfoBackfillTarget is one archived entry to (re)probe for the MediaInfo backfill.

type MediaInfoQuery

type MediaInfoQuery struct {
	Series  *string `json:"series"`
	Season  *int64  `json:"season"`
	Episode *int64  `json:"episode"`
	Movie   *string `json:"movie"`
	Year    *int64  `json:"year"`
}

type MediaIntegrityProblem

type MediaIntegrityProblem struct {
	TargetID   int64  `json:"target_id"`
	Kind       string `json:"kind"`
	Series     string `json:"series"`
	Season     int64  `json:"season"`
	Episode    int64  `json:"episode"`
	MovieName  string `json:"movie_name"`
	MovieYear  int64  `json:"movie_year"`
	Path       string `json:"path"`
	Status     string `json:"status"`
	Detail     string `json:"detail"`
	SizeBytes  int64  `json:"size_bytes"`
	ModifiedNS int64  `json:"modified_ns"`
	CheckedAt  string `json:"checked_at"`
}

MediaIntegrityProblem is a damaged or unreadable file stored by the scan.

func (MediaIntegrityProblem) Label

func (p MediaIntegrityProblem) Label() string

Label names the problem the way the operator sees it.

type MediaIntegrityStartInput

type MediaIntegrityStartInput struct {
	// Restart starts a fresh pass from the first file even when the previous
	// one was interrupted or completed.
	Restart bool `json:"restart"`
	// Batch is the number of files this run checks before stopping; 0 means
	// every pending file (the manual full pass).
	Batch int `json:"batch"`
}

MediaIntegrityStartInput is the optional body of the start request.

type MediaIntegrityState

type MediaIntegrityState struct {
	Cursor string `json:"cursor"`
	// Force rechecks every file, even the ones already checked and unchanged.
	Force bool `json:"force"`
	// ManifestFingerprint identifies the external report last applied. When it
	// changes, the pass starts again so the new verified files are honoured.
	ManifestFingerprint string `json:"manifest_fingerprint"`
	Total               int    `json:"total"`
	Checked             int    `json:"checked"`
	Running             bool   `json:"running"`
	// Stopped records that the last run ended because the operator stopped it,
	// so the next run says in the log that the check resumes from here.
	Stopped    bool   `json:"stopped"`
	Done       bool   `json:"done"`
	Current    string `json:"current"`
	StartedAt  string `json:"started_at"`
	FinishedAt string `json:"finished_at"`
}

MediaIntegrityState is the resumable progress of the scan. It is stored as JSON in ui_state so a restart continues where it left off.

type MediaIntegrityStatus

type MediaIntegrityStatus struct {
	OK         bool                    `json:"ok"`
	Available  bool                    `json:"available"`
	Missing    []string                `json:"missing,omitempty"`
	Running    bool                    `json:"running"`
	Done       bool                    `json:"done"`
	Total      int                     `json:"total"`
	Checked    int                     `json:"checked"`
	Damaged    int                     `json:"damaged"`
	Unreadable int                     `json:"unreadable"`
	Cursor     string                  `json:"cursor"`
	Current    string                  `json:"current"`
	StartedAt  string                  `json:"started_at"`
	FinishedAt string                  `json:"finished_at"`
	Problems   []MediaIntegrityProblem `json:"problems"`
}

MediaIntegrityStatus is the answer of the status endpoint and the model of the Maintenance panel.

type MediaIntegrityTarget

type MediaIntegrityTarget struct {
	// Kind is "episode" or "movie".
	Kind      string
	ID        int64
	Series    string
	Season    *int64
	Episode   *int64
	MovieName string
	MovieYear *int64
	Path      string
	// SizeBytes and ModifiedNS are the current file identity, read when the
	// target is selected. They are stored with the outcome so a later pass can
	// skip the file while it is unchanged.
	SizeBytes  int64
	ModifiedNS int64
	// Resolved is the video file actually probed: an archived folder is
	// resolved to its largest video file.
	Resolved string
}

MediaIntegrityTarget is one archived file the scan has to check.

func (MediaIntegrityTarget) Label

func (t MediaIntegrityTarget) Label() string

Label names the library item the way the operator sees it.

type MediaProbeInput

type MediaProbeInput struct {
	Path string `json:"path"`
}

MediaProbeInput is the body of a media info probe: the path to inspect.

type MigrateReport

type MigrateReport struct {
	From         string            `json:"from"`
	To           string            `json:"to"`
	Databases    map[string]string `json:"databases"`
	TorrentState string            `json:"torrent_state,omitempty"`
	ConfigJSON   string            `json:"config_json,omitempty"`
	Warnings     []string          `json:"warnings"`
}

MigrateReport summarises a data-directory migration.

func MigrateDataDir

func MigrateDataDir(from, to string) (MigrateReport, error)

MigrateDataDir copies a data directory from a previous gextto-compatible layout into the current one, renaming the databases and the libtorrent state directory. It never modifies the source: each database is copied with `VACUUM INTO` from a read-only connection (falling back to a byte copy when that is not possible), so a running daemon can be migrated safely.

type MigrationItem

type MigrationItem struct {
	Hash        string  `json:"hash"`
	Name        string  `json:"name"`
	TorrentFile string  `json:"torrent_file,omitempty"`
	Magnet      string  `json:"magnet,omitempty"`
	SavePath    string  `json:"save_path"`
	Progress    float64 `json:"progress"`
	State       string  `json:"state"`
	Paused      bool    `json:"paused"`
	TotalSize   int64   `json:"total_size"`
	HasMetadata bool    `json:"has_metadata"`
}

MigrationItem is one torrent to preserve across a backend switch.

type MigrationManifest

type MigrationManifest struct {
	FromBackend string          `json:"from_backend"`
	ToBackend   string          `json:"to_backend"`
	CreatedAt   string          `json:"created_at"`
	Items       []MigrationItem `json:"items"`
	Warnings    []string        `json:"warnings"`
	Ready       bool            `json:"ready"`
	// Imported and CompletedAt are set once the target backend re-imported the
	// manifest at startup, so the import is not repeated.
	Imported    int    `json:"imported,omitempty"`
	CompletedAt string `json:"completed_at,omitempty"`
}

MigrationManifest is the persisted, replayable state of one migration.

func BuildMigrationPlan

func BuildMigrationPlan(s *AppState, cfg *Config, target string) MigrationManifest

BuildMigrationPlan snapshots every managed torrent and validates the target backend without touching either engine.

func LoadMigrationManifest

func LoadMigrationManifest(cfg *Config) (*MigrationManifest, error)

LoadMigrationManifest reads a previously persisted manifest, if any.

type MissingSearchInput

type MissingSearchInput struct {
	Series  string `json:"series"`
	Season  int64  `json:"season"`
	Episode int64  `json:"episode"`
}

MissingSearchInput is the input of `search_missing`.

type MkdirInput

type MkdirInput struct {
	Path string `json:"path"`
}

type MovieArchiveIndex

type MovieArchiveIndex struct {
	// contains filtered or unexported fields
}

MovieArchiveIndex is one walk of the archive root, kept for the whole cycle so that every movie candidate does not walk the tree again. The walk reads each file name once and stats each file once; the score of a matching file is computed per candidate, because the settings can single out a movie by title.

func BuildMovieArchiveIndex

func BuildMovieArchiveIndex(cfg *Config) *MovieArchiveIndex

BuildMovieArchiveIndex walks the archive root once. A nil or missing root gives an empty index, so a caller can always use it.

func (*MovieArchiveIndex) Best

func (index *MovieArchiveIndex) Best(cfg *Config, release *models.Release) *models.ArchiveQuality

Best returns the best archived copy of the release, or nil when the archive has none: the same answer ArchiveMovieQuality gave walking the tree for every candidate.

type MovieConfig

type MovieConfig struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	Year string `json:"year"`
	// Identificativi e dati editoriali: non intervengono nei filtri o nello
	// stato del download e possono essere aggiornati dalla scelta TMDB/TVDB.
	TmdbID        string `json:"tmdb_id"`
	TvdbID        string `json:"tvdb_id"`
	OriginalTitle string `json:"original_title"`
	// Aliases are the other titles the film is released under (the
	// international title, for example). They are filled from TMDB and used by
	// the title match and the archive search, so a film monitored under its
	// Italian title is also found when the release uses another one.
	Aliases []string `json:"aliases"`
	// TitleTranslations holds TMDB's localized title for each language
	// (ISO 639-1: "it", "en", …). The indexer search uses the title in the
	// language chosen for the film and the English one; a nil map means "not
	// read yet".
	TitleTranslations    map[string]string `json:"title_translations,omitempty"`
	Overview             string            `json:"overview"`
	PosterPath           string            `json:"poster_path"`
	Quality              string            `json:"quality"`
	Audio                string            `json:"audio"`
	AudioChannels        string            `json:"audio_channels"`
	Language             string            `json:"language"`
	Enabled              bool              `json:"enabled"`
	Subtitle             string            `json:"subtitle"`
	Exclude              string            `json:"exclude"`
	LanguageRequirements string            `json:"language_requirements"`
	SubtitleRequirements string            `json:"subtitle_requirements"`
	// When true, a better release never replaces an archived file for this
	// movie. Default false (= upgrades allowed).
	DisableUpgrades bool `json:"disable_upgrades"`
}

MovieConfig is one monitored movie.

func (*MovieConfig) UpgradesAllowed

func (m *MovieConfig) UpgradesAllowed() bool

UpgradesAllowed reports whether a better release may replace an archived file (default true).

type MovieHistory

type MovieHistory struct {
	ID           int64   `json:"id"`
	Name         string  `json:"name"`
	Year         *int64  `json:"year"`
	Title        string  `json:"title"`
	QualityScore int64   `json:"quality_score"`
	DownloadedAt *string `json:"downloaded_at"`
	SizeBytes    int64   `json:"size_bytes"`
	MagnetHash   *string `json:"magnet_hash"`
}

MovieHistory is one downloaded movie of the history view.

type MovieMetadataApplyInput

type MovieMetadataApplyInput struct {
	Id     string `json:"id"`
	Source string `json:"source"`
}

MovieMetadataApplyInput is the input of `apply_movie_metadata`.

type MovieMetadataSearchInput

type MovieMetadataSearchInput struct {
	Query  string `json:"query"`
	Source string `json:"source"`
}

MovieMetadataSearchInput is the input of `movie_metadata_search`.

type MovieUpdateInput

type MovieUpdateInput struct {
	Name                 string  `json:"name"`
	Year                 string  `json:"year"`
	Quality              string  `json:"quality"`
	Audio                *string `json:"audio"`
	AudioChannels        *string `json:"audio_channels"`
	Language             string  `json:"language"`
	Subtitle             string  `json:"subtitle"`
	Exclude              string  `json:"exclude"`
	LanguageRequirements string  `json:"language_requirements"`
	SubtitleRequirements string  `json:"subtitle_requirements"`
	Enabled              *bool   `json:"enabled"`
	TmdbId               string  `json:"tmdb_id"`
	TvdbId               string  `json:"tvdb_id"`
	DisableUpgrades      *bool   `json:"disable_upgrades"`
	// SubtitleRequired is «Sottotitoli obbligatori»: when set it makes the
	// subtitle language a requirement (true) or only a preference (false),
	// replacing SubtitleRequirements.
	SubtitleRequired *bool `json:"subtitle_required"`
	// QualityProfileID, when above 0, copies that profile's values into the
	// movie (see SeriesUpdateInput).
	QualityProfileID *int `json:"quality_profile_id"`
}

MovieUpdateInput is the input of `update_movie`.

type NightMaintenanceForgetInput

type NightMaintenanceForgetInput struct {
	Series  string `json:"series"`
	Season  int64  `json:"season"`
	Episode int64  `json:"episode"`
}

NightMaintenanceForgetInput names the episode whose file is gone.

type NoRenameInput

type NoRenameInput struct {
	Value bool `json:"value"`
}

NoRenameInput is the input of `set_torrent_no_rename`.

type Notifier

type Notifier struct {
	// contains filtered or unexported fields
}

Notifier delivers notifications over Telegram, an HTTP webhook and SMTP, and dispatches the configured external event hooks. It is a faithful implementation of gextto's `notifier::Notifier`.

func FromConfig

func FromConfig(cfg *Config) *Notifier

FromConfig builds a notifier from the runtime configuration.

func NewNotifier

func NewNotifier() *Notifier

NewNotifier is the `Notifier::new()` constructor: everything disabled.

func (*Notifier) Async

func (n *Notifier) Async() *Notifier

Async returns a copy of the notifier whose NotifyEvent only enqueues the event and returns at once. The background workers (torrent events, cycle) use it: a slow or unreachable Telegram, webhook or SMTP server must not stall stall monitoring, seed policy or post-processing. Delivery errors are logged by the delivery goroutine. Interactive callers (the "test notification" button) keep the synchronous notifier so they can report the error.

func (*Notifier) Enabled

func (n *Notifier) Enabled() bool

Enabled reports whether at least one delivery channel is fully configured.

func (*Notifier) EventHooks

func (n *Notifier) EventHooks() []EventHook

EventHooks returns a copy of the configured event hooks.

func (*Notifier) Notify

func (n *Notifier) Notify(text string) error

Notify sends a plain text message (`message` event).

func (*Notifier) NotifyBackupDocument

func (n *Notifier) NotifyBackupDocument(path, caption string) (int, error)

NotifyBackupDocument uploads a backup archive to Telegram, split into pieces below the Bot API upload limit when it is larger. It returns how many pieces were sent (0 without an error when Telegram is not configured).

func (*Notifier) NotifyComicComplete

func (n *Notifier) NotifyComicComplete(title, path string, sizeBytes uint64, method string) error

NotifyComicComplete emits a `comic_completed` event.

func (*Notifier) NotifyEvent

func (n *Notifier) NotifyEvent(event string, data map[string]any) error

NotifyEvent formats and delivers one event to every enabled channel and dispatches the external hooks.

func (*Notifier) ReloadHooks

func (n *Notifier) ReloadHooks(hooks []EventHook)

ReloadHooks replaces the event hooks, e.g. after the settings API saved them.

type OrphanDownload

type OrphanDownload struct {
	Path      string `json:"path"`
	Name      string `json:"name"`
	SizeBytes int64  `json:"size_bytes"`
	Episodes  string `json:"episodes,omitempty"`
	Safe      bool   `json:"safe"`
	Reason    string `json:"reason,omitempty"`
}

OrphanDownload is one leftover entry in a download folder.

func FindOrphanedDownloads

func FindOrphanedDownloads(cfg *Config, db *Database, torrents TorrentEngine) []OrphanDownload

FindOrphanedDownloads scans the configured download folders. It never looks inside a folder owned by a live torrent, and it ignores entries that do not contain at least one episode-named video.

type PackEpisode

type PackEpisode struct {
	Episode   int64
	Path      string
	SizeBytes int64
	Score     int64
}

PackEpisode is one completed episode of a season pack: `(episode, path, size_bytes, quality_score)`.

type PackFileResult

type PackFileResult struct {
	Episode      int64
	Path         string
	SizeBytes    int64
	QualityScore int64
	Discarded    bool
	Upgrade      bool
	TrashCount   int
}

PackFileResult is the outcome of processing one staged pack episode.

func ProcessPackFiles

func ProcessPackFiles(
	ctx context.Context,
	files []PackInput,
	release *models.Release,
	cfg *Config,
	tmdb *TmdbClient,
) ([]PackFileResult, error)

ProcessPackFiles renames, deduplicates and scores each staged pack episode (implementation of `process_pack_files`).

type PackInput

type PackInput struct {
	Path   string
	Source PackSourceFile
}

PackInput pairs a staged file path with its pack identity, mirroring the `(PathBuf, PackSourceFile)` tuple.

type PackSourceFile

type PackSourceFile struct {
	Path    string
	Season  int64
	Episode int64
}

PackSourceFile pairs a pack file path with its resolved season/episode.

func MatchingPackFiles

func MatchingPackFiles(source string, release *models.Release) ([]PackSourceFile, error)

MatchingPackFiles resolves the episode identity of every file that can safely be imported from a pack.

type PathCheck

type PathCheck struct {
	Label    string `json:"label"`
	Path     string `json:"path"`
	Exists   bool   `json:"exists"`
	Writable bool   `json:"writable"`
}

PathCheck reports existence and writability of an operational path.

type PathMapping

type PathMapping struct {
	Gextto  string `json:"gextto"`
	Backend string `json:"backend"`
}

PathMapping translates between the path as Gextto sees it and the path as the backend process sees it. Empty/equal pairs are allowed and mean "identical".

func ParsePathMappings

func ParsePathMappings(raw string) ([]PathMapping, error)

ParsePathMappings decodes the `backend_path_mappings` setting, which is a newline-separated list of `gextto_path=backend_path` pairs. Lines starting with `#` and blank lines are ignored. Invalid lines are reported.

type PeerOptionsInput

type PeerOptionsInput struct {
	// BandwidthWeight is the share of a limited line in percent (100 =
	// normal, 10..1000).
	BandwidthWeight int  `json:"bandwidth_weight"`
	Dht             bool `json:"dht"`
	Pex             bool `json:"pex"`
	Lsd             bool `json:"lsd"`
}

PeerOptionsInput is the body of POST /api/torrents/{hash}/peer-options.

type PendingQueueItem

type PendingQueueItem struct {
	Title   string
	Label   string
	Waiting time.Duration
	Due     time.Duration
	Ready   bool
}

PendingQueueItem is a title held by the delay profile, with how long it has been waiting and how long until it is due.

type ProcessCpuSample

type ProcessCpuSample struct {
	// contains filtered or unexported fields
}

ProcessCpuSample is the last process CPU reading from /proc/self/stat.

type ProcessMetricsSnapshot

type ProcessMetricsSnapshot struct {
	ResidentBytes     uint64   `json:"resident_bytes"`
	ProcessCPUPercent *float64 `json:"process_cpu_percent"`
	// Go runtime figures help separate the process's own heap from the engine's
	// footprint (the managed qBittorrent process or the gx-torrent daemon).
	GoHeapBytes      uint64 `json:"go_heap_bytes"`
	GoHeapInuseBytes uint64 `json:"go_heap_inuse_bytes"`
	GoGoroutines     int    `json:"go_goroutines"`
	GoGCCount        uint32 `json:"go_gc_count"`
}

ProcessMetricsSnapshot holds the lightweight process-only metrics used by the always-visible UI status bar. It is the Go implementation of the `ProcessMetrics` struct; the type is named differently because Go does not allow a struct and the `ProcessMetrics()` function to share one package-level identifier.

func ProcessMetrics

func ProcessMetrics() ProcessMetricsSnapshot

ProcessMetrics returns the lightweight process-only metrics for the always-visible UI status bar. Unlike CheckWithPaths it does not inspect disks, paths or trash.

type Provenance

type Provenance struct {
	Origin    SettingOrigin
	Detail    string
	AppliedAt string
}

Provenance is the recorded origin of one setting.

type ProviderResetInput

type ProviderResetInput struct {
	Provider *string `json:"provider"`
}

type ProwlarrProbeEntry

type ProwlarrProbeEntry struct {
	// contains filtered or unexported fields
}

type PruneByIdsInput

type PruneByIdsInput struct {
	MovieSeen  []int64 `json:"movie_seen"`
	SeriesSeen []int64 `json:"series_seen"`
}

PruneByIdsInput is the input of `db_prune_by_ids`.

type PruneInput

type PruneInput struct {
	RetainCycles      *int64 `json:"retain_cycles"`
	ErrorAgeDays      *int64 `json:"error_age_days"`
	SeenRetentionDays *int64 `json:"seen_retention_days"`
	Preview           bool   `json:"preview"`
}

PruneInput is the input of `db_prune` / `db_prune_preview`.

type PrunePreview

type PrunePreview struct {
	OldCyclesToRemove     int `json:"old_cycles_to_remove"`
	StaleTorrentsToRemove int `json:"stale_torrents_to_remove"`
	SeenToRemove          int `json:"seen_to_remove"`
}

PrunePreview counts what a maintenance run *would* remove.

type QbittorrentPreflight

type QbittorrentPreflight struct {
	OK              bool          `json:"ok"`
	Connected       bool          `json:"connected"`
	AppVersion      string        `json:"app_version,omitempty"`
	WebAPIVersion   string        `json:"web_api_version,omitempty"`
	DefaultSavePath string        `json:"default_save_path,omitempty"`
	Torrents        int           `json:"torrents"`
	Mappings        []PathMapping `json:"path_mappings"`
	Warnings        []string      `json:"warnings,omitempty"`
	Errors          []string      `json:"errors,omitempty"`
}

QbittorrentPreflight is the result of the activation check surfaced to the UI.

func PreflightQbittorrent

func PreflightQbittorrent(cfg *Config) QbittorrentPreflight

PreflightQbittorrent runs the activation preflight from the current settings.

func PreflightQbittorrentWith

func PreflightQbittorrentWith(settings qbittorrentSettings) QbittorrentPreflight

PreflightQbittorrentWith runs connectivity + path checks for resolved settings.

type QualityProfile

type QualityProfile struct {
	ID              int    `json:"id"`
	Name            string `json:"name"`
	Quality         string `json:"quality"`
	Audio           string `json:"audio,omitempty"`
	Language        string `json:"language"`
	Subtitle        string `json:"subtitle"`
	Exclude         string `json:"exclude"`
	DisableUpgrades bool   `json:"disable_upgrades,omitempty"`
	Upgrades        string `json:"upgrades,omitempty"`
}

QualityProfile is one named combination of selection overrides. Audio is the minimum audio preset (empty = any); DisableUpgrades is «Permetti upgrade: No». Upgrades is the same switch as the profile editor writes it ("allow"/"deny"): normalizeProfileUpgrades keeps the two in step.

type RamDiskCreateInput

type RamDiskCreateInput struct {
	Path *string `json:"path"`
}

RamDiskCreateInput is the input of `create_ramdisk`.

type RamDiskInfo

type RamDiskInfo struct {
	Path       string `json:"path"`
	TotalBytes uint64 `json:"total_bytes"`
	FreeBytes  uint64 `json:"free_bytes"`
}

RamDiskInfo describes the optional libtorrent RAM disk.

type RamDiskSelectInput

type RamDiskSelectInput struct {
	Path string `json:"path"`
}

RamDiskSelectInput is the input of `select_ramdisk`.

type ReadyPending

type ReadyPending struct {
	Name    string
	Title   string
	Magnet  string
	Season  int64
	Episode int64
}

ReadyPending implements the `ReadyPending` tuple: `(series name, title, magnet, season, episode)`.

type ReadyPendingMovie

type ReadyPendingMovie struct {
	Name   string
	Title  string
	Magnet string
	Year   *int64
}

ReadyPendingMovie implements the `ReadyPendingMovie` tuple: `(name, title, magnet, year)`.

type RecentDownload

type RecentDownload struct {
	Kind         string  `json:"kind"`
	Name         string  `json:"name"`
	Season       *int64  `json:"season"`
	Episode      *int64  `json:"episode"`
	Year         *int64  `json:"year"`
	DownloadedAt string  `json:"downloaded_at"`
	SizeBytes    int64   `json:"size_bytes"`
	ArchivePath  *string `json:"archive_path"`
	QualityScore int64   `json:"quality_score"`
}

RecentDownload is one entry of the merged recent-download list.

type RemoveCompletedInput

type RemoveCompletedInput struct {
	DeleteFiles bool `json:"delete_files"`
}

RemoveCompletedInput is the input of `remove_completed_torrents`.

type RemoveOptionsInput

type RemoveOptionsInput struct {
	DeleteFiles bool `json:"delete_files"`
	Blocklist   bool `json:"blocklist"`
	Archive     bool `json:"archive"`
}

RemoveOptionsInput is the input of `remove_torrent_with_options`.

type RemoveTorrentInput

type RemoveTorrentInput struct {
	Hash        string `json:"hash"`
	DeleteFiles bool   `json:"delete_files"`
}

RemoveTorrentInput is the input of `remove_torrent_legacy`.

type RenameInput

type RenameInput struct {
	Force      bool `json:"force"`
	SourceOnly bool `json:"source_only"`
}

type RenameProgress

type RenameProgress struct {
	Running bool   `json:"running"`
	Current int    `json:"current"`
	Total   int    `json:"total"`
	Series  string `json:"series"`
	Message string `json:"message"`
	Errors  int    `json:"errors"`
}

RenameProgress is the progress of a background rename-all job.

type RestartCause

type RestartCause string

RestartCause classifies a start relative to the previous run.

const (
	// RestartFirstStart is the very first run: nothing to compare.
	RestartFirstStart RestartCause = "first-start"
	// RestartUpdate means the binary changed (version, build or commit): an
	// update/rebuild, never instability.
	RestartUpdate RestartCause = "update"
	// RestartUnclean means the previous run left no stop time (crash, kill -9).
	RestartUnclean RestartCause = "unclean"
	// RestartManual is a clean stop and start of the same binary.
	RestartManual RestartCause = "restart"
)

func ClassifyRestart

func ClassifyRestart(prev runState) RestartCause

ClassifyRestart tells an update/rebuild restart apart from an unclean stop and an ordinary clean restart.

type RestoreSourceInput

type RestoreSourceInput struct {
	Execute bool `json:"execute"`
}

RestoreSourceInput carries the execute flag of RestoreSource: when it is false the renames are only listed.

type RunNowQuery

type RunNowQuery struct {
	Domain *string `json:"domain"`
}

RunNowQuery is the query of `run_now`.

type ScorePreviewInput

type ScorePreviewInput struct {
	Title string `json:"title"`
}

ScorePreviewInput is the input of `score_preview`.

type ScrobbleInput

type ScrobbleInput struct {
	Action  *string `json:"action"`
	Payload any     `json:"payload"`
}

ScrobbleInput is the input of the scrobble endpoints.

type SearchAddInput

type SearchAddInput struct {
	Release models.Release `json:"release"`
}

SearchAddInput is the input of `add_search_result`.

type SearchInput

type SearchInput struct {
	Query string `json:"query"`
	// Kad asks the eD2k/Kad provider for this search. It is an explicit
	// per-search opt-in: the master switch (ed2k_enabled) permits it, the
	// checkbox in the search form decides whether to use it this time.
	Kad bool `json:"kad,omitempty"`
}

SearchInput is the input of `manual_search`.

type SearchResult

type SearchResult struct {
	Results []TmdbItem `json:"results"`
}

SearchResult mirrors the `SearchResult`.

type SeasonToggleInput

type SeasonToggleInput struct {
	Season  int64 `json:"season"`
	Enabled bool  `json:"enabled"`
}

SeasonToggleInput is the input of `toggle_season`.

type SeedRule

type SeedRule struct {
	Name string `json:"name"`
	// Source matches the release source (the indexer name as Gextto records
	// it, e.g. "mircrew indexerr", "jackett:LimeTorrents", "archive:ExtTo") by
	// a case-insensitive substring. Empty matches any source.
	Source string `json:"source"`
	// Category is series, movie, comic or other; empty matches any category.
	Category    string   `json:"category"`
	Ratio       *float64 `json:"ratio"`
	SeedDays    *float64 `json:"seed_days"`
	IdleMinutes *float64 `json:"idle_minutes"`
}

SeedRule is one per-origin seeding policy. A nil limit leaves that limit to the global setting; 0 means "no limit" (it overrides a global limit); a positive value is the limit.

type SeenQuery

type SeenQuery struct {
	Page  *int    `json:"page"`
	Limit *int    `json:"limit"`
	Q     *string `json:"q"`
	Key   *string `json:"key"`
	Group *string `json:"group"`
	Kind  *string `json:"kind"`
}

SeenQuery is the query of the seen/grouped views.

type SequentialInput

type SequentialInput struct {
	Enabled bool `json:"enabled"`
}

SequentialInput is the input of `set_sequential`.

type SeriesConfig

type SeriesConfig struct {
	Name             string   `json:"name"`
	Seasons          string   `json:"seasons"`
	Quality          string   `json:"quality"`
	Audio            string   `json:"audio"`
	AudioChannels    string   `json:"audio_channels"`
	Language         string   `json:"language"`
	ArchivePath      string   `json:"archive_path"`
	Timeframe        int64    `json:"timeframe"`
	Aliases          []string `json:"aliases"`
	TmdbID           string   `json:"tmdb_id"`
	TvdbID           string   `json:"tvdb_id"`
	Subtitle         string   `json:"subtitle"`
	Exclude          string   `json:"exclude"`
	Enabled          bool     `json:"enabled"`
	IgnoredSeasons   []int64  `json:"ignored_seasons"`
	SeasonSubfolders bool     `json:"season_subfolders"`
	// Anime series number releases by absolute episode ("Title - 1071"):
	// those numbers are mapped onto TMDB seasons.
	Anime bool `json:"anime"`
	// When true, a better release never replaces an archived file for this
	// series. Default false (= upgrades allowed).
	DisableUpgrades bool `json:"disable_upgrades"`
	// StatusOverride is the operator's answer to «is this series over?»: ""
	// leaves it to the sources (series_end_status.go), "ended" or
	// "continuing" beats them.
	StatusOverride string `json:"status_override,omitempty"`
}

SeriesConfig is one monitored series.

func (*SeriesConfig) UpgradesAllowed

func (s *SeriesConfig) UpgradesAllowed() bool

UpgradesAllowed reports whether a better release may replace an archived file (default true).

type SeriesEndRecord

type SeriesEndRecord struct {
	// Status is the provider status in TMDB words ("Ended", "Canceled",
	// "Returning Series", "In Production", ...).
	Status      string
	LastAirDate string
	// NextAirDate is the air date of the next announced episode ("" if none).
	NextAirDate string
	// TvmazeStatus is TVmaze's status ("Ended", "Running", "To Be Determined",
	// "In Development"); "" when TVmaze was not asked or does not know it.
	TvmazeStatus string
}

SeriesEndRecord is what the sources said about a series at the last refresh.

type SeriesEndVerdict

type SeriesEndVerdict struct {
	State string
	// Source is who decided: "manual", "schedule" (an announced episode),
	// "tmdb"/"tvdb" or "tvmaze".
	Source string
	// Disagreement is true when the provider and TVmaze give opposite answers
	// (one says over, the other running): the page says so.
	Disagreement bool
}

SeriesEndVerdict is the combined answer for one series.

type SeriesEpisodeIndex

type SeriesEpisodeIndex struct {
	// contains filtered or unexported fields
}

SeriesEpisodeIndex holds the episode rows of every series, read with one query per table, so a view of the whole library does not query each series on its own. Episodes assembles the same list as EpisodesForSeries.

func (*SeriesEpisodeIndex) Episodes

func (index *SeriesEpisodeIndex) Episodes(seriesName string, extraIgnored []int64) []EpisodeView

Episodes returns every episode of a series, as EpisodesForSeries does.

type SeriesGap

type SeriesGap struct {
	Series  string `json:"series"`
	Season  int64  `json:"season"`
	Episode int64  `json:"episode"`
}

SeriesGap is one gap in a series: `(series, season, episode)`.

type SeriesPathInput

type SeriesPathInput struct {
	ArchivePath *string `json:"archive_path"`
	Timeframe   *int64  `json:"timeframe"`
}

SeriesPathInput is the input of `set_series_path`.

type SeriesSummary

type SeriesSummary struct {
	Name           string
	Episodes       int64
	Downloaded     int64
	LastDownloaded *string
}

SeriesSummary implements the `SeriesSummary` tuple: `(name, total episodes, downloaded episodes, last download)`.

type SeriesUpdateInput

type SeriesUpdateInput struct {
	// Name renames the series in the library. Episodes and their history stay
	// linked; the archive folder is not moved.
	Name             *string   `json:"name"`
	Seasons          *string   `json:"seasons"`
	Quality          *string   `json:"quality"`
	Audio            *string   `json:"audio"`
	AudioChannels    *string   `json:"audio_channels"`
	Language         *string   `json:"language"`
	Subtitle         *string   `json:"subtitle"`
	Exclude          *string   `json:"exclude"`
	ArchivePath      *string   `json:"archive_path"`
	TmdbID           *string   `json:"tmdb_id"`
	TvdbID           *string   `json:"tvdb_id"`
	Aliases          *[]string `json:"aliases"`
	Enabled          *bool     `json:"enabled"`
	SeasonSubfolders *bool     `json:"season_subfolders"`
	DisableUpgrades  *bool     `json:"disable_upgrades"`
	Anime            *bool     `json:"anime"`
	Timeframe        *int64    `json:"timeframe"`
	// StatusOverride is «Serie terminata?»: "" or "auto" (the sources
	// decide), "ended" or "continuing".
	StatusOverride *string `json:"status_override"`
	// QualityProfileID, when above 0, copies that profile's quality, audio,
	// language, subtitles and upgrade switch into the series and adds its
	// exclusions to the series' own (the profile is a template).
	QualityProfileID *int `json:"quality_profile_id"`
}

SeriesUpdateInput is the input of `POST /api/series/{name}`. Every field is optional: only the ones present are changed, so a client never has to send (and possibly lose) fields it does not know about.

type ServiceActionInput

type ServiceActionInput struct {
	Action *string `json:"action"`
}

type SettingInput

type SettingInput struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

SettingInput is the input of `save_setting`.

type SettingOrigin

type SettingOrigin string

SettingOrigin is who wrote a setting.

const (
	// OriginAuto is a value the guided tuning wrote.
	OriginAuto SettingOrigin = "auto"
	// OriginManual is a value the user wrote (page or JSON API).
	OriginManual SettingOrigin = "manual"
)

type SettingsPatch

type SettingsPatch struct {
	Values map[string]any
}

SettingsPatch mirrors `SettingsPatch`, whose only field is the flattened inline field.

func (*SettingsPatch) UnmarshalJSON

func (s *SettingsPatch) UnmarshalJSON(data []byte) error

UnmarshalJSON captures every key of the flattened settings object. A body whose only key is a "values" object is unwrapped: older UI forms sent {"values": {...}}, which would otherwise save nothing and still answer ok.

type SimklClient

type SimklClient struct {
	// contains filtered or unexported fields
}

SimklClient is the Go implementation of gextto's Simkl integration client.

func (*SimklClient) Authenticated

func (c *SimklClient) Authenticated() bool

Authenticated reports whether a Simkl access token is set.

func (*SimklClient) Calendar

func (c *SimklClient) Calendar(ctx context.Context) (any, error)

Calendar fetches the Simkl calendar data.

func (*SimklClient) Configured

func (c *SimklClient) Configured() bool

Configured reports whether a Simkl client id is set.

func (*SimklClient) FromSettings

func (c *SimklClient) FromSettings(settings map[string]string) *SimklClient

FromSettings builds a SimklClient from the persisted settings map.

func (*SimklClient) MarkWatched

func (c *SimklClient) MarkWatched(ctx context.Context, payload any) (any, error)

MarkWatched posts history entries to Simkl.

func (*SimklClient) PinPoll

func (c *SimklClient) PinPoll(ctx context.Context, code string) (any, error)

PinPoll polls the Simkl PIN endpoint for the given code.

func (*SimklClient) PinStart

func (c *SimklClient) PinStart(ctx context.Context) (any, error)

PinStart requests a Simkl PIN code for device authentication.

func (*SimklClient) Watchlist

func (c *SimklClient) Watchlist(ctx context.Context) (any, error)

Watchlist fetches all Simkl list items.

type SourceAttempt

type SourceAttempt struct {
	Kind     string
	Provider string
	OK       bool
	Results  int
	Rows     int
	Error    string
}

SourceAttempt is one read of a source. Rows is how many rows the page carried and Results how many releases Gextto kept from them: a page with rows and no result is a listing whose markup no longer matches the parser, and the feed panel tells it apart from a listing that is simply empty.

type SourceFilter

type SourceFilter struct {
	Source   string   `json:"source"`
	Keywords []string `json:"keywords"`
	Enabled  bool     `json:"enabled"`
}

SourceFilter is a per-source content filter: when a release's `source` contains `source` (case-insensitive), any of `keywords` found in the title blocks the release. Lets the user silence one feed/indexer/engine without disabling it entirely.

func ParseSourceFilters

func ParseSourceFilters(raw string) []SourceFilter

ParseSourceFilters parses the `source_filters` setting (a JSON array); bad input yields none.

func (*SourceFilter) UnmarshalJSON

func (f *SourceFilter) UnmarshalJSON(data []byte) error

UnmarshalJSON applies the JSON default: `enabled` defaults to true when the key is absent. The plain Go zero value keeps it false, matching `SourceFilter::default()`.

type SourceFiltersInput

type SourceFiltersInput struct {
	Filters []SourceFilter `json:"filters"`
}

SourceFiltersInput is the input of `save_source_filters`.

type SourceQuery

type SourceQuery struct {
	Q *string `json:"q"`
}

type SpeedLimitsInput

type SpeedLimitsInput struct {
	DownloadKib int64 `json:"download_kib"`
	UploadKib   int64 `json:"upload_kib"`
}

type StallWatch

type StallWatch struct {
	// contains filtered or unexported fields
}

StallWatch tracks one download's progress timer (implementation of `StallWatch`).

type StorageMoveRetry

type StorageMoveRetry struct {
	// contains filtered or unexported fields
}

StorageMoveRetry is one pending/ongoing asynchronous storage move (implementation of `StorageMoveRetry`).

type StoragePath

type StoragePath struct {
	Path string `json:"path"`
}

StoragePath is the input of `move_torrent_storage`.

type StoredTorrent

type StoredTorrent struct {
	Hash          string  `json:"hash"`
	Name          string  `json:"name"`
	Tag           string  `json:"tag"`
	Source        string  `json:"source"`
	Progress      float64 `json:"progress"`
	Paused        bool    `json:"paused"`
	TotalSize     int64   `json:"total_size"`
	Downloaded    int64   `json:"downloaded"`
	Status        string  `json:"status"`
	UpdatedAt     string  `json:"updated_at"`
	Kind          string  `json:"kind"`
	SeriesName    string  `json:"series_name"`
	Season        int64   `json:"season"`
	Episode       int64   `json:"episode"`
	Year          int64   `json:"year"`
	QualityScore  int64   `json:"quality_score"`
	CompletedAt   string  `json:"completed_at"`
	ProcessedPath string  `json:"processed_path"`
	Error         string  `json:"error"`
	Reason        string  `json:"reason"`
}

StoredTorrent is one row of `torrent_meta` for the UI/API.

type StreamInfo

type StreamInfo struct {
	Index     int     `json:"index"`
	Type      string  `json:"type"`
	Codec     string  `json:"codec"`
	StartTime float64 `json:"start_time,omitempty"`
	HasStart  bool    `json:"-"`
	// Language is the stream's language tag as written (lower case).
	Language string `json:"language,omitempty"`
	// Disposition lists the flags set on the stream (default, forced,
	// hearing_impaired, …), sorted, so a remux can be proven not to have
	// switched a subtitle or an audio track on or off.
	Disposition []string `json:"disposition,omitempty"`
}

StreamInfo is one stream of the container, in file order. The cleanup needs the full list to prove that nothing but the chosen audio tracks changed.

type SuperSeedingInput

type SuperSeedingInput struct {
	Enabled bool `json:"enabled"`
}

type SystemFacts

type SystemFacts struct {
	MemTotal     uint64
	MemAvailable uint64
	NumCPU       int

	Download VolumeFacts
	Archive  VolumeFacts

	// DownloadNetwork/ArchiveNetwork mark a network filesystem (NFS/SMB).
	DownloadNetwork bool
	ArchiveNetwork  bool
	// SameDevice is true when the download folder and the library share a
	// filesystem, so hardlinks are possible.
	SameDevice bool

	// RamdiskDir is the RAM disk the tuning would use, empty when none is
	// available.
	RamdiskDir string
}

SystemFacts is everything the tuning reads from the machine.

func ProbeSystem

func ProbeSystem(cfg *Config) SystemFacts

ProbeSystem reads the machine facts used to propose a tuning. It never fails: an unavailable path is reported as not existing, and a missing reader simply leaves the field at zero.

type TagDirRule

type TagDirRule struct {
	Tag      string `json:"tag"`
	TempDir  string `json:"temp_dir"`
	FinalDir string `json:"final_dir"`
}

TagDirRule is one tag directory rule.

type TempLimitsInput

type TempLimitsInput struct {
	DownloadKib int64 `json:"download_kib"`
	UploadKib   int64 `json:"upload_kib"`
	Minutes     int64 `json:"minutes"`
	Clear       bool  `json:"clear"`
	// Auto, when set, turns the "auto speed" override on (true) or off (false):
	// the bandwidth is handed to the guided tuning with no cap, like being inside
	// an "Auto" window of the schedule. It is the temporary override's other mode.
	Auto *bool `json:"auto,omitempty"`
}

TempLimitsInput is the body of POST /api/torrents/temp-limits: a limit with its expiry, the request that keeps it until removed, or the "auto speed" switch.

type TestNotificationInput

type TestNotificationInput struct {
	Message *string `json:"message"`
}

TestNotificationInput is the input of `test_notification`.

type TmdbAddInput

type TmdbAddInput struct {
	Kind          string `json:"kind"`
	Name          string `json:"name"`
	Year          string `json:"year"`
	TmdbId        string `json:"tmdb_id"`
	TvdbId        string `json:"tvdb_id"`
	Quality       string `json:"quality"`
	Audio         string `json:"audio"`
	AudioChannels string `json:"audio_channels"`
	Language      string `json:"language"`
	Seasons       string `json:"seasons"`
	ArchivePath   string `json:"archive_path"`
	Exclude       string `json:"exclude"`
	Subtitle      string `json:"subtitle"`
	Aliases       string `json:"aliases"`
	// CreateFolder makes the series' archive folder (ArchivePath, or
	// <archive_root>/<name> when empty) before adding the series.
	CreateFolder bool `json:"create_folder"`
	// SeasonSubfolders archives episodes in a per-season subfolder.
	SeasonSubfolders bool `json:"season_subfolders"`
	// DisableUpgrades is «Permetti upgrade: No»: an archived file is never
	// replaced.
	DisableUpgrades bool `json:"disable_upgrades"`
	// QualityProfileID, when set, gives the title the quality, audio,
	// language, subtitles, exclusions and «Permetti upgrade» of that profile;
	// Exclude is then added to the profile's exclusions.
	QualityProfileID int `json:"quality_profile_id"`
}

TmdbAddInput is the input of `tmdb_add`.

type TmdbCastEntry

type TmdbCastEntry struct {
	ID   int64
	Name string
}

TmdbCastEntry is one `(person_id, name)` pair returned by SeriesCast, standing in for the tuple `Vec<(i64, String)>`.

type TmdbClient

type TmdbClient struct {
	// contains filtered or unexported fields
}

TmdbClient is the Go implementation of the `TmdbClient`. The cache mirrors the `Arc<Mutex<HashMap<String, Option<String>>>>`: a present key with a nil value is a cached `None`.

func NewTmdbClient

func NewTmdbClient(key *string) *TmdbClient

NewTmdbClient mirrors `TmdbClient::new` (Italian default language).

func NewTmdbClientWithLanguage

func NewTmdbClientWithLanguage(key *string, language string) *TmdbClient

NewTmdbClientWithLanguage mirrors `TmdbClient::with_language`.

func (*TmdbClient) Category

func (t *TmdbClient) Category(ctx context.Context, kind, category string) ([]TmdbItem, error)

Category mirrors `category`: curated TMDB categories used by the discovery view. TV has no exact counterpart for the two movie-only categories, so the closest official TV endpoints are used.

func (*TmdbClient) Clone

func (t *TmdbClient) Clone() *TmdbClient

Clone mirrors the derived `Clone` impl: the cache (and its lock) is shared, just like the `Arc<Mutex<...>>`.

func (*TmdbClient) Configured

func (t *TmdbClient) Configured() bool

Configured reports whether a non-blank TMDB API key is set.

func (*TmdbClient) EpisodeTitle

func (t *TmdbClient) EpisodeTitle(ctx context.Context, tmdbID string, season, episode int64) (*string, error)

EpisodeTitle mirrors `episode_title`.

func (*TmdbClient) FindSeriesByTvdbID

func (t *TmdbClient) FindSeriesByTvdbID(ctx context.Context, tvdbID int64) (*TmdbItem, error)

FindSeriesByTvdbID resolves a TVDB series id to the TMDB series (the /find endpoint), or nil when TMDB does not know it.

func (*TmdbClient) MovieAlternativeTitles

func (t *TmdbClient) MovieAlternativeTitles(ctx context.Context, tmdbID string) ([]string, error)

MovieAlternativeTitles returns the alternative titles TMDB knows for a movie: localized titles and working titles. They let a film monitored under one title be found under another (the international one, for example), which is what indexers put in the release name.

func (*TmdbClient) MovieCredits

func (t *TmdbClient) MovieCredits(ctx context.Context, tmdbID string) ([]CastMember, error)

MovieCredits mirrors `movie_credits`: top 12 cast members ordered by billing.

func (*TmdbClient) MovieDetails

func (t *TmdbClient) MovieDetails(ctx context.Context, tmdbID string) (*TmdbMovieDetails, error)

MovieDetails mirrors `movie_details`.

func (*TmdbClient) MovieReleaseDate

func (t *TmdbClient) MovieReleaseDate(ctx context.Context, tmdbID, country string) (date, kind string, ok bool, err error)

MovieReleaseDate returns the release date of a movie in country (an ISO 3166-1 code such as "IT") and its kind: "digital", "physical" or "theatrical", preferring the first that exists. Movies reach a country months or years after the original release, so this is the date that matters for a local audience. ok is false when TMDB has no date for country.

func (*TmdbClient) MovieTranslations

func (t *TmdbClient) MovieTranslations(ctx context.Context, tmdbID string) (map[string]string, error)

MovieTranslations returns the localized title TMDB has for a movie, by language code (ISO 639-1: "it", "en", …). The indexer search uses the title in the language chosen for the film and the English one; the other entries here are used by the match and the archive search.

func (*TmdbClient) NextEpisode

func (t *TmdbClient) NextEpisode(ctx context.Context, tmdbID string) (*TmdbEpisode, error)

NextEpisode mirrors `next_episode`.

func (*TmdbClient) Popular

func (t *TmdbClient) Popular(ctx context.Context, kind string) ([]TmdbItem, error)

Popular mirrors `popular`.

func (*TmdbClient) PosterForSeries

func (t *TmdbClient) PosterForSeries(ctx context.Context, name string) (*string, error)

PosterForSeries mirrors `poster_for_series`.

func (*TmdbClient) ResolveSeriesID

func (t *TmdbClient) ResolveSeriesID(ctx context.Context, name string) (*string, error)

ResolveSeriesID mirrors `resolve_series_id`.

func (*TmdbClient) SearchMovie

func (t *TmdbClient) SearchMovie(ctx context.Context, name string, year *int64) (*TmdbItem, error)

SearchMovie mirrors `search_movie`.

func (*TmdbClient) SearchMovies

func (t *TmdbClient) SearchMovies(ctx context.Context, name string) ([]TmdbItem, error)

SearchMovies mirrors `search_movies`.

func (*TmdbClient) SearchSeries

func (t *TmdbClient) SearchSeries(ctx context.Context, name string) ([]TmdbItem, error)

SearchSeries mirrors `search_series`.

func (*TmdbClient) SeasonCounts

func (t *TmdbClient) SeasonCounts(ctx context.Context, tmdbID string) (map[int64]int64, error)

SeasonCounts mirrors `season_counts`.

func (*TmdbClient) SeasonEpisodes

func (t *TmdbClient) SeasonEpisodes(ctx context.Context, tmdbID string, season int64) ([]TmdbEpisode, error)

SeasonEpisodes mirrors `season_episodes`: episodes and air dates for one season. Called only during an explicit metadata refresh; the caller persists them in the database.

func (*TmdbClient) SeriesCast

func (t *TmdbClient) SeriesCast(ctx context.Context, tmdbID string) ([]TmdbCastEntry, error)

SeriesCast mirrors `series_cast`: main cast (up to 8 members) as `(tmdb_person_id, name)` pairs.

func (*TmdbClient) SeriesInfo

func (t *TmdbClient) SeriesInfo(ctx context.Context, name string, tmdbID *string) (map[string]any, error)

SeriesInfo mirrors `series_info`: extended TV metadata for the series detail header. It uses the stored numeric TMDB id when available, otherwise it resolves the series by name.

func (*TmdbClient) Trending

func (t *TmdbClient) Trending(ctx context.Context, kind, window string) ([]TmdbItem, error)

Trending mirrors `trending`.

type TmdbEpisode

type TmdbEpisode struct {
	ID            *int64  `json:"id"`
	Name          *string `json:"name"`
	SeasonNumber  *int64  `json:"season_number"`
	EpisodeNumber *int64  `json:"episode_number"`
	AirDate       *string `json:"air_date"`
}

TmdbEpisode mirrors the `TmdbEpisode`.

type TmdbItem

type TmdbItem struct {
	ID           int64    `json:"id"`
	Name         *string  `json:"name"`
	Title        *string  `json:"title"`
	Overview     *string  `json:"overview"`
	PosterPath   *string  `json:"poster_path"`
	FirstAirDate *string  `json:"first_air_date"`
	ReleaseDate  *string  `json:"release_date"`
	VoteAverage  *float64 `json:"vote_average"`
	// InLibrary marks a discovery/search result already present in the local
	// library so the UI can show a "Già in lista" badge instead of offering a
	// duplicate insert.
	InLibrary bool `json:"in_library,omitempty"`
}

TmdbItem mirrors the `TmdbItem`.

type TmdbMovieDetails

type TmdbMovieDetails struct {
	ID            int64   `json:"id"`
	Title         *string `json:"title"`
	OriginalTitle *string `json:"original_title"`
	Overview      *string `json:"overview"`
	PosterPath    *string `json:"poster_path"`
	ReleaseDate   *string `json:"release_date"`
}

TmdbMovieDetails mirrors the `TmdbMovieDetails`: editorial movie data that can be persisted, separate from download settings.

type TmdbQuery

type TmdbQuery struct {
	Query string `json:"query"`
	Kind  string `json:"kind"`
}

TmdbQuery is the input of `tmdb_search`.

type TorrentBackend

type TorrentBackend interface {
	Name() string
	Capabilities() map[string]bool
}

TorrentBackend is the minimal identity contract (name + capabilities). The full operational contract is TorrentEngine.

func ActiveTorrentBackend

func ActiveTorrentBackend(s *AppState) TorrentBackend

ActiveTorrentBackend returns the backend currently driving the daemon.

type TorrentEngine

type TorrentEngine interface {
	TorrentSession

	Name() string
	Capabilities() map[string]bool

	Stats() map[string]any
	// AdjustQueue enforces Gextto's active-download slots on the backend. The
	// engines implement the same policy with pause/start.
	AdjustQueue(cfg *Config, effectiveDownloadKib int64)

	Add(magnet string, cfg *Config) (bool, error)
	AddWithPath(magnet string, cfg *Config, preferredPath *string) (bool, error)
	AddWithOptions(magnet string, cfg *Config, preferredPath *string, options AddOptions) (bool, error)
	AddTorrentFile(torrentPath, savePath string) (*string, error)
	AddTorrentFileEx(torrentPath, savePath string, options AddOptions) (*string, error)
	AddTorrentFileWithOptions(torrentPath string, cfg *Config, preferredPath *string, options AddOptions) (*string, error)
	AddFileWithPath(torrentPath string, cfg *Config, preferredPath *string) (bool, error)

	Files(hash string) ([]models.FileView, bool, error)
	Peers(hash string) ([]models.PeerView, bool, error)
	Trackers(hash string) ([]models.TrackerView, bool, error)
	SetFilePriorities(hash string, priorities []int32) (bool, error)
	SetTrackers(hash string, trackers []TrackerEntry) (bool, error)
	WebSeeds(hash, urls string, remove bool) (bool, error)
	// SetLimits changes the per-torrent rates and seed limits. A nil argument
	// keeps the current value: an update that touches only the seed days must
	// not reset the ratio (and a rate the caller does not mention must not
	// become "unlimited"). -1 means "use the global value", 0 "no limit".
	SetLimits(hash string, downloadLimit, uploadLimit *int64, seedRatio *float64, seedDays *int64) (bool, error)
	SetGlobalSpeedLimits(downloadKib, uploadKib int64) (bool, error)
	SetMaxConnections(hash string, value int) (bool, error)
	SetMaxUploads(hash string, value int) (bool, error)
	SetPin(hash string, pinned bool) (bool, error)
	SetSequential(enabled bool) (bool, error)
	// SetFirstLastDefault turns on the first/last-piece priority for every
	// torrent added afterwards (setting `libtorrent_first_last`), on top of the
	// per-torrent AddOptions.FirstLast.
	SetFirstLastDefault(enabled bool)
	AssociateStorage(hash, destination string) (bool, error)
	TorrentFilePath(hash string) (string, bool)
}

TorrentEngine is the full surface shared by the HTTP API and the acquisition path. Backends that cannot implement an operation must return an explicit error (ErrCapabilityUnavailable) instead of pretending success.

type TorrentEngineIdentity

type TorrentEngineIdentity interface {
	// EngineVersion returns the product label (a brand name, never translated,
	// e.g. "gx-core", "qBittorrent-nox") and the running version (e.g.
	// "1.1.193", "v5.1.1"). An empty version means "not available" and hides
	// the suffix.
	EngineVersion() (label, version string)
}

TorrentEngineIdentity is optionally implemented by backends whose underlying software has a version worth naming in the UI: "gx-core" for the gx-torrent daemon, "qBittorrent-nox" for the external engine. It is separate from TorrentEngine so a backend that cannot answer does not have to fake one: the header then shows only Gextto's own version.

type TorrentHashInput

type TorrentHashInput struct {
	Hash string `json:"hash"`
}

TorrentHashInput is the input of the hash-only torrent actions.

type TorrentLimits

type TorrentLimits struct {
	// Nil leaves the current value alone; -1 = the global value, 0 = no limit.
	DownloadLimit *int64   `json:"download_limit"`
	UploadLimit   *int64   `json:"upload_limit"`
	SeedRatio     *float64 `json:"seed_ratio"`
	SeedDays      *int64   `json:"seed_days"`
	// Per-torrent connection ceilings (nil = leave unchanged, 0 = unlimited).
	MaxConnections *int64 `json:"max_connections"`
	MaxUploads     *int64 `json:"max_uploads"`
}

TorrentLimits is the input of `set_torrent_limits`.

type TorrentLimitsInput

type TorrentLimitsInput struct {
	Hash      string   `json:"hash"`
	DlKbps    int64    `json:"dl_kbps"`
	UlKbps    int64    `json:"ul_kbps"`
	SeedRatio *float64 `json:"seed_ratio"`
	SeedDays  *int64   `json:"seed_days"`
}

TorrentLimitsInput is the input of `set_torrent_limits_legacy`.

type TorrentMoveState

type TorrentMoveState struct {
	Retry         *StorageMoveRetry
	PostSeedGuard bool
}

TorrentMoveState is the persisted storage-move state of one torrent.

type TorrentPieceAvailability

type TorrentPieceAvailability struct {
	Cells   []int `json:"cells"`
	Missing int   `json:"missing"`
	Most    int   `json:"most"`
}

TorrentPieceAvailability is how many connected peers hold the pieces still needed, in fixed stretches of the torrent: each cell is the fewest holders of a needed piece in that stretch, -1 when the stretch needs nothing. Missing is how many needed pieces no connected peer has; Most the highest count seen.

type TorrentPieceInspector

type TorrentPieceInspector interface {
	PieceRuns(hash string) ([]TorrentPieceRun, bool, error)
}

TorrentPieceInspector is implemented by backends that can expose per-piece diagnostics. Backends without it must answer with a capability error, never with fabricated data.

type TorrentPieceMapper

type TorrentPieceMapper interface {
	PieceMap(hash string) ([]TorrentPieceRun, *TorrentPieceAvailability, bool, error)
}

TorrentPieceMapper is implemented by backends that report the piece map and the availability in one call (gx-torrent). Availability is nil when the engine does not know it.

type TorrentPieceRun

type TorrentPieceRun struct {
	Begin int    `json:"begin"`
	End   int    `json:"end"`
	State string `json:"state"`
}

TorrentPieceRun is a compact run of consecutive pieces that share a state. Exposed by GET /api/torrents/{hash}/pieces for backends that support it.

type TorrentSession

type TorrentSession interface {
	List() []models.TorrentView
	PollEvents() []models.TorrentEvent

	Pause(hash string) (bool, error)
	Resume(hash string) (bool, error)
	Restart(hash string) (bool, error)
	Remove(hash string, deleteFiles bool) (bool, error)
	ForceRecheck(hash string) (bool, error)
	Reannounce(hash string) (bool, error)
	MoveStorage(hash, destination string) (bool, error)

	MarkStalled(hash string) (bool, error)
	ClearStalled(hash string)
	RamdiskUncommittedBytes(ramdisk string, excludeHash string) uint64
}

TorrentSession is the narrow, engine-agnostic surface the automation layer (queue, stalled/retry, storage moves, seed policy) needs. It is intentionally small so a backend only has to implement what Gextto actually automates.

type TorrentSessionHealth

type TorrentSessionHealth interface {
	SessionHealthy() bool
}

TorrentSessionHealth is optionally implemented by backends whose List result can be stale or empty while their external daemon is unavailable. Callers that perform destructive reconciliation must skip it until such a backend has a confirmed live snapshot.

type TorrentSkippedFiles

type TorrentSkippedFiles interface {
	SkippedVideoFiles(hash string) (names []string, supported bool, err error)
}

TorrentSkippedFiles is optionally implemented by a backend that can tell which video files it deliberately did not download (qBittorrent's excluded file names or a file left at priority 0). Gextto uses it when a completed torrent has no importable video: the error names the skipped files instead of leaving a generic "file not found" in the queue.

type TorrentSnapshotter

type TorrentSnapshotter interface {
	Snapshot() []models.TorrentView
}

TorrentSnapshotter is implemented by the backends that can answer from their last snapshot without polling the daemon.

type TorrentTagInput

type TorrentTagInput struct {
	Hash string `json:"hash"`
	Tag  string `json:"tag"`
}

TorrentTagInput is the input of `set_torrent_tag`.

type TorrentTimes

type TorrentTimes struct {
	CreatedAt   string
	CompletedAt *string
}

TorrentTimes is the `(created_at, completed_at)` pair of a torrent.

type TrackerEntry

type TrackerEntry struct {
	Tier int32
	URL  string
}

TrackerEntry is one (tier, URL) pair passed to SetTrackers.

type TrackerEntryInput

type TrackerEntryInput struct {
	Url  string `json:"url"`
	Tier int32  `json:"tier"`
}

type TrackersInput

type TrackersInput struct {
	Trackers []TrackerEntryInput `json:"trackers"`
}

type TransferSettings

type TransferSettings struct {
	PortMin          uint16  `json:"port_min"`
	PortMax          uint16  `json:"port_max"`
	DownloadLimitKib int64   `json:"download_limit_kib"`
	UploadLimitKib   int64   `json:"upload_limit_kib"`
	SeedRatio        float64 `json:"seed_ratio"`
	SeedTimeMinutes  int64   `json:"seed_time_minutes"`
	SeedTimeDays     int64   `json:"seed_time_days"`
	// SeedIdleMinutes stops a seed that uploaded nothing for that long while
	// seeding (0 = off); see seed_rules.go.
	SeedIdleMinutes int64 `json:"seed_idle_minutes"`
	ActiveDownloads int64 `json:"active_downloads"`
	ActiveSeeds     int64 `json:"active_seeds"`
	ActiveLimit     int64 `json:"active_limit"`
	Dht             bool  `json:"dht"`
	Pex             bool  `json:"pex"`
	Lsd             bool  `json:"lsd"`
	Upnp            bool  `json:"upnp"`
	Natpmp          bool  `json:"natpmp"`
	DynamicQueue    bool  `json:"dynamic_queue"`
	DynamicQueueMin int64 `json:"dynamic_queue_min"`
	DynamicQueueMax int64 `json:"dynamic_queue_max"`
	// Quando è true, i torrent che non trasferiscono payload non occupano uno
	// slot attivo: evita che gli swarm senza peer blocchino i download sani.
	DontCountSlowTorrents bool `json:"dont_count_slow_torrents"`
	AutoRemoveCompleted   bool `json:"auto_remove_completed"`
	// Extended session settings.
	ConnectionsLimit int64 `json:"connections_limit"`
	CacheSize        int64 `json:"cache_size"`
	CacheExpiry      int64 `json:"cache_expiry"`
	Utp              bool  `json:"utp"`
	Holepunch        bool  `json:"holepunch"`
	// LimitLanPeers applies the speed limits to the peers on the local network
	// too (gx-torrent only); off, they transfer at full speed.
	LimitLanPeers bool `json:"limit_lan_peers"`
	// UploadTradingShare, ClientFilter(List), TrackerListURL and GeoIPFile
	// are gx-torrent peer policies passed as start arguments.
	UploadTradingShare int64  `json:"upload_trading_share"`
	ClientFilter       bool   `json:"client_filter"`
	ClientFilterList   string `json:"client_filter_list"`
	TrackerList        bool   `json:"tracker_list"`
	TrackerListURL     string `json:"tracker_list_url"`
	PeerCountry        bool   `json:"peer_country"`
	GeoIPFile          string `json:"geoip_file"`
	ApplyIpFilter      bool   `json:"apply_ip_filter"`
	Encryption         int64  `json:"encryption"`
	IpFilterPath       string `json:"ip_filter_path"`
	ListenInterfaces   string `json:"listen_interfaces"`
	// Interfaccia forzata per il traffico in uscita (killswitch VPN). Quando è
	// impostata, libtorrent annuncia e si connette solo da questa scheda.
	OutgoingInterface string `json:"outgoing_interface"`
	DhtBootstrapNodes string `json:"dht_bootstrap_nodes"`
}

TransferSettings mirrors the libtorrent session configuration.

func DefaultTransferSettings

func DefaultTransferSettings() TransferSettings

DefaultTransferSettings implements `impl Default for TransferSettings`.

func (*TransferSettings) UnmarshalJSON

func (s *TransferSettings) UnmarshalJSON(data []byte) error

UnmarshalJSON overlays the present JSON keys on top of the defaults, so an omitted field keeps its documented default instead of the Go zero value.

type Translation

type Translation struct {
	Lang  string `json:"lang"`
	Key   string `json:"key"`
	Value string `json:"value"`
}

Translation is one persisted key/value pair for a language.

type TrashDeleteInput

type TrashDeleteInput struct {
	Names []string `json:"names"`
	All   bool     `json:"all"`
}

type TuningProposal

type TuningProposal struct {
	Key      string
	Current  string
	Proposed string
	// WhyTemplate is the Italian reason with %s/%d placeholders; WhyArgs are its
	// arguments (already human-readable strings where it matters).
	WhyTemplate string
	WhyArgs     []any
}

TuningProposal is one suggested change, with the reason already parameterised (WhyTemplate/WhyArgs) so the interface can translate it.

func ProposeTuning

func ProposeTuning(facts SystemFacts, cfg *Config, manual map[string]bool) []TuningProposal

ProposeTuning builds the proposal for the given machine facts. `manual` marks the settings the user changed by hand: they are never proposed, so re-optimizing cannot overwrite a deliberate choice.

type TvdbClient

type TvdbClient struct {
	// contains filtered or unexported fields
}

TvdbClient is the Go implementation of gextto's minimal TVDB v4 client: login, series search and extended data. The API key lives in the Gextto settings (`tvdb_api_key`); the login token is cached in memory for ~23 hours.

func New

func New(key *string) *TvdbClient

New builds a TVDB client for the given API key (nil disables it), defaulting to the Italian language like the `TvdbClient::new`.

func WithLanguage

func WithLanguage(key *string, language string) *TvdbClient

WithLanguage builds a TVDB client with an explicit Accept-Language; a blank language falls back to "ita".

func (*TvdbClient) Configured

func (c *TvdbClient) Configured() bool

Configured reports whether a non-blank TVDB API key is set.

func (*TvdbClient) EpisodeTitle

func (c *TvdbClient) EpisodeTitle(ctx context.Context, tvdbID string, season, episode int64) (*string, error)

EpisodeTitle returns the title of one episode (nil when unknown).

func (*TvdbClient) MovieDetails

func (c *TvdbClient) MovieDetails(ctx context.Context, id string) (any, error)

MovieDetails returns the editorial data of a selected TVDB movie. The payload stays raw JSON to tolerate the optional/variable fields of the v4 API.

func (*TvdbClient) NextEpisode

func (c *TvdbClient) NextEpisode(ctx context.Context, tvdbID string) (*TmdbEpisode, error)

NextEpisode returns the first regular episode airing today or later.

func (*TvdbClient) PosterForSeries

func (c *TvdbClient) PosterForSeries(ctx context.Context, name string) (*string, error)

PosterForSeries returns the poster of the first series found by name, as a full URL (TMDB returns a path; metadataImageURL handles both).

func (*TvdbClient) ResolveSeriesID

func (c *TvdbClient) ResolveSeriesID(ctx context.Context, name string) (*string, error)

ResolveSeriesID returns the TVDB id of the first series found by name.

func (*TvdbClient) SearchMovies

func (c *TvdbClient) SearchMovies(ctx context.Context, query string) ([]any, error)

SearchMovies searches TVDB movies, normalised into the same compact format used for series. It is only used by explicit movie metadata selection.

func (*TvdbClient) SearchSeries

func (c *TvdbClient) SearchSeries(ctx context.Context, query string) ([]any, error)

SearchSeries searches series by name. Returns compact results ready for the UI.

func (*TvdbClient) SeasonCounts

func (c *TvdbClient) SeasonCounts(ctx context.Context, tvdbID string) (map[int64]int64, error)

SeasonCounts returns the number of episodes of each season (season 0, the specials, included like TMDB does).

func (*TvdbClient) SeasonEpisodes

func (c *TvdbClient) SeasonEpisodes(ctx context.Context, tvdbID string, season int64) ([]TmdbEpisode, error)

SeasonEpisodes returns the episodes of one season with their air dates.

func (*TvdbClient) SeriesCharacters

func (c *TvdbClient) SeriesCharacters(ctx context.Context, id int64) ([]any, error)

SeriesCharacters returns the main characters/actors as `{name, tvdb_id}` (TVDB people id).

func (*TvdbClient) SeriesEpisodes

func (c *TvdbClient) SeriesEpisodes(ctx context.Context, tvdbID string) ([]TmdbEpisode, error)

SeriesEpisodes returns every episode of a series (aired order), with the titles in the configured language when TVDB has them, else the original.

func (*TvdbClient) SeriesExtended

func (c *TvdbClient) SeriesExtended(ctx context.Context, id int64) (any, error)

SeriesExtended returns extended series data (name, year, image, seasons summary, ...).

func (*TvdbClient) SeriesInfo

func (c *TvdbClient) SeriesInfo(ctx context.Context, name string, tvdbID *string) (map[string]any, error)

SeriesInfo returns the series details in the shape of the TMDB /tv record (name, overview, poster_path, status, dates, networks, genres, counts, last and next episode), plus "tvdb_id". There is no "id": it would be read as a TMDB id.

func (*TvdbClient) WithPin

func (c *TvdbClient) WithPin(pin string) *TvdbClient

WithPin sets the TVDB subscriber PIN sent at login (blank: none).

type TvdbQuery

type TvdbQuery struct {
	Query string `json:"query"`
}

type UpdateCommit

type UpdateCommit struct {
	Sha     string `json:"sha"`
	Date    string `json:"date"`
	Subject string `json:"subject"`
}

UpdateCommit is one changelog entry.

func (UpdateCommit) Day

func (c UpdateCommit) Day() string

Day is the commit date (YYYY-MM-DD).

func (UpdateCommit) Short

func (c UpdateCommit) Short() string

Short is the abbreviated commit hash shown in the UI.

func (UpdateCommit) URL

func (c UpdateCommit) URL() string

URL links the commit on GitHub.

type UpdateNotes

type UpdateNotes struct {
	FromVersion string         `json:"from_version"`
	FromCommit  string         `json:"from_commit"`
	Changes     []UpdateCommit `json:"changes"`
	At          time.Time      `json:"at"`
	// ToVersion is filled at display time: the running version.
	ToVersion string `json:"-"`
}

UpdateNotes is update-notes.json: written when an update is requested and shown once by the version that comes after it.

func PendingUpdateNotes

func PendingUpdateNotes(cfg *Config) (*UpdateNotes, bool)

PendingUpdateNotes returns the notes to show now: an update happened since they were written (the running commit is another one). Notes of an update that did not install are dropped once stale.

type UpdateOptions

type UpdateOptions struct {
	// Repo is the GitHub repository (`owner/name`). Defaults to DefaultRepo.
	Repo *string `json:"repo"`
	// Release is an explicit release tag, for example `v0.2.0`.
	Release *string `json:"release"`
	// Channel is the release channel (`continuous` or `stable`). Ignored when
	// Release is set.
	Channel *string `json:"channel"`
	// InstallDir is the installation directory. Defaults to the directory of the
	// running binary.
	InstallDir *string `json:"install_dir"`
	// Archive is a local archive to install instead of downloading one
	// (offline/testing).
	Archive *string `json:"archive"`
	// Restart restarts the service after a successful update (default: true).
	Restart bool `json:"restart"`
	// Force reinstalls even when the installed marker already matches the
	// release.
	Force bool `json:"force"`
}

UpdateOptions holds the options accepted by `gexttod --update`.

type UpdateStatus

type UpdateStatus struct {
	Version string `json:"version"`
	Commit  string `json:"commit"`
	BuiltAt string `json:"built_at"`
	Marker  string `json:"marker"`
	Channel string `json:"channel"`
	// Managed is true for an installation from a release archive (installer or
	// `gexttod --update`); a build from a source checkout updates with git.
	Managed bool `json:"managed"`
	// Updater is true when the root path unit that applies updates exists.
	Updater      bool   `json:"updater"`
	CheckEnabled bool   `json:"check_enabled"`
	CheckHours   int    `json:"check_hours"`
	CheckedAt    string `json:"checked_at,omitempty"`
	Error        string `json:"error,omitempty"`

	Available       bool           `json:"available"`
	LatestVersion   string         `json:"latest_version,omitempty"`
	LatestCommit    string         `json:"latest_commit,omitempty"`
	LatestBuiltAt   string         `json:"latest_built_at,omitempty"`
	LatestLabel     string         `json:"latest_label,omitempty"`
	Changes         []UpdateCommit `json:"changes,omitempty"`
	ChangesComplete bool           `json:"changes_complete"`

	// Requested is true while a request waits for the updater.
	Requested bool   `json:"requested"`
	LastLog   string `json:"last_log,omitempty"`
}

UpdateStatus is what /api/update and the maintenance panel show.

func (UpdateStatus) CanApply

func (u UpdateStatus) CanApply() bool

CanApply reports whether the "Update" button can work here.

type VolumeFacts

type VolumeFacts struct {
	Path   string
	Total  uint64
	Free   uint64
	Exists bool
}

VolumeFacts is one volume the probe inspected: its path, size and free space. Exists is false when the path is empty or not a directory.

type WatchedFolder

type WatchedFolder struct {
	// Path is the directory to scan.
	Path    string `json:"path"`
	Enabled bool   `json:"enabled"`
	// Recursive also scans subdirectories.
	Recursive bool `json:"recursive"`
	// DeleteAfter removes the file after a successful add (default true). When
	// false the worker keeps a processed-file memory so it is not added twice.
	DeleteAfter bool `json:"delete_after"`
}

WatchedFolder describes one directory monitored for torrent files.

func LoadWatchedFolders

func LoadWatchedFolders(settings map[string]string) []WatchedFolder

LoadWatchedFolders loads watched folders from the `watched_folders` settings key. A missing or unparseable value yields an empty list.

func (*WatchedFolder) UnmarshalJSON

func (w *WatchedFolder) UnmarshalJSON(data []byte) error

UnmarshalJSON applies the JSON defaults: `enabled` and `delete_after` default to true when the keys are absent. The plain Go zero value keeps them false, matching `WatchedFolder::default()`.

type WebSeedsInput

type WebSeedsInput struct {
	Urls   []string `json:"urls"`
	Remove bool     `json:"remove"`
}

type WeeklyPending

type WeeklyPending struct {
	PackDate   string
	Magnet     string
	TorrentURL string
}

WeeklyPending is one recorded weekly pack that has a link but was never sent.

type WorkDir

type WorkDir struct {
	// contains filtered or unexported fields
}

WorkDir is a temporary working directory removed on cleanup.

func NewWorkDir

func NewWorkDir() (*WorkDir, error)

NewWorkDir creates a fresh temporary working directory.

func (*WorkDir) Cleanup

func (w *WorkDir) Cleanup()

Cleanup removes the working directory and everything inside it.

func (*WorkDir) Path

func (w *WorkDir) Path() string

Path returns the working directory path.

Source Files

Directories

Path Synopsis
cmd
gexttod command
Command gexttod is the gextto daemon: a self-contained media acquisition and archiving service (Go implementation of gextto).
Command gexttod is the gextto daemon: a self-contained media acquisition and archiving service (Go implementation of gextto).
gx-torrent command
Command gx-torrent is a small BitTorrent daemon built on the gx-core engine (pure Go).
Command gx-torrent is a small BitTorrent daemon built on the gx-core engine (pure Go).
internal
amule
Package amule is Gextto's client for aMule's External Connections (EC) protocol, the binary TCP protocol amuled exposes to amulecmd, amuleweb and the remote GUI.
Package amule is Gextto's client for aMule's External Connections (EC) protocol, the binary TCP protocol amuled exposes to amulecmd, amuleweb and the remote GUI.
amule/amuletest
Package amuletest is a fake aMule core speaking the EC protocol, for tests that must not depend on amuled being installed.
Package amuletest is a fake aMule core speaking the EC protocol, for tests that must not depend on amuled being installed.
auth
Package auth holds the standalone daemon's access control: password hashing and the login sessions.
Package auth holds the standalone daemon's access control: password hashing and the login sessions.
autospeed
Package autospeed is the latency auto-speed controller (anti-bufferbloat), shared by the standalone gx-torrent daemon and by Gextto.
Package autospeed is the latency auto-speed controller (anti-bufferbloat), shared by the standalone gx-torrent daemon and by Gextto.
backoff
Package backoff implements the escalating provider backoff, based on Sonarr's EscalationBackOff.
Package backoff implements the escalating provider backoff, based on Sonarr's EscalationBackOff.
bwschedule
Package bwschedule is the weekly bandwidth scheduler shared by Gextto and the gx-torrent daemon: every weekday has its own window (start/end) and its own download/upload limits, and can be switched on or off by itself.
Package bwschedule is the weekly bandwidth scheduler shared by Gextto and the gx-torrent daemon: every weekday has its own window (start/end) and its own download/upload limits, and can be switched on or off by itself.
cache
Package cache is the persistent detail-page -> magnet cache (legacy SmartCache, corsaro_cache.json).
Package cache is the persistent detail-page -> magnet cache (legacy SmartCache, corsaro_cache.json).
constants
Package constants holds compile-time defaults shared across gextto.
Package constants holds compile-time defaults shared across gextto.
debugpprof
Package debugpprof is the opt-in profiling endpoint shared by gexttod and the gx-torrent daemon.
Package debugpprof is the opt-in profiling endpoint shared by gexttod and the gx-torrent daemon.
ed2k
Package ed2k parses and formats eD2k links (`ed2k://|file|...|/` and `ed2k://|server|...|/`).
Package ed2k parses and formats eD2k links (`ed2k://|file|...|/` and `ed2k://|server|...|/`).
emuleqt
Package emuleqt talks to an emule-qt core (emulecored) through its REST API (/api/v1, API key).
Package emuleqt talks to an emule-qt core (emulecored) through its REST API (/api/v1, API key).
emuleqt/emuleqttest
Package emuleqttest is a fake emule-qt core for tests: the REST routes Gextto uses, an API key, paged lists and searches that finish at once.
Package emuleqttest is a fake emule-qt core for tests: the REST routes Gextto uses, an API key, paged lists and searches that finish at once.
flaresolverr
Package flaresolverr is a minimal client for a FlareSolverr service (https://github.com/FlareSolverr/FlareSolverr): it solves pages that sit behind a Cloudflare challenge.
Package flaresolverr is a minimal client for a FlareSolverr service (https://github.com/FlareSolverr/FlareSolverr): it solves pages that sit behind a Cloudflare challenge.
freeleech
Package freeleech resolves the three states an indexer can report about the download quota: free, not free, and "not stated".
Package freeleech resolves the three states an indexer can report about the download quota: free, not free, and "not stated".
gxcore/internal/backoff
Package backoff implements retry timing for the engine: a BackOff policy, a Ticker that emits ticks at the policy's intervals, and a Retry helper.
Package backoff implements retry timing for the engine: a BackOff policy, a Ticker that emits ticks at the policy's intervals, and a Retry helper.
gxcore/internal/bandwidth
Package bandwidth provides a rate limiter whose rate can change while peers hold it.
Package bandwidth provides a rate limiter whose rate can change while peers hold it.
gxcore/internal/bencodecheck
Package bencodecheck screens bencoded bytes against the decoder used across the engine (zeebo/bencode), which allocates a string's declared length before reading it.
Package bencodecheck screens bencoded bytes against the decoder used across the engine (zeebo/bencode), which allocates a string's declared length before reading it.
gxcore/internal/bitfield
Package bitfield manipulates BEP 3 piece-availability bitfields: bit 0 is the most significant bit of byte 0.
Package bitfield manipulates BEP 3 piece-availability bitfields: bit 0 is the most significant bit of byte 0.
gxcore/internal/btconn
Package btconn dials and accepts raw BitTorrent connections: plain or MSE-encrypted TCP, plus the uTP path assembled by the session layer.
Package btconn dials and accepts raw BitTorrent connections: plain or MSE-encrypted TCP, plus the uTP path assembled by the session layer.
gxcore/internal/fast
Package fast implements the BEP 6 fast extension peer set.
Package fast implements the BEP 6 fast extension peer set.
gxcore/internal/logger
Package logger is the engine's logging facade.
Package logger is the engine's logging facade.
gxcore/internal/magnet
Package magnet parses and renders magnet links: v1 (BEP 5) and v2/BEP 52 topics, BEP 53 file selection and webseeds, BEP 46 DHT-resolved keys, tracker tiers and peer hints.
Package magnet parses and renders magnet links: v1 (BEP 5) and v2/BEP 52 topics, BEP 53 file selection and webseeds, BEP 46 DHT-resolved keys, tracker tiers and peer hints.
gxcore/internal/merkle
Package merkle implements the SHA-256 merkle trees used by BitTorrent v2 torrents (BEP 52).
Package merkle implements the SHA-256 merkle trees used by BitTorrent v2 torrents (BEP 52).
gxcore/internal/metainfo
Package metainfo reads and writes .torrent files: v1 (BEP 3), hybrids and v2 (BEP 52), plus the BEP 38 collection hints.
Package metainfo reads and writes .torrent files: v1 (BEP 3), hybrids and v2 (BEP 52), plus the BEP 38 collection hints.
gxcore/internal/mse
Package mse implements Message Stream Encryption for peer connections: Diffie-Hellman key exchange plus RC4 obfuscation that defeats passive traffic identification.
Package mse implements Message Stream Encryption for peer connections: Diffie-Hellman key exchange plus RC4 obfuscation that defeats passive traffic identification.
gxcore/internal/netx
Package netx centralizes the engine's outbound connections so that an outgoing interface (VPN killswitch) and a proxy apply to peers, trackers and web seeds alike.
Package netx centralizes the engine's outbound connections so that an outgoing interface (VPN killswitch) and a proxy apply to peers, trackers and web seeds alike.
gxcore/internal/peerpriority
Package peerpriority orders connection candidates per BEP 40: peers are ranked by a CRC32C of the address pair, masked so that close addresses (same /16, /24) spread across the hash space instead of clustering.
Package peerpriority orders connection candidates per BEP 40: peers are ranked by a CRC32C of the address pair, masked so that close addresses (same /16, /24) spread across the hash space instead of clustering.
gxcore/internal/resumer
Package resumer defines the persistence contract the torrent package uses to save and restore download progress across restarts.
Package resumer defines the persistence contract the torrent package uses to save and restore download progress across restarts.
gxcore/internal/resumer/boltdbresumer
Package boltdbresumer persists torrent resume records in BoltDB: one sub-bucket per torrent id, one key per field.
Package boltdbresumer persists torrent resume records in BoltDB: one sub-bucket per torrent id, one key per field.
gxcore/internal/storage
Package storage defines how the engine reads and writes torrent files: a Storage opens named files, a Provider hands out one Storage per torrent.
Package storage defines how the engine reads and writes torrent files: a Storage opens named files, a Provider hands out one Storage per torrent.
gxcore/internal/storage/filestorage
Package filestorage stores torrent files on disk: plain OS files with fdatasync durability, or shared memory mappings on Linux, under one root.
Package filestorage stores torrent files on disk: plain OS files with fdatasync durability, or shared memory mappings on Linux, under one root.
gxcore/internal/tracker
Package tracker provides support for announcing torrents to HTTP and UDP trackers.
Package tracker provides support for announcing torrents to HTTP and UDP trackers.
gxcore/internal/trackertest
Package trackertest serves minimal in-memory trackers for the engine's own tests: just enough HTTP (BEP 3) and UDP (BEP 15) announce protocol to run the tracker clients and end-to-end downloads, with no external tracker.
Package trackertest serves minimal in-memory trackers for the engine's own tests: just enough HTTP (BEP 3) and UDP (BEP 15) announce protocol to run the tracker clients and end-to-end downloads, with no external tracker.
gxcore/logging
Package logging is the gx-core engine's leveled logger.
Package logging is the gx-core engine's leveled logger.
gxcore/torrent
Package torrent implements a BitTorrent session: torrents, DHT, caches and the transports they share.
Package torrent implements a BitTorrent session: torrents, DHT, caches and the transports they share.
logging
Package logging provides the readable, rotating logger used across gextto.
Package logging provides the readable, rotating logger used across gextto.
messages
Package messages is the active-language helper for non-UI messages (notifications and the human-readable log summaries).
Package messages is the active-language helper for non-UI messages (notifications and the human-readable log summaries).
models
Package models defines the shared domain types of gextto.
Package models defines the shared domain types of gextto.
notify
Package notify delivers the gx-torrent daemon's notifications on the same channels Gextto offers — Telegram, a webhook (generic JSON or the Discord, Slack, Gotify, ntfy and Pushover formats) and e-mail over SMTP — and on the two further channels of indexarr's notification page: an Apprise API server and a custom script run on this machine.
Package notify delivers the gx-torrent daemon's notifications on the same channels Gextto offers — Telegram, a webhook (generic JSON or the Discord, Slack, Gotify, ntfy and Pushover formats) and e-mail over SMTP — and on the two further channels of indexarr's notification page: an Apprise API server and a custom script run on this machine.
qbittorrent
Package qbittorrent is a small, dependency-free client for the qBittorrent Web API (v2).
Package qbittorrent is a small, dependency-free client for the qBittorrent Web API (v2).
rarstore
Package rarstore extracts files from RAR archives: "store" mode (no compression, the form video releases split into volumes use) for RAR 4 and RAR 5, and the RAR 5 compression (unpack5.go), single and multi-volume ("name.part01.rar" or "name.rar", "name.r00", …), with the CRC checked.
Package rarstore extracts files from RAR archives: "store" mode (no compression, the form video releases split into volumes use) for RAR 4 and RAR 5, and the RAR 5 compression (unpack5.go), single and multi-volume ("name.part01.rar" or "name.rar", "name.r00", …), with the CRC checked.
rss
Package rss fetches and parses RSS/Atom/Torznab feeds into download items and applies include/exclude rules, so the standalone daemon can follow feeds (Jackett, Prowlarr, MIRCrew and any RSS listing) and add matching torrents.
Package rss fetches and parses RSS/Atom/Torznab feeds into download items and applies include/exclude rules, so the standalone daemon can follow feeds (Jackett, Prowlarr, MIRCrew and any RSS listing) and add matching torrents.
rules
Package rules implements the built-in, always-on release sanity rules.
Package rules implements the built-in, always-on release sanity rules.
settings
Package settings is a small persistent key/value store for gx-torrent's standalone mode: the operators' choices (language, folders, credentials) survive a restart.
Package settings is a small persistent key/value store for gx-torrent's standalone mode: the operators' choices (language, folders, credentials) survive a restart.
torznab
Package torznab is a small client for Torznab indexers (Jackett, Prowlarr and anything speaking the same API): it runs a search and returns the results as plain items, with no dependency on Gextto types so it can be reused by the standalone daemon and unit tested against a fake server.
Package torznab is a small client for Torznab indexers (Jackett, Prowlarr and anything speaking the same API): it runs a search and returns the results as plain items, with no dependency on Gextto types so it can be reused by the standalone daemon and unit tested against a fake server.
tui
Package tui implements the terminal interface for a running gextto daemon.
Package tui implements the terminal interface for a running gextto daemon.
tvmaze
Package tvmaze is the small client the standalone daemon uses to learn the real episode list of a series: TVmaze's public API needs no key and returns the seasons and episodes with their air dates.
Package tvmaze is the small client the standalone daemon uses to learn the real episode list of a series: TVmaze's public API needs no key and returns the seasons and episodes with their air dates.
updatecheck
Package updatecheck reads the release manifest (release.json) that CI publishes next to the archives and tells whether a newer build exists and which commits it brings.
Package updatecheck reads the release manifest (release.json) that CI publishes next to the archives and tells whether a newer build exists and which commits it brings.
utils
Package utils provides shared helpers based on gextto's utils module.
Package utils provides shared helpers based on gextto's utils module.
utp
Package utp isolates the uTP transport (BEP 29) behind Gextto's own API.
Package utp isolates the uTP transport (BEP 29) behind Gextto's own API.
utp/transport
Package transport is Gextto's own uTP (BEP 29) implementation.
Package transport is Gextto's own uTP (BEP 29) implementation.
webui/assets
Package assets bundles gx-torrent's web UI files into the binary: the page template, the token prompt page and the site icon.
Package assets bundles gx-torrent's web UI files into the binary: the page template, the token prompt page and the site icon.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL