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
7 from hashlib import md5
\r
11 from random import Random
\r
13 from django.utils.translation import ugettext as _
\r
14 import django.dispatch
\r
17 QUESTIONS_PER_PAGE_CHOICES = (
\r
23 class UserManager(CachedManager):
\r
24 def get_site_owner(self):
\r
25 return self.all().order_by('date_joined')[0]
\r
27 class AnonymousUser(DjangoAnonymousUser):
\r
28 def get_visible_answers(self, question):
\r
29 return question.answers.filter(deleted=False)
\r
31 def can_view_deleted_post(self, post):
\r
34 def can_vote_up(self):
\r
37 def can_vote_down(self):
\r
40 def can_flag_offensive(self, post=None):
\r
43 def can_view_offensive_flags(self, post=None):
\r
46 def can_comment(self, post):
\r
49 def can_like_comment(self, comment):
\r
52 def can_edit_comment(self, comment):
\r
55 def can_delete_comment(self, comment):
\r
58 def can_accept_answer(self, answer):
\r
61 def can_edit_post(self, post):
\r
64 def can_retag_questions(self):
\r
67 def can_close_question(self, question):
\r
70 def can_reopen_question(self, question):
\r
73 def can_delete_post(self, post):
\r
76 def can_upload_files(self):
\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 = models.PositiveIntegerField(default=1)
\r
85 gold = models.SmallIntegerField(default=0)
\r
86 silver = models.SmallIntegerField(default=0)
\r
87 bronze = models.SmallIntegerField(default=0)
\r
89 questions_per_page = models.SmallIntegerField(choices=QUESTIONS_PER_PAGE_CHOICES, default=10)
\r
90 hide_ignored_questions = models.BooleanField(default=False)
\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
99 objects = UserManager()
\r
102 def gravatar(self):
\r
103 return md5(self.email).hexdigest()
\r
105 def save(self, *args, **kwargs):
\r
106 if self.reputation < 0:
\r
107 self.reputation = 1
\r
109 super(User, self).save(*args, **kwargs)
\r
111 def get_absolute_url(self):
\r
112 return self.get_profile_url()
\r
114 def get_messages(self):
\r
116 for m in self.message_set.all():
\r
117 messages.append(m.message)
\r
120 def delete_messages(self):
\r
121 self.message_set.all().delete()
\r
123 def get_profile_url(self):
\r
124 """Returns the URL for this User's profile."""
\r
125 return "/%s%d/%s" % (_('users/'), self.id, slugify(self.username))
\r
127 def get_profile_link(self):
\r
128 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(),self.username)
\r
129 logging.debug('in get profile link %s' % profile_link)
\r
130 return mark_safe(profile_link)
\r
132 def get_vote_count_today(self):
\r
133 today = datetime.date.today()
\r
134 return self.votes.filter(voted_at__range=(today - datetime.timedelta(days=1), today)).count()
\r
136 def get_up_vote_count(self):
\r
137 return self.votes.filter(vote=1).count()
\r
139 def get_down_vote_count(self):
\r
140 return self.votes.filter(vote=-1).count()
\r
142 def get_reputation_by_upvoted_today(self):
\r
143 today = datetime.datetime.now()
\r
144 sum = self.reputes.filter(
\r
145 models.Q(reputation_type=TYPE_REPUTATION_GAIN_BY_UPVOTED) |
\r
146 models.Q(reputation_type=TYPE_REPUTATION_LOST_BY_UPVOTE_CANCELED),
\r
147 reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(models.Sum('value'))
\r
149 if sum.get('value__sum', None) is not None: return sum['value__sum']
\r
152 def get_flagged_items_count_today(self):
\r
153 today = datetime.date.today()
\r
154 return self.flaggeditems.filter(flagged_at__range=(today - datetime.timedelta(days=1), today)).count()
\r
156 def get_visible_answers(self, question):
\r
157 if self.is_superuser:
\r
158 return question.answers
\r
160 return question.answers.filter(models.Q(deleted=False) | models.Q(deleted_by=self))
\r
162 def can_view_deleted_post(self, post):
\r
163 return self.is_superuser or post.author == self
\r
165 def can_vote_up(self):
\r
166 return self.reputation >= int(settings.REP_TO_VOTE_UP) or self.is_superuser
\r
168 def can_vote_down(self):
\r
169 return self.reputation >= int(settings.REP_TO_VOTE_DOWN) or self.is_superuser
\r
171 def can_flag_offensive(self, post=None):
\r
172 if post is not None and post.author == self:
\r
174 return self.is_superuser or self.reputation >= int(settings.REP_TO_FLAG)
\r
176 def can_view_offensive_flags(self, post=None):
\r
177 if post is not None and post.author == self:
\r
179 return self.is_superuser or self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
\r
181 def can_comment(self, post):
\r
182 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
\r
183 ) or self.is_superuser or (post.__class__.__name__ == "Answer" and self == post.question.author)
\r
185 def can_like_comment(self, comment):
\r
186 return self != comment.user and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT) or self.is_superuser)
\r
188 def can_edit_comment(self, comment):
\r
189 return (comment.user == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
\r
190 ) or self.is_superuser
\r
192 def can_delete_comment(self, comment):
\r
193 return self == comment.user or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS) or self.is_superuser
\r
195 def can_accept_answer(self, answer):
\r
196 return self.is_superuser or self == answer.question.author
\r
198 def can_edit_post(self, post):
\r
199 return self.is_superuser or self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
\r
200 ) or (post.wiki and self.reputation >= int(settings.REP_TO_EDIT_WIKI))
\r
202 def can_retag_questions(self):
\r
203 return self.reputation >= int(settings.REP_TO_RETAG)
\r
205 def can_close_question(self, question):
\r
206 return self.is_superuser or (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
\r
207 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
\r
209 def can_reopen_question(self, question):
\r
210 return self.is_superuser or (self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN)
\r
212 def can_delete_post(self, post):
\r
213 return self.is_superuser or (self == post.author and (post.__class__.__name__ == "Answer" or
\r
214 not post.answers.filter(~Q(author=self)).count()))
\r
216 def can_upload_files(self):
\r
217 return self.is_superuser or self.reputation >= int(settings.REP_TO_UPLOAD)
\r
220 app_label = 'forum'
\r
222 class Activity(GenericContent):
\r
224 We keep some history data for user activities
\r
226 user = models.ForeignKey(User)
\r
227 activity_type = models.SmallIntegerField(choices=TYPE_ACTIVITY)
\r
228 active_at = models.DateTimeField(default=datetime.datetime.now)
\r
229 is_auditted = models.BooleanField(default=False)
\r
232 app_label = 'forum'
\r
233 db_table = u'activity'
\r
235 def __unicode__(self):
\r
236 return u'[%s] was active at %s' % (self.user.username, self.active_at)
\r
238 def save(self, *args, **kwargs):
\r
239 super(Activity, self).save(*args, **kwargs)
\r
241 activity_record.send(sender=self.activity_type, instance=self)
\r
245 if self.activity_type in (const.TYPE_ACTIVITY_ANSWER, const.TYPE_ACTIVITY_ASK_QUESTION,
\r
246 const.TYPE_ACTIVITY_MARK_ANSWER, const.TYPE_ACTIVITY_COMMENT_QUESTION, const.TYPE_ACTIVITY_COMMENT_ANSWER):
\r
247 return self.content_object.leaf
\r
249 if self.activity_type in (const.TYPE_ACTIVITY_UPDATE_ANSWER, const.TYPE_ACTIVITY_UPDATE_QUESTION):
\r
250 return self.content_object.node.leaf
\r
252 raise NotImplementedError()
\r
255 def type_as_string(self):
\r
256 if self.activity_type == const.TYPE_ACTIVITY_ASK_QUESTION:
\r
258 elif self.activity_type == const.TYPE_ACTIVITY_ANSWER:
\r
259 return _("answered")
\r
260 elif self.activity_type == const.TYPE_ACTIVITY_MARK_ANSWER:
\r
261 return _("marked an answer")
\r
262 elif self.activity_type == const.TYPE_ACTIVITY_UPDATE_QUESTION:
\r
263 return _("edited a question")
\r
264 elif self.activity_type == const.TYPE_ACTIVITY_COMMENT_QUESTION:
\r
265 return _("commented a question")
\r
266 elif self.activity_type == const.TYPE_ACTIVITY_COMMENT_ANSWER:
\r
267 return _("commented an answer")
\r
268 elif self.activity_type == const.TYPE_ACTIVITY_UPDATE_ANSWER:
\r
269 return _("edited an answer")
\r
270 elif self.activity_type == const.TYPE_ACTIVITY_PRIZE:
\r
271 return _("received badge")
\r
273 raise NotImplementedError()
\r
276 activity_record = django.dispatch.Signal(providing_args=['instance'])
\r
278 class SubscriptionSettings(models.Model):
\r
279 user = models.OneToOneField(User, related_name='subscription_settings')
\r
281 enable_notifications = models.BooleanField(default=True)
\r
284 member_joins = models.CharField(max_length=1, default='n', choices=const.NOTIFICATION_CHOICES)
\r
285 new_question = models.CharField(max_length=1, default='d', choices=const.NOTIFICATION_CHOICES)
\r
286 new_question_watched_tags = models.CharField(max_length=1, default='i', choices=const.NOTIFICATION_CHOICES)
\r
287 subscribed_questions = models.CharField(max_length=1, default='i', choices=const.NOTIFICATION_CHOICES)
\r
290 all_questions = models.BooleanField(default=False)
\r
291 all_questions_watched_tags = models.BooleanField(default=False)
\r
292 questions_asked = models.BooleanField(default=True)
\r
293 questions_answered = models.BooleanField(default=True)
\r
294 questions_commented = models.BooleanField(default=False)
\r
295 questions_viewed = models.BooleanField(default=False)
\r
297 #notify activity on subscribed
\r
298 notify_answers = models.BooleanField(default=True)
\r
299 notify_reply_to_comments = models.BooleanField(default=True)
\r
300 notify_comments_own_post = models.BooleanField(default=True)
\r
301 notify_comments = models.BooleanField(default=False)
\r
302 notify_accepted = models.BooleanField(default=False)
\r
305 app_label = 'forum'
\r
307 from forum.utils.time import one_day_from_now
\r
309 class ValidationHashManager(models.Manager):
\r
310 def _generate_md5_hash(self, user, type, hash_data, seed):
\r
311 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
\r
313 def create_new(self, user, type, hash_data=[], expiration=None):
\r
314 seed = ''.join(Random().sample(string.letters+string.digits, 12))
\r
315 hash = self._generate_md5_hash(user, type, hash_data, seed)
\r
317 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
\r
319 if expiration is not None:
\r
320 obj.expiration = expiration
\r
329 def validate(self, hash, user, type, hash_data=[]):
\r
331 obj = self.get(hash_code=hash)
\r
335 if obj.type != type:
\r
338 if obj.user != user:
\r
341 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
\r
344 if obj.expiration < datetime.datetime.now():
\r
353 class ValidationHash(models.Model):
\r
354 hash_code = models.CharField(max_length=255,unique=True)
\r
355 seed = models.CharField(max_length=12)
\r
356 expiration = models.DateTimeField(default=one_day_from_now)
\r
357 type = models.CharField(max_length=12)
\r
358 user = models.ForeignKey(User)
\r
360 objects = ValidationHashManager()
\r
363 unique_together = ('user', 'type')
\r
364 app_label = 'forum'
\r
367 return self.hash_code
\r
369 class AuthKeyUserAssociation(models.Model):
\r
370 key = models.CharField(max_length=255,null=False,unique=True)
\r
371 provider = models.CharField(max_length=64)
\r
372 user = models.ForeignKey(User, related_name="auth_keys")
\r
373 added_at = models.DateTimeField(default=datetime.datetime.now)
\r
376 app_label = 'forum'
\r