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