90 lines
1.8 KiB
Go
90 lines
1.8 KiB
Go
|
package ytsclient
|
||
|
|
||
|
import (
|
||
|
r "github.com/levigross/grequests"
|
||
|
"strconv"
|
||
|
)
|
||
|
|
||
|
type Client struct {
|
||
|
url string
|
||
|
list string
|
||
|
get string
|
||
|
suggestions string
|
||
|
}
|
||
|
|
||
|
const (
|
||
|
list = "/list_movies.json"
|
||
|
get = "/movie_details.json"
|
||
|
suggestions = "/movie_suggestions.json"
|
||
|
)
|
||
|
|
||
|
func NewClient(url string) *Client {
|
||
|
if url == "" {
|
||
|
url = "https://yts.am/api/v2"
|
||
|
}
|
||
|
return &Client{url, url + list, url + get, url + suggestions}
|
||
|
}
|
||
|
|
||
|
func (y *Client) List(params *ListParams) ([]Movie, error) {
|
||
|
if params == nil {
|
||
|
params = &ListParams{}
|
||
|
}
|
||
|
res, err := r.Get(y.list, params.format())
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
var resp ListResponse
|
||
|
if err := res.JSON(&resp); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return resp.Data.Movies, nil
|
||
|
}
|
||
|
|
||
|
func (y *Client) Search(search string, params *ListParams) ([]Movie, error) {
|
||
|
if params == nil {
|
||
|
params = &ListParams{}
|
||
|
}
|
||
|
params.QueryTerm = search
|
||
|
res, err := r.Get(y.list, params.format())
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
var resp ListResponse
|
||
|
if err := res.JSON(&resp); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return resp.Data.Movies, nil
|
||
|
}
|
||
|
|
||
|
func (y *Client) Get(id string, params *MovieParams) (Movie, error) {
|
||
|
if params == nil {
|
||
|
params = &MovieParams{}
|
||
|
}
|
||
|
p := params.format()
|
||
|
p.Params["movie_id"] = id
|
||
|
res, err := r.Get(y.get, p)
|
||
|
if err != nil {
|
||
|
return Movie{}, err
|
||
|
}
|
||
|
var resp MovieResponse
|
||
|
if err := res.JSON(&resp); err != nil {
|
||
|
return Movie{}, err
|
||
|
}
|
||
|
return resp.Data.Movie, nil
|
||
|
}
|
||
|
|
||
|
func (y *Client) Suggestions(id int) ([]Movie, error) {
|
||
|
ro := &r.RequestOptions{
|
||
|
Params: map[string]string{"movie_id": strconv.Itoa(id)},
|
||
|
}
|
||
|
res, err := r.Get(y.suggestions, ro)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
var resp ListResponse
|
||
|
if err := res.JSON(&resp); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return resp.Data.Movies, nil
|
||
|
}
|