<commit_before># shrunk - Rutgers University URL Shortener

"""Application forms for shrunk."""

import re

from wtforms import Form, TextField, RadioField, validators, ValidationError

import shrunk.filters

class LinkForm(Form):
    """A WTForm for creating and editing links.

    :Fields:
      - `long_url`: Text field for the original unshrunk URL
      - `title`: Text field for a descriptive link title
    """
    long_url = TextField("URL", validators=[
        validators.DataRequired("You need a link to shrink!"),
        validators.URL(require_tld=True, message="Please enter a valid URL.")
    ])
    title = TextField("Title", validators=[
        validators.DataRequired("Please enter a title.")
    ])
    short_url = TextField("Custom Alias", validators=[
        validators.Length(min=5, max=16, message="""Custom alias length must be
            between %(min)d and %(max)d characters."""),
        validators.Optional(strip_whitespace=False)
    ])

    rejected_regexes = []

    def __init__(self, form, banlist=None):
        """Initializes the form.

        :Parameters:
          - `form`: The form from an incoming request
          - `banlist` (optional): A list of strings to restrict, in addition to
            the default ones
        """
        super().__init__(form)
        if banlist:
            for r in banlist:
                LinkForm.rejected_regexes.append(re.compile(r))

    def validate_long_url(form, field):
        """Performs validation on the long_url field."""
        for regex in LinkForm.rejected_regexes:
            if regex.search(field.data):
                raise ValidationError("That URL is not allowed.")

    def validate_short_url(form, field):
        """Performs validation on the short_url field."""
        if not field.data.isalnum():
            raise ValidationError('Custom alias must be alphanumeric.')

    def to_json(self):
        """Exports the form"s fields into a JSON-compatible dictionary."""
        data = {
            "long_url": self.long_url.data,
            "title": self.title.data,
        }
        if self.short_url.data:
            data["short_url"] = self.short_url.data
        return data


class BlacklistUserForm(Form):
    """A WTForm for banning users.

    This form is accessible by administrators only.

    :Fields:
      - `netid`: Text field corresponding to the banned user's NetID
    """
    netid = TextField("NetID", validators=[validators.DataRequired()])

    def to_json(self):
        """Exports the form's fields into a JSON-compatible dictionary."""
        return {
            "netid": self.netid.data,
            "action": self.action.data
        }


class AddAdminForm(Form):
    """A WTForm for adding new administrators.
    
    This form is accessible by administrators only.

    :Fields:
      - `netid`: Text field corresponding to a NetID
    """
    netid = TextField("NetID", validators=[validators.DataRequired()])


class BlockLinksForm(Form):
    """A WTForm for blocking unwanted URLs.

    This form is accessible by administrators only.

    :Fields:
      - `link`: Text field corresponding to a long URL to block
    """
    link = TextField("Link", validators=[validators.DataRequired()])<commit_msg>refactor, force a banned url to be a url, and require a list of banned regexes<commit_after># shrunk - Rutgers University URL Shortener

"""Application forms for shrunk."""

import re

from wtforms import Form, TextField, RadioField, validators, ValidationError

import shrunk.filters

class LinkForm(Form):
    """A WTForm for creating and editing links.

    :Fields:
      - `long_url`: Text field for the original unshrunk URL
      - `title`: Text field for a descriptive link title
    """
    long_url = TextField("URL", validators=[
        validators.DataRequired("You need a link to shrink!"),
        validators.URL(require_tld=True, message="Please enter a valid URL.")
    ])
    title = TextField("Title", validators=[
        validators.DataRequired("Please enter a title.")
    ])
    short_url = TextField("Custom Alias", validators=[
        validators.Length(min=5, max=16, message="""Custom alias length must be
            between %(min)d and %(max)d characters."""),
        validators.Optional(strip_whitespace=False)
    ])

    rejected_regexes = []

    def __init__(self, form, banned_regexes):
        """Initializes the form.

        :Parameters:
          - `form`: The form from an incoming request
          - `banlist` (optional): A list of strings to restrict, in addition to
            the default ones
        """
        super().__init__(form)
        if banned_regexes:
            for regex in banned_regexes:
                LinkForm.rejected_regexes.append(re.compile(regex))

    def validate_long_url(form, field):
        """Performs validation on the long_url field."""
        for regex in LinkForm.rejected_regexes:
            if regex.search(field.data):
                raise ValidationError("That URL is not allowed.")

    def validate_short_url(form, field):
        """Performs validation on the short_url field."""
        if not field.data.isalnum():
            raise ValidationError('Custom alias must be alphanumeric.')

    def to_json(self):
        """Exports the form"s fields into a JSON-compatible dictionary."""
        data = {
            "long_url": self.long_url.data,
            "title": self.title.data,
        }
        if self.short_url.data:
            data["short_url"] = self.short_url.data
        return data


class BlacklistUserForm(Form):
    """A WTForm for banning users.

    This form is accessible by administrators only.

    :Fields:
      - `netid`: Text field corresponding to the banned user's NetID
    """
    netid = TextField("NetID", validators=[validators.DataRequired()])

    def to_json(self):
        """Exports the form's fields into a JSON-compatible dictionary."""
        return {
            "netid": self.netid.data,
            "action": self.action.data
        }


class AddAdminForm(Form):
    """A WTForm for adding new administrators.
    
    This form is accessible by administrators only.

    :Fields:
      - `netid`: Text field corresponding to a NetID
    """
    netid = TextField("NetID", validators=[validators.DataRequired()])


class BlockLinksForm(Form):
    """A WTForm for blocking unwanted URLs.

    This form is accessible by administrators only.

    :Fields:
      - `link`: Text field corresponding to a long URL to block
    """
    link = TextField("Link", validators=[
        validators.DataRequired(),
        validators.URL(require_tld=True, message="Please enter a valid URL.")
    ])
{'fraction_non_alphanumeric': 0.1061377245508982, 'fraction_numerical': 0.0008982035928143712, 'mean_word_length': 2.634929270946681, 'pattern_counts': {'":': 8, '<': 3, '<?xml version=': 0, '>': 3, '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': '4775156', 'n_tokens_mistral': 1894, 'n_tokens_neox': 1803, 'n_words': 585}