rewrite youtube plugin to use json instead of lxml.etree and to be more flexible

This commit is contained in:
Ryan Hitchman 2010-02-12 22:13:55 -07:00
parent 9b47d394ad
commit 9d139d8760
1 changed files with 29 additions and 31 deletions

View File

@ -1,41 +1,39 @@
import re
from lxml import etree
import json
import locale
import re
import urllib2
from util import hook
locale.setlocale(locale.LC_ALL, '')
def ytdata(id):
url = 'http://gdata.youtube.com/feeds/api/videos/' + id
x = etree.parse(url)
# I can't figure out how to deal with schemas/namespaces properly :(
yt = '{http://gdata.youtube.com/schemas/2007}'
media = '{http://search.yahoo.com/mrss/}'
rating = x.find('{http://schemas.google.com/g/2005}rating')
data = dict(rating.items())
data['title'] = x.find('{http://www.w3.org/2005/Atom}title').text
data['views'] = locale.format('%d', int(x.find(yt + 'statistics').get(
'viewCount')), 1)
length = int(x.find(media + 'group/' + yt + 'duration').get('seconds'))
data['length'] = ''
if length / 3600: # > 1 hour
data['length'] += str(length/3600) + 'h '
if length / 60: # > 1 minute
data['length'] += str(length/60 % 60) + 'm '
data['length'] += "%ds" % (length % 60)
return data
youtube_re = re.compile(r'.*youtube.*v=([-_a-z0-9]+)', flags=re.IGNORECASE)
youtube_re = re.compile(r'.*youtube.*v=([-_a-z0-9]+)', flags=re.I)
url = 'http://gdata.youtube.com/feeds/api/videos/%s?alt=json'
#@hook.command(hook=r'(.*)', prefix=False)
def youtube(inp):
m = youtube_re.match(inp)
if m:
data = ytdata(m.group(1))
return '\x02%(title)s\x02 - rated \x02%(average)s/%(max)s\x02 ' \
'(%(numRaters)s) - views \x02%(views)s\x02 - length \x02' \
'%(length)s\x02' % data
j = json.load(urllib2.urlopen(url % m.group(1)))['entry']
out = '\x02%s\x02' % j['title']['$t']
rating = j.get('gd$rating')
if rating:
out += ' - rated \x02%.2f/%.1f\x02 (%d)' % (rating['average'],
rating['max'], rating['numRaters'])
stats = j.get('yt$statistics')
if stats:
view_count = int(stats['viewCount'])
out += ' - views \x02%s\x02' % locale.format('%d', view_count, 1)
out += ' - length \x02'
length = int(j['media$group']['yt$duration']['seconds'])
if length / 3600: # > 1 hour
out += '%dh ' % (length / 3600)
if length / 60:
out += '%dm ' % (length / 60 % 60)
out += "%ds" % (length % 60)
return out