comparison gpp/oembed/views.py @ 285:8fd4984d5c3b

This is a first rough commit for #95, adding the ability to embed YouTube videos in forum posts. Some more polish and testing needs to happen at this point. I wanted to get all these changes off my hard drive and into the repository.
author Brian Neal <bgneal@gmail.com>
date Thu, 14 Oct 2010 02:39:35 +0000
parents
children 72fd300685d5
comparison
equal deleted inserted replaced
284:df2c81f705a8 285:8fd4984d5c3b
1 """
2 Views for the oembed application.
3 """
4 import re
5 import urllib2
6
7 from django.http import HttpResponse
8 from django.http import HttpResponseBadRequest
9 from django.http import HttpResponseForbidden
10 import django.utils.simplejson as json
11
12 from oembed.models import Provider
13 from oembed.models import Oembed
14 from oembed.core import get_oembed
15
16
17 def fetch_media(request):
18 """
19 This view returns the HTML media of an embeddable resource.
20 This view is the target of an AJAX request.
21 """
22 if not request.user.is_authenticated():
23 return HttpResponseForbidden('Please login or register.')
24
25 url = request.POST.get('q')
26
27 if not url:
28 return HttpResponseBadRequest('Please provide a valid URL.')
29
30 # Is this already in our database?
31 try:
32 oembed = Oembed.objects.get(url=url)
33 except Oembed.DoesNotExist:
34 pass
35 else:
36 data = dict(id=oembed.id, embed=oembed.html)
37 return HttpResponse(json.dumps(data), content_type='application/json')
38
39 # It isn't in the database, try to find it from our providers
40 providers = Provider.objects.all()
41 for provider in providers:
42 if re.match(provider.url_regex, url):
43 try:
44 data = get_oembed(provider.api_endpoint, url)
45 except IOError, e:
46 return HttpResponseBadRequest(
47 "Sorry, we could not retrieve your video (%s)" % e)
48
49 if 'type' not in data or data['type'] != 'video':
50 return HttpResponseBadRequest(
51 "Hey, this doesn't look like a video..??")
52
53 oembed = Oembed(url=url,
54 type=Oembed.VIDEO,
55 title=data.get('title', ''),
56 width=int(data.get('width', 0)),
57 height=int(data.get('height', 0)),
58 html=data.get('html', ''))
59 oembed.save()
60
61 data = dict(id=oembed.id, embed=oembed.html)
62 return HttpResponse(json.dumps(data),
63 content_type='application/json')
64
65 return HttpBadRequest("Sorry, we couldn't find that video.")