scraper

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package scraper implements a Cardigann-compatible scraping engine that executes Prowlarr YAML indexer definitions to scrape tracker websites and return structured search results.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyFilters

func ApplyFilters(value string, filters []FilterDef, ctx *TemplateContext) string

ApplyFilters runs a sequence of filters on a value.

`ctx` is used to evaluate Go templates that appear in filter arguments (Cardigann YAML routinely embeds `{{ if ... }}` directives in re_replace replacement strings — see Nyaa.si's title_phase2 filter). Pass nil to skip template evaluation when no context is available (e.g. download-link extraction at result-build time).

func EvalTemplate

func EvalTemplate(tmplStr string, ctx *TemplateContext) (string, error)

EvalTemplate evaluates a Go template string with the given context.

`missingkey=zero` makes references to absent map keys render as the element type's zero value (empty string for map[string]string) rather than the literal "<no value>" Go's default produces. Cardigann YAML frequently chains fields (e.g. Nyaa's title_phase1 → title_phase2 → title) where intermediate fields legitimately have no value for some rows; without this option the unrendered "<no value>" string leaks into the final title and the consumer sees `<no value>` everywhere.

func EvalTemplateOr

func EvalTemplateOr(tmplStr string, ctx *TemplateContext, fallback string) string

EvalTemplateOr evaluates a template, returning the fallback on error.

func ExtractFieldHTML

func ExtractFieldHTML(row *goquery.Selection, field FieldBlock, ctx *TemplateContext) string

ExtractFieldHTML extracts a field value from an HTML selection using the FieldBlock definition.

func ExtractFieldJSON

func ExtractFieldJSON(jsonStr string, field FieldBlock, ctx *TemplateContext) string

ExtractFieldJSON extracts a field value from a JSON result using gjson paths.

func FindRowsHTML

func FindRowsHTML(doc *goquery.Document, rows RowsBlock) *goquery.Selection

FindRowsHTML finds result rows in an HTML document using the rows selector.

func FindRowsJSON

func FindRowsJSON(body string, rows RowsBlock) []string

FindRowsJSON extracts result items from a JSON response.

func IsCloudflareError

func IsCloudflareError(err error) bool

IsCloudflareError checks if an error is a Cloudflare block.

func NoteChallengeForTest added in v0.5.0

func NoteChallengeForTest(t *Trace, solved bool)

NoteChallengeForTest records a challenge on t from outside the package. For tests that fake a search; the runner records challenges itself.

func WithTrace added in v0.5.0

func WithTrace(ctx context.Context, t *Trace) context.Context

WithTrace returns a context that carries t.

Types

type CapsBlock

type CapsBlock struct {
	CategoryMappings []CategoryMapping   `yaml:"categorymappings"`
	Modes            map[string][]string `yaml:"modes"`
	AllowRawSearch   bool                `yaml:"allowrawsearch"`
}

CapsBlock describes what the indexer supports.

type CategoryMapping

type CategoryMapping struct {
	ID   string `yaml:"id"`
	Cat  string `yaml:"cat"`
	Desc string `yaml:"desc"`
}

CategoryMapping maps a site-specific category ID to a Newznab category.

type CloudflareError

type CloudflareError struct {
	StatusCode int
}

CloudflareError indicates the request was blocked by Cloudflare protection.

func (*CloudflareError) Error

func (e *CloudflareError) Error() string

type Definition

type Definition struct {
	ID           string         `yaml:"id"`
	Name         string         `yaml:"name"`
	Description  string         `yaml:"description"`
	Language     string         `yaml:"language"`
	Type         string         `yaml:"type"` // public, semi-private, private
	Encoding     string         `yaml:"encoding"`
	RequestDelay int            `yaml:"requestDelay"` // milliseconds
	Links        []string       `yaml:"links"`
	LegacyLinks  []string       `yaml:"legacylinks"`
	Caps         CapsBlock      `yaml:"caps"`
	Settings     []SettingField `yaml:"settings"`
	Login        *LoginBlock    `yaml:"login,omitempty"`
	Search       SearchBlock    `yaml:"search"`
	Download     DownloadBlock  `yaml:"download"`
}

Definition is the full parsed representation of a Prowlarr Cardigann YAML file.

func ParseDefinition

func ParseDefinition(raw []byte) (*Definition, error)

ParseDefinition parses raw YAML bytes into a Definition.

Applies a small set of upstream-typo workarounds before YAML parse — see normalizeCardigannQuirks. These exist because the Prowlarr-Indexers repo occasionally ships YAML with subtle template-syntax typos that Prowlarr's C# Cardigann implementation tolerates but Go's text/template rejects. We patch them at load time rather than per-call so the rest of the runner sees clean templates.

type DownloadBlock

type DownloadBlock struct {
	Selectors []SelectorBlock `yaml:"selectors"`
	Method    string          `yaml:"method"`
}

DownloadBlock defines how to extract download links.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is the top-level scraping coordinator. It manages definitions, runners, and the result cache.

func NewEngine

func NewEngine(logger *slog.Logger, flaresolverr *FlareSolverr) *Engine

NewEngine creates a new scraping engine. flaresolverr can be nil if not configured.

func (*Engine) Cache

func (e *Engine) Cache() *ResultCache

Cache returns the result cache.

func (*Engine) ChallengeTroubles added in v0.4.0

func (e *Engine) ChallengeTroubles() []SiteTrouble

ChallengeTroubles lists sites whose Cloudflare challenges keep failing on the current egress IP. Empty without FlareSolverr.

func (*Engine) ClearScraperState added in v0.4.0

func (e *Engine) ClearScraperState()

ClearScraperState drops all IP-bound scraper state: cached FlareSolverr Cloudflare sessions and cached search results. Called after a VPN IP rotation — both are tied to the egress IP that produced them.

func (*Engine) GetRunner

func (e *Engine) GetRunner(catalogID string, settingsJSON string) (*Runner, error)

GetRunner returns a cached or new Runner for the given catalog ID and settings.

func (*Engine) HasDefinition

func (e *Engine) HasDefinition(catalogID string) bool

HasDefinition checks if a definition exists for the given catalog ID.

func (*Engine) LoadDefinitions

func (e *Engine) LoadDefinitions(defs map[string][]byte)

LoadDefinitions stores raw YAML bytes for all catalog entries. Called after the Prowlarr zip is fetched.

func (*Engine) ProbeSearch added in v0.5.0

func (e *Engine) ProbeSearch(ctx context.Context, catalogID, query string) ([]SearchResult, *Trace, error)

ProbeSearch runs one search against a catalog definition with its default settings, for testing indexers that haven't been added. The trace reports whether Cloudflare challenged it.

func (*Engine) ResolveCatalogID

func (e *Engine) ResolveCatalogID(name, url string) string

ResolveCatalogID finds the Prowlarr catalog ID for an indexer by trying: 1. Exact catalog ID match 2. Normalized name match (e.g., "The Pirate Bay" → "thepiratebay") 3. URL domain match (e.g., "https://1337x.to" → looks up "1337x.to")

func (*Engine) SolverBusy added in v0.5.0

func (e *Engine) SolverBusy() bool

SolverBusy reports whether FlareSolverr is solving a challenge right now.

type FieldBlock

type FieldBlock struct {
	SelectorBlock `yaml:",inline"`
	Optional      bool        `yaml:"optional"`
	Default       interface{} `yaml:"default"` // fallback when extraction yields nothing
}

FieldBlock defines how to extract a single field from a result row.

type FilterDef

type FilterDef struct {
	Name string      `yaml:"name"`
	Args interface{} `yaml:"args"` // string, []string, or []interface{}
}

FilterDef describes a single filter in the pipeline.

type FlareSolverr

type FlareSolverr struct {
	// contains filtered or unexported fields
}

FlareSolverr is a client for the FlareSolverr Cloudflare bypass proxy.

func NewFlareSolverr

func NewFlareSolverr(apiURL string, logger *slog.Logger) *FlareSolverr

NewFlareSolverr creates a FlareSolverr client. Returns nil if URL is empty.

func (*FlareSolverr) Busy added in v0.5.0

func (f *FlareSolverr) Busy() bool

Busy reports whether a solve is running right now. Background work (the catalog tester) waits for it so real searches get FlareSolverr first. Nil-safe: no FlareSolverr is never busy.

func (*FlareSolverr) ChallengeTroubles added in v0.4.0

func (f *FlareSolverr) ChallengeTroubles() []SiteTrouble

ChallengeTroubles lists sites whose Cloudflare challenges keep failing lately (see challengeStats.troubles). Nil-safe.

func (*FlareSolverr) ClearSessions added in v0.4.0

func (f *FlareSolverr) ClearSessions()

ClearSessions drops every cached Cloudflare session. Sessions are bound to the egress IP that solved them, so a VPN rotation invalidates them all — keeping them makes CF-walled indexers fail mysteriously until the TTL expires. Sessions are client-side only (no FlareSolverr server-side session objects exist), so a map reset is the whole job.

func (*FlareSolverr) GetSession

func (f *FlareSolverr) GetSession(domain string) (*cfSession, bool)

GetSession returns the cached CF session for a domain, if valid.

func (*FlareSolverr) PreWarm

func (f *FlareSolverr) PreWarm(ctx context.Context, urls []string)

PreWarm proactively solves Cloudflare challenges for a list of URLs. Called at startup, after VPN IP rotation, and on a periodic ticker; sessions younger than TTL−margin are skipped, so a warm pass is cheap.

func (*FlareSolverr) Solve

func (f *FlareSolverr) Solve(ctx context.Context, targetURL string) (html string, cookies []fsCookie, userAgent string, err error)

Solve sends a URL to FlareSolverr to bypass Cloudflare and returns the page HTML, cookies, and user agent string.

type HTTPStatusError added in v0.5.0

type HTTPStatusError struct {
	StatusCode int
}

HTTPStatusError is a non-OK HTTP status from an indexer site.

func (*HTTPStatusError) Error added in v0.5.0

func (e *HTTPStatusError) Error() string

type LoginBlock

type LoginBlock struct {
	Path   string            `yaml:"path"`
	Method string            `yaml:"method"` // post, get, form, cookie
	Inputs map[string]string `yaml:"inputs"`
	Error  []SelectorBlock   `yaml:"error"`
	Test   *TestBlock        `yaml:"test"`
}

LoginBlock describes how to authenticate with a private tracker.

type QueryContext

type QueryContext struct {
	Type     string
	Q        string
	Keywords string // same as the top-level Keywords; some definitions use .Query.Keywords
	IMDBID   string
	TMDBID   string
	TVDBID   string
	Season   string
	Ep       string
	Year     string
	Page     int
}

QueryContext holds search query parameters.

type RateLimitedClient

type RateLimitedClient struct {
	// contains filtered or unexported fields
}

RateLimitedClient is an HTTP client with per-host rate limiting.

func NewRateLimitedClient

func NewRateLimitedClient(delay time.Duration) *RateLimitedClient

NewRateLimitedClient creates an HTTP client with rate limiting. delay is the minimum time between requests (from the YAML requestDelay field).

func (*RateLimitedClient) ApplyCFSession

func (c *RateLimitedClient) ApplyCFSession(rawURL string, cookies []*http.Cookie, userAgent string)

ApplyCFSession sets Cloudflare bypass cookies and user agent from a FlareSolverr session onto this client's cookie jar.

func (*RateLimitedClient) Do

func (c *RateLimitedClient) Do(req *http.Request) (*http.Response, error)

Do executes an HTTP request, respecting the rate limit.

type ResponseConfig

type ResponseConfig struct {
	Type             string `yaml:"type"` // html (default), json, xml
	NoResultsMessage string `yaml:"noResultsMessage"`
}

ResponseConfig specifies the response format.

type ResultCache

type ResultCache struct {
	// contains filtered or unexported fields
}

ResultCache is a simple in-memory cache for search results.

func NewResultCache

func NewResultCache(ttl time.Duration) *ResultCache

NewResultCache creates a result cache with the given TTL.

func (*ResultCache) Cleanup

func (c *ResultCache) Cleanup()

Cleanup removes expired entries. Call periodically.

func (*ResultCache) Clear added in v0.4.0

func (c *ResultCache) Clear()

Clear drops all cached entries — used when the egress IP changes and cached results (and their proxied download URLs) may be stale.

func (*ResultCache) Get

func (c *ResultCache) Get(key string) ([]SearchResult, bool)

Get returns cached results if they exist and are not expired.

func (*ResultCache) Set

func (c *ResultCache) Set(key string, results []SearchResult)

Set stores results in the cache.

type RowsBlock

type RowsBlock struct {
	Selector string         `yaml:"selector"`
	After    int            `yaml:"after"`
	Remove   string         `yaml:"remove"`
	Multiple bool           `yaml:"multiple"`
	Count    *SelectorBlock `yaml:"count,omitempty"`
	Filters  []FilterDef    `yaml:"filters"` // e.g. andmatch — client-side keyword guard
}

RowsBlock defines how to find result rows in the response.

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner executes searches against a single indexer using its YAML definition.

func NewRunner

func NewRunner(def *Definition, settings map[string]string, flaresolverr *FlareSolverr, logger *slog.Logger) *Runner

NewRunner creates a runner for the given definition.

func (*Runner) CurrentBase added in v0.5.0

func (r *Runner) CurrentBase() string

CurrentBase is the site address searches start with: the one that last worked, else the definition's first link.

func (*Runner) Definition

func (r *Runner) Definition() *Definition

Definition returns the underlying definition.

func (*Runner) ResolveDownload

func (r *Runner) ResolveDownload(ctx context.Context, detailURL string) (string, error)

ResolveDownload fetches a detail page and extracts the actual download URL (magnet link or .torrent URL) using the definition's download selectors.

func (*Runner) Search

func (r *Runner) Search(ctx context.Context, query string, categories []int) ([]SearchResult, error)

Search executes a search and returns structured results. Kept for callers that only have a bare keyword string.

func (*Runner) SearchWithQuery added in v0.4.0

func (r *Runner) SearchWithQuery(ctx context.Context, sq SearchQuery) ([]SearchResult, error)

SearchWithQuery executes a search with full structured parameters.

Error contract: per-path failures are collected; if at least one path produced results, those are returned (with failures logged). If EVERY path failed, the combined error is returned — silently degrading a hard failure to "0 results" is what let half the indexer fleet stay broken for weeks without anything surfacing it.

type SearchBlock

type SearchBlock struct {
	Paths           []SearchPath          `yaml:"paths"`
	Inputs          map[string]string     `yaml:"inputs"`
	Headers         map[string][]string   `yaml:"headers"`
	KeywordsFilters []FilterDef           `yaml:"keywordsfilters"`
	Rows            RowsBlock             `yaml:"rows"`
	Fields          map[string]FieldBlock `yaml:"fields"`
}

SearchBlock defines how to search the tracker.

type SearchPath

type SearchPath struct {
	Path     string              `yaml:"path"`
	Method   string              `yaml:"method"`
	Inputs   map[string]string   `yaml:"inputs"`
	Headers  map[string][]string `yaml:"headers"`
	Response *ResponseConfig     `yaml:"response,omitempty"`
}

SearchPath is a single search URL pattern.

type SearchQuery added in v0.4.0

type SearchQuery struct {
	Keywords   string
	Type       string // torznab t= mode: search, tvsearch, movie, ...
	Season     int
	Ep         int
	IMDBID     string
	TMDBID     string
	TVDBID     string
	Year       int
	Categories []int
}

SearchQuery carries the structured torznab search parameters into the template context, so definitions using .Query.Season / .Query.IMDBID and friends resolve correctly.

type SearchResult

type SearchResult struct {
	Title                string
	Details              string // URL to the detail page
	Download             string // .torrent URL or magnet URI
	MagnetURI            string
	InfoHash             string
	Size                 int64
	Seeders              int
	Leechers             int
	Grabs                int
	Date                 string // RFC3339 or raw
	Category             string // Newznab category ID
	DownloadVolumeFactor float64
	UploadVolumeFactor   float64
	Description          string
	IMDBID               string
	Poster               string
}

SearchResult is a single result from a search execution.

type SelectorBlock

type SelectorBlock struct {
	Selector  string            `yaml:"selector"`
	Text      string            `yaml:"text"`
	Attribute string            `yaml:"attribute"`
	Remove    string            `yaml:"remove"`
	Filters   []FilterDef       `yaml:"filters"`
	Case      map[string]string `yaml:"case"`
}

SelectorBlock is the core unit for extracting data from HTML/JSON.

type SettingField

type SettingField struct {
	Name    string      `yaml:"name"`
	Type    string      `yaml:"type"`
	Label   string      `yaml:"label"`
	Default interface{} `yaml:"default"`
	Options interface{} `yaml:"options"` // map[string]string or []map[string]string
}

SettingField is a user-configurable field in the YAML definition. Uses interface{} for Default and Options to handle varied YAML types.

type SiteTrouble added in v0.4.0

type SiteTrouble struct {
	Host        string    `json:"host"`
	Failures    int       `json:"failures"`
	Successes   int       `json:"successes"`
	LastError   string    `json:"last_error"`
	LastFailure time.Time `json:"last_failure"`
}

SiteTrouble is one site whose Cloudflare challenges keep failing.

type TemplateContext

type TemplateContext struct {
	Config     map[string]string // user settings (sort, downloadlink, etc.)
	Keywords   string            // search query (after keywordsfilters)
	Query      QueryContext
	Categories []string          // site category IDs
	Result     map[string]string // for self-referencing fields
	True       bool
	False      bool
	Today      TodayContext
	// contains filtered or unexported fields
}

TemplateContext holds the variables available in Cardigann templates.

func NewTemplateContext

func NewTemplateContext(config map[string]string, query string) *TemplateContext

NewTemplateContext creates a context with sensible defaults.

type TestBlock

type TestBlock struct {
	Path     string `yaml:"path"`
	Selector string `yaml:"selector"`
}

TestBlock verifies a login succeeded.

type TodayContext

type TodayContext struct {
	Year int
}

TodayContext provides date helpers.

type Trace added in v0.5.0

type Trace struct {
	// contains filtered or unexported fields
}

Trace collects facts about one search as it runs, for indexer stats. Attach it with WithTrace before calling SearchWithQuery; the runner fills it in. Safe for concurrent use (multi-path definitions).

func (*Trace) Challenge added in v0.5.0

func (t *Trace) Challenge() (challenged, solved bool)

Challenge reports whether Cloudflare challenged the search and, if so, whether every challenge was solved.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL