Youtube plugin no longer relies on locale (fixes #53)

The plugin relied on the locale module to provide digit grouping of the view count. It could cause various encoding issues.
The digit grouping is now based on a simple homemade function.
This commit is contained in:
stoneLeaf 2012-04-15 20:54:58 +02:00 committed by Ryan Hitchman
parent 4f1d49ef04
commit 420bb2bf21
1 changed files with 13 additions and 11 deletions

View File

@ -1,19 +1,16 @@
import locale
import re import re
import time import time
from util import hook, http from util import hook, http
locale.setlocale(locale.LC_ALL, '')
youtube_re = (r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)' youtube_re = (r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)'
'([-_a-z0-9]+)', re.I) '([-_a-z0-9]+)', re.I)
base_url = 'http://gdata.youtube.com/feeds/api/' base_url = 'http://gdata.youtube.com/feeds/api/'
url = base_url + 'videos/%s?v=2&alt=jsonc' url = base_url + 'videos/%s?v=2&alt=jsonc'
search_api_url = base_url + 'videos?v=2&alt=jsonc&max-results=1' search_api_url = base_url + 'videos?v=2&alt=jsonc&max-results=1'
video_url = "http://youtube.com/watch?v=%s" video_url = 'http://youtube.com/watch?v=%s'
def get_video_description(vid_id): def get_video_description(vid_id):
@ -41,21 +38,26 @@ def get_video_description(vid_id):
out += ' - rated \x02%.2f/5.0\x02 (%d)' % (j['rating'], out += ' - rated \x02%.2f/5.0\x02 (%d)' % (j['rating'],
j['ratingCount']) j['ratingCount'])
# The use of str.decode() prevents UnicodeDecodeError with some locales
# See http://stackoverflow.com/questions/4082645/
if 'viewCount' in j: if 'viewCount' in j:
out += ' - \x02%s\x02 views' % locale.format('%d', out += ' - \x02%s\x02 views' % group_int_digits(j['viewCount'])
j['viewCount'], 1).decode(locale.getlocale()[1])
upload_time = time.strptime(j['uploaded'], "%Y-%m-%dT%H:%M:%S.000Z") upload_time = time.strptime(j['uploaded'], "%Y-%m-%dT%H:%M:%S.000Z")
out += ' - \x02%s\x02 on \x02%s\x02' % (j['uploader'], out += ' - \x02%s\x02 on \x02%s\x02' % (
time.strftime("%Y.%m.%d", upload_time)) j['uploader'], time.strftime("%Y.%m.%d", upload_time))
if 'contentRating' in j: if 'contentRating' in j:
out += ' - \x034NSFW\x02' out += ' - \x034NSFW\x02'
return out return out
def group_int_digits(number, delimiter=' ', grouping=3):
base = str(number).strip()
builder = []
while base:
builder.append(base[-grouping:])
base = base[:-grouping]
builder.reverse()
return delimiter.join(builder)
@hook.regex(*youtube_re) @hook.regex(*youtube_re)
def youtube_url(match): def youtube_url(match):
@ -71,7 +73,7 @@ def youtube(inp):
j = http.get_json(search_api_url, q=inp) j = http.get_json(search_api_url, q=inp)
if 'error' in j: if 'error' in j:
return 'error performing search' return 'error while performing the search'
if j['data']['totalItems'] == 0: if j['data']['totalItems'] == 0:
return 'no results found' return 'no results found'