django-orchestra-test/orchestra/apps/mails/validators.py

59 lines
1.8 KiB
Python
Raw Normal View History

2014-08-22 15:31:44 +00:00
import hashlib
import os
import re
2014-10-09 17:04:12 +00:00
from django.core.management.base import CommandError
2014-08-22 15:31:44 +00:00
from django.core.validators import ValidationError, EmailValidator
from django.utils.translation import ugettext_lazy as _
from orchestra.utils import paths
from orchestra.utils.system import run
from . import settings
def validate_emailname(value):
msg = _("'%s' is not a correct email name" % value)
if '@' in value:
raise ValidationError(msg)
value += '@localhost'
try:
EmailValidator(value)
except ValidationError:
raise ValidationError(msg)
def validate_forward(value):
""" space separated mailboxes or emails """
2014-10-09 17:04:12 +00:00
from .models import Mailbox
2014-08-22 15:31:44 +00:00
for destination in value.split():
2014-10-09 17:04:12 +00:00
msg = _("'%s' is not an existent mailbox" % destination)
if '@' in destination:
if not destination[-1].isalpha():
raise ValidationError(msg)
EmailValidator(destination)
else:
if not Mailbox.objects.filter(user__username=destination).exists():
raise ValidationError(msg)
validate_emailname(destination)
2014-08-22 15:31:44 +00:00
def validate_sieve(value):
sieve_name = '%s.sieve' % hashlib.md5(value).hexdigest()
2014-10-09 17:04:12 +00:00
path = os.path.join(settings.MAILS_SIEVETEST_PATH, sieve_name)
2014-08-22 15:31:44 +00:00
with open(path, 'wb') as f:
f.write(value)
context = {
'orchestra_root': paths.get_orchestra_root()
}
2014-10-09 17:04:12 +00:00
sievetest = settings.MAILS_SIEVETEST_BIN_PATH % context
try:
test = run(' '.join([sievetest, path, '/dev/null']), display=False)
except CommandError:
2014-08-22 15:31:44 +00:00
errors = []
for line in test.stderr.splitlines():
error = re.match(r'^.*(line\s+[0-9]+:.*)', line)
if error:
errors += error.groups()
raise ValidationError(' '.join(errors))