5 from django.utils.translation import ugettext as _
\r
6 from django.utils.safestring import mark_safe
\r
7 from django.utils.html import strip_tags
\r
8 from forum.utils.html import sanitize_html
\r
10 class NodeContent(models.Model):
\r
11 title = models.CharField(max_length=300)
\r
12 tagnames = models.CharField(max_length=125)
\r
13 author = models.ForeignKey(User, related_name='%(class)ss')
\r
14 body = models.TextField()
\r
22 return self.as_markdown()
\r
24 def as_markdown(self, *extensions):
\r
25 return mark_safe(sanitize_html(markdown.markdown(self.body, extensions=extensions)))
\r
31 def tagname_list(self):
\r
33 t = [name.strip() for name in self.tagnames.split(u' ') if name]
\r
34 return [name.strip() for name in self.tagnames.split(u' ') if name]
\r
38 def tagname_meta_generator(self):
\r
39 return u','.join([tag for tag in self.tagname_list()])
\r
45 class NodeMetaClass(BaseMetaClass):
\r
48 def __new__(cls, *args, **kwargs):
\r
49 new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
\r
51 if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
\r
52 NodeMetaClass.types[new_cls.get_type()] = new_cls
\r
57 def setup_relations(cls):
\r
58 for node_cls in NodeMetaClass.types.values():
\r
59 NodeMetaClass.setup_relation(node_cls)
\r
62 def setup_relation(cls, node_cls):
\r
63 name = node_cls.__name__.lower()
\r
66 return node_cls.objects.filter(parent=self)
\r
69 p = self.__dict__.get('_%s_cache' % name, None)
\r
71 if p is None and (self.parent is not None) and self.parent.node_type == name:
\r
72 p = self.parent.leaf
\r
73 self.__dict__['_%s_cache' % name] = p
\r
77 Node.add_to_class(name + 's', property(children))
\r
78 Node.add_to_class(name, property(parent))
\r
81 class NodeQuerySet(CachedQuerySet):
\r
82 def get(self, *args, **kwargs):
\r
83 node = super(NodeQuerySet, self).get(*args, **kwargs)
\r
84 cls = NodeMetaClass.types.get(node.node_type, None)
\r
86 if cls and (node.__class__ is not cls):
\r
91 class NodeManager(CachedManager):
\r
92 use_for_related_fields = True
\r
94 def get_query_set(self):
\r
95 qs = NodeQuerySet(self.model)
\r
97 if self.model is not Node:
\r
98 return qs.filter(node_type=self.model.get_type())
\r
102 def get_for_types(self, types, *args, **kwargs):
\r
103 kwargs['node_type__in'] = [t.get_type() for t in types]
\r
104 return self.get(*args, **kwargs)
\r
107 class Node(BaseModel, NodeContent):
\r
108 __metaclass__ = NodeMetaClass
\r
110 node_type = models.CharField(max_length=16, default='node')
\r
111 parent = models.ForeignKey('Node', related_name='children', null=True)
\r
112 abs_parent = models.ForeignKey('Node', related_name='all_children', null=True)
\r
114 added_at = models.DateTimeField(default=datetime.datetime.now)
\r
115 score = models.IntegerField(default=0)
\r
117 deleted = models.ForeignKey('Action', null=True, unique=True, related_name="deleted_node")
\r
118 in_moderation = models.ForeignKey('Action', null=True, unique=True, related_name="moderated_node")
\r
119 last_edited = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
\r
121 last_activity_by = models.ForeignKey(User, null=True)
\r
122 last_activity_at = models.DateTimeField(null=True, blank=True)
\r
124 tags = models.ManyToManyField('Tag', related_name='%(class)ss')
\r
125 active_revision = models.OneToOneField('NodeRevision', related_name='active', null=True)
\r
127 extra_ref = models.ForeignKey('Node', null=True)
\r
128 extra_count = models.IntegerField(default=0)
\r
129 extra_action = models.ForeignKey('Action', null=True, related_name="extra_node")
\r
131 marked = models.BooleanField(default=False)
\r
132 wiki = models.BooleanField(default=False)
\r
134 comment_count = DenormalizedField("children", node_type="comment", canceled=False)
\r
135 flag_count = DenormalizedField("flags")
\r
137 friendly_name = _("post")
\r
139 objects = NodeManager()
\r
142 def cache_key(cls, pk):
\r
143 return '%s.node:%s' % (settings.APP_URL, pk)
\r
147 return cls.__name__.lower()
\r
151 leaf_cls = NodeMetaClass.types.get(self.node_type, None)
\r
153 if leaf_cls is None:
\r
157 leaf.__dict__ = self.__dict__
\r
161 def absolute_parent(self):
\r
162 if not self.abs_parent_id:
\r
165 return self.abs_parent.leaf
\r
169 return strip_tags(self.html)[:300]
\r
172 def get_revisions_url(self):
\r
173 return ('revisions', (), {'id': self.id})
\r
175 def update_last_activity(self, user, save=False):
\r
176 self.last_activity_by = user
\r
177 self.last_activity_at = datetime.datetime.now()
\r
180 self.parent.update_last_activity(user, save=True)
\r
185 def _create_revision(self, user, number, **kwargs):
\r
186 revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
\r
190 def create_revision(self, user, **kwargs):
\r
191 number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
\r
192 revision = self._create_revision(user, number, **kwargs)
\r
193 self.activate_revision(user, revision)
\r
196 def activate_revision(self, user, revision):
\r
197 self.title = revision.title
\r
198 self.tagnames = revision.tagnames
\r
199 self.body = revision.body
\r
201 self.active_revision = revision
\r
202 self.update_last_activity(user)
\r
206 def _list_changes_in_tags(self):
\r
207 dirty = self.get_dirty_fields()
\r
209 if not 'tagnames' in dirty:
\r
212 if dirty['tagnames']:
\r
213 old_tags = set(name for name in dirty['tagnames'].split(u' '))
\r
216 new_tags = set(name for name in self.tagnames.split(u' ') if name)
\r
219 current=list(new_tags),
\r
220 added=list(new_tags - old_tags),
\r
221 removed=list(old_tags - new_tags)
\r
224 def _last_active_user(self):
\r
225 return self.last_edited and self.last_edited.by or self.author
\r
227 def _process_changes_in_tags(self):
\r
228 tag_changes = self._list_changes_in_tags()
\r
230 if tag_changes is not None:
\r
231 for name in tag_changes['added']:
\r
233 tag = Tag.objects.get(name=name)
\r
235 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
\r
237 if not self.deleted:
\r
238 tag.used_count = models.F('used_count') + 1
\r
241 if not self.deleted:
\r
242 for name in tag_changes['removed']:
\r
244 tag = Tag.objects.get(name=name)
\r
245 tag.used_count = models.F('used_count') - 1
\r
247 if tag.used_count == 0:
\r
248 tag.mark_deleted(self._last_active_user())
\r
256 def mark_deleted(self, action):
\r
257 self.deleted = action
\r
261 for tag in self.tags.all():
\r
262 tag.used_count = models.F('used_count') - 1
\r
264 if tag.used_count == 0:
\r
265 tag.mark_deleted(self._last_active_user())
\r
267 for tag in Tag.objects.filter(name__in=self.tagname_list()):
\r
268 tag.used_count = models.F('used_count') + 1
\r
271 def save(self, *args, **kwargs):
\r
273 self.node_type = self.get_type()
\r
274 super(BaseModel, self).save(*args, **kwargs)
\r
275 self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames, body=self.body)
\r
276 self.update_last_activity(self.author)
\r
278 if self.parent_id and not self.abs_parent_id:
\r
279 self.abs_parent = self.parent.absolute_parent
\r
281 tags_changed = self._process_changes_in_tags()
\r
283 super(Node, self).save(*args, **kwargs)
\r
284 if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
\r
287 app_label = 'forum'
\r
290 class NodeRevision(BaseModel, NodeContent):
\r
291 node = models.ForeignKey(Node, related_name='revisions')
\r
292 summary = models.CharField(max_length=300)
\r
293 revision = models.PositiveIntegerField()
\r
294 revised_at = models.DateTimeField(default=datetime.datetime.now)
\r
297 unique_together = ('node', 'revision')
\r
298 app_label = 'forum'
\r