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 from hashlib import md5
\r
8 from random import Random
\r
10 from django.utils.translation import ugettext as _
\r
11 import django.dispatch
\r
14 QUESTIONS_PER_PAGE_CHOICES = (
\r
20 class UserManager(CachedManager):
\r
21 def get_site_owner(self):
\r
22 return self.all().order_by('date_joined')[0]
\r
24 class AnonymousUser(DjangoAnonymousUser):
\r
25 def get_visible_answers(self, question):
\r
26 return question.answers.filter(deleted=False)
\r
28 def can_view_deleted_post(self, post):
\r
31 def can_vote_up(self):
\r
34 def can_vote_down(self):
\r
37 def can_flag_offensive(self, post=None):
\r
40 def can_view_offensive_flags(self, post=None):
\r
43 def can_comment(self, post):
\r
46 def can_like_comment(self, comment):
\r
49 def can_edit_comment(self, comment):
\r
52 def can_delete_comment(self, comment):
\r
55 def can_accept_answer(self, answer):
\r
58 def can_edit_post(self, post):
\r
61 def can_retag_questions(self):
\r
64 def can_close_question(self, question):
\r
67 def can_reopen_question(self, question):
\r
70 def can_delete_post(self, post):
\r
73 def can_upload_files(self):
\r
76 class User(BaseModel, DjangoUser):
\r
77 is_approved = models.BooleanField(default=False)
\r
78 email_isvalid = models.BooleanField(default=False)
\r
79 email_key = models.CharField(max_length=32, null=True)
\r
80 reputation = models.PositiveIntegerField(default=1)
\r
82 gold = models.SmallIntegerField(default=0)
\r
83 silver = models.SmallIntegerField(default=0)
\r
84 bronze = models.SmallIntegerField(default=0)
\r
86 questions_per_page = models.SmallIntegerField(choices=QUESTIONS_PER_PAGE_CHOICES, default=10)
\r
87 hide_ignored_questions = models.BooleanField(default=False)
\r
89 last_seen = models.DateTimeField(default=datetime.datetime.now)
\r
90 real_name = models.CharField(max_length=100, blank=True)
\r
91 website = models.URLField(max_length=200, blank=True)
\r
92 location = models.CharField(max_length=100, blank=True)
\r
93 date_of_birth = models.DateField(null=True, blank=True)
\r
94 about = models.TextField(blank=True)
\r
96 objects = UserManager()
\r
100 return hashlib.md5(self.email).hexdigest()
\r
102 def save(self, *args, **kwargs):
\r
103 if self.reputation < 0:
\r
104 self.reputation = 1
\r
106 super(User, self).save(*args, **kwargs)
\r
108 def get_absolute_url(self):
\r
109 return self.get_profile_url()
\r
111 def get_messages(self):
\r
113 for m in self.message_set.all():
\r
114 messages.append(m.message)
\r
117 def delete_messages(self):
\r
118 self.message_set.all().delete()
\r
120 def get_profile_url(self):
\r
121 """Returns the URL for this User's profile."""
\r
122 return "/%s%d/%s" % (_('users/'), self.id, slugify(self.username))
\r
124 def get_profile_link(self):
\r
125 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(),self.username)
\r
126 logging.debug('in get profile link %s' % profile_link)
\r
127 return mark_safe(profile_link)
\r
129 def get_vote_count_today(self):
\r
130 today = datetime.date.today()
\r
131 return self.votes.filter(voted_at__range=(today - datetime.timedelta(days=1), today)).count()
\r
133 def get_up_vote_count(self):
\r
134 return self.votes.filter(vote=1).count()
\r
136 def get_down_vote_count(self):
\r
137 return self.votes.filter(vote=-1).count()
\r
139 def get_reputation_by_upvoted_today(self):
\r
140 today = datetime.datetime.now()
\r
141 sum = self.reputes.filter(
\r
142 models.Q(reputation_type=TYPE_REPUTATION_GAIN_BY_UPVOTED) |
\r
143 models.Q(reputation_type=TYPE_REPUTATION_LOST_BY_UPVOTE_CANCELED),
\r
144 reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(models.Sum('value'))
\r
146 if sum.get('value__sum', None) is not None: return sum['value__sum']
\r
149 def get_flagged_items_count_today(self):
\r
150 today = datetime.date.today()
\r
151 return self.flaggeditems.filter(flagged_at__range=(today - datetime.timedelta(days=1), today)).count()
\r
153 def get_visible_answers(self, question):
\r
154 if self.is_superuser:
\r
155 return question.answers
\r
157 return question.answers.filter(models.Q(deleted=False) | models.Q(deleted_by=self))
\r
159 def can_view_deleted_post(self, post):
\r
160 return self.is_superuser or post.author == self
\r
162 def can_vote_up(self):
\r
163 return self.reputation >= int(settings.REP_TO_VOTE_UP) or self.is_superuser
\r
165 def can_vote_down(self):
\r
166 return self.reputation >= int(settings.REP_TO_VOTE_DOWN) or self.is_superuser
\r
168 def can_flag_offensive(self, post=None):
\r
169 if post is not None and post.author == self:
\r
171 return self.is_superuser or self.reputation >= int(settings.REP_TO_FLAG)
\r
173 def can_view_offensive_flags(self, post=None):
\r
174 if post is not None and post.author == self:
\r
176 return self.is_superuser or self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
\r
178 def can_comment(self, post):
\r
179 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
\r
180 ) or self.is_superuser or (post.__class__.__name__ == "Answer" and self == post.question.author)
\r
182 def can_like_comment(self, comment):
\r
183 return self != comment.user and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT) or self.is_superuser)
\r
185 def can_edit_comment(self, comment):
\r
186 return (comment.user == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
\r
187 ) or self.is_superuser
\r
189 def can_delete_comment(self, comment):
\r
190 return self == comment.user or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS) or self.is_superuser
\r
192 def can_accept_answer(self, answer):
\r
193 return self.is_superuser or self == answer.question.author
\r
195 def can_edit_post(self, post):
\r
196 return self.is_superuser or self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
\r
197 ) or (post.wiki and self.reputation >= int(settings.REP_TO_EDIT_WIKI))
\r
199 def can_retag_questions(self):
\r
200 return self.reputation >= int(settings.REP_TO_RETAG)
\r
202 def can_close_question(self, question):
\r
203 return self.is_superuser or (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
\r
204 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
\r
206 def can_reopen_question(self, question):
\r
207 return self.is_superuser or (self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN)
\r
209 def can_delete_post(self, post):
\r
210 return self.is_superuser or (self == post.author and (post.__class__.__name__ == "Answer" or
\r
211 not post.answers.filter(~Q(author=self)).count()))
\r
213 def can_upload_files(self):
\r
214 return self.is_superuser or self.reputation >= int(settings.REP_TO_UPLOAD)
\r
217 app_label = 'forum'
\r
219 class Activity(GenericContent):
\r
221 We keep some history data for user activities
\r
223 user = models.ForeignKey(User)
\r
224 activity_type = models.SmallIntegerField(choices=TYPE_ACTIVITY)
\r
225 active_at = models.DateTimeField(default=datetime.datetime.now)
\r
226 is_auditted = models.BooleanField(default=False)
\r
229 app_label = 'forum'
\r
230 db_table = u'activity'
\r
232 def __unicode__(self):
\r
233 return u'[%s] was active at %s' % (self.user.username, self.active_at)
\r
235 def save(self, *args, **kwargs):
\r
236 super(Activity, self).save(*args, **kwargs)
\r
238 activity_record.send(sender=self.activity_type, instance=self)
\r
242 if self.activity_type in (const.TYPE_ACTIVITY_ANSWER, const.TYPE_ACTIVITY_ASK_QUESTION,
\r
243 const.TYPE_ACTIVITY_MARK_ANSWER):
\r
244 return self.content_object
\r
246 if self.activity_type in (const.TYPE_ACTIVITY_COMMENT_QUESTION, const.TYPE_ACTIVITY_COMMENT_ANSWER):
\r
247 return self.content_object.parent.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