]> git.openstreetmap.org Git - osqa.git/blob - forum/views/commands.py
Initial commit
[osqa.git] / forum / views / commands.py
1 import datetime
2 from django.conf import settings
3 from django.utils import simplejson
4 from django.http import HttpResponse, HttpResponseRedirect
5 from django.shortcuts import get_object_or_404
6 from django.utils.translation import ugettext as _
7 from django.template import RequestContext
8 from forum.models import *
9 from forum.forms import CloseForm
10 from forum import auth
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 import logging
15
16 def vote(request, id):#refactor - pretty incomprehensible view used by various ajax calls
17 #issues: this subroutine is too long, contains many magic numbers and other issues
18 #it's called "vote" but many actions processed here have nothing to do with voting
19     """
20     vote_type:
21         acceptAnswer : 0,
22         questionUpVote : 1,
23         questionDownVote : 2,
24         favorite : 4,
25         answerUpVote: 5,
26         answerDownVote:6,
27         offensiveQuestion : 7,
28         offensiveAnswer:8,
29         removeQuestion: 9,
30         removeAnswer:10
31         questionSubscribeUpdates:11
32         questionUnSubscribeUpdates:12
33
34     accept answer code:
35         response_data['allowed'] = -1, Accept his own answer   0, no allowed - Anonymous    1, Allowed - by default
36         response_data['success'] =  0, failed                                               1, Success - by default
37         response_data['status']  =  0, By default                                           1, Answer has been accepted already(Cancel)
38
39     vote code:
40         allowed = -3, Don't have enough votes left
41                   -2, Don't have enough reputation score
42                   -1, Vote his own post
43                    0, no allowed - Anonymous
44                    1, Allowed - by default
45         status  =  0, By default
46                    1, Cancel
47                    2, Vote is too old to be canceled
48
49     offensive code:
50         allowed = -3, Don't have enough flags left
51                   -2, Don't have enough reputation score to do this
52                    0, not allowed
53                    1, allowed
54         status  =  0, by default
55                    1, can't do it again
56     """
57     response_data = {
58         "allowed": 1,
59         "success": 1,
60         "status" : 0,
61         "count"  : 0,
62         "message" : ''
63     }
64
65     def __can_vote(vote_score, user):#refactor - belongs to auth.py
66         if vote_score == 1:#refactor magic number
67             return auth.can_vote_up(request.user)
68         else:
69             return auth.can_vote_down(request.user)
70
71     try:
72         if not request.user.is_authenticated():
73             response_data['allowed'] = 0
74             response_data['success'] = 0
75
76         elif request.is_ajax() and request.method == 'POST':
77             question = get_object_or_404(Question, id=id)
78             vote_type = request.POST.get('type')
79
80             #accept answer
81             if vote_type == '0':
82                 answer_id = request.POST.get('postId')
83                 answer = get_object_or_404(Answer, id=answer_id)
84                 # make sure question author is current user
85                 if question.author == request.user:
86                     # answer user who is also question author is not allow to accept answer
87                     if answer.author == question.author:
88                         response_data['success'] = 0
89                         response_data['allowed'] = -1
90                     # check if answer has been accepted already
91                     elif answer.accepted:
92                         auth.onAnswerAcceptCanceled(answer, request.user)
93                         response_data['status'] = 1
94                     else:
95                         # set other answers in this question not accepted first
96                         for answer_of_question in Answer.objects.get_answers_from_question(question, request.user):
97                             if answer_of_question != answer and answer_of_question.accepted:
98                                 auth.onAnswerAcceptCanceled(answer_of_question, request.user)
99
100                         #make sure retrieve data again after above author changes, they may have related data
101                         answer = get_object_or_404(Answer, id=answer_id)
102                         auth.onAnswerAccept(answer, request.user)
103                 else:
104                     response_data['allowed'] = 0
105                     response_data['success'] = 0
106             # favorite
107             elif vote_type == '4':
108                 has_favorited = False
109                 fav_questions = FavoriteQuestion.objects.filter(question=question)
110                 # if the same question has been favorited before, then delete it
111                 if fav_questions is not None:
112                     for item in fav_questions:
113                         if item.user == request.user:
114                             item.delete()
115                             response_data['status'] = 1
116                             response_data['count']  = len(fav_questions) - 1
117                             if response_data['count'] < 0:
118                                 response_data['count'] = 0
119                             has_favorited = True
120                 # if above deletion has not been executed, just insert a new favorite question
121                 if not has_favorited:
122                     new_item = FavoriteQuestion(question=question, user=request.user)
123                     new_item.save()
124                     response_data['count']  = FavoriteQuestion.objects.filter(question=question).count()
125                 Question.objects.update_favorite_count(question)
126
127             elif vote_type in ['1', '2', '5', '6']:
128                 post_id = id
129                 post = question
130                 vote_score = 1
131                 if vote_type in ['5', '6']:
132                     answer_id = request.POST.get('postId')
133                     answer = get_object_or_404(Answer, id=answer_id)
134                     post_id = answer_id
135                     post = answer
136                 if vote_type in ['2', '6']:
137                     vote_score = -1
138
139                 if post.author == request.user:
140                     response_data['allowed'] = -1
141                 elif not __can_vote(vote_score, request.user):
142                     response_data['allowed'] = -2
143                 elif post.votes.filter(user=request.user).count() > 0:
144                     vote = post.votes.filter(user=request.user)[0]
145                     # unvote should be less than certain time
146                     if (datetime.datetime.now().day - vote.voted_at.day) >= auth.VOTE_RULES['scope_deny_unvote_days']:
147                         response_data['status'] = 2
148                     else:
149                         voted = vote.vote
150                         if voted > 0:
151                             # cancel upvote
152                             auth.onUpVotedCanceled(vote, post, request.user)
153
154                         else:
155                             # cancel downvote
156                             auth.onDownVotedCanceled(vote, post, request.user)
157
158                         response_data['status'] = 1
159                         response_data['count'] = post.score
160                 elif Vote.objects.get_votes_count_today_from_user(request.user) >= auth.VOTE_RULES['scope_votes_per_user_per_day']:
161                     response_data['allowed'] = -3
162                 else:
163                     vote = Vote(user=request.user, content_object=post, vote=vote_score, voted_at=datetime.datetime.now())
164                     if vote_score > 0:
165                         # upvote
166                         auth.onUpVoted(vote, post, request.user)
167                     else:
168                         # downvote
169                         auth.onDownVoted(vote, post, request.user)
170
171                     votes_left = auth.VOTE_RULES['scope_votes_per_user_per_day'] - Vote.objects.get_votes_count_today_from_user(request.user)
172                     if votes_left <= auth.VOTE_RULES['scope_warn_votes_left']:
173                         response_data['message'] = u'%s votes left' % votes_left
174                     response_data['count'] = post.score
175             elif vote_type in ['7', '8']:
176                 post = question
177                 post_id = id
178                 if vote_type == '8':
179                     post_id = request.POST.get('postId')
180                     post = get_object_or_404(Answer, id=post_id)
181
182                 if FlaggedItem.objects.get_flagged_items_count_today(request.user) >= auth.VOTE_RULES['scope_flags_per_user_per_day']:
183                     response_data['allowed'] = -3
184                 elif not auth.can_flag_offensive(request.user):
185                     response_data['allowed'] = -2
186                 elif post.flagged_items.filter(user=request.user).count() > 0:
187                     response_data['status'] = 1
188                 else:
189                     item = FlaggedItem(user=request.user, content_object=post, flagged_at=datetime.datetime.now())
190                     auth.onFlaggedItem(item, post, request.user)
191                     response_data['count'] = post.offensive_flag_count
192                     # send signal when question or answer be marked offensive
193                     mark_offensive.send(sender=post.__class__, instance=post, mark_by=request.user)
194             elif vote_type in ['9', '10']:
195                 post = question
196                 post_id = id
197                 if vote_type == '10':
198                     post_id = request.POST.get('postId')
199                     post = get_object_or_404(Answer, id=post_id)
200
201                 if not auth.can_delete_post(request.user, post):
202                     response_data['allowed'] = -2
203                 elif post.deleted == True:
204                     logging.debug('debug restoring post in view')
205                     auth.onDeleteCanceled(post, request.user)
206                     response_data['status'] = 1
207                 else:
208                     auth.onDeleted(post, request.user)
209                     delete_post_or_answer.send(sender=post.__class__, instance=post, delete_by=request.user)
210             elif vote_type == '11':#subscribe q updates
211                 user = request.user
212                 if user.is_authenticated():
213                     if user not in question.followed_by.all():
214                         question.followed_by.add(user)
215                         if settings.EMAIL_VALIDATION == 'on' and user.email_isvalid == False:
216                             response_data['message'] = \
217                                     _('subscription saved, %(email)s needs validation, see %(details_url)s') \
218                                     % {'email':user.email,'details_url':reverse('faq') + '#validate'}
219                     feed_setting = EmailFeedSetting.objects.get(subscriber=user,feed_type='q_sel')
220                     if feed_setting.frequency == 'n':
221                         feed_setting.frequency = 'd'
222                         feed_setting.save()
223                         if 'message' in response_data:
224                             response_data['message'] += '<br/>'
225                         response_data['message'] = _('email update frequency has been set to daily')
226                     #response_data['status'] = 1
227                     #responst_data['allowed'] = 1
228                 else:
229                     pass
230                     #response_data['status'] = 0
231                     #response_data['allowed'] = 0
232             elif vote_type == '12':#unsubscribe q updates
233                 user = request.user
234                 if user.is_authenticated():
235                     if user in question.followed_by.all():
236                         question.followed_by.remove(user)
237         else:
238             response_data['success'] = 0
239             response_data['message'] = u'Request mode is not supported. Please try again.'
240
241         data = simplejson.dumps(response_data)
242
243     except Exception, e:
244         response_data['message'] = str(e)
245         data = simplejson.dumps(response_data)
246     return HttpResponse(data, mimetype="application/json")
247
248 #internally grouped views - used by the tagging system
249 @ajax_login_required
250 def mark_tag(request, tag=None, **kwargs):#tagging system
251     action = kwargs['action']
252     ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
253     if action == 'remove':
254         logging.debug('deleting tag %s' % tag)
255         ts.delete()
256     else:
257         reason = kwargs['reason']
258         if len(ts) == 0:
259             try:
260                 t = Tag.objects.get(name=tag)
261                 mt = MarkedTag(user=request.user, reason=reason, tag=t)
262                 mt.save()
263             except:
264                 pass
265         else:
266             ts.update(reason=reason)
267     return HttpResponse(simplejson.dumps(''), mimetype="application/json")
268
269 @ajax_login_required
270 def ajax_toggle_ignored_questions(request):#ajax tagging and tag-filtering system
271     if request.user.hide_ignored_questions:
272         new_hide_setting = False
273     else:
274         new_hide_setting = True
275     request.user.hide_ignored_questions = new_hide_setting
276     request.user.save()
277
278 @ajax_method
279 def ajax_command(request):#refactor? view processing ajax commands - note "vote" and view others do it too
280     if 'command' not in request.POST:
281         return HttpResponseForbidden(mimetype="application/json")
282     if request.POST['command'] == 'toggle-ignored-questions':
283         return ajax_toggle_ignored_questions(request)
284
285 @login_required
286 def close(request, id):#close question
287     """view to initiate and process 
288     question close
289     """
290     question = get_object_or_404(Question, id=id)
291     if not auth.can_close_question(request.user, question):
292         return HttpResponse('Permission denied.')
293     if request.method == 'POST':
294         form = CloseForm(request.POST)
295         if form.is_valid():
296             reason = form.cleaned_data['reason']
297             question.closed = True
298             question.closed_by = request.user
299             question.closed_at = datetime.datetime.now()
300             question.close_reason = reason
301             question.save()
302         return HttpResponseRedirect(question.get_absolute_url())
303     else:
304         form = CloseForm()
305         return render_to_response('close.html', {
306             'form' : form,
307             'question' : question,
308             }, context_instance=RequestContext(request))
309
310 @login_required
311 def reopen(request, id):#re-open question
312     """view to initiate and process 
313     question close
314     """
315     question = get_object_or_404(Question, id=id)
316     # open question
317     if not auth.can_reopen_question(request.user, question):
318         return HttpResponse('Permission denied.')
319     if request.method == 'POST' :
320         Question.objects.filter(id=question.id).update(closed=False,
321             closed_by=None, closed_at=None, close_reason=None)
322         return HttpResponseRedirect(question.get_absolute_url())
323     else:
324         return render_to_response('reopen.html', {
325             'question' : question,
326             }, context_instance=RequestContext(request))
327
328 #osqa-user communication system
329 def read_message(request):#marks message a read
330     if request.method == "POST":
331         if request.POST['formdata'] == 'required':
332             request.session['message_silent'] = 1
333             if request.user.is_authenticated():
334                 request.user.delete_messages()
335     return HttpResponse('')