51371735ae74ad06a1abfdc4acabe2bae4f5fff7
[wolnelektury.git] / src / wolnelektury / views.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from datetime import date, datetime
6 import feedparser
7
8 from django.conf import settings
9 from django.contrib import auth
10 from django.contrib.auth.decorators import login_required
11 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
12 from django.core.cache import cache
13 from django.http import HttpResponse, HttpResponseRedirect
14 from django.shortcuts import render
15 from django.utils.http import urlquote_plus
16 from django.utils.translation import ugettext_lazy as _
17 from django.views.decorators.cache import never_cache
18
19 from ajaxable.utils import AjaxableFormView
20 from ajaxable.utils import placeholdized
21 from catalogue.models import Book
22 from ssify import ssi_included
23
24
25 def main_page(request):
26     last_published = Book.objects.exclude(cover_thumb='').filter(parent=None).order_by('-created_at')[:4]
27
28     return render(request, "main_page.html", {
29         'last_published': last_published,
30     })
31
32
33 class LoginFormView(AjaxableFormView):
34     form_class = AuthenticationForm
35     template = "auth/login.html"
36     placeholdize = True
37     title = _('Sign in')
38     submit = _('Sign in')
39     ajax_redirect = True
40
41     def __call__(self, request):
42         if request.user.is_authenticated():
43             return self.redirect_or_refresh(request, '/',
44                 message=_('Already logged in as user %(user)s', ) %
45                             {'user': request.user.username})
46         return super(LoginFormView, self).__call__(request)
47
48     def success(self, form, request):
49         auth.login(request, form.get_user())
50
51
52 class RegisterFormView(AjaxableFormView):
53     form_class = UserCreationForm
54     template = "auth/register.html"
55     placeholdize = True
56     title = _('Register')
57     submit = _('Register')
58     ajax_redirect = True
59     form_prefix = 'register'
60     honeypot = True
61
62     def __call__(self, request):
63         if request.user.is_authenticated():
64             return self.redirect_or_refresh(request, '/',
65                 message=_('Already logged in as user %(user)s', ) %
66                             {'user': request.user.username})
67         return super(RegisterFormView, self).__call__(request)
68
69     def success(self, form, request):
70         form.save()
71         user = auth.authenticate(
72             username=form.cleaned_data['username'],
73             password=form.cleaned_data['password1']
74         )
75         auth.login(request, user)
76
77
78 class LoginRegisterFormView(LoginFormView):
79     template = 'auth/login_register.html'
80     title = _('You have to be logged in to continue')
81
82     def extra_context(self, request, obj):
83         return {
84             "register_form": placeholdized(UserCreationForm(prefix='register')),
85             "register_submit": _('Register'),
86         }
87
88
89 @never_cache
90 def logout_then_redirect(request):
91     auth.logout(request)
92     return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
93
94
95 @never_cache
96 def clock(request):
97     """ Provides server UTC time for jquery.countdown,
98     in a format suitable for Date.parse()
99     """
100     return HttpResponse(datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S UTC'))
101
102
103 def publish_plan(request):
104     cache_key = "publish_plan"
105     plan = cache.get(cache_key)
106
107     if plan is None:
108         plan = []
109         try:
110             feed = feedparser.parse(settings.PUBLISH_PLAN_FEED)
111         except:
112             pass
113         else:
114             for i in range(len(feed['entries'])):
115                 plan.append({
116                     'title': feed['entries'][i].title,
117                     'link': feed['entries'][i].link,
118                     })
119         cache.set(cache_key, plan, 1800)
120
121     return render(request, "publish_plan.html", {'plan': plan})
122
123
124 @login_required
125 def user_settings(request):
126     return render(request, "user.html")
127
128
129 @ssi_included(use_lang=False, timeout=1800)
130 def latest_blog_posts(request, feed_url=None, posts_to_show=5):
131     if feed_url is None:
132         feed_url = settings.LATEST_BLOG_POSTS
133     try:
134         feed = feedparser.parse(str(feed_url))
135         posts = []
136         for i in range(posts_to_show):
137             pub_date = feed['entries'][i].published_parsed
138             published = date(pub_date[0], pub_date[1], pub_date[2])
139             posts.append({
140                 'title': feed['entries'][i].title,
141                 'summary': feed['entries'][i].summary,
142                 'link': feed['entries'][i].link,
143                 'date': published,
144                 })
145     except:
146         posts = []
147     return render(request, 'latest_blog_posts.html', {'posts': posts})
148
149
150 @ssi_included(use_lang=False)
151 def widget(request):
152     return render(request, 'widget.html')