]> git.openstreetmap.org Git - osqa.git/blob - forum/views/readers.py
made the number of answers label translatable.
[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, HttpResponseForbidden, 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
24 from forum.utils.diff import textDiff as htmldiff
25 from forum.forms import *
26 from forum.models import *
27 from forum.utils.forms import get_next_url
28 from forum.actions import QuestionViewAction
29 from forum.modules.decorators import decoratable
30 import decorators
31
32 # used in index page
33 #refactor - move these numbers somewhere?
34 INDEX_PAGE_SIZE = 30
35 INDEX_AWARD_SIZE = 15
36 INDEX_TAGS_SIZE = 25
37 # used in tags list
38 DEFAULT_PAGE_SIZE = 60
39 # used in questions
40 QUESTIONS_PAGE_SIZE = 30
41 # used in answers
42 ANSWERS_PAGE_SIZE = 10
43
44 @decorators.render('index.html')
45 def index(request):
46     return question_list(request,
47                          Question.objects.all(),
48                          sort=request.utils.set_sort_method('active'),
49                          base_path=reverse('questions'))
50
51 @decorators.render('questions.html', 'unanswered')
52 def unanswered(request):
53     return question_list(request,
54                          Question.objects.filter(extra_ref=None),
55                          _('open questions without an accepted answer'),
56                          request.utils.set_sort_method('active'),
57                          None,
58                          _("Unanswered questions"))
59
60 @decorators.render('questions.html', 'questions')
61 def questions(request):
62     return question_list(request, Question.objects.all(), _('questions'), request.utils.set_sort_method('active'))
63
64 @decorators.render('questions.html')
65 def tag(request, tag):
66     return question_list(request,
67                          Question.objects.filter(tags__name=unquote(tag)),
68                          mark_safe(_('questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
69                          request.utils.set_sort_method('active'),
70                          None,
71                          mark_safe(_('questions tagged %(tag)s') % {'tag': tag}),
72                          False)
73
74 @decorators.list('questions', QUESTIONS_PAGE_SIZE)
75 def question_list(request, initial, list_description=_('questions'), sort=None, base_path=None, page_title=None, allowIgnoreTags=True):
76     questions = initial.filter(deleted=None, in_moderation=None)
77
78     if request.user.is_authenticated() and allowIgnoreTags:
79         questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))
80
81     if sort is not False:
82         if sort is None:
83             sort = request.utils.sort_method('latest')
84         else:
85             request.utils.set_sort_method(sort)
86
87         view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-extra_count", "mostvoted":"-score" }
88
89         questions=questions.order_by(view_dic.get(sort, '-added_at'))
90
91     if page_title is None:
92         page_title = _("Questions")
93
94     answer_count = Answer.objects.filter(deleted=None, parent__in=questions).count()   
95     answer_description = _("answers")
96     
97     return {
98         "questions" : questions,
99         "questions_count" : questions.count(),
100         "answer_count" : answer_count,
101         #"tags_autocomplete" : _get_tags_cache_json(),
102         "list_description": list_description,
103         "answer_description": answer_description,
104         "base_path" : base_path,
105         "page_title" : page_title,
106         }
107
108
109 def search(request):
110     if request.method == "GET" and "q" in request.GET:
111         keywords = request.GET.get("q")
112         search_type = request.GET.get("t")
113
114         if not keywords:
115             return HttpResponseRedirect(reverse(index))
116         if search_type == 'tag':
117             return HttpResponseRedirect(reverse('tags') + '?q=%s' % (keywords.strip()))
118         elif search_type == "user":
119             return HttpResponseRedirect(reverse('users') + '?q=%s' % (keywords.strip()))
120         elif search_type == "question":
121             return question_search(request, keywords)
122     else:
123         return render_to_response("search.html", context_instance=RequestContext(request))
124
125 @decoratable
126 def do_question_search(keywords):
127     return Question.objects.filter(Q(title__icontains=keywords) | Q(body__icontains=keywords))
128
129 @decorators.render('questions.html')
130 def question_search(request, keywords):
131     initial = do_question_search(keywords)
132
133     return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
134             base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)), sort=False)
135
136
137 def tags(request):#view showing a listing of available tags - plain list
138     stag = ""
139     is_paginated = True
140     sortby = request.GET.get('sort', 'used')
141     try:
142         page = int(request.GET.get('page', '1'))
143     except ValueError:
144         page = 1
145
146     if request.method == "GET":
147         stag = request.GET.get("q", "").strip()
148         if stag != '':
149             objects_list = Paginator(Tag.objects.filter(deleted=False).exclude(used_count=0).extra(where=['name like %s'], params=['%' + stag + '%']), DEFAULT_PAGE_SIZE)
150         else:
151             if sortby == "name":
152                 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("name"), DEFAULT_PAGE_SIZE)
153             else:
154                 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("-used_count"), DEFAULT_PAGE_SIZE)
155
156     try:
157         tags = objects_list.page(page)
158     except (EmptyPage, InvalidPage):
159         tags = objects_list.page(objects_list.num_pages)
160
161     return render_to_response('tags.html', {
162                                             "tags" : tags,
163                                             "stag" : stag,
164                                             "tab_id" : sortby,
165                                             "keywords" : stag,
166                                             "context" : {
167                                                 'is_paginated' : is_paginated,
168                                                 'pages': objects_list.num_pages,
169                                                 'page': page,
170                                                 'has_previous': tags.has_previous(),
171                                                 'has_next': tags.has_next(),
172                                                 'previous': tags.previous_page_number(),
173                                                 'next': tags.next_page_number(),
174                                                 'base_url' : reverse('tags') + '?sort=%s&' % sortby
175                                             }
176                                 }, context_instance=RequestContext(request))
177
178 def get_answer_sort_order(request):
179     view_dic = {"latest":"-added_at", "oldest":"added_at", "votes":"-score" }
180
181     view_id = request.GET.get('sort', request.session.get('answer_sort_order', None))
182
183     if view_id is None or not view_id in view_dic:
184         view_id = "votes"
185
186     if view_id != request.session.get('answer_sort_order', None):
187         request.session['answer_sort_order'] = view_id
188
189     return (view_id, view_dic[view_id])
190
191 def update_question_view_times(request, question):
192     if not 'last_seen_in_question' in request.session:
193         request.session['last_seen_in_question'] = {}
194
195     last_seen = request.session['last_seen_in_question'].get(question.id,None)
196
197     if (not last_seen) or last_seen < question.last_activity_at:
198         QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
199         request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
200
201     request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
202
203 def match_question_slug(slug):
204     slug_words = slug.split('-')
205     qs = Question.objects.filter(node_type="question", title__istartswith=slug_words[0])
206
207     for q in qs:
208         if slug == urlquote(slugify(q.title)):
209             return q
210
211     return None
212
213 def question(request, id, slug):
214     try:
215         question = Question.objects.get(node_type="question", id=id)
216     except:
217         question = match_question_slug(slug)
218         if question is not None:
219             return HttpResponsePermanentRedirect(question.get_absolute_url())
220         else:
221             raise Http404()
222
223     if slug != urlquote(slugify(question.title)):
224         return HttpResponsePermanentRedirect(question.get_absolute_url())
225
226     page = int(request.GET.get('page', 1))
227     view_id, order_by = get_answer_sort_order(request)
228
229     if question.deleted and not request.user.can_view_deleted_post(question):
230         raise Http404
231
232     answer_form = AnswerForm(question)
233     answers = request.user.get_visible_answers(question)
234
235     if answers is not None:
236         answers = [a for a in answers.order_by("-marked", order_by)
237                    if not a.deleted or a.author == request.user]
238
239     objects_list = Paginator(answers, ANSWERS_PAGE_SIZE)
240     page_objects = objects_list.page(page)
241
242     update_question_view_times(request, question)
243
244     if request.user.is_authenticated():
245         try:
246             subscription = QuestionSubscription.objects.get(question=question, user=request.user)
247         except:
248             subscription = False
249     else:
250         subscription = False
251
252     return render_to_response('question.html', {
253         "question" : question,
254         "answer" : answer_form,
255         "answers" : page_objects.object_list,
256         "tab_id" : view_id,
257         "similar_questions" : question.get_related_questions(),
258         "subscription": subscription,
259         "context" : {
260             'is_paginated' : True,
261             'pages': objects_list.num_pages,
262             'page': page,
263             'has_previous': page_objects.has_previous(),
264             'has_next': page_objects.has_next(),
265             'previous': page_objects.previous_page_number(),
266             'next': page_objects.next_page_number(),
267             'base_url' : request.path + '?sort=%s&' % view_id,
268             'extend_url' : "#sort-top"
269         }
270         }, context_instance=RequestContext(request))
271
272
273 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
274
275 def revisions(request, id):
276     post = get_object_or_404(Node, id=id).leaf
277     revisions = list(post.revisions.order_by('revised_at'))
278
279     rev_ctx = []
280
281     for i, revision in enumerate(revisions):
282         rev_ctx.append(dict(inst=revision, html=REVISION_TEMPLATE.render(template.Context({
283                 'title': revision.title,
284                 'html': revision.html,
285                 'tags': revision.tagname_list(),
286         }))))
287
288         if i > 0:
289             rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
290         else:
291             rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
292
293         if not (revision.summary):
294             rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
295         else:
296             rev_ctx[i]['summary'] = revision.summary
297
298     return render_to_response('revisions.html', {
299                               'post': post,
300                               'revisions': rev_ctx,
301                               }, context_instance=RequestContext(request))
302
303
304