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_raw(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 # Replace \ with \\ to preserve backslashes during markdown processing
43 def _as_markdown(cls, content, *extensions):
44 return cls._as_markdown_raw(content.replace('\\','\\\\'), *extensions)
46 def as_markdown(self, *extensions):
47 return self._as_markdown(self.body, *extensions)
53 # Replaces multiple spaces with single ones.
54 title = re.sub(' +',' ', title)
58 def tagname_list(self):
60 return [name.strip() for name in self.tagnames.split() if name]
64 def tagname_meta_generator(self):
65 return u','.join([tag for tag in self.tagname_list()])
71 class NodeMetaClass(BaseMetaClass):
74 def __new__(cls, *args, **kwargs):
75 new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
77 if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
78 NodeMetaClass.types[new_cls.get_type()] = new_cls
83 def setup_relations(cls):
84 for node_cls in NodeMetaClass.types.values():
85 NodeMetaClass.setup_relation(node_cls)
88 def setup_relation(cls, node_cls):
89 name = node_cls.__name__.lower()
92 return node_cls.objects.filter(parent=self)
95 if (self.parent is not None) and self.parent.node_type == name:
96 return self.parent.leaf
100 Node.add_to_class(name + 's', property(children))
101 Node.add_to_class(name, property(parent))
104 class NodeQuerySet(CachedQuerySet):
105 def obj_from_datadict(self, datadict):
106 cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
109 obj.__dict__.update(datadict)
112 return super(NodeQuerySet, self).obj_from_datadict(datadict)
114 def get(self, *args, **kwargs):
115 node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
117 if not isinstance(node, self.model):
118 raise self.model.DoesNotExist()
122 def any_state(self, *args):
126 s_filter = models.Q(state_string__contains="(%s)" % s)
127 filter = filter and (filter | s_filter) or s_filter
130 return self.filter(filter)
134 def all_states(self, *args):
138 s_filter = models.Q(state_string__contains="(%s)" % s)
139 filter = filter and (filter & s_filter) or s_filter
142 return self.filter(filter)
146 def filter_state(self, **kwargs):
147 apply_bool = lambda q, b: b and q or ~q
148 return self.filter(*[apply_bool(models.Q(state_string__contains="(%s)" % s), b) for s, b in kwargs.items()])
150 def children_count(self, child_type):
151 return NodeMetaClass.types[child_type].objects.filter_state(deleted=False).filter(parent__in=self).count()
154 class NodeManager(CachedManager):
155 use_for_related_fields = True
157 def get_query_set(self):
158 qs = NodeQuerySet(self.model)
160 # If the node is an answer, question or comment we filter the Node model by type
161 if self.model is not Node:
162 qs = qs.filter(node_type=self.model.get_type())
166 def get_for_types(self, types, *args, **kwargs):
167 kwargs['node_type__in'] = [t.get_type() for t in types]
168 return self.get(*args, **kwargs)
170 def filter_state(self, **kwargs):
171 return self.all().filter_state(**kwargs)
174 class NodeStateDict(object):
175 def __init__(self, node):
176 self.__dict__['_node'] = node
178 def __getattr__(self, name):
179 if self.__dict__.get(name, None):
180 return self.__dict__[name]
183 node = self.__dict__['_node']
184 action = NodeState.objects.get(node=node, state_type=name).action
185 self.__dict__[name] = action
190 def __setattr__(self, name, value):
191 current = self.__getattr__(name)
195 current.action = value
198 node = self.__dict__['_node']
199 state = NodeState(node=node, action=value, state_type=name)
201 self.__dict__[name] = value
203 if not "(%s)" % name in node.state_string:
204 node.state_string = "%s(%s)" % (node.state_string, name)
208 node = self.__dict__['_node']
209 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
211 current.node_state.delete()
212 del self.__dict__[name]
215 class NodeStateQuery(object):
216 def __init__(self, node):
217 self.__dict__['_node'] = node
219 def __getattr__(self, name):
220 node = self.__dict__['_node']
221 return "(%s)" % name in node.state_string
224 class Node(BaseModel, NodeContent):
225 __metaclass__ = NodeMetaClass
227 node_type = models.CharField(max_length=16, default='node')
228 parent = models.ForeignKey('Node', related_name='children', null=True)
229 abs_parent = models.ForeignKey('Node', related_name='all_children', null=True)
231 added_at = models.DateTimeField(default=datetime.datetime.now)
232 score = models.IntegerField(default=0)
234 state_string = models.TextField(default='')
235 last_edited = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
237 last_activity_by = models.ForeignKey(User, null=True)
238 last_activity_at = models.DateTimeField(null=True, blank=True)
240 tags = models.ManyToManyField('Tag', related_name='%(class)ss')
241 active_revision = models.OneToOneField('NodeRevision', related_name='active', null=True)
243 extra = PickledObjectField()
244 extra_ref = models.ForeignKey('Node', null=True)
245 extra_count = models.IntegerField(default=0)
247 marked = models.BooleanField(default=False)
249 comment_count = DenormalizedField("children", node_type="comment", canceled=False)
250 flag_count = DenormalizedField("flags")
252 friendly_name = _("post")
254 objects = NodeManager()
256 def __unicode__(self):
260 def _generate_cache_key(cls, key, group="node"):
261 return super(Node, cls)._generate_cache_key(key, group)
265 return cls.__name__.lower()
269 leaf_cls = NodeMetaClass.types.get(self.node_type, None)
275 leaf.__dict__ = self.__dict__
280 state = self.__dict__.get('_nstate', None)
283 state = NodeStateDict(self)
290 nis = self.__dict__.get('_nis', None)
293 nis = NodeStateQuery(self)
299 def last_activity(self):
301 return self.actions.order_by('-action_date')[0].action_date
303 return self.last_seen
306 def state_list(self):
307 return [s.state_type for s in self.states.all()]
311 return self.nis.deleted
314 def absolute_parent(self):
315 if not self.abs_parent_id:
318 return self.abs_parent
322 content = strip_tags(self.html)[:SUMMARY_LENGTH]
324 # Remove multiple spaces.
325 content = re.sub(' +',' ', content)
327 # Remove line breaks. We don't need them at all.
328 content = content.replace("\n", '')
333 def get_revisions_url(self):
334 return ('revisions', (), {'id': self.id})
336 def update_last_activity(self, user, save=False, time=None):
338 time = datetime.datetime.now()
340 self.last_activity_by = user
341 self.last_activity_at = time
344 self.parent.update_last_activity(user, save=True, time=time)
349 def _create_revision(self, user, number, **kwargs):
350 revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
354 def create_revision(self, user, **kwargs):
355 number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
356 revision = self._create_revision(user, number, **kwargs)
357 self.activate_revision(user, revision)
360 def activate_revision(self, user, revision):
361 self.title = revision.title
362 self.tagnames = revision.tagnames
364 self.body = self.rendered(revision.body)
366 self.active_revision = revision
368 # Try getting the previous revision
370 prev_revision = NodeRevision.objects.get(node=self, revision=revision.revision-1)
372 update_activity = True
374 # Do not update the activity if only the tags are changed
375 if prev_revision.title == revision.title and prev_revision.body == revision.body \
376 and prev_revision.tagnames != revision.tagnames and not settings.UPDATE_LATEST_ACTIVITY_ON_TAG_EDIT:
377 update_activity = False
378 except NodeRevision.DoesNotExist:
379 update_activity = True
382 self.update_last_activity(user)
386 def get_active_users(self, active_users = None):
390 active_users.add(self.author)
392 for node in self.children.all():
393 if not node.nis.deleted:
394 node.get_active_users(active_users)
398 def get_last_edited(self):
399 if not self.last_edited:
401 le = self.actions.exclude(action_type__in=('voteup', 'votedown', 'flag'), canceled=True).order_by('-action_date')[0]
402 self.last_edited = le
407 return self.last_edited
410 def _list_changes_in_tags(self):
411 dirty = self.get_dirty_fields()
413 if not 'tagnames' in dirty:
416 if self._original_state['tagnames']:
417 old_tags = set(self._original_state['tagnames'].split())
420 new_tags = set(self.tagnames.split())
423 current=list(new_tags),
424 added=list(new_tags - old_tags),
425 removed=list(old_tags - new_tags)
428 def _last_active_user(self):
429 return self.last_edited and self.last_edited.by or self.author
431 def _process_changes_in_tags(self):
432 tag_changes = self._list_changes_in_tags()
434 if tag_changes is not None:
435 for name in tag_changes['added']:
437 tag = Tag.objects.get(name=name)
438 except Tag.DoesNotExist:
439 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
441 if not self.nis.deleted:
442 tag.add_to_usage_count(1)
445 if not self.nis.deleted:
446 for name in tag_changes['removed']:
448 tag = Tag.objects.get(name=name)
449 tag.add_to_usage_count(-1)
458 def mark_deleted(self, action):
459 self.nstate.deleted = action
463 for tag in self.tags.all():
464 tag.add_to_usage_count(-1)
467 for tag in Tag.objects.filter(name__in=self.tagname_list()):
468 tag.add_to_usage_count(1)
471 def delete(self, *args, **kwargs):
472 for tag in self.tags.all():
473 tag.add_to_usage_count(-1)
476 self.active_revision = None
479 for n in self.children.all():
482 for a in self.actions.all():
485 super(Node, self).delete(*args, **kwargs)
487 def save(self, *args, **kwargs):
489 self.node_type = self.get_type()
490 super(BaseModel, self).save(*args, **kwargs)
491 self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
493 self.activate_revision(self.author, self.active_revision)
494 self.update_last_activity(self.author, time=self.added_at)
496 if self.parent_id and not self.abs_parent_id:
497 self.abs_parent = self.parent.absolute_parent
499 tags_changed = self._process_changes_in_tags()
501 super(Node, self).save(*args, **kwargs)
503 if self.tagnames.strip():
504 self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
512 class NodeRevision(BaseModel, NodeContent):
513 node = models.ForeignKey(Node, related_name='revisions')
514 summary = models.CharField(max_length=300)
515 revision = models.PositiveIntegerField()
516 revised_at = models.DateTimeField(default=datetime.datetime.now)
519 unique_together = ('node', 'revision')
523 class NodeState(models.Model):
524 node = models.ForeignKey(Node, related_name='states')
525 state_type = models.CharField(max_length=16)
526 action = models.OneToOneField('Action', related_name="node_state")
529 unique_together = ('node', 'state_type')