Skip to content

Instantly share code, notes, and snippets.

@embedly
Created June 1, 2010 21:57
Show Gist options
  • Save embedly/421571 to your computer and use it in GitHub Desktop.
Save embedly/421571 to your computer and use it in GitHub Desktop.
import urllib2
import urllib
import json
import memcache
import re
#[url=http://example.com]Example[/url] OR [url]http://example.com[/url]
bbcode_url_re = re.compile('\[url(|\=(?P<url>.*?))\](?P<url_or_title>.*?)\[/url]')
cache = memcache.Client(['127.0.0.1:11211'])
MAX_WIDTH = 600
def get_services():
result = cache.get('embedly_services')
if result is None:
result = urllib2.urlopen('http://api.embed.ly/v1/api/services/python').read()
cache.set('embedly_services', result, 60*60*24)
return json.loads(result)
def get_oembed(url):
params = {'url' : url,
'maxwidth' : MAX_WIDTH,
'format' : 'json'}
fetch_url = 'http://api.embed.ly/v1/api/oembed?%s' % urllib.urlencode(params)
try:
result = urllib2.urlopen(fetch_url).read()
except:
return None
return json.loads(result)
def match(url):
for service in get_services():
for regex in service['regex']:
if re.match(regex, url):
return True
return False
def replace(matchobj):
url = matchobj.groupdict().get('url', None)
title = matchobj.groupdict().get('url_or_title', None)
if url is None and title:
url = title
title is None
#Not Something Embedly Handles
if not match(url):
matchobj.group()
oembed = get_oembed(url)
#embed was not found or it's a link type
if oembed is None or oembed['type'] == 'link':
return matchobj.group()
elif oembed['type'] in ['video', 'rich']:
return '<div class="embed">%s</div>' % oembed['html']
elif oembed['type'] == 'photo':
return '<div class="embed"><a href="%s" title="%s"><img src="%s"></img></a></div>'% (url,oembed.get('title', ''), oembed['url'])
#bad type?
return matchobj.group()
def parse(text):
"""
Parse a piece of text for bbcodes and insert the correct embed code
"""
return bbcode_url_re.sub(replace, text, re.M )
if __name__ == '__main__':
random_text = """ This is some text
[url]http://soundcloud.com/jameszabiela/blame-edit[/url] replaced
[url=http://twitpic.com/1sw5l1]Nice Hair[/url] replaced
[url=http://example.com]Example[/url] not replaced
"""
print parse(random_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment