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