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.userlinking import auto_user_link
10 from forum.utils.html import sanitize_html
11 from utils import PickledObjectField
13 class NodeContent(models.Model):
14 title = models.CharField(max_length=300)
15 tagnames = models.CharField(max_length=125)
16 author = models.ForeignKey(User, related_name='%(class)ss')
17 body = models.TextField()
28 def _as_markdown(cls, content, *extensions):
30 return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
33 logging.error("Caught exception %s in markdown parser rendering %s %s:\s %s" % (
34 str(e), cls.__name__, str(e), traceback.format_exc()))
37 def as_markdown(self, *extensions):
38 return self._as_markdown(self.body, *extensions)
44 def tagname_list(self):
46 t = [name.strip() for name in self.tagnames.split(u' ') if name]
47 return [name.strip() for name in self.tagnames.split(u' ') if name]
51 def tagname_meta_generator(self):
52 return u','.join([tag for tag in self.tagname_list()])
58 class NodeMetaClass(BaseMetaClass):
61 def __new__(cls, *args, **kwargs):
62 new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
64 if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
65 NodeMetaClass.types[new_cls.get_type()] = new_cls
70 def setup_relations(cls):
71 for node_cls in NodeMetaClass.types.values():
72 NodeMetaClass.setup_relation(node_cls)
75 def setup_relation(cls, node_cls):
76 name = node_cls.__name__.lower()
79 return node_cls.objects.filter(parent=self)
82 if (self.parent is not None) and self.parent.node_type == name:
83 return self.parent.leaf
87 Node.add_to_class(name + 's', property(children))
88 Node.add_to_class(name, property(parent))
91 class NodeQuerySet(CachedQuerySet):
92 def obj_from_datadict(self, datadict):
93 cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
96 obj.__dict__.update(datadict)
99 return super(NodeQuerySet, self).obj_from_datadict(datadict)
101 def get(self, *args, **kwargs):
102 node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
104 if not isinstance(node, self.model):
105 raise self.model.DoesNotExist()
109 def any_state(self, *args):
113 s_filter = models.Q(state_string__contains="(%s)" % s)
114 filter = filter and (filter | s_filter) or s_filter
117 return self.filter(filter)
121 def all_states(self, *args):
125 s_filter = models.Q(state_string__contains="(%s)" % s)
126 filter = filter and (filter & s_filter) or s_filter
129 return self.filter(filter)
133 def filter_state(self, **kwargs):
134 apply_bool = lambda q, b: b and q or ~q
135 return self.filter(*[apply_bool(models.Q(state_string__contains="(%s)" % s), b) for s, b in kwargs.items()])
137 def children_count(self, child_type):
138 return NodeMetaClass.types[child_type].objects.filter_state(deleted=False).filter(parent__in=self).count()
141 class NodeManager(CachedManager):
142 use_for_related_fields = True
144 def get_query_set(self):
145 qs = NodeQuerySet(self.model)
147 if self.model is not Node:
148 return qs.filter(node_type=self.model.get_type())
152 def get_for_types(self, types, *args, **kwargs):
153 kwargs['node_type__in'] = [t.get_type() for t in types]
154 return self.get(*args, **kwargs)
156 def filter_state(self, **kwargs):
157 return self.all().filter_state(**kwargs)
160 class NodeStateDict(object):
161 def __init__(self, node):
162 self.__dict__['_node'] = node
164 def __getattr__(self, name):
165 if self.__dict__.get(name, None):
166 return self.__dict__[name]
169 node = self.__dict__['_node']
170 action = NodeState.objects.get(node=node, state_type=name).action
171 self.__dict__[name] = action
176 def __setattr__(self, name, value):
177 current = self.__getattr__(name)
181 current.action = value
184 node = self.__dict__['_node']
185 state = NodeState(node=node, action=value, state_type=name)
187 self.__dict__[name] = value
189 if not "(%s)" % name in node.state_string:
190 node.state_string = "%s(%s)" % (node.state_string, name)
194 node = self.__dict__['_node']
195 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
197 current.node_state.delete()
198 del self.__dict__[name]
201 class NodeStateQuery(object):
202 def __init__(self, node):
203 self.__dict__['_node'] = node
205 def __getattr__(self, name):
206 node = self.__dict__['_node']
207 return "(%s)" % name in node.state_string
210 class Node(BaseModel, NodeContent):
211 __metaclass__ = NodeMetaClass
213 node_type = models.CharField(max_length=16, default='node')
214 parent = models.ForeignKey('Node', related_name='children', null=True)
215 abs_parent = models.ForeignKey('Node', related_name='all_children', null=True)
217 added_at = models.DateTimeField(default=datetime.datetime.now)
218 score = models.IntegerField(default=0)
220 state_string = models.TextField(default='')
221 last_edited = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
223 last_activity_by = models.ForeignKey(User, null=True)
224 last_activity_at = models.DateTimeField(null=True, blank=True)
226 tags = models.ManyToManyField('Tag', related_name='%(class)ss')
227 active_revision = models.OneToOneField('NodeRevision', related_name='active', null=True)
229 extra = PickledObjectField()
230 extra_ref = models.ForeignKey('Node', null=True)
231 extra_count = models.IntegerField(default=0)
233 marked = models.BooleanField(default=False)
235 comment_count = DenormalizedField("children", node_type="comment", canceled=False)
236 flag_count = DenormalizedField("flags")
238 friendly_name = _("post")
240 objects = NodeManager()
242 def __unicode__(self):
246 def _generate_cache_key(cls, key, group="node"):
247 return super(Node, cls)._generate_cache_key(key, group)
251 return cls.__name__.lower()
255 leaf_cls = NodeMetaClass.types.get(self.node_type, None)
261 leaf.__dict__ = self.__dict__
266 state = self.__dict__.get('_nstate', None)
269 state = NodeStateDict(self)
276 nis = self.__dict__.get('_nis', None)
279 nis = NodeStateQuery(self)
285 def last_activity(self):
287 return self.actions.order_by('-action_date')[0].action_date
289 return self.last_seen
292 def state_list(self):
293 return [s.state_type for s in self.states.all()]
297 return self.nis.deleted
300 def absolute_parent(self):
301 if not self.abs_parent_id:
304 return self.abs_parent
308 return strip_tags(self.html)[:300]
311 def get_revisions_url(self):
312 return ('revisions', (), {'id': self.id})
314 def update_last_activity(self, user, save=False, time=None):
316 time = datetime.datetime.now()
318 self.last_activity_by = user
319 self.last_activity_at = time
322 self.parent.update_last_activity(user, save=True, time=time)
327 def _create_revision(self, user, number, **kwargs):
328 revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
332 def create_revision(self, user, **kwargs):
333 number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
334 revision = self._create_revision(user, number, **kwargs)
335 self.activate_revision(user, revision, extensions=['urlize'])
338 def activate_revision(self, user, revision, extensions=['urlize']):
339 self.title = revision.title
340 self.tagnames = revision.tagnames
341 self.body = auto_user_link(self, self._as_markdown(revision.body, *extensions))
343 self.active_revision = revision
344 self.update_last_activity(user)
348 def _list_changes_in_tags(self):
349 dirty = self.get_dirty_fields()
351 if not 'tagnames' in dirty:
354 if self._original_state['tagnames']:
355 old_tags = set(name for name in self._original_state['tagnames'].split(u' '))
358 new_tags = set(name for name in self.tagnames.split(u' ') if name)
361 current=list(new_tags),
362 added=list(new_tags - old_tags),
363 removed=list(old_tags - new_tags)
366 def _last_active_user(self):
367 return self.last_edited and self.last_edited.by or self.author
369 def _process_changes_in_tags(self):
370 tag_changes = self._list_changes_in_tags()
372 if tag_changes is not None:
373 for name in tag_changes['added']:
375 tag = Tag.objects.get(name=name)
377 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
379 if not self.nis.deleted:
380 tag.add_to_usage_count(1)
383 if not self.nis.deleted:
384 for name in tag_changes['removed']:
386 tag = Tag.objects.get(name=name)
387 tag.add_to_usage_count(-1)
396 def mark_deleted(self, action):
397 self.nstate.deleted = action
401 for tag in self.tags.all():
402 tag.add_to_usage_count(-1)
405 for tag in Tag.objects.filter(name__in=self.tagname_list()):
406 tag.add_to_usage_count(1)
409 def delete(self, *args, **kwargs):
410 self.active_revision = None
413 for n in self.children.all():
416 for a in self.actions.all():
419 super(Node, self).delete(*args, **kwargs)
421 def save(self, *args, **kwargs):
423 self.node_type = self.get_type()
424 super(BaseModel, self).save(*args, **kwargs)
425 self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
427 self.activate_revision(self.author, self.active_revision)
428 self.update_last_activity(self.author, time=self.added_at)
430 if self.parent_id and not self.abs_parent_id:
431 self.abs_parent = self.parent.absolute_parent
433 tags_changed = self._process_changes_in_tags()
435 super(Node, self).save(*args, **kwargs)
437 if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
443 class NodeRevision(BaseModel, NodeContent):
444 node = models.ForeignKey(Node, related_name='revisions')
445 summary = models.CharField(max_length=300)
446 revision = models.PositiveIntegerField()
447 revised_at = models.DateTimeField(default=datetime.datetime.now)
450 unique_together = ('node', 'revision')
454 class NodeState(models.Model):
455 node = models.ForeignKey(Node, related_name='states')
456 state_type = models.CharField(max_length=16)
457 action = models.OneToOneField('Action', related_name="node_state")
460 unique_together = ('node', 'state_type')