b32c64c526429678475520fffd5baf8d5ded90e8
[wolnelektury.git] / src / wolnelektury / views.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from datetime import date, datetime
5 import feedparser
6 from allauth.socialaccount.views import SignupView
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 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, Collection, Tag, Fragment
22 from ssify import ssi_included
23
24 from social.utils import get_or_choose_cite
25 from wolnelektury.forms import RegistrationForm, SocialSignupForm
26
27
28 def main_page(request):
29     ctx = {
30         'last_published': Book.objects.exclude(cover_thumb='').filter(parent=None).order_by('-created_at')[:6],
31         'theme_books': [],
32     }
33
34     # FIXME: find this theme and books properly.
35     if Fragment.objects.exists():
36         while True:
37             ctx['theme'] = Tag.objects.filter(category='theme').order_by('?')[:1][0]
38             tf = Fragment.tagged.with_any([ctx['theme']]).select_related('book').order_by('?')[:100]
39             if not tf:
40                 continue
41             ctx['theme_fragment'] = tf[0]
42             for f in tf:
43                 if f.book not in ctx['theme_books']:
44                     ctx['theme_books'].append(f.book)
45                 if len(ctx['theme_books']) == 3:
46                     break
47             break
48
49     # Choose a collection for main.
50     try:
51         ctx['collection'] = Collection.objects.order_by('?')[:1][0]
52     except IndexError:
53         pass
54
55     ctx['best'] = Book.objects.order_by('?')[:5]
56
57     return render(request, "main_page.html", ctx)
58
59
60 class LoginFormView(AjaxableFormView):
61     form_class = AuthenticationForm
62     template = "auth/login.html"
63     placeholdize = True
64     title = _('Sign in')
65     submit = _('Sign in')
66     ajax_redirect = True
67
68     def __call__(self, request):
69         if request.user.is_authenticated():
70             return self.redirect_or_refresh(
71                 request, '/',
72                 message=_('Already logged in as user %(user)s', ) % {'user': request.user.username})
73         return super(LoginFormView, self).__call__(request)
74
75     def success(self, form, request):
76         auth.login(request, form.get_user())
77
78
79 class RegisterFormView(AjaxableFormView):
80     form_class = RegistrationForm
81     template = "auth/register.html"
82     placeholdize = True
83     title = _('Register')
84     submit = _('Register')
85     ajax_redirect = True
86     form_prefix = 'register'
87     honeypot = True
88
89     def __call__(self, request):
90         if request.user.is_authenticated():
91             return self.redirect_or_refresh(
92                 request, '/',
93                 message=_('Already logged in as user %(user)s', ) % {'user': request.user.username})
94         return super(RegisterFormView, self).__call__(request)
95
96     def success(self, form, request):
97         form.save()
98         user = auth.authenticate(
99             username=form.cleaned_data['username'],
100             password=form.cleaned_data['password1']
101         )
102         auth.login(request, user)
103
104
105 class LoginRegisterFormView(LoginFormView):
106     template = 'auth/login_register.html'
107     title = _('You have to be logged in to continue')
108
109     def extra_context(self, request, obj):
110         return {
111             "register_form": placeholdized(RegistrationForm(prefix='register')),
112             "register_submit": _('Register'),
113         }
114
115
116 @never_cache
117 def logout_then_redirect(request):
118     auth.logout(request)
119     return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
120
121
122 @never_cache
123 def clock(request):
124     """ Provides server UTC time for jquery.countdown,
125     in a format suitable for Date.parse()
126     """
127     return HttpResponse(datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S UTC'))
128
129
130 def publish_plan(request):
131     cache_key = "publish_plan"
132     plan = cache.get(cache_key)
133
134     if plan is None:
135         plan = []
136         try:
137             feed = feedparser.parse(settings.PUBLISH_PLAN_FEED)
138         except:
139             pass
140         else:
141             for i in range(len(feed['entries'])):
142                 plan.append({
143                     'title': feed['entries'][i].title,
144                     'link': feed['entries'][i].link,
145                     })
146         cache.set(cache_key, plan, 1800)
147
148     return render(request, "publish_plan.html", {'plan': plan})
149
150
151 @login_required
152 def user_settings(request):
153     return render(request, "user.html")
154
155
156 @ssi_included(use_lang=False, timeout=1800)
157 def latest_blog_posts(request, feed_url=None, posts_to_show=5):
158     if feed_url is None:
159         feed_url = settings.LATEST_BLOG_POSTS
160     try:
161         feed = feedparser.parse(str(feed_url))
162         posts = []
163         for i in range(posts_to_show):
164             pub_date = feed['entries'][i].published_parsed
165             published = date(pub_date[0], pub_date[1], pub_date[2])
166             posts.append({
167                 'title': feed['entries'][i].title,
168                 'summary': feed['entries'][i].summary,
169                 'link': feed['entries'][i].link,
170                 'date': published,
171                 })
172     except:
173         posts = []
174     return render(request, 'latest_blog_posts.html', {'posts': posts})
175
176
177 @ssi_included(use_lang=False)
178 def widget(request):
179     return render(request, 'widget.html')
180
181
182 class SocialSignupView(SignupView):
183     form_class = SocialSignupForm
184
185
186 def exception_test(request):
187     msg = request.GET.get('msg')
188     if msg:
189         raise Exception('Exception test: %s' % msg)
190     else:
191         raise Exception('Exception test')
192
193
194 def post_test(request):
195     return render(request, 'post_test.html', {'action': '/api/reading/jego-zasady/complete/'})