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