Simple upgrades.
[wolnelektury.git] / apps / wolnelektury_core / 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 datetime
6 import feedparser
7
8 from django.contrib import auth
9 from django.contrib.auth.decorators import login_required
10 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
11 from django.core.cache import cache
12 from django.http import HttpResponse, HttpResponseRedirect
13 from django.shortcuts import render_to_response
14 from django.template import RequestContext
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 django.conf import settings
20 from ajaxable.utils import AjaxableFormView
21 from catalogue.models import Book
22 from ajaxable.utils import placeholdized
23 from social.templatetags.social_tags import choose_cite
24
25
26 def main_page(request):
27     last_published = Book.objects.exclude(cover_thumb='').filter(parent=None).order_by('-created_at')[:4]
28     cite = choose_cite(RequestContext(request))
29
30     return render_to_response("main_page.html", locals(),
31         context_instance=RequestContext(request))
32
33
34 class LoginFormView(AjaxableFormView):
35     form_class = AuthenticationForm
36     template = "auth/login.html"
37     placeholdize = True
38     title = _('Sign in')
39     submit = _('Sign in')
40     ajax_redirect = True
41
42     def __call__(self, request):
43         if request.user.is_authenticated():
44             return self.redirect_or_refresh(request, '/',
45                 message=_('Already logged in as user %(user)s', ) %
46                             {'user': request.user.username})
47         return super(LoginFormView, self).__call__(request)
48
49     def success(self, form, request):
50         auth.login(request, form.get_user())
51
52
53 class RegisterFormView(AjaxableFormView):
54     form_class = UserCreationForm
55     template = "auth/register.html"
56     placeholdize = True
57     title = _('Register')
58     submit = _('Register')
59     ajax_redirect = True
60     form_prefix = 'register'
61     honeypot = True
62
63     def __call__(self, request):
64         if request.user.is_authenticated():
65             return self.redirect_or_refresh(request, '/',
66                 message=_('Already logged in as user %(user)s', ) %
67                             {'user': request.user.username})
68         return super(RegisterFormView, self).__call__(request)
69
70     def success(self, form, request):
71         form.save()
72         user = auth.authenticate(
73             username=form.cleaned_data['username'],
74             password=form.cleaned_data['password1']
75         )
76         auth.login(request, user)
77
78
79 class LoginRegisterFormView(LoginFormView):
80     template = 'auth/login_register.html'
81     title = _('You have to be logged in to continue')
82
83     def extra_context(self, request, obj):
84         return {
85             "register_form": placeholdized(UserCreationForm(prefix='register')),
86             "register_submit": _('Register'),
87         }
88
89
90 @never_cache
91 def logout_then_redirect(request):
92     auth.logout(request)
93     return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
94
95
96 @never_cache
97 def clock(request):
98     """ Provides server UTC time for jquery.countdown,
99     in a format suitable for Date.parse()
100     """
101     return HttpResponse(datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S UTC'))
102
103
104 def publish_plan(request):
105     cache_key = "publish_plan"
106     plan = cache.get(cache_key)
107
108     if plan is None:
109         plan = []
110         try:
111             feed = feedparser.parse(settings.PUBLISH_PLAN_FEED)
112         except:
113             pass
114         else:
115             for i in range(len(feed['entries'])):
116                 plan.append({
117                     'title': feed['entries'][i].title,
118                     'link': feed['entries'][i].link,
119                     })
120         cache.set(cache_key, plan, 1800)
121
122     return render_to_response("publish_plan.html", {'plan': plan},
123         context_instance=RequestContext(request))
124
125
126 @login_required
127 def user_settings(request):
128     return render_to_response("user.html",
129         context_instance=RequestContext(request))