views.py 4.43 KB
Newer Older
1
from pathlib import Path
2
from threading import Thread
3

4
from django.conf import settings
Claude Paroz's avatar
Claude Paroz committed
5
from django.contrib.auth.views import LoginView as AuthLoginView
6
from django.contrib import messages
7 8
from django.core.management import call_command
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect, Http404
9
from django.shortcuts import render
10
from django.template.loader import get_template, TemplateDoesNotExist
11
from django.urls import reverse
12
from django.utils.translation import ugettext as _
13
from django.views.decorators.csrf import csrf_exempt
14

15
from people.models import Person, obfuscate_email
16
from teams.models import Role
17
from people.forms import LoginForm, RegistrationForm
18
from .utils import get_user_locale, run_shell_command
19

20

21
def index(request):
22
    """ Homepage view """
23 24 25 26 27 28 29 30
    curlang = get_user_locale(request)

    context = {
        'pageSection': 'home',
        'user_language': curlang,
    }
    return render(request, 'index.html', context)

31

32
def about(request):
33
    translator_credits = _("translator-credits")
34
    if translator_credits == "translator-credits":
35 36
        translator_credits = ''
    else:
37
        translator_credits = [obfuscate_email(line) for line in translator_credits.split('\n')]
38 39
    context = {
        'pageSection': 'home',
40
        'translator_credits': translator_credits,
41
    }
42
    return render(request, 'about.html', context)
43

44

Claude Paroz's avatar
Claude Paroz committed
45 46
class LoginView(AuthLoginView):
    form_class = LoginForm
47 48 49 50 51 52 53
    redirect_field_name = 'referer'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if not context['referer']:
            context['referer'] = self.request.META.get('HTTP_REFERER', '')
        return context
54

55 56 57 58 59 60
    def get_redirect_url(self):
        url = super().get_redirect_url()
        if not url:
            url = self.request.META.get('HTTP_REFERER', '')
        return url

Claude Paroz's avatar
Claude Paroz committed
61 62 63 64 65 66 67 68 69
    def form_valid(self, form):
        response = super().form_valid(form)
        if Role.objects.filter(person__username=self.request.user.username).count() < 1:
            message = _("You have not joined any translation team yet. "
                        "You can do it from <a href=\"%(url)s\">your profile</a>.") % {
                'url': reverse('person_team_join'),
            }
            messages.info(self.request, message)
        return response
70

71 72 73 74
    def form_invalid(self, form):
        messages.error(self.request, _("Login unsuccessful. Please verify your username and password."))
        return super().form_invalid(form)

75

76 77
def site_register(request):
    if request.method == 'POST':
Claude Paroz's avatar
Claude Paroz committed
78
        form = RegistrationForm(data=request.POST)
79
        if form.is_valid():
80
            form.save(request)
81 82 83 84 85 86 87
            return HttpResponseRedirect(reverse('register_success'))
    else:
        form = RegistrationForm()
    context = {
        'pageSection': 'home',
        'form': form,
    }
88
    return render(request, 'registration/register.html', context)
89

Claude Paroz's avatar
Claude Paroz committed
90

91 92 93 94 95
def activate_account(request, key):
    """ Activate an account through the link a requestor has received by email """
    try:
        person = Person.objects.get(activation_key=key)
    except Person.DoesNotExist:
96
        return render(request, 'error.html', {'error': _("Sorry, the key you provided is not valid.")})
97
    person.activate()
98
    messages.success(request, _("Your account has been activated."))
Claude Paroz's avatar
Claude Paroz committed
99 100
    return HttpResponseRedirect(reverse('login'))

101

102
def help(request, topic, modal):
103 104
    template = 'help/%s.html' % topic
    try:
105
        get_template(template)
106 107
    except TemplateDoesNotExist:
        raise Http404
108 109 110
    return render(request, template, {
        'base': 'base_modal.html' if modal and int(modal) else 'base.html'
    })
111 112


113 114
# CSRF skipped, verification using a secret token.
@csrf_exempt
115 116 117 118 119 120 121 122 123 124
def pull_code(request):
    """GitLab Webhok endpoint to update code after a repository push."""
    verified = (
        request.method == 'POST' and
        request.META.get('HTTP_X_GITLAB_EVENT') == 'Push Hook' and
        request.META.get('HTTP_X_GITLAB_TOKEN') == settings.GITLAB_TOKEN
    )
    if not verified:
        return HttpResponseForbidden()

125 126 127
    # Run effective work in a separate thread to prevent timeouts
    thread = Thread(target=pull_code_real)
    thread.start()
128
    return HttpResponse('OK')
129 130 131 132 133 134 135


def pull_code_real():
    cwd = Path(settings.BASE_DIR) / 'damnedlies'
    run_shell_command(['git', 'pull', '--rebase'], cwd=cwd)
    call_command('compile-trans', verbosity=0)
    run_shell_command(['touch', 'wsgi.py'], cwd=cwd)