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