youtube_api.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 urllib import urlencode
  12. from dateutil import parser
  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. # add language tag if specified
  30. if params['language'] != 'all':
  31. params['url'] += '&relevanceLanguage=' + params['language'].split('_')[0]
  32. return params
  33. # get response from search-request
  34. def response(resp):
  35. results = []
  36. search_results = loads(resp.text)
  37. # return empty array if there are no results
  38. if 'items' not in search_results:
  39. return []
  40. # parse results
  41. for result in search_results['items']:
  42. videoid = result['id']['videoId']
  43. title = result['snippet']['title']
  44. content = ''
  45. thumbnail = ''
  46. pubdate = result['snippet']['publishedAt']
  47. publishedDate = parser.parse(pubdate)
  48. thumbnail = result['snippet']['thumbnails']['high']['url']
  49. content = result['snippet']['description']
  50. url = base_youtube_url + videoid
  51. embedded = embedded_url.format(videoid=videoid)
  52. # append result
  53. results.append({'url': url,
  54. 'title': title,
  55. 'content': content,
  56. 'template': 'videos.html',
  57. 'publishedDate': publishedDate,
  58. 'embedded': embedded,
  59. 'thumbnail': thumbnail})
  60. # return results
  61. return results