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