]> git.openstreetmap.org Git - osqa.git/blob - forum/models/user.py
Fixes some weird threading problems with modules.
[osqa.git] / forum / models / user.py
1 from base import *
2 from utils import PickledObjectField
3 from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
4 from django.contrib.contenttypes.models import ContentType
5 from django.contrib.auth.models import User as DjangoUser, AnonymousUser as DjangoAnonymousUser
6 from django.db.models import Q
7 try:
8     from hashlib import md5
9 except:
10     from md5 import new as md5
11
12 import string
13 from random import Random
14
15 from django.utils.translation import ugettext as _
16 import logging
17
18 class AnonymousUser(DjangoAnonymousUser):
19     reputation = 0
20     
21     def get_visible_answers(self, question):
22         return question.answers.filter_state(deleted=False)
23
24     def can_view_deleted_post(self, post):
25         return False
26
27     def can_vote_up(self):
28         return False
29
30     def can_vote_down(self):
31         return False
32     
33     def can_vote_count_today(self):
34         return 0
35
36     def can_flag_offensive(self, post=None):
37         return False
38
39     def can_view_offensive_flags(self, post=None):
40         return False
41
42     def can_comment(self, post):
43         return False
44
45     def can_like_comment(self, comment):
46         return False
47
48     def can_edit_comment(self, comment):
49         return False
50
51     def can_delete_comment(self, comment):
52         return False
53
54     def can_convert_to_comment(self, answer):
55         return False
56     
57     def can_convert_to_question(self, answer):
58         return False
59     
60     def can_convert_comment_to_answer(self, comment):
61         return False
62
63     def can_accept_answer(self, answer):
64         return False
65
66     def can_create_tags(self):
67         return False
68
69     def can_edit_post(self, post):
70         return False
71
72     def can_wikify(self, post):
73         return False
74
75     def can_cancel_wiki(self, post):
76         return False
77
78     def can_retag_questions(self):
79         return False
80
81     def can_close_question(self, question):
82         return False
83
84     def can_reopen_question(self, question):
85         return False
86
87     def can_delete_post(self, post):
88         return False
89
90     def can_upload_files(self):
91         return False
92
93     def is_a_super_user_or_staff(self):
94         return False
95
96 def true_if_is_super_or_staff(fn):
97     def decorated(self, *args, **kwargs):
98         return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
99
100     return decorated
101
102 def false_if_validation_required_to(item):
103     def decorator(fn):
104         def decorated(self, *args, **kwargs):
105             if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
106                 return False
107             else:
108                 return fn(self, *args, **kwargs)
109         return decorated
110     return decorator
111
112 class User(BaseModel, DjangoUser):
113     is_approved = models.BooleanField(default=False)
114     email_isvalid = models.BooleanField(default=False)
115
116     reputation = models.PositiveIntegerField(default=0)
117     gold = models.PositiveIntegerField(default=0)
118     silver = models.PositiveIntegerField(default=0)
119     bronze = models.PositiveIntegerField(default=0)
120
121     last_seen = models.DateTimeField(default=datetime.datetime.now)
122     real_name = models.CharField(max_length=100, blank=True)
123     website = models.URLField(max_length=200, blank=True)
124     location = models.CharField(max_length=100, blank=True)
125     date_of_birth = models.DateField(null=True, blank=True)
126     about = models.TextField(blank=True)
127
128     subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
129
130     vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
131     vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
132
133     def __unicode__(self):
134         return self.username
135
136     @property
137     def prop(self):
138         prop = self.__dict__.get('_prop', None)
139
140         if prop is None:
141             prop = UserPropertyDict(self)
142             self._prop = prop
143
144         return prop
145
146     @property
147     def is_siteowner(self):
148         #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
149         return self.id == 1
150
151     @property
152     def decorated_name(self):
153         if settings.SHOW_STATUS_DIAMONDS:
154             if self.is_superuser:
155                 return u"%s \u2666\u2666" % self.username
156
157             if self.is_staff:
158                 return u"%s \u2666" % self.username
159
160         return self.username
161
162     @property
163     def last_activity(self):
164         try:
165             return self.actions.order_by('-action_date')[0].action_date
166         except:
167             return self.last_seen
168
169     @property
170     def gravatar(self):
171         return md5(self.email.lower()).hexdigest()
172     
173     def save(self, *args, **kwargs):
174         if self.reputation < 0:
175             self.reputation = 0
176
177         new = not bool(self.id)
178
179         super(User, self).save(*args, **kwargs)
180
181         if new:
182             sub_settings = SubscriptionSettings(user=self)
183             sub_settings.save()
184
185     def get_messages(self):
186         messages = []
187         for m in self.message_set.all():
188             messages.append(m.message)
189         return messages
190
191     def delete_messages(self):
192         self.message_set.all().delete()
193
194     @models.permalink
195     def get_profile_url(self):
196         return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
197
198     def get_absolute_url(self):
199         return self.get_profile_url()
200
201     @models.permalink
202     def get_asked_url(self):
203         return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(self.username)})
204
205     @models.permalink
206     def get_answered_url(self):
207         return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
208
209     @models.permalink
210     def get_subscribed_url(self):
211         return ('user_questions', (), {'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(self.username)})
212
213     def get_profile_link(self):
214         profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
215         return mark_safe(profile_link)
216
217     def get_visible_answers(self, question):
218         return question.answers.filter_state(deleted=False)
219
220     def get_vote_count_today(self):
221         today = datetime.date.today()
222         return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
223                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
224
225     def get_reputation_by_upvoted_today(self):
226         today = datetime.datetime.now()
227         sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
228                 models.Sum('value'))
229         #todo: redo this, maybe transform in the daily cap
230         #if sum.get('value__sum', None) is not None: return sum['value__sum']
231         return 0
232
233     def get_flagged_items_count_today(self):
234         today = datetime.date.today()
235         return self.actions.filter(canceled=False, action_type="flag",
236                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
237     
238     def can_vote_count_today(self):
239         votes_today = settings.MAX_VOTES_PER_DAY
240         
241         if settings.USER_REPUTATION_TO_MAX_VOTES:
242             votes_today = votes_today + int(self.reputation)
243         
244         return votes_today
245     
246     @true_if_is_super_or_staff
247     def can_view_deleted_post(self, post):
248         return post.author == self
249
250     @true_if_is_super_or_staff
251     def can_vote_up(self):
252         return self.reputation >= int(settings.REP_TO_VOTE_UP)
253
254     @true_if_is_super_or_staff
255     def can_vote_down(self):
256         return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
257
258     @false_if_validation_required_to('flag')
259     def can_flag_offensive(self, post=None):
260         if post is not None and post.author == self:
261             return False
262         return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
263
264     @true_if_is_super_or_staff
265     def can_view_offensive_flags(self, post=None):
266         if post is not None and post.author == self:
267             return True
268         return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
269
270     @true_if_is_super_or_staff
271     @false_if_validation_required_to('comment')
272     def can_comment(self, post):
273         return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
274                 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
275
276     @true_if_is_super_or_staff
277     def can_like_comment(self, comment):
278         return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
279
280     @true_if_is_super_or_staff
281     def can_edit_comment(self, comment):
282         return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
283         ) or self.is_superuser
284
285     @true_if_is_super_or_staff
286     def can_delete_comment(self, comment):
287         return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
288
289     @true_if_is_super_or_staff
290     def can_convert_comment_to_answer(self, comment):
291         return self == comment.author or self.reputation >= int(settings.REP_TO_CONVERT_COMMENTS_TO_ANSWERS)
292
293     def can_convert_to_comment(self, answer):
294         return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
295                 (settings.REP_TO_CONVERT_TO_COMMENT))
296     
297     def can_convert_to_question(self, answer):
298         return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
299                 (settings.REP_TO_CONVERT_TO_QUESTION))
300
301     @true_if_is_super_or_staff
302     def can_accept_answer(self, answer):
303         return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
304
305     @true_if_is_super_or_staff
306     def can_create_tags(self):
307         return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
308
309     @true_if_is_super_or_staff
310     def can_edit_post(self, post):
311         return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
312                                                              ) or (post.nis.wiki and self.reputation >= int(
313                 settings.REP_TO_EDIT_WIKI))
314
315     @true_if_is_super_or_staff
316     def can_wikify(self, post):
317         return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
318
319     @true_if_is_super_or_staff
320     def can_cancel_wiki(self, post):
321         return self == post.author
322
323     @true_if_is_super_or_staff
324     def can_retag_questions(self):
325         return self.reputation >= int(settings.REP_TO_RETAG)
326
327     @true_if_is_super_or_staff
328     def can_close_question(self, question):
329         return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
330         ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
331
332     @true_if_is_super_or_staff
333     def can_reopen_question(self, question):
334         return self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
335
336     @true_if_is_super_or_staff
337     def can_delete_post(self, post):
338         if post.node_type == "comment":
339             return self.can_delete_comment(post)
340
341         return (self == post.author and (post.__class__.__name__ == "Answer" or
342         not post.answers.exclude(author__id=self.id).count()))
343
344     @true_if_is_super_or_staff
345     def can_upload_files(self):
346         return self.reputation >= int(settings.REP_TO_UPLOAD)
347
348     @true_if_is_super_or_staff
349     def is_a_super_user_or_staff(self):
350         return False
351
352     def email_valid_and_can_ask(self):
353         return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
354
355     def email_valid_and_can_answer(self):
356         return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
357
358     def check_password(self, old_passwd):
359         self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
360         return DjangoUser.check_password(self, old_passwd)
361
362     @property
363     def suspension(self):
364         if self.__dict__.get('_suspension_dencache_', False) != None:
365             try:
366                 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
367             except ObjectDoesNotExist:
368                 self.__dict__['_suspension_dencache_'] = None
369             except MultipleObjectsReturned:
370                 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
371                 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
372                                                                              ).order_by('-action__action_date')[0]
373
374         return self.__dict__['_suspension_dencache_']
375
376     def _pop_suspension_cache(self):
377         self.__dict__.pop('_suspension_dencache_', None)
378
379     def is_suspended(self):
380         if not self.is_active:
381             suspension = self.suspension
382
383             if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
384             datetime.datetime.now() > suspension.action_date + datetime.timedelta(
385                     days=int(suspension.extra.get('forxdays', 365)))):
386                 suspension.cancel()
387             else:
388                 return True
389
390         return False
391
392     class Meta:
393         app_label = 'forum'
394
395 class UserProperty(BaseModel):
396     user = models.ForeignKey(User, related_name='properties')
397     key = models.CharField(max_length=16)
398     value = PickledObjectField()
399
400     class Meta:
401         app_label = 'forum'
402         unique_together = ('user', 'key')
403
404     def cache_key(self):
405         return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
406
407     @classmethod
408     def infer_cache_key(cls, querydict):
409         if 'user' in querydict and 'key' in querydict:
410             return cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
411
412         return None
413
414 class UserPropertyDict(object):
415     def __init__(self, user):
416         self.__dict__['_user'] = user
417
418     def __get_property(self, name):
419         if self.__dict__.get('__%s__' % name, None):
420             return self.__dict__['__%s__' % name]
421         try:
422             user = self.__dict__['_user']
423             prop = UserProperty.objects.get(user=user, key=name)
424             self.__dict__['__%s__' % name] = prop
425             self.__dict__[name] = prop.value
426             return prop
427         except:
428             return None
429
430
431     def __getattr__(self, name):
432         if self.__dict__.get(name, None):
433             return self.__dict__[name]
434
435         prop = self.__get_property(name)
436
437         if prop:
438             return prop.value
439         else:
440             return None
441
442     def __setattr__(self, name, value):
443         current = self.__get_property(name)
444
445         if value is not None:
446             if current:
447                 current.value = value
448                 self.__dict__[name] = value
449                 current.save(full_save=True)
450             else:
451                 user = self.__dict__['_user']
452                 prop = UserProperty(user=user, value=value, key=name)
453                 prop.save()
454                 self.__dict__[name] = value
455                 self.__dict__['__%s__' % name] = prop
456         else:
457             if current:
458                 current.delete()
459                 del self.__dict__[name]
460                 del self.__dict__['__%s__' % name]
461
462
463 class SubscriptionSettings(models.Model):
464     user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
465
466     enable_notifications = models.BooleanField(default=True)
467
468     #notify if
469     member_joins = models.CharField(max_length=1, default='n')
470     new_question = models.CharField(max_length=1, default='n')
471     new_question_watched_tags = models.CharField(max_length=1, default='i')
472     subscribed_questions = models.CharField(max_length=1, default='i')
473
474     #auto_subscribe_to
475     all_questions = models.BooleanField(default=False)
476     all_questions_watched_tags = models.BooleanField(default=False)
477     questions_asked = models.BooleanField(default=True)
478     questions_answered = models.BooleanField(default=True)
479     questions_commented = models.BooleanField(default=False)
480     questions_viewed = models.BooleanField(default=False)
481
482     #notify activity on subscribed
483     notify_answers = models.BooleanField(default=True)
484     notify_reply_to_comments = models.BooleanField(default=True)
485     notify_comments_own_post = models.BooleanField(default=True)
486     notify_comments = models.BooleanField(default=False)
487     notify_accepted = models.BooleanField(default=False)
488
489     send_digest = models.BooleanField(default=True)
490
491     class Meta:
492         app_label = 'forum'
493
494 from forum.utils.time import one_day_from_now
495
496 class ValidationHashManager(models.Manager):
497     def _generate_md5_hash(self, user, type, hash_data, seed):
498         return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
499
500     def create_new(self, user, type, hash_data=[], expiration=None):
501         seed = ''.join(Random().sample(string.letters+string.digits, 12))
502         hash = self._generate_md5_hash(user, type, hash_data, seed)
503
504         obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
505
506         if expiration is not None:
507             obj.expiration = expiration
508
509         try:
510             obj.save()
511         except:
512             return None
513
514         return obj
515
516     def validate(self, hash, user, type, hash_data=[]):
517         try:
518             obj = self.get(hash_code=hash)
519         except:
520             return False
521
522         if obj.type != type:
523             return False
524
525         if obj.user != user:
526             return False
527
528         valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
529
530         if valid:
531             if obj.expiration < datetime.datetime.now():
532                 obj.delete()
533                 return False
534             else:
535                 obj.delete()
536                 return True
537
538         return False
539
540 class ValidationHash(models.Model):
541     hash_code = models.CharField(max_length=255, unique=True)
542     seed = models.CharField(max_length=12)
543     expiration = models.DateTimeField(default=one_day_from_now)
544     type = models.CharField(max_length=12)
545     user = models.ForeignKey(User)
546
547     objects = ValidationHashManager()
548
549     class Meta:
550         unique_together = ('user', 'type')
551         app_label = 'forum'
552
553     def __str__(self):
554         return self.hash_code
555
556 class AuthKeyUserAssociation(models.Model):
557     key = models.CharField(max_length=255, null=False, unique=True)
558     provider = models.CharField(max_length=64)
559     user = models.ForeignKey(User, related_name="auth_keys")
560     added_at = models.DateTimeField(default=datetime.datetime.now)
561
562     class Meta:
563         app_label = 'forum'