Initial navigation commit. Steps towards Model-managed navigation overrides.
[philo.git] / models / nodes.py
1 from django.db import models
2 from django.contrib.contenttypes.models import ContentType
3 from django.contrib.contenttypes import generic
4 from django.contrib.sites.models import Site
5 from django.http import HttpResponse, HttpResponseServerError, HttpResponseRedirect
6 from django.core.exceptions import ViewDoesNotExist
7 from django.core.servers.basehttp import FileWrapper
8 from django.core.urlresolvers import resolve, clear_url_caches, reverse, NoReverseMatch
9 from django.template import add_to_builtins as register_templatetags
10 from inspect import getargspec
11 from philo.exceptions import MIDDLEWARE_NOT_CONFIGURED
12 from philo.models.base import TreeEntity, Entity, QuerySetMapper, register_value_model
13 from philo.models.fields import JSONField
14 from philo.utils import ContentTypeSubclassLimiter
15 from philo.validators import RedirectValidator
16 from philo.exceptions import ViewCanNotProvideSubpath, ViewDoesNotProvideSubpaths, AncestorDoesNotExist
17 from philo.signals import view_about_to_render, view_finished_rendering
18
19
20 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
21 DEFAULT_NAVIGATION_DEPTH = 3
22
23
24 class Node(TreeEntity):
25         view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter)
26         view_object_id = models.PositiveIntegerField()
27         view = generic.GenericForeignKey('view_content_type', 'view_object_id')
28         
29         @property
30         def accepts_subpath(self):
31                 if self.view:
32                         return self.view.accepts_subpath
33                 return False
34         
35         def render_to_response(self, request, extra_context=None):
36                 return self.view.render_to_response(request, extra_context)
37         
38         def get_absolute_url(self):
39                 try:
40                         root = Site.objects.get_current().root_node
41                 except Site.DoesNotExist:
42                         root = None
43                 
44                 try:
45                         path = self.get_path(root=root)
46                         if path:
47                                 path += '/'
48                         root_url = reverse('philo-root')
49                         return '%s%s' % (root_url, path)
50                 except AncestorDoesNotExist, ViewDoesNotExist:
51                         return None
52         
53         def get_navigation(self, depth=DEFAULT_NAVIGATION_DEPTH, current_depth=0, found_node_pks=None):
54                 navigation = self.view.get_navigation(self, depth, current_depth)
55                 
56                 if depth == current_depth:
57                         return navigation
58                 import pdb
59                 pdb.set_trace()
60                 found_node_pks = found_node_pks or [self.pk]
61                 ordered_child_pks = NodeNavigationOverride.objects.filter(parent=self, child__parent=self).values_list('child__pk', flat=True)
62                 
63                 children = self.children.exclude(pk__in=found_node_pks)
64                 ordered_children = children.filter(pk__in=ordered_child_pks)
65                 unordered_children = children.exclude(pk__in=ordered_child_pks)
66                 
67                 children = list(ordered_children) + list(unordered_children)
68                 
69                 if children:
70                         child_navigation = []
71                         for child in children:
72                                 found_node_pks.append(child.pk)
73                                 try:
74                                         child_navigation.append(child.get_navigation(depth, current_depth + 1, found_node_pks))
75                                 except NotImplementedError:
76                                         pass
77                         
78                         if child_navigation:
79                                 if 'children' in navigation:
80                                         navigation['children'] += child_navigation
81                                 else:
82                                         navigation['children'] = child_navigation
83                 
84                 return navigation
85         
86         def save(self):
87                 super(Node, self).save()
88                 
89         
90         class Meta:
91                 app_label = 'philo'
92
93
94 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
95 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
96
97
98 class NodeNavigationOverride(Entity):
99         parent = models.ForeignKey(Node, related_name="navigation_override_child_set")
100         child = models.OneToOneField(Node, related_name="navigation_override")
101         url = models.CharField(max_length=200, validators=[RedirectValidator()], blank=True)
102         title = models.CharField(max_length=100, blank=True)
103         order = models.PositiveSmallIntegerField(blank=True, null=True)
104         child_navigation = JSONField()
105         
106         def get_navigation(self, node, depth, current_depth):
107                 if self.child_navigation:
108                         depth = current_depth
109                 default = node.get_navigation(depth, current_depth)
110                 if self.url:
111                         default['url'] = self.url
112                 if self.title:
113                         default['title'] = self.title
114                 if self.child_navigation:
115                         if 'children' in default:
116                                 default['children'] += self.child_navigation
117                         else:
118                                 default['children'] = self.child_navigation
119         
120         class Meta:
121                 ordering = ['order']
122
123
124 class View(Entity):
125         nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
126         
127         accepts_subpath = False
128         
129         def get_subpath(self, obj):
130                 if not self.accepts_subpath:
131                         raise ViewDoesNotProvideSubpaths
132                 
133                 view_name, args, kwargs = self.get_reverse_params(obj)
134                 try:
135                         return reverse(view_name, args=args, kwargs=kwargs, urlconf=self)
136                 except NoReverseMatch:
137                         raise ViewCanNotProvideSubpath
138         
139         def get_reverse_params(self, obj):
140                 """This method should return a view_name, args, kwargs tuple suitable for reversing a url for the given obj using self as the urlconf."""
141                 raise NotImplementedError("View subclasses must implement get_reverse_params to support subpaths.")
142         
143         def attributes_with_node(self, node):
144                 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
145         
146         def render_to_response(self, request, extra_context=None):
147                 if not hasattr(request, 'node'):
148                         raise MIDDLEWARE_NOT_CONFIGURED
149                 
150                 extra_context = extra_context or {}
151                 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
152                 response = self.actually_render_to_response(request, extra_context)
153                 view_finished_rendering.send(sender=self, response=response)
154                 return response
155         
156         def actually_render_to_response(self, request, extra_context=None):
157                 raise NotImplementedError('View subclasses must implement render_to_response.')
158         
159         def get_navigation(self, node, depth, current_depth):
160                 raise NotImplementedError('View subclasses must implement get_navigation.')
161         
162         class Meta:
163                 abstract = True
164
165
166 _view_content_type_limiter.cls = View
167
168
169 class MultiView(View):
170         accepts_subpath = True
171         
172         @property
173         def urlpatterns(self, obj):
174                 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
175         
176         def actually_render_to_response(self, request, extra_context=None):
177                 clear_url_caches()
178                 subpath = request.node.subpath
179                 if not subpath:
180                         subpath = ""
181                 subpath = "/" + subpath
182                 view, args, kwargs = resolve(subpath, urlconf=self)
183                 view_args = getargspec(view)
184                 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
185                         if 'extra_context' in kwargs:
186                                 extra_context.update(kwargs['extra_context'])
187                         kwargs['extra_context'] = extra_context
188                 return view(request, *args, **kwargs)
189         
190         class Meta:
191                 abstract = True
192
193
194 class Redirect(View):
195         STATUS_CODES = (
196                 (302, 'Temporary'),
197                 (301, 'Permanent'),
198         )
199         target = models.CharField(max_length=200, validators=[RedirectValidator()])
200         status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
201         
202         def actually_render_to_response(self, request, extra_context=None):
203                 response = HttpResponseRedirect(self.target)
204                 response.status_code = self.status_code
205                 return response
206         
207         class Meta:
208                 app_label = 'philo'
209
210
211 # Why does this exist?
212 class File(View):
213         """ For storing arbitrary files """
214         
215         mimetype = models.CharField(max_length=255)
216         file = models.FileField(upload_to='philo/files/%Y/%m/%d')
217         
218         def actually_render_to_response(self, request, extra_context=None):
219                 wrapper = FileWrapper(self.file)
220                 response = HttpResponse(wrapper, content_type=self.mimetype)
221                 response['Content-Length'] = self.file.size
222                 return response
223         
224         class Meta:
225                 app_label = 'philo'
226         
227         def __unicode__(self):
228                 return self.file.name
229
230
231 register_templatetags('philo.templatetags.nodes')
232 register_value_model(Node)