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