youtube_api.py 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Youtube (Videos)
  2. #
  3. # @website https://www.youtube.com/
  4. # @provide-api yes (https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.search.list)
  5. #
  6. # @using-api yes
  7. # @results JSON
  8. # @stable yes
  9. # @parse url, title, content, publishedDate, thumbnail, embedded
  10. from json import loads
  11. from dateutil import parser
  12. from searx.url_utils import urlencode
  13. # engine dependent config
  14. categories = ['videos', 'music']
  15. paging = False
  16. language_support = True
  17. api_key = None
  18. # search-url
  19. base_url = 'https://www.googleapis.com/youtube/v3/search'
  20. search_url = base_url + '?part=snippet&{query}&maxResults=20&key={api_key}'
  21. embedded_url = '<iframe width="540" height="304" ' +\
  22. 'data-src="//www.youtube-nocookie.com/embed/{videoid}" ' +\
  23. 'frameborder="0" allowfullscreen></iframe>'
  24. base_youtube_url = 'https://www.youtube.com/watch?v='
  25. # do search-request
  26. def request(query, params):
  27. params['url'] = search_url.format(query=urlencode({'q': query}),
  28. api_key=api_key)
  29. params['url'] += '&relevanceLanguage=' + params['language'].split('-')[0]
  30. return params
  31. # get response from search-request
  32. def response(resp):
  33. results = []
  34. search_results = loads(resp.text)
  35. # return empty array if there are no results
  36. if 'items' not in search_results:
  37. return []
  38. # parse results
  39. for result in search_results['items']:
  40. videoid = result['id']['videoId']
  41. title = result['snippet']['title']
  42. content = ''
  43. thumbnail = ''
  44. pubdate = result['snippet']['publishedAt']
  45. publishedDate = parser.parse(pubdate)
  46. thumbnail = result['snippet']['thumbnails']['high']['url']
  47. content = result['snippet']['description']
  48. url = base_youtube_url + videoid
  49. embedded = embedded_url.format(videoid=videoid)
  50. # append result
  51. results.append({'url': url,
  52. 'title': title,
  53. 'content': content,
  54. 'template': 'videos.html',
  55. 'publishedDate': publishedDate,
  56. 'embedded': embedded,
  57. 'thumbnail': thumbnail})
  58. # return results
  59. return results