.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
youtube_noapi.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Youtube (Videos)
3
4"""
5
6from functools import reduce
7from json import loads, dumps
8from urllib.parse import quote_plus
9
10# about
11about = {
12 "website": 'https://www.youtube.com/',
13 "wikidata_id": 'Q866',
14 "official_api_documentation": 'https://developers.google.com/youtube/v3/docs/search/list?apix=true',
15 "use_official_api": False,
16 "require_api_key": False,
17 "results": 'HTML',
18}
19
20# engine dependent config
21categories = ['videos', 'music']
22paging = True
23language_support = False
24time_range_support = True
25
26# search-url
27base_url = 'https://www.youtube.com/results'
28search_url = base_url + '?search_query={query}&page={page}'
29time_range_url = '&sp=EgII{time_range}%253D%253D'
30# the key seems to be constant
31next_page_url = 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
32time_range_dict = {'day': 'Ag', 'week': 'Aw', 'month': 'BA', 'year': 'BQ'}
33
34base_youtube_url = 'https://www.youtube.com/watch?v='
35
36
37# do search-request
38def request(query, params):
39 params['cookies']['CONSENT'] = "YES+"
40 if not params['engine_data'].get('next_page_token'):
41 params['url'] = search_url.format(query=quote_plus(query), page=params['pageno'])
42 if params['time_range'] in time_range_dict:
43 params['url'] += time_range_url.format(time_range=time_range_dict[params['time_range']])
44 else:
45 params['url'] = next_page_url
46 params['method'] = 'POST'
47 params['data'] = dumps(
48 {
49 'context': {"client": {"clientName": "WEB", "clientVersion": "2.20210310.12.01"}},
50 'continuation': params['engine_data']['next_page_token'],
51 }
52 )
53 params['headers']['Content-Type'] = 'application/json'
54
55 return params
56
57
58# get response from search-request
59def response(resp):
60 if resp.search_params.get('engine_data'):
61 return parse_next_page_response(resp.text)
62 return parse_first_page_response(resp.text)
63
64
65def parse_next_page_response(response_text):
66 results = []
67 result_json = loads(response_text)
68 for section in (
69 result_json['onResponseReceivedCommands'][0]
70 .get('appendContinuationItemsAction')['continuationItems'][0]
71 .get('itemSectionRenderer')['contents']
72 ):
73 if 'videoRenderer' not in section:
74 continue
75 section = section['videoRenderer']
76 content = "-"
77 if 'descriptionSnippet' in section:
78 content = ' '.join(x['text'] for x in section['descriptionSnippet']['runs'])
79 results.append(
80 {
81 'url': base_youtube_url + section['videoId'],
82 'title': ' '.join(x['text'] for x in section['title']['runs']),
83 'content': content,
84 'author': section['ownerText']['runs'][0]['text'],
85 'length': section['lengthText']['simpleText'],
86 'template': 'videos.html',
87 'iframe_src': 'https://www.youtube-nocookie.com/embed/' + section['videoId'],
88 'thumbnail': section['thumbnail']['thumbnails'][-1]['url'],
89 }
90 )
91 try:
92 token = (
93 result_json['onResponseReceivedCommands'][0]
94 .get('appendContinuationItemsAction')['continuationItems'][1]
95 .get('continuationItemRenderer')['continuationEndpoint']
96 .get('continuationCommand')['token']
97 )
98 results.append(
99 {
100 "engine_data": token,
101 "key": "next_page_token",
102 }
103 )
104 except: # pylint: disable=bare-except
105 pass
106
107 return results
108
109
110def parse_first_page_response(response_text):
111 results = []
112 results_data = response_text[response_text.find('ytInitialData') :]
113 results_data = results_data[results_data.find('{') : results_data.find(';</script>')]
114 results_json = loads(results_data) if results_data else {}
115 sections = (
116 results_json.get('contents', {})
117 .get('twoColumnSearchResultsRenderer', {})
118 .get('primaryContents', {})
119 .get('sectionListRenderer', {})
120 .get('contents', [])
121 )
122
123 for section in sections:
124 if "continuationItemRenderer" in section:
125 next_page_token = (
126 section["continuationItemRenderer"]
127 .get("continuationEndpoint", {})
128 .get("continuationCommand", {})
129 .get("token", "")
130 )
131 if next_page_token:
132 results.append(
133 {
134 "engine_data": next_page_token,
135 "key": "next_page_token",
136 }
137 )
138 for video_container in section.get('itemSectionRenderer', {}).get('contents', []):
139 video = video_container.get('videoRenderer', {})
140 videoid = video.get('videoId')
141 if videoid is not None:
142 url = base_youtube_url + videoid
143 thumbnail = 'https://i.ytimg.com/vi/' + videoid + '/hqdefault.jpg'
144 title = get_text_from_json(video.get('title', {}))
145 content = get_text_from_json(video.get('descriptionSnippet', {}))
146 author = get_text_from_json(video.get('ownerText', {}))
147 length = get_text_from_json(video.get('lengthText', {}))
148
149 # append result
150 results.append(
151 {
152 'url': url,
153 'title': title,
154 'content': content,
155 'author': author,
156 'length': length,
157 'template': 'videos.html',
158 'iframe_src': 'https://www.youtube-nocookie.com/embed/' + videoid,
159 'thumbnail': thumbnail,
160 }
161 )
162
163 # return results
164 return results
165
166
168 if 'runs' in element:
169 return reduce(lambda a, b: a + b.get('text', ''), element.get('runs'), '')
170 return element.get('simpleText', '')
parse_next_page_response(response_text)
parse_first_page_response(response_text)