youtube_noapi.py 5.9 KB

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