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