yts

package module
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2024 License: MIT Imports: 16 Imported by: 0

README

yflicks-yts

yflicks-yts is a client library for YTS, it is developed keeping the needs of the yflicks desktop application in mind, but you can leverage this package in your own project as well 👍. An example program can be found here demonstrating how to use this package.

Installation

go get github.com/atifcppprogrammer/yflicks-yts@latest

Development Setup

For working on this project, please ensure that your machine is provisioned with the following.

  1. GNU Make
  2. Golang version 1.21.5

We recommend using the asdf version manager and the corresponding Golang plugin for managing your installation 👍.

Once you have cloned this repository, please run make in the root of this repository. This will among other things perform the following important tasks.

  1. Install golangci-lint
  2. Setup necessry git hooks to ensure code quality.
  3. Download all dependencies for this package.

Documentation

Overview

Package yts provides a client that exposes methods for interacting with the YTS API (https://yts.mx/api), as well as scraping the YTS website, for content for which there are no API endpoints provided. This package was developed keeping the yflicks desktop application in mind, however you can leverage this package to create your own projects as well.

The general workflow for this package involves creating a client instance like so:

client, err := yts.NewClient()

Or if you wish to provide a custom configuration for the resulting client this can be done in the following manner.

var (
	parsedSiteURL, _    = url.Parse(DefaultSiteURL)
	parsedAPIBaseURL, _ = url.Parse(DefaultAPIBaseURL)
	torrentTrackers     =  []string{
	  "udp://tracker.openbittorrent.com:80",
	  "udp://open.demonii.com:1337/announce",
	  "udp://tracker.coppersurfer.tk:6969",
	}
)

config := yts.ClientConfig{
	APIBaseURL:      *parsedAPIBaseURL,
	SiteURL:         *parsedSiteURL,
	RequestTimeout:  time.Minute,
	TorrentTrackers: torrentTrackers,
	Debug:           false,
}

client, err := NewClientWithConfig(&config)

In most situations however it is prudent to use the default configuration and then modifying it to suit your needs.

config := DefaultClientConfig()
config.Debug = true
config.RequestTimeout = time.Minute * 2
client, err := NewClientWithConfig(&config)

With the the *yts.Client instance instantiated you can leverage the methods provided by the client in the following manner.

filters := yts.DefaultSearchMoviesFilters("oppenheimer")
response, err := client.SearchMovies(filters)
...
filters := yts.DefaultMovieDetailsFilters()
response, err := client.MovieDetails(3175, filters)
...
response, err := client.MovieSuggestions(3175)
...
response, err := client.TrendingMovies()
...
response, err := client.HomePageContent()

See the accompanying example program for a more detailed tutorial on how to use this package.

Index

Constants

View Source
const (
	// The value of the APIBaseURL field for the ClientConfig instance returned by
	// the DefaultClientConfig() function.
	DefaultAPIBaseURL = "https://yts.mx/api/v2"

	// The value of the SiteURL field for the ClientConfig instance returned by the
	// DefaultClientConfig() function.
	DefaultSiteURL = "https://yts.mx"
)
View Source
const (
	// TimeoutLimitUpper represents the maximum request Timeout that can be set for
	// the internal *http.Client used by the yts.Client methods.
	TimeoutLimitUpper = 5 * time.Minute

	// TimeoutLimitLower represents the minimum request Timeout that can be set for
	// the internal *http.Client used by the yts.Client methods.
	TimeoutLimitLower = 5 * time.Second
)

Variables

View Source
var (
	// ErrInvalidClientConfig indicates that you attempted to create a `yts.Client`
	// instance with an invalid client config, the error description will carry
	// further details.
	ErrInvalidClientConfig = errors.New("invalid_client_config")

	// ErrContentRetrievalFailure indicates that a yts.Client method failed to scrape
	// content from the YTS Site, and may indicate the presence of a bug, please
	// report these by creating an issue at the following URL.
	// https://github.com/atifcppprogrammer/yflicks-yts/issues/new.
	ErrContentRetrievalFailure = errors.New("content_retrieval_failure")

	// ErrFilterValidationFailure is reported when you provided invalid values for an
	// instance of SearchMoviesFilters, the error description will carry further
	// details.
	ErrFilterValidationFailure = errors.New("filter_validation_failure")

	// A ErrValidationFailure is reported whenever you provided an invalid value for
	// an input argument to one of the methods of the yts.Client method, the error
	// description will carry further information.
	ErrValidationFailure = errors.New("validation_failure")
)
View Source
var ErrUnexpectedHTTPResponseStatus = errors.New(
	"unexpected_http_response_status",
)

ErrUnexpectedHTTPResponseStatus indicates that a `yts.Client` method made a network call which had response code outside of the range (200-299).

Functions

func DefaultTorrentTrackers added in v0.9.0

func DefaultTorrentTrackers() []string

DefaultTorrentTrackers returns the list of torrent trackers which are used by the default client configuration i.e. the ClientConfig instance, return by the DefaultClientConfig() function. They are used for generating the magnets links for YTS torrents.

Types

type BaseResponse

type BaseResponse struct {
	Status        string `json:"status"`
	StatusMessage string `json:"status_message"`
	Meta          `json:"@meta"`
}

A BaseResponse instance helps to model the response type of the following endpoints the YTS API.

- "/api/v2/list_movies.json" - "/api/v2/movie_details.json" - "/api/v2/movie_suggestions.json"

type Cast

type Cast struct {
	Name          string `json:"name"`
	CharacterName string `json:"character_name"`
	ImdbCode      string `json:"imdb_code"`
	URLSmallImage string `json:"url_small_image"`
}

A Cast represents the cast information provided as part of the response of the following YTS API endpoints.

- "/api/v2/list_movies.json" - "/api/v2/movie_details.json" - "/api/v2/movie_suggestions.json"

type Client

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

A Client represents the main struct type provided by the `yts` package, you use this instance's method to interact with the YTS API and fetch content scraped from the YTS website.

func NewClient

func NewClient() *Client

NewClient returns a new `*yts.Client` instance with the internal ClientConfig being the one returned by the `DefaultClientConfig()` function.

func NewClientWithConfig added in v0.9.0

func NewClientWithConfig(config *ClientConfig) (*Client, error)

NewClientConfig creates `*Client` instance for the provided client config, an error will be returned in the event the provided config is invalid.

func (*Client) HomePageContent added in v0.9.7

func (c *Client) HomePageContent() (*HomePageContentResponse, error)

HomePageContent method scrapes the popular, latest torrents and upcoming movies sections of the YTS website's "/" home page and returns this as an instance of *HomePageContentResponse.

func (*Client) HomePageContentWithContext added in v0.9.7

func (c *Client) HomePageContentWithContext(ctx context.Context) (
	*HomePageContentResponse, error,
)

HomePageContentWithContext is the same as the HomePageContent method but requires a context.Context argument to be passed, this context is then passed to the http.NewRequestWithContext call used for making the network request.

func (c *Client) MagnetLinks(t TorrentInfoGetter) TorrentMagnets

MagnetLinks returns a TorrentMagnets instance for all torrents returned by the provided TorrentInfoGetter instance, you can pass instances of Movie and MoviePartial into this method directly since they both implement the TorrentInfoGetter interface.

func (*Client) MovieDetails added in v0.9.7

func (c *Client) MovieDetails(movieID int, filters *MovieDetailsFilters) (*MovieDetailsResponse, error)

MovieDetails returns the response of "/api/v2/movie_details.json" endpoint with the provided filters and movieID, the provided movieID must be positive integer a 404 error will be returned if no movie is found for provided movieID.

func (*Client) MovieDetailsWithContext added in v0.9.7

func (c *Client) MovieDetailsWithContext(ctx context.Context, movieID int, filters *MovieDetailsFilters) (
	*MovieDetailsResponse, error,
)

MovieDetailsWithContext is the same as the MovieDetails method but requires a context.Context argument to be passed, this context is then passed to the http.NewRequestWithContext call used for making the network request.

func (*Client) MovieSuggestions added in v0.9.7

func (c *Client) MovieSuggestions(movieID int) (*MovieSuggestionsResponse, error)

MovieSuggestions returns the response of the "/api/v2/movie_suggestions.json" endpoint, the provided movieID must be positive integer, a 404 error will be returned if no movie is found for provided movieID.

func (*Client) MovieSuggestionsWithContext added in v0.9.7

func (c *Client) MovieSuggestionsWithContext(ctx context.Context, movieID int) (
	*MovieSuggestionsResponse, error,
)

MovieSuggestionsWithContext is the same as the MovieSuggestions method but requires a context.Context argument to be passed, this context is then passed to the http.NewRequestWithContext call used for making the network request.

func (*Client) SearchMovies

func (c *Client) SearchMovies(filters *SearchMoviesFilters) (*SearchMoviesResponse, error)

SearchMovies returns the response of the "/api/v2/list_movies.json" endpoint with the provided search filters, the provided filter values are validated internally and an error is returned in the event validation fails.

func (*Client) SearchMoviesWithContext added in v0.9.6

func (c *Client) SearchMoviesWithContext(ctx context.Context, filters *SearchMoviesFilters) (
	*SearchMoviesResponse, error,
)

SearchMoviesWithContext is the same as the SearchMovies method but requires a context.Context argument to be passed, this context is then passed to the http.NewRequestWithContext call used for making the network request.

func (*Client) TrendingMovies added in v0.9.7

func (c *Client) TrendingMovies() (*TrendingMoviesResponse, error)

TrendingMovies method scrapes the "/trending" page of the YTS website and returns the movies shown therein as an instance of *TrendingMoviesResponse

func (*Client) TrendingMoviesWithContext added in v0.9.7

func (c *Client) TrendingMoviesWithContext(ctx context.Context) (
	*TrendingMoviesResponse, error,
)

TrendingMoviesWithContext is the same as the TrendingMovies method but requires a context.Context argument to be passed, this context is then passed to the http.NewRequestWithContext call used for making the network request.

type ClientConfig added in v0.9.0

type ClientConfig struct {
	// The base URL for the YTS API used by *yts.Client methods, you will likely never
	// have to specify a value for this other than DefaultAPIBaseURL
	APIBaseURL url.URL
	// The base URL for the YTS website used by *yts.Client methods, you will likely
	// never have to specify a value for this other than DefaultSiteURL
	SiteURL url.URL
	// The list of torrent tracker URLs used by the `MagnetLinks()` method for
	// preparing magnet links for movie torrents.
	TorrentTrackers []string
	// The timeout duration after which a http request will be cancelled by a client
	// method, this value is passed to the internal *http.Client instance used by the
	// *yts.Client.
	RequestTimeout time.Duration
	// This flag "switches on" an internal logger and is intended for use by developers
	// for debugging purposes, if you encounter a bug in this package turning this flag
	// on will reveal greater detail regarding the error in question.
	Debug bool
}

A ClientConfig allows you to configure the behavior of the `yts.Client` instance created by NewClient() function.

func DefaultClientConfig added in v0.9.0

func DefaultClientConfig() ClientConfig

DefaultClientConfig returns a `ClientConfig` instance, with sensible default field values.

type Genre added in v0.8.2

type Genre string

Represents all possible values for the "genre" query param for the "/api/list_movies.json" endpoint.

const (
	GenreAll         Genre = "all"
	GenreAction      Genre = "Action"
	GenreAdventure   Genre = "Adventure"
	GenreAnimation   Genre = "Animation"
	GenreBiography   Genre = "Biography"
	GenreComedy      Genre = "Comedy"
	GenreCrime       Genre = "Crime"
	GenreDocumentary Genre = "Documentary"
	GenreDrama       Genre = "Drama"
	GenreFamily      Genre = "Family"
	GenreFantasy     Genre = "Fantasy"
	GenreFilmNoir    Genre = "Film-Noir"
	GenreGameShow    Genre = "Game-Show"
	GenreHistory     Genre = "History"
	GenreHorror      Genre = "Horror"
	GenreMusic       Genre = "Music"
	GenreMusical     Genre = "Musical"
	GenreMystery     Genre = "Mystery"
	GenreNews        Genre = "News"
	GenreRealityTV   Genre = "Reality-TV"
	GenreRomance     Genre = "Romance"
	GenreSciFi       Genre = "Sci-Fi"
	GenreSport       Genre = "Sport"
	GenreTalkShow    Genre = "Talk-show"
	GenreThriller    Genre = "Thriller"
	GenreWar         Genre = "War"
	GenreWestern     Genre = "Western"
)

type HomePageContentData added in v0.8.0

type HomePageContentData struct {
	Popular  []SiteMovie
	Latest   []SiteMovie
	Upcoming []SiteUpcomingMovie
}

type HomePageContentResponse added in v0.8.0

type HomePageContentResponse struct {
	Data HomePageContentData `json:"data"`
}

A HomePageContentResponse holds the content retrieved by scraping the /trending page of the YTS website, the content in question being the current popular, trending and upcoming movie torrents.

type Meta

type Meta struct {
	ServerTime     int    `json:"server_time"`
	ServerTimezone string `json:"server_timezone"`
	APIVersion     int    `json:"api_version"`
	ExecutionTime  string `json:"execution_time"`
}

A Meta represents the meta information provided as part of the response of the following YTS API endpoints.

- "/api/v2/list_movies.json" - "/api/v2/movie_details.json" - "/api/v2/movie_suggestions.json"

type Movie

type Movie struct {
	MoviePartial
	Summary  string `json:"summary"`
	Synopsis string `json:"synopsis"`
	State    string `json:"state"`
}

A Movie represents the movie information provided as part of the response of the following YTS API endpoints.

- "/api/v2/list_movies.json" - "/api/v2/movie_suggestions.json"

type MovieDetails

type MovieDetails struct {
	MoviePartial
	LikeCount              int    `json:"like_count"`
	DescriptionIntro       string `json:"description_intro"`
	MediumScreenshotImage1 string `json:"medium_screenshot_image1"`
	MediumScreenshotImage2 string `json:"medium_screenshot_image2"`
	MediumScreenshotImage3 string `json:"medium_screenshot_image3"`
	LargeScreenshotImage1  string `json:"large_screenshot_image1"`
	LargeScreenshotImage2  string `json:"large_screenshot_image2"`
	LargeScreenshotImage3  string `json:"large_screenshot_image3"`
	Cast                   []Cast `json:"cast"`
}

A MoviePartial represents the movie information provided as part of the response of the following YTS API endpoints.

- "/api/v2/movie_details.json"

type MovieDetailsData

type MovieDetailsData struct {
	Movie MovieDetails `json:"movie"`
}

type MovieDetailsFilters

type MovieDetailsFilters struct {
	WithImages bool `json:"with_images"`
	WithCast   bool `json:"with_cast"`
}

A MovieDetailsFilters represents the complete set of filters (query params) that can be provided for the "/api/v2/movie_details.json" endpoint of the YTS API (https://yts.mx/api#movie_details).

func DefaultMovieDetailsFilters

func DefaultMovieDetailsFilters() *MovieDetailsFilters

DefaultMovieDetailsFilters returns the default *MovieDetailsFilters, unlike the YTS documentation (https://yts.mx/api#movie_details), we set "with_images" and "with_cast" to true.

type MovieDetailsResponse

type MovieDetailsResponse struct {
	BaseResponse
	Data MovieDetailsData `json:"data"`
}

A MovieDetailsResponse models the response of the "/api/v2/movie_details.json" endpoint of YTS API (https://yts.mx/api#movie_details).

type MoviePartial

type MoviePartial struct {
	ID                      int       `json:"id"`
	URL                     string    `json:"url"`
	ImdbCode                string    `json:"imdb_code"`
	Title                   string    `json:"title"`
	TitleEnglish            string    `json:"title_english"`
	TitleLong               string    `json:"title_long"`
	Slug                    string    `json:"slug"`
	Year                    int       `json:"year"`
	Rating                  float64   `json:"rating"`
	Runtime                 int       `json:"runtime"`
	Genres                  []Genre   `json:"genres"`
	DescriptionFull         string    `json:"description_full"`
	YtTrailerCode           string    `json:"yt_trailer_code"`
	Language                string    `json:"language"`
	MpaRating               string    `json:"mpa_rating"`
	BackgroundImage         string    `json:"background_image"`
	BackgroundImageOriginal string    `json:"background_image_original"`
	SmallCoverImage         string    `json:"small_cover_image"`
	MediumCoverImage        string    `json:"medium_cover_image"`
	LargeCoverImage         string    `json:"large_cover_image"`
	Torrents                []Torrent `json:"torrents"`
	DateUploaded            string    `json:"date_uploaded"`
	DateUploadedUnix        int       `json:"date_uploaded_unix"`
}

A MoviePartial represents the common movie information provided as part of the response of the following YTS API endpoints.

- "/api/v2/list_movies.json" - "/api/v2/movie_details.json" - "/api/v2/movie_suggestions.json"

func (*MoviePartial) GetTorrentInfo added in v0.9.0

func (mp *MoviePartial) GetTorrentInfo() *TorrentInfo

type MovieSuggestionsData

type MovieSuggestionsData struct {
	MovieCount int     `json:"movie_count"`
	Movies     []Movie `json:"movies"`
}

type MovieSuggestionsResponse

type MovieSuggestionsResponse struct {
	BaseResponse
	Data MovieSuggestionsData `json:"data"`
}

A MovieSuggestionsResponse models the response of the "/api/v2/movie_suggestions.json" endpoint of YTS API (https://yts.mx/api#movie_suggestions).

type OrderBy added in v0.8.2

type OrderBy string

Represents all possible values for the "order_by" query param for the "/api/list_movies.json" endpoint.

const (
	OrderByAsc  OrderBy = "asc"
	OrderByDesc OrderBy = "desc"
)

type Quality added in v0.8.2

type Quality string

Represents all possible values for the "quality" query param for the "/api/list_movies.json" endpoint.

const (
	QualityAll       Quality = "all"
	Quality480p      Quality = "480p"
	Quality720p      Quality = "720p"
	Quality1080p     Quality = "1080p"
	Quality1080pX265 Quality = "1080p.x265"
	Quality2160p     Quality = "2160p"
	Quality3D        Quality = "3D"
)

type SearchMoviesData

type SearchMoviesData struct {
	MovieCount int     `json:"movie_count"`
	Limit      int     `json:"limit"`
	PageNumber int     `json:"page_number"`
	Movies     []Movie `json:"movies"`
}

type SearchMoviesFilters

type SearchMoviesFilters struct {
	Limit         int     `json:"limit"`
	Page          int     `json:"page"`
	Quality       Quality `json:"quality"`
	MinimumRating int     `json:"minimum_rating"`
	QueryTerm     string  `json:"query_term"`
	Genre         Genre   `json:"genre"`
	SortBy        SortBy  `json:"sort_by"`
	OrderBy       OrderBy `json:"order_by"`
	WithRTRatings bool    `json:"with_rt_ratings"`
}

A SearchMoviesFilters represents the complete set of filters (query params) that can be provided for the "/api/v2/list_movies.json" endpoint of the YTS API (https://yts.mx/api#list_movies).

func DefaultSearchMoviesFilters added in v0.9.7

func DefaultSearchMoviesFilters(query string) *SearchMoviesFilters

DefaultSearchMoviesFilters returns the default *SearchMoviesFilters for the given search term as presented in the YTS documentation (https://yts.mx/api#list_movies).

type SearchMoviesResponse

type SearchMoviesResponse struct {
	BaseResponse
	Data SearchMoviesData `json:"data"`
}

A SearchMoviesResponse models the response of the "/api/v2/list_movies.json" endpoint of YTS API (https://yts.mx/api#list_movies).

type SiteMovie added in v0.9.0

type SiteMovie struct {
	SiteMovieBase
	Rating string `json:"rating"`
}

A SiteMovie instance represents all the information provided for each "movie card" show on the following pages of the YTS website.

- The popular and latest movie sections on the home page of the YTS website. - The trending movies shown on the YTS website.

type SiteMovieBase added in v0.9.0

type SiteMovieBase struct {
	Title  string  `json:"title"`
	Year   int     `json:"year"`
	Link   string  `json:"link"`
	Image  string  `json:"image"`
	Genres []Genre `json:"genres"`
}

The SiteMovieBase type contains all the information required by both the and SiteMovieUpcoming types.

type SiteUpcomingMovie added in v0.9.0

type SiteUpcomingMovie struct {
	SiteMovieBase
	Progress int     `json:"progress"`
	Quality  Quality `json:"quality"`
}

A SiteUpcomingMovie instance represents all the information provided for each "movie card" on the upcoming section on the home page of the YTS website.

type SortBy added in v0.8.2

type SortBy string

Represents all possible values for the "sort_by" query param for the "/api/list_movies.json" endpoint.

const (
	SortByTitle         SortBy = "title"
	SortByYear          SortBy = "year"
	SortByRating        SortBy = "rating"
	SortByPeers         SortBy = "peers"
	SortBySeeds         SortBy = "seeds"
	SortByDownloadCount SortBy = "download_count"
	SortByLikeCount     SortBy = "like_count"
	SortByDateAdded     SortBy = "date_added"
)

type Torrent

type Torrent struct {
	URL              string  `json:"url"`
	Hash             string  `json:"hash"`
	Quality          Quality `json:"quality"`
	Type             string  `json:"type"`
	IsRepack         string  `json:"is_repack"`
	VideoCodec       string  `json:"video_codec"`
	BitDepth         string  `json:"bit_depth"`
	AudioChannels    string  `json:"audio_channels"`
	Seeds            int     `json:"seeds"`
	Peers            int     `json:"peers"`
	Size             string  `json:"size"`
	SizeBytes        int     `json:"size_bytes"`
	DateUploaded     string  `json:"date_uploaded"`
	DateUploadedUnix int     `json:"date_uploaded_unix"`
}

A Torrent represents the torrent information provided as part of the response of the following YTS API endpoints.

- "/api/v2/list_movies.json" - "/api/v2/movie_details.json" - "/api/v2/movie_suggestions.json"

type TorrentInfo added in v0.9.0

type TorrentInfo struct {
	MovieTitle string
	Torrents   []Torrent
}

A TorrentInfo serves no grander purpose than a *TorrentInfo being the return type of the GetTorrentInfo method of the TorrrentInfoGetter interface.

type TorrentInfoGetter added in v0.9.0

type TorrentInfoGetter interface {
	GetTorrentInfo() *TorrentInfo
}

A TorrentInfoGetter serves essentially serves as a union type and is implemented by the MoviePartial type so that instances of both Movie and MovieDetails can be provided as inputs to the MagnetLinks method of a yts.Client

type TorrentMagnets added in v0.9.1

type TorrentMagnets map[Quality]string

A TorrentMagnets is the return type of MagnetLinks method of a `yts.Client`

type TrendingMoviesData added in v0.8.0

type TrendingMoviesData struct {
	Movies []SiteMovie `json:"movies"`
}

type TrendingMoviesResponse added in v0.8.0

type TrendingMoviesResponse struct {
	Data TrendingMoviesData `json:"data"`
}

A TrendingMoviesResponse holds the content retrieved by scraping the /trending page of the YTS website, the content in question being the movies currently trending in the past 24 Hours.

Jump to

Keyboard shortcuts

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