~gjabell/go-yt

ref: d004dd119c0c6f952a686f584d6b79f9943ae5e3 go-yt/yt.go -rw-r--r-- 1.5 KiB
d004dd11Galen Abell Split main file into subfiles 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package yt

import (
	"net/http"
	"net/url"
)

// SearchResult contains metadata about a Youtube video.
type SearchResult struct {
	Description string
	Channel     Channel
	ID          string
	Length      string // TODO convert to int?
	Title       string
	Thumbnails  []Thumbnail
	ViewCount   string
	VideoURL    string
}

// Channel contains a video's channel metadata.
type Channel struct {
	ID           string
	Name         string
	CanonicalURL string
}

// Thumbnail contains a video's thumbnail URL and dimensions.
type Thumbnail struct {
	URL    string
	Height int
	Width  int
}

var (
	searchURL    = "https://www.youtube.com/results"
	searchParams = "EgIQAQ%3D%3D"
	watchURL     = "https://www.youtube.com/watch"
)

// Search Youtube for a given query by page.
// Returns a list of SearchResults or an error if one occurred.
func Search(query string, page int) ([]SearchResult, error) {
	url, err := makeURL(searchURL, map[string]string{
		"search_query": query,
		"sp":           searchParams,
		"page":         string(page),
	})
	if err != nil {
		return nil, err
	}

	result, err := http.Get(url)
	if err != nil {
		return nil, err
	}

	data, err := parseDataFromHtml(result.Body)
	if err != nil {
		return nil, err
	}

	return parseDataFromJson(data)
}

func makeURL(path string, params map[string]string) (string, error) {
	parsedURL, err := url.Parse(path)
	if err != nil {
		return "", err
	}

	query := url.Values{}
	for key, param := range params {
		query.Set(key, param)
	}

	parsedURL.RawQuery = query.Encode()
	return parsedURL.String(), nil
}