Ejemplo n.º 1
0
    def normalize_phone(cls, phone_number, country=None):
        """Return the canonical phone number for a given phone number and country.

        Assumes a US phone number if no country is given.
        """
        errmsg = _('Does not seem to be a valid phone number')
        if len(phone_number) < 1:
            return ValueError(_("Phone number too short."))
        if not country and phone_number[0] != '+':
            # Assume US phone number
            country = 'US'

        try:
            pn = phonenumbers.parse(phone_number, country)
        except NumberParseException:
            pn = cls._try_plus_phonenumber(phone_number, errmsg)

        if not phonenumbers.is_valid_number(pn):
            # Sometimes a foreign number can look like a valid US number, but it's not
            # e.g. 48794987216 - Parses ok, but not is_valid_number. Adding + fixes.
            pn = cls._try_plus_phonenumber(phone_number, errmsg)

            if not phonenumbers.is_valid_number(pn):
                raise ValueError(errmsg)

        return phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.E164)
Ejemplo n.º 2
0
    def test_is_valid_number(self):
        p = phonenumbers.parse('+1123456789')
        self.assertFalse(phonenumbers.is_possible_number(p))
        self.assertFalse(phonenumbers.is_valid_number(p))

        p = phonenumbers.parse('+17184734811')
        self.assertTrue(phonenumbers.is_possible_number(p))
        self.assertTrue(phonenumbers.is_valid_number(p))
Ejemplo n.º 3
0
def phone_controll(phone):

    numero_tel = None

    #On controlle qu'il y a un plus au début, sinon il faut donner la localisation
    if phone[0] == "+":

        #Si jamais il y a un pb avec le parsage
        try:
            number = phonenumbers.parse(phone, None)


            #On vérifie que le nombre est valide
            if phonenumbers.is_valid_number(number):
                numero_tel = {}
                numero_tel["number"] = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
                numero_tel["country"] = phonenumbers.region_code_for_number(number)

                return numero_tel

            else:
                return numero_tel

        except phonenumbers.phonenumberutil.NumberParseException:
            return numero_tel




    #Sinon on doit donner une localisation
    else:
        try:

            number = phonenumbers.parse(phone, "FR")

            #On vérifie que le nombre est valide
            if phonenumbers.is_valid_number(number):
                numero_tel = {}
                numero_tel["number"] = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
                numero_tel["country"] = phonenumbers.region_code_for_number(number)

                return numero_tel

            elif phone.startswith("07"):
                numero_tel = {}
                numero_tel["number"] = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
                numero_tel["country"] = phonenumbers.region_code_for_number(number)
                return numero_tel

            else:
                return numero_tel


        except phonenumbers.phonenumberutil.NumberParseException:
            return numero_tel
Ejemplo n.º 4
0
    def clean(self):
        cleaned_data = super(UWSpotExtendedInfoForm, self).clean()
        # Have to check value here since we look at multiple items
        key = self.cleaned_data['key']
        value = self.cleaned_data['value']

        if key == 's_phone':
            p = re.compile('[A-Za-z]')
            if p.search(value):
                raise forms.ValidationError("Phone number cannot contain "
                                            "letters")

            try:
                number = phonenumbers.parse(value, "US")

                if (not phonenumbers.is_valid_number(number) or not
                        phonenumbers.is_possible_number(number)):
                    raise forms.ValidationError("")

                value = phonenumbers.format_number(number,
                                                   phonenumbers.
                                                   PhoneNumberFormat.E164)
                cleaned_data['value'] = value[2:]
            except Exception as ex:
                raise forms.ValidationError("s_phone must be a phone number")

        elif key in validated_ei:
            uw_validate(value, key, validated_ei[key])

        return cleaned_data
Ejemplo n.º 5
0
    def __init__(self,mobile):
        self.mobile = mobile
        self.access_token = getattr(settings, 'COGNALYS_ACCESS_TOKEN', '')
        self.app_id = getattr(settings, 'COGNALYS_APP_ID', '')
        self.api_version = getattr(settings, 'COGNALYS_API_VERSION', 'v1')


        p = self.mobile.replace("-", "").replace(" ", "")
        z = phonenumbers.parse(p, None)
        
        if not phonenumbers.is_valid_number(z):
            raise ValueError('Mobile Number is Not Valid')

        elif self.access_token == '':
            raise ValueError('Make sure COGNALYS_ACCESS_TOKEN is properly configured in settings.py')

        elif self.app_id == '':
            raise ValueError('Make sure COGNALYS_APP_ID is properly configured in settings.py')

        
        else:
            back = requests.get('https://www.cognalys.com/api/'+self.api_version+'/otp/?access_token='+self.access_token \
                                +'&app_id='+self.app_id+'&mobile='+p,verify=True)


            self.status =  back.json()['status']
            
            if back.json()['status'] == 'failed':
                self.error_messages = back.json()['errors'].values()
                self.error_codes = back.json()['errors'].keys()

            else:
                self.keymatch = back.json()['keymatch']
                self.mobile = back.json()['mobile']
                self.otp_start = back.json()['otp_start']
Ejemplo n.º 6
0
    def to_native(self, value, context=None):
        """ Schematics deserializer override

        We return a phoenumbers.PhoneNumber object so any kind
        of formatting can be trivially performed. Additionally,
        some convenient properties have been added:

            e164: string formatted '+11234567890'
            pretty: string formatted '(123) 456-7890'

        :return: phonenumbers.PhoneNumber
        """

        if isinstance(value, pn.phonenumber.PhoneNumber):
            return value

        try:
            phone = pn.parse(value, 'US')
            valid = pn.is_valid_number(phone)
        except (NumberParseException, TypeError):
            raise ConversionError(self.messages['convert'])

        if not valid and pn.is_possible_number(phone):
            raise ConversionError(self.messages['invalid'])
        elif not valid:
            raise ConversionError(self.messages['convert'])

        phone.e164 = pn.format_number(phone, pn.PhoneNumberFormat.E164)
        phone.pretty = pn.format_number(phone, pn.PhoneNumberFormat.NATIONAL)

        return phone
