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 forum.utils.userlinking import auto_user_link
11 from forum.settings import SUMMARY_LENGTH
12 from utils import PickledObjectField
14 class NodeContent(models.Model):
15 title = models.CharField(max_length=300)
16 tagnames = models.CharField(max_length=125)
17 author = models.ForeignKey(User, related_name='%(class)ss')
18 body = models.TextField()
28 def rendered(self, content):
29 return auto_user_link(self, self._as_markdown(content, *['auto_linker']))
32 def _as_markdown(cls, content, *extensions):
34 return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
37 logging.error("Caught exception %s in markdown parser rendering %s %s:\s %s" % (
38 str(e), cls.__name__, str(e), traceback.format_exc()))
41 def as_markdown(self, *extensions):
42 return self._as_markdown(self.body, *extensions)
48 # Replaces multiple spaces with single ones.
49 title = re.sub(' +',' ', title)
53 def tagname_list(self):
55 return [name.strip() for name in self.tagnames.split() if name]
59 def tagname_meta_generator(self):
60 return u','.join([tag for tag in self.tagname_list()])
66 class NodeMetaClass(BaseMetaClass):
69 def __new__(cls, *args, **kwargs):
70 new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
72 if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
73 NodeMetaClass.types[new_cls.get_type()] = new_cls
78 def setup_relations(cls):
79 for node_cls in NodeMetaClass.types.values():
80 NodeMetaClass.setup_relation(node_cls)
83 def setup_relation(cls, node_cls):
84 name = node_cls.__name__.lower()
87 return node_cls.objects.filter(parent=self)
90 if (self.parent is not None) and self.parent.node_type == name:
91 return self.parent.leaf
95 Node.add_to_class(name + 's', property(children))
96 Node.add_to_class(name, property(parent))
99 class NodeQuerySet(CachedQuerySet):
100 def obj_from_datadict(self, datadict):
101 cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
104 obj.__dict__.update(datadict)
107 return super(NodeQuerySet, self).obj_from_datadict(datadict)
109 def get(self, *args, **kwargs):
110 node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
112 if not isinstance(node, self.model):
113 raise self.model.DoesNotExist()
117 def any_state(self, *args):
121 s_filter = models.Q(state_string__contains="(%s)" % s)
122 filter = filter and (filter | s_filter) or s_filter
125 return self.filter(filter)
129 def all_states(self, *args):
133 s_filter = models.Q(state_string__contains="(%s)" % s)
134 filter = filter and (filter & s_filter) or s_filter
137 return self.filter(filter)
141 def filter_state(self, **kwargs):
142 apply_bool = lambda q, b: b and q or ~q
143 return self.filter(*[apply_bool(models.Q(state_string__contains="(%s)" % s), b) for s, b in kwargs.items()])
145 def children_count(self, child_type):
146 return NodeMetaClass.types[child_type].objects.filter_state(deleted=False).filter(parent__in=self).count()
149 class NodeManager(CachedManager):
150 use_for_related_fields = True
152 def get_query_set(self):
153 qs = NodeQuerySet(self.model)
155 # If the node is an answer, question or comment we filter the Node model by type
156 if self.model is not Node:
157 qs = qs.filter(node_type=self.model.get_type())
161 def get_for_types(self, types, *args, **kwargs):
162 kwargs['node_type__in'] = [t.get_type() for t in types]
163 return self.get(*args, **kwargs)
165 def filter_state(self, **kwargs):
166 return self.all().filter_state(**kwargs)
169 class NodeStateDict(object):
170 def __init__(self, node):
171 self.__dict__['_node'] = node
173 def __getattr__(self, name):
174 if self.__dict__.get(name, None):
175 return self.__dict__[name]
178 node = self.__dict__['_node']
179 action = NodeState.objects.get(node=node, state_type=name).action
180 self.__dict__[name] = action
185 def __setattr__(self, name, value):
186 current = self.__getattr__(name)
190 current.action = value
193 node = self.__dict__['_node']
194 state = NodeState(node=node, action=value, state_type=name)
196 self.__dict__[name] = value
198 if not "(%s)" % name in node.state_string:
199 node.state_string = "%s(%s)" % (node.state_string, name)
203 node = self.__dict__['_node']
204 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
206 current.node_state.delete()
207 del self.__dict__[name]
210 class NodeStateQuery(object):
211 def __init__(self, node):
212 self.__dict__['_node'] = node
214 def __getattr__(self, name):
215 node = self.__dict__['_node']
216 return "(%s)" % name in node.state_string
219 class Node(BaseModel, NodeContent):
220 __metaclass__ = NodeMetaClass
222 node_type = models.CharField(max_length=16, default='node')
223 parent = models.ForeignKey('Node', related_name='children', null=True)
224 abs_parent = models.ForeignKey('Node', related_name='all_children', null=True)
226 added_at = models.DateTimeField(default=datetime.datetime.now)
227 score = models.IntegerField(default=0)
229 state_string = models.TextField(default='')
230 last_edited = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
232 last_activity_by = models.ForeignKey(User, null=True)
233 last_activity_at = models.DateTimeField(null=True, blank=True)
235 tags = models.ManyToManyField('Tag', related_name='%(class)ss')
236 active_revision = models.OneToOneField('NodeRevision', related_name='active', null=True)
238 extra = PickledObjectField()
239 extra_ref = models.ForeignKey('Node', null=True)
240 extra_count = models.IntegerField(default=0)
242 marked = models.BooleanField(default=False)
244 comment_count = DenormalizedField("children", node_type="comment", canceled=False)
245 flag_count = DenormalizedField("flags")
247 friendly_name = _("post")
249 objects = NodeManager()
251 def __unicode__(self):
255 def _generate_cache_key(cls, key, group="node"):
256 return super(Node, cls)._generate_cache_key(key, group)
260 return cls.__name__.lower()
264 leaf_cls = NodeMetaClass.types.get(self.node_type, None)
270 leaf.__dict__ = self.__dict__
275 state = self.__dict__.get('_nstate', None)
278 state = NodeStateDict(self)
285 nis = self.__dict__.get('_nis', None)
288 nis = NodeStateQuery(self)
294 def last_activity(self):
296 return self.actions.order_by('-action_date')[0].action_date
298 return self.last_seen
301 def state_list(self):
302 return [s.state_type for s in self.states.all()]
306 return self.nis.deleted
309 def absolute_parent(self):
310 if not self.abs_parent_id:
313 return self.abs_parent
317 content = strip_tags(self.html)[:SUMMARY_LENGTH]
319 # Remove multiple spaces.
320 content = re.sub(' +',' ', content)
322 # Remove line breaks. We don't need them at all.
323 content = content.replace("\n", '')
328 def get_revisions_url(self):
329 return ('revisions', (), {'id': self.id})
331 def update_last_activity(self, user, save=False, time=None):
333 time = datetime.datetime.now()
335 self.last_activity_by = user
336 self.last_activity_at = time
339 self.parent.update_last_activity(user, save=True, time=time)
344 def _create_revision(self, user, number, **kwargs):
345 revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
349 def create_revision(self, user, **kwargs):
350 number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
351 revision = self._create_revision(user, number, **kwargs)
352 self.activate_revision(user, revision)
355 def activate_revision(self, user, revision):
356 self.title = revision.title
357 self.tagnames = revision.tagnames
359 self.body = self.rendered(revision.body)
361 self.active_revision = revision
363 # Try getting the previous revision
365 prev_revision = NodeRevision.objects.get(node=self, revision=revision.revision-1)
367 update_activity = True
369 # Do not update the activity if only the tags are changed
370 if prev_revision.title == revision.title and prev_revision.body == revision.body \
371 and prev_revision.tagnames != revision.tagnames and not settings.UPDATE_LATEST_ACTIVITY_ON_TAG_EDIT:
372 update_activity = False
373 except NodeRevision.DoesNotExist:
374 update_activity = True
377 self.update_last_activity(user)
381 def get_active_users(self, active_users = None):
385 active_users.add(self.author)
387 for node in self.children.all():
388 if not node.nis.deleted:
389 node.get_active_users(active_users)
393 def get_last_edited(self):
394 if not self.last_edited:
396 le = self.actions.exclude(action_type__in=('voteup', 'votedown', 'flag'), canceled=True).order_by('-action_date')[0]
397 self.last_edited = le
402 return self.last_edited
405 def _list_changes_in_tags(self):
406 dirty = self.get_dirty_fields()
408 if not 'tagnames' in dirty:
411 if self._original_state['tagnames']:
412 old_tags = set(self._original_state['tagnames'].split())
415 new_tags = set(self.tagnames.split())
418 current=list(new_tags),
419 added=list(new_tags - old_tags),
420 removed=list(old_tags - new_tags)
423 def _last_active_user(self):
424 return self.last_edited and self.last_edited.by or self.author
426 def _process_changes_in_tags(self):
427 tag_changes = self._list_changes_in_tags()
429 if tag_changes is not None:
430 for name in tag_changes['added']:
432 tag = Tag.objects.get(name=name)
433 except Tag.DoesNotExist:
434 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
436 if not self.nis.deleted:
437 tag.add_to_usage_count(1)
440 if not self.nis.deleted:
441 for name in tag_changes['removed']:
443 tag = Tag.objects.get(name=name)
444 tag.add_to_usage_count(-1)
453 def mark_deleted(self, action):
454 self.nstate.deleted = action
458 for tag in self.tags.all():
459 tag.add_to_usage_count(-1)
462 for tag in Tag.objects.filter(name__in=self.tagname_list()):
463 tag.add_to_usage_count(1)
466 def delete(self, *args, **kwargs):
467 for tag in self.tags.all():
468 tag.add_to_usage_count(-1)
471 self.active_revision = None
474 for n in self.children.all():
477 for a in self.actions.all():
480 super(Node, self).delete(*args, **kwargs)
482 def save(self, *args, **kwargs):
484 self.node_type = self.get_type()
485 super(BaseModel, self).save(*args, **kwargs)
486 self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
488 self.activate_revision(self.author, self.active_revision)
489 self.update_last_activity(self.author, time=self.added_at)
491 if self.parent_id and not self.abs_parent_id:
492 self.abs_parent = self.parent.absolute_parent
494 tags_changed = self._process_changes_in_tags()
496 super(Node, self).save(*args, **kwargs)
498 if self.tagnames.strip():
499 self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
507 class NodeRevision(BaseModel, NodeContent):
508 node = models.ForeignKey(Node, related_name='revisions')
509 summary = models.CharField(max_length=300)
510 revision = models.PositiveIntegerField()
511 revised_at = models.DateTimeField(default=datetime.datetime.now)
514 unique_together = ('node', 'revision')
518 class NodeState(models.Model):
519 node = models.ForeignKey(Node, related_name='states')
520 state_type = models.CharField(max_length=16)
521 action = models.OneToOneField('Action', related_name="node_state")
524 unique_together = ('node', 'state_type')