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