Ejemplo n.º 7
0
    def _validate_type_phonenumber(self, field, value):
        """ Validates a phone number is valid. Optionally formatting the number.

            :param field:  field name.
            :param value:  field value.
        """
        # get the region from schema for this field or use default
        self._set_region(self.schema[field].get('region'))
        try:
            phone_number = parse(value, self.region)

            # check that it's valid number
            if not is_valid_number(phone_number):
                self._error(field, 'Phone Number not valid: {}'.format(value))
            elif self.schema[field].get('formatPhoneNumber'):
                # if the schema's 'formatPhoneNumber' is set to True,
                # format the phone number using a formatter derived from
                # the schema's 'phoneNumberFormat' value, next checks the
                # environmen variable 'PHONE_NUMBER_FORMAT',
                # or defaults to 'NATIONAL'.
                formatter = self.schema[field].get('phoneNumberFormat')
                self._set_formatter(
                    formatter=formatter
                )
                self.document[field] = format_number(phone_number,
                                                     self.formatter)
        except NumberParseException:
            self._error(field, 'Phone Number not valid: {}'.format(value))
Ejemplo n.º 8
0
    def create(self, validated_data):
        caller = validated_data['caller']
        destination = validated_data['destination']

        if validated_data['direction'] == 'outbound':

            # Because of GRID-4965, the API returns the destination number in the same format user inserted it,
            # so if country code is missing let's patch it with the one from the caller number.
            if not destination['number'].startswith('+'):
                if caller['number'].startswith('+'):
                    try:
                        caller_number = phonenumbers.parse(caller['number'], None)
                        country_code = get_country_code_by_country(
                            geocoder.country_name_for_number(caller_number, 'en')
                        )
                        destination_number = phonenumbers.parse(destination['number'], country_code)

                        if phonenumbers.is_valid_number(destination_number):
                            destination['number'] = phonenumbers.format_number(
                                destination_number,
                                phonenumbers.PhoneNumberFormat.E164
                            )

                    except NumberParseException, e:
                        logger.error(traceback.format_exc(e))

            data = self.match_external_participant(destination)
            if not data['source']:
                # We don't save outbound calls where the destination isn't an account or a contact.
                # This is the only reliable way to filter out internal calls.
                return CallRecord()
Ejemplo n.º 9
0
 def handle(self, *args, **options):
     for pb in PublicBody.objects.filter(fax='').exclude(contact=''):
         match = FAX_RE.search(pb.contact)
         if match is None:
             continue
         # print(pb.id)
         if not match.group(1).strip():
             continue
         number = None
         while True:
             try:
                 number = phonenumbers.parse(match.group(1).strip(), 'DE')
                 break
             except phonenumbers.phonenumberutil.NumberParseException:
                 if match.group(1).startswith(')'):
                     match = POST_FAX_RE.search(pb.contact)
                 else:
                     print('Bad number:@%s@' % repr(match.group(1)), pb.contact)
                     break
         if number is None:
             continue
         if not phonenumbers.is_possible_number(number):
             print('impossible', match.group(1), '|', pb.contact, '|', pb.id)
             continue
         if not phonenumbers.is_valid_number(number):
             print('invalid', match.group(1), '|', pb.contact, '|', pb.id)
             continue
         fax_number = phonenumbers.format_number(number,
               phonenumbers.PhoneNumberFormat.E164)
         pb.fax = fax_number
         pb.save()
Ejemplo n.º 10
0
 def is_mobile_valid(mobile, mobile_code="+86"):
     
     m = mobile_code+mobile
     try:
         return phonenumbers.is_valid_number(phonenumbers.parse(m, None))
     except Exception as e:
         return False
Ejemplo n.º 11
0
def clean_phone(key, value, phone_types):
    #Athens phone numbers have a 3 digit area code(210) following for a 7 digit number
    #if only 7 digits are supplied, I assume it's missing the Athens area code
     
    list_of_phone_num = []
    phone_numbers = value.split(";")
    for number in phone_numbers:
            
        number = number.replace("+30","").lstrip().rstrip()   #strip out country code so that area code can be prefixed if required 
        m=re.match(r"[^0-9]",number)
        if m:
            phone_types[number].add(value)
        numbers_only = re.sub("[^0-9]", "", value)
        
        if len(numbers_only) == 7 :
           number = "210" +  number
        
        try:
           phone_num = pn.parse(value,"GR")
           if pn.is_valid_number(phone_num):
               cleaned = pn.format_number(phone_num,pn.PhoneNumberFormat.INTERNATIONAL)
               list_of_phone_num.append(cleaned)
           
        except:
            pass
    return list_of_phone_num
