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