Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions oembed/core.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import re
import urllib2
import gzip
import json
from heapq import heappush, heappop
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
import simplejson
except ImportError:
from django.utils import simplejson
from django.conf import settings
from django.utils.safestring import mark_safe
from oembed.models import ProviderRule, StoredOEmbed
Expand Down Expand Up @@ -62,18 +59,18 @@ def match_compare(x, y):
return x.start() - y.start()
prev_end = 0
iter_dict = dict((r, r.finditer(text)) for r in regex_list)

# a heapq containing matches
matches = []

# bootstrap the search with the first hit for each iterator
for regex, iterator in iter_dict.items():
try:
match = iterator.next()
heappush(matches, (match.start(), match))
except StopIteration:
iter_dict.pop(regex)

# process matches, revisiting each iterator from which a match is used
while matches:
# get the earliest match
Expand Down Expand Up @@ -102,12 +99,12 @@ def replace(text, max_width=MAX_WIDTH, max_height=MAX_HEIGHT):
"""
Scans a block of text, replacing anything matched by a ``ProviderRule``
pattern with an OEmbed html snippet, if possible.

Templates should be stored at oembed/{format}.html, so for example:

oembed/video.html
These templates are passed a context variable, ``response``, which is a

These templates are passed a context variable, ``response``, which is a
dictionary representation of the response.
"""
rules = list(ProviderRule.objects.all())
Expand Down Expand Up @@ -137,7 +134,7 @@ def replace(text, max_width=MAX_WIDTH, max_height=MAX_HEIGHT):
if to_append:
parts.append(to_append)
index += 1
# Now we fetch a list of all stored patterns, and put it in a dictionary
# Now we fetch a list of all stored patterns, and put it in a dictionary
# mapping the URL to to the stored model instance.
for stored_embed in StoredOEmbed.objects.filter(match__in=urls, max_width=max_width, max_height = max_height):
stored[stored_embed.match] = stored_embed
Expand All @@ -156,12 +153,12 @@ def replace(text, max_width=MAX_WIDTH, max_height=MAX_HEIGHT):
rule.endpoint, part, max_width, max_height, FORMAT
)
# Fetch the link and parse the JSON.
resp = simplejson.loads(fetch(url))
resp = json.loads(fetch(url))

# link types that don't have html elements aren't dealt with right now.
if resp['type'] == 'link' and 'html' not in resp:
raise ValueError

# Depending on the embed type, grab the associated template and
# pass it the parsed JSON response as context.
replacement = render_to_string('oembed/%s.html' % resp['type'], {'response': resp})
Expand Down