]> git.openstreetmap.org Git - osqa.git/blob - forum/models/user.py
f5eb9a615304bcd045617859fc01f8b0d6c6623e
[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 gravatar(self):
134         return md5(self.email).hexdigest()
135
136     def save(self, *args, **kwargs):
137         if self.reputation < 0:
138             self.reputation = 0
139
140         new = not bool(self.id)
141
142         super(User, self).save(*args, **kwargs)
143
144         if new:
145             sub_settings = SubscriptionSettings(user=self)
146             sub_settings.save()
147
148     def get_absolute_url(self):
149         return self.get_profile_url()
150
151     def get_messages(self):
152         messages = []
153         for m in self.message_set.all():
154             messages.append(m.message)
155         return messages
156
157     def delete_messages(self):
158         self.message_set.all().delete()
159
160     @models.permalink
161     def get_profile_url(self):
162         return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
163
164     def get_absolute_url(self):
165         return self.get_profile_url()
166
167     def get_profile_link(self):
168         profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
169         return mark_safe(profile_link)
170
171     def get_visible_answers(self, question):
172         return question.answers.filter_state(deleted=False)
173
174     def get_vote_count_today(self):
175         today = datetime.date.today()
176         return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
177                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
178
179     def get_reputation_by_upvoted_today(self):
180         today = datetime.datetime.now()
181         sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
182                 models.Sum('value'))
183         #todo: redo this, maybe transform in the daily cap
184         #if sum.get('value__sum', None) is not None: return sum['value__sum']
185         return 0
186
187     def get_flagged_items_count_today(self):
188         today = datetime.date.today()
189         return self.actions.filter(canceled=False, action_type="flag",
190                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
191
192     @true_if_is_super_or_staff
193     def can_view_deleted_post(self, post):
194         return post.author == self
195
196     @true_if_is_super_or_staff
197     def can_vote_up(self):
198         return self.reputation >= int(settings.REP_TO_VOTE_UP)
199
200     @true_if_is_super_or_staff
201     def can_vote_down(self):
202         return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
203
204     @false_if_validation_required_to('flag')
205     def can_flag_offensive(self, post=None):
206         if post is not None and post.author == self:
207             return False
208         return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
209
210     @true_if_is_super_or_staff
211     def can_view_offensive_flags(self, post=None):
212         if post is not None and post.author == self:
213             return True
214         return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
215
216     @true_if_is_super_or_staff
217     @false_if_validation_required_to('comment')
218     def can_comment(self, post):
219         return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
220                 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
221
222     @true_if_is_super_or_staff
223     def can_like_comment(self, comment):
224         return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
225
226     @true_if_is_super_or_staff
227     def can_edit_comment(self, comment):
228         return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
229         ) or self.is_superuser
230
231     @true_if_is_super_or_staff
232     def can_delete_comment(self, comment):
233         return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
234
235     def can_convert_to_comment(self, answer):
236         return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
237                 (settings.REP_TO_CONVERT_TO_COMMENT))
238
239     @true_if_is_super_or_staff
240     def can_accept_answer(self, answer):
241         return self == answer.question.author
242
243     @true_if_is_super_or_staff
244     def can_create_tags(self):
245         return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
246
247     @true_if_is_super_or_staff
248     def can_edit_post(self, post):
249         return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
250                                                              ) or (post.nis.wiki and self.reputation >= int(
251                 settings.REP_TO_EDIT_WIKI))
252
253     @true_if_is_super_or_staff
254     def can_wikify(self, post):
255         return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
256
257     @true_if_is_super_or_staff
258     def can_cancel_wiki(self, post):
259         return self == post.author
260
261     @true_if_is_super_or_staff
262     def can_retag_questions(self):
263         return self.reputation >= int(settings.REP_TO_RETAG)
264
265     @true_if_is_super_or_staff
266     def can_close_question(self, question):
267         return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
268         ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
269
270     @true_if_is_super_or_staff
271     def can_reopen_question(self, question):
272         return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN
273
274     @true_if_is_super_or_staff
275     def can_delete_post(self, post):
276         if post.node_type == "comment":
277             return self.can_delete_comment(post)
278
279         return (self == post.author and (post.__class__.__name__ == "Answer" or
280         not post.answers.exclude(author=self).count()))
281
282     @true_if_is_super_or_staff
283     def can_upload_files(self):
284         return self.reputation >= int(settings.REP_TO_UPLOAD)
285
286     def email_valid_and_can_ask(self):
287         return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
288
289     def email_valid_and_can_answer(self):
290         return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
291
292     def check_password(self, old_passwd):
293         self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
294         return DjangoUser.check_password(self, old_passwd)
295
296     @property
297     def suspension(self):
298         if self.__dict__.get('_suspension_dencache_', False) != None:
299             try:
300                 self.__dict__['_suspension_dencache_'] = self.actions.get(action_type="suspend", canceled=False)
301             except ObjectDoesNotExist:
302                 self.__dict__['_suspension_dencache_'] = None
303             except MultipleObjectsReturned:
304                 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
305                 self.__dict__['_suspension_dencache_'] = self.actions.filter(action_type="suspend", canceled=False
306                                                                              ).order_by('-action_date')[0]
307
308         return self.__dict__['_suspension_dencache_']
309
310     def _pop_suspension_cache(self):
311         self.__dict__.pop('_suspension_dencache_', None)
312
313     def is_suspended(self):
314         if not self.is_active:
315             suspension = self.suspension
316
317             if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
318             datetime.datetime.now() > suspension.action_date + datetime.timedelta(
319                     days=int(suspension.extra.get('forxdays', 365)))):
320                 suspension.cancel()
321             else:
322                 return True
323
324         return False
325
326     class Meta:
327         app_label = 'forum'
328
329 class SubscriptionSettings(models.Model):
330     user = models.OneToOneField(User, related_name='subscription_settings')
331
332     enable_notifications = models.BooleanField(default=True)
333
334     #notify if
335     member_joins = models.CharField(max_length=1, default='n')
336     new_question = models.CharField(max_length=1, default='d')
337     new_question_watched_tags = models.CharField(max_length=1, default='i')
338     subscribed_questions = models.CharField(max_length=1, default='i')
339
340     #auto_subscribe_to
341     all_questions = models.BooleanField(default=False)
342     all_questions_watched_tags = models.BooleanField(default=False)
343     questions_asked = models.BooleanField(default=True)
344     questions_answered = models.BooleanField(default=True)
345     questions_commented = models.BooleanField(default=False)
346     questions_viewed = models.BooleanField(default=False)
347
348     #notify activity on subscribed
349     notify_answers = models.BooleanField(default=True)
350     notify_reply_to_comments = models.BooleanField(default=True)
351     notify_comments_own_post = models.BooleanField(default=True)
352     notify_comments = models.BooleanField(default=False)
353     notify_accepted = models.BooleanField(default=False)
354
355     class Meta:
356         app_label = 'forum'
357
358 from forum.utils.time import one_day_from_now
359
360 class ValidationHashManager(models.Manager):
361     def _generate_md5_hash(self, user, type, hash_data, seed):
362         return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
363
364     def create_new(self, user, type, hash_data=[], expiration=None):
365         seed = ''.join(Random().sample(string.letters+string.digits, 12))
366         hash = self._generate_md5_hash(user, type, hash_data, seed)
367
368         obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
369
370         if expiration is not None:
371             obj.expiration = expiration
372
373         try:
374             obj.save()
375         except:
376             return None
377
378         return obj
379
380     def validate(self, hash, user, type, hash_data=[]):
381         try:
382             obj = self.get(hash_code=hash)
383         except:
384             return False
385
386         if obj.type != type:
387             return False
388
389         if obj.user != user:
390             return False
391
392         valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
393
394         if valid:
395             if obj.expiration < datetime.datetime.now():
396                 obj.delete()
397                 return False
398             else:
399                 obj.delete()
400                 return True
401
402         return False
403
404 class ValidationHash(models.Model):
405     hash_code = models.CharField(max_length=255, unique=True)
406     seed = models.CharField(max_length=12)
407     expiration = models.DateTimeField(default=one_day_from_now)
408     type = models.CharField(max_length=12)
409     user = models.ForeignKey(User)
410
411     objects = ValidationHashManager()
412
413     class Meta:
414         unique_together = ('user', 'type')
415         app_label = 'forum'
416
417     def __str__(self):
418         return self.hash_code
419
420 class AuthKeyUserAssociation(models.Model):
421     key = models.CharField(max_length=255, null=False, unique=True)
422     provider = models.CharField(max_length=64)
423     user = models.ForeignKey(User, related_name="auth_keys")
424     added_at = models.DateTimeField(default=datetime.datetime.now)
425
426     class Meta:
427         app_label = 'forum'