]> git.openstreetmap.org Git - osqa.git/blob - forum/views/readers.py
Merge pull request #49 from udacity/login_logout_links
[osqa.git] / forum / views / readers.py
1 # encoding:utf-8
2 import datetime
3 import logging
4 from urllib import unquote
5 from django.shortcuts import render_to_response, get_object_or_404
6 from django.http import HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
7 from django.core.paginator import Paginator, EmptyPage, InvalidPage
8 from django.template import RequestContext
9 from django import template
10 from django.utils.html import *
11 from django.utils.http import urlquote
12 from django.db.models import Q, Count
13 from django.utils.translation import ugettext as _
14 from django.core.urlresolvers import reverse
15 from django.template.defaultfilters import slugify
16 from django.utils.safestring import mark_safe
17
18 from forum import settings as django_settings
19 from forum.utils.html import hyperlink
20 from forum.utils.diff import textDiff as htmldiff
21 from forum.utils import pagination
22 from forum.forms import *
23 from forum.models import *
24 from forum.actions import QuestionViewAction
25 from forum.http_responses import HttpResponseUnauthorized
26 from forum.feed import RssQuestionFeed, RssAnswerFeed
27 from forum.utils.pagination import generate_uri
28
29 import decorators
30
31 class HottestQuestionsSort(pagination.SortBase):
32     def apply(self, questions):
33         return questions.extra(select={'new_child_count': '''
34             SELECT COUNT(1)
35                 FROM forum_node fn1
36                 WHERE fn1.abs_parent_id = forum_node.id
37                     AND fn1.id != forum_node.id
38                     AND NOT(fn1.state_string LIKE '%%(deleted)%%')
39                     AND added_at > %s'''
40             },
41             select_params=[ (datetime.datetime.now() - datetime.timedelta(days=2))
42                 .strftime('%Y-%m-%d')]
43         ).order_by('-new_child_count', 'last_activity_at')
44
45 class UnansweredQuestionsSort(pagination.SortBase):
46     def apply(self, questions):
47         return questions.extra(select={'answer_count': '''
48             SELECT COUNT(1)
49                 FROM forum_node fn1
50                 WHERE fn1.abs_parent_id = forum_node.id
51                     AND fn1.id != forum_node.id
52                     AND fn1.node_type='answer'
53                     AND NOT(fn1.state_string LIKE '%%(deleted)%%')'''
54             }).order_by('answer_count', 'last_activity_at')
55
56 class QuestionListPaginatorContext(pagination.PaginatorContext):
57     def __init__(self, id='QUESTIONS_LIST', prefix='', pagesizes=(15, 30, 50), default_pagesize=30):
58         super (QuestionListPaginatorContext, self).__init__(id, sort_methods=(
59             (_('active'), pagination.SimpleSort(_('active'), '-last_activity_at', _("Most <strong>recently updated</strong> questions"))),
60             (_('newest'), pagination.SimpleSort(_('newest'), '-added_at', _("most <strong>recently asked</strong> questions"))),
61             (_('hottest'), HottestQuestionsSort(_('hottest'), _("most <strong>active</strong> questions in the last 24 hours</strong>"))),
62             (_('mostvoted'), pagination.SimpleSort(_('most voted'), '-score', _("most <strong>voted</strong> questions"))),
63             (_('unanswered'), UnansweredQuestionsSort('unanswered', "questions with no answers")),
64         ), pagesizes=pagesizes, default_pagesize=default_pagesize, prefix=prefix)
65
66 class AnswerSort(pagination.SimpleSort):
67     def apply(self, answers):
68         if not settings.DISABLE_ACCEPTING_FEATURE:
69             return answers.order_by(*(['-marked'] + list(self._get_order_by())))
70         else:
71             return super(AnswerSort, self).apply(answers)
72
73 class AnswerPaginatorContext(pagination.PaginatorContext):
74     def __init__(self, id='ANSWER_LIST', prefix='', default_pagesize=10):
75         super (AnswerPaginatorContext, self).__init__(id, sort_methods=(
76             (_('active'), AnswerSort(_('active answers'), '-last_activity_at', _("most recently updated answers/comments will be shown first"))),
77             (_('oldest'), AnswerSort(_('oldest answers'), 'added_at', _("oldest answers will be shown first"))),
78             (_('newest'), AnswerSort(_('newest answers'), '-added_at', _("newest answers will be shown first"))),
79             (_('votes'), AnswerSort(_('popular answers'), ('-score', 'added_at'), _("most voted answers will be shown first"))),
80         ), default_sort=_('votes'), pagesizes=(5, 10, 20), default_pagesize=default_pagesize, prefix=prefix)
81
82 class TagPaginatorContext(pagination.PaginatorContext):
83     def __init__(self):
84         super (TagPaginatorContext, self).__init__('TAG_LIST', sort_methods=(
85             (_('name'), pagination.SimpleSort(_('by name'), 'name', _("sorted alphabetically"))),
86             (_('used'), pagination.SimpleSort(_('by popularity'), '-used_count', _("sorted by frequency of tag use"))),
87         ), default_sort=_('used'), pagesizes=(30, 60, 120))
88     
89
90 def feed(request):
91     return RssQuestionFeed(
92                 request,
93                 Question.objects.filter_state(deleted=False).order_by('-last_activity_at'),
94                 settings.APP_TITLE + _(' - ')+ _('latest questions'),
95                 settings.APP_DESCRIPTION)(request)
96
97 @decorators.render('index.html')
98 def index(request):
99     paginator_context = QuestionListPaginatorContext()
100     paginator_context.base_path = reverse('questions')
101     return question_list(request,
102                          Question.objects.all(),
103                          base_path=reverse('questions'),
104                          feed_url=reverse('latest_questions_feed'),
105                          paginator_context=paginator_context)
106
107 @decorators.render('questions.html', 'unanswered', _('unanswered'), weight=400)
108 def unanswered(request):
109     return question_list(request,
110                          Question.objects.exclude(id__in=Question.objects.filter(children__marked=True).distinct()).exclude(marked=True),
111                          _('open questions without an accepted answer'),
112                          None,
113                          _("Unanswered Questions"))
114
115 @decorators.render('questions.html', 'questions', _('questions'), weight=0)
116 def questions(request):
117     return question_list(request,
118                          Question.objects.all(),
119                          _('questions'))
120
121 @decorators.render('questions.html')
122 def tag(request, tag):
123     try:
124         tag = Tag.active.get(name=unquote(tag))
125     except Tag.DoesNotExist:
126         raise Http404
127
128     # Getting the questions QuerySet
129     questions = Question.objects.filter(tags__id=tag.id)
130
131     if request.method == "GET":
132         user = request.GET.get('user', None)
133
134         if user is not None:
135             try:
136                 questions = questions.filter(author=User.objects.get(username=user))
137             except User.DoesNotExist:
138                 raise Http404
139
140     # The extra tag context we need to pass
141     tag_context = {
142         'tag' : tag,
143     }
144
145     # The context returned by the question_list function, contains info about the questions
146     question_context = question_list(request,
147                          questions,
148                          mark_safe(_(u'questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
149                          None,
150                          mark_safe(_(u'Questions Tagged With %(tag)s') % {'tag': tag}),
151                          False)
152
153     # If the return data type is not a dict just return it
154     if not isinstance(question_context, dict):
155         return question_context
156
157     question_context = dict(question_context)
158
159     # Create the combined context
160     context = dict(question_context.items() + tag_context.items())
161
162     return context
163
164 @decorators.render('questions.html', 'questions', tabbed=False)
165 def user_questions(request, mode, user, slug):
166     user = get_object_or_404(User, id=user)
167
168     if mode == _('asked-by'):
169         questions = Question.objects.filter(author=user)
170         description = _("Questions asked by %s")
171     elif mode == _('answered-by'):
172         questions = Question.objects.filter(children__author=user, children__node_type='answer').distinct()
173         description = _("Questions answered by %s")
174     elif mode == _('subscribed-by'):
175         if not (request.user.is_superuser or request.user == user):
176             return HttpResponseUnauthorized(request)
177         questions = user.subscriptions
178
179         if request.user == user:
180             description = _("Questions you subscribed %s")
181         else:
182             description = _("Questions subscribed by %s")
183     else:
184         raise Http404
185
186
187     return question_list(request, questions,
188                          mark_safe(description % hyperlink(user.get_profile_url(), user.username)),
189                          page_title=description % user.username)
190
191 def question_list(request, initial,
192                   list_description=_('questions'),
193                   base_path=None,
194                   page_title=_("All Questions"),
195                   allowIgnoreTags=True,
196                   feed_url=None,
197                   paginator_context=None,
198                   show_summary=None,
199                   feed_sort=('-added_at',),
200                   feed_req_params_exclude=(_('page'), _('pagesize'), _('sort')),
201                   extra_context={}):
202
203     if show_summary is None:
204         show_summary = bool(settings.SHOW_SUMMARY_ON_QUESTIONS_LIST)
205
206     questions = initial.filter_state(deleted=False)
207
208     if request.user.is_authenticated() and allowIgnoreTags:
209         questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))
210
211     if page_title is None:
212         page_title = _("Questions")
213
214     if request.GET.get('type', None) == 'rss':
215         if feed_sort:
216             questions = questions.order_by(*feed_sort)
217         return RssQuestionFeed(request, questions, page_title, list_description)(request)
218
219     keywords =  ""
220     if request.GET.get("q"):
221         keywords = request.GET.get("q").strip()
222
223     #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
224     #answer_description = _("answers")
225
226     if not feed_url:
227         req_params = generate_uri(request.GET, feed_req_params_exclude)
228
229         if req_params:
230             req_params = '&' + req_params
231
232         feed_url = request.path + "?type=rss" + req_params
233
234     context = {
235         'questions' : questions.distinct(),
236         'questions_count' : questions.count(),
237         'keywords' : keywords,
238         'list_description': list_description,
239         'base_path' : base_path,
240         'page_title' : page_title,
241         'tab' : 'questions',
242         'feed_url': feed_url,
243         'show_summary' : show_summary,
244     }
245     context.update(extra_context)
246
247     return pagination.paginated(request,
248                                ('questions', paginator_context or QuestionListPaginatorContext()), context)
249
250
251 def search(request):
252     if request.method == "GET" and "q" in request.GET:
253         keywords = request.GET.get("q")
254         search_type = request.GET.get("t")
255
256         if not keywords:
257             return HttpResponseRedirect(reverse(index))
258         if search_type == 'tag':
259             return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
260         elif search_type == "user":
261             return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
262         else:
263             return question_search(request, keywords)
264     else:
265         return render_to_response("search.html", context_instance=RequestContext(request))
266
267 @decorators.render('questions.html')
268 def question_search(request, keywords):
269     rank_feed = False
270     can_rank, initial = Question.objects.search(keywords)
271
272     if can_rank:
273         sort_order = None
274
275         if isinstance(can_rank, basestring):
276             sort_order = can_rank
277             rank_feed = True
278
279         paginator_context = QuestionListPaginatorContext()
280         paginator_context.sort_methods[_('ranking')] = pagination.SimpleSort(_('relevance'), sort_order, _("most relevant questions"))
281         paginator_context.force_sort = _('ranking')
282     else:
283         paginator_context = None
284
285     feed_url = mark_safe(escape(request.path + "?type=rss&q=" + keywords))
286
287     return question_list(request, initial,
288                          _("questions matching '%(keywords)s'") % {'keywords': keywords},
289                          None,
290                          _("questions matching '%(keywords)s'") % {'keywords': keywords},
291                          paginator_context=paginator_context,
292                          feed_url=feed_url, feed_sort=rank_feed and (can_rank,) or '-added_at')
293
294
295 @decorators.render('tags.html', 'tags', _('tags'), weight=100)
296 def tags(request):
297     stag = ""
298     tags = Tag.active.all()
299
300     if request.method == "GET":
301         stag = request.GET.get("q", "").strip()
302         if stag:
303             tags = tags.filter(name__icontains=stag)
304
305     return pagination.paginated(request, ('tags', TagPaginatorContext()), {
306         "tags" : tags,
307         "stag" : stag,
308         "keywords" : stag
309     })
310
311 def update_question_view_times(request, question):
312     last_seen_in_question = request.session.get('last_seen_in_question', {})
313
314     last_seen = last_seen_in_question.get(question.id, None)
315
316     if (not last_seen) or (last_seen < question.last_activity_at):
317         QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
318         last_seen_in_question[question.id] = datetime.datetime.now()
319         request.session['last_seen_in_question'] = last_seen_in_question
320
321 def match_question_slug(id, slug):
322     slug_words = slug.split('-')
323     qs = Question.objects.filter(title__istartswith=slug_words[0])
324
325     for q in qs:
326         if slug == urlquote(slugify(q.title)):
327             return q
328
329     return None
330
331 def answer_redirect(request, answer):
332     pc = AnswerPaginatorContext()
333
334     sort = pc.sort(request)
335
336     if sort == _('oldest'):
337         filter = Q(added_at__lt=answer.added_at)
338     elif sort == _('newest'):
339         filter = Q(added_at__gt=answer.added_at)
340     elif sort == _('votes'):
341         filter = Q(score__gt=answer.score) | Q(score=answer.score, added_at__lt=answer.added_at)
342     else:
343         raise Http404()
344
345     count = answer.question.answers.filter(Q(marked=True) | filter).exclude(state_string="(deleted)").count()
346     pagesize = pc.pagesize(request)
347
348     page = count / pagesize
349     
350     if count % pagesize:
351         page += 1
352         
353     if page == 0:
354         page = 1
355
356     return HttpResponseRedirect("%s?%s=%s&focusedAnswerId=%s#%s" % (
357         answer.question.get_absolute_url(), _('page'), page, answer.id, answer.id))
358
359 @decorators.render("question.html", 'questions')
360 def question(request, id, slug='', answer=None):
361     try:
362         question = Question.objects.get(id=id)
363     except:
364         if slug:
365             question = match_question_slug(id, slug)
366             if question is not None:
367                 return HttpResponseRedirect(question.get_absolute_url())
368
369         raise Http404()
370
371     if question.nis.deleted and not request.user.can_view_deleted_post(question):
372         raise Http404
373
374     if request.GET.get('type', None) == 'rss':
375         return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)
376
377     if answer:
378         answer = get_object_or_404(Answer, id=answer)
379
380         if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
381             raise Http404
382
383         if answer.marked:
384             return HttpResponsePermanentRedirect(question.get_absolute_url())
385
386         return answer_redirect(request, answer)
387
388     if settings.FORCE_SINGLE_URL and (slug != slugify(question.title)):
389         return HttpResponsePermanentRedirect(question.get_absolute_url())
390
391     if request.POST:
392         answer_form = AnswerForm(request.POST, user=request.user)
393     else:
394         answer_form = AnswerForm(user=request.user)
395
396     answers = request.user.get_visible_answers(question)
397
398     update_question_view_times(request, question)
399
400     if request.user.is_authenticated():
401         try:
402             subscription = QuestionSubscription.objects.get(question=question, user=request.user)
403         except:
404             subscription = False
405     else:
406         subscription = False
407     try:
408         focused_answer_id = int(request.GET.get("focusedAnswerId", None))
409     except TypeError, ValueError:
410         focused_answer_id = None
411
412     return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
413     "question" : question,
414     "answer" : answer_form,
415     "answers" : answers,
416     "similar_questions" : question.get_related_questions(),
417     "subscription": subscription,
418     "embed_youtube_videos" : settings.EMBED_YOUTUBE_VIDEOS,
419     "focused_answer_id" : focused_answer_id
420     })
421
422
423 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
424
425 def revisions(request, id):
426     post = get_object_or_404(Node, id=id).leaf
427     revisions = list(post.revisions.order_by('revised_at'))
428     rev_ctx = []
429
430     for i, revision in enumerate(revisions):
431         rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({
432         'title': revision.title,
433         'html': revision.html,
434         'tags': revision.tagname_list(),
435         }))))
436
437         if i > 0:
438             rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
439         else:
440             rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
441
442         if not (revision.summary):
443             rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
444         else:
445             rev_ctx[i]['summary'] = revision.summary
446
447     rev_ctx.reverse()
448
449     return render_to_response('revisions.html', {
450     'post': post,
451     'revisions': rev_ctx,
452     }, context_instance=RequestContext(request))
453
454
455