Repository navigation
Expand file tree
/
Copy pathexternal.py
More file actions
116 lines (94 loc) · 3.4 KB
/
Copy pathexternal.py
File metadata and controls
116 lines (94 loc) · 3.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
from hashlib import md5
import requests
from django import forms
from django.core.cache import cache
from django.db import models
from django.utils.html import mark_safe
from django.utils.translation import ugettext, ugettext_lazy as _
from content_editor.admin import ContentEditorInline
__all__ = ('External', 'ExternalInline', 'oembed_html', 'render_external')
def oembed_html(url, cache_failures=True):
"""
Asks noembed.com for the embedding HTML code for arbitrary URLs. Sites
supported include Youtube, Vimeo, Twitter and many others.
Successful embeds are always cached for 30 days.
Failures are cached if ``cache_failures`` is ``True`` (the default). The
durations are as follows:
- Connection errors are cached 60 seconds with the hope that the connection
failure is only transient.
- HTTP errors codes and responses in an unexpected format (no JSON) are
cached for 24 hours.
The return value is always either a HTML fragment or an empty string.
"""
# Thundering herd problem etc...
key = 'oembed-url-%s' % md5(url.encode('utf-8')).hexdigest()
html = cache.get(key)
if html is not None:
return html
try:
html = requests.get(
'https://noembed.com/embed',
params={
'url': url,
'nowrap': 'on',
'maxwidth': 1200,
'maxheight': 800,
},
timeout=2,
).json().get('html', '')
except requests.ConnectionError:
# Connection failed? Hopefully temporary, try again soon.
if cache_failures:
cache.set(key, '', timeout=60)
return ''
except (ValueError, requests.HTTPError):
# Oof... HTTP error code, or no JSON? Try again tomorrow,
# and we should really log this.
if cache_failures:
cache.set(key, '', timeout=86400)
return ''
else:
# Perfect, cache for 30 days
cache.set(key, html, timeout=30 * 86400)
return html
def render_external(plugin, **kwargs):
"""
Render the plugin, embedding it in the appropriate markup for Foundation's
flex-video element (http://foundation.zurb.com/sites/docs/flex-video.html)
"""
html = oembed_html(plugin.url)
if 'youtube.com' in html:
return mark_safe(
'<div class="flex-video widescreen">{}</div>'.format(html))
if 'vimeo.com' in html:
return mark_safe(
'<div class="flex-video widescreen vimeo">{}</div>'.format(html))
return mark_safe(html)
class External(models.Model):
"""
External content plugin
"""
url = models.URLField(_('URL'))
class Meta:
abstract = True
verbose_name = _('external content')
def __str__(self):
return self.url
class ExternalForm(forms.ModelForm):
"""
Tries fetching the oEmbed code for the given URL when cleaning form data
"""
def clean(self):
data = super(ExternalForm, self).clean()
url = data.get('url')
if url and not oembed_html(url, cache_failures=False):
raise forms.ValidationError(
ugettext('Unable to fetch HTML for this URL, sorry!')
)
return data
class ExternalInline(ContentEditorInline):
"""
Content editor inline using the ``ExternalForm`` to verify whether the
given URL is embeddable using oEmbed or not.
"""
form = ExternalForm