2020-07-18 13:10:03 +00:00
|
|
|
from flask_wtf import FlaskForm
|
2020-07-18 16:40:51 +00:00
|
|
|
from wtforms import StringField, SubmitField, ValidationError
|
|
|
|
|
from wtforms.validators import DataRequired, Length
|
2020-07-20 16:53:18 +00:00
|
|
|
from tiny0.config import WEBSITE_DOMAIN
|
2020-07-18 13:10:03 +00:00
|
|
|
|
2020-07-18 16:40:51 +00:00
|
|
|
# Validates a URL
|
|
|
|
|
def validate_URL(form, field):
|
|
|
|
|
# Make sure the url is not too short or long
|
|
|
|
|
if len(field.data) < 4 or len(field.data) > 2000:
|
2020-07-19 22:14:49 +00:00
|
|
|
return
|
2020-07-18 13:10:03 +00:00
|
|
|
|
2020-07-18 16:40:51 +00:00
|
|
|
# If the url contains spaces or does not have any dots
|
2020-07-23 17:07:21 +00:00
|
|
|
if (" " in field.data) or not("." in field.data):
|
2020-07-18 16:40:51 +00:00
|
|
|
# Raise a ValidationError
|
2020-07-19 20:01:03 +00:00
|
|
|
raise ValidationError("Invalid URL")
|
2020-07-18 13:10:03 +00:00
|
|
|
|
2020-07-18 21:50:47 +00:00
|
|
|
# If the url starts with a dot after http:// or after https:// or just starts with a dot
|
|
|
|
|
if field.data.startswith("http://.") or field.data.startswith("https://.") or field.data.startswith("."):
|
|
|
|
|
# Raise a ValidationError
|
2020-07-19 20:01:03 +00:00
|
|
|
raise ValidationError("Invalid URL")
|
2020-07-18 21:50:47 +00:00
|
|
|
|
2020-07-23 16:57:16 +00:00
|
|
|
# If the url starts with a slash after http:// or after https:// or just starts with a slash
|
|
|
|
|
if field.data.startswith("http:///") or field.data.startswith("https:///") or field.data.startswith("/"):
|
|
|
|
|
# Raise a ValidationError
|
|
|
|
|
raise ValidationError("Invalid URL")
|
|
|
|
|
|
2020-07-18 21:50:47 +00:00
|
|
|
# If the url ends with a dot and it is the only dot
|
|
|
|
|
if field.data.endswith(".") and field.data.count(".") == 1:
|
|
|
|
|
# Raise a ValidationError
|
2020-07-19 20:01:03 +00:00
|
|
|
raise ValidationError("Invalid URL")
|
2020-07-18 21:50:47 +00:00
|
|
|
|
2020-07-20 16:53:18 +00:00
|
|
|
# If the url contains the websites domain
|
|
|
|
|
if WEBSITE_DOMAIN in field.data:
|
|
|
|
|
# Raise a ValidationError
|
|
|
|
|
raise ValidationError("Invalid URL")
|
|
|
|
|
|
2020-07-18 16:40:51 +00:00
|
|
|
# If the URL does not start with http:// and https://
|
|
|
|
|
if not(field.data.startswith("http://")) and not(field.data.startswith("https://")):
|
2020-07-20 18:55:07 +00:00
|
|
|
# Add http:// to the beginning of the URL
|
|
|
|
|
field.data = "http://" + field.data
|
2020-07-18 16:40:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class URLForm(FlaskForm):
|
2020-07-19 20:01:03 +00:00
|
|
|
url = StringField(validators=[DataRequired(),
|
2020-07-19 22:14:49 +00:00
|
|
|
Length(min=4, max=2000, message="Invalid URL Length"),
|
2020-07-19 20:01:03 +00:00
|
|
|
validate_URL])
|
2020-07-18 16:40:51 +00:00
|
|
|
|
2020-07-18 23:39:18 +00:00
|
|
|
submit = SubmitField("Shorten")
|