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