]> git.openstreetmap.org Git - osqa.git/blob - forum/models/user.py
Added the option to limit the tags creation. It will defaults to false, and there...
[osqa.git] / forum / models / user.py
1 from base import *\r
2 from django.contrib.contenttypes.models import ContentType\r
3 from django.contrib.auth.models import User as DjangoUser, AnonymousUser as DjangoAnonymousUser\r
4 from django.db.models import Q\r
5 try:\r
6     from hashlib import md5\r
7 except:\r
8     from md5 import new as md5\r
9 \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_state(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_convert_to_comment(self, answer):\r
59         return False\r
60 \r
61     def can_accept_answer(self, answer):\r
62         return False\r
63 \r
64     def can_create_tags(self):\r
65         return False\r
66 \r
67     def can_edit_post(self, post):\r
68         return False\r
69 \r
70     def can_wikify(self, post):\r
71         return False\r
72 \r
73     def can_cancel_wiki(self, post):\r
74         return False\r
75 \r
76     def can_retag_questions(self):\r
77         return False\r
78 \r
79     def can_close_question(self, question):\r
80         return False\r
81 \r
82     def can_reopen_question(self, question):\r
83         return False\r
84 \r
85     def can_delete_post(self, post):\r
86         return False\r
87 \r
88     def can_upload_files(self):\r
89         return False\r
90 \r
91 def true_if_is_super_or_staff(fn):\r
92     def decorated(self, *args, **kwargs):\r
93         return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)\r
94     return decorated\r
95 \r
96 class User(BaseModel, DjangoUser):\r
97     is_approved = models.BooleanField(default=False)\r
98     email_isvalid = models.BooleanField(default=False)\r
99 \r
100     reputation = models.PositiveIntegerField(default=0)\r
101     gold = models.PositiveIntegerField(default=0)\r
102     silver = models.PositiveIntegerField(default=0)\r
103     bronze = models.PositiveIntegerField(default=0)\r
104     \r
105     last_seen = models.DateTimeField(default=datetime.datetime.now)\r
106     real_name = models.CharField(max_length=100, blank=True)\r
107     website = models.URLField(max_length=200, blank=True)\r
108     location = models.CharField(max_length=100, blank=True)\r
109     date_of_birth = models.DateField(null=True, blank=True)\r
110     about = models.TextField(blank=True)\r
111 \r
112     subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')\r
113 \r
114     vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")\r
115     vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")\r
116    \r
117     objects = UserManager()\r
118 \r
119     @property\r
120     def gravatar(self):\r
121         return md5(self.email).hexdigest()\r
122 \r
123     def save(self, *args, **kwargs):\r
124         if self.reputation < 0:\r
125             self.reputation = 0\r
126 \r
127         new = not bool(self.id)\r
128 \r
129         super(User, self).save(*args, **kwargs)\r
130 \r
131         if new:\r
132             sub_settings = SubscriptionSettings(user=self)\r
133             sub_settings.save()\r
134 \r
135     def get_absolute_url(self):\r
136         return self.get_profile_url()\r
137 \r
138     def get_messages(self):\r
139         messages = []\r
140         for m in self.message_set.all():\r
141             messages.append(m.message)\r
142         return messages\r
143 \r
144     def delete_messages(self):\r
145         self.message_set.all().delete()\r
146 \r
147     @models.permalink\r
148     def get_profile_url(self):\r
149         return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})\r
150 \r
151     def get_profile_link(self):\r
152         profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(),self.username)\r
153         return mark_safe(profile_link)\r
154 \r
155     def get_visible_answers(self, question):\r
156         return question.answers.filter_state(deleted=False)\r
157 \r
158     def get_vote_count_today(self):\r
159         today = datetime.date.today()\r
160         return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),\r
161                 action_date__range=(today - datetime.timedelta(days=1), today)).count()\r
162 \r
163     def get_reputation_by_upvoted_today(self):\r
164         today = datetime.datetime.now()\r
165         sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(models.Sum('value'))\r
166         #todo: redo this, maybe transform in the daily cap\r
167         #if sum.get('value__sum', None) is not None: return sum['value__sum']\r
168         return 0\r
169 \r
170     def get_flagged_items_count_today(self):\r
171         today = datetime.date.today()\r
172         return self.actions.filter(canceled=False, action_type="flag",\r
173                 action_date__range=(today - datetime.timedelta(days=1), today)).count()\r
174 \r
175     @true_if_is_super_or_staff\r
176     def can_view_deleted_post(self, post):\r
177         return post.author == self\r
178 \r
179     @true_if_is_super_or_staff\r
180     def can_vote_up(self):\r
181         return self.reputation >= int(settings.REP_TO_VOTE_UP)\r
182 \r
183     @true_if_is_super_or_staff\r
184     def can_vote_down(self):\r
185         return self.reputation >= int(settings.REP_TO_VOTE_DOWN)\r
186 \r
187     def can_flag_offensive(self, post=None):\r
188         if post is not None and post.author == self:\r
189             return False\r
190         return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)\r
191 \r
192     @true_if_is_super_or_staff\r
193     def can_view_offensive_flags(self, post=None):\r
194         if post is not None and post.author == self:\r
195             return True\r
196         return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)\r
197 \r
198     @true_if_is_super_or_staff\r
199     def can_comment(self, post):\r
200         return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT\r
201         ) or (post.__class__.__name__ == "Answer" and self == post.question.author)\r
202 \r
203     @true_if_is_super_or_staff\r
204     def can_like_comment(self, comment):\r
205         return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))\r
206 \r
207     @true_if_is_super_or_staff\r
208     def can_edit_comment(self, comment):\r
209         return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)\r
210         ) or self.is_superuser\r
211 \r
212     @true_if_is_super_or_staff\r
213     def can_delete_comment(self, comment):\r
214         return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)\r
215 \r
216     def can_convert_to_comment(self, answer):\r
217         return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int(settings.REP_TO_CONVERT_TO_COMMENT))\r
218 \r
219     @true_if_is_super_or_staff\r
220     def can_accept_answer(self, answer):\r
221         return self == answer.question.author\r
222 \r
223     @true_if_is_super_or_staff\r
224     def can_create_tags(self):\r
225         return self.reputation >= int(settings.REP_TO_CREATE_TAGS)\r
226 \r
227     @true_if_is_super_or_staff\r
228     def can_edit_post(self, post):\r
229         return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS\r
230         ) or (post.nis.wiki and self.reputation >= int(settings.REP_TO_EDIT_WIKI))\r
231 \r
232     @true_if_is_super_or_staff\r
233     def can_wikify(self, post):\r
234         return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)\r
235 \r
236     @true_if_is_super_or_staff\r
237     def can_cancel_wiki(self, post):\r
238         return self == post.author\r
239 \r
240     @true_if_is_super_or_staff\r
241     def can_retag_questions(self):\r
242         return self.reputation >= int(settings.REP_TO_RETAG)\r
243 \r
244     @true_if_is_super_or_staff\r
245     def can_close_question(self, question):\r
246         return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)\r
247         ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)\r
248 \r
249     @true_if_is_super_or_staff\r
250     def can_reopen_question(self, question):\r
251         return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN\r
252 \r
253     @true_if_is_super_or_staff\r
254     def can_delete_post(self, post):\r
255         if post.node_type == "comment":\r
256             return self.can_delete_comment(post)\r
257             \r
258         return (self == post.author and (post.__class__.__name__ == "Answer" or\r
259             not post.answers.exclude(author=self).count()))\r
260 \r
261     @true_if_is_super_or_staff\r
262     def can_upload_files(self):\r
263         return self.reputation >= int(settings.REP_TO_UPLOAD)\r
264 \r
265     def check_password(self, old_passwd):\r
266         self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])\r
267         return DjangoUser.check_password(self, old_passwd)\r
268 \r
269 \r
270     class Meta:\r
271         app_label = 'forum'\r
272 \r
273 class SubscriptionSettings(models.Model):\r
274     user = models.OneToOneField(User, related_name='subscription_settings')\r
275 \r
276     enable_notifications = models.BooleanField(default=True)\r
277 \r
278     #notify if\r
279     member_joins = models.CharField(max_length=1, default='n')\r
280     new_question = models.CharField(max_length=1, default='d')\r
281     new_question_watched_tags = models.CharField(max_length=1, default='i')\r
282     subscribed_questions = models.CharField(max_length=1, default='i')\r
283     \r
284     #auto_subscribe_to\r
285     all_questions = models.BooleanField(default=False)\r
286     all_questions_watched_tags = models.BooleanField(default=False)\r
287     questions_asked = models.BooleanField(default=True)\r
288     questions_answered = models.BooleanField(default=True)\r
289     questions_commented = models.BooleanField(default=False)\r
290     questions_viewed = models.BooleanField(default=False)\r
291 \r
292     #notify activity on subscribed\r
293     notify_answers = models.BooleanField(default=True)\r
294     notify_reply_to_comments = models.BooleanField(default=True)\r
295     notify_comments_own_post = models.BooleanField(default=True)\r
296     notify_comments = models.BooleanField(default=False)\r
297     notify_accepted = models.BooleanField(default=False)\r
298 \r
299     class Meta:\r
300         app_label = 'forum'\r
301 \r
302 from forum.utils.time import one_day_from_now\r
303 \r
304 class ValidationHashManager(models.Manager):\r
305     def _generate_md5_hash(self, user, type, hash_data, seed):\r
306         return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()\r
307 \r
308     def create_new(self, user, type, hash_data=[], expiration=None):\r
309         seed = ''.join(Random().sample(string.letters+string.digits, 12))\r
310         hash = self._generate_md5_hash(user, type, hash_data, seed)\r
311 \r
312         obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)\r
313 \r
314         if expiration is not None:\r
315             obj.expiration = expiration\r
316 \r
317         try:\r
318             obj.save()\r
319         except:\r
320             return None\r
321             \r
322         return obj\r
323 \r
324     def validate(self, hash, user, type, hash_data=[]):\r
325         try:\r
326             obj = self.get(hash_code=hash)\r
327         except:\r
328             return False\r
329 \r
330         if obj.type != type:\r
331             return False\r
332 \r
333         if obj.user != user:\r
334             return False\r
335 \r
336         valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))\r
337 \r
338         if valid:\r
339             if obj.expiration < datetime.datetime.now():\r
340                 obj.delete()\r
341                 return False\r
342             else:\r
343                 obj.delete()\r
344                 return True\r
345 \r
346         return False\r
347 \r
348 class ValidationHash(models.Model):\r
349     hash_code = models.CharField(max_length=255,unique=True)\r
350     seed = models.CharField(max_length=12)\r
351     expiration = models.DateTimeField(default=one_day_from_now)\r
352     type = models.CharField(max_length=12)\r
353     user = models.ForeignKey(User)\r
354 \r
355     objects = ValidationHashManager()\r
356 \r
357     class Meta:\r
358         unique_together = ('user', 'type')\r
359         app_label = 'forum'\r
360 \r
361     def __str__(self):\r
362         return self.hash_code\r
363 \r
364 class AuthKeyUserAssociation(models.Model):\r
365     key = models.CharField(max_length=255,null=False,unique=True)\r
366     provider = models.CharField(max_length=64)\r
367     user = models.ForeignKey(User, related_name="auth_keys")\r
368     added_at = models.DateTimeField(default=datetime.datetime.now)\r
369 \r
370     class Meta:\r
371         app_label = 'forum'\r