def validate_phone_number(value, validation_error_class):
    """
    :type value:fields.PhoneNumber
    :return:
    """
    assert type(value) is PhoneNumber, "%s instance was supplied instead of PhoneNumber " % (type(value),)
    try:
        value.region_code = phonenumbers.region_code_for_country_code(int(value.country_code))
        value.google_phone_number = phonenumbers.parse(value.phone_number, value.region_code)
        value.country_code = value.google_phone_number.country_code
        if not phonenumbers.is_valid_number(value.google_phone_number):
            fixed = phonenumbers.format_number(phonenumbers.example_number_for_type(
                value.region_code,
                PhoneNumberType.FIXED_LINE
            ), phonenumbers.PhoneNumberFormat.NATIONAL)
            mobile = phonenumbers.format_number(phonenumbers.example_number_for_type(
                value.region_code,
                PhoneNumberType.MOBILE
            ), phonenumbers.PhoneNumberFormat.NATIONAL)
            raise validation_error_class(
                'Invalid number. format example are: ' +
                'for fixed line  %(fixed_example)s, for mobile %(mobile_example)s',
                code='invalid',
                params={
                    'fixed_example': fixed if fixed else 'no example',
                    'mobile_example': mobile if mobile else 'no example'
                }
            )
    except NumberParseException as ex:
        raise validation_error_class(str(ex))
    except validation_error_class as ex:
        raise ex
    return value
Ejemplo n.º 13
0
def to_international_format(local_number):
    country_code = timezone_to_country_code(settings.TIME_ZONE)
    number = phonenumbers.parse(local_number, region=country_code)
    if not phonenumbers.is_valid_number(number):
        raise InvalidNumber(number)
    return phonenumbers.format_number(
        number, phonenumbers.PhoneNumberFormat.E164)
Ejemplo n.º 14
0
    def _format_phone_number_entry(self, entry):
        """
        Takes a phone number, and adds a default country prefix to it if
        missing. It is assumed that phone numbers lacking a prefix, is from
        the default region defined in the configuration.

        :param unicode : A phone number
        :return: A phone number with a country prefix, or None
        :rtype: unicode
        """
        def warn():
            self.logger.warning(
                "CIMDataSource: Invalid phone number for person_id:{}, "
                "account_name:{}: {} {!r}".format(
                    self.pe.entity_id,
                    self.ac.account_name,
                    str(self.co.ContactInfo(entry['contact_type'])),
                    phone_number))

        phone_number = entry['contact_value']
        try:
            parsed_nr = phonenumbers.parse(
                number=phone_number,
                region=self.config.phone_country_default)
            if phonenumbers.is_valid_number(parsed_nr):
                return phonenumbers.format_number(
                    numobj=parsed_nr,
                    num_format=phonenumbers.PhoneNumberFormat.E164)
            else:
                warn()
        except (phonenumbers.NumberParseException, UnicodeDecodeError):
            warn()
        return None
Ejemplo n.º 15
0
Archivo: api.py Proyecto: jart/sparkles
def verify_phone(phone, **kwargs):
    phone = phonenumbers.parse(phone, "US")
    if not phonenumbers.is_valid_number(phone):
        raise utils.APIException("Invalid phone number")
    if phone.country_code != 1:
        raise utils.APIException("We only support US/CA numbers now :(")
    phone = utils.e164(phone)
    ip = _try_to_get_ip(kwargs)
    yesterday = utils.now() - timedelta(days=1)
    five = utils.now() - timedelta(seconds=5)
    if db.PhoneVerify.objects.filter(phone=phone, created__gt=five).count():
        return []
    invalid = False
    invalid |= db.UserInfo.objects.filter(phone=phone).count() > 0
    invalid |= db.PhoneBlacklist.objects.filter(phone=phone).count() > 0
    invalid |= (
        db.PhoneVerify.objects.filter(phone=phone, created__gt=yesterday).count() > settings.SPARK_AUTH_MAX_PHONE_DAY
    )
    if ip:
        invalid |= (
            db.PhoneVerify.objects.filter(ip=ip, created__gt=yesterday).count() > settings.SPARK_AUTH_MAX_PHONE_DAY
        )
    if invalid:
        raise utils.APIException("invalid phone number")
    code = db.base36(4)
    db.PhoneVerify.objects.create(phone=phone, code=code, ip=ip)
    message.sms_send(phone, "sparkles phone auth code: " + code)
    return []
Ejemplo n.º 16
0
def pass_number(number, addons):
    """Check number validity"""
    passnum = True
    
    try:
        marchex = json.load(addons)
        if marchex['results']['marchex_cleancall']['result']['result']['recommendation'] == 'BLOCK':
            passnum = False
    except:
        pass
                            
    try:
        gp = phonenumbers.parse(number)
    except:
        passnum = False
    else:
        if phonenumbers.is_possible_number(gp) and phonenumbers.is_valid_number(gp):
            if gp.country_code == 1:
                gpi = int(str(gp.national_number)[phonenumbers.phonenumberutil.length_of_national_destination_code(gp):])
                if gpi >= 5550100 and gpi <= 5550199:
                    passnum = False
        else:
            passnum = False
            
    if number in BLOCKED_NUMBERS:
        passnum = False
        
    return passnum
def main(argv):
	#usage = 'usage: \n %prog [options] arg1 arg2 press -h for help.'
	parser = argparse.ArgumentParser(description='Phone number validator using Google phone')
	parser.add_argument("-f", "--file", dest="inputFile",help="file for phone numbers")
	parser.add_argument("-p", "--phone",dest="phone",help="Phone number to validate.")
	parser.add_argument("-c", "--country",dest = "country",help=" Country code to validate.")
	
	opts = parser.parse_args()
	country = None				#TO prevent reference errors.

	if opts.inputFile :
		inputFile = opts.inputFile
	elif opts.phone != None and opts.country != None :
		phone = opts.phone
		country = opts.country 
	else :
		country =  raw_input("Please enter country to validate against :")
		phone =  raw_input("Please enter the Phone number : ")
		
	try:
		x = phonenumbers.parse(phone,country)
		if country:
			if  phonenumbers.is_valid_number(x) :
				print "Valid combinition of number and country"
			else : 
				print "Invalid combinition"
		else :
			print x
	except Exception, e:
		print "Invalid phone number or country code Please use -h for usage"
