[API] don't encode query string
[mygpo.git] / mygpo / api / simple.py
blob11662543ac0fcfad8d9dd84770e8648c5cc34b0b
2 # This file is part of my.gpodder.org.
4 # my.gpodder.org is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
9 # my.gpodder.org is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
12 # License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with my.gpodder.org. If not, see <http://www.gnu.org/licenses/>.
18 import string
19 from itertools import islice
20 from functools import wraps
22 from django.shortcuts import render
23 from django.core.cache import cache
24 from django.http import HttpResponse, HttpResponseBadRequest
25 from django.views.decorators.cache import cache_page
26 from django.views.decorators.csrf import csrf_exempt
27 from django.views.decorators.cache import never_cache
28 from django.contrib.sites.models import RequestSite
29 from django.utils.translation import ugettext as _
31 from mygpo.api.basic_auth import require_valid_user, check_username
32 from mygpo.api.backend import get_device
33 from mygpo.podcasts.models import Podcast
34 from mygpo.api.opml import Exporter, Importer
35 from mygpo.api.httpresponse import JsonResponse
36 from mygpo.directory.models import ExamplePodcast
37 from mygpo.api.advanced.directory import podcast_data
38 from mygpo.subscriptions import get_subscribed_podcasts, subscribe, unsubscribe
39 from mygpo.directory.search import search_podcasts
40 from mygpo.decorators import allowed_methods, cors_origin
41 from mygpo.utils import parse_range, normalize_feed_url
42 from mygpo.core.json import json, JSONDecodeError
44 import logging
45 logger = logging.getLogger(__name__)
48 ALLOWED_FORMATS = ('txt', 'opml', 'json', 'jsonp', 'xml')
50 def check_format(fn):
51 @wraps(fn)
52 def tmp(request, format, *args, **kwargs):
53 if not format in ALLOWED_FORMATS:
54 return HttpResponseBadRequest('Invalid format')
56 return fn(request, *args, format=format, **kwargs)
57 return tmp
60 @csrf_exempt
61 @require_valid_user
62 @check_username
63 @check_format
64 @never_cache
65 @allowed_methods(['GET', 'PUT', 'POST'])
66 @cors_origin()
67 def subscriptions(request, username, device_uid, format):
69 user_agent = request.META.get('HTTP_USER_AGENT', '')
71 if request.method == 'GET':
72 title = _('%(username)s\'s Subscription List') % {'username': username}
73 subscriptions = get_subscriptions(request.user, device_uid, user_agent)
74 return format_podcast_list(subscriptions, format, title, jsonp_padding=request.GET.get('jsonp'))
76 elif request.method in ('PUT', 'POST'):
77 try:
78 body = request.body.decode('utf-8')
79 subscriptions = parse_subscription(body, format)
81 except JSONDecodeError as e:
82 return HttpResponseBadRequest('Unable to parse POST data: %s' % str(e))
84 return set_subscriptions(subscriptions, request.user, device_uid,
85 user_agent)
88 @csrf_exempt
89 @require_valid_user
90 @check_username
91 @check_format
92 @never_cache
93 @allowed_methods(['GET'])
94 @cors_origin()
95 def all_subscriptions(request, username, format):
97 try:
98 scale = int(request.GET.get('scale_logo', 64))
99 except (TypeError, ValueError):
100 return HttpResponseBadRequest('scale_logo has to be a numeric value')
102 if scale not in range(1, 257):
103 return HttpResponseBadRequest('scale_logo has to be a number from 1 to 256')
106 subscriptions = get_subscribed_podcasts(request.user)
107 title = _('%(username)s\'s Subscription List') % {'username': username}
108 domain = RequestSite(request).domain
109 p_data = lambda p: podcast_data(p, domain, scale)
110 return format_podcast_list(subscriptions, format, title,
111 json_map=p_data, xml_template='podcasts.xml', request=request)
114 def format_podcast_list(obj_list, format, title, get_podcast=None,
115 json_map=lambda x: x.url, jsonp_padding=None,
116 xml_template=None, request=None, template_args={}):
118 Formats a list of podcasts for use in a API response
120 obj_list is a list of podcasts or objects that contain podcasts
121 format is one if txt, opml or json
122 title is a label of the list
123 if obj_list is a list of objects containing podcasts, get_podcast is the
124 function used to get the podcast out of the each of these objects
125 json_map is a function returning the contents of an object (from obj_list)
126 that should be contained in the result (only used for format='json')
129 def default_get_podcast(p):
130 return p
132 get_podcast = get_podcast or default_get_podcast
134 if format == 'txt':
135 podcasts = map(get_podcast, obj_list)
136 s = '\n'.join([p.url for p in podcasts] + [''])
137 return HttpResponse(s, content_type='text/plain')
139 elif format == 'opml':
140 podcasts = map(get_podcast, obj_list)
141 exporter = Exporter(title)
142 opml = exporter.generate(podcasts)
143 return HttpResponse(opml, content_type='text/xml')
145 elif format == 'json':
146 objs = map(json_map, obj_list)
147 return JsonResponse(objs)
149 elif format == 'jsonp':
150 ALLOWED_FUNCNAME = string.ascii_letters + string.digits + '_'
152 if not jsonp_padding:
153 return HttpResponseBadRequest('For a JSONP response, specify the name of the callback function in the jsonp parameter')
155 if any(x not in ALLOWED_FUNCNAME for x in jsonp_padding):
156 return HttpResponseBadRequest('JSONP padding can only contain the characters %(char)s' % {'char': ALLOWED_FUNCNAME})
158 objs = map(json_map, obj_list)
159 return JsonResponse(objs, jsonp_padding=jsonp_padding)
161 elif format == 'xml':
162 if None in (xml_template, request):
163 return HttpResponseBadRequest('XML is not a valid format for this request')
165 podcasts = map(json_map, obj_list)
166 template_args.update({'podcasts': podcasts})
168 return render(request, xml_template, template_args,
169 content_type='application/xml')
171 else:
172 return None
175 def get_subscriptions(user, device_uid, user_agent=None):
176 device = get_device(user, device_uid, user_agent)
177 return device.get_subscribed_podcasts()
180 def parse_subscription(raw_post_data, format):
181 """ Parses the data according to the format """
182 if format == 'txt':
183 urls = raw_post_data.split('\n')
185 elif format == 'opml':
186 begin = raw_post_data.find('<?xml')
187 end = raw_post_data.find('</opml>') + 7
188 i = Importer(content=raw_post_data[begin:end])
189 urls = [p['url'] for p in i.items]
191 elif format == 'json':
192 begin = raw_post_data.find('[')
193 end = raw_post_data.find(']') + 1
194 urls = json.loads(raw_post_data[begin:end])
196 else:
197 return []
199 urls = filter(None, urls)
200 urls = map(normalize_feed_url, urls)
201 return urls
204 def set_subscriptions(urls, user, device_uid, user_agent):
206 device = get_device(user, device_uid, user_agent, undelete=True)
208 subscriptions = dict( (p.url, p) for p in device.get_subscribed_podcasts())
209 new = [p for p in urls if p not in subscriptions.keys()]
210 rem = [p for p in subscriptions.keys() if p not in urls]
212 remove_podcasts = Podcast.objects.filter(urls__url__in=rem)
213 for podcast in remove_podcasts:
214 unsubscribe(podcast, user, device)
216 for url in new:
217 podcast = Podcast.objects.get_or_create_for_url(url)
218 subscribe(podcast, user, device, url)
220 # Only an empty response is a successful response
221 return HttpResponse('', content_type='text/plain')
224 @check_format
225 @allowed_methods(['GET'])
226 @cache_page(60 * 60)
227 @cors_origin()
228 def toplist(request, count, format):
229 count = parse_range(count, 1, 100, 100)
231 entries = Podcast.objects.all().toplist()[:count]
232 domain = RequestSite(request).domain
234 try:
235 scale = int(request.GET.get('scale_logo', 64))
236 except (TypeError, ValueError):
237 return HttpResponseBadRequest('scale_logo has to be a numeric value')
239 if scale not in range(1, 257):
240 return HttpResponseBadRequest('scale_logo has to be a number from 1 to 256')
243 def get_podcast(t):
244 return t
246 def json_map(t):
247 podcast = t
248 p = podcast_data(podcast, domain, scale)
249 return p
251 title = _('gpodder.net - Top %(count)d') % {'count': len(entries)}
252 return format_podcast_list(entries,
253 format,
254 title,
255 get_podcast=get_podcast,
256 json_map=json_map,
257 jsonp_padding=request.GET.get('jsonp', ''),
258 xml_template='podcasts.xml',
259 request=request,
263 @check_format
264 @cache_page(60 * 60)
265 @allowed_methods(['GET'])
266 @cors_origin()
267 def search(request, format):
269 NUM_RESULTS = 20
271 query = request.GET.get('q', '')
273 try:
274 scale = int(request.GET.get('scale_logo', 64))
275 except (TypeError, ValueError):
276 return HttpResponseBadRequest('scale_logo has to be a numeric value')
278 if scale not in range(1, 257):
279 return HttpResponseBadRequest('scale_logo has to be a number from 1 to 256')
281 if not query:
282 return HttpResponseBadRequest('/search.opml|txt|json?q={query}')
284 results = search_podcasts(query)[:NUM_RESULTS]
286 title = _('gpodder.net - Search')
287 domain = RequestSite(request).domain
288 p_data = lambda p: podcast_data(p, domain, scale)
289 return format_podcast_list(results, format, title, json_map=p_data, jsonp_padding=request.GET.get('jsonp', ''), xml_template='podcasts.xml', request=request)
292 @require_valid_user
293 @check_format
294 @never_cache
295 @allowed_methods(['GET'])
296 @cors_origin()
297 def suggestions(request, count, format):
298 count = parse_range(count, 1, 100, 100)
300 user = request.user
301 suggestions = Podcast.objects.filter(podcastsuggestion__suggested_to=user,
302 podcastsuggestion__deleted=False)
303 title = _('gpodder.net - %(count)d Suggestions') % {'count': len(suggestions)}
304 domain = RequestSite(request).domain
305 p_data = lambda p: podcast_data(p, domain)
306 return format_podcast_list(suggestions, format, title, json_map=p_data, jsonp_padding=request.GET.get('jsonp'))
309 @check_format
310 @allowed_methods(['GET'])
311 @cache_page(60 * 60)
312 @cors_origin()
313 def example_podcasts(request, format):
315 podcasts = cache.get('example-podcasts', None)
317 try:
318 scale = int(request.GET.get('scale_logo', 64))
319 except (TypeError, ValueError):
320 return HttpResponseBadRequest('scale_logo has to be a numeric value')
322 if scale not in range(1, 257):
323 return HttpResponseBadRequest('scale_logo has to be a number from 1 to 256')
325 if not podcasts:
326 podcasts = ExamplePodcast.objects.get_podcasts()
327 cache.set('example-podcasts', podcasts)
329 title = 'gPodder Podcast Directory'
330 domain = RequestSite(request).domain
331 p_data = lambda p: podcast_data(p, domain, scale)
332 return format_podcast_list(
333 podcasts,
334 format,
335 title,
336 json_map=p_data,
337 xml_template='podcasts.xml',
338 request=request,