]> git.openstreetmap.org Git - osqa.git/blob - forum/models/node.py
Makes hitting a question url using an id that is not a question raise a 404.
[osqa.git] / forum / models / node.py
1 from base import *
2 import re
3 from tag import Tag
4
5 import markdown
6 from django.utils.translation import ugettext as _
7 from django.utils.safestring import mark_safe
8 from django.utils.html import strip_tags
9 from forum.utils.html import sanitize_html
10 from utils import PickledObjectField
11
12 class NodeContent(models.Model):
13     title      = models.CharField(max_length=300)
14     tagnames   = models.CharField(max_length=125)
15     author     = models.ForeignKey(User, related_name='%(class)ss')
16     body       = models.TextField()
17
18     @property
19     def user(self):
20         return self.author
21
22     @property
23     def html(self):
24         return self.as_markdown()
25
26     @classmethod
27     def _as_markdown(cls, content, *extensions):
28         return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
29
30     def as_markdown(self, *extensions):
31         return self._as_markdown(self.body, *extensions)
32
33     @property
34     def headline(self):
35         return self.title
36
37     def tagname_list(self):
38         if self.tagnames:
39             t = [name.strip() for name in self.tagnames.split(u' ') if name]
40             return [name.strip() for name in self.tagnames.split(u' ') if name]
41         else:
42             return []
43
44     def tagname_meta_generator(self):
45         return u','.join([tag for tag in self.tagname_list()])
46
47     class Meta:
48         abstract = True
49         app_label = 'forum'
50
51 class NodeMetaClass(BaseMetaClass):
52     types = {}
53
54     def __new__(cls, *args, **kwargs):
55         new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
56
57         if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
58             NodeMetaClass.types[new_cls.get_type()] = new_cls
59
60         return new_cls
61
62     @classmethod
63     def setup_relations(cls):
64         for node_cls in NodeMetaClass.types.values():
65             NodeMetaClass.setup_relation(node_cls)
66
67     @classmethod
68     def setup_relation(cls, node_cls):
69         name = node_cls.__name__.lower()
70
71         def children(self):
72             return node_cls.objects.filter(parent=self)
73
74         def parent(self):
75             p = self.__dict__.get('_%s_cache' % name, None)
76
77             if p is None and (self.parent is not None) and self.parent.node_type == name:
78                 p = self.parent.leaf
79                 self.__dict__['_%s_cache' % name] = p
80
81             return p
82
83         Node.add_to_class(name + 's', property(children))
84         Node.add_to_class(name, property(parent))
85
86
87 class NodeQuerySet(CachedQuerySet):
88     def obj_from_datadict(self, datadict):
89         cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
90         if cls:
91             obj = cls()
92             obj.__dict__.update(datadict)
93             return obj
94         else:
95             return super(NodeQuerySet, self).obj_from_datadict(datadict)
96
97     def get(self, *args, **kwargs):
98         node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
99
100         if not isinstance(node, self.model):
101             raise self.model.DoesNotExist()
102
103         return node
104
105     def filter_state(self, **kwargs):
106         apply_bool = lambda q, b: b and q or ~q
107         return self.filter(*[apply_bool(models.Q(state_string__contains="(%s)" % s), b) for s, b in kwargs.items()])
108
109
110 class NodeManager(CachedManager):
111     use_for_related_fields = True
112
113     def get_query_set(self):
114         qs = NodeQuerySet(self.model)
115
116         if self.model is not Node:
117             return qs.filter(node_type=self.model.get_type())
118         else:
119             return qs
120
121     def get_for_types(self, types, *args, **kwargs):
122         kwargs['node_type__in'] = [t.get_type() for t in types]
123         return self.get(*args, **kwargs)
124
125     def filter_state(self, **kwargs):
126         return self.all().filter_state(**kwargs)
127
128
129 class NodeStateDict(object):
130     def __init__(self, node):
131         self.__dict__['_node'] = node
132
133     def __getattr__(self, name):
134         if self.__dict__.get(name, None):
135             return self.__dict__[name]
136
137         try:
138             node = self.__dict__['_node']
139             action = NodeState.objects.get(node=node, state_type=name).action
140             self.__dict__[name] = action
141             return action
142         except:
143             return None
144
145     def __setattr__(self, name, value):
146         current = self.__getattr__(name)
147
148         if value:
149             if current:
150                 current.action = value
151                 current.save()
152             else:
153                 node = self.__dict__['_node']
154                 state = NodeState(node=node, action=value, state_type=name)
155                 state.save()
156                 self.__dict__[name] = value
157
158                 if not "(%s)" % name in node.state_string:
159                     node.state_string = "%s(%s)" % (node.state_string, name)
160                     node.save()
161         else:
162             if current:
163                 node = self.__dict__['_node']
164                 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
165                 node.save()
166                 current.node_state.delete()
167                 del self.__dict__[name]
168
169
170 class NodeStateQuery(object):
171     def __init__(self, node):
172         self.__dict__['_node'] = node
173
174     def __getattr__(self, name):
175         node = self.__dict__['_node']
176         return "(%s)" % name in node.state_string
177
178
179 class Node(BaseModel, NodeContent):
180     __metaclass__ = NodeMetaClass
181
182     node_type            = models.CharField(max_length=16, default='node')
183     parent               = models.ForeignKey('Node', related_name='children', null=True)
184     abs_parent           = models.ForeignKey('Node', related_name='all_children', null=True)
185
186     added_at             = models.DateTimeField(default=datetime.datetime.now)
187     score                 = models.IntegerField(default=0)
188
189     state_string          = models.TextField(default='')
190     last_edited           = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
191
192     last_activity_by       = models.ForeignKey(User, null=True)
193     last_activity_at       = models.DateTimeField(null=True, blank=True)
194
195     tags                 = models.ManyToManyField('Tag', related_name='%(class)ss')
196     active_revision       = models.OneToOneField('NodeRevision', related_name='active', null=True)
197
198     extra = PickledObjectField()
199     extra_ref = models.ForeignKey('Node', null=True)
200     extra_count = models.IntegerField(default=0)
201
202     marked = models.BooleanField(default=False)
203
204     comment_count = DenormalizedField("children", node_type="comment", canceled=False)
205     flag_count = DenormalizedField("flags")
206
207     friendly_name = _("post")
208
209     objects = NodeManager()
210
211     def __unicode__(self):
212         return self.headline
213
214     @classmethod
215     def _generate_cache_key(cls, key, group="node"):
216         return super(Node, cls)._generate_cache_key(key, group)
217
218     @classmethod
219     def get_type(cls):
220         return cls.__name__.lower()
221
222     @property
223     def leaf(self):
224         leaf_cls = NodeMetaClass.types.get(self.node_type, None)
225
226         if leaf_cls is None:
227             return self
228
229         leaf = leaf_cls()
230         leaf.__dict__ = self.__dict__
231         return leaf
232
233     @property
234     def nstate(self):
235         state = self.__dict__.get('_nstate', None)
236
237         if state is None:
238             state = NodeStateDict(self)
239             self._nstate = state
240
241         return state
242
243     @property
244     def nis(self):
245         nis = self.__dict__.get('_nis', None)
246
247         if nis is None:
248             nis = NodeStateQuery(self)
249             self._nis = nis
250
251         return nis
252
253     @property
254     def deleted(self):
255         return self.nis.deleted
256
257     @property
258     def absolute_parent(self):
259         if not self.abs_parent_id:
260             return self
261
262         return self.abs_parent
263
264     @property
265     def summary(self):
266         return strip_tags(self.html)[:300]
267
268     @models.permalink
269     def get_revisions_url(self):
270         return ('revisions', (), {'id': self.id})
271
272     def update_last_activity(self, user, save=False):
273         self.last_activity_by = user
274         self.last_activity_at = datetime.datetime.now()
275
276         if self.parent:
277             self.parent.update_last_activity(user, save=True)
278
279         if save:
280             self.save()
281
282     def _create_revision(self, user, number, **kwargs):
283         revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
284         revision.save()
285         return revision
286
287     def create_revision(self, user, **kwargs):
288         number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
289         revision = self._create_revision(user, number, **kwargs)
290         self.activate_revision(user, revision)
291         return revision
292
293     def activate_revision(self, user, revision):
294         self.title = revision.title
295         self.tagnames = revision.tagnames
296         self.body = revision.body
297
298         self.active_revision = revision
299         self.update_last_activity(user)
300
301         self.save()
302
303     def _list_changes_in_tags(self):
304         dirty = self.get_dirty_fields()
305
306         if not 'tagnames' in dirty:
307             return None
308         else:
309             if self._original_state['tagnames']:
310                 old_tags = set(name for name in self._original_state['tagnames'].split(u' '))
311             else:
312                 old_tags = set()
313             new_tags = set(name for name in self.tagnames.split(u' ') if name)
314
315             return dict(
316                     current=list(new_tags),
317                     added=list(new_tags - old_tags),
318                     removed=list(old_tags - new_tags)
319                     )
320
321     def _last_active_user(self):
322         return self.last_edited and self.last_edited.by or self.author
323
324     def _process_changes_in_tags(self):
325         tag_changes = self._list_changes_in_tags()
326
327         if tag_changes is not None:
328             for name in tag_changes['added']:
329                 try:
330                     tag = Tag.objects.get(name=name)
331                 except:
332                     tag = Tag.objects.create(name=name, created_by=self._last_active_user())
333
334                 if not self.nis.deleted:
335                     tag.add_to_usage_count(1)
336                     tag.save()
337
338             if not self.nis.deleted:
339                 for name in tag_changes['removed']:
340                     try:
341                         tag = Tag.objects.get(name=name)
342                         tag.add_to_usage_count(-1)
343                         tag.save()
344                     except:
345                         pass
346
347             return True
348
349         return False
350
351     def mark_deleted(self, action):
352         self.nstate.deleted = action
353         self.save()
354
355         if action:
356             for tag in self.tags.all():
357                 tag.add_to_usage_count(-1)
358                 tag.save()
359         else:
360             for tag in Tag.objects.filter(name__in=self.tagname_list()):
361                 tag.add_to_usage_count(1)
362                 tag.save()
363
364     def save(self, *args, **kwargs):
365         tags_changed = self._process_changes_in_tags()
366
367         if not self.id:
368             self.node_type = self.get_type()
369             super(BaseModel, self).save(*args, **kwargs)
370             self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
371                                                          body=self.body)
372             self.update_last_activity(self.author)
373
374         if self.parent_id and not self.abs_parent_id:
375             self.abs_parent = self.parent.absolute_parent
376
377         super(Node, self).save(*args, **kwargs)
378         if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
379
380     class Meta:
381         app_label = 'forum'
382
383
384 class NodeRevision(BaseModel, NodeContent):
385     node       = models.ForeignKey(Node, related_name='revisions')
386     summary    = models.CharField(max_length=300)
387     revision   = models.PositiveIntegerField()
388     revised_at = models.DateTimeField(default=datetime.datetime.now)
389
390     class Meta:
391         unique_together = ('node', 'revision')
392         app_label = 'forum'
393
394
395 class NodeState(models.Model):
396     node       = models.ForeignKey(Node, related_name='states')
397     state_type = models.CharField(max_length=16)
398     action     = models.OneToOneField('Action', related_name="node_state")
399
400     class Meta:
401         unique_together = ('node', 'state_type')
402         app_label = 'forum'
403
404