Ejemplo n.º 18
0
def phonenumber(request, s):
    country = request.GET.get('country')
    p = phonenumbers.parse(s, country)
    possible = phonenumbers.is_possible_number(p)
    valid = phonenumbers.is_valid_number(p)
    resp = {
        'isPossible' : possible,
        'isValid' : valid,
    }
    remote = request.META.get('REMOTE_ADDR')
    user = request.META.get('HTTP_X_MASHAPE_USER')

    if possible and valid:
        resp_deets = {
            'countryCode' : p.country_code,
            'nationalNumber' : p.national_number,
            'e164' : phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.E164),
            'international' : phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.INTERNATIONAL),
            'national' : phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.NATIONAL),
            'rfc3966' : phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.RFC3966),
            'location' : geocoder.description_for_number(p, "en"),
            'country' : geocoder.country_name_for_number(p, 'en')
        }
        resp = dict(resp.items() + resp_deets.items())
    return resp
Ejemplo n.º 19
0
def format_phonenumber(number, international=True):
    # type: (Text, bool) -> Text
    """Format phone number for display.

    No formatting is applied if the number is not a valid phonenumber.

    :param number: the phone number to format.
    :param international: always use international format, unless number is in
    national format OR country is the same as app's default country.
    """
    country = default_country() or "FR"
    try:
        pn = phonenumbers.parse(number, country)
    except phonenumbers.NumberParseException:
        return number
    except BaseException:
        logger.exception(
            'error while applying jinja filter "phonenumber" ' "- filter ignored"
        )
        return number

    if not (phonenumbers.is_possible_number(pn) and phonenumbers.is_valid_number(pn)):
        return number

    fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL
    number_country = phonenumbers.region_code_for_country_code(pn.country_code)
    if not international and number_country == country:
        fmt = phonenumbers.PhoneNumberFormat.NATIONAL

    return phonenumbers.format_number(pn, fmt)
Ejemplo n.º 20
0
    def send_message(number=None, content=None):
        """ Send a message to the Twilio client for testing purposes.
        Uses twilio authentication and account information

        :param number: The 'from' phone number for this message
        :param content: The message content

        Returns a twilio message object.

        """
        from twilio.rest import TwilioRestClient
        import phonenumbers
        if number is None:
            assert 0, "Must provide number"
        z = phonenumbers.parse(number, None)
        if not phonenumbers.is_valid_number(z):
            assert 0, "Dodgy number."
        if content is None:
            assert 0, "Message content is empty"
        account = current_app.config['TWILIO_ACCOUNT_SID']
        token = current_app.config['TWILIO_AUTH_TOKEN']
        client = TwilioRestClient(account, token)
        message = client.messages.create(
            to=number,
            from_=current_app.config['TWILIO_NUMBER'],
            body=content)
        return message
Ejemplo n.º 21
0
def standardize_phone_number(number):
    try:
        p = parse(number, 'US')
        if is_valid_number(p):
            return "+%d%d" % (p.country_code, p.national_number)
    except:
        pass
Ejemplo n.º 22
0
def format_phone(num):
    try:
        num = phonenumbers.parse(num, "AU")
        if not phonenumbers.is_valid_number(num):
            return None
        return phonenumbers.format_number(num, phonenumbers.PhoneNumberFormat.NATIONAL)
    except:
        return None
Ejemplo n.º 23
0
    def phone_number_is_valid(self, phone_number):
        try:
            p = phonenumbers.parse(phone_number, None)
        except phonenumbers.phonenumberutil.NumberParseException:
            return False

        return phonenumbers.is_possible_number(p) and \
               phonenumbers.is_valid_number(p)
Ejemplo n.º 24
0
 def __call__(self, value):
     value = force_text(value)
     try:
         phonenumber = phonenumbers.parse(value, region="AU")
     except phonenumbers.NumberParseException:
         raise ValidationError(self.invalid_message)
     if not phonenumbers.is_valid_number(phonenumber):
         raise ValidationError(self.invalid_message)
Ejemplo n.º 25
0
def validate_number(phone_number, country):
  try:
    num = phonenumbers.parse(phone_number, country)
    if phonenumbers.is_valid_number(num):
      print "This phone number is valid."
    else:
      print "This phone number is invalid."
  except phonenumbers.phonenumberutil.NumberParseException:
    print "This phone number is invalid."
Ejemplo n.º 26
0
    def validate_number(self, number):
        if not phonenumbers.is_possible_number(number):
            return "This number is not possible: " \
                   "{0}".format(number)
        if not phonenumbers.is_valid_number(number):
            return "This number is not valid: " \
                   "{0}".format(number)

        return number
Ejemplo n.º 27
0
def valid_number(phone_number):
    """ validating phone numbers
    :param phone_number:
    """
    try:
        parsed_number = phonenumbers.parse(phone_number)
    except phonenumbers.phonenumberutil.NumberParseException:
        return False
    return phonenumbers.is_valid_number(parsed_number)
Ejemplo n.º 28
0
def validate_phone(value, country):
    """ local phone number or international """
    msg = _("Not a valid %s nor international phone number.") % country
    try:
        number = phonenumbers.parse(value, country)
    except phonenumbers.phonenumberutil.NumberParseException:
        raise ValidationError(msg)
    if not phonenumbers.is_valid_number(number):
        raise ValidationError(msg)
Ejemplo n.º 29
0
def validate_fax(fax):
    try:
        number = phonenumbers.parse(fax, settings.LANGUAGE_CODE.upper())
    except phonenumbers.phonenumberutil.NumberParseException:
        raise forms.ValidationError('Fax number cannot be parsed')
    if not phonenumbers.is_possible_number(number):
        raise forms.ValidationError('Impossible fax number')
    if not phonenumbers.is_valid_number(number):
        raise forms.ValidationError('Invalid fax number')
