youtube_noapi.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. # about
  8. about = {
  9. "website": 'https://www.youtube.com/',
  10. "wikidata_id": 'Q866',
  11. "official_api_documentation": 'https://developers.google.com/youtube/v3/docs/search/list?apix=true',
  12. "use_official_api": False,
  13. "require_api_key": False,
  14. "results": 'HTML',
  15. }
  16. # engine dependent config
  17. categories = ['videos', 'music']
  18. paging = True
  19. language_support = False
  20. time_range_support = True
  21. # search-url
  22. base_url = 'https://www.youtube.com/results'
  23. search_url = base_url + '?search_query={query}&page={page}'
  24. time_range_url = '&sp=EgII{time_range}%253D%253D'
  25. # the key seems to be constant
  26. next_page_url = 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
  27. time_range_dict = {'day': 'Ag', 'week': 'Aw', 'month': 'BA', 'year': 'BQ'}
  28. base_youtube_url = 'https://www.youtube.com/watch?v='
  29. # do search-request
  30. def request(query, params):
  31. params['cookies']['CONSENT'] = "YES+"
  32. if not params['engine_data'].get('next_page_token'):
  33. params['url'] = search_url.format(query=quote_plus(query), page=params['pageno'])
  34. if params['time_range'] in time_range_dict:
  35. params['url'] += time_range_url.format(time_range=time_range_dict[params['time_range']])
  36. else:
  37. params['url'] = next_page_url
  38. params['method'] = 'POST'
  39. params['data'] = dumps(
  40. {
  41. 'context': {"client": {"clientName": "WEB", "clientVersion": "2.20210310.12.01"}},
  42. 'continuation': params['engine_data']['next_page_token'],
  43. }
  44. )
  45. params['headers']['Content-Type'] = 'application/json'
  46. return params
  47. # get response from search-request
  48. def response(resp):
  49. if resp.search_params.get('engine_data'):
  50. return parse_next_page_response(resp.text)
  51. return parse_first_page_response(resp.text)
  52. def parse_next_page_response(response_text):
  53. results = []
  54. result_json = loads(response_text)
  55. for section in (
  56. result_json['onResponseReceivedCommands'][0]
  57. .get('appendContinuationItemsAction')['continuationItems'][0]
  58. .get('itemSectionRenderer')['contents']
  59. ):
  60. if 'videoRenderer' not in section:
  61. continue
  62. section = section['videoRenderer']
  63. content = "-"
  64. if 'descriptionSnippet' in section:
  65. content = ' '.join(x['text'] for x in section['descriptionSnippet']['runs'])
  66. results.append(
  67. {
  68. 'url': base_youtube_url + section['videoId'],
  69. 'title': ' '.join(x['text'] for x in section['title']['runs']),
  70. 'content': content,
  71. 'author': section['ownerText']['runs'][0]['text'],
  72. 'length': section['lengthText']['simpleText'],
  73. 'template': 'videos.html',
  74. 'iframe_src': 'https://www.youtube-nocookie.com/embed/' + section['videoId'],
  75. 'thumbnail': section['thumbnail']['thumbnails'][-1]['url'],
  76. }
  77. )
  78. try:
  79. token = (
  80. result_json['onResponseReceivedCommands'][0]
  81. .get('appendContinuationItemsAction')['continuationItems'][1]
  82. .get('continuationItemRenderer')['continuationEndpoint']
  83. .get('continuationCommand')['token']
  84. )
  85. results.append(
  86. {
  87. "engine_data": token,
  88. "key": "next_page_token",
  89. }
  90. )
  91. except: # pylint: disable=bare-except
  92. pass
  93. return results
  94. def parse_first_page_response(response_text):
  95. results = []
  96. results_data = response_text[response_text.find('ytInitialData') :]
  97. results_data = results_data[results_data.find('{') : results_data.find(';</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', '')