1 # -*- coding: utf-8 -*-
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
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()
31 def rendered(self, content):
32 return auto_user_link(self, self._as_markdown(content, *['auto_linker']))
35 def _as_markdown(cls, content, *extensions):
37 return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
40 logging.error("Caught exception %s in markdown parser rendering %s %s:\s %s" % (
41 str(e), cls.__name__, str(e), traceback.format_exc()))
44 def as_markdown(self, *extensions):
45 return self._as_markdown(smart_unicode(self.body), *extensions)
51 # Replaces multiple spaces with single ones.
52 title = re.sub(' +',' ', title)
56 def tagname_list(self):
58 return [name.strip() for name in self.tagnames.split() if name]
62 def tagname_meta_generator(self):
63 return u','.join([tag for tag in self.tagname_list()])
69 class NodeMetaClass(BaseMetaClass):
72 def __new__(cls, *args, **kwargs):
73 new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
75 if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
76 NodeMetaClass.types[new_cls.get_type()] = new_cls
81 def setup_relations(cls):
82 for node_cls in NodeMetaClass.types.values():
83 NodeMetaClass.setup_relation(node_cls)
86 def setup_relation(cls, node_cls):
87 name = node_cls.__name__.lower()
90 return node_cls.objects.filter(parent=self)
93 if (self.parent is not None) and self.parent.node_type == name:
94 return self.parent.leaf
98 Node.add_to_class(name + 's', property(children))
99 Node.add_to_class(name, property(parent))
102 class NodeQuerySet(CachedQuerySet):
103 def obj_from_datadict(self, datadict):
104 cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
107 obj.__dict__.update(datadict)
110 return super(NodeQuerySet, self).obj_from_datadict(datadict)
112 def get(self, *args, **kwargs):
113 node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
115 if not isinstance(node, self.model):
116 raise self.model.DoesNotExist()
120 def any_state(self, *args):
124 s_filter = models.Q(state_string__contains="(%s)" % s)
125 filter = filter and (filter | s_filter) or s_filter
128 return self.filter(filter)
132 def all_states(self, *args):
136 s_filter = models.Q(state_string__contains="(%s)" % s)
137 filter = filter and (filter & s_filter) or s_filter
140 return self.filter(filter)
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()])
148 def children_count(self, child_type):
149 return NodeMetaClass.types[child_type].objects.filter_state(deleted=False).filter(parent__in=self).count()
152 class NodeManager(CachedManager):
153 use_for_related_fields = True
155 def get_query_set(self):
156 qs = NodeQuerySet(self.model)
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())
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)
168 def filter_state(self, **kwargs):
169 return self.all().filter_state(**kwargs)
172 class NodeStateDict(object):
173 def __init__(self, node):
174 self.__dict__['_node'] = node
176 def __getattr__(self, name):
177 if self.__dict__.get(name, None):
178 return self.__dict__[name]
181 node = self.__dict__['_node']
182 action = NodeState.objects.get(node=node, state_type=name).action
183 self.__dict__[name] = action
188 def __setattr__(self, name, value):
189 current = self.__getattr__(name)
193 current.action = value
196 node = self.__dict__['_node']
197 state = NodeState(node=node, action=value, state_type=name)
199 self.__dict__[name] = value
201 if not "(%s)" % name in node.state_string:
202 node.state_string = "%s(%s)" % (node.state_string, name)
206 node = self.__dict__['_node']
207 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
209 current.node_state.delete()
210 del self.__dict__[name]
213 class NodeStateQuery(object):
214 def __init__(self, node):
215 self.__dict__['_node'] = node
217 def __getattr__(self, name):
218 node = self.__dict__['_node']
219 return "(%s)" % name in node.state_string
222 class Node(BaseModel, NodeContent):
223 __metaclass__ = NodeMetaClass
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)
229 added_at = models.DateTimeField(default=datetime.datetime.now)
230 score = models.IntegerField(default=0)
232 state_string = models.TextField(default='')
233 last_edited = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
235 last_activity_by = models.ForeignKey(User, null=True)
236 last_activity_at = models.DateTimeField(null=True, blank=True)
238 tags = models.ManyToManyField('Tag', related_name='%(class)ss')
239 active_revision = models.OneToOneField('NodeRevision', related_name='active', null=True)
241 extra = PickledObjectField()
242 extra_ref = models.ForeignKey('Node', null=True)
243 extra_count = models.IntegerField(default=0)
245 marked = models.BooleanField(default=False)
247 comment_count = DenormalizedField("children", node_type="comment", canceled=False)
248 flag_count = DenormalizedField("actions", action_type="flag", canceled=False)
250 friendly_name = _("post")
252 objects = NodeManager()
254 def __unicode__(self):
258 def _generate_cache_key(cls, key, group="node"):
259 return super(Node, cls)._generate_cache_key(key, group)
263 return cls.__name__.lower()
267 leaf_cls = NodeMetaClass.types.get(self.node_type, None)
273 leaf.__dict__ = self.__dict__
278 state = self.__dict__.get('_nstate', None)
281 state = NodeStateDict(self)
288 nis = self.__dict__.get('_nis', None)
291 nis = NodeStateQuery(self)
297 def last_activity(self):
299 return self.actions.order_by('-action_date')[0].action_date
301 return self.last_seen
304 def state_list(self):
305 return [s.state_type for s in self.states.all()]
309 return self.nis.deleted
312 def absolute_parent(self):
313 if not self.abs_parent_id:
316 return self.abs_parent
320 content = strip_tags(self.html)
322 # Remove multiple spaces.
323 content = re.sub(' +',' ', content)
325 # Replace line breaks with a space, we don't need them at all.
326 content = content.replace("\n", ' ')
328 # Truncate and all an ellipsis if length greater than summary length.
329 content = (content[:SUMMARY_LENGTH] + '...') if len(content) > SUMMARY_LENGTH else content
334 def get_revisions_url(self):
335 return ('revisions', (), {'id': self.id})
337 def update_last_activity(self, user, save=False, time=None):
339 time = datetime.datetime.now()
341 self.last_activity_by = user
342 self.last_activity_at = time
345 self.parent.update_last_activity(user, save=True, time=time)
350 def _create_revision(self, user, number, **kwargs):
351 revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
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)
361 def activate_revision(self, user, revision):
362 self.title = revision.title
363 self.tagnames = revision.tagnames
365 self.body = self.rendered(revision.body)
367 self.active_revision = revision
369 # Try getting the previous revision
371 prev_revision = NodeRevision.objects.get(node=self, revision=revision.revision-1)
373 update_activity = True
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
383 self.update_last_activity(user)
387 def get_active_users(self, active_users = None):
391 active_users.add(self.author)
393 for node in self.children.all():
394 if not node.nis.deleted:
395 node.get_active_users(active_users)
399 def get_last_edited(self):
400 if not self.last_edited:
402 le = self.actions.exclude(action_type__in=('voteup', 'votedown', 'flag'), canceled=True).order_by('-action_date')[0]
403 self.last_edited = le
408 return self.last_edited
411 def _list_changes_in_tags(self):
412 dirty = self.get_dirty_fields()
414 if not 'tagnames' in dirty:
417 if self._original_state['tagnames']:
418 old_tags = set(self._original_state['tagnames'].split())
421 new_tags = set(self.tagnames.split())
424 current=list(new_tags),
425 added=list(new_tags - old_tags),
426 removed=list(old_tags - new_tags)
429 def _last_active_user(self):
430 return self.last_edited and self.last_edited.by or self.author
432 def _process_changes_in_tags(self):
433 tag_changes = self._list_changes_in_tags()
435 if tag_changes is not None:
436 for name in tag_changes['added']:
438 tag = Tag.objects.get(name=name)
439 except Tag.DoesNotExist:
440 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
442 if not self.nis.deleted:
443 tag.add_to_usage_count(1)
446 if not self.nis.deleted:
447 for name in tag_changes['removed']:
449 tag = Tag.objects.get(name=name)
450 tag.add_to_usage_count(-1)
459 def mark_deleted(self, action):
460 self.nstate.deleted = action
464 for tag in self.tags.all():
465 tag.add_to_usage_count(-1)
468 for tag in Tag.objects.filter(name__in=self.tagname_list()):
469 tag.add_to_usage_count(1)
472 def delete(self, *args, **kwargs):
473 for tag in self.tags.all():
474 tag.add_to_usage_count(-1)
477 self.active_revision = None
480 for n in self.children.all():
483 for a in self.actions.all():
486 super(Node, self).delete(*args, **kwargs)
488 def save(self, *args, **kwargs):
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,
494 self.activate_revision(self.author, self.active_revision)
495 self.update_last_activity(self.author, time=self.added_at)
497 if self.parent_id and not self.abs_parent_id:
498 self.abs_parent = self.parent.absolute_parent
500 tags_changed = self._process_changes_in_tags()
502 super(Node, self).save(*args, **kwargs)
504 if self.tagnames.strip():
505 self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
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)
520 unique_together = ('node', 'revision')
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")
530 unique_together = ('node', 'state_type')