youtube_noapi.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. with open("/tmp/x", "w") as f:
  61. f.write(response_text)
  62. for section in (result_json['onResponseReceivedCommands'][0]
  63. .get('appendContinuationItemsAction')['continuationItems'][0]
  64. .get('itemSectionRenderer')['contents']):
  65. if 'videoRenderer' not in section:
  66. continue
  67. section = section['videoRenderer']
  68. content = "-"
  69. if 'descriptionSnippet' in section:
  70. content = ' '.join(x['text'] for x in section['descriptionSnippet']['runs'])
  71. results.append({
  72. 'url': base_youtube_url + section['videoId'],
  73. 'title': ' '.join(x['text'] for x in section['title']['runs']),
  74. 'content': content,
  75. 'author': section['ownerText']['runs'][0]['text'],
  76. 'length': section['lengthText']['simpleText'],
  77. 'template': 'videos.html',
  78. 'embedded': embedded_url.format(videoid=section['videoId']),
  79. 'thumbnail': section['thumbnail']['thumbnails'][-1]['url'],
  80. })
  81. try:
  82. token = result_json['onResponseReceivedCommands'][0]\
  83. .get('appendContinuationItemsAction')['continuationItems'][1]\
  84. .get('continuationItemRenderer')['continuationEndpoint']\
  85. .get('continuationCommand')['token']
  86. results.append({
  87. "engine_data": token,
  88. "key": "next_page_token",
  89. })
  90. except:
  91. pass
  92. return results
  93. def parse_first_page_response(response_text):
  94. results = []
  95. results_data = response_text[response_text.find('ytInitialData'):]
  96. results_data = results_data[results_data.find('{'):results_data.find(';</script>')]
  97. results_json = loads(results_data) if results_data else {}
  98. sections = results_json.get('contents', {})\
  99. .get('twoColumnSearchResultsRenderer', {})\
  100. .get('primaryContents', {})\
  101. .get('sectionListRenderer', {})\
  102. .get('contents', [])
  103. for section in sections:
  104. if "continuationItemRenderer" in section:
  105. next_page_token = section["continuationItemRenderer"]\
  106. .get("continuationEndpoint", {})\
  107. .get("continuationCommand", {})\
  108. .get("token", "")
  109. if next_page_token:
  110. results.append({
  111. "engine_data": next_page_token,
  112. "key": "next_page_token",
  113. })
  114. for video_container in section.get('itemSectionRenderer', {}).get('contents', []):
  115. video = video_container.get('videoRenderer', {})
  116. videoid = video.get('videoId')
  117. if videoid is not None:
  118. url = base_youtube_url + videoid
  119. thumbnail = 'https://i.ytimg.com/vi/' + videoid + '/hqdefault.jpg'
  120. title = get_text_from_json(video.get('title', {}))
  121. content = get_text_from_json(video.get('descriptionSnippet', {}))
  122. embedded = embedded_url.format(videoid=videoid)
  123. author = get_text_from_json(video.get('ownerText', {}))
  124. length = get_text_from_json(video.get('lengthText', {}))
  125. # append result
  126. results.append({'url': url,
  127. 'title': title,
  128. 'content': content,
  129. 'author': author,
  130. 'length': length,
  131. 'template': 'videos.html',
  132. 'embedded': embedded,
  133. 'thumbnail': thumbnail})
  134. # return results
  135. return results
  136. def get_text_from_json(element):
  137. if 'runs' in element:
  138. return reduce(lambda a, b: a + b.get('text', ''), element.get('runs'), '')
  139. else:
  140. return element.get('simpleText', '')