Ejemplo n.º 30
0
 def parse_phone_number(self, raw_string=None, country="US"):
     raw_string = raw_string or self.get_current_value()
     if raw_string:
         parsed_num = phonenumbers.parse(raw_string, country)
         if not phonenumbers.is_valid_number(parsed_num):
             raise exceptions.InvalidPhoneNumberException(
                 "'{}' is not a valid phone number".format(raw_string))
         return parsed_num
     return self.empty_value
Ejemplo n.º 31
0
def validate_phone(supposed_phone: str) -> bool:
    """
    Validate if the phone number given is valid
    or not.
    :param supposed_phone: Phone number
    :type supposed_phone: str
    :return: True if the phone number is valid
     and False if It is not.
    :rtype: bool
    """
    try:
        supposed_phone = phonenumbers.parse(supposed_phone)
        return phonenumbers.is_valid_number(supposed_phone)
    except phonenumbers.phonenumberutil.NumberParseException:
        return False
Ejemplo n.º 32
0
def phone_number_validator(value,
                           region=settings.KOMPASSI_PHONENUMBERS_DEFAULT_REGION
                           ):
    """
    Validate the phone number using Google's phonenumbers library.
    """
    exc = _('Invalid phone number.')

    try:
        phone_number = phonenumbers.parse(value, region)
    except phonenumbers.NumberParseException as e:
        raise ValidationError(exc)
    else:
        if not phonenumbers.is_valid_number(phone_number):
            raise ValidationError(exc)
Ejemplo n.º 33
0
def ValidPhone(Phone, country, url):
    if Phone != None:
        try:
            parsed_phone = phonenumbers.parse(Phone, country.upper(), True)
            valid_phone = phonenumbers.is_valid_number(parsed_phone)
            if valid_phone == False:
                Util.log.running_logger.warning(
                    '[Phone Invalid]: {0}: {1}'.format(url, Phone))
                return None
            return Phone
        except:
            Util.log.running_logger.error('[Phone Parse]: {0}: {1}'.format(
                url, Phone))
            return None
    return None
Ejemplo n.º 34
0
 def _sms_sanitization(self, partner, field_name):
     number = partner[field_name]
     if _sms_phonenumbers_lib_imported:
         country = self._phone_get_country(partner)
         country_code = country.code if country else None
         try:
             phone_nbr = phonenumbers.parse(number, region=country_code, keep_raw_input=True)
         except phonenumbers.phonenumberutil.NumberParseException:
             return number
         if not phonenumbers.is_possible_number(phone_nbr) or not phonenumbers.is_valid_number(phone_nbr):
             return number
         phone_fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL
         return phonenumbers.format_number(phone_nbr, phone_fmt).replace(' ', '')
     else:
         return number
Ejemplo n.º 35
0
def _validate_phone_number(value):
    value = str(value)
    phone_number = phonenumbers.parse(value, )
    if phonenumbers.is_valid_number(phone_number):
        if str(phone_number.country_code) in ALLOWED_COUNTRY_CODE.keys():
            return phonenumbers.format_number(
                phone_number,
                phonenumbers.PhoneNumberFormat.E164)
        else:
            msg = _("country code not supported yet and this shouldn't "
                    + "have happened anyways. It should have been checked "
                    + "while registering!")
    else:
        msg = _("phone number is not valid!!")
    raise ValueError(msg)
def set_field_new_building_in_floor(apps, schema_editor):
    Flats = apps.get_model('property', 'Flat')
    for flat in Flats.objects.all():
        owner_phone = flat.owners_phonenumber
        phone_number = phonenumbers.parse(owner_phone, "RU")
        if not phonenumbers.is_possible_number(phone_number):
            error_str = "Телефон {0} содержит неправильное колво цифр"
            print(error_str)
            continue
        if not phonenumbers.is_valid_number(phone_number):
            error_str = "Телефон {0} неправильный -не прошел валидациюр"
            print(error_str)
            continue
        flat.owner_pure_phone = phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.E164)
        flat.save()
Ejemplo n.º 37
0
def printable_phone_number(s):
    if not s:
        return ''

    # Note that we're assuming USA here, but this shouldn't matter, because
    # s should already be in E.164 format.
    no = phonenumbers.parse(s, 'US')
    if not phonenumbers.is_valid_number(no):
        return s

    # We're checking for +1 here, but this simply means that non-US numbers
    # will have the international prefix.
    fmt = (phonenumbers.PhoneNumberFormat.NATIONAL if no.country_code == 1 else
           phonenumbers.PhoneNumberFormat.INTERNATIONAL)
    return phonenumbers.format_number(no, fmt)
Ejemplo n.º 38
0
    def clean(self):
        data = self.cleaned_data
        if data['password'] != data['confirm_password']:
            self.add_error(
                'password',
                'Password and confirmation did not match'
            )

        phone_number = data['country_code'] + data['phone_number']
        try:
            phone_number = phonenumbers.parse(phone_number, None)
            if not phonenumbers.is_valid_number(phone_number):
                self.add_error('phone_number', 'Invalid phone number')
        except NumberParseException as e:
            self.add_error('phone_number', e)
