]> git.openstreetmap.org Git - osqa.git/blob - forum/views/commands.py
fix in flag and delete commands, and added the possibility for admins and post author...
[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, id, vote_type):
66     post = get_object_or_404(Node, 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, node=post, vote=vote_score)
98         vote.save()
99
100     response = {
101         'commands': {
102             'update_post_score': [id, vote.vote * (vote_type == 'none' and -1 or 1)],
103             'update_user_post_vote': [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, id):
117     post = get_object_or_404(Node, 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.flaggeditems.get(user=user)
136         raise CannotDoubleActionException(_('flag'))
137     except ObjectDoesNotExist:
138         flag = FlaggedItem(user=user, content_object=post)
139         flag.save()
140
141     return {}
142         
143 @command
144 def like_comment(request, id):
145     comment = get_object_or_404(Comment, id=id)
146     user = request.user
147
148     if not user.is_authenticated():
149         raise AnonymousNotAllowedException(_('like comments'))
150
151     if user == comment.user:
152         raise CannotDoOnOwnException(_('like'))
153
154     if not user.can_like_comment(comment):
155         raise NotEnoughRepPointsException( _('like comments'))    
156
157     try:
158         like = LikedComment.active.get(comment=comment, user=user)
159         like.cancel()
160         likes = False
161     except ObjectDoesNotExist:
162         like = LikedComment(comment=comment, user=user)
163         like.save()
164         likes = True
165
166     return {
167         'commands': {
168             'update_comment_score': [comment.id, likes and 1 or -1],
169             'update_likes_comment_mark': [comment.id, likes and 'on' or 'off']
170         }
171     }
172
173 @command
174 def delete_comment(request, id):
175     comment = get_object_or_404(Comment, id=id)
176     user = request.user
177
178     if not user.is_authenticated():
179         raise AnonymousNotAllowedException(_('delete comments'))
180
181     if not user.can_delete_comment(comment):
182         raise NotEnoughRepPointsException( _('delete comments'))
183
184     comment.mark_deleted(user)
185
186     return {
187         'commands': {
188             'remove_comment': [comment.id],
189         }
190     }
191
192 @command
193 def mark_favorite(request, id):
194     question = get_object_or_404(Question, id=id)
195
196     if not request.user.is_authenticated():
197         raise AnonymousNotAllowedException(_('mark a question as favorite'))
198
199     try:
200         favorite = FavoriteQuestion.objects.get(question=question, user=request.user)
201         favorite.delete()
202         added = False
203     except ObjectDoesNotExist:
204         favorite = FavoriteQuestion(question=question, user=request.user)
205         favorite.save()
206         added = True
207
208     return {
209         'commands': {
210             'update_favorite_count': [added and 1 or -1],
211             'update_favorite_mark': [added and 'on' or 'off']
212         }
213     }
214
215 @command
216 def comment(request, id):
217     post = get_object_or_404(Node, id=id)
218     user = request.user
219
220     if not user.is_authenticated():
221         raise AnonymousNotAllowedException(_('comment'))
222
223     if not request.method == 'POST':
224         raise Exception(_("Invalid request"))
225
226     if 'id' in request.POST:
227         comment = get_object_or_404(Comment, id=request.POST['id'])
228
229         if not user.can_edit_comment(comment):
230             raise NotEnoughRepPointsException( _('edit comments'))
231     else:
232         if not user.can_comment(post):
233             raise NotEnoughRepPointsException( _('comment'))
234
235         comment = Comment(user=user, node=post)
236
237     comment_text = request.POST.get('comment', '').strip()
238
239     if not len(comment_text):
240         raise Exception(_("Comment is empty"))
241
242     comment.comment=comment_text
243     comment.save()
244
245     if comment._is_new:
246         return {
247             'commands': {
248                 'insert_comment': [
249                     id, comment.id, comment_text, user.username, user.get_profile_url(), reverse('delete_comment', kwargs={'id': comment.id})
250                 ]
251             }
252         }
253     else:
254         return {
255             'commands': {
256                 'update_comment': [comment.id, comment.comment]
257             }
258         }
259
260
261 @command
262 def accept_answer(request, id):
263     user = request.user
264
265     if not user.is_authenticated():
266         raise AnonymousNotAllowedException(_('accept answers'))
267
268     answer = get_object_or_404(Answer, id=id)
269     question = answer.question
270
271     if not user.can_accept_answer(answer):
272         raise Exception(_("Sorry but only the question author can accept an answer"))
273
274     commands = {}
275
276     if answer.accepted:
277         answer.unmark_accepted()
278         commands['unmark_accepted'] = [answer.id]
279     else:
280         try:
281             accepted = question.answers.get(accepted=True)
282             accepted.unmark_accepted()
283             commands['unmark_accepted'] = [accepted.id]
284         except:
285             #import sys, traceback
286             #traceback.print_exc(file=sys.stdout)
287             pass
288
289         answer.mark_accepted(user)
290         commands['mark_accepted'] = [answer.id]
291
292     return {'commands': commands}
293
294 @command    
295 def delete_post(request, id):
296     post = get_object_or_404(Node, id=id)
297     user = request.user
298
299     if not user.is_authenticated():
300         raise AnonymousNotAllowedException(_('delete posts'))
301
302     if not (user.can_delete_post(post)):
303         raise NotEnoughRepPointsException(_('delete posts'))
304
305     post.mark_deleted(user)
306
307     return {
308         'commands': {
309                 'mark_deleted': [post.node_type, id]
310             }
311     }
312
313 @command
314 def subscribe(request, id):
315     question = get_object_or_404(Question, id=id)
316
317     try:
318         subscription = QuestionSubscription.objects.get(question=question, user=request.user)
319         subscription.delete()
320         subscribed = False
321     except:
322         subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
323         subscription.save()
324         subscribed = True
325
326     return {
327         'commands': {
328                 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
329                 'set_subscription_status': ['']
330             }
331     }
332
333 #internally grouped views - used by the tagging system
334 @ajax_login_required
335 def mark_tag(request, tag=None, **kwargs):#tagging system
336     action = kwargs['action']
337     ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
338     if action == 'remove':
339         logging.debug('deleting tag %s' % tag)
340         ts.delete()
341     else:
342         reason = kwargs['reason']
343         if len(ts) == 0:
344             try:
345                 t = Tag.objects.get(name=tag)
346                 mt = MarkedTag(user=request.user, reason=reason, tag=t)
347                 mt.save()
348             except:
349                 pass
350         else:
351             ts.update(reason=reason)
352     return HttpResponse(simplejson.dumps(''), mimetype="application/json")
353
354 @ajax_login_required
355 def ajax_toggle_ignored_questions(request):#ajax tagging and tag-filtering system
356     if request.user.hide_ignored_questions:
357         new_hide_setting = False
358     else:
359         new_hide_setting = True
360     request.user.hide_ignored_questions = new_hide_setting
361     request.user.save()
362
363 @ajax_method
364 def ajax_command(request):#refactor? view processing ajax commands - note "vote" and view others do it too
365     if 'command' not in request.POST:
366         return HttpResponseForbidden(mimetype="application/json")
367     if request.POST['command'] == 'toggle-ignored-questions':
368         return ajax_toggle_ignored_questions(request)
369
370 @login_required
371 def close(request, id):#close question
372     """view to initiate and process 
373     question close
374     """
375     question = get_object_or_404(Question, id=id)
376     if not request.user.can_close_question(question):
377         return HttpResponseForbidden()
378     if request.method == 'POST':
379         form = CloseForm(request.POST)
380         if form.is_valid():
381             reason = form.cleaned_data['reason']
382             question.closed = True
383             question.closed_by = request.user
384             question.closed_at = datetime.datetime.now()
385             question.close_reason = reason
386             question.save()
387         return HttpResponseRedirect(question.get_absolute_url())
388     else:
389         form = CloseForm()
390         return render_to_response('close.html', {
391             'form' : form,
392             'question' : question,
393             }, context_instance=RequestContext(request))
394
395 @login_required
396 def reopen(request, id):#re-open question
397     """view to initiate and process 
398     question close
399     """
400     question = get_object_or_404(Question, id=id)
401     # open question
402     if not request.user.can_reopen_question(question):
403         return HttpResponseForbidden()
404     if request.method == 'POST' :
405         Question.objects.filter(id=question.id).update(closed=False,
406             closed_by=None, closed_at=None, close_reason=None)
407         return HttpResponseRedirect(question.get_absolute_url())
408     else:
409         return render_to_response('reopen.html', {
410             'question' : question,
411             }, context_instance=RequestContext(request))
412
413 #osqa-user communication system
414 def read_message(request):#marks message a read
415     if request.method == "POST":
416         if request.POST['formdata'] == 'required':
417             request.session['message_silent'] = 1
418             if request.user.is_authenticated():
419                 request.user.delete_messages()
420     return HttpResponse('')
421
422