]> git.openstreetmap.org Git - osqa.git/blob - forum/models/user.py
Merge pull request #1 from udacity/add_requirements_file
[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     def get_messages(self):
213         messages = []
214         for m in self.message_set.all():
215             messages.append(m.message)
216         return messages
217
218     def delete_messages(self):
219         self.message_set.all().delete()
220
221     @models.permalink
222     def get_profile_url(self):
223         keyword_arguments = {
224             'slug': slugify(smart_unicode(self.username))
225         }
226         if settings.INCLUDE_ID_IN_USER_URLS:
227             keyword_arguments.update({
228                 'id': self.id,
229             })
230         return ('user_profile', (), keyword_arguments)
231
232     def get_absolute_url(self):
233         return self.get_profile_url()
234
235     @models.permalink
236     def get_asked_url(self):
237         return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
238
239     @models.permalink
240     def get_user_subscriptions_url(self):
241         keyword_arguments = {
242             'slug': slugify(smart_unicode(self.username))
243         }
244         if settings.INCLUDE_ID_IN_USER_URLS:
245             keyword_arguments.update({
246                 'id': self.id,
247             })
248         return ('user_subscriptions', (), keyword_arguments)
249
250     @models.permalink
251     def get_answered_url(self):
252         return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
253
254     def get_subscribed_url(self):
255         try:
256             # Try to retrieve the Subscribed User URL.
257             url = reverse('user_questions',
258                            kwargs={'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
259             return url
260         except Exception, e:
261             # If some Exception has been raised, don't forget to log it.
262             logging.error("Error retrieving a subscribed user URL: %s" % e)
263
264     def get_profile_link(self):
265         profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
266         return mark_safe(profile_link)
267
268     def get_visible_answers(self, question):
269         return question.answers.filter_state(deleted=False)
270
271     def get_vote_count_today(self):
272         today = datetime.date.today()
273         return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
274                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
275
276     def get_reputation_by_upvoted_today(self):
277         today = datetime.datetime.now()
278         sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
279                 models.Sum('value'))
280         #todo: redo this, maybe transform in the daily cap
281         #if sum.get('value__sum', None) is not None: return sum['value__sum']
282         return 0
283
284     def get_flagged_items_count_today(self):
285         today = datetime.date.today()
286         return self.actions.filter(canceled=False, action_type="flag",
287                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
288     
289     def can_vote_count_today(self):
290         votes_today = settings.MAX_VOTES_PER_DAY
291         
292         if settings.USER_REPUTATION_TO_MAX_VOTES:
293             votes_today = votes_today + int(self.reputation)
294         
295         return votes_today
296     
297     def can_use_canned_comments(self):
298         # The canned comments feature is available only for admins and moderators,
299         # and only if the "Use canned comments" setting is activated in the administration.
300         if (self.is_superuser or self.is_staff) and settings.USE_CANNED_COMMENTS:
301             return True
302         else:
303             return False
304
305     @true_if_is_super_or_staff
306     def can_view_deleted_post(self, post):
307         return post.author == self
308
309     @true_if_is_super_or_staff
310     def can_vote_up(self):
311         return self.reputation >= int(settings.REP_TO_VOTE_UP)
312
313     @true_if_is_super_or_staff
314     def can_vote_down(self):
315         return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
316
317     @false_if_validation_required_to('flag')
318     def can_flag_offensive(self, post=None):
319         if post is not None and post.author == self:
320             return False
321         return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
322
323     @true_if_is_super_or_staff
324     def can_view_offensive_flags(self, post=None):
325         if post is not None and post.author == self:
326             return True
327         return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
328
329     @true_if_is_super_or_staff
330     @false_if_validation_required_to('comment')
331     def can_comment(self, post):
332         return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
333                 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
334
335     @true_if_is_super_or_staff
336     def can_like_comment(self, comment):
337         return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
338
339     @true_if_is_super_or_staff
340     def can_edit_comment(self, comment):
341         return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
342         ) or self.is_superuser
343
344     @true_if_is_super_or_staff
345     def can_delete_comment(self, comment):
346         return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
347
348     def can_convert_comment_to_answer(self, comment):
349         # We need to know what is the comment parent node type.
350         comment_parent_type = comment.parent.node_type
351
352         # If the parent is not a question or an answer this comment cannot be converted to an answer.
353         if comment_parent_type != "question" and comment_parent_type != "answer":
354             return False
355
356         return (comment.parent.node_type in ('question', 'answer')) and (self.is_superuser or self.is_staff or (
357             self == comment.author) or (self.reputation >= int(settings.REP_TO_CONVERT_COMMENTS_TO_ANSWERS)))
358
359     def can_convert_to_comment(self, answer):
360         return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
361                 (settings.REP_TO_CONVERT_TO_COMMENT))
362     
363     def can_convert_to_question(self, node):
364         return (not node.marked) and (self.is_superuser or self.is_staff or node.author == self or self.reputation >= int
365                 (settings.REP_TO_CONVERT_TO_QUESTION))
366
367     @true_if_is_super_or_staff
368     def can_accept_answer(self, answer):
369         return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
370
371     @true_if_is_super_or_staff
372     def can_create_tags(self):
373         return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
374
375     @true_if_is_super_or_staff
376     def can_edit_post(self, post):
377         return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
378                                                              ) or (post.nis.wiki and self.reputation >= int(
379                 settings.REP_TO_EDIT_WIKI))
380
381     @true_if_is_super_or_staff
382     def can_wikify(self, post):
383         return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
384
385     @true_if_is_super_or_staff
386     def can_cancel_wiki(self, post):
387         return self == post.author
388
389     @true_if_is_super_or_staff
390     def can_retag_questions(self):
391         return self.reputation >= int(settings.REP_TO_RETAG)
392
393     @true_if_is_super_or_staff
394     def can_close_question(self, question):
395         return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
396         ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
397
398     @true_if_is_super_or_staff
399     def can_reopen_question(self, question):
400         # Check whether the setting to Unify close and reopen permissions has been activated
401         if bool(settings.UNIFY_PERMISSIONS_TO_CLOSE_AND_REOPEN):
402             # If we unify close to reopen check whether the user has permissions to close.
403             # If he has -- he can reopen his question too.
404             can_reopen = (
405                 self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
406             ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
407         else:
408             # Check whether the user is the author and has the required permissions to reopen
409             can_reopen = self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
410         return can_reopen
411
412     @true_if_is_super_or_staff
413     def can_delete_post(self, post):
414         if post.node_type == "comment":
415             return self.can_delete_comment(post)
416
417         return (self == post.author and (post.__class__.__name__ == "Answer" or
418         not post.answers.exclude(author__id=self.id).count()))
419
420     @true_if_is_super_or_staff
421     def can_upload_files(self):
422         return self.reputation >= int(settings.REP_TO_UPLOAD)
423
424     @true_if_is_super_or_staff
425     def is_a_super_user_or_staff(self):
426         return False
427
428     def email_valid_and_can_ask(self):
429         return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
430
431     def email_valid_and_can_answer(self):
432         return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
433
434     def check_password(self, old_passwd):
435         self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
436         return DjangoUser.check_password(self, old_passwd)
437
438     @property
439     def suspension(self):
440         if self.__dict__.get('_suspension_dencache_', False) != None:
441             try:
442                 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
443             except ObjectDoesNotExist:
444                 self.__dict__['_suspension_dencache_'] = None
445             except MultipleObjectsReturned:
446                 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
447                 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
448                                                                              ).order_by('-action__action_date')[0].action
449
450         return self.__dict__['_suspension_dencache_']
451
452     def _pop_suspension_cache(self):
453         self.__dict__.pop('_suspension_dencache_', None)
454
455     def is_suspended(self):
456         if not self.is_active:
457             suspension = self.suspension
458
459             if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
460             datetime.datetime.now() > suspension.action_date + datetime.timedelta(
461                     days=int(suspension.extra.get('forxdays', 365)))):
462                 suspension.cancel()
463             else:
464                 return True
465
466         return False
467
468     class Meta:
469         app_label = 'forum'
470
471 class UserProperty(BaseModel):
472     user = models.ForeignKey(User, related_name='properties')
473     key = models.CharField(max_length=16)
474     value = PickledObjectField()
475
476     class Meta:
477         app_label = 'forum'
478         unique_together = ('user', 'key')
479
480     def cache_key(self):
481         return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
482
483     @classmethod
484     def infer_cache_key(cls, querydict):
485         if 'user' in querydict and 'key' in querydict:
486             cache_key = cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
487             if len(cache_key) > django_settings.CACHE_MAX_KEY_LENGTH:
488                 cache_key = cache_key[:django_settings.CACHE_MAX_KEY_LENGTH]
489             return cache_key
490
491         return None
492
493 class UserPropertyDict(object):
494     def __init__(self, user):
495         self.__dict__['_user'] = user
496
497     def __get_property(self, name):
498         if self.__dict__.get('__%s__' % name, None):
499             return self.__dict__['__%s__' % name]
500         try:
501             user = self.__dict__['_user']
502             prop = UserProperty.objects.get(user=user, key=name)
503             self.__dict__['__%s__' % name] = prop
504             self.__dict__[name] = prop.value
505             return prop
506         except:
507             return None
508
509
510     def __getattr__(self, name):
511         if self.__dict__.get(name, None):
512             return self.__dict__[name]
513
514         prop = self.__get_property(name)
515
516         if prop:
517             return prop.value
518         else:
519             return None
520
521     def __setattr__(self, name, value):
522         current = self.__get_property(name)
523
524         if value is not None:
525             if current:
526                 current.value = value
527                 self.__dict__[name] = value
528                 current.save(full_save=True)
529             else:
530                 user = self.__dict__['_user']
531                 prop = UserProperty(user=user, value=value, key=name)
532                 prop.save()
533                 self.__dict__[name] = value
534                 self.__dict__['__%s__' % name] = prop
535         else:
536             if current:
537                 current.delete()
538                 del self.__dict__[name]
539                 del self.__dict__['__%s__' % name]
540
541
542 class SubscriptionSettings(models.Model):
543     user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
544
545     enable_notifications = models.BooleanField(default=True)
546
547     #notify if
548     member_joins = models.CharField(max_length=1, default='n')
549     new_question = models.CharField(max_length=1, default='n')
550     new_question_watched_tags = models.CharField(max_length=1, default='i')
551     subscribed_questions = models.CharField(max_length=1, default='i')
552
553     #auto_subscribe_to
554     all_questions = models.BooleanField(default=False)
555     all_questions_watched_tags = models.BooleanField(default=False)
556     questions_viewed = models.BooleanField(default=False)
557
558     #notify activity on subscribed
559     notify_answers = models.BooleanField(default=True)
560     notify_reply_to_comments = models.BooleanField(default=True)
561     notify_comments_own_post = models.BooleanField(default=True)
562     notify_comments = models.BooleanField(default=False)
563     notify_accepted = models.BooleanField(default=False)
564
565     send_digest = models.BooleanField(default=True)
566
567     class Meta:
568         app_label = 'forum'
569
570 from forum.utils.time import one_day_from_now
571
572 class ValidationHashManager(models.Manager):
573     def _generate_md5_hash(self, user, type, hash_data, seed):
574         return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
575
576     def create_new(self, user, type, hash_data=[], expiration=None):
577         seed = ''.join(Random().sample(string.letters+string.digits, 12))
578         hash = self._generate_md5_hash(user, type, hash_data, seed)
579
580         obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
581
582         if expiration is not None:
583             obj.expiration = expiration
584
585         try:
586             obj.save()
587         except:
588             return None
589
590         return obj
591
592     def validate(self, hash, user, type, hash_data=[]):
593         try:
594             obj = self.get(hash_code=hash)
595         except:
596             return False
597
598         if obj.type != type:
599             return False
600
601         if obj.user != user:
602             return False
603
604         valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
605
606         if valid:
607             if obj.expiration < datetime.datetime.now():
608                 obj.delete()
609                 return False
610             else:
611                 obj.delete()
612                 return True
613
614         return False
615
616 class ValidationHash(models.Model):
617     hash_code = models.CharField(max_length=255, unique=True)
618     seed = models.CharField(max_length=12)
619     expiration = models.DateTimeField(default=one_day_from_now)
620     type = models.CharField(max_length=12)
621     user = models.ForeignKey(User)
622
623     objects = ValidationHashManager()
624
625     class Meta:
626         unique_together = ('user', 'type')
627         app_label = 'forum'
628
629     def __str__(self):
630         return self.hash_code
631
632 class AuthKeyUserAssociation(models.Model):
633     key = models.CharField(max_length=255, null=False, unique=True)
634     provider = models.CharField(max_length=64)
635     user = models.ForeignKey(User, related_name="auth_keys")
636     added_at = models.DateTimeField(default=datetime.datetime.now)
637
638     class Meta:
639         app_label = 'forum'