]> git.openstreetmap.org Git - osqa.git/blob - forum/models/node.py
fixes OSQA 555 and OSQA 294
[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         
341         from forum.utils.userlinking import auto_user_link
342         
343         self.body = auto_user_link(self, self._as_markdown(revision.body, *extensions))
344
345         self.active_revision = revision
346         self.update_last_activity(user)
347
348         self.save()
349
350     def _list_changes_in_tags(self):
351         dirty = self.get_dirty_fields()
352
353         if not 'tagnames' in dirty:
354             return None
355         else:
356             if self._original_state['tagnames']:
357                 old_tags = set(name for name in self._original_state['tagnames'].split(u' '))
358             else:
359                 old_tags = set()
360             new_tags = set(name for name in self.tagnames.split(u' ') if name)
361
362             return dict(
363                     current=list(new_tags),
364                     added=list(new_tags - old_tags),
365                     removed=list(old_tags - new_tags)
366                     )
367
368     def _last_active_user(self):
369         return self.last_edited and self.last_edited.by or self.author
370
371     def _process_changes_in_tags(self):
372         tag_changes = self._list_changes_in_tags()
373
374         if tag_changes is not None:
375             for name in tag_changes['added']:
376                 try:
377                     tag = Tag.objects.get(name=name)
378                 except:
379                     tag = Tag.objects.create(name=name, created_by=self._last_active_user())
380
381                 if not self.nis.deleted:
382                     tag.add_to_usage_count(1)
383                     tag.save()
384
385             if not self.nis.deleted:
386                 for name in tag_changes['removed']:
387                     try:
388                         tag = Tag.objects.get(name=name)
389                         tag.add_to_usage_count(-1)
390                         tag.save()
391                     except:
392                         pass
393
394             return True
395
396         return False
397
398     def mark_deleted(self, action):
399         self.nstate.deleted = action
400         self.save()
401
402         if action:
403             for tag in self.tags.all():
404                 tag.add_to_usage_count(-1)
405                 tag.save()
406         else:
407             for tag in Tag.objects.filter(name__in=self.tagname_list()):
408                 tag.add_to_usage_count(1)
409                 tag.save()
410
411     def delete(self, *args, **kwargs):
412         self.active_revision = None
413         self.save()
414
415         for n in self.children.all():
416             n.delete()
417
418         for a in self.actions.all():
419             a.cancel()
420
421         super(Node, self).delete(*args, **kwargs)
422
423     def save(self, *args, **kwargs):
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         tags_changed = self._process_changes_in_tags()
436         
437         super(Node, self).save(*args, **kwargs)
438         
439         if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
440
441     class Meta:
442         app_label = 'forum'
443
444
445 class NodeRevision(BaseModel, NodeContent):
446     node       = models.ForeignKey(Node, related_name='revisions')
447     summary    = models.CharField(max_length=300)
448     revision   = models.PositiveIntegerField()
449     revised_at = models.DateTimeField(default=datetime.datetime.now)
450
451     class Meta:
452         unique_together = ('node', 'revision')
453         app_label = 'forum'
454
455
456 class NodeState(models.Model):
457     node       = models.ForeignKey(Node, related_name='states')
458     state_type = models.CharField(max_length=16)
459     action     = models.OneToOneField('Action', related_name="node_state")
460
461     class Meta:
462         unique_together = ('node', 'state_type')
463         app_label = 'forum'
464
465