extract

package
v0.1.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: 26 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 extract finds downloadable media on web pages.

Extraction is a two step process: Extract analyses a page and returns a Media description (title, voice-over translations, episodes) together with a Resolver. The resolver turns a concrete Selection (translation + episode) into a Stream: the list of available video formats, audio and subtitle tracks with the URLs needed to download them.

Index

Constants

This section is empty.

Variables

View Source
var DefaultYtDlpHosts = []string{
	"youtube.com", "youtu.be", "youtube-nocookie.com", "music.youtube.com",
	"vimeo.com", "dailymotion.com", "twitch.tv", "tiktok.com", "instagram.com", "facebook.com", "fb.watch",
	"twitter.com", "x.com", "reddit.com", "soundcloud.com", "bandcamp.com", "bilibili.com", "nicovideo.jp",
	"vk.com", "vkvideo.ru", "vk.ru", "rutube.ru", "ok.ru", "dzen.ru", "coub.com", "streamable.com", "archive.org",
}

DefaultYtDlpHosts are sites that are always delegated to yt-dlp.

View Source
var ErrNoMedia = errors.New("no media found on the page")

ErrNoMedia is returned when nothing downloadable was found.

View Source
var ErrYtDlpMissing = errors.New("yt-dlp is not configured (install it and pass -ytdlp)")

ErrYtDlpMissing is returned when yt-dlp is required but not configured.

View Source
var Modules = []Module{
	moduleFunc{"metadata", modMetadata},
	moduleFunc{"html5-video", modHTML5},
	moduleFunc{"json-ld", modJSONLD},
	moduleFunc{"iframes", modIframes},
	moduleFunc{"player-tabs", modPlayerTabs},
	moduleFunc{"episode-links", modEpisodeLinks},
	moduleFunc{"subtitle-attributes", modSubtitleAttrs},
	moduleFunc{"playerjs", modPlayerjs},
	moduleFunc{"js-playlist", modJSPlaylist},
	moduleFunc{"media-urls", modMediaURLs},
}

Modules is the ordered list of analysis modules.

Functions

func EpisodeName

func EpisodeName(title, episode string) string

EpisodeName combines a show title with an episode label for file names: "Серия 1" becomes "<title> - Серия 1", while a label that already names the show ("Show 2 серия") is kept as is.

func HeaderArgs

func HeaderArgs(h Headers, ua string) []string

HeaderArgs converts headers to ffmpeg/ffprobe input options.

func ModuleNames

func ModuleNames() []string

ModuleNames lists the names of the analysis modules that find media.

Types

type Browser

type Browser struct {
	ExecPath  string
	UserAgent string
	Proxy     string
	Timeout   time.Duration
	Log       *slog.Logger
	// contains filtered or unexported fields
}

Browser drives an external headless Chrome/Chromium to capture media requests made by JavaScript players. The browser binary is not bundled; its path is configured with -chrome.

func NewBrowser

func NewBrowser(execPath, userAgent, proxy string, timeout time.Duration, log *slog.Logger) *Browser

NewBrowser creates a browser runner allowing one session at a time.

func (*Browser) Capture

func (b *Browser) Capture(ctx context.Context, pageURL string) ([]candidate, Headers, error)

Capture loads pageURL, clicks the player and records media requests.

type Choice

type Choice struct {
	ID     string `json:"id"`
	Label  string `json:"label"`
	Season string `json:"season,omitempty"`
	Number int    `json:"number,omitzero"`
}

Choice is a selectable item: a translation or an episode.

type Engine

type Engine struct {
	Client   *netx.Client
	Generic  *Generic
	YtDlp    *YtDlp // nil when yt-dlp is not configured
	Specific []Extractor
	Prober   *Prober
	Log      *slog.Logger
}

Engine chooses and runs extractors.

func NewEngine

func NewEngine(c *netx.Client, yt *YtDlp, browser *Browser, prober *Prober, log *slog.Logger) *Engine

NewEngine wires the extractors together.

func (*Engine) Extract

func (e *Engine) Extract(ctx context.Context, pageURL string, opts Options) (*Result, error)

Extract analyses pageURL.

