]> git.openstreetmap.org Git - osqa.git/blob - forum/models/user.py
abb398931a495dafe96a23972dec68e3f0a2f161
[osqa.git] / forum / models / user.py
1 from base import *\r
2 from forum import const\r
3 from django.contrib.contenttypes.models import ContentType\r
4 from django.contrib.auth.models import User as DjangoUser, AnonymousUser as DjangoAnonymousUser\r
5 from django.db.models import Q\r
6 try:\r
7     from hashlib import md5\r
8 except:\r
9     import md5\r
10 import string\r
11 from random import Random\r
12 \r
13 from django.utils.translation import ugettext as _\r
14 import django.dispatch\r
15 \r
16 \r
17 QUESTIONS_PER_PAGE_CHOICES = (\r
18    (10, u'10'),\r
19    (30, u'30'),\r
20    (50, u'50'),\r
21 )\r
22 \r
23 class UserManager(CachedManager):\r
24     def get_site_owner(self):\r
25         return self.all().order_by('date_joined')[0]\r
26 \r
27 class AnonymousUser(DjangoAnonymousUser):\r
28     def get_visible_answers(self, question):\r
29         return question.answers.filter(deleted=False)\r
30 \r
31     def can_view_deleted_post(self, post):\r
32         return False\r
33 \r
34     def can_vote_up(self):\r
35         return False\r
36 \r
37     def can_vote_down(self):\r
38         return False\r
39 \r
40     def can_flag_offensive(self, post=None):\r
41         return False\r
42 \r
43     def can_view_offensive_flags(self, post=None):\r
44         return False\r
45 \r
46     def can_comment(self, post):\r
47         return False\r
48 \r
49     def can_like_comment(self, comment):\r
50         return False\r
51 \r
52     def can_edit_comment(self, comment):\r
53         return False\r
54 \r
55     def can_delete_comment(self, comment):\r
56         return False\r
57 \r
58     def can_accept_answer(self, answer):\r
59         return False\r
60 \r
61     def can_edit_post(self, post):\r
62         return False\r
63 \r
64     def can_retag_questions(self):\r
65         return False\r
66 \r
67     def can_close_question(self, question):\r
68         return False\r
69 \r
70     def can_reopen_question(self, question):\r
71         return False\r
72 \r
73     def can_delete_post(self, post):\r
74         return False\r
75 \r
76     def can_upload_files(self):\r
77         return False\r
78 \r
79 class User(BaseModel, DjangoUser):\r
80     is_approved = models.BooleanField(default=False)\r
81     email_isvalid = models.BooleanField(default=False)\r
82     email_key = models.CharField(max_length=32, null=True)\r
83     reputation = DenormalizedField(default=1)\r
84 \r
85     gold = DenormalizedField(default=0)\r
86     silver = DenormalizedField(default=0)\r
87     bronze = DenormalizedField(default=0)\r
88 \r
89     questions_per_page = models.SmallIntegerField(choices=QUESTIONS_PER_PAGE_CHOICES, default=10)\r
90     hide_ignored_questions = models.BooleanField(default=False)\r
91     \r
92     last_seen = models.DateTimeField(default=datetime.datetime.now)\r
93     real_name = models.CharField(max_length=100, blank=True)\r
94     website = models.URLField(max_length=200, blank=True)\r
95     location = models.CharField(max_length=100, blank=True)\r
96     date_of_birth = models.DateField(null=True, blank=True)\r
97     about = models.TextField(blank=True)\r
98     \r
99     objects = UserManager()\r
100 \r
101     @property\r
102     def gravatar(self):\r
103         return md5(self.email).hexdigest()\r
104 \r
105     def save(self, *args, **kwargs):\r
106         if self.reputation < 0:\r
107             self.reputation = 1\r
108 \r
109         super(User, self).save(*args, **kwargs)\r
110 \r
111     def get_absolute_url(self):\r
112         return self.get_profile_url()\r
113 \r
114     def get_messages(self):\r
115         messages = []\r
116         for m in self.message_set.all():\r
117             messages.append(m.message)\r
118         return messages\r
119 \r
120     def delete_messages(self):\r
121         self.message_set.all().delete()\r
122 \r
123     def get_profile_url(self):\r
124         return "/%s%d/%s" % (_('users/'), self.id, slugify(self.username))\r
125 \r
126     def get_profile_link(self):\r
127         profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(),self.username)\r
128         return mark_safe(profile_link)\r
129 \r
130     def get_vote_count_today(self):\r
131         today = datetime.date.today()\r
132         return self.votes.filter(voted_at__range=(today - datetime.timedelta(days=1), today)).count()\r
133 \r
134     def get_up_vote_count(self):\r
135         return self.votes.filter(vote=1).count()\r
136 \r
137     def get_down_vote_count(self):\r
138         return self.votes.filter(vote=-1).count()\r
139 \r
140     def get_reputation_by_upvoted_today(self):\r
141         today = datetime.datetime.now()\r
142         sum = self.reputes.filter(\r
143                 models.Q(reputation_type=TYPE_REPUTATION_GAIN_BY_UPVOTED) |\r
144                 models.Q(reputation_type=TYPE_REPUTATION_LOST_BY_UPVOTE_CANCELED),\r
145                 reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(models.Sum('value'))\r
146 \r
147         if sum.get('value__sum', None) is not None: return sum['value__sum']\r
148         return 0\r
149 \r
150     def get_flagged_items_count_today(self):\r
151         today = datetime.date.today()\r
152         return self.flaggeditems.filter(flagged_at__range=(today - datetime.timedelta(days=1), today)).count()\r
153 \r
154     def get_visible_answers(self, question):\r
155         if self.is_superuser:\r
156             return question.answers\r
157         else:\r
158             return question.answers.filter(models.Q(deleted=False) | models.Q(deleted_by=self))\r
159 \r
160     def can_view_deleted_post(self, post):\r
161         return self.is_superuser or post.author == self\r
162 \r
163     def can_vote_up(self):\r
164         return self.reputation >= int(settings.REP_TO_VOTE_UP) or self.is_superuser\r
165 \r
166     def can_vote_down(self):\r
167         return self.reputation >= int(settings.REP_TO_VOTE_DOWN) or self.is_superuser\r
168 \r
169     def can_flag_offensive(self, post=None):\r
170         if post is not None and post.author == self:\r
171             return False\r
172         return self.is_superuser or self.reputation >= int(settings.REP_TO_FLAG)\r
173 \r
174     def can_view_offensive_flags(self, post=None):\r
175         if post is not None and post.author == self:\r
176             return True\r
177         return self.is_superuser or self.reputation >= int(settings.REP_TO_VIEW_FLAGS)\r
178 \r
179     def can_comment(self, post):\r
180         return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT\r
181         ) or self.is_superuser or (post.__class__.__name__ == "Answer" and self == post.question.author)\r
182 \r
183     def can_like_comment(self, comment):\r
184         return self != comment.user and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT) or self.is_superuser)\r
185 \r
186     def can_edit_comment(self, comment):\r
187         return (comment.user == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)\r
188         ) or self.is_superuser\r
189 \r
190     def can_delete_comment(self, comment):\r
191         return self == comment.user or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS) or self.is_superuser\r
192 \r
193     def can_accept_answer(self, answer):\r
194         return self.is_superuser or self == answer.question.author\r
195 \r
196     def can_edit_post(self, post):\r
197         return self.is_superuser or self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS\r
198         ) or (post.wiki and self.reputation >= int(settings.REP_TO_EDIT_WIKI))\r
199 \r
200     def can_retag_questions(self):\r
201         return self.reputation >= int(settings.REP_TO_RETAG)\r
202 \r
203     def can_close_question(self, question):\r
204         return self.is_superuser or (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)\r
205         ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)\r
206 \r
207     def can_reopen_question(self, question):\r
208         return self.is_superuser or (self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN)\r
209 \r
210     def can_delete_post(self, post):\r
211         return self.is_superuser or (self == post.author and (post.__class__.__name__ == "Answer" or\r
212         not post.answers.filter(~Q(author=self)).count()))\r
213 \r
214     def can_upload_files(self):\r
215         return self.is_superuser or self.reputation >= int(settings.REP_TO_UPLOAD)\r
216 \r
217     class Meta:\r
218         app_label = 'forum'\r
219 \r
220 class Activity(GenericContent):\r
221     """\r
222     We keep some history data for user activities\r
223     """\r
224     user = models.ForeignKey(User)\r
225     activity_type = models.SmallIntegerField(choices=TYPE_ACTIVITY)\r
226     active_at = models.DateTimeField(default=datetime.datetime.now)\r
227     is_auditted    = models.BooleanField(default=False)\r
228 \r
229     class Meta:\r
230         app_label = 'forum'\r
231         db_table = u'activity'\r
232 \r
233     def __unicode__(self):\r
234         return u'[%s] was active at %s' % (self.user.username, self.active_at)\r
235 \r
236     def save(self, *args, **kwargs):\r
237         super(Activity, self).save(*args, **kwargs)\r
238         if self._is_new:\r
239             activity_record.send(sender=self.activity_type, instance=self)\r
240 \r
241     @property\r
242     def node(self):\r
243         if self.activity_type in (const.TYPE_ACTIVITY_ANSWER, const.TYPE_ACTIVITY_ASK_QUESTION,\r
244                 const.TYPE_ACTIVITY_MARK_ANSWER, const.TYPE_ACTIVITY_COMMENT_QUESTION, const.TYPE_ACTIVITY_COMMENT_ANSWER):\r
245             return self.content_object.leaf\r
246 \r
247         if self.activity_type in (const.TYPE_ACTIVITY_UPDATE_ANSWER, const.TYPE_ACTIVITY_UPDATE_QUESTION):\r
248             return self.content_object.node.leaf            \r
249             \r
250         raise NotImplementedError()\r
251 \r
252     @property\r
253     def type_as_string(self):\r
254         if self.activity_type == const.TYPE_ACTIVITY_ASK_QUESTION:\r
255             return _("asked")\r
256         elif self.activity_type  == const.TYPE_ACTIVITY_ANSWER:\r
257             return _("answered")\r
258         elif self.activity_type  == const.TYPE_ACTIVITY_MARK_ANSWER:\r
259             return _("marked an answer")\r
260         elif self.activity_type  == const.TYPE_ACTIVITY_UPDATE_QUESTION:\r
261             return _("edited a question")\r
262         elif self.activity_type == const.TYPE_ACTIVITY_COMMENT_QUESTION:\r
263             return _("commented a question")\r
264         elif self.activity_type == const.TYPE_ACTIVITY_COMMENT_ANSWER:\r
265             return _("commented an answer")\r
266         elif self.activity_type == const.TYPE_ACTIVITY_UPDATE_ANSWER:\r
267             return _("edited an answer")\r
268         elif self.activity_type == const.TYPE_ACTIVITY_PRIZE:\r
269             return _("received badge")\r
270         else:\r
271             raise NotImplementedError()\r
272 \r
273 \r
274 activity_record = django.dispatch.Signal(providing_args=['instance'])\r
275 \r
276 class SubscriptionSettings(models.Model):\r
277     user = models.OneToOneField(User, related_name='subscription_settings')\r
278 \r
279     enable_notifications = models.BooleanField(default=True)\r
280 \r
281     #notify if\r
282     member_joins = models.CharField(max_length=1, default='n', choices=const.NOTIFICATION_CHOICES)\r
283     new_question = models.CharField(max_length=1, default='d', choices=const.NOTIFICATION_CHOICES)\r
284     new_question_watched_tags = models.CharField(max_length=1, default='i', choices=const.NOTIFICATION_CHOICES)\r
285     subscribed_questions = models.CharField(max_length=1, default='i', choices=const.NOTIFICATION_CHOICES)\r
286     \r
287     #auto_subscribe_to\r
288     all_questions = models.BooleanField(default=False)\r
289     all_questions_watched_tags = models.BooleanField(default=False)\r
290     questions_asked = models.BooleanField(default=True)\r
291     questions_answered = models.BooleanField(default=True)\r
292     questions_commented = models.BooleanField(default=False)\r
293     questions_viewed = models.BooleanField(default=False)\r
294 \r
295     #notify activity on subscribed\r
296     notify_answers = models.BooleanField(default=True)\r
297     notify_reply_to_comments = models.BooleanField(default=True)\r
298     notify_comments_own_post = models.BooleanField(default=True)\r
299     notify_comments = models.BooleanField(default=False)\r
300     notify_accepted = models.BooleanField(default=False)\r
301 \r
302     class Meta:\r
303         app_label = 'forum'\r
304 \r
305 from forum.utils.time import one_day_from_now\r
306 \r
307 class ValidationHashManager(models.Manager):\r
308     def _generate_md5_hash(self, user, type, hash_data, seed):\r
309         return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()\r
310 \r
311     def create_new(self, user, type, hash_data=[], expiration=None):\r
312         seed = ''.join(Random().sample(string.letters+string.digits, 12))\r
313         hash = self._generate_md5_hash(user, type, hash_data, seed)\r
314 \r
315         obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)\r
316 \r
317         if expiration is not None:\r
318             obj.expiration = expiration\r
319 \r
320         try:\r
321             obj.save()\r
322         except:\r
323             return None\r
324             \r
325         return obj\r
326 \r
327     def validate(self, hash, user, type, hash_data=[]):\r
328         try:\r
329             obj = self.get(hash_code=hash)\r
330         except:\r
331             return False\r
332 \r
333         if obj.type != type:\r
334             return False\r
335 \r
336         if obj.user != user:\r
337             return False\r
338 \r
339         valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))\r
340 \r
341         if valid:\r
342             if obj.expiration < datetime.datetime.now():\r
343                 obj.delete()\r
344                 return False\r
345             else:\r
346                 obj.delete()\r
347                 return True\r
348 \r
349         return False\r
350 \r
351 class ValidationHash(models.Model):\r
352     hash_code = models.CharField(max_length=255,unique=True)\r
353     seed = models.CharField(max_length=12)\r
354     expiration = models.DateTimeField(default=one_day_from_now)\r
355     type = models.CharField(max_length=12)\r
356     user = models.ForeignKey(User)\r
357 \r
358     objects = ValidationHashManager()\r
359 \r
360     class Meta:\r
361         unique_together = ('user', 'type')\r
362         app_label = 'forum'\r
363 \r
364     def __str__(self):\r
365         return self.hash_code\r
366 \r
367 class AuthKeyUserAssociation(models.Model):\r
368     key = models.CharField(max_length=255,null=False,unique=True)\r
369     provider = models.CharField(max_length=64)\r
370     user = models.ForeignKey(User, related_name="auth_keys")\r
371     added_at = models.DateTimeField(default=datetime.datetime.now)\r
372 \r
373     class Meta:\r
374         app_label = 'forum'\r