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