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