]> git.openstreetmap.org Git - osqa.git/blob - forum/models/node.py
OSQA-809, Include question summaries in question and answers views, wrap that in...
[osqa.git] / forum / models / node.py
1 # -*- coding: utf-8 -*-
2
3 from base import *
4 import re
5 from tag import Tag
6
7 import markdown
8 from django.utils.encoding import smart_unicode
9 from django.utils.translation import ugettext as _
10 from django.utils.safestring import mark_safe
11 from django.utils.html import strip_tags
12 from forum.utils.html import sanitize_html
13 from forum.utils.userlinking import auto_user_link
14 from forum.settings import SUMMARY_LENGTH
15 from utils import PickledObjectField
16
17 class NodeContent(models.Model):
18     title      = models.CharField(max_length=300)
19     tagnames   = models.CharField(max_length=125)
20     author     = models.ForeignKey(User, related_name='%(class)ss')
21     body       = models.TextField()
22
23     @property
24     def user(self):
25         return self.author
26
27     @property
28     def html(self):
29         return self.body
30
31     def rendered(self, content):
32         return auto_user_link(self, self._as_markdown(content, *['auto_linker']))
33
34     @classmethod
35     def _as_markdown(cls, content, *extensions):
36         try:
37             return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
38         except Exception, e:
39             import traceback
40             logging.error("Caught exception %s in markdown parser rendering %s %s:\s %s" % (
41                 str(e), cls.__name__, str(e), traceback.format_exc()))
42             return ''
43
44     def as_markdown(self, *extensions):
45         return self._as_markdown(smart_unicode(self.body), *extensions)
46
47     @property
48     def headline(self):
49         title = self.title
50
51         # Replaces multiple spaces with single ones.
52         title = re.sub(' +',' ', title)
53
54         return title
55
56     def tagname_list(self):
57         if self.tagnames:
58             return [name.strip() for name in self.tagnames.split() if name]
59         else:
60             return []
61
62     def tagname_meta_generator(self):
63         return u','.join([tag for tag in self.tagname_list()])
64
65     class Meta:
66         abstract = True
67         app_label = 'forum'
68
69 class NodeMetaClass(BaseMetaClass):
70     types = {}
71
72     def __new__(cls, *args, **kwargs):
73         new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
74
75         if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
76             NodeMetaClass.types[new_cls.get_type()] = new_cls
77
78         return new_cls
79
80     @classmethod
81     def setup_relations(cls):
82         for node_cls in NodeMetaClass.types.values():
83             NodeMetaClass.setup_relation(node_cls)
84
85     @classmethod
86     def setup_relation(cls, node_cls):
87         name = node_cls.__name__.lower()
88
89         def children(self):
90             return node_cls.objects.filter(parent=self)
91
92         def parent(self):
93             if (self.parent is not None) and self.parent.node_type == name:
94                 return self.parent.leaf
95
96             return None
97
98         Node.add_to_class(name + 's', property(children))
99         Node.add_to_class(name, property(parent))
100
101
102 class NodeQuerySet(CachedQuerySet):
103     def obj_from_datadict(self, datadict):
104         cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
105         if cls:
106             obj = cls()
107             obj.__dict__.update(datadict)
108             return obj
109         else:
110             return super(NodeQuerySet, self).obj_from_datadict(datadict)
111
112     def get(self, *args, **kwargs):
113         node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
114
115         if not isinstance(node, self.model):
116             raise self.model.DoesNotExist()
117
118         return node
119
120     def any_state(self, *args):
121         filter = None
122
123         for s in args:
124             s_filter = models.Q(state_string__contains="(%s)" % s)
125             filter = filter and (filter | s_filter) or s_filter
126
127         if filter:
128             return self.filter(filter)
129         else:
130             return self
131
132     def all_states(self, *args):
133         filter = None
134
135         for s in args:
136             s_filter = models.Q(state_string__contains="(%s)" % s)
137             filter = filter and (filter & s_filter) or s_filter
138
139         if filter:
140             return self.filter(filter)
141         else:
142             return self
143
144     def filter_state(self, **kwargs):
145         apply_bool = lambda q, b: b and q or ~q
146         return self.filter(*[apply_bool(models.Q(state_string__contains="(%s)" % s), b) for s, b in kwargs.items()])
147
148     def children_count(self, child_type):
149         return NodeMetaClass.types[child_type].objects.filter_state(deleted=False).filter(parent__in=self).count()
150
151
152 class NodeManager(CachedManager):
153     use_for_related_fields = True
154
155     def get_query_set(self):
156         qs = NodeQuerySet(self.model)
157
158         # If the node is an answer, question or comment we filter the Node model by type
159         if self.model is not Node:
160             qs = qs.filter(node_type=self.model.get_type())
161
162         return qs
163
164     def get_for_types(self, types, *args, **kwargs):
165         kwargs['node_type__in'] = [t.get_type() for t in types]
166         return self.get(*args, **kwargs)
167
168     def filter_state(self, **kwargs):
169         return self.all().filter_state(**kwargs)
170
171
172 class NodeStateDict(object):
173     def __init__(self, node):
174         self.__dict__['_node'] = node
175
176     def __getattr__(self, name):
177         if self.__dict__.get(name, None):
178             return self.__dict__[name]
179
180         try:
181             node = self.__dict__['_node']
182             action = NodeState.objects.get(node=node, state_type=name).action
183             self.__dict__[name] = action
184             return action
185         except:
186             return None
187
188     def __setattr__(self, name, value):
189         current = self.__getattr__(name)
190
191         if value:
192             if current:
193                 current.action = value
194                 current.save()
195             else:
196                 node = self.__dict__['_node']
197                 state = NodeState(node=node, action=value, state_type=name)
198                 state.save()
199                 self.__dict__[name] = value
200
201                 if not "(%s)" % name in node.state_string:
202                     node.state_string = "%s(%s)" % (node.state_string, name)
203                     node.save()
204         else:
205             if current:
206                 node = self.__dict__['_node']
207                 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
208                 node.save()
209                 current.node_state.delete()
210                 del self.__dict__[name]
211
212
213 class NodeStateQuery(object):
214     def __init__(self, node):
215         self.__dict__['_node'] = node
216
217     def __getattr__(self, name):
218         node = self.__dict__['_node']
219         return "(%s)" % name in node.state_string
220
221
222 class Node(BaseModel, NodeContent):
223     __metaclass__ = NodeMetaClass
224
225     node_type            = models.CharField(max_length=16, default='node')
226     parent               = models.ForeignKey('Node', related_name='children', null=True)
227     abs_parent           = models.ForeignKey('Node', related_name='all_children', null=True)
228
229     added_at             = models.DateTimeField(default=datetime.datetime.now)
230     score                 = models.IntegerField(default=0)
231
232     state_string          = models.TextField(default='')
233     last_edited           = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
234
235     last_activity_by       = models.ForeignKey(User, null=True)
236     last_activity_at       = models.DateTimeField(null=True, blank=True)
237
238     tags                 = models.ManyToManyField('Tag', related_name='%(class)ss')
239     active_revision       = models.OneToOneField('NodeRevision', related_name='active', null=True)
240
241     extra = PickledObjectField()
242     extra_ref = models.ForeignKey('Node', null=True)
243     extra_count = models.IntegerField(default=0)
244
245     marked = models.BooleanField(default=False)
246
247     comment_count = DenormalizedField("children", node_type="comment", canceled=False)
248     flag_count = DenormalizedField("actions", action_type="flag", canceled=False)
249
250     friendly_name = _("post")
251
252     objects = NodeManager()
253
254     def __unicode__(self):
255         return self.headline
256
257     @classmethod
258     def _generate_cache_key(cls, key, group="node"):
259         return super(Node, cls)._generate_cache_key(key, group)
260         
261     @classmethod
262     def get_type(cls):
263         return cls.__name__.lower()
264
265     @property
266     def leaf(self):
267         leaf_cls = NodeMetaClass.types.get(self.node_type, None)
268
269         if leaf_cls is None:
270             return self
271
272         leaf = leaf_cls()
273         leaf.__dict__ = self.__dict__
274         return leaf
275
276     @property
277     def nstate(self):
278         state = self.__dict__.get('_nstate', None)
279
280         if state is None:
281             state = NodeStateDict(self)
282             self._nstate = state
283
284         return state
285
286     @property
287     def nis(self):
288         nis = self.__dict__.get('_nis', None)
289
290         if nis is None:
291             nis = NodeStateQuery(self)
292             self._nis = nis
293
294         return nis
295
296     @property
297     def last_activity(self):
298         try:
299             return self.actions.order_by('-action_date')[0].action_date
300         except:
301             return self.last_seen
302
303     @property
304     def state_list(self):
305         return [s.state_type for s in self.states.all()]
306
307     @property
308     def deleted(self):
309         return self.nis.deleted
310
311     @property
312     def absolute_parent(self):
313         if not self.abs_parent_id:
314             return self
315
316         return self.abs_parent
317
318     @property
319     def summary(self):
320         content = strip_tags(self.html)
321
322         # Remove multiple spaces.
323         content = re.sub(' +',' ', content)
324
325         # Replace line breaks with a space, we don't need them at all.
326         content = content.replace("\n", ' ')
327
328         # Truncate and all an ellipsis if length greater than summary length.
329         content = (content[:SUMMARY_LENGTH] + '...') if len(content) > SUMMARY_LENGTH else content
330
331         return content
332
333     @models.permalink
334     def get_revisions_url(self):
335         return ('revisions', (), {'id': self.id})
336
337     def update_last_activity(self, user, save=False, time=None):
338         if not time:
339             time = datetime.datetime.now()
340
341         self.last_activity_by = user
342         self.last_activity_at = time
343
344         if self.parent:
345             self.parent.update_last_activity(user, save=True, time=time)
346
347         if save:
348             self.save()
349
350     def _create_revision(self, user, number, **kwargs):
351         revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
352         revision.save()
353         return revision
354
355     def create_revision(self, user, **kwargs):
356         number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
357         revision = self._create_revision(user, number, **kwargs)
358         self.activate_revision(user, revision)
359         return revision
360
361     def activate_revision(self, user, revision):
362         self.title = revision.title
363         self.tagnames = revision.tagnames
364
365         self.body = self.rendered(revision.body)
366
367         self.active_revision = revision
368
369         # Try getting the previous revision
370         try:
371             prev_revision = NodeRevision.objects.get(node=self, revision=revision.revision-1)
372
373             update_activity = True
374
375             # Do not update the activity if only the tags are changed
376             if prev_revision.title == revision.title and prev_revision.body == revision.body \
377             and prev_revision.tagnames != revision.tagnames and not settings.UPDATE_LATEST_ACTIVITY_ON_TAG_EDIT:
378                 update_activity = False
379         except NodeRevision.DoesNotExist:
380             update_activity = True
381         finally:
382             if update_activity:
383                 self.update_last_activity(user)
384
385         self.save()
386
387     def get_active_users(self, active_users = None):
388         if not active_users:
389             active_users = set()
390
391         active_users.add(self.author)
392
393         for node in self.children.all():
394             if not node.nis.deleted:
395                 node.get_active_users(active_users)
396
397         return active_users
398
399     def get_last_edited(self):
400         if not self.last_edited:
401             try:
402                 le = self.actions.exclude(action_type__in=('voteup', 'votedown', 'flag'), canceled=True).order_by('-action_date')[0]
403                 self.last_edited = le
404                 self.save()
405             except:
406                 pass
407
408         return self.last_edited
409
410
411     def _list_changes_in_tags(self):
412         dirty = self.get_dirty_fields()
413
414         if not 'tagnames' in dirty:
415             return None
416         else:
417             if self._original_state['tagnames']:
418                 old_tags = set(self._original_state['tagnames'].split())
419             else:
420                 old_tags = set()
421             new_tags = set(self.tagnames.split())
422
423             return dict(
424                     current=list(new_tags),
425                     added=list(new_tags - old_tags),
426                     removed=list(old_tags - new_tags)
427                     )
428
429     def _last_active_user(self):
430         return self.last_edited and self.last_edited.by or self.author
431
432     def _process_changes_in_tags(self):
433         tag_changes = self._list_changes_in_tags()
434
435         if tag_changes is not None:
436             for name in tag_changes['added']:
437                 try:
438                     tag = Tag.objects.get(name=name)
439                 except Tag.DoesNotExist:
440                     tag = Tag.objects.create(name=name, created_by=self._last_active_user())
441
442                 if not self.nis.deleted:
443                     tag.add_to_usage_count(1)
444                     tag.save()
445
446             if not self.nis.deleted:
447                 for name in tag_changes['removed']:
448                     try:
449                         tag = Tag.objects.get(name=name)
450                         tag.add_to_usage_count(-1)
451                         tag.save()
452                     except:
453                         pass
454
455             return True
456
457         return False
458
459     def mark_deleted(self, action):
460         self.nstate.deleted = action
461         self.save()
462
463         if action:
464             for tag in self.tags.all():
465                 tag.add_to_usage_count(-1)
466                 tag.save()
467         else:
468             for tag in Tag.objects.filter(name__in=self.tagname_list()):
469                 tag.add_to_usage_count(1)
470                 tag.save()
471
472     def delete(self, *args, **kwargs):
473         for tag in self.tags.all():
474             tag.add_to_usage_count(-1)
475             tag.save()
476
477         self.active_revision = None
478         self.save()
479
480         for n in self.children.all():
481             n.delete()
482
483         for a in self.actions.all():
484             a.cancel()
485
486         super(Node, self).delete(*args, **kwargs)
487
488     def save(self, *args, **kwargs):
489         if not self.id:
490             self.node_type = self.get_type()
491             super(BaseModel, self).save(*args, **kwargs)
492             self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
493                                                          body=self.body)
494             self.activate_revision(self.author, self.active_revision)
495             self.update_last_activity(self.author, time=self.added_at)
496
497         if self.parent_id and not self.abs_parent_id:
498             self.abs_parent = self.parent.absolute_parent
499         
500         tags_changed = self._process_changes_in_tags()
501         
502         super(Node, self).save(*args, **kwargs)
503         if tags_changed:
504             if self.tagnames.strip():
505                 self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
506             else:
507                 self.tags = []
508
509     class Meta:
510         app_label = 'forum'
511
512
513 class NodeRevision(BaseModel, NodeContent):
514     node       = models.ForeignKey(Node, related_name='revisions')
515     summary    = models.CharField(max_length=300)
516     revision   = models.PositiveIntegerField()
517     revised_at = models.DateTimeField(default=datetime.datetime.now)
518
519     class Meta:
520         unique_together = ('node', 'revision')
521         app_label = 'forum'
522
523
524 class NodeState(models.Model):
525     node       = models.ForeignKey(Node, related_name='states')
526     state_type = models.CharField(max_length=16)
527     action     = models.OneToOneField('Action', related_name="node_state")
528
529     class Meta:
530         unique_together = ('node', 'state_type')
531         app_label = 'forum'
532
533