Dodanie middleware EditorSettings.
authorzuber <marek@stepniowski.com>
Wed, 2 Sep 2009 10:42:40 +0000 (12:42 +0200)
committerzuber <marek@stepniowski.com>
Wed, 2 Sep 2009 10:42:40 +0000 (12:42 +0200)
apps/explorer/fields.py [new file with mode: 0644]
apps/explorer/middleware.py [new file with mode: 0644]
apps/explorer/models.py
project/settings.py
project/urls.py

diff --git a/apps/explorer/fields.py b/apps/explorer/fields.py
new file mode 100644 (file)
index 0000000..5d03e68
--- /dev/null
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+import datetime
+
+from django.conf import settings
+from django.db import models
+from django import forms
+from django.utils import simplejson as json
+
+
+class JSONEncoder(json.JSONEncoder):
+    def default(self, obj):
+        if isinstance(obj, datetime.datetime):
+            return obj.strftime('%Y-%m-%dT%H:%M:%S')
+        elif isinstance(obj, datetime.date):
+            return obj.strftime('%Y-%m-%d')
+        elif isinstance(obj, datetime.time):
+            return obj.strftime('%H:%M:%S')
+        return json.JSONEncoder.default(self, obj)
+
+
+def dumps(data):
+    return JSONEncoder().encode(data)
+
+
+def loads(str):
+    return json.loads(str, encoding=settings.DEFAULT_CHARSET)
+
+
+class JSONFormField(forms.CharField):
+    widget = forms.Textarea
+    
+    def clean(self, value):
+        try:
+            loads(value)
+            return value
+        except ValueError, e:
+            raise forms.ValidationError('Enter a valid JSON value. Error: %s' % e)
+
+
+class JSONField(models.TextField):
+    def formfield(self, **kwargs):
+        defaults = {'form_class': JSONFormField}
+        defaults.update(kwargs)
+        return super(JSONField, self).formfield(**defaults)
+
+    def db_type(self):
+        return 'text'
+
+    def get_internal_type(self):
+        return 'TextField'
+
+    def contribute_to_class(self, cls, name):
+        super(JSONField, self).contribute_to_class(cls, name)
+        
+        def get_value(model_instance):
+            return loads(getattr(model_instance, self.attname, None))
+        setattr(cls, 'get_%s_value' % self.name, get_value)
+
+        def set_value(model_instance, json):
+            return setattr(model_instance, self.attname, dumps(json))
+        setattr(cls, 'set_%s_value' % self.name, set_value)
+
diff --git a/apps/explorer/middleware.py b/apps/explorer/middleware.py
new file mode 100644 (file)
index 0000000..661a7a6
--- /dev/null
@@ -0,0 +1,39 @@
+import urllib
+
+from django.conf import settings
+from django.utils import simplejson
+
+from explorer import models
+
+
+class EditorSettingsMiddleware(object):
+    def process_request(self, request):
+        if request.user.is_anonymous():
+            return
+        cookie_settings = request.COOKIES.get(settings.EDITOR_COOKIE_NAME, '{}')
+        
+        cookie_settings = simplejson.loads(urllib.unquote(cookie_settings))
+        last_update = cookie_settings.get('lastUpdate', 0)
+        
+        try:
+            editor_settings = models.EditorSettings.objects.get(user=request.user)
+        except models.EditorSettings.DoesNotExist:
+            editor_settings = models.EditorSettings(user=request.user)
+            editor_settings.set_settings_value(cookie_settings)
+            editor_settings.save()
+
+        # print editor_settings.get_settings_value()['lastUpdate'], '<>', last_update
+        if editor_settings.get_settings_value()['lastUpdate'] < last_update:
+            print "\n\nZmiana!\n\n"
+            editor_settings.set_settings_value(cookie_settings)
+            editor_settings.save()
+
+        request.editor_settings = editor_settings
+
+
+    def process_response(self, request, response):
+        if hasattr(request, 'editor_settings'):
+            response.set_cookie(settings.EDITOR_COOKIE_NAME,
+                urllib.quote(request.editor_settings.settings), max_age=7 * 60 * 60 * 24, path='/')
+
+        return response
index 9a5e0ff..e47c26f 100644 (file)
@@ -5,17 +5,19 @@ from django.contrib.auth.models import User
 from django.conf import settings
 from django.utils.translation import gettext_lazy as _
 
 from django.conf import settings
 from django.utils.translation import gettext_lazy as _
 
-class PanelSettings(models.Model):
-    user = models.ForeignKey(User)
-    left_panel = models.CharField(blank=True,  max_length=80)
-    right_panel = models.CharField(blank=True,  max_length=80)
+from explorer import fields
 
 
+
+class EditorSettings(models.Model):
+    user = models.ForeignKey(User, unique=True)
+    settings = fields.JSONField()
+    
     class Meta:
     class Meta:
-        ordering = ['user__name']
-        verbose_name, verbose_name_plural = _("panel settings"), _("panel settings")
+        verbose_name, verbose_name_plural = _("editor settings"), _("editor settings")
 
     def __unicode__(self):
 
     def __unicode__(self):
-        return u"Panel settings for %s" % self.user.name
+        return u"Editor settings for %s" % self.user.username
+
 
 class Book(models.Model):
     class Meta:
 
 class Book(models.Model):
     class Meta:
@@ -24,6 +26,7 @@ class Book(models.Model):
         )
     pass
 
         )
     pass
 
+
 class PullRequest(models.Model):
     comitter = models.ForeignKey(User) # the user who request the pull 
     file = models.CharField(max_length=256) # the file to request
 class PullRequest(models.Model):
     comitter = models.ForeignKey(User) # the user who request the pull 
     file = models.CharField(max_length=256) # the file to request
index e958113..3bfc7db 100644 (file)
@@ -75,6 +75,7 @@ MIDDLEWARE_CLASSES = (
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'explorer.middleware.EditorSettingsMiddleware',
     'django.middleware.doc.XViewMiddleware',
 )
 
     'django.middleware.doc.XViewMiddleware',
 )
 
@@ -117,6 +118,7 @@ INSTALLED_APPS = (
 
 # REPOSITORY_PATH = '/Users/zuber/Projekty/platforma/files/books'
 IMAGE_DIR = 'images'
 
 # REPOSITORY_PATH = '/Users/zuber/Projekty/platforma/files/books'
 IMAGE_DIR = 'images'
+EDITOR_COOKIE_NAME = 'options'
 
 try:
     from localsettings import *
 
 try:
     from localsettings import *
index 551f2e0..ec919ae 100644 (file)
@@ -32,7 +32,7 @@ urlpatterns = patterns('',
 
     # Authorization
     url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'redirect_field_name': 'next'}),
 
     # Authorization
     url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'redirect_field_name': 'next'}),
-    url(r'^accounts/logout$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
+    url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
 )
 
 
 )