661a7a6499cb5cca4f4890f66d9cf4ac6726791c
[redakcja.git] / apps / explorer / middleware.py
1 import urllib
2
3 from django.conf import settings
4 from django.utils import simplejson
5
6 from explorer import models
7
8
9 class EditorSettingsMiddleware(object):
10     def process_request(self, request):
11         if request.user.is_anonymous():
12             return
13         cookie_settings = request.COOKIES.get(settings.EDITOR_COOKIE_NAME, '{}')
14         
15         cookie_settings = simplejson.loads(urllib.unquote(cookie_settings))
16         last_update = cookie_settings.get('lastUpdate', 0)
17         
18         try:
19             editor_settings = models.EditorSettings.objects.get(user=request.user)
20         except models.EditorSettings.DoesNotExist:
21             editor_settings = models.EditorSettings(user=request.user)
22             editor_settings.set_settings_value(cookie_settings)
23             editor_settings.save()
24
25         # print editor_settings.get_settings_value()['lastUpdate'], '<>', last_update
26         if editor_settings.get_settings_value()['lastUpdate'] < last_update:
27             print "\n\nZmiana!\n\n"
28             editor_settings.set_settings_value(cookie_settings)
29             editor_settings.save()
30
31         request.editor_settings = editor_settings
32
33
34     def process_response(self, request, response):
35         if hasattr(request, 'editor_settings'):
36             response.set_cookie(settings.EDITOR_COOKIE_NAME,
37                 urllib.quote(request.editor_settings.settings), max_age=7 * 60 * 60 * 24, path='/')
38
39         return response