def extract_oembeds(text, args=None): """ Extract oembed resources from a block of text. Returns a list of dictionaries. Max width & height can be specified: {% for embed in block_of_text|extract_oembeds:"400x300" %} Resource type can be specified: {% for photo_embed in block_of_text|extract_oembeds:"photo" %} Or both: {% for embed in block_of_text|extract_oembeds:"400x300xphoto" %} """ resource_type = width = height = None if args: dimensions = args.lower().split('x') if len(dimensions) in (3, 1): resource_type = dimensions.pop() if len(dimensions) == 2: width, height = map(lambda x: int(x), dimensions) client = OEmbedConsumer() return client.extract(text, width, height, resource_type)
def extract_oembeds(input, args=None): """ Extract oembed resources from a block of text. Returns a list of dictionaries. Max width & height can be specified: {% for embed in block_of_text|extract_oembeds:"400x300" %} Resource type can be specified: {% for photo_embed in block_of_text|extract_oembeds:"photo" %} Or both: {% for embed in block_of_text|extract_oembeds:"400x300xphoto" %} """ resource_type = width = height = None if args: dimensions = args.lower().split("x") if len(dimensions) in (3, 1): resource_type = dimensions.pop() if len(dimensions) == 2: width, height = map(lambda x: int(x), dimensions) elif len(dimensions) != 0: raise template.TemplateSyntaxError( "OEmbed's optional WIDTHxHEIGH" "T argument requires WIDTH and HEIGHT to be positive integers." ) client = OEmbedConsumer() return client.extract(input, width, height, resource_type)
def oembed_filter(input, args=None): if args: dimensions = args.lower().split('x') if len(dimensions) != 2: raise template.TemplateSyntaxError("Usage: [width]x[height], e.g. 600x400") width, height = map(int, dimensions) else: width = height = None client = OEmbedConsumer() return mark_safe(client.parse(input, width, height))
def oembed_filter(input, args=None): if args: dimensions = args.lower().split('x') if len(dimensions) != 2: raise template.TemplateSyntaxError( "Usage: [width]x[height], e.g. 600x400") width, height = map(int, dimensions) else: width = height = None client = OEmbedConsumer() return mark_safe(client.parse(input, width, height))
def embed(request, slug): try: import oembed except: raise NotImplementedError oembed.autodiscover() from oembed.consumer import OEmbedConsumer client = OEmbedConsumer() embedded = client.parse_text(request.build_absolute_uri().replace('/embed/', '/').replace(request.get_host(), Site.objects.get_current().domain)) return HttpResponse(embedded)
def oembed_filter(input, args=None): if args: dimensions = args.lower().split("x") if len(dimensions) != 2: raise template.TemplateSyntaxError( "OEmbed's optional WIDTHxHEIGH" "argument requires WIDTH and HEIGHT to be positive integers." ) width, height = map(int, dimensions) else: width = height = None client = OEmbedConsumer() return mark_safe(client.parse(input, width, height))
def render(self, context): kwargs = {} if self.width and self.height: kwargs["maxwidth"] = self.width kwargs["maxheight"] = self.height kwargs["template_dir"] = self.template_dir kwargs["context"] = context client = OEmbedConsumer() parsed = client.parse(self.nodelist.render(context), **kwargs) if self.var_name: context[self.var_name] = parsed return "" else: return parsed
def render(self, context): kwargs = {} if self.width and self.height: kwargs['maxwidth'] = self.width kwargs['maxheight'] = self.height kwargs['template_dir'] = self.template_dir kwargs['context'] = context client = OEmbedConsumer() parsed = client.parse(self.nodelist.render(context), **kwargs) if self.var_name: context[self.var_name] = parsed return '' else: return parsed
def render(self, context): kwargs = {'context': context} if self.width and self.height: kwargs['maxwidth'] = self.width kwargs['maxheight'] = self.height if self.template_dir: kwargs['template_dir'] = self.template_dir client = OEmbedConsumer() parsed = client.parse(self.nodelist.render(context), **kwargs) if self.var_name: context[self.var_name] = parsed return '' else: return parsed
def embed_filter(input, args=None): if args: dimensions = args.lower().split('x') if len(dimensions) != 2: raise template.TemplateSyntaxError("OEmbed's optional WIDTHxHEIGH" \ "argument requires WIDTH and HEIGHT to be positive integers.") width, height = map(int, dimensions) else: width = height = None client = OEmbedConsumer() parsed = client.parse(input, width, height) # @todo: find better solution to detect parsing results if client.extract(input, width, height): return mark_safe(parsed) return ''
def consume_json(request): """ Extract and return oembed content for given urls. Required GET params: urls - list of urls to consume Optional GET params: width - maxwidth attribute for oembed content height - maxheight attribute for oembed content template_dir - template_dir to use when rendering oembed Returns: list of dictionaries with oembed metadata and renderings, json encoded """ client = OEmbedConsumer() urls = request.GET.getlist('urls') width = request.GET.get('width') height = request.GET.get('height') template_dir = request.GET.get('template_dir') output = {} ctx = RequestContext(request) for url in urls: try: provider = oembed.site.provider_for_url(url) except OEmbedMissingEndpoint: oembeds = None rendered = None else: oembeds = url rendered = client.parse_text(url, width, height, context=ctx, template_dir=template_dir) output[url] = { 'oembeds': oembeds, 'rendered': rendered, } return HttpResponse(json.dumps(output), mimetype='application/json')
class ConsumerTestCase(BaseOEmbedTestCase): def setUp(self): "Set up test environment" super(ConsumerTestCase, self).setUp() self.oembed_client = OEmbedConsumer() def test_parse_text(self): consumed = self.oembed_client.parse_text(self.category_url) self.assertEqual(consumed, self.category_embed) def test_parse_html(self): consumed = self.oembed_client.parse_html('<p>%s</p>' % self.category_url) self.assertEqual(consumed, '<p>%s</p>' % self.category_embed) def test_extract_oembeds(self): embeds = self.oembed_client.extract_oembeds(self.category_url) self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds(self.category_url, resource_type='photo') self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds(self.category_url, resource_type='video') self.assertEqual(len(embeds), 0) def test_extract_oembeds_html(self): embeds = self.oembed_client.extract_oembeds_html('<p>%s</p>' % self.category_url) self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds_html('<p>%s</p>' % self.category_url, resource_type='photo') self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds_html('<p>%s</p>' % self.category_url, resource_type='video') self.assertEqual(len(embeds), 0) embeds = self.oembed_client.extract_oembeds_html('<p><a href="%s">Some link</a></p>' % self.category_url) self.assertEqual(len(embeds), 0) embeds = self.oembed_client.extract_oembeds_html('<p><a href="/some-link/">%s</a></p>' % self.category_url) self.assertEqual(len(embeds), 0)
def consume_json(request): """ Extract and return oembed content for given urls. Required GET params: urls - list of urls to consume Optional GET params: width - maxwidth attribute for oembed content height - maxheight attribute for oembed content template_dir - template_dir to use when rendering oembed Returns: list of dictionaries with oembed metadata and renderings, json encoded """ client = OEmbedConsumer() urls = request.GET.getlist('urls') width = request.GET.get('width') height = request.GET.get('height') template_dir = request.GET.get('template_dir') output = {} ctx = RequestContext(request) for url in urls: try: provider = oembed.site.provider_for_url(url) except OEmbedMissingEndpoint: oembeds = None rendered = None else: oembeds = url rendered = client.parse_text(url, width, height, context=ctx, template_dir=template_dir) output[url] = { 'oembeds': oembeds, 'rendered': rendered, } return HttpResponse(simplejson.dumps(output), mimetype='application/json')
def strip_oembeds(text, args=None): """ Take a block of text and strip all the embeds from it, optionally taking a maxwidth, maxheight / resource_type Usage: {{ post.content|strip_embeds }} {{ post.content|strip_embeds:"600x600xphoto" }} {{ post.content|strip_embeds:"video" }} """ resource_type = width = height = None if args: dimensions = args.lower().split('x') if len(dimensions) in (3, 1): resource_type = dimensions.pop() if len(dimensions) == 2: width, height = map(lambda x: int(x), dimensions) client = OEmbedConsumer() return mark_safe(client.strip(text, width, height, resource_type))
class ConsumerTestCase(BaseOEmbedTestCase): def setUp(self): "Set up test environment" super(ConsumerTestCase, self).setUp() self.oembed_client = OEmbedConsumer() def test_parse_text(self): consumed = self.oembed_client.parse_text(self.category_url) self.assertEqual(consumed, self.category_embed) def test_parse_html(self): consumed = self.oembed_client.parse_html('<p>%s</p>' % self.category_url) self.assertEqual(consumed, '<p>%s</p>' % self.category_embed) def test_extract_oembeds(self): embeds = self.oembed_client.extract_oembeds(self.category_url) self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds(self.category_url, resource_type='photo') self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds(self.category_url, resource_type='video') self.assertEqual(len(embeds), 0) def test_extract_oembeds_html(self): embeds = self.oembed_client.extract_oembeds_html('<p>%s</p>' % self.category_url) self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds_html('<p>%s</p>' % self.category_url, resource_type='photo') self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds_html('<p>%s</p>' % self.category_url, resource_type='video') self.assertEqual(len(embeds), 0) embeds = self.oembed_client.extract_oembeds_html( '<p><a href="%s">Some link</a></p>' % self.category_url) self.assertEqual(len(embeds), 0) embeds = self.oembed_client.extract_oembeds_html( '<p><a href="/some-link/">%s</a></p>' % self.category_url) self.assertEqual(len(embeds), 0) def test_strip(self): test_string = 'testing [%s] [http://www.google.com]' % self.category_url expected = 'testing [] [http://www.google.com]' self.assertEqual(self.oembed_client.strip(test_string), expected) # with width & height self.assertEqual(self.oembed_client.strip(test_string, 600, 400), expected) # with resource_type self.assertEqual( self.oembed_client.strip(test_string, resource_type='photo'), expected) self.assertEqual( self.oembed_client.strip(test_string, resource_type='link'), test_string) def test_strip_html(self): test_string = '<a href="%(match)s">%(match)s</a> <p>%(no_match)s</p>' % \ {'match': self.category_url, 'no_match': 'http://www.google.com'} expected = test_string self.assertEqual(self.oembed_client.strip(test_string), expected) def test_strip_html_failure(self): # show how strip can fail when handling html - it picks up the match # in the p tag then replaces it everywhere, including in the a tags test_string = '<a href="%(match)s">%(match)s</a> <p>%(match)s</p> <p>%(no_match)s</p>' % \ {'match': self.category_url, 'no_match': 'http://www.google.com'} expected = test_string actual = '<a href=""></a> <p></p> <p>http://www.google.com</p>' self.assertEqual(self.oembed_client.strip(test_string), actual)
def setUp(self): "Set up test environment" super(ConsumerTestCase, self).setUp() self.oembed_client = OEmbedConsumer()
class ConsumerTestCase(BaseOEmbedTestCase): def setUp(self): "Set up test environment" super(ConsumerTestCase, self).setUp() self.oembed_client = OEmbedConsumer() def test_parse_text(self): consumed = self.oembed_client.parse_text(self.category_url) self.assertEqual(consumed, self.category_embed) def test_parse_html(self): consumed = self.oembed_client.parse_html('<p>%s</p>' % self.category_url) self.assertEqual(consumed, '<p>%s</p>' % self.category_embed) def test_extract_oembeds(self): embeds = self.oembed_client.extract_oembeds(self.category_url) self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds(self.category_url, resource_type='photo') self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds(self.category_url, resource_type='video') self.assertEqual(len(embeds), 0) def test_extract_oembeds_html(self): embeds = self.oembed_client.extract_oembeds_html('<p>%s</p>' % self.category_url) self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds_html('<p>%s</p>' % self.category_url, resource_type='photo') self.assertEqual(len(embeds), 1) self.assertEqual(embeds[0]['original_url'], self.category_url) embeds = self.oembed_client.extract_oembeds_html('<p>%s</p>' % self.category_url, resource_type='video') self.assertEqual(len(embeds), 0) embeds = self.oembed_client.extract_oembeds_html('<p><a href="%s">Some link</a></p>' % self.category_url) self.assertEqual(len(embeds), 0) embeds = self.oembed_client.extract_oembeds_html('<p><a href="/some-link/">%s</a></p>' % self.category_url) self.assertEqual(len(embeds), 0) def test_strip(self): test_string = 'testing [%s] [http://www.google.com]' % self.category_url expected = 'testing [] [http://www.google.com]' self.assertEqual(self.oembed_client.strip(test_string), expected) # with width & height self.assertEqual(self.oembed_client.strip(test_string, 600, 400), expected) # with resource_type self.assertEqual(self.oembed_client.strip(test_string, resource_type='photo'), expected) self.assertEqual(self.oembed_client.strip(test_string, resource_type='link'), test_string) def test_strip_html(self): test_string = '<a href="%(match)s">%(match)s</a> <p>%(no_match)s</p>' % \ {'match': self.category_url, 'no_match': 'http://www.google.com'} expected = test_string self.assertEqual(self.oembed_client.strip(test_string), expected) def test_strip_html_failure(self): # show how strip can fail when handling html - it picks up the match # in the p tag then replaces it everywhere, including in the a tags test_string = '<a href="%(match)s">%(match)s</a> <p>%(match)s</p> <p>%(no_match)s</p>' % \ {'match': self.category_url, 'no_match': 'http://www.google.com'} expected = test_string actual = '<a href=""></a> <p></p> <p>http://www.google.com</p>' self.assertEqual(self.oembed_client.strip(test_string), actual)
def oembed_replace(text): consumer = OEmbedConsumer() return consumer.parse(text)
from django.db import models from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core.exceptions import ValidationError import oembed from oembed.consumer import OEmbedConsumer from polymorphic import PolymorphicModel from autoslug import AutoSlugField from filebrowser.fields import FileBrowseField oembed_consumer = OEmbedConsumer() class Attachment(PolymorphicModel): class Meta: ordering = ('-creation', ) oembed = models.CharField(max_length=100, verbose_name=_('oembed')) creation = models.DateTimeField(editable=False, auto_now=True) slug = AutoSlugField(populate_from='_slug', unique=True) @models.permalink def get_absolute_url(self): return 'attachments:detail', (), {'slug': self.slug} def clean(self):