1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from datetime import date, datetime
5 from urllib.parse import quote_plus
7 from allauth.socialaccount.views import SignupView
9 from django.conf import settings
10 from django.contrib import auth
11 from django.contrib.auth.decorators import login_required
12 from django.contrib.auth.forms import AuthenticationForm
13 from django.core.cache import cache
14 from django.http import HttpResponse, HttpResponseRedirect
15 from django.shortcuts import render
16 from django.utils.translation import gettext_lazy as _
17 from django.views.decorators.cache import never_cache
19 from ajaxable.utils import AjaxableFormView
20 from ajaxable.utils import placeholdized
21 from catalogue.models import Book, Collection, Tag, Fragment
23 from social.utils import get_or_choose_cite
24 from wolnelektury.forms import RegistrationForm, SocialSignupForm
28 def main_page(request):
30 'last_published': Book.objects.exclude(cover_thumb='').filter(findable=True, parent=None).order_by('-created_at')[:6],
34 # FIXME: find this theme and books properly.
35 if Fragment.objects.exists():
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]
41 ctx['theme_fragment'] = tf[0]
43 if f.book not in ctx['theme_books']:
44 ctx['theme_books'].append(f.book)
45 if len(ctx['theme_books']) == 3:
49 # Choose collections for main.
50 ctx['collections'] = Collection.objects.filter(listed=True).order_by('?')[:4]
54 recommended_collection = None
55 for recommended in Collection.objects.filter(listed=True, role='recommend').order_by('?'):
56 if recommended_collection is None:
57 recommended_collection = recommended
58 books = list(recommended.get_books().exclude(id__in=[b.id for b in best]).order_by('?')[:best_places])
60 best_places -= len(books)
63 ctx['recommended_collection'] = recommended_collection
67 Book.objects.filter(findable=True).exclude(id__in=[b.id for b in best]).order_by('?')[:best_places]
72 return render(request, "main_page.html", ctx)
75 class LoginFormView(AjaxableFormView):
76 form_class = AuthenticationForm
77 template = "auth/login.html"
83 def __call__(self, request):
84 if request.user.is_authenticated:
85 return self.redirect_or_refresh(
87 message=_('Already logged in as user %(user)s', ) % {'user': request.user.username})
88 return super(LoginFormView, self).__call__(request)
90 def success(self, form, request):
91 auth.login(request, form.get_user())
94 class RegisterFormView(AjaxableFormView):
95 form_class = RegistrationForm
96 template = "auth/register.html"
99 submit = _('Register')
101 form_prefix = 'register'
104 def __call__(self, request):
105 if request.user.is_authenticated:
106 return self.redirect_or_refresh(
108 message=_('Already logged in as user %(user)s', ) % {'user': request.user.username})
109 return super(RegisterFormView, self).__call__(request)
111 def success(self, form, request):
113 user = auth.authenticate(
114 username=form.cleaned_data['username'],
115 password=form.cleaned_data['password1']
117 auth.login(request, user)
120 class LoginRegisterFormView(LoginFormView):
121 template = 'auth/login_register.html'
122 title = _('You have to be logged in to continue')
124 def extra_context(self, request, obj):
126 "register_form": placeholdized(RegistrationForm(prefix='register')),
127 "register_submit": _('Register'),
132 def logout_then_redirect(request):
134 return HttpResponseRedirect(quote_plus(request.GET.get('next', '/'), safe='/?='))
139 """ Provides server UTC time for jquery.countdown,
140 in a format suitable for Date.parse()
142 return HttpResponse(datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S UTC'))
145 def publish_plan(request):
146 cache_key = "publish_plan"
147 plan = cache.get(cache_key)
152 feed = feedparser.parse(settings.PUBLISH_PLAN_FEED)
156 for i in range(len(feed['entries'])):
158 'title': feed['entries'][i].title,
159 'link': feed['entries'][i].link,
161 cache.set(cache_key, plan, 1800)
163 return render(request, "publish_plan.html", {'plan': plan})
167 def user_settings(request):
168 return render(request, "user.html")
172 return render(request, 'widget.html')
175 class SocialSignupView(SignupView):
176 form_class = SocialSignupForm
179 def exception_test(request):
180 msg = request.GET.get('msg')
182 raise Exception('Exception test: %s' % msg)
184 raise Exception('Exception test')
187 def post_test(request):
188 return render(request, 'post_test.html', {'action': '/api/reading/jego-zasady/complete/'})