func (*Engine) Extractors

func (e *Engine) Extractors() []string

Extractors lists the names usable as Options.Force.

func (*Engine) Tried

func (e *Engine) Tried() []string

Tried lists everything the automatic mode attempts, in order.

type Extractor

type Extractor interface {
	Name() string
	// Match reports whether the extractor is responsible for u.
	Match(u *url.URL) bool
	Extract(ctx context.Context, pageURL string, opts Options) (*Result, error)
}

Extractor is implemented by site specific and generic extractors.

type Format

type Format struct {
	ID       string   `json:"id"`
	Label    string   `json:"label"`
	Width    int      `json:"width,omitzero"`
	Height   int      `json:"height,omitzero"`
	FPS      float64  `json:"fps,omitzero"`
	Bitrate  int      `json:"bitrate,omitzero"` // bits per second
	VCodec   string   `json:"vcodec,omitempty"`
	ACodec   string   `json:"acodec,omitempty"`
	Ext      string   `json:"ext,omitempty"`
	Size     int64    `json:"size,omitzero"`
	HasVideo bool     `json:"has_video"`
	HasAudio bool     `json:"has_audio"`
	Protocol Protocol `json:"protocol"`

	URL        string  `json:"-"`
	Headers    Headers `json:"-"`
	AudioGroup string  `json:"-"` // HLS EXT-X-MEDIA group id
	SubsGroup  string  `json:"-"`
}

Format is one downloadable video (or muxed audio+video) variant.

type Generic

type Generic struct {
	Client *netx.Client
	// Specific returns a site specific extractor for embedded player URLs.
	Specific func(u *url.URL) Extractor
	// Browser is used as a last resort when static analysis finds nothing.
	Browser *Browser
	Log     *slog.Logger
}

Generic extracts media from arbitrary pages using static HTML analysis, iframe recursion, Playerjs configs and (optionally) a headless browser.

func (*Generic) Extract

func (g *Generic) Extract(ctx context.Context, pageURL string, opts Options) (*Result, error)

Extract implements Extractor.

func (*Generic) Match

func (g *Generic) Match(*url.URL) bool

Match implements Extractor; the generic extractor accepts everything.

func (*Generic) Name

func (g *Generic) Name() string

Name implements Extractor.

type Headers

type Headers map[string]string

Headers are HTTP headers required to fetch a media URL (Referer, Origin...).

func (Headers) Clone

func (h Headers) Clone() Headers

Clone returns a copy of h (never nil).

type Media

type Media struct {
	PageURL      string    `json:"page_url"`
	Title        string    `json:"title"`
	Thumbnail    string    `json:"thumbnail,omitempty"`
	Extractor    string    `json:"extractor"`
	Duration     float64   `json:"duration,omitzero"`
	Translations []Choice  `json:"translations"`
	Episodes     []Choice  `json:"episodes"`
	Selected     Selection `json:"selected"`
	Notes        []string  `json:"notes,omitempty"`
	// Modules lists the analysis modules that recognised the page.
	Modules []string `json:"modules,omitempty"`
}

Media describes what was found on a page.

type Module

type Module interface {
	Name() string
	Analyze(d *doc, p *page)
}

Module recognises one way in which web pages expose video. The generic extractor runs every module on each analysed document (the page itself and every embedded player it follows). Modules only contribute findings to the page: media candidates, playlists, episode links, voice-over tabs, iframes.

New page layouts are supported by adding a module here; site specific logic (APIs, signatures) belongs into an Extractor instead.

type Options

type Options struct {
	// Cookies is a Netscape cookies.txt passed to yt-dlp (may be empty).
	Cookies string
	// Force selects an extractor by name ("" or "auto" = automatic).
	Force string
	// Referer of the embedding page (for embedded players).
	Referer string
}

Options carries per-request extraction settings.

type Prober

type Prober struct {
	Path  string
	Proxy string
	UA    string
}

Prober inspects progressive/DASH sources with ffprobe to discover the embedded audio and subtitle streams (multiple dubs inside one MKV/MP4).

func (*Prober) Probe

func (p *Prober) Probe(ctx context.Context, st *Stream)

Probe enriches the first format of st with stream information.

