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