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