Run 2to3-3.4
[mygpo.git] / mygpo / api / advanced / settings.py
blob57b4cad73e6242dee1ee552b0e44ddd74bf6fdf9
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 json
20 from django.shortcuts import get_object_or_404
22 from mygpo.api import APIView, RequestException
23 from mygpo.podcasts.models import Podcast, Episode
24 from mygpo.usersettings.models import UserSettings
25 from mygpo.api.httpresponse import JsonResponse
28 class SettingsAPI(APIView):
29 """ Settings API
31 wiki.gpodder.org/wiki/Web_Services/API_2/Settings """
33 def get(self, request, username, scope):
34 """ Get settings for scope object """
35 user = request.user
36 scope = self.get_scope(request, scope)
37 settings = UserSettings.objects.get_for_scope(user, scope)
38 return JsonResponse(settings.as_dict())
40 def post(self, request, username, scope):
41 """ Update settings for scope object """
42 user = request.user
43 scope = self.get_scope(request, scope)
44 actions = self.parsed_body(request)
45 settings = UserSettings.objects.get_for_scope(user, scope)
46 resp = self.update_settings(settings, actions)
47 return JsonResponse(resp)
49 def get_scope(self, request, scope):
50 """ Get the scope object """
51 if scope == 'account':
52 return None
54 if scope == 'device':
55 uid = request.GET.get('device', '')
56 return request.user.client_set.get(uid=uid)
58 episode_url = request.GET.get('episode', '')
59 podcast_url = request.GET.get('podcast', '')
61 if scope == 'podcast':
62 return get_object_or_404(Podcast, urls__url=podcast_url)
64 if scope == 'episode':
65 podcast = get_object_or_404(Podcast, urls__url=podcast_url)
66 return get_object_or_404(Episode, podcast=podcast,
67 urls__url=episode_url)
69 raise RequestException('undefined scope %s' % scope)
71 def update_settings(self, settings, actions):
72 """ Update the settings according to the actions """
73 for key, value in actions.get('set', {}).items():
74 settings.set_setting(key, value)
76 for key in actions.get('remove', []):
77 settings.del_setting(key)
79 settings.save()
80 return settings.as_dict()