Ejemplo n.º 39
0
def validating_phone_number(sender, instance, created, **kwargs):
    if created:
        phone = instance.number
        is_valid = False
        try:
            parsed = phonenumbers.parse(phone, str(instance.country).upper())
            is_valid = phonenumbers.is_valid_number(parsed)
            if is_valid:
                phone = "{}{}".format(parsed.country_code,
                                      parsed.national_number)
        except:
            pass
        instance.number = phone
        instance.is_phone_number = is_valid
        instance.save()
 def validatePhone__(self, phone):
     try:
         parsed_phone = phonenumbers.parse(phone,
                                           self._language.upper(),
                                           _check_region=True)
     except phonenumbers.phonenumberutil.NumberParseException as error:
         print str(phone) + ' can not parse'
         Util.log.running_logger.warning(str(phone) + ' : cannot parse')
         return None
     if not phonenumbers.is_valid_number(parsed_phone):
         print str(phone) + ': not number'
         Util.log.running_logger.warning(str(phone) + ' : not number')
         return None
     else:
         return phone
Ejemplo n.º 41
0
def _parse_phonenumber(val, country_code=None):
    try:
        phone_obj = phonenumbers.parse(val, country_code)
        if phonenumbers.is_valid_number(phone_obj):
            return {
                'e164': phonenumbers.format_number(
                    phone_obj, PhoneNumberFormat.E164),
                'international': phonenumbers.format_number(
                    phone_obj, PhoneNumberFormat.INTERNATIONAL),
                'national': phonenumbers.format_number(
                    phone_obj, PhoneNumberFormat.NATIONAL),
            }
        return None
    except phonenumberutil.NumberParseException:
        return None
