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.settings import SUMMARY_LENGTH
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)[:SUMMARY_LENGTH]
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
342 from forum.utils.userlinking import auto_user_link
344 self.body = auto_user_link(self, self._as_markdown(revision.body, *extensions))
346 self.active_revision = revision
347 self.update_last_activity(user)
351 def _list_changes_in_tags(self):
352 dirty = self.get_dirty_fields()
354 if not 'tagnames' in dirty:
357 if self._original_state['tagnames']:
358 old_tags = set(name for name in self._original_state['tagnames'].split(u' '))
361 new_tags = set(name for name in self.tagnames.split(u' ') if name)
364 current=list(new_tags),
365 added=list(new_tags - old_tags),
366 removed=list(old_tags - new_tags)
369 def _last_active_user(self):
370 return self.last_edited and self.last_edited.by or self.author
372 def _process_changes_in_tags(self):
373 tag_changes = self._list_changes_in_tags()
375 if tag_changes is not None:
376 for name in tag_changes['added']:
378 tag = Tag.objects.get(name=name)
380 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
382 if not self.nis.deleted:
383 tag.add_to_usage_count(1)
386 if not self.nis.deleted:
387 for name in tag_changes['removed']:
389 tag = Tag.objects.get(name=name)
390 tag.add_to_usage_count(-1)
399 def mark_deleted(self, action):
400 self.nstate.deleted = action
404 for tag in self.tags.all():
405 tag.add_to_usage_count(-1)
408 for tag in Tag.objects.filter(name__in=self.tagname_list()):
409 tag.add_to_usage_count(1)
412 def delete(self, *args, **kwargs):
413 self.active_revision = None
416 for n in self.children.all():
419 for a in self.actions.all():
422 super(Node, self).delete(*args, **kwargs)
424 def save(self, *args, **kwargs):
426 self.node_type = self.get_type()
427 super(BaseModel, self).save(*args, **kwargs)
428 self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
430 self.activate_revision(self.author, self.active_revision)
431 self.update_last_activity(self.author, time=self.added_at)
433 if self.parent_id and not self.abs_parent_id:
434 self.abs_parent = self.parent.absolute_parent
436 tags_changed = self._process_changes_in_tags()
438 super(Node, self).save(*args, **kwargs)
440 if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
446 class NodeRevision(BaseModel, NodeContent):
447 node = models.ForeignKey(Node, related_name='revisions')
448 summary = models.CharField(max_length=300)
449 revision = models.PositiveIntegerField()
450 revised_at = models.DateTimeField(default=datetime.datetime.now)
453 unique_together = ('node', 'revision')
457 class NodeState(models.Model):
458 node = models.ForeignKey(Node, related_name='states')
459 state_type = models.CharField(max_length=16)
460 action = models.OneToOneField('Action', related_name="node_state")
463 unique_together = ('node', 'state_type')