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