]> git.openstreetmap.org Git - osqa.git/blob - forum/views/commands.py
2fb2be4223d3005a44abf610363405ab8dc12896
[osqa.git] / forum / views / commands.py
1 import datetime
2 from django.conf import settings
3 from django.core.exceptions import ObjectDoesNotExist
4 from django.utils import simplejson
5 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
6 from django.shortcuts import get_object_or_404, render_to_response
7 from django.utils.translation import ungettext, ugettext as _
8 from django.template import RequestContext
9 from forum.models import *
10 from forum.forms import CloseForm
11 from django.core.urlresolvers import reverse
12 from django.contrib.auth.decorators import login_required
13 from forum.utils.decorators import ajax_method, ajax_login_required
14 from decorators import command
15 import logging
16
17 class NotEnoughRepPointsException(Exception):
18     def __init__(self, action):
19         super(NotEnoughRepPointsException, self).__init__(
20             _("""
21             Sorry, but you don't have enough reputation points to %(action)s.<br />
22             Please check the <a href'%(faq_url)s'>faq</a>
23             """ % {'action': action, 'faq_url': reverse('faq')})
24         )
25
26 class CannotDoOnOwnException(Exception):
27     def __init__(self, action):
28         super(CannotDoOnOwnException, self).__init__(
29             _("""
30             Sorry but you cannot %(action)s your own post.<br />
31             Please check the <a href'%(faq_url)s'>faq</a>
32             """ % {'action': action, 'faq_url': reverse('faq')})
33         )
34
35 class AnonymousNotAllowedException(Exception):
36     def __init__(self, action):
37         super(AnonymousNotAllowedException, self).__init__(
38             _("""
39             Sorry but anonymous users cannot %(action)s.<br />
40             Please login or create an account <a href'%(signin_url)s'>here</a>.
41             """ % {'action': action, 'signin_url': reverse('auth_signin')})
42         )
43
44 class NotEnoughLeftException(Exception):
45     def __init__(self, action, limit):
46         super(NotEnoughRepPointsException, self).__init__(
47             _("""
48             Sorry, but you don't have enough %(action)s left for today..<br />
49             The limit is %(limit)s per day..<br />
50             Please check the <a href'%(faq_url)s'>faq</a>
51             """ % {'action': action, 'limit': limit, 'faq_url': reverse('faq')})
52         )
53
54 class CannotDoubleActionException(Exception):
55     def __init__(self, action):
56         super(CannotDoubleActionException, self).__init__(
57             _("""
58             Sorry, but you cannot %(action)s twice the same post.<br />
59             Please check the <a href'%(faq_url)s'>faq</a>
60             """ % {'action': action, 'faq_url': reverse('faq')})
61         )
62
63
64 @command
65 def vote_post(request, post_type, id, vote_type):
66     post = get_object_or_404(post_type == "question" and Question or Answer, id=id)
67     vote_score = vote_type == 'up' and 1 or -1
68     user = request.user
69
70     if not user.is_authenticated():
71         raise AnonymousNotAllowedException(_('vote'))
72
73     if user == post.author:
74         raise CannotDoOnOwnException(_('vote'))
75
76     if not (vote_type == 'up' and user.can_vote_up() or user.can_vote_down()):
77         raise NotEnoughRepPointsException(vote_type == 'up' and _('upvote') or _('downvote'))
78
79     user_vote_count_today = user.get_vote_count_today()
80
81     if user_vote_count_today >= int(settings.MAX_VOTES_PER_DAY):
82         raise NotEnoughLeftException(_('votes'), str(settings.MAX_VOTES_PER_DAY))
83
84     try:
85         vote = post.votes.get(canceled=False, user=user)
86
87         if vote.voted_at < datetime.datetime.now() - datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)):
88             raise Exception(
89                     _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote") %
90                     {'ndays': int(settings.DENY_UNVOTE_DAYS), 'tdays': ungettext('day', 'days', int(settings.DENY_UNVOTE_DAYS))}
91             )
92
93         vote.cancel()
94         vote_type = 'none'
95     except ObjectDoesNotExist:
96         #there is no vote yet
97         vote = Vote(user=user, content_object=post, vote=vote_score)
98         vote.save()
99
100     response = {
101         'commands': {
102             'update_post_score': [post_type, id, vote.vote * (vote_type == 'none' and -1 or 1)],
103             'update_user_post_vote': [post_type, id, vote_type]
104         }
105     }
106
107     votes_left = int(settings.MAX_VOTES_PER_DAY) - user_vote_count_today + (vote_type == 'none' and -1 or 1)
108
109     if int(settings.START_WARN_VOTES_LEFT) >= votes_left:
110         response['message'] = _("You have %(nvotes) %(tvotes) left today.") % \
111                     {'nvotes': votes_left, 'tvotes': ungettext('vote', 'votes', votes_left)}
112
113     return response
114
115 @command
116 def flag_post(request, post_type, id):
117     post = get_object_or_404(post_type == "question" and Question or Answer, id=id)
118     user = request.user
119
120     if not user.is_authenticated():
121         raise AnonymousNotAllowedException(_('flag posts'))
122
123     if user == post.author:
124         raise CannotDoOnOwnException(_('flag'))
125
126     if not (user.can_flag_offensive(post)):
127         raise NotEnoughRepPointsException(_('flag posts'))
128
129     user_flag_count_today = user.get_flagged_items_count_today()
130
131     if user_flag_count_today >= int(settings.MAX_FLAGS_PER_DAY):
132         raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))
133
134     try:
135         post.flagged_items.get(user=user)
136         raise CannotDoubleActionException(_('flag'))
137     except ObjectDoesNotExist:
138         #there is no vote yet
139         flag = FlaggedItem(user=user, content_object=post)
140         flag.save()
141
142     response = {
143
144     }
145
146     return response
147         
148 @command
149 def like_comment(request, id):
150     comment = get_object_or_404(Comment, id=id)
151     user = request.user
152
153     if not user.is_authenticated():
154         raise AnonymousNotAllowedException(_('like comments'))
155
156     if user == comment.user:
157         raise CannotDoOnOwnException(_('like'))
158
159     if not user.can_like_comment(comment):
160         raise NotEnoughRepPointsException( _('like comments'))    
161
162     try:
163         like = LikedComment.active.get(comment=comment, user=user)
164         like.cancel()
165         likes = False
166     except ObjectDoesNotExist:
167         like = LikedComment(comment=comment, user=user)
168         like.save()
169         likes = True
170
171     return {
172         'commands': {
173             'update_comment_score': [comment.id, likes and 1 or -1],
174             'update_likes_comment_mark': [comment.id, likes and 'on' or 'off']
175         }
176     }
177
178 @command
179 def delete_comment(request, id):
180     comment = get_object_or_404(Comment, id=id)
181     user = request.user
182
183     if not user.is_authenticated():
184         raise AnonymousNotAllowedException(_('delete comments'))
185
186     if not user.can_delete_comment(comment):
187         raise NotEnoughRepPointsException( _('delete comments'))
188
189     comment.mark_deleted(user)
190
191     return {
192         'commands': {
193             'remove_comment': [comment.id],
194         }
195     }
196
197 @command
198 def mark_favorite(request, id):
199     question = get_object_or_404(Question, id=id)
200
201     if not request.user.is_authenticated():
202         raise AnonymousNotAllowedException(_('mark a question as favorite'))
203
204     try:
205         favorite = FavoriteQuestion.objects.get(question=question, user=request.user)
206         favorite.delete()
207         added = False
208     except ObjectDoesNotExist:
209         favorite = FavoriteQuestion(question=question, user=request.user)
210         favorite.save()
211         added = True
212
213     return {
214         'commands': {
215             'update_favorite_count': [added and 1 or -1],
216             'update_favorite_mark': [added and 'on' or 'off']
217         }
218     }
219
220 @command
221 def comment(request, post_type, id):
222     post = get_object_or_404(post_type == "question" and Question or Answer, id=id)
223     user = request.user
224
225     if not user.is_authenticated():
226         raise AnonymousNotAllowedException(_('comment'))
227
228     if not request.method == 'POST':
229         raise Exception(_("Invalid request"))
230
231     if 'id' in request.POST:
232         comment = get_object_or_404(Comment, id=request.POST['id'])
233
234         if not user.can_edit_comment(comment):
235             raise NotEnoughRepPointsException( _('edit comments'))
236     else:
237         if not user.can_comment(post):
238             raise NotEnoughRepPointsException( _('comment'))
239
240         comment = Comment(user=user, content_object=post)
241
242     comment_text = request.POST.get('comment', '').strip()
243
244     if not len(comment_text):
245         raise Exception(_("Comment is empty"))
246
247     comment.comment=comment_text
248     comment.save()
249
250     if comment._is_new:
251         return {
252             'commands': {
253                 'insert_comment': [
254                     post_type, id,
255                     comment.id, comment_text, user.username, user.get_profile_url(), reverse('delete_comment', kwargs={'id': comment.id})
256                 ]
257             }
258         }
259     else:
260         return {
261             'commands': {
262                 'update_comment': [comment.id, comment.comment]
263             }
264         }
265
266
267 @command
268 def accept_answer(request, id):
269     user = request.user
270
271     if not user.is_authenticated():
272         raise AnonymousNotAllowedException(_('accept answers'))
273
274     answer = get_object_or_404(Answer, id=id)
275     question = answer.question
276
277     if not user.can_accept_answer(answer):
278         raise Exception(_("Sorry but only the question author can accept an answer"))
279
280     commands = {}
281
282     if answer.accepted:
283         answer.unmark_accepted()
284         commands['unmark_accepted'] = [answer.id]
285     else:
286         try:
287             accepted = question.answers.get(accepted=True)
288             accepted.unmark_accepted()
289             commands['unmark_accepted'] = [accepted.id]
290         except:
291             pass
292
293         answer.mark_accepted(user)
294         commands['mark_accepted'] = [answer.id]
295
296     return {'commands': commands}
297
298 @command    
299 def delete_post(request, post_type, id):
300     post = get_object_or_404(post_type == "question" and Question or Answer, id=id)
301     user = request.user
302
303     if not user.is_authenticated():
304         raise AnonymousNotAllowedException(_('delete posts'))
305
306     if not (user.can_delete_post(post)):
307         raise NotEnoughRepPointsException(_('delete posts'))
308
309     post.mark_deleted(user)
310
311     return {
312         'commands': {
313                 'mark_deleted': [post_type, id]
314             }
315     }
316
317 @command
318 def subscribe(request, id):
319     question = get_object_or_404(Question, id=id)
320
321     try:
322         subscription = QuestionSubscription.objects.get(question=question, user=request.user)
323         subscription.delete()
324         subscribed = False
325     except:
326         subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
327         subscription.save()
328         subscribed = True
329
330     return {
331         'commands': {
332                 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
333                 'set_subscription_status': ['']
334             }
335     }
336
337 #internally grouped views - used by the tagging system
338 @ajax_login_required
339 def mark_tag(request, tag=None, **kwargs):#tagging system
340     action = kwargs['action']
341     ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
342     if action == 'remove':
343         logging.debug('deleting tag %s' % tag)
344         ts.delete()
345     else:
346         reason = kwargs['reason']
347         if len(ts) == 0:
348             try:
349                 t = Tag.objects.get(name=tag)
350                 mt = MarkedTag(user=request.user, reason=reason, tag=t)
351                 mt.save()
352             except:
353                 pass
354         else:
355             ts.update(reason=reason)
356     return HttpResponse(simplejson.dumps(''), mimetype="application/json")
357
358 @ajax_login_required
359 def ajax_toggle_ignored_questions(request):#ajax tagging and tag-filtering system
360     if request.user.hide_ignored_questions:
361         new_hide_setting = False
362     else:
363         new_hide_setting = True
364     request.user.hide_ignored_questions = new_hide_setting
365     request.user.save()
366
367 @ajax_method
368 def ajax_command(request):#refactor? view processing ajax commands - note "vote" and view others do it too
369     if 'command' not in request.POST:
370         return HttpResponseForbidden(mimetype="application/json")
371     if request.POST['command'] == 'toggle-ignored-questions':
372         return ajax_toggle_ignored_questions(request)
373
374 @login_required
375 def close(request, id):#close question
376     """view to initiate and process 
377     question close
378     """
379     question = get_object_or_404(Question, id=id)
380     if not request.user.can_close_question(question):
381         return HttpResponseForbidden()
382     if request.method == 'POST':
383         form = CloseForm(request.POST)
384         if form.is_valid():
385             reason = form.cleaned_data['reason']
386             question.closed = True
387             question.closed_by = request.user
388             question.closed_at = datetime.datetime.now()
389             question.close_reason = reason
390             question.save()
391         return HttpResponseRedirect(question.get_absolute_url())
392     else:
393         form = CloseForm()
394         return render_to_response('close.html', {
395             'form' : form,
396             'question' : question,
397             }, context_instance=RequestContext(request))
398
399 @login_required
400 def reopen(request, id):#re-open question
401     """view to initiate and process 
402     question close
403     """
404     question = get_object_or_404(Question, id=id)
405     # open question
406     if not request.user.can_reopen_question(question):
407         return HttpResponseForbidden()
408     if request.method == 'POST' :
409         Question.objects.filter(id=question.id).update(closed=False,
410             closed_by=None, closed_at=None, close_reason=None)
411         return HttpResponseRedirect(question.get_absolute_url())
412     else:
413         return render_to_response('reopen.html', {
414             'question' : question,
415             }, context_instance=RequestContext(request))
416
417 #osqa-user communication system
418 def read_message(request):#marks message a read
419     if request.method == "POST":
420         if request.POST['formdata'] == 'required':
421             request.session['message_silent'] = 1
422             if request.user.is_authenticated():
423                 request.user.delete_messages()
424     return HttpResponse('')
425
426