Tweaked NavigationItem.is_active to better leverage the caching.
[philo.git] / philo / contrib / shipherd / models.py
1 #encoding: utf-8
2 from UserDict import DictMixin
3 from hashlib import sha1
4
5 from django.contrib.sites.models import Site
6 from django.core.cache import cache
7 from django.core.exceptions import ValidationError
8 from django.core.urlresolvers import NoReverseMatch
9 from django.core.validators import RegexValidator, MinValueValidator
10 from django.db import models
11 from django.forms.models import model_to_dict
12
13 from philo.models.base import TreeEntity, TreeEntityManager, Entity
14 from philo.models.nodes import Node, TargetURLModel
15
16
17 DEFAULT_NAVIGATION_DEPTH = 3
18
19
20 class NavigationMapper(object, DictMixin):
21         """
22         The :class:`NavigationMapper` is a dictionary-like object which allows easy fetching of the root items of a navigation for a node according to a key. A :class:`NavigationMapper` instance will be available on each node instance as :attr:`Node.navigation` if :mod:`~philo.contrib.shipherd` is in the :setting:`INSTALLED_APPS`
23         
24         """
25         def __init__(self, node):
26                 self.node = node
27                 self._cache = {}
28         
29         def __getitem__(self, key):
30                 return Navigation.objects.get_for_node(self.node, key)
31                 #if key not in self._cache:
32                 #       try:
33                 #               self._cache[key] = Navigation.objects.get_for_node(self.node, key)
34                 #       except Navigation.DoesNotExist:
35                 #               self._cache[key] = None
36                 #return self._cache[key]
37
38
39 def navigation(self):
40         if not hasattr(self, '_navigation'):
41                 self._navigation = NavigationMapper(self)
42         return self._navigation
43
44
45 Node.navigation = property(navigation)
46
47
48 class NavigationManager(models.Manager):
49         use_for_related = True
50         
51         def get_for_node(self, node, key):
52                 cache_key = self._get_cache_key(node, key)
53                 cached = cache.get(cache_key)
54                 
55                 if cached is None:
56                         opts = Node._mptt_meta
57                         left = getattr(node, opts.left_attr)
58                         right = getattr(node, opts.right_attr)
59                         tree_id = getattr(node, opts.tree_id_attr)
60                         kwargs = {
61                                 "node__%s__lte" % opts.left_attr: left,
62                                 "node__%s__gte" % opts.right_attr: right,
63                                 "node__%s" % opts.tree_id_attr: tree_id
64                         }
65                         navs = self.filter(key=key, **kwargs).order_by('-node__%s' % opts.level_attr)
66                         nav = navs[0]
67                         roots = nav.roots.all().select_related('target_node').order_by('order')
68                         item_opts = NavigationItem._mptt_meta
69                         by_pk = {}
70                         tree_ids = []
71                         
72                         site_root_node = Site.objects.get_current().root_node
73                         
74                         for root in roots:
75                                 by_pk[root.pk] = root
76                                 tree_ids.append(getattr(root, item_opts.tree_id_attr))
77                                 root._cached_children = []
78                                 root.target_node.get_path(root=site_root_node)
79                                 root.navigation = nav
80                         
81                         kwargs = {
82                                 '%s__in' % item_opts.tree_id_attr: tree_ids,
83                                 '%s__lt' % item_opts.level_attr: nav.depth,
84                                 '%s__gt' % item_opts.level_attr: 0
85                         }
86                         items = NavigationItem.objects.filter(**kwargs).select_related('target_node').order_by('level', 'order')
87                         for item in items:
88                                 by_pk[item.pk] = item
89                                 item._cached_children = []
90                                 parent_pk = getattr(item, '%s_id' % item_opts.parent_attr)
91                                 item.parent = by_pk[parent_pk]
92                                 item.parent._cached_children.append(item)
93                                 item.target_node.get_path(root=site_root_node)
94                         
95                         cached = roots
96                         cache.set(cache_key, cached)
97                 
98                 return cached
99         
100         def _get_cache_key(self, node, key):
101                 opts = Node._mptt_meta
102                 left = getattr(node, opts.left_attr)
103                 right = getattr(node, opts.right_attr)
104                 tree_id = getattr(node, opts.tree_id_attr)
105                 parent_id = getattr(node, "%s_id" % opts.parent_attr)
106                 
107                 return sha1(unicode(left) + unicode(right) + unicode(tree_id) + unicode(parent_id) + unicode(node.pk) + unicode(key)).hexdigest()
108
109
110 class Navigation(Entity):
111         """
112         :class:`Navigation` represents a group of :class:`NavigationItem`\ s that have an intrinsic relationship in terms of navigating a website. For example, a ``main`` navigation versus a ``side`` navigation, or a ``authenticated`` navigation versus an ``anonymous`` navigation.
113         
114         A :class:`Navigation`'s :class:`NavigationItem`\ s will be accessible from its related :class:`.Node` and that :class:`.Node`'s descendants through a :class:`NavigationMapper` instance at :attr:`Node.navigation`. Example::
115         
116                 >>> node.navigation_set.all()
117                 []
118                 >>> parent = node.parent
119                 >>> items = parent.navigation_set.get(key='main').roots.all()
120                 >>> parent.navigation["main"] == node.navigation["main"] == list(items)
121                 True
122         
123         """
124         #: A :class:`NavigationManager` instance.
125         objects = NavigationManager()
126         
127         #: The :class:`.Node` which the :class:`Navigation` is attached to. The :class:`Navigation` will also be available to all the :class:`.Node`'s descendants and will override any :class:`Navigation` with the same key on any of the :class:`.Node`'s ancestors.
128         node = models.ForeignKey(Node, related_name='navigation_set', help_text="Be available as navigation for this node.")
129         #: Each :class:`Navigation` has a ``key`` which consists of one or more word characters so that it can easily be accessed in a template as ``{{ node.navigation.this_key }}``.
130         key = models.CharField(max_length=255, validators=[RegexValidator("\w+")], help_text="Must contain one or more alphanumeric characters or underscores.", db_index=True)
131         #: There is no limit to the depth of a tree of :class:`NavigationItem`\ s, but ``depth`` will limit how much of the tree will be displayed.
132         depth = models.PositiveSmallIntegerField(default=DEFAULT_NAVIGATION_DEPTH, validators=[MinValueValidator(1)], help_text="Defines the maximum display depth of this navigation.")
133         
134         def __unicode__(self):
135                 return "%s[%s]" % (self.node, self.key)
136         
137         class Meta:
138                 unique_together = ('node', 'key')
139
140
141 class NavigationItem(TreeEntity, TargetURLModel):
142         #: A :class:`ForeignKey` to a :class:`Navigation` instance. If this is not null, then the :class:`NavigationItem` will be a root node of the :class:`Navigation` instance.
143         navigation = models.ForeignKey(Navigation, blank=True, null=True, related_name='roots', help_text="Be a root in this navigation tree.")
144         #: The text which will be displayed in the navigation. This is a :class:`CharField` instance with max length 50.
145         text = models.CharField(max_length=50)
146         
147         #: The order in which the :class:`NavigationItem` will be displayed.
148         order = models.PositiveSmallIntegerField(default=0)
149         
150         def get_path(self, root=None, pathsep=u' › ', field='text'):
151                 return super(NavigationItem, self).get_path(root, pathsep, field)
152         path = property(get_path)
153         
154         def clean(self):
155                 super(NavigationItem, self).clean()
156                 if bool(self.parent) == bool(self.navigation):
157                         raise ValidationError("Exactly one of `parent` and `navigation` must be defined.")
158         
159         def is_active(self, request):
160                 """Returns ``True`` if the :class:`NavigationItem` is considered active for a given request and ``False`` otherwise."""
161                 if self.target_url == request.path:
162                         # Handle the `default` case where the target_url and requested path
163                         # are identical.
164                         return True
165                 
166                 if self.target_node is None and self.url_or_subpath == "http%s://%s%s" % (request.is_secure() and 's' or '', request.get_host(), request.path):
167                         # If there's no target_node, double-check whether it's a full-url
168                         # match.
169                         return True
170                 
171                 if self.target_node and not self.url_or_subpath:
172                         # If there is a target node and it's targeted simply, but the target URL is not
173                         # the same as the request path, check whether the target node is an ancestor
174                         # of the requested node. If so, this is active unless the target node
175                         # is the same as the ``host node`` for this navigation structure.
176                         root = self
177                         
178                         # The common case will be cached items, whose parents are cached with them.
179                         while root.parent is not None:
180                                 root = root.parent
181                         
182                         host_node_id = root.navigation.node_id
183                         if self.target_node.pk != host_node_id and self.target_node.is_ancestor_of(request.node):
184                                 return True
185                 
186                 return False
187         
188         def has_active_descendants(self, request):
189                 """Returns ``True`` if the :class:`NavigationItem` has active descendants and ``False`` otherwise."""
190                 for child in self.get_children():
191                         if child.is_active(request) or child.has_active_descendants(request):
192                                 return True
193                 return False