forked from pauloo27/searchtube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
142 lines (115 loc) Β· 3.5 KB
/
main.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package searchtube
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/buger/jsonparser"
)
func getContent(data []byte, index int) []byte {
id := fmt.Sprintf("[%d]", index)
contents, _, _, _ := jsonparser.Get(data, "contents", "twoColumnSearchResultsRenderer", "primaryContents", "sectionListRenderer", "contents", id, "itemSectionRenderer", "contents")
return contents
}
type SearchResult struct {
Title, Uploader, URL, RawDuration, ID, Thumbnail string
Live bool
duration time.Duration
}
func (s *SearchResult) GetDuration() (duration time.Duration, err error) {
duration = s.duration
if s.Live {
err = errors.New("cannot get duration of a live")
return
}
if duration == 0 {
str := s.RawDuration + "s"
if strings.Count(str, ":") == 2 {
str = strings.Replace(str, ":", "h", 1)
}
str = strings.Replace(str, ":", "m", 1)
duration, err = time.ParseDuration(str)
}
return
}
var httpClient = &http.Client{}
func Search(searchTerm string, limit int) (results []*SearchResult, err error) {
url := fmt.Sprintf("https://www.youtube.com/results?search_query=%s", url.QueryEscape(searchTerm))
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("Cannot create GET request: %v", err)
}
req.Header.Add("Accept-Language", "en")
req.Header.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36")
res, err := httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Cannot get youtube page: %v", err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, fmt.Errorf("status code error: %d %s", res.StatusCode, res.Status)
}
buffer, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("Cannot read body: %v", err)
}
body := string(buffer)
splittedScript := strings.Split(body, `window["ytInitialData"] = `)
if len(splittedScript) != 2 {
splittedScript = strings.Split(body, `var ytInitialData = `)
}
if len(splittedScript) != 2 {
if err != nil {
return nil, fmt.Errorf("Cannot split script: %v", err)
}
}
splittedScript = strings.Split(splittedScript[1], `window["ytInitialPlayerResponse"] = null;`)
jsonData := []byte(splittedScript[0])
index := 0
var contents []byte
for {
contents = getContent(jsonData, index)
_, _, _, err = jsonparser.Get(contents, "[0]", "carouselAdRenderer")
if err == nil {
index++
} else {
break
}
}
_, err = jsonparser.ArrayEach(contents, func(value []byte, t jsonparser.ValueType, i int, err error) {
if limit > 0 && len(results) >= limit {
return
}
id, err := jsonparser.GetString(value, "videoRenderer", "videoId")
if err != nil {
return
}
title, err := jsonparser.GetString(value, "videoRenderer", "title", "runs", "[0]", "text")
if err != nil {
return
}
uploader, err := jsonparser.GetString(value, "videoRenderer", "ownerText", "runs", "[0]", "text")
if err != nil {
return
}
live := false
duration, err := jsonparser.GetString(value, "videoRenderer", "lengthText", "simpleText")
if err != nil {
duration = ""
live = true
}
results = append(results, &SearchResult{
Title: title,
Uploader: uploader,
RawDuration: duration,
ID: id,
URL: fmt.Sprintf("https://youtube.com/watch?v=%s", id),
Live: live,
Thumbnail: fmt.Sprintf("https://i1.ytimg.com/vi/%s/hqdefault.jpg", id),
})
})
return
}