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