youtube_api.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Youtube (Videos)
  4. """
  5. from json import loads
  6. from dateutil import parser
  7. from urllib.parse import urlencode
  8. from searx.exceptions import SearxEngineAPIException
  9. # about
  10. about = {
  11. "website": 'https://www.youtube.com/',
  12. "wikidata_id": 'Q866',
  13. "official_api_documentation": 'https://developers.google.com/youtube/v3/docs/search/list?apix=true',
  14. "use_official_api": True,
  15. "require_api_key": False,
  16. "results": 'JSON',
  17. }
  18. # engine dependent config
  19. categories = ['videos', 'music']
  20. paging = False
  21. api_key = None
  22. # search-url
  23. base_url = 'https://www.googleapis.com/youtube/v3/search'
  24. search_url = base_url + '?part=snippet&{query}&maxResults=20&key={api_key}'
  25. embedded_url = '<iframe width="540" height="304" ' +\
  26. 'data-src="https://www.youtube-nocookie.com/embed/{videoid}" ' +\
  27. 'frameborder="0" allowfullscreen></iframe>'
  28. base_youtube_url = 'https://www.youtube.com/watch?v='
  29. # do search-request
  30. def request(query, params):
  31. params['url'] = search_url.format(query=urlencode({'q': query}),
  32. api_key=api_key)
  33. # add language tag if specified
  34. if params['language'] != 'all':
  35. params['url'] += '&relevanceLanguage=' + params['language'].split('-')[0]
  36. return params
  37. # get response from search-request
  38. def response(resp):
  39. results = []
  40. search_results = loads(resp.text)
  41. if 'error' in search_results and 'message' in search_results['error']:
  42. raise SearxEngineAPIException(search_results['error']['message'])
  43. # return empty array if there are no results
  44. if 'items' not in search_results:
  45. return []
  46. # parse results
  47. for result in search_results['items']:
  48. videoid = result['id']['videoId']
  49. title = result['snippet']['title']
  50. content = ''
  51. thumbnail = ''
  52. pubdate = result['snippet']['publishedAt']
  53. publishedDate = parser.parse(pubdate)
  54. thumbnail = result['snippet']['thumbnails']['high']['url']
  55. content = result['snippet']['description']
  56. url = base_youtube_url + videoid
  57. embedded = embedded_url.format(videoid=videoid)
  58. # append result
  59. results.append({'url': url,
  60. 'title': title,
  61. 'content': content,
  62. 'template': 'videos.html',
  63. 'publishedDate': publishedDate,
  64. 'embedded': embedded,
  65. 'thumbnail': thumbnail})
  66. # return results
  67. return results