]> git.openstreetmap.org Git - osqa.git/blob - forum/models/node.py
0dfe1d2cea73ebe7e90ed70bb325c263900250a9
[osqa.git] / forum / models / node.py
1 from base import *
2 import re
3 from tag import Tag
4
5 import markdown
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
12
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()
18
19     @property
20     def user(self):
21         return self.author
22
23     @property
24     def html(self):
25         return self.body
26
27     @classmethod
28     def _as_markdown(cls, content, *extensions):
29         try:
30             return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
31         except Exception, e:
32             import traceback
33             logging.error("Caught exception %s in markdown parser rendering %s %s:\s %s" % (
34                 str(e), cls.__name__, str(e), traceback.format_exc()))
35             return ''
36
37     def as_markdown(self, *extensions):
38         return self._as_markdown(self.body, *extensions)
39
40     @property
41     def headline(self):
42         return self.title
43
44     def tagname_list(self):
45         if self.tagnames:
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]
48         else:
49             return []
50
51     def tagname_meta_generator(self):
52         return u','.join([tag for tag in self.tagname_list()])
53
54     class Meta:
55         abstract = True
56         app_label = 'forum'
57
58 class NodeMetaClass(BaseMetaClass):
59     types = {}
60
61     def __new__(cls, *args, **kwargs):
62         new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
63
64         if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
65             NodeMetaClass.types[new_cls.get_type()] = new_cls
66
67         return new_cls
68
69     @classmethod
70     def setup_relations(cls):
71         for node_cls in NodeMetaClass.types.values():
72             NodeMetaClass.setup_relation(node_cls)
73
74     @classmethod
75     def setup_relation(cls, node_cls):
76         name = node_cls.__name__.lower()
77
78         def children(self):
79             return node_cls.objects.filter(parent=self)
80
81         def parent(self):
82             if (self.parent is not None) and self.parent.node_type == name:
83                 return self.parent.leaf
84
85             return None
86
87         Node.add_to_class(name + 's', property(children))
88         Node.add_to_class(name, property(parent))
89
90
91 class NodeQuerySet(CachedQuerySet):
92     def obj_from_datadict(self, datadict):
93         cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
94         if cls:
95             obj = cls()
96             obj.__dict__.update(datadict)
97             return obj
98         else:
99             return super(NodeQuerySet, self).obj_from_datadict(datadict)
100
101     def get(self, *args, **kwargs):
102         node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
103
104         if not isinstance(node, self.model):
105             raise self.model.DoesNotExist()
106
107         return node
108
109     def any_state(self, *args):
110         filter = None
111
112         for s in args:
113             s_filter = models.Q(state_string__contains="(%s)" % s)
114             filter = filter and (filter | s_filter) or s_filter
115
116         if filter:
117             return self.filter(filter)
118         else:
119             return self
120
121     def all_states(self, *args):
122         filter = None
123
124         for s in args:
125             s_filter = models.Q(state_string__contains="(%s)" % s)
126             filter = filter and (filter & s_filter) or s_filter
127
128         if filter:
129             return self.filter(filter)
130         else:
131             return self
132
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()])
136
137     def children_count(self, child_type):
138         return NodeMetaClass.types[child_type].objects.filter_state(deleted=False).filter(parent__in=self).count()
139
140
141 class NodeManager(CachedManager):
142     use_for_related_fields = True
143
144     def get_query_set(self):
145         qs = NodeQuerySet(self.model)
146
147         if self.model is not Node:
148             return qs.filter(node_type=self.model.get_type())
149         else:
150             return qs
151
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)
155
156     def filter_state(self, **kwargs):
157         return self.all().filter_state(**kwargs)
158
159
160 class NodeStateDict(object):
161     def __init__(self, node):
162         self.__dict__['_node'] = node
163
164     def __getattr__(self, name):
165         if self.__dict__.get(name, None):
166             return self.__dict__[name]
167
168         try:
169             node = self.__dict__['_node']
170             action = NodeState.objects.get(node=node, state_type=name).action
171             self.__dict__[name] = action
172             return action
173         except:
174             return None
175
176     def __setattr__(self, name, value):
177         current = self.__getattr__(name)
178
179         if value:
180             if current:
181                 current.action = value
182                 current.save()
183             else:
184                 node = self.__dict__['_node']
185                 state = NodeState(node=node, action=value, state_type=name)
186                 state.save()
187                 self.__dict__[name] = value
188
189                 if not "(%s)" % name in node.state_string:
190                     node.state_string = "%s(%s)" % (node.state_string, name)
191                     node.save()
192         else:
193             if current:
194                 node = self.__dict__['_node']
195                 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
196                 node.save()
197                 current.node_state.delete()
198                 del self.__dict__[name]
199
200
201 class NodeStateQuery(object):
202     def __init__(self, node):
203         self.__dict__['_node'] = node
204
205     def __getattr__(self, name):
206         node = self.__dict__['_node']
207         return "(%s)" % name in node.state_string
208
209
210 class Node(BaseModel, NodeContent):
211     __metaclass__ = NodeMetaClass
212
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)
216
217     added_at             = models.DateTimeField(default=datetime.datetime.now)
218     score                 = models.IntegerField(default=0)
219
220     state_string          = models.TextField(default='')
221     last_edited           = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
222
223     last_activity_by       = models.ForeignKey(User, null=True)
224     last_activity_at       = models.DateTimeField(null=True, blank=True)
225
226     tags                 = models.ManyToManyField('Tag', related_name='%(class)ss')
227     active_revision       = models.OneToOneField('NodeRevision', related_name='active', null=True)
228
229     extra = PickledObjectField()
230     extra_ref = models.ForeignKey('Node', null=True)
231     extra_count = models.IntegerField(default=0)
232
233     marked = models.BooleanField(default=False)
234
235     comment_count = DenormalizedField("children", node_type="comment", canceled=False)
236     flag_count = DenormalizedField("flags")
237
238     friendly_name = _("post")
239
240     objects = NodeManager()
241
242     def __unicode__(self):
243         return self.headline
244
245     @classmethod
246     def _generate_cache_key(cls, key, group="node"):
247         return super(Node, cls)._generate_cache_key(key, group)
248         
249     @classmethod
250     def get_type(cls):
251         return cls.__name__.lower()
252
253     @property
254     def leaf(self):
255         leaf_cls = NodeMetaClass.types.get(self.node_type, None)
256
257         if leaf_cls is None:
258             return self
259
260         leaf = leaf_cls()
261         leaf.__dict__ = self.__dict__
262         return leaf
263
264     @property
265     def nstate(self):
266         state = self.__dict__.get('_nstate', None)
267
268         if state is None:
269             state = NodeStateDict(self)
270             self._nstate = state
271
272         return state
273
274     @property
275     def nis(self):
276         nis = self.__dict__.get('_nis', None)
277
278         if nis is None:
279             nis = NodeStateQuery(self)
280             self._nis = nis
281
282         return nis
283
284     @property
285     def last_activity(self):
286         try:
287             return self.actions.order_by('-action_date')[0].action_date
288         except:
289             return self.last_seen
290
291     @property
292     def state_list(self):
293         return [s.state_type for s in self.states.all()]
294
295     @property
296     def deleted(self):
297         return self.nis.deleted
298
299     @property
300     def absolute_parent(self):
301         if not self.abs_parent_id:
302             return self
303
304         return self.abs_parent
305
306     @property
307     def summary(self):
308         return strip_tags(self.html)[:300]
309
310     @models.permalink
311     def get_revisions_url(self):
312         return ('revisions', (), {'id': self.id})
313
314     def update_last_activity(self, user, save=False, time=None):
315         if not time:
316             time = datetime.datetime.now()
317
318         self.last_activity_by = user
319         self.last_activity_at = time
320
321         if self.parent:
322             self.parent.update_last_activity(user, save=True, time=time)
323
324         if save:
325             self.save()
326
327     def _create_revision(self, user, number, **kwargs):
328         revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
329         revision.save()
330         return revision
331
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'])
336         return revision
337
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))
342
343         self.active_revision = revision
344         self.update_last_activity(user)
345
346         self.save()
347
348     def _list_changes_in_tags(self):
349         dirty = self.get_dirty_fields()
350
351         if not 'tagnames' in dirty:
352             return None
353         else:
354             if self._original_state['tagnames']:
355                 old_tags = set(name for name in self._original_state['tagnames'].split(u' '))
356             else:
357                 old_tags = set()
358             new_tags = set(name for name in self.tagnames.split(u' ') if name)
359
360             return dict(
361                     current=list(new_tags),
362                     added=list(new_tags - old_tags),
363                     removed=list(old_tags - new_tags)
364                     )
365
366     def _last_active_user(self):
367         return self.last_edited and self.last_edited.by or self.author
368
369     def _process_changes_in_tags(self):
370         tag_changes = self._list_changes_in_tags()
371
372         if tag_changes is not None:
373             for name in tag_changes['added']:
374                 try:
375                     tag = Tag.objects.get(name=name)
376                 except:
377                     tag = Tag.objects.create(name=name, created_by=self._last_active_user())
378
379                 if not self.nis.deleted:
380                     tag.add_to_usage_count(1)
381                     tag.save()
382
383             if not self.nis.deleted:
384                 for name in tag_changes['removed']:
385                     try:
386                         tag = Tag.objects.get(name=name)
387                         tag.add_to_usage_count(-1)
388                         tag.save()
389                     except:
390                         pass
391
392             return True
393
394         return False
395
396     def mark_deleted(self, action):
397         self.nstate.deleted = action
398         self.save()
399
400         if action:
401             for tag in self.tags.all():
402                 tag.add_to_usage_count(-1)
403                 tag.save()
404         else:
405             for tag in Tag.objects.filter(name__in=self.tagname_list()):
406                 tag.add_to_usage_count(1)
407                 tag.save()
408
409     def delete(self, *args, **kwargs):
410         self.active_revision = None
411         self.save()
412
413         for n in self.children.all():
414             n.delete()
415
416         for a in self.actions.all():
417             a.cancel()
418
419         super(Node, self).delete(*args, **kwargs)
420
421     def save(self, *args, **kwargs):
422         tags_changed = self._process_changes_in_tags()
423
424         if not self.id:
425             self.node_type = self.get_type()
426             super(BaseModel, self).save(*args, **kwargs)
427             self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
428                                                          body=self.body)
429             self.activate_revision(self.author, self.active_revision)
430             self.update_last_activity(self.author, time=self.added_at)
431
432         if self.parent_id and not self.abs_parent_id:
433             self.abs_parent = self.parent.absolute_parent
434
435         super(Node, self).save(*args, **kwargs)
436         if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
437
438     class Meta:
439         app_label = 'forum'
440
441
442 class NodeRevision(BaseModel, NodeContent):
443     node       = models.ForeignKey(Node, related_name='revisions')
444     summary    = models.CharField(max_length=300)
445     revision   = models.PositiveIntegerField()
446     revised_at = models.DateTimeField(default=datetime.datetime.now)
447
448     class Meta:
449         unique_together = ('node', 'revision')
450         app_label = 'forum'
451
452
453 class NodeState(models.Model):
454     node       = models.ForeignKey(Node, related_name='states')
455     state_type = models.CharField(max_length=16)
456     action     = models.OneToOneField('Action', related_name="node_state")
457
458     class Meta:
459         unique_together = ('node', 'state_type')
460         app_label = 'forum'
461
462