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