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