]> git.openstreetmap.org Git - osqa.git/blob - osqa/forum/views/readers.py
53236d506bf78dd18a0a1dd1baa6301351ed58c4
[osqa.git] / osqa / forum / views / readers.py
1 # encoding:utf-8
2 import datetime
3 import logging
4 from urllib import unquote
5 from django.conf 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
8 from django.core.paginator import Paginator, EmptyPage, InvalidPage
9 from django.template import RequestContext
10 from django.utils.html import *
11 from django.utils import simplejson
12 from django.db.models import Q
13 from django.utils.translation import ugettext as _
14 from django.template.defaultfilters import slugify
15 from django.core.urlresolvers import reverse
16 from django.utils.datastructures import SortedDict
17 from django.views.decorators.cache import cache_page
18 from django.utils.http import urlquote  as django_urlquote
19 from django.template.defaultfilters import slugify
20 from django.utils.safestring import mark_safe
21
22 from forum.utils.html import sanitize_html
23 from markdown2 import Markdown
24 from forum.utils.diff import textDiff as htmldiff
25 from forum.forms import *
26 from forum.models import *
27 from forum.const import *
28 from forum.utils.forms import get_next_url
29 from forum.models.question import question_view
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 markdowner = Markdown(html4tags=True)
45
46 #system to display main content
47 def _get_tags_cache_json():#service routine used by views requiring tag list in the javascript space
48     """returns list of all tags in json format
49     no caching yet, actually
50     """
51     tags = Tag.objects.filter(deleted=False).all()
52     tags_list = []
53     for tag in tags:
54         dic = {'n': tag.name, 'c': tag.used_count}
55         tags_list.append(dic)
56     tags = simplejson.dumps(tags_list)
57     return tags
58
59 @decorators.render('index.html')
60 def index(request):
61     return question_list(request, Question.objects.all(), sort='latest', base_path=reverse('questions'))
62
63 @decorators.render('questions.html', 'unanswered')
64 def unanswered(request):
65     return question_list(request, Question.objects.filter(answer_accepted=False),
66                          _('Open questions without an accepted answer'))
67
68 @decorators.render('questions.html', 'questions')
69 def questions(request):
70     return question_list(request, Question.objects.all())
71
72 @decorators.render('questions.html')
73 def tag(request, tag):
74     return question_list(request, Question.objects.filter(tags__name=unquote(tag)),
75                         mark_safe(_('Questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}))
76
77 @decorators.list('questions', QUESTIONS_PAGE_SIZE)
78 def question_list(request, initial, list_description=_('questions'), sort=None, base_path=None):
79     pagesize = request.utils.page_size(QUESTIONS_PAGE_SIZE)
80     page = int(request.GET.get('page', 1))
81
82     questions = initial.filter(deleted=False)
83
84     if request.user.is_authenticated():
85         questions = questions.filter(
86                 ~Q(tags__id__in=request.user.marked_tags.filter(user_selections__reason='bad')))
87
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":"-answer_count", "mostvoted":"-score" }
94
95     questions=questions.order_by(view_dic.get(sort, '-added_at'))
96
97     return {
98         "questions" : questions,
99         "questions_count" : questions.count(),
100         "tags_autocomplete" : _get_tags_cache_json(),
101         "list_description": list_description,
102         "base_path" : base_path,
103         }
104
105
106 def search(request):
107     if request.method == "GET" and "q" in request.GET:
108         keywords = request.GET.get("q")
109         search_type = request.GET.get("t")
110         
111         if not keywords:
112             return HttpResponseRedirect(reverse(index))
113         if search_type == 'tag':
114             return HttpResponseRedirect(reverse('tags') + '?q=%s' % (keywords.strip()))
115         elif search_type == "user":
116             return HttpResponseRedirect(reverse('users') + '?q=%s' % (keywords.strip()))
117         elif search_type == "question":
118             return question_search(request, keywords)
119     else:
120         return render_to_response("search.html", context_instance=RequestContext(request))
121
122 @decorators.render('questions.html')
123 def question_search(request, keywords):
124     def question_search(keywords, orderby):
125         return Question.objects.filter(Q(title__icontains=keywords) | Q(html__icontains=keywords))
126
127     from forum.modules import get_handler
128
129     question_search = get_handler('question_search', question_search)
130     initial = question_search(keywords)
131
132     return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
133             base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)))
134     
135
136 def tags(request):#view showing a listing of available tags - plain list
137     stag = ""
138     is_paginated = True
139     sortby = request.GET.get('sort', 'used')
140     try:
141         page = int(request.GET.get('page', '1'))
142     except ValueError:
143         page = 1
144
145     if request.method == "GET":
146         stag = request.GET.get("q", "").strip()
147         if stag != '':
148             objects_list = Paginator(Tag.objects.filter(deleted=False).exclude(used_count=0).extra(where=['name like %s'], params=['%' + stag + '%']), DEFAULT_PAGE_SIZE)
149         else:
150             if sortby == "name":
151                 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("name"), DEFAULT_PAGE_SIZE)
152             else:
153                 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("-used_count"), DEFAULT_PAGE_SIZE)
154
155     try:
156         tags = objects_list.page(page)
157     except (EmptyPage, InvalidPage):
158         tags = objects_list.page(objects_list.num_pages)
159
160     return render_to_response('tags.html', {
161                                             "tags" : tags,
162                                             "stag" : stag,
163                                             "tab_id" : sortby,
164                                             "keywords" : stag,
165                                             "context" : {
166                                                 'is_paginated' : is_paginated,
167                                                 'pages': objects_list.num_pages,
168                                                 'page': page,
169                                                 'has_previous': tags.has_previous(),
170                                                 'has_next': tags.has_next(),
171                                                 'previous': tags.previous_page_number(),
172                                                 'next': tags.next_page_number(),
173                                                 'base_url' : reverse('tags') + '?sort=%s&' % sortby
174                                             }
175                                 }, context_instance=RequestContext(request))
176
177 def get_answer_sort_order(request):
178     view_dic = {"latest":"-added_at", "oldest":"added_at", "votes":"-score" }
179
180     view_id = request.GET.get('sort', request.session.get('answer_sort_order', None))
181
182     if view_id is None or not view_id in view_dic:
183         view_id = "votes"
184
185     if view_id != request.session.get('answer_sort_order', None):
186         request.session['answer_sort_order'] = view_id
187
188     return (view_id, view_dic[view_id])
189
190 def update_question_view_times(request, question):
191     if not 'question_view_times' in request.session:
192         request.session['question_view_times'] = {}
193
194     last_seen = request.session['question_view_times'].get(question.id,None)
195     updated_when, updated_who = question.get_last_update_info()
196
197     if not last_seen or last_seen < updated_when:
198         question.view_count = question.view_count + 1
199         question_view.send(sender=update_question_view_times, instance=question, user=request.user)
200
201     request.session['question_view_times'][question.id] = datetime.datetime.now()
202
203 def question(request, id, slug):
204     question = get_object_or_404(Question, id=id)
205
206     if slug != urlquote(slugify(question.title)):
207         return HttpResponseRedirect(question.get_absolute_url())
208
209     page = int(request.GET.get('page', 1))
210     view_id, order_by = get_answer_sort_order(request)
211
212     if question.deleted and not request.user.can_view_deleted_post(question):
213         raise Http404
214
215     answer_form = AnswerForm(question,request.user)
216     answers = request.user.get_visible_answers(question)
217
218     if answers is not None:
219         answers = [a for a in answers.order_by("-accepted", order_by)
220                    if not a.deleted or a.author == request.user]
221
222     objects_list = Paginator(answers, ANSWERS_PAGE_SIZE)
223     page_objects = objects_list.page(page)
224
225     update_question_view_times(request, question)
226
227     if request.user.is_authenticated():
228         try:
229             subscription = QuestionSubscription.objects.get(question=question, user=request.user)
230         except:
231             subscription = False
232     else:
233         subscription = False
234
235     return render_to_response('question.html', {
236         "question" : question,
237         "answer" : answer_form,
238         "answers" : page_objects.object_list,
239         "tags" : question.tags.all(),
240         "tab_id" : view_id,
241         "similar_questions" : question.get_related_questions(),
242         "subscription": subscription,
243         "context" : {
244             'is_paginated' : True,
245             'pages': objects_list.num_pages,
246             'page': page,
247             'has_previous': page_objects.has_previous(),
248             'has_next': page_objects.has_next(),
249             'previous': page_objects.previous_page_number(),
250             'next': page_objects.next_page_number(),
251             'base_url' : request.path + '?sort=%s&' % view_id,
252             'extend_url' : "#sort-top"
253         }
254         }, context_instance=RequestContext(request))
255
256
257 QUESTION_REVISION_TEMPLATE = ('<h1>%(title)s</h1>\n'
258                               '<div class="text">%(html)s</div>\n'
259                               '<div class="tags">%(tags)s</div>')
260 def question_revisions(request, id):
261     post = get_object_or_404(Question, id=id)
262     revisions = list(post.revisions.all())
263     revisions.reverse()
264     for i, revision in enumerate(revisions):
265         revision.html = QUESTION_REVISION_TEMPLATE % {
266             'title': revision.title,
267             'html': sanitize_html(markdowner.convert(revision.text)),
268             'tags': ' '.join(['<a class="post-tag">%s</a>' % tag
269                               for tag in revision.tagnames.split(' ')]),
270         }
271         if i > 0:
272             revisions[i].diff = htmldiff(revisions[i-1].html, revision.html)
273         else:
274             revisions[i].diff = QUESTION_REVISION_TEMPLATE % {
275                 'title': revisions[0].title,
276                 'html': sanitize_html(markdowner.convert(revisions[0].text)),
277                 'tags': ' '.join(['<a class="post-tag">%s</a>' % tag
278                                  for tag in revisions[0].tagnames.split(' ')]),
279             }
280             revisions[i].summary = _('initial version') 
281     return render_to_response('revisions_question.html', {
282                               'post': post,
283                               'revisions': revisions,
284                               }, context_instance=RequestContext(request))
285
286 ANSWER_REVISION_TEMPLATE = ('<div class="text">%(html)s</div>')
287 def answer_revisions(request, id):
288     post = get_object_or_404(Answer, id=id)
289     revisions = list(post.revisions.all())
290     revisions.reverse()
291     for i, revision in enumerate(revisions):
292         revision.html = ANSWER_REVISION_TEMPLATE % {
293             'html': sanitize_html(markdowner.convert(revision.text))
294         }
295         if i > 0:
296             revisions[i].diff = htmldiff(revisions[i-1].html, revision.html)
297         else:
298             revisions[i].diff = revisions[i].text
299             revisions[i].summary = _('initial version')
300     return render_to_response('revisions_answer.html', {
301                               'post': post,
302                               'revisions': revisions,
303                               }, context_instance=RequestContext(request))
304