]> git.openstreetmap.org Git - osqa.git/blob - forum/models/user.py
Closing http://jira.osqa.net/browse/OSQA-24 with a bonus, it's also possible to speci...
[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     from md5 import new as md5\r
10 \r
11 import string\r
12 from random import Random\r
13 \r
14 from django.utils.translation import ugettext as _\r
15 import django.dispatch\r
16 \r
17 \r
18 QUESTIONS_PER_PAGE_CHOICES = (\r
19    (10, u'10'),\r
20    (30, u'30'),\r
21    (50, u'50'),\r
22 )\r
23 \r
24 class UserManager(CachedManager):\r
25     def get_site_owner(self):\r
26         return self.all().order_by('date_joined')[0]\r
27 \r
28 class AnonymousUser(DjangoAnonymousUser):\r
29     def get_visible_answers(self, question):\r
30         return question.answers.filter(deleted=None)\r
31 \r
32     def can_view_deleted_post(self, post):\r
33         return False\r
34 \r
35     def can_vote_up(self):\r
36         return False\r
37 \r
38     def can_vote_down(self):\r
39         return False\r
40 \r
41     def can_flag_offensive(self, post=None):\r
42         return False\r
43 \r
44     def can_view_offensive_flags(self, post=None):\r
45         return False\r
46 \r
47     def can_comment(self, post):\r
48         return False\r
49 \r
50     def can_like_comment(self, comment):\r
51         return False\r
52 \r
53     def can_edit_comment(self, comment):\r
54         return False\r
55 \r
56     def can_delete_comment(self, comment):\r
57         return False\r
58 \r
59     def can_accept_answer(self, answer):\r
60         return False\r
61 \r
62     def can_edit_post(self, post):\r
63         return False\r
64 \r
65     def can_retag_questions(self):\r
66         return False\r
67 \r
68     def can_close_question(self, question):\r
69         return False\r
70 \r
71     def can_reopen_question(self, question):\r
72         return False\r
73 \r
74     def can_delete_post(self, post):\r
75         return False\r
76 \r
77     def can_upload_files(self):\r
78         return False\r
79 \r
80 def true_if_is_super_or_staff(fn):\r
81     def decorated(self, *args, **kwargs):\r
82         return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)\r
83     return decorated\r
84 \r
85 class User(BaseModel, DjangoUser):\r
86     is_approved = models.BooleanField(default=False)\r
87     email_isvalid = models.BooleanField(default=False)\r
88 \r
89     reputation = models.PositiveIntegerField(default=0)\r
90     gold = models.PositiveIntegerField(default=0)\r
91     silver = models.PositiveIntegerField(default=0)\r
92     bronze = models.PositiveIntegerField(default=0)\r
93     \r
94     last_seen = models.DateTimeField(default=datetime.datetime.now)\r
95     real_name = models.CharField(max_length=100, blank=True)\r
96     website = models.URLField(max_length=200, blank=True)\r
97     location = models.CharField(max_length=100, blank=True)\r
98     date_of_birth = models.DateField(null=True, blank=True)\r
99     about = models.TextField(blank=True)\r
100 \r
101     subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')\r
102 \r
103     vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")\r
104     vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")\r
105    \r
106     objects = UserManager()\r
107 \r
108     @property\r
109     def gravatar(self):\r
110         return md5(self.email).hexdigest()\r
111 \r
112     def save(self, *args, **kwargs):\r
113         if self.reputation < 0:\r
114             self.reputation = 0\r
115 \r
116         new = not bool(self.id)\r
117 \r
118         super(User, self).save(*args, **kwargs)\r
119 \r
120         if new:\r
121             sub_settings = SubscriptionSettings(user=self)\r
122             sub_settings.save()\r
123 \r
124     def get_absolute_url(self):\r
125         return self.get_profile_url()\r
126 \r
127     def get_messages(self):\r
128         messages = []\r
129         for m in self.message_set.all():\r
130             messages.append(m.message)\r
131         return messages\r
132 \r
133     def delete_messages(self):\r
134         self.message_set.all().delete()\r
135 \r
136     @models.permalink\r
137     def get_profile_url(self):\r
138         return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})\r
139 \r
140     def get_profile_link(self):\r
141         profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(),self.username)\r
142         return mark_safe(profile_link)\r
143 \r
144     def get_visible_answers(self, question):\r
145         return question.answers.filter(deleted=None, in_moderation=None)\r
146 \r
147     def get_vote_count_today(self):\r
148         today = datetime.date.today()\r
149         return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),\r
150                 action_date__range=(today - datetime.timedelta(days=1), today)).count()\r
151 \r
152     def get_reputation_by_upvoted_today(self):\r
153         today = datetime.datetime.now()\r
154         sum = self.reputes.filter(\r
155                 models.Q(reputation_type=TYPE_REPUTATION_GAIN_BY_UPVOTED) |\r
156                 models.Q(reputation_type=TYPE_REPUTATION_LOST_BY_UPVOTE_CANCELED),\r
157                 reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(models.Sum('value'))\r
158 \r
159         if sum.get('value__sum', None) is not None: return sum['value__sum']\r
160         return 0\r
161 \r
162     def get_flagged_items_count_today(self):\r
163         today = datetime.date.today()\r
164         return self.actions.filter(canceled=False, action_type="flag",\r
165                 action_date__range=(today - datetime.timedelta(days=1), today)).count()\r
166 \r
167     @true_if_is_super_or_staff\r
168     def can_view_deleted_post(self, post):\r
169         return post.author == self\r
170 \r
171     @true_if_is_super_or_staff\r
172     def can_vote_up(self):\r
173         return self.reputation >= int(settings.REP_TO_VOTE_UP)\r
174 \r
175     @true_if_is_super_or_staff\r
176     def can_vote_down(self):\r
177         return self.reputation >= int(settings.REP_TO_VOTE_DOWN)\r
178 \r
179     def can_flag_offensive(self, post=None):\r
180         if post is not None and post.author == self:\r
181             return False\r
182         return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)\r
183 \r
184     @true_if_is_super_or_staff\r
185     def can_view_offensive_flags(self, post=None):\r
186         if post is not None and post.author == self:\r
187             return True\r
188         return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)\r
189 \r
190     @true_if_is_super_or_staff\r
191     def can_comment(self, post):\r
192         return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT\r
193         ) or (post.__class__.__name__ == "Answer" and self == post.question.author)\r
194 \r
195     @true_if_is_super_or_staff\r
196     def can_like_comment(self, comment):\r
197         return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))\r
198 \r
199     @true_if_is_super_or_staff\r
200     def can_edit_comment(self, comment):\r
201         return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)\r
202         ) or self.is_superuser\r
203 \r
204     @true_if_is_super_or_staff\r
205     def can_delete_comment(self, comment):\r
206         return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)\r
207 \r
208     @true_if_is_super_or_staff\r
209     def can_accept_answer(self, answer):\r
210         return self == answer.question.author\r
211 \r
212     @true_if_is_super_or_staff\r
213     def can_edit_post(self, post):\r
214         return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS\r
215         ) or (post.wiki and self.reputation >= int(settings.REP_TO_EDIT_WIKI))\r
216 \r
217     @true_if_is_super_or_staff\r
218     def can_retag_questions(self):\r
219         return self.reputation >= int(settings.REP_TO_RETAG)\r
220 \r
221     @true_if_is_super_or_staff\r
222     def can_close_question(self, question):\r
223         return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)\r
224         ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)\r
225 \r
226     @true_if_is_super_or_staff\r
227     def can_reopen_question(self, question):\r
228         return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN\r
229 \r
230     @true_if_is_super_or_staff\r
231     def can_delete_post(self, post):\r
232         if post.node_type == "comment":\r
233             return self.can_delete_comment(post)\r
234             \r
235         return (self == post.author and (post.__class__.__name__ == "Answer" or\r
236             not post.answers.exclude(author=self).count()))\r
237 \r
238     @true_if_is_super_or_staff\r
239     def can_upload_files(self):\r
240         return self.reputation >= int(settings.REP_TO_UPLOAD)\r
241 \r
242     class Meta:\r
243         app_label = 'forum'\r
244 \r
245 class SubscriptionSettings(models.Model):\r
246     user = models.OneToOneField(User, related_name='subscription_settings')\r
247 \r
248     enable_notifications = models.BooleanField(default=True)\r
249 \r
250     #notify if\r
251     member_joins = models.CharField(max_length=1, default='n', choices=const.NOTIFICATION_CHOICES)\r
252     new_question = models.CharField(max_length=1, default='d', choices=const.NOTIFICATION_CHOICES)\r
253     new_question_watched_tags = models.CharField(max_length=1, default='i', choices=const.NOTIFICATION_CHOICES)\r
254     subscribed_questions = models.CharField(max_length=1, default='i', choices=const.NOTIFICATION_CHOICES)\r
255     \r
256     #auto_subscribe_to\r
257     all_questions = models.BooleanField(default=False)\r
258     all_questions_watched_tags = models.BooleanField(default=False)\r
259     questions_asked = models.BooleanField(default=True)\r
260     questions_answered = models.BooleanField(default=True)\r
261     questions_commented = models.BooleanField(default=False)\r
262     questions_viewed = models.BooleanField(default=False)\r
263 \r
264     #notify activity on subscribed\r
265     notify_answers = models.BooleanField(default=True)\r
266     notify_reply_to_comments = models.BooleanField(default=True)\r
267     notify_comments_own_post = models.BooleanField(default=True)\r
268     notify_comments = models.BooleanField(default=False)\r
269     notify_accepted = models.BooleanField(default=False)\r
270 \r
271     class Meta:\r
272         app_label = 'forum'\r
273 \r
274 from forum.utils.time import one_day_from_now\r
275 \r
276 class ValidationHashManager(models.Manager):\r
277     def _generate_md5_hash(self, user, type, hash_data, seed):\r
278         return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()\r
279 \r
280     def create_new(self, user, type, hash_data=[], expiration=None):\r
281         seed = ''.join(Random().sample(string.letters+string.digits, 12))\r
282         hash = self._generate_md5_hash(user, type, hash_data, seed)\r
283 \r
284         obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)\r
285 \r
286         if expiration is not None:\r
287             obj.expiration = expiration\r
288 \r
289         try:\r
290             obj.save()\r
291         except:\r
292             return None\r
293             \r
294         return obj\r
295 \r
296     def validate(self, hash, user, type, hash_data=[]):\r
297         try:\r
298             obj = self.get(hash_code=hash)\r
299         except:\r
300             return False\r
301 \r
302         if obj.type != type:\r
303             return False\r
304 \r
305         if obj.user != user:\r
306             return False\r
307 \r
308         valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))\r
309 \r
310         if valid:\r
311             if obj.expiration < datetime.datetime.now():\r
312                 obj.delete()\r
313                 return False\r
314             else:\r
315                 obj.delete()\r
316                 return True\r
317 \r
318         return False\r
319 \r
320 class ValidationHash(models.Model):\r
321     hash_code = models.CharField(max_length=255,unique=True)\r
322     seed = models.CharField(max_length=12)\r
323     expiration = models.DateTimeField(default=one_day_from_now)\r
324     type = models.CharField(max_length=12)\r
325     user = models.ForeignKey(User)\r
326 \r
327     objects = ValidationHashManager()\r
328 \r
329     class Meta:\r
330         unique_together = ('user', 'type')\r
331         app_label = 'forum'\r
332 \r
333     def __str__(self):\r
334         return self.hash_code\r
335 \r
336 class AuthKeyUserAssociation(models.Model):\r
337     key = models.CharField(max_length=255,null=False,unique=True)\r
338     provider = models.CharField(max_length=64)\r
339     user = models.ForeignKey(User, related_name="auth_keys")\r
340     added_at = models.DateTimeField(default=datetime.datetime.now)\r
341 \r
342     class Meta:\r
343         app_label = 'forum'\r