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