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