youtube_noapi.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Youtube (Videos)
  4. """
  5. from functools import reduce
  6. from json import loads, dumps
  7. from urllib.parse import quote_plus
  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',
  29. 'week': 'Aw',
  30. 'month': 'BA',
  31. 'year': 'BQ'}
  32. embedded_url = '<iframe width="540" height="304" ' +\
  33. 'data-src="https://www.youtube-nocookie.com/embed/{videoid}" ' +\
  34. 'frameborder="0" allowfullscreen></iframe>'
  35. base_youtube_url = 'https://www.youtube.com/watch?v='
  36. # do search-request
  37. def request(query, params):
  38. if not params['engine_data'].get('next_page_token'):
  39. params['url'] = search_url.format(query=quote_plus(query), page=params['pageno'])
  40. if params['time_range'] in time_range_dict:
  41. params['url'] += time_range_url.format(time_range=time_range_dict[params['time_range']])
  42. else:
  43. print(params['engine_data']['next_page_token'])
  44. params['url'] = next_page_url
  45. params['method'] = 'POST'
  46. params['data'] = dumps({
  47. 'context': {"client": {"clientName": "WEB", "clientVersion": "2.20210310.12.01"}},
  48. 'continuation': params['engine_data']['next_page_token'],
  49. })
  50. params['headers']['Content-Type'] = 'application/json'
  51. return params
  52. # get response from search-request
  53. def response(resp):
  54. if resp.search_params.get('engine_data'):
  55. return parse_next_page_response(resp.text)
  56. return parse_first_page_response(resp.text)
  57. def parse_next_page_response(response_text):
  58. results = []
  59. result_json = loads(response_text)
  60. for section in (result_json['onResponseReceivedCommands'][0]
  61. .get('appendContinuationItemsAction')['continuationItems'][0]
  62. .get('itemSectionRenderer')['contents']):
  63. if 'videoRenderer' not in section:
  64. continue
  65. section = section['videoRenderer']
  66. content = "-"
  67. if 'descriptionSnippet' in section:
  68. content = ' '.join(x['text'] for x in section['descriptionSnippet']['runs'])
  69. results.append({
  70. 'url': base_youtube_url + section['videoId'],
  71. 'title': ' '.join(x['text'] for x in section['title']['runs']),
  72. 'content': content,
  73. 'author': section['ownerText']['runs'][0]['text'],
  74. 'length': section['lengthText']['simpleText'],
  75. 'template': 'videos.html',
  76. 'embedded': embedded_url.format(videoid=section['videoId']),
  77. 'thumbnail': section['thumbnail']['thumbnails'][-1]['url'],
  78. })
  79. try:
  80. token = result_json['onResponseReceivedCommands'][0]\
  81. .get('appendContinuationItemsAction')['continuationItems'][1]\
  82. .get('continuationItemRenderer')['continuationEndpoint']\
  83. .get('continuationCommand')['token']
  84. results.append({
  85. "engine_data": token,
  86. "key": "next_page_token",
  87. })
  88. except:
  89. pass
  90. return results
  91. def parse_first_page_response(response_text):
  92. results = []
  93. results_data = response_text[response_text.find('ytInitialData'):]
  94. results_data = results_data[results_data.find('{'):results_data.find(';</script>')]
  95. results_json = loads(results_data) if results_data else {}
  96. sections = results_json.get('contents', {})\
  97. .get('twoColumnSearchResultsRenderer', {})\
  98. .get('primaryContents', {})\
  99. .get('sectionListRenderer', {})\
  100. .get('contents', [])
  101. for section in sections:
  102. if "continuationItemRenderer" in section:
  103. next_page_token = section["continuationItemRenderer"]\
  104. .get("continuationEndpoint", {})\
  105. .get("continuationCommand", {})\
  106. .get("token", "")
  107. if next_page_token:
  108. results.append({
  109. "engine_data": next_page_token,
  110. "key": "next_page_token",
  111. })
  112. for video_container in section.get('itemSectionRenderer', {}).get('contents', []):
  113. video = video_container.get('videoRenderer', {})
  114. videoid = video.get('videoId')
  115. if videoid is not None:
  116. url = base_youtube_url + videoid
  117. thumbnail = 'https://i.ytimg.com/vi/' + videoid + '/hqdefault.jpg'
  118. title = get_text_from_json(video.get('title', {}))
  119. content = get_text_from_json(video.get('descriptionSnippet', {}))
  120. embedded = embedded_url.format(videoid=videoid)
  121. author = get_text_from_json(video.get('ownerText', {}))
  122. length = get_text_from_json(video.get('lengthText', {}))
  123. # append result
  124. results.append({'url': url,
  125. 'title': title,
  126. 'content': content,
  127. 'author': author,
  128. 'length': length,
  129. 'template': 'videos.html',
  130. 'embedded': embedded,
  131. 'thumbnail': thumbnail})
  132. # return results
  133. return results
  134. def get_text_from_json(element):
  135. if 'runs' in element:
  136. return reduce(lambda a, b: a + b.get('text', ''), element.get('runs'), '')
  137. else:
  138. return element.get('simpleText', '')