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