Ejemplo n.º 42
0
def get_normalized_phone_number(raw_phone_number, check_validity=False):
    try:
        parsed_data = phonenumbers.parse(raw_phone_number, "HU")
    except phonenumbers.NumberParseException:
        raise InvalidPhoneNumber(
            _('Include "+" sign, country code and area code.'))

    if phonenumbers.is_valid_number(parsed_data):
        return phonenumbers.format_number(
            parsed_data, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

    if check_validity:
        raise InvalidPhoneNumber(
            _('Include "+" sign, country code and area code.'))
    return raw_phone_number
Ejemplo n.º 43
0
def addProductPost(number):
    text = number
    for match in phonenumbers.PhoneNumberMatcher(text, "US"):
        numberFormated = (phonenumbers.format_number(
            match.number, phonenumbers.PhoneNumberFormat.E164))
    z = phonenumbers.parse(numberFormated, None)
    validNumber = phonenumbers.is_valid_number(z)
    ch_number = phonenumbers.parse(numberFormated, "CH")
    geo = geocoder.description_for_number(ch_number, "es")
    #numbers, valid, location
    return jsonify({
        "number": numberFormated,
        "valid": validNumber,
        "location": geo
    })
Ejemplo n.º 44
0
    def validate_phone_number(form, field):  # pylint: disable=no-self-argument, no-self-use
        """
        Validates that the provided phone number is valid.

        Args:
            form: The EditResidentProfileForm that was submitted.
            field: The phone_number field.

        Raises:
            ValidationError: If phone_number is not a valid phone number.
        """
        if len(field.data) > 16:
            raise ValidationError('Invalid phone number.')
        try:
            input_number = phonenumbers.parse(field.data)
            if not phonenumbers.is_valid_number(input_number):
                raise ValidationError('Invalid phone number.')
        except NumberParseException:
            try:  # Try to add the US area code to it
                input_number = phonenumbers.parse("+1" + field.data)
                if not phonenumbers.is_valid_number(input_number):
                    raise ValidationError('Invalid phone number.')
            except NumberParseException:  # pylint: disable=bare-except
                raise ValidationError('Invalid phone number.')
Ejemplo n.º 45
0
def validate_number(raw_number):
    """
	tries to validate the incoming number. Returns the number formatted in a way Twilio likes if it works, or None if it doesn't.
	"""
    try:
        parsed_number = phonenumbers.parse(raw_number, "US")
        if phonenumbers.is_possible_number(
                parsed_number) and phonenumbers.is_valid_number(parsed_number):
            formatted_number = phonenumbers.format_number(
                parsed_number, phonenumbers.PhoneNumberFormat.E164)
            return formatted_number
        else:
            return None
    except:
        return None
Ejemplo n.º 46
0
def normalize_owners_phone_numbers(apps, schema_editor):
    Flat = apps.get_model('property', 'Flat')
    for flat in Flat.objects.all():
        try:
            parsed_phonenumber = phonenumbers.parse(flat.owners_phonenumber,
                                                    'RU')

            if not phonenumbers.is_valid_number(parsed_phonenumber):
                flat.owner_pure_phone = ""
            else:
                flat.owner_pure_phone = parsed_phonenumber

        except phonenumbers.phonenumberutil.NumberParseException:
            flat.owner_pure_phone = ""
        flat.save()
Ejemplo n.º 47
0
 def save(self, *args, **kwargs):
     string_value = self.cod_pais + self.cod_area + self.nro_tel
     try:
         value = phonenumbers.parse(string_value, 'AR')
     except NumberParseException:
         raise ValidationError(
             'Ingrese un numero de telefono con formato valido.')
     if phonenumbers.is_valid_number(
             value) and phonenumbers.is_possible_number(value):
         self.full_nro_tel = phonenumbers.format_number(
             value, phonenumbers.PhoneNumberFormat.E164)
     else:
         raise ValidationError(
             'Ingrese un numero de telefono con formato valido.')
     super(PerTel, self).save(*args, **kwargs)
def fill_owners_phone_pure_field(apps, schema_editor):
    Flat = apps.get_model('property', 'Flat')

    all_flats = Flat.objects.all()

    for flat in all_flats:
        phone_number_object = phonenumbers.parse(flat.owners_phonenumber, 'RU')

        if phonenumbers.is_valid_number(phone_number_object):
            flat.owners_phone_pure = phonenumbers.format_number(
                numobj=phone_number_object,
                num_format=phonenumbers.PhoneNumberFormat.E164,
            )

    Flat.objects.bulk_update(all_flats, ['owners_phone_pure'])
Ejemplo n.º 49
0
def create_route():
    # Fetch clients from DB
    refresh_clients()
    # Validate request
    if not validate_recaptcha(request.values.get("recaptcha_token")):
        return "Invalid request", 401

    # Validate phone number
    phone_number = request.values.get("phone")
    phone_number_obj = phonenumbers.parse(phone_number, None)

    if phonenumbers.is_valid_number(phone_number_obj):
        return begin_onboard(phone_number)
    else:
        return "Invalid Number", 400
Ejemplo n.º 50
0
    def _force_validation(self, phonenumber, fieldname):
        """Force the validation using phonenumbers of a given number

        :param phonenumber: string
        :param str fieldname: name of the field the number is related to.
        :raise ValidationError: if the given number is not validated.
        """
        number = phonenumbers.parse(phonenumber, self.country_id.code)
        if not phonenumbers.is_valid_number(number):
            error_msg = '\n'.join([
                'The number ({}) "{}" seems not valid for {}.'.format(
                    fieldname, phonenumber, self.country_id.name),
                'Please double check it.'
            ])
            raise ValidationError(error_msg)
Ejemplo n.º 51
0
def validate_order(phoneNumber, diningDate, diningTime, cuisine):
    cuisine_list = ['chinese', 'japanese', 'american', 'mexican', 'italian']
    if cuisine is not None:
        if cuisine.lower() not in cuisine_list:
            return build_validation_result(
                False, 'cuisine',
                'We only have Chinese, Japanese, American, Mexican,'
                'Italian. Sorry for the inconvenience caused.')
    if phoneNumber is not None:
        try:
            if not phonenumbers.is_valid_number(
                    phonenumbers.parse(phoneNumber, "US")):
                return build_validation_result(
                    False, 'phoneNumber',
                    'Please provide a valid phone number.')
        except:
            return build_validation_result(
                False, 'phoneNumber', 'Please provide a valid phone number.')

    if diningDate is not None:
        if not isvalid_date(diningDate):
            return build_validation_result(
                False, 'diningDate', 'I did not understand that, '
                'what date would you like to go to the restaurant?')
        elif datetime.datetime.strptime(
                diningDate, '%Y-%m-%d').date() < datetime.date.today():
            return build_validation_result(
                False, 'diningDate',
                'You can go to the restaurant from today onwards.  '
                'What day would you like to go?')

    if diningTime is not None:
        if len(diningTime) != 5:
            # Not a valid time; use a prompt defined on the build-time model.
            return build_validation_result(False, 'diningTime', None)

        hour, minute = diningTime.split(':')
        hour = parse_int(hour)
        minute = parse_int(minute)
        if math.isnan(hour) or math.isnan(minute):
            # Not a valid time; use a prompt defined on the build-time model.
            return build_validation_result(False, 'diningTime', None)

        # if hour < 10 or hour > 16:
        #     # Outside of business hours
        #     return build_validation_result(False, 'PickupTime', 'Our business hours are from ten a m. to five p m. Can you specify a time during this range?')

    return build_validation_result(True, None, None)
Ejemplo n.º 52
0
    def getCoordFromPhoneAndPublish(self, phoneNumber, categ):
        try:
            rep = phonenumbers.parse(phoneNumber, None)
            if not (phonenumbers.is_valid_number(rep)
                    or phonenumbers.is_possible_number(rep)):
                self.logger.warning("Phone number not valid")
                return
            country_name = geocoder.country_name_for_number(rep, "en")
            country_code = self.country_to_iso[country_name]
            if country_code is None:
                self.logger.warning("Non matching ISO_CODE")
                return
            coord = self.country_code_to_coord[
                country_code.lower()]  # countrycode is in upper case
            coord_dic = {'lat': coord['lat'], 'lon': coord['long']}

            ordDic = OrderedDict()  #keep fields with the same layout in redis
            ordDic['lat'] = coord_dic['lat']
            ordDic['lon'] = coord_dic['lon']
            coord_list = [coord['lat'], coord['long']]
            if not self.coordinate_list_valid(coord_list):
                raise InvalidCoordinate(
                    "Coordinate do not match EPSG:900913 / EPSG:3785 / OSGEO:41001"
                )
            self.push_to_redis_zset(self.keyCategCoord, json.dumps(ordDic))
            self.push_to_redis_zset(self.keyCategCountry, country_code)
            ordDic = OrderedDict()  #keep fields with the same layout in redis
            ordDic['categ'] = categ
            ordDic['value'] = phoneNumber
            self.push_to_redis_geo(self.keyCategRad, coord['long'],
                                   coord['lat'], json.dumps(ordDic))
            to_send = {
                "coord": coord_dic,
                "categ": categ,
                "value": phoneNumber,
                "country": country_name,
                "specifName": "",
                "cityName": "",
                "regionCode": country_code,
            }
            j_to_send = json.dumps(to_send)
            self.serv_coord.publish(self.CHANNELDISP, j_to_send)
            self.live_helper.add_to_stream_log_cache('Map', j_to_send)
            self.logger.info('Published: {}'.format(json.dumps(to_send)))
        except phonenumbers.NumberParseException:
            self.logger.warning("Can't resolve phone number country")
        except InvalidCoordinate:
            self.logger.warning("Coordinate do not follow redis specification")
Ejemplo n.º 53
0
    def _run_validation_for_non_option_type(self, data: Any,
                                            question: Question) -> None:
        """
        This validates multiple requirements for an answer that has a
        corresponding question that of a non-option type:
        - The `answer_options` field must be null
        - The 'answer` field must have at least one character if the
          corresponding question has `required` set to True
        - The `answer` field is in the correct format, depending on the
          type of question the answer corresponds to
        """
        # Check that `answer` field is filled if the question says its required
        # and also check that the `answer_options` field is null
        if data.get("answer_options") is not None:
            self.fail_for_field("only_answer_field")
        if question.required and (data.get("answer") is None
                                  or data.get("answer").strip() == ""):
            self.fail_for_field("answer_is_required")

        # Validate if the `answer` field is in the correct format
        if question.type == Question.QuestionType.PHONE:
            try:
                pn = phonenumbers.parse(data.get("answer"))
                if not phonenumbers.is_valid_number(pn):
                    self.fail_for_field("invalid_phone_number")
            except phonenumbers.NumberParseException:
                self.fail_for_field("invalid_phone_number")
        elif question.type == Question.QuestionType.EMAIL:
            try:
                validate_email(data.get("answer"))
            except DjangoValidationError:
                self.fail_for_field("invalid_email")
        elif question.type == Question.QuestionType.HTTP_URL:
            try:
                validate_url = URLValidator(schemes=["http", "https"])
                validate_url(data.get("answer"))
            except DjangoValidationError:
                self.fail_for_field("invalid_http_url")
        elif question.type in [
                Question.QuestionType.PDF_FILE,
                Question.QuestionType.IMAGE_FILE,
        ]:
            try:
                af = AnswerFile.objects.get(id=data.get("answer"))
                if af.question.id != question.id:
                    self.fail_for_field("invalid_file")
            except AnswerFile.DoesNotExist:
                self.fail_for_field("invalid_file")
def do(x):
    phonenumber = phonenumbers.parse(x, 'NZ')
    print "Raw: %s" % x
    print "PhoneNumber: %s" % phonenumber
    print "National: %s" % phonenumbers.format_number(
        phonenumber, phonenumbers.PhoneNumberFormat.NATIONAL)
    print "International: %s" % phonenumbers.format_number(
        phonenumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
    print "E164: %s" % phonenumbers.format_number(
        phonenumber, phonenumbers.PhoneNumberFormat.E164)
    print "Possible Number: %s" % phonenumbers.is_valid_number(phonenumber)
    print "Valid Number: %s" % phonenumbers.is_possible_number(phonenumber)
    print "Type: %s" % phonenumbers.number_type(phonenumber)

    print "*********************"
    print '\n'
Ejemplo n.º 55
0
    def get_canonical_form(self, input_data):
        """ Validate and return a canonical form to be stored in DB
        and compared against.
        Returns ``None`` if input isn't a valid phone number.
        """
        import phonenumbers

        try:
            z = phonenumbers.parse(input_data,
                                   region=config_value("PHONE_REGION_DEFAULT"))
            if phonenumbers.is_valid_number(z):
                return phonenumbers.format_number(
                    z, phonenumbers.PhoneNumberFormat.E164)
            return None
        except phonenumbers.phonenumberutil.NumberParseException:
            return None
Ejemplo n.º 56
0
	def phone_check(self,phone):
		#Try parse phone number with E164 format
		try:
			p = phonenumbers.parse(phone, None)
		except:
			try:
				#if not in E164 format, parse with US phone number format by default
				p = phonenumbers.parse(phone,'US')
			except:
				return False
		#Use successful parsing phone number to validate
		m = phonenumbers.is_valid_number(p)
		if m is None:
			return False
		else:
			return True
Ejemplo n.º 57
0
    def validate_phone(self, phone):
        try:
            p = phonenumbers.parse(phone.data)
            if not phonenumbers.is_valid_number(p):
                raise ValueError()

        except (phonenumbers.phonenumberutil.NumberParseException, ValueError):
            raise ValidationError('Invalid phone number')
        try:
            user = User.query.filter_by(phone=phone.data).first()
            if user:
                raise ValidationError

        except (phonenumbers.phonenumberutil.NumberParseException, ValueError):
            raise ValidationError(
                'This number is already registered, try another one.')
Ejemplo n.º 58
0
 def validate_mobileNumber(self, mobileNumber):
     numberExist = User.query.filter_by(
         phonenumber=mobileNumber.data).first()
     if numberExist is not None:
         raise ValidationError(f'{mobileNumber.data} is already taken')
     if phone.match(mobileNumber.data):
         mobile = phonenumbers.parse(mobileNumber.data, "IN")
         checkNumber = phonenumbers.is_valid_number(mobile)
         if checkNumber:
             pass  #valid mobile Number
         else:
             raise ValidationError("Enter a valid phone Number")
     else:
         raise ValidationError(
             "Phone Numbers must start 0, +91 or the 10 digit number itself"
         )
Ejemplo n.º 59
0
def register(user_manager):
    """Create user."""
    request_data = request.get_json()
    if ("username" not in request_data or "password" not in request_data
            or "phone" not in request_data):
        raise InvalidRequestException
    if not phonenumbers.is_valid_number(
            phonenumbers.parse(request_data["phone"], None)):
        raise InvalidRequestException
    hashed_password = generate_password_hash(request_data["password"])
    user_manager.create(
        request_data["username"],
        hashed_password,
        request_data["phone"],
    )
    return jsonify({"message": "Successfully registered."})
Ejemplo n.º 60
0
def format_mobile(mobile):
    if mobile and mobile != '000':
        m = None
        try:
            m = phonenumbers.parse(mobile, 'CN')
        except:
            pass

        if m and phonenumbers.is_valid_number(m):
            if m.country_code == 86:
                return unicode(m.national_number)
            else:
                return phonenumbers.format_number(
                    m, phonenumbers.PhoneNumberFormat.E164)

    return mobile