<commit_before>from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

from models import ZLBVirtualServer, WhitelistIP

import netaddr

class BaseForm(forms.Form):
    @classmethod
    def validator_email(cls):
        return RegexValidator(
            r'^.*@.*$',
            'has to be an email address.',
            'Invalid email'
        )
    
    @classmethod
    def validator_integer(cls):
        return RegexValidator(
            r'^[0-9]+$',
            'has to be an integer.',
            'Invalid integer'
        )
    
    @classmethod
    def validator_whitelist_target(cls, value):
        ip = value.split('/')[0]
        if WhitelistIP.is_ip_in(ip):
            raise ValidationError(u'%s is in the IP Whitelist' % value)

class ComplaintBGPBlockForm(BaseForm):

    # Create a list of default blacklist durations
    durations = [
        (60 * 60,           '1 hour'),
        (60 * 60 * 12,      '12 hours'),
        (60 * 60 * 24,      '1 day'),
        (60 * 60 * 24 * 7,  '1 week'),
        (60 * 60 * 24 * 30, '30 days'),
        (0,                  'Custom...'),
    ]
    duration = forms.ChoiceField(choices=durations)

    target = forms.CharField(
        widget=forms.TextInput( attrs={'size':'43'} ),
        max_length=43,
        validators=[BaseForm.validator_whitelist_target],
    )

    start_date = forms.DateTimeField(required=True)
    end_date = forms.DateTimeField(required=True)

    comment = forms.CharField(
        widget=forms.TextInput( attrs={'size':'50'} ),
        max_length=1024
    )

    bug_number = forms.IntegerField(
        widget=forms.TextInput( attrs={'size':'7'} ),
        required=False
    )

    # clean_target takes the target field (a v4 or v6 IP address, with
    # optional CIDR) and creates validated 'address' and 'cidr'
    # values
    def clean_target(self):
        target = self.cleaned_data['target']
        fields = target.split('/')

        try:
            address = netaddr.ip.IPAddress(fields[0])
        except netaddr.core.AddrFormatError:
            raise forms.ValidationError("Invalid IP address")

        try:
            cidr = int(fields[1])
        except ValueError:
            raise forms.ValidationError("Invalid CIDR value")
        except IndexError:
            if address.version == 4:
                cidr = 32
            else:
                cidr = 128

        if address.version == 4:
            if cidr > 32 or cidr < 16:
                raise forms.ValidationError("Invalid CIDR value")
        elif address.version == 6:
            if cidr > 128 or cidr < 32:
                raise forms.ValidationError("Invalid CIDR value")

        self.cleaned_data['address'] = fields[0]
        self.cleaned_data['cidr'] = cidr
        return target
        

    # Perform any multi-field validation after all individual fields
    # have been cleaned
    def clean(self):
        cleaned_data = self.cleaned_data
        start_date = cleaned_data.get("start_date")
        end_date = cleaned_data.get("end_date")

        if start_date and end_date and end_date < start_date:
            self._errors["end_date"] = self.error_class(["End date must come after start date"])
            del cleaned_data["end_date"]

        return cleaned_data

class ComplaintZLBForm(ComplaintBGPBlockForm):
    select = forms.MultipleChoiceField(
        choices=zip(map(lambda a: str(a['id']),
                        ZLBVirtualServer.objects.values('id')),
                    ['']*ZLBVirtualServer.objects.count()),
        widget=forms.widgets.CheckboxSelectMultiple())

class SettingsForm(BaseForm):
    checkbox_fields = ['notifications_email_enable', 'notifications_irc_enable']<commit_msg>[webui] refactoring virtual server form validation<commit_after>from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

from models import ZLBVirtualServer, WhitelistIP

import netaddr

class BaseForm(forms.Form):
    @classmethod
    def validator_email(cls):
        return RegexValidator(
            r'^.*@.*$',
            'has to be an email address.',
            'Invalid email'
        )
    
    @classmethod
    def validator_integer(cls):
        return RegexValidator(
            r'^[0-9]+$',
            'has to be an integer.',
            'Invalid integer'
        )
    
    @classmethod
    def validator_whitelist_target(cls, value):
        ip = value.split('/')[0]
        if WhitelistIP.is_ip_in(ip):
            raise ValidationError(u'%s is in the IP Whitelist' % value)

class ComplaintBGPBlockForm(BaseForm):

    # Create a list of default blacklist durations
    durations = [
        (60 * 60,           '1 hour'),
        (60 * 60 * 12,      '12 hours'),
        (60 * 60 * 24,      '1 day'),
        (60 * 60 * 24 * 7,  '1 week'),
        (60 * 60 * 24 * 30, '30 days'),
        (0,                  'Custom...'),
    ]
    duration = forms.ChoiceField(choices=durations)

    target = forms.CharField(
        widget=forms.TextInput( attrs={'size':'43'} ),
        max_length=43,
        validators=[BaseForm.validator_whitelist_target],
    )

    start_date = forms.DateTimeField(required=True)
    end_date = forms.DateTimeField(required=True)

    comment = forms.CharField(
        widget=forms.TextInput( attrs={'size':'50'} ),
        max_length=1024
    )

    bug_number = forms.IntegerField(
        widget=forms.TextInput( attrs={'size':'7'} ),
        required=False
    )

    # clean_target takes the target field (a v4 or v6 IP address, with
    # optional CIDR) and creates validated 'address' and 'cidr'
    # values
    def clean_target(self):
        target = self.cleaned_data['target']
        fields = target.split('/')

        try:
            address = netaddr.ip.IPAddress(fields[0])
        except netaddr.core.AddrFormatError:
            raise forms.ValidationError("Invalid IP address")

        try:
            cidr = int(fields[1])
        except ValueError:
            raise forms.ValidationError("Invalid CIDR value")
        except IndexError:
            if address.version == 4:
                cidr = 32
            else:
                cidr = 128

        if address.version == 4:
            if cidr > 32 or cidr < 16:
                raise forms.ValidationError("Invalid CIDR value")
        elif address.version == 6:
            if cidr > 128 or cidr < 32:
                raise forms.ValidationError("Invalid CIDR value")

        self.cleaned_data['address'] = fields[0]
        self.cleaned_data['cidr'] = cidr
        return target
        

    # Perform any multi-field validation after all individual fields
    # have been cleaned
    def clean(self):
        cleaned_data = self.cleaned_data
        start_date = cleaned_data.get("start_date")
        end_date = cleaned_data.get("end_date")

        if start_date and end_date and end_date < start_date:
            self._errors["end_date"] = self.error_class(["End date must come after start date"])
            del cleaned_data["end_date"]

        return cleaned_data

class ComplaintZLBForm(ComplaintBGPBlockForm):
    select = forms.ModelMultipleChoiceField(
        queryset=ZLBVirtualServer.objects.all(),
        widget=forms.CheckboxSelectMultiple)

class SettingsForm(BaseForm):
    checkbox_fields = ['notifications_email_enable', 'notifications_irc_enable']
{'fraction_non_alphanumeric': 0.10484628809236139, 'fraction_numerical': 0.02013693113169553, 'mean_word_length': 2.2293021239705246, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2733106', 'n_tokens_mistral': 2294, 'n_tokens_neox': 2134, 'n_words': 528}