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