]> git.openstreetmap.org Git - osqa.git/blob - forum/views/commands.py
456199d8c1c05d75e996c20e42df288796631e46
[osqa.git] / forum / views / commands.py
1 import datetime
2 from forum import settings
3 from django.core.exceptions import ObjectDoesNotExist
4 from django.utils import simplejson
5 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, Http404
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.models.node import NodeMetaClass
11 from forum.actions import *
12 from django.core.urlresolvers import reverse
13 from django.contrib.auth.decorators import login_required
14 from forum.utils.decorators import ajax_method, ajax_login_required
15 from forum.modules.decorators import decoratable
16 from decorators import command, CommandException
17 from forum import settings
18 import logging
19
20 class NotEnoughRepPointsException(CommandException):
21     def __init__(self, action):
22         super(NotEnoughRepPointsException, self).__init__(
23             _("""Sorry, but you don't have enough reputation points to %(action)s.<br />Please check the <a href='%(faq_url)s'>faq</a>""") % {'action': action, 'faq_url': reverse('faq')}
24         )
25
26 class CannotDoOnOwnException(CommandException):
27     def __init__(self, action):
28         super(CannotDoOnOwnException, self).__init__(
29             _("""Sorry but you cannot %(action)s your own post.<br />Please check the <a href='%(faq_url)s'>faq</a>""") % {'action': action, 'faq_url': reverse('faq')}
30         )
31
32 class AnonymousNotAllowedException(CommandException):
33     def __init__(self, action):
34         super(AnonymousNotAllowedException, self).__init__(
35             _("""Sorry but anonymous users cannot %(action)s.<br />Please login or create an account <a href='%(signin_url)s'>here</a>.""") % {'action': action, 'signin_url': reverse('auth_signin')}
36         )
37
38 class NotEnoughLeftException(CommandException):
39     def __init__(self, action, limit):
40         super(NotEnoughLeftException, self).__init__(
41             _("""Sorry, but you don't have enough %(action)s left for today..<br />The limit is %(limit)s per day..<br />Please check the <a href='%(faq_url)s'>faq</a>""") % {'action': action, 'limit': limit, 'faq_url': reverse('faq')}
42         )
43
44 class CannotDoubleActionException(CommandException):
45     def __init__(self, action):
46         super(CannotDoubleActionException, self).__init__(
47             _("""Sorry, but you cannot %(action)s twice the same post.<br />Please check the <a href='%(faq_url)s'>faq</a>""") % {'action': action, 'faq_url': reverse('faq')}
48         )
49
50
51 @command
52 def vote_post(request, id, vote_type):
53     post = get_object_or_404(Node, id=id).leaf
54     user = request.user
55
56     if not user.is_authenticated():
57         raise AnonymousNotAllowedException(_('vote'))
58
59     if user == post.author:
60         raise CannotDoOnOwnException(_('vote'))
61
62     if not (vote_type == 'up' and user.can_vote_up() or user.can_vote_down()):
63         raise NotEnoughRepPointsException(vote_type == 'up' and _('upvote') or _('downvote'))
64
65     user_vote_count_today = user.get_vote_count_today()
66
67     if user_vote_count_today >= int(settings.MAX_VOTES_PER_DAY):
68         raise NotEnoughLeftException(_('votes'), str(settings.MAX_VOTES_PER_DAY))
69
70     new_vote_cls = (vote_type == 'up') and VoteUpAction or VoteDownAction
71     score_inc = 0
72
73     old_vote = VoteAction.get_action_for(node=post, user=user)
74
75     if old_vote:
76         if old_vote.action_date < datetime.datetime.now() - datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)):
77             raise CommandException(
78                     _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote") %
79                     {'ndays': int(settings.DENY_UNVOTE_DAYS), 'tdays': ungettext('day', 'days', int(settings.DENY_UNVOTE_DAYS))}
80             )
81
82         old_vote.cancel(ip=request.META['REMOTE_ADDR'])
83         score_inc += (old_vote.__class__ == VoteDownAction) and 1 or -1
84
85     if old_vote.__class__ != new_vote_cls:
86         new_vote_cls(user=user, node=post, ip=request.META['REMOTE_ADDR']).save()
87         score_inc += (new_vote_cls == VoteUpAction) and 1 or -1
88     else:
89         vote_type = "none"
90
91     response = {
92         'commands': {
93             'update_post_score': [id, score_inc],
94             'update_user_post_vote': [id, vote_type]
95         }
96     }
97
98     votes_left = (int(settings.MAX_VOTES_PER_DAY) - user_vote_count_today) + (vote_type == 'none' and -1 or 1)
99
100     if int(settings.START_WARN_VOTES_LEFT) >= votes_left:
101         response['message'] = _("You have %(nvotes)s %(tvotes)s left today.") % \
102                     {'nvotes': votes_left, 'tvotes': ungettext('vote', 'votes', votes_left)}
103
104     return response
105
106 @command
107 def flag_post(request, id):
108     if not request.POST:
109         return render_to_response('node/report.html', {'types': settings.FLAG_TYPES})
110
111     post = get_object_or_404(Node, id=id)
112     user = request.user
113
114     if not user.is_authenticated():
115         raise AnonymousNotAllowedException(_('flag posts'))
116
117     if user == post.author:
118         raise CannotDoOnOwnException(_('flag'))
119
120     if not (user.can_flag_offensive(post)):
121         raise NotEnoughRepPointsException(_('flag posts'))
122
123     user_flag_count_today = user.get_flagged_items_count_today()
124
125     if user_flag_count_today >= int(settings.MAX_FLAGS_PER_DAY):
126         raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))
127
128     try:
129         current = FlagAction.objects.get(canceled=False, user=user, node=post)
130         raise CommandException(_("You already flagged this post with the following reason: %(reason)s") % {'reason': current.extra})
131     except ObjectDoesNotExist:
132         reason = request.POST.get('prompt', '').strip()
133
134         if not len(reason):
135             raise CommandException(_("Reason is empty"))
136
137         FlagAction(user=user, node=post, extra=reason, ip=request.META['REMOTE_ADDR']).save()
138
139     return {'message': _("Thank you for your report. A moderator will review your submission shortly.")}
140         
141 @command
142 def like_comment(request, id):
143     comment = get_object_or_404(Comment, id=id)
144     user = request.user
145
146     if not user.is_authenticated():
147         raise AnonymousNotAllowedException(_('like comments'))
148
149     if user == comment.user:
150         raise CannotDoOnOwnException(_('like'))
151
152     if not user.can_like_comment(comment):
153         raise NotEnoughRepPointsException( _('like comments'))    
154
155     like = VoteAction.get_action_for(node=comment, user=user)
156
157     if like:
158         like.cancel(ip=request.META['REMOTE_ADDR'])
159         likes = False
160     else:
161         VoteUpCommentAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
162         likes = True
163
164     return {
165         'commands': {
166             'update_post_score': [comment.id, likes and 1 or -1],
167             'update_user_post_vote': [comment.id, likes and 'up' or 'none']
168         }
169     }
170
171 @command
172 def delete_comment(request, id):
173     comment = get_object_or_404(Comment, id=id)
174     user = request.user
175
176     if not user.is_authenticated():
177         raise AnonymousNotAllowedException(_('delete comments'))
178
179     if not user.can_delete_comment(comment):
180         raise NotEnoughRepPointsException( _('delete comments'))
181
182     if not comment.nis.deleted:
183         DeleteAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
184
185     return {
186         'commands': {
187             'remove_comment': [comment.id],
188         }
189     }
190
191 @command
192 def mark_favorite(request, id):
193     question = get_object_or_404(Question, id=id)
194
195     if not request.user.is_authenticated():
196         raise AnonymousNotAllowedException(_('mark a question as favorite'))
197
198     try:
199         favorite = FavoriteAction.objects.get(canceled=False, node=question, user=request.user)
200         favorite.cancel(ip=request.META['REMOTE_ADDR'])
201         added = False
202     except ObjectDoesNotExist:
203         FavoriteAction(node=question, user=request.user, ip=request.META['REMOTE_ADDR']).save()
204         added = True
205
206     return {
207         'commands': {
208             'update_favorite_count': [added and 1 or -1],
209             'update_favorite_mark': [added and 'on' or 'off']
210         }
211     }
212
213 @decoratable
214 @command
215 def comment(request, id):
216     post = get_object_or_404(Node, id=id)
217     user = request.user
218
219     if not user.is_authenticated():
220         raise AnonymousNotAllowedException(_('comment'))
221
222     if not request.method == 'POST':
223         raise CommandException(_("Invalid request"))
224
225     comment_text = request.POST.get('comment', '').strip()
226
227     if not len(comment_text):
228         raise CommandException(_("Comment is empty"))
229
230     if len(comment_text) < settings.FORM_MIN_COMMENT_BODY:
231         raise CommandException(_("At least %d characters required on comment body.") % settings.FORM_MIN_COMMENT_BODY)
232
233     if len(comment_text) > settings.FORM_MAX_COMMENT_BODY:
234         raise CommandException(_("No more than %d characters on comment body.") % settings.FORM_MAX_COMMENT_BODY)
235
236     if 'id' in request.POST:
237         comment = get_object_or_404(Comment, id=request.POST['id'])
238
239         if not user.can_edit_comment(comment):
240             raise NotEnoughRepPointsException( _('edit comments'))
241
242         comment = ReviseAction(user=user, node=comment, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text)).node
243     else:
244         if not user.can_comment(post):
245             raise NotEnoughRepPointsException( _('comment'))
246
247         comment = CommentAction(user=user, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text, parent=post)).node
248
249     if comment.active_revision.revision == 1:
250         return {
251             'commands': {
252                 'insert_comment': [
253                     id, comment.id, comment.comment, user.username, user.get_profile_url(),
254                         reverse('delete_comment', kwargs={'id': comment.id}), reverse('node_markdown', kwargs={'id': comment.id})
255                 ]
256             }
257         }
258     else:
259         return {
260             'commands': {
261                 'update_comment': [comment.id, comment.comment]
262             }
263         }
264
265 @command
266 def node_markdown(request, id):
267     user = request.user
268
269     if not user.is_authenticated():
270         raise AnonymousNotAllowedException(_('accept answers'))
271
272     node = get_object_or_404(Node, id=id)
273     return HttpResponse(node.body, mimetype="text/plain")
274
275
276 @command
277 def accept_answer(request, id):
278     user = request.user
279
280     if not user.is_authenticated():
281         raise AnonymousNotAllowedException(_('accept answers'))
282
283     answer = get_object_or_404(Answer, id=id)
284     question = answer.question
285
286     if not user.can_accept_answer(answer):
287         raise CommandException(_("Sorry but only the question author can accept an answer"))
288
289     commands = {}
290
291     if answer.nis.accepted:
292         answer.nstate.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
293         commands['unmark_accepted'] = [answer.id]
294     else:
295         if question.answer_accepted:
296             accepted = question.accepted_answer
297             accepted.nstate.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
298             commands['unmark_accepted'] = [accepted.id]
299
300         AcceptAnswerAction(node=answer, user=user, ip=request.META['REMOTE_ADDR']).save()
301         commands['mark_accepted'] = [answer.id]
302
303     return {'commands': commands}
304
305 @command    
306 def delete_post(request, id):
307     post = get_object_or_404(Node, id=id)
308     user = request.user
309
310     if not user.is_authenticated():
311         raise AnonymousNotAllowedException(_('delete posts'))
312
313     if not (user.can_delete_post(post)):
314         raise NotEnoughRepPointsException(_('delete posts'))
315
316     ret = {'commands': {}}
317
318     if post.nis.deleted:
319         post.nstate.deleted.cancel(user, ip=request.META['REMOTE_ADDR'])
320         ret['commands']['unmark_deleted'] = [post.node_type, id]
321     else:
322         DeleteAction(node=post, user=user, ip=request.META['REMOTE_ADDR']).save()
323
324         ret['commands']['mark_deleted'] = [post.node_type, id]
325
326     return ret
327
328 @command
329 def close(request, id, close):
330     if close and not request.POST:
331         return render_to_response('node/report.html', {'types': settings.CLOSE_TYPES})
332
333     question = get_object_or_404(Question, id=id)
334     user = request.user
335
336     if not user.is_authenticated():
337         raise AnonymousNotAllowedException(_('close questions'))
338
339     if question.nis.closed:
340         if not user.can_reopen_question(question):
341             raise NotEnoughRepPointsException(_('reopen questions'))
342
343         question.nstate.closed.cancel(user, ip=request.META['REMOTE_ADDR'])
344     else:
345         if not request.user.can_close_question(question):
346             raise NotEnoughRepPointsException(_('close questions'))
347
348         reason = request.POST.get('prompt', '').strip()
349
350         if not len(reason):
351             raise CommandException(_("Reason is empty"))
352
353         CloseAction(node=question, user=user, extra=reason, ip=request.META['REMOTE_ADDR']).save()
354
355     return {
356         'commands': {
357             'refresh_page': []
358         }
359     }
360
361 @command
362 def wikify(request, id):
363     node = get_object_or_404(Node, id=id)
364     user = request.user
365
366     if not user.is_authenticated():
367         raise AnonymousNotAllowedException(_('mark posts as community wiki'))
368
369     if node.nis.wiki:
370         if not user.can_cancel_wiki(node):
371             raise NotEnoughRepPointsException(_('cancel a community wiki post'))
372
373         if node.nstate.wiki.action_type == "wikify":
374             node.nstate.wiki.cancel()
375         else:
376             node.nstate.wiki = None
377     else:
378         if not user.can_wikify(node):
379             raise NotEnoughRepPointsException(_('mark posts as community wiki'))
380
381         WikifyAction(node=node, user=user, ip=request.META['REMOTE_ADDR']).save()
382
383     return {
384         'commands': {
385             'refresh_page': []
386         }
387     }
388
389 @command
390 def convert_to_comment(request, id):
391     user = request.user
392     answer = get_object_or_404(Answer, id=id)
393     question = answer.question
394
395     if not request.POST:
396         description = lambda a: _("Answer by %(uname)s: %(snippet)s...") % {'uname': a.author.username, 'snippet': a.summary[:10]}
397         nodes = [(question.id, _("Question"))]
398         [nodes.append((a.id, description(a))) for a in question.answers.filter_state(deleted=False).exclude(id=answer.id)]
399
400         return render_to_response('node/convert_to_comment.html', {'answer': answer, 'nodes': nodes})
401
402     if not user.is_authenticated():
403         raise AnonymousNotAllowedException(_("convert answers to comments"))
404
405     if not user.can_convert_to_comment(answer):
406         raise NotEnoughRepPointsException(_("convert answers to comments"))
407
408     try:
409         new_parent = Node.objects.get(id=request.POST.get('under', None))
410     except:
411         raise CommandException(_("That is an invalid post to put the comment under"))
412
413     if not (new_parent == question or (new_parent.node_type == 'answer' and new_parent.parent == question)):
414         raise CommandException(_("That is an invalid post to put the comment under"))
415
416     AnswerToCommentAction(user=user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(new_parent=new_parent))
417
418     return {
419         'commands': {
420             'refresh_page': []
421         }
422     }
423
424 @command
425 def subscribe(request, id):
426     question = get_object_or_404(Question, id=id)
427
428     try:
429         subscription = QuestionSubscription.objects.get(question=question, user=request.user)
430         subscription.delete()
431         subscribed = False
432     except:
433         subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
434         subscription.save()
435         subscribed = True
436
437     return {
438         'commands': {
439                 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
440                 'set_subscription_status': ['']
441             }
442     }
443
444 #internally grouped views - used by the tagging system
445 @ajax_login_required
446 def mark_tag(request, tag=None, **kwargs):#tagging system
447     action = kwargs['action']
448     ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
449     if action == 'remove':
450         logging.debug('deleting tag %s' % tag)
451         ts.delete()
452     else:
453         reason = kwargs['reason']
454         if len(ts) == 0:
455             try:
456                 t = Tag.objects.get(name=tag)
457                 mt = MarkedTag(user=request.user, reason=reason, tag=t)
458                 mt.save()
459             except:
460                 pass
461         else:
462             ts.update(reason=reason)
463     return HttpResponse(simplejson.dumps(''), mimetype="application/json")
464
465 def matching_tags(request):
466     if len(request.GET['q']) == 0:
467        raise CommandException(_("Invalid request"))
468
469     possible_tags = Tag.active.filter(name__istartswith = request.GET['q'])
470     tag_output = ''
471     for tag in possible_tags:
472         tag_output += (tag.name + "|" + tag.name + "." + tag.used_count.__str__() + "\n")
473         
474     return HttpResponse(tag_output, mimetype="text/plain")
475
476 def related_questions(request):
477     if request.POST and request.POST.get('title', None):
478         return HttpResponse(simplejson.dumps(
479                 [dict(title=q.title, url=q.get_absolute_url(), score=q.score, summary=q.summary)
480                  for q in Question.objects.search(request.POST['title']).filter_state(deleted=False)[0:10]]), mimetype="application/json")
481     else:
482         raise Http404()
483
484
485
486
487
488
489