youtube: update to v3 API (old API is deprecated)

This requires a Google API Key with Youtube read permissions enabled.
This commit is contained in:
Ryan Hitchman 2015-05-06 11:34:23 -07:00
parent f7671fce2c
commit b660993dfb
1 changed files with 22 additions and 32 deletions

View File

@ -7,46 +7,35 @@ from util import hook, http
youtube_re = (r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)'
'([-_a-z0-9]+)', re.I)
base_url = 'http://gdata.youtube.com/feeds/api/'
url = base_url + 'videos/%s?v=2&alt=jsonc'
search_api_url = 'https://www.googleapis.com/youtube/v3/search'
base_url = 'https://www.googleapis.com/youtube/v3/'
info_url = base_url + 'videos?part=snippet,contentDetails,statistics'
search_api_url = base_url + 'search'
video_url = 'http://youtube.com/watch?v=%s'
def get_video_description(vid_id):
j = http.get_json(url % vid_id)
def get_video_description(vid_id, api_key):
j = http.get_json(info_url, id=vid_id, key=api_key)
if j.get('error'):
if not j['pageInfo']['totalResults']:
return
j = j['data']
j = j['items'][0]
out = '\x02%s\x02' % j['title']
duration = j['contentDetails']['duration'].replace('PT', '').lower()
if not j.get('duration'):
return out
published = time.strptime(j['snippet']['publishedAt'],
"%Y-%m-%dT%H:%M:%S.000Z")
published = time.strftime("%Y.%m.%d", published)
out += ' - length \x02'
length = j['duration']
if length / 3600: # > 1 hour
out += '%dh ' % (length / 3600)
if length / 60:
out += '%dm ' % (length / 60 % 60)
out += "%ds\x02" % (length % 60)
views = group_int_digits(j['statistics']['viewCount'], ',')
if 'rating' in j:
out += ' - rated \x02%.2f/5.0\x02 (%d)' % (j['rating'],
j['ratingCount'])
out = (u'\x02{snippet[title]}\x02 - length \x02{duration}\x02 - '
u'{statistics[likeCount]}\u2191{statistics[dislikeCount]}\u2193 - '
u'\x02{views}\x02 views - '
u'\x02{snippet[channelTitle]}\x02 on \x02{published}\x02'
).format(duration=duration, views=views, published=published, **j)
if 'viewCount' in j:
out += ' - \x02%s\x02 views' % group_int_digits(j['viewCount'])
upload_time = time.strptime(j['uploaded'], "%Y-%m-%dT%H:%M:%S.000Z")
out += ' - \x02%s\x02 on \x02%s\x02' % (
j['uploader'], time.strftime("%Y.%m.%d", upload_time))
if 'contentRating' in j:
out += ' - \x034NSFW\x02'
# TODO: figure out how to detect NSFW videos
return out
@ -61,9 +50,10 @@ def group_int_digits(number, delimiter=' ', grouping=3):
return delimiter.join(builder)
@hook.api_key('google')
@hook.regex(*youtube_re)
def youtube_url(match):
return get_video_description(match.group(1))
def youtube_url(match, api_key=None):
return get_video_description(match.group(1), api_key)
@hook.api_key('google')
@ -93,4 +83,4 @@ def youtube(inp, api_key=None):
vid_id = j['items'][0]['id']['videoId']
return get_video_description(vid_id) + " - " + video_url % vid_id
return get_video_description(vid_id, api_key) + " - " + video_url % vid_id