+++ /dev/null
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
-@author: Frank Brehm
-@contact: frank.brehm@pixelpark.com
-@copyright: © 2021 by Frank Brehm, Publicis Pixelpark GmbH, Berlin
-@summary: The module for the MailAddress object.
-"""
-from __future__ import absolute_import
-
-# Standard modules
-import logging
-import re
-
-# Own modules
-from fb_tools.errors import InvalidMailAddressError
-
-from fb_tools.common import to_str
-
-from fb_tools.obj import FbGenericBaseObject
-
-from .xlate import XLATOR
-
-__version__ = '0.5.1'
-log = logging.getLogger(__name__)
-
-_ = XLATOR.gettext
-
-
-# =============================================================================
-class MailAddress(FbGenericBaseObject):
- """
- Class for encapsulating a mail simple address.
- """
-
- pattern_valid_domain = r'@((?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?\.)+[a-z][a-z]+)$'
-
- pattern_valid_user = r'^([a-z0-9][a-z0-9_\-\.\+\&@]*[a-z0-9]'
- pattern_valid_user += r'(?:\+[a-z0-9][a-z0-9_\-\.]*[a-z0-9])*)'
-
- pattern_valid_address = pattern_valid_user + pattern_valid_domain
-
- re_valid_user = re.compile(pattern_valid_user + r'$', re.IGNORECASE)
- re_valid_domain = re.compile(r'^' + pattern_valid_domain, re.IGNORECASE)
- re_valid_address = re.compile(pattern_valid_address, re.IGNORECASE)
-
- verbose = 0
-
- # -------------------------------------------------------------------------
- @classmethod
- def valid_address(cls, address, raise_on_failure=False):
-
- if not address:
- e = InvalidMailAddressError(address, _("Empty address."))
- if raise_on_failure:
- raise e
- elif cls.verbose > 2:
- log.debug(str(e))
- return False
-
- addr = to_str(address)
- if not isinstance(addr, str):
- e = InvalidMailAddressError(address, _("Wrong type."))
- if raise_on_failure:
- raise e
- elif cls.verbose > 2:
- log.debug(str(e))
- return False
-
- if cls.re_valid_address.search(addr):
- return True
-
- e = InvalidMailAddressError(address, _("Invalid address."))
- if raise_on_failure:
- raise e
- elif cls.verbose > 2:
- log.debug(str(e))
- return False
-
- # -------------------------------------------------------------------------
- def __init__(self, user=None, domain=None):
-
- self._user = ''
- self._domain = ''
-
- if not domain:
- if user:
- addr = to_str(user)
- if self.valid_address(addr):
- match = self.re_valid_address.search(addr)
- self._user = match.group(1)
- self._domain = match.group(2)
- return
- match = self.re_valid_domain.search(addr)
- if match:
- self._domain = match.group(1)
- return
- self._user = addr
- return
-
- self._user = to_str(user)
- self._domain = to_str(domain)
-
- # -----------------------------------------------------------
- @property
- def user(self):
- """The user part of the address."""
- if self._user is None:
- return ''
- return self._user
-
- # -----------------------------------------------------------
- @property
- def domain(self):
- """The domain part of the address."""
- if self._domain is None:
- return ''
- return self._domain
-
- # -------------------------------------------------------------------------
- def __str__(self):
-
- if not self.user and not self.domain:
- return ''
-
- if not self.domain:
- return self.user
-
- if not self.user:
- return '@' + self.domain
-
- return self.user + '@' + self.domain
-
- # -------------------------------------------------------------------------
- def str_for_access(self):
-
- if not self.user and not self.domain:
- return None
-
- if not self.domain:
- return self.user + '@'
-
- if not self.user:
- return self.domain
-
- return self.user + '@' + self.domain
-
- # -------------------------------------------------------------------------
- def __repr__(self):
- """Typecasting into a string for reproduction."""
-
- out = "<%s(" % (self.__class__.__name__)
-
- fields = []
- fields.append("user={!r}".format(self.user))
- fields.append("domain={!r}".format(self.domain))
-
- out += ", ".join(fields) + ")>"
- return out
-
- # -------------------------------------------------------------------------
- def __hash__(self):
- return hash(str(self).lower())
-
- # -------------------------------------------------------------------------
- def __eq__(self, other):
-
- if not isinstance(other, MailAddress):
- if other is None:
- return False
- return str(self).lower() == str(other).lower()
-
- if not self.user:
- if other.user:
- return False
- if not self.domain:
- if other.domain:
- return False
- return True
- if not other.domain:
- return False
- if self.domain.lower() == other.domain.lower():
- return True
- return False
-
- if not self.domain:
- if other.domain:
- return False
- if not other.user:
- return False
- if self.user.lower() == other.user.lower():
- return True
- return False
-
- if not other.user:
- return False
- if not other.domain:
- return False
- if self.domain.lower() != other.domain.lower():
- return False
- if self.user.lower() != other.user.lower():
- return False
-
- return True
-
- # -------------------------------------------------------------------------
- def __ne__(self, other):
-
- if self == other:
- return False
- return True
-
- # -------------------------------------------------------------------------
- def __lt__(self, other):
-
- if not isinstance(other, MailAddress):
- if other is None:
- return False
- return str(self).lower() < str(other).lower()
-
- if not self.user:
- if not self.domain:
- if other.domain:
- return False
- return True
- if not other.domain:
- return False
- if self.domain.lower() != other.domain.lower():
- return self.domain.lower() < other.domain.lower()
- if other.user:
- return False
- return True
-
- if not self.domain:
- if other.domain:
- return True
- if not other.user:
- return False
- if self.user.lower() != other.user.lower():
- return self.user.lower() < other.user.lower()
- return False
-
- if not other.domain:
- return False
- if not other.user:
- return False
-
- if self.domain.lower() != other.domain.lower():
- return self.domain.lower() < other.domain.lower()
- if self.user.lower() != other.user.lower():
- return self.user.lower() < other.user.lower()
-
- return False
-
- # -------------------------------------------------------------------------
- def __gt__(self, other):
-
- if not isinstance(other, MailAddress):
- return NotImplemented
-
- if self < other:
- return False
- return True
-
- # -------------------------------------------------------------------------
- def __copy__(self):
- "Implementing a wrapper for copy.copy()."
-
- addr = MailAddress()
- addr._user = self.user
- addr._domain = self.domain
- return addr
-
-
-# =============================================================================
-
-if __name__ == "__main__":
-
- pass
-
-# =============================================================================
-
-# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 list
+++ /dev/null
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-'''
-@author: Frank Brehm
-@contact: frank.brehm@pixelpark.com
-@copyright: © 2021 Frank Brehm, Digitas Pixelpark GmbH Berlin
-@license: LGPL3
-@summary: test script (and module) for unit tests on mailaddress class and objects
-'''
-
-import os
-import sys
-import logging
-
-try:
- import unittest2 as unittest
-except ImportError:
- import unittest
-
-libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'lib'))
-sys.path.insert(0, libdir)
-
-from general import PpAdminToolsTestcase, get_arg_verbose, init_root_logger
-
-LOG = logging.getLogger('test_mailaddress')
-
-
-# =============================================================================
-class TestMailaddress(PpAdminToolsTestcase):
-
- # -------------------------------------------------------------------------
- def setUp(self):
- pass
-
- # -------------------------------------------------------------------------
- def test_import(self):
-
- LOG.info("Testing import of pp_admintools.mailaddress ...")
- import pp_admintools.mailaddress
- LOG.debug("Version of pp_admintools.mailaddress: {!r}".format(
- pp_admintools.mailaddress.__version__))
-
- # -------------------------------------------------------------------------
- def test_object(self):
-
- LOG.info("Testing init of a simple mailaddress object.")
-
- from pp_admintools.mailaddress import MailAddress
-
- obj = MailAddress('frank.brehm@pixelpark.com')
- LOG.debug("MailAddress %%r: %r", obj)
- LOG.debug("MailAddress %%s: %s", str(obj))
-
-
-# =============================================================================
-if __name__ == '__main__':
-
- verbose = get_arg_verbose()
- if verbose is None:
- verbose = 0
- init_root_logger(verbose)
-
- LOG.info("Starting tests ...")
-
- suite = unittest.TestSuite()
-
- suite.addTest(TestMailaddress('test_import', verbose))
- suite.addTest(TestMailaddress('test_object', verbose))
-
- runner = unittest.TextTestRunner(verbosity=verbose)
-
- result = runner.run(suite)
-
-
-# =============================================================================
-
-# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4