Documentation
¶
Overview ¶
Package types holds the shared contract between the engine, api, settings and media packages. Everything stremio-web depends on is mirrored here so the individual packages can be developed independently against a stable surface.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AddOptions ¶
type AddOptions struct {
// MetaInfo holds raw .torrent bytes when available (from /create from=..).
MetaInfo []byte
// Torrent is the raw "torrent" object from a /:infoHash/create body, if any
// (stremio-web sends parsed torrent metadata: {infoHash, announce, files...}).
Torrent json.RawMessage
// Trackers / Sources are announce URLs (?tr=) or peerSearch sources
// ("tracker:<url>", "dht:<ih>"). The engine should extract real tracker URLs.
Trackers []string
Sources []string
}
AddOptions carries everything needed to add/locate a torrent. It is derived by the api layer from the create body and/or the streaming URL query string.
type Config ¶
type Config struct {
HTTPPort int // enginefs HTTP API port (default 11470)
HTTPSPort int // optional HTTPS port (default 12470, 0 = disabled)
AppPath string // application/cache root, e.g. ~/.stremio-server
CacheRoot string // torrent piece cache root (defaults to AppPath)
MemoryCacheSize int64 // opt-in in-RAM piece cache budget in bytes; 0 = disabled (write pieces to disk)
ListenPort int // BitTorrent peer listen port (0 = random)
WebUI string // redirect target for "GET /" (e.g. https://web.stremio.com/)
Version string // value reported as settings.serverVersion
TrackersMax int // max ranked UDP/HTTP trackers per torrent (STREMIO_TRACKERS_MAX; 0 = default)
// remote tracker list source (STREMIO_TRACKERS_URL); "" disables the remote
// fetch (embedded/cached list + DHT/PEX only). Default: a curated public list.
TrackersURL string
// disable ALL BitTorrent tracker announces (DHT/PEX/webseeds still used); STREMIO_DISABLE_TRACKERS; default false
DisableTrackers bool
// disable WebTorrent/WebRTC peers (pion); cuts ~60% of goroutines + RAM; STREMIO_DISABLE_WEBTORRENT; default true (disabled)
DisableWebtorrent bool
// established peer connections per torrent (scales half-open=n/2, high-water=n*10); STREMIO_PEERS_PER_TORRENT; 0 = default 50
PeersPerTorrent int
// enable DLNA/UPnP casting discovery + control on /casting; STREMIO_ENABLE_DLNA; default false (disabled)
EnableDLNA bool
// Stream proxy configuration.
ProxyPassword string // api_password for stream proxy; "" = no auth
ProxySecret string // hex-encoded 32-byte key for signed-URL tokens
ProxyIPACL string // comma-separated CIDR allowlist for proxy clients
ProxyPrebuffer int // number of segments to prefetch (0 = off)
ProxySegCacheTTL int // segment cache TTL in seconds (0 = caching off)
ProxyPublicURL string // explicit external base URL for proxy; "" = derive
ProxyUpstream string // global upstream proxy for stream-proxy fetches; "" = direct (STREMIO_PROXY_UPSTREAM; socks5/http)
// Bitmagnet integration (self-hosted DHT index).
BitmagnetURL string // GraphQL endpoint, e.g. http://localhost:3333/graphql; "" disables stream queries
// Torznab integration (Prowlarr/Jackett/NZBHydra/Bitmagnet /torznab).
TorznabURL string // Torznab endpoint base URL; "" disables stream queries
TorznabAPIKey string // Optional API key appended as &apikey=; "" = no auth
// Cinemeta-compatible metadata addon base URL used by the /bitmagnet and
// /torznab add-ons to resolve an IMDB id to a title (STREMIO_METADATA_URL).
// Default https://v3-cinemeta.strem.io; "" disables the lookup. Accepts any
// addon speaking /meta/{type}/{id}.json (Cinemeta, a self-hosted mirror, or
// a TMDB/aiometadata addon's configured base).
MetadataURL string
// LocalIMDB enables the local-files add-on's IMDB title->id resolution
// (queries IMDb's suggestion API; STREMIO_LOCAL_IMDB, default true). When
// false, local files keep filename-parsed titles and local: ids — no
// external IMDb call is made.
LocalIMDB bool
// Censorship resistance / anonymity.
// BitTorrent peer encryption policy (STREMIO_BT_ENCRYPTION): "prefer" (default; encrypt if peer supports, else
// plaintext), "require" (refuse plaintext — DPI evasion), "disable" (no obfuscation).
BTEncryption string
// upstream proxy for BitTorrent tracker announces, HTTP webseeds, metainfo + tracker-list fetch
// (STREMIO_BT_PROXY; socks5://host:port or http(s)://host:port). "" = direct.
// NOTE: peer connections are not proxied (anacrolix uses listen-bound sockets for peer dials).
BTProxy string
// extra DHT bootstrap nodes appended to defaults (STREMIO_DHT_BOOTSTRAP; comma-separated host:port). "" = defaults only.
DHTBootstrap string
// hide client version/fingerprint from peers (STREMIO_BT_ANONYMOUS; cc.AnonymousMode). default false.
BTAnonymous bool
// IdleTimeout removes a torrent that has had no open stream readers and no
// access for this long (STREMIO_TORRENT_IDLE_TIMEOUT, seconds; default 300,
// 0 = disabled). Matches the official server's inactive-torrent reclaim so a
// stopped torrent is dropped even when cacheSize is unlimited, while staying
// alive long enough for instant scrub/resume/next-episode.
IdleTimeout time.Duration
}
Config is the runtime configuration shared by all subsystems.
type Engine ¶
type Engine interface {
InfoHash() string
// Ready blocks until metadata (file list) is available, the context is
// cancelled, or the engine errors.
Ready(ctx context.Context) error
Files() []FileInfo
// Stats returns torrent-level stats when idx < 0, otherwise augmented with
// streamLen/streamName/streamProgress for that file.
Stats(idx int) *Stats
// NewReader returns a streaming reader for file idx plus the file length.
// The reader MUST support Seek (for HTTP Range) and prioritise pieces near
// the current read offset.
NewReader(idx int) (io.ReadSeekCloser, int64, error)
// GuessFileIdx returns the index of the most likely playable file
// (largest video file), or -1 when none.
GuessFileIdx() int
}
Engine is a single torrent handle.
type EngineManager ¶
type EngineManager interface {
// EnsureEngine adds (or returns the existing) torrent for infoHash. It is
// idempotent: a second call with more trackers should merge them.
EnsureEngine(infoHash string, opts AddOptions) (Engine, error)
GetEngine(infoHash string) (Engine, bool)
RemoveEngine(infoHash string) error
RemoveAll()
ListEngines() []string
// AllStats returns torrent-level stats keyed by infoHash (for /stats.json).
AllStats() map[string]*Stats
Close() error
}
EngineManager owns the anacrolix client and the set of live engines.
type FileInfo ¶
type FileInfo struct {
Name string `json:"name"`
Path string `json:"path"`
Length int64 `json:"length"`
Offset int64 `json:"offset"`
}
FileInfo mirrors an entry of stats.files as consumed by stremio-web.
type MediaProber ¶
type MediaProber interface {
Probe(streamURL string) (interface{}, error)
Tracks(rawURL string) (interface{}, error)
OpenSubHash(videoURL string) (result interface{}, err error)
SubtitlesTracks(subsURL string) (result interface{}, err error)
// WriteSubtitles converts the subtitle track at `from` into SRT (ext=="srt")
// or WEBVTT (ext=="vtt"), applying offsetMs, writing to w.
WriteSubtitles(w io.Writer, from, ext string, offsetMs int) error
// StartHLS starts (or reuses) an ffmpeg HLS transcode for session id and
// returns the master playlist text.
StartHLS(id, mediaURL string) (string, error)
// HLSFile returns the filesystem path and content-type for a file in the
// HLS session (playlist or .ts segment).
HLSFile(ctx context.Context, id, name string) (path, contentType string, err error)
}
MediaProber backs the ffmpeg-based helper routes. Implementations shell out to ffprobe/ffmpeg. Methods return values that are JSON-encoded verbatim.
type Options ¶ added in v0.7.0
type Options struct {
Connections *int `json:"connections"`
DHT bool `json:"dht"`
Growler Growler `json:"growler"`
HandshakeTimeout *int `json:"handshakeTimeout"`
Path string `json:"path"`
PeerSearch PeerSearch `json:"peerSearch"`
SwarmCap SwarmCap `json:"swarmCap"`
Timeout *int `json:"timeout"`
Tracker bool `json:"tracker"`
Virtual bool `json:"virtual"`
}
Options mirrors stats.opts (the torrent engine options object) consumed by stremio-core's strict Statistics.opts deserializer. Optional numeric fields are pointers so they marshal as JSON null. A typed struct (vs map[string]any) avoids reflect map-encoding + key sorting on every stats poll.
type PeerSearch ¶ added in v0.7.0
type PeerSearch struct {
Min int `json:"min"`
Max int `json:"max"`
Sources []string `json:"sources"`
}
PeerSearch is stats.opts.peerSearch.
type SettingsStore ¶
type SettingsStore interface {
// Values returns the current settings.values object.
Values() map[string]interface{}
// OptionsSchema returns the settings.options array (GUI schema). The list of
// available interface addresses feeds the remoteHttps selector.
OptionsSchema(availableInterfaces []string) []map[string]interface{}
// Extend merges a patch (POST /settings body) into the values.
Extend(patch map[string]interface{})
// Get returns a single value.
Get(key string) interface{}
// Save persists to disk.
Save() error
}
SettingsStore persists the user-facing server settings (cacheSize, bt*, ...).
type Source ¶
type Source struct {
LastStarted string `json:"lastStarted"`
URL string `json:"url"`
NumFound int `json:"numFound"`
NumFoundUniq int `json:"numFoundUniq"`
NumRequests int `json:"numRequests"`
}
Source is one tracker-announcement entry emitted in Stats.Sources. All fields are required (non-null) to match stremio-core's Source shape, which the strict (deny-missing) Statistics deserializer rejects if any are absent. url MUST be a parseable URL (udp:// or http(s)://) — never a "dht:" pseudo-URI.
type Stats ¶
type Stats struct {
InfoHash string `json:"infoHash"`
Name string `json:"name"`
Peers int `json:"peers"`
Unchoked int `json:"unchoked"`
Queued int `json:"queued"`
Unique int `json:"unique"`
ConnectionTries int `json:"connectionTries"`
SwarmPaused bool `json:"swarmPaused"`
SwarmConnections int `json:"swarmConnections"`
SwarmSize int `json:"swarmSize"`
// Selections holds piece-selection ranges (null or an array). The element
// shape is anacrolix-internal and never populated by the engine today, so
// []any preserves the null/empty-array wire semantics without constraining
// the unknown element type.
Selections []any `json:"selections"`
Wires []Wire `json:"wires"`
Files []FileInfo `json:"files"`
Downloaded int64 `json:"downloaded"`
Uploaded int64 `json:"uploaded"`
DownloadSpeed float64 `json:"downloadSpeed"`
UploadSpeed float64 `json:"uploadSpeed"`
Sources []Source `json:"sources"`
Opts Options `json:"opts"`
// PeerSearchRunning is REQUIRED (non-null) by stremio-core's Statistics.
PeerSearchRunning bool `json:"peerSearchRunning"`
// Per-file extras (only when a file index is requested).
StreamLen *int64 `json:"streamLen,omitempty"`
StreamName *string `json:"streamName,omitempty"`
StreamProgress *float64 `json:"streamProgress,omitempty"`
// GuessedFileIdx is set only in the /create response when the client asked
// the server to guess (guessFileIdx) or a fileMustInclude matched.
GuessedFileIdx *int `json:"guessedFileIdx,omitempty"`
}
Stats mirrors getStatistics(engine[, idx]) from the original server.js. Field names and JSON tags MUST match exactly. Per-file (idx>=0) fields are pointers so they are omitted at torrent level.