]> git.openstreetmap.org Git - osqa.git/blob - forum/views/commands.py
ALteration of the schema to a single content model. As a bonus there is a complete...
[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, 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, id):
222     post = get_object_or_404(Node, 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, node=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                     id, comment.id, comment_text, user.username, user.get_profile_url(), reverse('delete_comment', kwargs={'id': comment.id})
255                 ]
256             }
257         }
258     else:
259         return {
260             'commands': {
261                 'update_comment': [comment.id, comment.comment]
262             }
263         }
264
265
266 @command
267 def accept_answer(request, id):
268     user = request.user
269
270     if not user.is_authenticated():
271         raise AnonymousNotAllowedException(_('accept answers'))
272
273     answer = get_object_or_404(Answer, id=id)
274     question = answer.question
275
276     if not user.can_accept_answer(answer):
277         raise Exception(_("Sorry but only the question author can accept an answer"))
278
279     commands = {}
280
281     if answer.accepted:
282         answer.unmark_accepted()
283         commands['unmark_accepted'] = [answer.id]
284     else:
285         try:
286             accepted = question.answers.get(accepted=True)
287             accepted.unmark_accepted()
288             commands['unmark_accepted'] = [accepted.id]
289         except:
290             #import sys, traceback
291             #traceback.print_exc(file=sys.stdout)
292             pass
293
294         answer.mark_accepted(user)
295         commands['mark_accepted'] = [answer.id]
296
297     return {'commands': commands}
298
299 @command    
300 def delete_post(request, post_type, id):
301     post = get_object_or_404(post_type == "question" and Question or Answer, id=id)
302     user = request.user
303
304     if not user.is_authenticated():
305         raise AnonymousNotAllowedException(_('delete posts'))
306
307     if not (user.can_delete_post(post)):
308         raise NotEnoughRepPointsException(_('delete posts'))
309
310     post.mark_deleted(user)
311
312     return {
313         'commands': {
314                 'mark_deleted': [post_type, id]
315             }
316     }
317
318 @command
319 def subscribe(request, id):
320     question = get_object_or_404(Question, id=id)
321
322     try:
323         subscription = QuestionSubscription.objects.get(question=question, user=request.user)
324         subscription.delete()
325         subscribed = False
326     except:
327         subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
328         subscription.save()
329         subscribed = True
330
331     return {
332         'commands': {
333                 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
334                 'set_subscription_status': ['']
335             }
336     }
337
338 #internally grouped views - used by the tagging system
339 @ajax_login_required
340 def mark_tag(request, tag=None, **kwargs):#tagging system
341     action = kwargs['action']
342     ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
343     if action == 'remove':
344         logging.debug('deleting tag %s' % tag)
345         ts.delete()
346     else:
347         reason = kwargs['reason']
348         if len(ts) == 0:
349             try:
350                 t = Tag.objects.get(name=tag)
351                 mt = MarkedTag(user=request.user, reason=reason, tag=t)
352                 mt.save()
353             except:
354                 pass
355         else:
356             ts.update(reason=reason)
357     return HttpResponse(simplejson.dumps(''), mimetype="application/json")
358
359 @ajax_login_required
360 def ajax_toggle_ignored_questions(request):#ajax tagging and tag-filtering system
361     if request.user.hide_ignored_questions:
362         new_hide_setting = False
363     else:
364         new_hide_setting = True
365     request.user.hide_ignored_questions = new_hide_setting
366     request.user.save()
367
368 @ajax_method
369 def ajax_command(request):#refactor? view processing ajax commands - note "vote" and view others do it too
370     if 'command' not in request.POST:
371         return HttpResponseForbidden(mimetype="application/json")
372     if request.POST['command'] == 'toggle-ignored-questions':
373         return ajax_toggle_ignored_questions(request)
374
375 @login_required
376 def close(request, id):#close question
377     """view to initiate and process 
378     question close
379     """
380     question = get_object_or_404(Question, id=id)
381     if not request.user.can_close_question(question):
382         return HttpResponseForbidden()
383     if request.method == 'POST':
384         form = CloseForm(request.POST)
385         if form.is_valid():
386             reason = form.cleaned_data['reason']
387             question.closed = True
388             question.closed_by = request.user
389             question.closed_at = datetime.datetime.now()
390             question.close_reason = reason
391             question.save()
392         return HttpResponseRedirect(question.get_absolute_url())
393     else:
394         form = CloseForm()
395         return render_to_response('close.html', {
396             'form' : form,
397             'question' : question,
398             }, context_instance=RequestContext(request))
399
400 @login_required
401 def reopen(request, id):#re-open question
402     """view to initiate and process 
403     question close
404     """
405     question = get_object_or_404(Question, id=id)
406     # open question
407     if not request.user.can_reopen_question(question):
408         return HttpResponseForbidden()
409     if request.method == 'POST' :
410         Question.objects.filter(id=question.id).update(closed=False,
411             closed_by=None, closed_at=None, close_reason=None)
412         return HttpResponseRedirect(question.get_absolute_url())
413     else:
414         return render_to_response('reopen.html', {
415             'question' : question,
416             }, context_instance=RequestContext(request))
417
418 #osqa-user communication system
419 def read_message(request):#marks message a read
420     if request.method == "POST":
421         if request.POST['formdata'] == 'required':
422             request.session['message_silent'] = 1
423             if request.user.is_authenticated():
424                 request.user.delete_messages()
425     return HttpResponse('')
426
427