type Protocol

type Protocol string

Protocol describes how a media URL is downloaded.

const (
	ProtoHTTP  Protocol = "http"  // progressive file (mp4, webm, ...)
	ProtoHLS   Protocol = "hls"   // m3u8 playlist
	ProtoDASH  Protocol = "dash"  // mpd manifest
	ProtoYtDlp Protocol = "ytdlp" // piped through yt-dlp -f <id>
)

type Resolver

type Resolver func(ctx context.Context, sel Selection) (*Stream, error)

Resolver resolves a selection into a stream.

type Result

type Result struct {
	Media   *Media
	Resolve Resolver
	// Stream for Media.Selected, if already known.
	Stream *Stream
}

Result is returned by extractors.

type Selection

type Selection struct {
	Translation string `json:"translation"`
	Episode     string `json:"episode"`
}

Selection picks a translation and an episode ("" = default).

type Stream

type Stream struct {
	Formats   []Format `json:"formats"`
	Audio     []Track  `json:"audio"`
	Subtitles []Track  `json:"subtitles"`
	Duration  float64  `json:"duration,omitzero"`
	Title     string   `json:"title,omitempty"`
	// contains filtered or unexported fields
}

Stream is everything downloadable for one selection.

func (*Stream) FindAudio

func (s *Stream) FindAudio(id string) (*Track, bool)

FindAudio returns the audio track with the given id.

func (*Stream) FindFormat

func (s *Stream) FindFormat(id string) (*Format, bool)

FindFormat returns the format with the given id.

func (*Stream) FindSubtitle

func (s *Stream) FindSubtitle(id string) (*Track, bool)

FindSubtitle returns the subtitle track with the given id.

type Track

type Track struct {
	ID       string   `json:"id"`
	Label    string   `json:"label"`
	Lang     string   `json:"lang,omitempty"`
	Codec    string   `json:"codec,omitempty"`
	Bitrate  int      `json:"bitrate,omitzero"`
	Default  bool     `json:"default,omitzero"`
	Embedded bool     `json:"embedded,omitzero"` // stream inside the video file (selected with -map)
	Protocol Protocol `json:"protocol,omitempty"`

	URL         string  `json:"-"`
	Headers     Headers `json:"-"`
	Group       string  `json:"-"`
	StreamIndex int     `json:"-"` // index among the file's audio/subtitle streams when Embedded
}

Track is a separate audio or subtitle track.

type UnsupportedError

type UnsupportedError struct {
	Tried []string
	Cause error
}

UnsupportedError means that no extractor or analysis module could find media on the page: the site needs a new module or a site-specific extractor.

func (*UnsupportedError) Error

func (e *UnsupportedError) Error() string

func (*UnsupportedError) Unwrap

func (e *UnsupportedError) Unwrap() error

type YtDlp

type YtDlp struct {
	Path      string
	ExtraArgs []string
	Proxy     string
	Hosts     []string
	TempDir   string
	Log       *slog.Logger
}

YtDlp integrates the external yt-dlp binary (https://github.com/yt-dlp/yt-dlp). yt-dlp is NOT bundled with this project: install it separately and pass its path with -ytdlp. It is used for YouTube and many other well known sites, and as a fallback when the generic extractor finds nothing.

func (*YtDlp) BaseArgs

func (y *YtDlp) BaseArgs(cookiesPath string) []string

BaseArgs returns arguments shared by all yt-dlp invocations.

func (*YtDlp) Command

func (y *YtDlp) Command(ctx context.Context, pageURL, formatID, cookies string) (*exec.Cmd, func(), error)

Command builds a yt-dlp command that writes format formatID of pageURL to stdout. The returned cleanup removes temporary files and must be called after the process exits.

func (*YtDlp) Extract

func (y *YtDlp) Extract(ctx context.Context, pageURL string, opts Options) (*Result, error)

Extract implements Extractor.

func (*YtDlp) Match

func (y *YtDlp) Match(u *url.URL) bool

Match implements Extractor.

func (*YtDlp) Name

func (y *YtDlp) Name() string

Name implements Extractor.

Jump to

Keyboard shortcuts

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