2018-10-08 00:01:35 +00:00
|
|
|
from django.conf import settings
|
2018-10-29 16:52:09 +00:00
|
|
|
from external.pytaw.pytaw.youtube import YouTube, Channel, Playlist, PlaylistItem, Thumbnail, InvalidURL, Resource, Video
|
|
|
|
from typing import Optional
|
2018-10-08 00:01:35 +00:00
|
|
|
|
|
|
|
|
2018-10-29 16:52:09 +00:00
|
|
|
class YoutubeAPI(YouTube):
|
2018-10-08 00:01:35 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def build_public() -> 'YoutubeAPI':
|
2018-10-29 16:52:09 +00:00
|
|
|
return YoutubeAPI(key=settings.YOUTUBE_API_KEY)
|
2018-10-08 00:01:35 +00:00
|
|
|
|
2018-10-29 16:52:09 +00:00
|
|
|
# @staticmethod
|
|
|
|
# def build_oauth() -> 'YoutubeAPI':
|
|
|
|
# flow =
|
|
|
|
# credentials =
|
|
|
|
# service = build(API_SERVICE_NAME, API_VERSION, credentials)
|
2018-10-08 00:01:35 +00:00
|
|
|
|
|
|
|
|
2018-10-29 16:52:09 +00:00
|
|
|
def default_thumbnail(resource: Resource) -> Optional[Thumbnail]:
|
|
|
|
"""
|
|
|
|
Gets the default thumbnail for a resource.
|
|
|
|
Searches in the list of thumbnails for one with the label 'default', or takes the first one.
|
|
|
|
:param resource:
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
thumbs = getattr(resource, 'thumbnails', None)
|
2018-10-08 00:01:35 +00:00
|
|
|
|
2018-10-29 16:52:09 +00:00
|
|
|
if thumbs is None or len(thumbs) <= 0:
|
|
|
|
return None
|
2018-10-08 00:01:35 +00:00
|
|
|
|
2018-10-29 16:52:09 +00:00
|
|
|
return next(
|
|
|
|
(i for i in thumbs if i.id == 'default'),
|
|
|
|
thumbs[0]
|
|
|
|
)
|
2018-10-08 00:01:35 +00:00
|
|
|
|
2018-10-21 22:02:51 +00:00
|
|
|
|
2018-10-29 16:52:09 +00:00
|
|
|
def best_thumbnail(resource: Resource) -> Optional[Thumbnail]:
|
|
|
|
"""
|
|
|
|
Gets the best thumbnail available for a resource.
|
|
|
|
:param resource:
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
thumbs = getattr(resource, 'thumbnails', None)
|
2018-10-21 22:02:51 +00:00
|
|
|
|
2018-10-29 16:52:09 +00:00
|
|
|
if thumbs is None or len(thumbs) <= 0:
|
|
|
|
return None
|
2018-10-21 22:02:51 +00:00
|
|
|
|
2018-10-29 16:52:09 +00:00
|
|
|
return max(thumbs, key=lambda t: t.width * t.height)
|