<commit_before>##
#    Copyright (C) 2013-2014 <NAME> & <NAME>
#
#    This file is part of Inboxen.
#
#    Inboxen is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Inboxen is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with Inboxen.  If not, see <http://www.gnu.org/licenses/>.
##

from datetime import datetime

from django import forms
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import PasswordChangeForm, UserCreationForm
from django.core import exceptions
from django.utils.translation import ugettext as _

from ratelimitbackend.forms import AuthenticationForm
from pytz import utc

from inboxen import models
from queue.delete.tasks import delete_account
from queue.liberate.tasks import liberate as data_liberate
from website import fields
from website.forms.mixins import BootstrapFormMixin, PlaceHolderMixin, SROnlyLabelMixin

__all__ = ["DeleteAccountForm", "LiberationForm",
            "PlaceHolderAuthenticationForm", "PlaceHolderPasswordChangeForm",
            "PlaceHolderUserCreationForm", "RestoreSelectForm", "SettingsForm",
            "UsernameChangeForm",
            ]

class DeleteAccountForm(BootstrapFormMixin, forms.Form):

    username = forms.CharField(
        label=_("Please type your username to confirm"),
        widget=forms.TextInput(attrs={'placeholder': _('Username')}),
        required=False,
    )

    def __init__(self, request, *args, **kwargs):
        self.user = request.user
        self.request = request
        return super(DeleteAccountForm, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        cleaned_data = super(DeleteAccountForm, self).clean(*args, **kwargs)
        if cleaned_data.get("username", "") != self.user.get_username():
            raise exceptions.ValidationError(_("The username entered does not match your username"))

        return cleaned_data

    def save(self, *args, **kwargs):
        # Dispatch task and logout
        delete_account.delay(self.user.id)
        auth.logout(self.request)
        return self.user

class LiberationForm(BootstrapFormMixin, forms.ModelForm):
    class Meta:
        model = models.Inbox
        fields = []

    STORAGE_TYPES = (
        (0, _("Maildir")),
        (1, _("Mailbox .mbox")),
    )

    # Could we support zip files?
    COMPRESSION_TYPES = (
        (0, _("Tarball (gzip compressed)")),
        (1, _("Tarball (bzip2 compression)")),
        (2, _("Tarball (no compression)")),
    )

    storage_type = forms.ChoiceField(choices=STORAGE_TYPES)
    compression_type = forms.ChoiceField(choices=COMPRESSION_TYPES)

    def __init__(self, user, initial=None, *args, **kwargs):
        self.user = user
        if not initial:
            initial = {
                "storage_type": 0,
                "compression_type": 0,
            }

        return super(LiberationForm, self).__init__(initial=initial, *args, **kwargs)

    def save(self):
        lib_status = self.user.liberation
        if not lib_status.flags.running:
            lib_status.flags = models.Liberation.flags.running
            lib_status.started = datetime.now(utc)

            result = data_liberate.apply_async(
                                    kwargs={"user_id": self.user.id, "options": self.cleaned_data},
                                    countdown=10
                                    )

            lib_status.async_result = result.id
            lib_status.save()

        return self.user

class PlaceHolderAuthenticationForm(BootstrapFormMixin, SROnlyLabelMixin,
                        PlaceHolderMixin, AuthenticationForm):
    """Same as auth.forms.AuthenticationForm but adds a label as the placeholder
    in each field and marks labels as sr-only"""
    pass

class PlaceHolderPasswordChangeForm(BootstrapFormMixin, SROnlyLabelMixin,
                        PlaceHolderMixin, PasswordChangeForm):
    """Same as auth.forms.PasswordChangeForm but adds a label as the placeholder in each field"""
    new_password1 = fields.PasswordCheckField(label=_("New password"))

class PlaceHolderUserCreationForm(BootstrapFormMixin, SROnlyLabelMixin,
                        PlaceHolderMixin, UserCreationForm):
    """Same as auth.forms.UserCreationForm but adds a label as the placeholder in each field"""
    password1 = fields.PasswordCheckField(label=_("Password"))

    def clean_username(self):
        username = self.cleaned_data["username"]
        if get_user_model().objects.filter(username__iexact=username).exists():
            raise exceptions.ValidationError(
                self.error_messages['duplicate_username'],
                code='duplicate_username',
                )
<commit_msg>Return username at end of clean_username method!<commit_after>##
#    Copyright (C) 2013-2014 <NAME> & <NAME>
#
#    This file is part of Inboxen.
#
#    Inboxen is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Inboxen is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with Inboxen.  If not, see <http://www.gnu.org/licenses/>.
##

from datetime import datetime

from django import forms
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import PasswordChangeForm, UserCreationForm
from django.core import exceptions
from django.utils.translation import ugettext as _

from ratelimitbackend.forms import AuthenticationForm
from pytz import utc

from inboxen import models
from queue.delete.tasks import delete_account
from queue.liberate.tasks import liberate as data_liberate
from website import fields
from website.forms.mixins import BootstrapFormMixin, PlaceHolderMixin, SROnlyLabelMixin

__all__ = ["DeleteAccountForm", "LiberationForm",
            "PlaceHolderAuthenticationForm", "PlaceHolderPasswordChangeForm",
            "PlaceHolderUserCreationForm", "RestoreSelectForm", "SettingsForm",
            "UsernameChangeForm",
            ]

class DeleteAccountForm(BootstrapFormMixin, forms.Form):

    username = forms.CharField(
        label=_("Please type your username to confirm"),
        widget=forms.TextInput(attrs={'placeholder': _('Username')}),
        required=False,
    )

    def __init__(self, request, *args, **kwargs):
        self.user = request.user
        self.request = request
        return super(DeleteAccountForm, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        cleaned_data = super(DeleteAccountForm, self).clean(*args, **kwargs)
        if cleaned_data.get("username", "") != self.user.get_username():
            raise exceptions.ValidationError(_("The username entered does not match your username"))

        return cleaned_data

    def save(self, *args, **kwargs):
        # Dispatch task and logout
        delete_account.delay(self.user.id)
        auth.logout(self.request)
        return self.user

class LiberationForm(BootstrapFormMixin, forms.ModelForm):
    class Meta:
        model = models.Inbox
        fields = []

    STORAGE_TYPES = (
        (0, _("Maildir")),
        (1, _("Mailbox .mbox")),
    )

    # Could we support zip files?
    COMPRESSION_TYPES = (
        (0, _("Tarball (gzip compressed)")),
        (1, _("Tarball (bzip2 compression)")),
        (2, _("Tarball (no compression)")),
    )

    storage_type = forms.ChoiceField(choices=STORAGE_TYPES)
    compression_type = forms.ChoiceField(choices=COMPRESSION_TYPES)

    def __init__(self, user, initial=None, *args, **kwargs):
        self.user = user
        if not initial:
            initial = {
                "storage_type": 0,
                "compression_type": 0,
            }

        return super(LiberationForm, self).__init__(initial=initial, *args, **kwargs)

    def save(self):
        lib_status = self.user.liberation
        if not lib_status.flags.running:
            lib_status.flags = models.Liberation.flags.running
            lib_status.started = datetime.now(utc)

            result = data_liberate.apply_async(
                                    kwargs={"user_id": self.user.id, "options": self.cleaned_data},
                                    countdown=10
                                    )

            lib_status.async_result = result.id
            lib_status.save()

        return self.user

class PlaceHolderAuthenticationForm(BootstrapFormMixin, SROnlyLabelMixin,
                        PlaceHolderMixin, AuthenticationForm):
    """Same as auth.forms.AuthenticationForm but adds a label as the placeholder
    in each field and marks labels as sr-only"""
    pass

class PlaceHolderPasswordChangeForm(BootstrapFormMixin, SROnlyLabelMixin,
                        PlaceHolderMixin, PasswordChangeForm):
    """Same as auth.forms.PasswordChangeForm but adds a label as the placeholder in each field"""
    new_password1 = fields.PasswordCheckField(label=_("New password"))

class PlaceHolderUserCreationForm(BootstrapFormMixin, SROnlyLabelMixin,
                        PlaceHolderMixin, UserCreationForm):
    """Same as auth.forms.UserCreationForm but adds a label as the placeholder in each field"""
    password1 = fields.PasswordCheckField(label=_("Password"))

    def clean_username(self):
        username = self.cleaned_data["username"]
        if get_user_model().objects.filter(username__iexact=username).exists():
            raise exceptions.ValidationError(
                self.error_messages['duplicate_username'],
                code='duplicate_username',
                )
        return username

{'fraction_non_alphanumeric': 0.08957359534484403, 'fraction_numerical': 0.004006486692740628, 'mean_word_length': 2.8988471550762367, 'pattern_counts': {'":': 8, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5127106', 'n_tokens_mistral': 2882, 'n_tokens_neox': 2789, 'n_words': 804}