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