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