]> git.openstreetmap.org Git - osqa.git/blob - forum/views/readers.py
Adds feeds for answers or comments to questions.
[osqa.git] / forum / views / readers.py
1 # encoding:utf-8
2 import datetime
3 import logging
4 from urllib import unquote
5 from forum import settings as django_settings
6 from django.shortcuts import render_to_response, get_object_or_404
7 from django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponsePermanentRedirect
8 from django.core.paginator import Paginator, EmptyPage, InvalidPage
9 from django.template import RequestContext
10 from django import template
11 from django.utils.html import *
12 from django.utils import simplejson
13 from django.db.models import Q
14 from django.utils.translation import ugettext as _
15 from django.template.defaultfilters import slugify
16 from django.core.urlresolvers import reverse
17 from django.utils.datastructures import SortedDict
18 from django.views.decorators.cache import cache_page
19 from django.utils.http import urlquote  as django_urlquote
20 from django.template.defaultfilters import slugify
21 from django.utils.safestring import mark_safe
22
23 from forum.utils.html import sanitize_html, hyperlink
24 from forum.utils.diff import textDiff as htmldiff
25 from forum.utils import pagination
26 from forum.forms import *
27 from forum.models import *
28 from forum.forms import get_next_url
29 from forum.actions import QuestionViewAction
30 from forum.http_responses import HttpResponseUnauthorized
31 from forum.feed import RssQuestionFeed, RssAnswerFeed
32 import decorators
33
34 class QuestionListPaginatorContext(pagination.PaginatorContext):
35     def __init__(self, id='QUESTIONS_LIST', prefix='', default_pagesize=30):
36         super (QuestionListPaginatorContext, self).__init__(id, sort_methods=(
37             (_('active'), pagination.SimpleSort(_('active'), '-last_activity_at', _("most recently updated questions"))),
38             (_('newest'), pagination.SimpleSort(_('newest'), '-added_at', _("most recently asked questions"))),
39             (_('hottest'), pagination.SimpleSort(_('hottest'), '-extra_count', _("hottest questions"))),
40             (_('mostvoted'), pagination.SimpleSort(_('most voted'), '-score', _("most voted questions"))),
41         ), pagesizes=(15, 30, 50), default_pagesize=default_pagesize, prefix=prefix)
42
43 class AnswerSort(pagination.SimpleSort):
44     def apply(self, objects):
45         if self.label == _('votes'):
46             return objects.order_by('-marked', self.order_by, 'added_at')
47         else:
48             return objects.order_by('-marked', self.order_by)
49
50 class AnswerPaginatorContext(pagination.PaginatorContext):
51     def __init__(self, id='ANSWER_LIST', prefix='', default_pagesize=10):
52         super (AnswerPaginatorContext, self).__init__(id, sort_methods=(
53             (_('oldest'), AnswerSort(_('oldest answers'), 'added_at', _("oldest answers will be shown first"))),
54             (_('newest'), AnswerSort(_('newest answers'), '-added_at', _("newest answers will be shown first"))),
55             (_('votes'), AnswerSort(_('popular answers'), '-score', _("most voted answers will be shown first"))),
56         ), default_sort=_('votes'), sticky_sort = True, pagesizes=(5, 10, 20), default_pagesize=default_pagesize, prefix=prefix)
57
58 class TagPaginatorContext(pagination.PaginatorContext):
59     def __init__(self):
60         super (TagPaginatorContext, self).__init__('TAG_LIST', sort_methods=(
61             (_('name'), pagination.SimpleSort(_('by name'), 'name', _("sorted alphabetically"))),
62             (_('used'), pagination.SimpleSort(_('by popularity'), '-used_count', _("sorted by frequency of tag use"))),
63         ), default_sort=_('used'), pagesizes=(30, 60, 120))
64     
65
66 def feed(request):
67     return RssQuestionFeed(
68                 Question.objects.filter_state(deleted=False).order_by('-last_activity_at'),
69                 settings.APP_TITLE + _(' - ')+ _('latest questions'),
70                 settings.APP_DESCRIPTION,
71                 request)(request)
72
73
74 @decorators.render('index.html')
75 def index(request):
76     return question_list(request,
77                          Question.objects.all(),
78                          sort=request.utils.set_sort_method('active'),
79                          base_path=reverse('questions'),
80                          feed_url=reverse('latest_questions_feed'))
81
82 @decorators.render('questions.html', 'unanswered', _('unanswered'), weight=400)
83 def unanswered(request):
84     return question_list(request,
85                          Question.objects.filter(extra_ref=None),
86                          _('open questions without an accepted answer'),
87                          request.utils.set_sort_method('active'),
88                          None,
89                          _("Unanswered Questions"))
90
91 @decorators.render('questions.html', 'questions', _('questions'), weight=0)
92 def questions(request):
93     return question_list(request, Question.objects.all(), _('questions'), request.utils.set_sort_method('active'))
94
95 @decorators.render('questions.html')
96 def tag(request, tag):
97     return question_list(request,
98                          Question.objects.filter(tags__name=unquote(tag)),
99                          mark_safe(_('questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
100                          request.utils.set_sort_method('active'),
101                          None,
102                          mark_safe(_('Questions Tagged With %(tag)s') % {'tag': tag}),
103                          False)
104
105 @decorators.render('questions.html', 'questions', tabbed=False)
106 def user_questions(request, mode, user, slug):
107     user = get_object_or_404(User, id=user)
108
109     if mode == _('asked-by'):
110         questions = Question.objects.filter(author=user)
111         description = _("Questions asked by %s")
112     elif mode == _('answered-by'):
113         questions = Question.objects.filter(children__author=user, children__node_type='answer').distinct()
114         description = _("Questions answered by %s")
115     elif mode == _('subscribed-by'):
116         if not (request.user.is_superuser or request.user == user):
117             return HttpResponseUnauthorized(request)
118         questions = user.subscriptions
119
120         if request.user == user:
121             description = _("Questions you subscribed %s")
122         else:
123             description = _("Questions subscribed by %s")
124     else:
125         raise Http404
126
127
128     return question_list(request, questions,
129                          mark_safe(description % hyperlink(user.get_profile_url(), user.username)),
130                          request.utils.set_sort_method('active'),
131                          page_title=description % user.username)
132
133 def question_list(request, initial,
134                   list_description=_('questions'),
135                   sort=None,
136                   base_path=None,
137                   page_title=_("All Questions"),
138                   allowIgnoreTags=True,
139                   feed_url=None,
140                   paginator_context=None):
141
142     questions = initial.filter_state(deleted=False)
143
144     if request.user.is_authenticated() and allowIgnoreTags:
145         questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))
146
147     if page_title is None:
148         page_title = _("Questions")
149
150     if request.GET.get('type', None) == 'rss':
151         questions = questions.order_by('-added_at')
152         return RssQuestionFeed(request, questions, page_title, list_description)(request)
153
154     keywords =  ""
155     if request.GET.get("q"):
156         keywords = request.GET.get("q").strip()
157
158     answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
159     answer_description = _("answers")
160
161     if not feed_url:
162         req_params = "&".join(["%s=%s" % (k, v) for k, v in request.GET.items() if not k in (_('page'), _('pagesize'), _('sort'))])
163         if req_params:
164             req_params = '&' + req_params
165
166         feed_url = mark_safe(request.path + "?type=rss" + req_params)
167
168     return pagination.paginated(request, ('questions', paginator_context or QuestionListPaginatorContext()), {
169     "questions" : questions,
170     "questions_count" : questions.count(),
171     "answer_count" : answer_count,
172     "keywords" : keywords,
173     "list_description": list_description,
174     "answer_description": answer_description,
175     "base_path" : base_path,
176     "page_title" : page_title,
177     "tab" : "questions",
178     'feed_url': feed_url,
179     })
180
181
182 def search(request):
183     if request.method == "GET" and "q" in request.GET:
184         keywords = request.GET.get("q")
185         search_type = request.GET.get("t")
186
187         if not keywords:
188             return HttpResponseRedirect(reverse(index))
189         if search_type == 'tag':
190             return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
191         elif search_type == "user":
192             return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
193         elif search_type == "question":
194             return question_search(request, keywords)
195     else:
196         return render_to_response("search.html", context_instance=RequestContext(request))
197
198 @decorators.render('questions.html')
199 def question_search(request, keywords):
200     can_rank, initial = Question.objects.search(keywords)
201
202     if can_rank:
203         paginator_context = QuestionListPaginatorContext()
204         paginator_context.sort_methods[_('ranking')] = pagination.SimpleSort(_('relevance'), '-ranking', _("most relevant questions"))
205         paginator_context.force_sort = _('ranking')
206     else:
207         paginator_context = None
208
209     return question_list(request, initial,
210                          _("questions matching '%(keywords)s'") % {'keywords': keywords},
211                          False,
212                          "%s?t=question&q=%s" % (reverse('search'),django_urlquote(keywords)),
213                          _("questions matching '%(keywords)s'") % {'keywords': keywords},
214                          paginator_context=paginator_context)
215
216
217 @decorators.render('tags.html', 'tags', _('tags'), weight=100)
218 def tags(request):
219     stag = ""
220     tags = Tag.active.all()
221
222     if request.method == "GET":
223         stag = request.GET.get("q", "").strip()
224         if stag:
225             tags = tags.filter(name__contains=stag)
226
227     return pagination.paginated(request, ('tags', TagPaginatorContext()), {
228         "tags" : tags,
229         "stag" : stag,
230         "keywords" : stag
231     })
232
233 def update_question_view_times(request, question):
234     if not 'last_seen_in_question' in request.session:
235         request.session['last_seen_in_question'] = {}
236
237     last_seen = request.session['last_seen_in_question'].get(question.id, None)
238
239     if (not last_seen) or last_seen < question.last_activity_at:
240         QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
241         request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
242
243     request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
244
245 def match_question_slug(slug):
246     slug_words = slug.split('-')
247     qs = Question.objects.filter(title__istartswith=slug_words[0])
248
249     for q in qs:
250         if slug == urlquote(slugify(q.title)):
251             return q
252
253     return None
254
255 def answer_redirect(request, answer):
256     pc = AnswerPaginatorContext()
257
258     sort = pc.sort(request)
259
260     if sort == _('oldest'):
261         filter = Q(added_at__lt=answer.added_at)
262     elif sort == _('newest'):
263         filter = Q(added_at__gt=answer.added_at)
264     elif sort == _('votes'):
265         filter = Q(score__gt=answer.score) | Q(score=answer.score, added_at__lt=answer.added_at)
266     else:
267         raise Http404()
268         
269     count = answer.question.answers.filter(Q(marked=True) | filter).count()
270     pagesize = pc.pagesize(request)
271
272     page = count / pagesize
273     
274     if count % pagesize:
275         page += 1
276         
277     if page == 0:
278         page = 1
279
280     return HttpResponsePermanentRedirect("%s?%s=%s#%s" % (
281         answer.question.get_absolute_url(), _('page'), page, answer.id))
282
283 @decorators.render("question.html", 'questions')
284 def question(request, id, slug=None, answer=None):
285     try:
286         question = Question.objects.get(id=id)
287     except:
288         if slug:
289             question = match_question_slug(slug)
290             if question is not None:
291                 return HttpResponseRedirect(question.get_absolute_url())
292
293         raise Http404()
294
295     if question.nis.deleted and not request.user.can_view_deleted_post(question):
296         raise Http404
297
298     if request.GET.get('type', None) == 'rss':
299         return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)
300
301     if answer:
302         answer = get_object_or_404(Answer, id=answer)
303
304         if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
305             raise Http404
306
307         if answer.marked:
308             return HttpResponsePermanentRedirect(question.get_absolute_url())
309
310         return answer_redirect(request, answer)
311
312     if (not slug) or (slug != urlquote(slugify(question.title))):
313         return HttpResponsePermanentRedirect(question.get_absolute_url())
314
315     if request.POST:
316         answer_form = AnswerForm(question, request.POST)
317     else:
318         answer_form = AnswerForm(question)
319
320     answers = request.user.get_visible_answers(question)
321
322     update_question_view_times(request, question)
323
324     if request.user.is_authenticated():
325         try:
326             subscription = QuestionSubscription.objects.get(question=question, user=request.user)
327         except:
328             subscription = False
329     else:
330         subscription = False
331
332     return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
333     "question" : question,
334     "answer" : answer_form,
335     "answers" : answers,
336     "similar_questions" : question.get_related_questions(),
337     "subscription": subscription,
338     })
339
340
341 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
342
343 def revisions(request, id):
344     post = get_object_or_404(Node, id=id).leaf
345     revisions = list(post.revisions.order_by('revised_at'))
346     rev_ctx = []
347
348     for i, revision in enumerate(revisions):
349         rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({
350         'title': revision.title,
351         'html': revision.html,
352         'tags': revision.tagname_list(),
353         }))))
354
355         if i > 0:
356             rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
357         else:
358             rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
359
360         if not (revision.summary):
361             rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
362         else:
363             rev_ctx[i]['summary'] = revision.summary
364
365     rev_ctx.reverse()
366
367     return render_to_response('revisions.html', {
368     'post': post,
369     'revisions': rev_ctx,
370     }, context_instance=RequestContext(request))
371
372
373