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