Created
March 6, 2012 23:30
-
-
Save trojkat/1989762 to your computer and use it in GitHub Desktop.
django-shortcodes - YouTube parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#~ # -*- coding: utf-8 -*- | |
from urlparse import urlparse, parse_qs | |
from django.template import Template, Context | |
from django.conf import settings | |
def video_id(value): | |
""" | |
Examples: | |
- http://youtu.be/SA2iWivDJiE | |
- http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu | |
- http://www.youtube.com/embed/SA2iWivDJiE | |
- http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US | |
""" | |
query = urlparse(value) | |
if query.hostname == 'youtu.be': | |
return query.path[1:] | |
if query.hostname in ('www.youtube.com', 'youtube.com'): | |
if query.path == '/watch': | |
p = parse_qs(query.query) | |
return p['v'][0] | |
if query.path[:7] == '/embed/': | |
return query.path.split('/')[2] | |
if query.path[:3] == '/v/': | |
return query.path.split('/')[2] | |
return None | |
def parse(kwargs): | |
url = kwargs.get('url') | |
if not url: | |
return "[Add video url]" | |
id = video_id(url) | |
if id is None: | |
return "[Bad url]" | |
width = int(kwargs.get('width', getattr(settings, 'SHORTCODES_YOUTUBE_WIDTH', 425))) | |
height = int(kwargs.get('height', getattr(settings, 'SHORTCODES_YOUTUBE_HEIGHT', 0))) | |
if height == 0: | |
height = int(round(width / 425.0 * 344.0)) | |
return '<iframe width="%s" height="%s" src="http://www.youtube.com/embed/%s?wmode=opaque" frameborder="0" allowfullscreen></iframe>' % (width, height, id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment