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)[:SUMMARY_LENGTH]
322 # Remove multiple spaces.
323 content = re.sub(' +',' ', content)
325 # Remove line breaks. We don't need them at all.
326 content = content.replace("\n", '')
331 def get_revisions_url(self):
332 return ('revisions', (), {'id': self.id})
334 def update_last_activity(self, user, save=False, time=None):
336 time = datetime.datetime.now()
338 self.last_activity_by = user
339 self.last_activity_at = time
342 self.parent.update_last_activity(user, save=True, time=time)
347 def _create_revision(self, user, number, **kwargs):
348 revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
352 def create_revision(self, user, **kwargs):
353 number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
354 revision = self._create_revision(user, number, **kwargs)
355 self.activate_revision(user, revision)
358 def activate_revision(self, user, revision):
359 self.title = revision.title
360 self.tagnames = revision.tagnames
362 self.body = self.rendered(revision.body)
364 self.active_revision = revision
366 # Try getting the previous revision
368 prev_revision = NodeRevision.objects.get(node=self, revision=revision.revision-1)
370 update_activity = True
372 # Do not update the activity if only the tags are changed
373 if prev_revision.title == revision.title and prev_revision.body == revision.body \
374 and prev_revision.tagnames != revision.tagnames and not settings.UPDATE_LATEST_ACTIVITY_ON_TAG_EDIT:
375 update_activity = False
376 except NodeRevision.DoesNotExist:
377 update_activity = True
380 self.update_last_activity(user)
384 def get_active_users(self, active_users = None):
388 active_users.add(self.author)
390 for node in self.children.all():
391 if not node.nis.deleted:
392 node.get_active_users(active_users)
396 def get_last_edited(self):
397 if not self.last_edited:
399 le = self.actions.exclude(action_type__in=('voteup', 'votedown', 'flag'), canceled=True).order_by('-action_date')[0]
400 self.last_edited = le
405 return self.last_edited
408 def _list_changes_in_tags(self):
409 dirty = self.get_dirty_fields()
411 if not 'tagnames' in dirty:
414 if self._original_state['tagnames']:
415 old_tags = set(self._original_state['tagnames'].split())
418 new_tags = set(self.tagnames.split())
421 current=list(new_tags),
422 added=list(new_tags - old_tags),
423 removed=list(old_tags - new_tags)
426 def _last_active_user(self):
427 return self.last_edited and self.last_edited.by or self.author
429 def _process_changes_in_tags(self):
430 tag_changes = self._list_changes_in_tags()
432 if tag_changes is not None:
433 for name in tag_changes['added']:
435 tag = Tag.objects.get(name=name)
436 except Tag.DoesNotExist:
437 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
439 if not self.nis.deleted:
440 tag.add_to_usage_count(1)
443 if not self.nis.deleted:
444 for name in tag_changes['removed']:
446 tag = Tag.objects.get(name=name)
447 tag.add_to_usage_count(-1)
456 def mark_deleted(self, action):
457 self.nstate.deleted = action
461 for tag in self.tags.all():
462 tag.add_to_usage_count(-1)
465 for tag in Tag.objects.filter(name__in=self.tagname_list()):
466 tag.add_to_usage_count(1)
469 def delete(self, *args, **kwargs):
470 for tag in self.tags.all():
471 tag.add_to_usage_count(-1)
474 self.active_revision = None
477 for n in self.children.all():
480 for a in self.actions.all():
483 super(Node, self).delete(*args, **kwargs)
485 def save(self, *args, **kwargs):
487 self.node_type = self.get_type()
488 super(BaseModel, self).save(*args, **kwargs)
489 self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
491 self.activate_revision(self.author, self.active_revision)
492 self.update_last_activity(self.author, time=self.added_at)
494 if self.parent_id and not self.abs_parent_id:
495 self.abs_parent = self.parent.absolute_parent
497 tags_changed = self._process_changes_in_tags()
499 super(Node, self).save(*args, **kwargs)
501 if self.tagnames.strip():
502 self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
510 class NodeRevision(BaseModel, NodeContent):
511 node = models.ForeignKey(Node, related_name='revisions')
512 summary = models.CharField(max_length=300)
513 revision = models.PositiveIntegerField()
514 revised_at = models.DateTimeField(default=datetime.datetime.now)
517 unique_together = ('node', 'revision')
521 class NodeState(models.Model):
522 node = models.ForeignKey(Node, related_name='states')
523 state_type = models.CharField(max_length=16)
524 action = models.OneToOneField('Action', related_name="node_state")
527 unique_together = ('node', 'state_type')