Merge pull request #793 from gpodder/remove-advertise
[mygpo.git] / mygpo / api / advanced / settings.py
blobfb589f97713c6e5fe034e207964b614cb664716a
1 import json
3 from django.shortcuts import get_object_or_404
5 from mygpo.api import APIView, RequestException
6 from mygpo.podcasts.models import Podcast, Episode
7 from mygpo.usersettings.models import UserSettings
8 from mygpo.api.httpresponse import JsonResponse
11 class SettingsAPI(APIView):
12 """Settings API
14 wiki.gpodder.org/wiki/Web_Services/API_2/Settings"""
16 def get(self, request, username, scope):
17 """Get settings for scope object"""
18 user = request.user
19 scope = self.get_scope(request, scope)
20 settings = UserSettings.objects.get_for_scope(user, scope)
21 return JsonResponse(settings.as_dict())
23 def post(self, request, username, scope):
24 """Update settings for scope object"""
25 user = request.user
26 scope = self.get_scope(request, scope)
27 actions = self.parsed_body(request)
28 settings = UserSettings.objects.get_for_scope(user, scope)
29 resp = self.update_settings(settings, actions)
30 return JsonResponse(resp)
32 def get_scope(self, request, scope):
33 """Get the scope object"""
34 if scope == "account":
35 return None
37 if scope == "device":
38 uid = request.GET.get("device", "")
39 return request.user.client_set.get(uid=uid)
41 episode_url = request.GET.get("episode", "")
42 podcast_url = request.GET.get("podcast", "")
44 if scope == "podcast":
45 return get_object_or_404(Podcast, urls__url=podcast_url)
47 if scope == "episode":
48 podcast = get_object_or_404(Podcast, urls__url=podcast_url)
49 return get_object_or_404(Episode, podcast=podcast, urls__url=episode_url)
51 raise RequestException("undefined scope %s" % scope)
53 def update_settings(self, settings, actions):
54 """Update the settings according to the actions"""
55 for key, value in actions.get("set", {}).items():
56 settings.set_setting(key, value)
58 for key in actions.get("remove", []):
59 settings.del_setting(key)
61 settings.save()
62 return settings.as_dict()