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 utils import PickledObjectField
12 class NodeContent(models.Model):
13 title = models.CharField(max_length=300)
14 tagnames = models.CharField(max_length=125)
15 author = models.ForeignKey(User, related_name='%(class)ss')
16 body = models.TextField()
27 def _as_markdown(cls, content, *extensions):
29 return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
32 logging.error("Caught exception %s in markdown parser rendering %s %s:\s %s" % (
33 str(e), cls.__name__, str(e), traceback.format_exc()))
36 def as_markdown(self, *extensions):
37 return self._as_markdown(self.body, *extensions)
43 def tagname_list(self):
45 t = [name.strip() for name in self.tagnames.split(u' ') if name]
46 return [name.strip() for name in self.tagnames.split(u' ') if name]
50 def tagname_meta_generator(self):
51 return u','.join([tag for tag in self.tagname_list()])
57 class NodeMetaClass(BaseMetaClass):
60 def __new__(cls, *args, **kwargs):
61 new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
63 if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
64 NodeMetaClass.types[new_cls.get_type()] = new_cls
69 def setup_relations(cls):
70 for node_cls in NodeMetaClass.types.values():
71 NodeMetaClass.setup_relation(node_cls)
74 def setup_relation(cls, node_cls):
75 name = node_cls.__name__.lower()
78 return node_cls.objects.filter(parent=self)
81 if (self.parent is not None) and self.parent.node_type == name:
82 return self.parent.leaf
86 Node.add_to_class(name + 's', property(children))
87 Node.add_to_class(name, property(parent))
90 class NodeQuerySet(CachedQuerySet):
91 def obj_from_datadict(self, datadict):
92 cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
95 obj.__dict__.update(datadict)
98 return super(NodeQuerySet, self).obj_from_datadict(datadict)
100 def get(self, *args, **kwargs):
101 node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
103 if not isinstance(node, self.model):
104 raise self.model.DoesNotExist()
108 def any_state(self, *args):
112 s_filter = models.Q(state_string__contains="(%s)" % s)
113 filter = filter and (filter | s_filter) or s_filter
116 return self.filter(filter)
120 def all_states(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 filter_state(self, **kwargs):
133 apply_bool = lambda q, b: b and q or ~q
134 return self.filter(*[apply_bool(models.Q(state_string__contains="(%s)" % s), b) for s, b in kwargs.items()])
136 def children_count(self, child_type):
137 return NodeMetaClass.types[child_type].objects.filter_state(deleted=False).filter(parent__in=self).count()
140 class NodeManager(CachedManager):
141 use_for_related_fields = True
143 def get_query_set(self):
144 qs = NodeQuerySet(self.model)
146 if self.model is not Node:
147 return qs.filter(node_type=self.model.get_type())
151 def get_for_types(self, types, *args, **kwargs):
152 kwargs['node_type__in'] = [t.get_type() for t in types]
153 return self.get(*args, **kwargs)
155 def filter_state(self, **kwargs):
156 return self.all().filter_state(**kwargs)
159 class NodeStateDict(object):
160 def __init__(self, node):
161 self.__dict__['_node'] = node
163 def __getattr__(self, name):
164 if self.__dict__.get(name, None):
165 return self.__dict__[name]
168 node = self.__dict__['_node']
169 action = NodeState.objects.get(node=node, state_type=name).action
170 self.__dict__[name] = action
175 def __setattr__(self, name, value):
176 current = self.__getattr__(name)
180 current.action = value
183 node = self.__dict__['_node']
184 state = NodeState(node=node, action=value, state_type=name)
186 self.__dict__[name] = value
188 if not "(%s)" % name in node.state_string:
189 node.state_string = "%s(%s)" % (node.state_string, name)
193 node = self.__dict__['_node']
194 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
196 current.node_state.delete()
197 del self.__dict__[name]
200 class NodeStateQuery(object):
201 def __init__(self, node):
202 self.__dict__['_node'] = node
204 def __getattr__(self, name):
205 node = self.__dict__['_node']
206 return "(%s)" % name in node.state_string
209 class Node(BaseModel, NodeContent):
210 __metaclass__ = NodeMetaClass
212 node_type = models.CharField(max_length=16, default='node')
213 parent = models.ForeignKey('Node', related_name='children', null=True)
214 abs_parent = models.ForeignKey('Node', related_name='all_children', null=True)
216 added_at = models.DateTimeField(default=datetime.datetime.now)
217 score = models.IntegerField(default=0)
219 state_string = models.TextField(default='')
220 last_edited = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
222 last_activity_by = models.ForeignKey(User, null=True)
223 last_activity_at = models.DateTimeField(null=True, blank=True)
225 tags = models.ManyToManyField('Tag', related_name='%(class)ss')
226 active_revision = models.OneToOneField('NodeRevision', related_name='active', null=True)
228 extra = PickledObjectField()
229 extra_ref = models.ForeignKey('Node', null=True)
230 extra_count = models.IntegerField(default=0)
232 marked = models.BooleanField(default=False)
234 comment_count = DenormalizedField("children", node_type="comment", canceled=False)
235 flag_count = DenormalizedField("flags")
237 friendly_name = _("post")
239 objects = NodeManager()
241 def __unicode__(self):
245 def _generate_cache_key(cls, key, group="node"):
246 return super(Node, cls)._generate_cache_key(key, group)
250 return cls.__name__.lower()
254 leaf_cls = NodeMetaClass.types.get(self.node_type, None)
260 leaf.__dict__ = self.__dict__
265 state = self.__dict__.get('_nstate', None)
268 state = NodeStateDict(self)
275 nis = self.__dict__.get('_nis', None)
278 nis = NodeStateQuery(self)
284 def last_activity(self):
286 return self.actions.order_by('-action_date')[0].action_date
288 return self.last_seen
291 def state_list(self):
292 return [s.state_type for s in self.states.all()]
296 return self.nis.deleted
299 def absolute_parent(self):
300 if not self.abs_parent_id:
303 return self.abs_parent
307 return strip_tags(self.html)[:300]
310 def get_revisions_url(self):
311 return ('revisions', (), {'id': self.id})
313 def update_last_activity(self, user, save=False, time=None):
315 time = datetime.datetime.now()
317 self.last_activity_by = user
318 self.last_activity_at = time
321 self.parent.update_last_activity(user, save=True, time=time)
326 def _create_revision(self, user, number, **kwargs):
327 revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
331 def create_revision(self, user, **kwargs):
332 number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
333 revision = self._create_revision(user, number, **kwargs)
334 self.activate_revision(user, revision, extensions=['urlize'])
337 def activate_revision(self, user, revision, extensions):
338 self.title = revision.title
339 self.tagnames = revision.tagnames
340 self.body = self._as_markdown(revision.body, *extensions)
342 self.active_revision = revision
343 self.update_last_activity(user)
347 def _list_changes_in_tags(self):
348 dirty = self.get_dirty_fields()
350 if not 'tagnames' in dirty:
353 if self._original_state['tagnames']:
354 old_tags = set(name for name in self._original_state['tagnames'].split(u' '))
357 new_tags = set(name for name in self.tagnames.split(u' ') if name)
360 current=list(new_tags),
361 added=list(new_tags - old_tags),
362 removed=list(old_tags - new_tags)
365 def _last_active_user(self):
366 return self.last_edited and self.last_edited.by or self.author
368 def _process_changes_in_tags(self):
369 tag_changes = self._list_changes_in_tags()
371 if tag_changes is not None:
372 for name in tag_changes['added']:
374 tag = Tag.objects.get(name=name)
376 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
378 if not self.nis.deleted:
379 tag.add_to_usage_count(1)
382 if not self.nis.deleted:
383 for name in tag_changes['removed']:
385 tag = Tag.objects.get(name=name)
386 tag.add_to_usage_count(-1)
395 def mark_deleted(self, action):
396 self.nstate.deleted = action
400 for tag in self.tags.all():
401 tag.add_to_usage_count(-1)
404 for tag in Tag.objects.filter(name__in=self.tagname_list()):
405 tag.add_to_usage_count(1)
408 def delete(self, *args, **kwargs):
409 self.active_revision = None
412 for n in self.children.all():
415 for a in self.actions.all():
418 super(Node, self).delete(*args, **kwargs)
420 def save(self, *args, **kwargs):
421 tags_changed = self._process_changes_in_tags()
424 self.node_type = self.get_type()
425 super(BaseModel, self).save(*args, **kwargs)
426 self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
428 self.activate_revision(self.author, self.active_revision)
429 self.update_last_activity(self.author, time=self.added_at)
431 if self.parent_id and not self.abs_parent_id:
432 self.abs_parent = self.parent.absolute_parent
434 super(Node, self).save(*args, **kwargs)
435 if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
441 class NodeRevision(BaseModel, NodeContent):
442 node = models.ForeignKey(Node, related_name='revisions')
443 summary = models.CharField(max_length=300)
444 revision = models.PositiveIntegerField()
445 revised_at = models.DateTimeField(default=datetime.datetime.now)
448 unique_together = ('node', 'revision')
452 class NodeState(models.Model):
453 node = models.ForeignKey(Node, related_name='states')
454 state_type = models.CharField(max_length=16)
455 action = models.OneToOneField('Action', related_name="node_state")
458 unique_together = ('node', 'state_type')