2cc0fd79998a6989fedff731b2ea8033a9004a3e
[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
23 from social.utils import get_or_choose_cite
24 from wolnelektury.forms import RegistrationForm, SocialSignupForm
25
26
27 @never_cache
28 def main_page(request):
29     ctx = {
30         'last_published': Book.objects.exclude(cover_thumb='').filter(findable=True, 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').filter(book__findable=True).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 collections for main.
50     ctx['collections'] = Collection.objects.filter(listed=True).order_by('?')[:4]
51
52     best = []
53     best_places = 5
54     for recommended in Collection.objects.filter(listed=True, role='recommend').order_by('?'):
55         books = list(recommended.get_books().exclude(id__in=[b.id for b in best]).order_by('?')[:best_places])
56         best.extend(books)
57         best_places -= len(books)
58         if not best_places:
59             break
60     if best_places:
61         best.extend(
62             list(
63                 Book.objects.filter(findable=True).exclude(id__in=[b.id for b in best]).order_by('?')[:best_places]
64             )
65         )
66     ctx['best'] = best
67
68     return render(request, "main_page.html", ctx)
69
70
71 class LoginFormView(AjaxableFormView):
72     form_class = AuthenticationForm
73     template = "auth/login.html"
74     placeholdize = True
75     title = _('Sign in')
76     submit = _('Sign in')
77     ajax_redirect = True
78
79     def __call__(self, request):
80         if request.user.is_authenticated:
81             return self.redirect_or_refresh(
82                 request, '/',
83                 message=_('Already logged in as user %(user)s', ) % {'user': request.user.username})
84         return super(LoginFormView, self).__call__(request)
85
86     def success(self, form, request):
87         auth.login(request, form.get_user())
88
89
90 class RegisterFormView(AjaxableFormView):
91     form_class = RegistrationForm
92     template = "auth/register.html"
93     placeholdize = True
94     title = _('Register')
95     submit = _('Register')
96     ajax_redirect = True
97     form_prefix = 'register'
98     honeypot = True
99
100     def __call__(self, request):
101         if request.user.is_authenticated:
102             return self.redirect_or_refresh(
103                 request, '/',
104                 message=_('Already logged in as user %(user)s', ) % {'user': request.user.username})
105         return super(RegisterFormView, self).__call__(request)
106
107     def success(self, form, request):
108         form.save()
109         user = auth.authenticate(
110             username=form.cleaned_data['username'],
111             password=form.cleaned_data['password1']
112         )
113         auth.login(request, user)
114
115
116 class LoginRegisterFormView(LoginFormView):
117     template = 'auth/login_register.html'
118     title = _('You have to be logged in to continue')
119
120     def extra_context(self, request, obj):
121         return {
122             "register_form": placeholdized(RegistrationForm(prefix='register')),
123             "register_submit": _('Register'),
124         }
125
126
127 @never_cache
128 def logout_then_redirect(request):
129     auth.logout(request)
130     return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
131
132
133 @never_cache
134 def clock(request):
135     """ Provides server UTC time for jquery.countdown,
136     in a format suitable for Date.parse()
137     """
138     return HttpResponse(datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S UTC'))
139
140
141 def publish_plan(request):
142     cache_key = "publish_plan"
143     plan = cache.get(cache_key)
144
145     if plan is None:
146         plan = []
147         try:
148             feed = feedparser.parse(settings.PUBLISH_PLAN_FEED)
149         except:
150             pass
151         else:
152             for i in range(len(feed['entries'])):
153                 plan.append({
154                     'title': feed['entries'][i].title,
155                     'link': feed['entries'][i].link,
156                     })
157         cache.set(cache_key, plan, 1800)
158
159     return render(request, "publish_plan.html", {'plan': plan})
160
161
162 @login_required
163 def user_settings(request):
164     return render(request, "user.html")
165
166
167 def widget(request):
168     return render(request, 'widget.html')
169
170
171 class SocialSignupView(SignupView):
172     form_class = SocialSignupForm
173
174
175 def exception_test(request):
176     msg = request.GET.get('msg')
177     if msg:
178         raise Exception('Exception test: %s' % msg)
179     else:
180         raise Exception('Exception test')
181
182
183 def post_test(request):
184     return render(request, 'post_test.html', {'action': '/api/reading/jego-zasady/complete/'})